{"version":3,"sources":["../src/auth/timing-safe.ts","../src/brand.ts","../src/error.ts","../src/adapters/shared/optional-peer.ts","../src/logger.ts","../src/deferral/runtime-key.ts","../src/deferral/tokens.ts","../src/deferral/exchange-state.ts","../src/exchange.ts","../src/capabilities.ts","../src/adapters/direct/shared.ts","../src/adapters/mail/strict-verify.ts","../src/auth/jwt.ts","../src/auth/jwt-utils.ts","../src/auth/jwks.ts","../src/auth/authorize.ts","../src/auth/authentic.ts","../src/auth/expiry.ts","../src/auth/restored.ts","../src/auth/delegate.ts","../src/auth/authenticate.ts","../src/shared/runtime-env.ts","../src/auth/error-classification.ts","../src/index.ts","../src/shared/duration.ts","../src/shared/stale-options.ts","../src/enablement.ts","../src/context.ts","../src/route.ts","../src/adapters/shared/factory-tag.ts","../src/adapters/shared/role-facade.ts","../src/testing-hooks.ts","../src/queue.ts","../src/pipeline/synthetic-steps.ts","../src/adapters/shared/parse.ts","../src/operations/throttle-wrapper.ts","../src/types.ts","../src/operations/wrapper.ts","../src/dsl-symbol.ts","../src/deferral/sites.ts","../src/operations/event-scope.ts","../src/operations/cancellable-sleep.ts","../src/operations/max-keys.ts","../src/operations/route-scoped-controller.ts","../src/pipeline/validation.ts","../src/shared/thenable.ts","../src/shared/abort.ts","../src/pipeline/executor.ts","../src/recovery.ts","../src/deferral/defer.ts","../src/shared/standard-schema.ts","../src/deferral/hash.ts","../src/deferral/serialize.ts","../src/deferral/deferred.ts","../src/operations/split.ts","../src/pipeline/chain-policy.ts","../src/operations/timeout-wrapper.ts","../src/operations/retry-wrapper.ts","../src/operations/circuit-breaker-wrapper.ts","../src/operations/concurrency-wrapper.ts","../src/operations/semaphore.ts","../src/config-applier.ts","../src/event-bus.ts","../src/define-config.ts","../src/project-discoverer.ts","../src/plugins/server/plugin.ts","../src/plugins/http/server/index.ts","../src/plugins/http/server/node.ts","../src/plugins/server/request-validation.ts","../src/plugins/server/registry.ts","../src/plugins/http/auth.ts","../src/plugins/server/protected-resource.ts","../src/plugins/server/config.ts","../src/plugins/http/plugin.ts","../src/plugins/http/openapi.ts","../src/plugins/http/response.ts","../src/plugins/http/builtins.ts","../src/pipeline/caller-refusal.ts","../src/plugins/http/caller-refusal.ts","../src/plugins/http/dispatcher.ts","../src/plugins/http/body-parser.ts","../src/plugins/http/max-body-size.ts","../src/plugins/http/webhook-signature.ts","../src/shared/iterable.ts","../src/plugins/http/sse.ts","../src/plugins/http/registry.ts","../src/plugins/http/package-info.ts","../src/plugins/server/mount-path.ts","../src/plugins/http/path-matcher.ts","../src/plugins/http/config.ts","../src/plugins/ops/plugin.ts","../src/plugins/ops/indicator.ts","../src/client.ts","../src/plugins/ops/management.ts","../src/plugins/remotes/channel.ts","../src/shared/runtime-version.ts","../src/plugins/ops/client.ts","../src/plugins/ops/pagination.ts","../src/shared/compare.ts","../src/shared/safe-json.ts","../src/plugins/ops/store.ts","../src/plugins/remotes/store.ts","../src/plugins/ops/mount.ts","../src/plugins/ops/tier.ts","../src/plugins/ops/report.ts","../src/plugins/ops/state.ts","../src/plugins/ops/config.ts","../src/plugins/remotes/plugin.ts","../src/plugins/remotes/schema.ts","../src/plugins/remotes/config.ts","../src/adapters/cron/types.ts","../src/adapters/cron/source.ts","../src/adapters/cron/config.ts","../src/adapters/direct/config.ts","../src/adapters/mail/client-manager.ts","../src/adapters/mail/shared.ts","../src/adapters/mail/analysis.ts","../src/adapters/mail/config.ts","../src/adapters/carddav/client-manager.ts","../src/adapters/carddav/shared.ts","../src/adapters/carddav/config.ts","../src/shared/sqlite/driver.ts","../src/shared/sqlite/database.ts","../src/telemetry/schema.ts","../src/telemetry/sqlite-connection.ts","../src/telemetry/sqlite-processor.ts","../src/telemetry/sqlite-event-writer.ts","../package.json","../src/telemetry/plugin.ts","../src/telemetry/config.ts","../src/deferral/config.ts","../src/deferral/ops-resource.ts","../src/deferral/types.ts","../src/deferral/memory-store.ts","../src/deferral/sqlite-store.ts","../src/shared/sqlite/claims.ts","../src/deferral/revive.ts","../src/deferral/authorize.ts","../src/deferral/sweeper.ts","../src/plugins/server/cors.ts","../src/plugins/ops/types.ts","../src/operations/from.ts","../src/operations/process.ts","../src/operations/to.ts","../src/operations/adapter-roles.ts","../src/engine-headers.ts","../src/deferral/signal.ts","../src/operations/aggregate.ts","../src/operations/transform.ts","../src/operations/field-paths.ts","../src/operations/mask.ts","../src/operations/keep.ts","../src/operations/validate.ts","../src/operations/filter.ts","../src/operations/sample.ts","../src/operations/dedupe.ts","../src/operations/hash-body.ts","../src/operations/principal-identity.ts","../src/operations/debounce.ts","../src/operations/choice.ts","../src/step-builder-base.ts","../src/operations/enrich.ts","../src/operations/error-wrapper.ts","../src/operations/cache-wrapper.ts","../src/operations/cache-provider.ts","../src/operations/delay-wrapper.ts","../src/operations/tap.ts","../src/operations/authenticate.ts","../src/operations/delegate.ts","../src/operations/header.ts","../src/operations/multicast.ts","../src/operations/dispatch.ts","../src/operations/defer.ts","../src/operations/resume.ts","../src/deferral/principal-ref.ts","../src/builder.ts","../src/consumers/simple.ts","../src/consumers/batch.ts","../src/adapters/log/destination.ts","../src/adapters/log/index.ts","../src/dsl.ts","../src/shutdown.ts","../src/adapters/simple/source.ts","../src/adapters/simple/index.ts","../src/adapters/noop/destination.ts","../src/adapters/noop/index.ts","../src/adapters/direct/source.ts","../src/adapters/direct/enricher.ts","../src/adapters/direct/index.ts","../src/adapters/timer/types.ts","../src/adapters/timer/source.ts","../src/adapters/timer/index.ts","../src/adapters/cron/index.ts","../src/adapters/http/enricher.ts","../src/adapters/http/redirect.ts","../src/adapters/http/source.ts","../src/adapters/http/index.ts","../src/adapters/file/types.ts","../src/adapters/shared/line-reader.ts","../src/adapters/shared/fs-errors.ts","../src/adapters/shared/file-role-guards.ts","../src/adapters/file/source.ts","../src/adapters/file/destination.ts","../src/adapters/file/enricher.ts","../src/adapters/file/index.ts","../src/adapters/directory/scan.ts","../src/adapters/directory/source.ts","../src/adapters/directory/enricher.ts","../src/adapters/directory/index.ts","../src/adapters/html/shared.ts","../src/adapters/shared/body-text.ts","../src/adapters/html/transformer.ts","../src/adapters/html/source.ts","../src/adapters/html/destination.ts","../src/adapters/html/enricher.ts","../src/adapters/html/index.ts","../src/adapters/json/shared.ts","../src/adapters/json/transformer.ts","../src/adapters/json/source.ts","../src/adapters/json/destination.ts","../src/adapters/json/enricher.ts","../src/adapters/json/index.ts","../src/adapters/csv/types.ts","../src/adapters/csv/shared.ts","../src/adapters/csv/source.ts","../src/adapters/csv/destination.ts","../src/adapters/csv/enricher.ts","../src/adapters/csv/transformer.ts","../src/adapters/csv/index.ts","../src/adapters/xml/shared.ts","../src/adapters/xml/source.ts","../src/adapters/xml/destination.ts","../src/adapters/xml/enricher.ts","../src/adapters/xml/transformer.ts","../src/adapters/xml/index.ts","../src/adapters/jsonl/types.ts","../src/adapters/jsonl/source.ts","../src/adapters/jsonl/destination.ts","../src/adapters/jsonl/shared.ts","../src/adapters/jsonl/enricher.ts","../src/adapters/jsonl/transformer.ts","../src/adapters/jsonl/index.ts","../src/adapters/group/transformer.ts","../src/adapters/group/index.ts","../src/adapters/sources/event/source.ts","../src/adapters/sources/event/index.ts","../src/adapters/mail/index.ts","../src/adapters/mail/source.ts","../src/adapters/mail/enricher.ts","../src/adapters/mail/send-destination.ts","../src/adapters/mail/operation-destination.ts","../src/adapters/carddav/adapter.ts","../src/adapters/carddav/vcard-raw.ts","../src/adapters/carddav/vcard.ts","../src/adapters/carddav/constants.ts","../src/adapters/carddav/index.ts","../src/adapters/cosine/index.ts","../src/deferral/index.ts"],"names":["timingSafeEqual","path","RoutecraftError","RC","stdSerializers","homedir","resolve","existsSync","require","pino","isAbsolute","mkdirSync","dirname","openSync","tmpdir","basename","destination","options","HeadersKeys","logger","createRequire","DEFERRAL_RUNTIME","DEFERRAL_SECRET_ENV","randomBytes","claims","createHmac","DeferralHeaders","DefaultExchange","OperationType","clone","randomUUID","schema","authenticate","createVerify","target","timer","refuse","detail","ms","refresh","cron","delegate","declared","matches","reject","LRUCache","createHash","encode","adapterLabel","free","release","exchange","correlationId","event","getDirectChannel","sanitizeEndpoint","REGISTRY_KEY","getRegistry","entry","createServer","Readable","handle","refusal","mount","log","params","response","join","statSync","readFileSync","version","JSON_SCHEMA_TARGET","result","decodeSegment","withDetails","age","validate","names","verifyStrict","getClientManager","requireClientManager","trace","SpanStatusCode","SQLITE_CONSUMER","keep","claimed","authorize","cas","ABORTED","aggregated","next","targetIndex","mapper","getExchangeContext","REMOVED","text","adapter","createReadStream","createInterface","fsp","fsp2","fsp3","fsp4","path2","fsp5","nodePath","promise","fsp6","CRLF","book"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBO,SAAS,qBAAA,CACd,UACA,SAAA,EACS;AACT,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA;AACxC,EAAA,MAAM,YAAA,GAAe,MAAA,CAAO,IAAA,CAAK,SAAS,CAAA;AAC1C,EAAA,OACE,YAAY,MAAA,KAAW,YAAA,CAAa,MAAA,IACpCA,sBAAA,CAAgB,aAAa,YAAY,CAAA;AAE7C;AA7BA,IAAA,gBAAA,GAAA,KAAA,CAAA;AAAA,EAAA,yBAAA,GAAA;AAAA,EAAA;AAAA,CAAA,CAAA;;;ACiEO,SAAS,QAAA,CAAS,KAAa,KAAA,EAAqB;AACzD,EAAC,GAAA,CAA2C,KAAK,CAAA,GAAI,IAAA;AACvD;AASO,SAAS,YAAA,CACd,GAAA,EACA,GAAA,EACA,KAAA,EACM;AACN,EAAC,GAAA,CAAqC,GAAG,CAAA,GAAI,KAAA;AAC/C;AAWO,SAAS,SAAA,CAAU,KAAc,GAAA,EAAsB;AAC5D,EAAA,OACE,OAAO,GAAA,KAAQ,QAAA,IACf,QAAQ,IAAA,IACP,GAAA,CAAgC,GAAG,CAAA,KAAM,IAAA;AAE9C;AAKO,SAAS,eAAe,GAAA,EAAuB;AACpD,EAAA,OAAO,SAAA,CAAU,GAAA,EAAK,KAAA,CAAM,YAAY,C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ACrD,MAAA,OAAO,gBAAA,CAAiB,EAAA,EAAgB,EAAc,CAAA,GAAI,SAAA;AAAA,IAC5D;AAAA,GACF;AACF;;;ACXA,WAAA,EAAA;AAyDA,mBAAA,EAAA","file":"index.cjs","sourcesContent":["import { timingSafeEqual } from \"node:crypto\";\n\n/**\n * Constant-time equality for a secret and a candidate presented by a caller.\n *\n * Reach for this wherever a request is admitted by comparing something it\n * carried against something the process knows: a shared secret behind a\n * custom `validator`, a signature, a digest. `===` on those returns as soon\n * as two bytes differ, and the time it took is a measurement an attacker can\n * repeat to recover the secret one byte at a time.\n *\n * Wraps `timingSafeEqual` with the explicit length guard it requires: a\n * length mismatch is an ordinary rejection, not an exception. Length itself\n * is not treated as secret; digest lengths are fixed per algorithm, so a\n * mismatch only reveals that the candidate is malformed.\n *\n * @param expected - The value the process knows\n * @param candidate - The value the caller presented\n */\nexport function timingSafeStringEqual(\n  expected: string,\n  candidate: string,\n): boolean {\n  const expectedBuf = Buffer.from(expected);\n  const candidateBuf = Buffer.from(candidate);\n  return (\n    expectedBuf.length === candidateBuf.length &&\n    timingSafeEqual(expectedBuf, candidateBuf)\n  );\n}\n","/**\n * Cross-instance identity: Symbol.for() keys and type guards.\n * Shared across all copies of @routecraft/routecraft in a process (e.g. CLI vs user module).\n */\n\nexport const BRAND = {\n  CraftContext: Symbol.for(\"routecraft.CraftContext\"),\n  DefaultRoute: Symbol.for(\"routecraft.DefaultRoute\"),\n  RouteBuilder: Symbol.for(\"routecraft.RouteBuilder\"),\n  RouteDefinition: Symbol.for(\"routecraft.RouteDefinition\"),\n  RoutecraftError: Symbol.for(\"routecraft.RoutecraftError\"),\n  Exchange: Symbol.for(\"routecraft.Exchange\"),\n  // Envelope brands: value objects (not class instances) marked with\n  // `[brand]: true` so they survive crossing duplicate package copies.\n  SplitChild: Symbol.for(\"routecraft.split.child\"),\n  Recovery: Symbol.for(\"routecraft.recovery\"),\n  /**\n   * RESERVED for the adapter-sandbox `Secret` wrapper (#526). Nothing\n   * brands it yet. The deferral serializer already refuses a value\n   * carrying this brand, so the moment `Secret` starts applying it, \"a\n   * secret must never reach the deferral store\" becomes enforced without\n   * touching the serializer.\n   */\n  Secret: Symbol.for(\"routecraft.secret\"),\n  /**\n   * The `Deferred` acknowledgment execution one answers with. Branded so a\n   * transport recognises a deferred exchange without shape-sniffing a body a\n   * user route could also carry.\n   */\n  Deferred: Symbol.for(\"routecraft.deferred\"),\n  /**\n   * An adapter that may raise a durable deferral from inside its own\n   * execution (the agent tier's tool loop is the one shipped case). The\n   * defer-site walk assigns a re-entrant site to `.to()` / `.enrich()`\n   * steps whose adapter carries this brand, so a runtime deferral from\n   * such a step defers against a continuation that re-runs the step first.\n   * Core owns the symbol; consumer packages mark their adapters with it and\n   * never define their own.\n   */\n  DeferCapable: Symbol.for(\"routecraft.adapter.deferCapable\"),\n  /**\n   * The throwable a defer-capable adapter raises to defer the exchange it\n   * is executing. Converted into the ordinary `defer` StepOutcome at the\n   * step boundary (`.to()` / `.enrich()`), never propagated as a failure.\n   */\n  DeferSignal: Symbol.for(\"routecraft.deferSignal\"),\n} as const;\n\nexport const INTERNALS_KEY = Symbol.for(\"routecraft.exchange.internals\");\n\n/**\n * Type-only symbol used to mark enrich aggregators that declare a merge shape\n * (e.g. only(getValue, \"links\")). .enrich() infers result body as Current & that shape.\n * Not used at runtime.\n */\nexport const ENRICH_MERGE_TYPE: unique symbol = Symbol.for(\n  \"routecraft.EnrichMergeType\",\n) as never;\n\n/**\n * Applies a brand symbol to an object so type guards (isCraftContext, isRoute, etc.) recognize it.\n *\n * @param obj - Object to brand (e.g. CraftContext, DefaultRoute, Exchange)\n * @param brand - Symbol from BRAND (e.g. BRAND.Exchange)\n */\nexport function setBrand(obj: object, brand: symbol): void {\n  (obj as unknown as Record<symbol, boolean>)[brand] = true;\n}\n\n/**\n * Stores symbol-keyed internals on an object (e.g. exchange context/route). Not exposed on the public interface.\n *\n * @param obj - Object to attach internals to\n * @param key - Symbol key (e.g. INTERNALS_KEY)\n * @param value - Value to store\n */\nexport function setInternals<K extends symbol, V>(\n  obj: object,\n  key: K,\n  value: V,\n): void {\n  (obj as unknown as Record<symbol, V>)[key] = value;\n}\n\n/**\n * Shared brand predicate: true when `obj` is an object carrying\n * `[key]: true`. The single implementation of the cross-instance\n * identity check; all guards in this module and the envelope guards\n * (`isSplitChild`, `isRecovery`) go through it so any future hardening\n * of the check lands once.\n *\n * @internal\n */\nexport function isBranded(obj: unknown, key: symbol): boolean {\n  return (\n    typeof obj === \"object\" &&\n    obj !== null &&\n    (obj as Record<symbol, unknown>)[key] === true\n  );\n}\n\n/**\n * Returns true if the value is a CraftContext instance.\n */\nexport function isCraftContext(obj: unknown): boolean {\n  return isBranded(obj, BRAND.CraftContext);\n}\n\n/**\n * Returns true if the value is a Route (DefaultRoute) instance.\n */\nexport function isRoute(obj: unknown): boolean {\n  return isBranded(obj, BRAND.DefaultRoute);\n}\n\n/**\n * Returns true if the value is a RouteBuilder instance (has .build()).\n */\nexport function isRouteBuilder(obj: unknown): boolean {\n  return isBranded(obj, BRAND.RouteBuilder);\n}\n\n/**\n * Returns true if the value is a RouteDefinition (from craft().from().build()).\n */\nexport function isRouteDefinition(obj: unknown): boolean {\n  return isBranded(obj, BRAND.RouteDefinition);\n}\n\n/**\n * Returns true if the value is a RoutecraftError instance.\n */\nexport function isRoutecraftError(obj: unknown): boolean {\n  return isBranded(obj, BRAND.RoutecraftError);\n}\n\n/**\n * A RoutecraftError's RC code, or `undefined` for anything else.\n *\n * Lives beside the guard because every caller of one wants the other, and the\n * knowledge that the code sits on `.rc` was previously re-encoded as an\n * unchecked cast at each site. A cast fails silently when the field moves; one\n * reader fails loudly.\n */\nexport function rcCodeOf(error: unknown): string | undefined {\n  return isRoutecraftError(error) ? (error as { rc?: string }).rc : undefined;\n}\n\n/**\n * Returns true if the value is an Exchange instance.\n */\nexport function isExchange(obj: unknown): boolean {\n  return isBranded(obj, BRAND.Exchange);\n}\n","import { BRAND, setBrand } from \"./brand.ts\";\n\n/**\n * Well-known error categories used by core codes. Ecosystem packages may\n * use their own category strings; the `(string & {})` arm keeps\n * autocomplete on the known set while accepting any value.\n */\nexport type KnownErrorCategory =\n  \"Definition\" | \"DSL\" | \"Lifecycle\" | \"Adapter\" | \"Runtime\";\n\nexport type RCMeta = {\n  category: KnownErrorCategory | (string & {});\n  message: string;\n  suggestion?: string;\n  docs: string;\n  /**\n   * Whether this error should be retried by the retry wrapper.\n   * - `true`: Transient error, retry may succeed (e.g., network issues)\n   * - `false`: Permanent error, retry will not help (e.g., validation, config)\n   */\n  retryable: boolean;\n};\n\n/**\n * Open error-code registry. Core declares its own `RC####` codes here;\n * ecosystem packages add namespaced codes via declaration merging plus a\n * runtime {@link registerErrorCodes} call:\n *\n * ```typescript\n * declare module \"@routecraft/routecraft\" {\n *   interface ErrorCodeRegistry {\n *     AI1001: RCMeta;\n *   }\n * }\n * registerErrorCodes(\"AI\", { AI1001: { ... } }, \"@routecraft/ai\");\n * ```\n *\n * The `RC` namespace is reserved for core. Each namespace is claimable by\n * exactly one owner package, which makes cross-package code collisions a\n * detectable package-identity conflict instead of a silent numbering\n * accident (TypeScript merges identical `X: RCMeta` declarations without\n * complaint, so the compiler alone cannot catch them).\n */\nexport interface ErrorCodeRegistry {\n  RC1001: RCMeta;\n  RC1002: RCMeta;\n  RC1003: RCMeta;\n  RC1004: RCMeta;\n  RC2001: RCMeta;\n  RC2002: RCMeta;\n  RC3001: RCMeta;\n  RC3002: RCMeta;\n  RC5001: RCMeta;\n  RC5002: RCMeta;\n  RC5003: RCMeta;\n  RC5004: RCMeta;\n  RC5010: RCMeta;\n  RC5011: RCMeta;\n  RC5012: RCMeta;\n  RC5013: RCMeta;\n  RC5014: RCMeta;\n  RC5015: RCMeta;\n  RC5016: RCMeta;\n  RC5017: RCMeta;\n  RC5018: RCMeta;\n  RC5019: RCMeta;\n  RC5020: RCMeta;\n  RC5021: RCMeta;\n  RC5022: RCMeta;\n  RC5023: RCMeta;\n  RC5024: RCMeta;\n  RC5025: RCMeta;\n  RC5026: RCMeta;\n  RC5028: RCMeta;\n  RC5029: RCMeta;\n  RC5030: RCMeta;\n  RC5031: RCMeta;\n  RC5032: RCMeta;\n  RC5033: RCMeta;\n  RC5034: RCMeta;\n  RC5035: RCMeta;\n  RC5036: RCMeta;\n  RC5037: RCMeta;\n  RC5038: RCMeta;\n  RC5039: RCMeta;\n  RC5040: RCMeta;\n  RC5041: RCMeta;\n  RC5042: RCMeta;\n  RC5043: RCMeta;\n  RC5044: RCMeta;\n  RC5045: RCMeta;\n  RC5046: RCMeta;\n  RC5047: RCMeta;\n  RC5048: RCMeta;\n  RC5049: RCMeta;\n  RC5050: RCMeta;\n  RC5051: RCMeta;\n  RC5052: RCMeta;\n  RC5053: RCMeta;\n  RC5054: RCMeta;\n  RC5055: RCMeta;\n  RC5056: RCMeta;\n  RC5057: RCMeta;\n  RC5058: RCMeta;\n  RC5059: RCMeta;\n  RC5060: RCMeta;\n  RC5061: RCMeta;\n  RC5062: RCMeta;\n  RC5063: RCMeta;\n  RC5064: RCMeta;\n  RC5065: RCMeta;\n  RC5066: RCMeta;\n  RC9901: RCMeta;\n}\n\n/** All known error codes: core `RC####` plus registered ecosystem namespaces. */\nexport type RCCode = keyof ErrorCodeRegistry;\n\nexport const DOCS_BASE = \"https://routecraft.dev/docs/reference/errors\";\n\n/**\n * Core codes only: the `RC####` keys declared in this file. Ecosystem keys\n * merged into {@link ErrorCodeRegistry} are excluded so the `RC` const\n * below stays exhaustively checked against what core actually defines.\n */\ntype CoreErrorCode = keyof ErrorCodeRegistry & `RC${number}`;\n\nexport const RC: { [K in CoreErrorCode]: RCMeta } = {\n  RC1001: {\n    category: \"Definition\",\n    message: \"Route definition failed validation\",\n    suggestion: \"Ensure a source is defined: start with from(adapter)\",\n    docs: `${DOCS_BASE}#rc-1001`,\n    retryable: false, // Config error - won't change on retry\n  },\n  RC1002: {\n    category: \"Definition\",\n    message: \"Duplicate route id\",\n    suggestion: \"Ensure each route id is unique or set routeOptions.id\",\n    docs: `${DOCS_BASE}#rc-1002`,\n    retryable: false, // Config error - won't change on retry\n  },\n  RC1003: {\n    category: \"Definition\",\n    message: \"Error code registration failed\",\n    suggestion:\n      \"Namespaces must match /^[A-Z][A-Z0-9]{1,7}$/, 'RC' is reserved for core, each namespace is claimable by exactly one package, and every code must be the namespace followed by exactly four digits. If two packages claim the same namespace, report the collision to both package owners.\",\n    docs: `${DOCS_BASE}#rc-1003`,\n    retryable: false,\n  },\n  RC1004: {\n    category: \"Definition\",\n    message: \"Context already stopped\",\n    suggestion:\n      \"A CraftContext is single-use: once stopped, its routes and controllers are gone for good. Build a fresh context from your config instead of restarting a stopped one.\",\n    docs: `${DOCS_BASE}#rc-1004`,\n    retryable: false,\n  },\n  RC2001: {\n    category: \"DSL\",\n    message: \"Invalid operation type\",\n    suggestion: \"Use a supported operator and verify the step name\",\n    docs: `${DOCS_BASE}#rc-2001`,\n    retryable: false, // DSL error - won't change on retry\n  },\n  RC2002: {\n    category: \"DSL\",\n    message: \"Missing from step\",\n    suggestion: \"Start the route with from and a valid source adapter\",\n    docs: `${DOCS_BASE}#rc-2002`,\n    retryable: false, // DSL error - won't change on retry\n  },\n  RC3001: {\n    category: \"Lifecycle\",\n    message: \"Route failed to start\",\n    suggestion: \"Ensure the route is not aborted and adapters are configured\",\n    docs: `${DOCS_BASE}#rc-3001`,\n    retryable: false, // Lifecycle error - requires intervention\n  },\n  RC3002: {\n    category: \"Lifecycle\",\n    message: \"Context failed to start\",\n    suggestion: \"Validate plugin exports and global configuration\",\n    docs: `${DOCS_BASE}#rc-3002`,\n    retryable: false, // Lifecycle error - requires intervention\n  },\n  RC5001: {\n    category: \"Adapter\",\n    message: \"Step execution failed\",\n    suggestion:\n      \"Read the error message and suggestion; check adapter documentation\",\n    docs: `${DOCS_BASE}#rc-5001`,\n    retryable: true, // Per instance; adapter may override\n  },\n  RC5002: {\n    category: \"Adapter\",\n    message: \"Validation failed\",\n    suggestion: \"Adjust the schema or coerce input; check data shapes\",\n    docs: `${DOCS_BASE}#rc-5002`,\n    retryable: false,\n  },\n  RC5003: {\n    category: \"Adapter\",\n    message: \"Adapter misconfigured\",\n    suggestion:\n      \"Check required options and correct role usage (.from() vs .to())\",\n    docs: `${DOCS_BASE}#rc-5003`,\n    retryable: false,\n  },\n  RC5004: {\n    category: \"Adapter\",\n    message: \"No handler available\",\n    suggestion:\n      \"Ensure the consumer route is running before sending. Check route startup order.\",\n    docs: `${DOCS_BASE}#rc-5004`,\n    retryable: false,\n  },\n  RC5010: {\n    category: \"Adapter\",\n    message: \"Connection failed\",\n    suggestion:\n      \"Check network, DNS, ports, and firewall; verify service is running\",\n    docs: `${DOCS_BASE}#rc-5010`,\n    retryable: true,\n  },\n  RC5011: {\n    category: \"Adapter\",\n    message: \"Request timeout\",\n    suggestion: \"Increase timeout or configure retry with backoff\",\n    docs: `${DOCS_BASE}#rc-5011`,\n    retryable: true,\n  },\n  RC5012: {\n    category: \"Adapter\",\n    message: \"Authentication failed\",\n    suggestion: \"Verify API keys, tokens, and credential configuration\",\n    docs: `${DOCS_BASE}#rc-5012`,\n    retryable: false,\n  },\n  RC5013: {\n    category: \"Adapter\",\n    message: \"Rate limited\",\n    suggestion: \"Reduce request frequency or configure retry with backoff\",\n    docs: `${DOCS_BASE}#rc-5013`,\n    retryable: true,\n  },\n  RC5014: {\n    category: \"Adapter\",\n    message: \"Resource not found\",\n    suggestion:\n      \"Check that the resource exists (model ID, endpoint, queue name)\",\n    docs: `${DOCS_BASE}#rc-5014`,\n    retryable: false,\n  },\n  RC5015: {\n    category: \"Adapter\",\n    message: \"Permission denied\",\n    suggestion: \"Check access control, IAM, and scopes\",\n    docs: `${DOCS_BASE}#rc-5015`,\n    retryable: false,\n  },\n  RC5016: {\n    category: \"Adapter\",\n    message: \"Source payload parse failed\",\n    suggestion:\n      \"Check the input data matches the adapter's expected format (JSON, CSV, JSONL, HTML, MIME). Wire .error() on the route to recover, or set onParseError to 'abort' (stop the source) or 'drop' (emit route:exchange:dropped) on the adapter.\",\n    docs: `${DOCS_BASE}#rc-5016`,\n    retryable: false,\n  },\n  RC5017: {\n    category: \"Adapter\",\n    message: \"Optional peer dependency missing\",\n    suggestion:\n      \"Install the optional peer the adapter requires (the error message names the package).\",\n    docs: `${DOCS_BASE}#rc-5017`,\n    retryable: false,\n  },\n  RC5018: {\n    category: \"Adapter\",\n    message: \"HTTP source request rejected\",\n    suggestion:\n      \"Check that the request method and path match a registered http() source. 404 means no route is bound to that path; 405 means the path exists but the method differs; 413 means the body exceeded http.maxBodySize; 400 means it could not be parsed for its declared Content-Type.\",\n    docs: `${DOCS_BASE}#rc-5018`,\n    retryable: false,\n  },\n  RC5019: {\n    category: \"Adapter\",\n    message: \"HTTP server bind failed\",\n    suggestion:\n      \"Check that the configured port is free and the host is reachable. EADDRINUSE means another process owns the port; EADDRNOTAVAIL means the host is not one this machine can bind to.\",\n    docs: `${DOCS_BASE}#rc-5019`,\n    retryable: false,\n  },\n  RC5020: {\n    category: \"Adapter\",\n    message: \"Authorization failed: token expired during processing\",\n    suggestion:\n      \"The verified principal carried an `expiresAt` that is now in the past; a long-running step (LLM call, slow downstream) outlived the credential. The client should refresh and retry. Distinct from RC5012 (no principal) and RC5015 (wrong roles/scopes) so callers can react accordingly.\",\n    docs: `${DOCS_BASE}#rc-5020`,\n    retryable: false,\n  },\n  RC5021: {\n    category: \"Adapter\",\n    message: \"Principal enrichment failed\",\n    suggestion:\n      \"The `userinfo` option on `mcpPlugin({})` could not enrich the verified principal. The cause names the underlying problem (HTTP status, network error, malformed JSON, missing `userinfo_endpoint` in the OIDC Discovery document). Verify the userinfo endpoint URL, IdP availability, and the bearer token's scope grants. Fail-closed: the request is rejected to prevent silent identity gaps.\",\n    docs: `${DOCS_BASE}#rc-5021`,\n    retryable: false,\n  },\n  RC5022: {\n    category: \"Adapter\",\n    message: \"Userinfo sub invariant violated\",\n    suggestion:\n      \"Per OIDC Core §5.3.2, the userinfo response MUST carry a `sub` matching the verified token's `sub`. A mismatch (or missing `sub`) indicates a compromised userinfo endpoint or a configuration error mapping the wrong userinfo URL to the bearer's issuer. The request is rejected to prevent identity confusion.\",\n    docs: `${DOCS_BASE}#rc-5022`,\n    retryable: false,\n  },\n  RC5023: {\n    category: \"Adapter\",\n    message: \"Authorization failed: principal is not authentic\",\n    suggestion:\n      'A principal was present but was not established by a trusted origin (a plain object written onto headers[\"routecraft.auth.principal\"] is self-asserted). Mint identity with the .authenticate() operation or the authenticate() helper, or let a source verifier (jwt/jwks/oauth) attach it. Distinct from RC5012 (no principal) and RC5015 (wrong roles/scopes).',\n    docs: `${DOCS_BASE}#rc-5023`,\n    retryable: false,\n  },\n  RC5024: {\n    category: \"Adapter\",\n    message: \"authenticate() called with invalid claims\",\n    suggestion:\n      \"authenticate() (and the .authenticate() operation) require a non-empty `subject` naming the verified identity, and reject delegation state (`actor`, `grantId`): minting establishes identity, delegate() establishes who is acting for it. This is a programming error at the mint call, distinct from RC5023 (a principal that reached authorize() without being established by a trusted origin).\",\n    docs: `${DOCS_BASE}#rc-5024`,\n    retryable: false,\n  },\n  RC5025: {\n    category: \"Runtime\",\n    message: \"Circuit breaker is open\",\n    suggestion:\n      \"The route or step exceeded its failure threshold and is failing fast to prevent cascading failures against a downstream that is known to be unhealthy. Wait for the cooldown to elapse (the breaker then probes with a half-open call), configure a `fallback` to return a degraded result instead of throwing, or raise `failureThreshold` / `cooldownMs` if the breaker is too sensitive. Not retryable: an immediate retry would hit the same open breaker.\",\n    docs: `${DOCS_BASE}#rc-5025`,\n    retryable: false,\n  },\n  RC5026: {\n    category: \"Runtime\",\n    message: \"Concurrency limit exceeded\",\n    suggestion:\n      \"The route or step is at its `.concurrency({ max })` bulkhead limit and is failing fast (reject mode, or a full `maxQueue`) instead of admitting more simultaneous work. Retryable: a slot frees as soon as in-flight work completes, so an outer `.retry()` (which sits outside the bulkhead) can back off and re-acquire one. Raise `max`, switch to the default queue mode to apply backpressure instead, or shed load (e.g. return 503) in `.error()`.\",\n    docs: `${DOCS_BASE}#rc-5026`,\n    retryable: true,\n  },\n  RC5028: {\n    category: \"Adapter\",\n    message: \"Cache provider failed\",\n    suggestion:\n      \"Inspect the underlying cache backend (in-memory, Redis, etc.); transient backend errors may resolve on retry.\",\n    docs: `${DOCS_BASE}#rc-5028`,\n    retryable: true,\n  },\n  RC5029: {\n    category: \"Adapter\",\n    message: \"Cache key derivation failed\",\n    suggestion:\n      \"The default key needs a JSON-serialisable body. It fails when the body is undefined (a bodiless request such as an http() GET, whose input lives in the routecraft.http.params / routecraft.http.query headers) or cannot be serialised (a top-level function or symbol, a circular reference, a BigInt; nested functions and symbols are silently omitted, not rejected). Supply an explicit `key` function in cache({ key: ... }); a custom key is used verbatim, so include the route and caller identity when they matter. Retrying will not help: the same exchange fails the same way.\",\n    docs: `${DOCS_BASE}#rc-5029`,\n    retryable: false,\n  },\n  RC5030: {\n    category: \"Adapter\",\n    message: \"Resource changed (precondition failed)\",\n    suggestion:\n      \"A conditional write failed because the resource changed on the server since it was read (HTTP 412 / ETag mismatch, a mid-air collision). Re-read the resource and re-apply the change; a blind retry with the same precondition will keep failing, so this is not retryable.\",\n    docs: `${DOCS_BASE}#rc-5030`,\n    retryable: false,\n  },\n  RC5031: {\n    category: \"Runtime\",\n    message: \"Exchange dropped before completion\",\n    suggestion:\n      \"The target route discarded the exchange instead of completing it (a filter rejected it, the source's onParseError was 'drop', or an error handler returned recovery.drop()), so there is no response body for a request/reply caller. If the caller should receive a value, recover with a body in .error() or let the exchange pass the filter.\",\n    docs: `${DOCS_BASE}#rc-5031`,\n    retryable: false,\n  },\n  RC5032: {\n    category: \"Runtime\",\n    message: \"Unsupported step outcome\",\n    suggestion:\n      \"A step returned a StepOutcome the engine cannot schedule. Either the kind is one this build does not know, or a 'defer' outcome arrived without the request the executor needs to defer the exchange (only the framework's own `.defer()` step produces one). If you wrote a custom step, return a supported outcome (continue, complete, drop, branch, fanOut). Retrying will not help.\",\n    docs: `${DOCS_BASE}#rc-5032`,\n    retryable: false,\n  },\n  RC5033: {\n    category: \"Adapter\",\n    message: \"Dedupe key derivation failed\",\n    suggestion:\n      \"The default `.dedupe()` key hashes the caller's principal and JSON.stringify(body); it fails when the body is undefined (a bodiless request such as an http() GET, whose input lives in the routecraft.http.params / routecraft.http.query headers) or cannot be serialised (functions, symbols, circular refs, BigInt). Supply an explicit `key` function in dedupe({ key: ... }); a custom key is used verbatim, so include the caller's identity when callers must not dedupe each other. Retrying will not help: the same exchange fails the same way.\",\n    docs: `${DOCS_BASE}#rc-5033`,\n    retryable: false,\n  },\n  RC5034: {\n    category: \"Adapter\",\n    message: \"Actor not permitted\",\n    suggestion:\n      \"The principal carries an actor (a delegate acting on the subject's behalf) that this route's authorize({ actor }) does not accept. The default is actor: 'none' (not agent-reachable). Declare the permitted actor(s) on the route, or have the caller act directly. Permanent under the current declaration.\",\n    docs: `${DOCS_BASE}#rc-5034`,\n    retryable: false,\n  },\n  RC5035: {\n    category: \"Adapter\",\n    message: \"Subject not permitted\",\n    suggestion:\n      \"The principal's subject does not match this route's authorize({ subject }) constraint (subject id, issuer, or profile). Permanent under current credentials.\",\n    docs: `${DOCS_BASE}#rc-5035`,\n    retryable: false,\n  },\n  RC5036: {\n    category: \"Adapter\",\n    message: \"Delegation chain too deep\",\n    suggestion:\n      \"The principal's actor chain is longer than the route's maxDelegationDepth (default 1). Re-delegation through further agents is not accepted here; have an agent closer to the subject perform the call, or raise maxDelegationDepth deliberately.\",\n    docs: `${DOCS_BASE}#rc-5036`,\n    retryable: false,\n  },\n  RC5037: {\n    category: \"Adapter\",\n    message: \"Delegation refused by mayAct\",\n    suggestion:\n      \"delegate() was asked to mint an actor the subject has not permitted (no matching mayAct entry). Obtain the subject's consent (record a grant, which populates mayAct) and retry. Never widen mayAct without an explicit consent event.\",\n    docs: `${DOCS_BASE}#rc-5037`,\n    retryable: false,\n  },\n  RC5038: {\n    category: \"Adapter\",\n    message: \"Insufficient authority (recoverable)\",\n    suggestion:\n      \"The identity is valid but lacks scope for this capability. The error's `missing` detail lists what is absent (RFC 9470 / RFC 6750 insufficient_scope shape). Obtain the missing grant via your consent flow, then retry.\",\n    docs: `${DOCS_BASE}#rc-5038`,\n    // \"Recoverable\" describes the AUTHORIZATION outcome (a consent flow can\n    // add the scope), not the request. Retrying the same call with the same\n    // credential fails identically, so the retry wrapper must not treat this\n    // as transient.\n    retryable: false,\n  },\n  RC5039: {\n    category: \"Adapter\",\n    message: \"HTTP webhook signature verification failed\",\n    suggestion:\n      \"A route with http({ signature: {...} }) rejected a request whose signature header was missing, invalid, or expired. Check that the secret matches the provider's signing secret, the header name matches what the provider sends (e.g. x-hub-signature-256), and the prefix matches the provider's format (e.g. \\\"sha256=\\\" for GitHub). If the provider's deliveries pass through a proxy that re-encodes the body, the signed bytes no longer match; verification must see the exact wire bytes.\",\n    docs: `${DOCS_BASE}#rc-5039`,\n    retryable: false,\n  },\n  RC5040: {\n    category: \"Definition\",\n    message: \"Resume-token signing secret not configured\",\n    suggestion:\n      \"A route in this context can reach a durable .defer(), so resume tokens must be signable. Set the ROUTECRAFT_DEFERRAL_SECRET environment variable, or pass deferral: { secret } to defineConfig; generate one with `openssl rand -base64 32`. At least 32 bytes are required, because a resume token is a bearer capability and its holder can guess the secret offline without limit. The secret is never generated into the store: a store compromise must not yield forgeable resume tokens. testContext() and NODE_ENV=development or test mint an ephemeral in-memory key, so tests and local iteration need no setup.\",\n    docs: `${DOCS_BASE}#rc-5040`,\n    retryable: false,\n  },\n  RC5041: {\n    category: \"Runtime\",\n    message: \"Resume token rejected\",\n    suggestion:\n      \"The token presented to .resume() was malformed, carried a bad signature, or named a deferral this context cannot verify. Resume with the exact token minted at defer time. If the token is genuine, check that every node shares one signing secret: a token signed with a different secret is indistinguishable from a forged one.\",\n    docs: `${DOCS_BASE}#rc-5041`,\n    retryable: false,\n  },\n  RC5042: {\n    category: \"Runtime\",\n    message: \"Exchange cannot be persisted for deferral\",\n    suggestion:\n      \"Deferral serializes the exchange to durable storage, so its body and headers must be plain JSON data. A function, symbol, bigint, class instance, circular reference, or secret-bearing value cannot be written. Move the offending value out of the exchange before the defer point: resolve it to a string, keep it in context.store (which outlives the exchange and is not persisted), or recompute it after resume.\",\n    docs: `${DOCS_BASE}#rc-5042`,\n    retryable: false,\n  },\n  RC5043: {\n    category: \"Adapter\",\n    message: \"Principal restored from a deferral\",\n    suggestion:\n      \"authorize() rejected a principal that came back from durable storage with a resumed exchange. It is a recorded shape with no live credential behind it: nothing re-checked the signature, the expiry, or revocation. Re-verify the identity after resume with .authenticate() from a checked credential, or put the authorization on the resume ingress route, where the resuming principal is verified live. Distinct from RC5023 (self-asserted) because the fix differs: re-verify, do not mint.\",\n    docs: `${DOCS_BASE}#rc-5043`,\n    retryable: false,\n  },\n  RC5044: {\n    category: \"Runtime\",\n    message: \"Deferral store operation failed\",\n    suggestion:\n      \"The deferral store could not complete a read or write. Common causes: a duplicate deferral id (a bug in id derivation, since ids are minted per defer), a store file that is unwritable or out of disk, a store written by a newer Routecraft build than the one now running, and a path shared with another store. Each store needs its own file: every sqlite store versions itself through one PRAGMA user_version per database, so two pointed at one path are refused rather than made to work. Deliberately not retryable: none of these clear on a second attempt, so a .retry() wrapper must not burn its budget on them.\",\n    docs: `${DOCS_BASE}#rc-5044`,\n    retryable: false,\n  },\n  RC5045: {\n    category: \"Runtime\",\n    message: \"Deferral store busy\",\n    suggestion:\n      \"Another writer held the deferral store's write lock for longer than the busy timeout. Unlike RC5044 this is transient: the competing write finishes and the same call succeeds, so it is registered retryable and a .retry() wrapper re-attempts it. Persistent contention means more than one process is writing the same store file; give each its own store, or move to a backend built for concurrent writers.\",\n    docs: `${DOCS_BASE}#rc-5045`,\n    retryable: true,\n  },\n  RC5046: {\n    category: \"Runtime\",\n    message: \"Deferral not found\",\n    suggestion:\n      \"The resume token verified, but the store holds no deferral under that id. The record was purged by retention, the process is pointed at a different store than the one that deferred the exchange (an in-memory store after a restart, a different sqlite path), or the id was resumed against the wrong deployment. Check `deferral: { store }` names the same location on every node.\",\n    docs: `${DOCS_BASE}#rc-5046`,\n    retryable: false,\n  },\n  RC5047: {\n    category: \"Runtime\",\n    message: \"Deferral expired\",\n    suggestion:\n      \"The resume arrived after the deferral's `ttl` elapsed, so the deferred exchange is no longer resumable. This is catchable: the deferred route's own `.error()` handler receives this error and can notify and re-ask. Raise `ttl` on `.defer()` if the window is genuinely too short for the people it waits on.\",\n    docs: `${DOCS_BASE}#rc-5047`,\n    retryable: false,\n  },\n  RC5048: {\n    category: \"Runtime\",\n    message: \"Deferral continuation changed\",\n    suggestion:\n      \"The steps after the defer point (or the `expect` schema) changed while the exchange was deferred, so the stored approval no longer authorizes what would now run. Resuming is refused before any of those steps execute. This is catchable: the deferred route's `.error()` handler receives it and can re-ask with a fresh deferral. Note the hash also moves for edits that change emitted step source without changing behaviour (a formatting pass, different line endings, a build-settings change), so deployments that defer approvals for days should pin those.\",\n    docs: `${DOCS_BASE}#rc-5048`,\n    retryable: false,\n  },\n  RC5049: {\n    category: \"Runtime\",\n    message: \"Deferral result rejected\",\n    suggestion:\n      \"The payload handed to `.resume()` failed the `schema` declared on the deferring `.defer()`. The deferral is left resumable, so a corrected payload still works. Check the mapping function in `.resume((ex) => ({ token, result }))`: it owns the SHAPE of the payload, while validation happens at revival because only the deferral knows the schema. Unlike an expiry or a changed continuation, this is raised in the RESUME INGRESS route only: a malformed payload is a per-request input error, not a change the deferred route has to re-ask about. Handle it with an `.error()` on the ingress route if the caller deserves a reply.\",\n    docs: `${DOCS_BASE}#rc-5049`,\n    retryable: false,\n  },\n  RC5050: {\n    category: \"Runtime\",\n    message: \"Deferral denied\",\n    suggestion:\n      \"The deferral was marked denied before this resume arrived, typically because the run carrying the deferred exchange was cancelled. A denied deferral is terminal; the work must be re-submitted as a new exchange rather than resumed.\",\n    docs: `${DOCS_BASE}#rc-5050`,\n    retryable: false,\n  },\n  RC5051: {\n    category: \"Definition\",\n    message: \"Defer not supported at this position\",\n    suggestion:\n      \"A `.defer()` was declared where the framework cannot durably defer and revive the exchange: inside a `.split()` fan-out between the split and its `.aggregate()` (a durable aggregator would have to track N outstanding children across restarts), or inside a `.multicast()` path or `.dispatch()` target (those exchanges are isolated side flows rather than the route's primary flow, so a resumed continuation would have nowhere to rejoin). Move the defer out of the fan-out, or split the work into per-item child capabilities, each its own exchange deferring independently; on the main flow or a `.choice()` branch of it, a defer is fine. A `.defer()` under a step-scope wrapper is refused separately, as RC5003.\",\n    docs: `${DOCS_BASE}#rc-5051`,\n    retryable: false,\n  },\n  RC5052: {\n    category: \"Definition\",\n    message: \"Deferral runtime not configured\",\n    suggestion:\n      \"A route in this context can reach a durable `.defer()`, but nothing configured where deferred exchanges are stored or how resume tokens are signed. Add `deferral: {}` to `defineConfig` to take the defaults (sqlite plus the `ROUTECRAFT_DEFERRAL_SECRET` environment variable), or `deferral: { store, secret }` to be explicit. It is deliberately not implicit: a durable defer that silently defers into memory loses everything it promised on the next restart.\",\n    docs: `${DOCS_BASE}#rc-5052`,\n    retryable: false,\n  },\n  RC5053: {\n    category: \"Definition\",\n    message: \"Ops plugin misconfigured\",\n    suggestion:\n      \"Check the `ops` config. Common causes: an indicator bound to a `route` id no route declares (the message lists the known ids), two indicators sharing a name (names are the keys of the health report, so they must be unique), a value in `ops.indicators` that `defineIndicator()` did not produce, or an invalid `health.details` value.\",\n    docs: `${DOCS_BASE}#rc-5053`,\n    retryable: false,\n  },\n  RC5054: {\n    category: \"Runtime\",\n    message: \"Deferral cancelled by run abort\",\n    suggestion:\n      \"The run raised a durable deferral while it was being cancelled (a route stop or an elapsed .timeout()). If the abort won the race the exchange was never deferred; if the deferral won, the just-created deferral was immediately denied so its resume link is dead, and a presented token reads RC5050. Either way the caller sees this error instead of a resumable acknowledgment, which keeps the two stories consistent: a run reported as cancelled must not be resumable later. This is about the cancellation race only; a deferred exchange whose process merely stops SURVIVES the stop, which is the store's entire purpose.\",\n    docs: `${DOCS_BASE}#rc-5054`,\n    retryable: false,\n  },\n  RC5055: {\n    category: \"Runtime\",\n    message: \"Resume credential not bound to this call\",\n    suggestion:\n      \"The token verifies and names a real deferral, but it was minted for a different call than the one the record is deferred on. A batch of parallel tool calls mints one credential per call against a single record, and only the call that actually deferred may be resumed; a losing sibling's credential is refused here. Re-ask on the credential minted for the winning call, and do not route two recipients to one deferral. The refusal is non-destructive: the record is left exactly as it was found, still resumable by the rightful credential.\",\n    docs: `${DOCS_BASE}#rc-5055`,\n    retryable: false,\n  },\n  RC5056: {\n    category: \"Runtime\",\n    message: \"Resume refused by the route's authorize hook\",\n    suggestion:\n      \"The `.resume({ authorize })` hook on the ingress route refused this principal. Who may resume a deferred run is the application's policy, not the framework's: the hook receives the live principal, the deferred principal snapshot, the raw submitted payload, and the record's context (including whatever `meta` the defer site attached), and decides. A hook that returns false, throws, or does not settle before the route's own `.timeout()` produces this one code with the same message, deliberately: a hook whose failures can be told apart from outside is an oracle for what it knows. The cause is in the boundary log, never on the wire, and a thrown cause is never returned. The refusal is non-destructive, so the record stays resumable by whoever does qualify.\",\n    docs: `${DOCS_BASE}#rc-5056`,\n    retryable: false,\n  },\n  RC5057: {\n    category: \"Runtime\",\n    message: \"Deferral sequence header unusable\",\n    suggestion:\n      \"The framework-owned `routecraft.deferral.sequence` header carries a value the deferral counter cannot use, so no deferral id was derived. Headers are a writable bag, and this one is refused rather than reset because a reset counter re-derives an id an earlier deferral already used, and resume tokens sign the id: an old unspent link would then act on the new deferral. If the message says the value is malformed, find the step that overwrote or mangled the framework header (spreading headers through an external system is the usual culprit) and stop it. If it says the counter is exhausted, this exchange has deferred more times than a counter can count; that is not reachable by deferring in a loop within a ttl, so treat it as the same corruption with a plausible-looking value.\",\n    docs: `${DOCS_BASE}#rc-5057`,\n    retryable: false,\n  },\n  RC5058: {\n    category: \"Definition\",\n    message: \"Invalid shutdown configuration\",\n    suggestion:\n      '`shutdown.timeout` must be a positive, finite duration. It is refused rather than clamped because the two plausible readings of `0` are opposites: it looks like \"no bound\" and would behave as \"force immediately\", abandoning in-flight work the moment a stop begins. Omit the key to take the 30-second default, and set it below your platform\\'s kill timer so the process\\'s own policy decides the outcome.',\n    docs: `${DOCS_BASE}#rc-5058`,\n    retryable: false,\n  },\n  RC5059: {\n    category: \"Runtime\",\n    message: \"Management API request refused\",\n    suggestion:\n      \"The management API refused a paging argument rather than interpreting it. A `limit` must be a positive integer within the server-side maximum: it is refused rather than clamped because a caller that asked for 10000 and silently received a bounded page cannot tell a truncated answer from a complete one. A cursor must be the `nextCursor` from the previous page, passed back unchanged, and it is valid only for the filter that produced it: a cursor pages one result set, so changing a filter starts a new listing rather than resuming an old one under new terms.\",\n    docs: `${DOCS_BASE}#rc-5059`,\n    retryable: false,\n  },\n  RC5060: {\n    category: \"Runtime\",\n    message: \"Route is not dispatchable\",\n    suggestion:\n      \"`POST /ops/routes/{id}/exchanges` creates an exchange on a route, and only a `direct()` ingress makes a route id into a door that can accept one. A cron-, mail- or http-sourced route runs from its own trigger and has no such door, so a dispatch against it is refused here rather than failing somewhere less legible. Add `.from(direct())` to the route if it should be callable, or dispatch to one that already is; `GET /ops/routes?dispatchable=true` lists exactly the routes that will accept this call.\",\n    docs: `${DOCS_BASE}#rc-5060`,\n    retryable: false,\n  },\n  RC5061: {\n    category: \"Adapter\",\n    message: \"HTTP client response body exceeds maxBodySize\",\n    suggestion:\n      \"The response to an `http({ url })` call is larger than the route allows, so it was refused rather than read. The cap defaults to 10 MB, matching the http plugin's inbound `maxBodySize`; raise it with `http({ url, maxBodySize })` when the endpoint genuinely returns more, or ask the endpoint for less (a narrower query, a page, a range request). The body is never truncated to fit: half a JSON document parses as though it were whole, and a route acting on it would be wrong rather than failed. A declared `Content-Length` over the cap is refused before any byte is read; a body that declares nothing is abandoned mid-stream the moment the count crosses the ceiling, so the message names whichever number was seen.\",\n    docs: `${DOCS_BASE}#rc-5061`,\n    retryable: false,\n  },\n  RC5062: {\n    category: \"Runtime\",\n    message: \"Remote instance unreachable\",\n    suggestion:\n      \"A dispatch to a route imported through `defineConfig({ remotes })` never got an answer from the remote instance: the connection was refused or the name did not resolve, the connection was lost after the request was sent, or the request timed out. Check the remote's `url` and that the instance is running and serving its ops surface. Only a connection that never opened is safe to retry; a lost connection or a timeout is not, because the remote may still be running the work it accepted, and the error carries `retryable: false` for those. The message says which it was.\",\n    docs: `${DOCS_BASE}#rc-5062`,\n    retryable: true,\n  },\n  RC5063: {\n    category: \"Runtime\",\n    message: \"Remote instance refused the credential\",\n    suggestion:\n      \"The remote answered 401 or 403 to a dispatch on an imported route, so the problem is the identity the dispatch carried and not a fault in the route. The message carries the remote's own reason: no credential was presented (`remotes.<name>.auth.token` is unset or resolved to nothing), the credential was rejected or expired, it is valid but lacks the dispatch tier's or the route's scope, which needs a token carrying that scope rather than a new sign-in, or the route's own `.authorize()` does not admit the identity with the claims its credential carries (`insufficient_permissions`), which a retry with the same credential cannot change but a refreshed token carrying newly granted claims can. When the remote advertises RFC 9728 metadata the message also names who issues acceptable tokens.\",\n    docs: `${DOCS_BASE}#rc-5063`,\n    retryable: false,\n  },\n  RC5064: {\n    category: \"Runtime\",\n    message: \"Remote dispatch failed\",\n    suggestion:\n      \"The remote instance answered a dispatch on an imported route with an error. Its own error code rides in the message and on `cause`, and is what to read first: the ops door sends the code and never the message, so the remote's logs hold the detail. A `RC5060` from the remote means the route stopped being dispatchable there (it declared `direct({ internal: true })`, or lost its direct source); anything else is the route's own failure, exactly as it would have surfaced to a caller on the remote.\",\n    docs: `${DOCS_BASE}#rc-5064`,\n    retryable: false,\n  },\n  RC5065: {\n    category: \"Runtime\",\n    message: \"Request validation failed\",\n    suggestion:\n      \"The payload a caller supplied did not satisfy the route's `.input()` schema. Read the issues: each names a field (`path`) and the rule it broke (`message`); in process they are on the error's cause (`isInputValidationFailure(err.cause)`), and over HTTP the `http()` source and the ops dispatch mount answer 400 carrying them, with `in` naming the body or the headers. This is the caller's fault rather than the instance's, which is what separates it from `RC5002`. Issue messages are the schema's own text and reach the caller verbatim.\",\n    docs: `${DOCS_BASE}#rc-5065`,\n    retryable: false,\n  },\n  RC5066: {\n    category: \"Definition\",\n    message: \"Deferral store is missing a contract member\",\n    suggestion:\n      \"A surface asked the deferral store for something the store this context was given does not implement. The two shipped backends (sqlite and memory) implement the whole `DeferralStore` contract; a store supplied through `deferral: { store }` is the caller's own, and one written against an earlier version of the contract can be missing a member added since. The message names the member. Implement it, or drop back to a shipped backend. The surface refuses rather than answering empty, because an empty listing and a listing the store cannot produce look identical to whoever is reading it.\",\n    docs: `${DOCS_BASE}#rc-5066`,\n    retryable: false,\n  },\n  RC9901: {\n    category: \"Runtime\",\n    message: \"Unknown error\",\n    suggestion: \"Check logs and enable debug level\",\n    docs: `${DOCS_BASE}#rc-9901`,\n    retryable: true, // Unknown - optimistic default\n  },\n};\n\nexport class RoutecraftError extends Error {\n  /**\n   * Whether this error should be retried by the retry wrapper.\n   */\n  public readonly retryable: boolean;\n\n  constructor(\n    public readonly rc: RCCode,\n    public readonly meta: RCMeta,\n    cause?: unknown,\n  ) {\n    super(meta.message, { cause });\n    this.name = \"RoutecraftError\";\n    this.retryable = meta.retryable;\n    setBrand(this, BRAND.RoutecraftError);\n  }\n\n  override toString(): string {\n    let result = `[${this.rc}] ${this.meta.message}`;\n    if (this.meta.suggestion) {\n      result += `\\nSuggestion, ${this.meta.suggestion}`;\n    }\n    result += `\\nDocs, ${this.meta.docs}`;\n    if (this.cause instanceof Error) {\n      result += `\\nCaused by: ${this.cause.message}`;\n      if (this.cause.stack) {\n        result += `\\nStack trace:\\n${this.cause.stack}`;\n      }\n    }\n    return result;\n  }\n\n  /**\n   * Used by pino and other serializers so log output includes rc, message, suggestion, docs, causeMessage, causeStack as searchable fields.\n   */\n  toJSON(): Record<string, unknown> {\n    const causeMessage =\n      this.cause instanceof Error\n        ? this.cause.message\n        : this.cause !== undefined\n          ? String(this.cause)\n          : undefined;\n    const causeStack =\n      this.cause instanceof Error ? this.cause.stack : undefined;\n    return {\n      type: \"RoutecraftError\",\n      name: this.name,\n      rc: this.rc,\n      message: this.meta.message,\n      suggestion: this.meta.suggestion,\n      docs: this.meta.docs,\n      causeMessage,\n      causeStack,\n      retryable: this.retryable,\n      stack: this.stack,\n    };\n  }\n\n  static parse(cause: unknown): { message: string; error: Error } {\n    return cause instanceof Error\n      ? { message: cause.message, error: cause }\n      : { message: String(cause), error: new Error(String(cause)) };\n  }\n}\n\n/**\n * Standard Schema issue shape (subset of StandardSchemaV1.Issue).\n * Used to format validation errors into human-readable messages.\n */\ninterface SchemaIssue {\n  readonly message: string;\n  readonly path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;\n}\n\n/**\n * Formats Standard Schema validation issues into a human-readable string.\n * Each issue becomes \"path: message\" (or just \"message\" when there is no path).\n *\n * @param issues - The raw issues value from a Standard Schema validation result\n * @returns A formatted string describing what failed\n *\n * @example\n * ```\n * formatSchemaIssues([{ message: \"Required\", path: [\"name\"] }])\n * // => '\"name\": Required'\n * ```\n */\nexport function formatSchemaIssues(issues: unknown): string {\n  if (!Array.isArray(issues) || issues.length === 0) {\n    return typeof issues === \"object\" ? JSON.stringify(issues) : String(issues);\n  }\n\n  return (issues as SchemaIssue[])\n    .map((issue) => {\n      const path = formatIssuePath(issue.path);\n      const msg = issue.message ?? \"unknown error\";\n      return path ? `\"${path}\": ${msg}` : msg;\n    })\n    .join(\"; \");\n}\n\n/**\n * Converts a Standard Schema path array into a dot-separated string.\n *\n * @internal\n */\nexport function formatIssuePath(\n  path: SchemaIssue[\"path\"] | undefined,\n): string | undefined {\n  if (!path || path.length === 0) return undefined;\n  return path\n    .map((segment) =>\n      typeof segment === \"object\" && segment !== null && \"key\" in segment\n        ? String(segment.key)\n        : String(segment),\n    )\n    .join(\".\");\n}\n\n/**\n * Creates a RoutecraftError with the given code and optional cause/overrides.\n *\n * @param rc - Error code from the RC registry (e.g. \"RC5001\", \"RC1002\")\n * @param cause - Optional underlying error (stored as cause, message can be overridden)\n * @param overrides - Optional overrides for message, suggestion, docs, or\n *   retryable (e.g. an adapter that knows a specific occurrence of a\n *   normally-permanent code is transient, or vice versa)\n * @returns A RoutecraftError instance (branded, with retryable from RC meta)\n *\n * @example\n * ```typescript\n * throw rcError(\"RC5002\", new Error(\"Invalid payload\"), { message: \"Validation failed\" });\n * ```\n */\nexport function rcError(\n  rc: RCCode,\n  cause?: unknown,\n  overrides?: Partial<\n    Pick<RCMeta, \"message\" | \"suggestion\" | \"docs\" | \"retryable\">\n  >,\n): RoutecraftError {\n  const base = getErrorMeta(rc);\n  const meta: RCMeta = {\n    ...base,\n    ...(overrides || {}),\n    docs: overrides?.docs ?? base.docs,\n  };\n  const parsed =\n    cause !== undefined ? RoutecraftError.parse(cause).error : undefined;\n  return new RoutecraftError(rc, meta, parsed);\n}\n\n/**\n * Cross-instance runtime registry of error codes (core + ecosystem) and\n * claimed namespaces. `Symbol.for` so multiple copies of the package in a\n * workspace share one registry, mirroring the config-applier registry.\n */\nconst ERROR_REGISTRY_KEY: unique symbol = Symbol.for(\n  \"routecraft.error-code-registry\",\n);\n\ntype ErrorRegistryState = {\n  codes: Map<string, RCMeta>;\n  /** namespace -> owner package name */\n  namespaces: Map<string, string>;\n};\n\ntype GlobalWithErrorRegistry = typeof globalThis & {\n  [ERROR_REGISTRY_KEY]?: ErrorRegistryState;\n};\n\nfunction getErrorRegistry(): ErrorRegistryState {\n  const g = globalThis as GlobalWithErrorRegistry;\n  let state = g[ERROR_REGISTRY_KEY];\n  if (!state) {\n    state = { codes: new Map(), namespaces: new Map() };\n    state.namespaces.set(\"RC\", \"@routecraft/routecraft\");\n    for (const [code, meta] of Object.entries(RC)) {\n      state.codes.set(code, meta);\n    }\n    g[ERROR_REGISTRY_KEY] = state;\n  }\n  return state;\n}\n\n/** Namespace shape: 2-8 chars, uppercase alphanumeric, starts with a letter. */\nconst NAMESPACE_PATTERN = /^[A-Z][A-Z0-9]{1,7}$/;\n\n/**\n * Register ecosystem error codes under a claimed namespace.\n *\n * Call once at module load time (typically from a side-effect import next\n * to the matching `declare module` augmentation of {@link ErrorCodeRegistry}).\n * Each namespace is claimable by exactly one owner package; a second claim\n * throws RC1003 naming both packages so consumers know which two packages\n * collide (they cannot fix the collision themselves). Re-registration by\n * the same owner is idempotent and replaces the previous codes, so module\n * re-evaluation (test runners, HMR) is safe.\n *\n * @param namespace - Unique uppercase prefix, e.g. \"AI\" (`RC` is reserved for core)\n * @param codes - Map of `${namespace}${4 digits}` codes to their metadata\n * @param owner - Owning package name, used in collision diagnostics\n *\n * @example\n * ```typescript\n * registerErrorCodes(\n *   \"AI\",\n *   { AI1001: { category: \"Adapter\", message: \"...\", docs: \"...\", retryable: false } },\n *   \"@routecraft/ai\",\n * );\n * ```\n */\nexport function registerErrorCodes(\n  namespace: string,\n  codes: Record<string, RCMeta>,\n  owner: string,\n): void {\n  if (!NAMESPACE_PATTERN.test(namespace)) {\n    throw rcError(\"RC1003\", undefined, {\n      message: `Error namespace \"${namespace}\" is invalid: must match ${String(NAMESPACE_PATTERN)}.`,\n    });\n  }\n  if (namespace === \"RC\") {\n    throw rcError(\"RC1003\", undefined, {\n      message: `Error namespace \"RC\" is reserved for @routecraft/routecraft core codes.`,\n    });\n  }\n  const state = getErrorRegistry();\n  const existingOwner = state.namespaces.get(namespace);\n  if (existingOwner !== undefined && existingOwner !== owner) {\n    throw rcError(\"RC1003\", undefined, {\n      message:\n        `Error namespace \"${namespace}\" is already claimed by \"${existingOwner}\" and cannot be claimed by \"${owner}\". ` +\n        `Two installed packages picked the same namespace; report this collision to both package owners.`,\n    });\n  }\n  const codePattern = new RegExp(`^${namespace}\\\\d{4}$`);\n  for (const code of Object.keys(codes)) {\n    if (!codePattern.test(code)) {\n      throw rcError(\"RC1003\", undefined, {\n        message: `Error code \"${code}\" does not match its namespace: expected \"${namespace}\" followed by exactly four digits.`,\n      });\n    }\n  }\n  state.namespaces.set(namespace, owner);\n  // Replace, not merge: drop codes from a previous registration so a\n  // same-owner re-registration (test runners, HMR) cannot leave stale\n  // codes behind.\n  for (const code of state.codes.keys()) {\n    if (codePattern.test(code)) {\n      state.codes.delete(code);\n    }\n  }\n  for (const [code, meta] of Object.entries(codes)) {\n    state.codes.set(code, meta);\n  }\n}\n\n/**\n * Look up the metadata for a code, or `undefined` when this process has\n * never registered it.\n *\n * A miss is a normal outcome rather than a fault: an ecosystem code is\n * registered by the package that defines it, and a reader's process is\n * often not the one that imported it. Callers that can degrade (a docs\n * link, a rendered hint) take this; callers for which a miss is a bug take\n * {@link getErrorMeta}.\n *\n * @internal\n */\nexport function findErrorMeta(rc: string): RCMeta | undefined {\n  return getErrorRegistry().codes.get(rc);\n}\n\n/**\n * Look up the metadata for a code in the runtime registry (core +\n * registered ecosystem codes). Throws RC9901 for unknown codes, which in\n * practice means the package that registers the code was never imported.\n *\n * @internal Exposed for docs tooling and conformance tests.\n */\nexport function getErrorMeta(rc: string): RCMeta {\n  const meta = findErrorMeta(rc);\n  if (!meta) {\n    throw new RoutecraftError(\n      \"RC9901\" as RCCode,\n      {\n        ...RC.RC9901,\n        message: `Unknown error code \"${rc}\". If this is an ecosystem code, import the package that registers it before use.`,\n      },\n      undefined,\n    );\n  }\n  return meta;\n}\n\n/**\n * Snapshot of all registered codes (core + ecosystem), for docs tooling\n * and conformance tests.\n *\n * @internal\n */\nexport function getRegisteredErrorCodes(): ReadonlyMap<string, RCMeta> {\n  return new Map(getErrorRegistry().codes);\n}\n","import { rcError } from \"../../error.ts\";\n\n/**\n * Dynamically load an optional peer dependency. If the package is not\n * installed, throw a Routecraft error (RC5017) that names the missing\n * package and the install command. Other failures (an installed package\n * that throws during initialisation, ESM/CJS interop bugs, native binding\n * crashes) are rethrown unchanged so the surface message is not a\n * misleading \"install &lt;pkg&gt;\" suggestion.\n *\n * Use this anywhere a driver is declared as an optional peer dependency,\n * not only in adapters: the deferral store and the telemetry SQLite sink\n * are neither adapters nor in an adapter directory, and both load one. Pass\n * a thunk like `() => import(\"croner\")` so the bundler sees the literal\n * package name and can keep it external.\n *\n * @param loader - Thunk that performs the dynamic `import(\"...\")` call.\n * @param ctx - Names used in the error message: the subsystem that wanted\n *              the package (`cron adapter`, `deferral store (sqlite)`,\n *              ...) and the missing package itself. `consumer` is used as\n *              written, so it carries its own noun.\n */\nexport function loadOptionalPeer<T>(\n  loader: () => Promise<T>,\n  ctx: { consumer: string; packageName: string },\n): Promise<T> {\n  // Use a sync .catch() chain (rather than `async/await`) so the caller's\n  // `await loadOptionalPeer(...)` only adds one microtask hop. Two hops\n  // tripped fake-timer based cron tests where advanceTimersByTimeAsync(0)\n  // only flushes a single cycle of microtasks.\n  return loader().catch((cause: unknown) => {\n    if (!isMissingExpectedPackage(cause, ctx.packageName)) {\n      // Either an unrelated error code, or `ERR_MODULE_NOT_FOUND` for a\n      // *different* package than the one we tried to load (i.e. the peer\n      // is installed but imports a missing transitive dep). Rethrow so\n      // the user sees the real failure rather than a misleading \"install\n      // <our peer>\" hint.\n      throw cause;\n    }\n    throw rcError(\"RC5017\", cause, {\n      message:\n        `${ctx.consumer} requires the optional peer dependency \"${ctx.packageName}\". ` +\n        `Install it: bun add ${ctx.packageName} (or npm install ${ctx.packageName}).`,\n    });\n  });\n}\n\nfunction isMissingExpectedPackage(\n  cause: unknown,\n  packageName: string,\n): boolean {\n  if (cause === null || typeof cause !== \"object\") return false;\n  const code = (cause as { code?: unknown }).code;\n  if (code !== \"ERR_MODULE_NOT_FOUND\" && code !== \"MODULE_NOT_FOUND\") {\n    return false;\n  }\n  const message = (cause as { message?: unknown }).message;\n  if (typeof message !== \"string\") return false;\n  // Phrasings observed in the wild:\n  //   Node ESM:  `Cannot find package 'pkg' imported from /path`\n  //   CJS:       `Cannot find module 'pkg'`\n  //   Bun:       `Cannot find module 'pkg/subpath' from '/path'`\n  // Node names the package even when the import used a subpath; Bun quotes the\n  // full specifier. Accept the quoted name with an optional subpath suffix so a\n  // subpath loader (`pkg/stdio`) still yields RC5017 on Bun instead of a raw\n  // ERR_MODULE_NOT_FOUND. The quote-or-slash boundary keeps this from matching\n  // a longer package name that merely starts with the same characters, and the\n  // opening quote keeps a transitive-dep miss inside the same package from\n  // being mistaken for the peer itself. The resolved-path phrasing\n  // (`Cannot find module '/abs/path/pkg/index.js'`) is deliberately NOT\n  // matched: it means the package resolved but its entry file is missing,\n  // which is a broken install rather than an absent peer, and an install hint\n  // would send the user down the wrong path.\n  // Every occurrence is examined, not just the first: a message may quote a\n  // longer name sharing our prefix before it quotes ours (`'@scope/pkg-extra'`\n  // ahead of `'@scope/pkg'`), and stopping at the first hit would fail the\n  // boundary check against the wrong one and degrade RC5017 into a raw\n  // ERR_MODULE_NOT_FOUND.\n  return QUOTES.some((quote) => {\n    const needle = `${quote}${packageName}`;\n    for (\n      let start = message.indexOf(needle);\n      start !== -1;\n      start = message.indexOf(needle, start + 1)\n    ) {\n      const next = message[start + needle.length];\n      if (next === quote || next === \"/\") return true;\n    }\n    return false;\n  });\n}\n\n/** Quote characters a runtime may wrap a specifier in. */\nconst QUOTES = [\"'\", '\"'] as const;\n","import { createRequire } from \"node:module\";\nimport { mkdirSync, openSync, existsSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, resolve, isAbsolute, basename } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { pino, stdSerializers } from \"pino\";\nimport type { Route } from \"./route.ts\";\nimport { type Exchange, getExchangeContext, HeadersKeys } from \"./exchange.ts\";\nimport { isCraftContext, isRoute, isExchange } from \"./brand.ts\";\nimport type { CraftContext } from \"./context.ts\";\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Serialize a logged error, collapsing a cause that only repeats the message.\n *\n * pino appends a cause's message to the error's own, which is what you want\n * when they differ: \"Adapter operation failed: the socket closed\" says more\n * than either half. The framework routinely makes them identical, because\n * `processError` wraps an arbitrary throw as `RC5001` and takes the thrown\n * message as its own while keeping the original as the cause for its stack.\n * The reader then gets the same sentence twice, joined by a colon, on every\n * adapter failure and on the longest messages worst:\n *\n *     \"The socket connection was closed unexpectedly...: The socket\n *      connection was closed unexpectedly...\"\n *\n * Only the exact duplicate is collapsed. A cause that says something the\n * error does not is still appended, and nothing here changes any error's own\n * `message`, which is what the rest of the framework reads.\n *\n * @internal Exported for tests.\n */\nexport function serializeError(error: unknown): unknown {\n  const serialized = stdSerializers.err(\n    error as Parameters<typeof stdSerializers.err>[0],\n  );\n  const cause: unknown = (error as { cause?: unknown }).cause;\n  if (!(cause instanceof Error)) return serialized;\n  if (serialized.message === `${cause.message}: ${cause.message}`) {\n    serialized.message = cause.message;\n  }\n  return serialized;\n}\n\n/** Pino options shape we support from config files; env overrides applied on top. */\ntype PinoOptionsLike = {\n  level?: string;\n  redact?: string[];\n  [key: string]: unknown;\n};\n\n/**\n * Load config from first existing file: cwd/craft.log.{cjs,js}, then ~/.routecraft/craft.log.{cjs,js}.\n * Returns plain object; never throws (returns {} if no file or invalid).\n */\nfunction loadConfigFile(): PinoOptionsLike {\n  const cwd = process.cwd();\n  const home = homedir();\n  const dirs = [cwd, resolve(home, \".routecraft\")];\n  const names = [\"craft.log.cjs\", \"craft.log.js\"];\n  for (const dir of dirs) {\n    for (const name of names) {\n      const path = resolve(dir, name);\n      if (existsSync(path)) {\n        try {\n          const mod = require(path);\n          const config = mod?.default ?? mod;\n          if (config && typeof config === \"object\") {\n            return { ...config };\n          }\n        } catch {\n          // ignore invalid or missing export\n        }\n      }\n    }\n  }\n  return {};\n}\n\n/**\n * A log file the logger was asked for and could not open. Read by the CLI,\n * which owns the setting and refuses to run with its logs diverted.\n *\n * @internal\n */\nexport interface LogFileDiversion {\n  /** The file as it was named. */\n  path: string;\n  /** Where the name came from. */\n  source: \"LOG_FILE\" | \"CRAFT_LOG_FILE\" | \"craft.log\";\n  /** Why it could not be opened for appending. */\n  reason: string;\n}\n\nlet diversion: LogFileDiversion | undefined;\n\n/**\n * The log file the logger could not open, if it was asked for one.\n *\n * The logger never fails over its destination: an embedding application\n * cannot be stopped by its logger, so a file that cannot be opened diverts\n * the logs to a file of the same name in the temporary directory, then to\n * standard error. A host that owns the setting reads this to refuse instead.\n *\n * @internal\n */\nexport function logFileDiversion(): LogFileDiversion | undefined {\n  return diversion;\n}\n\n/**\n * Resolve destination stream. ENV wins, then config file, then stdout.\n * Aligns with pino's default and 12-factor. Adapters that own stdout\n * (e.g. MCP stdio) must redirect logs via --log-file or --log-level silent.\n */\nfunction getDestination(fileConfig?: string): NodeJS.WritableStream {\n  const pinoDest = pino as unknown as {\n    destination: (pathOrFd: string | number) => NodeJS.WritableStream;\n  };\n  const source =\n    process.env[\"LOG_FILE\"] !== undefined\n      ? \"LOG_FILE\"\n      : process.env[\"CRAFT_LOG_FILE\"] !== undefined\n        ? \"CRAFT_LOG_FILE\"\n        : \"craft.log\";\n  const logFile =\n    process.env[\"LOG_FILE\"] ?? process.env[\"CRAFT_LOG_FILE\"] ?? fileConfig;\n  if (logFile) {\n    const resolved = isAbsolute(logFile)\n      ? logFile\n      : resolve(process.cwd(), logFile);\n    try {\n      mkdirSync(dirname(resolved), { recursive: true });\n      const fd = openSync(resolved, \"a\");\n      return pinoDest.destination(fd);\n    } catch (error: unknown) {\n      diversion = {\n        path: logFile,\n        source,\n        reason: error instanceof Error ? error.message : String(error),\n      };\n      try {\n        const pathToUse = resolve(tmpdir(), basename(logFile));\n        const fd = openSync(pathToUse, \"a\");\n        return pinoDest.destination(fd);\n      } catch {\n        // User asked for \"not stdout\" via --log-file; honour that even when\n        // both file paths fail. Fall back to stderr rather than violating the\n        // flag's contract (e.g. corrupting an MCP stdio protocol stream).\n        return pinoDest.destination(2);\n      }\n    }\n  }\n  return pinoDest.destination(1);\n}\n\n/** Options object accepted by pino() */\ntype PinoOptions = Parameters<typeof pino>[0];\n\n/**\n * Use pretty (pino-pretty) when NODE_ENV is not production and we're writing to stdout.\n * Override with PINO_PRETTY=1 to force pretty; set LOG_FILE to get JSON (e.g. for MCP).\n */\nfunction usePrettyOutput(filePath?: string): boolean {\n  const hasLogFile =\n    process.env[\"LOG_FILE\"] ?? process.env[\"CRAFT_LOG_FILE\"] ?? filePath;\n  if (hasLogFile) return false;\n  const nodeEnv = process.env[\"NODE_ENV\"];\n  if (nodeEnv === \"production\") return false;\n  const explicit =\n    process.env[\"PINO_PRETTY\"] === \"1\" || process.env[\"PINO_PRETTY\"] === \"true\";\n  return nodeEnv === \"development\" || !nodeEnv || explicit;\n}\n\n/**\n * Resolve final pino options: config file base, then env overrides (env always wins).\n */\nfunction resolveConfig(): {\n  options: PinoOptions;\n  destination: NodeJS.WritableStream | undefined;\n} {\n  const fromFile = loadConfigFile();\n  const level =\n    process.env[\"LOG_LEVEL\"] ??\n    process.env[\"CRAFT_LOG_LEVEL\"] ??\n    fromFile.level ??\n    \"warn\";\n  const redactEnv =\n    process.env[\"LOG_REDACT\"] ?? process.env[\"CRAFT_LOG_REDACT\"];\n  const redact = redactEnv\n    ? redactEnv\n        .split(\",\")\n        .map((s) => s.trim())\n        .filter(Boolean)\n    : fromFile.redact;\n  const filePath =\n    typeof fromFile[\"file\"] === \"string\" ? fromFile[\"file\"] : undefined;\n  const usePretty = usePrettyOutput(filePath);\n  const destination = usePretty ? undefined : getDestination(filePath);\n\n  const options: PinoOptions = {\n    ...fromFile,\n    level,\n    formatters: {\n      level(label: string) {\n        return { level: label };\n      },\n    },\n    serializers: { err: serializeError },\n    ...(redact && redact.length > 0 ? { redact } : {}),\n    ...(usePretty\n      ? {\n          transport: {\n            target: \"pino-pretty\",\n            options: { colorize: true },\n          },\n        }\n      : {}),\n  };\n\n  return { options, destination };\n}\n\nconst { options, destination } = resolveConfig();\n/**\n * Framework-level pino logger instance. Configured via craft.log.{cjs,js} or environment variables.\n */\nexport const logger =\n  destination !== undefined ? pino(options, destination) : pino(options);\n\n/**\n * Returns pino child logger bindings for the given context so logs include contextId, route, exchangeId, etc.\n *\n * @param context - CraftContext, Route, or Exchange instance\n * @returns Object of key-value bindings (e.g. { contextId, route, correlationId, exchangeId })\n *\n * @example\n * ```typescript\n * const child = logger.child(childBindings(exchange));\n * child.info({ extra: 1 }, 'Processing');\n * ```\n */\nexport function childBindings(\n  context: CraftContext | Route | Exchange,\n): Record<string, unknown> {\n  if (isCraftContext(context)) {\n    const ctx = context as CraftContext;\n    const bindings: Record<string, unknown> = { contextId: ctx.contextId };\n    if (ctx.name !== undefined) bindings[\"service.name\"] = ctx.name;\n    return bindings;\n  }\n  if (isRoute(context)) {\n    const route = context as Route;\n    const bindings: Record<string, unknown> = {\n      contextId: route.context.contextId,\n      route: route.definition.id,\n    };\n    if (route.context.name !== undefined)\n      bindings[\"service.name\"] = route.context.name;\n    return bindings;\n  }\n  if (isExchange(context)) {\n    const ex = context as Exchange;\n    const ctx = getExchangeContext(ex);\n    if (ctx) {\n      const bindings: Record<string, unknown> = {\n        contextId: ctx.contextId,\n        route: ex.headers[HeadersKeys.ROUTE_ID],\n        correlationId: ex.headers[HeadersKeys.CORRELATION_ID],\n        exchangeId: ex.id,\n      };\n\n      if (ctx.name !== undefined) bindings[\"service.name\"] = ctx.name;\n\n      // Include non-PII auth identifiers from the principal when present.\n      // Only subject and issuer are safe for logs; fields like email,\n      // name, and roles are omitted to avoid leaking PII.\n      const principal = ex.principal;\n      if (principal?.subject !== undefined)\n        bindings[\"auth.subject\"] = principal.subject;\n      if (principal?.issuer !== undefined)\n        bindings[\"auth.issuer\"] = principal.issuer;\n\n      return bindings;\n    }\n  }\n  return {};\n}\n","import type { DeferralRuntime } from \"./config.ts\";\n\n/**\n * Context-store key holding the resolved deferral runtime.\n *\n * Exported so the executor, the resume path, and the sweeper reach one\n * resolved store and one signer per context rather than each building their\n * own.\n *\n * It lives in this leaf module rather than next to\n * {@link createDeferralRuntime} because `exchange.ts` reads the key to\n * build the `ex.deferral` affordance, and importing `config.ts` from\n * there would pull the store backends (and, through them, the context) into\n * a runtime cycle rooted at the exchange. The type-only import above is\n * erased, so this module has no runtime dependencies at all.\n */\nexport const DEFERRAL_RUNTIME = \"routecraft.deferral.runtime\" as const;\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [DEFERRAL_RUNTIME]: DeferralRuntime;\n  }\n}\n","import { createHmac, randomBytes } from \"node:crypto\";\nimport { rcError } from \"../error.ts\";\nimport { timingSafeStringEqual } from \"../auth/timing-safe.ts\";\n\n/**\n * Environment variable read for the resume-token signing secret when the\n * context does not configure one explicitly.\n */\nexport const DEFERRAL_SECRET_ENV = \"ROUTECRAFT_DEFERRAL_SECRET\";\n\n/** Token format version, so a future format change is detectable rather than silent. */\nconst TOKEN_VERSION = 1;\n\n/**\n * A signed capability naming one deferral.\n *\n * The token proves that whoever holds it was handed it by this deployment.\n * It does NOT prove the holder may resume: authorizing the resuming\n * principal is the resume ingress route's job (`.resume({ authorize })`,\n * sender verification, a per-recipient link), which is where an\n * authenticated principal is available. Nor does the token enforce single use on its own; the store's\n * compare-and-swap does that, so a replayed token finds the deferral\n * already resumed and gets the cached continuation result instead of a second\n * execution.\n */\nexport interface ResumeTokenPayload {\n  /** Deferral this token resumes. */\n  readonly id: string;\n  /** Mint time, epoch milliseconds. Carried for audit, not enforced. */\n  readonly iat: number;\n  /**\n   * The call this credential belongs to, when the deferring step can raise\n   * more than one at a time.\n   *\n   * A deferral id names a RECORD; on the agent surface a single record is\n   * reached through whichever tool call won a parallel batch, and every\n   * handler in that batch is handed a credential before the winner is\n   * known. Binding the credential to its own call is what stops the loser's\n   * recipient from resuming the winner's deferral: revive compares this claim\n   * against the record's own `stepState.deferredToolCallId` and refuses a\n   * mismatch before touching the record.\n   *\n   * Absent for a static `.defer()`, which has exactly one logical call.\n   * Both mismatched arms fail closed: a token without this claim cannot\n   * resume a record that has a bound call, and a token carrying it cannot\n   * resume a record that has none.\n   */\n  readonly sub?: string;\n}\n\n/**\n * Mints and verifies resume tokens for one context.\n *\n * HMAC-SHA256 over a compact JSON payload, encoded base64url so a token\n * survives a URL, an email body, and a chat message without escaping.\n */\nexport class ResumeTokenSigner {\n  readonly #secret: Buffer;\n\n  /**\n   * How the secret was obtained. Surfaced so the context can log it once at\n   * startup: an operator seeing `ephemeral` in production has a\n   * misconfiguration, and that is worth being able to spot.\n   */\n  readonly source: SigningSecretSource;\n\n  constructor(secret: string | Buffer, source: SigningSecretSource) {\n    this.#secret =\n      typeof secret === \"string\" ? Buffer.from(secret, \"utf8\") : secret;\n    this.source = source;\n  }\n\n  /**\n   * Mint a token for a deferral id.\n   *\n   * Callable BEFORE the deferring step runs, which is what lets a\n   * notification step earlier in the pipeline put a working resume link in\n   * the message it sends. Nothing about the deferred exchange is needed to\n   * sign: the deferral id is derivable from the exchange (see\n   * {@link deferralIdFor}), and the token carries no claims of its own.\n   *\n   * @param id - The deferral id this token will resume.\n   * @param now - Mint timestamp, injectable for deterministic tests.\n   * @param sub - The call this credential belongs to, when the deferring\n   *   step can raise several at once. See {@link ResumeTokenPayload.sub}.\n   */\n  mint(id: string, now: Date = new Date(), sub?: string): string {\n    // `verify` refuses a zero-length `sub`, so minting one would produce a\n    // credential that provably never verifies and then reports itself as a\n    // forgery (`RC5041`), pointing at the holder rather than at the call\n    // site that asked for a binding it did not have.\n    if (sub !== undefined && sub.length === 0) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"Cannot mint a resume token bound to an empty call binding: the binding must name the call this credential belongs to.\",\n      });\n    }\n    const payload: ResumeTokenPayload = {\n      id,\n      iat: now.getTime(),\n      ...(sub !== undefined ? { sub } : {}),\n    };\n    const body = encode(JSON.stringify({ v: TOKEN_VERSION, ...payload }));\n    return `${body}.${this.#sign(body)}`;\n  }\n\n  /**\n   * Verify a token and return what it names.\n   *\n   * @param token - The token as presented by the resume ingress.\n   * @returns The verified payload.\n   * @throws RC5041 when the token is malformed, carries an unknown format\n   *   version, or fails signature verification. The three are deliberately\n   *   one error: telling a caller which of them failed tells an attacker\n   *   how far a forgery got.\n   */\n  verify(token: string): ResumeTokenPayload {\n    const separator = token.lastIndexOf(\".\");\n    if (separator <= 0) throw reject();\n    const body = token.slice(0, separator);\n    const signature = token.slice(separator + 1);\n\n    if (!timingSafeStringEqual(this.#sign(body), signature)) throw reject();\n\n    let parsed: unknown;\n    try {\n      parsed = JSON.parse(Buffer.from(body, \"base64url\").toString(\"utf8\"));\n    } catch {\n      throw reject();\n    }\n    // `JSON.parse(\"null\")` yields null, whose property read would escape as a\n    // TypeError rather than the RC5041 this method's contract promises.\n    if (parsed === null || typeof parsed !== \"object\") throw reject();\n    const claims = parsed as {\n      v?: unknown;\n      id?: unknown;\n      iat?: unknown;\n      sub?: unknown;\n    };\n    if (\n      claims.v !== TOKEN_VERSION ||\n      typeof claims.id !== \"string\" ||\n      claims.id.length === 0 ||\n      typeof claims.iat !== \"number\" ||\n      (claims.sub !== undefined &&\n        (typeof claims.sub !== \"string\" || claims.sub.length === 0))\n    ) {\n      throw reject();\n    }\n    return {\n      id: claims.id,\n      iat: claims.iat,\n      ...(typeof claims.sub === \"string\" ? { sub: claims.sub } : {}),\n    };\n  }\n\n  #sign(body: string): string {\n    return createHmac(\"sha256\", this.#secret)\n      .update(body, \"utf8\")\n      .digest(\"base64url\");\n  }\n}\n\n/** Where a context's signing secret came from. */\nexport type SigningSecretSource = \"config\" | \"env\" | \"ephemeral\";\n\n/**\n * Separator between the exchange id and the sequence number.\n *\n * Unreserved in RFC 3986, chosen so the framework's own contribution to the\n * id needs no escaping. `#` would have started a fragment and truncated the\n * id at its first hop through a browser.\n *\n * This does NOT make a deferral id URL-safe on its own: the exchange id it\n * wraps is opaque, and an adapter is free to set `headers[\"routecraft.id\"]`\n * from an upstream message id containing anything at all. A deferral id is\n * an identifier, not a URL component; whoever embeds one in a resume link\n * percent-encodes it there.\n */\nconst DEFERRAL_ID_SEPARATOR = \"~\";\n\n/**\n * Derive the id of a deferral from the exchange that will defer.\n *\n * Deterministic on purpose: `ex.deferral.token` and\n * `ex.deferral.resumeUrl` must be readable by a notification step that\n * runs BEFORE the defer, so the id cannot be minted by the defer step\n * itself. The exchange id is the natural key, and `sequence` distinguishes\n * successive defers of the same exchange, which happens whenever a route\n * defers, resumes, and defers again for a second approval.\n *\n * The sequence is always appended, including for the first deferral. Omitting it\n * at zero looks tidier and collides: an exchange whose id already ends in\n * `~1` (ids are `randomUUID()` by default but an adapter may set\n * `headers[\"routecraft.id\"]` from an upstream message id) would produce the\n * same deferral id as that exchange's second deferral. Two unrelated deferred\n * exchanges sharing an id means one overwrites the other in the store.\n * Appending unconditionally is injective, because the suffix is a canonical\n * decimal after the final separator.\n *\n * @param exchangeId - The deferring exchange's id.\n * @param sequence - How many times this exchange has already deferred.\n *\n * @internal\n */\nexport function deferralIdFor(exchangeId: string, sequence: number): string {\n  return `${exchangeId}${DEFERRAL_ID_SEPARATOR}${sequence}`;\n}\n\n/**\n * Options accepted by {@link resolveSigningSecret}.\n */\nexport interface SigningSecretOptions {\n  /** Secret supplied directly on `deferral: { secret }`. */\n  secret?: string | undefined;\n  /** Environment to read, injectable for tests. Defaults to `process.env`. */\n  env?: Record<string, string | undefined>;\n  /**\n   * Allow minting an ephemeral in-memory key when nothing is configured.\n   * Set by `testContext()` and by development mode. Never set in\n   * production: an ephemeral key means every resume token becomes\n   * unverifiable the moment the process restarts, which is precisely the\n   * restart the feature exists to survive.\n   */\n  allowEphemeral?: boolean;\n}\n\n/**\n * Resolve the resume-token signing secret for a context.\n *\n * Configuration order is explicit value, then environment, then (only when\n * permitted) an ephemeral key. There is deliberately no fourth option: the\n * secret is never generated INTO the store, because a store compromise must\n * not also yield the ability to forge resume tokens, and because a\n * store-resident key stops working the moment a second node appears.\n *\n * @throws RC5040 when no secret is configured and ephemeral keys are not\n *   permitted. Raised while the context is being built, not on the first\n *   defer, so a missing secret is a startup failure rather than a\n *   production surprise on the first large payout.\n *\n * @internal\n */\nexport function resolveSigningSecret(\n  options: SigningSecretOptions = {},\n): ResumeTokenSigner {\n  const configured = options.secret?.trim();\n  if (configured) {\n    return new ResumeTokenSigner(assertStrong(configured, \"config\"), \"config\");\n  }\n\n  const fromEnv = (options.env ?? process.env)[DEFERRAL_SECRET_ENV]?.trim();\n  if (fromEnv) {\n    return new ResumeTokenSigner(assertStrong(fromEnv, \"env\"), \"env\");\n  }\n\n  if (options.allowEphemeral) {\n    return new ResumeTokenSigner(randomBytes(32), \"ephemeral\");\n  }\n\n  throw rcError(\"RC5040\", undefined, {\n    message: `No resume-token signing secret is configured. Set ${DEFERRAL_SECRET_ENV}, or pass deferral: { secret } to defineConfig.`,\n  });\n}\n\n/**\n * Minimum signing-secret length, in bytes.\n *\n * A resume token is a bearer capability, and any holder of one token has an\n * offline oracle: body plus HMAC, unlimited guesses, nothing to rate limit.\n * A dictionary-strength secret falls in seconds, after which an attacker\n * mints a token for any deferral id, and ids are derived from the exchange\n * id rather than being a second secret. 32 bytes is the SHA-256 digest\n * size, which RFC 2104 gives as the recommended minimum HMAC key length.\n */\nconst MIN_SECRET_BYTES = 32;\n\n/**\n * Reject a secret too weak to resist offline guessing, at resolution time\n * where the failure is already a startup error rather than a runtime one.\n *\n * @internal\n */\nfunction assertStrong(secret: string, source: string): string {\n  const bytes = Buffer.byteLength(secret, \"utf8\");\n  if (bytes < MIN_SECRET_BYTES) {\n    throw rcError(\"RC5040\", undefined, {\n      message: `The resume-token signing secret from ${source} is ${bytes} bytes; at least ${MIN_SECRET_BYTES} are required. Generate one with: openssl rand -base64 32`,\n    });\n  }\n  return secret;\n}\n\n/** @internal */\nfunction encode(value: string): string {\n  return Buffer.from(value, \"utf8\").toString(\"base64url\");\n}\n\n/** @internal */\nfunction reject(): Error {\n  return rcError(\"RC5041\", undefined, {\n    message: \"Resume token rejected: malformed or signature mismatch.\",\n  });\n}\n","import type { CraftContext } from \"../context.ts\";\nimport type { ExchangeHeaders } from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { DEFERRAL_RUNTIME } from \"./runtime-key.ts\";\nimport { deferralIdFor } from \"./tokens.ts\";\nimport type { PrincipalRef } from \"./types.ts\";\n\n/**\n * Deferral state carried on the exchange.\n *\n * Per `.standards/exchange-state-model.md`, everything that must survive a\n * deferral lives in `headers`; `ex.deferral` is a derivation over these keys\n * plus the context's signer, in the same shape as `ex.principal` and\n * `ex.logger`. Nothing here is a second per-exchange bag.\n */\nexport const DeferralHeaders = {\n  /**\n   * How many times this exchange has already deferred. Distinguishes\n   * successive deferrals of one exchange (a route that defers, resumes,\n   * and defers again for a second approval), which is what keeps their\n   * deferral ids distinct.\n   */\n  SEQUENCE: \"routecraft.deferral.sequence\",\n  /**\n   * Id of the exchange a snapshot was taken of, set when the framework\n   * clones an exchange (`.tap()`, `.multicast()`). A clone gets a fresh\n   * `routecraft.id` by design, so without this a token minted inside a\n   * `.tap()` notification would name a deferral that never exists. The\n   * canonical \"notify before deferring\" step is exactly such a tap, so the affordance follows this key back to the exchange that will\n   * actually defers.\n   */\n  OWNER: \"routecraft.deferral.owner\",\n  /** The validated resume payload, written by the resume path before the continuation runs. */\n  RESULT: \"routecraft.deferral.result\",\n  /** Who resumed it, recorded for audit. */\n  RESUMED_BY: \"routecraft.deferral.resumedBy\",\n  /** When the resume was accepted. */\n  RESUMED_AT: \"routecraft.deferral.resumedAt\",\n} as const satisfies Record<string, string>;\n\ndeclare module \"@routecraft/routecraft\" {\n  interface RoutecraftHeaders {\n    \"routecraft.deferral.sequence\"?: number;\n    \"routecraft.deferral.owner\"?: string;\n    \"routecraft.deferral.result\"?: unknown;\n    \"routecraft.deferral.resumedBy\"?: PrincipalRef;\n    \"routecraft.deferral.resumedAt\"?: Date;\n  }\n}\n\n/**\n * The `ex.deferral` affordance.\n *\n * Readable at any point in a pipeline, which is the whole point: `id` and\n * `token` are derived from the exchange rather than minted by the defer\n * step, so a notification step that runs BEFORE the `.defer()` can put a\n * working resume link in the message it sends (n8n's `$execution.resumeUrl`\n * has the same property).\n *\n * `result`, `resumedBy` and `resumedAt` are the other half: they are absent\n * on execution one and populated by the resume path before the continuation\n * runs. `result` is typed `unknown` here and narrowed by the builder, which\n * threads the `schema` option's output type into every step after the\n * `.defer()`, the way `.input()` types the body.\n *\n * @template R - The resume payload type, threaded in by `.defer({ schema })`\n */\nexport interface DeferralAffordance<R = unknown> {\n  /** Id of the deferral this exchange would defer as (or deferred as). */\n  readonly id: string;\n  /** How many times this exchange has already deferred. Zero before the first defer. */\n  readonly sequence: number;\n  /**\n   * Signed, single-use resume token for {@link DeferralAffordance.id}.\n   *\n   * @throws RC5052 when the context has no deferral runtime configured.\n   */\n  readonly token: string;\n  /**\n   * A resume token bound to one specific call on this record.\n   *\n   * Only a step that can raise several calls against one deferral needs this:\n   * the agent tier's parallel tool batch is the shipped case, where every\n   * handler sees the same deferral id (it names the deferral, not the call)\n   * and each sends its own recipient a link. Binding the credential to the\n   * call means the handler that then LOSES the deferral cannot have its\n   * recipient resume the winner's deferral; they take `RC5055` instead.\n   *\n   * The binding is checked against what the record actually deferred with, so\n   * minting one here without the deferral recording the same value refuses\n   * every resume. Plain `.defer()` sites use {@link\n   * DeferralAffordance.token}.\n   *\n   * @throws RC5052 when the context has no deferral runtime configured.\n   */\n  readonly tokenFor: (callBinding: string) => string;\n  /** The validated resume payload. Present only after a resume. */\n  readonly result: R;\n  /** Who resumed it. Present only after a resume, and only when the ingress route had a principal. */\n  readonly resumedBy: PrincipalRef | undefined;\n  /** When the resume was accepted. Present only after a resume. */\n  readonly resumedAt: Date | undefined;\n}\n\n/**\n * Build the `ex.deferral` view.\n *\n * Takes the context and headers rather than the exchange so this module has\n * no runtime dependency on `exchange.ts`, which imports it back. `token` is\n * a getter because minting reaches into the context store, and the common\n * case (a route that never reads it) should not pay for that.\n *\n * @param context - Context the exchange belongs to, when it has one\n * @param headers - The exchange's headers\n * @param exchangeId - The exchange's id, which seeds the deferral id\n *   unless the exchange is a snapshot of another (see\n *   {@link DeferralHeaders.OWNER})\n *\n * @internal\n */\nexport function deferralAffordance(\n  context: CraftContext | undefined,\n  headers: ExchangeHeaders,\n  exchangeId: string,\n  floor?: number,\n): DeferralAffordance {\n  const sequence = effectiveSequence(headers, floor);\n  const id = deferralIdOf(headers, exchangeId, floor);\n  const mint = (callBinding?: string): string => {\n    const runtime = context?.getStore(DEFERRAL_RUNTIME);\n    if (!runtime) {\n      throw rcError(\"RC5052\", undefined, {\n        message:\n          \"Cannot mint a resume token: this context has no deferral runtime. Add deferral: {} to defineConfig.\",\n      });\n    }\n    return runtime.signer.mint(id, new Date(), callBinding);\n  };\n  return {\n    id,\n    sequence,\n    get token(): string {\n      return mint();\n    },\n    // Checked rather than left to the type: the whole point of this member\n    // is that the credential names a call, and an untyped caller reaching it\n    // through a loosely typed boundary must not be able to get an unbound\n    // one from it. Silently minting one would produce a link that refuses\n    // every resume with RC5055, pointing at the holder rather than at the\n    // call site that asked for a binding it did not have.\n    tokenFor: (callBinding: string): string => {\n      if (typeof callBinding !== \"string\") {\n        throw rcError(\"RC5003\", undefined, {\n          message:\n            \"ex.deferral.tokenFor(callBinding) requires the call binding as a string. Use ex.deferral.token for an unbound resume token.\",\n        });\n      }\n      return mint(callBinding);\n    },\n    result: headers[DeferralHeaders.RESULT],\n    resumedBy: headers[DeferralHeaders.RESUMED_BY],\n    resumedAt: headers[DeferralHeaders.RESUMED_AT],\n  };\n}\n\n/**\n * The deferral id an exchange defers as.\n *\n * The one derivation, called by the `ex.deferral` affordance and by the\n * deferral path alike. They must agree: the affordance is what a notification\n * step mints a token from BEFORE the deferral, and the deferral is what writes the\n * record that token has to find. Deriving it twice let them diverge for any\n * exchange carrying an owner header, which is every exchange a `.debounce()`\n * releases downstream, and the symptom was a resume link that verified and\n * then found nothing.\n *\n * @param headers - The exchange's headers\n * @param exchangeId - The exchange's own id, used when it is not a snapshot\n *\n * @internal\n */\nexport function deferralIdOf(\n  headers: ExchangeHeaders,\n  exchangeId: string,\n  floor?: number,\n): string {\n  return deferralIdFor(\n    headers[DeferralHeaders.OWNER] ?? exchangeId,\n    effectiveSequence(headers, floor),\n  );\n}\n\n/**\n * The sequence a deferral derives its id from: the header's, unless an aside\n * deferral in this run already advanced past it (`asideSequenceOf`), which\n * the live exchange's frozen headers cannot carry.\n *\n * @internal\n */\nexport function effectiveSequence(\n  headers: ExchangeHeaders,\n  floor: number | undefined,\n): number {\n  const fromHeader = readSequence(headers);\n  return floor !== undefined && floor > fromHeader ? floor : fromHeader;\n}\n\n/**\n * Read the deferral counter off an exchange's headers.\n *\n * A missing header is the counter at zero: every exchange that has never\n * deferred legitimately carries none. Anything else that is not a usable\n * counter value REFUSES rather than resetting, because the deferral id\n * derives from this counter and resume tokens sign the id: a reset counter\n * re-derives an id an earlier deferral of the same owner already used, and an\n * old unspent link would verify against the new deferral. The store's\n * create-collision check backstops the case where the earlier record still\n * exists; this refusal closes the silent path around it.\n *\n * The throw only ever reaches deferral surfaces (`ex.deferral` is a\n * lazy getter, and the deferral calls this on the way in), so an exchange with\n * a mangled header still flows through routes that never touch deferral.\n *\n * @throws RC5057 when the header holds a malformed value, or a value at or\n *   above the exhaustion bound (`MAX_SAFE_INTEGER - 1`). The bound sits one\n *   below the safe-integer ceiling so every accepted value has a writable\n *   successor; that successor may be the bound itself, in which case\n *   exhaustion surfaces loudly on the read after the final deferral rather\n *   than as the reset this function exists to refuse\n *\n * @internal\n */\nexport function readSequence(headers: ExchangeHeaders): number {\n  const raw = headers[DeferralHeaders.SEQUENCE];\n  if (raw === undefined) return 0;\n  if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw < 0) {\n    throw rcError(\"RC5057\", undefined, {\n      message: `The deferral sequence header (\"${DeferralHeaders.SEQUENCE}\") is malformed: expected a non-negative safe integer, found ${JSON.stringify(raw)}. Refusing to derive a deferral id from it, because a reset counter reuses an id an earlier deferral already used.`,\n    });\n  }\n  if (raw >= Number.MAX_SAFE_INTEGER - 1) {\n    throw rcError(\"RC5057\", undefined, {\n      message: `The deferral sequence header (\"${DeferralHeaders.SEQUENCE}\") is exhausted at ${raw}: the counter refuses before it can store a value whose own increment would leave the safe-integer range. This value is not reachable by deferring in a loop; treat it as corruption of the framework-owned header.`,\n    });\n  }\n  return raw;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { INTERNALS_KEY, BRAND, setBrand, setInternals } from \"./brand.ts\";\n// `import type` (not `import { type }`): under verbatimModuleSyntax the\n// braced form keeps a runtime side-effect import, which closes the module\n// cycle exchange -> context -> route -> wrapper -> exchange and leaves\n// OperationType uninitialised for ESM loaders that evaluate the cycle in\n// that order (vite/vitest; bun's loader happens to tolerate it).\nimport type { CraftContext } from \"./context.ts\";\nimport { logger, childBindings } from \"./logger.ts\";\nimport type { Route } from \"./route.ts\";\nimport type { OnParseError } from \"./adapters/shared/parse.ts\";\nimport type { Principal } from \"./auth/types.ts\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport {\n  type DeferralAffordance,\n  DeferralHeaders,\n  deferralAffordance,\n} from \"./deferral/exchange-state.ts\";\n\n/**\n * Local alias so the clone path reads at a glance. See\n * {@link DeferralHeaders.OWNER}.\n */\nconst DEFERRAL_OWNER_HEADER = DeferralHeaders.OWNER;\n\n/**\n * Types of operations that can be performed on an exchange.\n * These values are used in exchange headers to track the current operation.\n */\nexport enum OperationType {\n  /** The exchange was created from a source */\n  FROM = \"from\",\n  /**\n   * Synthetic step inserted by the runtime when a source adapter attaches a\n   * `parse` function to the queued message. Builds a derived exchange via\n   * `DefaultExchange.rewrap(exchange, { body: await parse(exchange.body) })`\n   * before any user steps so parse failures flow through the route's normal\n   * error handling instead of aborting the source. See #187.\n   */\n  PARSE = \"parse\",\n  /** The exchange was processed by a processor */\n  PROCESS = \"process\",\n  /** The exchange was sent to a destination */\n  TO = \"to\",\n  /** The exchange was split into multiple exchanges */\n  SPLIT = \"split\",\n  /** The exchange was aggregated from multiple exchanges */\n  AGGREGATE = \"aggregate\",\n  /** Modify the body of the exchange */\n  TRANSFORM = \"transform\",\n  /** Tap an exchange without modifying it */\n  TAP = \"tap\",\n  /** Filter an exchange based on a condition and reject the message if the condition is not met */\n  FILTER = \"filter\",\n  /** Validate the exchange against a schema and reject the message if the schema is not met */\n  VALIDATE = \"validate\",\n  /** Enrich the exchange with data from another exchange */\n  ENRICH = \"enrich\",\n  /** Set or override a header on the exchange */\n  HEADER = \"header\",\n  /** Conditionally route the exchange through one of several branches */\n  CHOICE = \"choice\",\n  /** Fan the exchange out to multiple independent paths in parallel */\n  MULTICAST = \"multicast\",\n  /** Run exactly one of several targets, chosen by load-balancing strategy */\n  DISPATCH = \"dispatch\",\n  /** Rate limit an operation, pacing exchanges that exceed the rate */\n  THROTTLE = \"throttle\",\n  /** Fast-fail an operation while a downstream is known to be failing */\n  CIRCUIT_BREAKER = \"circuit-breaker\",\n  /** Bound how many exchanges run an operation simultaneously (bulkhead) */\n  CONCURRENCY = \"concurrency\",\n  /** Pass every Nth exchange (or the first per time window), dropping the rest */\n  SAMPLE = \"sample\",\n  /** Drop exchanges whose derived key has already been seen */\n  DEDUPE = \"dedupe\",\n  /** Hold a burst of exchanges and release only the last after a quiet period */\n  DEBOUNCE = \"debounce\",\n  /** Short-circuit the pipeline: drop the exchange without further steps */\n  HALT = \"halt\",\n  /** Defer the exchange durably and exit the pipeline, to be resumed later at the next step */\n  DEFER = \"defer\",\n  /** Revive a deferred exchange addressed by a signed resume token */\n  RESUME = \"resume\",\n}\n\n/**\n * Framework-owned header keys present on every exchange.\n *\n * The whole `routecraft.*` header namespace is RESERVED: the framework and\n * its adapters own every key under it. Adapter-specific keys live in\n * per-adapter key objects next to their adapters (e.g. `MailHeaders.UID`,\n * `CronHeaders.EXPRESSION`); each adapter merges its keys into\n * {@link RoutecraftHeaders} via declaration merging so they stay typed on\n * `exchange.headers`. User-defined headers must use their own namespace\n * (e.g. `x-...` or `myapp.*`).\n */\nexport const HeadersKeys = {\n  /** Unique identifier for this exchange. Stored in headers so it survives halt/continue alongside body. */\n  ID: \"routecraft.id\",\n  /** The operation type (from, process, to) */\n  OPERATION: \"routecraft.operation\",\n  /** The route id */\n  ROUTE_ID: \"routecraft.route\",\n  /** The correlation id */\n  CORRELATION_ID: \"routecraft.correlation_id\",\n  /** The hierarchy of split groups this exchange belongs to */\n  SPLIT_HIERARCHY: \"routecraft.split_hierarchy\",\n  /**\n   * Authenticated principal resolved from the request, when available.\n   * Carries the structured `Principal` object; the `ex.principal` getter\n   * is sugar over `ex.headers[HeadersKeys.AUTH_PRINCIPAL]`.\n   */\n  AUTH_PRINCIPAL: \"routecraft.auth.principal\",\n} as const satisfies Record<string, string>;\n\n/**\n * Typed map of well-known headers on an exchange. The core interface\n * declares only the framework-owned keys; adapters and ecosystem packages\n * merge their own `routecraft.<adapter>.*` keys in via declaration merging,\n * next to the adapter that owns them:\n *\n * ```ts\n * declare module \"@routecraft/routecraft\" {\n *   interface RoutecraftHeaders {\n *     \"routecraft.myadapter.thing\"?: string;\n *   }\n * }\n * ```\n *\n * The `routecraft.*` namespace is reserved for the framework and adapters;\n * see {@link HeadersKeys}.\n */\nexport interface RoutecraftHeaders {\n  /**\n   * Unique identifier for this exchange.\n   *\n   * Stored in headers (not as a separate field) so it travels with the\n   * exchange's serializable state. This is the single source of truth for\n   * exchange identity; the `ex.id` getter reads from this key.\n   */\n  \"routecraft.id\": string;\n\n  /** The current operation being performed (OperationType or DSL label) */\n  \"routecraft.operation\": OperationType | string;\n\n  /** The ID of the route processing this exchange */\n  \"routecraft.route\": string;\n\n  /** Unique identifier for correlating related exchanges */\n  \"routecraft.correlation_id\": string;\n\n  /** Hierarchy path for split operations */\n  \"routecraft.split_hierarchy\"?: readonly string[];\n}\n\n/**\n * Allowed types for a single header value at the **bag** level.\n *\n * `unknown` lets cross-cutting concerns (auth principal, future tracing\n * spans, tenancy contexts) live in `headers` as a single typed slot rather\n * than being spread across many flat keys. Per-key types are narrowed by\n * {@link RoutecraftHeaders} (which adapters extend via declaration\n * merging); this bag-level type is just the catch-all for unregistered\n * keys.\n *\n * For API surfaces that accept a static header value (e.g. `.header(\"k\",\n * v)`), prefer {@link HeaderLiteral} which excludes function types so user\n * lambdas get correct inference in the value-or-function overload.\n *\n * Array values declared on registered keys are typed `readonly string[]` so\n * they cannot be mutated via `push` / `splice` / index assignment through\n * the (already `Readonly<>`) `ExchangeHeaders` map. The contract is\n * type-level; the constructor freezes array values defensively so a caller\n * who casts away the readonly cannot mutate a shared reference.\n */\nexport type HeaderValue = unknown;\n\n/**\n * Allowed types for a header value when supplied as a literal at an API\n * boundary that also accepts a callback (e.g. `.header(\"k\", v)` /\n * `.header(\"k\", ex => ...)`). Excludes function types so the callback arm\n * of the union infers parameters correctly.\n *\n * Includes the original primitive types for source-compat plus\n * `Readonly<Record<string, unknown>>` so structured values (Principal,\n * future Span, etc.) can be assigned directly when they aren't mediated by\n * a callback.\n */\nexport type HeaderLiteral =\n  | string\n  | number\n  | boolean\n  | null\n  | undefined\n  | readonly string[]\n  | Readonly<Record<string, unknown>>;\n\n/**\n * Complete set of headers for an exchange. Read-only by contract: produce\n * derived headers via spread (`{ ...exchange.headers, key: value }`) and the\n * framework re-wraps the resulting exchange when the operation hands it back.\n *\n * Includes standard Routecraft headers, adapter-declared headers (merged\n * into {@link RoutecraftHeaders}), and custom headers.\n */\nexport type ExchangeHeaders = Readonly<\n  Partial<RoutecraftHeaders> & Record<string, HeaderValue>\n>;\n\n/**\n * Represents a message being processed through a route.\n *\n * An exchange has two kinds of state:\n *\n * 1. **Stored fields** (`body`, `headers`) carry the data and metadata that\n *    must survive halt/continue. Persistence serializes exactly these two\n *    slots; rehydration constructs a new instance around them.\n * 2. **Derived accessors** (`id`, `principal`, `logger`) read from\n *    `headers` (or runtime services) and look like properties at the call\n *    site. They are not stored separately. `id` reads\n *    `headers[\"routecraft.id\"]`; `principal` reads\n *    `headers[\"routecraft.auth.principal\"]`; `logger` builds a child logger\n *    lazily from the framework's logger and the exchange's id.\n *\n * Cross-cutting concerns (auth, tracing, tenancy) all live as keys in\n * `headers` rather than as top-level fields. This keeps the serialization\n * surface small and avoids a \"special field\" precedent for every new\n * concern.\n *\n * Exchanges are immutable. Operations that change body or headers must\n * produce a new exchange (typically via spread) and return it; the\n * framework re-wraps the result via {@link DefaultExchange.rewrap} so it\n * preserves internal bindings (context, route). Body is not deep-frozen so\n * adapter authors can attach arbitrary user payloads, but the framework\n * will not mutate it and authors should treat it the same way.\n *\n * @template T The type of data in the body\n */\nexport type Exchange<T = unknown> = {\n  /**\n   * Unique identifier for this exchange.\n   *\n   * Reads from `headers[\"routecraft.id\"]`. Stable across `rewrap`s so\n   * pipeline steps see the same id throughout a route.\n   */\n  readonly id: string;\n\n  /** Headers containing metadata, including cross-cutting concerns like the authenticated principal. */\n  readonly headers: ExchangeHeaders;\n\n  /** The data being processed */\n  readonly body: T;\n\n  /**\n   * Authenticated principal for this exchange, when one has been resolved.\n   *\n   * Sugar over `headers[\"routecraft.auth.principal\"]`. Set automatically by\n   * source adapters that perform authentication (e.g. the MCP server when\n   * `auth:` is configured) by writing the principal into headers. Routes\n   * may also assign a custom principal in `.process()` by spreading new\n   * headers with this key.\n   *\n   * Propagates naturally because it lives in `headers`: any operation that\n   * spreads `prev.headers` keeps the principal sticky-set automatically,\n   * with no special-case plumbing.\n   */\n  readonly principal?: Principal | undefined;\n\n  /**\n   * Logger for this exchange (pino child logger).\n   *\n   * Built lazily from the framework's base logger and the exchange's id /\n   * route / correlation. Not stored as serializable state; rehydrated\n   * exchanges build a fresh child logger on first access.\n   */\n  readonly logger: ReturnType<typeof logger.child>;\n\n  /**\n   * Durable-deferral view of this exchange: the id and signed token it\n   * would defer as, and (after a resume) the payload that revived it.\n   *\n   * Sugar over the `routecraft.deferral.*` headers plus the context's\n   * token signer, in the same shape as `principal` and `logger`. Readable\n   * before the `.defer()` runs, which is what lets a notification step\n   * earlier in the pipeline send a working resume link.\n   *\n   * `result` is `unknown` here; `.defer({ schema })` narrows it to the\n   * schema's output type for every step after the defer.\n   */\n  readonly deferral: DeferralAffordance;\n};\n\n/**\n * Internal state for exchanges.\n * Stored in WeakMap so it is not exposed on the public Exchange interface.\n *\n * @internal\n */\ntype ExchangeInternals = {\n  context: CraftContext;\n  route?: Route;\n  /**\n   * The sequence the next deferral in this run must use, set by an aside deferral\n   * (`deferAside`). The aside stores the successor sequence on the record\n   * it writes, as a `.defer()` deferral does, but the live exchange runs\n   * on with its headers unchanged, so a later deferral in the same run would\n   * derive the id the aside just took. Shared across rewraps like the\n   * flags above.\n   *\n   * @internal\n   */\n  deferralSequence?: number;\n  /**\n   * Optional parser the runtime applies as a synthetic first pipeline step.\n   * Set by `DefaultRoute` from the queue `Message.parse` when a source\n   * adapter attaches one (see `CallableSource.handler` parse argument and\n   * #187). The runtime clears this after running it so it does not run\n   * twice.\n   *\n   * @internal\n   */\n  parse?: (raw: unknown) => unknown | Promise<unknown>;\n  /**\n   * How the synthetic parse step should handle a parse failure.\n   * - `\"fail\"` / `\"abort\"`: throw `RC5016` so `route:exchange:failed` fires (and\n   *   for `\"abort\"` the adapter rethrows out of subscribe).\n   * - `\"drop\"`: emit `route:exchange:dropped` with `reason: \"parse-failed\"`,\n   *   matching filter/validate drop semantics; the pipeline halts cleanly\n   *   without invoking `.error()`. See #187.\n   *\n   * @internal\n   */\n  parseFailureMode?: OnParseError;\n  /**\n   * Optional input-schema validation deferred to run inside the synthetic\n   * parse step. Used when a route has both `.input()` schemas and a\n   * parsing source: validation must see the parsed body, not the raw\n   * bytes. `DefaultRoute` populates this alongside `parse`. See #187.\n   *\n   * Returns the validated exchange (with body and/or headers updated)\n   * so the parse step can thread the new immutable instance forward.\n   *\n   * @internal\n   */\n  applyValidation?: (exchange: Exchange) => Promise<Exchange>;\n  /**\n   * Route-scope cache key captured by the `cache-check` filter and\n   * read back by the `cache-store` filter at the tail of the chain.\n   * Lives on internals so the filters can be constructed once at\n   * builder time (rather than per-`runPipeline` closures); each exchange\n   * carries its own key via this slot. Unset when the route has no\n   * `.cache()` configured. See `.standards/pre-from-filter-chain.md`.\n   *\n   * @internal\n   */\n  cacheKey?: string;\n  /**\n   * When the engine first encounters an exchange in the step loop it\n   * records the start timestamp here, used later to compute duration\n   * for `route:exchange:completed`. Stored on internals (rather than headers)\n   * so it survives `rewrap` calls without consuming a header slot, and\n   * so aggregator code can read child start times without the engine\n   * having to thread a side-Map through.\n   *\n   * @internal\n   */\n  startedAt?: number;\n  /**\n   * Set when an exchange is dropped (filter, choice halt / unmatched,\n   * parse drop, input-validation drop, `recovery.drop()` directives; see\n   * {@link emitExchangeDropped}). The runtime engine reads this\n   * after `runPipeline` completes to skip `route:exchange:completed` emission.\n   * Stored on internals so the flag survives `rewrap`: the engine\n   * rewraps an exchange before each step (to update the operation\n   * header), so an operation that calls `markDropped(exchange)` is\n   * marking the rewrapped instance, but the engine's outer parameter\n   * is the pre-rewrap original. Both share the same internals object\n   * via {@link DefaultExchange.rewrap}'s `rewrapState`, so the flag is\n   * visible from either reference.\n   *\n   * @internal\n   */\n  dropped?: boolean;\n  /**\n   * The schema the route's `.output({ body })` validation accepted this\n   * exchange's body against. Stored on internals so it survives the `rewrap`\n   * that carries the validated value, and so a request/reply adapter can tell\n   * a body the route vouched for from one that reached it another way.\n   *\n   * The schema itself rather than a boolean: \"some schema accepted this\" is\n   * not the question a downstream enforcer is asking. It wants to know\n   * whether *its* contract was the one checked, so an exchange validated\n   * elsewhere cannot walk past a different contract unexamined.\n   *\n   * Load-bearing beyond bookkeeping: validation replaces the body with the\n   * schema's output, and a schema whose output type differs from its input\n   * type rejects its own output, so anything downstream that re-runs the\n   * same schema must know not to.\n   *\n   * @internal\n   */\n  outputValidatedAgainst?: StandardSchemaV1;\n  /**\n   * Set when the exchange deferred at a `.defer()`. Read after\n   * `runPipeline` returns to skip `.output()` validation and\n   * `route:exchange:completed`: execution one ends with the `Deferred`\n   * acknowledgment as its body, which is deliberately NOT the route's\n   * declared output, and its terminal event is `route:exchange:deferred`.\n   *\n   * On internals for the same reason as {@link ExchangeInternals.dropped}:\n   * the flag is set on the exchange a step was handed (already rewrapped),\n   * while the run that has to read it holds the pre-rewrap reference, and a\n   * nested run (a route-scope retry / timeout / bulkhead segment) holds yet\n   * another. All of them share one internals object.\n   *\n   * @internal\n   */\n  deferred?: boolean;\n  /**\n   * Step-owned closure state read back off a deferral record, set by the\n   * resume path just before a re-entrant continuation runs. The deferring\n   * step reads it without consuming ({@link peekResumeStepState}) and the\n   * executor clears it when that step settles, so a retried attempt still\n   * resumes while a second dispatch of the same step later in the\n   * continuation starts fresh instead of resuming again.\n   *\n   * On internals rather than headers deliberately: it is runtime context\n   * for exactly one step execution on this process, not exchange state, and\n   * it must never be re-serialized into the next deferral (the step builds a\n   * fresh stepState for that).\n   *\n   * @internal\n   */\n  resumeStepState?: unknown;\n};\n\n/**\n * WeakMap storing internal state for exchanges.\n * Used to hide context and task tracking from external access.\n *\n * @internal\n */\nexport const EXCHANGE_INTERNALS = new WeakMap<Exchange, ExchangeInternals>();\n\n/**\n * Get the CraftContext for an exchange, if it has internals.\n * Reads from symbol-keyed storage first (cross-instance safe), then WeakMap.\n *\n * @param exchange The exchange\n * @returns The context or undefined\n * @internal\n */\nexport function getExchangeContext(\n  exchange: Exchange,\n): CraftContext | undefined {\n  return internalsOf(exchange)?.context;\n}\n\n/**\n * Resolve an exchange's internals: symbol-keyed slot first (which works\n * across duplicate copies of the package in one process), WeakMap second.\n *\n * One accessor rather than the lookup written out at each call site. The\n * two-step rule is load-bearing (a `rewrap` shares the internals object by\n * reference, which is what makes the dropped and deferred flags visible\n * from every derivation of one logical exchange), and a site that got it\n * wrong would silently read `undefined` and lose the flag.\n *\n * @internal\n */\nfunction internalsOf(exchange: Exchange): ExchangeInternals | undefined {\n  return (\n    (exchange as Exchange & { [INTERNALS_KEY]?: ExchangeInternals })[\n      INTERNALS_KEY\n    ] ?? EXCHANGE_INTERNALS.get(exchange)\n  );\n}\n\n/**\n * Get the route for an exchange, if it has internals.\n * Reads from symbol-keyed storage first (cross-instance safe), then WeakMap.\n *\n * @param exchange The exchange\n * @returns The route or undefined\n * @internal\n */\nexport function getExchangeRoute(exchange: Exchange): Route | undefined {\n  return internalsOf(exchange)?.route;\n}\n\n/**\n * Bind a route onto an exchange's internals. Symbol-key first (cross-instance\n * safe), WeakMap fallback -- the symmetric write half of {@link\n * getExchangeRoute}. Used wherever an exchange is constructed outside the\n * normal source path and must be made executor-ready (split children,\n * {@link cloneExchange}). The internals object is mutable post-construction\n * (the wrapper is frozen, the internals are not), so this is safe after the\n * exchange has been created.\n *\n * @internal\n */\nexport function setExchangeRoute(exchange: Exchange, route: Route): void {\n  const internals = internalsOf(exchange);\n  if (internals) internals.route = route;\n}\n\n/**\n * Attach a deferral record's `stepState` for the re-entrant step about to\n * re-run. Set by the resume path; read by {@link peekResumeStepState} and\n * cleared by the executor once that step settles.\n *\n * @internal\n */\nexport function setResumeStepState(exchange: Exchange, state: unknown): void {\n  const internals = internalsOf(exchange);\n  if (internals) internals.resumeStepState = state;\n}\n\n/**\n * The step state a resume attached for the re-entrant step about to re-run,\n * or `undefined` when this execution is not resuming that step.\n *\n * A defer-capable adapter (see {@link markDeferCapable}) calls this at\n * the top of its execution to decide between a fresh run and a resumed one.\n * Reading does NOT consume the state: the executor clears it when the step\n * settles, so a step-scope or route-scope `.retry()` re-running a failed\n * resume attempt still sees it, while a later defer-capable step in the\n * same continuation (or a fresh deferral by the same step) starts clean.\n */\nexport function peekResumeStepState(exchange: Exchange): unknown {\n  return internalsOf(exchange)?.resumeStepState;\n}\n\n/**\n * Drop the resume step state once the re-entrant host step has settled\n * (any committed outcome: success, drop, or a fresh defer). Called by the\n * pipeline executor, never by adapters; a thrown failure leaves the state\n * in place so a retry of the attempt can still resume.\n *\n * @internal\n */\nexport function clearResumeStepState(exchange: Exchange): void {\n  const internals = internalsOf(exchange);\n  if (internals) internals.resumeStepState = undefined;\n}\n\n/**\n * Deep-clone an exchange for fan-out operations (the `tap` snapshot and\n * `multicast` paths). ONLY the body is deep-copied (`structuredClone`), so a\n * clone-side body mutation can never race the original. Headers are spread\n * SHALLOWLY: framework headers are immutable and safe to share by reference,\n * but object-valued user headers (e.g. `.header(\"x\", { ... })`) remain shared\n * between the clone and the source -- mutating a nested header field is an\n * anti-pattern that is NOT isolated. The clone gets a fresh `routecraft.id`\n * (so logs and identity-aware tooling distinguish it) and preserves the\n * correlation id so it stays traceable to the same logical request.\n *\n * When `route` is supplied it is bound onto the clone's internals so the\n * clone can run through the pipeline executor (multicast paths need this). It\n * is left unset by default so a detached snapshot (tap) stays route-less and\n * route-reading adapters see no binding, matching tap's isolation contract.\n *\n * @internal\n */\nexport function cloneExchange<T>(\n  exchange: Exchange<T>,\n  context: CraftContext,\n  route?: Route,\n): Exchange<T> {\n  const clone = new DefaultExchange<T>(context, {\n    body: structuredClone(exchange.body),\n    headers: {\n      ...exchange.headers,\n      [HeadersKeys.ID]: randomUUID(),\n      // The fresh id above is what makes a clone distinguishable in logs,\n      // but it would also point `ex.deferral` at a deferral that never\n      // defers. Record which exchange this is a snapshot OF so a `.tap()`\n      // notification can mint the resume token for the exchange that will.\n      [DEFERRAL_OWNER_HEADER]:\n        exchange.headers[DEFERRAL_OWNER_HEADER] ?? exchange.id,\n    },\n  });\n  if (route) setExchangeRoute(clone, route);\n  return clone;\n}\n\n/**\n * Mark an exchange as dropped. Idempotent. Drop sites that also emit\n * `route:exchange:dropped` go through {@link emitExchangeDropped}, which\n * wraps this; call this directly only when there is no emission to pair\n * with (e.g. the cache wrapper's loader-drop path, or marking ahead of an\n * earlier event that carries the exchange).\n *\n * The drop flag lives on the exchange's internals object (which is shared\n * by reference across `rewrap`) rather than a per-instance WeakSet, so a\n * filter that marks the rewrapped exchange the engine handed it remains\n * visible to the engine's final `isDropped` check on the outer parameter:\n * both reference the same internals.\n *\n * @internal\n */\nexport function markDropped(exchange: Exchange): void {\n  const internals = internalsOf(exchange);\n  if (internals) internals.dropped = true;\n}\n\n/**\n * Drop an exchange: mark it dropped, then emit `route:exchange:dropped`.\n *\n * This is the single sanctioned way to drop an exchange from a step or\n * pipeline site. The mark MUST precede the emission so a subscriber that\n * calls `isDropped(event.details.exchange)` observes the correct state;\n * the runtime engine reads the flag after `runPipeline` to skip\n * `route:exchange:completed` (see `pipeline/executor.ts`). The mark is\n * unconditional ({@link markDropped} is idempotent); the emission is\n * skipped when no context is bound, which keeps the drop flag correct\n * for synthetic exchanges in unit tests.\n *\n * Sites that emit additional events before the drop (`route:step:completed`,\n * `route:step:failed`, `operation:choice:unmatched`, error-handler events)\n * keep those emissions local and call this helper last, so\n * `route:exchange:dropped` stays the final event for the exchange.\n *\n * @internal\n */\nexport function emitExchangeDropped(\n  context: CraftContext | undefined,\n  details: {\n    routeId: string;\n    correlationId: string;\n    reason: string;\n    exchange: Exchange;\n  },\n): void {\n  const { routeId, correlationId, reason, exchange } = details;\n  markDropped(exchange);\n  context?.emit(\"route:exchange:dropped\", {\n    routeId,\n    exchangeId: exchange.id,\n    correlationId,\n    reason,\n    exchange,\n  });\n}\n\n/**\n * Record the schema the route's declared output validation accepted this\n * exchange's body against. Idempotent. Called by `applyOutputValidation` only.\n *\n * @internal\n */\nexport function markOutputValidated(\n  exchange: Exchange,\n  schema: StandardSchemaV1,\n): void {\n  const internals = internalsOf(exchange);\n  if (internals) internals.outputValidatedAgainst = schema;\n}\n\n/**\n * Returns true if the route's `.output({ body })` validation accepted this\n * exchange's body against `schema` specifically.\n *\n * A request/reply source adapter that enforces the same schema at its own\n * protocol boundary reads this to avoid validating twice. The second run is\n * not merely redundant: validation replaces the body with the schema's\n * output value, so a schema that transforms (`z.string().transform(...)`,\n * `.pipe()`) rejects the very value it just produced.\n *\n * The schema is compared by identity, so an exchange validated against some\n * other contract does not count as validated against this one.\n *\n * @param exchange - The exchange to test, or any rewrap of it\n * @param schema - The schema the caller is about to enforce\n * @returns Whether the route already validated this body against that schema\n */\nexport function wasOutputValidated(\n  exchange: Exchange,\n  schema: StandardSchemaV1,\n): boolean {\n  return internalsOf(exchange)?.outputValidatedAgainst === schema;\n}\n\n/**\n * Mark an exchange as deferred at a `.defer()`. Idempotent. Called by the\n * executor once the deferral is durably stored, never before: the flag\n * suppresses the exchange's completion accounting, so setting it for a deferral\n * that then failed to write would lose the exchange from every ledger.\n *\n * @internal\n */\nexport function markDeferred(exchange: Exchange): void {\n  const internals = internalsOf(exchange);\n  if (internals) internals.deferred = true;\n}\n\n/**\n * Record the sequence the next deferral in this run must use, after an aside\n * deferral took the current one. See `ExchangeInternals.deferralSequence`.\n *\n * @internal\n */\nexport function noteAsideSequence(exchange: Exchange, next: number): void {\n  const internals = internalsOf(exchange);\n  if (internals) internals.deferralSequence = next;\n}\n\n/**\n * The sequence an aside deferral in this run advanced to, or `undefined` when\n * none did and the header is the whole truth.\n *\n * @internal\n */\nexport function asideSequenceOf(exchange: Exchange): number | undefined {\n  return internalsOf(exchange)?.deferralSequence;\n}\n\n/**\n * Returns true if the exchange (or any rewrap of it sharing the same\n * internals) deferred at a `.defer()` during this run.\n *\n * @internal\n */\nexport function isDeferredRun(exchange: Exchange): boolean {\n  return internalsOf(exchange)?.deferred === true;\n}\n\n/**\n * Returns true if the exchange (or any rewrap of it sharing the same\n * internals) has been marked as dropped.\n *\n * A request/reply source adapter reads this to tell \"the route declined\n * this request\" apart from \"the route produced this result\": a dropped\n * exchange resolves with the body it came in with, so an adapter that does\n * not check hands the caller its own request back as if it were an answer.\n * `CraftClient.sendDirect` and the route-scope `forward` both raise RC5031\n * on it; an adapter outside core translates it into whatever its protocol\n * uses to decline.\n *\n * @param exchange - The exchange to test, or any rewrap of it\n * @returns Whether the exchange was dropped rather than completed\n */\nexport function isDropped(exchange: Exchange): boolean {\n  return internalsOf(exchange)?.dropped === true;\n}\n\n/**\n * Record the timestamp at which the runtime engine first encountered an\n * exchange in the step loop. Stored on the exchange's internals so it\n * survives `rewrap` (which shares internals between prev and next) and so\n * aggregator code can read child start times without a side channel.\n *\n * @internal\n */\nexport function setStartedAt(exchange: Exchange, ts: number): void {\n  const internals = internalsOf(exchange);\n  if (internals) internals.startedAt = ts;\n}\n\n/**\n * Read the recorded start timestamp for an exchange, if one was set.\n *\n * @internal\n */\nexport function getStartedAt(exchange: Exchange): number | undefined {\n  return internalsOf(exchange)?.startedAt;\n}\n\n/**\n * Internal options accepted by {@link DefaultExchange}'s constructor.\n * The constructor freezes whatever it produces; callers can supply either a\n * `Readonly<...>` headers object (e.g. from another exchange) or a plain\n * literal.\n *\n * `id` and `principal` are NOT options here: they live inside `headers`\n * (`headers[\"routecraft.id\"]` and `headers[\"routecraft.auth.principal\"]`).\n * Callers that want to control them set the corresponding header keys when\n * building `headers`.\n *\n * @internal\n */\ntype DefaultExchangeOptions<T> = {\n  body?: T;\n  headers?: ExchangeHeaders;\n};\n\n/**\n * Internal payload used by {@link DefaultExchange.rewrap} to thread state\n * from the previous exchange into the new instance without going through\n * the public constructor's default-injection / fresh-logger paths.\n *\n * - `internals` is shared by reference so any post-construction write\n *   (route binding, child startedAt, parse hooks) is visible on every\n *   rewrap of the same logical exchange.\n * - `logger` is reused because its child bindings (contextId, route,\n *   correlationId, exchangeId) are unchanged across `rewrap` (rewrap\n *   preserves `id`). Pre-populating the lazy `#logger` slot avoids\n *   rebuilding the same child on every rewrap of a long pipeline.\n *\n * @internal\n */\ntype RewrapState = {\n  readonly internals: ExchangeInternals;\n  readonly logger: ReturnType<typeof logger.child>;\n};\n\n/**\n * Module-private hand-off slot for the rewrap fast path. `rewrap` writes\n * the previous exchange's state here immediately before calling the\n * constructor, which consumes (and clears) it as its first action; the\n * construction is synchronous, so nothing can interleave. Threading the\n * state through a slot instead of a constructor parameter keeps the\n * exported constructor surface at `(context, options?)`: no internal type\n * appears in the published declarations and external code has no way to\n * supply rewrap state.\n */\nlet pendingRewrap: RewrapState | undefined;\n\n/**\n * Default implementation of the Exchange interface.\n *\n * The implementation stores exactly two fields, `body` and `headers`.\n * Everything else surfaced on the public `Exchange<T>` API (`id`,\n * `principal`, `logger`) is exposed through getters that derive from\n * `headers` plus runtime services. This keeps the serialization surface\n * for halt/continue narrow (just `{ body, headers }`) and removes the\n * \"special field\" precedent for cross-cutting concerns.\n *\n * Instances are immutable: the constructor freezes the wrapper and headers\n * (and any non-primitive header values, defensively). Body is left\n * unfrozen so user payloads of any shape can flow through; the framework\n * does not mutate it.\n *\n * @template T The type of data in the body\n *\n * @example\n * ```typescript\n * // Create a simple exchange with a string body\n * const exchange = new DefaultExchange<string>(context, {\n *   body: \"Hello, World!\"\n * });\n *\n * // Access exchange properties\n * console.log(exchange.id);        // Unique UUID (read from headers[\"routecraft.id\"])\n * console.log(exchange.body);      // \"Hello, World!\"\n * console.log(exchange.headers);   // Headers object with standard fields\n * ```\n */\nexport class DefaultExchange<T = unknown> implements Exchange<T> {\n  /** Headers containing metadata, including the exchange id and (when set) the authenticated principal. */\n  readonly headers: ExchangeHeaders;\n\n  /** The data being processed */\n  readonly body: T;\n\n  /**\n   * Lazily-built pino child logger. Filled on first access by the `logger`\n   * getter, or pre-populated by `rewrap` so a long pipeline reuses the\n   * parent exchange's child instead of rebuilding it on every step.\n   *\n   * Private fields are stored in a hidden internal slot, not as own\n   * properties, so writes to `#logger` are unaffected by `Object.freeze(this)`.\n   */\n  #logger: ReturnType<typeof logger.child> | undefined;\n\n  /**\n   * Create a new exchange.\n   *\n   * @param context The CraftContext this exchange belongs to\n   * @param options Optional configuration for the exchange. Set the exchange\n   *   id by including `headers[\"routecraft.id\"]`; set the principal by\n   *   including `headers[\"routecraft.auth.principal\"]`. Both default to\n   *   sensible runtime values when omitted (id: `randomUUID()`).\n   */\n  constructor(context: CraftContext, options?: DefaultExchangeOptions<T>) {\n    // Consume the rewrap hand-off slot first so it can never leak into a\n    // later construction (including when this constructor throws). When\n    // {@link DefaultExchange.rewrap} is building a derived instance, the\n    // slot threads the previous exchange's internals and logger through so\n    // they are genuinely shared (not just copied) and the constructor\n    // skips `logger.child(...)` work the rewrap path would otherwise\n    // repeat. The slot is module-private, so this path is unreachable\n    // from outside the framework.\n    const rewrapState = pendingRewrap;\n    pendingRewrap = undefined;\n    // Per-key gating preserves required defaults (`ID`, `OPERATION`,\n    // `ROUTE_ID`, `CORRELATION_ID`) when a caller supplies only some of\n    // them, instead of an all-or-nothing fast path that would silently\n    // drop the others. The rewrap path supplies all four via the spread\n    // of `prev.headers`, so the `??` branches are no-ops in the hot path\n    // and the per-construction `randomUUID()` cost is paid only at the\n    // route boundary.\n    //\n    // The supplied headers are spread FIRST so that the explicit\n    // required-key slots that follow override an `undefined` value the\n    // caller may have included (e.g. `{ ROUTE_ID: undefined }`). If the\n    // spread came last, an explicit `undefined` would clobber the\n    // just-computed default and leave required headers missing.\n    const supplied = options?.headers;\n    const merged: Record<string, HeaderValue> = {\n      ...(supplied || {}),\n      [HeadersKeys.ID]: supplied?.[HeadersKeys.ID] ?? randomUUID(),\n      [HeadersKeys.ROUTE_ID]: supplied?.[HeadersKeys.ROUTE_ID] ?? randomUUID(),\n      [HeadersKeys.OPERATION]:\n        supplied?.[HeadersKeys.OPERATION] ?? OperationType.FROM,\n      [HeadersKeys.CORRELATION_ID]:\n        supplied?.[HeadersKeys.CORRELATION_ID] ?? randomUUID(),\n    };\n    // Defensive freeze on values that callers might mutate by reference:\n    //\n    // - Arrays: type-level `readonly` on `HeaderValue` array variants\n    //   prevents mutation through `exchange.headers` in TypeScript code,\n    //   but a caller who casts away the readonly could still\n    //   `arr.push(...)` into a shared array reference. Clone-and-freeze\n    //   each unfrozen array so the runtime guarantee matches the type\n    //   contract.\n    // - Principal: a structured header value. Shallow-freezing the wrapper\n    //   makes claim mutation by adapters caught at runtime\n    //   (`exchange.principal.subject = ...` throws). Nested claims are\n    //   not deep-frozen.\n    //\n    // We don't deep-clone or freeze arbitrary objects; those are caller\n    // payloads and the framework treats them as opaque, the same way\n    // `body` is left unfrozen.\n    for (const key of Object.keys(merged)) {\n      const value = merged[key];\n      if (Array.isArray(value) && !Object.isFrozen(value)) {\n        merged[key] = Object.freeze([...value]);\n      }\n    }\n    // This block is an immutability defence only; it is NOT load-bearing for\n    // authenticity. Trust is conferred solely by membership in the private\n    // WeakSet in `auth/authentic.ts` (added by `markAuthentic`), which a clone\n    // here would not carry. Authentic principals always arrive already frozen\n    // (markAuthentic freezes), so this clone-and-freeze fires only for a\n    // self-asserted plain object, which `authorize()` rejects regardless.\n    const principal = merged[HeadersKeys.AUTH_PRINCIPAL];\n    if (\n      principal !== undefined &&\n      typeof principal === \"object\" &&\n      principal !== null &&\n      !Object.isFrozen(principal)\n    ) {\n      merged[HeadersKeys.AUTH_PRINCIPAL] = Object.freeze({\n        ...(principal as Principal),\n      });\n    }\n    this.headers = Object.freeze(merged);\n    // Honour an explicit `body: undefined` from the caller (e.g. a\n    // transform that intentionally returns undefined for a missing JSON\n    // path). Only fall back to `{}` when the caller did not pass a body\n    // key at all.\n    this.body = options && \"body\" in options ? (options.body as T) : ({} as T);\n\n    // Store internals: symbol key (cross-instance) and WeakMap (same-instance compat).\n    // Internals live BEFORE the wrapper is frozen because freeze prevents\n    // adding new own properties; symbol-keyed `[INTERNALS_KEY]` must be\n    // attached now. The internals OBJECT itself stays mutable (split.ts\n    // sets `internals.route` after construction; that mutates the object,\n    // not the exchange). When `rewrapState` is supplied, the previous\n    // exchange's internals object is reused by reference so any post-\n    // construction writes (route binding, child startedAt, parse hooks)\n    // are visible on every rewrap of the same logical exchange.\n    const internals: ExchangeInternals = rewrapState?.internals ?? { context };\n    setInternals(this, INTERNALS_KEY, internals);\n    EXCHANGE_INTERNALS.set(this, internals);\n    setBrand(this, BRAND.Exchange);\n    // Pre-populate the lazy logger slot when rewrapping. The child\n    // bindings (contextId, route, correlationId, exchangeId) are\n    // unchanged because rewrap preserves id, so the parent's logger\n    // stays correctly scoped. Fresh exchanges leave `#logger` undefined\n    // so the first read of `.logger` builds the child on demand.\n    if (rewrapState?.logger) {\n      this.#logger = rewrapState.logger;\n    }\n\n    // Freeze the wrapper itself last so own properties (including the\n    // symbol-keyed internals slot and the brand) are sealed against\n    // reassignment. Mutating user code via `as any` casts now produces a\n    // TypeError in strict mode, which the package runs in. Private fields\n    // (`#logger`) live in a hidden internal slot and are unaffected by\n    // freeze, so the lazy-build path keeps working post-freeze.\n    Object.freeze(this);\n  }\n\n  /**\n   * Unique identifier for this exchange. Reads from\n   * `headers[\"routecraft.id\"]` so the id travels with the serializable\n   * state and survives halt/continue.\n   */\n  get id(): string {\n    return this.headers[HeadersKeys.ID] as string;\n  }\n\n  /**\n   * Authenticated principal, when one has been resolved. Sugar over\n   * `headers[\"routecraft.auth.principal\"]`.\n   */\n  get principal(): Principal | undefined {\n    return this.headers[HeadersKeys.AUTH_PRINCIPAL] as Principal | undefined;\n  }\n\n  /**\n   * Pino child logger scoped to this exchange. Built lazily from the\n   * framework's base logger; rebuilt on a rehydrated exchange because the\n   * logger is not part of the serializable state.\n   */\n  get logger(): ReturnType<typeof logger.child> {\n    if (this.#logger === undefined) {\n      this.#logger = logger.child(childBindings(this));\n    }\n    return this.#logger;\n  }\n\n  /**\n   * Durable-deferral view of this exchange. See {@link Exchange.deferral}.\n   *\n   * Built per access rather than cached: the view derives from `headers`,\n   * which a resume rewrites, so a cached one would go stale exactly when it\n   * matters. It is a small object of getters, and the expensive part\n   * (minting a token) only runs if the caller reads `token`.\n   */\n  get deferral(): DeferralAffordance {\n    return deferralAffordance(\n      getExchangeContext(this),\n      this.headers,\n      this.id,\n      asideSequenceOf(this),\n    );\n  }\n\n  /**\n   * Construct a new {@link DefaultExchange} that combines internals from a\n   * previous exchange (context, route binding, parse hooks) with field\n   * overrides from a partial. Used by the engine to normalise plain\n   * objects user code returns from `.process()` (or any `with*`-style\n   * spread) back into proper instances without losing the framework's\n   * back-channel state.\n   *\n   * - `headers` defaults to `prev.headers`. Identity (`routecraft.id`) is\n   *   forced to `prev.id` so it survives a caller-supplied headers object\n   *   that came from a different exchange. Cross-cutting concerns\n   *   (`routecraft.auth.principal`, future tracing/tenancy keys) flow\n   *   through naturally because they live in the same headers bag.\n   * - `body` defaults to `prev.body`.\n   *\n   * Identity-changing operations (split, aggregate restoring a parent)\n   * construct a new `DefaultExchange` directly with fresh headers rather\n   * than calling `rewrap`.\n   *\n   * @internal\n   */\n  static rewrap<T>(\n    prev: Exchange,\n    partial: {\n      readonly body?: T;\n      readonly headers?: ExchangeHeaders;\n    } = {},\n  ): DefaultExchange<T> {\n    const prevInternals = internalsOf(prev);\n    const context = prevInternals?.context;\n    if (!context) {\n      throw new Error(\n        \"DefaultExchange.rewrap: previous exchange has no context binding; \" +\n          \"cannot construct a derived exchange. This usually means an \" +\n          \"adapter constructed an Exchange-shaped plain object outside the \" +\n          \"framework. Use `new DefaultExchange(context, { ... })` instead.\",\n      );\n    }\n\n    // Force prev's id into the new headers so a caller-supplied `headers`\n    // object that came from a foreign exchange (e.g. user code returning\n    // `{ ...someOtherExchange, body: x }` from `.process()`) does not\n    // silently change the exchange identity mid-route. Identity is owned\n    // by the framework and is preserved across rewraps. Identity-changing\n    // operations (split, aggregate-restore-parent) construct a new\n    // `DefaultExchange` directly rather than going through `rewrap`.\n    //\n    // For body, use `'body' in partial` so an explicit `body: undefined`\n    // (e.g. `transform(() => undefined)` or `json({ path: missingKey })`)\n    // sets the new body to undefined rather than inheriting prev's.\n    //\n    // Internals are shared by reference (not copied) via `rewrapState` so a\n    // post-construction write on either prev or next is visible on the\n    // other. The logger is reused for the same reason: bindings derive\n    // from id/contextId/route/correlationId, all of which `rewrap`\n    // preserves.\n    const baseHeaders = partial.headers ?? prev.headers;\n    const newHeaders =\n      baseHeaders[HeadersKeys.ID] === prev.id\n        ? baseHeaders\n        : { ...baseHeaders, [HeadersKeys.ID]: prev.id };\n    pendingRewrap = {\n      internals: prevInternals,\n      logger: prev.logger,\n    };\n    return new DefaultExchange<T>(context, {\n      headers: newHeaders,\n      body: (\"body\" in partial ? partial.body : prev.body) as T,\n    });\n  }\n}\n","import type { CraftContext } from \"./context.ts\";\nimport { rcError } from \"./error.ts\";\nimport type { RouteDiscovery } from \"./route.ts\";\n\n/**\n * A discoverable capability registered in a context: an endpoint plus the\n * route's discovery bundle (`.title()` / `.description()` / `.input()` /\n * `.output()` / `.tag()`).\n *\n * Returned by {@link CraftContext.capabilities}; dispatch into a\n * capability with `CraftClient.sendDirect(endpoint, body)`.\n */\nexport interface Capability extends RouteDiscovery {\n  /** Raw endpoint / route id, exactly as passed to `.id(...)` / `direct(...)`. */\n  endpoint: string;\n  /**\n   * The remote this capability was imported from (`defineConfig({ remotes })`),\n   * absent for a capability a local route registered. Read by the ops\n   * listing to name the origin and by the agent tool policy so a rule can\n   * keep an agent local-only.\n   */\n  remote?: string;\n}\n\n/**\n * Core-owned store key for the capability registry, keyed by RAW endpoint.\n *\n * Ownership is deliberately inverted from \"core reads an adapter's\n * registry\": adapters that expose discoverable endpoints WRITE into this\n * registry via {@link registerCapability}, and `context.capabilities()`\n * reads it without knowing which adapter populated it. That keeps the\n * core context free of adapter knowledge and lets future discoverable\n * adapters surface in `capabilities()` without core changes.\n *\n * `Symbol.for` so duplicate copies of the package (CLI vs user module)\n * share one registry.\n *\n * @internal The registry shape is internal; read via\n *   `context.capabilities()` and write via {@link registerCapability}.\n */\nexport const CAPABILITY_REGISTRY = Symbol.for(\"routecraft.capabilities\");\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [CAPABILITY_REGISTRY]: Map<string, Capability>;\n  }\n}\n\n/**\n * Register (or update) a discoverable capability on the context. Called\n * by adapters when a discoverable endpoint subscribes; the direct source\n * is the built-in writer, and ecosystem adapters exposing their own\n * discoverable endpoints use the same call.\n *\n * Keyed by the RAW endpoint id; any transport-level key encoding stays\n * inside the adapter that needs it.\n *\n * @returns A disposer that removes THIS registration when the endpoint is\n *   still held by it, and does nothing once something else has taken the\n *   name. An unconditional delete would be wrong on the one path that\n *   matters: a local route stopping hands its endpoint to the remote route\n *   it shadowed, `route:stopped` reaches the remotes plugin before the\n *   direct source's own abort listener, and a blind delete would then\n *   erase the replacement that already owns the name.\n */\nexport function registerCapability(\n  context: CraftContext,\n  capability: Capability,\n): () => void {\n  // Loud, not last-writer-wins: a capability is an external door, and an\n  // endpoint that declared itself internal must not have one quietly opened\n  // beside it. Fail-open here would expose the very subroutine the flag\n  // exists to close off (e.g. a route carrying both `direct()` and\n  // `direct({ internal: true })` sources).\n  if (isInternalEndpoint(context, capability.endpoint)) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `Endpoint \"${capability.endpoint}\" is declared internal (direct({ internal: true })) and cannot also register as a discoverable capability. Declare the endpoint internal or dispatchable, not both.`,\n    });\n  }\n  let registry = context.getStore(CAPABILITY_REGISTRY);\n  if (!registry) {\n    registry = new Map<string, Capability>();\n    context.setStore(CAPABILITY_REGISTRY, registry);\n  }\n  const entry = snapshotCapability(capability);\n  registry.set(capability.endpoint, entry);\n  return () => {\n    if (registry.get(capability.endpoint) === entry) {\n      registry.delete(capability.endpoint);\n    }\n  };\n}\n\n/**\n * Core-owned store key for endpoints declared internal, keyed by RAW\n * endpoint. Same ownership inversion as {@link CAPABILITY_REGISTRY}:\n * adapters write, consumers read without knowing which adapter wrote.\n *\n * A `direct({ internal: true })` source registers here INSTEAD of the\n * capability registry: its in-process endpoint works unchanged, while the\n * two external doors (ops dispatch, agent `directTool` resolution) find\n * no capability. This map is what lets their refusals say \"declared\n * internal\" instead of the wrong advice \"add `.from(direct())`\" for a\n * route that has one.\n *\n * A map rather than a set of names, because a marker has to be removable\n * by the registration that wrote it and by nothing else. The value is an\n * identity token: a stale disposer from a route that has already stopped\n * compares its own token against what the map holds and finds a stranger\n * there, so it leaves the live marker alone.\n *\n * @internal The map shape is internal; write via\n *   {@link registerInternalEndpoint} and read via {@link isInternalEndpoint}.\n */\nexport const INTERNAL_ENDPOINT_REGISTRY = Symbol.for(\n  \"routecraft.capabilities.internal\",\n);\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [INTERNAL_ENDPOINT_REGISTRY]: Map<string, symbol>;\n  }\n}\n\n/**\n * Record that an endpoint declared itself internal: composable in-process,\n * deliberately absent from the capability registry. Called by adapters at\n * subscribe, alongside where they would otherwise register a capability.\n *\n * @returns A disposer with the same ownership rule as\n *   {@link registerCapability}'s: it clears the marker only while this\n *   registration still holds it.\n */\nexport function registerInternalEndpoint(\n  context: CraftContext,\n  endpoint: string,\n): () => void {\n  // The mirror of the guard in registerCapability: whichever half of a\n  // contradictory declaration registers second is the one that fails, so\n  // the contradiction is loud regardless of source order.\n  if (context.getStore(CAPABILITY_REGISTRY)?.has(endpoint)) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `Endpoint \"${endpoint}\" is already registered as a discoverable capability and cannot also declare direct({ internal: true }). Declare the endpoint internal or dispatchable, not both.`,\n    });\n  }\n  let registry = context.getStore(INTERNAL_ENDPOINT_REGISTRY);\n  if (!registry) {\n    registry = new Map<string, symbol>();\n    context.setStore(INTERNAL_ENDPOINT_REGISTRY, registry);\n  }\n  const token = Symbol(endpoint);\n  registry.set(endpoint, token);\n  return () => {\n    if (registry.get(endpoint) === token) registry.delete(endpoint);\n  };\n}\n\n/**\n * Whether an endpoint declared itself internal. Read by the external doors\n * (ops dispatch, agent tool resolution) to refuse by name rather than with\n * advice that does not apply.\n */\nexport function isInternalEndpoint(\n  context: CraftContext,\n  endpoint: string,\n): boolean {\n  return context.getStore(INTERNAL_ENDPOINT_REGISTRY)?.has(endpoint) ?? false;\n}\n\n/**\n * Copy a capability, cloning the mutable `tags` array so neither the\n * registering adapter nor a `capabilities()` caller can mutate the\n * registry's copy (or vice versa) through a shared reference. Schemas\n * (`input` / `output`) are intentionally shared: they are live Standard\n * Schema objects, not data.\n *\n * @internal\n */\nexport function snapshotCapability(capability: Capability): Capability {\n  return {\n    ...capability,\n    ...(capability.tags ? { tags: [...capability.tags] } : {}),\n  };\n}\n","import type { CraftContext } from \"../../context\";\nimport { registerCapability, type Capability } from \"../../capabilities\";\nimport { rcError } from \"../../error\";\nimport type { RouteDiscovery } from \"../../route\";\nimport type {\n  DirectChannel,\n  DirectChannelType,\n  DirectBaseOptions,\n} from \"./types\";\nimport type { Exchange } from \"../../exchange\";\n\n/**\n * Store key for the direct channel map (endpoint name -> channel instance).\n * @internal\n */\nexport const ADAPTER_DIRECT_STORE = Symbol.for(\n  \"routecraft.adapter.direct.store\",\n);\n\n/**\n * Store key for the context-level direct channel type.\n * Set via `CraftConfig.direct` to swap all direct endpoints to a custom\n * channel implementation (e.g. Kafka, Redis) instead of in-memory.\n * @internal\n */\nexport const ADAPTER_DIRECT_OPTIONS = Symbol.for(\n  \"routecraft.adapter.direct.options\",\n);\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [ADAPTER_DIRECT_STORE]: Map<string, DirectChannel<Exchange>>;\n    [ADAPTER_DIRECT_OPTIONS]: Pick<DirectBaseOptions, \"channelType\">;\n  }\n}\n\n/**\n * Resolve the channel type to use for a given endpoint. Checks the\n * per-adapter options first, then falls back to the context-level default\n * set via `CraftConfig.direct`.\n */\nfunction resolveChannelType(\n  context: CraftContext,\n  adapterOptions: Partial<DirectBaseOptions>,\n): DirectChannelType<DirectChannel> | undefined {\n  if (adapterOptions.channelType) return adapterOptions.channelType;\n  const store = context.getStore(ADAPTER_DIRECT_OPTIONS) as\n    Pick<DirectBaseOptions, \"channelType\"> | undefined;\n  return store?.channelType;\n}\n\n/**\n * Get or create the direct channel for the given endpoint.\n *\n * @param context - The CraftContext\n * @param endpoint - The sanitized endpoint name\n * @param options - Per-adapter options that may contain a custom channel type\n * @returns The DirectChannel instance for this endpoint\n * @internal\n */\nexport function getDirectChannel<T>(\n  context: CraftContext,\n  endpoint: string,\n  options: Partial<DirectBaseOptions>,\n): DirectChannel<Exchange<T>> {\n  let store = context.getStore(ADAPTER_DIRECT_STORE) as\n    Map<string, DirectChannel<Exchange<T>>> | undefined;\n\n  // If the store is not set, create a new one\n  if (!store) {\n    store = new Map<string, DirectChannel<Exchange<T>>>();\n    context.setStore(ADAPTER_DIRECT_STORE, store);\n  }\n\n  // If the endpoint is not in the store, create a new one\n  if (!store.has(endpoint)) {\n    const ChannelCtor = resolveChannelType(context, options);\n    if (ChannelCtor) {\n      store.set(\n        endpoint,\n        new ChannelCtor(endpoint) as DirectChannel<Exchange<T>>,\n      );\n    } else {\n      // Fallback to a default in-memory implementation\n      store.set(endpoint, new InMemoryDirectChannel<Exchange<T>>());\n    }\n  }\n\n  return store.get(endpoint) as DirectChannel<Exchange<T>>;\n}\n\n/**\n * Register the route as a discoverable capability. The metadata comes\n * from the route's discovery bundle (set via `.title()` /\n * `.description()` / `.input()` / `.output()` on the builder); direct\n * itself carries no discovery fields on its own options. Writes into the\n * core-owned capability registry keyed by the RAW endpoint id; the\n * sanitised channel key stays a transport detail of this adapter.\n *\n * @returns The disposer {@link registerCapability} minted, which the\n *   source calls when the route stops so the registry stops advertising\n *   an endpoint nothing answers on.\n */\nexport function registerRoute(\n  context: CraftContext,\n  endpoint: string,\n  discovery?: RouteDiscovery,\n): () => void {\n  const capability: Capability = { endpoint };\n  if (discovery?.title !== undefined) capability.title = discovery.title;\n  if (discovery?.description !== undefined) {\n    capability.description = discovery.description;\n  }\n  if (discovery?.input !== undefined) capability.input = discovery.input;\n  if (discovery?.output !== undefined) capability.output = discovery.output;\n  if (discovery?.tags !== undefined && discovery.tags.length > 0) {\n    capability.tags = [...discovery.tags];\n  }\n  const dispose = registerCapability(context, capability);\n\n  context.logger.debug(\n    { endpoint, adapter: \"direct\" },\n    \"Registered direct route as a discoverable capability\",\n  );\n\n  return dispose;\n}\n\n/**\n * Sanitize endpoint name using URL encoding for reversible, collision-free keys.\n *\n * Uses `encodeURIComponent()` to ensure distinct endpoints like \"a/b\" and \"a-b\"\n * map to unique keys (\"a%2Fb\" vs \"a-b\"), preventing routing collisions.\n *\n * @param endpoint - Raw endpoint string\n * @returns URL-encoded endpoint string safe for use as Map key\n * @internal\n */\nexport function sanitizeEndpoint(endpoint: string): string {\n  return encodeURIComponent(endpoint);\n}\n\n/**\n * Default in-memory implementation of DirectChannel.\n *\n * IMPORTANT: This implements single-consumer semantics where only the\n * last route to subscribe to an endpoint will receive messages.\n * Previous subscribers are automatically replaced (last one wins).\n *\n * Exported for the remotes plugin, which hands one to a local route that\n * subscribes onto an endpoint a remote already holds.\n *\n * @internal\n */\nexport class InMemoryDirectChannel<T> implements DirectChannel<T> {\n  private handler: ((message: T) => Promise<T>) | null = null;\n\n  async send(endpoint: string, message: T): Promise<T> {\n    if (this.handler) {\n      // Synchronous behavior - single consumer gets the message and we wait for result\n      return await this.handler(message);\n    }\n    throw rcError(\"RC5004\", undefined, {\n      message: `No handler subscribed on direct endpoint \"${endpoint}\"; route may have stopped or was never started`,\n    });\n  }\n\n  async subscribe(\n    _context: CraftContext,\n    _endpoint: string,\n    handler: (message: T) => Promise<T>,\n  ): Promise<void> {\n    // Single consumer - only one handler allowed\n    // This replaces any existing handler (last subscriber wins)\n    this.handler = handler;\n  }\n\n  async unsubscribe(\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _context: CraftContext,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _endpoint: string,\n  ): Promise<void> {\n    this.handler = null;\n  }\n}\n","/**\n * Cryptographic verification of a received message via `mailauth`.\n *\n * Only loaded when the mail adapter is configured with `verify: \"strict\"`.\n * `mailauth` is an optional peer; users who enable strict mode must install it.\n */\n\nimport { rcError } from \"../../error.ts\";\nimport { loadOptionalPeer } from \"../shared/optional-peer.ts\";\nimport type { MailSender } from \"./analysis.ts\";\n\n/**\n * Cached `mailauth.authenticate` so a missing install is surfaced (and a\n * successful install resolved) exactly once per process.\n */\nlet authenticatePromise:\n  | Promise<\n      (\n        input: Buffer | string,\n        options?: Record<string, unknown>,\n      ) => Promise<MailAuthResult>\n    >\n  | undefined;\n\n/**\n * Run `mailauth.authenticate()` on the raw message source and fold the\n * cryptographic verdicts back into the header-derived {@link MailSender}.\n *\n * The header-derived analysis already resolved the forward chain and effective\n * sender; this pass only overrides the `authentication` verdicts and `trust`\n * based on cryptographic checks (DKIM/SPF/DMARC/ARC).\n */\nexport async function verifyStrict(\n  source: Buffer | undefined,\n  sender: MailSender,\n): Promise<MailSender> {\n  if (!source) return sender;\n\n  if (!authenticatePromise) {\n    authenticatePromise = (async () => {\n      const mod = (await loadOptionalPeer(() => import(\"mailauth\"), {\n        consumer: \"mail adapter (verify: 'strict')\",\n        packageName: \"mailauth\",\n      })) as unknown as {\n        authenticate: (\n          input: Buffer | string,\n          options?: Record<string, unknown>,\n        ) => Promise<MailAuthResult>;\n      };\n      return mod.authenticate;\n    })();\n  }\n  const authenticate = await authenticatePromise;\n\n  let result: MailAuthResult;\n  try {\n    result = await authenticate(source, { trustReceived: false });\n  } catch (error) {\n    throw rcError(\"RC5001\", error instanceof Error ? error : undefined, {\n      message: `mailauth verification failed: ${error instanceof Error ? error.message : String(error)}`,\n    });\n  }\n\n  const dkim = normalizeVerdict(result.dkim?.results?.[0]?.status?.result);\n  const spf = normalizeVerdict(result.spf?.status?.result);\n  const dmarc = normalizeVerdict(result.dmarc?.status?.result);\n  const arc = normalizeArc(result.arc?.status?.result);\n\n  const updated: MailSender = {\n    ...sender,\n    authentication: { dkim, spf, dmarc, arc },\n  };\n\n  if (sender.forwardType === \"direct\") {\n    updated.trust =\n      dmarc === \"pass\"\n        ? \"verified\"\n        : dmarc === \"fail\"\n          ? \"failed\"\n          : \"unverified\";\n    updated.reason =\n      dmarc === \"pass\"\n        ? \"direct-dmarc-crypto-verified\"\n        : dmarc === \"fail\"\n          ? \"direct-dmarc-crypto-fail\"\n          : \"direct-crypto-unverified\";\n  } else {\n    updated.trust =\n      arc === \"pass\" ? \"verified\" : arc === \"fail\" ? \"failed\" : \"unverified\";\n    updated.reason = `${sender.forwardType}-arc-crypto-${\n      arc === \"pass\" ? \"verified\" : arc === \"fail\" ? \"fail\" : \"unverified\"\n    }`;\n  }\n\n  return updated;\n}\n\n// ---------------------------------------------------------------------------\n// Internal typing for mailauth's result shape (partial, just what we use)\n// ---------------------------------------------------------------------------\n\ninterface MailAuthStatus {\n  result?: string;\n}\n\ninterface MailAuthResult {\n  dkim?: { results?: Array<{ status?: MailAuthStatus }> };\n  spf?: { status?: MailAuthStatus };\n  dmarc?: { status?: MailAuthStatus };\n  arc?: { status?: MailAuthStatus };\n}\n\nfunction normalizeVerdict(\n  v: string | undefined,\n): \"pass\" | \"fail\" | \"neutral\" | \"none\" {\n  const n = (v ?? \"\").toLowerCase();\n  return n === \"pass\" || n === \"fail\" || n === \"neutral\" ? n : \"none\";\n}\n\nfunction normalizeArc(v: string | undefined): \"pass\" | \"fail\" | \"none\" {\n  const n = (v ?? \"\").toLowerCase();\n  return n === \"pass\" || n === \"fail\" ? n : \"none\";\n}\n","import { createHmac, createVerify } from \"node:crypto\";\nimport { timingSafeStringEqual } from \"./timing-safe\";\nimport type {\n  ClaimMappers,\n  JwtAudience,\n  OAuthPrincipal,\n  OAuthValidatorAuthOptions,\n} from \"./types.ts\";\nimport { assertIssuerAudience, principalFromJwtPayload } from \"./jwt-utils.ts\";\n\n/**\n * Supported HMAC algorithms for JWT signature verification.\n * Maps JWT `alg` header values to Node.js `crypto.createHmac` digest names.\n */\nconst HMAC_ALGORITHMS = {\n  HS256: \"sha256\",\n  HS384: \"sha384\",\n  HS512: \"sha512\",\n} as const;\n\n/**\n * Supported RSA algorithms for JWT signature verification.\n * Maps JWT `alg` header values to Node.js `crypto.createVerify` algorithm names.\n */\nconst RSA_ALGORITHMS = {\n  RS256: \"RSA-SHA256\",\n  RS384: \"RSA-SHA384\",\n  RS512: \"RSA-SHA512\",\n} as const;\n\ntype HmacAlgorithm = keyof typeof HMAC_ALGORITHMS;\ntype RsaAlgorithm = keyof typeof RSA_ALGORITHMS;\n\n/**\n * HMAC (symmetric) JWT options.\n * Uses a shared secret to sign and verify tokens.\n */\nexport interface JwtHmacOptions {\n  /** Shared secret used to verify HMAC signatures. */\n  secret: string;\n  /**\n   * HMAC algorithm to accept. Default: `\"HS256\"`.\n   * The helper rejects tokens whose `alg` header does not match.\n   */\n  algorithm?: HmacAlgorithm;\n  /**\n   * Clock skew tolerance in seconds for `exp` and `nbf` checks.\n   * Default: `0` (no tolerance).\n   */\n  clockToleranceSec?: number;\n  /**\n   * Expected `iss` claim. Tokens whose `iss` does not match are rejected.\n   * Required to prevent cross-issuer token replay.\n   */\n  issuer: string | string[];\n  /**\n   * Expected `aud` claim. Pass `\"*\"` to explicitly skip audience validation\n   * (cross-audience token replay becomes possible -- use only when the IdP\n   * does not emit `aud`, e.g. Clerk with no API audience configured).\n   * Required to prevent cross-audience token replay.\n   */\n  audience: JwtAudience;\n  /** Optional per-claim overrides for non-standard IdPs. */\n  claims?: ClaimMappers;\n}\n\n/**\n * RSA (asymmetric) JWT options.\n * Uses a public key to verify signatures.\n */\nexport interface JwtRsaOptions {\n  /** PEM-encoded public key or certificate used to verify RSA signatures. */\n  publicKey: string;\n  /**\n   * RSA algorithm to accept. Default: `\"RS256\"`.\n   * The helper rejects tokens whose `alg` header does not match.\n   */\n  algorithm?: RsaAlgorithm;\n  /**\n   * Clock skew tolerance in seconds for `exp` and `nbf` checks.\n   * Default: `0` (no tolerance).\n   */\n  clockToleranceSec?: number;\n  /**\n   * Expected `iss` claim. Tokens whose `iss` does not match are rejected.\n   * Required to prevent cross-issuer token replay.\n   */\n  issuer: string | string[];\n  /**\n   * Expected `aud` claim. Pass `\"*\"` to explicitly skip audience validation\n   * (cross-audience token replay becomes possible -- use only when the IdP\n   * does not emit `aud`, e.g. Clerk with no API audience configured).\n   * Required to prevent cross-audience token replay.\n   */\n  audience: JwtAudience;\n  /** Optional per-claim overrides for non-standard IdPs. */\n  claims?: ClaimMappers;\n}\n\n/**\n * Options for the built-in static-key JWT auth helper.\n * Supports HMAC (symmetric) and RSA (asymmetric) signing.\n *\n * Discriminated by key: pass `secret` for HMAC, `publicKey` for RSA.\n */\nexport type JwtAuthOptions = JwtHmacOptions | JwtRsaOptions;\n\n/**\n * Decode and parse the JWT header and payload segments.\n * Returns `null` if the token is malformed or not valid JSON.\n */\nfunction decodeToken(token: string): {\n  headerB64: string;\n  payloadB64: string;\n  signatureB64: string;\n  header: Record<string, unknown>;\n  payload: Record<string, unknown>;\n} | null {\n  const parts = token.split(\".\");\n  if (parts.length !== 3) return null;\n\n  const [headerB64, payloadB64, signatureB64] = parts;\n\n  try {\n    const header = JSON.parse(\n      Buffer.from(headerB64, \"base64url\").toString(),\n    ) as Record<string, unknown>;\n    const payload = JSON.parse(\n      Buffer.from(payloadB64, \"base64url\").toString(),\n    ) as Record<string, unknown>;\n    return { headerB64, payloadB64, signatureB64, header, payload };\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Assert the `exp` and `nbf` temporal claims, throwing on failure. The expired\n * case carries jose's stable `ERR_JWT_EXPIRED` code so downstream log-level\n * classification treats a `jwt()` expiry the same as a `jwks()` / jose expiry\n * (a routine refresh, logged at `debug`, not `warn`). Tokens without an `exp`\n * claim are rejected unconditionally: every token verified by `jwt()` feeds into\n * flows that require a bearer-token expiry (see {@link OAuthPrincipal}).\n */\nfunction assertTemporalClaims(\n  payload: Record<string, unknown>,\n  clockToleranceSec: number,\n): void {\n  const now = Math.floor(Date.now() / 1000);\n\n  if (typeof payload[\"exp\"] !== \"number\") {\n    throw new Error(\"jwt: token is missing the required exp claim\");\n  }\n  // Inclusive, matching jose's `exp <= now - tolerance` and RFC 7519 §4.1.4:\n  // the current time must be *before* `exp`, so `now === exp` is expired.\n  if (now >= payload[\"exp\"] + clockToleranceSec) {\n    throw Object.assign(new Error(\"jwt: token has expired\"), {\n      code: \"ERR_JWT_EXPIRED\",\n    });\n  }\n  if (\n    typeof payload[\"nbf\"] === \"number\" &&\n    now < payload[\"nbf\"] - clockToleranceSec\n  ) {\n    throw new Error(\"jwt: token is not yet valid (nbf)\");\n  }\n}\n\n/**\n * Validate the `iss` and `aud` claims against expected values.\n * When `expectedAudience` is `\"*\"` the audience check is skipped entirely.\n */\nfunction validateIssuerAudience(\n  payload: Record<string, unknown>,\n  expectedIssuer: string | string[],\n  expectedAudience: JwtAudience,\n): boolean {\n  if (typeof payload[\"iss\"] !== \"string\") return false;\n  const allowedIssuers = Array.isArray(expectedIssuer)\n    ? expectedIssuer\n    : [expectedIssuer];\n  if (!allowedIssuers.includes(payload[\"iss\"])) return false;\n\n  if (expectedAudience === \"*\") return true;\n\n  const allowedAudiences = Array.isArray(expectedAudience)\n    ? expectedAudience\n    : [expectedAudience];\n  const aud = payload[\"aud\"];\n  const tokenAud = Array.isArray(aud)\n    ? aud.filter((a): a is string => typeof a === \"string\")\n    : typeof aud === \"string\"\n      ? [aud]\n      : [];\n  if (!tokenAud.some((a) => allowedAudiences.includes(a))) return false;\n\n  return true;\n}\n\n/** Type guard: options contain `secret` (HMAC). */\nfunction isHmac(options: JwtAuthOptions): options is JwtHmacOptions {\n  return \"secret\" in options;\n}\n\n/**\n * Create an HMAC signature verifier.\n */\nfunction createHmacValidator(\n  options: JwtHmacOptions,\n): (token: string) => Promise<OAuthPrincipal> {\n  const {\n    secret,\n    algorithm = \"HS256\",\n    clockToleranceSec = 0,\n    issuer,\n    audience,\n    claims,\n  } = options;\n\n  if (!secret || typeof secret !== \"string\") {\n    throw new TypeError(\"jwt: secret must be a non-empty string\");\n  }\n  if (!(algorithm in HMAC_ALGORITHMS)) {\n    throw new TypeError(\n      `jwt: unsupported algorithm \"${algorithm}\". Supported: ${Object.keys(HMAC_ALGORITHMS).join(\", \")}`,\n    );\n  }\n\n  const digest = HMAC_ALGORITHMS[algorithm];\n\n  return async (token: string): Promise<OAuthPrincipal> => {\n    const decoded = decodeToken(token);\n    if (!decoded) throw new Error(\"jwt: malformed token\");\n\n    const { headerB64, payloadB64, signatureB64, header, payload } = decoded;\n\n    if (header[\"alg\"] !== algorithm)\n      throw new Error(`jwt: unexpected algorithm \"${String(header[\"alg\"])}\"`);\n\n    const hmac = createHmac(digest, secret);\n    hmac.update(`${headerB64}.${payloadB64}`);\n    const expectedSig = hmac.digest(\"base64url\");\n\n    if (!timingSafeStringEqual(expectedSig, signatureB64)) {\n      throw new Error(\"jwt: invalid signature\");\n    }\n\n    assertTemporalClaims(payload, clockToleranceSec);\n    if (!validateIssuerAudience(payload, issuer, audience))\n      throw new Error(\"jwt: invalid issuer or audience\");\n\n    return principalFromJwtPayload(payload, {\n      kind: \"jwt\",\n      ...(claims !== undefined && { claims }),\n    });\n  };\n}\n\n/**\n * Create an RSA signature verifier.\n */\nfunction createRsaValidator(\n  options: JwtRsaOptions,\n): (token: string) => Promise<OAuthPrincipal> {\n  const {\n    publicKey,\n    algorithm = \"RS256\",\n    clockToleranceSec = 0,\n    issuer,\n    audience,\n    claims,\n  } = options;\n\n  if (!publicKey || typeof publicKey !== \"string\") {\n    throw new TypeError(\"jwt: publicKey must be a non-empty PEM string\");\n  }\n  if (!(algorithm in RSA_ALGORITHMS)) {\n    throw new TypeError(\n      `jwt: unsupported algorithm \"${algorithm}\". Supported: ${Object.keys(RSA_ALGORITHMS).join(\", \")}`,\n    );\n  }\n\n  const verifyAlgorithm = RSA_ALGORITHMS[algorithm];\n\n  return async (token: string): Promise<OAuthPrincipal> => {\n    const decoded = decodeToken(token);\n    if (!decoded) throw new Error(\"jwt: malformed token\");\n\n    const { headerB64, payloadB64, signatureB64, header, payload } = decoded;\n\n    if (header[\"alg\"] !== algorithm)\n      throw new Error(`jwt: unexpected algorithm \"${String(header[\"alg\"])}\"`);\n\n    const verifier = createVerify(verifyAlgorithm);\n    verifier.update(`${headerB64}.${payloadB64}`);\n\n    if (!verifier.verify(publicKey, signatureB64, \"base64url\")) {\n      throw new Error(\"jwt: invalid signature\");\n    }\n\n    assertTemporalClaims(payload, clockToleranceSec);\n    if (!validateIssuerAudience(payload, issuer, audience))\n      throw new Error(\"jwt: invalid issuer or audience\");\n\n    return principalFromJwtPayload(payload, {\n      kind: \"jwt\",\n      ...(claims !== undefined && { claims }),\n    });\n  };\n}\n\n/**\n * Built-in static-key JWT authentication helper.\n * Verifies HMAC or RSA signed JWTs using only `node:crypto` (no external\n * dependencies).\n *\n * Returns an {@link OAuthValidatorAuthOptions} that can be passed directly to\n * `mcpPlugin({ auth: jwt({ ... }) })` or `oauth({ verify: jwt({ ... }) })`.\n * Because the return type guarantees an {@link OAuthPrincipal}, it is also\n * structurally assignable wherever a plain `ValidatorAuthOptions` is accepted.\n *\n * On success the validator returns an {@link OAuthPrincipal} (`kind: \"jwt\"`)\n * populated from standard JWT claims (`sub`, `iss`, `aud`, `exp`, `scope`,\n * etc.) with the full decoded payload available in `claims`.\n *\n * Security: `issuer` is required to bind tokens to the expected IdP and prevent\n * cross-issuer replay. `audience` is required (or explicitly set to `\"*\"` to\n * opt out) to bind tokens to this resource and prevent cross-audience replay.\n * Tokens without an `exp` claim are always rejected.\n *\n * @example\n * ```ts\n * import { mcpPlugin, jwt } from \"@routecraft/ai\";\n *\n * // HMAC (symmetric): shared secret\n * mcpPlugin({\n *   transport: \"http\",\n *   auth: jwt({\n *     secret: process.env.JWT_SECRET!,\n *     issuer: \"https://idp.example.com\",\n *     audience: \"https://mcp.example.com\",\n *   }),\n * });\n *\n * // RSA (asymmetric): public key only\n * mcpPlugin({\n *   transport: \"http\",\n *   auth: jwt({\n *     algorithm: \"RS256\",\n *     publicKey: process.env.JWT_PUBLIC_KEY!,\n *     issuer: \"https://idp.example.com\",\n *     audience: \"https://mcp.example.com\",\n *   }),\n * });\n * ```\n */\nexport function jwt(options: JwtAuthOptions): OAuthValidatorAuthOptions {\n  assertIssuerAudience(\"jwt\", options.issuer, options.audience);\n  const validator = isHmac(options)\n    ? createHmacValidator(options)\n    : createRsaValidator(options);\n\n  return {\n    validator,\n    issuer: options.issuer,\n    ...(options.clockToleranceSec !== undefined && {\n      clockToleranceSec: options.clockToleranceSec,\n    }),\n  };\n}\n","import type {\n  ActorMatcher,\n  ClaimMappers,\n  JwtAudience,\n  OAuthPrincipal,\n  Principal,\n} from \"./types.ts\";\n\nfunction stringClaim(value: unknown): string | undefined {\n  return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction isNonEmpty(value: string | string[] | undefined): boolean {\n  if (typeof value === \"string\") return value.length > 0;\n  if (Array.isArray(value))\n    return (\n      value.length > 0 &&\n      value.every((v) => typeof v === \"string\" && v.length > 0)\n    );\n  return false;\n}\n\n/**\n * Assert that `issuer` is supplied and `audience` is either a non-empty value\n * or the `\"*\"` sentinel. Shared by `jwt()` and `jwks()` so the error wording\n * and the exact validation shape stay in sync.\n *\n * @internal\n */\nexport function assertIssuerAudience(\n  kind: \"jwt\" | \"jwks\",\n  issuer: string | string[] | undefined,\n  audience: JwtAudience | undefined,\n): void {\n  if (!isNonEmpty(issuer)) {\n    throw new TypeError(\n      `${kind}: \\`issuer\\` is required. Set it to the expected \\`iss\\` claim value(s) to prevent cross-issuer token replay.`,\n    );\n  }\n  if (audience === undefined || audience === null) {\n    throw new TypeError(\n      `${kind}: \\`audience\\` is required. Set it to the expected \\`aud\\` value(s), or pass \"*\" to skip audience validation (cross-audience replay risk).`,\n    );\n  }\n  if (audience === \"*\") return;\n  if (!isNonEmpty(audience)) {\n    throw new TypeError(\n      `${kind}: \\`audience\\` must be a non-empty string or array, or \"*\" to skip the check.`,\n    );\n  }\n}\n\n/**\n * Map a verified JWT payload to an {@link OAuthPrincipal}.\n *\n * Subject fallback order: `claims.subject(payload)` -> `sub` -> `client_id`\n * -> `azp`. This supports client-credentials tokens (often no `sub`) and IdPs\n * that emit only `azp`.\n *\n * Callers must ensure `exp` is already verified (jwt() enforces it before\n * calling; jwks() passes `requiredClaims: [\"exp\"]` to `jose.jwtVerify`). This\n * function throws if `exp` is missing, upholding the {@link OAuthPrincipal}\n * contract at the boundary.\n *\n * Package-internal helper shared between `jwt.ts` and `jwks.ts`. Never\n * re-exported from `packages/routecraft/src/index.ts`; do not import from\n * outside `src/auth/`.\n *\n * @internal\n */\nexport function principalFromJwtPayload(\n  payload: Record<string, unknown>,\n  options: { kind: \"jwt\" | \"jwks\"; claims?: ClaimMappers },\n): OAuthPrincipal {\n  const sub = stringClaim(payload[\"sub\"]);\n  const payloadClientId = stringClaim(payload[\"client_id\"]);\n  const azp = stringClaim(payload[\"azp\"]);\n\n  const subject =\n    options.claims?.subject?.(payload) ?? sub ?? payloadClientId ?? azp;\n  if (typeof subject !== \"string\" || subject.length === 0) {\n    throw new TypeError(\n      `${options.kind}: verified token has no subject. Expected \\`sub\\`, \\`client_id\\`, or \\`azp\\`; provide claims.subject to map from a non-standard field.`,\n    );\n  }\n\n  const payloadClientIdOrAzp = payloadClientId ?? azp;\n  const clientIdValue =\n    options.claims?.clientId?.(payload) ?? payloadClientIdOrAzp;\n\n  const audienceRaw = payload[\"aud\"];\n  const audience = Array.isArray(audienceRaw)\n    ? audienceRaw.filter((a): a is string => typeof a === \"string\")\n    : typeof audienceRaw === \"string\"\n      ? [audienceRaw]\n      : undefined;\n\n  if (typeof payload[\"exp\"] !== \"number\") {\n    throw new TypeError(\n      `${options.kind}: verified token has no \\`exp\\` claim. Tokens composed into OAuth / MCP bearer flows must carry an expiry.`,\n    );\n  }\n\n  const principal: OAuthPrincipal = {\n    kind: options.kind,\n    scheme: \"bearer\",\n    subject,\n    expiresAt: payload[\"exp\"],\n    claims: payload,\n  };\n\n  if (clientIdValue !== undefined) principal.clientId = clientIdValue;\n\n  const email = stringClaim(payload[\"email\"]);\n  if (email) principal.email = email;\n\n  const name = stringClaim(payload[\"name\"]);\n  if (name) principal.name = name;\n\n  if (typeof payload[\"iss\"] === \"string\") principal.issuer = payload[\"iss\"];\n  if (audience !== undefined) principal.audience = audience;\n\n  // Presence-checked for the same reason as `roles` below: scopes grant\n  // authority (authorize() reads them for RC5038), so a mapper that\n  // deliberately returns undefined must not have the top-level `scope`\n  // claim silently reinstated.\n  const scopes = options.claims?.scopes\n    ? options.claims.scopes(payload)\n    : typeof payload[\"scope\"] === \"string\"\n      ? (payload[\"scope\"] as string).split(\" \").filter(Boolean)\n      : undefined;\n  if (scopes !== undefined) principal.scopes = scopes;\n\n  // Presence-checked like the delegation mappers below, not `??`-chained:\n  // roles grant authority, so a mapper that deliberately returns undefined\n  // (e.g. a Keycloak realm_access mapper on a token without realm_access)\n  // must not have a top-level `roles` claim silently reinstated.\n  const roles = options.claims?.roles\n    ? options.claims.roles(payload)\n    : Array.isArray(payload[\"roles\"])\n      ? (payload[\"roles\"] as unknown[]).filter(\n          (r): r is string => typeof r === \"string\",\n        )\n      : undefined;\n  if (roles !== undefined) principal.roles = roles;\n\n  // Same fail-closed discipline as `sub_profile` inside act / may_act\n  // entries: a present-but-malformed profile must not silently leave the\n  // principal unclassified, or a predicate written as an exclusion\n  // (p.subjectProfile !== 'ai_agent') would pass the malformed token.\n  const subProfileRaw = payload[\"sub_profile\"];\n  if (subProfileRaw !== undefined) {\n    const subjectProfile = stringClaim(subProfileRaw);\n    if (subjectProfile === undefined) {\n      throw new TypeError(\n        `${options.kind}: verified token has a malformed \\`sub_profile\\` claim (expected a non-empty string). Refusing rather than leaving the principal unclassified.`,\n      );\n    }\n    principal.subjectProfile = subjectProfile;\n  }\n\n  // Both delegation claims fail closed when present but unparseable (see\n  // the parsers). A supplied mapper replaces the default parse ENTIRELY,\n  // including its undefined results: presence-checked, not `??`-chained,\n  // because a mapper that deliberately returns undefined for an\n  // RFC-8693-shaped claim must not have the default parser silently\n  // reinstate the actor or restriction it decided against.\n  const actor = options.claims?.actor\n    ? options.claims.actor(payload)\n    : actorFromActClaim(payload[\"act\"], options.kind);\n  if (actor !== undefined) principal.actor = actor;\n\n  const mayAct = options.claims?.mayAct\n    ? options.claims.mayAct(payload)\n    : mayActFromClaim(payload[\"may_act\"], options.kind);\n  if (mayAct !== undefined) principal.mayAct = mayAct;\n\n  return principal;\n}\n\n/**\n * Maximum `act` nesting depth accepted from a token. RFC 8693 places no\n * bound on the chain, but the parse is recursive and the depth beyond a\n * route's `maxDelegationDepth` is never used, so an unbounded chain buys a\n * caller nothing but stack pressure. Exceeding the cap rejects the token\n * rather than truncating it: a silently shortened chain would misreport the\n * current actor.\n */\nconst MAX_ACT_DEPTH = 16;\n\n/**\n * Read an optional string field off a delegation-claim entry, failing\n * closed on a present-but-malformed value. Dropping a malformed\n * constraint would change the claim's meaning: a dropped `iss` on an\n * `act` entry misidentifies the actor (a same-named actor from another\n * issuer would match issuer-less matchers), and a dropped constraint on\n * a `may_act` entry widens the restriction the token stated.\n *\n * @internal\n */\nfunction optionalConstraint(\n  record: Record<string, unknown>,\n  key: string,\n  claim: \"act\" | \"may_act\",\n  kind: \"jwt\" | \"jwks\",\n): string | undefined {\n  const value = record[key];\n  if (value === undefined) return undefined;\n  const parsed = stringClaim(value);\n  if (parsed === undefined) {\n    throw new TypeError(\n      `${kind}: verified token has a \\`${claim}\\` entry whose \\`${key}\\` is not a non-empty string. Refusing rather than dropping the constraint; provide claims.${claim === \"act\" ? \"actor\" : \"mayAct\"} to map a non-standard shape.`,\n    );\n  }\n  return parsed;\n}\n\n/**\n * Map an RFC 8693 section 4.1 `act` claim (possibly nested) to a\n * {@link Principal} actor chain. The outermost entry is the current actor.\n *\n * **Fails closed.** RFC 8693 requires `sub` on every `act` entry. A present\n * but unparseable claim THROWS rather than resolving to `undefined`,\n * because a dropped actor is not a neutral outcome: it promotes a delegated\n * token to a direct call, which is exactly what the `authorize({ actor })`\n * default of `'none'` exists to refuse. Deployments whose IdP identifies\n * actors by a non-standard claim (for example `client_id` on a\n * client-credentials actor) map it explicitly via `ClaimMappers.actor`.\n *\n * Nested actors are plain objects at construction; the verifier boundary\n * brands and deep-freezes the chain through `markAuthentic`.\n *\n * @internal\n */\nfunction actorFromActClaim(\n  act: unknown,\n  kind: \"jwt\" | \"jwks\",\n  depth = 1,\n): Principal | undefined {\n  // Only an ABSENT claim is a direct call. A present `act: null` is a\n  // malformed delegation claim and must reject like any other\n  // unparseable shape, or a delegated token could pass actor: 'none'.\n  if (act === undefined) return undefined;\n  if (depth > MAX_ACT_DEPTH) {\n    throw new TypeError(\n      `${kind}: verified token has an \\`act\\` chain deeper than ${MAX_ACT_DEPTH}. Refusing the token rather than truncating the delegation chain.`,\n    );\n  }\n  if (typeof act !== \"object\" || act === null || Array.isArray(act)) {\n    throw new TypeError(\n      `${kind}: verified token has a non-object \\`act\\` claim. RFC 8693 section 4.1 requires a JSON object identifying the current actor; provide claims.actor to map a non-standard shape.`,\n    );\n  }\n  const record = act as Record<string, unknown>;\n  const subject = stringClaim(record[\"sub\"]);\n  if (subject === undefined) {\n    throw new TypeError(\n      `${kind}: verified token has an \\`act\\` claim without a \\`sub\\`. An actor the policy layer cannot identify must not be silently dropped, which would let a delegated token pass an actor: 'none' route; provide claims.actor to map a non-standard shape.`,\n    );\n  }\n  const actor: Principal = { kind, scheme: \"bearer\", subject };\n  const issuer = optionalConstraint(record, \"iss\", \"act\", kind);\n  if (issuer !== undefined) actor.issuer = issuer;\n  const profile = optionalConstraint(record, \"sub_profile\", \"act\", kind);\n  if (profile !== undefined) actor.subjectProfile = profile;\n  const nested = actorFromActClaim(record[\"act\"], kind, depth + 1);\n  if (nested !== undefined) actor.actor = nested;\n  return actor;\n}\n\n/**\n * Map an RFC 8693 section 4.4 `may_act` claim to {@link ActorMatcher}\n * entries. The wire claim is a single JSON object naming one permitted\n * party; an array of such objects is also accepted since multi-party\n * deployments emit it in practice.\n *\n * **Fails closed**, for the same reason as {@link actorFromActClaim} and in\n * the same direction: `may_act` is a RESTRICTION, so a present-but-\n * unparseable claim must never resolve to `undefined`, which `delegate()`\n * reads as \"no restriction\" and would turn a narrowing claim into a\n * permissive one. Map non-standard shapes with `ClaimMappers.mayAct`.\n *\n * @internal\n */\nfunction mayActFromClaim(\n  mayAct: unknown,\n  kind: \"jwt\" | \"jwks\",\n): ActorMatcher[] | undefined {\n  // Only an ABSENT claim means unrestricted. `may_act: null` is a\n  // malformed restriction and rejects (the singleton path below throws\n  // on null); an empty array is a stated restriction that permits\n  // nobody and is preserved as such, never widened to undefined.\n  if (mayAct === undefined) return undefined;\n  const entries = Array.isArray(mayAct) ? mayAct : [mayAct];\n  const matchers: ActorMatcher[] = [];\n  for (const entry of entries) {\n    if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n      throw new TypeError(\n        `${kind}: verified token has a malformed \\`may_act\\` entry (expected a JSON object). Refusing rather than treating a delegation restriction as absent; provide claims.mayAct to map a non-standard shape.`,\n      );\n    }\n    const record = entry as Record<string, unknown>;\n    const subject = stringClaim(record[\"sub\"]);\n    if (subject === undefined) {\n      throw new TypeError(\n        `${kind}: verified token has a \\`may_act\\` entry without a \\`sub\\`. Refusing rather than treating a delegation restriction as absent; provide claims.mayAct to map a non-standard shape.`,\n      );\n    }\n    const matcher: ActorMatcher = { subject };\n    // Carry the narrowing constraints the wire claim expressed, and\n    // reject present-but-malformed ones. Dropping either would widen the\n    // matcher relative to what the token stated.\n    const issuer = optionalConstraint(record, \"iss\", \"may_act\", kind);\n    if (issuer !== undefined) matcher.issuer = issuer;\n    const profile = optionalConstraint(record, \"sub_profile\", \"may_act\", kind);\n    if (profile !== undefined) matcher.profile = profile;\n    const rolesRaw = record[\"roles\"];\n    if (rolesRaw !== undefined) {\n      if (\n        !Array.isArray(rolesRaw) ||\n        !rolesRaw.every((r) => typeof r === \"string\" && r.length > 0)\n      ) {\n        throw new TypeError(\n          `${kind}: verified token has a \\`may_act\\` entry whose \\`roles\\` is not an array of non-empty strings. Refusing rather than dropping the constraint; provide claims.mayAct to map a non-standard shape.`,\n        );\n      }\n      if (rolesRaw.length > 0) matcher.roles = rolesRaw as string[];\n    }\n    matchers.push(matcher);\n  }\n  return matchers;\n}\n","import type {\n  ClaimMappers,\n  JwtAudience,\n  OAuthValidatorAuthOptions,\n} from \"./types.ts\";\nimport { assertIssuerAudience, principalFromJwtPayload } from \"./jwt-utils.ts\";\nimport { loadOptionalPeer } from \"../adapters/shared/optional-peer.ts\";\n\n/**\n * Loader for the `jose` driver. Exposed as a mutable seam so tests can\n * substitute an implementation that simulates the missing-peer path\n * without `vi.mock(\"jose\", ...)`, which surfaces a generic vitest wrapper\n * error rather than the underlying ERR_MODULE_NOT_FOUND and defeats the\n * package-name discrimination loadOptionalPeer relies on.\n * @internal\n */\nexport const __jwksLoaders = {\n  loadJose: (): Promise<JoseSubset> =>\n    loadOptionalPeer(() => import(\"jose\"), {\n      consumer: \"jwks verification\",\n      packageName: \"jose\",\n    }) as unknown as Promise<JoseSubset>,\n};\n\n/**\n * Narrow subset of `jose` the JWKS verifier uses. Declared so the verifier\n * has real types even when the optional peer dependency is not resolvable at\n * compile time.\n */\ninterface JoseSubset {\n  createRemoteJWKSet: (\n    url: URL,\n  ) => (header: unknown, input: unknown) => Promise<unknown>;\n  jwtVerify: (\n    token: string,\n    key: unknown,\n    options: {\n      issuer?: string | string[];\n      audience?: string | string[];\n      algorithms?: string[];\n      clockTolerance?: number;\n      requiredClaims?: string[];\n    },\n  ) => Promise<{ payload: Record<string, unknown> }>;\n}\n\n/**\n * Default allowlist of JWS algorithms accepted by `jwks()`.\n * Asymmetric only; symmetric `HS*` algorithms are excluded because a JWKS\n * containing an `oct` key that a JWT-issuing attacker can reproduce would\n * enable algorithm-confusion attacks.\n */\nconst DEFAULT_JWKS_ALGORITHMS = [\n  \"RS256\",\n  \"RS384\",\n  \"RS512\",\n  \"PS256\",\n  \"PS384\",\n  \"PS512\",\n  \"ES256\",\n  \"ES384\",\n  \"ES512\",\n  \"EdDSA\",\n];\n\n/**\n * Options for the JWKS-backed JWT auth helper.\n */\nexport interface JwksOptions {\n  /**\n   * JWKS endpoint URL used to fetch the IdP's signing keys.\n   * Keys are cached and rotated by `jose`'s `createRemoteJWKSet`.\n   */\n  jwksUrl: string | URL;\n  /**\n   * Expected `iss` claim. Tokens whose issuer does not match are rejected,\n   * preventing cross-issuer replay.\n   */\n  issuer: string | string[];\n  /**\n   * Expected `aud` claim. Pass `\"*\"` to explicitly skip audience validation\n   * (cross-audience token replay becomes possible -- use only when the IdP\n   * does not emit `aud`, e.g. Clerk with no API audience configured).\n   * Required to prevent cross-audience token replay.\n   */\n  audience: JwtAudience;\n  /**\n   * Accepted JWS algorithms. Defaults to the asymmetric `RS*`/`PS*`/`ES*`/`EdDSA`\n   * family. Restrict further if the IdP only uses a single algorithm; expand\n   * only if the IdP uses something outside the defaults.\n   */\n  algorithms?: string[];\n  /**\n   * Clock skew tolerance in seconds applied to `exp` and `nbf` validation.\n   * Passed through to `jose`'s `jwtVerify`. Default: no tolerance.\n   */\n  clockToleranceSec?: number;\n  /** Optional per-claim overrides for non-standard IdPs. */\n  claims?: ClaimMappers;\n}\n\n/**\n * JWKS-backed JWT authentication helper.\n * Verifies bearer JWTs against a remote JWKS endpoint using `jose`.\n * Keys are cached and rotated automatically. Tokens without an `exp` claim\n * are always rejected (enforced via `jose`'s `requiredClaims`).\n *\n * Returns an {@link OAuthValidatorAuthOptions} that can be passed directly to\n * `mcpPlugin({ auth: jwks({ ... }) })` or `oauth({ verify: jwks({ ... }) })`.\n * Because the return type guarantees an {@link OAuthPrincipal}, it is also\n * structurally assignable wherever a plain `ValidatorAuthOptions` is accepted.\n *\n * On success the validator returns an {@link OAuthPrincipal} (`kind: \"jwks\"`)\n * populated from standard JWT claims (`sub`, `iss`, `aud`, `exp`, `scope`,\n * etc.) with the full decoded payload available in `claims`.\n *\n * Requires the optional peer dependency `jose`:\n * ```sh\n * bun add jose\n * ```\n *\n * @example\n * ```ts\n * import { mcpPlugin, jwks } from \"@routecraft/ai\";\n *\n * // Standalone: just verify bearer JWTs (no OAuth proxy flow)\n * mcpPlugin({\n *   transport: \"http\",\n *   auth: jwks({\n *     jwksUrl: \"https://idp.example.com/.well-known/jwks.json\",\n *     issuer: \"https://idp.example.com\",\n *     audience: \"https://mcp.example.com\",\n *   }),\n * });\n * ```\n */\nexport function jwks(options: JwksOptions): OAuthValidatorAuthOptions {\n  assertIssuerAudience(\"jwks\", options.issuer, options.audience);\n\n  let joseMod: JoseSubset | null = null;\n  let jwkSet: ReturnType<JoseSubset[\"createRemoteJWKSet\"]> | null = null;\n\n  const algorithms = options.algorithms ?? DEFAULT_JWKS_ALGORITHMS;\n\n  return {\n    issuer: options.issuer,\n    ...(options.clockToleranceSec !== undefined && {\n      clockToleranceSec: options.clockToleranceSec,\n    }),\n    validator: async (token: string) => {\n      if (joseMod === null) {\n        joseMod = await __jwksLoaders.loadJose();\n      }\n      if (jwkSet === null) {\n        jwkSet = joseMod.createRemoteJWKSet(\n          new URL(options.jwksUrl.toString()),\n        );\n      }\n\n      const joseOptions: {\n        issuer?: string | string[];\n        audience?: string | string[];\n        algorithms?: string[];\n        clockTolerance?: number;\n        requiredClaims?: string[];\n      } = {\n        issuer: options.issuer,\n        algorithms,\n        requiredClaims: [\"exp\"],\n      };\n\n      if (options.audience !== \"*\") {\n        joseOptions.audience = options.audience as string | string[];\n      }\n      if (options.clockToleranceSec !== undefined) {\n        joseOptions.clockTolerance = options.clockToleranceSec;\n      }\n\n      const { payload } = await joseMod.jwtVerify(token, jwkSet, joseOptions);\n\n      return principalFromJwtPayload(payload as Record<string, unknown>, {\n        kind: \"jwks\",\n        ...(options.claims !== undefined && { claims: options.claims }),\n      });\n    },\n  };\n}\n","import { HeadersKeys, type Exchange } from \"../exchange.ts\";\nimport { rcError, type RoutecraftError } from \"../error.ts\";\nimport type { CallableValidator } from \"../operations/validate.ts\";\nimport { isAuthentic } from \"./authentic.ts\";\nimport { isPrincipalExpired } from \"./expiry.ts\";\nimport { isRestored } from \"./restored.ts\";\nimport { actorMatches } from \"./delegate.ts\";\nimport type { ActorMatcher, Principal, PrincipalProfile } from \"./types.ts\";\n\n/**\n * Machine-readable detail attached to an `RC5038` error's cause, naming\n * exactly what the principal lacked. Read it off `error.cause` to drive a\n * consent flow:\n *\n * ```ts\n * const missing = (err.cause as InsufficientAuthority | undefined)?.missing\n * if (missing?.mode === \"any\") offerChoice(missing.scopes)\n * else if (missing?.scopes) requestGrant(missing.scopes)\n * ```\n *\n * Carries the scopes the principal lacked for a `scopes` refusal, and the\n * whole accepted set for an `anyScope` one, where any single entry would\n * have opened the door.\n *\n * In-process only: `RoutecraftError.toJSON()` serialises the cause's message\n * and stack, not its own properties, so a consumer reading the failure from\n * a serialised event log sees the scope names in the message text but not\n * this structured field.\n */\nexport interface InsufficientAuthority extends Error {\n  missing: {\n    scopes: string[];\n    /**\n     * How to read `scopes`. `\"all\"` lists the required scopes the\n     * principal lacked, every one of them needed. `\"any\"` lists the whole\n     * accepted set of an `anyScope` check, of which ONE suffices, so a\n     * consent flow can offer the choice rather than requesting all of them.\n     *\n     * Optional because an application throwing this shape itself (the\n     * documented workaround before `anyScope` existed) predates the field;\n     * `authorize()` always sets it. Absent means `\"all\"`.\n     */\n    mode?: \"all\" | \"any\";\n  };\n}\n\n/**\n * Refusals raised by an {@link authorize} check, keyed to the id of the\n * route whose exchange was refused.\n *\n * A module-private `WeakMap` rather than a property brand, for the reason\n * `authentic.ts` gives: membership cannot be enumerated, read back, or\n * copied onto another object. The codes `authorize()` throws are shared\n * with adapters that raise them for upstream or operator faults (an IMAP\n * login refused, a delegation misconfigured), so the code alone cannot say\n * whether the caller was refused. Only the origin can, and a copyable brand\n * would let any step dress its own failure up as the caller's.\n *\n * The route id and the refused principal ride along because a refusal\n * can be about someone other than the caller. A route calling another\n * through `direct()` receives the callee's refusal as its own step failure,\n * and a pipeline that swaps in an identity of its own (`.authenticate()`, a\n * delegation) and then checks it refused the instance, not the caller.\n */\ninterface RefusalOrigin {\n  routeId: string | undefined;\n  principal: Principal | undefined;\n}\n\nconst refusals = new WeakMap<object, RefusalOrigin>();\n\nfunction refusal(\n  exchange: Exchange<unknown>,\n  error: RoutecraftError,\n): RoutecraftError {\n  // The validator is public and callable on a hand-built exchange-like\n  // object, which may carry no headers at all.\n  const headers = exchange.headers as Exchange[\"headers\"] | undefined;\n  const routeId = headers?.[HeadersKeys.ROUTE_ID];\n  refusals.set(error, {\n    routeId: typeof routeId === \"string\" ? routeId : undefined,\n    principal: headers?.[HeadersKeys.AUTH_PRINCIPAL] as Principal | undefined,\n  });\n  return error;\n}\n\n/**\n * Whether `error` is a refusal raised by an {@link authorize} check, as\n * opposed to the same code thrown by anything else.\n *\n * Doors use this to answer a refusal with a client status (401 / 403)\n * while an adapter's `RC5012` for a rejected upstream login stays a server\n * fault. With `caller`, only a refusal of that caller counts: raised on an\n * exchange of the route the door dispatched, about the very principal the\n * door admitted (compared by reference, the way identity is carried per\n * hop). A refusal raised further down the call chain, or of an identity the\n * pipeline substituted, is the instance's fault and does not match.\n *\n * @param error - Any thrown value\n * @param caller - The route the door dispatched and the principal it\n *   admitted (`undefined` when it admitted none)\n * @returns `true` when `authorize()` raised this exact error object, for\n *   `caller` when given\n */\nexport function isAuthorizationRefusal(\n  error: unknown,\n  caller?: { routeId: string; principal: Principal | undefined },\n): error is RoutecraftError {\n  if (typeof error !== \"object\" || error === null) return false;\n  const origin = refusals.get(error);\n  if (origin === undefined) return false;\n  return (\n    caller === undefined ||\n    (origin.routeId === caller.routeId && origin.principal === caller.principal)\n  );\n}\n\n/**\n * Constraint on who is driving the request (the outermost `actor`).\n *\n * - `'none'`: reject when any actor is present. This is the DEFAULT: a\n *   capability is not reachable through delegation unless it says so, per\n *   the security-defaults policy (production-safe unconfigured default).\n * - `'any'`: accept any actor (and no actor).\n * - {@link ActorMatcher}: require an actor matching the given identity.\n * - Array: OR across entries; include `'none'` to also accept direct calls.\n * - Predicate: full custom check over `(actor, subject)`.\n *\n * Per RFC 8693 section 4.1, only the OUTERMOST actor is considered; prior\n * actors in a nested chain are audit data and never a policy input.\n */\nexport type ActorSpec =\n  | \"none\"\n  | \"any\"\n  | ActorMatcher\n  | Array<\"none\" | ActorMatcher>\n  | ((actor: Principal | undefined, subject: Principal) => boolean);\n\n/**\n * Constraint on whose authority is being exercised (the subject). All\n * provided fields must match; array-valued fields are an OR across values.\n */\nexport interface SubjectMatcher {\n  /** Subject id(s) to accept. */\n  subject?: string | string[];\n  /** Issuer the subject is scoped to. */\n  issuer?: string;\n  /** Entity profile(s) to accept (e.g. restrict a route to `ai_agent`). */\n  profile?: PrincipalProfile | PrincipalProfile[];\n}\n\n/**\n * Options accepted by {@link authorize}. All criteria are AND-combined: the\n * principal must satisfy every provided constraint to pass the check.\n */\nexport interface AuthorizeOptions {\n  /**\n   * Required roles. The principal must carry every listed role on\n   * `principal.roles`. Roles are SUBJECT attributes: they describe who the\n   * action is for and pass through delegation unchanged, so this checks the\n   * subject even when an actor is driving. Defaults to no role check.\n   */\n  roles?: string[];\n  /**\n   * Required scopes. The principal must carry every listed scope on\n   * `principal.scopes`. Scopes are CREDENTIAL capabilities: delegation\n   * intersects them at every hop, so this checks the effective (narrowed)\n   * set. Defaults to no scope check.\n   */\n  scopes?: string[];\n  /**\n   * Required scopes, any ONE of which admits the principal, where `scopes`\n   * requires every one. For a scope family whose variants are\n   * interchangeable at the door (`leave:read`, `leave:read:self`,\n   * `leave:read:base`): any of them opens it, and the exact variant held\n   * narrows what the pipeline returns further down.\n   *\n   * Refuses with RC5038 naming the whole accepted set rather than one\n   * entry, because no single entry was required and a consent flow should\n   * be able to offer the caller the choice.\n   *\n   * Composes with `scopes` as an AND of the two conditions: every entry of\n   * `scopes`, and at least one entry of `anyScope`. Defaults to no check.\n   *\n   * An empty array is refused with RC2001 when the validator is built,\n   * rather than read as no check. It is the one list on these options whose\n   * empty form is not vacuously satisfied: a requirement of no scopes admits\n   * everyone, while an accepted set naming nobody admits nobody, and a set\n   * computed empty would otherwise remove a route's only scope gate in\n   * silence. Omit the option to mean no check.\n   */\n  anyScope?: string[];\n  /**\n   * Whether `scopes` and `anyScope` may also be satisfied from the ACTOR's\n   * scopes. Defaults to `false`, so a route that does not ask is unchanged.\n   *\n   * With `true` the scope checks read the subject's ring plus the OUTERMOST\n   * actor's, which is how an agent exercises its own standing authority on\n   * a caller's behalf: an agent legitimately holds scopes nobody who asks\n   * it for something holds. Only the outermost actor is read, matching the\n   * rule `actor` already follows (RFC 8693 section 4.1); prior actors in a\n   * nested chain stay audit data.\n   *\n   * Never applies to `roles` under any combination. A role is what the\n   * principal IS; scopes are what a keyring CARRIES, and only keyrings are\n   * inheritable. An agent driving a request does not become the subject.\n   *\n   * A no-op under the default `actor: 'none'`, which admits no actor for\n   * the flag to read. That combination is a harmless misconfiguration\n   * rather than an error.\n   *\n   * It reads `actor.scopes`, so the actor has to carry some. An actor minted\n   * by `delegate()` does. An actor parsed from a token's RFC 8693 `act`\n   * claim does NOT: the claim has no scope member, and the parser will not\n   * invent authority from an unstandardised one. For token-borne delegation,\n   * map whatever your IdP emits with `ClaimMappers.actor`, or the check sees\n   * an empty ring and refuses.\n   *\n   * The check reads the UNION of the two rings, so a caller passes on their\n   * own scopes or on the agent's. The agent is not a cap: `delegate()`\n   * deliberately does not intersect delegated scopes with the actor's own,\n   * and this flag does not either. What an agent's grant bounds is the\n   * additional authority a caller gains by going through it, which is why\n   * this is opt-in per route rather than a context-wide setting: a gate that\n   * must stay on the subject's own ring simply does not set it.\n   */\n  effective?: boolean;\n  /**\n   * Custom predicate for advanced checks. Return `false` to reject. Runs\n   * after the built-in checks.\n   */\n  predicate?: (principal: Principal) => boolean;\n  /**\n   * Clock skew tolerance in seconds applied to the `expiresAt` check.\n   * Matches the semantics of `jwt({ clockToleranceSec })` and\n   * `jwks({ clockToleranceSec })`: a token whose `expiresAt` is less than\n   * `clockToleranceSec` seconds in the past is still accepted. Defaults to\n   * `0` (strict). Set to the same value used on the source-side verifier so\n   * a token accepted at the route boundary is not rejected mid-pipeline by\n   * a fraction of a second.\n   */\n  clockToleranceSec?: number;\n  /**\n   * Constrain whose authority is exercised. Throws RC5035 on mismatch.\n   * Defaults to no subject constraint.\n   */\n  subject?: SubjectMatcher | ((subject: Principal) => boolean);\n  /**\n   * Constrain who is driving. Defaults to `'none'`: a principal carrying an\n   * actor (a delegate acting on the subject's behalf) is rejected with\n   * RC5034 unless the route explicitly admits one. See {@link ActorSpec}.\n   */\n  actor?: ActorSpec;\n  /**\n   * Maximum delegation chain length (number of nested actors). Applies only\n   * once the `actor` spec admits an actor at all. Defaults to `1`: one\n   * delegation hop is accepted, a re-delegated chain (agent to sub-agent)\n   * throws RC5036 until a route raises the limit deliberately.\n   */\n  maxDelegationDepth?: number;\n}\n\n/**\n * Depth of the actor chain: 0 for no actor, 1 per nesting level.\n *\n * Stops at `limit + 1` because the caller only ever asks \"is this deeper\n * than the limit\", never \"how much deeper\". The bound doubles as the cycle\n * guard: a hand-assembled self-referential chain would otherwise spin here\n * forever, turning a policy check into a hung event loop.\n */\nfunction chainDepth(principal: Principal, limit: number): number {\n  const ceiling = Number.isFinite(limit) ? Math.max(0, limit) + 1 : 1;\n  let depth = 0;\n  let current = principal.actor;\n  while (current !== undefined && depth < ceiling) {\n    depth += 1;\n    current = current.actor;\n  }\n  return depth;\n}\n\nfunction subjectMatches(\n  principal: Principal,\n  matcher: SubjectMatcher,\n): boolean {\n  if (matcher.subject !== undefined) {\n    const subjects = Array.isArray(matcher.subject)\n      ? matcher.subject\n      : [matcher.subject];\n    if (!subjects.includes(principal.subject)) return false;\n  }\n  if (matcher.issuer !== undefined && principal.issuer !== matcher.issuer) {\n    return false;\n  }\n  if (matcher.profile !== undefined) {\n    const profiles: PrincipalProfile[] = Array.isArray(matcher.profile)\n      ? matcher.profile\n      : [matcher.profile];\n    if (\n      principal.subjectProfile === undefined ||\n      !profiles.includes(principal.subjectProfile)\n    ) {\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction actorAllowed(\n  spec: ActorSpec,\n  actor: Principal | undefined,\n  subject: Principal,\n): boolean {\n  if (typeof spec === \"function\") return spec(actor, subject);\n  if (spec === \"any\") return true;\n  if (spec === \"none\") return actor === undefined;\n  if (Array.isArray(spec)) {\n    return spec.some((entry) =>\n      entry === \"none\"\n        ? actor === undefined\n        : actor !== undefined && actorMatches(actor, entry),\n    );\n  }\n  return actor !== undefined && actorMatches(actor, spec);\n}\n\n/**\n * Build a {@link CallableValidator} that **checks** the exchange carries an\n * authenticated principal and (optionally) that the principal has every\n * required role and scope, an admissible subject, and an admissible actor.\n * This is a verification primitive: it asserts an existing identity meets\n * the criteria. It does NOT issue, mint, or attach credentials to the\n * exchange (use `.authenticate()` / `.delegate()` for that), and it trusts\n * only principals established by a trusted origin.\n *\n * Delegation awareness (RFC 8693): `roles` are checked on the subject\n * (they pass through delegation), `scopes` on the effective narrowed set,\n * and the `actor` spec on the OUTERMOST actor only; nested prior actors are\n * audit data. The default `actor: 'none'` means a route is not reachable\n * through delegation unless it says so.\n *\n * Scope checks read the subject's ring alone unless `effective: true`\n * widens them to the outermost actor's as well, which is how an agent\n * exercises its own standing authority on a caller's behalf. Roles are\n * never widened that way: a role is what the principal IS, and only a\n * keyring is inheritable.\n *\n * Throws `RC5012` when no principal is present, `RC5043` when the\n * principal was restored from a deferral rather than verified live,\n * `RC5023` when a principal is present but was not established by a\n * trusted origin, `RC5020` on\n * expiry, `RC5034` when the actor is not admitted, `RC5035` when the\n * subject is not admitted, `RC5036` when the delegation chain exceeds\n * `maxDelegationDepth`, `RC5015` when the principal fails the role or\n * predicate check, and `RC5038` when a required scope is missing\n * (recoverable; the cause carries `missing.scopes`, naming the whole\n * accepted set for an `anyScope` refusal).\n *\n * Throws `RC2001` when the validator is built with an empty `anyScope`,\n * which would name an accepted set that admits nobody.\n *\n * Every refusal is recognisable through {@link isAuthorizationRefusal}, which\n * is how the `http()` source and the ops dispatch door answer a refusal of\n * the route they dispatched with 401 or 403 rather than 500.\n *\n * Most routes should declare authorization at the route boundary using the\n * pre-from `.authorize()` builder method, which wires this validator as a\n * route-entry guard. Use this function directly with `.validate(...)` only\n * when the check must run mid-pipeline (for example, after an\n * `.authenticate()` or `.delegate()` step, or inside a `.choice()` branch).\n *\n * @example Route-entry guard (preferred)\n * ```ts\n * craft()\n *   .id(\"delete-user\")\n *   .authorize({ roles: [\"admin\"], actor: \"none\" })\n *   .from(mcp({ annotations: { destructiveHint: true } }))\n *   .to(deleteUserDestination)\n * ```\n *\n * @example Admit one named agent alongside direct callers\n * ```ts\n * craft()\n *   .id(\"send-reply\")\n *   .authorize({\n *     scopes: [\"mail:send\"],\n *     actor: [\"none\", { subject: \"agent:aria\", issuer: \"https://acme.example\" }],\n *   })\n *   .from(direct())\n *   .to(smtp())\n * ```\n *\n * @example Any one of a scope family, satisfiable by the agent's own ring\n * ```ts\n * craft()\n *   .id(\"read-leave\")\n *   .authorize({\n *     anyScope: [\"leave:read\", \"leave:read:self\", \"leave:read:base\"],\n *     effective: true,\n *     actor: [\"none\", { subject: \"agent:aria\", issuer: \"https://agents.example\" }],\n *   })\n *   .from(direct())\n *   .to(leaveDestination)\n * ```\n *\n * @example Mid-pipeline check (escape hatch)\n * ```ts\n * import { authorize } from \"@routecraft/routecraft\";\n *\n * craft()\n *   .from(http({ path: \"/admin\", method: \"POST\" }))\n *   .authenticate(() => ({ subject: \"service-account\", roles: [\"admin\"] }))\n *   .validate(authorize({ roles: [\"admin\"] }))\n *   .to(adminDestination)\n * ```\n */\nexport function authorize(\n  options: AuthorizeOptions = {},\n): CallableValidator<unknown, unknown> {\n  const {\n    roles,\n    scopes,\n    anyScope,\n    effective = false,\n    predicate,\n    clockToleranceSec = 0,\n    subject: subjectSpec,\n    actor: actorSpec = \"none\",\n    maxDelegationDepth = 1,\n  } = options;\n  if (anyScope !== undefined && anyScope.length === 0) {\n    throw rcError(\"RC2001\", new Error(\"Empty anyScope\"), {\n      message:\n        \"authorize({ anyScope: [] }) names an accepted set that admits nobody\",\n      suggestion:\n        \"Omit anyScope for no scope check, or list the scopes that admit the caller. An empty accepted set is refused rather than read either way: unlike scopes: [], which is a requirement of nothing and vacuously satisfied, an empty any-of list is satisfiable by nobody, and a set computed empty (a tenant lookup that missed, an unset environment variable) would otherwise remove the route's only scope gate in silence.\",\n    });\n  }\n  return (exchange: Exchange<unknown>) => {\n    const refuse = (...args: Parameters<typeof rcError>): RoutecraftError =>\n      refusal(exchange, rcError(...args));\n    const principal = exchange.principal;\n    if (!principal) {\n      throw refuse(\"RC5012\", new Error(\"No authenticated principal\"), {\n        message: \"Authorization failed: no authenticated principal\",\n        suggestion:\n          \"Configure auth on the source so it emits a Principal (e.g. mcp({ auth: jwt(...) })). For a mid-pipeline check, mint a principal with the .authenticate() operation (or the authenticate() helper) before authorize().\",\n      });\n    }\n\n    // Trust only principals established by a trusted origin: a source-side\n    // verifier (jwt/jwks/oauth) or an explicit authenticate()/delegate()\n    // mint. A plain object written onto headers[\"routecraft.auth.principal\"]\n    // is treated as self-asserted and rejected, so identity cannot be forged\n    // by an incidental header write or by spreading an existing principal\n    // with elevated roles.\n    // A principal rehydrated from a deferral is reported separately from\n    // a self-asserted one. Both are rejected, but the caller's next move\n    // differs: a restored identity needs re-verification against the live\n    // credential, not a mint.\n    if (isRestored(principal)) {\n      throw refuse(\n        \"RC5043\",\n        new Error(\"Principal was restored from a deferral\"),\n        {\n          message:\n            \"Authorization failed: principal was restored from a deferral, not verified live\",\n          suggestion:\n            \"The exchange resumed from durable storage, so its principal is a recorded shape with no live credential behind it. Re-verify the identity after resume (a fresh .authenticate() from a checked credential), or authorize the resume ingress route instead, where the resuming principal is verified live. ex.deferral.resumedBy records who resumed it.\",\n        },\n      );\n    }\n\n    if (!isAuthentic(principal)) {\n      throw refuse(\"RC5023\", new Error(\"Principal is not authentic\"), {\n        message:\n          \"Authorization failed: principal was not established by a trusted origin\",\n        suggestion:\n          'Mint the identity with the .authenticate() operation or the authenticate() helper (or let a source verifier such as jwt()/jwks()/oauth() attach it). A plain object assigned to headers[\"routecraft.auth.principal\"] is not trusted.',\n      });\n    }\n\n    // Boundary semantics (floored, inclusive, fail-closed on non-finite) live\n    // on the shared predicate so this gate and the HTTP bearer middleware can\n    // never disagree by a second.\n    if (isPrincipalExpired(principal, clockToleranceSec)) {\n      throw refuse(\"RC5020\", new Error(\"Token expired\"), {\n        message: \"Authorization failed: token expired during processing\",\n        suggestion:\n          \"The token's `exp` is in the past (or `expiresAt` / `clockToleranceSec` was non-finite). A long-running step likely outlived the credential; the client should refresh and retry. To recover in-route, restructure the pipeline so authorize() runs before the slow step or attach a fresh principal in a .process() before the validator.\",\n      });\n    }\n\n    // Actor gate before role/scope checks: \"you may not be here as a\n    // delegate\" is a different fact from \"you lack a role\", and the actor\n    // decision must not leak which roles would have sufficed.\n    const currentActor = principal.actor;\n    if (!actorAllowed(actorSpec, currentActor, principal)) {\n      throw refuse(\n        \"RC5034\",\n        new Error(\n          currentActor === undefined\n            ? \"Direct calls are not admitted by the actor spec\"\n            : `Actor \"${currentActor.subject}\" is not admitted`,\n        ),\n        {\n          message:\n            currentActor === undefined\n              ? \"Authorization failed: this route requires a delegated actor and the call is direct\"\n              : `Authorization failed: actor \"${currentActor.subject}\" is not permitted to act on the subject's behalf here`,\n          suggestion:\n            \"Declare the permitted actor(s) on the route's authorize({ actor }) (the default 'none' rejects all delegation), or have the permitted party perform the call.\",\n        },\n      );\n    }\n\n    if (currentActor !== undefined) {\n      const depth = chainDepth(principal, maxDelegationDepth);\n      // Fail closed on a non-finite limit, matching the expiresAt /\n      // clockToleranceSec discipline above: `depth > NaN` is always false,\n      // so a misconfigured limit (e.g. Number(unsetEnvVar)) would silently\n      // accept a chain of any depth instead of rejecting it.\n      if (!Number.isFinite(maxDelegationDepth) || depth > maxDelegationDepth) {\n        throw refuse(\n          \"RC5036\",\n          new Error(\n            `Delegation depth ${depth} exceeds maximum ${maxDelegationDepth}`,\n          ),\n          {\n            message: `Authorization failed: delegation chain of depth ${depth} exceeds this route's maximum of ${maxDelegationDepth}`,\n            suggestion:\n              \"Have an agent closer to the subject perform the call, or raise maxDelegationDepth on the route deliberately. Only the outermost actor is a policy input; deeper chains add audit surface, not authority.\",\n          },\n        );\n      }\n    }\n\n    if (subjectSpec !== undefined) {\n      const ok =\n        typeof subjectSpec === \"function\"\n          ? subjectSpec(principal)\n          : subjectMatches(principal, subjectSpec);\n      if (!ok) {\n        throw refuse(\"RC5035\", new Error(\"Subject not permitted\"), {\n          message: `Authorization failed: subject \"${principal.subject}\" is not permitted by this route's subject constraint`,\n          suggestion:\n            \"Check the route's authorize({ subject }) constraint (subject id, issuer, profile) against the caller's identity.\",\n        });\n      }\n    }\n\n    if (roles && roles.length > 0) {\n      const granted = new Set(principal.roles ?? []);\n      const missing = roles.filter((r) => !granted.has(r));\n      if (missing.length > 0) {\n        throw refuse(\n          \"RC5015\",\n          new Error(`Missing required roles: ${missing.join(\", \")}`),\n          {\n            message: `Authorization failed: principal is missing required role(s): ${missing.join(\", \")}`,\n            suggestion:\n              \"Grant the principal the missing role(s) at the IdP, or relax the authorize() requirement.\",\n          },\n        );\n      }\n    }\n\n    if ((scopes && scopes.length > 0) || anyScope !== undefined) {\n      const granted = grantedScopes(principal, effective);\n      if (scopes && scopes.length > 0) {\n        const missing = scopes.filter((scope) => !granted.has(scope));\n        if (missing.length > 0) {\n          throw refusal(exchange, insufficientScope(missing, \"all\"));\n        }\n      }\n      if (\n        anyScope !== undefined &&\n        !anyScope.some((scope) => granted.has(scope))\n      ) {\n        throw refusal(exchange, insufficientScope([...anyScope], \"any\"));\n      }\n    }\n\n    if (predicate && !predicate(principal)) {\n      throw refuse(\"RC5015\", new Error(\"Principal failed predicate check\"), {\n        message: \"Authorization failed: principal failed predicate check\",\n        suggestion:\n          \"Adjust the predicate or the principal's claims so the check passes.\",\n      });\n    }\n\n    return exchange.body;\n  };\n}\n\n/**\n * The scopes a check may draw on: the principal's own, plus the outermost\n * actor's when `effective` widens the ring.\n *\n * The bound is `principal.actor` and nothing deeper, deliberately. Walking\n * the chain would read authority from parties `authorize({ actor })` never\n * considers (RFC 8693 section 4.1), undo the intersection `delegate()`\n * applies at every hop, and let authority accumulate with delegation depth,\n * which fails open where missing authority fails closed.\n */\nfunction grantedScopes(principal: Principal, effective: boolean): Set<string> {\n  const granted = new Set(principal.scopes ?? []);\n  if (effective) {\n    for (const scope of principal.actor?.scopes ?? []) granted.add(scope);\n  }\n  return granted;\n}\n\n/**\n * The RC5038 refusal, carrying `missing.scopes` for a consent flow.\n *\n * RC5038 rather than RC5015: a missing scope is the one recoverable failure\n * (RFC 9470 / RFC 6750 insufficient_scope shape). The identity is valid, so\n * a consent flow could add the scope and the call could be retried. Role and\n * predicate failures stay RC5015 because no ceremony changes who the subject\n * is.\n *\n * `mode` decides what the scope list means. `\"all\"` names the entries the\n * principal lacked, since every one was required. `\"any\"` names the whole\n * accepted set, since no single entry was required and any one of them would\n * have opened the door.\n */\nfunction insufficientScope(\n  scopes: string[],\n  mode: \"all\" | \"any\",\n): RoutecraftError {\n  const detail =\n    mode === \"all\"\n      ? `missing required scope(s): ${scopes.join(\", \")}`\n      : `holding none of the accepted scope(s): ${scopes.join(\", \")}`;\n  return rcError(\n    \"RC5038\",\n    Object.assign(\n      new Error(\n        mode === \"all\"\n          ? `Missing required scopes: ${scopes.join(\", \")}`\n          : `Missing any of the accepted scopes: ${scopes.join(\", \")}`,\n      ),\n      { missing: { scopes, mode } },\n    ) satisfies InsufficientAuthority,\n    {\n      message: `Authorization failed: principal is ${detail}`,\n      suggestion:\n        mode === \"all\"\n          ? \"The identity is valid but lacks scope. Obtain the missing scope(s) via your consent/grant flow (the cause's `missing.scopes` lists them), or grant them at the IdP, then retry.\"\n          : \"The identity is valid but carries none of the accepted scopes. Obtain any ONE of them via your consent/grant flow (the cause's `missing.scopes` lists the full accepted set, so a consent flow can offer the choice), or grant one at the IdP, then retry.\",\n    },\n  );\n}\n\n/**\n * Scopes in `required` the principal does not carry on its own ring.\n *\n * The one scope comparison in the framework. `authorize()` and the ops\n * management tiers both gate on it, and the property an operator is promised,\n * that there is a single scope model rather than two, is only true while they\n * share this function rather than a comment saying they agree.\n *\n * Reads the principal's own scopes only, which is the ring the ops tiers\n * gate on. `authorize()` compares against a ring it builds itself through\n * the shared {@link grantedScopes}, because `effective: true` may widen that\n * ring to the outermost actor's; the widening is a property of that one gate\n * rather than of the scope model, and membership is decided the same way on\n * both paths.\n */\nexport function missingScopes(\n  principal: Principal,\n  required: readonly string[],\n): string[] {\n  const granted = grantedScopes(principal, false);\n  return required.filter((scope) => !granted.has(scope));\n}\n","import type { ActorMatcher, Principal } from \"./types.ts\";\n\n/**\n * Module-private registry of authentic principals.\n *\n * Membership in this `WeakSet` is the authenticity signal. A `WeakSet` is\n * used deliberately instead of a property brand: set membership cannot be\n * enumerated, read back, copied, or transferred. Code that holds a genuine\n * authentic principal (userland receives them via `ex.principal`, `.process()`\n * callbacks, and event payloads) has no way to mark a different object as\n * authentic. A property-based brand would be reflectable via\n * `Object.getOwnPropertySymbols()` even when keyed by a private,\n * non-enumerable symbol, so any holder of a real principal could copy the\n * brand onto a forged object; the `WeakSet` closes that hole.\n *\n * Only {@link markAuthentic} adds to this set, and it is the single point at\n * which trust is conferred.\n *\n * @internal\n */\nconst authentic = new WeakSet<object>();\n\n/**\n * DANGER: every principal passed to this function becomes trusted by\n * `authorize()`. Call it ONLY after you have verified the caller's identity\n * yourself. Passing an unverified or attacker-influenced principal is a\n * privilege-escalation bug, the framework cannot check your work here.\n *\n * Mark a principal as authentic and freeze it. Authenticity is the\n * framework's signal that a principal was established by a trusted origin: an\n * explicit `authenticate()` mint, or a source-side verifier (`jwt()`,\n * `jwks()`, OAuth). `authorize()` trusts only branded principals; a plain\n * object written onto `headers[\"routecraft.auth.principal\"]` is rejected.\n *\n * Always returns a frozen copy (never the input object, so the caller's\n * principal is not mutated or frozen as a side effect), registered in the\n * private authenticity set. Idempotent: a principal that is already authentic\n * is returned unchanged.\n *\n * Returning a frozen object matters: the exchange constructor only clones an\n * unfrozen principal header, so a frozen branded principal flows downstream\n * by reference and keeps its set membership. Always use the return value;\n * never assume the argument was branded in place.\n *\n * This is a trusted primitive, exported for adapter and source authors who\n * verify identity themselves (for example a custom Slack or e-mail source).\n * Application route code should mint identities with `authenticate()` instead.\n */\nexport function markAuthentic<P extends Principal>(principal: P): P {\n  if (isAuthentic(principal)) return principal;\n  const copy = { ...(principal as Principal) };\n  // Clone, then freeze, the policy-bearing structures, not just the top\n  // level. `actor`, `mayAct`, and the policy arrays (`roles`, `scopes`,\n  // `audience`) are access-control inputs: the outermost actor decides\n  // `authorize({ actor })`, `mayAct` decides whether `delegate()` is\n  // permitted, and roles/scopes decide RC5015/RC5038. A shallow freeze\n  // would leave all of them writable through any holder of\n  // `ex.principal`, so an in-process caller could push a role, rewrite\n  // the current actor, or widen the consent list of an already-authentic\n  // identity. Cloning first keeps this function's contract (the caller's\n  // input is neither mutated nor frozen as a side effect): the spread\n  // above copies only references, so freezing in place would freeze the\n  // caller's structures too.\n  cloneDelegationState(copy, principal as Principal);\n  freezeDelegationState(copy);\n  const target = Object.freeze(copy) as P;\n  authentic.add(target);\n  return target;\n}\n\n/**\n * Replace the policy-bearing structures of `principal` (a fresh shallow\n * copy) with clones, so the subsequent freeze never reaches the caller's\n * objects. Cycle-safe: an original-to-clone map keeps a self-referential\n * actor chain self-referential instead of unrolling it, so the depth\n * bound in `authorize()` still detects it.\n *\n * @internal\n */\nfunction cloneDelegationState(principal: Principal, original: Principal): void {\n  if (principal.roles) principal.roles = [...principal.roles];\n  if (principal.scopes) principal.scopes = [...principal.scopes];\n  if (principal.audience) principal.audience = [...principal.audience];\n  if (principal.mayAct) principal.mayAct = cloneMatchers(principal.mayAct);\n  if (principal.actor) {\n    // Seed the map with the roots (the caller's original object and the\n    // fresh copy) so a hand-assembled chain that points back at either\n    // closes on the copy itself instead of minting an extra clone, which\n    // would shift the depth authorize() counts by one hop.\n    const seen = new Map<Principal, Principal>([\n      [original, principal],\n      [principal, principal],\n    ]);\n    principal.actor = cloneActor(principal.actor, seen);\n  }\n}\n\n/** @internal */\nfunction cloneMatchers(matchers: ActorMatcher[]): ActorMatcher[] {\n  return matchers.map((matcher) => {\n    if (typeof matcher !== \"object\" || matcher === null) return matcher;\n    const clone: ActorMatcher = { ...matcher };\n    if (Array.isArray(clone.subject)) clone.subject = [...clone.subject];\n    if (Array.isArray(clone.profile)) clone.profile = [...clone.profile];\n    if (clone.roles) clone.roles = [...clone.roles];\n    return clone;\n  });\n}\n\n/** @internal */\nfunction cloneActor(\n  actor: Principal,\n  seen: Map<Principal, Principal>,\n): Principal {\n  const existing = seen.get(actor);\n  if (existing) return existing;\n  const clone: Principal = { ...actor };\n  seen.set(actor, clone);\n  if (clone.roles) clone.roles = [...clone.roles];\n  if (clone.scopes) clone.scopes = [...clone.scopes];\n  if (clone.audience) clone.audience = [...clone.audience];\n  if (actor.mayAct) clone.mayAct = cloneMatchers(actor.mayAct);\n  if (actor.actor) clone.actor = cloneActor(actor.actor, seen);\n  return clone;\n}\n\n/**\n * Freeze the `actor` chain and the `mayAct` list of a principal in place.\n * Cycle-guarded: an actor chain is acyclic when built by `delegate()` or\n * parsed from a token, but a hand-assembled one need not be, and freezing\n * must not be the thing that hangs.\n *\n * @internal\n */\nfunction freezeDelegationState(\n  principal: Principal,\n  seen: WeakSet<object> = new WeakSet(),\n): void {\n  // The subject's own policy arrays are the primary access-control inputs\n  // (authorize() reads roles for RC5015 and scopes for RC5038). The spread\n  // in markAuthentic copies the ARRAY REFERENCES, and the top-level\n  // Object.freeze is shallow, so without this a holder of ex.principal\n  // could push a role or scope onto an already-authentic identity.\n  if (principal.roles) Object.freeze(principal.roles);\n  if (principal.scopes) Object.freeze(principal.scopes);\n  if (principal.audience) Object.freeze(principal.audience);\n  if (principal.mayAct !== undefined) {\n    for (const matcher of principal.mayAct) {\n      if (typeof matcher === \"object\" && matcher !== null) {\n        if (Array.isArray(matcher.subject)) Object.freeze(matcher.subject);\n        if (Array.isArray(matcher.profile)) Object.freeze(matcher.profile);\n        if (Array.isArray(matcher.roles)) Object.freeze(matcher.roles);\n        Object.freeze(matcher);\n      }\n    }\n    Object.freeze(principal.mayAct);\n  }\n  let current = principal.actor;\n  while (current !== undefined && !seen.has(current)) {\n    seen.add(current);\n    if (current.roles) Object.freeze(current.roles);\n    if (current.scopes) Object.freeze(current.scopes);\n    if (current.audience) Object.freeze(current.audience);\n    if (current.mayAct !== undefined) freezeDelegationState(current, seen);\n    const next = current.actor;\n    Object.freeze(current);\n    current = next;\n  }\n}\n\n/**\n * Whether a value is a principal that was established by a trusted origin\n * (see {@link markAuthentic}). Returns `false` for plain objects, `null`,\n * `undefined`, and non-objects.\n */\nexport function isAuthentic(principal: unknown): principal is Principal {\n  return (\n    typeof principal === \"object\" &&\n    principal !== null &&\n    authentic.has(principal)\n  );\n}\n","import type { Principal } from \"./types.ts\";\n\n/**\n * Whether a verified principal's expiry has passed.\n *\n * The boundary is inclusive and floored to whole seconds, matching `jose`\n * (`exp <= now - tolerance`) and RFC 7519 section 4.1.4, which requires the\n * current time to be strictly before `exp`. A fractional `now` would put this\n * boundary up to a second ahead of the verifier's; an exclusive `>` would put\n * it a second behind and honour a token for a further second.\n *\n * Non-finite inputs fail closed: a NaN comparison is always false and would\n * silently disable the check (see `.standards/security.md` section 7).\n *\n * A principal without an `expiresAt` passes: a credential with no expiry\n * concept (an API key behind a custom validator) is a legitimate result, and\n * requiring `exp` belongs to the verifier layer (section 1), never here.\n *\n * This predicate is the single source of the boundary. Three checkpoints call\n * it: `authorize()` (RC5020), the HTTP bearer middleware, and\n * {@link principalExpirySignal}, which closes a stream when the credential\n * that admitted it lapses. All three pass the same `clockToleranceSec`, which\n * is what keeps them from disagreeing by a second on one credential; calling\n * this predicate while dropping its tolerance argument buys the appearance of\n * that guarantee without the substance.\n */\nexport function isPrincipalExpired(\n  principal: Pick<Principal, \"expiresAt\">,\n  clockToleranceSec = 0,\n): boolean {\n  if (principal.expiresAt === undefined) return false;\n  return (\n    !Number.isFinite(principal.expiresAt) ||\n    !Number.isFinite(clockToleranceSec) ||\n    Math.floor(Date.now() / 1000) >= principal.expiresAt + clockToleranceSec\n  );\n}\n\n/**\n * `setTimeout`'s ceiling: a delay past a signed 32-bit integer overflows and\n * fires on the next tick instead of waiting.\n */\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\n/**\n * A signal that fires when a verified principal's credential expires.\n *\n * For a response that outlives the single admission check that let it in. An\n * ordinary request is over long before its token is, but a stream can be held\n * open for hours, and `security.md` makes `exp` mandatory precisely so that\n * authority does not outlive it.\n *\n * The timer only schedules the check. Whether the credential has actually\n * lapsed is {@link isPrincipalExpired}'s to say, so the boundary and its clock\n * tolerance stay the framework's single answer rather than a second comparison\n * that can drift by a second, and a timer that fires early against a skewed\n * clock re-arms instead of closing a live stream.\n *\n * Each sleep is clamped to {@link MAX_TIMEOUT_MS}. A credential expiring\n * further out than that overflows `setTimeout`, which fires immediately rather\n * than waiting: the re-arm would then spin as fast as the event loop allows,\n * for the life of the stream. Clamped, a distant expiry simply sleeps in\n * stages.\n *\n * The tolerance is the one the verification that admitted this credential\n * applied, carried on the admit verdict and passed in here. Without it a\n * client inside the tolerance window loops: admission admits, the stream arms\n * and finds the credential expired by its own stricter boundary, closes, and\n * the client reconnects into the same pair of answers.\n *\n * @param principal - The admitted principal, or undefined for an\n *   unauthenticated request\n * @param options.clockToleranceSec - Skew the admitting verification allowed\n * @param options.onExpired - Called once when the credential is found to have\n *   lapsed, for the surface to report it. Runs after the signal aborts, and\n *   a throw from it is swallowed: revocation does not depend on it\n * @returns The signal and a `cancel` to release the timer when the response\n *   ends, or `undefined` when the principal carries no expiry, since a\n *   credential that does not expire granting a stream that does not expire is\n *   the operator's own choice correctly honoured\n */\nexport function principalExpirySignal(\n  principal: Pick<Principal, \"expiresAt\" | \"subject\"> | undefined,\n  options: {\n    /**\n     * Required, like the field on the verdict it comes from: a default of\n     * `0` here is the stricter boundary that closed a stream the door had\n     * just admitted, and an optional field is how a fourth caller reaches\n     * for it without noticing.\n     */\n    clockToleranceSec: number;\n    onExpired?: (principal: Pick<Principal, \"subject\">) => void;\n  },\n): { signal: AbortSignal; cancel: () => void } | undefined {\n  const expiresAt = principal?.expiresAt;\n  if (principal === undefined || expiresAt === undefined) return undefined;\n\n  const { clockToleranceSec } = options;\n  const controller = new AbortController();\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  const arm = (): void => {\n    if (isPrincipalExpired(principal, clockToleranceSec)) {\n      // Abort first, and never behind the notification: revoking the stream\n      // is this function's contract and telling someone about it is a\n      // courtesy, so a notifier that throws must not be able to keep an\n      // expired credential's stream open.\n      controller.abort(new Error(\"Credential expired\"));\n      try {\n        options.onExpired?.(principal);\n      } catch {\n        // Swallowed rather than rethrown because there is nowhere to report\n        // it: the notifier is the surface's own logger, and on the timer\n        // path a throw here is an uncaught exception that takes the process\n        // down over a log line.\n      }\n      return;\n    }\n    // The deadline the tolerance actually moves, not `exp` itself: sleeping\n    // to `exp` inside a tolerance window would wake, find the credential\n    // still good, and re-arm on the 50ms floor for the whole window.\n    const remaining = (expiresAt + clockToleranceSec) * 1000 - Date.now();\n    timer = setTimeout(arm, Math.min(Math.max(remaining, 50), MAX_TIMEOUT_MS));\n  };\n  arm();\n  return {\n    signal: controller.signal,\n    cancel: () => clearTimeout(timer),\n  };\n}\n","import type { Principal } from \"./types.ts\";\n\n/**\n * Module-private registry of restored principals.\n *\n * Same `WeakSet` construction as the authenticity registry in\n * `authentic.ts`, for the same reason: membership cannot be enumerated,\n * read back, copied, or transferred, so no holder of a restored principal\n * can launder a different object into the set.\n *\n * @internal\n */\nconst restored = new WeakSet<object>();\n\n/**\n * Mark a principal as restored from durable storage, and freeze it.\n *\n * A deferred exchange is serialized to a store and rehydrated hours or\n * days later, possibly in a different process. What comes back is the\n * SHAPE of the principal that was verified at defer time, with nothing\n * behind it: no live token, no signature check, no revocation lookup. It is\n * therefore deliberately NOT authentic. `authorize()` rejects it with\n * `RC5043`, which is the whole point of this mark: without it, a rehydrated\n * principal would be indistinguishable from a self-asserted plain object\n * and would report the confusing `RC5023` (\"not established by a trusted\n * origin\") instead of the actionable \"this identity came back from a\n * deferral; re-verify it\".\n *\n * This closes the direct route back to #355's bug class. Deferral is the\n * easiest way to reintroduce laundering, because the natural implementation\n * is to re-mark whatever principal was serialized as authentic on the way\n * back in.\n *\n * The principal remains readable: routes still see who the exchange was\n * running as, and `resumedBy` records who resumed it. What it cannot do is\n * pass an authorization check on its own.\n *\n * @param principal - The principal shape read back from a deferral.\n * @returns A frozen copy registered as restored. Always use the return\n *   value; the argument is neither mutated nor frozen.\n */\nexport function markRestored<P extends Principal>(principal: P): P {\n  if (isRestored(principal)) return principal;\n  const target = Object.freeze({ ...(principal as Principal) }) as P;\n  restored.add(target);\n  return target;\n}\n\n/**\n * Whether a value is a principal that was rehydrated from durable storage\n * (see {@link markRestored}). Restored principals are never authentic, so\n * this is not the inverse of `isAuthentic`: a plain self-asserted object is\n * neither.\n *\n * Returns a plain boolean rather than a type predicate on purpose. A\n * predicate here would narrow the FALSE branch of an already-`Principal`\n * value to `never`, which is not what a caller means by \"this principal is\n * not restored\".\n */\nexport function isRestored(principal: unknown): boolean {\n  return (\n    typeof principal === \"object\" &&\n    principal !== null &&\n    restored.has(principal)\n  );\n}\n","import { rcError } from \"../error.ts\";\nimport { authenticate, type PrincipalClaims } from \"./authenticate.ts\";\nimport { isAuthentic, markAuthentic } from \"./authentic.ts\";\nimport type { ActorMatcher, Principal, PrincipalProfile } from \"./types.ts\";\n\n/**\n * Options accepted by {@link delegate}.\n */\nexport interface DelegateOptions {\n  /**\n   * Scope ceiling from the caller's consent mechanism (an OAuth grant, a\n   * grant table, static config). Effective scopes on the delegated\n   * principal are the intersection of the subject's scopes and this\n   * ceiling; omitting it leaves the subject's scopes as they are.\n   *\n   * The actor's OWN scopes are deliberately NOT a term. They describe what\n   * the actor may do under its own identity (when it is the subject of an\n   * autonomous run), which is a different question from what a user may\n   * delegate to it. Intersecting them would make it impossible to grant an\n   * agent something it must never do standalone: an agent with no write\n   * access of its own could never be granted write access on a user's\n   * behalf, because the term it lacks would strip the grant. Delegated\n   * authority derives from the subject and the consent record; the actor's\n   * reachability is enforced by `authorize({ actor })` at each route.\n   *\n   * Roles are never intersected either: the subject's roles pass through\n   * (they describe who the subject IS, RFC 9068 section 2.2.3.1), and the\n   * actor's own roles stay on `actor.roles` for matching.\n   */\n  scopes?: string[];\n  /** Consent record id to carry on the delegated principal for audit. */\n  grantId?: string;\n}\n\n/**\n * Whether `actor` satisfies `matcher`. All provided matcher fields must\n * match (AND); array-valued fields are an OR across their values.\n *\n * @internal Shared between `delegate()` (mayAct) and `authorize()` (actor\n * spec) so \"does this actor match\" has exactly one definition.\n */\nexport function actorMatches(actor: Principal, matcher: ActorMatcher): boolean {\n  if (matcher.subject !== undefined) {\n    const subjects = Array.isArray(matcher.subject)\n      ? matcher.subject\n      : [matcher.subject];\n    if (!subjects.includes(actor.subject)) return false;\n  }\n  if (matcher.issuer !== undefined && actor.issuer !== matcher.issuer) {\n    return false;\n  }\n  if (matcher.profile !== undefined) {\n    const profiles: PrincipalProfile[] = Array.isArray(matcher.profile)\n      ? matcher.profile\n      : [matcher.profile];\n    if (\n      actor.subjectProfile === undefined ||\n      !profiles.includes(actor.subjectProfile)\n    ) {\n      return false;\n    }\n  }\n  if (matcher.roles !== undefined && matcher.roles.length > 0) {\n    const granted = new Set(actor.roles ?? []);\n    if (!matcher.roles.every((r) => granted.has(r))) return false;\n  }\n  return true;\n}\n\nfunction intersect(\n  base: string[] | undefined,\n  ...ceilings: Array<string[] | undefined>\n): string[] | undefined {\n  let result = base;\n  for (const ceiling of ceilings) {\n    if (ceiling === undefined) continue;\n    if (result === undefined) {\n      // A ceiling with no base grants nothing: the subject never held any\n      // scope for the ceiling to narrow.\n      return [];\n    }\n    const allowed = new Set(ceiling);\n    result = result.filter((s) => allowed.has(s));\n  }\n  return result;\n}\n\n/**\n * Mint a delegated {@link Principal}: `subject` acting through `actor`.\n *\n * This is the delegation sibling of `authenticate()`: a pure function with\n * no I/O. The caller resolves WHAT the actor may do (a consent record, an\n * OAuth grant, static config) and passes the resulting scope ceiling;\n * `delegate()` mints. Where the ceiling came from is the caller's business,\n * exactly as `authenticate()` does not care how an identity was verified.\n *\n * Semantics (see the delegation table in the docs):\n *\n * - `subject`, `roles`, `claims`, `email`, `name` pass through unchanged.\n * - `scopes` become the intersection of the subject's scopes and the\n *   `options.scopes` ceiling. The actor's own scopes are NOT a term (see\n *   {@link DelegateOptions.scopes}): an agent must be grantable something\n *   it may never do standalone.\n * - `actor` is set to the minted actor principal; a pre-existing actor\n *   nests one level down, expressing the chain (RFC 8693 section 4.1).\n *   The outermost entry is the current actor.\n * - `expiresAt` becomes the earlier of the subject's and the actor's.\n * - The result carries a fresh authenticity brand; nested actors are\n *   branded transitively because the chain is constructed here and only\n *   here.\n *\n * Routecraft supports delegation only, never impersonation (RFC 8693\n * section 1.1): the subject is always retained and the actor always named.\n *\n * @throws RC5023 when `subject` is not an authentic principal. A chain may\n *   only be built on an identity the framework already trusts; this is what\n *   keeps authenticity a property of the whole chain.\n * @throws RC5037 when `subject.mayAct` is present and no entry matches the\n *   requested actor.\n *\n * Note for custom steps calling this helper directly: the `.delegate()`\n * route operation defaults to DROPPING a non-delegated direct principal\n * when its resolver returns `undefined` (fail closed;\n * `DelegateStepOptions.otherwise: \"keep\"` is the opt-out). The helper\n * itself only mints. A custom step that skips minting on a missing grant\n * must decide what happens to the caller's direct principal, or the\n * continuation runs with the caller's full direct authority precisely\n * when consent is absent.\n *\n * @example\n * ```ts\n * const delegated = delegate(ex.principal, zoeIdentity, {\n *   scopes: grant.scopes,\n *   grantId: grant.id,\n * })\n * ```\n */\nexport function delegate(\n  subject: Principal,\n  actor: PrincipalClaims,\n  options: DelegateOptions = {},\n): Principal {\n  if (!isAuthentic(subject)) {\n    throw rcError(\"RC5023\", new Error(\"Subject principal is not authentic\"), {\n      message:\n        \"delegate() requires an authentic subject principal; a self-asserted object cannot be delegated\",\n      suggestion:\n        \"Mint the subject with .authenticate() / authenticate() (or let a source verifier attach it) before delegating. delegate() refuses to build a chain on an untrusted identity.\",\n    });\n  }\n\n  // Mint the actor first (validates its own claims, e.g. non-empty subject)\n  // so a bad actor identity fails before we touch the subject. `actor` is\n  // typed without a nested `actor`, but strip it defensively: a caller who\n  // casts could otherwise hand in a pre-built chain, which would forge\n  // prior-actor audit data (the whole point of the nested entries) and\n  // inflate the depth `authorize({ maxDelegationDepth })` counts. Nesting\n  // is derived from `subject.actor` below and from nowhere else.\n  // grantId is stripped for the same reason: grant attribution belongs to\n  // THIS delegation and comes only from options.grantId; a cast-in value\n  // would otherwise surface as an authenticate()-attributed RC5024.\n  const actorClaims: PrincipalClaims = { ...actor };\n  delete (actorClaims as { actor?: unknown; grantId?: unknown }).actor;\n  delete (actorClaims as { actor?: unknown; grantId?: unknown }).grantId;\n  const actorPrincipal = authenticate(actorClaims);\n\n  if (subject.mayAct !== undefined) {\n    const permitted = subject.mayAct.some((m) =>\n      actorMatches(actorPrincipal, m),\n    );\n    if (!permitted) {\n      throw rcError(\"RC5037\", new Error(\"Actor not permitted by mayAct\"), {\n        message: `delegate() refused: subject \"${subject.subject}\" has not permitted \"${actorPrincipal.subject}\" to act on their behalf`,\n        suggestion:\n          \"Obtain the subject's consent (add a matching entry to the subject's mayAct, typically from your grant store) and retry. Do not widen mayAct without an explicit consent event.\",\n      });\n    }\n  }\n\n  const scopes = intersect(subject.scopes, options.scopes);\n\n  const chainedActor: Principal =\n    subject.actor === undefined\n      ? actorPrincipal\n      : markAuthentic({ ...actorPrincipal, actor: subject.actor });\n\n  const expiresAt =\n    subject.expiresAt !== undefined || actorPrincipal.expiresAt !== undefined\n      ? Math.min(\n          subject.expiresAt ?? Number.POSITIVE_INFINITY,\n          actorPrincipal.expiresAt ?? Number.POSITIVE_INFINITY,\n        )\n      : undefined;\n\n  const delegated: Principal = {\n    ...subject,\n    actor: chainedActor,\n  };\n  if (scopes !== undefined) delegated.scopes = scopes;\n  else delete delegated.scopes;\n  if (expiresAt !== undefined) delegated.expiresAt = expiresAt;\n  // grantId attributes THIS delegation to its consent record. A\n  // re-delegation without its own grantId must not inherit the prior\n  // hop's id through the subject spread, or the new hop would be\n  // misattributed to an earlier consent.\n  if (options.grantId !== undefined) delegated.grantId = options.grantId;\n  else delete delegated.grantId;\n\n  return markAuthentic(delegated);\n}\n","import { rcError } from \"../error.ts\";\nimport { markAuthentic } from \"./authentic.ts\";\nimport type { Principal } from \"./types.ts\";\n\n/**\n * Identity claims accepted by {@link authenticate}. Derived from\n * {@link Principal} so the two never drift: `kind` and `scheme` are optional\n * (they default), every other `Principal` field is carried through, and\n * `subject` stays required because every minted identity must name who it\n * represents.\n */\nexport type PrincipalClaims = Partial<Pick<Principal, \"kind\" | \"scheme\">> &\n  Omit<Principal, \"kind\" | \"scheme\" | \"actor\" | \"grantId\">;\n\n/**\n * Mint an authenticated {@link Principal} from identity claims you have\n * already verified yourself.\n *\n * This is the explicit, greppable way to establish identity from a source\n * the framework cannot verify on its own: an inbound e-mail whose sender you\n * validated, a Slack event signature you checked, a webhook HMAC, and so on.\n * The returned principal is branded as authentic (see `markAuthentic`) and\n * frozen, so `authorize()` trusts it. A plain object written onto\n * `headers[\"routecraft.auth.principal\"]` is NOT trusted: minting must be a\n * deliberate call, not an incidental header write.\n *\n * Inside a route, prefer the `.authenticate()` builder operation, which is\n * sugar over this helper. Use this function directly in tests, in custom\n * source adapters, or inside a `.process()` / `.choice()` branch where the\n * builder step does not fit.\n *\n * @throws RC5024 when `subject` is missing or empty.\n *\n * @example Mid-pipeline / custom source\n * ```ts\n * import { authenticate } from \"@routecraft/routecraft\";\n *\n * const principal = authenticate({\n *   scheme: \"email\",\n *   subject: sender.address,\n *   roles: sender.address.endsWith(\"@acme.com\") ? [\"internal\"] : [],\n * });\n * ```\n */\nexport function authenticate(claims: PrincipalClaims): Principal {\n  if (typeof claims?.subject !== \"string\" || claims.subject.length === 0) {\n    throw rcError(\"RC5024\", new Error(\"Principal has no subject\"), {\n      message: \"authenticate() requires a non-empty `subject`\",\n      suggestion:\n        \"Pass the stable identity of the caller you verified, e.g. authenticate({ subject: sender.address, roles: [...] }).\",\n    });\n  }\n\n  // Delegation state is `delegate()`'s to establish, never a mint's. The\n  // type excludes `actor` / `grantId`, and this guard closes the runtime\n  // hole: without it, spreading an existing principal into authenticate()\n  // would produce an authentic DELEGATED identity while skipping every\n  // invariant delegate() enforces (mayAct consent, scope intersection,\n  // truthful chain nesting). `mayAct` is deliberately still accepted: it\n  // describes the subject (who may act FOR them), like roles, and is\n  // legitimately established when identity is minted.\n  const withDelegation = claims as Partial<Principal>;\n  if (\n    withDelegation.actor !== undefined ||\n    withDelegation.grantId !== undefined\n  ) {\n    throw rcError(\n      \"RC5024\",\n      new Error(\"Delegation state passed to authenticate()\"),\n      {\n        message:\n          \"authenticate() does not accept `actor` or `grantId`: minting establishes identity, delegation establishes who is acting for it\",\n        suggestion:\n          \"Mint the subject with authenticate(), then hand it to delegate(subject, actorClaims, { scopes, grantId }). Spreading a delegated principal back through authenticate() would bypass the mayAct consent check and the scope intersection.\",\n      },\n    );\n  }\n\n  const principal: Principal = {\n    ...claims,\n    kind: claims.kind ?? \"custom\",\n    scheme: claims.scheme ?? \"custom\",\n  };\n\n  return markAuthentic(principal);\n}\n","/**\n * Whether the process is running a named development or test environment.\n *\n * Deliberately an allowlist rather than `NODE_ENV !== \"production\"`: an\n * unset `NODE_ENV` is the most common production misconfiguration, and\n * under the negated form it would silently relax a production guard on a\n * real deployment. Per `.standards/security.md` section 6a, the relaxed\n * mode is the one that has to be named. Shared with `@routecraft/ai`, whose\n * MCP resource guard follows the same rule.\n *\n * @internal\n */\nexport function isDevelopmentRuntime(): boolean {\n  const env = process.env[\"NODE_ENV\"];\n  return env === \"development\" || env === \"test\";\n}\n","import { isRoutecraftError } from \"../brand.ts\";\n\n/**\n * Whether a token verification error represents an expired token.\n *\n * An expired token is a routine part of the client lifecycle: clients present a\n * stale cached token, receive a 401, then refresh and retry. Callers log it at\n * `debug` so the `warn` channel stays reserved for failures that genuinely\n * warrant attention (bad signature, wrong audience or issuer, malformed token).\n *\n * Detection keys off `jose`'s stable `ERR_JWT_EXPIRED` code, thrown by `jwks()`\n * and surfaced unchanged through userinfo enrichment, and also tagged on\n * `jwt()`'s expiry error so both built-in verifiers classify uniformly. `jose`\n * raises this code only for expiry, so audience and issuer mismatches\n * (`ERR_JWT_CLAIM_VALIDATION_FAILED`) correctly fall through. Validators that\n * reject expiry without this code also fall through to `warn`, the safe default\n * for an unclassified rejection.\n */\nexport function isExpiredTokenError(err: unknown): boolean {\n  return (\n    typeof err === \"object\" &&\n    err !== null &&\n    (err as { code?: unknown }).code === \"ERR_JWT_EXPIRED\"\n  );\n}\n\n/**\n * `jose` error codes that denote a server-side failure to fetch or parse the\n * JWKS, not a problem with the presented token. `ERR_JWKS_NO_MATCHING_KEY` is\n * deliberately absent: `jose` only surfaces it after re-fetching the key set, so\n * a propagated no-matching-key means the token references an unknown signing key\n * (a token problem, 401), not an infrastructure failure.\n */\nconst JOSE_INFRASTRUCTURE_CODES = new Set([\n  \"ERR_JWKS_TIMEOUT\", // JWKS endpoint did not respond within the timeout\n  \"ERR_JWKS_INVALID\", // JWKS document was structurally invalid\n  \"ERR_JOSE_GENERIC\", // jose's catch-all: non-200 / unparseable JWKS response\n]);\n\n/**\n * Node / undici surface a `fetch` network failure as a `TypeError` whose\n * `cause` carries the real errno. These are the codes seen when the IdP's JWKS\n * endpoint is unreachable (DNS failure, connection refused, socket timeout).\n */\nconst NETWORK_ERROR_CODES = new Set([\n  \"ECONNREFUSED\",\n  \"ECONNRESET\",\n  \"ENOTFOUND\",\n  \"EAI_AGAIN\",\n  \"ETIMEDOUT\",\n  \"UND_ERR_CONNECT_TIMEOUT\",\n  \"UND_ERR_HEADERS_TIMEOUT\",\n  \"UND_ERR_SOCKET\",\n]);\n\n/**\n * Whether a token verification error is a server-side infrastructure failure\n * (JWKS endpoint unreachable, timed out, or returning a bad response) rather\n * than the verifier rejecting the presented token.\n *\n * The distinction matters for the HTTP status: an infrastructure failure must\n * map to 500 (so the client retries later), never to `401 invalid_token`, which\n * would make every client discard its valid cached token and stampede an\n * already-struggling IdP with refreshes. A token rejection is the opposite: it\n * must be 401 so the client refreshes. Callers therefore treat anything that is\n * NOT an infrastructure failure (and not a framework error) as a token\n * rejection, which keeps custom and built-in `jwt()` validators that throw a\n * plain `Error` mapping to 401.\n *\n * The whole `cause` chain is inspected, not just the immediate error: Node /\n * undici nest the real errno under a `fetch failed` TypeError, and a verifier\n * may wrap the underlying failure one or more levels deep. The walk is bounded\n * to guard against a self-referential `cause` cycle.\n */\nexport function isInfrastructureError(err: unknown): boolean {\n  let current: unknown = err;\n  for (let depth = 0; depth < 5; depth++) {\n    if (typeof current !== \"object\" || current === null) return false;\n    const code = (current as { code?: unknown }).code;\n    if (\n      typeof code === \"string\" &&\n      (JOSE_INFRASTRUCTURE_CODES.has(code) || NETWORK_ERROR_CODES.has(code))\n    ) {\n      return true;\n    }\n    current = (current as { cause?: unknown }).cause;\n  }\n  return false;\n}\n\n/**\n * Bounded vocabulary for the reasons a token-verification throw can classify\n * to. The full `auth:rejected` vocabulary is wider (`missing_header`,\n * `unsupported_scheme`, `insufficient_scope`, the api-key and signature\n * literals); this type covers only the verifier-throw classification shared by\n * the HTTP and MCP bearer paths.\n */\nexport type AuthRejectionReason =\n  \"expired\" | \"infrastructure\" | \"invalid_token\";\n\n/**\n * Map a token-verification error to the bounded `auth:rejected` reason\n * vocabulary. Never derived from the raw error message: a custom verifier\n * controls that message and could embed the bearer token, leaking a secret\n * into an aggregator-indexed event field (see `.standards/security.md`\n * sections 4 and 10). The full error stays operator-only via the structured\n * `{ err }` log binding.\n *\n * `infrastructure` mirrors the predicate the 500 mapping uses (framework\n * errors and JWKS infrastructure failures), so the event payload always\n * matches the HTTP status the client receives.\n */\nexport function classifyRejectionReason(err: unknown): AuthRejectionReason {\n  if (isExpiredTokenError(err)) return \"expired\";\n  if (isRoutecraftError(err) || isInfrastructureError(err)) {\n    return \"infrastructure\";\n  }\n  return \"invalid_token\";\n}\n","export { jwt } from \"./auth/jwt.ts\";\nexport type {\n  JwtAuthOptions,\n  JwtHmacOptions,\n  JwtRsaOptions,\n} from \"./auth/jwt.ts\";\nexport { jwks } from \"./auth/jwks.ts\";\nexport type { JwksOptions } from \"./auth/jwks.ts\";\nexport {\n  authorize,\n  type AuthorizeOptions,\n  type ActorSpec,\n  type InsufficientAuthority,\n  isAuthorizationRefusal,\n  type SubjectMatcher,\n} from \"./auth/authorize.ts\";\nexport { authenticate, type PrincipalClaims } from \"./auth/authenticate.ts\";\nexport { delegate, type DelegateOptions } from \"./auth/delegate.ts\";\nexport { isAuthentic, markAuthentic } from \"./auth/authentic.ts\";\nexport { isDevelopmentRuntime } from \"./shared/runtime-env.ts\";\nexport {\n  classifyRejectionReason,\n  isExpiredTokenError,\n  isInfrastructureError,\n  type AuthRejectionReason,\n} from \"./auth/error-classification.ts\";\nexport { isPrincipalExpired } from \"./auth/expiry.ts\";\nexport { isRestored, markRestored } from \"./auth/restored.ts\";\nexport { timingSafeStringEqual } from \"./auth/timing-safe.ts\";\nexport type {\n  ActorMatcher,\n  ClaimMappers,\n  JwtAudience,\n  OAuthPrincipal,\n  OAuthTokenVerifier,\n  OAuthValidatorAuthOptions,\n  Principal,\n  PrincipalProfile,\n  TokenVerifier,\n  ValidatorAuthOptions,\n} from \"./auth/types.ts\";\n\nexport {\n  DefaultExchange,\n  type Exchange,\n  type ExchangeHeaders,\n  getExchangeContext,\n  getExchangeRoute,\n  HeadersKeys,\n  type HeaderValue,\n  type HeaderLiteral,\n  isDropped,\n  OperationType,\n  peekResumeStepState,\n  wasOutputValidated,\n  type RoutecraftHeaders,\n} from \"./exchange.ts\";\n\nexport {\n  CraftContext,\n  type MergedOptions,\n  type StoreRegistry,\n  RUNNER_ARGV,\n  DEFAULT_SHUTDOWN_TIMEOUT_MS,\n  type CraftConfig,\n  type CraftPlugin,\n  type ShutdownConfig,\n  type ShutdownOutcome,\n  type TeardownInfo,\n} from \"./context.ts\";\nexport {\n  type Capability,\n  isInternalEndpoint,\n  registerCapability,\n  registerInternalEndpoint,\n} from \"./capabilities.ts\";\nexport { defineConfig } from \"./define-config.ts\";\nexport { registerConfigApplier, type ConfigApplier } from \"./config-applier.ts\";\nexport {\n  getProjectDiscoverers,\n  mergeProjectConfig,\n  registerProjectDiscoverer,\n  type ProjectDiscoverer,\n  type ProjectDiscovererOptions,\n  type ProjectDiscoveryContext,\n  type RegisteredProjectDiscoverer,\n} from \"./project-discoverer.ts\";\nexport { type HttpConfig } from \"./adapters/http/types.ts\";\n\n// Side-effect: register the config appliers for first-class config keys\n// (`http`, `cron`, `direct`, `mail`, `telemetry`) so `defineConfig({...})`\n// materialises the wiring without users importing plugins manually. Each\n// module also augments CraftConfig with its key; the core context has no\n// adapter knowledge.\nimport \"./plugins/server/config.ts\";\nimport \"./plugins/http/config.ts\";\nimport \"./plugins/ops/config.ts\";\nimport \"./plugins/remotes/config.ts\";\nimport \"./adapters/cron/config.ts\";\nimport \"./adapters/direct/config.ts\";\nimport \"./adapters/mail/config.ts\";\nimport \"./adapters/carddav/config.ts\";\nimport \"./telemetry/config.ts\";\nimport \"./deferral/config.ts\";\n\nexport { httpPlugin } from \"./plugins/http/plugin.ts\";\nexport { serversPlugin } from \"./plugins/server/plugin.ts\";\nexport { requireWebIngress } from \"./plugins/server/registry.ts\";\nexport { normalizeStaticPathPrefix } from \"./plugins/server/mount-path.ts\";\nexport type {\n  HttpMount,\n  HttpMountAuth,\n  HttpMountAuthPolicy,\n  HttpMountContext,\n  HttpServerDefinition,\n  PathClaim,\n  ServerDefinitions,\n  WebIngress,\n} from \"./plugins/server/types.ts\";\nexport { apiKey } from \"./plugins/http/auth.ts\";\nexport type { SseEvent } from \"./plugins/http/sse.ts\";\nexport {\n  bearerChallenge,\n  buildProtectedResourceMetadata,\n  PROTECTED_RESOURCE_METADATA_PATH,\n  resourceMetadataUrlFor,\n  type ProtectedResourceMetadata,\n  type ProtectedResourceMetadataInput,\n} from \"./plugins/server/protected-resource.ts\";\nexport {\n  buildCorsHeaders,\n  defaultLoopbackOriginResolver,\n  resolveCorsOptions,\n  type HttpCorsOptions,\n  type HttpCorsOriginResolver,\n} from \"./plugins/server/cors.ts\";\n\nexport { opsPlugin } from \"./plugins/ops/plugin.ts\";\nexport { defineIndicator } from \"./plugins/ops/indicator.ts\";\nexport {\n  OPS_HEALTH_STATE,\n  OPS_RESOURCES,\n  registerOpsResource,\n} from \"./plugins/ops/store.ts\";\n// Paging for contributed resources, so a contributor's collection carries the\n// same cursor contract as the route listing rather than a second one.\nexport {\n  DEFAULT_PAGE_SIZE,\n  cursorScope,\n  decodeCursor,\n  encodeCursor,\n  malformedCursor,\n  parsePageQuery,\n  takePage,\n  type CursorScope,\n  type PageFilter,\n} from \"./plugins/ops/pagination.ts\";\n// The read surface only. The ledger's mutators are the plugin's translation of\n// framework events, and the store hands back the live instance, so a type that\n// exposed them would let an app inject a transition nothing ever observed.\nexport type { HealthLedger } from \"./plugins/ops/state.ts\";\nexport type {\n  CircuitState,\n  ContextState,\n  FailureDomain,\n  Health,\n  HealthChange,\n  HealthComponent,\n  HealthDetails,\n  HealthDetailsExposure,\n  HealthDetailValue,\n  HealthReport,\n  HealthStatus,\n  HealthView,\n  Indicator,\n  IndicatorDefinition,\n  LivenessReport,\n  OpsConfig,\n  OpsDeferralSummary,\n  OpsDispatchOutcome,\n  OpsHealthOptions,\n  OpsPage,\n  OpsPluginOptions,\n  OpsResource,\n  OpsRouteDetail,\n  OpsRouteFilter,\n  OpsRouteQuery,\n  OpsRouteSchemas,\n  OpsEventTailItem,\n  OpsRouteSummary,\n  OpsTier,\n  OpsTiers,\n  RouteLifecycle,\n} from \"./plugins/ops/types.ts\";\nexport {\n  OPS_SCOPE_DISPATCH,\n  OPS_SCOPE_EVENTS,\n  OPS_SCOPE_INTROSPECTION,\n} from \"./plugins/ops/types.ts\";\n// The client of that API, shared with the CLI and the remotes plugin so the\n// wire is spoken in one place.\nexport {\n  createOpsHttpClient,\n  isLoopbackHostname,\n  OpsClientError,\n  type OpsBearerToken,\n  type OpsDeferralFilter,\n  type OpsFailureKind,\n  type OpsHttpClient,\n  type OpsHttpClientOptions,\n} from \"./plugins/ops/client.ts\";\nexport {\n  compareRuntimeVersion,\n  parseRuntimeVersion,\n  type RuntimeVersion,\n} from \"./shared/runtime-version.ts\";\nexport { remotesPlugin } from \"./plugins/remotes/plugin.ts\";\nexport type {\n  RemoteDefinition,\n  RemotesConfig,\n  RemotesPluginOptions,\n} from \"./plugins/remotes/types.ts\";\n/** @deprecated Use `CraftConfig.direct` instead. Will be removed in next major version. */\nexport { type DirectConfig } from \"./adapters/direct/types.ts\";\n\nexport {\n  recovery,\n  type Recovery,\n  type RecoveryDrop,\n  type RecoveryRethrow,\n  isRecovery,\n} from \"./recovery.ts\";\n\nexport {\n  DefaultRoute,\n  type Route,\n  type RouteDefinition,\n  type ErrorHandler,\n  type ForwardFn,\n  type RouteDiscovery,\n  type RouteSchemas,\n  type KnownTag,\n  type Tag,\n} from \"./route.ts\";\n\nexport {\n  type CallableSource,\n  type GeneratorSource,\n  type Source,\n  type SourceLike,\n  type SourceList,\n  type SourceMeta,\n  type Subscription,\n} from \"./operations/from.ts\";\n\nexport { type Processor } from \"./operations/process.ts\";\n\nexport {\n  type Destination,\n  type CallableDestination,\n  type SendContext,\n  type ToTarget,\n} from \"./operations/to.ts\";\n\nexport {\n  type Splitter,\n  type SplitResult,\n  type SplitChild,\n  splitChild,\n  isSplitChild,\n} from \"./operations/split.ts\";\n\nexport { type Aggregator } from \"./operations/aggregate.ts\";\n\nexport {\n  type Transformer,\n  type CallableTransformer,\n  type FieldTransform,\n  mapper,\n} from \"./operations/transform.ts\";\n\nexport { mask, type MaskFn, type MaskRules } from \"./operations/mask.ts\";\n\nexport {\n  keep,\n  type Grant,\n  type KeepRule,\n  type KeepRules,\n  type KeepOptions,\n} from \"./operations/keep.ts\";\n\nexport {\n  type Validator,\n  type CallableValidator,\n  schema,\n} from \"./operations/validate.ts\";\n\nexport { type Filter, type FilterDropResult } from \"./operations/filter.ts\";\n\nexport {\n  SampleStep,\n  type SampleOptions,\n  type ResolvedSampleOptions,\n} from \"./operations/sample.ts\";\n\nexport {\n  DedupeStep,\n  type DedupeOptions,\n  type ResolvedDedupeOptions,\n} from \"./operations/dedupe.ts\";\n\n// ResolvedDebounceOptions is @internal and deliberately NOT re-exported here\n// (DEFINITION_OF_DONE.md: no new @internal symbols on the public entry\n// point; the Resolved* exports above it are grandfathered).\nexport { DebounceStep, type DebounceOptions } from \"./operations/debounce.ts\";\n\nexport { hashExchangeBody } from \"./operations/hash-body.ts\";\n\nexport {\n  PathBuilder,\n  when,\n  otherwise,\n  type ChoicePredicate,\n  type Path,\n  type WhenDescriptor,\n  type OtherwiseDescriptor,\n  type ChoiceDescriptor,\n} from \"./operations/choice.ts\";\n\nexport { MulticastStep } from \"./operations/multicast.ts\";\n\nexport {\n  DispatchStep,\n  weighted,\n  type DispatchStrategy,\n  type DispatchStrategyName,\n  type DispatchTarget,\n  type WeightedTarget,\n} from \"./operations/dispatch.ts\";\n\nexport { type HeaderSetter } from \"./operations/header.ts\";\n\nexport { type DeferOptions } from \"./operations/defer.ts\";\nexport { type ResumeMapper, type ResumeOptions } from \"./operations/resume.ts\";\n\nexport { type CallableAuthenticator } from \"./operations/authenticate.ts\";\n\nexport {\n  type CallableDelegator,\n  type DelegateStepOptions,\n  type DelegationClaims,\n} from \"./operations/delegate.ts\";\n\nexport {\n  type Enricher,\n  type CallableEnricher,\n  type EnrichAggregator,\n  only,\n  none,\n} from \"./operations/enrich.ts\";\n\nexport { WrapperStep } from \"./operations/wrapper.ts\";\nexport { ErrorWrapperStep } from \"./operations/error-wrapper.ts\";\nexport {\n  CacheWrapperStep,\n  type CacheOptions,\n} from \"./operations/cache-wrapper.ts\";\nexport {\n  type CacheProvider,\n  MemoryCacheProvider,\n  type MemoryCacheProviderOptions,\n} from \"./operations/cache-provider.ts\";\nexport { DelayWrapperStep } from \"./operations/delay-wrapper.ts\";\nexport {\n  TimeoutWrapperStep,\n  type ResolvedTimeoutOptions,\n} from \"./operations/timeout-wrapper.ts\";\nexport {\n  RetryWrapperStep,\n  type RetryOptions,\n  type ResolvedRetryOptions,\n} from \"./operations/retry-wrapper.ts\";\nexport {\n  ThrottleWrapperStep,\n  type ThrottleOptions,\n  type ThrottleTimeUnit,\n  type ResolvedThrottleOptions,\n} from \"./operations/throttle-wrapper.ts\";\nexport {\n  CircuitBreakerWrapperStep,\n  type CircuitBreakerOptions,\n  type CircuitBreakerState,\n  type ResolvedCircuitBreakerOptions,\n} from \"./operations/circuit-breaker-wrapper.ts\";\nexport {\n  ConcurrencyWrapperStep,\n  type ConcurrencyOptions,\n} from \"./operations/concurrency-wrapper.ts\";\n\nexport {\n  ContextBuilder,\n  craft,\n  RouteBuilder,\n  type AnyRouteBuilder,\n  type PreFromBuilder,\n  type PreFromStaging,\n  type PreFromTypedBuilder,\n  type RouteOptions,\n} from \"./builder.ts\";\n\n/**\n * Type-only re-exports of the shared builder base and its type-state\n * machinery. Exposed so that `registerDsl` can augment a single interface\n * (`StepBuilderBase<S extends BuilderState>`) and have both `RouteBuilder`\n * and `PathBuilder` inherit the augmentation via class-interface\n * inheritance; `SetBody`, `SetDeferral` and `Retyped` are the helpers\n * type-changing sugar uses to advance the bag. `ExchangeOf` and `PathState`\n * are published for the same reason: both appear in signatures a user can\n * see (`ExchangeOf` in every callable-taking builder method, `PathState` in\n * the exported `Path` / `when()` / `otherwise()` types), so naming them has\n * to be possible without re-declaring them. The class value is deliberately\n * not re-exported: the base is not a public extension point and the\n * closed-world `Retyped` helper falls through to `never` for any subclass\n * outside the framework-owned set.\n */\nexport type {\n  StepBuilderBase,\n  BuilderState,\n  ExchangeOf,\n  PathState,\n  SetBody,\n  SetDeferral,\n  FetchedBody,\n  Retyped,\n} from \"./step-builder-base.ts\";\n\nexport { CraftClient } from \"./client.ts\";\n\nexport {\n  registerDsl,\n  type PrimitiveKind,\n  type DslRegistration,\n} from \"./dsl.ts\";\n// Side-effect import: triggers built-in sugar registrations (.log, .debug, .map, .schema)\nimport \"./dsl.ts\";\n\nexport {\n  RoutecraftError,\n  type RCCode,\n  type RCMeta,\n  type KnownErrorCategory,\n  type ErrorCodeRegistry,\n  rcError,\n  registerErrorCodes,\n  formatSchemaIssues,\n  RC,\n} from \"./error.ts\";\n\nexport {\n  validateAgainst,\n  isInputValidationFailure,\n  type InputValidationFailure,\n  isOutputValidationFailure,\n  type OutputValidationFailure,\n} from \"./pipeline/validation.ts\";\nexport {\n  callerRefusalOf,\n  wireIssues,\n  type CallerRefusal,\n  type CallerRefusalOrigin,\n  type WireIssue,\n  type WireIssues,\n} from \"./pipeline/caller-refusal.ts\";\nexport { isStandardSchema } from \"./shared/standard-schema.ts\";\nexport { parseDuration } from \"./shared/duration.ts\";\nexport { rejectStaleOptions } from \"./shared/stale-options.ts\";\nexport { anySignal } from \"./shared/abort.ts\";\nexport { MANUAL_REFRESH, NEVER_FORCE } from \"./enablement.ts\";\nexport type {\n  EnablementOptions,\n  EnablementPredicate,\n  EnablementState,\n  EnablementVerdict,\n  RefreshCadence,\n  RouteEnablement,\n} from \"./enablement.ts\";\nexport type { Duration, DurationUnit } from \"./shared/duration.ts\";\n\nexport {\n  isCraftContext,\n  isRoute,\n  isRouteBuilder,\n  isRouteDefinition,\n  isRoutecraftError,\n  rcCodeOf,\n  isExchange,\n} from \"./brand.ts\";\n\nexport {\n  type DirectEndpointRegistry,\n  type ResolveKey,\n  type ResolveBody,\n  type RegisteredDirectEndpoint,\n} from \"./registry.ts\";\n\nexport { logger, logFileDiversion, type LogFileDiversion } from \"./logger.ts\";\n\nexport { shutdownHandler } from \"./shutdown.ts\";\n\nexport {\n  RC_ADAPTER_OVERRIDES,\n  SOURCE_FIXTURE,\n  isSourceFixture,\n  type AdapterOverride,\n  type AdapterSendCall,\n  type AdapterSourceCall,\n  type SendOverrideHandler,\n  type SourceOverrideBehavior,\n  type SourceFixture,\n  type SourceMessage,\n} from \"./testing-hooks.ts\";\n\nexport { tagAdapter, factoryArgs } from \"./adapters/shared/factory-tag.ts\";\nexport { loadOptionalPeer } from \"./adapters/shared/optional-peer.ts\";\n\nexport {\n  type OnParseError,\n  DEFAULT_ON_PARSE_ERROR,\n} from \"./adapters/shared/parse.ts\";\n\nexport {\n  type Adapter,\n  type Consumer,\n  type ConsumerDeps,\n  type ConsumerType,\n  type EventDetailsMap,\n  type EventName,\n  type EventHandler,\n  type EventPayload,\n  forRoute,\n  type Message,\n  type ProcessingQueue,\n  type Step,\n  type StepContext,\n  type StepSignalContext,\n  type StepOutcome,\n  type StepOutcomeMetadata,\n} from \"./types.ts\";\n\nexport { SimpleConsumer } from \"./consumers/simple.ts\";\n\nexport { BatchConsumer, type BatchOptions } from \"./consumers/batch.ts\";\n\nexport { simple } from \"./adapters/simple/index.ts\";\nexport { noop } from \"./adapters/noop/index.ts\";\nexport { log, debug } from \"./adapters/log/index.ts\";\nexport { direct } from \"./adapters/direct/index.ts\";\nexport { timer } from \"./adapters/timer/index.ts\";\nexport { cron } from \"./adapters/cron/index.ts\";\nexport { http } from \"./adapters/http/index.ts\";\nexport {\n  isRedirect,\n  HTTP_REDIRECT_STATUSES,\n} from \"./adapters/http/redirect.ts\";\nexport { file } from \"./adapters/file/index.ts\";\nexport { directory } from \"./adapters/directory/index.ts\";\nexport { html } from \"./adapters/html/index.ts\";\nexport { json } from \"./adapters/json/index.ts\";\nexport { csv } from \"./adapters/csv/index.ts\";\nexport { xml } from \"./adapters/xml/index.ts\";\nexport { jsonl } from \"./adapters/jsonl/index.ts\";\nexport { group } from \"./adapters/group/index.ts\";\nexport { event } from \"./adapters/sources/event/index.ts\";\nexport { mail } from \"./adapters/mail/index.ts\";\nexport { carddav } from \"./adapters/carddav/index.ts\";\n\nexport { type LogOptions, type LogLevel } from \"./adapters/log/index.ts\";\nexport {\n  type HttpClientOptions,\n  type HttpResult,\n  type HttpMethod,\n  type HttpRedirectMode,\n  type HttpRequestPayload,\n  type HttpResponder,\n  type HttpRespondContext,\n  type HttpRespondRequest,\n  type HttpResponseBodyMode,\n  type HttpResponseDescriptor,\n  type QueryParams,\n  type HttpServerOptions,\n  type HttpPluginOptions,\n  type HttpRequestBody,\n  type HttpResponseHint,\n  type HttpAuth,\n  type ApiKeyAuthOptions,\n  type HttpBuiltinsOptions,\n  type HttpBuiltinOptions,\n  type HttpOpenApiBuiltinOptions,\n  type HttpOpenApiInfo,\n  type HttpWebhookSignatureOptions,\n  type HttpWebhookSignatureScheme,\n} from \"./adapters/http/index.ts\";\nexport {\n  type DirectBaseOptions,\n  type DirectChannel,\n  type DirectChannelType,\n  type DirectClientOptions,\n  type DirectOptions,\n  type DirectServerOptions,\n} from \"./adapters/direct/index.ts\";\nexport { type TimerOptions, TimerHeaders } from \"./adapters/timer/index.ts\";\nexport {\n  type CronExpression,\n  type CronOptions,\n  CronHeaders,\n} from \"./adapters/cron/index.ts\";\nexport {\n  type FileOptions,\n  type FileAdapter,\n  FileHeaders,\n} from \"./adapters/file/index.ts\";\nexport {\n  type DirectoryOptions,\n  type DirectoryAdapter,\n  type DirectoryChunkedAdapter,\n  type DirectoryEntry,\n} from \"./adapters/directory/index.ts\";\nexport {\n  type HtmlOptions,\n  type HtmlResult,\n  type HtmlAdapter,\n} from \"./adapters/html/index.ts\";\nexport {\n  type JsonOptions,\n  type JsonTransformerOptions,\n  type JsonFileOptions,\n  type JsonFileAdapterType,\n} from \"./adapters/json/index.ts\";\nexport {\n  type CsvOptions,\n  type CsvTransformerOptions,\n  type CsvFileOptions,\n  type CsvRow,\n  type CsvData,\n  type CsvAdapter,\n  type CsvChunkedAdapter,\n  CsvHeaders,\n} from \"./adapters/csv/index.ts\";\nexport {\n  type XmlOptions,\n  type XmlTransformerOptions,\n  type XmlFileOptions,\n  type XmlParseOptions,\n  type XmlBuildOptions,\n  type XmlData,\n  type XmlAdapter,\n} from \"./adapters/xml/index.ts\";\nexport {\n  type JsonlOptions,\n  type JsonlFileOptions,\n  type JsonlTransformerOptions,\n  type JsonlAdapter,\n  type JsonlChunkedAdapter,\n  JsonlHeaders,\n} from \"./adapters/jsonl/index.ts\";\nexport { type GroupOptions } from \"./adapters/group/index.ts\";\nexport {\n  cosine,\n  type CosineOptions,\n  type Comparator,\n} from \"./adapters/cosine/index.ts\";\nexport {\n  type EventFilter,\n  type EventSourceOptions,\n} from \"./adapters/sources/event/index.ts\";\n\nexport { telemetry } from \"./telemetry/index.ts\";\nexport {\n  SqliteSpanProcessor,\n  SqliteConnection,\n  SqliteEventWriter,\n  ATTR,\n  SPAN_KIND,\n} from \"./telemetry/index.ts\";\nexport type {\n  TelemetryOptions,\n  TelemetrySqliteOptions,\n  TelemetryEvent,\n} from \"./telemetry/index.ts\";\n\n// The minimal sqlite surface every storage subsystem shares. Published\n// because the CLI's telemetry reader sits on the same shape, and a store\n// backend written outside this repo needs it to type its driver.\nexport type {\n  SqliteDatabase,\n  SqliteDatabaseConstructor,\n  SqliteStatement,\n} from \"./shared/sqlite/types.ts\";\n// The sqlite seam another package opens a store on: @routecraft/ai opens\n// its session store on the same runtime split (bun:sqlite under Bun,\n// better-sqlite3 as an optional peer under Node) with the same path\n// resolution, busy classification and migration runner, and a package\n// cannot reach a deep import of core. The first brick of #601, shared\n// rather than copied.\nexport {\n  resolveSqliteDriver,\n  type ResolvedSqliteDriver,\n  type SqliteDriverLoaders,\n  type SqliteDriverName,\n} from \"./shared/sqlite/driver.ts\";\nexport {\n  describeSqliteFile,\n  isSqliteBusy,\n  migrateSqlite,\n  resolveDatabasePath,\n  SQLITE_APPLICATION_IDS,\n  sqliteApplicationName,\n  type SqliteApplicationId,\n  type SqliteMigrationFailure,\n} from \"./shared/sqlite/database.ts\";\nexport {\n  claimDatabasePath,\n  releaseClaimant,\n  type SqlitePathConflict,\n} from \"./shared/sqlite/claims.ts\";\n\n// The deferral engine (hashing, serialization, token minting, runtime\n// resolution) stays behind `./deferral/index.ts`, which is where the\n// executor imports it from. Only the surface a user touches is published:\n// configuration, the store contract for anyone writing a backend, the two\n// shipped backends, and the environment-variable names.\nexport {\n  DEFAULT_DEFERRAL_DB_PATH,\n  MemoryDeferralStore,\n  DEFERRED_JSON_SCHEMA,\n  DEFERRAL_RUNTIME,\n  DEFERRAL_SECRET_ENV,\n  DEFERRAL_STORE_ENV,\n  SqliteDeferralStore,\n  DeferSignal,\n  DeferralHeaders,\n  isDeferSignal,\n  isDeferred,\n  markDeferCapable,\n  // deferAside and reviveDeferral are @internal and re-exported on purpose:\n  // @routecraft/ai stores and revives an agent session's continuation\n  // through them, and a package cannot reach a deep import of core.\n  deferAside,\n  reviveDeferral,\n  routeCanDefer,\n  stepStateFingerprint,\n  deferredSchema,\n  deferralPlugin,\n} from \"./deferral/index.ts\";\nexport type {\n  ExpiredScanCursor,\n  NewDeferral,\n  DeferSignalRequest,\n  DeferSite,\n  PendingDeferralSummary,\n  PrincipalRef,\n  ResumeAcknowledgment,\n  ResumeAuthorizer,\n  ResumeAuthorizerInput,\n  ResumeRequest,\n  Deferred,\n  DeferralRecordView,\n  DeferralAffordance,\n  SerializedExchange,\n  SerializedOutcome,\n  Deferral,\n  DeferralCasResult,\n  DeferralConfig,\n  DeferralListCursor,\n  DeferralListQuery,\n  DeferralSummary,\n  DeferralSchema,\n  DeferralResumption,\n  DeferralRuntime,\n  DeferralState,\n  DeferralOutcome,\n  DeferralWaitingFor,\n  DeferralStore,\n  DeferralStoreConfig,\n} from \"./deferral/index.ts\";\nexport { claimed, resumable, summariseDeferral } from \"./deferral/index.ts\";\nexport {\n  type MailAuth,\n  type MailReconnectOptions,\n  type MailServerOptions,\n  type MailClientOptions,\n  type MailOptions,\n  type MailBody,\n  type MailMessage,\n  type MailAttachment,\n  type MailSendPayload,\n  type MailFetchResult,\n  type MailFolderAdapter,\n  type MailContextConfig,\n  type MailAccountConfig,\n  type MailAccountImapConfig,\n  type MailAccountSmtpConfig,\n  type MailAction,\n  type MailMoveAction,\n  type MailCopyAction,\n  type MailDeleteAction,\n  type MailFlagAction,\n  type MailUnflagAction,\n  type MailAppendAction,\n  type MailTargetExtractor,\n  type MailSender,\n  type EmailAddress,\n  type ForwardHop,\n  type ForwardType,\n  type TrustLevel,\n  analyzeHeaders,\n  parseAuthResults,\n  ANALYSIS_HEADER_NAMES,\n  MailClientManager,\n  MailHeaders,\n} from \"./adapters/mail/index.ts\";\nexport {\n  CarddavAdapter,\n  CarddavClientManager,\n  CARDDAV_CLIENT_MANAGER,\n  DEFAULT_CARDDAV_SERVER_URL,\n  CarddavHeaders,\n  VCard,\n  VCardProperty,\n  parseVCard,\n  VCARD,\n  VPARAM,\n  type KnownProperty,\n  type KnownParam,\n  type CarddavOptions,\n  type CarddavServerOptions,\n  type CarddavClientOptions,\n  type CarddavContextConfig,\n  type CarddavAccountConfig,\n  type CarddavAction,\n  type CarddavTargetExtractor,\n  type CarddavDriverClient,\n  type DAVAddressBookLike,\n  type DAVVCardLike,\n  type ResolvedCarddavConnection,\n  type VCardBody,\n  type VCardPropertyData,\n  type VCardPropertyOptions,\n  type VCardParam,\n} from \"./adapters/carddav/index.ts\";\n","import { rcError } from \"../error.ts\";\n\n/**\n * How long a deferral stays resumable: milliseconds, or a duration\n * string with a unit suffix (`\"500ms\"`, `\"30s\"`, `\"15m\"`, `\"72h\"`, `\"7d\"`).\n *\n * The string form exists because the realistic values here are human ones:\n * an approval window is three days, not 259_200_000.\n */\nexport type Duration = number | `${number}${DurationUnit}`;\n\n/** Unit suffixes accepted by {@link parseDuration}. */\nexport type DurationUnit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\n\nconst UNIT_MS: Record<DurationUnit, number> = {\n  ms: 1,\n  s: 1_000,\n  m: 60_000,\n  h: 3_600_000,\n  d: 86_400_000,\n};\n\n// Anchored, and the unit is required: \"72\" would otherwise be ambiguous\n// between 72ms (the numeric form's unit) and the 72 hours the author meant.\nconst PATTERN = /^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d)$/;\n\n/**\n * Resolve a {@link Duration} to milliseconds.\n *\n * The single duration guard for the whole framework: every authored time\n * option parses here, so the accepted grammar cannot drift between the\n * surfaces that use it.\n *\n * @param value - Milliseconds, or a duration string\n * @param field - Option name quoted in the error message\n * @param min - Smallest accepted duration. `1` (the default) for a\n *   deadline, where zero means \"already expired\" and is always a mistake;\n *   `0` for a wait, where zero legitimately means \"do not wait\".\n * @returns The duration in milliseconds\n * @throws RC5003 when the value is not a duration an `expiresAt` `Date`\n *   can represent: at least `min` milliseconds, and not past the end of\n *   the representable time range\n */\nexport function parseDuration(\n  value: Duration,\n  field: string,\n  min: 0 | 1 = 1,\n): number {\n  if (typeof value === \"number\") return assertRepresentable(value, field, min);\n  // Narrowed before `.trim()`: `ttl` crosses a plain-JavaScript boundary,\n  // where `null`, a boolean or an object would otherwise raise a native\n  // TypeError instead of the RC5003 this function documents.\n  if (typeof value !== \"string\") {\n    throw refuse(\n      field,\n      typeof value === \"object\" ? \"an object\" : String(value),\n      min,\n    );\n  }\n  const match = PATTERN.exec(value.trim());\n  if (!match) throw refuse(field, value, min);\n  return assertRepresentable(\n    Number(match[1]) * UNIT_MS[match[2] as DurationUnit],\n    field,\n    min,\n  );\n}\n\n/**\n * Bound a duration to what an `expiresAt` `Date` can actually hold.\n *\n * Both ends matter and both fail late without this. Below a millisecond\n * the deadline rounds to the moment of deferring, so the deferral expires\n * on arrival; beyond the Date range the arithmetic yields an Invalid Date\n * that is only discovered once the record is already in the store, where\n * every comparison against it is false.\n *\n * @internal\n */\nfunction assertRepresentable(ms: number, field: string, min: 0 | 1): number {\n  if (!Number.isFinite(ms) || ms < min) throw refuse(field, String(ms), min);\n  // ECMAScript pins the time value range at +/- 8.64e15 ms from the epoch;\n  // a TTL is added to \"now\", so the ceiling is what is left of it.\n  if (Date.now() + ms > 8.64e15) throw refuse(field, String(ms), min);\n  return Math.floor(ms);\n}\n\n/** @internal */\nfunction refuse(field: string, value: string, min: 0 | 1): Error {\n  const floor = min === 0 ? \"a non-negative\" : \"a positive\";\n  return rcError(\"RC5003\", undefined, {\n    message: `${field} must be ${floor} number of milliseconds or a duration string like \"30s\", \"15m\", \"72h\" or \"7d\"; received ${JSON.stringify(value)}.`,\n  });\n}\n","import { rcError } from \"../error.ts\";\n\n/**\n * Reject options that no longer exist, so a stale name fails at build\n * rather than being ignored.\n *\n * TypeScript already refuses an unknown key, but only on an object literal.\n * A plain-JS caller, an `as any`, or an options object assembled elsewhere\n * and spread in gets no such check, and the option is simply dropped. A\n * timer that quietly keeps its 1000ms default because `intervalMs` no\n * longer means anything is a far worse failure than one that refuses to\n * build, so every removal is named here.\n *\n * Two kinds of staleness are caught. Any key ending in `Ms` is stale by\n * construction: authored time options take a {@link Duration} and carry no\n * unit suffix, so `Ms` on an authored option can only be a pre-0.7 name.\n * Anything else removed for its own reasons is listed per call site.\n *\n * @param options - The user-supplied options object, if any\n * @param surface - Call shape quoted in the error, e.g. `timer`\n * @param removed - Removed key mapped to the sentence saying what to write instead\n * @throws RC5003 naming the stale option and its replacement\n *\n * @internal\n */\nexport function rejectStaleOptions(\n  options: unknown,\n  surface: string,\n  removed: Readonly<Record<string, string>> = {},\n): void {\n  if (typeof options !== \"object\" || options === null) return;\n\n  for (const [key, guidance] of Object.entries(removed)) {\n    // Own keys only, matching the Ms scan below. `in` would walk the\n    // prototype chain and fail a build over a key the caller never wrote.\n    if (Object.hasOwn(options, key)) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `${surface}({ ${key} }) was removed; ${guidance}`,\n      });\n    }\n  }\n\n  for (const key of Object.keys(options)) {\n    if (/[a-z]Ms$/.test(key)) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `${surface}({ ${key} }) was renamed to ${surface}({ ${key.slice(0, -2)} }); authored time options take a Duration (a number of milliseconds, or a string such as \"5m\"), so the Ms suffix is gone.`,\n      });\n    }\n  }\n}\n","import type { Cron as CronType } from \"croner\";\nimport { loadOptionalPeer } from \"./adapters/shared/optional-peer.ts\";\nimport { rcError } from \"./error.ts\";\nimport type { CronExpression } from \"./adapters/cron/types.ts\";\nimport { type Duration, parseDuration } from \"./shared/duration.ts\";\n\n/**\n * What an {@link EnablementPredicate} answers with.\n *\n * `true` enables the route. A string disables it and IS the reason, so ops\n * can report why without the author declaring the reason a second time\n * (which is the declaration that goes stale). `false` disables it with a\n * generic reason, for a predicate that has nothing useful to add.\n */\nexport type EnablementVerdict = boolean | string;\n\n/**\n * Decides whether a route runs.\n *\n * Evaluated once as the context starts, and again on the cadence the route\n * declared via {@link EnablementOptions.refresh}. It is per-route lifecycle,\n * not per-exchange filtering: it never sees an exchange and never runs on\n * the hot path.\n *\n * A predicate that throws leaves the route disabled with the error message\n * as its reason and never fails the boot. A capability whose credentials are\n * missing is a configuration state, and a configuration state must not take\n * the process down.\n */\nexport type EnablementPredicate = () =>\n  EnablementVerdict | Promise<EnablementVerdict>;\n\n/**\n * How often a route's predicate is re-evaluated.\n *\n * A {@link Duration} is a fixed interval; a cron expression is a schedule.\n * They are told apart by shape rather than by a mode flag: every cron\n * expression contains a space or starts with `@`, and no `Duration` does.\n */\nexport type RefreshCadence = Duration | CronExpression | typeof MANUAL_REFRESH;\n\n/**\n * Explicit opt-out from any refresh cadence: the predicate is evaluated once\n * as the route starts and never again until something asks.\n *\n * Omitting `refresh` means the same thing, so this exists for the case where\n * the cadence is COMPUTED: `refresh: pollCadence ?? \"manual\"` says what it\n * means, where the alternative is assembling the options object\n * conditionally. It also restores the sentinel precedent `deferral`\n * already sets with `defaultTtl: \"never\"` and `retention: \"never\"`.\n */\nexport const MANUAL_REFRESH = \"manual\";\n\n/**\n * `drainGrace` value meaning \"wait as long as it takes\": the disable never\n * forces, and in-flight exchanges always reach a terminal outcome.\n *\n * The route stops intaking immediately either way, so this trades a bounded\n * transition for a guaranteed one. Choose it when the work is more expensive\n * to lose than the transition is to wait for, and only when the pipeline is\n * known to terminate; a step that can hang holds the disable open forever.\n */\nexport const NEVER_FORCE = \"never\";\n\n/** Options for the second argument of `.enabled()`. */\nexport interface EnablementOptions {\n  /**\n   * Re-evaluate the predicate on this cadence.\n   *\n   * Omitted (the default) is MANUAL: the predicate runs once as the route\n   * starts and never again until something explicitly asks. That keeps the\n   * common case, an environment variable that cannot change without a\n   * restart, free of any recurring cost, and it stops a predicate that\n   * reaches the network from becoming an invisible repeating one.\n   *\n   * Pass `\"manual\"` to say so explicitly, which is what a computed cadence\n   * wants: `refresh: pollCadence ?? \"manual\"`.\n   */\n  refresh?: RefreshCadence;\n\n  /**\n   * How long in-flight exchanges may keep running after the route stops\n   * intaking, before execution is abandoned.\n   *\n   * Defaults to the context's `shutdown.timeout`, because a disable is a\n   * per-route shutdown and one knob for both is what an operator expects to\n   * find. Set it per route when the author knows what this pipeline's\n   * in-flight work actually costs: a route whose steps take a minute needs\n   * longer than the 30 second default, and a route of fast steps can be\n   * taken out of service far quicker.\n   *\n   * `\"never\"` ({@link NEVER_FORCE}) waits indefinitely, so every in-flight\n   * exchange reaches a terminal outcome and nothing is abandoned. See\n   * {@link NEVER_FORCE} for when that is the right trade.\n   */\n  drainGrace?: Duration | typeof NEVER_FORCE;\n}\n\n/**\n * A route's enablement declaration, as stored on its definition.\n *\n * @internal The shape is internal; declare it with `.enabled()`.\n */\nexport interface RouteEnablement {\n  readonly predicate: EnablementPredicate;\n  readonly refresh?: RefreshCadence;\n  readonly drainGrace?: Duration | typeof NEVER_FORCE;\n}\n\n/**\n * Where a route stands: enabled, or disabled with the reason ops reports.\n *\n * A discriminated union rather than a `{ enabled, reason? }` pair so a\n * reader cannot consult `reason` on an enabled route, and so the disabled\n * arm can never be constructed without one.\n */\nexport type EnablementState =\n  | { readonly enabled: true }\n  | { readonly enabled: false; readonly reason: string };\n\n/** Reason recorded when a predicate returns a bare `false`. */\nexport const DEFAULT_DISABLED_REASON =\n  \"the route's enabled() predicate returned false\";\n\n/**\n * Whether a cadence re-evaluates on its own, as opposed to only when\n * something explicitly asks.\n *\n * The distinction the context's auto-stop turns on: a live cadence is a\n * reason to keep a context alive, and a manual one is not, because a manual\n * route has no in-process path back to enabled and waiting for one would\n * only cost the shutdown.\n */\nexport function isLiveCadence(\n  refresh: RefreshCadence | undefined,\n): refresh is Exclude<RefreshCadence, typeof MANUAL_REFRESH> {\n  return refresh !== undefined && refresh !== MANUAL_REFRESH;\n}\n\n/**\n * Whether a refresh cadence is a cron schedule rather than an interval.\n *\n * Shape alone decides it. A cron expression is either a nickname (`@daily`)\n * or whitespace-separated fields; a `Duration` is a number or a single\n * unit-suffixed token, so neither form can be mistaken for the other.\n *\n * Returns a plain `boolean` rather than a type predicate on purpose.\n * `CronExpression` ends in `(string & {})`, which absorbs every string in\n * the union, so `refresh is CronExpression` would narrow the FALSE branch to\n * `number` while `\"5m\"` routinely flows through it. The next edit there that\n * trusted the compiler's `number` would compile and produce `NaN`.\n */\nexport function isCronCadence(refresh: RefreshCadence): boolean {\n  return (\n    typeof refresh === \"string\" &&\n    refresh !== MANUAL_REFRESH &&\n    (refresh.startsWith(\"@\") || /\\s/.test(refresh.trim()))\n  );\n}\n\n/**\n * Run a route's predicate and turn whatever it did into an\n * {@link EnablementState}.\n *\n * Total by construction: every return value, and every throw, maps onto a\n * state. Nothing here rethrows, because the caller is the boot path and a\n * predicate is not allowed to fail it.\n *\n * @param enablement - The route's declaration.\n * @returns The resolved state. Never rejects.\n */\nexport async function evaluateEnablement(\n  enablement: RouteEnablement,\n  onThrow?: (err: unknown) => void,\n): Promise<EnablementState> {\n  try {\n    const verdict = await enablement.predicate();\n    if (verdict === true) return { enabled: true };\n    if (verdict === false) {\n      return { enabled: false, reason: DEFAULT_DISABLED_REASON };\n    }\n    if (typeof verdict === \"string\") {\n      const reason = verdict.trim();\n      return {\n        enabled: false,\n        reason: reason === \"\" ? DEFAULT_DISABLED_REASON : reason,\n      };\n    }\n    // A JS caller returning a number, null or an object: treat anything that\n    // is not an explicit `true` as \"not enabled\" rather than coercing. A\n    // truthy object silently enabling a route whose credentials are absent\n    // is the exact failure this feature exists to prevent.\n    return {\n      enabled: false,\n      reason: `the route's enabled() predicate returned ${typeof verdict}, which is not a boolean or a reason string`,\n    };\n  } catch (err) {\n    // This is a BOUNDARY in the sense of `.standards/error-and-logging-policy.md`:\n    // user code threw, and it is handled here rather than re-thrown. The\n    // reason string keeps only the message, so the caller is handed the raw\n    // error to log; without that the stack is lost and a broken predicate is\n    // indistinguishable from a deliberately-off route in the logs.\n    onThrow?.(err);\n    const message =\n      err instanceof Error ? err.message : String(err ?? \"unknown error\");\n    return {\n      enabled: false,\n      reason: `the route's enabled() predicate threw: ${message}`,\n    };\n  }\n}\n\n/**\n * Resolve a route's drain grace to milliseconds, or `undefined` for the\n * context default, or `null` when the route opted out of forcing entirely.\n *\n * Three-way rather than two, because \"use the context's knob\" and \"never\n * force\" are different instructions and a number cannot carry both.\n *\n * @internal\n */\nexport function resolveDrainGrace(\n  route: EnablementRoute,\n): number | undefined | null {\n  const grace = route.definition.enablement?.drainGrace;\n  if (grace === undefined) return undefined;\n  if (grace === NEVER_FORCE) return null;\n  return parseDuration(\n    grace,\n    `route \"${route.definition.id}\" .enabled({ drainGrace })`,\n    0,\n  );\n}\n\n/**\n * Resolve a refresh cadence into the milliseconds an interval should use.\n *\n * @throws RC5003 when the value is neither a cron expression nor a usable\n *   duration.\n */\nexport function refreshIntervalMs(refresh: Duration, routeId: string): number {\n  return parseDuration(refresh, `route \"${routeId}\" .enabled({ refresh })`);\n}\n\n/**\n * Load `croner`, the same optional peer the `cron()` adapter uses.\n *\n * Loaded lazily and only for a route that actually declared a cron refresh,\n * so a context whose routes all use the default manual cadence never pays\n * for a dependency it does not use. Kept as a static field for the same\n * reason the cron source does: tests replace it without touching the\n * module registry.\n *\n * @internal\n */\nexport const loadCronDriver: { current: () => Promise<typeof CronType> } = {\n  current: () =>\n    loadOptionalPeer(() => import(\"croner\"), {\n      consumer: \"route .enabled({ refresh }) cron cadence\",\n      packageName: \"croner\",\n    }).then((m) => m.Cron),\n};\n\n/**\n * Owns every route's enablement state, its refresh cadence, and the\n * transitions between the two states.\n *\n * The context owns one of these. It is deliberately the ONLY thing that\n * decides whether a route is running for enablement reasons: ops reads its\n * state, the capability surface filters on it, and the refresh timers drive\n * it. Splitting the refresh scheduler into its own plugin stays attractive\n * for keeping core lean and is a follow-up, not a reason to spread the\n * decision across two owners now.\n *\n * @internal The class is internal; reach it through `CraftContext`.\n */\nexport class RouteEnablementCoordinator<\n  R extends EnablementRoute = EnablementRoute,\n> {\n  readonly #states = new Map<string, EnablementState>();\n  readonly #intervals = new Map<string, ReturnType<typeof setInterval>>();\n  readonly #crons = new Map<string, CronType>();\n  /** Newest in-flight transition per route id; see {@link refresh}. */\n  readonly #inFlight = new Map<string, Promise<EnablementState>>();\n  #stopped = false;\n\n  /**\n   * @param deps - The context's own capabilities, injected rather than\n   *   imported so this file stays testable without building a context and\n   *   free of a cycle back into `context.ts`.\n   */\n  constructor(private readonly deps: EnablementDeps<R>) {}\n\n  /** Whether this route may run. True for a route that never declared one. */\n  isEnabled(routeId: string): boolean {\n    return this.#states.get(routeId)?.enabled !== false;\n  }\n\n  /** Every disabled route, id to reason. Ops renders this. */\n  disabled(): ReadonlyMap<string, string> {\n    const out = new Map<string, string>();\n    for (const [id, state] of this.#states) {\n      if (!state.enabled) out.set(id, state.reason);\n    }\n    return out;\n  }\n\n  /**\n   * Evaluate the declaring routes once, before any route starts.\n   *\n   * Run as a batch ahead of the boot rather than per route inside it, so one\n   * slow predicate delays only the decision and never sits between two\n   * unrelated routes starting.\n   *\n   * Takes the ALREADY-FILTERED list rather than filtering here, because the\n   * caller must be able to skip this call entirely: awaiting it is an extra\n   * turn on the boot path, and a context whose routes declare no predicate\n   * must not pay one (a `start()` racing a `stop()` interleaves differently\n   * across that turn).\n   *\n   * @param declaring - Routes that declared `.enabled()`. Nothing else.\n   * @returns The ids that must NOT be started.\n   */\n  async evaluateForBoot(\n    declaring: ReadonlyArray<R>,\n  ): Promise<ReadonlySet<string>> {\n    await Promise.all(\n      declaring.map(async (route) => {\n        const enablement = route.definition.enablement;\n        if (!enablement) return;\n        const state = await evaluateEnablement(\n          enablement,\n          this.#logPredicateThrow(route),\n        );\n        this.#record(route, state);\n      }),\n    );\n    const skip = new Set<string>();\n    for (const [id, state] of this.#states) {\n      if (!state.enabled) skip.add(id);\n    }\n    return skip;\n  }\n\n  /**\n   * Arm the refresh cadences, once the boot has settled.\n   *\n   * Separate from {@link RouteEnablementCoordinator.evaluateForBoot} because\n   * a timer armed before the routes are up could fire a transition into a\n   * context that is still starting.\n   *\n   * Awaited by the caller, and a cadence that cannot be armed REJECTS. A\n   * cadence is authored configuration, so an unusable one is the author's\n   * error and gets the same treatment either form receives: a malformed\n   * `Duration` already throws when the route is built, and `cron()` already\n   * rejects its subscribe on a bad expression or an absent `croner`. Warning\n   * here instead would have left one arm of the same option silently\n   * degraded.\n   */\n  async startRefreshing(routes: ReadonlyArray<R>): Promise<void> {\n    if (this.#stopped) return;\n    const arming: Promise<void>[] = [];\n    for (const route of routes) {\n      const refresh = route.definition.enablement?.refresh;\n      // Absent and `\"manual\"` are the same state deliberately: the sentinel\n      // exists to let an author SAY manual, not to behave differently.\n      if (refresh === undefined || refresh === MANUAL_REFRESH) continue;\n      if (isCronCadence(refresh)) {\n        arming.push(this.#armCron(route, refresh as CronExpression));\n      } else {\n        const ms = refreshIntervalMs(refresh as Duration, route.definition.id);\n        const timer = setInterval(() => {\n          void this.refresh(route);\n        }, ms);\n        // Deliberately NOT unref'd. A declared cadence is ongoing work the\n        // author asked for, exactly like a plugin's `keepsAlive`, and the\n        // context suppresses its auto-stop for it. Unref'ing while also\n        // suppressing the auto-stop is the contradiction that strands a\n        // context: nothing refs the loop, so the process exits having run no\n        // teardown, and the re-check the cadence promised never happens.\n        // `stop()` clears every timer, so this cannot outlive a shutdown.\n        this.#intervals.set(route.definition.id, timer);\n      }\n    }\n    await Promise.all(arming);\n  }\n\n  /**\n   * Re-evaluate one route's predicate now and apply any transition.\n   *\n   * This is the internal control surface the deferred ops re-evaluate\n   * endpoint will call: the operator sets the secret, asks for a re-check,\n   * and the route comes up without a process restart. Adding that endpoint\n   * is wiring rather than redesign precisely because this exists.\n   *\n   * @returns The state after the re-evaluation.\n   */\n  async refresh(route: R): Promise<EnablementState> {\n    const id = route.definition.id;\n    // Serialised per route. Three drivers reach this concurrently (an\n    // interval tick, a cron fire, an operator's on-demand re-check) and a\n    // transition is long: a disable holds until its drain grace elapses.\n    // Overlapping them lets a stale disable force-abort the execution\n    // controller of the run that a later enable already restarted, leaving\n    // the route reporting enabled while its execution signal is aborted.\n    // Chained rather than dropped, so an on-demand re-check still takes\n    // effect rather than being silently swallowed by an in-flight tick.\n    const chained = (this.#inFlight.get(id) ?? Promise.resolve())\n      .catch(() => undefined)\n      .then(() => this.#refreshNow(route));\n    this.#inFlight.set(id, chained);\n    try {\n      return await chained;\n    } finally {\n      // Only the newest link clears the slot; an older one finishing must\n      // not drop a successor that is still queued behind it.\n      if (this.#inFlight.get(id) === chained) this.#inFlight.delete(id);\n    }\n  }\n\n  /** One transition, with no other transition for this route in flight. */\n  async #refreshNow(route: R): Promise<EnablementState> {\n    const enablement = route.definition.enablement;\n    if (!enablement) return { enabled: true };\n    if (this.#stopped) {\n      return this.#states.get(route.definition.id) ?? { enabled: true };\n    }\n    const next = await evaluateEnablement(\n      enablement,\n      this.#logPredicateThrow(route),\n    );\n    // Re-checked after the predicate: it is user code of unbounded duration,\n    // so a shutdown can complete while it runs. Without this a slow predicate\n    // resolving after `context:stopped` restarts the route behind the\n    // shutdown, and nothing is left to ever stop it again.\n    if (this.#stopped) return next;\n    const previous = this.#states.get(route.definition.id);\n    this.#record(route, next);\n    if (previous === undefined || previous.enabled === next.enabled) {\n      return next;\n    }\n    if (next.enabled) {\n      await this.#enable(route);\n    } else {\n      await this.#disable(route, next.reason);\n    }\n    return next;\n  }\n\n  /** Re-evaluate every declaring route. The all-routes control surface. */\n  async refreshAll(\n    routes: ReadonlyArray<R>,\n  ): Promise<ReadonlyMap<string, EnablementState>> {\n    await Promise.all(\n      routes\n        .filter((r) => r.definition.enablement)\n        .map((route) => this.refresh(route)),\n    );\n    return new Map(this.#states);\n  }\n\n  /**\n   * Drop every refresh timer. Called from context shutdown, before the\n   * routes are torn down, so no transition can start against a context that\n   * is on its way out.\n   */\n  stop(): void {\n    this.#stopped = true;\n    for (const timer of this.#intervals.values()) clearInterval(timer);\n    this.#intervals.clear();\n    for (const cron of this.#crons.values()) cron.stop();\n    this.#crons.clear();\n  }\n\n  /**\n   * Take a running route out of service: stop intake, let in-flight\n   * exchanges finish, then abandon whatever is left once the grace deadline\n   * passes.\n   *\n   * Exactly what shutdown does per route, through the same two signals, for\n   * the same reason: a flag flip must never be a data-loss event. There is\n   * deliberately no second stop path.\n   *\n   * The deadline is the route's own `drainGrace` when it declared one, and\n   * the context's `shutdown.timeout` otherwise. `\"never\"` waits indefinitely,\n   * which is the only setting under which no exchange is ever abandoned.\n   */\n  async #disable(route: R, reason: string): Promise<void> {\n    const graceMs = resolveDrainGrace(route);\n    this.deps.logger().info(\n      {\n        route: route.definition.id,\n        reason,\n        ...(graceMs === undefined ? {} : { graceMs }),\n      },\n      \"Route disabled by its enabled() predicate; draining\",\n    );\n    // Stage one: intake only. Work already in the pipeline runs to its\n    // natural end, which is the whole difference between a drain and a\n    // cancellation.\n    this.deps.abortIntake(route.definition.id, `disabled: ${reason}`);\n    const drained = await this.deps.drainWithin(route, graceMs);\n    // Deliberately NOT guarded on `#stopped`. Aborting intake lets a server\n    // ingress resolve its subscribe, which can settle the context's own\n    // route promises and trip its auto-stop while this drain is still\n    // running. `#stopped` therefore goes true on the ordinary path, and\n    // skipping the force here would leave the wedged work running.\n    // Guarding the stale-transition case needs a per-route token, not this\n    // flag; see the serialisation in `refresh`.\n    if (!drained) {\n      route.abortExecution(`disabled: ${reason}`);\n    }\n  }\n\n  /** Bring a disabled route up: re-arm it, then start it normally. */\n  async #enable(route: R): Promise<void> {\n    if (this.#stopped) return;\n    this.deps\n      .logger()\n      .info(\n        { route: route.definition.id },\n        \"Route enabled by its enabled() predicate; starting\",\n      );\n    try {\n      await this.deps.startRoute(route);\n    } catch (err) {\n      // A route that could not start is a FAILED route, not a disabled one,\n      // and the two must stay distinct: disabled is a deliberate\n      // configuration state that never pages, and reporting a broken start\n      // as disabled would hide a real incident behind it. Leave the state\n      // enabled and let the route's own failure path report it.\n      this.deps\n        .logger()\n        .error(\n          { route: route.definition.id, err },\n          \"Route was re-enabled but failed to start\",\n        );\n    }\n  }\n\n  /**\n   * The boundary log for a throwing `.enabled()` predicate.\n   *\n   * `error` level with `{ route, err }`, matching the agent tool policy\n   * predicate row in `.standards/error-and-logging-policy.md`: both are user\n   * code the framework calls and handles rather than propagates, and in both\n   * the raw error is only ever seen here.\n   */\n  #logPredicateThrow(route: R): (err: unknown) => void {\n    return (err) => {\n      this.deps\n        .logger()\n        .error(\n          { route: route.definition.id, err },\n          \"Route enabled() predicate threw; the route is left disabled\",\n        );\n    };\n  }\n\n  /** Store the state and announce a genuine change. */\n  #record(route: R, state: EnablementState): void {\n    const previous = this.#states.get(route.definition.id);\n    this.#states.set(route.definition.id, state);\n    // Only a real transition is announced. A five-minute cadence over a\n    // stable predicate would otherwise emit a heartbeat that every listener\n    // has to filter, and the one event that matters would be lost in it.\n    if (previous !== undefined && previous.enabled === state.enabled) return;\n    this.deps.emitChanged(route, state);\n  }\n\n  /**\n   * Arm a cron cadence, loading `croner` only for a route that wants one.\n   *\n   * `croner` is an optional peer resolved by an async dynamic import, so its\n   * grammar cannot be consulted while the route is being built: the peer may\n   * not be installed, and the load cannot happen inside a synchronous\n   * constructor. That is why an expression is validated HERE and not at\n   * build time, and it is also why the framework does not pre-check the\n   * expression itself. A second grammar of our own would disagree with\n   * croner at the edges, and rejecting an expression croner accepts is worse\n   * than validating a moment later: it breaks a working route.\n   *\n   * @throws RC5003 when the expression is one croner refuses, wrapping the\n   *   driver's own message. A missing `croner` surfaces as the RC5017 the\n   *   optional-peer loader raises, with its install hint intact.\n   */\n  async #armCron(route: R, expression: CronExpression): Promise<void> {\n    const Cron = await loadCronDriver.current();\n    if (this.#stopped) return;\n    try {\n      this.#crons.set(\n        route.definition.id,\n        new Cron(expression, () => {\n          void this.refresh(route);\n        }),\n      );\n    } catch (err) {\n      // Croner stays the authority on what a cron expression means; this\n      // only names the route and the option so the message says where to\n      // look, rather than surfacing a bare parser error.\n      throw rcError(\"RC5003\", undefined, {\n        message: `Route \"${route.definition.id}\": .enabled({ refresh: ${JSON.stringify(expression)} }) is not a cron expression croner accepts. ${err instanceof Error ? err.message : String(err)}`,\n      });\n    }\n  }\n}\n\n/** The subset of a route the coordinator touches. @internal */\nexport interface EnablementRoute {\n  readonly definition: {\n    readonly id: string;\n    readonly enablement?: RouteEnablement;\n  };\n  abortExecution(reason?: unknown): void;\n}\n\n/**\n * What the coordinator needs from its context, injected at construction.\n *\n * An interface rather than a `CraftContext` so this module does not import\n * the context that owns it, and so the transitions can be driven directly\n * in a test.\n *\n * @internal\n */\nexport interface EnablementDeps<R extends EnablementRoute = EnablementRoute> {\n  logger(): {\n    info(obj: object, msg: string): void;\n    error(obj: object, msg: string): void;\n  };\n  /** Fire the route's intake signal: stop accepting, keep running. */\n  abortIntake(routeId: string, reason: string): void;\n  /**\n   * Wait for the route to drain. False when the grace elapsed first.\n   *\n   * @param graceMs - The route's own grace in milliseconds; `undefined` for\n   *   the context's `shutdown.timeout`; `null` to wait indefinitely.\n   */\n  drainWithin(route: R, graceMs: number | undefined | null): Promise<boolean>;\n  /** Re-arm and start a route that was disabled. */\n  startRoute(route: R): Promise<void>;\n  emitChanged(route: R, state: EnablementState): void;\n}\n","import { type Duration, parseDuration } from \"./shared/duration.ts\";\nimport { rejectStaleOptions } from \"./shared/stale-options.ts\";\nimport {\n  isLiveCadence,\n  RouteEnablementCoordinator,\n  type EnablementState,\n} from \"./enablement.ts\";\nimport { randomUUID } from \"node:crypto\";\nimport { BRAND, setBrand } from \"./brand.ts\";\nimport { DefaultRoute, type Route, type RouteDefinition } from \"./route.ts\";\nimport {\n  CAPABILITY_REGISTRY,\n  snapshotCapability,\n  type Capability,\n} from \"./capabilities.ts\";\nimport { rcError, RC } from \"./error.ts\";\nimport { isRoutecraftError } from \"./brand.ts\";\nimport { logger, childBindings } from \"./logger.ts\";\nimport { type AdapterOverride, RC_ADAPTER_OVERRIDES } from \"./testing-hooks.ts\";\nimport { getConfigAppliers } from \"./config-applier.ts\";\nimport { DEFERRAL_RUNTIME } from \"./deferral/runtime-key.ts\";\nimport { EventBus } from \"./event-bus.ts\";\n\nimport type { EventHandler, EventName, EventPayload } from \"./types.ts\";\n\n/**\n * Store key for runner-provided argv tokens.\n *\n * Set by `craft run` (or any runner) before `context.start()` so that\n * adapters can read the remaining CLI arguments without coupling to a\n * specific runner package.\n */\nexport const RUNNER_ARGV: unique symbol = Symbol.for(\"routecraft.runner.argv\");\n\n/**\n * Base store registry that can be extended by adapters\n *\n * @example\n * ```typescript\n * // Extend the store registry with channel adapter types\n * declare module \"@routecraft/routecraft\" {\n *   interface StoreRegistry {\n *     \"routecraft.adapter.channel.store\": Map<string, import(\"./adapters/channel.ts\").MessageChannel>;\n *     \"routecraft.adapter.channel.config\": Partial<ChannelAdapterOptions>;\n *   }\n * }\n * ```\n */\nexport interface StoreRegistry {\n  [key: `${string}.${string}.${string}`]: unknown;\n  [RUNNER_ARGV]: string[];\n  [RC_ADAPTER_OVERRIDES]: AdapterOverride[];\n}\n\n/**\n * Options with merged configuration support.\n * This type is used for adapters that support both direct options and\n * options that can be merged with context configuration.\n */\nexport type MergedOptions<T> = {\n  /** Direct options for configuration */\n  options: Partial<T>;\n\n  /**\n   * Function to merge options with context configuration\n   * @param context The CraftContext instance\n   * @returns Merged options\n   */\n  mergedOptions(context: CraftContext): T;\n};\n\n/**\n * A plugin configures the context and may own work for as long as it runs.\n *\n * Three phases, each answering a different question:\n *\n * - `apply(ctx)` wires the context, before routes are registered\n *   (`initPlugins()`). Nothing is running yet.\n * - `start(ctx)` begins work, after every route has started. Optional.\n * - `teardown(ctx)` releases whatever the other two acquired, when the\n *   context stops and routes have drained. Optional.\n *\n * The split matters for anything with a lifetime. A plugin that opens a\n * handle does it in `apply()`; a plugin that starts a timer or drives routes\n * does it in `start()`, because at `apply()` time there are no routes to\n * drive. Either way `teardown()` is what releases it.\n *\n * Plugins needing neither can omit both; use `ctx.registerTeardown()` from\n * `apply()` for one-off cleanup callbacks.\n */\nexport interface CraftPlugin {\n  /**\n   * Stable identifier for the plugin, surfaced as `pluginId` on\n   * `plugin:*` event payloads and in logs. Falls back to the plugin's\n   * constructor name (or `plugin-<index>`) when omitted.\n   */\n  name?: string;\n  /**\n   * RESERVED. Names of plugins this plugin depends on. Not enforced yet:\n   * declaring it today has no effect, but the key is reserved so a\n   * future dependency-ordered initialisation can use it without a\n   * breaking change.\n   */\n  dependsOn?: string[];\n  /** Keep the context running after all routes complete until `stop()` is called. */\n  keepsAlive?: boolean;\n  apply(ctx: CraftContext): void | Promise<void>;\n  /**\n   * Called once per context start, after every route has been started, in\n   * plugin registration order. Awaited. Optional.\n   *\n   * This is where a plugin owning a background task belongs, because\n   * `apply()` runs at build time when no route is running yet. A plugin\n   * that starts something here MUST stop it in {@link CraftPlugin.teardown}:\n   * a live interval keeps the process alive with no visible cause.\n   *\n   * A throw fails `context.start()`. The context then shuts down (routes\n   * aborted and drained, every plugin torn down in reverse order) and the\n   * original error is rethrown unchanged, so a plugin that fails to start\n   * cannot leave a half-running context behind.\n   */\n  start?(ctx: CraftContext): void | Promise<void>;\n  /**\n   * Called when the context stops, after routes have drained, and when a\n   * build or a start failed partway. Optional.\n   *\n   * The second argument says which of those happened, so a plugin never has\n   * to infer it from its own state. Ignore it and the hook behaves exactly\n   * as it did when teardown only ran on a fully started context; read it\n   * when releasing depends on how far the context got.\n   */\n  teardown?(ctx: CraftContext, info: TeardownInfo): void | Promise<void>;\n}\n\n/**\n * What the context managed to do before this teardown, handed to every\n * {@link CraftPlugin.teardown}.\n *\n * The distinction exists because teardown now runs on three different\n * shapes of context: one that started and is stopping, one whose build\n * failed with only some plugins applied, and one whose start failed with\n * only some plugins started. A plugin that closes what `apply()` opened\n * needs none of this; a plugin that stops what `start()` began must not be\n * told to stop something it never began.\n */\nexport interface TeardownInfo {\n  /**\n   * This is not a fully started context. Either it never started (a build\n   * that failed partway, or an embedder that built and then stopped without\n   * ever calling `start()`) or a `start()` hook threw. Routes may not be\n   * registered and later plugins may never have applied, so state a plugin\n   * would expect a running context to hold may be missing.\n   */\n  partial: boolean;\n  /**\n   * THIS plugin's own `start()` hook ran to completion. Always false for a\n   * plugin with no `start()` hook, and false during a build-failure unwind,\n   * where nothing started.\n   */\n  started: boolean;\n}\n\n/**\n * How long `start()` waits for routes to signal readiness before starting\n * plugins anyway. Generous, because it is a backstop against a source that\n * never signals rather than a deadline anything healthy approaches.\n */\nconst ROUTE_READINESS_TIMEOUT_MS = 30_000;\n\n/**\n * What became of one route by the time the readiness gate settled.\n * `waiting` means the backstop fired before the route signalled, which is\n * a different operational problem from a route that failed outright.\n */\ntype RouteBootOutcome = \"started\" | \"failed\" | \"waiting\" | \"disabled\";\n\n/**\n * Validate `shutdown.timeout` at construction.\n *\n * Refused rather than clamped, and refused while the context is being built\n * rather than when it stops: a `0` reads as \"no bound\" and behaves as \"force\n * immediately\", and an operator discovering that during an outage is the worst\n * possible moment to learn the polarity.\n *\n * @throws RC5058 when the value is not a positive, finite duration. The\n *   shutdown-specific code is kept rather than letting `parseDuration`'s\n *   generic RC5003 surface, because RC5058 carries the polarity warning an\n *   operator needs and the docs page is written against that code.\n */\nfunction resolveShutdownTimeout(timeout: Duration | undefined): number {\n  if (timeout === undefined) return DEFAULT_SHUTDOWN_TIMEOUT_MS;\n  try {\n    return parseDuration(timeout, \"shutdown.timeout\");\n  } catch {\n    throw rcError(\"RC5058\", undefined, {\n      message: `shutdown.timeout must be a positive number of milliseconds or a duration string like \"30s\". Received ${JSON.stringify(timeout)}. Omit it to use the ${String(DEFAULT_SHUTDOWN_TIMEOUT_MS)}ms default.`,\n    });\n  }\n}\n\n/**\n * Refuse pre-0.7 `Ms`-suffixed names on the config's authored durations.\n *\n * Checked here rather than in `defineConfig()`, which is an optional typing\n * helper: a config object handed straight to the context would otherwise\n * skip the guard entirely, and a `shutdown.timeoutMs` that means nothing is\n * a 30-second default nobody asked for.\n */\nfunction rejectStaleConfig(config: CraftConfig): void {\n  rejectStaleOptions(config.shutdown, \"shutdown\");\n  for (const [name, server] of Object.entries(config.servers ?? {})) {\n    rejectStaleOptions(server, `servers.${name}`);\n  }\n  rejectStaleOptions(config.telemetry?.sqlite, \"telemetry.sqlite\");\n}\n\n/** Shared empty set, so the no-predicate boot path allocates nothing. */\nconst EMPTY_ROUTE_IDS: ReadonlySet<string> = new Set<string>();\n\n/** Rejection marker for the shutdown deadline, so it cannot be confused with a drain failure. */\nconst SHUTDOWN_DEADLINE = Symbol(\"routecraft.shutdown.deadline\");\n\n/**\n * Config keys handled directly by the CraftContext constructor, as opposed\n * to keys claimed by registered config appliers. Used to detect config keys\n * that nothing consumes. Must stay in sync with the fields of\n * {@link CraftConfig} declared in this file (ecosystem augmentations are\n * covered by the applier registry instead).\n */\nconst BASE_CONFIG_KEYS: ReadonlySet<string> = new Set([\n  \"name\",\n  \"store\",\n  \"on\",\n  \"once\",\n  \"plugins\",\n  \"shutdown\",\n]);\n\n/**\n * Configuration options for creating a CraftContext.\n *\n * Declared as an `interface` so ecosystem packages can extend it via\n * declaration merging. Pair an augmentation with `registerConfigApplier`\n * to promote an ecosystem capability to a first-class config key.\n *\n * @example\n * ```typescript\n * declare module \"@routecraft/routecraft\" {\n *   interface CraftConfig {\n *     myCapability?: MyCapabilityOptions;\n *   }\n * }\n * ```\n */\nexport interface CraftConfig {\n  /**\n   * Service / application name for this context. Emitted on every log line as\n   * `service.name` (the OpenTelemetry semantic convention), so log aggregators\n   * that map OTel resource attributes (e.g. BetterStack `resources.service.name`)\n   * can identify the originating app. When omitted, no `service.name` field is\n   * added to logs.\n   */\n  name?: string;\n  /** Initial values for the context store */\n  store?: Map<keyof StoreRegistry, StoreRegistry[keyof StoreRegistry]>;\n  /** Event handlers to register on context creation */\n  on?: Partial<\n    Record<EventName, EventHandler<EventName> | EventHandler<EventName>[]>\n  >;\n  /** One-time event handlers to register on context creation (fire once, then auto-unsubscribe) */\n  once?: Partial<\n    Record<EventName, EventHandler<EventName> | EventHandler<EventName>[]>\n  >;\n  /** Plugins to run before routes are registered (call initPlugins() then registerRoutes) */\n  plugins?: CraftPlugin[];\n  /** How long a graceful shutdown may drain before it is forced. */\n  shutdown?: ShutdownConfig;\n}\n\n/**\n * Bounds on {@link CraftContext.stop}.\n *\n * Shutdown behaviour is a property of the app, not of one invocation, which\n * is why this is config rather than a CLI flag: the same bound applies to a\n * signal, to `craft start --once`, and to an embedder calling `stop()`.\n */\nexport interface ShutdownConfig {\n  /**\n   * How long stage one may drain in-flight exchanges before stage two is\n   * forced. Defaults to {@link DEFAULT_SHUTDOWN_TIMEOUT_MS}.\n   *\n   * Set it BELOW the platform's own kill timer (Kubernetes\n   * `terminationGracePeriodSeconds` and friends) so the process's policy\n   * decides the outcome rather than the platform's: past that timer the\n   * platform sends SIGKILL and whatever stage two was meant to do is lost.\n   */\n  timeout?: Duration;\n}\n\n/**\n * How long a graceful shutdown drains before it is forced. Thirty seconds\n * because it sits under the common platform defaults (Kubernetes ships 30s\n * itself, and operators who raise it raise this with it) while being long\n * enough that ordinary in-flight work finishes inside it.\n */\nexport const DEFAULT_SHUTDOWN_TIMEOUT_MS = 30_000;\n\n/**\n * What a completed {@link CraftContext.stop} reports.\n *\n * Returned because it is an answer the caller acts on: `shutdownHandler`\n * maps it to an exit code, and `craft start --once` reports a forced stop as\n * a failure. The same pair also rides on `context:stopped`, because counting\n * forced shutdowns is observability and an exit code is not something an\n * in-process subscriber can read.\n */\nexport interface ShutdownOutcome {\n  /**\n   * Stage one did not finish inside the deadline, so in-flight execution was\n   * abandoned. The process should exit non-zero.\n   */\n  forced: boolean;\n  /**\n   * Route ids that still had work in flight when the deadline hit. Empty on\n   * a clean stop, so the shape does not change between the two arms.\n   */\n  pending: string[];\n}\n\n/**\n * The main context for running and managing routes.\n *\n * CraftContext is the central runtime environment that:\n * - Manages the lifecycle of routes\n * - Provides a storage system for adapters\n * - Handles startup and shutdown of the application\n *\n * @example\n * ```typescript\n * // Create a context with routes and event handlers\n * const context = new CraftContext({\n *   on: {\n *     'context:starting': async () => {\n *       console.log('Starting application');\n *     },\n *     'context:stopping': async () => {\n *       console.log('Shutting down application');\n *     }\n *   }\n * });\n *\n * // Register routes\n * context.registerRoutes(myRoute1, myRoute2);\n *\n * // Start processing routes\n * await context.start();\n *\n * // Later, stop all routes\n * await context.stop();\n * ```\n */\nexport class CraftContext {\n  /** Unique identifier for this context instance */\n  public readonly contextId: string = randomUUID();\n\n  /** Service / application name, surfaced on logs as `service.name`. */\n  public readonly name?: string;\n\n  /** Routes registered with this context */\n  private routes: Route[] = [];\n\n  /** Abort controllers for each route */\n  private controllers: Map<string, AbortController> = new Map();\n\n  /**\n   * Owns every route's `.enabled()` state, its refresh cadence, and the\n   * transitions between them. Built eagerly (it is a few maps) so the\n   * capability filter and ops can read it whether or not any route\n   * declares a predicate.\n   */\n  private readonly enablement = new RouteEnablementCoordinator<Route>({\n    logger: () => this.logger,\n    abortIntake: (routeId, reason) => {\n      // The route's INTAKE controller, the same one shutdown's stage one\n      // fires. Sources stop producing; in-flight exchanges are untouched.\n      this.controllers.get(routeId)?.abort(reason);\n    },\n    drainWithin: (route, graceMs) => this.drainRouteWithin(route, graceMs),\n    startRoute: (route) => this.restartRoute(route),\n    emitChanged: (route, state) => {\n      this.emit(\"route:enablement:changed\", {\n        routeId: route.definition.id,\n        route,\n        enabled: state.enabled,\n        ...(state.enabled ? {} : { reason: state.reason }),\n      });\n    },\n  });\n\n  /** Storage for adapter configuration and state */\n  private store = new Map<\n    keyof StoreRegistry,\n    StoreRegistry[keyof StoreRegistry]\n  >();\n\n  /** Logger for this context (pino child logger) */\n  public readonly logger: ReturnType<typeof logger.child>;\n\n  /** Event bus backing on/once/emit (see event-bus.ts) */\n  private readonly events: EventBus;\n\n  /** Plugins from config, run by initPlugins() before routes are registered */\n  private readonly plugins: CraftPlugin[] = [];\n\n  /** Guards initPlugins() so start() can call it idempotently */\n  private pluginsInitialized = false;\n\n  /**\n   * Indices of plugins whose `apply()` returned. Teardown walks this rather\n   * than the whole plugin list: a build that failed at plugin 3 must not\n   * tear down plugin 4, which never ran.\n   */\n  private readonly appliedPlugins = new Set<number>();\n\n  /** Indices of plugins whose `start()` hook returned. */\n  private readonly startedPlugins = new Set<number>();\n\n  /** Latched once `start()` has fully completed, for {@link TeardownInfo.partial}. */\n  private startCompleted = false;\n\n  /** How long stage one of shutdown may drain; see {@link ShutdownConfig}. */\n  private readonly shutdownTimeoutMs: number;\n\n  /** Teardown callbacks registered by plugins; run during stop() before context:stopped */\n  private readonly teardownCallbacks: Array<() => void | Promise<void>> = [];\n\n  /** Cached shutdown promise so concurrent stop() callers all await the same teardown */\n  private shutdownPromise: Promise<ShutdownOutcome> | null = null;\n\n  /** Backing gate for {@link CraftContext.whenStarted}. */\n  private startedGate: PromiseWithResolvers<void> | undefined;\n\n  /** The in-flight start, so concurrent `start()` calls join one boot. */\n  private startInFlight: Promise<void> | undefined;\n\n  /**\n   * The plugin lifecycle hook currently awaiting, so a `stop()` that lands\n   * mid-boot can let it finish before teardown runs.\n   *\n   * Scoped to `apply()` and `start()` alone, never `run()`: for an\n   * indefinite route `run()` resolves only once the context stops, so\n   * waiting on it would deadlock the shutdown this ordering exists to serve.\n   */\n  private pluginHookInFlight: Promise<void> | undefined;\n\n  /** Latched by `stop()`. A stopped context refuses to start again. */\n  private hasStopped = false;\n\n  /**\n   * Create a new CraftContext instance.\n   *\n   * @param config Optional configuration for the context\n   */\n  constructor(config?: CraftConfig) {\n    setBrand(this, BRAND.CraftContext);\n    if (config !== undefined) rejectStaleConfig(config);\n    if (config?.name !== undefined) this.name = config.name;\n    this.shutdownTimeoutMs = resolveShutdownTimeout(config?.shutdown?.timeout);\n    this.logger = logger.child(childBindings(this));\n    this.events = new EventBus(this.contextId, this.logger);\n    if (config) {\n      // Initialize store from config\n      if (config.store) {\n        for (const [key, value] of config.store.entries()) {\n          this.store.set(key, value);\n        }\n      }\n\n      // Register event handlers from config\n      if (config.on) {\n        for (const [event, handler] of Object.entries(config.on)) {\n          if (Array.isArray(handler)) {\n            handler.forEach((h) => this.on(event as EventName, h));\n          } else if (handler) {\n            this.on(event as EventName, handler);\n          }\n        }\n      }\n\n      // Register one-time event handlers from config\n      if (config.once) {\n        for (const [event, handler] of Object.entries(config.once)) {\n          if (Array.isArray(handler)) {\n            handler.forEach((h) => this.once(event as EventName, h));\n          } else if (handler) {\n            this.once(event as EventName, handler);\n          }\n        }\n      }\n      // Walk registered config appliers. ALL first-class config keys go\n      // through this registry: core keys (`http`, `cron`, `direct`, `mail`,\n      // `telemetry`) are registered by side-effect imports in index.ts, and\n      // ecosystem packages (e.g. @routecraft/ai promotes `llm`, `mcp`,\n      // `embedding`, `agent`) extend it the same way. The core context has\n      // no knowledge of any adapter or plugin internals.\n      //\n      // The push order into `this.plugins` drives both apply() order\n      // (forward) and teardown() order (reverse):\n      //   1. registered appliers, in registration order (core keys first,\n      //      since index.ts imports run before ecosystem modules load)\n      //   2. user config.plugins\n      //\n      // Reverse-iteration in performShutdown() therefore tears down user\n      // plugins first, then appliers in reverse registration order.\n      //\n      // The applier guard is strictly `value !== undefined`, not a truthy\n      // check. The applier registry is an open extension point: ecosystem\n      // packages can register appliers for any value shape, including\n      // primitives where `false`, `0`, or `\"\"` are valid. \"Not set\" must\n      // mean only `undefined` so applier authors can rely on a stable\n      // contract regardless of value type.\n      const configRecord = config as unknown as Record<string, unknown>;\n      const applierKeys = new Set<string>();\n      for (const [key, factory] of getConfigAppliers()) {\n        applierKeys.add(key);\n        const value = configRecord[key];\n        if (value !== undefined) {\n          this.plugins.push(factory(value));\n        }\n      }\n\n      // A set config key that is neither a base key nor a registered applier\n      // is dead weight: a typo (`htttp`), or an applier whose registering\n      // module never loaded (the config-applier bundle regression shipped\n      // exactly this way, with `mail: {...}` silently ignored). Warn instead\n      // of throwing because appliers are an open registry and a false\n      // positive must not take down an otherwise valid context.\n      for (const key of Object.keys(configRecord)) {\n        if (configRecord[key] === undefined) continue;\n        if (BASE_CONFIG_KEYS.has(key) || applierKeys.has(key)) continue;\n        this.logger.warn(\n          { configKey: key },\n          `Unknown config key \"${key}\": no config applier is registered for it, so it has no effect. ` +\n            `Check the spelling, and ensure the package that provides the key is imported before the context is created.`,\n        );\n      }\n\n      if (config.plugins?.length) {\n        this.plugins.push(...config.plugins);\n      }\n    }\n  }\n\n  /**\n   * Generate a plugin identifier from the plugin's constructor name or index.\n   * @param plugin The plugin instance\n   * @param index The plugin's index in the plugins array\n   * @returns A string identifier for the plugin\n   */\n  private getPluginId(plugin: CraftPlugin, index: number): string {\n    if (typeof plugin.name === \"string\" && plugin.name) return plugin.name;\n    const constructorName =\n      plugin.constructor?.name !== \"Object\" ? plugin.constructor?.name : null;\n    return constructorName ?? `plugin-${index}`;\n  }\n\n  /**\n   * Run plugins from config. Called by the builder's `build()` (and by\n   * `start()` as an idempotent fallback) before routes are registered so\n   * plugins can set up state or dynamically add routes.\n   *\n   * Fails fast: on first plugin error, logs, emits `error`, and rethrows.\n   *\n   * @throws Rethrows if any plugin's `apply(ctx)` throws\n   * @internal Public for the builder and tests; not part of the supported\n   *   embedding surface. The context initialises plugins itself.\n   */\n  async initPlugins(): Promise<void> {\n    if (this.pluginsInitialized) return;\n    this.pluginsInitialized = true;\n    for (const [pluginIndex, plugin] of this.plugins.entries()) {\n      // Same guard as startPlugins(), for the same reason: once teardown has\n      // walked the applied set, a plugin applied after it acquires resources\n      // nothing will ever release.\n      if (this.hasStopped) return;\n      try {\n        if (\n          !plugin ||\n          typeof plugin !== \"object\" ||\n          typeof (plugin as CraftPlugin).apply !== \"function\"\n        ) {\n          const err = rcError(\"RC9901\", undefined, {\n            message: `Invalid plugin at index ${pluginIndex}: expected object with apply(ctx)`,\n          });\n          this.logger.error(\n            { pluginIndex, err },\n            \"Invalid plugin: expected object with apply(ctx) method.\",\n          );\n          this.emit(\"context:error\", { error: err });\n          throw err;\n        }\n\n        // Generate plugin ID from constructor name or index\n        const pluginId = this.getPluginId(plugin as CraftPlugin, pluginIndex);\n\n        // Plugins are \"registered\" at construction; a separate\n        // plugin:registered event fired at the same moment with the same\n        // payload carried no extra information and was removed.\n        this.emit(\"plugin:applying\", {\n          pluginId,\n          pluginIndex,\n        });\n\n        // Re-checked after the emit, not only at the loop head: handlers run\n        // synchronously, so a subscriber calling stop() lands between the two\n        // and the hook would otherwise start into a shutdown already waiting\n        // for it.\n        if (this.hasStopped) return;\n\n        await this.runLifecycleHook(async () => {\n          await (plugin as CraftPlugin).apply(this);\n          this.appliedPlugins.add(pluginIndex);\n          this.emit(\"plugin:applied\", { pluginId, pluginIndex });\n        });\n      } catch (err) {\n        this.logger.error(\n          { pluginIndex, err },\n          \"Plugin threw during initPlugins. Check stack and plugin implementation.\",\n        );\n        this.emit(\"context:error\", { error: err });\n        throw err;\n      }\n    }\n  }\n\n  /**\n   * Resolves once the context is fully started: every route has emitted\n   * `route:started` AND every plugin `start()` hook has resolved.\n   *\n   * `context.start()` cannot answer this, because it does not resolve until\n   * the routes complete, and an http or cron route completes at shutdown.\n   * Waiting on `route:started` alone answers only two thirds of the\n   * lifecycle, which is why anything needing a started context (a test\n   * harness, a readiness probe) waits here instead.\n   *\n   * A hook that performs bounded startup work is awaited by this, on\n   * purpose: the deferral sweeper's downtime scan has RUN by the time\n   * this resolves, so overdue expiries reach their routes before new\n   * traffic does. Rejects with the error that refused the start, which is a\n   * plugin `start()` hook or the context's own config. A single route that\n   * fails to come up is NOT observable here: `start()` keeps the remaining\n   * routes running by design, so a probe that must know a specific route is\n   * serving watches `route:started` for it.\n   *\n   * A context starts once (`start()` after `stop()` refuses with RC1004),\n   * so this settles exactly once and keeps reporting that outcome.\n   */\n  whenStarted(): Promise<void> {\n    return this.ensureStartedGate().promise;\n  }\n\n  /**\n   * The gate behind {@link CraftContext.whenStarted}, created on first\n   * use by either side.\n   *\n   * Lazy because most contexts never ask, and shared because `start()` has\n   * to settle the same promise a caller may already be holding.\n   *\n   * @internal\n   */\n  private ensureStartedGate(): PromiseWithResolvers<void> {\n    if (!this.startedGate) {\n      const deferred = Promise.withResolvers<void>();\n      // Nobody is obliged to await this, and a refused start must not\n      // surface as an unhandled rejection on top of the error start()\n      // already throws.\n      deferred.promise.catch(() => {});\n      this.startedGate = deferred;\n    }\n    return this.startedGate;\n  }\n\n  /**\n   * Resolve once every route has signalled readiness, or stopped trying.\n   *\n   * `Promise.allSettled` over the route starts cannot answer this: each\n   * mapped function runs only as far as its first `await`, so it returns\n   * when every route has ENTERED `start()`, not when its sources are\n   * listening. A plugin whose `start()` hook talks to a route would race\n   * the source's subscribe, and a readiness probe would report a context\n   * ready before its HTTP port was bound.\n   *\n   * A route that fails or completes counts as settled rather than ready.\n   * One failing route does not fail the context (`start()` keeps the others\n   * running by design), so readiness cannot report it either: what this\n   * waits for is that no route is still coming up, not that all of them did.\n   *\n   * The wait is bounded because readiness is not something every source\n   * signals. Everything `.from()` normalizes signals it (the iterable path\n   * from its loop, a bare callable on invocation), but a hand-written\n   * `Source` adapter that never calls `ready()` and never emits would\n   * otherwise hold the whole context down forever. The bound is a guard\n   * against that, not a deadline anything healthy approaches.\n   *\n   * @internal\n   */\n  private awaitRoutesStarted(disabled: ReadonlySet<string>): {\n    ready: Promise<void>;\n    settle: (routeId: string, outcome: RouteBootOutcome) => void;\n    outcomes: Map<string, RouteBootOutcome>;\n  } {\n    const pending = new Map<string, { resolve: () => void }>();\n    const outcomes = new Map<string, RouteBootOutcome>(\n      this.routes.map((route) => [\n        route.definition.id,\n        disabled.has(route.definition.id)\n          ? (\"disabled\" as const)\n          : (\"waiting\" as const),\n      ]),\n    );\n    // A disabled route is settled before the gate is armed rather than left\n    // to time out: it is never going to emit `route:started`, and making\n    // every boot with one dormant capability wait out the readiness bound\n    // would turn a deliberate configuration state into a slow start.\n    const waits = this.routes\n      .filter((route) => !disabled.has(route.definition.id))\n      .map(\n        (route) =>\n          new Promise<void>((resolve) => {\n            pending.set(route.definition.id, { resolve });\n          }),\n      );\n    const off = this.on(\"route:started\", ({ details }) => {\n      outcomes.set(details.routeId, \"started\");\n      pending.get(details.routeId)?.resolve();\n    });\n\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const bound = new Promise<void>((resolve) => {\n      timer = setTimeout(() => {\n        this.logger.warn(\n          { timeoutMs: ROUTE_READINESS_TIMEOUT_MS },\n          \"Some routes did not signal readiness in time; starting plugins anyway. A Source adapter that never calls ready() and never emits reaches readiness only when it produces its first message.\",\n        );\n        resolve();\n      }, ROUTE_READINESS_TIMEOUT_MS);\n      timer.unref?.();\n    });\n\n    return {\n      ready: Promise.race([Promise.all(waits).then(() => {}), bound]).finally(\n        () => {\n          off();\n          if (timer) clearTimeout(timer);\n        },\n      ),\n      // A route that failed or completed counts as settled, not started, so\n      // the gate stops waiting on it while the summary still reports what\n      // actually happened to it. A FAILURE is the final word: a source that\n      // signalled readiness and then rejected (an async callable that fails\n      // on its first await, which is what a bad credential or a refused\n      // connect looks like) did not come up, and the summary must not report\n      // it as started just because `route:started` had already fired.\n      settle: (routeId: string, outcome: RouteBootOutcome) => {\n        if (outcomes.get(routeId) === \"disabled\") return;\n        if (outcome === \"failed\" || outcomes.get(routeId) !== \"started\") {\n          outcomes.set(routeId, outcome);\n        }\n        pending.get(routeId)?.resolve();\n      },\n      outcomes,\n    };\n  }\n\n  /**\n   * Log one line saying whether the boot came up, after the readiness gate\n   * settles.\n   *\n   * `whenStarted()` deliberately cannot report a single route failing to\n   * bind, because partial availability is the design: one route failing\n   * does not fail the context. That leaves an operator watching a boot with\n   * no single answer to \"did everything come up\", visible only to whoever\n   * subscribed to `route:started` at the right moment. This is that answer,\n   * and nothing more: no new events, no semantics change.\n   */\n  private logBootSummary(outcomes: Map<string, RouteBootOutcome>): void {\n    const by = (outcome: RouteBootOutcome): string[] =>\n      [...outcomes.entries()]\n        .filter(([, value]) => value === outcome)\n        .map(([routeId]) => routeId);\n\n    const started = by(\"started\");\n    const failed = by(\"failed\");\n    const waiting = by(\"waiting\");\n    // Listed, never counted as a problem: a route held back by its own\n    // predicate is a configuration state the operator chose, so it belongs\n    // in the line without turning it into a warning.\n    const disabled = by(\"disabled\");\n    const total = outcomes.size;\n    const summary = {\n      started: started.length,\n      total,\n      ...(failed.length > 0 ? { failed } : {}),\n      ...(waiting.length > 0 ? { waiting } : {}),\n      ...(disabled.length > 0 ? { disabled } : {}),\n    };\n    // Fixed message, counts in bindings: `.standards/error-and-logging-policy.md`\n    // section 3, so the line stays countable in an aggregator.\n    if (failed.length > 0 || waiting.length > 0) {\n      this.logger.warn(summary, \"Routes started\");\n    } else {\n      this.logger.info(summary, \"Routes started\");\n    }\n  }\n\n  /**\n   * Run every plugin's optional `start()`, in registration order.\n   *\n   * Separate from {@link CraftContext.initPlugins} because the two phases\n   * answer different questions. `apply()` wires the context and runs at\n   * build time; `start()` begins work and needs the routes running. The\n   * deferral sweeper is the first consumer: it re-enters a route's error\n   * channel when a deferred exchange expires, which is not something that can\n   * be done against a route that has not started.\n   *\n   * A throw propagates to `context.start()`, which shuts the context down\n   * before rethrowing it unchanged. Unwinding a partially started context\n   * is deliberately the existing shutdown path rather than a second\n   * mechanism, so a plugin's stop logic has one home; a failed build\n   * unwinds through the same walk via {@link CraftContext.unwindFailedBuild},\n   * so which phase failed does not change where cleanup lives.\n   */\n  private async startPlugins(): Promise<void> {\n    for (const [pluginIndex, plugin] of this.plugins.entries()) {\n      // Re-checked per hook, not only on entry: a stop() arriving while an\n      // earlier hook is mid-await has already torn the plugins down, and a\n      // hook launched after that begins work nothing will ever stop.\n      if (this.hasStopped) return;\n      if (typeof plugin.start !== \"function\") continue;\n      const startHook = plugin.start.bind(plugin);\n      const pluginId = this.getPluginId(plugin, pluginIndex);\n      try {\n        this.emit(\"plugin:starting\", { pluginId, pluginIndex });\n        // See initPlugins(): a synchronous subscriber can stop the context\n        // between the loop guard and this call.\n        if (this.hasStopped) return;\n\n        await this.runLifecycleHook(async () => {\n          await startHook(this);\n          this.startedPlugins.add(pluginIndex);\n          this.emit(\"plugin:started\", { pluginId, pluginIndex });\n        });\n      } catch (err) {\n        this.logger.error(\n          { pluginIndex, pluginId, err },\n          \"Plugin threw during start(). The context will not start.\",\n        );\n        this.emit(\"context:error\", { error: err });\n        throw err;\n      }\n    }\n  }\n\n  /**\n   * Run one plugin lifecycle hook, publishing it as the in-flight hook for\n   * as long as it runs.\n   *\n   * The published promise covers the hook and the bookkeeping that records\n   * it, so a shutdown waiting on it sees a plugin either fully applied or\n   * fully absent, never half-recorded.\n   *\n   * @param hook The hook call together with the state it updates on success\n   */\n  private async runLifecycleHook(hook: () => Promise<void>): Promise<void> {\n    const inFlight = hook();\n    this.pluginHookInFlight = inFlight;\n    try {\n      await inFlight;\n    } finally {\n      if (this.pluginHookInFlight === inFlight) {\n        this.pluginHookInFlight = undefined;\n      }\n    }\n  }\n\n  /**\n   * Wait for a plugin lifecycle hook still in flight before teardown runs.\n   *\n   * Waiting rather than interrupting, and unbounded, for the reason plugin\n   * teardown is unbounded: a hook cut off partway keeps whatever it acquired\n   * after its last await point, and no teardown can release what the plugin\n   * had not yet handed over. Interrupting instead would oblige every plugin\n   * author to write `start()` so it tolerates teardown-before-completion, a\n   * contract paid for by every correct plugin to contain a defective one.\n   * A hook that never settles is that defective plugin, not a shutdown\n   * policy question.\n   *\n   * The hook's own rejection belongs to whoever invoked it, which is why\n   * only its settling is observed here.\n   */\n  private async settlePluginHook(): Promise<void> {\n    await this.pluginHookInFlight?.catch(() => undefined);\n  }\n\n  /**\n   * Refuse to start when a route can reach a `.defer()` and nothing\n   * configured where deferred exchanges go.\n   *\n   * Deliberately not auto-provisioned. The deferral runtime decides\n   * whether this deployment survives a restart and whether resume tokens\n   * outlive the process, and defaulting it silently would hand a route that\n   * promises durability an in-memory store nobody chose. Failing at startup\n   * costs one config line; failing on the first large payout costs the\n   * payout.\n   *\n   * Routes that never touch deferral carry neither marker, so a context\n   * without the feature pays nothing here.\n   *\n   * @throws RC5052 when a deferrable route has no deferral runtime\n   */\n  private assertDeferralConfigured(): void {\n    if (this.getStore(DEFERRAL_RUNTIME)) return;\n    const deferring = this.routes.find(\n      (route) => (route.definition.deferSteps?.length ?? 0) > 0,\n    );\n    // A resume ingress needs the runtime just as much: it verifies tokens\n    // against the signer and reads the store. Left out, a resume-only\n    // deployment starts clean and refuses every answer at request time.\n    const resuming = this.routes.find((route) => route.definition.usesResume);\n    const offender = deferring ?? resuming;\n    if (!offender) return;\n    const reached = deferring ? \".defer()\" : \".resume()\";\n    const err = rcError(\"RC5052\", undefined, {\n      message: `Route \"${offender.definition.id}\" can reach a ${reached}, but this context has no deferral runtime. Add deferral: {} to defineConfig (or deferral: { store, secret } to be explicit).`,\n    });\n    // Emitted as well as thrown, matching the plugin-init failure path: a\n    // caller that never awaits `start()` (every long-running source holds\n    // it open until shutdown) would otherwise only see this as an\n    // unobserved rejection.\n    this.logger.fatal({ err }, err.meta.message);\n    this.emit(\"context:error\", { error: err });\n    throw err;\n  }\n\n  /**\n   * Register a teardown callback to run when the context stops. Plugins use this\n   * to release resources (e.g. caches, native handles) after routes have drained.\n   * Callbacks run in REVERSE registration order (LIFO, mirroring plugin\n   * teardown) before `context:stopped` is emitted, so resources unwind in\n   * the opposite order they were acquired.\n   *\n   * @param fn - Callback (sync or async) to run during stop()\n   */\n  registerTeardown(fn: () => void | Promise<void>): void {\n    this.teardownCallbacks.push(fn);\n  }\n\n  /**\n   * Subscribe to lifecycle and system events.\n   *\n   * Takes an exact event name, or `\"*\"` for every event. Patterns such as\n   * `route:*` are refused with RC2001: event names are a fixed set and the\n   * route id lives in the payload, so scope to one route with\n   * `forRoute(routeId, handler)`. The `event()` source still accepts patterns.\n   *\n   * @param event - Exact event name (e.g. `route:started`) or `\"*\"`\n   * @param handler - Callback receiving `{ ts, contextId, details }`\n   * @returns Unsubscribe function (call to remove the handler)\n   *\n   * @example\n   * ```typescript\n   * // Subscribe to specific event\n   * const unsubscribe = ctx.on('route:started', ({ details }) => {\n   *   console.log('Route started:', details.route.definition.id);\n   * });\n   *\n   * // One route's failed exchanges\n   * ctx.on('route:exchange:failed', forRoute('orders', ({ details }) => {\n   *   console.log('Order failed:', details.error);\n   * }));\n   *\n   * // Every event\n   * ctx.on('*', ({ details }) => {\n   *   console.log('Event:', details);\n   * });\n   *\n   * // later: unsubscribe();\n   * ```\n   */\n  on<K extends EventName>(event: K, handler: EventHandler<K>): () => void;\n  on(event: \"*\", handler: EventHandler<EventName>): () => void;\n  on(event: EventName | \"*\", handler: EventHandler<EventName>): () => void {\n    return this.events.on(event as EventName, handler);\n  }\n\n  /**\n   * Subscribe to an event for a single occurrence. The handler is automatically\n   * removed after the first time the event is emitted.\n   *\n   * Accepts the same names as `on()`: an exact event name, or `\"*\"`.\n   *\n   * @param event - Exact event name or `\"*\"`\n   * @param handler - Callback receiving `{ ts, contextId, details }`\n   * @returns Unsubscribe function (call to remove the handler before it fires)\n   *\n   * @example\n   * ```typescript\n   * // Wait for context to start\n   * ctx.once('context:started', () => {\n   *   console.log('Context started!');\n   * });\n   *\n   * // Wait for the first route to start\n   * ctx.once('route:started', ({ details }) => {\n   *   console.log('First route started:', details.routeId);\n   * });\n   * ```\n   */\n  once<K extends EventName>(event: K, handler: EventHandler<K>): () => void;\n  once(event: \"*\", handler: EventHandler<EventName>): () => void;\n  once(event: EventName | \"*\", handler: EventHandler<EventName>): () => void {\n    return this.events.once(event as EventName, handler);\n  }\n\n  /**\n   * Emit an event to registered handlers.\n   *\n   * @param event - Event name\n   * @param details - Event-specific payload (merged into `EventPayload.details`)\n   * @internal Public for use by routes/adapters; prefer subscribing via on()\n   */\n  emit<K extends EventName>(\n    event: K,\n    details: EventPayload<K>[\"details\"],\n  ): void {\n    this.events.emit(event, details);\n  }\n\n  // onStartup/onShutdown removed in favor of event listeners\n\n  /**\n   * Register routes with this context.\n   *\n   * @param definitions Route definitions to register\n   * @throws {RoutecraftError} If there are duplicate route IDs or invalid route definitions\n   *\n   * @example\n   * ```typescript\n   * // Register a single route\n   * context.registerRoutes(myRoute);\n   *\n   * // Register multiple routes\n   * context.registerRoutes(route1, route2, route3);\n   * ```\n   */\n  registerRoutes(...definitions: RouteDefinition[]): void {\n    // 1) Gather all IDs from the new route definitions\n    const allIDs = definitions.map((def) => def.id);\n\n    // 2) Check for duplicates within the new route definitions\n    const hasInternalDuplicates = allIDs.some(\n      (id, idx) => allIDs.indexOf(id) !== idx,\n    );\n\n    // 3) Check for duplicates against existing routes\n    const conflictWithExistingRoutes = definitions.some((def) =>\n      this.routes.some((r) => r.definition.id === def.id),\n    );\n\n    // 4) If either case has duplicates, throw the error\n    if (hasInternalDuplicates || conflictWithExistingRoutes) {\n      // Identify any one duplicate ID\n      const duplicateId =\n        allIDs.find((id, idx) => allIDs.indexOf(id) !== idx) ??\n        definitions.find((def) =>\n          this.routes.some((r) => r.definition.id === def.id),\n        )?.id ??\n        \"unknown\";\n\n      throw rcError(\"RC1002\", undefined, {\n        message: `${RC[\"RC1002\"].message}: ${duplicateId}`,\n      });\n    }\n\n    // 5) Register each definition now that there's no duplication\n    for (const definition of definitions) {\n      if (\n        !Array.isArray(definition.sources) ||\n        definition.sources.length === 0 ||\n        definition.sources.some(\n          (source) => !source || typeof source.subscribe !== \"function\",\n        )\n      ) {\n        throw rcError(\"RC1001\", undefined, {\n          message: `${RC[\"RC1001\"].message}: ${definition.id}`,\n        });\n      }\n\n      // Binder injection removed\n\n      const controller = new AbortController();\n      this.controllers.set(definition.id, controller);\n      const route = new DefaultRoute(this, definition, controller);\n      this.routes.push(route);\n      this.emit(\"route:registered\", { routeId: definition.id, route });\n    }\n  }\n\n  /**\n   * Get all routes registered with this context.\n   *\n   * @returns A copy of the route list. Mutating the returned array does\n   *   not affect the context; routes are managed via `registerRoutes()`.\n   */\n  getRoutes(): Route[] {\n    return [...this.routes];\n  }\n\n  /**\n   * List the discoverable capabilities registered in this context: every\n   * direct endpoint together with its route's discovery metadata. Agents\n   * and embedding code use this instead of reaching into the (internal)\n   * direct registry; dispatch into a capability with\n   * `CraftClient.sendDirect(capability.endpoint, body)`.\n   *\n   * @returns A fresh array of capability snapshots. Endpoints are the raw\n   *   ids as passed to `.id(...)`; mutating the result does not affect\n   *   the registry.\n   */\n  capabilities(): Capability[] {\n    const registry = this.getStore(CAPABILITY_REGISTRY);\n    if (!registry) return [];\n    // Filtered by enablement, which is what makes \"the agent cannot use\n    // this until I supply credentials\" true by construction: the tool\n    // surface is derived from this list, so a disabled capability is never\n    // offered to the model rather than being offered and failing on call.\n    // A route disabled at boot never subscribed and so never registered\n    // here at all; this covers the route disabled AFTER it started, whose\n    // registry entry outlives the transition. A capability imported from\n    // another instance is that instance's to enable: it shares an id with\n    // a local route only while it holds the endpoint the local route gave\n    // up, and filtering it on the local predicate would hide the one that\n    // answers.\n    return [...registry.values()]\n      .filter(\n        (capability) =>\n          capability.remote !== undefined ||\n          this.enablement.isEnabled(capability.endpoint),\n      )\n      .map(snapshotCapability);\n  }\n\n  /**\n   * Get a value from the context store.\n   *\n   * @template K Store key type\n   * @param key The store key to retrieve\n   * @returns The stored value or undefined if not found\n   *\n   * @example\n   * ```typescript\n   * // Get channel store\n   * const channelStore = context.getStore('routecraft.adapter.channel.store');\n   * ```\n   */\n  getStore<K extends keyof StoreRegistry>(\n    key: K,\n  ): StoreRegistry[K] | undefined {\n    const value = this.store.get(key);\n    return value as StoreRegistry[K] | undefined;\n  }\n\n  /**\n   * Set a value in the context store.\n   *\n   * @template K Store key type\n   * @param key The store key\n   * @param value The value to store\n   *\n   * @example\n   * ```typescript\n   * // Set channel store\n   * context.setStore('routecraft.adapter.channel.store', new Map());\n   * ```\n   */\n  setStore<K extends keyof StoreRegistry>(\n    key: K,\n    value: StoreRegistry[K],\n  ): void {\n    this.store.set(key, value);\n  }\n\n  /**\n   * Find a route by its ID.\n   *\n   * @param id The route ID to find\n   * @returns The matching route or undefined if not found\n   */\n  getRouteById(id: string): Route | undefined {\n    return this.routes.find((route) => route.definition.id === id);\n  }\n\n  /**\n   * Start all routes registered with this context.\n   *\n   * Emits `context:starting` and `context:started`, then starts all routes in parallel.\n   * If all routes complete (e.g. finite sources), the context automatically stops.\n   * If any route fails to start, the error is logged, emitted as `error`, and rethrown.\n   *\n   * **Context Lifecycle Events:**\n   * - `context:starting` - Context initialization begins\n   * - `context:started` - Context initialized (routes may not be started yet)\n   * - `context:stopping` - Context shutdown begins\n   * - `context:stopped` - Context shutdown complete\n   *\n   * **Note:** `context:started` fires after context initialization but BEFORE\n   * individual routes start. To track route readiness, subscribe to\n   * `route:started` or `route:stopping` events instead.\n   * To filter by specific route, inspect details.route.definition.id in the handler.\n   *\n   * @returns A promise that resolves when all routes have started (or when context stops)\n   * @throws If any route fails to start\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   await context.start();\n   *   console.log('All routes started successfully');\n   * } catch (error) {\n   *   console.error('Failed to start routes:', error);\n   * }\n   * ```\n   */\n  async start(): Promise<void> {\n    // A context is single-use. Route controllers are built once and never\n    // rebuilt, so a start after a stop would report ready over dead routes\n    // and the deferral scan would retire records into them. The real\n    // restart unit is the process; refuse loudly rather than half-run.\n    if (this.hasStopped) {\n      throw rcError(\"RC1004\", undefined, {\n        message:\n          \"This context has been stopped and cannot be started again. Build a fresh context from your config.\",\n      });\n    }\n    // Two concurrent starts collapse into one: a double boot would run every\n    // plugin start() hook twice and orphan the first run's background tasks.\n    if (this.startInFlight) return this.startInFlight;\n    this.startInFlight = this.run();\n    return this.startInFlight;\n  }\n\n  private async run(): Promise<void> {\n    const started = this.ensureStartedGate();\n    try {\n      // Idempotent: ContextBuilder.build() may already have run plugins.\n      // Guarantees directly-constructed contexts get config-applier wiring\n      // before routes run.\n      if (!this.pluginsInitialized) {\n        await this.initPlugins();\n      }\n      this.assertDeferralConfigured();\n    } catch (err) {\n      // Every exit settles the deferred: a readiness probe waiting on a\n      // context that refused its config must see the refusal.\n      started.reject(err);\n      throw err;\n    }\n\n    // A stop() that landed while the plugins were applying has already torn\n    // them down. Starting routes now announces boot progress for a context\n    // that is gone: route:starting fires after context:stopped, every route\n    // refuses with RC3001 against its aborted controller, and the boot\n    // summary reports a failed boot for what was a clean shutdown. Waiting\n    // for that shutdown before returning also keeps start() from resolving\n    // while teardown is still running.\n    if (this.hasStopped) {\n      // The shutdown's own failure belongs to whoever called stop().\n      await this.shutdownPromise?.catch(() => undefined);\n      return;\n    }\n\n    this.logger.info(\n      { routeCount: this.routes.length },\n      \"Starting Routecraft context\",\n    );\n    this.emit(\"context:starting\", {});\n\n    // Every predicate is evaluated here, as one batch, BEFORE any route\n    // starts. A disabled route must never subscribe even briefly: a mail\n    // source with no credentials would connect and fail, which is the\n    // failure this feature exists to prevent. Batched rather than folded\n    // into each route's start so one slow predicate delays the decision\n    // only, never an unrelated route coming up.\n    //\n    // Guarded rather than awaited unconditionally: every await here is a\n    // turn a concurrent `stop()` can land on, so a context whose routes\n    // declare no predicate must reach the start loop exactly as directly\n    // as it did before this feature existed.\n    let disabled: ReadonlySet<string> = EMPTY_ROUTE_IDS;\n    const declaring = this.routes.filter(\n      (route) => route.definition.enablement,\n    );\n    if (declaring.length > 0) {\n      disabled = await this.enablement.evaluateForBoot(declaring);\n      // Same re-check the post-readiness path makes: a stop() that landed\n      // while the predicates were running has already torn the plugins\n      // down, and starting routes now would announce boot progress for a\n      // context that is gone.\n      if (this.hasStopped) {\n        await this.shutdownPromise?.catch(() => undefined);\n        return;\n      }\n      for (const [routeId, reason] of this.enablement.disabled()) {\n        this.logger.info(\n          { route: routeId, reason },\n          \"Route is disabled by its enabled() predicate; registered but not started\",\n        );\n      }\n    }\n\n    this.logger.debug({}, \"Starting all routes\");\n    this.emit(\"context:started\", {});\n    const routes = this.awaitRoutesStarted(disabled);\n    const running = Promise.allSettled(\n      this.routes.map(async (route) => {\n        // Registered and known to the context, not started and not\n        // intaking. The route object stays in `getRoutes()` so ops can\n        // report it: a missing route and a deliberately-off one must not\n        // look identical, since only one of them is an incident.\n        if (disabled.has(route.definition.id)) {\n          return { routeId: route.definition.id, success: true as const };\n        }\n        try {\n          this.logger.info({ route: route.definition.id }, \"Starting route\");\n          this.emit(\"route:starting\", {\n            routeId: route.definition.id,\n            route,\n          });\n          await route.start();\n          // Only log if the route completed on its own (not via context.stop())\n          if (!this.shutdownPromise) {\n            this.logger.info({ route: route.definition.id }, \"Route completed\");\n          }\n          routes.settle(route.definition.id, \"started\");\n          return { routeId: route.definition.id, success: true as const };\n        } catch (error) {\n          const msg = isRoutecraftError(error)\n            ? (error as { meta: { message: string } }).meta.message\n            : error instanceof Error\n              ? error.message\n              : \"Route failed to start\";\n          this.logger.fatal({ route: route.definition.id, err: error }, msg);\n          this.emit(\"context:error\", { error, route });\n          // Abort just this failing route\n          const controller = this.controllers.get(route.definition.id);\n          controller?.abort();\n          routes.settle(route.definition.id, \"failed\");\n          throw error;\n        }\n      }),\n    );\n\n    // After the routes are listening: a plugin's background task may drive\n    // them, and `allSettled` above keeps the route promises handled even\n    // when a plugin refuses to start.\n    try {\n      await routes.ready;\n      this.logBootSummary(routes.outcomes);\n      // Re-checked after the wait: a stop() arriving while routes were\n      // still coming up has already torn the plugins down, and a start()\n      // hook run now would begin work on a stopped context with nothing\n      // left to ever tear it down.\n      if (!this.hasStopped) await this.startPlugins();\n      // Armed only once the boot has settled: a cadence firing into a\n      // context that is still starting could transition a route the boot\n      // gate is still waiting on. Awaited, so a cadence that cannot be\n      // armed fails the boot instead of leaving the route silently without\n      // the refresh it declared.\n      if (!this.hasStopped) await this.enablement.startRefreshing(this.routes);\n    } catch (err) {\n      started.reject(err);\n      try {\n        await this.stop();\n      } catch (stopErr) {\n        // The unwind's own failure must not replace the boot error: the\n        // operator needs the cause of the failed start, not what the\n        // cleanup hit on the way out.\n        this.logger.error(\n          { err: stopErr },\n          \"Shutdown after a failed start also failed; reporting the start error.\",\n        );\n      }\n      await running;\n      throw err;\n    }\n    if (this.hasStopped) {\n      started.reject(\n        rcError(\"RC1004\", undefined, {\n          message: \"The context was stopped before it finished starting.\",\n        }),\n      );\n    } else {\n      this.startCompleted = true;\n      started.resolve();\n    }\n\n    return running\n      .then(async (results) => {\n        // Skip if shutdown was already triggered (e.g. via signal handler).\n        // The outcome is dropped here: `start()` resolves when the context is\n        // done running, and whoever called `stop()` is holding the outcome.\n        if (this.shutdownPromise) {\n          await this.shutdownPromise;\n          return;\n        }\n\n        // Check if all routes completed successfully\n        const allFulfilled = results.every((r) => r.status === \"fulfilled\");\n        // A disabled route has not COMPLETED, it never ran, so it must not\n        // be counted as work that finished. But suppressing the auto-stop\n        // for EVERY disabled route strands the context: a route disabled\n        // under the default MANUAL cadence has no in-process path back to\n        // enabled, so nothing would ever re-evaluate it and the wait buys\n        // nothing while costing the whole shutdown (no plugin teardown, no\n        // `context:stopped`). Suppress only for a cadence that re-evaluates\n        // on its own; its timer is ref'd for the same reason, so the two\n        // decisions cannot disagree.\n        const awaitingCadence = [...this.enablement.disabled().keys()].some(\n          (routeId) =>\n            isLiveCadence(\n              this.getRouteById(routeId)?.definition.enablement?.refresh,\n            ),\n        );\n        if (\n          allFulfilled &&\n          !awaitingCadence &&\n          !this.plugins.some((plugin) => plugin.keepsAlive)\n        ) {\n          this.logger.debug({}, \"All routes have completed. Stopping context.\");\n          await this.stop();\n          return;\n        } else {\n          this.logger.info(\n            {},\n            \"Some routes ended or failed; context remains active. Call context.stop() or let other indefinite routes continue.\",\n          );\n          // Do not stop automatically; let other routes run.\n          return;\n        }\n      })\n      .catch((error) => {\n        const msg = isRoutecraftError(error)\n          ? (error as { meta: { message: string } }).meta.message\n          : error instanceof Error\n            ? error.message\n            : \"Context start failed\";\n        this.logger.fatal({ err: error }, msg);\n        this.emit(\"context:error\", { error });\n        throw error;\n      });\n  }\n\n  /**\n   * Wait for all in-flight route handlers (and their background tasks) to complete.\n   * Does not stop sources; use stop() for full shutdown.\n   *\n   * @returns A promise that resolves when all routes have drained\n   */\n  async drain(): Promise<void> {\n    this.logger.debug(\n      { routeCount: this.routes.length },\n      \"Draining context: waiting for all route handlers and tasks\",\n    );\n    await Promise.all(this.routes.map((r) => r.drain()));\n    this.logger.debug({}, \"Context drained\");\n  }\n\n  /**\n   * Stop all routes and shut down the context.\n   *\n   * This will:\n   * 1. Abort all route controllers (stops sources)\n   * 2. Drain all routes (wait for in-flight handlers and their background tasks)\n   *\n   * @returns A promise that resolves when all shutdown operations complete\n   *\n   * @example\n   * ```typescript\n   * // Handle shutdown signals\n   * process.on('SIGINT', async () => {\n   *   console.log('Shutting down...');\n   *   await context.stop();\n   *   process.exit(0);\n   * });\n   * ```\n   */\n  async stop(): Promise<ShutdownOutcome> {\n    if (this.shutdownPromise) return this.shutdownPromise;\n    this.hasStopped = true;\n    // Settles readiness for a context stopped before it ever became ready,\n    // so a probe observes termination instead of waiting forever. A no-op\n    // when the deferred already settled, which is every ordinary shutdown.\n    this.ensureStartedGate().reject(\n      rcError(\"RC1004\", undefined, {\n        message: \"The context was stopped before it finished starting.\",\n      }),\n    );\n    this.shutdownPromise = this.performShutdown();\n    return this.shutdownPromise;\n  }\n\n  /**\n   * Tear down every plugin that applied, in reverse application order, then\n   * the registered teardown callbacks.\n   *\n   * One walk serves all three exits: an ordinary shutdown, a start that\n   * failed partway, and a build that failed partway. They differ only in\n   * what {@link TeardownInfo} reports, which is why they are not three\n   * mechanisms.\n   *\n   * Only APPLIED plugins are torn down. A build that failed at plugin 3\n   * leaves plugin 4 never having run, and calling its teardown would ask it\n   * to release something it never acquired.\n   *\n   * Failure-tolerant throughout: a throwing teardown is logged and the\n   * remaining teardowns still run, because the caller's original error is\n   * what the operator needs and one plugin's cleanup must not strand\n   * another's.\n   *\n   * @param partial - The context never finished starting.\n   */\n  private async teardownPlugins(partial: boolean): Promise<void> {\n    for (let i = this.plugins.length - 1; i >= 0; i--) {\n      if (!this.appliedPlugins.has(i)) continue;\n      const plugin = this.plugins[i] as CraftPlugin | undefined;\n      if (!plugin?.teardown) continue;\n      const pluginId = this.getPluginId(plugin, i);\n\n      this.emit(\"plugin:stopping\", { pluginId, pluginIndex: i });\n\n      try {\n        await Promise.resolve(\n          plugin.teardown(this, {\n            partial,\n            started: this.startedPlugins.has(i),\n          }),\n        );\n        this.emit(\"plugin:stopped\", { pluginId, pluginIndex: i });\n      } catch (err) {\n        this.logger.warn(\n          { err, pluginIndex: i },\n          \"Plugin teardown threw; continuing with remaining teardowns.\",\n        );\n      }\n    }\n    // LIFO: unwind registered teardowns in the opposite order they were\n    // acquired, mirroring the reverse plugin teardown above.\n    for (let i = this.teardownCallbacks.length - 1; i >= 0; i--) {\n      try {\n        await Promise.resolve(this.teardownCallbacks[i]());\n      } catch (err) {\n        this.logger.warn(\n          { err },\n          \"Plugin teardown threw; continuing with remaining teardowns.\",\n        );\n      }\n    }\n  }\n\n  /**\n   * Release everything a failed `build()` acquired, then let the caller\n   * rethrow the original error.\n   *\n   * `build()` never returns a context when it fails, so the caller has no\n   * handle to run teardown against: whatever an `apply()` opened (a database\n   * handle, a socket, an interval) is unreachable and stays open. Under a\n   * supervisor that retries boot, one handle leaks per attempt, and with\n   * SQLite the held handle also keeps the file locked, so a transient boot\n   * failure becomes a permanent one whose error names lock contention rather\n   * than the real cause.\n   *\n   * @internal Called by `ContextBuilder.build()` on the failure path.\n   */\n  async unwindFailedBuild(): Promise<void> {\n    this.hasStopped = true;\n    await this.teardownPlugins(true);\n  }\n\n  private async performShutdown(): Promise<ShutdownOutcome> {\n    this.logger.info({}, \"Stopping Routecraft context\");\n    // Before anything is torn down: a refresh firing mid-shutdown would\n    // start a route the shutdown has already walked past, leaving an\n    // ingress open behind the drain.\n    this.enablement.stop();\n    this.emit(\"context:stopping\", { reason: undefined });\n\n    // STAGE ONE. Close intake: sources stop producing, no new exchange is\n    // admitted. Deliberately not the execution signal, so an exchange\n    // already in the pipeline (an agent mid-tool-call, a deferral\n    // continuation) runs to its natural end. Dedicated force signals and the\n    // shutdown deadline are what abandon work that does not finish in time.\n    for (const route of this.routes) {\n      this.logger.info({ route: route.definition.id }, \"Stopping route\");\n      const controller = this.controllers.get(route.definition.id);\n      controller?.abort(\"context.stop()\");\n    }\n\n    // Drain, bounded. Past the deadline the work is abandoned rather than\n    // waited out: an unbounded stage one hands the outcome to the platform's\n    // kill timer, which is what this bound exists to take back.\n    const drain = Promise.all(this.routes.map((r) => r.drain()));\n    let drainError: unknown;\n    let forced = false;\n    let pending: string[] = [];\n    try {\n      await this.raceShutdownDeadline(drain);\n    } catch (err) {\n      if (err === SHUTDOWN_DEADLINE) {\n        forced = true;\n        pending = this.forceStageTwo();\n        // The drain promise is abandoned, not awaited: work that hears the\n        // execution abort unwinds on its own, and work that does not is what\n        // \"forced\" means. Its rejection is still claimed so an abandoned\n        // route failure does not surface as an unhandled rejection.\n        void drain.catch(() => undefined);\n      } else {\n        drainError = err;\n        this.logger.warn(\n          { err },\n          \"Route drain failed during stop(); continuing teardown.\",\n        );\n      }\n    }\n\n    // A stop() racing boot lets the hook already awaiting finish first, so\n    // a plugin is never torn down while its own apply() or start() is still\n    // acquiring. Outside that race this settles immediately.\n    await this.settlePluginHook();\n\n    // Plugin teardown (plugins with teardown in reverse order, then\n    // registerTeardown callbacks). Unbounded on purpose: teardown releases\n    // resources, and a plugin that wedges there is a different defect from\n    // the one this deadline addresses.\n    await this.teardownPlugins(!this.startCompleted);\n\n    this.logger.info({}, \"Routecraft context stopped\");\n    this.emit(\"context:stopped\", { forced, pending });\n\n    if (drainError) {\n      throw drainError;\n    }\n    return { forced, pending };\n  }\n\n  /**\n   * Wait for ONE route to drain, bounded by the route's own grace or, when\n   * it declared none, by the same `shutdown.timeout` the whole-context\n   * shutdown uses.\n   *\n   * Enablement's disable transition is the caller: taking a route out of\n   * service is a per-route shutdown, so it defaults to the same\n   * operator-facing knob rather than a second timeout nobody knows to look\n   * for. A route that declared `.enabled({ drainGrace })` overrides it,\n   * because the author is the one who knows what this pipeline's in-flight\n   * work costs.\n   *\n   * @param graceMs - Milliseconds to allow; `undefined` for the context\n   *   default; `null` to wait indefinitely and never force.\n   * @returns True when the route drained; false when the deadline elapsed\n   *   first and the caller must force it.\n   */\n  private async drainRouteWithin(\n    route: Route,\n    graceMs?: number | null,\n  ): Promise<boolean> {\n    // A drain that threw is a route that is no longer working, which is\n    // what the caller wanted; the failure belongs to the route's own error\n    // path, not to the flag flip that asked it to stop.\n    const drained = route.drain().then(\n      () => true as const,\n      (err: unknown) => {\n        this.logger.warn(\n          { route: route.definition.id, err },\n          \"Route drain threw while it was being disabled; treating it as drained\",\n        );\n        return true as const;\n      },\n    );\n\n    // An unbounded wait has no deadline arm at all, so nothing can report\n    // `false` and the caller never forces.\n    if (graceMs === null) return drained;\n\n    const boundMs = graceMs ?? this.shutdownTimeoutMs;\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const deadline = new Promise<false>((resolve) => {\n      timer = setTimeout(() => resolve(false), boundMs);\n      timer.unref?.();\n    });\n    try {\n      return await Promise.race([drained, deadline]);\n    } finally {\n      if (timer) clearTimeout(timer);\n    }\n  }\n\n  /**\n   * Re-arm a disabled route under a fresh controller and start it.\n   *\n   * The controller is minted HERE rather than inside the route so this map\n   * and the route never disagree about which controller a shutdown aborts:\n   * a route holding one controller while `controllers` held the previous,\n   * latched one would make `stop()` a silent no-op for that route.\n   */\n  private async restartRoute(route: Route): Promise<void> {\n    const controller = new AbortController();\n    this.controllers.set(route.definition.id, controller);\n    route.resetForRestart(controller);\n    this.emit(\"route:starting\", { routeId: route.definition.id, route });\n\n    // Resolved on READINESS, not on `start()` settling, exactly as the boot\n    // path does. A server ingress (direct, http, mcp) holds its subscribe\n    // open until the route is aborted, so awaiting `start()` here would\n    // never return and the re-enable would hang forever on precisely the\n    // routes this feature is for. A finite source settles `start()` first\n    // and resolves through the other arm.\n    const ready = Promise.withResolvers<void>();\n    const off = this.on(\"route:started\", ({ details }) => {\n      if (details.routeId === route.definition.id) ready.resolve();\n    });\n    const running = route.start().catch((err: unknown) => {\n      controller.abort(err);\n      route.abortExecution(err);\n      ready.reject(err);\n    });\n\n    // The same bound the boot applies, for the same reason: a source that\n    // never calls ready() and never emits would otherwise hold this open\n    // forever, and a server ingress never settles `running` either, so\n    // without it the caller of a re-enable can wait indefinitely while the\n    // cadence keeps queueing further transitions behind it.\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const bound = new Promise<void>((resolve) => {\n      timer = setTimeout(() => {\n        this.logger.warn(\n          {\n            route: route.definition.id,\n            timeoutMs: ROUTE_READINESS_TIMEOUT_MS,\n          },\n          \"Re-enabled route did not signal readiness in time; continuing.\",\n        );\n        resolve();\n      }, ROUTE_READINESS_TIMEOUT_MS);\n      timer.unref?.();\n    });\n\n    try {\n      await Promise.race([ready.promise, running, bound]);\n    } finally {\n      off();\n      if (timer) clearTimeout(timer);\n    }\n  }\n\n  /**\n   * Re-evaluate enablement predicates on demand and apply any transitions.\n   *\n   * The internal control surface behind the operator loop the deferred\n   * `/ops` re-evaluate endpoint will expose: set the secret, ask for a\n   * re-check, and a route whose predicate now passes starts without a\n   * process restart. The endpoint is wiring on top of this, not a redesign\n   * of it.\n   *\n   * @param routeId - Re-evaluate only this route. Omitted re-evaluates\n   *   every route that declared a predicate.\n   * @returns Each re-evaluated route's resulting state, by route id.\n   */\n  async reevaluateEnablement(\n    routeId?: string,\n  ): Promise<ReadonlyMap<string, EnablementState>> {\n    if (routeId === undefined) {\n      return this.enablement.refreshAll(this.routes);\n    }\n    const route = this.getRouteById(routeId);\n    if (!route) return new Map();\n    const state = await this.enablement.refresh(route);\n    return new Map([[routeId, state]]);\n  }\n\n  /**\n   * Whether a route is currently serving, as far as `.enabled()` is\n   * concerned. True for a route that never declared a predicate.\n   */\n  isRouteEnabled(routeId: string): boolean {\n    return this.enablement.isEnabled(routeId);\n  }\n\n  /**\n   * Every route currently disabled by its predicate, mapped to the reason.\n   *\n   * Read by the ops surface, which reports a disabled route distinctly from\n   * a failed one: a deliberate configuration state is not an open circuit\n   * and must not degrade the aggregate.\n   */\n  disabledRoutes(): ReadonlyMap<string, string> {\n    return this.enablement.disabled();\n  }\n\n  /**\n   * Resolve when `drain` settles, or reject with {@link SHUTDOWN_DEADLINE}\n   * once the configured bound elapses.\n   */\n  private raceShutdownDeadline(drain: Promise<unknown>): Promise<unknown> {\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const deadline = new Promise<never>((_resolve, reject) => {\n      timer = setTimeout(\n        () => reject(SHUTDOWN_DEADLINE),\n        this.shutdownTimeoutMs,\n      );\n      timer.unref?.();\n    });\n    return Promise.race([drain, deadline]).finally(() => {\n      if (timer) clearTimeout(timer);\n    });\n  }\n\n  /**\n   * Abandon in-flight execution on every route, and report what was still\n   * running.\n   *\n   * The log line names route ids and their pending counts rather than a\n   * total, because it is the only forensic record a forced shutdown leaves:\n   * an operator reading it afterwards needs to know WHICH capability was\n   * still working, not merely that something was.\n   *\n   * What this accepts losing: in-flight exchanges are abandoned mid-step and\n   * emit no terminal event. What it does NOT do is settle or deny anything on\n   * the way down, so a deferred exchange survives a forced shutdown exactly\n   * as it survives a graceful one.\n   *\n   * It does NOT reach the deferral sweeper. The sweeper stops cooperatively\n   * from `context:stopping`, which fires at the start of EVERY shutdown, and\n   * plugin teardown then awaits its in-flight sweep unbounded, outside this\n   * deadline. Records it had claimed heal via their lease either way.\n   */\n  private forceStageTwo(): string[] {\n    const pending = this.routes\n      .filter((route) => route.inFlightCount > 0)\n      .map((route) => ({\n        route: route.definition.id,\n        inFlight: route.inFlightCount,\n      }));\n    this.logger.warn(\n      { timeoutMs: this.shutdownTimeoutMs, pending },\n      pending.length > 0\n        ? \"Graceful shutdown did not drain in time; abandoning in-flight work and forcing shutdown. Deferred exchanges are left untouched.\"\n        : \"Graceful shutdown did not complete in time; forcing shutdown.\",\n    );\n    for (const route of this.routes) {\n      route.abortExecution(\"shutdown.timeout elapsed\");\n    }\n    return pending.map((entry) => entry.route);\n  }\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { CraftContext } from \"./context.ts\";\nimport {\n  type Exchange,\n  HeadersKeys,\n  OperationType,\n  type ExchangeHeaders,\n  DefaultExchange,\n  EXCHANGE_INTERNALS,\n  isDropped,\n} from \"./exchange.ts\";\nimport type { RegisteredDirectEndpoint } from \"./registry.ts\";\nimport {\n  resolveAdapterOverride,\n  wrapSourceWithOverride,\n} from \"./testing-hooks.ts\";\nimport { BRAND, INTERNALS_KEY, setBrand } from \"./brand.ts\";\nimport { rcError, RC } from \"./error.ts\";\nimport { isRoutecraftError } from \"./brand.ts\";\nimport { logger, childBindings } from \"./logger.ts\";\nimport type { Source, Subscription } from \"./operations/from.ts\";\nimport type { ResolvedRetryOptions } from \"./operations/retry-wrapper.ts\";\nimport type { ResolvedTimeoutOptions } from \"./operations/timeout-wrapper.ts\";\nimport type { CircuitBreakerController } from \"./operations/circuit-breaker-wrapper.ts\";\nimport type { ConcurrencyController } from \"./operations/concurrency-wrapper.ts\";\nimport type {\n  Adapter,\n  Step,\n  Consumer,\n  ConsumerType,\n  Message,\n  ProcessingQueue,\n} from \"./types.ts\";\nimport { InMemoryProcessingQueue } from \"./queue.ts\";\nimport {\n  buildCacheCheckStep,\n  buildCacheStoreStep,\n  buildThrottleCheckStep,\n} from \"./pipeline/synthetic-steps.ts\";\nimport {\n  applyOutputStage,\n  validateInputOrThrow,\n  type ValidationDeps,\n} from \"./pipeline/validation.ts\";\nimport {\n  runDetachedPipeline,\n  runPipeline,\n  type DetachedResult,\n  type ExecutorDeps,\n} from \"./pipeline/executor.ts\";\nimport { detachedDefinition } from \"./pipeline/chain-policy.ts\";\nimport type { DeferCapableStep, DeferrableStep } from \"./deferral/sites.ts\";\nimport type { RouteEnablement } from \"./enablement.ts\";\n\n// Re-exported for existing imports (builder.ts and @internal consumers).\nexport { buildCacheCheckStep, buildCacheStoreStep, buildThrottleCheckStep };\n\n/**\n * Function that forwards a payload to another route via the direct adapter and returns its result.\n *\n * @param endpoint - The target route's direct endpoint\n * @param payload - The data to send\n * @returns The result of the target route's pipeline\n */\nexport type ForwardFn = (\n  endpoint: RegisteredDirectEndpoint,\n  payload: unknown,\n) => Promise<unknown>;\n\n/**\n * Error handler invoked when a step in the route pipeline throws an unhandled error.\n *\n * The pipeline does not resume after this handler runs. The handler's return value\n * becomes the route's final exchange body. Use `forward` to delegate to another route.\n *\n * Instead of a recovery body the handler may return a branded `Recovery`\n * directive built with the `recovery` helpers (see `recovery.ts`):\n * `recovery.drop(reason?)` discards the exchange (emits\n * `route:exchange:dropped`, no `route:exchange:completed`), and\n * `recovery.rethrow()` propagates the original error exactly as if the\n * handler had thrown it. Plain (unbranded) return values are unaffected.\n *\n * @param error - The thrown error\n * @param exchange - The exchange at the point of failure\n * @param forward - Sends a payload to another route via the direct adapter\n * @returns Static fallback value, result of forward(), or a `Recovery` directive\n */\nexport type ErrorHandler = (\n  error: unknown,\n  exchange: Exchange,\n  forward: ForwardFn,\n) => unknown | Promise<unknown>;\n\n/**\n * Per-direction schema bundle for discoverable-capability routes. Mirrors the\n * Standard Schema shape used by adapters; the engine enforces `input` before\n * pipeline steps run and `output` before the primary destination fires.\n */\nexport interface RouteSchemas {\n  /** Standard Schema for the body. */\n  body?: StandardSchemaV1;\n  /** Standard Schema for the headers. */\n  headers?: StandardSchemaV1;\n}\n\n/**\n * Well-known tag values surfaced as autocomplete suggestions while still\n * accepting any user-defined string. Use these consistently to enable\n * downstream filtering (e.g. an agent that only whitelists `\"read-only\"`\n * tools).\n */\nexport type KnownTag =\n  \"read-only\" | \"destructive\" | \"idempotent\" | \"open-world\";\n\n/**\n * Tag value: one of the framework's well-known tags or any user string.\n * The `& {}` keeps autocomplete on `KnownTag` while accepting arbitrary\n * strings.\n */\nexport type Tag = KnownTag | (string & {});\n\n/**\n * Route-level discovery bundle. Adapters that maintain registries (direct,\n * mcp) mirror these fields into their registry entries; the engine uses\n * `input` / `output` for framework-enforced validation regardless of adapter.\n *\n * Set via the `.title()`, `.description()`, `.input()`, `.output()`,\n * and `.tag()` builder methods. All fields are optional.\n */\nexport interface RouteDiscovery {\n  /** Human-readable display title for discovery consumers (agents, docs). */\n  title?: string;\n  /** Human-readable description of what this route does. */\n  description?: string;\n  /** Input schemas runtime-enforced before pipeline steps run. */\n  input?: RouteSchemas;\n  /** Output schemas runtime-enforced before the primary destination. */\n  output?: RouteSchemas;\n  /**\n   * Tags surfaced on `ToolsCatalog` entries for the builder form of\n   * `tools((catalog) => ...)` in `@routecraft/ai`, and on resolved\n   * tool entries for downstream inspection. Empty/missing means no\n   * tags.\n   */\n  tags?: Tag[];\n}\n\n/**\n * Configuration for a route: source, steps, and consumer.\n *\n * Describes how data flows from a source through processing steps to destinations.\n * The builder preserves body type `T`; at runtime the runnable Route uses `Exchange`\n * and handlers/events receive `Exchange<unknown>` unless you narrow or use `Route<T>`.\n *\n * @template T - Body type produced by the source (flowing through the chain until type-erased at runtime)\n *\n * @example\n * ```typescript\n * const def: RouteDefinition<string> = {\n *   id: 'my-route',\n *   sources: [simple('hello')],\n *   steps: [...],\n *   consumer: { type: SimpleConsumer, options: undefined }\n * };\n * ```\n */\nexport type RouteDefinition<T = unknown> = {\n  /** Unique identifier for the route */\n  readonly id: string;\n\n  /**\n   * The sources that feed data into the route. A route may expose multiple\n   * ingresses (e.g. `direct` for internal callers, `mcp` for agents, `http`\n   * for integrations) that all drive the same downstream pipeline. The route\n   * stays a single logical entity: one id, one set of lifecycle events, and\n   * (where the registries derive a public name from the route id) one name\n   * across ingresses. Every entry must be non-empty; the builder normalizes a\n   * single `.from(x)` to `[x]`.\n   */\n  readonly sources: readonly Source<T>[];\n\n  /** Processing steps that transform, filter, or direct the data */\n  readonly steps: Step<Adapter>[];\n\n  /** Consumer configuration that determines how data is processed */\n  readonly consumer: {\n    /** The type of consumer to use */\n    type: ConsumerType<Consumer>;\n\n    /** Options for the consumer */\n    options: unknown;\n  };\n\n  /**\n   * Optional error handler invoked when a step throws an unhandled error.\n   * If defined, the handler's return value becomes the final exchange body.\n   * If not defined, the error is logged and emitted via the error event (current behavior).\n   */\n  readonly errorHandler?: ErrorHandler;\n\n  /**\n   * Framework-managed filters that run BEFORE the source-attached\n   * parse step (and therefore before everything else). Today: the\n   * `.authorize()` ValidateSteps in declaration order. This is chain\n   * position #2 in `.standards/pre-from-filter-chain.md`.\n   *\n   * @internal\n   */\n  readonly preParseFilters: Step<Adapter>[];\n\n  /**\n   * Framework-managed filters that run AFTER the source-attached parse\n   * step but BEFORE the user pipeline. Today: the route-scope\n   * `cache-check` filter (chain position #9). The future\n   * `circuitBreaker` (#6) slots in once it lands. Route-scope\n   * `throttle` (#5), `retry` (#7), and `timeout` (#8) instead sit\n   * OUTSIDE this array (it is wrapped by the retry / timeout segments),\n   * so they ride on their own definition fields below.\n   *\n   * @internal\n   */\n  readonly postParseFilters: Step<Adapter>[];\n\n  /**\n   * Framework-managed filters that run AFTER the user pipeline.\n   * Today: the route-scope `cache-store` filter (chain position #10)\n   * when `.cache()` is configured. Reached only on miss-success; the\n   * cache-check filter pushes `steps: []` on a hit to short-circuit.\n   *\n   * @internal\n   */\n  readonly postFromFilters: Step<Adapter>[];\n\n  /**\n   * Optional route-level discovery bundle: title, description, and input /\n   * output schemas. Populated via `.title()`, `.description()`, `.input()`,\n   * and `.output()` on the route builder. The engine enforces `input` and\n   * `output` schemas; discovery-aware adapters (direct, mcp) mirror the\n   * metadata into their registries.\n   */\n  readonly discovery?: RouteDiscovery;\n\n  /**\n   * The route's enablement predicate and refresh cadence, from `.enabled()`.\n   *\n   * Route metadata rather than a filter: it decides whether this route runs\n   * at all, per route and per lifecycle, so it never enters the pre-from\n   * filter chain and never sees an exchange. Absent means always enabled,\n   * which is every route that does not declare one.\n   */\n  readonly enablement?: RouteEnablement;\n\n  /**\n   * True when the route declares a route-entry `.authorize()`. Mirrored to\n   * sources via {@link SourceMeta.requiresPrincipal} so identity-capable\n   * transports enforce credential verification before dispatching into the\n   * route, even on an unwalled mount.\n   */\n  readonly requiresPrincipal?: boolean;\n\n  /**\n   * Route-scope `.retry()` config (pre-from filter chain position #7).\n   * Unlike the cache filters, retry is not a flat step in\n   * `postParseFilters`: it scopes over the whole chain tail (timeout,\n   * cache-check, user pipeline, cache-store) and re-runs it on\n   * failure, so the pipeline executor wraps the tail in a retry\n   * segment step when this is set. See\n   * `.standards/pre-from-filter-chain.md`.\n   */\n  readonly retry?: ResolvedRetryOptions;\n\n  /**\n   * Route-scope `.timeout()` config (pre-from filter chain position\n   * #8). Bounds each run of the chain tail below it with a deadline;\n   * placed inside `retry` so every attempt gets its own deadline. Like\n   * `retry`, realized as a segment step wrapped around the tail by the\n   * pipeline executor rather than a flat `postParseFilters` entry.\n   */\n  readonly timeout?: ResolvedTimeoutOptions;\n\n  /**\n   * Route-scope `.throttle()` admission gates (pre-from filter chain\n   * position #5), in declaration order. Each is a one-shot gate (a flat\n   * step, not a segment like retry / timeout); the exchange must be\n   * admitted by ALL of them, so stacking `.throttle()` calls AND-combines\n   * independent limits (e.g. a global ceiling plus a per-principal rate).\n   * The pipeline executor places them OUTSIDE the retry (#7) / timeout\n   * (#8) segments (throttle #5 is above them in the chain) and runs them\n   * once per exchange; a retried attempt re-runs only the tail below and\n   * never re-acquires a token.\n   *\n   * @internal\n   */\n  readonly throttle?: Step<Adapter>[];\n\n  /**\n   * Route-scope `.circuitBreaker()` controller (pre-from filter chain\n   * position #6). Unlike retry / timeout (config objects re-built into a\n   * segment per run), the breaker holds persistent per-Route state (the\n   * failure window and the open/half-open machine), so the builder stores\n   * the live {@link CircuitBreakerController} here once at `.from()` time\n   * and the pipeline executor wraps the chain tail in a breaker segment\n   * around it. Sits OUTSIDE the retry (#7) / timeout (#8) segments and\n   * INSIDE the throttle (#5) gate: when open it fast-fails before retry /\n   * timeout run, so one tripped breaker call is recorded per fully\n   * exhausted attempt, not per retry. See\n   * `.standards/pre-from-filter-chain.md`.\n   *\n   * @internal\n   */\n  readonly circuitBreaker?: CircuitBreakerController;\n\n  /**\n   * Route-scope `.concurrency()` bulkhead controllers (one per\n   * `.concurrency()` call; they nest). Like the circuit breaker they hold\n   * persistent per-Route state (the slot pool / semaphores), so the builder\n   * stores the live {@link ConcurrencyController}s here once at `.from()`\n   * time and the pipeline executor wraps the chain tail in a bulkhead\n   * segment per controller. Sits at the INNERMOST resilience position,\n   * INSIDE the retry (#7) / timeout (#8) segments, so a slot is acquired\n   * per attempt and released between retry backoffs (never held while a\n   * retry sleeps). See `.standards/pre-from-filter-chain.md`.\n   *\n   * @internal\n   */\n  readonly concurrency?: ConcurrencyController[];\n\n  /**\n   * Every `.defer()` the route can reach, resolved once at build time and\n   * in pre-order. Each step carries the {@link DeferSite} naming its\n   * address and its continuation, which is what a resume addresses: the\n   * continuation cannot be a closure captured at defer time, because\n   * execution two happens in a different process.\n   *\n   * Absent (rather than empty) on a route that never defers, so the\n   * common case costs nothing and `context.start()` can tell \"no defers\"\n   * from \"defers, needs a runtime\" without walking anything.\n   *\n   * @internal\n   */\n  deferSteps?: DeferrableStep[];\n\n  /**\n   * Every defer-capable `.to()` / `.enrich()` step the route carries on\n   * its primary flow, each holding the re-entrant {@link DeferSite} the\n   * walk assigned it. Separate from {@link RouteDefinition.deferSteps}\n   * deliberately: a capable step only MAY defer at runtime, so it does not\n   * make the route require a deferral runtime at startup (`RC5052` stays\n   * keyed to static sites; a runtime deferral without the runtime fails as an\n   * ordinary step error naming the config line), and it does not trip the\n   * route-scope cache refusal, whose \"silently never caches\" reasoning\n   * assumes every run defers.\n   *\n   * @internal\n   */\n  reentrantDeferSteps?: DeferCapableStep[];\n\n  /**\n   * The route can reach a `.resume()`. Recorded alongside\n   * {@link RouteDefinition.deferSteps} because a resume ingress needs the\n   * deferral runtime too (it verifies tokens and reads the store), and a\n   * resume-only route carries no defer sites to infer that from.\n   *\n   * @internal\n   */\n  usesResume?: boolean;\n\n  /**\n   * The route has no `.id()` and a `.cache()` using the default key, which\n   * is namespaced by the route id. The generated id changes on every start,\n   * so the route warns once it is registered. Set by `RouteBuilder.build()`.\n   *\n   * @internal\n   */\n  volatileCacheKey?: boolean;\n\n  /**\n   * Fingerprint of the user pipeline a route-scope `.cache()` skips on a\n   * hit, folded into its default key (see `CacheKeyScope`). Set by\n   * `RouteBuilder.build()` on a route with a route-scope cache.\n   *\n   * @internal\n   */\n  cachePipeline?: string;\n};\n\n/**\n * Represents a runnable route that processes data.\n *\n * Routes handle the flow of data from a source through processing steps\n * and can be started and stopped. Use Route<T> when you know the route's\n * body type (e.g. from a typed definition); at runtime, handlers and\n * events receive Exchange (body: unknown) unless narrowed.\n *\n * @template T The body type of the route's exchange when known (default unknown)\n */\nexport interface Route<T = unknown> {\n  /** The context this route belongs to */\n  readonly context: CraftContext;\n\n  /** The route's configuration */\n  readonly definition: RouteDefinition<T>;\n\n  /**\n   * Fires when in-flight work on this route is being abandoned. NOT fired\n   * when the route merely stops accepting new work, which is what graceful\n   * shutdown's first stage does.\n   */\n  readonly signal: AbortSignal;\n\n  /**\n   * Fires when the route stops accepting new work, which is the moment\n   * graceful shutdown begins. Work already in flight keeps running.\n   *\n   * A wrapper that is WAITING observes this: a `.delay()` wait, a\n   * `.throttle()` pacing gap, a bulkhead queue slot, a `.retry()` backoff.\n   * The wait is cut short once shutdown begins and the exchange still\n   * reaches a terminal outcome, where sitting the timer out burns the\n   * shutdown deadline and ends in an abandonment that reports nothing.\n   * {@link Route.signal} is for abandonment itself, never for shortening a\n   * wait.\n   */\n  readonly intakeSignal: AbortSignal;\n\n  /**\n   * Abandon in-flight execution on this route. The forced stage of shutdown\n   * and an explicit `stop()`; never the graceful drain.\n   * @internal\n   */\n  abortExecution(reason?: unknown): void;\n\n  /**\n   * How much work is still in flight. Read when a forced shutdown reports\n   * what it is abandoning, which is the only forensic record that stage\n   * leaves.\n   * @internal\n   */\n  readonly inFlightCount: number;\n\n  /** Logger for this route (pino child logger) */\n  logger: ReturnType<typeof logger.child>;\n\n  /**\n   * Start processing: subscribe to every source and begin delivering messages through the steps.\n   * @returns Promise that resolves when all sources have been subscribed and the consumers are ready\n   */\n  start(): Promise<void>;\n\n  /**\n   * Stop the route: abort all source subscriptions and clear the internal queues.\n   */\n  stop(): void;\n\n  /**\n   * Re-arm a stopped route so {@link Route.start} can run again, under the\n   * fresh controller the context now holds for it.\n   *\n   * Only enablement calls this. Both abort controllers latch, and the queues\n   * and consumers behind them belong to the run that just ended, so a route\n   * brought back from `disabled` needs new ones or it would refuse to start\n   * against its own aborted signal. Route IDENTITY is deliberately preserved:\n   * ops tracks by route id, the capability registry keys by endpoint, and\n   * listeners hold this instance, so re-enabling must not hand out a\n   * different object.\n   *\n   * @param controller - The intake controller the context has registered\n   *   for this route, so the two never disagree about which one a shutdown\n   *   aborts.\n   * @internal\n   */\n  resetForRestart(controller: AbortController): void;\n\n  /**\n   * Wait until all in-flight message handlers and tracked tasks (e.g. tap) have completed.\n   * Does not stop the route; use stop() to abort the sources.\n   */\n  drain(): Promise<void>;\n\n  /**\n   * Track a background task (e.g. tap) for this route.\n   * @param promise The promise to track\n   * @internal\n   */\n  trackTask(promise: Promise<unknown>): void;\n\n  /**\n   * Register a callback run at the START of every `drain()` (which shutdown\n   * also calls), before the in-flight wait loop. Lets a step holding an\n   * exchange outside the queue (debounce) flush it into in-flight work so\n   * drain releases it promptly instead of waiting out a timer. Callbacks\n   * must be idempotent: `drain()` can be called more than once.\n   *\n   * @internal\n   */\n  onDrain(callback: () => void): void;\n\n  /**\n   * Run `steps` against a revived exchange as a first-class run of this\n   * route: its own `route:exchange:started` / `:completed` pair, the route-scope\n   * `.error()` handler, and `.output()` validation before completion.\n   *\n   * The entry point for execution two. The steps handed in are the deferred\n   * exchange's continuation, so the route resumes partway down its pipeline\n   * without re-running what already ran, and without re-running the\n   * pre-from filter chain (authorize, parse, input, throttle, cache), all\n   * of which belong to execution one.\n   *\n   * @param exchange - The rehydrated exchange, already bound to this route\n   * @param steps - The continuation, in execution order\n   * @internal\n   */\n  runContinuation(\n    exchange: Exchange,\n    steps: ReadonlyArray<Step<Adapter>>,\n  ): Promise<DetachedResult>;\n\n  /**\n   * Push an error into this route's error channel for an exchange that is\n   * not currently running in it.\n   *\n   * The resume path uses it so a revival failure (an expired deferral, a\n   * continuation that changed under a deferred exchange) reaches the\n   * DEFERRED route's `.error()` handler rather than only the ingress\n   * route's. That is the difference between a route that can notify the\n   * approver and re-ask, and an approver left at a dead link.\n   *\n   * @param exchange - The exchange the failure concerns\n   * @param error - The failure to route\n   * @param operation - Step label reported on the error events\n   * @internal\n   */\n  enterErrorChannel(\n    exchange: Exchange,\n    error: unknown,\n    operation: string,\n  ): Promise<void>;\n\n  /**\n   * Build a forward function the route uses to delegate from an\n   * error / fallback handler to another route via the direct adapter.\n   * Exposed so step-scope `WrapperStep` subclasses can hand the same\n   * callable to a user-supplied handler as the route-level pipeline\n   * does.\n   *\n   * @param caller The exchange the forward is issued from. Its headers\n   *   travel with the forwarded call, so the target sees the same\n   *   principal and correlation id as the caller. Required rather than\n   *   optional so a new call site cannot silently forward anonymously.\n   * @internal\n   */\n  getForward(caller: Exchange): ForwardFn;\n}\n\n/**\n * Default implementation of the Route interface.\n *\n * Manages message flow from the source through the defined steps and the\n * internal processing queue to the consumer. Handles start, stop, drain, and\n * background task tracking (e.g. for tap).\n */\nexport class DefaultRoute implements Route {\n  /**\n   * Stops INTAKE: sources subscribe against this, and aborting it means\n   * \"produce nothing further\". It does NOT cancel work already in flight,\n   * which is what makes graceful shutdown's first stage a drain rather than\n   * a cancellation.\n   */\n  private abortController: AbortController;\n\n  /**\n   * Abandons EXECUTION: surfaced as {@link DefaultRoute.signal} and threaded\n   * into steps, wrappers and agent dispatch. Aborted only when work is\n   * genuinely being given up on: a forced shutdown, an explicit `stop()`, or\n   * a route that failed to start.\n   *\n   * Separate from intake because one controller carrying both meanings made\n   * the documented two-stage shutdown a lie: the first signal, which\n   * promises to stop accepting work and drain, cancelled every in-flight\n   * exchange as well.\n   */\n  private executionController = new AbortController();\n\n  /** Logger for this route (pino child logger) */\n  public readonly logger: ReturnType<typeof logger.child>;\n\n  /** Internal queues, one per source, for passing messages to the consumers */\n  private messageChannels!: ProcessingQueue<Message>[];\n\n  /** Processes messages from the message channels, one consumer per source */\n  private consumers!: Consumer[];\n\n  /** All in-flight work (handler and task promises) for drain */\n  private inFlight = new Set<Promise<unknown>>();\n\n  /** Callbacks run at the start of drain() to flush deferred holds (debounce). */\n  private drainCallbacks = new Set<() => void>();\n\n  /**\n   * Create a new route instance.\n   *\n   * @param context The context this route belongs to\n   * @param definition The route's configuration\n   * @param abortController Optional controller for aborting the route\n   */\n  constructor(\n    public readonly context: CraftContext,\n    public readonly definition: RouteDefinition,\n    abortController?: AbortController,\n  ) {\n    setBrand(this, BRAND.DefaultRoute);\n    this.assertNotAborted();\n    this.abortController = abortController ?? new AbortController();\n    this.logger = logger.child(childBindings(this));\n    if (definition.volatileCacheKey) {\n      this.logger.warn(\n        { route: definition.id },\n        `Route \"${definition.id}\" has no .id() and uses .cache() with the default key, which includes the route id. ` +\n          `The id is generated on every start, so cached entries never match after a restart. Add .id() to the route.`,\n      );\n    }\n    // One (channel, consumer) pair per source so each ingress gets its own\n    // delivery queue and, for batch routes, its own batch window. All\n    // consumers drive the same shared step pipeline via the handler\n    // registered in start(); the route stays a single logical entity (one id,\n    // one lifecycle event stream) regardless of how many ingresses it exposes.\n    this.buildChannelsAndConsumers();\n\n    this.watchIntakeAbort();\n  }\n\n  /**\n   * Emit `route:stopping` / `route:stopped` when the intake controller\n   * aborts, however that abort arrives (shutdown, `stop()`, a finite source\n   * completing). Re-armed on every restart because the listener belongs to\n   * the controller, and a restart installs a new one.\n   */\n  private watchIntakeAbort(): void {\n    this.abortController.signal.addEventListener(\"abort\", (event) => {\n      try {\n        this.context.emit(\"route:stopping\", {\n          routeId: this.definition.id,\n          route: this,\n          reason: (event as unknown as { reason?: unknown })?.reason,\n        });\n      } finally {\n        this.context.emit(\"route:stopped\", {\n          routeId: this.definition.id,\n          route: this,\n        });\n      }\n    });\n  }\n\n  /** @inheritDoc */\n  get intakeSignal(): AbortSignal {\n    return this.abortController.signal;\n  }\n\n  /** @inheritDoc */\n  get inFlightCount(): number {\n    return this.inFlight.size;\n  }\n\n  /**\n   * The EXECUTION signal: fires when in-flight work is being abandoned, not\n   * when the route merely stops accepting new work. Steps, resilience\n   * wrappers and agent dispatch observe this.\n   */\n  get signal(): AbortSignal {\n    return this.executionController.signal;\n  }\n\n  /**\n   * Abandon in-flight execution on this route.\n   *\n   * Graceful shutdown never calls this: stage one aborts intake and waits.\n   * It is the forced stage, an explicit `stop()`, and a route that failed to\n   * start.\n   *\n   * @param reason - Recorded as the abort reason for anything observing it.\n   * @internal\n   */\n  abortExecution(reason?: unknown): void {\n    if (!this.executionController.signal.aborted) {\n      this.executionController.abort(reason);\n    }\n  }\n\n  /**\n   * Create a new exchange object from a message and optional headers.\n   *\n   * Sources that authenticate at their boundary set the structured\n   * `Principal` on `headers[\"routecraft.auth.principal\"]` before calling\n   * the consumer handler; that value flows through this method as a\n   * normal header and surfaces on the exchange via the `ex.principal`\n   * getter.\n   *\n   * This is the single route-ingress boundary: both the consumer handler\n   * and `buildForward` funnel through it, and a `direct()` source hands the\n   * target its caller's headers verbatim. Engine-owned identity is\n   * therefore re-established here rather than inherited:\n   *\n   * - `routecraft.id` is minted fresh. Ingress is always a new exchange,\n   *   and an inherited id collides in every store keyed by it (telemetry\n   *   spans and rows, deferral ids). The correlation id is what links a\n   *   hop, not the exchange id.\n   * - `routecraft.split_hierarchy` is dropped. A split group only joins\n   *   within the executor run that created it, so an inherited hierarchy is\n   *   unjoinable, and `.aggregate()` would resolve its trailing group id\n   *   against the context-wide split-parent store and delete the caller's\n   *   still-in-flight entry.\n   * - `routecraft.route` and `routecraft.operation` are stamped for the\n   *   receiving route.\n   *\n   * Everything else, principal and correlation id included, is inherited by\n   * reference. See `.standards/security.md` section 3.\n   *\n   * @param message The message data\n   * @param headers Optional headers to include\n   * @returns A new Exchange object\n   * @private\n   */\n  private buildExchange(message: unknown, headers?: ExchangeHeaders): Exchange {\n    // Preserve the caller's correlation id when the source forwarded one\n    // (route-to-route via direct(), MCP tool calls, HTTP requests carrying\n    // a trace header). Falls back to a fresh UUID for sources that emit\n    // independent exchanges (timer, cron, simple, fresh ingress). This\n    // keeps cross-route logs / spans on the same logical request without\n    // requiring callers to thread the id manually.\n    const incomingCorrelationId = headers?.[HeadersKeys.CORRELATION_ID] as\n      string | undefined;\n    // Omitted rather than deleted after the fact: `delete` on a fresh literal\n    // drops the object into dictionary mode, and this one becomes the header\n    // bag every step then reads.\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars -- destructure to omit\n    const { [HeadersKeys.SPLIT_HIERARCHY]: _unjoinable, ...inherited } =\n      headers ?? {};\n    const builtHeaders: Record<string, unknown> = {\n      ...inherited,\n      [HeadersKeys.ID]: randomUUID(),\n      [HeadersKeys.CORRELATION_ID]: incomingCorrelationId ?? randomUUID(),\n      [HeadersKeys.ROUTE_ID]: this.definition.id,\n      [HeadersKeys.OPERATION]: OperationType.FROM,\n    };\n    const exchange = new DefaultExchange(this.context, {\n      body: message,\n      headers: builtHeaders,\n    });\n\n    // Add route to internals so steps like tap can access it (symbol-key for cross-instance)\n    const internals =\n      (\n        exchange as unknown as Exchange & {\n          [key: symbol]: { context: CraftContext; route?: Route };\n        }\n      )[INTERNALS_KEY] ?? EXCHANGE_INTERNALS.get(exchange);\n    if (internals) {\n      internals.route = this;\n    }\n\n    return exchange;\n  }\n\n  private cachedExecutorDeps?: ExecutorDeps;\n  private cachedValidationDeps?: ValidationDeps;\n\n  /**\n   * Assemble the deps object for the pipeline executor. Memoized: every\n   * field is stable for the lifetime of the route, and this is called on\n   * the per-exchange hot path.\n   */\n  private executorDeps(): ExecutorDeps {\n    this.cachedExecutorDeps ??= {\n      routeId: this.definition.id,\n      context: this.context,\n      route: this,\n      definition: this.definition,\n      buildForward: (caller: Exchange) => this.buildForward(caller),\n    };\n    return this.cachedExecutorDeps;\n  }\n\n  /** Assemble the deps object for the pipeline validation helpers (memoized, see {@link executorDeps}). */\n  private validationDeps(): ValidationDeps {\n    if (!this.cachedValidationDeps) {\n      const deps: ValidationDeps = {\n        routeId: this.definition.id,\n        context: this.context,\n        route: this,\n        buildForward: (caller: Exchange) => this.buildForward(caller),\n      };\n      if (this.definition.errorHandler) {\n        deps.errorHandler = this.definition.errorHandler;\n      }\n      this.cachedValidationDeps = deps;\n    }\n    return this.cachedValidationDeps;\n  }\n\n  /**\n   * Track a background task (e.g. tap) for this route.\n   * @internal\n   */\n  trackTask(promise: Promise<unknown>): void {\n    const handledPromise = promise.catch((err: unknown) => {\n      const msg = isRoutecraftError(err)\n        ? (err as { meta: { message: string } }).meta.message\n        : err instanceof Error\n          ? err.message\n          : \"Background task failed\";\n      this.logger.error({ err, route: this.definition.id }, msg);\n    });\n    this.inFlight.add(handledPromise);\n    handledPromise.finally(() => this.inFlight.delete(handledPromise));\n  }\n\n  /**\n   * Register a flush callback run at the start of drain(). See {@link Route.onDrain}.\n   * @internal\n   */\n  onDrain(callback: () => void): void {\n    this.drainCallbacks.add(callback);\n  }\n\n  /**\n   * Start processing data on this route.\n   *\n   * This method:\n   * 1. Registers each per-source consumer to process messages\n   * 2. Subscribes to every source to receive data\n   *\n   * @returns A promise that resolves when the route has started\n   * @throws {RoutecraftError} If the route has been aborted\n   */\n  async start(): Promise<void> {\n    this.assertNotAborted();\n    // Lifecycle log is emitted only by context (one log per event).\n\n    // Register the shared pipeline handler on every per-source consumer.\n    // Framework-level `.input()` validation is stashed on exchange\n    // internals here and runs INSIDE the pre-from filter chain (position\n    // #4), so any source adapter with an `.input()` schema on the route\n    // inherits validation without per-adapter wiring, and a failure is\n    // routable through the route-scope `.error()` handler. Unrecovered,\n    // the handler's rejection still reaches the source's own caller\n    // (e.g. a direct channel's `send`). See #447.\n    const consumerHandler = this.buildConsumerHandler();\n    for (const consumer of this.consumers) {\n      consumer.register(consumerHandler);\n    }\n\n    // Emit `route:started` once ALL sources have signalled readiness. The\n    // route is a single logical entity, so its lifecycle events fire once no\n    // matter how many ingresses it exposes. Every built-in source calls\n    // `onReady`; the enqueue callback also marks readiness as a fallback for\n    // callable sources that produce a message without calling it.\n    const total = this.definition.sources.length;\n    const readyIndices = new Set<number>();\n    let startedEmitted = false;\n    const markReady = (index: number): void => {\n      readyIndices.add(index);\n      if (!startedEmitted && readyIndices.size === total) {\n        startedEmitted = true;\n        this.context.emit(\"route:started\", {\n          routeId: this.definition.id,\n          route: this,\n        });\n      }\n    };\n\n    const meta = {\n      routeId: this.definition.id,\n      ...(this.definition.discovery\n        ? { discovery: this.definition.discovery }\n        : {}),\n      ...(this.definition.requiresPrincipal ? { requiresPrincipal: true } : {}),\n      // Read from the consumer's own declaration, and resolved here because\n      // this is where the consumer is known rather than in each source.\n      ...(this.definition.consumer.type.buffers === true\n        ? { bufferedConsumer: true }\n        : {}),\n    };\n\n    // Subscribe every source, each into its own channel. A test-time override\n    // is resolved per source so individual ingresses can be mocked. start()\n    // resolves only when ALL subscriptions resolve: server ingresses (direct,\n    // http, mcp) hold open until abort, so a multi-ingress route with any\n    // server ingress keeps the context alive, while a route whose sources are\n    // all finite completes and lets the context auto-stop.\n    // Build AND await every subscription inside the try so both a synchronous\n    // throw while wiring a source (override resolution, a sync callable source)\n    // and an async subscribe rejection hit the same cleanup path. On failure,\n    // abort the route so any sibling ingresses that already subscribed are torn\n    // down (registry entries cleared, pending subscribes resolved) instead of\n    // leaking, then surface the error. `context.start()` already aborts on a\n    // failed route.start(); this makes start() self-cleaning for direct callers\n    // too. Harmless for the single-source case (no siblings).\n    try {\n      const subscriptions = this.definition.sources.map(\n        (definitionSource, index) => {\n          const channel = this.messageChannels[index];\n          const sourceOverride = resolveAdapterOverride(\n            definitionSource,\n            this.context,\n            \"source\",\n          );\n          const activeSource =\n            sourceOverride && sourceOverride.source\n              ? wrapSourceWithOverride(definitionSource, sourceOverride)\n              : definitionSource;\n          // A single-source route hands the source the route's own controller\n          // so a finite source completing (such sources call abort() when done)\n          // stops the route exactly as before. A multi-ingress route gives each\n          // source a child controller linked to the route's: the route aborts\n          // every child, but one finite ingress completing only aborts its own\n          // child and never tears down a sibling ingress (e.g. a long-lived\n          // http/mcp server holding the route open).\n          const sourceController =\n            total === 1 ? this.abortController : this.linkedChildController();\n          // Assemble the Subscription object: the single argument every\n          // source receives. Capabilities are added here as new fields,\n          // never as new positional parameters.\n          const subscription: Subscription = {\n            context: this.context,\n            signal: sourceController.signal,\n            meta,\n            ready: () => markReady(index),\n            complete: (reason?: unknown) => sourceController.abort(reason),\n            emit: (msg) => {\n              markReady(index); // fallback: fire before first message if adapter never called ready()\n              return channel.enqueue({\n                message: msg.message,\n                headers: msg.headers ?? {},\n                ...(msg.parse\n                  ? {\n                      parse: msg.parse,\n                      parseFailureMode: msg.parseFailureMode ?? \"fail\",\n                    }\n                  : {}),\n              });\n            },\n          };\n          // Coerce to a promise so a void return and an async rejection are\n          // handled uniformly by Promise.all; a synchronous throw is caught by\n          // the surrounding try because the map runs inside it. A rejection\n          // means the source gave up producing (a dead channel), which is a\n          // state operators must be able to alarm on: emit the per-source\n          // event here, before the route-level abort below, so listeners see\n          // which ingress died even on a multi-ingress route. A rejection\n          // after the source's controller aborted is teardown noise (an\n          // orderly stop, or a sibling being torn down because another\n          // source already failed), not a dead channel: skip the event.\n          return Promise.resolve(activeSource.subscribe(subscription)).catch(\n            (error: unknown) => {\n              if (!sourceController.signal.aborted) {\n                this.context.emit(\"route:source:failed\", {\n                  routeId: this.definition.id,\n                  route: this,\n                  ...(activeSource.adapterId\n                    ? { adapter: activeSource.adapterId }\n                    : {}),\n                  error,\n                });\n              }\n              throw error;\n            },\n          );\n        },\n      );\n      await Promise.all(subscriptions);\n    } catch (err) {\n      // A source that could not subscribe is a failure, not a completion, so\n      // in-flight work on this route is abandoned along with intake.\n      if (!this.abortController.signal.aborted) {\n        this.abortController.abort(err);\n      }\n      this.abortExecution(err);\n      throw err;\n    }\n\n    // Every ingress's subscription resolved. For a multi-ingress route whose\n    // sources are all finite this means every ingress has completed: mirror the\n    // single-source contract (where a finite source aborts the route's own\n    // controller on completion) by aborting here so the route's terminal\n    // lifecycle events fire even when an indefinite sibling route keeps the\n    // context alive. A route holding any server ingress never reaches this with\n    // an un-aborted controller (a server's subscribe only resolves once the\n    // controller is aborted), so the guard makes this a no-op there. The\n    // single-source path is left exactly as before: its source drives\n    // completion.\n    //\n    // INTAKE only. Sources finishing means no more work arrives, not that\n    // exchanges already in the pipeline should be cancelled; those drain.\n    if (total > 1 && !this.abortController.signal.aborted) {\n      this.abortController.abort(\"All ingresses completed\");\n    }\n  }\n\n  /**\n   * Create an AbortController that aborts when the route's controller aborts,\n   * but whose own abort does not propagate back to the route. Used to give\n   * each ingress of a multi-source route an independent lifetime so a finite\n   * source completing does not tear down its sibling ingresses.\n   */\n  private linkedChildController(): AbortController {\n    const child = new AbortController();\n    if (this.abortController.signal.aborted) {\n      child.abort(this.abortController.signal.reason);\n    } else {\n      this.abortController.signal.addEventListener(\n        \"abort\",\n        () => child.abort(this.abortController.signal.reason),\n        { once: true },\n      );\n    }\n    return child;\n  }\n\n  /**\n   * Build the handler registered on every per-source consumer. The handler is\n   * shared across all of a route's ingresses so they drive one pipeline; it\n   * stashes the source-supplied parser and the route's `.input()` validator\n   * on exchange internals so `runPipeline` runs both INSIDE the pre-from\n   * filter chain (positions #3 / #4). A parse or validation failure is\n   * therefore a normal step failure, routable through the route-scope\n   * `.error()` handler (chain position #1) for every source shape; see\n   * #187 (parse) and #447 (the input fold).\n   */\n  private buildConsumerHandler(): (envelope: Message) => Promise<Exchange> {\n    return async ({ message, headers, parse, parseFailureMode }) => {\n      const exchange = this.buildExchange(message, headers);\n      const inputSchemas = this.definition.discovery?.input;\n      const hasInputSchema = !!inputSchemas?.body || !!inputSchemas?.headers;\n\n      const internals = EXCHANGE_INTERNALS.get(exchange);\n      if (internals) {\n        if (parse) {\n          // Stash the source-supplied parser so `runPipeline` applies it\n          // as a synthetic first pipeline step. This is what makes parse\n          // errors surface as normal pipeline events the route can\n          // observe (`.error()` for `'fail'`, `route:exchange:dropped` for\n          // `'drop'`). See #187.\n          internals.parse = parse;\n          internals.parseFailureMode = parseFailureMode ?? \"fail\";\n        }\n        // Stash the `.input()` validator alongside. With a parser the\n        // synthetic parse step runs it once parse succeeds (input\n        // validates the parsed body, not the raw bytes); without one\n        // `runPipeline` inserts a standalone input step in the same\n        // chain position. The non-emitting variant throws RC5065\n        // cleanly into the step loop's catch path (which emits\n        // `route:step:failed` and then the error path), without firing\n        // duplicate `route:exchange:started` / stray `route:exchange:dropped`\n        // events (see #187, #447).\n        if (hasInputSchema && inputSchemas) {\n          internals.applyValidation = (ex: Exchange) =>\n            validateInputOrThrow(this.validationDeps(), ex, inputSchemas);\n        }\n      }\n\n      return this.handler(exchange);\n    };\n  }\n\n  /**\n   * Stop processing data on this route.\n   *\n   * This method:\n   * 1. Unsubscribes from the internal processing queue\n   * 2. Aborts the route's controller\n   */\n  stop(): void {\n    // Lifecycle log is emitted only by context (one log per event).\n    for (const channel of this.messageChannels) {\n      channel.clear();\n    }\n    // Both signals: stop() discards queued messages, so it is a giving-up on\n    // this route rather than the orderly drain graceful shutdown performs.\n    this.abortController.abort(\"Route stop() called\");\n    this.abortExecution(\"Route stop() called\");\n  }\n\n  /**\n   * One (channel, consumer) pair per source, so each ingress gets its own\n   * delivery queue and, for batch routes, its own batch window. All\n   * consumers drive the same shared step pipeline via the handler registered\n   * in start(), so the route stays a single logical entity regardless of how\n   * many ingresses it exposes.\n   *\n   * Shared by the constructor and the restart so a consumer that gains a\n   * construction dependency cannot get it in one path and silently miss it\n   * in the other.\n   */\n  private buildChannelsAndConsumers(): void {\n    this.messageChannels = this.definition.sources.map(\n      () => new InMemoryProcessingQueue<Message>(),\n    );\n    this.consumers = this.messageChannels.map(\n      (channel) =>\n        new this.definition.consumer.type({\n          context: this.context,\n          definition: this.definition,\n          channel,\n          options: this.definition.consumer.options,\n        }),\n    );\n  }\n\n  /** @inheritDoc */\n  resetForRestart(controller: AbortController): void {\n    this.abortController = controller;\n    this.executionController = new AbortController();\n    // Rebuilt rather than reused: a queue cleared by stop() is still the\n    // queue whose consumer was registered against the previous run, and a\n    // consumer may hold per-run state (a batch window, a debounce hold).\n    // start() registers a fresh handler on whatever is here.\n    this.buildChannelsAndConsumers();\n    this.watchIntakeAbort();\n  }\n\n  /**\n   * Process an exchange through the route's steps.\n   * Resolves with the result immediately; then waits for background tasks (e.g. tap) before cleanup.\n   *\n   * @param exchange The initial exchange to process\n   * @returns A promise that resolves when processing is complete\n   * @private\n   */\n  private handler(exchange: Exchange): Promise<Exchange> {\n    exchange.logger.debug({ operation: \"from\" }, \"Processing initial exchange\");\n\n    const startTime = Date.now();\n\n    // Emit route:exchange:started event\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n    this.context.emit(\"route:exchange:started\", {\n      routeId: this.definition.id,\n      exchangeId: exchange.id,\n      correlationId,\n    });\n\n    // Run steps (tap adds tasks via route.trackTask)\n    const handlerPromise = runPipeline(\n      this.executorDeps(),\n      exchange,\n      startTime,\n    ).then(async (result) => {\n      // Framework-level output validation runs on successful, non-dropped\n      // exchanges before we declare completion. A failure falls through the\n      // same path as a thrown step: errorHandler if set, else a failed result.\n      // A deferred exchange is exempt from the output stage AND from\n      // completion: its body is the `Deferred` acknowledgment rather than\n      // the route's declared output (the two arms of the route's\n      // `Output | Deferred` type), and its terminal event was\n      // `route:exchange:deferred`. The source still receives the exchange,\n      // which is how each transport renders the acknowledgment.\n      const finalResult = await applyOutputStage(\n        this.validationDeps(),\n        this.definition.discovery?.output,\n        result,\n        startTime,\n      );\n\n      if (\n        !finalResult.failed &&\n        !finalResult.dropped &&\n        !finalResult.deferred\n      ) {\n        const duration = Date.now() - startTime;\n        const correlationId = exchange.headers[\n          HeadersKeys.CORRELATION_ID\n        ] as string;\n        this.context.emit(\"route:exchange:completed\", {\n          routeId: this.definition.id,\n          exchangeId: exchange.id,\n          correlationId,\n          duration,\n          exchange: finalResult.exchange,\n        });\n      }\n\n      // Reject so callers (CraftClient, direct channel) can handle the error.\n      // Source adapters catch this rejection and continue processing.\n      if (finalResult.failed && finalResult.error) {\n        throw finalResult.error;\n      }\n\n      return finalResult.exchange;\n    });\n\n    // Track in-flight work. Use a catch-suppressed wrapper so rejected\n    // handler promises don't trigger unhandled rejection warnings; the\n    // actual rejection is handled by the caller (source adapter / channel).\n    const tracked = handlerPromise.catch(() => {});\n    this.inFlight.add(tracked);\n    tracked.finally(() => this.inFlight.delete(tracked));\n\n    return handlerPromise;\n  }\n\n  /**\n   * Run a revived exchange through its continuation. See\n   * {@link Route.runContinuation}.\n   *\n   * Tracked as in-flight work so `drain()` (and therefore shutdown) waits\n   * for execution two, which arrives out of band and would otherwise be\n   * invisible to the route that owns it.\n   *\n   * @internal\n   */\n  runContinuation(\n    exchange: Exchange,\n    steps: ReadonlyArray<Step<Adapter>>,\n  ): Promise<DetachedResult> {\n    const run = runDetachedPipeline(\n      this.executorDeps(),\n      steps,\n      exchange,\n      \"resume\",\n    );\n    this.trackTask(run);\n    return run;\n  }\n\n  /**\n   * Push an error into this route's error channel. See\n   * {@link Route.enterErrorChannel}.\n   *\n   * Implemented as a one-step pipeline whose step throws, rather than by\n   * calling the handler directly, so a revival failure produces exactly the\n   * events a step failure produces (`route:step:error`,\n   * `route:error-handler:invoked` / `:recovered` / `:failed`, or the\n   * default `route:error` + `context:error` + `route:exchange:failed`\n   * path). A second, hand-rolled error path would drift from that one.\n   *\n   * @internal\n   */\n  async enterErrorChannel(\n    exchange: Exchange,\n    error: unknown,\n    operation: string,\n  ): Promise<void> {\n    const start = Date.now();\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n    // The re-entry is a run of this route in its own right, so it gets its\n    // own started / terminal pair rather than leaving a stray `failed` with\n    // no `started` before it. `.output()` validation is deliberately NOT\n    // applied to a recovered body: what a re-ask handler returns is a\n    // notification, not the route's output.\n    this.context.emit(\"route:exchange:started\", {\n      routeId: this.definition.id,\n      exchangeId: exchange.id,\n      correlationId,\n    });\n    const deps: ExecutorDeps = {\n      // The memoised deps carry the route's own `buildForward`, so the\n      // re-ask handler forwards as the DEFERRED exchange: its `forward()`\n      // takes the correlation of the work being re-asked about, and its\n      // principal, which came back from the store marked restored. A target\n      // declaring `.authorize()` refuses it for that reason (RC5043), which\n      // is the correct answer: nothing re-verified that identity across the\n      // deferral.\n      ...this.executorDeps(),\n      definition: detachedDefinition(\n        this.definition,\n        [\n          {\n            operation: OperationType.PROCESS,\n            label: operation,\n            // Derived from the caller's label rather than pinned to the\n            // resume operation: a cancellation sweeper or an operator deny\n            // path pushing into this channel must not have its failures\n            // attributed to resume in telemetry.\n            adapter: { adapterId: `routecraft.operation.${operation}` },\n            execute: () => Promise.reject(error),\n          },\n        ],\n        \"errorChannel\",\n      ),\n    };\n    const result = await runPipeline(deps, exchange, start);\n    if (!result.failed && !result.dropped) {\n      this.context.emit(\"route:exchange:completed\", {\n        routeId: this.definition.id,\n        exchangeId: exchange.id,\n        correlationId,\n        duration: Date.now() - start,\n        exchange: result.exchange,\n      });\n    }\n  }\n\n  /**\n   * Build a forward function that sends a payload to another route via the direct adapter.\n   *\n   * Exposed (`@internal`) so step-scope `WrapperStep` subclasses can hand\n   * the same forward callable to a user-supplied error / fallback handler\n   * as the route-level pipeline does. Resolve via\n   * `getExchangeRoute(exchange).getForward(exchange)`.\n   *\n   * @returns A forward function\n   */\n  getForward(caller: Exchange): ForwardFn {\n    return this.buildForward(caller);\n  }\n\n  /**\n   * Build a forward function that sends a payload to another route via the direct adapter.\n   *\n   * The forwarded exchange inherits the calling exchange's headers, which is\n   * what carries the caller's principal and correlation id across the hop. A\n   * `direct()` destination gets this for free because it hands the target its\n   * live exchange; forward builds a fresh envelope, so it has to pass the\n   * headers explicitly or the target sees an anonymous, separately-traced\n   * call.\n   *\n   * @param caller The exchange the forward is issued from\n   * @returns A forward function\n   * @private\n   */\n  private buildForward(caller: Exchange): ForwardFn {\n    return async (\n      endpoint: RegisteredDirectEndpoint,\n      payload: unknown,\n    ): Promise<unknown> => {\n      const { getDirectChannel, sanitizeEndpoint } =\n        await import(\"./adapters/direct/shared.ts\");\n      const sanitized = sanitizeEndpoint(endpoint as string);\n      const channel = getDirectChannel(this.context, sanitized, {});\n      const forwardExchange = this.buildExchange(payload, caller.headers);\n      const result = await channel.send(sanitized, forwardExchange);\n      // Mirror CraftClient.sendDirect: a dropped exchange has no result,\n      // and resolving with its body would echo the forwarded payload back\n      // as if the target route produced it.\n      if (isDropped(result)) {\n        throw rcError(\"RC5031\", undefined, {\n          message: `Forward target \"${String(endpoint)}\" dropped the exchange instead of completing it; there is no result body.`,\n        });\n      }\n      return result.body;\n    };\n  }\n\n  /**\n   * Wait for all in-flight work (handlers and tasks) to complete.\n   * Loops until no new work is added (drains consumer queue).\n   */\n  async drain(): Promise<void> {\n    // Flush any deferred holds (e.g. debounce) FIRST so their releases become\n    // tracked in-flight work before we wait, rather than waiting out a timer.\n    this.runDrainCallbacks();\n    this.logger.debug(\n      { inFlight: this.inFlight.size },\n      \"Draining route: waiting for in-flight handlers and tasks\",\n    );\n    while (this.inFlight.size > 0) {\n      const current = [...this.inFlight];\n      await Promise.allSettled(current);\n      // Re-flush after each settle round: a flushed release can create a NEW\n      // hold further down the pipeline (e.g. chained debounce steps), which\n      // would otherwise sit out its full timer before the loop could finish.\n      this.runDrainCallbacks();\n    }\n    this.logger.debug({}, \"Route drained\");\n  }\n\n  /**\n   * Run the registered drain-flush callbacks (see {@link Route.onDrain}).\n   * Callbacks are idempotent by contract, so calling this repeatedly (once\n   * up front and once per drain settle round) is safe.\n   */\n  private runDrainCallbacks(): void {\n    for (const callback of this.drainCallbacks) {\n      try {\n        callback();\n      } catch (err) {\n        this.logger.error(\n          { err, route: this.definition.id },\n          \"drain flush callback failed\",\n        );\n      }\n    }\n  }\n\n  /**\n   * Check if the route has been aborted, and throw an error if it has.\n   *\n   * @throws {RoutecraftError} If the route has been aborted\n   * @private\n   */\n  private assertNotAborted(): void {\n    if (this.abortController?.signal.aborted) {\n      throw rcError(\"RC3001\", undefined, {\n        message: `${RC[\"RC3001\"].message}: ${this.definition.id}`,\n      });\n    }\n  }\n}\n","/**\n * Factory-tagging primitive used to mark adapter instances with the factory\n * that produced them. Enables the testing override API to resolve which mock\n * applies to an adapter instance at route execution time.\n *\n * Two non-enumerable symbol properties are stamped on the instance:\n * - {@link RC_ADAPTER_FACTORY} - reference to the factory function\n * - {@link RC_ADAPTER_ARGS} - the args passed to the factory\n *\n * Symbols are global (`Symbol.for`) so cross-instance equality holds if the\n * package is loaded more than once via different resolutions.\n *\n * @internal\n */\n\nexport const RC_ADAPTER_FACTORY: unique symbol = Symbol.for(\n  \"routecraft.adapter.factory\",\n);\n\nexport const RC_ADAPTER_ARGS: unique symbol = Symbol.for(\n  \"routecraft.adapter.args\",\n);\n\n/**\n * Stamp an adapter instance with its factory and construction args so that\n * `testContext().override(mockAdapter(factory, ...))` can match the instance\n * back to its factory at route execution time.\n *\n * Tagging is optional: adapters that skip it can still be mocked by passing\n * the adapter class to `mockAdapter(Class, ...)` (class-based resolution).\n * Tagging is preferred for single-role factories where the factory reference\n * is what users import and think in terms of.\n *\n * @param adapter - Adapter instance returned by a factory\n * @param factory - Factory function that produced the instance (self-reference)\n * @param args - Args that were passed to the factory\n * @returns The same adapter instance (for chaining)\n */\nexport function tagAdapter<A extends object>(\n  adapter: A,\n  factory: unknown,\n  args: unknown[],\n): A {\n  Object.defineProperty(adapter, RC_ADAPTER_FACTORY, {\n    value: factory,\n    enumerable: false,\n    configurable: true,\n    writable: false,\n  });\n  Object.defineProperty(adapter, RC_ADAPTER_ARGS, {\n    value: args,\n    enumerable: false,\n    configurable: true,\n    writable: false,\n  });\n  return adapter;\n}\n\n/**\n * Build the `args` tuple passed to {@link tagAdapter} from a variadic\n * factory's parameter list, trimming trailing `undefined` entries so the\n * recorded length matches what the user actually typed at the call site.\n *\n * Use this helper from every adapter factory that forwards user args to\n * `tagAdapter`, so mock authors see a consistent `args.length` across\n * adapters (for example, `mail()`, `mcp(endpoint)` and `http({})` all\n * record a single-element tuple when only one argument was passed).\n *\n * @example\n * ```ts\n * function mcp(endpoint, options?) {\n *   return tagAdapter(new McpAdapter(...), mcp, factoryArgs(endpoint, options));\n * }\n * ```\n */\nexport function factoryArgs(...args: unknown[]): unknown[] {\n  let end = args.length;\n  while (end > 0 && args[end - 1] === undefined) end--;\n  return args.slice(0, end);\n}\n\n/**\n * Read the factory reference from a tagged adapter instance.\n *\n * @param adapter - Candidate adapter instance\n * @returns The factory function, or undefined if not tagged\n *\n * @internal\n */\nexport function getAdapterFactory(\n  adapter: unknown,\n): ((...args: unknown[]) => unknown) | undefined {\n  if (adapter === null || typeof adapter !== \"object\") return undefined;\n  return (adapter as Record<symbol, unknown>)[RC_ADAPTER_FACTORY] as\n    ((...args: unknown[]) => unknown) | undefined;\n}\n\n/**\n * Read the construction args from a tagged adapter instance.\n *\n * @param adapter - Candidate adapter instance\n * @returns The args array, or undefined if not tagged\n *\n * @internal\n */\nexport function getAdapterArgs(adapter: unknown): unknown[] | undefined {\n  if (adapter === null || typeof adapter !== \"object\") return undefined;\n  return (adapter as Record<symbol, unknown>)[RC_ADAPTER_ARGS] as\n    unknown[] | undefined;\n}\n","/**\n * Stamp a role facade with the constructor of the adapter it delegates to.\n *\n * A factory that exposes only the slots matching its configured shape has to\n * build a plain object: keeping the class instance would leak the opposite\n * role (a read-shaped `carddav()` would still carry `send` on its prototype,\n * so `.to()` would resolve the wrong slot). The plain object costs the\n * adapter its identity, and `mockAdapter` matches an override either by\n * tagged factory OR by `adapter.constructor`, so a class-based\n * `mockAdapter(CarddavAdapter, ...)` would silently stop intercepting: the\n * route would hit the network in a test that reads as mocked.\n *\n * Re-pointing `constructor` at the delegate keeps that route working without\n * putting the prototype (and its unwanted slots) back in the chain. It is\n * non-enumerable, the same way a real prototype's `constructor` is, so\n * spreads and `Object.assign` of the facade are unaffected.\n *\n * @param facade - Role-slot object the factory returns\n * @param delegate - Adapter instance the facade forwards to\n * @returns The same facade, for chaining into `tagAdapter`\n * @internal\n */\nexport function withAdapterIdentity<F extends object>(\n  facade: F,\n  delegate: object,\n  ...alsoStandsFor: readonly AdapterConstructor[]\n): F {\n  Object.defineProperty(facade, \"constructor\", {\n    value: delegate.constructor,\n    enumerable: false,\n    writable: true,\n    configurable: true,\n  });\n  if (alsoStandsFor.length > 0) {\n    // Constructors, not instances: a facade may front a delegate it builds\n    // lazily, and naming the class keeps that delegate unconstructed until\n    // its role is actually used.\n    Object.defineProperty(facade, RC_ADAPTER_IDENTITIES, {\n      value: new Set<unknown>([delegate.constructor, ...alsoStandsFor]),\n      enumerable: false,\n      writable: true,\n      configurable: true,\n    });\n  }\n  return facade;\n}\n\n/**\n * An adapter implementation class, as named for override matching. `never[]`\n * params make every concrete constructor assignable regardless of its own\n * signature; `abstract new` additionally admits abstract bases.\n *\n * @internal\n */\nexport type AdapterConstructor = abstract new (...args: never[]) => unknown;\n\n/**\n * Every constructor a facade stands in for, when one facade fronts more than\n * one implementation class.\n *\n * `constructor` can only name one of them, but a facade that merges two role\n * implementations (mail's read side: an IDLE/polling source and a batch\n * enricher) is a legitimate target for a class-based mock of EITHER. Without\n * this, mocking the un-named class silently fails to intercept and the test\n * reaches the real service.\n *\n * @internal\n */\nexport const RC_ADAPTER_IDENTITIES: unique symbol = Symbol.for(\n  \"routecraft.adapter.identities\",\n);\n\n/**\n * The constructors an adapter answers to for class-based override matching:\n * the full set when it is a multi-delegate facade, otherwise just its own.\n *\n * @internal\n */\nexport function adapterIdentities(adapter: unknown): ReadonlySet<unknown> {\n  if (adapter === null || typeof adapter !== \"object\") return new Set();\n  const declared = (\n    adapter as { [RC_ADAPTER_IDENTITIES]?: ReadonlySet<unknown> }\n  )[RC_ADAPTER_IDENTITIES];\n  return (\n    declared ?? new Set([(adapter as { constructor?: unknown }).constructor])\n  );\n}\n","import type { CraftContext } from \"./context.ts\";\nimport type { Exchange, ExchangeHeaders } from \"./exchange.ts\";\nimport type { Adapter } from \"./types.ts\";\nimport type { Source } from \"./operations/from.ts\";\nimport {\n  getAdapterFactory,\n  getAdapterArgs,\n  tagAdapter,\n} from \"./adapters/shared/factory-tag.ts\";\nimport { adapterIdentities } from \"./adapters/shared/role-facade.ts\";\n\n/**\n * Store key under which test-time adapter overrides are registered.\n *\n * Intended for use by `@routecraft/testing`'s `testContext().override(...)`\n * API. Production code should not write to this key.\n * @internal\n */\nexport const RC_ADAPTER_OVERRIDES: unique symbol = Symbol.for(\n  \"routecraft.testing.adapter-overrides\",\n);\n\n/**\n * Recorded call to an overridden destination adapter (send / enrich).\n * @internal\n */\nexport interface AdapterSendCall {\n  /** Args that were passed to the adapter's factory at route definition time. */\n  args: unknown[];\n  /** Snapshot of the exchange as seen by the adapter at the moment of the call. */\n  exchange: {\n    id: string;\n    body: unknown;\n    headers: ExchangeHeaders;\n  };\n  /** Result the mock returned (undefined for void-returning sends). */\n  result: unknown;\n}\n\n/**\n * Recorded call to an overridden source adapter (subscribe).\n * @internal\n */\nexport interface AdapterSourceCall {\n  /** Args that were passed to the factory at route definition time. */\n  args: unknown[];\n  /** Number of messages yielded by this subscription. */\n  yielded: number;\n}\n\n/**\n * Brand marking a source fixture that carries explicit headers alongside its\n * body. Lets a source-role mock reproduce the body/headers split that real\n * envelope-carrying sources (http, mail) perform, so a route that reads\n * `routecraft.<adapter>.*` headers can be exercised through `mockAdapter`.\n *\n * Use the `sourceMessage()` helper from `@routecraft/testing` to construct\n * these rather than building the branded object by hand.\n * @internal\n */\nexport const SOURCE_FIXTURE: unique symbol = Symbol.for(\n  \"routecraft.testing.source-fixture\",\n);\n\n/**\n * A source fixture pairing a message body with the headers a real source would\n * have attached. Recognised by {@link wrapSourceWithOverride}.\n * @internal\n */\nexport interface SourceFixture<M = unknown> {\n  readonly [SOURCE_FIXTURE]: true;\n  /** The body the source would deliver on the exchange. */\n  readonly body: M;\n  /** Headers the source would attach (e.g. `routecraft.mail.*`). */\n  readonly headers?: ExchangeHeaders;\n}\n\n/**\n * Type guard for {@link SourceFixture}. A plain message is delivered as the\n * body with no headers; a branded fixture is unwrapped into `(body, headers)`.\n * @internal\n */\nexport function isSourceFixture(value: unknown): value is SourceFixture {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    (value as { [SOURCE_FIXTURE]?: unknown })[SOURCE_FIXTURE] === true\n  );\n}\n\n/**\n * A source-role fixture: either a plain message (delivered as the body with no\n * headers) or a {@link SourceFixture} carrying body + headers.\n * @internal\n */\nexport type SourceMessage<M = unknown> = M | SourceFixture<M>;\n\n/**\n * Handler shape for a source-role mock. May be a plain array of fixtures,\n * an async iterable, or a callable that returns either (receiving the\n * construction args so it can vary by call site). Each fixture may be a plain\n * message or a {@link SourceFixture} (via `sourceMessage()`) to also attach\n * headers.\n * @internal\n */\nexport type SourceOverrideBehavior<M = unknown> =\n  | readonly SourceMessage<M>[]\n  | AsyncIterable<SourceMessage<M>>\n  | Iterable<SourceMessage<M>>\n  | ((\n      args: unknown[],\n    ) =>\n      | readonly SourceMessage<M>[]\n      | Iterable<SourceMessage<M>>\n      | AsyncIterable<SourceMessage<M>>);\n\n/**\n * Handler shape for a destination-role mock. Receives the exchange (as\n * seen by the adapter) and a meta object containing the factory args used\n * at the call site. Returning a value replaces `exchange.body` upstream.\n * @internal\n */\nexport type SendOverrideHandler = (\n  exchange: Exchange,\n  meta: { args: unknown[] },\n) => unknown | Promise<unknown>;\n\n/**\n * An override registered on a test context. `target` may be either the\n * factory function that produced the adapter (matched via the factory-tag\n * set by `tagAdapter`) or the adapter's constructor class (matched by\n * `adapter.constructor === target`). Both routes coexist so any adapter\n * can be mocked without opt-in, while tagged factories keep nicer DX.\n * @internal\n */\nexport interface AdapterOverride {\n  /** Factory function or adapter class to match against the adapter instance. */\n  target: unknown;\n  /** Optional source-role behaviour (used when adapter has `subscribe`). */\n  source?: SourceOverrideBehavior;\n  /** Optional destination-role behaviour (used when adapter has `send`). */\n  send?: SendOverrideHandler;\n  /** Recorded calls, populated at execution time. */\n  calls: {\n    source: AdapterSourceCall[];\n    send: AdapterSendCall[];\n  };\n}\n\n/**\n * Take a defensive copy of an exchange body at call-recording time, so that\n * handlers mutating the body afterwards cannot corrupt the recorded snapshot.\n *\n * Uses `structuredClone` for plain values; falls back to the original\n * reference for values that cannot be cloned (functions, class instances\n * with unclonable internals, etc.) so recording never throws.\n */\nfunction snapshotBody(body: unknown): unknown {\n  if (body === null || typeof body !== \"object\") return body;\n  try {\n    return structuredClone(body);\n  } catch {\n    return body;\n  }\n}\n\n/**\n * Which role slot an override is being resolved for. `.enrich()` and a\n * fetch-resolved `.to()` both draw on the `send` behaviour, so the axis is\n * subscribe-versus-call rather than one member per operation keyword.\n *\n * @internal\n */\nexport type OverrideRole = \"source\" | \"send\";\n\n/**\n * Look up an override registered on the given context for the adapter.\n * Matches by tagged factory first (if the adapter was stamped via\n * `tagAdapter`); falls back to matching by adapter constructor class so\n * any adapter can be mocked without opt-in tagging.\n *\n * @param adapter - Adapter instance or role facade the step is about to use\n * @param context - Context whose registered overrides to search\n * @param role - Role slot being resolved, used to break a multi-identity tie\n * @internal\n */\nexport function resolveAdapterOverride(\n  adapter: unknown,\n  context: CraftContext | undefined,\n  role: OverrideRole,\n): AdapterOverride | undefined {\n  if (!context) return undefined;\n  const overrides = context.getStore(RC_ADAPTER_OVERRIDES);\n  if (!overrides || overrides.length === 0) return undefined;\n  const factory = getAdapterFactory(adapter);\n  // A role facade can front more than one implementation class, and\n  // `constructor` names only one of them; match against every identity it\n  // declares so mocking either delegate intercepts.\n  const identities = adapterIdentities(adapter);\n  const matches = overrides.filter(\n    (o) =>\n      (factory !== undefined && o.target === factory) ||\n      identities.has(o.target),\n  );\n\n  // Resolve by ROLE, not by registration order. A mock that declares only the\n  // OTHER role must not answer this one: a source-only mock reached through\n  // `.enrich()` has no handler, so the fetched value would silently become\n  // undefined, and an enricher-only mock reached through `.from()` has no\n  // `source` behaviour, so the route would fall through to the real service in\n  // a test that reads as mocked. This bites on a multi-identity facade (mail's\n  // read side, where each delegate can carry its own override) and equally on\n  // a lone mock registered for one role and reached through the other.\n  //\n  // A mock declaring NEITHER behaviour is a different thing: the documented\n  // recording no-op, which must keep intercepting so `.to()` stays mocked\n  // rather than reaching the real destination. Hence the second pass instead\n  // of a single `o[role] !== undefined` filter.\n  return (\n    matches.find((o) => o[role] !== undefined) ??\n    matches.find((o) => o.source === undefined && o.send === undefined)\n  );\n}\n\n/**\n * Wrap a Source adapter so its `subscribe` is routed through the override's\n * `source` behaviour. The returned Source records calls on the override.\n *\n * If the override has no `source` behaviour, the original adapter is returned\n * unchanged (so that an override can stub only the destination side).\n *\n * @internal\n */\nexport function wrapSourceWithOverride<M = unknown>(\n  adapter: Source<M>,\n  override: AdapterOverride,\n): Source<M> {\n  if (!override.source) return adapter;\n  const args = getAdapterArgs(adapter) ?? [];\n  const behavior = override.source;\n\n  // Preserve the prototype chain so `instanceof` and inherited methods keep\n  // working on the wrapped source. Object.assign then copies the own\n  // enumerable properties; the non-enumerable factory tags are re-applied\n  // below so downstream tag lookups still resolve on the wrapper.\n  const wrapped = Object.assign(\n    Object.create(Object.getPrototypeOf(adapter) as object) as Source<M>,\n    adapter as object,\n  );\n  const factory = getAdapterFactory(adapter);\n  if (factory !== undefined) {\n    tagAdapter(wrapped as object, factory, args);\n  }\n\n  wrapped.subscribe = async function subscribe(sub): Promise<void> {\n    sub.ready();\n    const record: AdapterSourceCall = { args, yielded: 0 };\n    override.calls.source.push(record);\n\n    const values = typeof behavior === \"function\" ? behavior(args) : behavior;\n\n    // Dispatch all messages concurrently so `drain()` sees every handler\n    // in-flight before the subscribe resolves. A sequential emit would\n    // race against the drain/stop sequence and silently drop tail messages.\n    const pending: Promise<void>[] = [];\n    const dispatch = (message: unknown): void => {\n      if (sub.signal.aborted) return;\n      // A branded fixture carries its own headers (mirroring an\n      // envelope-carrying source); a plain fixture is delivered as the body.\n      const body = (isSourceFixture(message) ? message.body : message) as M;\n      const headers = isSourceFixture(message) ? message.headers : undefined;\n      pending.push(\n        sub\n          .emit({ message: body, ...(headers ? { headers } : {}) })\n          .then(() => {\n            record.yielded++;\n          }),\n      );\n    };\n\n    if (Array.isArray(values)) {\n      for (const message of values) dispatch(message);\n      await Promise.all(pending);\n      return;\n    }\n\n    for await (const message of values as\n      Iterable<unknown> | AsyncIterable<unknown>) {\n      if (sub.signal.aborted) break;\n      dispatch(message);\n    }\n    await Promise.all(pending);\n  };\n\n  return wrapped;\n}\n\n/**\n * Invoke an overridden destination/enricher adapter and record the call.\n * Returns the mock's result. For a fetch-resolved step (`.enrich()`, or a\n * fetch-only adapter in `.to()`) the caller uses it to replace the body; for\n * a send-resolved `.to()` the result is discarded (send is void).\n *\n * @internal\n */\nexport async function invokeSendOverride(\n  exchange: Exchange,\n  adapter: Adapter,\n  override: AdapterOverride,\n): Promise<unknown> {\n  const args = getAdapterArgs(adapter) ?? [];\n  const handler = override.send;\n\n  const snapshot: AdapterSendCall[\"exchange\"] = {\n    id: exchange.id,\n    body: snapshotBody(exchange.body),\n    headers: { ...exchange.headers },\n  };\n\n  const record: AdapterSendCall = {\n    args,\n    exchange: snapshot,\n    result: undefined,\n  };\n  override.calls.send.push(record);\n\n  if (!handler) return undefined;\n\n  // The call is already recorded above, so a rejection from `handler` still\n  // shows up in `calls.send` (with `result` undefined) and then propagates\n  // up the route pipeline the same way a real adapter failure would.\n  const result = await Promise.resolve(handler(exchange, { args }));\n  record.result = result;\n  return result;\n}\n","import type { ProcessingQueue } from \"./types.ts\";\nimport type { Exchange } from \"./exchange.ts\";\n\n/**\n * In-memory processing queue used internally by a route to pass messages from the source to the consumer.\n * Sources enqueue via `enqueue()`; the route sets a handler via `setHandler()` so each message is processed.\n * Intentionally minimal (no persistence, no backpressure); for advanced scenarios a custom ProcessingQueue can be used.\n */\nexport class InMemoryProcessingQueue<\n  T = unknown,\n> implements ProcessingQueue<T> {\n  private handler: ((message: T) => Promise<Exchange>) | undefined;\n  private buffer: T[] = [];\n\n  async enqueue(message: T): Promise<Exchange> {\n    if (!this.handler) {\n      this.buffer.push(message);\n      // Resolve immediately when no handler; tests don't use return value here\n      return Promise.resolve({} as Exchange);\n    }\n    return await this.handler(message);\n  }\n\n  setHandler(handler: (message: T) => Promise<Exchange>): Promise<void> | void {\n    this.handler = handler;\n\n    const q = this.buffer;\n    if (q.length > 0) {\n      const deliver = async () => {\n        while (q.length > 0) {\n          await handler(q.shift()!);\n        }\n      };\n      void deliver();\n      this.buffer = [];\n    }\n    return Promise.resolve();\n  }\n\n  clear(): Promise<void> {\n    this.handler = undefined;\n    this.buffer = [];\n    return Promise.resolve();\n  }\n}\n","import {\n  type Exchange,\n  HeadersKeys,\n  OperationType,\n  DefaultExchange,\n  EXCHANGE_INTERNALS,\n  emitExchangeDropped,\n  getExchangeContext,\n  getExchangeRoute,\n} from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { isRoutecraftError } from \"../brand.ts\";\nimport {\n  type OnParseError,\n  PARSE_DROPPED_REASON,\n} from \"../adapters/shared/parse.ts\";\nimport type { Adapter, Step } from \"../types.ts\";\nimport type { ResolvedCacheOptions } from \"../operations/cache-wrapper.ts\";\nimport {\n  ThrottleController,\n  throttleEmitHooks,\n  type ResolvedThrottleOptions,\n} from \"../operations/throttle-wrapper.ts\";\n\n/**\n * Synthetic pipeline steps the engine inserts around user steps: the\n * source-parse step and the route-scope cache check/store pair. Moved\n * verbatim from route.ts; these have zero coupling to DefaultRoute and\n * communicate only through the exchange and the step queue.\n */\n\n/**\n * Synthetic adapter used as the carrier for the parse step. Has no behaviour;\n * the step's `execute` does the work.\n */\nconst PARSE_STEP_ADAPTER: Adapter = { adapterId: \"routecraft.parse\" };\n\n/**\n * Build a synthetic pipeline step that runs a source-supplied parse function\n * against the exchange body. Inserted by `runPipeline` as the first step when a\n * source attaches `parse` to its message; this is what makes parse failures\n * observable as normal pipeline events (rather than aborting the source).\n * See #187.\n *\n * Behaviour on parse failure depends on `failureMode`:\n * - `\"fail\"` / `\"abort\"`: throw `RC5016` so `route:exchange:failed` fires (or the\n *   route's `.error()` handler recovers). The adapter's caller distinguishes\n *   `\"abort\"` by re-throwing the rejection out of subscribe.\n * - `\"drop\"`: emit `route:exchange:dropped` with `reason: \"parse-failed\"` (matching\n *   filter / validate drop semantics) and halt the pipeline cleanly without\n *   invoking `.error()`.\n *\n * When `applyValidation` is supplied, it runs immediately after a successful\n * parse so route-level `.input()` schemas validate the parsed body, not the\n * raw bytes. Validation failure throws out of `applyValidation` and is\n * handled by the step loop's catch path like any step error.\n *\n * The step manages its own `route:step:started` / `route:step:completed` /\n * `route:step:failed` events (`skipStepEvents: true`), so a drop can emit\n * `route:step:failed` followed by `route:exchange:dropped` without the route\n * loop double-emitting.\n */\nexport function buildParseStep(\n  parse: (raw: unknown) => unknown | Promise<unknown>,\n  failureMode: OnParseError,\n  applyValidation?: (exchange: Exchange) => Promise<Exchange>,\n): Step<Adapter> {\n  return {\n    operation: OperationType.PARSE,\n    label: \"parse\",\n    adapter: PARSE_STEP_ADAPTER,\n    skipStepEvents: true,\n    async execute(exchange) {\n      const internals = EXCHANGE_INTERNALS.get(exchange);\n      const context = internals?.context;\n      const route = internals?.route;\n      const routeId =\n        route?.definition.id ??\n        (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n      const stepStart = Date.now();\n\n      const emitStepStarted = () => {\n        context?.emit(\"route:step:started\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          operation: \"parse\",\n          adapter: \"parse\",\n        });\n      };\n      const emitStepCompleted = () => {\n        context?.emit(\"route:step:completed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          operation: \"parse\",\n          adapter: \"parse\",\n          duration: Date.now() - stepStart,\n        });\n      };\n      const emitStepFailed = (err: unknown) => {\n        context?.emit(\"route:step:failed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          operation: \"parse\",\n          adapter: \"parse\",\n          duration: Date.now() - stepStart,\n          error: err instanceof Error ? err.message : String(err),\n        });\n      };\n\n      emitStepStarted();\n\n      let parsed: Exchange;\n      try {\n        const parsedBody = await parse(exchange.body);\n        parsed = DefaultExchange.rewrap(exchange, { body: parsedBody });\n      } catch (cause) {\n        if (failureMode === \"drop\") {\n          // The parse threw, so the step itself failed: emit route:step:failed\n          // (honest about what happened), then route:exchange:dropped with a\n          // stable reason (carries the policy decision). Subscribers\n          // counting parse failures see route:step:failed; subscribers\n          // tracking drop policy see route:exchange:dropped.\n          emitStepFailed(cause);\n          emitExchangeDropped(context, {\n            routeId,\n            correlationId,\n            reason: PARSE_DROPPED_REASON,\n            exchange,\n          });\n          return { kind: \"drop\" } as const;\n        }\n        // 'fail' / 'abort': throw RC5016 so the step loop's catch path\n        // emits route:exchange:failed (or invokes the route's `.error()`).\n        emitStepFailed(cause);\n        const causeMessage =\n          cause instanceof Error ? cause.message : String(cause);\n        throw rcError(\"RC5016\", cause, {\n          message: `Source payload parse failed: ${causeMessage}`,\n        });\n      }\n\n      if (applyValidation) {\n        try {\n          parsed = await applyValidation(parsed);\n        } catch (cause) {\n          emitStepFailed(cause);\n          throw cause;\n        }\n      }\n\n      emitStepCompleted();\n      // Hand control back to the executor with the parsed exchange.\n      return { kind: \"continue\", exchange: parsed } as const;\n    },\n  };\n}\n\n/**\n * Synthetic adapter used as the carrier for the standalone input-validation\n * step. Has no behaviour; the step's `execute` does the work.\n */\nconst INPUT_STEP_ADAPTER: Adapter = { adapterId: \"routecraft.input\" };\n\n/**\n * Build the synthetic `input` chain step (pre-from chain position #4).\n * Inserted by `runPipeline` when the route has `.input()` schemas and the\n * source did NOT attach a parser; with a parser the validator runs inside\n * the parse step instead (position #3 and #4 collapse into one step, since\n * input must validate the parsed body). Either way the validation failure\n * throws `RC5065` into the step loop's catch path, so it is routable\n * through the route-scope `.error()` handler (chain position #1) exactly\n * like `RC5012` / `RC5015` / `RC5016` from the other deterministic gates.\n * See #447 for the fold that replaced the old eager consumer-handler path.\n *\n * The step manages its own lifecycle events (`skipStepEvents: true`),\n * mirroring the parse step: subscribers see `operation: \"input\"` and\n * `adapter: \"input\"` on the payloads. (The carrier's `routecraft.input`\n * adapter id is not what reaches subscribers, exactly as the parse step\n * emits `adapter: \"parse\"` rather than `routecraft.parse`.)\n */\nexport function buildInputValidationStep(\n  applyValidation: (exchange: Exchange) => Promise<Exchange>,\n): Step<Adapter> {\n  return {\n    operation: OperationType.VALIDATE,\n    label: \"input\",\n    adapter: INPUT_STEP_ADAPTER,\n    skipStepEvents: true,\n    async execute(exchange) {\n      const internals = EXCHANGE_INTERNALS.get(exchange);\n      const context = internals?.context;\n      const route = internals?.route;\n      const routeId =\n        route?.definition.id ??\n        (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n      const stepStart = Date.now();\n\n      context?.emit(\"route:step:started\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: \"input\",\n        adapter: \"input\",\n      });\n\n      let validated: Exchange;\n      try {\n        validated = await applyValidation(exchange);\n      } catch (cause) {\n        context?.emit(\"route:step:failed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          operation: \"input\",\n          adapter: \"input\",\n          duration: Date.now() - stepStart,\n          error: cause instanceof Error ? cause.message : String(cause),\n        });\n        throw cause;\n      }\n\n      context?.emit(\"route:step:completed\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: \"input\",\n        adapter: \"input\",\n        duration: Date.now() - stepStart,\n      });\n      return { kind: \"continue\", exchange: validated } as const;\n    },\n  };\n}\n\n/**\n * Synthetic adapter carriers for the route-scope cache filter steps.\n * Distinct adapter ids per filter so telemetry / event subscribers\n * correlating by `adapter` can tell read failures (`cache.check`) from\n * write failures (`cache.store`) without parsing the step label.\n * Neither carrier has behaviour; the steps' `execute` does the work.\n */\nconst CACHE_CHECK_STEP_ADAPTER: Adapter = {\n  adapterId: \"routecraft.cache.check\",\n};\nconst CACHE_STORE_STEP_ADAPTER: Adapter = {\n  adapterId: \"routecraft.cache.store\",\n};\n\n/**\n * Build the route-scope cache HIT-CHECK synthetic step. Inserted into\n * `initialSteps` AFTER `buildParseStep` (so parse + `applyValidation`\n * have already run) and BEFORE the user steps. Derives the cache key\n * from the parsed/validated exchange (the default key is namespaced by\n * route id and principal), looks it up in the provider, and\n * on a hit pushes a rewrapped exchange with `steps: []` to short-circuit\n * the rest of the pipeline (including the matching cache-store step).\n * On a miss pushes the exchange with the unchanged `remainingSteps` so\n * the user pipeline runs.\n *\n * Manages its own observability: emits `route:cache:hit` / `route:cache:miss` /\n * `route:cache:failed` plus `route:exchange:restored` on a hit. `skipStepEvents:\n * true` keeps `runPipeline` from emitting generic `route:step:started` /\n * `route:step:completed` for this internal step.\n *\n * @internal Exported only so `RouteBuilder.from()` can assemble it into\n * `RouteDefinition.postParseFilters`. Not part of the public API; the\n * signature may change without notice.\n */\nexport function buildCacheCheckStep(\n  cacheConfig: ResolvedCacheOptions,\n): Step<Adapter> {\n  return {\n    operation: OperationType.PROCESS,\n    label: \"cache-check\",\n    adapter: CACHE_CHECK_STEP_ADAPTER,\n    skipStepEvents: true,\n    async execute(exchange) {\n      const internals = EXCHANGE_INTERNALS.get(exchange);\n      const context = internals?.context;\n      const route = internals?.route;\n      const routeId =\n        route?.definition.id ??\n        (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n\n      let key: string;\n      try {\n        const pipeline = route?.definition.cachePipeline;\n        if (pipeline === undefined) {\n          throw rcError(\"RC5029\", undefined, {\n            message:\n              \"This route-scope .cache() is not part of a built route, so the pipeline its key covers is unknown. Build the route through craft()...build() rather than assembling a RouteDefinition by hand.\",\n          });\n        }\n        key = cacheConfig.key(exchange, { kind: \"route\", routeId, pipeline });\n      } catch (err) {\n        context?.emit(\"route:cache:failed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          stepLabel: \"route\",\n          scope: \"route\",\n          phase: \"key\",\n          error: err instanceof Error ? err.message : String(err),\n        });\n        throw isRoutecraftError(err)\n          ? err\n          : rcError(\"RC5029\", err, {\n              message: `Route-scope .cache({ key }) for \"${routeId}\" threw while deriving the cache key`,\n            });\n      }\n      // Hand the key off to the matching cache-store filter via\n      // exchange internals. Internals is the framework's per-exchange\n      // state bag set at construction time; absence here means the\n      // caller built an exchange outside `DefaultExchange.rewrap`,\n      // which violates the contract. Fail loudly rather than silently\n      // skip the cache write at the tail of the pipeline.\n      if (!internals) {\n        throw rcError(\"RC5028\", undefined, {\n          message: `Route-scope .cache() for \"${routeId}\" ran on an exchange without framework internals; cache key cannot be propagated to the store step. This indicates an adapter or step constructed an Exchange outside DefaultExchange.rewrap.`,\n        });\n      }\n      internals.cacheKey = key;\n\n      let cached: unknown;\n      try {\n        cached = await cacheConfig.provider.get(key);\n      } catch (err) {\n        context?.emit(\"route:cache:failed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          stepLabel: \"route\",\n          scope: \"route\",\n          phase: \"get\",\n          key,\n          error: err instanceof Error ? err.message : String(err),\n        });\n        throw isRoutecraftError(err)\n          ? err\n          : rcError(\"RC5028\", err, {\n              message: `Route-scope .cache() provider read failed for \"${routeId}\"`,\n            });\n      }\n\n      if (cached !== undefined) {\n        // HIT: short-circuit the pipeline by pushing the rewrapped\n        // exchange with no remaining steps. The matching cache-store\n        // step (tail of initialSteps) is therefore skipped too.\n        context?.emit(\"route:cache:hit\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          stepLabel: \"route\",\n          scope: \"route\",\n          key,\n        });\n        context?.emit(\"route:exchange:restored\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          source: \"cache\",\n        });\n        // Complete: skip the rest of the pipeline (including the matching\n        // cache-store step) and finish the exchange with the cached body.\n        return {\n          kind: \"complete\",\n          exchange: DefaultExchange.rewrap(exchange, { body: cached }),\n        } as const;\n      }\n\n      // MISS: continue the pipeline.\n      context?.emit(\"route:cache:miss\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        stepLabel: \"route\",\n        scope: \"route\",\n        key,\n      });\n      return { kind: \"continue\", exchange } as const;\n    },\n  };\n}\n\n/**\n * Build the route-scope cache STORE synthetic step. Inserted as the\n * tail of `initialSteps` after the user steps. Reached only on the\n * miss path (the cache-check step pushes `steps: []` on a hit to skip\n * everything including this step). Writes the terminal body using the\n * key captured by the matching check step.\n *\n * Provider write failures emit `route:cache:failed phase:\"set\"` for\n * observability but do NOT fail the exchange: the result was already\n * computed by the user pipeline. This diverges from step-scope, where\n * a write failure throws RC5028; the divergence is intentional and\n * documented on the operation reference page.\n *\n * `skipStepEvents: true` keeps `runPipeline` from emitting generic\n * lifecycle events for this internal step.\n *\n * @internal Exported only so `RouteBuilder.from()` can assemble it into\n * `RouteDefinition.postFromFilters`. Not part of the public API; the\n * signature may change without notice.\n */\nexport function buildCacheStoreStep(\n  cacheConfig: ResolvedCacheOptions,\n): Step<Adapter> {\n  return {\n    operation: OperationType.PROCESS,\n    label: \"cache-store\",\n    adapter: CACHE_STORE_STEP_ADAPTER,\n    skipStepEvents: true,\n    async execute(exchange) {\n      const internals = EXCHANGE_INTERNALS.get(exchange);\n      const context = internals?.context;\n      const route = internals?.route;\n      const routeId =\n        route?.definition.id ??\n        (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n      const key = internals?.cacheKey;\n\n      // Only cache successful runs whose terminal body is not\n      // `undefined`. `null` is cached (envelope handles it). Dropped\n      // exchanges never reach this step because the queue loop stops\n      // pushing on a drop.\n      if (key !== undefined && exchange.body !== undefined) {\n        try {\n          await cacheConfig.provider.set(key, exchange.body, cacheConfig.ttl);\n          context?.emit(\"route:cache:stored\", {\n            routeId,\n            exchangeId: exchange.id,\n            correlationId,\n            stepLabel: \"route\",\n            scope: \"route\",\n            key,\n            ...(cacheConfig.ttl !== undefined ? { ttl: cacheConfig.ttl } : {}),\n          });\n        } catch (err) {\n          context?.emit(\"route:cache:failed\", {\n            routeId,\n            exchangeId: exchange.id,\n            correlationId,\n            stepLabel: \"route\",\n            scope: \"route\",\n            phase: \"set\",\n            key,\n            error: err instanceof Error ? err.message : String(err),\n          });\n        }\n      }\n      return { kind: \"continue\", exchange } as const;\n    },\n  };\n}\n\n/**\n * Synthetic adapter carrier for the route-scope throttle gate. Distinct\n * id so telemetry correlating by `adapter` can tell route-scope rate\n * limiting apart from the user pipeline. No behaviour; the step's\n * `execute` does the work.\n */\nconst THROTTLE_CHECK_STEP_ADAPTER: Adapter = {\n  adapterId: \"routecraft.throttle\",\n};\n\n/**\n * Build a route-scope `.throttle()` gate (pre-from chain position #5).\n * Acquires a token from the route's limiter, pacing the exchange when\n * the bucket is empty, then continues the pipeline unchanged. It still\n * runs before the cache check, so a paced request does not consume a\n * cache lookup until it is admitted.\n *\n * Unlike `.retry()` / `.timeout()`, throttle does not scope OVER the\n * chain tail (it neither re-runs nor bounds it): it is a one-shot gate.\n * Because it must sit OUTSIDE the retry / timeout segments (which wrap\n * `postParseFilters`), it rides on the dedicated `RouteDefinition.throttle`\n * field rather than in `postParseFilters`; the executor prepends it to\n * the tail AFTER those segments wrap, so a retried attempt re-runs only\n * the tail below it and never re-acquires a token. Multiple `.throttle()`\n * calls produce multiple gates that all must admit the exchange.\n *\n * The {@link ThrottleController} keys its buckets by Route, so the same\n * definition registered into several contexts gives each Route its own\n * limiter rather than one shared bucket. Reading route/context through\n * `getExchangeRoute`/`getExchangeContext` (symbol-first, cross-instance\n * safe) keeps the gate consistent with the step-scope wrapper. Emits the\n * `route:throttle:*` family with `scope: \"route\"`. `skipStepEvents: true`\n * keeps `runPipeline` from emitting generic lifecycle events for this\n * internal step.\n *\n * @internal Exported only so `RouteBuilder.from()` can assemble it onto\n * `RouteDefinition.throttle`. Not part of the public API; the signature\n * may change without notice.\n */\nexport function buildThrottleCheckStep(\n  options: ResolvedThrottleOptions,\n): Step<Adapter> {\n  const controller = new ThrottleController(options);\n  return {\n    operation: OperationType.THROTTLE,\n    label: \"throttle\",\n    adapter: THROTTLE_CHECK_STEP_ADAPTER,\n    skipStepEvents: true,\n    async execute(exchange) {\n      const route = getExchangeRoute(exchange);\n      const context = getExchangeContext(exchange);\n      const routeId =\n        route?.definition.id ??\n        (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n      const scoped = {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        stepLabel: \"route\",\n        scope: \"route\" as const,\n        ...(controller.label !== undefined ? { label: controller.label } : {}),\n      };\n\n      await controller.acquire(exchange, route, {\n        // Intake: a pacing gap is idle time, and cutting it short at the\n        // start of shutdown still runs the exchange.\n        ...(route ? { signal: route.intakeSignal } : {}),\n        ...throttleEmitHooks(context, scoped, true),\n      });\n\n      return { kind: \"continue\", exchange } as const;\n    },\n  };\n}\n","/**\n * How a source adapter handles a parse failure on an individual item.\n *\n * Source adapters that translate raw bytes into a structured body (json,\n * html, csv, jsonl, mail) accept this option to control what happens when\n * the parse step throws.\n *\n * All three modes are observable via the events bus, mirroring the\n * filter / validate operation patterns:\n *\n * | Mode    | Lifecycle events fired                       |\n * |---------|----------------------------------------------|\n * | `fail`  | `route:exchange:started` -> `route:exchange:failed` (or `route:error:caught` if `.error()` recovers) |\n * | `abort` | `route:exchange:started` -> `route:exchange:failed`, then `context:error` and the source dies |\n * | `drop`  | `route:exchange:started` -> `route:exchange:dropped` (`reason: \"parse-failed\"`) |\n *\n * adopt the contract.\n */\nexport type OnParseError =\n  /**\n   * Default. The exchange fails: the route's `.error()` handler is invoked\n   * with an `RC5016` error, or `route:exchange:failed` is emitted when no handler\n   * is set. Streaming adapters continue to the next item.\n   *\n   * Use when you want parse failures to be observable per item and the rest\n   * of the source to keep flowing.\n   */\n  | \"fail\"\n  /**\n   * The source aborts on the first parse failure. The bad item still emits\n   * `route:exchange:started` -> `route:exchange:failed` for per-item observability;\n   * then the source's subscribe promise rejects and `context:error` fires.\n   *\n   * Use when partial-data is unacceptable and a malformed item should stop\n   * the import (atomic-load semantics).\n   */\n  | \"abort\"\n  /**\n   * The parse failure is dropped from the pipeline. The synthetic parse\n   * step emits `route:exchange:started` -> `route:exchange:dropped` with\n   * `reason: \"parse-failed\"` (matching `filter` / `validate` drop\n   * semantics). Streaming adapters continue to the next item; no\n   * `route:exchange:failed` and no `.error()` handler invocation.\n   *\n   * Use when malformed items are expected (scraping, lossy upstreams) and\n   * you want them counted in `route:exchange:dropped` metrics rather than\n   * surfaced as route errors.\n   */\n  | \"drop\";\n\n/**\n * Default `OnParseError` value applied when a parsing adapter does not set\n * one explicitly.\n */\nexport const DEFAULT_ON_PARSE_ERROR: OnParseError = \"fail\";\n\n/**\n * Reason string emitted on `route:exchange:dropped` when an `onParseError: 'drop'`\n * source rejects a malformed item. Stable so subscribers can filter:\n *\n * ```ts\n * ctx.on('route:exchange:dropped', ({ details }) => {\n *   if (details.reason === PARSE_DROPPED_REASON) metrics.increment('parse.dropped');\n * });\n * ```\n */\nexport const PARSE_DROPPED_REASON = \"parse-failed\";\n\n/**\n * True if `err` is a Routecraft `RC5016` parse-failure error. Used by\n * source adapters in `'abort'` mode to discriminate between parse failures\n * (which should abort the source) and downstream pipeline failures\n * (destination errors, transform errors, etc.) that should NOT abort -\n * `'abort'` is documented as parse-specific behaviour.\n *\n * Mirrors the `isMailParseError` helper in the mail adapter.\n */\nexport function isParseError(err: unknown): boolean {\n  return (\n    typeof err === \"object\" &&\n    err !== null &&\n    (err as { rc?: unknown }).rc === \"RC5016\"\n  );\n}\n","import { LRUCache } from \"lru-cache\";\nimport type { Exchange } from \"../exchange.ts\";\nimport { type Duration, parseDuration } from \"../shared/duration.ts\";\nimport { rcError } from \"../error.ts\";\nimport type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport type { CraftContext } from \"../context.ts\";\nimport type { Route } from \"../route.ts\";\nimport { WrapperStep } from \"./wrapper.ts\";\nimport { wrapperEventScope } from \"./event-scope.ts\";\nimport { cancellableSleep, SleepAbortedError } from \"./cancellable-sleep.ts\";\nimport { DEFAULT_MAX_KEYS, validateMaxKeys } from \"./max-keys.ts\";\nimport { RouteScopedController } from \"./route-scoped-controller.ts\";\n\n/**\n * Time window a `.throttle()` rate is measured over.\n *\n * Longer quota windows (week / month) are intentionally absent: this is\n * an IN-MEMORY limiter, so its state resets on process restart and is\n * not shared across instances. That is fine for second-to-day smoothing\n * but unsafe for a durable \"N per month\" quota, which needs persistent,\n * shared storage (a separate feature).\n */\nexport type ThrottleTimeUnit = \"second\" | \"minute\" | \"hour\" | \"day\";\n\nconst WINDOW_MS: Record<ThrottleTimeUnit, number> = {\n  second: 1000,\n  minute: 60_000,\n  hour: 3_600_000,\n  day: 86_400_000,\n};\n\n/**\n * Resolve the `per` window to milliseconds.\n *\n * The unit words are checked first, so they keep their exact meaning and\n * never reach the duration grammar (where `\"minute\"` would be a parse\n * error). Everything else is an ordinary {@link Duration}, which is what\n * makes `per: \"90s\"` expressible at all.\n *\n * @internal\n */\nfunction resolveWindow(per: ThrottleTimeUnit | Duration): number {\n  // `hasOwn`, not `in`: `per: \"constructor\"` resolves through the prototype\n  // chain, and the resulting `rate / undefined` is a NaN refill rate, which\n  // is a limiter that never admits anything and never errors.\n  if (typeof per === \"string\" && Object.hasOwn(WINDOW_MS, per)) {\n    return WINDOW_MS[per as ThrottleTimeUnit];\n  }\n  try {\n    return parseDuration(per as Duration, \"throttle({ per })\");\n  } catch {\n    // The duration grammar is the wrong thing to quote at someone who\n    // mistyped a unit word, which is the likelier mistake now that both\n    // forms are accepted. Name both vocabularies.\n    throw rcError(\"RC5003\", undefined, {\n      message: `throttle({ per }) must be one of ${Object.keys(WINDOW_MS)\n        .map((u) => `\"${u}\"`)\n        .join(\", \")}, or a duration like \"90s\"; got ${String(per)}.`,\n    });\n  }\n}\n\n/**\n * `setTimeout`'s maximum delay; a larger value is coerced to ~1ms and\n * fires immediately. The pacing wait is clamped to this so an extreme\n * backlog still waits (rather than being admitted instantly, which would\n * break the rate guarantee precisely under heavy backpressure).\n */\nconst MAX_TIMER_MS = 2_147_483_647;\n\n/**\n * Options for the `.throttle()` wrapper (step scope and route scope).\n */\nexport interface ThrottleOptions {\n  /** Allowed requests per `per` window. Must be a finite number > 0. */\n  rate: number;\n  /**\n   * Time window the `rate` is measured over. Default `\"second\"`.\n   *\n   * A unit word (`\"minute\"`) reads best for the common case; a\n   * {@link Duration} covers windows a unit word cannot name, such as\n   * `\"90s\"`. Note that a BARE NUMBER is milliseconds, as everywhere else a\n   * `Duration` is accepted: `per: 60` is 60ms, not a minute. Write\n   * `per: \"60s\"` (or `per: \"minute\"`) for that.\n   */\n  per?: ThrottleTimeUnit | Duration;\n  /**\n   * Behaviour when an exchange exceeds the rate:\n   * - `\"delay\"` (default): pace it, waiting until a token frees. Smooths\n   *   bursty traffic into a steady rate; never drops an exchange.\n   * - `\"reject\"`: throw `RC5013` immediately so the caller fails fast\n   *   (e.g. a source returns 429) instead of being buffered. Avoids the\n   *   unbounded in-flight growth that delay can accumulate under a fast\n   *   source. A rejected exchange does NOT consume a token.\n   */\n  mode?: \"delay\" | \"reject\";\n  /**\n   * Burst allowance: the most calls admitted back-to-back after an idle\n   * window before pacing kicks in (the token bucket's capacity). Default\n   * is `rate` (one window's worth). Set it lower for stricter pacing, or\n   * higher to tolerate spikes. Decoupled from `per`, so `{ rate: 600,\n   * per: \"minute\" }` does not silently allow a 600-wide burst unless you\n   * ask for it.\n   */\n  burst?: number;\n  /**\n   * Partition the limit: each distinct key gets its own independent\n   * bucket, so you can rate-limit per user, per IP, per tenant, etc.\n   * Omit for a single bucket shared across the whole route (a global\n   * limit). The selector runs once per exchange and MUST return a\n   * string; coalesce missing values (e.g. `?? \"anonymous\"`). A selector\n   * that throws fails the exchange (it is user code, like a transform),\n   * so guard it rather than relying on the never-drops contract.\n   *\n   * @example Per authenticated principal\n   * ```ts\n   * .throttle({ rate: 10, key: (ex) => ex.principal?.subject ?? \"anonymous\" })\n   * ```\n   */\n  key?: (exchange: Exchange) => string;\n  /**\n   * Maximum number of distinct keys to track concurrently when `key` is\n   * set. The per-key buckets live in an LRU, so memory stays bounded\n   * even with an unbounded key space (the least-recently-used key's\n   * bucket is evicted and resets when it next appears). Default\n   * `10_000`. Ignored when `key` is not set.\n   */\n  maxKeys?: number;\n  /**\n   * Optional label carried on this throttle's `route:throttle:*` events,\n   * so stacked gates (e.g. a global limit plus a per-IP limit) can be\n   * told apart in logs and metrics. Has no effect on behaviour.\n   */\n  label?: string;\n}\n\n/**\n * {@link ThrottleOptions} normalised to what the limiter needs. Staged\n * on the builder's pending options for route-scope `.throttle()`.\n *\n * @internal\n */\nexport interface ResolvedThrottleOptions {\n  /** Token bucket capacity (burst allowance). */\n  capacity: number;\n  /** Tokens replenished per millisecond (`rate / windowMs`). */\n  refillPerMs: number;\n  /** On-limit behaviour. */\n  mode: \"delay\" | \"reject\";\n  /** Per-exchange partition selector; absent means a single shared bucket. */\n  key?: (exchange: Exchange) => string;\n  /** LRU cap on distinct keys (only meaningful when `key` is set). */\n  maxKeys: number;\n  /** Optional label for `route:throttle:*` events. */\n  label?: string;\n}\n\n/**\n * Validate user-supplied {@link ThrottleOptions} into a\n * {@link ResolvedThrottleOptions}. Rejects at build time so a typo fails\n * when the route is built rather than silently never (or always)\n * admitting at runtime.\n *\n * @internal\n */\nexport function resolveThrottleOptions(\n  options: ThrottleOptions,\n): ResolvedThrottleOptions {\n  const {\n    rate,\n    per = \"second\",\n    mode = \"delay\",\n    burst,\n    key,\n    maxKeys = DEFAULT_MAX_KEYS,\n    label,\n  } = options;\n\n  if (mode !== \"delay\" && mode !== \"reject\") {\n    throw rcError(\"RC5003\", undefined, {\n      message: `throttle({ mode }) must be \"delay\" or \"reject\", got ${String(mode)}.`,\n    });\n  }\n  if (!Number.isFinite(rate) || rate <= 0) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `throttle({ rate }) must be a finite number > 0, got ${String(rate)}.`,\n    });\n  }\n  const windowMs = resolveWindow(per);\n  if (burst !== undefined && (!Number.isFinite(burst) || burst <= 0)) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `throttle({ burst }) must be a finite number > 0, got ${String(burst)}.`,\n    });\n  }\n  // Upper-bound `maxKeys`: the per-key LRU pre-allocates index arrays\n  // sized to `max` at construction, so an \"effectively unlimited\" value\n  // would OOM the process the moment the limiter is built, not gradually.\n  validateMaxKeys(\"throttle\", maxKeys);\n\n  return {\n    // Capacity floors at 1 so a sub-1 rate (or an accidental sub-1\n    // `burst`) still admits the first call immediately instead of pacing\n    // every exchange.\n    capacity: Math.max(1, burst ?? rate),\n    refillPerMs: rate / windowMs,\n    mode,\n    ...(key ? { key } : {}),\n    maxKeys,\n    ...(label !== undefined ? { label } : {}),\n  };\n}\n\n/**\n * Lazy-refill token bucket. `reserve()` is synchronous, so under the\n * single-threaded event loop a batch of concurrent exchanges each takes\n * a distinct slot in the same tick and their waits stack deterministically\n * (FIFO-fair, never exceeding the configured rate).\n *\n * Tokens are allowed to go negative: a caller that finds the bucket\n * empty still decrements, which reserves a slot further in the future\n * for the next caller. That is what makes concurrent waits queue\n * instead of all racing for the same single token.\n *\n * @internal\n */\nexport class TokenBucket {\n  #tokens: number;\n  #lastRefillAt: number;\n  readonly #capacity: number;\n  readonly #refillPerMs: number;\n\n  constructor(\n    { capacity, refillPerMs }: ResolvedThrottleOptions,\n    now: number = Date.now(),\n  ) {\n    this.#capacity = capacity;\n    this.#refillPerMs = refillPerMs;\n    // Start full so the first burst (up to `capacity`) is admitted\n    // without an initial wait.\n    this.#tokens = capacity;\n    this.#lastRefillAt = now;\n  }\n\n  /**\n   * Reserve one token for the calling exchange and return how long it\n   * must wait (ms) before that token is available. `0` means a token was\n   * free immediately.\n   */\n  reserve(now: number = Date.now()): number {\n    // Clamp at 0: a backward wall-clock step (NTP / DST / manual) must\n    // not subtract tokens, which would over-pace the next callers.\n    const elapsed = Math.max(0, now - this.#lastRefillAt);\n    this.#tokens = Math.min(\n      this.#capacity,\n      this.#tokens + elapsed * this.#refillPerMs,\n    );\n    this.#lastRefillAt = now;\n\n    // Decrement once, then derive the wait from any resulting deficit.\n    this.#tokens -= 1;\n    if (this.#tokens >= 0) return 0;\n    const waitMs = -this.#tokens / this.#refillPerMs;\n    // Cap at the timer ceiling so a huge backlog still waits instead of\n    // being coerced to ~1ms by setTimeout and admitted immediately.\n    return Math.min(waitMs, MAX_TIMER_MS);\n  }\n\n  /**\n   * Reject-mode acquire: take a token only if one is available right now.\n   * Returns `0` when admitted; otherwise the time (ms) until a token\n   * would free, WITHOUT consuming one (a rejected request must not drive\n   * the bucket negative or it would penalise later conforming calls).\n   */\n  tryAcquire(now: number = Date.now()): number {\n    const elapsed = Math.max(0, now - this.#lastRefillAt);\n    this.#tokens = Math.min(\n      this.#capacity,\n      this.#tokens + elapsed * this.#refillPerMs,\n    );\n    this.#lastRefillAt = now;\n\n    if (this.#tokens >= 1) {\n      this.#tokens -= 1;\n      return 0;\n    }\n    return (1 - this.#tokens) / this.#refillPerMs;\n  }\n}\n\n/**\n * Per-route rate-limiter state for one `.throttle()`. Holds a single\n * shared {@link TokenBucket} when unkeyed, or an LRU of per-key buckets\n * when a `key` selector is configured. One instance per Route (see\n * {@link ThrottleController}), never one per exchange.\n *\n * @internal\n */\nexport class ThrottleLimiter {\n  readonly #options: ResolvedThrottleOptions;\n  #single?: TokenBucket;\n  readonly #keyed?: LRUCache<string, TokenBucket>;\n\n  constructor(options: ResolvedThrottleOptions) {\n    this.#options = options;\n    if (options.key) {\n      // Idle keys are dropped once their bucket would have refilled to\n      // full: a full bucket is indistinguishable from a fresh one, so a\n      // returning key just rebuilds an identical full bucket. `ttl` =\n      // refill-to-full FROM EMPTY; `updateAgeOnGet` makes it \"idle since\n      // last use\". A bucket driven negative (heavy backlog) needs longer\n      // than `ttl` to truly reach full, so evicting it at `ttl` can\n      // forgive a little unpaid debt and grant the returning key an early\n      // burst -- a bounded, self-correcting over-admit at the eviction\n      // boundary, accepted as the price of cheap memory reclamation.\n      // `max` is the hard ceiling for a flood of distinct keys WITHIN one\n      // ttl window (e.g. random-IP abuse), so memory stays bounded.\n      const ttl = Math.max(\n        1,\n        Math.ceil(options.capacity / options.refillPerMs),\n      );\n      this.#keyed = new LRUCache<string, TokenBucket>({\n        max: options.maxKeys,\n        ttl,\n        updateAgeOnGet: true,\n      });\n    }\n  }\n\n  /**\n   * Resolve the {@link TokenBucket} for `exchange` (the shared one, or\n   * the per-key one, creating it on first use), plus the partition key it\n   * belongs to (absent when unkeyed). The caller decides whether to\n   * `reserve` (delay) or `tryAcquire` (reject) against it.\n   */\n  bucketFor(\n    exchange: Exchange,\n    now: number,\n  ): { bucket: TokenBucket; key?: string } {\n    if (!this.#options.key) {\n      this.#single ??= new TokenBucket(this.#options, now);\n      return { bucket: this.#single };\n    }\n    let key: string;\n    try {\n      key = this.#options.key(exchange);\n    } catch (err) {\n      // The selector is user code; surface a clear, actionable error\n      // rather than a generic step failure. Throttle's \"only ever\n      // delays\" contract covers the rate mechanism, not a throwing key\n      // selector (use a fallback such as `?? \"anonymous\"`).\n      throw rcError(\"RC5003\", err, {\n        message:\n          'throttle({ key }) selector threw; it must return a string for every exchange (e.g. coalesce a missing value with `?? \"anonymous\"`).',\n      });\n    }\n    let bucket = this.#keyed!.get(key);\n    if (!bucket) {\n      bucket = new TokenBucket(this.#options, now);\n      this.#keyed!.set(key, bucket);\n    }\n    return { bucket, key };\n  }\n}\n\n/**\n * Lifecycle hooks the throttle gate reports to, so the step-scope\n * wrapper and the route-scope filter emit the same `route:throttle:*`\n * events with their own `scope` / `stepLabel` bindings.\n *\n * @internal\n */\nexport interface ThrottleHooks {\n  /** Route intake signal; cuts the pacing wait short once shutdown begins. */\n  signal?: AbortSignal;\n  /** A token was not free; the exchange will wait `waitMs` before admission. */\n  onDelayed(waitMs: number, key?: string): void;\n  /**\n   * The exchange is admitted. `waited` is true when it had to pace;\n   * `elapsed` is the total time spent in the gate; `key` is the partition\n   * it was charged against (absent when unkeyed).\n   */\n  onPassed(waited: boolean, elapsed: number, key?: string): void;\n  /**\n   * Reject-mode only: the exchange exceeded the rate and is being failed.\n   * `retryAfterMs` is how long until a token would free.\n   */\n  onRejected(retryAfterMs: number, key?: string): void;\n}\n\n/** Event-scope bindings shared by the `route:throttle:*` payloads. */\nexport interface ThrottleEventScope {\n  routeId: string;\n  exchangeId: string;\n  correlationId: string;\n  stepLabel: string;\n  scope: \"route\" | \"step\";\n  /** Optional gate label, when configured. */\n  label?: string;\n}\n\n/**\n * Build the `onDelayed` / `onPassed` half of {@link ThrottleHooks} that\n * emits the `route:throttle:*` events. Shared by the step-scope wrapper\n * and the route-scope gate so the event payload shape lives in one place\n * (only the `scoped` descriptor and the `emit` guard differ between\n * them). `context?.emit` no-ops when the exchange carries no context.\n *\n * @internal\n */\nexport function throttleEmitHooks(\n  context: CraftContext | undefined,\n  scoped: ThrottleEventScope,\n  emit: boolean,\n): Pick<ThrottleHooks, \"onDelayed\" | \"onPassed\" | \"onRejected\"> {\n  return {\n    onDelayed: (waitMs, key) => {\n      if (emit) {\n        context?.emit(\"route:throttle:delayed\", {\n          ...scoped,\n          waitMs,\n          ...(key !== undefined ? { key } : {}),\n        });\n      }\n    },\n    onPassed: (waited, elapsed, key) => {\n      if (emit) {\n        context?.emit(\"route:throttle:passed\", {\n          ...scoped,\n          waited,\n          elapsed,\n          ...(key !== undefined ? { key } : {}),\n        });\n      }\n    },\n    onRejected: (retryAfterMs, key) => {\n      if (emit) {\n        context?.emit(\"route:throttle:rejected\", {\n          ...scoped,\n          retryAfterMs,\n          ...(key !== undefined ? { key } : {}),\n        });\n      }\n    },\n  };\n}\n\n/**\n * Owns the rate-limiter state for one `.throttle()` across every Route\n * the enclosing step runs in. Keyed by Route in a WeakMap, so a single\n * step instance or gate closure shared by a `RouteDefinition` registered\n * into multiple contexts gives each Route its OWN limiter rather than\n * one shared bucket (which would let the contexts cross-rate-limit).\n *\n * @internal\n */\nexport class ThrottleController extends RouteScopedController<ThrottleLimiter> {\n  readonly #options: ResolvedThrottleOptions;\n\n  constructor(options: ResolvedThrottleOptions) {\n    super();\n    this.#options = options;\n  }\n\n  /** Optional gate label, surfaced on the `route:throttle:*` events. */\n  get label(): string | undefined {\n    return this.#options.label;\n  }\n\n  protected createState(): ThrottleLimiter {\n    return new ThrottleLimiter(this.#options);\n  }\n\n  /**\n   * Acquire a slot. In `delay` mode (default) the caller is paced when\n   * the bucket is empty; the pacing wait is cancellable, so on route\n   * shutdown the exchange is admitted rather than dropped. In `reject`\n   * mode an over-limit exchange is failed fast with `RC5013` (and a\n   * `route:throttle:rejected` event) without consuming a token.\n   */\n  async acquire(\n    exchange: Exchange,\n    route: Route | undefined,\n    hooks: ThrottleHooks,\n  ): Promise<void> {\n    const start = Date.now();\n    const { bucket, key } = this.stateFor(route).bucketFor(exchange, start);\n\n    if (this.#options.mode === \"reject\") {\n      const retryAfterMs = bucket.tryAcquire(start);\n      if (retryAfterMs <= 0) {\n        hooks.onPassed(false, 0, key);\n        return;\n      }\n      hooks.onRejected(retryAfterMs, key);\n      throw rcError(\"RC5013\", undefined, {\n        message: `throttle rejected the exchange: rate limit exceeded${\n          key !== undefined ? ` for key \"${key}\"` : \"\"\n        }. Retry after ~${Math.ceil(retryAfterMs)}ms.`,\n      });\n    }\n\n    const waitMs = bucket.reserve(start);\n    if (waitMs <= 0) {\n      hooks.onPassed(false, 0, key);\n      return;\n    }\n    hooks.onDelayed(waitMs, key);\n    try {\n      await cancellableSleep(waitMs, hooks.signal);\n    } catch (err) {\n      if (!(err instanceof SleepAbortedError)) throw err;\n      // Route shutdown: stop pacing and admit the exchange so teardown\n      // does not silently drop it.\n    }\n    hooks.onPassed(true, Date.now() - start, key);\n  }\n}\n\n/**\n * Step-scope `.throttle()` wrapper. Rate-limits the wrapped step to a\n * fixed number of calls per time window, pacing exchanges that exceed\n * the rate (backpressure) rather than dropping them.\n *\n * The limiter state lives on a {@link ThrottleController} held on the\n * wrapper instance. The builder constructs one wrapper instance per\n * route at build time, but the controller keys its buckets by Route, so\n * every exchange on a given Route shares one limiter while distinct\n * Routes (even built from the same definition) stay isolated. This is\n * the deliberate exception to the `WrapperStep` rule against storing\n * state on `this`: that rule bars PER-EXECUTION state; a rate limiter is\n * PER-ROUTE state and sharing it is the entire point. See\n * `.standards/resilience-wrappers.md` section 8.\n *\n * Emits scope-aware lifecycle events:\n * - `route:throttle:delayed` when an exchange must wait for a token.\n * - `route:throttle:passed` when an exchange is admitted (with `waited`).\n */\nexport class ThrottleWrapperStep<\n  T extends Adapter = Adapter,\n> extends WrapperStep<T> {\n  readonly #options: ResolvedThrottleOptions;\n  readonly #controller: ThrottleController;\n\n  constructor(inner: Step<T>, options: ThrottleOptions) {\n    super(inner);\n    this.#options = resolveThrottleOptions(options);\n    this.#controller = new ThrottleController(this.#options);\n  }\n\n  protected override describeOptions(): unknown {\n    return this.#options;\n  }\n\n  protected override async runInner(\n    exchange: Exchange,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const { route, context, routeId, stepLabel, correlationId } =\n      wrapperEventScope(exchange, this);\n    const shouldEmit = route && context && routeId;\n    const scoped: ThrottleEventScope = {\n      routeId: routeId as string,\n      exchangeId: exchange.id,\n      correlationId,\n      stepLabel,\n      scope: \"step\",\n      ...(this.#controller.label !== undefined\n        ? { label: this.#controller.label }\n        : {}),\n    };\n\n    await this.#controller.acquire(exchange, route, {\n      ...(route ? { signal: route.intakeSignal } : {}),\n      ...throttleEmitHooks(context, scoped, Boolean(shouldEmit)),\n    });\n\n    return await this.inner.execute(exchange, ctx);\n  }\n}\n","import type { Exchange, ExchangeHeaders } from \"./exchange.ts\";\nimport type { OperationType } from \"./exchange.ts\";\nimport type { CraftContext } from \"./context.ts\";\nimport type { RouteDefinition } from \"./route.ts\";\nimport type { Route } from \"./route.ts\";\nimport type { OnParseError } from \"./adapters/shared/parse.ts\";\nimport type { DeferRequest } from \"./deferral/sites.ts\";\nimport type { PrincipalRef } from \"./deferral/types.ts\";\nimport type { HealthChange } from \"./plugins/ops/types.ts\";\n\n/**\n * Base interface for all adapters (sources, destinations, transformers, filters, etc.).\n * Adapters can expose an optional `adapterId` string for logging (e.g. \"routecraft.adapter.log\").\n */\nexport interface Adapter {\n  /**\n   * Dotted identifier used for log and trace labels, by convention\n   * \"<vendor>.adapter.<name>\" (e.g. \"routecraft.adapter.mail\"). The last\n   * segment is shown in step events and logs. Optional so inline adapter\n   * objects (e.g. `{ aggregate: fn }`) stay ergonomic; framework-shipped\n   * adapters always set it.\n   */\n  adapterId?: string;\n\n  /**\n   * Observability hook for the FETCH slot: given the value the fetch\n   * produced, return details to attach to the step's completion event\n   * (`details.metadata`). Fires for `.enrich()` and for a fetch-only adapter\n   * in `.to()`.\n   *\n   * Derive the result from the arguments, never from state written during the\n   * call: one adapter instance serves every exchange on a route, so a field\n   * set by one call is routinely read back by another.\n   *\n   * @param result - Value the fetch resolved to\n   * @param exchange - Exchange the call ran against\n   */\n  getMetadata?(\n    result: unknown,\n    exchange?: Exchange<unknown>,\n  ): StepOutcomeMetadata;\n\n  /**\n   * Observability hook for the SEND slot: given the receipt headers the send\n   * recorded through {@link SendContext} (or `undefined` when it recorded\n   * none), return details to attach to the step's completion event. Fires for\n   * a send-resolved `.to()`.\n   *\n   * Named separately from {@link Adapter.getMetadata} so an adapter filling\n   * both slots never has to sniff which contract it was handed. The same\n   * no-instance-state rule applies.\n   *\n   * @param receipts - Receipt headers collected during the send\n   * @param exchange - Exchange the call ran against\n   */\n  getSendMetadata?(\n    receipts: unknown,\n    exchange?: Exchange<unknown>,\n  ): StepOutcomeMetadata;\n}\n\n/**\n * Returns a short label for logging which adapter is used.\n * Uses adapterId's last segment (e.g. \"routecraft.adapter.llm\" → \"llm\"), constructor name, or \"inline\" for plain objects.\n *\n * @param adapter - Adapter instance (or undefined)\n * @returns Label string or undefined\n */\nexport function getAdapterLabel(\n  adapter: Adapter | undefined,\n): string | undefined {\n  if (!adapter) return undefined;\n  if (adapter.adapterId) return adapter.adapterId.split(\".\").pop();\n  const name = (adapter as { constructor?: { name?: string } }).constructor\n    ?.name;\n  return name === \"Object\" ? \"inline\" : name;\n}\n\nexport interface Step<T extends Adapter> {\n  operation: OperationType;\n  adapter: T;\n\n  /**\n   * Display name shown in traces, logs, and step events instead of the\n   * raw OperationType. Set automatically by registerDsl for sugar methods\n   * (e.g., \"log\" instead of \"tap\", \"schema\" instead of \"validate\").\n   * When absent, the operation field is used.\n   */\n  label?: string;\n\n  /**\n   * When true, runPipeline will not emit generic route:step:started/route:step:completed\n   * events for this step. The step is responsible for emitting its own\n   * lifecycle events with the correct exchange identity.\n   */\n  skipStepEvents?: boolean;\n\n  /**\n   * Execute this step and report what happened. The executor owns all\n   * scheduling: steps no longer see the work queue or the remaining\n   * pipeline, they describe an outcome and the engine routes it.\n   *\n   * The exchange is typed as Exchange at runtime (body is unknown);\n   * the builder chain preserves body types for the next step, but custom\n   * steps receive an untyped exchange. Narrow or assert body type if needed.\n   */\n  execute(exchange: Exchange, ctx: StepContext): Promise<StepOutcome>;\n}\n\n/**\n * Observability metadata a step may attach to its outcome (e.g. LLM token\n * usage, HTTP status codes). The executor copies it into the\n * `route:step:completed` event payload. Guidelines: small values only\n * (IDs, names, counts, codes), no large bodies. Outcome-scoped on purpose:\n * `Step` instances are shared across exchanges, so per-execution data must\n * never live on the step itself.\n */\nexport type StepOutcomeMetadata = Record<string, unknown>;\n\n/**\n * Read {@link StepOutcomeMetadata} from an adapter's optional metadata\n * hook. Shared by the `to` and `enrich` steps so the metadata contract has\n * one implementation; `skip` short-circuits when a test override replaced\n * the adapter result (mock results are typically primitives and carry no\n * adapter metadata).\n *\n * The two role slots have distinct hooks, so an adapter never has to sniff\n * which contract it received:\n *\n * - `getMetadata(result, exchange)` fires for fetch-resolved steps\n *   (`.enrich()`, or a fetch-only adapter in `.to()`) with the fetched value.\n * - `getSendMetadata(receipts, exchange)` fires for send-resolved `.to()`\n *   steps with the receipt-header record collected from the\n *   {@link SendContext} sink, or `undefined` when the send set no receipts.\n *\n * Both hooks also receive the exchange the call ran against. Step instances\n * (and the adapters they hold) are shared across every exchange on a route,\n * so an adapter must derive per-call metadata from this argument rather than\n * stashing it on `this` during the call: with concurrent exchanges in flight,\n * instance state written by one call is routinely read back by another.\n *\n * `.tap()` never collects metadata (it runs detached; see TapStep).\n *\n * @internal\n */\nexport function extractOutcomeMetadata(\n  adapter: Adapter,\n  result: unknown,\n  skip: boolean,\n  hook: \"getMetadata\" | \"getSendMetadata\" = \"getMetadata\",\n  exchange?: Exchange<unknown>,\n): StepOutcomeMetadata | undefined {\n  if (skip) return undefined;\n  const extract = (\n    adapter as Partial<\n      Record<\n        typeof hook,\n        (result: unknown, exchange?: Exchange<unknown>) => StepOutcomeMetadata\n      >\n    >\n  )[hook];\n  if (!extract) return undefined;\n  // Best-effort: metadata is advisory (event-payload enrichment only). A\n  // throwing hook must not turn an adapter operation that already\n  // succeeded (and may have had side effects) into a route failure.\n  try {\n    return extract.call(adapter, result, exchange);\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * What a step did with its exchange. Returned from {@link Step.execute};\n * the pipeline executor translates outcomes into scheduling:\n *\n * - `continue`: run the remaining steps against `exchange` (the common case;\n *   `exchange` is usually a rewrapped derivation of the input).\n * - `complete`: skip the remaining steps and complete the exchange\n *   successfully (route-scope cache hit).\n * - `drop`: halt the exchange. The step has already called `markDropped`\n *   and emitted its drop events (filter reject, choice unmatched,\n *   parse-drop); the executor schedules nothing.\n * - `branch`: run `steps` and then the remaining steps against `exchange`\n *   (choice routes into the matched branch).\n * - `fanOut`: schedule each child exchange independently through the\n *   remaining steps (split).\n * - `defer`: deferral `exchange` durably and exit the pipeline, to be resumed\n *   later at the next step. Produced by `.defer()`. The executor\n *   serializes the exchange, writes the deferral, emits\n *   `route:exchange:deferred`, and schedules nothing further for it;\n *   `request` carries what it needs to do that (the `expect` schema, the\n *   TTL, and where the defer sits in the route). Only the framework's own\n *   defer step can produce a coherent `request`, so a custom step\n *   returning this kind without one is rejected with `RC5032` rather than\n *   silently dropping the exchange.\n *\n * The union is OPEN across minor releases: new kinds may be added as the\n * engine grows (the executor exhaustively handles every kind it ships\n * with). Code that consumes outcomes (custom wrappers, tests) should pass\n * unrecognised kinds through rather than throwing on them.\n */\nexport type StepOutcome =\n  | { kind: \"continue\"; exchange: Exchange; metadata?: StepOutcomeMetadata }\n  | { kind: \"complete\"; exchange: Exchange; metadata?: StepOutcomeMetadata }\n  | { kind: \"drop\"; metadata?: StepOutcomeMetadata }\n  | { kind: \"branch\"; exchange: Exchange; steps: Step<Adapter>[] }\n  | { kind: \"fanOut\"; exchanges: Exchange[] }\n  | { kind: \"defer\"; exchange: Exchange; request: DeferRequest };\n\n/**\n * The abort surface of a step execution, handed to function-form steps\n * (`.process()`, `.transform()`, `.to()`, `.enrich()`) as their trailing\n * argument. {@link StepContext} extends it, so adapter authors\n * implementing {@link Step.execute} read the same field from `ctx`.\n *\n * `signal` fires when an enclosing `.timeout()` deadline expires (step\n * scope or route scope): promises cannot be cancelled, so the framework\n * discards the losing run's outcome, and this signal is how the run\n * itself finds out. Forward it into cancellation-aware IO (`fetch`, DB\n * drivers) so abandoned work actually stops instead of running to\n * completion in the background:\n *\n * ```ts\n * .timeout(3000)\n * .process(async (ex, { signal }) => {\n *   const res = await fetch(url, { signal });\n *   return { ...ex, body: await res.json() };\n * })\n * ```\n *\n * The signal's abort reason is the `RC5011` timeout error. It is absent\n * when no timeout wraps the step. Route shutdown does NOT fire it:\n * graceful drain lets in-flight exchanges complete (sources observe\n * shutdown via their own `Subscription.signal`).\n */\nexport interface StepSignalContext {\n  /** Fires when an enclosing `.timeout()` deadline expires. */\n  readonly signal?: AbortSignal;\n}\n\n/**\n * Narrow a {@link StepContext} down to its abort surface for handing to\n * user code. Function-form steps (`.process()`, `.transform()`, `.to()`,\n * `.enrich()`) pass THIS to their callables instead of the executor's\n * full context: the narrowing is a deliberate capability boundary (only\n * `signal` may reach user code, never scheduling capabilities like\n * `takePending`), so every call site funnels through here rather than\n * re-spelling the spread.\n *\n * @internal\n */\nexport function toSignalContext(ctx?: StepContext): StepSignalContext {\n  return ctx?.signal ? { signal: ctx.signal } : {};\n}\n\n/**\n * Narrow executor capability handed to {@link Step.execute}.\n *\n * `takePending` atomically removes and returns pending sibling exchanges\n * matching the predicate; it exists for join-style steps (aggregate) that\n * consume their split siblings. The queue itself is never exposed, so\n * steps cannot reorder, duplicate, or corrupt scheduling.\n *\n * Extends {@link StepSignalContext}: `signal` fires when an enclosing\n * `.timeout()` deadline expires, so steps doing cancellation-aware IO\n * can abort abandoned work.\n */\nexport interface StepContext extends StepSignalContext {\n  takePending(predicate: (exchange: Exchange) => boolean): Exchange[];\n\n  /**\n   * Run each provided sub-pipeline against its own exchange, all in\n   * parallel, resolving once every path has settled (`Promise.allSettled`\n   * semantics: one path throwing does not reject the call). Each path runs\n   * as an isolated nested pipeline whose failure fires that exchange's\n   * default error events (the caller's route-scope `.error()` handler does\n   * NOT run for a path) but does not affect the caller or sibling paths.\n   * The queue itself stays private, so a fan-out step (e.g. `multicast`)\n   * cannot reorder or corrupt the parent's scheduling.\n   */\n  runPaths(\n    runs: ReadonlyArray<{ steps: Step<Adapter>[]; exchange: Exchange }>,\n  ): Promise<void>;\n\n  /**\n   * Run ONE sub-pipeline against its own exchange as an isolated nested run,\n   * resolving with the run's outcome. Like a single {@link runPaths} entry,\n   * but the result is reported back rather than swallowed, so a caller (e.g.\n   * `dispatch`'s `failover` strategy) can decide what to do next based on\n   * whether the run failed or was deliberately dropped. A failing path still\n   * fires that exchange's default error events (the caller's route-scope\n   * `.error()` handler does NOT run for it) and never rejects this call.\n   */\n  runPath(run: { steps: Step<Adapter>[]; exchange: Exchange }): Promise<{\n    failed: boolean;\n    dropped: boolean;\n    error?: unknown;\n    /**\n     * True when an outer abort signal (a route-scope timeout abandoning the\n     * attempt) truncated the run before or while it was scheduling steps.\n     * An aborted run is neither a success nor a target failure; callers\n     * (dispatch failover) must not treat it as a handled exchange.\n     */\n    aborted?: boolean;\n  }>;\n\n  /**\n   * Capture the downstream continuation for the currently-executing step:\n   * returns a runner that, when later invoked with an exchange, runs it\n   * through the steps that FOLLOW this one as a detached, route-tracked\n   * pipeline (with its own `route:exchange:started` / `:completed` lifecycle).\n   *\n   * Snapshot it synchronously inside `execute`; the runner stays valid after\n   * `execute` resolves. Used by `debounce` to release a held exchange after\n   * its quiet window closes without re-running the steps before it. Because\n   * the released exchange is the route's PRIMARY flow (not a side-effect\n   * clone), the detached run honors the route-scope `.error()` handler and\n   * enforces the route's `.output()` schemas before completing, and it\n   * inherits no abort signal from the capturing attempt.\n   */\n  captureDownstream(): (\n    exchange: Exchange,\n  ) => Promise<{ failed: boolean; dropped: boolean }>;\n}\n\n// MessageChannel lives with channel adapter now\n\n/**\n * Construction dependencies handed to a {@link Consumer} by the route\n * runtime, one bag per (source, consumer) pair.\n *\n * `options` is deliberately `unknown` here: route definitions store\n * heterogeneous consumer configurations, so the typed options surface\n * lives on the builder method that stages the consumer (e.g.\n * `.batch(...)`). Each consumer narrows and defaults its own options in\n * its constructor; it owns the interpretation of that value.\n */\nexport type ConsumerDeps = {\n  context: CraftContext;\n  definition: RouteDefinition;\n  channel: ProcessingQueue<Message>;\n  options: unknown;\n};\n\n/**\n * Constructable consumer class. The single deps-bag parameter (rather\n * than positional arguments) keeps every consumer class assignable to\n * `ConsumerType<Consumer>` without casts, so route definitions can store\n * any consumer implementation uniformly.\n */\nexport type ConsumerType<T extends Consumer = Consumer> = (new (\n  deps: ConsumerDeps,\n) => T) & {\n  /**\n   * The consumer may hold a message before the pipeline runs, the way\n   * `.batch()` fills a buffer. A held message is not the route's in-flight\n   * work, so a graceful shutdown can drain past it, and a transport that\n   * answers its caller before the pipeline finishes cannot promise the\n   * delivery will run. Declared by the consumer rather than inferred from\n   * its class, so a new consumer states its own answer instead of an\n   * unrelated file guessing.\n   */\n  readonly buffers?: boolean;\n};\n\n/**\n * Internal envelope flowing from a source adapter to its consumer through the\n * route's processing queue.\n *\n * @property message - Raw payload as the adapter handed it to `handler(...)`.\n *   When `parse` is set this is typically the unparsed bytes/string; when\n *   `parse` is unset this is the already-parsed value used directly as the\n *   exchange body.\n * @property headers - Optional exchange headers attached by the adapter.\n * @property parse - Optional parser the runtime invokes as a synthetic first\n *   step before any user-defined steps run. When provided, the runtime\n *   builds a derived exchange via\n *   `DefaultExchange.rewrap(exchange, { body: await parse(exchange.body) })`\n *   inside the same try/catch that handles step errors, so a parse\n *   failure flows through the route's `errorHandler` and\n *   `route:exchange:failed` event path. See `adapters/shared/parse.ts` for\n *   the `OnParseError` semantics. If `parse` resolves to `undefined`\n *   the body is explicitly set to `undefined` (the rewrap respects an\n *   explicit `body: undefined`), not left as the previous value.\n * @property parseFailureMode - Decides how the synthetic parse step handles\n *   a thrown parse error. `\"fail\"` (default) and `\"abort\"` throw `RC5016`\n *   so `route:exchange:failed` fires; `\"drop\"` instead emits `route:exchange:dropped`\n *   with `reason: \"parse-failed\"`. Adapters set this from their\n *   `onParseError` option; the source loop additionally rethrows for\n *   `\"abort\"` so the source dies. See #187.\n *\n * parse-error-handling work in #187. Their shape may evolve.\n */\nexport type Message<T = unknown> = {\n  /**\n   * The payload. When `parse` is set this is the RAW pre-parse value\n   * (e.g. a JSON line string), typed as `T` only after the synthetic\n   * parse step runs; adapters narrow at the call site.\n   */\n  message: T;\n  headers?: ExchangeHeaders;\n  parse?: (raw: unknown) => unknown | Promise<unknown>;\n  parseFailureMode?: OnParseError;\n};\n\nexport interface Consumer<O = unknown> {\n  context: CraftContext;\n  channel: ProcessingQueue<Message>;\n  definition: RouteDefinition;\n  options: O;\n  /**\n   * Register the route handler. The handler receives the same\n   * {@link Message} envelope that sources enqueue, so a pass-through\n   * consumer forwards it untouched while merging consumers (e.g. batch)\n   * synthesize new envelopes. At runtime the envelope's `message` and the\n   * returned exchange's body are untyped (unknown); the builder chain is\n   * typed, so narrow or assert in the handler if you need body fields.\n   *\n   * When the envelope carries a `parse` function the route captures it on\n   * the exchange internals so `runPipeline` can apply it as a synthetic\n   * first pipeline step. Consumers that merge multiple messages parse\n   * items eagerly during enqueue and hand over a `parse`-less envelope.\n   */\n  register(handler: (envelope: Message) => Promise<Exchange>): void;\n}\n\n/**\n * Internal queue API for route source→consumer flow. Sources enqueue messages; the consumer handler is set by the route and receives messages. Used by DefaultRoute.\n *\n * @template T - Message type (typically Message with message + headers)\n */\nexport interface ProcessingQueue<T = unknown> {\n  enqueue(message: T): Promise<Exchange>;\n  setHandler(handler: (message: T) => Promise<Exchange>): Promise<void> | void;\n  clear(): Promise<void> | void;\n}\n\n// Events API\n\n/** Exchange snapshot attached to terminal exchange events. */\ntype ExchangeSnapshot = {\n  id: string;\n  headers: Record<string, unknown>;\n  body: unknown;\n};\n\n/** Shared identity fields on per-exchange events. */\ntype ExchangeScoped = {\n  routeId: string;\n  exchangeId: string;\n  correlationId: string;\n};\n\n/**\n * What every tool-call event carries.\n *\n * `session` names the conversation the call was made in, when the agent\n * was dispatched with one. A session's boundary turn runs on the exchange\n * that deferred, which may be an earlier caller's, so the exchange identity\n * alone cannot say which conversation a call belongs to; the session can.\n */\ntype ToolCallScoped = ExchangeScoped & {\n  toolCallId: string;\n  toolName: string;\n  session?: string;\n};\n\n/**\n * Every event the framework emits, mapped to its detail payload.\n *\n * Event names are a FIXED, finite set: identity (route id, plugin id,\n * step label) lives in the payload, not the name. Subscribe with exact\n * names and filter on payload fields (see {@link forRoute}), or use the\n * single catch-all `\"*\"` to observe everything (telemetry-style taps).\n *\n * Declared as an interface so ecosystem packages can add their own events\n * via declaration merging, mirroring `ErrorCodeRegistry` / `StoreRegistry`:\n *\n * ```typescript\n * declare module \"@routecraft/routecraft\" {\n *   interface EventDetailsMap {\n *     \"myext:thing:happened\": { routeId: string; thing: string };\n *   }\n * }\n * ```\n */\nexport interface EventDetailsMap {\n  // -- Context lifecycle --\n  \"context:starting\": Record<string, never>;\n  \"context:started\": Record<string, never>;\n  \"context:stopping\": { reason?: unknown };\n  /**\n   * Shutdown finished. `forced` is true when stage one did not drain inside\n   * `shutdown.timeout` and in-flight execution was abandoned, with\n   * `pending` naming the routes that still had work. A clean stop carries\n   * `forced: false` and an empty `pending`, so the shape is stable and a\n   * subscriber can count forced shutdowns without reading exit codes.\n   */\n  \"context:stopped\": { forced: boolean; pending: string[] };\n  \"context:error\": {\n    error: unknown;\n    route?: Route;\n    exchange?: Exchange<unknown>;\n  };\n\n  // -- Auth --\n  \"auth:success\": { subject: string; scheme: string; source: string };\n  \"auth:rejected\": { reason: string; scheme: string; source: string };\n\n  // -- Route lifecycle --\n  \"route:registered\": { routeId: string; route: Route };\n  /**\n   * A route's enablement predicate was evaluated and the verdict CHANGED\n   * (or was reached for the first time). Not emitted when a refresh\n   * re-confirms what the route was already doing, so a five-minute cadence\n   * on a stable predicate is silent rather than a heartbeat.\n   *\n   * `reason` is present only when `enabled` is false, and is what ops\n   * reports next to the route.\n   */\n  \"route:enablement:changed\": {\n    routeId: string;\n    route: Route;\n    enabled: boolean;\n    reason?: string;\n  };\n  \"route:starting\": { routeId: string; route: Route };\n  \"route:started\": { routeId: string; route: Route };\n  \"route:stopping\": {\n    routeId: string;\n    route: Route;\n    reason?: unknown;\n    exchange?: Exchange<unknown>;\n  };\n  \"route:stopped\": {\n    routeId: string;\n    route: Route;\n    exchange?: Exchange<unknown>;\n  };\n  /**\n   * A source subscription rejected: the source gave up producing (e.g. a\n   * connection-backed source exhausted its reconnect attempts) and the route\n   * is about to stop. Distinct from `route:stopping`, which also fires for\n   * orderly shutdowns; subscribe to this one to alarm on a dead channel.\n   */\n  \"route:source:failed\": {\n    routeId: string;\n    route: Route;\n    /** `adapterId` of the failed source, when the adapter declares one. */\n    adapter?: string;\n    error: unknown;\n  };\n  \"route:error\": {\n    routeId: string;\n    error: unknown;\n    route?: Route;\n    exchange?: Exchange<unknown>;\n  };\n  \"route:error:caught\": {\n    routeId: string;\n    error: unknown;\n    route?: Route;\n    exchange?: Exchange<unknown>;\n  };\n\n  // -- Exchange lifecycle --\n  \"route:exchange:started\": ExchangeScoped;\n  \"route:exchange:completed\": ExchangeScoped & {\n    duration: number;\n    exchange?: ExchangeSnapshot;\n  };\n  \"route:exchange:failed\": ExchangeScoped & {\n    duration: number;\n    error: unknown;\n    exchange?: ExchangeSnapshot;\n  };\n  \"route:exchange:dropped\": ExchangeScoped & {\n    reason: string;\n    exchange?: ExchangeSnapshot;\n  };\n  \"route:exchange:restored\": ExchangeScoped & { source: string };\n  /**\n   * The exchange deferred at a `.defer()` and execution one ended. This is\n   * that run's terminal event, in place of `:completed`: the body the\n   * source receives is the `Deferred` acknowledgment, and the route's real\n   * output flows on execution two.\n   */\n  \"route:exchange:deferred\": ExchangeScoped & {\n    deferralId: string;\n    /** Address of the deferring step; the continuation is what follows it. */\n    position: number;\n    /** When the deferral stops being resumable, when a `ttl` was declared. */\n    expiresAt?: Date;\n  };\n  /**\n   * A deferred exchange was revived and its continuation is about to run.\n   * Execution two's `:started` follows immediately, and that run gets its\n   * own `:completed` / `:failed` / `:dropped`.\n   */\n  \"route:exchange:resumed\": ExchangeScoped & {\n    deferralId: string;\n    position: number;\n    /** Who resumed it, when the resume ingress had an authenticated principal. */\n    resumedBy?: PrincipalRef;\n  };\n  /**\n   * A deferral stopped being resumable because its `ttl` elapsed. Fires\n   * when a late resume discovers it, and (once the sweeper lands) when the\n   * sweeper reaches it first. The deferred route's error channel receives\n   * `RC5047` alongside, which is where a re-ask belongs.\n   */\n  \"route:exchange:expired\": ExchangeScoped & {\n    deferralId: string;\n    expiresAt: Date;\n  };\n\n  // -- Step lifecycle --\n  \"route:step:started\": ExchangeScoped & {\n    operation: OperationType | string;\n    adapter?: string;\n  };\n  \"route:step:completed\": ExchangeScoped & {\n    operation: OperationType | string;\n    adapter?: string;\n    duration: number;\n    metadata?: Record<string, unknown>;\n  };\n  \"route:step:failed\": ExchangeScoped & {\n    operation: OperationType | string;\n    adapter?: string;\n    duration: number;\n    error: string;\n  };\n  /** A step threw; `operation` is the step label (was `route:<id>:step:<label>:error`). */\n  \"route:step:error\": {\n    routeId: string;\n    error: unknown;\n    route?: Route;\n    exchange?: Exchange<unknown>;\n    operation: string;\n  };\n  // -- Batch --\n  \"route:batch:started\": {\n    routeId: string;\n    batchSize: number;\n    batchId: string;\n  };\n  \"route:batch:flushed\": {\n    routeId: string;\n    batchSize: number;\n    batchId: string;\n    waitTime: number;\n    reason: \"size\" | \"time\";\n  };\n  \"route:batch:stopped\": { routeId: string; batchId: string };\n\n  // -- Retry (route- and step-scope wrapper) --\n  \"route:retry:started\": ExchangeScoped & {\n    /** Label of the wrapped step, or `\"route\"` when `scope === \"route\"`. */\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    maxAttempts: number;\n  };\n  /** A failed attempt will be re-attempted after `backoffMs`. */\n  \"route:retry:attempt\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    attemptNumber: number;\n    maxAttempts: number;\n    /** Actual wait before the next attempt (factor growth + jitter applied). */\n    backoffMs: number;\n    lastError?: unknown;\n  };\n  \"route:retry:stopped\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    attemptNumber: number;\n    success: boolean;\n    /**\n     * Present when `success` is false: the raw error that caused the\n     * final failure (non-retryable error, exhausted attempts, or the\n     * last failure when shutdown interrupted the backoff).\n     */\n    error?: unknown;\n  };\n\n  // -- Delay (step-scope wrapper) --\n  \"route:delay:started\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"step\";\n    delayMs: number;\n  };\n  \"route:delay:stopped\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"step\";\n    delayMs: number;\n    elapsed: number;\n    /** True when route shutdown cut the wait short (the step still ran). */\n    cancelled: boolean;\n  };\n\n  // -- Timeout (route- and step-scope wrapper) --\n  \"route:timeout:started\": ExchangeScoped & {\n    /** Label of the wrapped step, or `\"route\"` when `scope === \"route\"`. */\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    timeoutMs: number;\n  };\n  /** The deadline fired before the guarded execution settled; RC5011 follows. */\n  \"route:timeout:expired\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    timeoutMs: number;\n    elapsed: number;\n  };\n  /** The guarded execution settled within the deadline. */\n  \"route:timeout:stopped\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    timeoutMs: number;\n    elapsed: number;\n  };\n\n  // -- Throttle (route- and step-scope wrapper) --\n  /** No token was free; the exchange will wait `waitMs` before admission (delay mode). */\n  \"route:throttle:delayed\": ExchangeScoped & {\n    /** Label of the wrapped step, or `\"route\"` when `scope === \"route\"`. */\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    /** Pacing wait applied before this exchange is admitted. */\n    waitMs: number;\n    /** Partition key the exchange was charged against, when `key` is set. */\n    key?: string;\n    /** Gate label, when `.throttle({ label })` is set. */\n    label?: string;\n  };\n  /** The exchange was admitted through the rate limiter. */\n  \"route:throttle:passed\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    /** True when the exchange had to wait for a token before admission. */\n    waited: boolean;\n    /** Total time spent in the throttle gate (0 on the fast path). */\n    elapsed: number;\n    /** Partition key the exchange was charged against, when `key` is set. */\n    key?: string;\n    /** Gate label, when `.throttle({ label })` is set. */\n    label?: string;\n  };\n  /** The exchange exceeded the rate and was rejected (reject mode); `RC5013` follows. */\n  \"route:throttle:rejected\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    /** Time until a token would free, for a Retry-After style hint. */\n    retryAfterMs: number;\n    /** Partition key the exchange was charged against, when `key` is set. */\n    key?: string;\n    /** Gate label, when `.throttle({ label })` is set. */\n    label?: string;\n  };\n\n  // -- Circuit breaker (route- and step-scope wrapper) --\n  /** The breaker tripped to open: failures reached the threshold (from closed) or a probe failed (from half-open). */\n  \"route:circuitBreaker:opened\": ExchangeScoped & {\n    /** Label of the wrapped step, or `\"route\"` when `scope === \"route\"`. */\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    /** Counted failures in the window at the moment the breaker tripped. */\n    failureCount: number;\n    /** Configured failure threshold. */\n    threshold: number;\n    /** Cooldown before the breaker will admit a probe (half-open). */\n    cooldownMs: number;\n    /** Breaker label, when `.circuitBreaker({ label })` is set. */\n    label?: string;\n  };\n  /** Cooldown elapsed; the breaker admitted a probe call to test recovery. */\n  \"route:circuitBreaker:halfOpen\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    label?: string;\n  };\n  /** A probe succeeded; the breaker recovered to closed. */\n  \"route:circuitBreaker:closed\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    label?: string;\n  };\n  /** A call was rejected because the breaker is open (or half-open at capacity); a `fallback` ran or `RC5025` followed. */\n  \"route:circuitBreaker:rejected\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    /** Breaker state at rejection time. */\n    state: \"open\" | \"half-open\";\n    /** Time until the breaker would admit a probe, for a Retry-After style hint (0 when half-open at capacity). */\n    retryAfterMs: number;\n    label?: string;\n  };\n\n  // -- Concurrency / bulkhead (route- and step-scope wrapper) --\n  /** All slots were busy; the exchange joined the wait queue (queue mode). */\n  \"route:concurrency:queued\": ExchangeScoped & {\n    /** Label of the wrapped step, or `\"route\"` when `scope === \"route\"`. */\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    /** The exchange's position in the wait queue (1 = next to be admitted). */\n    queueDepth: number;\n    /** Partition key the exchange was charged against, when `key` is set. */\n    key?: string;\n    /** Limiter label, when `.concurrency({ label })` is set. */\n    label?: string;\n  };\n  /** A slot was acquired and the wrapped work began. */\n  \"route:concurrency:acquired\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    /** True when the exchange had to queue before a slot freed. */\n    waited: boolean;\n    /** Slots in use (including this one) at admission time. */\n    inUse: number;\n    key?: string;\n    label?: string;\n  };\n  /** The held slot was released (work settled: success, drop, or failure). */\n  \"route:concurrency:released\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    /** How long the work held the slot, in milliseconds. */\n    heldMs: number;\n    key?: string;\n    label?: string;\n  };\n  /** The exchange was failed fast with `RC5026`; `RC5026` follows. */\n  \"route:concurrency:rejected\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    /** `\"busy\"`: reject mode, all slots in use. `\"queue-full\"`: queue mode, wait line at `maxQueue`. */\n    reason: \"busy\" | \"queue-full\";\n    key?: string;\n    label?: string;\n  };\n\n  // -- Error handler (route- and step-scope wrappers) --\n  \"route:error-handler:invoked\": ExchangeScoped & {\n    originalError: unknown;\n    failedOperation: string;\n    /**\n     * `\"route\"` for the route-level (`.error()` before `.from()`)\n     * catch-all handler; `\"step\"` for a wrapper-scope handler\n     * attached to a single step (`.error()` after `.from()`).\n     */\n    scope?: \"route\" | \"step\";\n    /** Step label when `scope === \"step\"`. */\n    stepLabel?: string;\n  };\n  \"route:error-handler:recovered\": ExchangeScoped & {\n    originalError: unknown;\n    failedOperation: string;\n    recoveryStrategy: string;\n    scope?: \"route\" | \"step\";\n    stepLabel?: string;\n  };\n  \"route:error-handler:failed\": ExchangeScoped & {\n    originalError: unknown;\n    failedOperation: string;\n    recoveryStrategy?: string;\n    scope?: \"route\" | \"step\";\n    stepLabel?: string;\n  };\n\n  // -- Cache --\n  \"route:cache:hit\": ExchangeScoped & {\n    /** Label of the wrapped step, or `\"route\"` when `scope === \"route\"`. */\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    key: string;\n  };\n  \"route:cache:miss\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    key: string;\n    /** True when the wrapped step dropped the exchange (filter/halt). */\n    dropped?: boolean;\n  };\n  \"route:cache:stored\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    key: string;\n    /** TTL in ms when one was configured. */\n    ttl?: number;\n  };\n  \"route:cache:failed\": ExchangeScoped & {\n    stepLabel: string;\n    scope: \"route\" | \"step\";\n    /**\n     * Where the failure occurred: `\"key\"` = key derivation threw,\n     * `\"get\"` = provider read threw, `\"inner\"` = the wrapped step threw,\n     * `\"set\"` = the provider write threw after the wrapped step succeeded.\n     */\n    phase: \"key\" | \"get\" | \"inner\" | \"set\";\n    key?: string;\n    error: string;\n  };\n\n  // -- Choice --\n  \"route:operation:choice:matched\": ExchangeScoped & {\n    branchIndex: number;\n    branchLabel: \"when\" | \"otherwise\";\n  };\n  \"route:operation:choice:unmatched\": ExchangeScoped;\n\n  // -- Multicast --\n  /** Fan-out started: the exchange is about to be cloned to each path. */\n  \"route:operation:multicast:started\": ExchangeScoped & {\n    /** Number of paths the exchange is fanned out to. */\n    pathCount: number;\n  };\n  /** Fan-out finished: every path has settled and the original continues. */\n  \"route:operation:multicast:stopped\": ExchangeScoped & {\n    pathCount: number;\n  };\n\n  // -- Dispatch --\n  /** A target was selected to run. For `failover`, fired once per attempt. */\n  \"route:operation:dispatch:selected\": ExchangeScoped & {\n    /**\n     * The strategy that made the pick. Inlines `DispatchStrategyName`\n     * (operations/dispatch.ts): this file is the dependency root and never\n     * imports from operations, so keep the two unions in sync.\n     */\n    strategy: \"failover\" | \"round-robin\" | \"weighted\" | \"sticky\";\n    /** Index of the selected target in the `.dispatch()` target list. */\n    targetIndex: number;\n  };\n  /** `failover` ran out of targets: every one failed and none handled the exchange. */\n  \"route:operation:dispatch:exhausted\": ExchangeScoped & {\n    strategy: \"failover\";\n    /** How many targets were tried before giving up. */\n    targetCount: number;\n  };\n\n  // -- Sample --\n  /** The sampler admitted this exchange. */\n  \"route:operation:sample:passed\": ExchangeScoped & {\n    /** `\"count\"` for `every`-based sampling, `\"interval\"` for `intervalMs`. */\n    mode: \"count\" | \"interval\";\n  };\n  /** The sampler dropped this exchange (between samples). */\n  \"route:operation:sample:dropped\": ExchangeScoped & {\n    mode: \"count\" | \"interval\";\n  };\n\n  // -- Dedupe --\n  /** The key was unseen; it is reserved and the exchange continues. */\n  \"route:operation:dedupe:pass\": ExchangeScoped & {\n    /** The derived key reserved for this exchange. */\n    key: string;\n  };\n  /** The key was already reserved or committed; the exchange is dropped. */\n  \"route:operation:dedupe:duplicate\": ExchangeScoped & {\n    /** The derived key that was already seen. */\n    key: string;\n  };\n\n  // -- Debounce --\n  /** An exchange entered the debounce window and is being held (timer armed/reset). */\n  \"route:operation:debounce:held\": ExchangeScoped & {\n    /** The partition key the exchange was held under, when `key` is set. */\n    key?: string;\n  };\n  /** A held exchange was superseded by a newer arrival in the same burst and dropped. */\n  \"route:operation:debounce:dropped\": ExchangeScoped & {\n    key?: string;\n  };\n  /** The quiet window (or `maxWait` cap) elapsed; the last held exchange is released downstream. */\n  \"route:operation:debounce:released\": ExchangeScoped & {\n    key?: string;\n    /**\n     * Why the exchange was released: `\"quiet\"` when the `waitMs` window\n     * closed, `\"maxWait\"` when the `maxWaitMs` cap fired during continuous\n     * activity, or `\"flush\"` when a drain / shutdown released it early.\n     */\n    reason: \"quiet\" | \"maxWait\" | \"flush\";\n  };\n\n  // -- Agent (emitted by @routecraft/ai agent() destinations) --\n  // Sensitive payloads (tool input/output, thrown errors that may echo\n  // them) ride in the `_snapshot` envelope: the bus always carries them,\n  // but the telemetry sink persists them only when snapshot capture is on.\n  \"route:agent:started\": ExchangeScoped & {\n    agentName?: string;\n    model: string;\n    toolNames: string[];\n    maxTurns: number;\n  };\n  /**\n   * A tool was refused admission to an agent's tool list by\n   * `agentPlugin({ toolPolicy })` and never offered to the model.\n   *\n   * Emitted once per denied tool per dispatch, alongside whichever log\n   * that denial produced: `warn` when a rule decided against the tool,\n   * `error` when a rule threw (the tool is denied to fail closed, and\n   * the warn line is suppressed so one failure is not reported twice).\n   * The two channels serve different consumers: the log is for someone\n   * reading text, the event is for alerting and audit, which is what a\n   * policy decision needs to be queryable from.\n   *\n   * `reason` distinguishes a rule that decided against the tool from a\n   * rule that threw (denied to fail closed) and from provenance the\n   * resolver could not classify. `unknown-provenance` covers every tool\n   * whose `source` is missing or carries a kind the policy surface does\n   * not define, since no rule runs in either case; `toolKind` is\n   * reported as `\"unknown\"` for both.\n   */\n  \"route:agent:tool:denied\": ExchangeScoped & {\n    agentName?: string;\n    toolName: string;\n    toolKind: string;\n    reason: \"rule\" | \"rule-error\" | \"unknown-provenance\";\n  };\n  /**\n   * A call the model made was refused by the tool's guard, at call time,\n   * on a tool the model could see and was allowed to attempt.\n   *\n   * Distinct from `denied`, which fires when a policy withholds a tool at\n   * selection time so the model never sees it. Counting the two together\n   * would mix \"this agent may not have that tool\" with \"this agent asked\n   * for something its grant does not cover\", and it is the second that\n   * tells an operator an agent is probing the edges of its allowlist.\n   * That signal is the whole reason an allowlist is worth auditing.\n   *\n   * The payload is deliberately bounded to identity plus the error code.\n   * The refused input is what carries the secret material (a command line\n   * can hold a token someone passed as an argument), and a refusal is\n   * exactly the case where that input is least trustworthy, so it is not\n   * carried here even under snapshot capture.\n   */\n  \"route:agent:tool:refused\": ToolCallScoped & {\n    /** Error code when the guard threw a Routecraft error, e.g. `RC5002`. */\n    rc?: string;\n  };\n  \"route:agent:tool:invoked\": ToolCallScoped & {\n    _snapshot: { input: unknown };\n  };\n  \"route:agent:tool:result\": ToolCallScoped & {\n    _snapshot: { output: unknown };\n    duration: number;\n  };\n  \"route:agent:tool:error\": ToolCallScoped & {\n    errorName: string;\n    _snapshot: { error: unknown };\n    duration: number;\n  };\n  \"route:agent:block:loaded\": ExchangeScoped & {\n    toolCallId: string;\n    blockName: string;\n    _snapshot: { output: unknown };\n    duration: number;\n  };\n  \"route:agent:block:error\": ExchangeScoped & {\n    toolCallId: string;\n    blockName: string;\n    errorName: string;\n    _snapshot: { error: unknown };\n    duration: number;\n  };\n  \"route:agent:finished\": ExchangeScoped & {\n    agentName?: string;\n    model: string;\n    finishReason: string;\n    inputTokens?: number;\n    outputTokens?: number;\n    totalTokens?: number;\n  };\n  /**\n   * Emitted after every successful agent dispatch alongside\n   * `route:agent:finished`. Carries the full token breakdown for the\n   * dispatch so consumers can compute cost without subscribing to the\n   * broader lifecycle event.\n   *\n   * Cache fields are present only when the provider reports them (e.g.\n   * Anthropic with prompt caching enabled).\n   */\n  \"route:agent:usage\": ExchangeScoped & {\n    agentName?: string;\n    model: string;\n    inputTokens?: number;\n    outputTokens?: number;\n    totalTokens?: number;\n    cacheReadTokens?: number;\n    cacheWriteTokens?: number;\n  };\n  \"route:agent:error\": ExchangeScoped & {\n    agentName?: string;\n    model: string;\n    error: unknown;\n  };\n\n  // -- Agent sessions (emitted by @routecraft/ai for agent() dispatches\n  // that carry `session`). `agentName` is the session's agent: the\n  // registered name, or the route id for an inline agent.\n  /**\n   * A message arrived for a session whose turn is running and was queued\n   * for the next turn boundary. The caller was acknowledged, not answered.\n   */\n  \"route:agent:session:queued\": ExchangeScoped & {\n    agentName: string;\n    session: string;\n    /** Inbox depth after this message was appended. */\n    depth: number;\n    /** The message asked for the running turn to be interrupted. */\n    interrupt: boolean;\n  };\n  /** A running turn was cancelled by a later message with `interrupt: true`. */\n  \"route:agent:session:interrupted\": ExchangeScoped & {\n    agentName: string;\n    session: string;\n  };\n  /**\n   * A turn started on a session whose previous turn was cut short by a\n   * restart: its partial transcript was kept, its inbox was intact, and\n   * every background call it was waiting on was reported lost.\n   */\n  \"route:agent:session:restored\": ExchangeScoped & {\n    agentName: string;\n    session: string;\n    lostBackground: number;\n  };\n  /**\n   * A turn ended with work outstanding (background calls running, or\n   * messages queued), so its exchange's continuation was stored: what a\n   * completion, the queued messages, or a boot revives to run the next\n   * turn and the route's downstream steps.\n   */\n  \"route:agent:session:deferred\": ExchangeScoped & {\n    agentName: string;\n    session: string;\n    deferralId: string;\n    /** Messages waiting when the deferral was stored. */\n    inbox: number;\n    /** Background calls still running when the deferral was stored. */\n    background: number;\n  };\n  /**\n   * A stored continuation was revived and this turn is the one it runs:\n   * the inbox is its user message and the route's downstream steps follow.\n   * Emitted on the revived exchange, after core's `route:exchange:resumed`.\n   */\n  \"route:agent:session:revived\": ExchangeScoped & {\n    agentName: string;\n    session: string;\n    deferralId: string;\n  };\n  /** A background tool dispatched its route and returned a handle to the model. */\n  \"route:agent:session:background:started\": ExchangeScoped & {\n    agentName: string;\n    session: string;\n    handle: string;\n    toolName: string;\n  };\n  /** A background tool's route finished and its result was posted to the session inbox. */\n  \"route:agent:session:background:completed\": ExchangeScoped & {\n    agentName: string;\n    session: string;\n    handle: string;\n    toolName: string;\n    duration: number;\n  };\n  /** A background tool's route failed and the failure was posted to the session inbox. */\n  \"route:agent:session:background:failed\": ExchangeScoped & {\n    agentName: string;\n    session: string;\n    handle: string;\n    toolName: string;\n    errorName: string;\n    duration: number;\n  };\n\n  // -- Agent / tool registration (emitted once per registered agent / fn\n  // on context:started by agentPlugin in @routecraft/ai, so observability\n  // consumers can list agents and tools before any of them runs) --\n  \"agent:registered\": {\n    agentId: string;\n    description?: string;\n    model?: string;\n    source: \"registered\";\n  };\n  \"agent:tool:registered\": {\n    toolName: string;\n    description?: string;\n    tags?: string[];\n    source: \"registered\";\n  };\n\n  // -- Named servers (shared web ingress) --\n  \"server:listening\": { server: string; port: number; host: string };\n  \"server:failed\": { server: string; error: unknown };\n  \"server:closed\": { server: string };\n  /** A protocol request was refused before authentication or SDK dispatch. */\n  \"server:request:rejected\": {\n    server: string;\n    mount: string;\n    reason: \"host\" | \"origin\";\n  };\n\n  // -- HTTP plugin --\n  /**\n   * A health component changed status, so an operator can alert on the\n   * transition rather than polling for it. The ops listener's own lifecycle\n   * is reported by the server events above, since the ops surface mounts on a\n   * named server rather than owning a socket.\n   */\n  \"plugin:ops:health:changed\": HealthChange;\n  \"plugin:http:request:completed\": {\n    method: string;\n    path: string;\n    status: number;\n    durationMs: number;\n    routeId?: string;\n    principal?: { subject: string } | undefined;\n    /**\n     * Why a streaming response ended badly, when it did.\n     *\n     * A stream fails after its status line is already on the wire, so\n     * `status` still reports what was sent and cannot say the response\n     * broke. Without this an operator counting completions would score a\n     * truncated stream as a 200 success, and only the logs would disagree.\n     * Absent on every response that completed normally.\n     */\n    error?: { name: string; message: string };\n  };\n\n  // -- Plugin lifecycle --\n  /** The plugin's `apply()` hook is about to run, at context build time. */\n  \"plugin:applying\": { pluginId: string; pluginIndex: number };\n  /** The plugin's `apply()` hook returned. */\n  \"plugin:applied\": { pluginId: string; pluginIndex: number };\n  /**\n   * The plugin's `start()` hook is about to run, after every route has\n   * signalled readiness or the readiness backstop elapsed, so it is not\n   * proof that every source is listening.\n   * Until 0.7 this pair bracketed `apply()`; that phase is now\n   * `plugin:applying` / `plugin:applied`, so the event vocabulary matches\n   * the lifecycle: applying, starting, stopping.\n   */\n  \"plugin:starting\": { pluginId: string; pluginIndex: number };\n  /** The plugin's `start()` hook resolved. */\n  \"plugin:started\": { pluginId: string; pluginIndex: number };\n  \"plugin:stopping\": { pluginId: string; pluginIndex: number };\n  \"plugin:stopped\": { pluginId: string; pluginIndex: number };\n}\n\n/**\n * Union of all event names: the keys of {@link EventDetailsMap} plus the\n * catch-all `\"*\"` accepted by `on()` / `once()` (never emitted itself).\n */\nexport type EventName = keyof EventDetailsMap;\n\n/** Detail payload for a given event name. */\nexport type EventDetailsMapping<K extends EventName = EventName> =\n  EventDetailsMap[K];\n\nexport type EventPayload<K extends EventName> = {\n  ts: string;\n  contextId: string;\n  details: EventDetailsMap[K];\n  /** The exact event name that was emitted. Set by context.emit(). */\n  _event: string;\n};\n\nexport type EventHandler<K extends EventName> = (\n  payload: EventPayload<K>,\n) => void | Promise<void>;\n\n/**\n * Event names whose payload carries a `routeId`, i.e. the events\n * {@link forRoute} can meaningfully filter. Subscribing `forRoute` to a\n * route-less event (context, auth, plugin lifecycle) would silently never\n * fire, so the constraint makes that a compile error instead.\n */\nexport type RouteScopedEventName = {\n  // Key presence (not `extends { routeId: string }`) so events with an\n  // OPTIONAL routeId (e.g. plugin:http:request:completed) stay filterable.\n  [K in EventName]: \"routeId\" extends keyof EventDetailsMap[K] ? K : never;\n}[EventName];\n\n/**\n * Wrap an event handler so it only fires for events whose payload carries\n * the given `routeId`. Identity lives in the payload (event names are a\n * fixed set), so per-route subscription is a filter:\n *\n * ```typescript\n * ctx.on(\"route:exchange:failed\", forRoute(\"orders\", ({ details }) => {\n *   console.error(\"orders failed:\", details.error);\n * }));\n * ```\n */\nexport function forRoute<K extends RouteScopedEventName>(\n  routeId: string,\n  handler: EventHandler<K>,\n): EventHandler<K> {\n  return (payload) => {\n    if (payload.details.routeId === routeId) {\n      return handler(payload);\n    }\n    return undefined;\n  };\n}\n","import type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport { getAdapterLabel } from \"../types.ts\";\nimport {\n  type Exchange,\n  getExchangeContext,\n  getExchangeRoute,\n  HeadersKeys,\n  OperationType,\n} from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { NESTED_STEPS, DEFER_HOST } from \"../dsl-symbol.ts\";\nimport {\n  type NestedSteps,\n  type DeferCapableStep,\n  nestedStepsOf,\n  deferHostOf,\n} from \"../deferral/sites.ts\";\n\n/**\n * Operation kinds that resilience wrappers cannot safely wrap. Validated\n * at construction time by {@link WrapperStep} so misuse fails when the\n * route is built, not at first dispatch.\n *\n * - `aggregate`: a join point that consumes pending sibling exchanges\n *   via the executor's `takePending` capability. That shared pending\n *   state cannot be isolated per wrapper execution, so retry/recovery\n *   semantics around it are undefined. Wrap the steps UPSTREAM of\n *   `.aggregate()` instead.\n * - `split`: emits children via a `fanOut` outcome. A recovering\n *   wrapper would have to convert a fan-out failure into a single\n *   recovered exchange, silently changing the pipeline's cardinality.\n *   Wrap the steps DOWNSTREAM of `.split()` instead.\n * - `debounce`: holds exchanges OUTSIDE the pipeline queue across\n *   arrivals (N in, 1 released later via a detached run), the same\n *   shared-state / cardinality profile as aggregate. Its execute never\n *   fails per-exchange, so a wrapper could never trigger, while a\n *   step-scope `.error()` would falsely suggest it covers failures of\n *   the RELEASED exchange (those run detached, bypassing wrappers).\n *   Wrap the steps DOWNSTREAM of `.debounce()` instead.\n * - `defer`: exits the pipeline and defers the exchange durably. It never\n *   fails per-exchange, so a recovering wrapper could never trigger, while\n *   the ones that CAN act would each act wrongly: `.retry()` would re-defer\n *   an exchange that did not fail, `.timeout()` would bound a wait that is\n *   measured in days and lives in the store rather than in this process,\n *   and `.cache()` would replay a single-use resume token to a second\n *   exchange. Put `.error()` at route scope instead, where it also catches\n *   the revival failures a resume re-enters through.\n *\n * @internal\n */\nconst NON_WRAPPABLE_OPERATIONS: ReadonlySet<OperationType> = new Set([\n  OperationType.AGGREGATE,\n  OperationType.SPLIT,\n  OperationType.DEBOUNCE,\n  OperationType.DEFER,\n]);\n\n/**\n * Abstract base for \"dual-mode wrapper\" operations: a single concept\n * (`.error()`, `.retry()`, `.timeout()`, `.cache()`, ...) that\n * applies at either route scope (when staged before `.from()`) or step\n * scope (when chained after `.from()`). The route-scope path is wired\n * by the builder via existing fields on `RouteDefinition`. The\n * step-scope path is wired by wrapping the *immediately next* step in a\n * concrete `WrapperStep` subclass.\n *\n * Subclasses implement {@link WrapperStep.runInner}: run the inner step\n * and return its {@link StepOutcome} (usually unchanged), substitute a\n * recovery outcome on failure, or rethrow (signals an unrecoverable\n * error for the pipeline executor to handle).\n *\n * The template `execute()` handles the boilerplate: emitting the\n * inner step's `route:step:started` / `route:step:completed` events with the inner\n * label (so the wrapper is observationally invisible) around the\n * subclass's `runInner`, and passing the inner's outcome through to the\n * executor, which owns all scheduling.\n *\n * The `WrapperStep` class is exposed for forward-compat as wrapper\n * authors land additional operations (retry, cache, timeout, circuit\n * breaker, etc.).\n */\nexport abstract class WrapperStep<\n  T extends Adapter = Adapter,\n> implements Step<T> {\n  /**\n   * Operation kind delegated from the inner step so observers see the\n   * wrapped operation's identity, not a generic \"wrapper\".\n   */\n  readonly operation: Step<T>[\"operation\"];\n  /** Adapter delegated from the inner step. */\n  readonly adapter: T;\n  /** Display label delegated from the inner step. */\n  readonly label?: string;\n  /**\n   * The wrapper emits its own `route:step:started` / `route:step:completed` events\n   * with the inner step's label, so the executor must not emit a generic\n   * pair around the wrapper.\n   */\n  readonly skipStepEvents = true;\n\n  /**\n   * Forward the inner step's sub-pipelines so a wrapper is transparent to\n   * framework-level walks of the route's step tree.\n   *\n   * Without this a wrapped nesting step hides everything inside it: a\n   * `.error(h).choice(when(p, (b) => b.defer(...)))` route resolved zero\n   * defer sites, which silently disabled the build-time refusals AND the\n   * startup check, and then failed at runtime, after the approver had\n   * already been notified, with a diagnostic telling the user to build the\n   * route through `craft()` (which they had).\n   *\n   * @internal\n   */\n  [NESTED_STEPS](): ReadonlyArray<NestedSteps> {\n    return nestedStepsOf(this.inner);\n  }\n\n  /**\n   * Forward the defer-host protocol to the inner step, for the same\n   * reason nested steps are forwarded: the defer-site walk sees the\n   * wrapper (which delegates the inner adapter, so the capability brand is\n   * visible), but the site must land on the instance whose `execute`\n   * converts the defer signal, which is the innermost `.to()` /\n   * `.enrich()` step.\n   *\n   * @internal\n   */\n  [DEFER_HOST](): DeferCapableStep | undefined {\n    return deferHostOf(this.inner);\n  }\n\n  constructor(protected readonly inner: Step<T>) {\n    if (NON_WRAPPABLE_OPERATIONS.has(inner.operation)) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          `Wrapper operations (.error() / .retry() / .timeout() / .throttle() / .circuitBreaker() / .concurrency() / .cache() / .delay()) cannot wrap \"${inner.operation}\" steps. ` +\n          `Aggregate consumes pending siblings (shared join state), split fans out children, debounce holds exchanges ` +\n          `outside the queue for a later detached release, and defer defers the exchange durably outside this process; ` +\n          `all have semantics that conflict with per-execution wrapper recovery. Wrap the steps downstream of ` +\n          `split/debounce/defer or upstream of aggregate instead, or put .error() at route scope.`,\n      });\n    }\n    this.operation = inner.operation;\n    this.adapter = inner.adapter;\n    if (inner.label !== undefined) this.label = inner.label;\n  }\n\n  /**\n   * The step this wrapper folds around, for build-time walks that must see\n   * through a stack of wrappers (e.g. assigning a step-scope cache its site).\n   *\n   * @internal\n   */\n  get wrapped(): Step<T> {\n    return this.inner;\n  }\n\n  /**\n   * The options this wrapper was built with, as reported by\n   * {@link describeOptions}, for build-time walks that fingerprint a\n   * wrapper stack.\n   *\n   * @internal\n   */\n  get fingerprintOptions(): unknown {\n    return this.describeOptions();\n  }\n\n  /**\n   * Report the options that define this wrapper, so a `.cache()` whose\n   * cached computation includes it (a step-scope cache stacked above it,\n   * or a route-scope cache over the pipeline) can fold them into its\n   * default key.\n   * Without them, editing a wrapper between a cache and its step (an\n   * `.error()` handler's recovery value, a `.retry()` predicate deciding\n   * which failures are recovered) would leave the key unchanged and an\n   * external provider would keep replaying what the old wrapper produced.\n   *\n   * Return the configuration, not runtime state: callables as themselves\n   * (their source text is hashed), plain data as plain data, and never a\n   * controller, bucket or other live object (those hash as `[opaque]` and\n   * add nothing). Return `null` when the wrapper takes no options. The\n   * value goes through the same projection as an adapter's options in\n   * `deferral/hash.ts`, so the same carriers and depth bound apply.\n   *\n   * Abstract so a new wrapper cannot silently opt out of the cache key.\n   */\n  protected abstract describeOptions(): unknown;\n\n  /**\n   * Run the inner step with whatever extra behaviour the subclass adds\n   * and return the outcome the pipeline should act on. Return the\n   * inner's outcome unchanged when it succeeded; return a substitute\n   * outcome (e.g. `continue` with a recovered exchange) when the\n   * wrapper handled a failure. Throw to signal the wrapper could not\n   * recover; the executor will then fall through to the route-level\n   * error handler (or fail the exchange when none is set).\n   *\n   * There is no scheduling to intercept: the inner step never sees the\n   * work queue, so a failed inner step has, by construction, scheduled\n   * nothing. The pre-outcome engine required subclasses to capture and\n   * replay inner queue pushes (and clear them on recovery); that whole\n   * protocol is gone.\n   *\n   * @param exchange Live exchange to feed to the inner step.\n   * @param ctx Executor capability passthrough for the inner step.\n   * @returns Outcome the executor schedules.\n   */\n  protected abstract runInner(\n    exchange: Exchange,\n    ctx: StepContext,\n  ): Promise<StepOutcome>;\n\n  /**\n   * Template method called by the pipeline executor. Emits the inner\n   * step's lifecycle events with the inner label, delegates to\n   * {@link runInner}, and returns the outcome for the executor to\n   * schedule. Wrapper-specific failure events are emitted by the\n   * subclass before it rethrows.\n   */\n  async execute(exchange: Exchange, ctx: StepContext): Promise<StepOutcome> {\n    const route = getExchangeRoute(exchange);\n    const context = getExchangeContext(exchange);\n    const stepLabel = this.label ?? String(this.operation);\n    const adapterLabel = getAdapterLabel(this.adapter);\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n    const routeId = route?.definition.id;\n    // The wrapper only emits step lifecycle events when the inner\n    // step does NOT manage its own. Steps with `skipStepEvents = true`\n    // (filter, choice, choice's halt, child wrappers in a stack) emit\n    // their own pair, so the wrapper must stay silent to avoid\n    // duplicates.\n    const innerOwnsEvents = this.inner.skipStepEvents === true;\n    const shouldEmitEvents = !innerOwnsEvents && route && context && routeId;\n\n    if (shouldEmitEvents) {\n      context.emit(\"route:step:started\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: stepLabel,\n        ...(adapterLabel ? { adapter: adapterLabel } : {}),\n      });\n    }\n\n    const stepStart = Date.now();\n    let outcome: StepOutcome;\n    try {\n      outcome = await this.runInner(exchange, ctx);\n    } catch (err) {\n      // Emit route:step:failed before propagating so observers see a\n      // balanced started -> failed pair. This matters for stacked\n      // wrappers where an inner wrapper threw and an outer wrapper\n      // recovers; without this, the inner wrapper's started event\n      // would never have a closing event.\n      if (shouldEmitEvents) {\n        context.emit(\"route:step:failed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          operation: stepLabel,\n          ...(adapterLabel ? { adapter: adapterLabel } : {}),\n          duration: Date.now() - stepStart,\n          error: err instanceof Error ? err.message : String(err),\n        });\n      }\n      throw err;\n    }\n\n    if (shouldEmitEvents) {\n      context.emit(\"route:step:completed\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: stepLabel,\n        ...(adapterLabel ? { adapter: adapterLabel } : {}),\n        duration: Date.now() - stepStart,\n        // Mirror the executor: forward the adapter-populated observability\n        // metadata carried on the inner step's outcome.\n        ...(\"metadata\" in outcome && outcome.metadata\n          ? { metadata: outcome.metadata }\n          : {}),\n      });\n    }\n\n    return outcome;\n  }\n}\n","/**\n * Symbol used by registerDsl to access the builder's internal addStep method.\n * Defined in a separate module to avoid circular imports between builder.ts\n * and dsl.ts.\n *\n * @internal\n */\nexport const PUSH_STEP: unique symbol = Symbol.for(\n  \"routecraft.builder.pushStep\",\n);\n\n/**\n * Symbol used by sub-pipeline builders (the shared PathBuilder for choice and\n * multicast paths) to hand their compiled step array back to their parent Step\n * without exposing a public `.steps()` API. Keeps the \"no headless builder\"\n * constraint on RouteBuilder intact.\n *\n * @internal\n */\nexport const COLLECT_STEPS: unique symbol = Symbol.for(\n  \"routecraft.builder.collectSteps\",\n);\n\n/**\n * Symbol a step implements to expose the sub-pipelines it carries (choice\n * branches, multicast paths, dispatch targets) to framework-level walks of\n * a route's step tree, without widening the public `Step` contract or\n * making those step arrays writable from outside.\n *\n * The one walk today is the defer-site resolver, which has to know both\n * that a sub-pipeline exists and whether it rejoins the main flow.\n *\n * @internal\n */\nexport const NESTED_STEPS: unique symbol = Symbol.for(\n  \"routecraft.step.nestedSteps\",\n);\n\n/**\n * Symbol a step implements to expose the step instance that hosts a\n * re-entrant defer site: the `.to()` / `.enrich()` step whose adapter\n * carries the defer-capable brand. Step-scope wrappers forward it to\n * their inner step (like {@link NESTED_STEPS}), so the defer-site walk\n * can store the site on the instance whose `execute` converts the defer\n * signal, however deeply the step is wrapped.\n *\n * @internal\n */\nexport const DEFER_HOST: unique symbol = Symbol.for(\n  \"routecraft.step.deferHost\",\n);\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { BRAND, isBranded, setBrand } from \"../brand.ts\";\nimport { rcError } from \"../error.ts\";\nimport { type Exchange, OperationType } from \"../exchange.ts\";\nimport { NESTED_STEPS, DEFER_HOST } from \"../dsl-symbol.ts\";\nimport type { Adapter, Step } from \"../types.ts\";\nimport type { RouteDefinition } from \"../route.ts\";\n\n/**\n * Where a `.defer()` sits in a route, and what runs when it is resumed.\n *\n * Resolved once at `craft().build()` time and stored on the route\n * definition, for one reason: execution two happens in a different process,\n * so the continuation cannot be a closure captured at defer time. It has\n * to be re-derivable from the route definition alone, and a site is exactly\n * that derivation.\n */\nexport interface DeferSite {\n  /**\n   * Stable address of the deferring step within the route.\n   *\n   * The index of the step in a pre-order walk of the route's step tree, not\n   * an index into `definition.steps`: a defer inside a `.choice()` branch\n   * is a real position that a flat index cannot name. Two processes running\n   * the same route source derive the same numbers, which is all the address\n   * has to guarantee. The record's `position` field carries it, and\n   * `position + 1` onward is {@link DeferSite.continuation}, except for a\n   * re-entrant site, whose continuation starts at `position` itself.\n   */\n  readonly position: number;\n  /**\n   * The steps that run on resume, flattened in execution order.\n   *\n   * For a defer on the main flow this is simply the steps after it. For a\n   * defer inside a `.choice()` branch it is the rest of that branch\n   * followed by the steps after the choice, which is the same sequence the\n   * executor would have run had the exchange never deferred (a matched branch\n   * rejoins the main flow).\n   *\n   * For a re-entrant site the continuation additionally INCLUDES the\n   * deferring step itself at its head, because the step must re-run to\n   * finish the work it deferred in the middle of. That head is therefore also\n   * covered by the continuation hash: editing a defer-capable step's own\n   * definition (an inline agent's options, say) invalidates its deferred\n   * exchanges, which is correct because that definition is what resumes.\n   */\n  readonly continuation: ReadonlyArray<Step<Adapter>>;\n  /**\n   * Resume re-enters the deferring step itself rather than the step after\n   * it. Set on sites assigned to defer-capable `.to()` / `.enrich()`\n   * steps; absent on static `.defer()` sites.\n   *\n   * Two consequences at revival, both deliberate: the payload is NOT\n   * validated against a live schema (the schema the step raised at defer\n   * time lives in its own code and cannot be read back off the route, so\n   * `RC5049` never fires for a re-entrant site and the step is the\n   * validator), and the stored schema descriptor is compared against\n   * itself, so a changed schema cannot be detected. Both are the same\n   * residue class as \"the hash covers step definitions, never the behaviour\n   * of what the tail calls\".\n   */\n  readonly reentrant?: boolean;\n}\n\n/**\n * Mark an adapter as able to raise a durable deferral from inside its own\n * execution (by throwing a `DeferSignal` from `fetch` / `send`). The\n * defer-site walk assigns `.to()` / `.enrich()` steps carrying a marked\n * adapter a re-entrant {@link DeferSite}.\n *\n * Core owns the brand; a consumer package (the agent tier is the shipped\n * case) marks its adapter with this helper and never mints its own symbol.\n */\nexport function markDeferCapable(adapter: Adapter): void {\n  setBrand(adapter, BRAND.DeferCapable);\n}\n\n/**\n * Whether an adapter was marked with {@link markDeferCapable}.\n *\n * @internal\n */\nexport function isDeferCapable(adapter: Adapter): boolean {\n  return isBranded(adapter, BRAND.DeferCapable);\n}\n\n/**\n * A `.to()` / `.enrich()` step that can host a re-entrant defer site.\n * The walk stores its verdict on the hosting instance, because that\n * instance's `execute` is where the defer signal is converted (before any\n * step-scope wrapper can observe the throw and, say, retry the step).\n *\n * @internal\n */\nexport interface DeferCapableStep extends Step<Adapter> {\n  /** Assigned by {@link resolveDeferSites} when the step sits on the primary flow. */\n  deferSite?: DeferSite;\n  /**\n   * Why no site was assigned, when the step sits somewhere a durable deferral\n   * cannot be revived from (inside a `.split()` fan-out, or a\n   * `.multicast()` path / `.dispatch()` target). Deferability of a\n   * capable step is dynamic, so the refusal cannot fail the build the way a\n   * static `.defer()` does; it fails the first actual deferral instead,\n   * with this message, as `RC5051`.\n   */\n  deferRefusal?: string;\n  /** Identity through wrappers: the instance the walk stores the site on. */\n  [DEFER_HOST](): DeferCapableStep | undefined;\n}\n\n/**\n * Resolve the defer-capable host of a step, looking through step-scope\n * wrappers (which forward {@link DEFER_HOST} like they forward\n * {@link NESTED_STEPS}). Returns undefined for steps that cannot host a\n * re-entrant site, which is every step other than `.to()` / `.enrich()`\n * (and a wrapper around one of those).\n *\n * @internal\n */\nexport function deferHostOf(step: Step<Adapter>): DeferCapableStep | undefined {\n  const resolve = (step as Partial<DeferCapableStep>)[DEFER_HOST];\n  return typeof resolve === \"function\"\n    ? resolve.call(step as DeferCapableStep)\n    : undefined;\n}\n\n/**\n * What a `defer` outcome hands the executor.\n *\n * The step resolves the pieces (its schema, its expiry, its site) and the\n * executor owns the effects (serialize, hash, store, emit), which keeps\n * every scheduling decision in one place, as with every other outcome kind.\n *\n * It lives here rather than beside the operation because `types.ts` names\n * it on the `StepOutcome` union, and `types.ts` is the dependency root: it\n * does not import from `operations/`.\n *\n * @internal\n */\nexport interface DeferRequest {\n  /**\n   * Live schema the eventual resume payload is validated against, when the site\n   * declared one. Absent defers with no ingress validation, which is the\n   * click-yes case: the route's own continuation is then the only reader of\n   * whatever arrives.\n   */\n  readonly schema?: StandardSchemaV1;\n  /** Resolved TTL in milliseconds, when one was declared. */\n  readonly expiresInMs?: number;\n  /**\n   * Whatever the deferring step attached at deferral. Persisted verbatim and\n   * handed to the resume route's `authorize` hook; never interpreted here.\n   */\n  readonly meta?: unknown;\n  /**\n   * Identity of the call this deferral belongs to, when the deferring step\n   * mints one credential per call. Persisted as the record's `callBinding`\n   * and carried as the token's `sub` claim.\n   */\n  readonly callBinding?: string;\n  /** Where this defer sits, and what runs on resume. */\n  readonly site: DeferSite;\n  /**\n   * Closure state owned by the deferring step, persisted in the record's\n   * `stepState` slot and handed back to a re-entrant step at revival. The\n   * store never interprets it; the plain-JSON rule (`RC5042`) applies.\n   */\n  readonly stepState?: unknown;\n}\n\n/**\n * A step that can defer the exchange. Implemented by the `.defer()` step;\n * declared here so the walk can recognise one without importing the\n * operation (which imports this module back).\n *\n * @internal\n */\nexport interface DeferrableStep extends Step<Adapter> {\n  readonly operation: OperationType.DEFER;\n  /**\n   * The live resume-payload schema, when the site declared one. Read back\n   * off the step at resume time to validate the submitted payload, because a\n   * Standard Schema cannot be persisted with the record.\n   */\n  readonly schema?: StandardSchemaV1;\n  /** Assigned by {@link resolveDeferSites}. Absent means the step is not reachable from a built route. */\n  site?: DeferSite;\n}\n\n/**\n * One nested sub-pipeline of a step, as reported through\n * {@link NESTED_STEPS}.\n *\n * `rejoins` is the load-bearing field. A `.choice()` branch flows back into\n * the main pipeline when it matches, so a defer inside one has a\n * well-defined continuation that spans the branch tail and the main tail. A\n * `.multicast()` path or a `.dispatch()` target runs as an isolated nested\n * pipeline whose exchange is not the route's primary flow, so there is no\n * such continuation and a defer inside one is refused.\n */\nexport interface NestedSteps {\n  readonly steps: ReadonlyArray<Step<Adapter>>;\n  readonly rejoins: boolean;\n  /**\n   * The predicate that selects this sub-pipeline, when one does (a\n   * `.choice()` branch). It decides which branch shapes the body, so a\n   * fingerprint of the pipeline has to see it.\n   */\n  readonly predicate?: (exchange: Exchange) => boolean;\n}\n\n/** A step that carries nested sub-pipelines. @internal */\ninterface NestingStep extends Step<Adapter> {\n  [NESTED_STEPS](): ReadonlyArray<NestedSteps>;\n}\n\n/**\n * What {@link resolveDeferSites} resolves for one route: the static\n * `.defer()` steps, and the defer-capable `.to()` / `.enrich()` steps\n * that were assigned a re-entrant site. The two lists are kept apart\n * because they answer different questions: static sites are what the\n * startup runtime check (`RC5052`) and the route-scope cache refusal key\n * on, while re-entrant sites only say a step MAY defer at runtime.\n *\n * @internal\n */\nexport interface ResolvedDeferSites {\n  deferSteps: DeferrableStep[];\n  reentrantDeferSteps: DeferCapableStep[];\n}\n\n/**\n * Whether a built route can raise a durable deferral: statically (a\n * declared `.defer()`) or at runtime (a defer-capable step that MAY\n * defer). The predicate transports key on to advertise a `Deferred`\n * acknowledgment arm, owned here next to the fields it reads so a new way\n * for a route to defer updates every consumer in one edit.\n */\nexport function routeCanDefer(definition: RouteDefinition): boolean {\n  return (\n    (definition.deferSteps?.length ?? 0) > 0 ||\n    (definition.reentrantDeferSteps?.length ?? 0) > 0\n  );\n}\n\n/**\n * Resolve every defer site in a route, refusing the positions where a\n * durable deferral cannot be revived.\n *\n * Runs at build time so an incoherent route fails on the deploy that\n * introduced it rather than on the first large payout. Assigns each\n * deferring step its {@link DeferSite} as a side effect, because the\n * step is what the executor holds when the outcome comes back.\n *\n * A static `.defer()` in an unrevivable position fails the build; a\n * defer-capable step there gets a stored refusal instead, because whether\n * it ever defers is dynamic, and refusing the build would reject every\n * route that fans an agent out over a split whether or not any tool defers.\n * The refusal carries the same explanation and fires as `RC5051` on the\n * first actual deferral.\n *\n * @param route - A finalised route definition\n * @returns The static defer steps and the re-entrant hosts, in pre-order,\n *   each carrying the site (or refusal) it was assigned\n * @throws RC5051 when a `.defer()` sits somewhere it cannot be revived\n *   from: inside a `.split()` fan-out (balanced or not), or inside a\n *   `.multicast()` path or `.dispatch()` target.\n *\n * @internal\n */\nexport function resolveDeferSites(route: RouteDefinition): ResolvedDeferSites {\n  const found: ResolvedDeferSites = {\n    deferSteps: [],\n    reentrantDeferSteps: [],\n  };\n  const counter = { next: 0 };\n  walk(route, route.steps, [], found, counter, {\n    splitDepth: 0,\n    sealed: false,\n  });\n  return found;\n}\n\n/**\n * Whether a route can reach a `.resume()`.\n *\n * A resume ingress needs the deferral runtime just as much as a\n * deferring route does: it verifies tokens against the signer and reads\n * the store. Without this a resume-only deployment (the common shape, since\n * the ingress is usually its own capability) starts clean and then refuses\n * every resume at request time, which is the failure the startup check\n * exists to move forward.\n *\n * @internal\n */\nexport function usesResume(route: RouteDefinition): boolean {\n  return containsResume(route.steps);\n}\n\n/** @internal */\nfunction containsResume(steps: ReadonlyArray<Step<Adapter>>): boolean {\n  return steps.some(\n    (step) =>\n      step.operation === OperationType.RESUME ||\n      nestedStepsOf(step).some((nested) => containsResume(nested.steps)),\n  );\n}\n\n/**\n * Walk a step array in execution order, assigning positions and sites.\n *\n * @param tail - Steps that run after this array finishes, already flattened.\n *   A branch inherits the tail of the step that contains it, which is what\n *   makes a branch-local continuation span the main flow too.\n * @param scope - `splitDepth` counts `.split()` calls not yet balanced by an\n *   `.aggregate()`; `sealed` marks a sub-pipeline that never rejoins.\n *\n * @internal\n */\nfunction walk(\n  route: RouteDefinition,\n  steps: ReadonlyArray<Step<Adapter>>,\n  tail: ReadonlyArray<Step<Adapter>>,\n  found: ResolvedDeferSites,\n  counter: { next: number },\n  scope: { splitDepth: number; sealed: boolean },\n): void {\n  let splitDepth = scope.splitDepth;\n  for (let i = 0; i < steps.length; i++) {\n    const step = steps[i]!;\n    const position = counter.next++;\n    const after = [...steps.slice(i + 1), ...tail];\n\n    if (step.operation === OperationType.SPLIT) splitDepth++;\n    else if (step.operation === OperationType.AGGREGATE && splitDepth > 0) {\n      splitDepth--;\n    }\n\n    if (step.operation === OperationType.DEFER) {\n      if (splitDepth > 0) {\n        throw refuse(route.id, \"split\");\n      }\n      if (scope.sealed) {\n        throw refuse(route.id, \"sealed\");\n      }\n      const defer = step as DeferrableStep;\n      defer.site = { position, continuation: after };\n      found.deferSteps.push(defer);\n      continue;\n    }\n\n    const host = deferHostOf(step);\n    if (host && isDeferCapable(step.adapter)) {\n      // The same positions a static `.defer()` is refused from, with the\n      // same reasons, but recorded rather than thrown: whether a capable\n      // step ever defers is dynamic, so the refusal fires as RC5051 on\n      // the first actual deferral instead of failing every route that\n      // merely places an agent inside a fan-out or a side flow.\n      // A rebuilt walk starts every host clean so a stale field from an\n      // earlier resolution can never outrank the fresh one.\n      delete host.deferRefusal;\n      delete host.deferSite;\n      if (splitDepth > 0) {\n        host.deferRefusal = unrevivablePosition(route.id, \"split\", \"raised\");\n      } else if (scope.sealed) {\n        host.deferRefusal = unrevivablePosition(route.id, \"sealed\", \"raised\");\n      } else {\n        // The step itself heads the continuation: a re-entrant resume runs\n        // the step again to finish the work it deferred in the middle of.\n        host.deferSite = {\n          position,\n          continuation: [step, ...after],\n          reentrant: true,\n        };\n        found.reentrantDeferSteps.push(host);\n      }\n    }\n\n    const nested = nestedStepsOf(step);\n    // Presence of the protocol, not emptiness of its answer: a\n    // `.multicast()` with zero paths legitimately reports none, while a\n    // step that never implemented the protocol reports none for the very\n    // reason this check exists.\n    if (!answersNestedSteps(step) && NESTING_OPERATIONS.has(step.operation)) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          `Route \"${route.id}\" has a \"${step.operation}\" step that does not report its sub-pipelines, ` +\n          `so the framework cannot see what is inside it. A step carrying sub-pipelines must implement ` +\n          `the NESTED_STEPS protocol, and a wrapper around one must forward it.`,\n      });\n    }\n    for (const branch of nested) {\n      walk(route, branch.steps, branch.rejoins ? after : [], found, counter, {\n        splitDepth,\n        sealed: scope.sealed || !branch.rejoins,\n      });\n    }\n  }\n}\n\n/**\n * Sub-pipelines a step carries, or none.\n *\n * @internal\n */\nexport function nestedStepsOf(step: Step<Adapter>): ReadonlyArray<NestedSteps> {\n  const nesting = (step as Partial<NestingStep>)[NESTED_STEPS];\n  return typeof nesting === \"function\" ? nesting.call(step as NestingStep) : [];\n}\n\n/**\n * Whether a step implements the {@link NESTED_STEPS} protocol at all.\n *\n * @internal\n */\nfunction answersNestedSteps(step: Step<Adapter>): boolean {\n  return typeof (step as Partial<NestingStep>)[NESTED_STEPS] === \"function\";\n}\n\n/**\n * Operations that MUST answer the {@link NESTED_STEPS} protocol.\n *\n * The protocol is opt-in, and an opt-in protocol fails silently: a step\n * that carries sub-pipelines but does not implement it makes everything\n * inside it invisible to this walk, so a `.defer()` in there is refused\n * at runtime (after the approver was notified) rather than at build time,\n * and the route-scope cache and startup-runtime checks silently pass.\n *\n * Listing the operations that carry sub-pipelines turns that silent hole\n * into a loud one: a new nesting operation, or a wrapper that stops\n * forwarding, fails the build of any route using it rather than the resume\n * of one exchange.\n *\n * @internal\n */\nconst NESTING_OPERATIONS: ReadonlySet<OperationType> = new Set([\n  OperationType.CHOICE,\n  OperationType.MULTICAST,\n  OperationType.DISPATCH,\n]);\n\n/** @internal */\nfunction refuse(routeId: string, position: \"split\" | \"sealed\"): Error {\n  return rcError(\"RC5051\", undefined, {\n    message: unrevivablePosition(routeId, position, \"declares\"),\n  });\n}\n\n/**\n * One fact, two raisers: the positions a durable deferral cannot be\n * revived from, phrased for whichever site reports it. The build-time throw\n * (a static `.defer()`) and the recorded runtime refusal (a\n * defer-capable step, RC5051 on its first actual deferral) must never\n * drift into telling users different stories about the same constraint, so\n * both render from here.\n *\n * @internal\n */\nfunction unrevivablePosition(\n  routeId: string,\n  position: \"split\" | \"sealed\",\n  form: \"declares\" | \"raised\",\n): string {\n  const subject =\n    form === \"declares\" ? \"declares a .defer()\" : \"raised a durable deferral\";\n  const mover = form === \"declares\" ? \"the defer\" : \"the deferring step\";\n  const body =\n    position === \"split\"\n      ? `inside a .split() fan-out, between the split and its .aggregate(). Reviving one deferred child would mean tracking every outstanding sibling across restarts, which is a distributed coordination problem in disguise. Move ${mover} out of the fan-out, or split the work into per-item child capabilities: each is then its own exchange and defers independently.`\n      : `inside a .multicast() path or .dispatch() target. Those exchanges are isolated side flows rather than the route's primary flow, so a resumed continuation would have nowhere to rejoin. Move ${mover} onto the main flow, or onto a .choice() branch of it.`;\n  return `Route \"${routeId}\" ${subject} ${body}`;\n}\n","import {\n  type Exchange,\n  getExchangeContext,\n  getExchangeRoute,\n  HeadersKeys,\n  type OperationType,\n} from \"../exchange.ts\";\nimport type { CraftContext } from \"../context.ts\";\nimport type { Route } from \"../route.ts\";\n\n/**\n * Per-exchange event-scope bindings shared by every resilience wrapper's\n * `runInner`. Derives the route, context, route id, step label, and\n * correlation id once so the wrappers (`.delay()`, `.timeout()`,\n * `.retry()`, `.throttle()`, `.cache()`) stop hand-rolling the same six\n * lines.\n *\n * Returned for DESTRUCTURING rather than as a ready-made `shouldEmit`\n * flag on purpose: the caller keeps its own\n * `const shouldEmit = route && context && routeId`, which lets\n * TypeScript's aliased-condition narrowing prove `context` is defined\n * inside the emit guard. A boolean returned from here would not narrow\n * the separately-returned `context`, forcing every call site to\n * re-assert it.\n *\n * @param exchange Live exchange whose internals carry the route / context.\n * @param step The wrapper step; `label` and `operation` form the display\n *   label.\n * @returns The scope bindings. `route` / `context` are `undefined` when the\n *   exchange has no attached route (e.g. a step run in isolation), so the\n *   caller's `shouldEmit` is falsy and no events fire. `routeId` falls back\n *   to the `routecraft.route` header (always populated by the\n *   `DefaultExchange` constructor) so flow-control operations that emit\n *   with only a context binding still carry a stable id.\n * @internal\n */\nexport function wrapperEventScope(\n  exchange: Exchange,\n  step: { label?: string; operation: OperationType },\n): {\n  route: Route | undefined;\n  context: CraftContext | undefined;\n  routeId: string;\n  stepLabel: string;\n  correlationId: string;\n} {\n  const route = getExchangeRoute(exchange);\n  return {\n    route,\n    context: getExchangeContext(exchange),\n    routeId:\n      route?.definition.id ??\n      (exchange.headers[HeadersKeys.ROUTE_ID] as string),\n    stepLabel: step.label ?? String(step.operation),\n    correlationId: exchange.headers[HeadersKeys.CORRELATION_ID] as string,\n  };\n}\n","/**\n * Sentinel error rejected by {@link cancellableSleep} when the supplied\n * signal aborts before the timer fires. Callers catch it to tell an\n * orderly shutdown apart from a real failure; it never escapes the\n * framework's resilience wrappers.\n *\n * @internal\n */\nexport class SleepAbortedError extends Error {\n  constructor() {\n    super(\"routecraft.sleep.aborted\");\n    this.name = \"SleepAbortedError\";\n  }\n}\n\n/**\n * Sleep for `ms` milliseconds, rejecting early with\n * {@link SleepAbortedError} the moment `signal` aborts. The pending\n * timer is cleared on abort so a shutting-down route leaks no timers\n * and never waits out a delay or retry backoff it no longer needs.\n *\n * Shared by the resilience wrappers: `.delay()` (the wait itself),\n * `.retry()` (the backoff between attempts), and `.throttle()`\n * (the pacing wait). Route shutdown exposes the signal via\n * `Route.signal`.\n *\n * @param ms - Milliseconds to wait\n * @param signal - Optional abort signal that cancels the wait\n * @internal\n */\nexport function cancellableSleep(\n  ms: number,\n  signal?: AbortSignal,\n): Promise<void> {\n  return new Promise((resolve, reject) => {\n    if (signal?.aborted) {\n      reject(new SleepAbortedError());\n      return;\n    }\n    const onAbort = () => {\n      clearTimeout(timer);\n      reject(new SleepAbortedError());\n    };\n    const timer = setTimeout(() => {\n      signal?.removeEventListener(\"abort\", onAbort);\n      resolve();\n    }, ms);\n    signal?.addEventListener(\"abort\", onAbort, { once: true });\n  });\n}\n","import { rcError } from \"../error.ts\";\n\n/**\n * Default cap on distinct keys tracked by a keyed in-memory operation (the\n * `.throttle({ key })` per-key buckets, the `.dedupe()` committed-key set).\n */\nexport const DEFAULT_MAX_KEYS = 10_000;\n\n/**\n * Hard ceiling on `maxKeys`. The per-key LRU pre-allocates index arrays sized\n * to its `max`, so this bounds the eager allocation a single keyed operation\n * can trigger and stops an absurd value from OOMing the process at build time.\n */\nexport const MAX_KEYS_CEILING = 1_000_000;\n\n/**\n * Validate a user-supplied `maxKeys` against the shared bound, throwing\n * `RC5003` at build time so a typo fails when the route is built rather than\n * allocating an oversized index array at runtime. `op` names the operation for\n * the error message (e.g. `\"throttle\"`, `\"dedupe\"`).\n *\n * @internal\n */\nexport function validateMaxKeys(op: string, maxKeys: number): void {\n  if (!Number.isInteger(maxKeys) || maxKeys < 1 || maxKeys > MAX_KEYS_CEILING) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `${op}({ maxKeys }) must be an integer between 1 and ${MAX_KEYS_CEILING}, got ${String(maxKeys)}.`,\n    });\n  }\n}\n","import type { Route } from \"../route.ts\";\n\n/**\n * Base for a stateful operation that holds one piece of state PER ROUTE.\n *\n * A single step (or controller) instance is built once per `RouteDefinition`,\n * but that definition can be registered into multiple contexts, producing\n * several live `Route` instances. Keying the state by `Route` in a WeakMap\n * gives each Route its OWN state, so the contexts cannot cross-contaminate\n * each other (cross-sample, cross-suppress, cross-trip, cross-rate-limit).\n * A single `#routeless` fallback covers the route-less case (a step run in\n * isolation, e.g. a unit test) so behaviour stays bounded there too.\n *\n * Subclasses provide {@link createState}; the per-route lookup and lazy\n * creation live here once rather than being re-implemented per operation.\n *\n * @internal\n */\nexport abstract class RouteScopedController<S> {\n  readonly #byRoute = new WeakMap<Route, S>();\n  #routeless?: S;\n\n  /**\n   * Build a fresh state instance. Called at most once per Route (and once\n   * for the route-less fallback), on first use.\n   */\n  protected abstract createState(): S;\n\n  /**\n   * Resolve the state for `route`, creating it on first use; or the shared\n   * route-less instance when no Route is attached.\n   */\n  stateFor(route: Route | undefined): S {\n    if (!route) return (this.#routeless ??= this.createState());\n    let state = this.#byRoute.get(route);\n    if (state === undefined) {\n      state = this.createState();\n      this.#byRoute.set(route, state);\n    }\n    return state;\n  }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { CraftContext } from \"../context.ts\";\nimport {\n  type Exchange,\n  type ExchangeHeaders,\n  HeadersKeys,\n  DefaultExchange,\n  markOutputValidated,\n} from \"../exchange.ts\";\nimport { rcError, formatSchemaIssues } from \"../error.ts\";\nimport { isThenable } from \"../shared/thenable.ts\";\nimport type { ErrorHandler, ForwardFn, Route } from \"../route.ts\";\n\n/**\n * Dependencies the validation helpers need from the owning route. Passed\n * explicitly so the helpers are free functions (moved verbatim from\n * DefaultRoute private methods; only `this.*` references became `deps.*`).\n */\nexport interface ValidationDeps {\n  routeId: string;\n  context: CraftContext;\n  /** The owning route, surfaced on validation event payloads. */\n  route: Route;\n  errorHandler?: ErrorHandler;\n  /** Build a forward callable whose target inherits `caller`'s headers. */\n  buildForward: (caller: Exchange) => ForwardFn;\n}\n\n/**\n * Run Standard Schema validation against a value. Returns the validated\n * value on success (schemas can legitimately transform to `undefined`,\n * so presence of the `value` key is what decides success, not truthiness)\n * or a human-readable message on failure.\n *\n * Exported for adapter and plugin authors who validate at a protocol\n * boundary and need the failure as a message to hand back over the wire\n * rather than as a thrown error.\n *\n * The validated value carries the schema's output type, which for a\n * transforming schema is not the type that went in. `issues` accompanies\n * `message` so a caller can build a structured rejection (a JSON-RPC\n * `error.data`, an HTTP 422 field map) instead of only a sentence.\n *\n * Standard Schema allows `validate()` to return a thenable rather than a\n * real `Promise`, so awaiting one runs schema-author `then` code on this\n * path: a schema that never settles hangs the validation instead of\n * silently passing, which is the safer of the two failures. Nothing bounds\n * that wait. `.input()` is position #4 of the pre-from chain and `.timeout()`\n * is #8, so a route timeout sits below validation and cannot reclaim it.\n *\n * `schema` is assumed to carry a callable `~standard.validate`; this helper\n * dereferences it unguarded, so a caller holding a value from configuration\n * checks that first and chooses its own refusal.\n *\n * @param schema - The Standard Schema to validate with\n * @param value - The value to validate\n * @returns `{ ok: true, value }` with the validated (possibly transformed)\n *   value, or `{ ok: false, message, issues }` with the failure both\n *   formatted and raw. A schema that returns something other than a result\n *   record fails the same way, with an empty `issues` and a message naming\n *   what came back\n *\n * @example\n * ```ts\n * const result = await validateAgainst(schema, exchange.body);\n * if (!result.ok) return { isError: true, message: result.message };\n * ```\n */\nexport async function validateAgainst<S extends StandardSchemaV1>(\n  schema: S,\n  value: unknown,\n): Promise<\n  | { ok: true; value: StandardSchemaV1.InferOutput<S> }\n  | {\n      ok: false;\n      message: string;\n      issues: readonly StandardSchemaV1.Issue[];\n    }\n> {\n  let result: unknown = schema[\"~standard\"].validate(value);\n  if (isThenable(result)) result = await result;\n  // After the await, so a sync schema, a thenable and a real `Promise` are\n  // held to the same contract. A non-record fails three ways: `undefined`\n  // and `null` die on the `issues` read, a primitive survives that and dies\n  // on `\"value\" in successResult`, and an array clears both (it is a\n  // non-null `object`) to reach the input fallback and report success on\n  // unvalidated input. The message is written out rather than routed through\n  // `formatSchemaIssues`, which renders an empty issue list as \"[]\".\n  if (typeof result !== \"object\" || result === null || Array.isArray(result)) {\n    return {\n      ok: false,\n      message: `schema returned a malformed result: expected an object, received ${\n        Array.isArray(result)\n          ? \"array\"\n          : result === null\n            ? \"null\"\n            : typeof result\n      }`,\n      issues: [],\n    };\n  }\n  const issues = (result as { issues?: unknown }).issues;\n  if (issues !== undefined && issues !== null) {\n    return {\n      ok: false,\n      message: formatSchemaIssues(issues),\n      // A non-array `issues` breaks the spec; report the failure without them.\n      issues: Array.isArray(issues)\n        ? (issues as readonly StandardSchemaV1.Issue[])\n        : [],\n    };\n  }\n  const successResult = result as { value?: unknown };\n  return {\n    ok: true,\n    value: (\"value\" in successResult\n      ? successResult.value\n      : value) as StandardSchemaV1.InferOutput<S>,\n  };\n}\n\n/**\n * The route's terminal output stage: enforce `.output()` schemas on a run\n * that produced the route's output, or pass the result through untouched\n * when it did not.\n *\n * One implementation because there are two callers with identical rules\n * (`DefaultRoute.handler` for a source-driven run, `runDetachedPipeline`\n * for a debounce release or a resumed continuation), and the defer work\n * proved they drift: both had to grow the same `deferred` exemption in\n * the same shape. A third terminal state, or any change to the failure\n * path, now lands once.\n *\n * A failed, dropped, or deferred run is exempt. The first two never produced\n * an output; the third produced the `Deferred` acknowledgment, which is\n * deliberately not the declared output but the other arm of the route's\n * `Output | Deferred` type.\n *\n * @param deps - Route identity plus the route-scope error handler\n * @param schemas - The route's declared output schemas, if any\n * @param result - The run's result\n * @param startTime - Run start, for the failure path's duration\n * @returns The result, with a validated exchange or a failure recorded\n *\n * @internal\n */\nexport async function applyOutputStage<\n  R extends {\n    exchange: Exchange;\n    failed: boolean;\n    dropped: boolean;\n    deferred: boolean;\n    error?: unknown;\n  },\n>(\n  deps: ValidationDeps,\n  schemas: { body?: StandardSchemaV1; headers?: StandardSchemaV1 } | undefined,\n  result: R,\n  startTime: number,\n): Promise<R> {\n  if (result.failed || result.dropped || result.deferred) return result;\n  if (!schemas?.body && !schemas?.headers) return result;\n  try {\n    return {\n      ...result,\n      exchange: await applyOutputValidation(deps, result.exchange, schemas),\n    };\n  } catch (err) {\n    return {\n      ...result,\n      // `deferred` is false by construction: this arm only runs for a\n      // result that reached validation.\n      ...(await handleOutputValidationFailure(\n        deps,\n        result.exchange,\n        err,\n        startTime,\n        schemas,\n      )),\n    };\n  }\n}\n\n/**\n * Machine-readable detail attached to an `RC5065` error's cause: which part\n * of the input failed the route's `.input()` schema, and the schema's own\n * issues. Read it off `error.cause` through {@link isInputValidationFailure}\n * to build a structured rejection instead of parsing the message:\n *\n * ```ts\n * if (isInputValidationFailure(err.cause)) {\n *   for (const issue of err.cause.invalid.issues) report(issue.path, issue.message)\n * }\n * ```\n *\n * The http doors (the `http()` source and the ops dispatch mount) send\n * `in` and each issue's path and message to the caller, so issue messages\n * are client-facing: a schema author's custom message reaches the wire\n * verbatim.\n *\n * In-process only, like `InsufficientAuthority`: `RoutecraftError.toJSON()`\n * serialises the cause's message and stack, not its own properties.\n */\nexport interface InputValidationFailure extends Error {\n  invalid: {\n    /** Which part of the input the schema refused. */\n    in: \"body\" | \"headers\";\n    /** The schema's issues, as it returned them. */\n    issues: readonly StandardSchemaV1.Issue[];\n    /**\n     * The route whose `.input()` refused. A route calling another through\n     * `direct()` receives the callee's RC5065 as its own step failure, and\n     * what the callee refused was the caller route's output, not input\n     * anyone outside supplied.\n     */\n    routeId: string;\n  };\n}\n\n/**\n * Whether `value` (typically an RC5065 error's `cause`) carries the\n * {@link InputValidationFailure} detail.\n *\n * @param value - Any value, usually `error.cause`\n * @returns `true` when the value is an Error carrying a well-formed `invalid` detail\n */\nexport function isInputValidationFailure(\n  value: unknown,\n): value is InputValidationFailure {\n  return (\n    value instanceof Error &&\n    isValidationDetail((value as { invalid?: unknown }).invalid)\n  );\n}\n\nfunction isValidationDetail(detail: unknown): boolean {\n  if (typeof detail !== \"object\" || detail === null) return false;\n  const fields = detail as Record<string, unknown>;\n  return (\n    (fields[\"in\"] === \"body\" || fields[\"in\"] === \"headers\") &&\n    Array.isArray(fields[\"issues\"]) &&\n    typeof fields[\"routeId\"] === \"string\"\n  );\n}\n\n/**\n * Machine-readable detail attached to the cause of an error raised because a\n * result broke its declared output schema: which part failed, the schema's\n * own issues, and the route or tool. Read it off `error.cause` through\n * {@link isOutputValidationFailure}.\n *\n * Two checks attach it: a route's `.output()` (`RC5002`) and the MCP\n * server's check of a tool result against the `outputSchema` it advertised\n * (`AI2001`, for a tool the pipeline did not validate). `RC5002` also covers\n * a mid-pipeline `.validate()` and an empty aggregation, whose causes carry\n * no such detail, so its presence is what tells a door the result broke a\n * declared contract. The MCP server sends the body issues to the caller,\n * because the tool advertised that schema.\n *\n * In-process only, like {@link InputValidationFailure}.\n */\nexport interface OutputValidationFailure extends Error {\n  invalidOutput: {\n    /** Which part of the result the schema refused. */\n    in: \"body\" | \"headers\";\n    /** The schema's issues, as it returned them. */\n    issues: readonly StandardSchemaV1.Issue[];\n    /**\n     * The route whose `.output()` refused, or the tool whose advertised\n     * schema refused. A route calling another through `direct()` receives\n     * the callee's RC5002 as its own step failure.\n     */\n    routeId: string;\n  };\n}\n\n/**\n * Whether `value` (typically an RC5002 error's `cause`) carries the\n * {@link OutputValidationFailure} detail.\n *\n * @param value - Any value, usually `error.cause`\n * @returns `true` when the value is an Error carrying a well-formed `invalidOutput` detail\n */\nexport function isOutputValidationFailure(\n  value: unknown,\n): value is OutputValidationFailure {\n  return (\n    value instanceof Error &&\n    isValidationDetail((value as { invalidOutput?: unknown }).invalidOutput)\n  );\n}\n\n/**\n * The cause of an output RC5002. A schema that failed without issues broke\n * its own contract rather than the route's output, so it gets no detail and\n * no door reports it as a declared-schema violation.\n */\nfunction outputValidationFailure(\n  message: string,\n  part: \"body\" | \"headers\",\n  issues: readonly StandardSchemaV1.Issue[],\n  routeId: string,\n): Error {\n  const cause = new Error(message);\n  return issues.length === 0\n    ? cause\n    : Object.assign(cause, { invalidOutput: { in: part, issues, routeId } });\n}\n\n/**\n * Validate an exchange against the route's `input` schemas, throwing\n * `RC5065` on failure without emitting any lifecycle events: the caller\n * is a chain step inside `runPipeline`, so the failure becomes a normal\n * step failure (`route:step:failed` -> the error-handler-or-failed path).\n *\n * The error's cause is an {@link InputValidationFailure} naming the part\n * that failed and the schema's issues, unless the schema failed without\n * any, which is the schema's fault and carries no detail.\n *\n * On success returns a (possibly new) exchange with validated / coerced\n * values; validated headers are merged over the originals so caller\n * pass-through keys (correlation IDs, adapter-injected metadata) survive\n * schemas that strip unknowns.\n *\n * Used by the synthetic parse step (input validates the parsed body) and\n * by the standalone synthetic input step for parser-less sources; both\n * paths sit at chain position #4, so `.error()` can recover an RC5065 for\n * every source shape (see #187, #447).\n */\nexport async function validateInputOrThrow(\n  deps: ValidationDeps,\n  exchange: Exchange,\n  schemas: { body?: StandardSchemaV1; headers?: StandardSchemaV1 },\n): Promise<Exchange> {\n  let current = exchange;\n  if (schemas.body) {\n    const res = await validateAgainst(schemas.body, current.body);\n    if (!res.ok) {\n      throw rcError(\n        \"RC5065\",\n        inputValidationFailure(res.message, \"body\", res.issues, deps.routeId),\n        {\n          message: `Body validation failed for route \"${deps.routeId}\": ${res.message}`,\n        },\n      );\n    }\n    current = DefaultExchange.rewrap(current, { body: res.value });\n  }\n  if (schemas.headers) {\n    const res = await validateAgainst(schemas.headers, current.headers);\n    if (!res.ok) {\n      throw rcError(\n        \"RC5065\",\n        inputValidationFailure(\n          res.message,\n          \"headers\",\n          res.issues,\n          deps.routeId,\n        ),\n        {\n          message: `Header validation failed for route \"${deps.routeId}\": ${res.message}`,\n        },\n      );\n    }\n    const headerValue = res.value as ExchangeHeaders | undefined;\n    if (headerValue !== undefined) {\n      current = DefaultExchange.rewrap(current, {\n        headers: { ...current.headers, ...headerValue },\n      });\n    }\n  }\n  return current;\n}\n\n/**\n * The cause of an RC5065. A schema that failed without issues broke its own\n * contract rather than refused the caller, so it gets no detail and no door\n * answers it as a caller refusal.\n */\nfunction inputValidationFailure(\n  message: string,\n  part: \"body\" | \"headers\",\n  issues: readonly StandardSchemaV1.Issue[],\n  routeId: string,\n): Error {\n  const cause = new Error(message);\n  return issues.length === 0\n    ? cause\n    : Object.assign(cause, { invalid: { in: part, issues, routeId } });\n}\n\n/**\n * Handle an output-validation failure. Delegates to the route's error\n * handler when one is configured (mirroring how step errors recover);\n * otherwise emits `route:exchange:failed` and returns a failed result so the\n * caller can surface the error.\n */\nexport async function handleOutputValidationFailure(\n  deps: ValidationDeps,\n  exchange: Exchange,\n  error: unknown,\n  startTime: number,\n  schemas: { body?: StandardSchemaV1; headers?: StandardSchemaV1 },\n): Promise<{\n  exchange: Exchange;\n  failed: boolean;\n  dropped: boolean;\n  error?: unknown;\n}> {\n  const routeId = deps.routeId;\n  const correlationId = exchange.headers[HeadersKeys.CORRELATION_ID] as string;\n\n  deps.context.emit(\"route:step:error\", {\n    routeId,\n    error,\n    route: deps.route,\n    exchange,\n    operation: \"output\",\n  });\n\n  if (deps.errorHandler) {\n    try {\n      const forward = deps.buildForward(exchange);\n      const recovered = await deps.errorHandler(error, exchange, forward);\n      // Re-validate the recovered body against the same output schemas\n      // before declaring success. Without this, an `errorHandler` that\n      // returns another invalid payload would silently bypass the\n      // route's `.output()` contract and flow out via\n      // `route:exchange:completed`. A second failure here cascades through\n      // the existing handlerErr branch so the failure surfaces the\n      // same way (`route:exchange:failed` plus the failure result).\n      const recoveredExchange = await applyOutputValidation(\n        deps,\n        DefaultExchange.rewrap(exchange, { body: recovered }),\n        schemas,\n      );\n      deps.context.emit(\"route:error:caught\", {\n        routeId,\n        error,\n        route: deps.route,\n        exchange: recoveredExchange,\n      });\n      return { exchange: recoveredExchange, failed: false, dropped: false };\n    } catch (handlerErr) {\n      deps.context.emit(\"route:exchange:failed\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        duration: Date.now() - startTime,\n        error: handlerErr,\n        exchange,\n      });\n      return { exchange, failed: true, dropped: false, error: handlerErr };\n    }\n  }\n\n  deps.context.emit(\"route:exchange:failed\", {\n    routeId,\n    exchangeId: exchange.id,\n    correlationId,\n    duration: Date.now() - startTime,\n    error,\n    exchange,\n  });\n  return { exchange, failed: true, dropped: false, error };\n}\n\n/**\n * Validate the final exchange against the route's `output` schemas.\n * On success returns the validated (possibly new) exchange. On failure\n * throws an RC5002 error so the normal error / error-handler flow takes\n * over.\n */\nexport async function applyOutputValidation(\n  deps: ValidationDeps,\n  exchange: Exchange,\n  schemas: { body?: StandardSchemaV1; headers?: StandardSchemaV1 },\n): Promise<Exchange> {\n  let current = exchange;\n  if (schemas.body) {\n    const res = await validateAgainst(schemas.body, current.body);\n    if (!res.ok) {\n      throw rcError(\n        \"RC5002\",\n        outputValidationFailure(res.message, \"body\", res.issues, deps.routeId),\n        {\n          message: `Output body validation failed for route \"${deps.routeId}\"`,\n        },\n      );\n    }\n    current = DefaultExchange.rewrap(current, { body: res.value });\n    markOutputValidated(current, schemas.body);\n  }\n  if (schemas.headers) {\n    const res = await validateAgainst(schemas.headers, current.headers);\n    if (!res.ok) {\n      throw rcError(\n        \"RC5002\",\n        outputValidationFailure(\n          res.message,\n          \"headers\",\n          res.issues,\n          deps.routeId,\n        ),\n        {\n          message: `Output header validation failed for route \"${deps.routeId}\"`,\n        },\n      );\n    }\n    const headerValue = res.value as ExchangeHeaders | undefined;\n    if (headerValue !== undefined) {\n      current = DefaultExchange.rewrap(current, {\n        headers: { ...current.headers, ...headerValue },\n      });\n    }\n  }\n  return current;\n}\n","/**\n * Recognising a promise by contract rather than by class.\n *\n * Standard Schema says `validate()` returns a result or a promise of one,\n * and JavaScript says \"promise\" is anything with a callable `then`, not\n * only an instance of `Promise`. The two diverge for a thenable a library\n * hand-rolls, and for a genuine native `Promise` built in another realm,\n * which fails `instanceof` in this one. Gating on the class misses both\n * (#545), so every site that has to decide \"is this asynchronous\" tests\n * for `then`.\n *\n * Core-internal on purpose: this is plumbing, and\n * `DEFINITION_OF_DONE.md` bars new `@internal` symbols from the public\n * entry point. `@routecraft/ai` cannot reach this module across the\n * package boundary and keeps its own copy at the AI SDK seam.\n */\n\n/**\n * Whether a value is thenable, and so must be awaited or adapted before\n * its settled value can be read.\n *\n * A thenable is not necessarily a `Promise`, so it carries no `catch` or\n * `finally`. Normalise with `Promise.resolve(value)` before reaching for\n * either.\n *\n * @internal\n */\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n  return typeof (value as { then?: unknown } | null)?.then === \"function\";\n}\n","/**\n * Composing cancellation scopes.\n *\n * A step can be cancelled by more than one owner: the route stopping, an\n * enclosing `.timeout()` expiring, a client disconnecting, a credential\n * reaching its expiry. Each site that needs the union was deciding three\n * things for itself, and the sites had already drifted on the third: filter\n * out the absent signals, avoid allocating for the single-signal case, and\n * answer what \"no owner at all\" means. This is the one answer.\n */\n\n/**\n * A signal that never fires, for a composition with no owners.\n *\n * Shared rather than allocated per call: a caller holding it must see the\n * same never-aborting signal every other caller does, and an allocation per\n * request would be a controller per request that nothing ever aborts.\n */\nconst NEVER_ABORTED = new AbortController().signal;\n\n/**\n * Compose cancellation scopes into one signal.\n *\n * Absent signals are ignored, so a caller passes its optional owners\n * positionally without pre-filtering. With no present signal the result\n * never aborts, which is the honest reading of \"nothing can cancel this\"\n * and is what every call site previously spelled differently.\n *\n * @param signals - Cancellation owners, any of which may be absent\n * @returns The union: aborts when the first present signal aborts\n */\nexport function anySignal(\n  ...signals: readonly (AbortSignal | undefined)[]\n): AbortSignal {\n  const present = signals.filter((s): s is AbortSignal => s !== undefined);\n  if (present.length === 0) return NEVER_ABORTED;\n  return present.length === 1 ? present[0]! : AbortSignal.any(present);\n}\n","import type { CraftContext } from \"../context.ts\";\nimport { anySignal } from \"../shared/abort.ts\";\nimport {\n  type Exchange,\n  HeadersKeys,\n  DefaultExchange,\n  EXCHANGE_INTERNALS,\n  clearResumeStepState,\n  isDropped,\n  isDeferredRun,\n  OperationType,\n  peekResumeStepState,\n  setResumeStepState,\n  setStartedAt,\n} from \"../exchange.ts\";\nimport { isRecovery, applyDropDirective } from \"../recovery.ts\";\nimport { deferExchange } from \"../deferral/defer.ts\";\nimport { SPLIT_PARENT_STORE } from \"../operations/split.ts\";\nimport { rcError, RoutecraftError } from \"../error.ts\";\nimport { isRoutecraftError } from \"../brand.ts\";\nimport {\n  type Adapter,\n  type Step,\n  type StepContext,\n  type StepOutcome,\n  getAdapterLabel,\n} from \"../types.ts\";\nimport { buildInputValidationStep, buildParseStep } from \"./synthetic-steps.ts\";\nimport { applyOutputStage } from \"./validation.ts\";\nimport {\n  CHAIN_SURVIVAL,\n  type ExecutedDefinition,\n  type DetachedKind,\n  detachedDefinition,\n} from \"./chain-policy.ts\";\nimport {\n  DeadlineExceededError,\n  raceWithDeadline,\n} from \"../operations/timeout-wrapper.ts\";\nimport {\n  executeWithRetry,\n  type ResolvedRetryOptions,\n} from \"../operations/retry-wrapper.ts\";\nimport {\n  type CircuitBreakerController,\n  type CircuitBreakerEventScope,\n  circuitBreakerEmitHooks,\n  circuitOpenOutcome,\n  executeWithCircuitBreaker,\n} from \"../operations/circuit-breaker-wrapper.ts\";\nimport {\n  type ConcurrencyController,\n  type ConcurrencyEventScope,\n  concurrencyEmitHooks,\n  executeWithConcurrency,\n} from \"../operations/concurrency-wrapper.ts\";\nimport type { ForwardFn, Route } from \"../route.ts\";\n\n/**\n * Dependencies the pipeline executor needs from the owning route. Passed\n * explicitly so the step loop is a free function (moved verbatim from\n * DefaultRoute.runSteps; only `this.*` references became `deps.*`).\n */\nexport interface ExecutorDeps {\n  routeId: string;\n  context: CraftContext;\n  /** The owning route, surfaced on error event payloads. */\n  route: Route;\n  /**\n   * The chain positions this run executes under, plus its steps.\n   *\n   * Deliberately the same type the detached policy produces. Listing the\n   * fields again here would be a second place to forget one, and the whole\n   * point of deriving the policy from `RouteDefinition` is that there is\n   * only one.\n   */\n  definition: ExecutedDefinition;\n  /** Build a forward callable whose target inherits `caller`'s headers. */\n  buildForward: (caller: Exchange) => ForwardFn;\n  /**\n   * When set and no `errorHandler` is defined, an unhandled failure of\n   * the parent exchange THROWS out of `runPipeline` instead of firing\n   * the default error path (`route:error` + `context:error` +\n   * `route:exchange:failed`). Used by the route-scope resilience\n   * segment steps, whose nested executor invocations must surface a\n   * failed attempt to the wrapping retry / timeout logic rather than\n   * emitting terminal failure events per attempt. Failed split\n   * children keep the default per-child accounting.\n   *\n   * @internal\n   */\n  rethrowUnhandled?: boolean;\n  /**\n   * When set, the step loop stops scheduling further steps once the\n   * signal aborts: the in-flight step settles, its outcome is\n   * discarded, and the queue drains without running the remaining\n   * steps. Used by the route-scope timeout segment so an expired\n   * attempt cannot keep producing downstream side effects (e.g. a\n   * `.to()` firing after the caller already received RC5011).\n   *\n   * @internal\n   */\n  abortSignal?: AbortSignal;\n  /**\n   * When set, route-scope `.concurrency()` queues this run for a slot\n   * rather than refusing it. Resolved from `CHAIN_SURVIVAL.concurrency`,\n   * which is where a kind declares whether it can absorb a refusal.\n   *\n   * The bound still holds: the semaphore is the route's own, shared with\n   * the ingress leg, so this waits for the same slot rather than escaping\n   * the limit.\n   *\n   * @internal\n   */\n  admissionMustWait?: boolean;\n}\n\n/**\n * Run the step loop for an exchange.\n *\n * @param exchange The initial exchange to process\n * @param startTime The timestamp when exchange processing started (for duration calculation)\n * @returns The last processed exchange\n * @private\n */\nexport async function runPipeline(\n  deps: ExecutorDeps,\n  exchange: Exchange,\n  startTime: number,\n): Promise<{\n  exchange: Exchange;\n  failed: boolean;\n  dropped: boolean;\n  /** The exchange deferred at a `.defer()`; execution one ends here. */\n  deferred: boolean;\n  error?: unknown;\n}> {\n  // If the source adapter attached a `parse` function (see #187), prepend\n  // a synthetic step that runs it before any user-defined steps. The step\n  // throws an `RC5016` error on parse failure, which then flows through\n  // the same error-handler path as any other step error: the route's\n  // `.error()` handler is invoked, or `route:exchange:failed` fires.\n  //\n  // `.input()` validation (chain position #4) rides the same internals\n  // slot: with a parser it runs inside the parse step (input validates\n  // the parsed body, so #3 and #4 collapse into one step); without one it\n  // becomes a standalone synthetic input step in the same position. Both\n  // paths throw `RC5065` into this run's catch boundary, so a validation\n  // failure is routable through `.error()` regardless of the source\n  // shape (#447).\n  const internals = EXCHANGE_INTERNALS.get(exchange);\n  const sourceParse = internals?.parse;\n  const sourceValidate = internals?.applyValidation;\n  const sourceFailureMode = internals?.parseFailureMode ?? \"fail\";\n  if (internals && (sourceParse || sourceValidate)) {\n    // Clear so parse / validation never run twice on the same exchange\n    // (e.g. if the exchange is forwarded back through the queue).\n    delete internals.parse;\n    delete internals.parseFailureMode;\n    delete internals.applyValidation;\n  }\n\n  // The route's pre-from filter chain (assembled at builder time in\n  // the framework-fixed order documented at\n  // `.standards/pre-from-filter-chain.md`). Parse is dynamic per\n  // exchange (source-attached) and is interleaved between the two\n  // pre-from arrays:\n  //\n  //   preParseFilters    -> .authorize()\n  //   (parse if present) -> source-attached; runs .input() after parse\n  //   (input if present) -> .input() as a standalone step when no parser\n  //   retry segment      -> route-scope .retry() (#7, wraps the tail)\n  //   timeout segment    -> route-scope .timeout() (#8, wraps the tail)\n  //   concurrency segment-> route-scope .concurrency() (bulkhead, innermost\n  //                         resilience layer: wraps the tail INSIDE retry /\n  //                         timeout so a slot is held per attempt only)\n  //   throttle gate      -> route-scope .throttle() (#5, admits once,\n  //                         OUTSIDE the retry / timeout segments)\n  //   postParseFilters   -> .cache() check (#9), future .circuitBreaker() (#6)\n  //   userSteps          -> declaration order, unchanged\n  //   postFromFilters    -> .cache() store\n  //\n  // The route's `.error()` handler wraps the queue loop (filter\n  // position #1 in the chain doc); it is implemented as a try/catch\n  // around the user pipeline, not a step that calls `next()`.\n  //\n  // The cache key flows from cache-check to cache-store via\n  // `internals.cacheKey` on the exchange -- per-invocation, no\n  // shared closure -- so the filter steps can be constructed once\n  // at builder time.\n  // Chain tail below the route-scope resilience wrappers: cacheCheck\n  // (#9), the user pipeline, and cacheStore (#10). Route-scope retry\n  // (#7) and timeout (#8) scope OVER this whole segment (retry re-runs\n  // it; timeout bounds each run), so they cannot be flat entries in\n  // the step array: each becomes a synthetic segment step that runs\n  // the tail via a nested executor invocation. Timeout wraps first so\n  // retry is outermost: every attempt gets its own deadline\n  // (Resilience4J convention, see `.standards/pre-from-filter-chain.md`).\n  let tail: Step<Adapter>[] = [\n    ...deps.definition.postParseFilters,\n    ...deps.definition.steps,\n    ...deps.definition.postFromFilters,\n  ];\n  // Route-scope concurrency (bulkhead) is the INNERMOST resilience layer:\n  // it wraps the chain tail BEFORE timeout / retry / breaker so a slot is\n  // acquired per attempt and released between retry backoffs (a scarce slot\n  // is never held while a retry sleeps), and an outer retry can re-acquire\n  // one after a reject-mode RC5026. Multiple controllers (stacked\n  // `.concurrency()` calls) nest; the first declared ends up outermost\n  // among them because each successive wrap goes around the previous.\n  if (deps.definition.concurrency) {\n    for (let i = deps.definition.concurrency.length - 1; i >= 0; i--) {\n      tail = [\n        buildConcurrencySegmentStep(\n          deps,\n          tail,\n          deps.definition.concurrency[i]!,\n        ),\n      ];\n    }\n  }\n  if (deps.definition.timeout) {\n    tail = [\n      buildTimeoutSegmentStep(deps, tail, deps.definition.timeout.timeoutMs),\n    ];\n  }\n  if (deps.definition.retry) {\n    tail = [buildRetrySegmentStep(deps, tail, deps.definition.retry)];\n  }\n  // Route-scope circuit breaker (#6) sits OUTSIDE retry / timeout: when\n  // open it fast-fails before they run, so the breaker records ONE failure\n  // per fully exhausted attempt rather than one per retry. Wrapping it\n  // after the retry segment makes it the outer of the two.\n  if (deps.definition.circuitBreaker) {\n    tail = [\n      buildCircuitBreakerSegmentStep(\n        deps,\n        tail,\n        deps.definition.circuitBreaker,\n      ),\n    ];\n  }\n  // Route-scope throttle (#5) is the outermost resilience filter: it\n  // admits an exchange ONCE, then the retry / timeout segments (and the\n  // cache-check + user pipeline below them) run. A retried attempt\n  // re-runs only the wrapped tail, so it never re-acquires a token.\n  // Unlike retry / timeout it does not scope over the tail, so each gate\n  // is a flat sibling step prepended here rather than a wrapping segment;\n  // multiple gates (stacked `.throttle()` calls) all run before the tail.\n  if (deps.definition.throttle) {\n    tail = [...deps.definition.throttle, ...tail];\n  }\n\n  const initialSteps: Step<Adapter>[] = [\n    ...deps.definition.preParseFilters,\n    ...(sourceParse\n      ? [buildParseStep(sourceParse, sourceFailureMode, sourceValidate)]\n      : sourceValidate\n        ? [buildInputValidationStep(sourceValidate)]\n        : []),\n    ...tail,\n  ];\n\n  const queue: { exchange: Exchange; steps: Step<Adapter>[] }[] = [\n    { exchange: exchange, steps: initialSteps },\n  ];\n\n  let lastProcessedExchange: Exchange = exchange;\n  let failed = false;\n  let dropped = false;\n  let stepError: unknown;\n  // Track child exchanges so we can emit route:exchange:started/completed for them.\n  // The parent exchange (first one) is handled by handler().\n  const parentExchangeId = exchange.id;\n  const seenChildExchanges = new Set<string>();\n  const childStartTimes = new Map<string, number>();\n  const failedChildExchanges = new Set<string>();\n\n  // Snapshot existing split parent keys so cleanup only touches groups\n  // created during THIS invocation, not groups from concurrent handlers.\n  const parentMap = deps.context.getStore(SPLIT_PARENT_STORE) as\n    Map<string, Exchange> | undefined;\n  const preExistingGroups = parentMap\n    ? new Set(parentMap.keys())\n    : new Set<string>();\n\n  // Tracks the steps that follow the currently-executing step, refreshed each\n  // loop iteration. `captureDownstream` snapshots it so a step (debounce) can\n  // release a held exchange through its downstream continuation later.\n  let currentRemaining: Step<Adapter>[] = [];\n\n  // Narrow capability handed to steps. takePending implements the same\n  // splice scan aggregate used to run against the raw queue, so join\n  // semantics (including filter-dropped children: only survivors are\n  // collected, nothing waits) are byte-identical to the pre-outcome engine.\n  const stepContext: StepContext = {\n    // Surface the abandon signal (route-scope timeout) to the steps\n    // themselves, not just the scheduling loop below: a step doing\n    // cancellation-aware IO forwards it into fetch / DB drivers so an\n    // expired attempt stops working, instead of merely having its\n    // outcome discarded. Step-scope `.timeout()` composes on top by\n    // deriving a linked signal per wrapped step.\n    ...(deps.abortSignal ? { signal: deps.abortSignal } : {}),\n    takePending(predicate: (candidate: Exchange) => boolean): Exchange[] {\n      const taken: Exchange[] = [];\n      for (let i = 0; i < queue.length;) {\n        if (predicate(queue[i].exchange)) {\n          taken.push(queue[i].exchange);\n          queue.splice(i, 1);\n        } else {\n          i++;\n        }\n      }\n      return taken;\n    },\n    async runPaths(runs): Promise<void> {\n      // Each path is its own isolated nested pipeline run on a clone. They\n      // run concurrently and we wait for all of them to settle: a path\n      // failure surfaces as that clone's default error events (the nested\n      // deps carry no `rethrowUnhandled`) and never rejects this call, so\n      // one bad path cannot take the route down. The original exchange is\n      // untouched and continues once every path has settled.\n      await Promise.allSettled(\n        runs.map((run) =>\n          runPipeline(\n            // Forward any outer abortSignal (a route-scope timeout) so an\n            // expired attempt stops scheduling in-flight paths; omit\n            // rethrowUnhandled so a failing path stays isolated.\n            nestedDeps(deps, run.steps, { abortSignal: deps.abortSignal }),\n            run.exchange,\n            Date.now(),\n          ),\n        ),\n      );\n    },\n    async runPath(run): Promise<{\n      failed: boolean;\n      dropped: boolean;\n      error?: unknown;\n      aborted?: boolean;\n    }> {\n      // Single isolated nested run that reports its outcome back. Same\n      // isolation as a runPaths entry (no rethrowUnhandled, so a failure\n      // fires the clone's own error events rather than propagating), but the\n      // result is returned so a caller can react (dispatch failover advances\n      // to the next target on `failed`). The outer abortSignal is forwarded\n      // so a route-scope timeout can stop an in-flight target.\n      const result = await runPipeline(\n        nestedDeps(deps, run.steps, { abortSignal: deps.abortSignal }),\n        run.exchange,\n        Date.now(),\n      );\n      return {\n        failed: result.failed,\n        dropped: result.dropped,\n        // The nested run stops scheduling once the outer abortSignal fires;\n        // report the truncation so a caller (dispatch failover) does not\n        // mistake an abandoned attempt for a handled exchange.\n        aborted: deps.abortSignal?.aborted === true,\n        ...(result.error !== undefined ? { error: result.error } : {}),\n      };\n    },\n    captureDownstream(): (\n      exchange: Exchange,\n    ) => Promise<{ failed: boolean; dropped: boolean }> {\n      // Snapshot the downstream steps for the CURRENT step now; the runner\n      // itself is built by a module-level factory so it captures only\n      // route-stable state. See makeDownstreamRunner for the full contract\n      // (no inherited abort signal, route-scope error handler honored,\n      // output validation applied).\n      return makeDownstreamRunner(deps, currentRemaining);\n    },\n  };\n\n  while (queue.length > 0) {\n    // Abandoned segment run (route-scope timeout expired): stop\n    // scheduling. The result of this invocation is already discarded\n    // by the segment step, so running further steps would only produce\n    // side effects after the exchange has failed.\n    if (deps.abortSignal?.aborted) break;\n\n    const popped = queue.shift()!;\n    const { steps } = popped;\n    // `let` because the engine may rewrap the exchange below to update\n    // bookkeeping headers (operation label) without mutating the frozen\n    // wrapper. Subsequent reads in this iteration use the rewrapped value.\n    let exchange = popped.exchange;\n    if (steps.length === 0) {\n      // Emit route:exchange:completed for child exchanges when their steps are done\n      if (\n        exchange.id !== parentExchangeId &&\n        seenChildExchanges.has(exchange.id) &&\n        !failedChildExchanges.has(exchange.id)\n      ) {\n        const childStart = childStartTimes.get(exchange.id) ?? startTime;\n        const correlationId = exchange.headers[\n          HeadersKeys.CORRELATION_ID\n        ] as string;\n        deps.context.emit(\"route:exchange:completed\", {\n          routeId: deps.routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          duration: Date.now() - childStart,\n          exchange,\n        });\n      }\n      lastProcessedExchange = exchange;\n      continue;\n    }\n\n    // Emit route:exchange:started for child exchanges on first encounter\n    if (\n      exchange.id !== parentExchangeId &&\n      !seenChildExchanges.has(exchange.id)\n    ) {\n      seenChildExchanges.add(exchange.id);\n      const childNow = Date.now();\n      childStartTimes.set(exchange.id, childNow);\n      // Stash the start timestamp on the exchange's internals so\n      // aggregate (and other observers) can read child duration without\n      // a side-Map handed across module boundaries. Internals survive\n      // `rewrap` because rewrap shares them between prev and next.\n      setStartedAt(exchange, childNow);\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n      deps.context.emit(\"route:exchange:started\", {\n        routeId: deps.routeId,\n        exchangeId: exchange.id,\n        correlationId,\n      });\n    }\n\n    const [step, ...remainingSteps] = steps;\n    // Expose the downstream continuation for a step that wants to capture it\n    // (debounce releasing a held exchange later); refreshed every iteration.\n    currentRemaining = remainingSteps;\n\n    // Prefer the DSL label (e.g., \"log\") over the raw OperationType (e.g., \"tap\")\n    const stepLabel = step.label ?? step.operation;\n\n    // Update the operation header for this step. Headers are frozen, so\n    // we rewrap onto a derived exchange (preserves id and internals).\n    // The cost is one allocation per step on top of whatever the step\n    // itself produces; in practice the dominant cost is still I/O.\n    exchange = DefaultExchange.rewrap(exchange, {\n      headers: { ...exchange.headers, [HeadersKeys.OPERATION]: stepLabel },\n    });\n\n    const adapterLabel = getAdapterLabel(step.adapter);\n    exchange.logger.debug(\n      {\n        operation: stepLabel,\n        ...(adapterLabel ? { adapter: adapterLabel } : {}),\n      },\n      \"Processing step\",\n    );\n\n    const stepStartTime = Date.now();\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n\n    // Emit route:step:started event unless the step manages its own events\n    if (!step.skipStepEvents) {\n      deps.context.emit(\"route:step:started\", {\n        routeId: deps.routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: stepLabel,\n        ...(adapterLabel ? { adapter: adapterLabel } : {}),\n      });\n    }\n\n    try {\n      const outcome = await step.execute(exchange, stepContext);\n      // A settled step consumed any resume step state a revival attached:\n      // the re-entrant host is by construction the first step of its\n      // continuation, so clearing on every committed outcome keeps the\n      // once-only contract while a thrown attempt (a retryable provider\n      // failure) leaves the state in place for the retry to resume.\n      clearResumeStepState(exchange);\n\n      // The executor owns scheduling: translate the outcome into queue\n      // entries. Pushes carry no events, so push-vs-emit ordering below\n      // is observationally identical to the old in-step pushes.\n      switch (outcome.kind) {\n        case \"continue\":\n          queue.push({ exchange: outcome.exchange, steps: remainingSteps });\n          break;\n        case \"complete\":\n          queue.push({ exchange: outcome.exchange, steps: [] });\n          break;\n        case \"branch\":\n          queue.push({\n            exchange: outcome.exchange,\n            steps: [...outcome.steps, ...remainingSteps],\n          });\n          break;\n        case \"fanOut\":\n          for (const child of outcome.exchanges) {\n            queue.push({ exchange: child, steps: remainingSteps });\n          }\n          break;\n        case \"drop\":\n          // The step marked the exchange dropped and emitted its drop\n          // events; schedule nothing.\n          break;\n        case \"defer\": {\n          // The exchange defers here and this run ends: the executor\n          // serializes it, writes the deferral, and answers with the\n          // `Deferred` acknowledgment. Nothing is scheduled beyond that\n          // (`steps: []`), no worker waits, and the route stays live for\n          // every other exchange, because the continuation lives in the\n          // store rather than in this process.\n          if (!outcome.request) {\n            throw rcError(\"RC5032\", undefined, {\n              message: `Step \"${stepLabel}\" returned a \"defer\" outcome without a defer request, so the engine cannot work out what to defer or what would resume.`,\n            });\n          }\n          // A cancelled run must not leave a live resume link behind: the\n          // caller is being told the run failed (a timeout, a stop), so an\n          // approver clicking days later would continue work its caller\n          // already saw cancelled. Before the store write, refusing to defer\n          // is free; an abort that lands during the write is resolved\n          // inside `deferExchange` (deny, then RC5054) BEFORE the deferred\n          // event, so one exchange never announces two terminals. The\n          // caller's RC5054 is the notification; no re-ask is delivered.\n          if (deps.abortSignal?.aborted) {\n            throw rcError(\"RC5054\", deps.abortSignal.reason, {\n              message: `Step \"${stepLabel}\" raised a deferral after its run was cancelled; nothing was deferred.`,\n            });\n          }\n          const deferred = await deferExchange(\n            deps.context,\n            outcome.exchange,\n            outcome.request,\n            deps.routeId,\n            deps.abortSignal,\n          );\n          queue.push({ exchange: deferred, steps: [] });\n          break;\n        }\n      }\n\n      // Emit route:step:completed event unless the step manages its own events\n      if (!step.skipStepEvents) {\n        const stepDuration = Date.now() - stepStartTime;\n        const correlationId = exchange.headers[\n          HeadersKeys.CORRELATION_ID\n        ] as string;\n        deps.context.emit(\"route:step:completed\", {\n          routeId: deps.routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          operation: stepLabel,\n          ...(adapterLabel ? { adapter: adapterLabel } : {}),\n          duration: stepDuration,\n          // Adapter-populated observability metadata (e.g. LLM token\n          // usage from to/enrich getMetadata), carried on the outcome.\n          ...(\"metadata\" in outcome && outcome.metadata\n            ? { metadata: outcome.metadata }\n            : {}),\n        });\n      }\n    } catch (error) {\n      const err = processError(error);\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n      const duration = Date.now() - startTime;\n\n      // Emit step-level error, unless this run was already abandoned by\n      // an outer abort (a route-scope timeout that expired). Since the\n      // wrapped step now receives that abort through its StepContext\n      // signal, a cancellation-aware step FAILS on expiry rather than\n      // running to completion with a discarded outcome. That failure is\n      // a consequence of the deadline the segment step has already\n      // reported (RC5011), not an independent step error, so surfacing\n      // it would add a spurious `route:step:error` per expiry for\n      // exactly the steps that cooperate with cancellation. The\n      // abandoned run's result is discarded either way.\n      if (!deps.abortSignal?.aborted) {\n        deps.context.emit(\"route:step:error\", {\n          routeId: deps.routeId,\n          error: err,\n          route: deps.route,\n          exchange,\n          operation: stepLabel,\n        });\n      }\n\n      if (deps.definition.errorHandler) {\n        // Route-scope error-handler events. Step-scope wrappers\n        // emit the same set with `scope: \"step\"` and `stepLabel`.\n        deps.context.emit(\"route:error-handler:invoked\", {\n          routeId: deps.routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          originalError: err,\n          failedOperation: stepLabel,\n          scope: \"route\",\n        });\n\n        try {\n          const forward = deps.buildForward(exchange);\n          const result = await deps.definition.errorHandler(\n            err,\n            exchange,\n            forward,\n          );\n          if (isRecovery(result)) {\n            if (result.kind === \"rethrow\") {\n              // Declarative equivalent of `throw error` inside the\n              // handler: fall through to the handler-threw path below\n              // with the original error.\n              throw err;\n            }\n            // `recovery.drop()`: resolve the error by discarding the\n            // exchange (shared semantics in applyDropDirective).\n            applyDropDirective({\n              context: deps.context,\n              routeId: deps.routeId,\n              exchange,\n              originalError: err,\n              failedOperation: stepLabel,\n              correlationId,\n              reason: result.reason,\n              scope: \"route\",\n              route: deps.route,\n            });\n            // Only a drop of the PARENT exchange marks the run dropped\n            // (suppressing the parent's route:exchange:completed). A dropped\n            // split CHILD resolves that child alone, mirroring the\n            // handler-threw path's failedChildExchanges accounting.\n            if (exchange.id === parentExchangeId) {\n              dropped = true;\n            }\n          } else {\n            // Replace body via rewrap (frozen exchange); keep id and\n            // internals so telemetry continues to reference the same\n            // logical exchange.\n            const recovered = DefaultExchange.rewrap(exchange, {\n              body: result,\n            });\n            lastProcessedExchange = recovered;\n\n            // Error handler recovered\n            deps.context.emit(\"route:error:caught\", {\n              routeId: deps.routeId,\n              error: err,\n              route: deps.route,\n              exchange: recovered,\n            });\n            deps.context.emit(\"route:error-handler:recovered\", {\n              routeId: deps.routeId,\n              exchangeId: recovered.id,\n              correlationId,\n              originalError: err,\n              failedOperation: stepLabel,\n              recoveryStrategy: \"route-error-handler\",\n              scope: \"route\",\n            });\n          }\n        } catch (handlerError) {\n          const handlerErr = processError(handlerError);\n          exchange.logger.error(\n            {\n              operation: stepLabel,\n              err: handlerErr,\n              context: \"error handler\",\n            },\n            handlerErr.meta.message,\n          );\n          deps.context.emit(\"route:error-handler:failed\", {\n            routeId: deps.routeId,\n            exchangeId: exchange.id,\n            correlationId,\n            originalError: err,\n            failedOperation: stepLabel,\n            recoveryStrategy: \"route-error-handler\",\n            scope: \"route\",\n          });\n          // Error handler rethrew -- route-level + context-level error\n          deps.context.emit(\"route:error\", {\n            routeId: deps.routeId,\n            error: handlerErr,\n            route: deps.route,\n            exchange,\n          });\n          deps.context.emit(\"context:error\", {\n            error: handlerErr,\n            route: deps.route,\n            exchange,\n          });\n          deps.context.emit(\"route:exchange:failed\", {\n            routeId: deps.routeId,\n            exchangeId: exchange.id,\n            correlationId,\n            duration,\n            error: handlerErr,\n            exchange,\n          });\n          if (exchange.id !== parentExchangeId) {\n            failedChildExchanges.add(exchange.id);\n          } else {\n            failed = true;\n            stepError = handlerErr;\n          }\n        }\n\n        // Pipeline does not resume after error handler (success or failure)\n        return {\n          exchange: lastProcessedExchange,\n          failed,\n          dropped,\n          deferred: isDeferredRun(exchange),\n          error: stepError,\n        };\n      }\n\n      // No error handler -- inside a nested resilience segment the\n      // parent's failure must surface to the wrapping segment step\n      // (retry decides whether to re-attempt; timeout maps its own\n      // expiry) instead of firing the default error path per attempt.\n      // Failed split children keep the default per-child accounting\n      // below.\n      if (deps.rethrowUnhandled && exchange.id === parentExchangeId) {\n        throw err;\n      }\n\n      // No error handler -- route-level error\n      exchange.logger.error(\n        {\n          operation: stepLabel,\n          ...(adapterLabel ? { adapter: adapterLabel } : {}),\n          err,\n        },\n        err.meta.message,\n      );\n      // No error handler -- route-level + context-level error\n      deps.context.emit(\"route:error\", {\n        routeId: deps.routeId,\n        error: err,\n        route: deps.route,\n        exchange,\n      });\n      deps.context.emit(\"context:error\", {\n        error: err,\n        route: deps.route,\n        exchange,\n      });\n      deps.context.emit(\"route:exchange:failed\", {\n        routeId: deps.routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        duration,\n        error: err,\n        exchange,\n      });\n      if (exchange.id !== parentExchangeId) {\n        failedChildExchanges.add(exchange.id);\n      } else {\n        failed = true;\n        stepError = err;\n      }\n\n      // Don't re-throw - error is logged and emitted via events.\n      // The error is returned in the result so callers (e.g. CraftClient)\n      // can handle it. Source adapters catch and continue.\n      // Do NOT return here: the while loop continues so other queue items (e.g. split children) are processed\n    }\n  }\n\n  // Clean up orphaned split parent map entries added during THIS invocation.\n  // Only touch groups that did not exist before runSteps started, to avoid\n  // deleting entries owned by concurrent handlers on the same context.\n  if (parentMap && parentMap.size > 0) {\n    for (const groupId of Array.from(parentMap.keys())) {\n      if (preExistingGroups.has(groupId)) continue;\n      const parentEx = parentMap.get(groupId);\n      if (parentEx) {\n        const hierarchy = parentEx.headers[HeadersKeys.SPLIT_HIERARCHY] as\n          string[] | undefined;\n        // Only clean up groups that are NOT part of a nested hierarchy\n        if (!hierarchy || !hierarchy.includes(groupId)) {\n          parentMap.delete(groupId);\n        }\n      }\n    }\n  }\n\n  // Check if the root exchange was dropped (e.g. by a filter). The drop\n  // flag lives on the exchange's shared internals object (see\n  // `markDropped` / `isDropped` in `exchange.ts`), so it survives the\n  // engine's per-step `rewrap`: an operation that marks the rewrapped\n  // exchange handed to it remains visible from the outer parameter\n  // because both reference the same internals.\n  if (isDropped(exchange)) {\n    dropped = true;\n  }\n\n  // Route-scope cache writes (`cacheConfig`) are handled inline by\n  // the `cache-store` synthetic step appended to `initialSteps` at\n  // the top of this function. Nothing to do here.\n\n  return {\n    exchange: lastProcessedExchange,\n    failed,\n    dropped,\n    deferred: isDeferredRun(exchange),\n    error: stepError,\n  };\n}\n\n/**\n * Synthetic adapter carriers for the route-scope resilience segment\n * steps. Distinct adapter ids so telemetry correlating by `adapter`\n * can tell retry re-runs (`routecraft.retry`) from deadline guards\n * (`routecraft.timeout`) without parsing the step label. Neither\n * carrier has behaviour; the steps' `execute` does the work.\n */\nconst RETRY_SEGMENT_ADAPTER: Adapter = { adapterId: \"routecraft.retry\" };\nconst TIMEOUT_SEGMENT_ADAPTER: Adapter = { adapterId: \"routecraft.timeout\" };\nconst CIRCUIT_BREAKER_SEGMENT_ADAPTER: Adapter = {\n  adapterId: \"routecraft.circuitBreaker\",\n};\nconst CONCURRENCY_SEGMENT_ADAPTER: Adapter = {\n  adapterId: \"routecraft.concurrency\",\n};\n\n/**\n * Convert a nested segment run's result into the {@link StepOutcome} the\n * outer pipeline schedules: a deliberately dropped run resolves as a\n * drop, every other run continues with the produced exchange. Shared by\n * the timeout / retry / circuit-breaker segment builders so the mapping\n * lives in one place.\n */\nfunction segmentResultToOutcome(result: {\n  exchange: Exchange;\n  dropped: boolean;\n}): StepOutcome {\n  if (result.dropped) return { kind: \"drop\" } as const;\n  // A run that deferred inside the segment has already been answered with its\n  // `Deferred` acknowledgment, and the deferring is recorded on the\n  // exchange's shared internals, so the outer run must schedule nothing\n  // further rather than continuing into steps the deferred exchange is no\n  // longer at. It is `complete`, not a second `defer`: the exchange is\n  // deferred once, by the run that reached the step.\n  if (isDeferredRun(result.exchange)) {\n    return { kind: \"complete\", exchange: result.exchange } as const;\n  }\n  return { kind: \"continue\", exchange: result.exchange } as const;\n}\n\n/**\n * Executor deps for a nested `runPipeline` invocation: same route identity\n * and capabilities, but the step array carries only the wrapped segment and\n * no `errorHandler` / `retry` / `timeout` (the outer invocation owns filter\n * #1 and the segment wrappers themselves; omitting them here is also what\n * stops the nested run from re-wrapping recursively).\n *\n * Two callers, distinguished by `opts`:\n * - Resilience segments (timeout / retry / circuit breaker) pass\n *   `rethrowUnhandled: true` so a failed attempt throws out of the nested\n *   run and the segment step can react, and the timeout segment additionally\n *   passes its `abortSignal` so an expired attempt stops scheduling.\n * - Multicast paths omit `rethrowUnhandled` so a path that throws resolves\n *   through the default error path for its own clone (firing that exchange's\n *   `route:error` / `context:error` / `route:exchange:failed`) rather than\n *   propagating -- one failing path neither rejects `runPaths` nor disturbs\n *   the others -- while still forwarding any outer `abortSignal` so a\n *   route-scope timeout can stop in-flight paths.\n *\n * The empty definition is deliberately outside `CHAIN_SURVIVAL`: a nested\n * segment is not a re-entry, so it has nothing to declare per position. The\n * invocation above it already applied the chain.\n */\nfunction nestedDeps(\n  deps: ExecutorDeps,\n  segment: Step<Adapter>[],\n  opts: {\n    rethrowUnhandled?: boolean;\n    abortSignal?: AbortSignal | undefined;\n  } = {},\n): ExecutorDeps {\n  return {\n    routeId: deps.routeId,\n    context: deps.context,\n    route: deps.route,\n    buildForward: deps.buildForward,\n    ...(opts.rethrowUnhandled ? { rethrowUnhandled: true } : {}),\n    ...(opts.abortSignal ? { abortSignal: opts.abortSignal } : {}),\n    definition: {\n      preParseFilters: [],\n      postParseFilters: [],\n      steps: segment,\n      postFromFilters: [],\n    },\n  };\n}\n\n/**\n * Build the detached-release runner handed out by `captureDownstream`.\n *\n * Module-level on purpose, for two verified reasons:\n *\n * - The returned closure must capture ONLY route-stable state (`deps` and\n *   the downstream step array). Building it inside `runPipeline` would chain\n *   it to that invocation's activation context (pinning the capturing\n *   arrival's queue for as long as the runner is retained) and, worse, to\n *   `deps.abortSignal`: when the capturing arrival ran inside a route-scope\n *   timeout / concurrency attempt, that per-attempt signal can abort later\n *   and would permanently poison every future release into scheduling zero\n *   steps. A released exchange is a fresh detached flow, so it inherits NO\n *   abort signal.\n * - For a holding operation (debounce) the released exchange IS the route's\n *   primary flow, not a side effect, so unlike fan-out paths the detached\n *   run honors the route-scope `.error()` handler and enforces the route's\n *   `.output()` schemas before completion. Both are read from\n *   `deps.route.definition` (the full definition) because the capturing\n *   invocation may be a nested segment whose own `deps.definition` has them\n *   stripped.\n *\n * The released exchange gets its own `route:exchange:started` / `:completed`\n * lifecycle pair, and the run is `trackTask`ed so `drain()` waits for it.\n */\nfunction makeDownstreamRunner(\n  deps: ExecutorDeps,\n  downstream: Step<Adapter>[],\n): (exchange: Exchange) => Promise<{ failed: boolean; dropped: boolean }> {\n  return (releaseExchange) => {\n    const release = runDetachedPipeline(\n      deps,\n      downstream,\n      releaseExchange,\n      \"debounce\",\n    );\n    // Track the ENTIRE release flow (pipeline, output validation, and the\n    // completion emit), not just the pipeline promise: a caller that does not\n    // itself await the runner to completion (debounce's settle latch does,\n    // but the contract must not depend on the caller) would otherwise let\n    // drain() return between the pipeline settling and the validation /\n    // completed emit finishing.\n    deps.route.trackTask(release);\n    return release;\n  };\n}\n\n/**\n * Run `steps` against `exchange` as a detached, first-class run of the\n * route: its own `route:exchange:started` / `:completed` pair, the route-scope\n * `.error()` handler honoured, and the route's `.output()` schemas enforced\n * before completion.\n *\n * Two callers, sharing the run's shape but not its chain. `debounce`\n * releases a held exchange into the steps that follow it, and a resume\n * revives a deferred exchange into its continuation. Neither is a side-effect\n * clone: in both cases the exchange IS the route's primary flow, resuming\n * partway down a pipeline whose earlier steps must not re-run.\n *\n * `kind` is what separates them, because the chain above the entry point\n * means different things for each: a released exchange is work the route\n * held back and never admitted, while a resumed one entered the route once\n * and was admitted then. Which positions apply is declared per position in\n * `chain-policy.ts` rather than decided here.\n *\n * The run inherits NO abort signal. A signal from the capturing attempt (a\n * route-scope timeout) can fire long after, and a detached run is a fresh\n * flow rather than a continuation of that attempt.\n *\n * @param kind - Which detached run this is, selecting the chain policy\n *\n * @internal\n */\nexport function runDetachedPipeline(\n  deps: ExecutorDeps,\n  downstream: ReadonlyArray<Step<Adapter>>,\n  releaseExchange: Exchange,\n  kind: DetachedKind,\n): Promise<DetachedResult> {\n  return (async (): Promise<DetachedResult> => {\n    const start = Date.now();\n    const correlationId = releaseExchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n    deps.context.emit(\"route:exchange:started\", {\n      routeId: deps.routeId,\n      exchangeId: releaseExchange.id,\n      correlationId,\n    });\n    const routeDefinition = deps.route.definition;\n    const nested: ExecutorDeps = {\n      routeId: deps.routeId,\n      context: deps.context,\n      route: deps.route,\n      buildForward: deps.buildForward,\n      definition: detachedDefinition(routeDefinition, downstream, kind),\n      ...(CHAIN_SURVIVAL.concurrency[kind].mustNotRefuse\n        ? { admissionMustWait: true }\n        : {}),\n    };\n    let result = await runPipeline(nested, releaseExchange, start);\n\n    // The released exchange carries the route's final output, so the same\n    // output stage the source-driven path uses runs here too.\n    result = await applyOutputStage(\n      {\n        routeId: deps.routeId,\n        context: deps.context,\n        route: deps.route,\n        buildForward: deps.buildForward,\n        ...(routeDefinition.errorHandler\n          ? { errorHandler: routeDefinition.errorHandler }\n          : {}),\n      },\n      routeDefinition.discovery?.output,\n      result,\n      start,\n    );\n\n    // A run that deferred at a `.defer()` ends with the `Deferred`\n    // acknowledgment rather than the route's output, and its terminal\n    // event was `route:exchange:deferred`. Completing it here would both\n    // claim an output it does not carry and give the exchange two\n    // terminal events.\n    if (!result.failed && !result.dropped && !result.deferred) {\n      deps.context.emit(\"route:exchange:completed\", {\n        routeId: deps.routeId,\n        exchangeId: releaseExchange.id,\n        correlationId,\n        duration: Date.now() - start,\n        exchange: result.exchange,\n      });\n    }\n    return {\n      failed: result.failed,\n      dropped: result.dropped,\n      deferred: result.deferred,\n      exchange: result.exchange,\n      ...(result.error !== undefined ? { error: result.error } : {}),\n    };\n  })();\n}\n\n/**\n * What a detached run reports back. `error` is present exactly when\n * `failed` is true and the failure reached the run's boundary, which is\n * what a resume needs to cache as the deferral's continuation result.\n *\n * @internal\n */\nexport interface DetachedResult {\n  failed: boolean;\n  dropped: boolean;\n  /**\n   * The run deferred at a `.defer()`. Distinct from every other outcome:\n   * the exchange is neither finished nor failed, and its terminal body is\n   * the `Deferred` acknowledgment rather than the route's output. A caller\n   * that treats it as a completion publishes both a false receipt and the\n   * next deferral's resume token.\n   */\n  deferred: boolean;\n  exchange: Exchange;\n  error?: unknown;\n}\n\n/**\n * Build the route-scope `.timeout()` segment step (pre-from chain\n * position #8). Runs the chain tail via a nested executor invocation\n * raced against the deadline. On expiry, emits `route:timeout:expired`,\n * throws `RC5011`, and aborts the nested run: no further steps are\n * scheduled, the in-flight step's outcome is discarded, and the abort\n * (reason: the RC5011 error) reaches that step through its StepContext\n * `signal` so cancellation-aware IO stops instead of running to\n * completion in the background.\n *\n * `skipStepEvents: true` keeps `runPipeline` from emitting generic\n * lifecycle events for this internal step; the segment emits its own\n * `route:timeout:*` family with `scope: \"route\"`.\n */\nfunction buildTimeoutSegmentStep(\n  deps: ExecutorDeps,\n  segment: Step<Adapter>[],\n  timeoutMs: number,\n): Step<Adapter> {\n  return {\n    operation: OperationType.PROCESS,\n    label: \"timeout\",\n    adapter: TIMEOUT_SEGMENT_ADAPTER,\n    skipStepEvents: true,\n    async execute(exchange) {\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n      const scoped = {\n        routeId: deps.routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        stepLabel: \"route\",\n        scope: \"route\" as const,\n        timeoutMs,\n      };\n      deps.context.emit(\"route:timeout:started\", scoped);\n      const start = Date.now();\n      const abandon = new AbortController();\n      try {\n        const result = await raceWithDeadline(\n          runPipeline(\n            nestedDeps(deps, segment, {\n              rethrowUnhandled: true,\n              abortSignal: abandon.signal,\n            }),\n            exchange,\n            Date.now(),\n          ),\n          timeoutMs,\n        );\n        deps.context.emit(\"route:timeout:stopped\", {\n          ...scoped,\n          elapsed: Date.now() - start,\n        });\n        return segmentResultToOutcome(result);\n      } catch (err) {\n        if (!(err instanceof DeadlineExceededError)) throw err;\n        const timeoutError = rcError(\"RC5011\", undefined, {\n          message: `Route \"${deps.routeId}\" pipeline exceeded its ${timeoutMs}ms timeout`,\n        });\n        // Stop the abandoned run: the scheduling loop stops queueing\n        // further steps, and the in-flight step sees the abort via its\n        // StepContext signal (exposed by the nested run's stepContext)\n        // so cancellation-aware IO stops instead of running to\n        // completion with a discarded outcome. The RC5011 error rides\n        // as the abort reason.\n        abandon.abort(timeoutError);\n        deps.context.emit(\"route:timeout:expired\", {\n          ...scoped,\n          elapsed: Date.now() - start,\n        });\n        throw timeoutError;\n      }\n    },\n  };\n}\n\n/**\n * Build the route-scope `.retry()` segment step (pre-from chain\n * position #7). Re-runs the chain tail (including a nested timeout\n * segment, the cache check, the user pipeline, and the cache store)\n * via nested executor invocations until an attempt succeeds, the error\n * is non-retryable, or attempts are exhausted; then the final error\n * propagates unchanged to the route-scope `.error()` handler or the\n * default error path.\n *\n * A dropped attempt (filter rejection, parse-drop) is a deliberate\n * resolution, not a failure: it is never re-attempted.\n */\nfunction buildRetrySegmentStep(\n  deps: ExecutorDeps,\n  segment: Step<Adapter>[],\n  options: ResolvedRetryOptions,\n): Step<Adapter> {\n  return {\n    operation: OperationType.PROCESS,\n    label: \"retry\",\n    adapter: RETRY_SEGMENT_ADAPTER,\n    skipStepEvents: true,\n    async execute(exchange, ctx) {\n      const abandon = ctx?.signal ?? deps.abortSignal;\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n      const scoped = {\n        routeId: deps.routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        stepLabel: \"route\",\n        scope: \"route\" as const,\n      };\n      // A resumed continuation may retry: each attempt must re-enter the\n      // deferring step with the same deferred state, even though a settled\n      // step inside a prior attempt already cleared it (a later step's\n      // retryable failure would otherwise re-run the agent from scratch).\n      const resumeSnapshot = peekResumeStepState(exchange);\n      const result = await executeWithRetry(\n        () => {\n          if (resumeSnapshot !== undefined) {\n            setResumeStepState(exchange, resumeSnapshot);\n          }\n          return runPipeline(\n            nestedDeps(deps, segment, {\n              rethrowUnhandled: true,\n              abortSignal: abandon,\n            }),\n            exchange,\n            Date.now(),\n          );\n        },\n        options,\n        {\n          // Intake, not execution. A backoff cut short surfaces the last\n          // error as a proper terminal outcome; waiting it out burns the\n          // shutdown deadline on attempts that cannot finish and ends in an\n          // abandonment that emits no terminal event at all. An abandoned\n          // run must also stop sleeping between attempts, hence `abandon`:\n          // a backoff outlives the deadline that abandoned it.\n          signal: anySignal(deps.route.intakeSignal, abandon),\n          onStarted: () => {\n            deps.context.emit(\"route:retry:started\", {\n              ...scoped,\n              maxAttempts: options.maxAttempts,\n            });\n          },\n          onAttempt: (attemptNumber, waitMs, lastError) => {\n            deps.context.emit(\"route:retry:attempt\", {\n              ...scoped,\n              attemptNumber,\n              maxAttempts: options.maxAttempts,\n              backoffMs: waitMs,\n              lastError,\n            });\n          },\n          onStopped: (attemptNumber, success, error) => {\n            deps.context.emit(\"route:retry:stopped\", {\n              ...scoped,\n              attemptNumber,\n              success,\n              ...(error !== undefined ? { error } : {}),\n            });\n          },\n        },\n      );\n      return segmentResultToOutcome(result);\n    },\n  };\n}\n\n/**\n * Build the route-scope `.circuitBreaker()` segment step (pre-from chain\n * position #6). Wraps the chain tail (the retry / timeout segments, the\n * cache check, the user pipeline, and the cache store). On each exchange\n * the breaker decides whether to admit the call:\n *\n * - OPEN (cooldown not elapsed) or HALF-OPEN at capacity: fast-fail\n *   WITHOUT running the tail. With a `fallback` the configured value\n *   becomes the body and the pipeline completes; without one it throws\n *   `RC5025` to the route-scope `.error()` handler (or the default error\n *   path).\n * - CLOSED, or HALF-OPEN with a free probe slot: run the tail via a\n *   nested executor invocation (`rethrowUnhandled`, so a failed attempt\n *   surfaces here). A success closes a half-open breaker; a counted\n *   failure trips a closed breaker or re-opens a half-open one.\n *\n * Because it sits OUTSIDE retry, one fully exhausted attempt (after retry\n * gives up) is recorded as a single breaker failure, not one per retry.\n *\n * The breaker `controller` is built once per route definition (in\n * `RouteBuilder.from`) and holds the persistent per-Route state, so it is\n * passed in rather than constructed here. `skipStepEvents: true` keeps\n * `runPipeline` from emitting generic lifecycle events for this internal\n * step; the segment emits its own `route:circuitBreaker:*` family with\n * `scope: \"route\"`.\n */\nfunction buildCircuitBreakerSegmentStep(\n  deps: ExecutorDeps,\n  segment: Step<Adapter>[],\n  controller: CircuitBreakerController,\n): Step<Adapter> {\n  return {\n    operation: OperationType.CIRCUIT_BREAKER,\n    label: \"circuitBreaker\",\n    adapter: CIRCUIT_BREAKER_SEGMENT_ADAPTER,\n    skipStepEvents: true,\n    async execute(exchange, ctx) {\n      const abandon = ctx?.signal ?? deps.abortSignal;\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n      const scoped: CircuitBreakerEventScope = {\n        routeId: deps.routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        stepLabel: \"route\",\n        scope: \"route\",\n        ...(controller.label !== undefined ? { label: controller.label } : {}),\n      };\n      const hooks = circuitBreakerEmitHooks(\n        deps.context,\n        scoped,\n        true,\n        controller.options,\n      );\n\n      const forward = deps.buildForward(exchange);\n\n      return executeWithCircuitBreaker(\n        controller,\n        deps.route,\n        hooks,\n        () =>\n          circuitOpenOutcome(\n            exchange,\n            controller.options,\n            forward,\n            `for route \"${deps.routeId}\"`,\n          ),\n        async () =>\n          segmentResultToOutcome(\n            await runPipeline(\n              nestedDeps(deps, segment, {\n                rethrowUnhandled: true,\n                abortSignal: abandon,\n              }),\n              exchange,\n              Date.now(),\n            ),\n          ),\n      );\n    },\n  };\n}\n\n/**\n * Build a route-scope `.concurrency()` bulkhead segment step, the\n * INNERMOST resilience layer (inside retry / timeout). Acquires a slot\n * (queueing or fast-failing per mode), runs the chain tail via a nested\n * executor invocation, and releases the slot when that run settles, so a\n * slot is held only for the actual attempt and freed between retry\n * backoffs. A `reject`-mode or queue-full rejection throws `RC5026`, which\n * an outer `.retry()` (sitting outside this segment) can re-attempt.\n *\n * `skipStepEvents: true` keeps `runPipeline` from emitting generic\n * lifecycle events; the segment emits its own `route:concurrency:*` family\n * with `scope: \"route\"`.\n */\nfunction buildConcurrencySegmentStep(\n  deps: ExecutorDeps,\n  segment: Step<Adapter>[],\n  controller: ConcurrencyController,\n): Step<Adapter> {\n  return {\n    operation: OperationType.CONCURRENCY,\n    label: \"concurrency\",\n    adapter: CONCURRENCY_SEGMENT_ADAPTER,\n    skipStepEvents: true,\n    async execute(exchange, ctx) {\n      // The segment step is built once, when the chain is assembled, but an\n      // abandon signal belongs to a single execution: an outer `.timeout()`\n      // mints a fresh controller per attempt and hands it down through the\n      // step context. Reading it from the build-time `deps` would always\n      // read the signal that existed before any attempt started.\n      const abandon = ctx?.signal ?? deps.abortSignal;\n      const correlationId = exchange.headers[\n        HeadersKeys.CORRELATION_ID\n      ] as string;\n      const scoped: ConcurrencyEventScope = {\n        routeId: deps.routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        stepLabel: \"route\",\n        scope: \"route\",\n        ...(controller.label !== undefined ? { label: controller.label } : {}),\n      };\n\n      return executeWithConcurrency(\n        controller,\n        exchange,\n        deps.route,\n        {\n          // Intake: a queued segment step is released as soon as shutdown\n          // begins and admitted with a no-op release (see `#joinWaitLine`),\n          // so the drain runs it instead of leaving it deferred behind a slot\n          // that will never free. Also cancelled when an outer segment\n          // abandons this attempt (e.g. a route-scope timeout firing while\n          // this exchange is still deferred in the bulkhead queue).\n          signal: anySignal(deps.route.intakeSignal, abandon),\n          ...concurrencyEmitHooks(deps.context, scoped, true),\n        },\n        async () =>\n          segmentResultToOutcome(\n            await runPipeline(\n              nestedDeps(deps, segment, {\n                rethrowUnhandled: true,\n                abortSignal: abandon,\n              }),\n              exchange,\n              Date.now(),\n            ),\n          ),\n        { mustWait: deps.admissionMustWait === true },\n      );\n    },\n  };\n}\n\n/**\n * Normalize an operation error into a RoutecraftError.\n * If the error is already a RoutecraftError, it is returned unchanged.\n *\n * @param error - The thrown value (Error or RoutecraftError)\n * @returns A RoutecraftError (existing or RC5001-wrapped)\n * @private\n */\nexport function processError(error: unknown): RoutecraftError {\n  if (isRoutecraftError(error)) {\n    return error as RoutecraftError;\n  }\n  const msg = error instanceof Error ? error.message : String(error);\n  return rcError(\"RC5001\", error, { message: msg });\n}\n","import { markDropped, emitExchangeDropped, type Exchange } from \"./exchange.ts\";\nimport { BRAND, isBranded } from \"./brand.ts\";\nimport type { CraftContext } from \"./context.ts\";\nimport type { Route } from \"./route.ts\";\n\n/**\n * Brand key marking a {@link Recovery} directive. Registered in\n * {@link BRAND} (`Symbol.for`) so directives survive crossing duplicate\n * copies of the package (CLI vs user module).\n */\nconst RECOVERY = BRAND.Recovery;\n\n/**\n * Directive returned from an {@link ErrorHandler} to drop the failing\n * exchange instead of recovering with a body. The engine marks the\n * exchange dropped and emits `route:exchange:dropped` with `reason`;\n * `route:exchange:completed` does not fire and no recovery body is produced.\n */\nexport interface RecoveryDrop {\n  readonly [RECOVERY]: true;\n  readonly kind: \"drop\";\n  readonly reason: string;\n}\n\n/**\n * Directive returned from an {@link ErrorHandler} to propagate the\n * original error, declining recovery. Equivalent to `throw error` inside\n * the handler: the engine follows the handler-threw path\n * (`route:error-handler:failed`, then the route-level cascade for\n * step-scope handlers or the `route:exchange:failed` path for route scope).\n */\nexport interface RecoveryRethrow {\n  readonly [RECOVERY]: true;\n  readonly kind: \"rethrow\";\n}\n\n/**\n * Branded directive an error handler may return instead of a recovery\n * body. Plain return values (anything unbranded) keep their existing\n * meaning: they become the recovered exchange body. The brand makes the\n * directive unambiguous, so a handler that legitimately recovers with a\n * `{ kind: \"drop\" }`-shaped body is never misread; directives are only\n * created via the {@link recovery} helpers.\n */\nexport type Recovery = RecoveryDrop | RecoveryRethrow;\n\n/**\n * Helpers for building {@link Recovery} directives inside `.error()`\n * handlers (route scope and step scope alike).\n *\n * @example\n * ```ts\n * craft()\n *   .error((err, ex) =>\n *     isTransient(err) ? recovery.rethrow() : recovery.drop(\"poison message\"),\n *   )\n *   .from(source)\n * ```\n */\nexport const recovery = {\n  /**\n   * Drop the failing exchange. The `reason` surfaces on the\n   * `route:exchange:dropped` event (and the TUI), mirroring filter drop\n   * semantics.\n   */\n  drop(reason = \"error-handler-drop\"): RecoveryDrop {\n    return { [RECOVERY]: true, kind: \"drop\", reason };\n  },\n\n  /**\n   * Decline recovery and propagate the original error, exactly as if the\n   * handler had thrown it.\n   */\n  rethrow(): RecoveryRethrow {\n    return { [RECOVERY]: true, kind: \"rethrow\" };\n  },\n};\n\n/**\n * Type guard for {@link Recovery} directives. Checks the brand AND the\n * directive shape: a branded object with an unknown `kind` (e.g. a\n * hand-built object reusing the `Symbol.for` brand) must not pass as a\n * directive, so only the two known shapes are accepted; anything else\n * keeps its plain-recovery-body meaning.\n */\nexport function isRecovery(value: unknown): value is Recovery {\n  if (!isBranded(value, RECOVERY)) return false;\n  const directive = value as { kind?: unknown; reason?: unknown };\n  return (\n    directive.kind === \"rethrow\" ||\n    (directive.kind === \"drop\" && typeof directive.reason === \"string\")\n  );\n}\n\n/**\n * Apply a {@link RecoveryDrop} directive on behalf of an error handler:\n * mark the exchange dropped and emit the recovery lifecycle events. The\n * single implementation keeps route-scope (pipeline executor) and\n * step-scope (ErrorWrapperStep) drop semantics identical.\n *\n * Marks BEFORE emitting so a subscriber observing the events sees\n * `isDropped(exchange) === true`; the route engine reads the flag to skip\n * `route:exchange:completed`.\n *\n * @internal\n */\nexport function applyDropDirective(args: {\n  context: CraftContext;\n  routeId: string;\n  exchange: Exchange;\n  /** The error the handler was invoked with. */\n  originalError: unknown;\n  /** Step label of the operation that failed. */\n  failedOperation: string;\n  correlationId: string;\n  /** Drop reason from the directive, surfaced on `route:exchange:dropped`. */\n  reason: string;\n  scope: \"route\" | \"step\";\n  /**\n   * Owning route. Present at route scope, where the handler resolution\n   * additionally emits `route:error:caught` (the event the docs attribute\n   * to route-handler recovery); step scope never emitted it.\n   */\n  route?: Route;\n  stepLabel?: string;\n}): void {\n  const {\n    context,\n    routeId,\n    exchange,\n    originalError,\n    failedOperation,\n    correlationId,\n    reason,\n    scope,\n    route,\n    stepLabel,\n  } = args;\n\n  // Mark eagerly (ahead of the final mark-and-emit below) so subscribers\n  // to `route:error:caught`, whose payload carries the exchange, already\n  // observe `isDropped(exchange) === true`.\n  markDropped(exchange);\n\n  if (scope === \"route\" && route) {\n    context.emit(\"route:error:caught\", {\n      routeId,\n      error: originalError,\n      route,\n      exchange,\n    });\n  }\n\n  context.emit(\"route:error-handler:recovered\", {\n    routeId,\n    exchangeId: exchange.id,\n    correlationId,\n    originalError,\n    failedOperation,\n    recoveryStrategy:\n      scope === \"route\" ? \"route-error-handler\" : \"step-error-handler\",\n    scope,\n    ...(stepLabel !== undefined ? { stepLabel } : {}),\n  });\n\n  emitExchangeDropped(context, {\n    routeId,\n    correlationId,\n    reason,\n    exchange,\n  });\n}\n","import type { CraftContext } from \"../context.ts\";\nimport { rcError } from \"../error.ts\";\nimport {\n  type Exchange,\n  DefaultExchange,\n  HeadersKeys,\n  asideSequenceOf,\n  markDeferred,\n  noteAsideSequence,\n} from \"../exchange.ts\";\nimport type { DeferRequest } from \"./sites.ts\";\nimport {\n  actionFingerprint,\n  continuationTailHash,\n  describeSchema,\n} from \"./hash.ts\";\nimport {\n  DeferralHeaders,\n  effectiveSequence,\n  deferralIdOf,\n} from \"./exchange-state.ts\";\nimport { DEFERRAL_RUNTIME } from \"./runtime-key.ts\";\nimport { serializeExchange } from \"./serialize.ts\";\nimport { type Deferred, createDeferred } from \"./deferred.ts\";\nimport type { NewDeferral } from \"./types.ts\";\n\n/**\n * Deferring an exchange: everything that happens between a `.defer()`\n * producing its outcome and execution one answering.\n *\n * Ordering is deliberate and load-bearing. The exchange is serialized\n * FIRST, so the three serialization rules (no live values, no secrets, no\n * live-verified principal) fail the step before anything is written or\n * emitted; the store write comes next, so nothing is announced that cannot\n * be resumed; the mark and the event come last, once the deferral is\n * durable. A failure anywhere in here is an ordinary step failure and\n * reaches the route's `.error()` handler, because the exchange has not been\n * deferred and the route still owns it.\n *\n * @param context - Context whose deferral runtime holds the store and signer\n * @param exchange - The exchange as the defer step handed it over\n * @param request - What the defer step resolved: schema, meta, TTL, and site\n * @param routeId - Route the deferred exchange belongs to\n * @param abortSignal - The run's cancellation signal; an abort that lands\n *   during the store write denies the just-created deferral and fails the\n *   deferral with RC5054 before anything is announced\n * @returns The exchange execution one terminates with, its body replaced by\n *   the {@link Deferred} acknowledgment\n * @throws RC5052 when the context has no deferral runtime, RC5042 when\n *   the exchange cannot be persisted, RC5044 when the store write fails,\n *   RC5054 when the run was cancelled around the write\n *\n * @internal\n */\nexport async function deferExchange(\n  context: CraftContext,\n  exchange: Exchange,\n  request: DeferRequest,\n  routeId: string,\n  abortSignal?: AbortSignal,\n): Promise<Exchange> {\n  const runtime = context.getStore(DEFERRAL_RUNTIME);\n  if (!runtime) {\n    throw rcError(\"RC5052\", undefined, {\n      message: `Route \"${routeId}\" reached a .defer() but this context has no deferral runtime. Add deferral: {} to defineConfig.`,\n    });\n  }\n\n  // Per-defer `ttl` first, then the context default. A deferral with\n  // no deadline at all is only reachable through `defaultTtl: \"never\"`,\n  // because a deferral nobody resumes should eventually reach the route\n  // that asked for it rather than sit in the store forever.\n  const { id, deferring, record } = describeRecord(\n    exchange,\n    routeId,\n    request,\n    request.expiresInMs ?? runtime.defaultTtlMs,\n  );\n  const schema = record.schema;\n\n  await runtime.store.create(record);\n\n  // A cancellation that raced the store write and lost is resolved HERE,\n  // after the durable write but before the mark and the announcement: the\n  // just-created deferral is denied (claim-first, so a replayed token\n  // reads RC5050 from the settled path) and the run fails with RC5054\n  // without ever emitting `route:exchange:deferred`. Announcing first\n  // would give one `route:exchange:started` two terminals, breaking the events\n  // page's exactly-one lifecycle guarantee.\n  if (abortSignal?.aborted) {\n    const settled = await denyDeferredOnCancellation(\n      context,\n      deferring,\n      id,\n      routeId,\n      record.expiresAt,\n    );\n    // The RC5054 must land whatever the store does (the caller was told\n    // the run failed), but it must not claim a denial that did not commit:\n    // a store failure leaves the link live until the ttl retires it, and\n    // the error-level log above is the operator's cue to settle it by hand.\n    throw rcError(\"RC5054\", abortSignal.reason, {\n      message: settled\n        ? `Route \"${routeId}\" deferred an exchange while its run was being cancelled; the deferral was denied so its resume link is dead.`\n        : record.expiresAt\n          ? `Route \"${routeId}\" deferred an exchange while its run was being cancelled, and denying the deferral failed; its resume link may stay live until the ttl retires it (deferral \"${id}\", see the error log).`\n          : `Route \"${routeId}\" deferred an exchange while its run was being cancelled, and denying the deferral failed; its resume link has no expiry, so it stays live until an operator settles it (deferral \"${id}\", see the error log).`,\n    });\n  }\n\n  // After the durable write, not before: this file's ordering promises that\n  // nothing is announced that cannot be resumed, and a deferral that fails at\n  // serialization or the store write must not leave an operator a warning\n  // about a deferral that never existed.\n  if (schema.degraded) {\n    deferring.logger.warn(\n      { deferralId: id, routeId, position: request.site.position },\n      \"The resume-payload schema advertises a JSON Schema extension that produced nothing, so this deferral cannot detect a changed schema: only the step tail is covered. Zod throws for a Date, a bigint or any transform.\",\n    );\n  }\n\n  const ack: Deferred = createDeferred({\n    deferralId: id,\n    token: runtime.signer.mint(id, new Date(), request.callBinding),\n    ...(schema.jsonSchema !== undefined ? { schema: schema.jsonSchema } : {}),\n    ...(record.expiresAt ? { expiresAt: record.expiresAt.toISOString() } : {}),\n  });\n\n  const deferred = DefaultExchange.rewrap(deferring, { body: ack });\n  markDeferred(deferred);\n  context.emit(\"route:exchange:deferred\", {\n    routeId,\n    exchangeId: deferred.id,\n    correlationId: deferred.headers[HeadersKeys.CORRELATION_ID] as string,\n    deferralId: id,\n    position: request.site.position,\n    ...(record.expiresAt ? { expiresAt: record.expiresAt } : {}),\n  });\n  deferred.logger.info(\n    { deferralId: id, routeId, position: request.site.position },\n    \"Exchange deferred\",\n  );\n  return deferred;\n}\n\n/**\n * The record a deferral writes, and the exchange it was taken from.\n *\n * Shared by the two ways an exchange reaches the store: a `.defer()`\n * deferral, which replaces the run's outcome with the acknowledgment, and an\n * aside deferral, which stores a continuation for a run that completes\n * normally. Both must agree on the id, the sequence, the serialised\n * exchange and the hash, or a revival of one would not find what the\n * other wrote.\n */\nfunction describeRecord(\n  exchange: Exchange,\n  routeId: string,\n  request: Pick<\n    DeferRequest,\n    \"site\" | \"schema\" | \"meta\" | \"callBinding\" | \"stepState\"\n  >,\n  ttlMs: number | undefined,\n): { id: string; deferring: Exchange; record: NewDeferral } {\n  const floor = asideSequenceOf(exchange);\n  const sequence = effectiveSequence(exchange.headers, floor);\n  const id = deferralIdOf(exchange.headers, exchange.id, floor);\n  // The deferred exchange carries the sequence its successor will use, so a\n  // route that defers, resumes, and defers again mints a fresh id\n  // rather than colliding with the record it just settled.\n  const deferring = DefaultExchange.rewrap(exchange, {\n    headers: {\n      ...exchange.headers,\n      [DeferralHeaders.SEQUENCE]: sequence + 1,\n    },\n  });\n\n  const schema = describeSchema(request.schema);\n  const serialized = serializeExchange(deferring);\n  // The site's continuation is exactly what a resume would run: for a\n  // static `.defer()` it excludes the step itself (it already ran), and\n  // for a re-entrant site it includes it (it runs again). The hash covers\n  // whichever is true.\n  const hash = continuationTailHash(request.site.continuation, schema);\n  // `stepState` crosses the persistence boundary raw: the store's `create`\n  // applies the same plain-JSON rule as the exchange (both backends encode\n  // it, refusing a resolver, a secret, or a non-envelope Date with RC5042),\n  // so the deferral still fails here rather than surprising the revival, and\n  // encoding happens exactly once. Encoding it here too would double-wrap\n  // the Date envelope, which the second pass refuses as a reserved shape.\n  const stepState = request.stepState;\n  const deferredAt = new Date();\n  const record: NewDeferral = {\n    id,\n    routeId,\n    position: request.site.position,\n    continuationHash: hash,\n    exchange: serialized,\n    schema,\n    ...(request.meta !== undefined ? { meta: request.meta } : {}),\n    ...(request.callBinding !== undefined\n      ? { callBinding: request.callBinding }\n      : {}),\n    ...(stepState !== undefined ? { stepState } : {}),\n    actionFingerprint: actionFingerprint({\n      routeId,\n      position: request.site.position,\n      continuationHash: hash,\n      exchange: serialized,\n    }),\n    deferredAt,\n    waitingFor: \"resume\",\n    ...(ttlMs !== undefined\n      ? { expiresAt: new Date(deferredAt.getTime() + ttlMs) }\n      : {}),\n  };\n  return { id, deferring, record };\n}\n\n/**\n * Store a continuation for an exchange that completes normally.\n *\n * A `.defer()` deferral ends the run and answers with the acknowledgment. An\n * aside deferral does not: the run goes on to complete, and what is stored is\n * a way to re-enter the route at `site` later, on this process, with the\n * exchange's body and headers exactly as a deferral stores them. The agent\n * tier uses it for a session turn that ends with work still outstanding\n * (a background tool running, messages queued): the caller has its reply,\n * and the continuation is what a completion revives to run the next turn\n * and the route's downstream steps.\n *\n * No `route:exchange:deferred` is emitted and the exchange is not marked\n * deferred, because it is not: it completes, and one `route:exchange:started`\n * must reach exactly one terminal. Revival is a first-class run of the\n * route with its own pair. The record carries no deadline, since what it\n * waits on has none the framework knows.\n *\n * @param stepState - Built from the deferral id, so the state a revival\n *   hands back can name the record it came from\n * @param announce - Awaited with the id before the record is written, so\n *   the caller's own record can name the deferral from the first write on\n * @returns The deferral id, which `reviveDeferral` takes back\n * @throws RC5052 without a deferral runtime, RC5042 when the exchange\n *   cannot be persisted, RC5044 when the store write fails\n *\n * @internal\n */\nexport async function deferAside(\n  context: CraftContext,\n  exchange: Exchange,\n  site: DeferRequest[\"site\"],\n  routeId: string,\n  stepState: (deferralId: string) => unknown,\n  announce?: (deferralId: string) => Promise<void>,\n): Promise<{ deferralId: string }> {\n  const runtime = context.getStore(DEFERRAL_RUNTIME);\n  if (!runtime) {\n    throw rcError(\"RC5052\", undefined, {\n      message: `Route \"${routeId}\" needs a continuation stored for a later turn, and this context has no deferral runtime. Add deferral: {} to defineConfig.`,\n    });\n  }\n  const floor = asideSequenceOf(exchange);\n  const sequence = effectiveSequence(exchange.headers, floor);\n  const id = deferralIdOf(exchange.headers, exchange.id, floor);\n  const { record } = describeRecord(\n    exchange,\n    routeId,\n    { site, stepState: stepState(id) },\n    undefined,\n  );\n  // The caller learns the id before the record exists, so what it keeps\n  // can name the deferral from the first write on: a crash between the two\n  // leaves a reference to release, not a record nothing points at, and an\n  // aside deferral has no expiry to retire it otherwise.\n  if (announce) await announce(id);\n  await runtime.store.create(record);\n  // The run goes on with this exchange, and its headers are frozen: the\n  // successor sequence the record carries is noted on the exchange too,\n  // so a `.defer()` later in the same run does not derive this id.\n  noteAsideSequence(exchange, sequence + 1);\n  return { deferralId: id };\n}\n\n/**\n * Deny a deferral whose run was cancelled after the deferral committed.\n *\n * The abort raced the store write and lost, so a caller who is being told\n * the run failed would otherwise leave behind a live resume link: an\n * approver clicking it days later would run a continuation for work whose\n * caller already saw a cancellation. Claim-first, like expiry and the\n * changed-continuation denial, so a crash between the transition and the\n * caller's cancellation error still leaves the record deniable rather than\n * stuck. No re-ask is delivered: the cancellation error the caller receives\n * IS the notification, and a later replay of the token reads the denial as\n * `RC5050` from the settled path.\n *\n * Best effort by design: the cancellation error must reach the caller\n * whatever the store does, so a store failure here is logged and swallowed.\n * The return value keeps the caller's RC5054 honest about what happened.\n *\n * @returns Whether the record is confirmed settled (denied here, or already\n *   settled by whoever won the claim). `false` means the denial failed and\n *   the resume link may still be live.\n *\n * @internal\n */\nasync function denyDeferredOnCancellation(\n  context: CraftContext,\n  exchange: Exchange,\n  deferralId: string,\n  routeId: string,\n  expiresAt?: Date,\n): Promise<boolean> {\n  const runtime = context.getStore(DEFERRAL_RUNTIME);\n  if (!runtime) return false;\n  try {\n    const claim = await runtime.store.claimExpiry(deferralId, new Date());\n    // Losing the claim means someone else already settled the record (an\n    // resume that raced in, the sweeper). Whoever won owns the outcome.\n    if (!claim.won) return true;\n    // `markDenied` is itself a compare-and-swap against the claim. Reporting\n    // a confirmed denial without reading it would be the one thing this\n    // return value exists to prevent: if the claim's lease elapsed in\n    // between, `releaseClaims` has cleared it, the record is resumable\n    // again, and the link the caller was told is dead comes back.\n    const denied = await runtime.store.markDenied(deferralId, \"run cancelled\");\n    if (!denied.won) {\n      exchange.logger.error(\n        { deferralId, routeId, expiresAt },\n        \"A deferral deferred by a cancelled run lost its denial transition, so its resume link may become live again when the expiry claim is released.\",\n      );\n    }\n    return denied.won;\n  } catch (err) {\n    exchange.logger.error(\n      { deferralId, routeId, expiresAt, err },\n      expiresAt\n        ? \"Could not deny a deferral deferred by a cancelled run. Its resume link stays live until the ttl retires it.\"\n        : 'Could not deny a deferral deferred by a cancelled run. It has no ttl (defaultTtl: \"never\"), so its resume link stays live until it is settled by hand.',\n    );\n    return false;\n  }\n}\n","/**\n * Reading the non-standard `~standard.jsonSchema` extension.\n *\n * Standard Schema itself defines no JSON Schema export, so everything here\n * is opportunistic: Zod, ArkType and the AI SDK bridge expose the extension,\n * and a library without it yields nothing while nothing else changes.\n *\n * Two callers share it for different reasons. The deferral descriptor\n * (`deferral/hash.ts`) folds the rendering into `continuationHash` so a\n * schema edited under a deferred exchange is caught. The ops management API\n * publishes it so an operator can see what a route accepts without reading\n * the source.\n *\n * The dialect is a required argument rather than a default here, because\n * one of those callers hashes what comes back: a default changed in this\n * module would change every stored digest without a line of deferral code\n * moving. Each caller pins its own constant and passes it.\n *\n * The module also holds `isStandardSchema`, which reads the same bag for a\n * callable `validate` rather than for the JSON Schema arms.\n */\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/** The `~standard` bag, as far as anything here reads it. */\nexport interface StandardExtension {\n  vendor?: string;\n  version?: number;\n  validate?: unknown;\n  jsonSchema?: { input?: unknown; output?: unknown };\n}\n\n/**\n * Read a schema's `~standard` bag, or `undefined` when it carries none.\n *\n * Functions count. An ArkType schema is a callable object carrying the bag,\n * and `validate()` works on one, so a test that admitted only `\"object\"`\n * was narrower than the validation it feeds.\n */\nexport function standardExtensionOf(\n  schema: unknown,\n): StandardExtension | undefined {\n  if (\n    schema === null ||\n    (typeof schema !== \"object\" && typeof schema !== \"function\")\n  ) {\n    return undefined;\n  }\n  return (schema as { \"~standard\"?: StandardExtension })[\"~standard\"];\n}\n\n/**\n * Whether a value is a Standard Schema carrying a callable validator.\n *\n * The check every validation boundary has to make before handing a\n * caller-supplied value to `validateAgainst`, which dereferences\n * `~standard.validate` without guarding. Seven sites hand-rolled the same\n * index cast and predicate before this existed (#575).\n *\n * Deliberately only the predicate: the refusal stays with the caller,\n * because the error code and message differ per boundary on purpose. A\n * plugin option validator throws a plain `Error` for its own message, the\n * fn registry throws `RC5003` naming the fn, and the structured-text\n * fallback declines to a `undefined` rather than throwing at all.\n *\n * @param value - Any value, typically arriving from user configuration\n * @returns Whether `value[\"~standard\"].validate` is callable. That is all it\n *   proves: `version` and `vendor` are spec-required but not checked, and\n *   the local `StandardExtension` treats both as optional because schemas\n *   omitting them reach the framework in practice. A caller that reads\n *   either should still guard it.\n *\n * @example\n * ```ts\n * if (!isStandardSchema(schema)) {\n *   throw new Error(\"options.schema must be a Standard Schema\");\n * }\n * const result = await validateAgainst(schema, value);\n * ```\n */\nexport function isStandardSchema(value: unknown): value is StandardSchemaV1 {\n  return typeof standardExtensionOf(value)?.validate === \"function\";\n}\n\n/**\n * Resolve one arm of the extension to a rendered JSON Schema.\n *\n * The arm is either the rendered schema or a producer for it (Zod 4 ships\n * the lazy form). A producer is vendor code, so a throwing one yields no\n * rendering rather than propagating: the rendering is descriptive, and the\n * live schema is what validation actually runs against.\n *\n * A producer is called with the spec's options first and then, if that\n * throws, with none. Standard JSON Schema types both arms as\n * `(options: { target }) => ...`, so an implementation is entitled to read\n * `options.target` and throw without it; the second attempt covers one\n * predating the options argument.\n *\n * @internal\n */\nexport function renderJsonSchemaArm(arm: unknown, target: string): unknown {\n  if (arm === undefined || arm === null) return undefined;\n  if (typeof arm !== \"function\") return arm;\n  const producer = arm as (options?: { target: string }) => unknown;\n  for (const call of [() => producer({ target }), () => producer()]) {\n    try {\n      const produced = call();\n      if (produced !== null && produced !== undefined) return produced;\n    } catch {\n      // Try the next calling convention; an arm that yields nothing at all\n      // is the caller's business to report, not this function's.\n    }\n  }\n  return undefined;\n}\n","import { createHash } from \"node:crypto\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { getAdapterArgs } from \"../adapters/shared/factory-tag.ts\";\nimport type { Adapter, Step } from \"../types.ts\";\nimport {\n  renderJsonSchemaArm,\n  standardExtensionOf,\n} from \"../shared/standard-schema.ts\";\nimport type { SerializedExchange, DeferralSchema } from \"./types.ts\";\n\n/**\n * Hash the continuation of a deferred exchange: the steps that have NOT run\n * yet, plus the schema the eventual resume payload is validated against.\n *\n * ## Why the tail and not the pipeline\n *\n * Steps before the defer point already ran. Changing one cannot affect\n * what happens after resume, so including them would invalidate every\n * approval in flight on any deploy that touched the route, and the approver\n * would discover it by clicking a dead link. Hashing from `position + 1`\n * onward keeps the property worth keeping (a change to what the approval\n * authorizes invalidates it) and drops the one that made it unusable.\n *\n * ## What the hash does NOT cover\n *\n * Step DEFINITIONS only. A `direct()` route the tail forwards to, an\n * adapter version, an environment variable, or any external system the tail\n * reaches can all change freely without moving this hash. That residue is\n * deliberate, and the mitigations are the catchable error-channel re-ask\n * path and `actionFingerprint`'s audit binding. Never describe the hash as\n * covering more than step definitions.\n *\n * Option VALUES have their own residue, and it is narrower than it looks.\n * `describable` projects the carriers an adapter option realistically names\n * a target with (string, number, boolean, `Date`, `URL`, `RegExp`, `Map`,\n * `Set`, arrays, plain objects), but any other class instance collapses to\n * `[opaque]` and anything nested five deep collapses to `[deep]`. Two\n * options differing only there hash alike, so an adapter that hides its\n * target inside a bespoke config class is outside the compatibility check.\n * Prefer plain options on a route that defers.\n *\n * ## What makes it move\n *\n * Each step contributes its operation kind, its DSL label, its adapter id,\n * the source text of the callables the adapter carries (where a user's\n * inline lambda lives), and the adapter's own data properties (where an\n * adapter's options live). So `.transform((p) => payOut(p))` becoming\n * `.transform((p) => payOutTwice(p))` moves the hash, and so does\n * `http({ url: bankA })` becoming `http({ url: bankB })`, while editing\n * `payOut` itself does not: that is the \"step definitions only\" boundary\n * stated above, seen from the other side.\n *\n * ## The design rule: never normalize the source\n *\n * Function source is taken VERBATIM. Do not add whitespace collapsing,\n * formatting normalization, or any other canonicalization ahead of this\n * digest, however safe a given transformation looks.\n *\n * The reasoning is asymmetric and it is the whole argument. Normalization\n * can only ever fold two distinct sources onto one digest. Every such fold\n * is a chance to MISS a change, and a missed change means a deferred approval\n * resumes into behaviour its approver never authorized. The opposite error,\n * treating an inert edit as a change, costs an error-channel re-ask, which\n * is a path this design already provides and expects to be used.\n *\n * This was learned rather than assumed. An earlier revision normalized\n * whitespace outside string literals with a hand-rolled scanner. Review\n * found three separate ways to desynchronize it (automatic semicolon\n * insertion, regex literals, and an apostrophe inside a comment), each\n * fixable only by moving closer to a real JavaScript tokenizer, and each\n * failing in the direction that resumes a deferred approval into different\n * behaviour. The scanner was deleted rather than completed.\n *\n * ## What that costs, and why it is the right trade\n *\n * The hash reads emitted text, so it is sensitive to more than the source\n * tree: a formatting pass, a checkout with different line endings, or a\n * build that changes emitted text (a different minifier, new bundler\n * settings, a TypeScript target bump) all move it for steps whose behaviour\n * did not change. Every one of those outcomes is an error-channel re-ask,\n * never a wrong resume. Deployments that defer approvals for days should pin\n * line endings and build settings; the configuration reference says so for\n * users.\n *\n * @param tail - Steps from the one after the deferring step to the end.\n * @param schema - The resume-payload schema descriptor.\n * @returns A hex SHA-256 digest.\n *\n * @internal\n */\n\n/**\n * Hash an already-resolved continuation tail. The tail is exactly what a\n * resume would run, which for a static `.defer()` is the steps after it\n * and for a re-entrant site includes the deferring step itself at its\n * head. Same digest as {@link continuationHash} over the equivalent slice,\n * so records deferred before this helper existed keep verifying.\n *\n * @internal\n */\nexport function continuationTailHash(\n  tail: ReadonlyArray<Step<Adapter>>,\n  schema: DeferralSchema,\n): string {\n  return sha256(\n    canonical({\n      tail: tail.map(describeStep),\n      // Kept under the historical key so a digest computed before the\n      // rename verifies unchanged. The wire and the record moved; this\n      // string is an internal hash input nobody reads.\n      expect: schema.hash,\n    }),\n  );\n}\n\n/**\n * Describe the expected-result schema for storage and hashing.\n *\n * The schema itself is a live object with a validate function, so it cannot\n * be persisted. What is persisted is this descriptor: a hash that folds\n * into {@link continuationHash} so a schema changed under a deferred exchange\n * is caught, plus an optional JSON Schema rendering for the caller and the\n * operator. Validation at resume always runs against the live schema read\n * back off the route.\n *\n * The rendering comes from the non-standard `~standard.jsonSchema`\n * extension that Zod, ArkType, and the AI SDK bridge expose. Standard\n * Schema itself defines no JSON Schema export, so a schema library without\n * that extension simply yields no rendering; nothing else changes.\n *\n * The extension's arms may be the rendered schema OR a function that\n * produces it on demand (Zod 4 ships the lazy form), so\n * {@link renderJsonSchemaArm} resolves either. Storing the unresolved function instead would be\n * quietly destructive twice over: it cannot be persisted, and it hashes to\n * the same digest for EVERY schema, which silently disables the\n * changed-schema half of the compatibility check.\n *\n * A site that declares NO schema gets the absent sentinel rather than an\n * empty descriptor. The two are different facts and must hash differently:\n * \"declared a schema whose rendering was lost\" still validates the payload at\n * resume, while \"declared nothing\" does not, so collapsing them would let an\n * edit between the two pass the compatibility check unnoticed.\n *\n * @param schema - The `schema` declared on `.defer()`, if any.\n * @returns A serializable descriptor of the schema.\n *\n * @internal\n */\nexport function describeSchema(schema?: StandardSchemaV1): DeferralSchema {\n  if (!schema) {\n    return { hash: sha256(canonical({ absent: true })), absent: true };\n  }\n  const standard = standardExtensionOf(schema);\n  const arms = [standard?.jsonSchema?.output, standard?.jsonSchema?.input];\n  const jsonSchema =\n    renderJsonSchemaArm(arms[0], JSON_SCHEMA_TARGET) ??\n    renderJsonSchemaArm(arms[1], JSON_SCHEMA_TARGET);\n  // Without a rendering there is nothing schema-specific to hash, so the\n  // descriptor falls back to vendor and version. That fallback is identical\n  // for every schema the vendor produces, which means the changed-`expect`\n  // half of the compatibility check cannot fire for this deferral: only\n  // the step tail is still covered.\n  //\n  // The two ways to get here are not equally expected, and the caller is\n  // told which. A library with no `jsonSchema` extension at all never had a\n  // rendering to lose. A library that OFFERS the extension and then yields\n  // nothing has lost one it advertised, and that is worth a word at the deferral\n  // rather than a surprise at the approver's click.\n  const degraded =\n    jsonSchema === undefined && standard?.jsonSchema !== undefined;\n  const identity =\n    jsonSchema !== undefined\n      ? { jsonSchema }\n      : {\n          vendor: standard?.vendor ?? \"unknown\",\n          version: standard?.version ?? 0,\n        };\n  return {\n    hash: sha256(canonical(identity)),\n    ...(jsonSchema !== undefined ? { jsonSchema } : {}),\n    ...(degraded ? { degraded: true } : {}),\n  };\n}\n\n/**\n * JSON Schema dialect asked of a producer.\n *\n * Standard JSON Schema types both arms as `(options: { target }) => …`, so\n * the argument is required rather than optional: an implementation is\n * entitled to read `options.target` and throw without it. Zod 4 tolerates\n * the omission, which is why calling with no argument looked correct.\n * Pinned rather than configurable, because the value is folded into\n * `continuationHash`: letting it vary would change every stored digest.\n */\nconst JSON_SCHEMA_TARGET = \"draft-2020-12\";\n\n/**\n * Bind an approval to the operation it authorized.\n *\n * Without this, a receipt says \"someone approved deferral abc123\". With\n * it, the receipt says \"this principal authorized this exact operation on\n * this exact payload\". It costs one hash and turns the audit trail from a\n * reference into evidence.\n *\n * This is audit-grade binding, not a second access control: the frozen\n * exchange already stops payload tampering, and `continuationHash` already\n * catches a changed continuation.\n *\n * @param input - Route identity, defer position, the continuation hash,\n *   and the serialized exchange whose body was shown to the approver.\n * @returns A hex SHA-256 digest.\n *\n * @internal\n */\nexport function actionFingerprint(input: {\n  routeId: string;\n  position: number;\n  continuationHash: string;\n  exchange: SerializedExchange;\n}): string {\n  return sha256(\n    canonical({\n      routeId: input.routeId,\n      position: input.position,\n      continuationHash: input.continuationHash,\n      body: input.exchange.body,\n    }),\n  );\n}\n\n/**\n * Digest of one step's definition: the projection {@link continuationHash}\n * applies to each tail step (operation kind, label, adapter id, callable\n * source, adapter options). Inherits the same \"step definitions only\"\n * boundary and the same verbatim-source rule.\n *\n * @internal\n */\nexport function stepDefinitionFingerprint(step: Step<Adapter>): string {\n  return sha256(canonical(describeStep(step)));\n}\n\n/**\n * Digest of a definition value that lives outside a step's adapter: a\n * wrapper's options as its `describeOptions()` reports them, or the\n * predicate selecting a `.choice()` branch. The same projection a step's\n * adapter options go through, so callables contribute their verbatim\n * source and anything the projection cannot represent collapses to its\n * stable placeholder.\n *\n * @internal\n */\nexport function definitionFingerprint(value: unknown): string {\n  return sha256(canonical(describable(value)));\n}\n\n/**\n * Reduce a step to the parts that define what it will do.\n *\n * Two kinds of own property carry that definition, and both have to be in\n * the digest. Callables are where an inline lambda lives on a plain-object\n * adapter (`.transform((p) => payOut(p))`). Data properties are where an\n * adapter's OPTIONS live: a class-based adapter such as the http enricher\n * keeps its config in an `options` property and exposes a `fetch` whose\n * source text is identical for every instance, so hashing callables alone\n * would give `http({ url: bankA })` and `http({ url: bankB })` the same\n * digest and let a deferred approval resume into a different payee.\n *\n * `adapterId` is read separately and excluded from the config walk so it is\n * not counted twice.\n *\n * @internal\n */\nfunction describeStep(step: Step<Adapter>): unknown {\n  const adapter = step.adapter as Record<string, unknown> | undefined;\n  const callables: Record<string, string> = {};\n  const config: Record<string, unknown> = {};\n  if (adapter) {\n    for (const key of Object.keys(adapter).sort()) {\n      if (key === \"adapterId\") continue;\n      const value = adapter[key];\n      if (typeof value === \"function\") callables[key] = sourceOf(value);\n      else config[key] = describable(value);\n    }\n  }\n  return {\n    operation: step.operation,\n    label: step.label ?? null,\n    adapterId: (adapter?.[\"adapterId\"] as string | undefined) ?? null,\n    callables,\n    config,\n    // The own-property walk above only reaches an adapter that keeps its\n    // options on itself. Every factory-built adapter returns a role facade\n    // (`{ adapterId, subscribe, send, fetch }`) whose slots are bound\n    // methods of a delegate holding the options, so its own properties are\n    // functions with identical source for every instance: without this,\n    // `file({ path: a })` and `file({ path: b })` describe identically.\n    // `tagAdapter` already records what the factory was called with, which\n    // is the configuration in its most direct form.\n    args: (getAdapterArgs(adapter) ?? []).map((arg) => describable(arg)),\n  };\n}\n\n/**\n * Project an adapter option into something hashable.\n *\n * Total by construction, because adapters legitimately hold live clients,\n * sockets and credentials alongside their config. Anything the digest\n * cannot represent collapses to a stable placeholder rather than throwing:\n * a step whose adapter holds a socket must still be hashable, it just\n * cannot contribute that field to the comparison.\n *\n * @internal\n */\nfunction describable(value: unknown, depth = 0): unknown {\n  if (value === null) return null;\n  const kind = typeof value;\n  if (kind === \"string\" || kind === \"boolean\") return value;\n  if (kind === \"number\") return Number.isFinite(value) ? value : \"[number]\";\n  if (kind === \"bigint\") return `[bigint:${String(value)}]`;\n  if (kind === \"undefined\") return undefined;\n  if (kind === \"symbol\") return \"[unhashable]\";\n  // A callback nested in options is a step definition just as much as a\n  // top-level adapter callable: `http({ url: (ex) => bankA(ex) })` and the\n  // same with `bankB` differ only here. Collapsing it to a placeholder\n  // would let the tail's actual target change under a deferred approval.\n  if (kind === \"function\") return sourceOf(value as object);\n  if (value instanceof Date) return value.toISOString();\n  // Carriers an adapter option realistically uses to name its target. Left\n  // to the opaque collapse below they would all hash alike, so a payee\n  // spelled `new URL(...)` could be edited under a deferred approval without\n  // moving the digest.\n  if (value instanceof URL) return `[url:${value.href}]`;\n  if (value instanceof RegExp) return `[regexp:${value.source}/${value.flags}]`;\n  // Bound the walk: a deeply nested or self-referential options object must\n  // not turn hashing a route into a graph traversal. Above every branch that\n  // recurses, collections included, or a cycle through a Map never reaches it.\n  if (depth >= 4) return \"[deep]\";\n  if (value instanceof Map) {\n    return {\n      \"[map]\": [...value].map(([key, entry]) => [\n        describable(key, depth + 1),\n        describable(entry, depth + 1),\n      ]),\n    };\n  }\n  if (value instanceof Set) {\n    return {\n      \"[set]\": [...value].map((entry) => describable(entry, depth + 1)),\n    };\n  }\n  if (Array.isArray(value)) {\n    return value.map((entry) => describable(entry, depth + 1));\n  }\n  const prototype = Object.getPrototypeOf(value as object);\n  if (prototype !== Object.prototype && prototype !== null) return \"[opaque]\";\n  // Null-prototype accumulator, for the same reason `serialize.ts` uses one:\n  // `__proto__` is a genuine own key on anything that came from JSON.parse,\n  // and assigning it on an object literal hits the Object.prototype setter,\n  // which drops the field. Dropped here it would let a tail option carrying\n  // that key change under a deferred approval without moving the digest.\n  const projected: Record<string, unknown> = Object.create(null);\n  for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n    projected[key] = describable(entry, depth + 1);\n  }\n  return projected;\n}\n\n/**\n * A function's source text, verbatim.\n *\n * Deliberately not normalized. See the design rule on\n * {@link continuationHash}: anything that folds two distinct sources onto\n * one digest can only weaken this hash, and the only failure it can produce\n * is the one the hash exists to prevent.\n *\n * @internal\n */\nfunction sourceOf(fn: object): string {\n  return Function.prototype.toString.call(fn);\n}\n\n/**\n * Deterministic JSON with object keys sorted at every depth, so two\n * structurally equal values always hash to the same digest regardless of\n * insertion order.\n *\n * @internal\n */\nfunction canonical(value: unknown): string {\n  if (value === null || typeof value !== \"object\") {\n    return JSON.stringify(value) ?? \"null\";\n  }\n  if (Array.isArray(value)) {\n    return `[${value.map(canonical).join(\",\")}]`;\n  }\n  const entries = Object.entries(value as Record<string, unknown>)\n    .filter(([, entry]) => entry !== undefined)\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n    .map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`);\n  return `{${entries.join(\",\")}}`;\n}\n\n/** @internal */\nfunction sha256(input: string): string {\n  return createHash(\"sha256\").update(input, \"utf8\").digest(\"hex\");\n}\n\n/**\n * Digest of a deferral's `stepState` slot, used as the compare half of\n * the store's `replaceStepState` compare-and-swap.\n *\n * A digest rather than the value itself, for two reasons. The slot holds an\n * arbitrarily large blob (an agent's whole message thread is the motivating\n * case), and shipping it back to the store to be compared would double the\n * write. And equality on the blob is only meaningful under a canonical\n * form: the two backends round-trip it through different machinery\n * (`structuredClone` and `JSON.parse`), so key order is not a property a\n * caller can rely on. Hashing the canonical rendering makes the comparison\n * structural.\n *\n * A record with no step state gets its own digest, distinct from one\n * holding `null`, rather than being special-cased at every call site. That\n * makes \"the record had no step state\" an expectation a caller can hold and\n * lose like any other.\n */\nexport function stepStateFingerprint(stepState: unknown): string {\n  return sha256(\n    stepState === undefined\n      ? canonical({ absent: true })\n      : canonical({ stepState }),\n  );\n}\n","import { BRAND, isBranded } from \"../brand.ts\";\nimport { rcError } from \"../error.ts\";\nimport {\n  type Exchange,\n  type ExchangeHeaders,\n  DefaultExchange,\n  HeadersKeys,\n} from \"../exchange.ts\";\nimport type { CraftContext } from \"../context.ts\";\nimport { markRestored } from \"../auth/restored.ts\";\nimport type { Principal } from \"../auth/types.ts\";\nimport type { SerializedExchange } from \"./types.ts\";\n\n/**\n * Serialization is a security boundary, not plumbing.\n *\n * Three rules are enforced here, at defer time, so a violation surfaces\n * on the deploy that introduced it rather than days later when an approver\n * clicks a link:\n *\n * 1. **Nothing but plain JSON data is persisted.** Functions, symbols,\n *    bigints, class instances and circular references are refused with\n *    `RC5042`. This is what keeps a live resolver from being written to the\n *    store: a `Blocks` record whose entries are functions cannot cross the\n *    boundary, so only resolved string outputs survive. Blocks declared\n *    `lifetime: \"context\"` are unaffected, because they live in\n *    `context.store`, which outlives the exchange and is never serialized.\n * 2. **Secrets never reach the store.** A value carrying `BRAND.Secret` is\n *    refused. The brand is reserved ahead of #526; the check is live now so\n *    the rule holds the moment `Secret` starts applying it.\n * 3. **A rehydrated principal is not a verified one.** Deserialization\n *    marks it restored rather than authentic, so `authorize()` reports\n *    `RC5043` instead of trusting a shape read off disk. See\n *    `auth/restored.ts` for why deferral is the direct route back into\n *    #355's bug class.\n *\n * ## The wire form\n *\n * Everything a backend receives is JSON data, which is what lets the\n * in-memory and sqlite backends behave identically. `Date` is the one type\n * JSON cannot carry that exchange bodies routinely hold (a mail `date`, a\n * cron tick), so it travels in a tagged envelope, {@link DATE_TAG}, and is\n * revived on the way back. An object whose only key is that tag is\n * therefore reserved; any other non-plain object (a `Uint8Array`, a `Map`,\n * a class instance) is refused rather than silently downgraded to a\n * differently-behaved object wearing the same fields.\n */\n\n/**\n * Envelope key that carries a `Date` through JSON storage. An object whose\n * sole key is this tag is reserved by the framework and is revived as a\n * `Date` on resume.\n */\nexport const DATE_TAG = \"$routecraft.date\";\n\n/**\n * Convert a live exchange into its persistable form.\n *\n * Exactly the two stored slots (`body`, `headers`) cross the boundary, per\n * `.standards/exchange-state-model.md`. Derivations (`id`, `principal`,\n * `logger`) are not persisted separately: `id` and `principal` already live\n * inside `headers`, and `logger` is rebuilt from runtime services on the\n * resuming process.\n *\n * The result is a detached deep copy, so the store never holds a reference\n * into an exchange a later step could still mutate.\n *\n * @param exchange - The exchange being deferred.\n * @returns JSON data safe to hand to any store backend.\n * @throws RC5042 when a value in `body` or `headers` cannot be persisted.\n *\n * @internal\n */\nexport function serializeExchange(exchange: Exchange): SerializedExchange {\n  return {\n    body: encode(exchange.body, \"body\"),\n    headers: encode(exchange.headers, \"headers\") as Readonly<\n      Record<string, unknown>\n    >,\n  };\n}\n\n/**\n * Rebuild a live exchange from its persisted form.\n *\n * The result is a genuine `DefaultExchange` on the resuming context, so the\n * derived accessors work immediately. The route binding is NOT restored\n * here: the resume path owns finding the route by\n * `headers[\"routecraft.route\"]` and binding it, because only it knows which\n * context is reviving the exchange.\n *\n * @param context - The context reviving the exchange.\n * @param serialized - The stored `{ body, headers }` pair.\n * @returns A live exchange whose principal, if any, is marked restored.\n *\n * @internal\n */\nexport function deserializeExchange(\n  context: CraftContext,\n  serialized: SerializedExchange,\n): Exchange {\n  const headers = decode(serialized.headers) as Record<string, unknown>;\n  const principal = headers[HeadersKeys.AUTH_PRINCIPAL];\n  if (\n    principal !== undefined &&\n    typeof principal === \"object\" &&\n    principal !== null\n  ) {\n    headers[HeadersKeys.AUTH_PRINCIPAL] = markRestored(principal as Principal);\n  }\n  return new DefaultExchange(context, {\n    body: decode(serialized.body),\n    headers: headers as ExchangeHeaders,\n  });\n}\n\n/**\n * Run an arbitrary value through the same JSON-data rules the exchange\n * gets, returning a detached copy or throwing `RC5042`.\n *\n * Used for the record's other free-form slots, `stepState` and a terminal\n * outcome's body. They never pass through {@link serializeExchange}, so\n * without this a backend would apply its own rules to them: sqlite would\n * silently drop a function via `JSON.stringify` while the in-memory backend\n * kept it alive through `structuredClone`, and the two would disagree about\n * what a resumed step gets back. `stepState` is opaque to the store, not\n * exempt from being storable.\n *\n * @param value - The value to check and copy.\n * @param path - Label used in the error message when it fails.\n * @throws RC5042 naming the offending path.\n *\n * @internal\n */\nexport function encodePersistable(value: unknown, path: string): unknown {\n  return encode(value, path);\n}\n\n/**\n * The read half of {@link encodePersistable}: revive the reserved envelopes\n * (a `Date` written by `encode`) in a stored free-form slot. `stepState` is\n * the consumer, so a step-owned `Date` round-trips the same way an\n * exchange-held one does rather than resurfacing as the raw envelope\n * object.\n *\n * @internal\n */\nexport function decodePersistable(value: unknown): unknown {\n  return decode(value);\n}\n\n/**\n * Deep-check and copy `value` into JSON data, or throw `RC5042` naming the\n * exact path that failed.\n *\n * Walking the structure ourselves rather than round-tripping through\n * `JSON.stringify` is what makes the failure legible: the message says\n * `headers.routecraft.mail.client holds an instance of ImapFlow`, not\n * \"Converting circular structure to JSON\".\n *\n * `undefined` is dropped from object properties and becomes `null` inside\n * arrays, matching JSON semantics, so a value round-trips identically on\n * every backend rather than depending on which one a deployment resolved.\n *\n * @internal\n */\nfunction encode(\n  value: unknown,\n  path: string,\n  seen: Set<object> = new Set(),\n): unknown {\n  if (value === null || value === undefined) return value;\n\n  const kind = typeof value;\n  if (kind === \"string\" || kind === \"boolean\") return value;\n  if (kind === \"number\") {\n    // NaN and Infinity serialize to null, which would quietly change the\n    // value under a deferred exchange. Refuse instead of rounding it off.\n    if (!Number.isFinite(value)) {\n      throw refuse(path, `a non-finite number (${String(value)})`);\n    }\n    // `JSON.parse(\"-0\")` yields -0, which `JSON.stringify` then writes back\n    // as `0` while `structuredClone` preserves it, so the sqlite and memory\n    // backends would disagree on a value that reached the body from an\n    // ordinary inbound payload. Normalized for the same reason array holes\n    // and `undefined` are: the persisted form must not depend on which\n    // backend a deployment resolved.\n    return Object.is(value, -0) ? 0 : value;\n  }\n  if (kind === \"function\") throw refuse(path, \"a function\");\n  if (kind === \"symbol\") throw refuse(path, \"a symbol\");\n  if (kind === \"bigint\") throw refuse(path, \"a bigint\");\n\n  const object = value as object;\n  if (isBranded(object, BRAND.Secret)) throw refuse(path, \"a Secret\");\n  if (seen.has(object)) throw refuse(path, \"a circular reference\");\n  // A Date SUBCLASS deliberately fails this test and falls through to the\n  // class-instance refusal below: the envelope carries an instant and\n  // nothing else, so a subclass would resume as a plain Date with its added\n  // behaviour gone.\n  if (\n    value instanceof Date &&\n    Object.getPrototypeOf(value) === Date.prototype\n  ) {\n    if (Number.isNaN(value.getTime())) throw refuse(path, \"an invalid Date\");\n    // A Date carrying its own properties would defer fine and resume with\n    // those properties gone, since the envelope keeps only the instant.\n    // Silent loss is the outcome this walk exists to prevent.\n    // `getOwnPropertyNames`, not `keys`: a non-enumerable field is lost just\n    // as silently as an enumerable one.\n    if (\n      Object.getOwnPropertyNames(value).length > 0 ||\n      Object.getOwnPropertySymbols(value).length > 0\n    ) {\n      throw refuse(path, \"a Date carrying extra properties\");\n    }\n    return { [DATE_TAG]: value.toISOString() };\n  }\n\n  seen.add(object);\n  try {\n    if (Array.isArray(value)) {\n      // Named or symbol-keyed properties on an array are invisible to the\n      // index walk, so they would be dropped rather than refused.\n      // `getOwnPropertyNames`, not `keys`: a non-enumerable name is lost just\n      // as silently, same reason the Date check above reads all own names.\n      const named = Object.getOwnPropertyNames(value).filter(\n        (key) => key !== \"length\" && !isArrayIndex(key, value.length),\n      );\n      if (named.length > 0) {\n        throw refuse(path, `an array with a named property (\"${named[0]}\")`);\n      }\n      if (Object.getOwnPropertySymbols(value).length > 0) {\n        throw refuse(path, \"an array with a symbol-keyed property\");\n      }\n      // Holes and `undefined` entries become `null`, which is what JSON\n      // does. Without this the in-memory backend (a structured clone) would\n      // keep `undefined` while sqlite (a JSON round trip) yields `null`, so\n      // a route would see a different value depending on which backend a\n      // deployment happened to resolve.\n      return Array.from(value, (entry, index) =>\n        entry === undefined ? null : encode(entry, `${path}[${index}]`, seen),\n      );\n    }\n\n    const prototype = Object.getPrototypeOf(object);\n    if (prototype !== Object.prototype && prototype !== null) {\n      throw refuse(\n        path,\n        `an instance of ${(object as { constructor?: { name?: string } }).constructor?.name ?? \"a class\"}`,\n      );\n    }\n\n    // Symbol keys are invisible to Object.entries, so without this they\n    // would be dropped in silence rather than refused, which is the exact\n    // outcome this walk exists to prevent. Symbol-keyed state is the\n    // framework's own idiom for context stores, so an author moving a value\n    // onto the exchange lands here.\n    const symbols = Object.getOwnPropertySymbols(object);\n    if (symbols.length > 0) {\n      throw refuse(path, `a symbol-keyed property (${String(symbols[0])})`);\n    }\n\n    const keys = Object.keys(object);\n    // Third and last place this walk enumerates own names, after the Date\n    // and array branches above. All three refuse rather than enumerate,\n    // because a non-enumerable own property is dropped by JSON exactly as\n    // silently as a symbol-keyed one, and silent loss is what this walk\n    // exists to prevent.\n    // Compared by count first. `getOwnPropertyNames` is a superset of\n    // `keys`, so the two differ exactly when a non-enumerable own name\n    // exists, and the common case (there is none) stays linear with nothing\n    // allocated. Naming the offender is the throwing path's problem.\n    const names = Object.getOwnPropertyNames(object);\n    if (names.length !== keys.length) {\n      const enumerable = new Set(keys);\n      const hidden = names.find((key) => !enumerable.has(key));\n      throw refuse(path, `a non-enumerable property (\"${hidden}\")`);\n    }\n\n    if (keys.length === 1 && keys[0] === DATE_TAG) {\n      throw refuse(path, `the reserved ${DATE_TAG} envelope key`);\n    }\n\n    // Null-prototype accumulator: `__proto__` is a genuine own key on any\n    // object that came from JSON.parse, and assigning it on a normal object\n    // literal triggers the Object.prototype setter, which swaps the copy's\n    // prototype and loses the field.\n    const copy: Record<string, unknown> = Object.create(null);\n    for (const key of keys) {\n      const entry = (object as Record<string, unknown>)[key];\n      if (entry === undefined) continue;\n      copy[key] = encode(entry, `${path}.${key}`, seen);\n    }\n    return copy;\n  } finally {\n    seen.delete(object);\n  }\n}\n\n/**\n * Revive tagged values produced by {@link encode}. Everything else is\n * returned as-is; the input is already JSON data by construction.\n *\n * @internal\n */\nfunction decode(value: unknown): unknown {\n  if (value === null || typeof value !== \"object\") return value;\n  if (Array.isArray(value)) return value.map(decode);\n\n  const entries = Object.entries(value as Record<string, unknown>);\n  if (entries.length === 1 && entries[0]?.[0] === DATE_TAG) {\n    const revived = new Date(String(entries[0][1]));\n    // A stored envelope that does not parse means the row was corrupted or\n    // hand-edited. Reviving it as `Invalid Date` would hand the route a\n    // Date-shaped value that fails every comparison it is used in.\n    if (Number.isNaN(revived.getTime())) {\n      // Not `refuse()`: that phrases everything as a defer-time failure,\n      // and this runs on the way back out of the store.\n      throw rcError(\"RC5042\", undefined, {\n        message:\n          \"Cannot resume: the stored exchange holds an unparseable date envelope, so it cannot be revived.\",\n      });\n    }\n    return revived;\n  }\n\n  // Same `__proto__` hazard as `encode`, but the revived value is handed\n  // back to route code, so it keeps an ordinary prototype (a null-prototype\n  // body would break `instanceof Object` and `hasOwnProperty` call sites\n  // that worked before the defer). `defineProperty` writes the key\n  // without going through the inherited setter.\n  const copy: Record<string, unknown> = {};\n  for (const [key, entry] of entries) {\n    Object.defineProperty(copy, key, {\n      value: decode(entry),\n      enumerable: true,\n      writable: true,\n      configurable: true,\n    });\n  }\n  return copy;\n}\n\n/**\n * Whether `key` names one of the positions the index walk will visit.\n *\n * A digit test alone is not enough. `\"01\"` and any numeric beyond `length`\n * are ordinary string keys that `Array.from` never reads, so they would be\n * dropped in silence instead of being refused as the named properties they\n * are.\n *\n * @internal\n */\nfunction isArrayIndex(key: string, length: number): boolean {\n  const index = Number(key);\n  return (\n    Number.isInteger(index) &&\n    index >= 0 &&\n    index < length &&\n    String(index) === key\n  );\n}\n\n/** @internal */\nfunction refuse(path: string, what: string): Error {\n  return rcError(\"RC5042\", undefined, {\n    message: `Cannot defer: exchange ${path} holds ${what}, which cannot be persisted to the deferral store.`,\n  });\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { BRAND, isBranded, setBrand } from \"../brand.ts\";\n\n/**\n * What execution one returns when a route defers.\n *\n * A durable defer cannot hold a caller: the resume payload arrives in\n * hours or days and the process will be restarted first. So the run that\n * reaches a `.defer()` terminates there and replies immediately with this value\n * instead of the route's declared output. The real output flows to the\n * route's destinations on execution two.\n *\n * Every source renders it in its own terms (`202` plus this body on\n * `http()`, the value itself on `direct()`, a log line on `cron()` /\n * `simple()` / file sources, an ack on queue sources), which is why a route\n * with a reachable durable defer has output type `Output | Deferred`.\n *\n * The value is deliberately transport-shaped and JSON-safe: it crosses the\n * wire to whoever called the route.\n */\nexport interface Deferred {\n  readonly status: \"deferred\";\n  /** The deferred exchange's deferral id. */\n  readonly deferralId: string;\n  /** Signed, single-use token that resumes it. */\n  readonly token: string;\n  /**\n   * JSON Schema rendering of what a valid resume payload looks like, when the\n   * deferring step declared a schema and it exposes one (Zod, ArkType and\n   * the AI SDK bridge do through the non-standard `~standard.jsonSchema`\n   * extension). Absent otherwise, and absent whenever the site declared no\n   * schema at all; validation always runs against the live schema at\n   * resume, so nothing depends on this being present.\n   */\n  readonly schema?: unknown;\n  /** When the deferral expires, ISO-8601. Absent when `.defer()` declared no `ttl`. */\n  readonly expiresAt?: string;\n}\n\n/**\n * Mint the acknowledgment value for a deferred exchange.\n *\n * Branded so a transport can recognise it (`http()` answers `202` rather\n * than `200`) without string-sniffing a `status` field that any user body\n * could also carry. The brand is a symbol-keyed own property, so it never\n * appears in the JSON that reaches the caller.\n *\n * @internal\n */\nexport function createDeferred(value: Omit<Deferred, \"status\">): Deferred {\n  const deferred: Deferred = { status: \"deferred\", ...value };\n  setBrand(deferred, BRAND.Deferred);\n  return deferred;\n}\n\n/**\n * Whether a value is the framework's own {@link Deferred} acknowledgment.\n *\n * Transports call this on a route's terminal body to decide how to render\n * it. It is a brand check rather than a shape check on purpose: a route\n * whose real output happens to have `status: \"deferred\"` must not be\n * mistaken for a deferred exchange.\n */\nexport function isDeferred(value: unknown): value is Deferred {\n  return isBranded(value, BRAND.Deferred);\n}\n\n/**\n * JSON Schema for the {@link Deferred} acknowledgment, draft 2020-12.\n *\n * The shape a transport publishes when it advertises that a tool or route\n * may defer: the MCP server derives `oneOf: [Output, Deferred]` for a\n * deferrable tool's `outputSchema` from this rendering. Closed for\n * additional properties so the advertised contract is exactly the value\n * {@link createDeferred} mints.\n */\nexport const DEFERRED_JSON_SCHEMA = {\n  type: \"object\",\n  description:\n    \"The run deferred at a durable deferral. The resume payload is delivered out of band with the resume token, and the real result is produced when the run continues.\",\n  properties: {\n    status: { const: \"deferred\" },\n    deferralId: { type: \"string\" },\n    token: { type: \"string\" },\n    schema: {\n      description:\n        \"JSON Schema of what a valid resume payload looks like, when the deferring step declared a schema that renders one.\",\n    },\n    expiresAt: { type: \"string\", format: \"date-time\" },\n  },\n  required: [\"status\", \"deferralId\", \"token\"],\n  additionalProperties: false,\n} as const;\n\n/**\n * Standard Schema for the {@link Deferred} acknowledgment.\n *\n * Exists so surfaces that reason in schema arms (the MCP server's\n * advertised-output arms are the shipped consumer) can carry the\n * acknowledgment as an ordinary `StandardSchemaV1` next to a route's own\n * `.output()` schema. Validation accepts the framework's own acknowledgment\n * by brand first, so a genuine `Deferred` value always passes whatever a\n * structural check would say, and falls back to the structural check for\n * values that crossed a process boundary and lost the brand.\n */\nexport const deferredSchema: StandardSchemaV1<unknown, Deferred> = {\n  \"~standard\": {\n    version: 1,\n    vendor: \"routecraft\",\n    validate(value) {\n      if (isDeferred(value)) return { value };\n      // Mirror DEFERRED_JSON_SCHEMA exactly (types of the optional fields\n      // included, undeclared string keys rejected) so the runtime check and\n      // the advertised contract cannot say different things. The brand rides\n      // a symbol key, which JSON never carries and Object.keys never lists.\n      if (\n        typeof value === \"object\" &&\n        value !== null &&\n        !Array.isArray(value) &&\n        (value as { status?: unknown }).status === \"deferred\" &&\n        typeof (value as { deferralId?: unknown }).deferralId === \"string\" &&\n        typeof (value as { token?: unknown }).token === \"string\" &&\n        Object.entries(value).every(([key, field]) => {\n          switch (key) {\n            case \"status\":\n            case \"deferralId\":\n            case \"token\":\n              return true;\n            case \"schema\":\n              return true;\n            case \"expiresAt\":\n              return typeof field === \"string\";\n            default:\n              return false;\n          }\n        })\n      ) {\n        return { value: value as Deferred };\n      }\n      return {\n        issues: [\n          {\n            message:\n              'Expected the framework Deferred acknowledgment: { status: \"deferred\", deferralId, token, ... } with no undeclared properties.',\n          },\n        ],\n      };\n    },\n    // Non-standard `jsonSchema` extension, the same one Zod and ArkType\n    // expose and the JSON Schema conversion sites look up defensively.\n    jsonSchema: {\n      input: () => DEFERRED_JSON_SCHEMA,\n      output: () => DEFERRED_JSON_SCHEMA,\n    },\n  } as StandardSchemaV1<unknown, Deferred>[\"~standard\"],\n};\n","import { randomUUID } from \"node:crypto\";\nimport {\n  type Adapter,\n  type Step,\n  getAdapterLabel,\n  type StepOutcome,\n} from \"../types.ts\";\nimport { BRAND, isBranded, isExchange } from \"../brand.ts\";\nimport { rcError } from \"../error.ts\";\nimport {\n  type Exchange,\n  type ExchangeHeaders,\n  OperationType,\n  HeadersKeys,\n  DefaultExchange,\n  getExchangeContext,\n  getExchangeRoute,\n  setExchangeRoute,\n} from \"../exchange.ts\";\nimport type { Route } from \"../route.ts\";\n\n/**\n * Store key for the map of split group IDs to their parent exchanges.\n * Used by the aggregate step to restore the parent exchange identity\n * after merging children.\n */\nexport const SPLIT_PARENT_STORE = \"routecraft.split.parents\" as const;\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [SPLIT_PARENT_STORE]: Map<string, Exchange>;\n  }\n}\n\n/**\n * Brand key marking a {@link SplitChild} envelope. Registered in\n * {@link BRAND} (`Symbol.for`) so envelopes survive crossing duplicate\n * copies of the package (CLI vs user module).\n */\nconst SPLIT_CHILD = BRAND.SplitChild;\n\n/**\n * Per-child envelope produced by {@link splitChild}: a body plus optional\n * header OVERRIDES for that child. The brand makes the envelope\n * unambiguous -- a split item that happens to have a `body` property is\n * still treated as a plain body unless it went through `splitChild`.\n *\n * @template R - Body type of the child\n */\nexport interface SplitChild<R = unknown> {\n  readonly [SPLIT_CHILD]: true;\n  readonly body: R;\n  readonly headers?: ExchangeHeaders;\n}\n\n/**\n * Wrap one split child with per-child header overrides. Plain return values\n * from a splitter become child bodies that inherit the parent's headers;\n * use this helper only when a child needs its own header values on top.\n *\n * @example\n * ```ts\n * .split((exchange) =>\n *   exchange.body.lines.map((line, i) => splitChild(line, { \"x-line\": i })),\n * )\n * ```\n */\nexport function splitChild<R>(\n  body: R,\n  headers?: ExchangeHeaders,\n): SplitChild<R> {\n  return headers === undefined\n    ? { [SPLIT_CHILD]: true, body }\n    : { [SPLIT_CHILD]: true, body, headers };\n}\n\n/** Type guard for {@link SplitChild} envelopes. */\nexport function isSplitChild(value: unknown): value is SplitChild {\n  return isBranded(value, SPLIT_CHILD);\n}\n\n/**\n * What a splitter produces per child: the child's body, or a\n * {@link splitChild} envelope when the child needs header overrides. The\n * FRAMEWORK constructs the child exchanges (fresh id, parent headers\n * inherited, `routecraft.split_hierarchy` maintained); splitters never\n * build `Exchange` instances themselves.\n *\n * @template R - Body type of the child\n */\nexport type SplitResult<R = unknown> = R | SplitChild<R>;\n\n/**\n * Function form of a splitter: takes the current exchange and returns the\n * child bodies (or {@link splitChild} envelopes). Use with\n * `.split(splitter)` or no-arg `.split()` for arrays.\n *\n * @template T - Current body type\n * @template R - Body type of each child\n */\nexport type CallableSplitter<T = unknown, R = unknown> = (\n  exchange: Exchange<T>,\n) => Promise<Array<SplitResult<R>>> | Array<SplitResult<R>>;\n\n/**\n * Splitter adapter: turns one body into many; each item is processed as a separate exchange.\n * Used with `.split()`. Default (no adapter): array bodies are split into elements; non-arrays become one item.\n *\n * @template T - Current body type\n * @template R - Item type\n */\nexport interface Splitter<T = unknown, R = unknown> extends Adapter {\n  split: CallableSplitter<T, R>;\n}\n\n/**\n * Step that splits the exchange into multiple exchanges (e.g. one per array element).\n * Each new exchange gets a new id and shared split hierarchy for aggregation.\n * Framework maintains `routecraft.split_hierarchy` headers for aggregation.\n */\nexport class SplitStep<T = unknown, R = unknown> implements Step<\n  Splitter<T, R>\n> {\n  operation: OperationType = OperationType.SPLIT;\n  adapter: Splitter<T, R>;\n  skipStepEvents = true;\n\n  constructor(adapter: Splitter<T, R> | CallableSplitter<T, R>) {\n    this.adapter = typeof adapter === \"function\" ? { split: adapter } : adapter;\n  }\n\n  async execute(exchange: Exchange<T>): Promise<StepOutcome> {\n    const context = getExchangeContext(exchange);\n    const route = getExchangeRoute(exchange);\n\n    if (!context) {\n      throw new Error(\"Exchange has no context; cannot execute split\");\n    }\n\n    const routeId =\n      route?.definition.id ??\n      (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n    const adapterLabel = getAdapterLabel(this.adapter);\n    const stepStart = Date.now();\n\n    context.emit(\"route:step:started\", {\n      routeId,\n      exchangeId: exchange.id,\n      correlationId,\n      operation: this.operation,\n      ...(adapterLabel ? { adapter: adapterLabel } : {}),\n    });\n\n    let splitResults: Array<SplitResult<R>>;\n    try {\n      splitResults = await Promise.resolve(this.adapter.split(exchange));\n    } catch (error: unknown) {\n      context.emit(\"route:step:failed\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: this.operation,\n        ...(adapterLabel ? { adapter: adapterLabel } : {}),\n        duration: Date.now() - stepStart,\n        error: error instanceof Error ? error.message : String(error),\n      });\n      throw error;\n    }\n    const groupId = randomUUID();\n\n    // Stash the parent exchange so aggregate can restore it\n    let parentMap = context.getStore(SPLIT_PARENT_STORE) as\n      Map<string, Exchange> | undefined;\n    if (!parentMap) {\n      parentMap = new Map<string, Exchange>();\n      context.setStore(SPLIT_PARENT_STORE, parentMap);\n    }\n    parentMap.set(groupId, exchange);\n\n    const existingHierarchy =\n      (exchange.headers[HeadersKeys.SPLIT_HIERARCHY] as string[]) || [];\n    const splitHierarchy = [...existingHierarchy, groupId];\n\n    const children: Exchange<R>[] = [];\n    for (const result of splitResults) {\n      // Loud guard for the pre-0.6 splitter contract: hand-built Exchange\n      // instances are no longer accepted (the framework owns child\n      // construction). The types catch this for TS users; this check\n      // catches plain-JS / `as any` splitters that would otherwise flow\n      // a whole Exchange object downstream as the child body.\n      if (isExchange(result)) {\n        throw rcError(\"RC5003\", undefined, {\n          message:\n            \".split() returned an Exchange instance; splitters return child bodies. Return the value itself, or splitChild(body, headers) for per-child header overrides.\",\n        });\n      }\n      const envelope = isSplitChild(result)\n        ? (result as SplitChild<R>)\n        : undefined;\n      const childBody = envelope ? envelope.body : (result as R);\n      // Spread parent headers first so cross-cutting concerns\n      // (`routecraft.auth.principal`, future tracing/tenancy keys) flow\n      // through to every child. A `splitChild` envelope's headers override\n      // on collision EXCEPT for engine-owned keys: id, split hierarchy,\n      // route id, and operation are reasserted after the envelope spread,\n      // mirroring the `.header()` guard so the same runtime contract holds\n      // on both APIs (an envelope value for those keys is ignored).\n      const postProcessedExchange = new DefaultExchange<R>(context, {\n        body: childBody,\n        headers: {\n          ...exchange.headers,\n          // Spreading undefined is a no-op, so plain children pay no\n          // empty-object allocation.\n          ...envelope?.headers,\n          [HeadersKeys.ROUTE_ID]: exchange.headers[\n            HeadersKeys.ROUTE_ID\n          ] as string,\n          [HeadersKeys.OPERATION]: exchange.headers[\n            HeadersKeys.OPERATION\n          ] as string,\n          [HeadersKeys.ID]: randomUUID(),\n          [HeadersKeys.SPLIT_HIERARCHY]: splitHierarchy,\n        },\n      });\n\n      // Set route in internals if it exists (symbol-key for cross-instance)\n      if (route) {\n        setExchangeRoute(postProcessedExchange, route as Route);\n      }\n\n      const adapterLabel = getAdapterLabel(this.adapter);\n      postProcessedExchange.logger.debug(\n        {\n          operation: \"split\",\n          ...(adapterLabel ? { adapter: adapterLabel } : {}),\n          splitHierarchy:\n            postProcessedExchange.headers[HeadersKeys.SPLIT_HIERARCHY],\n        },\n        \"Emitting split child exchange\",\n      );\n      children.push(postProcessedExchange);\n    }\n\n    context.emit(\"route:step:completed\", {\n      routeId,\n      exchangeId: exchange.id,\n      correlationId,\n      operation: this.operation,\n      ...(adapterLabel ? { adapter: adapterLabel } : {}),\n      duration: Date.now() - stepStart,\n      metadata: { childCount: splitResults.length },\n    });\n\n    return { kind: \"fanOut\", exchanges: children };\n  }\n}\n","import type { RouteDefinition } from \"../route.ts\";\nimport type { Adapter, Step } from \"../types.ts\";\n\n/**\n * Fields of {@link RouteDefinition} that are not pre-from chain positions.\n *\n * This list is the only place that says \"this field is not part of the\n * chain\". Every other field IS one, and must declare in\n * {@link CHAIN_SURVIVAL} whether it survives each kind of detached run, so\n * adding a field to `RouteDefinition` fails the build until it is either\n * excluded here or given a policy.\n *\n * The forcing is keyed by FIELD, and a field is not the same unit as a\n * chain position, so three cases sit outside it and still need a human:\n * `parse` (#3) is not on the definition at all, `input` (#4) lives under\n * `discovery`, and the three filter arrays each hold an arbitrary number of\n * positions that share one answer. A position added inside one of those\n * arrays inherits its neighbour's policy without breaking the build.\n */\ntype NonChainField =\n  | \"id\"\n  | \"sources\"\n  | \"steps\"\n  | \"consumer\"\n  | \"discovery\"\n  | \"deferSteps\"\n  // Site bookkeeping like deferSteps: which steps could defer, not a\n  // chain position. A detached run reaches those steps through its own\n  // step array, and each host carries its site on the instance.\n  | \"reentrantDeferSteps\"\n  | \"usesResume\"\n  // Metadata mirrored to sources (transport admission), not a chain\n  // position: the authorize steps it describes already answer for\n  // themselves under `preParseFilters`.\n  | \"requiresPrincipal\"\n  // A build-time diagnostic flag read once when the route is registered.\n  | \"volatileCacheKey\"\n  // An input to the cache-check filter's key, not a position: the filter\n  // itself answers under `postParseFilters`.\n  | \"cachePipeline\"\n  // Per-route LIFECYCLE, not per-exchange admission: it decides whether the\n  // route runs at all, and is evaluated when the route starts rather than\n  // when an exchange arrives. A detached run only happens inside a route\n  // that is already running, so the predicate has nothing to say about it.\n  | \"enablement\";\n\n/** A pre-from filter chain position, as carried on the route definition. */\ntype ChainField = Exclude<keyof RouteDefinition, NonChainField>;\n\n/**\n * The runs that re-enter a route partway down its pipeline.\n *\n * They are not variants of one thing, which is why each states its own\n * answer per position rather than inheriting a shared one.\n *\n * - `resume` is execution two of an exchange that entered the route once,\n *   possibly days earlier, and was admitted then. Its deferral is already\n *   claimed by the time the continuation runs.\n * - `debounce` is work the route deliberately held back. It never entered,\n *   so the chain above has not run for it at all.\n * - `errorChannel` is a failure pushed at an exchange that is not running,\n *   so that the route's own handler can react. It is not the exchange's\n *   work resuming; it is the route being told something about it.\n */\nexport type DetachedKind = \"resume\" | \"debounce\" | \"errorChannel\";\n\n/** Whether one chain position survives one kind of detached run, and why. */\ninterface KindPolicy {\n  readonly survives: boolean;\n  /**\n   * This run may not be REFUSED admission by the position: it queues\n   * instead. Only meaningful where {@link KindPolicy.survives} is true.\n   */\n  readonly mustNotRefuse?: boolean;\n  /** Stated per kind: the same position is off for different reasons. */\n  readonly why: string;\n}\n\n/**\n * Which chain positions apply to a run that re-enters partway down.\n *\n * Every position answers for every kind. That exhaustiveness is enforced by\n * the type rather than by review: `ChainField` is derived from\n * `RouteDefinition`, so a new field breaks this record until it is\n * classified, and `Record<DetachedKind, KindPolicy>` breaks it again if a\n * new kind of detached run is added without deciding what that position\n * means for it.\n *\n * One rule governs the `resume` column. A position that REFUSES work\n * without attempting it must not sit below the store transition, because a\n * resume claims its deferral before the continuation starts, so a refusal\n * becomes that deferral's continuation result and spends an approval on work\n * that never ran. A position that BOUNDS work already underway is safe.\n *\n * `timeout` (#8) satisfies the rule only in the common case. It wraps the\n * bulkhead rather than sitting inside it, so on a route declaring both, a\n * deadline can elapse while the continuation is still queued for a slot and\n * fail work that never started. Narrowing that needs the chain order to\n * differ per kind, which the fixed-order contract in\n * `.standards/pre-from-filter-chain.md` does not currently allow.\n */\nexport const CHAIN_SURVIVAL: Readonly<\n  Record<ChainField, Readonly<Record<DetachedKind, KindPolicy>>>\n> = {\n  errorHandler: {\n    resume: {\n      survives: true,\n      why: \"The route still owns the exchange, and a revival failure has nowhere else to go: only the deferred route can notify and re-ask.\",\n    },\n    debounce: {\n      survives: true,\n      why: \"A released exchange is the route's primary flow, so its failures belong to the route's handler like any other.\",\n    },\n    errorChannel: {\n      survives: true,\n      why: \"Reaching this handler IS the point of the re-entry. Without it there is nothing to push the failure at.\",\n    },\n  },\n  preParseFilters: {\n    resume: {\n      survives: false,\n      why: \"authorize (#2). A principal restored from the store fails RC5043 by design (#355), so re-running it would refuse every resume. The resuming principal is authorized live at the resume ingress.\",\n    },\n    debounce: {\n      survives: false,\n      why: \"authorize (#2). The released exchange was authorized when it arrived, before the route held it back.\",\n    },\n    errorChannel: {\n      survives: false,\n      why: \"authorize (#2). Nothing is being admitted: a failure is being reported about work that already ran.\",\n    },\n  },\n  postParseFilters: {\n    resume: {\n      survives: false,\n      why: \"cacheCheck (#9). Refused at build alongside a reachable defer, because a deferral exits the pipeline this filter wraps.\",\n    },\n    debounce: {\n      survives: false,\n      why: \"cacheCheck (#9). The release re-enters below it, so a check here would key work that is already in flight.\",\n    },\n    errorChannel: {\n      survives: false,\n      why: \"cacheCheck (#9). A failure report is not a cacheable request.\",\n    },\n  },\n  postFromFilters: {\n    resume: {\n      survives: false,\n      why: \"cacheStore (#10). The other half of the same refusal.\",\n    },\n    debounce: {\n      survives: false,\n      why: \"cacheStore (#10). No key was taken on the way in, so there is nothing to store against.\",\n    },\n    errorChannel: {\n      survives: false,\n      why: \"cacheStore (#10). What a re-ask handler returns is a notification, not a cacheable output.\",\n    },\n  },\n  throttle: {\n    resume: {\n      survives: false,\n      why: \"It admits new work into the route; a deferred exchange was admitted on execution one. Answer arrival is governed by the resume ingress route's own throttle.\",\n    },\n    debounce: {\n      survives: false,\n      why: \"The exchange was admitted on arrival; the hold was the route's own doing, not a second admission.\",\n    },\n    errorChannel: {\n      survives: false,\n      why: \"Rate-limiting a failure report would drop the report, not the load.\",\n    },\n  },\n  circuitBreaker: {\n    resume: {\n      survives: false,\n      why: \"It fast-fails, and a continuation runs after the deferral is claimed, so a refusal here would record a failed continuation result and spend the approval. Its home is the resume ingress route's chain, which wraps .resume() and so refuses above that transition.\",\n    },\n    debounce: {\n      survives: false,\n      why: \"A released exchange has been held once already; fast-failing it discards work the route chose to keep.\",\n    },\n    errorChannel: {\n      survives: false,\n      why: \"An open breaker must not suppress the report of a failure.\",\n    },\n  },\n  retry: {\n    resume: {\n      survives: true,\n      why: \"Retrying a continuation is the wanted behaviour and is safe against the transition: attempts run before any continuation result is recorded, so a retried continuation never spends an approval.\",\n    },\n    debounce: {\n      survives: false,\n      why: \"A release is one settled decision by the debounce window, and re-running it would repeat side effects the window exists to collapse.\",\n    },\n    errorChannel: {\n      survives: false,\n      why: \"Re-running a handler would re-notify per attempt, which is the amplifier the exactly-once transitions exist to prevent.\",\n    },\n  },\n  timeout: {\n    resume: {\n      survives: true,\n      why: \"Bounds execution two. Distinct from a deferral's ttl, which is a store-side expiry rather than a per-attempt deadline in this process.\",\n    },\n    debounce: {\n      survives: false,\n      why: \"The release is detached from the arrival whose deadline this describes.\",\n    },\n    errorChannel: {\n      survives: false,\n      why: \"A handler that runs long should finish reporting rather than be abandoned mid-notification.\",\n    },\n  },\n  concurrency: {\n    resume: {\n      survives: true,\n      mustNotRefuse: true,\n      why: \"A bulkhead bounds simultaneous work in the route against a downstream, and a continuation is that work. It queues for the route's own semaphore rather than refusing, because a refusal below the claim would spend an approval. The wait is unbounded in time, and a `key` selector that throws still refuses.\",\n    },\n    debounce: {\n      survives: false,\n      why: \"A bulkhead that can refuse would discard a release the window already decided to make.\",\n    },\n    errorChannel: {\n      survives: false,\n      why: \"A failure report must not queue behind the work it is reporting on.\",\n    },\n  },\n};\n\n/** The chain positions, as a value. */\nconst CHAIN_FIELDS = Object.keys(CHAIN_SURVIVAL) as ChainField[];\n\n/**\n * What a run executes under: the chain positions it carries, plus its own\n * steps. Every run has one, detached or not.\n *\n * `ExecutorDeps[\"definition\"]` is this same type, so the set of fields the\n * executor consumes and the set the policy classifies cannot drift apart.\n */\nexport type ExecutedDefinition = Pick<RouteDefinition, ChainField | \"steps\">;\n\n/** Chain positions whose absence is an empty array rather than undefined. */\nconst emptyChain = (): Pick<\n  RouteDefinition,\n  \"preParseFilters\" | \"postParseFilters\" | \"postFromFilters\"\n> => ({\n  preParseFilters: [],\n  postParseFilters: [],\n  postFromFilters: [],\n});\n\n/**\n * Build the definition a detached run executes under, position by position.\n *\n * Derived from {@link CHAIN_SURVIVAL} rather than written out, so a chain\n * position cannot be carried, or dropped, without saying so.\n *\n * @param source - The route's own definition\n * @param steps - The steps this run executes\n * @param kind - Which detached run this is, which selects the policy\n *\n * @internal\n */\nexport function detachedDefinition(\n  source: Pick<RouteDefinition, ChainField>,\n  steps: ReadonlyArray<Step<Adapter>>,\n  kind: DetachedKind,\n): ExecutedDefinition {\n  const carried: Partial<Pick<RouteDefinition, ChainField>> = {};\n  for (const field of CHAIN_FIELDS) {\n    if (!CHAIN_SURVIVAL[field][kind].survives) continue;\n    const value = source[field];\n    if (value !== undefined) Object.assign(carried, { [field]: value });\n  }\n  return { ...emptyChain(), ...carried, steps: [...steps] };\n}\n","import type { Exchange } from \"../exchange.ts\";\nimport { anySignal } from \"../shared/abort.ts\";\nimport { wrapperEventScope } from \"./event-scope.ts\";\nimport { rcError } from \"../error.ts\";\nimport type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport { WrapperStep } from \"./wrapper.ts\";\nimport { type Duration, parseDuration } from \"../shared/duration.ts\";\n\n/**\n * Route-scope `.timeout()` config. This is the shape stored on\n * `RouteDefinition.timeout` (and is therefore part of the public\n * definition surface); the builder stages it pre-`.from()` and the\n * pipeline executor's timeout segment consumes it.\n */\nexport interface ResolvedTimeoutOptions {\n  /** Deadline in milliseconds for each run of the bounded segment. */\n  timeoutMs: number;\n}\n\n/**\n * Validate a user-supplied timeout into a {@link ResolvedTimeoutOptions}.\n * Shared by the step-scope wrapper constructor and the builder's\n * route-scope staging so both fail fast on a non-finite or\n * non-positive deadline (a `setTimeout(NaN)` would otherwise expire\n * instantly at runtime).\n *\n * @internal\n */\nexport function resolveTimeoutOptions(\n  duration: Duration,\n): ResolvedTimeoutOptions {\n  return { timeoutMs: parseDuration(duration, \"timeout(duration)\") };\n}\n\n/**\n * Sentinel error rejected by the deadline arm of\n * {@link raceWithDeadline}. Callers map it to the public `RC5011`\n * timeout error; it never escapes the framework.\n *\n * @internal\n */\nexport class DeadlineExceededError extends Error {\n  constructor() {\n    super(\"routecraft.timeout.deadline\");\n    this.name = \"DeadlineExceededError\";\n  }\n}\n\n/**\n * Race `run` against a `timeoutMs` deadline. Resolves with the run's\n * value when it settles in time; rejects with\n * {@link DeadlineExceededError} when the deadline fires first. The\n * deadline timer is cleared in all cases so no timer outlives the\n * race.\n *\n * JavaScript promises cannot be cancelled: when the deadline wins, the\n * losing run keeps executing in the background. Its eventual\n * settlement is swallowed here so it cannot surface as an unhandled\n * rejection. Side effects of the abandoned run still happen; the\n * timeout bounds how long the pipeline waits, not the work itself.\n *\n * Shared by the step-scope `.timeout()` wrapper and the route-scope\n * timeout segment in the pipeline executor.\n *\n * @internal\n */\nexport async function raceWithDeadline<R>(\n  run: Promise<R>,\n  timeoutMs: number,\n): Promise<R> {\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  const deadline = new Promise<never>((_, reject) => {\n    timer = setTimeout(() => reject(new DeadlineExceededError()), timeoutMs);\n  });\n  try {\n    return await Promise.race([run, deadline]);\n  } catch (err) {\n    if (err instanceof DeadlineExceededError) {\n      run.catch(() => {});\n    }\n    throw err;\n  } finally {\n    clearTimeout(timer);\n  }\n}\n\n/**\n * Step-scope `.timeout()` wrapper. Bounds the wrapped step with a\n * deadline: when the step settles in time its outcome passes through\n * unchanged; when the deadline fires first the wrapper throws `RC5011`\n * (Request timeout, `retryable: true`) so an outer `.retry()` wrapper\n * re-attempts it by default and `.error()` handlers can branch on the\n * code.\n *\n * The wrapped step's promise is not cancelled on expiry (promises\n * cannot be cancelled): its eventual settlement is discarded. What the\n * step DOES get is an `AbortSignal` on its `StepContext` that fires\n * when the deadline expires, with the `RC5011` error as the abort\n * reason. A step that forwards `ctx.signal` into cancellation-aware IO\n * (`fetch`, DB drivers) therefore aborts its abandoned work instead of\n * running it to completion in the background. The signal is linked to\n * any enclosing signal (a route-scope timeout's abandon signal, an\n * outer step-scope timeout), so whichever deadline fires first aborts\n * the innermost work.\n *\n * Emits scope-aware lifecycle events:\n * - `route:timeout:started` when the guarded execution begins.\n * - `route:timeout:stopped` when the step settles within the deadline.\n * - `route:timeout:expired` when the deadline fires (then throws).\n */\nexport class TimeoutWrapperStep<\n  T extends Adapter = Adapter,\n> extends WrapperStep<T> {\n  readonly #timeoutMs: number;\n\n  constructor(inner: Step<T>, duration: Duration) {\n    super(inner);\n    this.#timeoutMs = resolveTimeoutOptions(duration).timeoutMs;\n  }\n\n  protected override describeOptions(): unknown {\n    return { timeoutMs: this.#timeoutMs };\n  }\n\n  protected override async runInner(\n    exchange: Exchange,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const { route, context, routeId, stepLabel, correlationId } =\n      wrapperEventScope(exchange, this);\n    const shouldEmit = route && context && routeId;\n\n    if (shouldEmit) {\n      context.emit(\"route:timeout:started\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        stepLabel,\n        scope: \"step\",\n        timeoutMs: this.#timeoutMs,\n      });\n    }\n\n    // Per-execution controller: aborts when THIS deadline expires so the\n    // inner step can cancel in-flight IO. Linked to any enclosing signal\n    // (route-scope abandon, outer step-scope timeout) via AbortSignal.any\n    // so the earliest deadline wins; the composed signal replaces\n    // `ctx.signal` for the inner step only, every other StepContext\n    // capability passes through untouched.\n    const controller = new AbortController();\n    const innerCtx: StepContext = {\n      ...ctx,\n      signal: anySignal(ctx.signal, controller.signal),\n    };\n\n    const start = Date.now();\n    try {\n      const outcome = await raceWithDeadline(\n        this.inner.execute(exchange, innerCtx),\n        this.#timeoutMs,\n      );\n      if (shouldEmit) {\n        context.emit(\"route:timeout:stopped\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          stepLabel,\n          scope: \"step\",\n          timeoutMs: this.#timeoutMs,\n          elapsed: Date.now() - start,\n        });\n      }\n      return outcome;\n    } catch (err) {\n      if (!(err instanceof DeadlineExceededError)) throw err;\n      const timeoutError = rcError(\"RC5011\", undefined, {\n        message: `Step \"${stepLabel}\" exceeded its ${this.#timeoutMs}ms timeout`,\n      });\n      // Abort BEFORE emitting so cancellation-aware IO in the abandoned\n      // run stops as early as possible; the reason surfaces as the\n      // rejection of any fetch()/driver call holding the signal.\n      controller.abort(timeoutError);\n      if (shouldEmit) {\n        context.emit(\"route:timeout:expired\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          stepLabel,\n          scope: \"step\",\n          timeoutMs: this.#timeoutMs,\n          elapsed: Date.now() - start,\n        });\n      }\n      throw timeoutError;\n    }\n  }\n}\n","import type { Exchange } from \"../exchange.ts\";\nimport { wrapperEventScope } from \"./event-scope.ts\";\nimport { rcError, RoutecraftError } from \"../error.ts\";\nimport { isRoutecraftError } from \"../brand.ts\";\nimport type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport { WrapperStep } from \"./wrapper.ts\";\nimport { cancellableSleep, SleepAbortedError } from \"./cancellable-sleep.ts\";\nimport { type Duration, parseDuration } from \"../shared/duration.ts\";\nimport { rejectStaleOptions } from \"../shared/stale-options.ts\";\n\n/**\n * Options for the `.retry()` wrapper (step scope and route scope).\n */\nexport interface RetryOptions {\n  /**\n   * Maximum total attempts, including the first one. `3` means the\n   * original execution plus up to two re-attempts. Must be at least 1.\n   * Default: `3`.\n   */\n  maxAttempts?: number;\n  /**\n   * Base wait between attempts. Default: `1000`.\n   */\n  backoff?: Duration;\n  /**\n   * Growth multiplier applied to `backoff` each attempt: the wait\n   * before attempt `n` is `backoff * factor^(n - 1)`. `1` (the default)\n   * is fixed backoff; `2` doubles each time (`100, 200, 400, ...`); any\n   * value `>= 1` is allowed for gentler or steeper curves. Replaces the\n   * old `exponential` boolean (`exponential: true` is now `factor: 2`).\n   */\n  factor?: number;\n  /**\n   * Upper bound (ms) on a single wait, so an exponential `factor` cannot\n   * grow the backoff without limit at higher `maxAttempts`. The computed\n   * wait is clamped to this BEFORE jitter is applied. Default: the\n   * platform timer ceiling (`2_147_483_647`), i.e. effectively unbounded.\n   */\n  maxBackoff?: Duration;\n  /**\n   * Randomise each wait to avoid synchronized retry storms across many\n   * exchanges hitting the same downstream:\n   * - `\"none\"` (default): use the computed wait exactly.\n   * - `\"full\"`: pick uniformly in `[0, computed]` (AWS \"full jitter\").\n   * - a number in `[0, 1]`: subtract up to that fraction, i.e. pick in\n   *   `[computed * (1 - jitter), computed]` (`0.2` keeps 80-100% of the\n   *   wait). `\"full\"` is `1`; `\"none\"` is `0`.\n   *\n   * Jitter only ever reduces a wait, so it never exceeds `maxBackoff`.\n   */\n  jitter?: \"none\" | \"full\" | number;\n  /**\n   * Decide whether a failed attempt is re-attempted. Default: skip\n   * `RoutecraftError`s with `retryable: false` (validation, auth,\n   * config errors fail the same way every time); everything else,\n   * including unknown third-party errors, is retried.\n   */\n  retryOn?: (error: Error) => boolean;\n}\n\n/**\n * {@link RetryOptions} with every field populated. This is the shape\n * stored on `RouteDefinition.retry` for route-scope `.retry()` (and is\n * therefore part of the public definition surface); internally it is\n * shared between the step-scope wrapper and the route-scope segment\n * step in the pipeline executor.\n */\nexport interface ResolvedRetryOptions {\n  maxAttempts: number;\n  backoffMs: number;\n  /** Growth multiplier per attempt; `1` is fixed backoff. */\n  factor: number;\n  /** Hard cap on a single computed wait (before jitter). */\n  maxBackoffMs: number;\n  /** Jitter fraction in `[0, 1]`: `0` none, `1` full. */\n  jitter: number;\n  retryOn: (error: Error) => boolean;\n}\n\n/**\n * Default `retryOn` predicate: a `RoutecraftError` registered (or\n * overridden) as `retryable: false` is not re-attempted; every other\n * error is. Unknown third-party errors are retried (optimistic\n * default).\n *\n * @internal\n */\nexport function defaultRetryOn(error: Error): boolean {\n  if (isRoutecraftError(error)) {\n    return (error as RoutecraftError).retryable !== false;\n  }\n  return true;\n}\n\n/**\n * Resolve user-supplied {@link RetryOptions} into a fully populated\n * {@link ResolvedRetryOptions}, validating `maxAttempts`.\n *\n * @internal\n */\nexport function resolveRetryOptions(\n  options: RetryOptions = {},\n): ResolvedRetryOptions {\n  rejectStaleOptions(options, \"retry\", {\n    exponential:\n      \"use factor (exponential: true -> factor: 2, exponential: false -> factor: 1).\",\n  });\n\n  const maxAttempts = options.maxAttempts ?? 3;\n  if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `retry({ maxAttempts }) must be an integer >= 1, got ${String(maxAttempts)}.`,\n    });\n  }\n  const backoffMs =\n    options.backoff === undefined\n      ? 1000\n      : parseDuration(options.backoff, \"retry({ backoff })\", 0);\n\n  const factor = options.factor ?? 1;\n  if (!Number.isFinite(factor) || factor < 1) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `retry({ factor }) must be a finite number >= 1, got ${String(factor)}.`,\n    });\n  }\n  // Default the ceiling to the platform timer max: past it, setTimeout\n  // coerces the delay (Node clamps to ~1ms, so a huge backoff would fire\n  // instantly), which also bounds the `factor ** n` growth from overflowing.\n  const maxBackoffMs =\n    options.maxBackoff === undefined\n      ? RETRY_TIMER_CEILING_MS\n      : parseDuration(options.maxBackoff, \"retry({ maxBackoff })\");\n\n  return {\n    maxAttempts,\n    backoffMs,\n    factor,\n    maxBackoffMs,\n    jitter: resolveJitter(options.jitter),\n    retryOn: options.retryOn ?? defaultRetryOn,\n  };\n}\n\n/**\n * The platform `setTimeout` ceiling (2^31 - 1 ms). Used as the default\n * `maxBackoffMs` so an unbounded exponential growth still clamps to a\n * value the timer can represent rather than firing instantly.\n *\n * @internal\n */\nconst RETRY_TIMER_CEILING_MS = 2_147_483_647;\n\n/**\n * Normalise the {@link RetryOptions.jitter} option to a fraction in\n * `[0, 1]`: `\"none\"` -> `0`, `\"full\"` -> `1`, a number passes through after\n * a range check. Rejects anything else at build time (RC5003).\n *\n * @internal\n */\nfunction resolveJitter(jitter: RetryOptions[\"jitter\"]): number {\n  if (jitter === undefined || jitter === \"none\") return 0;\n  if (jitter === \"full\") return 1;\n  if (Number.isFinite(jitter) && jitter >= 0 && jitter <= 1) return jitter;\n  throw rcError(\"RC5003\", undefined, {\n    message: `retry({ jitter }) must be \"none\", \"full\", or a number in [0, 1], got ${String(jitter)}.`,\n  });\n}\n\n/**\n * Lifecycle hooks the retry loop reports to, so the step-scope wrapper\n * and the route-scope segment step emit the same `route:retry:*`\n * events with their own `scope` / `stepLabel` bindings.\n *\n * @internal\n */\nexport interface RetryHooks {\n  /** Route abort signal; cancels the backoff wait on shutdown. */\n  signal?: AbortSignal;\n  onStarted(): void;\n  /**\n   * A failed attempt will be re-attempted after `waitMs`. `lastError`\n   * is the raw thrown value (matching the event payload's `unknown`),\n   * not the Error normalised for the `retryOn` check.\n   */\n  onAttempt(attemptNumber: number, waitMs: number, lastError: unknown): void;\n  /** Final outcome. `error` is the final raw thrown value on failure. */\n  onStopped(attemptNumber: number, success: boolean, error?: unknown): void;\n}\n\n/**\n * The retry loop shared by the step-scope wrapper and the route-scope\n * segment step. Runs `attempt` up to `options.maxAttempts` times,\n * waiting `backoffMs * factor^(n-1)` (clamped to `maxBackoffMs`, then\n * optionally jittered) between attempts.\n *\n * - A non-retryable error (per `retryOn`) propagates immediately.\n * - When the route shuts down during a backoff wait, the loop gives up\n *   and propagates the last real error rather than waiting out the\n *   backoff or burning further attempts during teardown.\n * - After the final attempt fails, the final error propagates\n *   unchanged so route-level `.error()` handlers see the real cause.\n *\n * @internal\n */\nexport async function executeWithRetry<R>(\n  attempt: () => Promise<R>,\n  options: ResolvedRetryOptions,\n  hooks: RetryHooks,\n): Promise<R> {\n  hooks.onStarted();\n  // Unbounded loop on purpose: every iteration either returns or\n  // throws once `attemptNumber` reaches `maxAttempts` (validated >= 1\n  // by resolveRetryOptions), and an explicit bound would leave dead\n  // code after the loop to satisfy control-flow analysis.\n  for (let attemptNumber = 1; ; attemptNumber++) {\n    try {\n      const result = await attempt();\n      hooks.onStopped(attemptNumber, true);\n      return result;\n    } catch (err) {\n      const error = err instanceof Error ? err : new Error(String(err));\n      if (attemptNumber >= options.maxAttempts || !options.retryOn(error)) {\n        hooks.onStopped(attemptNumber, false, err);\n        throw err;\n      }\n      // base * factor^(n-1), clamped to maxBackoffMs. A zero base stays\n      // zero regardless of factor: short-circuit it so an overflowing\n      // factor^(n-1) cannot produce `0 * Infinity === NaN` (which would\n      // otherwise pin to maxBackoffMs, inverting an explicit zero backoff\n      // into a ~24-day wait). For a positive base an overflow saturates to\n      // Infinity, which the clamp pins to maxBackoffMs. Jitter then only\n      // ever SHORTENS the wait (`jitter` is in [0, 1]), so it stays clamped.\n      const computed =\n        options.backoffMs === 0\n          ? 0\n          : Math.min(\n              options.backoffMs * options.factor ** (attemptNumber - 1),\n              options.maxBackoffMs,\n            );\n      const waitMs = computed * (1 - options.jitter * Math.random());\n      hooks.onAttempt(attemptNumber, waitMs, err);\n      try {\n        await cancellableSleep(waitMs, hooks.signal);\n      } catch (sleepErr) {\n        if (!(sleepErr instanceof SleepAbortedError)) throw sleepErr;\n        // Shutdown during backoff: surface the last real failure\n        // instead of attempting work on a stopping route.\n        hooks.onStopped(attemptNumber, false, err);\n        throw err;\n      }\n    }\n  }\n}\n\n/**\n * Step-scope `.retry()` wrapper. Re-attempts the wrapped step on\n * failure with configurable backoff. Each attempt receives the same\n * (frozen) exchange, so a re-attempt always starts from the input that\n * failed, not from partial output.\n *\n * The attempt counter is loop-local state inside one execution; it is\n * NOT written to exchange headers (headers carry persistent exchange\n * state, see `.standards/exchange-state-model.md`). Observers track\n * attempts via the `route:retry:attempt` events instead.\n *\n * Emits the pre-declared scope-aware lifecycle events:\n * - `route:retry:started` when the guarded execution begins.\n * - `route:retry:attempt` before each backoff wait + re-attempt.\n * - `route:retry:stopped` on final success or failure.\n */\nexport class RetryWrapperStep<\n  T extends Adapter = Adapter,\n> extends WrapperStep<T> {\n  readonly #options: ResolvedRetryOptions;\n\n  constructor(inner: Step<T>, options: RetryOptions = {}) {\n    super(inner);\n    this.#options = resolveRetryOptions(options);\n  }\n\n  protected override describeOptions(): unknown {\n    return this.#options;\n  }\n\n  protected override async runInner(\n    exchange: Exchange,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const { route, context, routeId, stepLabel, correlationId } =\n      wrapperEventScope(exchange, this);\n    const shouldEmit = route && context && routeId;\n    const scoped = {\n      routeId: routeId as string,\n      exchangeId: exchange.id,\n      correlationId,\n      stepLabel,\n      scope: \"step\" as const,\n    };\n\n    return await executeWithRetry(\n      () => this.inner.execute(exchange, ctx),\n      this.#options,\n      {\n        // Intake: a backoff cut short at the start of shutdown surfaces the\n        // last error as a terminal outcome, where waiting it out ends in an\n        // abandonment that reports nothing.\n        ...(route ? { signal: route.intakeSignal } : {}),\n        onStarted: () => {\n          if (shouldEmit) {\n            context.emit(\"route:retry:started\", {\n              ...scoped,\n              maxAttempts: this.#options.maxAttempts,\n            });\n          }\n        },\n        onAttempt: (attemptNumber, waitMs, lastError) => {\n          if (shouldEmit) {\n            context.emit(\"route:retry:attempt\", {\n              ...scoped,\n              attemptNumber,\n              maxAttempts: this.#options.maxAttempts,\n              backoffMs: waitMs,\n              lastError,\n            });\n          }\n        },\n        onStopped: (attemptNumber, success, error) => {\n          if (shouldEmit) {\n            context.emit(\"route:retry:stopped\", {\n              ...scoped,\n              attemptNumber,\n              success,\n              ...(error !== undefined ? { error } : {}),\n            });\n          }\n        },\n      },\n    );\n  }\n}\n","import { type Exchange, DefaultExchange } from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { logger } from \"../logger.ts\";\nimport type { CraftContext } from \"../context.ts\";\nimport type { ForwardFn, Route } from \"../route.ts\";\nimport type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport { WrapperStep } from \"./wrapper.ts\";\nimport { wrapperEventScope } from \"./event-scope.ts\";\nimport { type Duration, parseDuration } from \"../shared/duration.ts\";\nimport { rejectStaleOptions } from \"../shared/stale-options.ts\";\nimport { defaultRetryOn } from \"./retry-wrapper.ts\";\nimport { RouteScopedController } from \"./route-scoped-controller.ts\";\n\n/**\n * The three states of a circuit breaker.\n *\n * - `closed`: calls flow through; failures within the sliding window are\n *   counted, and the breaker trips to `open` once they reach the\n *   threshold.\n * - `open`: calls fast-fail (fallback or `RC5025`) without running the\n *   protected work, until `cooldown` has elapsed.\n * - `half-open`: a bounded number of probe calls are allowed through to\n *   test whether the downstream has recovered; one success closes the\n *   breaker, one failure re-opens it.\n */\nexport type CircuitBreakerState = \"closed\" | \"open\" | \"half-open\";\n\n/**\n * Options for the `.circuitBreaker()` operation (step scope and route\n * scope). A breaker tracks failures over a sliding window and short-circuits\n * execution when the target is known to be failing, so a flaky downstream\n * does not turn into a pile of slow, doomed calls.\n */\nexport interface CircuitBreakerOptions {\n  /**\n   * Number of failures within `window` that trips the breaker from\n   * `closed` to `open`. Must be a finite integer >= 1.\n   */\n  failureThreshold: number;\n  /**\n   * Sliding window over which failures are counted. Failures older than\n   * this no longer count toward the threshold. Default `60_000`.\n   */\n  window?: Duration;\n  /**\n   * How long the breaker stays `open` before allowing a probe\n   * (transition to `half-open`). Default `30_000`.\n   */\n  cooldown?: Duration;\n  /**\n   * Maximum concurrent probe calls allowed in the `half-open` state.\n   * Default `1`. Values above 1 are best-effort: the first probe to\n   * succeed closes the breaker, so concurrent probes resolving after it\n   * are accounted against the now-closed breaker.\n   */\n  halfOpenMax?: number;\n  /**\n   * Produce the value to use when the breaker rejects a call (open, or\n   * half-open at capacity). When set, the rejected exchange's body becomes\n   * the result of `fallback` and the pipeline continues; when omitted, the\n   * breaker throws `RC5025` so a `.error()` handler (or the default error\n   * path) can react.\n   *\n   * The second argument is `forward`, the same direct-route caller the\n   * `.error()` handler receives: `forward(endpoint, payload)` sends to a\n   * direct route and resolves with that route's result, so a fallback can\n   * be dynamic (serve from a cache route, a secondary provider, etc.)\n   * rather than a static value. May be async.\n   *\n   * @example Static fallback\n   * ```ts\n   * .circuitBreaker({ failureThreshold: 5, fallback: () => ({ degraded: true }) })\n   * ```\n   * @example Dynamic fallback via a direct route\n   * ```ts\n   * .circuitBreaker({\n   *   failureThreshold: 5,\n   *   fallback: (exchange, forward) => forward(\"recs-fallback\", exchange.body),\n   * })\n   * ```\n   */\n  fallback?: (\n    exchange: Exchange,\n    forward: ForwardFn,\n  ) => unknown | Promise<unknown>;\n  /**\n   * Decide whether a failed call counts toward the failure threshold.\n   * Default: count everything except `RoutecraftError`s flagged\n   * `retryable: false` (auth `RC5012`, validation `RC5002`, etc.), which\n   * are deterministic and not evidence the downstream is unhealthy. This\n   * mirrors `.retry()`'s `retryOn` default.\n   */\n  isFailure?: (error: Error) => boolean;\n  /**\n   * Optional label carried on this breaker's `route:circuitBreaker:*`\n   * events, so stacked or sibling breakers can be told apart in logs and\n   * metrics. Has no effect on behaviour. Observe transitions by\n   * subscribing to those events (`route:circuitBreaker:opened` /\n   * `:halfOpen` / `:closed` / `:rejected`); the breaker exposes no\n   * notification callback, consistent with the other operations.\n   */\n  label?: string;\n}\n\n/**\n * {@link CircuitBreakerOptions} with every behavioural field populated.\n * This is the shape stored behind {@link CircuitBreakerController} and is\n * shared by the step-scope wrapper and the route-scope segment.\n *\n * @internal\n */\nexport interface ResolvedCircuitBreakerOptions {\n  failureThreshold: number;\n  windowMs: number;\n  cooldownMs: number;\n  halfOpenMax: number;\n  fallback?: (\n    exchange: Exchange,\n    forward: ForwardFn,\n  ) => unknown | Promise<unknown>;\n  isFailure: (error: Error) => boolean;\n  label?: string;\n}\n\n/**\n * Validate user-supplied {@link CircuitBreakerOptions} into a\n * {@link ResolvedCircuitBreakerOptions}. Rejects at build time (RC5003)\n * so a typo fails when the route is built rather than at first dispatch.\n *\n * @internal\n */\nexport function resolveCircuitBreakerOptions(\n  options: CircuitBreakerOptions,\n): ResolvedCircuitBreakerOptions {\n  rejectStaleOptions(options, \"circuitBreaker\");\n  const {\n    failureThreshold,\n    window = 60_000,\n    cooldown = 30_000,\n    halfOpenMax = 1,\n    fallback,\n    isFailure = defaultRetryOn,\n    label,\n  } = options;\n\n  if (!Number.isInteger(failureThreshold) || failureThreshold < 1) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `circuitBreaker({ failureThreshold }) must be an integer >= 1, got ${String(failureThreshold)}.`,\n    });\n  }\n  const windowMs = parseDuration(window, \"circuitBreaker({ window })\");\n  const cooldownMs = parseDuration(cooldown, \"circuitBreaker({ cooldown })\");\n  if (!Number.isInteger(halfOpenMax) || halfOpenMax < 1) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `circuitBreaker({ halfOpenMax }) must be an integer >= 1, got ${String(halfOpenMax)}.`,\n    });\n  }\n\n  return {\n    failureThreshold,\n    windowMs,\n    cooldownMs,\n    halfOpenMax,\n    isFailure,\n    ...(fallback ? { fallback } : {}),\n    ...(label !== undefined ? { label } : {}),\n  };\n}\n\n/**\n * Decision returned by {@link CircuitBreakerMachine.acquire}. `probe` is\n * true when the admitted call is a half-open probe, so the matching\n * record call knows to release the probe slot and apply half-open\n * transition semantics.\n *\n * @internal\n */\nexport type CircuitBreakerDecision =\n  | { admitted: true; probe: boolean }\n  | { admitted: false; state: \"open\" | \"half-open\"; retryAfterMs: number };\n\n/**\n * Lifecycle hooks the breaker reports transitions to, so the step-scope\n * wrapper and the route-scope segment emit the same\n * `route:circuitBreaker:*` events with their own `scope` / `stepLabel`\n * bindings.\n *\n * @internal\n */\nexport interface CircuitBreakerHooks {\n  /** Closed/half-open -> open (the breaker tripped). */\n  onOpened(failureCount: number): void;\n  /** Open -> half-open (cooldown elapsed; a probe is being admitted). */\n  onHalfOpen(): void;\n  /** Half-open -> closed (a probe succeeded; the breaker recovered). */\n  onClosed(): void;\n  /** A call was rejected because the breaker is open or half-open at capacity. */\n  onRejected(state: \"open\" | \"half-open\", retryAfterMs: number): void;\n}\n\n/**\n * The per-route state machine. Holds the sliding window of failure\n * timestamps (a ring buffer, pruned on access, not a flat counter so the\n * window genuinely slides), the current state, the open timestamp, and\n * the in-flight half-open probe count. One instance per Route (see\n * {@link CircuitBreakerController}), never one per exchange.\n *\n * @internal\n */\nexport class CircuitBreakerMachine {\n  #state: CircuitBreakerState = \"closed\";\n  /** Timestamps of counted failures within the window, oldest first. */\n  readonly #failures: number[] = [];\n  #openedAt = 0;\n  #halfOpenInFlight = 0;\n  readonly #options: ResolvedCircuitBreakerOptions;\n\n  constructor(options: ResolvedCircuitBreakerOptions) {\n    this.#options = options;\n  }\n\n  /** Current breaker state (exposed for diagnostics and tests). */\n  get state(): CircuitBreakerState {\n    return this.#state;\n  }\n\n  #prune(now: number): void {\n    const cutoff = now - this.#options.windowMs;\n    while (this.#failures.length > 0 && this.#failures[0]! < cutoff) {\n      this.#failures.shift();\n    }\n  }\n\n  /**\n   * Decide whether the calling exchange may proceed. May transition\n   * open -> half-open when the cooldown has elapsed. Emits `halfOpen` /\n   * `rejected` via `hooks`.\n   */\n  acquire(now: number, hooks: CircuitBreakerHooks): CircuitBreakerDecision {\n    if (this.#state === \"open\") {\n      const elapsed = now - this.#openedAt;\n      if (elapsed >= this.#options.cooldownMs) {\n        this.#halfOpenInFlight = 0;\n        this.#state = \"half-open\";\n        hooks.onHalfOpen();\n      } else {\n        const retryAfterMs = this.#options.cooldownMs - elapsed;\n        hooks.onRejected(\"open\", retryAfterMs);\n        return { admitted: false, state: \"open\", retryAfterMs };\n      }\n    }\n\n    if (this.#state === \"half-open\") {\n      if (this.#halfOpenInFlight < this.#options.halfOpenMax) {\n        this.#halfOpenInFlight += 1;\n        return { admitted: true, probe: true };\n      }\n      hooks.onRejected(\"half-open\", 0);\n      return { admitted: false, state: \"half-open\", retryAfterMs: 0 };\n    }\n\n    // closed\n    return { admitted: true, probe: false };\n  }\n\n  /** Record a successful call. A successful probe closes the breaker. */\n  recordSuccess(probe: boolean, hooks: CircuitBreakerHooks): void {\n    if (probe && this.#halfOpenInFlight > 0) this.#halfOpenInFlight -= 1;\n    // Only the probe's outcome decides a half-open breaker. A non-probe\n    // success here is stale work from a call admitted while the breaker\n    // was still closed (long enough to outlive the trip + cooldown); it\n    // must not close the breaker out from under the in-flight probe.\n    if (this.#state === \"half-open\" && probe) {\n      this.#failures.length = 0;\n      this.#state = \"closed\";\n      hooks.onClosed();\n    }\n    // In `closed`, a success does not retract windowed failures; the\n    // window expiry does. In `open` a success cannot occur (no call ran).\n  }\n\n  /**\n   * Record a failed call. `counts` is false for deterministic errors that\n   * should not trip the breaker (the probe slot is still released so it\n   * does not leak, but no state transition is applied).\n   */\n  recordFailure(\n    now: number,\n    probe: boolean,\n    counts: boolean,\n    hooks: CircuitBreakerHooks,\n  ): void {\n    if (probe && this.#halfOpenInFlight > 0) this.#halfOpenInFlight -= 1;\n    if (!counts) return;\n\n    if (this.#state === \"half-open\") {\n      // Symmetric with recordSuccess: only the probe re-opens a half-open\n      // breaker. A non-probe failure here is stale work from a call\n      // admitted before the trip and must not override the probe's verdict.\n      if (!probe) return;\n      this.#openedAt = now;\n      this.#state = \"open\";\n      // Exactly one failed probe re-opened the breaker. Report 1 rather\n      // than `#failures.length`, which still holds the original\n      // closed-state trip's timestamps (cleared only on close) and is\n      // therefore a stale, window-dependent number here.\n      hooks.onOpened(1);\n      return;\n    }\n\n    if (this.#state === \"closed\") {\n      this.#failures.push(now);\n      this.#prune(now);\n      if (this.#failures.length >= this.#options.failureThreshold) {\n        this.#openedAt = now;\n        this.#state = \"open\";\n        hooks.onOpened(this.#failures.length);\n      }\n    }\n  }\n}\n\n/**\n * Owns the circuit-breaker state for one `.circuitBreaker()` across every\n * Route the enclosing step (or segment) runs in. Keyed by Route in a\n * WeakMap, so a single definition registered into multiple contexts gives\n * each Route its OWN breaker rather than one shared circuit (which would\n * let the contexts trip each other). Mirrors {@link ThrottleController}.\n *\n * @internal\n */\nexport class CircuitBreakerController extends RouteScopedController<CircuitBreakerMachine> {\n  readonly #options: ResolvedCircuitBreakerOptions;\n\n  constructor(options: ResolvedCircuitBreakerOptions) {\n    super();\n    this.#options = options;\n  }\n\n  /** The resolved options (fallback, threshold, cooldown, label, ...). */\n  get options(): ResolvedCircuitBreakerOptions {\n    return this.#options;\n  }\n\n  /** Optional gate label, surfaced on the `route:circuitBreaker:*` events. */\n  get label(): string | undefined {\n    return this.#options.label;\n  }\n\n  protected createState(): CircuitBreakerMachine {\n    return new CircuitBreakerMachine(this.#options);\n  }\n\n  acquire(\n    route: Route | undefined,\n    hooks: CircuitBreakerHooks,\n  ): CircuitBreakerDecision {\n    return this.stateFor(route).acquire(Date.now(), hooks);\n  }\n\n  recordSuccess(\n    route: Route | undefined,\n    probe: boolean,\n    hooks: CircuitBreakerHooks,\n  ): void {\n    this.stateFor(route).recordSuccess(probe, hooks);\n  }\n\n  recordFailure(\n    route: Route | undefined,\n    error: Error,\n    probe: boolean,\n    hooks: CircuitBreakerHooks,\n  ): void {\n    // `isFailure` is user code. Isolate it like `onStateChange`: a throwing\n    // predicate must not mask the original step error (re-thrown by the\n    // caller after this returns), skip breaker accounting, or leak the\n    // half-open probe slot. Default to counting the failure on a throw.\n    let counts = true;\n    try {\n      counts = this.#options.isFailure(error);\n    } catch (err) {\n      logger.warn(\n        { err },\n        \"circuitBreaker isFailure callback threw; counting the failure\",\n      );\n    }\n    this.stateFor(route).recordFailure(Date.now(), probe, counts, hooks);\n  }\n}\n\n/** Event-scope bindings shared by the `route:circuitBreaker:*` payloads. */\nexport interface CircuitBreakerEventScope {\n  routeId: string;\n  exchangeId: string;\n  correlationId: string;\n  stepLabel: string;\n  scope: \"route\" | \"step\";\n  /** Optional breaker label, when configured. */\n  label?: string;\n}\n\n/**\n * Build the {@link CircuitBreakerHooks} that emit the\n * `route:circuitBreaker:*` events. Shared by the step-scope wrapper and\n * the route-scope segment so the payload shape lives in one place (only\n * the `scoped` descriptor and the `emit` guard differ). `context?.emit`\n * no-ops when the exchange carries no context.\n *\n * @internal\n */\nexport function circuitBreakerEmitHooks(\n  context: CraftContext | undefined,\n  scoped: CircuitBreakerEventScope,\n  emit: boolean,\n  options: ResolvedCircuitBreakerOptions,\n): CircuitBreakerHooks {\n  return {\n    onOpened: (failureCount) => {\n      if (emit) {\n        context?.emit(\"route:circuitBreaker:opened\", {\n          ...scoped,\n          failureCount,\n          threshold: options.failureThreshold,\n          cooldownMs: options.cooldownMs,\n        });\n      }\n    },\n    onHalfOpen: () => {\n      if (emit) context?.emit(\"route:circuitBreaker:halfOpen\", { ...scoped });\n    },\n    onClosed: () => {\n      if (emit) context?.emit(\"route:circuitBreaker:closed\", { ...scoped });\n    },\n    onRejected: (state, retryAfterMs) => {\n      if (emit) {\n        context?.emit(\"route:circuitBreaker:rejected\", {\n          ...scoped,\n          state,\n          retryAfterMs,\n        });\n      }\n    },\n  };\n}\n\n/**\n * Build the `forward` passed to a `fallback`: the route's direct-route\n * caller, or (when the step ran without a route binding, e.g. a unit test)\n * a stub that fails loudly only if the fallback actually calls it, so a\n * static fallback that ignores `forward` still works. Mirrors the\n * step-scope `.error()` handler's forward handling.\n *\n * @internal\n */\nexport function circuitBreakerForward(\n  route: Route | undefined,\n  caller: Exchange,\n): ForwardFn {\n  if (route) return route.getForward(caller);\n  return () =>\n    Promise.reject(\n      rcError(\"RC5001\", undefined, {\n        message:\n          \"circuitBreaker fallback called forward() but the step ran without a route binding; forward() requires a route.\",\n      }),\n    );\n}\n\n/**\n * Outcome for a rejected call (breaker open, or half-open at capacity):\n * substitute the configured `fallback` body and continue, or throw\n * `RC5025` so the route's `.error()` handler (or the default error path)\n * decides what to do. The `fallback` receives `forward` so it can produce\n * a dynamic body from a direct route, and may be async. Shared by the\n * step-scope wrapper and the route-scope segment.\n *\n * @internal\n */\nexport async function circuitOpenOutcome(\n  exchange: Exchange,\n  options: ResolvedCircuitBreakerOptions,\n  forward: ForwardFn,\n  scopeDescription: string,\n): Promise<StepOutcome> {\n  if (options.fallback) {\n    const body = await options.fallback(exchange, forward);\n    return {\n      kind: \"continue\",\n      exchange: DefaultExchange.rewrap(exchange, { body }),\n    };\n  }\n  throw rcError(\"RC5025\", undefined, {\n    message: `Circuit breaker ${scopeDescription} is open; failing fast (no fallback configured).`,\n  });\n}\n\n/**\n * Run `run` under the breaker `controller` for `route`, recording the\n * outcome: a resolve (success, or a drop) records a success, a throw\n * records a counted failure and re-throws. When the breaker rejects the\n * call (open, or half-open at capacity) the protected work is skipped and\n * `onOpen()` produces the substitute outcome (a `fallback` continue, or a\n * thrown `RC5025`).\n *\n * Shared by the step-scope wrapper and the route-scope segment so the\n * acquire / record protocol lives in one place, mirroring the retry\n * operation's `executeWithRetry`.\n *\n * @internal\n */\nexport async function executeWithCircuitBreaker(\n  controller: CircuitBreakerController,\n  route: Route | undefined,\n  hooks: CircuitBreakerHooks,\n  onOpen: () => Promise<StepOutcome>,\n  run: () => Promise<StepOutcome>,\n): Promise<StepOutcome> {\n  const decision = controller.acquire(route, hooks);\n  if (!decision.admitted) return onOpen();\n  try {\n    const outcome = await run();\n    controller.recordSuccess(route, decision.probe, hooks);\n    return outcome;\n  } catch (err) {\n    controller.recordFailure(\n      route,\n      err instanceof Error ? err : new Error(String(err)),\n      decision.probe,\n      hooks,\n    );\n    throw err;\n  }\n}\n\n/**\n * Step-scope `.circuitBreaker()` wrapper. Protects the immediately-next\n * step: counts its failures over a sliding window, trips after the\n * threshold, then fast-fails subsequent calls (fallback or `RC5025`)\n * until the cooldown elapses and a probe is allowed through. The breaker\n * state lives on a {@link CircuitBreakerController} keyed by Route, so\n * every exchange on a given Route shares one breaker while distinct\n * Routes (even from the same definition) stay isolated. This is the\n * deliberate per-ROUTE shared-state exception to the `WrapperStep` rule\n * (see `.standards/resilience-wrappers.md` section 8).\n *\n * Emits the `route:circuitBreaker:opened` / `:halfOpen` / `:closed` /\n * `:rejected` family with `scope: \"step\"`.\n */\nexport class CircuitBreakerWrapperStep<\n  T extends Adapter = Adapter,\n> extends WrapperStep<T> {\n  readonly #options: ResolvedCircuitBreakerOptions;\n  readonly #controller: CircuitBreakerController;\n\n  constructor(inner: Step<T>, options: CircuitBreakerOptions) {\n    super(inner);\n    this.#options = resolveCircuitBreakerOptions(options);\n    this.#controller = new CircuitBreakerController(this.#options);\n  }\n\n  protected override describeOptions(): unknown {\n    return this.#options;\n  }\n\n  protected override async runInner(\n    exchange: Exchange,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const { route, context, routeId, stepLabel, correlationId } =\n      wrapperEventScope(exchange, this);\n    const shouldEmit = Boolean(route && context && routeId);\n    const scoped: CircuitBreakerEventScope = {\n      routeId: routeId as string,\n      exchangeId: exchange.id,\n      correlationId,\n      stepLabel,\n      scope: \"step\",\n      ...(this.#controller.label !== undefined\n        ? { label: this.#controller.label }\n        : {}),\n    };\n    const hooks = circuitBreakerEmitHooks(\n      context,\n      scoped,\n      shouldEmit,\n      this.#controller.options,\n    );\n\n    const forward = circuitBreakerForward(route, exchange);\n\n    return executeWithCircuitBreaker(\n      this.#controller,\n      route,\n      hooks,\n      () =>\n        circuitOpenOutcome(\n          exchange,\n          this.#controller.options,\n          forward,\n          `for step \"${stepLabel}\"`,\n        ),\n      () => this.inner.execute(exchange, ctx),\n    );\n  }\n}\n","import { LRUCache } from \"lru-cache\";\nimport type { Exchange } from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport type { CraftContext } from \"../context.ts\";\nimport type { Route } from \"../route.ts\";\nimport { WrapperStep } from \"./wrapper.ts\";\nimport { wrapperEventScope } from \"./event-scope.ts\";\nimport { SleepAbortedError } from \"./cancellable-sleep.ts\";\nimport { DEFAULT_MAX_KEYS, validateMaxKeys } from \"./max-keys.ts\";\nimport { RouteScopedController } from \"./route-scoped-controller.ts\";\nimport { Semaphore } from \"./semaphore.ts\";\n\n/**\n * Options for the `.concurrency()` wrapper (step scope and route scope).\n *\n * A bulkhead: it bounds how many exchanges run the wrapped work AT ONCE,\n * as opposed to `.throttle()`, which bounds how many run PER TIME WINDOW.\n * The two compose but are not substitutes: a 10/sec throttle still allows\n * unbounded simultaneous in-flight exchanges if each is slow; a\n * concurrency of 5 caps simultaneity regardless of rate (protect a\n * connection pool, a memory-bound step, or a downstream with a hard\n * concurrency cap).\n */\nexport interface ConcurrencyOptions {\n  /** Maximum simultaneous in-flight exchanges. Must be a finite integer >= 1. */\n  max: number;\n  /**\n   * Behaviour when all slots are busy:\n   * - `\"queue\"` (default): the exchange waits FIFO for a slot, applying\n   *   backpressure rather than dropping it. The wait is cancellable, so on\n   *   route shutdown a waiting exchange is admitted rather than stranded.\n   * - `\"reject\"`: fail fast with `RC5026` (no slot, no wait) so the caller\n   *   sheds load instead of building an unbounded in-memory backlog.\n   */\n  mode?: \"queue\" | \"reject\";\n  /**\n   * Queue mode only: cap the wait line. When `max` slots are busy AND\n   * `maxQueue` exchanges are already waiting, the next one fails fast with\n   * `RC5026` instead of joining the queue. The middle ground between \"wait\n   * forever\" (omit it) and \"reject as soon as busy\" (`mode: \"reject\"`).\n   * Must be a finite integer >= 1; passing it in `reject` mode is rejected\n   * at build time (use `mode: \"reject\"`, which is `maxQueue: 0`). Default:\n   * unbounded.\n   */\n  maxQueue?: number;\n  /**\n   * Partition the limit: each distinct key gets its own independent slot\n   * pool, so you can cap concurrency per user / tenant / connection pool.\n   * Omit for a single pool shared across the whole route. The selector runs\n   * once per exchange and MUST return a string; coalesce missing values\n   * (e.g. `?? \"anonymous\"`). A selector that throws fails the exchange.\n   *\n   * @example Per authenticated principal\n   * ```ts\n   * .concurrency({ max: 3, key: (ex) => ex.principal?.subject ?? \"anonymous\" })\n   * ```\n   */\n  key?: (exchange: Exchange) => string;\n  /**\n   * Maximum number of distinct keys to track concurrently when `key` is\n   * set. Per-key semaphores live in an LRU, so memory stays bounded even\n   * with an unbounded key space. Default `10_000`. Ignored when `key` is\n   * not set.\n   */\n  maxKeys?: number;\n  /**\n   * Optional label carried on this bulkhead's `route:concurrency:*` events,\n   * so stacked or sibling limiters can be told apart in logs and metrics.\n   * Has no effect on behaviour.\n   */\n  label?: string;\n}\n\n/**\n * {@link ConcurrencyOptions} with every behavioural field populated. Shared\n * by the step-scope wrapper and the route-scope segment.\n *\n * @internal\n */\nexport interface ResolvedConcurrencyOptions {\n  max: number;\n  mode: \"queue\" | \"reject\";\n  /** Wait-queue bound; `Number.POSITIVE_INFINITY` when unbounded. */\n  maxQueue: number;\n  key?: (exchange: Exchange) => string;\n  maxKeys: number;\n  label?: string;\n}\n\n/**\n * Validate user-supplied {@link ConcurrencyOptions} into a\n * {@link ResolvedConcurrencyOptions}. Rejects at build time (RC5003) so a\n * typo fails when the route is built rather than at first dispatch.\n *\n * @internal\n */\nexport function resolveConcurrencyOptions(\n  options: ConcurrencyOptions,\n): ResolvedConcurrencyOptions {\n  const {\n    max,\n    mode = \"queue\",\n    maxQueue,\n    key,\n    maxKeys = DEFAULT_MAX_KEYS,\n    label,\n  } = options;\n\n  if (!Number.isInteger(max) || max < 1) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `concurrency({ max }) must be an integer >= 1, got ${String(max)}.`,\n    });\n  }\n  if (mode !== \"queue\" && mode !== \"reject\") {\n    throw rcError(\"RC5003\", undefined, {\n      message: `concurrency({ mode }) must be \"queue\" or \"reject\", got ${String(mode)}.`,\n    });\n  }\n  if (maxQueue !== undefined) {\n    if (mode === \"reject\") {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          'concurrency({ maxQueue }) is meaningless in reject mode (reject never queues). Drop maxQueue, or use mode \"queue\".',\n      });\n    }\n    if (!Number.isInteger(maxQueue) || maxQueue < 1) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `concurrency({ maxQueue }) must be an integer >= 1, got ${String(maxQueue)}. To fail fast when all slots are busy, use mode \"reject\".`,\n      });\n    }\n  }\n  validateMaxKeys(\"concurrency\", maxKeys);\n\n  return {\n    max,\n    mode,\n    maxQueue: maxQueue ?? Number.POSITIVE_INFINITY,\n    ...(key ? { key } : {}),\n    maxKeys,\n    ...(label !== undefined ? { label } : {}),\n  };\n}\n\n/**\n * Per-route bulkhead state for one `.concurrency()`. Holds a single shared\n * {@link Semaphore} when unkeyed, or an LRU of per-key semaphores when a\n * `key` selector is configured. One instance per Route (see\n * {@link ConcurrencyController}), never one per exchange.\n *\n * @internal\n */\nexport class ConcurrencyLimiter {\n  readonly #options: ResolvedConcurrencyOptions;\n  #single?: Semaphore;\n  readonly #keyed?: LRUCache<string, Semaphore>;\n\n  constructor(options: ResolvedConcurrencyOptions) {\n    this.#options = options;\n    if (options.key) {\n      // Per-key semaphores live in an LRU so memory stays bounded under an\n      // unbounded key space. We do NOT try to protect an in-use pool from\n      // eviction: re-admitting it inside lru-cache's `dispose` is unsafe\n      // (a re-entrant `set` during eviction is swallowed and corrupts the\n      // cache, per lru-cache's own docs). If a key with in-flight work is\n      // evicted (only possible when more than `maxKeys` distinct keys are\n      // live at once), its existing holders keep their slots via the\n      // release closures and drain correctly; the next call for that key\n      // builds a fresh pool. The transient effect is a bounded over-admit\n      // for that one key at the eviction boundary (at most `max` extra\n      // in-flight until the orphaned pool drains), the same self-correcting\n      // trade-off `.throttle()` accepts for its keyed buckets. Raise\n      // `maxKeys` if a hard per-key cap must hold under extreme cardinality.\n      this.#keyed = new LRUCache<string, Semaphore>({ max: options.maxKeys });\n    }\n  }\n\n  /**\n   * Resolve the {@link Semaphore} for `exchange` (the shared one, or the\n   * per-key one, creating it on first use), plus the partition key it\n   * belongs to (absent when unkeyed).\n   */\n  semaphoreFor(exchange: Exchange): { semaphore: Semaphore; key?: string } {\n    if (!this.#options.key) {\n      this.#single ??= new Semaphore(this.#options.max);\n      return { semaphore: this.#single };\n    }\n    let key: string;\n    try {\n      key = this.#options.key(exchange);\n    } catch (err) {\n      throw rcError(\"RC5003\", err, {\n        message:\n          'concurrency({ key }) selector threw; it must return a string for every exchange (e.g. coalesce a missing value with `?? \"anonymous\"`).',\n      });\n    }\n    let semaphore = this.#keyed!.get(key);\n    if (!semaphore) {\n      semaphore = new Semaphore(this.#options.max);\n      this.#keyed!.set(key, semaphore);\n    }\n    return { semaphore, key };\n  }\n}\n\n/**\n * Lifecycle hooks the bulkhead reports to, so the step-scope wrapper and\n * the route-scope segment emit the same `route:concurrency:*` events with\n * their own `scope` / `stepLabel` bindings.\n *\n * @internal\n */\nexport interface ConcurrencyHooks {\n  /** Route abort signal; cancels the queue wait on shutdown. */\n  signal?: AbortSignal;\n  /** All slots were busy; the exchange joins the wait queue at `queueDepth`. */\n  onQueued(queueDepth: number, key?: string): void;\n  /**\n   * A slot was acquired. `waited` is true when the exchange had to queue\n   * first; `inUse` is the slot count after admission.\n   */\n  onAcquired(waited: boolean, inUse: number, key?: string): void;\n  /** The held slot was released; `heldMs` is how long the work held it. */\n  onReleased(heldMs: number, key?: string): void;\n  /**\n   * The exchange was failed fast (`RC5026`): `reason` is `\"busy\"` (reject\n   * mode, all slots busy) or `\"queue-full\"` (queue mode, wait line at\n   * `maxQueue`).\n   */\n  onRejected(reason: \"busy\" | \"queue-full\", key?: string): void;\n}\n\n/** Event-scope bindings shared by the `route:concurrency:*` payloads. */\nexport interface ConcurrencyEventScope {\n  routeId: string;\n  exchangeId: string;\n  correlationId: string;\n  stepLabel: string;\n  scope: \"route\" | \"step\";\n  /** Optional limiter label, when configured. */\n  label?: string;\n}\n\n/**\n * Build the {@link ConcurrencyHooks} that emit the `route:concurrency:*`\n * events. Shared by the step-scope wrapper and the route-scope segment so\n * the payload shape lives in one place (only the `scoped` descriptor and\n * the `emit` guard differ). `context?.emit` no-ops when the exchange\n * carries no context.\n *\n * @internal\n */\nexport function concurrencyEmitHooks(\n  context: CraftContext | undefined,\n  scoped: ConcurrencyEventScope,\n  emit: boolean,\n): Pick<\n  ConcurrencyHooks,\n  \"onQueued\" | \"onAcquired\" | \"onReleased\" | \"onRejected\"\n> {\n  return {\n    onQueued: (queueDepth, key) => {\n      if (emit) {\n        context?.emit(\"route:concurrency:queued\", {\n          ...scoped,\n          queueDepth,\n          ...(key !== undefined ? { key } : {}),\n        });\n      }\n    },\n    onAcquired: (waited, inUse, key) => {\n      if (emit) {\n        context?.emit(\"route:concurrency:acquired\", {\n          ...scoped,\n          waited,\n          inUse,\n          ...(key !== undefined ? { key } : {}),\n        });\n      }\n    },\n    onReleased: (heldMs, key) => {\n      if (emit) {\n        context?.emit(\"route:concurrency:released\", {\n          ...scoped,\n          heldMs,\n          ...(key !== undefined ? { key } : {}),\n        });\n      }\n    },\n    onRejected: (reason, key) => {\n      if (emit) {\n        context?.emit(\"route:concurrency:rejected\", {\n          ...scoped,\n          reason,\n          ...(key !== undefined ? { key } : {}),\n        });\n      }\n    },\n  };\n}\n\n/**\n * Owns the bulkhead state for one `.concurrency()` across every Route the\n * enclosing step (or segment) runs in. Keyed by Route in a WeakMap, so a\n * single definition registered into multiple contexts gives each Route its\n * OWN slot pool rather than one shared bulkhead (which would let the\n * contexts steal each other's slots). Mirrors {@link ThrottleController}.\n *\n * @internal\n */\nexport class ConcurrencyController extends RouteScopedController<ConcurrencyLimiter> {\n  readonly #options: ResolvedConcurrencyOptions;\n\n  constructor(options: ResolvedConcurrencyOptions) {\n    super();\n    this.#options = options;\n  }\n\n  /** Optional limiter label, surfaced on the `route:concurrency:*` events. */\n  get label(): string | undefined {\n    return this.#options.label;\n  }\n\n  protected createState(): ConcurrencyLimiter {\n    return new ConcurrencyLimiter(this.#options);\n  }\n\n  /**\n   * Build the `RC5026` rejection message. A private method (not a per-call\n   * closure or an eagerly-built string) so the hot admit path allocates\n   * nothing: it runs only on the cold reject path. When keyed, `max` is the\n   * PER-KEY limit, so the message says so rather than reading as a global cap.\n   */\n  #rejectionMessage(key: string | undefined, queueFull: boolean): string {\n    const limit =\n      key !== undefined\n        ? `the per-key concurrency limit of ${this.#options.max} is full for key \"${key}\"`\n        : `all ${this.#options.max} concurrency slots are busy`;\n    const tail = queueFull\n      ? ` and the wait queue is full (maxQueue ${this.#options.maxQueue})`\n      : \"\";\n    return `concurrency rejected the exchange: ${limit}${tail}.`;\n  }\n\n  /**\n   * Acquire a slot for `exchange`. In `queue` mode (default) the caller\n   * waits FIFO when the pool is full (bounded by `maxQueue`); the wait is\n   * cancellable, so on route shutdown the exchange is admitted rather than\n   * stranded. In `reject` mode a busy pool fails fast with `RC5026` without\n   * waiting. Returns the (idempotent) release function plus the partition\n   * key it was charged against (absent when unkeyed).\n   *\n   * `opts.mustWait` overrides BOTH modes for a caller that cannot absorb a\n   * refusal, and deliberately ignores `maxQueue` as well: rejecting is the\n   * outcome the flag exists to prevent, so a bounded wait line would\n   * reintroduce it under a different name. The limit itself still holds,\n   * because the semaphore is the route's own and is shared with every other\n   * caller. Read `maxQueue` as bounding the exchanges that CAN be shed.\n   *\n   * Two gaps that flag does not close, both worth knowing before sizing\n   * `max`: the wait is unbounded in TIME as well as in depth, so a saturated\n   * pool holds each waiter (and whatever answered it) until a slot frees or\n   * the route stops; and a `key` selector that throws still raises `RC5003`\n   * from below, because the partition has to be resolved before the mode is\n   * consulted.\n   */\n  async acquire(\n    exchange: Exchange,\n    route: Route | undefined,\n    hooks: ConcurrencyHooks,\n    opts: { mustWait?: boolean } = {},\n  ): Promise<{ release: () => void; key?: string }> {\n    const { semaphore, key } = this.stateFor(route).semaphoreFor(exchange);\n\n    if (opts.mustWait) {\n      const free = semaphore.tryAcquire();\n      if (free) {\n        hooks.onAcquired(false, semaphore.inUse, key);\n        return { release: free, ...(key !== undefined ? { key } : {}) };\n      }\n      return this.#joinWaitLine(semaphore, hooks, key);\n    }\n\n    if (this.#options.mode === \"reject\") {\n      const release = semaphore.tryAcquire();\n      if (release) {\n        hooks.onAcquired(false, semaphore.inUse, key);\n        return { release, ...(key !== undefined ? { key } : {}) };\n      }\n      hooks.onRejected(\"busy\", key);\n      throw rcError(\"RC5026\", undefined, {\n        message: this.#rejectionMessage(key, false),\n      });\n    }\n\n    // Queue mode: take a free slot immediately, else join the bounded wait\n    // line. `waiting >= maxQueue` is checked BEFORE queueing so the cap\n    // counts only exchanges actually deferred (not the one being admitted).\n    const free = semaphore.tryAcquire();\n    if (free) {\n      hooks.onAcquired(false, semaphore.inUse, key);\n      return { release: free, ...(key !== undefined ? { key } : {}) };\n    }\n    if (semaphore.waiting >= this.#options.maxQueue) {\n      hooks.onRejected(\"queue-full\", key);\n      throw rcError(\"RC5026\", undefined, {\n        message: this.#rejectionMessage(key, true),\n      });\n    }\n\n    return this.#joinWaitLine(semaphore, hooks, key);\n  }\n\n  /**\n   * Wait FIFO for a slot, shared by queue mode and `mustWait`. Only the\n   * decision to join differs between them; the wait itself must not.\n   *\n   * Route shutdown while queued admits the exchange with a no-op release so\n   * teardown processes it rather than dropping it. No slot is charged\n   * (`inUse` excludes this exchange), but the balanced `acquired` ->\n   * `released` pair still fires so the `queued` event has a matching\n   * terminal; suppressing them would leave an orphaned `queued` and\n   * unbalance queue-depth accounting at teardown.\n   */\n  async #joinWaitLine(\n    semaphore: Semaphore,\n    hooks: ConcurrencyHooks,\n    key: string | undefined,\n  ): Promise<{ release: () => void; key?: string }> {\n    hooks.onQueued(semaphore.waiting + 1, key);\n    try {\n      const release = await semaphore.acquire(hooks.signal);\n      hooks.onAcquired(true, semaphore.inUse, key);\n      return { release, ...(key !== undefined ? { key } : {}) };\n    } catch (err) {\n      if (!(err instanceof SleepAbortedError)) throw err;\n      hooks.onAcquired(true, semaphore.inUse, key);\n      return { release: () => {}, ...(key !== undefined ? { key } : {}) };\n    }\n  }\n}\n\n/**\n * Run `run` under the bulkhead `controller` for `route`: acquire a slot\n * (queueing or fast-failing per mode), run the work, and release the slot\n * in a `finally` so a throw, drop, or success all free it exactly once.\n * Shared by the step-scope wrapper and the route-scope segment so the\n * acquire / release protocol lives in one place, mirroring\n * `executeWithCircuitBreaker` / `executeWithRetry`.\n *\n * @internal\n */\nexport async function executeWithConcurrency(\n  controller: ConcurrencyController,\n  exchange: Exchange,\n  route: Route | undefined,\n  hooks: ConcurrencyHooks,\n  run: () => Promise<StepOutcome>,\n  opts: { mustWait?: boolean } = {},\n): Promise<StepOutcome> {\n  const { release, key } = await controller.acquire(\n    exchange,\n    route,\n    hooks,\n    opts,\n  );\n  const heldStart = Date.now();\n  try {\n    return await run();\n  } finally {\n    release();\n    hooks.onReleased(Date.now() - heldStart, key);\n  }\n}\n\n/**\n * Step-scope `.concurrency()` wrapper. Bounds the wrapped step to `max`\n * simultaneous in-flight exchanges, queueing (backpressure) or fast-failing\n * (`RC5026`) the rest per `mode`.\n *\n * The slot pool lives on a {@link ConcurrencyController} keyed by Route, so\n * every exchange on a given Route shares one bulkhead while distinct Routes\n * (even from the same definition) stay isolated. This is the deliberate\n * per-ROUTE shared-state exception to the `WrapperStep` rule (see\n * `.standards/resilience-wrappers.md` section 8).\n *\n * Emits the `route:concurrency:queued` / `:acquired` / `:released` /\n * `:rejected` family with `scope: \"step\"`.\n */\nexport class ConcurrencyWrapperStep<\n  T extends Adapter = Adapter,\n> extends WrapperStep<T> {\n  readonly #options: ResolvedConcurrencyOptions;\n  readonly #controller: ConcurrencyController;\n\n  constructor(inner: Step<T>, options: ConcurrencyOptions) {\n    super(inner);\n    this.#options = resolveConcurrencyOptions(options);\n    this.#controller = new ConcurrencyController(this.#options);\n  }\n\n  protected override describeOptions(): unknown {\n    return this.#options;\n  }\n\n  protected override async runInner(\n    exchange: Exchange,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const { route, context, routeId, stepLabel, correlationId } =\n      wrapperEventScope(exchange, this);\n    const shouldEmit = Boolean(route && context && routeId);\n    const scoped: ConcurrencyEventScope = {\n      routeId: routeId as string,\n      exchangeId: exchange.id,\n      correlationId,\n      stepLabel,\n      scope: \"step\",\n      ...(this.#controller.label !== undefined\n        ? { label: this.#controller.label }\n        : {}),\n    };\n\n    return executeWithConcurrency(\n      this.#controller,\n      exchange,\n      route,\n      {\n        // Intake: a queued exchange is released as soon as shutdown begins\n        // and admitted with a no-op release (see `#joinWaitLine`), so the\n        // drain runs it instead of leaving it deferred behind a slot that will\n        // never free.\n        ...(route ? { signal: route.intakeSignal } : {}),\n        ...concurrencyEmitHooks(context, scoped, shouldEmit),\n      },\n      () => this.inner.execute(exchange, ctx),\n    );\n  }\n}\n","import { SleepAbortedError } from \"./cancellable-sleep.ts\";\n\n/**\n * One exchange waiting for a slot to free. Resolved (with a fresh release\n * function) when a holder releases, or rejected with\n * {@link SleepAbortedError} when its `signal` aborts first.\n *\n * @internal\n */\ninterface SemaphoreWaiter {\n  resolve: (release: () => void) => void;\n  reject: (error: Error) => void;\n  signal?: AbortSignal;\n  onAbort?: () => void;\n}\n\n/**\n * A counting semaphore: bounds how many holders may run at once, queueing\n * the rest FIFO. The shared concurrency primitive behind `.concurrency()`\n * (the bulkhead wrapper) and, in future, bounded `.split()` fan-out.\n *\n * Synchronous-first, like {@link TokenBucket}: under the single-threaded\n * event loop a batch of concurrent exchanges each take a distinct slot (or\n * a distinct queue position) in the same tick, so admission order is\n * deterministic FIFO and the cap is never exceeded.\n *\n * State is in-memory and lives PER ROUTE (one `Semaphore` per Route, held\n * by a controller's WeakMap), never per exchange. A handed-out release\n * function is idempotent: calling it twice frees exactly one slot.\n *\n * @internal\n */\nexport class Semaphore {\n  readonly #max: number;\n  #inUse = 0;\n  readonly #waiters: SemaphoreWaiter[] = [];\n\n  constructor(max: number) {\n    this.#max = max;\n  }\n\n  /** Configured maximum simultaneous holders. */\n  get max(): number {\n    return this.#max;\n  }\n\n  /** Slots currently held (admitted but not yet released). */\n  get inUse(): number {\n    return this.#inUse;\n  }\n\n  /** Exchanges currently queued, waiting for a slot to free. */\n  get waiting(): number {\n    return this.#waiters.length;\n  }\n\n  /**\n   * Take a slot only if one is free right now. Returns a release function\n   * on success, or `undefined` when all slots are in use (the caller fails\n   * fast rather than waiting). Used by reject mode.\n   */\n  tryAcquire(): (() => void) | undefined {\n    if (this.#inUse < this.#max) {\n      this.#inUse += 1;\n      return this.#makeRelease();\n    }\n    return undefined;\n  }\n\n  /**\n   * Acquire a slot, waiting FIFO until one frees when all are in use.\n   * Resolves with a release function. Rejects with {@link SleepAbortedError}\n   * the moment `signal` aborts (route shutdown), so a stopping route does\n   * not strand an exchange in the wait queue. Used by queue mode.\n   */\n  acquire(signal?: AbortSignal): Promise<() => void> {\n    if (signal?.aborted) return Promise.reject(new SleepAbortedError());\n    if (this.#inUse < this.#max) {\n      this.#inUse += 1;\n      return Promise.resolve(this.#makeRelease());\n    }\n    return new Promise<() => void>((resolve, reject) => {\n      const waiter: SemaphoreWaiter = { resolve, reject };\n      if (signal) {\n        waiter.signal = signal;\n        waiter.onAbort = () => {\n          const index = this.#waiters.indexOf(waiter);\n          if (index >= 0) this.#waiters.splice(index, 1);\n          reject(new SleepAbortedError());\n        };\n        signal.addEventListener(\"abort\", waiter.onAbort, { once: true });\n      }\n      this.#waiters.push(waiter);\n    });\n  }\n\n  /**\n   * Build an idempotent release function. The slot is freed at most once\n   * regardless of how many times the function is called, so a wrapper that\n   * releases in a `finally` AND on an early path never double-frees.\n   */\n  #makeRelease(): () => void {\n    let released = false;\n    return () => {\n      if (released) return;\n      released = true;\n      this.#release();\n    };\n  }\n\n  /**\n   * Free one slot: hand it straight to the next waiter (the slot stays \"in\n   * use\", transferred without a decrement so the cap holds), or decrement\n   * `#inUse` when no one is waiting.\n   */\n  #release(): void {\n    const next = this.#waiters.shift();\n    if (next) {\n      if (next.signal && next.onAbort) {\n        next.signal.removeEventListener(\"abort\", next.onAbort);\n      }\n      next.resolve(this.#makeRelease());\n      return;\n    }\n    this.#inUse -= 1;\n  }\n}\n","import type { CraftPlugin } from \"./context.ts\";\n// Self-reference via the published specifier so ecosystem augmentations\n// (`declare module \"@routecraft/routecraft\" { interface CraftConfig { ... } }`)\n// propagate into this module's view of `CraftConfig`. Importing through\n// `./context.ts` would resolve to a separate module identity and miss the\n// augmentations.\nimport type { CraftConfig } from \"@routecraft/routecraft\";\n\n/**\n * Build a {@link CraftPlugin} from the value found at a given key on\n * {@link CraftConfig}. Receives the non-undefined value of `config[K]` and\n * returns a plugin whose `apply` and (optional) `teardown` participate in the\n * standard plugin lifecycle.\n *\n * @template K - Key on `CraftConfig` this applier handles\n */\nexport type ConfigApplier<K extends keyof CraftConfig> = (\n  options: NonNullable<CraftConfig[K]>,\n) => CraftPlugin;\n\n/**\n * Internal applier signature used by the registry. Public callers go through\n * {@link registerConfigApplier} which preserves the typed `K`.\n */\ntype AnyConfigApplier = (options: unknown) => CraftPlugin;\n\n/**\n * Cross-instance registry. `Symbol.for` so multiple copies of the package in\n * a workspace share a single registry; without this, an applier registered\n * by one package copy would be invisible to a `CraftContext` constructed\n * from another copy.\n */\nconst REGISTRY_KEY: unique symbol = Symbol.for(\n  \"routecraft.config-applier-registry\",\n);\n\ntype GlobalWithRegistry = typeof globalThis & {\n  [REGISTRY_KEY]?: Map<string, AnyConfigApplier>;\n};\n\nfunction getRegistry(): Map<string, AnyConfigApplier> {\n  const g = globalThis as GlobalWithRegistry;\n  let registry = g[REGISTRY_KEY];\n  if (!registry) {\n    registry = new Map<string, AnyConfigApplier>();\n    g[REGISTRY_KEY] = registry;\n  }\n  return registry;\n}\n\n/**\n * Register a function that converts a {@link CraftConfig} key into a plugin.\n *\n * Ecosystem packages call this once at module load time (typically from a\n * side-effect import) so that setting `config[key]` becomes equivalent to\n * pushing the corresponding plugin onto `config.plugins`. Resulting plugins\n * participate in the standard lifecycle: `apply()` runs during\n * `initPlugins()`, `teardown()` runs during `context.stop()`.\n *\n * The framework invokes the applier whenever `config[key] !== undefined`.\n * Falsy values (`false`, `0`, `\"\"`, `null`) are still passed through; only\n * `undefined` means \"not set\". This lets primitive-valued keys behave\n * sensibly without needing a wrapper object.\n *\n * Re-registering a key replaces the previous registration: last writer wins.\n * The registry is shared across copies of the package via `Symbol.for`, but\n * an applier registered by one copy of an ecosystem package is a different\n * function reference from the same applier registered by another copy. If\n * two copies of `@routecraft/ai` end up in the same workspace, the last one\n * to load is the one whose applier (and therefore whose `llmPlugin`\n * instance) runs. Structure your workspace to avoid duplicate copies of the\n * same ecosystem package; this registry does not transparently de-duplicate.\n *\n * @template K - Key on `CraftConfig` this applier handles\n * @param key - The `CraftConfig` key\n * @param applier - Factory that builds a plugin from the value at `config[key]`\n *\n * @example\n * ```typescript\n * declare module \"@routecraft/routecraft\" {\n *   interface CraftConfig {\n *     myKey?: MyOptions;\n *   }\n * }\n *\n * registerConfigApplier(\"myKey\", (options) => myPlugin(options));\n * ```\n */\nexport function registerConfigApplier<K extends keyof CraftConfig>(\n  key: K,\n  applier: ConfigApplier<K>,\n): void {\n  // Cast: at runtime we always invoke the applier with the value at config[key],\n  // which TS narrows to the registered type at the registration site. Storing\n  // as an unknown-keyed function lets the registry hold heterogeneous appliers.\n  getRegistry().set(key as string, applier as AnyConfigApplier);\n}\n\n/**\n * Get the registered config appliers in registration order.\n *\n * Consumed by `CraftContext` and `ContextBuilder` to convert first-class\n * config keys into plugins at construction time. Iteration order matches\n * registration order, which the constructor relies on to position ecosystem\n * appliers between core inline conversions and `config.plugins`.\n *\n * @internal\n */\nexport function getConfigAppliers(): ReadonlyMap<string, AnyConfigApplier> {\n  return getRegistry();\n}\n","import { rcError } from \"./error.ts\";\nimport type { EventHandler, EventName, EventPayload } from \"./types.ts\";\nimport { isThenable } from \"./shared/thenable.ts\";\n\n/**\n * Minimal logging surface the bus needs for handler-error reporting.\n * Matches the pino child logger used by `CraftContext`.\n */\ntype EventBusLogger = {\n  warn(obj: unknown, msg?: string): void;\n  error(obj: unknown, msg?: string): void;\n};\n\n/**\n * In-process event bus backing `CraftContext.on/once/emit`.\n *\n * Event names are a fixed, finite set (see `EventDetailsMap`); identity\n * (route id, plugin id, step label) lives in the payload. Subscription is\n * by exact name, plus the single catch-all `\"*\"` for telemetry-style taps\n * that observe every event. There is no pattern matching: emit is one Map\n * lookup plus the catch-all set, so the per-step hot path stays flat no\n * matter how many subscriptions exist.\n *\n * Not exported from the package index: the public subscription surface is\n * `CraftContext.on/once`. Tests may import this module directly.\n *\n * @internal\n */\nexport class EventBus {\n  /** Exact-name event handlers */\n  private readonly handlers: Map<EventName, Set<EventHandler<EventName>>> =\n    new Map();\n\n  /** Catch-all handlers subscribed via `\"*\"` (receive every event) */\n  private readonly catchAllHandlers: Set<EventHandler<EventName>> = new Set();\n\n  constructor(\n    private readonly contextId: string,\n    private readonly logger: EventBusLogger,\n  ) {}\n\n  /**\n   * Subscribe to an exact event name, or `\"*\"` for every event.\n   *\n   * Legacy wildcard patterns (`route:*`, `route:**`, ...) are rejected\n   * loudly: identity moved into event payloads, so per-route filtering is\n   * `ctx.on(\"route:exchange:failed\", forRoute(\"orders\", handler))`.\n   *\n   * @param event - Exact event name or `\"*\"`\n   * @param handler - Callback receiving `{ ts, contextId, details }`\n   * @returns Unsubscribe function (call to remove the handler)\n   */\n  on<K extends EventName>(event: K, handler: EventHandler<K>): () => void;\n  on(event: \"*\", handler: EventHandler<EventName>): () => void;\n  on(event: EventName | \"*\", handler: EventHandler<EventName>): () => void {\n    if (event === \"*\") {\n      this.catchAllHandlers.add(handler);\n      return () => {\n        this.catchAllHandlers.delete(handler);\n      };\n    }\n    if (typeof event === \"string\" && event.includes(\"*\")) {\n      throw rcError(\"RC2001\", undefined, {\n        message:\n          `Event pattern \"${event}\" is not supported: event names are a fixed set and identity lives in the payload. ` +\n          `Subscribe to the exact name (e.g. \"route:exchange:failed\") and filter with forRoute(routeId, handler), ` +\n          `or use \"*\" to observe every event.`,\n      });\n    }\n    const set = this.handlers.get(event) ?? new Set();\n    set.add(handler as unknown as EventHandler<EventName>);\n    this.handlers.set(event, set);\n    return () => {\n      set.delete(handler as unknown as EventHandler<EventName>);\n    };\n  }\n\n  /**\n   * Subscribe to an event for a single occurrence. The handler is\n   * automatically removed after the first time the event is emitted.\n   *\n   * Accepts the same names as `on()` (exact names or `\"*\"`).\n   *\n   * @param event - Exact event name or `\"*\"`\n   * @param handler - Callback receiving `{ ts, contextId, details }`\n   * @returns Unsubscribe function (call to remove the handler before it fires)\n   */\n  once<K extends EventName>(event: K, handler: EventHandler<K>): () => void;\n  once(event: \"*\", handler: EventHandler<EventName>): () => void;\n  once(event: EventName | \"*\", handler: EventHandler<EventName>): () => void {\n    const wrappedHandler: EventHandler<EventName> = (payload) => {\n      unsubscribe();\n      return handler(payload);\n    };\n    const unsubscribe = this.on(event as EventName, wrappedHandler);\n    return unsubscribe;\n  }\n\n  /**\n   * Emit an event to registered handlers.\n   *\n   * @param event - Event name\n   * @param details - Event-specific payload (merged into `EventPayload.details`)\n   */\n  emit<K extends EventName>(\n    event: K,\n    details: EventPayload<K>[\"details\"],\n  ): void {\n    const exactSet = this.handlers.get(event);\n    const exactCount = exactSet ? exactSet.size : 0;\n    if (exactCount === 0 && this.catchAllHandlers.size === 0) return;\n\n    const payload: EventPayload<K> = {\n      ts: new Date().toISOString(),\n      contextId: this.contextId,\n      details,\n    } as EventPayload<K>;\n\n    payload._event = event;\n\n    // Snapshot so handlers that unsubscribe (once) or subscribe during\n    // dispatch do not affect this emit.\n    const matchingHandlers: EventHandler<EventName>[] = [];\n    if (exactSet && exactCount > 0) {\n      matchingHandlers.push(...Array.from(exactSet));\n    }\n    if (this.catchAllHandlers.size > 0) {\n      matchingHandlers.push(...Array.from(this.catchAllHandlers));\n    }\n\n    // Execute all matching handlers\n    for (const handler of matchingHandlers) {\n      try {\n        const result = (handler as unknown as EventHandler<K>)(payload);\n        // A thenable carries no `catch`, and reaching for one unwrapped\n        // throws from inside this `try`, misreporting the handler as\n        // having thrown when it returned normally.\n        if (isThenable(result)) {\n          void Promise.resolve(result).catch((err: unknown) => {\n            // Log async handler errors at error level for error events, warn for others\n            const logLevel = event === \"context:error\" ? \"error\" : \"warn\";\n            this.logger[logLevel](\n              { event, err },\n              \"Async event handler rejected. Handler should not throw; errors are emitted as context 'error' event.\",\n            );\n            if (event !== \"context:error\") {\n              this.emit(\"context:error\", { error: err });\n            }\n          });\n        }\n      } catch (err) {\n        // Swallow synchronous handler errors but log them and emit system error\n        // Log error events at error level, others at warn\n        const logLevel = event === \"context:error\" ? \"error\" : \"warn\";\n        this.logger[logLevel](\n          { event, err },\n          \"Event handler threw. Handler should not throw; errors are emitted as context 'error' event.\",\n        );\n        if (event !== \"context:error\") {\n          this.emit(\"context:error\", { error: err });\n        }\n      }\n    }\n  }\n}\n","// Self-reference via the published specifier so ecosystem augmentations\n// (`declare module \"@routecraft/routecraft\" { interface CraftConfig { ... } }`)\n// propagate into this module's view of `CraftConfig`. Importing through\n// `./context.ts` would resolve to a separate module identity and miss the\n// augmentations. See config-applier.ts for the same pattern.\nimport type { CraftConfig } from \"@routecraft/routecraft\";\n\n/**\n * Identity helper for typing a {@link CraftConfig}. Returns the input\n * unchanged at runtime; at compile time it gives the literal the same\n * checking a `const config: CraftConfig = {...}` annotation does: autocomplete\n * for every key (including keys augmented by ecosystem packages such as\n * `@routecraft/ai`) and an error for any key `CraftConfig` does not declare,\n * at every nesting level.\n *\n * The parameter is deliberately not generic. TypeScript checks excess\n * properties only against a concrete target type, so a `<T extends\n * CraftConfig>` parameter let a stale or misspelled key compile and fail at\n * boot instead.\n *\n * @param config - Config object\n * @returns The same config object\n *\n * @example\n * ```typescript\n * import { defineConfig } from \"@routecraft/routecraft\";\n * import \"@routecraft/ai\"; // augments CraftConfig with `llm`, `mcp`, etc.\n *\n * export const craftConfig = defineConfig({\n *   cron: { timezone: \"UTC\" },\n *   llm: { providers: { openai: { apiKey: process.env.OPENAI_API_KEY! } } },\n * });\n * ```\n */\nexport function defineConfig(config: CraftConfig): CraftConfig {\n  return config;\n}\n","// Self-reference via the published specifier so ecosystem augmentations\n// (`declare module \"@routecraft/routecraft\" { interface CraftConfig { ... } }`)\n// propagate into this module's view of `CraftConfig`. Importing through\n// `./context.ts` would resolve to a separate module identity and miss the\n// augmentations.\nimport type { CraftConfig } from \"@routecraft/routecraft\";\nimport { rcError } from \"./error.ts\";\n\n/**\n * Everything a discoverer is given about the folder it matched and the\n * project around it.\n *\n * Passed as one object rather than positional arguments so the contract\n * can grow (a logger, a dry-run flag) without breaking every ecosystem\n * package that implements one, and so a discoverer never has to derive\n * a path the runner already knows. Deriving `contentRoot` from\n * `directory` looks harmless but bakes in an invariant the runner does\n * not promise.\n */\nexport interface ProjectDiscoveryContext {\n  /** Absolute path of the discovered folder. */\n  readonly directory: string;\n  /**\n   * Absolute path of the content root the folder was found under: the\n   * project root, or its `src` when the project uses that layout. A\n   * sibling convention folder lives here.\n   */\n  readonly contentRoot: string;\n  /** Absolute path of the project root, where `craft.config.ts` lives. */\n  readonly projectRoot: string;\n  /**\n   * Configuration accumulated so far: the project's own\n   * `craft.config.ts` plus every fragment from a discoverer that ran\n   * earlier. Never mutated.\n   */\n  readonly config: Readonly<CraftConfig>;\n  /**\n   * The project's own configuration, before any discoverer contributed.\n   *\n   * This is the one that answers \"did the project declare this?\", which\n   * {@link config} cannot: by the time a later discoverer runs, an\n   * earlier one's fragment is indistinguishable from something the\n   * author wrote. Use it for precedence decisions and for reporting\n   * where a value came from; use `config` to see what is actually in\n   * effect.\n   */\n  readonly declared: Readonly<CraftConfig>;\n}\n\n/**\n * Turn a convention folder into a `CraftConfig` fragment.\n *\n * A project runner (`craft start`) walks the filesystem and knows which\n * folders exist; it does not know what the contents mean. A discoverer\n * supplies that meaning for one folder name, which is how `agents/` and\n * `skills/` are understood by `@routecraft/ai` without the CLI ever\n * depending on it.\n *\n * Two rules follow from being handed the accumulated config:\n *\n * - **Precedence is the discoverer's job.** Code wins and convention\n *   fills the gaps, so a discoverer inspects `ctx.config` and declines\n *   to produce anything the project already declared.\n * - **Return the contribution, not the base.** The merge preserves what\n *   is already there, so a fragment should carry only what the\n *   discoverer adds. Copying existing values back into the fragment is\n *   redundant and, for an array-valued field, duplicates entries.\n *\n * The return type is `Partial<CraftConfig>`, which is shallow: it\n * cannot express \"a partial value nested inside a record\". A fragment\n * that patches one entry of `agent.agents` is still a patch, and may\n * need a cast at the boundary. That is a limitation of the type, not\n * permission to return complete values you did not compute.\n */\nexport type ProjectDiscoverer = (\n  ctx: ProjectDiscoveryContext,\n) => Promise<Partial<CraftConfig>>;\n\n/**\n * Registration options for {@link registerProjectDiscoverer}.\n */\nexport interface ProjectDiscovererOptions {\n  /**\n   * Folder names whose fragments must already be in `ctx.config` when\n   * this discoverer runs. Declaring the dependency beats picking a\n   * number: it says which discoverer you need rather than where you\n   * hope to sit, and a third party can target a folder name without\n   * importing a constant it cannot see.\n   *\n   * Two edge semantics, both deliberate:\n   *\n   * - A name nobody registered is a **satisfied** constraint, not an\n   *   error. A discoverer that composes another's output when present\n   *   must still run when that package is absent.\n   * - A cycle is an **error**, raised by {@link getProjectDiscoverers},\n   *   because no run order can satisfy it and silently picking one\n   *   would make the outcome depend on import order.\n   */\n  after?: readonly string[];\n}\n\n/**\n * A discoverer as held by the registry.\n */\nexport interface RegisteredProjectDiscoverer {\n  /** Folder name, relative to the project's content root. */\n  readonly folder: string;\n  /** Folder names that must run before this one. */\n  readonly after: readonly string[];\n  /** The discoverer itself. */\n  readonly discover: ProjectDiscoverer;\n}\n\n/**\n * Cross-instance registry. `Symbol.for` so multiple copies of the\n * package in a workspace share a single registry; without this, a\n * discoverer registered by one package copy would be invisible to a\n * runner constructed from another copy.\n */\nconst REGISTRY_KEY: unique symbol = Symbol.for(\n  \"routecraft.project-discoverer-registry\",\n);\n\ntype GlobalWithRegistry = typeof globalThis & {\n  [REGISTRY_KEY]?: Map<string, RegisteredProjectDiscoverer>;\n};\n\nfunction getRegistry(): Map<string, RegisteredProjectDiscoverer> {\n  const g = globalThis as GlobalWithRegistry;\n  let registry = g[REGISTRY_KEY];\n  if (!registry) {\n    registry = new Map<string, RegisteredProjectDiscoverer>();\n    g[REGISTRY_KEY] = registry;\n  }\n  return registry;\n}\n\n/**\n * Register a discoverer for one convention folder.\n *\n * Ecosystem packages call this at module load time from a side-effect\n * import, the same way `registerConfigApplier` promotes a config key.\n * Registering the same folder twice replaces the previous\n * registration: last writer wins.\n *\n * Registration happens on **import**, which is worth stating plainly\n * because it is the failure mode users hit: a project whose\n * `craft.config.ts` only carries `import type { ... }` from the\n * package never registers anything, because a type-only import is\n * erased at compile time.\n *\n * @param folder - Folder name relative to the project's content root\n * @param discoverer - Builds a config fragment from that folder\n * @param options - Declared dependencies on other folders\n *\n * @example\n * ```typescript\n * registerProjectDiscoverer(\n *   \"agents\",\n *   async (ctx) => ({ agent: { agents: await load(ctx) } }),\n *   { after: [\"skills\"] },\n * );\n * ```\n */\nexport function registerProjectDiscoverer(\n  folder: string,\n  discoverer: ProjectDiscoverer,\n  options: ProjectDiscovererOptions = {},\n): void {\n  getRegistry().set(folder, {\n    folder,\n    after: options.after ?? [],\n    discover: discoverer,\n  });\n}\n\n/**\n * Get the registered discoverers in run order.\n *\n * Sorted so every declared `after` dependency runs first, with\n * registration order preserved between independent entries so the\n * result is stable. A dependency on a folder nobody registered is\n * satisfied by definition.\n *\n * @throws RC5003 when the declared dependencies form a cycle.\n */\nexport function getProjectDiscoverers(): readonly RegisteredProjectDiscoverer[] {\n  const registered = getRegistry();\n  const pending = [...registered.values()];\n  const out: RegisteredProjectDiscoverer[] = [];\n  const done = new Set<string>();\n\n  // Kahn rather than a depth-first walk: emitting a dependency the\n  // moment it is reached would hoist it above independent discoverers\n  // that registered earlier, so an unrelated registration could reorder\n  // two entries that have nothing to do with each other, and ordering\n  // here decides which fragment merges over which. Repeatedly taking\n  // the earliest-registered entry whose dependencies have all run keeps\n  // registration order as the only tiebreak.\n  while (pending.length > 0) {\n    const index = pending.findIndex((entry) =>\n      entry.after.every(\n        // A dependency nobody registered is satisfied: the package that\n        // would have claimed the folder simply is not installed.\n        (folder) => !registered.has(folder) || done.has(folder),\n      ),\n    );\n    if (index === -1) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `Project discoverers form a dependency cycle among: ${cycleMembers(\n          pending,\n        ).join(\n          \", \",\n        )}. One of the \"after\" declarations has to go; no run order can satisfy a cycle.`,\n      });\n    }\n    const [entry] = pending.splice(index, 1) as [RegisteredProjectDiscoverer];\n    done.add(entry.folder);\n    out.push(entry);\n  }\n  return out;\n}\n\n/**\n * Narrow a deadlocked set to the folders actually on a cycle.\n *\n * Everything still pending when the sort deadlocks is blocked, but most\n * of it may be blocked merely by sitting downstream of the cycle. Naming\n * those in the error sends the reader hunting through `after`\n * declarations that are perfectly fine.\n *\n * A folder is on a cycle exactly when it can reach itself by following\n * `after` edges, which is the definition rather than an approximation of\n * it: peeling away entries nothing depends on looks equivalent but keeps\n * a bridge between two separate cycles, and that bridge is innocent.\n *\n * @internal\n */\nfunction cycleMembers(\n  pending: readonly RegisteredProjectDiscoverer[],\n): string[] {\n  const byFolder = new Map(pending.map((entry) => [entry.folder, entry]));\n  const reaches = (\n    from: string,\n    target: string,\n    seen: Set<string>,\n  ): boolean => {\n    if (seen.has(from)) return false;\n    seen.add(from);\n    const entry = byFolder.get(from);\n    if (!entry) return false;\n    return entry.after.some(\n      (folder) => folder === target || reaches(folder, target, seen),\n    );\n  };\n  return pending\n    .filter((entry) => reaches(entry.folder, entry.folder, new Set()))\n    .map((entry) => entry.folder)\n    .sort();\n}\n\n/**\n * True for objects the merge is allowed to recurse into: object\n * literals and null-prototype records. Class instances, arrays, and\n * functions are values, not shapes to combine.\n *\n * An object carrying own symbol keys is also treated as a value. Those\n * keys are how the framework brands cross-instance types (a\n * `ToolSelection` is an object literal with a `Symbol.for` brand), and\n * a rebuilt copy would be a different thing wearing the same shape.\n */\nfunction isMergeableRecord(value: unknown): value is Record<string, unknown> {\n  if (typeof value !== \"object\" || value === null) return false;\n  const proto = Object.getPrototypeOf(value) as object | null;\n  if (proto !== Object.prototype && proto !== null) return false;\n  return Object.getOwnPropertySymbols(value).length === 0;\n}\n\n/**\n * Merge a discoverer's fragment into a configuration and return a new\n * object. Neither input is mutated.\n *\n * Rules, in order:\n *\n * 1. An `undefined` value in the fragment is ignored, so a discoverer\n *    that produces nothing can return `{}` or omit the key.\n * 2. Two plain objects merge recursively. This is what puts a\n *    discovered agent beside a config-declared one instead of\n *    replacing the whole map.\n * 3. Two arrays concatenate, base first, which is how a discovered\n *    plugin joins the ones the project declared.\n * 4. Anything else: the fragment's value replaces the base's.\n *\n * Rule 4 is the reason precedence lives in the discoverer rather than\n * here. The merge cannot tell an intentional override from an\n * accidental one; the discoverer can, because it is handed the config\n * before it decides what to return.\n */\nexport function mergeProjectConfig(\n  base: CraftConfig,\n  fragment: Partial<CraftConfig>,\n): CraftConfig {\n  return mergeRecords(\n    base as Record<string, unknown>,\n    fragment as Record<string, unknown>,\n  ) as CraftConfig;\n}\n\n/**\n * Write a key without going through a setter. `out[key] = value` would\n * hit `Object.prototype.__proto__` for a key of that name, silently\n * dropping the entry and changing the object's prototype; the spread\n * that seeded `out` defines it as a real own property, so the two\n * halves of this function have to agree.\n */\nfunction define(\n  target: Record<string | symbol, unknown>,\n  key: string | symbol,\n  value: unknown,\n): void {\n  Object.defineProperty(target, key, {\n    value,\n    writable: true,\n    enumerable: true,\n    configurable: true,\n  });\n}\n\nfunction mergeRecords(\n  base: Record<string, unknown>,\n  fragment: Record<string, unknown>,\n): Record<string, unknown> {\n  // Spread and `Reflect.ownKeys` rather than `Object.entries` so own\n  // symbol keys survive on both sides; see isMergeableRecord.\n  const out: Record<string, unknown> = { ...base };\n  const target = out as Record<string | symbol, unknown>;\n  for (const key of Reflect.ownKeys(fragment) as Array<string | symbol>) {\n    const value = (fragment as Record<string | symbol, unknown>)[key];\n    if (value === undefined) continue;\n    const current = target[key];\n    if (isMergeableRecord(current) && isMergeableRecord(value)) {\n      define(target, key, mergeRecords(current, value));\n    } else if (Array.isArray(current) && Array.isArray(value)) {\n      define(target, key, [...current, ...value]);\n    } else {\n      define(target, key, value);\n    }\n  }\n  return out;\n}\n","import type { CraftContext, CraftPlugin } from \"../../context.ts\";\nimport { rcError } from \"../../error.ts\";\nimport { type Duration, parseDuration } from \"../../shared/duration.ts\";\nimport { startServer, type HttpServerHandle } from \"../http/server/index.ts\";\nimport { HttpMountRegistry, WEB_INGRESSES } from \"./registry.ts\";\nimport { resolveAllowedHostnames } from \"./request-validation.ts\";\nimport type { ServerDefinitions } from \"./types.ts\";\n\nconst DEFAULT_HOST = \"127.0.0.1\";\nconst DEFAULT_SHUTDOWN_GRACE_MS = 30_000;\n/**\n * Bun's ceiling for a per-connection idle timeout, and therefore ours on\n * every runtime: a value only one runtime can honour is a config that means\n * different things depending on where it runs.\n */\nconst MAX_IDLE_TIMEOUT_MS = 255_000;\n\n/**\n * Resolve one server's `shutdownGrace` to milliseconds, defaulting when it is\n * unset. `0` is legal here (close the listener immediately), which is why the\n * floor is 0 rather than the deadline default of 1.\n *\n * @param name - Server name, quoted in the refusal so a multi-server config\n *   says which entry is wrong.\n */\nfunction resolveShutdownGrace(\n  name: string,\n  grace: Duration | undefined,\n): number {\n  if (grace === undefined) return DEFAULT_SHUTDOWN_GRACE_MS;\n  return parseDuration(grace, `servers.${name}.shutdownGrace`, 0);\n}\n\n/**\n * Resolve one server's `idleTimeout` to milliseconds.\n *\n * Refused above Bun's ceiling rather than clamped. Silently honouring 600s on\n * Node while capping it at 255s on Bun would make the same config behave\n * differently by runtime, which is the failure the never-degrade rule exists\n * to prevent. The floor is 1: an idle timeout of zero would reap every\n * connection the moment it went quiet.\n */\nfunction resolveIdleTimeout(\n  name: string,\n  idleTimeout: Duration | undefined,\n): number {\n  if (idleTimeout === undefined) return MAX_IDLE_TIMEOUT_MS;\n  const ms = parseDuration(idleTimeout, `servers.${name}.idleTimeout`, 1);\n  if (ms > MAX_IDLE_TIMEOUT_MS) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        `servers.${name}.idleTimeout is ${ms}ms, above the ${MAX_IDLE_TIMEOUT_MS}ms (255s) ceiling Bun enforces on a per-connection idle timeout. ` +\n        `Streaming responses are exempt from the reaper and bounded by servers.${name}.maxStreamingRequests instead, so a longer idle timeout is rarely what is wanted.`,\n    });\n  }\n  return ms;\n}\n\n/** Refuse a cap that cannot bound anything. */\nfunction resolveMaxStreamingRequests(\n  name: string,\n  max: number | undefined,\n): number | undefined {\n  if (max === undefined) return undefined;\n  if (!Number.isInteger(max) || max < 1) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `servers.${name}.maxStreamingRequests must be a positive integer; received ${JSON.stringify(max)}.`,\n    });\n  }\n  return max;\n}\n\nasync function closeServer(\n  handle: HttpServerHandle,\n  graceMs: number,\n): Promise<void> {\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  try {\n    const deadline = new Promise<\"deadline\">((resolve) => {\n      timer = setTimeout(() => resolve(\"deadline\"), graceMs);\n      // The grace timer must never itself hold the process open.\n      (timer as { unref?: () => void }).unref?.();\n    });\n    const outcome = await Promise.race([\n      handle.gracefulClose().then(\n        () => \"closed\" as const,\n        // A rejecting graceful close is a failed graceful close, not a\n        // reason to skip the force path and leave the listener running.\n        () => \"graceful-failed\" as const,\n      ),\n      deadline,\n    ]);\n    if (outcome !== \"closed\") await handle.forceClose();\n  } finally {\n    // finally, not inline: a rejecting gracefulClose must not leave the\n    // timer pending for the rest of the grace period.\n    if (timer !== undefined) clearTimeout(timer);\n  }\n}\n\ninterface ServerState {\n  registries: Map<string, HttpMountRegistry>;\n  handles: Map<string, HttpServerHandle>;\n  /** Set at teardown entry so a bind racing stop() closes itself. */\n  closed: boolean;\n  /** In-flight start(), awaited by teardown so stop() cannot resolve while a raced bind is still open. */\n  starting?: Promise<void>;\n}\n\nexport function serversPlugin(definitions: ServerDefinitions): CraftPlugin {\n  validateDefinitions(definitions);\n  const states = new WeakMap<CraftContext, ServerState>();\n\n  return {\n    name: \"servers\",\n    keepsAlive: true,\n    apply(ctx) {\n      const registries = new Map<string, HttpMountRegistry>();\n      for (const name of Object.keys(definitions)) {\n        registries.set(\n          name,\n          new HttpMountRegistry(\n            name,\n            ctx,\n            definitions[name]?.auth,\n            resolveMaxStreamingRequests(\n              name,\n              definitions[name]?.maxStreamingRequests,\n            ),\n            definitions[name]?.allowedHostnames,\n          ),\n        );\n      }\n      states.set(ctx, { registries, handles: new Map(), closed: false });\n      ctx.setStore(WEB_INGRESSES, registries);\n    },\n    async start(ctx) {\n      const state = states.get(ctx);\n      if (!state) return;\n      const boot = bindAll(ctx, state);\n      state.starting = boot;\n      await boot;\n    },\n    async teardown(ctx) {\n      const state = states.get(ctx);\n      if (!state) return;\n      state.closed = true;\n      // A raced start() closes its own in-flight bind on seeing `closed`;\n      // waiting for it here keeps stop() from resolving while that listener\n      // is still open. Its failure is the start path's to report.\n      await state.starting?.catch(() => {});\n      for (const [name, handle] of [...state.handles].reverse()) {\n        try {\n          await closeServer(\n            handle,\n            resolveShutdownGrace(name, definitions[name]?.shutdownGrace),\n          );\n          ctx.logger.info({ server: name }, \"Server closed\");\n          ctx.emit(\"server:closed\", { server: name });\n        } catch (error) {\n          ctx.logger.warn(\n            { err: error, server: name },\n            \"Named server failed to close cleanly\",\n          );\n        }\n      }\n      states.delete(ctx);\n    },\n  };\n\n  async function bindAll(ctx: CraftContext, state: ServerState): Promise<void> {\n    assertEveryServerMounted(state.registries);\n    for (const registry of state.registries.values()) registry.validate();\n    for (const [name, definition] of Object.entries(definitions)) {\n      const registry = state.registries.get(name)!;\n      const host = definition.host ?? DEFAULT_HOST;\n      let handle: HttpServerHandle;\n      try {\n        handle = await startServer({\n          host,\n          port: definition.port,\n          idleTimeoutMs: resolveIdleTimeout(name, definition.idleTimeout),\n          fetch: (request, runtime) => registry.dispatch(request, runtime),\n          logger: ctx.logger,\n        });\n      } catch (error) {\n        ctx.emit(\"server:failed\", { server: name, error });\n        throw rcError(\"RC5019\", error, {\n          message: `servers.${name}: bind failed on ${host}:${definition.port}: ${error instanceof Error ? error.message : String(error)}`,\n        });\n      }\n      // A stop() arriving while the bind above was in flight has already\n      // run teardown past this server; record nothing and close the fresh\n      // handle here or it leaks with nothing left to ever close it.\n      if (state.closed) {\n        await closeServer(\n          handle,\n          resolveShutdownGrace(name, definition.shutdownGrace),\n        );\n        return;\n      }\n      state.handles.set(name, handle);\n      registry.setBoundAddress(host, handle.port);\n      ctx.logger.info(\n        { server: name, host, port: handle.port },\n        \"Server listening\",\n      );\n      ctx.emit(\"server:listening\", { server: name, host, port: handle.port });\n    }\n  }\n}\n\n/**\n * Refuse declared servers that nothing mounted on, naming the whole mount\n * topology in the message.\n *\n * The check lives here rather than on the registry because a registry only\n * knows its own mounts, and the fact a reader needs is the one it cannot\n * see: what mounted somewhere else. An empty server almost always means the\n * surface meant for it never mounted (a plugin that failed to apply, a\n * misspelt server name, or a plugin predating named servers), and the mount\n * list is what makes that visible at a glance. Every empty server is\n * reported at once so an app declaring several does not learn about them one\n * boot at a time.\n */\nfunction assertEveryServerMounted(\n  registries: ReadonlyMap<string, HttpMountRegistry>,\n): void {\n  const empty: string[] = [];\n  const mounted: string[] = [];\n  for (const [name, registry] of registries) {\n    const ids = registry.mountIds();\n    if (ids.length === 0) {\n      empty.push(name);\n      continue;\n    }\n    for (const id of ids) mounted.push(`${id} -> servers.${name}`);\n  }\n  if (empty.length === 0) return;\n  const subject =\n    empty.length === 1\n      ? `servers.${empty[0]}: server has no mounts.`\n      : `servers: ${empty.map((name) => `\"${name}\"`).join(\", \")} have no mounts.`;\n  const topology =\n    mounted.length > 0\n      ? ` Mounted surfaces: ${mounted.join(\", \")}.`\n      : \" No surface mounted on any server.\";\n  throw rcError(\"RC5003\", undefined, {\n    message:\n      `${subject}${topology} Either remove the unused ${empty.length === 1 ? \"server\" : \"servers\"}, or bind a surface to ${empty.length === 1 ? \"it\" : \"them\"}. ` +\n      \"A surface that names the server in config but did not mount is usually a plugin that failed to apply, a misspelt server name, or a plugin version that predates named servers.\",\n  });\n}\n\nfunction validateDefinitions(definitions: ServerDefinitions): void {\n  const entries = Object.entries(definitions);\n  if (entries.length === 0) {\n    throw rcError(\"RC5003\", undefined, {\n      message: \"servers: define at least one named server\",\n    });\n  }\n  const binds = new Map<string, string>();\n  for (const [name, definition] of entries) {\n    if (!name) {\n      throw rcError(\"RC5003\", undefined, {\n        message: \"servers: names must not be empty\",\n      });\n    }\n    if (definition.kind !== undefined && definition.kind !== \"http\") {\n      throw rcError(\"RC5003\", undefined, {\n        message: `servers.${name}: unsupported kind ${JSON.stringify(definition.kind)}. Supported: \"http\".`,\n      });\n    }\n    if (\n      !Number.isInteger(definition.port) ||\n      definition.port < 0 ||\n      definition.port > 65535\n    ) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `servers.${name}: invalid port ${String(definition.port)}`,\n      });\n    }\n    try {\n      resolveAllowedHostnames(definition.allowedHostnames);\n    } catch (error) {\n      throw rcError(\"RC5003\", error, {\n        message: `servers.${name}.allowedHostnames: ${error instanceof Error ? error.message : String(error)}`,\n      });\n    }\n    resolveShutdownGrace(name, definition.shutdownGrace);\n    resolveIdleTimeout(name, definition.idleTimeout);\n    resolveMaxStreamingRequests(name, definition.maxStreamingRequests);\n    const host = (definition.host ?? DEFAULT_HOST).toLowerCase();\n    const key = `${host}:${definition.port}`;\n    const existing = binds.get(key);\n    if (existing) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `servers.${name}: duplicate bind ${key}, already declared by servers.${existing}`,\n      });\n    }\n    if (definition.port !== 0) binds.set(key, name);\n  }\n}\n","import { rcError } from \"../../../error\";\nimport { startNodeServer, type NodeServerHandle } from \"./node\";\n\n/**\n * Common handle returned by {@link startServer}. Implementations on Bun and\n * Node both satisfy this; callers do not need to know which runtime is\n * powering the listener.\n */\nexport interface HttpServerHandle {\n  readonly port: number;\n  gracefulClose(): Promise<void>;\n  forceClose(): Promise<void>;\n}\n\n/**\n * Per-request capabilities the runtime listener hands the dispatcher.\n * `exemptFromIdleTimeout` lifts the listener's idle timeout for one request\n * so a long-lived stream (MCP streamable HTTP, SSE) can stay quiet\n * indefinitely while ordinary connections keep being reaped. A no-op on\n * Node, whose timeouts do not govern response streaming.\n */\nexport interface HttpServerRuntime {\n  exemptFromIdleTimeout(req: Request): void;\n}\n\nexport interface StartServerOptions {\n  port: number;\n  host: string;\n  /** Idle reap window in milliseconds. Bun's ceiling (255s) is enforced by the caller. */\n  idleTimeoutMs?: number;\n  fetch: (req: Request, runtime: HttpServerRuntime) => Promise<Response>;\n  /** Receives startup warnings (e.g. a Bun too old for per-request timeout exemptions). */\n  logger?: {\n    warn(details: Record<string, unknown>, message: string): void;\n  };\n}\n\ninterface BunServeHandle {\n  readonly port: number;\n  stop(closeActiveConnections?: boolean): Promise<void> | void;\n  /** Per-request idle timeout override; 0 disables it for that request. */\n  timeout?(req: Request, seconds: number): void;\n}\n\ninterface BunLike {\n  serve(opts: {\n    port: number;\n    hostname: string;\n    idleTimeout: number;\n    fetch: (\n      req: Request,\n      server: BunServeHandle,\n    ) => Promise<Response> | Response;\n  }): BunServeHandle;\n}\n\nfunction getBun(): BunLike | undefined {\n  const candidate = (globalThis as { Bun?: BunLike }).Bun;\n  if (candidate && typeof candidate.serve === \"function\") {\n    return candidate;\n  }\n  return undefined;\n}\n\n/**\n * Bind a Web-standard fetch handler to a port. Picks the Bun-native path\n * when `globalThis.Bun.serve` exists, else falls back to the `node:http`\n * shim. Throws `RC5019` if the port cannot be bound.\n */\nexport async function startServer(\n  opts: StartServerOptions,\n): Promise<HttpServerHandle> {\n  const bun = getBun();\n  if (bun) {\n    try {\n      const server = bun.serve({\n        port: opts.port,\n        hostname: opts.host,\n        // Seconds on Bun's side, and 0 is its \"never reap\" sentinel, which\n        // would let idle sockets accumulate to the fd limit and hold\n        // graceful close open. Hence the floor: a sub-second configured\n        // value rounds to 0. Long-lived quiet streams survive via the\n        // per-request exemption below, not by widening this.\n        idleTimeout: Math.max(\n          1,\n          Math.round((opts.idleTimeoutMs ?? 255_000) / 1000),\n        ),\n        fetch: (req, bunServer) =>\n          opts.fetch(req, {\n            // Lift the idle timeout for one request only: mounts that\n            // declare long-lived streams (MCP, SSE) opt their requests out\n            // while every other connection keeps being reaped.\n            exemptFromIdleTimeout: (r) => bunServer.timeout?.(r, 0),\n          }),\n      });\n      // Bun before 1.1.27 has no per-request timeout override, so quiet\n      // long-lived streams get reaped at the listener default with no\n      // exemption possible. Say so at bind instead of failing silently.\n      if (typeof server.timeout !== \"function\") {\n        opts.logger?.warn(\n          { host: opts.host, port: server.port },\n          \"This Bun version lacks per-request timeout overrides (added in 1.1.27); long-lived streams (MCP, SSE) will be cut at the idle timeout. Upgrade Bun to exempt them.\",\n        );\n      }\n      return {\n        port: server.port,\n        gracefulClose: async () => {\n          await server.stop(false);\n        },\n        forceClose: async () => {\n          await server.stop(true);\n        },\n      };\n    } catch (err) {\n      throw rcError(\"RC5019\", err, {\n        message: `HTTP server bind failed on ${opts.host}:${opts.port}: ${err instanceof Error ? err.message : String(err)}`,\n      });\n    }\n  }\n\n  const handle: NodeServerHandle = await startNodeServer(opts);\n  return handle;\n}\n","import {\n  createServer,\n  type IncomingMessage,\n  type ServerResponse,\n} from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport type { AddressInfo } from \"node:net\";\nimport { rcError } from \"../../../error\";\nimport type { HttpServerRuntime } from \"./index.ts\";\n\nexport interface NodeServerHandle {\n  /** Resolved port (useful when `port: 0` is passed to let the OS choose). */\n  readonly port: number;\n  /** Stop accepting new connections and wait for in-flight requests to complete. */\n  gracefulClose(): Promise<void>;\n  forceClose(): Promise<void>;\n}\n\nexport interface NodeServerOptions {\n  port: number;\n  host: string;\n  /** Web-standard fetch handler. */\n  fetch: (req: Request, runtime: HttpServerRuntime) => Promise<Response>;\n}\n\n/** Node timeouts do not govern response streaming, so the exemption is inert. */\nconst NODE_RUNTIME: HttpServerRuntime = {\n  exemptFromIdleTimeout: () => {},\n};\n\n/**\n * Bridge Node's `http.createServer` into a Web-standard `(Request) => Response`\n * handler. Used on Node 22+ where `Bun.serve` is not available.\n *\n * The shim covers the surface our dispatcher needs:\n *   - Convert IncomingMessage to a Web Request (headers, method, body stream).\n *   - Convert the Response back (status, headers, body stream).\n *   - Surface bind failures as `RC5019`.\n *\n * Anything outside that scope (HTTP/2, TLS, request timeouts, raw socket\n * access) is deliberately not bridged.\n */\nexport function startNodeServer(\n  opts: NodeServerOptions,\n): Promise<NodeServerHandle> {\n  return new Promise((resolve, reject) => {\n    const server = createServer((req, res) => {\n      void handle(opts.fetch, req, res, opts.host);\n    });\n\n    const onError = (err: Error): void => {\n      reject(\n        rcError(\"RC5019\", err, {\n          message: `HTTP server bind failed on ${opts.host}:${opts.port}: ${err.message}`,\n        }),\n      );\n    };\n    server.once(\"error\", onError);\n    server.listen(opts.port, opts.host, () => {\n      server.off(\"error\", onError);\n      // Re-attach a softer error handler so runtime errors after bind are\n      // logged but do not crash the process.\n      server.on(\"error\", () => {\n        // Intentionally swallowed; per-request errors land on the request\n        // path which converts them to 5xx responses.\n      });\n\n      const address = server.address() as AddressInfo | null;\n      const resolvedPort = address?.port ?? opts.port;\n      // One close() call, shared between both close modes: `forceClose` after\n      // a timed-out `gracefulClose` would otherwise call close() a second\n      // time and reject with ERR_SERVER_NOT_RUNNING even though the force\n      // path did exactly its job.\n      let closed: Promise<void> | undefined;\n      const requestClose = (): Promise<void> => {\n        closed ??= new Promise<void>((res, rej) => {\n          server.close((err) =>\n            err &&\n            (err as NodeJS.ErrnoException).code !== \"ERR_SERVER_NOT_RUNNING\"\n              ? rej(err)\n              : res(),\n          );\n        });\n        return closed;\n      };\n      resolve({\n        port: resolvedPort,\n        gracefulClose: () => {\n          const done = requestClose();\n          // Deferred keep-alive sockets hold close() open forever; reap them so\n          // the grace window only covers genuinely in-flight requests.\n          server.closeIdleConnections();\n          return done;\n        },\n        forceClose: () => {\n          server.closeAllConnections();\n          return requestClose();\n        },\n      });\n    });\n  });\n}\n\nasync function handle(\n  fetchHandler: NodeServerOptions[\"fetch\"],\n  nReq: IncomingMessage,\n  nRes: ServerResponse,\n  fallbackHost: string,\n): Promise<void> {\n  try {\n    const abort = new AbortController();\n    const onAborted = () => abort.abort(new Error(\"Client disconnected\"));\n    nReq.once(\"aborted\", onAborted);\n    nRes.once(\"close\", () => {\n      if (!nRes.writableEnded) onAborted();\n    });\n    const webReq = toWebRequest(nReq, fallbackHost, abort.signal);\n    const webRes = await fetchHandler(webReq, NODE_RUNTIME);\n    await writeNodeResponse(nRes, webRes, abort.signal);\n  } catch {\n    // The dispatcher is responsible for normalising everything to a Response;\n    // anything that escapes is a bug we still need to answer for. Emit a 500\n    // with a tiny body so the client always gets a closed response.\n    if (!nRes.headersSent) {\n      nRes.statusCode = 500;\n      nRes.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n    }\n    try {\n      nRes.end(\"Internal Server Error\");\n    } catch {\n      nRes.destroy();\n    }\n  }\n}\n\nfunction toWebRequest(\n  req: IncomingMessage,\n  fallbackHost: string,\n  signal: AbortSignal,\n): Request {\n  const host = req.headers.host ?? fallbackHost;\n  // `req.url` is always a path-and-query when received by an HTTP server.\n  const url = new URL(req.url ?? \"/\", `http://${host}`);\n\n  const headers = new Headers();\n  for (const [name, value] of Object.entries(req.headers)) {\n    if (value === undefined) continue;\n    if (Array.isArray(value)) {\n      for (const v of value) headers.append(name, v);\n    } else {\n      headers.set(name, value);\n    }\n  }\n\n  const method = (req.method ?? \"GET\").toUpperCase();\n  const hasBody = method !== \"GET\" && method !== \"HEAD\";\n  const init: RequestInit = { method, headers, signal };\n  if (hasBody) {\n    // Readable.toWeb returns ReadableStream<any>; the Request constructor\n    // wants ReadableStream<Uint8Array>. Cast through unknown so TS does not\n    // complain about variance on the chunk type.\n    init.body = Readable.toWeb(req) as unknown as ReadableStream<Uint8Array>;\n    // Node's fetch Request requires `duplex: \"half\"` when constructed with a\n    // stream body. The field is not yet on the standard RequestInit so we\n    // attach it via a cast.\n    (init as RequestInit & { duplex: \"half\" }).duplex = \"half\";\n  }\n  return new Request(url.toString(), init);\n}\n\nasync function writeNodeResponse(\n  nRes: ServerResponse,\n  webRes: Response,\n  signal: AbortSignal,\n): Promise<void> {\n  nRes.statusCode = webRes.status;\n  if (webRes.statusText) nRes.statusMessage = webRes.statusText;\n  webRes.headers.forEach((value, key) => {\n    // Set-Cookie is handled separately below; forEach joins multiple values\n    // with \", \" which is wrong for cookie headers (cookie values can contain\n    // \", \" themselves and the Vary semantics differ).\n    if (key.toLowerCase() === \"set-cookie\") return;\n    nRes.setHeader(key, value);\n  });\n  // getSetCookie() returns each cookie as a separate string, preserving the\n  // boundary between distinct Set-Cookie fields (Node 20+, Bun 1+).\n  const cookies =\n    typeof webRes.headers.getSetCookie === \"function\"\n      ? webRes.headers.getSetCookie()\n      : [];\n  if (cookies.length > 0) {\n    nRes.setHeader(\"Set-Cookie\", cookies);\n  }\n\n  if (!webRes.body) {\n    nRes.end();\n    return;\n  }\n\n  const reader = webRes.body.getReader();\n  const onAbort = () => {\n    void reader.cancel(signal.reason);\n    nRes.destroy();\n  };\n  // The client may have disconnected while the fetch handler was still\n  // running; a listener added now would never fire, so cancel directly.\n  if (signal.aborted) {\n    onAbort();\n    return;\n  }\n  signal.addEventListener(\"abort\", onAbort, { once: true });\n  try {\n    for (;;) {\n      const { done, value } = await reader.read();\n      if (done) break;\n      if (value) {\n        if (!nRes.write(value)) {\n          // \"drain\" never fires on a destroyed response, so a disconnect\n          // mid-backpressure must also settle this wait or the request\n          // promise defers until force-close.\n          const resumed = await new Promise<\"drain\" | \"closed\">((resolve) => {\n            const onDrain = (): void => {\n              cleanup();\n              resolve(\"drain\");\n            };\n            const onClose = (): void => {\n              cleanup();\n              resolve(\"closed\");\n            };\n            const cleanup = (): void => {\n              nRes.off(\"drain\", onDrain);\n              nRes.off(\"close\", onClose);\n            };\n            nRes.once(\"drain\", onDrain);\n            nRes.once(\"close\", onClose);\n          });\n          if (resumed === \"closed\") {\n            void reader.cancel(new Error(\"Client disconnected\"));\n            break;\n          }\n        }\n      }\n    }\n  } finally {\n    signal.removeEventListener(\"abort\", onAbort);\n    if (!signal.aborted && !nRes.destroyed) nRes.end();\n  }\n}\n","import type { HttpMount } from \"./types.ts\";\n\n/** Parse an HTTP authority without accepting URL paths, userinfo or escapes. */\nfunction hostnameOf(authority: string): string | undefined {\n  if (\n    !/^(?:\\[[0-9a-fA-F:.]+\\]|[a-zA-Z0-9._-]+)(?::[0-9]{1,5})?$/.test(authority)\n  ) {\n    return undefined;\n  }\n  try {\n    return new URL(`http://${authority}`).hostname\n      .toLowerCase()\n      .replace(/\\.$/, \"\");\n  } catch {\n    return undefined;\n  }\n}\n\n/** Validate and snapshot explicitly trusted hostnames at construction. */\nexport function resolveAllowedHostnames(\n  input: readonly string[] | undefined,\n): ReadonlySet<string> {\n  if (input !== undefined && !Array.isArray(input)) {\n    throw new TypeError(\"allowedHostnames must be an array of hostnames\");\n  }\n  return new Set(\n    (input ?? []).map((name) => {\n      if (typeof name !== \"string\") {\n        throw new TypeError(\n          \"allowedHostnames entries must be hostnames without a scheme, path or port\",\n        );\n      }\n      const authority =\n        name.includes(\":\") && !name.startsWith(\"[\") ? `[${name}]` : name;\n      const hostname = hostnameOf(authority);\n      if (\n        hostname === undefined ||\n        (!authority.endsWith(\"]\") && authority.includes(\":\"))\n      ) {\n        throw new TypeError(\n          \"allowedHostnames entries must be hostnames without a scheme, path or port\",\n        );\n      }\n      return hostname;\n    }),\n  );\n}\n\n/** Only serialized HTTP(S) origins are browser-admission identities. */\nfunction isBrowserOrigin(origin: string): boolean {\n  try {\n    const url = new URL(origin);\n    return (\n      (url.protocol === \"http:\" || url.protocol === \"https:\") &&\n      url.origin === origin\n    );\n  } catch {\n    return false;\n  }\n}\n\nexport interface ResolvedRequestValidation {\n  readonly allowedHostnames: ReadonlySet<string>;\n  readonly browserOrigins: ReadonlySet<string>;\n}\n\n/** Browser access is denied unless a mount explicitly names the origins. */\nexport function resolveRequestValidation(\n  options: NonNullable<HttpMount[\"requestValidation\"]>,\n): ResolvedRequestValidation {\n  if (\n    options.browserOrigins !== undefined &&\n    !Array.isArray(options.browserOrigins)\n  ) {\n    throw new TypeError(\"browserOrigins must be an array of HTTP(S) origins\");\n  }\n  const origins = options.browserOrigins ?? [];\n  for (const origin of origins) {\n    if (typeof origin !== \"string\" || !isBrowserOrigin(origin)) {\n      throw new TypeError(\n        \"browserOrigins entries must be exact HTTP(S) origins without a path, wildcard or credentials\",\n      );\n    }\n  }\n  return {\n    allowedHostnames: resolveAllowedHostnames(options.allowedHostnames),\n    browserOrigins: new Set(origins),\n  };\n}\n\nconst LOOPBACK = [\"localhost\", \"127.0.0.1\", \"[::1]\"];\nconst LOCAL_BINDS = new Set([...LOOPBACK, \"0.0.0.0\", \"[::]\"]);\n\n/**\n * One protocol ingress gate, independent of CORS and authentication.\n * Forwarding headers and the request URL never contribute trusted names.\n */\nexport function requestValidationFailure(\n  request: Request,\n  boundHost: string | undefined,\n  serverHostnames: ReadonlySet<string>,\n  policy: ResolvedRequestValidation,\n): \"host\" | \"origin\" | undefined {\n  const host = hostnameOf(request.headers.get(\"host\") ?? \"\");\n  const bound =\n    boundHost === undefined\n      ? undefined\n      : hostnameOf(\n          boundHost.includes(\":\") && !boundHost.startsWith(\"[\")\n            ? `[${boundHost}]`\n            : boundHost,\n        );\n  if (\n    host === undefined ||\n    !(\n      host === bound ||\n      serverHostnames.has(host) ||\n      policy.allowedHostnames.has(host) ||\n      (bound !== undefined && LOCAL_BINDS.has(bound) && LOOPBACK.includes(host))\n    )\n  )\n    return \"host\";\n\n  const origin = request.headers.get(\"origin\");\n  if (\n    origin !== null &&\n    (!isBrowserOrigin(origin) || !policy.browserOrigins.has(origin))\n  ) {\n    return \"origin\";\n  }\n  return undefined;\n}\n","import {\n  requestValidationFailure,\n  resolveAllowedHostnames,\n  resolveRequestValidation,\n  type ResolvedRequestValidation,\n} from \"./request-validation.ts\";\nimport type { CraftContext } from \"../../context.ts\";\nimport { rcError } from \"../../error.ts\";\nimport type { HttpServerRuntime } from \"../http/server/index.ts\";\nimport type { HttpAuth, HttpMethod } from \"../../adapters/http/types.ts\";\nimport type {\n  HttpMount,\n  HttpMountAuth,\n  HttpMountAuthPolicy,\n  PathClaim,\n  WebIngress,\n} from \"./types.ts\";\nimport type { ValidatorAuthOptions } from \"../../auth/types.ts\";\nimport {\n  createAuthMiddleware,\n  type AuthResult,\n  type HttpAuthMiddleware,\n} from \"../http/auth.ts\";\nimport {\n  buildProtectedResourceMetadata,\n  PROTECTED_RESOURCE_METADATA_PATH,\n} from \"./protected-resource.ts\";\n\nexport const WEB_INGRESSES: unique symbol = Symbol.for(\n  \"routecraft.plugin.server.web-ingresses\",\n);\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [WEB_INGRESSES]: ReadonlyMap<string, WebIngress>;\n  }\n}\n\nconst ALL_METHODS: readonly HttpMethod[] = [\n  \"GET\",\n  \"POST\",\n  \"PUT\",\n  \"PATCH\",\n  \"DELETE\",\n  \"HEAD\",\n  \"OPTIONS\",\n];\n\nfunction methodsOf(claim: PathClaim): readonly HttpMethod[] {\n  return claim.kind === \"prefix\" ? ALL_METHODS : (claim.methods ?? ALL_METHODS);\n}\n\nfunction methodsOverlap(a: PathClaim, b: PathClaim): boolean {\n  const right = new Set(methodsOf(b));\n  return methodsOf(a).some((method) => right.has(method));\n}\n\nfunction prefixContains(prefix: string, path: string): boolean {\n  if (prefix === \"/\") return true;\n  return path === prefix || path.startsWith(`${prefix}/`);\n}\n\nfunction patternsOverlap(left: string, right: string): boolean {\n  const a = left.replace(/\\/+$/, \"\").split(\"/\").filter(Boolean);\n  const b = right.replace(/\\/+$/, \"\").split(\"/\").filter(Boolean);\n  if (a.length !== b.length) return false;\n  return a.every((segment, index) => {\n    const other = b[index]!;\n    return (\n      segment.startsWith(\":\") || other.startsWith(\":\") || segment === other\n    );\n  });\n}\n\n/**\n * A pattern has a fixed segment count, so it reaches into a prefix claim only\n * when it is at least as deep as the prefix and its leading segments can\n * match the prefix's literals. Comparing on the pattern's static prefix alone\n * would flag `/api/:id` against the disjoint mount `/api/v1/deep`, and a\n * literal root route (static prefix `/`) against every mount.\n */\nfunction patternOverlapsPrefix(pattern: string, prefixPath: string): boolean {\n  const patternSegments = pattern\n    .replace(/\\/+$/, \"\")\n    .split(\"/\")\n    .filter(Boolean);\n  const prefixSegments = prefixPath\n    .replace(/\\/+$/, \"\")\n    .split(\"/\")\n    .filter(Boolean);\n  if (patternSegments.length < prefixSegments.length) return false;\n  return prefixSegments.every((segment, index) => {\n    const candidate = patternSegments[index]!;\n    return candidate.startsWith(\":\") || candidate === segment;\n  });\n}\n\nfunction claimsOverlap(a: PathClaim, b: PathClaim): boolean {\n  if (!methodsOverlap(a, b)) return false;\n  if (a.kind === \"exact\" && b.kind === \"exact\") return a.path === b.path;\n  if (a.kind === \"exact\" && b.kind === \"pattern\") {\n    return b.matcher.match(a.path) !== null;\n  }\n  if (a.kind === \"pattern\" && b.kind === \"exact\") {\n    return a.matcher.match(b.path) !== null;\n  }\n  if (a.kind === \"exact\" && b.kind === \"prefix\") {\n    if (b.path === \"/\") return false;\n    return prefixContains(b.path, a.path);\n  }\n  if (a.kind === \"prefix\" && b.kind === \"exact\") {\n    if (a.path === \"/\") return false;\n    return prefixContains(a.path, b.path);\n  }\n  if (a.kind === \"prefix\" && b.kind === \"prefix\") {\n    if (a.path === \"/\" || b.path === \"/\") return false;\n    return prefixContains(a.path, b.path) || prefixContains(b.path, a.path);\n  }\n  if (a.kind === \"pattern\" && b.kind === \"prefix\") {\n    if (b.path === \"/\") return false;\n    return patternOverlapsPrefix(a.matcher.pattern, b.path);\n  }\n  if (a.kind === \"prefix\" && b.kind === \"pattern\") {\n    return claimsOverlap(b, a);\n  }\n  if (a.kind === \"pattern\" && b.kind === \"pattern\") {\n    return patternsOverlap(a.matcher.pattern, b.matcher.pattern);\n  }\n  return false;\n}\n\nfunction describeClaim(claim: PathClaim): string {\n  const methods = methodsOf(claim).join(\",\");\n  if (claim.kind === \"pattern\") return `${methods} ${claim.matcher.pattern}`;\n  return `${methods} ${claim.path}${claim.kind === \"prefix\" ? \"/*\" : \"\"}`;\n}\n\n/**\n * Dispatch tiers: an exact claim always beats a pattern, a pattern always\n * beats a prefix, and the `/` fallback (length 1) loses to every other\n * prefix. Within a tier, the longer static path wins.\n */\nfunction scoreClaim(claim: PathClaim, path: string): number | undefined {\n  if (claim.kind === \"exact\") {\n    return claim.path === path ? 1_000_000 + path.length : undefined;\n  }\n  if (claim.kind === \"pattern\") {\n    return claim.matcher.match(path)\n      ? 500_000 + claim.staticPrefix.length\n      : undefined;\n  }\n  return prefixContains(claim.path, path) ? claim.path.length : undefined;\n}\n\n/** Streaming responses one listener carries before it refuses more. */\nconst DEFAULT_MAX_STREAMING_REQUESTS = 500;\n\n/**\n * The issuer an auth config advertises, when it has one. `jwt()` and\n * `jwks()` surface it; a bare `{ validator }` and an api-key config do not,\n * and RFC 9728 allows the resulting document to omit the field.\n */\nfunction issuerOf(\n  auth: HttpMount[\"auth\"] | ValidatorAuthOptions | undefined,\n): string | string[] | undefined {\n  if (auth === undefined || auth === false) return undefined;\n  return \"issuer\" in auth\n    ? (auth as { issuer?: string | string[] }).issuer\n    : undefined;\n}\n\nexport class HttpMountRegistry implements WebIngress {\n  readonly serverName: string;\n  boundAddress: { readonly host: string; readonly port: number } | undefined;\n  private readonly mounts = new Map<string, HttpMount>();\n  private readonly requestPolicies = new Map<\n    string,\n    ResolvedRequestValidation\n  >();\n  private readonly allowedHostnames: ReadonlySet<string>;\n  private readonly serverAuth: ValidatorAuthOptions | undefined;\n  private readonly context: CraftContext;\n  private readonly authByMount = new Map<\n    string,\n    HttpAuthMiddleware | undefined\n  >();\n  private readonly authPolicyByMount = new Map<\n    string,\n    HttpMountAuthPolicy | undefined\n  >();\n  private readonly authFactsByMount = new Map<string, HttpMountAuth>();\n  private evaluatedClaims: ReadonlyArray<{\n    mount: HttpMount;\n    claims: readonly PathClaim[];\n  }> = [];\n  private validated = false;\n\n  /** Streaming responses currently open on this listener. */\n  private streaming = 0;\n  private readonly maxStreamingRequests: number;\n\n  constructor(\n    serverName: string,\n    context: CraftContext,\n    serverAuth?: ValidatorAuthOptions,\n    maxStreamingRequests = DEFAULT_MAX_STREAMING_REQUESTS,\n    allowedHostnames?: readonly string[],\n  ) {\n    this.allowedHostnames = resolveAllowedHostnames(allowedHostnames);\n    this.serverName = serverName;\n    this.context = context;\n    this.serverAuth = serverAuth;\n    this.maxStreamingRequests = maxStreamingRequests;\n  }\n\n  /**\n   * Take a streaming slot, or refuse when the listener is full.\n   *\n   * The release is idempotent: a response can end more than one way (drained,\n   * cancelled, failed) and the paths that report it are deliberately not\n   * exclusive, so double-releasing must not hand the listener free budget.\n   */\n  private takeStreamingSlot(\n    request: Request,\n    runtime: HttpServerRuntime | undefined,\n  ): (() => void) | undefined {\n    if (this.streaming >= this.maxStreamingRequests) return undefined;\n    this.streaming++;\n    runtime?.exemptFromIdleTimeout(request);\n    let released = false;\n    return () => {\n      if (released) return;\n      released = true;\n      this.streaming--;\n    };\n  }\n\n  resolveMountAuth(auth: HttpMount[\"auth\"]): HttpMountAuth {\n    const own = auth !== undefined && auth !== false;\n    const optedOut = auth === false;\n    // `false` keeps the inherited validator: it removes the wall, not the\n    // ability of a route's .authorize() to pull identity through it.\n    const configured = own || this.serverAuth !== undefined;\n    return { configured, own, optedOut, walled: configured && !optedOut };\n  }\n\n  mountHttp(mount: HttpMount): () => void {\n    // Claims are evaluated once at start() validation; a mount arriving after\n    // that would silently never dispatch, so refuse it loudly instead.\n    // (see hasMount below for why registration order does not matter to it)\n    if (this.validated) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `servers.${this.serverName}: mount \"${mount.id}\" registered after the server validated its mounts. Register mounts during plugin apply(), before context start().`,\n      });\n    }\n    if (this.mounts.has(mount.id)) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `servers.${this.serverName}: duplicate mount id \"${mount.id}\"`,\n      });\n    }\n    if (mount.requestValidation !== undefined) {\n      this.requestPolicies.set(\n        mount.id,\n        resolveRequestValidation(mount.requestValidation),\n      );\n    }\n    this.mounts.set(mount.id, mount);\n    this.authFactsByMount.set(mount.id, this.resolveMountAuth(mount.auth));\n    return () => {\n      if (this.mounts.get(mount.id) !== mount) return;\n      this.mounts.delete(mount.id);\n      this.requestPolicies.delete(mount.id);\n      // Prune every derived structure, not only the source map: dispatch\n      // routes off the evaluated snapshot, so an unmount that left it in\n      // place would keep serving a surface that believes it is gone.\n      this.evaluatedClaims = this.evaluatedClaims.filter(\n        (entry) => entry.mount !== mount,\n      );\n      this.authByMount.delete(mount.id);\n      this.authPolicyByMount.delete(mount.id);\n      this.authFactsByMount.delete(mount.id);\n    };\n  }\n\n  setBoundAddress(host: string, port: number): void {\n    this.boundAddress = { host, port };\n  }\n\n  /** Mount ids registered on this server, in registration order. */\n  mountIds(): readonly string[] {\n    return [...this.mounts.keys()];\n  }\n\n  validate(): void {\n    const evaluated = [...this.mounts.values()].map((mount) => ({\n      mount,\n      claims: [...mount.claims()],\n    }));\n    this.evaluatedClaims = evaluated;\n    this.validated = true;\n    this.authByMount.clear();\n    this.authPolicyByMount.clear();\n    for (const { mount } of evaluated) {\n      const facts = this.authFactsByMount.get(mount.id)!;\n      // Walled, inheriting, and enforcing: an opted-out mount and a surface\n      // that never walls (ops) both resolve the server validator without it\n      // gating anything, so announcing inheritance for them would misstate\n      // the exposure.\n      const inherited =\n        facts.walled && !facts.own && mount.enforcesWall !== false;\n      const auth = this.effectiveAuthOf(mount);\n      this.authByMount.set(mount.id, createAuthMiddleware(auth));\n      const issuer = issuerOf(auth);\n      this.authPolicyByMount.set(\n        mount.id,\n        issuer !== undefined ? { issuer } : undefined,\n      );\n      if (inherited) {\n        this.context.logger.info(\n          { server: this.serverName, mount: mount.id },\n          \"Server mount inherited authentication\",\n        );\n      }\n    }\n    // The `/` fallback is exempt from prefix-overlap (it is the designated\n    // loser), so two mounts both claiming it would pass the pairwise check\n    // and shadow each other by iteration order. Refuse that explicitly.\n    const fallbackOwners = evaluated\n      .filter(({ claims }) =>\n        claims.some((claim) => claim.kind === \"prefix\" && claim.path === \"/\"),\n      )\n      .map(({ mount }) => mount.id);\n    if (fallbackOwners.length > 1) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `servers.${this.serverName}: mounts ${fallbackOwners.map((id) => `\"${id}\"`).join(\", \")} all claim the \"/\" catch-all. At most one mount per server may own the fallback.`,\n      });\n    }\n    for (let i = 0; i < evaluated.length; i++) {\n      for (let j = i + 1; j < evaluated.length; j++) {\n        const left = evaluated[i]!;\n        const right = evaluated[j]!;\n        for (const a of left.claims) {\n          for (const b of right.claims) {\n            if (!claimsOverlap(a, b)) continue;\n            throw rcError(\"RC5003\", undefined, {\n              message: `servers.${this.serverName}: mount \"${left.mount.id}\" claim ${describeClaim(a)} conflicts with mount \"${right.mount.id}\" claim ${describeClaim(b)}`,\n            });\n          }\n        }\n      }\n    }\n  }\n\n  /**\n   * Whether a mount with this id is registered here.\n   *\n   * Answered from the registration map rather than the evaluated snapshot, so\n   * a `claims()` thunk can consult it: thunks run once every mount has\n   * registered, which makes the answer independent of plugin order.\n   */\n  hasMount(id: string): boolean {\n    return this.mounts.has(id);\n  }\n\n  /**\n   * The auth a mount effectively verifies with: its own when it declares\n   * one, else the server's. `false` and unset both resolve the inherited\n   * validator, per the mount option contract. The single derivation both\n   * `validate()` (the enforced policy) and the metadata serving (the\n   * advertised policy) read, so the two cannot drift.\n   */\n  private effectiveAuthOf(mount: HttpMount | undefined): HttpAuth | undefined {\n    if (mount === undefined) return this.serverAuth;\n    return mount.auth === false || mount.auth === undefined\n      ? this.serverAuth\n      : mount.auth;\n  }\n\n  /**\n   * The mount that owns a resource path, ignoring methods.\n   *\n   * Method-blind on purpose: the metadata document describes a resource,\n   * and a path served only for POST (a dispatch endpoint) still has\n   * exactly one owning mount whose auth the document must state.\n   */\n  private resolveOwningMount(path: string): HttpMount | undefined {\n    let best: { mount: HttpMount; score: number } | undefined;\n    for (const { mount, claims } of this.evaluatedClaims) {\n      for (const claim of claims) {\n        const score = scoreClaim(claim, path);\n        if (score === undefined) continue;\n        if (best === undefined || score > best.score) {\n          best = { mount, score };\n        }\n      }\n    }\n    return best?.mount;\n  }\n\n  /**\n   * Serve the RFC 9728 document for a metadata path no mount claims.\n   *\n   * The suffix mirrors the resource path per RFC 9728 section 3.1, so the\n   * document for `/ops/routes` is looked up by resolving which mount owns\n   * `/ops/routes` and reading its effective auth: issuer from the same\n   * resolved policy the mount enforces with, scopes from what the mount\n   * declared. A suffixed path no mount owns gets no document at all: a 200\n   * would assert a protected-resource identity for a resource the server\n   * does not serve, and a spec-following client would then request a token\n   * for it. Only the root document (the server itself) is served without\n   * an owning mount, from the server-level validator, and a server with no\n   * auth still answers it with the honest minimum: the resource identity\n   * and nothing more.\n   *\n   * Identical for every credential state and served before any\n   * verification, so a caller with a stale or malformed token can still\n   * learn where to re-authenticate. `no-cache` because the body derives\n   * from live configuration and from the caller's own Host: an hour-stale\n   * copy misdirects the one caller who reads it to find the current way\n   * in, and a shared cache with a normalised key could hand one host's\n   * identity to another. No CORS headers: this fallback serves surfaces\n   * that never declared a browser policy, and the craft CLI (no Origin\n   * header) is unaffected. The MCP mount keeps serving its own document\n   * under its own CORS policy.\n   */\n  private serveResourceMetadata(\n    request: Request,\n    path: string,\n    method: HttpMethod,\n  ): Response | undefined {\n    const isMetadataPath =\n      path === PROTECTED_RESOURCE_METADATA_PATH ||\n      path.startsWith(`${PROTECTED_RESOURCE_METADATA_PATH}/`);\n    if (!isMetadataPath) return undefined;\n    if (method !== \"GET\" && method !== \"HEAD\") return undefined;\n\n    const suffix = path.slice(PROTECTED_RESOURCE_METADATA_PATH.length);\n    const resourcePath = suffix === \"\" ? \"/\" : suffix;\n    const mount = this.resolveOwningMount(resourcePath);\n    if (mount === undefined && suffix !== \"\") return undefined;\n    if (mount !== undefined) {\n      const refusal = this.validateRequest(request, mount);\n      if (refusal) return refusal;\n    }\n    const issuer =\n      mount !== undefined\n        ? this.authPolicyByMount.get(mount.id)?.issuer\n        : issuerOf(this.serverAuth);\n    const origin = new URL(request.url).origin;\n    const body = JSON.stringify(\n      buildProtectedResourceMetadata({\n        resource: `${origin}${suffix}`,\n        ...(issuer !== undefined ? { issuer } : {}),\n        ...(mount?.resourceMetadata?.scopesSupported !== undefined\n          ? { scopesSupported: mount.resourceMetadata.scopesSupported }\n          : {}),\n      }),\n    );\n    return new Response(method === \"HEAD\" ? null : body, {\n      status: 200,\n      headers: {\n        \"content-type\": \"application/json\",\n        \"cache-control\": \"no-cache\",\n      },\n    });\n  }\n\n  /** Reject before preflight, auth, SDK work or stream allocation. */\n  private validateRequest(\n    request: Request,\n    mount: HttpMount,\n  ): Response | undefined {\n    const policy = this.requestPolicies.get(mount.id);\n    if (policy === undefined) return undefined;\n    const reason = requestValidationFailure(\n      request,\n      this.boundAddress?.host,\n      this.allowedHostnames,\n      policy,\n    );\n    if (reason === undefined) return undefined;\n    const detail = { server: this.serverName, mount: mount.id, reason };\n    this.context.logger.debug(detail, \"Protocol ingress request refused\");\n    this.context.emit(\"server:request:rejected\", detail);\n    return Response.json(\n      { error: \"Forbidden\" },\n      {\n        status: 403,\n        headers: { \"cache-control\": \"no-store\" },\n      },\n    );\n  }\n\n  async dispatch(\n    request: Request,\n    runtime?: import(\"../http/server/index.ts\").HttpServerRuntime,\n  ): Promise<Response> {\n    const path = new URL(request.url).pathname;\n    const method = request.method.toUpperCase() as HttpMethod;\n    let best: { mount: HttpMount; claim: PathClaim; score: number } | undefined;\n    search: for (const { mount, claims } of this.evaluatedClaims) {\n      for (const claim of claims) {\n        if (!methodsOf(claim).includes(method)) continue;\n        const score = scoreClaim(claim, path);\n        if (score === undefined) continue;\n        if (best === undefined || score > best.score) {\n          best = { mount, claim, score };\n        }\n        // An exact hit is unbeatable: validation refuses duplicate exact\n        // path+method claims, so no other claim can outscore it.\n        if (claim.kind === \"exact\") break search;\n      }\n    }\n    // RFC 9728 discovery: the ingress owns the well-known namespace unless\n    // a mount claims the specific path (exact or pattern), the way the MCP\n    // mount claims and serves its own suffixed document under its own CORS\n    // policy and resource identity. A prefix claim (notably the \"/\"\n    // catch-all of a default http mount) does not take a metadata path: it\n    // would only 404 a document the ingress can answer truthfully.\n    if (best === undefined || best.claim.kind === \"prefix\") {\n      const metadata = this.serveResourceMetadata(request, path, method);\n      if (metadata) return metadata;\n    }\n    if (!best) {\n      return Response.json({ error: \"not found\", path }, { status: 404 });\n    }\n    const mount = best.mount;\n    const refusal = this.validateRequest(request, mount);\n    if (refusal) return refusal;\n    if (mount.longLived) runtime?.exemptFromIdleTimeout(request);\n    const authMiddleware = this.authByMount.get(mount.id);\n\n    // Verification is pulled by the mount, never pushed by the ingress: a\n    // public path (discovery, health, a route with auth: \"skip\") must not\n    // pay validator work or pollute the auth event stream just because the\n    // listener is shared. Memoized so the mount and its inner dispatcher\n    // resolve the same request at most once, with the events emitted at\n    // that single resolution.\n    let resolved: Promise<AuthResult | undefined> | undefined;\n    const authenticate = (): Promise<AuthResult | undefined> => {\n      resolved ??= (async () => {\n        if (!authMiddleware) return undefined;\n        const auth = await authMiddleware(request);\n        if (auth.kind === \"admit\") {\n          this.context.emit(\"auth:success\", {\n            subject: auth.principal.subject,\n            scheme: auth.principal.scheme,\n            source: mount.id,\n          });\n        } else if (auth.kind === \"reject\") {\n          this.context.emit(\"auth:rejected\", {\n            reason: auth.reason,\n            scheme: auth.scheme,\n            source: mount.id,\n          });\n        }\n        return auth;\n      })();\n      return resolved;\n    };\n\n    return mount.handler(request, {\n      serverName: this.serverName,\n      authenticate,\n      claimStreamingSlot: () => this.takeStreamingSlot(request, runtime),\n      authPolicy: this.authPolicyByMount.get(mount.id),\n      auth:\n        this.authFactsByMount.get(mount.id) ??\n        this.resolveMountAuth(mount.auth),\n    });\n  }\n}\n\nexport function requireWebIngress(\n  ctx: CraftContext,\n  serverName = \"default\",\n): WebIngress {\n  const ingresses = ctx.getStore(WEB_INGRESSES);\n  const ingress = ingresses?.get(serverName);\n  if (ingress) return ingress;\n  const names = ingresses ? [...ingresses.keys()] : [];\n  throw rcError(\"RC5003\", undefined, {\n    message: `Server \"${serverName}\" is not defined. Defined servers: ${names.length > 0 ? names.join(\", \") : \"none\"}. Configure defineConfig({ servers: { ${serverName}: { port: 8080 } } }).`,\n  });\n}\n","import { createHash } from \"node:crypto\";\nimport { rcError } from \"../../error\";\nimport { bearerChallenge } from \"../server/protected-resource.ts\";\nimport { classifyRejectionReason } from \"../../auth/error-classification\";\nimport { isPrincipalExpired } from \"../../auth/expiry\";\nimport { markAuthentic } from \"../../auth/authentic\";\nimport type { Principal, TokenVerifier } from \"../../auth/types\";\nimport type {\n  ApiKeyAuthOptions,\n  HttpAuth,\n  OAuthAuthOptionsReserved,\n} from \"../../adapters/http/types\";\n\n/**\n * Result of running the auth middleware on a request.\n *\n * - `admit` always carries a {@link Principal}: every implemented strategy\n *   (apiKey static / verify, validator bearer) produces one on the admit\n *   path.\n * - `absent` is returned when the request carried no credential at all (no\n *   `Authorization` header for bearer; no header / query parameter for\n *   apiKey). The dispatcher converts this to 401 on `auth: \"required\"`\n *   routes and lets the request through with no principal on\n *   `auth: \"optional\"` routes. Carries the `scheme` only; the dispatcher\n *   decides whether to issue a Response based on the route's auth mode.\n * - `reject` is returned when a credential was presented but failed\n *   verification. It carries the canonical response the dispatcher should\n *   return (401, or 500 when verification itself failed on the server\n *   side), plus the `reason` and `scheme` that drive the `auth:rejected`\n *   event payload.\n */\nexport type AuthResult =\n  | {\n      kind: \"admit\";\n      principal: Principal;\n      /**\n       * Raw credential passed through for protocol adapters such as MCP.\n       * This is secret material: never log it, emit it in an event, include it\n       * in an error, or persist it outside the request lifetime.\n       */\n      credential: string;\n      /**\n       * Clock skew the verification that admitted this credential allowed.\n       *\n       * Carried on the verdict rather than re-derived from config by each\n       * consumer, because anything re-checking the same credential later (a\n       * stream that outlives its admission) must apply the same boundary.\n       * Two resolutions of one setting can drift; an inherited value cannot.\n       */\n      clockToleranceSec: number;\n    }\n  | { kind: \"absent\"; scheme: string }\n  | {\n      kind: \"reject\";\n      response: Response;\n      reason: string;\n      scheme: string;\n      cause?: unknown;\n    };\n\n/** Request-level middleware produced by {@link createAuthMiddleware}. */\nexport type HttpAuthMiddleware = (req: Request) => Promise<AuthResult>;\n\n/**\n * Build an API-key auth strategy. Use with `http: { auth: apiKey({...}) }`.\n *\n * @example Static allowlist (most common case)\n * ```ts\n * http: { port: 8080, auth: apiKey({ keys: [process.env.API_KEY!] }) }\n * ```\n *\n * @example Database-backed lookup that resolves to a per-user principal\n * ```ts\n * apiKey({\n *   in: \"header\",\n *   name: \"x-api-key\",\n *   verify: async (key) => {\n *     const user = await db.users.findByApiKey(key);\n *     if (!user) return null;\n *     return { kind: \"custom\", scheme: \"apiKey\", subject: user.id, roles: user.roles };\n *   },\n * })\n * ```\n *\n * @experimental\n */\nexport function apiKey(\n  opts: Omit<ApiKeyAuthOptions, \"kind\">,\n): ApiKeyAuthOptions {\n  const hasKeys = Array.isArray(opts.keys) && opts.keys.length > 0;\n  if (!hasKeys && !opts.verify) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"apiKey() requires a non-empty `keys` allowlist or a `verify` function.\",\n    });\n  }\n  if (hasKeys && opts.verify) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"apiKey() accepts either `keys` or `verify`, not both. Pick the static allowlist (`keys`) or the dynamic verifier (`verify`).\",\n    });\n  }\n  if (opts.scopes !== undefined && opts.verify) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"apiKey() `scopes` applies to the static `keys` allowlist only. A `verify` function returns the principal itself, so put the scopes on what it returns rather than here, where they would be silently ignored.\",\n    });\n  }\n  if (opts.name !== undefined) {\n    if (opts.name.trim() === \"\") {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"apiKey() received an empty `name`. Provide a non-empty header or query parameter name, or omit `name` for the default.\",\n      });\n    }\n    // RFC 7230 §3.2.6: header field names must be valid tokens. Validate only\n    // when the key is sourced from a header; query parameter names are less\n    // restricted and a bad one fails loudly at request time anyway.\n    if (\n      (opts.in ?? \"header\") === \"header\" &&\n      !/^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/.test(opts.name)\n    ) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"apiKey() received an invalid header `name`. Use a valid HTTP header token (RFC 7230 §3.2.6).\",\n      });\n    }\n  }\n  // Spread first so the `kind` literal always wins over an untyped caller that\n  // sneaks a different discriminator through `as any`.\n  return { ...opts, kind: \"apiKey\" };\n}\n\n/**\n * Map the auth scheme to the canonical \"missing credential\" reason.\n * Returned to clients in the 401 body and emitted as the `reason` field on\n * `auth:rejected` events when the dispatcher synthesises a missing-credential\n * 401. Centralised so the response body and the event payload cannot drift.\n *\n * Bearer uses `missing_header`, the same bounded token MCP emits, so the\n * shared vocabulary in `.standards/security.md` section 10 holds across\n * surfaces; api-key keeps its documented literal.\n */\nexport function missingCredentialReason(scheme: string): string {\n  return scheme === \"apiKey\" ? \"missing api key\" : \"missing_header\";\n}\n\nfunction reject(\n  reason: string,\n  scheme: string,\n  requestUrl: string,\n  cause?: unknown,\n): AuthResult {\n  // An infrastructure failure (JWKS unreachable, userinfo fetch failed) is a\n  // server-side fault, never the caller's credential: it maps to 500 so the\n  // client retries later instead of discarding a valid cached token and\n  // stampeding the IdP with refreshes (`.standards/security.md` Boundaries).\n  // The classification string stays on the AuthResult for the event payload\n  // but is not echoed to anonymous callers in the body.\n  const infrastructure = reason === \"infrastructure\";\n  const headers: Record<string, string> = {\n    \"content-type\": \"application/json\",\n  };\n  // `WWW-Authenticate` advertises a scheme the server actually accepts. Only\n  // emit it for the bearer scheme; sending `Bearer` on an api-key rejection\n  // mis-signals the protocol (RFC 7235) and confuses auto-refreshing clients.\n  // A 500 carries no challenge at all: the credential was never judged.\n  // `resource_metadata` (RFC 9728 section 5.1) points a refused caller at\n  // the document naming who issues acceptable tokens; the ingress serves it\n  // for every mount, so the hint goes on every bearer challenge.\n  if (scheme === \"bearer\" && !infrastructure) {\n    headers[\"www-authenticate\"] = bearerChallenge({ requestUrl });\n  }\n  const response = new Response(\n    JSON.stringify(\n      infrastructure\n        ? { error: \"authentication_unavailable\" }\n        : { error: \"unauthorized\", reason },\n    ),\n    {\n      status: infrastructure ? 500 : 401,\n      headers,\n    },\n  );\n  return {\n    kind: \"reject\",\n    response,\n    reason,\n    scheme,\n    ...(cause !== undefined ? { cause } : {}),\n  };\n}\n\nfunction isApiKeyAuth(auth: HttpAuth): auth is ApiKeyAuthOptions {\n  return (auth as { kind?: string }).kind === \"apiKey\";\n}\n\nfunction isOAuthReserved(auth: HttpAuth): auth is OAuthAuthOptionsReserved {\n  return (auth as { kind?: string }).kind === \"oauth\";\n}\n\nfunction isValidatorAuth(auth: HttpAuth): auth is { validator: TokenVerifier } {\n  return (\n    typeof (auth as { validator?: unknown }).validator === \"function\" &&\n    !isApiKeyAuth(auth) &&\n    !isOAuthReserved(auth)\n  );\n}\n\n// Default key name differs per location to match each convention: `x-api-key`\n// for headers, `api_key` for query strings. Lookups also differ on casing:\n// header names are case-insensitive (HTTP), so the header path lowercases;\n// query parameter names are case-sensitive (URL spec), so the query path\n// matches verbatim. Both behaviours are documented on the adapters reference\n// page.\nfunction defaultApiKeyName(where: \"header\" | \"query\"): string {\n  return where === \"header\" ? \"x-api-key\" : \"api_key\";\n}\n\nfunction syntheticApiKeyPrincipal(\n  key: string,\n  scopes: readonly string[] | undefined,\n): Principal {\n  // SHA-256, truncated to 16 hex chars. Stable across processes, collision-safe\n  // at any realistic key count, and reveals nothing about the source string\n  // regardless of its length. The earlier substring approach leaked short keys\n  // verbatim into `subject` (and therefore into logs and `auth:success`\n  // payloads), which is exactly what the security standard forbids.\n  const digest = createHash(\"sha256\").update(key).digest(\"hex\").slice(0, 16);\n  return {\n    kind: \"custom\",\n    scheme: \"apiKey\",\n    subject: `apiKey:${digest}`,\n    ...(scopes !== undefined && scopes.length > 0\n      ? { scopes: [...scopes] }\n      : {}),\n  };\n}\n\n/**\n * Build the middleware that runs once per incoming request. Returns\n * `undefined` (callers should treat as \"no auth, admit all\") when the\n * plugin was configured without an `auth` block.\n *\n * Throws `RC5003` at plugin init when the supplied options are malformed\n * (notably: OAuth reserved sentinel, since OAuth 2.1 is a v2 follow-up).\n */\nexport function createAuthMiddleware(\n  auth: HttpAuth | undefined,\n): HttpAuthMiddleware | undefined {\n  if (auth === undefined) return undefined;\n\n  if (isOAuthReserved(auth)) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"OAuth 2.1 auth is reserved on the http plugin but not implemented in this release. Use jwt(...) / jwks(...) for bearer auth, or apiKey(...) for API-key auth.\",\n    });\n  }\n\n  if (isApiKeyAuth(auth)) {\n    const where = auth.in ?? \"header\";\n    const name = auth.name ?? defaultApiKeyName(where);\n    const lowerName = name.toLowerCase();\n    const allowedSet =\n      auth.keys && auth.keys.length > 0 ? new Set(auth.keys) : undefined;\n    const verify = auth.verify;\n\n    // The factory guarantees exactly one of `allowedSet` / `verify` is set;\n    // assert here so a future bug in the factory surfaces as RC5003 instead\n    // of a silent 401.\n    if (!allowedSet && !verify) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"apiKey middleware reached construction with neither `keys` nor `verify`. Check the apiKey() factory.\",\n      });\n    }\n\n    return async (req: Request): Promise<AuthResult> => {\n      let raw: string | null = null;\n      if (where === \"header\") {\n        raw = req.headers.get(lowerName);\n      } else {\n        try {\n          raw = new URL(req.url).searchParams.get(name);\n        } catch {\n          raw = null;\n        }\n      }\n      // `absent` is reserved for \"no credential was presented at all\" (the\n      // header / query parameter is missing). An empty string or whitespace\n      // is a *presented* credential that fails validation -- treat it as\n      // reject so `auth: \"optional\"` cannot silently downgrade it to\n      // anonymous access.\n      if (raw === null) {\n        return { kind: \"absent\", scheme: \"apiKey\" };\n      }\n      if (raw.trim() === \"\") {\n        return reject(\"invalid api key\", \"apiKey\", req.url);\n      }\n      if (allowedSet) {\n        if (!allowedSet.has(raw)) {\n          return reject(\"invalid api key\", \"apiKey\", req.url);\n        }\n        return {\n          kind: \"admit\",\n          principal: markAuthentic(syntheticApiKeyPrincipal(raw, auth.scopes)),\n          credential: raw,\n          // An api key is compared, never dated: this path applies no\n          // tolerance, so anything inheriting the verdict applies none either.\n          clockToleranceSec: 0,\n        };\n      }\n      try {\n        const principal = await verify!(raw);\n        if (!principal) {\n          return reject(\"invalid api key\", \"apiKey\", req.url);\n        }\n        return {\n          kind: \"admit\",\n          principal: markAuthentic(principal),\n          credential: raw,\n          clockToleranceSec: 0,\n        };\n      } catch {\n        return reject(\"invalid api key\", \"apiKey\", req.url);\n      }\n    };\n  }\n\n  if (isValidatorAuth(auth)) {\n    const validator = auth.validator;\n    const clockToleranceSec =\n      \"clockToleranceSec\" in auth &&\n      typeof (auth as { clockToleranceSec?: unknown }).clockToleranceSec ===\n        \"number\"\n        ? (auth as { clockToleranceSec: number }).clockToleranceSec\n        : 0;\n    return async (req: Request): Promise<AuthResult> => {\n      // `absent` is reserved for \"no Authorization header at all\". A header\n      // with a different scheme (Basic, Digest, etc.) or a Bearer scheme\n      // with an empty token is a *presented* credential that fails\n      // verification; route it through `reject` so `auth: \"optional\"` does\n      // not silently downgrade it to anonymous access.\n      const header = req.headers.get(\"authorization\");\n      if (header === null) {\n        return { kind: \"absent\", scheme: \"bearer\" };\n      }\n      if (!header.toLowerCase().startsWith(\"bearer \")) {\n        return reject(\"unsupported_scheme\", \"bearer\", req.url);\n      }\n      const token = header.slice(7).trim();\n      if (!token) {\n        return reject(\"invalid_token\", \"bearer\", req.url);\n      }\n      try {\n        const principal = await validator(token);\n        if (!principal) {\n          return reject(\"invalid_token\", \"bearer\", req.url);\n        }\n        // Defense in depth for custom validators that return an already\n        // elapsed `expiresAt` instead of throwing: the built-in verifiers\n        // enforce `exp` themselves, but a hand-rolled one may not.\n        if (isPrincipalExpired(principal, clockToleranceSec)) {\n          return reject(\"expired\", \"bearer\", req.url);\n        }\n        return {\n          kind: \"admit\",\n          principal: markAuthentic(principal),\n          credential: token,\n          clockToleranceSec,\n        };\n      } catch (error) {\n        return reject(classifyRejectionReason(error), \"bearer\", req.url, error);\n      }\n    };\n  }\n\n  throw rcError(\"RC5003\", undefined, {\n    message:\n      \"http plugin: unsupported auth shape. Pass jwt(...) / jwks(...), apiKey({...}), or { validator: (token) => Principal }.\",\n  });\n}\n","/**\n * RFC 9728 OAuth 2.0 Protected Resource Metadata, shared by every http\n * surface.\n *\n * The document is how a refused caller learns who issues acceptable\n * credentials: a 401 challenge carries a `resource_metadata` URL, the\n * caller fetches it, and `authorization_servers` plus `scopes_supported`\n * name the way in. Core owns the builder and the serving fallback (see\n * `HttpMountRegistry.dispatch`); the MCP transport consumes the same\n * builder for the document it serves on its own claimed path.\n *\n * Everything here is sourced from configuration the operator already\n * wrote: issuer from `jwt()` / `jwks()`, scopes from what a mount\n * declares. A validator with no issuer produces an honest minimal\n * document rather than an invented one.\n */\n\n/** Root path of the RFC 9728 protected-resource metadata document. */\nexport const PROTECTED_RESOURCE_METADATA_PATH =\n  \"/.well-known/oauth-protected-resource\";\n\n/**\n * RFC 9728 OAuth 2.0 Protected Resource Metadata payload returned by\n * `GET /.well-known/oauth-protected-resource` (and its path-suffixed\n * variants). Optional fields are omitted from the JSON when unset.\n */\nexport interface ProtectedResourceMetadata {\n  resource: string;\n  resource_name?: string;\n  authorization_servers?: string[];\n  bearer_methods_supported: [\"header\"];\n  scopes_supported?: string[];\n  resource_documentation?: string;\n}\n\n/** What a metadata document is built from; every field beyond `resource` is optional. */\nexport interface ProtectedResourceMetadataInput {\n  /** Absolute URL identifying the protected resource. */\n  resource: string;\n  /** Human-readable name (RFC 9728 `resource_name`). */\n  resourceName?: string;\n  /** Issuer(s) of acceptable tokens, from the effective validator. */\n  issuer?: string | string[];\n  /** Scopes this resource understands, from resolved configuration. */\n  scopesSupported?: readonly string[];\n  /** Documentation URL (RFC 9728 `resource_documentation`). */\n  documentationUrl?: string;\n}\n\n/**\n * Build the RFC 9728 protected-resource metadata document.\n *\n * `resource` is a required input rather than a default the caller patches\n * afterwards: the resolved identity depends on the bound address, and a\n * builder that returned a knowingly wrong placeholder would let any future\n * call site silently advertise it.\n *\n * `authorization_servers` is populated from the effective validator's\n * `issuer`. When the verifier exposes no issuer, the field is omitted\n * (RFC 9728 allows that): bearer is accepted and no AS is discoverable,\n * which is the truth of a bare `{ validator }`.\n */\nexport function buildProtectedResourceMetadata(\n  input: ProtectedResourceMetadataInput,\n): ProtectedResourceMetadata {\n  const metadata: ProtectedResourceMetadata = {\n    resource: input.resource,\n    bearer_methods_supported: [\"header\"],\n  };\n  if (input.resourceName !== undefined) {\n    metadata.resource_name = input.resourceName;\n  }\n  if (input.issuer !== undefined) {\n    metadata.authorization_servers = Array.isArray(input.issuer)\n      ? [...input.issuer]\n      : [input.issuer];\n  }\n  if (input.scopesSupported !== undefined && input.scopesSupported.length > 0) {\n    metadata.scopes_supported = [...input.scopesSupported];\n  }\n  if (input.documentationUrl !== undefined) {\n    metadata.resource_documentation = input.documentationUrl;\n  }\n  return metadata;\n}\n\n/**\n * The RFC 9728 metadata URL a challenge on `requestUrl` should hint at.\n *\n * Path insertion per RFC 9728 section 3.1: the well-known prefix goes\n * between the origin and the resource path, so `/ops/routes` hints at\n * `/.well-known/oauth-protected-resource/ops/routes`. The origin comes\n * from the request URL, which reflects the Host header the caller used,\n * so the hint survives port forwards and reverse proxies that preserve\n * Host.\n */\nexport function resourceMetadataUrlFor(requestUrl: string): string {\n  const url = new URL(requestUrl);\n  const suffix = url.pathname === \"/\" ? \"\" : url.pathname;\n  return `${url.origin}${PROTECTED_RESOURCE_METADATA_PATH}${suffix}`;\n}\n\n/**\n * Build the RFC 6750 bearer challenge every routecraft-owned surface emits\n * on a refusal.\n *\n * One builder rather than one string per call site, because the challenge\n * is a single wire contract with a single consumer-side parser (the CLI's\n * refusal enrichment): a parameter added in one copy and not another would\n * still parse and silently say less. `realm` leads and `resource_metadata`\n * trails, matching what the MCP mount already emits, so parsers keyed on\n * either order hold.\n *\n * `requestUrl` is required, not optional: every bearer refusal hints\n * (`.standards/security.md` section 6), and an optional parameter would let\n * the next refusal path compile while quietly dropping the hint.\n */\nexport function bearerChallenge(options: {\n  requestUrl: string;\n  params?: Record<string, string>;\n}): string {\n  const attributes = [\n    `realm=\"routecraft\"`,\n    ...Object.entries(options.params ?? {}).map(\n      ([key, value]) => `${key}=\"${value}\"`,\n    ),\n    `resource_metadata=\"${resourceMetadataUrlFor(options.requestUrl)}\"`,\n  ];\n  return `Bearer ${attributes.join(\", \")}`;\n}\n","import { registerConfigApplier } from \"../../config-applier.ts\";\nimport { serversPlugin } from \"./plugin.ts\";\nimport type { ServerDefinitions } from \"./types.ts\";\n\ndeclare module \"@routecraft/routecraft\" {\n  interface CraftConfig {\n    servers?: ServerDefinitions;\n  }\n}\n\nregisterConfigApplier(\"servers\", (definitions) => serversPlugin(definitions));\n","import type { CraftContext, CraftPlugin } from \"../../context\";\nimport { rcError } from \"../../error\";\nimport type {\n  HttpAuth,\n  HttpMountDefinition,\n  HttpPluginOptions,\n} from \"../../adapters/http/types\";\nimport { missingCredentialReason } from \"./auth\";\nimport {\n  buildReadyResponse,\n  createBuiltins,\n  createOpenApiGatedHandler,\n} from \"./builtins\";\nimport {\n  createDispatcher,\n  type AuthAwareBuiltins,\n  type GatedBuiltins,\n  type RequestCompletedHandler,\n} from \"./dispatcher\";\nimport {\n  HTTP_MOUNTS,\n  HTTP_PLUGIN_REGISTERED,\n  type HttpMountRuntime,\n  type HttpRouteView,\n} from \"./registry\";\nimport type { HttpOpenApiInfo } from \"./openapi\";\nimport type { HttpWebhookSignatureRejection } from \"./webhook-signature\";\nimport { findPackageInfo } from \"./package-info\";\nimport { requireWebIngress } from \"../server/registry.ts\";\nimport { normalizeStaticPathPrefix } from \"../server/mount-path.ts\";\nimport type { PathClaim } from \"../server/types.ts\";\nimport { staticPathPrefix } from \"./path-matcher.ts\";\nimport { resolveMaxBodySize } from \"./max-body-size.ts\";\n\n/** Resolved per-mount config after the single-mount sugar is normalised. */\ninterface ResolvedMount {\n  readonly name: string;\n  readonly path: string;\n  readonly server: string;\n  readonly auth: HttpAuth | false | undefined;\n}\n\n/**\n * HTTP plugin. Owns the route registries and request dispatchers for its\n * path-scoped mounts, registered on a named server (the listener itself\n * belongs to `defineConfig({ servers })`). Materialised by the config\n * applier so users typically configure it via `defineConfig({ http: {...} })`\n * rather than pushing it onto `config.plugins`. The function is still\n * exported for advanced users who want to wire it manually.\n *\n * The mount is the authentication wall: a mount with an effective validator\n * (its own `auth`, or the server's) requires a valid credential for every\n * route; `auth: false` removes the wall while keeping the inherited validator\n * reachable, so routes never see credentials except those that declare\n * `.authorize()`, which pull verification through it.\n *\n * Lifecycle:\n *   - `apply(ctx)`: validate options, publish the mount table on the context\n *     store, and mount each dispatcher on its mount's named server.\n *   - `teardown(ctx)`: unmount the dispatchers and clear the registries.\n */\nexport function httpPlugin(options: HttpPluginOptions): CraftPlugin {\n  const { mounts: mountsResolved, maxBodySize } = validate(options);\n\n  const perRequestEnabled = options.events?.perRequest ?? true;\n\n  // Built-ins config: every endpoint takes the same {enabled, requireAuth}\n  // shape. Defaults differ per endpoint (see HttpBuiltinOptions JSDoc).\n  const healthEnabled = options.builtins?.health?.enabled ?? true;\n  const readyEnabled = options.builtins?.ready?.enabled ?? true;\n  const readyRequireAuth = options.builtins?.ready?.requireAuth ?? true;\n  const openapiEnabled = options.builtins?.openapi?.enabled ?? true;\n  const openapiRequireAuth = options.builtins?.openapi?.requireAuth ?? false;\n\n  // Resolve the OpenAPI `info` block once: auto-detect `title` (name) and\n  // `version` from the nearest package.json, then layer the caller's\n  // explicit overrides on top. Description / contact / license are NOT\n  // auto-pulled (see HttpOpenApiInfo JSDoc for the security rationale).\n  // Skip the fs walk entirely when openapi is disabled.\n  const openapiInfoOverride = options.builtins?.openapi?.info;\n  const pkg = openapiEnabled ? findPackageInfo() : {};\n  const openapiInfo: HttpOpenApiInfo = {\n    ...(pkg.name !== undefined ? { title: pkg.name } : {}),\n    ...(pkg.version !== undefined ? { version: pkg.version } : {}),\n    ...(openapiInfoOverride ?? {}),\n  };\n\n  const unmounts: Array<() => void> = [];\n  const mountRuntimes = new Map<string, HttpMountRuntime>();\n  for (const mount of mountsResolved) {\n    mountRuntimes.set(mount.name, {\n      path: mount.path,\n      registry: new Map(),\n    });\n  }\n\n  // Built-ins (/health, /ready, /openapi.json) serve only from the \"default\"\n  // mount when it owns the \"/\" catch-all, and report routes across every\n  // mount ON THAT MOUNT'S SERVER only. Aggregating across servers would\n  // publish an internal listener's route inventory and schemas through the\n  // public listener's OpenAPI document.\n  const routesOnServer = (server: string): HttpRouteView => ({\n    get size() {\n      let total = 0;\n      for (const mount of mountsResolved) {\n        if (mount.server !== server) continue;\n        total += mountRuntimes.get(mount.name)!.registry.size;\n      }\n      return total;\n    },\n    *values() {\n      for (const mount of mountsResolved) {\n        if (mount.server !== server) continue;\n        yield* mountRuntimes.get(mount.name)!.registry.values();\n      }\n    },\n  });\n\n  return {\n    async apply(ctx: CraftContext) {\n      ctx.setStore(HTTP_PLUGIN_REGISTERED, true);\n      ctx.setStore(HTTP_MOUNTS, mountRuntimes);\n\n      const onRequestCompleted: RequestCompletedHandler | undefined =\n        perRequestEnabled\n          ? (event) => ctx.emit(\"plugin:http:request:completed\", { ...event })\n          : undefined;\n\n      // Streaming responses are the one kind of in-flight request that can\n      // outlive any sensible grace window, because nothing about them says\n      // when they end. `context:stopping` is emitted before sources are\n      // closed, so every open stream hears the shutdown first and the\n      // listener's graceful close finds nothing left to drain.\n      const shutdown = new AbortController();\n      unmounts.push(\n        ctx.on(\"context:stopping\", () => {\n          shutdown.abort(new Error(\"Context is stopping\"));\n        }),\n      );\n\n      // All server names resolve before anything mounts, so a misspelt\n      // `server` on the third mount cannot leave the first two registered on\n      // a context whose boot then fails; the unwind is not guaranteed to\n      // reach this plugin's teardown.\n      const ingresses = new Map(\n        mountsResolved.map((mount) => [\n          mount.name,\n          requireWebIngress(ctx, mount.server),\n        ]),\n      );\n      for (const mount of mountsResolved) {\n        const ingress = ingresses.get(mount.name)!;\n        const runtime = mountRuntimes.get(mount.name)!;\n        const mountId =\n          mount.name === \"default\" ? \"http\" : `http:${mount.name}`;\n\n        // The shared ingress emits auth:success / auth:rejected when the\n        // `authenticate` thunk resolves an admit or a reject; `absent` is\n        // neither, so the missing-credential 401 the dispatcher synthesises\n        // on a walled mount (or an authorize-pull route) would otherwise be\n        // invisible. This hook is the one place that case can still raise\n        // the event. Built per mount so every rejection path on one surface\n        // reports the same `source` the thunk's events carry.\n        const onAuthAbsent = (scheme: string) => {\n          ctx.emit(\"auth:rejected\", {\n            reason: missingCredentialReason(scheme),\n            scheme,\n            source: mountId,\n          });\n        };\n\n        // Signature rejections surface through the same auth:rejected event\n        // as credential failures. Wired unconditionally (unlike onAuthAbsent)\n        // because the per-route signature gate is independent of the mount\n        // wall; a webhook endpoint typically lives on a public mount.\n        const onSignatureRejected = (reason: HttpWebhookSignatureRejection) => {\n          ctx.emit(\"auth:rejected\", {\n            reason,\n            scheme: \"signature\",\n            source: mountId,\n          });\n        };\n\n        // The effective-auth rule lives in the registry; these are facts.\n        const mountAuth = ingress.resolveMountAuth(mount.auth);\n        const walled = mountAuth.walled;\n        const isDefaultRoot = mount.name === \"default\" && mount.path === \"/\";\n        const authConfigured = walled;\n        const serverRoutes = routesOnServer(mount.server);\n\n        // Built-ins layering (default-root mount only). See the matrix in\n        // HttpBuiltinOptions: /ready and /openapi.json gate on the mount\n        // wall being configured.\n        const readyLayer: \"off\" | \"public-full\" | \"auth-aware\" =\n          !isDefaultRoot || !readyEnabled\n            ? \"off\"\n            : readyRequireAuth && authConfigured\n              ? \"auth-aware\"\n              : \"public-full\";\n        const openapiServedPublic =\n          isDefaultRoot &&\n          openapiEnabled &&\n          (!openapiRequireAuth || !authConfigured);\n        const openapiServedGated =\n          isDefaultRoot &&\n          openapiEnabled &&\n          openapiRequireAuth &&\n          authConfigured;\n\n        const builtins = createBuiltins({\n          registry: serverRoutes,\n          serveHealth: isDefaultRoot && healthEnabled,\n          ready: readyLayer === \"public-full\" ? \"full\" : \"off\",\n          serveOpenApi: openapiServedPublic,\n          openapiInfo,\n        });\n\n        const authAwareBuiltins: AuthAwareBuiltins | undefined =\n          readyLayer === \"auth-aware\"\n            ? {\n                paths: new Set([\"/ready\"]),\n                handler: (_req, pathname, isAuthenticated) =>\n                  pathname === \"/ready\"\n                    ? buildReadyResponse(serverRoutes, isAuthenticated)\n                    : null,\n              }\n            : undefined;\n\n        const gatedBuiltins: GatedBuiltins | undefined = openapiServedGated\n          ? {\n              paths: new Set([\"/openapi.json\"]),\n              handler: createOpenApiGatedHandler(serverRoutes, openapiInfo),\n            }\n          : undefined;\n\n        const dispatcher = createDispatcher({\n          registry: runtime.registry,\n          walled,\n          maxBodySize,\n          builtins,\n          ...(authAwareBuiltins !== undefined ? { authAwareBuiltins } : {}),\n          ...(gatedBuiltins !== undefined ? { gatedBuiltins } : {}),\n          ...(onRequestCompleted !== undefined ? { onRequestCompleted } : {}),\n          shutdownSignal: shutdown.signal,\n          onAuthAbsent,\n          onSignatureRejected,\n          logger: ctx.logger,\n        });\n        unmounts.push(\n          ingress.mountHttp({\n            id: mountId,\n            // Forwarded verbatim, `false` included (see the plugin JSDoc).\n            ...(mount.auth !== undefined ? { auth: mount.auth } : {}),\n            claims: () => {\n              // Routes that demand identity on an unwalled mount need a\n              // validator in scope; with none anywhere the route can never\n              // serve, so refuse at bind rather than 401 every request.\n              if (!walled && !mountAuth.configured) {\n                for (const entry of runtime.registry.values()) {\n                  if (entry.requiresPrincipal) {\n                    throw rcError(\"RC5003\", undefined, {\n                      message: `http mount \"${mount.name}\": route \"${entry.routeId}\" declares .authorize() but no validator is in scope. Set auth on the mount or on servers.${mount.server}.auth.`,\n                    });\n                  }\n                }\n              }\n              const claims: PathClaim[] = [\n                { kind: \"prefix\", path: mount.path },\n              ];\n              // Built-ins are answered inside this mount's dispatcher, so\n              // without an explicit claim they are invisible to bind-time\n              // validation and any other surface claiming the same path wins\n              // silently on dispatch score instead of being refused.\n              //\n              // The ops surface is the deliberate exception: its `/health` is\n              // a strict superset of the constant this one serves, so rather\n              // than refusing the most natural pair of config keys\n              // (`http: {}` alongside `ops: {}`) the built-in stands down and\n              // lets ops answer. Every other collision still fails at bind.\n              const opsOwnsHealth = ingress.hasMount(\"ops\");\n              for (const [path, enabled] of [\n                [\"/health\", isDefaultRoot && healthEnabled && !opsOwnsHealth],\n                [\"/ready\", isDefaultRoot && readyEnabled],\n                [\"/openapi.json\", isDefaultRoot && openapiEnabled],\n              ] as const) {\n                if (enabled)\n                  claims.push({ kind: \"exact\", path, methods: [\"GET\"] });\n              }\n              for (const entry of runtime.registry.values()) {\n                claims.push({\n                  kind: \"pattern\",\n                  matcher: entry.matcher,\n                  staticPrefix: staticPathPrefix(entry.matcher.pattern),\n                  methods: [entry.method],\n                });\n              }\n              return claims;\n            },\n            handler: (request, mountContext) =>\n              dispatcher(\n                request,\n                mountContext.authenticate,\n                mountContext.claimStreamingSlot,\n              ),\n          }),\n        );\n      }\n    },\n    async teardown(ctx: CraftContext) {\n      for (const unmount of unmounts.splice(0)) {\n        try {\n          unmount();\n        } catch (error) {\n          ctx.logger.warn(\n            { err: error },\n            \"HTTP mount failed to unmount cleanly\",\n          );\n        }\n      }\n      for (const runtime of mountRuntimes.values()) {\n        runtime.registry.clear();\n      }\n      ctx.setStore(HTTP_PLUGIN_REGISTERED, false);\n    },\n  };\n}\n\nfunction validate(options: HttpPluginOptions): {\n  mounts: ResolvedMount[];\n  maxBodySize: number;\n} {\n  const removed = options as HttpPluginOptions & {\n    port?: unknown;\n    host?: unknown;\n  };\n  if (removed.port !== undefined || removed.host !== undefined) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        'httpPlugin: `port` and `host` were removed. Define `servers.default: { host, port }` and use `http: { server: \"default\" }`.',\n    });\n  }\n  if (options.server !== undefined && options.server.length === 0) {\n    throw rcError(\"RC5003\", undefined, {\n      message: \"httpPlugin: server name must not be empty\",\n    });\n  }\n  if (options.mounts !== undefined && options.auth !== undefined) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"httpPlugin: `auth` and `mounts` are mutually exclusive. Top-level `auth` is sugar for a single default mount; with `mounts`, set auth per mount.\",\n    });\n  }\n  if (options.mounts !== undefined && options.server !== undefined) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"httpPlugin: `server` and `mounts` are mutually exclusive. Top-level `server` is sugar for a single default mount; with `mounts`, set server per mount.\",\n    });\n  }\n  const maxBodySize = resolveMaxBodySize(options.maxBodySize, \"httpPlugin\");\n  for (const name of [\"health\", \"ready\", \"openapi\"] as const) {\n    const entry = options.builtins?.[name];\n    if (entry === undefined) continue;\n    // Guard against `builtins: { openapi: false as any }` slipping through:\n    // without this check, apply() would silently fall back to the defaults\n    // (and leave /openapi.json publicly exposed).\n    if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `httpPlugin: invalid builtins.${name} ${JSON.stringify(\n          entry,\n        )}. Pass an object with optional { enabled, requireAuth } fields.`,\n      });\n    }\n    if (entry.enabled !== undefined && typeof entry.enabled !== \"boolean\") {\n      throw rcError(\"RC5003\", undefined, {\n        message: `httpPlugin: invalid builtins.${name}.enabled ${JSON.stringify(\n          entry.enabled,\n        )}. Pass a boolean.`,\n      });\n    }\n    if (\n      entry.requireAuth !== undefined &&\n      typeof entry.requireAuth !== \"boolean\"\n    ) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `httpPlugin: invalid builtins.${name}.requireAuth ${JSON.stringify(\n          entry.requireAuth,\n        )}. Pass a boolean.`,\n      });\n    }\n  }\n  const openapiInfo = options.builtins?.openapi?.info;\n  if (openapiInfo !== undefined) {\n    if (\n      typeof openapiInfo !== \"object\" ||\n      openapiInfo === null ||\n      Array.isArray(openapiInfo)\n    ) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `httpPlugin: invalid builtins.openapi.info ${JSON.stringify(\n          openapiInfo,\n        )}. Pass an OpenAPI Info Object (e.g. { title, version, description }).`,\n      });\n    }\n  }\n\n  return { mounts: resolveMounts(options), maxBodySize };\n}\n\nfunction resolveMounts(options: HttpPluginOptions): ResolvedMount[] {\n  if (options.mounts === undefined) {\n    return [\n      {\n        name: \"default\",\n        path: \"/\",\n        server: options.server ?? \"default\",\n        auth: options.auth,\n      },\n    ];\n  }\n  const entries = Object.entries(options.mounts);\n  if (entries.length === 0) {\n    throw rcError(\"RC5003\", undefined, {\n      message: \"httpPlugin: `mounts` must declare at least one mount.\",\n    });\n  }\n  // Keyed by server AND path: two mounts may claim the same path on\n  // different listeners. The registry re-checks claim overlap per server at\n  // bind; this is the same refusal made early, with the config names.\n  const seenPaths = new Map<string, string>();\n  const resolved: ResolvedMount[] = [];\n  for (const [name, definition] of entries) {\n    if (!name) {\n      throw rcError(\"RC5003\", undefined, {\n        message: \"httpPlugin: mount names must not be empty\",\n      });\n    }\n    if (definition.server !== undefined && definition.server.length === 0) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `httpPlugin: mount \"${name}\": server name must not be empty`,\n      });\n    }\n    const server = definition.server ?? \"default\";\n    const path = normalizeMountPath(name, definition);\n    const key = `${server}\\u0000${path}`;\n    const owner = seenPaths.get(key);\n    if (owner !== undefined) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `httpPlugin: mounts \"${owner}\" and \"${name}\" both claim path \"${path}\" on servers.${server}.`,\n      });\n    }\n    seenPaths.set(key, name);\n    resolved.push({ name, path, server, auth: definition.auth });\n  }\n  return resolved;\n}\n\nfunction normalizeMountPath(\n  name: string,\n  definition: HttpMountDefinition,\n): string {\n  return normalizeStaticPathPrefix(\n    definition.path,\n    `httpPlugin: mount \"${name}\"`,\n  );\n}\n","import type {\n  HttpRouteEntry,\n  HttpRouteRegistry,\n  HttpRouteView,\n} from \"./registry\";\n\ninterface OpenApiParameter {\n  name: string;\n  in: \"path\";\n  required: true;\n  schema: { type: \"string\" };\n}\n\ninterface OpenApiOperation {\n  operationId: string;\n  summary?: string;\n  description?: string;\n  parameters?: OpenApiParameter[];\n  responses: Record<string, { description: string }>;\n}\n\ntype OpenApiMethod =\n  \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\" | \"head\" | \"options\";\n\ninterface OpenApiPathItem {\n  get?: OpenApiOperation;\n  post?: OpenApiOperation;\n  put?: OpenApiOperation;\n  patch?: OpenApiOperation;\n  delete?: OpenApiOperation;\n  head?: OpenApiOperation;\n  options?: OpenApiOperation;\n}\n\n/**\n * `info` block of an OpenAPI 3.1 document. Mirrors the OpenAPI Info Object\n * shape (`title`, `version`, optional `description`, `contact`, `license`).\n *\n * Defaults are auto-detected from the host project's `package.json` at\n * plugin apply time:\n *\n * - `title`   -> `package.json` `name` (literal, including any `@scope/`).\n * - `version` -> `package.json` `version`.\n *\n * Description / contact / license are **not** auto-pulled even when\n * present in `package.json`: those fields commonly carry internal\n * context (TODO notes, author emails, license boilerplate) that should\n * not leak into a publicly served document by default. Set them\n * explicitly to publish them.\n *\n * Auto-detection deliberately yields nothing when the nearest\n * `package.json` is a workspace container (a `workspaces` field, or a\n * `pnpm-workspace.yaml` beside it): a monorepo root's private, often\n * stale identity must not be advertised on a publicly served document.\n * See `findPackageInfo` for the full resolution rules.\n *\n * Any explicit field passed by the caller wins over the auto-detected\n * default; no usable `package.json` falls back to the hardcoded\n * \"Routecraft HTTP API\" / \"0.0.0\".\n */\nexport interface HttpOpenApiInfo {\n  title?: string;\n  version?: string;\n  description?: string;\n  contact?: { name?: string; url?: string; email?: string };\n  license?: { name: string; identifier?: string; url?: string };\n}\n\ninterface OpenApiDocument {\n  openapi: \"3.1.0\";\n  info: HttpOpenApiInfo & { title: string; version: string };\n  paths: Record<string, OpenApiPathItem>;\n}\n\n/**\n * Translate the http plugin's route registry into an OpenAPI 3.1 document.\n *\n * Best-effort by design in v1: paths, methods, summaries, descriptions, and\n * path-parameter slots are all emitted, but request/response body schemas\n * come back as the empty schema `{}` because Standard Schema does not\n * define a generic `toJsonSchema()`. The follow-up issue will plug in\n * optional-peer converters (`@valibot/to-json-schema`, `zod-to-json-schema`,\n * etc.) via `loadOptionalPeer`.\n */\nexport function buildOpenApiDocument(\n  registry: HttpRouteView,\n  info?: HttpOpenApiInfo,\n): OpenApiDocument {\n  const resolvedInfo: HttpOpenApiInfo & { title: string; version: string } = {\n    title: info?.title ?? \"Routecraft HTTP API\",\n    version: info?.version ?? \"0.0.0\",\n  };\n  if (info?.description) resolvedInfo.description = info.description;\n  if (info?.contact) resolvedInfo.contact = info.contact;\n  if (info?.license) resolvedInfo.license = info.license;\n\n  const doc: OpenApiDocument = {\n    openapi: \"3.1.0\",\n    info: resolvedInfo,\n    paths: {},\n  };\n\n  for (const entry of registry.values()) {\n    const path = patternToOpenApi(entry.matcher.pattern);\n    const method = entry.method.toLowerCase() as OpenApiMethod;\n    const item = (doc.paths[path] ??= {});\n    // A route with a responder documents no success code: the answer comes\n    // from a function and nothing here can know what it returns. Its\n    // rejection codes stay, since every gate still runs ahead of it.\n    const successResponses = entry.respond\n      ? {}\n      : {\n          \"200\": { description: \"Successful response\" },\n          \"204\": { description: \"No content\" },\n        };\n    const op: OpenApiOperation = {\n      operationId: entry.routeId,\n      responses: {\n        ...successResponses,\n        \"400\": { description: \"Bad request\" },\n        \"401\": { description: \"Unauthorized\" },\n        \"403\": { description: \"Forbidden\" },\n        \"404\": { description: \"Not found\" },\n        \"405\": { description: \"Method not allowed\" },\n        \"413\": { description: \"Payload too large\" },\n        \"500\": { description: \"Internal server error\" },\n      },\n    };\n    const summary = entry.discovery?.title;\n    if (summary) op.summary = summary;\n    const description = entry.discovery?.description;\n    if (description) op.description = description;\n    if (entry.matcher.paramNames.length > 0) {\n      op.parameters = entry.matcher.paramNames.map<OpenApiParameter>(\n        (name) => ({\n          name,\n          in: \"path\",\n          required: true,\n          schema: { type: \"string\" },\n        }),\n      );\n    }\n    item[method] = op;\n  }\n\n  return doc;\n}\n\n/**\n * Convert a routecraft pattern (`:param`) into the OpenAPI form (`{param}`).\n * Trailing slashes are preserved as-is since OpenAPI treats `/x` and `/x/`\n * as distinct paths.\n */\nfunction patternToOpenApi(pattern: string): string {\n  // Match any non-empty param name that doesn't contain `/` or `{}`; this\n  // covers all names the path-matcher accepts (including hyphens etc.).\n  return pattern.replace(/:([^/{}]+)/g, \"{$1}\");\n}\n\n/**\n * Re-export for ergonomic typing inside the tests.\n */\nexport type { HttpRouteEntry, HttpRouteRegistry };\n","import { missingCredentialReason } from \"./auth.ts\";\nimport { bearerChallenge } from \"../server/protected-resource.ts\";\n\n/**\n * The JSON response every routecraft-owned HTTP surface answers with.\n *\n * Shared so the wire format is decided once: a change to it (a `cache-control`\n * on probe responses, a `vary` header) would otherwise be applied to whichever\n * copy the author happened to be looking at, and the surfaces on one listener\n * would drift apart.\n */\nexport function jsonResponse(\n  payload: unknown,\n  init: { status: number; headers?: Record<string, string> },\n): Response {\n  return new Response(JSON.stringify(payload), {\n    status: init.status,\n    headers: {\n      \"content-type\": \"application/json; charset=utf-8\",\n      ...(init.headers ?? {}),\n    },\n  });\n}\n\n/**\n * The 401 every routecraft-owned surface answers when a credential is\n * required and none was presented.\n *\n * Shared alongside {@link jsonResponse} for the same reason: the http\n * dispatcher and the ops management tiers both refuse a credential-free\n * caller, and two copies of this shape would drift the moment one of them\n * gained a header. The reason string comes from `missingCredentialReason`\n * so the body and the `auth:rejected` event it pairs with cannot disagree.\n */\nexport function missingCredentialResponse(\n  scheme: string,\n  requestUrl: string,\n): Response {\n  return jsonResponse(\n    { error: \"unauthorized\", reason: missingCredentialReason(scheme) },\n    { status: 401, headers: bearerChallengeHeaders(scheme, requestUrl) },\n  );\n}\n\n/**\n * The `WWW-Authenticate` header a refusal carries, present only for the\n * bearer scheme.\n *\n * RFC 7235: announcing `Bearer` to an api-key client points it at a\n * ceremony it cannot perform. The bearer challenge carries the RFC 9728\n * `resource_metadata` hint, so a refused caller can discover who issues.\n * One helper so every refusal decides the scheme question the same way.\n */\nexport function bearerChallengeHeaders(\n  scheme: string | undefined,\n  requestUrl: string,\n  params?: Record<string, string>,\n): Record<string, string> {\n  if (scheme !== \"bearer\") return {};\n  return {\n    \"www-authenticate\": bearerChallenge({\n      requestUrl,\n      ...(params !== undefined ? { params } : {}),\n    }),\n  };\n}\n\n/**\n * The 403 a caller gets when its identity is valid and its credential lacks\n * a scope: the ops tier check's refusal and a route's own `RC5038` alike,\n * so a client reads both the same way.\n *\n * `anyOf` marks a list that is an accepted set, of which one entry\n * suffices, with `scope_mode: \"any\"`; read as requirements it would send a\n * consent flow after every member of the family. The challenge then omits\n * `scope`, since RFC 6750 reads that attribute as the scope the token needs.\n */\nexport function insufficientScopeResponse(\n  scheme: string | undefined,\n  requestUrl: string,\n  refusal: { scope: string; anyOf?: boolean },\n): Response {\n  const { scope, anyOf = false } = refusal;\n  return jsonResponse(\n    {\n      error: \"forbidden\",\n      reason: \"insufficient_scope\",\n      scope,\n      ...(anyOf ? { scope_mode: \"any\" } : {}),\n    },\n    {\n      status: 403,\n      headers: bearerChallengeHeaders(scheme, requestUrl, {\n        error: \"insufficient_scope\",\n        ...(anyOf || scope.length === 0 ? {} : { scope }),\n      }),\n    },\n  );\n}\n\n/**\n * The empty-body 405 every routecraft-owned surface answers.\n *\n * Shared for the same reason as the shapes above: the ops mount, the health\n * report and the http built-ins all refuse a wrong method identically, and\n * separate copies drift the first time one gains a header.\n */\nexport function methodNotAllowed(allow: string): Response {\n  return new Response(null, { status: 405, headers: { Allow: allow } });\n}\n","import type { BuiltinHandler } from \"./dispatcher\";\nimport { buildOpenApiDocument, type HttpOpenApiInfo } from \"./openapi\";\nimport type { HttpRouteView } from \"./registry\";\n\nimport { jsonResponse } from \"./response.ts\";\n\nexport interface BuiltinsOptions {\n  registry: HttpRouteView;\n  /** Whether the always-on built-ins layer should serve `/health`. */\n  serveHealth: boolean;\n  /**\n   * Mode for the always-on built-ins layer's `/ready` handling.\n   *\n   * - `\"off\"`: do not serve here. The path is either disabled entirely\n   *   (`enabled: false`) or routed through the auth-aware layer\n   *   (`requireAuth: true` with auth configured).\n   * - `\"full\"`: serve `{ status: \"ready\", routes }`. This is the layer\n   *   used when `requireAuth: false`, or when `requireAuth: true` but no\n   *   global auth is configured (nothing to authenticate against).\n   */\n  ready: \"off\" | \"full\";\n  /** Whether the always-on built-ins layer should serve `/openapi.json`. */\n  serveOpenApi: boolean;\n  /**\n   * OpenAPI `info` block used when serving `/openapi.json` (either layer).\n   * Already resolved by the plugin: package.json auto-detected defaults\n   * layered under the caller's explicit overrides.\n   */\n  openapiInfo?: HttpOpenApiInfo;\n}\n\n/**\n * Always-on endpoints registered before user routes. The dispatcher consults\n * built-ins only after the user registry returns no match, so a user route\n * registered at the same path takes precedence.\n *\n * The plugin decides which of these to serve based on its `builtins` config;\n * a path served by the auth-aware or gated layer (`/ready` or\n * `/openapi.json` with `requireAuth: true` on a walled mount) is omitted\n * from this handler so the dispatcher runs the auth middleware first.\n *\n * Returns `null` for any other request so the dispatcher can answer 404.\n */\nexport function createBuiltins(opts: BuiltinsOptions): BuiltinHandler {\n  return function builtinHandler(req: Request, pathname: string) {\n    const isKnown =\n      (pathname === \"/health\" && opts.serveHealth) ||\n      (pathname === \"/ready\" && opts.ready !== \"off\") ||\n      (pathname === \"/openapi.json\" && opts.serveOpenApi);\n    if (!isKnown) return null;\n\n    if (req.method !== \"GET\") {\n      return new Response(null, { status: 405, headers: { Allow: \"GET\" } });\n    }\n\n    if (pathname === \"/health\") {\n      return jsonResponse({ status: \"ok\" }, { status: 200 });\n    }\n\n    if (pathname === \"/ready\") {\n      return jsonResponse(\n        { status: \"ready\", routes: opts.registry.size },\n        { status: 200 },\n      );\n    }\n\n    // pathname === \"/openapi.json\" && opts.serveOpenApi (covered by isKnown above)\n    const doc = buildOpenApiDocument(opts.registry, opts.openapiInfo);\n    return jsonResponse(doc, { status: 200 });\n  };\n}\n\n/**\n * The dispatcher invokes this handler after the auth middleware admits the\n * request. Used by the plugin when `openapi.requireAuth === true` and an\n * `auth` strategy is configured.\n */\nexport function createOpenApiGatedHandler(\n  registry: HttpRouteView,\n  info?: HttpOpenApiInfo,\n): BuiltinHandler {\n  return function openApiHandler(req, pathname) {\n    if (pathname !== \"/openapi.json\") return null;\n    if (req.method !== \"GET\") {\n      return new Response(null, { status: 405, headers: { Allow: \"GET\" } });\n    }\n    return jsonResponse(buildOpenApiDocument(registry, info), { status: 200 });\n  };\n}\n\n/**\n * Build the `/ready` response when the path is served by the dispatcher's\n * auth-aware layer (`requireAuth: true` on a walled mount). Always returns\n * 200 so k8s readiness probes keep working without a credential; the body\n * varies with the auth result. Spring Boot Actuator calls this same pattern\n * `show-details: when-authorized`.\n */\nexport function buildReadyResponse(\n  registry: HttpRouteView,\n  isAuthenticated: boolean,\n): Response {\n  return isAuthenticated\n    ? jsonResponse({ status: \"ready\", routes: registry.size }, { status: 200 })\n    : jsonResponse({ status: \"ready\" }, { status: 200 });\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { rcCodeOf } from \"../brand.ts\";\nimport { formatIssuePath } from \"../error.ts\";\nimport {\n  isAuthorizationRefusal,\n  type InsufficientAuthority,\n} from \"../auth/authorize.ts\";\nimport type { Principal } from \"../auth/types.ts\";\nimport { isInputValidationFailure } from \"./validation.ts\";\n\n/** One schema issue as a door shows it to a caller: where, and what. */\nexport interface WireIssue {\n  /** Dot-joined issue path, absent for an issue about the whole value. */\n  path?: string;\n  message: string;\n}\n\n/**\n * Schema issues bounded for the wire: the first {@link MAX_WIRE_ISSUES}, and\n * how many more there were.\n */\nexport interface WireIssues {\n  issues: WireIssue[];\n  /** Issues left out of `issues`; `0` when all of them fit. */\n  omitted: number;\n}\n\n/**\n * How many schema issues a door sends. A payload with thousands of bad array\n * items would otherwise produce an answer proportional to the damage.\n */\nexport const MAX_WIRE_ISSUES = 20;\n\n/**\n * The longest path or message a wire issue carries. A path echoes the\n * caller's own keys, so a record key of a megabyte repeated across every\n * issue would make the answer many times the size of the request.\n */\nconst MAX_WIRE_ISSUE_TEXT = 256;\n\n/**\n * Cut by code point, ellipsis included, so a cut never splits a surrogate\n * pair. Only the head is walked: a code point spans at most two UTF-16\n * units, so twice the cap in units holds every code point that can survive.\n */\nfunction clip(text: string): string {\n  if (text.length <= MAX_WIRE_ISSUE_TEXT) return text;\n  const chars = Array.from(text.slice(0, MAX_WIRE_ISSUE_TEXT * 2));\n  return text.length <= MAX_WIRE_ISSUE_TEXT * 2 &&\n    chars.length <= MAX_WIRE_ISSUE_TEXT\n    ? text\n    : `${chars.slice(0, MAX_WIRE_ISSUE_TEXT - 3).join(\"\")}...`;\n}\n\n/**\n * Reduce Standard Schema issues to what a door may put on the wire: each\n * issue's path and message, at most {@link MAX_WIRE_ISSUES} of them, each\n * clipped to {@link MAX_WIRE_ISSUE_TEXT} characters.\n *\n * The message is the schema's own text, so a schema author's custom message\n * reaches the caller verbatim. A non-string message becomes `\"invalid\"`.\n *\n * @param issues - The issues a schema returned\n * @returns The first issues as path and message, and the count left out\n */\nexport function wireIssues(\n  issues: readonly StandardSchemaV1.Issue[],\n): WireIssues {\n  return {\n    issues: issues.slice(0, MAX_WIRE_ISSUES).map((issue) => {\n      const path = formatIssuePath(issue.path);\n      return {\n        ...(path !== undefined ? { path: clip(path) } : {}),\n        message:\n          typeof issue.message === \"string\" ? clip(issue.message) : \"invalid\",\n      };\n    }),\n    omitted: Math.max(0, issues.length - MAX_WIRE_ISSUES),\n  };\n}\n\n/**\n * A route failure the caller caused, classified by what the caller can do\n * about it. Each door renders it in its own protocol: an http status and\n * body, an MCP tool error, and so on.\n *\n * - `input`: the route's `.input()` schema refused what the caller sent.\n *   Carries the part and the issues, never the error message, which names\n *   the route.\n * - `unauthenticated`: the route needs an identity and the caller presented\n *   none.\n * - `expired`: the caller's credential expired while the route ran.\n * - `insufficient_permissions`: the identity is not permitted, as itself or\n *   through the delegation it arrived by. One class for four codes, because\n *   the caller's remedy is the same and naming the check that failed would\n *   tell a prober which part of the policy it tripped.\n * - `insufficient_scope`: the credential lacks a scope. `scopes` lists the\n *   missing ones, or with `anyOf` the whole accepted set, of which one\n *   suffices.\n */\nexport type CallerRefusal =\n  | ({ kind: \"input\"; in: \"body\" | \"headers\" } & WireIssues)\n  | { kind: \"unauthenticated\" }\n  | { kind: \"expired\" }\n  | { kind: \"insufficient_permissions\" }\n  | { kind: \"insufficient_scope\"; scopes: string[]; anyOf: boolean };\n\n/** What a door knows about the call whose route failed. */\nexport interface CallerRefusalOrigin {\n  /**\n   * The route the door dispatched. A failure raised by any other route\n   * reached this one through a `direct()` call, and what that route refused\n   * was this route's doing rather than the caller's.\n   */\n  routeId: string;\n  /**\n   * The principal the door put on the exchange, by reference, or `undefined`\n   * when it put none. A refusal maps only when it is this exact principal\n   * that `authorize()` refused.\n   */\n  principal: Principal | undefined;\n  /**\n   * Whether presenting a credential could have changed the outcome: the\n   * door consulted a validator and the call went without a principal.\n   *\n   * Decides whether a missing principal (`RC5012`) is the caller's to fix.\n   * When it is not, the door never reads a credential for this route, so\n   * telling the caller to present one would send it after something that\n   * changes nothing, and the failure stays the route's.\n   */\n  credentialCouldHelp?: boolean;\n}\n\n/**\n * Classify a route failure the caller caused, or return `undefined` for one\n * the instance owns.\n *\n * One classification for every door that runs a route on a caller's behalf\n * (the `http()` source, the ops dispatch mount, the MCP server), so the same\n * refusal cannot be the caller's on one door and the instance's on another.\n * A door answers everything this returns `undefined` for with the error\n * code alone: an error message routinely interpolates the cause, and the\n * cause of a route failure is whatever its steps threw, hostnames, file\n * paths and upstream response text included.\n *\n * Attribution is by origin, never by code:\n *\n * - `RC5065` maps only when it carries the `InputValidationFailure` detail\n *   for the dispatched route. One without it was thrown by something other\n *   than `.input()`, and one naming another route came up through\n *   `direct()`, so neither is the caller's.\n * - The authorization codes map only when {@link isAuthorizationRefusal}\n *   says `authorize()` raised them on the dispatched route about the\n *   principal the door admitted. The same codes come out of adapters for an\n *   upstream login refused, and a check of an identity the pipeline swapped\n *   in (`.authenticate()`, a delegation) refused the instance; both stay the\n *   instance's, which also keeps an internal identity's requirements off the\n *   wire. `RC5012` additionally needs `credentialCouldHelp`. `RC5023` (a\n *   self-asserted principal) and `RC5043` (one restored from a deferral) are\n *   never mapped: a door brands every principal it verifies, so either one\n *   was put there by the route.\n *\n * @param error - What the route threw\n * @param origin - The dispatched route and the principal the door admitted\n * @returns The refusal to render, or `undefined` when the failure is the instance's\n */\nexport function callerRefusalOf(\n  error: unknown,\n  origin: CallerRefusalOrigin,\n): CallerRefusal | undefined {\n  const code = rcCodeOf(error);\n  if (code === \"RC5065\") {\n    const cause = (error as Error).cause;\n    if (\n      !isInputValidationFailure(cause) ||\n      cause.invalid.routeId !== origin.routeId\n    ) {\n      return undefined;\n    }\n    return {\n      kind: \"input\",\n      in: cause.invalid.in,\n      ...wireIssues(cause.invalid.issues),\n    };\n  }\n  if (\n    !isAuthorizationRefusal(error, {\n      routeId: origin.routeId,\n      principal: origin.principal,\n    })\n  ) {\n    return undefined;\n  }\n  switch (code) {\n    case \"RC5012\":\n      return origin.credentialCouldHelp === true\n        ? { kind: \"unauthenticated\" }\n        : undefined;\n    case \"RC5020\":\n      return { kind: \"expired\" };\n    case \"RC5015\":\n    case \"RC5034\":\n    case \"RC5035\":\n    case \"RC5036\":\n      return { kind: \"insufficient_permissions\" };\n    case \"RC5038\": {\n      const missing = (\n        error.cause as Partial<InsufficientAuthority> | undefined\n      )?.missing;\n      return {\n        kind: \"insufficient_scope\",\n        scopes: missing?.scopes ?? [],\n        anyOf: missing?.mode === \"any\",\n      };\n    }\n    default:\n      return undefined;\n  }\n}\n","import type { Principal } from \"../../auth/types.ts\";\nimport { callerRefusalOf } from \"../../pipeline/caller-refusal.ts\";\nimport {\n  bearerChallengeHeaders,\n  insufficientScopeResponse,\n  jsonResponse,\n} from \"./response.ts\";\n\n/**\n * What a door knows about the request whose route failed.\n *\n * @internal\n */\nexport interface CallerRefusalContext {\n  /**\n   * The route the door dispatched. A failure raised by any other route\n   * reached this one through a `direct()` call, and what that route refused\n   * was this route's doing rather than the caller's.\n   */\n  routeId: string;\n  /** The request URL, for the RFC 9728 hint on a bearer challenge. */\n  requestUrl: string;\n  /**\n   * The principal the door admitted, if any. Its scheme picks the\n   * challenge, and a refusal maps only when it is this exact principal\n   * that `authorize()` refused.\n   */\n  principal?: Principal | undefined;\n  /**\n   * What the door answers a caller who had to authenticate and did not,\n   * supplied only when a credential could have changed the outcome: the\n   * door consulted a validator and the request went without a principal.\n   *\n   * Decides whether a missing principal (`RC5012`) is the caller's to fix.\n   * Unset, it is not: the door never reads a credential for this route, so\n   * a 401 would send the caller to present one that would change nothing,\n   * and the failure stays the route's.\n   */\n  unauthenticated?: (() => Response) | undefined;\n}\n\n/**\n * Answer a route failure the caller caused with a client status, or return\n * `undefined` for one the instance owns.\n *\n * The http rendering of {@link callerRefusalOf}, which decides whose failure\n * it is. Shared by the `http()` source and the ops dispatch mount, so the\n * same refusal cannot be a 403 on one and a 500 on the other. Each door\n * keeps its own fallthrough 500 and whatever codes only it answers.\n *\n * - `input`: 400 with the part that failed and the schema's issues, the\n *   ones left out counted in `truncated`.\n * - `unauthenticated`: the door's own unauthenticated answer.\n * - `expired`: 401 `expired`, with an RFC 6750 `invalid_token` challenge on\n *   a bearer principal so the client refreshes.\n * - `insufficient_permissions`: 403 `insufficient_permissions`.\n * - `insufficient_scope`: 403 `insufficient_scope`, in the shape the ops\n *   tier check already answers, naming the scopes.\n *\n * @internal\n */\nexport function callerRefusalResponse(\n  error: unknown,\n  context: CallerRefusalContext,\n): Response | undefined {\n  const refusal = callerRefusalOf(error, {\n    routeId: context.routeId,\n    principal: context.principal,\n    credentialCouldHelp: context.unauthenticated !== undefined,\n  });\n  if (refusal === undefined) return undefined;\n  const scheme = context.principal?.scheme;\n  switch (refusal.kind) {\n    case \"input\":\n      return jsonResponse(\n        {\n          error: \"bad request\",\n          code: \"RC5065\",\n          in: refusal.in,\n          issues: refusal.issues,\n          ...(refusal.omitted > 0 ? { truncated: refusal.omitted } : {}),\n        },\n        { status: 400 },\n      );\n    case \"unauthenticated\":\n      return context.unauthenticated?.();\n    case \"expired\":\n      return jsonResponse(\n        { error: \"unauthorized\", reason: \"expired\" },\n        {\n          status: 401,\n          headers: bearerChallengeHeaders(scheme, context.requestUrl, {\n            error: \"invalid_token\",\n          }),\n        },\n      );\n    case \"insufficient_permissions\":\n      return jsonResponse(\n        { error: \"forbidden\", reason: \"insufficient_permissions\" },\n        { status: 403 },\n      );\n    case \"insufficient_scope\":\n      return insufficientScopeResponse(scheme, context.requestUrl, {\n        scope: refusal.scopes.join(\" \"),\n        anyOf: refusal.anyOf,\n      });\n  }\n}\n","import { jsonResponse, missingCredentialResponse } from \"./response.ts\";\nimport { callerRefusalResponse } from \"./caller-refusal.ts\";\nimport { anySignal } from \"../../shared/abort.ts\";\nimport { logger as defaultLogger } from \"../../logger\";\nimport {\n  type Exchange,\n  type ExchangeHeaders,\n  HeadersKeys,\n} from \"../../exchange\";\nimport { isRoutecraftError } from \"../../brand\";\nimport { rcError } from \"../../error\";\nimport { isDeferred } from \"../../deferral/deferred\";\nimport { principalExpirySignal } from \"../../auth/expiry.ts\";\nimport type { Principal } from \"../../auth/types\";\nimport type {\n  HttpMethod,\n  HttpResponseDescriptor,\n  HttpResponseHint,\n} from \"../../adapters/http/types\";\nimport type { AuthResult } from \"./auth\";\nimport type { HttpRouteEntry, HttpRouteRegistry } from \"./registry\";\nimport {\n  isSignatureRejection,\n  parseRequestBody,\n  type HttpBodyError,\n} from \"./body-parser\";\nimport {\n  isAsyncIterable,\n  isReadableStream,\n  SSE_CACHE_CONTROL,\n  SSE_CONTENT_TYPE,\n  streamResponseBody,\n} from \"./sse\";\nimport type { HttpWebhookSignatureRejection } from \"./webhook-signature\";\n\n/** Function called once per completed dispatch when per-request events are enabled. */\nexport type RequestCompletedHandler = (event: {\n  method: HttpMethod;\n  path: string;\n  status: number;\n  durationMs: number;\n  routeId?: string;\n  principal?: Pick<Principal, \"subject\"> | undefined;\n  /** Set when a streaming body failed after its status line was sent. */\n  error?: { name: string; message: string };\n}) => void;\n\n/** Synthetic handler for built-in endpoints (/health, /ready, /openapi.json). */\nexport type BuiltinHandler = (\n  req: Request,\n  pathname: string,\n) => Response | Promise<Response> | null;\n\n/**\n * Built-ins that require authentication before serving. The dispatcher checks\n * `paths` first (cheap, no commit to a response) and only invokes `handler`\n * after the auth middleware admits.\n */\nexport interface GatedBuiltins {\n  paths: ReadonlySet<string>;\n  handler: BuiltinHandler;\n}\n\n/**\n * Built-ins that always return a response (200) but vary the body based on\n * whether the request was authenticated. Used by `/ready` under\n * `requireAuth: true` on a walled mount: anonymous callers get a minimal\n * body, authenticated callers get the full one. The endpoint never returns\n * 401 so k8s readiness probes keep working without a credential.\n */\nexport interface AuthAwareBuiltins {\n  paths: ReadonlySet<string>;\n  handler: (\n    req: Request,\n    pathname: string,\n    isAuthenticated: boolean,\n  ) => Response | Promise<Response> | null;\n}\n\nexport interface DispatcherOptions {\n  registry: HttpRouteRegistry;\n  /**\n   * The mount has an effective validator and did not opt out: every route\n   * requires an admitted credential. When false, routes are served without\n   * credentials ever being inspected, except entries flagged\n   * `requiresPrincipal` (a route-entry `.authorize()`), which pull\n   * verification individually.\n   */\n  walled: boolean;\n  maxBodySize: number;\n  builtins: BuiltinHandler;\n  /** Optional gated built-ins (e.g. /openapi.json under `access: \"authenticated\"`). */\n  gatedBuiltins?: GatedBuiltins;\n  /** Optional auth-aware built-ins (/ready under `requireAuth: true`). */\n  authAwareBuiltins?: AuthAwareBuiltins;\n  onRequestCompleted?: RequestCompletedHandler;\n  /**\n   * Fires when the context begins stopping.\n   *\n   * A streaming response is in-flight work for as long as it runs, so\n   * without this a graceful close waits out its whole grace window on a\n   * stream that would happily have ended on request. Combined with the\n   * client's own signal, so either end can close the stream.\n   */\n  shutdownSignal?: AbortSignal;\n  /**\n   * Called when the dispatcher itself synthesises a 401 because a route\n   * with `auth: \"required\"` saw no credential. The plugin uses this to\n   * emit `auth:rejected` for the missing-credential case: the shared\n   * ingress only emits auth events when the `authenticate` thunk resolves\n   * an admit or a reject, and `absent` is neither, so this hook is the one\n   * place that case can still surface.\n   */\n  onAuthAbsent?: (scheme: string) => void;\n  /**\n   * Called when a route's webhook-signature gate rejects a request (RC5039\n   * out of the body parser). The plugin uses this to emit `auth:rejected`\n   * with `scheme: \"signature\"`, keeping signature failures on the same\n   * observability surface as credential failures.\n   */\n  onSignatureRejected?: (reason: HttpWebhookSignatureRejection) => void;\n  /** Optional logger; defaults to the framework logger. */\n  logger?: typeof defaultLogger;\n}\n\n/**\n * Build the Web-Fetch handler used by both the Bun and Node servers. The\n * dispatcher does not know which server it is talking to -- it only deals in\n * `Request` and `Response`. Pure-ish: state lives in the supplied `registry`,\n * which the plugin owns.\n */\nexport function createDispatcher(\n  opts: DispatcherOptions,\n): (\n  req: Request,\n  authenticate?: () => Promise<AuthResult | undefined>,\n  claimStreamingSlot?: () => (() => void) | undefined,\n) => Promise<Response> {\n  const log = opts.logger ?? defaultLogger;\n\n  return async function dispatch(\n    req: Request,\n    authenticate?: () => Promise<AuthResult | undefined>,\n    claimStreamingSlot?: () => (() => void) | undefined,\n  ): Promise<Response> {\n    const started = performance.now();\n    const url = new URL(req.url);\n    const method = req.method.toUpperCase() as HttpMethod;\n    const pathname = url.pathname;\n    // The ingress-supplied thunk memoizes per request and emits the auth\n    // events at its single resolution, so calling it from more than one\n    // branch below never verifies twice.\n    const resolveAuth = async (): Promise<AuthResult | undefined> =>\n      authenticate?.();\n\n    // 1. Match against the user registry first. Built-ins act as a default\n    //    when no user route claims the path, so users can override /health\n    //    et al by registering their own route.\n    let methodMatch: {\n      entry: HttpRouteEntry;\n      params: Readonly<Record<string, string>>;\n    } | null = null;\n    const pathMatchMethods: HttpMethod[] = [];\n    for (const entry of opts.registry.values()) {\n      const params = entry.matcher.match(pathname);\n      if (!params) continue;\n      pathMatchMethods.push(entry.method);\n      if (entry.method === method) {\n        methodMatch = { entry, params };\n        break;\n      }\n    }\n\n    // 2. Built-ins answer when no user route matched. Three layers:\n    //      a) Public: bypass auth and per-request events (probe-heavy\n    //         deployments). Always-200.\n    //      b) Auth-aware: run auth without forcing 401. The handler returns\n    //         a richer response when admitted, a minimal one otherwise.\n    //         Used by /ready under `requireAuth: true` so readiness probes\n    //         keep working without a credential.\n    //      c) Gated: require admission, 401 otherwise. Used by\n    //         /openapi.json under `requireAuth: true`.\n    if (!methodMatch && pathMatchMethods.length === 0) {\n      // Public built-ins (and plain 404s) bypass auth entirely: probes and\n      // unmatched paths must never pay validator work or emit auth events.\n      const builtinRes = await opts.builtins(req, pathname);\n      if (builtinRes) return builtinRes;\n\n      if (opts.authAwareBuiltins?.paths.has(pathname)) {\n        if (req.method !== \"GET\") {\n          return new Response(null, {\n            status: 405,\n            headers: { Allow: \"GET\" },\n          });\n        }\n        let isAuthenticated = false;\n        const result = await resolveAuth();\n        isAuthenticated = result?.kind === \"admit\";\n        const authAwareRes = await opts.authAwareBuiltins.handler(\n          req,\n          pathname,\n          isAuthenticated,\n        );\n        if (authAwareRes) return authAwareRes;\n      }\n\n      if (opts.gatedBuiltins?.paths.has(pathname)) {\n        const result = await resolveAuth();\n        // Built-ins never produce request:completed events regardless of\n        // auth outcome; only emit for user-registered routes. Treat\n        // `absent` like `reject`: gated built-ins are by definition\n        // `openapi.access: \"authenticated\"`, so a missing credential is\n        // a 401 just like a bad one. The ingress emits `auth:rejected` for\n        // `reject` at resolution; `absent` surfaces through the same\n        // `onAuthAbsent` hook the user-route path uses.\n        if (result?.kind === \"reject\") return result.response;\n        if (result?.kind === \"absent\") {\n          safeNotify(() => opts.onAuthAbsent?.(result.scheme));\n          return missingCredentialResponse(result.scheme, req.url);\n        }\n        const gatedRes = await opts.gatedBuiltins.handler(req, pathname);\n        if (gatedRes) return gatedRes;\n      }\n    }\n\n    if (!methodMatch) {\n      if (pathMatchMethods.length > 0) {\n        const response = jsonResponse(\n          { error: \"method not allowed\", allowed: pathMatchMethods },\n          { status: 405, headers: { Allow: pathMatchMethods.join(\", \") } },\n        );\n        emitCompleted(opts, {\n          method,\n          path: pathname,\n          status: 405,\n          durationMs: ms(started),\n        });\n        return response;\n      }\n      const response = jsonResponse(\n        { error: \"not found\", path: pathname },\n        { status: 404 },\n      );\n      emitCompleted(opts, {\n        method,\n        path: pathname,\n        status: 404,\n        durationMs: ms(started),\n      });\n      return response;\n    }\n\n    const { entry, params } = methodMatch;\n\n    // 3. Admission per the mount posture. The mount is the wall: `walled`\n    //    demands an admitted credential for every route. On a public mount\n    //    (`walled: false`) credentials are never inspected, except for a\n    //    route that declares `.authorize()` (`requiresPrincipal`), which\n    //    can only make itself stricter, never looser.\n    let principal: Principal | undefined;\n    // Kept beside the principal rather than re-read from config later: the\n    // stream expiry check below re-examines this very credential, and the\n    // boundary it applies has to be the one that admitted it.\n    let clockToleranceSec = 0;\n    if (opts.walled || entry.requiresPrincipal) {\n      const result = await resolveAuth();\n      if (!result) {\n        // No validator anywhere. Unreachable for `walled` (a wall implies\n        // a validator) and for `requiresPrincipal` (refused at bind); kept\n        // as a served fallthrough so a future gap fails open loudly in\n        // authorize() (RC5012) rather than silently 500ing here.\n      } else if (result.kind === \"reject\") {\n        emitCompleted(opts, {\n          method,\n          path: entry.matcher.pattern,\n          status: result.response.status,\n          durationMs: ms(started),\n          routeId: entry.routeId,\n        });\n        return result.response;\n      } else if (result.kind === \"absent\") {\n        safeNotify(() => opts.onAuthAbsent?.(result.scheme));\n        const response = missingCredentialResponse(result.scheme, req.url);\n        emitCompleted(opts, {\n          method,\n          path: entry.matcher.pattern,\n          status: response.status,\n          durationMs: ms(started),\n          routeId: entry.routeId,\n        });\n        return response;\n      } else {\n        principal = result.principal;\n        clockToleranceSec = result.clockToleranceSec;\n      }\n    }\n\n    // 4. Parse the body. Failures here are user-input errors (malformed JSON,\n    //    body too large, failed signature) -> 4xx; never 5xx. The signature\n    //    gate runs inside parseRequestBody, after the maxBodySize checks and\n    //    before content-type parsing.\n    let parsedBody: unknown;\n    let rawBytes: Uint8Array | undefined;\n    try {\n      const parsed = await parseRequestBody(req, {\n        maxBodySize: opts.maxBodySize,\n        ...(entry.signature !== undefined\n          ? { signature: entry.signature }\n          : {}),\n        ...(entry.rawBody ? { rawBody: true } : {}),\n      });\n      parsedBody = parsed.body;\n      // Only retain the wire buffer when the route asked for it; holding it\n      // unconditionally would pin up to maxBodySize per in-flight request on\n      // routes that never opted in.\n      rawBytes = entry.rawBody ? parsed.rawBytes : undefined;\n    } catch (err) {\n      if (isSignatureRejection(err)) {\n        // Signature rejections use the same wire shape as the other 401s\n        // (missing/invalid credential). No WWW-Authenticate: the mechanism\n        // is not an RFC 7235 challenge scheme, matching the apiKey\n        // precedent. The bounded reason rides the typed field on the error,\n        // never err.message (see .standards/security.md section 10).\n        safeNotify(() => opts.onSignatureRejected?.(err.signatureRejection));\n        const response = jsonResponse(\n          { error: \"unauthorized\", reason: err.signatureRejection },\n          { status: err.httpStatus },\n        );\n        emitCompleted(opts, {\n          method,\n          path: entry.matcher.pattern,\n          status: err.httpStatus,\n          durationMs: ms(started),\n          routeId: entry.routeId,\n        });\n        return response;\n      }\n      const status = isRoutecraftError(err)\n        ? ((err as HttpBodyError).httpStatus ?? 400)\n        : 400;\n      const message =\n        err instanceof Error ? err.message : \"request body could not be parsed\";\n      const response = jsonResponse(\n        { error: \"bad request\", message },\n        { status },\n      );\n      emitCompleted(opts, {\n        method,\n        path: entry.matcher.pattern,\n        status,\n        durationMs: ms(started),\n        routeId: entry.routeId,\n      });\n      return response;\n    }\n\n    // 5. Build the headers passed to the runtime handler. The parsed request\n    //    envelope (method, path, url) is promoted to its own dotted keys, with\n    //    typed nested maps for params and query; the open-ended pass-through\n    //    wire headers go into the single `routecraft.http.rawHeaders` map.\n    const queryObject: Record<string, string> = {};\n    for (const [k, v] of url.searchParams) queryObject[k] = v;\n    const reqHeaders: Record<string, string> = {};\n    req.headers.forEach((value, key) => {\n      reqHeaders[key] = value;\n    });\n\n    const handlerHeaders: ExchangeHeaders = {\n      \"routecraft.http.method\": method,\n      \"routecraft.http.path\": entry.matcher.pattern,\n      \"routecraft.http.url\": req.url,\n      \"routecraft.http.params\": params,\n      \"routecraft.http.query\": Object.freeze(queryObject),\n      \"routecraft.http.rawHeaders\": Object.freeze(reqHeaders),\n      ...(entry.rawBody && rawBytes !== undefined\n        ? { \"routecraft.http.rawBody\": rawBytes }\n        : {}),\n      ...(principal !== undefined\n        ? { [HeadersKeys.AUTH_PRINCIPAL]: principal }\n        : {}),\n    } as ExchangeHeaders;\n\n    // 6. Run the route. The runtime hands us back the final exchange (post\n    //    user steps and any registered .error() handler). We translate its\n    //    body + response hints into a Response.\n    try {\n      let exchange: Exchange;\n      if (entry.respond !== undefined) {\n        // Refused for every responder, not just one that answers early: which\n        // it is cannot be known before calling it. See HttpResponder.\n        if (opts.shutdownSignal?.aborted === true) {\n          const response = jsonResponse(\n            { error: \"service unavailable\", reason: \"shutting_down\" },\n            { status: 503, headers: { \"retry-after\": \"5\" } },\n          );\n          emitCompleted(opts, {\n            method,\n            path: entry.matcher.pattern,\n            status: 503,\n            durationMs: ms(started),\n            routeId: entry.routeId,\n          });\n          return response;\n        }\n        // Started before the responder so the exchange is in-flight for the\n        // shutdown drain whether or not the responder waits for it.\n        const finished = entry.handler(parsedBody, handlerHeaders);\n        // Claimed here, before the responder sees it, so an ignored `finished`\n        // never surfaces as an unhandled rejection. The pipeline's own\n        // boundary has already logged it; logging again would duplicate.\n        const settled = finished.then(\n          (result) => result,\n          () => undefined,\n        );\n        // The response is built by the responder, so nothing will ever read\n        // the exchange's body, and a stream holds its socket or file\n        // descriptor until GC finalises it. Cancelling can itself reject (a\n        // locked stream throws), and an unhandled rejection is fatal under\n        // Node's default, so the failure is logged rather than thrown into\n        // a request that has already been answered.\n        const cancelUnreadBody = (): void => {\n          void settled\n            .then((result) => {\n              const body = result?.body;\n              return isReadableStream(body) ? body.cancel() : undefined;\n            })\n            .catch((error: unknown) => {\n              log.warn(\n                { err: error, routeId: entry.routeId, method, path: pathname },\n                \"http source: could not cancel the unread body of a detached run\",\n              );\n            });\n        };\n        let descriptor: HttpResponseDescriptor | undefined;\n        try {\n          descriptor = await entry.respond({\n            request: {\n              body: parsedBody,\n              headers: Object.freeze(reqHeaders),\n              params,\n              method,\n              path: entry.matcher.pattern,\n              ...(principal !== undefined ? { principal } : {}),\n            },\n            finished,\n          });\n        } catch (error) {\n          // The pipeline is already running and cannot be un-started, so the\n          // orphaned body still needs releasing before the 500 goes out.\n          cancelUnreadBody();\n          throw error;\n        }\n        if (descriptor !== undefined) {\n          cancelUnreadBody();\n          const response = serialiseDescriptor(descriptor);\n          emitCompleted(opts, {\n            method,\n            path: entry.matcher.pattern,\n            status: response.status,\n            durationMs: ms(started),\n            routeId: entry.routeId,\n            principal: principal ? { subject: principal.subject } : undefined,\n          });\n          return response;\n        }\n        // Deferred: await the run already in flight, never start a second one,\n        // which would process the delivery twice.\n        exchange = await finished;\n      } else {\n        exchange = await entry.handler(parsedBody, handlerHeaders);\n      }\n      const plan = planStream(exchange.body, exchange.headers);\n      if (plan) {\n        // A stream may stay quiet far longer than the listener's idle\n        // reaper allows, and the mount cannot know at bind time which of\n        // its routes will stream, so the slot is claimed here, for this\n        // request, once the body proves to be one. A listener already at\n        // its cap refuses rather than opening a stream it cannot bound.\n        const release = claimStreamingSlot?.();\n        if (claimStreamingSlot !== undefined && release === undefined) {\n          const response = jsonResponse(\n            { error: \"service unavailable\", reason: \"streaming_capacity\" },\n            { status: 503, headers: { \"retry-after\": \"5\" } },\n          );\n          emitCompleted(opts, {\n            method,\n            path: entry.matcher.pattern,\n            status: 503,\n            durationMs: ms(started),\n            routeId: entry.routeId,\n          });\n          return response;\n        }\n        // A stream admitted on a credential that expires mid-flight would\n        // otherwise keep serving on authority that has lapsed, and this is\n        // the first surface where one admission check covers an unbounded\n        // window. Closing is the whole remedy: a 401 cannot follow a 200, and\n        // an SSE client reconnects by specification, so the reconnect goes\n        // through ordinary admission and gets its 401 from the path that\n        // already exists. A principal with no `expiresAt` is left alone,\n        // because a credential with no expiry granting an unexpiring stream\n        // is the operator's choice honoured rather than a gap.\n        const expiry = principalExpirySignal(principal, {\n          clockToleranceSec,\n          onExpired: ({ subject }) => {\n            log.info(\n              { subject, routeId: entry.routeId, path: pathname },\n              \"http source: closing stream, the admitted credential has expired\",\n            );\n          },\n        });\n        const body = streamResponseBody(plan.body, {\n          signal: anySignal(req.signal, opts.shutdownSignal, expiry?.signal),\n          preamble: plan.preamble,\n          onCleanupError: (error) => {\n            log.error(\n              { err: error, routeId: entry.routeId, method, path: pathname },\n              \"http source: streaming route failed to clean up after the response ended\",\n            );\n          },\n          onEnd: (error) => {\n            release?.();\n            expiry?.cancel();\n            if (error !== undefined) {\n              log.error(\n                { err: error, routeId: entry.routeId, method, path: pathname },\n                \"http source: streaming response body failed after the status line was sent\",\n              );\n            }\n            emitCompleted(opts, {\n              method,\n              path: entry.matcher.pattern,\n              status: plan.status,\n              durationMs: ms(started),\n              routeId: entry.routeId,\n              principal: principal ? { subject: principal.subject } : undefined,\n              ...(error !== undefined\n                ? {\n                    error: {\n                      name: error instanceof Error ? error.name : \"Error\",\n                      message:\n                        error instanceof Error ? error.message : String(error),\n                    },\n                  }\n                : {}),\n            });\n          },\n        });\n        return new Response(body, {\n          status: plan.status,\n          headers: plan.headers,\n        });\n      }\n      const response = serialiseResponse(exchange.body, exchange.headers);\n      emitCompleted(opts, {\n        method,\n        path: entry.matcher.pattern,\n        status: response.status,\n        durationMs: ms(started),\n        routeId: entry.routeId,\n        principal: principal ? { subject: principal.subject } : undefined,\n      });\n      return response;\n    } catch (err) {\n      // No `unauthenticated`: a principal-less run never had its credential read.\n      const refused = callerRefusalResponse(err, {\n        routeId: entry.routeId,\n        requestUrl: req.url,\n        principal,\n      });\n      if (refused !== undefined) {\n        log.debug(\n          { err, routeId: entry.routeId, method, path: pathname },\n          \"http source: route refused the caller\",\n        );\n        emitCompleted(opts, {\n          method,\n          path: entry.matcher.pattern,\n          status: refused.status,\n          durationMs: ms(started),\n          routeId: entry.routeId,\n          principal: principal ? { subject: principal.subject } : undefined,\n        });\n        return refused;\n      }\n      log.error(\n        { err, routeId: entry.routeId, method, path: pathname },\n        entry.respond !== undefined\n          ? \"http source: respond threw; the pipeline it started keeps running\"\n          : \"http source: route handler threw\",\n      );\n      const response = jsonResponse(\n        { error: \"internal server error\" },\n        { status: 500 },\n      );\n      emitCompleted(opts, {\n        method,\n        path: entry.matcher.pattern,\n        status: 500,\n        durationMs: ms(started),\n        routeId: entry.routeId,\n      });\n      return response;\n    }\n  };\n}\n\n/**\n * Run a user-facing listener without letting its exceptions reach the\n * request path, mirroring the guard emitCompleted applies to its handler.\n */\nfunction safeNotify(fn: () => void): void {\n  try {\n    fn();\n  } catch {\n    // never let listener exceptions propagate into the request path\n  }\n}\n\nfunction emitCompleted(\n  opts: DispatcherOptions,\n  event: Parameters<RequestCompletedHandler>[0],\n): void {\n  if (opts.onRequestCompleted) {\n    try {\n      opts.onRequestCompleted(event);\n    } catch {\n      // never let listener exceptions propagate into the request path\n    }\n  }\n}\n\nfunction ms(started: number): number {\n  return Math.round(performance.now() - started);\n}\n\n/** A streaming body, with the status and headers its response carries. */\ninterface StreamPlan {\n  body: AsyncIterable<unknown> | ReadableStream<Uint8Array>;\n  status: number;\n  headers: Record<string, string>;\n  /** The response is an event stream, so it opens with the SSE comment. */\n  preamble: boolean;\n}\n\n/**\n * Recognise a streaming body and decide the response it heads.\n *\n * Two arms, split on what the route handed back rather than on any option.\n * An `AsyncIterable` is framed as Server-Sent Events, because that is the\n * only thing a sequence of yielded values can mean over HTTP without the\n * route saying more. A `ReadableStream` is already bytes and is passed\n * through untouched, so a route that has its own wire format reaches for\n * that one.\n *\n * Overrides win over both defaults, which is how a caller chooses\n * `application/x-ndjson`. Framing follows the body type, not the content\n * type: an iterable of objects is SSE-framed whatever the header says, and\n * a route wanting different bytes yields strings.\n */\nfunction planStream(\n  body: unknown,\n  headers: ExchangeHeaders,\n): StreamPlan | undefined {\n  if (body === null || body === undefined) return undefined;\n  const raw = isReadableStream(body);\n  if (!raw && !isAsyncIterable(body)) return undefined;\n\n  const hint = readResponseHint(headers);\n  const extraHeaders = lowerCaseKeys(hint.headers);\n  const responseHeaders = raw\n    ? {\n        \"content-type\": hint.contentType ?? \"application/octet-stream\",\n        ...extraHeaders,\n      }\n    : {\n        \"content-type\": hint.contentType ?? SSE_CONTENT_TYPE,\n        \"cache-control\": SSE_CACHE_CONTROL,\n        ...extraHeaders,\n      };\n  return {\n    body: body as AsyncIterable<unknown> | ReadableStream<Uint8Array>,\n    status: hint.status ?? 200,\n    headers: responseHeaders,\n    // Conditioned on the content type rather than on the body type, because\n    // the comment is only legal in an event stream. A route that named a\n    // different format owns its bytes from the first one.\n    preamble:\n      responseHeaders[\"content-type\"]?.startsWith(\"text/event-stream\") === true,\n  };\n}\n\n/**\n * Lower-case a header override's keys so the spread that follows genuinely\n * overrides.\n *\n * HTTP header names are case-insensitive and object keys are not, so a route\n * spelling an override `Content-Type` used to add a second key beside the\n * framework's own `content-type`. `Headers` then joined the two values into\n * one nonsensical field, and the streaming arm additionally read the wrong\n * one when deciding whether to open with the SSE comment, prepending bytes\n * to a body the route had declared as something else.\n */\nfunction lowerCaseKeys(\n  headers: Readonly<Record<string, string>> | undefined,\n): Record<string, string> {\n  if (headers === undefined) return {};\n  return Object.fromEntries(\n    Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]),\n  );\n}\n\n/**\n * Translate the final exchange body + response hint headers into a Response\n * according to the documented convention.\n */\n/**\n * Turn a responder's descriptor into a Response. Body serialisation follows\n * the same rules as a pipeline result, so one set of rules governs both\n * paths; the status is taken as given, because choosing it is the whole\n * reason a responder exists, and an absent body sends nothing rather than\n * collapsing to 204.\n *\n * Streaming is deliberately absent. A stream needs the listener's slot\n * accounting and its own expiry handling, both of which belong to the\n * framework's path, so a route that streams does not configure a responder.\n */\n/**\n * Statuses the Fetch specification forbids a body on. Node throws when one\n * carries a body and Bun does not, so the body is dropped here and the two\n * runtimes answer the same way rather than one of them 500ing.\n */\nconst NULL_BODY_STATUSES: ReadonlySet<number> = new Set([101, 204, 205, 304]);\n\nfunction serialiseDescriptor(descriptor: HttpResponseDescriptor): Response {\n  const { status, body } = descriptor;\n  if (!Number.isInteger(status) || status < 200 || status > 599) {\n    // Left to the platform this is a RangeError caught by the 500 arm, which\n    // reads as a route failure and names the wrong culprit. An omitted status\n    // is worse: `new Response(x, { status: undefined })` is a silent 200, so a\n    // sender would read a forgotten field as an acknowledgement.\n    throw rcError(\"RC5003\", undefined, {\n      message: `http() source: respond returned status ${String(status)}; it must be an integer between 200 and 599, e.g. { status: 202 }.`,\n    });\n  }\n  if (isReadableStream(body) || isAsyncIterable(body)) {\n    // Without this the stream falls through to the JSON arm and the caller\n    // receives \"{}\" with a 200, while the stream itself is never read and\n    // holds its resource open. Streaming belongs to the framework's own\n    // path, which has the listener's slot accounting and the credential\n    // expiry handling a stream needs.\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"http() source: respond returned a streaming body, which it cannot serialise. Omit respond on a route that streams, or return a string, bytes, or a JSON-serialisable value.\",\n    });\n  }\n  const { init, contentType } = NULL_BODY_STATUSES.has(status)\n    ? { init: null, contentType: undefined }\n    : bodyToWire(body);\n  return new Response(init, {\n    status,\n    headers: {\n      ...(contentType !== undefined ? { \"content-type\": contentType } : {}),\n      ...lowerCaseKeys(descriptor.headers),\n    },\n  });\n}\n\n/**\n * The wire form of a body value: what to hand `Response`, and the content type\n * it implies. Shared by both response paths so the promise that a responder's\n * descriptor serialises by the same rules as a pipeline result is kept by the\n * code rather than by a comment. Status and any route-supplied overrides stay\n * with the caller, which is the only thing the two paths disagree about.\n */\nfunction bodyToWire(body: unknown): {\n  init: BodyInit | null;\n  contentType: string | undefined;\n} {\n  if (body === null || body === undefined) {\n    return { init: null, contentType: undefined };\n  }\n  if (typeof body === \"string\") {\n    return { init: body, contentType: \"text/plain; charset=utf-8\" };\n  }\n  if (body instanceof Uint8Array) {\n    // Uint8Array is a valid BodyInit at runtime, but TS picks the\n    // URLSearchParams overload of the union under bun-types/node-types mixing.\n    return {\n      init: body as unknown as BodyInit,\n      contentType: \"application/octet-stream\",\n    };\n  }\n  if (body instanceof ArrayBuffer) {\n    return { init: body, contentType: \"application/octet-stream\" };\n  }\n  return {\n    init: JSON.stringify(body),\n    contentType: \"application/json; charset=utf-8\",\n  };\n}\n\nfunction serialiseResponse(body: unknown, headers: ExchangeHeaders): Response {\n  const hint = readResponseHint(headers);\n  // Same normalisation as the streaming arm: a differently-cased override\n  // otherwise duplicates the header rather than replacing it.\n  const extraHeaders = lowerCaseKeys(hint.headers);\n\n  // A deferred exchange answers 202 with the acknowledgment as its body. HTTP\n  // is the one transport with an out-of-band status channel, so the status\n  // carries the `Output | Deferred` discrimination and the declared 200\n  // body type stays the route's own output. `Retry-After` is the TTL, which\n  // is the honest hint: after it, the deferral is no longer resumable. An\n  // explicit `.header(\"routecraft.http.response.status\", ...)` still wins,\n  // because a route that overrode the status meant it.\n  if (isDeferred(body)) {\n    const retryAfter = retryAfterSeconds(body.expiresAt);\n    return new Response(JSON.stringify(body), {\n      status: hint.status ?? 202,\n      headers: {\n        \"content-type\": hint.contentType ?? \"application/json; charset=utf-8\",\n        ...(retryAfter !== undefined\n          ? { \"retry-after\": String(retryAfter) }\n          : {}),\n        ...extraHeaders,\n      },\n    });\n  }\n\n  // An absent body is 204 unless the route overrode the status; everything\n  // else is 200. The content type is the body's own unless the route named\n  // one, and an absent body carries none at all.\n  const { init, contentType } = bodyToWire(body);\n  return new Response(init, {\n    status: hint.status ?? (init === null ? 204 : 200),\n    headers: {\n      ...(contentType !== undefined\n        ? { \"content-type\": hint.contentType ?? contentType }\n        : {}),\n      ...extraHeaders,\n    },\n  });\n}\n\n/**\n * Whole seconds until `expiresAt`, for `Retry-After`.\n *\n * Absent when the deferral has no TTL (nothing honest to promise) or the\n * deadline has already passed (a `Retry-After: 0` would invite an immediate\n * retry against a deferral that can no longer be resumed).\n */\nfunction retryAfterSeconds(expiresAt: string | undefined): number | undefined {\n  if (expiresAt === undefined) return undefined;\n  const remaining = Date.parse(expiresAt) - Date.now();\n  if (!Number.isFinite(remaining) || remaining <= 0) return undefined;\n  return Math.ceil(remaining / 1000);\n}\n\nfunction readResponseHint(headers: ExchangeHeaders): HttpResponseHint {\n  const status = headers[\"routecraft.http.response.status\"];\n  const contentType = headers[\"routecraft.http.response.contentType\"];\n  const responseHeaders = headers[\"routecraft.http.response.headers\"];\n  return {\n    ...(typeof status === \"number\" ? { status } : {}),\n    ...(typeof contentType === \"string\" ? { contentType } : {}),\n    ...(responseHeaders ? { headers: responseHeaders } : {}),\n  };\n}\n","import { isRoutecraftError } from \"../../brand\";\nimport { rcError, type RCCode, type RoutecraftError } from \"../../error\";\nimport { declaredLengthOver } from \"./max-body-size.ts\";\nimport {\n  verifyWebhookSignature,\n  type HttpWebhookSignatureOptions,\n  type HttpWebhookSignatureRejection,\n} from \"./webhook-signature\";\n\nexport interface ParsedRequestBody {\n  /** The parsed body in its post-parse shape. `undefined` for methods without a body. */\n  body: unknown;\n  /**\n   * The exact wire bytes of the request body (empty for bodyless methods).\n   * This is the same buffer the content-type parsers read from, so\n   * populating it costs nothing; the dispatcher only attaches it to the\n   * exchange when the route opted in via `http({ rawBody: true })`. When\n   * that opt-in is active and the body itself is the raw bytes (unknown\n   * content-type), `rawBytes` is a defensive copy so in-place body\n   * mutation cannot corrupt it.\n   */\n  rawBytes: Uint8Array;\n}\n\n/** Body-stage error carrying the HTTP status the dispatcher should return. */\nexport type HttpBodyError = RoutecraftError & { httpStatus: number };\n\n/**\n * RC5039 signature rejection thrown by the pre-parse gate. Carries the\n * typed bounded reason so the dispatcher's 401 body and the auth:rejected\n * event never have to re-derive it from `err.message` free text (which the\n * security standard forbids).\n */\nexport type HttpSignatureRejectionError = HttpBodyError & {\n  signatureRejection: HttpWebhookSignatureRejection;\n};\n\n/** Type guard for the RC5039 signature rejection thrown by {@link parseRequestBody}. */\nexport function isSignatureRejection(\n  err: unknown,\n): err is HttpSignatureRejectionError {\n  return isRoutecraftError(err) && (err as RoutecraftError).rc === \"RC5039\";\n}\n\n/**\n * Build a body-stage error tagged with the response status the dispatcher\n * should use. Carrying the status explicitly avoids the dispatcher having to\n * infer 413-vs-400 from the message text. Defaults to RC5018 (malformed or\n * oversized body); the signature gate passes RC5039.\n */\nfunction bodyError(\n  httpStatus: number,\n  message: string,\n  cause?: unknown,\n  rc: RCCode = \"RC5018\",\n): HttpBodyError {\n  const err = rcError(rc, cause, { message }) as HttpBodyError;\n  err.httpStatus = httpStatus;\n  return err;\n}\n\ninterface ParseOptions {\n  maxBodySize: number;\n  /**\n   * When set, verify the raw body against the signature header before any\n   * content-type parsing. Failures throw RC5039 tagged 401.\n   */\n  signature?: HttpWebhookSignatureOptions;\n  /**\n   * Whether the route opted in to raw-body exposure. Only consulted on the\n   * unknown-content-type branch, where body and raw bytes would otherwise\n   * alias the same buffer.\n   */\n  rawBody?: boolean;\n}\n\n/**\n * Methods whose requests carry no body. Exported because the http source's\n * construction-time signature guard must stay in lockstep with the skip\n * below: a method in this set never reaches the signature gate, so allowing\n * `signature` on it would silently disable verification.\n */\nexport const METHODS_WITHOUT_BODY: ReadonlySet<string> = new Set([\n  \"GET\",\n  \"HEAD\",\n  \"DELETE\",\n  \"OPTIONS\",\n]);\n\nconst EMPTY_BODY = new Uint8Array(0);\n\n/**\n * Read and parse the request body using a `Content-Type`-driven strategy.\n *\n * Buffers the full body in memory before parsing so we can enforce\n * `maxBodySize` deterministically, which means a chunked request over the cap\n * is held before it is refused. The `http()` client counts while it streams\n * instead; bringing that here is a follow-up.\n *\n * Methods listed in {@link METHODS_WITHOUT_BODY} produce\n * `{ body: undefined, rawBytes: <empty> }` without touching the request\n * stream, matching what fetch clients usually send for those verbs.\n *\n * @throws HttpBodyError RC5018 tagged with `httpStatus` 413 when the body\n * exceeds `maxBodySize`, or 400 when a typed body cannot be parsed.\n * @throws HttpSignatureRejectionError RC5039 tagged with `httpStatus` 401\n * when `opts.signature` is set and verification fails; carries the bounded\n * rejection reason as `signatureRejection`.\n */\nexport async function parseRequestBody(\n  req: Request,\n  opts: ParseOptions,\n): Promise<ParsedRequestBody> {\n  const method = req.method.toUpperCase();\n  if (METHODS_WITHOUT_BODY.has(method)) {\n    // `signature` on a bodyless method is rejected at http({...}) construction\n    // time, so skipping verification here cannot silently disable a gate.\n    return { body: undefined, rawBytes: EMPTY_BODY };\n  }\n\n  // Guard against oversized requests before buffering when the client\n  // declares Content-Length.\n  const declaredLength = declaredLengthOver(\n    req.headers.get(\"content-length\"),\n    opts.maxBodySize,\n  );\n  if (declaredLength !== undefined) {\n    throw bodyError(\n      413,\n      `request body of ${declaredLength} bytes exceeds maxBodySize ${opts.maxBodySize}`,\n    );\n  }\n\n  // arrayBuffer() buffers the full body, so a chunked request over the cap is\n  // held in memory before the post-buffer check below rejects it. The http()\n  // client streams and counts instead (see its readBody); adopting that here\n  // is a follow-up, and the reason this side still buffers is history rather\n  // than a missing mechanism.\n  const buffer = await req.arrayBuffer();\n  if (buffer.byteLength > opts.maxBodySize) {\n    throw bodyError(\n      413,\n      `request body of ${buffer.byteLength} bytes exceeds maxBodySize ${opts.maxBodySize}`,\n    );\n  }\n\n  const bytes = new Uint8Array(buffer);\n\n  // Verify the signature before the zero-length shortcut and before any\n  // content-type parsing: a signature-gated route must reject an empty or\n  // malformed body that is not correctly signed, not admit it by accident.\n  if (opts.signature) {\n    const result = verifyWebhookSignature(bytes, req.headers, opts.signature);\n    if (!result.ok) {\n      const err = bodyError(\n        401,\n        result.reason,\n        undefined,\n        \"RC5039\",\n      ) as HttpSignatureRejectionError;\n      err.signatureRejection = result.reason;\n      throw err;\n    }\n  }\n\n  if (buffer.byteLength === 0) {\n    return { body: undefined, rawBytes: bytes };\n  }\n\n  const contentType = (req.headers.get(\"content-type\") ?? \"\").toLowerCase();\n\n  if (contentType.includes(\"application/json\")) {\n    const text = new TextDecoder().decode(bytes);\n    try {\n      return { body: JSON.parse(text), rawBytes: bytes };\n    } catch (err) {\n      throw bodyError(400, \"request body is not valid JSON\", err);\n    }\n  }\n\n  if (contentType.includes(\"application/x-www-form-urlencoded\")) {\n    const text = new TextDecoder().decode(bytes);\n    const params = new URLSearchParams(text);\n    const obj: Record<string, string> = {};\n    for (const [k, v] of params) obj[k] = v;\n    return { body: obj, rawBytes: bytes };\n  }\n\n  if (contentType.includes(\"multipart/form-data\")) {\n    // Rebuild a Request so the runtime's `formData()` parser sees both the\n    // body and the boundary-bearing Content-Type. We cannot call\n    // `req.formData()` directly because `req` is already consumed.\n    const replay = new Request(\"http://internal.multipart.parser/\", {\n      method: \"POST\",\n      headers: { \"content-type\": req.headers.get(\"content-type\") ?? \"\" },\n      body: buffer,\n    });\n    try {\n      const formData = await replay.formData();\n      return { body: formData, rawBytes: bytes };\n    } catch (err) {\n      throw bodyError(400, \"multipart/form-data body could not be parsed\", err);\n    }\n  }\n\n  if (contentType.startsWith(\"text/\")) {\n    return { body: new TextDecoder().decode(bytes), rawBytes: bytes };\n  }\n\n  // Unknown content-type: the body IS the raw bytes. When the route wants\n  // rawBody, hand it a defensive copy so an in-place body mutation cannot\n  // corrupt the wire bytes the header promises; without the opt-in the\n  // shared instance is never exposed twice, so no copy is needed.\n  return {\n    body: bytes,\n    rawBytes: opts.rawBody === true ? bytes.slice() : bytes,\n  };\n}\n","import { rcError } from \"../../error\";\n\n/**\n * The `maxBodySize` ceiling, shared by the http plugin's inbound request cap\n * and the `http()` client's response cap.\n *\n * One definition rather than two literals that happen to agree: the reference\n * pages, the `RC5061` suggestion and the changelog all tell readers the two\n * sides are the same number, and a promise stated in four documents needs\n * something that breaks when it stops being true.\n */\nexport const DEFAULT_MAX_BODY_SIZE = 10 * 1024 * 1024;\n\n/**\n * Resolve a configured `maxBodySize` against the shared default.\n *\n * Zero and negatives are always refused rather than read as \"no limit\",\n * because the two readings of `0` are opposites: it looks like \"unbounded\"\n * and would behave as \"reject everything\". So an options object built\n * programmatically cannot arrive at unbounded by accident on either side.\n *\n * Whether unbounded can be asked for at all is the caller's to decide, and\n * the two sides answer differently. Outbound, the route author chose the\n * endpoint and is spending their own process on a response they asked for,\n * so `Infinity` is a legitimate opt-out. Inbound, the caller is a stranger\n * and the request is buffered whole before it can be measured, so an\n * unbounded cap means one request can exhaust the process, which is the\n * exact thing the option exists to prevent. Refusing is therefore the\n * default and permitting it is opt-in, never the other way around.\n *\n * @param subject Prefix naming the caller for the error message, for example\n * `\"http() client\"` or `\"httpPlugin\"`.\n * @param allowUnbounded Whether `Infinity` is accepted as a named opt-out.\n * Defaults to `false`.\n * @throws RoutecraftError RC5003 when the value is not a positive integer,\n * or is `Infinity` where unbounded is not permitted.\n */\nexport function resolveMaxBodySize(\n  value: number | undefined,\n  subject: string,\n  { allowUnbounded = false }: { allowUnbounded?: boolean } = {},\n): number {\n  if (value === undefined) return DEFAULT_MAX_BODY_SIZE;\n  if (allowUnbounded && value === Number.POSITIVE_INFINITY) return value;\n  if (!Number.isInteger(value) || value <= 0) {\n    const ways = allowUnbounded\n      ? \"Pass a positive integer (bytes), or Infinity for no limit.\"\n      : \"Pass a positive integer (bytes).\";\n    throw rcError(\"RC5003\", undefined, {\n      message: `${subject}: invalid maxBodySize ${String(value)}. ${ways}`,\n    });\n  }\n  return value;\n}\n\n/**\n * The declared `Content-Length` when it is over `max`, otherwise `undefined`.\n *\n * An absent or unparseable declaration is not a pass, it is simply no\n * information: both sides still have to bound what actually arrives.\n */\nexport function declaredLengthOver(\n  header: string | null | undefined,\n  max: number,\n): number | undefined {\n  const declared = parseInt(header ?? \"\", 10);\n  return !isNaN(declared) && declared > max ? declared : undefined;\n}\n","import { createHmac } from \"node:crypto\";\nimport { timingSafeStringEqual } from \"../../auth/timing-safe\";\n\nconst SCHEMES = [\n  \"hmac-sha256-hex\",\n  \"hmac-sha1-hex\",\n  \"stripe-timestamped\",\n  \"standard-webhooks\",\n] as const;\n\n/**\n * Signature schemes supported by the built-in webhook verifier.\n *\n * - `\"hmac-sha256-hex\"`: hex-encoded HMAC-SHA256 of the raw body. GitHub's\n *   `X-Hub-Signature-256` uses this with `prefix: \"sha256=\"`.\n * - `\"hmac-sha1-hex\"`: hex-encoded HMAC-SHA1 of the raw body. Legacy GitHub\n *   `X-Hub-Signature` uses this with `prefix: \"sha1=\"`. Prefer sha256 when\n *   the provider offers both.\n * - `\"stripe-timestamped\"`: Stripe's `Stripe-Signature` format\n *   (`t=<unix>,v1=<hex>`). The signed payload is `<t>.<raw body>` and the\n *   timestamp must be within `toleranceSec` of the server clock, which\n *   bounds replay of captured deliveries.\n * - `\"standard-webhooks\"`: the [Standard Webhooks](https://www.standardwebhooks.com/)\n *   format, sent by Resend, Bird and Svix among others. Reads the three\n *   headers the specification fixes (`webhook-id`, `webhook-timestamp`,\n *   `webhook-signature`), signs `<id>.<timestamp>.<raw body>` with the\n *   base64-decoded secret, and admits when any space-separated `v1,` entry\n *   matches. Covers the symmetric half of the specification only:\n *   asymmetric `v1a` (ed25519) entries are skipped like any other\n *   non-`v1` version.\n */\nexport type HttpWebhookSignatureScheme = (typeof SCHEMES)[number];\n\n/** Fields every scheme takes. */\ninterface HttpWebhookSignatureOptionsBase {\n  /** Shared secret the provider signs with. */\n  secret: string;\n  /**\n   * Literal prefix stripped from the header value before comparison, e.g.\n   * `\"sha256=\"` for GitHub. A header value that does not start with the\n   * prefix is an invalid signature. Ignored by `\"stripe-timestamped\"` and\n   * `\"standard-webhooks\"`, which have their own field formats.\n   */\n  prefix?: string;\n  /**\n   * Maximum allowed clock skew, in seconds, between the signature's\n   * embedded timestamp and the server clock. Used by\n   * `\"stripe-timestamped\"` and `\"standard-webhooks\"`. Defaults to 300.\n   */\n  toleranceSec?: number;\n}\n\n/**\n * The three schemes that read one configured header. `header` is required:\n * nothing in these formats fixes a header name, so there is no default that\n * would be right more often than it is wrong.\n */\nexport interface HttpWebhookSignatureHeaderOptions extends HttpWebhookSignatureOptionsBase {\n  /** Request header carrying the signature (e.g. `\"x-hub-signature-256\"`). Case-insensitive. */\n  header: string;\n  /** Signature scheme. See {@link HttpWebhookSignatureScheme}. */\n  scheme: Exclude<HttpWebhookSignatureScheme, \"standard-webhooks\">;\n}\n\n/**\n * Standard Webhooks. The specification fixes all three header names, so a\n * route configures a secret and nothing else. There is deliberately no\n * per-header override: the id and timestamp names are read from the\n * specification, so renaming only the signature header would build a route\n * that constructs cleanly and then rejects every live delivery.\n */\nexport interface HttpStandardWebhooksSignatureOptions extends HttpWebhookSignatureOptionsBase {\n  scheme: \"standard-webhooks\";\n  /**\n   * Never set. Declared so the refusal survives a config object that is not\n   * an object literal, where excess-property checking does not apply.\n   */\n  header?: never;\n}\n\n/**\n * Declarative webhook-signature verification for `http({...})` sources.\n * When configured, the plugin verifies the raw request bytes against the\n * signature header and rejects 401 before any route step runs, so HMAC\n * comparison never has to be hand-rolled in a `.filter()`.\n *\n * For providers whose scheme is not covered here, opt in to\n * `http({ rawBody: true })` instead and verify in a route step against\n * `routecraft.http.rawBody`.\n */\nexport type HttpWebhookSignatureOptions =\n  HttpWebhookSignatureHeaderOptions | HttpStandardWebhooksSignatureOptions;\n\n/**\n * Bounded rejection reasons, returned to clients in the 401 body and emitted\n * as the `reason` field on `auth:rejected`. Kept a closed vocabulary per the\n * security standard: never derived from `err.message` free text.\n */\nexport type HttpWebhookSignatureRejection =\n  \"missing signature header\" | \"invalid signature\" | \"signature expired\";\n\nexport type HttpWebhookSignatureResult =\n  { ok: true } | { ok: false; reason: HttpWebhookSignatureRejection };\n\nconst DEFAULT_TOLERANCE_SEC = 300;\n\n/** Unix seconds as the sender wrote them; never a re-serialised parse. */\nconst UNIX_SECONDS = /^\\d+$/;\n\n/**\n * The replay bound every timestamped scheme applies: true when the signed\n * timestamp sits further from the server clock than the tolerance allows.\n * Shared rather than copied because the schemes are documented as bounding\n * replay the same way, so they have one reason to change.\n */\nfunction outsideTolerance(\n  rawTimestamp: string,\n  toleranceSec: number | undefined,\n): boolean {\n  const tolerance = toleranceSec ?? DEFAULT_TOLERANCE_SEC;\n  const nowSec = Math.floor(Date.now() / 1000);\n  return Math.abs(nowSec - parseInt(rawTimestamp, 10)) > tolerance;\n}\n\n/**\n * RFC 7230 header-name token. `Headers.get()` throws a TypeError on names\n * outside this set, so an invalid name must be rejected at construction\n * rather than exploding at the first delivery.\n */\nconst HEADER_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n\n/** True when `value` is a string usable as a header name. */\nfunction isHeaderName(value: unknown): value is string {\n  return typeof value === \"string\" && HEADER_TOKEN.test(value);\n}\n\n/** Exact hex-digest shape per scheme, used to reject malformed candidates before hashing. */\nconst HEX_DIGEST_PATTERN = {\n  \"hmac-sha256-hex\": /^[0-9a-fA-F]{64}$/,\n  \"hmac-sha1-hex\": /^[0-9a-fA-F]{40}$/,\n} as const;\n\n/** Base64 of a 32-byte digest: 43 symbols and one pad character. */\nconst BASE64_SHA256_PATTERN = /^[A-Za-z0-9+/]{43}=$/;\n\n/**\n * The base64 alphabet a Standard Webhooks secret may use, padding already\n * stripped. Both the standard and the URL-safe alphabet are accepted because\n * `Buffer.from(x, \"base64\")` decodes either.\n */\nconst BASE64_SECRET_PATTERN = /^[A-Za-z0-9+/\\-_]+$/;\n\n/**\n * The three header names the Standard Webhooks specification fixes. None is\n * configurable: a sender that renamed them would not be sending Standard\n * Webhooks, and renaming only one of the three would build a route that\n * constructs cleanly and then rejects every live delivery.\n */\nconst STANDARD_WEBHOOKS_SIGNATURE_HEADER = \"webhook-signature\";\nconst STANDARD_WEBHOOKS_ID_HEADER = \"webhook-id\";\nconst STANDARD_WEBHOOKS_TIMESTAMP_HEADER = \"webhook-timestamp\";\n\n/** Identification prefix on a Standard Webhooks symmetric secret. */\nconst STANDARD_WEBHOOKS_SECRET_PREFIX = \"whsec_\";\n\n/**\n * The base64 body of a Standard Webhooks secret, with the identification\n * prefix stripped when present. The reference implementation accepts the\n * secret either way, so a route that pastes the value straight out of a\n * provider dashboard works whether or not the dashboard shows the prefix.\n */\nfunction standardWebhooksSecretBody(secret: string): string {\n  return secret.startsWith(STANDARD_WEBHOOKS_SECRET_PREFIX)\n    ? secret.slice(STANDARD_WEBHOOKS_SECRET_PREFIX.length)\n    : secret;\n}\n\n/**\n * Render an untrusted config value for an error message without letting the\n * renderer itself throw (JSON.stringify rejects BigInt and circular values,\n * which are exactly the malformed inputs being reported).\n */\nfunction describeValue(value: unknown): string {\n  try {\n    return JSON.stringify(value) ?? String(value);\n  } catch {\n    try {\n      return String(value);\n    } catch {\n      return \"<unrepresentable value>\";\n    }\n  }\n}\n\n/**\n * Validate a signature options object at construction time. Returns an\n * error message when the shape is invalid, `null` when it is usable.\n * The http source turns a non-null result into RC5003 so misconfiguration\n * fails at the `http({...})` call site, not at the first delivery.\n */\nexport function invalidSignatureOptionsReason(\n  options: HttpWebhookSignatureOptions,\n): string | null {\n  if (typeof options !== \"object\" || options === null) {\n    return `invalid signature options ${describeValue(options)}. Pass { header, secret, scheme }.`;\n  }\n  if (!SCHEMES.includes(options.scheme)) {\n    return `invalid signature.scheme ${describeValue(options.scheme)}. Allowed: ${SCHEMES.map((s) => `\"${s}\"`).join(\", \")}.`;\n  }\n  // Every scheme but standard-webhooks needs a header name, because none of\n  // their formats fixes one. Standard Webhooks takes no header at all.\n  if (options.scheme !== \"standard-webhooks\" && !isHeaderName(options.header)) {\n    return `invalid signature.header ${describeValue(options.header)}. Pass a legal HTTP header name (RFC 7230 token, e.g. \"x-hub-signature-256\").`;\n  }\n  if (typeof options.secret !== \"string\" || options.secret === \"\") {\n    return \"invalid signature.secret. Pass the provider's non-empty signing secret.\";\n  }\n  if (options.scheme === \"standard-webhooks\") {\n    // Decoded here rather than at the first delivery: a secret that cannot\n    // be decoded would otherwise reject every delivery as an invalid\n    // signature, which reads as the sender's fault rather than the config's.\n    const body = standardWebhooksSecretBody(options.secret).replace(/=+$/, \"\");\n    // Padding is not required: `Buffer.from(x, \"base64\")` decodes an unpadded\n    // secret, and a dashboard or an env pipeline that trimmed the \"=\" would\n    // otherwise be told its correct secret is malformed. A length of 1 more\n    // than a multiple of 4 encodes no whole byte, so it is still refused.\n    if (\n      body === \"\" ||\n      body.length % 4 === 1 ||\n      !BASE64_SECRET_PATTERN.test(body)\n    ) {\n      return `invalid signature.secret. A \"standard-webhooks\" secret is base64, optionally prefixed with \"${STANDARD_WEBHOOKS_SECRET_PREFIX}\" (e.g. \"whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw\").`;\n    }\n  }\n  if (options.prefix !== undefined && typeof options.prefix !== \"string\") {\n    return `invalid signature.prefix ${describeValue(options.prefix)}. Pass a string (e.g. \"sha256=\").`;\n  }\n  if (\n    options.toleranceSec !== undefined &&\n    (typeof options.toleranceSec !== \"number\" ||\n      !Number.isFinite(options.toleranceSec) ||\n      options.toleranceSec <= 0)\n  ) {\n    return `invalid signature.toleranceSec ${describeValue(options.toleranceSec)}. Pass a positive number of seconds.`;\n  }\n  return null;\n}\n\n/**\n * Verify a webhook signature against the raw request bytes.\n *\n * Takes the request's whole header set rather than one pre-read value,\n * because a scheme decides for itself which headers it needs:\n * `\"standard-webhooks\"` reads three.\n *\n * All comparisons are timing-safe via the shared {@link timingSafeStringEqual}\n * (length-guarded `timingSafeEqual`, also used by the JWT HMAC validator).\n * Hex comparison is case-insensitive: providers disagree on digest casing\n * and hex case carries no information. Candidates that do not match the\n * scheme's exact hex-digest shape are rejected before any HMAC is computed, so floods of\n * malformed signatures do not pay a full-body hash. The verifier never\n * throws for untrusted input; every failure mode maps to a bounded\n * {@link HttpWebhookSignatureRejection}.\n */\nexport function verifyWebhookSignature(\n  rawBody: Uint8Array,\n  headers: Headers,\n  options: HttpWebhookSignatureOptions,\n): HttpWebhookSignatureResult {\n  // Dispatched on the scheme before any header is read, so each scheme reads\n  // the headers it fixes and the union stays narrowed.\n  if (options.scheme === \"standard-webhooks\") {\n    return verifyStandardWebhooks(rawBody, headers, options);\n  }\n\n  const headerValue = headers.get(options.header);\n  if (headerValue === null || headerValue.trim() === \"\") {\n    return { ok: false, reason: \"missing signature header\" };\n  }\n\n  if (options.scheme === \"stripe-timestamped\") {\n    return verifyStripeTimestamped(rawBody, headerValue, options);\n  }\n\n  let candidate = headerValue.trim();\n  if (options.prefix !== undefined) {\n    if (!candidate.startsWith(options.prefix)) {\n      return { ok: false, reason: \"invalid signature\" };\n    }\n    candidate = candidate.slice(options.prefix.length);\n  }\n  if (!HEX_DIGEST_PATTERN[options.scheme].test(candidate)) {\n    return { ok: false, reason: \"invalid signature\" };\n  }\n\n  const digest = options.scheme === \"hmac-sha256-hex\" ? \"sha256\" : \"sha1\";\n  const expected = createHmac(digest, options.secret)\n    .update(rawBody)\n    .digest(\"hex\");\n  return timingSafeStringEqual(expected, candidate.toLowerCase())\n    ? { ok: true }\n    : { ok: false, reason: \"invalid signature\" };\n}\n\n/**\n * Verify Stripe's `t=<unix>,v1=<hex>` format. Multiple `v1` fields are\n * accepted (Stripe sends more than one during secret rotation); any match\n * admits. Unknown fields (`v0`, future versions) are ignored.\n *\n * The signed payload uses the raw `t` field text, not a re-serialised\n * parse of it: the provider signs the exact characters it sent, so\n * rebuilding from `parseInt` would reject non-canonical encodings. The\n * field must be digits-only; anything else is an invalid signature rather\n * than a silently truncated timestamp.\n */\nfunction verifyStripeTimestamped(\n  rawBody: Uint8Array,\n  headerValue: string,\n  options: HttpWebhookSignatureOptions,\n): HttpWebhookSignatureResult {\n  let rawTimestamp: string | undefined;\n  const candidates: string[] = [];\n  for (const field of headerValue.split(\",\")) {\n    const eq = field.indexOf(\"=\");\n    if (eq === -1) continue;\n    const key = field.slice(0, eq).trim();\n    const value = field.slice(eq + 1).trim();\n    if (key === \"t\") {\n      rawTimestamp = value;\n    } else if (key === \"v1\") {\n      candidates.push(value);\n    }\n  }\n\n  if (\n    rawTimestamp === undefined ||\n    !UNIX_SECONDS.test(rawTimestamp) ||\n    candidates.length === 0\n  ) {\n    return { ok: false, reason: \"invalid signature\" };\n  }\n\n  // Drop candidates whose length cannot match a sha256 hex digest BEFORE\n  // hashing, so the module's no-full-body-hash-for-malformed-signatures\n  // guarantee holds for this scheme too.\n  const viable = candidates.filter((candidate) =>\n    HEX_DIGEST_PATTERN[\"hmac-sha256-hex\"].test(candidate),\n  );\n  if (viable.length === 0) {\n    return { ok: false, reason: \"invalid signature\" };\n  }\n\n  if (outsideTolerance(rawTimestamp, options.toleranceSec)) {\n    return { ok: false, reason: \"signature expired\" };\n  }\n\n  // Chained update() streams `<raw t>.<raw body>` into the HMAC without\n  // building an intermediate concatenated buffer (and without a string\n  // round-trip that could mangle a non-UTF-8-clean body).\n  const expected = createHmac(\"sha256\", options.secret)\n    .update(`${rawTimestamp}.`)\n    .update(rawBody)\n    .digest(\"hex\");\n  return viable.some((candidate) =>\n    timingSafeStringEqual(expected, candidate.toLowerCase()),\n  )\n    ? { ok: true }\n    : { ok: false, reason: \"invalid signature\" };\n}\n\n/**\n * Verify the [Standard Webhooks](https://www.standardwebhooks.com/) format.\n *\n * The signed payload is `<webhook-id>.<webhook-timestamp>.<raw body>`, keyed\n * on the base64-decoded secret. The signature header is a space-separated\n * list of `<version>,<base64>` entries, several of which appear during key\n * rotation; any `v1` entry that matches admits, and entries of another\n * version (the specification's asymmetric `v1a` among them) are skipped\n * rather than treated as failures.\n *\n * A delivery missing either fixed header is `missing signature header`\n * rather than `invalid signature`: nothing was presented to verify, which is\n * the same thing an absent signature header means.\n *\n * The raw header text is signed, never a re-serialised parse of it, for the\n * reason the Stripe scheme does the same: the sender signed the exact\n * characters it sent.\n */\nfunction verifyStandardWebhooks(\n  rawBody: Uint8Array,\n  headers: Headers,\n  options: HttpStandardWebhooksSignatureOptions,\n): HttpWebhookSignatureResult {\n  const headerValue = headers.get(STANDARD_WEBHOOKS_SIGNATURE_HEADER);\n  if (headerValue === null || headerValue.trim() === \"\") {\n    return { ok: false, reason: \"missing signature header\" };\n  }\n  const id = headers.get(STANDARD_WEBHOOKS_ID_HEADER);\n  const rawTimestamp = headers.get(STANDARD_WEBHOOKS_TIMESTAMP_HEADER);\n  if (\n    id === null ||\n    id.trim() === \"\" ||\n    rawTimestamp === null ||\n    rawTimestamp.trim() === \"\"\n  ) {\n    return { ok: false, reason: \"missing signature header\" };\n  }\n  if (!UNIX_SECONDS.test(rawTimestamp)) {\n    return { ok: false, reason: \"invalid signature\" };\n  }\n\n  // Same pre-hash filter as the other schemes: a flood of malformed\n  // signatures must not each pay a full-body HMAC.\n  const viable: string[] = [];\n  for (const entry of headerValue.split(\" \")) {\n    const comma = entry.indexOf(\",\");\n    if (comma === -1) continue;\n    if (entry.slice(0, comma) !== \"v1\") continue;\n    const candidate = entry.slice(comma + 1);\n    if (BASE64_SHA256_PATTERN.test(candidate)) viable.push(candidate);\n  }\n  if (viable.length === 0) {\n    return { ok: false, reason: \"invalid signature\" };\n  }\n\n  if (outsideTolerance(rawTimestamp, options.toleranceSec)) {\n    return { ok: false, reason: \"signature expired\" };\n  }\n\n  const key = Buffer.from(standardWebhooksSecretBody(options.secret), \"base64\");\n  const expected = createHmac(\"sha256\", key)\n    .update(`${id}.${rawTimestamp}.`)\n    .update(rawBody)\n    .digest(\"base64\");\n  return viable.some((candidate) => timingSafeStringEqual(expected, candidate))\n    ? { ok: true }\n    : { ok: false, reason: \"invalid signature\" };\n}\n","/**\n * Runtime guards for the two web streaming primitives.\n *\n * Neither has anything to do with any one adapter or plugin: they answer\n * \"what kind of value is this\" about platform types, which is the same job\n * `isThenable` does next door. Kept here so the next consumer that needs one\n * imports a shared guard rather than reaching into a plugin it does not\n * depend on, or hand-rolling a fourth copy of the `Symbol.asyncIterator`\n * probe whose `typeof` half is the part people drop.\n */\nexport function isReadableStream(\n  value: unknown,\n): value is ReadableStream<Uint8Array> {\n  return (\n    typeof ReadableStream !== \"undefined\" && value instanceof ReadableStream\n  );\n}\n\nexport function isAsyncIterable(\n  value: unknown,\n): value is AsyncIterable<unknown> {\n  return (\n    (typeof value === \"object\" || typeof value === \"function\") &&\n    value !== null &&\n    Symbol.asyncIterator in value &&\n    typeof (value as { [Symbol.asyncIterator]: unknown })[\n      Symbol.asyncIterator\n    ] === \"function\"\n  );\n}\n","/**\n * Streaming response bodies for the http source: SSE framing for an\n * `AsyncIterable`, byte passthrough for a `ReadableStream`.\n *\n * The dispatcher normalises every route result to a `Response`, and a\n * streaming body is one more entry in that convention table rather than a\n * transport of its own. SSE needs no upgrade and no second request shape:\n * one exchange, one response, the pre-from chain applied once at entry.\n * That is why it lives on `http()` and not behind an `sse()` adapter.\n *\n * Both runtimes already carry the bytes. `Bun.serve` streams a\n * stream-bodied `Response` natively, and the `node:http` shim pumps the\n * body reader chunk by chunk with client-abort propagation. What this\n * module adds is the framing, the cancel path into the route's iterator,\n * and the single end-of-stream signal the dispatcher needs to close out\n * its per-request event.\n */\n\nexport { isAsyncIterable, isReadableStream } from \"../../shared/iterable.ts\";\n\n/** Default content type for the SSE arm, overridable per response. */\nexport const SSE_CONTENT_TYPE = \"text/event-stream; charset=utf-8\";\n\n/**\n * Cache directive every event stream carries. A cached event stream is a\n * contradiction, and an intermediary that buffers one turns a live feed\n * into a delayed batch.\n */\nexport const SSE_CACHE_CONTROL = \"no-cache\";\n\n/**\n * One yielded SSE event.\n *\n * A yielded object is read as this descriptor when it carries an own `data`\n * property; every other object is itself the payload and is JSON-encoded\n * into `data`. Keys outside the four SSE fields are not sent, so a domain\n * object that happens to have a `data` field is mapped in a `.transform()`\n * step rather than yielded raw.\n */\nexport interface SseEvent {\n  /** Payload. Strings are sent verbatim, anything else is JSON-encoded. */\n  data: unknown;\n  /** Event name, read by `addEventListener(name)` on an `EventSource`. */\n  event?: string;\n  /** Last event id, echoed back by a reconnecting client as `Last-Event-ID`. */\n  id?: string | number;\n  /** Reconnection delay in whole milliseconds. */\n  retry?: number;\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * Strip the characters that would end the field or the frame.\n *\n * A route builds `event` and `id` from its own data, and a newline in\n * either would let that data close the frame and forge the next one. The\n * SSE grammar has no escape for it, so the character is removed rather\n * than encoded. `id` additionally may not carry U+0000 (the field is\n * ignored wholesale by a conforming client if it does).\n */\nfunction singleLine(value: string): string {\n  return value.replace(/[\\r\\n\\0]/g, \"\");\n}\n\nfunction isSseEvent(value: object): value is SseEvent {\n  return Object.hasOwn(value, \"data\");\n}\n\n/**\n * Serialise one yielded value into SSE wire bytes.\n *\n * Strings and `Uint8Array`s pass through untouched: they are the escape\n * hatch for a route that already speaks the protocol (a `\": ping\"`\n * heartbeat, a hand-built frame, or a completely different line format\n * behind a `contentType` override). Such a value carries its own frame\n * terminator; nothing is appended.\n *\n * `undefined` yields nothing, so a producer can filter without branching\n * at every yield site.\n */\nexport function encodeSseFrame(value: unknown): Uint8Array | undefined {\n  if (value === undefined) return undefined;\n  if (value instanceof Uint8Array) return value;\n  if (typeof value === \"string\") return encoder.encode(value);\n\n  const event =\n    typeof value === \"object\" && value !== null && isSseEvent(value)\n      ? value\n      : { data: value };\n\n  let frame = \"\";\n  if (typeof event.event === \"string\" && event.event.length > 0) {\n    frame += `event: ${singleLine(event.event)}\\n`;\n  }\n  if (typeof event.id === \"string\" || typeof event.id === \"number\") {\n    frame += `id: ${singleLine(String(event.id))}\\n`;\n  }\n  // Whole non-negative milliseconds only: a client parsing anything else\n  // ignores the field, and a route that meant to send one deserves to see\n  // its value rejected here rather than silently dropped on the wire.\n  if (\n    typeof event.retry === \"number\" &&\n    Number.isInteger(event.retry) &&\n    event.retry >= 0\n  ) {\n    frame += `retry: ${event.retry}\\n`;\n  }\n\n  const payload =\n    typeof event.data === \"string\" ? event.data : JSON.stringify(event.data);\n  // JSON.stringify returns undefined for undefined and for a function; an\n  // event with no representable payload still needs its `data` field, or a\n  // client reading `event.data` gets the previous frame's value.\n  for (const line of (payload ?? \"\").split(/\\r\\n|\\r|\\n/)) {\n    frame += `data: ${line}\\n`;\n  }\n  return encoder.encode(`${frame}\\n`);\n}\n\n/**\n * A stream body reduced to the two calls the pump makes of it, so the SSE\n * arm and the raw-passthrough arm share one lifecycle.\n */\ninterface ChunkSource {\n  next(): Promise<{ done?: boolean; value?: Uint8Array | undefined }>;\n  cancel(reason: unknown): Promise<void>;\n}\n\nfunction iterableSource(iterable: AsyncIterable<unknown>): ChunkSource {\n  const iterator = iterable[Symbol.asyncIterator]();\n  return {\n    async next() {\n      const step = await iterator.next();\n      return step.done === true\n        ? { done: true, value: undefined }\n        : { done: false, value: encodeSseFrame(step.value) };\n    },\n    async cancel(reason) {\n      await iterator.return?.(reason);\n    },\n  };\n}\n\nfunction streamSource(stream: ReadableStream<Uint8Array>): ChunkSource {\n  const reader = stream.getReader();\n  return {\n    next: () => reader.read(),\n    cancel: (reason) => reader.cancel(reason),\n  };\n}\n\n/**\n * The comment an event stream opens with.\n *\n * Neither runtime puts the status line on the wire until the body produces\n * its first chunk, so a stream that is quiet to begin with, which is most\n * of them, leaves the client's `fetch` unresolved and an `EventSource`\n * without its `open`. One comment fixes that: the SSE grammar defines it as\n * a no-op, every conforming client discards it, and it costs nine bytes.\n */\nconst SSE_PREAMBLE = \": open\\n\\n\";\n\nexport interface StreamBodyOptions {\n  /** The request's signal. Aborting it cancels the source. */\n  signal: AbortSignal;\n  /**\n   * Open the stream with the SSE comment above, flushing the response\n   * headers before the first event. Only for a response that actually is\n   * an event stream: any other body owns its bytes from the first one.\n   */\n  preamble?: boolean;\n  /**\n   * Called exactly once when the response body is finished, whichever way\n   * it finished: drained, cancelled by a disconnect, or failed mid-flight.\n   * The dispatcher's per-request event hangs off this, which is what makes\n   * `durationMs` span request receipt to stream end.\n   */\n  onEnd: (error?: unknown) => void;\n  /**\n   * Called when tearing the source down fails, which is separate from the\n   * body ending. Cancelling runs the route's own cleanup, and a cleanup that\n   * throws is the route's bug: it must be reported, but it cannot change a\n   * response that has already been delivered and closed out.\n   */\n  onCleanupError?: (error: unknown) => void;\n}\n\n/**\n * Wrap a stream body in a `ReadableStream` that cancels its source when\n * the client goes away.\n *\n * `pull` rather than an eager loop in `start`, so a slow consumer's\n * back-pressure reaches the producer instead of buffering the whole stream\n * in the queue. Disconnect arrives by two doors and both are wired: the\n * runtime cancels the response body (Bun natively, the node shim through\n * `reader.cancel`), and the request's own signal fires. Whichever comes\n * first calls `return()` on the route's iterator, which is what a\n * `for await` loop or a generator's `finally` block sees.\n *\n * A generator deferred on an inner `await` when the client disconnects sees\n * its `return()` queued behind that pending `next()`: async iteration\n * settles a pending step before it delivers a return. A producer that must\n * unblock promptly watches its own cancellation source.\n */\nexport function streamResponseBody(\n  body: AsyncIterable<unknown> | ReadableStream<Uint8Array>,\n  options: StreamBodyOptions,\n): ReadableStream<Uint8Array> {\n  const source =\n    body instanceof ReadableStream ? streamSource(body) : iterableSource(body);\n\n  let ended = false;\n  const end = (error?: unknown): void => {\n    if (ended) return;\n    ended = true;\n    options.signal.removeEventListener(\"abort\", onAbort);\n    options.onEnd(error);\n  };\n  /**\n   * Tear down the source without letting its failure escape.\n   *\n   * Cancelling runs the route's own cleanup: `iterator.return()` lands in a\n   * generator's `finally`, which is exactly where an author writes\n   * `await conn.close()`. A rejection from that had nothing to catch it, and\n   * an unhandled rejection ends the process on both runtimes, so one client\n   * disconnecting from a route whose cleanup failed took the server down.\n   * Reported rather than discarded, and on its own channel: by the time a\n   * cancel settles the body has already ended, so `onEnd` has fired and the\n   * request is closed out. A cleanup that fails afterwards is the route's,\n   * not the response's.\n   */\n  const cancelSource = (reason: unknown): void => {\n    void Promise.resolve(source.cancel(reason)).catch((error: unknown) => {\n      options.onCleanupError?.(error);\n    });\n  };\n  function onAbort(): void {\n    cancelSource(options.signal.reason);\n    end();\n  }\n  options.signal.addEventListener(\"abort\", onAbort, { once: true });\n  // An abort that landed before this wiring never invokes the listener, and\n  // a runtime under no obligation to read a body it has given up on (Bun,\n  // where the response is neither pulled nor cancelled) then leaves the\n  // route's source running with nothing to stop it.\n  if (options.signal.aborted) onAbort();\n\n  return new ReadableStream<Uint8Array>({\n    start(controller) {\n      if (options.preamble === true) {\n        controller.enqueue(encoder.encode(SSE_PREAMBLE));\n      }\n    },\n    async pull(controller) {\n      // The client may have gone while this stream sat in the queue, in\n      // which case no cancel is coming and the pump has to notice itself.\n      if (options.signal.aborted) {\n        cancelSource(options.signal.reason);\n        controller.close();\n        end();\n        return;\n      }\n      try {\n        const step = await source.next();\n        if (step.done === true) {\n          controller.close();\n          end();\n          return;\n        }\n        if (step.value !== undefined && step.value.length > 0) {\n          controller.enqueue(step.value);\n        }\n      } catch (error) {\n        // The status line left long ago, so there is no failure to report\n        // on the wire beyond an unterminated body. The dispatcher logs it.\n        controller.error(error);\n        end(error);\n      }\n    },\n    cancel(reason) {\n      // Ended before the teardown, not after: `return()` into a generator\n      // deferred on an inner await sits behind that pending `next()`, and the\n      // request's completion must not wait on something that may never\n      // settle. Not awaited for the same reason.\n      end();\n      cancelSource(reason);\n    },\n  });\n}\n\n/**\n * The plain SSE response, for a routecraft-owned surface that streams\n * events of its own rather than serving a route's body.\n *\n * The http dispatcher does not use this: a route's response also carries\n * whatever status and headers the exchange asked for, so it builds its own.\n * What both share is the pair of header values, which are decided above.\n */\nexport function sseResponse(\n  events: AsyncIterable<unknown>,\n  signal: AbortSignal,\n  onEnd: () => void = () => {},\n): Response {\n  return new Response(\n    streamResponseBody(events, { signal, preamble: true, onEnd }),\n    {\n      status: 200,\n      headers: {\n        \"content-type\": SSE_CONTENT_TYPE,\n        \"cache-control\": SSE_CACHE_CONTROL,\n      },\n    },\n  );\n}\n","import type { Exchange, ExchangeHeaders } from \"../../exchange\";\nimport type { RouteDiscovery } from \"../../route\";\nimport type { HttpMethod, HttpResponder } from \"../../adapters/http/types\";\nimport type { PathMatcher } from \"./path-matcher\";\nimport type { HttpWebhookSignatureOptions } from \"./webhook-signature\";\n\n/**\n * One entry in an http mount's route registry. Created when a\n * `from(http({...}))` source subscribes and removed on abort. The mount's\n * dispatcher matches incoming requests against this registry.\n *\n * The route's `handler` is the runtime-provided callback that turns a message\n * into a fully-processed {@link Exchange}. The source's job is just to call\n * it (and to convert the result back into the wire format).\n */\nexport interface HttpRouteEntry {\n  readonly routeId: string;\n  readonly method: HttpMethod;\n  /** Matcher over the FULL request path (mount prefix already joined in). */\n  readonly matcher: PathMatcher;\n  /**\n   * The route declares a route-entry `.authorize()`. On a walled mount this\n   * is redundant (the wall already ran); on a public mount it forces the\n   * dispatcher to pull credential verification for this route.\n   */\n  readonly requiresPrincipal: boolean;\n  /** Whether the route opted in to `routecraft.http.rawBody` on the exchange. */\n  readonly rawBody: boolean;\n  /** Webhook-signature gate; requests failing verification 401 before the route runs. */\n  readonly signature: HttpWebhookSignatureOptions | undefined;\n  /**\n   * Decides when the caller is answered and with what. Undefined leaves the\n   * dispatcher's own path, which awaits the pipeline and serialises it.\n   */\n  readonly respond: HttpResponder | undefined;\n  /** Route-level discovery bundle, used by /openapi.json. */\n  readonly discovery: RouteDiscovery | undefined;\n  /** Provided by the source on subscribe; the dispatcher calls it once it has a parsed body. */\n  readonly handler: (\n    body: unknown,\n    headers: ExchangeHeaders,\n  ) => Promise<Exchange>;\n}\n\n/**\n * Per-mount route registry. The http plugin instantiates one per configured\n * mount; source adapters resolve their mount by name and push/pop entries.\n */\nexport type HttpRouteRegistry = Map<string, HttpRouteEntry>;\n\n/**\n * Read-only view over route entries, satisfied by a single registry Map and\n * by the combined all-mounts view the built-ins (`/ready`, `/openapi.json`)\n * consume so they report every mount's routes.\n */\nexport interface HttpRouteView {\n  readonly size: number;\n  values(): IterableIterator<HttpRouteEntry>;\n}\n\n/**\n * What the http source needs to know about one configured mount: where its\n * routes register and which path prefix route patterns are joined onto.\n */\nexport interface HttpMountRuntime {\n  /** Mount path prefix; `\"/\"` for the catch-all. */\n  readonly path: string;\n  readonly registry: HttpRouteRegistry;\n}\n\n/**\n * Symbol key sharing the mount table between the http plugin (which creates\n * and owns it) and the http source (which resolves a mount by name and\n * inserts / removes route entries). `Symbol.for` so the key is shared across\n * any duplicate package copies in a workspace (matches the convention used\n * by every other plugin in `.standards/adapter-architecture.md`).\n */\nexport const HTTP_MOUNTS: unique symbol = Symbol.for(\n  \"routecraft.plugin.http.mounts\",\n);\n\n/**\n * Symbol key used by the http source to assert the plugin has been\n * registered. Set to `true` in `httpPlugin.apply(ctx)`. The source throws\n * `RC5003` when it is missing so misconfiguration fails at subscribe time.\n */\nexport const HTTP_PLUGIN_REGISTERED: unique symbol = Symbol.for(\n  \"routecraft.plugin.http.registered\",\n);\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [HTTP_MOUNTS]: ReadonlyMap<string, HttpMountRuntime>;\n    [HTTP_PLUGIN_REGISTERED]: boolean;\n  }\n}\n","import { readFileSync, statSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/**\n * Subset of `package.json` fields the http plugin auto-detects for the\n * OpenAPI `info` block. Conservative on purpose: only `name` and `version`\n * are public-by-nature on npm. Description / author / license are NOT\n * pulled here even when present, so they cannot accidentally leak\n * through the publicly-served `/openapi.json` doc.\n */\nexport interface PackageInfo {\n  name?: string;\n  version?: string;\n}\n\n/**\n * Walk upward from `start` looking for the nearest `package.json` and\n * return its `name` / `version`. Returns `{}` (no fields) if no\n * `package.json` is reachable. Never throws -- the plugin must still\n * apply when running in environments without a `package.json` on disk\n * (single-file bundled binaries, Docker scratch images), falling back\n * to hard-coded defaults in the OpenAPI builder.\n *\n * Resolution rule when a `package.json` IS present at a given level: the\n * walk commits to that level and never falls through to a parent, since\n * an ancestor's metadata is by definition less related to the running\n * service than the nearest manifest. Concretely:\n *\n * - Unreadable or malformed manifest: return `{}`. A corrupt local\n *   manifest must not silently get replaced with an unrelated parent's\n *   `name` / `version` on the publicly-served `/openapi.json`.\n * - Workspace-container manifest (a `workspaces` field, or a\n *   `pnpm-workspace.yaml` beside it): return `{}`. The container is\n *   repository infrastructure, not a service identity; it is typically\n *   private, often versionless, and changesets-style tooling never\n *   versions it, so its `version` silently goes stale. Advertising it\n *   on a public document mis-attributes the service, so the safe\n *   default is no identity at all (the OpenAPI builder's neutral\n *   fallbacks apply) until the caller sets `builtins.openapi.info`.\n *\n * `private: true` alone is NOT treated as a container marker: plenty of\n * real, deliberately-unpublished apps are private, and their own\n * `name` / `version` is exactly the identity their `/openapi.json`\n * should carry.\n */\nexport function findPackageInfo(start: string = process.cwd()): PackageInfo {\n  let dir = start;\n  // Bounded climb to avoid surprises on misconfigured environments. 32 is\n  // far beyond any realistic project depth.\n  for (let i = 0; i < 32; i++) {\n    const candidate = join(dir, \"package.json\");\n    let exists = false;\n    try {\n      exists = statSync(candidate).isFile();\n    } catch {\n      // statSync throws when the candidate doesn't exist (ENOENT) or on\n      // permission errors. Treat both as \"not here, try the parent\" -- the\n      // only path where falling through to a parent directory is correct.\n      exists = false;\n    }\n    if (exists) {\n      try {\n        const parsed = JSON.parse(readFileSync(candidate, \"utf8\")) as Record<\n          string,\n          unknown\n        >;\n        if (isWorkspaceContainer(parsed, dir)) return {};\n        const info: PackageInfo = {};\n        if (typeof parsed[\"name\"] === \"string\") info.name = parsed[\"name\"];\n        if (typeof parsed[\"version\"] === \"string\") {\n          info.version = parsed[\"version\"];\n        }\n        return info;\n      } catch {\n        return {};\n      }\n    }\n    const parent = dirname(dir);\n    if (parent === dir) break;\n    dir = parent;\n  }\n  return {};\n}\n\n/**\n * A manifest counts as a workspace container when it declares workspaces\n * itself (npm / yarn / bun keep them in `package.json`) or when a\n * `pnpm-workspace.yaml` sits beside it (pnpm keeps them out of the\n * manifest entirely).\n */\nfunction isWorkspaceContainer(\n  manifest: Record<string, unknown>,\n  dir: string,\n): boolean {\n  const workspaces = manifest[\"workspaces\"];\n  if (Array.isArray(workspaces)) return true;\n  if (typeof workspaces === \"object\" && workspaces !== null) return true;\n  try {\n    return statSync(join(dir, \"pnpm-workspace.yaml\")).isFile();\n  } catch {\n    return false;\n  }\n}\n","import { rcError } from \"../../error\";\n\n/**\n * Validate and normalise a static pathname claim: an http mount prefix or the\n * MCP endpoint path.\n *\n * Dispatch compares the request URL's parsed pathname literally against these\n * strings, so a claim the WHATWG parser would rewrite (dot segments raw or\n * encoded, backslashes, spaces, non-ASCII) can never match what the server\n * dispatches on, and percent-encoding makes two spellings of the same\n * resource compare differently. A colon is allowed inside a segment (a legal\n * pathname character the parser preserves) but not at its start, which is the\n * `:param` shape route patterns treat as dynamic. Everything outside the\n * canonical form is refused at construction with RC5003.\n *\n * Normalisation strips exactly one trailing slash (`\"/api/\"` becomes\n * `\"/api\"`); repeated trailing slashes are a typo and fall through to the\n * empty-segment rejection instead of being silently collapsed, including the\n * bare `\"//\"` that would otherwise collapse into the catch-all.\n */\nexport function normalizeStaticPathPrefix(raw: unknown, owner: string): string {\n  const shown = typeof raw === \"string\" ? JSON.stringify(raw) : String(raw);\n  if (typeof raw !== \"string\" || !raw.startsWith(\"/\")) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `${owner}: invalid path ${shown}. Pass an absolute prefix such as \"/api\" (or \"/\" for the catch-all).`,\n    });\n  }\n  const path = raw.length > 1 ? raw.replace(/\\/$/, \"\") : raw;\n  if (\n    (path === \"/\" && raw !== \"/\") ||\n    (path !== \"/\" &&\n      !/^\\/(?:[^/?#:\\\\%][^/?#\\\\%]*\\/)*[^/?#:\\\\%][^/?#\\\\%]*$/.test(path))\n  ) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `${owner}: invalid path ${shown}. Paths are static pathname prefixes: no \"?\", \"#\", \":param\" segments, empty segments, backslashes, or percent-encoding.`,\n    });\n  }\n  if (new URL(path, \"http://routecraft.invalid\").pathname !== path) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `${owner}: invalid path ${shown}. Paths must be canonical pathnames: no \".\" or \"..\" segments, spaces, or characters the URL parser rewrites.`,\n    });\n  }\n  return path;\n}\n","/**\n * Compile a path pattern into a matcher closure.\n *\n * Supports literal segments and `:param` segments. Pattern and pathname are\n * tokenised on `/`; an empty leading token (from the leading `/`) and any\n * empty trailing token (from a trailing `/`) are dropped so `\"/orders\"`,\n * `\"/orders/\"`, and the pathname `\"/orders/\"` all behave the same way.\n *\n * URL-decoding happens once per matched segment so handlers receive the\n * decoded value (`\"hello world\"`, not `\"hello%20world\"`).\n *\n * URLPattern would do all of this, but it is not a global in Node 22. Doing\n * it by hand keeps the http source dependency-free; richer patterns\n * (constraints, wildcards) can move to URLPattern when the minimum Node\n * version catches up.\n */\n\nexport interface PathMatcher {\n  /** Try to match a concrete pathname. Returns the resolved params on success, null on miss. */\n  match(pathname: string): Readonly<Record<string, string>> | null;\n  /** Original pattern, e.g. `/orders/:id`. */\n  readonly pattern: string;\n  /** Names of `:param` segments in the pattern, in declaration order. */\n  readonly paramNames: readonly string[];\n}\n\n/** Literal prefix before the first parameter segment, used for mount conflict checks. */\nexport function staticPathPrefix(pattern: string): string {\n  const segments = tokenise(pattern);\n  const literals: string[] = [];\n  for (const segment of segments) {\n    if (segment.startsWith(\":\")) break;\n    literals.push(segment);\n  }\n  return literals.length === 0 ? \"/\" : `/${literals.join(\"/\")}`;\n}\n\ninterface CompiledSegment {\n  readonly literal: string | null;\n  readonly param: string | null;\n}\n\nfunction tokenise(value: string): string[] {\n  const stripped = value.replace(/\\/+$/, \"\");\n  if (stripped === \"\" || stripped === \"/\") return [];\n  return stripped.split(\"/\").filter((s) => s !== \"\");\n}\n\nfunction compileSegment(segment: string, pattern: string): CompiledSegment {\n  if (segment.startsWith(\":\")) {\n    const name = segment.slice(1);\n    if (name === \"\") {\n      throw new Error(\n        `compilePathMatcher: empty parameter name in pattern \"${pattern}\"`,\n      );\n    }\n    return { literal: null, param: name };\n  }\n  return { literal: segment, param: null };\n}\n\n/**\n * Compile a pattern string into a {@link PathMatcher}. Throws on malformed\n * patterns (empty `:` parameter names) so misconfiguration fails at startup\n * rather than per request.\n */\nexport function compilePathMatcher(pattern: string): PathMatcher {\n  const segments = tokenise(pattern).map((seg) => compileSegment(seg, pattern));\n  const paramNames = segments\n    .map((s) => s.param)\n    .filter((p): p is string => p !== null);\n\n  return {\n    pattern,\n    paramNames,\n    match(pathname: string): Readonly<Record<string, string>> | null {\n      const tokens = tokenise(pathname);\n      if (tokens.length !== segments.length) return null;\n      const params: Record<string, string> = {};\n      for (let i = 0; i < segments.length; i++) {\n        const seg = segments[i]!;\n        const token = tokens[i]!;\n        if (seg.literal !== null) {\n          if (seg.literal !== token) return null;\n          continue;\n        }\n        if (seg.param !== null) {\n          try {\n            params[seg.param] = decodeURIComponent(token);\n          } catch {\n            // Malformed percent-encoding: treat as a non-match rather than\n            // surfacing a decode error to the client.\n            return null;\n          }\n        }\n      }\n      return Object.freeze(params);\n    },\n  };\n}\n","import { registerConfigApplier } from \"../../config-applier\";\nimport { httpPlugin } from \"./plugin\";\nimport type { HttpConfig } from \"../../adapters/http/types\";\n\ndeclare module \"@routecraft/routecraft\" {\n  interface CraftConfig {\n    /** HTTP server config for inbound http() sources (port, auth, etc.) */\n    http?: HttpConfig;\n  }\n}\n\n/**\n * Register the `http` config key so `defineConfig({ http: {...} })` is\n * equivalent to `defineConfig({ plugins: [httpPlugin({...})] })`. Loaded as\n * a side-effect import from `packages/routecraft/src/index.ts` so users do\n * not have to wire it manually.\n */\nregisterConfigApplier(\"http\", (options) => httpPlugin(options));\n","/**\n * Ops plugin: the operational surface, with health as its first capability.\n *\n * It folds framework lifecycle events into a per-context {@link HealthState}\n * and serves the result over HTTP. The judgement lives in `state.ts` and the\n * response contract in `report.ts`; this file is the wiring.\n *\n * The surface is a mount on a named server rather than a listener of its own,\n * so an internal-only ops port is a second entry in `defineConfig({ servers })`\n * that this mount points at, and the socket's lifecycle belongs to the server\n * plugin.\n */\n\nimport type { CraftContext, CraftPlugin } from \"../../context\";\nimport { parseDuration } from \"../../shared/duration.ts\";\nimport { rcError } from \"../../error\";\nimport { requireWebIngress } from \"../server/registry\";\nimport type { PathClaim } from \"../server/types\";\nimport {\n  bindIndicator,\n  isIndicator,\n  unbindIndicator,\n  unboundIndicators,\n} from \"./indicator\";\nimport { createManagementApi } from \"./management\";\nimport { createManagementHandler } from \"./mount\";\nimport { createHealthHandler } from \"./report\";\nimport { HealthState } from \"./state\";\nimport {\n  OPS_CONTRIBUTED_INDICATORS,\n  OPS_HEALTH_STATE,\n  type ContributedIndicator,\n} from \"./store\";\nimport { enforcesWall } from \"./tier\";\nimport type { Health, Indicator, OpsPluginOptions, OpsTiers } from \"./types\";\n\n/**\n * Everything the mount answers. Claimed exhaustively so the server's\n * bind-time validation catches a collision with another surface rather than\n * letting dispatch order decide who owns `/health`.\n *\n * `/ops` carries the management API. The prefix is claimed whole even when\n * every tier is disabled, so a disabled tier answers this mount's 404\n * rather than falling through to whatever else a shared listener carries.\n */\nconst CLAIMS: readonly PathClaim[] = [\n  { kind: \"prefix\", path: \"/health\" },\n  { kind: \"prefix\", path: \"/ops\" },\n];\n\n/** Per-context state. One plugin instance may serve several contexts. */\ninterface Runtime {\n  state: HealthState;\n  unsubscribes: (() => void)[];\n  /** The mount's effective validator exists (its own auth, or the server's). */\n  authConfigured: boolean;\n  /** Every indicator name registered on the ledger, from options and contributions. */\n  indicatorNames: Set<string>;\n  /** Contributed indicators bound at start, with this ledger's sink, released at teardown. */\n  contributed: Array<{\n    entry: ContributedIndicator;\n    sink: (health: Health, reportedAt: number) => void;\n  }>;\n  unmount?: () => void;\n}\n\n/**\n * The operational surface for a routecraft app.\n *\n * Materialised by the config applier, so apps normally configure it with\n * `defineConfig({ ops: {} })` rather than pushing it onto `config.plugins`.\n * The function is exported for advanced wiring.\n *\n * What it reports needs no application code: route lifecycle, circuit-breaker\n * position and the context's own serving state are all derived from events the\n * framework already emits. Indicators are the one thing an app adds by hand,\n * for dependencies the framework cannot see.\n *\n * Lifecycle:\n * - `apply(ctx)`: build the ledger, bind indicators, subscribe to lifecycle\n *   events, and register the mount. Nothing is listening yet, so a\n *   misconfiguration fails the build rather than a live surface.\n * - `start(ctx)`: check that every route-bound indicator names a real route.\n *   The server binds its listener in its own `start()`, after routes are up,\n *   so a probe arriving before that gets connection refused, which every\n *   orchestrator reads as not-ready.\n * - `teardown(ctx)`: unmount, unsubscribe, and release the indicator bindings.\n *\n * The health surface never walls, whatever `auth` says: the ingress never\n * authenticates on its own, and this surface calls `authenticate()` only to\n * decide whether to serve `details`. A probe carrying no credential still\n * gets every status, which is the only way an orchestrator can use it, while\n * an operator holding a token the effective validator (the mount's own\n * `auth`, else the server's) admits also gets the diagnostics.\n */\nexport function opsPlugin(options: OpsPluginOptions = {}): CraftPlugin {\n  validate(options);\n\n  const serverName = options.server ?? \"default\";\n  const detailsExposure = options.health?.details ?? \"when-authenticated\";\n  const detailsExplicit = options.health?.details !== undefined;\n  const mountAuthOption = options.auth;\n  const tiers: OpsTiers = options.tiers ?? {};\n  const indicators: readonly Indicator[] = options.indicators ?? [];\n\n  const runtimes = new WeakMap<CraftContext, Runtime>();\n\n  return {\n    name: \"ops\",\n\n    apply(ctx: CraftContext) {\n      // Everything below is resolved and validated before anything with a\n      // side effect happens. The boot unwind is not guaranteed to reach this\n      // plugin's teardown, so a binding or subscription installed before a\n      // later throw would outlive the dead context.\n      const ingress = requireWebIngress(ctx, serverName);\n      const mountAuth = ingress.resolveMountAuth(mountAuthOption);\n\n      // Explicit intent with nothing to gate on is refused; only the\n      // unwritten default may collapse (to `never`, in the handler).\n      if (\n        detailsExplicit &&\n        detailsExposure === \"when-authenticated\" &&\n        !mountAuth.configured\n      ) {\n        throw rcError(\"RC5053\", undefined, {\n          message: `ops.health.details is \"when-authenticated\" but no validator is in scope: the ops mount declares no auth and servers.${serverName} has none. Set ops.auth (or servers.${serverName}.auth) to gate details, \"always\" to serve them to every caller, or \"never\" to withhold them.`,\n        });\n      }\n\n      // Gated on `walled`, not `configured`: a tier scope check refuses the\n      // request, so it is a wall, and `auth: false` says this mount declares\n      // none while keeping the inherited validator reachable for pulls.\n      for (const [name, value] of Object.entries(tiers)) {\n        if (typeof value !== \"string\" || mountAuth.walled) continue;\n        throw rcError(\"RC5053\", undefined, {\n          message: `ops.tiers.${name} requires the scope \"${value}\" but no validator is in scope: the ops mount ${mountAuthOption === false ? \"opted out of auth with `auth: false`\" : \"declares no auth\"} and servers.${serverName} has none. Set ops.auth (or servers.${serverName}.auth) so a credential can be verified, or set the tier to true to expose it without one.`,\n        });\n      }\n\n      // Refused here rather than at mountHttp: by the time the mount is\n      // registered this apply() has already replaced the published ledger and\n      // rebound every indicator to it, so a second instance would leave the\n      // already-mounted handler reporting from a ledger nothing writes to.\n      if (ingress.hasMount(\"ops\")) {\n        throw rcError(\"RC5053\", undefined, {\n          message: `servers.${serverName} already carries an ops mount. One ops surface per server: configure it once through defineConfig({ ops }), or point the second at another named server.`,\n        });\n      }\n\n      const state = new HealthState({\n        onChange: (change) => {\n          ctx.emit(\"plugin:ops:health:changed\", change);\n        },\n      });\n      const names = new Set<string>();\n      const runtime: Runtime = {\n        state,\n        unsubscribes: [],\n        authConfigured: mountAuth.configured,\n        indicatorNames: names,\n        contributed: [],\n      };\n      runtimes.set(ctx, runtime);\n      ctx.setStore(OPS_HEALTH_STATE, state);\n\n      for (const indicator of indicators) {\n        if (!isIndicator(indicator)) {\n          throw rcError(\"RC5053\", undefined, {\n            message: `ops.indicators contains a value defineIndicator() did not produce. Declare indicators with defineIndicator({ name }); an object of the same shape has no ledger to report into.`,\n          });\n        }\n        if (names.has(indicator.name)) {\n          throw rcError(\"RC5053\", undefined, {\n            message: `Duplicate indicator name \"${indicator.name}\" in ops.indicators. Indicator names are the keys of the health report, so they must be unique.`,\n          });\n        }\n        names.add(indicator.name);\n      }\n\n      for (const indicator of indicators) {\n        const { maxAge, domain } = indicator.definition;\n        const maxAgeMs =\n          maxAge === undefined ? undefined : parseDuration(maxAge, \"maxAge\");\n        state.registerIndicator(indicator.name, {\n          ...(maxAgeMs !== undefined ? { maxAgeMs } : {}),\n          ...(domain !== undefined ? { domain } : {}),\n        });\n        bindIndicator(indicator, ctx, state);\n      }\n\n      // Indicators bound to a route, keyed by route id, so one subscription\n      // serves however many indicators name the same probe.\n      const boundIndicators = new Map<string, string[]>();\n      for (const indicator of indicators) {\n        const boundRoute = indicator.definition.route;\n        if (boundRoute === undefined) continue;\n        const names = boundIndicators.get(boundRoute) ?? [];\n        names.push(indicator.name);\n        boundIndicators.set(boundRoute, names);\n      }\n      const hasBoundIndicators = boundIndicators.size > 0;\n\n      const { unsubscribes } = runtime;\n      unsubscribes.push(\n        // `context:started` is deliberately not subscribed. It fires before\n        // routes are started, so readiness taken from it would answer 200 to\n        // an orchestrator while a source is still coming up. The context is\n        // marked started in this plugin's own start() hook instead, which the\n        // framework runs after route readiness settles.\n        ctx.on(\"context:stopping\", () => state.contextStopping()),\n        ctx.on(\"route:started\", ({ details }) => {\n          state.routeStarted(details.routeId);\n        }),\n        ctx.on(\"route:stopped\", ({ details }) => {\n          state.routeStopped(details.routeId);\n        }),\n        // Disabled is reported distinctly from failed, WITH its reason, and\n        // never degrades the aggregate: an operator reading /ops sees\n        // \"mail-inbound: disabled (MAIL_USER, MAIL_APP_PASSWORD unset)\" and\n        // knows immediately that nothing is broken.\n        ctx.on(\"route:enablement:changed\", ({ details }) => {\n          if (details.enabled) {\n            state.clearRouteDisabled(details.routeId);\n          } else {\n            state.setRouteDisabled(\n              details.routeId,\n              details.reason ?? \"disabled by its enabled() predicate\",\n            );\n          }\n        }),\n        // The only route-liveness signal. `context:error` is deliberately not\n        // subscribed: it fires for every unhandled exchange error and for any\n        // throwing event handler, so reading it as a dead source would make\n        // one refused caller report the route down.\n        ctx.on(\"route:source:failed\", ({ details }) => {\n          state.sourceDied(details.routeId);\n        }),\n        ctx.on(\"route:exchange:completed\", ({ details }) => {\n          state.exchangeCompleted(details.routeId);\n          if (hasBoundIndicators) {\n            for (const name of boundIndicators.get(details.routeId) ?? []) {\n              state.reportIndicator(name, { status: \"up\" });\n            }\n          }\n        }),\n        // `route:exchange:dropped` is deliberately not subscribed. A drop is\n        // the third terminal state and suppresses `completed`, but it is not\n        // evidence either way: the exchange may have been filtered out before\n        // the dependency was ever reached. Reporting a verdict from it would\n        // be inventing one, so a bound indicator on a route that only drops\n        // goes stale, which is the truthful answer.\n        ctx.on(\"route:exchange:failed\", ({ details }) => {\n          state.exchangeFailed(details.routeId);\n          if (hasBoundIndicators) {\n            for (const name of boundIndicators.get(details.routeId) ?? []) {\n              state.reportIndicator(name, { status: \"down\" });\n            }\n          }\n        }),\n        // A breaker is the one thing that turns repeated failure into a health\n        // signal, because it is the one thing that actually stops the route\n        // serving. Both scopes count: a step-scope breaker still means part of\n        // this route is refusing work.\n        ctx.on(\"route:circuitBreaker:opened\", ({ details }) => {\n          state.circuitOpened(details.routeId, details.stepLabel, \"open\");\n        }),\n        ctx.on(\"route:circuitBreaker:halfOpen\", ({ details }) => {\n          state.circuitOpened(details.routeId, details.stepLabel, \"half-open\");\n        }),\n        ctx.on(\"route:circuitBreaker:closed\", ({ details }) => {\n          state.circuitClosed(details.routeId, details.stepLabel);\n        }),\n      );\n\n      const health = createHealthHandler({\n        state,\n        details: detailsExposure,\n        uptime: () => process.uptime(),\n      });\n      const management = createManagementHandler({\n        api: createManagementApi(ctx),\n        tiers,\n        onRefused: ({ reason, scheme }) => {\n          ctx.emit(\"auth:rejected\", { reason, scheme, source: \"ops\" });\n        },\n      });\n\n      // One mount, two surfaces with opposite postures. Management is\n      // offered the request first and answers `undefined` for anything\n      // outside `/ops`, so neither surface has to know the other's routing\n      // table and `/health` keeps answering exactly as it did.\n      const handler = async (\n        req: Request,\n        mountContext: Parameters<typeof health>[1],\n      ): Promise<Response> =>\n        (await management(req, mountContext)) ?? health(req, mountContext);\n\n      // The scopes the RFC 9728 document may advertise: exactly the tier\n      // gates an operator configured, deduplicated in configuration order.\n      // Boolean tiers contribute nothing; there is no scope to name.\n      const tierScopes = [\n        ...new Set(\n          Object.values(tiers).filter(\n            (value): value is string => typeof value === \"string\",\n          ),\n        ),\n      ];\n      runtime.unmount = ingress.mountHttp({\n        id: \"ops\",\n        // The health paths never wall, so the flag answers for the mount as\n        // a whole only when a management tier actually gates on a scope.\n        // Without that, the registry's inherited-authentication log would\n        // claim a gate this mount never runs.\n        enforcesWall: enforcesWall(tiers),\n        ...(mountAuthOption !== undefined ? { auth: mountAuthOption } : {}),\n        ...(tierScopes.length > 0\n          ? { resourceMetadata: { scopesSupported: tierScopes } }\n          : {}),\n        claims: () => CLAIMS,\n        handler,\n      });\n    },\n\n    start(ctx: CraftContext) {\n      const runtime = runtimes.get(ctx);\n      if (!runtime) return;\n\n      // An indicator naming a route that does not exist is a typo that would\n      // otherwise present as a dependency stuck reporting nothing. Routes are\n      // registered by the time start() runs, so this is the first point the\n      // check can be made.\n      const known = new Set(\n        ctx.getRoutes().map((route) => route.definition.id),\n      );\n      for (const indicator of indicators) {\n        const boundRoute = indicator.definition.route;\n        if (boundRoute !== undefined && !known.has(boundRoute)) {\n          throw rcError(\"RC5053\", undefined, {\n            message: `Indicator \"${indicator.name}\" is bound to route \"${boundRoute}\", which no route declares. Known routes: ${[...known].sort().join(\", \") || \"(none)\"}.`,\n          });\n        }\n      }\n\n      // Every declared route is listed, whether or not it signalled. Route\n      // readiness is bounded by a timeout, so a source that never signals\n      // would otherwise be missing from the report rather than shown as\n      // unproven. Routes that did signal already have their real state.\n      for (const route of ctx.getRoutes()) {\n        runtime.state.declareRoute(route.definition.id);\n      }\n\n      // Routes disabled during the boot: their `route:enablement:changed`\n      // fired while the context was starting, which is before this plugin's\n      // start() hook runs, so the subscription above missed it. Replayed\n      // from the context's own record rather than by re-evaluating the\n      // predicates, which would run a user's credential check a second time\n      // for a state the context already holds.\n      for (const [routeId, reason] of ctx.disabledRoutes()) {\n        runtime.state.setRouteDisabled(routeId, reason);\n      }\n\n      // Reaching this with the gate mode and no validator means the\n      // unwritten default collapsed; the explicit case was refused at apply.\n      if (detailsExposure === \"when-authenticated\" && !runtime.authConfigured) {\n        ctx.logger.warn(\n          { server: serverName, plugin: \"ops\" },\n          `ops.health serves statuses only: no validator is in scope, so the default \"when-authenticated\" gate withholds per-component details from every caller. Set ops.auth (or servers.${serverName}.auth) to gate them, or health.details: \"always\" to serve them to everyone.`,\n        );\n      }\n\n      // Indicators other plugins contributed from their apply(), bound here\n      // because a contributor may have applied after this plugin did. Names\n      // share one report with ops.indicators, so a clash is refused rather\n      // than letting whichever registered last own the key.\n      for (const entry of ctx.getStore(OPS_CONTRIBUTED_INDICATORS)?.values() ??\n        []) {\n        if (runtime.indicatorNames.has(entry.name)) {\n          throw rcError(\"RC5053\", undefined, {\n            message: `Indicator \"${entry.name}\" is both listed in ops.indicators and contributed by a plugin. Indicator names are the keys of the health report, so they must be unique.`,\n          });\n        }\n        runtime.indicatorNames.add(entry.name);\n        const maxAgeMs =\n          entry.maxAge === undefined\n            ? undefined\n            : parseDuration(entry.maxAge, \"maxAge\");\n        runtime.state.registerIndicator(entry.name, {\n          ...(maxAgeMs !== undefined ? { maxAgeMs } : {}),\n          ...(entry.domain !== undefined ? { domain: entry.domain } : {}),\n        });\n        const { state } = runtime;\n        const sink = (health: Health, reportedAt: number): void => {\n          state.reportIndicator(entry.name, health, reportedAt);\n        };\n        entry.sinks.add(sink);\n        // A contributor whose start() already ran reported into nothing; its\n        // last verdict is what the ledger should open with, at the time it\n        // was made, so a maxAge window is measured from the report and not\n        // from this binding.\n        if (entry.last !== undefined) sink(entry.last.health, entry.last.at);\n        runtime.contributed.push({ entry, sink });\n      }\n\n      const unbound = unboundIndicators();\n      if (unbound.length > 0) {\n        ctx.logger.warn(\n          { indicators: unbound, plugin: \"ops\" },\n          `Indicators declared but not registered: ${unbound.join(\", \")}. A push through an unregistered handle is inert, so these dependencies would never appear in the health report. Add them to ops.indicators.`,\n        );\n      }\n\n      // Routes have started by the time a plugin's start() hook runs, so this\n      // is the first moment the context can honestly claim to be serving.\n      runtime.state.contextStarted();\n    },\n\n    teardown(ctx: CraftContext) {\n      const runtime = runtimes.get(ctx);\n      if (!runtime) return;\n\n      // teardown must tolerate its own start() never having run: the unwind\n      // after a failed boot tears down every applied plugin. Unwinding in\n      // `finally` keeps the subscriptions and bindings from leaking if the\n      // unmount throws.\n      try {\n        runtime.unmount?.();\n      } finally {\n        // The terminal state is set here rather than from `context:stopped`,\n        // which the framework emits after every teardown has run and so after\n        // these subscriptions are gone. Without it a store reader would see a\n        // context draining forever.\n        runtime.state.contextStopped();\n        for (const unsubscribe of runtime.unsubscribes) unsubscribe();\n        for (const indicator of indicators) unbindIndicator(indicator, ctx);\n        for (const { entry, sink } of runtime.contributed) {\n          entry.sinks.delete(sink);\n        }\n        runtimes.delete(ctx);\n      }\n    },\n  };\n}\n\nfunction validate(options: OpsPluginOptions): void {\n  for (const [name, value] of Object.entries(options.tiers ?? {})) {\n    if (typeof value === \"boolean\" || value === undefined) continue;\n    if (typeof value !== \"string\") {\n      throw rcError(\"RC5053\", undefined, {\n        message: `ops.tiers.${name} must be false, true, or a scope string; received ${JSON.stringify(value)}.`,\n      });\n    }\n    if (value.trim() === \"\") {\n      throw rcError(\"RC5053\", undefined, {\n        message: `ops.tiers.${name} is an empty scope string, which no principal can carry and so refuses every caller. Use false to disable the tier, true to expose it without a credential, or a real scope name.`,\n      });\n    }\n  }\n  const exposure = options.health?.details;\n  if (\n    exposure !== undefined &&\n    exposure !== \"always\" &&\n    exposure !== \"when-authenticated\" &&\n    exposure !== \"never\"\n  ) {\n    throw rcError(\"RC5053\", undefined, {\n      message: `opsPlugin: invalid health.details ${JSON.stringify(exposure)}. Use \"always\", \"when-authenticated\", or \"never\".`,\n    });\n  }\n}\n","/**\n * Indicator handles: the one thing an app writes by hand for health.\n *\n * Routes, circuit breakers and the serving lifecycle are all derived from\n * events the framework already emits, so an app that only wants those writes\n * no code at all. An indicator exists for the other case: a dependency whose\n * health the framework cannot see, such as a mailbox, a third-party API, or a\n * licence server.\n */\n\nimport { parseDuration } from \"../../shared/duration.ts\";\nimport { rejectStaleOptions } from \"../../shared/stale-options.ts\";\nimport { rcError } from \"../../error\";\nimport type { CraftContext } from \"../../context\";\nimport type { HealthState } from \"./state\";\nimport type { Indicator, IndicatorDefinition } from \"./types\";\n\ninterface Bound {\n  ctx: CraftContext;\n  state: HealthState;\n}\n\n/**\n * The binding side-channel, keyed by handle.\n *\n * Kept off the handle object so `Indicator` stays a plain read-and-push\n * surface: a hand-written object satisfying `Indicator` structurally is\n * therefore detectable (it has no entry here) rather than crashing on a\n * missing method when the plugin tries to bind it.\n */\nconst binders = new WeakMap<Indicator, Bound[]>();\n\n/**\n * Every handle `defineIndicator` produced, so the plugin can report the ones\n * an app forgot to register. Strongly held on purpose: handles are\n * module-scope constants whose lifetime is the process anyway, and the set is\n * bounded by how many an app declares in source.\n */\nconst declared = new Set<Indicator>();\n\n/**\n * Bind a handle to a context's ledger. Bindings are keyed by context, never\n * held in a single slot, because one plugin instance may serve several\n * contexts in a process.\n *\n * @internal\n */\nexport function bindIndicator(\n  indicator: Indicator,\n  ctx: CraftContext,\n  state: HealthState,\n): void {\n  // Callers validate with `isIndicator` before binding, so a missing entry\n  // cannot happen here; the plugin owns the refusal and its message.\n  const bound = binders.get(indicator)!;\n  const existing = bound.findIndex((entry) => entry.ctx === ctx);\n  if (existing >= 0) bound.splice(existing, 1);\n  bound.push({ ctx, state });\n}\n\n/**\n * Release a handle's binding to one context.\n *\n * @internal\n */\nexport function unbindIndicator(indicator: Indicator, ctx: CraftContext): void {\n  const bound = binders.get(indicator);\n  if (!bound) return;\n  const index = bound.findIndex((entry) => entry.ctx === ctx);\n  if (index >= 0) bound.splice(index, 1);\n}\n\n/**\n * Whether this handle came from {@link defineIndicator}.\n *\n * @internal\n */\nexport function isIndicator(value: unknown): value is Indicator {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    binders.has(value as Indicator)\n  );\n}\n\n/**\n * Refuse a name that cannot be an indicator's.\n *\n * The name is the report key and one path segment of\n * `/health/indicators/<name>`. A slash would split that segment, and `.` or\n * `..` are eaten by URL normalisation before the handler ever sees them, so\n * either way the component is unreachable at its own path: a typo that\n * would otherwise present as an endpoint that is simply missing.\n *\n * @internal\n */\nexport function assertIndicatorName(name: string, surface: string): void {\n  if (name.trim() === \"\") {\n    throw rcError(\"RC5053\", undefined, {\n      message: `${surface}: name must not be empty.`,\n    });\n  }\n  if (name === \".\" || name === \"..\" || name !== encodeURIComponent(name)) {\n    throw rcError(\"RC5053\", undefined, {\n      message: `${surface}(\"${name}\"): name must be usable as a single URL path segment. It is the key in the health report and the last segment of /health/indicators/<name>, so it cannot contain a slash, a space, or any character needing percent-encoding.`,\n    });\n  }\n}\n\n/**\n * Declare an indicator: a named dependency whose health the app reports.\n *\n * The returned handle is both the declaration and the push surface, and it is\n * inert until an ops plugin binds it to a context. Register it through\n * `ops.indicators` so a push has a ledger to land in; a handle that is never\n * registered is reported at context start, where the message can name the fix,\n * rather than by throwing from whatever step happened to push it.\n *\n * Two ways to report, and the first needs no code in the route:\n *\n * ```typescript\n * // Bound to a probe route: a completed exchange reports up, a failed one\n * // reports down, and no exchange within maxAge goes stale.\n * export const mailHealth = defineIndicator({\n *   name: \"mail\",\n *   maxAge: \"15m\",\n *   route: \"probe-mail\",\n * });\n *\n * // Pushed by hand, from any .process() or .error() step.\n * mailHealth.down({ subsystem: \"imap\" });\n * ```\n *\n * A handle used against several live contexts reports into each of their\n * ledgers, because a push carries no context of its own and routecraft exposes\n * no ambient accessor inside an `.error()` handler. In the ordinary\n * single-context process that is exactly one ledger.\n *\n * Pushing through an unbound handle is deliberately inert rather than a throw.\n * Health instrumentation must not be able to kill the code it instruments: an\n * exchange draining during shutdown, after teardown released the binding, would\n * otherwise take an error out of its `.error()` handler and into the route.\n *\n * @param definition - Name, optional staleness window, failure domain, and\n *   optional route binding.\n * @returns A handle to register in `ops.indicators` and push through.\n */\nexport function defineIndicator(definition: IndicatorDefinition): Indicator {\n  assertIndicatorName(definition.name, \"defineIndicator\");\n  // Parsed for its refusal, not its value: the resolved milliseconds are\n  // computed again where the indicator registers. Validating here is what\n  // makes a malformed duration fail at definition rather than at boot.\n  rejectStaleOptions(definition, `defineIndicator(\"${definition.name}\")`);\n  if (definition.maxAge !== undefined) {\n    try {\n      parseDuration(definition.maxAge, \"maxAge\");\n    } catch {\n      throw rcError(\"RC5053\", undefined, {\n        message: `defineIndicator(\"${definition.name}\"): maxAge must be a positive, finite duration.`,\n      });\n    }\n  }\n\n  const bound: Bound[] = [];\n  const frozen: Readonly<IndicatorDefinition> = Object.freeze({\n    ...definition,\n  });\n\n  const indicator: Indicator = {\n    name: frozen.name,\n    definition: frozen,\n    up(details) {\n      for (const entry of bound) {\n        entry.state.reportIndicator(frozen.name, {\n          status: \"up\",\n          ...(details !== undefined ? { details } : {}),\n        });\n      }\n    },\n    down(details) {\n      for (const entry of bound) {\n        entry.state.reportIndicator(frozen.name, {\n          status: \"down\",\n          ...(details !== undefined ? { details } : {}),\n        });\n      }\n    },\n    inactive() {\n      for (const entry of bound) {\n        entry.state.setIndicatorInactive(frozen.name, true);\n      }\n    },\n  };\n\n  binders.set(indicator, bound);\n  declared.add(indicator);\n  return indicator;\n}\n\n/**\n * Names of handles this process declared that NO context has bound.\n *\n * Forgetting one entry in `ops.indicators` is the likeliest mistake with a\n * two-step API and the one that fails silently: the route keeps pushing, the\n * report never grows the key, and nothing pages.\n *\n * Deliberately not per-context. Several independently configured contexts can\n * share this module, and a handle registered by one of them is not something\n * the others forgot; asking every context about every handle would tell an app\n * to register another app's. Only a handle nobody anywhere registered is a\n * mistake, and that is what this reports.\n *\n * @internal\n */\nexport function unboundIndicators(): string[] {\n  return [...declared]\n    .filter((handle) => (binders.get(handle) ?? []).length === 0)\n    .map((handle) => handle.name);\n}\n","import type { CraftContext } from \"./context.ts\";\nimport type { Exchange, ExchangeHeaders } from \"./exchange.ts\";\nimport { DefaultExchange, isDropped } from \"./exchange.ts\";\nimport { rcError } from \"./error.ts\";\nimport {\n  ADAPTER_DIRECT_STORE,\n  sanitizeEndpoint,\n} from \"./adapters/direct/shared.ts\";\n\n/**\n * Programmatic client for dispatching messages into running routes.\n *\n * Use this to call routes from external code (CLI frameworks, HTTP servers,\n * application logic) without coupling to the CraftContext internals.\n *\n * Returned alongside the context from `ContextBuilder.build()`.\n *\n * @example\n * ```typescript\n * const { context, client } = await new ContextBuilder()\n *   .routes(capabilities)\n *   .build();\n *\n * await context.start();\n *\n * // Dispatch from Commander action\n * program.command('greet').action(async (name) => {\n *   const result = await client.sendDirect('greet', { name });\n *   console.log(result);\n * });\n * ```\n */\nexport class CraftClient {\n  constructor(private readonly ctx: CraftContext) {}\n\n  /**\n   * Send a message to a direct endpoint and return the result. The name\n   * carries the transport: future transports (e.g. HTTP dispatch) get\n   * their own verbs instead of overloading one `send`.\n   *\n   * The context must be started and the target route must be subscribed\n   * before calling sendDirect.\n   *\n   * @param endpoint - Direct endpoint name (must match the endpoint string passed to `direct(endpoint, options)`)\n   * @param body - Request body\n   * @param headers - Optional exchange headers\n   * @returns The response body from the route. `R` defaults to `unknown`:\n   *   the route's output type is not derivable from the request type, so\n   *   callers narrow explicitly.\n   * @throws {RoutecraftError} RC5004 if no direct channel exists for the endpoint\n   */\n  async sendDirect<T = unknown, R = unknown>(\n    endpoint: string,\n    body: T,\n    headers?: ExchangeHeaders,\n  ): Promise<R> {\n    const store = this.ctx.getStore(ADAPTER_DIRECT_STORE);\n    const sanitized = sanitizeEndpoint(endpoint);\n    const channel = store?.get(sanitized);\n    if (!channel) {\n      throw rcError(\"RC5004\", undefined, {\n        message: `No direct channel for endpoint \"${endpoint}\". Is the context started and does a route subscribe to this endpoint?`,\n      });\n    }\n    const exchange = new DefaultExchange(this.ctx, {\n      body,\n      ...(headers !== undefined && { headers }),\n    });\n    const result = (await channel.send(sanitized, exchange)) as Exchange;\n    // A dropped exchange has no response: resolving with its body would\n    // hand the caller back its own request as if it were the route's\n    // output. Surface the drop as an error the caller can branch on.\n    if (isDropped(result)) {\n      throw rcError(\"RC5031\", undefined, {\n        message: `Direct endpoint \"${endpoint}\" dropped the exchange instead of completing it; there is no response body.`,\n      });\n    }\n    return result.body as R;\n  }\n}\n","/**\n * The management API's handlers, with no transport in sight.\n *\n * Every function here takes decoded arguments and returns decoded results.\n * The ops mount (`mount.ts`) is a thin door that turns a `Request` into\n * these calls and their results into a `Response`, and it is the only file\n * in this surface that knows HTTP exists. That separation is what lets the\n * console's control API (#494) grow over the same handlers later without\n * protocol rework, and it is why a resource-shaped door did not become a\n * licence to move logic into it.\n */\n\nimport { CraftClient } from \"../../client\";\nimport { isInternalEndpoint } from \"../../capabilities\";\nimport type { CraftContext } from \"../../context\";\nimport { isRemoteAbsence } from \"../remotes/channel\";\nimport { HeadersKeys } from \"../../exchange\";\nimport type { ExchangeHeaders } from \"../../exchange\";\nimport { rcCodeOf } from \"../../brand\";\nimport type { Principal } from \"../../auth/types\";\nimport type { Capability } from \"../../capabilities\";\nimport type { RouteDefinition } from \"../../route\";\nimport { getAdapterLabel } from \"../../types\";\nimport type { Adapter } from \"../../types\";\nimport { isDeferred } from \"../../deferral/deferred\";\nimport {\n  renderJsonSchemaArm,\n  standardExtensionOf,\n} from \"../../shared/standard-schema\";\nimport { decodeCursor, takePage } from \"./pagination\";\nimport { safeStringify } from \"../../shared/safe-json.ts\";\nimport { compareCodeUnits } from \"../../shared/compare\";\nimport { OPS_RESOURCES } from \"./store\";\nimport { REMOTE_ROUTES, type RemoteRoute } from \"../remotes/store\";\nimport type {\n  OpsDispatchOutcome,\n  OpsEventTailItem,\n  OpsPage,\n  OpsResource,\n  OpsRouteDetail,\n  OpsRouteFilter,\n  OpsRouteQuery,\n  OpsRouteSchemas,\n  OpsRouteSummary,\n} from \"./types\";\n\n/**\n * JSON Schema dialect asked of a schema library's producer.\n *\n * Pinned so two instances of this API describe the same route identically.\n * Unrelated to the deferral descriptor's constant of the same value:\n * that one is folded into a stored hash and must not move, this one is\n * descriptive, and sharing a single mutable constant between them would\n * couple a display choice to every deferred exchange's digest.\n */\nconst JSON_SCHEMA_TARGET = \"draft-2020-12\";\n\n/**\n * A dispatch refused because of the id the caller named, before any route\n * ran: no route answers to it, or the route has no door a dispatch can use.\n *\n * Returned rather than thrown so a door can never mistake a route's own\n * failure for one. The codes that name these conditions, `RC5004` and\n * `RC5060`, also come out of pipelines (a nested `direct()` to an endpoint\n * nothing answers is the common case), and such a failure is the\n * instance's: it answers 500, and the name of the missing endpoint is not\n * the caller's to read. Everything `dispatch` throws is the route's.\n *\n * @internal\n */\nexport type OpsDispatchRefusal =\n  | { outcome: \"refused\"; reason: \"unknown\" }\n  | { outcome: \"refused\"; reason: \"not-dispatchable\"; message: string };\n\n/** What the management handlers need from a running context. */\nexport interface ManagementApi {\n  listRoutes(query: OpsRouteQuery): OpsPage<OpsRouteSummary>;\n  describeRoute(id: string): OpsRouteDetail | undefined;\n  dispatch(\n    id: string,\n    body: unknown,\n    principal: Principal | undefined,\n  ): Promise<OpsDispatchOutcome | OpsDispatchRefusal>;\n  tailEvents(signal: AbortSignal): AsyncIterable<OpsEventTailItem>;\n  /**\n   * A contributed resource by name, read per request so a plugin applied\n   * after the ops mount is served too. `undefined` for a name nothing\n   * contributed, which the mount answers as 404 like any unknown path.\n   */\n  resource(name: string): OpsResource | undefined;\n}\n\n/**\n * How many events the tail holds for a reader that has fallen behind.\n *\n * The bus emits synchronously on the route's own hot path, so the tail can\n * never block it: it buffers and moves on. A bound is what keeps a reader\n * that stopped reading from growing that buffer until the process dies,\n * and dropping the oldest is the right end to lose, because a live tail is\n * watched for what is happening now.\n */\nconst TAIL_BUFFER = 256;\n\n/**\n * How many bytes of rendered frames the tail holds for the same reader.\n *\n * The count bound alone bounds nothing about size: an event whose details\n * carry a large error or a large body renders to a large frame, and a few\n * hundred of those is a few hundred times whatever the largest one is.\n * Streaming slots are per-server, so that ceiling multiplies by every tail\n * an operator has open. Bytes and count are both evicted oldest-first, and\n * both feed the same dropped marker the reader already sees.\n */\nconst TAIL_BUFFER_BYTES = 1_048_576;\n\n/**\n * How long the tail stays silent before putting a comment on the wire.\n *\n * An idle app emits nothing, and a proxy between the operator and the\n * process reaps a connection that says nothing for long enough. The comment\n * is the SSE spec's own no-op, ignored by every conforming client.\n */\nconst TAIL_HEARTBEAT_MS = 30_000;\n\n/**\n * What one queued frame costs the byte budget.\n *\n * UTF-16 code units rather than encoded bytes: the frame is not encoded\n * until the reader takes it, and an exact count would mean encoding every\n * event on the bus's hot path to bound a buffer. The two agree for ASCII\n * and stay within a small factor otherwise, which is all a ceiling needs.\n */\nfunction frameBytes(item: OpsEventTailItem): number {\n  return item.kind === \"event\" ? item.data.length : 0;\n}\n\n/**\n * Build the management handlers over a live context.\n *\n * Routes and capabilities are read per call rather than captured, because\n * both change as routes start and stop and a snapshot taken at mount time\n * would describe the instance as it was at boot.\n */\nexport function createManagementApi(ctx: CraftContext): ManagementApi {\n  const client = new CraftClient(ctx);\n\n  /**\n   * The dispatchable set, keyed by raw route id.\n   *\n   * `direct()` writes the capability registry when it subscribes, and that\n   * registration IS the door a dispatch goes through, so dispatchability\n   * is observed here rather than inferred from a route's source shape. It\n   * also carries the title, description, schemas and tags a route declared,\n   * which is what makes this listing useful to a human.\n   */\n  const capabilityIndex = (): Map<string, Capability> =>\n    new Map(ctx.capabilities().map((entry) => [entry.endpoint, entry]));\n\n  /**\n   * Routes imported from other instances, keyed by local endpoint.\n   *\n   * Listed beside the local routes as dispatchable, with `remote` naming\n   * the origin. A local route with the same id wins while it shadows the\n   * remote route, and the capability registry is what says so: `direct()`\n   * writes a local capability when the route subscribes, and the remotes\n   * plugin writes the remote's back when that route stops. A stopped\n   * route stays in `getRoutes()`, so the id alone cannot decide.\n   */\n  const remoteIndex = (): Map<string, RemoteRoute> =>\n    ctx.getStore(REMOTE_ROUTES) ?? new Map<string, RemoteRoute>();\n\n  const remoteAnswers = (\n    id: string,\n    capabilities: Map<string, Capability>,\n  ): boolean =>\n    remoteIndex().has(id) && capabilities.get(id)?.remote !== undefined;\n\n  const summaries = (): OpsRouteSummary[] => {\n    const capabilities = capabilityIndex();\n    const local = ctx\n      .getRoutes()\n      .filter((route) => !remoteAnswers(route.definition.id, capabilities))\n      .map((route) => summarise(ctx, route.definition, capabilities));\n    const localIds = new Set(local.map((route) => route.id));\n    const imported = [...remoteIndex().values()]\n      .filter((route) => !localIds.has(route.endpoint))\n      .map(summariseRemote);\n    return [...local, ...imported].sort((left, right) =>\n      compareCodeUnits(left.id, right.id),\n    );\n  };\n\n  return {\n    listRoutes(query: OpsRouteQuery): OpsPage<OpsRouteSummary> {\n      const filter: OpsRouteFilter = {\n        ...(query.dispatchable !== undefined\n          ? { dispatchable: query.dispatchable }\n          : {}),\n        ...(query.id !== undefined ? { id: query.id } : {}),\n        ...(query.source !== undefined ? { source: query.source } : {}),\n      };\n      const matched = summaries().filter((route) => matches(route, filter));\n      const after =\n        query.after === undefined\n          ? undefined\n          : decodeCursor(query.after, filter);\n      const page = takePage(matched, filter, query.limit, after);\n      return page.nextCursor === undefined\n        ? { items: page.items }\n        : { items: page.items, nextCursor: page.nextCursor };\n    },\n\n    /**\n     * Tail every event the context emits until the caller goes away.\n     *\n     * Subscribes to the bus catch-all and hands items over a bounded\n     * buffer, because `emit` runs on the caller's stack: a tail that awaited\n     * its reader there would put an operator's network back-pressure inside\n     * a route step.\n     *\n     * The generator defers on a promise rather than polling, and the signal\n     * resolves it. Cancelling the response is not enough on its own: an\n     * async generator delivers a queued `return()` only after the pending\n     * `next()` settles, so a tail with nothing to yield would sit on that\n     * promise forever with its subscription still live.\n     */\n    async *tailEvents(signal: AbortSignal): AsyncIterable<OpsEventTailItem> {\n      const queue: OpsEventTailItem[] = [];\n      let queuedBytes = 0;\n      let dropped = 0;\n      let wake: (() => void) | undefined;\n\n      // The tail is in-flight work for as long as it runs, and a graceful\n      // close would otherwise wait out its whole window on a stream that\n      // ends the moment it is asked to. `context:stopping` arrives on the\n      // bus this is already reading, so it needs no second channel: the\n      // event is delivered, and then the tail closes behind it.\n      let stopping = false;\n      const unsubscribe = ctx.on(\"*\", (payload) => {\n        const item: OpsEventTailItem = {\n          kind: \"event\",\n          name: payload._event,\n          // Rendered here, on the emit, rather than held by reference until\n          // the reader takes it: see OpsEventTailItem.data. `_snapshot`\n          // sub-payloads go with it, because they exist so a surface that was\n          // not asked to capture payloads does not, and a tail an operator\n          // opened is not that asking.\n          data: safeStringify(\n            {\n              event: payload._event,\n              ts: payload.ts,\n              contextId: payload.contextId,\n              details: payload.details,\n            },\n            { dropSnapshot: true },\n          ),\n        };\n        const size = frameBytes(item);\n        // An oversized frame still goes on: evicting the whole buffer and\n        // then refusing it would leave the reader nothing at all. It is the\n        // next push that evicts it.\n        while (\n          queue.length > 0 &&\n          (queue.length >= TAIL_BUFFER ||\n            queuedBytes + size > TAIL_BUFFER_BYTES)\n        ) {\n          queuedBytes -= frameBytes(queue.shift()!);\n          dropped++;\n        }\n        queue.push(item);\n        queuedBytes += size;\n        if (payload._event === \"context:stopping\") stopping = true;\n        wake?.();\n      });\n      const onAbort = (): void => wake?.();\n      signal.addEventListener(\"abort\", onAbort);\n\n      try {\n        while (!signal.aborted) {\n          if (queue.length === 0) {\n            let timer: ReturnType<typeof setTimeout> | undefined;\n            await new Promise<void>((resolve) => {\n              wake = resolve;\n              timer = setTimeout(resolve, TAIL_HEARTBEAT_MS);\n            });\n            if (timer !== undefined) clearTimeout(timer);\n            wake = undefined;\n            if (queue.length === 0 && !signal.aborted)\n              yield { kind: \"heartbeat\" };\n            continue;\n          }\n          if (dropped > 0) {\n            const count = dropped;\n            dropped = 0;\n            yield { kind: \"dropped\", count };\n          }\n          const next = queue.shift()!;\n          queuedBytes -= frameBytes(next);\n          yield next;\n          if (stopping && queue.length === 0) return;\n        }\n      } finally {\n        signal.removeEventListener(\"abort\", onAbort);\n        unsubscribe();\n      }\n    },\n\n    resource(name: string): OpsResource | undefined {\n      return ctx.getStore(OPS_RESOURCES)?.get(name);\n    },\n\n    describeRoute(id: string): OpsRouteDetail | undefined {\n      const capabilities = capabilityIndex();\n      const route = remoteAnswers(id, capabilities)\n        ? undefined\n        : ctx.getRoutes().find((candidate) => candidate.definition.id === id);\n      if (route) return detail(ctx, route.definition, capabilities);\n      const imported = remoteIndex().get(id);\n      return imported === undefined ? undefined : detailRemote(imported);\n    },\n\n    async dispatch(\n      id: string,\n      body: unknown,\n      principal: Principal | undefined,\n    ): Promise<OpsDispatchOutcome | OpsDispatchRefusal> {\n      const capabilities = capabilityIndex();\n      const route = remoteAnswers(id, capabilities)\n        ? undefined\n        : ctx.getRoutes().find((candidate) => candidate.definition.id === id);\n      // An imported route has no definition here and needs none: its\n      // capability is its door, and the channel behind it carries the\n      // exchange to the instance that defines it. Re-exposing it through\n      // this door is intentional, exactly as a tool fronting an\n      // authenticated REST call re-exposes that call.\n      if (!route && !remoteIndex().has(id)) {\n        return { outcome: \"refused\", reason: \"unknown\" };\n      }\n      if (route && !capabilities.has(id)) {\n        return {\n          outcome: \"refused\",\n          reason: \"not-dispatchable\",\n          message: notDispatchable(ctx, id, route.definition),\n        };\n      }\n\n      // The principal is passed through exactly as the mount's validator\n      // minted it, on the header the framework itself uses. There is no\n      // synthetic operator identity and no bypass: the full pre-from chain\n      // runs, so a downstream .authorize() cannot tell an operator dispatch\n      // from any other authenticated caller, which is the entire point.\n      const headers: ExchangeHeaders =\n        principal === undefined\n          ? {}\n          : ({ [HeadersKeys.AUTH_PRINCIPAL]: principal } as ExchangeHeaders);\n\n      try {\n        const result = await client.sendDirect(id, body, headers);\n        if (isDeferred(result)) {\n          return { outcome: \"deferred\", deferral: result };\n        }\n        return { outcome: \"completed\", body: result };\n      } catch (error: unknown) {\n        // A drop is a terminal outcome, not a fault: a filter said no and\n        // there is no response body. Reporting it as a failure would tell\n        // an operator to go looking for a broken step.\n        if (rcCodeOf(error) === \"RC5031\") {\n          return {\n            outcome: \"dropped\",\n            message: (error as Error).message,\n          };\n        }\n        // The remote's door said the id is gone, which is this door's\n        // answer too: the channel is the only door an imported route has.\n        if (isRemoteAbsence(error, id)) {\n          return { outcome: \"refused\", reason: \"unknown\" };\n        }\n        throw error;\n      }\n    },\n  };\n}\n\n/**\n * Why a route that exists cannot take a dispatch, phrased as the remedy.\n *\n * Three refusals behind one absent capability. A route that declared\n * `direct({ internal: true })` HAS a direct source, so telling its caller\n * to add one would be wrong advice; the internal registry remembers the\n * difference. A route with a direct source and no capability is stopped or\n * disabled, since the capability lives exactly as long as the subscription.\n * Only the rest genuinely lack the door.\n */\nfunction notDispatchable(\n  ctx: CraftContext,\n  id: string,\n  definition: RouteDefinition,\n): string {\n  if (isInternalEndpoint(ctx, id)) {\n    return `Route \"${id}\" is declared internal (direct({ internal: true })) and not dispatchable. It is only composable from another route; dispatch to a boundary route that fronts it instead.`;\n  }\n  const kinds = sourceKinds(definition);\n  if (kinds.includes(\"direct\")) {\n    return ctx.isRouteEnabled(id)\n      ? `Route \"${id}\" has a direct() door but is not running, so nothing answers it. Start the route on that instance before dispatching to it.`\n      : `Route \"${id}\" has a direct() door and is disabled by its .enabled() predicate, so nothing answers it. Enable it before dispatching to it.`;\n  }\n  return `Route \"${id}\" has no dispatch door: its sources are ${\n    kinds.join(\", \") || \"(none)\"\n  }, and only a direct() ingress makes a route id dispatchable. Add .from(direct()) to the route, or dispatch to one that has it.`;\n}\n\n/**\n * An imported route as the listing presents it: what the remote said about\n * its route, under the local endpoint, with the origin named. Always\n * dispatchable and enabled, because the remote only lists routes that are,\n * and the JSON Schema renderings pass through as the remote rendered them.\n */\nfunction summariseRemote(route: RemoteRoute): OpsRouteSummary {\n  const { detail } = route;\n  return {\n    id: route.endpoint,\n    dispatchable: true,\n    enabled: true,\n    sources: [\"remote\"],\n    requiresPrincipal: detail.requiresPrincipal,\n    ...(detail.title !== undefined ? { title: detail.title } : {}),\n    ...(detail.description !== undefined\n      ? { description: detail.description }\n      : {}),\n    ...(detail.tags !== undefined && detail.tags.length > 0\n      ? { tags: [...detail.tags] }\n      : {}),\n    remote: route.remote,\n  };\n}\n\nfunction detailRemote(route: RemoteRoute): OpsRouteDetail {\n  const { detail } = route;\n  return {\n    ...summariseRemote(route),\n    ...(detail.input !== undefined ? { input: detail.input } : {}),\n    ...(detail.output !== undefined ? { output: detail.output } : {}),\n  };\n}\n\n/** Source kinds a route declares, in declaration order. */\nfunction sourceKinds(definition: RouteDefinition): string[] {\n  return definition.sources.map(\n    (source) => getAdapterLabel(source as Adapter) ?? \"inline\",\n  );\n}\n\nfunction summarise(\n  ctx: CraftContext,\n  definition: RouteDefinition,\n  capabilities: Map<string, Capability>,\n): OpsRouteSummary {\n  const capability = capabilities.get(definition.id);\n  const discovery = definition.discovery;\n  const title = capability?.title ?? discovery?.title;\n  const description = capability?.description ?? discovery?.description;\n  const tags = capability?.tags ?? discovery?.tags;\n  return {\n    id: definition.id,\n    dispatchable: capabilities.has(definition.id),\n    enabled: ctx.isRouteEnabled(definition.id),\n    sources: sourceKinds(definition),\n    requiresPrincipal: definition.requiresPrincipal === true,\n    ...(title !== undefined ? { title } : {}),\n    ...(description !== undefined ? { description } : {}),\n    ...(tags !== undefined && tags.length > 0 ? { tags: [...tags] } : {}),\n  };\n}\n\nfunction detail(\n  ctx: CraftContext,\n  definition: RouteDefinition,\n  capabilities: Map<string, Capability>,\n): OpsRouteDetail {\n  const capability = capabilities.get(definition.id);\n  const discovery = definition.discovery;\n  const input = renderSchemas(capability?.input ?? discovery?.input, \"input\");\n  const output = renderSchemas(\n    capability?.output ?? discovery?.output,\n    \"output\",\n  );\n  return {\n    ...summarise(ctx, definition, capabilities),\n    ...(input !== undefined ? { input } : {}),\n    ...(output !== undefined ? { output } : {}),\n  };\n}\n\n/**\n * Render a route's declared schemas to JSON Schema, when the library\n * exposes the non-standard extension.\n *\n * The preferred arm follows the direction the schema is used in: what a\n * caller must SEND is the input schema's input arm, and what it receives\n * is the output schema's output arm. The other arm is a fallback rather\n * than an equal, because for a transforming schema the two differ and\n * showing the wrong one would document a request shape nobody may send.\n */\nfunction renderSchemas(\n  schemas: { body?: unknown; headers?: unknown } | undefined,\n  direction: \"input\" | \"output\",\n): OpsRouteSchemas | undefined {\n  if (!schemas) return undefined;\n  const body = renderSchema(schemas.body, direction);\n  const headers = renderSchema(schemas.headers, direction);\n  if (body === undefined && headers === undefined) return undefined;\n  return {\n    ...(body !== undefined ? { body } : {}),\n    ...(headers !== undefined ? { headers } : {}),\n  };\n}\n\nfunction renderSchema(schema: unknown, direction: \"input\" | \"output\"): unknown {\n  if (schema === undefined || schema === null) return undefined;\n  const standard = standardExtensionOf(schema);\n  const arms =\n    direction === \"input\"\n      ? [standard?.jsonSchema?.input, standard?.jsonSchema?.output]\n      : [standard?.jsonSchema?.output, standard?.jsonSchema?.input];\n  return (\n    renderJsonSchemaArm(arms[0], JSON_SCHEMA_TARGET) ??\n    renderJsonSchemaArm(arms[1], JSON_SCHEMA_TARGET)\n  );\n}\n\nfunction matches(route: OpsRouteSummary, filter: OpsRouteFilter): boolean {\n  if (\n    filter.dispatchable !== undefined &&\n    route.dispatchable !== filter.dispatchable\n  ) {\n    return false;\n  }\n  // Exact, not a prefix: a prefix match makes the result set of a cursor\n  // hard for a caller to reason about, and an id is a name rather than a\n  // search term.\n  if (filter.id !== undefined && route.id !== filter.id) return false;\n  if (filter.source !== undefined && !route.sources.includes(filter.source)) {\n    return false;\n  }\n  return true;\n}\n","/**\n * The direct channel behind an imported route.\n *\n * Registered in the direct store under the route's local endpoint, so\n * `direct('lab:hello')`, `forward('lab:hello', ...)`, `CraftClient.sendDirect`\n * and a `directTool` all reach it through the code paths they already use.\n * A send becomes `POST /ops/routes/{id}/exchanges` on the remote, and the\n * remote's outcome is mapped onto the in-process one: a completed exchange\n * is the body, a drop is `RC5031`, a deferral is the standard `Deferred`\n * acknowledgment, and the door's own refusals and failures become codes a\n * caller can tell apart.\n */\n\nimport type { CraftContext } from \"../../context\";\nimport { rcError } from \"../../error\";\nimport { DefaultExchange, type Exchange } from \"../../exchange\";\nimport type { DirectChannel } from \"../../adapters/direct/types\";\nimport { InMemoryDirectChannel } from \"../../adapters/direct/shared\";\nimport { createDeferred } from \"../../deferral/deferred\";\nimport { OpsClientError, type OpsHttpClient } from \"../ops/client\";\n\n/**\n * `RC5004` failures a channel raised because its remote answered 404, keyed\n * to the local endpoint the channel fronts.\n *\n * Module-private for the reason `authorize.ts` keeps its refusals in one: a\n * route reaching this endpoint through a nested `direct()` fails with the\n * same code, and so does any step that throws it. Only the ops door that\n * dispatched this endpoint itself may answer the remote's 404 as its own.\n */\nconst absences = new WeakMap<object, string>();\n\n/**\n * Whether `error` is a channel's report that the remote no longer answers\n * `endpoint`, as opposed to an `RC5004` raised anywhere else, including by\n * a channel fronting a different endpoint.\n *\n * @internal\n */\nexport function isRemoteAbsence(error: unknown, endpoint: string): boolean {\n  if (typeof error !== \"object\" || error === null) return false;\n  return absences.get(error) === endpoint;\n}\n\n/** What a channel needs to know about the route it fronts. */\nexport interface RemoteTarget {\n  ctx: CraftContext;\n  /** The remote's name in `defineConfig({ remotes })`. */\n  remote: string;\n  /** The route id on the remote. */\n  id: string;\n  /** The local endpoint, for log lines and messages. */\n  endpoint: string;\n  client: OpsHttpClient;\n  /** The remote named for a reader, without the credential. */\n  describe(): string;\n  /**\n   * Called when the remote answers 404 for this route, which means the\n   * inventory is stale: the route is gone, or the dispatch tier closed.\n   * Awaited before the failure is thrown, so the next call sees the truth.\n   */\n  onMissing(): Promise<void>;\n}\n\n/**\n * A direct channel that dispatches to another instance.\n *\n * It also carries the shadow rule. A local route may subscribe onto an\n * endpoint this channel holds, or may already hold the endpoint when the\n * remote's inventory arrives; either way `local` is set and the local\n * route answers every send, with a warning naming the remote route that is\n * being shadowed, because a shadow is the promotion window and a caller\n * reading the logs should be able to see which of the two ran. The plugin\n * lifts the shadow when the local route stops, together with the\n * capability's provenance, so the channel never decides that on its own.\n */\nexport class RemoteDirectChannel implements DirectChannel<Exchange> {\n  /** The local route's channel when one shadows this endpoint. */\n  local: DirectChannel<Exchange> | undefined;\n\n  constructor(\n    private readonly target: RemoteTarget,\n    local?: DirectChannel<Exchange>,\n  ) {\n    this.local = local;\n  }\n\n  async send(endpoint: string, exchange: Exchange): Promise<Exchange> {\n    if (this.local !== undefined) {\n      const { ctx, remote, id, endpoint: local } = this.target;\n      ctx.logger.warn(\n        { endpoint: local, remote, remoteRouteId: id },\n        `Direct endpoint \"${local}\" is answered by the local route; the route \"${id}\" of remote \"${remote}\" is shadowed and stays reachable as \"${remote}:${id}\"`,\n      );\n      return this.local.send(endpoint, exchange);\n    }\n    return this.dispatch(exchange);\n  }\n\n  async subscribe(\n    context: CraftContext,\n    endpoint: string,\n    handler: (message: Exchange) => Promise<Exchange>,\n  ): Promise<void> {\n    this.local ??= new InMemoryDirectChannel<Exchange>();\n    await this.local.subscribe(context, endpoint, handler);\n  }\n\n  async unsubscribe(context: CraftContext, endpoint: string): Promise<void> {\n    if (this.local === undefined) return;\n    await this.local.unsubscribe(context, endpoint);\n    // The local route left, so the remote answers again: a capability\n    // demoted from the laptop still exists on the server.\n    this.local = undefined;\n  }\n\n  private async dispatch(exchange: Exchange): Promise<Exchange> {\n    const { ctx, remote, id, client } = this.target;\n    let outcome: Awaited<ReturnType<OpsHttpClient[\"dispatch\"]>>;\n    try {\n      outcome = await client.dispatch(id, exchange.body);\n    } catch (error: unknown) {\n      throw await this.translate(error);\n    }\n    switch (outcome.outcome) {\n      case \"completed\":\n        return new DefaultExchange(ctx, {\n          body: outcome.body,\n          headers: exchange.headers,\n        });\n      case \"deferred\": {\n        // Re-branded so the local transports recognise the deferral the way they\n        // recognise one of their own: the ops door answers 202, an agent\n        // tool reports it, and a route with `.defer()` downstream is not\n        // fooled by a body that merely looks deferred. Resume stays at the\n        // remote's door, under the remote's policy.\n        const { deferralId, token, schema, expiresAt } = outcome.deferral;\n        return new DefaultExchange(ctx, {\n          body: createDeferred({\n            deferralId,\n            token,\n            ...(schema !== undefined ? { schema } : {}),\n            ...(expiresAt !== undefined ? { expiresAt } : {}),\n          }),\n          headers: exchange.headers,\n        });\n      }\n      case \"dropped\":\n        throw rcError(\"RC5031\", undefined, {\n          message: `Route \"${id}\" on remote \"${remote}\" dropped the exchange instead of completing it; there is no response body. ${outcome.message}`,\n        });\n      default:\n        // The client only guarantees an object came back. Anything that is\n        // not one of the three outcomes is an instance this side does not\n        // understand, and it fails as a remote failure rather than as a\n        // TypeError in whoever reads the result.\n        throw rcError(\"RC5064\", undefined, {\n          message: `Dispatching route \"${id}\" on remote \"${remote}\" (${this.target.describe()}): the remote answered with an envelope this instance does not recognise (outcome ${JSON.stringify((outcome as { outcome?: unknown }).outcome)}). Check that the address is a routecraft ops server of a compatible version.`,\n        });\n    }\n  }\n\n  /**\n   * Map the client's failure onto the codes a caller branches on.\n   *\n   * Every message names the remote and the route and never the bearer:\n   * the client's own messages already hold that line, and this layer only\n   * adds which remote it was.\n   */\n  private async translate(error: unknown): Promise<Error> {\n    const { remote, id } = this.target;\n    const where = `route \"${id}\" on remote \"${remote}\" (${this.target.describe()})`;\n    if (!(error instanceof OpsClientError)) {\n      return rcError(\"RC5062\", error, {\n        message: `Dispatching ${where} failed before an answer arrived: ${\n          error instanceof Error ? error.message : String(error)\n        }`,\n      });\n    }\n    switch (error.kind) {\n      case \"unreachable\":\n        return rcError(\"RC5062\", error, {\n          message: `Dispatching ${where}: ${error.message}`,\n        });\n      case \"interrupted\":\n        // The request may have run on the remote, so a retry could run a\n        // non-idempotent route twice, for the reason the timeout is not\n        // retryable either.\n        return rcError(\"RC5062\", error, {\n          message: `Dispatching ${where}: ${error.message}`,\n          retryable: false,\n        });\n      case \"refused\":\n        return rcError(\"RC5063\", error, {\n          message: `Dispatching ${where}: ${error.message}`,\n        });\n      case \"absent\": {\n        await this.target.onMissing();\n        const absence = rcError(\"RC5004\", error, {\n          message: `Dispatching ${where}: the remote answered 404, so the route is gone from the remote or its dispatch tier is closed. The inventory has been refreshed; a route the remote no longer lists is no longer a direct endpoint here.`,\n        });\n        absences.set(absence, this.target.endpoint);\n        return absence;\n      }\n      case \"error\":\n        // No status means the request never completed: a timeout, where\n        // the work may still be running on the remote. Not retryable, for\n        // the reason the client's own message gives.\n        if (error.status === undefined) {\n          return rcError(\"RC5062\", error, {\n            message: `Dispatching ${where}: ${error.message}`,\n            retryable: false,\n          });\n        }\n        return rcError(\"RC5064\", error, {\n          message: `Dispatching ${where}: ${error.message}`,\n        });\n    }\n  }\n}\n","/**\n * Reading a runtime's own version string.\n *\n * Two places need it and they must not answer differently: the CLI gate\n * refuses a Bun below the supported floor, and the ops client decides\n * whether this Bun re-sends a dropped non-idempotent request by itself.\n * Written twice, the two copies disagreed on the same input within one\n * release: one read a two-segment `\"1.4\"` as `1.4.0` and the other as\n * unparseable.\n */\n\n/** A SemVer core, with prerelease and build metadata already dropped. */\nexport interface RuntimeVersion {\n  readonly major: number;\n  readonly minor: number;\n  readonly patch: number;\n}\n\n/**\n * Parse a runtime version string, or `undefined` when it is not one.\n *\n * A missing patch (or minor) segment reads as zero, matching how a\n * runtime that reports `\"1.4\"` means `1.4.0`. Prerelease and build\n * metadata are stripped per SemVer, so a canary compares as its release.\n *\n * @internal\n */\nexport function parseRuntimeVersion(\n  version: string,\n): RuntimeVersion | undefined {\n  const segments = (version.split(/[-+]/)[0] ?? \"\").split(\".\");\n  // Four or more segments is not a version this can read. Truncating to the\n  // first three would accept it and answer confidently about a string\n  // nobody understands, and both callers would rather refuse.\n  if (segments.length > 3) return undefined;\n  const [major, minor, patch] = segments.map((segment) =>\n    segment === \"\" ? Number.NaN : Number(segment),\n  );\n  if (major === undefined || !Number.isInteger(major)) return undefined;\n  if (minor !== undefined && !Number.isInteger(minor)) return undefined;\n  if (patch !== undefined && !Number.isInteger(patch)) return undefined;\n  return { major, minor: minor ?? 0, patch: patch ?? 0 };\n}\n\n/**\n * Negative when `a` is older than `b`, zero when they are the same core.\n *\n * @internal\n */\nexport function compareRuntimeVersion(\n  a: RuntimeVersion,\n  b: RuntimeVersion,\n): number {\n  return a.major - b.major || a.minor - b.minor || a.patch - b.patch;\n}\n","/**\n * HTTP client for a running instance's ops server.\n *\n * Spans two surfaces that behave differently and must not be flattened.\n * `/health` never walls, so a probe with no credential works, and it\n * returns MORE when authenticated: per-component `details` are gated by\n * `health.details`. `/ops` answers by tier: 404 when a tier is off, open\n * when `true`, scope-checked when a scope string is configured.\n *\n * So this client presents a credential whenever one is configured, on both\n * surfaces, and degrades when none is. That is a correctness requirement\n * rather than a nicety: unauthenticated, a route component says `degraded`\n * and nothing else; authenticated, it says `degraded` because a breaker is\n * open. The bare status does not answer the question an operator is asking.\n *\n * Two callers share it. The `craft` CLI drives one instance from a\n * terminal, and the remotes plugin imports another instance's dispatchable\n * routes into a running context. Neither knows anything the other does\n * not about the wire, so the client lives in core beside the server it\n * speaks to, and each caller supplies only the words its own reader needs\n * (where the address came from, and what to do when refused).\n */\n\nimport type { DeferralState } from \"../../deferral/types.ts\";\nimport {\n  compareRuntimeVersion,\n  parseRuntimeVersion,\n  type RuntimeVersion,\n} from \"../../shared/runtime-version.ts\";\nimport type { Duration } from \"../../shared/duration.ts\";\nimport { parseDuration } from \"../../shared/duration.ts\";\nimport { DOCS_BASE, findErrorMeta } from \"../../error.ts\";\nimport {\n  MAX_WIRE_ISSUES,\n  type WireIssue,\n} from \"../../pipeline/caller-refusal.ts\";\nimport type {\n  HealthComponent,\n  HealthReport,\n  OpsDeferralSummary,\n  OpsDispatchOutcome,\n  OpsPage,\n  OpsRouteDetail,\n  OpsRouteFilter,\n  OpsRouteSummary,\n} from \"./types\";\n\n/**\n * How long one request may take before the client gives up.\n *\n * A connection the instance accepts and then never answers is otherwise\n * indistinguishable from work in progress, and a caller that hangs with no\n * output is the worst way for a read to fail. The abort lands in the same\n * catch as a refused connection, so it is reported with the address named.\n */\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * How long the follow-up fetch of an RFC 9728 metadata document may take.\n *\n * Much shorter than the request timeout: the refusal is already decided,\n * and this fetch only enriches the message. A caller must never wait\n * longer to be told no than they would have waited to be told yes.\n */\nconst DISCOVERY_TIMEOUT_MS = 5_000;\n\n/**\n * The first Bun that refuses to re-send a non-idempotent request when a\n * reused keep-alive socket closes before any response byte arrives.\n *\n * Below it, `fetch` retried the POST on a fresh connection on its own, so a\n * dispatch whose connection dropped mid-flight ran the route TWICE on the\n * instance while this client saw one attempt and one failure. That is the\n * exact outcome the `interrupted` classification exists to prevent, and it\n * happened below the layer that classifies. Node's `fetch` never had the\n * behaviour.\n *\n * Measured rather than read off a changelog: a stand-in server that serves\n * its inventory over keep-alive and drops the reused socket on the dispatch\n * counts two executions on 1.3.11 and one on 1.3.14 and 1.4.2.\n */\nconst BUN_WITHOUT_DISPATCH_REPLAY: RuntimeVersion = {\n  major: 1,\n  minor: 3,\n  patch: 14,\n};\n\n/**\n * Whether this runtime re-sends a dropped non-idempotent request by itself.\n *\n * Read once per process. An unparseable version answers true: the cost of\n * being wrong is a handshake per dispatch, and the cost of the other answer\n * is running somebody's payout route twice.\n *\n * @internal Exported for its own unit test. The connection policy it drives\n *   is not observable on the wire, so this predicate is where the decision\n *   can be checked; that the policy works end to end is proven by the\n *   dropped-socket case in the remotes suite.\n *\n * @param bunVersion - `null` means \"not running on Bun\". Deliberately not\n *   `undefined`, which JS default-parameter semantics would replace with\n *   the real version, so a test for the Node path would silently read\n *   Bun's own while the suite runs under Bun.\n */\nexport function runtimeReplaysDroppedRequests(\n  bunVersion: string | null = process.versions[\"bun\"] ?? null,\n): boolean {\n  if (bunVersion === null) return false;\n  const version = parseRuntimeVersion(bunVersion);\n  return (\n    version === undefined ||\n    compareRuntimeVersion(version, BUN_WITHOUT_DISPATCH_REPLAY) < 0\n  );\n}\n\n/**\n * Methods a runtime may safely re-send, per RFC 9110 section 9.2.2.\n *\n * The set is deliberately the safe methods rather than the full idempotent\n * ones: this decides whether a call may travel on a pooled socket, and\n * being wrong about a `PUT` or `DELETE` this API might grow later costs a\n * duplicate side effect, while being wrong the other way costs a\n * handshake.\n */\nconst IDEMPOTENT_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\nfunction isIdempotentMethod(method: string): boolean {\n  return IDEMPOTENT_METHODS.has(method.toUpperCase());\n}\n\n/** Why a call did not produce an answer. Each needs a different remedy. */\nexport type OpsFailureKind =\n  /** The instance could not be reached at all; the request never left. */\n  | \"unreachable\"\n  /**\n   * The request may have reached the instance: the connection was lost\n   * after it was sent, or while the answer was being read. Whatever it\n   * asked for may have run.\n   */\n  | \"interrupted\"\n  /** The door refused: no credential, a bad one, or a missing scope. */\n  | \"refused\"\n  /** The tier is disabled, or the thing asked for does not exist. */\n  | \"absent\"\n  /** The instance answered, and the answer was an error. */\n  | \"error\";\n\n/** A call that did not produce an answer, with what to do about it. */\nexport class OpsClientError extends Error {\n  constructor(\n    readonly kind: OpsFailureKind,\n    message: string,\n    readonly status?: number,\n    readonly detail?: unknown,\n  ) {\n    super(message);\n    this.name = \"OpsClientError\";\n  }\n}\n\n/** A response body carrying the API's structured refusal or error. */\ninterface WireError {\n  error?: string;\n  reason?: string;\n  scope?: string;\n  scope_mode?: string;\n  code?: string;\n  message?: string;\n  /** An input refusal's schema issues, sanitised and bounded. */\n  issues?: WireIssue[];\n  /** Issues the body or this client left out of `issues`. */\n  truncated?: number;\n}\n\n/**\n * The bearer presented on every call: a string, or a function evaluated\n * per request. A rotation reaches a running process only through a function\n * that reads a source that changes (a mounted secret file, a secret manager);\n * a change made outside the process never reaches its `process.env`. A\n * function returning `undefined` presents no credential for that call.\n */\nexport type OpsBearerToken =\n  string | (() => string | undefined | Promise<string | undefined>);\n\n/** What a caller supplies to build a client. */\nexport interface OpsHttpClientOptions {\n  /** The instance's base URL. A trailing slash is tolerated. */\n  url: string;\n  /** Credential for both surfaces. Absent means every call is unauthenticated. */\n  token?: OpsBearerToken;\n  /** Per-request deadline. Defaults to 30 seconds. */\n  timeout?: Duration;\n  /**\n   * How the address is named in an error a reader must act on. A wrong\n   * pinned address is otherwise indistinguishable from a stopped instance,\n   * so the CLI says where it read the address from and the remotes plugin\n   * says which remote it is.\n   */\n  describeAddress?: () => string;\n  /** Sentences appended to a refusal or a transport failure, naming the caller's own remedy. */\n  advice?: {\n    /** What to do when the door wants a credential and none was presented. */\n    missingCredential?: string;\n    /** What to do when nothing answered at the address. */\n    unreachable?: string;\n  };\n  /**\n   * Override the runtime detection behind the per-dispatch connection.\n   *\n   * A test seam rather than a knob: the behaviour is a property of the\n   * runtime, not of a deployment, so nothing in production should set it.\n   * It exists because the alternative is asserting a connection policy by\n   * running the suite twice on two Bun builds.\n   *\n   * @internal\n   */\n  replaysDroppedRequests?: boolean;\n}\n\nexport interface OpsHttpClient {\n  /** Whether a credential is configured, for rendering the view. */\n  readonly authenticated: boolean;\n  health(): Promise<HealthReport>;\n  ready(): Promise<HealthReport>;\n  routeHealth(id: string): Promise<HealthComponent>;\n  indicatorHealth(name: string): Promise<HealthComponent>;\n  listRoutes(filter?: OpsRouteFilter): Promise<OpsRouteSummary[]>;\n  describeRoute(id: string): Promise<OpsRouteDetail>;\n  dispatch(id: string, body: unknown): Promise<OpsDispatchOutcome>;\n  /**\n   * One page of deferrals, and the cursor for the next when there is one.\n   *\n   * The page rather than the whole collection, which is the opposite of\n   * {@link OpsHttpClient.listRoutes}. A route inventory is bounded by what\n   * an author wrote; an instance can hold every exchange it has ever\n   * deferred, so walking it would be a request to load an unbounded set\n   * into memory to print the first screen of it.\n   */\n  listDeferrals(\n    filter?: OpsDeferralFilter,\n  ): Promise<OpsPage<OpsDeferralSummary>>;\n  describeDeferral(id: string): Promise<OpsDeferralSummary>;\n}\n\n/** What `GET /ops/deferrals` accepts. */\nexport interface OpsDeferralFilter {\n  /** Waiting by default on the server; `all` asks for both states. */\n  state?: DeferralState | \"all\";\n  /** Only deferrals belonging to this route. */\n  route?: string;\n  /** Rows in one page. The server bounds it and refuses a larger ask. */\n  limit?: number;\n  /** The previous page's `nextCursor`, passed back unchanged. */\n  after?: string;\n}\n\n/**\n * localhost, 127.0.0.0/8 and ::1, as `URL.hostname` renders them.\n *\n * The one place a bearer may travel over plain `http:`: the bytes never\n * leave the machine. Every caller that refuses clear-text bearers decides\n * with this predicate so the exception cannot drift between them.\n */\nexport function isLoopbackHostname(hostname: string): boolean {\n  const host = hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n  return (\n    host === \"localhost\" || host === \"::1\" || /^127(?:\\.\\d{1,3}){3}$/.test(host)\n  );\n}\n\nexport function createOpsHttpClient(\n  options: OpsHttpClientOptions,\n): OpsHttpClient {\n  const base = options.url.replace(/\\/+$/, \"\");\n  const token = options.token;\n  const timeoutMs =\n    options.timeout === undefined\n      ? DEFAULT_TIMEOUT_MS\n      : parseDuration(options.timeout, \"timeout\");\n  const addressBlame = options.describeAddress ?? (() => base);\n  const advice = options.advice ?? {};\n  const replaysDroppedRequests =\n    options.replaysDroppedRequests ?? runtimeReplaysDroppedRequests();\n\n  async function resolveToken(): Promise<string | undefined> {\n    if (typeof token !== \"function\") return token;\n    const resolved = await token();\n    return resolved === undefined || resolved.length === 0\n      ? undefined\n      : resolved;\n  }\n\n  async function call<T>(\n    path: string,\n    init: {\n      method?: string;\n      body?: unknown;\n      /**\n       * Statuses whose body is an answer rather than an error. The health\n       * surface replies 503 with a full report when a component is down, and\n       * that is precisely the report an operator is asking for.\n       */\n      answeredBy?: readonly number[];\n    } = {},\n  ): Promise<T> {\n    const headers: Record<string, string> = {};\n    const bearer = await resolveToken();\n    if (bearer !== undefined) headers[\"authorization\"] = `Bearer ${bearer}`;\n    if (init.body !== undefined) {\n      headers[\"content-type\"] = \"application/json\";\n    }\n\n    const method = init.method ?? \"GET\";\n    let response: Response;\n    try {\n      response = await fetch(`${base}${path}`, {\n        method,\n        headers,\n        signal: AbortSignal.timeout(timeoutMs),\n        // Derived from the method rather than declared per call, so the\n        // next non-idempotent call added here is protected on arrival\n        // instead of inheriting the hazard by forgetting a flag.\n        // `connection: close` does not work here: fetch treats it as a\n        // forbidden header name, drops it silently, and retries anyway.\n        ...(replaysDroppedRequests && !isIdempotentMethod(method)\n          ? { keepalive: false }\n          : {}),\n        ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),\n      });\n    } catch (error: unknown) {\n      throw classifyTransportFailure(error, addressBlame(), \"request\");\n    }\n\n    // Inside its own guard: an abort part-way through the body is the same\n    // class of failure as one during the request, and leaving it outside\n    // turned a timeout into an unhandled rejection with a stack trace.\n    let text: string;\n    try {\n      text = await response.text();\n    } catch (error: unknown) {\n      throw classifyTransportFailure(error, addressBlame(), \"response\");\n    }\n    const parsed: unknown = text.length === 0 ? undefined : parseJson(text);\n\n    if (response.ok || (init.answeredBy?.includes(response.status) ?? false)) {\n      // A 200 from something that is not this API (a wrong port, a proxy's\n      // error page) would otherwise be cast to the caller's type and crash\n      // in the renderer rather than here, where the address can be named.\n      if (\n        parsed === null ||\n        typeof parsed !== \"object\" ||\n        Array.isArray(parsed)\n      ) {\n        throw new OpsClientError(\n          \"error\",\n          `The instance at ${addressBlame()} answered ${String(response.status)} with a body this client does not recognise. Check that the address is a routecraft ops server.`,\n          response.status,\n        );\n      }\n      return parsed as T;\n    }\n\n    // A body that is not JSON still carries the reason on the error path: a\n    // proxy's plain-text refusal names the thing that refused.\n    const wire = sanitizeWire(\n      parsed === null || typeof parsed !== \"object\"\n        ? { ...textAsWireError(text) }\n        : (parsed as Record<string, unknown>),\n    );\n    if (response.status === 401 || response.status === 403) {\n      const challenge = parseBearerChallenge(\n        response.headers.get(\"www-authenticate\"),\n      );\n      const discovery = await fetchDiscovery(challenge.resourceMetadata, base);\n      throw new OpsClientError(\n        \"refused\",\n        refusalMessage(\n          response.status,\n          wire,\n          bearer !== undefined,\n          challenge,\n          discovery,\n        ),\n        response.status,\n        wire,\n      );\n    }\n    if (response.status === 404) {\n      throw new OpsClientError(\n        \"absent\",\n        wire.message ?? \"not found\",\n        404,\n        wire,\n      );\n    }\n    throw new OpsClientError(\n      \"error\",\n      wire.message ??\n        (wire.issues !== undefined\n          ? `The instance refused the payload: ${renderIssues(wire.issues, wire.truncated)}.`\n          : describeWireError(wire, response.status)),\n      response.status,\n      wire,\n    );\n  }\n\n  /**\n   * Render the door's own refusal rather than a summary of it. A missing\n   * scope and a missing credential need opposite actions, and the server\n   * already distinguishes them on the wire.\n   *\n   * When the challenge carried an RFC 9728 `resource_metadata` hint and the\n   * document resolved, the refusal also says who issues acceptable tokens\n   * and which scopes the surface understands. One message path for every\n   * refusal: the discovery lines append to the existing text, they never\n   * replace it.\n   */\n  function refusalMessage(\n    status: number,\n    wire: WireError,\n    presented: boolean,\n    challenge: BearerChallenge,\n    discovery: Discovery | undefined,\n  ): string {\n    const lines: string[] = [];\n    if (status === 403 && wire.reason === \"insufficient_scope\") {\n      lines.push(\n        wire.scope_mode === \"any\"\n          ? `Refused: the credential carries none of the scopes \"${\n              wire.scope ?? \"(unnamed)\"\n            }\", any one of which would do. The identity is valid and the credential is not, so this needs a token carrying one of them rather than signing in again.`\n          : `Refused: the credential does not carry the scope \"${\n              wire.scope ?? challenge.scope ?? \"(unnamed)\"\n            }\". The identity is valid and the credential is not, so this needs a token carrying that scope rather than signing in again.`,\n      );\n    } else if (status === 403 && wire.reason === \"insufficient_permissions\") {\n      lines.push(\n        \"Refused: the route's policy does not admit this identity with the claims its credential carries (roles, subject, actor or delegation). Retrying with the same credential will not change this; if access has been granted since it was issued, a refreshed token carrying the new claims can.\",\n      );\n    } else if (!presented) {\n      lines.push(\n        `Refused: this surface requires a credential and none was presented.${\n          advice.missingCredential === undefined\n            ? \"\"\n            : ` ${advice.missingCredential}`\n        }`,\n      );\n    } else {\n      lines.push(\n        `Refused: the instance rejected the credential${\n          wire.reason === undefined ? \"\" : ` (${wire.reason})`\n        }.`,\n      );\n    }\n    if (discovery !== undefined) {\n      lines.push(\n        discovery.issuers !== undefined && discovery.issuers.length > 0\n          ? `Tokens are issued by ${discovery.issuers.join(\", \")}.`\n          : \"The instance advertises no authorization server, so discovery cannot say who issues. Ask whoever operates the instance how to obtain a credential.\",\n      );\n      if (discovery.scopes !== undefined && discovery.scopes.length > 0) {\n        lines.push(\n          `Scopes this surface understands: ${discovery.scopes.join(\", \")}.`,\n        );\n      }\n    }\n    return lines.join(\"\\n\");\n  }\n\n  /**\n   * Tell a request that never left from one the instance may have received.\n   *\n   * They need opposite reactions. \"Could not reach it, start one\" invites a\n   * retry, which for a dispatch means running a possibly non-idempotent\n   * route a second time while the first is still going. So a failure is\n   * `unreachable` only when the connection provably never opened; a\n   * connection lost after that, a timeout, or a failure while reading the\n   * answer all mean the request may have run.\n   */\n  function classifyTransportFailure(\n    error: unknown,\n    address: string,\n    phase: \"request\" | \"response\",\n  ): OpsClientError {\n    const aborted =\n      error instanceof Error &&\n      (error.name === \"TimeoutError\" || error.name === \"AbortError\");\n    if (aborted) {\n      return new OpsClientError(\n        \"error\",\n        `The instance at ${address} accepted the request but did not answer within ${String(timeoutMs / 1000)}s. Any work it started is still running there, so do not simply re-run this.`,\n      );\n    }\n    if (phase === \"request\" && neverConnected(error)) {\n      return new OpsClientError(\n        \"unreachable\",\n        `Could not reach a running instance at ${address}: ${messageOf(error)}${\n          advice.unreachable === undefined ? \"\" : `\\n${advice.unreachable}`\n        }`,\n      );\n    }\n    return new OpsClientError(\n      \"interrupted\",\n      `The instance at ${address} may have received the request, but the connection was lost before it answered: ${messageOf(error)}. Any work it started may still be running there, so do not simply re-run this.`,\n    );\n  }\n\n  // The health surface answers 503 with a complete report when something is\n  // down. Treating that as a failure would blank the output at the one moment\n  // the command exists for.\n  const DOWN_IS_AN_ANSWER = { answeredBy: [503] } as const;\n\n  return {\n    authenticated: token !== undefined,\n\n    health: () => call<HealthReport>(\"/health\", DOWN_IS_AN_ANSWER),\n    ready: () => call<HealthReport>(\"/health/ready\", DOWN_IS_AN_ANSWER),\n    routeHealth: (id: string) =>\n      call<HealthComponent>(\n        `/health/routes/${encodeURIComponent(id)}`,\n        DOWN_IS_AN_ANSWER,\n      ),\n    indicatorHealth: (name: string) =>\n      call<HealthComponent>(\n        `/health/indicators/${encodeURIComponent(name)}`,\n        DOWN_IS_AN_ANSWER,\n      ),\n\n    /**\n     * Walk the whole collection rather than showing page one and stopping.\n     *\n     * The envelope's contract is that a present cursor means there is more,\n     * and a client that ignores it silently reports a partial inventory as\n     * a complete one. The cursor is replayed under the same filter it was\n     * minted with, which is the only way the server will honour it.\n     */\n    async listRoutes(filter: OpsRouteFilter = {}): Promise<OpsRouteSummary[]> {\n      // Serialised here, the one place that knows the wire, so no caller has\n      // to spell a filter name as a string the compiler does not own.\n      const query: Record<string, string> = {\n        ...(filter.dispatchable !== undefined\n          ? { dispatchable: String(filter.dispatchable) }\n          : {}),\n        ...(filter.id !== undefined ? { id: filter.id } : {}),\n        ...(filter.source !== undefined ? { source: filter.source } : {}),\n      };\n      const items: OpsRouteSummary[] = [];\n      const seen = new Set<string>();\n      let cursor: string | undefined;\n      do {\n        const params = new URLSearchParams(query);\n        if (cursor !== undefined) params.set(\"after\", cursor);\n        const suffix = params.toString();\n        const page = await call<OpsPage<OpsRouteSummary>>(\n          `/ops/routes${suffix.length > 0 ? `?${suffix}` : \"\"}`,\n        );\n        items.push(...page.items);\n        cursor = page.nextCursor;\n        // The loop trusts the instance to advance, and this client talks to\n        // instances it did not build: a repeated cursor would page forever and\n        // grow `items` without bound. Refusing beats hanging, and beats\n        // silently returning a listing with the same rows in it many times.\n        if (cursor !== undefined && !seen.add(cursor)) {\n          throw new OpsClientError(\n            \"error\",\n            \"The instance repeated a pagination cursor, so the route listing cannot be completed. This is a fault in the instance rather than in the request.\",\n          );\n        }\n      } while (cursor !== undefined);\n      return items;\n    },\n\n    describeRoute: (id: string) =>\n      call<OpsRouteDetail>(`/ops/routes/${encodeURIComponent(id)}`),\n\n    listDeferrals(filter: OpsDeferralFilter = {}) {\n      const params = new URLSearchParams({\n        ...(filter.state !== undefined ? { state: filter.state } : {}),\n        ...(filter.route !== undefined ? { route: filter.route } : {}),\n        ...(filter.limit !== undefined ? { limit: String(filter.limit) } : {}),\n        ...(filter.after !== undefined ? { after: filter.after } : {}),\n      });\n      const suffix = params.toString();\n      return call<OpsPage<OpsDeferralSummary>>(\n        `/ops/deferrals${suffix.length > 0 ? `?${suffix}` : \"\"}`,\n      );\n    },\n\n    describeDeferral: (id: string) =>\n      call<OpsDeferralSummary>(`/ops/deferrals/${encodeURIComponent(id)}`),\n\n    dispatch: (id: string, body: unknown) =>\n      call<OpsDispatchOutcome>(\n        `/ops/routes/${encodeURIComponent(id)}/exchanges`,\n        { method: \"POST\", body },\n      ),\n  };\n}\n\n/** What a refusal's `WWW-Authenticate` header said, reduced to what is used. */\ninterface BearerChallenge {\n  scope?: string;\n  resourceMetadata?: string;\n}\n\n/**\n * Read the RFC 6750 challenge parameters off a refusal.\n *\n * Quoted `key=\"value\"` pairs only, which is what every routecraft surface\n * emits and what RFC 9728 prescribes for `resource_metadata`. A header\n * that is absent, not a Bearer challenge, or otherwise unparseable yields\n * an empty result rather than an error: the challenge only enriches a\n * refusal that already stands on its own.\n */\nfunction parseBearerChallenge(header: string | null): BearerChallenge {\n  if (header === null || !/^\\s*bearer[\\s,]/i.test(header)) return {};\n  const result: BearerChallenge = {};\n  for (const match of header.matchAll(/([a-z_]+)\\s*=\\s*\"([^\"]*)\"/gi)) {\n    const key = match[1]!.toLowerCase();\n    if (key === \"scope\") result.scope = match[2]!;\n    if (key === \"resource_metadata\") result.resourceMetadata = match[2]!;\n  }\n  return result;\n}\n\n/** What the RFC 9728 document said, reduced to what a refusal can report. */\ninterface Discovery {\n  issuers?: string[];\n  scopes?: string[];\n}\n\n/**\n * Follow a challenge's `resource_metadata` hint.\n *\n * Best-effort by design: the hint names the instance's own document, but a\n * proxy can strip it, the fetch can time out, and a non-routecraft server\n * can answer nonsense. Every failure resolves to `undefined` so the\n * refusal degrades to what the status line already proves, never to a\n * second error about the enrichment.\n *\n * The hint is followed only to the origin the caller addressed\n * (RFC 9728 section 3.3): a `WWW-Authenticate` header is unvalidated\n * input, and a refusing server that could point this process anywhere\n * would hold an SSRF primitive aimed from the caller's network.\n * Redirects are refused for the same reason: a 302 on the first hop\n * would carry the fetch past the origin check.\n */\nasync function fetchDiscovery(\n  url: string | undefined,\n  base: string,\n): Promise<Discovery | undefined> {\n  if (url === undefined) return undefined;\n  let parsed: URL;\n  try {\n    parsed = new URL(url);\n  } catch {\n    return undefined;\n  }\n  if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n    return undefined;\n  }\n  try {\n    if (parsed.origin !== new URL(base).origin) return undefined;\n  } catch {\n    return undefined;\n  }\n  try {\n    const response = await fetch(url, {\n      redirect: \"error\",\n      signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),\n    });\n    if (!response.ok) return undefined;\n    const doc = (await response.json()) as {\n      authorization_servers?: unknown;\n      scopes_supported?: unknown;\n    };\n    const strings = (value: unknown): string[] | undefined =>\n      Array.isArray(value) && value.every((entry) => typeof entry === \"string\")\n        ? (value as string[]).map(printable)\n        : undefined;\n    const issuers = strings(doc.authorization_servers);\n    const scopes = strings(doc.scopes_supported);\n    return {\n      ...(issuers !== undefined ? { issuers } : {}),\n      ...(scopes !== undefined ? { scopes } : {}),\n    };\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Strip control characters from a server-supplied string before it reaches\n * a terminal or a log, so a hostile document cannot smuggle ANSI escapes or\n * fake extra lines into the refusal message. Bounded too: an issuer is a\n * URL, not a page.\n */\nfunction printable(value: string): string {\n  // eslint-disable-next-line no-control-regex -- removing control chars is the point\n  return value.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \"\").slice(0, 256);\n}\n\n/**\n * Parse a response body, or `undefined` when it is not JSON.\n *\n * Wrapping unparseable text in an object would let it through the\n * success guard, which only checks that the body is an object: a proxy\n * answering 200 with an HTML error page would then be handed to the caller\n * as a page whose `items` is missing, and the crash would land in the\n * renderer rather than here, where the address can be named.\n */\nfunction parseJson(text: string): unknown {\n  try {\n    return JSON.parse(text);\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Describe an error body that carries no message.\n *\n * The framework's error code belongs to a bounded, documented vocabulary and\n * is safe to show, so it is shown: without it a route that refused the\n * caller's own credential (`RC5038`) is indistinguishable from one that\n * crashed, and the operator is told only that the instance answered 500.\n */\nfunction describeWireError(wire: WireError, status: number): string {\n  const answered = `The instance answered ${String(status)}`;\n  if (wire.error === undefined && wire.code === undefined)\n    return `${answered}.`;\n  const parts = [wire.error, wire.code].filter(\n    (part): part is string => part !== undefined,\n  );\n  return `${answered}: ${parts.join(\" \")}. See ${docsFor(wire.code)} for what the code means.`;\n}\n\n/**\n * The documentation the code's own metadata points at, which is anchored at\n * the code rather than the top of a long page. The reader was handed a code,\n * so they have already done the part a search box would help with.\n *\n * A code this process has never registered falls back to the index. That is\n * the normal case for an ecosystem code, because the client runs wherever\n * the reader is and the instance is what imported the package that defines\n * it. Deriving the anchor from the string instead would produce a confident\n * link into the core page for a code documented somewhere else entirely.\n */\nfunction docsFor(code: string | undefined): string {\n  if (code === undefined) return DOCS_BASE;\n  return findErrorMeta(code)?.docs ?? DOCS_BASE;\n}\n\n/** A non-JSON error body, carried as the reason so it still reaches the reader. */\nfunction textAsWireError(text: string): WireError {\n  const message = text.trim();\n  return message.length > 0 ? { message } : {};\n}\n\n/**\n * Strip and bound every string the wire supplied before it reaches an error\n * message. The body came from whatever answered at the address, which may\n * be a proxy or a stranger, and an error message reaches terminals and logs.\n */\nfunction sanitizeWire(wire: Readonly<Record<string, unknown>>): WireError {\n  const out: WireError = {};\n  for (const key of [\n    \"error\",\n    \"reason\",\n    \"scope\",\n    \"scope_mode\",\n    \"code\",\n    \"message\",\n  ] as const) {\n    const value = wire[key];\n    if (typeof value === \"string\") out[key] = printable(value);\n  }\n  const raw = wire[\"issues\"];\n  if (Array.isArray(raw) && raw.length > 0) {\n    out.issues = raw.slice(0, MAX_WIRE_ISSUES).map(sanitizeIssue);\n    const truncated = wire[\"truncated\"];\n    const omitted =\n      raw.length -\n      out.issues.length +\n      (typeof truncated === \"number\" && Number.isInteger(truncated)\n        ? Math.max(0, truncated)\n        : 0);\n    if (omitted > 0) out.truncated = omitted;\n  }\n  return out;\n}\n\n/** How many issues reach an error message before it says how many more. */\nconst MAX_RENDERED_ISSUES = 5;\n\nfunction sanitizeIssue(issue: unknown): WireIssue {\n  const { path, message } = (issue ?? {}) as {\n    path?: unknown;\n    message?: unknown;\n  };\n  return {\n    ...(typeof path === \"string\" ? { path: printable(path) } : {}),\n    message: typeof message === \"string\" ? printable(message) : \"invalid\",\n  };\n}\n\n/**\n * Render an input refusal's issues as `path: message; ...`, bounded, since\n * a payload with a thousand bad array items would otherwise produce a\n * thousand-line error message.\n */\nfunction renderIssues(issues: readonly WireIssue[], truncated = 0): string {\n  const rendered = issues\n    .slice(0, MAX_RENDERED_ISSUES)\n    .map((issue) =>\n      issue.path !== undefined\n        ? `${issue.path}: ${issue.message}`\n        : issue.message,\n    );\n  const more = issues.length - rendered.length + truncated;\n  return more > 0\n    ? `${rendered.join(\"; \")}; and ${String(more)} more`\n    : rendered.join(\"; \");\n}\n\n/**\n * The codes a runtime raises when no connection was ever established, so\n * nothing was sent: refused, no route to the host, or a name that did not\n * resolve. Node reports them on the cause of `fetch failed`, Bun on the\n * error itself under its own names. Anything else is treated as possibly\n * delivered, which is the safe reading for a request that may run work.\n *\n * `ETIMEDOUT` is deliberately absent: Node raises it for a connect that\n * never completed and for a socket that went quiet after the request was\n * written, and the code alone cannot tell the two apart. undici's own\n * connect timeout has its own code and is listed.\n */\nconst NEVER_CONNECTED = new Set([\n  \"ECONNREFUSED\",\n  \"EHOSTUNREACH\",\n  \"ENETUNREACH\",\n  \"EADDRNOTAVAIL\",\n  \"UND_ERR_CONNECT_TIMEOUT\",\n  \"ENOTFOUND\",\n  \"EAI_AGAIN\",\n  \"EAI_NONAME\",\n  \"EAI_FAIL\",\n  \"ConnectionRefused\",\n  \"FailedToOpenSocket\",\n  \"DNSException\",\n]);\n\nfunction neverConnected(error: unknown): boolean {\n  let current: unknown = error;\n  for (let depth = 0; depth < 4 && current !== undefined; depth += 1) {\n    if (typeof current !== \"object\" || current === null) return false;\n    const code = (current as { code?: unknown }).code;\n    if (typeof code === \"string\" && NEVER_CONNECTED.has(code)) return true;\n    current = (current as { cause?: unknown }).cause;\n  }\n  return false;\n}\n\n/** A thrown value's message; non-Error throws (a `ResolveMessage`) still carry one. */\nfunction messageOf(error: unknown): string {\n  if (error instanceof Error) return error.message;\n  return typeof error === \"object\" && error !== null && \"message\" in error\n    ? String((error as { message: unknown }).message)\n    : String(error);\n}\n","/**\n * Paging the management API's collections.\n *\n * Keyset cursors, matching `DeferralStore.findExpired`'s idiom rather\n * than inventing a second one. The reason is not consistency for its own\n * sake: the collections this API will grow (deferrals, exchange\n * history) are live and mutating while an operator reads them, and offset\n * paging over a mutating set silently skips rows and repeats others. That\n * surfaces as \"the console lost a deferred payout\", never as an error.\n *\n * A cursor is valid only for the filter that produced it, exactly as the\n * deferral store's cursor is valid only against the store that produced\n * it. Replaying one under a different filter would hand back a page from a\n * different result set with no way for the caller to notice, so it is\n * refused instead.\n */\n\nimport { rcError } from \"../../error\";\nimport { compareCodeUnits } from \"../../shared/compare\";\nimport type { OpsRouteFilter } from \"./types\";\n\n/**\n * Page size when the caller names none.\n *\n * Exported so a contributed resource defaults to the same number rather\n * than picking its own: two independent defaults that happen to agree\n * drift the moment one is changed, and the collections would then page\n * differently for no reason a reader could see.\n */\nexport const DEFAULT_PAGE_SIZE = 50;\n\n/**\n * Largest page a caller may ask for. A bound rather than a preference: an\n * unbounded `limit` turns one request into an out-of-memory event.\n */\nconst MAX_PAGE_SIZE = 200;\n\n/** A decoded cursor: where to resume, and the filter it was minted under. */\ninterface DecodedCursor {\n  after: string;\n  filter: string;\n}\n\n/**\n * The result set a cursor pages, for a collection the mount does not own:\n * a contributed resource renders its own filter canonically (fixed field\n * order, absent fields as `null`) and hands the string here, so its\n * cursors are bound to its filters exactly as the route listing's are.\n */\nexport interface CursorScope {\n  readonly fingerprint: string;\n}\n\n/** What binds a cursor: the route filter, or a contributor's own scope. */\nexport type PageFilter = OpsRouteFilter | CursorScope;\n\n/**\n * The one refusal for a cursor this API cannot use.\n *\n * Named once because it is thrown from three places: both arms of\n * {@link decodeCursor} and any contributed resource decoding a keyset of\n * its own. Three copies of the sentence meant the same failure answered\n * differently depending on which half rejected it.\n *\n * @throws RC5059 always\n */\nexport function malformedCursor(): never {\n  throw rcError(\"RC5059\", undefined, {\n    message:\n      \"The cursor is malformed. Pass back the `nextCursor` from the previous page unchanged, or omit it to start from the first page.\",\n  });\n}\n\n/**\n * Build a cursor scope for a contributed collection: the resource name,\n * then its filter fields in a fixed order.\n *\n * A function rather than a paragraph a contributor re-reads and re-types.\n * The recipe fails silently when it is got wrong: leave a filter field\n * out of the fingerprint and the cursors it mints are honoured across\n * that filter, handing back a page of a different result set with no\n * error, which is the one thing the fingerprint exists to prevent.\n */\nexport function cursorScope(\n  resource: string,\n  ...fields: ReadonlyArray<string | number | boolean | null | undefined>\n): CursorScope {\n  return {\n    fingerprint: JSON.stringify([resource, ...fields.map((f) => f ?? null)]),\n  };\n}\n\n/**\n * Canonical rendering of a filter, used to bind a cursor to it.\n *\n * Field order is fixed here rather than taken from the caller's query\n * string, so the same filter written two ways produces one fingerprint and\n * a cursor survives a client that reorders its parameters.\n */\nfunction fingerprintFilter(filter: PageFilter): string {\n  if (\"fingerprint\" in filter) return filter.fingerprint;\n  return JSON.stringify([\n    filter.dispatchable ?? null,\n    filter.id ?? null,\n    filter.source ?? null,\n  ]);\n}\n\n/**\n * Read `limit` and `after` off a resource's raw query, as the mount reads\n * them for the route listing: a `limit` that is not a positive integer is\n * `RC5059`, which the mount answers as a 400 naming the rule.\n */\nexport function parsePageQuery(query: Readonly<Record<string, string>>): {\n  limit?: number;\n  after?: string;\n} {\n  const raw = query[\"limit\"];\n  let limit: number | undefined;\n  if (raw !== undefined) {\n    limit = Number(raw);\n    assertPageLimit(limit);\n  }\n  const after = query[\"after\"];\n  return {\n    ...(limit !== undefined ? { limit } : {}),\n    ...(after !== undefined ? { after } : {}),\n  };\n}\n\n/**\n * Reject a `limit` the API would otherwise have to guess at.\n *\n * Refused rather than clamped, as `assertSweepLimit` already does for the\n * deferral store: a caller that asked for 10000 and silently received 200\n * cannot tell a bounded page from a complete answer, and will read page one\n * forever believing it has everything.\n */\nfunction assertPageLimit(limit: number | undefined): void {\n  if (limit === undefined) return;\n  if (!Number.isInteger(limit) || limit <= 0) {\n    throw rcError(\"RC5059\", undefined, {\n      message: `The page limit must be a positive integer; received ${String(limit)}.`,\n    });\n  }\n  if (limit > MAX_PAGE_SIZE) {\n    throw rcError(\"RC5059\", undefined, {\n      message: `The page limit must not exceed ${String(MAX_PAGE_SIZE)}; received ${String(limit)}.`,\n    });\n  }\n}\n\n/**\n * Mint a cursor pointing just past `key`, bound to the filter that\n * produced the page.\n *\n * Opaque to the caller by construction: base64url of a shape this module\n * owns. A client that decodes it and constructs its own is outside the\n * contract, which is the point of publishing a string rather than a key.\n *\n * The key is whatever orders the contributor's own result set strictly:\n * {@link takePage} passes a row's `id`, and a collection ordered by\n * something else renders its keyset into one string and reads it back\n * itself. The deferral listing does that, ordering by `(deferredAt, id)`\n * because a deferral id says nothing about time.\n */\nexport function encodeCursor(key: string, filter: PageFilter): string {\n  const payload: DecodedCursor = {\n    after: key,\n    filter: fingerprintFilter(filter),\n  };\n  return Buffer.from(JSON.stringify(payload), \"utf8\").toString(\"base64url\");\n}\n\n/**\n * Decode a cursor and check it was minted under this same filter.\n *\n * Both failure modes are the caller's, and they are deliberately one code\n * with different messages: a garbled cursor and a cursor replayed under a\n * changed filter are both \"this cursor cannot be used here\", and neither\n * says anything about the data behind it.\n */\nexport function decodeCursor(cursor: string, filter: PageFilter): string {\n  let decoded: unknown;\n  try {\n    decoded = JSON.parse(Buffer.from(cursor, \"base64url\").toString(\"utf8\"));\n  } catch {\n    malformedCursor();\n  }\n  const value = decoded as Partial<DecodedCursor> | null;\n  if (\n    value === null ||\n    typeof value !== \"object\" ||\n    typeof value.after !== \"string\" ||\n    typeof value.filter !== \"string\"\n  ) {\n    malformedCursor();\n  }\n  if (value.filter !== fingerprintFilter(filter)) {\n    throw rcError(\"RC5059\", undefined, {\n      message:\n        \"The cursor was produced under a different filter. A cursor pages one result set, so changing a filter starts a new listing: drop the cursor, or restore the filter it was issued under.\",\n    });\n  }\n  return value.after;\n}\n\n/**\n * Take one page from an id-ordered list.\n *\n * The list must already be sorted by `id` on the same strict total order\n * the cursor assumes; `compareCodeUnits` is that order.\n */\nexport function takePage<T extends { id: string }>(\n  sorted: readonly T[],\n  filter: PageFilter,\n  limit: number | undefined,\n  after: string | undefined,\n): { items: T[]; nextCursor?: string } {\n  assertPageLimit(limit);\n  const size = limit ?? DEFAULT_PAGE_SIZE;\n  const start =\n    after === undefined\n      ? 0\n      : sorted.findIndex((item) => compareCodeUnits(item.id, after) > 0);\n  // A cursor whose row has since disappeared is not an error: the next row\n  // in order is exactly where the caller should resume, and findIndex\n  // returning -1 means every remaining row sorts at or before it.\n  if (start === -1) return { items: [] };\n  const items = sorted.slice(start, start + size);\n  const last = items[items.length - 1];\n  const more = last !== undefined && start + size < sorted.length;\n  return more\n    ? { items, nextCursor: encodeCursor(last.id, filter) }\n    : { items };\n}\n","/**\n * Ordering primitives shared by the keyset cursors.\n *\n * Two cursors page by `(key, id)` today, the deferral store's expiry scan\n * and the management API's route collection, and both depend on the same\n * property: a strict total order that does not move between runtimes. One\n * copy so a well-meant change in either place cannot break only the other.\n */\n\n/**\n * Code-unit comparison, deliberately not `localeCompare`: a keyset cursor\n * needs a stable strict order, and locale collation can change between\n * runtimes and between platforms running the same code.\n */\nexport function compareCodeUnits(a: string, b: string): number {\n  return a < b ? -1 : a > b ? 1 : 0;\n}\n","/**\n * JSON for values that were never written to be JSON.\n *\n * Event payloads carry whatever the emitting code had to hand: an `Error`,\n * a live exchange, the route it is running on, the context that owns both.\n * `JSON.stringify` renders an `Error` as `{}` and throws outright on the\n * cycles the other three contain, so every surface that puts a bus payload\n * on a wire or in a column needs the same reductions. They live here so the\n * telemetry sink and the ops event tail cannot disagree about what an\n * exchange looks like once serialised.\n */\n\nimport { isCraftContext, isExchange, isRoute } from \"../brand.ts\";\n\nexport interface SafeStringifyOptions {\n  /**\n   * Omit any property named `_snapshot`, at every level.\n   *\n   * Event authors mark sub-payloads with it when they carry the exchange's\n   * own body and headers, which is payload data rather than metadata. A\n   * surface that has not been asked to capture payloads drops it.\n   */\n  dropSnapshot?: boolean;\n}\n\n/**\n * Stringify a value, reducing what cannot be rendered honestly.\n *\n * Errors keep their name, message and stack. An exchange, a route and a\n * context each collapse to their identifier, which is what a reader can act\n * on and all that would survive the cycle anyway. An object that contains\n * itself becomes `\"[Circular]\"`; one merely referenced twice is rendered\n * twice, because a shared value is not a cycle and a reader that asked for\n * the payload should get all of it. A failure to serialise even after all\n * that returns a\n * one-field object naming the failure rather than throwing into the caller,\n * because the caller is a log sink or a live stream and neither can do\n * anything useful with the exception.\n */\nexport function safeStringify(\n  value: unknown,\n  options: SafeStringifyOptions = {},\n): string {\n  // The chain of holders from the root down to the value being visited, not\n  // every object already seen. A set that only ever grows cannot tell a cycle\n  // from a diamond, and calls the second arm of the diamond `\"[Circular]\"`.\n  // `JSON.stringify` binds the replacer's `this` to the holder, so popping\n  // back to it before each visit keeps the stack to the live ancestors.\n  const ancestors: unknown[] = [];\n  try {\n    // `JSON.stringify` answers `undefined` for a top-level undefined, symbol\n    // or function, and every caller here is writing to a wire that needs a\n    // string. `null` is the honest JSON rendering of a value with no\n    // representation.\n    return (\n      JSON.stringify(value, function (this: unknown, key, val: unknown) {\n        while (\n          ancestors.length > 0 &&\n          ancestors[ancestors.length - 1] !== this\n        ) {\n          ancestors.pop();\n        }\n        if (options.dropSnapshot === true && key === \"_snapshot\")\n          return undefined;\n        if (val instanceof Error) {\n          return {\n            name: val.name,\n            message: val.message,\n            ...(typeof val.stack === \"string\" ? { stack: val.stack } : {}),\n          };\n        }\n        // The framework's own brand guards, not a shape heuristic. The\n        // structural version misread any payload that happened to carry the\n        // same key names, and its unguarded read through `definition` threw\n        // inside the replacer for a nullish one, which collapsed the WHOLE\n        // value to a serialisation error rather than losing one field. These\n        // are the same guards `logger.ts` already discriminates these three\n        // types with, so the two readers cannot disagree about what an\n        // exchange looks like.\n        if (isExchange(val)) return { exchangeId: (val as { id: string }).id };\n        if (isRoute(val)) {\n          return {\n            routeId: (val as { definition: { id: string } }).definition.id,\n          };\n        }\n        if (isCraftContext(val)) {\n          return { contextId: (val as { contextId: string }).contextId };\n        }\n        if (val !== null && typeof val === \"object\") {\n          if (ancestors.includes(val)) return \"[Circular]\";\n          ancestors.push(val);\n        }\n        return val;\n      }) ?? \"null\"\n    );\n  } catch (err) {\n    return JSON.stringify({ _serializationError: String(err) });\n  }\n}\n","import type { HealthLedger } from \"./state\";\nimport type { CraftContext } from \"../../context\";\nimport { rcError } from \"../../error\";\nimport type { Duration } from \"../../shared/duration.ts\";\nimport { assertIndicatorName } from \"./indicator\";\nimport type { FailureDomain, Health, OpsResource } from \"./types\";\n\n/**\n * Symbol key the ops plugin publishes its per-context ledger under.\n *\n * Exposed on the store so other surfaces can read health without going\n * through HTTP: the CLI's TUI, a future management console, and the `/ops`\n * action endpoints all need the same ledger the endpoints report from.\n * `Symbol.for` so the key is shared across duplicate package copies in a\n * workspace, matching every other plugin's convention.\n */\nexport const OPS_HEALTH_STATE: unique symbol = Symbol.for(\n  \"routecraft.plugin.ops.health-state\",\n);\n\n/**\n * Symbol key for the management resources other packages contribute, keyed\n * by resource name. Written by {@link registerOpsResource}, read by the ops\n * mount per request, so a resource registered by a plugin applied before\n * or after the ops plugin is served alike.\n */\nexport const OPS_RESOURCES: unique symbol = Symbol.for(\n  \"routecraft.plugin.ops.resources\",\n);\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [OPS_HEALTH_STATE]: HealthLedger;\n    [OPS_RESOURCES]: Map<string, OpsResource>;\n  }\n}\n\n/** Names the mount serves itself; a contributed resource cannot take them. */\nconst RESERVED_RESOURCE_NAMES = new Set([\"routes\", \"events\"]);\n\n/** A resource name is one path segment: what an operator types after `/ops/`. */\nconst RESOURCE_NAME = /^[a-z][a-z0-9-]*$/;\n\n/**\n * Contribute a read-only resource to the management API. See\n * {@link OpsResource} for the contract and where it is served.\n *\n * Call it from a plugin's `apply()`. It needs no ops plugin to be present:\n * the registration lives on the context store and is served when an ops\n * mount exists, and inert otherwise.\n *\n * @throws RC5053 on a reserved or malformed name, or a name already taken\n */\nexport function registerOpsResource<TItem>(\n  ctx: CraftContext,\n  resource: OpsResource<TItem>,\n): void {\n  if (typeof resource.name !== \"string\" || !RESOURCE_NAME.test(resource.name)) {\n    throw rcError(\"RC5053\", undefined, {\n      message: `Management resource name \"${resource.name}\" must be one lowercase path segment (letters, digits and dashes), because it is what follows /ops/ on the wire.`,\n    });\n  }\n  if (RESERVED_RESOURCE_NAMES.has(resource.name)) {\n    throw rcError(\"RC5053\", undefined, {\n      message: `Management resource name \"${resource.name}\" is served by the ops mount itself and cannot be contributed.`,\n    });\n  }\n  const registry =\n    ctx.getStore(OPS_RESOURCES) ?? new Map<string, OpsResource>();\n  if (registry.has(resource.name)) {\n    throw rcError(\"RC5053\", undefined, {\n      message: `Management resource \"${resource.name}\" is already registered on this context. One contributor per name.`,\n    });\n  }\n  registry.set(resource.name, resource as OpsResource);\n  ctx.setStore(OPS_RESOURCES, registry);\n}\n\n/**\n * An indicator another plugin contributes, without the app listing it.\n *\n * `defineIndicator` is the app's API: a handle declared in source and named\n * in `ops.indicators`. A plugin that watches a dependency the app never\n * wrote a line for (the remotes plugin and the instances it imports from)\n * has no such handle to hand the app, so it contributes the declaration\n * here and reports through the function the contribution returns. The\n * ops plugin binds it to its ledger at start, and before that, or without\n * an ops plugin at all, a report is inert for the same reason a push\n * through an unbound handle is: health instrumentation must not be able\n * to fail the code it instruments.\n */\nexport interface ContributedIndicator {\n  readonly name: string;\n  readonly domain?: FailureDomain;\n  readonly maxAge?: Duration;\n  /**\n   * Where reports go: one sink per ops ledger that bound the indicator, so a\n   * context carrying two ops mounts reports into both. Empty until an ops\n   * plugin binds it, and empty again after teardown.\n   */\n  readonly sinks: Set<(health: Health, reportedAt: number) => void>;\n  /**\n   * The most recent report, replayed to a ledger that binds after it was\n   * made. A contributor whose start() ran before the ops plugin's would\n   * otherwise have its first verdict lost, and a remote unreachable at boot\n   * would read as up until its next refresh.\n   */\n  last?: { health: Health; at: number };\n}\n\n/**\n * Symbol key for the indicators other plugins contribute, keyed by name.\n * Written by {@link contributeOpsIndicator}, bound by the ops plugin's\n * `start()`, so a contribution made from any plugin's `apply()` is served\n * whatever order the plugins were applied in.\n *\n * @internal\n */\nexport const OPS_CONTRIBUTED_INDICATORS: unique symbol = Symbol.for(\n  \"routecraft.plugin.ops.contributed-indicators\",\n);\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [OPS_CONTRIBUTED_INDICATORS]: Map<string, ContributedIndicator>;\n  }\n}\n\n/**\n * Contribute an indicator to the health report from a plugin's `apply()`.\n *\n * Returns the function to report through. A report made before an ops\n * plugin binds the indicator is kept and replayed into the ledger when it\n * binds, at the time it was made; in a context with no ops plugin a report\n * goes nowhere.\n *\n * @throws RC5053 on a malformed name, or a name another contributor took\n */\nexport function contributeOpsIndicator(\n  ctx: CraftContext,\n  definition: Omit<ContributedIndicator, \"sinks\" | \"last\">,\n): (health: Health) => void {\n  assertIndicatorName(definition.name, \"contributeOpsIndicator\");\n  const registry =\n    ctx.getStore(OPS_CONTRIBUTED_INDICATORS) ??\n    new Map<string, ContributedIndicator>();\n  if (registry.has(definition.name)) {\n    throw rcError(\"RC5053\", undefined, {\n      message: `Indicator \"${definition.name}\" is already contributed on this context. One contributor per name.`,\n    });\n  }\n  const entry: ContributedIndicator = { ...definition, sinks: new Set() };\n  registry.set(definition.name, entry);\n  ctx.setStore(OPS_CONTRIBUTED_INDICATORS, registry);\n  return (health) => {\n    const at = Date.now();\n    entry.last = { health, at };\n    for (const sink of entry.sinks) sink(health, at);\n  };\n}\n","import type { OpsRouteDetail } from \"../ops/types\";\n\n/**\n * One imported route, as the ops listing presents it.\n *\n * The capability registry carries what the agent surface needs (a schema\n * per arm, a description, tags); this record carries the rest of what the\n * remote said about the route, so the local listing can describe an\n * imported route exactly as the remote's own listing would, with the\n * JSON Schema renderings passed through rather than re-rendered.\n */\nexport interface RemoteRoute {\n  /** The remote's name in `defineConfig({ remotes })`. */\n  remote: string;\n  /** The route id on the remote. */\n  id: string;\n  /** The local endpoint the route answers on (`id` for the default remote, else `remote:id`). */\n  endpoint: string;\n  /** The remote's own description of the route. */\n  detail: OpsRouteDetail;\n}\n\n/**\n * Symbol key the remotes plugin publishes imported routes under, keyed by\n * local endpoint. Read by the ops management API so an imported route is\n * listed, described and dispatched through the local door like any other.\n *\n * `Symbol.for` so the key is shared across duplicate package copies in a\n * workspace, matching every other plugin's convention.\n *\n * @internal\n */\nexport const REMOTE_ROUTES: unique symbol = Symbol.for(\n  \"routecraft.plugin.remotes.routes\",\n);\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [REMOTE_ROUTES]: Map<string, RemoteRoute>;\n  }\n}\n","/**\n * The management API's HTTP door.\n *\n * The only file in this surface that knows HTTP exists: it turns a request\n * into a call on {@link ManagementApi} and that call's result into a\n * response. Resource-shaped, because dispatching creates an exchange and\n * the exchange is a sub-resource of the route it runs on, which also gives\n * the operations tier somewhere obvious to land later without inventing a\n * second grammar.\n *\n * The shape of the door is not a licence to move logic through it: every\n * decision about what a route IS lives in `management.ts`, and every\n * decision about who may act lives in `tier.ts`.\n */\n\nimport { parsePageQuery } from \"./pagination.ts\";\nimport { isRoutecraftError, rcCodeOf } from \"../../brand\";\nimport { missingCredentialReason } from \"../http/auth\";\nimport {\n  insufficientScopeResponse,\n  jsonResponse,\n  methodNotAllowed,\n  missingCredentialResponse,\n} from \"../http/response\";\nimport { callerRefusalResponse } from \"../http/caller-refusal.ts\";\nimport { principalExpirySignal } from \"../../auth/expiry.ts\";\nimport { anySignal } from \"../../shared/abort.ts\";\nimport { sseResponse, type SseEvent } from \"../http/sse\";\nimport type { HttpMountContext } from \"../server/types\";\nimport type { ManagementApi } from \"./management\";\nimport { admitToTier, type TierVerdict } from \"./tier\";\nimport type { OpsEventTailItem, OpsRouteQuery, OpsTiers } from \"./types\";\n\nexport interface ManagementHandlerOptions {\n  api: ManagementApi;\n  /** Resolved tier values. Unset tiers are disabled. */\n  tiers: OpsTiers;\n  /**\n   * Report a refusal this mount made itself.\n   *\n   * The ingress emits `auth:success` and `auth:rejected` around the validator,\n   * which covers a credential that failed verification. It cannot cover the\n   * two refusals decided here: a credential-free caller on a scope-gated tier\n   * (the validator answers `absent`, which is neither), and a caller the\n   * validator admitted whose principal lacks the scope. Without this, an\n   * operator counting rejections to spot probing of the management surface\n   * sees nothing for either, and sees `auth:success` for someone who was then\n   * refused. The http plugin wires the same parity hook for its own `absent`\n   * case.\n   */\n  onRefused?: (refusal: { reason: string; scheme: string }) => void;\n}\n\n/** `GET /ops/routes` and `GET /ops/routes/{id}`. */\nconst ROUTES_COLLECTION = \"/ops/routes\";\nconst ROUTE_DETAIL = /^\\/ops\\/routes\\/([^/]+)$/;\nconst ROUTE_EXCHANGES = /^\\/ops\\/routes\\/([^/]+)\\/exchanges$/;\n/** `GET /ops/events`. */\nconst EVENTS = \"/ops/events\";\n/** `GET /ops/{resource}` and `GET /ops/{resource}/{segment...}` for contributed resources. */\nconst RESOURCE = /^\\/ops\\/([^/]+)((?:\\/[^/]+)*)$/;\n\n/**\n * Percent-decode a path segment, or `undefined` when the escape is\n * malformed. `decodeURIComponent` throws on input like `%` or `%zz`, which\n * any caller can send; funnelling those into the same 404 as an unknown\n * route keeps a malformed id from reading as a server fault.\n */\nfunction decodeSegment(value: string): string | undefined {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return undefined;\n  }\n}\n\nconst notFound = (): Response =>\n  jsonResponse({ error: \"not found\" }, { status: 404 });\n\n/** A HEAD's answer: the status and the type of the body a GET would carry. */\nconst emptyOk = (): Response =>\n  new Response(null, {\n    status: 200,\n    headers: { \"content-type\": \"application/json; charset=utf-8\" },\n  });\n\n/**\n * The listener is already carrying its full complement of streams.\n *\n * 503 rather than 429: nothing about this caller is wrong, and the condition\n * clears as other streams end, which is what `Retry-After` says. The delay is\n * a hint rather than a promise, since no one can know when a slot frees.\n */\nconst listenerFull = (): Response =>\n  jsonResponse(\n    { error: \"service unavailable\", reason: \"streaming_capacity\" },\n    { status: 503, headers: { \"retry-after\": \"5\" } },\n  );\n\n/**\n * Turn a refusal into its wire form.\n *\n * A disabled tier answers 404 rather than 403 so an instance discloses\n * nothing about what it could expose, and so the rule is the one an ingress\n * proxy would enforce in front of it. A missing scope is 403 with the\n * RFC 6750 `insufficient_scope` shape, which is what tells a client the\n * identity was fine and the credential was not.\n */\nfunction refuse(\n  verdict: Exclude<TierVerdict, { kind: \"admit\" }>,\n  onRefused: ManagementHandlerOptions[\"onRefused\"],\n  requestUrl: string,\n): Response {\n  // A disabled tier is not an auth decision: it answers 404 to everyone, so\n  // reporting it as a rejection would count configuration as probing.\n  if (verdict.kind === \"disabled\") return notFound();\n  // The ingress already emitted for a verified-and-rejected credential.\n  if (verdict.kind === \"rejected\") return verdict.response;\n  if (verdict.kind === \"unauthenticated\") {\n    onRefused?.({\n      reason: missingCredentialReason(verdict.scheme),\n      scheme: verdict.scheme,\n    });\n    return missingCredentialResponse(verdict.scheme, requestUrl);\n  }\n  onRefused?.({ reason: \"insufficient_scope\", scheme: verdict.scheme });\n  return insufficientScopeResponse(verdict.scheme, requestUrl, {\n    scope: verdict.missing,\n  });\n}\n\n/** Parse `?dispatchable=`, refusing a value that is neither true nor false. */\nfunction readBoolean(raw: string | null): boolean | undefined | \"invalid\" {\n  if (raw === null) return undefined;\n  if (raw === \"true\") return true;\n  if (raw === \"false\") return false;\n  return \"invalid\";\n}\n\n/** Parse `?limit=`, leaving range validation to the pagination module. */\nfunction readLimit(raw: string | null): number | undefined | \"invalid\" {\n  if (raw === null) return undefined;\n  const value = Number(raw);\n  if (!Number.isFinite(value)) return \"invalid\";\n  return value;\n}\n\n/**\n * Build the `/ops` request handler.\n *\n * Returns `undefined` for any path it does not own, so the ops mount can\n * offer the request to its health surface instead of the two competing over\n * one routing table.\n */\nexport function createManagementHandler(\n  options: ManagementHandlerOptions,\n): (req: Request, context: HttpMountContext) => Promise<Response | undefined> {\n  const { api, tiers, onRefused } = options;\n\n  return async function handle(\n    req: Request,\n    context: HttpMountContext,\n  ): Promise<Response | undefined> {\n    const url = new URL(req.url);\n    const { pathname } = url;\n    if (!pathname.startsWith(\"/ops/\")) {\n      return undefined;\n    }\n\n    const detailMatch = ROUTE_DETAIL.exec(pathname);\n    const exchangesMatch = ROUTE_EXCHANGES.exec(pathname);\n\n    if (pathname === ROUTES_COLLECTION || detailMatch) {\n      const verdict = await admitToTier(tiers.introspection, context);\n      if (verdict.kind !== \"admit\") return refuse(verdict, onRefused, req.url);\n      if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n        return methodNotAllowed(\"GET, HEAD\");\n      }\n      return pathname === ROUTES_COLLECTION\n        ? listRoutes(api, url)\n        : describeRoute(api, detailMatch![1]!);\n    }\n\n    if (pathname === EVENTS) {\n      const verdict = await admitToTier(tiers.events, context);\n      if (verdict.kind !== \"admit\") return refuse(verdict, onRefused, req.url);\n      if (req.method !== \"GET\") {\n        return methodNotAllowed(\"GET\");\n      }\n      // A tail may say nothing for hours, which is exactly what the\n      // listener's idle reaper exists to cut. The rest of this mount is\n      // ordinary request/response, so the slot is claimed for this request\n      // rather than declared for the whole surface.\n      const release = context.claimStreamingSlot();\n      if (release === undefined) return listenerFull();\n      // Admission is checked once, and this tail may outlive the credential\n      // that passed it by hours. The rule is the http source's, and it bites\n      // hardest here: this is the surface that streams failure events with\n      // their messages and stack traces, so it is the last one that should\n      // keep serving on lapsed authority. Closing is the whole remedy, since\n      // a 401 cannot follow the 200 already on the wire and an EventSource\n      // reconnects into ordinary admission.\n      // No event and no wire message: the close IS the signal, and inventing\n      // an auth:rejected reason for it would put a value outside the bounded\n      // vocabulary onto a surface an operator counts refusals from.\n      const expiry = principalExpirySignal(verdict.principal, {\n        clockToleranceSec: verdict.clockToleranceSec,\n      });\n      const closes = anySignal(req.signal, expiry?.signal);\n      return sseResponse(tailEvents(api, closes), closes, () => {\n        expiry?.cancel();\n        release();\n      });\n    }\n\n    if (exchangesMatch) {\n      const verdict = await admitToTier(tiers.dispatch, context);\n      if (verdict.kind !== \"admit\") return refuse(verdict, onRefused, req.url);\n      if (req.method !== \"POST\") {\n        return methodNotAllowed(\"POST\");\n      }\n      return dispatchExchange(\n        api,\n        exchangesMatch[1]!,\n        req,\n        verdict.principal,\n        context,\n        onRefused,\n      );\n    }\n\n    const resourceMatch = RESOURCE.exec(pathname);\n    if (resourceMatch) {\n      const name = decodeSegment(resourceMatch[1]!);\n      const resource = name === undefined ? undefined : api.resource(name);\n      // An unknown resource and a disabled tier answer alike, on purpose:\n      // the tier check comes first so an unconfigured instance discloses\n      // neither which resources exist nor that the surface does.\n      const verdict = await admitToTier(tiers.introspection, context);\n      if (verdict.kind !== \"admit\") return refuse(verdict, onRefused, req.url);\n      if (resource === undefined) return notFound();\n      if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n        return methodNotAllowed(\"GET, HEAD\");\n      }\n      const rest = resourceMatch[2]!.split(\"/\").filter((s) => s.length > 0);\n      const segments: string[] = [];\n      for (const raw of rest) {\n        const segment = decodeSegment(raw);\n        if (segment === undefined) return notFound();\n        segments.push(segment);\n      }\n      try {\n        if (segments.length === 0) {\n          const query = Object.fromEntries(url.searchParams.entries());\n          // A HEAD carries no body, and a contributed listing costs the\n          // contributor a read per item; the route listing it mirrors\n          // is a scan, so this is where the cost would be new. The page\n          // limit is still checked, so a malformed one is 400 on HEAD as\n          // on GET; a cursor is the contributor's to decode against its\n          // own scope, and HEAD does not ask it to.\n          if (req.method === \"HEAD\") {\n            parsePageQuery(query);\n            return emptyOk();\n          }\n          return jsonResponse(await resource.list(query), { status: 200 });\n        }\n        const item = await resource.describe(segments);\n        return item === undefined\n          ? notFound()\n          : jsonResponse(item, { status: 200 });\n      } catch (error: unknown) {\n        // A malformed limit or cursor is the caller's; anything else is\n        // the contributor's and reaches the wire as a code, never a\n        // message, as the dispatch surface does.\n        const code = rcCodeOf(error);\n        if (code === \"RC5059\") return badRequest((error as Error).message);\n        return jsonResponse(\n          { error: \"resource failed\", resource: name, code },\n          { status: 500 },\n        );\n      }\n    }\n\n    return notFound();\n  };\n}\n\nfunction listRoutes(api: ManagementApi, url: URL): Response {\n  const dispatchable = readBoolean(url.searchParams.get(\"dispatchable\"));\n  if (dispatchable === \"invalid\") {\n    return badRequest('The \"dispatchable\" filter must be \"true\" or \"false\".');\n  }\n  const limit = readLimit(url.searchParams.get(\"limit\"));\n  if (limit === \"invalid\") {\n    return badRequest(\"The page limit must be a positive integer.\");\n  }\n  const id = url.searchParams.get(\"id\");\n  const source = url.searchParams.get(\"source\");\n  const after = url.searchParams.get(\"after\");\n\n  const query: OpsRouteQuery = {\n    ...(dispatchable !== undefined ? { dispatchable } : {}),\n    ...(id !== null ? { id } : {}),\n    ...(source !== null ? { source } : {}),\n    ...(limit !== undefined ? { limit } : {}),\n    ...(after !== null ? { after } : {}),\n  };\n\n  try {\n    return jsonResponse(api.listRoutes(query), { status: 200 });\n  } catch (error: unknown) {\n    // A malformed limit or cursor is the caller's, and its message names\n    // the way out; anything else is ours and must not be echoed.\n    if (rcCodeOf(error) === \"RC5059\") {\n      return badRequest((error as Error).message);\n    }\n    throw error;\n  }\n}\n\nfunction describeRoute(api: ManagementApi, rawId: string): Response {\n  const id = decodeSegment(rawId);\n  if (id === undefined) return notFound();\n  const route = api.describeRoute(id);\n  return route === undefined\n    ? notFound()\n    : jsonResponse(route, { status: 200 });\n}\n\n/**\n * What this door answers a route that needed an identity the request went\n * without, when a credential could have supplied one: an open tier admits a\n * credential-free caller, and one whose credential failed, as anonymous.\n * `undefined` when the mount has no validator or the caller was admitted\n * with a principal, since no credential would then change the outcome.\n *\n * `authenticate` is memoized per request and admission has already called\n * it wherever a validator is in scope, so this reads the verdict rather\n * than verifying a second time. A failed credential gets the canonical\n * rejection the ingress already reported; a missing one gets the same 401\n * and `auth:rejected` a scope-gated tier gives it.\n */\nasync function unauthenticatedAnswer(\n  context: HttpMountContext,\n  requestUrl: string,\n  onRefused: ManagementHandlerOptions[\"onRefused\"],\n): Promise<(() => Response) | undefined> {\n  if (!context.auth.configured) return undefined;\n  const result = await context.authenticate();\n  if (result === undefined || result.kind === \"admit\") return undefined;\n  if (result.kind === \"reject\") return () => result.response.clone();\n  return () => {\n    onRefused?.({\n      reason: missingCredentialReason(result.scheme),\n      scheme: result.scheme,\n    });\n    return missingCredentialResponse(result.scheme, requestUrl);\n  };\n}\n\nasync function dispatchExchange(\n  api: ManagementApi,\n  rawId: string,\n  req: Request,\n  principal: Parameters<ManagementApi[\"dispatch\"]>[2],\n  context: HttpMountContext,\n  onRefused: ManagementHandlerOptions[\"onRefused\"],\n): Promise<Response> {\n  const id = decodeSegment(rawId);\n  if (id === undefined) return notFound();\n\n  let body: unknown;\n  try {\n    const text = await req.text();\n    body = text.length === 0 ? undefined : JSON.parse(text);\n  } catch {\n    return badRequest(\"The request body must be JSON.\");\n  }\n\n  let outcome: Awaited<ReturnType<ManagementApi[\"dispatch\"]>>;\n  try {\n    outcome = await api.dispatch(id, body, principal);\n  } catch (error: unknown) {\n    if (!isRoutecraftError(error)) throw error;\n    const code = rcCodeOf(error);\n    const refused = callerRefusalResponse(error, {\n      routeId: id,\n      requestUrl: req.url,\n      principal,\n      unauthenticated: await unauthenticatedAnswer(context, req.url, onRefused),\n    });\n    if (refused !== undefined) return refused;\n    // The code crosses the wire and the message does not. A route failure is\n    // whatever its steps threw, and `rcError` messages routinely interpolate\n    // the cause: adapter failures carry hostnames, file paths and upstream\n    // response text. On an open dispatch tier that is reconnaissance for\n    // anyone who can reach the port, and it would contradict the health\n    // surface's rule that no response body carries an error message. That\n    // rule governs dispatch and health; the event tail is a separately\n    // scope-gated observation surface and does carry messages, on purpose,\n    // because a failure event without one is not diagnostic. The code\n    // is enough to tell one kind of failure from another; the message is in\n    // the logs, where the error policy already routes it.\n    //\n    // `RC5002` stays here on purpose. It is not only the caller's input: the\n    // same code covers `.output()` validation, a mid-pipeline `.validate()`\n    // and an empty aggregation, which are the instance's faults and would be\n    // misattributed by a 400. An `RC5004` or `RC5060` reaches this line only\n    // from the route's pipeline: the dispatch's own refusals arrive as values.\n    return jsonResponse({ error: \"dispatch failed\", code }, { status: 500 });\n  }\n\n  if (outcome.outcome === \"refused\") {\n    if (outcome.reason === \"unknown\") return notFound();\n    return jsonResponse(\n      {\n        error: \"not dispatchable\",\n        code: \"RC5060\",\n        message: outcome.message,\n      },\n      { status: 409 },\n    );\n  }\n  if (outcome.outcome === \"deferred\") {\n    // 202 for a deferral, the same answer the http() source gives: the work\n    // was accepted and is not finished, and the acknowledgment carries\n    // what is needed to finish it.\n    return jsonResponse(outcome, { status: 202 });\n  }\n  // A drop is a terminal outcome the request delivered successfully, so\n  // it is 200 with the outcome named rather than an error status: the\n  // caller asked for a dispatch and got a complete answer about one.\n  return jsonResponse(outcome, { status: 200 });\n}\n\nfunction badRequest(message: string): Response {\n  return jsonResponse({ error: \"bad request\", message }, { status: 400 });\n}\n\n/**\n * Map the tail's items onto the wire.\n *\n * The bus event name rides the SSE `event` field so a client can subscribe\n * to one kind, and repeats inside `data` because a reader consuming the\n * body with `fetch` rather than `EventSource` sees the payload and not the\n * fields. The tail's own signals are not bus events and do not borrow a\n * bus name: a drop is named for what it is, and a heartbeat is the spec's\n * comment, which every client already ignores.\n */\nasync function* tailEvents(\n  api: ManagementApi,\n  signal: AbortSignal,\n): AsyncIterable<SseEvent | string> {\n  for await (const item of api.tailEvents(signal)) {\n    yield frameOf(item);\n  }\n}\n\nfunction frameOf(item: OpsEventTailItem): SseEvent | string {\n  if (item.kind === \"heartbeat\") return \": keep-alive\\n\\n\";\n  if (item.kind === \"dropped\") {\n    return { event: \"ops:events:dropped\", data: { count: item.count } };\n  }\n  // Already rendered at emission, so it passes through untouched: sending it\n  // back through the serialiser would escape it a second time and hand the\n  // reader a JSON string where it expects an object.\n  return { event: item.name, data: item.data };\n}\n","/**\n * Admission to a management tier.\n *\n * Two decisions, kept apart on purpose. The mount's `auth` (its own, or the\n * named server's, per the server plugin's inheritance) decides WHO the\n * caller is. The tier's own value decides what that identity must carry.\n * One validator serves every tier; only the requirement differs, which is\n * what makes \"this token may read routes but may not dispatch\" a rule an\n * operator can also enforce at a proxy.\n */\n\nimport { missingScopes } from \"../../auth/authorize\";\nimport type { Principal } from \"../../auth/types\";\nimport type { HttpMountContext } from \"../server/types\";\nimport type { OpsTier, OpsTiers } from \"./types\";\n\n/**\n * What admission decided. Transport-neutral apart from the `rejected` arm,\n * which passes the auth middleware's own canonical response through: that\n * response carries the 401-versus-500 classification the security standard\n * requires (an unreachable JWKS is a server fault, never a bad credential),\n * and re-deriving it here would be a second place for that to drift.\n */\nexport type TierVerdict =\n  | { kind: \"disabled\" }\n  | {\n      kind: \"admit\";\n      principal?: Principal;\n      /**\n       * Clock skew the verification that admitted this caller allowed,\n       * carried through so a tail re-checking the same credential applies\n       * the boundary that let it in rather than a stricter one of its own.\n       *\n       * Required, like the field it comes from: an optional one would be a\n       * re-derivation with nicer syntax, and the value a consumer would\n       * reach for is `?? 0`, which is exactly the stricter boundary that\n       * closed a stream the door had just admitted. A verdict with no\n       * principal carries `0` honestly, because no credential was checked.\n       */\n      clockToleranceSec: number;\n    }\n  | { kind: \"unauthenticated\"; scheme: string }\n  | { kind: \"rejected\"; response: Response }\n  | { kind: \"insufficient\"; missing: string; scheme: string };\n\n/**\n * Decide whether this request may act on a tier.\n *\n * On an open (`true`) tier a presented credential is still resolved, so a\n * dispatch carries the real principal into the route rather than running\n * anonymously just because the tier asked for nothing. A credential that\n * fails there leaves the caller anonymous rather than refused, matching the\n * rule already applied to an opted-out mcp mount: on a surface with no wall,\n * presenting a credential must never leave a caller worse off than silence.\n *\n * On a scope-gated tier the scope check is exact membership against\n * `principal.scopes`, through the same `missingScopes` that backs\n * `authorize({ scopes })`, so an operator reasons about one scope model\n * rather than two. A tier reads the subject's own ring and nothing else:\n * `authorize({ effective })` can widen a ROUTE's check to the outermost\n * actor's scopes, and that widening is a property of that gate, never of\n * this one.\n */\nexport async function admitToTier(\n  tier: OpsTier | undefined,\n  context: HttpMountContext,\n): Promise<TierVerdict> {\n  if (tier === undefined || tier === false) return { kind: \"disabled\" };\n\n  if (tier === true) {\n    if (!context.auth.configured) {\n      return { kind: \"admit\", clockToleranceSec: 0 };\n    }\n    const result = await context.authenticate();\n    return result?.kind === \"admit\"\n      ? {\n          kind: \"admit\",\n          principal: result.principal,\n          clockToleranceSec: result.clockToleranceSec,\n        }\n      : { kind: \"admit\", clockToleranceSec: 0 };\n  }\n\n  const result = await context.authenticate();\n  if (!result) {\n    // Unreachable: a scope-gated tier with no validator in scope fails the\n    // boot. Kept as an explicit refusal so a future gap fails closed rather\n    // than admitting every caller to a tier that asked for a scope.\n    return { kind: \"unauthenticated\", scheme: \"bearer\" };\n  }\n  if (result.kind === \"absent\") {\n    return { kind: \"unauthenticated\", scheme: result.scheme };\n  }\n  if (result.kind === \"reject\")\n    return { kind: \"rejected\", response: result.response };\n\n  if (missingScopes(result.principal, [tier]).length > 0) {\n    // The scheme rides along because the refusal carries a challenge, and a\n    // challenge naming the wrong scheme tells an api-key client to go and\n    // get a bearer token it has no way to obtain.\n    return {\n      kind: \"insufficient\",\n      missing: tier,\n      scheme: result.principal.scheme,\n    };\n  }\n  return {\n    kind: \"admit\",\n    principal: result.principal,\n    clockToleranceSec: result.clockToleranceSec,\n  };\n}\n\n/** Whether any tier is scope-gated, and so actually enforces a wall. */\nexport function enforcesWall(tiers: OpsTiers): boolean {\n  return Object.values(tiers).some((value) => typeof value === \"string\");\n}\n","/**\n * Turning ledger state into HTTP responses.\n *\n * The routing table is deliberately tiny and fully enumerated: five paths,\n * everything else 404. Keeping it here rather than in the plugin leaves the\n * plugin as wiring and makes the response contract unit-testable without\n * binding a port.\n */\n\nimport { jsonResponse } from \"../http/response\";\nimport type { HttpMountContext } from \"../server/types\";\nimport type { HealthLedger } from \"./state\";\nimport type {\n  HealthComponent,\n  HealthDetailsExposure,\n  HealthReport,\n  LivenessReport,\n} from \"./types\";\n\nexport interface HealthHandlerOptions {\n  state: HealthLedger;\n  /** Exposure of per-component `details`. */\n  details: HealthDetailsExposure;\n  /** Process uptime in seconds, injectable for tests. */\n  uptime: () => number;\n}\n\n/**\n * Whether `details` maps are served on this request.\n *\n * `when-authenticated` resolves the caller's credential through the mount's\n * effective validator, read off the mount context's resolved facts so this\n * gate and `authenticate()` can never disagree about what \"has a validator\"\n * means. With no validator in scope it fails closed: writing the mode\n * explicitly with nothing to gate on is refused at boot by the plugin, so\n * the unauthenticated-serving path here is only ever the unwritten default,\n * and a default must not leak app-supplied diagnostics to an anonymous\n * caller. Verification runs only in that one mode, so a probe against an\n * open surface never pays for it.\n */\nasync function servesDetails(\n  exposure: HealthDetailsExposure,\n  context: HttpMountContext,\n): Promise<boolean> {\n  if (exposure === \"never\") return false;\n  if (exposure === \"always\") return true;\n  if (!context.auth.configured) return false;\n  const result = await context.authenticate();\n  return result?.kind === \"admit\";\n}\n\n/** Strip `details` from a component when the exposure gate is closed. */\nfunction project(\n  component: HealthComponent,\n  withDetails: boolean,\n): HealthComponent {\n  if (withDetails) return component;\n  return component.details === undefined\n    ? component\n    : {\n        status: component.status,\n        domain: component.domain,\n        ...(component.ageMs !== undefined ? { ageMs: component.ageMs } : {}),\n      };\n}\n\n/** Strip `details` from every component of a report. */\nfunction projectReport(\n  report: HealthReport,\n  withDetails: boolean,\n): HealthReport {\n  if (withDetails) return report;\n  const map = (\n    components: Record<string, HealthComponent>,\n  ): Record<string, HealthComponent> =>\n    Object.fromEntries(\n      Object.entries(components).map(([key, value]) => [\n        key,\n        project(value, false),\n      ]),\n    );\n  return {\n    view: report.view,\n    status: report.status,\n    context: project(report.context, false),\n    routes: map(report.routes),\n    indicators: map(report.indicators),\n  };\n}\n\n/**\n * Percent-decode a path segment, or `undefined` when the escape is malformed.\n *\n * `decodeURIComponent` throws `URIError` on input like `%` or `%zz`, which any\n * caller can send. Returning `undefined` funnels those into the same 404 as an\n * unknown component.\n */\nfunction decodeSegment(value: string): string | undefined {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return undefined;\n  }\n}\n\n/** Resolve a per-component path to its component, or `undefined` if unknown. */\nfunction resolveComponent(\n  state: HealthLedger,\n  pathname: string,\n): HealthComponent | undefined {\n  const routeId = /^\\/health\\/routes\\/([^/]+)$/.exec(pathname)?.[1];\n  if (routeId !== undefined) {\n    const decoded = decodeSegment(routeId);\n    return decoded === undefined ? undefined : state.routeComponentOf(decoded);\n  }\n\n  const indicator = /^\\/health\\/indicators\\/([^/]+)$/.exec(pathname)?.[1];\n  if (indicator !== undefined) {\n    const decoded = decodeSegment(indicator);\n    return decoded === undefined\n      ? undefined\n      : state.indicatorComponentOf(decoded);\n  }\n\n  return undefined;\n}\n\n/**\n * Build the ops request handler.\n *\n * Three signals, separated by what acting on each one does. The layout follows\n * MicroProfile Health (`/health`, `/health/live`, `/health/ready`, as\n * implemented by Quarkus, Helidon and Open Liberty) with Actuator's\n * per-component drill-down beneath the aggregate:\n *\n * - `GET /health`: operational health. Every component, whatever its domain.\n *   What an uptime monitor pages on. Never influences routing.\n * - `GET /health/live`: liveness. 200 while the process is up, and nothing\n *   else ever. Docker's HEALTHCHECK probes this, so no component may reach it:\n *   a third party going down would otherwise restart every replica in a loop.\n * - `GET /health/ready`: readiness. Whether this instance can serve right now,\n *   which is mostly its own lifecycle plus any instance-domain component.\n *   Consumed by reverse proxies and orchestrators.\n * - `GET /health/routes/<id>` and `GET /health/indicators/<name>`: one\n *   component with its own status code, for drill-down and targeted monitors.\n *   The `routes/` and `indicators/` prefixes keep component names from\n *   colliding with `live` and `ready` in the same path namespace.\n *\n * `/ops/*` is claimed by the same mount and answers 404 until the action\n * surface ships, so the paths cannot be taken by another surface in the\n * meantime. Every action there mutates and will require an authenticated\n * principal, which is the opposite posture to this read surface.\n */\nexport function createHealthHandler(\n  options: HealthHandlerOptions,\n): (req: Request, context: HttpMountContext) => Promise<Response> {\n  const { state, details, uptime } = options;\n\n  return async function handle(\n    req: Request,\n    context: HttpMountContext,\n  ): Promise<Response> {\n    const { pathname } = new URL(req.url);\n\n    const known =\n      pathname === \"/health\" ||\n      pathname === \"/health/live\" ||\n      pathname === \"/health/ready\" ||\n      pathname.startsWith(\"/health/routes/\") ||\n      pathname.startsWith(\"/health/indicators/\");\n\n    if (!known) {\n      return jsonResponse({ error: \"not found\" }, { status: 404 });\n    }\n\n    if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n      return new Response(null, {\n        status: 405,\n        headers: { Allow: \"GET, HEAD\" },\n      });\n    }\n\n    if (pathname === \"/health/live\") {\n      const body: LivenessReport = { status: \"up\", uptime: uptime() };\n      return jsonResponse(body, { status: 200 });\n    }\n\n    if (pathname === \"/health\" || pathname === \"/health/ready\") {\n      const withDetails = await servesDetails(details, context);\n      const report = state.report(\n        pathname === \"/health/ready\" ? \"readiness\" : \"all\",\n      );\n      return jsonResponse(projectReport(report, withDetails), {\n        status: report.status === \"down\" ? 503 : 200,\n      });\n    }\n\n    // Resolved before the gate: an unknown component answers 404 either way,\n    // so verifying a credential first would be work whose outcome cannot\n    // change the response.\n    const component = resolveComponent(state, pathname);\n    if (!component)\n      return jsonResponse({ error: \"not found\" }, { status: 404 });\n    const withDetails = await servesDetails(details, context);\n    return jsonResponse(project(component, withDetails), {\n      status: component.status === \"down\" ? 503 : 200,\n    });\n  };\n}\n","/**\n * Health state for one context.\n *\n * Pure and framework-free on purpose: it deals in route-id strings and its own\n * types, never in context or adapter modules. The plugin translates framework\n * events into calls here; this file holds the judgement and is unit-tested in\n * isolation with an injected clock.\n *\n * What health answers is deliberately narrow: can this component serve at all?\n * A route is `down` only when it is not running (its source gave up) and\n * `degraded` only when a circuit breaker is holding calls off or it was taken\n * offline on purpose. The outcome of an individual exchange never decides it.\n * A refused caller, a validation error, or a business rule saying no are all a\n * running route behaving correctly, and paging on them turns every scope gap\n * and every malformed request into an incident. Those outcomes are still\n * counted, and the count still surfaces in `details` so a human reading the\n * report can see a route that is serving badly; they just do not change its\n * status. Escalating repeated failure into a health signal is the circuit\n * breaker's job, because only the breaker knows which errors it counts\n * (routecraft excludes non-retryable ones, so authorization failures cannot\n * trip it) and only the breaker actually stops the route serving.\n */\n\nimport type {\n  CircuitState,\n  HealthChange,\n  ContextState,\n  FailureDomain,\n  Health,\n  HealthComponent,\n  HealthDetails,\n  HealthReport,\n  HealthStatus,\n  HealthView,\n  RouteLifecycle,\n} from \"./types\";\n\nexport interface HealthStateOptions {\n  /** Injectable clock, for tests. Defaults to `Date.now`. */\n  now?: () => number;\n  /**\n   * Called when a component's status changes, so the plugin can emit an event\n   * without the ledger knowing what an event is.\n   *\n   * Transitions are detected per component as it mutates rather than by\n   * re-deriving the whole report, so a hot route emitting one event per\n   * exchange costs a single status comparison rather than a walk of every\n   * component.\n   *\n   * Staleness is the exception: it is a function of elapsed time rather than\n   * of any call, so an indicator going stale surfaces on the next report and\n   * not as a transition.\n   */\n  onChange?: (change: HealthChange) => void;\n}\n\ninterface RouteRecord {\n  lifecycle: RouteLifecycle;\n  /**\n   * Breakers currently holding calls off, by label (`\"route\"` for a\n   * route-scope breaker). Empty is the healthy case. Tracked per label because\n   * a route may wrap several steps in their own.\n   */\n  breakers: Map<string, CircuitState>;\n  /**\n   * Consecutive failed exchanges. Diagnostic only: it explains a route that is\n   * serving badly, and never decides that the route is unhealthy.\n   */\n  consecutiveFailures: number;\n  /** Whether this route has ever completed an exchange successfully. */\n  everSucceeded: boolean;\n  /** Last status reported to `onChange`, so a transition is detected in O(1). */\n  lastStatus: HealthStatus;\n  /**\n   * Why the route's `.enabled()` predicate held it back. Set only while\n   * `lifecycle` is `disabled`; it is the whole point of reporting disabled\n   * rather than merely absent, so an operator reads \"mail-inbound: disabled\n   * (MAIL_USER, MAIL_APP_PASSWORD unset)\" and knows nothing is broken.\n   */\n  disabledReason?: string;\n}\n\ninterface IndicatorRecord {\n  maxAgeMs?: number;\n  domain: FailureDomain;\n  /** Set once the context reports started, which is when staleness starts counting. */\n  startedAt?: number;\n  lastReportAt?: number;\n  lastHealth?: Health;\n  inactive: boolean;\n  /** Last status reported to `onChange`, so a transition is detected in O(1). */\n  lastStatus: HealthStatus;\n}\n\n/**\n * A route's status, without building its details map.\n *\n * Split from {@link routeComponent} because transition detection runs on every\n * exchange: allocating a details object per exchange to read one field off it\n * is GC churn on the framework's hottest path.\n */\nfunction routeStatus(record: RouteRecord): HealthStatus {\n  const { lifecycle, breakers } = record;\n  if (lifecycle === \"failed\") return \"down\";\n  // Excluded from aggregation entirely, ahead of every other reading: a\n  // route the operator deliberately switched off must not move the overall\n  // status at all. Degrading on it would make a dormant capability page,\n  // which is precisely the alarm this feature exists to avoid.\n  if (lifecycle === \"disabled\") return \"inactive\";\n  if (lifecycle === \"offline\") return \"degraded\";\n  if (lifecycle === \"running\") return breakers.size > 0 ? \"degraded\" : \"up\";\n  return \"inactive\";\n}\n\n/**\n * Map a route's lifecycle and breakers onto the status vocabulary.\n *\n * Only `failed` is `down`: the route is not running, so nothing it is meant to\n * serve is being served. An open breaker is `degraded` instead, because the\n * route is live and the breaker is expected to close again on its own. So is a\n * route deliberately taken offline, which makes reduced capability visible in\n * the aggregate without paging. A route that ran once and closed, or was\n * stopped cleanly, reports `inactive`: still listed (so \"did it run?\" is\n * answerable) but excluded from aggregation.\n *\n * Recent exchange failures ride along in `details` whatever the status, since\n * \"up, but its last four calls failed\" is the report a human actually needs,\n * and is precisely the thing that must not page.\n */\nfunction routeComponent(record: RouteRecord): HealthComponent {\n  const { lifecycle, breakers } = record;\n  const details: HealthDetails = { lifecycle };\n\n  if (record.disabledReason !== undefined) {\n    details[\"reason\"] = record.disabledReason;\n  }\n  if (breakers.size > 0) {\n    details[\"circuit\"] = [...breakers.values()].includes(\"open\")\n      ? \"open\"\n      : \"half-open\";\n    details[\"breakers\"] = [...breakers.keys()].sort().join(\",\");\n  }\n  if (record.consecutiveFailures > 0) {\n    details[\"failures\"] = record.consecutiveFailures;\n  }\n\n  // Routes are always deployment-domain: derotating one instance cannot\n  // redirect work that every replica would fail at identically, and no route\n  // can declare otherwise in this version.\n  const domain: FailureDomain = \"deployment\";\n\n  return { status: routeStatus(record), domain, details };\n}\n\n/** Whether a component belongs in a given view. */\nfunction includedIn(view: HealthView, component: HealthComponent): boolean {\n  return view === \"all\" || component.domain === \"instance\";\n}\n\n/**\n * The read surface other components get.\n *\n * Published on the store instead of {@link HealthState} itself. Withholding\n * the constructor prevents nothing: `ctx.getStore(OPS_HEALTH_STATE)` hands\n * back the live instance, so a wider type would let any consumer call\n * `sourceDied` or `reportIndicator` and drive the ledger into a state the\n * framework never observed, which is the invariant the whole design rests on.\n * The `/ops` action surface will get a deliberate mutating interface when it\n * ships, rather than inheriting every method by default.\n */\nexport interface HealthLedger {\n  /** Where the app is in its serving lifecycle. */\n  readonly lifecycle: ContextState;\n  report(view?: HealthView): HealthReport;\n  routeComponentOf(routeId: string): HealthComponent | undefined;\n  indicatorComponentOf(name: string): HealthComponent | undefined;\n}\n\n/**\n * Aggregates route and indicator health, and projects it into views.\n *\n * Both push (indicators report up or down when they run) and event-derived\n * (routes are tracked from the framework's lifecycle and exchange events).\n * There is no scheduled check: in routecraft the idiomatic periodic worker is\n * a route, so dependency probes are routes that push into an indicator here.\n *\n * One ledger backs every view. What differs between them is only which\n * components they cover, decided by failure domain, so readiness can carry a\n * routing signal while operational health carries an alerting one without the\n * two states ever drifting apart.\n */\nexport class HealthState implements HealthLedger {\n  private readonly routes = new Map<string, RouteRecord>();\n  private readonly indicators = new Map<string, IndicatorRecord>();\n  private readonly now: () => number;\n  private readonly onChange: (change: HealthChange) => void;\n  private contextState: ContextState = \"starting\";\n  private lastContextStatus: HealthStatus = \"down\";\n\n  constructor(options: HealthStateOptions = {}) {\n    this.now = options.now ?? Date.now;\n    this.onChange = options.onChange ?? (() => {});\n  }\n\n  /** Emit a transition for one route, if its status moved. */\n  private settleRoute(name: string, record: RouteRecord): void {\n    const next = routeStatus(record);\n    if (next === record.lastStatus) return;\n    const from = record.lastStatus;\n    record.lastStatus = next;\n    this.onChange({ component: \"route\", name, from, to: next });\n  }\n\n  /** Emit a transition for one indicator, if its status moved. */\n  private settleIndicator(name: string, record: IndicatorRecord): void {\n    const next = this.indicatorComponent(record).status;\n    if (next === record.lastStatus) return;\n    const from = record.lastStatus;\n    record.lastStatus = next;\n    this.onChange({ component: \"indicator\", name, from, to: next });\n  }\n\n  /** Emit a transition for the context component, if its status moved. */\n  private settleContext(): void {\n    const next = this.contextComponent().status;\n    if (next === this.lastContextStatus) return;\n    const from = this.lastContextStatus;\n    this.lastContextStatus = next;\n    this.onChange({ component: \"context\", name: \"context\", from, to: next });\n  }\n\n  /**\n   * The context finished starting: every route has subscribed, so this\n   * instance can serve. Until this fires, readiness refuses traffic.\n   */\n  contextStarted(): void {\n    this.contextState = \"started\";\n    const at = this.now();\n    for (const record of this.indicators.values()) {\n      record.startedAt ??= at;\n    }\n    this.settleContext();\n  }\n\n  /**\n   * Shutdown began. Readiness refuses traffic immediately, before any route is\n   * torn down, so a load balancer stops sending work while in-flight exchanges\n   * drain rather than during the teardown.\n   */\n  contextStopping(): void {\n    this.contextState = \"stopping\";\n    this.settleContext();\n  }\n\n  /** Shutdown finished. */\n  contextStopped(): void {\n    this.contextState = \"stopped\";\n    this.settleContext();\n  }\n\n  /** Where the app is in its serving lifecycle. */\n  get lifecycle(): ContextState {\n    return this.contextState;\n  }\n\n  /** A route started (or restarted): it is running with a clean slate. */\n  routeStarted(routeId: string): void {\n    // Carry the previous status across the reset. Without it a route that died\n    // and restarted compares up against a freshly initialised up and emits no\n    // transition, leaving an alert opened by the down event never closed.\n    const previous = this.routes.get(routeId)?.lastStatus ?? \"up\";\n    const record: RouteRecord = {\n      lifecycle: \"running\",\n      breakers: new Map(),\n      consecutiveFailures: 0,\n      everSucceeded: false,\n      lastStatus: previous,\n    };\n    this.routes.set(routeId, record);\n    this.settleRoute(routeId, record);\n  }\n\n  /**\n   * A route's `.enabled()` predicate held it back, or released it.\n   *\n   * Kept apart from {@link HealthState.setRouteOffline} rather than folded\n   * into it: `offline` degrades and `disabled` does not, because one is a\n   * running deployment losing capability and the other is capability that\n   * was never configured. Collapsing them would either page on a dormant\n   * route or stop paging on a derotated one.\n   *\n   * @param reason - Why it is off. Reported next to the route.\n   */\n  setRouteDisabled(routeId: string, reason: string): void {\n    const record = this.ensureRoute(routeId);\n    record.lifecycle = \"disabled\";\n    record.disabledReason = reason;\n    record.breakers.clear();\n    record.consecutiveFailures = 0;\n    this.settleRoute(routeId, record);\n  }\n\n  /**\n   * A route's predicate now passes. The route itself reports `running` once\n   * it starts; this only clears the disabled disposition so that\n   * `routeStarted` is not overruled by a stale reason.\n   */\n  clearRouteDisabled(routeId: string): void {\n    const record = this.routes.get(routeId);\n    if (!record || record.lifecycle !== \"disabled\") return;\n    record.lifecycle = \"stopped\";\n    delete record.disabledReason;\n    this.settleRoute(routeId, record);\n  }\n\n  /**\n   * A route stopped. A one-shot that ran and succeeded is `completed`, one\n   * that did nothing is `stopped`, and both are fine: a route closing is not a\n   * failure. A route already judged `failed` or `offline` keeps that\n   * disposition.\n   */\n  routeStopped(routeId: string): void {\n    const record = this.routes.get(routeId);\n    if (!record) return;\n    if (\n      record.lifecycle === \"failed\" ||\n      record.lifecycle === \"offline\" ||\n      // A route stopping BECAUSE it was disabled would otherwise report as a\n      // clean finish, losing the reason and the distinction the whole\n      // feature rests on.\n      record.lifecycle === \"disabled\"\n    ) {\n      return;\n    }\n    record.lifecycle = record.everSucceeded ? \"completed\" : \"stopped\";\n    this.settleRoute(routeId, record);\n  }\n\n  /**\n   * Mark a route deliberately out of service. Reports `degraded`, so the\n   * aggregate shows reduced capability without paging, restarting, or\n   * derotating anything.\n   */\n  setRouteOffline(routeId: string, offline: boolean): void {\n    const record = this.routes.get(routeId);\n    if (!record) return;\n    // A dead source stays dead. Bringing a route back online says the\n    // operator wants it serving, not that its source recovered; only\n    // `routeStarted` can clear `failed`, which is the same rule\n    // `routeStopped` and `exchangeCompleted` already follow. A disabled\n    // route is the same case from the other direction: the predicate\n    // decides, and an operator toggling offline must not talk it into\n    // serving without its credentials.\n    if (record.lifecycle === \"failed\" || record.lifecycle === \"disabled\") {\n      return;\n    }\n    record.lifecycle = offline ? \"offline\" : \"running\";\n    if (!offline) record.consecutiveFailures = 0;\n    this.settleRoute(routeId, record);\n  }\n\n  /**\n   * A source gave up producing, so the route is no longer running. This is the\n   * genuine liveness signal: nothing this route serves is being served, and no\n   * exchange outcome can say the same.\n   */\n  sourceDied(routeId: string): void {\n    const record = this.ensureRoute(routeId);\n    record.lifecycle = \"failed\";\n    this.settleRoute(routeId, record);\n  }\n\n  /**\n   * Record that a route exists, without claiming anything about its health.\n   *\n   * Route readiness is bounded by a timeout, so a source that never signals\n   * (and legitimately may not: one that reaches readiness only on its first\n   * message) leaves no lifecycle event behind. Without this the route would be\n   * absent from the report altogether, and a route stuck starting would be\n   * invisible rather than merely unproven. Seeded as `inactive` so it is\n   * listed and excluded from aggregation: there is no evidence it is serving,\n   * and none that it has failed. Any later event replaces this.\n   */\n  declareRoute(routeId: string): void {\n    if (this.routes.has(routeId)) return;\n    this.routes.set(routeId, {\n      lifecycle: \"stopped\",\n      breakers: new Map(),\n      consecutiveFailures: 0,\n      everSucceeded: false,\n      lastStatus: \"inactive\",\n    });\n  }\n\n  /**\n   * An exchange completed: the route is serving, so its failure run resets.\n   *\n   * A dead source is not revived by one. `route:source:failed` is emitted\n   * before the route's controller aborts, so exchanges already in flight\n   * settle afterwards; treating those as evidence of life would clear the\n   * failure, and the subsequent stop would then read as a clean finish and\n   * drop the route out of aggregation. Only `routeStarted` clears `failed`,\n   * matching how `routeStopped` already preserves it.\n   */\n  exchangeCompleted(routeId: string): void {\n    const record = this.ensureRoute(routeId);\n    if (\n      record.lifecycle !== \"offline\" &&\n      record.lifecycle !== \"failed\" &&\n      // An exchange draining out of a route that was just disabled settles\n      // after the flip. Treating it as evidence of life would clear the\n      // reason and report the route running while it drains to a stop.\n      record.lifecycle !== \"disabled\"\n    ) {\n      record.lifecycle = \"running\";\n    }\n    record.everSucceeded = true;\n    record.consecutiveFailures = 0;\n    this.settleRoute(routeId, record);\n  }\n\n  /**\n   * An exchange failed. Counted, never escalated: the route is still running\n   * and still serving, and this one caller got an error. Whether that error\n   * was a dead upstream or a caller asking for something they may not have is\n   * not a distinction health can draw, so it draws none and reports the\n   * failure as context on a route that stays `up`.\n   */\n  exchangeFailed(routeId: string): void {\n    this.ensureRoute(routeId).consecutiveFailures += 1;\n  }\n\n  /**\n   * A circuit breaker tripped or is probing recovery: calls are being held\n   * off, so the route is degraded until it closes again.\n   *\n   * @param routeId - The route the breaker belongs to.\n   * @param label - The breaker's label, `\"route\"` for a route-scope breaker.\n   *   Tracked per label because several breakers may be open at once.\n   */\n  circuitOpened(routeId: string, label: string, state: CircuitState): void {\n    const record = this.ensureRoute(routeId);\n    record.breakers.set(label, state);\n    this.settleRoute(routeId, record);\n  }\n\n  /** A breaker recovered: it stops holding the route degraded. */\n  circuitClosed(routeId: string, label: string): void {\n    const record = this.routes.get(routeId);\n    if (!record) return;\n    record.breakers.delete(label);\n    this.settleRoute(routeId, record);\n  }\n\n  /**\n   * Register an indicator. Registering also makes it appear in reports\n   * immediately (as healthy, then stale if it never reports), so a probe route\n   * that never runs is itself a signal.\n   */\n  registerIndicator(\n    name: string,\n    options: { maxAgeMs?: number; domain?: FailureDomain } = {},\n  ): void {\n    this.indicators.set(name, {\n      ...(options.maxAgeMs !== undefined ? { maxAgeMs: options.maxAgeMs } : {}),\n      domain: options.domain ?? \"deployment\",\n      ...(this.contextState === \"started\" ? { startedAt: this.now() } : {}),\n      inactive: false,\n      lastStatus: \"up\",\n    });\n  }\n\n  /** Record an indicator report. Any report clears a prior `inactive` marker. */\n  reportIndicator(\n    name: string,\n    health: Health,\n    reportedAt: number = this.now(),\n  ): void {\n    const record = this.indicators.get(name);\n    if (!record) return;\n    // A report replayed from before this ledger existed keeps its own time,\n    // so a maxAge window measures from the report and not from the binding.\n    record.lastReportAt = reportedAt;\n    // Copied, not referenced: this object came from the caller and is handed\n    // back in every subsequent report, so sharing it would let either side\n    // rewrite a verdict after the fact. Values are structural scalars, so a\n    // shallow copy is a whole one.\n    record.lastHealth =\n      health.details === undefined\n        ? { status: health.status }\n        : { status: health.status, details: { ...health.details } };\n    record.inactive = false;\n    this.settleIndicator(name, record);\n  }\n\n  /** Mute an indicator (maintenance): it reports `inactive` and never pages. */\n  setIndicatorInactive(name: string, inactive: boolean): void {\n    const record = this.indicators.get(name);\n    if (!record) return;\n    record.inactive = inactive;\n    this.settleIndicator(name, record);\n  }\n\n  /**\n   * Produce a report over one view.\n   *\n   * @param view - `all` for the operational report (everything, read by humans\n   *   and monitors), `readiness` for the routing signal (instance-domain\n   *   components only). Defaults to `all`.\n   *\n   * The readiness view is often just the context component, and that is the\n   * designed outcome rather than an oversight: nothing else qualifies until a\n   * component declares that its failures really are local to one replica. The\n   * context component alone still makes the view meaningful, because it is\n   * what refuses traffic during boot and drain.\n   */\n  report(view: HealthView = \"all\"): HealthReport {\n    // Null-prototype maps: component names are caller-chosen, and assigning\n    // `__proto__` on a plain object silently discards the entry. A dropped\n    // component is not merely missing from the body, it is missing from the\n    // aggregate, so a down dependency would read as healthy.\n    const routes: Record<string, HealthComponent> = Object.create(\n      null,\n    ) as Record<string, HealthComponent>;\n    for (const [id, record] of this.routes) {\n      const component = routeComponent(record);\n      if (includedIn(view, component)) routes[id] = component;\n    }\n\n    const indicators: Record<string, HealthComponent> = Object.create(\n      null,\n    ) as Record<string, HealthComponent>;\n    for (const [name, record] of this.indicators) {\n      const component = this.indicatorComponent(record);\n      if (includedIn(view, component)) indicators[name] = component;\n    }\n\n    const context = this.contextComponent();\n    const components = [\n      context,\n      ...Object.values(routes),\n      ...Object.values(indicators),\n    ].filter((component) => component.status !== \"inactive\");\n\n    const anyDown = components.some((c) => c.status === \"down\");\n    const anyDegraded = components.some((c) => c.status === \"degraded\");\n    const status: HealthStatus = anyDown\n      ? \"down\"\n      : anyDegraded\n        ? \"degraded\"\n        : \"up\";\n\n    return { view, status, context, routes, indicators };\n  }\n\n  /** One route's component, or `undefined` if no such route is tracked. */\n  routeComponentOf(routeId: string): HealthComponent | undefined {\n    const record = this.routes.get(routeId);\n    return record ? routeComponent(record) : undefined;\n  }\n\n  /** One indicator's component, or `undefined` if no such indicator exists. */\n  indicatorComponentOf(name: string): HealthComponent | undefined {\n    const record = this.indicators.get(name);\n    return record ? this.indicatorComponent(record) : undefined;\n  }\n\n  /** Where a route is in its life, or `undefined` if it is not tracked. */\n  routeLifecycle(routeId: string): RouteLifecycle | undefined {\n    return this.routes.get(routeId)?.lifecycle;\n  }\n\n  /**\n   * The app's serving lifecycle as a component.\n   *\n   * Always `instance` domain: whether this process has finished booting or has\n   * begun draining says nothing about its peers, and it is exactly the case\n   * where moving traffic elsewhere is the right response.\n   */\n  private contextComponent(): HealthComponent {\n    return {\n      status: this.contextState === \"started\" ? \"up\" : \"down\",\n      domain: \"instance\",\n      details: { state: this.contextState },\n    };\n  }\n\n  /**\n   * The record for a route, created if the event arrived before\n   * `route:started` (or without one at all, as a context-level source failure\n   * does). A route first seen this way is assumed running, since something\n   * produced an event for it.\n   */\n  private ensureRoute(routeId: string): RouteRecord {\n    const existing = this.routes.get(routeId);\n    if (existing) return existing;\n    const record: RouteRecord = {\n      lifecycle: \"running\",\n      breakers: new Map(),\n      consecutiveFailures: 0,\n      everSucceeded: false,\n      lastStatus: \"up\",\n    };\n    this.routes.set(routeId, record);\n    return record;\n  }\n\n  /**\n   * Project an indicator record, applying staleness.\n   *\n   * An indicator with no `maxAge` never goes stale: it is only as fresh as\n   * its last push, which is the right reading for one fed by a business route\n   * that may be idle for hours. Staleness is measured from the last report,\n   * or from `context:started` when it has never reported, so a slow first\n   * probe does not read as a dead dependency during boot.\n   */\n  private indicatorComponent(record: IndicatorRecord): HealthComponent {\n    const { domain } = record;\n    if (record.inactive) return { status: \"inactive\", domain };\n\n    const now = this.now();\n    const { maxAgeMs } = record;\n\n    if (record.lastReportAt === undefined) {\n      if (maxAgeMs === undefined) return { status: \"up\", domain };\n      const since = record.startedAt ?? now;\n      const age = now - since;\n      return age > maxAgeMs\n        ? {\n            status: \"down\",\n            domain,\n            ageMs: age,\n            details: { reason: \"no-report\" },\n          }\n        : { status: \"up\", domain, ageMs: age, details: { booting: true } };\n    }\n\n    const age = now - record.lastReportAt;\n    const last = record.lastHealth ?? { status: \"up\" as const };\n    // Copied on the way out as well as in: the record outlives the response,\n    // so handing back the stored map would let a reader rewrite the verdict\n    // every later report is built from.\n    const carried =\n      last.details !== undefined ? { details: { ...last.details } } : {};\n    if (last.status === \"down\") {\n      return { status: \"down\", domain, ageMs: age, ...carried };\n    }\n    if (maxAgeMs !== undefined && age > maxAgeMs) {\n      return {\n        status: \"down\",\n        domain,\n        ageMs: age,\n        details: { reason: \"stale\" },\n      };\n    }\n    return { status: last.status, domain, ageMs: age, ...carried };\n  }\n}\n","import { registerConfigApplier } from \"../../config-applier\";\nimport { opsPlugin } from \"./plugin\";\nimport type { OpsConfig } from \"./types\";\n\ndeclare module \"@routecraft/routecraft\" {\n  interface CraftConfig {\n    /** Operational surface: health endpoints, and later the action namespace. */\n    ops?: OpsConfig;\n  }\n}\n\n/**\n * Register the `ops` config key so `defineConfig({ ops: {...} })` is\n * equivalent to `defineConfig({ plugins: [opsPlugin({...})] })`. Loaded as a\n * side-effect import from `packages/routecraft/src/index.ts` so users do not\n * have to wire it manually.\n */\nregisterConfigApplier(\"ops\", (options) => opsPlugin(options));\n","/**\n * Remotes plugin: the dispatchable routes of other instances become direct\n * endpoints here.\n *\n * The consumer is a deployment where one constrained instance hosts\n * approved capabilities behind its own door and every engineer runs a\n * local instance with their own agents. The local instance names the\n * server under `remotes`, reads its route inventory through the ops\n * management API, and registers each route in the direct store and the\n * capability registry under a local endpoint. From then on nothing else\n * in the framework knows the route is elsewhere: `direct()`, `forward()`,\n * `directTool()`, `Direct(...)` in an agent's tool list, the tool policy\n * and the local ops listing all see a capability.\n *\n * The server keeps its service credentials and its `.authorize()`; this\n * side holds only a bearer for the server's door, and the local caller's\n * principal is never forwarded. What the server's validator mints from the\n * bearer is the identity every imported route runs under.\n */\n\nimport type { CraftContext, CraftPlugin } from \"../../context\";\nimport { rcError } from \"../../error\";\nimport {\n  CAPABILITY_REGISTRY,\n  isInternalEndpoint,\n  registerCapability,\n  type Capability,\n} from \"../../capabilities\";\nimport {\n  ADAPTER_DIRECT_STORE,\n  sanitizeEndpoint,\n} from \"../../adapters/direct/shared\";\nimport type { DirectChannel } from \"../../adapters/direct/types\";\nimport type { Exchange } from \"../../exchange\";\nimport { parseDuration } from \"../../shared/duration.ts\";\nimport {\n  createOpsHttpClient,\n  isLoopbackHostname,\n  type OpsHttpClient,\n} from \"../ops/client\";\nimport { contributeOpsIndicator } from \"../ops/store\";\nimport type { Health, OpsRouteDetail } from \"../ops/types\";\nimport { RemoteDirectChannel, type RemoteTarget } from \"./channel\";\nimport { standardSchemaFromJsonSchema } from \"./schema\";\nimport { REMOTE_ROUTES, type RemoteRoute } from \"./store\";\nimport type { RemoteDefinition, RemotesPluginOptions } from \"./types\";\n\n/** The remote whose routes are advertised bare. */\nconst DEFAULT_REMOTE = \"default\";\n\nconst DEFAULT_REFRESH = \"60s\";\nconst DEFAULT_TIMEOUT = \"30s\";\n\n/**\n * A remote's name is one segment of a tool wire name (`remote__lab__hello`)\n * and one half of a qualified endpoint (`lab:hello`), so it carries the\n * charset a model provider accepts and never the `__` separator that\n * would make the wire name ambiguous to split.\n */\nconst REMOTE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;\n\n/** One remote's live state on one context. */\ninterface RemoteRuntime {\n  name: string;\n  definition: RemoteDefinition;\n  client: OpsHttpClient;\n  report: (health: Health) => void;\n  refreshMs: number | undefined;\n  /** The channels this remote installed, by local endpoint. */\n  channels: Map<string, RemoteDirectChannel>;\n  /** The last inventory's detail per local endpoint, shadowed ones included. */\n  details: Map<string, OpsRouteDetail>;\n  /**\n   * How this remote removes each capability it registered, by local\n   * endpoint. Held rather than discarded so removal goes through the same\n   * identity-checked disposer every writer on that registry uses.\n   */\n  disposers: Map<string, () => void>;\n  timer?: ReturnType<typeof setInterval>;\n  inflight?: Promise<void>;\n  /** Whether the last refresh failed, so a repeat is logged quietly. */\n  down: boolean;\n  /** Whether an inventory has ever landed, so the first one is logged at info. */\n  seen: boolean;\n}\n\n/** Per-context state. One plugin instance may serve several contexts. */\ninterface Runtime {\n  remotes: RemoteRuntime[];\n  /** Stops listening for local routes starting and stopping. */\n  off: Array<() => void>;\n}\n\n/** The health indicator an imported remote reports through. */\nfunction indicatorName(remote: string): string {\n  return `remote.${remote}`;\n}\n\n/** The local endpoint a remote route answers on when qualified. */\nfunction qualified(remote: string, id: string): string {\n  return `${remote}:${id}`;\n}\n\n/**\n * Validate the config key once, at construction, so a typo fails\n * `defineConfig` rather than the first refresh.\n */\nfunction validate(options: RemotesPluginOptions): void {\n  if (\n    typeof options !== \"object\" ||\n    options === null ||\n    Array.isArray(options)\n  ) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `remotes must be an object of remotes by name, e.g. { default: { url } }.`,\n    });\n  }\n  for (const [name, definition] of Object.entries(options)) {\n    if (!REMOTE_NAME.test(name) || name.includes(\"__\") || name.endsWith(\"_\")) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `remotes.${name}: a remote name must match ${REMOTE_NAME.source}, must not contain \"__\" and must not end in \"_\". It becomes one segment of the tool name a model sees (remote__${name}__<route>) and the prefix of every qualified endpoint (${name}:<route>).`,\n      });\n    }\n    if (typeof definition !== \"object\" || definition === null) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `remotes.${name} must be an object with at least a url.`,\n      });\n    }\n    let url: URL;\n    try {\n      url = new URL(definition.url);\n    } catch {\n      throw rcError(\"RC5003\", undefined, {\n        message: `remotes.${name}.url must be an absolute URL; got ${JSON.stringify(definition.url)}.`,\n      });\n    }\n    if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n      throw rcError(\"RC5003\", undefined, {\n        message: `remotes.${name}.url must be an http or https URL; got ${url.protocol}.`,\n      });\n    }\n    const token = definition.auth?.token;\n    if (\n      token !== undefined &&\n      typeof token !== \"function\" &&\n      (typeof token !== \"string\" || token.length === 0)\n    ) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `remotes.${name}.auth.token must be a non-empty string or a function returning one.`,\n      });\n    }\n    // The same rule the CLI enforces, for the same reason: a bearer over\n    // plain http is readable by every hop, and loopback is the one address\n    // where there are none.\n    if (\n      token !== undefined &&\n      url.protocol === \"http:\" &&\n      !isLoopbackHostname(url.hostname)\n    ) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `remotes.${name}.url is ${definition.url}, which is plain http, and auth.token would travel over it as clear text. Use an https URL, or a loopback address (localhost, 127.0.0.1, ::1) for an instance on this machine.`,\n      });\n    }\n    if (definition.timeout !== undefined) {\n      parseDuration(definition.timeout, `remotes.${name}.timeout`);\n    }\n    if (definition.refresh !== undefined && definition.refresh !== false) {\n      parseDuration(definition.refresh, `remotes.${name}.refresh`);\n    }\n  }\n}\n\n/**\n * Another instance's dispatchable routes as direct endpoints here.\n *\n * Materialised by the config applier, so apps normally write\n * `defineConfig({ remotes: { default: { url, auth } } })` rather than\n * pushing it onto `config.plugins`.\n *\n * `apply` validates, builds a client per remote and contributes an\n * indicator per remote to the health report. `start` reads every\n * inventory once, awaited, so a route the remote exposes is a local\n * endpoint by the time the context reports ready, and a remote that is\n * unreachable registers nothing, logs, and reports its indicator down;\n * its routes appear on the refresh that first reaches it. `teardown`\n * clears the timers and removes every endpoint this plugin installed.\n */\nexport function remotesPlugin(options: RemotesPluginOptions): CraftPlugin {\n  validate(options);\n  const runtimes = new WeakMap<CraftContext, Runtime>();\n\n  return {\n    name: \"remotes\",\n\n    apply(ctx: CraftContext) {\n      const remotes: RemoteRuntime[] = Object.entries(options).map(\n        ([name, definition]) => {\n          const client = createOpsHttpClient({\n            url: definition.url,\n            ...(definition.auth?.token !== undefined\n              ? { token: definition.auth.token }\n              : {}),\n            timeout: definition.timeout ?? DEFAULT_TIMEOUT,\n            describeAddress: () => `remote \"${name}\" at ${definition.url}`,\n            advice: {\n              missingCredential: `Set remotes.${name}.auth.token to a credential the remote's door accepts.`,\n              unreachable: `Check remotes.${name}.url and that the instance is running.`,\n            },\n          });\n          const refreshMs =\n            definition.refresh === false\n              ? undefined\n              : parseDuration(\n                  definition.refresh ?? DEFAULT_REFRESH,\n                  `remotes.${name}.refresh`,\n                );\n          // Deployment domain: every replica reaches the remote with the same\n          // credential over the same network, so one failing means all do,\n          // and moving traffic between replicas would not help.\n          const report = contributeOpsIndicator(ctx, {\n            name: indicatorName(name),\n            domain: \"deployment\",\n          });\n          return {\n            name,\n            definition,\n            client,\n            report,\n            refreshMs,\n            channels: new Map(),\n            details: new Map(),\n            disposers: new Map(),\n            down: false,\n            seen: false,\n          };\n        },\n      );\n      // A local route that stops hands its endpoint to the remote route it\n      // shadowed, and this is where that transition happens. Whether the\n      // local route is still there at all is the capability registry's\n      // answer now that the direct source unregisters at stop, so this\n      // plugin no longer tracks the lifecycle itself. Listening from\n      // apply, not start, so no route can stop unseen.\n      const off = [\n        ctx.on(\"route:stopped\", ({ details }) => {\n          for (const remote of remotes) lift(ctx, remote, details.routeId);\n        }),\n      ];\n      runtimes.set(ctx, { remotes, off });\n      if (!ctx.getStore(REMOTE_ROUTES)) {\n        ctx.setStore(REMOTE_ROUTES, new Map<string, RemoteRoute>());\n      }\n    },\n\n    async start(ctx: CraftContext) {\n      const runtime = runtimes.get(ctx);\n      if (!runtime) return;\n      await Promise.all(runtime.remotes.map((remote) => refresh(ctx, remote)));\n      for (const remote of runtime.remotes) {\n        if (remote.refreshMs === undefined) continue;\n        const timer = setInterval(() => {\n          void refresh(ctx, remote);\n        }, remote.refreshMs);\n        timer.unref?.();\n        remote.timer = timer;\n      }\n    },\n\n    async teardown(ctx: CraftContext) {\n      const runtime = runtimes.get(ctx);\n      if (!runtime) return;\n      runtimes.delete(ctx);\n      for (const off of runtime.off) off();\n      for (const remote of runtime.remotes) {\n        if (remote.timer !== undefined) clearInterval(remote.timer);\n        delete remote.timer;\n        // A refresh in flight would otherwise re-install what is removed\n        // below on a context that is going away.\n        await remote.inflight?.catch(() => undefined);\n        for (const endpoint of [...remote.channels.keys()]) {\n          release(ctx, remote, endpoint);\n        }\n      }\n    },\n  };\n}\n\n/**\n * Re-read one remote's inventory and reconcile the local endpoints.\n *\n * Serialised per remote: the interval can fire while a forced refresh is\n * still running, and two reconciliations interleaving would install and\n * release the same endpoints against each other. A caller that finds one\n * in flight joins it, which is also the right answer for a dispatch that\n * met a 404 while the interval was already asking.\n */\nfunction refresh(ctx: CraftContext, remote: RemoteRuntime): Promise<void> {\n  if (remote.inflight !== undefined) return remote.inflight;\n  remote.inflight = reconcile(ctx, remote).finally(() => {\n    delete remote.inflight;\n  });\n  return remote.inflight;\n}\n\nasync function reconcile(\n  ctx: CraftContext,\n  remote: RemoteRuntime,\n): Promise<void> {\n  const { name, client } = remote;\n  let details: OpsRouteDetail[];\n  try {\n    const summaries = await client.listRoutes({ dispatchable: true });\n    details = await Promise.all(\n      summaries.map((summary) => client.describeRoute(summary.id)),\n    );\n  } catch (error: unknown) {\n    // The last inventory stays: a remote that blinks must not take every\n    // imported endpoint with it, and a dispatch against a route that is\n    // truly gone finds out at the door and forces the next refresh.\n    const log = remote.down ? ctx.logger.debug : ctx.logger.warn;\n    log.call(\n      ctx.logger,\n      { remote: name, url: remote.definition.url, err: error },\n      `Remote \"${name}\" inventory could not be read; keeping the last inventory (${String(remote.channels.size)} routes)`,\n    );\n    remote.down = true;\n    remote.report({\n      status: \"down\",\n      details: { routes: remote.channels.size },\n    });\n    return;\n  }\n\n  const wanted = new Map<string, OpsRouteDetail>();\n  for (const detail of details) {\n    wanted.set(qualified(name, detail.id), detail);\n    if (name === DEFAULT_REMOTE) wanted.set(detail.id, detail);\n  }\n  for (const endpoint of [...remote.channels.keys()]) {\n    if (!wanted.has(endpoint)) release(ctx, remote, endpoint);\n  }\n  for (const [endpoint, detail] of wanted) {\n    install(ctx, remote, endpoint, detail);\n  }\n\n  const log = remote.seen ? ctx.logger.debug : ctx.logger.info;\n  log.call(\n    ctx.logger,\n    { remote: name, url: remote.definition.url, routes: details.length },\n    `Remote \"${name}\" inventory read: ${String(details.length)} dispatchable routes`,\n  );\n  remote.seen = true;\n  remote.down = false;\n  remote.report({ status: \"up\", details: { routes: details.length } });\n}\n\n/**\n * Register one remote route under one local endpoint, or find out why not.\n *\n * Local wins. A capability the registry holds without a `remote` is a\n * local route, and an endpoint declared internal is one too; either\n * shadows the remote route. The remote's channel is still installed\n * around the local one so every call through the shadow says so, and the\n * route stays reachable under its qualified name, which this function is\n * also called for. A stopped local route leaves no capability behind, so\n * an inventory arriving after the stop finds nothing to shadow and the\n * remote route simply takes the endpoint.\n */\nfunction install(\n  ctx: CraftContext,\n  remote: RemoteRuntime,\n  endpoint: string,\n  detail: OpsRouteDetail,\n): void {\n  const { name } = remote;\n  const registry = ctx.getStore(CAPABILITY_REGISTRY);\n  const existing = registry?.get(endpoint);\n  const routes = ctx.getStore(REMOTE_ROUTES)!;\n  remote.details.set(endpoint, detail);\n\n  if (\n    isInternalEndpoint(ctx, endpoint) ||\n    (existing !== undefined && existing.remote === undefined)\n  ) {\n    ctx.logger.warn(\n      { endpoint, remote: name, remoteRouteId: detail.id },\n      endpoint === qualified(name, detail.id)\n        ? `Local route \"${endpoint}\" shadows route \"${detail.id}\" of remote \"${name}\", which is unreachable until the local route is renamed`\n        : `Local route \"${endpoint}\" shadows route \"${detail.id}\" of remote \"${name}\"; the local route answers direct(\"${endpoint}\") and the remote route stays reachable as \"${qualified(name, detail.id)}\"`,\n    );\n    routes.delete(endpoint);\n    if (!remote.channels.has(endpoint)) {\n      const store = directStore(ctx);\n      const key = sanitizeEndpoint(endpoint);\n      const local = store.get(key);\n      // No channel means an internal route that never subscribed, or a\n      // route whose channel comes later; there is nothing to warn through.\n      if (local === undefined) return;\n      const channel = new RemoteDirectChannel(\n        target(ctx, remote, endpoint, detail.id),\n        local,\n      );\n      store.set(key, channel);\n      remote.channels.set(endpoint, channel);\n    }\n    return;\n  }\n\n  if (\n    existing !== undefined &&\n    existing.remote !== undefined &&\n    existing.remote !== name\n  ) {\n    ctx.logger.error(\n      {\n        endpoint,\n        remote: name,\n        remoteRouteId: detail.id,\n        heldBy: existing.remote,\n      },\n      `Route \"${detail.id}\" of remote \"${name}\" would be advertised as \"${endpoint}\", which remote \"${existing.remote}\" already holds; skipping it. Rename the route on one of the remotes`,\n    );\n    return;\n  }\n\n  advertise(ctx, remote, endpoint, detail);\n\n  if (!remote.channels.has(endpoint)) {\n    const store = directStore(ctx);\n    // Whatever the store holds here is a placeholder an enricher created\n    // on demand before this inventory landed (a subscribed local route\n    // would have registered a capability and returned above), so replacing\n    // it is what makes that enricher's next fetch reach the remote.\n    const channel = new RemoteDirectChannel(\n      target(ctx, remote, endpoint, detail.id),\n    );\n    store.set(sanitizeEndpoint(endpoint), channel);\n    remote.channels.set(endpoint, channel);\n  }\n}\n\n/** Register the remote route as the capability behind a local endpoint. */\nfunction advertise(\n  ctx: CraftContext,\n  remote: RemoteRuntime,\n  endpoint: string,\n  detail: OpsRouteDetail,\n): void {\n  const { name } = remote;\n  const capability: Capability = { endpoint, remote: name };\n  if (detail.title !== undefined) capability.title = detail.title;\n  if (detail.description !== undefined) {\n    capability.description = detail.description;\n  }\n  if (detail.tags !== undefined && detail.tags.length > 0) {\n    capability.tags = [...detail.tags];\n  }\n  if (detail.input?.body !== undefined) {\n    capability.input = {\n      body: standardSchemaFromJsonSchema(detail.input.body),\n    };\n  }\n  if (detail.output?.body !== undefined) {\n    capability.output = {\n      body: standardSchemaFromJsonSchema(detail.output.body),\n    };\n  }\n  // The disposer is kept rather than discarded so this plugin removes its\n  // own entries the way every other writer does: by identity, through the\n  // function that wrote them. Comparing `remote` on the way out is weaker,\n  // because two successive installs by one remote compare equal, so a\n  // stale release could take an entry a later refresh had installed.\n  remote.disposers.set(endpoint, registerCapability(ctx, capability));\n  const routes = ctx.getStore(REMOTE_ROUTES)!;\n  routes.set(endpoint, { remote: name, id: detail.id, endpoint, detail });\n}\n\n/**\n * Hand a shadowed endpoint to the remote route once the local route that\n * shadowed it has stopped.\n *\n * A shadow is a channel this remote installed for an endpoint that is not\n * listed as one of its routes. The transition rewrites both halves at\n * once: the channel stops answering from the local route, and the\n * capability registry says the endpoint is the remote's, so the listing\n * and an agent's tool policy see a remote-backed endpoint and never a\n * local one that quietly dispatches elsewhere. An internal endpoint is\n * left alone: the app declared it is not a capability, and a remote route\n * behind it would open the door the declaration closed.\n */\nfunction lift(\n  ctx: CraftContext,\n  remote: RemoteRuntime,\n  endpoint: string,\n): void {\n  const channel = remote.channels.get(endpoint);\n  const detail = remote.details.get(endpoint);\n  const routes = ctx.getStore(REMOTE_ROUTES);\n  if (\n    channel === undefined ||\n    detail === undefined ||\n    routes?.has(endpoint) === true ||\n    isInternalEndpoint(ctx, endpoint)\n  ) {\n    return;\n  }\n  channel.local = undefined;\n  advertise(ctx, remote, endpoint, detail);\n  ctx.logger.info(\n    { endpoint, remote: remote.name, remoteRouteId: detail.id },\n    `The local route on \"${endpoint}\" has stopped; the route \"${detail.id}\" of remote \"${remote.name}\" answers it from now on`,\n  );\n}\n\n/** Remove one endpoint this remote installed, restoring a shadowed local channel. */\nfunction release(\n  ctx: CraftContext,\n  remote: RemoteRuntime,\n  endpoint: string,\n): void {\n  const channel = remote.channels.get(endpoint);\n  remote.channels.delete(endpoint);\n  remote.details.delete(endpoint);\n  remote.disposers.get(endpoint)?.();\n  remote.disposers.delete(endpoint);\n  const routes = ctx.getStore(REMOTE_ROUTES);\n  if (routes?.get(endpoint)?.remote === remote.name) routes.delete(endpoint);\n  const store = ctx.getStore(ADAPTER_DIRECT_STORE);\n  const key = sanitizeEndpoint(endpoint);\n  if (\n    store === undefined ||\n    channel === undefined ||\n    store.get(key) !== channel\n  ) {\n    return;\n  }\n  if (channel.local !== undefined) {\n    store.set(key, channel.local);\n  } else {\n    store.delete(key);\n  }\n}\n\nfunction directStore(ctx: CraftContext): Map<string, DirectChannel<Exchange>> {\n  let store = ctx.getStore(ADAPTER_DIRECT_STORE);\n  if (!store) {\n    store = new Map<string, DirectChannel<Exchange>>();\n    ctx.setStore(ADAPTER_DIRECT_STORE, store);\n  }\n  return store;\n}\n\nfunction target(\n  ctx: CraftContext,\n  remote: RemoteRuntime,\n  endpoint: string,\n  id: string,\n): RemoteTarget {\n  return {\n    ctx,\n    remote: remote.name,\n    id,\n    endpoint,\n    client: remote.client,\n    describe: () => remote.definition.url,\n    onMissing: () => refresh(ctx, remote),\n  };\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * Wrap a JSON Schema the remote rendered as a Standard Schema.\n *\n * The result is the discovery bundle a local route would have declared,\n * so nothing downstream learns that the schema came from a remote: the\n * ops listing renders it back through the same `~standard.jsonSchema`\n * arms it reads for a Zod schema, and the agent tool bridge hands it to\n * the model provider the way it hands an MCP tool's.\n *\n * Validation is a pass-through on purpose. The remote validates at its\n * own door against the live schema, and a second validation here against\n * a rendering would add latency and, the day the two disagree, refuse\n * what the remote accepts.\n */\nexport function standardSchemaFromJsonSchema(\n  schema: unknown,\n): StandardSchemaV1<unknown, unknown> {\n  return {\n    \"~standard\": {\n      version: 1,\n      vendor: \"routecraft\",\n      validate(value) {\n        return { value };\n      },\n      jsonSchema: {\n        input: () => schema,\n        output: () => schema,\n      },\n    } as StandardSchemaV1<unknown, unknown>[\"~standard\"],\n  };\n}\n","import { registerConfigApplier } from \"../../config-applier\";\nimport { remotesPlugin } from \"./plugin\";\nimport type { RemotesConfig } from \"./types\";\n\ndeclare module \"@routecraft/routecraft\" {\n  interface CraftConfig {\n    /** Other running instances whose dispatchable routes become direct endpoints here. */\n    remotes?: RemotesConfig;\n  }\n}\n\n/**\n * Register the `remotes` config key so `defineConfig({ remotes: {...} })`\n * is equivalent to `defineConfig({ plugins: [remotesPlugin({...})] })`.\n * Loaded as a side-effect import from `packages/routecraft/src/index.ts`,\n * after the `ops` key, so an imported route's indicator has a ledger to\n * report into when the app carries an ops surface.\n */\nregisterConfigApplier(\"remotes\", (options) => remotesPlugin(options));\n","import type { Duration } from \"../../shared/duration.ts\";\n/**\n * Cron expression with autocomplete for nicknames and common patterns.\n * Accepts any valid cron string (5-field or 6-field) as well.\n */\nexport type CronExpression =\n  | \"@yearly\" // Once a year (Jan 1 at midnight)\n  | \"@annually\" // Once a year (Jan 1 at midnight)\n  | \"@monthly\" // Once a month (1st at midnight)\n  | \"@weekly\" // Once a week (Sunday at midnight)\n  | \"@daily\" // Once a day (at midnight)\n  | \"@midnight\" // Once a day (at midnight)\n  | \"@hourly\" // Once an hour (at minute 0)\n  | \"* * * * *\" // Every minute\n  | \"*/5 * * * *\" // Every 5 minutes\n  | \"*/15 * * * *\" // Every 15 minutes\n  | \"*/30 * * * *\" // Every 30 minutes\n  | \"0 * * * *\" // Every hour (at minute 0)\n  | \"0 0 * * *\" // Daily at midnight\n  | \"0 0 * * 0\" // Weekly on Sunday at midnight\n  | \"0 0 1 * *\" // Monthly on the 1st at midnight\n  | \"0 0 1 1 *\" // Yearly on Jan 1 at midnight\n  | (string & {}); // Any valid 5-field or 6-field cron expression\n\n/**\n * Configuration options for the cron source adapter.\n */\nexport interface CronOptions {\n  /**\n   * IANA timezone for the cron schedule (e.g., \"America/New_York\")\n   * @default undefined (system timezone)\n   */\n  timezone?: string;\n\n  /**\n   * Maximum number of times the cron job will fire before stopping.\n   * Delegated to croner's `maxRuns` option.\n   * @default Infinity\n   */\n  maxFires?: number;\n\n  /**\n   * Upper bound on a random delay added to each trigger, to prevent\n   * synchronized spikes in distributed deployments. Each delay is drawn\n   * uniformly from `[0, maxJitter)`.\n   * Recommended: \"1s\" to \"30s\" for production workloads.\n   * Can be set globally via `ADAPTER_CRON_OPTIONS` in the context store.\n   * @default 0\n   */\n  maxJitter?: Duration;\n\n  /**\n   * Human-readable name for the cron job, used in headers for observability\n   * @default undefined\n   */\n  name?: string;\n\n  /**\n   * If true, prevents the job from running if the previous execution\n   * (including any jitter delay) is still in progress. Delegated to\n   * croner's `protect` option.\n   * @default true\n   */\n  protect?: boolean;\n\n  /**\n   * Date or ISO 8601 string at which the cron job should start running.\n   * Ticks before this date are skipped.\n   * @default undefined (starts immediately)\n   */\n  startAt?: Date | string;\n\n  /**\n   * Date or ISO 8601 string at which the cron job should stop running.\n   * The job is permanently stopped once this date is reached.\n   * @default undefined (runs indefinitely)\n   */\n  stopAt?: Date | string;\n}\n\n/**\n * Header keys the cron source sets on every emitted exchange. Keys live\n * under the reserved `routecraft.cron.*` namespace; the value types are\n * merged into `RoutecraftHeaders` below.\n */\nexport const CronHeaders = {\n  /** The cron expression that triggered this exchange */\n  EXPRESSION: \"routecraft.cron.expression\",\n  /** The timestamp when the cron job fired, in ISO 8601 format */\n  FIRED_TIME: \"routecraft.cron.firedTime\",\n  /** The next timestamp when the cron job will fire, in ISO 8601 format */\n  NEXT_RUN: \"routecraft.cron.nextRun\",\n  /** The number of times the cron job has fired */\n  COUNTER: \"routecraft.cron.counter\",\n  /** The IANA timezone for the cron schedule */\n  TIMEZONE: \"routecraft.cron.timezone\",\n  /** The human-readable name for the cron job */\n  NAME: \"routecraft.cron.name\",\n} as const satisfies Record<string, `routecraft.cron.${string}`>;\n\ndeclare module \"@routecraft/routecraft\" {\n  interface RoutecraftHeaders {\n    /** The cron expression that triggered this exchange */\n    [CronHeaders.EXPRESSION]?: string;\n    /** The timestamp when the cron job fired, in ISO 8601 format */\n    [CronHeaders.FIRED_TIME]?: string;\n    /** The next timestamp when the cron job will fire, in ISO 8601 format */\n    [CronHeaders.NEXT_RUN]?: string;\n    /** The number of times the cron job has fired */\n    [CronHeaders.COUNTER]?: number;\n    /** The IANA timezone for the cron schedule */\n    [CronHeaders.TIMEZONE]?: string;\n    /** The human-readable name for the cron job */\n    [CronHeaders.NAME]?: string;\n  }\n}\n","import type { Cron as CronType } from \"croner\";\nimport type { ExchangeHeaders } from \"../../exchange\";\nimport { CronHeaders } from \"./types\";\nimport type { Source, Subscription } from \"../../operations/from\";\nimport type { CraftContext, MergedOptions } from \"../../context\";\nimport { loadOptionalPeer } from \"../shared/optional-peer\";\nimport { parseDuration } from \"../../shared/duration.ts\";\nimport type { CronExpression, CronOptions } from \"./types\";\n\n/**\n * Store key for merged cron adapter options.\n * Set context-level defaults (e.g., maxJitter) once and share across all\n * cron sources in the same context.\n * @internal\n */\nexport const ADAPTER_CRON_OPTIONS = Symbol.for(\n  \"routecraft.adapter.cron.options\",\n);\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [ADAPTER_CRON_OPTIONS]: Partial<CronOptions>;\n  }\n}\n\n/**\n * Source adapter that fires on a cron schedule using the `croner` library.\n *\n * Body is always `undefined`; scheduling metadata is provided via\n * `routecraft.cron.*` exchange headers (expression, firedTime, nextRun,\n * counter, timezone, name).\n *\n * Supports standard 5-field cron (minute granularity), extended 6-field\n * (second granularity), and nicknames (`@daily`, `@hourly`, etc.).\n *\n * Options can be set per-adapter or globally via `CraftContext` store\n * using the `ADAPTER_CRON_OPTIONS` key. Per-adapter options take precedence.\n */\nexport class CronSourceAdapter\n  implements Source<undefined>, MergedOptions<CronOptions>\n{\n  readonly adapterId = \"routecraft.adapter.cron\";\n  public options: Partial<CronOptions>;\n\n  /**\n   * Loader for the `croner` driver. Exposed as a static so tests can\n   * substitute a synchronous implementation and avoid the dynamic-import\n   * + fake-timer interaction (Node's dynamic import internals lean on\n   * `setImmediate`, which `vi.useFakeTimers()` mocks).\n   * @internal\n   */\n  static loadDriver: () => Promise<typeof CronType> = () =>\n    loadOptionalPeer(() => import(\"croner\"), {\n      consumer: \"cron adapter\",\n      packageName: \"croner\",\n    }).then((m) => m.Cron);\n\n  constructor(\n    private readonly expression: CronExpression,\n    options?: CronOptions,\n  ) {\n    this.options = options ?? {};\n  }\n\n  /**\n   * Merge adapter-level options with context-level options.\n   * Per-adapter values take precedence over context-level defaults.\n   *\n   * @param context - The CraftContext\n   * @returns Merged options\n   */\n  mergedOptions(context: CraftContext): CronOptions {\n    const contextOptions =\n      (context.getStore(ADAPTER_CRON_OPTIONS) as\n        Partial<CronOptions> | undefined) ?? {};\n    return {\n      ...contextOptions,\n      ...this.options,\n    };\n  }\n\n  /**\n   * Subscribe to cron-scheduled triggers.\n   *\n   * Creates a `croner` job from the configured expression and invokes\n   * the handler on each scheduled fire. The returned promise resolves\n   * when the job is stopped (via abort, maxFires, or handler error),\n   * and rejects if croner is missing or the expression is invalid.\n   *\n   * @param sub - Subscription handle. `sub.context` provides logging and\n   *   merged options; `sub.emit` is called with `undefined` body and cron\n   *   headers on each fire; `sub.signal` stops the cron job. `sub.ready()`\n   *   fires once the job is scheduled, after the lazy `croner` import\n   *   resolves on first use, so on a cold start it lands one or more\n   *   microtasks after `subscribe()` returns rather than synchronously.\n   *   Consumers of `route:started` see the same delay.\n   */\n  subscribe(sub: Subscription<undefined>): Promise<void> {\n    const context = sub.context;\n    const {\n      timezone,\n      maxFires = Infinity,\n      maxJitter = 0,\n      name,\n      protect = true,\n      startAt,\n      stopAt,\n    } = this.mergedOptions(context);\n\n    if (Number.isNaN(maxFires) || maxFires < 0) {\n      throw new Error(\"cron maxFires must be a non-negative number\");\n    }\n    const maxJitterMs = parseDuration(maxJitter, \"cron({ maxJitter })\", 0);\n\n    // Resolve immediately if already aborted (avoids hanging when\n    // startAt/stopAt postpone the first tick indefinitely).\n    if (sub.signal.aborted) {\n      return Promise.resolve();\n    }\n\n    return new Promise<void>((resolve, reject) => {\n      let counter = 0;\n      let settled = false;\n      let job: CronType | null = null;\n\n      const finish = (fn: () => void) => {\n        if (settled) return;\n        settled = true;\n        sub.signal.removeEventListener(\"abort\", onAbort);\n        job?.stop();\n        fn();\n      };\n      const settle = () => finish(resolve);\n      const fail = (err: unknown) => finish(() => reject(err));\n\n      // Register the abort listener synchronously so an abort that arrives\n      // before the dynamic croner import resolves still tears the source\n      // down; finish() removes it so a non-abort settle does not leak the\n      // listener on the (long-lived) route signal.\n      const onAbort = () => settle();\n      sub.signal.addEventListener(\"abort\", onAbort, { once: true });\n\n      // croner is declared as an optional peer dep; load it lazily so\n      // routes that never use cron() do not require the package.\n      void (async () => {\n        let Cron: typeof CronType;\n        try {\n          Cron = await CronSourceAdapter.loadDriver();\n        } catch (err) {\n          fail(err);\n          return;\n        }\n        if (settled) return;\n\n        // Wrap synchronous setup (`new Cron`, `onReady`) so a throw from\n        // croner (e.g. invalid expression) rejects the outer promise\n        // instead of leaking as an unhandled rejection.\n        try {\n          job = new Cron(\n            this.expression,\n            {\n              ...(timezone ? { timezone } : {}),\n              protect,\n              ...(maxFires !== Infinity ? { maxRuns: maxFires } : {}),\n              ...(startAt ? { startAt } : {}),\n              ...(stopAt ? { stopAt } : {}),\n              paused: false,\n            },\n            async () => {\n              if (settled || sub.signal.aborted) {\n                settle();\n                return;\n              }\n\n              counter++;\n              const firedTime = new Date();\n\n              // Apply jitter delay before firing (blocking, not fire-and-forget)\n              if (maxJitterMs > 0) {\n                // Uniform in [0, maxJitter): the option is an upper bound,\n                // which is what its name promises.\n                const jitter = Math.floor(Math.random() * maxJitterMs);\n                await new Promise((r) => setTimeout(r, jitter));\n                if (sub.signal.aborted) {\n                  settle();\n                  return;\n                }\n              }\n\n              const nextDate = job!.nextRun();\n              const headers: ExchangeHeaders = {\n                [CronHeaders.EXPRESSION]: this.expression,\n                [CronHeaders.FIRED_TIME]: firedTime.toISOString(),\n                [CronHeaders.COUNTER]: counter,\n                ...(nextDate\n                  ? { [CronHeaders.NEXT_RUN]: nextDate.toISOString() }\n                  : {}),\n                ...(timezone ? { [CronHeaders.TIMEZONE]: timezone } : {}),\n                ...(name ? { [CronHeaders.NAME]: name } : {}),\n              };\n\n              try {\n                await sub.emit({ message: undefined, headers });\n              } catch {\n                // Exchange error already logged by the route pipeline.\n                // Cron jobs are long-running; continue to the next scheduled fire.\n              }\n\n              // Settle when croner has exhausted maxRuns\n              if (job!.runsLeft() === 0) {\n                settle();\n              }\n            },\n          );\n\n          sub.ready();\n        } catch (err) {\n          fail(err);\n        }\n      })();\n    });\n  }\n}\n","import { registerConfigApplier } from \"../../config-applier.ts\";\nimport type { StoreRegistry } from \"../../context.ts\";\nimport { ADAPTER_CRON_OPTIONS } from \"./source.ts\";\nimport type { CronOptions } from \"./types.ts\";\n\ndeclare module \"@routecraft/routecraft\" {\n  interface CraftConfig {\n    /** Default options applied to all cron() sources in this context */\n    cron?: Partial<CronOptions>;\n  }\n}\n\n/**\n * Register the `cron` config key so `defineConfig({ cron: {...} })` seeds\n * the context store with default cron options. Loaded as a side-effect\n * import from `packages/routecraft/src/index.ts` so users do not have to\n * wire it manually. Keeps the core context free of cron adapter knowledge.\n */\nregisterConfigApplier(\"cron\", (options) => ({\n  apply(ctx) {\n    ctx.setStore(ADAPTER_CRON_OPTIONS as keyof StoreRegistry, options);\n  },\n}));\n","import { registerConfigApplier } from \"../../config-applier.ts\";\nimport type { StoreRegistry } from \"../../context.ts\";\nimport { ADAPTER_DIRECT_OPTIONS } from \"./shared.ts\";\nimport type { DirectBaseOptions } from \"./types.ts\";\n\ndeclare module \"@routecraft/routecraft\" {\n  interface CraftConfig {\n    /** Default channel implementation for all direct() adapters (e.g. swap in-memory for Kafka) */\n    direct?: Pick<DirectBaseOptions, \"channelType\">;\n  }\n}\n\n/**\n * Register the `direct` config key so `defineConfig({ direct: {...} })`\n * seeds the context store with channel defaults. Loaded as a side-effect\n * import from `packages/routecraft/src/index.ts` so users do not have to\n * wire it manually. Keeps the core context free of direct adapter knowledge.\n */\nregisterConfigApplier(\"direct\", (options) => ({\n  apply(ctx) {\n    ctx.setStore(ADAPTER_DIRECT_OPTIONS as keyof StoreRegistry, options);\n  },\n}));\n","/**\n * Mail client manager with per-account IMAP connection pools and SMTP transporter reuse.\n *\n * Created by the ContextBuilder when `mail` config is present.\n * Adapters access it via the context store to acquire/release connections.\n */\n\nimport { rcError } from \"../../error.ts\";\nimport type {\n  MailContextConfig,\n  MailServerOptions,\n  MailClientOptions,\n  MailAuth,\n} from \"./types.ts\";\nimport { buildImapConfig } from \"./shared.ts\";\nimport { loadOptionalPeer } from \"../shared/optional-peer.ts\";\n\n// ---------------------------------------------------------------------------\n// ImapPool: fixed-size, mailbox-aware IMAP connection pool for one account\n// ---------------------------------------------------------------------------\n\nfunction drainedError(): Error {\n  return new Error(\"IMAP pool drained during shutdown\");\n}\n\n/**\n * Fixed-size IMAP connection pool for a single account.\n * Tracks which mailbox each connection has open to avoid unnecessary switches.\n * @internal\n */\nexport class ImapPool {\n  private readonly entries: Array<{\n    /**\n     * Null while the slot is reserved and its connect is still in flight.\n     * The reservation is what bounds the pool, so it has to exist before\n     * there is a client to put in it.\n     */\n    client: InstanceType<typeof import(\"imapflow\").ImapFlow> | null;\n    inUse: boolean;\n    currentMailbox: string | null;\n  }> = [];\n  private readonly waitQueue: Array<{\n    resolve: (client: InstanceType<typeof import(\"imapflow\").ImapFlow>) => void;\n    reject: (error: Error) => void;\n  }> = [];\n  private drained = false;\n  private readonly poolSize: number;\n  private readonly imapConfig: {\n    host?: string;\n    port?: number;\n    secure?: boolean;\n    auth?: MailAuth;\n  };\n\n  constructor(imapConfig: {\n    host?: string;\n    port?: number;\n    secure?: boolean;\n    auth?: MailAuth;\n    poolSize?: number;\n  }) {\n    this.imapConfig = imapConfig;\n    this.poolSize = imapConfig.poolSize ?? 3;\n  }\n\n  /**\n   * Acquire an IMAP client from the pool.\n   * Prefers connections that already have the target mailbox open.\n   */\n  async acquire(\n    mailbox?: string,\n  ): Promise<InstanceType<typeof import(\"imapflow\").ImapFlow>> {\n    // A drained pool never serves again, and every path below would strand\n    // the caller: creating opens a fresh connection mid-shutdown, and\n    // queueing waits on a queue drain() already emptied and will never\n    // revisit, so that promise would never settle at all.\n    if (this.drained) throw drainedError();\n\n    // 1. Prefer idle connection with same mailbox already open\n    if (mailbox) {\n      const sameMailbox = this.entries.find(\n        (c) => c.client !== null && !c.inUse && c.currentMailbox === mailbox,\n      );\n      if (sameMailbox?.client) {\n        sameMailbox.inUse = true;\n        if (sameMailbox.client.usable) return sameMailbox.client;\n        // Dead connection, remove and fall through\n        this.entries.splice(this.entries.indexOf(sameMailbox), 1);\n      }\n    }\n\n    // 2. Any idle connection\n    const idle = this.entries.find((c) => c.client !== null && !c.inUse);\n    if (idle?.client) {\n      idle.inUse = true;\n      if (idle.client.usable) return idle.client;\n      // Dead connection, remove and fall through\n      this.entries.splice(this.entries.indexOf(idle), 1);\n    }\n\n    // 3. Create new if under limit (reserve slot before async connect)\n    if (this.entries.length < this.poolSize) {\n      const placeholder = {\n        client: null as InstanceType<typeof import(\"imapflow\").ImapFlow> | null,\n        inUse: true,\n        currentMailbox: null,\n      };\n      this.entries.push(placeholder);\n      // Both the drained branch and the catch release the reservation, and\n      // the drained branch reaches the catch by throwing. Removal has to be\n      // idempotent: a bare splice(indexOf(x), 1) on an already-removed entry\n      // splices at -1, which silently drops somebody else's slot and leaves\n      // that connection with nothing to close it.\n      const releaseReservation = () => {\n        const index = this.entries.indexOf(placeholder);\n        if (index >= 0) this.entries.splice(index, 1);\n      };\n      try {\n        const client = await this.createClient();\n        // The pool can be drained while this connect is in flight, which is\n        // the ordinary shape of a shutdown that begins during startup. Drain\n        // has already walked the entries by then, so this connection would\n        // otherwise stay open with nothing left holding a reference to it.\n        if (this.drained) {\n          releaseReservation();\n          await client.logout().catch(() => {});\n          throw drainedError();\n        }\n        placeholder.client = client;\n        return client;\n      } catch (error) {\n        releaseReservation();\n        throw error;\n      }\n    }\n\n    // 4. Queue and wait for release\n    return new Promise((resolve, reject) =>\n      this.waitQueue.push({ resolve, reject }),\n    );\n  }\n\n  /**\n   * Release an IMAP client back to the pool.\n   */\n  release(client: InstanceType<typeof import(\"imapflow\").ImapFlow>): void {\n    const entry = this.entries.find((c) => c.client === client);\n    if (!entry) return;\n\n    // Remove dead connections so their slot can be reused\n    if (!client.usable) {\n      this.entries.splice(this.entries.indexOf(entry), 1);\n      return;\n    }\n\n    // If someone is waiting, hand directly\n    const waiter = this.waitQueue.shift();\n    if (waiter) {\n      waiter.resolve(client);\n      return;\n    }\n\n    entry.inUse = false;\n  }\n\n  /**\n   * Update the tracked mailbox for a client after mailboxOpen().\n   */\n  trackMailbox(\n    client: InstanceType<typeof import(\"imapflow\").ImapFlow>,\n    mailbox: string,\n  ): void {\n    const entry = this.entries.find((c) => c.client === client);\n    if (entry) entry.currentMailbox = mailbox;\n  }\n\n  /**\n   * Drain all connections. Called during context teardown.\n   */\n  async drain(): Promise<void> {\n    this.drained = true;\n    const drainError = drainedError();\n    for (const waiter of this.waitQueue) {\n      waiter.reject(drainError);\n    }\n    this.waitQueue.length = 0;\n    for (const entry of this.entries) {\n      // A slot whose connect has not resolved holds no client yet. That\n      // acquire logs its own connection out when it lands, so skipping it\n      // here leaves nothing open.\n      if (entry.client) await entry.client.logout().catch(() => {});\n    }\n    this.entries.length = 0;\n  }\n\n  private async createClient(): Promise<\n    InstanceType<typeof import(\"imapflow\").ImapFlow>\n  > {\n    const config = buildImapConfig(this.imapConfig);\n    const { ImapFlow } = await loadOptionalPeer(() => import(\"imapflow\"), {\n      consumer: \"mail adapter\",\n      packageName: \"imapflow\",\n    });\n    const client = new ImapFlow(config);\n    await client.connect();\n    return client;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// MailClientManager: per-account pools + SMTP transporters\n// ---------------------------------------------------------------------------\n\n/**\n * Manages per-account IMAP connection pools and SMTP transporters.\n * Created by the ContextBuilder when `mail` config is present.\n */\nexport class MailClientManager {\n  private readonly pools = new Map<string, ImapPool>();\n  private readonly transports = new Map<\n    string,\n    ReturnType<typeof import(\"nodemailer\").createTransport>\n  >();\n  readonly config: MailContextConfig;\n  readonly defaultAccount: string;\n\n  constructor(config: MailContextConfig) {\n    this.config = config;\n\n    // Determine default account: key named \"default\", or first defined\n    const accounts = config.accounts ?? {};\n    this.defaultAccount =\n      \"default\" in accounts ? \"default\" : (Object.keys(accounts)[0] ?? \"\");\n  }\n\n  /**\n   * Acquire an IMAP client for the given account.\n   * Creates the account pool lazily on first access.\n   */\n  async acquireImap(\n    account?: string,\n    mailbox?: string,\n  ): Promise<InstanceType<typeof import(\"imapflow\").ImapFlow>> {\n    const name = account ?? this.defaultAccount;\n    let pool = this.pools.get(name);\n    if (!pool) {\n      const accountConfig = this.config.accounts?.[name];\n      if (!accountConfig?.imap) {\n        throw rcError(\"RC5003\", undefined, {\n          message: `Mail account '${name}' has no IMAP configuration.`,\n        });\n      }\n      pool = new ImapPool(accountConfig.imap);\n      this.pools.set(name, pool);\n    }\n    return pool.acquire(mailbox);\n  }\n\n  /**\n   * Release an IMAP client back to its account pool.\n   */\n  releaseImap(\n    account: string | undefined,\n    client: InstanceType<typeof import(\"imapflow\").ImapFlow>,\n  ): void {\n    const name = account ?? this.defaultAccount;\n    this.pools.get(name)?.release(client);\n  }\n\n  /**\n   * Update the tracked mailbox for a pooled client.\n   */\n  trackMailbox(\n    account: string | undefined,\n    client: InstanceType<typeof import(\"imapflow\").ImapFlow>,\n    mailbox: string,\n  ): void {\n    const name = account ?? this.defaultAccount;\n    this.pools.get(name)?.trackMailbox(client, mailbox);\n  }\n\n  /**\n   * Get the SMTP transporter for the given account (lazy init).\n   */\n  async getSmtp(\n    account?: string,\n  ): Promise<ReturnType<typeof import(\"nodemailer\").createTransport>> {\n    const name = account ?? this.defaultAccount;\n    const existing = this.transports.get(name);\n    if (existing) return existing;\n\n    const accountConfig = this.config.accounts?.[name];\n    if (!accountConfig?.smtp) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `Mail account '${name}' has no SMTP configuration.`,\n      });\n    }\n\n    const smtp = accountConfig.smtp;\n    if (!smtp.host) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `Mail account '${name}' SMTP host is required.`,\n      });\n    }\n    if (!smtp.auth) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `Mail account '${name}' SMTP auth is required.`,\n      });\n    }\n\n    const nodemailer = await loadOptionalPeer(() => import(\"nodemailer\"), {\n      consumer: \"mail adapter\",\n      packageName: \"nodemailer\",\n    });\n    const transport = nodemailer.createTransport({\n      host: smtp.host,\n      port: smtp.port ?? 465,\n      secure: smtp.secure ?? true,\n      auth: smtp.auth,\n    });\n    this.transports.set(name, transport);\n    return transport;\n  }\n\n  /**\n   * Resolve IMAP options: adapter overrides > account config > shared defaults > built-in defaults.\n   */\n  resolveImapOptions(\n    account?: string,\n    overrides: Partial<MailServerOptions> = {},\n  ): MailServerOptions {\n    const acct = this.config.accounts?.[account ?? this.defaultAccount];\n    const result: MailServerOptions = {\n      port: overrides.port ?? acct?.imap?.port ?? 993,\n      secure: overrides.secure ?? acct?.imap?.secure ?? true,\n      folder: overrides.folder ?? this.config.folder ?? \"INBOX\",\n      markSeen: overrides.markSeen ?? this.config.markSeen ?? true,\n      unseen: overrides.unseen ?? true,\n    };\n\n    const host = overrides.host ?? acct?.imap?.host;\n    if (host !== undefined) result.host = host;\n\n    const auth = overrides.auth ?? acct?.imap?.auth;\n    if (auth !== undefined) result.auth = auth;\n\n    if (overrides.since !== undefined) result.since = overrides.since;\n    if (overrides.limit !== undefined) result.limit = overrides.limit;\n    if (overrides.pollInterval !== undefined)\n      result.pollInterval = overrides.pollInterval;\n    if (overrides.includeHeaders !== undefined)\n      result.includeHeaders = overrides.includeHeaders;\n    if (overrides.verify !== undefined) result.verify = overrides.verify;\n\n    // Pass through search filters\n    if (overrides.from !== undefined) result.from = overrides.from;\n    if (overrides.to !== undefined) result.to = overrides.to;\n    if (overrides.subject !== undefined) result.subject = overrides.subject;\n    if (overrides.body !== undefined) result.body = overrides.body;\n    if (overrides.header !== undefined) result.header = overrides.header;\n\n    // Parse-error handling (#187).\n    if (overrides.onParseError !== undefined)\n      result.onParseError = overrides.onParseError;\n\n    // Source connection-recovery tuning (#425).\n    if (overrides.reconnect !== undefined)\n      result.reconnect = overrides.reconnect;\n\n    return result;\n  }\n\n  /**\n   * Resolve SMTP options: adapter overrides > account config > shared defaults.\n   */\n  resolveSmtpOptions(\n    account?: string,\n    overrides: Partial<MailClientOptions> = {},\n  ): MailClientOptions {\n    const acct = this.config.accounts?.[account ?? this.defaultAccount];\n    const result: MailClientOptions = {\n      port: overrides.port ?? acct?.smtp?.port ?? 465,\n      secure: overrides.secure ?? acct?.smtp?.secure ?? true,\n    };\n\n    const host = overrides.host ?? acct?.smtp?.host;\n    if (host !== undefined) result.host = host;\n\n    const auth = overrides.auth ?? acct?.smtp?.auth;\n    if (auth !== undefined) result.auth = auth;\n\n    const from = overrides.from ?? acct?.smtp?.from;\n    if (from !== undefined) result.from = from;\n\n    const replyTo = overrides.replyTo ?? acct?.smtp?.replyTo;\n    if (replyTo !== undefined) result.replyTo = replyTo;\n\n    const cc = overrides.cc ?? acct?.smtp?.cc;\n    if (cc !== undefined) result.cc = cc;\n\n    const bcc = overrides.bcc ?? acct?.smtp?.bcc;\n    if (bcc !== undefined) result.bcc = bcc;\n\n    return result;\n  }\n\n  /**\n   * Drain all pools and transports. Called during context teardown.\n   */\n  async drain(): Promise<void> {\n    for (const pool of this.pools.values()) {\n      await pool.drain();\n    }\n    this.pools.clear();\n    for (const transport of this.transports.values()) {\n      transport.close();\n    }\n    this.transports.clear();\n  }\n}\n","import type { CraftContext } from \"../../context.ts\";\nimport type { Exchange, ExchangeHeaders } from \"../../exchange.ts\";\nimport { rcError } from \"../../error.ts\";\nimport { isRoutecraftError } from \"../../brand.ts\";\nimport type {\n  MailBody,\n  MailMessage,\n  MailServerOptions,\n  MailClientOptions,\n  MailSendPayload,\n  MailTargetExtractor,\n} from \"./types.ts\";\nimport type { MailClientManager } from \"./client-manager.ts\";\nimport { loadOptionalPeer } from \"../shared/optional-peer.ts\";\nimport {\n  analyzeHeaders,\n  extractAnalysisHeaders,\n  type MailSender,\n} from \"./analysis.ts\";\n\n// ---------------------------------------------------------------------------\n// Store keys\n// ---------------------------------------------------------------------------\n\n/**\n * Store key for the mail client manager.\n * Set by the ContextBuilder when `mail` config is present.\n * @internal\n */\nexport const MAIL_CLIENT_MANAGER = Symbol.for(\n  \"routecraft.adapter.mail.client-manager\",\n);\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [MAIL_CLIENT_MANAGER]: MailClientManager;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Header constants\n// ---------------------------------------------------------------------------\n\n/**\n * Header keys the mail source sets for the message envelope. Keys live\n * under the reserved `routecraft.mail.*` namespace; the value types are\n * merged into `RoutecraftHeaders` in `./types.ts`.\n */\nexport const MailHeaders = {\n  /** IMAP UID of the source message. */\n  UID: \"routecraft.mail.uid\",\n  /** IMAP folder of the source message. */\n  FOLDER: \"routecraft.mail.folder\",\n  /** `Message-ID` of the source message. */\n  MESSAGE_ID: \"routecraft.mail.messageId\",\n  /** Literal `From:` address. */\n  FROM: \"routecraft.mail.from\",\n  /** Recipient address(es) (always an array). */\n  TO: \"routecraft.mail.to\",\n  /** CC recipient address(es). */\n  CC: \"routecraft.mail.cc\",\n  /** BCC recipient address(es). */\n  BCC: \"routecraft.mail.bcc\",\n  /** Subject line. */\n  SUBJECT: \"routecraft.mail.subject\",\n  /** Date the message was sent. */\n  DATE: \"routecraft.mail.date\",\n  /** Reply-To address. */\n  REPLY_TO: \"routecraft.mail.replyTo\",\n  /** IMAP flags. */\n  FLAGS: \"routecraft.mail.flags\",\n  /** Computed effective sender (when `verify !== \"off\"`). */\n  SENDER: \"routecraft.mail.sender\",\n  /** Raw email headers (requested via `includeHeaders`). */\n  RAW_HEADERS: \"routecraft.mail.rawHeaders\",\n  /**\n   * SMTP send receipt: `Message-ID` of the SENT email. Deliberately not\n   * {@link MailHeaders.MESSAGE_ID}: the inbound message and an outbound\n   * reply are different entities, so a `.from(mail(...))....to(mail())`\n   * route keeps the source message's id intact for correlation.\n   */\n  SENT_MESSAGE_ID: \"routecraft.mail.sentMessageId\",\n  /** SMTP send receipt: accepted recipient addresses. */\n  ACCEPTED: \"routecraft.mail.accepted\",\n  /** SMTP send receipt: rejected recipient addresses. */\n  REJECTED: \"routecraft.mail.rejected\",\n  /** SMTP send receipt: raw SMTP server response string. */\n  RESPONSE: \"routecraft.mail.response\",\n} as const satisfies Record<string, `routecraft.mail.${string}`>;\n\n// ---------------------------------------------------------------------------\n// Client manager access\n// ---------------------------------------------------------------------------\n\n/**\n * Get the MailClientManager from the exchange context.\n * Returns null if no mail config was provided (standalone mode).\n */\nexport function getClientManager(\n  context: CraftContext | undefined,\n): MailClientManager | null {\n  if (!context) return null;\n  return (\n    (context.getStore(MAIL_CLIENT_MANAGER) as MailClientManager | undefined) ??\n    null\n  );\n}\n\n/**\n * Get the MailClientManager from the exchange context, throwing if not found.\n */\nexport function requireClientManager(\n  context: CraftContext | undefined,\n): MailClientManager {\n  const manager = getClientManager(context);\n  if (!manager) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"Mail adapter requires mail configuration. Add mail config via .with({ mail: { accounts: {...} } }).\",\n    });\n  }\n  return manager;\n}\n\n// ---------------------------------------------------------------------------\n// Target resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the UIDs and folder for a mail operation.\n * Three-tier: custom extractor > headers > body fallback (single or array).\n */\nexport function resolveMailTarget(\n  exchange: Exchange<unknown>,\n  extractor?: MailTargetExtractor,\n): { uids: number[]; folder: string } {\n  // 1. Custom extractor\n  if (extractor) return extractor(exchange);\n\n  // 2. Headers (survive .transform())\n  const headerUid = exchange.headers[MailHeaders.UID];\n  const headerFolder = exchange.headers[MailHeaders.FOLDER];\n  if (headerUid !== undefined && headerFolder !== undefined) {\n    const uid = Number(headerUid);\n    if (!Number.isFinite(uid) || uid < 1) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `Invalid mail UID header value: ${String(headerUid)}`,\n      });\n    }\n    return { uids: [uid], folder: String(headerFolder) };\n  }\n\n  // 3a. Body: array (batch from .enrich())\n  const body = exchange.body;\n  if (\n    Array.isArray(body) &&\n    body.length > 0 &&\n    \"uid\" in body[0] &&\n    \"folder\" in body[0]\n  ) {\n    return {\n      uids: body.map((m: { uid: number }) => m.uid),\n      folder: (body[0] as { folder: string }).folder,\n    };\n  }\n\n  // 3b. Body: single message\n  if (body && typeof body === \"object\" && \"uid\" in body && \"folder\" in body) {\n    const msg = body as { uid: number; folder: string };\n    return { uids: [msg.uid], folder: msg.folder };\n  }\n\n  throw rcError(\"RC5003\", undefined, {\n    message:\n      \"Mail operation requires a mail message context. Ensure the exchange originates from a mail source, has routecraft.mail.uid/routecraft.mail.folder headers, or provide a custom target extractor.\",\n  });\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize a string or string array to an array.\n */\nexport function toArray(value: string | string[]): string[] {\n  return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Split a fetched {@link MailMessage} into the shape the streaming source\n * delivers: message content on `body` (a {@link MailBody}) and envelope\n * metadata on `routecraft.mail.*` headers.\n *\n * This mirrors the HTTP source convention (payload on `body`, envelope on\n * `headers`) so the same `.transform()` / `.filter()` operators compose across\n * adapters. Attachments are message content, not envelope, so they stay on the\n * body alongside `text`/`html`. IMAP routing identity (`uid`/`folder`) and the\n * rest of the envelope move to headers.\n *\n * @param message - A message produced by {@link fetchMessages}\n * @returns The `body`/`headers` pair to hand to the source's exchange handler\n */\nexport function splitMailMessage(message: MailMessage): {\n  body: MailBody;\n  headers: ExchangeHeaders;\n} {\n  const body: MailBody = {};\n  if (message.body.text !== undefined) body.text = message.body.text;\n  if (message.body.html !== undefined) body.html = message.body.html;\n  if (message.attachments !== undefined) body.attachments = message.attachments;\n\n  // `ExchangeHeaders` is `Readonly`, so build the map in one literal (with\n  // conditional spreads for the optional envelope fields) rather than\n  // post-assigning. Empty cc/bcc arrays are omitted to keep headers clean.\n  const headers: ExchangeHeaders = {\n    [MailHeaders.UID]: message.uid,\n    [MailHeaders.FOLDER]: message.folder,\n    [MailHeaders.MESSAGE_ID]: message.messageId,\n    [MailHeaders.FROM]: message.from,\n    [MailHeaders.TO]: toArray(message.to),\n    [MailHeaders.SUBJECT]: message.subject,\n    [MailHeaders.DATE]: message.date,\n    [MailHeaders.FLAGS]: message.flags,\n    ...(message.cc !== undefined && message.cc.length > 0\n      ? { [MailHeaders.CC]: message.cc }\n      : {}),\n    ...(message.bcc !== undefined && message.bcc.length > 0\n      ? { [MailHeaders.BCC]: message.bcc }\n      : {}),\n    ...(message.replyTo !== undefined\n      ? { [MailHeaders.REPLY_TO]: message.replyTo }\n      : {}),\n    ...(message.rawHeaders !== undefined\n      ? { [MailHeaders.RAW_HEADERS]: message.rawHeaders }\n      : {}),\n    ...(message.sender !== undefined\n      ? { [MailHeaders.SENDER]: message.sender }\n      : {}),\n  };\n\n  return { body, headers };\n}\n\n/**\n * Composed message options accepted by both nodemailer's `sendMail` and\n * `MailComposer`. One shape for the two egress paths (SMTP send and IMAP\n * append) so a composed reply threads identically wherever it ends up.\n */\nexport interface MailMessageOptions {\n  from?: string | undefined;\n  to: string | string[];\n  subject: string;\n  text?: string | undefined;\n  html?: string | undefined;\n  cc?: string | string[] | undefined;\n  bcc?: string | string[] | undefined;\n  replyTo?: string | undefined;\n  headers?: Record<string, string> | undefined;\n  inReplyTo?: string | undefined;\n  references?: string | string[] | undefined;\n  attachments?: MailSendPayload[\"attachments\"] | undefined;\n  disableFileAccess: true;\n  disableUrlAccess: true;\n}\n\n/**\n * Map a {@link MailSendPayload} onto nodemailer message options, merging\n * option-level defaults (from, replyTo, cc, bcc) and deriving the\n * threading headers. Shared by the SMTP send destination and the IMAP\n * append flow so the threading contract lives in one place.\n *\n * The payload is often untrusted (an HTTP body, an MCP tool call), and\n * nodemailer reads a local file for an attachment's `path` and fetches a URL\n * for its `href`. Attachments are therefore rebuilt from their declared\n * fields only, and file and URL access are disabled for the whole message, so\n * a crafted payload cannot attach `/etc/passwd` or reach an internal address.\n */\nexport function buildMessageOptions(\n  payload: MailSendPayload,\n  defaults: MailClientOptions,\n): MailMessageOptions {\n  // Threading sugar: a reply that only knows the original Message-ID\n  // still gets a References header, so clients stitch the thread. An\n  // empty string or empty array counts as \"not given\", matching the\n  // documented inReplyTo contract.\n  const hasReferences = Array.isArray(payload.references)\n    ? payload.references.length > 0\n    : payload.references !== undefined && payload.references !== \"\";\n  const references = hasReferences ? payload.references : payload.inReplyTo;\n\n  return {\n    from: payload.from ?? defaults.from,\n    to: payload.to,\n    subject: payload.subject,\n    text: payload.text,\n    html: payload.html,\n    cc: payload.cc ?? defaults.cc,\n    bcc: payload.bcc ?? defaults.bcc,\n    replyTo: payload.replyTo ?? defaults.replyTo,\n    headers: payload.headers,\n    inReplyTo: payload.inReplyTo,\n    references,\n    attachments: payload.attachments?.map(\n      ({ filename, content, contentType }) => ({\n        filename,\n        content,\n        ...(contentType !== undefined ? { contentType } : {}),\n      }),\n    ),\n    disableFileAccess: true,\n    disableUrlAccess: true,\n  };\n}\n\n/**\n * Build a raw MIME message from a MailSendPayload using nodemailer's MailComposer.\n */\nexport async function buildMimeMessage(\n  payload: MailSendPayload,\n  smtpDefaults: MailClientOptions,\n): Promise<Buffer> {\n  const MailComposer = (\n    await loadOptionalPeer(() => import(\"nodemailer/lib/mail-composer\"), {\n      consumer: \"mail adapter\",\n      packageName: \"nodemailer\",\n    })\n  ).default;\n  const composer = new MailComposer(buildMessageOptions(payload, smtpDefaults));\n  return composer.compile().build();\n}\n\n// ---------------------------------------------------------------------------\n// Shared IMAP config builder\n// ---------------------------------------------------------------------------\n\n/**\n * Validate IMAP connection options and return a config object for ImapFlow.\n * Shared by both standalone `createImapClient` and `ImapPool.createClient`.\n */\nexport function buildImapConfig(options: {\n  host?: string;\n  port?: number;\n  secure?: boolean;\n  auth?: { user: string; pass: string };\n}): {\n  host: string;\n  port: number;\n  secure: boolean;\n  auth: { user: string; pass: string };\n  logger: false;\n} {\n  if (!options.host) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"Mail adapter IMAP host is required. Set host in account config or adapter options.\",\n    });\n  }\n  if (!options.auth) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"Mail adapter auth is required. Set auth in account config or adapter options.\",\n    });\n  }\n  return {\n    host: options.host,\n    port: options.port ?? 993,\n    secure: options.secure ?? true,\n    auth: options.auth,\n    logger: false,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Standalone IMAP client (for inline overrides without named account)\n// ---------------------------------------------------------------------------\n\n/**\n * Create a standalone ImapFlow client from resolved server options.\n * Used when an adapter provides inline host/auth overrides (no named account).\n */\nexport async function createImapClient(\n  options: MailServerOptions,\n): Promise<InstanceType<typeof import(\"imapflow\").ImapFlow>> {\n  const config = buildImapConfig(options);\n  const { ImapFlow } = await loadOptionalPeer(() => import(\"imapflow\"), {\n    consumer: \"mail adapter\",\n    packageName: \"imapflow\",\n  });\n  return new ImapFlow(config);\n}\n\n/**\n * Create a nodemailer SMTP transporter from resolved client options.\n * Used when an adapter provides inline host/auth overrides (no named account).\n */\nexport async function createSmtpTransport(\n  options: MailClientOptions,\n): Promise<ReturnType<typeof import(\"nodemailer\").createTransport>> {\n  if (!options.host) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"Mail adapter SMTP host is required. Set host in account config or adapter options.\",\n    });\n  }\n  if (!options.auth) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"Mail adapter auth is required. Set auth in account config or adapter options.\",\n    });\n  }\n\n  const nodemailer = await loadOptionalPeer(() => import(\"nodemailer\"), {\n    consumer: \"mail adapter\",\n    packageName: \"nodemailer\",\n  });\n  return nodemailer.createTransport({\n    host: options.host,\n    port: options.port ?? 465,\n    secure: options.secure ?? true,\n    auth: options.auth,\n  });\n}\n\n// ---------------------------------------------------------------------------\n// Error helpers\n// ---------------------------------------------------------------------------\n\n/**\n * True when the error is the RC5017 raised by `loadOptionalPeer` for a\n * missing optional peer (`imapflow`, `nodemailer`, `mailparser`). A missing\n * package cannot be fixed by reconnecting; the source must surface the\n * install hint and stop instead of burning reconnect attempts into RC5010.\n */\nexport function isMissingPeerError(error: unknown): boolean {\n  return (\n    isRoutecraftError(error) && (error as { rc?: unknown }).rc === \"RC5017\"\n  );\n}\n\n/**\n * Check whether an error is an authentication failure.\n */\nexport function isMailAuthError(error: unknown): boolean {\n  if (!(error instanceof Error)) return false;\n  const msg = error.message.toLowerCase();\n  return (\n    msg.includes(\"auth\") ||\n    msg.includes(\"credentials\") ||\n    msg.includes(\"login\") ||\n    msg.includes(\"535\")\n  );\n}\n\n/**\n * Throw a RoutecraftError for a mail connection or authentication failure.\n */\nexport function throwMailConnectionError(\n  error: unknown,\n  protocol: \"IMAP\" | \"SMTP\",\n): never {\n  const auth = isMailAuthError(error);\n  throw rcError(\n    auth ? \"RC5012\" : \"RC5010\",\n    error instanceof Error ? error : undefined,\n    {\n      message: `Mail adapter ${protocol} ${auth ? \"authentication\" : \"connection\"} failed: ${error instanceof Error ? error.message : String(error)}`,\n    },\n  );\n}\n\n// ---------------------------------------------------------------------------\n// IMAP search and message parsing\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize a search field value to an array.\n */\nfunction toSearchArray(value: string | string[] | undefined): string[] {\n  if (value === undefined) return [];\n  return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Build one or more IMAP search criteria sets from server options.\n *\n * Scalar filters (unseen, since) are shared across all sets.\n * Array filters (from, to, subject, body) produce the cartesian product\n * so each combination is a separate IMAP search (OR within a field,\n * AND between fields). Results are deduped by UID after fetching.\n */\nexport function buildSearchCriteriaSets(\n  options: MailServerOptions,\n): Record<string, unknown>[] {\n  // Shared base criteria (AND between fields)\n  const base: Record<string, unknown> = {};\n  if (options.unseen !== false) base[\"seen\"] = false;\n  if (options.since) base[\"since\"] = options.since;\n\n  // Collect per-field arrays\n  const fromValues = toSearchArray(options.from);\n  const toValues = toSearchArray(options.to);\n  const subjectValues = toSearchArray(options.subject);\n  const bodyValues = toSearchArray(options.body);\n\n  // Build field entries: [imapKey, values[]]\n  const fields: Array<[string, string[]]> = [];\n  if (fromValues.length > 0) fields.push([\"from\", fromValues]);\n  if (toValues.length > 0) fields.push([\"to\", toValues]);\n  if (subjectValues.length > 0) fields.push([\"subject\", subjectValues]);\n  if (bodyValues.length > 0) fields.push([\"body\", bodyValues]);\n\n  // Raw header filters: each header key expands as OR, AND between keys\n  const headerEntries: Array<[string, string[]]> = [];\n  if (options.header) {\n    for (const [headerName, headerValue] of Object.entries(options.header)) {\n      const values = toSearchArray(headerValue);\n      if (values.length > 0) headerEntries.push([headerName, values]);\n    }\n  }\n\n  if (fields.length === 0 && headerEntries.length === 0) return [base];\n\n  // Cartesian product of all field values\n  let combinations: Record<string, unknown>[] = [{ ...base }];\n  for (const [key, values] of fields) {\n    const expanded: Record<string, unknown>[] = [];\n    for (const combo of combinations) {\n      for (const val of values) {\n        expanded.push({ ...combo, [key]: val });\n      }\n    }\n    combinations = expanded;\n  }\n\n  // Expand header filters into the cartesian product.\n  // ImapFlow expects: { header: { \"Header-Name\": \"value\" } }\n  // Each header key with multiple values produces OR branches.\n  for (const [headerName, values] of headerEntries) {\n    const expanded: Record<string, unknown>[] = [];\n    for (const combo of combinations) {\n      for (const val of values) {\n        const existingHeader =\n          (combo[\"header\"] as Record<string, string> | undefined) ?? {};\n        expanded.push({\n          ...combo,\n          header: { ...existingHeader, [headerName]: val },\n        });\n      }\n    }\n    combinations = expanded;\n  }\n\n  return combinations;\n}\n\n/**\n * Convert an imapflow message object to a MailMessage.\n *\n * @param msg - Raw message data with uid, flags, and envelope\n * @param folder - The IMAP folder this message was fetched from\n * @param content - Parsed text/html/attachments content\n */\nexport function toMailMessage(\n  msg: {\n    uid: number;\n    flags: Set<string>;\n    envelope: {\n      messageId?: string;\n      from?: Array<{ address?: string; name?: string }>;\n      to?: Array<{ address?: string; name?: string }>;\n      cc?: Array<{ address?: string; name?: string }>;\n      bcc?: Array<{ address?: string; name?: string }>;\n      replyTo?: Array<{ address?: string; name?: string }>;\n      subject?: string;\n      date?: Date;\n    };\n  },\n  folder: string,\n  content?: {\n    text?: string;\n    html?: string;\n    attachments?: Array<{\n      filename?: string;\n      contentType: string;\n      size: number;\n      content: Buffer;\n    }>;\n    rawHeaders?: Record<string, string | string[]>;\n  },\n): MailMessage {\n  const envelope = msg.envelope;\n  const fromAddrs = envelope.from ?? [];\n  const toAddrs = envelope.to ?? [];\n  const ccAddrs = envelope.cc ?? [];\n  const bccAddrs = envelope.bcc ?? [];\n  const replyToAddrs = envelope.replyTo ?? [];\n\n  const toList = toAddrs\n    .map((a) => a.address)\n    .filter((a): a is string => a !== undefined);\n\n  const body: { text?: string; html?: string } = {};\n  if (content?.text !== undefined) body.text = content.text;\n  if (content?.html !== undefined) body.html = content.html;\n\n  const result: MailMessage = {\n    uid: msg.uid,\n    messageId: envelope.messageId ?? \"\",\n    from: fromAddrs[0]?.address ?? \"\",\n    to: toList.length === 1 ? toList[0] : toList,\n    subject: envelope.subject ?? \"\",\n    date: envelope.date ?? new Date(),\n    body,\n    cc: ccAddrs\n      .map((a) => a.address)\n      .filter((a): a is string => a !== undefined),\n    bcc: bccAddrs\n      .map((a) => a.address)\n      .filter((a): a is string => a !== undefined),\n    flags: msg.flags,\n    folder,\n  };\n\n  if (replyToAddrs[0]?.address !== undefined)\n    result.replyTo = replyToAddrs[0].address;\n  if (content?.attachments !== undefined)\n    result.attachments = content.attachments;\n  if (content?.rawHeaders !== undefined) result.rawHeaders = content.rawHeaders;\n\n  return result;\n}\n\n/**\n * Parse a single IMAP message into content fields using mailparser.\n *\n * When `includeAnalysisHeaders` is true, auth-relevant headers are also\n * extracted (independently of `requestedHeaders`) and returned via\n * `analysisHeaders` for sender analysis.\n */\nasync function parseMessageContent(\n  source: Buffer | undefined,\n  simpleParser: typeof import(\"mailparser\").simpleParser,\n  requestedHeaders?: true | string[],\n  includeAnalysisHeaders?: boolean,\n): Promise<{\n  text?: string;\n  html?: string;\n  attachments?: Array<{\n    filename?: string;\n    contentType: string;\n    size: number;\n    content: Buffer;\n  }>;\n  rawHeaders?: Record<string, string | string[]>;\n  analysisHeaders?: Record<string, string | string[]>;\n}> {\n  if (!source) return {};\n  // Throws on malformed MIME. Callers decide whether to swallow, route the\n  // error through the route pipeline, or abort (see `onParseError` and #187).\n  const parsed = await simpleParser(source);\n  const content: {\n    text?: string;\n    html?: string;\n    attachments?: Array<{\n      filename?: string;\n      contentType: string;\n      size: number;\n      content: Buffer;\n    }>;\n    rawHeaders?: Record<string, string | string[]>;\n    analysisHeaders?: Record<string, string | string[]>;\n  } = {};\n  if (parsed.text) content.text = parsed.text;\n  if (typeof parsed.html === \"string\") content.html = parsed.html;\n  if (parsed.attachments && parsed.attachments.length > 0) {\n    content.attachments = parsed.attachments.map((att) => {\n      const a: {\n        filename?: string;\n        contentType: string;\n        size: number;\n        content: Buffer;\n      } = {\n        contentType: att.contentType,\n        size: att.size,\n        content: att.content,\n      };\n      if (att.filename) a.filename = att.filename;\n      return a;\n    });\n  }\n  if (requestedHeaders && parsed.headerLines) {\n    const hdrs: Record<string, string | string[]> = {};\n    const wanted =\n      requestedHeaders === true\n        ? null\n        : new Set(requestedHeaders.map((h) => h.toLowerCase()));\n    for (const entry of parsed.headerLines as Array<{\n      key: string;\n      line: string;\n    }>) {\n      if (wanted && !wanted.has(entry.key)) continue;\n      // Extract value portion after \"Header-Name: \"\n      const colonIdx = entry.line.indexOf(\":\");\n      const value =\n        colonIdx >= 0 ? entry.line.slice(colonIdx + 1).trim() : entry.line;\n      // Accumulate multi-value headers (e.g. Received) as arrays\n      const existing = hdrs[entry.key];\n      if (existing === undefined) {\n        hdrs[entry.key] = value;\n      } else if (Array.isArray(existing)) {\n        existing.push(value);\n      } else {\n        hdrs[entry.key] = [existing, value];\n      }\n    }\n    if (Object.keys(hdrs).length > 0) content.rawHeaders = hdrs;\n  }\n  if (includeAnalysisHeaders && parsed.headerLines) {\n    const analysis = extractAnalysisHeaders(\n      parsed.headerLines as ReadonlyArray<{ key: string; line: string }>,\n    );\n    if (Object.keys(analysis).length > 0) content.analysisHeaders = analysis;\n  }\n  return content;\n}\n\n/**\n * Per-message parse error attached to a `MailMessage` when the source's\n * `onParseError` is `'fail'`. The mail source loop reads this and routes the\n * error through the route's `.error()` handler via the `parse` argument so\n * malformed MIME becomes a normal pipeline error instead of a silent\n * degraded delivery. See #187.\n *\n * @internal Module-level registry. Safe globally because each `MailMessage`\n * is constructed for one and only one fetch cycle, and entries are deleted\n * by the source loop as soon as they are consumed. WeakMap GC handles any\n * messages that go unread (e.g. after an abort mid-fetch).\n */\nexport const MAIL_PARSE_ERRORS = new WeakMap<MailMessage, Error>();\n\n/**\n * Minimal logger shape accepted by `fetchMessages`. Matches the methods used\n * on a pino child logger without pinning to pino's types.\n */\nexport interface MailFetchLogger {\n  debug: (obj: Record<string, unknown>, msg: string) => void;\n  warn: (obj: Record<string, unknown>, msg: string) => void;\n}\n\n/**\n * Fetch messages from an open IMAP mailbox using the given client.\n * The client must already be connected and have a mailbox open.\n *\n * When search options contain array values (OR semantics within a field),\n * multiple IMAP searches are executed and results are deduped by UID.\n *\n * @param client - Connected ImapFlow client with open mailbox\n * @param options - Resolved IMAP options (for search criteria, limit, markSeen)\n * @param folder - The folder name (for setting on MailMessage)\n * @param logger - Optional logger for parse/verify diagnostics\n */\nexport async function fetchMessages(\n  client: InstanceType<typeof import(\"imapflow\").ImapFlow>,\n  options: MailServerOptions,\n  folder: string,\n  logger?: MailFetchLogger,\n): Promise<MailMessage[]> {\n  const criteriaSets = buildSearchCriteriaSets(options);\n  const messages: MailMessage[] = [];\n  const seenUids = new Set<number>();\n\n  // Load the parser BEFORE the fetch try/catch: its catch wraps every error\n  // in retryable RC5001, which would bury the RC5017 install hint and spin\n  // reconnect loops on a missing optional peer.\n  const { simpleParser } = await loadOptionalPeer(() => import(\"mailparser\"), {\n    consumer: \"mail adapter\",\n    packageName: \"mailparser\",\n  });\n\n  try {\n    const fetchOptions = {\n      envelope: true,\n      uid: true,\n      flags: true,\n      source: true,\n    };\n\n    const verify = options.verify ?? \"headers\";\n\n    for (const criteria of criteriaSets) {\n      let searchQuery: Record<string, unknown> | string = criteria;\n      if (Object.keys(criteria).length === 0) {\n        searchQuery = \"1:*\";\n      }\n\n      for await (const msg of client.fetch(searchQuery, fetchOptions)) {\n        // Dedupe across criteria sets\n        if (seenUids.has(msg.uid)) continue;\n        seenUids.add(msg.uid);\n\n        let content:\n          Awaited<ReturnType<typeof parseMessageContent>> | undefined;\n        let parseError: Error | undefined;\n        try {\n          content = await parseMessageContent(\n            msg.source,\n            simpleParser,\n            options.includeHeaders,\n            verify !== \"off\",\n          );\n        } catch (err) {\n          const wrapped = err instanceof Error ? err : new Error(String(err));\n          // 'fail', 'abort', and 'drop' all capture the error so the per-\n          // message lifecycle event fires from the synthetic parse step.\n          // For 'abort' the source loop rethrows after the event fires so\n          // the source still dies; for 'drop' the route emits\n          // `route:exchange:dropped`; for 'fail' the route's `.error()` handler\n          // catches it. See #187.\n          parseError = wrapped;\n          content = {};\n        }\n\n        const mailMessage = toMailMessage(\n          {\n            uid: msg.uid,\n            flags: msg.flags ?? new Set(),\n            envelope: msg.envelope ?? {},\n          },\n          folder,\n          content,\n        );\n\n        if (parseError) {\n          MAIL_PARSE_ERRORS.set(mailMessage, parseError);\n        }\n\n        if (verify !== \"off\") {\n          const analysisHeaders = content.analysisHeaders;\n          // Only populate `sender` when we have headers to analyse. An empty\n          // map means the source buffer was missing or unparseable; stamping\n          // a degenerate `sender` with empty address would be worse than\n          // omitting it, since consumers cannot distinguish \"analysis ran\"\n          // from \"analysis found nothing\".\n          if (analysisHeaders && Object.keys(analysisHeaders).length > 0) {\n            let sender: MailSender = analyzeHeaders(analysisHeaders);\n            if (verify === \"strict\") {\n              try {\n                const { verifyStrict } = await import(\"./strict-verify.ts\");\n                sender = await verifyStrict(msg.source, sender);\n              } catch (error) {\n                // Do not let a single verification failure (transient DNS,\n                // malformed signature, missing mailauth install surfacing\n                // mid-fetch) tear down the whole poll cycle. Degrade trust\n                // and continue.\n                sender = {\n                  ...sender,\n                  trust: \"failed\",\n                  reason: \"strict-verify-error\",\n                };\n                logger?.warn(\n                  {\n                    err:\n                      error instanceof Error ? error : new Error(String(error)),\n                    uid: msg.uid,\n                    folder,\n                  },\n                  \"mail adapter strict verify failed; continuing with header-only verdict\",\n                );\n              }\n            }\n            mailMessage.sender = sender;\n            // Observability: one structured log line per message describing the\n            // verdict. Debug for verified/unverified (can be noisy), warn for\n            // failed so security graphs can scrape \"DMARC failures per hour\"\n            // without needing a bespoke event type.\n            const verdictLog = {\n              uid: msg.uid,\n              folder,\n              mode: verify,\n              forwardType: sender.forwardType,\n              trust: sender.trust,\n              reason: sender.reason,\n              authentication: sender.authentication,\n            };\n            if (sender.trust === \"failed\") {\n              logger?.warn(verdictLog, \"mail adapter verify: trust failed\");\n            } else {\n              logger?.debug(verdictLog, \"mail adapter verify: completed\");\n            }\n          }\n        }\n\n        messages.push(mailMessage);\n\n        if (options.limit && messages.length >= options.limit) {\n          break;\n        }\n      }\n\n      // Stop searching further criteria sets if limit reached\n      if (options.limit && messages.length >= options.limit) {\n        break;\n      }\n    }\n  } catch (error) {\n    throw rcError(\"RC5001\", error instanceof Error ? error : undefined, {\n      message: `Failed to fetch messages from IMAP: ${error instanceof Error ? error.message : String(error)}`,\n    });\n  }\n\n  return messages;\n}\n\n/**\n * Mark one or more messages as \\Seen on an open IMAP mailbox.\n *\n * Never throws: flagging failure degrades correctness (a message may be\n * redelivered) but must not tear down the fetch cycle or source subscription.\n * Callers that care about the failure should pass a logger.\n *\n * @param client - Connected ImapFlow client with the target mailbox open\n * @param uids - UIDs to flag. May be a single uid or an array. Empty arrays are a no-op.\n * @param logger - Optional logger for flagging diagnostics\n */\nexport async function markMessagesSeen(\n  client: InstanceType<typeof import(\"imapflow\").ImapFlow>,\n  uids: number | number[],\n  logger?: MailFetchLogger,\n): Promise<void> {\n  const list = Array.isArray(uids) ? uids : [uids];\n  if (list.length === 0) return;\n  try {\n    await client.messageFlagsAdd(list.join(\",\"), [\"\\\\Seen\"], {\n      uid: true,\n    });\n  } catch (error) {\n    logger?.warn(\n      {\n        err: error instanceof Error ? error : new Error(String(error)),\n        uids: list,\n      },\n      \"mail adapter failed to mark messages as seen\",\n    );\n  }\n}\n","/**\n * Sender analysis for received mail messages.\n *\n * Derives the \"effective sender\" by unwinding mailing-list and auto-forward\n * rewrites using already-present headers (`List-Id`, `X-Original-From`,\n * `Authentication-Results`, `ARC-*`). No network, no crypto. For cryptographic\n * verification see `strict-verify.ts`.\n */\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * How a message reached the recipient.\n */\nexport type ForwardType = \"direct\" | \"auto-forward\" | \"mailing-list\";\n\n/**\n * Trust state of the effective sender.\n */\nexport type TrustLevel = \"verified\" | \"unverified\" | \"failed\";\n\n/**\n * Parsed email address.\n */\nexport interface EmailAddress {\n  address: string;\n  name?: string;\n  domain: string;\n}\n\n/**\n * One hop in a forward chain.\n */\nexport interface ForwardHop {\n  via: EmailAddress;\n  type: \"auto-forward\" | \"mailing-list\";\n  arcInstance?: number;\n}\n\n/**\n * Effective sender plus the evidence used to resolve it.\n */\nexport interface MailSender extends EmailAddress {\n  /** How the message reached us. */\n  forwardType: ForwardType;\n  /** Chain of forwarders, nearest hop first. Empty for direct mail. */\n  forwardChain: ForwardHop[];\n  /** Trust state of this sender. */\n  trust: TrustLevel;\n  /** Machine-readable reason, e.g. \"list-forward-arc-verified\". */\n  reason: string;\n  /** Authentication verdicts from the receiving server's Authentication-Results. */\n  authentication: {\n    dkim: \"pass\" | \"fail\" | \"neutral\" | \"none\";\n    spf: \"pass\" | \"fail\" | \"neutral\" | \"none\";\n    dmarc: \"pass\" | \"fail\" | \"neutral\" | \"none\";\n    arc: \"pass\" | \"fail\" | \"none\";\n  };\n  /** Literal `From:` header, only set when it differs from the effective sender. */\n  headerFrom?: EmailAddress;\n}\n\n// ---------------------------------------------------------------------------\n// Header allowlist used for analysis\n// ---------------------------------------------------------------------------\n\n/**\n * Lowercased header names relevant to sender analysis. Always extracted from\n * a parsed message even when the caller has not requested `includeHeaders`.\n */\nexport const ANALYSIS_HEADER_NAMES = [\n  \"from\",\n  \"sender\",\n  \"reply-to\",\n  \"x-original-from\",\n  \"x-original-sender\",\n  \"list-id\",\n  \"list-post\",\n  \"list-unsubscribe\",\n  \"precedence\",\n  \"authentication-results\",\n  \"arc-authentication-results\",\n  \"arc-message-signature\",\n  \"arc-seal\",\n  \"received\",\n] as const;\n\n/**\n * Extract the auth-relevant headers from a mailparser `headerLines` array.\n * Keys are lowercased. Multi-value headers become arrays.\n */\nexport function extractAnalysisHeaders(\n  headerLines: ReadonlyArray<{ key: string; line: string }> | undefined,\n): Record<string, string | string[]> {\n  if (!headerLines) return {};\n  const wanted = new Set<string>(ANALYSIS_HEADER_NAMES);\n  const out: Record<string, string | string[]> = {};\n  for (const entry of headerLines) {\n    const key = entry.key.toLowerCase();\n    if (!wanted.has(key)) continue;\n    const colonIdx = entry.line.indexOf(\":\");\n    const value =\n      colonIdx >= 0 ? entry.line.slice(colonIdx + 1).trim() : entry.line;\n    const existing = out[key];\n    if (existing === undefined) {\n      out[key] = value;\n    } else if (Array.isArray(existing)) {\n      existing.push(value);\n    } else {\n      out[key] = [existing, value];\n    }\n  }\n  return out;\n}\n\n// ---------------------------------------------------------------------------\n// Address parsing\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a single address header value like `\"Team Flextender\" <x@y.nl>` or `x@y.nl`.\n * Returns null when no address-looking token is found.\n */\nexport function parseAddress(value: string | undefined): EmailAddress | null {\n  if (!value) return null;\n  const trimmed = value.trim();\n  // \"Name\" <addr@host> or Name <addr@host>\n  const angle = trimmed.match(/^(.*?)<([^>]+)>\\s*$/);\n  let addr: string;\n  let name: string | undefined;\n  if (angle) {\n    name = angle[1].trim().replace(/^\"|\"$/g, \"\").trim() || undefined;\n    addr = angle[2].trim();\n  } else {\n    addr = trimmed;\n  }\n  const at = addr.lastIndexOf(\"@\");\n  if (at <= 0 || at === addr.length - 1) return null;\n  const domain = addr.slice(at + 1).toLowerCase();\n  const result: EmailAddress = {\n    address: addr.toLowerCase(),\n    domain,\n  };\n  if (name) result.name = name;\n  return result;\n}\n\n/** Pick the first value of a possibly-multi-value header. */\nfunction firstHeader(\n  headers: Record<string, string | string[]>,\n  key: string,\n): string | undefined {\n  const v = headers[key];\n  if (Array.isArray(v)) return v[0];\n  return v;\n}\n\n/** All values of a possibly-multi-value header. */\nfunction allHeaders(\n  headers: Record<string, string | string[]>,\n  key: string,\n): string[] {\n  const v = headers[key];\n  if (v === undefined) return [];\n  return Array.isArray(v) ? v : [v];\n}\n\n// ---------------------------------------------------------------------------\n// Authentication-Results parsing\n// ---------------------------------------------------------------------------\n\ntype AuthVerdict = \"pass\" | \"fail\" | \"neutral\" | \"none\";\n\ninterface ParsedAuthResults {\n  dkim: AuthVerdict;\n  spf: AuthVerdict;\n  dmarc: AuthVerdict;\n  /** header.from reported by dmarc, if present. */\n  dmarcHeaderFrom?: string;\n  /** header.i (or header.d) reported by the strongest dkim result. */\n  dkimDomain?: string;\n}\n\n/**\n * Parse an `Authentication-Results` style header value.\n *\n * Format (RFC 8601): `authserv-id; method=result (comment) property=value; ...`\n * We pluck out method verdicts plus a couple of properties we care about.\n */\nexport function parseAuthResults(value: string | undefined): ParsedAuthResults {\n  const out: ParsedAuthResults = {\n    dkim: \"none\",\n    spf: \"none\",\n    dmarc: \"none\",\n  };\n  if (!value) return out;\n  // Each result is separated by `;`. The first token is the authserv-id.\n  const parts = value\n    .split(\";\")\n    .map((s) => s.trim())\n    .filter(Boolean);\n  for (const part of parts) {\n    const methodMatch = part.match(/^(dkim|spf|dmarc)\\s*=\\s*(\\w+)/i);\n    if (!methodMatch) continue;\n    const method = methodMatch[1].toLowerCase() as \"dkim\" | \"spf\" | \"dmarc\";\n    const verdict = methodMatch[2].toLowerCase();\n    const normalized: AuthVerdict =\n      verdict === \"pass\" || verdict === \"fail\" || verdict === \"neutral\"\n        ? verdict\n        : \"none\";\n    // Prefer the first non-none verdict we see per method (closest to authserv).\n    if (out[method] === \"none\") out[method] = normalized;\n\n    if (method === \"dmarc\") {\n      const hf = part.match(/header\\.from\\s*=\\s*([^\\s;]+)/i);\n      if (hf && !out.dmarcHeaderFrom) out.dmarcHeaderFrom = hf[1].toLowerCase();\n    }\n    if (method === \"dkim\") {\n      const di =\n        part.match(/header\\.i\\s*=\\s*@?([^\\s;]+)/i) ??\n        part.match(/header\\.d\\s*=\\s*([^\\s;]+)/i);\n      if (di && !out.dkimDomain) out.dkimDomain = di[1].toLowerCase();\n    }\n  }\n  return out;\n}\n\n/**\n * Parse an `ARC-Authentication-Results` header; same body format as\n * `Authentication-Results`, prefixed with `i=N;`.\n */\nfunction parseArcAuthResults(\n  value: string,\n): { instance: number; results: ParsedAuthResults } | null {\n  const m = value.match(/^\\s*i\\s*=\\s*(\\d+)\\s*;\\s*(.*)$/s);\n  if (!m) return null;\n  const instance = Number(m[1]);\n  if (!Number.isFinite(instance)) return null;\n  return { instance, results: parseAuthResults(m[2]) };\n}\n\ninterface ArcChainState {\n  /** Final chain validity from the highest-instance ARC-Seal's `cv=`. */\n  cv: \"pass\" | \"fail\" | \"none\";\n  /** ARC signer domain per instance, parsed from ARC-Seal `d=`. */\n  domainsByInstance: Map<number, string>;\n}\n\n/** Read ARC chain state from every `ARC-Seal` header. */\nfunction parseArcChainState(\n  headers: Record<string, string | string[]>,\n): ArcChainState {\n  const out: ArcChainState = { cv: \"none\", domainsByInstance: new Map() };\n  const seals = allHeaders(headers, \"arc-seal\");\n  if (seals.length === 0) return out;\n  let bestInstance = -1;\n  for (const seal of seals) {\n    const i = seal.match(/\\bi\\s*=\\s*(\\d+)/);\n    if (!i) continue;\n    const instance = Number(i[1]);\n    const d = seal.match(/\\bd\\s*=\\s*([^\\s;]+)/i);\n    if (d) out.domainsByInstance.set(instance, d[1].toLowerCase());\n    const cv = seal.match(/\\bcv\\s*=\\s*(\\w+)/i);\n    if (cv && instance > bestInstance) {\n      bestInstance = instance;\n      const v = cv[1].toLowerCase();\n      out.cv = v === \"pass\" ? \"pass\" : v === \"fail\" ? \"fail\" : \"none\";\n    }\n  }\n  return out;\n}\n\n/**\n * Build a placeholder {@link EmailAddress} when only the sending domain is\n * known (e.g. from ARC `d=` or DMARC `header.from=<domain>`). The synthesised\n * local part is a stable marker so equality checks against real addresses\n * never collide.\n */\nfunction addressFromDomain(domain: string, marker: string): EmailAddress {\n  return { address: `${marker}@${domain}`, domain };\n}\n\n// ---------------------------------------------------------------------------\n// Main entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Derive a {@link MailSender} from the auth-relevant headers of a received\n * message. Pure function, no I/O.\n *\n * @param headers - Lowercased header map, as returned by {@link extractAnalysisHeaders}.\n */\nexport function analyzeHeaders(\n  headers: Record<string, string | string[]>,\n): MailSender {\n  const headerFrom = parseAddress(firstHeader(headers, \"from\"));\n  const listId = firstHeader(headers, \"list-id\");\n  const precedence = firstHeader(headers, \"precedence\");\n  const sender = parseAddress(firstHeader(headers, \"sender\"));\n  const xOriginalFrom = parseAddress(firstHeader(headers, \"x-original-from\"));\n  const xOriginalSender = parseAddress(\n    firstHeader(headers, \"x-original-sender\"),\n  );\n\n  const authResults = parseAuthResults(\n    firstHeader(headers, \"authentication-results\"),\n  );\n  const arcResults = allHeaders(headers, \"arc-authentication-results\")\n    .map(parseArcAuthResults)\n    .filter((v): v is NonNullable<typeof v> => v !== null)\n    .sort((a, b) => a.instance - b.instance);\n  const arcChain = parseArcChainState(headers);\n\n  const isList =\n    listId !== undefined ||\n    /^\\s*(list|bulk)\\b/i.test(precedence ?? \"\") ||\n    (sender !== null &&\n      headerFrom !== null &&\n      sender.domain !== headerFrom.domain);\n  // The delivering MX adds a single first-hop ARC set (i=1, cv=none) to direct\n  // mail (Gmail/Workspace seals everything it accepts), so the presence of ARC\n  // headers is not by itself evidence of forwarding. Real forwarding shows\n  // either a validated chain (cv=pass/fail) or more than one ARC instance.\n  const maxArcInstance = Math.max(\n    0,\n    ...arcResults.map((r) => r.instance),\n    ...arcChain.domainsByInstance.keys(),\n  );\n  const hasArc = arcChain.cv !== \"none\" || maxArcInstance >= 2;\n\n  let forwardType: ForwardType = \"direct\";\n  let effective: EmailAddress | null = headerFrom;\n  const forwardChain: ForwardHop[] = [];\n  let reason = \"direct\";\n\n  if (isList) {\n    forwardType = \"mailing-list\";\n    // Prefer explicit X-Original-From (Google Groups), then X-Original-Sender,\n    // then an authenticated domain from the earliest ARC instance (synthesised\n    // because `header.from=` is domain-only), else Sender.\n    const arcFirst = arcResults[0];\n    const arcFromDomain = arcFirst?.results.dmarcHeaderFrom;\n    const arcFrom: EmailAddress | null =\n      arcFromDomain && (!headerFrom || headerFrom.domain !== arcFromDomain)\n        ? addressFromDomain(arcFromDomain, \"unknown\")\n        : null;\n    effective =\n      xOriginalFrom ?? xOriginalSender ?? arcFrom ?? sender ?? headerFrom;\n    const via = headerFrom ?? sender;\n    if (via) {\n      const hop: ForwardHop = { via, type: \"mailing-list\" };\n      if (arcFirst) hop.arcInstance = arcFirst.instance;\n      forwardChain.push(hop);\n    }\n    reason =\n      arcChain.cv === \"pass\"\n        ? \"list-forward-arc-verified\"\n        : hasArc\n          ? \"list-forward-arc-unverified\"\n          : \"list-forward-unverified\";\n  } else if (hasArc) {\n    forwardType = \"auto-forward\";\n    effective = headerFrom;\n    // One hop per ARC instance, nearest (highest i=) first. Prefer the ARC\n    // signer domain from ARC-Seal `d=`; fall back to the instance's\n    // authentication-results header.from domain.\n    const instances =\n      arcResults.length > 0\n        ? arcResults.map((r) => r.instance)\n        : [...arcChain.domainsByInstance.keys()];\n    for (const instance of [...instances].sort((a, b) => b - a)) {\n      const arcDomain =\n        arcChain.domainsByInstance.get(instance) ??\n        arcResults.find((r) => r.instance === instance)?.results\n          .dmarcHeaderFrom;\n      const hop: ForwardHop = {\n        via: arcDomain\n          ? addressFromDomain(arcDomain, \"arc\")\n          : { address: \"\", domain: \"\" },\n        type: \"auto-forward\",\n        arcInstance: instance,\n      };\n      forwardChain.push(hop);\n    }\n    reason =\n      arcChain.cv === \"pass\"\n        ? \"auto-forward-arc-verified\"\n        : \"auto-forward-arc-unverified\";\n  } else {\n    forwardType = \"direct\";\n    effective = headerFrom;\n    reason =\n      authResults.dmarc === \"pass\"\n        ? \"direct-dmarc-aligned\"\n        : authResults.dmarc === \"fail\"\n          ? \"direct-dmarc-fail\"\n          : \"direct-unverified\";\n  }\n\n  // Trust:\n  //   - failed: any explicit dmarc=fail for a non-forwarded message, or ARC cv=fail\n  //   - verified: direct + dmarc=pass, or forwarded + arc cv=pass\n  //   - unverified: everything else\n  let trust: TrustLevel;\n  if (forwardType === \"direct\") {\n    trust =\n      authResults.dmarc === \"pass\"\n        ? \"verified\"\n        : authResults.dmarc === \"fail\"\n          ? \"failed\"\n          : \"unverified\";\n  } else {\n    trust =\n      arcChain.cv === \"pass\"\n        ? \"verified\"\n        : arcChain.cv === \"fail\"\n          ? \"failed\"\n          : \"unverified\";\n  }\n\n  const fallbackAddress = effective ?? headerFrom ?? sender;\n  const resolvedAddress: EmailAddress = fallbackAddress ?? {\n    address: \"\",\n    domain: \"\",\n  };\n\n  const result: MailSender = {\n    address: resolvedAddress.address,\n    domain: resolvedAddress.domain,\n    forwardType,\n    forwardChain,\n    trust,\n    reason,\n    authentication: {\n      dkim: authResults.dkim,\n      spf: authResults.spf,\n      dmarc: authResults.dmarc,\n      arc: arcChain.cv,\n    },\n  };\n  if (resolvedAddress.name) result.name = resolvedAddress.name;\n  if (headerFrom && headerFrom.address !== resolvedAddress.address) {\n    result.headerFrom = headerFrom;\n  }\n  return result;\n}\n","import { registerConfigApplier } from \"../../config-applier.ts\";\nimport type { StoreRegistry } from \"../../context.ts\";\nimport { MailClientManager } from \"./client-manager.ts\";\nimport { MAIL_CLIENT_MANAGER } from \"./shared.ts\";\nimport type { MailContextConfig } from \"./types.ts\";\n\ndeclare module \"@routecraft/routecraft\" {\n  interface CraftConfig {\n    /** Mail adapter configuration with named accounts */\n    mail?: MailContextConfig;\n  }\n}\n\n/**\n * Register the `mail` config key so `defineConfig({ mail: {...} })`\n * constructs the shared {@link MailClientManager} during `initPlugins()`\n * and drains it during plugin teardown (reverse plugin order, so user\n * plugins tear down first). Loaded as a side-effect import from\n * `packages/routecraft/src/index.ts`. Keeps the core context free of\n * mail adapter knowledge.\n */\nregisterConfigApplier(\"mail\", (options) => {\n  let manager: MailClientManager | undefined;\n  return {\n    apply(ctx) {\n      manager = new MailClientManager(options);\n      ctx.setStore(MAIL_CLIENT_MANAGER as keyof StoreRegistry, manager);\n    },\n    async teardown() {\n      await manager?.drain();\n    },\n  };\n});\n","/**\n * CardDAV client manager: one logged-in DAV client per named account.\n *\n * Created by the ContextBuilder when `carddav` config is present. Adapters get\n * it from the context store and request a client by account name. The\n * underlying tsdav client is HTTP/stateless, so there are no sockets to pool;\n * the manager simply caches the logged-in client (login is the only async cost).\n *\n * @experimental\n */\n\nimport { rcError } from \"../../error.ts\";\nimport { loadOptionalPeer } from \"../shared/optional-peer.ts\";\nimport type { CarddavContextConfig } from \"./types.ts\";\nimport {\n  DEFAULT_CARDDAV_SERVER_URL,\n  throwCarddavError,\n  type CarddavDriverClient,\n} from \"./shared.ts\";\n\n/** Connection inputs resolved from account + context config. */\nexport interface ResolvedCarddavConnection {\n  serverUrl: string;\n  username: string;\n  password: string;\n}\n\n/**\n * Manages per-account logged-in CardDAV clients.\n *\n * @experimental\n */\nexport class CarddavClientManager {\n  /**\n   * Login seam. Resolves a driver client for the given connection. Exposed as a\n   * static so tests can substitute a fake client without a network round-trip\n   * (mirrors the cron adapter's `loadDriver` pattern).\n   * @internal\n   */\n  static createDriverClient: (\n    connection: ResolvedCarddavConnection,\n  ) => Promise<CarddavDriverClient> = async (connection) => {\n    const tsdav = await loadOptionalPeer(() => import(\"tsdav\"), {\n      consumer: \"carddav adapter\",\n      packageName: \"tsdav\",\n    });\n    const client = await tsdav.createDAVClient({\n      serverUrl: connection.serverUrl,\n      credentials: {\n        username: connection.username,\n        password: connection.password,\n      },\n      authMethod: \"Basic\",\n      defaultAccountType: \"carddav\",\n    });\n    return client as unknown as CarddavDriverClient;\n  };\n\n  private readonly clients = new Map<string, Promise<CarddavDriverClient>>();\n  readonly config: CarddavContextConfig;\n  readonly defaultAccount: string;\n\n  constructor(config: CarddavContextConfig) {\n    this.config = config;\n    const accounts = config.accounts ?? {};\n    this.defaultAccount =\n      \"default\" in accounts ? \"default\" : (Object.keys(accounts)[0] ?? \"\");\n  }\n\n  /** Resolve the connection inputs for an account, throwing RC5003 if incomplete. */\n  resolveConnection(account?: string): ResolvedCarddavConnection {\n    const name = account ?? this.defaultAccount;\n    const acct = this.config.accounts?.[name];\n    if (!acct) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `CardDAV account '${name || \"(none)\"}' is not configured.`,\n      });\n    }\n    if (!acct.username || !acct.appPassword) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `CardDAV account '${name}' requires both username and appPassword.`,\n      });\n    }\n    return {\n      serverUrl:\n        acct.serverUrl ?? this.config.serverUrl ?? DEFAULT_CARDDAV_SERVER_URL,\n      username: acct.username,\n      password: acct.appPassword,\n    };\n  }\n\n  /** The default address book display name for an account, if configured. */\n  resolveAddressBookName(account?: string): string | undefined {\n    const name = account ?? this.defaultAccount;\n    return this.config.accounts?.[name]?.addressBook ?? this.config.addressBook;\n  }\n\n  /** Acquire (and cache) a logged-in client for the given account. */\n  async getClient(account?: string): Promise<CarddavDriverClient> {\n    const name = account ?? this.defaultAccount;\n    let pending = this.clients.get(name);\n    if (!pending) {\n      const connection = this.resolveConnection(name);\n      pending = CarddavClientManager.createDriverClient(connection).catch(\n        (error: unknown) => {\n          // Drop the rejected promise so a later call can retry the login.\n          this.clients.delete(name);\n          throwCarddavError(error, \"login\");\n        },\n      );\n      this.clients.set(name, pending);\n    }\n    return pending;\n  }\n\n  /**\n   * Release cached clients. Called during context teardown. Awaits any logins\n   * still in flight (via `allSettled`) so a slow login that rejects after the\n   * map has been cleared does not surface as an `unhandledRejection`.\n   */\n  async drain(): Promise<void> {\n    const pending = Array.from(this.clients.values());\n    this.clients.clear();\n    await Promise.allSettled(pending);\n  }\n}\n","/**\n * Shared CardDAV adapter helpers: store key, client-manager access, the minimal\n * DAV driver surface the adapter depends on, and HTTP/error mapping.\n *\n * @experimental\n */\n\nimport type { CraftContext } from \"../../context.ts\";\nimport { rcError, RoutecraftError } from \"../../error.ts\";\nimport type { CarddavClientManager } from \"./client-manager.ts\";\n\n/** Default CardDAV server for iCloud Contacts. */\nexport const DEFAULT_CARDDAV_SERVER_URL = \"https://contacts.icloud.com\";\n\n// ---------------------------------------------------------------------------\n// Store key\n// ---------------------------------------------------------------------------\n\n/**\n * Store key for the CardDAV client manager.\n * Set by the ContextBuilder when `carddav` config is present.\n * @experimental\n */\nexport const CARDDAV_CLIENT_MANAGER = Symbol.for(\n  \"routecraft.adapter.carddav.client-manager\",\n);\n\ndeclare module \"@routecraft/routecraft\" {\n  interface StoreRegistry {\n    [CARDDAV_CLIENT_MANAGER]: CarddavClientManager;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Header constants\n// ---------------------------------------------------------------------------\n\n/**\n * Header keys the CardDAV adapter sets for contact metadata. Keys live\n * under the reserved `routecraft.carddav.*` namespace; the value types are\n * merged into `RoutecraftHeaders` below.\n * @experimental\n */\nexport const CarddavHeaders = {\n  /** vCard UID of a contact. */\n  UID: \"routecraft.carddav.uid\",\n  /** DAV object URL of a contact. */\n  URL: \"routecraft.carddav.url\",\n  /** DAV ETag of a contact. */\n  ETAG: \"routecraft.carddav.etag\",\n  /** Named account a contact was read from. */\n  ACCOUNT: \"routecraft.carddav.account\",\n  /** Write receipt: true when the write created a new contact, false when it updated one. */\n  CREATED: \"routecraft.carddav.created\",\n} as const satisfies Record<string, `routecraft.carddav.${string}`>;\n\ndeclare module \"@routecraft/routecraft\" {\n  interface RoutecraftHeaders {\n    /** vCard UID of a contact. */\n    [CarddavHeaders.UID]?: string;\n    /** DAV object URL of a contact. */\n    [CarddavHeaders.URL]?: string;\n    /** DAV ETag of a contact. */\n    [CarddavHeaders.ETAG]?: string;\n    /** Named account a contact was read from. */\n    [CarddavHeaders.ACCOUNT]?: string;\n    /** Write receipt: true when the write created a new contact, false when it updated one. */\n    [CarddavHeaders.CREATED]?: boolean;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Minimal DAV driver surface (subset of tsdav used by the adapter)\n// ---------------------------------------------------------------------------\n\n/** Address book collection as returned by the driver. */\nexport interface DAVAddressBookLike {\n  url: string;\n  displayName?: string | Record<string, unknown>;\n}\n\n/** A single vCard object as returned by the driver. */\nexport interface DAVVCardLike {\n  url: string;\n  etag?: string;\n  data?: string;\n}\n\n/**\n * The subset of a tsdav client the CardDAV adapter calls. Declaring our own\n * surface keeps the adapter `any`-free (tsdav types `data` as `any`) and lets\n * tests substitute a lightweight fake.\n */\nexport interface CarddavDriverClient {\n  fetchAddressBooks(params?: {\n    account?: unknown;\n  }): Promise<DAVAddressBookLike[]>;\n  fetchVCards(params: {\n    addressBook: DAVAddressBookLike;\n  }): Promise<DAVVCardLike[]>;\n  createVCard(params: {\n    addressBook: DAVAddressBookLike;\n    vCardString: string;\n    filename: string;\n  }): Promise<Response>;\n  updateVCard(params: { vCard: DAVVCardLike }): Promise<Response>;\n  deleteVCard(params: { vCard: DAVVCardLike }): Promise<Response>;\n}\n\n// ---------------------------------------------------------------------------\n// Client manager access\n// ---------------------------------------------------------------------------\n\n/**\n * Get the CarddavClientManager from the context, or null when no `carddav`\n * config was provided.\n */\nexport function getClientManager(\n  context: CraftContext | undefined,\n): CarddavClientManager | null {\n  if (!context) return null;\n  return (\n    (context.getStore(CARDDAV_CLIENT_MANAGER) as\n      CarddavClientManager | undefined) ?? null\n  );\n}\n\n/** Get the CarddavClientManager, throwing RC5003 when it is absent. */\nexport function requireClientManager(\n  context: CraftContext | undefined,\n): CarddavClientManager {\n  const manager = getClientManager(context);\n  if (!manager) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        \"CardDAV adapter requires carddav configuration. Add it via \" +\n        \"defineConfig({ carddav: { accounts: { default: { username, appPassword } } } }).\",\n    });\n  }\n  return manager;\n}\n\n// ---------------------------------------------------------------------------\n// Address book resolution\n// ---------------------------------------------------------------------------\n\nfunction displayNameOf(book: DAVAddressBookLike): string | undefined {\n  const name = book.displayName;\n  if (typeof name === \"string\") return name;\n  return undefined;\n}\n\n/**\n * Pick the target address book: the one whose display name matches `wanted`\n * (case-insensitive), else the first book. Throws RC5014 when none exist or the\n * requested name is not found.\n */\nexport function selectAddressBook(\n  books: DAVAddressBookLike[],\n  wanted: string | undefined,\n): DAVAddressBookLike {\n  if (books.length === 0) {\n    throw rcError(\"RC5014\", undefined, {\n      message: \"CardDAV account has no address books.\",\n    });\n  }\n  if (!wanted) return books[0] as DAVAddressBookLike;\n  const target = wanted.toLowerCase();\n  const match = books.find(\n    (book) => displayNameOf(book)?.toLowerCase() === target,\n  );\n  if (!match) {\n    const available = books\n      .map((book) => displayNameOf(book) ?? book.url)\n      .join(\", \");\n    throw rcError(\"RC5014\", undefined, {\n      message: `CardDAV address book \"${wanted}\" not found. Available: ${available}.`,\n    });\n  }\n  return match;\n}\n\n// ---------------------------------------------------------------------------\n// Error mapping\n// ---------------------------------------------------------------------------\n\n/** Map a thrown driver error (login, network) to a RoutecraftError. */\nexport function throwCarddavError(error: unknown, operation: string): never {\n  if (error instanceof RoutecraftError) throw error;\n  const message = error instanceof Error ? error.message : String(error);\n  const lower = message.toLowerCase();\n  const cause = error instanceof Error ? error : undefined;\n  if (\n    lower.includes(\"401\") ||\n    lower.includes(\"unauthor\") ||\n    lower.includes(\"authentication\") ||\n    lower.includes(\"credential\")\n  ) {\n    throw rcError(\"RC5012\", cause, {\n      message: `CardDAV ${operation} failed: ${message}`,\n    });\n  }\n  throw rcError(\"RC5010\", cause, {\n    message: `CardDAV ${operation} failed: ${message}`,\n  });\n}\n\n/** Map a non-OK DAV HTTP response to a RoutecraftError. No-op when ok. */\nexport function assertResponseOk(response: Response, operation: string): void {\n  if (response.ok) return;\n  const status = response.status;\n  if (status === 401) {\n    throw rcError(\"RC5012\", undefined, {\n      message: `CardDAV ${operation} failed: authentication rejected (401). Check the Apple ID and app-specific password.`,\n    });\n  }\n  if (status === 403) {\n    throw rcError(\"RC5015\", undefined, {\n      message: `CardDAV ${operation} failed: permission denied (403).`,\n    });\n  }\n  if (status === 404) {\n    throw rcError(\"RC5014\", undefined, {\n      message: `CardDAV ${operation} failed: resource not found (404).`,\n    });\n  }\n  if (status === 412) {\n    throw rcError(\"RC5030\", undefined, {\n      message: `CardDAV ${operation} failed: ETag precondition failed (412). The contact changed on the server; re-read before updating.`,\n    });\n  }\n  if (status === 429) {\n    throw rcError(\"RC5013\", undefined, {\n      message: `CardDAV ${operation} failed: rate limited (429).`,\n    });\n  }\n  throw rcError(\"RC5001\", undefined, {\n    message: `CardDAV ${operation} failed with HTTP ${status}.`,\n  });\n}\n","import { registerConfigApplier } from \"../../config-applier.ts\";\nimport type { StoreRegistry } from \"../../context.ts\";\nimport { CarddavClientManager } from \"./client-manager.ts\";\nimport { CARDDAV_CLIENT_MANAGER } from \"./shared.ts\";\nimport type { CarddavContextConfig } from \"./types.ts\";\n\ndeclare module \"@routecraft/routecraft\" {\n  interface CraftConfig {\n    /** CardDAV adapter configuration with named accounts */\n    carddav?: CarddavContextConfig;\n  }\n}\n\n/**\n * Register the `carddav` config key so `defineConfig({ carddav: {...} })`\n * constructs the shared {@link CarddavClientManager} during `initPlugins()`\n * and drains it during plugin teardown (reverse plugin order, so user\n * plugins tear down first). Loaded as a side-effect import from\n * `packages/routecraft/src/index.ts`. Keeps the core context free of\n * CardDAV adapter knowledge.\n */\nregisterConfigApplier(\"carddav\", (options) => {\n  let manager: CarddavClientManager | undefined;\n  return {\n    apply(ctx) {\n      manager = new CarddavClientManager(options);\n      ctx.setStore(CARDDAV_CLIENT_MANAGER as keyof StoreRegistry, manager);\n    },\n    async teardown() {\n      await manager?.drain();\n    },\n  };\n});\n","/// <reference types=\"bun-types\" />\nimport { createRequire } from \"node:module\";\nimport { loadOptionalPeer } from \"../../adapters/shared/optional-peer.ts\";\nimport { rcError } from \"../../error.ts\";\nimport type { SqliteDatabaseConstructor } from \"./types.ts\";\n\nexport type {\n  SqliteDatabase,\n  SqliteDatabaseConstructor,\n  SqliteStatement,\n} from \"./types.ts\";\n\n/**\n * Which driver backs a resolved connection. Surfaced so the store factory\n * can log what a deployment actually got, and so tests can assert the split\n * rather than infer it.\n */\nexport type SqliteDriverName = \"bun:sqlite\" | \"better-sqlite3\";\n\nexport interface ResolvedSqliteDriver {\n  readonly name: SqliteDriverName;\n  readonly Database: SqliteDatabaseConstructor;\n}\n\n/**\n * Resolve a synchronous SQLite driver for the current runtime.\n *\n * `bun:sqlite` under Bun, `better-sqlite3` as an optional peer under Node,\n * and an in-memory fallback with a loud warning when neither is available.\n * The default is durable wherever the runtime allows, because surviving a\n * restart is the feature's whole promise.\n *\n * ## Why not `node:sqlite`\n *\n * It is ruled out by the engines floor rather than by its API:\n *\n * | Runtime | `bun:sqlite` | `node:sqlite` | `better-sqlite3` |\n * | --- | --- | --- | --- |\n * | Bun >= 1.1 (our floor) | built in | n/a | installable |\n * | Node 22.0 - 22.4 (our floor) | n/a | does not exist | installable |\n * | Node 22.5+ | n/a | behind `--experimental-sqlite` | installable |\n * | Node 24+ | n/a | unflagged | installable |\n *\n * Core's floor is Node 22.0, so across the supported range `node:sqlite`\n * either does not exist or needs a CLI flag the framework cannot set on the\n * user's behalf. That inverts the naive preference order for the Node arm\n * and leaves `better-sqlite3` as the only Node option that works on the\n * whole range.\n *\n * ## Graduation condition for `node:sqlite`\n *\n * `node:sqlite` becomes the preferred Node driver, ahead of\n * `better-sqlite3`, once `@routecraft/routecraft`'s `engines.node` floor\n * moves past the first Node major where it runs unflagged (Node 24). At\n * that point it is a built-in with no install step and no native rebuild,\n * which beats an optional peer on every axis; `better-sqlite3` stays\n * supported as a fallback for anyone below the new floor. Revisit this\n * function and nothing else: the store talks to {@link SqliteDatabase},\n * not to a driver.\n *\n * @param consumer - Names the subsystem asking, so an absent peer names\n *   what wanted it (\"deferral store (sqlite)\", \"telemetry (sqlite)\")\n *   rather than reporting a generic sqlite failure. Used ONLY to build the\n *   default loaders: a caller that supplies its own `loaders` owns the\n *   naming inside them, and this argument then has no effect.\n * @param loaders - Injection point for tests, which need to simulate a\n *   runtime that lacks a driver without leaving the runtime they run on.\n * @returns The resolved driver for this runtime.\n * @throws RC5017 when running under Node and `better-sqlite3` is absent.\n *   Whether that is fatal is the store factory's call, not this\n *   function's: an unconfigured context falls back to memory with a\n *   warning, while a context that named a store path fails to start,\n *   because silently degrading a deployment that asked for durability is\n *   worse than refusing to run.\n */\nexport async function resolveSqliteDriver(\n  consumer: string,\n  loaders: SqliteDriverLoaders = defaultLoaders(consumer),\n): Promise<ResolvedSqliteDriver> {\n  if (isBun()) {\n    return { name: \"bun:sqlite\", Database: await loaders.bun() };\n  }\n  return { name: \"better-sqlite3\", Database: await loaders.node() };\n}\n\n/**\n * Driver loaders. Injectable so a store in another package, or a test\n * exercising the absent-peer arm, supplies its own resolution rather than\n * the runtime's.\n */\nexport interface SqliteDriverLoaders {\n  bun(): Promise<SqliteDatabaseConstructor>;\n  node(): Promise<SqliteDatabaseConstructor>;\n}\n\n/**\n * The real loaders for a named consumer. A factory rather than a constant\n * because the Node arm's RC5017 has to name who wanted the driver.\n *\n * @internal\n */\nexport function defaultLoaders(consumer: string): SqliteDriverLoaders {\n  return {\n    async bun() {\n      // A Bun built-in, not an optional peer: there is no package to install\n      // and no RC5017 to raise, so this is deliberately outside\n      // `loadOptionalPeer`. Under Bun the import always resolves.\n      const mod = await import(\"bun:sqlite\");\n      return (mod as { Database: unknown })\n        .Database as SqliteDatabaseConstructor;\n    },\n    async node() {\n      const mod = await loadOptionalPeer(() => import(\"better-sqlite3\"), {\n        consumer,\n        packageName: \"better-sqlite3\",\n      });\n      assertBetterSqliteRuns(\n        consumer,\n        installedBetterSqliteVersion(),\n        process.versions[\"napi\"],\n      );\n      const ctor = (mod as { default?: unknown }).default ?? mod;\n      return ctor as SqliteDatabaseConstructor;\n    },\n  };\n}\n\n/**\n * Refuse a `better-sqlite3` the running Node cannot load.\n *\n * From 13 its binaries target Node-API 10, which Node ships from 22.14.\n * Core's floor is Node 22.0, and below 22.14 constructing a database does\n * not throw: the addon segfaults the process past every catch. The pairing\n * is therefore refused before the first database opens, with the same\n * RC5017 a missing driver raises, so the stores fall back or fail at start\n * exactly as they do without the peer.\n *\n * @param consumer - The subsystem asking, named in the error.\n * @param version - The installed `better-sqlite3` version.\n * @param nodeApi - The runtime's Node-API version (`process.versions.napi`).\n * @throws RC5017 when `better-sqlite3` is 13 or later and Node-API is below 10.\n * @internal\n */\nexport function assertBetterSqliteRuns(\n  consumer: string,\n  version: string,\n  nodeApi: string | undefined,\n): void {\n  const major = Number.parseInt(version, 10);\n  if (major < 13 || Number(nodeApi ?? 0) >= 10) return;\n  throw rcError(\"RC5017\", undefined, {\n    message:\n      `${consumer} cannot use better-sqlite3 ${version} on Node ${process.versions.node}: ` +\n      \"it needs Node 22.14 or later. Upgrade Node, or install better-sqlite3 12: \" +\n      \"bun add better-sqlite3@12 (or npm install better-sqlite3@12).\",\n  });\n}\n\nfunction installedBetterSqliteVersion(): string {\n  const require = createRequire(import.meta.url);\n  return (require(\"better-sqlite3/package.json\") as { version: string })\n    .version;\n}\n\n/** @internal */\nexport function isBun(): boolean {\n  return typeof process.versions[\"bun\"] === \"string\";\n}\n","import { isAbsolute, resolve } from \"node:path\";\nimport type { SqliteDatabase } from \"./types.ts\";\n\n/**\n * A database file path as the drivers want it: absolute, or the\n * `\":memory:\"` sentinel untouched.\n *\n * Shared because a store that resolves the path differently in two places\n * (an existence probe and the open beside it) reports an empty store while\n * a database sits on disk holding its records.\n */\nexport function resolveDatabasePath(path: string): string {\n  if (path === \":memory:\") return path;\n  return isAbsolute(path) ? path : resolve(process.cwd(), path);\n}\n\n/**\n * Whether a driver error is SQLite reporting lock contention rather than a\n * permanent fault. Both drivers surface it in the message; better-sqlite3\n * additionally sets a `code`.\n *\n * Shared because this is knowledge about the drivers rather than about any\n * one store, and a store that answers a transient lock as a permanent\n * failure sends its caller to the wrong remedy.\n */\nexport function isSqliteBusy(cause: unknown): boolean {\n  const code = (cause as { code?: unknown } | null)?.code;\n  if (typeof code === \"string\" && /^SQLITE_BUSY|^SQLITE_LOCKED/.test(code)) {\n    return true;\n  }\n  const message = cause instanceof Error ? cause.message : String(cause);\n  return /database is locked|database table is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(\n    message,\n  );\n}\n\n/**\n * Which store a database file belongs to, stamped into\n * `PRAGMA application_id` so a store can tell its own file from another's.\n *\n * Every store in the repository writes into `.routecraft/` and versions\n * itself through `PRAGMA user_version`, which is one integer per file. Two\n * stores pointed at one path therefore cannot both be satisfied, and\n * without an identity the loser can only report the version it found,\n * which reads as \"upgrade your build\" for a file no build will ever\n * understand.\n *\n * The values are the ASCII of a four-letter tag, which is what\n * `application_id` is conventionally used for and what `file` and\n * `sqlite3` will show an operator.\n */\nexport const SQLITE_APPLICATION_IDS = {\n  /** \"RCDE\", the deferral store. */\n  deferral: 0x5243_4445,\n  /** \"RCSE\", the agent session store. */\n  session: 0x5243_5345,\n} as const;\n\n/** A stamped identity, or 0 for a file no build has claimed. */\nexport type SqliteApplicationId =\n  (typeof SQLITE_APPLICATION_IDS)[keyof typeof SQLITE_APPLICATION_IDS] | 0;\n\n/** The tag a stamped file carries, for naming it in a refusal. */\nexport function sqliteApplicationName(id: number): string | undefined {\n  for (const [name, value] of Object.entries(SQLITE_APPLICATION_IDS)) {\n    if (value === id) return name;\n  }\n  return undefined;\n}\n\n/** What went wrong in {@link migrateSqlite}, for the consumer's own error. */\nexport interface SqliteMigrationFailure {\n  /**\n   * `foreign` is a file belonging to a different store, which is a\n   * configuration mistake rather than a version problem; `downgrade` is a\n   * file written by a newer build of THIS store, which no migration can\n   * repair; `migrate` is a statement that failed.\n   */\n  readonly kind: \"foreign\" | \"downgrade\" | \"migrate\";\n  readonly cause: unknown;\n  /** The version the file is on. */\n  readonly current: number;\n  /**\n   * The file's own tables, so a refusal can say what the file actually is\n   * rather than only what it is not. Empty for a file with no schema.\n   */\n  readonly tables: readonly string[];\n  /**\n   * The identity stamped on the file: another store's id, or 0 when the\n   * file predates stamping and was identified by its tables instead.\n   */\n  readonly applicationId: number;\n}\n\n/**\n * Bring a database's schema up to date from `PRAGMA user_version`, inside\n * one transaction so an interrupted upgrade leaves the file on its previous\n * version rather than half way between two.\n *\n * The version is read INSIDE the write transaction. Two processes starting\n * against one file would otherwise both read version 0, both try to create\n * the tables, and the loser fail on an existing table, which for a store\n * that falls back to memory means losing durability at exactly the moment\n * a deployment restarts.\n *\n * Before any of that, the file is checked to be this store's own. A store\n * adopts a file only when the file is empty, or already carries this\n * store's identity, or predates stamping and holds this store's own table.\n * Anything else is refused as `foreign`, because two stores sharing one\n * path is a configuration mistake that no migration can resolve.\n *\n * @param options.schemaVersion - The version this build understands.\n * @param options.migrations - Forward-only statements; index `n` migrates\n *   version `n` to `n + 1`, so a fresh file runs them all.\n * @param options.applicationId - This store's identity, stamped into\n *   `PRAGMA application_id` on adoption.\n * @param options.identityTable - A table this store's schema always has,\n *   used to adopt files written before stamping existed.\n * @param options.onFailure - Builds the store's own error for a failure.\n *   The returned error is thrown as it is, so each store keeps its code.\n */\nexport function migrateSqlite(\n  db: SqliteDatabase,\n  options: {\n    schemaVersion: number;\n    migrations: ReadonlyArray<string>;\n    applicationId: SqliteApplicationId;\n    identityTable: string;\n    onFailure: (failure: SqliteMigrationFailure) => Error;\n  },\n): void {\n  const { schemaVersion, migrations, applicationId, identityTable, onFailure } =\n    options;\n  let current = 0;\n  // The downgrade error is built inside the transaction and rethrown\n  // unwrapped by the catch below, which cannot otherwise tell it from a\n  // statement that failed.\n  let refusal: Error | undefined;\n  try {\n    db.exec(\"BEGIN IMMEDIATE\");\n    const row = db.prepare(\"PRAGMA user_version\").get() as\n      { user_version?: number } | undefined;\n    current = row?.user_version ?? 0;\n    const tables = tablesIn(db);\n    const empty = schemaIsEmpty(db);\n    const stamped =\n      (\n        db.prepare(\"PRAGMA application_id\").get() as\n          { application_id?: number } | undefined\n      )?.application_id ?? 0;\n    // Ownership is settled before the version is looked at. A file\n    // belonging to another store is on ITS version line, so reporting that\n    // number as a downgrade tells the reader to find a newer build of a\n    // store that will never open this file.\n    if (stamped !== 0 && stamped !== applicationId) {\n      refusal = onFailure({\n        kind: \"foreign\",\n        cause: undefined,\n        current,\n        tables,\n        applicationId: stamped,\n      });\n      throw refusal;\n    }\n    // An unstamped file predates stamping, so its schema is the only\n    // evidence. A file with none at all is ours to claim; one already\n    // carrying our table is ours to adopt; anything else is not.\n    //\n    // Emptiness is decided over every schema object rather than over\n    // tables, because a file holding only views, indexes or triggers has no\n    // tables and still belongs to somebody. The table subset stays the\n    // evidence for ownership, since identityTable is a table.\n    if (stamped === 0 && !empty && !tables.includes(identityTable)) {\n      refusal = onFailure({\n        kind: \"foreign\",\n        cause: undefined,\n        current,\n        tables,\n        applicationId: 0,\n      });\n      throw refusal;\n    }\n    // The downgrade guard has to run BEFORE the up-to-date check, not\n    // after: a file written by a newer build satisfies both conditions, so\n    // ordering it second made it unreachable and turned a rollback into a\n    // misleading write failure on first use.\n    if (current > schemaVersion) {\n      refusal = onFailure({\n        kind: \"downgrade\",\n        cause: undefined,\n        current,\n        tables,\n        applicationId: stamped,\n      });\n      throw refusal;\n    }\n    if (stamped !== applicationId) {\n      // Interpolated rather than bound: PRAGMA takes no parameters. The\n      // value is a module constant, never user input.\n      db.exec(`PRAGMA application_id = ${applicationId}`);\n    }\n    if (current === schemaVersion) {\n      db.exec(\"COMMIT\");\n      return;\n    }\n    for (let version = current; version < schemaVersion; version++) {\n      db.exec(migrations[version] as string);\n    }\n    // Interpolated rather than bound: PRAGMA does not accept parameters.\n    // The value is the caller's module constant, never user input.\n    db.exec(`PRAGMA user_version = ${schemaVersion}`);\n    db.exec(\"COMMIT\");\n  } catch (cause) {\n    try {\n      db.exec(\"ROLLBACK\");\n    } catch {\n      // BEGIN itself failed; there is no transaction to roll back.\n    }\n    if (refusal !== undefined && cause === refusal) throw refusal;\n    throw onFailure({\n      kind: \"migrate\",\n      cause,\n      current,\n      tables: [],\n      applicationId: 0,\n    });\n  }\n}\n\n/**\n * Whether the file carries no schema of its own, which is what makes it\n * safe to claim. Counted over every object type, so a file holding only a\n * view, an index or a trigger is not mistaken for an unused one.\n */\nfunction schemaIsEmpty(db: SqliteDatabase): boolean {\n  const row = db\n    .prepare(\n      \"SELECT count(*) AS objects FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'\",\n    )\n    .get() as { objects: number };\n  return row.objects === 0;\n}\n\n/**\n * The file's own table names, the evidence for ownership and for naming\n * what a foreign file actually holds.\n */\nfunction tablesIn(db: SqliteDatabase): string[] {\n  const rows = db\n    .prepare(\n      \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n    )\n    .all() as Array<{ name: string }>;\n  return rows.map((row) => row.name);\n}\n\n/**\n * Say what a foreign file actually is, for the refusal that names it.\n *\n * A stamped file names itself. One that predates stamping is described by\n * its tables, which is the only evidence there is, and is worth printing\n * because it is what an operator sees running `sqlite3` against the file.\n */\nexport function describeSqliteFile(failure: SqliteMigrationFailure): string {\n  const name = sqliteApplicationName(failure.applicationId);\n  if (name !== undefined) return `it belongs to the ${name} store`;\n  if (failure.tables.length === 0) return \"it holds an unrecognised schema\";\n  return `it holds ${failure.tables.join(\", \")}`;\n}\n","/**\n * SQLite DDL statements for the telemetry database.\n *\n * Tables:\n * - events: All framework events (context, route, exchange, step, operation, plugin, error)\n * - routes: Route registration and lifecycle tracking\n * - exchanges: Exchange lifecycle tracking with duration and error info\n */\n\n/** Create the events table for storing all framework events. */\nexport const CREATE_EVENTS_TABLE = `\nCREATE TABLE IF NOT EXISTS events (\n  id INTEGER PRIMARY KEY AUTOINCREMENT,\n  timestamp TEXT NOT NULL,\n  context_id TEXT NOT NULL,\n  event_name TEXT NOT NULL,\n  details TEXT NOT NULL,\n  exchange_id TEXT,\n  correlation_id TEXT,\n  created_at TEXT NOT NULL DEFAULT (datetime('now'))\n)`;\n\n/** Create the routes table for tracking route lifecycle. */\nexport const CREATE_ROUTES_TABLE = `\nCREATE TABLE IF NOT EXISTS routes (\n  id TEXT NOT NULL,\n  context_id TEXT NOT NULL,\n  registered_at TEXT NOT NULL,\n  status TEXT NOT NULL DEFAULT 'registered',\n  PRIMARY KEY (id, context_id)\n)`;\n\n/** Create the exchanges table for tracking exchange lifecycle. */\nexport const CREATE_EXCHANGES_TABLE = `\nCREATE TABLE IF NOT EXISTS exchanges (\n  id TEXT NOT NULL,\n  route_id TEXT NOT NULL,\n  context_id TEXT NOT NULL,\n  correlation_id TEXT NOT NULL,\n  status TEXT NOT NULL DEFAULT 'started',\n  started_at TEXT NOT NULL,\n  completed_at TEXT,\n  duration_ms INTEGER,\n  error TEXT,\n  PRIMARY KEY (id, context_id)\n)`;\n\n/** Index on events.event_name for filtered queries. */\nexport const CREATE_EVENTS_EVENT_NAME_INDEX = `\nCREATE INDEX IF NOT EXISTS idx_events_event_name ON events(event_name)`;\n\n/** Index on events.context_id for context-scoped queries. */\nexport const CREATE_EVENTS_CONTEXT_ID_INDEX = `\nCREATE INDEX IF NOT EXISTS idx_events_context_id ON events(context_id)`;\n\n/** Index on exchanges.route_id for route-scoped queries. */\nexport const CREATE_EXCHANGES_ROUTE_ID_INDEX = `\nCREATE INDEX IF NOT EXISTS idx_exchanges_route_id ON exchanges(route_id)`;\n\n/** Index on exchanges.status for filtered queries. */\nexport const CREATE_EXCHANGES_STATUS_INDEX = `\nCREATE INDEX IF NOT EXISTS idx_exchanges_status ON exchanges(status)`;\n\n/** Index on exchanges.started_at for time-bucketed queries. */\nexport const CREATE_EXCHANGES_STARTED_AT_INDEX = `\nCREATE INDEX IF NOT EXISTS idx_exchanges_started_at ON exchanges(started_at)`;\n\n/** Composite index on exchanges(route_id, started_at) for per-route time queries. */\nexport const CREATE_EXCHANGES_ROUTE_STARTED_INDEX = `\nCREATE INDEX IF NOT EXISTS idx_exchanges_route_started ON exchanges(route_id, started_at)`;\n\n/** Index on exchanges.correlation_id for correlation chain lookups. */\nexport const CREATE_EXCHANGES_CORRELATION_INDEX = `\nCREATE INDEX IF NOT EXISTS idx_exchanges_correlation_id ON exchanges(correlation_id)`;\n\n/** Index on events.exchange_id for exchange-scoped event lookups. */\nexport const CREATE_EVENTS_EXCHANGE_ID_INDEX = `\nCREATE INDEX IF NOT EXISTS idx_events_exchange_id ON events(exchange_id)`;\n\n/** Index on events.correlation_id for correlation chain event lookups. */\nexport const CREATE_EVENTS_CORRELATION_ID_INDEX = `\nCREATE INDEX IF NOT EXISTS idx_events_correlation_id ON events(correlation_id)`;\n\n/** Create the exchange_snapshots table for storing exchange headers and body. */\nexport const CREATE_EXCHANGE_SNAPSHOTS_TABLE = `\nCREATE TABLE IF NOT EXISTS exchange_snapshots (\n  exchange_id TEXT NOT NULL,\n  context_id TEXT NOT NULL,\n  headers TEXT NOT NULL,\n  body TEXT,\n  truncated INTEGER NOT NULL DEFAULT 0,\n  captured_at TEXT NOT NULL DEFAULT (datetime('now')),\n  PRIMARY KEY (exchange_id, context_id)\n)`;\n\n/** All DDL statements in execution order. */\nexport const ALL_DDL = [\n  CREATE_EVENTS_TABLE,\n  CREATE_ROUTES_TABLE,\n  CREATE_EXCHANGES_TABLE,\n  CREATE_EVENTS_EVENT_NAME_INDEX,\n  CREATE_EVENTS_CONTEXT_ID_INDEX,\n  CREATE_EXCHANGES_ROUTE_ID_INDEX,\n  CREATE_EXCHANGES_STATUS_INDEX,\n  CREATE_EXCHANGES_STARTED_AT_INDEX,\n  CREATE_EXCHANGES_ROUTE_STARTED_INDEX,\n  CREATE_EXCHANGES_CORRELATION_INDEX,\n  CREATE_EVENTS_EXCHANGE_ID_INDEX,\n  CREATE_EVENTS_CORRELATION_ID_INDEX,\n  CREATE_EXCHANGE_SNAPSHOTS_TABLE,\n] as const;\n","import { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport {\n  type SqliteDriverLoaders,\n  resolveSqliteDriver,\n} from \"../shared/sqlite/driver.ts\";\nimport type { SqliteDatabase } from \"../shared/sqlite/types.ts\";\nimport { resolveDatabasePath } from \"../shared/sqlite/database.ts\";\nimport { ALL_DDL } from \"./schema.ts\";\nimport type { TelemetryLogger } from \"./types.ts\";\n\n/**\n * Default path for the telemetry database, relative to cwd.\n */\nconst DEFAULT_DB_PATH = \".routecraft/telemetry.db\";\n\n/**\n * Options accepted by {@link SqliteConnection.open}.\n */\nexport interface SqliteConnectionOptions {\n  /** Path to the SQLite database file. */\n  dbPath?: string;\n  /** Enable WAL mode (defaults to `true`). */\n  walMode?: boolean;\n  /**\n   * Maximum number of exchange rows to retain.\n   * Older rows are pruned on startup and periodically.\n   * Set to `0` to disable exchange pruning. Defaults to `0` (disabled).\n   */\n  maxExchanges?: number;\n  /**\n   * Maximum number of event rows to retain.\n   * Older rows are pruned on startup and periodically.\n   * Set to `0` to disable event pruning. Defaults to `0` (disabled).\n   */\n  maxEvents?: number;\n}\n\n/**\n * Names this subsystem in the absent-peer error, so a Node deployment\n * missing `better-sqlite3` reads which feature asked for it.\n */\nconst SQLITE_CONSUMER = \"telemetry (sqlite)\";\n\n/**\n * Default prune interval in milliseconds (60 seconds).\n */\nconst PRUNE_INTERVAL_MS = 60_000;\n\n/**\n * Shared SQLite connection for telemetry.\n *\n * Encapsulates database opening, WAL mode, DDL execution, and data\n * retention pruning. Pruning is a storage-layer concern and is managed\n * entirely within this class.\n *\n * Used by both {@link SqliteSpanProcessor} and {@link SqliteEventWriter}.\n *\n * Backed by whichever synchronous driver the runtime provides:\n * `bun:sqlite` under Bun, `better-sqlite3` as an optional peer under Node.\n * When neither resolves, {@link open} returns `null` and the calling plugin\n * disables the SQLite path with a warn log, leaving an OTLP exporter\n * configured via `telemetry({ tracerProvider })` as the way to keep\n * telemetry flowing.\n */\nexport class SqliteConnection {\n  readonly db: TelemetryDatabase;\n  readonly logger: TelemetryLogger | undefined;\n  private pruneTimer: ReturnType<typeof setInterval> | undefined;\n\n  private constructor(db: TelemetryDatabase, logger?: TelemetryLogger) {\n    this.db = db;\n    this.logger = logger;\n  }\n\n  /**\n   * Open (or create) the telemetry database.\n   *\n   * When `maxExchanges` or `maxEvents` are greater than 0, the connection\n   * prunes on startup and schedules periodic pruning automatically.\n   * The timer is stopped when {@link close} is called.\n   *\n   * @param options - Database path and retention limits.\n   * @param logger - Optional telemetry logger for the failure paths.\n   * @param loaders - Driver loader injection point for tests.\n   * @returns A connection, or `null` when no driver resolved or the\n   *   database could not be opened.\n   */\n  static async open(\n    options?: SqliteConnectionOptions,\n    logger?: TelemetryLogger,\n    loaders?: SqliteDriverLoaders,\n  ): Promise<SqliteConnection | null> {\n    const dbPathRaw = options?.dbPath ?? DEFAULT_DB_PATH;\n    const dbPath = resolveDatabasePath(dbPathRaw);\n    const walMode = options?.walMode !== false;\n\n    let Database: TelemetryDatabaseConstructor;\n    try {\n      const driver = await resolveSqliteDriver(SQLITE_CONSUMER, loaders);\n      Database = driver.Database as TelemetryDatabaseConstructor;\n    } catch (err) {\n      // Loud on both arms. Under Node the cause is a missing\n      // `better-sqlite3` (RC5017 carries the install hint); under Bun a\n      // throw means a broken install. Either way the user configured\n      // `telemetry.sqlite` and is not getting it, which is not something to\n      // swallow.\n      logger?.warn(\n        { err },\n        \"No SQLite driver available; the telemetry SQLite sink is disabled. Configure an OTLP exporter, or install the driver named in the error.\",\n      );\n      return null;\n    }\n\n    try {\n      mkdirSync(dirname(dbPath), { recursive: true });\n\n      const db = new Database(dbPath);\n\n      if (walMode) {\n        db.exec(\"PRAGMA journal_mode = WAL\");\n      }\n\n      for (const ddl of ALL_DDL) {\n        db.exec(ddl);\n      }\n\n      const conn = new SqliteConnection(db, logger);\n      conn.startPruning(options?.maxExchanges ?? 0, options?.maxEvents ?? 0);\n      return conn;\n    } catch (err) {\n      logger?.warn({ err }, \"Failed to open telemetry SQLite database\");\n      return null;\n    }\n  }\n\n  /**\n   * Run an initial prune and schedule periodic pruning if limits are set.\n   */\n  private startPruning(maxExchanges: number, maxEvents: number): void {\n    if (maxExchanges <= 0 && maxEvents <= 0) return;\n\n    this.prune(maxExchanges, maxEvents);\n    this.pruneTimer = setInterval(\n      () => this.prune(maxExchanges, maxEvents),\n      PRUNE_INTERVAL_MS,\n    );\n    this.pruneTimer.unref();\n  }\n\n  /**\n   * Delete old rows beyond the configured retention limits.\n   * Uses ROWID ordering for efficient deletion without scanning timestamps.\n   */\n  private prune(maxExchanges: number, maxEvents: number): void {\n    try {\n      if (maxExchanges > 0) {\n        this.db\n          .prepare(\n            `DELETE FROM exchanges WHERE ROWID <= (\n              SELECT ROWID FROM exchanges ORDER BY ROWID DESC LIMIT 1 OFFSET ?\n            )`,\n          )\n          .run(maxExchanges);\n\n        // Remove orphaned snapshots whose exchange was pruned\n        this.db.exec(\n          `DELETE FROM exchange_snapshots\n           WHERE exchange_id NOT IN (SELECT id FROM exchanges)`,\n        );\n      }\n      if (maxEvents > 0) {\n        this.db\n          .prepare(\n            `DELETE FROM events WHERE id <= (\n              SELECT id FROM events ORDER BY id DESC LIMIT 1 OFFSET ?\n            )`,\n          )\n          .run(maxEvents);\n      }\n    } catch {\n      // Pruning is best-effort; do not disrupt the running application\n    }\n  }\n\n  close(): void {\n    if (this.pruneTimer) {\n      clearInterval(this.pruneTimer);\n      this.pruneTimer = undefined;\n    }\n    try {\n      this.db.close();\n    } catch {\n      // Ignore close errors during teardown\n    }\n  }\n}\n\n/**\n * The shared minimal surface plus the one member telemetry needs on top:\n * batched event inserts run inside a transaction. Both drivers expose it\n * with this shape.\n */\ninterface TelemetryDatabase extends SqliteDatabase {\n  transaction<T>(fn: (...args: T[]) => void): (...args: T[]) => void;\n}\n\ntype TelemetryDatabaseConstructor = new (\n  filename: string,\n  options?: { readonly?: boolean; create?: boolean },\n) => TelemetryDatabase;\n\nexport type { TelemetryDatabase };\n","import type { SqliteConnection } from \"./sqlite-connection.ts\";\nimport type { TelemetryLogger } from \"./types.ts\";\n\n/**\n * Semantic attribute keys used by the telemetry plugin to tag spans.\n */\nexport const ATTR = {\n  SPAN_KIND: \"routecraft.span.kind\",\n  ROUTE_ID: \"routecraft.route.id\",\n  CONTEXT_ID: \"routecraft.context.id\",\n  EXCHANGE_ID: \"routecraft.exchange.id\",\n  CORRELATION_ID: \"routecraft.correlation.id\",\n  DURATION_MS: \"routecraft.duration_ms\",\n  DROP_REASON: \"routecraft.drop.reason\",\n  DROPPED: \"routecraft.dropped\",\n  ERROR: \"routecraft.error\",\n  OPERATION_TYPE: \"routecraft.operation.type\",\n  ADAPTER_ID: \"routecraft.adapter.id\",\n} as const;\n\n/**\n * Span kind values used to identify what a span represents.\n */\nexport const SPAN_KIND = {\n  ROUTE: \"route\",\n  EXCHANGE: \"exchange\",\n  OPERATION: \"operation\",\n} as const;\n\n/**\n * Duck-typed OTel ReadableSpan for use in `onEnd`.\n * Only the fields SqliteSpanProcessor actually reads.\n */\ninterface OTelReadableSpan {\n  name: string;\n  attributes: Record<string, unknown>;\n  status: { code: number; message?: string };\n  startTime: [number, number]; // [seconds, nanoseconds]\n  endTime: [number, number];\n}\n\n/**\n * Duck-typed OTel Span for use in `onStart`.\n */\ninterface OTelSpan {\n  setAttribute(key: string, value: unknown): void;\n  attributes?: Record<string, unknown>;\n  spanContext?(): { traceId: string; spanId: string };\n}\n\n/**\n * SQLite-backed SpanProcessor that writes route and exchange lifecycle\n * data to the `routes` and `exchanges` tables.\n *\n * Implements the OTel SpanProcessor interface via duck typing so\n * `@opentelemetry/sdk-trace-base` is not required at runtime for\n * the default SQLite path.\n *\n * The plugin calls `onStart`/`onEnd` directly from event handlers;\n * it also works when registered with a `BasicTracerProvider` for\n * external export scenarios.\n */\nexport class SqliteSpanProcessor {\n  private readonly logger: TelemetryLogger | undefined;\n  private readonly upsertRouteStmt: { run(...params: unknown[]): unknown };\n  private readonly updateRouteStatusStmt: {\n    run(...params: unknown[]): unknown;\n  };\n  private readonly insertExchangeStmt: { run(...params: unknown[]): unknown };\n  private readonly updateExchangeCompletedStmt: {\n    run(...params: unknown[]): unknown;\n  };\n  private readonly updateExchangeFailedStmt: {\n    run(...params: unknown[]): unknown;\n  };\n  private readonly updateExchangeDroppedStmt: {\n    run(...params: unknown[]): unknown;\n  };\n\n  private readonly upsertSnapshotStmt: { run(...params: unknown[]): unknown };\n\n  constructor(connection: SqliteConnection) {\n    this.logger = connection.logger;\n\n    this.upsertSnapshotStmt = connection.db.prepare(\n      `INSERT INTO exchange_snapshots (exchange_id, context_id, headers, body, truncated)\n       VALUES (?, ?, ?, ?, ?)\n       ON CONFLICT(exchange_id, context_id) DO UPDATE\n         SET headers = excluded.headers,\n             body = excluded.body,\n             truncated = excluded.truncated,\n             captured_at = datetime('now')`,\n    );\n\n    this.upsertRouteStmt = connection.db.prepare(\n      `INSERT INTO routes (id, context_id, registered_at, status)\n       VALUES (?, ?, ?, 'registered')\n       ON CONFLICT(id, context_id) DO UPDATE SET status = 'registered'`,\n    );\n\n    this.updateRouteStatusStmt = connection.db.prepare(\n      \"UPDATE routes SET status = ? WHERE id = ? AND context_id = ?\",\n    );\n\n    this.insertExchangeStmt = connection.db.prepare(\n      `INSERT OR IGNORE INTO exchanges (id, route_id, context_id, correlation_id, status, started_at)\n       VALUES (?, ?, ?, ?, 'started', ?)`,\n    );\n\n    this.updateExchangeCompletedStmt = connection.db.prepare(\n      `UPDATE exchanges SET status = 'completed', completed_at = ?, duration_ms = ?\n       WHERE id = ? AND context_id = ?`,\n    );\n\n    this.updateExchangeFailedStmt = connection.db.prepare(\n      `UPDATE exchanges SET status = 'failed', completed_at = ?, duration_ms = ?, error = ?\n       WHERE id = ? AND context_id = ?`,\n    );\n\n    this.updateExchangeDroppedStmt = connection.db.prepare(\n      `UPDATE exchanges SET status = 'dropped', completed_at = ?, duration_ms = 0, error = ?\n       WHERE id = ? AND context_id = ?`,\n    );\n  }\n\n  // -- Direct API (called by plugin without OTel SDK) --\n\n  writeRoute(routeId: string, contextId: string, registeredAt: string): void {\n    try {\n      this.upsertRouteStmt.run(routeId, contextId, registeredAt);\n    } catch (err) {\n      this.logger?.warn({ err, routeId }, \"Failed to write telemetry route\");\n    }\n  }\n\n  updateRouteStatus(routeId: string, contextId: string, status: string): void {\n    try {\n      this.updateRouteStatusStmt.run(status, routeId, contextId);\n    } catch (err) {\n      this.logger?.warn(\n        { err, routeId, status },\n        \"Failed to update telemetry route status\",\n      );\n    }\n  }\n\n  writeExchange(\n    exchangeId: string,\n    routeId: string,\n    contextId: string,\n    correlationId: string,\n    startedAt: string,\n  ): void {\n    try {\n      this.insertExchangeStmt.run(\n        exchangeId,\n        routeId,\n        contextId,\n        correlationId,\n        startedAt,\n      );\n    } catch (err) {\n      this.logger?.warn(\n        { err, exchangeId, routeId },\n        \"Failed to write telemetry exchange\",\n      );\n    }\n  }\n\n  completeExchange(\n    exchangeId: string,\n    contextId: string,\n    completedAt: string,\n    durationMs: number,\n  ): void {\n    try {\n      this.updateExchangeCompletedStmt.run(\n        completedAt,\n        durationMs,\n        exchangeId,\n        contextId,\n      );\n    } catch (err) {\n      this.logger?.warn(\n        { err, exchangeId },\n        \"Failed to complete telemetry exchange\",\n      );\n    }\n  }\n\n  failExchange(\n    exchangeId: string,\n    contextId: string,\n    completedAt: string,\n    durationMs: number,\n    error: string,\n  ): void {\n    try {\n      this.updateExchangeFailedStmt.run(\n        completedAt,\n        durationMs,\n        error,\n        exchangeId,\n        contextId,\n      );\n    } catch (err) {\n      this.logger?.warn(\n        { err, exchangeId },\n        \"Failed to record telemetry exchange failure\",\n      );\n    }\n  }\n\n  dropExchange(\n    exchangeId: string,\n    contextId: string,\n    droppedAt: string,\n    reason: string,\n  ): void {\n    try {\n      this.updateExchangeDroppedStmt.run(\n        droppedAt,\n        reason,\n        exchangeId,\n        contextId,\n      );\n    } catch (err) {\n      this.logger?.warn(\n        { err, exchangeId },\n        \"Failed to record telemetry exchange drop\",\n      );\n    }\n  }\n\n  writeSnapshot(\n    exchangeId: string,\n    contextId: string,\n    headers: string,\n    body: string | null,\n    truncated: boolean,\n  ): void {\n    try {\n      this.upsertSnapshotStmt.run(\n        exchangeId,\n        contextId,\n        headers,\n        body,\n        truncated ? 1 : 0,\n      );\n    } catch (err) {\n      this.logger?.warn(\n        { err, exchangeId },\n        \"Failed to write exchange snapshot\",\n      );\n    }\n  }\n\n  // -- OTel SpanProcessor interface (duck-typed) --\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- OTel SpanProcessor interface requires this parameter\n  onStart(span: OTelSpan, _parentContext?: unknown): void {\n    const attrs = span.attributes ?? ({} as Record<string, unknown>);\n    const kind = attrs[ATTR.SPAN_KIND] as string | undefined;\n    if (!kind) return;\n\n    const contextId = attrs[ATTR.CONTEXT_ID] as string;\n    const ts = new Date().toISOString();\n\n    if (kind === SPAN_KIND.ROUTE) {\n      const routeId = attrs[ATTR.ROUTE_ID] as string;\n      this.writeRoute(routeId, contextId, ts);\n    } else if (kind === SPAN_KIND.EXCHANGE) {\n      const exchangeId = attrs[ATTR.EXCHANGE_ID] as string;\n      const routeId = attrs[ATTR.ROUTE_ID] as string;\n      const correlationId = attrs[ATTR.CORRELATION_ID] as string;\n      this.writeExchange(exchangeId, routeId, contextId, correlationId, ts);\n    }\n  }\n\n  onEnd(span: OTelReadableSpan): void {\n    const attrs = span.attributes;\n    const kind = attrs[ATTR.SPAN_KIND] as string | undefined;\n    if (!kind) return;\n\n    const contextId = attrs[ATTR.CONTEXT_ID] as string;\n    const ts = new Date().toISOString();\n\n    if (kind === SPAN_KIND.ROUTE) {\n      const routeId = attrs[ATTR.ROUTE_ID] as string;\n      this.updateRouteStatus(routeId, contextId, \"stopped\");\n    } else if (kind === SPAN_KIND.EXCHANGE) {\n      const exchangeId = attrs[ATTR.EXCHANGE_ID] as string;\n      const durationMs = Number(attrs[ATTR.DURATION_MS] ?? 0);\n\n      if (attrs[ATTR.DROPPED] === true) {\n        const reason = (attrs[ATTR.DROP_REASON] as string) ?? \"dropped\";\n        this.dropExchange(exchangeId, contextId, ts, reason);\n      } else if (span.status.code === 2) {\n        // SpanStatusCode.ERROR = 2\n        const error =\n          (attrs[ATTR.ERROR] as string) ?? span.status.message ?? \"unknown\";\n        this.failExchange(exchangeId, contextId, ts, durationMs, error);\n      } else {\n        this.completeExchange(exchangeId, contextId, ts, durationMs);\n      }\n    }\n  }\n\n  async forceFlush(): Promise<void> {\n    // Writes are synchronous, nothing to flush\n  }\n\n  async shutdown(): Promise<void> {\n    // Connection lifecycle managed by SqliteConnection\n  }\n}\n","import type { SqliteConnection } from \"./sqlite-connection.ts\";\nimport type { TelemetryEvent, TelemetryLogger } from \"./types.ts\";\n\n/**\n * Upper bound on events retained in memory while flushes keep failing. A\n * transient fault is retried without loss; a sustained outage drops the\n * oldest events past this cap so the sink can never OOM the host process.\n */\nconst MAX_BUFFERED_EVENTS = 10_000;\n\n/**\n * Buffered batch writer for the SQLite `events` table.\n *\n * Accumulates events in memory and flushes them in batches\n * (by size threshold or time interval) for performance.\n *\n * This is a SQLite-specific materialized view of the raw event stream.\n * External backends derive the same view from trace data.\n */\nexport class SqliteEventWriter {\n  private readonly logger: TelemetryLogger | undefined;\n  private readonly batchSize: number;\n  private readonly flushIntervalMs: number;\n  private readonly insertStmt: { run(...params: unknown[]): unknown };\n  private readonly insertManyTxn: (events: TelemetryEvent[]) => void;\n  private buffer: TelemetryEvent[] = [];\n  private flushTimer: ReturnType<typeof setInterval> | undefined;\n\n  constructor(\n    connection: SqliteConnection,\n    batchSize: number,\n    flushIntervalMs: number,\n  ) {\n    this.logger = connection.logger;\n    this.batchSize = batchSize;\n    this.flushIntervalMs = flushIntervalMs;\n\n    this.insertStmt = connection.db.prepare(\n      \"INSERT INTO events (timestamp, context_id, event_name, details, exchange_id, correlation_id) VALUES (?, ?, ?, ?, ?, ?)\",\n    );\n\n    this.insertManyTxn = connection.db.transaction(\n      (events: TelemetryEvent[]) => {\n        for (const event of events) {\n          this.insertStmt.run(\n            event.timestamp,\n            event.contextId,\n            event.eventName,\n            event.details,\n            event.exchangeId ?? null,\n            event.correlationId ?? null,\n          );\n        }\n      },\n    );\n\n    this.flushTimer = setInterval(() => {\n      this.flush();\n    }, this.flushIntervalMs);\n\n    if (\n      this.flushTimer &&\n      typeof this.flushTimer === \"object\" &&\n      \"unref\" in this.flushTimer\n    ) {\n      this.flushTimer.unref();\n    }\n  }\n\n  write(event: TelemetryEvent): void {\n    this.buffer.push(event);\n    if (this.buffer.length >= this.batchSize) {\n      this.flush();\n    }\n  }\n\n  flush(): void {\n    if (this.buffer.length === 0) return;\n    // Snapshot without removing: a failed transaction must leave the events\n    // buffered so a transient fault (locked DB, brief I/O error) is retried on\n    // the next flush instead of silently dropping telemetry.\n    const batch = this.buffer.slice();\n    try {\n      this.insertManyTxn(batch);\n    } catch (err) {\n      // Non-blocking: SQLite errors must not destabilize event processing.\n      // Keep the batch buffered for retry, but bound the buffer so a sustained\n      // outage cannot grow it without limit and OOM the host process. Past the\n      // cap, drop the oldest overflow (the freshest events are most useful).\n      this.logger?.warn(\n        { err, batchSize: batch.length },\n        \"Failed to flush telemetry event batch; retaining for retry\",\n      );\n      if (this.buffer.length > MAX_BUFFERED_EVENTS) {\n        const dropped = this.buffer.length - MAX_BUFFERED_EVENTS;\n        this.buffer.splice(0, dropped);\n        this.logger?.warn(\n          { dropped },\n          \"Telemetry buffer exceeded cap during sustained sink failure; dropped oldest events\",\n        );\n      }\n      return;\n    }\n    // Commit succeeded: drop exactly the events we persisted. flush() is\n    // synchronous (bun:sqlite transactions run sync), so no write() interleaved\n    // and the first batch.length entries are exactly the committed ones.\n    this.buffer.splice(0, batch.length);\n  }\n\n  close(): void {\n    if (this.flushTimer !== undefined) {\n      clearInterval(this.flushTimer);\n      this.flushTimer = undefined;\n    }\n    this.flush();\n  }\n}\n","{\n  \"name\": \"@routecraft/routecraft\",\n  \"version\": \"0.7.2\",\n  \"description\": \"Open source AI automation platform: build the capabilities your agents use, or the agent itself, in TypeScript\",\n  \"type\": \"module\",\n  \"main\": \"./dist/index.cjs\",\n  \"module\": \"./dist/index.js\",\n  \"types\": \"./dist/index.d.ts\",\n  \"exports\": {\n    \".\": {\n      \"types\": \"./dist/index.d.ts\",\n      \"import\": \"./dist/index.js\",\n      \"require\": \"./dist/index.cjs\"\n    }\n  },\n  \"files\": [\n    \"dist\"\n  ],\n  \"scripts\": {\n    \"build\": \"tsup && bun scripts/verify-dist.mjs esm && bun scripts/verify-dist.mjs cjs\",\n    \"test\": \"vitest\",\n    \"test:coverage\": \"vitest --coverage\",\n    \"prepublishOnly\": \"bun run build\"\n  },\n  \"dependencies\": {\n    \"@opentelemetry/api\": \"^1.9.1\",\n    \"@standard-schema/spec\": \"^1.1.0\",\n    \"lru-cache\": \"^11.5.3\",\n    \"pino\": \"^10.3.1\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"devDependencies\": {\n    \"@opentelemetry/sdk-trace-base\": \"^2.11.0\",\n    \"@routecraft/testing\": \"workspace:*\",\n    \"@sinonjs/fake-timers\": \"^11.3.1\",\n    \"@types/better-sqlite3\": \"^7.6.13\",\n    \"@types/mailparser\": \"^3.4.6\",\n    \"@types/papaparse\": \"^5.5.2\",\n    \"@types/semver\": \"^7.8.0\",\n    \"@types/sinonjs__fake-timers\": \"^15.0.1\",\n    \"arktype\": \"^2.2.3\",\n    \"better-sqlite3\": \"^13.0.3\",\n    \"cheerio\": \"^1.2.0\",\n    \"croner\": \"^10.0.1\",\n    \"fast-xml-parser\": \"^5.11.1\",\n    \"imapflow\": \"^1.7.8\",\n    \"mailauth\": \"^7.1.0\",\n    \"mailparser\": \"^3.9.28\",\n    \"nodemailer\": \"^10.0.13\",\n    \"papaparse\": \"^5.7.0\",\n    \"semver\": \"^7.8.5\",\n    \"tsdav\": \"^2.3.3\",\n    \"vitest\": \"^4.1.11\",\n    \"zod\": \"^4.6.1\"\n  },\n  \"repository\": \"https://github.com/routecraftjs/routecraft\",\n  \"keywords\": [\n    \"integration\",\n    \"automation\",\n    \"routes\",\n    \"dsl\",\n    \"typescript\",\n    \"camel\",\n    \"data-processing\",\n    \"workflow\",\n    \"middleware\"\n  ],\n  \"author\": \"routecraftjs\",\n  \"license\": \"Apache-2.0\",\n  \"homepage\": \"https://routecraft.dev\",\n  \"bugs\": \"https://github.com/routecraftjs/routecraft/issues\",\n  \"peerDependencies\": {\n    \"@opentelemetry/sdk-trace-base\": \"^2.6.0\",\n    \"better-sqlite3\": \"^11.0.0 || ^12.0.0 || ^13.0.0\",\n    \"cheerio\": \"^1.2.0\",\n    \"croner\": \"^10.0.1\",\n    \"fast-xml-parser\": \"^5.11.1\",\n    \"imapflow\": \"^1.0.0\",\n    \"jose\": \"^6.0.0\",\n    \"mailauth\": \"^4.0.0 || ^5.0.0 || ^7.1.0\",\n    \"mailparser\": \"^3.7.0\",\n    \"nodemailer\": \"^6.0.0 || ^10.0.6\",\n    \"papaparse\": \"^5.4.1\",\n    \"pino-pretty\": \"^13.1.3\",\n    \"tsdav\": \"^2.1.0\"\n  },\n  \"peerDependenciesMeta\": {\n    \"cheerio\": {\n      \"optional\": true\n    },\n    \"croner\": {\n      \"optional\": true\n    },\n    \"fast-xml-parser\": {\n      \"optional\": true\n    },\n    \"papaparse\": {\n      \"optional\": true\n    },\n    \"imapflow\": {\n      \"optional\": true\n    },\n    \"mailauth\": {\n      \"optional\": true\n    },\n    \"mailparser\": {\n      \"optional\": true\n    },\n    \"nodemailer\": {\n      \"optional\": true\n    },\n    \"pino-pretty\": {\n      \"optional\": true\n    },\n    \"@opentelemetry/sdk-trace-base\": {\n      \"optional\": true\n    },\n    \"jose\": {\n      \"optional\": true\n    },\n    \"tsdav\": {\n      \"optional\": true\n    },\n    \"better-sqlite3\": {\n      \"optional\": true\n    }\n  },\n  \"optionalDependencies\": {\n    \"pino-pretty\": \"^13.1.3\"\n  }\n}\n","import { parseDuration } from \"../shared/duration.ts\";\nimport {\n  trace,\n  type Tracer,\n  type Span,\n  SpanStatusCode,\n} from \"@opentelemetry/api\";\nimport type { CraftContext, CraftPlugin } from \"../context.ts\";\nimport { safeStringify } from \"../shared/safe-json.ts\";\nimport type { EventName, EventHandler } from \"../types.ts\";\nimport type { TelemetryOptions, TelemetryEvent } from \"./types.ts\";\nimport { SqliteConnection } from \"./sqlite-connection.ts\";\nimport { SqliteSpanProcessor, ATTR, SPAN_KIND } from \"./sqlite-processor.ts\";\nimport { SqliteEventWriter } from \"./sqlite-event-writer.ts\";\nimport { version as TRACER_VERSION } from \"../../package.json\";\n\n/**\n * Default batch size for the event writer.\n */\nconst DEFAULT_BATCH_SIZE = 50;\n\n/**\n * Default flush interval in milliseconds.\n */\nconst DEFAULT_FLUSH_INTERVAL_MS = 1000;\n\n/**\n * Default maximum exchange rows for pruning.\n */\nconst DEFAULT_MAX_EXCHANGES = 50_000;\n\n/**\n * Default maximum event rows for pruning.\n */\nconst DEFAULT_MAX_EVENTS = 100_000;\n\n/**\n * Telemetry plugin that instruments the framework with OpenTelemetry traces\n * and persists data to SQLite for the TUI.\n *\n * Fan-out architecture:\n * - SQLite path: `SqliteSpanProcessor` (routes/exchanges) + `SqliteEventWriter` (events)\n * - External path: user's `TracerProvider` creates real OTel spans\n *\n * Both paths receive identical data.\n *\n * @example\n * ```typescript\n * import { telemetry } from \"@routecraft/routecraft\";\n *\n * // Default SQLite sink\n * telemetry()\n *\n * // External provider (e.g. Better Stack)\n * telemetry({ tracerProvider: myTracerProvider })\n * ```\n */\n/**\n * Default maximum snapshot body size in bytes.\n */\nconst DEFAULT_MAX_SNAPSHOT_BYTES = 65_536;\n\nclass TelemetryPlugin implements CraftPlugin {\n  private readonly options: TelemetryOptions;\n  private readonly batchSize: number;\n  private readonly flushIntervalMs: number;\n  private readonly captureSnapshots: boolean;\n  private readonly maxSnapshotBytes: number;\n\n  private connection: SqliteConnection | undefined;\n  private spanProcessor: SqliteSpanProcessor | undefined;\n  private eventWriter: SqliteEventWriter | undefined;\n  private tracer: Tracer | undefined;\n  private unsubscribers: Array<() => void> = [];\n\n  // Track active spans for route lifecycle (long-lived)\n  private routeSpans = new Map<string, Span>();\n  // Track active spans for exchange lifecycle\n  private exchangeSpans = new Map<string, Span>();\n\n  constructor(options?: TelemetryOptions) {\n    this.options = options ?? {};\n    const sqlite = this.options.sqlite ?? {};\n    const batchSize = Math.trunc(sqlite.eventBatchSize ?? DEFAULT_BATCH_SIZE);\n    const flushIntervalMs = Math.trunc(\n      sqlite.eventFlushInterval === undefined\n        ? DEFAULT_FLUSH_INTERVAL_MS\n        : parseDuration(\n            sqlite.eventFlushInterval,\n            \"telemetry.sqlite.eventFlushInterval\",\n          ),\n    );\n    this.batchSize = batchSize > 0 ? batchSize : DEFAULT_BATCH_SIZE;\n    this.flushIntervalMs =\n      flushIntervalMs > 0 ? flushIntervalMs : DEFAULT_FLUSH_INTERVAL_MS;\n    this.captureSnapshots = sqlite.captureSnapshots === true;\n    this.maxSnapshotBytes = Math.trunc(\n      sqlite.maxSnapshotBytes ?? DEFAULT_MAX_SNAPSHOT_BYTES,\n    );\n  }\n\n  async apply(ctx: CraftContext): Promise<void> {\n    // -- SQLite path --\n    if (!this.options.disableSqlite) {\n      const sqlite = this.options.sqlite ?? {};\n      const conn = await SqliteConnection.open(\n        {\n          ...(sqlite.dbPath !== undefined ? { dbPath: sqlite.dbPath } : {}),\n          maxExchanges: sqlite.maxExchanges ?? DEFAULT_MAX_EXCHANGES,\n          maxEvents: sqlite.maxEvents ?? DEFAULT_MAX_EVENTS,\n        },\n        ctx.logger,\n      );\n      if (conn) {\n        this.connection = conn;\n        this.spanProcessor = new SqliteSpanProcessor(conn);\n        this.eventWriter = new SqliteEventWriter(\n          conn,\n          this.batchSize,\n          this.flushIntervalMs,\n        );\n      } else {\n        ctx.logger.warn(\n          {},\n          \"Telemetry SQLite backend requires Bun. Disabled under this runtime. \" +\n            \"Pass `telemetry({ tracerProvider })` to export traces via OTLP, or \" +\n            \"`telemetry({ disableSqlite: true })` to silence this warning.\",\n        );\n      }\n    }\n\n    // -- External OTel path --\n    if (this.options.tracerProvider) {\n      this.tracer = this.options.tracerProvider.getTracer(\n        \"routecraft\",\n        TRACER_VERSION,\n      );\n    } else if (trace.getTracerProvider() !== undefined) {\n      // Use globally registered provider if no explicit one given\n      // (no-op if no SDK installed)\n      this.tracer = trace.getTracer(\"routecraft\", TRACER_VERSION);\n    }\n\n    // -- Subscribe to events --\n    this.subscribeAll(ctx);\n    this.subscribeRouteLifecycle(ctx);\n    this.subscribeExchangeLifecycle(ctx);\n  }\n\n  async teardown(): Promise<void> {\n    for (const unsub of this.unsubscribers) {\n      unsub();\n    }\n    this.unsubscribers = [];\n\n    // End any lingering route spans\n    for (const span of this.routeSpans.values()) {\n      span.end();\n    }\n    this.routeSpans.clear();\n\n    // End any lingering exchange spans\n    for (const span of this.exchangeSpans.values()) {\n      span.end();\n    }\n    this.exchangeSpans.clear();\n\n    if (this.eventWriter) {\n      this.eventWriter.close();\n      this.eventWriter = undefined;\n    }\n\n    if (this.connection) {\n      this.connection.close();\n      this.connection = undefined;\n    }\n  }\n\n  // -- Raw event log (events table) --\n\n  private subscribeAll(ctx: CraftContext): void {\n    this.unsubscribers.push(\n      ctx.on(\"*\", ((payload: {\n        ts: string;\n        contextId: string;\n        details: unknown;\n        _event?: string;\n      }) => {\n        if (!this.eventWriter) return;\n        const d = payload.details as Record<string, unknown> | null;\n        const exchangeId =\n          d && typeof d[\"exchangeId\"] === \"string\"\n            ? d[\"exchangeId\"]\n            : undefined;\n        const corrId =\n          d && typeof d[\"correlationId\"] === \"string\"\n            ? d[\"correlationId\"]\n            : undefined;\n        const event: TelemetryEvent = {\n          timestamp: payload.ts,\n          contextId: payload.contextId,\n          eventName: payload._event ?? extractEventName(payload),\n          // Drop the conventional `_snapshot` envelope from event details\n          // unless snapshot capture is enabled. This is a generic,\n          // domain-agnostic redaction: any event author can stash\n          // potentially-sensitive payloads under `_snapshot` (e.g. the AI\n          // package puts agent tool input/output there) and have them\n          // honour the same switch as exchange-body snapshots.\n          details: safeStringify(payload.details, {\n            dropSnapshot: !this.captureSnapshots,\n          }),\n        };\n        if (exchangeId) event.exchangeId = exchangeId;\n        if (corrId) event.correlationId = corrId;\n        this.eventWriter.write(event);\n      }) as EventHandler<EventName>),\n    );\n  }\n\n  // -- Route lifecycle (spans) --\n\n  private subscribeRouteLifecycle(ctx: CraftContext): void {\n    // Route registered\n    this.unsubscribers.push(\n      ctx.on(\"route:registered\", ((payload: {\n        ts: string;\n        contextId: string;\n        details: { route: { definition: { id: string } } };\n      }) => {\n        const routeId = payload.details.route.definition.id;\n        const key = `${routeId}:${payload.contextId}`;\n\n        // SQLite\n        this.spanProcessor?.writeRoute(routeId, payload.contextId, payload.ts);\n\n        // OTel\n        if (this.tracer) {\n          const span = this.tracer.startSpan(`route:${routeId}`, {\n            attributes: {\n              [ATTR.SPAN_KIND]: SPAN_KIND.ROUTE,\n              [ATTR.ROUTE_ID]: routeId,\n              [ATTR.CONTEXT_ID]: payload.contextId,\n            },\n          });\n          this.routeSpans.set(key, span);\n        }\n      }) as EventHandler<EventName>),\n    );\n\n    // Route started\n    this.unsubscribers.push(\n      ctx.on(\"route:started\", ((payload: {\n        ts: string;\n        contextId: string;\n        details: { route: { definition: { id: string } } };\n      }) => {\n        const routeId = payload.details.route.definition.id;\n\n        // SQLite\n        this.spanProcessor?.updateRouteStatus(\n          routeId,\n          payload.contextId,\n          \"started\",\n        );\n\n        // OTel: add event to existing span\n        const key = `${routeId}:${payload.contextId}`;\n        const span = this.routeSpans.get(key);\n        span?.addEvent(\"started\");\n      }) as EventHandler<EventName>),\n    );\n\n    // Route stopped\n    this.unsubscribers.push(\n      ctx.on(\"route:stopped\", ((payload: {\n        ts: string;\n        contextId: string;\n        details: { route: { definition: { id: string } } };\n      }) => {\n        const routeId = payload.details.route.definition.id;\n\n        // SQLite\n        this.spanProcessor?.updateRouteStatus(\n          routeId,\n          payload.contextId,\n          \"stopped\",\n        );\n\n        // OTel: end the route span\n        const key = `${routeId}:${payload.contextId}`;\n        const span = this.routeSpans.get(key);\n        if (span) {\n          span.addEvent(\"stopped\");\n          span.end();\n          this.routeSpans.delete(key);\n        }\n      }) as EventHandler<EventName>),\n    );\n  }\n\n  /**\n   * Serialize and persist an exchange snapshot when capture is enabled.\n   */\n  private captureExchangeSnapshot(\n    exchange: { id: string; headers: Record<string, unknown>; body: unknown },\n    contextId: string,\n  ): void {\n    if (!this.captureSnapshots || !this.spanProcessor) return;\n\n    const headers = safeStringify(exchange.headers);\n    let body = safeStringify(exchange.body);\n    let truncated = false;\n\n    if (body.length > this.maxSnapshotBytes) {\n      body = body.slice(0, this.maxSnapshotBytes);\n      truncated = true;\n    }\n\n    this.spanProcessor.writeSnapshot(\n      exchange.id,\n      contextId,\n      headers,\n      body,\n      truncated,\n    );\n  }\n\n  // -- Exchange lifecycle (spans) --\n\n  private subscribeExchangeLifecycle(ctx: CraftContext): void {\n    // Exchange started\n    this.unsubscribers.push(\n      ctx.on(\"route:exchange:started\", ((payload: {\n        ts: string;\n        contextId: string;\n        details: {\n          routeId: string;\n          exchangeId: string;\n          correlationId: string;\n        };\n      }) => {\n        const { routeId, exchangeId, correlationId } = payload.details;\n        const key = `${exchangeId}:${payload.contextId}`;\n\n        // SQLite\n        this.spanProcessor?.writeExchange(\n          exchangeId,\n          routeId,\n          payload.contextId,\n          correlationId,\n          payload.ts,\n        );\n\n        // OTel\n        if (this.tracer) {\n          const span = this.tracer.startSpan(`exchange:${exchangeId}`, {\n            attributes: {\n              [ATTR.SPAN_KIND]: SPAN_KIND.EXCHANGE,\n              [ATTR.ROUTE_ID]: routeId,\n              [ATTR.EXCHANGE_ID]: exchangeId,\n              [ATTR.CORRELATION_ID]: correlationId,\n              [ATTR.CONTEXT_ID]: payload.contextId,\n            },\n          });\n          this.exchangeSpans.set(key, span);\n        }\n      }) as EventHandler<EventName>),\n    );\n\n    // Exchange completed\n    this.unsubscribers.push(\n      ctx.on(\"route:exchange:completed\", ((payload: {\n        ts: string;\n        contextId: string;\n        details: {\n          exchangeId: string;\n          duration: number;\n          exchange?: {\n            id: string;\n            headers: Record<string, unknown>;\n            body: unknown;\n          };\n        };\n      }) => {\n        const { exchangeId, duration, exchange } = payload.details;\n        const key = `${exchangeId}:${payload.contextId}`;\n\n        // SQLite\n        this.spanProcessor?.completeExchange(\n          exchangeId,\n          payload.contextId,\n          payload.ts,\n          duration,\n        );\n\n        // Snapshot\n        if (exchange) {\n          this.captureExchangeSnapshot(exchange, payload.contextId);\n        }\n\n        // OTel\n        const span = this.exchangeSpans.get(key);\n        if (span) {\n          span.setAttribute(ATTR.DURATION_MS, duration);\n          span.end();\n          this.exchangeSpans.delete(key);\n        }\n      }) as EventHandler<EventName>),\n    );\n\n    // Exchange failed\n    this.unsubscribers.push(\n      ctx.on(\"route:exchange:failed\", ((payload: {\n        ts: string;\n        contextId: string;\n        details: {\n          exchangeId: string;\n          duration: number;\n          error: unknown;\n          exchange?: {\n            id: string;\n            headers: Record<string, unknown>;\n            body: unknown;\n          };\n        };\n      }) => {\n        const { exchangeId, duration, error, exchange } = payload.details;\n        const key = `${exchangeId}:${payload.contextId}`;\n        const errorStr = error instanceof Error ? error.message : String(error);\n\n        // SQLite\n        this.spanProcessor?.failExchange(\n          exchangeId,\n          payload.contextId,\n          payload.ts,\n          duration,\n          errorStr,\n        );\n\n        // Snapshot\n        if (exchange) {\n          this.captureExchangeSnapshot(exchange, payload.contextId);\n        }\n\n        // OTel\n        const span = this.exchangeSpans.get(key);\n        if (span) {\n          span.setAttribute(ATTR.DURATION_MS, duration);\n          span.setAttribute(ATTR.ERROR, errorStr);\n          span.setStatus({\n            code: SpanStatusCode.ERROR,\n            message: errorStr,\n          });\n          span.end();\n          this.exchangeSpans.delete(key);\n        }\n      }) as EventHandler<EventName>),\n    );\n\n    // Exchange dropped\n    this.unsubscribers.push(\n      ctx.on(\"route:exchange:dropped\", ((payload: {\n        ts: string;\n        contextId: string;\n        details: {\n          exchangeId: string;\n          reason?: string;\n          exchange?: {\n            id: string;\n            headers: Record<string, unknown>;\n            body: unknown;\n          };\n        };\n      }) => {\n        const { exchangeId, reason, exchange } = payload.details;\n        const key = `${exchangeId}:${payload.contextId}`;\n        const dropReason = reason ?? \"dropped\";\n\n        // SQLite\n        this.spanProcessor?.dropExchange(\n          exchangeId,\n          payload.contextId,\n          payload.ts,\n          dropReason,\n        );\n\n        // Snapshot\n        if (exchange) {\n          this.captureExchangeSnapshot(exchange, payload.contextId);\n        }\n\n        // OTel\n        const span = this.exchangeSpans.get(key);\n        if (span) {\n          span.setAttribute(ATTR.DROPPED, true);\n          span.setAttribute(ATTR.DROP_REASON, dropReason);\n          span.end();\n          this.exchangeSpans.delete(key);\n        }\n      }) as EventHandler<EventName>),\n    );\n  }\n}\n\n/**\n * Create a telemetry plugin that instruments the framework with\n * OpenTelemetry traces and persists data to SQLite for the TUI.\n *\n * When no `tracerProvider` is given and `disableSqlite` is false (default),\n * events are persisted to a local SQLite database for the TUI to read.\n *\n * @param options - TracerProvider, SQLite path, and buffer configuration\n * @returns A CraftPlugin instance\n *\n * @example\n * ```typescript\n * import { telemetry } from \"@routecraft/routecraft\";\n *\n * // Default SQLite backend\n * telemetry()\n *\n * // Export to Better Stack via OTLP\n * telemetry({ tracerProvider: myTracerProvider })\n *\n * // External only, no SQLite\n * telemetry({ tracerProvider, disableSqlite: true })\n * ```\n */\nexport function telemetry(options?: TelemetryOptions): CraftPlugin {\n  return new TelemetryPlugin(options);\n}\n\n/**\n * Extract a meaningful event name from a wildcard payload.\n *\n * This is a best-effort fallback for events that lack the `_event` field.\n * The `_event` field (checked by the caller) is the authoritative source.\n * These heuristics infer the event name from payload shape and may\n * misclassify events with overlapping fields.\n */\nfunction extractEventName(payload: { details: unknown }): string {\n  const d = payload.details as Record<string, unknown> | null;\n  if (!d) return \"unknown\";\n\n  if (\"route\" in d && typeof d[\"route\"] === \"object\" && d[\"route\"] !== null) {\n    const route = d[\"route\"] as { definition?: { id?: string } };\n    if (route.definition?.id) {\n      if (\"reason\" in d) return \"route:stopping\";\n      return \"route:event\";\n    }\n  }\n\n  // Step events also carry exchangeId, so the more specific shape\n  // (operation present) must be checked before the exchange shapes.\n  if (\"routeId\" in d && \"operation\" in d) {\n    if (\"error\" in d) {\n      return \"duration\" in d ? \"route:step:failed\" : \"route:step:error\";\n    }\n    if (\"duration\" in d) return \"route:step:completed\";\n    return \"route:step:started\";\n  }\n\n  if (\"routeId\" in d && \"exchangeId\" in d) {\n    if (\"reason\" in d) return \"route:exchange:dropped\";\n    if (\"error\" in d && \"duration\" in d) return \"route:exchange:failed\";\n    if (\"duration\" in d) return \"route:exchange:completed\";\n    return \"route:exchange:started\";\n  }\n\n  if (\"pluginId\" in d) return \"plugin:event\";\n  if (\"error\" in d && !(\"routeId\" in d)) return \"context:error\";\n\n  return \"context:event\";\n}\n","import { registerConfigApplier } from \"../config-applier.ts\";\nimport { telemetry } from \"./index.ts\";\nimport type { TelemetryOptions } from \"./types.ts\";\n\ndeclare module \"@routecraft/routecraft\" {\n  interface CraftConfig {\n    /** Telemetry plugin configuration (SQLite, OpenTelemetry) */\n    telemetry?: TelemetryOptions;\n  }\n}\n\n/**\n * Register the `telemetry` config key so `defineConfig({ telemetry: {...} })`\n * is equivalent to `defineConfig({ plugins: [telemetry({...})] })`. Loaded\n * as a side-effect import from `packages/routecraft/src/index.ts`. Keeps\n * the core context free of telemetry plugin knowledge.\n */\nregisterConfigApplier(\"telemetry\", (options) => telemetry(options));\n","import type { CraftContext, CraftPlugin } from \"../context.ts\";\nimport { registerConfigApplier } from \"../config-applier.ts\";\nimport { DEFERRAL_RUNTIME } from \"./runtime-key.ts\";\nimport { registerDeferralsResource } from \"./ops-resource.ts\";\nimport { MemoryDeferralStore } from \"./memory-store.ts\";\nimport {\n  DEFAULT_DEFERRAL_DB_PATH,\n  SqliteDeferralStore,\n} from \"./sqlite-store.ts\";\nimport type { SqliteDriverLoaders } from \"../shared/sqlite/driver.ts\";\nimport { claimDatabasePath, releaseClaimant } from \"../shared/sqlite/claims.ts\";\nimport { rcError } from \"../error.ts\";\nimport {\n  type ResumeTokenSigner,\n  DEFERRAL_SECRET_ENV,\n  resolveSigningSecret,\n} from \"./tokens.ts\";\nimport type { DeferralStore } from \"./types.ts\";\nimport { type Duration, parseDuration } from \"../shared/duration.ts\";\nimport {\n  DEFAULT_EXPIRY_LEASE,\n  DEFAULT_DEFERRAL_RETENTION,\n  DEFAULT_SWEEP_INTERVAL,\n  DEFAULT_DEFERRAL_TTL,\n  DeferralSweeper,\n} from \"./sweeper.ts\";\nimport { isDevelopmentRuntime } from \"../shared/runtime-env.ts\";\n\n/**\n * Environment variable naming where deferred exchanges are persisted. Either\n * a file path or the literal `memory`. Overridden by an explicit\n * `deferral: { store }`.\n */\nexport const DEFERRAL_STORE_ENV = \"ROUTECRAFT_DEFERRAL_STORE\";\n\n/** The setting this store's path claim is reported under. */\nconst DEFERRAL_CLAIMANT = \"deferral: { store }\";\n\nexport { DEFERRAL_RUNTIME };\n\ndeclare module \"@routecraft/routecraft\" {\n  interface CraftConfig {\n    /**\n     * Durable defer and resume. Set it when any route can reach a\n     * `.defer()`; leaving it unset is fine for a context that never\n     * defers.\n     */\n    deferral?: DeferralConfig;\n  }\n}\n\n/**\n * Where deferred exchanges live.\n *\n * - A path (or `{ path }`) opens the sqlite backend at that location. This\n *   is the value a container deployment sets to a mounted volume, which is\n *   the whole point of it being configurable.\n * - `\"memory\"` opts into the in-process backend explicitly, accepting that\n *   deferred exchanges die with the process.\n * - A {@link DeferralStore} instance plugs in a backend of your own\n *   (postgres, redis) without waiting for core to ship one.\n */\nexport type DeferralStoreConfig =\n  string | { path: string } | \"memory\" | DeferralStore;\n\n/**\n * Deferral configuration on `defineConfig`.\n */\nexport interface DeferralConfig {\n  /**\n   * Where deferred exchanges are persisted. Defaults to the sqlite backend at\n   * {@link DEFAULT_DEFERRAL_DB_PATH}, or to whatever\n   * {@link DEFERRAL_STORE_ENV} names.\n   */\n  store?: DeferralStoreConfig;\n  /**\n   * HMAC secret for signing resume tokens.\n   *\n   * Prefer the {@link DEFERRAL_SECRET_ENV} environment variable: a secret\n   * in a config file is a secret in version control. This field exists for\n   * deployments that pull secrets from a manager at boot and hand them to\n   * `defineConfig` in code.\n   */\n  secret?: string;\n  /**\n   * How long a deferral stays resumable when `.defer()` names no `ttl`.\n   *\n   * Defaults to {@link DEFAULT_DEFERRAL_TTL}. Set `\"never\"` to opt a\n   * context out of default expiry entirely, which means an unresumed\n   * deferral is kept until something else retires it.\n   */\n  defaultTtl?: Duration | \"never\";\n  /**\n   * How often the sweeper looks for overdue deferrals.\n   *\n   * Defaults to {@link DEFAULT_SWEEP_INTERVAL}. TTLs are measured in hours,\n   * so sub-minute precision buys nothing; the knob exists for tests and for\n   * deployments that want expiry noticed sooner.\n   */\n  sweepInterval?: Duration;\n  /**\n   * How long an expiry-delivery claim is honoured before the sweeper\n   * releases it for redelivery.\n   *\n   * Defaults to {@link DEFAULT_EXPIRY_LEASE}. Only a crash mid-delivery\n   * ever spends this; keep it comfortably longer than the slowest `.error()`\n   * handler, because a lease shorter than a slow handler would make one\n   * healthy process double-deliver by itself.\n   */\n  expiryLease?: Duration;\n  /**\n   * How long settled deferrals (resumed, expired, denied) are kept before\n   * the sweeper purges them.\n   *\n   * Defaults to {@link DEFAULT_DEFERRAL_RETENTION}. Set `\"never\"` to keep\n   * everything, which is the audit-trail configuration; the store then\n   * grows with every exchange that ever deferred.\n   */\n  retention?: Duration | \"never\";\n}\n\n/**\n * Seams the test harness needs and users must not have.\n *\n * Kept off {@link DeferralConfig} rather than tagged `@internal` on it,\n * because `allowEphemeralSecret` is a security relaxation: it short-circuits\n * the named-environment gate that `.standards/security.md` section 6a\n * requires, and `@internal` is a documentation tag, not an enforcement\n * mechanism. On the public config type it would be exactly the flag someone\n * copies out of a test fixture to make an RC5040 startup error go away.\n * `CraftConfig[\"deferral\"]` is declared as `DeferralConfig` alone;\n * `@routecraft/testing` supplies these separately.\n *\n * @internal\n */\nexport interface DeferralTestSeams {\n  /** Driver loader injection, for exercising the absent-peer arm. */\n  loaders?: SqliteDriverLoaders;\n  /**\n   * Permit an ephemeral in-memory signing key when no secret is\n   * configured, regardless of `NODE_ENV`.\n   */\n  allowEphemeralSecret?: boolean;\n}\n\n/**\n * The resolved per-context deferral runtime: one store, one signer.\n */\nexport interface DeferralRuntime {\n  readonly store: DeferralStore;\n  readonly signer: ResumeTokenSigner;\n  /**\n   * What the store resolved to, for the startup log line. `custom` is a\n   * store the caller supplied; reporting it as `sqlite` would mislead\n   * exactly the operators who configured a backend deliberately, on the one\n   * field that answers \"is this deployment durable, and against what\".\n   */\n  readonly backend: \"sqlite\" | \"memory\" | \"custom\";\n  /**\n   * False when the caller supplied the store, in which case they own its\n   * lifecycle and the plugin must not close it on teardown. A user-supplied\n   * backend typically wraps a pool shared with the rest of the application,\n   * or is reused across two contexts in one process (which is how a\n   * restart-durability test is written).\n   */\n  readonly ownsStore: boolean;\n  /**\n   * Milliseconds a deferral stays resumable when `.defer()` names no\n   * `ttl`. Undefined when the context opted out with `defaultTtl: \"never\"`,\n   * which is the only way to defer something with no deadline at all.\n   */\n  readonly defaultTtlMs?: number;\n  /**\n   * Milliseconds between sweeps. Resolved here rather than in the plugin's\n   * `start()` hook so a malformed duration fails while the context is still\n   * being built, which is the rule the rest of this config already follows.\n   */\n  readonly sweepIntervalMs: number;\n  /** Milliseconds an expiry-delivery claim is honoured before redelivery. */\n  readonly expiryLeaseMs: number;\n  /** Milliseconds settled records are kept. Undefined means keep forever. */\n  readonly retentionMs?: number;\n}\n\n/**\n * Build the deferral runtime for a context.\n *\n * The durability decision happens here, once, and it is deliberately loud\n * in the degraded case. A deployment that asked for a durable store and did\n * not get one has lost the feature's entire promise, so:\n *\n * - An explicitly configured path that cannot be opened FAILS. Silently\n *   degrading a deployment that named a volume would turn \"we survive\n *   restarts\" into \"we lost the approvals\" with no signal.\n * - An unconfigured context that cannot open the default path falls back to\n *   memory with a `warn` line naming the reason, because the most likely\n *   cause is a Node install without `better-sqlite3`, and that should not\n *   stop a context whose routes may never defer at all.\n *\n * @param context - Context whose logger reports the outcome.\n * @param config - The `deferral` config block, if any.\n *\n * @internal\n */\nexport async function createDeferralRuntime(\n  context: CraftContext,\n  config: DeferralConfig & DeferralTestSeams = {},\n): Promise<DeferralRuntime> {\n  const configuredTtl = config.defaultTtl ?? DEFAULT_DEFERRAL_TTL;\n  const defaultTtlMs =\n    configuredTtl === \"never\"\n      ? undefined\n      : parseDuration(configuredTtl, \"deferral.defaultTtl\");\n\n  const sweepIntervalMs = parseDuration(\n    config.sweepInterval ?? DEFAULT_SWEEP_INTERVAL,\n    \"deferral.sweepInterval\",\n  );\n  const expiryLeaseMs = parseDuration(\n    config.expiryLease ?? DEFAULT_EXPIRY_LEASE,\n    \"deferral.expiryLease\",\n  );\n  const configuredRetention = config.retention ?? DEFAULT_DEFERRAL_RETENTION;\n  const retentionMs =\n    configuredRetention === \"never\"\n      ? undefined\n      : parseDuration(configuredRetention, \"deferral.retention\");\n\n  const signer = resolveSigningSecret({\n    ...(config.secret !== undefined ? { secret: config.secret } : {}),\n    allowEphemeral: config.allowEphemeralSecret ?? isDevelopmentRuntime(),\n  });\n  if (signer.source === \"ephemeral\") {\n    context.logger.warn(\n      {},\n      `Deferral resume tokens are signed with an ephemeral key. Tokens minted by this process become unverifiable when it restarts. Set ${DEFERRAL_SECRET_ENV} before deploying.`,\n    );\n  }\n\n  /**\n   * One shape for every exit. Four hand-written literals is how\n   * `defaultTtlMs` came to be silently dropped on the sqlite branch, which\n   * is the backend the production default uses.\n   */\n  const runtime = (\n    store: DeferralStore,\n    backend: DeferralRuntime[\"backend\"],\n    ownsStore: boolean,\n  ): DeferralRuntime => ({\n    store,\n    signer,\n    backend,\n    ownsStore,\n    sweepIntervalMs,\n    expiryLeaseMs,\n    ...(retentionMs !== undefined ? { retentionMs } : {}),\n    ...(defaultTtlMs !== undefined ? { defaultTtlMs } : {}),\n  });\n\n  // A present-but-empty environment variable means unset, not \"open the\n  // working directory as a database\". `resolveSigningSecret` treats a blank\n  // secret the same way.\n  const fromEnv = process.env[DEFERRAL_STORE_ENV]?.trim();\n  const configured =\n    config.store ??\n    (fromEnv !== undefined && fromEnv !== \"\" ? fromEnv : undefined);\n  const explicit = configured !== undefined;\n\n  if (\n    configured !== undefined &&\n    typeof configured === \"object\" &&\n    \"create\" in configured\n  ) {\n    releaseClaimant({ scope: context, claimant: DEFERRAL_CLAIMANT });\n    return runtime(configured, \"custom\", false);\n  }\n  if (configured === \"memory\") {\n    releaseClaimant({ scope: context, claimant: DEFERRAL_CLAIMANT });\n    return runtime(new MemoryDeferralStore(), \"memory\", true);\n  }\n\n  const path =\n    typeof configured === \"object\" && configured !== null\n      ? configured.path\n      : ((configured as string | undefined) ?? DEFAULT_DEFERRAL_DB_PATH);\n\n  claimDatabasePath({\n    scope: context,\n    path,\n    claimant: DEFERRAL_CLAIMANT,\n    onConflict: (conflict) =>\n      rcError(\"RC5044\", undefined, {\n        message: `deferral: { store } and ${conflict.held} both point at \"${conflict.path}\". Each store versions its own file, so they cannot share one; give them separate paths.`,\n      }),\n  });\n\n  try {\n    const store = await SqliteDeferralStore.open({\n      path,\n      ...(config.loaders ? { loaders: config.loaders } : {}),\n    });\n    context.logger.debug(\n      { backend: \"sqlite\", driver: store.driver, path },\n      \"Deferral store opened\",\n    );\n    return runtime(store, \"sqlite\", true);\n  } catch (err) {\n    if (explicit) throw err;\n    // Nothing opened the file, so nothing may go on holding it: this\n    // fallback is a deliberate degradation, and a claim left behind would\n    // refuse the next store to ask for a path no store is using.\n    releaseClaimant({ scope: context, claimant: DEFERRAL_CLAIMANT });\n    context.logger.warn(\n      { err, path },\n      \"No durable deferral store available; deferred exchanges will NOT survive a restart. Install better-sqlite3 (Node) or configure deferral: { store } to keep deferrals durable.\",\n    );\n    return runtime(new MemoryDeferralStore(), \"memory\", true);\n  }\n}\n\n/**\n * Plugin form of {@link createDeferralRuntime}, wired to the `deferral`\n * config key. Resolves the runtime during `initPlugins()` so a missing\n * signing secret fails at startup, and closes the store during teardown,\n * but only a store it opened itself.\n */\nexport function deferralPlugin(config: DeferralConfig = {}): CraftPlugin {\n  // Keyed by context, not a plain closure variable: one plugin instance can\n  // serve two contexts in the same process (a `defineConfig` export reused\n  // across tests), and a single slot would let the second start overwrite\n  // the first sweeper, leaving its interval running against a store that is\n  // about to close.\n  const sweepers = new WeakMap<CraftContext, DeferralSweeper>();\n\n  return {\n    name: \"deferral\",\n    async apply(ctx: CraftContext) {\n      // Registration first: it throws on a name collision, and a failed\n      // `apply()` is not yet recorded for teardown, so a store opened\n      // before it would leak its handle for the life of the process.\n      registerDeferralsResource(ctx);\n      ctx.setStore(DEFERRAL_RUNTIME, await createDeferralRuntime(ctx, config));\n    },\n    async start(ctx: CraftContext) {\n      const runtime = ctx.getStore(DEFERRAL_RUNTIME);\n      if (!runtime) return;\n      const sweeper = new DeferralSweeper(ctx, runtime.store, {\n        intervalMs: runtime.sweepIntervalMs,\n        leaseMs: runtime.expiryLeaseMs,\n        ...(runtime.retentionMs !== undefined\n          ? { retentionMs: runtime.retentionMs }\n          : {}),\n      });\n      sweepers.set(ctx, sweeper);\n      // Before the interval, and awaited: what expired during the outage\n      // reaches its routes ahead of anything new arriving.\n      await sweeper.scanOnStart();\n      sweeper.start();\n    },\n    async teardown(ctx: CraftContext) {\n      // Awaited before the store closes; see DeferralSweeper.stop().\n      await sweepers.get(ctx)?.stop();\n      sweepers.delete(ctx);\n      const runtime = ctx.getStore(DEFERRAL_RUNTIME);\n      if (runtime?.ownsStore) await runtime.store.close();\n    },\n  };\n}\n\nregisterConfigApplier(\"deferral\", (options) => deferralPlugin(options));\n","import type { CraftContext } from \"../context.ts\";\nimport { rcError } from \"../error.ts\";\nimport {\n  DEFAULT_PAGE_SIZE,\n  cursorScope,\n  decodeCursor,\n  encodeCursor,\n  malformedCursor,\n  parsePageQuery,\n} from \"../plugins/ops/pagination.ts\";\nimport { registerOpsResource } from \"../plugins/ops/store.ts\";\nimport type { CursorScope } from \"../plugins/ops/pagination.ts\";\nimport type { OpsDeferralSummary, OpsPage } from \"../plugins/ops/types.ts\";\nimport { DEFERRAL_RUNTIME } from \"./runtime-key.ts\";\nimport { summariseDeferral } from \"./types.ts\";\nimport type {\n  DeferralListCursor,\n  DeferralState,\n  DeferralStore,\n  DeferralSummary,\n} from \"./types.ts\";\n\n/**\n * The management listing of what an instance is waiting on.\n *\n * Everything a reader needs is already on the record: what the work waits\n * for, when it was deferred, when it comes due, whether a delivery claim\n * is outstanding, and how a settled one ended. What was missing until now\n * is a surface that renders it, so a deferral could only be seen by\n * invoking the route that produced it.\n *\n * Contributed through the same seam `@routecraft/ai` uses for\n * `agent-sessions`, rather than served by the ops mount itself, because\n * the mount owns `routes` and `events` and nothing else. Registration is\n * inert until an ops mount exists.\n */\n\n/** The path segment under `/ops`. */\nconst DEFERRALS_RESOURCE = \"deferrals\";\n\n/**\n * What a bare listing shows.\n *\n * Waiting, because the question an operator opens this with is what is\n * still owed an answer, and a settled deferral is history. `?state=settled`\n * asks for the history, and `?state=all` for both.\n */\nconst DEFAULT_STATE: DeferralState = \"waiting\";\n\n/**\n * The keyset the ops cursor carries for this collection, rendered into\n * the opaque string the shared helpers page on.\n *\n * `deferredAt` is an epoch millisecond count rather than an ISO string so\n * the key cannot carry a second rendering of the same instant, and the\n * separator is a character no deferral id contains, since an id is\n * `{uuid}#{sequence}`.\n */\nconst KEY_SEPARATOR = \"|\";\n\nfunction encodeKey(summary: DeferralSummary): string {\n  return `${String(summary.deferredAt.getTime())}${KEY_SEPARATOR}${summary.id}`;\n}\n\n/**\n * Render a store's summary onto the wire.\n *\n * The one difference is the timestamps: a store answers in `Date` and the\n * wire has none, so they are rendered here rather than left for\n * `JSON.stringify` to do silently against a type that claims otherwise.\n * `by` is narrowed to the fields a listing may show; `actorSubject` is\n * part of the audit record and not part of this answer.\n */\nfunction onWire(summary: DeferralSummary): OpsDeferralSummary {\n  return {\n    id: summary.id,\n    routeId: summary.routeId,\n    state: summary.state,\n    waitingFor: summary.waitingFor,\n    claimed: summary.claimed,\n    deferredAt: summary.deferredAt.toISOString(),\n    ...(summary.expiresAt !== undefined\n      ? { expiresAt: summary.expiresAt.toISOString() }\n      : {}),\n    ...(summary.outcome !== undefined\n      ? {\n          outcome: {\n            kind: summary.outcome.kind,\n            at: summary.outcome.at.toISOString(),\n            ...(summary.outcome.reason !== undefined\n              ? { reason: summary.outcome.reason }\n              : {}),\n            ...(summary.outcome.by !== undefined\n              ? {\n                  by: {\n                    subject: summary.outcome.by.subject,\n                    ...(summary.outcome.by.issuer !== undefined\n                      ? { issuer: summary.outcome.by.issuer }\n                      : {}),\n                    ...(summary.outcome.by.clientId !== undefined\n                      ? { clientId: summary.outcome.by.clientId }\n                      : {}),\n                  },\n                }\n              : {}),\n          },\n        }\n      : {}),\n  };\n}\n\n/**\n * Read a cursor key back, refusing anything the store would have to guess\n * at. A malformed key is the caller's, and `RC5059` is the code the mount\n * answers as a 400 naming the rule, exactly as it does for a bad `limit`.\n */\nfunction decodeKey(key: string): DeferralListCursor {\n  const at = key.indexOf(KEY_SEPARATOR);\n  const millis = at <= 0 ? Number.NaN : Number(key.slice(0, at));\n  const id = at <= 0 ? \"\" : key.slice(at + 1);\n  // Range-checked, not merely finite: JavaScript's time range stops at\n  // 8.64e15 ms, so a finite value past it builds an Invalid Date that\n  // sails through here and is caught one layer down by the store, whose\n  // RC5044 the mount renders as a 500. A cursor a caller mangled is a\n  // 400, and this is the layer that owns saying so.\n  const deferredAt = new Date(millis);\n  if (\n    !Number.isFinite(millis) ||\n    Number.isNaN(deferredAt.getTime()) ||\n    id.length === 0\n  ) {\n    malformedCursor();\n  }\n  return { deferredAt, id };\n}\n\n/**\n * Bind a cursor to the filter that produced it, so a cursor minted under\n * one state or route filter is refused under another.\n */\nfunction scopeOf(state: DeferralState | \"all\", routeId?: string): CursorScope {\n  return cursorScope(DEFERRALS_RESOURCE, state, routeId);\n}\n\n/**\n * The state a query asks for. `all` is a filter value rather than an\n * omitted parameter so a cursor can be bound to it: \"no state given\" and\n * \"both states\" would otherwise fingerprint differently while paging the\n * same result set.\n */\nfunction stateOf(raw: string | undefined): DeferralState | \"all\" {\n  if (raw === undefined) return DEFAULT_STATE;\n  if (raw === \"waiting\" || raw === \"settled\" || raw === \"all\") return raw;\n  throw rcError(\"RC5059\", undefined, {\n    message: `The state filter must be \"waiting\", \"settled\" or \"all\"; received ${JSON.stringify(raw)}.`,\n  });\n}\n\n/**\n * The store's listing, or a refusal naming what is missing.\n *\n * The member is required on the interface, so this branch is unreachable\n * from typed code and exists for the consumers who do not reach it that\n * way: a JavaScript store, or an upgrade that skipped a typecheck.\n * Answering an empty page would be indistinguishable from an instance\n * with nothing deferred, which is the one answer this surface must never\n * give wrongly.\n *\n * @throws RC5066 when the configured store does not implement `list`\n */\nfunction listingOf(store: DeferralStore): DeferralStore[\"list\"] {\n  if (typeof store.list !== \"function\") {\n    throw rcError(\"RC5066\", undefined, {\n      message:\n        'The deferral store configured on this context does not implement \"list\", which GET /ops/deferrals reads. Implement DeferralStore.list, or use one of the shipped backends (sqlite or memory).',\n    });\n  }\n  return store.list.bind(store);\n}\n\n/**\n * Contribute `GET /ops/deferrals` to the management API.\n *\n * Called from the deferral plugin's `apply()`, so a context that\n * configured deferral has the listing and one that did not has no\n * resource at all rather than an empty one. A second registration of the\n * name is refused by the seam, which is what a context carrying two\n * deferral plugins deserves.\n *\n * @internal\n */\nexport function registerDeferralsResource(ctx: CraftContext): void {\n  registerOpsResource<OpsDeferralSummary>(ctx, {\n    name: DEFERRALS_RESOURCE,\n    async list(query): Promise<OpsPage<OpsDeferralSummary>> {\n      const runtime = ctx.getStore(DEFERRAL_RUNTIME);\n      // Not an empty page. This resource is registered by the deferral\n      // plugin's own `apply()`, immediately after it sets the runtime, so\n      // there is no state in which it is served without one; and an empty\n      // listing is exactly the lie RC5066 exists to refuse, whatever the\n      // reason the store cannot answer.\n      if (runtime === undefined) {\n        throw rcError(\"RC5066\", undefined, {\n          message:\n            \"The deferrals resource is registered but this context holds no deferral runtime, so there is no store to list.\",\n        });\n      }\n      const list = listingOf(runtime.store);\n      const state = stateOf(query[\"state\"]);\n      const routeId = query[\"route\"];\n      const scope = scopeOf(state, routeId);\n      const page = parsePageQuery(query);\n      const limit = page.limit ?? DEFAULT_PAGE_SIZE;\n      const after =\n        page.after === undefined\n          ? undefined\n          : decodeKey(decodeCursor(page.after, scope));\n\n      // One more than the page, so \"is there another page\" is answered by\n      // the read rather than by a second query or by a count that a\n      // concurrent defer would invalidate between the two.\n      const rows = await list({\n        ...(state === \"all\" ? {} : { state }),\n        ...(routeId !== undefined ? { routeId } : {}),\n        limit: limit + 1,\n        ...(after !== undefined ? { after } : {}),\n      });\n      const items = rows.slice(0, limit);\n      const last = items[items.length - 1];\n      return rows.length > limit && last !== undefined\n        ? {\n            items: items.map(onWire),\n            nextCursor: encodeCursor(encodeKey(last), scope),\n          }\n        : { items: items.map(onWire) };\n    },\n    async describe(segments): Promise<OpsDeferralSummary | undefined> {\n      // One segment: a deferral is named by its id alone. The id contains\n      // a `#`, which the mount has already decoded out of the path.\n      if (segments.length !== 1) return undefined;\n      const runtime = ctx.getStore(DEFERRAL_RUNTIME);\n      // Undefined here is a 404, which is the right answer for an id\n      // lookup and is why this arm diverges from the collection's throw:\n      // \"no such deferral\" is what a reader asked about, and it is true.\n      if (runtime === undefined) return undefined;\n      // Through `get` rather than the listing, because addressing one\n      // record by id is what `get` is, and the summary projection is the\n      // same either way. The stored exchange is dropped here rather than\n      // rendered, as it is for the collection.\n      const deferral = await runtime.store.get(segments[0]!);\n      return deferral === undefined\n        ? undefined\n        : onWire(summariseDeferral(deferral));\n    },\n  });\n}\n","/**\n * Whether a deferred exchange is still waiting or has settled.\n *\n * Two values, because the five that came before were answers to three\n * different questions. What the work is waiting FOR is\n * {@link Deferral.waitingFor}; how it settled is {@link Deferral.outcome};\n * whether a delivery claim is outstanding is {@link Deferral.claimedAt}. A\n * reader asks one of those and reads the field that answers it, instead of\n * inferring all three from which of five values a record landed on.\n *\n * A deferral is resumable while it is `waiting` AND unclaimed. The claim is\n * a second axis rather than a third state: whoever holds it owns telling the\n * route, and a claim whose holder died is released by\n * {@link DeferralStore.releaseClaims} once its lease elapses, so the next\n * sweep redelivers. Every transition goes through the store's\n * compare-and-swap methods so exactly one caller wins a race between a\n * resume, a sweep, and a cancellation.\n */\nexport type DeferralState = \"waiting\" | \"settled\";\n\n/**\n * What a deferral is waiting for.\n *\n * One value today: `.defer()` waits for somebody to call `.resume()`. It is\n * a stored field rather than an implied constant so a management surface can\n * group by it, and so the kinds #737 and #738 add (asking a person, handing\n * work outside the process) widen this union instead of introducing a second\n * vocabulary beside it.\n *\n * Kept on a settled record too, because it says what the work WAS waiting\n * for. That is what makes \"expired while waiting for a resume\" readable off\n * one record rather than reconstructed from two.\n */\nexport type DeferralWaitingFor = \"resume\";\n\n/**\n * Keyset cursor for {@link DeferralStore.findExpired}.\n *\n * Pages advance strictly past `(expiresAt, id)`, so a record the caller\n * visited and could not retire is never re-read by the same pass, whatever\n * its state. That is what makes an arbitrarily long unretirable prefix\n * unable to starve the records behind it.\n */\nexport interface ExpiredScanCursor {\n  readonly expiresAt: Date;\n  readonly id: string;\n}\n\n/**\n * Keyset cursor for {@link DeferralStore.list}.\n *\n * A deferral id is `{exchangeId}#{sequence}` and an exchange id is a uuid,\n * so id order says nothing about time. The listing is ordered by\n * `(deferredAt, id)` instead, which is the order an operator reads it in:\n * what has been waiting longest is what they are looking for.\n */\nexport interface DeferralListCursor {\n  readonly deferredAt: Date;\n  readonly id: string;\n}\n\n/**\n * What {@link DeferralStore.list} is being asked for.\n *\n * `state` defaults to `waiting` at the caller rather than here, because a\n * store implementation must not have to know which half of the collection\n * a management surface considers interesting.\n */\nexport interface DeferralListQuery {\n  /** Only deferrals in this state. Both states when absent. */\n  readonly state?: DeferralState;\n  /** Only deferrals belonging to this route. */\n  readonly routeId?: string;\n  /** Bound on one page. A non-positive or non-integer value throws. */\n  readonly limit: number;\n  /** Resume strictly past this position in `(deferredAt, id)` order. */\n  readonly after?: DeferralListCursor;\n}\n\n/**\n * One deferral as a management surface presents it.\n *\n * A projection rather than the record, and deliberately so: the record\n * carries the serialized exchange, the step state and the resume-payload\n * schema, none of which a listing may show and none of which it should\n * pull into memory a page at a time to then drop. What a reader needs is\n * what it is waiting for, how long it has waited, and whether anything\n * already holds it.\n */\nexport interface DeferralSummary {\n  readonly id: string;\n  readonly routeId: string;\n  readonly state: DeferralState;\n  /** What the work is waiting for, or was waiting for when it settled. */\n  readonly waitingFor: DeferralWaitingFor;\n  /**\n   * Whether a delivery claim is outstanding, rather than when it was\n   * taken. A reader asks whether anything already owns telling the route,\n   * and the timestamp is an implementation detail of the lease.\n   */\n  readonly claimed: boolean;\n  readonly deferredAt: Date;\n  /** When the sweeper will expire it. Absent means no deadline. */\n  readonly expiresAt?: Date;\n  /** How it settled. Absent while it is waiting. */\n  readonly outcome?: DeferralOutcome;\n}\n\n/**\n * Whether a delivery claim is outstanding right now.\n *\n * Only while waiting. `markExpired` and `markDenied` both settle a record\n * through a claim and neither clears `claimedAt`, so the stored timestamp\n * says a claim once existed, never that one is still held. Exported\n * because the sqlite store summarises from columns rather than from a\n * `Deferral`, and the two readings have to agree.\n */\nexport function claimIsOutstanding(\n  state: DeferralState,\n  claimedAt: Date | null | undefined,\n): boolean {\n  return state === \"waiting\" && claimedAt != null;\n}\n\n/**\n * Project a stored record onto what a management surface may see.\n *\n * Named once and shared by both backends so a field can never reach the\n * listing from one store and not the other, and so the exchange has one\n * place it is dropped rather than one per backend.\n */\nexport function summariseDeferral(deferral: Deferral): DeferralSummary {\n  return {\n    id: deferral.id,\n    routeId: deferral.routeId,\n    state: deferral.state,\n    waitingFor: deferral.waitingFor,\n    claimed: claimIsOutstanding(deferral.state, deferral.claimedAt),\n    deferredAt: deferral.deferredAt,\n    ...(deferral.expiresAt !== undefined\n      ? { expiresAt: deferral.expiresAt }\n      : {}),\n    ...(deferral.outcome !== undefined ? { outcome: deferral.outcome } : {}),\n  };\n}\n\n/**\n * The persisted form of a deferred exchange: exactly the two stored slots of\n * `Exchange` (`body` and `headers`), per\n * `.standards/exchange-state-model.md`. Derivations (`id`, `principal`,\n * `logger`) are rebuilt by constructing a `DefaultExchange` around these\n * two on the resuming process, so there is nothing else to persist.\n *\n * Both slots are plain JSON data. `serializeExchange` refuses anything else\n * with `RC5042` rather than writing a value the store cannot round-trip.\n */\nexport interface SerializedExchange {\n  readonly body: unknown;\n  readonly headers: Readonly<Record<string, unknown>>;\n}\n\n/**\n * How the resume-payload schema is carried on a stored deferral.\n *\n * A Standard Schema is a live object with a validate function, so it cannot\n * be persisted. What is persisted is a reference: the `(routeId, position)`\n * pair on the record identifies the deferring step, whose live `schema` is\n * read back off the route at resume time, and `hash` is folded into\n * `continuationHash` so a schema that changed under a deferred exchange fails\n * the compatibility check rather than validating against the wrong\n * contract.\n *\n * `jsonSchema` is populated opportunistically from the non-standard\n * `~standard.jsonSchema` extension that Zod, ArkType and the AI SDK bridge\n * expose. It is descriptive only: it tells a caller and an operator what a\n * a valid resume payload looks like. Validation always runs against the live schema.\n *\n * A site that declares NO schema still gets a descriptor, carrying\n * {@link DeferralSchema.absent}. That sentinel is deliberately distinct\n * from the degraded fallback below: without it, editing a site from a\n * declared-but-unrenderable schema to no schema at all would leave the\n * digest unmoved, so a recipient told there was a contract would have their\n * payload accepted unvalidated with no re-ask.\n */\nexport interface DeferralSchema {\n  /** Stable hash of the resume-payload schema, or the absent sentinel. */\n  readonly hash: string;\n  /** Set when the site declared no schema at all. */\n  readonly absent?: boolean;\n  /** JSON Schema rendering when the schema exposes one. Never used to validate. */\n  readonly jsonSchema?: unknown;\n  /**\n   * Set when the schema advertised a `~standard.jsonSchema` extension that\n   * then produced nothing, so {@link DeferralSchema.hash} identifies only\n   * the vendor rather than the contract.\n   *\n   * The consequence is worth stating where it is read: the step tail is\n   * still hashed, but a widened or narrowed schema of that kind cannot\n   * move the digest, so a resume will not catch it. Zod throws for\n   * unrepresentable types (a `Date`, a `bigint`, any `.transform()`), which\n   * makes this reachable with an ordinary approval schema.\n   */\n  readonly degraded?: boolean;\n}\n\n/**\n * Audit record of who resumed a deferral.\n *\n * A subset of `Principal` rather than the principal itself: the store is a\n * persistence surface, and a full principal carries claims, scopes and a\n * delegation chain that would be resurrected as data with no verification\n * behind it. What is recorded is enough to answer \"who authorized this\",\n * which is what the receipt is for.\n */\nexport interface PrincipalRef {\n  readonly subject: string;\n  readonly issuer?: string;\n  readonly clientId?: string;\n  /** The outermost actor's subject when a delegate resumed on someone's behalf. */\n  readonly actorSubject?: string;\n}\n\n/**\n * How a deferral settled.\n *\n * Present exactly when {@link Deferral.state} is `settled` and absent\n * exactly while it is `waiting`. Nothing in the type system enforces that\n * pairing; the store's transitions do, because every one of them writes\n * `state` and `outcome` in the same compare-and-swap.\n */\nexport interface DeferralOutcome {\n  /** Which way it ended. */\n  readonly kind: \"resumed\" | \"expired\" | \"denied\";\n  /**\n   * When the record left the waiting state. This is the retention clock:\n   * {@link DeferralStore.purgeSettled} measures from here, so a record that\n   * waits for months and settles today is kept for the full retention\n   * window from today.\n   */\n  readonly at: Date;\n  /** Why a `denied` deferral was denied (cancellation, operator action). */\n  readonly reason?: string;\n  /** Who resumed it. Only ever set on a `resumed` outcome. */\n  readonly by?: PrincipalRef;\n}\n\n/**\n * The cached result of execution two, written once the resumed exchange\n * settles. A duplicate resume returns this instead of running the\n * continuation a second time.\n */\nexport interface SerializedOutcome {\n  /**\n   * How execution two ended. `deferred` is the two-stage-approval case:\n   * the continuation reached ANOTHER `.defer()` and deferred again, so the\n   * work is neither finished nor failed. It is recorded distinctly because\n   * calling it `completed` would tell a receipt, a dashboard, and every\n   * duplicate resume that the work finished while it is still waiting on\n   * the next resume.\n   */\n  readonly status: \"completed\" | \"failed\" | \"dropped\" | \"deferred\";\n  /** Terminal body on a completed run. Plain JSON data, same rule as {@link SerializedExchange}. */\n  readonly body?: unknown;\n  /** Error code and message on a failed run. The stack is deliberately not persisted. */\n  readonly error?: { readonly rc?: string; readonly message: string };\n  /** Drop reason on a dropped run. */\n  readonly reason?: string;\n  readonly at: Date;\n}\n\n/**\n * A deferred exchange plus everything needed to revive it.\n *\n * The record is deliberately free of anything agent-shaped. A deferring\n * step that needs to carry closure state of its own puts it in\n * {@link Deferral.stepState}, which the store never interprets; that one\n * opaque slot is what lets the agent tier (#258) share this store instead\n * of growing a second one.\n */\nexport interface Deferral {\n  /** Deferral identity. Distinct from the deferred exchange's own id. */\n  readonly id: string;\n  /** Route the deferred exchange belongs to. Resume re-enters this route. */\n  readonly routeId: string;\n  /** Index of the deferring step. Execution two resumes at `position + 1`. */\n  readonly position: number;\n  /**\n   * Hash over steps `position + 1` to the end of the pipeline, plus the\n   * resume-payload schema descriptor.\n   *\n   * {@link Deferral.meta} is deliberately NOT folded in. It lives only on\n   * the record, so it has no live copy to drift from: a defer site that\n   * snapshots its policy there is protected by where the value lives rather\n   * than by a tamper check.\n   *\n   * Covers step DEFINITIONS only: what a `direct()` route the tail forwards\n   * to actually does, which version an adapter is on, and how an external\n   * system behaves can all change without moving this hash. See\n   * {@link continuationHash}.\n   */\n  readonly continuationHash: string;\n  readonly exchange: SerializedExchange;\n  readonly schema: DeferralSchema;\n  /**\n   * Whatever the deferring step attached at deferral, persisted verbatim and\n   * handed back to the resume route's `authorize` hook.\n   *\n   * The framework never reads it. Who may resume a deferred run is the\n   * application's policy, and this is where the deferral carries whatever that\n   * policy needs: a channel name, the roles the defer site required, an amount,\n   * a snapshot of the policy in force at deferral time. Subject to the same\n   * plain-JSON rule as the exchange (`RC5042`).\n   *\n   * On the agent surface it is supplied by a tool handler, which means the\n   * MODEL influenced it. Treat it as data the defer site chose, not as a fact\n   * the framework vouches for.\n   */\n  readonly meta?: unknown;\n  /**\n   * Which call this record belongs to, when the deferring step mints one\n   * credential per call.\n   *\n   * A batch of parallel tool calls shares one record (one deferral) while each\n   * handler sends its own recipient a link. Only the call that actually won\n   * the deferral may be resumed, so its identity is recorded here and every\n   * credential carries the same value as its `sub` claim. A losing sibling's\n   * recipient then takes `RC5055` rather than resuming a deferral that was never\n   * theirs.\n   *\n   * Absent for an ordinary `.defer()`, where there is nothing to\n   * disambiguate.\n   */\n  readonly callBinding?: string;\n  /**\n   * Opaque state owned by the deferring step. Absent for an ordinary step;\n   * an agent step puts its messages thread and outstanding tool-call id\n   * here. The store persists it verbatim and never reads into it, so it is\n   * subject to the same JSON-data rule as the exchange.\n   */\n  readonly stepState?: unknown;\n  /**\n   * Binds an approval to the operation it authorized rather than to a\n   * deferral id, so a receipt reads \"this principal authorized this exact\n   * operation\". See {@link actionFingerprint}.\n   */\n  readonly actionFingerprint: string;\n  readonly deferredAt: Date;\n  /** When the sweeper will expire this deferral. Absent means no TTL. */\n  readonly expiresAt?: Date;\n  /**\n   * When the outstanding delivery claim was taken, which is BEFORE the\n   * notification: it is a claim timestamp, not proof of delivery. Set only\n   * on a `waiting` record, cleared when a stale claim is released, and kept\n   * on a settled one as the record of who got there first.\n   *\n   * Load-bearing rather than informational: a claimed record is not\n   * resumable, because the claim holder owns the outcome. That is the\n   * compare every transition out of `waiting` makes.\n   */\n  readonly claimedAt?: Date;\n  readonly state: DeferralState;\n  readonly waitingFor: DeferralWaitingFor;\n  /** How it settled. Absent while {@link Deferral.state} is `waiting`. */\n  readonly outcome?: DeferralOutcome;\n  /** Cached result of execution two, for idempotent re-resume. */\n  readonly continuation?: SerializedOutcome;\n}\n\n/**\n * A deferral as it is handed to {@link DeferralStore.create}.\n *\n * A record is born `waiting`, so the fields only a transition can produce\n * are not part of the input. Taking a full {@link Deferral} would let a\n * caller insert a record that is already settled, and every compare-and-swap\n * in the contract then refuses to move it: the exchange is deferred\n * permanently, with no error to notice.\n */\nexport type NewDeferral = Omit<Deferral, DeferralTransitionField> & {\n  // Declared as optional `never` rather than merely omitted. A plain `Omit`\n  // is satisfied by a full `Deferral` variable, because excess-property\n  // checking only fires on a fresh object literal, so the one shape most\n  // likely to carry a settled status (a record read back out of the store\n  // and handed to `create`) would have passed unremarked.\n  readonly [K in DeferralTransitionField]?: never;\n};\n\n/**\n * The fields only a `mark*` transition may write.\n */\ntype DeferralTransitionField =\n  \"state\" | \"outcome\" | \"continuation\" | \"claimedAt\";\n\n/**\n * Details recorded when a resume wins the compare-and-swap.\n */\nexport interface DeferralResumption {\n  readonly at: Date;\n  readonly by?: PrincipalRef;\n}\n\n/**\n * Result of a compare-and-swap on a deferral.\n *\n * `won` is the load-bearing field: it reports whether THIS caller performed\n * the transition. A resume arriving at the same moment the sweeper expires\n * the deferral produces exactly one `won: true`, and the loser reads\n * `deferral.outcome` to find out what happened instead.\n *\n * `deferral` is the record as it stands after the attempt, so a loser\n * does not need a second read to react. It is `undefined` only when the id\n * is unknown.\n */\nexport interface DeferralCasResult {\n  readonly won: boolean;\n  readonly deferral: Deferral | undefined;\n}\n\n/**\n * What the startup scan reports at info level.\n */\nexport interface PendingDeferralSummary {\n  /** Deferrals still waiting. */\n  readonly count: number;\n  /** `deferredAt` of the oldest of them, absent when there are none. */\n  readonly oldest?: Date;\n}\n\n/**\n * Whether a deferral can still be resumed: waiting, with no delivery claim\n * outstanding.\n *\n * The two-field condition every transition out of waiting compares against,\n * named once so the stores, the revival path and the sweeper cannot drift on\n * it. A claimed record is deliberately excluded even though it is still\n * waiting: the claim holder owns the outcome, and letting a resume in behind\n * it would produce two notifications for one event.\n */\nexport function resumable(deferral: Deferral): boolean {\n  return deferral.state === \"waiting\" && deferral.claimedAt === undefined;\n}\n\n/**\n * Whether a delivery claim is outstanding on a waiting deferral, which is\n * what {@link DeferralStore.markExpired} and\n * {@link DeferralStore.markDenied} settle.\n */\nexport function claimed(\n  deferral: Deferral,\n): deferral is Deferral & { readonly claimedAt: Date } {\n  return deferral.state === \"waiting\" && deferral.claimedAt !== undefined;\n}\n\n/**\n * Persistence contract for deferred exchanges.\n *\n * Two backends ship: {@link MemoryDeferralStore} for tests and ephemeral\n * use, and {@link SqliteDeferralStore} as the durable default wherever\n * the runtime allows. Postgres and redis are out of scope; the contract is\n * shaped so they can be added without touching call sites, which is why\n * every method is async and why the state transitions are compare-and-swap\n * rather than read-then-write.\n *\n * Implementations must treat the three `mark*` methods as atomic with\n * respect to each other. Single-node coordination is all that is required\n * today, but a read-then-write implementation cannot be made safe later\n * without a rewrite, and the atomic form costs nothing now.\n */\nexport interface DeferralStore {\n  /**\n   * Persist a newly deferred exchange. Throws if `record.id` already exists:\n   * a deferral id is minted per defer and a collision means a bug, not\n   * a retry. The stored record is `waiting` and unclaimed; only the\n   * transitions below move it.\n   */\n  create(record: NewDeferral): Promise<void>;\n\n  /** Load a deferral by id. `undefined` when the id is unknown. */\n  get(id: string): Promise<Deferral | undefined>;\n\n  /**\n   * Settle an unclaimed waiting deferral as `resumed`, recording who resumed\n   * it and when. Exactly one concurrent caller wins.\n   */\n  markResumed(\n    id: string,\n    resumption: DeferralResumption,\n  ): Promise<DeferralCasResult>;\n\n  /**\n   * Claim an unclaimed waiting deferral for delivery, recording when the\n   * claim was taken. The record stays `waiting`, which is the point: a claim\n   * is not an outcome. Winning it is the right to notify the route, and the\n   * caller delivers the re-ask and then settles with\n   * {@link DeferralStore.markExpired} or {@link DeferralStore.markDenied}. A\n   * holder that dies mid-delivery is healed by\n   * {@link DeferralStore.releaseClaims} rather than leaving the record\n   * stuck.\n   *\n   * A released EXPIRY claim is overdue, so the next sweep redelivers it. A\n   * released DENIAL claim is not, so its redelivery waits for the next\n   * replay of the token, or for the deadline, whichever comes first; the\n   * proactive nag is lost only for a record that has no deadline and is\n   * never replayed, which is the pre-lease behaviour for every crash.\n   */\n  claimExpiry(id: string, at: Date): Promise<DeferralCasResult>;\n\n  /**\n   * Settle a claimed deferral as `expired`, stamping\n   * {@link DeferralOutcome.at} at the write. `expiresAt` still says when the\n   * deferral came due and `claimedAt` when its delivery was claimed; the\n   * outcome's own timestamp is when the record actually stopped waiting,\n   * which is what retention measures from.\n   */\n  markExpired(id: string): Promise<DeferralCasResult>;\n\n  /**\n   * Settle a claimed deferral as `denied`, stamping\n   * {@link DeferralOutcome.at} at the write.\n   * The claim-first shape applies to denial for the same reason as expiry:\n   * a crash between the transition and the notification must heal by\n   * redelivery, not strand the approver. Cancellation (#552) will claim\n   * first too.\n   */\n  markDenied(id: string, reason?: string): Promise<DeferralCasResult>;\n\n  /**\n   * Release every delivery claim taken at or before `before` by clearing\n   * {@link Deferral.claimedAt}, and report how many were released. The\n   * records were and remain `waiting`; what changes is that they are\n   * resumable and sweepable again.\n   *\n   * This is the healing half of the claim: a released record is past its\n   * deadline, so the next ordinary sweep pass redelivers it. A crash after\n   * delivery but before finalize therefore costs one duplicate escalation\n   * after the lease elapses, which is the accepted at-least-once trade;\n   * a crash before delivery costs nothing but the lease's delay.\n   */\n  releaseClaims(before: Date): Promise<number>;\n\n  /**\n   * Compare-and-swap the opaque {@link Deferral.stepState} slot of a\n   * record that is STILL waiting and unclaimed, leaving every other field\n   * alone.\n   *\n   * The one write that edits a waiting record in place rather than settling\n   * it. Compaction is the motivating caller: an agent's deferred thread grows\n   * past what the model will accept, and shrinking it has to happen while\n   * the exchange stays deferred, because a resume that lands on an\n   * unshrinkable thread has nowhere to go.\n   *\n   * Two races are closed by the same compare. `expected` is the\n   * `stepStateFingerprint` of the state the caller read and rewrote, so two\n   * compactions of the same record produce one winner and one `won: false`\n   * holding the state that landed, instead of the second silently\n   * discarding the first. And the swap only matches an unclaimed waiting\n   * row, so a resume or a sweep that got there first wins outright: the compaction is\n   * refused rather than rewriting the thread of a run that is already\n   * executing its continuation.\n   *\n   * The store still never reads INTO the slot. Whether the replacement is a\n   * usable thread is the owning tier's question, and `@routecraft/ai`\n   * answers it before calling this.\n   *\n   * @param id - Deferral whose step state is being replaced\n   * @param expected - Fingerprint of the step state the caller based its\n   *   replacement on, from `stepStateFingerprint`\n   * @param stepState - The replacement. Subject to the same plain-JSON rule\n   *   as every other free-form slot (`RC5042`). `undefined` clears the slot\n   *   on every backend.\n   */\n  replaceStepState(\n    id: string,\n    expected: string,\n    stepState: unknown,\n  ): Promise<DeferralCasResult>;\n\n  /**\n   * Cache the result of execution two so a duplicate resume can reply\n   * without re-running the continuation. Silently ignores an unknown id: the\n   * cache is a convenience, and losing the race to a sweep must not turn\n   * into a second failure on the way out.\n   *\n   * Unconditional by design: only the caller that won `markResumed` ever\n   * writes a continuation, so there is no competing writer for this row and\n   * a compare would defend nothing.\n   */\n  recordContinuation(\n    id: string,\n    continuation: SerializedOutcome,\n  ): Promise<void>;\n\n  /**\n   * Deferrals still waiting and unclaimed whose `expiresAt` is at or\n   * before `now`, ordered by `(expiresAt ASC, id ASC)` and starting\n   * strictly after `after` when one is given. `limit` bounds one page so a\n   * backlog accumulated while the process was down does not produce an\n   * unbounded batch.\n   *\n   * The ordering is a strict total order within a backend, which is what\n   * makes the cursor sound; it is not guaranteed byte-identical across\n   * backends for non-ASCII ids, so a cursor must only ever be replayed\n   * against the store that produced it.\n   *\n   * A non-positive or non-integer `limit`, or a malformed `after`, is a\n   * caller error and throws rather than being interpreted.\n   */\n  findExpired(\n    now: Date,\n    limit: number,\n    after?: ExpiredScanCursor,\n  ): Promise<Deferral[]>;\n\n  /** Count and oldest `deferredAt` across deferrals still waiting. */\n  pending(): Promise<PendingDeferralSummary>;\n\n  /**\n   * One page of deferrals as a management surface presents them, ordered\n   * `(deferredAt ASC, id ASC)` and starting strictly after\n   * {@link DeferralListQuery.after} when one is given.\n   *\n   * Ordered by time rather than by id because a deferral id is\n   * `{exchangeId}#{sequence}` over a uuid, so id order is arbitrary and a\n   * listing in it answers no question anyone asks. Oldest first is the\n   * question: what has been waiting longest.\n   *\n   * A projection rather than the records, so the serialized exchange, the\n   * step state and the resume-payload schema never enter the read path at\n   * all. The listing must not show them, and a store that returned whole\n   * records would page a hundred thousand exchange bodies through memory\n   * on the way to dropping them.\n   *\n   * The ordering is a strict total order within a backend, and as with\n   * {@link DeferralStore.findExpired} it is not guaranteed byte-identical\n   * across backends for non-ASCII ids, so a cursor is only ever replayed\n   * against the store that produced it.\n   *\n   * A non-positive or non-integer `limit` is a caller error and throws\n   * rather than being interpreted.\n   */\n  list(query: DeferralListQuery): Promise<DeferralSummary[]>;\n\n  /**\n   * Records settled as `resumed` whose continuation never landed, oldest\n   * first.\n   *\n   * This is crash residue. A resume wins the compare-and-swap out of\n   * `waiting` BEFORE running the continuation and caches the result after,\n   * so a record in this state means the process died between the two.\n   * The approval is spent, the work half ran, and nothing will ever revisit\n   * it: it is invisible to {@link DeferralStore.findExpired}, which only\n   * looks at waiting records.\n   *\n   * Re-running a\n   * continuation whose side effects may have half happened needs a lease on\n   * the resumed outcome and idempotent continuations, which is the\n   * admission-and-idempotency work tracked separately. What this method is\n   * for is the boot summary after an outage, which is the first moment\n   * anyone could learn such a record exists.\n   *\n   * The asymmetry with the delivery claim is deliberate: expiry\n   * NOTIFICATIONS heal by redelivery because re-sending a nag is safe,\n   * while this residue is a half-run CONTINUATION and is only ever\n   * reported.\n   *\n   * @param limit - Cap on records returned. Omit for all of them.\n   */\n  resumedWithoutContinuation(limit?: number): Promise<Deferral[]>;\n\n  /**\n   * Delete settled deferrals whose {@link DeferralOutcome.at} is before\n   * `before`, and report how many went.\n   *\n   * A settled record holds a full serialized exchange body plus its cached\n   * continuation, and nothing else ever removes one. Without a\n   * retention path a long-running process accumulates every exchange that\n   * ever deferred: on disk under sqlite, and on the heap under the\n   * in-memory backend, which is also the automatic fallback for a Node\n   * install without a driver. Waiting records are never touched, whatever\n   * their age; expiring them is the sweeper's job and goes through\n   * {@link DeferralStore.markExpired}.\n   *\n   * The cutoff is the outcome's timestamp, not `deferredAt`: retention\n   * promises how long a SETTLED record is kept, and measuring from the\n   * deferral would purge a record that waited 89 days and settled on day 89\n   * one day after it settled.\n   */\n  purgeSettled(before: Date): Promise<number>;\n\n  /** Release backend resources. Idempotent. */\n  close(): Promise<void>;\n}\n","import { rcError } from \"../error.ts\";\nimport { compareCodeUnits } from \"../shared/compare.ts\";\nimport { stepStateFingerprint } from \"./hash.ts\";\nimport { encodePersistable } from \"./serialize.ts\";\nimport { claimed, resumable, summariseDeferral } from \"./types.ts\";\nimport type {\n  ExpiredScanCursor,\n  NewDeferral,\n  PendingDeferralSummary,\n  SerializedOutcome,\n  Deferral,\n  DeferralCasResult,\n  DeferralListCursor,\n  DeferralListQuery,\n  DeferralResumption,\n  DeferralStore,\n  DeferralSummary,\n} from \"./types.ts\";\n\n/**\n * In-process deferral store.\n *\n * The default under `testContext()` and the fallback when no durable\n * backend is available. Everything it holds dies with the process, so it is\n * the right choice for tests and for a route whose deferrals are\n * genuinely ephemeral, and the wrong choice for the feature's headline\n * promise: an exchange deferred here does not survive a restart. The store\n * factory logs a warning whenever it falls back to this backend for that\n * reason.\n *\n * Records are cloned on the way in and on the way out, so a caller cannot\n * reach into stored state through a reference it kept, and the backend\n * behaves like a real one that round-trips through storage.\n *\n * The compare-and-swap methods complete within a single event-loop turn\n * (they never await between reading the status and writing it), which is\n * what makes them atomic on this backend.\n */\nexport class MemoryDeferralStore implements DeferralStore {\n  readonly #records = new Map<string, Deferral>();\n\n  /**\n   * The live record map, bypassing the transitions and the clone-on-read\n   * boundary. A test seam: the purge contract must hold for shapes the\n   * public transitions cannot produce (a settled record with no outcome),\n   * and proving that on this backend requires injecting one.\n   * Sqlite's equivalent seam is raw SQL against the database file.\n   *\n   * @internal\n   */\n  static unsafeRecords(store: MemoryDeferralStore): Map<string, Deferral> {\n    return store.#records;\n  }\n\n  async create(record: NewDeferral): Promise<void> {\n    if (this.#records.has(record.id)) {\n      throw rcError(\"RC5044\", undefined, {\n        message: `Deferral \"${record.id}\" already exists in the store.`,\n      });\n    }\n    // Built field by field rather than spread. The sqlite backend inserts\n    // only the columns it names, so anything the caller carried in beyond the\n    // creation fields leaves no trace there; a spread here would keep it\n    // alive on a record that reports itself deferred, and the two backends\n    // would stop being substitutable. `NewDeferral` types those fields\n    // away, but a store is a persistence boundary and enforces its own\n    // invariants rather than trusting the caller's compiler.\n    this.#records.set(\n      record.id,\n      clone(\n        normalise({\n          id: record.id,\n          routeId: record.routeId,\n          position: record.position,\n          continuationHash: record.continuationHash,\n          actionFingerprint: record.actionFingerprint,\n          exchange: record.exchange,\n          schema: record.schema,\n          ...(record.callBinding !== undefined\n            ? { callBinding: record.callBinding }\n            : {}),\n          ...(record.meta !== undefined ? { meta: record.meta } : {}),\n          ...(record.stepState !== undefined\n            ? { stepState: record.stepState }\n            : {}),\n          deferredAt: record.deferredAt,\n          ...(record.expiresAt !== undefined\n            ? { expiresAt: record.expiresAt }\n            : {}),\n          state: \"waiting\",\n          waitingFor: record.waitingFor,\n        }),\n      ),\n    );\n  }\n\n  async get(id: string): Promise<Deferral | undefined> {\n    const record = this.#records.get(id);\n    return record ? clone(record) : undefined;\n  }\n\n  async markResumed(\n    id: string,\n    resumption: DeferralResumption,\n  ): Promise<DeferralCasResult> {\n    return this.#transition(id, resumable, {\n      state: \"settled\",\n      outcome: {\n        kind: \"resumed\",\n        at: resumption.at,\n        ...(resumption.by ? { by: resumption.by } : {}),\n      },\n    });\n  }\n\n  async claimExpiry(id: string, at: Date): Promise<DeferralCasResult> {\n    return this.#transition(id, resumable, { claimedAt: at });\n  }\n\n  async markExpired(id: string): Promise<DeferralCasResult> {\n    return this.#transition(id, claimed, {\n      state: \"settled\",\n      outcome: { kind: \"expired\", at: new Date() },\n    });\n  }\n\n  async markDenied(id: string, reason?: string): Promise<DeferralCasResult> {\n    return this.#transition(id, claimed, {\n      state: \"settled\",\n      outcome: {\n        kind: \"denied\",\n        at: new Date(),\n        ...(reason !== undefined ? { reason } : {}),\n      },\n    });\n  }\n\n  async releaseClaims(before: Date): Promise<number> {\n    let released = 0;\n    for (const [id, record] of this.#records) {\n      if (!claimed(record)) continue;\n      if (record.claimedAt.getTime() > before.getTime()) continue;\n      // eslint-disable-next-line @typescript-eslint/no-unused-vars -- destructure to omit\n      const { claimedAt: _claimedAt, ...rest } = record;\n      this.#records.set(id, clone(rest));\n      released++;\n    }\n    return released;\n  }\n\n  async replaceStepState(\n    id: string,\n    expected: string,\n    stepState: unknown,\n  ): Promise<DeferralCasResult> {\n    // Before the compare, matching the sqlite backend, so an unpersistable\n    // replacement is RC5042 on both rather than RC5042 on one and a quiet\n    // `won: false` on the other. The slot is free-form, so a caller can hand\n    // back a value the durable backend would refuse, and finding that out\n    // only after a failover is the bug this avoids.\n    const encoded = encodePersistable(stepState, \"stepState\");\n    const record = this.#records.get(id);\n    if (!record) return { won: false, deferral: undefined };\n    if (\n      !resumable(record) ||\n      stepStateFingerprint(record.stepState) !== expected\n    ) {\n      return { won: false, deferral: clone(record) };\n    }\n    // Deleted rather than held as an undefined-valued key, so a cleared slot\n    // reads back the same way it does from the durable backend, where the\n    // column is NULL.\n    const next = { ...record, stepState: encoded };\n    if (encoded === undefined) delete next.stepState;\n    const stored = clone(next);\n    this.#records.set(id, stored);\n    return { won: true, deferral: clone(stored) };\n  }\n\n  async recordContinuation(\n    id: string,\n    continuation: SerializedOutcome,\n  ): Promise<void> {\n    const record = this.#records.get(id);\n    if (!record) return;\n    this.#records.set(\n      id,\n      clone({\n        ...record,\n        continuation: {\n          ...continuation,\n          ...(continuation.body !== undefined\n            ? {\n                body: encodePersistable(continuation.body, \"continuation.body\"),\n              }\n            : {}),\n        },\n      }),\n    );\n  }\n\n  /**\n   * The shared shape of the deferredAt-ordered queries: limit validation,\n   * oldest first, an omitted limit meaning all of them, and a defensive\n   * copy on the way out. The expiry scan orders by `(expiresAt, id)` for\n   * its cursor and does not go through here.\n   */\n  #scan(matches: (record: Deferral) => boolean, limit?: number): Deferral[] {\n    assertSweepLimit(limit);\n    const found = [...this.#records.values()]\n      .filter(matches)\n      .sort((a, b) => a.deferredAt.getTime() - b.deferredAt.getTime());\n    return (limit === undefined ? found : found.slice(0, limit)).map(clone);\n  }\n\n  async findExpired(\n    now: Date,\n    limit: number,\n    after?: ExpiredScanCursor,\n  ): Promise<Deferral[]> {\n    assertSweepLimit(limit);\n    assertScanCursor(after);\n    const found = [...this.#records.values()]\n      .filter(\n        (record) =>\n          resumable(record) &&\n          record.expiresAt !== undefined &&\n          record.expiresAt.getTime() <= now.getTime() &&\n          (after === undefined ||\n            record.expiresAt.getTime() > after.expiresAt.getTime() ||\n            (record.expiresAt.getTime() === after.expiresAt.getTime() &&\n              compareCodeUnits(record.id, after.id) > 0)),\n      )\n      .sort(\n        (a, b) =>\n          (a.expiresAt?.getTime() ?? 0) - (b.expiresAt?.getTime() ?? 0) ||\n          compareCodeUnits(a.id, b.id),\n      );\n    return found.slice(0, limit).map(clone);\n  }\n\n  async resumedWithoutContinuation(limit?: number): Promise<Deferral[]> {\n    return this.#scan(\n      (record) =>\n        record.outcome?.kind === \"resumed\" && record.continuation === undefined,\n      limit,\n    );\n  }\n\n  async pending(): Promise<PendingDeferralSummary> {\n    let count = 0;\n    let oldest: Date | undefined;\n    for (const record of this.#records.values()) {\n      if (record.state !== \"waiting\") continue;\n      count++;\n      if (!oldest || record.deferredAt.getTime() < oldest.getTime()) {\n        oldest = record.deferredAt;\n      }\n    }\n    return { count, ...(oldest ? { oldest: new Date(oldest.getTime()) } : {}) };\n  }\n\n  async list(query: DeferralListQuery): Promise<DeferralSummary[]> {\n    assertSweepLimit(query.limit);\n    assertListCursor(query.after);\n    const after = query.after;\n    return (\n      [...this.#records.values()]\n        .filter(\n          (record) =>\n            (query.state === undefined || record.state === query.state) &&\n            (query.routeId === undefined || record.routeId === query.routeId) &&\n            (after === undefined ||\n              record.deferredAt.getTime() > after.deferredAt.getTime() ||\n              (record.deferredAt.getTime() === after.deferredAt.getTime() &&\n                compareCodeUnits(record.id, after.id) > 0)),\n        )\n        .sort(\n          (a, b) =>\n            a.deferredAt.getTime() - b.deferredAt.getTime() ||\n            compareCodeUnits(a.id, b.id),\n        )\n        .slice(0, query.limit)\n        // Cloned like every other read on this backend: `summariseDeferral`\n        // copies field references, so an uncloned summary would alias the\n        // stored record's `Date`s and its outcome object, and a caller\n        // normalising a listing in place would rewrite what the sweeper and\n        // the retention purge then read.\n        .map((record) => summariseDeferral(clone(record)))\n    );\n  }\n\n  async purgeSettled(before: Date): Promise<number> {\n    let purged = 0;\n    for (const [id, record] of this.#records) {\n      // Settled only. A waiting record with a delivery claim outstanding is\n      // still live, and purging one mid-delivery would strand the finalize\n      // against a row that no longer exists.\n      if (record.state !== \"settled\") continue;\n      // A settled record without an outcome is only reachable by injection\n      // around the transitions. Skipped, never dated by fallback: sqlite's\n      // NULL comparison skips the same row, and refusing to delete a record\n      // you cannot date beats purging it on the clock #634 removed.\n      if (record.outcome === undefined) continue;\n      if (record.outcome.at.getTime() >= before.getTime()) continue;\n      this.#records.delete(id);\n      purged++;\n    }\n    return purged;\n  }\n\n  /**\n   * Releases nothing, because there is nothing to release. It deliberately\n   * does NOT clear the records: `close()` means \"release backend\n   * resources\" on every other backend, and a call that is a handle release\n   * on sqlite but a data wipe here would make the two non-substitutable\n   * for any code written against the interface. The map is collected with\n   * the store. Use {@link MemoryDeferralStore.reset} to discard records.\n   */\n  async close(): Promise<void> {}\n\n  /**\n   * Discard every record. Not part of {@link DeferralStore}: wiping is\n   * specific to this backend, and a test wanting isolation should\n   * construct a fresh store rather than rely on a method an arbitrary\n   * backend may not have.\n   */\n  reset(): void {\n    this.#records.clear();\n  }\n\n  /**\n   * Compare-and-swap a record `matches` accepts. Synchronous from read to\n   * write so two concurrent callers cannot both observe the pre-transition\n   * state.\n   *\n   * The compare is a predicate rather than a state value because the\n   * resumable condition spans two fields: waiting, and no delivery claim\n   * outstanding. Sqlite spells the same compare as its `WHERE` clause.\n   */\n  #transition(\n    id: string,\n    matches: (record: Deferral) => boolean,\n    fields: Partial<Deferral>,\n  ): DeferralCasResult {\n    const record = this.#records.get(id);\n    if (!record) return { won: false, deferral: undefined };\n    if (!matches(record)) {\n      return { won: false, deferral: clone(record) };\n    }\n    // `fields` carries caller-owned values (a `Date`, a `PrincipalRef`), so\n    // the stored copy has to be detached too, not just the returned one.\n    const stored = clone({ ...record, ...fields } as Deferral);\n    this.#records.set(id, stored);\n    return { won: true, deferral: clone(stored) };\n  }\n}\n\n/**\n * Reject a `limit` the two backends would read differently. Exported so the\n * sqlite backend applies the identical rule.\n *\n * @internal\n */\nexport function assertSweepLimit(limit: number | undefined): void {\n  if (limit === undefined) return;\n  if (!Number.isInteger(limit) || limit <= 0) {\n    throw rcError(\"RC5044\", undefined, {\n      message: `The scan limit must be a positive integer; received ${String(limit)}.`,\n    });\n  }\n}\n\n/**\n * Reject a cursor a backend would have to guess at. Exported for the same\n * reason as {@link assertSweepLimit}: both backends apply the identical\n * rule.\n *\n * @internal\n */\nexport function assertScanCursor(after: ExpiredScanCursor | undefined): void {\n  if (after === undefined) return;\n  if (\n    !(after.expiresAt instanceof Date) ||\n    Number.isNaN(after.expiresAt.getTime()) ||\n    typeof after.id !== \"string\" ||\n    after.id.length === 0\n  ) {\n    throw rcError(\"RC5044\", undefined, {\n      message:\n        \"findExpired() cursor must carry a valid expiresAt Date and a non-empty id.\",\n    });\n  }\n}\n\n/**\n * Reject a listing cursor a backend would have to guess at. The mirror of\n * {@link assertScanCursor} over the other keyset, kept separate because\n * the two order by different fields and a shared check would have to be\n * told which.\n *\n * @internal\n */\nexport function assertListCursor(after: DeferralListCursor | undefined): void {\n  if (after === undefined) return;\n  // `null` only reaches here from JavaScript, where the type is not\n  // enforced. Reading its fields would raise a TypeError instead of the\n  // coded refusal every other malformed cursor gets.\n  if (\n    after === null ||\n    !(after.deferredAt instanceof Date) ||\n    Number.isNaN(after.deferredAt.getTime()) ||\n    typeof after.id !== \"string\" ||\n    after.id.length === 0\n  ) {\n    throw rcError(\"RC5044\", undefined, {\n      message:\n        \"list() cursor must carry a valid deferredAt Date and a non-empty id.\",\n    });\n  }\n}\n\n/**\n * Put the record's free-form slots through the same JSON-data rules the\n * durable backend applies, so a deployment that fell back to memory sees\n * identical values to one that did not. `structuredClone` alone would keep\n * shapes sqlite cannot store, and the divergence would only appear once a\n * driver was installed.\n *\n * @internal\n */\nfunction normalise(record: Deferral): Deferral {\n  return {\n    ...record,\n    ...(record.stepState !== undefined\n      ? { stepState: encodePersistable(record.stepState, \"stepState\") }\n      : {}),\n    ...(record.meta !== undefined\n      ? { meta: encodePersistable(record.meta, \"meta\") }\n      : {}),\n  };\n}\n\n/**\n * Detach a record from the caller. `structuredClone` preserves the `Date`\n * fields the record carries, which a JSON round trip would flatten to\n * strings.\n *\n * @internal\n */\nfunction clone(record: Deferral): Deferral {\n  return structuredClone(record) as Deferral;\n}\n","import { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { rcError } from \"../error.ts\";\nimport { isRoutecraftError } from \"../brand.ts\";\nimport { stepStateFingerprint } from \"./hash.ts\";\nimport { encodePersistable } from \"./serialize.ts\";\nimport {\n  assertListCursor,\n  assertScanCursor,\n  assertSweepLimit,\n} from \"./memory-store.ts\";\nimport {\n  type ResolvedSqliteDriver,\n  type SqliteDatabase,\n  type SqliteDriverLoaders,\n  resolveSqliteDriver,\n} from \"../shared/sqlite/driver.ts\";\nimport {\n  describeSqliteFile,\n  isSqliteBusy,\n  migrateSqlite,\n  resolveDatabasePath,\n  SQLITE_APPLICATION_IDS,\n} from \"../shared/sqlite/database.ts\";\nimport { claimIsOutstanding } from \"./types.ts\";\nimport type {\n  ExpiredScanCursor,\n  NewDeferral,\n  PendingDeferralSummary,\n  PrincipalRef,\n  SerializedExchange,\n  SerializedOutcome,\n  Deferral,\n  DeferralCasResult,\n  DeferralListQuery,\n  DeferralOutcome,\n  DeferralSchema,\n  DeferralResumption,\n  DeferralState,\n  DeferralStore,\n  DeferralSummary,\n  DeferralWaitingFor,\n} from \"./types.ts\";\n\n/**\n * Default location of the deferral database, relative to the working\n * directory. Deployments that mount a volume (the Docker showcase does)\n * override it via `deferral: { store: { path } }` or\n * `ROUTECRAFT_DEFERRAL_STORE`.\n */\nexport const DEFAULT_DEFERRAL_DB_PATH = \".routecraft/deferrals.db\";\n\n/**\n * Names this subsystem in the absent-peer error, so a Node deployment\n * missing `better-sqlite3` reads which feature asked for it.\n */\nconst SQLITE_CONSUMER = \"deferral store (sqlite)\";\n\n/**\n * Schema version this build writes. Bumped whenever\n * {@link MIGRATIONS} grows an entry.\n */\nconst SCHEMA_VERSION = 1;\n\n/**\n * How long a writer waits for a competing write lock before giving up.\n * Set explicitly because the two drivers ship different defaults.\n */\nconst BUSY_TIMEOUT_MS = 5_000;\n\n/**\n * The resumable compare, spelled once. `resumable()` in `types.ts` is the\n * same condition in TypeScript, and the memory backend uses that; a store\n * whose `WHERE` clause drifted from it would accept a resume the other\n * backend refuses.\n */\nconst RESUMABLE = \"state = 'waiting' AND claimed_at IS NULL\";\n\n/** The claimed compare, the other half of {@link RESUMABLE}. */\nconst CLAIMED = \"state = 'waiting' AND claimed_at IS NOT NULL\";\n\n/**\n * Forward-only migrations, applied in order from the database's current\n * `PRAGMA user_version` to {@link SCHEMA_VERSION}. Index `n` migrates from\n * version `n` to `n + 1`, so a fresh file (version 0) runs all of them and\n * an up-to-date one runs none. This is what makes first run safe: opening\n * the store creates its own schema, there is no separate migrate step to\n * forget.\n *\n * `deferrals_pending` carries `id` as its last column so it serves the\n * management listing's `(deferred_at, id)` keyset as well as `pending()`,\n * and `deferrals_listing` serves the same ordering with `state` unbound,\n * which is what `?state=all` and a route-only filter ask for: without it\n * that path is a full scan plus a temp sort of every surviving row, per\n * page, on a table that holds every deferral until retention takes it.\n * Both folded into version 1 rather than added as version 2 for the same\n * reason the canary chain is not carried: no released build has written\n * this file yet.\n *\n * Version 1 is the first shape a release ever wrote. The chain that built it\n * across the 0.7.0 canary is deliberately not carried: no released build\n * produced those files, and keeping the steps would preserve the retired\n * vocabulary in table and column names an operator only meets by opening the\n * database.\n *\n * Timestamps are stored as epoch milliseconds rather than SQLite datetimes\n * so ordering and comparison work without a date function, and JSON columns\n * hold the already-serialized exchange, so the store never re-encodes what\n * `serializeExchange` produced.\n */\nconst MIGRATIONS: ReadonlyArray<string> = [\n  `CREATE TABLE deferrals (\n     id                 TEXT PRIMARY KEY,\n     route_id           TEXT    NOT NULL,\n     position           INTEGER NOT NULL,\n     continuation_hash  TEXT    NOT NULL,\n     action_fingerprint TEXT    NOT NULL,\n     exchange           TEXT    NOT NULL,\n     \"schema\"           TEXT    NOT NULL,\n     step_state         TEXT,\n     state              TEXT    NOT NULL,\n     waiting_for        TEXT    NOT NULL,\n     deferred_at        INTEGER NOT NULL,\n     expires_at         INTEGER,\n     claimed_at         INTEGER,\n     outcome_kind       TEXT,\n     outcome_at         INTEGER,\n     outcome_reason     TEXT,\n     outcome_by         TEXT,\n     continuation       TEXT,\n     call_binding       TEXT,\n     meta               TEXT\n   );\n   CREATE INDEX deferrals_sweep ON deferrals (state, claimed_at, expires_at, id);\n   CREATE INDEX deferrals_pending ON deferrals (state, deferred_at, id);\n   CREATE INDEX deferrals_listing ON deferrals (deferred_at, id);\n   CREATE INDEX deferrals_by_route ON deferrals (route_id, deferred_at, id);\n   CREATE INDEX deferrals_retention ON deferrals (state, outcome_at);\n   CREATE INDEX deferrals_stranded ON deferrals (outcome_kind, deferred_at);`,\n];\n\n/**\n * Durable deferral store on SQLite.\n *\n * One implementation over two drivers: `bun:sqlite` under Bun and\n * `better-sqlite3` under Node. Both are synchronous, which is what makes\n * the compare-and-swap methods genuinely atomic here: a single `UPDATE\n * ... WHERE state = 'waiting' AND claimed_at IS NULL` either changes one row\n * or none, and the driver returns which. See `shared/sqlite/driver.ts` for the runtime-split\n * decision, the version matrix behind it, and the graduation condition for\n * `node:sqlite`.\n *\n * Open it with {@link SqliteDeferralStore.open}; the constructor is\n * private because a store is only usable after its schema has been\n * migrated.\n */\nexport class SqliteDeferralStore implements DeferralStore {\n  readonly #db: SqliteDatabase;\n\n  /** Which driver backs this store. Surfaced for logging and tests. */\n  readonly driver: ResolvedSqliteDriver[\"name\"];\n\n  #closed = false;\n\n  private constructor(\n    db: SqliteDatabase,\n    driver: ResolvedSqliteDriver[\"name\"],\n  ) {\n    this.#db = db;\n    this.driver = driver;\n  }\n\n  /**\n   * Open (creating if absent) the deferral database and bring its schema\n   * up to date.\n   *\n   * @param options.path - Database file path, absolute or relative to the\n   *   working directory. `\":memory:\"` opens a private in-process database,\n   *   which is useful for exercising the sqlite code paths in tests without\n   *   touching disk.\n   * @param options.loaders - Driver loader injection point for tests.\n   * @throws RC5017 under Node when `better-sqlite3` is not installed.\n   */\n  static async open(options: {\n    path: string;\n    loaders?: SqliteDriverLoaders;\n  }): Promise<SqliteDeferralStore> {\n    const driver = await resolveSqliteDriver(SQLITE_CONSUMER, options.loaders);\n    const path = resolveDatabasePath(options.path);\n    if (path !== \":memory:\") mkdirSync(dirname(path), { recursive: true });\n\n    const db = new driver.Database(path);\n    try {\n      initialise(db);\n    } catch (cause) {\n      // The handle exists but no store owns it yet, so nothing else would\n      // ever close it. Release it before the error propagates, otherwise a\n      // context that falls back to memory leaves the file locked.\n      try {\n        db.close();\n      } catch {\n        // Already unusable; the original cause is what matters.\n      }\n      throw cause;\n    }\n    return new SqliteDeferralStore(db, driver.name);\n  }\n\n  async create(record: NewDeferral): Promise<void> {\n    try {\n      this.#db\n        .prepare(\n          `INSERT INTO deferrals (\n             id, route_id, position, continuation_hash, action_fingerprint,\n             exchange, \"schema\", call_binding, meta,\n             step_state, state, waiting_for, deferred_at, expires_at\n           ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n        )\n        .run(\n          record.id,\n          record.routeId,\n          record.position,\n          record.continuationHash,\n          record.actionFingerprint,\n          JSON.stringify(record.exchange),\n          JSON.stringify(record.schema),\n          record.callBinding ?? null,\n          record.meta === undefined\n            ? null\n            : JSON.stringify(encodePersistable(record.meta, \"meta\")),\n          record.stepState === undefined\n            ? null\n            : JSON.stringify(encodePersistable(record.stepState, \"stepState\")),\n          \"waiting\" satisfies DeferralState,\n          record.waitingFor,\n          record.deferredAt.getTime(),\n          record.expiresAt ? record.expiresAt.getTime() : null,\n        );\n    } catch (cause) {\n      // `encodePersistable` runs inside this try, so its RC5042 arrives here\n      // too. Wrapping it as a store failure would replace \"stepState holds a\n      // function\" with \"failed to persist to the sqlite store\", and the\n      // memory backend, which encodes outside any catch, would report the\n      // same input differently. Same passthrough `guard` uses below.\n      if (isRoutecraftError(cause)) throw cause;\n      // Discriminate the one failure the contract names. A duplicate id\n      // means the id derivation is wrong, which no retry fixes, so it must\n      // not reach a `.retry()` wrapper as a retryable error.\n      const duplicate = /UNIQUE constraint failed/i.test(\n        cause instanceof Error ? cause.message : String(cause),\n      );\n      if (isSqliteBusy(cause)) {\n        throw rcError(\"RC5045\", cause, {\n          message: `The deferral store was busy while persisting \"${record.id}\".`,\n        });\n      }\n      throw rcError(\"RC5044\", cause, {\n        message: duplicate\n          ? `Deferral \"${record.id}\" already exists in the store.`\n          : `Failed to persist deferral \"${record.id}\" to the sqlite store.`,\n      });\n    }\n  }\n\n  async get(id: string): Promise<Deferral | undefined> {\n    return guard(`read deferral \"${id}\"`, () => {\n      const row = this.#db\n        .prepare(`SELECT * FROM deferrals WHERE id = ?`)\n        .get(id);\n      return row ? toDeferral(row as DeferralRow) : undefined;\n    });\n  }\n\n  async markResumed(\n    id: string,\n    resumption: DeferralResumption,\n  ): Promise<DeferralCasResult> {\n    return this.#transition(\n      id,\n      `UPDATE deferrals\n          SET state = 'settled', outcome_kind = 'resumed',\n              outcome_at = ?, outcome_by = ?\n        WHERE id = ? AND ${RESUMABLE}`,\n      [\n        resumption.at.getTime(),\n        resumption.by ? JSON.stringify(resumption.by) : null,\n      ],\n    );\n  }\n\n  async claimExpiry(id: string, at: Date): Promise<DeferralCasResult> {\n    return this.#transition(\n      id,\n      `UPDATE deferrals SET claimed_at = ?\n        WHERE id = ? AND ${RESUMABLE}`,\n      [at.getTime()],\n    );\n  }\n\n  async markExpired(id: string): Promise<DeferralCasResult> {\n    return this.#transition(\n      id,\n      `UPDATE deferrals\n          SET state = 'settled', outcome_kind = 'expired', outcome_at = ?\n        WHERE id = ? AND ${CLAIMED}`,\n      [Date.now()],\n    );\n  }\n\n  async markDenied(id: string, reason?: string): Promise<DeferralCasResult> {\n    return this.#transition(\n      id,\n      `UPDATE deferrals\n          SET state = 'settled', outcome_kind = 'denied',\n              outcome_reason = ?, outcome_at = ?\n        WHERE id = ? AND ${CLAIMED}`,\n      [reason ?? null, Date.now()],\n    );\n  }\n\n  async releaseClaims(before: Date): Promise<number> {\n    return guard(\"release stale delivery claims\", () => {\n      this.#db\n        .prepare(\n          `UPDATE deferrals SET claimed_at = NULL\n            WHERE state = 'waiting' AND claimed_at <= ?`,\n        )\n        .run(before.getTime());\n      return (\n        this.#db.prepare(\"SELECT changes() AS changed\").get() as {\n          changed: number;\n        }\n      ).changed;\n    });\n  }\n\n  /**\n   * Unlike the `mark*` transitions this cannot be one conditional `UPDATE`:\n   * the compare is a digest of a JSON column, which SQLite cannot compute.\n   * The read and the write therefore share one `BEGIN IMMEDIATE`, which\n   * takes the write lock at the read, so no other connection can move the\n   * row in between. That is the same guarantee the single-statement form\n   * gives, bought with a lock held for one extra statement.\n   */\n  async replaceStepState(\n    id: string,\n    expected: string,\n    stepState: unknown,\n  ): Promise<DeferralCasResult> {\n    // Outside the transaction on purpose: RC5042 for an unpersistable\n    // replacement is the caller's bug, and reporting it as a store failure\n    // would also leave a lock taken for a write that was never viable.\n    const encoded = encodePersistable(stepState, \"stepState\");\n    let won = false;\n    let row: unknown;\n    try {\n      this.#db.exec(\"BEGIN IMMEDIATE\");\n      const current = this.#db\n        .prepare(\n          `SELECT state, claimed_at, step_state FROM deferrals WHERE id = ?`,\n        )\n        .get(id) as\n        | {\n            state: string;\n            claimed_at: number | null;\n            step_state: string | null;\n          }\n        | undefined\n        | null;\n      if (\n        current != null &&\n        current.state === \"waiting\" &&\n        current.claimed_at === null &&\n        stepStateFingerprint(\n          current.step_state === null\n            ? undefined\n            : (JSON.parse(current.step_state) as unknown),\n        ) === expected\n      ) {\n        this.#db\n          .prepare(\n            `UPDATE deferrals SET step_state = ?\n             WHERE id = ? AND ${RESUMABLE}`,\n          )\n          // `create` guards the same way. `bun:sqlite` binds an undefined\n          // parameter as NULL and `better-sqlite3` rejects it, so the branch\n          // is what keeps the two drivers substitutable.\n          .run(encoded === undefined ? null : JSON.stringify(encoded), id);\n        won =\n          (\n            this.#db.prepare(\"SELECT changes() AS changed\").get() as {\n              changed: number;\n            }\n          ).changed === 1;\n      }\n      row = this.#db.prepare(`SELECT * FROM deferrals WHERE id = ?`).get(id);\n      this.#db.exec(\"COMMIT\");\n    } catch (cause) {\n      try {\n        this.#db.exec(\"ROLLBACK\");\n      } catch {\n        // BEGIN itself failed, so there is no transaction to roll back.\n      }\n      throw rcError(isSqliteBusy(cause) ? \"RC5045\" : \"RC5044\", cause, {\n        message: `Failed to replace the step state of deferral \"${id}\" in the sqlite store.`,\n      });\n    }\n    return {\n      won,\n      deferral: row ? toDeferral(row as DeferralRow) : undefined,\n    };\n  }\n\n  async recordContinuation(\n    id: string,\n    continuation: SerializedOutcome,\n  ): Promise<void> {\n    guard(`record the continuation result of \"${id}\"`, () => {\n      this.#db\n        .prepare(`UPDATE deferrals SET continuation = ? WHERE id = ?`)\n        .run(JSON.stringify(serializeContinuation(continuation)), id);\n    });\n  }\n\n  async findExpired(\n    now: Date,\n    limit: number,\n    after?: ExpiredScanCursor,\n  ): Promise<Deferral[]> {\n    assertSweepLimit(limit);\n    assertScanCursor(after);\n    return guard(\"scan for expired deferrals\", () => {\n      // The expanded `(a > x OR (a = x AND b > y))` form rather than\n      // row-value syntax, which would put a floor on the SQLite version.\n      const rows = after\n        ? this.#db\n            .prepare(\n              `SELECT * FROM deferrals\n                WHERE ${RESUMABLE}\n                  AND expires_at IS NOT NULL\n                  AND expires_at <= ?\n                  AND (expires_at > ? OR (expires_at = ? AND id > ?))\n                ORDER BY expires_at ASC, id ASC\n                LIMIT ?`,\n            )\n            .all(\n              now.getTime(),\n              after.expiresAt.getTime(),\n              after.expiresAt.getTime(),\n              after.id,\n              limit,\n            )\n        : this.#db\n            .prepare(\n              `SELECT * FROM deferrals\n                WHERE ${RESUMABLE}\n                  AND expires_at IS NOT NULL\n                  AND expires_at <= ?\n                ORDER BY expires_at ASC, id ASC\n                LIMIT ?`,\n            )\n            .all(now.getTime(), limit);\n      return rows.map((row) => toDeferral(row as DeferralRow));\n    });\n  }\n\n  async list(query: DeferralListQuery): Promise<DeferralSummary[]> {\n    assertSweepLimit(query.limit);\n    assertListCursor(query.after);\n    return guard(\"list deferrals\", () => {\n      // Only the summary's own columns, so a page never reads a serialized\n      // exchange out of the database to then drop it.\n      const where: string[] = [];\n      const params: Array<string | number> = [];\n      if (query.state !== undefined) {\n        where.push(\"state = ?\");\n        params.push(query.state);\n      }\n      if (query.routeId !== undefined) {\n        where.push(\"route_id = ?\");\n        params.push(query.routeId);\n      }\n      if (query.after !== undefined) {\n        // Expanded rather than row-value syntax, matching findExpired: the\n        // latter puts a floor on the SQLite version.\n        where.push(\"(deferred_at > ? OR (deferred_at = ? AND id > ?))\");\n        params.push(\n          query.after.deferredAt.getTime(),\n          query.after.deferredAt.getTime(),\n          query.after.id,\n        );\n      }\n      const rows = this.#db\n        .prepare(\n          `SELECT id, route_id, state, waiting_for, deferred_at, expires_at,\n                  claimed_at, outcome_kind, outcome_at, outcome_reason, outcome_by\n             FROM deferrals\n             ${where.length > 0 ? `WHERE ${where.join(\" AND \")}` : \"\"}\n             ORDER BY deferred_at ASC, id ASC\n             LIMIT ?`,\n        )\n        .all(...params, query.limit);\n      return rows.map((row) => toSummary(row as DeferralSummaryRow));\n    });\n  }\n\n  async resumedWithoutContinuation(limit?: number): Promise<Deferral[]> {\n    assertSweepLimit(limit);\n    return guard(\"scan for stranded resumes\", () => {\n      const rows = this.#db\n        .prepare(\n          `SELECT * FROM deferrals\n          WHERE outcome_kind = 'resumed'\n            AND continuation IS NULL\n          ORDER BY deferred_at ASC\n          LIMIT ?`,\n        )\n        .all(limit ?? -1);\n      return rows.map((row) => toDeferral(row as DeferralRow));\n    });\n  }\n\n  async pending(): Promise<PendingDeferralSummary> {\n    return guard(\"summarise pending deferrals\", () => {\n      const row = this.#db\n        .prepare(\n          `SELECT COUNT(*) AS count, MIN(deferred_at) AS oldest\n           FROM deferrals WHERE state = 'waiting'`,\n        )\n        .get() as { count: number; oldest: number | null } | undefined;\n      const count = row?.count ?? 0;\n      return {\n        count,\n        ...(row?.oldest != null ? { oldest: new Date(row.oldest) } : {}),\n      };\n    });\n  }\n\n  async purgeSettled(before: Date): Promise<number> {\n    return guard(\"purge settled deferrals\", () => {\n      this.#db\n        .prepare(\n          `DELETE FROM deferrals\n          WHERE state = 'settled'\n            AND outcome_at < ?`,\n        )\n        .run(before.getTime());\n      return (\n        this.#db.prepare(\"SELECT changes() AS changed\").get() as {\n          changed: number;\n        }\n      ).changed;\n    });\n  }\n\n  async close(): Promise<void> {\n    if (this.#closed) return;\n    this.#closed = true;\n    this.#db.close();\n  }\n\n  /**\n   * Run a conditional `UPDATE` that only matches a row in the state the\n   * caller expected, and report whether this caller performed it.\n   *\n   * The update and the read-back run inside one immediate transaction so\n   * the returned record is the state this transition produced, not a state\n   * some later writer moved on to. The {@link RESUMABLE} or {@link CLAIMED}\n   * clause is the compare half of the compare-and-swap; `changes` is the\n   * answer.\n   */\n  #transition(\n    id: string,\n    sql: string,\n    leadingParams: unknown[],\n  ): DeferralCasResult {\n    let won = false;\n    let row: unknown;\n    try {\n      // BEGIN sits inside the try so a busy lock surfaces as the wrapped\n      // store error this method promises, not as a raw driver throw.\n      this.#db.exec(\"BEGIN IMMEDIATE\");\n      this.#db.prepare(sql).run(...leadingParams, id);\n      // Read the affected-row count from SQLite rather than from the\n      // driver's run() return value. `bun:sqlite` only began returning\n      // `{ changes }` partway through the 1.1 line, and the declared floor\n      // is 1.1.0, so trusting it would report every compare-and-swap as\n      // lost on an in-range Bun: the row would transition, every caller\n      // would be told it lost the race, and nothing would ever resume.\n      won =\n        (\n          this.#db.prepare(\"SELECT changes() AS changed\").get() as {\n            changed: number;\n          }\n        ).changed === 1;\n      row = this.#db.prepare(`SELECT * FROM deferrals WHERE id = ?`).get(id);\n      this.#db.exec(\"COMMIT\");\n    } catch (cause) {\n      try {\n        this.#db.exec(\"ROLLBACK\");\n      } catch {\n        // BEGIN itself failed, so there is no transaction to roll back.\n        // The original cause is the one worth reporting.\n      }\n      throw rcError(isSqliteBusy(cause) ? \"RC5045\" : \"RC5044\", cause, {\n        message: `Failed to transition deferral \"${id}\" in the sqlite store.`,\n      });\n    }\n    // Decoding runs after COMMIT and outside the try: a corrupt column\n    // would otherwise throw with no transaction active, and the rollback's\n    // own \"no transaction is active\" error would replace the parse failure.\n    return {\n      won,\n      deferral: row ? toDeferral(row as DeferralRow) : undefined,\n    };\n  }\n}\n\n/**\n * Configure the connection and bring its schema up to date. Split out of\n * `open` so a failure here can be caught while the handle is still in\n * scope and closed.\n *\n * @internal\n */\nfunction initialise(db: SqliteDatabase): void {\n  // WAL lets the sweeper read while a resume writes. Harmless on\n  // `:memory:`, where SQLite ignores the journal mode change.\n  db.exec(\"PRAGMA journal_mode = WAL\");\n  // Set explicitly because the drivers disagree: better-sqlite3 defaults to\n  // 5s, bun:sqlite to 0. Without this, a second writer on the same file (an\n  // operator running the CLI against a live deployment, a restart\n  // overlapping the previous shutdown) fails a resume instantly under Bun\n  // and waits under Node, so the bug would not reproduce for whoever is\n  // debugging on the other runtime.\n  db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);\n  db.exec(\"PRAGMA foreign_keys = ON\");\n  migrate(db);\n}\n\n/**\n * Apply outstanding migrations, mapping a refusal onto the store's own\n * code. The transaction and the version handling are shared with every\n * other sqlite store in the repository.\n *\n * @internal\n */\nfunction migrate(db: SqliteDatabase): void {\n  migrateSqlite(db, {\n    schemaVersion: SCHEMA_VERSION,\n    migrations: MIGRATIONS,\n    applicationId: SQLITE_APPLICATION_IDS.deferral,\n    identityTable: \"deferrals\",\n    onFailure: (failure) => {\n      if (failure.kind === \"foreign\") {\n        return rcError(\"RC5044\", undefined, {\n          message: `This file is not a deferral store; ${describeSqliteFile(failure)}. Point deferral.store.path at its own file: every store keeps one, and they cannot share. A 0.7.0 canary's own database also arrives here when its configured path was carried over unchanged, because the store's identity moved with the rename: delete that file or name a new path, since canary records are not carried into the release.`,\n        });\n      }\n      if (failure.kind === \"downgrade\") {\n        return rcError(\"RC5044\", undefined, {\n          message: `Deferral store schema version ${failure.current} is newer than this build understands (${SCHEMA_VERSION}). Run the newer Routecraft build, or point deferral.store.path at a fresh file.`,\n        });\n      }\n      return rcError(\"RC5044\", failure.cause, {\n        message: \"Failed to migrate the deferral store schema.\",\n      });\n    },\n  });\n}\n\n/**\n * Run a store operation, mapping any driver or decode failure onto the\n * store's own codes. Without this the read paths surfaced raw driver errors\n * and raw `SyntaxError`s from a corrupt column, so a caller could not tell a\n * retryable busy lock from a permanent fault.\n *\n * @internal\n */\nfunction guard<T>(what: string, run: () => T): T {\n  try {\n    return run();\n  } catch (cause) {\n    if (isRoutecraftError(cause)) throw cause;\n    throw rcError(isSqliteBusy(cause) ? \"RC5045\" : \"RC5044\", cause, {\n      message: `Failed to ${what} in the sqlite store.`,\n    });\n  }\n}\n\n/**\n * Row shape as the drivers return it. Both produce plain objects with\n * snake_case column names.\n *\n * @internal\n */\ninterface DeferralRow {\n  id: string;\n  route_id: string;\n  position: number;\n  continuation_hash: string;\n  action_fingerprint: string;\n  exchange: string;\n  schema: string;\n  call_binding: string | null;\n  meta: string | null;\n  step_state: string | null;\n  state: string;\n  waiting_for: string;\n  deferred_at: number;\n  expires_at: number | null;\n  claimed_at: number | null;\n  outcome_kind: string | null;\n  outcome_at: number | null;\n  outcome_reason: string | null;\n  outcome_by: string | null;\n  continuation: string | null;\n}\n\n/**\n * The columns the management listing selects. Derived from\n * {@link DeferralRow} rather than re-typed, so the column-to-type mapping\n * for this table lives once: the query names these so the exchange, the\n * step state and the schema are never read at all.\n */\ntype DeferralSummaryRow = Pick<\n  DeferralRow,\n  | \"id\"\n  | \"route_id\"\n  | \"state\"\n  | \"waiting_for\"\n  | \"deferred_at\"\n  | \"expires_at\"\n  | \"claimed_at\"\n  | \"outcome_kind\"\n  | \"outcome_at\"\n  | \"outcome_reason\"\n  | \"outcome_by\"\n>;\n\n/**\n * Hydrate the outcome half of a row, for the record and the summary alike.\n *\n * Both columns or neither. A row carrying one of them is only reachable by\n * raw SQL, and reading it back as a partial outcome would mean inventing\n * the missing half: a kind for a row that never settled, or a date the\n * retention sweep would then act on. Absent is what it is, and it is what\n * the memory backend produces for the same injection.\n *\n * @internal\n */\nfunction toOutcome(row: DeferralSummaryRow): { outcome?: DeferralOutcome } {\n  if (row.outcome_kind === null || row.outcome_at === null) return {};\n  return {\n    outcome: {\n      kind: row.outcome_kind as DeferralOutcome[\"kind\"],\n      at: new Date(row.outcome_at),\n      ...(row.outcome_reason !== null ? { reason: row.outcome_reason } : {}),\n      ...(row.outcome_by !== null\n        ? { by: JSON.parse(row.outcome_by) as PrincipalRef }\n        : {}),\n    },\n  };\n}\n\n/**\n * Read a summary row.\n *\n * Not `summariseDeferral(toDeferral(row))`: the query deliberately does not\n * select the exchange, the schema or the step state, so there is no full\n * record here to summarise.\n *\n * @internal\n */\nfunction toSummary(row: DeferralSummaryRow): DeferralSummary {\n  return {\n    id: row.id,\n    routeId: row.route_id,\n    state: row.state as DeferralState,\n    waitingFor: row.waiting_for as DeferralWaitingFor,\n    claimed: claimIsOutstanding(\n      row.state as DeferralState,\n      row.claimed_at === null ? null : new Date(row.claimed_at),\n    ),\n    deferredAt: new Date(row.deferred_at),\n    ...(row.expires_at !== null ? { expiresAt: new Date(row.expires_at) } : {}),\n    ...toOutcome(row),\n  };\n}\n\n/** @internal */\nfunction toDeferral(row: DeferralRow): Deferral {\n  const continuation = row.continuation\n    ? (JSON.parse(row.continuation) as SerializedOutcome & { at: string })\n    : undefined;\n  return {\n    id: row.id,\n    routeId: row.route_id,\n    position: row.position,\n    continuationHash: row.continuation_hash,\n    actionFingerprint: row.action_fingerprint,\n    exchange: JSON.parse(row.exchange) as SerializedExchange,\n    schema: JSON.parse(row.schema) as DeferralSchema,\n    ...(row.call_binding !== null ? { callBinding: row.call_binding } : {}),\n    ...(row.meta !== null ? { meta: JSON.parse(row.meta) as unknown } : {}),\n    ...(row.step_state !== null\n      ? { stepState: JSON.parse(row.step_state) as unknown }\n      : {}),\n    state: row.state as DeferralState,\n    waitingFor: row.waiting_for as DeferralWaitingFor,\n    deferredAt: new Date(row.deferred_at),\n    ...(row.expires_at !== null ? { expiresAt: new Date(row.expires_at) } : {}),\n    ...(row.claimed_at != null ? { claimedAt: new Date(row.claimed_at) } : {}),\n    ...toOutcome(row),\n    ...(continuation\n      ? { continuation: { ...continuation, at: new Date(continuation.at) } }\n      : {}),\n  };\n}\n\n/**\n * `Date` does not survive `JSON.stringify` as a `Date`, so the continuation\n * result's timestamp is written as an ISO string and revived in\n * {@link toDeferral}.\n *\n * @internal\n */\nfunction serializeContinuation(continuation: SerializedOutcome): unknown {\n  return {\n    ...continuation,\n    ...(continuation.body !== undefined\n      ? { body: encodePersistable(continuation.body, \"continuation.body\") }\n      : {}),\n    at: continuation.at.toISOString(),\n  };\n}\n","import { resolveDatabasePath } from \"./database.ts\";\n\n/**\n * Which subsystem opened which database file, per context.\n *\n * Every sqlite store versions itself through `PRAGMA user_version`, which\n * is one integer per file. Two stores pointed at one path can therefore\n * never both be satisfied: whichever opens first stamps its own version\n * and the other refuses. The stores discover that separately and late, and\n * the second one only knows that the number it found is not its own.\n *\n * Claiming the path at configuration time turns that into one error at\n * boot naming both settings, which is where a person can act on it.\n *\n * Keyed weakly by the context so a test that builds many contexts does not\n * inherit another's claims, and so nothing here outlives the context.\n */\nconst claims = new WeakMap<object, Map<string, string>>();\n\n/** A path already held by a different subsystem. */\nexport interface SqlitePathConflict {\n  /** The path as configured, before resolution, for the message. */\n  readonly path: string;\n  /** The subsystem that claimed it first, named as its setting. */\n  readonly held: string;\n  /** The subsystem claiming it now. */\n  readonly claimant: string;\n}\n\n/**\n * Record that `claimant` opens the database at `path` in this context, and\n * refuse when another subsystem already opened the same file.\n *\n * `\":memory:\"` is exempt: each in-memory database is private to the\n * connection that opened it, so two stores asking for one never meet.\n *\n * A claimant holds at most one path, because each names one setting and a\n * setting chooses one store. Claiming a second path releases the first: an\n * unconfigured default is resolved and later replaced by the block that\n * configures it, and the path the default gave up must not go on blocking\n * another store that legitimately wants it.\n *\n * @param options.scope - The context the claim belongs to.\n * @param options.path - Database path as configured.\n * @param options.claimant - The setting that chose it, e.g.\n *   `sessions: { store }`, quoted back to the reader in the error.\n * @param options.onConflict - Builds the caller's own error, so each\n *   subsystem keeps its code. The returned error is thrown as it is.\n */\nexport function claimDatabasePath(options: {\n  scope: object;\n  path: string;\n  claimant: string;\n  onConflict: (conflict: SqlitePathConflict) => Error;\n}): void {\n  const { scope, path, claimant, onConflict } = options;\n  let held = claims.get(scope);\n  if (held === undefined) {\n    held = new Map();\n    claims.set(scope, held);\n  }\n  // An in-process database is private to the connection that opened it, so\n  // there is nothing to claim. The claimant has still moved, though, and\n  // whatever it held before must go with it.\n  if (path === \":memory:\") {\n    releaseIn(held, claimant);\n    return;\n  }\n  const resolved = resolveDatabasePath(path);\n  const owner = held.get(resolved);\n  if (owner !== undefined && owner !== claimant) {\n    throw onConflict({ path, held: owner, claimant });\n  }\n  // Released only once the new claim is known to be good, so a refused\n  // claim leaves the claimant holding what it already had.\n  releaseIn(held, claimant, resolved);\n  held.set(resolved, claimant);\n}\n\n/**\n * Give up whatever this claimant holds, for a store that resolved to a\n * backend with no file at all: the memory fallback, or one a caller\n * supplied. Those never reach {@link claimDatabasePath}, so without this\n * the path an earlier default claimed would go on blocking a store that\n * legitimately wants it.\n */\nexport function releaseClaimant(options: {\n  scope: object;\n  claimant: string;\n}): void {\n  const held = claims.get(options.scope);\n  if (held !== undefined) releaseIn(held, options.claimant);\n}\n\n/** Drop every path this claimant holds, except one it is keeping. */\nfunction releaseIn(\n  held: Map<string, string>,\n  claimant: string,\n  keep?: string,\n): void {\n  for (const [path, by] of held) {\n    if (by === claimant && path !== keep) held.delete(path);\n  }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { CraftContext } from \"../context.ts\";\nimport { validateAgainst } from \"../pipeline/validation.ts\";\nimport { rcError } from \"../error.ts\";\nimport {\n  type Exchange,\n  DefaultExchange,\n  HeadersKeys,\n  setExchangeRoute,\n  setResumeStepState,\n} from \"../exchange.ts\";\nimport type { Route } from \"../route.ts\";\nimport type { Adapter, Step } from \"../types.ts\";\nimport { continuationTailHash, describeSchema } from \"./hash.ts\";\nimport {\n  type ResumeAuthorizer,\n  checkCallBinding,\n  deferredPrincipal,\n  recordView,\n  runAuthorizer,\n} from \"./authorize.ts\";\nimport { DeferralHeaders } from \"./exchange-state.ts\";\nimport { DEFERRAL_RUNTIME } from \"./runtime-key.ts\";\nimport {\n  decodePersistable,\n  deserializeExchange,\n  encodePersistable,\n} from \"./serialize.ts\";\nimport type { DeferSite } from \"./sites.ts\";\nimport type { Principal } from \"../auth/types.ts\";\nimport { resumable } from \"./types.ts\";\nimport type {\n  PrincipalRef,\n  SerializedOutcome,\n  Deferral,\n  DeferralCasResult,\n  DeferralStore,\n} from \"./types.ts\";\n\n/**\n * What `.resume()`'s mapping function produces: which deferral to revive,\n * and the payload to revive it with.\n *\n * The split is the boundary between the two halves of a resume. The mapping\n * function owns SHAPE (find the token in a mail reply, lift an approval out\n * of a chat webhook), because only the ingress route knows what its\n * transport looks like. Revival owns VALIDATION, because only the\n * deferral knows the schema the deferring step declared.\n */\nexport interface ResumeRequest {\n  /** The signed token minted when the exchange deferred. */\n  token: string;\n  /** The submitted payload, validated against the deferring step's `schema`. */\n  result: unknown;\n  /**\n   * Who resumed it. Defaults to the ingress exchange's own principal, which\n   * is the value worth recording: it was verified live on the route that\n   * accepted the submission, unlike anything read back out of the store.\n   * Set it explicitly only when the resuming principal is not the caller\n   * (an ops tool resuming on someone's behalf).\n   */\n  resumedBy?: PrincipalRef;\n}\n\n/**\n * What the resume DOOR contributes, as opposed to what its mapper produced.\n *\n * Kept separate from {@link ResumeRequest} deliberately. The mapper is user\n * code shaping a transport payload, and a payload is exactly what an\n * attacker controls; letting it name the resuming principal or supply the\n * hook would let the untrusted half of an ingress choose what the trusted\n * half checks.\n *\n * @internal\n */\nexport interface ResumeDoor {\n  /** The door's own authorization policy, when it declares one. */\n  readonly authorize?: ResumeAuthorizer;\n  /** The principal this ingress route verified live, if any. */\n  readonly principal?: Principal;\n  /** The ingress step's abort signal, which is what bounds an async hook. */\n  readonly signal?: AbortSignal;\n}\n\n/**\n * What `.resume()` puts in the ingress route's body once revival settles.\n *\n * The ingress route continues after this, which is what lets it reply on\n * the caller's own channel (\"thanks, the payout is on its way\"). It therefore\n * reports how execution two ended rather than just that the token was\n * accepted.\n */\nexport interface ResumeAcknowledgment {\n  /**\n   * `\"resumed\"` when this call revived the exchange; `\"duplicate\"` when the\n   * deferral had already been resumed and this is the cached result of that\n   * first revival. A duplicate re-runs nothing.\n   */\n  readonly status: \"resumed\" | \"duplicate\";\n  readonly deferralId: string;\n  /** Route the revived exchange belongs to. Not the ingress route. */\n  readonly routeId: string;\n  /**\n   * How execution two ended.\n   *\n   * Named for the run rather than called an outcome, because\n   * {@link Deferral.outcome} is how the DEFERRAL ended (resumed, expired,\n   * denied) and the two would otherwise share a word while meaning\n   * different things on adjacent types.\n   */\n  readonly continuation: SerializedOutcome;\n}\n\n/**\n * Revive a deferred exchange and run its continuation to completion.\n *\n * The order of checks is the security contract, and it is ordered rather\n * than merely \"pre-claim\" because the window before the claim is NOT inert:\n * the deadline arm and the continuation arm each take a compare-and-swap\n * that settles the record and drives the deferred route's error channel,\n * which in practice sends the approver a message. A credential that has no\n * business here must be refused before it can reach either, or the wrong\n * holder can burn the rightful principal's claim and drive an outbound\n * notification with it.\n *\n * 1. The token verifies (`RC5041`) and the deferral exists (`RC5046`).\n * 2. The credential was minted for THIS call (`RC5055`), read from the\n *    record alone.\n * 3. The route's own `authorize` hook accepts the principal (`RC5056`), if\n *    it declared one. This is where an application's policy runs; the\n *    framework has none of its own.\n * 4. Only now the lifecycle: a duplicate gets the cached continuation result\n *    rather than a second execution, an expired record `RC5047`, a denied\n *    one `RC5050`. Steps 2 and 3 sit above this deliberately, so a refused\n *    caller learns nothing about the record's state.\n * 5. Its route is still registered and still leads to the same continuation\n *    (`RC5048`), so an approval cannot authorize steps that were edited\n *    under it. The hash is COMPARED non-destructively; only a mismatch\n *    reached by a caller steps 2 and 3 already accepted may settle it.\n * 6. The payload satisfies the deferring step's `schema` (`RC5049`, in\n *    the ingress route only), and the compare-and-swap out of `deferred`\n *    is won here and not by a concurrent resume or the expiry sweeper.\n *\n * Every failure throws in the ingress route. A failure that leaves the\n * approver STRANDED (an expiry, a changed continuation, a denied\n * deferral) additionally re-enters the deferred route's error channel,\n * because only that route can notify and re-ask. A rejected payload\n * (`RC5049`) deliberately does not: it is a per-request input error rather\n * than a change in the world, the deferral stays resumable, and routing\n * it through the deferred route would let any token holder drive that\n * route's re-ask path with junk. The two authorization refusals are the\n * same: they leave the record exactly as they found it.\n *\n * @param context - The context reviving the exchange (the ingress route's)\n * @param request - Token plus submitted payload, as the mapper produced them\n * @param door - What the ingress route itself declares and verified\n * @returns The acknowledgment for the ingress route's body\n *\n * @internal\n */\nexport async function reviveDeferral(\n  context: CraftContext,\n  request: ResumeRequest,\n  door: ResumeDoor = {},\n): Promise<ResumeAcknowledgment> {\n  const runtime = context.getStore(DEFERRAL_RUNTIME);\n  if (!runtime) {\n    throw rcError(\"RC5052\", undefined, {\n      message:\n        \"Cannot resume: this context has no deferral runtime, so no token it was handed can be verified. Add deferral: {} to defineConfig.\",\n    });\n  }\n\n  const { id, sub } = runtime.signer.verify(request.token);\n  const deferral = await runtime.store.get(id);\n  if (!deferral) {\n    throw rcError(\"RC5046\", undefined, {\n      message: `No deferral is stored under id \"${id}\".`,\n    });\n  }\n\n  // Record and credential only: no route lookup, no transition, no\n  // disclosure. Placed above the settled return deliberately, so a holder\n  // whose credential does not belong here cannot use the response to learn\n  // the record's lifecycle state.\n  checkCallBinding(deferral, sub);\n\n  // The application's own policy, and the last thing that runs before the\n  // record's lifecycle becomes observable. It reads the record and the two\n  // principals; it cannot transition anything, and a refusal leaves the\n  // record exactly as it was found.\n  if (door.authorize) {\n    await runAuthorizer(\n      door.authorize,\n      {\n        principal: door.principal,\n        deferred: deferredPrincipal(deferral),\n        payload: request.result,\n        record: recordView(deferral),\n      },\n      context.logger,\n      door.signal,\n    );\n  }\n\n  if (!resumable(deferral)) {\n    return unresumable(deferral);\n  }\n\n  const route = context.getRouteById(deferral.routeId);\n  if (!route) {\n    throw rcError(\"RC5046\", undefined, {\n      message: `Deferral \"${id}\" belongs to route \"${deferral.routeId}\", which is not registered in this context. Resume must run in a context that has the deferred route.`,\n    });\n  }\n\n  // Checked here as well as by the sweeper: a resume can arrive between the\n  // deadline and the sweep that marks it, and resuming into a window the\n  // route already declared closed is exactly what `ttl` rules out. Reached\n  // after the hook has settled on purpose, so a hook that overran the\n  // deadline reports RC5047 rather than reviving into a closed window.\n  //\n  // The transition is what makes the re-ask exactly-once. Without the\n  // compare-and-swap, every replay of one dead token would emit the event\n  // again, run the deferred route's error channel again, and typically\n  // send the approver another notification: an outbound-message amplifier\n  // driven by a party the token does not authenticate. Winning the CAS is\n  // the right to notify, and the sweeper competes for the same right.\n  const deadline = deferral.expiresAt;\n  if (deadline !== undefined && deadline.getTime() <= Date.now()) {\n    const { cas, error } = await expireDeferral(context, runtime.store, route, {\n      ...deferral,\n      expiresAt: deadline,\n    });\n    if (!cas.won) {\n      // The winner is not necessarily the sweeper. A concurrent resume can\n      // win `markResumed` right on the deadline, and that resume WAS\n      // accepted: reporting an expiry to this caller would be a false\n      // negative about work that is running. Whoever won says what\n      // happened.\n      if (cas.deferral) return unresumable(cas.deferral);\n    }\n    throw error;\n  }\n\n  const site = findSite(route, deferral);\n  if (!site) {\n    return await refuseContinuation(\n      context,\n      runtime.store,\n      route,\n      deferral,\n      \"defer site removed\",\n      `Route \"${deferral.routeId}\" no longer has a .defer() at position ${deferral.position}.`,\n    );\n  }\n\n  // For a static site: the descriptor of the LIVE schema, never the stored\n  // one. The stored descriptor is what was folded into\n  // `deferral.continuationHash` at deferral time, so comparing it against\n  // itself is inert and a widened schema would resume into a contract its\n  // approver never saw. The deferring step's own definition is excluded\n  // from the hashed tail by design, which makes this descriptor the ONLY\n  // representation of that step in the digest.\n  //\n  // For a re-entrant site the stored descriptor is all there is: the live\n  // schema was raised inside the step's own code and cannot be read back\n  // off the route, so the schema arm IS inert there. The step itself heads\n  // the hashed tail instead, so its definition is covered; the schema is\n  // the same residue class as the behaviour of what the tail calls.\n  //\n  // `meta` is deliberately NOT in the digest. It lives only on the record,\n  // so there is no live copy for it to drift from: a defer site that snapshots\n  // its policy into `meta` gets policy-travels-with-the-deferral by\n  // construction rather than by a tamper check.\n  //\n  // The branch keys on RE-ENTRANCY, not on whether a live schema was found.\n  // A static site always describes what it declares TODAY, absence included:\n  // keying on `site.schema` would make a removed schema fall through to the\n  // stored descriptor, compare it against itself, and accept the deferred\n  // payload unvalidated with no re-ask, which is the exact edit the absent\n  // sentinel exists to catch.\n  const current = continuationTailHash(\n    site.site.continuation,\n    site.site.reentrant ? deferral.schema : describeSchema(site.schema),\n  );\n  if (current !== deferral.continuationHash) {\n    // Reached only by a caller the credential binding and the door's hook\n    // both accepted. `refuseContinuation` denies the record and drives the\n    // approver notification, so a refused holder must never get here: they\n    // would burn the rightful principal's claim and send the message\n    // themselves.\n    return await refuseContinuation(\n      context,\n      runtime.store,\n      route,\n      deferral,\n      \"continuation changed\",\n      `Route \"${deferral.routeId}\" changed after position ${deferral.position} while this exchange was deferred, so the stored payload no longer authorizes what would run.`,\n    );\n  }\n\n  // Validation runs against the LIVE schema read off the route: a Standard\n  // Schema is an object with a validate function and cannot be persisted.\n  // Reaching here means the hash check above already confirmed that live\n  // schema is the one the approval was taken against.\n  //\n  // A re-entrant site has no live schema to read back (it was raised inside\n  // the step's own code), so the check is skipped THERE AND ONLY THERE: the\n  // raw payload is handed to the re-entering step as its deferred call's\n  // result, and the step is the validator. A token holder can therefore\n  // resume a re-entrant deferral with any JSON; the consuming step (the\n  // agent tier's model loop is the shipped case) must treat it as untrusted\n  // input, which a tool result already is.\n  let payload: unknown = request.result;\n  if (site.schema) {\n    const result = await validateAgainst(site.schema, request.result);\n    if (!result.ok) {\n      // Ingress only, deliberately: unlike an expiry or a changed\n      // continuation, a malformed payload is not a change in the world the\n      // deferred route has to react to. It is a per-request input error, and\n      // re-entering the deferred route's error channel for it would hand any\n      // token holder a lever to drive that route's re-ask path (approver\n      // notifications included) with junk. The deferral is left resumable,\n      // so the caller simply corrects the payload; shaping a reply to a bad\n      // payload is the ingress route's own `.error()` handler's job.\n      throw rcError(\"RC5049\", result.message, {\n        message: `The payload for deferral \"${id}\" does not satisfy its declared schema: ${result.message}`,\n      });\n    }\n    payload = result.value;\n  }\n\n  const resumedAt = new Date();\n  const cas = await runtime.store.markResumed(id, {\n    at: resumedAt,\n    ...(request.resumedBy ? { by: request.resumedBy } : {}),\n  });\n  if (!cas.won) {\n    // Lost the race. Whoever won says what happened: a concurrent resume\n    // yields its cached result, the sweeper an expiry, a cancellation a\n    // denial. Reading the post-attempt record avoids a second store read.\n    if (!cas.deferral) {\n      throw rcError(\"RC5046\", undefined, {\n        message: `Deferral \"${id}\" disappeared while it was being resumed.`,\n      });\n    }\n    return unresumable(cas.deferral);\n  }\n\n  // The deadline is re-checked AFTER winning the transition. The check\n  // above ran before validating the payload, and validation is a user\n  // schema: it can await. Without this, a payload that arrived in time but\n  // validated slowly would run the continuation past the window its route\n  // declared, which is the one thing `ttl` promises it will not do.\n  if (\n    deferral.expiresAt !== undefined &&\n    deferral.expiresAt.getTime() <= Date.now()\n  ) {\n    const expiry = rcError(\"RC5047\", undefined, {\n      message: `Deferral \"${id}\" expired at ${deferral.expiresAt.toISOString()} while its payload was being validated.`,\n    });\n    // Winning `markResumed` means the sweeper cannot also report this, so\n    // the notification is ours to send exactly once.\n    await runtime.store.recordContinuation(id, {\n      status: \"failed\",\n      error: { rc: \"RC5047\", message: expiry.message },\n      at: resumedAt,\n    });\n    context.emit(\"route:exchange:expired\", {\n      routeId: deferral.routeId,\n      exchangeId: exchangeIdOf(deferral),\n      correlationId: correlationIdOf(deferral),\n      deferralId: id,\n      expiresAt: deferral.expiresAt,\n    });\n    throw await reask(context, route, deferral, expiry);\n  }\n\n  // Everything from here is under one catch, because this resume has won\n  // `markResumed` and nothing else will ever settle the record. A throw\n  // between the transition and `recordContinuation` (a stored exchange the\n  // deserializer refuses, a `route:exchange:resumed` subscriber that fails)\n  // would otherwise leave the deferral resumed with no continuation result\n  // forever, and every later resume would be told the first resume has not\n  // recorded one yet. Recording the failure keeps a replay idempotent, which\n  // is the contract a claimed deferral owes.\n  let continuation: SerializedOutcome;\n  try {\n    const exchange = rehydrate(context, route, deferral, {\n      result: payload,\n      resumedAt,\n      ...(request.resumedBy ? { resumedBy: request.resumedBy } : {}),\n    });\n    // The step-owned closure state goes back to the step that deferred it,\n    // through internals rather than headers: it is runtime context for one\n    // re-entrant execution on this process, never exchange state, and must\n    // not be re-serialized into a second deferral.\n    if (site.site.reentrant && deferral.stepState !== undefined) {\n      setResumeStepState(exchange, decodePersistable(deferral.stepState));\n    }\n\n    context.emit(\"route:exchange:resumed\", {\n      routeId: deferral.routeId,\n      exchangeId: exchange.id,\n      correlationId: exchange.headers[HeadersKeys.CORRELATION_ID] as string,\n      deferralId: id,\n      position: deferral.position,\n      ...(request.resumedBy ? { resumedBy: request.resumedBy } : {}),\n    });\n\n    continuation = await runContinuation(\n      route,\n      exchange,\n      site.site.continuation,\n      resumedAt,\n    );\n  } catch (error) {\n    // Best-effort, and the ordering is the point: the original error must\n    // reach the ingress route whatever the store does. A throw from\n    // `recordContinuation` here would mask it AND leave the record unsettled,\n    // reproducing one level up the condition this block exists to remove.\n    // `rc` is carried like the expiry path carries RC5047, so a duplicate\n    // resume and an operator dashboard see the code rather than prose.\n    const failure = error as { rc?: string; message?: string } | undefined;\n    try {\n      await runtime.store.recordContinuation(id, {\n        status: \"failed\",\n        error: {\n          ...(typeof failure?.rc === \"string\" ? { rc: failure.rc } : {}),\n          message: failure?.message ?? \"the revival failed\",\n        },\n        at: resumedAt,\n      });\n    } catch (unrecorded) {\n      route.logger.error(\n        { deferralId: id, err: unrecorded },\n        \"Could not record the continuation result of a failed revival. The deferral stays resumed with no result and needs an operator.\",\n      );\n    }\n    throw error;\n  }\n  try {\n    await runtime.store.recordContinuation(id, continuation);\n  } catch (err) {\n    // The work is DONE: destinations fired and the result below is true.\n    // Throwing here would tell the caller the work failed after it\n    // succeeded, and the boot scan would later count the record as a\n    // half-run continuation. A missing cached result only costs a\n    // duplicate resume its cached reply.\n    route.logger.error(\n      { deferralId: id, err },\n      \"Could not cache the continuation result of a completed revival. The work finished; a duplicate resume will be told the result is unrecorded.\",\n    );\n  }\n\n  return {\n    status: \"resumed\",\n    deferralId: id,\n    routeId: deferral.routeId,\n    continuation,\n  };\n}\n\n/**\n * Refuse a resume whose continuation no longer matches, exactly once.\n *\n * The transition is what bounds the notification. A continuation mismatch\n * is permanent for that record (the live hash is recomputed on every\n * attempt and will not match again), so without a latch every replay of a\n * still-valid token would re-drive the deferred route's error channel,\n * approver notifications included, for as long as the token lives. That is\n * the amplifier the expiry path is hardened against and the one the\n * RC5049 narrowing removed; this path had neither guard.\n *\n * `denied` is the honest state: the deferral can no longer be honoured,\n * and the route has been told to re-ask rather than to wait. The cost is\n * that rolling the deploy back no longer rescues this exchange, which is\n * consistent with how the design treats a changed continuation (re-ask\n * with a fresh deferral) rather than a new limitation.\n *\n * @internal\n */\nasync function refuseContinuation(\n  context: CraftContext,\n  store: DeferralStore,\n  route: Route,\n  deferral: Deferral,\n  reason: string,\n  message: string,\n): Promise<ResumeAcknowledgment> {\n  const error = rcError(\"RC5048\", undefined, { message });\n  // Same claim-deliver-finalize shape as expiry, for the same crash: a\n  // denial finalized before its re-ask was delivered would strand the\n  // approver at a dead link with no signal.\n  const cas = await store.claimExpiry(deferral.id, new Date());\n  if (!cas.won) {\n    // Whoever won the transition says what happened, as on the expiry and\n    // duplicate paths. A replay that lost to the denial has to read back the\n    // stored denial reason rather than this request's RC5048, and a resume\n    // that won `markResumed` on the way in was accepted: reporting a changed\n    // continuation for it would describe work that is running as refused.\n    if (cas.deferral) return unresumable(cas.deferral);\n    throw error;\n  }\n  await reask(context, route, deferral, error);\n  const finalized = await store.markDenied(deferral.id, reason);\n  if (!finalized.won) {\n    // The claim was released before the denial landed, which puts the record\n    // back to deferred with a hash that can never match again. Every replay\n    // of a still-valid token now re-wins this path and re-drives the re-ask,\n    // which is the outbound amplifier the latch exists to remove.\n    context.logger.warn(\n      { deferralId: deferral.id, routeId: deferral.routeId, reason },\n      \"A continuation refusal was released before its denial finalized, so the record is resumable again and a replay will re-drive the re-ask\",\n    );\n  }\n  throw error;\n}\n\n/**\n * Read an identity header straight off the stored exchange.\n *\n * Event payloads carry the DEFERRED exchange's identity, not the ingress\n * route's, because the events describe the deferred exchange's lifecycle:\n * a consumer correlating `:deferred` with `:resumed` has to see the same\n * ids on both. Rehydrating a whole exchange just to read two headers would\n * be wasteful, and would fail for a record the deserializer refuses, on a\n * path whose whole job is to report a failure.\n *\n * @internal\n */\nfunction headerOf(deferral: Deferral, key: string): string {\n  const value = deferral.exchange.headers[key];\n  return typeof value === \"string\" ? value : deferral.id;\n}\n\n/** @internal */\nfunction exchangeIdOf(deferral: Deferral): string {\n  return headerOf(deferral, HeadersKeys.ID);\n}\n\n/** @internal */\nfunction correlationIdOf(deferral: Deferral): string {\n  return headerOf(deferral, HeadersKeys.CORRELATION_ID);\n}\n\n/**\n * Reply to a resume that arrived at a deferral nothing can resume any more:\n * one that has settled, or one a delivery claim is outstanding on.\n *\n * A duplicate resume is the normal case here (an approver double-clicks, a\n * webhook is redelivered), and it must not re-run the continuation: the\n * cached continuation result is exactly what the first resume produced. The\n * other cases are failures the caller has to see.\n *\n * @internal\n */\nfunction unresumable(deferral: Deferral): ResumeAcknowledgment {\n  if (deferral.outcome?.kind === \"resumed\") {\n    return {\n      status: \"duplicate\",\n      deferralId: deferral.id,\n      routeId: deferral.routeId,\n      // A resumed deferral whose continuation result is missing means\n      // execution two is still running (or the process died mid-run). Report\n      // it as such rather than inventing a completion.\n      continuation: deferral.continuation ?? {\n        status: \"failed\",\n        error: {\n          message:\n            \"The first resume of this deferral has not recorded a continuation result yet.\",\n        },\n        at: deferral.outcome.at,\n      },\n    };\n  }\n\n  // No re-ask here, deliberately. The record is ALREADY settled or claimed,\n  // so whoever moved it there (the sweeper, a cancellation, an earlier\n  // resume that lost no race) owns the notification. Re-entering the\n  // route's error channel per arriving replay would notify the approver\n  // once per request rather than once per event, from a token anyone who\n  // saw the original link still holds.\n  //\n  // An outstanding claim is disambiguated by WHEN it was taken, not by the\n  // clock now: an expiry claim is only ever taken once the deadline has\n  // passed, and a denial claim only while it has not, so the claim\n  // timestamp against the deadline says which flow owns the record. The\n  // current time would flip a denial claim into an \"expiry\" merely because\n  // its slow re-ask crossed the deadline while running.\n  const claimRef = deferral.claimedAt ?? new Date();\n  const expiryClaim =\n    deferral.expiresAt !== undefined &&\n    claimRef.getTime() >= deferral.expiresAt.getTime();\n  throw deferral.outcome?.kind === \"expired\" ||\n    (deferral.outcome === undefined && expiryClaim)\n    ? rcError(\"RC5047\", undefined, {\n        message: `Deferral \"${deferral.id}\" expired before a resume arrived.`,\n      })\n    : rcError(\"RC5050\", undefined, {\n        message: `Deferral \"${deferral.id}\" was denied${deferral.outcome?.reason ? `: ${deferral.outcome.reason}` : \"\"}.`,\n      });\n}\n\n/** A deferral the store gave a deadline, which is the only kind that expires. */\nexport type ExpiringDeferral = Deferral & { expiresAt: Date };\n\n/**\n * Retire an overdue deferral and tell its route, exactly once.\n *\n * Shared by the two things that can discover an expiry: a late resume\n * arriving at `.resume()`, and the sweeper. Both must reach the same\n * outcome, and only one of them may notify, which is what the\n * compare-and-swap decides. The loser gets the post-attempt record back\n * and reports what the winner did rather than its own view, so a resume\n * that won `markResumed` on the deadline is reported as resumed, not\n * expired.\n *\n * Returns rather than throws: the sweeper has no caller to reply to, so an\n * expiry is not exceptional to it. The caller decides whether the error is\n * a return value or a throw.\n *\n * @internal\n */\nexport async function expireDeferral(\n  context: CraftContext,\n  store: DeferralStore,\n  route: Route,\n  deferral: ExpiringDeferral,\n): Promise<{ cas: DeferralCasResult; error: Error }> {\n  const deadline = deferral.expiresAt;\n  const error = rcError(\"RC5047\", undefined, {\n    message: `Deferral \"${deferral.id}\" expired at ${deadline.toISOString()}.`,\n  });\n  // Claim, deliver, finalize. The claim is what makes a crash mid-delivery\n  // healable: a claim left outstanding is released once its lease elapses\n  // and the next sweep redelivers it, where a record\n  // settled before delivery would be terminal with its approver never\n  // told. The cost is that a crash AFTER delivery but before finalize\n  // redelivers once; notification is at-least-once by design.\n  const cas = await store.claimExpiry(deferral.id, new Date());\n  if (!cas.won) return { cas, error };\n\n  context.emit(\"route:exchange:expired\", {\n    routeId: deferral.routeId,\n    exchangeId: exchangeIdOf(deferral),\n    correlationId: correlationIdOf(deferral),\n    deferralId: deferral.id,\n    expiresAt: deadline,\n  });\n  await reask(context, route, deferral, error);\n  const finalized = await store.markExpired(deferral.id);\n  if (!finalized.won) {\n    // Single-node, so the only way to lose a finalize is a lease release\n    // racing an extremely slow delivery. The next sweep pass redelivers,\n    // which is the at-least-once trade already made above.\n    context.logger.warn(\n      { deferralId: deferral.id },\n      \"An expiry claim was released before its delivery finalized, so the next sweep will redeliver it.\",\n    );\n  }\n  return { cas, error };\n}\n\n/**\n * Re-enter the deferred route's error channel with a revival failure, then\n * hand the error back so the ingress route sees it too.\n *\n * Both halves matter. The ingress caller gets a typed error because it\n * made a request and deserves a reply. The deferred route gets the same\n * error through its own `.error()` handler because it is the only place\n * that can do something useful about it: notify, escalate, or re-ask with a\n * fresh deferral. Without that, a late resume strands its sender at a\n * dead link.\n *\n * The rehydrated exchange is what the handler receives, so it sees the\n * payload the approval was about. Its principal comes back marked restored\n * (see `auth/restored.ts`), so an `authorize()` in a re-ask path refuses it\n * rather than trusting a shape read off disk.\n *\n * @internal\n */\nasync function reask(\n  context: CraftContext,\n  route: Route,\n  deferral: Deferral,\n  error: Error,\n): Promise<Error> {\n  try {\n    await route.enterErrorChannel(\n      rehydrate(context, route, deferral),\n      error,\n      \"resume\",\n    );\n  } catch (channelError) {\n    // The re-ask path is best effort by construction: the caller is already\n    // being handed `error`, and replacing it with whatever the route's own\n    // error handler did would hide the actual revival failure.\n    context.logger.error(\n      {\n        err: channelError,\n        routeId: deferral.routeId,\n        deferralId: deferral.id,\n      },\n      \"Deferred route's error channel failed while handling a revival failure\",\n    );\n  }\n  return error;\n}\n\n/**\n * Rebuild the deferred exchange on this process, with the payload in place.\n *\n * The resume state goes on headers rather than being handed to the steps\n * some other way, because it has to survive a SECOND defer of the same\n * exchange, and headers are the exchange's state (see\n * `.standards/exchange-state-model.md`). It is stored LIVE (a `Date` in the\n * payload stays a `Date`); the serialization rules apply to it at the next\n * deferral, the same as to every other header.\n *\n * @internal\n */\nfunction rehydrate(\n  context: CraftContext,\n  route: Route,\n  deferral: Deferral,\n  resumption?: {\n    result: unknown;\n    resumedAt: Date;\n    resumedBy?: PrincipalRef;\n  },\n): Exchange {\n  const base = deserializeExchange(context, deferral.exchange);\n  const exchange = DefaultExchange.rewrap(base, {\n    headers: {\n      ...base.headers,\n      [HeadersKeys.ROUTE_ID]: deferral.routeId,\n      ...(resumption\n        ? {\n            [DeferralHeaders.RESULT]: resumption.result,\n            [DeferralHeaders.RESUMED_AT]: resumption.resumedAt,\n            ...(resumption.resumedBy\n              ? { [DeferralHeaders.RESUMED_BY]: resumption.resumedBy }\n              : {}),\n          }\n        : {}),\n    },\n  });\n  setExchangeRoute(exchange, route);\n  return exchange;\n}\n\n/**\n * Run the continuation and reduce it to the outcome the store caches.\n *\n * @internal\n */\nasync function runContinuation(\n  route: Route,\n  exchange: Exchange,\n  continuation: ReadonlyArray<Step<Adapter>>,\n  at: Date,\n): Promise<SerializedOutcome> {\n  const result = await route.runContinuation(exchange, continuation);\n  if (result.deferred) {\n    // The continuation reached another `.defer()`. Recording a body here\n    // would cache the SECOND deferral's acknowledgment, token included,\n    // and hand it back to whoever resumed the first one: in a two-stage\n    // approval that is approver A receiving approver B's capability.\n    return { status: \"deferred\", at };\n  }\n  if (result.dropped) {\n    return { status: \"dropped\", reason: \"dropped by the route\", at };\n  }\n  if (result.failed) {\n    const error = result.error as\n      | { rc?: string; meta?: { message?: string }; message?: string }\n      | undefined;\n    return {\n      status: \"failed\",\n      error: {\n        ...(typeof error?.rc === \"string\" ? { rc: error.rc } : {}),\n        message:\n          error?.meta?.message ?? error?.message ?? \"the continuation failed\",\n      },\n      at,\n    };\n  }\n  // Only the terminal BODY is cached, and only if it is storable. A route\n  // whose output is not JSON data still resumes correctly; a duplicate\n  // resume then learns that it completed without being handed a body it\n  // could not have round-tripped anyway.\n  let body: unknown;\n  try {\n    body = encodePersistable(result.exchange.body, \"terminal body\");\n  } catch {\n    body = undefined;\n  }\n  return {\n    status: \"completed\",\n    ...(body !== undefined ? { body } : {}),\n    at,\n  };\n}\n\n/**\n * Find the deferring step and its site by the address on the record.\n *\n * A static `.defer()` site can be read back off the route, so its live\n * schema comes back here when it declared one, gating payload validation\n * (`RC5049`). A re-entrant site carries none, because the schema was raised\n * inside the step's own code and cannot be read back, so its payload skips\n * validation and its hash comparison uses the stored descriptor. The step\n * itself heads the hashed tail there instead.\n *\n * @internal\n */\nfunction findSite(\n  route: Route,\n  deferral: Deferral,\n):\n  | { step: Step<Adapter>; site: DeferSite; schema?: StandardSchemaV1 }\n  | undefined {\n  for (const step of route.definition.deferSteps ?? []) {\n    if (step.site?.position === deferral.position) {\n      return {\n        step,\n        site: step.site,\n        ...(step.schema !== undefined ? { schema: step.schema } : {}),\n      };\n    }\n  }\n  for (const host of route.definition.reentrantDeferSteps ?? []) {\n    if (host.deferSite?.position === deferral.position) {\n      return { step: host, site: host.deferSite };\n    }\n  }\n  return undefined;\n}\n","import type { CraftContext } from \"../context.ts\";\nimport type { Principal } from \"../auth/types.ts\";\nimport { markRestored } from \"../auth/restored.ts\";\nimport { HeadersKeys } from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { decodePersistable } from \"./serialize.ts\";\nimport type { Deferral } from \"./types.ts\";\n\n/**\n * The record, as the resume route's `authorize` hook sees it.\n *\n * Deliberately no access to the deferred body. The hook runs BEFORE the\n * resuming principal has been authorized and before the record's own\n * lifecycle is disclosed, so a body-reading hook would put the deferred\n * payload in front of exactly the party the check exists to reject.\n */\nexport interface DeferralRecordView {\n  /** Deferral identity, the same value the acknowledgment carried. */\n  readonly id: string;\n  /**\n   * Whatever the deferring step attached at deferral.\n   *\n   * The framework never reads it: this is where the deferral carries the\n   * application's own policy inputs. A defer site that snapshots its policy\n   * here gets \"policy travels with the deferral\" for free, because the record\n   * is what the hook reads and editing the site cannot reach it.\n   *\n   * On the agent surface a tool handler supplies it, which means the MODEL\n   * influenced it, and the model has read whatever untrusted tool output is\n   * in its thread. Treat it as what the defer site chose, not as a fact the\n   * framework vouches for.\n   */\n  readonly meta?: unknown;\n  /** Route the deferred exchange belongs to. Not the resume ingress route. */\n  readonly routeId: string;\n  readonly deferredAt: Date;\n  readonly expiresAt?: Date;\n}\n\n/**\n * What a `.resume({ authorize })` hook is handed.\n *\n * The two principals are not the same kind of thing, and the types say so.\n * `principal` was verified live by this ingress route's own\n * `.authenticate()`. `deferred` came back out of the store, so it is marked\n * restored (`auth/restored.ts`) and `authorize()` refuses it anywhere it is\n * offered as a credential; here it is reference data, which is what makes a\n * \"not the requester\" comparison expressible at all.\n */\nexport interface ResumeAuthorizerInput {\n  /** Who is resuming, verified live by this route. Anonymous when it verified nobody. */\n  readonly principal: Principal | undefined;\n  /** Who deferred the exchange, restored from storage. Never a credential. */\n  readonly deferred: Principal | undefined;\n  /**\n   * The submission, exactly as it arrived.\n   *\n   * Raw at hook time: `schema` validation runs only once the hook has\n   * passed, so a hook that refuses a submission spends nothing and a\n   * malformed one never reaches the validator. A hook that reads into this\n   * is reading unvalidated input and should narrow it itself.\n   */\n  readonly payload: unknown;\n  readonly record: DeferralRecordView;\n}\n\n/**\n * Decides whether this principal may resume this deferral.\n *\n * The framework has no opinion about what makes a resuming principal\n * legitimate: it guarantees that the decision happens before the single-use\n * claim is spent and that a \"no\" costs the rightful principal nothing. What\n * \"no\" means is this function's business.\n *\n * Returning false, throwing, and failing to settle before the route stops\n * or its `.timeout()` fires are one refusal on the wire; the log\n * distinguishes them.\n */\nexport type ResumeAuthorizer = (\n  input: ResumeAuthorizerInput,\n) => boolean | Promise<boolean>;\n\n/**\n * Read the deferred principal back off a stored record.\n *\n * Marked restored on the way out, so the one object in the resume path that\n * came from storage rather than from a live verification cannot be mistaken\n * for a credential by anything downstream, the hook included.\n *\n * @internal\n */\nexport function deferredPrincipal(deferral: Deferral): Principal | undefined {\n  const stored = deferral.exchange.headers[HeadersKeys.AUTH_PRINCIPAL];\n  if (stored === undefined || typeof stored !== \"object\" || stored === null) {\n    return undefined;\n  }\n  return markRestored(decodePersistable(stored) as Principal);\n}\n\n/**\n * The resume credential names the call it belongs to.\n *\n * A batch of parallel tool calls mints one credential per call against a\n * single record, because only one of them will win the deferral and the losers'\n * recipients must not be able to resume the winner's deferral. The record\n * records which call it belongs to and the credential carries the same\n * value as its `sub` claim, so the pairing is checked here.\n *\n * Both mismatched arms fail closed on purpose. A credential with no claim\n * presented against a per-call record is a credential minted before the\n * binding existed; a claim-carrying credential presented against a record\n * with no binding is a claim nothing checked. Passing either would make the\n * binding advisory, and an advisory binding is not one.\n *\n * @throws RC5055 when the credential does not name this record's call\n *\n * @internal\n */\nexport function checkCallBinding(\n  deferral: Deferral,\n  claimed: string | undefined,\n): void {\n  if (deferral.callBinding === claimed) return;\n  throw rcError(\"RC5055\", undefined, {\n    message: `The resume credential presented for deferral \"${deferral.id}\" was not minted for the call this record is deferred on.`,\n  });\n}\n\n/**\n * Build the record view handed to the hook.\n *\n * @internal\n */\nexport function recordView(deferral: Deferral): DeferralRecordView {\n  return {\n    id: deferral.id,\n    ...(deferral.meta !== undefined ? { meta: deferral.meta } : {}),\n    routeId: deferral.routeId,\n    deferredAt: deferral.deferredAt,\n    ...(deferral.expiresAt !== undefined\n      ? { expiresAt: deferral.expiresAt }\n      : {}),\n  };\n}\n\n/**\n * Run the resume route's `authorize` hook.\n *\n * Bounded by the ingress route's own abort signal rather than by a framework\n * knob: the hook is ordinary code on a running route, so its bound is the\n * route's stop signal, widened by an enclosing `.timeout()` where the route\n * declares one. Stop has to be in there: without it a resume route with no\n * `.timeout()` could never interrupt a hook that never settles, and an\n * unsettled hook holds the step, which holds `drain()`. What the framework\n * owns is that such a hook can never fall through to the claim.\n *\n * Three refusals, one wire message. False is a decision, a throw is a hook\n * that broke, and an abort is a hook that never settled; the log\n * distinguishes them for the operator and the caller sees the same RC5056\n * for all three, because a hook whose failures are distinguishable from\n * outside is an oracle for what it knows.\n *\n * @throws RC5056 on false, on a thrown cause, and on an abort\n *\n * @internal\n */\nexport async function runAuthorizer(\n  authorize: ResumeAuthorizer,\n  input: ResumeAuthorizerInput,\n  logger: CraftContext[\"logger\"],\n  signal?: AbortSignal,\n): Promise<void> {\n  const refused = (outcome: string, err?: unknown): Error => {\n    logger.warn(\n      {\n        deferralId: input.record.id,\n        routeId: input.record.routeId,\n        principal: input.principal?.subject,\n        outcome,\n        ...(err !== undefined ? { err } : {}),\n      },\n      \"A .resume({ authorize }) hook refused a resume\",\n    );\n    return rcError(\"RC5056\", undefined, {\n      message: `The resume route's authorize hook refused this principal for deferral \"${input.record.id}\".`,\n    });\n  };\n\n  let onAbort: (() => void) | undefined;\n  try {\n    const verdict = await Promise.race([\n      (async () => authorize(input))(),\n      new Promise<never>((_, reject) => {\n        if (!signal) return;\n        if (signal.aborted) {\n          reject(ABORTED);\n          return;\n        }\n        onAbort = () => {\n          reject(ABORTED);\n        };\n        signal.addEventListener(\"abort\", onAbort, { once: true });\n      }),\n    ]);\n    if (verdict !== true) throw refused(\"returned false\");\n  } catch (err) {\n    if (err === ABORTED)\n      throw refused(\"did not settle before the route aborted\");\n    // A refusal this function already built and logged. Re-logging it as a\n    // hook that threw would double-count it and misname it.\n    if (isRefusal(err)) throw err;\n    throw refused(\"threw\", err);\n  } finally {\n    if (onAbort && signal) signal.removeEventListener(\"abort\", onAbort);\n  }\n}\n\n/** Sentinel for the abort arm, so it is distinguishable from a thrown cause. */\nconst ABORTED = Symbol(\"routecraft.deferral.authorize.aborted\");\n\nfunction isRefusal(err: unknown): boolean {\n  return (\n    typeof err === \"object\" &&\n    err !== null &&\n    (err as { rc?: unknown }).rc === \"RC5056\"\n  );\n}\n","import type { CraftContext } from \"../context.ts\";\nimport { expireDeferral } from \"./revive.ts\";\nimport type { ExpiredScanCursor, DeferralStore } from \"./types.ts\";\n\n/** How often the sweeper looks for overdue deferrals, when unconfigured. */\nexport const DEFAULT_SWEEP_INTERVAL = \"60s\";\n\n/**\n * How long a delivery claim is honoured before it is released for\n * redelivery.\n *\n * Deliberately generous relative to handler work: a lease shorter than a\n * slow error handler would make one healthy process double-deliver by\n * itself. The lease only matters after a crash, so its length costs nothing\n * in the healthy case.\n */\nexport const DEFAULT_EXPIRY_LEASE = \"60m\";\n\n/**\n * How long settled deferrals are kept before the sweeper purges them,\n * when unconfigured. `\"never\"` opts out for audit deployments.\n */\nexport const DEFAULT_DEFERRAL_RETENTION = \"90d\";\n\n/**\n * How long a deferral stays resumable when `.defer()` names no `ttl`.\n *\n * Three days. Long enough to survive a weekend, so an approver who is away\n * on Friday still has a live link on Monday, and short enough that an\n * unresumed deferral does not sit in the store forever. Configurable per\n * context, and overridable per defer.\n */\nexport const DEFAULT_DEFERRAL_TTL = \"72h\";\n\n/**\n * Deferrals retired per `findExpired` call.\n *\n * The scan pages rather than loading the overdue set in one query, because\n * the backlog after a long outage is unbounded and each retirement runs a\n * route's error handler. Paging keeps memory flat and lets the startup scan\n * report progress instead of appearing hung.\n */\nconst SWEEP_BATCH = 100;\n\n/**\n * Stranded resumes fetched for the boot summary.\n *\n * Bounded because this is a report, not a work queue: past a certain point\n * the count is the signal and the ids stop being individually actionable.\n */\nconst STRANDED_REPORT = 100;\n\n/**\n * Distinct absent routes named per orphan warning. Same bounding logic as\n * {@link STRANDED_REPORT}: past this the count is the signal.\n */\nconst MISSING_ROUTE_REPORT = 20;\n\n/** How often a sweep pass also purges settled records past retention. */\nconst PURGE_CADENCE_MS = 60 * 60 * 1000;\n\n/**\n * Drives expiry for one context.\n *\n * Expiry has to be pushed rather than pulled. A `ttl` exists so a route can\n * react when nobody resumes it, and by definition nobody is going to present a\n * token for a deferral that timed out, so without something firing on a\n * schedule the \"escalate after 72 hours\" flow never runs at all.\n *\n * The sweeper never decides an outcome by itself: it competes for the same\n * compare-and-swap a late resume competes for, so a deferral resumed at\n * the instant it expires has exactly one winner, and only that winner\n * notifies.\n *\n * @internal\n */\nexport interface SweeperOptions {\n  readonly intervalMs: number;\n  readonly leaseMs: number;\n  /** Absent when the context opted out with `retention: \"never\"`. */\n  readonly retentionMs?: number;\n}\n\nexport class DeferralSweeper {\n  private timer: ReturnType<typeof setInterval> | undefined;\n  /** The sweep currently running. See {@link DeferralSweeper.stop}. */\n  private inFlight: Promise<unknown> | undefined;\n  /**\n   * Set the moment shutdown begins, which is earlier than teardown: routes\n   * are aborted and drained before plugins are torn down, so a tick landing\n   * in that window would retire into a route that can no longer notify.\n   */\n  private stopping = false;\n  private offStopping: (() => void) | undefined;\n  /** Epoch ms of the last retention purge; zero forces one on the boot scan. */\n  private lastPurgeAt = 0;\n\n  constructor(\n    private readonly context: CraftContext,\n    private readonly store: DeferralStore,\n    private readonly options: SweeperOptions,\n  ) {\n    // Subscribed at construction, not in start(): the boot scan runs before\n    // the interval is armed, and a shutdown arriving during that scan must\n    // stop it from claiming records whose routes are already draining.\n    this.offStopping = this.context.on(\"context:stopping\", () => {\n      void this.stop();\n    });\n  }\n\n  /**\n   * Retire every deferral already overdue at `now`.\n   *\n   * Returns how many this pass retired, which is what makes the startup\n   * scan able to say whether a restart had work waiting for it.\n   */\n  async sweep(now: Date = new Date()): Promise<number> {\n    // Heal before scanning: a claim whose holder died mid-delivery is\n    // released once its lease elapses, and the released records are past\n    // their deadline, so this same pass redelivers them.\n    const released = await this.store.releaseClaims(\n      new Date(now.getTime() - this.options.leaseMs),\n    );\n    if (released > 0) {\n      this.context.logger.info(\n        { released },\n        \"Released stale delivery claims for redelivery; a process died while delivering them.\",\n      );\n    }\n\n    await this.purgeOnCadence(now);\n\n    let retired = 0;\n    let visited = 0;\n    const missing = new Map<string, number>();\n    // Keyset pages: the cursor advances strictly past every record visited,\n    // retired or not, so an arbitrarily long unretirable prefix can never\n    // starve the records behind it. `now` is frozen at pass start, which is\n    // what bounds a pass while records keep coming due.\n    let cursor: ExpiredScanCursor | undefined;\n    for (;;) {\n      if (this.stopping) break;\n      const due = await this.store.findExpired(now, SWEEP_BATCH, cursor);\n      if (due.length === 0) break;\n\n      for (const deferral of due) {\n        // Between retirements, not only between pages: shutdown can begin\n        // mid-batch, and a claim taken after that point notifies nobody.\n        if (this.stopping) break;\n        const deadline = deferral.expiresAt;\n        if (deadline === undefined) {\n          // Contractually unreachable: findExpired only returns records with\n          // a deadline. A backend that violates that cannot advance the\n          // cursor, so the pass aborts rather than re-reading the same page.\n          this.context.logger.error(\n            { deferralId: deferral.id },\n            \"findExpired returned a deferral without a deadline; aborting this sweep pass.\",\n          );\n          return retired;\n        }\n        cursor = { expiresAt: deadline, id: deferral.id };\n        visited++;\n        const route = this.context.getRouteById(deferral.routeId);\n        if (!route) {\n          // The store outlives any one deployment, so it can hold work for\n          // a route this process does not have. Retiring it here would\n          // consume the record with nobody able to run its error channel,\n          // so it is left for the deployment that owns it. Counted rather\n          // than logged per record: an orphaned route means one problem,\n          // not one problem per deferred exchange.\n          missing.set(\n            deferral.routeId,\n            (missing.get(deferral.routeId) ?? 0) + 1,\n          );\n          continue;\n        }\n        try {\n          const { cas } = await expireDeferral(\n            this.context,\n            this.store,\n            route,\n            { ...deferral, expiresAt: deadline },\n          );\n          if (cas.won) retired++;\n        } catch (err) {\n          // One route's error handler throwing must not strand the rest of\n          // the batch: the sweep is the only thing that will ever visit\n          // them.\n          this.context.logger.error(\n            { err, deferralId: deferral.id, routeId: deferral.routeId },\n            \"Failed to retire an expired deferral; continuing the sweep.\",\n          );\n        }\n      }\n\n      if (due.length < SWEEP_BATCH) break;\n      this.context.logger.info({ retired }, \"Still retiring expired deferrals\");\n    }\n\n    this.reportMissingRoutes(missing);\n    if (visited > 0 && retired === 0 && !this.stopping) {\n      this.context.logger.warn(\n        { visited },\n        \"Overdue deferrals were visited but none could be retired this pass. Each stays deferred and is revisited next sweep; the route warnings above say why.\",\n      );\n    }\n    return retired;\n  }\n\n  /**\n   * Purge settled records past retention, at most once per\n   * {@link PURGE_CADENCE_MS} and once on the boot scan. The store deletes\n   * in one statement; there is nothing to page or notify.\n   */\n  private async purgeOnCadence(now: Date): Promise<void> {\n    const retentionMs = this.options.retentionMs;\n    if (retentionMs === undefined) return;\n    if (now.getTime() - this.lastPurgeAt < PURGE_CADENCE_MS) return;\n    this.lastPurgeAt = now.getTime();\n    try {\n      const purged = await this.store.purgeSettled(\n        new Date(now.getTime() - retentionMs),\n      );\n      if (purged > 0) {\n        this.context.logger.info(\n          { purged },\n          \"Purged settled deferrals past retention.\",\n        );\n      }\n    } catch (err) {\n      this.context.logger.error(\n        { err },\n        \"Failed to purge settled deferrals; the next cadence will retry.\",\n      );\n    }\n  }\n\n  /** One bounded warning per absent route, never one per record. */\n  private reportMissingRoutes(missing: Map<string, number>): void {\n    let reported = 0;\n    let overflowRoutes = 0;\n    let overflowRecords = 0;\n    for (const [routeId, count] of missing) {\n      if (reported >= MISSING_ROUTE_REPORT) {\n        overflowRoutes++;\n        overflowRecords += count;\n        continue;\n      }\n      reported++;\n      this.context.logger.warn(\n        { routeId, count },\n        `${count} expired deferral(s) belong to route \"${routeId}\", which this context does not have, so they were left for a context that does. Either that route was renamed or removed while deferrals for it were still deferred, or two deployments are sharing one deferral store and should not be.`,\n      );\n    }\n    if (overflowRoutes > 0) {\n      this.context.logger.warn(\n        { routes: overflowRoutes, records: overflowRecords },\n        \"Further absent routes hold expired deferrals this context left alone.\",\n      );\n    }\n  }\n\n  /**\n   * Sweep what expired while the process was down, and report what is\n   * deferred.\n   *\n   * Awaited by `start()` on purpose, so a context is not ready until its\n   * overdue work has reached the routes that own it. An operator restarting\n   * after an outage gets the escalations before the new traffic, which is\n   * the order they would have arrived in had the process stayed up.\n   */\n  async scanOnStart(): Promise<void> {\n    // Held in the same slot the interval uses, so a shutdown arriving during\n    // the scan waits for it rather than closing the store underneath it.\n    this.inFlight = this.runStartScan().finally(() => {\n      this.inFlight = undefined;\n    });\n    await this.inFlight;\n  }\n\n  /**\n   * Throws on a store failure, deliberately: the boot scan is awaited by the\n   * plugin's start() hook, and a store that cannot answer at boot is the\n   * loud-degradation case the deferral config already fails on.\n   *\n   * @internal\n   */\n  private async runStartScan(): Promise<void> {\n    const retired = await this.sweep();\n    const summary = await this.store.pending();\n    const stranded =\n      await this.store.resumedWithoutContinuation(STRANDED_REPORT);\n\n    this.context.logger.info(\n      {\n        retiredOnStart: retired,\n        pending: summary.count,\n        ...(summary.oldest !== undefined\n          ? { oldestDeferredAt: summary.oldest.toISOString() }\n          : {}),\n        stranded: stranded.length,\n        ...(stranded[0] !== undefined\n          ? { oldestStrandedAt: stranded[0].deferredAt.toISOString() }\n          : {}),\n      },\n      // `pending` counts every record the store holds, which includes the\n      // records other tiers keep in it (agent session transcripts) and not\n      // only deferred exchanges; the store cannot tell them apart.\n      \"Deferral store scanned (pending counts every stored record, deferred exchanges and agent session records alike)\",\n    );\n\n    if (stranded.length > 0) {\n      // Reported, never re-driven. Each of these spent its approval and may\n      // have half applied its side effects, so an operator decides what\n      // happens to it. Ids at debug because the count is what an alert\n      // watches and the ids are what an investigation needs.\n      this.context.logger.warn(\n        { stranded: stranded.length },\n        \"Deferrals were resumed but never recorded an outcome, so a process died mid-continuation. Their approvals are spent and nothing will retry them; each needs an operator.\",\n      );\n      this.context.logger.debug(\n        { deferralIds: stranded.map((record) => record.id) },\n        \"Stranded deferral ids\",\n      );\n    }\n  }\n\n  /** Begin the periodic sweep. Idempotent. */\n  start(): void {\n    if (this.timer) return;\n    this.timer = setInterval(() => {\n      if (this.inFlight) return;\n      this.inFlight = this.sweep()\n        .catch((err: unknown) => {\n          this.context.logger.error(\n            { err },\n            \"Deferral sweep failed; the next tick will retry.\",\n          );\n        })\n        .finally(() => {\n          this.inFlight = undefined;\n        });\n    }, this.options.intervalMs);\n    // A sweep must never be the reason a process stays alive: it exists to\n    // serve routes, and a context whose routes have all finished should\n    // exit.\n    this.timer.unref?.();\n  }\n\n  /**\n   * Stop the periodic sweep and wait for the one in flight. Idempotent.\n   *\n   * Awaiting matters more than clearing the interval: the caller closes the\n   * store next, and a sweep still running would meet a closed handle. Worse,\n   * a retirement that already won its transition would re-enter a route that\n   * has drained, leaving the record `expired` with its approver never told\n   * and nothing left to revisit it.\n   */\n  async stop(): Promise<void> {\n    this.stopping = true;\n    this.offStopping?.();\n    this.offStopping = undefined;\n    if (this.timer) {\n      clearInterval(this.timer);\n      this.timer = undefined;\n    }\n    try {\n      await this.inFlight;\n    } catch {\n      // The boot scan's failure already reached whoever awaited scanOnStart();\n      // re-raising it from every stop() caller would turn one startup error\n      // into an unhandled rejection in the stopping listener and a second\n      // failure in teardown.\n    }\n  }\n}\n","/**\n * CORS for browser-facing http surfaces on a named server.\n *\n * Owned by core so every surface that needs a browser to read its responses\n * (the MCP HTTP transport is the first consumer) shares one policy engine and\n * one header math, instead of each protocol mount growing a slightly\n * different copy.\n *\n * The default is **loopback-only**: a request whose `Origin` is on `localhost`,\n * `127.0.0.1`, or `::1` (any port, http or https) gets reflected; everything\n * else gets no `Access-Control-Allow-Origin` header back and is blocked by the\n * browser. Protocol mounts separately require an explicit `browserOrigins`\n * opt-in before processing any request carrying Origin, including loopback.\n * CORS configuration never grants browser admission. See `.standards/security.md` ->\n * \"Security defaults policy\" for the broader principle.\n *\n * Server-to-server callers (curl, the craft CLI, `mcp-remote`) are unaffected\n * by CORS because they do not send an `Origin` header.\n *\n * The public option surface is intentionally minimal: only `origin` is\n * configurable. Method, header, expose-header, credentials, and preflight-cache\n * values are framework-controlled constants -- chosen to satisfy the RFC 9728\n * discovery contract and the MCP JSON-RPC handshake -- and can be expanded\n * later if a real use case demands it.\n */\n\n/**\n * Resolver form of `origin`. Receives the request's `Origin` header (or\n * `undefined` when absent) and returns either the value to echo in\n * `Access-Control-Allow-Origin`, or `false` to disallow.\n *\n * Implementations SHOULD NOT throw. A thrown error is caught at the request\n * boundary and treated as `false` (fail-closed), but emitting an exception\n * also clears CORS for that request silently. Return `false` explicitly to\n * disallow.\n *\n * Keeping this transport-agnostic (no `IncomingMessage`) lets the helper run\n * on Bun, Node, and in tests without coupling to `node:http`.\n */\nexport type HttpCorsOriginResolver = (\n  requestOrigin: string | undefined,\n) => string | false;\n\n/**\n * CORS configuration for a browser-facing http surface. The MCP transport\n * passes it via `mcpPlugin({ cors: { origin: ... } })`.\n *\n * Omitting the config entirely applies the loopback-only default. Consumers\n * accept `false` in their own option slot to disable CORS handling completely\n * (useful when a reverse proxy or CDN owns CORS).\n */\nexport interface HttpCorsOptions {\n  /**\n   * Allowed origin(s).\n   *\n   * - `\"*\"` -- permissive, no `Vary: Origin` emitted.\n   * - `string` -- exact match against the request `Origin`; non-match returns no allow header.\n   * - `string[]` -- allowlist; if the request `Origin` matches one entry, it is reflected.\n   * - {@link HttpCorsOriginResolver} -- custom resolver, returns the value to echo or `false` to disallow.\n   */\n  origin: \"*\" | string | string[] | HttpCorsOriginResolver;\n}\n\n/**\n * Internal resolved CORS shape. The consumer never has to branch on string vs\n * array vs function form of `origin`. Not exported beyond this file.\n *\n * @internal\n */\ninterface ResolvedHttpCors {\n  resolveOrigin: HttpCorsOriginResolver;\n  /** `true` when `origin` was the literal `\"*\"`. Skips `Vary: Origin`. */\n  isWildcard: boolean;\n}\n\n/**\n * Framework-controlled CORS constants. Not user-configurable; chosen to\n * satisfy the RFC 9728 discovery contract and the MCP JSON-RPC handshake.\n *\n * - `Access-Control-Allow-Methods`: the verbs the consuming transports accept.\n * - `Access-Control-Allow-Headers`: `Authorization, *`. The wildcard admits\n *   whatever headers MCP clients add without gating them, but the Fetch spec\n *   excludes `Authorization` from it, so a bearer token has to be named.\n *   Firefox already warns on a preflight that relies on the wildcard for it.\n * - `Access-Control-Expose-Headers` (non-preflight only): the response headers\n *   browser clients must be able to read. Only `WWW-Authenticate` (the\n *   RFC 9728 `resource_metadata` hint on a 401) qualifies: MCP protocol\n *   revision 2026-07-28 removed both `Mcp-Session-Id` (no protocol-level\n *   sessions) and SSE resumability (`Last-Event-ID`), and the stateless\n *   serving of 2025-era traffic mints neither, so nothing else is ever\n *   emitted to read.\n *\n * @internal\n */\nconst ALLOW_METHODS = \"GET, POST, OPTIONS\";\nconst ALLOW_HEADERS = \"Authorization, *\";\nconst EXPOSE_HEADERS = \"WWW-Authenticate\";\n\n/**\n * Hostnames recognised as loopback by the default policy.\n *\n * IPv6: both Node and Bun's `URL.hostname` return the bracketed form\n * `\"[::1]\"` for `http://[::1]:8080`, not `\"::1\"`. The unbracketed `\"::1\"`\n * entry is kept as defence-in-depth in case a future URL parser surfaces it\n * (the WHATWG URL spec is unsettled on this; older parsers and some\n * synthesised inputs may produce the unbracketed form).\n */\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"::1\", \"[::1]\"]);\n\n/**\n * Default origin resolver: reflect the request `Origin` iff it is loopback\n * AND in canonical form per RFC 6454 §7.1 (`scheme://host[:port]`, no path,\n * no userinfo, no query, no fragment). Returns `false` otherwise.\n *\n * Real browsers never emit anything other than a canonical Origin, so this\n * tightening costs nothing in practice while ensuring we never echo a\n * malformed value into `Access-Control-Allow-Origin`.\n */\nexport function defaultLoopbackOriginResolver(\n  requestOrigin: string | undefined,\n): string | false {\n  if (!requestOrigin) return false;\n  if (requestOrigin === \"null\") return false;\n  let parsed: URL;\n  try {\n    parsed = new URL(requestOrigin);\n  } catch {\n    return false;\n  }\n  if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n  if (parsed.username || parsed.password) return false;\n  if (parsed.pathname !== \"/\" && parsed.pathname !== \"\") return false;\n  if (parsed.search || parsed.hash) return false;\n  return LOOPBACK_HOSTS.has(parsed.hostname) ? requestOrigin : false;\n}\n\n/**\n * Resolve a `cors` config slot into either a fully-populated internal shape or\n * `null` (CORS disabled entirely). `undefined` produces the loopback default.\n */\nexport function resolveCorsOptions(\n  input: false | HttpCorsOptions | undefined,\n): ResolvedHttpCors | null {\n  if (input === false) return null;\n  if (input === undefined) {\n    return {\n      resolveOrigin: defaultLoopbackOriginResolver,\n      isWildcard: false,\n    };\n  }\n\n  const { origin } = input;\n  if (origin === \"*\") {\n    return { resolveOrigin: () => \"*\", isWildcard: true };\n  }\n  if (typeof origin === \"string\") {\n    const allowed = origin;\n    return {\n      resolveOrigin: (requestOrigin) =>\n        requestOrigin === allowed ? allowed : false,\n      isWildcard: false,\n    };\n  }\n  if (Array.isArray(origin)) {\n    const allowed = new Set(origin);\n    return {\n      resolveOrigin: (requestOrigin) =>\n        requestOrigin !== undefined && allowed.has(requestOrigin)\n          ? requestOrigin\n          : false,\n      isWildcard: false,\n    };\n  }\n  if (typeof origin === \"function\") {\n    return { resolveOrigin: origin, isWildcard: false };\n  }\n  throw new TypeError(\n    \"cors.origin must be '*', a string, a string array, or a function\",\n  );\n}\n\n/**\n * Run the resolver in a try/catch so a misbehaving custom origin function\n * fails closed rather than crashing the in-flight request.\n */\nfunction safeResolveOrigin(\n  cors: ResolvedHttpCors,\n  requestOrigin: string | undefined,\n): string | false {\n  try {\n    return cors.resolveOrigin(requestOrigin);\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Build the response headers to add for a given request `Origin`.\n *\n * Returns an empty object when CORS is disabled (`cors === null`).\n *\n * When the policy is origin-dependent (non-wildcard), `Vary: Origin` is\n * **always** included -- including for rejected origins -- so a shared cache\n * keyed by the response cannot serve a no-CORS response back to a loopback\n * origin. Disallowed origins receive `{ Vary: \"Origin\" }` only, with no\n * `Access-Control-Allow-Origin`.\n *\n * The caller is responsible for applying these headers: spread the record\n * into the response headers, appending `Vary` when a prior value exists.\n *\n * @param cors Resolved CORS options, or `null` to short-circuit.\n * @param requestOrigin Value of the request's `Origin` header.\n * @param preflight `true` to include `Access-Control-Allow-Methods/Headers`.\n */\nexport function buildCorsHeaders(\n  cors: ResolvedHttpCors | null,\n  requestOrigin: string | undefined,\n  preflight: boolean,\n): Record<string, string> {\n  if (!cors) return {};\n\n  const headers: Record<string, string> = {};\n  if (!cors.isWildcard) {\n    headers[\"Vary\"] = \"Origin\";\n  }\n\n  const allowed = safeResolveOrigin(cors, requestOrigin);\n  if (allowed === false) return headers;\n\n  headers[\"Access-Control-Allow-Origin\"] = allowed;\n  // Allow-Methods/Allow-Headers belong on preflight (204) only;\n  // Expose-Headers belongs on the actual response only (browsers ignore it\n  // on a preflight per the Fetch spec). Mirror that asymmetry here.\n  if (preflight) {\n    headers[\"Access-Control-Allow-Methods\"] = ALLOW_METHODS;\n    headers[\"Access-Control-Allow-Headers\"] = ALLOW_HEADERS;\n    // Chrome Private Network Access: when a non-loopback Origin reaches a\n    // loopback/private target (e.g. a hosted browser MCP client tunneled\n    // to a local MCP server during integration testing), Chrome blocks the\n    // preflight unless the server opts in via this header. The header is\n    // ignored by other browsers and by Chrome when the cross-network\n    // condition does not apply, so emitting it unconditionally on preflight\n    // -- gated on the origin already being allowlisted by the policy --\n    // is safe and avoids threading the request headers through the helper.\n    // Spec: https://wicg.github.io/private-network-access/\n    headers[\"Access-Control-Allow-Private-Network\"] = \"true\";\n  } else {\n    headers[\"Access-Control-Expose-Headers\"] = EXPOSE_HEADERS;\n  }\n  return headers;\n}\n","/**\n * Public types for the ops plugin's health surface.\n *\n * The status vocabulary and the report shape are the external contract an\n * uptime monitor and an orchestrator match against, so both are add-only:\n * fields may be added, never removed or repurposed.\n */\n\nimport type { Duration } from \"../../shared/duration.ts\";\nimport type { HttpAuth } from \"../../adapters/http/types\";\nimport type { Deferred } from \"../../deferral/deferred\";\nimport type {\n  DeferralOutcome,\n  DeferralState,\n  DeferralWaitingFor,\n} from \"../../deferral/types.ts\";\n\n/**\n * The four-member health vocabulary.\n *\n * - `up`: serving normally.\n * - `degraded`: serving with reduced capability. A circuit breaker is holding\n *   calls off, or the route was deliberately taken offline. Never pages.\n * - `down`: cannot serve at all. For a route this means its source gave up\n *   producing; nothing it exists to serve is being served.\n * - `inactive`: deliberately out of the picture. A finished one-shot route, a\n *   route stopped cleanly, or an indicator muted for maintenance. Excluded\n *   from aggregation entirely.\n *\n * New signals map into these rather than extending them; their richer state\n * belongs in the per-component `details` map.\n */\nexport type HealthStatus = \"up\" | \"degraded\" | \"down\" | \"inactive\";\n\n/**\n * How widely a failure is felt, which decides whether readiness may carry it.\n *\n * - `instance`: this process or replica specifically. Peers may be fine, so\n *   taking this instance out of the load balancer's pool can genuinely help.\n * - `deployment`: every replica alike. Derotating one sends traffic to a peer\n *   that fails identically, so readiness must ignore it and only the\n *   operational signal may carry it.\n */\nexport type FailureDomain = \"instance\" | \"deployment\";\n\n/**\n * Which components a report covers.\n *\n * - `readiness`: instance-domain components only, because the only thing\n *   acting on this view does is move traffic between replicas, which helps\n *   only when the peers are in a better position.\n * - `all`: every component, whatever its domain. The operational view, read by\n *   humans and monitors, which never influences routing.\n */\nexport type HealthView = \"readiness\" | \"all\";\n\n/**\n * Where the app is in its own serving life, independent of whether any\n * dependency is healthy. This is the substance of readiness: during a deploy\n * a new container must not receive traffic until its routes are subscribed,\n * and during shutdown it must stop receiving before the process exits.\n */\nexport type ContextState = \"starting\" | \"started\" | \"stopping\" | \"stopped\";\n\n/**\n * Where a route is in its life, independent of whether that is healthy.\n *\n * Routecraft routes are not all long-running: a one-shot source runs, does its\n * work, and closes. Without this distinction such a route would either look\n * permanently `up` (a lie) or trip readiness when it finished (a false page).\n *\n * - `running`: started, still live.\n * - `completed`: stopped after doing work successfully. A finished one-shot.\n * - `stopped`: stopped cleanly without ever succeeding (shutdown, or a source\n *   that had nothing to do).\n * - `offline`: taken out of service by an operator. Reports `degraded`,\n *   never pages.\n * - `disabled`: held back by its own `.enabled()` predicate, with the reason\n *   in `details.reason`. Reports `inactive`, so it is listed and excluded\n *   from aggregation: a capability whose credentials were never supplied is\n *   a configuration state the operator chose, and paging on it would make\n *   every deliberately-dormant route an incident. Distinct from `offline`,\n *   which is a running deployment having capability taken away from it, and\n *   from `failed`, which is a route that should be running and is not.\n * - `failed`: not running when it should be. Its source gave up producing.\n */\nexport type RouteLifecycle =\n  \"running\" | \"completed\" | \"stopped\" | \"offline\" | \"disabled\" | \"failed\";\n\n/** A circuit breaker's position, mirroring routecraft's breaker events. */\nexport type CircuitState = \"open\" | \"half-open\";\n\n/**\n * A component's status transition, as carried by `plugin:ops:health:changed`.\n *\n * Emitted as a component changes rather than derived by re-reading the whole\n * report, so an operator alerts on the transition instead of polling for it.\n */\nexport interface HealthChange {\n  component: \"context\" | \"route\" | \"indicator\";\n  /** The component's name; the reserved id `context` for the serving lifecycle. */\n  name: string;\n  from: HealthStatus;\n  to: HealthStatus;\n}\n\n/**\n * A value allowed in a component's `details` map.\n *\n * Structural facts only: enums, numbers, booleans. Never an error message.\n * Health answers whether a component can serve; what went wrong and why is\n * carried by logs and telemetry, which are not readable by everyone who can\n * reach this endpoint.\n */\nexport type HealthDetailValue = string | number | boolean;\n\n/** Component-owned diagnostic context. Structural facts only. */\nexport type HealthDetails = Record<string, HealthDetailValue>;\n\n/** What a component reports. */\nexport interface Health {\n  status: HealthStatus;\n  details?: HealthDetails;\n}\n\n/** A component as it appears in a report. */\nexport interface HealthComponent extends Health {\n  /**\n   * How widely this component's failure is felt. Only `instance` components\n   * appear in the readiness view.\n   */\n  domain: FailureDomain;\n  /** Milliseconds since this component last reported. Indicators only. */\n  ageMs?: number;\n}\n\n/**\n * A report body. This shape is the external contract, so it is add-only:\n * fields may be added, never removed or repurposed.\n *\n * There is deliberately no separate `ready` flag. It would be exactly\n * `status !== \"down\"` on whichever view produced the report, and a derivable\n * field named `ready` on the operational aggregate invites the one mistake\n * this design exists to prevent: routing traffic on the deployment-wide\n * signal. Read `status`, and read it from `/health/ready` when the answer\n * decides where traffic goes.\n */\nexport interface HealthReport {\n  /**\n   * Which components this report covers. Carried on the body so a consumer\n   * holding a report can tell the operational aggregate from the routing\n   * signal, rather than having to remember which path produced it.\n   */\n  view: HealthView;\n  status: HealthStatus;\n  /** The app's own serving lifecycle. Always present, always instance-domain. */\n  context: HealthComponent;\n  routes: Record<string, HealthComponent>;\n  indicators: Record<string, HealthComponent>;\n}\n\n/** The liveness body. Deliberately carries no component state. */\nexport interface LivenessReport {\n  status: \"up\";\n  uptime: number;\n}\n\n/**\n * Exposure of the per-component `details` maps.\n *\n * - `always`: serve details to every caller.\n * - `when-authenticated`: serve details only to a caller the mount's\n *   effective validator admits (the ops mount's own `auth`, else the\n *   server's). Written explicitly with no validator in scope it fails the\n *   boot: the operator asked for a gate and there is nothing to gate with.\n *   As the unwritten default with no validator it collapses to `never`,\n *   with a startup warning naming the ways out: a missing diagnostic is\n *   visible and self-correcting, a leak is silent, and indicator details are\n *   arbitrary app-supplied objects.\n * - `never`: never serve details.\n *\n * The gate withholds per-component diagnostics and nothing else. It does not\n * hide topology: component names are the keys of the always-served status\n * maps, and the per-component paths answer 404 for an unknown id in every\n * mode. An app that must not disclose its route inventory puts the ops\n * listener somewhere the public cannot reach it.\n */\nexport type HealthDetailsExposure = \"always\" | \"when-authenticated\" | \"never\";\n\n/** Health endpoint configuration. */\nexport interface OpsHealthOptions {\n  /** Exposure of per-component `details`. Defaults to `when-authenticated`. */\n  details?: HealthDetailsExposure;\n}\n\n/** Options for {@link opsPlugin}. */\nexport interface OpsPluginOptions {\n  /**\n   * Named server (`defineConfig({ servers })`) to mount the health paths on.\n   * Defaults to `\"default\"`.\n   *\n   * A dedicated ops port is a second named server the surface points at, which\n   * is how an internal-only surface is expressed. Bind that server somewhere\n   * the probes can reach: a Kubernetes `httpGet` probe comes from the kubelet\n   * against the pod IP and a reverse-proxy check comes from the proxy, so\n   * neither reaches `127.0.0.1`. Only a Docker `HEALTHCHECK`, which runs\n   * inside the container, does. Keep the port private at the network layer\n   * rather than by binding loopback.\n   */\n  server?: string;\n  /**\n   * Validator for the details gate: `health.details: \"when-authenticated\"`\n   * admits callers through this, falling back to the server's validator when\n   * unset. It is not a wall. The health surface answers every probe without\n   * a credential whatever this says, because an orchestrator's probe carries\n   * none and a health endpoint that answers it 401 is a health endpoint that\n   * restarts the pod. `health.details: \"always\"` is the way to serve\n   * details to every caller.\n   *\n   * The management tiers under `/ops` identify their caller through this\n   * same validator, and each tier's own {@link OpsTier} value decides what\n   * that identity must carry.\n   *\n   * `false` follows the server plugin's meaning unchanged: the mount\n   * declares no wall, while the inherited validator stays reachable for\n   * anything that pulls identity rather than demanding it. So the details\n   * gate still admits an authenticated caller, and a scope-gated tier,\n   * which does demand it, is refused at boot as a contradiction rather than\n   * quietly enforced through a validator the mount opted out of.\n   */\n  auth?: HttpAuth | false;\n  /** Health endpoint configuration. */\n  health?: OpsHealthOptions;\n  /**\n   * The management API's exposure, one field per tier. Every tier is\n   * disabled unless named here, so an app that configures nothing serves\n   * health and answers 404 on every `/ops` path.\n   *\n   * See {@link OpsTier} for what each value means. A scope string needs a\n   * wall to enforce it, so one written where this mount declares none\n   * (no `auth` here and none on its server, or an explicit `auth: false`)\n   * fails the boot rather than admitting everyone.\n   */\n  tiers?: OpsTiers;\n  /** Indicators to register. See `defineIndicator`. */\n  indicators?: readonly Indicator[];\n}\n\n/** The `ops` config key. */\nexport type OpsConfig = OpsPluginOptions;\n\n/** How an indicator is declared. */\nexport interface IndicatorDefinition {\n  /** Unique name. Becomes the key in the report and the path segment. */\n  name: string;\n  /**\n   * No report within this window makes the indicator `down` (stale).\n   *\n   * Optional. With it, the indicator is expected on a cadence, which is right\n   * for a probe route. Without it the indicator is only as fresh as its last\n   * push, which is the correct reading for one fed from a business route that\n   * may legitimately be idle for hours.\n   */\n  maxAge?: Duration;\n  /**\n   * How widely this dependency's failure is felt. Defaults to `deployment`,\n   * which is right for anything reached over the network with shared\n   * credentials: every replica would fail the same way, so it must page\n   * without ever moving traffic.\n   */\n  domain?: FailureDomain;\n  /**\n   * Bind this indicator to a route's exchange outcomes: a completed exchange\n   * reports up, a failed exchange reports down, and no exchange within\n   * `maxAge` goes stale. The route needs no health code at all.\n   *\n   * For probe routes only, where the exchange is the health check by\n   * construction. Binding a business route would make every expected refusal\n   * (a caller without the scope, a validation error, a business rule saying\n   * no) report the dependency down, which is the escalation this design\n   * exists to prevent.\n   */\n  route?: string;\n}\n\n/**\n * A registered indicator: both the declaration and the push handle.\n *\n * Inert until an ops plugin binds it to a context. Ledgers are keyed by\n * context rather than held in a closure slot, so one module-scope handle\n * serves any number of live contexts.\n */\nexport interface Indicator {\n  readonly name: string;\n  readonly definition: Readonly<IndicatorDefinition>;\n  /**\n   * Report this dependency healthy.\n   *\n   * Anything passed in `details` is published on the health endpoint, which\n   * may admit unauthenticated callers. Pass structural facts, never an error\n   * message: `err.message` from a connection or auth failure routinely carries\n   * hosts, usernames, and provider text. Log the error where it happened.\n   */\n  up(details?: HealthDetails): void;\n  /**\n   * Report this dependency unhealthy.\n   *\n   * The same rule as {@link Indicator.up}: `details` reaches the endpoint, so\n   * it carries structural facts and never an error message.\n   */\n  down(details?: HealthDetails): void;\n  /** Mark the indicator inactive: it reports `inactive` and never pages until it reports again. */\n  inactive(): void;\n}\n\n/**\n * One management tier's admission rule.\n *\n * - `false` (and unset): the tier is disabled and its paths answer 404.\n * - `true`: the tier is open and needs no credential of its own.\n * - a scope string: the caller's principal must carry that scope.\n *\n * The mount's `auth` (its own, or the named server's, per the server\n * plugin's inheritance) decides WHO the caller is; this value decides what\n * that identity must carry. The two are deliberately separate: the same\n * validator serves every tier, and only the requirement differs.\n *\n * Disabled answers 404 rather than 403 so an unconfigured instance\n * discloses nothing about what it could expose, and so the rule is the one\n * an ingress proxy would enforce in front of it.\n */\nexport type OpsTier = boolean | string;\n\n/**\n * The management tiers, individually exposed. Unset is `false`, so an app\n * that configures nothing answers 404 on every management path.\n *\n * `operations` (taking a route offline, resetting a breaker) is named in\n * the design and deliberately not delivered yet; it slots in here without\n * reshaping anything.\n */\nexport interface OpsTiers {\n  /** `GET /ops/routes` and `GET /ops/routes/{id}`. */\n  introspection?: OpsTier;\n  /** `POST /ops/routes/{id}/exchanges`. */\n  dispatch?: OpsTier;\n  /**\n   * `GET /ops/events`, the context event bus tailed as Server-Sent Events.\n   *\n   * Its own tier rather than a corner of introspection: the route listing\n   * describes an app's shape, while the tail carries what it is doing right\n   * now, exchange failures and auth decisions included. An operator who\n   * wants one is not thereby asking for the other.\n   */\n  events?: OpsTier;\n}\n\n/**\n * The scope name this project documents for the introspection tier.\n *\n * A convention, not a default: every tier defaults to `false`, and the value\n * an operator writes is any string their tokens carry.\n */\nexport const OPS_SCOPE_INTROSPECTION = \"ops:introspection\";\n/** The scope name this project documents for the dispatch tier. */\nexport const OPS_SCOPE_DISPATCH = \"ops:dispatch\";\n/** The scope name this project documents for the events tier. */\nexport const OPS_SCOPE_EVENTS = \"ops:events\";\n\n/**\n * A read-only resource another package contributes to the management API,\n * served under the introspection tier at `GET /ops/{name}` and\n * `GET /ops/{name}/{segment...}`.\n *\n * The ops plugin lives in core and knows routes, exchanges and events.\n * What an ecosystem package keeps alongside them (an agent's sessions) is\n * listable through the same door and the same tier without core learning\n * what it is: the contributor answers the two reads, and the mount owns\n * admission, method handling and the wire.\n *\n * Read-only by contract. A resource that needs to act on something is the\n * operations tier's business and slots in there when it ships.\n *\n * A throw from either read is answered as a 500 carrying the error's code\n * and never its message; `RC5059` (a malformed limit or cursor) is the one\n * the caller owns and is answered as a 400 with the message.\n *\n * @template TItem - What the collection lists and the item view describes;\n *   plain JSON, since it goes on the wire as the mount serialises it\n */\nexport interface OpsResource<TItem = unknown> {\n  /**\n   * The path segment under `/ops`. `routes` and `events` are the mount's\n   * own and refused.\n   */\n  readonly name: string;\n  /**\n   * The collection, filtered by the request's query parameters. The\n   * contributor pages, with `parsePageQuery()`, `takePage()` and\n   * `decodeCursor()` from core: a present `nextCursor` means there is\n   * more, exactly as for the route collection, and a resource whose whole\n   * collection fits one page returns it without one.\n   */\n  list(query: Readonly<Record<string, string>>): Promise<OpsPage<TItem>>;\n  /**\n   * One item, addressed by the decoded path segments after the resource\n   * name. `undefined` answers 404.\n   */\n  describe(segments: readonly string[]): Promise<TItem | undefined>;\n}\n\n/**\n * A collection response. Never a bare array, from the first release: a\n * present `nextCursor` means there is more, and a correct client follows\n * it even against a collection that does not produce one today.\n */\nexport interface OpsPage<T> {\n  items: T[];\n  /** Opaque keyset cursor. Absent on the last page. */\n  nextCursor?: string;\n}\n\n/**\n * One deferral as `GET /ops/deferrals` renders it.\n *\n * Distinct from the store's own `DeferralSummary`, and only in its\n * timestamps: a store answers in `Date`, and the wire has no such thing.\n * Left as `Date` on this type, `JSON.stringify` would still send strings\n * and every consumer of the client would be typed for a value it never\n * receives. Every closed vocabulary keeps its union, so a consumer can\n * switch exhaustively and a renamed state fails their build rather than\n * silently taking the other branch.\n *\n * What is absent is as deliberate as what is here. Never the resume\n * token, which is the credential; never the stored exchange, which is the\n * caller's data and can be anything; never the step state or the\n * resume-payload schema. A listing answers what is waiting, on what, and\n * for how long.\n */\nexport interface OpsDeferralSummary {\n  /** Deferral id, distinct from the deferred exchange's own id. */\n  id: string;\n  /** The route the deferred exchange belongs to, and re-enters on resume. */\n  routeId: string;\n  state: DeferralState;\n  /** What the work is waiting for, or was waiting for when it settled. */\n  waitingFor: DeferralWaitingFor;\n  /**\n   * Whether a delivery claim is outstanding. A claimed deferral is still\n   * waiting, and is not resumable while the claim holds: whoever took it\n   * owns telling the route.\n   */\n  claimed: boolean;\n  /** ISO 8601. */\n  deferredAt: string;\n  /** ISO 8601. Absent means no deadline. */\n  expiresAt?: string;\n  /** How it settled. Absent while it is waiting. */\n  outcome?: {\n    kind: DeferralOutcome[\"kind\"];\n    /** ISO 8601. When it stopped waiting, which is what retention measures from. */\n    at: string;\n    reason?: string;\n    /** Who resumed it. Only ever set on a `resumed` outcome. */\n    by?: { subject: string; issuer?: string; clientId?: string };\n  };\n}\n\n/**\n * JSON Schema renderings of a route's declared schemas, when the schema\n * library exposes the non-standard `~standard.jsonSchema` extension. A\n * library without it yields nothing here; the live schema is what\n * validation runs against either way, so nothing depends on these.\n */\nexport interface OpsRouteSchemas {\n  body?: unknown;\n  headers?: unknown;\n}\n\n/**\n * A route as the management API presents it.\n *\n * `dispatchable` is observed rather than inferred: a `direct()` ingress\n * registers the route in the capability registry when it subscribes, and\n * that registration is the door `POST .../exchanges` goes through. A cron-,\n * mail- or http-sourced route has no such door and says so here rather than\n * failing at dispatch time.\n *\n * `enabled` is reported separately because `dispatchable` alone cannot carry\n * both meanings. A route held back by its `.enabled()` predicate never\n * subscribes, so it is not in the capability registry either, and without\n * this field it would be indistinguishable from a cron-sourced route that\n * simply has no dispatch door. One is a configuration state an operator can\n * change; the other is the shape of the route.\n */\nexport interface OpsRouteSummary {\n  id: string;\n  dispatchable: boolean;\n  /**\n   * False only while the route's `.enabled()` predicate is holding it back.\n   * True for every route that declares no predicate, so an existing consumer\n   * reading this field sees the state it already assumed.\n   */\n  enabled: boolean;\n  /** Source kinds, in declaration order (`direct`, `cron`, `mail`, ...). */\n  sources: string[];\n  /** The route declares a route-entry `.authorize()`. */\n  requiresPrincipal: boolean;\n  title?: string;\n  description?: string;\n  tags?: string[];\n  /**\n   * The remote this route was imported from, for a route another instance\n   * exposes and `defineConfig({ remotes })` made dispatchable here. Absent\n   * for a route this instance defines. Additive: an existing consumer that\n   * never reads it sees the listing it always saw.\n   */\n  remote?: string;\n}\n\n/** One route in full. Adds the schema renderings to the summary. */\nexport interface OpsRouteDetail extends OpsRouteSummary {\n  input?: OpsRouteSchemas;\n  output?: OpsRouteSchemas;\n}\n\n/** Documented filters on `GET /ops/routes`. */\nexport interface OpsRouteFilter {\n  /** Only routes that do (or do not) have a dispatch door. */\n  dispatchable?: boolean;\n  /** Exact route id match, not a prefix. */\n  id?: string;\n  /** Routes carrying a source of this kind. */\n  source?: string;\n}\n\n/** A page request against the route collection. */\nexport interface OpsRouteQuery extends OpsRouteFilter {\n  limit?: number;\n  after?: string;\n}\n\n/**\n * One item from the event tail.\n *\n * `dropped` and `heartbeat` are the tail's own signals rather than bus\n * events: a slow reader must learn that it missed something instead of\n * silently seeing a gap, and an idle app must still put a byte on the wire\n * often enough that an intermediary does not reap the connection.\n */\nexport type OpsEventTailItem =\n  | {\n      kind: \"event\";\n      /** The bus event's name, which rides the SSE `event` field. */\n      name: string;\n      /**\n       * The frame's payload, already rendered to JSON.\n       *\n       * Rendered when the event is emitted rather than when the reader takes\n       * it, for two reasons. A bus payload may carry `exchange.body`, which\n       * the framework deliberately leaves mutable, so a reference held until\n       * the reader catches up could report a value that never existed at the\n       * moment it was emitted. And holding a few hundred payloads by\n       * reference pins whatever they reach, which on a route moving large\n       * bodies is all of it. Rendering unpins that; the tail's byte budget\n       * is what bounds what remains.\n       */\n      data: string;\n    }\n  | { kind: \"dropped\"; count: number }\n  | { kind: \"heartbeat\" };\n\n/**\n * What a dispatch produced.\n *\n * A deferral is an outcome, not an error: a route that reaches a durable\n * `.defer()` replies with the acknowledgment every other surface returns,\n * and the operator at the terminal is often exactly who the deferral waits for.\n * A drop is separate from a failure because they need different answers: a\n * drop means a filter said no, a failure means something broke.\n */\nexport type OpsDispatchOutcome =\n  | { outcome: \"completed\"; body: unknown }\n  | { outcome: \"deferred\"; deferral: Deferred }\n  | { outcome: \"dropped\"; message: string };\n","import type { CraftContext } from \"../context.ts\";\nimport type { Exchange } from \"../exchange.ts\";\nimport type { RouteDiscovery } from \"../route.ts\";\nimport type { Adapter, Message } from \"../types.ts\";\n\n/**\n * Metadata the engine passes to a source adapter at subscribe time.\n *\n * Carries the route's id and optional discovery bundle so adapters that\n * maintain registries (direct, mcp) can mirror route-level metadata into\n * their own registry entries without re-declaring it in adapter options.\n */\nexport interface SourceMeta {\n  /** ID of the route this source is subscribed to. */\n  routeId: string;\n  /** Route-level discovery bundle, when set via the builder. */\n  discovery?: RouteDiscovery;\n  /**\n   * The route declares a route-entry `.authorize()`, so it cannot run\n   * without a verified principal. Identity-capable transports (the http\n   * dispatcher) use this to pull credential verification even on a mount\n   * with no wall; transports without a credential channel ignore it and\n   * the authorize step rejects at route entry as before.\n   */\n  requiresPrincipal?: boolean;\n  /**\n   * The route's consumer may hold a message before the pipeline runs, as\n   * `.batch()` does, so `emit()` returning does not mean work has started or\n   * that the route counts it as in flight.\n   *\n   * A source that acknowledges a delivery on its own authority needs to know\n   * this: it would otherwise report success for a message the route can still\n   * discard at shutdown. Sources that simply await `emit()` can ignore it.\n   */\n  bufferedConsumer?: boolean;\n}\n\n/**\n * Everything a source adapter needs from the engine, handed to\n * {@link CallableSource} as a single object. Adding a capability to this\n * interface is additive; the source contract never changes shape again.\n *\n * Sources that authenticate at their boundary (e.g. the MCP server with\n * `auth:` configured) forward the resolved identity by writing the\n * structured `Principal` into `headers[\"routecraft.auth.principal\"]`\n * on the emitted message: state lives on `headers`, full stop.\n *\n * @template T - Body type of messages produced by this source (after parse)\n */\nexport interface Subscription<T = unknown> {\n  /** The owning context (store access, logger, events). */\n  context: CraftContext;\n  /** Fires when the route stops; sources must stop producing and return. */\n  signal: AbortSignal;\n  /** Route id and discovery bundle for registry-maintaining sources. */\n  meta: SourceMeta;\n  /**\n   * Signal readiness: the source is wired and able to produce. Routes\n   * emit `route:started` once every source has called this (emitting a\n   * first message also marks readiness as a fallback).\n   */\n  ready(): void;\n  /**\n   * Signal that this finite source has finished producing. Aborts the\n   * source's controller so a single-source route completes; on a\n   * multi-ingress route only this source's child controller aborts.\n   * Pass a reason to record an abnormal completion as the abort reason;\n   * to surface a fatal source error to the engine, reject from\n   * `subscribe` instead (the route aborts with that error). Idempotent:\n   * calling it again (or after the signal already aborted) is a no-op.\n   */\n  complete(reason?: unknown): void;\n  /**\n   * Hand one message to the route. Resolves with the processed exchange\n   * (or rejects with the pipeline error, which sources typically catch\n   * and log so one bad message does not kill the source).\n   *\n   * The {@link Message} envelope carries the payload plus the optional\n   * `parse` / `parseFailureMode` used by the synthetic parse step: when\n   * `parse` is set, `message` is the RAW value (e.g. a JSON line string)\n   * and the parsed result becomes the exchange body. See\n   * `adapters/shared/parse.ts` for the `OnParseError` semantics.\n   */\n  emit(msg: Message<T>): Promise<Exchange>;\n}\n\n/**\n * Function form of a source: subscribes to data and emits messages until\n * the subscription's signal aborts. Use with `.from(callableSource)` or\n * adapters that implement {@link Source}.\n *\n * ```ts\n * .from(async (sub) => {\n *   while (!sub.signal.aborted) {\n *     const item = await poll();\n *     await sub.emit({ message: item, headers: { \"x-origin\": \"poll\" } });\n *   }\n * })\n * ```\n *\n * @template T - Body type of messages produced by this source (after parse)\n */\nexport type CallableSource<T = unknown> = (\n  sub: Subscription<T>,\n) => Promise<void> | void;\n\n/**\n * Source adapter: produces messages for a route. Used with `.from(source)`.\n *\n * @template T - Body type of messages produced\n */\nexport interface Source<T = unknown> extends Adapter {\n  subscribe: CallableSource<T>;\n}\n\n/**\n * Generator form of a source: an (async) generator function receiving the\n * {@link Subscription} and yielding message bodies. Each yielded value is\n * emitted sequentially (`await sub.emit(...)` per item, so the pipeline\n * applies natural backpressure); when the generator returns, the source\n * completes like any finite source. Use `sub.emit({ message, headers })`\n * directly inside the generator when a message needs headers.\n *\n * ```ts\n * .from(async function* (sub) {\n *   while (!sub.signal.aborted) {\n *     yield await poll();\n *   }\n * })\n * ```\n *\n * @template T - Body type of messages produced by this source\n */\nexport type GeneratorSource<T = unknown> = (\n  sub: Subscription<T>,\n) => AsyncGenerator<T, void, unknown> | Generator<T, void, unknown>;\n\n/**\n * Anything `.from()` accepts and normalizes into a {@link Source}:\n * a Source adapter, a callable source, an (async) generator function,\n * or a bare (async) iterable of message bodies.\n *\n * @template T - Body type of messages produced\n */\nexport type SourceLike<T = unknown> =\n  | Source<T>\n  | CallableSource<T>\n  | GeneratorSource<T>\n  | AsyncIterable<T>\n  | Iterable<T>;\n\n/** A non-empty list of sources, the type a helper returns so `.from(...helper())` compiles. */\nexport type SourceList = [SourceLike<unknown>, ...SourceLike<unknown>[]];\n\nconst ASYNC_GENERATOR_CTOR = Object.getPrototypeOf(async function* () {})\n  .constructor as object;\nconst GENERATOR_CTOR = Object.getPrototypeOf(function* () {})\n  .constructor as object;\n\n/** True when `value` is an (async) generator FUNCTION (not a running generator). */\nfunction isGeneratorFunction(value: unknown): value is GeneratorSource {\n  if (typeof value !== \"function\") return false;\n  const ctor = (value as { constructor?: object }).constructor;\n  return ctor === ASYNC_GENERATOR_CTOR || ctor === GENERATOR_CTOR;\n}\n\n/** True when `value` is a bare (async) iterable object (not a Source). */\nfunction isIterableSource(value: unknown): value is AsyncIterable<unknown> {\n  if (value === null || typeof value !== \"object\") return false;\n  if (typeof (value as Source).subscribe === \"function\") return false;\n  const v = value as Record<symbol, unknown>;\n  return (\n    typeof v[Symbol.asyncIterator] === \"function\" ||\n    typeof v[Symbol.iterator] === \"function\"\n  );\n}\n\n/**\n * Normalize anything `.from()` accepts into a {@link Source}.\n *\n * Generator functions and bare iterables drive the subscription loop:\n * items are emitted sequentially, per-item pipeline failures are logged\n * at debug and do not stop iteration (matching `simple()`'s batch\n * semantics), and exhaustion completes the source.\n *\n * Every normalized form signals readiness on its own: the iterable path\n * from inside its loop, a bare callable the moment the route invokes it.\n * A `Source` adapter remains responsible for its own `ready()`.\n *\n * @internal Used by the route builder.\n */\nexport function toSource<T>(input: SourceLike<T>): Source<T> {\n  if (typeof input === \"function\") {\n    if (isGeneratorFunction(input)) {\n      const generator = input as GeneratorSource<T>;\n      return { subscribe: (sub) => drainIterable(sub, generator(sub)) };\n    }\n    const callable = input as CallableSource<T>;\n    // A bare callable IS the consumer loop: it is invoked once and polls\n    // until the signal aborts. Readiness therefore belongs at the moment\n    // the loop begins, not at its first message. Left to the emit-time\n    // fallback, the polling shape the `from()` docs teach (a quiet mail\n    // folder, an idle queue) signals readiness only when something finally\n    // arrives, so every boot pays the 30s route-readiness backstop.\n    return {\n      subscribe: (sub) => {\n        // Invoke FIRST, then mark ready: a callable that throws\n        // synchronously while wiring never became able to produce, and\n        // must not have announced itself as ready on the way out. An async\n        // callable has returned at its first await by this point, which is\n        // the loop running.\n        const running = callable(sub);\n        sub.ready();\n        return running;\n      },\n    };\n  }\n  if (isIterableSource(input)) {\n    const iterable = input as AsyncIterable<T>;\n    return { subscribe: (sub) => drainIterable(sub, iterable) };\n  }\n  return input as Source<T>;\n}\n\n/** Sentinel resolved by the abort race so a deferred pull can be abandoned. */\nconst ABORTED = Symbol(\"routecraft.iterable.aborted\");\n\n/** Shared loop for generator and iterable sources. */\nasync function drainIterable<T>(\n  sub: Subscription<T>,\n  iterable: AsyncIterable<T> | Iterable<T>,\n): Promise<void> {\n  sub.ready();\n  let failCount = 0;\n  const iterator =\n    Symbol.asyncIterator in iterable\n      ? iterable[Symbol.asyncIterator]()\n      : (iterable as Iterable<T>)[Symbol.iterator]();\n  // Race each pull against abort: a generator deferred on a slow await\n  // would otherwise pin shutdown until its next yield.\n  let onAbort: (() => void) | undefined;\n  const aborted = new Promise<typeof ABORTED>((resolve) => {\n    onAbort = () => resolve(ABORTED);\n    sub.signal.addEventListener(\"abort\", onAbort, { once: true });\n  });\n  let iterErr: unknown;\n  try {\n    while (!sub.signal.aborted) {\n      const result = await Promise.race([\n        Promise.resolve(iterator.next()),\n        aborted,\n      ]);\n      if (result === ABORTED || result.done) break;\n      try {\n        await sub.emit({ message: result.value });\n      } catch {\n        // Exchange error already logged by the route pipeline; keep\n        // iterating so one bad item does not kill the source (matching\n        // simple()'s array semantics).\n        failCount++;\n      }\n    }\n  } catch (err) {\n    // Record the reason for complete(), then rethrow so the engine treats\n    // an iterator crash as a source failure (route aborts with the error).\n    iterErr = err;\n    throw err;\n  } finally {\n    if (onAbort) sub.signal.removeEventListener(\"abort\", onAbort);\n    // Best-effort resource release when we bailed before exhaustion\n    // (abort or a pipeline-level break); errors here are secondary.\n    try {\n      await Promise.resolve(iterator.return?.()).catch(() => undefined);\n    } catch {\n      // Sync iterators can throw from return(); nothing left to clean up.\n    }\n    if (failCount > 0) {\n      sub.context.logger.warn(\n        { adapter: \"iterable\", failCount },\n        \"Some exchanges from iterable source failed\",\n      );\n    }\n    sub.complete(iterErr);\n  }\n}\n","import {\n  type Adapter,\n  type Step,\n  type StepContext,\n  type StepOutcome,\n  type StepSignalContext,\n  toSignalContext,\n} from \"../types.ts\";\nimport { type Exchange, OperationType, DefaultExchange } from \"../exchange.ts\";\n\n/**\n * Function form of a processor: receives the full exchange and returns a new\n * exchange. Use with `.process(processor)`. Prefer pure logic; use `.to()`\n * for IO side effects.\n *\n * The returned exchange must be a new value; the parameter is `Readonly<>`\n * and the framework will TypeError if user code reassigns its fields. Build\n * the result via spread:\n *\n * ```ts\n * .process((ex) => ({\n *   ...ex,\n *   body: { ...ex.body, hello: \"world\" },\n *   headers: { ...ex.headers, \"x-tag\": \"v\" },\n * }))\n * ```\n *\n * The framework re-wraps a plain spread back into a proper exchange instance\n * via {@link DefaultExchange.rewrap}, preserving the internal context binding.\n *\n * The second argument carries the step's {@link StepSignalContext}: when an\n * enclosing `.timeout()` expires, `ctx.signal` aborts, so a processor doing\n * cancellation-aware IO can forward it (`fetch(url, { signal })`). Declaring\n * only the first parameter remains valid.\n *\n * @template T - Current body type\n * @template R - Result body type (default T)\n */\nexport type CallableProcessor<\n  T = unknown,\n  R = T,\n  Ex extends Exchange<T> = Exchange<T>,\n> = (\n  exchange: Ex,\n  ctx?: StepSignalContext,\n) => Promise<Exchange<R>> | Exchange<R>;\n\n/**\n * Processor adapter: transforms the whole exchange (body, headers). Used with `.process()`.\n * Use when you need headers or full exchange; use `.transform()` for body-only mapping.\n *\n * @template T - Current body type\n * @template R - Result body type\n */\nexport interface Processor<T = unknown, R = T> extends Adapter {\n  process: CallableProcessor<T, R>;\n}\n\n/**\n * Step that runs a processor on the full exchange. The returned exchange's\n * body and headers replace the current ones; identity (id, internals) is\n * preserved by the framework.\n */\nexport class ProcessStep<T = unknown, R = T> implements Step<Processor<T, R>> {\n  operation: OperationType = OperationType.PROCESS;\n  adapter: Processor<T, R>;\n\n  constructor(adapter: Processor<T, R> | CallableProcessor<T, R>) {\n    this.adapter =\n      typeof adapter === \"function\" ? { process: adapter } : adapter;\n  }\n\n  async execute(\n    exchange: Exchange<T>,\n    ctx?: StepContext,\n  ): Promise<StepOutcome> {\n    const returned = await Promise.resolve(\n      this.adapter.process(exchange, toSignalContext(ctx)),\n    );\n    // The fast path is identity equality (the user returned the same `ex`\n    // they were given). For anything else -- a plain spread, a freshly\n    // constructed `DefaultExchange`, or even an exchange built against a\n    // foreign context -- always rewrap onto THIS exchange's internals.\n    // An `instanceof DefaultExchange` fast-path would let a user return\n    // `new DefaultExchange(otherContext, ...)` and break route binding\n    // for downstream telemetry / split / tap; rewrap restores it.\n    //\n    // Cross-cutting concerns like the authenticated principal flow through\n    // `returned.headers` automatically: rewrap forces `prev.id` for\n    // identity but otherwise threads the user's headers verbatim, so a\n    // returned exchange that preserves `headers` (the common case via\n    // spread) keeps its principal, span, tenant, etc. without any\n    // operation-specific plumbing.\n    //\n    // We do NOT forward `returned.id` into rewrap. `.process()` is a body\n    // transform; identity is owned by the framework. A user who returns\n    // `new DefaultExchange(ctx, ...)` (with a fresh UUID) inside a\n    // processor must not silently change the exchange id mid-route, or\n    // event correlation, split bookkeeping, and child telemetry break.\n    // Identity-changing operations (split, aggregate) have dedicated\n    // paths.\n    // Fast-path: a processor that returns the same instance it was handed\n    // (typical for `tap`-like uses or transform-in-place patterns) skips\n    // a `rewrap` allocation. The double cast is required because\n    // `exchange: Exchange<T>` and `returned: Exchange<R>` have different\n    // generic parameters even when they are the same runtime reference;\n    // `===` operates on the runtime reference, the cast just satisfies\n    // the type checker that the reference is shape-compatible with R.\n    const next =\n      returned === (exchange as unknown as Exchange<R>)\n        ? (exchange as unknown as Exchange<R>)\n        : DefaultExchange.rewrap<R>(exchange, {\n            body: returned.body,\n            headers: returned.headers,\n          });\n    return { kind: \"continue\", exchange: next };\n  }\n}\n","import {\n  type Adapter,\n  type Step,\n  type StepContext,\n  type StepOutcome,\n  type StepSignalContext,\n  extractOutcomeMetadata,\n  toSignalContext,\n} from \"../types.ts\";\nimport {\n  type Exchange,\n  type ExchangeHeaders,\n  type HeaderValue,\n  OperationType,\n  getExchangeContext,\n  DefaultExchange,\n} from \"../exchange.ts\";\nimport type { Enricher, CallableEnricher } from \"./enrich.ts\";\nimport { hasSend, hasFetch, missingSlotError } from \"./adapter-roles.ts\";\nimport { engineOwnedHeaderSuggestion } from \"../engine-headers.ts\";\nimport {\n  resolveAdapterOverride,\n  invokeSendOverride,\n} from \"../testing-hooks.ts\";\nimport { DEFER_HOST } from \"../dsl-symbol.ts\";\nimport type { DeferCapableStep, DeferSite } from \"../deferral/sites.ts\";\nimport { convertDeferSignal, isDeferSignal } from \"../deferral/signal.ts\";\n\n/**\n * Context handed to a destination's `send`. Extends the abort surface with a\n * header sink: a send that produces a receipt (a message id, an etag, a\n * created-resource URL) surfaces it by calling `setHeader`, and the `.to()`\n * step merges the collected headers onto the continuing exchange. The body is\n * never touched by a send; receipts ride headers, results ride `fetch`.\n *\n * `.tap()` also provides the sink, but the tap runs against a detached\n * snapshot, so headers set there are discarded with it.\n *\n * The parameter is optional at the call site (adapters invoked directly in\n * tests may omit it), so implementations should guard: `ctx?.setHeader(...)`.\n */\nexport interface SendContext extends StepSignalContext {\n  /** Record a receipt header to merge onto the continuing exchange. */\n  setHeader(key: string, value: HeaderValue): void;\n}\n\n/**\n * Function form of a destination: receives the exchange and performs a side\n * effect. Strictly void: a returned value is not a body replacement (use an\n * {@link Enricher} or `.enrich()` when the step should produce data).\n *\n * The second argument carries the step's {@link SendContext}: `signal` aborts\n * when an enclosing `.timeout()` expires (forward it into cancellation-aware\n * IO), and `setHeader` records receipt headers for the continuing exchange.\n * Declaring only the first parameter remains valid.\n *\n * @template T - Current body type\n */\nexport type CallableDestination<T = unknown> = (\n  exchange: Exchange<T>,\n  ctx?: SendContext,\n) => Promise<void> | void;\n\n/**\n * Destination adapter: pushes the exchange OUT to an external system (HTTP\n * call, queue, file write, SMTP send). Used with `.to()` and `.tap()`.\n *\n * `send` is strictly void: the body flows through a `.to()` step unchanged.\n * A send that produces a receipt surfaces it via `ctx.setHeader` (see\n * {@link SendContext}); an adapter whose purpose is to PRODUCE data\n * implements {@link Enricher} instead (or additionally).\n *\n * @template T - Current body type\n */\nexport interface Destination<T = unknown> extends Adapter {\n  send: CallableDestination<T>;\n}\n\n/**\n * Anything `.to()` accepts: a Destination (send wins when both slots exist),\n * an Enricher (fetch-only pull-in; the result replaces the body), or a\n * function form routed by its inferred return type.\n *\n * @template T - Current body type\n * @template R - Fetch result type for the enricher / function forms\n */\nexport type ToTarget<T = unknown, R = unknown> =\n  | Destination<T>\n  | Enricher<T, R>\n  | CallableDestination<T>\n  | CallableEnricher<T, R>;\n\n/**\n * Step that hands the exchange to a destination or enricher.\n *\n * Resolution follows the role model: an adapter with `send` is invoked as a\n * push-out and the body continues unchanged (receipt headers from the\n * {@link SendContext} sink are merged on); an adapter with only `fetch` is\n * invoked as a pull-in and the result replaces the body. Function forms are\n * invoked directly: a returned value (other than `undefined`) replaces the\n * body, mirroring the static send/fetch split on the inferred return type.\n */\nexport class ToStep<T = unknown, R = unknown>\n  implements Step<Adapter>, DeferCapableStep\n{\n  operation: OperationType = OperationType.TO;\n  adapter: Adapter;\n  /** Assigned by the defer-site walk when the adapter is defer-capable. */\n  deferSite?: DeferSite;\n  /** Why the walk refused a site (fan-out or sealed side flow), when it did. */\n  deferRefusal?: string;\n  /** Function form, when constructed from a bare callable. */\n  private readonly callable: CallableEnricher<T, R | void> | undefined;\n\n  /** This step hosts its own defer site; wrappers forward here. @internal */\n  [DEFER_HOST](): DeferCapableStep {\n    return this;\n  }\n\n  constructor(target: ToTarget<T, R>) {\n    if (typeof target === \"function\") {\n      this.callable = target as CallableEnricher<T, R | void>;\n      this.adapter = { send: target } as Adapter;\n    } else {\n      this.callable = undefined;\n      this.adapter = target;\n    }\n  }\n\n  async execute(\n    exchange: Exchange<T>,\n    ctx?: StepContext,\n  ): Promise<StepOutcome> {\n    // Resolve a test-time override (if any) registered on the context.\n    // When present, the mock handler stands in for the adapter; if the mock\n    // has no handler, the call is silently swallowed (a noop destination).\n    const override = resolveAdapterOverride(\n      this.adapter,\n      getExchangeContext(exchange),\n      \"send\",\n    );\n\n    const receiptHeaders: Record<string, HeaderValue> = {};\n    const sendContext: SendContext = {\n      ...toSignalContext(ctx),\n      setHeader: (key, value) => {\n        // Receipts are merged onto the continuing exchange, so the sink has\n        // to respect the same engine-owned keys `.header()` rejects: a\n        // receipt landing on `routecraft.route` or `.split_hierarchy` would\n        // misattribute events or break split correlation. `.header()` can\n        // throw because it validates at construction; here the send has\n        // already happened, so failing the step would be worse than dropping\n        // the header. Warn loudly and ignore.\n        const suggestion = engineOwnedHeaderSuggestion(key);\n        if (suggestion !== undefined) {\n          exchange.logger.warn(\n            { header: key, adapter: this.adapter.adapterId, suggestion },\n            \"Adapter tried to set a framework-owned header as a send receipt; ignoring\",\n          );\n          return;\n        }\n        receiptHeaders[key] = value;\n      },\n    };\n\n    let result: unknown;\n    let sendResolved = false;\n    try {\n      if (override) {\n        result = await invokeSendOverride(exchange, this.adapter, override);\n        // A mocked send stays a send: the body continues unchanged even if\n        // the mock returned a value. Only fetch-resolved calls replace it.\n        if (!this.callable && hasSend<T>(this.adapter)) {\n          result = undefined;\n        }\n      } else if (this.callable) {\n        result = await Promise.resolve(this.callable(exchange, sendContext));\n      } else if (hasSend<T>(this.adapter)) {\n        sendResolved = true;\n        await Promise.resolve(this.adapter.send(exchange, sendContext));\n        result = undefined;\n      } else if (hasFetch<T, R>(this.adapter)) {\n        result = await Promise.resolve(\n          this.adapter.fetch(exchange, toSignalContext(ctx)),\n        );\n      } else {\n        throw missingSlotError(\"`.to()`\");\n      }\n    } catch (err) {\n      // Converted here, inside the step, so a step-scope wrapper never\n      // observes the raw throw (a retry wrapper would re-run the adapter\n      // and charge the deferred work twice).\n      if (isDeferSignal(err)) {\n        return convertDeferSignal(this, exchange, err);\n      }\n      throw err;\n    }\n\n    const collectedHeaders = Object.keys(receiptHeaders).length\n      ? receiptHeaders\n      : undefined;\n\n    // The metadata rides the OUTCOME, not the step: Step instances are\n    // shared across exchanges. The two slots have distinct hooks: a\n    // fetch-resolved call hands its result to `getMetadata`, a\n    // send-resolved call hands its receipt-header record (or undefined\n    // when no receipts were set) to `getSendMetadata`.\n    const metadata = sendResolved\n      ? extractOutcomeMetadata(\n          this.adapter,\n          collectedHeaders,\n          !!override,\n          \"getSendMetadata\",\n          exchange,\n        )\n      : extractOutcomeMetadata(\n          this.adapter,\n          result,\n          !!override,\n          \"getMetadata\",\n          exchange,\n        );\n\n    // A fetch result (or a value returned from a function form) replaces the\n    // body via a derived exchange; receipt headers from a send are merged the\n    // same way. The original is frozen, so a new wrapper preserves identity\n    // and internals via rewrap.\n    let next: Exchange<unknown> = exchange;\n    if (result !== undefined || collectedHeaders) {\n      next = DefaultExchange.rewrap<unknown>(exchange, {\n        ...(result !== undefined ? { body: result } : {}),\n        ...(collectedHeaders\n          ? {\n              headers: {\n                ...exchange.headers,\n                ...collectedHeaders,\n              } as ExchangeHeaders,\n            }\n          : {}),\n      });\n    }\n\n    return {\n      kind: \"continue\",\n      exchange: next,\n      ...(metadata ? { metadata } : {}),\n    };\n  }\n}\n","import { rcError, type RoutecraftError } from \"../error.ts\";\nimport type { Destination } from \"./to.ts\";\nimport type { Enricher } from \"./enrich.ts\";\n\n/**\n * Structural checks for the adapter role slots, shared by the steps that\n * resolve them (`.to()`, `.tap()`, `.enrich()`) so send-wins resolution has\n * exactly one definition. Leaf module on purpose: it imports only types, so\n * every operation module can depend on it without cycles.\n */\n\n/** Structural check for the send slot. @internal */\nexport function hasSend<T>(adapter: object): adapter is Destination<T> {\n  return typeof (adapter as Destination<T>).send === \"function\";\n}\n\n/** Structural check for the fetch slot. @internal */\nexport function hasFetch<T, R>(adapter: object): adapter is Enricher<T, R> {\n  return typeof (adapter as Enricher<T, R>).fetch === \"function\";\n}\n\n/**\n * RC5003 for a `.to()` / `.tap()` target that fills neither role slot.\n * `.enrich()` keeps its own fetch-only wording and does not use this.\n * @internal\n */\nexport function missingSlotError(op: \"`.to()`\" | \"`.tap()`\"): RoutecraftError {\n  return rcError(\"RC5003\", undefined, {\n    message: `${op} target implements neither \\`send\\` nor \\`fetch\\``,\n    suggestion:\n      \"Pass a Destination (send), an Enricher (fetch), or a function form\",\n  });\n}\n","import { HeadersKeys } from \"./exchange.ts\";\n\n/**\n * Engine-owned headers, mapped to the remediation shown when something tries\n * to set one:\n *\n * - `routecraft.id`: `DefaultExchange.rewrap` unconditionally restores\n *   `prev.id` into the new headers, so a write would land in the merged\n *   record but be overwritten by the next rewrap, silently no-op-ing.\n * - `routecraft.operation`: rewritten by the engine before every step to\n *   reflect the current operation; a write is equally futile.\n * - `routecraft.route`: set at exchange construction; a write would\n *   persist but lie about which route owns the exchange.\n * - `routecraft.split_hierarchy`: maintained by split/aggregate to\n *   correlate children with their parent; a write corrupts joins.\n *\n * The rest of the reserved `routecraft.*` namespace (correlation id,\n * principal, adapter envelope keys) is deliberately settable: those keys are\n * documented inputs (e.g. addressing a mail operation via `MailHeaders.UID`),\n * and adapter receipt headers live there too.\n *\n * A `Map` (not an object literal) so user keys that collide with\n * `Object.prototype` members (\"toString\", \"constructor\", \"__proto__\", ...)\n * are never misread as engine-owned.\n *\n * Two callers enforce this from opposite ends: `.header()` rejects at\n * construction (RC5003), and the `.to()` receipt sink drops the write at\n * runtime with a warning (the send has already happened by then, so failing\n * the step would be worse than ignoring the header).\n *\n * @internal\n */\nconst ENGINE_OWNED_HEADERS: ReadonlyMap<string, string> = new Map([\n  [\n    HeadersKeys.ID,\n    \"Identity is set once when the exchange is constructed and propagates automatically. If you need to correlate with an upstream id, use routecraft.correlation_id (settable via .header() or by source adapters).\",\n  ],\n  [\n    HeadersKeys.OPERATION,\n    \"The engine rewrites the operation header before every step; observe it via exchange.headers instead of setting it.\",\n  ],\n  [\n    HeadersKeys.ROUTE_ID,\n    \"The route id is bound when the exchange is constructed. To hand work to another route, use forward() or a direct() destination.\",\n  ],\n  [\n    HeadersKeys.SPLIT_HIERARCHY,\n    \"The split hierarchy is maintained by .split() / .aggregate(). To attach your own grouping metadata, use a custom header key.\",\n  ],\n]);\n\n/**\n * Remediation text for an engine-owned header key, or `undefined` when the key\n * is free to set.\n *\n * @param key - Header key to test\n * @returns Suggestion to show the caller, or `undefined` when the key is settable\n * @internal\n */\nexport function engineOwnedHeaderSuggestion(key: string): string | undefined {\n  return ENGINE_OWNED_HEADERS.get(key);\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { BRAND, isBranded, setBrand } from \"../brand.ts\";\nimport { rcError } from \"../error.ts\";\nimport type { Exchange } from \"../exchange.ts\";\nimport type { StepOutcome } from \"../types.ts\";\nimport { type Duration, parseDuration } from \"../shared/duration.ts\";\nimport type { DeferCapableStep } from \"./sites.ts\";\n\n/**\n * What a defer-capable adapter resolves when it raises a deferral from\n * inside its own execution: the same pieces `.defer({ schema, ttl })`\n * declares statically, plus the closure state only the step can produce.\n */\nexport interface DeferSignalRequest {\n  /**\n   * Schema describing what a valid resume payload looks like. Optional: absent\n   * declares no contract at all, and the descriptor records that, so a site\n   * edited from a declared schema to none moves the digest rather than\n   * quietly accepting anything.\n   *\n   * Folded into the continuation hash and rendered onto the `Deferred`\n   * acknowledgment. For a re-entrant site it is descriptive only at resume\n   * time: the live schema exists in the raising step's own code and cannot\n   * be read back off the route, so revival delivers the raw payload and the\n   * step is the validator. See `DeferSite.reentrant`.\n   */\n  readonly schema?: StandardSchemaV1;\n  /** How long the deferral stays resumable. Absent means the context default. */\n  readonly ttl?: Duration;\n  /**\n   * Anything the resuming route needs to decide who may resume. Plain\n   * JSON, persisted verbatim, never interpreted by the framework.\n   */\n  readonly meta?: unknown;\n  /**\n   * Identity of the call this deferral belongs to, so a batch that mints one\n   * credential per call cannot have one call's recipient resume another's\n   * deferral.\n   */\n  readonly callBinding?: string;\n  /**\n   * Closure state owned by the raising step, persisted verbatim in the\n   * record's `stepState` slot and handed back to the step when the\n   * exchange resumes. Subject to the same plain-JSON rule as the exchange\n   * (`RC5042`).\n   */\n  readonly stepState?: unknown;\n}\n\n/**\n * The throwable a defer-capable adapter raises to defer the exchange it is\n * executing.\n *\n * An `Error` subclass on purpose: the signal is control flow, and the\n * `.to()` / `.enrich()` step that hosts the site converts it into the\n * ordinary `defer` StepOutcome before any wrapper can observe it, but a\n * signal raised somewhere without a revivable site (a `.tap()` snapshot, an\n * unbuilt route, a synthetic dispatch) surfaces as a legible failure rather\n * than an opaque thrown object.\n *\n * Never `instanceof`-checked: the brand survives duplicate copies of this\n * package in one process, which is the same reason every other framework\n * brand uses `Symbol.for`.\n */\nexport class DeferSignal extends Error {\n  override readonly name = \"DeferSignal\";\n  readonly request: DeferSignalRequest;\n\n  constructor(request: DeferSignalRequest) {\n    super(\n      \"A durable deferral was raised from a step without a revivable defer site. \" +\n        \"A deferral can only be raised from a .to() / .enrich() step of a built route's \" +\n        \"primary flow (or a .choice() branch of it): not from a .tap() snapshot, a \" +\n        \".multicast() path, a .dispatch() target, inside a .split() fan-out, or a \" +\n        \"dispatch that never entered a route.\",\n    );\n    this.request = request;\n    setBrand(this, BRAND.DeferSignal);\n  }\n}\n\n/**\n * Whether a thrown value is the framework's own {@link DeferSignal}.\n *\n * Public alongside {@link DeferSignal} for the same audience: a runtime\n * hosting defer-capable steps (the agent tier is the shipped one) uses it\n * to let a raised deferral pass through its own error accounting instead\n * of reporting a deferral as a failure.\n */\nexport function isDeferSignal(value: unknown): value is DeferSignal {\n  return isBranded(value, BRAND.DeferSignal);\n}\n\n/**\n * Convert a caught {@link DeferSignal} into the ordinary `defer`\n * StepOutcome, or refuse it where no revivable site exists.\n *\n * Called by the `.to()` / `.enrich()` step that hosts the site, INSIDE its\n * own `execute`, which is the property that keeps step-scope wrappers\n * honest: a retry wrapper that saw the raw throw would re-run the step and\n * charge the work twice, so by the time any wrapper observes anything, the\n * deferral is already an outcome wrappers pass through.\n *\n * @throws RC5051 when the step has no site: it sits inside a `.split()`\n *   fan-out or a sealed side flow (the walk recorded why), or the signal\n *   was raised somewhere that never went through a built route.\n *\n * @internal\n */\nexport function convertDeferSignal(\n  host: Pick<DeferCapableStep, \"deferSite\" | \"deferRefusal\">,\n  exchange: Exchange,\n  signal: DeferSignal,\n): StepOutcome {\n  const site = host.deferSite;\n  if (!site) {\n    throw rcError(\"RC5051\", signal, {\n      message: host.deferRefusal ?? signal.message,\n    });\n  }\n  const { schema, ttl, stepState, meta, callBinding } = signal.request;\n  return {\n    kind: \"defer\",\n    exchange,\n    request: {\n      ...(schema !== undefined ? { schema } : {}),\n      ...(meta !== undefined ? { meta } : {}),\n      ...(callBinding !== undefined ? { callBinding } : {}),\n      ...(ttl !== undefined\n        ? { expiresInMs: parseDuration(ttl, \"defer({ ttl })\") }\n        : {}),\n      ...(stepState !== undefined ? { stepState } : {}),\n      site,\n    },\n  };\n}\n","import type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport {\n  type Exchange,\n  type ExchangeHeaders,\n  OperationType,\n  HeadersKeys,\n  getExchangeContext,\n  getExchangeRoute,\n  getStartedAt,\n  DefaultExchange,\n} from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { SPLIT_PARENT_STORE } from \"./split.ts\";\n\n/**\n * What an aggregator returns: the combined body plus optional headers for\n * the resulting exchange. When `headers` is omitted the engine keeps the\n * base exchange's headers. The engine always rewraps the result onto the\n * parent exchange's identity, so aggregators no longer fabricate a fake\n * `Exchange`; returning a full exchange still works structurally.\n *\n * @template R - Result body type\n */\nexport type AggregateResult<R = unknown> = {\n  body: R;\n  headers?: ExchangeHeaders;\n};\n\n/**\n * Function form of an aggregator: takes an array of exchanges and returns the combined result.\n * Use with `.aggregate(aggregator)`. Default aggregator collects bodies into an array.\n *\n * @template T - Body type of incoming exchanges\n * @template R - Result body type (default T)\n */\nexport type CallableAggregator<T = unknown, R = T> = (\n  exchanges: Exchange<T>[],\n) => Promise<AggregateResult<R>> | AggregateResult<R>;\n\n/**\n * Helper type to extract the element type from an array type, or return the type itself.\n */\ntype ExtractArrayElement<T> = T extends Array<infer U> ? U : T;\n\n/**\n * Helper type to determine the result type after flattening.\n * If T is an array type, extract its element type; otherwise use T itself.\n * The result is always an array of the flattened element type.\n */\ntype FlattenedAggregateResult<T> = T extends Array<infer U> ? U[] : T[];\n\n/**\n * Default aggregator that collects exchange bodies into an array.\n * If any body is an array, all arrays are flattened ONE LEVEL and combined with scalar values.\n * Preserves the metadata from the first exchange.\n *\n * @template T The type of items in the exchanges\n * @param exchanges - Array of exchanges to aggregate\n * @returns Single exchange with array of bodies (flattened if any body was an array)\n *\n * @example\n * // All scalar values: [1, 2, 3]\n * // Mixed arrays and scalars: [1, 2, 3, 4, 5] (arrays flattened, scalars added)\n * // All arrays: [1, 2, 3, 4, 5] (all arrays flattened)\n * // Empty arrays are flattened away: [[], 1, []] → [1]\n * // Only one level deep: [[[1]], 2] → [[1], 2]\n */\nexport const defaultAggregate = <T>(\n  exchanges: Exchange<T>[],\n): AggregateResult<FlattenedAggregateResult<T>> => {\n  if (exchanges.length === 0) {\n    throw rcError(\"RC5002\", undefined, {\n      message: \"Aggregator received empty array of exchanges\",\n      suggestion:\n        \"Ensure at least one exchange is available before aggregation\",\n    });\n  }\n\n  // Check if any body is an array\n  const hasArrayBody = exchanges.some((x) => Array.isArray(x.body));\n\n  // Spread-of-exchange (`{ ...exchanges[0], body }`) used to copy stored\n  // fields like `principal` forward; with the unified state model only\n  // `body` and `headers` are own-properties, so we hand the consuming\n  // `AggregateStep` the explicit shape it needs (body + headers from the\n  // first exchange). Identity, principal, and logger are derived from\n  // headers via getters and reattach automatically when the engine wraps\n  // the aggregate result back into a `DefaultExchange`.\n  if (hasArrayBody) {\n    // Flatten arrays and combine with scalar values\n    const flattened: ExtractArrayElement<T>[] = [];\n    for (const exchange of exchanges) {\n      if (Array.isArray(exchange.body)) {\n        flattened.push(...(exchange.body as ExtractArrayElement<T>[]));\n      } else {\n        flattened.push(exchange.body as ExtractArrayElement<T>);\n      }\n    }\n    return {\n      headers: exchanges[0].headers,\n      body: flattened as FlattenedAggregateResult<T>,\n    };\n  }\n\n  // No arrays found, return array of bodies (original behavior)\n  return {\n    headers: exchanges[0].headers,\n    body: exchanges.map((x) => x.body) as FlattenedAggregateResult<T>,\n  };\n};\n\n/**\n * Aggregator adapter: combines multiple exchanges (e.g. after a split) into one.\n * Used with `.aggregate()`. Default: collect bodies into an array (with one-level flattening).\n *\n * @template T - Body type of incoming exchanges\n * @template R - Result body type\n */\nexport interface Aggregator<T = unknown, R = unknown> extends Adapter {\n  aggregate: CallableAggregator<T, R>;\n}\n\n/**\n * Step that aggregates exchanges from the same split group into a single exchange.\n * Uses the split hierarchy header to collect siblings; then runs the aggregator and continues with the result.\n */\nexport class AggregateStep<T = unknown, R = unknown> implements Step<\n  Aggregator<T, R>\n> {\n  operation: OperationType = OperationType.AGGREGATE;\n  adapter: Aggregator<T, R>;\n  skipStepEvents = true;\n\n  constructor(adapter: Aggregator<T, R> | CallableAggregator<T, R>) {\n    this.adapter =\n      typeof adapter === \"function\" ? { aggregate: adapter } : adapter;\n  }\n\n  async execute(exchange: Exchange<T>, ctx: StepContext): Promise<StepOutcome> {\n    const context = getExchangeContext(exchange);\n    const route = getExchangeRoute(exchange);\n    const routeId =\n      route?.definition.id ??\n      (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n    const stepStartTime = Date.now();\n\n    const splitHierarchy = exchange.headers[\n      HeadersKeys.SPLIT_HIERARCHY\n    ] as string[];\n    const currentGroupId = splitHierarchy?.[splitHierarchy.length - 1];\n\n    // Look up the parent exchange early so step events use its ID\n    const parentMap = context?.getStore(SPLIT_PARENT_STORE) as\n      Map<string, Exchange> | undefined;\n    const parentExchange = currentGroupId\n      ? parentMap?.get(currentGroupId)\n      : undefined;\n    const stepExchangeId = parentExchange?.id ?? exchange.id;\n\n    if (context) {\n      context.emit(\"route:step:started\", {\n        routeId,\n        exchangeId: stepExchangeId,\n        correlationId,\n        operation: this.operation,\n      });\n    }\n\n    // If there's no split hierarchy, just aggregate the single exchange\n    if (!splitHierarchy) {\n      const aggregated = await Promise.resolve(\n        this.adapter.aggregate([exchange]),\n      );\n      const next = DefaultExchange.rewrap<R>(exchange, {\n        body: aggregated.body,\n        headers: aggregated.headers ?? exchange.headers,\n      });\n\n      if (context) {\n        context.emit(\"route:step:completed\", {\n          routeId,\n          exchangeId: next.id,\n          correlationId: next.headers[HeadersKeys.CORRELATION_ID] as string,\n          operation: this.operation,\n          duration: Date.now() - stepStartTime,\n          metadata: { inputCount: 1 },\n        });\n      }\n\n      return { kind: \"continue\", exchange: next };\n    }\n\n    // Join point: atomically consume pending siblings from the same split\n    // group via the executor capability. Only survivors are collected\n    // (children dropped by an intermediate filter are simply absent), so\n    // this never waits on children that will not arrive.\n    const aggregationGroup: Exchange[] = [\n      exchange,\n      ...ctx.takePending((candidate: Exchange) => {\n        const candidateHierarchy = candidate.headers[\n          HeadersKeys.SPLIT_HIERARCHY\n        ] as string[];\n        return candidateHierarchy?.at(-1) === currentGroupId;\n      }),\n    ];\n\n    // Emit route:exchange:completed for each child being aggregated\n    if (context) {\n      for (const child of aggregationGroup) {\n        const childStart = getStartedAt(child) ?? Date.now();\n        context.emit(\"route:exchange:completed\", {\n          routeId,\n          exchangeId: child.id,\n          correlationId: child.headers[HeadersKeys.CORRELATION_ID] as string,\n          duration: Date.now() - childStart,\n        });\n      }\n    }\n\n    let aggregated: AggregateResult<R>;\n    try {\n      aggregated = await Promise.resolve(\n        this.adapter.aggregate(aggregationGroup as Exchange<T>[]),\n      );\n    } finally {\n      // Clean up the stored parent reference even on error\n      if (currentGroupId) {\n        parentMap?.delete(currentGroupId);\n      }\n    }\n\n    // Restore the parent exchange identity by deriving from `parentExchange`\n    // (or the current exchange when no parent was stashed). The new exchange\n    // takes the aggregator's body / headers / principal but the parent's id\n    // and internals (context, route binding) so post-aggregate telemetry\n    // continues to reference the parent's lifecycle.\n    const baseExchange = parentExchange ?? exchange;\n\n    // Compute final headers: aggregator's headers minus the current split\n    // group from the hierarchy (or strip the hierarchy entirely if this was\n    // the outermost split).\n    const remainingHierarchy = splitHierarchy.slice(0, -1);\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars -- destructure to omit\n    const { [HeadersKeys.SPLIT_HIERARCHY]: _stripped, ...restHeaders } =\n      aggregated.headers ?? exchange.headers;\n    const finalHeaders =\n      remainingHierarchy.length > 0\n        ? { ...restHeaders, [HeadersKeys.SPLIT_HIERARCHY]: remainingHierarchy }\n        : restHeaders;\n\n    const next = DefaultExchange.rewrap<R>(baseExchange, {\n      body: aggregated.body,\n      headers: finalHeaders,\n    });\n\n    if (context) {\n      context.emit(\"route:step:completed\", {\n        routeId,\n        exchangeId: next.id,\n        correlationId: next.headers[HeadersKeys.CORRELATION_ID] as string,\n        operation: this.operation,\n        duration: Date.now() - stepStartTime,\n        metadata: { inputCount: aggregationGroup.length },\n      });\n    }\n\n    return { kind: \"continue\", exchange: next };\n  }\n}\n","import {\n  type Adapter,\n  type Step,\n  type StepContext,\n  type StepOutcome,\n  type StepSignalContext,\n  toSignalContext,\n} from \"../types.ts\";\nimport { type Exchange, OperationType, DefaultExchange } from \"../exchange.ts\";\n\n/**\n * Function form of a transformer: maps the body to a new value. Headers are unchanged.\n * Use with `.transform(transformer)`. Prefer over `.process()` when only the body changes.\n * The current exchange is passed as a second, read-only argument so a\n * transformer can derive the new body from context (the principal, headers,\n * correlation id) without dropping to `.process()`. A transformer still\n * returns only the body; to rewrite headers or the principal use `.process()`.\n * The third argument carries the step's {@link StepSignalContext}: when an\n * enclosing `.timeout()` expires, `ctx.signal` aborts, so a transformer doing\n * cancellation-aware IO can forward it (`fetch(url, { signal })`).\n * Adding parameters is backwards compatible: a one-argument\n * `(message) => ...` is still a valid transformer.\n * @template T - Current body type\n * @template R - Result body type (default T)\n */\nexport type CallableTransformer<\n  T = unknown,\n  R = T,\n  Ex extends Exchange<T> = Exchange<T>,\n> = (message: T, exchange: Ex, ctx?: StepSignalContext) => Promise<R> | R;\n\n/**\n * Result of the field-shaping helpers (`keep`, `mask`). Generic over the\n * actual body so it preserves the precise type whether applied to a single\n * record or, element-wise, to an array of records. `T` is the record\n * (element) type in both cases, so grant predicates and mask functions always\n * see one record. Assignable to {@link CallableTransformer}, so it drops\n * straight into `.transform(...)`.\n */\nexport type FieldTransform<T> = <B extends T | T[]>(\n  body: B,\n  exchange?: Exchange<B>,\n) => B;\n\n/**\n * Transformer adapter: body-only conversion. Used with `.transform()`.\n * Headers and exchange metadata are preserved. Use `.process()` to change headers or the full exchange.\n * @template T - Current body type\n * @template R - Result body type\n */\nexport interface Transformer<T = unknown, R = T> extends Adapter {\n  transform: CallableTransformer<T, R>;\n}\n\n/**\n * Creates a transformer from declarative field mappings. Each key in the\n * mapping corresponds to a field in the output type, with a function that\n * extracts the value from the source body.\n * Use with `.transform(mapper({...}))` or the `.map()` sugar method.\n * @template T - Source body type\n * @template R - Result body type\n * @param fieldMappings - Object mapping output field names to extractor functions\n * @returns A callable transformer that maps each field via the provided functions\n * @example\n * ```ts\n * craft()\n *   .from(source)\n *   .transform(mapper<ApiUser, DbUser>({\n *     id: (user) => user.userId,\n *     name: (user) => user.fullName,\n *   }))\n *   .to(dest)\n * ```\n */\nexport function mapper<T, R>(fieldMappings: {\n  [K in keyof R]: (src: T) => R[K];\n}): CallableTransformer<T, R> {\n  return (message: T): R => {\n    const result = {} as R;\n    for (const key in fieldMappings) {\n      const k = key as keyof R;\n      result[k] = fieldMappings[k](message);\n    }\n    return result;\n  };\n}\n\n/**\n * Step that replaces the exchange body with the result of the transformer.\n * Headers and id are unchanged.\n */\nexport class TransformStep<T = unknown, R = T> implements Step<\n  Transformer<T, R>\n> {\n  operation: OperationType = OperationType.TRANSFORM;\n  label?: string;\n  adapter: Transformer<T, R>;\n\n  constructor(adapter: Transformer<T, R> | CallableTransformer<T, R>) {\n    this.adapter =\n      typeof adapter === \"function\" ? { transform: adapter } : adapter;\n  }\n\n  async execute(\n    exchange: Exchange<T>,\n    ctx?: StepContext,\n  ): Promise<StepOutcome> {\n    const newBody = await Promise.resolve(\n      this.adapter.transform(exchange.body, exchange, toSignalContext(ctx)),\n    );\n    return {\n      kind: \"continue\",\n      exchange: DefaultExchange.rewrap<R>(exchange, { body: newBody }),\n    };\n  }\n}\n","/**\n * Dot-path utilities shared by the `mask` and `keep` transform helpers so\n * both address nested fields (\"review.rating\") the same way. All writers are\n * immutable: they clone along the touched path and leave the input untouched,\n * matching the framework's exchange-immutability contract.\n *\n * Reads and writes use own-property semantics and reject the prototype-\n * pollution segments (`__proto__`, `prototype`, `constructor`), so an\n * inherited member like `toString` never counts as a present field and a\n * crafted rule key cannot reach the prototype chain.\n *\n * @internal\n */\n\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction ownKey(obj: Record<string, unknown>, key: string): boolean {\n  return (\n    !FORBIDDEN_SEGMENTS.has(key) &&\n    Object.prototype.hasOwnProperty.call(obj, key)\n  );\n}\n\n/** Read the value at a dot path, or `undefined` if any segment is missing. */\nexport function getPath(obj: unknown, path: string): unknown {\n  let cur: unknown = obj;\n  for (const seg of path.split(\".\")) {\n    if (!isRecord(cur) || !ownKey(cur, seg)) return undefined;\n    cur = cur[seg];\n  }\n  return cur;\n}\n\n/** Whether every segment of a dot path is an own key down the chain. */\nexport function hasPath(obj: unknown, path: string): boolean {\n  let cur: unknown = obj;\n  for (const seg of path.split(\".\")) {\n    if (!isRecord(cur) || !ownKey(cur, seg)) return false;\n    cur = cur[seg];\n  }\n  return true;\n}\n\n/** Return a copy of `obj` with the value at the dot path replaced. */\nexport function setPath<T>(obj: T, path: string, value: unknown): T {\n  const [head, ...rest] = path.split(\".\");\n  if (FORBIDDEN_SEGMENTS.has(head)) return obj;\n  const base: Record<string, unknown> = isRecord(obj) ? obj : {};\n  if (rest.length === 0) {\n    return { ...base, [head]: value } as T;\n  }\n  return { ...base, [head]: setPath(base[head], rest.join(\".\"), value) } as T;\n}\n\n/** Return a copy of `obj` with the value at the dot path removed. */\nexport function deletePath<T>(obj: T, path: string): T {\n  const [head, ...rest] = path.split(\".\");\n  if (!isRecord(obj) || !ownKey(obj, head)) return obj;\n  const clone: Record<string, unknown> = { ...obj };\n  if (rest.length === 0) {\n    delete clone[head];\n  } else {\n    clone[head] = deletePath(clone[head], rest.join(\".\"));\n  }\n  return clone as T;\n}\n\n/** Build a new object containing only the given dot paths from `obj`. */\nexport function pickPaths<T>(obj: T, paths: string[]): T {\n  let out = {} as T;\n  for (const path of paths) {\n    if (hasPath(obj, path)) out = setPath(out, path, getPath(obj, path));\n  }\n  return out;\n}\n","import type { FieldTransform } from \"./transform.ts\";\nimport { getPath, hasPath, setPath } from \"./field-paths.ts\";\n\n/**\n * Obfuscates a single field value. Receives the current value and the whole\n * record it belongs to (typed `R`), and returns the value to show in its\n * place. Pure with respect to identity: `mask` never looks at the principal.\n * `value` stays `unknown` because the value at an arbitrary dot path is not\n * statically known.\n */\nexport type MaskFn<R = unknown> = (value: unknown, record: R) => unknown;\n\n/**\n * Map of dot-path -> obfuscation function. Only the listed fields are\n * rewritten; every other field is left as-is.\n */\nexport type MaskRules<R = unknown> = Record<string, MaskFn<R>>;\n\nfunction maskRecord<R>(record: R, rules: MaskRules<R>): R {\n  let out = record;\n  for (const path of Object.keys(rules)) {\n    if (hasPath(out, path)) {\n      out = setPath(out, path, rules[path](getPath(out, path), record));\n    }\n  }\n  return out;\n}\n\n/**\n * Transform helper that obfuscates field values, regardless of who is asking.\n * Use it for values that should never be shown verbatim at a boundary even to\n * an authorised caller, for example masking an e-mail on a public HTTP\n * response. To remove fields a caller is not allowed to see at all, compose\n * `keep` before `mask`.\n * Returns a {@link FieldTransform}, so drop it straight into\n * `.transform(mask({ ... }))`. Applies to the body when it is a single\n * record, and element-wise when the body is an array of records. For a\n * wrapped collection, mask the inner array:\n * `.transform((b, ex) => ({ ...b, items: mask(rules)(b.items, ex) }))`.\n * @example\n * ```ts\n * craft()\n *   .from(source)\n *   .transform(mask({\n *     email: (v) => maskEmail(String(v)),\n *     \"card.number\": (v) => \"**** \" + String(v).slice(-4),\n *   }))\n *   .to(dest)\n * ```\n */\nexport function mask<T>(rules: MaskRules<T>): FieldTransform<T> {\n  const fn = (body: unknown): unknown => {\n    if (Array.isArray(body)) {\n      return body.map((item) =>\n        item !== null && typeof item === \"object\" && !Array.isArray(item)\n          ? maskRecord(item as T, rules)\n          : item,\n      );\n    }\n    return body !== null && typeof body === \"object\" && !Array.isArray(body)\n      ? maskRecord(body as T, rules)\n      : body;\n  };\n  return fn as unknown as FieldTransform<T>;\n}\n","import type { Exchange } from \"../exchange.ts\";\nimport type { Principal } from \"../auth/types.ts\";\nimport { isAuthentic } from \"../auth/authentic.ts\";\nimport type { FieldTransform } from \"./transform.ts\";\nimport { deletePath, hasPath, pickPaths } from \"./field-paths.ts\";\n\n/**\n * A grant the caller must hold to keep a field. Either a role name matched\n * against `principal.roles`, or a predicate evaluated against the record and\n * the caller's principal. `self` and relationships like \"manages\" are written\n * as predicates; there is no magic string, `admin` is just a role name.\n */\nexport type Grant<T = unknown> =\n  string | ((record: T, principal: Principal | undefined) => boolean);\n\n/**\n * Rule for one field: `true` keeps it for everyone who reaches this step, or a\n * list of grants any one of which keeps it.\n */\nexport type KeepRule<T = unknown> = true | Grant<T>[];\n\n/**\n * Map of dot-path -> {@link KeepRule}.\n */\nexport type KeepRules<T = unknown> = Record<string, KeepRule<T>>;\n\n/**\n * Options for {@link keep}.\n */\nexport interface KeepOptions {\n  /**\n   * `true` (default): strict allowlist. Only fields listed in the rules\n   * survive, each kept when its grant holds; anything not listed is dropped.\n   * Safe by default, a new sensitive field stays hidden until you list it.\n   *\n   * `false`: gate only the listed fields. A listed field is dropped when its\n   * grant fails; every unlisted field passes through untouched.\n   */\n  strict?: boolean;\n}\n\nfunction holds<T>(\n  rule: KeepRule<T>,\n  record: T,\n  principal: Principal | undefined,\n): boolean {\n  if (rule === true) return true;\n  return rule.some((grant) =>\n    typeof grant === \"function\"\n      ? grant(record, principal)\n      : (principal?.roles?.includes(grant) ?? false),\n  );\n}\n\nfunction keepRecord<R>(\n  record: R,\n  rules: KeepRules<R>,\n  principal: Principal | undefined,\n  strict: boolean,\n): R {\n  if (strict) {\n    const allowed: string[] = [];\n    for (const path of Object.keys(rules)) {\n      if (hasPath(record, path) && holds(rules[path], record, principal)) {\n        allowed.push(path);\n      }\n    }\n    return pickPaths(record, allowed);\n  }\n  // Evaluate every rule against the ORIGINAL record (not the progressively\n  // deleted copy) so a predicate grant that reads another field is not\n  // affected by an earlier deletion, and so non-strict agrees with strict.\n  let out = record;\n  for (const path of Object.keys(rules)) {\n    if (hasPath(record, path) && !holds(rules[path], record, principal)) {\n      out = deletePath(out, path);\n    }\n  }\n  return out;\n}\n\n/**\n * Transform helper that keeps fields based on the caller's grants, removing\n * the rest. This is the access-control half of field shaping: a field the\n * caller has no grant for is dropped entirely (compose `mask` after `keep` to\n * obfuscate what remains). Reads the caller from the exchange the transform\n * step now provides. It fails closed: only an authentic principal (one\n * established by a source verifier or `authenticate()`) is trusted; a\n * self-asserted principal header is treated as missing, so role and predicate\n * grants do not pass, matching `authorize()`.\n * Strict by default: only listed fields survive (use `true` to keep a field\n * for any caller). Pass `{ strict: false }` to instead gate only the listed\n * fields and pass everything else through.\n * Returns a {@link FieldTransform}, so use `.transform(keep({ ... }))`. `T` is\n * the record (element) type: applies to the body when it is a single record,\n * element-wise when it is an array of records, preserving the precise type\n * either way. For a wrapped collection, keep the inner array:\n * `.transform((b, ex) => ({ ...b, items: keep(rules)(b.items, ex) }))`.\n * @example\n * ```ts\n * const self = (e: Employee, p) => e.email === p?.email;\n * craft()\n *   .from(source)\n *   .transform(keep({\n *     id: true,\n *     email: true,\n *     yearlyWage: [self, \"hr\"],   // own salary, or the hr role\n *     internalNotes: [\"hr\"],      // hr only, dropped for everyone else\n *   }))\n *   .to(dest)\n * ```\n */\nexport function keep<T>(\n  rules: KeepRules<T>,\n  options: KeepOptions = {},\n): FieldTransform<T> {\n  const strict = options.strict ?? true;\n  const fn = (body: unknown, exchange?: Exchange<unknown>): unknown => {\n    // Trust only an authentic principal (one established by a source verifier\n    // or authenticate()). A self-asserted principal header is treated as\n    // missing, so role and predicate grants fail closed, matching authorize().\n    const raw = exchange?.principal;\n    const principal = isAuthentic(raw) ? raw : undefined;\n    if (Array.isArray(body)) {\n      return body.map((item) =>\n        item !== null && typeof item === \"object\" && !Array.isArray(item)\n          ? keepRecord(item, rules as KeepRules<unknown>, principal, strict)\n          : item,\n      );\n    }\n    return body !== null && typeof body === \"object\" && !Array.isArray(body)\n      ? keepRecord(body, rules as KeepRules<unknown>, principal, strict)\n      : body;\n  };\n  return fn as unknown as FieldTransform<T>;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Adapter, Step, StepOutcome } from \"../types.ts\";\nimport { type Exchange, OperationType, DefaultExchange } from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { validateAgainst } from \"../pipeline/validation.ts\";\n\n/**\n * Callable validator function. Receives the full exchange, returns the\n * validated (possibly coerced) body value. Throws on failure.\n *\n * @template T - Input body type\n * @template R - Output body type (may differ if the validator coerces)\n */\nexport type CallableValidator<\n  T = unknown,\n  R = T,\n  Ex extends Exchange<T> = Exchange<T>,\n> = (exchange: Ex) => R | Promise<R>;\n\n/**\n * Validator adapter: validates the exchange body and returns the validated\n * value. Throws on failure (e.g., RC5002 for schema violations).\n *\n * @template T - Input body type\n * @template R - Output body type\n */\nexport interface Validator<T = unknown, R = T> extends Adapter {\n  validate: CallableValidator<T, R>;\n}\n\n/**\n * Step that validates the exchange body using a Validator adapter.\n * On success the exchange continues with the (possibly coerced) body.\n * On failure the adapter throws and the normal error path handles it\n * (error handler if configured, otherwise route:exchange:failed).\n */\nexport class ValidateStep<T = unknown, R = T> implements Step<Validator<T, R>> {\n  operation: OperationType = OperationType.VALIDATE;\n  label?: string;\n  adapter: Validator<T, R>;\n\n  constructor(adapter: Validator<T, R> | CallableValidator<T, R>) {\n    this.adapter =\n      typeof adapter === \"function\" ? { validate: adapter } : adapter;\n  }\n\n  async execute(exchange: Exchange): Promise<StepOutcome> {\n    const result = await Promise.resolve(\n      this.adapter.validate(exchange as Exchange<T>),\n    );\n    return {\n      kind: \"continue\",\n      exchange: DefaultExchange.rewrap<R>(exchange, { body: result }),\n    };\n  }\n}\n\n/**\n * Creates a Validator adapter from a Standard Schema. On success the\n * validated (possibly coerced) value replaces the exchange body. On\n * failure throws RC5002 with formatted issue details.\n *\n * Use with `.validate(schema(...))` or the `.schema()` sugar method.\n *\n * @param standardSchema - Any Standard Schema v1 implementation (Zod, Valibot, ArkType, etc.)\n * @returns A Validator adapter that throws RC5002 on failure\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * craft()\n *   .from(source)\n *   .validate(schema(z.object({ name: z.string() })))\n *   .to(dest)\n * ```\n */\nexport function schema<S extends StandardSchemaV1>(\n  standardSchema: S,\n): Validator<unknown, StandardSchemaV1.InferOutput<S>> {\n  return {\n    validate: async (exchange) => {\n      const result = await validateAgainst(standardSchema, exchange.body);\n      if (!result.ok) {\n        throw rcError(\"RC5002\", new Error(result.message), {\n          message: `Validation failed: ${result.message}`,\n        });\n      }\n      return result.value;\n    },\n  };\n}\n","import {\n  type Adapter,\n  type Step,\n  getAdapterLabel,\n  type StepOutcome,\n} from \"../types.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  HeadersKeys,\n  getExchangeContext,\n  getExchangeRoute,\n  emitExchangeDropped,\n} from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\n\n/**\n * Returned by a filter predicate to drop an exchange with a reason.\n * The reason is recorded in telemetry and shown in the TUI.\n */\nexport interface FilterDropResult {\n  reason: string;\n}\n\n/**\n * Predicate over the full exchange. Return `true` to keep the exchange,\n * `false` to drop it, or `{ reason: \"...\" }` to drop with an explanation.\n *\n * @template T - Body type of the exchange\n *\n * @example\n * ```ts\n * .filter((ex) => {\n *   if (!ex.body.name) return { reason: \"name is required\" };\n *   if (ex.body.age < 18) return { reason: \"age must be 18 or older\" };\n *   return true;\n * })\n * ```\n */\nexport type CallableFilter<\n  T = unknown,\n  Ex extends Exchange<T> = Exchange<T>,\n> = (\n  exchange: Ex,\n) => Promise<boolean | FilterDropResult> | boolean | FilterDropResult;\n\n/**\n * Filter adapter: keeps or drops the exchange based on a predicate. Used with `.filter()`.\n *\n * @template T - Body type\n */\nexport interface Filter<T = unknown> extends Adapter {\n  filter: CallableFilter<T>;\n}\n\n/**\n * Step that runs a predicate on the exchange. If the predicate returns false, the exchange is dropped (no further steps).\n * If it throws, the error is wrapped as RC5001.\n */\nexport class FilterStep<T = unknown> implements Step<Filter<T>> {\n  operation: OperationType = OperationType.FILTER;\n  label?: string;\n  adapter: Filter<T>;\n  skipStepEvents = true;\n\n  constructor(adapter: Filter<T> | CallableFilter<T>) {\n    this.adapter =\n      typeof adapter === \"function\" ? { filter: adapter } : adapter;\n  }\n\n  async execute(exchange: Exchange<T>): Promise<StepOutcome> {\n    const context = getExchangeContext(exchange);\n    const route = getExchangeRoute(exchange);\n    const routeId =\n      route?.definition.id ??\n      (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n    const adapterLabel = getAdapterLabel(this.adapter);\n    const stepStart = Date.now();\n    const stepLabel = this.label ?? this.operation;\n\n    // Emit route:step:started\n    if (context) {\n      context.emit(\"route:step:started\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: stepLabel,\n        ...(adapterLabel ? { adapter: adapterLabel } : {}),\n      });\n    }\n\n    try {\n      const result = await Promise.resolve(this.adapter.filter(exchange));\n\n      // Determine if the exchange should be dropped and extract the reason.\n      const dropReason = isFilterDrop(result)\n        ? result.reason\n        : result\n          ? undefined\n          : \"filtered\";\n\n      if (dropReason !== undefined) {\n        exchange.logger.debug(\n          {\n            operation: stepLabel,\n            reason: dropReason,\n            ...(adapterLabel ? { adapter: adapterLabel } : {}),\n          },\n          \"Filter rejected exchange\",\n        );\n\n        // Emit route:step:completed first, then route:exchange:dropped\n        context?.emit(\"route:step:completed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          operation: stepLabel,\n          ...(adapterLabel ? { adapter: adapterLabel } : {}),\n          duration: Date.now() - stepStart,\n        });\n\n        emitExchangeDropped(context, {\n          routeId,\n          correlationId,\n          reason: dropReason,\n          exchange,\n        });\n        return { kind: \"drop\" };\n      }\n    } catch (error: unknown) {\n      if (context) {\n        context.emit(\"route:step:failed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          operation: stepLabel,\n          ...(adapterLabel ? { adapter: adapterLabel } : {}),\n          duration: Date.now() - stepStart,\n          error: error instanceof Error ? error.message : String(error),\n        });\n      }\n      throw rcError(\"RC5001\", error, {\n        message: \"Filter predicate threw\",\n      });\n    }\n\n    // Emit route:step:completed for passed exchanges\n    if (context) {\n      context.emit(\"route:step:completed\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: stepLabel,\n        ...(adapterLabel ? { adapter: adapterLabel } : {}),\n        duration: Date.now() - stepStart,\n      });\n    }\n\n    return { kind: \"continue\", exchange };\n  }\n}\n\n/**\n * Type guard for a {@link FilterDropResult} returned by a filter predicate.\n */\nfunction isFilterDrop(\n  value: boolean | FilterDropResult,\n): value is FilterDropResult {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    typeof (value as FilterDropResult).reason === \"string\"\n  );\n}\n","import { type Duration, parseDuration } from \"../shared/duration.ts\";\nimport { rejectStaleOptions } from \"../shared/stale-options.ts\";\nimport type { Adapter, Step, StepOutcome } from \"../types.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  HeadersKeys,\n  getExchangeContext,\n  getExchangeRoute,\n  emitExchangeDropped,\n} from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { RouteScopedController } from \"./route-scoped-controller.ts\";\n\n/**\n * Options for the `.sample()` flow-control operation. Exactly one of\n * `every` (count-based) or `interval` (time-based) must be set; the union\n * makes them mutually exclusive at compile time (passing both, or neither,\n * is a type error), and {@link resolveSampleOptions} re-checks at runtime\n * for JS callers.\n */\nexport type SampleOptions =\n  | {\n      /**\n       * Count-based: pass every Nth exchange and drop the rest, so\n       * `{ every: 5 }` passes the 5th, 10th, 15th, ... exchange. Must be a\n       * finite integer >= 1.\n       */\n      every: number;\n      interval?: never;\n    }\n  | {\n      /**\n       * Time-based: pass the first exchange seen in each `interval` window\n       * and drop the rest until the window elapses. Must be at least 1ms.\n       */\n      interval: Duration;\n      every?: never;\n    };\n\n/**\n * {@link SampleOptions} with the sampling mode resolved and validated. A\n * discriminated union, so narrowing on `mode` proves which numeric field is\n * present (no non-null assertions at the use site).\n *\n * @internal\n */\nexport type ResolvedSampleOptions =\n  { mode: \"count\"; every: number } | { mode: \"interval\"; intervalMs: number };\n\n/**\n * Validate user-supplied {@link SampleOptions} into a\n * {@link ResolvedSampleOptions}. Rejects at build time (RC5003) so a\n * mis-specified sampler fails when the route is built rather than silently\n * passing or dropping every exchange at runtime.\n *\n * @internal\n */\nexport function resolveSampleOptions(\n  options: SampleOptions,\n): ResolvedSampleOptions {\n  // The XOR is already a compile-time error for typed callers (the union's\n  // `?: never` arms); these runtime checks defend JS callers and widened\n  // values that bypass the types. One shared message so the two sites cannot\n  // drift.\n  const exclusiveMessage =\n    \"sample() requires exactly one of `every` or `interval` (they are mutually exclusive).\";\n\n  // Guard before destructuring so a non-object (a JS caller passing nothing,\n  // null, or a primitive) yields the coded RC5003 rather than a bare TypeError.\n  if (typeof options !== \"object\" || options === null) {\n    throw rcError(\"RC5003\", undefined, { message: exclusiveMessage });\n  }\n\n  rejectStaleOptions(options, \"sample\");\n\n  const { every, interval } = options;\n\n  if (every !== undefined && interval !== undefined) {\n    throw rcError(\"RC5003\", undefined, { message: exclusiveMessage });\n  }\n\n  if (every !== undefined) {\n    // Safe integer, not just integer: above 2^53 the per-route counter loses\n    // precision and can never reach `every`, freezing the sampler into a\n    // permanent drop. Fail such a config at build time instead.\n    if (!Number.isSafeInteger(every) || every < 1) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `sample({ every }) must be a safe integer >= 1, got ${String(every)}.`,\n      });\n    }\n    return { mode: \"count\", every };\n  }\n\n  if (interval !== undefined) {\n    return {\n      mode: \"interval\",\n      intervalMs: parseDuration(interval, \"sample({ interval })\"),\n    };\n  }\n\n  throw rcError(\"RC5003\", undefined, { message: exclusiveMessage });\n}\n\n/**\n * Per-route sampler state. Count mode keeps a running counter; interval\n * mode keeps the timestamp of the last admitted exchange. One instance per\n * Route (see {@link SampleController}), never one per exchange.\n *\n * @internal\n */\nclass SampleState {\n  count = 0;\n  lastPassedAt: number | undefined;\n}\n\n/**\n * Owns the sampler state for one `.sample()` across every Route the step\n * runs in (see {@link RouteScopedController}): each Route gets its own\n * counter / window so contexts cannot cross-sample each other.\n *\n * @internal\n */\nclass SampleController extends RouteScopedController<SampleState> {\n  protected createState(): SampleState {\n    return new SampleState();\n  }\n}\n\n/** Marker adapter for the sample step; carries no configuration. */\nexport interface SampleAdapter extends Adapter {\n  readonly adapterId: \"routecraft.operation.sample\";\n}\n\n/**\n * Step that samples exchanges by count (`every`) or time window\n * (`interval`), passing the admitted ones and dropping the rest. A drop\n * is silent (no error), exactly like a `filter` predicate returning false:\n * it emits `route:operation:sample:dropped` and `route:exchange:dropped`\n * (reason `\"sampled\"`) so telemetry and the TUI can count it.\n *\n * Sampler state is per-route (see {@link SampleController}), so every\n * exchange on a given Route shares one counter / window while distinct\n * Routes stay isolated.\n */\nexport class SampleStep implements Step<SampleAdapter> {\n  operation: OperationType = OperationType.SAMPLE;\n  label?: string;\n  adapter: SampleAdapter = { adapterId: \"routecraft.operation.sample\" };\n  skipStepEvents = true;\n\n  readonly #options: ResolvedSampleOptions;\n  readonly #controller = new SampleController();\n\n  constructor(options: SampleOptions) {\n    this.#options = resolveSampleOptions(options);\n  }\n\n  async execute(exchange: Exchange): Promise<StepOutcome> {\n    const context = getExchangeContext(exchange);\n    const route = getExchangeRoute(exchange);\n    const routeId =\n      route?.definition.id ??\n      (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n    const stepLabel = this.label ?? this.operation;\n    const stepStart = Date.now();\n    const { mode } = this.#options;\n\n    if (context) {\n      context.emit(\"route:step:started\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: stepLabel,\n      });\n    }\n\n    const state = this.#controller.stateFor(route);\n    const pass = this.#shouldPass(state);\n\n    if (context) {\n      context.emit(\"route:step:completed\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: stepLabel,\n        duration: Date.now() - stepStart,\n      });\n    }\n\n    if (!pass) {\n      context?.emit(\"route:operation:sample:dropped\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        mode,\n      });\n      emitExchangeDropped(context, {\n        routeId,\n        correlationId,\n        reason: \"sampled\",\n        exchange,\n      });\n      return { kind: \"drop\" };\n    }\n\n    context?.emit(\"route:operation:sample:passed\", {\n      routeId,\n      exchangeId: exchange.id,\n      correlationId,\n      mode,\n    });\n    return { kind: \"continue\", exchange };\n  }\n\n  /** Advance the sampler state and decide whether this exchange passes. */\n  #shouldPass(state: SampleState): boolean {\n    const options = this.#options;\n    if (options.mode === \"count\") {\n      // Count up to `every`, then reset and pass. Resetting (rather than an\n      // ever-growing counter with a modulo) keeps the count bounded, so a\n      // long-lived high-frequency route never drifts past Number.MAX_SAFE_INTEGER\n      // where `count + 1 === count` would freeze the sampler.\n      state.count += 1;\n      if (state.count >= options.every) {\n        state.count = 0;\n        return true;\n      }\n      return false;\n    }\n    const now = Date.now();\n    if (\n      state.lastPassedAt === undefined ||\n      now - state.lastPassedAt >= options.intervalMs\n    ) {\n      state.lastPassedAt = now;\n      return true;\n    }\n    return false;\n  }\n}\n","import { createHash } from \"node:crypto\";\nimport { LRUCache } from \"lru-cache\";\nimport {\n  type Adapter,\n  type Step,\n  type StepOutcome,\n  forRoute,\n} from \"../types.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  HeadersKeys,\n  getExchangeContext,\n  getExchangeRoute,\n  emitExchangeDropped,\n} from \"../exchange.ts\";\nimport { type Duration, parseDuration } from \"../shared/duration.ts\";\nimport { rcError } from \"../error.ts\";\nimport { isRoutecraftError } from \"../brand.ts\";\nimport type { CraftContext } from \"../context.ts\";\nimport type { Route } from \"../route.ts\";\nimport { hashExchangeBody } from \"./hash-body.ts\";\nimport { principalIdentity } from \"./principal-identity.ts\";\nimport { DEFAULT_MAX_KEYS, validateMaxKeys } from \"./max-keys.ts\";\nimport { RouteScopedController } from \"./route-scoped-controller.ts\";\n\n/**\n * Options for the `.dedupe()` flow-control operation.\n */\nexport interface DedupeOptions {\n  /**\n   * Derive the deduplication key from the exchange. The returned string is\n   * the identity two exchanges are compared on.\n   *\n   * When omitted, the key is a SHA-256 over the principal's `issuer` and\n   * `subject` plus those of every `actor` hop when the exchange carries\n   * one, and a SHA-256 of `JSON.stringify(body)` (see\n   * {@link hashExchangeBody}). Two callers with different identities\n   * sending the same body are therefore not duplicates of each other, and\n   * neither are two delegates acting for the same subject. Identity means\n   * issuer and subject per hop: exchanges with no principal all share one\n   * identity, and principals differing only in `clientId` or `grantId`\n   * count as the same caller. The route is not part of the\n   * key: each `.dedupe()` already keeps its own seen-key set per route.\n   * The default needs a body: an `undefined` body (a bodiless `http()`\n   * GET) or one `JSON.stringify` cannot represent fails with `RC5033`.\n   *\n   * A custom `key` is used VERBATIM: nothing is added to it, so every\n   * caller returning the same key dedupes against every other. When\n   * callers must not dedupe each other, put the caller's identity\n   * (`ex.principal?.issuer` and `subject`, plus `ex.principal?.actor` on a\n   * route that admits delegation) in the key. Supply `key` as well when\n   * the body is not JSON-serialisable or when a stable identity lives in a\n   * header (a file path, an event id) that should survive body changes.\n   */\n  key?: (exchange: Exchange) => string;\n  /**\n   * Time to live in milliseconds for a committed key. The TTL is a sliding\n   * (inactivity) window, not a fixed lifetime from commit: each duplicate hit\n   * refreshes it, so an actively-arriving duplicate stream keeps being\n   * suppressed and a key only expires once it has been quiet for `ttl`. After\n   * expiry the next exchange with that key is treated as new (passes again).\n   * When omitted, committed keys are retained until LRU eviction at `maxKeys`.\n   *\n   * This is the memory bound for long-running routes: without a `ttl`, only\n   * `maxKeys` caps the committed set, and an evicted key's next occurrence\n   * is no longer recognised as a duplicate.\n   */\n  ttl?: Duration;\n  /**\n   * Maximum number of committed keys retained per route. The committed set\n   * is an LRU keyed by recency of use (a duplicate hit counts as a use, not\n   * just the original commit), so memory stays bounded even with an unbounded\n   * key space: the least-recently-seen key is evicted, and its next\n   * occurrence passes as new. Default `10_000`.\n   */\n  maxKeys?: number;\n}\n\n/**\n * {@link DedupeOptions} with every field resolved and validated.\n *\n * @internal\n */\nexport interface ResolvedDedupeOptions {\n  key: (exchange: Exchange) => string;\n  ttl: number | undefined;\n  maxKeys: number;\n}\n\n/**\n * Validate user-supplied {@link DedupeOptions} into a\n * {@link ResolvedDedupeOptions}, filling defaults: the principal-and-body\n * hasher for `key`, no TTL, and a `maxKeys` ceiling of 10_000. Rejects at\n * build time (RC5003) so a typo fails when the route is built.\n *\n * @internal\n */\nexport function resolveDedupeOptions(\n  options: DedupeOptions = {},\n): ResolvedDedupeOptions {\n  const { maxKeys = DEFAULT_MAX_KEYS } = options;\n  const ttl =\n    options.ttl === undefined\n      ? undefined\n      : parseDuration(options.ttl, \"dedupe({ ttl })\");\n  // Upper-bound `maxKeys`: the committed-key LRU pre-allocates index arrays\n  // sized to `max` at construction, so an \"effectively unlimited\" value\n  // would OOM the process the moment the dedupe state is built.\n  validateMaxKeys(\"dedupe\", maxKeys);\n\n  return {\n    key: options.key ?? defaultDedupeKey,\n    ttl,\n    maxKeys,\n  };\n}\n\n/**\n * The default dedupe key: a SHA-256 over the JSON tuple\n * `[principalChain | null, bodyHash]`, where `principalChain` is\n * {@link principalIdentity}. Dedupe state is per step and per route, so\n * the route and the step's position need not be in the key the way they\n * are for `.cache()`, whose provider is shared.\n *\n * @throws RC5033 when the body is `undefined` (nothing to key on) or is\n *   not JSON-serialisable.\n * @internal\n */\nfunction defaultDedupeKey(exchange: Exchange<unknown>): string {\n  if (exchange.body === undefined) {\n    throw rcError(\"RC5033\", undefined, {\n      message:\n        \"Default dedupe key has nothing to key on: the exchange body is undefined. \" +\n        \"A bodiless request such as an http() GET carries its input in the routecraft.http.params and \" +\n        \"routecraft.http.query headers, which the default key does not read. Supply a key, e.g. \" +\n        \"dedupe({ key: (ex) => JSON.stringify([ex.principal?.issuer, ex.principal?.subject, \" +\n        \"ex.headers['routecraft.http.params'], ex.headers['routecraft.http.query']]) }). \" +\n        \"A custom key is used verbatim: drop the principal only when callers may dedupe each other, \" +\n        \"and on a route that admits delegation add each ex.principal.actor hop as well.\",\n    });\n  }\n  let bodyHash: string;\n  try {\n    bodyHash = hashExchangeBody(exchange.body);\n  } catch (err) {\n    throw rcError(\"RC5033\", err, {\n      message:\n        \"Default dedupe key derivation failed: the exchange body is not JSON-serialisable. \" +\n        \"Supply an explicit `key` function in dedupe({ key: ... }).\",\n    });\n  }\n  const identity = JSON.stringify([\n    principalIdentity(exchange.principal),\n    bodyHash,\n  ]);\n  return createHash(\"sha256\").update(identity).digest(\"hex\");\n}\n\n/**\n * Per-route dedupe state implementing the reserve / commit / release\n * protocol. A key is reserved the moment an exchange enters dedupe and\n * stays reserved until that exchange reaches a terminal route event:\n *\n * - `route:exchange:completed` -> commit (the input was handled cleanly,\n *   so future occurrences are duplicates).\n * - `route:exchange:dropped` / `route:exchange:failed` -> release (the input\n *   was not successfully handled, so a re-send may try again).\n *\n * A key that is reserved OR committed is a duplicate. Reservation gives\n * single-flight behaviour: a second exchange with the same key that arrives\n * while the first is still in flight is dropped without waiting. One\n * instance per Route (see {@link DedupeController}), never one per exchange.\n *\n * @internal\n */\nclass DedupeState {\n  /** Committed keys, LRU- and (optionally) TTL-bounded. */\n  readonly #committed: LRUCache<string, true>;\n  /** Keys reserved by an in-flight exchange (single-flight gate). */\n  readonly #reserved = new Set<string>();\n  /** Maps a reserving exchange's id to the key it holds, for commit/release. */\n  readonly #pending = new Map<string, string>();\n  #subscribed = false;\n\n  constructor(options: ResolvedDedupeOptions) {\n    this.#committed = new LRUCache<string, true>({\n      max: options.maxKeys,\n      ...(options.ttl !== undefined ? { ttl: options.ttl } : {}),\n      // Duplicate detection reads via `has()`; refresh recency (and TTL) on\n      // a hit so a frequently-seen key is not LRU-evicted ahead of colder\n      // keys and a sliding TTL keeps suppressing an actively-arriving\n      // duplicate stream.\n      updateAgeOnHas: true,\n    });\n  }\n\n  /** A key already reserved by an in-flight exchange or committed is a duplicate. */\n  isDuplicate(key: string): boolean {\n    return this.#reserved.has(key) || this.#committed.has(key);\n  }\n\n  /** Reserve `key` for `exchangeId` (single-flight gate). */\n  reserve(key: string, exchangeId: string): void {\n    this.#reserved.add(key);\n    this.#pending.set(exchangeId, key);\n  }\n\n  /** Terminal success: promote the reservation to a committed key. */\n  commit(exchangeId: string): void {\n    const key = this.#pending.get(exchangeId);\n    if (key === undefined) return;\n    this.#pending.delete(exchangeId);\n    this.#reserved.delete(key);\n    this.#committed.set(key, true);\n  }\n\n  /**\n   * Terminal failure or drop: drop the reservation without committing, so a\n   * re-send may try again. A drop is treated like a failure here on purpose:\n   * an exchange that dedupe let through but a later step discarded (a filter\n   * rejection, a halt) was not actually handled, so committing its key would\n   * permanently suppress a legitimate re-send. Only a clean completion\n   * commits.\n   */\n  release(exchangeId: string): void {\n    const key = this.#pending.get(exchangeId);\n    if (key === undefined) return;\n    this.#pending.delete(exchangeId);\n    this.#reserved.delete(key);\n  }\n\n  /**\n   * Subscribe the commit / release hooks to the route's terminal exchange\n   * events exactly once. The reservation pattern needs to know when an\n   * exchange finished the whole pipeline, which the exchange-lifecycle\n   * events report; `forRoute` scopes them to this route. A clean completion\n   * commits; a failure or a drop releases. Subscriptions are torn down when\n   * the route aborts (and the state is re-armed) so they do not accumulate\n   * across route restarts on a shared context.\n   */\n  ensureSubscribed(\n    context: CraftContext,\n    routeId: string,\n    route: Route | undefined,\n  ): void {\n    if (this.#subscribed) return;\n    this.#subscribed = true;\n\n    const offs = [\n      context.on(\n        \"route:exchange:completed\",\n        forRoute(routeId, ({ details }) => this.commit(details.exchangeId)),\n      ),\n      context.on(\n        \"route:exchange:dropped\",\n        forRoute(routeId, ({ details }) => this.release(details.exchangeId)),\n      ),\n      context.on(\n        \"route:exchange:failed\",\n        forRoute(routeId, ({ details }) => this.release(details.exchangeId)),\n      ),\n    ];\n\n    if (route) {\n      const cleanup = (): void => {\n        for (const off of offs) off();\n        // Re-arm: a fresh run of this route (after a restart on a shared\n        // context) re-subscribes rather than running with dead listeners.\n        this.#subscribed = false;\n        this.#reserved.clear();\n        this.#pending.clear();\n      };\n      if (route.intakeSignal.aborted) cleanup();\n      else\n        route.intakeSignal.addEventListener(\"abort\", cleanup, { once: true });\n    }\n  }\n}\n\n/**\n * Owns the dedupe state for one `.dedupe()` across every Route the step\n * runs in (see {@link RouteScopedController}): each Route gets its own\n * seen-key set so contexts cannot suppress each other's exchanges.\n *\n * @internal\n */\nclass DedupeController extends RouteScopedController<DedupeState> {\n  readonly #options: ResolvedDedupeOptions;\n\n  constructor(options: ResolvedDedupeOptions) {\n    super();\n    this.#options = options;\n  }\n\n  protected createState(): DedupeState {\n    return new DedupeState(this.#options);\n  }\n}\n\n/** Marker adapter for the dedupe step; carries no configuration. */\nexport interface DedupeAdapter extends Adapter {\n  readonly adapterId: \"routecraft.operation.dedupe\";\n}\n\n/**\n * Step that suppresses duplicate exchanges by a derived key. The first time\n * a key is seen it is reserved and the exchange continues; a subsequent\n * exchange whose key is still reserved (in flight) or already committed\n * (handled) is dropped silently, exactly like a `filter` returning false.\n *\n * Reservation semantics give single-flight behaviour and correct retries:\n * the key is committed only when the exchange completes the route cleanly\n * (`route:exchange:completed`) and released when it fails or is dropped\n * (`route:exchange:failed` / `:dropped`), so an input that was not actually\n * handled is not permanently suppressed. State is in-memory and per-route\n * (see {@link DedupeController}); a cross-instance provider is a future\n * addition.\n *\n * Emits `route:operation:dedupe:pass` when a key is reserved and\n * `route:operation:dedupe:duplicate` (plus `route:exchange:dropped`, reason\n * `\"duplicate\"`) when one is suppressed.\n *\n * Known limitation: the commit/release decision is keyed on the entering\n * exchange's terminal event, so placing `.dedupe()` before a `split` (or\n * other fan-out) whose children fail still commits the parent's key (the\n * parent completes even when children fail), suppressing a retriable\n * re-send. Place `.dedupe()` after a fan-out until lineage-aware settlement\n * lands (tracked as a follow-up).\n */\nexport class DedupeStep implements Step<DedupeAdapter> {\n  operation: OperationType = OperationType.DEDUPE;\n  label?: string;\n  adapter: DedupeAdapter = { adapterId: \"routecraft.operation.dedupe\" };\n  skipStepEvents = true;\n\n  readonly #options: ResolvedDedupeOptions;\n  readonly #controller: DedupeController;\n\n  constructor(options: DedupeOptions = {}) {\n    this.#options = resolveDedupeOptions(options);\n    this.#controller = new DedupeController(this.#options);\n  }\n\n  async execute(exchange: Exchange): Promise<StepOutcome> {\n    const context = getExchangeContext(exchange);\n    const route = getExchangeRoute(exchange);\n    const routeId =\n      route?.definition.id ??\n      (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n    const stepLabel = this.label ?? this.operation;\n    const stepStart = Date.now();\n\n    if (context) {\n      context.emit(\"route:step:started\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: stepLabel,\n      });\n    }\n\n    let key: string;\n    try {\n      const derived = this.#options.key(exchange);\n      // Defend JS callers and widened types: `key` is typed to return a\n      // string, but a non-string return would corrupt the identity used as\n      // the committed-key and the `key: string` event contract. Treat it as a\n      // coded derivation failure, same as a throwing `key`.\n      if (typeof derived !== \"string\") {\n        throw rcError(\"RC5033\", undefined, {\n          message: `dedupe({ key }) for \"${stepLabel}\" must return a string, got ${typeof derived}`,\n        });\n      }\n      key = derived;\n    } catch (err) {\n      if (context) {\n        context.emit(\"route:step:failed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          operation: stepLabel,\n          duration: Date.now() - stepStart,\n          error: err instanceof Error ? err.message : String(err),\n        });\n      }\n      // Surface a coded error for a throwing user `key`, mirroring the\n      // default-key path (RC5033) and cache's RC5029, rather than leaking a\n      // bare throw. The default-key deriver already throws RC5033.\n      throw isRoutecraftError(err)\n        ? err\n        : rcError(\"RC5033\", err, {\n            message: `dedupe({ key }) for \"${stepLabel}\" threw while deriving the key`,\n          });\n    }\n\n    const state = this.#controller.stateFor(route);\n    // Wire commit/release to the route's terminal events the first time we\n    // run; safe to call on every exchange (it no-ops after the first).\n    if (route && context) state.ensureSubscribed(context, routeId, route);\n\n    // Reserve only when bound to a route: the reservation is released by a\n    // terminal exchange event scoped to the route (and torn down on the\n    // route's abort signal), neither of which exists on the route-less\n    // synthetic/unit path, where reserving would leak the key and the\n    // listeners forever. Without a route dedupe degrades to pass-through.\n    const duplicate = state.isDuplicate(key);\n    if (!duplicate && route && context) state.reserve(key, exchange.id);\n\n    if (context) {\n      context.emit(\"route:step:completed\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: stepLabel,\n        duration: Date.now() - stepStart,\n      });\n    }\n\n    if (duplicate) {\n      context?.emit(\"route:operation:dedupe:duplicate\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        key,\n      });\n      emitExchangeDropped(context, {\n        routeId,\n        correlationId,\n        reason: \"duplicate\",\n        exchange,\n      });\n      return { kind: \"drop\" };\n    }\n\n    context?.emit(\"route:operation:dedupe:pass\", {\n      routeId,\n      exchangeId: exchange.id,\n      correlationId,\n      key,\n    });\n    return { kind: \"continue\", exchange };\n  }\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Derive a stable SHA-256 hex digest from an exchange body by hashing its\n * JSON serialisation. The default `.dedupe()` key hashes it together with\n * the principal, and the default `.cache()` key with the route and\n * principal, so the two operations agree on what \"the same body\" means.\n *\n * Works for JSON-shaped bodies: primitives, arrays, and plain objects with\n * string keys. It does NOT canonicalise object key order, so two objects\n * with the same entries in a different order hash differently; supply an\n * explicit `key` when a stable identity must survive key reordering.\n *\n * Throws a plain `Error` when the body is not JSON-serialisable: a\n * top-level `undefined`, function, or symbol (which `JSON.stringify`\n * renders as `undefined`), or a `BigInt` / circular reference (which it\n * throws on). Callers translate the throw into their operation-specific\n * `RoutecraftError` with an actionable message, so the failure points the\n * user at the right `key` option.\n *\n * Performance: this serialises and hashes the body on every call. For hot\n * paths or large bodies, supply a `key` that returns a stable identifier\n * already to hand (an id field, a content hash in a header) to avoid the\n * re-serialise and re-hash.\n *\n * @internal\n */\nexport function hashExchangeBody(body: unknown): string {\n  const stringified = JSON.stringify(body);\n  if (stringified === undefined) {\n    throw new Error(\n      \"Exchange body is not JSON-serialisable (top-level undefined, function, or symbol).\",\n    );\n  }\n  return createHash(\"sha256\").update(stringified).digest(\"hex\");\n}\n","import type { Principal } from \"../auth/types.ts\";\n\n/**\n * Who is asking, as a JSON-encodable chain: see {@link principalIdentity}.\n *\n * @internal\n */\nexport type PrincipalIdentity = Array<[string | null, string] | number>;\n\n/**\n * `[issuer, subject]` for the principal and then for every `actor` hop,\n * outermost first, or `null` when the exchange carries no principal. The\n * default `.cache()` and `.dedupe()` keys both include it, so two callers\n * sending the same body never share an entry or dedupe each other. The\n * actor chain is part of who is asking: a delegate acting for the same\n * subject can be authorized differently, so it is kept apart from another\n * delegate.\n *\n * A hand-assembled self-referential chain ends in the index of the hop it\n * loops back to, so it neither spins nor keys like the same chain without\n * the loop.\n *\n * @internal\n */\nexport function principalIdentity(\n  principal: Principal | undefined,\n): PrincipalIdentity | null {\n  if (!principal) return null;\n  const chain: PrincipalIdentity = [];\n  const seen = new Map<Principal, number>();\n  for (let hop: Principal | undefined = principal; hop; hop = hop.actor) {\n    const loop = seen.get(hop);\n    if (loop !== undefined) {\n      chain.push(loop);\n      break;\n    }\n    seen.set(hop, chain.length);\n    chain.push([hop.issuer ?? null, hop.subject]);\n  }\n  return chain;\n}\n","import type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  HeadersKeys,\n  cloneExchange,\n  getExchangeRoute,\n  markDropped,\n  emitExchangeDropped,\n} from \"../exchange.ts\";\nimport { wrapperEventScope } from \"./event-scope.ts\";\nimport { type Duration, parseDuration } from \"../shared/duration.ts\";\nimport { rejectStaleOptions } from \"../shared/stale-options.ts\";\nimport { rcError } from \"../error.ts\";\nimport { RouteScopedController } from \"./route-scoped-controller.ts\";\n\n/**\n * Options for the `.debounce()` flow-control operation.\n */\nexport interface DebounceOptions<In = unknown> {\n  /**\n   * Quiet window. An exchange is released only after `wait` has elapsed with\n   * no newer arrival in its group; each new arrival resets the window and\n   * supersedes (drops) the one being held. Must be at least 1ms.\n   */\n  wait: Duration;\n  /**\n   * Partition selector: exchanges sharing a key are debounced independently\n   * (for example one quiet window per file path). When omitted, the whole\n   * route shares a single window.\n   */\n  key?: (exchange: Exchange<In>) => string;\n  /**\n   * Upper bound on how long an exchange may be held from the START of its\n   * burst, guaranteeing eventual release under continuous activity\n   * (otherwise a steady stream of arrivals could reset `wait` forever and\n   * starve the trailing edge). Measured from the first arrival in the burst\n   * and NOT reset by later arrivals. Must be `>= wait` when set.\n   */\n  maxWait?: Duration;\n}\n\n/**\n * {@link DebounceOptions} with every field resolved and validated.\n *\n * @internal\n */\nexport interface ResolvedDebounceOptions {\n  waitMs: number;\n  key: ((exchange: Exchange) => string) | undefined;\n  maxWaitMs: number | undefined;\n}\n\n/**\n * Validate user-supplied {@link DebounceOptions} into a\n * {@link ResolvedDebounceOptions}. Rejects at build time (RC5003) so a\n * mis-specified window fails when the route is built rather than at runtime.\n *\n * @internal\n */\nexport function resolveDebounceOptions(\n  options: DebounceOptions<unknown>,\n): ResolvedDebounceOptions {\n  if (typeof options !== \"object\" || options === null) {\n    throw rcError(\"RC5003\", undefined, {\n      message: \"debounce() requires an options object with a `wait`.\",\n    });\n  }\n  rejectStaleOptions(options, \"debounce\");\n  const { wait, maxWait, key } = options;\n  // Defend JS callers and widened values: a non-function `key` would pass\n  // the build and then throw a raw TypeError on every exchange. Mirrors the\n  // sticky-key validation in dispatch.\n  if (key !== undefined && typeof key !== \"function\") {\n    throw rcError(\"RC5003\", undefined, {\n      message: `debounce({ key }) must be a function deriving the partition key, got ${typeof key}.`,\n    });\n  }\n  const waitMs = parseDuration(wait, \"debounce({ wait })\");\n  const maxWaitMs =\n    maxWait === undefined\n      ? undefined\n      : parseDuration(maxWait, \"debounce({ maxWait })\");\n  if (maxWaitMs !== undefined && maxWaitMs < waitMs) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `debounce({ maxWait }) must be >= wait (${waitMs}ms), got ${maxWaitMs}ms.`,\n    });\n  }\n  return {\n    waitMs,\n    key: key as ((exchange: Exchange) => string) | undefined,\n    maxWaitMs,\n  };\n}\n\n/**\n * Why a held exchange was released. `\"quiet\"`: the `wait` window closed;\n * `\"maxWait\"`: the `maxWait` cap fired during continuous activity;\n * `\"flush\"`: a drain / shutdown released it early.\n *\n * @internal\n */\ntype ReleaseReason = \"quiet\" | \"maxWait\" | \"flush\";\n\n/**\n * One held burst for a single key: the exchange currently being held, its\n * pacing timers, and the deferred that keeps the route's `drain()` waiting\n * until the burst releases.\n *\n * @internal\n */\ninterface PendingHold {\n  /** The most recent arrival in the burst (the one that will be released). */\n  exchange: Exchange;\n  /** Fires `waitMs` after the latest arrival; reset on each new arrival. */\n  waitTimer: ReturnType<typeof setTimeout>;\n  /** Fires `maxWaitMs` after the FIRST arrival; never reset. */\n  maxTimer: ReturnType<typeof setTimeout> | undefined;\n  /** Resolves the tracked in-flight promise once the burst releases. */\n  settle: () => void;\n}\n\n/**\n * Per-route debounce state: the captured downstream runner (shared across the\n * route's exchanges) and the per-key holds. One instance per Route (see\n * {@link DebounceController}), never one per exchange.\n *\n * @internal\n */\nclass DebounceState {\n  /** Runs a released exchange through the steps after debounce; captured once. */\n  runner: ((exchange: Exchange) => Promise<{ failed: boolean }>) | undefined;\n  /** Active holds keyed by partition key (`\"\"` when no `key` selector). */\n  readonly pending = new Map<string, PendingHold>();\n  /** Whether the drain / abort flush hooks have been wired for this route. */\n  flushRegistered = false;\n}\n\n/**\n * Owns the debounce state for one `.debounce()` across every Route the step\n * runs in (see {@link RouteScopedController}).\n *\n * @internal\n */\nclass DebounceController extends RouteScopedController<DebounceState> {\n  protected createState(): DebounceState {\n    return new DebounceState();\n  }\n}\n\n/** Marker adapter for the debounce step; carries no configuration. */\nexport interface DebounceAdapter extends Adapter {\n  readonly adapterId: \"routecraft.operation.debounce\";\n}\n\n/**\n * Step that suppresses bursts of exchanges, releasing only the LAST one in a\n * burst after a quiet period. The archetypal use is collapsing a flurry of\n * file-change or search-as-you-type events down to their final state.\n *\n * Each arrival is held (not passed downstream) and resets a `waitMs` quiet\n * timer; a newer arrival in the same group supersedes and drops the one being\n * held. When the timer finally fires (or the optional `maxWait` cap elapses\n * from the burst's start, guaranteeing progress under continuous activity),\n * the held exchange is released through the steps that follow `.debounce()`.\n * An optional `key` selector debounces independently per group.\n *\n * This is the only operation that breaks the \"process each exchange\n * immediately\" model: it holds an exchange OUTSIDE the pipeline queue and\n * re-runs it later via the executor's captured downstream continuation, so a\n * released exchange runs the post-debounce steps as a fresh exchange (new id,\n * preserved correlation id) with its own `route:exchange:started` / `:completed`\n * lifecycle. Because the hold lives outside the queue, a pending exchange is\n * flushed on `drain()` / shutdown rather than being lost.\n *\n * Emits `route:operation:debounce:held` (arrival held / timer reset),\n * `route:operation:debounce:dropped` (a held exchange superseded), and\n * `route:operation:debounce:released` (the trailing exchange released).\n */\nexport class DebounceStep<In = unknown> implements Step<DebounceAdapter> {\n  operation: OperationType = OperationType.DEBOUNCE;\n  label?: string;\n  adapter: DebounceAdapter = { adapterId: \"routecraft.operation.debounce\" };\n  skipStepEvents = true;\n\n  readonly #options: ResolvedDebounceOptions;\n  readonly #controller = new DebounceController();\n\n  constructor(options: DebounceOptions<In>) {\n    this.#options = resolveDebounceOptions(options as DebounceOptions<unknown>);\n  }\n\n  async execute(\n    exchange: Exchange<In>,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const { route, context, routeId, correlationId, stepLabel } =\n      wrapperEventScope(exchange, this);\n    const stepStart = Date.now();\n\n    // Without a context there is nowhere to emit or run downstream; pass the\n    // exchange through unchanged (defensive, mirrors the other operations).\n    if (!context) {\n      return { kind: \"continue\", exchange };\n    }\n\n    context.emit(\"route:step:started\", {\n      routeId,\n      exchangeId: exchange.id,\n      correlationId,\n      operation: stepLabel,\n    });\n\n    const state = this.#controller.stateFor(route);\n    // Capture the downstream continuation once: debounce sits at a fixed\n    // pipeline position, so the steps after it are the same for every arrival.\n    state.runner ??= ctx.captureDownstream();\n    this.#ensureFlushHooks(state, route);\n\n    const key = this.#options.key ? this.#options.key(exchange) : \"\";\n    const keyField = this.#options.key ? { key } : {};\n\n    // The arrival is absorbed into the hold, so mark it dropped now to\n    // suppress its own `route:exchange:completed`; the released exchange (built at\n    // release time) carries the downstream lifecycle instead.\n    markDropped(exchange);\n\n    const existing = state.pending.get(key);\n    if (existing) {\n      // Supersede: the exchange currently held loses to this newer arrival.\n      const superseded = existing.exchange;\n      context.emit(\"route:operation:debounce:dropped\", {\n        routeId,\n        exchangeId: superseded.id,\n        correlationId: superseded.headers[HeadersKeys.CORRELATION_ID] as string,\n        ...keyField,\n      });\n      emitExchangeDropped(context, {\n        routeId,\n        correlationId: superseded.headers[HeadersKeys.CORRELATION_ID] as string,\n        reason: \"debounced\",\n        exchange: superseded,\n      });\n      clearTimeout(existing.waitTimer);\n      existing.exchange = exchange;\n      existing.waitTimer = setTimeout(\n        () => this.#release(state, key, \"quiet\"),\n        this.#options.waitMs,\n      );\n      // maxTimer is deliberately NOT reset: it caps the whole burst.\n    } else {\n      // Burst start: create the hold and a tracked promise so drain() waits\n      // for the eventual release instead of finishing while it is pending.\n      let settle: () => void = () => {};\n      const tracked = new Promise<void>((resolve) => {\n        settle = resolve;\n      });\n      route?.trackTask(tracked);\n      const hold: PendingHold = {\n        exchange,\n        waitTimer: setTimeout(\n          () => this.#release(state, key, \"quiet\"),\n          this.#options.waitMs,\n        ),\n        maxTimer:\n          this.#options.maxWaitMs !== undefined\n            ? setTimeout(\n                () => this.#release(state, key, \"maxWait\"),\n                this.#options.maxWaitMs,\n              )\n            : undefined,\n        settle,\n      };\n      state.pending.set(key, hold);\n    }\n\n    context.emit(\"route:operation:debounce:held\", {\n      routeId,\n      exchangeId: exchange.id,\n      correlationId,\n      ...keyField,\n    });\n\n    context.emit(\"route:step:completed\", {\n      routeId,\n      exchangeId: exchange.id,\n      correlationId,\n      operation: stepLabel,\n      duration: Date.now() - stepStart,\n    });\n\n    // An arrival delivered after the route's signal aborted would never be\n    // abort-flushed (the abort listener fired, or was never installed\n    // because the signal was already aborted when the hooks were wired):\n    // flush its hold immediately so shutdown does not wait out the timer.\n    if (route?.intakeSignal.aborted) {\n      this.#release(state, key, \"flush\");\n    }\n\n    // The arrival never continues in-line; it is released later (or dropped\n    // when superseded).\n    return { kind: \"drop\" };\n  }\n\n  /**\n   * Wire the drain and abort flush hooks for this route exactly once, so a\n   * held exchange is released promptly on `drain()` / shutdown instead of\n   * waiting out its timer (or being lost when the route stops).\n   */\n  #ensureFlushHooks(\n    state: DebounceState,\n    route: ReturnType<typeof getExchangeRoute>,\n  ): void {\n    if (state.flushRegistered || !route) return;\n    state.flushRegistered = true;\n    route.onDrain(() => this.#flushAll(state));\n    // No listener when the signal is already aborted: it would never fire,\n    // and flushing here would hit an empty map (the hold is created after\n    // this call). Post-abort arrivals are flushed per-arrival in execute()\n    // instead, which covers both this first arrival and later ones.\n    if (!route.intakeSignal.aborted) {\n      route.intakeSignal.addEventListener(\n        \"abort\",\n        () => this.#flushAll(state),\n        {\n          once: true,\n        },\n      );\n    }\n  }\n\n  /** Release every pending hold immediately (drain / shutdown). Idempotent. */\n  #flushAll(state: DebounceState): void {\n    for (const key of [...state.pending.keys()]) {\n      this.#release(state, key, \"flush\");\n    }\n  }\n\n  /**\n   * Release the held exchange for `key` through the downstream continuation.\n   *\n   * Infallible by design: this runs from bare timer callbacks, the route's\n   * abort listener, and drain flush callbacks, none of which sit inside the\n   * executor's per-step try/catch. A synchronous throw here (most likely\n   * `cloneExchange` on a non-structured-cloneable body) would otherwise\n   * crash the process or shutdown, and, because the hold is already removed\n   * from `pending`, leave the tracked promise unsettled and hang `drain()`\n   * forever. Every path, success or failure, settles the hold.\n   */\n  #release(state: DebounceState, key: string, reason: ReleaseReason): void {\n    const hold = state.pending.get(key);\n    if (!hold) return;\n    state.pending.delete(key);\n    clearTimeout(hold.waitTimer);\n    if (hold.maxTimer) clearTimeout(hold.maxTimer);\n\n    const held = hold.exchange;\n    const { route, context, routeId, correlationId } = wrapperEventScope(\n      held,\n      this,\n    );\n\n    // Clone FIRST, before any terminal event for the held arrival, so a\n    // clone failure produces a single coherent terminal (`route:exchange:failed`)\n    // instead of a drop followed by a crash. cloneExchange gives fresh\n    // internals (a new id, preserved correlation id) and binds the route so\n    // the released exchange is executor-ready; the held one was marked\n    // dropped at hold time and cannot carry the release itself.\n    let released: Exchange;\n    try {\n      released = context ? cloneExchange(held, context, route) : held;\n    } catch (err) {\n      held.logger.error(\n        { err, reason },\n        \"debounce release failed: the held body is not structured-cloneable\",\n      );\n      context?.emit(\"route:exchange:failed\", {\n        routeId,\n        exchangeId: held.id,\n        correlationId,\n        duration: 0,\n        error: err,\n        exchange: held,\n      });\n      hold.settle();\n      return;\n    }\n\n    // Balance the absorbed arrival's lifecycle: it emitted `route:exchange:started`\n    // on entry and was only MARKED dropped at hold time, so without this\n    // emission its id would have a `started` with no terminal event, reading\n    // as permanently in-flight to observers that pair them, and leaking any\n    // upstream reservation keyed to the arrival id (e.g. a `.dedupe()`\n    // before the debounce commits/releases on terminal events). Emitted at\n    // release time, not hold time, so a superseded arrival's drop stays\n    // attributable to its superseder in the supersede branch above.\n    emitExchangeDropped(context, {\n      routeId,\n      correlationId,\n      reason: \"debounced\",\n      exchange: held,\n    });\n\n    context?.emit(\"route:operation:debounce:released\", {\n      routeId,\n      exchangeId: released.id,\n      correlationId,\n      ...(this.#options.key ? { key } : {}),\n      reason,\n    });\n\n    const runner = state.runner;\n    const run = runner ? runner(released) : Promise.resolve();\n    // Settle the tracked promise once the downstream run finishes, so drain()\n    // waits for the released exchange to complete, not merely to be\n    // scheduled. The runner is engineered never to reject (runPipeline\n    // without rethrowUnhandled contains step errors), but that invariant\n    // lives across a module boundary: catch defensively so a future change\n    // cannot turn a release into a fatal unhandledRejection.\n    void Promise.resolve(run)\n      .catch((err: unknown) => {\n        held.logger.error({ err }, \"debounce release runner rejected\");\n      })\n      .finally(() => hold.settle());\n  }\n}\n\n/**\n * Build the {@link DebounceStep} for a `.debounce(options)` call. Keeps the\n * step value encapsulated in this module so the builder only depends on the\n * helper.\n *\n * @internal\n */\nexport function buildDebounceStep<In = unknown>(\n  options: DebounceOptions<In>,\n): DebounceStep<In> {\n  return new DebounceStep<In>(options);\n}\n","import type { Adapter, Step, StepOutcome } from \"../types.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  HeadersKeys,\n  getExchangeContext,\n  getExchangeRoute,\n  emitExchangeDropped,\n} from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { COLLECT_STEPS, NESTED_STEPS } from \"../dsl-symbol.ts\";\nimport type { NestedSteps } from \"../deferral/sites.ts\";\nimport {\n  StepBuilderBase,\n  type BuilderState,\n  type FetchedBody,\n  type PathState,\n} from \"../step-builder-base.ts\";\nimport type { Destination } from \"./to.ts\";\nimport type { Enricher } from \"./enrich.ts\";\n\n/**\n * Predicate that decides whether a choice branch matches an exchange.\n *\n * Predicates are synchronous by design for phase 1. Async predicates can be\n * introduced later without changing the runtime shape; the branch registration\n * API would add an `asyncWhen` or widen `predicate` to return a Promise.\n *\n * @template T - Body type of the exchange at the point of the choice\n */\nexport type ChoicePredicate<T = unknown> = (exchange: Exchange<T>) => boolean;\n\n/**\n * A single fan-out path: either a bare destination (the exchange is sent to\n * it) or a callback that builds a sub-pipeline on a {@link PathBuilder}. This\n * is the one shared path shape used by `choice` (`when` / `otherwise`),\n * `multicast`, and future branch operations.\n *\n * A callable destination (a bare function with a `send` method) is NOT a\n * valid bare path here, because it is indistinguishable at runtime from a\n * builder callback; wrap it as `(b) => b.to(callableDest)` instead.\n *\n * @template In  - Body type entering the path\n * @template Out - Body type the path produces (defaults to `In`)\n */\nexport type Path<In = unknown, Out = In> =\n  | Destination<In>\n  | Enricher<In, unknown>\n  | ((b: PathBuilder<PathState<In>>) => PathBuilder<PathState<Out>>);\n\n/**\n * Internal representation of one registered branch: a predicate plus the\n * compiled step array that runs when the predicate matches.\n *\n * @internal\n */\ninterface ChoiceBranch {\n  predicate: ChoicePredicate<unknown>;\n  steps: Step<Adapter>[];\n  label: \"when\" | \"otherwise\";\n}\n\n/**\n * Descriptor produced by {@link when}: a predicate plus the path that runs\n * when it matches. Opaque to callers; consumed by `.choice(...)`.\n *\n * @template In  - Body type entering the branch\n * @template Out - Body type the branch produces\n */\nexport interface WhenDescriptor<In = unknown, Out = In> {\n  readonly kind: \"when\";\n  readonly predicate: ChoicePredicate<In>;\n  readonly path: Path<In, Out>;\n}\n\n/**\n * Descriptor produced by {@link otherwise}: the default path taken when no\n * `when` predicate matches. Opaque to callers; consumed by `.choice(...)`.\n *\n * @template In  - Body type entering the branch\n * @template Out - Body type the branch produces\n */\nexport interface OtherwiseDescriptor<In = unknown, Out = In> {\n  readonly kind: \"otherwise\";\n  readonly path: Path<In, Out>;\n}\n\n/**\n * Either kind of branch descriptor accepted by `.choice(...)`.\n *\n * @template In  - Body type entering the branches\n * @template Out - Body type every branch must converge on\n */\nexport type ChoiceDescriptor<In = unknown, Out = In> =\n  WhenDescriptor<In, Out> | OtherwiseDescriptor<In, Out>;\n\n/**\n * Register a conditional branch for `.choice(...)`. The predicate receives\n * the exchange at the point of the choice; the path runs when it returns\n * true. Branches are evaluated in registration order and the first match\n * wins.\n *\n * Three overloads, so the branch's OUTPUT type is checked against the choice's\n * converged `Out` either way: a sub-pipeline callback `(b) => b...` produces\n * the body type its chain ends on, and a bare adapter follows `.to()`\n * semantics (a Destination's send leaves the body unchanged, a fetch-only\n * Enricher replaces it with the fetched value). When the branches differ, set\n * the choice output to the union and narrow downstream:\n * `.choice<Report | Audit>(when(p, b => b.transform(toReport)), otherwise(...))`.\n *\n * When `when(...)` is passed directly as a `.choice(...)` argument, the body\n * type flows in by contextual typing, so `ex.body` is typed without an\n * annotation. Only when a descriptor is built OUTSIDE the call (assigned to a\n * variable first) is there no context to infer from; annotate the predicate\n * parameter or supply the `In` type argument\n * (`when<Order>((ex) => ex.body.priority === \"urgent\", ...)`) in that case.\n *\n * @param predicate - Receives the exchange; returns true if this branch handles it\n * @param branch - Sub-pipeline callback (overload 1) or bare destination (overload 2)\n */\nexport function when<In = unknown, Out = In>(\n  predicate: ChoicePredicate<In>,\n  branch: (b: PathBuilder<PathState<In>>) => PathBuilder<PathState<Out>>,\n): WhenDescriptor<In, Out>;\nexport function when<In = unknown>(\n  predicate: ChoicePredicate<In>,\n  destination: Destination<In>,\n): WhenDescriptor<In, In>;\nexport function when<In = unknown, R = unknown>(\n  predicate: ChoicePredicate<In>,\n  enricher: Enricher<In, R>,\n): WhenDescriptor<In, FetchedBody<In, R>>;\nexport function when(\n  predicate: ChoicePredicate<unknown>,\n  path: Path<unknown, unknown>,\n): WhenDescriptor<unknown, unknown> {\n  return { kind: \"when\", predicate, path };\n}\n\n/**\n * Register the default branch for `.choice(...)`, taken when no `when`\n * predicate matches. Equivalent to Camel's `.otherwise()`. If omitted and no\n * branch matches, the exchange is dropped with `reason: \"unmatched\"`. At most\n * one `otherwise` may be passed to a single `.choice(...)`.\n *\n * Like {@link when}, the overloads accept a sub-pipeline callback or a bare\n * adapter, both with their output checked against the choice's `Out`.\n *\n * @param branch - Sub-pipeline callback (overload 1) or bare adapter (overloads 2 and 3)\n */\nexport function otherwise<In = unknown, Out = In>(\n  branch: (b: PathBuilder<PathState<In>>) => PathBuilder<PathState<Out>>,\n): OtherwiseDescriptor<In, Out>;\nexport function otherwise<In = unknown>(\n  destination: Destination<In>,\n): OtherwiseDescriptor<In, In>;\nexport function otherwise<In = unknown, R = unknown>(\n  enricher: Enricher<In, R>,\n): OtherwiseDescriptor<In, FetchedBody<In, R>>;\nexport function otherwise(\n  path: Path<unknown, unknown>,\n): OtherwiseDescriptor<unknown, unknown> {\n  return { kind: \"otherwise\", path };\n}\n\n/**\n * Compile one {@link Path} into the step array the executor inlines. A bare\n * destination becomes a single `.to()` step; a callback is run against a\n * fresh {@link PathBuilder} and its collected steps are returned.\n *\n * @internal\n */\nexport function compilePath(path: Path<unknown, unknown>): Step<Adapter>[] {\n  const builder = new PathBuilder<PathState<unknown>>();\n  if (typeof path === \"function\") {\n    path(builder);\n  } else {\n    // The union collapses at runtime: ToStep resolves send/fetch\n    // structurally, so the compile-time overload split is irrelevant here.\n    builder.to(path as Destination<unknown>);\n  }\n  return builder[COLLECT_STEPS]();\n}\n\n/**\n * Compile the variadic `.choice(...)` descriptors into the evaluation-ordered\n * branch list: registered `when` branches first, then the optional\n * `otherwise`. Throws (RC5001) if more than one `otherwise` is supplied.\n *\n * @internal\n */\nexport function compileChoiceBranches(\n  descriptors: readonly ChoiceDescriptor<unknown, unknown>[],\n): ChoiceBranch[] {\n  const whenBranches: ChoiceBranch[] = [];\n  let otherwiseBranch: ChoiceBranch | undefined;\n  for (const descriptor of descriptors) {\n    if (descriptor.kind === \"when\") {\n      whenBranches.push({\n        predicate: descriptor.predicate,\n        steps: compilePath(descriptor.path),\n        label: \"when\",\n      });\n    } else {\n      if (otherwiseBranch) {\n        // RC2001 (DSL, build-time) rather than RC5001 (Adapter, runtime): a\n        // duplicate otherwise() is an authoring error caught while compiling\n        // the route, not a step-execution failure.\n        throw rcError(\"RC2001\", undefined, {\n          message:\n            \"choice() may have at most one otherwise() branch; received two\",\n        });\n      }\n      otherwiseBranch = {\n        predicate: () => true,\n        steps: compilePath(descriptor.path),\n        label: \"otherwise\",\n      };\n    }\n  }\n  return otherwiseBranch\n    ? [...whenBranches, otherwiseBranch]\n    : [...whenBranches];\n}\n\n/**\n * Build the {@link ChoiceStep} for a variadic `.choice(...)` call. Keeps the\n * {@link ChoiceStep} value encapsulated in this module so the builder only\n * depends on the helper.\n *\n * @internal\n */\nexport function buildChoiceStep(\n  descriptors: readonly ChoiceDescriptor<unknown, unknown>[],\n): ChoiceStep {\n  return new ChoiceStep(compileChoiceBranches(descriptors));\n}\n\n/**\n * Marker adapter for the HaltStep. Halt has no configuration; the adapter is\n * a zero-field marker so the Step interface shape stays uniform and telemetry\n * can surface the adapter label.\n */\nexport interface HaltAdapter extends Adapter {\n  readonly adapterId: \"routecraft.operation.halt\";\n}\n\n/**\n * Step that short-circuits the pipeline for the current exchange. Used by\n * `b.halt()` inside a path to signal \"this path should not continue past the\n * choice / multicast.\" Emits `route:exchange:dropped` with reason `\"halted\"`.\n *\n * Halt is an explicit stop. It is distinct from filter (predicate rejection)\n * and from choice-unmatched (no branch matched); callers can distinguish the\n * three via the `reason` field on the `route:exchange:dropped` event.\n */\nexport class HaltStep implements Step<HaltAdapter> {\n  operation: OperationType = OperationType.HALT;\n  adapter: HaltAdapter = { adapterId: \"routecraft.operation.halt\" };\n\n  async execute(exchange: Exchange): Promise<StepOutcome> {\n    const context = getExchangeContext(exchange);\n    const route = getExchangeRoute(exchange);\n    const routeId =\n      route?.definition.id ??\n      (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n\n    emitExchangeDropped(context, {\n      routeId,\n      correlationId,\n      reason: \"halted\",\n      exchange,\n    });\n\n    return { kind: \"drop\" };\n  }\n}\n\n/**\n * Sub-builder that defines the step pipeline for a single fan-out path.\n *\n * Exposed to the user as the `b` parameter inside `when(pred, b => ...)`,\n * `otherwise(b => ...)`, and `multicast(b => ...)`. Pipeline operations\n * (`to`, `transform`, `enrich`, ...) are inherited from\n * {@link StepBuilderBase} and behave identically to their counterparts on\n * `RouteBuilder`; the polymorphic return types ensure a chained call re-types\n * this builder as `PathBuilder<NewT>`.\n *\n * PathBuilder adds `.halt()` for explicit short-circuit of the enclosing\n * path. Path-unsafe ops like `.split()` / `.aggregate()` / `.from()` are\n * deliberately absent because they have no coherent meaning inside a path.\n *\n * @template S - The {@link BuilderState} bag entering this path\n */\nexport class PathBuilder<\n  S extends BuilderState = BuilderState,\n> extends StepBuilderBase<S> {\n  private readonly steps: Step<Adapter>[] = [];\n\n  protected override pushStep<T extends Adapter>(step: Step<T>): void {\n    this.steps.push(this.applyPendingWrappers(step));\n  }\n\n  /**\n   * Short-circuit the pipeline for this exchange. Once `halt()` executes, no\n   * further steps run -- neither the remaining path steps nor (for a choice\n   * branch) the steps after the enclosing `.choice()` on the main pipeline.\n   * The exchange emits `route:exchange:dropped` with `reason: \"halted\"`.\n   *\n   * Useful for branches that handle error cases and do not want the rest of\n   * the main pipeline to run, e.g.\n   * `.otherwise(b => b.to(errorSink).halt())`.\n   *\n   * @returns This builder (for chaining, though no further steps will execute)\n   */\n  halt(): PathBuilder<S> {\n    this.pushStep(new HaltStep());\n    return this;\n  }\n\n  /**\n   * Hand the compiled step array to the enclosing step. Symbol-keyed so it\n   * does not pollute the public autocomplete surface on the builder.\n   *\n   * @internal\n   */\n  [COLLECT_STEPS](): Step<Adapter>[] {\n    return this.steps;\n  }\n}\n\n/**\n * Marker adapter for the ChoiceStep. Exposes no configuration; branches live\n * on the step itself.\n */\nexport interface ChoiceAdapter extends Adapter {\n  readonly adapterId: \"routecraft.operation.choice\";\n}\n\n/**\n * Step that evaluates registered branch predicates in order and inlines the\n * matching branch's steps into the main execution queue. If no branch\n * matches, the exchange is dropped.\n *\n * The branch steps are inlined before the remaining main-pipeline steps, so\n * a matched branch flows naturally back into the main pipeline (convergence\n * semantics). A branch can opt out of convergence by ending in `.halt()`,\n * which sets the dropped flag and prevents further steps from executing.\n */\nexport class ChoiceStep<In = unknown> implements Step<ChoiceAdapter> {\n  operation: OperationType = OperationType.CHOICE;\n  adapter: ChoiceAdapter = { adapterId: \"routecraft.operation.choice\" };\n  skipStepEvents = true;\n\n  constructor(private readonly branches: ChoiceBranch[]) {}\n\n  /**\n   * Expose the branch pipelines to framework-level walks of the route's\n   * step tree. `rejoins: true`: a matched branch is inlined ahead of the\n   * remaining main-pipeline steps, so a `.defer()` inside a branch has a\n   * continuation that spans the branch tail and the main tail.\n   *\n   * @internal\n   */\n  [NESTED_STEPS](): ReadonlyArray<NestedSteps> {\n    return this.branches.map((branch) => ({\n      steps: branch.steps,\n      rejoins: true,\n      predicate: branch.predicate,\n    }));\n  }\n\n  async execute(exchange: Exchange<In>): Promise<StepOutcome> {\n    const context = getExchangeContext(exchange);\n    const route = getExchangeRoute(exchange);\n    const routeId =\n      route?.definition.id ??\n      (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n    const stepStart = Date.now();\n\n    if (context) {\n      context.emit(\"route:step:started\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: this.operation,\n      });\n    }\n\n    let matchedIndex = -1;\n    let matchedBranch: ChoiceBranch | undefined;\n    for (let i = 0; i < this.branches.length; i++) {\n      const branch = this.branches[i];\n      let result: boolean;\n      try {\n        result = branch.predicate(exchange as Exchange<unknown>);\n      } catch (error: unknown) {\n        if (context) {\n          context.emit(\"route:step:failed\", {\n            routeId,\n            exchangeId: exchange.id,\n            correlationId,\n            operation: this.operation,\n            duration: Date.now() - stepStart,\n            error: error instanceof Error ? error.message : String(error),\n          });\n        }\n        throw rcError(\"RC5001\", error, {\n          message: `choice predicate threw (branch index ${i})`,\n        });\n      }\n      if (result) {\n        matchedIndex = i;\n        matchedBranch = branch;\n        break;\n      }\n    }\n\n    if (!matchedBranch) {\n      if (context) {\n        context.emit(\"route:step:completed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          operation: this.operation,\n          duration: Date.now() - stepStart,\n          metadata: { matched: false },\n        });\n        context.emit(\"route:operation:choice:unmatched\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n        });\n      }\n      emitExchangeDropped(context, {\n        routeId,\n        correlationId,\n        reason: \"unmatched\",\n        exchange,\n      });\n      return { kind: \"drop\" };\n    }\n\n    if (context) {\n      context.emit(\"route:step:completed\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        operation: this.operation,\n        duration: Date.now() - stepStart,\n        metadata: { matched: true, branchIndex: matchedIndex },\n      });\n      context.emit(\"route:operation:choice:matched\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        branchIndex: matchedIndex,\n        branchLabel: matchedBranch.label,\n      });\n    }\n\n    return { kind: \"branch\", exchange, steps: matchedBranch.steps };\n  }\n}\n","import type { Duration } from \"./shared/duration.ts\";\nimport { ENRICH_MERGE_TYPE } from \"./brand.ts\";\nimport type { Adapter, Step } from \"./types.ts\";\nimport type { Exchange, HeaderValue, HeaderLiteral } from \"./exchange.ts\";\nimport type { DeferralAffordance } from \"./deferral/exchange-state.ts\";\nimport {\n  type Destination,\n  type SendContext,\n  type ToTarget,\n  ToStep,\n} from \"./operations/to.ts\";\nimport {\n  type Transformer,\n  type CallableTransformer,\n  TransformStep,\n} from \"./operations/transform.ts\";\nimport {\n  EnrichStep,\n  type Enricher,\n  type CallableEnricher,\n  type EnrichAggregator,\n  type EnrichMergeShape,\n  type EnrichAggregatorOption,\n} from \"./operations/enrich.ts\";\nimport { ErrorWrapperStep } from \"./operations/error-wrapper.ts\";\nimport {\n  CacheWrapperStep,\n  type CacheOptions,\n} from \"./operations/cache-wrapper.ts\";\nimport { DelayWrapperStep } from \"./operations/delay-wrapper.ts\";\nimport { TimeoutWrapperStep } from \"./operations/timeout-wrapper.ts\";\nimport {\n  RetryWrapperStep,\n  type RetryOptions,\n} from \"./operations/retry-wrapper.ts\";\nimport {\n  ThrottleWrapperStep,\n  type ThrottleOptions,\n} from \"./operations/throttle-wrapper.ts\";\nimport {\n  CircuitBreakerWrapperStep,\n  type CircuitBreakerOptions,\n} from \"./operations/circuit-breaker-wrapper.ts\";\nimport {\n  ConcurrencyWrapperStep,\n  type ConcurrencyOptions,\n} from \"./operations/concurrency-wrapper.ts\";\nimport {\n  type Processor,\n  type CallableProcessor,\n  ProcessStep,\n} from \"./operations/process.ts\";\nimport { TapStep, type TapTarget } from \"./operations/tap.ts\";\nimport {\n  type CallableFilter,\n  type Filter,\n  FilterStep,\n} from \"./operations/filter.ts\";\nimport { type SampleOptions, SampleStep } from \"./operations/sample.ts\";\nimport { type DedupeOptions, DedupeStep } from \"./operations/dedupe.ts\";\nimport {\n  type Validator,\n  type CallableValidator,\n  ValidateStep,\n} from \"./operations/validate.ts\";\nimport {\n  type CallableAuthenticator,\n  AuthenticateStep,\n} from \"./operations/authenticate.ts\";\nimport {\n  type CallableDelegator,\n  DelegateStep,\n  type DelegateStepOptions,\n} from \"./operations/delegate.ts\";\nimport { HeaderStep } from \"./operations/header.ts\";\nimport type { ErrorHandler } from \"./route.ts\";\nimport { PUSH_STEP } from \"./dsl-symbol.ts\";\n\n/**\n * Builder hook that wraps a single step in a \"dual-mode wrapper\"\n * (e.g. `.error()`, `.retry()`, `.timeout()`, `.cache()`, `.delay()`).\n * Pushed onto {@link StepBuilderBase}'s pending wrapper stack when the\n * builder method runs in step scope; folded around the next pushed\n * step inside {@link StepBuilderBase.applyPendingWrappers}.\n *\n * @internal\n */\nexport type StepWrapperFactory = <T extends Adapter>(inner: Step<T>) => Step<T>;\n\n// Type-only imports to avoid a runtime cycle. The `Retyped` conditional below\n// resolves `this` into the concrete subclass typed at the new state bag; the\n// value side of each subclass is defined in its own module and imports\n// StepBuilderBase, not the other way around.\nimport type { RouteBuilder } from \"./builder.ts\";\nimport type { PathBuilder } from \"./operations/choice.ts\";\n\n/**\n * The type-state bag threaded through the builder chain.\n *\n * Every builder generic (`RouteBuilder<S>`, `PathBuilder<S>`,\n * `StepBuilderBase<S>`) is parameterised by ONE bag rather than by loose\n * type arguments, because declaration merging freezes generic arity: the\n * moment an ecosystem package augments `interface StepBuilderBase<S>`, the\n * parameter list can never change again. With a bag, new tracked facets\n * (typed headers, accumulated tags, ...) become new OPTIONAL fields on this\n * interface, which is a non-breaking change for every augmentation already\n * in the wild.\n *\n * `body` is the only field today: the body type entering the next step.\n */\nexport interface BuilderState {\n  /** Body type entering the next pipeline step. */\n  body: unknown;\n  /**\n   * Type of `ex.deferral.result` for the steps that follow a\n   * `.defer({ schema })`, threaded in from the declared schema the way\n   * `body` is threaded in from `.input()`. `unknown` before any defer.\n   *\n   * Optional, per the extension rule above: an existing augmentation or a\n   * hand-written state bag that predates this field still satisfies the\n   * constraint. Framework-internal bags always carry it explicitly, because\n   * a bag that OMITS the key is a different shape from one that has it, and\n   * the two do not interconvert (the builders are invariant in this bag).\n   */\n  deferral?: unknown;\n}\n\n/**\n * Replace the `body` field of a state bag, preserving every other (current\n * or future) field. The single way builder methods advance the body type;\n * using it everywhere means a new `BuilderState` field flows through every\n * existing chain method untouched.\n *\n * @template S - The incoming state bag\n * @template B - The new body type\n */\nexport type SetBody<S extends BuilderState, B> = {\n  [K in keyof S]: K extends \"body\" ? B : S[K];\n};\n\n/**\n * Replace the `deferral` field of a state bag, preserving every other\n * field. The `.defer()` counterpart of {@link SetBody}: it advances the\n * type of `ex.deferral.result` for the rest of the chain.\n *\n * `Omit` plus an intersection rather than a mapped type, because a mapped\n * type preserves optionality: mapping the OPTIONAL `deferral` key would\n * type the result as `R | undefined` and force a needless narrowing on\n * every read after a defer. After a `.defer()` the field is known.\n *\n * @template S - The incoming state bag\n * @template R - The expected-result type declared by `.defer({ schema })`\n */\nexport type SetDeferral<S extends BuilderState, R> = Omit<S, \"deferral\"> & {\n  deferral: R;\n};\n\n/**\n * The exchange type a callable sees at this point in the chain: the body\n * type from the bag, plus `ex.deferral.result` narrowed to whatever the\n * last `.defer({ schema })` declared.\n *\n * An intersection rather than a rewritten `Exchange`, so the narrowing is\n * additive: `Exchange<T>` already carries `deferral`, and\n * `DeferralAffordance<unknown> & DeferralAffordance<R>` reads `result`\n * as `R`. Before any defer the bag's field is `unknown` and the\n * intersection is a no-op.\n *\n * @template S - The state bag at this chain position\n */\nexport type ExchangeOf<S extends BuilderState> = Exchange<S[\"body\"]> & {\n  readonly deferral: DeferralAffordance<S[\"deferral\"]>;\n};\n\n/**\n * A path's state bag: a fresh chain over body `T`.\n *\n * Spelled out (rather than `{ body: T }`) because the builders are\n * invariant in their bag: a sub-pipeline that ends in a `.defer()`\n * produces a bag WITH the `deferral` key, and it is only assignable back\n * to the declared path type if that type has the key too.\n *\n * @template T - Body type entering the path\n */\nexport type PathState<T> = { body: T; deferral: unknown };\n\n/**\n * Body type after a bare pull-in step (`.enrich(x)` with no aggregator, or a\n * fetch-only adapter in `.to()`). A fetch that resolves `undefined` means\n * \"no value\" and leaves the body unchanged at runtime, so a result type that\n * includes `undefined` yields the union of the previous body and the defined\n * results; this keeps the static claim honest for nullable enrichers (a\n * cache miss, `(ex) => map.get(k)`). Return `null` instead when a miss\n * should be an observable replacement value. Result types without\n * `undefined` collapse to plain `R`.\n *\n * `void` is handled first and separately: an enricher declared to produce\n * nothing never replaces the body, so the body carries through as `Current`\n * rather than widening to `Current | void`. This mirrors the callable `.to()`\n * overload, which collapses a `void`-returning function the same way.\n *\n * @template Current - Body type entering the step\n * @template R - Value type the fetch produces\n */\nexport type FetchedBody<Current, R> = R extends void\n  ? Current\n  : undefined extends R\n    ? Current | Exclude<R, undefined>\n    : R;\n\n/**\n * Maps the polymorphic `this` type of a `StepBuilderBase` call to the same\n * concrete subclass re-typed at the new state bag `S2`. Enables methods on\n * the shared base class to return `RouteBuilder<S2>` or `PathBuilder<S2>`\n * automatically based on the receiver at the call site, without each subclass\n * overriding every method to narrow its return.\n *\n * Closed-world on purpose: only the framework-owned subclasses participate.\n * External subclasses fall through to `never`, which is intentional -- the\n * shared base class is not a public extension point today. Any future\n * framework-owned subclass (for example, a `dispatch` target builder) must\n * be added to the union below.\n *\n * @template This - The polymorphic `this` type inside a method on StepBuilderBase\n * @template S2 - The new state bag to re-type the subclass at\n */\n// The `infer` holes below are match-only: the builder classes are invariant\n// in their state bag, so a structural `extends RouteBuilder<BuilderState>`\n// check fails for concrete instantiations; inferential matching does not.\n/* eslint-disable @typescript-eslint/no-unused-vars */\nexport type Retyped<This, S2 extends BuilderState> =\n  This extends RouteBuilder<infer _RS extends BuilderState>\n    ? RouteBuilder<S2>\n    : This extends PathBuilder<infer _BS extends BuilderState>\n      ? PathBuilder<S2>\n      : never;\n/* eslint-enable @typescript-eslint/no-unused-vars */\n\n/**\n * Shared abstract base for builders that accumulate pipeline steps.\n *\n * Implements the pipeline operations that are identical across\n * `RouteBuilder` and `PathBuilder` (`to`, `transform`, `enrich`). Each\n * subclass provides its own `pushStep` hook describing where steps go --\n * `RouteBuilder` pushes into the current route definition (and enforces\n * that `.from()` has been called via `requireSource`), while\n * `PathBuilder` pushes into its internal step array.\n *\n * Return types are threaded through the polymorphic `this` via\n * {@link Retyped}, so a `.transform()` call on a `RouteBuilder<{ body: A }>`\n * returns `RouteBuilder<{ body: B }>` and the same call on\n * `PathBuilder<{ body: A }>` returns `PathBuilder<{ body: B }>`.\n *\n * The class value is framework-internal and must not be subclassed outside\n * the framework (the {@link Retyped} conditional is closed-world and external\n * subclasses would silently resolve to `never`). The TYPE, however, is the\n * documented augmentation point for DSL sugar: `registerDsl` adds the runtime\n * method here, and ecosystem packages declare its type by merging into\n * `interface StepBuilderBase<S extends BuilderState>` (see `registerDsl`).\n *\n * @template S - The {@link BuilderState} bag for the chain position\n */\nexport abstract class StepBuilderBase<S extends BuilderState = BuilderState> {\n  /**\n   * Stack of step-scope wrapper factories declared since the last\n   * pushed step, in declaration order. Folded around the next pushed\n   * step by {@link applyPendingWrappers}; the first-declared wrapper\n   * is outermost (`.retry().timeout().process(slow)` means\n   * `retry(timeout(process))`). Cleared after each push.\n   *\n   * @internal\n   */\n  protected pendingStepWrappers: StepWrapperFactory[] = [];\n\n  /**\n   * Fold any wrappers staged since the last push around `step`,\n   * returning the (possibly wrapped) step that subclasses should hand\n   * to their target collection. Clears the stack on every call so a\n   * wrapper attaches to exactly one step.\n   *\n   * @internal\n   */\n  protected applyPendingWrappers<T extends Adapter>(step: Step<T>): Step<T> {\n    if (this.pendingStepWrappers.length === 0) return step;\n    let wrapped: Step<Adapter> = step as Step<Adapter>;\n    for (let i = this.pendingStepWrappers.length - 1; i >= 0; i--) {\n      const factory = this.pendingStepWrappers[i]!;\n      wrapped = factory(wrapped);\n    }\n    this.pendingStepWrappers = [];\n    return wrapped as unknown as Step<T>;\n  }\n\n  /**\n   * Append a step to the builder's pipeline. Implemented by each subclass\n   * to route the step into the right collection (current route definition\n   * vs. branch step array). Subclass-specific validation (e.g.\n   * `RouteBuilder.requireSource`) lives in the implementation. Subclasses\n   * MUST run `step` through {@link applyPendingWrappers} so dual-mode\n   * wrappers (`.error()`, `.retry()`, `.timeout()`, etc.) attach to the right\n   * step.\n   *\n   * @param step - The step to append\n   */\n  protected abstract pushStep<T extends Adapter>(step: Step<T>): void;\n\n  /**\n   * Attach an error handler to the next step. When the wrapped step\n   * throws, the handler runs with `(err, exchange, forward)` (same\n   * shape as the route-level handler), its return value replaces\n   * `exchange.body`, and the pipeline continues with the next step.\n   *\n   * On `RouteBuilder`, this method is dual-mode: when called BEFORE\n   * `.from()` it stages a route-level catch-all (existing behaviour);\n   * when called AFTER `.from()` it wraps the next step. On\n   * `PathBuilder`, it is always step-scope.\n   *\n   * If the handler itself throws, the wrapper rethrows so the\n   * route-level handler (when set) catches it; otherwise the route's\n   * default error path fires (`route:error`, `context:error`,\n   * `route:exchange:failed`). The route is NOT stopped.\n   *\n   * Stacks left-to-right: `.error(h1).error(h2).to(dest)` produces\n   * `h1` outermost wrapping `h2` wrapping `dest`. `h2` runs first; if\n   * it rethrows, `h1` gets a chance.\n   *\n   * wrapper pattern (see `.standards/resilience-wrappers.md`).\n   */\n  error(handler: ErrorHandler): this {\n    this.pendingStepWrappers.push(\n      (inner) => new ErrorWrapperStep(inner, handler),\n    );\n    return this;\n  }\n\n  /**\n   * Cache the result of the next step. When a cached value exists for\n   * the derived key, the wrapped step is skipped and the cached body\n   * replaces `exchange.body`. On a miss, the step runs and its output\n   * body is written to the cache for future calls.\n   *\n   * Only the next step's output is cached, and only when that step\n   * does not throw: a throw propagates and leaves the cache untouched,\n   * and dropped exchanges (filter / halt) are not cached. A step that\n   * returns an error reply without throwing (an `http()` enricher with\n   * `throwOnHttpError: false` answering 503) succeeded as far as the\n   * cache can tell, so that reply IS cached. Use route scope, or make\n   * the step throw, when a failure must not be remembered.\n   *\n   * Concurrent exchanges with the same key share one computation via\n   * the provider's `getOrCompute`, so a slow underlying operation\n   * runs at most once per key per TTL window.\n   *\n   * On `RouteBuilder`, this method is dual-mode: called BEFORE\n   * `.from()` it caches the whole route and never stores a failed\n   * exchange (see {@link RouteBuilder.cache}). On `PathBuilder`, it is\n   * always step-scope.\n   *\n   * Stacks left-to-right with other wrappers: `.error(h).cache().to(d)`\n   * produces `error(cache(d))`, so the cache runs inside the error\n   * handler's recovery scope.\n   *\n   * @param options Optional `{ key, ttl, provider }`. Defaults: a key\n   *   namespaced by route id (plus, at step scope, this cache's site in the\n   *   route) and the principal's issuer and subject (with its actor chain),\n   *   then a SHA-256 of\n   *   `JSON.stringify(body)` (see {@link CacheOptions.key}; a bodiless\n   *   exchange needs an explicit `key`, used verbatim); no TTL;\n   *   process-wide in-memory provider.\n   */\n  cache(options: CacheOptions<S[\"body\"]> = {}): this {\n    this.pendingStepWrappers.push(\n      (inner) => new CacheWrapperStep(inner, options as CacheOptions),\n    );\n    return this;\n  }\n\n  /**\n   * Wait a fixed time before the next step runs. Pass-through: the\n   * exchange is unchanged by the wait. The wait is cancelled when the\n   * route shuts down mid-wait; the wrapped step still runs, so no\n   * exchange is silently dropped by a shutdown.\n   *\n   * Step scope only: there is no route-scope form (a route-scope delay\n   * is equivalent to a delay before the first step) and the pre-from\n   * filter chain reserves no slot for it.\n   *\n   * Stacks with other wrappers in declaration order (first-declared\n   * outermost): `.retry().delay(1000).process(op)` waits before each\n   * attempt, because retry re-runs the delay-wrapped step.\n   *\n   * @param duration - How long to wait before the next step\n   * @returns This builder (same subclass, same body type)\n   */\n  delay(duration: Duration): this {\n    this.pendingStepWrappers.push(\n      (inner) => new DelayWrapperStep(inner, duration),\n    );\n    return this;\n  }\n\n  /**\n   * Bound the next step with a deadline. When the step settles in time\n   * its outcome passes through unchanged; when the deadline fires first\n   * the wrapper throws `RC5011` (Request timeout, `retryable: true`),\n   * so an outer `.retry()` re-attempts it by default and `.error()`\n   * handlers can branch on the code.\n   *\n   * The step is not cancelled on expiry (promises cannot be\n   * cancelled): it keeps running in the background and its eventual\n   * result is discarded, so side effects of the abandoned attempt may\n   * still happen. The timeout bounds how long the pipeline waits, not\n   * the work itself.\n   *\n   * On `RouteBuilder`, this method is dual-mode: called BEFORE\n   * `.from()` it bounds each run of the whole pipeline at pre-from\n   * filter chain position 8 (inside `.retry()`, so each attempt gets\n   * its own deadline); called AFTER `.from()` it wraps the next step.\n   *\n   * @param duration - The deadline\n   * @returns This builder (same subclass, same body type)\n   */\n  timeout(duration: Duration): this {\n    this.pendingStepWrappers.push(\n      (inner) => new TimeoutWrapperStep(inner, duration),\n    );\n    return this;\n  }\n\n  /**\n   * Re-attempt the next step on failure with configurable backoff.\n   * Each attempt receives the same (frozen) exchange, so a re-attempt\n   * always starts from the input that failed. After the final attempt\n   * fails, the original error propagates unchanged to outer wrappers\n   * or the route-level handler.\n   *\n   * By default only errors with `retryable: false` (validation, auth,\n   * config) are NOT re-attempted; everything else, including timeouts\n   * (`RC5011`) and unknown third-party errors, is retried. Override\n   * with `retryOn`.\n   *\n   * On `RouteBuilder`, this method is dual-mode: called BEFORE\n   * `.from()` it re-runs the whole pipeline at pre-from filter chain\n   * position 7 (outside `.timeout()`, inside `.error()`); called AFTER\n   * `.from()` it wraps the next step.\n   *\n   * Stacks with other wrappers in declaration order (first-declared\n   * outermost): `.retry().timeout(5000).to(dest)` gives each attempt\n   * its own 5s deadline.\n   *\n   * @param options - `maxAttempts` (default 3), `backoff` (a `Duration`,\n   *   default 1000 ms), `factor` (growth multiplier, default 1 = fixed),\n   *   `maxBackoff` (a `Duration`, the wait ceiling), `jitter` (`\"none\"` | `\"full\"` |\n   *   `0..1`, default `\"none\"`), `retryOn` (default: skip non-retryable\n   *   RoutecraftErrors)\n   * @returns This builder (same subclass, same body type)\n   */\n  retry(options: RetryOptions = {}): this {\n    this.pendingStepWrappers.push(\n      (inner) => new RetryWrapperStep(inner, options),\n    );\n    return this;\n  }\n\n  /**\n   * Rate-limit the next step to `rate` calls per `per` window (token\n   * bucket). Exchanges that exceed the rate are paced (delayed) rather\n   * than dropped, so backpressure flows back through the pipeline.\n   *\n   * By default the limiter is one bucket shared across the route (a\n   * global limit). Pass a `key` selector to partition it per user / IP /\n   * tenant: each distinct key gets its own bucket, bounded by `maxKeys`.\n   * After an idle window up to `burst` calls (default `rate`) pass\n   * immediately, then admissions settle to the configured rate.\n   *\n   * On `RouteBuilder`, this method is dual-mode: called BEFORE\n   * `.from()` it rate-limits the whole pipeline at pre-from filter chain\n   * position 5 (outside the resilience wrappers, so a throttled request\n   * never reaches retry / timeout); called AFTER `.from()` it wraps the\n   * next step. Multiple `.throttle()` calls AND-combine into independent\n   * limits.\n   *\n   * The pacing wait is cancellable: when the route shuts down mid-wait\n   * the exchange is admitted immediately rather than dropped.\n   *\n   * @param options - `{ rate, per?, burst?, key?, maxKeys? }`\n   * @returns This builder (same subclass, same body type)\n   */\n  throttle(options: ThrottleOptions): this {\n    this.pendingStepWrappers.push(\n      (inner) => new ThrottleWrapperStep(inner, options),\n    );\n    return this;\n  }\n\n  /**\n   * Protect the next step with a circuit breaker. Counts the step's\n   * failures over a sliding `windowMs`; once `failureThreshold` failures\n   * accumulate the breaker trips OPEN and subsequent calls fast-fail\n   * (returning `fallback(exchange)` when set, otherwise throwing\n   * `RC5025`) without running the step. After `cooldownMs` the breaker\n   * goes HALF-OPEN and admits up to `halfOpenMax` probe calls: one\n   * success closes it, one failure re-opens it.\n   *\n   * Deterministic errors do not count toward the threshold by default\n   * (any `RoutecraftError` flagged `retryable: false`, e.g. auth or\n   * validation), since they are not evidence the downstream is unhealthy;\n   * override with `isFailure`.\n   *\n   * Only the immediately-next step is protected; later steps run\n   * normally. The breaker state is shared per route (one circuit across\n   * every exchange on the route), not per exchange.\n   *\n   * On `RouteBuilder`, this method is dual-mode: called BEFORE `.from()`\n   * it protects the whole pipeline at pre-from filter chain position 6\n   * (outside `.retry()` / `.timeout()`, so it records one tripped call\n   * per fully exhausted attempt); called AFTER `.from()` it wraps the\n   * next step.\n   *\n   * Stacks with other wrappers in declaration order (first-declared\n   * outermost).\n   *\n   * @param options - `failureThreshold` (required), `windowMs` (default\n   *   60_000), `cooldownMs` (default 30_000), `halfOpenMax` (default 1),\n   *   optional `fallback`, `onStateChange`, `isFailure`, and `label`.\n   * @returns This builder (same subclass, same body type)\n   */\n  circuitBreaker(options: CircuitBreakerOptions): this {\n    this.pendingStepWrappers.push(\n      (inner) => new CircuitBreakerWrapperStep(inner, options),\n    );\n    return this;\n  }\n\n  /**\n   * Bound the next step to `max` simultaneous in-flight exchanges\n   * (a bulkhead). Where `.throttle()` caps a RATE (calls per window),\n   * `.concurrency()` caps SIMULTANEITY (how many run at once) -- protect a\n   * connection pool, a memory-bound step, or a downstream with a hard\n   * concurrency cap. The two compose but are not substitutes.\n   *\n   * When all slots are busy the default `queue` mode makes the exchange\n   * wait FIFO for a slot (backpressure), bounded by `maxQueue`; `reject`\n   * mode fails fast with `RC5026` instead. Pass a `key` selector to give\n   * each user / tenant / pool its own independent slots, bounded by\n   * `maxKeys`. The queue wait is cancellable: on route shutdown a waiting\n   * exchange is admitted rather than dropped.\n   *\n   * On `RouteBuilder`, this method is dual-mode: called BEFORE `.from()` it\n   * bounds the whole pipeline at the innermost resilience position (inside\n   * `.retry()` / `.timeout()`, so a slot is acquired per attempt and\n   * released between retry backoffs, never held while sleeping); called\n   * AFTER `.from()` it wraps the next step.\n   *\n   * Stacks with other wrappers in declaration order (first-declared\n   * outermost).\n   *\n   * @param options - `{ max, mode?, maxQueue?, key?, maxKeys?, label? }`\n   * @returns This builder (same subclass, same body type)\n   */\n  concurrency(options: ConcurrencyOptions): this {\n    this.pendingStepWrappers.push(\n      (inner) => new ConcurrencyWrapperStep(inner, options),\n    );\n    return this;\n  }\n\n  /**\n   * Return `this` re-typed to the concrete subclass with the state bag's\n   * `body` replaced by `B` (other bag fields preserved).\n   *\n   * The single cast point used by every pipeline method that changes the\n   * body type. Centralising it means `RouteBuilder` and `PathBuilder`\n   * do not each need their own `withType<T>()` helper, and the closed-world\n   * {@link Retyped} conditional resolves the return type to the caller's\n   * concrete subclass.\n   *\n   * @template B - New body type\n   * @returns This instance, re-typed\n   */\n  protected retype<B>(): Retyped<this, SetBody<S, B>> {\n    return this as unknown as Retyped<this, SetBody<S, B>>;\n  }\n\n  /**\n   * Hand the exchange to a destination (push out) or enricher (pull in).\n   *\n   * Role resolution: an adapter with a `send` slot is a push-out, and the\n   * body continues unchanged (receipts surface via headers, see\n   * {@link SendContext}); when an adapter has both `send` and `fetch`,\n   * `send` wins (\"to a file means save to it\"). A fetch-only adapter (e.g.\n   * `http({ url })`, `direct(\"endpoint\")`) is a pull-in, and the fetched\n   * value replaces the body; a fetch resolving `undefined` means \"no value\"\n   * and leaves the body unchanged (see {@link FetchedBody}). Function forms\n   * follow their inferred return type: `(ex) => void` is a send,\n   * `(ex) => R` replaces the body with `R`.\n   *\n   * @param target - Destination, Enricher, or callable\n   * @returns The subclass builder re-typed to the step's output body\n   * @template R - Fetched result body type for pull-in targets\n   */\n  to(destination: Destination<S[\"body\"]>): Retyped<this, S>;\n  to<R>(\n    enricher: Enricher<S[\"body\"], R>,\n  ): Retyped<this, SetBody<S, FetchedBody<S[\"body\"], R>>>;\n  to<R = void>(\n    fn: (exchange: ExchangeOf<S>, ctx?: SendContext) => Promise<R> | R,\n  ): Retyped<this, SetBody<S, R extends void ? S[\"body\"] : R>>;\n  to(target: ToTarget<S[\"body\"], unknown>): unknown {\n    this.pushStep(new ToStep<S[\"body\"], unknown>(target));\n    return this.retype<unknown>();\n  }\n\n  /**\n   * Transform the exchange body. The transformer receives the current\n   * body and returns the replacement body. Headers and exchange identity\n   * are preserved. Use `.process()` when the full exchange is needed.\n   *\n   * @param transformer - Adapter or callable that maps the body to a new value\n   * @returns The subclass builder re-typed to the transformer's output\n   * @template Return - Result body type\n   */\n  transform<Return>(\n    transformer:\n      | Transformer<S[\"body\"], Return>\n      | CallableTransformer<S[\"body\"], Return, ExchangeOf<S>>,\n  ): Retyped<this, SetBody<S, Return>> {\n    this.pushStep(new TransformStep<S[\"body\"], Return>(transformer));\n    return this.retype<Return>();\n  }\n\n  /**\n   * Enrich the exchange with data pulled in by an {@link Enricher} (e.g. an\n   * HTTP lookup or a file read). With no aggregator the fetched value\n   * REPLACES the body. Pass an aggregator to merge instead: `only(...)`\n   * carries an `ENRICH_MERGE_TYPE` brand that drives the body-type\n   * inference, `none()` keeps the body, and a custom aggregator returns the\n   * derived exchange itself.\n   *\n   * A fetch resolving `undefined` means \"no value\" and leaves the body\n   * unchanged ({@link FetchedBody} reflects this in the inferred type);\n   * return `null` when a miss should be an observable replacement value.\n   *\n   * @param enricher - Enricher adapter or callable that produces the data\n   * @param aggregator - Optional merge strategy; omitted = replace the body\n   * @returns The subclass builder re-typed to the resulting body shape\n   * @template R - Value type produced by the enricher\n   * @template A - Aggregator type (drives body shape inference)\n   */\n  enrich<R>(\n    enricher:\n      Enricher<S[\"body\"], R> | CallableEnricher<S[\"body\"], R, ExchangeOf<S>>,\n  ): Retyped<this, SetBody<S, FetchedBody<S[\"body\"], R>>>;\n  enrich<\n    R,\n    A extends\n      | EnrichAggregator<S[\"body\"], R>\n      | (EnrichAggregator<unknown, unknown> & {\n          [ENRICH_MERGE_TYPE]?: EnrichMergeShape;\n        }),\n  >(\n    enricher:\n      Enricher<S[\"body\"], R> | CallableEnricher<S[\"body\"], R, ExchangeOf<S>>,\n    aggregator: A,\n  ): Retyped<\n    this,\n    SetBody<\n      S,\n      A extends { [ENRICH_MERGE_TYPE]: infer M } ? S[\"body\"] & M : S[\"body\"]\n    >\n  >;\n  enrich<R>(\n    enricher:\n      Enricher<S[\"body\"], R> | CallableEnricher<S[\"body\"], R, ExchangeOf<S>>,\n    aggregator?: EnrichAggregatorOption<S[\"body\"], R>,\n  ): unknown {\n    this.pushStep(new EnrichStep<S[\"body\"], R>(enricher, aggregator));\n    return this.retype<unknown>();\n  }\n\n  /**\n   * Process the exchange with a custom function with full access to\n   * headers, body, and context. Use when you need more control than\n   * `.transform()` (which only operates on the body).\n   *\n   * @param processor - Function that receives and returns the exchange\n   * @returns The subclass builder re-typed to the processor's output body\n   * @template Return - Result body type (defaults to the current body)\n   */\n  process<Return = S[\"body\"]>(\n    processor:\n      | Processor<S[\"body\"], Return>\n      | CallableProcessor<S[\"body\"], Return, ExchangeOf<S>>,\n  ): Retyped<this, SetBody<S, Return>> {\n    this.pushStep(new ProcessStep<S[\"body\"], Return>(processor));\n    return this.retype<Return>();\n  }\n\n  /**\n   * Set or override a single header on the current exchange. Body type is\n   * unchanged.\n   *\n   * @param key - Header key to set (e.g. `x-request-id`, `routecraft.custom`)\n   * @param valueOrFn - Static value or a function returning the value from the exchange\n   * @returns This builder (same subclass, same body type)\n   */\n  header(\n    key: string,\n    valueOrFn:\n      | HeaderLiteral\n      | ((exchange: ExchangeOf<S>) => HeaderValue | Promise<HeaderValue>),\n  ): this {\n    this.pushStep(new HeaderStep<S[\"body\"]>(key, valueOrFn));\n    return this;\n  }\n\n  /**\n   * Establish the authenticated principal for the exchange. The resolver\n   * returns identity claims you have verified yourself (an e-mail sender, a\n   * Slack signature, a webhook HMAC); they are minted into a branded\n   * principal and attached to the exchange. Return `undefined` to leave the\n   * caller anonymous. Body type is unchanged.\n   *\n   * This is the explicit, greppable way to mint identity. `authorize()`\n   * trusts only principals established this way (or by a source verifier);\n   * a plain object written via `.header(\"routecraft.auth.principal\", ...)`\n   * is rejected. Sugar over the `authenticate()` helper.\n   *\n   * @param resolver - Returns the caller's claims, or `undefined` to skip\n   * @returns This builder (same subclass, same body type)\n   *\n   * @example\n   * ```ts\n   * craft()\n   *   .from(mail(\"INBOX\"))\n   *   .filter(verifiedSenders)\n   *   .authenticate((ex) => {\n   *     // The mail source attaches the computed sender to a header.\n   *     const sender = ex.headers[\"routecraft.mail.sender\"];\n   *     return {\n   *       scheme: \"email\",\n   *       subject: sender.address,\n   *       roles: sender.address.endsWith(\"@acme.com\") ? [\"internal\"] : [],\n   *     };\n   *   })\n   *   .authorize({ roles: [\"internal\"] })\n   *   .to(dest)\n   * ```\n   */\n  authenticate(resolver: CallableAuthenticator<S[\"body\"]>): this {\n    this.pushStep(new AuthenticateStep<S[\"body\"]>(resolver));\n    return this;\n  }\n\n  /**\n   * Mark the exchange's principal as being exercised by an actor (an agent,\n   * a service) on the subject's behalf. The resolver returns the actor's\n   * identity claims plus the consent-derived scope ceiling; they are minted\n   * into a delegated principal (subject unchanged, actor set, scopes\n   * intersected) and attached to the exchange. Body type is unchanged.\n   *\n   * A resolver that returns `undefined` (no consent record) fails closed by\n   * default: the subject's direct principal is STRIPPED so the continuation\n   * runs anonymous and downstream `authorize()` refuses with RC5012. An\n   * actor downstream must never inherit a caller's full direct authority\n   * precisely because consent is absent. The strip skips anonymous\n   * exchanges, already-delegated principals, and autonomous agent subjects\n   * (`subjectProfile: \"ai_agent\"`). Pass `{ otherwise: \"keep\" }` when the\n   * continuation serves the caller directly and an ungranted caller should\n   * keep acting as themselves.\n   *\n   * Sugar over the `delegate()` helper; see it for the full semantics\n   * (scope intersection, role pass-through, chain nesting, mayAct\n   * enforcement). Requires an authentic principal on the exchange when a\n   * directive is returned.\n   *\n   * @param resolver - Returns the delegation directive, or `undefined`\n   * @param options - No-consent behavior; default `{ otherwise: \"drop\" }`\n   * @returns This builder (same subclass, same body type)\n   *\n   * @example\n   * ```ts\n   * craft()\n   *   .from(mail(\"INBOX\"))\n   *   .authenticate(mailPrincipal)\n   *   .delegate((ex) => {\n   *     const grant = grants.find(ex.principal?.subject, \"agent:zoe\")\n   *     if (!grant) return undefined // no consent: principal is dropped\n   *     return { actor: zoeIdentity, scopes: grant.scopes, grantId: grant.id }\n   *   })\n   *   .to(agent(\"zoe\"))\n   * ```\n   */\n  delegate(\n    resolver: CallableDelegator<S[\"body\"]>,\n    options?: DelegateStepOptions,\n  ): this {\n    this.pushStep(new DelegateStep<S[\"body\"]>(resolver, options));\n    return this;\n  }\n\n  /**\n   * Execute a side effect without changing the data. Fire-and-forget --\n   * the tap runs asynchronously (tracked for drain) while the main flow\n   * continues. Tap receives a snapshot of the exchange (body/headers\n   * cloned). Accepts a Destination (send), a fetch-only Enricher (fetch and\n   * discard, e.g. `.tap(http({ url }))` as a fire-and-forget call), or a\n   * function form. Errors are emitted as events and rethrown for\n   * observability, but do not stop the pipeline.\n   *\n   * @param target - Destination, Enricher, or callable for the side effect\n   * @returns This builder (same subclass, same body type)\n   */\n  tap(target: TapTarget<S[\"body\"], ExchangeOf<S>>): this {\n    this.pushStep(new TapStep<S[\"body\"]>(target));\n    return this;\n  }\n\n  /**\n   * Filter the exchange based on a predicate. Return `true` to keep the\n   * exchange, `false` to drop it, or `{ reason: string }` to drop with\n   * an explanation recorded in telemetry.\n   *\n   * @param filter - Filter adapter or callable predicate\n   * @returns This builder (same subclass, same body type)\n   */\n  filter(\n    filter: Filter<S[\"body\"]> | CallableFilter<S[\"body\"], ExchangeOf<S>>,\n  ): this {\n    this.pushStep(new FilterStep<S[\"body\"]>(filter));\n    return this;\n  }\n\n  /**\n   * Sample exchanges by count or time interval, passing the admitted ones\n   * and dropping the rest (silently, like a `filter` returning false).\n   * Useful for reducing volume from a high-frequency source while staying\n   * representative. Pass exactly one of `every` (count-based: every Nth\n   * exchange) or `intervalMs` (time-based: the first exchange per window).\n   * Sampler state is per-route.\n   *\n   * @param options - `{ every }` for count-based or `{ intervalMs }` for time-based sampling\n   * @returns This builder (same subclass, same body type)\n   */\n  sample(options: SampleOptions): this {\n    this.pushStep(new SampleStep(options));\n    return this;\n  }\n\n  /**\n   * Suppress duplicate exchanges by a derived key, so the same input is not\n   * processed more than once. The key is derived from the body by default\n   * (SHA-256 of its JSON serialisation) or from an explicit `key` function.\n   * A key is reserved on entry and committed when the exchange completes\n   * (released on failure, so an errored input may retry); a duplicate is\n   * dropped silently. State is in-memory and per-route.\n   *\n   * @param options - Optional `key` deriver, `ttl` (ms), and `maxKeys` bound\n   * @returns This builder (same subclass, same body type)\n   */\n  dedupe(options?: DedupeOptions): this {\n    this.pushStep(new DedupeStep(options));\n    return this;\n  }\n\n  /**\n   * Validate the exchange body using a Validator adapter or callable. On\n   * success the (possibly coerced) return value replaces the body. On\n   * failure the adapter throws and the route error handler (if configured)\n   * or the default error path handles it. For Standard Schema, prefer the\n   * `.schema()` sugar or pass the `schema()` factory.\n   *\n   * @param validator - Validator adapter or callable\n   * @returns The subclass builder re-typed to the validator's output body\n   * @template R - Output body type after validation (defaults to the current body)\n   */\n  validate<R = S[\"body\"]>(\n    validator:\n      Validator<S[\"body\"], R> | CallableValidator<S[\"body\"], R, ExchangeOf<S>>,\n  ): Retyped<this, SetBody<S, R>> {\n    this.pushStep(new ValidateStep<S[\"body\"], R>(validator));\n    return this.retype<R>();\n  }\n\n  /**\n   * Symbol-keyed append used by `registerDsl` to add sugar methods\n   * without exposing `pushStep` as public API. Lives on the base so\n   * both `RouteBuilder` and `PathBuilder` inherit it and registered\n   * sugar works on both.\n   *\n   * @internal\n   */\n  [PUSH_STEP]<T extends Adapter>(step: Step<T>): this {\n    this.pushStep(step);\n    return this;\n  }\n}\n","import { ENRICH_MERGE_TYPE } from \"../brand.ts\";\nimport {\n  type Adapter,\n  type Step,\n  type StepContext,\n  type StepOutcome,\n  type StepSignalContext,\n  extractOutcomeMetadata,\n  toSignalContext,\n} from \"../types.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  getExchangeContext,\n  DefaultExchange,\n} from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { hasFetch } from \"./adapter-roles.ts\";\nimport {\n  resolveAdapterOverride,\n  invokeSendOverride,\n} from \"../testing-hooks.ts\";\nimport { DEFER_HOST } from \"../dsl-symbol.ts\";\nimport type { DeferCapableStep, DeferSite } from \"../deferral/sites.ts\";\nimport { convertDeferSignal, isDeferSignal } from \"../deferral/signal.ts\";\n\n/**\n * Function form of an enricher: receives the exchange and produces a value\n * (a lookup result, a file's parsed content, an API response). Used with\n * `.enrich()`, and accepted by `.to()` / `.tap()` where the returned value\n * replaces the body / is discarded respectively.\n *\n * The second argument carries the step's {@link StepSignalContext}: when an\n * enclosing `.timeout()` expires, `ctx.signal` aborts, so an enricher doing\n * cancellation-aware IO can forward it (`fetch(url, { signal })`). Declaring\n * only the first parameter remains valid.\n *\n * @template T - Current body type\n * @template R - Produced value type\n */\nexport type CallableEnricher<\n  T = unknown,\n  R = unknown,\n  Ex extends Exchange<T> = Exchange<T>,\n> = (exchange: Ex, ctx?: StepSignalContext) => Promise<R> | R;\n\n/**\n * Enricher adapter: pulls a value IN per exchange (HTTP GET, file read, IMAP\n * fetch, LLM call). Used with `.enrich()`; also accepted by `.to()` (the\n * result replaces the body) and `.tap()` (the result is discarded).\n *\n * The pull-in counterpart of {@link Destination}: `send` pushes out and is\n * void, `fetch` pulls in and produces a value. An adapter may implement both\n * roles on one object (e.g. `file()`: send writes, fetch reads); the\n * operation keyword selects the role, and `.to()` prefers `send`.\n *\n * @template T - Current body type\n * @template R - Produced value type\n */\nexport interface Enricher<T = unknown, R = unknown> extends Adapter {\n  fetch: CallableEnricher<T, R>;\n}\n\n/**\n * Aggregator used by `.enrich()` to merge the fetched value with the current\n * exchange. Receives the original exchange and the enrichment result; returns\n * the (derived) exchange.\n *\n * @template T - Current body type\n * @template R - Type produced by the enricher\n */\nexport type EnrichAggregator<T = unknown, R = unknown> = (\n  original: Exchange<T>,\n  enrichmentData: R,\n) => Exchange<T>;\n\n/**\n * When an aggregator is branded with [ENRICH_MERGE_TYPE], `.enrich()` infers the result body as `Current & shape`.\n * Used by `only(getValue, into)` when `into` is a string literal for type inference.\n */\nexport type EnrichMergeShape = Record<string, unknown>;\n\n/**\n * Returns an aggregator for `.enrich()` that merges a single value from the enrichment result into the body.\n *\n * - `getValue(enrichmentData)` extracts the value; null/undefined are not merged.\n * - If `into` is omitted: plain objects are spread onto body; primitives go to `body.stdout`; arrays to `body.array`.\n * - If `into` is provided: the value is set at `body[into]`. When `into` is a string literal, the builder infers body as `Current & { [into]: V }`.\n *\n * @param getValue - Function to extract the value from the enrichment result\n * @param into - Optional key to set on body (enables type inference when a string literal)\n * @returns An aggregator usable with `.enrich(enricher, aggregator)`\n *\n * @example\n * ```typescript\n * .enrich(http({ url: (ex) => `https://api.example.com/users/${ex.body.userId}` }), only((r) => r.body.name, 'userName'))\n * // Body type becomes Current & { userName: string }\n * ```\n */\nexport function only<R, V, K extends string>(\n  getValue: (enrichmentData: R) => V,\n  into: K,\n): EnrichAggregator<unknown, unknown> & {\n  [ENRICH_MERGE_TYPE]: Record<K, V>;\n};\nexport function only<T = unknown, R = unknown, V = unknown>(\n  getValue: (enrichmentData: R) => V,\n  into?: string,\n): EnrichAggregator<T, R>;\nexport function only<T = unknown, R = unknown, V = unknown>(\n  getValue: (enrichmentData: R) => V,\n  into?: string,\n): EnrichAggregator<T, R> {\n  return (original: Exchange<T>, enrichmentData: R): Exchange<T> => {\n    const value = getValue(enrichmentData);\n    if (value === undefined || value === null) {\n      return original;\n    }\n\n    const isBodyObject =\n      typeof original.body === \"object\" && original.body !== null;\n    const originalBody = isBodyObject\n      ? (original.body as Record<string, unknown>)\n      : { stdout: original.body };\n\n    if (into !== undefined) {\n      return { ...original, body: { ...originalBody, [into]: value } as T };\n    }\n\n    const isPlainObject =\n      typeof value === \"object\" && value !== null && !Array.isArray(value);\n    if (isPlainObject) {\n      return {\n        ...original,\n        body: {\n          ...originalBody,\n          ...(value as Record<string, unknown>),\n        } as T,\n      };\n    }\n    if (Array.isArray(value)) {\n      return { ...original, body: { ...originalBody, array: value } as T };\n    }\n    return { ...original, body: { ...originalBody, stdout: value } as T };\n  };\n}\n\n/**\n * No-op aggregator for `.enrich()`: returns the original exchange unchanged (enrichment is ignored).\n * Use when you only need the side effect of the fetch (e.g. warming a cache) while gating the pipeline on it.\n *\n * @example\n * ```typescript\n * .enrich(http({ url: 'https://api.example.com/ping' }), none())\n * ```\n */\nexport const none = <T = unknown, R = unknown>(): EnrichAggregator<T, R> => {\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- second param required by signature, intentionally unused\n  return (original: Exchange<T>, _ignored: R): Exchange<T> => {\n    return original;\n  };\n};\n\n/**\n * Aggregator type accepted by EnrichStep. Includes `only()` return type (with [ENRICH_MERGE_TYPE]) for body-type inference.\n */\nexport type EnrichAggregatorOption<T, R> =\n  | EnrichAggregator<T, R>\n  | (EnrichAggregator<unknown, unknown> & {\n      [ENRICH_MERGE_TYPE]?: EnrichMergeShape;\n    });\n\n/**\n * Step that enriches the exchange with data pulled in by an {@link Enricher}\n * (e.g. HTTP lookup, file read). With no aggregator the fetched value\n * REPLACES the body; pass an aggregator (`only()`, `none()`, or a custom\n * function) to merge instead.\n */\nexport class EnrichStep<T = unknown, R = unknown>\n  implements Step<Adapter>, DeferCapableStep\n{\n  operation: OperationType = OperationType.ENRICH;\n  adapter: Adapter;\n  aggregator: EnrichAggregatorOption<T, R> | undefined;\n  /** Assigned by the defer-site walk when the adapter is defer-capable. */\n  deferSite?: DeferSite;\n  /** Why the walk refused a site (fan-out or sealed side flow), when it did. */\n  deferRefusal?: string;\n\n  /** This step hosts its own defer site; wrappers forward here. @internal */\n  [DEFER_HOST](): DeferCapableStep {\n    return this;\n  }\n\n  constructor(\n    enricher: Enricher<T, R> | CallableEnricher<T, R>,\n    aggregator?: EnrichAggregatorOption<T, R>,\n  ) {\n    this.adapter =\n      typeof enricher === \"function\" ? { fetch: enricher } : enricher;\n    this.aggregator = aggregator;\n  }\n\n  async execute(\n    exchange: Exchange<T>,\n    ctx?: StepContext,\n  ): Promise<StepOutcome> {\n    // Resolve a test-time override (if any) registered on the context.\n    const override = resolveAdapterOverride(\n      this.adapter,\n      getExchangeContext(exchange),\n      \"send\",\n    );\n\n    // Pull the enrichment data through the fetch slot (or the mock handler\n    // when an override is registered).\n    let enrichmentData: R;\n    try {\n      if (override) {\n        enrichmentData = (await invokeSendOverride(\n          exchange,\n          this.adapter,\n          override,\n        )) as R;\n      } else {\n        if (!hasFetch<T, R>(this.adapter)) {\n          throw rcError(\"RC5003\", undefined, {\n            message: \"`.enrich()` target does not implement `fetch`\",\n            suggestion:\n              \"Enrichment pulls data in; pass an Enricher (fetch) or a function form. Push-out sends belong in `.to()` / `.tap()`\",\n          });\n        }\n        enrichmentData = await Promise.resolve(\n          this.adapter.fetch(exchange, toSignalContext(ctx)),\n        );\n      }\n    } catch (err) {\n      // Converted here, inside the step, so a step-scope wrapper never\n      // observes the raw throw (a retry wrapper would re-run the adapter\n      // and charge the deferred work twice).\n      if (isDeferSignal(err)) {\n        return convertDeferSignal(this, exchange, err);\n      }\n      throw err;\n    }\n\n    // The metadata rides the OUTCOME, not the step: Step instances are\n    // shared across exchanges.\n    const metadata = extractOutcomeMetadata(\n      this.adapter,\n      enrichmentData,\n      !!override,\n      \"getMetadata\",\n      exchange,\n    );\n\n    // No aggregator: the fetched value replaces the body. `undefined` (e.g.\n    // a mock override with no handler) leaves the exchange unchanged.\n    if (this.aggregator === undefined) {\n      const next =\n        enrichmentData === undefined\n          ? (exchange as Exchange<unknown>)\n          : DefaultExchange.rewrap<unknown>(exchange, {\n              body: enrichmentData,\n            });\n      return {\n        kind: \"continue\",\n        exchange: next,\n        ...(metadata ? { metadata } : {}),\n      };\n    }\n\n    // Aggregator returns a (possibly new) exchange. The fast-path is\n    // identity equality (aggregator returned the same input); anything\n    // else -- plain spread, freshly constructed DefaultExchange,\n    // foreign-context exchange -- is always rewrapped onto THIS\n    // exchange's internals so route binding / context survive the\n    // aggregator and principal sticky-set semantics stay consistent.\n    const result = (await Promise.resolve(\n      this.aggregator(exchange, enrichmentData),\n    )) as Exchange<T>;\n\n    const next: Exchange<T> =\n      result === exchange\n        ? exchange\n        : DefaultExchange.rewrap<T>(exchange, {\n            body: result.body,\n            headers: result.headers,\n          });\n\n    return {\n      kind: \"continue\",\n      exchange: next,\n      ...(metadata ? { metadata } : {}),\n    };\n  }\n}\n","import {\n  type Exchange,\n  getExchangeContext,\n  getExchangeRoute,\n  HeadersKeys,\n  DefaultExchange,\n  markDropped,\n} from \"../exchange.ts\";\nimport { rcError, RoutecraftError } from \"../error.ts\";\nimport { isRoutecraftError } from \"../brand.ts\";\nimport { isRecovery, applyDropDirective } from \"../recovery.ts\";\nimport type { ErrorHandler } from \"../route.ts\";\nimport type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport { WrapperStep } from \"./wrapper.ts\";\n\n/**\n * Step-scope `.error()` handler. Wraps a single step. On wrapped-step\n * success the pipeline continues unchanged; on wrapped-step failure\n * the user-supplied handler runs, its return value replaces\n * `exchange.body`, and the pipeline continues with the next step.\n *\n * Mirrors the route-level `errorHandler` semantics (`(err, exchange,\n * forward) => unknown`), but bound to one step instead of the whole\n * pipeline. The handler receives the same `forward` callable as the\n * route-level handler, so a step-scope handler can delegate recovery\n * to a direct route the same way:\n *\n * ```ts\n * .error((err, ex, forward) => forward('errors.dlq', ex.body))\n * .to(http({ url: 'https://flaky.api/x' }))\n * ```\n *\n * If the handler itself throws, the wrapper rethrows so the route's\n * outer catch in `runPipeline` fires the route-level handler when one is\n * defined, or the default `route:error` / `context:error` /\n * `route:exchange:failed` path otherwise. The route is NOT stopped.\n *\n * Emits scope-aware lifecycle events:\n * - `route:error-handler:invoked`  ({ scope: \"step\", stepLabel })\n * - `route:error-handler:recovered` on handler success\n * - `route:error-handler:failed`    on handler throw (rethrown)\n */\nexport class ErrorWrapperStep<\n  T extends Adapter = Adapter,\n> extends WrapperStep<T> {\n  constructor(\n    inner: Step<T>,\n    private readonly handler: ErrorHandler,\n  ) {\n    super(inner);\n  }\n\n  protected override describeOptions(): unknown {\n    return { handler: this.handler };\n  }\n\n  protected override async runInner(\n    exchange: Exchange,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const route = getExchangeRoute(exchange);\n    const context = getExchangeContext(exchange);\n    const stepLabel = this.label ?? String(this.operation);\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n\n    // Run the inner step and pass its outcome through unchanged on\n    // success. The inner never sees the work queue, so a failure here\n    // has scheduled nothing; recovery simply substitutes an outcome.\n    try {\n      return await this.inner.execute(exchange, ctx);\n    } catch (rawInnerError) {\n      // Normalise the thrown value to `RoutecraftError` so the\n      // step-scope handler receives the same shape the route-scope\n      // handler does (route.ts's `processError` does the same).\n      // Handlers that branch on `error.rc` / `error.meta.message`\n      // work in both positions without special-casing.\n      const innerError: RoutecraftError = isRoutecraftError(rawInnerError)\n        ? (rawInnerError as RoutecraftError)\n        : rcError(\"RC5001\", rawInnerError, {\n            message:\n              rawInnerError instanceof Error\n                ? rawInnerError.message\n                : String(rawInnerError),\n          });\n      const routeId = route?.definition.id;\n      if (route && context && routeId) {\n        context.emit(\"route:error-handler:invoked\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          originalError: innerError,\n          failedOperation: stepLabel,\n          scope: \"step\",\n          stepLabel,\n        });\n      }\n\n      try {\n        const forward = route?.getForward(exchange);\n        if (!forward) {\n          // Should not happen in normal pipelines (route is always\n          // bound), but fail loudly rather than silently mis-recover.\n          throw rcError(\"RC5001\", innerError, {\n            message:\n              \"Step-scope .error() handler ran without a route binding; cannot build forward()\",\n          });\n        }\n        const recovered = await this.handler(innerError, exchange, forward);\n        if (isRecovery(recovered)) {\n          if (recovered.kind === \"rethrow\") {\n            // Declarative equivalent of `throw error` inside the\n            // handler: fall through to the handler-threw path below with\n            // the original error so the route-level cascade fires.\n            throw innerError;\n          }\n          // `recovery.drop()`: resolve the error by discarding the\n          // exchange (shared semantics in applyDropDirective). The\n          // forward guard above already threw when no route is bound, so\n          // context/routeId are present here in any framework-built\n          // pipeline; the fallback mark keeps the drop flag correct for\n          // synthetic exchanges in unit tests.\n          if (route && context && routeId) {\n            applyDropDirective({\n              context,\n              routeId,\n              exchange,\n              originalError: innerError,\n              failedOperation: stepLabel,\n              correlationId,\n              reason: recovered.reason,\n              scope: \"step\",\n              stepLabel,\n            });\n          } else {\n            markDropped(exchange);\n          }\n          return { kind: \"drop\" };\n        }\n        // Build a recovered exchange (the original is frozen). Inheriting\n        // identity / internals via rewrap keeps event correlation\n        // (exchangeId, route binding) consistent across the recovery.\n        const recoveredExchange = DefaultExchange.rewrap(exchange, {\n          body: recovered,\n        });\n\n        if (route && context && routeId) {\n          context.emit(\"route:error-handler:recovered\", {\n            routeId,\n            exchangeId: exchange.id,\n            correlationId,\n            originalError: innerError,\n            failedOperation: stepLabel,\n            recoveryStrategy: \"step-error-handler\",\n            scope: \"step\",\n            stepLabel,\n          });\n        }\n        return { kind: \"continue\", exchange: recoveredExchange };\n      } catch (handlerError) {\n        if (route && context && routeId) {\n          context.emit(\"route:error-handler:failed\", {\n            routeId,\n            exchangeId: exchange.id,\n            correlationId,\n            originalError: innerError,\n            failedOperation: stepLabel,\n            recoveryStrategy: \"step-error-handler\",\n            scope: \"step\",\n            stepLabel,\n          });\n        }\n        // Rethrow so `runPipeline` cascades to the route-level handler\n        // (or the default error path when none is set). Wrap raw\n        // throws in `RoutecraftError` for consistent observability;\n        // pass-through if already an RoutecraftError.\n        throw handlerError instanceof RoutecraftError\n          ? handlerError\n          : rcError(\"RC5001\", handlerError, {\n              message: `Step-scope .error() handler for \"${stepLabel}\" threw`,\n            });\n      }\n    }\n  }\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { type Duration, parseDuration } from \"../shared/duration.ts\";\nimport {\n  type Exchange,\n  DefaultExchange,\n  isDropped,\n  markDropped,\n} from \"../exchange.ts\";\nimport { wrapperEventScope } from \"./event-scope.ts\";\nimport { rcError } from \"../error.ts\";\nimport { isRoutecraftError } from \"../brand.ts\";\nimport { hashExchangeBody } from \"./hash-body.ts\";\nimport { principalIdentity } from \"./principal-identity.ts\";\nimport type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport type { RouteDefinition } from \"../route.ts\";\nimport { WrapperStep } from \"./wrapper.ts\";\nimport { nestedStepsOf } from \"../deferral/sites.ts\";\nimport {\n  definitionFingerprint,\n  stepDefinitionFingerprint,\n} from \"../deferral/hash.ts\";\nimport {\n  type CacheProvider,\n  defaultMemoryCacheProvider,\n} from \"./cache-provider.ts\";\n\n/**\n * Options for `.cache()`, at route scope (before `.from()`) and step scope\n * (after `.from()`).\n *\n * @template Current Body type entering the cached route or step.\n */\nexport interface CacheOptions<Current = unknown> {\n  /**\n   * Derive the cache key from the exchange. The returned string is the\n   * identity used by the provider's `get` / `set`.\n   *\n   * When omitted, the key is a SHA-256 over the route id (plus, at step\n   * scope, the cache's site, and at route scope, a fingerprint of the\n   * cached pipeline: see `CacheKeyScope`), the principal's\n   * `issuer` and `subject` plus those of every `actor` hop when the\n   * exchange carries one, and a SHA-256 of `JSON.stringify(body)`. Two routes, two cached steps, or two\n   * callers therefore never share an entry by accident. The route id is\n   * part of the key, so give the route an `.id()`: an unnamed route gets\n   * a fresh id on every start, and its entries in an external provider\n   * stop matching after a restart.\n   *\n   * The default needs a body. An exchange whose body is `undefined` (a\n   * bodiless `http()` GET, whose input lives in the\n   * `routecraft.http.params` / `routecraft.http.query` headers) fails\n   * with `RC5029`, as does a body `JSON.stringify` cannot represent\n   * (a top-level function or symbol, a circular reference, a `BigInt`).\n   * Nested functions and symbols are silently dropped by `JSON.stringify`,\n   * so bodies differing only there share a key. Supply `key` for those. A\n   * `null` body is keyable.\n   *\n   * A custom `key` is used VERBATIM: nothing is added to it. Every route\n   * and step on the same provider shares entries for equal keys, and so\n   * does every caller, so put the route (`ex.headers[HeadersKeys.ROUTE_ID]`)\n   * and the caller's identity (`ex.principal?.issuer` and `subject`) in\n   * the key, and drop the principal only when every caller sees the same\n   * answer. On a route that admits delegation, add the current actor\n   * (`ex.principal?.actor?.issuer` and `subject`) as well, or two delegates\n   * acting for the same subject share entries.\n   *\n   * Performance: the default hashes a JSON serialisation of the body on\n   * every exchange. For hot paths or large bodies (file contents, large\n   * payloads), supply a `key` that returns a stable identifier already\n   * to hand (an id field, a content hash in a header, a tuple of the\n   * relevant fields) to avoid re-serialising and re-hashing.\n   */\n  key?: (exchange: Exchange<Current>) => string;\n  /**\n   * Time to live. After expiry, the next execution with the same key\n   * recomputes the value. When omitted, the provider's default applies\n   * (the bundled in-memory provider keeps entries until LRU eviction).\n   */\n  ttl?: Duration;\n  /**\n   * Cache backend. Defaults to a process-wide in-memory provider. Pass\n   * a custom provider (Redis, multi-tier, file-backed, etc.) by\n   * constructing an implementation of {@link CacheProvider} and\n   * handing it in here.\n   */\n  provider?: CacheProvider;\n}\n\n/**\n * Where a cache sits, which the default key namespaces its entries by.\n *\n * `site` is the JSON of `[index, stackIndex, below, fingerprint]`: the\n * step's pre-order index in the route's step tree, the cache's index in\n * that step's full wrapper stack, `[kind, optionsFingerprint]` for each\n * wrapper between the cache and the innermost step, and a fingerprint of\n * the innermost step's definition (operation, label, adapter id and\n * options, callable source). It derives from the route definition alone,\n * so every process running the same route source computes the same site\n * and shares entries in an external provider. Moving a step, reordering\n * its wrappers, or changing its definition or the options of a wrapper\n * below the cache (an `.error()` handler, a `.retry()` policy) changes the\n * site, so those edits cause misses rather than replays of entries the old\n * definition produced.\n *\n * Wrappers above the cache contribute their count (through `stackIndex`)\n * but not their options: they run outside the cached computation and none\n * rewrites the exchange it passes inward, so they cannot change what is\n * stored for a key. The fingerprints do not cover what a callable closes\n * over or config read at run time; put those in an explicit key when they\n * change the output.\n *\n * At route scope there is no site; `pipeline` is the\n * {@link pipelineFingerprint} of every step a hit skips, nested branches\n * and wrapper options included, so editing any of them misses rather than\n * replaying what the old pipeline produced. The route's `.input()` and\n * `.output()` schemas stay out: input validation runs before the cache\n * check (its result is the body the key hashes) and output validation runs\n * after the pipeline on a hit as on a miss, so neither shapes a stored\n * entry.\n *\n * @internal\n */\nexport type CacheKeyScope =\n  | {\n      readonly kind: \"route\";\n      readonly routeId: string;\n      readonly pipeline: string;\n    }\n  | { readonly kind: \"step\"; readonly routeId: string; readonly site: string };\n\n/**\n * Internal resolved shape of {@link CacheOptions}: every field is\n * populated, with defaults filled in. Shared between the step-scope\n * wrapper and the route-scope filter steps.\n *\n * @internal\n */\nexport interface ResolvedCacheOptions<Current = unknown> {\n  key: (exchange: Exchange<Current>, scope: CacheKeyScope) => string;\n  /** No custom `key` was supplied, so `key` is {@link defaultCacheKey}. */\n  usesDefaultKey: boolean;\n  ttl: number | undefined;\n  provider: CacheProvider;\n}\n\n/**\n * Resolve a user-supplied {@link CacheOptions} into a fully populated\n * {@link ResolvedCacheOptions}, filling defaults: {@link defaultCacheKey}\n * for `key`, no TTL, and the module-level in-memory provider. A custom\n * `key` ignores the scope.\n *\n * @internal\n */\nexport function resolveCacheOptions<Current = unknown>(\n  options: CacheOptions<Current> = {},\n): ResolvedCacheOptions<Current> {\n  const custom = options.key;\n  return {\n    key: custom ? (exchange) => custom(exchange) : defaultCacheKey,\n    usesDefaultKey: custom === undefined,\n    ttl:\n      options.ttl === undefined\n        ? undefined\n        : parseDuration(options.ttl, \"cache({ ttl })\"),\n    provider: options.provider ?? defaultMemoryCacheProvider,\n  };\n}\n\n/**\n * The default cache key: a SHA-256 over the JSON tuple\n * `[scope.kind, routeId, site | pipeline, principalChain | null, bodyHash]`,\n * where `principalChain` is `[issuer | null, subject]` for the principal\n * and each `actor` hop.\n * Encoding the tuple as JSON keeps the fields from running into each\n * other; hashing the body first keeps a large body out of the second\n * serialisation.\n *\n * @throws RC5029 when the body is `undefined` (nothing to key on) or is\n *   not JSON-serialisable.\n * @internal\n */\nexport function defaultCacheKey(\n  exchange: Exchange<unknown>,\n  scope: CacheKeyScope,\n): string {\n  if (exchange.body === undefined) {\n    throw rcError(\"RC5029\", undefined, {\n      message:\n        `Default cache key for route \"${scope.routeId}\" has nothing to key on: the exchange body is undefined. ` +\n        \"A bodiless request such as an http() GET carries its input in the routecraft.http.params and \" +\n        \"routecraft.http.query headers, which the default key does not read. Supply a key, e.g. \" +\n        \"cache({ key: (ex) => JSON.stringify([ex.headers['routecraft.route'], ex.principal?.issuer, \" +\n        \"ex.principal?.subject, ex.headers['routecraft.http.params'], ex.headers['routecraft.http.query']]) }). \" +\n        \"A custom key is used verbatim: drop the principal only when every caller sees the same answer, \" +\n        \"and on a route that admits delegation add each ex.principal.actor hop as well.\",\n    });\n  }\n  let bodyHash: string;\n  try {\n    bodyHash = hashExchangeBody(exchange.body);\n  } catch (err) {\n    throw rcError(\"RC5029\", err, {\n      message:\n        \"Default cache key derivation failed: the exchange body is not JSON-serialisable. \" +\n        \"Supply an explicit `key` function in cache({ key: ... }).\",\n    });\n  }\n  const identity = JSON.stringify([\n    scope.kind,\n    scope.routeId,\n    scope.kind === \"step\" ? scope.site : scope.pipeline,\n    principalIdentity(exchange.principal),\n    bodyHash,\n  ]);\n  return createHash(\"sha256\").update(identity).digest(\"hex\");\n}\n\n/**\n * Give every step-scope cache in a finalised route its\n * {@link CacheKeyScope} site. Runs from `RouteBuilder.build()`, walking the\n * step tree in pre-order and looking through wrapper stacks, so a cache\n * inside a `.choice()` branch or under an outer `.retry()` is found too.\n *\n * @returns Whether any step-scope cache in the route uses the default key.\n * @internal\n */\nexport function assignCacheSites(route: RouteDefinition): boolean {\n  let next = 0;\n  let usesDefaultKey = false;\n  const visit = (steps: ReadonlyArray<Step<Adapter>>): void => {\n    for (const step of steps) {\n      const position = next++;\n      const { stack, innermost } = unwrapStack(step);\n      const fingerprint = stepDefinitionFingerprint(innermost);\n      stack.forEach((wrapper, index) => {\n        if (!(wrapper instanceof CacheWrapperStep)) return;\n        const below = stack.slice(index + 1).map(wrapperIdentity);\n        wrapper.assignSite(\n          JSON.stringify([position, index, below, fingerprint]),\n        );\n        usesDefaultKey ||= wrapper.usesDefaultKey;\n      });\n      for (const nested of nestedStepsOf(step)) visit(nested.steps);\n    }\n  };\n  visit(route.steps);\n  return usesDefaultKey;\n}\n\n/**\n * Fingerprint of a whole pipeline, which a route-scope cache folds into\n * its default key because a hit skips every step in it. Each step\n * contributes `[kind, optionsFingerprint]` for every wrapper in its stack,\n * the innermost step's definition fingerprint, and, for every nested\n * sub-pipeline, the fingerprint of the predicate selecting it (a\n * `.choice()` branch) and the nested pipeline's own description. Derived\n * from the definition alone, so every process running the same route\n * source computes the same digest.\n *\n * @internal\n */\nexport function pipelineFingerprint(\n  steps: ReadonlyArray<Step<Adapter>>,\n): string {\n  return createHash(\"sha256\")\n    .update(JSON.stringify(describePipeline(steps)))\n    .digest(\"hex\");\n}\n\nfunction describePipeline(steps: ReadonlyArray<Step<Adapter>>): unknown[] {\n  return steps.map((step) => {\n    const { stack, innermost } = unwrapStack(step);\n    return [\n      stack.map(wrapperIdentity),\n      stepDefinitionFingerprint(innermost),\n      nestedStepsOf(step).map((nested) => [\n        nested.predicate === undefined\n          ? null\n          : definitionFingerprint(nested.predicate),\n        describePipeline(nested.steps),\n      ]),\n    ];\n  });\n}\n\n/** A step's wrapper stack, outermost first, and the step it folds around. */\nfunction unwrapStack(step: Step<Adapter>): {\n  stack: WrapperStep<Adapter>[];\n  innermost: Step<Adapter>;\n} {\n  const stack: WrapperStep<Adapter>[] = [];\n  let innermost: Step<Adapter> = step;\n  while (innermost instanceof WrapperStep) {\n    stack.push(innermost);\n    innermost = innermost.wrapped;\n  }\n  return { stack, innermost };\n}\n\nfunction wrapperIdentity(wrapper: WrapperStep<Adapter>): [string, string] {\n  return [\n    wrapper.constructor.name,\n    definitionFingerprint(wrapper.fingerprintOptions),\n  ];\n}\n\n/**\n * Sentinel error thrown by the cache loader when the wrapped step\n * dropped the exchange (filter rejection, halt, etc.). Used to abort\n * the provider's `getOrCompute` so nothing is written to the cache,\n * while letting concurrent waiters observe the drop and mark their\n * own exchanges accordingly. Internal; never escapes the wrapper.\n */\nclass CacheLoaderDrop extends Error {\n  constructor() {\n    super(\"routecraft.cache.drop\");\n    this.name = \"CacheLoaderDrop\";\n  }\n}\n\n/**\n * Step-scope `.cache()` wrapper. On a cache hit, replaces\n * `exchange.body` with the cached value and skips the wrapped step. On\n * a miss, runs the wrapped step, caches its produced body, and lets\n * the pipeline continue normally. Errors from the wrapped step are\n * NOT cached and propagate to outer wrappers / route-level handlers; an\n * error reply the step returns without throwing is cached (see\n * `StepBuilderBase.cache`).\n *\n * The default key is namespaced by route id and by this wrapper's site\n * ({@link CacheKeyScope}), assigned by {@link assignCacheSites} when the\n * route is built. A wrapper\n * that never went through `RouteBuilder.build()` (constructed by hand)\n * gets a random site on first use, so it never shares entries with\n * another cache, at the cost of not sharing them across restarts either.\n *\n * Concurrent exchanges with the same derived key share a single\n * computation via the provider's `getOrCompute`, so a slow underlying\n * operation runs at most once per key per TTL window.\n *\n * Emits cache lifecycle events on the route's event bus:\n * - `route:cache:hit` when a cached value is reused.\n * - `route:cache:miss` when the wrapped step runs.\n * - `route:cache:stored` when a fresh value is written.\n * - `route:cache:failed` when key derivation or the provider throws.\n *\n * Known limitation: concurrent exchanges that share a single\n * `getOrCompute` computation (stampede dedupe) currently report\n * `route:cache:hit` for the waiters rather than a distinct \"deduped\" signal,\n * which can inflate hit-rate metrics. Tracked separately; needs a\n * provider-interface change to report whether the current call ran the\n * loader.\n *\n * Ordering note: a step-scope `.error()` placed INSIDE the cache\n * (`.cache().error(h).to(d)`) feeds the handler's recovery value into\n * the cache, so a fallback becomes the permanent cached answer for that\n * key. Put `.error()` OUTSIDE the cache (`.error(h).cache().to(d)`)\n * unless caching recovery results is intended.\n *\n * Route scope (`.cache()` before `.from()`) does not use this class; it\n * runs as the `cacheCheck` / `cacheStore` filter steps.\n */\nexport class CacheWrapperStep<\n  T extends Adapter = Adapter,\n> extends WrapperStep<T> {\n  readonly #options: ResolvedCacheOptions;\n  // The resolved `key` wraps a custom key in one adapter lambda whose\n  // source is the same for every cache, so fingerprint the original.\n  readonly #customKey: CacheOptions[\"key\"];\n  #site: string | undefined;\n\n  constructor(inner: Step<T>, options: CacheOptions = {}) {\n    super(inner);\n    this.#options = resolveCacheOptions(options);\n    this.#customKey = options.key;\n  }\n\n  protected override describeOptions(): unknown {\n    return { key: this.#customKey ?? null, ttl: this.#options.ttl ?? null };\n  }\n\n  /**\n   * Whether this cache derives its key with {@link defaultCacheKey}, which\n   * depends on the route id.\n   *\n   * @internal\n   */\n  get usesDefaultKey(): boolean {\n    return this.#options.usesDefaultKey;\n  }\n\n  /**\n   * Record this wrapper's position in its route. Called by\n   * {@link assignCacheSites}; see {@link CacheKeyScope}.\n   *\n   * @internal\n   */\n  assignSite(site: string): void {\n    this.#site = site;\n  }\n\n  protected override async runInner(\n    exchange: Exchange,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const { route, context, routeId, stepLabel, correlationId } =\n      wrapperEventScope(exchange, this);\n    const shouldEmit = route && context && routeId;\n    const site = (this.#site ??= `unbuilt:${randomUUID()}`);\n\n    let key: string;\n    try {\n      key = this.#options.key(exchange, { kind: \"step\", routeId, site });\n    } catch (err) {\n      if (shouldEmit) {\n        context.emit(\"route:cache:failed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          stepLabel,\n          scope: \"step\",\n          phase: \"key\",\n          error: err instanceof Error ? err.message : String(err),\n        });\n      }\n      throw isRoutecraftError(err)\n        ? err\n        : rcError(\"RC5029\", err, {\n            message: `cache({ key }) for \"${stepLabel}\" threw while deriving the cache key`,\n          });\n    }\n\n    let ranInner = false;\n    // Flips true once the inner step has produced its value inside the\n    // loader. Lets the catch below tell an inner-step failure (loader\n    // not yet resolved) from a provider write failure (loader resolved,\n    // `getOrCompute` rejected while caching).\n    let loaderResolved = false;\n    // Set only by the call that runs the loader (the cache miss). On a\n    // hit or stampede-dedup this stays undefined and the wrapper rewraps\n    // the current exchange with the cached body instead.\n    let producedExchange: Exchange | undefined;\n    let computed: unknown;\n\n    try {\n      computed = await this.#options.provider.getOrCompute(\n        key,\n        async () => {\n          ranInner = true;\n          const outcome = await this.inner.execute(exchange, ctx);\n          // A genuine drop is signalled by the drop outcome (filter\n          // reject / halt), NOT by an undefined body: a step such as\n          // `transform(() => undefined)` legitimately sets the body to\n          // undefined and must not be misread as a drop.\n          if (outcome.kind === \"drop\" || isDropped(exchange)) {\n            // Abort via sentinel so `getOrCompute` writes nothing.\n            throw new CacheLoaderDrop();\n          }\n          if (\n            outcome.kind === \"fanOut\" ||\n            outcome.kind === \"branch\" ||\n            outcome.kind === \"defer\"\n          ) {\n            // The wrapper caches and replays a single output. Fan-out\n            // would lose all but one child; a branch outcome carries\n            // live steps that cannot be cached; a defer exchange is\n            // mid-flight and must never be cache-stored. split / aggregate\n            // are already blocked at construction by WrapperStep; this\n            // guards choice and custom steps explicitly (the\n            // pre-outcome engine silently discarded a wrapped choice's\n            // branch steps instead).\n            throw rcError(\"RC5003\", undefined, {\n              message:\n                `.cache() cannot wrap \"${stepLabel}\": the step produced a \"${outcome.kind}\" ` +\n                `outcome, but cache replays a single output. Wrap a single-output step instead.`,\n            });\n          }\n          producedExchange = outcome.exchange;\n          loaderResolved = true;\n          return outcome.exchange.body;\n        },\n        this.#options.ttl,\n      );\n    } catch (err) {\n      if (err instanceof CacheLoaderDrop) {\n        // Mark this exchange (may be a concurrent waiter whose own\n        // inner never ran) so the template's empty-queue branch\n        // forwards a drop, not a live exchange.\n        markDropped(exchange);\n        if (shouldEmit) {\n          context.emit(\"route:cache:miss\", {\n            routeId,\n            exchangeId: exchange.id,\n            correlationId,\n            stepLabel,\n            scope: \"step\",\n            key,\n            dropped: true,\n          });\n        }\n        return { kind: \"drop\" };\n      }\n      // Attribute the failure:\n      // - `\"get\"`   provider read threw before the inner ran.\n      // - `\"inner\"` the wrapped step itself threw (loader not resolved).\n      // - `\"set\"`   the inner succeeded but the provider write threw.\n      const phase = !ranInner ? \"get\" : loaderResolved ? \"set\" : \"inner\";\n      if (shouldEmit) {\n        context.emit(\"route:cache:failed\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          stepLabel,\n          scope: \"step\",\n          phase,\n          key,\n          error: err instanceof Error ? err.message : String(err),\n        });\n      }\n      // Inner-step failures propagate unchanged so route-level handlers\n      // see the real cause (matching unwrapped step behaviour). Provider\n      // read / write failures map to the retryable RC5028 boundary code\n      // unless the provider already threw a RoutecraftError.\n      if (phase !== \"inner\" && !isRoutecraftError(err)) {\n        throw rcError(\"RC5028\", err, {\n          message: `cache() provider ${phase === \"get\" ? \"read\" : \"write\"} failed for \"${stepLabel}\"`,\n        });\n      }\n      throw err;\n    }\n\n    if (shouldEmit) {\n      context.emit(ranInner ? \"route:cache:miss\" : \"route:cache:hit\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        stepLabel,\n        scope: \"step\",\n        key,\n      });\n      if (ranInner) {\n        context.emit(\"route:cache:stored\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          stepLabel,\n          scope: \"step\",\n          key,\n          ...(this.#options.ttl !== undefined\n            ? { ttl: this.#options.ttl }\n            : {}),\n        });\n      }\n    }\n\n    // On a miss (this call ran the inner), forward the inner's produced\n    // exchange so its header mutations and body survive. On a hit or\n    // stampede-dedup the inner did not run for THIS exchange, so rewrap\n    // the current exchange with the cached body: a cache hit means the\n    // wrapped step's side effects (including header writes) did not\n    // happen for this exchange.\n    const forwarded =\n      ranInner && producedExchange !== undefined\n        ? producedExchange\n        : DefaultExchange.rewrap(exchange, { body: computed });\n    return { kind: \"continue\", exchange: forwarded };\n  }\n}\n","import { LRUCache } from \"lru-cache\";\n\nimport { rcError } from \"../error.ts\";\n\n/**\n * Internal storage envelope. Wrapping the value keeps `lru-cache`'s\n * non-nullable value constraint satisfied while still allowing `null`\n * to be a legitimate cached value (a bare `null` cannot be stored in\n * `lru-cache`, but `{ v: null }` can). A missing key returns\n * `undefined` from the LRU; a cached `null` returns `{ v: null }`, so\n * the two are never conflated.\n */\ntype CacheEnvelope = { v: unknown };\n\n/**\n * Pluggable backend for the `.cache()` operation. Implementations decide\n * where cached values live (in-memory, Redis, file-backed, multi-tier,\n * etc.) and how eviction works. The contract is async-by-default so\n * remote backends fit without breaking the call signature.\n *\n * A reference implementation backed by `lru-cache` ships as\n * {@link MemoryCacheProvider}. Custom providers can be supplied\n * per-operation via `cache({ provider })`; a future change will allow a\n * global default to be set on `CraftConfig` (tracked in #112).\n *\n * Stampede protection (deduping concurrent computations for the same\n * key) is the provider's responsibility via {@link getOrCompute} so the\n * dedupe strategy can match the backend. In-memory providers track an\n * in-flight Promise per key; distributed providers like Redis can use a\n * lock key or rely on the underlying store's atomicity.\n */\nexport interface CacheProvider {\n  /**\n   * Fetch a value by key. Returns `undefined` when there is no entry\n   * for the key (cache miss) or when the entry has expired. Treat\n   * `undefined` as \"miss\"; do not store `undefined` as a cached value.\n   *\n   * `null` is a valid cached value and is distinct from a miss: a\n   * cached `null` returns `null`, not `undefined`.\n   *\n   * @param key The cache key.\n   */\n  get(key: string): Promise<unknown>;\n\n  /**\n   * Store a value under `key`. When `ttl` is provided, the entry\n   * expires after `ttl` milliseconds; otherwise the provider's default\n   * expiry applies (which may be \"never\").\n   *\n   * `undefined` is not a storable value (it is the miss sentinel);\n   * implementations must reject it. `null` is storable.\n   *\n   * @param key The cache key.\n   * @param value The value to cache. Must not be `undefined`.\n   * @param ttl Optional time to live in milliseconds.\n   */\n  set(key: string, value: unknown, ttl?: number): Promise<void>;\n\n  /** Remove an entry by key. No-op if the key is absent. */\n  delete(key: string): Promise<void>;\n\n  /** Check existence without producing a \"hit\" side effect. */\n  has(key: string): Promise<boolean>;\n\n  /**\n   * Atomic \"get-or-compute\" with stampede protection. On a hit, returns\n   * the cached value. On a miss, runs `loader()` exactly once across\n   * concurrent callers with the same key and caches the result before\n   * resolving. If `loader` throws, the error propagates and nothing is\n   * cached.\n   *\n   * Wrappers and adapters should prefer this over manual\n   * `get` / `set` round-trips so the dedupe strategy stays with the\n   * provider.\n   *\n   * If `loader` resolves to `undefined`, treat it as a non-value:\n   * return it to the caller but do NOT store it (consistent with `get`\n   * returning `undefined` for a miss). Do not throw in this case, even\n   * though `set` rejects `undefined`. `null` is a value and is cached.\n   *\n   * @param key The cache key.\n   * @param loader Producer for the cached value on a miss.\n   * @param ttl Optional time to live for the produced value.\n   */\n  getOrCompute<T>(\n    key: string,\n    loader: () => Promise<T>,\n    ttl?: number,\n  ): Promise<T>;\n}\n\n/**\n * Construction options for {@link MemoryCacheProvider}.\n */\nexport interface MemoryCacheProviderOptions {\n  /**\n   * Maximum number of entries to keep. When the cache is full, the\n   * least-recently-used entry is evicted to make room. Defaults to\n   * 1000.\n   */\n  max?: number;\n  /**\n   * Default time to live in milliseconds, applied when a `set` call\n   * omits `ttl`. Defaults to no expiry (entries live until evicted by\n   * the LRU policy or explicitly deleted).\n   */\n  ttl?: number;\n}\n\n/**\n * Default in-process cache provider. Backed by `lru-cache` for\n * size-bounded LRU eviction with optional TTL, plus an in-flight\n * Promise map for stampede protection.\n *\n * Two instances are independent stores; the framework does not share\n * state across `MemoryCacheProvider` instances. The module-level\n * `defaultMemoryCacheProvider` is shared by every `.cache()` call that\n * does not supply its own provider.\n *\n * Thread-safe within the JS event loop: `getOrCompute` reads, registers\n * an in-flight Promise, and resolves it atomically with respect to\n * other JS turns on the same key. Across workers / processes the cache\n * is local to the host.\n */\nexport class MemoryCacheProvider implements CacheProvider {\n  // Values are wrapped in a `CacheEnvelope` so `null` can be cached\n  // (lru-cache rejects null/undefined values) and so a missing key\n  // (LRU returns `undefined`) is never confused with a cached `null`\n  // (LRU returns `{ v: null }`).\n  readonly #lru: LRUCache<string, CacheEnvelope>;\n  readonly #inFlight = new Map<string, Promise<unknown>>();\n\n  constructor(options: MemoryCacheProviderOptions = {}) {\n    this.#lru = new LRUCache<string, CacheEnvelope>({\n      max: options.max ?? 1000,\n      ...(options.ttl !== undefined ? { ttl: options.ttl } : {}),\n    });\n  }\n\n  async get(key: string): Promise<unknown> {\n    const entry = this.#lru.get(key);\n    return entry === undefined ? undefined : entry.v;\n  }\n\n  async set(key: string, value: unknown, ttl?: number): Promise<void> {\n    if (value === undefined) {\n      throw rcError(\"RC5028\", undefined, {\n        message:\n          \"CacheProvider.set received `undefined`, which is the cache-miss sentinel and cannot be stored. \" +\n          \"Use `null` for an intentional empty value, or skip the write.\",\n      });\n    }\n    this.#store(key, value, ttl);\n  }\n\n  async delete(key: string): Promise<void> {\n    this.#lru.delete(key);\n  }\n\n  async has(key: string): Promise<boolean> {\n    return this.#lru.has(key);\n  }\n\n  async getOrCompute<T>(\n    key: string,\n    loader: () => Promise<T>,\n    ttl?: number,\n  ): Promise<T> {\n    const cached = this.#lru.get(key);\n    if (cached !== undefined) return cached.v as T;\n\n    const existing = this.#inFlight.get(key);\n    if (existing) return existing as Promise<T>;\n\n    const promise = (async () => {\n      try {\n        const value = await loader();\n        // Cache everything except `undefined` (the miss sentinel).\n        // `null` and other falsy values are cached.\n        if (value !== undefined) this.#store(key, value, ttl);\n        return value;\n      } finally {\n        this.#inFlight.delete(key);\n      }\n    })();\n\n    this.#inFlight.set(key, promise);\n    return promise;\n  }\n\n  #store(key: string, value: unknown, ttl?: number): void {\n    const entry: CacheEnvelope = { v: value };\n    if (ttl !== undefined) {\n      this.#lru.set(key, entry, { ttl });\n    } else {\n      this.#lru.set(key, entry);\n    }\n  }\n\n  /**\n   * Drop all entries. Mainly for tests and explicit invalidation.\n   *\n   * Not part of the {@link CacheProvider} interface: clearing semantics\n   * vary by backend (a Redis `FLUSHDB` is destructive and shared), so\n   * this helper is specific to the in-memory provider. Construct a fresh\n   * provider for test isolation rather than relying on `clear()` against\n   * an arbitrary `CacheProvider`.\n   */\n  clear(): void {\n    this.#lru.clear();\n    this.#inFlight.clear();\n  }\n\n  /**\n   * Number of live entries (excludes in-flight loaders).\n   *\n   * Not part of the {@link CacheProvider} interface; specific to the\n   * in-memory provider and intended for tests and diagnostics.\n   */\n  get size(): number {\n    return this.#lru.size;\n  }\n}\n\n/**\n * Process-wide default provider used by `.cache()` when the call site\n * does not supply its own. Sized at 1000 entries, no default TTL. Tests\n * that need isolation should pass their own provider via\n * `cache({ provider: new MemoryCacheProvider() })` rather than mutating\n * this one.\n *\n * @internal\n */\nexport const defaultMemoryCacheProvider = new MemoryCacheProvider();\n","import type { Exchange } from \"../exchange.ts\";\nimport type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport { WrapperStep } from \"./wrapper.ts\";\nimport { wrapperEventScope } from \"./event-scope.ts\";\nimport { cancellableSleep, SleepAbortedError } from \"./cancellable-sleep.ts\";\nimport { type Duration, parseDuration } from \"../shared/duration.ts\";\n\n/**\n * Step-scope `.delay()` wrapper. Waits a fixed time, then runs the\n * wrapped step. Pass-through: the exchange is unchanged by the wait.\n *\n * The wait is tied to the route's INTAKE signal: when shutdown begins\n * mid-wait, the remaining wait is skipped and the wrapped step still\n * runs, so no exchange is silently dropped by a shutdown. The\n * `route:delay:stopped` event carries `cancelled: true` in that case.\n * Intake rather than execution because releasing early does not change\n * what the exchange does, only when: sitting out the timer would make a\n * graceful drain wait for a delay that buys nothing once no new work is\n * arriving.\n *\n * Step scope only: there is no route-scope form. A route-scope delay\n * would be equivalent to a delay before the first step, so the\n * builder does not stage one (see `.standards/resilience-wrappers.md`\n * and the pre-from filter chain, which reserves no slot for delay).\n *\n * Emits scope-aware lifecycle events:\n * - `route:delay:started` when the wait begins.\n * - `route:delay:stopped` when the wait ends (elapsed, cancelled flag).\n */\nexport class DelayWrapperStep<\n  T extends Adapter = Adapter,\n> extends WrapperStep<T> {\n  readonly #delayMs: number;\n\n  constructor(inner: Step<T>, duration: Duration) {\n    super(inner);\n    this.#delayMs = parseDuration(duration, \"delay(duration)\", 0);\n  }\n\n  protected override describeOptions(): unknown {\n    return { delayMs: this.#delayMs };\n  }\n\n  protected override async runInner(\n    exchange: Exchange,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const { route, context, routeId, stepLabel, correlationId } =\n      wrapperEventScope(exchange, this);\n    const shouldEmit = route && context && routeId;\n\n    if (shouldEmit) {\n      context.emit(\"route:delay:started\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        stepLabel,\n        scope: \"step\",\n        delayMs: this.#delayMs,\n      });\n    }\n\n    const start = Date.now();\n    let cancelled = false;\n    try {\n      await cancellableSleep(this.#delayMs, route?.intakeSignal);\n    } catch (err) {\n      if (!(err instanceof SleepAbortedError)) throw err;\n      // Route shutdown: skip the remaining wait but still run the\n      // wrapped step. Cancellation cuts the wait short; it never drops\n      // the exchange.\n      cancelled = true;\n    }\n\n    if (shouldEmit) {\n      context.emit(\"route:delay:stopped\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        stepLabel,\n        scope: \"step\",\n        delayMs: this.#delayMs,\n        elapsed: Date.now() - start,\n        cancelled,\n      });\n    }\n\n    return await this.inner.execute(exchange, ctx);\n  }\n}\n","import type { Adapter, Step, StepOutcome } from \"../types.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  cloneExchange,\n  getExchangeContext,\n  getExchangeRoute,\n} from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport type { Destination, SendContext } from \"./to.ts\";\nimport type { Enricher } from \"./enrich.ts\";\nimport { hasSend, hasFetch, missingSlotError } from \"./adapter-roles.ts\";\nimport {\n  resolveAdapterOverride,\n  invokeSendOverride,\n} from \"../testing-hooks.ts\";\n\n/**\n * Function form of a tap. One signature covers both role shapes (a\n * {@link CallableDestination} written for `.to()` and a\n * {@link CallableEnricher}) so either drops into `.tap()` unchanged and the\n * exchange parameter stays contextually typed: the `ctx` is a\n * {@link SendContext} (its `setHeader` sink discards receipts with the\n * snapshot), and any returned value is discarded.\n *\n * @template T - Current body type\n */\nexport type TapCallable<T = unknown, Ex extends Exchange<T> = Exchange<T>> = (\n  exchange: Ex,\n  ctx?: SendContext,\n) => unknown;\n\n/**\n * Anything `.tap()` accepts: a Destination (send), an Enricher (fetch and\n * discard), or a function form. Results are always discarded; a tap\n * observes.\n *\n * @template T - Current body type\n */\nexport type TapTarget<T = unknown, Ex extends Exchange<T> = Exchange<T>> =\n  Destination<T> | Enricher<T, unknown> | TapCallable<T, Ex>;\n\n/**\n * Step that runs a destination (or enricher) as a side effect without changing\n * the main exchange. The tap runs asynchronously (route.trackTask); the main\n * flow continues immediately. Tap receives a snapshot of the exchange\n * (body/headers cloned). `send` is preferred when both slots exist; a\n * fetch-only adapter is invoked and its result discarded. Receipt headers set\n * through the {@link SendContext} sink are discarded with the snapshot.\n * Errors are emitted as `error` and rethrown for observability.\n */\nexport class TapStep<T = unknown> implements Step<Adapter> {\n  operation: OperationType = OperationType.TAP;\n  label?: string;\n  adapter: Adapter;\n  /** Function form, when constructed from a bare callable. */\n  private readonly callable: TapCallable<T> | undefined;\n\n  constructor(target: TapTarget<T>) {\n    if (typeof target === \"function\") {\n      this.callable = target;\n      this.adapter = { send: target } as Adapter;\n    } else {\n      this.callable = undefined;\n      this.adapter = target;\n    }\n  }\n\n  async execute(exchange: Exchange<T>): Promise<StepOutcome> {\n    const context = getExchangeContext(exchange);\n    const route = getExchangeRoute(exchange);\n\n    if (!context || !route) {\n      throw new Error(\"Exchange has no context or route; cannot execute tap\");\n    }\n\n    // Tap runs against a deep clone so a tap-side body mutation cannot\n    // race the main pipeline. The clone gets a fresh id (so logs can\n    // distinguish tap from the main flow) while preserving the\n    // correlation id; tap is for observation, not mutation.\n    const snapshot = cloneExchange(exchange, context);\n\n    // Resolve a test-time override (if any) so `.tap(adapter)` is intercepted\n    // the same way `.to()` and `.enrich()` are.\n    const override = resolveAdapterOverride(this.adapter, context, \"send\");\n\n    const promise = (async () => {\n      try {\n        // Adapter metadata (getMetadata) is intentionally NOT collected\n        // here: the tap runs detached, so this exchange's route:step:completed\n        // event has already been emitted by the time the call resolves and\n        // any metadata written now would be misattributed to a later\n        // exchange's event.\n        // No signal on purpose: the tap runs detached from the main flow\n        // (its outcome never gates the pipeline), so an enclosing timeout\n        // abandoning the ATTEMPT must not cancel an observation already in\n        // flight. Mirrors captureDownstream's no-inherited-abort-signal\n        // contract. The header sink swallows receipts: they would only\n        // ever decorate the discarded snapshot. Function forms get the\n        // same sink so a callable written for `.to()` behaves identically.\n        const sink: SendContext = { setHeader: () => undefined };\n        if (override) {\n          await invokeSendOverride(snapshot, this.adapter, override);\n        } else if (this.callable) {\n          await Promise.resolve(this.callable(snapshot, sink));\n        } else if (hasSend<T>(this.adapter)) {\n          await Promise.resolve(this.adapter.send(snapshot, sink));\n        } else if (hasFetch<T, unknown>(this.adapter)) {\n          await Promise.resolve(this.adapter.fetch(snapshot, {}));\n        } else {\n          throw missingSlotError(\"`.tap()`\");\n        }\n      } catch (error: unknown) {\n        const err = rcError(\"RC5001\", error, {\n          message: `Error tapping exchange ${snapshot.id}`,\n          suggestion:\n            \"Tap errors can be handled in the route-level error() operation.\",\n        });\n        const tapLabel = this.label ?? \"tap\";\n        context.emit(\"route:step:error\", {\n          routeId: route.definition.id,\n          error: err,\n          route,\n          exchange: snapshot,\n          operation: tapLabel,\n        });\n        throw err; // Reject for observability\n      }\n    })();\n\n    route.trackTask(promise);\n\n    return { kind: \"continue\", exchange };\n  }\n}\n","import type { Adapter, Step, StepOutcome } from \"../types.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  DefaultExchange,\n  HeadersKeys,\n} from \"../exchange.ts\";\nimport { authenticate, type PrincipalClaims } from \"../auth/authenticate.ts\";\n\n/**\n * Resolve identity claims for the current exchange. Return claims to mint and\n * attach an authenticated principal, or `undefined` to leave the exchange as\n * it is (the caller stays anonymous, or keeps an already-attached identity).\n *\n * @template T - Body type of the exchange\n */\nexport type CallableAuthenticator<T = unknown> = (\n  exchange: Exchange<T>,\n) => PrincipalClaims | undefined | Promise<PrincipalClaims | undefined>;\n\n/**\n * Step that establishes the authenticated principal for the exchange. Mints a\n * branded principal from the resolver's claims (via `authenticate()`) and\n * writes it onto `headers[\"routecraft.auth.principal\"]`. Body is unchanged.\n *\n * When the resolver returns `undefined` the exchange passes through untouched,\n * so a source that cannot identify a given caller simply leaves it anonymous.\n */\nexport class AuthenticateStep<T = unknown> implements Step<Adapter> {\n  operation: OperationType = OperationType.HEADER;\n  adapter: Adapter = {};\n\n  constructor(private readonly resolve: CallableAuthenticator<T>) {}\n\n  async execute(exchange: Exchange<T>): Promise<StepOutcome> {\n    const claims = await Promise.resolve(this.resolve(exchange));\n    const next =\n      claims === undefined\n        ? exchange\n        : DefaultExchange.rewrap<T>(exchange, {\n            headers: {\n              ...exchange.headers,\n              [HeadersKeys.AUTH_PRINCIPAL]: authenticate(claims),\n            },\n          });\n    return { kind: \"continue\", exchange: next };\n  }\n}\n","import type { Adapter, Step, StepOutcome } from \"../types.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  DefaultExchange,\n  HeadersKeys,\n} from \"../exchange.ts\";\nimport type { PrincipalClaims } from \"../auth/authenticate.ts\";\nimport { delegate, type DelegateOptions } from \"../auth/delegate.ts\";\nimport { rcError } from \"../error.ts\";\n\n/**\n * Delegation directive returned by a {@link CallableDelegator}: the actor\n * identity plus the consent-derived scope ceiling.\n */\nexport interface DelegationClaims extends DelegateOptions {\n  /** Identity claims of the party that will act on the subject's behalf. */\n  actor: PrincipalClaims;\n}\n\n/**\n * Resolve the delegation for the current exchange. Return a directive to\n * mark an actor as acting on the current principal's behalf, or `undefined`\n * when no consent exists. What `undefined` does to the exchange is governed\n * by {@link DelegateStepOptions.otherwise}: by default the subject's direct\n * principal is stripped (the continuation runs anonymous), so an actor\n * downstream never wields an identity nobody consented to hand it.\n *\n * @template T - Body type of the exchange\n */\nexport type CallableDelegator<T = unknown> = (\n  exchange: Exchange<T>,\n) => DelegationClaims | undefined | Promise<DelegationClaims | undefined>;\n\n/**\n * Options for the `.delegate()` operation.\n */\nexport interface DelegateStepOptions {\n  /**\n   * What happens to the exchange when the resolver returns `undefined`\n   * (no consent record):\n   *\n   * - `\"drop\"` (default): strip the subject's direct principal so the\n   *   exchange continues anonymous. This is the right mode when the\n   *   continuation acts THROUGH someone else (an agent, a service): without\n   *   consent, the actor must not inherit the caller's full direct\n   *   authority, which is exactly what passing the principal through would\n   *   grant. Downstream `authorize()` then refuses with RC5012 instead of\n   *   silently acting with undelegated power. The strip is precise: it\n   *   only removes a principal that is present, not already delegated (no\n   *   `actor`), and not an autonomous agent subject\n   *   (`subjectProfile: \"ai_agent\"`). Anonymous exchanges, delegated\n   *   principals, and agent subjects pass through untouched.\n   *\n   * - `\"keep\"`: leave the exchange untouched, preserving the caller's\n   *   direct principal. This is the right mode when the continuation\n   *   serves the caller DIRECTLY (the delegation was an optional\n   *   enhancement, not the authority boundary), so an ungranted caller\n   *   should keep acting as themselves.\n   */\n  otherwise?: \"drop\" | \"keep\";\n}\n\n/**\n * Step that marks the exchange's principal as being exercised by an actor\n * (an agent, a service) on the subject's behalf. Mints the delegated\n * principal via `delegate()` and writes it onto\n * `headers[\"routecraft.auth.principal\"]`. Body is unchanged.\n *\n * Requires an authentic principal on the exchange: delegation transforms an\n * existing identity, it never creates one. A resolver that finds no\n * principal to delegate should return `undefined`; returning a directive on\n * an anonymous exchange throws RC5012. When the resolver returns\n * `undefined`, the no-consent behavior follows\n * {@link DelegateStepOptions.otherwise} (default: strip the direct\n * principal, fail closed).\n */\nexport class DelegateStep<T = unknown> implements Step<Adapter> {\n  operation: OperationType = OperationType.HEADER;\n  adapter: Adapter = {};\n\n  constructor(\n    private readonly resolve: CallableDelegator<T>,\n    private readonly options: DelegateStepOptions = {},\n  ) {}\n\n  async execute(exchange: Exchange<T>): Promise<StepOutcome> {\n    const directive = await Promise.resolve(this.resolve(exchange));\n    if (directive === undefined) {\n      if ((this.options.otherwise ?? \"drop\") === \"keep\") {\n        return { kind: \"continue\", exchange };\n      }\n      return { kind: \"continue\", exchange: dropUndelegated(exchange) };\n    }\n\n    const subject = exchange.principal;\n    if (!subject) {\n      throw rcError(\"RC5012\", new Error(\"No principal to delegate\"), {\n        message:\n          \"delegate step: resolver returned a delegation directive but the exchange has no authenticated principal\",\n        suggestion:\n          \"Establish identity first (.authenticate() or a source verifier), or return undefined from the resolver when the exchange is anonymous.\",\n      });\n    }\n\n    const { actor, ...options } = directive;\n    const next = DefaultExchange.rewrap<T>(exchange, {\n      headers: {\n        ...exchange.headers,\n        [HeadersKeys.AUTH_PRINCIPAL]: delegate(subject, actor, options),\n      },\n    });\n    return { kind: \"continue\", exchange: next };\n  }\n}\n\n/**\n * Fail-closed backstop for the default `otherwise: \"drop\"` mode: a direct\n * principal that did NOT get delegated must not flow onward, or the\n * continuation would wield the caller's full authority precisely when\n * consent is absent. Strips the principal so the exchange continues\n * anonymous and every downstream `authorize()` refuses it (RC5012).\n *\n * The strip is deliberately narrow. Untouched pass through for:\n * - anonymous exchanges (nothing to strip),\n * - already-delegated principals (an earlier hop established consent),\n * - autonomous agent subjects (`subjectProfile: \"ai_agent\"`), which are\n *   minted deliberately on internal triggers and act as themselves.\n */\nfunction dropUndelegated<T>(exchange: Exchange<T>): Exchange<T> {\n  const principal = exchange.principal;\n  if (!principal || principal.actor) return exchange;\n  if (principal.subjectProfile === \"ai_agent\") return exchange;\n  const headers = { ...exchange.headers };\n  delete headers[HeadersKeys.AUTH_PRINCIPAL];\n  return DefaultExchange.rewrap<T>(exchange, { headers });\n}\n","import type { Adapter, Step, StepOutcome } from \"../types.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  type HeaderValue,\n  type HeaderLiteral,\n  DefaultExchange,\n} from \"../exchange.ts\";\nimport { rcError } from \"../error.ts\";\nimport { engineOwnedHeaderSuggestion } from \"../engine-headers.ts\";\n\n/**\n * Function that returns the value for a header. Can be async. Use with `.header(key, valueOrFn)`.\n *\n * @template T - Body type of the exchange\n */\nexport type CallableHeaderSetter<T = unknown> = (\n  exchange: Exchange<T>,\n) => Promise<HeaderValue> | HeaderValue;\n\n/**\n * Header setter adapter: sets or overrides one exchange header. Body is unchanged.\n * Used by the builder's `.header(key, valueOrFn)`.\n *\n * @template T - Body type\n */\nexport interface HeaderSetter<T = unknown> extends Adapter {\n  /** Header key to set (e.g. `x-request-id`, `routecraft.custom`) */\n  key: string;\n  /** Computes the header value from the exchange (or static value via wrapper) */\n  set: CallableHeaderSetter<T>;\n}\n\n/**\n * Step that sets or overrides a single header on the exchange. Body type is unchanged.\n */\nexport class HeaderStep<T = unknown> implements Step<HeaderSetter<T>> {\n  operation: OperationType = OperationType.HEADER;\n  adapter: HeaderSetter<T>;\n\n  constructor(\n    key: string,\n    setterOrValue: CallableHeaderSetter<T> | HeaderLiteral,\n  ) {\n    const suggestion = engineOwnedHeaderSuggestion(key);\n    if (suggestion !== undefined) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `.header() cannot set \"${key}\": this header is framework-owned and maintained by the engine.`,\n        suggestion,\n      });\n    }\n\n    const set: CallableHeaderSetter<T> =\n      typeof setterOrValue === \"function\"\n        ? (setterOrValue as CallableHeaderSetter<T>)\n        : () => setterOrValue;\n\n    this.adapter = { key, set };\n  }\n\n  async execute(exchange: Exchange<T>): Promise<StepOutcome> {\n    const value = await Promise.resolve(this.adapter.set(exchange));\n    const next = DefaultExchange.rewrap<T>(exchange, {\n      headers: { ...exchange.headers, [this.adapter.key]: value },\n    });\n    return { kind: \"continue\", exchange: next };\n  }\n}\n","import type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport { NESTED_STEPS } from \"../dsl-symbol.ts\";\nimport type { NestedSteps } from \"../deferral/sites.ts\";\nimport {\n  type Exchange,\n  OperationType,\n  HeadersKeys,\n  cloneExchange,\n  getExchangeContext,\n  getExchangeRoute,\n} from \"../exchange.ts\";\n\n/**\n * Marker adapter for the MulticastStep. Exposes no configuration; the paths\n * live on the step itself.\n */\nexport interface MulticastAdapter extends Adapter {\n  readonly adapterId: \"routecraft.operation.multicast\";\n}\n\n/**\n * Step that fans the exchange out to multiple independent paths in parallel.\n *\n * Each path receives its own deep clone of the exchange (fresh id, preserved\n * correlation id) and runs as an isolated nested pipeline. All paths run\n * concurrently and the step waits for every one to settle\n * (`Promise.allSettled` semantics): a path that throws fires that clone's own\n * error events but does not fail the route or its sibling paths, and a path\n * that `.halt()`s only stops itself. Once every path has settled the ORIGINAL\n * exchange continues downstream unchanged.\n *\n * Path failures do NOT reach the route-scope `.error()` handler: each path is\n * a self-contained sub-flow whose failure resolves through its own clone's\n * default error events. Only the body is deep-copied; object-valued user\n * headers are shared by reference across clones (mutating a nested header\n * field from a path is not isolated). The body must be structured-cloneable;\n * a non-cloneable body fails this step.\n *\n * Fire-and-forget is intentionally not offered here; use `tap` (already\n * fire-and-forget) for that.\n */\nexport class MulticastStep<In = unknown> implements Step<MulticastAdapter> {\n  operation: OperationType = OperationType.MULTICAST;\n  adapter: MulticastAdapter = { adapterId: \"routecraft.operation.multicast\" };\n\n  constructor(private readonly paths: Step<Adapter>[][]) {}\n\n  /**\n   * Expose the fan-out paths to framework-level walks of the route's step\n   * tree. `rejoins: false`: a path runs as an isolated nested pipeline on\n   * its own clone and never flows back into the main pipeline, so the\n   * defer-site resolver refuses a `.defer()` inside one.\n   *\n   * @internal\n   */\n  [NESTED_STEPS](): ReadonlyArray<NestedSteps> {\n    return this.paths.map((steps) => ({ steps, rejoins: false }));\n  }\n\n  async execute(\n    exchange: Exchange<In>,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const context = getExchangeContext(exchange);\n    const route = getExchangeRoute(exchange);\n    const routeId =\n      route?.definition.id ??\n      (exchange.headers[HeadersKeys.ROUTE_ID] as string);\n    const correlationId = exchange.headers[\n      HeadersKeys.CORRELATION_ID\n    ] as string;\n\n    // With no context there is nothing to run paths against; pass the\n    // exchange through unchanged. In practice the executor always supplies a\n    // context, so this is a defensive no-op.\n    if (!context) {\n      return { kind: \"continue\", exchange };\n    }\n\n    // Emit started/stopped unconditionally and pair them with try/finally so\n    // a `started` is ALWAYS followed by a `stopped`, even if a path clone\n    // throws (a non-cloneable body) or the fan-out is empty. The cloning and\n    // fan-out only happen when there are paths to run.\n    context.emit(\"route:operation:multicast:started\", {\n      routeId,\n      exchangeId: exchange.id,\n      correlationId,\n      pathCount: this.paths.length,\n    });\n    try {\n      if (this.paths.length > 0) {\n        // Clone once per path so each path mutates an independent copy, binding\n        // the (already-derived) route so the clone is executor-ready, then run\n        // them all in parallel and wait for every one to settle.\n        await ctx.runPaths(\n          this.paths.map((steps) => ({\n            steps,\n            exchange: cloneExchange(exchange, context, route),\n          })),\n        );\n      }\n    } finally {\n      context.emit(\"route:operation:multicast:stopped\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        pathCount: this.paths.length,\n      });\n    }\n\n    // The original exchange continues downstream unchanged.\n    return { kind: \"continue\", exchange };\n  }\n}\n","import { LRUCache } from \"lru-cache\";\nimport type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport { type Exchange, OperationType, cloneExchange } from \"../exchange.ts\";\nimport { wrapperEventScope } from \"./event-scope.ts\";\nimport { rcError } from \"../error.ts\";\nimport { type Path, compilePath } from \"./choice.ts\";\nimport { NESTED_STEPS } from \"../dsl-symbol.ts\";\nimport type { NestedSteps } from \"../deferral/sites.ts\";\nimport { RouteScopedController } from \"./route-scoped-controller.ts\";\nimport { DEFAULT_MAX_KEYS, validateMaxKeys } from \"./max-keys.ts\";\n\n/**\n * Name of a dispatch selection strategy. Surfaced on the\n * `route:operation:dispatch:selected` event so observers can attribute a\n * pick to the strategy that made it. The event payloads in `types.ts`\n * inline this union (types.ts is the dependency root and never imports\n * from operations); keep the two in sync when adding a strategy.\n */\nexport type DispatchStrategyName =\n  \"failover\" | \"round-robin\" | \"weighted\" | \"sticky\";\n\n/**\n * Strategy argument accepted as the required leading parameter of\n * `.dispatch(strategy, ...targets)`. There is no safe default strategy\n * (each makes a materially different routing decision), so it is required.\n *\n * - String form for the strategies that carry no extra configuration:\n *   `\"failover\"`, `\"round-robin\"`, `\"weighted\"`.\n * - Object form when the strategy needs config. `sticky` REQUIRES a `key`\n *   selector (it has nothing to partition on otherwise) and so has no string\n *   form, and accepts an optional `maxKeys` bound on the affinity map.\n *\n * The config-less object arm (`{ strategy: \"failover\" | ... }`) is kept\n * deliberately for forward-compat symmetry: a strategy can gain options\n * later without a shape change at call sites, and the issue-spec examples\n * use it (`.dispatch({ strategy: \"weighted\" }, ...)`). Prefer the string\n * form when there is no config.\n *\n * @template In - Body type of the exchange at the point of the dispatch\n */\nexport type DispatchStrategy<In = unknown> =\n  | \"failover\"\n  | \"round-robin\"\n  | \"weighted\"\n  | { strategy: \"failover\" | \"round-robin\" | \"weighted\" }\n  | {\n      strategy: \"sticky\";\n      /** Partition selector: exchanges sharing a key stick to one target. */\n      key: (exchange: Exchange<In>) => string;\n      /**\n       * Maximum number of distinct keys retained in the affinity map (an\n       * LRU). When the cap is reached the least-recently-seen key is evicted\n       * and its next occurrence is reassigned (possibly to a different\n       * target). Default {@link DEFAULT_MAX_KEYS}.\n       */\n      maxKeys?: number;\n    };\n\n/**\n * Brand marking a {@link WeightedTarget}. A symbol (not a string field) so a\n * user destination or body can never collide with it, and so the wrapper is\n * invisible to ordinary property enumeration.\n */\nconst WEIGHTED = Symbol(\"routecraft.dispatch.weighted\");\n\n/**\n * A dispatch target with its relative weight co-located. Produced by\n * {@link weighted}; consumed only by the `weighted` strategy (other\n * strategies ignore the weight). Keeping the weight next to its target makes\n * the target list reorder-safe and mixable with un-weighted targets, which\n * default to weight 1.\n *\n * @template In  - Body type entering the target\n * @template Out - Body type the target produces (discarded; dispatch is\n *   side-effect-only)\n */\nexport interface WeightedTarget<In = unknown, Out = unknown> {\n  readonly [WEIGHTED]: true;\n  readonly weight: number;\n  readonly path: Path<In, Out>;\n}\n\n/**\n * A single dispatch target: a bare destination, a sub-pipeline callback (the\n * shared {@link Path} surface), or either of those wrapped in a relative\n * {@link weighted} weight.\n *\n * @template In  - Body type entering the target\n * @template Out - Body type the target produces (discarded)\n */\nexport type DispatchTarget<In = unknown, Out = unknown> =\n  Path<In, Out> | WeightedTarget<In, Out>;\n\n/**\n * Co-locate a relative weight with a dispatch target for the `weighted`\n * strategy. Weights are relative, not percentages, so `weighted(a, 3)` and\n * `weighted(b, 1)` send roughly three exchanges to `a` for each one to `b`.\n * Mixable with un-weighted targets, which take a default weight of 1.\n *\n * Rejected at build time (RC5003) if the weight is not a finite number > 0,\n * so a mis-typed weight fails when the route is built rather than silently\n * starving a target.\n *\n * @param path - The destination or sub-pipeline callback to weight\n * @param weight - Relative weight; must be a finite number > 0\n * @returns A weighted target consumed by `.dispatch(\"weighted\", ...)`\n */\nexport function weighted<In = unknown, Out = unknown>(\n  path: Path<In, Out>,\n  weight: number,\n): WeightedTarget<In, Out> {\n  if (!Number.isFinite(weight) || weight <= 0) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `weighted() weight must be a finite number > 0, got ${String(weight)}.`,\n    });\n  }\n  return { [WEIGHTED]: true, weight, path };\n}\n\n/** Type guard: is this target a {@link weighted} wrapper rather than a bare path? */\nfunction isWeighted(\n  target: DispatchTarget<unknown, unknown>,\n): target is WeightedTarget<unknown, unknown> {\n  return (\n    typeof target === \"object\" &&\n    target !== null &&\n    (target as { [WEIGHTED]?: true })[WEIGHTED] === true\n  );\n}\n\n/**\n * One compiled target: the step array to run plus its relative weight (1 for\n * an un-weighted target).\n *\n * @internal\n */\ninterface CompiledTarget {\n  steps: Step<Adapter>[];\n  weight: number;\n}\n\n/**\n * The selection strategy with its mode resolved and (for `sticky`) the key\n * selector and affinity bound validated.\n *\n * @internal\n */\ntype ResolvedDispatchStrategy =\n  | { name: \"failover\" }\n  | { name: \"round-robin\" }\n  | { name: \"weighted\" }\n  | {\n      name: \"sticky\";\n      key: (exchange: Exchange) => string;\n      maxKeys: number;\n    };\n\n/**\n * Validate the leading strategy argument into a {@link ResolvedDispatchStrategy}.\n * Rejects at build time (RC5003) so a bad strategy (or a `sticky` missing its\n * `key`) fails when the route is built. The type already forbids these for\n * typed callers; the runtime checks defend JS callers and widened values.\n *\n * @internal\n */\nexport function resolveDispatchStrategy(\n  strategy: DispatchStrategy<unknown>,\n): ResolvedDispatchStrategy {\n  const unknownStrategy = (name: unknown): never => {\n    throw rcError(\"RC5003\", undefined, {\n      message: `dispatch() unknown strategy \"${String(name)}\"; expected \"failover\", \"round-robin\", \"weighted\", or { strategy: \"sticky\", key }.`,\n    });\n  };\n  const requireStickyKey = (): never => {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        'dispatch({ strategy: \"sticky\" }) requires a `key` function to partition on (no string form).',\n    });\n  };\n\n  if (typeof strategy === \"string\") {\n    if (\n      strategy === \"failover\" ||\n      strategy === \"round-robin\" ||\n      strategy === \"weighted\"\n    ) {\n      return { name: strategy };\n    }\n    // The type has no `\"sticky\"` string member (sticky has nothing to\n    // partition on without a key), but a JS caller could still pass it: point\n    // them at the object form rather than the generic unknown-strategy error.\n    return String(strategy) === \"sticky\"\n      ? requireStickyKey()\n      : unknownStrategy(strategy);\n  }\n\n  // Defend JS callers passing null/undefined (or another non-object): fail\n  // with the coded RC5003 rather than a raw TypeError on `.strategy` below.\n  if (typeof strategy !== \"object\" || strategy === null) {\n    return unknownStrategy(strategy);\n  }\n\n  if (strategy.strategy === \"sticky\") {\n    if (typeof strategy.key !== \"function\") return requireStickyKey();\n    const maxKeys = strategy.maxKeys ?? DEFAULT_MAX_KEYS;\n    validateMaxKeys(\"dispatch\", maxKeys);\n    return { name: \"sticky\", key: strategy.key, maxKeys };\n  }\n\n  switch (strategy.strategy) {\n    case \"failover\":\n    case \"round-robin\":\n    case \"weighted\":\n      return { name: strategy.strategy };\n    default:\n      return unknownStrategy((strategy as { strategy?: unknown }).strategy);\n  }\n}\n\n/**\n * Compile the variadic targets into their step arrays and weights. Rejects an\n * empty target list at build time (RC5003): a dispatch with nothing to select\n * between is meaningless.\n *\n * @internal\n */\nexport function compileDispatchTargets(\n  targets: readonly DispatchTarget<unknown, unknown>[],\n): CompiledTarget[] {\n  if (targets.length === 0) {\n    throw rcError(\"RC5003\", undefined, {\n      message: \"dispatch() requires at least one target.\",\n    });\n  }\n  return targets.map((target) =>\n    isWeighted(target)\n      ? { steps: compilePath(target.path), weight: target.weight }\n      : { steps: compilePath(target), weight: 1 },\n  );\n}\n\n/**\n * Per-route dispatch state. One instance per Route (see\n * {@link DispatchController}), never one per exchange: the cursors and the\n * affinity map must persist across the exchanges a Route processes for the\n * strategies to mean anything.\n *\n * @internal\n */\nclass DispatchState {\n  /** Round-robin: index of the next target to hand out. */\n  rrCursor = 0;\n  /**\n   * Failover: index of the current preferred target. Starts at 0 and advances\n   * only when the preferred target fails, so a healthy target keeps serving\n   * without re-probing a dead one each exchange. Does not auto-revert.\n   */\n  failoverCursor = 0;\n  /** Sticky: round-robins NEW keys across targets so affinity spreads evenly. */\n  stickyCursor = 0;\n  /** Weighted (smooth weighted round-robin): per-target running current weight. */\n  readonly currentWeights: number[];\n  /** Sticky: key -> target index affinity map, LRU-bounded by `maxKeys`. */\n  readonly sticky: LRUCache<string, number>;\n\n  constructor(targetCount: number, stickyMaxKeys: number) {\n    this.currentWeights = new Array<number>(targetCount).fill(0);\n    this.sticky = new LRUCache<string, number>({\n      max: stickyMaxKeys,\n      // A hit is a use: refresh recency so an actively-arriving key keeps its\n      // affinity rather than being evicted ahead of colder keys.\n      updateAgeOnGet: true,\n    });\n  }\n}\n\n/**\n * Owns the dispatch state for one `.dispatch()` across every Route the step\n * runs in (see {@link RouteScopedController}): each Route gets its own cursors\n * and affinity map so contexts cannot cross-route each other's traffic.\n *\n * @internal\n */\nclass DispatchController extends RouteScopedController<DispatchState> {\n  readonly #targetCount: number;\n  readonly #stickyMaxKeys: number;\n\n  constructor(targetCount: number, stickyMaxKeys: number) {\n    super();\n    this.#targetCount = targetCount;\n    this.#stickyMaxKeys = stickyMaxKeys;\n  }\n\n  protected createState(): DispatchState {\n    return new DispatchState(this.#targetCount, this.#stickyMaxKeys);\n  }\n}\n\n/** Marker adapter for the dispatch step; the targets live on the step itself. */\nexport interface DispatchAdapter extends Adapter {\n  readonly adapterId: \"routecraft.operation.dispatch\";\n}\n\n/**\n * Step that runs EXACTLY ONE of its targets, chosen by strategy, and lets the\n * original exchange continue downstream unchanged. The sibling of `multicast`\n * (all targets) and `choice` (one target by predicate); dispatch is one target\n * by load-balancing strategy.\n *\n * Side-effect-only: the selected target runs on its own deep clone (fresh id,\n * preserved correlation id), exactly like a multicast path, so a target that\n * reshapes the body does not change what continues downstream. There is no\n * branch-convergence requirement, so a target's output type is unconstrained.\n *\n * Strategies:\n * - `failover`: try targets in order from the current preferred cursor until\n *   one settles without failing (a target that deliberately drops the exchange\n *   counts as handled). On a failure, advance to the next target and retry; the\n *   cursor persists so a healthy target keeps serving and a dead one is not\n *   re-probed every exchange. If every target fails, emit\n *   `route:operation:dispatch:exhausted` and let the original continue. Pairs\n *   naturally with per-target `.retry()` / `.circuitBreaker()`.\n * - `round-robin`: hand out targets in order, cycling.\n * - `weighted`: smooth weighted round-robin over the `weighted()` weights, so\n *   the distribution matches the weights and is deterministic (testable)\n *   rather than random.\n * - `sticky`: exchanges sharing a `key` go to the same target; new keys are\n *   round-robined across targets and remembered in an LRU-bounded map.\n *\n * A failing target fires its own clone's error events (`route:error` /\n * `route:exchange:failed`) but never fails the route or the dispatch step\n * itself, matching multicast's isolation contract.\n */\nexport class DispatchStep<In = unknown> implements Step<DispatchAdapter> {\n  operation: OperationType = OperationType.DISPATCH;\n  adapter: DispatchAdapter = { adapterId: \"routecraft.operation.dispatch\" };\n\n  readonly #strategy: ResolvedDispatchStrategy;\n  readonly #targets: CompiledTarget[];\n  readonly #weights: number[];\n  readonly #controller: DispatchController;\n\n  constructor(\n    strategy: DispatchStrategy<In>,\n    targets: readonly DispatchTarget<In, unknown>[],\n  ) {\n    this.#strategy = resolveDispatchStrategy(\n      strategy as DispatchStrategy<unknown>,\n    );\n    this.#targets = compileDispatchTargets(\n      targets as readonly DispatchTarget<unknown, unknown>[],\n    );\n    this.#weights = this.#targets.map((t) => t.weight);\n    this.#controller = new DispatchController(\n      this.#targets.length,\n      this.#strategy.name === \"sticky\" ? this.#strategy.maxKeys : 1,\n    );\n  }\n\n  /**\n   * Expose the compiled targets to framework-level walks of the route's\n   * step tree. `rejoins: false`: a target runs as an isolated nested\n   * pipeline whose result the main flow does not carry, so the\n   * defer-site resolver refuses a `.defer()` inside one.\n   *\n   * @internal\n   */\n  [NESTED_STEPS](): ReadonlyArray<NestedSteps> {\n    return this.#targets.map((target) => ({\n      steps: target.steps,\n      rejoins: false,\n    }));\n  }\n\n  async execute(\n    exchange: Exchange<In>,\n    ctx: StepContext,\n  ): Promise<StepOutcome> {\n    const { route, context, routeId, correlationId } = wrapperEventScope(\n      exchange,\n      this,\n    );\n\n    // With no context there is nothing to run a target against; pass the\n    // exchange through unchanged. In practice the executor always supplies a\n    // context, so this is a defensive no-op (mirrors multicast).\n    if (!context) {\n      return { kind: \"continue\", exchange };\n    }\n\n    const state = this.#controller.stateFor(route);\n    const n = this.#targets.length;\n\n    if (this.#strategy.name === \"failover\") {\n      for (let attempt = 0; attempt < n; attempt++) {\n        const targetIndex = (state.failoverCursor + attempt) % n;\n        context.emit(\"route:operation:dispatch:selected\", {\n          routeId,\n          exchangeId: exchange.id,\n          correlationId,\n          strategy: \"failover\",\n          targetIndex,\n        });\n        const result = await ctx.runPath({\n          steps: this.#targets[targetIndex].steps,\n          exchange: cloneExchange(exchange, context, route),\n        });\n        // An abort-truncated run (a route-scope timeout abandoned this\n        // attempt; the nested pipeline scheduled nothing) is neither success\n        // nor target failure: stop probing without promoting the cursor or\n        // declaring exhaustion, since the attempt's outcome is discarded.\n        if (result.aborted) {\n          return { kind: \"continue\", exchange };\n        }\n        // A drop is a deliberate resolution (the target handled it and chose\n        // to discard), not a failure: only a genuine failure fails over.\n        if (!result.failed) {\n          state.failoverCursor = targetIndex;\n          return { kind: \"continue\", exchange };\n        }\n      }\n      // Every target failed. Side-effect-only: the original still continues;\n      // the exhausted event is the signal that no target handled it.\n      context.emit(\"route:operation:dispatch:exhausted\", {\n        routeId,\n        exchangeId: exchange.id,\n        correlationId,\n        strategy: \"failover\",\n        targetCount: n,\n      });\n      return { kind: \"continue\", exchange };\n    }\n\n    const targetIndex = this.#select(state, exchange);\n    context.emit(\"route:operation:dispatch:selected\", {\n      routeId,\n      exchangeId: exchange.id,\n      correlationId,\n      strategy: this.#strategy.name,\n      targetIndex,\n    });\n    // Run the selected target on its own clone and wait for it to settle\n    // before the original continues, so ordering is deterministic. The\n    // result is ignored: a non-failover target's failure stays isolated to\n    // its clone's own error events, exactly like a multicast path.\n    await ctx.runPath({\n      steps: this.#targets[targetIndex].steps,\n      exchange: cloneExchange(exchange, context, route),\n    });\n    return { kind: \"continue\", exchange };\n  }\n\n  /** Pick one target index for the non-failover strategies. */\n  #select(state: DispatchState, exchange: Exchange<In>): number {\n    const n = this.#targets.length;\n    switch (this.#strategy.name) {\n      case \"round-robin\": {\n        const index = state.rrCursor % n;\n        state.rrCursor = (state.rrCursor + 1) % n;\n        return index;\n      }\n      case \"weighted\": {\n        // Smooth weighted round-robin (the nginx algorithm): add each target's\n        // weight to its running current, pick the max, then subtract the total\n        // from the winner. Deterministic and evenly interleaved for any weights.\n        let total = 0;\n        let best = 0;\n        for (let i = 0; i < n; i++) {\n          state.currentWeights[i] += this.#weights[i];\n          total += this.#weights[i];\n          if (state.currentWeights[i] > state.currentWeights[best]) {\n            best = i;\n          }\n        }\n        state.currentWeights[best] -= total;\n        return best;\n      }\n      case \"sticky\": {\n        const key = this.#strategy.key(exchange);\n        const existing = state.sticky.get(key);\n        if (existing !== undefined) return existing;\n        // New key: assign the next target round-robin so affinity spreads\n        // evenly, then remember it (LRU-bounded by maxKeys).\n        const index = state.stickyCursor % n;\n        state.stickyCursor = (state.stickyCursor + 1) % n;\n        state.sticky.set(key, index);\n        return index;\n      }\n      default:\n        // `failover` is handled in execute() and never reaches #select; the\n        // other names are exhausted above. This guards a widened value.\n        throw rcError(\"RC5001\", undefined, {\n          message: `dispatch() reached #select with unhandled strategy \"${this.#strategy.name}\".`,\n        });\n    }\n  }\n}\n\n/**\n * Build the {@link DispatchStep} for a variadic `.dispatch(strategy, ...targets)`\n * call. Keeps the step value encapsulated in this module so the builder only\n * depends on the helper.\n *\n * @internal\n */\nexport function buildDispatchStep<In = unknown>(\n  strategy: DispatchStrategy<In>,\n  targets: readonly DispatchTarget<In, unknown>[],\n): DispatchStep<In> {\n  return new DispatchStep<In>(strategy, targets);\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { rcError } from \"../error.ts\";\nimport { type Exchange, OperationType } from \"../exchange.ts\";\nimport type { Adapter, StepOutcome } from \"../types.ts\";\nimport type { Duration } from \"../shared/duration.ts\";\nimport { parseDuration } from \"../shared/duration.ts\";\nimport type { DeferSite, DeferrableStep } from \"../deferral/sites.ts\";\n\n/**\n * Options for `.defer()`.\n *\n * Notification, conditional asking, and consuming the verdict are all\n * expressible with operations the DSL already has, so none of them is an\n * option here: notify with a `.tap()` before the defer, gate with\n * `.choice()`, consume with `.filter()` after it.\n *\n * Who may RESUME is not an option here either, and deliberately so: the\n * framework has no model of what makes a resuming principal legitimate.\n * `meta` carries whatever the application's own policy needs onto the\n * record, and `.resume({ authorize })` is where that policy runs.\n *\n * @template Schema - The `schema` option, whose output types `ex.deferral.result`\n */\nexport interface DeferOptions<\n  Schema extends StandardSchemaV1 = StandardSchemaV1,\n> {\n  /**\n   * The declared shape of the resume payload. Optional.\n   *\n   * The framework has no approve/deny concept: a deferral is a durable\n   * pause with one single-use payload slot of arbitrary shape, and this\n   * route's own continuation interprets whatever arrives. Declaring a\n   * schema buys three things: the JSON Schema rendering advertised on the\n   * acknowledgment so an approval UI or a calling agent can render a form,\n   * pre-claim validation of the payload (`RC5049`, so garbage cannot spend\n   * the link), and the typing of `ex.deferral.result` downstream.\n   *\n   * Absent, none of those apply: no ingress validation, and the result\n   * types `unknown`. A click-yes consent flow stops paying schema ceremony\n   * it never needed.\n   */\n  schema?: Schema;\n  /**\n   * How long the deferral stays resumable. Omit for no expiry.\n   *\n   * An expired deferral is not a dead end: a resume arriving late (or the\n   * sweeper reaching it first) re-enters this route's error channel with\n   * `RC5047`, so a route-scope `.error()` can notify the recipient and\n   * re-ask.\n   */\n  ttl?: Duration;\n  /**\n   * Anything the resuming route needs to decide who may resume, or that an\n   * operator needs to read off the record.\n   *\n   * Plain JSON, persisted verbatim, and never interpreted by the framework:\n   * how approvals work is the application's design. A defer site that snapshots\n   * its policy here gets \"policy travels with the deferral\" for free, because\n   * the record is what `.resume({ authorize })` reads and editing this site\n   * cannot reach records already deferred.\n   */\n  meta?: unknown;\n}\n\n/** Marker adapter for the defer step; its options live on the step. */\nexport interface DeferAdapter extends Adapter {\n  readonly adapterId: \"routecraft.operation.defer\";\n}\n\n/**\n * Step that defers the exchange and exits the pipeline.\n *\n * It performs no effects of its own: it produces the `defer` outcome and\n * the executor does the deferring. Nothing is scheduled, no worker waits, and\n * the route stays live for every other exchange, because a deferred exchange\n * lives in the deferral store rather than in this process.\n */\nexport class DeferStep implements DeferrableStep {\n  readonly operation = OperationType.DEFER;\n  readonly adapter: DeferAdapter = {\n    adapterId: \"routecraft.operation.defer\",\n  };\n\n  /**\n   * Assigned by the build-time site resolver. A step that never got one is\n   * not reachable from a built route, so there is no continuation to revive\n   * and the step refuses rather than deferring an exchange nothing can wake.\n   */\n  site?: DeferSite;\n\n  /**\n   * The live resume-payload schema, when one was declared. Public because\n   * the resume path reads it back off the route to validate the submitted\n   * payload: a Standard Schema is an object with a validate function, so it\n   * cannot travel in the record.\n   */\n  readonly schema?: StandardSchemaV1;\n\n  /** Policy inputs the defer site attached, persisted verbatim on the record. */\n  readonly meta?: unknown;\n\n  readonly #expiresInMs?: number;\n\n  constructor(options: DeferOptions = {}) {\n    if (options.schema !== undefined) this.schema = options.schema;\n    if (options.meta !== undefined) this.meta = options.meta;\n    if (options.ttl !== undefined) {\n      this.#expiresInMs = parseDuration(options.ttl, \".defer({ ttl })\");\n    }\n  }\n\n  async execute(exchange: Exchange): Promise<StepOutcome> {\n    if (!this.site) {\n      throw rcError(\"RC5051\", undefined, {\n        message:\n          \"This .defer() is not reachable from a built route, so the framework cannot work out what would run when it resumes. Build the route through craft()...build() rather than assembling a RouteDefinition by hand.\",\n      });\n    }\n    return {\n      kind: \"defer\",\n      exchange,\n      request: {\n        ...(this.schema !== undefined ? { schema: this.schema } : {}),\n        ...(this.#expiresInMs !== undefined\n          ? { expiresInMs: this.#expiresInMs }\n          : {}),\n        ...(this.meta !== undefined ? { meta: this.meta } : {}),\n        site: this.site,\n      },\n    };\n  }\n}\n","import { rcError } from \"../error.ts\";\nimport { anySignal } from \"../shared/abort.ts\";\nimport {\n  type Exchange,\n  DefaultExchange,\n  OperationType,\n  getExchangeContext,\n  getExchangeRoute,\n} from \"../exchange.ts\";\nimport { isRestored } from \"../auth/restored.ts\";\nimport { toSignalContext } from \"../types.ts\";\nimport type { Adapter, Step, StepContext, StepOutcome } from \"../types.ts\";\nimport {\n  type ResumeAcknowledgment,\n  type ResumeRequest,\n  reviveDeferral,\n} from \"../deferral/revive.ts\";\nimport { principalRef } from \"../deferral/principal-ref.ts\";\nimport type { ResumeAuthorizer } from \"../deferral/authorize.ts\";\n\n/**\n * Maps the ingress exchange to the deferral it resumes.\n *\n * The preferred form of `.resume()`, because the ingress transport decides\n * where the token and the payload actually live: a token in a mail subject\n * line and a verdict in the first line of the reply, a chat webhook's\n * button payload, an ops CLI's flags.\n *\n * @template T - Body type of the ingress exchange\n */\nexport type ResumeMapper<T = unknown> = (\n  exchange: Exchange<T>,\n  ctx?: { readonly signal?: AbortSignal },\n) => ResumeRequest | Promise<ResumeRequest>;\n\n/** Marker adapter for the resume step; the mapper lives on the step. */\nexport interface ResumeAdapter extends Adapter {\n  readonly adapterId: \"routecraft.operation.resume\";\n}\n\n/**\n * Options for `.resume()`.\n */\nexport interface ResumeOptions {\n  /**\n   * Decides whether the principal presenting this token may resume the\n   * deferral it names.\n   *\n   * The framework has no model of what makes a resuming principal\n   * legitimate, so it does not ship one. What it guarantees is the part an\n   * application cannot build from outside: this runs BEFORE the store's\n   * compare-and-swap, so a \"no\" never spends the rightful principal's\n   * single-use link, and before the record's lifecycle is disclosed, so a\n   * refused caller learns nothing about it.\n   *\n   * Receives the live principal (whatever this route's `.authenticate()`\n   * resolved, or undefined when it resolved nobody), the deferred principal\n   * restored from storage, the raw submitted payload, and the record's\n   * context, including the `meta` the defer site attached. Never the\n   * deferred body.\n   *\n   * Omitted, the door is bearer: any holder of a valid token may resume.\n   * That is the historical behaviour and it stays the default, so securing\n   * a resume ingress is a thing you do, not a thing you inherit.\n   */\n  authorize?: ResumeAuthorizer;\n}\n\n/**\n * Step that revives a deferred exchange addressed by a signed token.\n *\n * It addresses an EXCHANGE, not a route. `direct(\"x\")` names a route and\n * enters it through its source; resume names one deferred exchange and\n * re-enters its pipeline partway down. That is why a Gmail-born exchange\n * can be continued by a WhatsApp-born resume: the original source takes no\n * part in execution two, and sources create exchanges rather than revive\n * them.\n *\n * The revived route runs to completion before this step resolves, so the\n * acknowledgment it puts in the ingress body reports how execution two\n * actually ended. That is also what makes a duplicate resume cheap: it\n * returns the cached continuation result of the first one instead of running\n * anything.\n */\nexport class ResumeStep<In = unknown> implements Step<ResumeAdapter> {\n  readonly operation = OperationType.RESUME;\n  readonly adapter: ResumeAdapter = {\n    adapterId: \"routecraft.operation.resume\",\n  };\n\n  /** The door's own authorization policy, when it declares one. */\n  readonly authorize?: ResumeAuthorizer;\n\n  constructor(\n    private readonly mapper?: ResumeMapper<In>,\n    options?: ResumeOptions,\n  ) {\n    if (options?.authorize !== undefined) {\n      if (typeof options.authorize !== \"function\") {\n        throw rcError(\"RC5003\", undefined, {\n          message:\n            \".resume({ authorize }) must be a function receiving { principal, deferred, payload, record } and returning a boolean (or a promise of one).\",\n        });\n      }\n      this.authorize = options.authorize;\n    }\n  }\n\n  async execute(exchange: Exchange, ctx: StepContext): Promise<StepOutcome> {\n    const context = getExchangeContext(exchange);\n    if (!context) {\n      // Not RC5052: nothing is misconfigured. An exchange reaching a step\n      // without a context binding is a framework invariant violation, which\n      // is what the catch-all code is for.\n      throw rcError(\"RC5001\", undefined, {\n        message:\n          \"Cannot resume: this exchange has no context binding, so there is no deferral store to revive from.\",\n      });\n    }\n\n    const signalCtx = toSignalContext(ctx) as {\n      readonly signal?: AbortSignal;\n    };\n    // The hook's bound is the route's intake signal (shutdown has begun) as\n    // well as an enclosing .timeout(): ctx.signal is populated only by a\n    // route-scope timeout, so\n    // racing the hook against that alone leaves a resume route without one\n    // unable to interrupt a hook that never settles, and an unsettled hook\n    // holds the step, which holds drain().\n    const route = getExchangeRoute(exchange);\n    const hookSignal = anySignal(route?.intakeSignal, signalCtx.signal);\n    // Only a principal this ingress verified live may stand as the resuming\n    // party. A revived exchange carries its deferred principal back marked\n    // restored, so a route that both defers and resumes would otherwise\n    // hand the hook storage data under a contract that says verified live.\n    const live =\n      exchange.principal && !isRestored(exchange.principal)\n        ? exchange.principal\n        : undefined;\n    const request = this.mapper\n      ? await this.mapper(exchange as Exchange<In>, signalCtx)\n      : fromBody(exchange);\n\n    const acknowledgment: ResumeAcknowledgment = await reviveDeferral(\n      context,\n      {\n        ...request,\n        // The ingress route's principal is the one worth recording: it was\n        // verified live here, on the route that accepted the submission,\n        // unlike anything read back out of the store. An explicit\n        // `resumedBy` from the mapper wins, for an ops tool resuming on\n        // someone's behalf.\n        ...(request.resumedBy === undefined && live\n          ? { resumedBy: principalRef(live) }\n          : {}),\n      },\n      // The door's own facts, kept OFF the mapper's request on purpose. The\n      // mapper shapes a transport payload, which is exactly what an attacker\n      // controls; letting it name the principal or supply the hook would let\n      // the untrusted half of an ingress choose what the trusted half checks.\n      {\n        ...(this.authorize !== undefined ? { authorize: this.authorize } : {}),\n        ...(live ? { principal: live } : {}),\n        ...(hookSignal ? { signal: hookSignal } : {}),\n      },\n    );\n\n    return {\n      kind: \"continue\",\n      exchange: DefaultExchange.rewrap(exchange, { body: acknowledgment }),\n      metadata: {\n        deferralId: acknowledgment.deferralId,\n        resumedRouteId: acknowledgment.routeId,\n        status: acknowledgment.status,\n        outcome: acknowledgment.continuation.status,\n      },\n    };\n  }\n}\n\n/**\n * The convention fallback for a bare `.resume()`: the body is already\n * `{ token, result }`.\n *\n * Refuses anything else rather than reviving with a token read out of a\n * shape it does not recognise, since the token is a bearer capability and a\n * wrong one is a resume against the wrong exchange.\n *\n * @internal\n */\nfunction fromBody(exchange: Exchange): ResumeRequest {\n  const body = exchange.body as { token?: unknown; result?: unknown } | null;\n  if (\n    typeof body !== \"object\" ||\n    body === null ||\n    typeof body.token !== \"string\" ||\n    !(\"result\" in body)\n  ) {\n    throw rcError(\"RC5041\", undefined, {\n      message:\n        \"Bare .resume() expects the body to already be shaped { token, result }. Map it explicitly with .resume((ex) => ({ token, result })) when the ingress carries the payload in its own shape.\",\n    });\n  }\n  return { token: body.token, result: body.result };\n}\n","import type { Principal } from \"../auth/types.ts\";\nimport type { PrincipalRef } from \"./types.ts\";\n\n/**\n * Reduce a live principal to the audit reference a deferral records.\n *\n * A subset, not the principal itself: a full principal carries claims,\n * scopes and a delegation chain that would be resurrected as data with no\n * verification behind it. What the record answers is \"who authorized\n * this\", which is what a receipt is for.\n *\n * It lives next to {@link PrincipalRef} rather than in the resume\n * operation because the reduction IS the type's contract. The next writer\n * of a `PrincipalRef` (an operator deny path, a cancellation) has to\n * record the same subset, and a second hand-rolled projection is how a\n * scope or a claims bag ends up in the store.\n *\n * @internal\n */\nexport function principalRef(principal: Principal): PrincipalRef {\n  return {\n    subject: principal.subject,\n    ...(principal.issuer !== undefined ? { issuer: principal.issuer } : {}),\n    ...(principal.clientId !== undefined\n      ? { clientId: principal.clientId }\n      : {}),\n    ...(principal.actor?.subject !== undefined\n      ? { actorSubject: principal.actor.subject }\n      : {}),\n  };\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { type Duration, parseDuration } from \"./shared/duration.ts\";\nimport { rejectStaleOptions } from \"./shared/stale-options.ts\";\nimport {\n  isCronCadence,\n  MANUAL_REFRESH,\n  NEVER_FORCE,\n  type EnablementOptions,\n  type EnablementPredicate,\n  type RouteEnablement,\n} from \"./enablement.ts\";\nimport { BRAND, setBrand } from \"./brand.ts\";\nimport {\n  StepBuilderBase,\n  type BuilderState,\n  type SetBody,\n} from \"./step-builder-base.ts\";\nimport {\n  type RouteDefinition,\n  type ErrorHandler,\n  type RouteDiscovery,\n  type RouteSchemas,\n  type Tag,\n  buildCacheCheckStep,\n  buildCacheStoreStep,\n  buildThrottleCheckStep,\n} from \"./route.ts\";\nimport {\n  CraftContext,\n  type StoreRegistry,\n  type CraftConfig,\n} from \"./context.ts\";\nimport { rcError } from \"./error.ts\";\nimport { logger } from \"./logger.ts\";\nimport { CraftClient } from \"./client.ts\";\nimport type { EventHandler, EventName } from \"./types.ts\";\nimport { SimpleConsumer } from \"./consumers/simple.ts\";\nimport { BatchConsumer } from \"./consumers/batch.ts\";\nimport {\n  type Source,\n  type SourceLike,\n  type SourceList,\n  toSource,\n} from \"./operations/from.ts\";\nimport type { Adapter, Step, Consumer, ConsumerType } from \"./types.ts\";\nimport { OperationType } from \"./exchange.ts\";\nimport {\n  nestedStepsOf,\n  resolveDeferSites,\n  usesResume,\n} from \"./deferral/sites.ts\";\nimport { WrapperStep } from \"./operations/wrapper.ts\";\nimport { AuthenticateStep } from \"./operations/authenticate.ts\";\nimport {\n  type Splitter,\n  type CallableSplitter,\n  SplitStep,\n} from \"./operations/split.ts\";\nimport {\n  type Aggregator,\n  type CallableAggregator,\n  AggregateStep,\n  defaultAggregate,\n} from \"./operations/aggregate.ts\";\nimport {\n  buildChoiceStep,\n  compilePath,\n  type ChoiceDescriptor,\n  type Path,\n} from \"./operations/choice.ts\";\nimport { MulticastStep } from \"./operations/multicast.ts\";\nimport {\n  buildDispatchStep,\n  type DispatchStrategy,\n  type DispatchTarget,\n} from \"./operations/dispatch.ts\";\nimport {\n  buildDebounceStep,\n  type DebounceOptions,\n} from \"./operations/debounce.ts\";\nimport { ValidateStep } from \"./operations/validate.ts\";\nimport { authorize, type AuthorizeOptions } from \"./auth/authorize.ts\";\nimport {\n  type CacheOptions,\n  assignCacheSites,\n  pipelineFingerprint,\n  resolveCacheOptions,\n  type ResolvedCacheOptions,\n} from \"./operations/cache-wrapper.ts\";\nimport {\n  type RetryOptions,\n  type ResolvedRetryOptions,\n  resolveRetryOptions,\n} from \"./operations/retry-wrapper.ts\";\nimport {\n  type ResolvedTimeoutOptions,\n  resolveTimeoutOptions,\n} from \"./operations/timeout-wrapper.ts\";\nimport {\n  type ThrottleOptions,\n  type ResolvedThrottleOptions,\n  resolveThrottleOptions,\n} from \"./operations/throttle-wrapper.ts\";\nimport {\n  type CircuitBreakerOptions,\n  type ResolvedCircuitBreakerOptions,\n  resolveCircuitBreakerOptions,\n  CircuitBreakerController,\n} from \"./operations/circuit-breaker-wrapper.ts\";\nimport {\n  type ConcurrencyOptions,\n  type ResolvedConcurrencyOptions,\n  resolveConcurrencyOptions,\n  ConcurrencyController,\n} from \"./operations/concurrency-wrapper.ts\";\n\n/**\n * Builder for creating a Routecraft context with routes and configuration.\n *\n * This builder provides a fluent API for configuring and creating a CraftContext\n * with routes, startup/shutdown handlers, and initial store values.\n *\n * @example\n * ```typescript\n * // Create a context with routes and handlers\n * const { context, client } = await new ContextBuilder()\n *   .with({ store: new Map() })\n *   .on('context:starting', ({ ts }) => console.log('Starting at', ts))\n *   .store('routecraft.adapter.channel.store', new Map())\n *   .routes(routes1)\n *   .routes([routes2, routes3])\n *   .build();\n *\n * // Start the context to begin processing\n * await context.start();\n *\n * // Dispatch messages programmatically\n * await client.sendDirect('my-endpoint', { data: 'hello' });\n * ```\n *\n * Plugins run before routes are registered, allowing them to:\n * - Set up stores and state\n * - Dynamically register additional routes\n * - Subscribe to lifecycle events\n * - Perform other initialization\n */\nexport class ContextBuilder {\n  protected config?: CraftConfig;\n  protected definitions: RouteDefinition[] = [];\n  protected initialStores = new Map<\n    keyof StoreRegistry,\n    StoreRegistry[keyof StoreRegistry]\n  >();\n  protected eventHandlers = new Map<EventName, Set<EventHandler<EventName>>>();\n  protected onceHandlers = new Map<EventName, Set<EventHandler<EventName>>>();\n  protected plugins: Array<import(\"./context.ts\").CraftPlugin> = [];\n\n  constructor() {}\n\n  /**\n   * Configure the context with the provided config object.\n   *\n   * Merge semantics across multiple `with()` calls are not symmetric:\n   *\n   * - `plugins` accumulates: every `with()` call appends its `plugins[]`\n   *   to a builder-side list. Builder stores and event handlers also\n   *   accumulate.\n   * - Every other key (`store`'s value map aside, plus `cron`, `direct`,\n   *   `http`, `mail`, `telemetry`, and any ecosystem-augmented keys such\n   *   as `llm`, `mcp`) is last-writer-wins: a second `with()` replaces\n   *   the previously stored config object, and only the most recent\n   *   non-`plugins` keys reach the constructor.\n   *\n   * If you need to combine non-`plugins` keys across sources, merge them\n   * into a single object before calling `with()` (or call `with()` once).\n   *\n   * @param config The configuration object for the context\n   * @returns This builder instance for method chaining\n   */\n  with(config: CraftConfig): this {\n    this.config = config;\n\n    // Extract store entries if provided\n    if (config.store) {\n      for (const [key, value] of config.store.entries()) {\n        this.initialStores.set(key, value);\n      }\n    }\n\n    // Extract event handlers if provided\n    if (config.on) {\n      for (const [event, handler] of Object.entries(config.on)) {\n        const eventName = event as EventName;\n        if (Array.isArray(handler)) {\n          handler.forEach((h) => {\n            const set = this.eventHandlers.get(eventName) ?? new Set();\n            set.add(h as EventHandler<EventName>);\n            this.eventHandlers.set(eventName, set);\n          });\n        } else if (handler) {\n          const set = this.eventHandlers.get(eventName) ?? new Set();\n          set.add(handler as EventHandler<EventName>);\n          this.eventHandlers.set(eventName, set);\n        }\n      }\n    }\n\n    // Accumulate plugins across multiple with() calls. The CraftContext\n    // constructor handles config.cron, config.direct, config.http,\n    // config.mail, and config.telemetry from `this.config`; we don't\n    // duplicate those conversions here. Only `plugins` needs to be\n    // accumulated because successive with() calls overwrite this.config.\n    if (config.plugins) {\n      this.plugins.push(...config.plugins);\n    }\n\n    return this;\n  }\n\n  // binders(...) API removed\n\n  /**\n   * Register an event listener to be attached to the built context.\n   */\n  on<K extends EventName>(event: K, handler: EventHandler<K>): this {\n    const set = this.eventHandlers.get(event) ?? new Set();\n    set.add(handler as unknown as EventHandler<EventName>);\n    this.eventHandlers.set(event, set);\n    return this;\n  }\n\n  /**\n   * Register a one-time event listener to be attached to the built context.\n   * The handler fires once and then auto-unsubscribes.\n   */\n  once<K extends EventName>(event: K, handler: EventHandler<K>): this {\n    const set = this.onceHandlers.get(event) ?? new Set();\n    set.add(handler as unknown as EventHandler<EventName>);\n    this.onceHandlers.set(event, set);\n    return this;\n  }\n\n  /**\n   * Add an initial value to the context store.\n   *\n   * @template K The store key type\n   * @param key The store key\n   * @param value The initial value for the store\n   * @returns This builder instance for method chaining\n   *\n   * @example\n   * ```typescript\n   * // Add an initial channel store\n   * builder.store('routecraft.adapter.channel.store', new Map());\n   * ```\n   */\n  store<K extends keyof StoreRegistry>(key: K, value: StoreRegistry[K]): this {\n    this.initialStores.set(key, value);\n    return this;\n  }\n\n  /**\n   * Add routes to the context.\n   *\n   * Routes can be added as individual RouteDefinitions, RouteBuilders, or arrays of either.\n   * RouteBuilder-like objects (duck-typed by having a .build() that returns RouteDefinition[])\n   * are supported so that builders from another copy of the package (e.g. CLI vs user module)\n   * are still recognized.\n   *\n   * @param routes Individual or array of route definitions/builders to add\n   * @returns This builder instance for method chaining\n   *\n   * @example\n   * ```typescript\n   * // Add a single route\n   * builder.routes(myRoute);\n   *\n   * // Add multiple routes\n   * builder.routes([route1, route2, route3]);\n   *\n   * // Add a route builder\n   * builder.routes(\n   *   craft()\n   *     .from(simple(\"hello\"))\n   *     .to(log())\n   * );\n   * ```\n   */\n  routes(\n    routes:\n      RouteDefinition[] | AnyRouteBuilder[] | RouteDefinition | AnyRouteBuilder,\n  ): this {\n    const addOne = (route: RouteDefinition | AnyRouteBuilder): void => {\n      // Structural check, matching `AnyRouteBuilder` (and the duck-typing\n      // promise above): anything with a callable `.build()` is treated as\n      // a builder. The brand check alone would misclassify unbranded\n      // structural builders as RouteDefinitions; RouteDefinition has no\n      // `build`, so the duck-type cannot misfire the other way.\n      if (typeof (route as Partial<AnyRouteBuilder>).build === \"function\") {\n        this.definitions.push(...(route as AnyRouteBuilder).build());\n      } else {\n        this.definitions.push(route as RouteDefinition);\n      }\n    };\n\n    if (Array.isArray(routes)) {\n      routes.forEach(addOne);\n    } else {\n      addOne(routes);\n    }\n    return this;\n  }\n\n  /**\n   * Build and return a configured CraftContext and CraftClient.\n   *\n   * This finalizes the configuration, runs plugins, and creates a ready-to-use\n   * context with all the configured routes, handlers, and store values.\n   * The client provides a programmatic API for dispatching messages into routes.\n   *\n   * @returns A promise resolving to `{ context, client }`\n   *\n   * @example\n   * ```typescript\n   * const { context, client } = await new ContextBuilder()\n   *   .routes(capabilities)\n   *   .build();\n   *\n   * await context.start();\n   * await client.sendDirect('greet', { name: 'World' });\n   * ```\n   */\n  async build(): Promise<{ context: CraftContext; client: CraftClient }> {\n    // The builder accumulates plugins across multiple with() calls into\n    // `this.plugins`; replace `config.plugins` with the accumulated list so\n    // the constructor sees the union, not just the last with()'s plugins.\n    // Config keys like `telemetry`, `mail`, and registered config appliers\n    // (e.g. `llm`, `mcp`) are converted into plugins inside the constructor\n    // and run before user `plugins[]`; see CraftContext.constructor.\n    const mergedConfig: CraftConfig = {\n      ...this.config,\n      plugins: this.plugins,\n    };\n    const ctx = new CraftContext(mergedConfig);\n\n    // Add stores from builder (config stores already added in constructor)\n    for (const [key, value] of this.initialStores) {\n      if (!this.config?.store?.has(key)) {\n        ctx.setStore(key, value);\n      }\n    }\n\n    // Attach event handlers from builder. `config.on` handlers are already\n    // registered by the constructor, but the builder's `eventHandlers` map\n    // also contains them (with the same handler references), so the\n    // CraftContext's Set-based registry deduplicates.\n    for (const [event, handlers] of this.eventHandlers.entries()) {\n      for (const handler of handlers) {\n        ctx.on(event as EventName, handler as EventHandler<EventName>);\n      }\n    }\n\n    // Attach one-time event handlers from builder (config once handlers already added in constructor)\n    for (const [event, handlers] of this.onceHandlers.entries()) {\n      for (const handler of handlers) {\n        ctx.once(event as EventName, handler as EventHandler<EventName>);\n      }\n    }\n\n    // Run plugins before routes are registered (context runs config.plugins),\n    // then register the routes. A failure in EITHER leaves plugins applied\n    // that nobody can reach, because build() returns no context to tear down:\n    // unwind them here and rethrow the original error unchanged.\n    try {\n      await ctx.initPlugins();\n      ctx.registerRoutes(...this.definitions);\n    } catch (err) {\n      await ctx.unwindFailedBuild();\n      throw err;\n    }\n\n    return { context: ctx, client: new CraftClient(ctx) };\n  }\n}\n\n/**\n * Any route builder, regardless of its tracked {@link BuilderState}.\n *\n * `RouteBuilder<S>` is invariant in its state bag (the body type appears in\n * both parameter and return positions), so a fully chained\n * `RouteBuilder<{ body: X }>` is not assignable to\n * `RouteBuilder<BuilderState>`. Positions that accept \"some finished route\n * builder\" (`ContextBuilder.routes`, the CLI loader, test harnesses) only\n * ever call `.build()`, which does not involve the bag at all, so this\n * minimal structural alias is the correct parameter type for them.\n */\nexport type AnyRouteBuilder = Pick<RouteBuilder, \"build\">;\n\n/**\n * Options for configuring a route.\n */\nexport type RouteOptions = Partial<Pick<RouteDefinition, \"consumer\">> & {\n  /**\n   * Unique identifier for the route.\n   */\n  id: string;\n};\n\n/**\n * Builder for creating route definitions with a fluent API.\n *\n * This builder provides methods for defining the steps in a route,\n * including sources, transformations, filters, destinations, and more.\n *\n * The type parameter tracks the data type flowing through the route\n * at each step, providing type safety throughout the route definition.\n *\n * @template S The {@link BuilderState} bag tracking the data flowing through the route\n *\n * @example\n * ```typescript\n * // Create a simple route that processes a string\n * const route = craft()\n *   .from(simple(\"Hello, World!\"))\n *   .transform(msg => msg.toUpperCase())\n *   .to(log())\n * ```\n */\n\n/**\n * @internal\n *\n * Verifies a finalised route honours the route-scope `.cache()` contract.\n *\n * Route-scope `.cache()` caches a single terminal body per source message.\n * A bare `.split()` produces N terminal exchanges with no fold-back, so\n * there is no single value to cache. A `.split()` that is balanced by a\n * matching `.aggregate()` collapses the children back into one terminal\n * body, which is cacheable.\n *\n * The check counts nesting depth across the step list: every `split`\n * increments, every `aggregate` decrements. A non-zero depth at the end\n * of the route means at least one `split` was not aggregated, so the\n * route is rejected with `RC5003`.\n *\n * A reachable `.defer()` is refused for a related reason: the cache\n * filters sit OUTSIDE the user pipeline (check before it, store after it),\n * while a deferral exits the pipeline and a resume re-enters it partway down.\n * Neither filter would run on either execution, so the route would carry a\n * `.cache()` that silently never caches.\n *\n * A reachable `.authenticate()` is refused because the cache check runs\n * before the pipeline: a hit would return a stored response without\n * running authentication, and the key could not see the principal it would\n * have minted. This holds for a custom key too.\n *\n * Step-scope `.cache()` is unaffected; it wraps a single inner step and\n * never participates in this check.\n */\nfunction assertRouteScopeCacheCompatibility(route: RouteDefinition): void {\n  const hasRouteScopeCache = route.postParseFilters.some(\n    (f) => f.label === \"cache-check\",\n  );\n  if (!hasRouteScopeCache) return;\n\n  if (containsAuthenticate(route.steps)) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        `Route \"${route.id}\" has route-scope .cache() and an .authenticate() step. ` +\n        `The cache check runs before the pipeline, so a hit would return a cached response ` +\n        `without running .authenticate(). Cache the expensive step with a step-scope ` +\n        `.cache() placed after .authenticate() instead.`,\n    });\n  }\n\n  if ((route.deferSteps?.length ?? 0) > 0) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        `Route \"${route.id}\" has route-scope .cache() and a reachable .defer(). ` +\n        `The cache filters wrap the user pipeline, but a deferred exchange exits it and ` +\n        `resumes partway down, so neither the check nor the store would ever run and the ` +\n        `cache would silently do nothing. Cache the expensive step with a step-scope ` +\n        `.cache() instead, or drop the route-scope one.`,\n    });\n  }\n\n  let depth = 0;\n  for (const step of route.steps) {\n    if (step.operation === OperationType.SPLIT) {\n      depth++;\n    } else if (step.operation === OperationType.AGGREGATE && depth > 0) {\n      depth--;\n    }\n  }\n\n  if (depth > 0) {\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        `Route \"${route.id}\" has route-scope .cache() and an unbalanced .split() ` +\n        `(no matching .aggregate()). A fire-and-forget split produces multiple ` +\n        `terminal exchanges, so there is no single body to cache. ` +\n        `Add an .aggregate() to fold the children back into one terminal ` +\n        `value, or use step-scope .cache() to wrap the expensive operation.`,\n    });\n  }\n}\n\n/**\n * Whether any step in the tree, looking through wrapper stacks and into\n * nested sub-pipelines, is an `.authenticate()` step.\n */\nfunction containsAuthenticate(steps: ReadonlyArray<Step<Adapter>>): boolean {\n  return steps.some((step) => {\n    let innermost: Step<Adapter> = step;\n    while (innermost instanceof WrapperStep) innermost = innermost.wrapped;\n    if (innermost instanceof AuthenticateStep) return true;\n    return nestedStepsOf(step).some((nested) =>\n      containsAuthenticate(nested.steps),\n    );\n  });\n}\n\n/**\n * Route-scope staging methods shared by both pre-`.from()` surfaces\n * ({@link PreFromBuilder} and {@link PreFromTypedBuilder}). Methods return\n * `this` so the chain keeps whichever surface it is on: staging calls after\n * a typed `.input()` do not lose the staged body type.\n *\n * @template S - The {@link BuilderState} bag carried into the next route\n */\nexport interface PreFromStaging<S extends BuilderState = BuilderState> {\n  /** Set the route id for the next route. See {@link RouteBuilder.id}. */\n  id(id: string): this;\n  /** Set a human-readable title for the next route. See {@link RouteBuilder.title}. */\n  title(value: string): this;\n  /** Set a human-readable description for the next route. See {@link RouteBuilder.description}. */\n  description(value: string): this;\n  /** Gate the next route on a predicate. See {@link RouteBuilder.enabled}. */\n  enabled(predicate: EnablementPredicate, options?: EnablementOptions): this;\n  /**\n   * Declare input schemas for the next route and retype the chain. When a\n   * body schema is given (bare, or as `{ body }`), the schema's inferred\n   * output type becomes the body type the following `.from(source)` opens\n   * the pipeline with, so no duplicated `.from<T>()` generic is needed.\n   * See {@link RouteBuilder.input}.\n   */\n  input<Schema extends StandardSchemaV1>(\n    schemas: Schema | (RouteSchemas & { body: Schema }),\n  ): PreFromTypedBuilder<SetBody<S, StandardSchemaV1.InferOutput<Schema>>>;\n  /** Declare input schemas (no body schema, so no retyping). See {@link RouteBuilder.input}. */\n  input(schemas: RouteSchemas): this;\n  /** Declare output schemas for the next route. See {@link RouteBuilder.output}. */\n  output(schemas: RouteSchemas | StandardSchemaV1): this;\n  /** Tag the next route. See {@link RouteBuilder.tag}. */\n  tag(value: Tag | Tag[]): this;\n  /** Configure batch processing for the next route. See {@link RouteBuilder.batch}. */\n  batch(options?: { size?: number; flushInterval?: Duration }): this;\n  /**\n   * Attach a ROUTE-SCOPE error handler (catch-all) to the next route. The\n   * step-scope variant lives on the post-`.from()` builder; position picks\n   * the mode. See {@link RouteBuilder.error}.\n   */\n  error(handler: ErrorHandler): this;\n  /**\n   * Configure ROUTE-SCOPE caching for the next route (whole-pipeline\n   * memoisation); a failed exchange is never stored. After `.from()` only\n   * the next step's output is cached, see {@link RouteBuilder.cache}.\n   */\n  cache(options?: CacheOptions<unknown>): this;\n  /**\n   * Configure a ROUTE-SCOPE retry for the next route (re-run the whole\n   * pipeline on failure, chain position 7). The step-scope variant\n   * lives on the post-`.from()` builder. See {@link RouteBuilder.retry}.\n   */\n  retry(options?: RetryOptions): this;\n  /**\n   * Configure a ROUTE-SCOPE timeout for the next route (per-attempt\n   * deadline over the whole pipeline, chain position 8). The\n   * step-scope variant lives on the post-`.from()` builder. See\n   * {@link RouteBuilder.timeout}.\n   */\n  timeout(duration: Duration): this;\n  /**\n   * Configure a ROUTE-SCOPE throttle for the next route (rate-limit the\n   * whole pipeline, chain position 5). The step-scope variant lives on\n   * the post-`.from()` builder. See {@link RouteBuilder.throttle}.\n   */\n  throttle(options: ThrottleOptions): this;\n  /**\n   * Configure a ROUTE-SCOPE circuit breaker for the next route (protect\n   * the whole pipeline, chain position 6). The step-scope variant lives\n   * on the post-`.from()` builder. See {@link RouteBuilder.circuitBreaker}.\n   */\n  circuitBreaker(options: CircuitBreakerOptions): this;\n  /**\n   * Configure a ROUTE-SCOPE concurrency limiter (bulkhead) for the next\n   * route (bound how many exchanges run the whole pipeline at once,\n   * innermost resilience position). The step-scope variant lives on the\n   * post-`.from()` builder. See {@link RouteBuilder.concurrency}.\n   */\n  concurrency(options: ConcurrencyOptions): this;\n  /** Declare an authorization requirement on the next route. See {@link RouteBuilder.authorize}. */\n  authorize(options?: AuthorizeOptions): this;\n  /** Finalize and return the route definition(s). See {@link RouteBuilder.build}. */\n  build: RouteBuilder<S>[\"build\"];\n}\n\n/**\n * The route builder BEFORE `.from()`: only route-scope staging is reachable.\n *\n * `craft()` returns this type, and every staging method on the full\n * {@link RouteBuilder} (`.id()`, `.title()`, ...) flips the chain back into\n * it, so calling a pipeline operation (`.to()`, `.transform()`, `.split()`,\n * ...) before `.from()` is a COMPILE error rather than only the runtime\n * RC2001/RC2002 it has always been. The runtime guards remain for plain\n * JavaScript users; this interface is the type-level mirror of the same\n * contract.\n *\n * There is no separate runtime class: the value behind this type is the one\n * `RouteBuilder` instance, re-surfaced. `.from()` opens the route and hands\n * back the full pipeline surface. A `.input()` call with a body schema\n * flips the chain into {@link PreFromTypedBuilder} instead, which seeds\n * `.from()` with the schema's inferred body type.\n *\n * @template S - The {@link BuilderState} bag carried into the next route\n */\nexport interface PreFromBuilder<\n  S extends BuilderState = BuilderState,\n> extends PreFromStaging<S> {\n  /**\n   * Open the route: define its source(s) and enter the pipeline surface.\n   * Derived from the class via an indexed-access type so the (ordering\n   * sensitive) overload set is defined exactly once, on\n   * {@link RouteBuilder.from}; a future overload change cannot diverge\n   * between the pre-`from` and post-`from` surfaces.\n   */\n  from: RouteBuilder<S>[\"from\"];\n}\n\n/**\n * The pre-`.from()` surface after `.input()` declared a body schema: the\n * schema's inferred output type is staged in `S`, and `.from(source)` opens\n * the pipeline with that body type instead of inferring (typically\n * `unknown`) from the source adapter. The engine validates every inbound\n * body against the schema before the first step runs, which is what makes\n * seeding the static type from the schema sound.\n *\n * An explicit `.from<T>(source)` generic still overrides the staged type.\n *\n * @template S - The {@link BuilderState} bag, body already set from the schema\n */\nexport interface PreFromTypedBuilder<\n  S extends BuilderState = BuilderState,\n> extends PreFromStaging<S> {\n  /**\n   * Open the route with the body type staged by `.input()`. Accepts one or\n   * more sources; multi-ingress routes require the `.input()` body schema\n   * anyway (RC2001), so every channel validates to this one type. The\n   * spread forms of {@link RouteBuilder.from} apply here too.\n   */\n  from(...sources: SourceList): RouteBuilder<S>;\n  /**\n   * Open the route with an explicit body type, overriding the staged one.\n   */\n  from<T>(...sources: SourceList): RouteBuilder<SetBody<S, T>>;\n}\n\nexport class RouteBuilder<\n  S extends BuilderState = BuilderState,\n> extends StepBuilderBase<S> {\n  protected currentRoute?: RouteDefinition;\n  protected routes: RouteDefinition[] = [];\n  /**\n   * Routes whose id was generated because no `.id()` was staged, mapped to\n   * whether their route-scope `.cache()` uses the default key.\n   */\n  private readonly unnamedRoutes = new WeakMap<RouteDefinition, boolean>();\n\n  // Pending options set via .id() / .batch() / .error() / .description() / ... before .from()\n  protected pendingOptions?:\n    | {\n        id?: string;\n        consumer?: {\n          type: ConsumerType<Consumer>;\n          options?: unknown;\n        };\n        errorHandler?: ErrorHandler;\n        cacheConfig?: ResolvedCacheOptions;\n        retryConfig?: ResolvedRetryOptions;\n        timeoutConfig?: ResolvedTimeoutOptions;\n        throttleConfigs?: ResolvedThrottleOptions[];\n        circuitBreakerConfig?: ResolvedCircuitBreakerOptions;\n        concurrencyConfigs?: ResolvedConcurrencyOptions[];\n        discovery?: RouteDiscovery;\n        enablement?: RouteEnablement;\n        authorizers?: AuthorizeOptions[];\n      }\n    | undefined;\n\n  constructor() {\n    super();\n    setBrand(this, BRAND.RouteBuilder);\n  }\n\n  /**\n   * Set the route id for the next route to be created.\n   * Stages the id; does not affect the current route if one already exists.\n   *\n   * @param id - Unique route identifier (used in logs and context.getRouteById())\n   * @returns This builder for chaining\n   *\n   * @example\n   * ```typescript\n   * craft().id('ingest-api').from(http({ path: '/ingest', method: 'POST' })).to(log()).build();\n   * ```\n   */\n  id(id: string): PreFromBuilder {\n    this.assertNoPendingWrappers(\"id\");\n    this.pendingOptions = { ...(this.pendingOptions ?? {}), id };\n    logger.trace({ route: id }, \"Staging route id for next route\");\n    return this.prelude();\n  }\n\n  /**\n   * Set a human-readable title for the next route. Mirrored into the\n   * direct / mcp registries so discovery consumers (agents, docs) can\n   * display it alongside the id.\n   */\n  title(value: string): PreFromBuilder {\n    this.mergeDiscovery({ title: value });\n    return this.prelude();\n  }\n\n  /**\n   * Set a human-readable description for the next route. Used by\n   * discovery-aware adapters when exposing the route to external consumers\n   * (agents, MCP clients).\n   */\n  description(value: string): PreFromBuilder {\n    this.mergeDiscovery({ description: value });\n    return this.prelude();\n  }\n\n  /**\n   * Gate the next route on a predicate. A route whose predicate is false is\n   * `disabled`: registered and known to the context, not started, not\n   * intaking, and not advertised as an agent tool.\n   *\n   * This is what makes \"the agent cannot call this until I supply\n   * credentials\" true by construction. The tool surface is derived from what\n   * the context has enabled, so a disabled capability is never offered to\n   * the model rather than being offered and failing when called.\n   *\n   * Returning `true` enables the route. Returning a STRING disables it and\n   * that string is the reason ops reports, which is why there is no separate\n   * reason argument: one declaration cannot drift from the other. A\n   * predicate that throws leaves the route disabled with the error message\n   * as its reason and never fails the boot, because a missing credential is\n   * a configuration state and not a reason to take the process down.\n   *\n   * Route metadata, not a filter: this decides whether the route runs at\n   * all, so it sits beside `.id()` and `.description()` and never enters the\n   * pre-from filter chain. It is evaluated per route lifecycle, never per\n   * exchange.\n   *\n   * @param predicate - Returns `true`, or a string naming why it is off.\n   * @param options - `refresh` re-evaluates on an interval or a cron\n   *   schedule. Omitted (or `\"manual\"`) is MANUAL: evaluated once as the\n   *   route starts and never again until something explicitly asks, which\n   *   keeps the common environment-variable case free of any recurring cost.\n   *\n   * @example\n   * ```typescript\n   * craft()\n   *   .id('mail-inbound')\n   *   .description('Triage inbound mail')\n   *   .enabled(() =>\n   *     env.MAIL_USER && env.MAIL_APP_PASSWORD\n   *       ? true\n   *       : 'MAIL_USER and MAIL_APP_PASSWORD are not set',\n   *   )\n   *   .from(mail({ account: 'default', folder: 'INBOX' }))\n   *   .to(direct('triage'));\n   * ```\n   */\n  enabled(\n    predicate: EnablementPredicate,\n    options?: EnablementOptions,\n  ): PreFromBuilder {\n    if (typeof predicate !== \"function\") {\n      throw rcError(\"RC2001\", undefined, {\n        message: `.enabled() takes a predicate function returning true or a reason string, got ${typeof predicate}.`,\n      });\n    }\n    if (this.pendingOptions?.enablement !== undefined) {\n      throw rcError(\"RC2001\", undefined, {\n        message: `Route metadata already declared: .enabled() can only be called once per route.`,\n      });\n    }\n    // Resolved here rather than at start so a malformed cadence fails while\n    // the route is being built, which is where every other staged option\n    // fails, instead of surfacing as a dead refresh timer at boot.\n    if (\n      options?.refresh !== undefined &&\n      options.refresh !== MANUAL_REFRESH &&\n      !isCronCadence(options.refresh)\n    ) {\n      parseDuration(options.refresh as Duration, \".enabled({ refresh })\");\n    }\n    // Resolved here for the same reason the cadence is: a malformed grace\n    // must fail while the route is being built, not when a transition\n    // eventually needs it.\n    if (\n      options?.drainGrace !== undefined &&\n      options.drainGrace !== NEVER_FORCE\n    ) {\n      parseDuration(options.drainGrace, \".enabled({ drainGrace })\", 0);\n    }\n    this.pendingOptions = {\n      ...(this.pendingOptions ?? {}),\n      enablement: {\n        predicate,\n        ...(options?.refresh !== undefined ? { refresh: options.refresh } : {}),\n        ...(options?.drainGrace !== undefined\n          ? { drainGrace: options.drainGrace }\n          : {}),\n      },\n    };\n    return this.prelude();\n  }\n\n  /**\n   * Declare input schemas for the next route. The engine validates incoming\n   * message bodies and headers against these schemas before any pipeline\n   * step runs, so the pipeline never sees an invalid message. A failure\n   * throws `RC5065`, which a route `.error()` handler can recover;\n   * unrecovered, it emits `route:exchange:failed`. Accepts either a bundle\n   * (`{ body, headers }`) or a bare Standard Schema as a body-only shorthand.\n   *\n   * Issue messages are client-facing. The `http()` source and the ops\n   * dispatch door answer an unrecovered failure with 400 carrying each\n   * issue's path and message verbatim, so a custom message on a refinement\n   * or an async validator reaches the caller as written: keep internal\n   * detail out of it.\n   *\n   * When a body schema is given, the chain is retyped: the following\n   * `.from(source)` opens the pipeline with the schema's inferred output\n   * type, so the type does not have to be repeated as a `.from<T>()`\n   * generic. An explicit `.from<T>()` still overrides the staged type.\n   *\n   * @example\n   * ```typescript\n   * craft()\n   *   .id('lookup-user')\n   *   .input({ body: UserQuerySchema })\n   *   .from(direct())\n   *   // the body is already typed as the schema output\n   *   .transform((body) => findUser(body.userId))\n   * ```\n   */\n  input<Schema extends StandardSchemaV1>(\n    schemas: Schema | (RouteSchemas & { body: Schema }),\n  ): PreFromTypedBuilder<SetBody<S, StandardSchemaV1.InferOutput<Schema>>>;\n  input(schemas: RouteSchemas): PreFromBuilder;\n  input(\n    schemas: RouteSchemas | StandardSchemaV1,\n  ): PreFromBuilder | PreFromTypedBuilder<SetBody<S, unknown>> {\n    this.mergeDiscovery({ input: this.normalizeSchemas(schemas) });\n    return this.prelude();\n  }\n\n  /**\n   * Declare output schemas for the next route. The engine validates the\n   * final exchange against these schemas before the primary destination\n   * fires; a validation failure is routed to the error handler. Accepts\n   * either a bundle (`{ body, headers }`) or a bare Standard Schema as a\n   * body-only shorthand.\n   */\n  output(schemas: RouteSchemas | StandardSchemaV1): PreFromBuilder {\n    this.mergeDiscovery({ output: this.normalizeSchemas(schemas) });\n    return this.prelude();\n  }\n\n  /**\n   * Tag the next route. Accepts a single tag or an array; multiple\n   * `.tag()` calls before `.from()` accumulate (deduplicated, insertion\n   * order preserved). Empty strings are rejected.\n   *\n   * Tags drive selectors like `tools({ tagged: \"read-only\" })` in\n   * `@routecraft/ai`; use the `KnownTag` literals (`\"read-only\"`,\n   * `\"destructive\"`, `\"idempotent\"`, `\"open-world\"`) where they fit, and any\n   * string otherwise. On a route exposed via `.from(mcp())`, these four tags\n   * also derive the MCP tool annotation hints (`readOnlyHint`,\n   * `destructiveHint`, `idempotentHint`, `openWorldHint`), so the same fact is\n   * declared once; explicit `annotations` on `mcp()` still override per-key.\n   */\n  tag(value: Tag | Tag[]): PreFromBuilder {\n    const incoming = (Array.isArray(value) ? value : [value]).map((t) => {\n      if (typeof t !== \"string\" || t.trim() === \"\") {\n        throw rcError(\"RC2001\", undefined, {\n          message: `Route .tag() value must be a non-empty string.`,\n        });\n      }\n      return t.trim();\n    });\n    const existing = this.pendingOptions?.discovery?.tags ?? [];\n    const merged = [...existing];\n    for (const t of incoming) if (!merged.includes(t)) merged.push(t);\n    this.mergeDiscovery({ tags: merged });\n    return this.prelude();\n  }\n\n  private mergeDiscovery(partial: Partial<RouteDiscovery>): void {\n    const existing = this.pendingOptions?.discovery;\n    if (partial.input !== undefined && existing?.input !== undefined) {\n      throw rcError(\"RC2001\", undefined, {\n        message: `Route metadata already declared: .input() can only be called once per route.`,\n      });\n    }\n    if (partial.output !== undefined && existing?.output !== undefined) {\n      throw rcError(\"RC2001\", undefined, {\n        message: `Route metadata already declared: .output() can only be called once per route.`,\n      });\n    }\n    this.pendingOptions = {\n      ...(this.pendingOptions ?? {}),\n      discovery: { ...(existing ?? {}), ...partial },\n    };\n  }\n\n  private normalizeSchemas(\n    value: RouteSchemas | StandardSchemaV1,\n  ): RouteSchemas {\n    return \"~standard\" in value ? { body: value as StandardSchemaV1 } : value;\n  }\n\n  /**\n   * Configure batch processing for the next route to be created.\n   * Stages the batch consumer; does not affect the current route if one already exists.\n   *\n   * @param options - Optional `size` (batch size) and `flushInterval`\n   * @returns This builder for chaining\n   *\n   * @example\n   * ```typescript\n   * craft().batch({ size: 10, flushInterval: \"1s\" }).from(timer({ interval: \"1s\" })).to(log()).build();\n   * ```\n   */\n  batch(options?: { size?: number; flushInterval?: Duration }): PreFromBuilder {\n    rejectStaleOptions(options, \"batch\");\n    const mapped = {\n      size: options?.size,\n      time:\n        options?.flushInterval === undefined\n          ? undefined\n          : parseDuration(options.flushInterval, \"batch({ flushInterval })\"),\n    };\n    this.pendingOptions = {\n      ...(this.pendingOptions ?? {}),\n      consumer: {\n        type: BatchConsumer,\n        options: mapped,\n      },\n    };\n    logger.trace(\"Staging batch processing for next route\");\n    return this.prelude();\n  }\n\n  /**\n   * Attach an error handler. Dual-mode based on position relative to\n   * `.from()`:\n   *\n   * - **Before `.from()`** (route scope): stages a catch-all for the\n   *   route's pipeline. When any step throws an unhandled error the\n   *   handler runs and the pipeline does NOT resume; the handler's\n   *   return value becomes the route's final exchange body.\n   * - **After `.from()`** (step scope): wraps the immediately next\n   *   step. When that step throws the handler runs, its return value\n   *   replaces `exchange.body`, and the pipeline continues with the\n   *   next step. Subsequent steps see the recovery as if nothing went\n   *   wrong.\n   *\n   * The handler signature is identical in both positions\n   * (`(error, exchange, forward) => unknown`). When a step-scope\n   * handler itself throws, the wrapper rethrows so a route-scope\n   * handler (when set) catches it; otherwise the default error path\n   * fires (`route:error`, `context:error`, `route:exchange:failed`). The\n   * route is NOT stopped.\n   *\n   * @param handler - Receives the error, the exchange at the point of\n   *   failure, and a `forward` function to delegate to another route\n   *   via the direct adapter.\n   * @returns This builder for chaining\n   *\n   * @example Route-scope catch-all\n   * ```ts\n   * craft()\n   *   .id('process-orders')\n   *   .error((err, ex, forward) => forward('error-route', { reason: String(err) }))\n   *   .from(timer({ interval: \"1m\" }))\n   *   .to(dangerousDestination)\n   * ```\n   *\n   * @example Step-scope recovery (pipeline continues)\n   * ```ts\n   * craft()\n   *   .id('resilient-pipeline')\n   *   .from(timer({ interval: \"1m\" }))\n   *   .transform(prepareRequest)\n   *   .error((err) => ({ fallback: true, reason: String(err) }))\n   *   .to(http({ url: 'https://flaky.api/endpoint' }))\n   *   .to(database())\n   * ```\n   *\n   * wrapper pattern. See `.standards/resilience-wrappers.md`.\n   */\n  override error(handler: ErrorHandler): this {\n    if (this.currentRoute === undefined || this.pendingOptions !== undefined) {\n      // Pre-`.from()` for the FIRST route, OR staging for the NEXT\n      // route in a chained `craft().id(a).from(...).to(...).id(b)\n      // .error(h)...` pattern. In both cases `.error()` configures\n      // route-scope behaviour for the route currently being staged\n      // by `pendingOptions`. The base-class wrapper stack stays empty.\n      this.pendingOptions = {\n        ...(this.pendingOptions ?? {}),\n        errorHandler: handler,\n      };\n      logger.trace(\"Staging route-scope error handler for next route\");\n      return this;\n    }\n    // Post-`.from()` on the current route: delegate to the base-class\n    // step-scope path so the next pushed step is wrapped in\n    // `ErrorWrapperStep`.\n    return super.error(handler);\n  }\n\n  /**\n   * Cache. Dual-mode, and the position decides what is cached:\n   *\n   * - **Before `.from()` (route scope):** caches the whole route. The\n   *   route looks up its provider before any pipeline step runs. On a\n   *   hit, the entire pipeline is skipped and the cached body is\n   *   returned to the source as the route's final exchange body. On a\n   *   miss, the pipeline runs and the terminal body is stored only when\n   *   the exchange completes; a failed exchange is never stored. Side\n   *   effects (e.g. `.to(destination)` calls) do NOT replay on a hit.\n   *\n   * - **After `.from()` (step scope):** caches only the output of the\n   *   immediately-next step, whatever the rest of the route does. A step\n   *   that returns an error reply without throwing (an `http()` enricher\n   *   with `throwOnHttpError: false` answering 503) has that reply\n   *   cached. See {@link StepBuilderBase.cache} for the step-scope\n   *   contract.\n   *\n   * The default key is namespaced by route id (plus the cache's site at\n   * step scope) and by the principal's issuer and subject with its actor\n   * chain, then the body; a bodiless exchange needs an explicit `key`,\n   * which is used verbatim. See {@link CacheOptions.key}.\n   *\n   * Route scope is refused at build (`RC5003`) on a route whose pipeline\n   * contains `.authenticate()`: the cache check runs before the pipeline,\n   * so a hit would skip authentication.\n   *\n   * Routes with an unbalanced `.split()` are not supported at route\n   * scope (the pipeline produces N terminals rather than one) and throw\n   * `RC5003` at build time. Use step-scope `.cache()` to wrap the\n   * expensive step inside such a route.\n   */\n  override cache(options: CacheOptions<S[\"body\"]> = {}): this {\n    if (this.currentRoute === undefined || this.pendingOptions !== undefined) {\n      // Route scope: stage the resolved config onto pendingOptions so\n      // the next `.from()` writes it into the new RouteDefinition.\n      this.pendingOptions = {\n        ...(this.pendingOptions ?? {}),\n        cacheConfig: resolveCacheOptions(options as CacheOptions),\n      };\n      logger.trace(\"Staging route-scope cache config for next route\");\n      return this;\n    }\n    return super.cache(options);\n  }\n\n  /**\n   * Timeout. Dual-mode:\n   *\n   * - **Before `.from()` (route scope):** bounds each run of the whole\n   *   pipeline with a deadline at pre-from filter chain position 8\n   *   (inside `.retry()`, so every attempt gets its own deadline). On\n   *   expiry the pipeline throws `RC5011`, which a route-scope\n   *   `.error()` handler catches like any other failure.\n   *\n   * - **After `.from()` (step scope):** wraps the immediately-next\n   *   step; see {@link StepBuilderBase.timeout} for the step-scope\n   *   contract.\n   *\n   * The bounded work is not cancelled on expiry (promises cannot be\n   * cancelled); the timeout bounds how long the route waits, not the\n   * work itself.\n   */\n  override timeout(duration: Duration): this {\n    if (this.currentRoute === undefined || this.pendingOptions !== undefined) {\n      // Route scope: stage the resolved config (validates the deadline\n      // at staging time) so the next `.from()` writes it into the new\n      // RouteDefinition.\n      this.pendingOptions = {\n        ...(this.pendingOptions ?? {}),\n        timeoutConfig: resolveTimeoutOptions(duration),\n      };\n      logger.trace(\"Staging route-scope timeout config for next route\");\n      return this;\n    }\n    return super.timeout(duration);\n  }\n\n  /**\n   * Retry. Dual-mode:\n   *\n   * - **Before `.from()` (route scope):** re-runs the whole pipeline\n   *   on failure at pre-from filter chain position 7 (outside\n   *   `.timeout()`, inside `.error()`). Every attempt re-runs the\n   *   chain tail including the cache check, so a value cached by a\n   *   previous attempt short-circuits the next one. After the final\n   *   attempt fails, the error reaches the route-scope `.error()`\n   *   handler (when set) or the default error path.\n   *\n   * - **After `.from()` (step scope):** wraps the immediately-next\n   *   step; see {@link StepBuilderBase.retry} for the step-scope\n   *   contract.\n   *\n   * Route-scope re-attempts re-run user steps and their side effects;\n   * wrap only the flaky step with step-scope `.retry()` when the rest\n   * of the pipeline must not repeat.\n   *\n   * With a `.split()` in the pipeline, every child still processes to\n   * completion on each attempt, but only a failure of the MAIN\n   * exchange triggers a re-attempt: a failed split child resolves\n   * through the per-child failure events exactly as it would without\n   * `.retry()`. Wrap a flaky per-child step with step-scope `.retry()`\n   * after the split instead.\n   */\n  override retry(options: RetryOptions = {}): this {\n    if (this.currentRoute === undefined || this.pendingOptions !== undefined) {\n      // Route scope: stage the resolved config (validates maxAttempts\n      // at staging time) so the next `.from()` writes it into the new\n      // RouteDefinition, mirroring the `.cache()` staging convention.\n      this.pendingOptions = {\n        ...(this.pendingOptions ?? {}),\n        retryConfig: resolveRetryOptions(options),\n      };\n      logger.trace(\"Staging route-scope retry config for next route\");\n      return this;\n    }\n    return super.retry(options);\n  }\n\n  /**\n   * Throttle. Dual-mode:\n   *\n   * - **Before `.from()` (route scope):** rate-limits the whole pipeline\n   *   at pre-from filter chain position 5, OUTSIDE the resilience\n   *   wrappers (a throttled request never reaches retry / timeout). The\n   *   gate runs before the cache check, so a paced request does not\n   *   consume a cache lookup until it is admitted. Each gate's limiter\n   *   is built per Route, so a definition reused across contexts does\n   *   not share buckets.\n   *\n   *   Stacking is supported: multiple `.throttle()` calls before\n   *   `.from()` AND-combine into independent gates (e.g. a global\n   *   ceiling plus a per-principal `key` limit); the exchange must be\n   *   admitted by all of them.\n   *\n   *   This gate paces exchanges WITHIN the pipeline: it rate-limits the\n   *   downstream work but does not pause the source consumer, so under\n   *   high concurrency exchanges queue in flight while they wait for a\n   *   token. True source backpressure (a consumer that stops pulling) is\n   *   a follow-up; see `.standards/resilience-wrappers.md` section 7.\n   *\n   * - **After `.from()` (step scope):** wraps the immediately-next step;\n   *   see {@link StepBuilderBase.throttle} for the step-scope contract.\n   */\n  override throttle(options: ThrottleOptions): this {\n    if (this.currentRoute === undefined || this.pendingOptions !== undefined) {\n      // Route scope: append the resolved config (validates at staging\n      // time) so the next `.from()` builds one gate per config. Stacking\n      // accumulates rather than overwriting, so independent limits\n      // compose.\n      this.pendingOptions = {\n        ...(this.pendingOptions ?? {}),\n        throttleConfigs: [\n          ...(this.pendingOptions?.throttleConfigs ?? []),\n          resolveThrottleOptions(options),\n        ],\n      };\n      logger.trace(\"Staging route-scope throttle config for next route\");\n      return this;\n    }\n    return super.throttle(options);\n  }\n\n  /**\n   * Circuit breaker. Dual-mode:\n   *\n   * - **Before `.from()` (route scope):** protects the whole pipeline at\n   *   pre-from filter chain position 6, OUTSIDE `.retry()` (#7) and\n   *   `.timeout()` (#8) and INSIDE `.throttle()` (#5). When the breaker\n   *   is open the pipeline is skipped entirely and the configured\n   *   `fallback` becomes the body (or `RC5025` is thrown when no fallback\n   *   is set, which a route-scope `.error()` handler can catch). Because\n   *   it sits outside retry, one fully exhausted attempt is recorded as a\n   *   single breaker failure rather than one per retry. State is per\n   *   Route, so a definition reused across contexts does not share a\n   *   circuit.\n   *\n   * - **After `.from()` (step scope):** wraps the immediately-next step;\n   *   see {@link StepBuilderBase.circuitBreaker} for the step-scope\n   *   contract.\n   *\n   * Unlike `.throttle()`, circuit breakers do not stack: a single breaker\n   * per route protects the pipeline. A second `.circuitBreaker()` before\n   * `.from()` overwrites the first.\n   */\n  override circuitBreaker(options: CircuitBreakerOptions): this {\n    if (this.currentRoute === undefined || this.pendingOptions !== undefined) {\n      // Route scope: stage the resolved config (validates the options at\n      // staging time) so the next `.from()` builds one controller per\n      // RouteDefinition.\n      this.pendingOptions = {\n        ...(this.pendingOptions ?? {}),\n        circuitBreakerConfig: resolveCircuitBreakerOptions(options),\n      };\n      logger.trace(\"Staging route-scope circuit breaker config for next route\");\n      return this;\n    }\n    return super.circuitBreaker(options);\n  }\n\n  /**\n   * Concurrency limiter (bulkhead). Dual-mode:\n   *\n   * - **Before `.from()` (route scope):** bounds the whole pipeline to\n   *   `max` simultaneous in-flight exchanges at the INNERMOST resilience\n   *   position, inside `.retry()` (#7) and `.timeout()` (#8) and inside\n   *   `.circuitBreaker()` (#6) / `.throttle()` (#5). Innermost means a slot\n   *   is acquired per attempt and released between retry backoffs, so a\n   *   scarce slot is never held while a retry sleeps; it also means an\n   *   outer `.retry()` can re-acquire a slot after a `reject`-mode\n   *   `RC5026`. State is per Route, so a definition reused across contexts\n   *   does not share a slot pool. Multiple `.concurrency()` calls stack and\n   *   nest (e.g. a global `max` plus a per-key `max`).\n   *\n   * - **After `.from()` (step scope):** wraps the immediately-next step;\n   *   see {@link StepBuilderBase.concurrency} for the step-scope contract.\n   */\n  override concurrency(options: ConcurrencyOptions): this {\n    if (this.currentRoute === undefined || this.pendingOptions !== undefined) {\n      // Route scope: append the resolved config (validates at staging time)\n      // so the next `.from()` builds one controller per config. Stacking\n      // accumulates rather than overwriting, so independent limits compose.\n      this.pendingOptions = {\n        ...(this.pendingOptions ?? {}),\n        concurrencyConfigs: [\n          ...(this.pendingOptions?.concurrencyConfigs ?? []),\n          resolveConcurrencyOptions(options),\n        ],\n      };\n      logger.trace(\"Staging route-scope concurrency config for next route\");\n      return this;\n    }\n    return super.concurrency(options);\n  }\n\n  /**\n   * Declare an authorization requirement on the next route. **Route-only**:\n   * stages the authorizer onto the next-route options and runs at route\n   * entry, before any pipeline step. Same staging convention as `.id`,\n   * `.title`, `.description`, `.input`, `.output`, `.tag`, and `.batch`:\n   * a route-level pipeline op (e.g. `.to()`, `.transform()`) called while\n   * authorizers are staged but no new `.from()` has opened a route throws\n   * RC2001. For a mid-pipeline check use `.validate(authorize({...}))`\n   * directly.\n   *\n   * The check verifies that the inbound exchange carries an authenticated\n   * principal and (optionally) that the principal has every required role\n   * and scope. It does NOT issue, mint, or attach any credential: it\n   * asserts an existing identity meets the criteria.\n   *\n   * Multiple `.authorize()` calls stack and AND-combine: each runs in\n   * declaration order, so a missing role in the first call short-circuits\n   * before later predicates run.\n   *\n   * Failures throw RC5012 (no principal) or RC5015 (principal failed the\n   * role / scope / predicate check). A route-level `.error()` handler\n   * catches both like any other validation failure.\n   *\n   * @param options - Required roles, scopes, or a custom predicate. When\n   *   omitted, only existence of an authenticated principal is checked.\n   *\n   * @example Route-entry guard on an MCP tool\n   * ```ts\n   * craft()\n   *   .id('delete-user')\n   *   .description('Delete a user by id')\n   *   .authorize({ roles: ['admin'] })\n   *   .from(mcp({ annotations: { destructiveHint: true } }))\n   *   .to(deleteUserDestination)\n   * ```\n   *\n   * @example Stacked authorizers on an HTTP route\n   * ```ts\n   * craft()\n   *   .id('admin-billing')\n   *   .authorize({ roles: ['admin'] })\n   *   .authorize({ scopes: ['billing:write'] })\n   *   .from(http({ path: '/admin/billing', method: 'POST' }))\n   *   .to(billingDestination)\n   * ```\n   *\n   * @example Chained routes\n   * ```ts\n   * craft()\n   *   .id('public').from(simple('hi')).to(noop())\n   *   .id('admin').authorize({ roles: ['admin'] }).from(adminSrc).to(noop())\n   * ```\n   */\n  authorize(options?: AuthorizeOptions): PreFromBuilder {\n    const next = this.pendingOptions ?? {};\n    const existing = next.authorizers ?? [];\n    this.pendingOptions = {\n      ...next,\n      authorizers: [...existing, options ?? {}],\n    };\n    logger.trace(\"Staging route-scope authorization for next route\");\n    return this.prelude();\n  }\n\n  /**\n   * Define the source of data for this route.\n   * This is typically the first step in defining a route.\n   *\n   * @template T The type of data produced by the source\n   * @param sources One or more source adapters or functions. Multiple\n   *   sources require `.input({ body })` declared first (RC2001) so every\n   *   ingress validates to the same body type.\n   * @returns A RouteBuilder with the specified type T\n   * @example\n   * // Simple source with inferred type\n   * .from<string[]>(http({ path: '/api/data', method: 'GET' }))\n   *\n   * // Source with callable function\n   * .from<User[]>(async () => {\n   *   const response = await fetch('https://api.example.com/users');\n   *   return response.json();\n   * })\n   *\n   * // After `.input({ body: schema })`, the schema's inferred output type\n   * // flows through the chain automatically (see PreFromTypedBuilder):\n   * // .input({ body: MySchema }).from(direct())\n   *\n   * // Expose one capability on several ingresses (internal + agents +\n   * // integrations) that all feed the same pipeline. Multi-ingress requires\n   * // `.input()` so every channel validates and normalizes to one body type:\n   * // .input(QuerySchema).from(direct(), mcp(), http({ path: '/q', method: 'POST' }))\n   *\n   * // Spread sources in; `.from(list)` without the spread is ONE Iterable\n   * // source that emits each element as a body. A spread on its own needs a\n   * // `SourceList` return type:\n   * // .input(QuerySchema).from(direct(), ...extraIngresses)\n   * // .input(QuerySchema).from(...ingresses())\n   *\n   * The multiple-source `.input()` requirement is a deliberate build-time\n   * precondition, enforced at `.from()` with RC2001 rather than in the type\n   * system: the variadic overload is statically reachable on THIS class.\n   * Chains that declare `.input({ body })` first go through\n   * {@link PreFromTypedBuilder.from} instead, where the staged schema type\n   * seeds the body so multi-ingress is typed without an explicit generic.\n   */\n  from<T>(source: SourceLike<T>): RouteBuilder<SetBody<S, T>>;\n  // Stays last so a single source still resolves to the inferring overload above.\n  from<T>(...sources: SourceList): RouteBuilder<SetBody<S, T>>;\n  from<T>(...sources: Array<SourceLike<T>>): RouteBuilder<SetBody<S, T>> {\n    this.assertNoPendingWrappers(\"from\");\n    if (sources.length === 0) {\n      throw rcError(\"RC2001\", undefined, {\n        message: `Route .from() requires at least one source.`,\n      });\n    }\n    const id = this.pendingOptions?.id ?? randomUUID();\n    const consumer = this.pendingOptions?.consumer ?? {\n      type: SimpleConsumer,\n      options: undefined,\n    };\n    const errorHandler = this.pendingOptions?.errorHandler;\n    const cacheConfig = this.pendingOptions?.cacheConfig;\n    const retryConfig = this.pendingOptions?.retryConfig;\n    const timeoutConfig = this.pendingOptions?.timeoutConfig;\n    const throttleConfigs = this.pendingOptions?.throttleConfigs;\n    const circuitBreakerConfig = this.pendingOptions?.circuitBreakerConfig;\n    const concurrencyConfigs = this.pendingOptions?.concurrencyConfigs;\n    const discovery = this.pendingOptions?.discovery;\n    const enablement = this.pendingOptions?.enablement;\n    const authorizers = this.pendingOptions?.authorizers ?? [];\n\n    // Multi-ingress routes feed one shared pipeline, so they need one shared\n    // input contract. Require `.input()` (with a body schema) so every\n    // ingress validates and normalizes its heterogeneous raw body (direct\n    // `unknown`, mcp `McpMessage`, http `HttpRequestBody`) to the same type\n    // before the pipeline runs. Without it the pipeline body would be an\n    // unsound union of the raw source types. A single source keeps the\n    // existing behaviour (type flows from `.from<T>()` or the source).\n    if (sources.length > 1 && !discovery?.input?.body) {\n      throw rcError(\"RC2001\", undefined, {\n        message: `Route \"${id}\": .from() with multiple sources requires .input({ body }) so every ingress validates to one shared body type. Declare .input() before .from(), or expose each channel as its own single-source route.`,\n      });\n    }\n\n    logger.trace(\n      { route: id, sourceCount: sources.length },\n      \"Creating route definition\",\n    );\n\n    // Assemble the route's pre-from filter chain. Order is fixed by\n    // `.standards/pre-from-filter-chain.md`:\n    //\n    //   preParseFilters   -> .authorize() (#2)\n    //   parse              (#3; dynamic, source-attached, inserted at runtime)\n    //   .input()           (#4; dynamic like parse -- the consumer handler\n    //                       stashes the validator on exchange internals and\n    //                       runPipeline runs it inside the parse step, or as\n    //                       a standalone synthetic input step for\n    //                       parser-less sources. RC5065 is routable through\n    //                       `.error()` either way; see #447.)\n    //   postParseFilters  -> .cache() check (#9); reserved slot for future\n    //                        .circuitBreaker() (#6). Route-scope .throttle()\n    //                        (#5), .retry() (#7), and .timeout() (#8) sit\n    //                        OUTSIDE this array and ride on RouteDefinition\n    //                        fields instead (see below)\n    //   userSteps         -> declaration order, unchanged\n    //   postFromFilters   -> .cache() store (#10)\n    //\n    // The user does NOT control this order: `.authorize().cache()`\n    // and `.cache().authorize()` produce identical chains.\n    const authorizerSteps = authorizers.map(\n      (opts) => new ValidateStep(authorize(opts)),\n    );\n    const preParseFilters: Step<Adapter>[] = authorizerSteps;\n\n    const postParseFilters: Step<Adapter>[] = cacheConfig\n      ? [buildCacheCheckStep(cacheConfig)]\n      : [];\n\n    // Route-scope throttle (#5) is a one-shot admission gate, not a\n    // segment, but it must sit OUTSIDE the retry (#7) / timeout (#8)\n    // segments so a retried attempt re-runs only the tail below it and\n    // never re-acquires a token. It therefore rides on its own\n    // definition field (like retry / timeout) rather than in\n    // `postParseFilters`, which the executor wraps INSIDE the segments.\n    // One gate per `.throttle()` call (they AND-combine); each gate's\n    // limiter is built per Route at runtime, not shared here.\n    const throttleGates = throttleConfigs?.map((cfg) =>\n      buildThrottleCheckStep(cfg),\n    );\n\n    // Route-scope circuit breaker (#6) holds persistent per-Route state\n    // (the failure window + the open/half-open machine), so unlike retry /\n    // timeout (re-built into a segment per run from a plain config object)\n    // its live controller is built ONCE here and stored on the definition.\n    // The pipeline executor wraps the chain tail in a breaker segment\n    // around this controller, OUTSIDE the retry / timeout segments. The\n    // controller keys its machines by Route, so a definition reused across\n    // contexts gives each Route its own circuit.\n    const circuitBreakerController = circuitBreakerConfig\n      ? new CircuitBreakerController(circuitBreakerConfig)\n      : undefined;\n\n    // Route-scope concurrency (#bulkhead) also holds persistent per-Route\n    // state (the slot pool / semaphores), so its live controllers are built\n    // ONCE here and stored on the definition, like the circuit breaker. The\n    // executor wraps the chain tail in a bulkhead segment per controller at\n    // the INNERMOST resilience position (inside retry / timeout), so a slot\n    // is acquired per attempt and released between backoffs. One controller\n    // per `.concurrency()` call (they nest); each keys its pool by Route.\n    const concurrencyControllers = concurrencyConfigs?.map(\n      (cfg) => new ConcurrencyController(cfg),\n    );\n\n    const postFromFilters: Step<Adapter>[] = cacheConfig\n      ? [buildCacheStoreStep(cacheConfig)]\n      : [];\n\n    const normalizedSources: Source<T>[] = sources.map((source) =>\n      toSource(source),\n    );\n\n    this.currentRoute = {\n      id,\n      sources: normalizedSources,\n      steps: [],\n      preParseFilters,\n      postParseFilters,\n      postFromFilters,\n      consumer: {\n        type: consumer.type,\n        options: consumer.options ?? undefined,\n      },\n      ...(errorHandler ? { errorHandler } : {}),\n      ...(discovery ? { discovery } : {}),\n      ...(enablement ? { enablement } : {}),\n      ...(authorizers.length > 0 ? { requiresPrincipal: true } : {}),\n      // Route-scope retry (#7) and timeout (#8) scope over the chain\n      // tail rather than running as flat filters, so they live as\n      // definition fields; the pipeline executor wraps the tail in the\n      // matching segment steps. See `.standards/pre-from-filter-chain.md`.\n      ...(retryConfig ? { retry: retryConfig } : {}),\n      ...(timeoutConfig ? { timeout: timeoutConfig } : {}),\n      ...(throttleGates && throttleGates.length > 0\n        ? { throttle: throttleGates }\n        : {}),\n      // Route-scope circuit breaker (#6): segment-wrapped by the executor\n      // around the persistent controller (see above).\n      ...(circuitBreakerController\n        ? { circuitBreaker: circuitBreakerController }\n        : {}),\n      // Route-scope concurrency (bulkhead): segment-wrapped by the executor\n      // around the persistent controllers, innermost of the resilience tier.\n      ...(concurrencyControllers && concurrencyControllers.length > 0\n        ? { concurrency: concurrencyControllers }\n        : {}),\n    };\n    setBrand(this.currentRoute, BRAND.RouteDefinition);\n    if (this.pendingOptions?.id === undefined) {\n      this.unnamedRoutes.set(\n        this.currentRoute,\n        cacheConfig?.usesDefaultKey ?? false,\n      );\n    }\n\n    // Clear staged options once used\n    this.pendingOptions = undefined;\n\n    this.routes.push(this.currentRoute);\n    return this.retype<T>();\n  }\n\n  /**\n   * Re-surface this instance as the pre-`.from()` staging type. The single\n   * cast point for the route-scope staging methods, mirroring `retype()` on\n   * the base class: there is one runtime object, and position in the chain\n   * decides which type-level surface is reachable.\n   */\n  private prelude(): PreFromBuilder {\n    return this as unknown as PreFromBuilder;\n  }\n\n  /**\n   * Internal method to ensure a source has been defined for the current route.\n   * Throws an error if no source has been defined.\n   *\n   * @returns The current route definition\n   * @throws Error if no source has been defined\n   * @private\n   */\n  private requireSource(): RouteDefinition {\n    if (!this.currentRoute) {\n      throw rcError(\"RC2002\");\n    }\n    if (this.pendingOptions !== undefined) {\n      throw rcError(\"RC2001\", undefined, {\n        message:\n          `Route metadata staged but no .from() called: route-level configuration ` +\n          `(.id / .title / .description / .input / .output / .batch / .error / .authorize / ` +\n          `.cache / .retry / .timeout / .throttle / .circuitBreaker / .concurrency) must be ` +\n          `followed by .from() before pipeline operations on the next route.`,\n      });\n    }\n    return this.currentRoute;\n  }\n\n  /**\n   * Append a step to the current route. Implements the abstract hook from\n   * {@link StepBuilderBase}, so every inherited pipeline operation (and\n   * every registered DSL sugar) flows through this method. The route-only\n   * operations that stay on `RouteBuilder` (`split`, `aggregate`, `choice`)\n   * call it too.\n   *\n   * @param step - The step to append\n   * @throws {RoutecraftError} RC2002 if `.from()` has not been called yet\n   */\n  protected override pushStep<T extends Adapter>(step: Step<T>): void {\n    const route = this.requireSource();\n    const wrapped = this.applyPendingWrappers(step);\n    // Route-scope `.cache()` + `.split()` compatibility is checked at\n    // build time: a balanced `split + aggregate` route is cacheable\n    // (the aggregated body is the single terminal value), but a\n    // fire-and-forget split has no single result to cache. See\n    // {@link assertRouteScopeCacheCompatibility} -- it walks each\n    // finalised route in `build()` and throws `RC5003` for unbalanced\n    // shapes. Per-step rejection at push time would refuse the\n    // balanced case before the user gets a chance to add the matching\n    // aggregate.\n    logger.trace(\n      { operation: wrapped.operation, route: route.id },\n      \"Adding step to route\",\n    );\n    route.steps.push(wrapped);\n  }\n\n  /**\n   * Split into multiple exchanges for fan-out. Each returned exchange is processed independently.\n   * If no splitter is provided: array bodies are split into one exchange per element; non-array bodies\n   * are treated as a single item (one exchange). Framework maintains `routecraft.split_hierarchy`\n   * headers for aggregation.\n   *\n   * Splitters return the child BODIES (or `splitChild(body, headers)`\n   * envelopes for per-child header overrides); the framework constructs the\n   * child exchanges, assigns fresh ids, and inherits the parent's headers.\n   *\n   * @template ItemType The type of items in the array (inferred from array if not specified)\n   * @param splitter Optional adapter or function `(exchange) => SplitResult<ItemType>[]`\n   * @returns A RouteBuilder with the item type\n   * @example\n   * // Automatically split an array of numbers\n   * .from<number[]>(source)\n   * .split() // ItemType is inferred as number\n   *\n   * // Custom splitting logic - return the child bodies\n   * .from(source)\n   * .split<User>((exchange) => exchange.body.users)\n   *\n   * // Split a string by delimiter, with per-child header overrides\n   * .split<string>((exchange) =>\n   *   exchange.body.split(\",\").map((part, i) => splitChild(part, { \"x-part\": i })))\n   */\n  split<ItemType = S[\"body\"] extends Array<infer U> ? U : S[\"body\"]>(\n    splitter?:\n      Splitter<S[\"body\"], ItemType> | CallableSplitter<S[\"body\"], ItemType>,\n  ): RouteBuilder<SetBody<S, ItemType>> {\n    // If no splitter is provided, use default splitter: arrays are split, non-arrays as single item\n    if (!splitter) {\n      const defaultSplitter: CallableSplitter<S[\"body\"], ItemType> = (\n        exchange,\n      ) => {\n        const body = exchange.body;\n        return Array.isArray(body)\n          ? (body as ItemType[])\n          : [body as unknown as ItemType];\n      };\n\n      this.pushStep(new SplitStep<S[\"body\"], ItemType>(defaultSplitter));\n    } else {\n      this.pushStep(new SplitStep<S[\"body\"], ItemType>(splitter));\n    }\n\n    return this.retype<ItemType>();\n  }\n\n  /**\n   * Aggregate multiple items into a single result.\n   * This is often used after a split operation to collect and combine the results.\n   * If no aggregator is provided, items are collected into an array.\n   *\n   * @template ResultType The resulting type after aggregation\n   * @param aggregator Optional function that combines multiple items into a single result\n   * @returns A RouteBuilder with the new aggregated type\n   * @example\n   * // Automatically collect items into an array\n   * .split()\n   * .process((exchange) => ({ ...exchange, body: exchange.body * 2 }))\n   * .aggregate() // Returns array of processed items\n   *\n   * // Custom aggregation logic\n   * .aggregate<number>((exchanges) => {\n   *   const sum = exchanges.reduce((acc, ex) => acc + ex.body, 0);\n   *   return { body: sum, headers: exchanges[0].headers };\n   * })\n   */\n  aggregate<ResultType = Array<S[\"body\"]>>(\n    aggregator?:\n      | Aggregator<S[\"body\"], ResultType>\n      | CallableAggregator<S[\"body\"], ResultType>,\n  ): RouteBuilder<SetBody<S, ResultType>> {\n    if (!aggregator) {\n      // Use default aggregator which collects bodies into an array\n      this.pushStep(\n        new AggregateStep<S[\"body\"], ResultType>(\n          defaultAggregate as CallableAggregator<S[\"body\"], ResultType>,\n        ),\n      );\n    } else {\n      this.pushStep(new AggregateStep<S[\"body\"], ResultType>(aggregator));\n    }\n    return this.retype<ResultType>();\n  }\n\n  /**\n   * Conditionally route the exchange through one of several branches.\n   *\n   * Branches are passed variadically as {@link when} / {@link otherwise}\n   * descriptors built from the standalone helpers, the same path surface\n   * shared with `multicast`. Predicates are evaluated in registration order;\n   * the first match wins. An optional `otherwise` branch catches exchanges\n   * that no `when` matched. If no branch matches and no `otherwise` is\n   * registered, the exchange is dropped with `reason: \"unmatched\"`.\n   *\n   * By default, a matched branch's steps are inlined before the remaining\n   * main-pipeline steps, so the exchange converges back into the main flow\n   * after the choice. A branch that ends in `b.halt()` short-circuits: the\n   * exchange is dropped with `reason: \"halted\"` and the main pipeline does\n   * not resume for it.\n   *\n   * Every branch's output (a sub-pipeline's final body, or a bare\n   * destination's `.to()` result) is checked against `Out`, which becomes the\n   * builder's body type after the choice. `Out` defaults to the current body,\n   * so when all branches keep or converge on one type you write nothing\n   * extra. When branches produce DIFFERENT types, name `Out` as the union and\n   * narrow downstream:\n   * `.choice<Report | Audit>(when(p, b => b.transform(toReport)), otherwise(...))`.\n   * Each branch must produce a member of the union; the downstream sees the\n   * union and must narrow it. The compiler enforces both.\n   *\n   * @template Out - Body type the choice produces (union of the branch outputs;\n   *   defaults to the current body and is checked against every branch)\n   * @param descriptors - `when(...)` / `otherwise(...)` branch descriptors\n   * @returns A RouteBuilder typed at `Out`\n   *\n   * @example\n   * ```ts\n   * .choice(\n   *   when(ex => ex.body.priority === 'urgent', b => b.to(urgentQueue)),\n   *   when(ex => ex.body.amount > 1000,         b => b.to(reviewQueue)),\n   *   otherwise(                                b => b.to(errorSink).halt()),\n   * )\n   * .to(finalDest)\n   * ```\n   */\n  choice<Out = S[\"body\"]>(\n    ...descriptors: ChoiceDescriptor<S[\"body\"], Out>[]\n  ): RouteBuilder<SetBody<S, Out>> {\n    this.pushStep(\n      buildChoiceStep(descriptors as ChoiceDescriptor<unknown, unknown>[]),\n    );\n    return this.retype<Out>();\n  }\n\n  /**\n   * Fan the exchange out to multiple independent paths in parallel.\n   *\n   * Each path is either a bare destination or a sub-pipeline callback (the\n   * same path surface as `choice`). Every path receives its own deep clone\n   * of the exchange (fresh id, preserved correlation id) and runs as an\n   * isolated nested pipeline; all paths run concurrently and the step waits\n   * for every one to settle (`Promise.allSettled` semantics). A path that\n   * throws fires its own clone's error events but does not fail the route or\n   * its sibling paths, and a path that `.halt()`s only stops itself. Once\n   * every path has settled, the ORIGINAL exchange continues downstream\n   * unchanged, so the body type is preserved.\n   *\n   * Fire-and-forget is intentionally not offered; use `tap` (already\n   * fire-and-forget) for that.\n   *\n   * A path output type is unconstrained (`Path<S[\"body\"], unknown>`): a path\n   * may reshape the body however it likes because its result is discarded;\n   * only the original exchange continues. This differs from `choice`, where\n   * branches must converge on one `Out`.\n   *\n   * Notes and limitations:\n   * - The route-scope `.error()` handler does NOT fire for a path failure: a\n   *   path that throws resolves through its own clone's default error events\n   *   (`route:error` / `context:error` / `route:exchange:failed`). Wrap\n   *   per-path recovery inside the path (`b => b.error(...).to(...)`) if you\n   *   need it.\n   * - Only the body is deep-copied. Object-valued user headers are shared by\n   *   reference across the clones and the original; mutating a nested header\n   *   field from a path is not isolated (an anti-pattern, as for `tap`).\n   * - The body must be structured-cloneable (`structuredClone`); a body that\n   *   cannot be cloned (class instances with methods, streams, functions)\n   *   fails the multicast step.\n   *\n   * @param paths - Bare destinations or sub-pipeline callbacks to fan out to\n   * @returns This RouteBuilder, body type unchanged\n   *\n   * @example\n   * ```ts\n   * .from(http('/orders'))\n   * .multicast(\n   *   queue('audit'),                                // bare destination\n   *   b => b.transform(toWarehouse).to(http('/wh')), // sub-pipeline path\n   * )\n   * .to(next); // runs on the original exchange after all paths settle\n   * ```\n   */\n  multicast(...paths: Path<S[\"body\"], unknown>[]): RouteBuilder<S> {\n    this.pushStep(new MulticastStep(paths.map((path) => compilePath(path))));\n    return this;\n  }\n\n  /**\n   * Run EXACTLY ONE of several targets, chosen by a load-balancing strategy.\n   * The sibling of `multicast` (all targets) and `choice` (one target by\n   * predicate); dispatch is one target by strategy.\n   *\n   * The required leading argument is the strategy; the rest are the targets.\n   * A target is a bare destination, a sub-pipeline callback `(b) => b...` (the\n   * same path surface as `multicast`), or either wrapped in {@link weighted}\n   * to co-locate a relative weight. There is no safe default strategy, so it\n   * is required:\n   *\n   * - `\"failover\"` -- try targets in order until one succeeds; pairs with\n   *   per-target `.retry()` / `.circuitBreaker()`.\n   * - `\"round-robin\"` -- cycle through targets in order.\n   * - `\"weighted\"` -- distribute by the `weighted()` weights (smooth weighted\n   *   round-robin, deterministic).\n   * - `{ strategy: \"sticky\", key }` -- exchanges sharing a `key` stick to one\n   *   target. Object form only, because `key` is required.\n   *\n   * Side-effect-only, like `multicast`: the selected target runs on its own\n   * deep clone, and the ORIGINAL exchange continues downstream unchanged, so\n   * the body type is preserved and a target's output is unconstrained. A\n   * target that throws fires its own clone's error events but does not fail\n   * the route or the dispatch step (for `failover`, a failure advances to the\n   * next target instead; if all fail, `route:operation:dispatch:exhausted`\n   * fires and the original still continues).\n   *\n   * @param strategy - The selection strategy (string or object form)\n   * @param targets - Destinations, sub-pipeline callbacks, or `weighted(...)`\n   * @returns This RouteBuilder, body type unchanged\n   *\n   * @example\n   * ```ts\n   * .dispatch(\"failover\", primary, secondary)\n   * .dispatch(\"round-robin\", workerA, workerB, workerC)\n   * .dispatch(\"weighted\", weighted(stable, 95), weighted(canary, 5))\n   * .dispatch({ strategy: \"sticky\", key: (ex) => ex.body.userId }, a, b)\n   * ```\n   */\n  dispatch(\n    strategy: DispatchStrategy<S[\"body\"]>,\n    ...targets: DispatchTarget<S[\"body\"], unknown>[]\n  ): RouteBuilder<S> {\n    this.pushStep(\n      buildDispatchStep(\n        strategy as DispatchStrategy<unknown>,\n        targets as DispatchTarget<unknown, unknown>[],\n      ),\n    );\n    return this;\n  }\n\n  /**\n   * Suppress bursts of exchanges, releasing only the LAST one in a burst\n   * after a quiet period. The archetypal use is collapsing a flurry of\n   * file-change or search-as-you-type events down to their final state.\n   *\n   * Each arrival is held (not passed downstream) and resets a `waitMs` quiet\n   * timer; a newer arrival supersedes and drops the one being held. When the\n   * timer fires (or the optional `maxWait` cap elapses from the burst's\n   * start, guaranteeing progress under continuous activity), the held\n   * exchange is released through the steps after `.debounce()`. An optional\n   * `key` selector debounces independently per group.\n   *\n   * Unlike the other flow-control operations, debounce holds an exchange\n   * OUTSIDE the pipeline queue and re-runs it later, so a released exchange\n   * runs the downstream steps as a fresh exchange (new id, preserved\n   * correlation id). A pending exchange is flushed on `drain()` / shutdown\n   * rather than being lost. State is per-route; it is a route-scope operation\n   * and is deliberately not available inside a fan-out path.\n   *\n   * @param options - `{ wait }`, plus optional `key` selector and `maxWait` cap\n   * @returns This RouteBuilder, body type unchanged\n   *\n   * @example\n   * ```ts\n   * .from(file({ path: \"./config\", watch: true }))\n   * .debounce({ wait: \"500ms\" }) // wait for editing to finish\n   * .process(reloadConfig)\n   * ```\n   */\n  debounce(options: DebounceOptions<S[\"body\"]>): RouteBuilder<S> {\n    this.pushStep(buildDebounceStep(options));\n    return this;\n  }\n\n  /**\n   * Finalize and return the route definition(s). Call after defining all steps.\n   *\n   * @returns Array of RouteDefinition (one per `.from()` in this builder chain)\n   *\n   * @example\n   * ```typescript\n   * const definitions = craft()\n   *   .from<string[]>(source)\n   *   .split()\n   *   .process((ex) => ({ ...ex, body: (ex.body as string).toUpperCase() }))\n   *   .to(destination)\n   *   .build();\n   * const { context } = await new ContextBuilder().routes(definitions).build();\n   * await context.start();\n   * ```\n   */\n  build(): RouteDefinition[] {\n    if (this.pendingOptions !== undefined) {\n      throw rcError(\"RC2001\", undefined, {\n        message: `Route metadata staged but never consumed by .from().`,\n      });\n    }\n    this.assertNoPendingWrappers(\"build\");\n    for (const route of this.routes) {\n      // Resolving defer sites is also where a `.defer()` in a position\n      // that cannot be revived is refused, so it runs on every build rather\n      // than only when the route turns out to defer. It runs BEFORE the\n      // cache check, which reads what it resolved.\n      const sites = resolveDeferSites(route);\n      if (sites.deferSteps.length > 0) {\n        route.deferSteps = sites.deferSteps;\n      }\n      if (sites.reentrantDeferSteps.length > 0) {\n        route.reentrantDeferSteps = sites.reentrantDeferSteps;\n      }\n      if (usesResume(route)) route.usesResume = true;\n      assertRouteScopeCacheCompatibility(route);\n      const stepScopeDefaultKey = assignCacheSites(route);\n      if (route.postParseFilters.some((f) => f.label === \"cache-check\")) {\n        route.cachePipeline = pipelineFingerprint(route.steps);\n      }\n      const routeScopeDefaultKey = this.unnamedRoutes.get(route);\n      if (\n        routeScopeDefaultKey !== undefined &&\n        (routeScopeDefaultKey || stepScopeDefaultKey)\n      ) {\n        route.volatileCacheKey = true;\n      }\n    }\n    logger.trace({ routeCount: this.routes.length }, \"Building routes\");\n    return this.routes;\n  }\n\n  /**\n   * Throw when a step-scope wrapper (`.error()`, `.retry()`, `.timeout()`,\n   * `.throttle()`, `.circuitBreaker()`, `.concurrency()`, `.cache()`,\n   * `.delay()`) was staged but the user is starting a\n   * new route or finalising the build without consuming it. A wrapper\n   * attaches to the immediately next pipeline step; if no step\n   * follows on the current route, the wrapper would silently leak\n   * into the next route's first step. Symmetric with the existing\n   * \"metadata staged but never consumed\" rule.\n   *\n   * @internal\n   */\n  private assertNoPendingWrappers(method: string): void {\n    if (this.pendingStepWrappers.length > 0) {\n      throw rcError(\"RC2001\", undefined, {\n        message:\n          `Wrapper(s) staged via .error() / .retry() / .timeout() / .throttle() / .circuitBreaker() / .cache() / .delay() / .concurrency() but no step followed before .${method}(). ` +\n          `A wrapper attaches to the immediately next pipeline step; orphaning one (or letting it leak into the next route) is almost always a mistake.`,\n      });\n    }\n  }\n}\n\n/**\n * Create a new route builder.\n *\n * This is the entry point for defining routes in a fluent way.\n *\n * @returns A new RouteBuilder instance\n *\n * @example\n * ```typescript\n * // Define a route that processes data\n * const myRoute = craft()\n *   .from(simple(\"Hello, World!\"))\n *   .transform(data => data.toUpperCase())\n *   .to(log())\n * ```\n */\nexport function craft(): PreFromBuilder {\n  return new RouteBuilder();\n}\n","import { CraftContext } from \"../context.ts\";\nimport type { RouteDefinition } from \"../route.ts\";\nimport type {\n  ProcessingQueue,\n  Message,\n  Consumer,\n  ConsumerDeps,\n} from \"../types.ts\";\nimport type { Exchange } from \"../exchange.ts\";\n\nexport class SimpleConsumer implements Consumer<undefined> {\n  public readonly context: CraftContext;\n  public readonly definition: RouteDefinition;\n  public readonly channel: ProcessingQueue<Message>;\n  public readonly options: undefined;\n\n  constructor(deps: ConsumerDeps) {\n    this.context = deps.context;\n    this.definition = deps.definition;\n    this.channel = deps.channel;\n    this.options = undefined;\n  }\n\n  register(handler: (envelope: Message) => Promise<Exchange>): void {\n    this.channel.setHandler(handler);\n  }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { CraftContext } from \"../context.ts\";\nimport type { RouteDefinition } from \"../route.ts\";\nimport type {\n  ProcessingQueue,\n  Message,\n  Consumer,\n  ConsumerDeps,\n  EventName,\n  EventHandler,\n} from \"../types.ts\";\nimport type { Exchange, ExchangeHeaders, HeaderValue } from \"../exchange.ts\";\n\nexport type BatchOptions = {\n  /**\n   * The size of the batch.\n   */\n  size?: number;\n  /**\n   * The timeout between batches in milliseconds.\n   */\n  time?: number;\n  /**\n   * The function to merge the produced messages.\n   */\n  merge?: (exchanges: { message: unknown; headers?: ExchangeHeaders }[]) => {\n    message: unknown;\n    headers?: ExchangeHeaders;\n  };\n};\n\nexport class BatchConsumer implements Consumer<Required<BatchOptions>> {\n  /** Messages wait in the buffer until the batch flushes. See {@link ConsumerType.buffers}. */\n  static readonly buffers = true;\n\n  public readonly context: CraftContext;\n  public readonly definition: RouteDefinition;\n  public readonly channel: ProcessingQueue<Message>;\n  public readonly options: Required<BatchOptions>;\n\n  constructor(deps: ConsumerDeps) {\n    this.context = deps.context;\n    this.definition = deps.definition;\n    this.channel = deps.channel;\n    // The deps bag carries options as `unknown` (route definitions store\n    // heterogeneous consumer configs); this consumer owns the narrowing.\n    const options = (deps.options ?? {}) as BatchOptions;\n    this.options = {\n      size: options.size ?? 1000,\n      time: options.time ?? 10 * 1000,\n      merge:\n        options.merge ??\n        ((messages) => {\n          const headers: Record<string, HeaderValue> = {};\n          for (const message of messages) {\n            for (const [key, value] of Object.entries(message.headers ?? {})) {\n              headers[key] = value;\n            }\n          }\n          return {\n            message: messages.map((message) => message.message),\n            headers,\n          };\n        }),\n    };\n  }\n\n  /**\n   * Register the route handler for batched delivery.\n   *\n   * **Principal handling.** The merged-batch path inherits whatever the\n   * configured `merge` produces for headers; the default merge keeps the\n   * last-write-wins value for `routecraft.auth.principal` if multiple\n   * items in the batch carry one, which is rarely meaningful. Routes that\n   * need per-message identity attribution should use the simple consumer\n   * or attach a principal in a `.process()` step after the batch is\n   * unpacked.\n   *\n   * The per-item parse-failure escape hatch (where a bad item is routed as\n   * its own exchange instead of joining the batch) forwards the source's\n   * headers verbatim, so any `routecraft.auth.principal` set by the source\n   * survives into `.error()` for authorization checks.\n   */\n  register(handler: (envelope: Message) => Promise<Exchange>): void {\n    let batch: Message[] = [];\n    let resolvers: {\n      resolve: (ex: Exchange) => void;\n      reject: (e: unknown) => void;\n    }[] = [];\n    let timer: ReturnType<typeof setTimeout> | null = null;\n    const batchId = randomUUID();\n    let batchStartTime: number | null = null;\n\n    const flushBatch = async (reason: \"size\" | \"time\") => {\n      if (batch.length > 0) {\n        const currentBatch = batch;\n        const currentResolvers = resolvers;\n        const waitTime =\n          batchStartTime === null ? 0 : Date.now() - batchStartTime;\n        batch = [];\n        resolvers = [];\n        batchStartTime = null;\n\n        // Emit batch:flushed event\n        this.context.emit(\"route:batch:flushed\", {\n          routeId: this.definition.id,\n          batchSize: currentBatch.length,\n          batchId,\n          waitTime,\n          reason,\n        });\n\n        try {\n          const merged = this.options.merge(currentBatch);\n          const finalExchange = await handler({\n            message: merged.message,\n            ...(merged.headers !== undefined\n              ? { headers: merged.headers }\n              : {}),\n          });\n          for (const { resolve } of currentResolvers) {\n            resolve(finalExchange);\n          }\n        } catch (error) {\n          this.context.logger.warn(\n            { err: error, route: this.definition.id },\n            \"Batch consumer handler failed\",\n          );\n          for (const { reject } of currentResolvers) {\n            reject(error);\n          }\n        }\n      }\n      if (timer) {\n        clearTimeout(timer);\n        timer = null;\n      }\n    };\n\n    this.channel.setHandler(async (message) => {\n      // When a source adapter attaches a `parse` function (see #187), the\n      // batch consumer cannot defer it to the synthetic pipeline step that\n      // the simple consumer relies on: the merged batch exchange has no\n      // per-item parse function, so the runtime cannot apply parsing after\n      // batching. We pre-parse here so the batch contains parsed values.\n      //\n      // On parse failure we route the bad item through the pipeline as its\n      // own per-item exchange (handler invoked with the raw message and the\n      // captured parse function so the synthetic parse step throws RC5016).\n      // This preserves `onParseError: 'fail'` semantics: the route's\n      // `.error()` handler fires, `route:exchange:failed` fires when no handler\n      // is set, and the source's per-item `.catch()` continues. The bad\n      // item is NOT added to the in-progress batch.\n      if (message.parse) {\n        const itemParse = message.parse;\n        const itemMode = message.parseFailureMode;\n        const rawMessage = message.message;\n        try {\n          message.message = await itemParse(rawMessage);\n        } catch (parseErr) {\n          // Route the failed item as a per-item exchange so the synthetic\n          // parse step fires the correct lifecycle event for the mode\n          // (fail/abort -> route:exchange:failed, drop -> route:exchange:dropped).\n          // Pass a closure that throws the captured error rather than\n          // re-invoking `itemParse` on the same input, since user-supplied\n          // parsers may have side effects (logging, metrics, prefetch).\n          // Mirrors the mail adapter's `MAIL_PARSE_ERRORS` pattern.\n          return handler({\n            message: rawMessage,\n            ...(message.headers !== undefined\n              ? { headers: message.headers }\n              : {}),\n            parse: () => {\n              throw parseErr;\n            },\n            ...(itemMode !== undefined ? { parseFailureMode: itemMode } : {}),\n          });\n        }\n        delete message.parse;\n        delete message.parseFailureMode;\n      }\n\n      const promise = new Promise<Exchange>((resolve, reject) => {\n        batch.push(message);\n        resolvers.push({ resolve, reject });\n      });\n\n      if (batch.length === 1) {\n        batchStartTime = Date.now();\n\n        this.context.emit(\"route:batch:started\", {\n          routeId: this.definition.id,\n          batchSize: this.options.size,\n          batchId,\n        });\n\n        if (timer) {\n          clearTimeout(timer);\n        }\n        timer = setTimeout(async () => {\n          await flushBatch(\"time\");\n        }, this.options.time);\n      }\n\n      if (batch.length >= this.options.size) {\n        await flushBatch(\"size\");\n      }\n      return promise;\n    });\n\n    // Listen for route stopping to emit batch:stopped\n    const unsubscribe = this.context.on(\"route:stopping\", ((payload: {\n      details: { route: { definition: { id: string } } };\n    }) => {\n      if (payload.details.route.definition.id === this.definition.id) {\n        // Clear any pending timer\n        if (timer) {\n          clearTimeout(timer);\n          timer = null;\n        }\n\n        // Reject all pending promises to prevent memory leaks\n        for (const { reject } of resolvers) {\n          reject(new Error(\"BatchConsumerStopped: Route is shutting down\"));\n        }\n        resolvers.length = 0;\n\n        // Emit batch:stopped event\n        this.context.emit(\"route:batch:stopped\", {\n          routeId: this.definition.id,\n          batchId,\n        });\n\n        // Unsubscribe after emitting\n        unsubscribe();\n      }\n    }) as EventHandler<EventName>);\n  }\n}\n","import type { Destination } from \"../../operations/to\";\nimport type { Exchange } from \"../../exchange\";\nimport type { LogLevel, LogOptions } from \"./types\";\n\nconst DEFAULT_LEVEL: LogLevel = \"info\";\n\nexport class LogDestinationAdapter<T = unknown> implements Destination<T> {\n  readonly adapterId = \"routecraft.adapter.log\";\n\n  private readonly level: LogLevel;\n  private readonly formatter: ((exchange: Exchange<T>) => unknown) | undefined;\n\n  constructor(\n    formatter?: (exchange: Exchange<T>) => unknown,\n    options?: LogOptions,\n  ) {\n    this.formatter = formatter;\n    this.level = options?.level ?? DEFAULT_LEVEL;\n  }\n\n  send(exchange: Exchange<T>): Promise<void> {\n    const logData = this.formatter\n      ? this.formatter(exchange)\n      : this.baseExchange(exchange);\n    const adapterLabel = this.adapterId.split(\".\").pop();\n    const bindings =\n      typeof logData === \"object\" && logData !== null\n        ? { ...logData, adapter: adapterLabel }\n        : { adapter: adapterLabel, value: logData };\n    exchange.logger[this.level](bindings, \"LogAdapter output\");\n    return Promise.resolve();\n  }\n\n  private baseExchange(exchange: Exchange<T>): Partial<Exchange<T>> {\n    const { id, body, headers } = exchange;\n    return { id, body, headers };\n  }\n}\n","import type { Destination } from \"../../operations/to\";\nimport type { Exchange } from \"../../exchange\";\nimport { LogDestinationAdapter } from \"./destination\";\nimport type { LogOptions } from \"./types\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag\";\n\n/**\n * Creates a logging destination that logs each exchange (or a formatted value) via the exchange logger.\n *\n * @template T - Body type of the exchange\n * @param formatter - Optional function (exchange) => value to log; default logs id, body, headers\n * @param options - Optional `level` (default \"info\")\n * @returns A Destination usable with `.to(log())` or `.tap(log())`\n *\n * @example\n * ```typescript\n * .to(log())\n * .to(log((ex) => ({ id: ex.id, body: ex.body })))\n * .to(log(undefined, { level: 'debug' }))\n * ```\n */\nexport function log<T = unknown>(\n  formatter?: (exchange: Exchange<T>) => unknown,\n  options?: LogOptions,\n): Destination<T> {\n  return tagAdapter(\n    new LogDestinationAdapter<T>(formatter, options),\n    log,\n    factoryArgs(formatter, options),\n  );\n}\n\n/**\n * Same as `log()` but with level fixed to `\"debug\"`. Useful for verbose pipelines.\n *\n * @template T - Body type of the exchange\n * @param formatter - Optional (exchange) => value to log\n * @param options - Optional config (level is always \"debug\")\n * @returns A Destination that logs at debug level\n */\nexport function debug<T = unknown>(\n  formatter?: (exchange: Exchange<T>) => unknown,\n  options?: Omit<LogOptions, \"level\">,\n): Destination<T> {\n  return tagAdapter(\n    new LogDestinationAdapter<T>(formatter, {\n      ...options,\n      level: \"debug\",\n    }),\n    debug,\n    factoryArgs(formatter, options),\n  );\n}\n\n// Re-export adapter class and types for public API\nexport { LogDestinationAdapter } from \"./destination\";\nexport type { LogLevel, LogOptions } from \"./types\";\n","/**\n * DSL registration system for RouteBuilder sugar methods.\n *\n * Built-in sugar (.log, .debug, .map, .schema) is registered at module\n * scope so it is available as soon as anything is imported from the\n * package. External packages follow the same pattern: import their\n * index, and their sugar is registered automatically.\n */\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Adapter, Step } from \"./types.ts\";\nimport type { Exchange } from \"./exchange.ts\";\nimport {\n  StepBuilderBase,\n  type BuilderState,\n  type ExchangeOf,\n  type Retyped,\n  type SetBody,\n  type SetDeferral,\n} from \"./step-builder-base.ts\";\nimport { PUSH_STEP } from \"./dsl-symbol.ts\";\nimport { TapStep } from \"./operations/tap.ts\";\nimport { TransformStep, mapper } from \"./operations/transform.ts\";\nimport { ValidateStep, schema } from \"./operations/validate.ts\";\nimport { log, debug, type LogOptions } from \"./adapters/log/index.ts\";\nimport { DeferStep, type DeferOptions } from \"./operations/defer.ts\";\nimport {\n  ResumeStep,\n  type ResumeMapper,\n  type ResumeOptions,\n} from \"./operations/resume.ts\";\nimport type { ResumeAcknowledgment } from \"./deferral/revive.ts\";\n\n// ---------------------------------------------------------------------------\n// registerDsl\n// ---------------------------------------------------------------------------\n\n/**\n * Primitive step kinds. Used as documentation in DslRegistration to\n * indicate which core step the sugar delegates to. Not enforced at\n * runtime since the factory creates the step directly.\n */\nexport type PrimitiveKind =\n  \"process\" | \"transform\" | \"tap\" | \"filter\" | \"validate\";\n\n/**\n * Registration descriptor for a DSL sugar method.\n */\nexport interface DslRegistration {\n  /** The core primitive step kind this DSL method delegates to. */\n  kind: PrimitiveKind;\n  /** Display label shown in traces, logs, and step events. */\n  label: string;\n  /** Factory that receives the user's call-site arguments and returns a Step. */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- factory must accept arbitrary call-site args; actual types come from module augmentation\n  factory: (...args: any[]) => Step<Adapter>;\n}\n\n/**\n * Register a sugar method on `StepBuilderBase` that delegates to a core\n * primitive step type. The method is added to the shared base prototype\n * so it is available on both `RouteBuilder` and `PathBuilder` (and any\n * future framework-owned subclass).\n *\n * TypeScript types for the new method must be provided separately via\n * module augmentation. Augment `StepBuilderBase<S extends BuilderState>`\n * once (the type parameter list must match the declaration exactly) and\n * both subclasses inherit the method via class-interface inheritance.\n * Type-preserving sugar should return `this`; type-changing sugar should\n * use `Retyped<this, SetBody<S, NewBody>>` so the concrete subclass is\n * preserved across the chain and any future `BuilderState` fields flow\n * through untouched. `StepBuilderBase`, `BuilderState`, `SetBody`, and\n * `Retyped` are exposed as type-only re-exports from the package entry\n * for exactly this purpose.\n *\n * @param name - Method name to add to the shared base prototype\n * @param registration - Kind, label, and factory for the sugar method\n * @throws If a method with the given name already exists on the base\n *\n * @example\n * ```ts\n * registerDsl(\"myStep\", {\n *   kind: \"tap\",\n *   label: \"myStep\",\n *   factory: (opts) => new TapStep(myAdapter(opts)),\n * });\n *\n * declare module \"@routecraft/routecraft\" {\n *   interface StepBuilderBase<S extends BuilderState> {\n *     // Type-preserving: returns `this` (resolves to the concrete subclass)\n *     myStep(opts: MyOpts): this;\n *\n *     // Type-changing variant would look like:\n *     // myMap<Return>(\n *     //   fn: (src: S[\"body\"]) => Return,\n *     // ): Retyped<this, SetBody<S, Return>>;\n *   }\n * }\n * ```\n */\nexport function registerDsl(name: string, registration: DslRegistration): void {\n  if (name in StepBuilderBase.prototype) {\n    throw new Error(\n      `Cannot register DSL method \"${name}\": already exists on StepBuilderBase`,\n    );\n  }\n\n  const { label, factory } = registration;\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic prototype patching requires indexing with a string key\n  (StepBuilderBase.prototype as Record<string, any>)[name] = function (\n    this: StepBuilderBase<BuilderState>,\n    ...args: unknown[]\n  ) {\n    const step = factory(...args);\n    step.label = label;\n    this[PUSH_STEP](step);\n    return this;\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Built-in sugar registrations (run at import time)\n// ---------------------------------------------------------------------------\n\nregisterDsl(\"log\", {\n  kind: \"tap\",\n  label: \"log\",\n  factory: (\n    formatter?: (exchange: Exchange<unknown>) => unknown,\n    options?: LogOptions,\n  ) => new TapStep(log(formatter, options)),\n});\n\nregisterDsl(\"debug\", {\n  kind: \"tap\",\n  label: \"debug\",\n  factory: (\n    formatter?: (exchange: Exchange<unknown>) => unknown,\n    options?: Omit<LogOptions, \"level\">,\n  ) => new TapStep(debug(formatter, options)),\n});\n\nregisterDsl(\"map\", {\n  kind: \"transform\",\n  label: \"map\",\n  factory: (fieldMappings: Record<string, (src: unknown) => unknown>) =>\n    new TransformStep(mapper(fieldMappings)),\n});\n\nregisterDsl(\"schema\", {\n  kind: \"validate\",\n  label: \"schema\",\n  factory: (standardSchema: StandardSchemaV1) =>\n    new ValidateStep(schema(standardSchema)),\n});\n\n// `.defer()` and `.resume()` register here rather than living on\n// StepBuilderBase for the same reason `.log()` and `.schema()` do: they are\n// one step each with no builder state of their own. They are also\n// symmetric, and registering them side by side keeps them that way.\nregisterDsl(\"defer\", {\n  kind: \"process\",\n  label: \"defer\",\n  factory: (options: DeferOptions) => new DeferStep(options),\n});\n\nregisterDsl(\"resume\", {\n  kind: \"process\",\n  label: \"resume\",\n  factory: (mapper?: ResumeMapper | ResumeOptions, options?: ResumeOptions) =>\n    typeof mapper === \"function\"\n      ? new ResumeStep(mapper, options)\n      : // `.resume({ authorize })` puts the options first; `.resume(undefined,\n        // { authorize })` is the same door written the long way, and both\n        // have to reach the step or a declared hook is silently dropped.\n        new ResumeStep(undefined, mapper ?? options),\n});\n\n// ---------------------------------------------------------------------------\n// Module augmentation: TypeScript types for built-in sugar\n// ---------------------------------------------------------------------------\n\n// See .standards/type-safety-and-schemas.md#module-augmentation for why this\n// targets the package specifier and not a relative path.\n//\n// Sugar methods are declared on the shared `StepBuilderBase` interface so\n// both `RouteBuilder` and `PathBuilder` inherit them via class-interface\n// inheritance. Type-preserving sugars return `this` (polymorphic -- resolves\n// to the concrete subclass at the call site); type-changing sugars use\n// `Retyped<this, NewT>` (same closed-world conditional the base already uses\n// for `.to` / `.transform` / `.enrich`). One declaration, both subclasses\n// pick it up.\ndeclare module \"@routecraft/routecraft\" {\n  interface StepBuilderBase<S extends BuilderState> {\n    /**\n     * Log the current exchange at info level. Type-preserving tap.\n     *\n     * @param formatter - Optional function to format the log output\n     * @param options - Optional log options (level defaults to \"info\")\n     */\n    log(\n      formatter?: (exchange: Exchange<S[\"body\"]>) => unknown,\n      options?: LogOptions,\n    ): this;\n\n    /**\n     * Log the current exchange at debug level. Type-preserving tap.\n     *\n     * @param formatter - Optional function to format the log output\n     * @param options - Optional log options (level is always \"debug\")\n     */\n    debug(\n      formatter?: (exchange: Exchange<S[\"body\"]>) => unknown,\n      options?: Omit<LogOptions, \"level\">,\n    ): this;\n\n    /**\n     * Map fields from the current data to create a new object. Sugar\n     * for `.transform(mapper({...}))`.\n     *\n     * @template Return - The resulting type after mapping\n     * @param fieldMappings - Object mapping output field names to extractor functions\n     * @example\n     * ```ts\n     * .map<DbUser>({\n     *   id: (apiUser) => apiUser.userId,\n     *   name: (apiUser) => apiUser.fullName,\n     * })\n     * ```\n     */\n    map<Return>(fieldMappings: {\n      [K in keyof Return]: (src: S[\"body\"]) => Return[K];\n    }): Retyped<this, SetBody<S, Return>>;\n\n    /**\n     * Validate the exchange body against a Standard Schema. Sugar for\n     * `.validate(schema(standardSchema))`. On failure throws RC5002.\n     *\n     * @param standardSchema - Any Standard Schema v1 (Zod, Valibot, ArkType, etc.)\n     * @example\n     * ```ts\n     * import { z } from \"zod\";\n     * craft()\n     *   .from(source)\n     *   .schema(z.object({ name: z.string() }))\n     *   .to(dest)\n     * ```\n     */\n    schema<Schema extends StandardSchemaV1>(\n      standardSchema: Schema,\n    ): Retyped<this, SetBody<S, StandardSchemaV1.InferOutput<Schema>>>;\n\n    /**\n     * Defer the exchange durably and exit the pipeline, to be resumed later\n     * at the next step.\n     *\n     * This run ends here and replies immediately with the `Deferred`\n     * acknowledgment, because a durable defer cannot hold a caller: the\n     * resume payload arrives in hours or days and the process will be\n     * restarted first. Nothing is scheduled, no worker waits, and the route\n     * stays live for every other exchange. The route's real output flows to\n     * its destinations on execution two, when `.resume()` revives the\n     * exchange with the payload.\n     *\n     * The body is unchanged across the deferral, so a branch that defers\n     * rejoins the main flow with the contract it left on. The payload\n     * arrives beside it, on `ex.deferral.result`, typed by `schema`.\n     *\n     * @param options - `schema` (what a valid resume payload looks like), a\n     *   `ttl` after which the deferral stops being resumable, and `meta`:\n     *   anything the resuming route's `.resume({ authorize })` hook needs to\n     *   decide who may resume\n     * @example\n     * ```ts\n     * craft()\n     *   .id(\"payout\")\n     *   .input({ body: PayoutRequest })\n     *   .from(http({ path: \"/payouts\", method: \"POST\" }))\n     *   .choice(\n     *     when((ex) => ex.body.amountCents >= 50_000, (b) =>\n     *       b\n     *         .tap(direct(\"notify-approver\"))\n     *         .defer({ schema: Approval, ttl: \"72h\" })\n     *         .filter((ex) =>\n     *           ex.deferral.result.approved\n     *             ? true\n     *             : { reason: `rejected by ${ex.deferral.resumedBy?.subject}` },\n     *         ),\n     *     ),\n     *   )\n     *   .to(payouts())\n     * ```\n     */\n    defer<Schema extends StandardSchemaV1>(\n      options?: DeferOptions<Schema>,\n    ): Retyped<this, SetDeferral<S, StandardSchemaV1.InferOutput<Schema>>>;\n\n    /**\n     * Revive a deferred exchange and run its continuation.\n     *\n     * Addresses an EXCHANGE by signed token, not a route by name: any route\n     * ending in `.resume()` is a resume ingress, whether it is fed by an\n     * HTTP webhook, a mail-reply parser, or an ops CLI. The original source\n     * takes no part in execution two, which is what lets a mail-born\n     * exchange be continued by a chat-born resume.\n     *\n     * The mapping function owns SHAPE (find the token, build the payload);\n     * validation against the deferring step's `schema` happens at revival,\n     * because only the deferral knows that schema. The bare form expects\n     * the body to already be `{ token, result }`.\n     *\n     * Authorizing the resuming principal belongs on this route, through the\n     * `authorize` option: the token proves the deployment minted it, not\n     * that its holder may resume. The hook runs before the store's claim\n     * and before the record's lifecycle is disclosed, so a refusal costs\n     * the rightful principal nothing and tells a refused caller nothing.\n     * Whoever this route authenticated is recorded as `resumedBy`. A door\n     * exposed publicly wants a `.throttle()` in front of it.\n     *\n     * The revived route runs to completion before this step continues, so\n     * the acknowledgment placed in the body reports how execution two\n     * ended, and the ingress route can reply on the caller's own channel.\n     * A duplicate resume returns the first one's cached continuation result\n     * without re-running anything.\n     *\n     * @param map - Maps the ingress exchange to `{ token, result }`\n     * @param options - `authorize`, deciding who may resume. Omitted, the\n     *   door is bearer: any holder of a valid token may resume.\n     * @example\n     * ```ts\n     * craft()\n     *   .id(\"approval-replies\")\n     *   .from(mail(\"INBOX\"))\n     *   .authenticate(mailPrincipal)\n     *   .resume((ex) => ({\n     *     token: tokenFrom(ex.headers[\"routecraft.mail.subject\"]),\n     *     result: { approved: /^yes/i.test(ex.body.text ?? \"\") },\n     *   }))\n     *   .to(log())\n     * ```\n     */\n    resume(\n      map?: (\n        exchange: ExchangeOf<S>,\n        ctx?: { readonly signal?: AbortSignal },\n      ) => ReturnType<ResumeMapper<S[\"body\"]>>,\n      options?: ResumeOptions,\n    ): Retyped<this, SetBody<S, ResumeAcknowledgment>>;\n    resume(\n      options: ResumeOptions,\n    ): Retyped<this, SetBody<S, ResumeAcknowledgment>>;\n  }\n}\n","import type { CraftContext } from \"./context.ts\";\n\n/**\n * Register SIGINT/SIGTERM handlers for graceful two-stage shutdown.\n *\n * **First signal** (Ctrl+C): closes intake so sources stop producing, lets\n * in-flight exchanges run to their natural end, runs plugin teardown, then\n * exits 0. In-flight work is NOT cancelled here. Repeated SIGINT/SIGTERM\n * signals are ignored while this graceful shutdown is in progress.\n *\n * **Dedicated force signals** (Ctrl+Backslash/SIGQUIT or Ctrl+Break/SIGBREAK):\n * force an immediate exit for when graceful shutdown is stuck or taking too\n * long. They force exit even when graceful shutdown has not started.\n *\n * Stage one is bounded by `shutdown: { timeout }` even without a force signal,\n * which is what an orchestrator needs: it sends one SIGTERM and then SIGKILLs,\n * so there is no dedicated force signal coming. On that deadline in-flight\n * execution is abandoned and the process exits 1, so exit-code-sensitive\n * tooling can tell a forced shutdown from a clean one.\n *\n * @param context - A built `CraftContext` to shut down on signal\n *\n * @example\n * ```typescript\n * const { context } = await builder.build();\n * shutdownHandler(context);\n * await context.start();\n * ```\n */\nexport function shutdownHandler(context: CraftContext): () => void {\n  let shuttingDown = false;\n\n  const onGracefulSignal = async (signal: \"SIGINT\" | \"SIGTERM\") => {\n    if (shuttingDown) {\n      context.logger.info(\n        { signal },\n        \"Received repeated signal during graceful shutdown; ignoring\",\n      );\n      return;\n    }\n\n    shuttingDown = true;\n    context.logger.info(\n      { signal },\n      \"Received signal; shutting down gracefully (use Ctrl+Backslash or Ctrl+Break to force)\",\n    );\n\n    try {\n      const outcome = await context.stop();\n      context.logger.info(\"Cleanup complete\");\n      // Non-zero on a forced stop: work was abandoned, and a caller that\n      // reads exit codes must not be told that went cleanly. The reason is\n      // in the log line the forced stage writes.\n      process.exit(outcome.forced ? 1 : 0);\n    } catch (err) {\n      context.logger.warn({ err }, \"Error during graceful shutdown; exiting\");\n      process.exit(1);\n    }\n  };\n\n  const onForceSignal = (signal: \"SIGQUIT\" | \"SIGBREAK\") => {\n    context.logger.warn({ signal }, \"Received force signal; exiting now\");\n    process.exit(1);\n  };\n\n  const sigintHandler = () => void onGracefulSignal(\"SIGINT\");\n  const sigtermHandler = () => void onGracefulSignal(\"SIGTERM\");\n  const sigquitHandler = () => onForceSignal(\"SIGQUIT\");\n  const sigbreakHandler = () => onForceSignal(\"SIGBREAK\");\n  process.on(\"SIGINT\", sigintHandler);\n  process.on(\"SIGTERM\", sigtermHandler);\n  process.on(\"SIGQUIT\", sigquitHandler);\n  process.on(\"SIGBREAK\", sigbreakHandler);\n\n  return () => {\n    process.off(\"SIGINT\", sigintHandler);\n    process.off(\"SIGTERM\", sigtermHandler);\n    process.off(\"SIGQUIT\", sigquitHandler);\n    process.off(\"SIGBREAK\", sigbreakHandler);\n  };\n}\n","import type { Source, Subscription } from \"../../operations/from\";\n\nexport class SimpleSourceAdapter<T = unknown> implements Source<T> {\n  readonly adapterId = \"routecraft.adapter.simple\";\n\n  constructor(private producer: () => T | Promise<T>) {}\n\n  async subscribe(sub: Subscription<T>): Promise<void> {\n    sub.ready();\n    sub.context.logger.debug({ adapter: \"simple\" }, \"Producing messages\");\n    let result;\n    try {\n      result = await this.producer();\n    } catch (error) {\n      sub.context.logger.error(\n        { adapter: \"simple\", err: error },\n        \"Producer failed; aborting\",\n      );\n      sub.complete();\n      throw error;\n    }\n\n    if (Array.isArray(result)) {\n      sub.context.logger.debug(\n        { adapter: \"simple\", messageCount: result.length },\n        \"Processing array of messages\",\n      );\n      let failCount = 0;\n      try {\n        await Promise.all(\n          result.map((item: T) =>\n            sub.emit({ message: item }).catch(() => {\n              // Exchange error already logged by the route pipeline.\n              failCount++;\n            }),\n          ),\n        );\n      } finally {\n        if (failCount > 0) {\n          sub.context.logger.warn(\n            { adapter: \"simple\", failCount, total: result.length },\n            \"Some exchanges in batch failed\",\n          );\n        }\n        sub.context.logger.debug(\n          { adapter: \"simple\" },\n          \"Finished processing array of messages\",\n        );\n        sub.complete();\n      }\n    } else {\n      sub.context.logger.debug(\n        { adapter: \"simple\" },\n        \"Processing single message\",\n      );\n      try {\n        await sub.emit({ message: result });\n      } catch {\n        // Exchange error already logged by the route pipeline.\n        // SimpleSource does not re-throw: the route already emitted\n        // context:error, and re-throwing would cause a duplicate emission.\n      } finally {\n        sub.context.logger.debug(\n          { adapter: \"simple\" },\n          \"Finished processing single message\",\n        );\n        sub.complete();\n      }\n    }\n  }\n}\n","import type { Source } from \"../../operations/from\";\nimport { SimpleSourceAdapter } from \"./source\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag\";\n\n/**\n * Creates a source that produces one or more exchanges.\n * Use as the first step in a route with `.from(simple(...))`.\n *\n * When the producer returns (or is) an **array**, each element becomes a\n * separate exchange processed independently through the pipeline. This is\n * useful for seeding multiple messages from a single source. To pass an\n * array as the body of a single exchange, wrap it:\n * `simple({ items: [1, 2, 3] })` or use a transform after a string source.\n *\n * **Note:** If you need to emit a function itself as a value (not call it as a producer),\n * use `simple.value(myFunction)` instead of `simple(myFunction)`.\n *\n * @template T - Body type produced\n * @param producer - Static value, or function that returns T | Promise<T>\n * @returns A Source usable with `.from(simple(producer))`\n *\n * @example\n * ```typescript\n * // Single exchange with string body\n * .from(simple('hello'))\n *\n * // Two separate exchanges (one per array element)\n * .from(simple([1, 2]))\n *\n * // Single exchange with array body (wrap in object)\n * .from(simple({ items: [1, 2] }))\n *\n * // Async producer\n * .from(simple(() => fetch('/api/data').then(r => r.json())))\n *\n * // Emit a function as a value\n * .from(simple.value(myCallback))\n * ```\n */\nexport function simple<T = unknown>(\n  producer: (() => T | Promise<T>) | T,\n): Source<T> {\n  return tagAdapter(\n    new SimpleSourceAdapter<T>(\n      typeof producer === \"function\"\n        ? (producer as () => T | Promise<T>)\n        : () => producer,\n    ),\n    simple,\n    factoryArgs(producer),\n  );\n}\n\n/**\n * Creates a source that emits a static value without checking if it's a function.\n * Use this when you need to emit a function itself as a value.\n *\n * @template T - The value type to emit\n * @param value - The value to emit (including functions)\n * @returns A Source that emits the value as-is\n *\n * @example\n * ```typescript\n * const myCallback = () => console.log('hello');\n * .from(simple.value(myCallback)) // Emits the function, doesn't call it\n * ```\n */\nsimple.value = function <T>(value: T): Source<T> {\n  return tagAdapter(\n    new SimpleSourceAdapter<T>(() => value),\n    simple.value,\n    factoryArgs(value),\n  );\n};\n\n// Re-export adapter class for public API\nexport { SimpleSourceAdapter } from \"./source\";\n","import type { Destination } from \"../../operations/to.ts\";\nimport type { Exchange } from \"../../exchange.ts\";\n\n/**\n * NoopDestinationAdapter discards messages without side effects.\n */\nexport class NoopDestinationAdapter<T = unknown> implements Destination<T> {\n  readonly adapterId = \"routecraft.adapter.noop\";\n\n  send(exchange: Exchange<T>): Promise<void> {\n    const adapterLabel = this.adapterId.split(\".\").pop();\n    exchange.logger.debug(\n      { adapter: adapterLabel },\n      \"Discarding message (noop)\",\n    );\n    return Promise.resolve();\n  }\n}\n","import type { Destination } from \"../../operations/to.ts\";\nimport { NoopDestinationAdapter } from \"./destination.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\n\n/**\n * Create a no-operation adapter that does nothing.\n *\n * This can be useful for testing or as a placeholder.\n *\n * @template T The type of data this adapter processes\n * @returns A Destination that discards all messages\n */\nexport function noop<T = unknown>(): Destination<T> {\n  return tagAdapter(new NoopDestinationAdapter<T>(), noop, factoryArgs());\n}\n","import type { Exchange } from \"../../exchange\";\nimport type { Source, Subscription } from \"../../operations/from\";\nimport { rcError } from \"../../error\";\nimport { registerInternalEndpoint } from \"../../capabilities\";\nimport type { DirectServerOptions } from \"./types\";\nimport { getDirectChannel, registerRoute, sanitizeEndpoint } from \"./shared\";\n\n/**\n * DirectSourceAdapter implements the Source interface for the direct adapter.\n *\n * The endpoint name is the route id: there is no explicit endpoint option.\n * A route without `.id()` falls back to the builder's UUID id, which is by\n * design an agent-only capability (code cannot reference it as a destination,\n * but the registry still exposes it for discovery).\n *\n * This adapter is pure mechanism: input / output validation and discovery\n * metadata live on the route via `.title()` / `.description()` / `.input()` /\n * `.output()` and are handled by the framework.\n */\nexport class DirectSourceAdapter<T = unknown> implements Source<T> {\n  readonly adapterId: string = \"routecraft.adapter.direct\";\n\n  public options: DirectServerOptions;\n\n  constructor(options: DirectServerOptions = {}) {\n    this.options = options;\n  }\n\n  /**\n   * Subscribe the route's endpoint, and keep the registry honest about it.\n   *\n   * One rule, stated here rather than at each of the sites that keep it:\n   * the registry entry (a capability, or an internal marker) is written\n   * only once the subscription can actually answer, and is disposed on\n   * every path that leaves nothing to answer it. A stopped route that\n   * stayed listed was offered to agents and reported dispatchable by the\n   * ops listing, and the dispatch that followed reached a channel with no\n   * handler and failed RC5004.\n   */\n  async subscribe(sub: Subscription<T>): Promise<void> {\n    const { context, meta } = sub;\n    if (!meta?.routeId) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"DirectSourceAdapter requires a route id from the engine (missing SourceMeta.routeId)\",\n        suggestion:\n          \"Direct source adapters receive their endpoint name from the route id. This error indicates a harness or test is calling subscribe() without meta; pass { routeId: '<name>' }.\",\n      });\n    }\n\n    const endpoint = sanitizeEndpoint(meta.routeId);\n\n    // Before registering: an aborted subscription returns below without a\n    // handler, and would leave no unsubscribe to undo the entry.\n    if (sub.signal.aborted) {\n      context.logger.debug(\n        { endpoint, adapter: \"direct\" },\n        \"Subscription aborted for direct endpoint\",\n      );\n      return;\n    }\n\n    // Discovery speaks raw route ids; the sanitised key is only for the\n    // channel map. An internal route registers its internal-ness INSTEAD\n    // of a capability: the in-process endpoint below works unchanged,\n    // while ops dispatch and directTool resolution find no capability and\n    // can refuse by name.\n    // The channel first: a configured `channelType` constructor can throw,\n    // and a registry entry written before it would outlive a route that\n    // never subscribed, which is the defect this whole path exists to stop.\n    const channel = getDirectChannel<T>(context, endpoint, this.options);\n\n    const unregister =\n      this.options.internal === true\n        ? registerInternalEndpoint(context, meta.routeId)\n        : registerRoute(context, meta.routeId, meta.discovery);\n\n    context.logger.debug(\n      { endpoint, adapter: \"direct\" },\n      \"Setting up subscription for direct endpoint\",\n    );\n\n    // Unwrap the channel's Exchange payload and hand body / headers to the\n    // framework-provided handler. The caller's principal rides through on\n    // `headers[\"routecraft.auth.principal\"]` (the source of truth after\n    // the state-model unification), so route-to-route invocations\n    // preserve identity automatically: the called route's `.authorize()`\n    // sees the same principal as the caller without a separate parameter.\n    // Framework-level input validation runs inside the handler, so the\n    // adapter has nothing more to do here.\n    const wrappedHandler = async (exchange: Exchange<T>) => {\n      const result = await sub.emit({\n        message: exchange.body as T,\n        headers: exchange.headers,\n      });\n      return result as Exchange<T>;\n    };\n\n    // Wired before subscribing, so an abort landing mid-setup is caught.\n    sub.signal.addEventListener(\n      \"abort\",\n      () => {\n        unregister();\n        channel.unsubscribe(context, endpoint).catch((err) => {\n          context.logger.error(\n            { err, adapter: \"direct\", endpoint, operation: \"unsubscribe\" },\n            \"Failed to unsubscribe from direct endpoint during abort\",\n          );\n        });\n      },\n      { once: true },\n    );\n\n    // Roll the registration back if the channel refuses the handler.\n    try {\n      await channel.subscribe(context, endpoint, wrappedHandler);\n    } catch (error: unknown) {\n      unregister();\n      throw error;\n    }\n\n    sub.ready();\n\n    // Keep the route \"running\" until the context stops (abort). Otherwise the context\n    // would see all routes complete and auto-stop, e.g. before MCP can serve tool calls.\n    await new Promise<void>((resolve) => {\n      if (sub.signal.aborted) {\n        resolve();\n        return;\n      }\n      sub.signal.addEventListener(\"abort\", () => resolve(), {\n        once: true,\n      });\n    });\n  }\n}\n","import type { Exchange } from \"../../exchange\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport type { DirectEndpoint, DirectClientOptions } from \"./types\";\nimport { getDirectChannel, sanitizeEndpoint } from \"./shared\";\n\n/**\n * DirectEnricherAdapter implements the Enricher (fetch) role for the direct\n * adapter: an in-process request/response is a pull-in (the caller blocks on\n * the target route and receives its response body).\n *\n * This adapter is used when direct() is called with one argument:\n * - `direct(endpoint)` where endpoint is a string\n * - `direct((exchange) => endpoint)` where endpoint is a function\n *\n * The two generics model the in-process request/response shape: `TIn` is the\n * body type the caller sends, `TOut` is the body type the target route\n * returns. They default to being equal for backwards compatibility with the\n * symmetric `Enricher<T, T>` overload of `direct()`.\n */\nexport class DirectEnricherAdapter<\n  TIn = unknown,\n  TOut = TIn,\n> implements Enricher<TIn, TOut> {\n  readonly adapterId: string = \"routecraft.adapter.direct\";\n\n  private rawEndpoint: DirectEndpoint<TIn>;\n  public options: DirectClientOptions;\n  /**\n   * Endpoint each in-flight fetch resolved, keyed by the exchange it ran\n   * against so `getMetadata` reports that call's endpoint. One adapter\n   * instance serves every exchange on the route, so a single \"last resolved\"\n   * field would report whichever concurrent exchange finished resolving last.\n   * Weak keys: entries go when the exchange does.\n   */\n  private readonly resolvedEndpoints = new WeakMap<Exchange<TIn>, string>();\n\n  constructor(\n    rawEndpoint: DirectEndpoint<TIn>,\n    options: DirectClientOptions = {},\n  ) {\n    this.rawEndpoint = rawEndpoint;\n    this.options = options;\n  }\n\n  fetch = async (exchange: Exchange<TIn>): Promise<TOut> => {\n    // Import dynamically to avoid circular dependency\n    const { getExchangeContext } = await import(\"../../exchange\");\n    const context = getExchangeContext(exchange);\n    if (!context) {\n      throw new Error(\"Exchange has no context; cannot call direct endpoint\");\n    }\n\n    // Resolve endpoint dynamically if needed\n    const endpoint = this.resolveEndpoint(exchange);\n    this.resolvedEndpoints.set(exchange, endpoint);\n\n    exchange.logger.debug(\n      { endpoint, adapter: \"direct\" },\n      \"Preparing to send message to direct endpoint\",\n    );\n\n    const channel = getDirectChannel<TIn>(context, endpoint, this.options);\n\n    // Send and wait for result - this is synchronous blocking behavior\n    const result = await channel.send(endpoint, exchange);\n\n    // The wire-level channel is body-symmetric, but the consumer route may\n    // produce a body whose shape differs from the caller's input. That shape\n    // is opaque to this adapter at compile time, so we widen here.\n    return result.body as unknown as TOut;\n  };\n\n  /**\n   * Observability metadata for the fetch role: the endpoint THIS exchange's\n   * fetch resolved, read back from {@link resolvedEndpoints}.\n   *\n   * Deliberately not re-running the endpoint selector: a dynamic\n   * `direct((ex) => ...)` is user code, so calling it a second time would\n   * double any side effect it has and could name a different route than the\n   * one that actually handled the exchange. A static endpoint has no such\n   * hazard, so it falls back to resolving.\n   */\n  getMetadata(\n    _result?: unknown,\n    exchange?: Exchange<TIn>,\n  ): Record<string, unknown> {\n    const recorded = exchange\n      ? this.resolvedEndpoints.get(exchange)\n      : undefined;\n    if (recorded !== undefined) return { endpoint: recorded };\n    return {\n      endpoint:\n        typeof this.rawEndpoint === \"string\"\n          ? sanitizeEndpoint(this.rawEndpoint)\n          : \"unknown\",\n    };\n  }\n\n  private resolveEndpoint(exchange: Exchange<TIn>): string {\n    const endpoint =\n      typeof this.rawEndpoint === \"function\"\n        ? this.rawEndpoint(exchange)\n        : this.rawEndpoint;\n    return sanitizeEndpoint(endpoint);\n  }\n}\n","import type { Exchange } from \"../../exchange\";\nimport type { Source } from \"../../operations/from\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport type {\n  RegisteredDirectEndpoint,\n  DirectEndpointRegistry,\n  ResolveBody,\n} from \"../../registry\";\nimport { DirectSourceAdapter } from \"./source\";\nimport { DirectEnricherAdapter } from \"./enricher\";\nimport type { DirectEndpoint, DirectServerOptions } from \"./types\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag\";\n\n/**\n * Creates a direct adapter for synchronous, in-process inter-route messaging.\n *\n * - **Source (for `.from()`):** Call with channel options (`channelType`,\n *   `internal`) or with no arguments. The endpoint is always the route id;\n *   discoverable metadata (title, description, input, output) lives on the\n *   route via `.title()`, `.description()`, `.input()`, `.output()`.\n *   `direct({ internal: true })` keeps the in-process endpoint and closes\n *   the external doors: not dispatchable through ops, not resolvable as an\n *   agent `directTool`; only composable from another route.\n * - **Enricher (for `.to()` / `.enrich()` / `.tap()`):** Call with a string\n *   or function naming the target route: `direct(\"fetch-order\")` or\n *   `direct((exchange) => exchange.headers[\"x-endpoint\"] as string)`. The\n *   call is a pull-in: the target route's response body replaces the body in\n *   `.to()` / bare `.enrich()`, feeds the aggregator in `.enrich(x, agg)`,\n *   and is discarded by `.tap()`.\n * - **Enricher with explicit input/output types:** Supply two type\n *   arguments to express a route whose response body shape differs from\n *   the caller's input shape, e.g. `direct<ChatInput, AgentResult>(\"agent\")`.\n *   Works with both string and function endpoints. When\n *   `DirectEndpointRegistry` is populated, the endpoint string is still\n *   constrained to registered keys.\n *\n * Semantics: single consumer per endpoint (last subscriber wins), blocking\n * send (sender waits for response).\n *\n * @example\n * ```ts\n * // Source route (endpoint = route id)\n * craft()\n *   .id(\"ingest\")\n *   .title(\"Ingest API\")\n *   .description(\"Accept ingest payloads\")\n *   .input({ body: mySchema })\n *   .from(direct())\n *\n * // Agent-only source (no id -> UUID endpoint, not callable from code)\n * craft()\n *   .description(\"Internal knowledge base lookup\")\n *   .input({ body: querySchema })\n *   .from(direct())\n *\n * // Destination\n * .to(direct(\"ingest\"))\n * .to(direct((ex) => ex.headers[\"x-endpoint\"] as string))\n *\n * // Destination with input != output (e.g. in-process agent call)\n * .transform((b) => ({ name: b.agent, query: b.text }))\n * .enrich(direct<{ name: string; query: string }, AgentResult>(\"agent\"))\n * ```\n */\nexport function direct(options: DirectServerOptions): Source<unknown>;\nexport function direct(): Source<unknown>;\nexport function direct<K extends RegisteredDirectEndpoint>(\n  endpoint: K,\n): Enricher<ResolveBody<DirectEndpointRegistry, K>, unknown>;\nexport function direct<T = unknown>(\n  endpoint: DirectEndpoint<T>,\n): Enricher<T, T>;\n/**\n * Enricher with explicit input and output body types. Use when the\n * target route's response body shape differs from the caller's input\n * shape (e.g. an in-process agent or RPC-style call). Accepts a string\n * endpoint (constrained to registered keys when `DirectEndpointRegistry`\n * is populated) or a function endpoint resolved from the exchange.\n *\n *   actually returns a value matching `TOut`. The caller asserts the\n *   output shape. A future release may require a matching\n *   `.output({ body: schema })` on the callee and validate the response\n *   automatically; until then, treat `TOut` as a caller-side assertion\n *   rather than a framework-enforced contract.\n */\nexport function direct<TIn, TOut>(\n  endpoint: RegisteredDirectEndpoint | ((exchange: Exchange<TIn>) => string),\n): Enricher<TIn, TOut>;\nexport function direct<TIn = unknown, TOut = TIn>(\n  arg?: DirectEndpoint<TIn> | DirectServerOptions,\n): Source<unknown> | Enricher<TIn, TOut> {\n  // String or function first-arg -> Enricher (names a target route).\n  if (typeof arg === \"string\" || typeof arg === \"function\") {\n    return tagAdapter(\n      new DirectEnricherAdapter<TIn, TOut>(arg),\n      direct,\n      factoryArgs(arg),\n    );\n  }\n  // Undefined or options object -> Source (endpoint resolved from route id).\n  return tagAdapter(\n    new DirectSourceAdapter(arg ?? {}),\n    direct,\n    factoryArgs(arg),\n  ) as Source<unknown>;\n}\n\n// Re-export types for public API\nexport type {\n  DirectChannel,\n  DirectChannelType,\n  DirectEndpoint,\n  DirectBaseOptions,\n  DirectServerOptions,\n  DirectClientOptions,\n  DirectOptions,\n} from \"./types\";\n\n// Re-export constants for registry access\nexport {\n  ADAPTER_DIRECT_STORE,\n  ADAPTER_DIRECT_OPTIONS,\n  getDirectChannel,\n  sanitizeEndpoint,\n} from \"./shared\";\n","import type { Duration } from \"../../shared/duration.ts\";\n\nexport interface TimerOptions {\n  /**\n   * Time between executions.\n   * @default 1000\n   */\n  interval?: Duration;\n\n  /**\n   * Delay before the first execution.\n   * @default 0\n   */\n  delay?: Duration;\n\n  /**\n   * Number of times to trigger before stopping\n   * @default Infinity\n   */\n  repeatCount?: number;\n\n  /**\n   * Ensures execution happens at exact intervals (ignoring execution time)\n   * @default false\n   */\n  fixedRate?: boolean;\n\n  /**\n   * Upper bound on a random delay added to each scheduled run, to stop many\n   * instances firing in lockstep. Each wait is drawn uniformly from\n   * `[0, maxJitter)`.\n   * @default 0\n   */\n  maxJitter?: Duration;\n}\n\n/**\n * Header keys the timer source sets on every emitted exchange. Keys live\n * under the reserved `routecraft.timer.*` namespace; the value types are\n * merged into `RoutecraftHeaders` below.\n */\nexport const TimerHeaders = {\n  /** The exact timestamp when the timer fired, in ISO 8601 format */\n  TIME: \"routecraft.timer.time\",\n  /** The timestamp when the exchange was created, in ISO 8601 format */\n  FIRED_TIME: \"routecraft.timer.firedTime\",\n  /** The period in milliseconds between timer firings */\n  PERIOD_MS: \"routecraft.timer.periodMs\",\n  /** The number of times the timer has fired */\n  COUNTER: \"routecraft.timer.counter\",\n  /** The next timestamp when the timer will fire, in ISO 8601 format */\n  NEXT_RUN: \"routecraft.timer.nextRun\",\n} as const satisfies Record<string, `routecraft.timer.${string}`>;\n\ndeclare module \"@routecraft/routecraft\" {\n  interface RoutecraftHeaders {\n    /** The exact timestamp when the timer fired, in ISO 8601 format */\n    [TimerHeaders.TIME]?: string;\n    /** The timestamp when the exchange was created, in ISO 8601 format */\n    [TimerHeaders.FIRED_TIME]?: string;\n    /** The period in milliseconds between timer firings */\n    [TimerHeaders.PERIOD_MS]?: number;\n    /** The number of times the timer has fired */\n    [TimerHeaders.COUNTER]?: number;\n    /** The next timestamp when the timer will fire, in ISO 8601 format */\n    [TimerHeaders.NEXT_RUN]?: string;\n  }\n}\n","import type { ExchangeHeaders } from \"../../exchange\";\nimport { TimerHeaders } from \"./types\";\nimport type { Source, Subscription } from \"../../operations/from\";\nimport type { TimerOptions } from \"./types\";\nimport { parseDuration } from \"../../shared/duration.ts\";\n\nexport class TimerSourceAdapter implements Source<undefined> {\n  readonly adapterId = \"routecraft.adapter.timer\";\n  constructor(private options?: TimerOptions) {}\n\n  subscribe(sub: Subscription<undefined>): Promise<void> {\n    const {\n      interval = 1000,\n      delay = 0,\n      repeatCount = Infinity,\n      fixedRate = false,\n      maxJitter = 0,\n    } = this.options || {};\n    const intervalMs = parseDuration(interval, \"timer({ interval })\");\n    const delayMs = parseDuration(delay, \"timer({ delay })\", 0);\n    const maxJitterMs = parseDuration(maxJitter, \"timer({ maxJitter })\", 0);\n\n    const baseTime = Date.now() + delayMs;\n\n    sub.ready();\n\n    // Create and return an async promise that runs the timer loop\n    return new Promise<void>((resolve) => {\n      let count = 0;\n\n      const runTimer = async () => {\n        while (count < repeatCount && !sub.signal.aborted) {\n          let scheduledTime: number;\n          if (fixedRate) {\n            scheduledTime = baseTime + count * intervalMs;\n          } else {\n            // Non-fixedRate: the first run uses baseTime; subsequent runs trigger delay after the previous run.\n            if (count === 0) {\n              scheduledTime = baseTime;\n            } else {\n              scheduledTime = Date.now() + intervalMs;\n            }\n          }\n\n          // Calculate waiting time until scheduled execution\n          const now = Date.now();\n          let waitTime = scheduledTime - now;\n          if (waitTime < 0) {\n            waitTime = 0;\n          }\n          if (maxJitterMs > 0) {\n            // Uniform in [0, maxJitter): the option is an upper bound, which\n            // is what its name promises.\n            waitTime += Math.floor(Math.random() * maxJitterMs);\n          }\n\n          // Abort-aware wait: a plain setTimeout would pin shutdown for up\n          // to one full interval after the route stops.\n          await new Promise<void>((r) => {\n            const onAbort = () => {\n              clearTimeout(t);\n              r();\n            };\n            const t = setTimeout(() => {\n              sub.signal.removeEventListener(\"abort\", onAbort);\n              r();\n            }, waitTime);\n            sub.signal.addEventListener(\"abort\", onAbort, { once: true });\n          });\n          if (sub.signal.aborted) break;\n\n          const firedTime = new Date();\n          count++;\n\n          // Compute the next scheduled time for header information\n          const nextScheduledTime = fixedRate\n            ? baseTime + count * intervalMs\n            : Date.now() + intervalMs;\n\n          // Prepare timer-based headers\n          const headers: ExchangeHeaders = {\n            [TimerHeaders.TIME]: firedTime.toISOString(),\n            [TimerHeaders.FIRED_TIME]: firedTime.toISOString(),\n            [TimerHeaders.PERIOD_MS]: intervalMs,\n            [TimerHeaders.COUNTER]: count,\n            [TimerHeaders.NEXT_RUN]: new Date(nextScheduledTime).toISOString(),\n          };\n\n          try {\n            await sub.emit({ message: undefined, headers });\n          } catch {\n            // Exchange error already logged by the route pipeline.\n            // Timer continues to fire for remaining ticks.\n          }\n        }\n        resolve();\n      };\n\n      runTimer();\n    });\n  }\n}\n","import type { Source } from \"../../operations/from\";\nimport { TimerSourceAdapter } from \"./source\";\nimport type { TimerOptions } from \"./types\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag\";\nimport { rejectStaleOptions } from \"../../shared/stale-options.ts\";\n\n/** Options removed in 0.7, mapped to what to write instead. */\nconst REMOVED: Readonly<Record<string, string>> = {\n  timePattern:\n    \"use cron() for a wall-clock schedule, which also has timezones.\",\n  exactTime:\n    \"use cron() for a wall-clock schedule, or timer({ delay }) to offset the first run.\",\n  jitter:\n    \"use maxJitter, the same value under a name that says it is an upper bound.\",\n  jitterMs:\n    \"use maxJitter, the same value under a name that says it is an upper bound.\",\n};\n\n/**\n * Creates a source that emits at a fixed interval. Body is undefined; timer\n * metadata is in exchange headers (routecraft.timer.*).\n *\n * For a wall-clock schedule (\"every weekday at 09:00\") use `cron()`, which\n * supports timezones.\n *\n * @param options - interval, delay, repeatCount, fixedRate, maxJitter\n * @returns A Source usable with `.from(timer(options))`\n *\n * @example\n * ```typescript\n * .from(timer({ interval: \"5s\", repeatCount: 10 }))\n * .from(timer({ interval: \"1m\", maxJitter: \"5s\" }))\n * ```\n */\nexport function timer(options?: TimerOptions): Source<undefined> {\n  rejectStaleOptions(options, \"timer\", REMOVED);\n  return tagAdapter(\n    new TimerSourceAdapter(options),\n    timer,\n    factoryArgs(options),\n  );\n}\n\n// Re-export adapter class and types for public API\nexport { TimerSourceAdapter } from \"./source\";\nexport type { TimerOptions } from \"./types\";\nexport { TimerHeaders } from \"./types\";\n","import type { Source } from \"../../operations/from\";\nimport { CronSourceAdapter } from \"./source\";\nimport type { CronExpression, CronOptions } from \"./types\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag\";\nimport { rejectStaleOptions } from \"../../shared/stale-options.ts\";\n\n/** Options removed in 0.7, mapped to what to write instead. */\nconst REMOVED: Readonly<Record<string, string>> = {\n  jitter:\n    \"use maxJitter, the same value under a name that says it is an upper bound.\",\n  jitterMs:\n    \"use maxJitter, the same value under a name that says it is an upper bound.\",\n};\n\n/**\n * Creates a source that emits on a cron schedule. Body is undefined; cron metadata is in exchange headers (routecraft.cron.*).\n *\n * Supports standard 5-field cron, 6-field (with seconds), and nicknames (@daily, @weekly, @hourly, @monthly, @yearly, @annually, @midnight).\n *\n * @param expression - Cron expression string\n * @param options - timezone, maxFires, maxJitter, name, protect, startAt, stopAt\n * @returns A Source usable with `.from(cron(expression, options))`\n *\n * @example\n * ```typescript\n * .from(cron(\"0 9 * * 1-5\"))                              // weekdays at 9am\n * .from(cron(\"@daily\", { timezone: \"America/New_York\" }))  // daily in EST\n * .from(cron(\"0 0 1 * *\", { name: \"monthly-report\" }))    // first of each month\n * ```\n */\nexport function cron(\n  expression: CronExpression,\n  options?: CronOptions,\n): Source<undefined> {\n  rejectStaleOptions(options, \"cron\", REMOVED);\n  return tagAdapter(\n    new CronSourceAdapter(expression, options),\n    cron,\n    factoryArgs(expression, options),\n  );\n}\n\nexport { CronSourceAdapter, ADAPTER_CRON_OPTIONS } from \"./source\";\nexport type { CronExpression, CronOptions } from \"./types\";\nexport { CronHeaders } from \"./types\";\n","import type { Enricher } from \"../../operations/enrich.ts\";\nimport { anySignal } from \"../../shared/abort.ts\";\nimport type { Exchange } from \"../../exchange\";\nimport { parseDuration } from \"../../shared/duration.ts\";\nimport { rcError } from \"../../error\";\nimport {\n  declaredLengthOver,\n  resolveMaxBodySize,\n} from \"../../plugins/http/max-body-size\";\nimport type { StepSignalContext } from \"../../types.ts\";\nimport { isRedirect } from \"./redirect\";\nimport type {\n  HttpClientOptions,\n  HttpRedirectMode,\n  HttpResponseBodyMode,\n  HttpResult,\n  QueryParams,\n} from \"./types\";\n\nconst REDIRECT_MODES: ReadonlySet<string> = new Set<HttpRedirectMode>([\n  \"follow\",\n  \"manual\",\n  \"error\",\n]);\n\n/**\n * HttpEnricherAdapter performs HTTP requests and returns the result: a pure\n * pull-in, so it implements the fetch role only.\n * - With `.enrich()`: the result replaces the body (or feeds the aggregator)\n * - With `.to()`: fetch-only fallback, the result replaces the body\n * - With `.tap()`: fire-and-forget, the result is discarded\n *\n * Two options bound what a remote endpoint can do to a route that calls it.\n * `maxBodySize` caps the response body, enforced against a declared\n * `Content-Length` before any byte is read and again against the running\n * count while the body streams, so the ceiling bounds what the process\n * spends rather than only what the route receives. `redirect` mirrors the\n * platform's three modes and takes no position on where a redirect leads:\n * with `\"manual\"` the 3xx comes back intact and the route decides.\n */\nexport class HttpEnricherAdapter<T = unknown, R = unknown> implements Enricher<\n  T,\n  HttpResult<R>\n> {\n  readonly adapterId = \"routecraft.adapter.http\";\n\n  private readonly maxBodySize: number;\n  private readonly redirect: HttpRedirectMode;\n  private readonly responseBody: HttpResponseBodyMode;\n\n  constructor(private readonly options: HttpClientOptions<T>) {\n    this.maxBodySize = resolveMaxBodySize(\n      options.maxBodySize,\n      \"http() client\",\n      { allowUnbounded: true },\n    );\n    this.redirect = normalizeRedirect(options.redirect);\n    this.responseBody = normalizeResponseBody(options.responseBody);\n  }\n\n  fetch = async (\n    exchange: Exchange<T>,\n    ctx: StepSignalContext = {},\n  ): Promise<HttpResult<R>> => {\n    const result = await this.performFetch(exchange, ctx.signal);\n    return result as HttpResult<R>;\n  };\n\n  /**\n   * Extract metadata from HTTP result for observability.\n   * Includes method, url, statusCode, and contentLength.\n   */\n  getMetadata(result: unknown): Record<string, unknown> {\n    const httpResult = result as HttpResult<R>;\n    const metadata: Record<string, unknown> = {\n      method: this.options.method ?? \"GET\",\n      url: httpResult.url,\n      statusCode: httpResult.status,\n    };\n\n    // Add content length if available from headers\n    const contentLength = httpResult.headers?.[\"content-length\"];\n    if (contentLength !== undefined) {\n      const parsed = parseInt(contentLength, 10);\n      if (!isNaN(parsed)) {\n        metadata[\"contentLength\"] = parsed;\n      }\n    }\n\n    return metadata;\n  }\n\n  private async performFetch(\n    exchange: Exchange<T>,\n    stepSignal?: AbortSignal,\n  ): Promise<HttpResult> {\n    const method = this.options.method ?? \"GET\";\n    const url = this.resolveRequired(this.options.url, exchange);\n    const headers = { ...(this.resolve(this.options.headers, exchange) ?? {}) };\n    const query = this.resolve(this.options.query, exchange);\n    const resolvedBody = this.resolve(this.options.body, exchange);\n    const throwOnHttpError = this.options.throwOnHttpError ?? true;\n    const timeoutMs =\n      this.options.timeout === undefined\n        ? undefined\n        : parseDuration(this.options.timeout, \"http({ timeout })\");\n\n    const finalUrl = this.appendQuery(url, query ?? {});\n\n    let body: BodyInit | undefined;\n    if (resolvedBody !== undefined && resolvedBody !== null) {\n      if (\n        typeof resolvedBody === \"string\" ||\n        ArrayBuffer.isView(resolvedBody) ||\n        resolvedBody instanceof ArrayBuffer ||\n        resolvedBody instanceof Blob ||\n        resolvedBody instanceof FormData ||\n        resolvedBody instanceof URLSearchParams\n      ) {\n        // Handed over untouched, and deliberately without a Content-Type of\n        // our own: fetch derives the right one, including the multipart\n        // boundary, which cannot be written by hand. JSON.stringify reduces a\n        // FormData to \"{}\" on Node and to a plain object on Bun, so the same\n        // upload would lose its files on one runtime and change format on the\n        // other.\n        body = resolvedBody as BodyInit;\n      } else {\n        // Looked up case-insensitively: a route that set `content-type`\n        // itself would otherwise get the header twice, since fetch keeps\n        // both spellings.\n        if (!hasHeader(headers, \"content-type\"))\n          headers[\"Content-Type\"] = \"application/json\";\n        body = JSON.stringify(resolvedBody);\n      }\n    }\n\n    const controller = timeoutMs ? new AbortController() : undefined;\n    const timeout = timeoutMs\n      ? setTimeout(() => controller!.abort(), timeoutMs)\n      : undefined;\n    // Combine the adapter's own timeout controller with the step's\n    // signal (an enclosing `.timeout()` deadline): whichever fires\n    // first aborts the request.\n    const signal = anySignal(controller?.signal, stepSignal);\n\n    try {\n      const res = (await globalThis.fetch(finalUrl, {\n        method,\n        headers,\n        body,\n        redirect: this.redirect,\n        signal,\n      } as RequestInit)) as Response;\n\n      const headersRecord: Record<string, string> = {};\n      res.headers.forEach((value, key) => {\n        headersRecord[key] = value;\n      });\n\n      const raw = await this.readBody(res, headersRecord, finalUrl);\n\n      const isRequestedRedirect =\n        this.redirect === \"manual\" && isRedirect({ status: res.status });\n\n      if (throwOnHttpError && !res.ok && !isRequestedRedirect) {\n        // A binary body has no text to quote, and decoding it for the message\n        // would reintroduce on the error path exactly the corruption this\n        // mode exists to avoid. Name its shape instead.\n        throw new Error(\n          typeof raw === \"string\"\n            ? `HTTP ${res.status}: ${raw}`\n            : `HTTP ${res.status}: ${raw.byteLength} bytes of ${headersRecord[\"content-type\"] ?? \"an unnamed content type\"}`,\n        );\n      }\n\n      // Auto-parse JSON based on Content-Type. Bytes are handed over as they\n      // arrived: the mode exists because the caller wants the wire form.\n      let parsedBody: string | unknown = raw;\n      const contentType = headersRecord[\"content-type\"]?.toLowerCase() || \"\";\n      if (typeof raw === \"string\" && contentType.includes(\"application/json\")) {\n        try {\n          parsedBody = JSON.parse(raw);\n        } catch {\n          // Parse failed, keep as string\n          parsedBody = raw;\n        }\n      }\n\n      return {\n        status: res.status,\n        headers: headersRecord,\n        body: parsedBody,\n        url: res.url || finalUrl,\n      } satisfies HttpResult;\n    } finally {\n      if (timeout) clearTimeout(timeout);\n    }\n  }\n\n  /**\n   * Read the response body as text without letting it exceed\n   * `maxBodySize`.\n   *\n   * A declared `Content-Length` over the cap is refused first, without\n   * reading a byte of the body: the cheapest refusal available. It is not\n   * sufficient alone, because a chunked response declares nothing, so the\n   * streaming arm counts what actually arrives and abandons the response the\n   * moment the count crosses the ceiling. That second arm is what makes the\n   * option bound what the process spends rather than only what the route\n   * sees. Chunks are decoded as they arrive and never held together, so the\n   * peak is the decoded text plus one chunk rather than several copies of\n   * the body.\n   *\n   * Both refusing arms cancel the body first. An unconsumed response body\n   * holds its connection checked out and keeps the runtime buffering\n   * whatever the server sends, which is the exact cost the refusal exists to\n   * avoid, and it leaks a socket per attempt on a route that polls.\n   *\n   * A response with no readable stream (a 204, a `HEAD`, or a test double\n   * standing in for one) falls back to buffering, where the cap can only be\n   * checked after the fact. Nothing is lost: a body that never streamed was\n   * already in memory before this method was called.\n   *\n   * @throws RoutecraftError RC5061 when the declared or actual size exceeds\n   * the cap.\n   */\n  private async readBody(\n    res: Response,\n    headersRecord: Record<string, string>,\n    requestUrl: string,\n  ): Promise<string | Uint8Array> {\n    const max = this.maxBodySize;\n    const asBytes = this.responseBody === \"bytes\";\n\n    const declared = declaredLengthOver(headersRecord[\"content-length\"], max);\n    if (declared !== undefined) {\n      await res.body?.cancel().catch(() => {});\n      throw this.tooLarge(res, requestUrl, declared, \"declared\");\n    }\n\n    const stream = res.body;\n    if (!stream) {\n      if (asBytes) {\n        const bytes = new Uint8Array(await res.arrayBuffer());\n        if (bytes.byteLength > max) {\n          throw this.tooLarge(res, requestUrl, bytes.byteLength, \"read\");\n        }\n        return bytes;\n      }\n      const text = await res.text();\n      const size = new TextEncoder().encode(text).byteLength;\n      if (size > max) {\n        throw this.tooLarge(res, requestUrl, size, \"read\");\n      }\n      return text;\n    }\n\n    const reader = stream.getReader();\n    // Only one of these accumulates, chosen by the mode. The counting and the\n    // cap are identical either way: the difference is whether the bytes are\n    // decoded on the way past.\n    const decoder = asBytes ? undefined : new TextDecoder();\n    const chunks: Uint8Array[] = [];\n    let text = \"\";\n    let total = 0;\n    try {\n      for (;;) {\n        const { done, value } = await reader.read();\n        if (done) break;\n        total += value.byteLength;\n        if (total > max) {\n          throw this.tooLarge(res, requestUrl, total, \"read\");\n        }\n        if (decoder === undefined) {\n          chunks.push(value);\n        } else {\n          // `stream: true` keeps a multi-byte character split across a chunk\n          // boundary intact.\n          text += decoder.decode(value, { stream: true });\n        }\n      }\n    } finally {\n      await reader.cancel().catch(() => {});\n    }\n    if (decoder === undefined) return concatBytes(chunks, total);\n    return text + decoder.decode();\n  }\n\n  /**\n   * Build the `RC5061` refusal.\n   *\n   * Names the request URL, the status, the limit, and the size that was\n   * either declared or counted, because the two arms know different things:\n   * a declaration is what the server claimed, a count is what had arrived\n   * before the read was abandoned and says nothing about what was still\n   * coming. The status is in the message so an oversized error response\n   * stays diagnosable as the HTTP failure it also is.\n   */\n  private tooLarge(\n    res: Response,\n    requestUrl: string,\n    size: number,\n    kind: \"declared\" | \"read\",\n  ): Error {\n    const seen =\n      kind === \"declared\"\n        ? `declares a body of ${size} bytes`\n        : `had sent at least ${size} bytes when the read was abandoned`;\n    return rcError(\"RC5061\", undefined, {\n      message: `http() client: ${requestUrl} (HTTP ${res.status}) ${seen}, over the maxBodySize of ${this.maxBodySize} bytes. Raise maxBodySize on this http({...}) call if the response is legitimately this large.`,\n    });\n  }\n\n  private resolve<V>(\n    val: V | ((exchange: Exchange<T>) => V) | undefined,\n    exchange: Exchange<T>,\n  ): V | undefined {\n    if (typeof val === \"function\") {\n      return (val as (e: Exchange<T>) => V)(exchange);\n    }\n    return val as V | undefined;\n  }\n\n  private resolveRequired<V>(\n    val: V | ((exchange: Exchange<T>) => V),\n    exchange: Exchange<T>,\n  ): V {\n    if (typeof val === \"function\") {\n      return (val as (e: Exchange<T>) => V)(exchange);\n    }\n    return val as V;\n  }\n\n  private appendQuery(url: string, query?: QueryParams): string {\n    if (!query || Object.keys(query).length === 0) return url;\n    const u = new URL(url, this.base(url));\n    for (const [k, v] of Object.entries(query)) {\n      u.searchParams.set(k, String(v));\n    }\n    return u.toString();\n  }\n\n  private base(url: string): string | undefined {\n    try {\n      const u = new URL(url);\n      return `${u.protocol}//${u.host}`;\n    } catch {\n      return undefined;\n    }\n  }\n}\n\n/**\n * @throws RoutecraftError RC5003 when the mode is not one the platform\n * defines. Passing an unknown string to `fetch` is silently ignored by\n * some runtimes, which would leave a route believing it had opted out of\n * following redirects while the adapter kept following them.\n */\nfunction normalizeRedirect(\n  value: HttpRedirectMode | undefined,\n): HttpRedirectMode {\n  if (value === undefined) return \"follow\";\n  if (!REDIRECT_MODES.has(value)) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `http() client: invalid redirect ${String(value)}. Allowed: ${[...REDIRECT_MODES].map((m) => `\"${m}\"`).join(\", \")}.`,\n    });\n  }\n  return value;\n}\n\n/**\n * Resolve `responseBody`, defaulting to the mode every route had before the\n * option existed. An unknown value fails at the `http({...})` call site rather\n * than being read as the default: a route meaning to receive bytes and\n * silently receiving a corrupted string is the exact failure this option was\n * added to remove.\n */\nfunction normalizeResponseBody(\n  mode: HttpResponseBodyMode | undefined,\n): HttpResponseBodyMode {\n  if (mode === undefined) return \"text\";\n  if (mode !== \"text\" && mode !== \"bytes\") {\n    throw rcError(\"RC5003\", undefined, {\n      message: `http() client: invalid responseBody ${JSON.stringify(mode)}. Allowed: \"text\", \"bytes\".`,\n    });\n  }\n  return mode;\n}\n\n/**\n * Case-insensitive lookup for a header already set to a non-empty value.\n *\n * Tests the value, not just the key: the check this replaced was\n * `!headers[\"Content-Type\"]`, so an empty string was overwritten rather than\n * honoured, and a callback building headers with `?? \"\"` relies on that.\n */\nfunction hasHeader(headers: Record<string, string>, name: string): boolean {\n  const wanted = name.toLowerCase();\n  for (const [key, value] of Object.entries(headers)) {\n    if (key.toLowerCase() === wanted) return value !== \"\";\n  }\n  return false;\n}\n\n/**\n * Join the chunks as they arrived. `total` is already known from the cap\n * accounting, so the result is allocated once rather than grown per chunk.\n */\nfunction concatBytes(chunks: readonly Uint8Array[], total: number): Uint8Array {\n  const out = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    out.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return out;\n}\n","import type { HttpResult } from \"./types\";\n\n/**\n * Statuses that carry a redirect.\n *\n * `304 Not Modified` is deliberately absent: it is a cache answer rather than\n * a hop, it names no `Location`, and a route asking about redirects is asking\n * about hops. The obvious hand-rolled predicate (`status >= 300 && status <\n * 400`) includes it and therefore disagrees with the adapter, which is why\n * this set is exported rather than left for every route to re-derive.\n */\nexport const HTTP_REDIRECT_STATUSES: ReadonlySet<number> = new Set([\n  301, 302, 303, 307, 308,\n]);\n\n/**\n * True when a result carries a redirect the route may choose to follow.\n *\n * The predicate a `redirect: \"manual\"` route branches on, and the same rule\n * the adapter itself applies when deciding that a 3xx is the outcome the\n * route asked for rather than an http error. Excludes `304`, per\n * {@link HTTP_REDIRECT_STATUSES}.\n *\n * @example\n * ```typescript\n * .enrich(http({ url: (ex) => ex.body.url, redirect: \"manual\" }))\n * .choice(when(isRedirect, revalidateAndFollow))\n * ```\n */\nexport function isRedirect(result: Pick<HttpResult, \"status\">): boolean {\n  return HTTP_REDIRECT_STATUSES.has(result.status);\n}\n","import type { CraftPlugin } from \"../../context\";\nimport { rcError } from \"../../error\";\nimport type { Source, Subscription } from \"../../operations/from\";\nimport {\n  HTTP_MOUNTS,\n  HTTP_PLUGIN_REGISTERED,\n  type HttpMountRuntime,\n  type HttpRouteEntry,\n} from \"../../plugins/http/registry\";\nimport { compilePathMatcher } from \"../../plugins/http/path-matcher\";\nimport { METHODS_WITHOUT_BODY } from \"../../plugins/http/body-parser\";\nimport { invalidSignatureOptionsReason } from \"../../plugins/http/webhook-signature\";\nimport type { HttpMethod, HttpRequestBody, HttpServerOptions } from \"./types\";\n\nconst HTTP_METHODS: ReadonlySet<string> = new Set([\n  \"GET\",\n  \"POST\",\n  \"PUT\",\n  \"PATCH\",\n  \"DELETE\",\n  \"HEAD\",\n  \"OPTIONS\",\n]);\n\n/**\n * Resolve the route's method, defaulting to GET and upper-casing so an\n * untyped JS caller passing `method: \"post\"` matches the dispatcher's\n * uppercase comparison instead of silently registering a route that can\n * never match a request. Anything outside the supported set (including\n * non-strings squeezed past the types) fails RC5003 at the http({...})\n * call site rather than registering a dead route.\n */\nfunction normalizeMethod(options: HttpServerOptions): HttpMethod {\n  const method = options.method ?? \"GET\";\n  const normalized =\n    typeof method === \"string\" ? method.toUpperCase() : undefined;\n  if (normalized === undefined || !HTTP_METHODS.has(normalized)) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `http() source: invalid method ${String(method)}. Allowed: ${[...HTTP_METHODS].map((m) => `\"${m}\"`).join(\", \")}.`,\n    });\n  }\n  return normalized as HttpMethod;\n}\n\n/**\n * Refuse a `respond` that is not callable. An options object built\n * programmatically (or by an untyped caller) would otherwise register a route\n * whose responder throws on the first request, which is a 500 per delivery\n * rather than a boot failure.\n */\nfunction assertRespondCallable(options: HttpServerOptions): void {\n  if (options.respond !== undefined && typeof options.respond !== \"function\") {\n    throw rcError(\"RC5003\", undefined, {\n      message: `http() source: respond must be a function, received ${typeof options.respond}. It is called once per request and returns the response to send, e.g. respond: () => ({ status: 202 }).`,\n    });\n  }\n}\n\n/**\n * Join a mount prefix and a mount-relative route path into the full request\n * pattern. `\"/\"` plus `\"/orders\"` is `/orders`; `\"/api\"` plus `\"/orders\"`\n * is `/api/orders`.\n */\nfunction joinMountPath(mountPath: string, routePath: string): string {\n  const prefix = mountPath === \"/\" ? \"\" : mountPath.replace(/\\/+$/, \"\");\n  const suffix = routePath.startsWith(\"/\") ? routePath : `/${routePath}`;\n  return `${prefix}${suffix}` || \"/\";\n}\n\n// Surface CraftPlugin in the public types of this module so consumers that\n// only import the source adapter still see the symbol (without re-exporting\n// the whole plugin entry point).\nexport type { CraftPlugin };\n\n/**\n * Source adapter exposed by `http({ path, method })` when used with\n * `.from(...)`. Registers itself in the http plugin's registry on\n * subscribe; deregisters on abort. The plugin owns the listener, the auth\n * middleware, and the dispatcher -- this adapter is just the entry that\n * tells the dispatcher \"this route claims this path/method\".\n */\nexport class HttpSourceAdapter implements Source<HttpRequestBody> {\n  readonly adapterId = \"routecraft.adapter.http.source\";\n\n  constructor(private readonly options: HttpServerOptions) {\n    // Validate the method unconditionally so an unsupported or non-string\n    // method fails here, not as a dead route at subscribe time.\n    normalizeMethod(options);\n    assertRespondCallable(options);\n\n    // Auth is mount-owned; the removed per-route auth modes fail loudly so\n    // an untyped caller migrating from 0.6 learns the new model instead of\n    // silently keeping a knob that no longer exists.\n    const legacyAuth = (options as { auth?: unknown }).auth;\n    if (legacyAuth !== undefined) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"http() source: per-route `auth` was removed. The mount decides authentication: put public routes on a mount with `auth: false`, walled routes on a mount with a validator, and use `.authorize()` on a route that needs identity on a public mount.\",\n      });\n    }\n\n    if (options.mount !== undefined && options.mount.length === 0) {\n      throw rcError(\"RC5003\", undefined, {\n        message: \"http() source: mount name must not be empty\",\n      });\n    }\n\n    if (options.signature !== undefined) {\n      // The body parser skips METHODS_WITHOUT_BODY entirely, which would\n      // silently skip verification too. A signature gate on a route that\n      // never has a body to sign is a configuration error; fail at the\n      // http({...}) call site, not at the first delivery. Checking the\n      // shared set (not a local copy) keeps this guard in lockstep with\n      // the parser's skip.\n      const method = normalizeMethod(this.options);\n      if (METHODS_WITHOUT_BODY.has(method)) {\n        throw rcError(\"RC5003\", undefined, {\n          message: `http() source: signature verification requires a body-bearing method, got \"${method}\". Webhook providers sign the request body; use POST, PUT, or PATCH.`,\n        });\n      }\n      const invalid = invalidSignatureOptionsReason(options.signature);\n      if (invalid !== null) {\n        throw rcError(\"RC5003\", undefined, {\n          message: `http() source: ${invalid}`,\n        });\n      }\n    }\n  }\n\n  async subscribe(sub: Subscription<HttpRequestBody>): Promise<void> {\n    const { context, meta } = sub;\n    const registered = context.getStore(HTTP_PLUGIN_REGISTERED);\n    if (registered !== true) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"http() source requires the http plugin. Add `servers: { default: { port: 8080 } }, http: {}` to defineConfig({...}).\",\n      });\n    }\n    const mounts: ReadonlyMap<string, HttpMountRuntime> | undefined =\n      context.getStore(HTTP_MOUNTS);\n    if (!mounts) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"http() source: mount table missing from context store. The http plugin failed to initialise.\",\n      });\n    }\n\n    // No silent fallback: an omitted `mount` resolves only to a mount\n    // literally named \"default\", so a forgotten mount name can never land a\n    // route on an unintended surface.\n    const mountName = this.options.mount ?? \"default\";\n    const mount = mounts.get(mountName);\n    if (!mount) {\n      const names = [...mounts.keys()].map((n) => `\"${n}\"`).join(\", \");\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          this.options.mount === undefined\n            ? `http() source: no mount named \"default\" exists; declare mount explicitly. Configured mounts: ${names}.`\n            : `http() source: mount \"${mountName}\" is not configured. Configured mounts: ${names}.`,\n      });\n    }\n    const registry = mount.registry;\n\n    const respond = this.options.respond;\n    if (respond !== undefined && meta?.bufferedConsumer === true) {\n      // A buffering consumer defers the message instead of starting the\n      // pipeline, so the route never counts it as in flight and a graceful\n      // shutdown drains past it: an answer already sent would outlive the\n      // delivery, and a sender that received one does not redeliver. Nothing\n      // here can tell whether this particular responder would have awaited\n      // the pipeline, because that is decided inside the function at request\n      // time, so the refusal covers every responder.\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"http() source: respond cannot be combined with a batching route. A batched message waits in the buffer instead of running, so it is not in-flight work and a graceful shutdown discards it, while the responder has already answered. Drop .batch() from this route, or drop respond and let the framework answer with the pipeline's result.\",\n      });\n    }\n\n    const method = normalizeMethod(this.options);\n    // Route paths are relative to the mount prefix; the matcher covers the\n    // full request path so dispatch and OpenAPI need no join at read time.\n    const matcher = compilePathMatcher(\n      joinMountPath(mount.path, this.options.path),\n    );\n    const routeId = meta?.routeId ?? `http:${method}:${matcher.pattern}`;\n    const entry: HttpRouteEntry = {\n      routeId,\n      method,\n      matcher,\n      requiresPrincipal: meta?.requiresPrincipal === true,\n      rawBody: this.options.rawBody ?? false,\n      signature: this.options.signature,\n      respond,\n      discovery: meta?.discovery,\n      handler: (body, headers) =>\n        sub.emit({\n          message: body as HttpRequestBody,\n          ...(headers ? { headers } : {}),\n        }),\n    };\n\n    if (registry.has(routeId)) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `http() source: duplicate route id \"${routeId}\"`,\n      });\n    }\n    for (const existing of registry.values()) {\n      if (\n        existing.method === method &&\n        existing.matcher.pattern === matcher.pattern\n      ) {\n        throw rcError(\"RC5003\", undefined, {\n          message: `http() source: duplicate route ${method} ${matcher.pattern} (already claimed by \"${existing.routeId}\")`,\n        });\n      }\n    }\n    registry.set(routeId, entry);\n\n    sub.ready();\n\n    // Hold the subscription open until the route is aborted. The dispatcher\n    // calls our entry's handler for each incoming request; no per-request\n    // work happens here.\n    await new Promise<void>((resolve) => {\n      if (sub.signal.aborted) {\n        registry.delete(routeId);\n        resolve();\n        return;\n      }\n      sub.signal.addEventListener(\n        \"abort\",\n        () => {\n          registry.delete(routeId);\n          resolve();\n        },\n        { once: true },\n      );\n    });\n  }\n}\n","import type { Enricher } from \"../../operations/enrich.ts\";\nimport type { Source } from \"../../operations/from\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag\";\nimport { rejectStaleOptions } from \"../../shared/stale-options.ts\";\nimport { HttpEnricherAdapter } from \"./enricher\";\nimport { HttpSourceAdapter } from \"./source\";\nimport type {\n  HttpClientOptions,\n  HttpRequestBody,\n  HttpResult,\n  HttpServerOptions,\n} from \"./types\";\n\n/**\n * Discriminator for the overloaded factory: a source uses `path` while the\n * destination uses `url`. Internal helper kept private so callers always go\n * through the typed overloads.\n */\nfunction isSourceOptions(\n  options: HttpServerOptions | HttpClientOptions<unknown>,\n): options is HttpServerOptions {\n  return (\n    typeof (options as HttpServerOptions).path === \"string\" &&\n    (options as HttpClientOptions<unknown>).url === undefined\n  );\n}\n\n/**\n * Create an HTTP source. Use with `.from(...)`. Requires `http: {...}` to be\n * configured on the context (typically via `defineConfig({ http: {...} })`)\n * so the plugin owns the port and the global auth check.\n *\n * @example\n * ```typescript\n * .from(http({ path: \"/orders/:id\", method: \"GET\" }))\n * .from(http({ path: \"/health\", method: \"GET\", auth: \"skip\" }))\n * ```\n *\n * @experimental\n */\nexport function http(options: HttpServerOptions): Source<HttpRequestBody>;\n/**\n * Create an HTTP client enricher (a pull-in). Use with `.enrich()`, `.to()`\n * (the result replaces the body), or `.tap()` (fire-and-forget). Supports\n * dynamic url, headers, query, and body from the exchange.\n *\n * The client shape is selected by key presence (`url`), and the operation\n * keyword enforces the category: `.from(http({ url }))` fails to compile\n * because the client has no `subscribe`.\n *\n * `responseBody: \"bytes\"` does NOT change this signature's result type. Name\n * the body yourself: `http<In, Uint8Array>({ url, responseBody: \"bytes\" })`.\n * An option value that selects the adapter's type is what Option Law 2\n * forbids, and the two ways of getting it here both fail: a bytes overload\n * with one type parameter is skipped by the two-argument form the examples\n * and templates use, which is then told its body is `Out` while the runtime\n * hands back bytes, and overloads narrow enough to refuse that also refuse\n * any options object whose mode is not a literal.\n *\n * @param options - method, url (string or (exchange) => string), optional headers, query, body, timeout, throwOnHttpError, maxBodySize, redirect, responseBody\n * @returns An Enricher whose fetch returns { status, headers, body, url }\n *\n * @example\n * ```typescript\n * .to(http({ url: 'https://api.example.com/ingest', method: 'POST', body: (ex) => ex.body }))\n * .enrich(http({ url: (ex) => `https://api.example.com/users/${ex.body.userId}` }), only((r) => r.body, 'user'))\n * .enrich(http({ url: (ex) => ex.body.mediaUrl, responseBody: 'bytes' }), only((r) => r.body, 'media'))\n * ```\n */\nexport function http<T = unknown, R = unknown>(\n  options: HttpClientOptions<T>,\n): Enricher<T, HttpResult<R>>;\nexport function http(\n  options: HttpServerOptions | HttpClientOptions<unknown>,\n): Source<HttpRequestBody> | Enricher<unknown, HttpResult<unknown>> {\n  rejectStaleOptions(options, \"http\");\n  if (isSourceOptions(options)) {\n    const adapter = new HttpSourceAdapter(options);\n    return tagAdapter(adapter, http, factoryArgs(options));\n  }\n  const adapter = new HttpEnricherAdapter<unknown, unknown>(options);\n  return tagAdapter(adapter, http, factoryArgs(options));\n}\n\n// Re-export adapter classes and types for the public API surface.\nexport { isRedirect, HTTP_REDIRECT_STATUSES } from \"./redirect\";\nexport { HttpEnricherAdapter } from \"./enricher\";\nexport { HttpSourceAdapter } from \"./source\";\nexport type {\n  HttpMethod,\n  HttpRedirectMode,\n  HttpRequestPayload,\n  HttpResponder,\n  HttpRespondContext,\n  HttpRespondRequest,\n  HttpResponseBodyMode,\n  HttpResponseDescriptor,\n  QueryParams,\n  HttpClientOptions,\n  HttpResult,\n  HttpServerOptions,\n  HttpPluginOptions,\n  HttpRequestBody,\n  HttpResponseHint,\n  HttpAuth,\n  HttpConfig,\n  ApiKeyAuthOptions,\n  HttpBuiltinsOptions,\n  HttpBuiltinOptions,\n  HttpOpenApiBuiltinOptions,\n  HttpOpenApiInfo,\n  HttpWebhookSignatureOptions,\n  HttpWebhookSignatureScheme,\n} from \"./types\";\n","import type { Exchange } from \"../../exchange.ts\";\n\nexport interface FileOptions {\n  /**\n   * File path string or function that returns the path.\n   * The function form receives the exchange (send/fetch roles only; the\n   * source role needs a static string because no exchange exists yet).\n   */\n  path: string | ((exchange: Exchange) => string);\n  /**\n   * Text encoding. Default: 'utf-8'\n   */\n  encoding?: BufferEncoding;\n  /**\n   * Create parent directories if they don't exist (send role only).\n   * Default: false\n   */\n  createDirs?: boolean;\n  /**\n   * Send role behavior: append to the file instead of overwriting it.\n   * Mutually exclusive with `delete`. Default: false (overwrite)\n   */\n  append?: boolean;\n  /**\n   * Send role behavior: delete the file instead of writing it. Idempotent:\n   * an already-absent path is a no-op. The body is unchanged. Mutually\n   * exclusive with `append`. Default: false\n   */\n  delete?: boolean;\n  /**\n   * When true, the source emits one exchange per line instead of the entire\n   * file content. Source role only; the send/fetch roles are identical under\n   * chunked. Each chunked exchange includes FILE_LINE and FILE_PATH headers.\n   * Default: false\n   */\n  chunked?: boolean;\n}\n\n/**\n * Header keys the file source sets on chunked-mode exchanges. Keys live\n * under the reserved `routecraft.file.*` namespace; the value types are\n * merged into `RoutecraftHeaders` below.\n */\nexport const FileHeaders = {\n  /** The 1-based line number when reading a file in chunked mode */\n  LINE: \"routecraft.file.line\",\n  /** The file path when reading a file in chunked mode */\n  PATH: \"routecraft.file.path\",\n} as const satisfies Record<string, `routecraft.file.${string}`>;\n\ndeclare module \"@routecraft/routecraft\" {\n  interface RoutecraftHeaders {\n    /** The 1-based line number when reading a file in chunked mode */\n    [FileHeaders.LINE]?: number;\n    /** The file path when reading a file in chunked mode */\n    [FileHeaders.PATH]?: string;\n  }\n}\n","import { createReadStream } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\n\n/**\n * Reads a file line by line, invoking a callback for each line.\n * Supports abort via AbortSignal for cooperative cancellation.\n *\n * @internal Not exported from the package public API.\n *\n * @param filePath - Absolute or relative path to the file\n * @param encoding - Text encoding (e.g. 'utf-8')\n * @param signal - AbortSignal to cancel reading mid-stream\n * @param callback - Async function called for each line with the line content and 1-based line number\n */\nexport async function forEachLine(\n  filePath: string,\n  encoding: BufferEncoding,\n  signal: AbortSignal,\n  callback: (line: string, lineNumber: number) => Promise<void>,\n): Promise<void> {\n  if (signal.aborted) return;\n\n  const stream = createReadStream(filePath, { encoding });\n  const rl = createInterface({ input: stream, crlfDelay: Infinity });\n\n  let lineNumber = 0;\n\n  const onAbort = () => {\n    rl.close();\n    stream.destroy();\n  };\n  signal.addEventListener(\"abort\", onAbort, { once: true });\n\n  try {\n    for await (const line of rl) {\n      if (signal.aborted) break;\n      lineNumber++;\n      await callback(line, lineNumber);\n      if (signal.aborted) break;\n    }\n  } finally {\n    signal.removeEventListener(\"abort\", onAbort);\n    rl.close();\n    stream.destroy();\n  }\n}\n","/**\n * Shared filesystem error mapping for adapters that read files or scan\n * directories. Maps the common errno codes to clear, adapter-prefixed\n * messages so `file`, `csv`, `jsonl`, and `directory` report the same\n * underlying failure the same way.\n *\n * @internal Not exported from the package public API.\n */\n\n/** The filesystem noun the error message speaks about. */\ntype FsNoun = \"file\" | \"directory\";\n\n/**\n * Shared errno-to-message mapping. ENOTDIR is only meaningful for\n * directory targets (a path component that is not a directory); file\n * adapters keep their historical messages for that code via the generic\n * fallback.\n */\nfunction throwFsError(\n  adapter: string,\n  noun: FsNoun,\n  target: string,\n  err: unknown,\n): never {\n  const code = (err as NodeJS.ErrnoException).code;\n  if (code === \"ENOENT\") {\n    throw new Error(`${adapter} adapter: ${noun} not found: ${target}`);\n  }\n  if (noun === \"directory\" && code === \"ENOTDIR\") {\n    throw new Error(`${adapter} adapter: not a directory: ${target}`);\n  }\n  if (code === \"EACCES\") {\n    throw new Error(\n      `${adapter} adapter: permission denied reading ${noun}: ${target}`,\n    );\n  }\n  const message = err instanceof Error ? err.message : String(err);\n  throw new Error(`${adapter} adapter: failed to read ${noun}: ${message}`);\n}\n\n/**\n * Throws a standardized file-related error for an adapter.\n * Handles ENOENT, EACCES, and generic errors.\n *\n * @param adapter - Adapter name for the error prefix (e.g. 'file', 'csv', 'jsonl')\n * @param filePath - The file path that caused the error\n * @param err - The original error\n */\nexport function throwFileError(\n  adapter: string,\n  filePath: string,\n  err: unknown,\n): never {\n  throwFsError(adapter, \"file\", filePath, err);\n}\n\n/**\n * Throws a standardized directory-related error for an adapter.\n * Handles ENOENT, ENOTDIR, EACCES, and generic errors.\n *\n * @param adapter - Adapter name for the error prefix (e.g. 'directory')\n * @param dir - The directory path that caused the error\n * @param err - The original error\n */\nexport function throwDirectoryError(\n  adapter: string,\n  dir: string,\n  err: unknown,\n): never {\n  throwFsError(adapter, \"directory\", dir, err);\n}\n","import { rcError } from \"../../error.ts\";\n\n/**\n * Enforces the mutually-exclusive send-behavior law for file-role adapters\n * (`append: true` and `delete: true` cannot be combined). Called from the\n * destination adapter constructors; the factories construct their\n * destination eagerly, so the error still surfaces at factory-call time\n * while the factory itself stays \"construction only\" per\n * `.standards/adapter-architecture.md`.\n *\n * @internal\n */\nexport function assertExclusiveSendBehavior(\n  adapter: string,\n  options: { append?: boolean; delete?: boolean },\n): void {\n  if (options.append && options.delete) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `${adapter} adapter: \\`append\\` and \\`delete\\` are mutually exclusive send behaviors`,\n      suggestion: \"Pass at most one of `append: true` / `delete: true`\",\n    });\n  }\n}\n\n/**\n * The single error for using a dynamic (function) `path` in the source\n * role, shared by every file-family adapter so the message cannot drift.\n *\n * Coded like every other adapter-role rejection so callers can classify it\n * programmatically, even though it is thrown lazily from `subscribe` rather\n * than at construction (a dynamic path is legal for send and fetch, so the\n * factory cannot reject it up front).\n *\n * @internal\n */\nexport function staticSourcePathError(adapter: string): Error {\n  return rcError(\"RC5003\", undefined, {\n    message: `${adapter} adapter: the source role requires a static string path (dynamic paths resolve against an exchange, which does not exist at subscribe time)`,\n    suggestion:\n      \"Pass a string `path` to `.from()`, or keep the function path and use the send / fetch roles (`.to()` / `.enrich()`)\",\n  });\n}\n\n/**\n * Decides whether a `path` option selects the file roles, for the factories\n * whose call shapes are discriminated by its presence (`json`, `html`: a\n * transformer without a path, file roles with one).\n *\n * Presence means \"the key was SUPPLIED\", never \"the key holds something\n * truthy\". Two shapes are supplied-but-empty and both are refused:\n *\n * - `path: \"\"`, from a template that resolved to nothing.\n * - `path: undefined`, from options built programmatically\n *   (`json({ ...cfg })` where `cfg.path` is `string | undefined`).\n *\n * The second is the absence-axis twin of the widened-boolean hazard that\n * bans `chunked: someBoolean`: the call means \"file adapter, path from\n * config\", and silently demoting it to a transformer would produce an\n * adapter that ignores every file option alongside it and fails far from the\n * cause. Only an OMITTED key selects the transformer role.\n *\n * @param adapter - Factory name, for the error message\n * @param options - Options object as supplied, tested for the key itself\n * @returns `true` when the file roles apply, `false` for the transformer role\n * @internal\n */\nexport function selectsFileRole(adapter: string, options: object): boolean {\n  // Own property, not `in`: an inherited `path` (a class instance, an object\n  // built with Object.create) was not supplied by this caller and must not\n  // reclassify the adapter.\n  if (!Object.prototype.hasOwnProperty.call(options, \"path\")) return false;\n  const path = (options as { path?: unknown }).path;\n  if (path === undefined) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `${adapter} adapter: \\`path\\` was supplied but is undefined`,\n      suggestion: `Omit \\`path\\` entirely for the transformer role, or resolve it before the call (e.g. cfg.path ?? throwIfMissing()) to use the file roles`,\n    });\n  }\n  if (typeof path === \"string\" && path.length === 0) {\n    throw rcError(\"RC5003\", undefined, {\n      message: `${adapter} adapter: \\`path\\` is an empty string`,\n      suggestion: `Pass a real file path to use the file roles, or omit \\`path\\` entirely for the transformer role`,\n    });\n  }\n  return true;\n}\n","import * as fsp from \"node:fs/promises\";\nimport type { Source, CallableSource } from \"../../operations/from.ts\";\nimport type { FileOptions } from \"./types.ts\";\nimport type { ExchangeHeaders } from \"../../exchange.ts\";\nimport { FileHeaders } from \"./types.ts\";\nimport { forEachLine } from \"../shared/line-reader.ts\";\nimport { throwFileError } from \"../shared/fs-errors.ts\";\nimport { staticSourcePathError } from \"../shared/file-role-guards.ts\";\n\n/**\n * FileSourceAdapter implements the Source interface for reading files.\n * Reads the file once and emits its content as a string.\n * When chunked is true, emits one exchange per line.\n */\nexport class FileSourceAdapter implements Source<string> {\n  readonly adapterId = \"routecraft.adapter.file\";\n\n  constructor(private readonly options: FileOptions) {}\n\n  /**\n   * Source implementation: subscribe to file content.\n   * Reads the file once (or line-by-line when chunked).\n   */\n  subscribe: CallableSource<string> = async (sub) => {\n    // Check if already aborted\n    if (sub.signal.aborted) return;\n\n    const {\n      path: filePath,\n      encoding = \"utf-8\",\n      chunked = false,\n    } = this.options;\n\n    if (typeof filePath !== \"string\") {\n      throw staticSourcePathError(\"file\");\n    }\n\n    // Ready means \"wired and able to produce\", so signal before reading\n    // rather than after the file is fully emitted.\n    sub.ready();\n\n    if (chunked) {\n      try {\n        await forEachLine(\n          filePath,\n          encoding,\n          sub.signal,\n          async (line, lineNumber) => {\n            const headers: ExchangeHeaders = {\n              [FileHeaders.LINE]: lineNumber,\n              [FileHeaders.PATH]: filePath,\n            } as ExchangeHeaders;\n            try {\n              await sub.emit({ message: line, headers });\n            } catch (err) {\n              // Pipeline failure for one line, not a file error: the route\n              // boundary already emitted route:exchange:failed; keep reading\n              // (matching json/jsonl/csv chunked semantics).\n              if (sub.signal.aborted) return;\n              sub.context.logger.debug(\n                { err, path: filePath, line: lineNumber, adapter: \"file\" },\n                \"file adapter: pipeline failed for line; continuing\",\n              );\n            }\n          },\n        );\n      } catch (err) {\n        if (sub.signal.aborted) return;\n        throwFileError(\"file\", filePath, err);\n      }\n    } else {\n      const content = await fsp\n        .readFile(filePath, { encoding })\n        .catch((err) => throwFileError(\"file\", filePath, err));\n\n      // Check if aborted before emitting\n      if (sub.signal.aborted) return;\n\n      // Emit the content\n      await sub.emit({ message: content });\n    }\n  };\n}\n","import * as fsp from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport type { Destination, CallableDestination } from \"../../operations/to.ts\";\nimport type { FileOptions } from \"./types.ts\";\nimport { assertExclusiveSendBehavior } from \"../shared/file-role-guards.ts\";\n\n/**\n * FileDestinationAdapter implements the Destination (send) role for file I/O.\n *\n * `send` is strictly void: it writes the exchange body to the resolved path\n * (overwrite by default, `append: true` to append) or removes the file\n * (`delete: true`, idempotent). Reading lives on the fetch role\n * (FileEnricherAdapter); the source role reads at subscribe time.\n */\nexport class FileDestinationAdapter implements Destination<unknown> {\n  readonly adapterId = \"routecraft.adapter.file\";\n\n  constructor(private readonly options: FileOptions) {\n    assertExclusiveSendBehavior(\"file\", options);\n  }\n\n  /**\n   * Send implementation. Deletes (delete: true) or writes/appends the\n   * resolved path. Static and dynamic paths are supported.\n   */\n  send: CallableDestination<unknown> = async (exchange) => {\n    const {\n      path: filePath,\n      encoding = \"utf-8\",\n      createDirs = false,\n      append = false,\n      delete: remove = false,\n    } = this.options;\n\n    // Resolve path (static or dynamic)\n    const resolvedPath =\n      typeof filePath === \"function\" ? filePath(exchange) : filePath;\n\n    // Delete behavior: remove the file. Idempotent (force) so an\n    // already-absent path succeeds; the body is unchanged.\n    if (remove) {\n      try {\n        await fsp.rm(resolvedPath, { force: true });\n      } catch (err) {\n        const message = err instanceof Error ? err.message : String(err);\n        if ((err as NodeJS.ErrnoException).code === \"EACCES\") {\n          throw new Error(\n            `file adapter: permission denied deleting file: ${resolvedPath}`,\n          );\n        }\n        throw new Error(`file adapter: failed to delete file: ${message}`);\n      }\n      return;\n    }\n\n    // Get content from exchange body\n    let content: string;\n    if (typeof exchange.body === \"string\") {\n      content = exchange.body;\n    } else {\n      // Convert to string if not already\n      content = JSON.stringify(exchange.body, null, 2);\n    }\n\n    // Create parent directories if requested\n    if (createDirs) {\n      const dir = path.dirname(resolvedPath);\n      try {\n        await fsp.mkdir(dir, { recursive: true });\n      } catch (err) {\n        const message = err instanceof Error ? err.message : String(err);\n        throw new Error(\n          `file adapter: failed to create directories for ${resolvedPath}: ${message}`,\n        );\n      }\n    }\n\n    // Write or append to file\n    try {\n      if (append) {\n        await fsp.appendFile(resolvedPath, content, { encoding });\n      } else {\n        await fsp.writeFile(resolvedPath, content, { encoding });\n      }\n    } catch (err) {\n      const message = err instanceof Error ? err.message : String(err);\n      if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n        throw new Error(\n          `file adapter: directory not found for file: ${resolvedPath} (use createDirs: true to create parent directories)`,\n        );\n      }\n      if ((err as NodeJS.ErrnoException).code === \"EACCES\") {\n        throw new Error(\n          `file adapter: permission denied writing file: ${resolvedPath}`,\n        );\n      }\n      throw new Error(`file adapter: failed to write file: ${message}`);\n    }\n  };\n}\n","import * as fsp from \"node:fs/promises\";\nimport type { Enricher, CallableEnricher } from \"../../operations/enrich.ts\";\nimport type { FileOptions } from \"./types.ts\";\nimport { throwFileError } from \"../shared/fs-errors.ts\";\n\n/**\n * FileEnricherAdapter implements the Enricher (fetch) role for file I/O:\n * `fetch` reads the resolved path and returns its content as a string, so\n * `.enrich(file({ path }))` pulls a file into the route mid-flow. Dynamic\n * (function) paths are supported because the exchange is available when the\n * read runs.\n */\nexport class FileEnricherAdapter implements Enricher<unknown, string> {\n  readonly adapterId = \"routecraft.adapter.file\";\n\n  constructor(private readonly options: FileOptions) {}\n\n  /** Fetch implementation: read the resolved path and return the content. */\n  fetch: CallableEnricher<unknown, string> = async (exchange) => {\n    const { path: filePath, encoding = \"utf-8\" } = this.options;\n    const resolvedPath =\n      typeof filePath === \"function\" ? filePath(exchange) : filePath;\n    return fsp\n      .readFile(resolvedPath, { encoding })\n      .catch((err) => throwFileError(\"file\", resolvedPath, err));\n  };\n}\n","import type { Source } from \"../../operations/from.ts\";\nimport type { Destination } from \"../../operations/to.ts\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\nimport type { FileOptions } from \"./types.ts\";\nimport { FileSourceAdapter } from \"./source.ts\";\nimport { FileDestinationAdapter } from \"./destination.ts\";\nimport { FileEnricherAdapter } from \"./enricher.ts\";\n\n/**\n * Combined file adapter type: all three roles on one honest type. The\n * operation keyword selects the role (`.from()` subscribes, `.to()` sends,\n * `.enrich()` fetches).\n */\nexport type FileAdapter = Source<string> &\n  Destination<unknown> &\n  Enricher<unknown, string> & { readonly adapterId: string };\n\n/**\n * Creates a file adapter for plain text files. One factory, one type; the\n * POSITION in the route selects the role:\n *\n * - **`.from(file({ path }))`** reads the file and emits its content\n *   (`chunked: true` emits one exchange per line with FILE_LINE / FILE_PATH\n *   headers). The source role needs a static string path.\n * - **`.to(file({ path }))`** writes the exchange body to the file\n *   (overwrite; `append: true` appends; `delete: true` removes the file).\n *   The body flows through unchanged.\n * - **`.enrich(file({ path }))`** reads the file mid-route and the content\n *   replaces the body (pass an aggregator such as `only()` to merge\n *   instead). Dynamic (function) paths resolve against the exchange.\n *\n * @param options - File path, encoding, createDirs, append/delete, chunked\n * @returns The combined Source + Destination + Enricher adapter\n *\n * @example\n * ```typescript\n * // Read file as source\n * .from(file({ path: './input.txt' }))\n *\n * // Read one exchange per line\n * .from(file({ path: './input.txt', chunked: true }))\n *\n * // Write to file\n * .to(file({ path: './output.txt' }))\n *\n * // Append to log\n * .to(file({ path: './log.txt', append: true }))\n *\n * // Pull a file into the body mid-route, alongside the existing data\n * .enrich(file({ path: './config.txt' }), only((s: string) => s, 'config'))\n *\n * // Dynamic path with directory creation\n * .to(file({\n *   path: (ex) => `./data/${ex.body.date}.txt`,\n *   createDirs: true\n * }))\n * ```\n */\nexport function file(options: FileOptions): FileAdapter {\n  const source = new FileSourceAdapter(options);\n  const destination = new FileDestinationAdapter(options);\n  const enricher = new FileEnricherAdapter(options);\n  return tagAdapter(\n    {\n      adapterId: \"routecraft.adapter.file\",\n      subscribe: source.subscribe,\n      send: destination.send,\n      fetch: enricher.fetch,\n    },\n    file,\n    factoryArgs(options),\n  );\n}\n\n// Re-export types for public API\nexport type { FileOptions } from \"./types.ts\";\nexport { FileHeaders } from \"./types.ts\";\n\n// Re-export classes for internal use (e.g., by html and csv adapters)\nexport { FileSourceAdapter } from \"./source.ts\";\nexport { FileDestinationAdapter } from \"./destination.ts\";\nexport { FileEnricherAdapter } from \"./enricher.ts\";\n","import * as fsp from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport type { Dirent, Stats } from \"node:fs\";\nimport type { CraftContext } from \"../../context.ts\";\nimport type { DirectoryEntry, DirectoryOptions } from \"./types.ts\";\nimport { throwDirectoryError } from \"../shared/fs-errors.ts\";\n\n/**\n * Max concurrent `stat` calls while resolving directory entries. Bounds the\n * open-handle count so a huge recursive tree cannot exhaust file descriptors\n * (EMFILE), while still overlapping the syscall latency that dominates a scan.\n */\nconst STAT_CONCURRENCY = 32;\n\n/**\n * IO hooks for {@link scanDirectory}. Both are optional so the scan works\n * from a source subscription (subscription signal + context logger) and from\n * an enricher fetch (step signal, exchange-resolved logger) alike.\n *\n * @internal\n */\nexport interface DirectoryScanIo {\n  /**\n   * When it aborts, workers stop claiming entries and the partial result is\n   * returned. Callers that must not act on a partial listing check the\n   * signal after the scan resolves (the enricher throws; the source simply\n   * stops emitting).\n   */\n  signal?: AbortSignal | undefined;\n  /** Logger for per-entry skip diagnostics; skips are silent when omitted. */\n  logger?: CraftContext[\"logger\"] | undefined;\n}\n\n/**\n * Scan a directory and return its entries, sorted deterministically. This is\n * the single scan implementation shared by the directory source (`.from()`)\n * and the directory enricher (`.enrich()` / `.to()`), so `recursive`,\n * `includeDirs`, symlink handling, and ordering behave identically in every\n * role by construction rather than by discipline.\n *\n * Entries are sorted by their relative path with separators normalized to\n * `/`, so emission order (chunked source), array order (non-chunked source),\n * and the enricher's returned array are deterministic and identical across\n * platforms (raw `readdir` order, the concurrent stat phase below, and a raw\n * sort on OS-separator paths are not).\n *\n * Symlinks are followed (`stat`): a symlink to a directory is treated as a\n * directory (skipped unless `includeDirs`), a symlink to a file is listed\n * with the target's metadata, and a broken symlink is skipped.\n *\n * A missing or unreadable directory throws via {@link throwDirectoryError}.\n *\n * @internal\n */\nexport async function scanDirectory(\n  dir: string,\n  options: Pick<DirectoryOptions, \"recursive\" | \"includeDirs\">,\n  io: DirectoryScanIo = {},\n): Promise<DirectoryEntry[]> {\n  const { recursive = false, includeDirs = false } = options;\n  const { signal, logger } = io;\n\n  let dirents: Dirent[];\n  try {\n    dirents = await fsp.readdir(dir, { withFileTypes: true, recursive });\n  } catch (err) {\n    throwDirectoryError(\"directory\", dir, err);\n  }\n\n  // Resolve each entry's stats with bounded concurrency. The results feed an\n  // in-memory array that is not visible until the whole scan completes, so\n  // there is no backpressure reason to serialise these syscalls, and a large\n  // recursive scan is dominated by stat latency. Directory-ness is decided\n  // from the followed stats, not the Dirent, so a symlink to a directory is\n  // treated consistently for both the includeDirs filter and the returned\n  // isDirectory field.\n  const entries: DirectoryEntry[] = [];\n  let cursor = 0;\n  const resolveEntries = async (): Promise<void> => {\n    while (!signal?.aborted) {\n      // `cursor++` is a single synchronous step (no await between read and\n      // increment), so workers never claim the same index.\n      const index = cursor++;\n      if (index >= dirents.length) return;\n      const dirent = dirents[index];\n\n      // Skip plain directories before paying for a stat. Dirent type\n      // checks reflect lstat semantics, so isDirectory() is false for a\n      // symlink pointing at a directory; those fall through to the\n      // followed stat below and are filtered by the post-stat check.\n      if (!includeDirs && dirent.isDirectory()) continue;\n\n      // Node always sets parentPath on Dirents (>= 22); fall back to the\n      // scanned dir for the non-recursive case to be safe.\n      const parent = dirent.parentPath ?? dir;\n      const fullPath = path.join(parent, dirent.name);\n\n      let stats: Stats;\n      try {\n        stats = await fsp.stat(fullPath);\n      } catch (err) {\n        // ENOENT means the entry vanished between listing and statting,\n        // or is a broken symlink: expected churn, skip at debug. Any\n        // other failure (EACCES, EMFILE, ELOOP) also skips the entry so\n        // one bad node cannot fail the whole scan, but warns, because\n        // the listing is now silently incomplete otherwise.\n        const code = (err as NodeJS.ErrnoException).code;\n        if (code === \"ENOENT\") {\n          logger?.debug(\n            { err, path: fullPath, adapter: \"directory\" },\n            \"directory adapter: entry vanished or broken symlink; skipping\",\n          );\n        } else {\n          logger?.warn(\n            { err, path: fullPath, adapter: \"directory\" },\n            \"directory adapter: could not stat entry; listing is incomplete\",\n          );\n        }\n        continue;\n      }\n\n      const isDirectory = stats.isDirectory();\n      if (isDirectory && !includeDirs) continue;\n\n      entries.push({\n        path: fullPath,\n        name: dirent.name,\n        dir: parent,\n        ext: path.extname(dirent.name).toLowerCase(),\n        relativePath: path.relative(dir, fullPath),\n        size: stats.size,\n        modifiedAt: stats.mtime,\n        createdAt: stats.birthtime,\n        isDirectory,\n      });\n    }\n  };\n  await Promise.all(\n    Array.from({ length: Math.min(STAT_CONCURRENCY, dirents.length) }, () =>\n      resolveEntries(),\n    ),\n  );\n\n  // Sort on a separator-normalized key so the order is identical across\n  // platforms: a raw sort on relativePath would diverge on Windows, where\n  // the backslash separator (0x5C) sorts after characters that `/` (0x2F)\n  // sorts before (digits, uppercase letters).\n  const sortKey = (e: DirectoryEntry): string =>\n    path.sep === \"/\"\n      ? e.relativePath\n      : e.relativePath.split(path.sep).join(\"/\");\n  entries.sort((a, b) => {\n    const ka = sortKey(a);\n    const kb = sortKey(b);\n    return ka < kb ? -1 : ka > kb ? 1 : 0;\n  });\n\n  return entries;\n}\n","import type { Source, CallableSource } from \"../../operations/from.ts\";\nimport type { DirectoryEntry, DirectoryOptions } from \"./types.ts\";\nimport { staticSourcePathError } from \"../shared/file-role-guards.ts\";\nimport { scanDirectory } from \"./scan.ts\";\n\n/**\n * DirectorySourceAdapter implements the Source interface for scanning a\n * directory. It lists the directory once and emits the result either as a\n * single exchange carrying the full {@link DirectoryEntry}`[]` listing (default)\n * or, when `chunked`, one exchange per entry.\n *\n * Filtering is intentionally not built in: list the entries and let the route\n * decide. In chunked mode, filter on the body (`.filter((ex) => ex.body.ext\n * === \".json\")`), then read content with the file adapter (`.enrich(file({\n * path: (ex) => ex.body.path }))`). This keeps \"find files\" and \"decide which\n * ones\" as separate, composable steps.\n *\n * The scan itself (entry resolution, symlink handling, deterministic sort\n * order) lives in {@link scanDirectory}, shared with the enricher role so\n * every role lists the same tree identically.\n */\nexport class DirectorySourceAdapter implements Source<\n  DirectoryEntry | DirectoryEntry[]\n> {\n  readonly adapterId = \"routecraft.adapter.directory\";\n\n  constructor(private readonly options: DirectoryOptions) {}\n\n  /**\n   * Source implementation: scan the directory and emit the listing. Reads the\n   * directory once (this is a finite source). When `chunked`, emits one\n   * exchange per entry; otherwise a single exchange with the `DirectoryEntry[]`.\n   */\n  subscribe: CallableSource<DirectoryEntry | DirectoryEntry[]> = async (\n    sub,\n  ) => {\n    if (sub.signal.aborted) return;\n\n    const {\n      path: dir,\n      recursive = false,\n      includeDirs = false,\n      chunked = false,\n    } = this.options;\n\n    if (typeof dir !== \"string\") {\n      throw staticSourcePathError(\"directory\");\n    }\n\n    // Ready means \"wired and able to produce\", so signal before scanning\n    // rather than after every entry has been emitted.\n    sub.ready();\n\n    const entries = await scanDirectory(\n      dir,\n      { recursive, includeDirs },\n      { signal: sub.signal, logger: sub.context.logger },\n    );\n    if (sub.signal.aborted) return;\n\n    if (chunked) {\n      for (const entry of entries) {\n        if (sub.signal.aborted) return;\n        try {\n          await sub.emit({ message: entry });\n        } catch {\n          // Pipeline failure for one entry, not a scan error: the route\n          // boundary already emitted route:exchange:failed; keep emitting the rest\n          // (matching the file/csv/jsonl chunked semantics).\n          if (sub.signal.aborted) return;\n          sub.context.logger.debug(\n            { path: entry.path, adapter: \"directory\" },\n            \"directory adapter: pipeline failed for entry; continuing\",\n          );\n        }\n      }\n    } else if (!sub.signal.aborted) {\n      // Default: a single exchange carrying the whole listing, mirroring the\n      // non-chunked csv/jsonl shape. An empty directory still emits one\n      // exchange with an empty array.\n      try {\n        await sub.emit({ message: entries });\n      } catch {\n        // Exchange error already logged by the route pipeline; mirror the\n        // chunked branch's debug line so the adapter is not silent when\n        // its only exchange fails.\n        sub.context.logger.debug(\n          { path: dir, adapter: \"directory\" },\n          \"directory adapter: pipeline failed for listing exchange\",\n        );\n      }\n    }\n\n    // Finite source: signal completion so a single-source route can finish.\n    sub.complete();\n  };\n}\n","import type { Enricher, CallableEnricher } from \"../../operations/enrich.ts\";\nimport type { DirectoryEntry, DirectoryOptions } from \"./types.ts\";\nimport { getExchangeContext } from \"../../exchange.ts\";\nimport { rcError } from \"../../error.ts\";\nimport { scanDirectory } from \"./scan.ts\";\n\n/**\n * DirectoryEnricherAdapter implements the Enricher (fetch) role for\n * directories: `fetch` scans the resolved path and returns the sorted\n * {@link DirectoryEntry}`[]` listing, so `.enrich(directory({ path }))` pulls\n * a listing into the route mid-flow (and `.to(directory({ path }))` replaces\n * the body with it, since directory has no `send`). A listing is a read, so\n * it belongs in the pull-in role alongside a file read.\n *\n * This is what makes the adapter usable inside a `direct()` capability, where\n * there is no `.from()` slot to hang the listing on. Dynamic (function) paths\n * are supported because the exchange is available when the scan runs; the\n * source role keeps its static-string requirement.\n *\n * `recursive`, `includeDirs`, symlink handling, and the deterministic sort\n * order are identical to the source: both delegate to {@link scanDirectory}.\n */\nexport class DirectoryEnricherAdapter implements Enricher<\n  unknown,\n  DirectoryEntry[]\n> {\n  readonly adapterId = \"routecraft.adapter.directory\";\n\n  constructor(private readonly options: DirectoryOptions) {}\n\n  /**\n   * Fetch implementation: scan the resolved path and return the sorted\n   * listing. A missing or unreadable directory throws (`directory not\n   * found`, `not a directory`, `permission denied`), matching the source's\n   * error mapping.\n   */\n  fetch: CallableEnricher<unknown, DirectoryEntry[]> = async (\n    exchange,\n    ctx,\n  ) => {\n    const { path: dir, recursive = false, includeDirs = false } = this.options;\n\n    // Resolve the path (static or dynamic).\n    const resolvedDir = typeof dir === \"function\" ? dir(exchange) : dir;\n\n    const entries = await scanDirectory(\n      resolvedDir,\n      { recursive, includeDirs },\n      {\n        // An enclosing .timeout() abort stops the stat workers early.\n        signal: ctx?.signal,\n        logger: getExchangeContext(exchange)?.logger,\n      },\n    );\n\n    // An aborted scan returns whatever it had collected, which is a partial\n    // listing indistinguishable from a complete one. That is fine for the\n    // source (abort just stops emission) but not here: the fetched value\n    // becomes the route's body. Throw instead, so a truncated listing can\n    // never be mistaken for the real contents of the directory. Correctness\n    // must not depend on the caller discarding the value.\n    if (ctx?.signal?.aborted) {\n      // RC5011 is what the timeout wrapper throws when its own deadline\n      // fires, so classifying this the same way keeps `.error()` handlers\n      // and retry policy treating a cut-short listing as the timeout it is,\n      // rather than as an opaque adapter failure.\n      throw rcError(\"RC5011\", undefined, {\n        message: `directory adapter: listing aborted before completion: ${resolvedDir}`,\n        suggestion:\n          \"Increase the enclosing .timeout() so the scan can finish, or narrow the scan (drop recursive, or point at a smaller directory)\",\n      });\n    }\n\n    return entries;\n  };\n}\n","import type { Source } from \"../../operations/from.ts\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\nimport type { DirectoryEntry, DirectoryOptions } from \"./types.ts\";\nimport { DirectorySourceAdapter } from \"./source.ts\";\nimport { DirectoryEnricherAdapter } from \"./enricher.ts\";\n\n/**\n * Directory adapter type: source and enricher on one honest type. The\n * operation keyword selects the role (`.from()` subscribes and emits the\n * listing, `.enrich()` fetches it mid-route). There is no `send`: a listing\n * is a read, so `.to(directory({ path }))` resolves to the fetch and the\n * listing replaces the body.\n */\nexport type DirectoryAdapter = Source<DirectoryEntry[]> &\n  Enricher<unknown, DirectoryEntry[]> & { readonly adapterId: string };\n\n/**\n * Directory adapter type in chunked mode: the source emits one\n * {@link DirectoryEntry} per exchange. The enricher role is unaffected by\n * `chunked` (a fetch produces one value) and still returns the full listing.\n */\nexport type DirectoryChunkedAdapter = Source<DirectoryEntry> &\n  Enricher<unknown, DirectoryEntry[]> & { readonly adapterId: string };\n\n/**\n * Creates a directory adapter in chunked mode: the source emits one exchange\n * per entry, each body a {@link DirectoryEntry}. Filter by metadata or name\n * with `.filter()`, then read content with the file adapter. Chunked is a\n * source-only emission shape, so the path must be a static string.\n *\n * @param options - Directory options with `chunked: true`\n * @returns A Source emitting one {@link DirectoryEntry} per entry (plus the\n *   unchanged enricher role)\n *\n * @example\n * ```typescript\n * // Read the content of every .json file in a directory\n * craft()\n *   .from(directory({ path: \"./inbox\", chunked: true }))\n *   .filter((ex) => ex.body.ext === \".json\")\n *   .enrich(\n *     file({ path: (ex) => ex.body.path }),\n *     only((content: string) => content, \"content\"),\n *   )\n *   .to(log());\n * ```\n */\nexport function directory(\n  options: Omit<DirectoryOptions, \"path\"> & { path: string; chunked: true },\n): DirectoryChunkedAdapter;\n/**\n * Creates a directory adapter that scans a directory and produces the full\n * {@link DirectoryEntry}`[]` listing (sorted by relative path). One factory,\n * one type; the POSITION in the route selects the role:\n *\n * - **`.from(directory({ path }))`** emits a single exchange whose body is the\n *   listing, mirroring the non-chunked `csv` / `jsonl` adapters; pass\n *   `chunked: true` to emit one exchange per entry instead. The source role\n *   needs a static string path.\n * - **`.enrich(directory({ path }))`** scans the directory mid-route and the\n *   listing replaces the body (pass an aggregator such as `only()` to merge\n *   instead). Dynamic (function) paths resolve against the exchange.\n * - **`.to(directory({ path }))`** has no `send` to prefer, so it resolves to\n *   the same fetch and the listing becomes the body. This is what makes the\n *   adapter usable inside a `direct()` capability.\n *\n * Filtering is not built in by design: list the entries, then narrow with the\n * normal operations (`.filter()` per-entry in chunked mode, or `.split()` /\n * `.transform()` on the array), and read content with the file adapter. This\n * keeps \"find the files\" and \"decide which ones\" composable.\n *\n * @param options - Directory path plus `recursive`, `includeDirs`, `chunked`\n * @returns The combined Source + Enricher adapter\n *\n * @example\n * ```typescript\n * // Get the whole listing as one body, then act on the collection\n * craft()\n *   .from(directory({ path: \"./inbox\" }))\n *   .transform((entries) => entries.filter((e) => e.ext === \".json\"))\n *   .split((ex) => ex.body)\n *   .enrich(\n *     file({ path: (ex) => ex.body.path }),\n *     only((content: string) => content, \"content\"),\n *   )\n *   .to(log());\n *\n * // List a directory mid-route, e.g. inside a direct() capability\n * craft()\n *   .id(\"search-notes\")\n *   .from(direct())\n *   .to(directory({ path: \"./notes\", recursive: true }))\n *   .transform((entries) => entries.filter((e) => e.ext === \".md\"))\n *   .to(log());\n * ```\n */\nexport function directory(options: DirectoryOptions): DirectoryAdapter;\nexport function directory(\n  options: DirectoryOptions,\n): (Source<DirectoryEntry | DirectoryEntry[]> &\n  Enricher<unknown, DirectoryEntry[]>) & { readonly adapterId: string } {\n  return tagAdapter(\n    {\n      adapterId: \"routecraft.adapter.directory\",\n      subscribe: new DirectorySourceAdapter(options).subscribe,\n      fetch: new DirectoryEnricherAdapter(options).fetch,\n    },\n    directory,\n    factoryArgs(options),\n  );\n}\n\n// Re-export types for the public API.\nexport type { DirectoryEntry, DirectoryOptions } from \"./types.ts\";\n\n// Re-export role classes for internal use, matching the file adapter.\nexport { DirectorySourceAdapter } from \"./source.ts\";\nexport { DirectoryEnricherAdapter } from \"./enricher.ts\";\n","import type { HtmlResult, HtmlOptions } from \"./types.ts\";\nimport { loadOptionalPeer } from \"../shared/optional-peer.ts\";\nimport { getBodyText } from \"../shared/body-text.ts\";\n\n// Memoise the loaded cheerio module so high-volume html() calls do not\n// re-pay the dynamic-import lookup or re-allocate the loadOptionalPeer\n// closures. The promise is shared across all callers, so the import\n// happens at most once per process.\n//\n// A rejected promise is intentionally cached too: if cheerio is genuinely\n// missing it cannot appear mid-process, so retrying would reproduce the\n// same RC5017 with the same install hint. Caching the rejection avoids\n// log noise from repeated dynamic-import failures across every html()\n// call on a route that fires many times.\nlet cheerioPromise: Promise<typeof import(\"cheerio\")> | null = null;\nfunction getCheerio(): Promise<typeof import(\"cheerio\")> {\n  cheerioPromise ??= loadOptionalPeer(() => import(\"cheerio\"), {\n    consumer: \"html adapter\",\n    packageName: \"cheerio\",\n  });\n  return cheerioPromise;\n}\n\nexport function getHtml<T>(\n  body: T,\n  from: ((body: T) => string) | undefined,\n): string {\n  return getBodyText(body, from, \"html\");\n}\n\n/**\n * Core HTML extraction logic shared by transformer and source adapters.\n *\n * cheerio is declared as an optional peer dep; it is loaded lazily inside\n * this function so routes that never use html() do not require the package.\n */\nexport async function extractHtml<T, R>(\n  body: T,\n  options: HtmlOptions<T, R>,\n): Promise<R> {\n  const htmlString = getHtml(body, options.from);\n  const extract = options.extract ?? \"text\";\n  const selector = options.selector;\n  const attr = options.attr;\n\n  if (!selector) {\n    throw new Error(\n      \"html adapter: `selector` is required to extract from HTML. Every reading role extracts (`.transform(html())`, `.from(html({ path }))`, `.enrich(html({ path }))`); only the send role writes without a selector\",\n    );\n  }\n\n  if (extract === \"attr\" && !attr) {\n    throw new Error('html adapter: extract \"attr\" requires an attr option');\n  }\n\n  const cheerio = await getCheerio();\n  const $ = cheerio.load(htmlString);\n  const $el = $(selector);\n  const length = $el.length;\n\n  const textFrom = ($node: ReturnType<typeof $>) =>\n    $node.clone().find(\"style, script\").remove().end().text().trim();\n\n  const getOne = (): string => {\n    if (\n      extract === \"text\" ||\n      extract === \"innerText\" ||\n      extract === \"textContent\"\n    )\n      return textFrom($el);\n    if (extract === \"html\") return $el.html()?.trim() ?? \"\";\n    if (extract === \"attr\") return $el.attr(attr!) ?? \"\";\n    if (extract === \"outerHtml\") return $el.prop(\"outerHTML\") ?? \"\";\n    return \"\";\n  };\n  const getMany = (): string[] => {\n    const values: string[] = [];\n    $el.each((_, el) => {\n      const $e = $(el);\n      if (\n        extract === \"text\" ||\n        extract === \"innerText\" ||\n        extract === \"textContent\"\n      )\n        values.push(textFrom($e));\n      else if (extract === \"html\") values.push($e.html()?.trim() ?? \"\");\n      else if (extract === \"attr\") values.push($e.attr(attr!) ?? \"\");\n      else if (extract === \"outerHtml\") values.push($e.prop(\"outerHTML\") ?? \"\");\n    });\n    return values;\n  };\n\n  let result: HtmlResult;\n  if (length === 0) {\n    result = \"\";\n  } else if (length === 1) {\n    result = getOne();\n  } else {\n    result = getMany();\n  }\n\n  const to = options.to;\n  if (to) return to(body, result) as R;\n  return result as unknown as R;\n}\n","/**\n * Pluck a text payload from an exchange body for codec transformer modes.\n *\n * Shared by the codec decode transformers (json/csv/jsonl/html) so they treat\n * the incoming body the same way: an explicit `from` wins; otherwise a string\n * body is used directly, and an object carrying a string `body` property (e.g.\n * the result of `http()`) has that property used. Anything else throws an\n * adapter-specific error.\n *\n * @param body - The exchange body to read the text from.\n * @param from - Optional explicit extractor; when provided it is used verbatim.\n * @param adapter - Adapter name used to prefix the thrown error message.\n * @returns The extracted text payload.\n * @internal Not exported from the package public API.\n */\nexport function getBodyText<T>(\n  body: T,\n  from: ((body: T) => string) | undefined,\n  adapter: string,\n): string {\n  if (from) return from(body);\n  if (typeof body === \"string\") return body;\n  if (\n    body &&\n    typeof body === \"object\" &&\n    \"body\" in body &&\n    typeof (body as { body: unknown }).body === \"string\"\n  ) {\n    return (body as { body: string }).body;\n  }\n  throw new Error(\n    `${adapter} adapter: body must be a string, an object with a string body property (e.g. http() result), or provide a from() option`,\n  );\n}\n","import type { Transformer } from \"../../operations/transform.ts\";\nimport type { HtmlOptions, HtmlResult } from \"./types.ts\";\nimport { extractHtml } from \"./shared.ts\";\n\n/**\n * HtmlTransformerAdapter extracts data from HTML using CSS selectors (cheerio).\n */\nexport class HtmlTransformerAdapter<\n  T = unknown,\n  R = HtmlResult,\n> implements Transformer<T, R> {\n  readonly adapterId = \"routecraft.adapter.html\";\n\n  constructor(private readonly options: HtmlOptions<T, R>) {}\n\n  transform(body: T): Promise<R> {\n    return extractHtml(body, this.options);\n  }\n}\n","import type { Source, CallableSource } from \"../../operations/from.ts\";\nimport type { HtmlOptions, HtmlResult } from \"./types.ts\";\nimport type { FileOptions } from \"../file/types.ts\";\nimport { file } from \"../file/index.ts\";\nimport { extractHtml } from \"./shared.ts\";\nimport { DEFAULT_ON_PARSE_ERROR, isParseError } from \"../shared/parse.ts\";\n\n/**\n * HtmlSourceAdapter reads HTML from a file and extracts data using CSS selectors.\n * Only available when path option is provided.\n *\n * Extraction is deferred to the route's pipeline by passing a `parse`\n * callback to `handler(...)`: the runtime applies it as a synthetic first\n * step so an extraction failure becomes an observable pipeline event.\n *\n * | `onParseError` | Lifecycle on extraction failure                                  |\n * |----------------|------------------------------------------------------------------|\n * | `'fail'` (default) | `route:exchange:failed` (or `route:error:caught` if `.error()` recovers) |\n * | `'abort'`      | `route:exchange:failed`, then source rejects and `context:error` fires |\n * | `'drop'`       | `route:exchange:dropped` with `reason: \"parse-failed\"`                 |\n *\n * See #187.\n */\nexport class HtmlSourceAdapter<\n  T = unknown,\n  R = HtmlResult,\n> implements Source<HtmlResult> {\n  readonly adapterId = \"routecraft.adapter.html\";\n  private readonly fileAdapter;\n\n  constructor(private readonly options: HtmlOptions<T, R>) {\n    if (!options.path) {\n      throw new Error(\n        \"html adapter: the source role requires the path option to be provided\",\n      );\n    }\n    const fileOpts: FileOptions = { path: options.path };\n    if (options.encoding !== undefined) fileOpts.encoding = options.encoding;\n    this.fileAdapter = file(fileOpts);\n  }\n\n  subscribe: CallableSource<HtmlResult> = async (sub) => {\n    const onParseError = this.options.onParseError ?? DEFAULT_ON_PARSE_ERROR;\n    const opts = this.options;\n    const filePath = opts.path as string;\n\n    // Delegate to the file source with a derived subscription whose emit\n    // attaches the HTML extraction as the parse step.\n    return this.fileAdapter.subscribe({\n      ...sub,\n      emit: async (msg) => {\n        const promise = sub.emit({\n          ...msg,\n          parse: (raw) => extractHtml(raw as T, opts) as Promise<HtmlResult>,\n          parseFailureMode: onParseError,\n        });\n        // 'abort' is parse-specific: only RC5016 should tear down the\n        // source. Downstream destination errors must NOT propagate as\n        // an abort signal even when onParseError === 'abort'.\n        return await promise.catch((err: unknown) => {\n          if (onParseError === \"abort\" && isParseError(err)) throw err;\n          // 'fail' / 'drop' / non-parse failures under 'abort': route\n          // boundary already emitted the appropriate lifecycle event\n          // (route:exchange:failed or route:exchange:dropped). Log at debug for\n          // operator parity with jsonl/source.ts and swallow so the\n          // file source keeps reading. The file adapter ignores the\n          // resolved value, so returning undefined is safe.\n          sub.context.logger.debug(\n            { err, path: filePath, adapter: \"html\" },\n            \"html adapter: pipeline failed for file; continuing\",\n          );\n          return undefined as never;\n        });\n      },\n    });\n  };\n}\n","import type { Destination, CallableDestination } from \"../../operations/to.ts\";\nimport type { Exchange } from \"../../exchange.ts\";\nimport type { HtmlOptions, HtmlResult } from \"./types.ts\";\nimport { file } from \"../file/index.ts\";\nimport { getHtml } from \"./shared.ts\";\nimport { assertExclusiveSendBehavior } from \"../shared/file-role-guards.ts\";\n\n/**\n * HtmlDestinationAdapter implements the Destination (send) role for HTML\n * files.\n *\n * `send` is strictly void: it writes the HTML string from the body to the\n * resolved path (overwrite by default, `append: true` to append,\n * `delete: true` to remove the file). Reading + extraction lives on the\n * fetch role (HtmlEnricherAdapter).\n */\nexport class HtmlDestinationAdapter<\n  T = unknown,\n  R = HtmlResult,\n> implements Destination<unknown> {\n  readonly adapterId = \"routecraft.adapter.html\";\n  private readonly pathOption: string | ((exchange: Exchange) => string);\n\n  constructor(private readonly options: HtmlOptions<T, R>) {\n    if (!options.path) {\n      throw new Error(\n        \"html adapter: the send role requires the path option to be provided\",\n      );\n    }\n    assertExclusiveSendBehavior(\"html\", options);\n    this.pathOption = options.path;\n  }\n\n  send: CallableDestination<unknown> = async (exchange) => {\n    const resolvedPath =\n      typeof this.pathOption === \"function\"\n        ? this.pathOption(exchange)\n        : this.pathOption;\n\n    // Delete behavior: delegate to the file adapter (no write). Idempotent.\n    if (this.options.delete) {\n      await file({ path: resolvedPath, delete: true }).send(exchange);\n      return;\n    }\n\n    // Write / append: pull the HTML string from the body and write it.\n    const htmlContent = getHtml(exchange.body, undefined);\n\n    const adapter = file({\n      path: resolvedPath,\n      append: this.options.append ?? false,\n      ...(this.options.encoding !== undefined\n        ? { encoding: this.options.encoding }\n        : {}),\n      ...(this.options.createDirs !== undefined\n        ? { createDirs: this.options.createDirs }\n        : {}),\n    });\n\n    await adapter.send({ ...exchange, body: htmlContent });\n  };\n}\n","import type { Enricher, CallableEnricher } from \"../../operations/enrich.ts\";\nimport type { Exchange } from \"../../exchange.ts\";\nimport type { HtmlOptions, HtmlResult } from \"./types.ts\";\nimport { FileEnricherAdapter } from \"../file/enricher.ts\";\nimport { extractHtml } from \"./shared.ts\";\n\n/**\n * HtmlEnricherAdapter implements the Enricher (fetch) role for HTML files:\n * `fetch` reads the resolved path, extracts via the selector, and returns\n * the raw extracted result, so `.enrich(html({ path, selector }))` pulls an\n * extraction into the route mid-flow. The transformer-role `to` mapping is\n * not applied (the raw `HtmlResult` is returned and placement is left to\n * the aggregator). Extraction failures throw (the route boundary surfaces\n * them as `route:exchange:failed`); the `onParseError` lifecycle controls apply to\n * the source role only.\n */\nexport class HtmlEnricherAdapter<\n  T = unknown,\n  R = HtmlResult,\n> implements Enricher<unknown, HtmlResult> {\n  readonly adapterId = \"routecraft.adapter.html\";\n  private readonly pathOption: string | ((exchange: Exchange) => string);\n\n  constructor(private readonly options: HtmlOptions<T, R>) {\n    if (!options.path) {\n      throw new Error(\n        \"html adapter: the fetch role requires the path option to be provided\",\n      );\n    }\n    this.pathOption = options.path;\n  }\n\n  /** Fetch implementation: read the resolved path and return the extraction. */\n  fetch: CallableEnricher<unknown, HtmlResult> = async (exchange, ctx) => {\n    const resolvedPath =\n      typeof this.pathOption === \"function\"\n        ? this.pathOption(exchange)\n        : this.pathOption;\n    // Only the fetch slot is needed; skip the full file() facade on the\n    // hot path.\n    const content = await new FileEnricherAdapter({\n      path: resolvedPath,\n      encoding: this.options.encoding ?? \"utf-8\",\n    }).fetch(exchange, ctx);\n    const extractOpts: HtmlOptions<string, HtmlResult> = {};\n    if (this.options.selector !== undefined)\n      extractOpts.selector = this.options.selector;\n    if (this.options.extract !== undefined)\n      extractOpts.extract = this.options.extract;\n    if (this.options.attr !== undefined) extractOpts.attr = this.options.attr;\n    return extractHtml<string, HtmlResult>(content, extractOpts);\n  };\n}\n","import type { Source, CallableSource } from \"../../operations/from.ts\";\nimport type { Destination } from \"../../operations/to.ts\";\nimport type { Exchange } from \"../../exchange.ts\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport type { Transformer } from \"../../operations/transform.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\nimport type { HtmlOptions, HtmlResult } from \"./types.ts\";\nimport { HtmlTransformerAdapter } from \"./transformer.ts\";\nimport { HtmlSourceAdapter } from \"./source.ts\";\nimport { HtmlDestinationAdapter } from \"./destination.ts\";\nimport { HtmlEnricherAdapter } from \"./enricher.ts\";\nimport {\n  selectsFileRole,\n  staticSourcePathError,\n} from \"../shared/file-role-guards.ts\";\n\n/**\n * Combined HTML file adapter type: the file roles on one honest type. The\n * operation keyword selects the role (`.from()` subscribes, `.to()` sends,\n * `.enrich()` fetches). The transformer role lives on the no-`path` variant\n * of the factory (an extraction over the body needs no file).\n */\nexport type HtmlAdapter = Source<HtmlResult> &\n  Destination<unknown> &\n  Enricher<unknown, HtmlResult> & { readonly adapterId: string };\n\n/**\n * Create an HTML adapter that extracts data from HTML using CSS selectors (cheerio).\n *\n * **Transformer role** (no `path` option): extracts data from the HTML\n * string in the exchange body. Use `from` to read a sub-field and `to` to\n * write the result to a sub-field.\n *\n * **File roles** (`path` present); the POSITION in the route selects the role:\n * - **`.from(html({ path, selector }))`** reads the file, extracts via the\n *   selector, and emits the result.\n * - **`.to(html({ path }))`** writes the HTML string from the body to the\n *   file (overwrite; `append: true` appends; `delete: true` removes the\n *   file). The body flows through unchanged.\n * - **`.enrich(html({ path, selector }))`** extracts from the file\n *   mid-route; the result replaces the body (pass an aggregator such as\n *   `only()` to merge instead).\n *\n * Requires `cheerio` to be installed as an optional peer dependency.\n *\n * @param options - selector, extract type, optional path for file roles, optional from/to for the transformer role\n * @returns A Transformer (no path) or the combined file adapter (path)\n *\n * @example\n * ```typescript\n * // Transformer role\n * .transform(html({ selector: 'title', extract: 'text' }))\n *\n * // Source role: read HTML file and extract\n * .from(html({ path: './page.html', selector: 'h1', extract: 'text' }))\n *\n * // Fetch mid-route: extract from a file and merge the result\n * .enrich(html({ path: './page.html', selector: 'h1' }), only((h1) => h1, 'h1'))\n *\n * // Send role: write HTML to file\n * .to(html({ path: './output.html' }))\n *\n * // Delete an HTML file (idempotent)\n * .to(html({ path: (ex) => ex.body.processedPath, delete: true }))\n * ```\n */\nexport function html<T = unknown, R = HtmlResult>(\n  options: HtmlOptions<T, R> & {\n    path: string | ((exchange: Exchange) => string);\n  },\n): HtmlAdapter;\nexport function html<T = unknown, R = HtmlResult>(\n  options: HtmlOptions<T, R> & { path?: undefined },\n): Transformer<T, R> & { readonly adapterId: string };\nexport function html<T = unknown, R = HtmlResult>(\n  options: HtmlOptions<T, R>,\n): (Transformer<T, R> & { readonly adapterId: string }) | HtmlAdapter {\n  const args = factoryArgs(options);\n  if (selectsFileRole(\"html\", options)) {\n    const destination = new HtmlDestinationAdapter<T, R>(options);\n    const enricher = new HtmlEnricherAdapter<T, R>(options);\n\n    // The source role requires a static string path. For dynamic (function)\n    // paths, expose a `subscribe` that throws the same clear error lazily,\n    // so send/fetch usage with a dynamic path still works.\n    const subscribe: CallableSource<HtmlResult> =\n      typeof options.path === \"string\"\n        ? new HtmlSourceAdapter<T, R>(options).subscribe\n        : async () => {\n            throw staticSourcePathError(\"html\");\n          };\n\n    return tagAdapter(\n      {\n        adapterId: \"routecraft.adapter.html\",\n        subscribe,\n        send: destination.send,\n        fetch: enricher.fetch,\n      },\n      html,\n      args,\n    ) as HtmlAdapter;\n  }\n  const transformer = new HtmlTransformerAdapter<T, R>(options);\n  return tagAdapter(\n    {\n      adapterId: \"routecraft.adapter.html\",\n      transform: transformer.transform.bind(transformer),\n    },\n    html,\n    args,\n  );\n}\n\n// Re-export types\nexport type { HtmlOptions, HtmlResult } from \"./types.ts\";\n","import { getBodyText } from \"../shared/body-text.ts\";\n\nexport function getText<T>(\n  body: T,\n  from: ((body: T) => string) | undefined,\n): string {\n  return getBodyText(body, from, \"json\");\n}\n\n/**\n * Get a value from an object by dot path with optional [index] for arrays.\n * e.g. \"data.items[0].name\" -> obj.data.items[0].name\n */\nexport function getByPath(obj: unknown, path: string): unknown {\n  const trimmed = path.trim();\n  if (!trimmed) return obj;\n  const segments = trimmed.split(\".\").filter(Boolean);\n  let current: unknown = obj;\n  for (const seg of segments) {\n    if (current === null || current === undefined) return undefined;\n    const bracket = seg.indexOf(\"[\");\n    if (bracket === -1) {\n      current = (current as Record<string, unknown>)[seg];\n      continue;\n    }\n    const key = seg.slice(0, bracket);\n    const indexMatch = seg.slice(bracket).match(/^\\[(\\d+)\\]$/);\n    if (key) {\n      current = (current as Record<string, unknown>)[key];\n    }\n    if (indexMatch) {\n      const index = Number(indexMatch[1]);\n      current = Array.isArray(current) ? current[index] : undefined;\n    }\n  }\n  return current;\n}\n","import type { Transformer } from \"../../operations/transform.ts\";\nimport type { JsonTransformerOptions } from \"./types.ts\";\nimport { getText, getByPath } from \"./shared.ts\";\n\n/**\n * JsonTransformerAdapter parses a JSON string and optionally extracts a value by path.\n */\nexport class JsonTransformerAdapter<\n  T = unknown,\n  R = unknown,\n  V = unknown,\n> implements Transformer<T, R> {\n  readonly adapterId = \"routecraft.adapter.json\";\n\n  constructor(private readonly options: JsonTransformerOptions<T, R, V>) {}\n\n  transform(body: T): R {\n    const text = getText(body, this.options.from);\n    let parsed: unknown;\n    try {\n      parsed = JSON.parse(text);\n    } catch (err) {\n      const message = err instanceof Error ? err.message : String(err);\n      throw new Error(`json adapter: failed to parse JSON: ${message}`);\n    }\n    const pointer = this.options.pointer?.trim();\n    const pathResult = pointer ? getByPath(parsed, pointer) : parsed;\n    const result = this.options.getValue\n      ? this.options.getValue(pathResult)\n      : pathResult;\n\n    const to = this.options.to;\n    if (to) return to(body, result as V) as R;\n    return result as unknown as R;\n  }\n}\n","import type { Source, CallableSource } from \"../../operations/from.ts\";\nimport type { JsonFileOptions } from \"./types.ts\";\nimport type { FileOptions } from \"../file/types.ts\";\nimport { file } from \"../file/index.ts\";\nimport { DEFAULT_ON_PARSE_ERROR, isParseError } from \"../shared/parse.ts\";\nimport { staticSourcePathError } from \"../shared/file-role-guards.ts\";\n\n/**\n * JsonSourceAdapter reads and parses JSON files.\n *\n * Parses are deferred to the route's pipeline by passing a `parse` callback\n * to `handler(...)`: the runtime applies it as a synthetic first step so a\n * malformed JSON file becomes an observable pipeline event:\n *\n * | `onParseError` | Lifecycle on bad JSON                                          |\n * |----------------|----------------------------------------------------------------|\n * | `'fail'` (default) | `route:exchange:failed` (or `route:error:caught` if `.error()` recovers) |\n * | `'abort'`      | `route:exchange:failed`, then source rejects and `context:error` fires |\n * | `'drop'`       | `route:exchange:dropped` with `reason: \"parse-failed\"`               |\n *\n * See #187.\n */\nexport class JsonSourceAdapter implements Source<unknown> {\n  readonly adapterId = \"routecraft.adapter.json.file\";\n  private readonly fileAdapter;\n\n  constructor(private readonly options: JsonFileOptions) {\n    if (typeof options.path !== \"string\") {\n      throw staticSourcePathError(\"json\");\n    }\n    // Build options object, only including defined properties to satisfy exactOptionalPropertyTypes\n    const fileOptions: FileOptions = { path: options.path };\n    if (options.encoding !== undefined) fileOptions.encoding = options.encoding;\n    this.fileAdapter = file(fileOptions);\n  }\n\n  subscribe: CallableSource<unknown> = async (sub) => {\n    const onParseError = this.options.onParseError ?? DEFAULT_ON_PARSE_ERROR;\n    const reviver = this.options.reviver;\n    const filePath = this.options.path as string;\n\n    // Delegate to the file source with a derived subscription whose emit\n    // attaches the JSON parse to each raw message. All three modes route\n    // through the synthetic parse step so the exchange exists, lifecycle\n    // events fire, and the route can observe each outcome:\n    //   'fail'  -> route:exchange:failed (or .error() recovers)\n    //   'abort' -> route:exchange:failed, then we rethrow to abort the source\n    //                (only for RC5016; downstream errors are swallowed)\n    //   'drop'  -> route:exchange:dropped with reason \"parse-failed\"\n    return this.fileAdapter.subscribe({\n      ...sub,\n      emit: async (msg) => {\n        const promise = sub.emit({\n          ...msg,\n          parse: (raw) => JSON.parse(raw as string, reviver as never),\n          parseFailureMode: onParseError,\n        });\n        return await promise.catch((err: unknown) => {\n          // 'abort' is parse-specific: only RC5016 should tear down the\n          // source. A downstream destination error must NOT propagate\n          // as an abort signal.\n          if (onParseError === \"abort\" && isParseError(err)) throw err;\n          // 'fail' / 'drop' / non-parse failures under 'abort': route\n          // boundary already emitted the appropriate lifecycle event.\n          // Log at debug for operator parity with jsonl/source.ts.\n          sub.context.logger.debug(\n            { err, path: filePath, adapter: \"json\" },\n            \"json adapter: pipeline failed for file; continuing\",\n          );\n          return undefined as never;\n        });\n      },\n    });\n  };\n}\n","import type { Destination, CallableDestination } from \"../../operations/to.ts\";\nimport type { Exchange } from \"../../exchange.ts\";\nimport type { JsonFileOptions } from \"./types.ts\";\nimport { file } from \"../file/index.ts\";\nimport { assertExclusiveSendBehavior } from \"../shared/file-role-guards.ts\";\n\n/**\n * JsonDestinationAdapter implements the Destination (send) role for JSON\n * files.\n *\n * `send` is strictly void: it stringifies the exchange body and writes it\n * (overwrite by default, `append: true` to append, `delete: true` to remove\n * the file). Reading lives on the fetch role (JsonEnricherAdapter).\n */\nexport class JsonDestinationAdapter implements Destination<unknown> {\n  readonly adapterId = \"routecraft.adapter.json.file\";\n\n  constructor(private readonly options: JsonFileOptions) {\n    assertExclusiveSendBehavior(\"json\", options);\n  }\n\n  send: CallableDestination<unknown> = async (exchange) => {\n    const {\n      space,\n      indent,\n      replacer,\n      path: filePath,\n      encoding,\n      createDirs,\n      append = false,\n      delete: remove = false,\n    } = this.options;\n\n    const resolvedPath =\n      typeof filePath === \"function\" ? filePath(exchange) : filePath;\n\n    // Delete behavior: delegate to the file adapter (no stringify). Idempotent.\n    if (remove) {\n      await file({ path: resolvedPath, delete: true }).send(exchange);\n      return;\n    }\n\n    const formatting = indent ?? space ?? 0;\n\n    let jsonString: string;\n    try {\n      const result = JSON.stringify(\n        exchange.body,\n        replacer as never,\n        formatting,\n      );\n      if (result === undefined) {\n        throw new Error(\n          \"value is not JSON-serializable (top-level undefined, function, or symbol)\",\n        );\n      }\n      jsonString = result;\n    } catch (err) {\n      const message = err instanceof Error ? err.message : String(err);\n      throw new Error(`json adapter: failed to stringify JSON: ${message}`);\n    }\n\n    const stringExchange: Exchange = {\n      ...exchange,\n      body: jsonString,\n    };\n\n    await file({\n      path: resolvedPath,\n      append,\n      ...(encoding !== undefined ? { encoding } : {}),\n      ...(createDirs !== undefined ? { createDirs } : {}),\n    }).send(stringExchange);\n  };\n}\n","import type { Enricher, CallableEnricher } from \"../../operations/enrich.ts\";\nimport type { JsonFileOptions } from \"./types.ts\";\nimport { FileEnricherAdapter } from \"../file/enricher.ts\";\n\n/**\n * JsonEnricherAdapter implements the Enricher (fetch) role for JSON files:\n * `fetch` reads the resolved path, `JSON.parse`s it, and returns the parsed\n * value, so `.enrich(json({ path }))` pulls a JSON file into the route\n * mid-flow. Parse failures throw (the route boundary surfaces them as\n * `route:exchange:failed`); the `onParseError` lifecycle controls apply to the\n * source role only.\n *\n * @template T - Parsed value type (caller-asserted, e.g. `json<Config>(...)`)\n */\nexport class JsonEnricherAdapter<T = unknown> implements Enricher<unknown, T> {\n  readonly adapterId = \"routecraft.adapter.json.file\";\n\n  constructor(private readonly options: JsonFileOptions) {}\n\n  /** Fetch implementation: read the resolved path and return the parsed value. */\n  fetch: CallableEnricher<unknown, T> = async (exchange, ctx) => {\n    const { path: filePath, encoding, reviver } = this.options;\n    const resolvedPath =\n      typeof filePath === \"function\" ? filePath(exchange) : filePath;\n    // Only the fetch slot is needed; skip the full file() facade on the\n    // hot path.\n    const content = await new FileEnricherAdapter({\n      path: resolvedPath,\n      encoding: encoding ?? \"utf-8\",\n    }).fetch(exchange, ctx);\n    try {\n      return JSON.parse(content, reviver as never) as T;\n    } catch (err) {\n      const message = err instanceof Error ? err.message : String(err);\n      throw new Error(\n        `json adapter: failed to parse JSON from ${resolvedPath}: ${message}`,\n      );\n    }\n  };\n}\n","import type { Source, CallableSource } from \"../../operations/from.ts\";\nimport type { Destination } from \"../../operations/to.ts\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport type { Transformer } from \"../../operations/transform.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\nimport type {\n  JsonTransformerOptions,\n  JsonFileOptions,\n  JsonOptions,\n} from \"./types.ts\";\nimport { JsonTransformerAdapter } from \"./transformer.ts\";\nimport { JsonSourceAdapter } from \"./source.ts\";\nimport { JsonDestinationAdapter } from \"./destination.ts\";\nimport { JsonEnricherAdapter } from \"./enricher.ts\";\nimport { selectsFileRole } from \"../shared/file-role-guards.ts\";\n\n/**\n * Combined JSON file adapter type: all three roles on one honest type. The\n * operation keyword selects the role (`.from()` subscribes, `.to()` sends,\n * `.enrich()` fetches). The parsed value is typed `T` (default `unknown`);\n * pass it explicitly (`json<Product[]>(...)`) for a typed body.\n *\n * @template T - Parsed value type (caller-asserted)\n */\nexport type JsonFileAdapterType<T = unknown> = Source<T> &\n  Destination<unknown> &\n  Enricher<unknown, T> & { readonly adapterId: string };\n\n/**\n * Creates a JSON adapter.\n *\n * **Transformer role** (no `path` option):\n * Parses a JSON string and optionally extracts a value by `pointer`\n * (dot-notation into the parsed value). By default uses body (or body.body\n * when object) as the JSON string and replaces the body with the result.\n *\n * **File roles** (`path` present); the POSITION in the route selects the role:\n * - **`.from(json({ path }))`** reads + parses the file and emits the value.\n * - **`.to(json({ path }))`** stringifies the body and writes it (overwrite;\n *   `append: true` appends; `delete: true` removes the file). The body flows\n *   through unchanged.\n * - **`.enrich(json({ path }))`** reads + parses mid-route; the value\n *   replaces the body (pass an aggregator such as `only()` to merge instead).\n *\n * @param options - Transformer options (`from`, `pointer`, `getValue`, `to`) or file options (`path`, `space`, etc.)\n * @returns A Transformer (no path) or the combined file adapter (path)\n *\n * @example\n * ```typescript\n * // Transformer role\n * .transform(json({ pointer: 'data.items' }))\n * .transform(json({ from: (b) => b.raw, getValue: (p) => p as User[] }))\n *\n * // Source role\n * .from(json({ path: './data.json' }))\n *\n * // Read mid-route (the parsed value replaces the body)\n * .enrich(json<Product[]>({ path: './data.json' }), only((p) => p, 'catalogue'))\n *\n * // Send role (write)\n * .to(json({ path: './output.json', space: 2 }))\n * .to(json({ path: (ex) => `./data/${ex.body.id}.json`, createDirs: true }))\n * ```\n */\nexport function json<T, R, V>(\n  options: JsonTransformerOptions<T, R, V> & {\n    getValue: (parsed: unknown) => V;\n    to?: undefined;\n  },\n): Transformer<T, V>;\nexport function json<T = unknown>(\n  options: JsonFileOptions,\n): JsonFileAdapterType<T>;\nexport function json<T = unknown, R = unknown, V = unknown>(\n  options?: JsonTransformerOptions<T, R, V>,\n): Transformer<T, R>;\nexport function json<T = unknown, R = unknown, V = unknown>(\n  options: JsonOptions<T, R, V> = {},\n): Transformer<T, R> | Transformer<T, V> | JsonFileAdapterType<T> {\n  const args = factoryArgs(options);\n\n  // File roles: `path` presence is the discriminator; `path` always means a\n  // file path (the transformer's extraction key is `pointer`). The guard\n  // tests for the key itself, so a supplied-but-empty path is refused rather\n  // than silently demoted to the transformer role.\n  if (selectsFileRole(\"json\", options)) {\n    const fileOptions = options as JsonFileOptions;\n    const destination = new JsonDestinationAdapter(fileOptions);\n    const enricher = new JsonEnricherAdapter<T>(fileOptions);\n\n    // The source role requires a static string path; a function path keeps\n    // the honest combined type, and its subscribe throws the same clear\n    // error lazily (the JsonSourceAdapter constructor enforces it).\n    let sourceAdapter: JsonSourceAdapter | undefined;\n    const subscribe: CallableSource<T> = async (sub) => {\n      sourceAdapter ??= new JsonSourceAdapter(fileOptions);\n      return sourceAdapter.subscribe(sub) as Promise<void>;\n    };\n\n    return tagAdapter(\n      {\n        adapterId: \"routecraft.adapter.json.file\",\n        subscribe,\n        send: destination.send,\n        fetch: enricher.fetch,\n      },\n      json,\n      args,\n    ) as JsonFileAdapterType<T>;\n  }\n\n  return tagAdapter(\n    new JsonTransformerAdapter<T, R, V>(\n      options as JsonTransformerOptions<T, R, V>,\n    ),\n    json,\n    args,\n  ) as unknown as Transformer<T, R> | Transformer<T, V>;\n}\n\n// Re-export types\nexport type {\n  JsonOptions,\n  JsonTransformerOptions,\n  JsonFileOptions,\n} from \"./types.ts\";\n","import type { Exchange } from \"../../exchange.ts\";\nimport type { OnParseError } from \"../shared/parse.ts\";\n\n/**\n * Parsing/formatting options shared by transformer and file modes.\n */\nexport interface CsvParseOptions {\n  /**\n   * Whether the CSV has a header row (parse) or should include headers (format).\n   * Default: true\n   */\n  header?: boolean;\n\n  /**\n   * Field delimiter. Default: ','\n   */\n  delimiter?: string;\n\n  /**\n   * Quote character. Default: '\"'\n   */\n  quoteChar?: string;\n\n  /**\n   * Skip empty lines. Default: true\n   */\n  skipEmptyLines?: boolean;\n}\n\n/**\n * Transformer-mode options (no `path`): parse a CSV string already in the body.\n */\nexport interface CsvTransformerOptions<\n  T = unknown,\n  R = unknown,\n> extends CsvParseOptions {\n  /**\n   * Pluck the CSV string from the body. If omitted: body is used when it's a\n   * string, or body.body when body is an object (e.g. after http()).\n   */\n  from?: (body: T) => string;\n\n  /**\n   * Where to put the parsed rows. If omitted, the result replaces the entire\n   * body. Use e.g. (body, rows) => ({ ...body, rows }) to write to a sub-field.\n   */\n  to?: (body: T, result: CsvData) => R;\n}\n\n/**\n * Source/Destination mode options (with `path`).\n */\nexport interface CsvFileOptions extends CsvParseOptions {\n  /**\n   * File path for source/destination mode.\n   */\n  path: string | ((exchange: Exchange) => string);\n\n  /**\n   * Text encoding. Default: 'utf-8'\n   */\n  encoding?: BufferEncoding;\n\n  /**\n   * Create parent directories if they don't exist (send role only).\n   * Default: false\n   */\n  createDirs?: boolean;\n\n  /**\n   * Send role behavior: append rows to the file instead of overwriting it\n   * (the header row is only written when the file does not exist yet).\n   * Mutually exclusive with `delete`. Default: false (overwrite)\n   */\n  append?: boolean;\n\n  /**\n   * Send role behavior: delete the CSV file instead of writing it.\n   * Idempotent: an already-absent path is a no-op. The body is unchanged.\n   * Mutually exclusive with `append`. Default: false\n   */\n  delete?: boolean;\n\n  /**\n   * When true, the source emits one exchange per row instead of the entire\n   * parsed array. Source role only; the send/fetch roles are identical under\n   * chunked. Each chunked exchange includes CSV_ROW and CSV_PATH headers.\n   * Default: false\n   */\n  chunked?: boolean;\n\n  /**\n   * How to handle a Papa Parse row error (chunked mode) or parse error\n   * (non-chunked mode).\n   *\n   * - `'fail'` (default): `route:exchange:failed` fires for the bad row, or\n   *   `route:error:caught` when the route's `.error()` handler recovers it;\n   *   chunked mode continues to the next row.\n   * - `'abort'`: `route:exchange:failed` fires, then the source dies\n   *   (`context:error`).\n   * - `'drop'`: `route:exchange:dropped` fires with `reason: \"parse-failed\"`;\n   *   chunked mode continues.\n   *\n   * See `OnParseError` for full semantics.\n   *\n   * @default \"fail\"\n   */\n  onParseError?: OnParseError;\n}\n\nexport type CsvOptions<T = unknown, R = unknown> =\n  CsvTransformerOptions<T, R> | CsvFileOptions;\n\nexport type CsvRow = Record<string, unknown> | string[];\nexport type CsvData = CsvRow[];\n\n/**\n * Header keys the CSV source sets on chunked-mode exchanges. Keys live\n * under the reserved `routecraft.csv.*` namespace; the value types are\n * merged into `RoutecraftHeaders` below.\n */\nexport const CsvHeaders = {\n  /** The 1-based row number when reading a CSV file in chunked mode */\n  ROW: \"routecraft.csv.row\",\n  /** The file path when reading a CSV file in chunked mode */\n  PATH: \"routecraft.csv.path\",\n} as const satisfies Record<string, `routecraft.csv.${string}`>;\n\ndeclare module \"@routecraft/routecraft\" {\n  interface RoutecraftHeaders {\n    /** The 1-based row number when reading a CSV file in chunked mode */\n    [CsvHeaders.ROW]?: number;\n    /** The file path when reading a CSV file in chunked mode */\n    [CsvHeaders.PATH]?: string;\n  }\n}\n","import { createRequire } from \"node:module\";\nimport type { CsvData, CsvParseOptions } from \"./types.ts\";\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Dynamically load papaparse and verify it is installed.\n * Throws with installation instructions if not available.\n *\n * @internal Not exported from the package public API.\n */\nexport function ensurePapaparse(): typeof import(\"papaparse\") {\n  try {\n    const papa = require(\"papaparse\");\n    return papa.default || papa;\n  } catch {\n    throw new Error(\n      \"csv adapter requires 'papaparse' to be installed. Install it with: npm install papaparse\",\n    );\n  }\n}\n\n/**\n * Parse a CSV string into rows via PapaParse, throwing on the first error.\n *\n * Shared by source (non-chunked), the read-as-destination mode, and the\n * transformer so they all surface parse failures the same way.\n *\n * @internal Not exported from the package public API.\n */\nexport function parseCsv(content: string, options: CsvParseOptions): CsvData {\n  const Papa = ensurePapaparse();\n  const {\n    header = true,\n    delimiter = \",\",\n    quoteChar = '\"',\n    skipEmptyLines = true,\n  } = options;\n  const result = Papa.parse(content, {\n    header,\n    delimiter,\n    quoteChar,\n    skipEmptyLines,\n  });\n  if (result.errors.length > 0) {\n    const firstError = result.errors[0];\n    throw new Error(\n      `csv adapter: parse error at row ${firstError.row}: ${firstError.message}`,\n    );\n  }\n  return result.data as CsvData;\n}\n","import { createReadStream } from \"node:fs\";\nimport type {\n  Source,\n  CallableSource,\n  Subscription,\n} from \"../../operations/from.ts\";\nimport type { CsvFileOptions, CsvData, CsvRow } from \"./types.ts\";\nimport type { ExchangeHeaders } from \"../../exchange.ts\";\nimport { CsvHeaders } from \"./types.ts\";\nimport { file } from \"../file/index.ts\";\nimport { ensurePapaparse, parseCsv } from \"./shared.ts\";\nimport { throwFileError } from \"../shared/fs-errors.ts\";\nimport {\n  DEFAULT_ON_PARSE_ERROR,\n  isParseError,\n  type OnParseError,\n} from \"../shared/parse.ts\";\nimport { staticSourcePathError } from \"../shared/file-role-guards.ts\";\n\n/**\n * CsvSourceAdapter reads CSV files and parses them via PapaParse.\n *\n * Non-chunked: emits a single exchange whose body is the full parsed array.\n * Chunked: streams rows from disk and emits one exchange per row with\n * `CSV_ROW` and `CSV_PATH` headers; uses `parser.pause()` /\n * `parser.resume()` around each handler call for backpressure.\n *\n * Per-row parse failures are observable via the events bus:\n *\n * | `onParseError` | Lifecycle on bad row (chunked)                                  |\n * |----------------|-----------------------------------------------------------------|\n * | `'fail'` (default) | `route:exchange:failed` (or `route:error:caught`); next row continues |\n * | `'abort'`      | `route:exchange:failed` for the bad row, then source dies (`context:error`) |\n * | `'drop'`       | `route:exchange:dropped` (`reason: \"parse-failed\"`); next row continues |\n *\n * See #187.\n */\nexport class CsvSourceAdapter implements Source<CsvData | CsvRow> {\n  readonly adapterId = \"routecraft.adapter.csv\";\n\n  constructor(private readonly options: CsvFileOptions) {}\n\n  subscribe: CallableSource<CsvData | CsvRow> = async (sub) => {\n    const Papa = ensurePapaparse();\n    const {\n      header = true,\n      delimiter = \",\",\n      quoteChar = '\"',\n      skipEmptyLines = true,\n      chunked = false,\n      onParseError = DEFAULT_ON_PARSE_ERROR,\n    } = this.options;\n\n    if (chunked) {\n      sub.ready();\n      await this.subscribeChunked(\n        sub as Subscription<CsvData | CsvRow>,\n        Papa,\n        { header, delimiter, quoteChar, skipEmptyLines },\n        onParseError,\n      );\n      return;\n    }\n\n    const filePath = this.options.path;\n    if (typeof filePath !== \"string\") {\n      throw staticSourcePathError(\"csv\");\n    }\n\n    const fileAdapter = file({\n      path: filePath,\n      encoding: this.options.encoding || \"utf-8\",\n    });\n\n    const parseFn = (raw: unknown): CsvData =>\n      parseCsv(raw as string, {\n        header,\n        delimiter,\n        quoteChar,\n        skipEmptyLines,\n      });\n\n    // Delegate to the file source with a derived subscription whose emit\n    // attaches the CSV parse to the raw file content.\n    await fileAdapter.subscribe({\n      ...sub,\n      emit: async (msg) => {\n        // The raw file content is a string pre-parse; the synthetic parse\n        // step narrows it to CsvData (the standard pre-parse type caveat).\n        const promise = sub.emit({\n          message: msg.message as unknown as CsvData,\n          ...(msg.headers ? { headers: msg.headers } : {}),\n          parse: parseFn,\n          parseFailureMode: onParseError,\n        });\n        // 'abort' is parse-specific: only RC5016 should tear down the\n        // source. A downstream destination error must NOT propagate as\n        // an abort signal even when onParseError === 'abort'. Every other\n        // failure is debug-logged and swallowed (matching json/jsonl/html)\n        // so the file source keeps reading.\n        return await promise.catch((err: unknown) => {\n          if (onParseError === \"abort\" && isParseError(err)) throw err;\n          sub.context.logger.debug(\n            { err, path: filePath, adapter: \"csv\" },\n            \"csv adapter: pipeline failed for exchange; continuing\",\n          );\n          return undefined as never;\n        });\n      },\n    });\n  };\n\n  private async subscribeChunked(\n    sub: Subscription<CsvData | CsvRow>,\n    Papa: ReturnType<typeof ensurePapaparse>,\n    parseOptions: {\n      header: boolean;\n      delimiter: string;\n      quoteChar: string;\n      skipEmptyLines: boolean;\n    },\n    onParseError: OnParseError,\n  ): Promise<void> {\n    if (sub.signal.aborted) return;\n\n    const filePath = this.options.path;\n    if (typeof filePath !== \"string\") {\n      throw staticSourcePathError(\"csv\");\n    }\n\n    const encoding = this.options.encoding || \"utf-8\";\n\n    return new Promise<void>((resolve, reject) => {\n      const stream = createReadStream(filePath, { encoding });\n      let rowNumber = 0;\n      let aborted = false;\n      let settled = false;\n\n      const settle = (fn: () => void) => {\n        if (!settled) {\n          settled = true;\n          fn();\n        }\n      };\n\n      const onAbort = () => {\n        aborted = true;\n        stream.destroy();\n        settle(() => resolve());\n      };\n      sub.signal.addEventListener(\"abort\", onAbort, {\n        once: true,\n      });\n\n      Papa.parse(stream, {\n        header: parseOptions.header,\n        delimiter: parseOptions.delimiter,\n        quoteChar: parseOptions.quoteChar,\n        skipEmptyLines: parseOptions.skipEmptyLines,\n        step: (\n          results: { data: CsvRow; errors: Array<{ message: string }> },\n          parser: {\n            pause: () => void;\n            resume: () => void;\n            abort: () => void;\n          },\n        ) => {\n          if (aborted) {\n            parser.abort();\n            return;\n          }\n\n          rowNumber++;\n          const currentRow = rowNumber;\n          const rowErrors = results.errors;\n          const headers: ExchangeHeaders = {\n            [CsvHeaders.ROW]: currentRow,\n            [CsvHeaders.PATH]: filePath,\n          } as ExchangeHeaders;\n\n          parser.pause();\n\n          // Only attach a parse callback when the row actually has errors.\n          // Clean rows take the normal handler path with no synthetic parse\n          // step so we do not emit a no-op `route:step:started`/`route:step:completed`\n          // for every valid row in a 1M-row CSV.\n          const hasRowErrors = rowErrors.length > 0;\n          const callPromise = hasRowErrors\n            ? sub.emit({\n                message: results.data as CsvRow,\n                headers,\n                parse: () => {\n                  const firstError = rowErrors[0];\n                  throw new Error(\n                    `csv adapter: parse error at row ${currentRow}: ${firstError.message}`,\n                  );\n                },\n                parseFailureMode: onParseError,\n              })\n            : sub.emit({ message: results.data as CsvRow, headers });\n\n          callPromise\n            .then(() => {\n              if (!aborted) parser.resume();\n            })\n            .catch((err: unknown) => {\n              // 'abort' is parse-specific: only RC5016 should tear\n              // down the stream. A downstream destination error must\n              // NOT abort even when onParseError === 'abort'; the\n              // route boundary has already emitted route:exchange:failed\n              // and we just continue.\n              if (onParseError === \"abort\" && isParseError(err)) {\n                parser.abort();\n                settle(() => reject(err));\n                return;\n              }\n              sub.context.logger.debug(\n                { err, path: filePath, row: currentRow, adapter: \"csv\" },\n                \"csv adapter: pipeline failed for row; continuing\",\n              );\n              if (!aborted) parser.resume();\n            });\n        },\n        complete: () => {\n          sub.signal.removeEventListener(\"abort\", onAbort);\n          settle(() => resolve());\n        },\n        error: (err: Error) => {\n          sub.signal.removeEventListener(\"abort\", onAbort);\n          if (aborted) {\n            settle(() => resolve());\n            return;\n          }\n          try {\n            throwFileError(\"csv\", filePath, err);\n          } catch (wrapped) {\n            settle(() => reject(wrapped));\n          }\n        },\n      });\n    });\n  }\n}\n","import * as fsp from \"node:fs/promises\";\nimport * as nodePath from \"node:path\";\nimport type { Destination, CallableDestination } from \"../../operations/to.ts\";\nimport type { Exchange } from \"../../exchange.ts\";\nimport type { CsvFileOptions } from \"./types.ts\";\nimport { file } from \"../file/index.ts\";\nimport { ensurePapaparse } from \"./shared.ts\";\nimport { assertExclusiveSendBehavior } from \"../shared/file-role-guards.ts\";\n\n/**\n * Record separator Papa emits between rows. `CsvFileOptions` exposes no\n * newline setting, so every chunk this adapter formats uses Papa's default\n * (CRLF, per RFC 4180). Appends to a file that already uses LF follow the\n * file instead, so a given file never ends up mixing the two.\n */\nconst DEFAULT_RECORD_SEPARATOR = \"\\r\\n\";\n\n/**\n * Tail of the in-flight append chain per resolved path, shared across every\n * `CsvDestinationAdapter` in the process.\n *\n * An append is a read-then-write (does the file have content? then write the\n * header or not, and does it end mid-record?), so two concurrent appends to\n * one file could both observe \"empty\" and both emit a header. Keying the lock\n * on the path rather than on the adapter covers the case where two routes,\n * each with their own `csv()` instance, target the same file. A writer in\n * another process is still outside our reach.\n *\n * Entries are removed once their chain drains, so a route with per-exchange\n * dynamic paths does not accumulate one entry per path forever.\n */\nconst appendLocks = new Map<string, Promise<void>>();\n\n/**\n * What the append target looks like at its tail, read before formatting so\n * the chunk can be terminated (and if needed prefixed) to keep row boundaries\n * intact.\n */\ninterface AppendTail {\n  /** File exists and is non-empty (so a header would be a duplicate). */\n  hasContent: boolean;\n  /** File ends mid-record, so the new chunk needs a leading separator. */\n  needsSeparator: boolean;\n  /** Separator the file already uses, when its last record is terminated. */\n  separator: string | undefined;\n}\n\n/**\n * Read the end of the append target to classify its tail. Reads a handful of\n * bytes rather than the file so appending to a large log stays cheap.\n *\n * The tail is decoded with the file's own encoding before the newline check:\n * in `utf16le` / `ucs2` a newline is two bytes (`0A 00`), so a raw byte\n * comparison would read the trailing NUL as \"unterminated\" and splice a blank\n * row into every append. Four bytes cover a CRLF in either width.\n *\n * @param filePath - Resolved path of the file about to be appended to\n * @param encoding - Encoding the adapter writes with\n */\nasync function inspectAppendTail(\n  filePath: string,\n  encoding: BufferEncoding,\n): Promise<AppendTail> {\n  const missing: AppendTail = {\n    hasContent: false,\n    needsSeparator: false,\n    separator: undefined,\n  };\n  let handle;\n  try {\n    handle = await fsp.open(filePath, \"r\");\n  } catch (error) {\n    // Only a genuinely absent file means \"start fresh\". Anything else\n    // (permissions, a directory in the way) must surface: treating it as\n    // missing would write a second header into a file that already has one.\n    if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n    return missing;\n  }\n  try {\n    const { size } = await handle.stat();\n    if (size === 0) return missing;\n    const length = Math.min(4, size);\n    const bytes = Buffer.alloc(length);\n    await handle.read(bytes, 0, length, size - length);\n    const tail = bytes.toString(encoding);\n    if (!tail.endsWith(\"\\n\")) {\n      // Ends mid-record: whoever wrote it left the row unterminated.\n      return { hasContent: true, needsSeparator: true, separator: undefined };\n    }\n    return {\n      hasContent: true,\n      needsSeparator: false,\n      separator: tail.endsWith(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\",\n    };\n  } finally {\n    await handle.close();\n  }\n}\n\n/**\n * CsvDestinationAdapter implements the Destination (send) role for CSV files.\n *\n * `send` is strictly void: it formats the exchange body (object or array of\n * objects) as CSV and writes it (overwrite by default, `append: true` to\n * append with header handling, `delete: true` to remove the file). Reading\n * lives on the fetch role (CsvEnricherAdapter).\n */\nexport class CsvDestinationAdapter implements Destination<unknown> {\n  readonly adapterId = \"routecraft.adapter.csv\";\n\n  constructor(private readonly options: CsvFileOptions) {\n    assertExclusiveSendBehavior(\"csv\", options);\n  }\n\n  send: CallableDestination<unknown> = async (exchange) => {\n    const resolvedPath =\n      typeof this.options.path === \"function\"\n        ? this.options.path(exchange)\n        : this.options.path;\n\n    // Delete behavior: delegate to the file adapter (no format). Idempotent.\n    if (this.options.delete) {\n      await file({ path: resolvedPath, delete: true }).send(exchange);\n      return;\n    }\n\n    if (!this.options.append) {\n      await this.write(exchange, resolvedPath);\n      return;\n    }\n\n    // Serialise appends to this path: the previous append must have landed\n    // before the next one inspects the file's tail. Keyed on the absolute\n    // path so two adapters pointed at the same file share one chain.\n    const lockKey = nodePath.resolve(resolvedPath);\n    const previous = appendLocks.get(lockKey) ?? Promise.resolve();\n    const current = previous\n      // A failed append must not poison the chain for the next writer, so the\n      // link the chain holds swallows the rejection; `current` below still\n      // rethrows it to this caller.\n      .catch(() => undefined)\n      .then(() => this.write(exchange, resolvedPath));\n    const queued = current.catch(() => undefined);\n    appendLocks.set(lockKey, queued);\n    try {\n      await current;\n    } finally {\n      // Drop the entry only when nothing queued behind this append, so a\n      // route writing per-exchange dynamic paths keeps the map at the size of\n      // the in-flight set rather than of every path it has ever written.\n      if (appendLocks.get(lockKey) === queued) appendLocks.delete(lockKey);\n    }\n  };\n\n  private async write(\n    exchange: Exchange<unknown>,\n    resolvedPath: string,\n  ): Promise<void> {\n    const Papa = ensurePapaparse();\n    const {\n      header = true,\n      delimiter = \",\",\n      quoteChar = '\"',\n      skipEmptyLines = true,\n      append = false,\n      encoding = \"utf-8\",\n    } = this.options;\n\n    // Extract data from exchange body\n    let data: Array<Record<string, unknown>>;\n    if (Array.isArray(exchange.body)) {\n      data = exchange.body;\n    } else if (exchange.body && typeof exchange.body === \"object\") {\n      data = [exchange.body as Record<string, unknown>];\n    } else {\n      throw new Error(\n        \"csv adapter: send role requires exchange body to be an object or array of objects\",\n      );\n    }\n\n    // Inspect the tail once: it decides both whether a header would duplicate\n    // an existing one and whether the file's last record is terminated.\n    const tail: AppendTail = append\n      ? await inspectAppendTail(resolvedPath, encoding)\n      : { hasContent: false, needsSeparator: false, separator: undefined };\n\n    const includeHeader = header && !(append && tail.hasContent);\n    let csvContent: string;\n    try {\n      csvContent = Papa.unparse(data, {\n        header: includeHeader,\n        delimiter,\n        quotes: false,\n        quoteChar,\n        skipEmptyLines,\n      });\n    } catch (err) {\n      const message = err instanceof Error ? err.message : String(err);\n      throw new Error(`csv adapter: failed to format CSV: ${message}`);\n    }\n\n    // Papa.unparse emits no trailing newline, so an append would splice the\n    // new first record onto the previous last one (\"a,b\" + \"c,d\" =>\n    // \"a,bc,d\"). Two boundaries need a separator: the one this chunk leaves\n    // behind for the NEXT append, and the one an already-unterminated file\n    // left behind for this one. Follow the separator the file already uses so\n    // it never ends up mixing CRLF and LF.\n    if (append && csvContent.length > 0) {\n      const separator = tail.separator ?? DEFAULT_RECORD_SEPARATOR;\n      if (tail.needsSeparator) csvContent = separator + csvContent;\n      if (!csvContent.endsWith(\"\\n\")) csvContent += separator;\n    }\n\n    const fileAdapter = file({\n      path: resolvedPath,\n      encoding,\n      append,\n      createDirs: this.options.createDirs || false,\n    });\n\n    const fileExchange = {\n      ...exchange,\n      body: csvContent,\n    };\n    await fileAdapter.send(fileExchange);\n  }\n}\n","import type { Enricher, CallableEnricher } from \"../../operations/enrich.ts\";\nimport type { CsvFileOptions, CsvData } from \"./types.ts\";\nimport { FileEnricherAdapter } from \"../file/enricher.ts\";\nimport { parseCsv } from \"./shared.ts\";\n\n/**\n * CsvEnricherAdapter implements the Enricher (fetch) role for CSV files:\n * `fetch` reads the resolved path, parses it, and returns the rows, so\n * `.enrich(csv({ path }))` pulls a CSV into the route mid-flow. Parse\n * failures throw (the route boundary surfaces them as `route:exchange:failed`);\n * the `onParseError` lifecycle controls apply to the source role only.\n */\nexport class CsvEnricherAdapter implements Enricher<unknown, CsvData> {\n  readonly adapterId = \"routecraft.adapter.csv\";\n\n  constructor(private readonly options: CsvFileOptions) {}\n\n  /** Fetch implementation: read the resolved path and return the parsed rows. */\n  fetch: CallableEnricher<unknown, CsvData> = async (exchange, ctx) => {\n    const resolvedPath =\n      typeof this.options.path === \"function\"\n        ? this.options.path(exchange)\n        : this.options.path;\n    // Only the fetch slot is needed; constructing the full file() facade\n    // (three role instances plus tagging) per exchange would be waste on\n    // this hot path.\n    const content = await new FileEnricherAdapter({\n      path: resolvedPath,\n      encoding: this.options.encoding ?? \"utf-8\",\n    }).fetch(exchange, ctx);\n    return parseCsv(content, this.options) as CsvData;\n  };\n}\n","import type { Transformer } from \"../../operations/transform.ts\";\nimport type { CsvTransformerOptions } from \"./types.ts\";\nimport { parseCsv } from \"./shared.ts\";\nimport { getBodyText } from \"../shared/body-text.ts\";\n\n/**\n * CsvTransformerAdapter parses a CSV string already in the exchange body into\n * rows. It is the decode counterpart to the file source: use it when the CSV\n * text arrived in-memory (e.g. an HTTP response) rather than from disk.\n *\n * Requires `papaparse` to be installed as a peer dependency.\n */\nexport class CsvTransformerAdapter<\n  T = unknown,\n  R = unknown,\n> implements Transformer<T, R> {\n  readonly adapterId = \"routecraft.adapter.csv\";\n\n  constructor(private readonly options: CsvTransformerOptions<T, R>) {}\n\n  transform(body: T): R {\n    const text = getBodyText(body, this.options.from, \"csv\");\n    const rows = parseCsv(text, this.options);\n    const to = this.options.to;\n    if (to) return to(body, rows);\n    return rows as unknown as R;\n  }\n}\n","import type { Source } from \"../../operations/from.ts\";\nimport type { Destination } from \"../../operations/to.ts\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport type { Transformer } from \"../../operations/transform.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\nimport type {\n  CsvOptions,\n  CsvFileOptions,\n  CsvTransformerOptions,\n  CsvData,\n  CsvRow,\n} from \"./types.ts\";\nimport { CsvSourceAdapter } from \"./source.ts\";\nimport { CsvDestinationAdapter } from \"./destination.ts\";\nimport { CsvEnricherAdapter } from \"./enricher.ts\";\nimport { CsvTransformerAdapter } from \"./transformer.ts\";\nimport { selectsFileRole } from \"../shared/file-role-guards.ts\";\n\n/**\n * Combined CSV file adapter type: all three roles on one honest type. The\n * operation keyword selects the role (`.from()` subscribes, `.to()` sends,\n * `.enrich()` fetches).\n */\nexport type CsvAdapter = Source<CsvData> &\n  Destination<unknown> &\n  Enricher<unknown, CsvData> & { readonly adapterId: string };\n\n/**\n * Chunked CSV adapter: identical to {@link CsvAdapter} except the source\n * emits one exchange per row (`CsvRow`) instead of one `CsvData` array. The\n * send/fetch roles are unchanged (the chunked option concerns the subscribe\n * role only).\n */\nexport type CsvChunkedAdapter = Source<CsvRow> &\n  Destination<unknown> &\n  Enricher<unknown, CsvData> & { readonly adapterId: string };\n\n/**\n * Creates a CSV adapter in chunked source mode: one exchange per row with\n * CSV_ROW and CSV_PATH headers. `chunked` must be the literal `true`; a\n * widened boolean is a compile error, so dynamic chunking is an explicit\n * branch at the call site.\n *\n * Requires `papaparse` to be installed as a peer dependency.\n *\n * @param options - CSV file options with chunked: true\n * @returns The combined adapter with a per-row Source\n */\nexport function csv(\n  options: CsvFileOptions & { chunked: true },\n): CsvChunkedAdapter;\n/**\n * Creates a CSV adapter for a CSV file. One factory, one type; the POSITION\n * in the route selects the role:\n *\n * - **`.from(csv({ path }))`** reads + parses the file and emits the rows.\n * - **`.to(csv({ path }))`** formats the exchange body as CSV and writes it\n *   (overwrite; `append: true` appends; `delete: true` removes the file).\n *   The body flows through unchanged.\n * - **`.enrich(csv({ path }))`** reads + parses mid-route; the rows replace\n *   the body (pass an aggregator such as `only()` to merge instead).\n *\n * Requires `papaparse` to be installed as a peer dependency.\n *\n * @param options - CSV path, parsing/formatting options\n * @returns The combined Source + Destination + Enricher adapter\n *\n * @example\n * ```typescript\n * // Read CSV file as source\n * .from(csv({ path: './data.csv', header: true }))\n *\n * // Read mid-route (the parsed rows replace the body)\n * .enrich(csv({ path: './data.csv' }))\n *\n * // Write to CSV file\n * .to(csv({ path: './output.csv', header: true }))\n *\n * // Append to CSV file\n * .to(csv({ path: './log.csv', append: true }))\n *\n * // Delete a CSV file (idempotent)\n * .to(csv({ path: (ex) => ex.body.processedPath, delete: true }))\n * ```\n */\nexport function csv(options: CsvFileOptions & { chunked?: false }): CsvAdapter;\n/**\n * Creates a CSV transformer that parses a CSV string already in the body.\n *\n * Requires `papaparse` to be installed as a peer dependency.\n *\n * @param options - Transformer options (`from`, `to`, parsing options); no `path`\n * @returns A Transformer\n */\nexport function csv<T = unknown, R = unknown>(\n  options?: CsvTransformerOptions<T, R>,\n): Transformer<T, R> & { readonly adapterId: string };\nexport function csv<T = unknown, R = unknown>(\n  options: CsvOptions<T, R> = {},\n):\n  | (Transformer<T, R> & { readonly adapterId: string })\n  | CsvChunkedAdapter\n  | CsvAdapter {\n  const args = factoryArgs(options);\n\n  // Transformer role: no path means parse a CSV string already in the body.\n  // The `.transform()` keyword enforces the category, so dropping `path`\n  // fails loudly at `.from()` / `.to()` (no subscribe/send slot) instead of\n  // silently changing the adapter's kind.\n  if (!selectsFileRole(\"csv\", options)) {\n    const transformer = new CsvTransformerAdapter<T, R>(\n      options as CsvTransformerOptions<T, R>,\n    );\n    return tagAdapter(\n      {\n        adapterId: \"routecraft.adapter.csv\",\n        transform: transformer.transform.bind(transformer),\n      },\n      csv,\n      args,\n    ) as Transformer<T, R> & { readonly adapterId: string };\n  }\n\n  const fileOptions = options as CsvFileOptions;\n  const source = new CsvSourceAdapter(fileOptions);\n  const destination = new CsvDestinationAdapter(fileOptions);\n  const enricher = new CsvEnricherAdapter(fileOptions);\n  return tagAdapter(\n    {\n      adapterId: \"routecraft.adapter.csv\",\n      subscribe: source.subscribe,\n      send: destination.send,\n      fetch: enricher.fetch,\n    },\n    csv,\n    args,\n  ) as CsvChunkedAdapter | CsvAdapter;\n}\n\n// Re-export types\nexport type {\n  CsvOptions,\n  CsvTransformerOptions,\n  CsvFileOptions,\n  CsvRow,\n  CsvData,\n} from \"./types.ts\";\nexport { CsvHeaders } from \"./types.ts\";\n","import { loadOptionalPeer } from \"../shared/optional-peer.ts\";\nimport type { XmlBuildOptions, XmlData, XmlParseOptions } from \"./types.ts\";\n\n// Memoise the loaded fast-xml-parser module so high-volume xml() calls do not\n// re-pay the dynamic-import lookup or re-allocate the loadOptionalPeer\n// closures. The promise is shared across all callers, so the import happens at\n// most once per process. A rejected promise is intentionally cached too: a\n// genuinely missing peer cannot appear mid-process, so retrying would only\n// reproduce the same RC5017 with the same install hint.\nlet fxpPromise: Promise<typeof import(\"fast-xml-parser\")> | null = null;\n\n/**\n * Load fast-xml-parser as an optional peer dependency. Missing-package\n * failures surface as RC5017 with an install hint.\n *\n * Source mode calls this eagerly (before the first emit) so a missing peer\n * surfaces as an honest RC5017 up front, rather than being deferred into the\n * per-item parse callback where it would be rewrapped as an RC5016 parse\n * failure (and silently swallowed under `onParseError: 'drop'`).\n *\n * @internal Not exported from the package public API.\n */\nexport function getFastXmlParser(): Promise<typeof import(\"fast-xml-parser\")> {\n  fxpPromise ??= loadOptionalPeer(() => import(\"fast-xml-parser\"), {\n    consumer: \"xml adapter\",\n    packageName: \"fast-xml-parser\",\n  });\n  return fxpPromise;\n}\n\n/**\n * Validate and parse an XML string into a plain object.\n *\n * The content is validated first so malformed XML throws a descriptive error\n * (fast-xml-parser's parser is otherwise lenient and would silently produce a\n * partial object). Source / read-destination modes surface the throw as an\n * RC5016 parse failure via the synthetic parse step.\n *\n * @internal Not exported from the package public API.\n */\nexport async function parseXml(\n  content: string,\n  options: XmlParseOptions,\n): Promise<XmlData> {\n  const { XMLParser, XMLValidator } = await getFastXmlParser();\n\n  const validation = XMLValidator.validate(content);\n  if (validation !== true) {\n    const { msg, line, col } = validation.err;\n    throw new Error(\n      `xml adapter: parse error at line ${line}, column ${col}: ${msg}`,\n    );\n  }\n\n  const parser = new XMLParser({\n    ignoreAttributes: options.ignoreAttributes ?? false,\n    attributeNamePrefix: options.attributeNamePrefix ?? \"@_\",\n    textNodeName: options.textNodeName ?? \"#text\",\n    parseAttributeValue: options.parseAttributeValue ?? false,\n    parseTagValue: options.parseTagValue ?? true,\n    trimValues: options.trimValues ?? true,\n    removeNSPrefix: options.removeNSPrefix ?? false,\n    ...(options.cdataPropName !== undefined\n      ? { cdataPropName: options.cdataPropName }\n      : {}),\n    // Our public `isArray` types the jPath argument as a plain string (the\n    // documented common value) for DX. fast-xml-parser's own type widens that\n    // argument to a jPath-or-matcher union, so widen the param to `unknown` at\n    // the boundary to bridge the two without leaking the peer's types into our\n    // public API (which must resolve even when the peer is not installed).\n    ...(options.isArray !== undefined\n      ? {\n          isArray: options.isArray as (\n            tagName: string,\n            jPath: unknown,\n            isLeafNode: boolean,\n            isAttribute: boolean,\n          ) => boolean,\n        }\n      : {}),\n  });\n\n  return parser.parse(content) as XmlData;\n}\n\n/**\n * Build an XML string from a plain object.\n *\n * @internal Not exported from the package public API.\n */\nexport async function buildXml(\n  value: unknown,\n  options: XmlParseOptions & XmlBuildOptions,\n): Promise<string> {\n  const { XMLBuilder } = await getFastXmlParser();\n\n  const builder = new XMLBuilder({\n    ignoreAttributes: options.ignoreAttributes ?? false,\n    attributeNamePrefix: options.attributeNamePrefix ?? \"@_\",\n    textNodeName: options.textNodeName ?? \"#text\",\n    format: options.format ?? false,\n    indentBy: options.indentBy ?? \"  \",\n    suppressEmptyNode: options.suppressEmptyNode ?? false,\n    ...(options.cdataPropName !== undefined\n      ? { cdataPropName: options.cdataPropName }\n      : {}),\n  });\n\n  return builder.build(value) as string;\n}\n","import type { Source, CallableSource } from \"../../operations/from.ts\";\nimport type { XmlData, XmlFileOptions } from \"./types.ts\";\nimport { file } from \"../file/index.ts\";\nimport { getFastXmlParser, parseXml } from \"./shared.ts\";\nimport { DEFAULT_ON_PARSE_ERROR, isParseError } from \"../shared/parse.ts\";\nimport { staticSourcePathError } from \"../shared/file-role-guards.ts\";\n\n/**\n * XmlSourceAdapter reads XML files and parses them via fast-xml-parser.\n *\n * Emits a single exchange whose body is the parsed object. Parsing is deferred\n * to the route's pipeline by passing a `parse` callback to `emit`: the runtime\n * applies it as a synthetic first step so a malformed XML file becomes an\n * observable pipeline event:\n *\n * | `onParseError` | Lifecycle on bad XML                                          |\n * |----------------|---------------------------------------------------------------|\n * | `'fail'` (default) | `route:exchange:failed` (or `route:error:caught` if `.error()` recovers) |\n * | `'abort'`      | `route:exchange:failed`, then source rejects and `context:error` fires |\n * | `'drop'`       | `route:exchange:dropped` with `reason: \"parse-failed\"`              |\n */\nexport class XmlSourceAdapter implements Source<XmlData> {\n  readonly adapterId = \"routecraft.adapter.xml\";\n\n  constructor(private readonly options: XmlFileOptions) {}\n\n  subscribe: CallableSource<XmlData> = async (sub) => {\n    const onParseError = this.options.onParseError ?? DEFAULT_ON_PARSE_ERROR;\n\n    // Resolve the optional peer up front so a missing install fails as RC5017\n    // (with an install hint) rather than being deferred into the per-item\n    // parse callback, where the synthetic parse step would rewrap it as an\n    // RC5016 parse failure and `onParseError: 'drop'` would swallow it\n    // silently. Mirrors csv's eager ensurePapaparse(). The promise is\n    // memoised, so the later parse re-await is free.\n    await getFastXmlParser();\n\n    const filePath = this.options.path;\n    if (typeof filePath !== \"string\") {\n      throw staticSourcePathError(\"xml\");\n    }\n\n    const fileAdapter = file({\n      path: filePath,\n      encoding: this.options.encoding || \"utf-8\",\n    });\n\n    const parseFn = (raw: unknown): Promise<XmlData> =>\n      parseXml(raw as string, this.options);\n\n    // Delegate to the file source with a derived subscription whose emit\n    // attaches the XML parse to the raw file content.\n    await fileAdapter.subscribe({\n      ...sub,\n      emit: async (msg) => {\n        // The raw file content is a string pre-parse; the synthetic parse\n        // step narrows it to XmlData (the standard pre-parse type caveat).\n        const promise = sub.emit({\n          message: msg.message as unknown as XmlData,\n          ...(msg.headers ? { headers: msg.headers } : {}),\n          parse: parseFn,\n          parseFailureMode: onParseError,\n        });\n        // 'abort' is parse-specific: only RC5016 should tear down the source.\n        // A downstream destination error must NOT propagate as an abort signal\n        // even when onParseError === 'abort'. Every other failure is\n        // debug-logged and swallowed (matching json/csv) so the source keeps\n        // reading.\n        return await promise.catch((err: unknown) => {\n          if (onParseError === \"abort\" && isParseError(err)) throw err;\n          sub.context.logger.debug(\n            { err, path: filePath, adapter: \"xml\" },\n            \"xml adapter: pipeline failed for file; continuing\",\n          );\n          return undefined as never;\n        });\n      },\n    });\n  };\n}\n","import type { Destination, CallableDestination } from \"../../operations/to.ts\";\nimport type { XmlFileOptions } from \"./types.ts\";\nimport { file } from \"../file/index.ts\";\nimport { buildXml } from \"./shared.ts\";\n\n/**\n * XmlDestinationAdapter implements the Destination (send) role for XML files.\n *\n * `send` is strictly void: it builds the exchange body (a plain object) into\n * an XML document and writes it (overwrite; `delete: true` removes the file\n * instead). Reading lives on the fetch role (XmlEnricherAdapter).\n */\nexport class XmlDestinationAdapter implements Destination<unknown> {\n  readonly adapterId = \"routecraft.adapter.xml\";\n\n  constructor(private readonly options: XmlFileOptions) {}\n\n  send: CallableDestination<unknown> = async (exchange) => {\n    const resolvedPath =\n      typeof this.options.path === \"function\"\n        ? this.options.path(exchange)\n        : this.options.path;\n\n    // Delete behavior: delegate to the file adapter (no build). Idempotent.\n    if (this.options.delete) {\n      await file({ path: resolvedPath, delete: true }).send(exchange);\n      return;\n    }\n\n    // Write behavior: the body must be a single object describing the XML\n    // document. Arrays are rejected: they have no single root element, so the\n    // builder would emit numerically-named sibling tags (e.g. <0>...</0>) and\n    // an invalid document rather than failing.\n    if (\n      exchange.body === null ||\n      typeof exchange.body !== \"object\" ||\n      Array.isArray(exchange.body)\n    ) {\n      throw new Error(\n        \"xml adapter: the send role requires the exchange body to be a single object representing the XML document (a single root element); arrays produce multiple root elements and an invalid document\",\n      );\n    }\n\n    // An XML document has exactly one root element. The builder emits a\n    // top-level tag for every object key, so a multi-key body like\n    // { a: {...}, b: {...} } would serialise to sibling roots (<a/><b/>) and\n    // an invalid document. Keys starting with \"?\" are the XML declaration and\n    // processing instructions (e.g. \"?xml\"), which the builder emits before\n    // the root, so they are not counted as roots.\n    const rootKeys = Object.keys(exchange.body).filter(\n      (key) => !key.startsWith(\"?\"),\n    );\n    if (rootKeys.length !== 1) {\n      throw new Error(\n        `xml adapter: the send role requires the exchange body to have exactly one root element, but found ${rootKeys.length} (${rootKeys.join(\", \") || \"none\"}); wrap your data in a single root object`,\n      );\n    }\n\n    let xmlString: string;\n    try {\n      xmlString = await buildXml(exchange.body, this.options);\n    } catch (err) {\n      const message = err instanceof Error ? err.message : String(err);\n      throw new Error(`xml adapter: failed to build XML: ${message}`);\n    }\n\n    const fileAdapter = file({\n      path: resolvedPath,\n      encoding: this.options.encoding || \"utf-8\",\n      createDirs: this.options.createDirs || false,\n    });\n\n    await fileAdapter.send({\n      ...exchange,\n      body: xmlString,\n    });\n  };\n}\n","import type { Enricher, CallableEnricher } from \"../../operations/enrich.ts\";\nimport type { XmlData, XmlFileOptions } from \"./types.ts\";\nimport { FileEnricherAdapter } from \"../file/enricher.ts\";\nimport { parseXml } from \"./shared.ts\";\n\n/**\n * XmlEnricherAdapter implements the Enricher (fetch) role for XML files:\n * `fetch` reads the resolved path, parses it, and returns the parsed object,\n * so `.enrich(xml({ path }))` pulls an XML file into the route mid-flow.\n * Parse failures throw (the route boundary surfaces them as\n * `route:exchange:failed`); the `onParseError` lifecycle controls apply to the\n * source role only.\n *\n * @template T - Parsed object type (caller-asserted, e.g. `xml<MyDoc>(...)`)\n */\nexport class XmlEnricherAdapter<T = XmlData> implements Enricher<unknown, T> {\n  readonly adapterId = \"routecraft.adapter.xml\";\n\n  constructor(private readonly options: XmlFileOptions) {}\n\n  /** Fetch implementation: read the resolved path and return the parsed object. */\n  fetch: CallableEnricher<unknown, T> = async (exchange, ctx) => {\n    const resolvedPath =\n      typeof this.options.path === \"function\"\n        ? this.options.path(exchange)\n        : this.options.path;\n    // Only the fetch slot is needed; skip the full file() facade on the\n    // hot path.\n    const content = await new FileEnricherAdapter({\n      path: resolvedPath,\n      encoding: this.options.encoding ?? \"utf-8\",\n    }).fetch(exchange, ctx);\n    return (await parseXml(content, this.options)) as T;\n  };\n}\n","import type { Transformer } from \"../../operations/transform.ts\";\nimport type { XmlData, XmlTransformerOptions } from \"./types.ts\";\nimport { parseXml } from \"./shared.ts\";\nimport { getBodyText } from \"../shared/body-text.ts\";\n\n/**\n * XmlTransformerAdapter parses an XML string already in the exchange body into\n * a plain object. It is the decode counterpart to the file source: use it when\n * the XML text arrived in-memory (e.g. an HTTP response) rather than from disk.\n *\n * Requires `fast-xml-parser` to be installed as an optional peer dependency.\n */\nexport class XmlTransformerAdapter<\n  T = unknown,\n  R = unknown,\n> implements Transformer<T, R> {\n  readonly adapterId = \"routecraft.adapter.xml\";\n\n  constructor(private readonly options: XmlTransformerOptions<T, R>) {}\n\n  async transform(body: T): Promise<R> {\n    const text = getBodyText(body, this.options.from, \"xml\");\n    const parsed: XmlData = await parseXml(text, this.options);\n    const to = this.options.to;\n    if (to) return to(body, parsed);\n    return parsed as unknown as R;\n  }\n}\n","import type { Source } from \"../../operations/from.ts\";\nimport type { Destination } from \"../../operations/to.ts\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport type { Transformer } from \"../../operations/transform.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\nimport { selectsFileRole } from \"../shared/file-role-guards.ts\";\nimport type {\n  XmlData,\n  XmlFileOptions,\n  XmlOptions,\n  XmlTransformerOptions,\n} from \"./types.ts\";\nimport { XmlSourceAdapter } from \"./source.ts\";\nimport { XmlDestinationAdapter } from \"./destination.ts\";\nimport { XmlEnricherAdapter } from \"./enricher.ts\";\nimport { XmlTransformerAdapter } from \"./transformer.ts\";\n\n/**\n * Combined XML file adapter type: all three roles on one honest type. The\n * operation keyword selects the role (`.from()` subscribes, `.to()` sends,\n * `.enrich()` fetches). The parsed object is typed `T` (default `XmlData`);\n * pass it explicitly (`xml<MyDoc>(...)`) for a typed body.\n *\n * @template T - Parsed object type (caller-asserted)\n */\nexport type XmlAdapter<T = XmlData> = Source<T> &\n  Destination<unknown> &\n  Enricher<unknown, T> & { readonly adapterId: string };\n\n/**\n * Creates an XML adapter.\n *\n * **Transformer role** (no `path` option): parses an XML string already in\n * the body.\n *\n * **File roles** (`path` present); the POSITION in the route selects the role:\n * - **`.from(xml({ path }))`** reads + parses the file and emits the object.\n * - **`.to(xml({ path }))`** builds the body object into an XML document and\n *   writes it (`delete: true` removes the file instead). The body flows\n *   through unchanged.\n * - **`.enrich(xml({ path }))`** reads + parses mid-route; the object\n *   replaces the body (pass an aggregator such as `only()` to merge instead).\n *\n * Requires `fast-xml-parser` to be installed as an optional peer dependency.\n *\n * @param options - Transformer options (no `path`) or file options\n * @returns A Transformer (no path) or the combined file adapter (path)\n *\n * @example\n * ```typescript\n * // Parse an XML string already in the body (transformer role)\n * .transform(xml({ from: (b) => b.body }))\n *\n * // Read an XML file as a source\n * .from(xml({ path: './data.xml' }))\n *\n * // Read mid-route (the parsed object replaces the body)\n * .enrich(xml({ path: './data.xml' }), only((doc) => doc, 'doc'))\n *\n * // Write to an XML file (pretty-printed)\n * .to(xml({ path: './output.xml', format: true }))\n *\n * // Delete an XML file (idempotent)\n * .to(xml({ path: (ex) => ex.body.processedPath, delete: true }))\n * ```\n */\nexport function xml<T = XmlData>(options: XmlFileOptions): XmlAdapter<T>;\nexport function xml<T = unknown, R = unknown>(\n  options?: XmlTransformerOptions<T, R>,\n): Transformer<T, R> & { readonly adapterId: string };\nexport function xml<T = unknown, R = unknown>(\n  options: XmlOptions<T, R> = {},\n): (Transformer<T, R> & { readonly adapterId: string }) | XmlAdapter {\n  const args = factoryArgs(options);\n\n  // Transformer role: no path means parse an XML string already in the body.\n  if (!selectsFileRole(\"xml\", options)) {\n    const transformer = new XmlTransformerAdapter<T, R>(\n      options as XmlTransformerOptions<T, R>,\n    );\n    return tagAdapter(\n      {\n        adapterId: \"routecraft.adapter.xml\",\n        transform: transformer.transform.bind(transformer),\n      },\n      xml,\n      args,\n    ) as Transformer<T, R> & { readonly adapterId: string };\n  }\n\n  const fileOptions = options as XmlFileOptions;\n  const source = new XmlSourceAdapter(fileOptions);\n  const destination = new XmlDestinationAdapter(fileOptions);\n  const enricher = new XmlEnricherAdapter(fileOptions);\n  return tagAdapter(\n    {\n      adapterId: \"routecraft.adapter.xml\",\n      subscribe: source.subscribe,\n      send: destination.send,\n      fetch: enricher.fetch,\n    },\n    xml,\n    args,\n  ) as XmlAdapter;\n}\n\n// Re-export types\nexport type {\n  XmlOptions,\n  XmlTransformerOptions,\n  XmlFileOptions,\n  XmlParseOptions,\n  XmlBuildOptions,\n  XmlData,\n} from \"./types.ts\";\n","import type { Exchange } from \"../../exchange.ts\";\nimport type { OnParseError } from \"../shared/parse.ts\";\n\n/**\n * Single options type for the jsonl file family: one options shape per\n * adapter, shared by all three roles (the file-family pattern shared with\n * `JsonFileOptions` / `CsvFileOptions`). The operation keyword selects the\n * role; options only tune behavior within a role.\n */\nexport interface JsonlFileOptions {\n  /**\n   * File path string or function that returns the path. Function paths\n   * receive the exchange (send/fetch roles only; the source role requires a\n   * static string path).\n   */\n  path: string | ((exchange: Exchange) => string);\n\n  /**\n   * Text encoding. Default: 'utf-8'\n   */\n  encoding?: BufferEncoding;\n\n  /**\n   * When true, the source emits one exchange per line instead of a parsed\n   * array. Source role only; the send/fetch roles are identical under\n   * chunked. Each chunked exchange includes `JsonlHeaders.LINE` and\n   * `JsonlHeaders.PATH` headers.\n   * Default: false\n   */\n  chunked?: boolean;\n\n  /**\n   * Send role behavior: append lines to the file instead of overwriting it.\n   * Mutually exclusive with `delete`. Default: false (overwrite; note this\n   * changed from the pre-role-model default, which appended)\n   */\n  append?: boolean;\n\n  /**\n   * Send role behavior: delete the file instead of writing it. Idempotent:\n   * an already-absent path is a no-op. The body is unchanged. Mutually\n   * exclusive with `append`. Default: false\n   */\n  delete?: boolean;\n\n  /**\n   * Create parent directories if they don't exist (send role only).\n   * Default: false\n   */\n  createDirs?: boolean;\n\n  /**\n   * Optional reviver function passed to JSON.parse (source/fetch roles).\n   */\n  reviver?: (key: string, value: unknown) => unknown;\n\n  /**\n   * Optional replacer passed to JSON.stringify (send role).\n   * Can be a function or an array of allowed keys.\n   */\n  replacer?:\n    ((key: string, value: unknown) => unknown) | Array<string | number> | null;\n\n  /**\n   * How to handle a `JSON.parse` failure on a line (chunked mode) or any\n   * line of the file (non-chunked mode). Source mode only.\n   *\n   * - `'fail'` (default): `route:exchange:failed` fires for the bad line, or\n   *   `route:error:caught` when the route's `.error()` handler recovers it;\n   *   chunked mode continues.\n   * - `'abort'`: `route:exchange:failed` fires, then the source dies\n   *   (`context:error`).\n   * - `'drop'`: `route:exchange:dropped` fires with `reason: \"parse-failed\"`;\n   *   chunked mode continues.\n   *\n   * See `OnParseError` for full semantics.\n   *\n   * @default \"fail\"\n   */\n  onParseError?: OnParseError;\n}\n\n/**\n * Transformer-mode options (no `path`): parse a JSONL string already in the\n * body into an array.\n */\nexport interface JsonlTransformerOptions<T = unknown, R = unknown> {\n  /**\n   * Pluck the JSONL string from the body. If omitted: body is used when it's a\n   * string, or body.body when body is an object (e.g. after http()).\n   */\n  from?: (body: T) => string;\n\n  /**\n   * Where to put the parsed array. If omitted, the result replaces the entire\n   * body. Use e.g. (body, rows) => ({ ...body, rows }) to write to a sub-field.\n   */\n  to?: (body: T, result: unknown[]) => R;\n\n  /**\n   * Optional reviver passed to JSON.parse.\n   */\n  reviver?: (key: string, value: unknown) => unknown;\n}\n\nexport type JsonlOptions = JsonlFileOptions | JsonlTransformerOptions;\n\n/**\n * Header keys the JSONL source sets on chunked-mode exchanges. Keys live\n * under the reserved `routecraft.jsonl.*` namespace; the value types are\n * merged into `RoutecraftHeaders` below.\n */\nexport const JsonlHeaders = {\n  /** The 1-based line number when reading a JSONL file in chunked mode */\n  LINE: \"routecraft.jsonl.line\",\n  /** The file path when reading a JSONL file in chunked mode */\n  PATH: \"routecraft.jsonl.path\",\n} as const satisfies Record<string, `routecraft.jsonl.${string}`>;\n\ndeclare module \"@routecraft/routecraft\" {\n  interface RoutecraftHeaders {\n    /** The 1-based line number when reading a JSONL file in chunked mode */\n    [JsonlHeaders.LINE]?: number;\n    /** The file path when reading a JSONL file in chunked mode */\n    [JsonlHeaders.PATH]?: string;\n  }\n}\n","import * as fsp from \"node:fs/promises\";\nimport type { Source, CallableSource } from \"../../operations/from.ts\";\nimport type { JsonlFileOptions } from \"./types.ts\";\nimport type { ExchangeHeaders } from \"../../exchange.ts\";\nimport { JsonlHeaders } from \"./types.ts\";\nimport { forEachLine } from \"../shared/line-reader.ts\";\nimport { throwFileError } from \"../shared/fs-errors.ts\";\nimport { DEFAULT_ON_PARSE_ERROR, isParseError } from \"../shared/parse.ts\";\n\n/**\n * JsonlSourceAdapter reads JSON Lines files.\n *\n * Non-chunked: emits a single array of all parsed objects. With\n * `onParseError: 'fail'` a malformed line fails the entire array (one\n * `RC5016` covering the file) since non-chunked emits one exchange. Use\n * chunked mode for per-line `.error()` granularity.\n *\n * Chunked: emits one exchange per line with `JSONL_LINE` and `JSONL_PATH`\n * headers.\n *\n * Per-line `JSON.parse` failures are observable via the events bus:\n *\n * | `onParseError` | Lifecycle on bad line (chunked)                                  |\n * |----------------|------------------------------------------------------------------|\n * | `'fail'` (default) | `route:exchange:failed` (or `route:error:caught`); next line continues  |\n * | `'abort'`      | `route:exchange:failed` for the bad line, then source dies (`context:error`) |\n * | `'drop'`       | `route:exchange:dropped` (`reason: \"parse-failed\"`); next line continues |\n *\n * See #187.\n */\nexport class JsonlSourceAdapter<T = unknown> implements Source<T | T[]> {\n  readonly adapterId = \"routecraft.adapter.jsonl\";\n\n  // Source mode requires a static string path; the factory enforces it.\n  constructor(private readonly options: JsonlFileOptions & { path: string }) {}\n\n  subscribe: CallableSource<T | T[]> = async (sub) => {\n    if (sub.signal.aborted) return;\n\n    const {\n      path: filePath,\n      encoding = \"utf-8\",\n      chunked = false,\n      reviver,\n      onParseError = DEFAULT_ON_PARSE_ERROR,\n    } = this.options;\n\n    if (chunked) {\n      sub.ready();\n      try {\n        await forEachLine(\n          filePath,\n          encoding,\n          sub.signal,\n          async (line, lineNumber) => {\n            const trimmed = line.trim();\n            if (trimmed === \"\") return;\n\n            const headers: ExchangeHeaders = {\n              [JsonlHeaders.LINE]: lineNumber,\n              [JsonlHeaders.PATH]: filePath,\n            } as ExchangeHeaders;\n\n            // Defer parse to the synthetic pipeline step. The mode the\n            // runtime uses controls observability:\n            //   'fail'  -> route:exchange:failed; we .catch() and continue\n            //   'abort' -> route:exchange:failed; we let the rejection propagate\n            //              out of forEachLine to abort the source\n            //   'drop'  -> route:exchange:dropped; promise resolves cleanly\n            const promise = sub.emit({\n              message: trimmed as unknown as T,\n              headers,\n              parse: (raw) => JSON.parse(raw as string, reviver) as T,\n              parseFailureMode: onParseError,\n            });\n\n            await promise.catch((err: unknown) => {\n              // 'abort' is parse-specific: only RC5016 should tear\n              // down the source. Downstream destination errors must\n              // NOT propagate as an abort signal.\n              if (onParseError === \"abort\" && isParseError(err)) throw err;\n              // 'fail' / 'drop' / non-parse failures under 'abort': the\n              // route boundary already emitted the lifecycle event;\n              // debug-level avoids double-logging what runPipeline logged.\n              sub.context.logger.debug(\n                { err, path: filePath, line: lineNumber, adapter: \"jsonl\" },\n                \"jsonl adapter: pipeline failed for line; continuing\",\n              );\n            });\n          },\n        );\n      } catch (err) {\n        if (sub.signal.aborted) return;\n        // Preserve framework error codes (e.g. RC5016 from `'abort'` mode).\n        // `throwFileError` wraps as `RC5010` which would mask the original\n        // parse-error code, so re-throw RC-bearing errors as-is.\n        if (\n          typeof err === \"object\" &&\n          err !== null &&\n          \"rc\" in (err as Record<string, unknown>)\n        ) {\n          throw err;\n        }\n        throwFileError(\"jsonl\", filePath, err);\n      }\n      return;\n    }\n\n    // Non-chunked: single exchange with the full parsed array. The\n    // synthetic parse step parses ALL lines as one operation, so a single\n    // bad line fails the whole array. For per-line granularity use\n    // chunked mode.\n    const content = await fsp\n      .readFile(filePath, { encoding })\n      .catch((err) => throwFileError(\"jsonl\", filePath, err));\n\n    if (sub.signal.aborted) return;\n\n    const lines = content.split(\"\\n\");\n    const rawLines: string[] = [];\n    for (const line of lines) {\n      const trimmed = line.trim();\n      if (trimmed !== \"\") rawLines.push(trimmed);\n    }\n\n    const promise = sub.emit({\n      message: rawLines as unknown as T[],\n      parse: (raw) => (raw as string[]).map((l) => JSON.parse(l, reviver) as T),\n      parseFailureMode: onParseError,\n    });\n\n    await promise.catch((err: unknown) => {\n      // 'abort' is parse-specific: only RC5016 should tear down the\n      // source. Downstream destination errors must NOT propagate.\n      if (onParseError === \"abort\" && isParseError(err)) throw err;\n      sub.context.logger.debug(\n        { err, path: filePath, adapter: \"jsonl\" },\n        \"jsonl adapter: pipeline failed; non-chunked emits one exchange\",\n      );\n    });\n\n    sub.ready();\n  };\n}\n","import type { Destination, CallableDestination } from \"../../operations/to.ts\";\nimport type { JsonlFileOptions } from \"./types.ts\";\nimport { file } from \"../file/index.ts\";\nimport { assertExclusiveSendBehavior } from \"../shared/file-role-guards.ts\";\n\n/**\n * JsonlDestinationAdapter implements the Destination (send) role for JSON\n * Lines files.\n *\n * `send` is strictly void: it stringifies the body to JSONL (array bodies\n * write one line per element) and writes it (overwrite by default,\n * `append: true` to append, `delete: true` to remove the file). Reading\n * lives on the fetch role (JsonlEnricherAdapter).\n */\nexport class JsonlDestinationAdapter implements Destination<unknown> {\n  readonly adapterId = \"routecraft.adapter.jsonl\";\n\n  constructor(private readonly options: JsonlFileOptions) {\n    assertExclusiveSendBehavior(\"jsonl\", options);\n  }\n\n  send: CallableDestination<unknown> = async (exchange) => {\n    const {\n      path: filePath,\n      encoding = \"utf-8\",\n      append = false,\n      delete: remove = false,\n      createDirs = false,\n      replacer,\n    } = this.options;\n\n    const resolvedPath =\n      typeof filePath === \"function\" ? filePath(exchange) : filePath;\n\n    // Delete behavior: delegate to the file adapter (no stringify). Idempotent.\n    if (remove) {\n      await file({ path: resolvedPath, delete: true }).send(exchange);\n      return;\n    }\n\n    const stringify = (value: unknown): string =>\n      Array.isArray(replacer)\n        ? JSON.stringify(value, replacer)\n        : JSON.stringify(\n            value,\n            replacer as ((key: string, value: unknown) => unknown) | undefined,\n          );\n\n    let output: string;\n    if (Array.isArray(exchange.body)) {\n      output = exchange.body.map((item) => stringify(item)).join(\"\\n\") + \"\\n\";\n    } else {\n      output = stringify(exchange.body) + \"\\n\";\n    }\n\n    const fileAdapter = file({\n      path: resolvedPath,\n      encoding,\n      append,\n      createDirs,\n    });\n\n    await fileAdapter.send({ ...exchange, body: output });\n  };\n}\n","/**\n * Parse a JSON Lines string into an array of values.\n *\n * Splits on newlines, skips empty lines, and `JSON.parse`s each remaining line\n * with the optional reviver. Shared by the read-as-destination mode and the\n * transformer so both decode in-memory JSONL the same way.\n *\n * @internal Not exported from the package public API.\n */\nexport function parseJsonl<T = unknown>(\n  content: string,\n  reviver?: (key: string, value: unknown) => unknown,\n): T[] {\n  const out: T[] = [];\n  for (const line of content.split(\"\\n\")) {\n    const trimmed = line.trim();\n    if (trimmed === \"\") continue;\n    out.push(JSON.parse(trimmed, reviver) as T);\n  }\n  return out;\n}\n","import type { Enricher, CallableEnricher } from \"../../operations/enrich.ts\";\nimport type { JsonlFileOptions } from \"./types.ts\";\nimport { FileEnricherAdapter } from \"../file/enricher.ts\";\nimport { parseJsonl } from \"./shared.ts\";\n\n/**\n * JsonlEnricherAdapter implements the Enricher (fetch) role for JSON Lines\n * files: `fetch` reads the resolved path, parses every line, and returns the\n * array, so `.enrich(jsonl({ path }))` pulls a JSONL file into the route\n * mid-flow. Parse failures throw (the route boundary surfaces them as\n * `route:exchange:failed`); the `onParseError` lifecycle controls apply to the\n * source role only.\n *\n * @template T - Element type of the parsed array (caller-asserted)\n */\nexport class JsonlEnricherAdapter<T = unknown> implements Enricher<\n  unknown,\n  T[]\n> {\n  readonly adapterId = \"routecraft.adapter.jsonl\";\n\n  constructor(private readonly options: JsonlFileOptions) {}\n\n  /** Fetch implementation: read the resolved path and return the parsed array. */\n  fetch: CallableEnricher<unknown, T[]> = async (exchange, ctx) => {\n    const { path: filePath, encoding = \"utf-8\", reviver } = this.options;\n    const resolvedPath =\n      typeof filePath === \"function\" ? filePath(exchange) : filePath;\n    // Only the fetch slot is needed; skip the full file() facade on the\n    // hot path.\n    const content = await new FileEnricherAdapter({\n      path: resolvedPath,\n      encoding,\n    }).fetch(exchange, ctx);\n    return parseJsonl(content, reviver) as T[];\n  };\n}\n","import type { Transformer } from \"../../operations/transform.ts\";\nimport type { JsonlTransformerOptions } from \"./types.ts\";\nimport { parseJsonl } from \"./shared.ts\";\nimport { getBodyText } from \"../shared/body-text.ts\";\n\n/**\n * JsonlTransformerAdapter parses a JSON Lines string already in the exchange\n * body into an array. It is the decode counterpart to the file source: use it\n * when the JSONL text arrived in-memory (e.g. an HTTP response) rather than\n * from disk.\n */\nexport class JsonlTransformerAdapter<\n  T = unknown,\n  R = unknown,\n> implements Transformer<T, R> {\n  readonly adapterId = \"routecraft.adapter.jsonl\";\n\n  constructor(private readonly options: JsonlTransformerOptions<T, R>) {}\n\n  transform(body: T): R {\n    const text = getBodyText(body, this.options.from, \"jsonl\");\n    const rows = parseJsonl(text, this.options.reviver);\n    const to = this.options.to;\n    if (to) return to(body, rows);\n    return rows as unknown as R;\n  }\n}\n","import type { Source, CallableSource } from \"../../operations/from.ts\";\nimport type { Destination } from \"../../operations/to.ts\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport type { Transformer } from \"../../operations/transform.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\nimport { selectsFileRole } from \"../shared/file-role-guards.ts\";\nimport type { JsonlFileOptions, JsonlTransformerOptions } from \"./types.ts\";\nimport { JsonlSourceAdapter } from \"./source.ts\";\nimport { JsonlDestinationAdapter } from \"./destination.ts\";\nimport { JsonlEnricherAdapter } from \"./enricher.ts\";\nimport { JsonlTransformerAdapter } from \"./transformer.ts\";\n\n/**\n * Combined JSONL file adapter type: all three roles on one honest type. The\n * operation keyword selects the role (`.from()` subscribes, `.to()` sends,\n * `.enrich()` fetches).\n *\n * @template T - Element type of the parsed array (caller-asserted)\n */\nexport type JsonlAdapter<T = unknown> = Source<T[]> &\n  Destination<unknown> &\n  Enricher<unknown, T[]> & { readonly adapterId: string };\n\n/**\n * Chunked JSONL adapter: identical to {@link JsonlAdapter} except the source\n * emits one exchange per line (`T`) instead of one `T[]` array. The\n * send/fetch roles are unchanged (the chunked option concerns the subscribe\n * role only).\n *\n * @template T - Element type of each emitted line (caller-asserted)\n */\nexport type JsonlChunkedAdapter<T = unknown> = Source<T> &\n  Destination<unknown> &\n  Enricher<unknown, T[]> & { readonly adapterId: string };\n\n/**\n * Creates a JSONL adapter in chunked source mode: one exchange per line with\n * `JsonlHeaders.LINE` and `JsonlHeaders.PATH` headers. `chunked` must be the\n * literal `true`; a widened boolean is a compile error, so dynamic chunking\n * is an explicit branch at the call site.\n *\n * @param options - JSONL file options with chunked: true\n * @returns The combined adapter with a per-line Source\n */\nexport function jsonl<T = unknown>(\n  options: JsonlFileOptions & { chunked: true },\n): JsonlChunkedAdapter<T>;\n/**\n * Creates a JSONL adapter for a JSON Lines file. One factory, one type; the\n * POSITION in the route selects the role:\n *\n * - **`.from(jsonl({ path }))`** reads + parses the file and emits the\n *   array (`chunked: true` emits one exchange per line).\n * - **`.to(jsonl({ path }))`** stringifies the body to JSONL and writes it\n *   (overwrite; `append: true` appends; `delete: true` removes the file).\n *   Array bodies write one line per element. The body flows through\n *   unchanged.\n * - **`.enrich(jsonl({ path }))`** reads + parses mid-route; the array\n *   replaces the body (pass an aggregator such as `only()` to merge\n *   instead).\n *\n * @param options - JSONL file path, encoding, append/delete, and parse options\n * @returns The combined Source + Destination + Enricher adapter\n *\n * @example\n * ```typescript\n * // Read JSONL as array\n * .from(jsonl({ path: './events.jsonl' }))\n *\n * // Read JSONL per-line\n * .from(jsonl({ path: './events.jsonl', chunked: true }))\n *\n * // Read mid-route (the parsed array replaces the body)\n * .enrich(jsonl({ path: './events.jsonl' }))\n *\n * // Append to JSONL (an event log)\n * .to(jsonl({ path: './output.jsonl', append: true }))\n *\n * // Delete a JSONL file (idempotent)\n * .to(jsonl({ path: (ex) => ex.body.processedPath, delete: true }))\n * ```\n */\nexport function jsonl<T = unknown>(\n  options: JsonlFileOptions & { chunked?: false },\n): JsonlAdapter<T>;\n/**\n * Creates a JSONL transformer that parses a JSONL string already in the body.\n *\n * @param options - Transformer options (`from`, `to`, `reviver`); no `path`\n * @returns A Transformer\n */\nexport function jsonl<T = unknown, R = unknown>(\n  options?: JsonlTransformerOptions<T, R>,\n): Transformer<T, R> & { readonly adapterId: string };\nexport function jsonl<T = unknown, R = unknown>(\n  options: JsonlFileOptions | JsonlTransformerOptions<T, R> = {},\n):\n  | (Transformer<T, R> & { readonly adapterId: string })\n  | JsonlChunkedAdapter<T>\n  | JsonlAdapter<T> {\n  const args = factoryArgs(options);\n\n  // Transformer role: no path means parse a JSONL string already in the\n  // body. The `.transform()` keyword enforces the category, so dropping\n  // `path` fails loudly at `.from()` / `.to()` instead of silently changing\n  // the adapter's kind.\n  if (!selectsFileRole(\"jsonl\", options)) {\n    const transformer = new JsonlTransformerAdapter<T, R>(\n      options as JsonlTransformerOptions<T, R>,\n    );\n    return tagAdapter(\n      {\n        adapterId: \"routecraft.adapter.jsonl\",\n        transform: transformer.transform.bind(transformer),\n      },\n      jsonl,\n      args,\n    ) as Transformer<T, R> & { readonly adapterId: string };\n  }\n\n  const fileOptions = options as JsonlFileOptions;\n\n  const destination = new JsonlDestinationAdapter(fileOptions);\n  const enricher = new JsonlEnricherAdapter<T>(fileOptions);\n\n  // The source role requires a static string path (no exchange exists at\n  // subscribe time). A function path keeps the honest combined type; its\n  // subscribe throws the same clear error lazily so `.from()` misuse fails\n  // with a message instead of an undefined-property TypeError.\n  const subscribe: CallableSource<T | T[]> =\n    typeof fileOptions.path === \"string\"\n      ? new JsonlSourceAdapter<T>(\n          fileOptions as JsonlFileOptions & { path: string },\n        ).subscribe\n      : async () => {\n          throw staticSourcePathError(\"jsonl\");\n        };\n\n  return tagAdapter(\n    {\n      adapterId: \"routecraft.adapter.jsonl\",\n      subscribe,\n      send: destination.send,\n      fetch: enricher.fetch,\n    },\n    jsonl,\n    args,\n  ) as unknown as JsonlChunkedAdapter<T> | JsonlAdapter<T>;\n}\n\n// Re-export types\nexport type {\n  JsonlFileOptions,\n  JsonlTransformerOptions,\n  JsonlOptions,\n} from \"./types.ts\";\nimport { staticSourcePathError } from \"../shared/file-role-guards.ts\";\nexport { JsonlHeaders } from \"./types.ts\";\n","import type { Transformer } from \"../../operations/transform.ts\";\nimport type { GroupOptions } from \"./types.ts\";\n\n/**\n * GroupTransformerAdapter groups an array into clusters using a comparator.\n */\nexport class GroupTransformerAdapter<\n  T = unknown,\n  R = T[],\n> implements Transformer<unknown, unknown> {\n  readonly adapterId = \"routecraft.adapter.group\";\n\n  constructor(private readonly options: GroupOptions<T, R>) {}\n\n  transform(body: unknown): unknown {\n    const items = this.options.from ? this.options.from(body) : (body as T[]);\n    const clusters: T[][] = [];\n\n    for (const item of items) {\n      const match = clusters.find((c) =>\n        c.some((member) => this.options.comparator.compare(member, item)),\n      );\n      if (match) {\n        match.push(item);\n      } else {\n        clusters.push([item]);\n      }\n    }\n\n    const result = this.options.map\n      ? clusters.map(this.options.map)\n      : (clusters as unknown as R[]);\n    if (this.options.to) {\n      return this.options.to(body, result as R[]);\n    }\n    return result;\n  }\n}\n","import type { Transformer } from \"../../operations/transform.ts\";\nimport type { GroupOptions } from \"./types.ts\";\nimport { GroupTransformerAdapter } from \"./transformer.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\n\n/**\n * Creates a transformer that groups an array into clusters using a comparator (e.g. cosine similarity).\n * By default uses body as the array and replaces the body with the array of clusters. Use `from`/`to` to read/write sub-fields; use `map` to shape each cluster.\n *\n * @param options - `comparator` (e.g. from `cosine()`), optional `from(body)`, `map(cluster)`, `to(body, result)`\n * @returns A Transformer usable with `.transform(group(options))`\n *\n * @example\n * ```typescript\n * .transform(group({\n *   comparator: cosine({ field: 'embedding', threshold: 0.82 }),\n *   from: (body) => body.items,\n *   map: (cluster) => ({ size: cluster.length, first: cluster[0] })\n * }))\n * ```\n */\nexport function group<T = unknown, R = T[]>(\n  options: GroupOptions<T, R>,\n): Transformer<unknown, unknown> {\n  return tagAdapter(\n    new GroupTransformerAdapter<T, R>(options),\n    group,\n    factoryArgs(options),\n  );\n}\n\n// Re-export types\nexport type { GroupOptions } from \"./types.ts\";\n","import { randomUUID } from \"node:crypto\";\nimport { HeadersKeys } from \"../../../exchange\";\nimport type { Source, Subscription } from \"../../../operations/from\";\nimport type { EventName, EventPayload } from \"../../../types\";\nimport type { EventFilter } from \"./types\";\n\n/**\n * Event source adapter that produces exchanges from framework events.\n * Subscribes to context events and emits them as exchanges.\n *\n * Events a route's own exchanges cause (`route:step:*`, `route:exchange:*`,\n * `route:operation:*`, and errors raised while one runs) are not delivered\n * back to it, including those of the routes it calls through `direct()`:\n * every step emits step events, so the route would otherwise feed on itself.\n * Its own lifecycle events, such as `route:started`, are delivered.\n *\n * Two `event()` routes that each watch step or exchange events still feed\n * each other: every exchange one runs emits events the other consumes. Point\n * observability routes at the routes they observe, not at each other.\n *\n * ```typescript\n * // Every step of every other route, as it completes\n * craft()\n *   .id(\"step-metrics\")\n *   .from(event(\"route:step:completed\"))\n *   .to(log())\n *\n * // Failed exchanges of one route only\n * craft()\n *   .id(\"orders-failures\")\n *   .from(event(\"route:exchange:failed\"))\n *   .filter((ex) => ex.body.details.routeId === \"orders\")\n *   .to(http({ url: alertUrl }))\n * ```\n */\nexport class EventSourceAdapter implements Source<EventPayload<EventName>> {\n  readonly adapterId = \"routecraft.adapter.event\";\n\n  constructor(private filter: EventFilter) {}\n\n  async subscribe(sub: Subscription<EventPayload<EventName>>): Promise<void> {\n    const context = sub.context;\n    const filters = Array.isArray(this.filter) ? this.filter : [this.filter];\n    const unsubscribers: Array<() => void> = [];\n\n    const ownRouteId = sub.meta.routeId;\n    // Correlation ids of the exchanges this route has in flight. A called\n    // route inherits the caller's correlation id, so this is what recognises\n    // events from further down the call chain.\n    const inFlight = new Set<string>();\n\n    // Determine which events to subscribe to\n    const eventNames = this.resolveEventNames(filters);\n\n    context.logger.debug(\n      { adapter: \"event\", filter: this.filter, eventNames },\n      \"Subscribing to events\",\n    );\n\n    const deliver = async (\n      eventName: string,\n      payload: EventPayload<EventName>,\n    ): Promise<void> => {\n      if (!sub.signal.aborted) {\n        if (isOwnExchangeEvent(payload, ownRouteId, inFlight)) return;\n        const correlationId = randomUUID();\n        inFlight.add(correlationId);\n        try {\n          await sub.emit({\n            message: payload,\n            headers: { [HeadersKeys.CORRELATION_ID]: correlationId },\n          });\n        } catch (err) {\n          const metaMessage =\n            typeof err === \"object\" &&\n            err !== null &&\n            \"meta\" in err &&\n            typeof (err as { meta?: { message?: unknown } }).meta?.message ===\n              \"string\"\n              ? (err as { meta: { message: string } }).meta.message\n              : undefined;\n          const errorMessage =\n            typeof err === \"object\" &&\n            err !== null &&\n            \"message\" in err &&\n            typeof (err as { message?: unknown }).message === \"string\"\n              ? (err as { message: string }).message\n              : undefined;\n\n          context.logger.warn(\n            { adapter: \"event\", event: eventName, err },\n            metaMessage ?? errorMessage ?? \"Event handler failed\",\n          );\n        } finally {\n          inFlight.delete(correlationId);\n        }\n      }\n    };\n\n    // Exact names subscribe directly; patterns (legacy wildcard syntax)\n    // attach ONE catch-all subscription and match the emitted name per\n    // event. The matcher cost is scoped to routes that use event() with\n    // patterns; the context's event bus itself stays pattern-free.\n    const exactNames = eventNames.filter((n) => !n.includes(\"*\"));\n    const patterns = eventNames.filter((n) => n.includes(\"*\"));\n\n    for (const eventName of exactNames) {\n      unsubscribers.push(\n        context.on(eventName as EventName, (payload) =>\n          deliver(eventName, payload as EventPayload<EventName>),\n        ),\n      );\n    }\n    if (patterns.length > 0) {\n      unsubscribers.push(\n        context.on(\"*\", (payload) => {\n          const emitted = (payload as { _event: string })._event;\n          if (patterns.some((p) => matchesEventPattern(emitted, p))) {\n            return deliver(emitted, payload as EventPayload<EventName>);\n          }\n          return undefined;\n        }),\n      );\n    }\n\n    // Cleanup on abort\n    sub.signal.addEventListener(\"abort\", () => {\n      context.logger.debug({ adapter: \"event\" }, \"Unsubscribing from events\");\n      for (const unsubscribe of unsubscribers) {\n        unsubscribe();\n      }\n    });\n\n    sub.ready();\n\n    // Keep the subscription alive until aborted\n    return new Promise<void>((resolve) => {\n      // Check if already aborted\n      if (sub.signal.aborted) {\n        resolve();\n        return;\n      }\n\n      // Add listener with { once: true } to prevent leaks\n      sub.signal.addEventListener(\"abort\", () => resolve(), {\n        once: true,\n      });\n    });\n  }\n\n  /**\n   * Resolve event names from filters. Exact names subscribe directly;\n   * names containing `*` are treated as patterns matched against emitted\n   * event names via the adapter's local matcher.\n   */\n  private resolveEventNames(filters: string[]): string[] {\n    // Deduplicate filters\n    const resolved = new Set<string>();\n\n    for (const filter of filters) {\n      resolved.add(filter);\n    }\n\n    return Array.from(resolved);\n  }\n}\n\n/**\n * Whether an event was caused by one of this route's own exchanges.\n *\n * Every step emits `route:step:*` and every exchange `route:exchange:*`, so\n * an `event()` route delivered its own events would start an exchange per\n * event it processes, forever, and starve the event loop. The route's own\n * lifecycle events (`route:started` and the like) carry no exchange and are\n * still delivered.\n *\n * Exchange events name their exchange in one of two shapes: `routeId` and\n * `correlationId` beside `exchangeId`, or the `route` and `exchange`\n * themselves (`route:error`, `context:error`). Both are read.\n *\n * @param inFlight Correlation ids of the exchanges this route has in flight\n */\nfunction isOwnExchangeEvent(\n  payload: EventPayload<EventName>,\n  ownRouteId: string,\n  inFlight: ReadonlySet<string>,\n): boolean {\n  const details = payload.details as {\n    routeId?: unknown;\n    correlationId?: unknown;\n    exchangeId?: unknown;\n    route?: { definition?: { id?: unknown } };\n    exchange?: { headers?: Record<string, unknown> };\n  };\n  const correlationId =\n    details.correlationId ??\n    details.exchange?.headers?.[HeadersKeys.CORRELATION_ID];\n  if (typeof correlationId === \"string\" && inFlight.has(correlationId)) {\n    return true;\n  }\n  const routeId = details.routeId ?? details.route?.definition?.id;\n  return (\n    routeId === ownRouteId &&\n    (details.exchangeId !== undefined || details.exchange !== undefined)\n  );\n}\n\n/**\n * Match an emitted event name against a colon-segmented pattern.\n * `*` matches one segment; `**` matches zero or more segments; a bare\n * `\"*\"` pattern matches everything. Local to the event source adapter:\n * the framework's event names are a fixed set and the bus has no pattern\n * matching, but this adapter keeps the pattern UX for observability\n * routes (cold path, per-subscription).\n */\nexport function matchesEventPattern(event: string, pattern: string): boolean {\n  if (pattern === \"*\" || pattern === \"**\") return true;\n  if (!pattern.includes(\"*\")) return event === pattern;\n\n  const eventSegments = event.split(\":\");\n  const patternSegments = pattern.split(\":\");\n\n  let e = 0;\n  let p = 0;\n  while (p < patternSegments.length) {\n    const seg = patternSegments[p];\n    if (seg === \"**\") {\n      if (p === patternSegments.length - 1) return true;\n      const rest = patternSegments.slice(p + 1).join(\":\");\n      for (let i = e; i <= eventSegments.length; i++) {\n        if (matchesEventPattern(eventSegments.slice(i).join(\":\"), rest)) {\n          return true;\n        }\n      }\n      return false;\n    } else if (seg === \"*\") {\n      if (e >= eventSegments.length) return false;\n      e++;\n      p++;\n    } else {\n      if (e >= eventSegments.length || eventSegments[e] !== seg) return false;\n      e++;\n      p++;\n    }\n  }\n  return e === eventSegments.length;\n}\n","import type { Source } from \"../../../operations/from\";\nimport type { EventPayload, EventName } from \"../../../types\";\nimport { EventSourceAdapter } from \"./source\";\nimport type { EventFilter } from \"./types\";\nimport { tagAdapter, factoryArgs } from \"../../shared/factory-tag\";\n\n/**\n * Creates a source that produces exchanges from framework events.\n * Use as the first step in a route with `.from(event(...))`.\n *\n * Event names are a fixed set; the route id and the exchange live in the\n * payload's `details`, so scope to one route by filtering on\n * `details.routeId`. Patterns match the emitted name:\n *\n * - `*` matches exactly one colon-separated segment: `route:exchange:*`\n *   matches `route:exchange:failed` but not `route:started`.\n * - `**` matches zero or more segments: `route:**` matches every route event.\n * - `*` on its own matches every event.\n *\n * Events the route's own exchanges emit are not delivered back to it; see\n * {@link EventSourceAdapter}.\n *\n * @template T - Event payload type\n * @param filter - Event name(s) or wildcard pattern to listen for\n * @returns A Source usable with `.from(event(filter))`\n *\n * @example\n * ```typescript\n * // Single event\n * .from(event('route:started'))\n *\n * // Multiple events\n * .from(event(['route:started', 'route:stopped']))\n *\n * // Every exchange event: started, completed, failed, dropped, ...\n * .from(event('route:exchange:*'))\n *\n * // Every operation event, at any depth\n * .from(event('route:operation:**'))\n *\n * // Every route event\n * .from(event('route:**'))\n *\n * // Match all events\n * .from(event('*'))\n * ```\n */\nexport function event(filter: EventFilter): Source<EventPayload<EventName>> {\n  return tagAdapter(new EventSourceAdapter(filter), event, factoryArgs(filter));\n}\n\n// Re-export types for public API\nexport type { EventFilter, EventSourceOptions } from \"./types\";\nexport { EventSourceAdapter } from \"./source\";\n","import type { Source } from \"../../operations/from.ts\";\nimport type { Destination } from \"../../operations/to.ts\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport { rcError } from \"../../error.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\nimport { rejectStaleOptions } from \"../../shared/stale-options.ts\";\nimport { withAdapterIdentity } from \"../shared/role-facade.ts\";\nimport { MailSourceAdapter } from \"./source.ts\";\nimport { MailEnricherAdapter } from \"./enricher.ts\";\nimport { MailSendDestinationAdapter } from \"./send-destination.ts\";\nimport { MailOperationDestinationAdapter } from \"./operation-destination.ts\";\nimport type {\n  MailServerOptions,\n  MailClientOptions,\n  MailBody,\n  MailFetchResult,\n  MailSendPayload,\n  MailAction,\n} from \"./types.ts\";\n\n/**\n * The read side of the mail adapter: one object carrying both read roles, so\n * the operation keyword picks between them instead of the call shape.\n * `.from()` subscribes (IDLE / polling), `.enrich()` fetches the folder as a\n * batch.\n */\nexport type MailFolderAdapter = Source<MailBody> &\n  Enricher<unknown, MailFetchResult>;\n\n/**\n * Build the read-side facade from the two role implementations, which keep\n * genuinely different machinery (IDLE / polling versus a batch fetch).\n *\n * Three things the facade must carry beyond the two slots:\n *\n * - `getMetadata`, forwarded from the enricher. A facade that lists only its\n *   role slots silently drops the hook, and a fetch-resolved step then\n *   attaches no metadata to its completion event with nothing to catch it.\n * - Both implementation constructors as override identities, so class-based\n *   `mockAdapter(MailEnricherAdapter, ...)` AND\n *   `mockAdapter(MailSourceAdapter, ...)` keep intercepting. Before the\n *   arity collapse those were two separate returned objects.\n * - A lazily built source, because subscribing is the rarer role and\n *   constructing it eagerly would allocate IDLE state for every\n *   `.enrich(mail(...))`. The identity set names the CLASS rather than an\n *   instance precisely so the delegate can stay unbuilt.\n */\nfunction folderAdapter(\n  options: MailServerOptions & { folder: string },\n): MailFolderAdapter {\n  const enricher = new MailEnricherAdapter(options);\n  let source: MailSourceAdapter | undefined;\n  return withAdapterIdentity(\n    {\n      adapterId: enricher.adapterId,\n      subscribe: (sub) => {\n        source ??= new MailSourceAdapter(options.folder, options);\n        return source.subscribe(sub);\n      },\n      fetch: enricher.fetch,\n      getMetadata: (result: unknown) => enricher.getMetadata(result),\n    } satisfies MailFolderAdapter & {\n      getMetadata(result: unknown): Record<string, unknown>;\n    },\n    enricher,\n    MailSourceAdapter,\n  );\n}\n\n/**\n * Creates a mail adapter for reading email via IMAP, sending via SMTP,\n * or performing IMAP operations (move, copy, delete, flag, unflag, append).\n *\n * **Reading a folder (`.from()` / `.enrich()`):** name a folder, either as\n * `mail(folder, options?)` or as `mail({ folder, ...options })`. Both carry\n * BOTH read roles and the operation keyword picks between them: `.from()`\n * subscribes (IMAP IDLE or polling, pushing new messages into the route) and\n * `.enrich()` fetches the folder as a batch. The `folder` key is what\n * distinguishes a read from a send (mirroring `http`'s `path` vs `url`\n * split); passing options does not change the role, so `mail('INBOX')` and\n * `mail('INBOX', { markSeen: true })` differ only in configuration.\n *\n * **Send Destination (for `.to()`):** Call with no arguments or client options\n * (no `folder`). Sends email via SMTP using the exchange body as the payload.\n * The send is void: the body flows through unchanged and the receipt\n * (`routecraft.mail.sentMessageId`, `.accepted`, `.rejected`, `.response`)\n * lands on headers. The sent id is deliberately its own key: an inbound\n * `routecraft.mail.messageId` set by the source is left untouched so a\n * mail-to-mail route keeps its correlation id.\n *\n * **Operation Destination (for `.to()`):** Call with a MailAction object.\n * Performs IMAP operations (move, copy, delete, flag, unflag, append) on messages.\n *\n * @example\n * ```typescript\n * // Fetch mail via .enrich() (primary pattern)\n * craft()\n *   .from(cron('0 0/5 * * * *'))\n *   .enrich(mail('INBOX'))\n *   .to(processMessages())\n *\n * // Fetch with options: `folder` is required and marks the fetch intent\n * craft()\n *   .from(cron('0 0/5 * * * *'))\n *   .enrich(mail({ folder: 'INBOX', unseen: true, limit: 10 }))\n *   .to(processMessages())\n *\n * // Source: IMAP IDLE for push-based processing\n * craft()\n *   .from(mail('INBOX', { markSeen: true }))\n *   .to(processMessage())\n *\n * // Send mail via .to()\n * craft()\n *   .id('outbound')\n *   .from(direct())\n *   .to(mail())\n *\n * // IMAP operations\n * craft()\n *   .from(mail('INBOX', { unseen: true }))\n *   .to(mail({ action: 'move', folder: 'Archive' }))\n *\n * // Named account\n * craft()\n *   .from(mail('INBOX', { account: 'support' }))\n *   .to(mail({ action: 'flag', flags: '\\\\Seen', account: 'support' }))\n * ```\n *\n * @param folder - IMAP mailbox folder name (e.g. 'INBOX')\n * @param options - Server options for IMAP connection and fetch behavior\n * @returns Source, Enricher, Send Destination, or Operation Destination depending on arguments\n */\nexport function mail(\n  folder: string,\n  options?: MailServerOptions,\n): MailFolderAdapter;\nexport function mail(action: MailAction): Destination<unknown>;\nexport function mail(\n  options: MailServerOptions & { folder: string },\n): MailFolderAdapter;\nexport function mail(options?: MailClientOptions): Destination<MailSendPayload>;\nexport function mail(\n  folderOrOptions?: string | MailServerOptions | MailClientOptions | MailAction,\n  options?: MailServerOptions,\n): MailFolderAdapter | Destination<MailSendPayload> | Destination<unknown> {\n  // Both argument positions can carry options, and `reconnect` is the one\n  // nested object with authored durations of its own.\n  for (const candidate of [folderOrOptions, options]) {\n    rejectStaleOptions(candidate, \"mail\");\n    if (candidate !== undefined && typeof candidate === \"object\") {\n      rejectStaleOptions(\n        (candidate as { reconnect?: unknown }).reconnect,\n        \"mail({ reconnect })\",\n      );\n    }\n  }\n\n  const args = factoryArgs(folderOrOptions, options);\n\n  // A folder string names a folder to READ; whether that read streams\n  // (`.from()`) or batches (`.enrich()`) is the keyword's call, not the\n  // argument count's. Options configure the read, they do not select it.\n  if (typeof folderOrOptions === \"string\") {\n    return tagAdapter(\n      folderAdapter({ ...options, folder: folderOrOptions }),\n      mail,\n      args,\n    );\n  }\n\n  // Action discriminator -> Operation Destination (checked before `folder`:\n  // move/copy/append actions carry a folder of their own)\n  if (folderOrOptions && \"action\" in folderOrOptions) {\n    const adapter = new MailOperationDestinationAdapter(\n      folderOrOptions as MailAction,\n    );\n    return tagAdapter(adapter, mail, args) as Destination<unknown>;\n  }\n\n  // `folder` is the required fetch discriminator (object-form counterpart of\n  // the mail('INBOX') shorthand). Key presence declares the intent; an\n  // undefined value still resolves through the context-level folder default.\n  if (folderOrOptions && \"folder\" in folderOrOptions) {\n    return tagAdapter(\n      folderAdapter(folderOrOptions as MailServerOptions & { folder: string }),\n      mail,\n      args,\n    );\n  }\n\n  // Fetch-only keys without `folder` mean the intent is ambiguous (fetch\n  // options, send dispatch). Refuse rather than guess; only reachable from\n  // untyped JS because the overloads reject this shape at compile time.\n  if (folderOrOptions) {\n    const fetchOnly = serverOnlyKeysIn(folderOrOptions);\n    if (fetchOnly.length > 0) {\n      throw rcError(\"RC5003\", undefined, {\n        message: `mail() options include IMAP fetch keys (${fetchOnly.join(\", \")}) but no folder; cannot tell fetch intent from send intent`,\n        suggestion:\n          \"Add folder (e.g. mail({ folder: 'INBOX', ... })) or use the mail('INBOX') shorthand to fetch; remove fetch-only keys to send via SMTP\",\n      });\n    }\n  }\n\n  // No args or client-only keys -> Send Destination\n  const adapter = new MailSendDestinationAdapter(\n    folderOrOptions as MailClientOptions | undefined,\n  );\n  return tagAdapter(adapter, mail, args) as Destination<MailSendPayload>;\n}\n\n/**\n * Option keys that exist on {@link MailServerOptions} but not on\n * {@link MailClientOptions}. Keys shared by both sides (`host`, `port`,\n * `secure`, `auth`, `account`, `from`) carry no intent and are excluded\n * by the `Exclude<>` automatically.\n */\ntype ServerOnlyKey = Exclude<keyof MailServerOptions, keyof MailClientOptions>;\n\n/**\n * Exhaustive map of server-only keys, used by {@link serverOnlyKeysIn} to\n * detect fetch intent on options that lack the `folder` discriminator.\n * `Record<ServerOnlyKey, true>` makes the list exhaustive by construction:\n * adding a field to MailServerOptions that is absent from MailClientOptions\n * without listing it here is a compile error, so the runtime guard cannot\n * drift from the option types. (`folder` itself never reaches the guard;\n * it dispatches to the fetch destination earlier.)\n */\nconst SERVER_ONLY_KEYS: Record<ServerOnlyKey, true> = {\n  folder: true,\n  markSeen: true,\n  since: true,\n  unseen: true,\n  to: true,\n  subject: true,\n  body: true,\n  header: true,\n  limit: true,\n  description: true,\n  keywords: true,\n  pollInterval: true,\n  includeHeaders: true,\n  verify: true,\n  onParseError: true,\n  reconnect: true,\n};\n\n/**\n * List the server-only (IMAP fetch) keys present on an options object,\n * for the ambiguity guard's error message.\n */\nfunction serverOnlyKeysIn(opts: object): string[] {\n  return Object.keys(SERVER_ONLY_KEYS).filter((key) => key in opts);\n}\n\n// Re-export types for public API\nexport type {\n  MailAuth,\n  MailReconnectOptions,\n  MailServerOptions,\n  MailClientOptions,\n  MailOptions,\n  MailBody,\n  MailMessage,\n  MailAttachment,\n  MailSendPayload,\n  MailFetchResult,\n  MailContextConfig,\n  MailAccountConfig,\n  MailAccountImapConfig,\n  MailAccountSmtpConfig,\n  MailAction,\n  MailMoveAction,\n  MailCopyAction,\n  MailDeleteAction,\n  MailFlagAction,\n  MailUnflagAction,\n  MailAppendAction,\n  MailTargetExtractor,\n} from \"./types.ts\";\n\n// Re-export store key and client manager\nexport { MAIL_CLIENT_MANAGER } from \"./shared.ts\";\nexport { MailClientManager } from \"./client-manager.ts\";\n\n// Re-export the `routecraft.mail.*` header key object so consumers reading\n// envelope metadata off the source exchange get named constants and type-safe\n// autocomplete (the keys are also declaration-merged into `RoutecraftHeaders`).\nexport { MailHeaders } from \"./shared.ts\";\n\n// Sender analysis\nexport type {\n  MailSender,\n  EmailAddress,\n  ForwardHop,\n  ForwardType,\n  TrustLevel,\n} from \"./analysis.ts\";\nexport {\n  analyzeHeaders,\n  parseAuthResults,\n  ANALYSIS_HEADER_NAMES,\n} from \"./analysis.ts\";\n","import type { Source, Subscription } from \"../../operations/from.ts\";\nimport type { Exchange } from \"../../exchange.ts\";\nimport { parseDuration } from \"../../shared/duration.ts\";\nimport { rcError } from \"../../error.ts\";\nimport { isRoutecraftError } from \"../../brand.ts\";\nimport type { MailBody, MailMessage, MailServerOptions } from \"./types.ts\";\nimport type { MailClientManager } from \"./client-manager.ts\";\nimport { DEFAULT_ON_PARSE_ERROR, isParseError } from \"../shared/parse.ts\";\nimport {\n  getClientManager,\n  createImapClient,\n  fetchMessages,\n  markMessagesSeen,\n  isMailAuthError,\n  throwMailConnectionError,\n  splitMailMessage,\n  MAIL_PARSE_ERRORS,\n  type MailFetchLogger,\n  isMissingPeerError,\n} from \"./shared.ts\";\n\ntype ImapClient = InstanceType<typeof import(\"imapflow\").ImapFlow>;\n\n/** Default cap on reconnect attempts; override via `reconnect.maxAttempts`. */\nconst MAIL_RECONNECT_MAX_ATTEMPTS = 30;\n/** Default initial backoff between mail reconnect attempts. */\nconst MAIL_RECONNECT_BASE_MS = 1_000;\n/** Default cap for exponential backoff. */\nconst MAIL_RECONNECT_MAX_MS = 60_000;\n\n/**\n * Resolve `pollInterval` to milliseconds, with `0` for both \"not declared\"\n * and \"declared as zero\".\n *\n * One resolver so the mode switch, the poll loop and the validator cannot\n * disagree about what a given value means. They did: a presence test chose\n * poll mode while the validator's `> 0` said the same options were not\n * polling at all.\n */\nfunction resolvePollIntervalMs(options: MailServerOptions): number {\n  return options.pollInterval === undefined\n    ? 0\n    : parseDuration(options.pollInterval, \"mail({ pollInterval })\", 0);\n}\n\n/**\n * Resolve the `reconnect` option against defaults. `null` means reconnection\n * is disabled (`reconnect: false`) and connection failures are fatal\n * immediately.\n */\nfunction resolveReconnect(\n  options: MailServerOptions,\n): ResolvedReconnect | null {\n  if (options.reconnect === false) return null;\n  const { baseDelay, maxDelay } = options.reconnect ?? {};\n  return {\n    maxAttempts: options.reconnect?.maxAttempts ?? MAIL_RECONNECT_MAX_ATTEMPTS,\n    baseDelayMs:\n      baseDelay === undefined\n        ? MAIL_RECONNECT_BASE_MS\n        : parseDuration(baseDelay, \"mail({ reconnect: { baseDelay } })\"),\n    maxDelayMs:\n      maxDelay === undefined\n        ? MAIL_RECONNECT_MAX_MS\n        : parseDuration(maxDelay, \"mail({ reconnect: { maxDelay } })\"),\n  };\n}\n\n/**\n * `reconnect` with every default applied and every duration resolved to\n * milliseconds, which is what the backoff arithmetic needs.\n */\ninterface ResolvedReconnect {\n  maxAttempts: number;\n  baseDelayMs: number;\n  maxDelayMs: number;\n}\n\n/**\n * Fail-fast path (`reconnect: false`): surface the connection failure as a\n * boundary error. Errors already wrapped by a lower boundary (RC5001 fetch\n * failures, RC5010 standalone connect failures) pass through unchanged; raw\n * socket errors (e.g. from `client.idle()`) get the RC5010 connection wrap.\n */\nfunction throwFailFast(error: unknown): never {\n  if (isRoutecraftError(error)) throw error;\n  throwMailConnectionError(error, \"IMAP\");\n}\n\n/**\n * Source adapter that receives email messages from IMAP using IDLE or polling.\n * Used with `.from(mail(folder, options))` for push-based email processing.\n *\n * When a MailClientManager is available (via context mail config), uses pooled\n * connections. Otherwise falls back to standalone connections.\n *\n * Splits each message into a {@link MailBody} payload on `exchange.body`\n * (`text`, `html`, and `attachments`) and the envelope on `routecraft.mail.*`\n * headers (`uid`, `folder`, `from`, `to`, `cc`, `bcc`, `subject`, `date`,\n * `messageId`, `replyTo`, `flags`, `sender`, `rawHeaders`). This mirrors the\n * HTTP source convention so the same `.transform()` / `.filter()` operators\n * compose across adapters, and downstream IMAP operations can resolve the\n * target message from headers even after body transforms.\n *\n * ## IDLE vs poll\n *\n * - Default mode is IDLE: the server pushes new-arrival notifications and the\n *   \\Seen flag is the cross-cycle dedupe state. This is the right model when\n *   each message should be delivered to the handler exactly once.\n * - Set `pollInterval` to run in poll mode. Poll mode is required whenever\n *   you opt out of the \\Seen-flag model by setting `markSeen: false` or\n *   `unseen: false` (for example, to re-evaluate the inbox on every cycle and\n *   rely on a folder move as the done-signal). IDLE cannot bound re-delivery\n *   cycles, so combining it with those overrides would flood the handler on\n *   every inbound message.\n * - `limit` combined with IDLE is a latency trap: backlog beyond `limit` only\n *   drains when new mail arrives. A warning is logged at subscribe time.\n *\n * @example\n * ```typescript\n * // Default: IDLE, \\Seen-based dedupe, exactly-once-ish delivery.\n * craft()\n *   .from(mail('INBOX', {}))\n *   .to(processMessage())\n *\n * // Re-evaluate the inbox on a cadence, move-to-archive as the done signal.\n * craft()\n *   .from(mail('INBOX', {\n *     markSeen: false,\n *     unseen: false,\n *     pollInterval: \"60s\",\n *   }))\n *   .filter(matchesCriteria)\n *   .to(mail({ action: 'move', folder: 'Archive' }))\n * ```\n */\nexport class MailSourceAdapter implements Source<MailBody> {\n  readonly adapterId = \"routecraft.adapter.mail\";\n  private readonly adapterOptions: MailServerOptions;\n  private readonly folder: string | undefined;\n\n  constructor(folder: string | undefined, options: MailServerOptions) {\n    this.folder = folder;\n    this.adapterOptions = options;\n  }\n\n  async subscribe(sub: Subscription<MailBody>): Promise<void> {\n    const context = sub.context;\n    // The poll/idle loops and shared fetch helpers take an AbortController;\n    // bridge the subscription's signal onto an adapter-internal controller\n    // so their signatures stay unchanged.\n    const abortController = new AbortController();\n    if (sub.signal.aborted) {\n      abortController.abort(sub.signal.reason);\n    } else {\n      sub.signal.addEventListener(\n        \"abort\",\n        () => abortController.abort(sub.signal.reason),\n        { once: true },\n      );\n    }\n    const manager = getClientManager(context);\n    const account = this.adapterOptions.account;\n\n    // Only contribute `folder` when this adapter actually carries one:\n    // spreading an explicit `undefined` would mask the context default that\n    // `mail({ folder: undefined })` exists to reach.\n    const folderOption =\n      this.folder !== undefined ? { folder: this.folder } : {};\n    const resolved: MailServerOptions = manager\n      ? manager.resolveImapOptions(account, {\n          ...this.adapterOptions,\n          ...folderOption,\n        })\n      : ({ ...this.adapterOptions, ...folderOption } as MailServerOptions);\n\n    // Same ladder the fetch role uses (adapter option, then context default,\n    // then INBOX). `mail({ folder: undefined })` deliberately means \"take the\n    // folder from context config\", so both read roles must agree on what\n    // happens when the context has none either.\n    const folder = resolved.folder ?? this.folder ?? \"INBOX\";\n    const hasConnectionOverride =\n      this.adapterOptions.host !== undefined ||\n      this.adapterOptions.port !== undefined ||\n      this.adapterOptions.secure !== undefined ||\n      this.adapterOptions.auth !== undefined;\n    const usePool = !!manager && !hasConnectionOverride;\n\n    const logger: MailFetchLogger | undefined = context.logger\n      ? {\n          debug: (obj, msg) => context.logger.debug(obj, msg),\n          warn: (obj, msg) => context.logger.warn(obj, msg),\n        }\n      : undefined;\n\n    validateSourceOptions(resolved, logger);\n\n    const markSeenEnabled = resolved.markSeen !== false;\n\n    // Mutable ref so the connect/idle/poll paths can swap the client on\n    // reconnect while the abort handler still releases whatever connection\n    // is current.\n    const clientRef: { current: ImapClient | null } = { current: null };\n\n    let released = false;\n    const releaseClient = () => {\n      if (released) return;\n      released = true;\n      const c = clientRef.current;\n      if (!c) return;\n      clientRef.current = null;\n      if (usePool) {\n        manager!.releaseImap(account, c);\n      } else {\n        c.logout().catch(() => {});\n      }\n    };\n\n    const onAbort = () => releaseClient();\n    abortController.signal.addEventListener(\"abort\", onAbort, { once: true });\n\n    // The MIME parse failure mode is decided per-poll-cycle from\n    // resolved options. `'fail'` (default) surfaces malformed messages\n    // through the route's `.error()` handler; `'drop'` emits\n    // `route:exchange:dropped` with `reason: \"parse-failed\"`; `'abort'` would\n    // additionally re-throw out of the source loop.\n    const parseFailureMode = resolved.onParseError ?? DEFAULT_ON_PARSE_ERROR;\n\n    const handlerWithHeaders = (message: MailMessage) => {\n      // Split the fetched message into payload (body) and envelope (headers)\n      // so the route sees the same payload-on-body / envelope-on-headers shape\n      // as the HTTP source.\n      const { body, headers } = splitMailMessage(message);\n      // When the message had a MIME parse failure during fetch, surface\n      // the captured error from the synthetic parse step so the route\n      // observes it via the configured failure mode. See #187.\n      const parseError = MAIL_PARSE_ERRORS.get(message);\n      if (parseError) {\n        MAIL_PARSE_ERRORS.delete(message);\n        return sub.emit({\n          message: body,\n          headers,\n          parse: () => {\n            throw parseError;\n          },\n          parseFailureMode,\n        });\n      }\n      return sub.emit({ message: body, headers });\n    };\n\n    try {\n      // Signal readiness before the first connection attempt: with reconnect\n      // enabled, an IMAP server that is unreachable at route start leaves the\n      // route running in a degraded-but-recovering state instead of failing\n      // startup. The tradeoff is that `route:started` no longer guarantees\n      // the mailbox was reachable.\n      sub.ready();\n\n      await this.initialConnect(\n        clientRef,\n        manager,\n        account,\n        resolved,\n        folder,\n        usePool,\n        abortController,\n        logger,\n      );\n      // Aborted while still connecting: nothing to drain or watch.\n      if (!clientRef.current) return;\n\n      const resolvedPollIntervalMs = resolvePollIntervalMs(resolved);\n      // `> 0`, not merely \"declared\": `pollInterval: 0` reads as \"no\n      // polling\" and must keep falling through to IDLE, which is what the\n      // truthiness test did before this option took a Duration. A presence\n      // test turns it into a poll loop whose wait is zero, hammering the\n      // IMAP server as fast as it answers. `validateSourceOptions` already\n      // decides \"has poll\" this way; the two must agree.\n      if (resolvedPollIntervalMs > 0) {\n        await this.pollLoop(\n          clientRef,\n          manager,\n          account,\n          resolved,\n          folder,\n          usePool,\n          markSeenEnabled,\n          handlerWithHeaders,\n          abortController,\n          logger,\n        );\n      } else {\n        await this.idleLoop(\n          clientRef,\n          manager,\n          account,\n          resolved,\n          folder,\n          usePool,\n          markSeenEnabled,\n          handlerWithHeaders,\n          abortController,\n          logger,\n        );\n      }\n    } finally {\n      abortController.signal.removeEventListener(\"abort\", onAbort);\n      releaseClient();\n    }\n  }\n\n  /** Acquire an IMAP client (pool or standalone) and open the mailbox. */\n  private async acquireAndOpen(\n    manager: MailClientManager | null,\n    account: string | undefined,\n    resolved: MailServerOptions,\n    folder: string,\n    usePool: boolean,\n  ): Promise<ImapClient> {\n    let client: ImapClient;\n    if (usePool) {\n      client = await manager!.acquireImap(account, folder);\n    } else {\n      client = await createImapClient(resolved);\n      try {\n        await client.connect();\n      } catch (error) {\n        try {\n          client.close();\n        } catch {\n          // Ignore cleanup errors\n        }\n        throwMailConnectionError(error, \"IMAP\");\n      }\n    }\n    try {\n      await client.mailboxOpen(folder);\n      if (usePool) manager!.trackMailbox(account, client, folder);\n      return client;\n    } catch (error) {\n      if (usePool) {\n        manager!.releaseImap(account, client);\n      } else {\n        await client.logout().catch(() => {});\n      }\n      throw error;\n    }\n  }\n\n  /**\n   * Establish the first connection of the subscription. With reconnect\n   * enabled, a connection failure here enters the same backoff loop as a\n   * mid-life drop, so a server that is unreachable at route start is retried\n   * instead of killing the route. Auth failures and `reconnect: false` keep\n   * the fail-fast behaviour. Leaves `clientRef.current` null when the\n   * subscription is aborted before a connection could be established.\n   */\n  private async initialConnect(\n    clientRef: { current: ImapClient | null },\n    manager: MailClientManager | null,\n    account: string | undefined,\n    options: MailServerOptions,\n    folder: string,\n    usePool: boolean,\n    abortController: AbortController,\n    logger?: MailFetchLogger,\n  ): Promise<void> {\n    try {\n      clientRef.current = await this.acquireAndOpen(\n        manager,\n        account,\n        options,\n        folder,\n        usePool,\n      );\n    } catch (error) {\n      if (abortController.signal.aborted) return;\n      if (isMissingPeerError(error)) {\n        // Missing optional peer: reconnecting cannot install the package.\n        throw error;\n      }\n      if (isMailAuthError(error)) {\n        // Auth failures will not recover on reconnect; surface clearly and stop.\n        throwMailConnectionError(error, \"IMAP\");\n      }\n      const reconnect = resolveReconnect(options);\n      if (!reconnect) throwFailFast(error);\n      logger?.warn(\n        {\n          err: error instanceof Error ? error : new Error(String(error)),\n          folder,\n        },\n        \"mail adapter initial connect failed; attempting reconnect\",\n      );\n      await this.reconnectWithBackoff(\n        clientRef,\n        manager,\n        account,\n        options,\n        folder,\n        usePool,\n        \"connect\",\n        reconnect,\n        abortController,\n        logger,\n      );\n    }\n  }\n\n  /**\n   * Reconnect on a dropped connection using the same backoff as IDLE. Without\n   * this, a transient socket failure during a fetch would tear the\n   * subscription down for good and the only recovery is a process restart.\n   */\n  private async pollLoop(\n    clientRef: { current: ImapClient | null },\n    manager: MailClientManager | null,\n    account: string | undefined,\n    options: MailServerOptions,\n    folder: string,\n    usePool: boolean,\n    markSeenEnabled: boolean,\n    handler: (message: MailMessage) => Promise<Exchange>,\n    abortController: AbortController,\n    logger?: MailFetchLogger,\n  ): Promise<void> {\n    const onParseError = options.onParseError ?? DEFAULT_ON_PARSE_ERROR;\n    const pollIntervalMs = resolvePollIntervalMs(options);\n    const reconnect = resolveReconnect(options);\n    while (!abortController.signal.aborted) {\n      const client = clientRef.current;\n      if (!client) return;\n\n      let messages: MailMessage[];\n      try {\n        messages = await fetchMessages(client, options, folder, logger);\n      } catch (error) {\n        if (abortController.signal.aborted) return;\n        if (isMissingPeerError(error)) {\n          // Missing optional peer: reconnecting cannot install the package.\n          throw error;\n        }\n        if (isMailAuthError(error)) {\n          // Auth failures will not recover on reconnect; surface clearly and stop.\n          throwMailConnectionError(error, \"IMAP\");\n        }\n        if (!reconnect) throwFailFast(error);\n        logger?.warn(\n          {\n            err: error instanceof Error ? error : new Error(String(error)),\n            folder,\n          },\n          \"mail adapter poll fetch failed; attempting reconnect\",\n        );\n        await this.reconnectWithBackoff(\n          clientRef,\n          manager,\n          account,\n          options,\n          folder,\n          usePool,\n          \"poll\",\n          reconnect,\n          abortController,\n          logger,\n        );\n        if (abortController.signal.aborted) return;\n        continue;\n      }\n\n      for (const message of messages) {\n        if (abortController.signal.aborted) break;\n        try {\n          // Mark-Seen-on-success covers two parse-failure paths via the\n          // handler resolving cleanly:\n          //   1. 'drop': synthetic parse step emits route:exchange:dropped and\n          //      runPipeline returns without throwing.\n          //   2. 'fail' with a route .error() handler that recovers: catch\n          //      block sets exchange.body and runPipeline returns cleanly.\n          // The catch block below covers the remaining parse-failure paths\n          // ('fail' without handler, 'abort').\n          await handler(message);\n          if (markSeenEnabled) {\n            await markMessagesSeen(client, message.uid, logger);\n          }\n        } catch (err) {\n          // A parse failure (RC5016) is permanent: retrying will hit the\n          // same malformed MIME forever. Mark Seen so the message exits\n          // the unread set, then re-evaluate based on the configured mode.\n          if (isParseError(err)) {\n            if (markSeenEnabled) {\n              await markMessagesSeen(client, message.uid, logger);\n            }\n            // 'abort': rethrow so the source dies (`context:error` fires).\n            // The per-message `route:exchange:failed` already fired from the\n            // synthetic parse step.\n            if (onParseError === \"abort\") throw err;\n          }\n          // Non-parse handler errors are treated as transient and left\n          // un-Seen for retry on the next cycle.\n        }\n      }\n\n      if (abortController.signal.aborted) break;\n\n      await waitWithAbort(pollIntervalMs, abortController);\n    }\n  }\n\n  private async idleLoop(\n    clientRef: { current: ImapClient | null },\n    manager: MailClientManager | null,\n    account: string | undefined,\n    options: MailServerOptions,\n    folder: string,\n    usePool: boolean,\n    markSeenEnabled: boolean,\n    handler: (message: MailMessage) => Promise<Exchange>,\n    abortController: AbortController,\n    logger?: MailFetchLogger,\n  ): Promise<void> {\n    const reconnect = resolveReconnect(options);\n    // Drain on entry, after every IDLE wake, and after every reconnect: mail\n    // that arrived during an outage would otherwise sit unseen until the\n    // next new-arrival notification. The drain runs inside the same\n    // catch-and-reconnect handling as idle() itself; a connection dropped\n    // between the IDLE wake and the fetch must reconnect, not kill the\n    // subscription (the failure mode behind #425).\n    let needDrain = true;\n    while (!abortController.signal.aborted) {\n      const client = clientRef.current;\n      if (!client) return;\n\n      try {\n        if (needDrain) {\n          await this.drainOnce(\n            clientRef,\n            options,\n            folder,\n            markSeenEnabled,\n            handler,\n            abortController,\n            logger,\n          );\n          needDrain = false;\n        }\n        if (abortController.signal.aborted) return;\n        await client.idle();\n        needDrain = true;\n      } catch (error) {\n        if (abortController.signal.aborted) return;\n        if (isMissingPeerError(error)) {\n          // Missing optional peer: reconnecting cannot install the package.\n          throw error;\n        }\n        if (isMailAuthError(error)) {\n          // Auth failures will not recover on reconnect; surface clearly and stop.\n          throwMailConnectionError(error, \"IMAP\");\n        }\n        // A parse rethrow out of the drain (`onParseError: 'abort'`) is a\n        // deliberate source kill, not a connection failure: never reconnect.\n        if (isParseError(error)) throw error;\n        if (!reconnect) throwFailFast(error);\n        logger?.warn(\n          {\n            err: error instanceof Error ? error : new Error(String(error)),\n            folder,\n          },\n          \"mail adapter IDLE connection dropped; attempting reconnect\",\n        );\n        await this.reconnectWithBackoff(\n          clientRef,\n          manager,\n          account,\n          options,\n          folder,\n          usePool,\n          \"idle\",\n          reconnect,\n          abortController,\n          logger,\n        );\n        if (abortController.signal.aborted) return;\n        needDrain = true;\n      }\n    }\n  }\n\n  /**\n   * Fetch matching messages once and deliver each to the handler.\n   * Marks each message Seen only after the handler resolves successfully,\n   * so a handler failure leaves the message in the pool for retry.\n   */\n  private async drainOnce(\n    clientRef: { current: ImapClient | null },\n    options: MailServerOptions,\n    folder: string,\n    markSeenEnabled: boolean,\n    handler: (message: MailMessage) => Promise<Exchange>,\n    abortController: AbortController,\n    logger?: MailFetchLogger,\n  ): Promise<void> {\n    const client = clientRef.current;\n    if (!client) return;\n    const onParseError = options.onParseError ?? DEFAULT_ON_PARSE_ERROR;\n\n    const messages = await fetchMessages(client, options, folder, logger);\n    for (const message of messages) {\n      if (abortController.signal.aborted) return;\n      try {\n        await handler(message);\n        if (markSeenEnabled) {\n          await markMessagesSeen(client, message.uid, logger);\n        }\n      } catch (err) {\n        // RC5016 is a permanent MIME parse failure; mark Seen so we don't\n        // re-fetch the same malformed message forever, and rethrow when\n        // the configured mode is `'abort'` so the source dies.\n        if (isParseError(err)) {\n          if (markSeenEnabled) {\n            await markMessagesSeen(client, message.uid, logger);\n          }\n          if (onParseError === \"abort\") throw err;\n        }\n        // Non-parse handler errors are treated as transient and left\n        // un-Seen for retry on the next cycle.\n      }\n    }\n  }\n\n  /**\n   * Replace a dead IMAP client after a connect, fetch, or IDLE failure.\n   * Exponential backoff with jitter; attempts, base, and cap come from the\n   * resolved `reconnect` option. Releases the current client on the first\n   * attempt so the pool slot is freed for the new connection. `mode` is\n   * interpolated into log lines and the give-up error so operators can tell\n   * which path the reconnect was driven from.\n   */\n  private async reconnectWithBackoff(\n    clientRef: { current: ImapClient | null },\n    manager: MailClientManager | null,\n    account: string | undefined,\n    options: MailServerOptions,\n    folder: string,\n    usePool: boolean,\n    mode: \"connect\" | \"idle\" | \"poll\",\n    reconnect: ResolvedReconnect,\n    abortController: AbortController,\n    logger?: MailFetchLogger,\n  ): Promise<void> {\n    const dead = clientRef.current;\n    clientRef.current = null;\n    if (dead) {\n      if (usePool) {\n        try {\n          manager!.releaseImap(account, dead);\n        } catch {\n          // Ignore release errors on a client we know is broken\n        }\n      } else {\n        await dead.logout().catch(() => {});\n      }\n    }\n\n    for (let attempt = 1; attempt <= reconnect.maxAttempts; attempt++) {\n      if (abortController.signal.aborted) return;\n\n      // 2**(attempt-1) overflows to Infinity for large attempt counts\n      // (maxAttempts: Infinity); min() then pins the base to maxDelayMs.\n      const base = Math.min(\n        reconnect.baseDelayMs * 2 ** (attempt - 1),\n        reconnect.maxDelayMs,\n      );\n      // Full jitter: pick uniformly in [0, base] so retries don't thunder.\n      const delay = Math.floor(Math.random() * base);\n      await waitWithAbort(delay, abortController);\n      if (abortController.signal.aborted) return;\n\n      try {\n        const fresh = await this.acquireAndOpen(\n          manager,\n          account,\n          options,\n          folder,\n          usePool,\n        );\n        if (abortController.signal.aborted) {\n          // The subscription's abort handler already ran while no client was\n          // current, so nothing will release this late arrival: do it here.\n          if (usePool) {\n            try {\n              manager!.releaseImap(account, fresh);\n            } catch {\n              // Ignore release errors during teardown\n            }\n          } else {\n            await fresh.logout().catch(() => {});\n          }\n          return;\n        }\n        clientRef.current = fresh;\n        logger?.debug(\n          { folder, attempt, mode },\n          `mail adapter ${mode} reconnect succeeded`,\n        );\n        return;\n      } catch (error) {\n        if (isMissingPeerError(error)) {\n          // Missing optional peer: reconnecting cannot install the package.\n          throw error;\n        }\n        if (isMailAuthError(error)) {\n          throwMailConnectionError(error, \"IMAP\");\n        }\n        logger?.warn(\n          {\n            err: error instanceof Error ? error : new Error(String(error)),\n            folder,\n            attempt,\n            mode,\n          },\n          `mail adapter ${mode} reconnect attempt failed`,\n        );\n      }\n    }\n\n    throw rcError(\"RC5010\", undefined, {\n      message: `Mail adapter ${mode} reconnect gave up after ${reconnect.maxAttempts} attempts on folder \"${folder}\".`,\n    });\n  }\n}\n\n/**\n * Subscribe-time validation.\n *\n * Re-evaluation mode (`markSeen: false` or `unseen: false`) requires an\n * explicit poll cadence: IDLE has no cycle boundary so it would re-fetch the\n * entire folder on every inbound message, flooding the handler.\n * `limit` without a poll interval is a latency trap but not dangerous, so it\n * only warns.\n */\nfunction validateSourceOptions(\n  options: MailServerOptions,\n  logger?: MailFetchLogger,\n): void {\n  const disabledSeen = options.markSeen === false;\n  const disabledUnseen = options.unseen === false;\n  const hasPoll = resolvePollIntervalMs(options) > 0;\n\n  if ((disabledSeen || disabledUnseen) && !hasPoll) {\n    const which = disabledSeen ? \"markSeen: false\" : \"unseen: false\";\n    throw rcError(\"RC5003\", undefined, {\n      message:\n        `Mail source configured with ${which} requires pollInterval. ` +\n        \"IDLE mode cannot bound re-delivery cycles and would refetch the \" +\n        \"entire folder on every incoming message. Set pollInterval to \" +\n        \"poll on a cadence, or remove the markSeen/unseen override.\",\n    });\n  }\n\n  if (typeof options.limit === \"number\" && !hasPoll) {\n    logger?.warn(\n      { limit: options.limit, folder: options.folder },\n      \"mail source `limit` with IDLE: backlog beyond the limit will only \" +\n        \"drain when new mail arrives. Use pollInterval for predictable drain.\",\n    );\n  }\n\n  if (options.reconnect !== undefined && options.reconnect !== false) {\n    const { maxAttempts, baseDelay, maxDelay } = options.reconnect;\n    if (\n      maxAttempts !== undefined &&\n      maxAttempts !== Infinity &&\n      !(Number.isInteger(maxAttempts) && maxAttempts >= 1)\n    ) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"Mail source reconnect.maxAttempts must be a positive integer or Infinity.\",\n      });\n    }\n    const base =\n      baseDelay === undefined\n        ? MAIL_RECONNECT_BASE_MS\n        : parseDuration(baseDelay, \"mail({ reconnect: { baseDelay } })\");\n    const max =\n      maxDelay === undefined\n        ? MAIL_RECONNECT_MAX_MS\n        : parseDuration(maxDelay, \"mail({ reconnect: { maxDelay } })\");\n    if (max < base) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"Mail source reconnect.maxDelay must be greater than or equal to reconnect.baseDelay.\",\n      });\n    }\n  }\n}\n\n/**\n * Sleep for `ms` milliseconds, resolving early if the abort signal fires.\n * `ms <= 0` resolves immediately (still observing abort synchronously).\n */\nfunction waitWithAbort(\n  ms: number,\n  abortController: AbortController,\n): Promise<void> {\n  if (ms <= 0) return Promise.resolve();\n  return new Promise<void>((resolve) => {\n    const timeout = setTimeout(() => {\n      abortController.signal.removeEventListener(\"abort\", onAbort);\n      resolve();\n    }, ms);\n    const onAbort = () => {\n      clearTimeout(timeout);\n      resolve();\n    };\n    abortController.signal.addEventListener(\"abort\", onAbort, { once: true });\n  });\n}\n","import type { Enricher } from \"../../operations/enrich.ts\";\nimport type { Exchange } from \"../../exchange.ts\";\nimport { getExchangeContext } from \"../../exchange.ts\";\nimport type { MailFetchResult, MailServerOptions } from \"./types.ts\";\nimport {\n  getClientManager,\n  createImapClient,\n  fetchMessages,\n  markMessagesSeen,\n  throwMailConnectionError,\n  type MailFetchLogger,\n} from \"./shared.ts\";\n\n/**\n * Enricher adapter that fetches email messages from IMAP (a pull-in, so it\n * implements the fetch role). Designed for use with `.enrich()` to pull\n * messages into the exchange body.\n *\n * When a MailClientManager is available (via context mail config), uses pooled\n * connections. Otherwise falls back to standalone connections.\n *\n * @example\n * ```typescript\n * craft()\n *   .from(cron('0 0/5 * * * *'))\n *   .enrich(mail('INBOX'))\n *   .to(processMessages())\n * ```\n */\nexport class MailEnricherAdapter implements Enricher<unknown, MailFetchResult> {\n  readonly adapterId = \"routecraft.adapter.mail\";\n  private readonly adapterOptions: MailServerOptions;\n\n  constructor(options: MailServerOptions) {\n    this.adapterOptions = options;\n  }\n\n  fetch = async (exchange: Exchange<unknown>): Promise<MailFetchResult> => {\n    const context = getExchangeContext(exchange);\n    const manager = getClientManager(context);\n    const account = this.adapterOptions.account;\n\n    // Resolve options\n    const resolved: MailServerOptions = manager\n      ? manager.resolveImapOptions(account, this.adapterOptions)\n      : (this.adapterOptions as MailServerOptions);\n\n    const folder = resolved.folder ?? \"INBOX\";\n    const hasConnectionOverride =\n      this.adapterOptions.host !== undefined ||\n      this.adapterOptions.port !== undefined ||\n      this.adapterOptions.secure !== undefined ||\n      this.adapterOptions.auth !== undefined;\n    const usePool = !!manager && !hasConnectionOverride;\n\n    let client: InstanceType<typeof import(\"imapflow\").ImapFlow>;\n\n    if (usePool) {\n      client = await manager!.acquireImap(account, folder);\n    } else {\n      client = await createImapClient(resolved);\n      try {\n        await client.connect();\n      } catch (error) {\n        try {\n          client.close();\n        } catch {\n          // Ignore cleanup errors\n        }\n        throwMailConnectionError(error, \"IMAP\");\n      }\n    }\n\n    try {\n      await client.mailboxOpen(folder);\n      if (usePool) manager!.trackMailbox(account, client, folder);\n      const logger: MailFetchLogger | undefined = context?.logger\n        ? {\n            debug: (obj, msg) => context.logger.debug(obj, msg),\n            warn: (obj, msg) => context.logger.warn(obj, msg),\n          }\n        : undefined;\n      const messages = await fetchMessages(client, resolved, folder, logger);\n\n      // The fetch role has no post-commit hook, so mark Seen here.\n      // Best-effort: a flag failure must not fail the enrichment since\n      // messages have already been fetched.\n      if (resolved.markSeen !== false && messages.length > 0) {\n        await markMessagesSeen(\n          client,\n          messages.map((m) => m.uid),\n          logger,\n        );\n      }\n\n      return messages;\n    } finally {\n      if (usePool) {\n        manager!.releaseImap(account, client);\n      } else {\n        await client.logout().catch(() => {});\n      }\n    }\n  };\n\n  /**\n   * Extract metadata from fetch result for observability.\n   */\n  getMetadata(result: unknown): Record<string, unknown> {\n    const messages = result as MailFetchResult;\n    return {\n      folder: this.adapterOptions.folder ?? \"INBOX\",\n      messageCount: messages.length,\n      uids: messages.map((m) => m.uid),\n    };\n  }\n}\n","import type { Destination, SendContext } from \"../../operations/to.ts\";\nimport type { Exchange } from \"../../exchange.ts\";\nimport { getExchangeContext } from \"../../exchange.ts\";\nimport type { MailSendPayload, MailClientOptions } from \"./types.ts\";\nimport {\n  getClientManager,\n  createSmtpTransport,\n  buildMessageOptions,\n  throwMailConnectionError,\n  MailHeaders,\n} from \"./shared.ts\";\n\n/**\n * Destination adapter that sends email via SMTP.\n * Used with `.to(mail())` to send messages.\n *\n * A true push-out: `send` is void and the body flows through unchanged. The\n * send receipt surfaces via headers on the continuing exchange:\n * `routecraft.mail.sentMessageId` ({@link MailHeaders.SENT_MESSAGE_ID}),\n * the `routecraft.mail.accepted` / `routecraft.mail.rejected` recipient\n * lists, and the raw SMTP response on `routecraft.mail.response`. The\n * inbound `routecraft.mail.messageId` (set by the mail source) is left\n * untouched, so mail-to-mail routes keep their correlation id.\n *\n * When a MailClientManager is available (via context mail config), uses the\n * shared SMTP transporter. Otherwise falls back to standalone transporter.\n *\n * The exchange body must conform to {@link MailSendPayload}.\n * Connection config and defaults (from, replyTo, cc, bcc) come from the\n * named account config, overridable per-operation.\n *\n * @example\n * ```typescript\n * craft()\n *   .id('outbound-email')\n *   .from(direct())\n *   .to(mail())\n * ```\n */\nexport class MailSendDestinationAdapter implements Destination<MailSendPayload> {\n  readonly adapterId = \"routecraft.adapter.mail\";\n  private readonly adapterOptions: MailClientOptions;\n  private cachedTransporter?: Awaited<ReturnType<typeof createSmtpTransport>>;\n  private cachedTransporterKey?: string;\n\n  constructor(options?: MailClientOptions) {\n    this.adapterOptions = options ?? {};\n  }\n\n  async send(\n    exchange: Exchange<MailSendPayload>,\n    ctx?: SendContext,\n  ): Promise<void> {\n    const context = getExchangeContext(exchange);\n    const manager = getClientManager(context);\n    const account = this.adapterOptions.account;\n\n    // Resolve options\n    const resolved: MailClientOptions = manager\n      ? manager.resolveSmtpOptions(account, this.adapterOptions)\n      : (this.adapterOptions as MailClientOptions);\n\n    // Get transporter: pooled or standalone (with caching)\n    let transporter: Awaited<ReturnType<typeof createSmtpTransport>>;\n    const hasConnectionOverride =\n      this.adapterOptions.host !== undefined ||\n      this.adapterOptions.port !== undefined ||\n      this.adapterOptions.secure !== undefined ||\n      this.adapterOptions.auth !== undefined;\n    const usePool = !!manager && !hasConnectionOverride;\n\n    if (usePool) {\n      transporter = await manager!.getSmtp(account);\n    } else {\n      const key = `${resolved.host}:${resolved.port}:${resolved.auth?.user}:${resolved.auth?.pass}`;\n      if (!this.cachedTransporter || this.cachedTransporterKey !== key) {\n        this.cachedTransporter = await createSmtpTransport(resolved);\n        this.cachedTransporterKey = key;\n      }\n      transporter = this.cachedTransporter;\n    }\n\n    const mailOptions = buildMessageOptions(exchange.body, resolved);\n\n    try {\n      const info = await transporter.sendMail(mailOptions);\n\n      // Receipt headers, not a body replacement: the body flows through\n      // unchanged and downstream steps read the receipt off the headers.\n      // The sent message's id gets its OWN key so a mail-to-mail route\n      // (`.from(mail(...))....to(mail())`) keeps the inbound\n      // routecraft.mail.messageId intact for correlation.\n      ctx?.setHeader(MailHeaders.SENT_MESSAGE_ID, info.messageId ?? \"\");\n      ctx?.setHeader(\n        MailHeaders.ACCEPTED,\n        Array.isArray(info.accepted) ? info.accepted.map(String) : [],\n      );\n      ctx?.setHeader(\n        MailHeaders.REJECTED,\n        Array.isArray(info.rejected) ? info.rejected.map(String) : [],\n      );\n      ctx?.setHeader(MailHeaders.RESPONSE, info.response ?? \"\");\n    } catch (error) {\n      throwMailConnectionError(error, \"SMTP\");\n    }\n  }\n\n  /**\n   * Extract send metadata for observability: receives the receipt-header\n   * record collected by the `.to()` step (send is void).\n   */\n  getSendMetadata(receiptHeaders: unknown): Record<string, unknown> {\n    const receipts = (receiptHeaders ?? {}) as Record<string, unknown>;\n    const meta: Record<string, unknown> = {};\n    if (receipts[MailHeaders.SENT_MESSAGE_ID] !== undefined)\n      meta[\"messageId\"] = receipts[MailHeaders.SENT_MESSAGE_ID];\n    if (receipts[MailHeaders.ACCEPTED] !== undefined)\n      meta[\"accepted\"] = receipts[MailHeaders.ACCEPTED];\n    if (receipts[MailHeaders.REJECTED] !== undefined)\n      meta[\"rejected\"] = receipts[MailHeaders.REJECTED];\n    return meta;\n  }\n}\n","import type { Destination } from \"../../operations/to.ts\";\nimport type { Exchange } from \"../../exchange.ts\";\nimport { getExchangeContext } from \"../../exchange.ts\";\nimport type { MailAction, MailSendPayload } from \"./types.ts\";\nimport {\n  requireClientManager,\n  resolveMailTarget,\n  toArray,\n  buildMimeMessage,\n  throwMailConnectionError,\n} from \"./shared.ts\";\n\n/**\n * Destination adapter for IMAP operations on mail messages.\n * Handles move, copy, delete, flag, unflag, and append actions.\n *\n * Uses the MailClientManager from context for connection pooling.\n * Supports batch operations when exchange body is MailMessage[].\n *\n * @example\n * ```typescript\n * craft()\n *   .from(mail('INBOX', { markSeen: false }))\n *   .to(mail({ action: 'move', folder: 'Archive' }))\n *\n * craft()\n *   .id('compose')\n *   .from(direct())\n *   .to(mail({ action: 'append', folder: 'Drafts', flags: ['\\\\Draft'] }))\n * ```\n */\nexport class MailOperationDestinationAdapter implements Destination<unknown> {\n  readonly adapterId = \"routecraft.adapter.mail\";\n\n  constructor(private readonly action: MailAction) {}\n\n  async send(exchange: Exchange<unknown>): Promise<void> {\n    const context = getExchangeContext(exchange);\n    const manager = requireClientManager(context);\n    const account = this.action.account;\n\n    if (this.action.action === \"append\") {\n      await this.handleAppend(exchange);\n      return;\n    }\n\n    const { uids, folder } = resolveMailTarget(exchange, this.action.target);\n    if (uids.length === 0) return;\n\n    const client = await manager.acquireImap(account, folder);\n\n    try {\n      await client.mailboxOpen(folder);\n      manager.trackMailbox(account, client, folder);\n      const uidStr = uids.join(\",\");\n\n      switch (this.action.action) {\n        case \"move\":\n          await client.messageMove(uidStr, this.action.folder, { uid: true });\n          break;\n        case \"copy\":\n          await client.messageCopy(uidStr, this.action.folder, { uid: true });\n          break;\n        case \"delete\":\n          await client.messageDelete(uidStr, { uid: true });\n          break;\n        case \"flag\":\n          await client.messageFlagsAdd(uidStr, toArray(this.action.flags), {\n            uid: true,\n          });\n          break;\n        case \"unflag\":\n          await client.messageFlagsRemove(uidStr, toArray(this.action.flags), {\n            uid: true,\n          });\n          break;\n      }\n    } catch (error) {\n      throwMailConnectionError(error, \"IMAP\");\n    } finally {\n      manager.releaseImap(account, client);\n    }\n  }\n\n  private async handleAppend(exchange: Exchange<unknown>): Promise<void> {\n    const context = getExchangeContext(exchange);\n    const manager = requireClientManager(context);\n    const action = this.action as Extract<MailAction, { action: \"append\" }>;\n    const account = action.account;\n\n    const smtpOpts = manager.resolveSmtpOptions(account);\n    const raw = await buildMimeMessage(\n      exchange.body as MailSendPayload,\n      smtpOpts,\n    );\n\n    const client = await manager.acquireImap(account, action.folder);\n    try {\n      await client.append(\n        action.folder,\n        raw,\n        toArray(action.flags ?? []),\n        action.date,\n      );\n    } catch (error) {\n      throwMailConnectionError(error, \"IMAP\");\n    } finally {\n      manager.releaseImap(account, client);\n    }\n  }\n\n  /**\n   * Observability metadata for the send role: describes the IMAP operation\n   * that ran. Named for the send slot (a `.to()` step resolving through\n   * `send` reads `getSendMetadata`, never `getMetadata`), and it ignores the\n   * receipt record because the operation itself is the interesting detail.\n   */\n  getSendMetadata(): Record<string, unknown> {\n    const { target, ...rest } = this.action;\n    void target;\n    return rest;\n  }\n}\n","/**\n * CardDAV adapter: reads vCard documents as a source, fetches them for\n * `.enrich()`, and creates / updates / deletes them as a destination.\n *\n * The body is a plain {@link VCardBody} (a `version` plus a property list). Wrap\n * it in a {@link VCard} for ergonomic reads/edits. DAV identity (`url`, `uid`,\n * `etag`) lives on the exchange headers (`routecraft.carddav.*`), not the body,\n * the same way the mail adapter carries its envelope metadata.\n *\n * The role is selected the same way the mail adapter selects its mode, via an\n * `action` flag on the options:\n *\n * - no action (read): `.from(carddav())` emits one `VCardBody` per address-book\n *   entry; `.enrich(carddav())` fetches all cards as a `VCardBody[]` body\n *   (pass an aggregator such as `only()` to merge instead of replacing).\n * - `action: 'save' | 'create' | 'update'`: `.to(carddav(...))` serializes the\n *   exchange body and writes it. A write replaces the card; it does not merge.\n *   Reading is lossless, so a read-modify-write keeps properties you did not\n *   touch; removing a property removes it. The write receipt (`url` / `uid` /\n *   `etag`, plus `created` for insert-vs-update) lands on the\n *   `routecraft.carddav.*` headers.\n * - `action: 'delete'`: deletes the contact resolved from the headers, the body,\n *   or a custom `target` extractor.\n *\n * Update and delete target the `routecraft.carddav.url` header and send the\n * read-time `routecraft.carddav.etag` as an `If-Match` precondition, so a\n * concurrent change surfaces as a conflict (RC5030) instead of being silently\n * overwritten. They do not re-fetch the address book; only an upsert without a\n * known url (or a delete by uid alone) pays a lookup.\n *\n * @experimental\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { CraftContext } from \"../../context.ts\";\nimport type { Exchange, ExchangeHeaders } from \"../../exchange.ts\";\nimport { getExchangeContext } from \"../../exchange.ts\";\nimport { rcError } from \"../../error.ts\";\nimport type { Source, Subscription } from \"../../operations/from.ts\";\nimport type { Destination, SendContext } from \"../../operations/to.ts\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport type { CarddavClientManager } from \"./client-manager.ts\";\nimport { VCard, type VCardBody } from \"./vcard.ts\";\nimport {\n  assertResponseOk,\n  requireClientManager,\n  selectAddressBook,\n  throwCarddavError,\n  CarddavHeaders,\n  type CarddavDriverClient,\n  type DAVAddressBookLike,\n  type DAVVCardLike,\n} from \"./shared.ts\";\nimport type {\n  CarddavAction,\n  CarddavDeleteResult,\n  CarddavOptions,\n  CarddavTargetExtractor,\n  CarddavWriteResult,\n} from \"./types.ts\";\n\n/** Identifies a contact resource for update/delete. */\ninterface ContactTarget {\n  url?: string;\n  uid?: string;\n  etag?: string;\n}\n\n/** Flattened options so field access does not require narrowing the union. */\ninterface NormalizedOptions {\n  account?: string;\n  addressBook?: string;\n  limit?: number;\n  action?: CarddavAction;\n  target?: CarddavTargetExtractor;\n}\n\nfunction uidFromUrl(url: string): string | undefined {\n  const last = url.split(\"/\").pop();\n  if (!last) return undefined;\n  const encoded = last.replace(/\\.vcf$/i, \"\");\n  if (encoded.length === 0) return undefined;\n  try {\n    return decodeURIComponent(encoded);\n  } catch {\n    return encoded;\n  }\n}\n\n/** Build the resource filename for a UID, URL-escaping it into one path segment. */\nfunction vcfFilename(uid: string): string {\n  return `${encodeURIComponent(uid)}.vcf`;\n}\n\n/**\n * Read the authoritative `UID` from a vCard payload. The DAV resource filename\n * is not guaranteed to equal the vCard `UID`, so this is preferred over\n * {@link uidFromUrl} wherever the card body is available.\n */\nfunction uidFromVCardData(data: unknown): string | undefined {\n  if (typeof data !== \"string\" || data.length === 0) return undefined;\n  try {\n    return VCard.parse(data).uid;\n  } catch {\n    return undefined;\n  }\n}\n\n/** Coerce an exchange body to a plain {@link VCardBody} (or undefined). */\nfunction coerceBody(body: unknown): VCardBody | undefined {\n  if (body instanceof VCard) return body.data;\n  if (\n    body !== null &&\n    typeof body === \"object\" &&\n    Array.isArray((body as VCardBody).properties)\n  ) {\n    return body as VCardBody;\n  }\n  return undefined;\n}\n\n/** Serialize a body, ensuring it carries `uid` (without mutating the input). */\nfunction serializeWithUid(body: VCardBody, uid: string): string {\n  const card = VCard.wrap(body);\n  if (card.uid) return card.toString();\n  const copy = card.clone();\n  copy.uid = uid;\n  return copy.toString();\n}\n\nfunction joinUrl(base: string, filename: string): string {\n  return base.endsWith(\"/\") ? `${base}${filename}` : `${base}/${filename}`;\n}\n\n/**\n * CardDAV facade: source (read all, one exchange each), enricher (fetch all\n * as an array), and destination (write / delete with receipt headers). The\n * factory exposes the role slots that match the configured `action`.\n *\n * @experimental\n */\nexport class CarddavAdapter\n  implements\n    Source<VCardBody>,\n    Destination<unknown>,\n    Enricher<unknown, VCardBody[]>\n{\n  readonly adapterId = \"routecraft.adapter.carddav\";\n  private readonly options: NormalizedOptions;\n\n  constructor(options?: CarddavOptions) {\n    this.options = { ...(options ?? {}) } as NormalizedOptions;\n  }\n\n  // -------------------------------------------------------------------------\n  // Source: read all contacts, one exchange each\n  // -------------------------------------------------------------------------\n\n  async subscribe(sub: Subscription<VCardBody>): Promise<void> {\n    const { client, book, account } = await this.openRead(sub.context);\n\n    let cards: DAVVCardLike[];\n    try {\n      cards = await client.fetchVCards({ addressBook: book });\n    } catch (error) {\n      throwCarddavError(error, \"fetch contacts\");\n    }\n\n    sub.ready();\n\n    const limit = this.options.limit;\n    let emitted = 0;\n    for (const dav of cards) {\n      if (sub.signal.aborted) break;\n      if (typeof limit === \"number\" && emitted >= limit) break;\n      const raw = typeof dav.data === \"string\" ? dav.data : \"\";\n      if (!raw) continue;\n\n      let card: VCard;\n      try {\n        card = VCard.parse(raw);\n      } catch (error) {\n        // Surface a malformed vCard as a per-exchange parse failure (RC5016)\n        // via the synthetic parse step, so the route's `.error()` handler can\n        // recover it instead of tearing down the read.\n        await sub.emit({\n          message: raw as unknown as VCardBody,\n          headers: this.buildHeaders(dav, account, uidFromUrl(dav.url)),\n          parse: () => {\n            throw error;\n          },\n          parseFailureMode: \"fail\",\n        });\n        emitted++;\n        continue;\n      }\n\n      await sub.emit({\n        message: card.data,\n        headers: this.buildHeaders(\n          dav,\n          account,\n          card.uid ?? uidFromUrl(dav.url),\n        ),\n      });\n      emitted++;\n    }\n\n    // Finite source: all contacts emitted, signal completion so the route\n    // wraps up like other finite sources instead of waiting on the\n    // context's auto-stop sweep.\n    sub.complete();\n  }\n\n  // -------------------------------------------------------------------------\n  // Enricher: fetch all cards as an array (used by `.enrich(carddav())`)\n  // -------------------------------------------------------------------------\n\n  fetch = async (exchange: Exchange<unknown>): Promise<VCardBody[]> => {\n    return this.fetchAll(getExchangeContext(exchange));\n  };\n\n  // -------------------------------------------------------------------------\n  // Destination: write / delete, selected by `action`; receipts via headers\n  // -------------------------------------------------------------------------\n\n  async send(exchange: Exchange<unknown>, ctx?: SendContext): Promise<void> {\n    const action = this.options.action;\n    if (action === undefined) {\n      throw rcError(\"RC5003\", undefined, {\n        message:\n          \"carddav adapter: the send role requires an `action` (save / create / update / delete)\",\n        suggestion:\n          \"Use `.enrich(carddav())` (or `.from(carddav())`) to read; pass an action to write\",\n      });\n    }\n    if (action === \"delete\") {\n      const result = await this.remove(exchange);\n      // Receipt headers, not a body replacement: identity of the deleted\n      // resource lands on the same routecraft.carddav.* keys the read\n      // side sets.\n      ctx?.setHeader(CarddavHeaders.URL, result.url);\n      if (result.uid) ctx?.setHeader(CarddavHeaders.UID, result.uid);\n      if (result.etag) ctx?.setHeader(CarddavHeaders.ETAG, result.etag);\n      return;\n    }\n    const result = await this.write(exchange, action);\n    // A saved card's identity lands where a read card's identity lives, so\n    // downstream update/delete steps target it without a re-read. `created`\n    // is receipt-only: it distinguishes an insert from an update for\n    // routes that branch on it.\n    ctx?.setHeader(CarddavHeaders.URL, result.url);\n    ctx?.setHeader(CarddavHeaders.UID, result.uid);\n    if (result.etag) ctx?.setHeader(CarddavHeaders.ETAG, result.etag);\n    ctx?.setHeader(CarddavHeaders.CREATED, result.created);\n  }\n\n  /** Observability metadata for the fetch role: the fetched card array. */\n  getMetadata(result: unknown): Record<string, unknown> {\n    return { count: Array.isArray(result) ? result.length : 0 };\n  }\n\n  /**\n   * Observability metadata for the send role: receives the receipt-header\n   * record collected by the `.to()` step (send is void).\n   */\n  getSendMetadata(receiptHeaders: unknown): Record<string, unknown> {\n    const receipts = (receiptHeaders ?? {}) as Record<string, unknown>;\n    const meta: Record<string, unknown> = {};\n    if (receipts[CarddavHeaders.UID] !== undefined)\n      meta[\"uid\"] = receipts[CarddavHeaders.UID];\n    if (receipts[CarddavHeaders.URL] !== undefined)\n      meta[\"url\"] = receipts[CarddavHeaders.URL];\n    if (receipts[CarddavHeaders.CREATED] !== undefined)\n      meta[\"created\"] = receipts[CarddavHeaders.CREATED];\n    return meta;\n  }\n\n  // -------------------------------------------------------------------------\n  // Read implementations\n  // -------------------------------------------------------------------------\n\n  /** Fetch all contacts as an array (best-effort: malformed cards are skipped). */\n  private async fetchAll(\n    context: CraftContext | undefined,\n  ): Promise<VCardBody[]> {\n    const { client, book } = await this.openRead(context);\n    let cards: DAVVCardLike[];\n    try {\n      cards = await client.fetchVCards({ addressBook: book });\n    } catch (error) {\n      throwCarddavError(error, \"fetch contacts\");\n    }\n    const limit = this.options.limit;\n    const out: VCardBody[] = [];\n    for (const dav of cards) {\n      if (typeof limit === \"number\" && out.length >= limit) break;\n      const raw = typeof dav.data === \"string\" ? dav.data : \"\";\n      if (!raw) continue;\n      try {\n        out.push(VCard.parse(raw).data);\n      } catch {\n        // Skip malformed cards during a bulk fetch; one bad card must not fail\n        // the whole enrichment.\n      }\n    }\n    return out;\n  }\n\n  // -------------------------------------------------------------------------\n  // Write implementation\n  // -------------------------------------------------------------------------\n\n  private async write(\n    exchange: Exchange<unknown>,\n    action: \"save\" | \"create\" | \"update\",\n  ): Promise<CarddavWriteResult> {\n    const body = coerceBody(exchange.body);\n    if (!body) {\n      throw rcError(\"RC5001\", undefined, {\n        message: `CardDAV ${action} requires the exchange body to be a VCard document (a VCardBody or a VCard). Build one with VCard.parse(), VCard.create(), or VCard.wrap().`,\n      });\n    }\n    const target = this.resolveTarget(exchange);\n    const { client, manager, account } = await this.connect(\n      getExchangeContext(exchange),\n    );\n\n    if (action === \"update\") {\n      const url = target.url;\n      if (!url) {\n        throw rcError(\"RC5014\", undefined, {\n          message:\n            \"CardDAV update needs a contact url (the routecraft.carddav.url header). Read the contact first, or use action: 'save'.\",\n        });\n      }\n      return this.put(client, url, body, target);\n    }\n\n    if (action === \"create\") {\n      const book = await this.resolveBook(client, manager, account);\n      return this.create(client, book, body);\n    }\n\n    // save (upsert): update in place when we know the url, else create and only\n    // fall back to a lookup if the resource already exists.\n    if (target.url) {\n      return this.put(client, target.url, body, target);\n    }\n    const book = await this.resolveBook(client, manager, account);\n    const uid = VCard.wrap(body).uid ?? target.uid ?? randomUUID();\n    const filename = vcfFilename(uid);\n    let response: Response;\n    try {\n      response = await client.createVCard({\n        addressBook: book,\n        vCardString: serializeWithUid(body, uid),\n        filename,\n      });\n    } catch (error) {\n      throwCarddavError(error, \"save contact\");\n    }\n    if (response.status === 412) {\n      const existing = await this.findByUid(client, book, uid);\n      if (existing) {\n        const conflictTarget: ContactTarget = { uid };\n        if (existing.etag) conflictTarget.etag = existing.etag;\n        return this.put(client, existing.url, body, conflictTarget);\n      }\n    }\n    assertResponseOk(response, \"save contact\");\n    return this.createResult(uid, joinUrl(book.url, filename), response);\n  }\n\n  /** PUT a full serialization of `body` to `url`, with `If-Match` when known. */\n  private async put(\n    client: CarddavDriverClient,\n    url: string,\n    body: VCardBody,\n    target: ContactTarget,\n  ): Promise<CarddavWriteResult> {\n    const uid =\n      VCard.wrap(body).uid ?? target.uid ?? uidFromUrl(url) ?? randomUUID();\n    const vCard: DAVVCardLike = { url, data: serializeWithUid(body, uid) };\n    const etag = target.etag;\n    if (etag) vCard.etag = etag;\n    let response: Response;\n    try {\n      response = await client.updateVCard({ vCard });\n    } catch (error) {\n      throwCarddavError(error, \"update contact\");\n    }\n    assertResponseOk(response, \"update contact\");\n    const result: CarddavWriteResult = { uid, url, created: false };\n    const newEtag = response.headers.get(\"etag\") ?? etag;\n    if (newEtag) result.etag = newEtag;\n    return result;\n  }\n\n  /** Create a new card. Relies on the driver's `If-None-Match: *` precondition. */\n  private async create(\n    client: CarddavDriverClient,\n    book: DAVAddressBookLike,\n    body: VCardBody,\n  ): Promise<CarddavWriteResult> {\n    const uid = VCard.wrap(body).uid ?? randomUUID();\n    const filename = vcfFilename(uid);\n    let response: Response;\n    try {\n      response = await client.createVCard({\n        addressBook: book,\n        vCardString: serializeWithUid(body, uid),\n        filename,\n      });\n    } catch (error) {\n      throwCarddavError(error, \"create contact\");\n    }\n    assertResponseOk(response, \"create contact\");\n    return this.createResult(uid, joinUrl(book.url, filename), response);\n  }\n\n  private createResult(\n    uid: string,\n    url: string,\n    response: Response,\n  ): CarddavWriteResult {\n    const result: CarddavWriteResult = { uid, url, created: true };\n    const etag = response.headers.get(\"etag\");\n    if (etag) result.etag = etag;\n    return result;\n  }\n\n  // -------------------------------------------------------------------------\n  // Delete implementation\n  // -------------------------------------------------------------------------\n\n  private async remove(\n    exchange: Exchange<unknown>,\n  ): Promise<CarddavDeleteResult> {\n    const { client, manager, account } = await this.connect(\n      getExchangeContext(exchange),\n    );\n    const target = this.resolveTarget(exchange);\n    let url = target.url;\n    let etag = target.etag;\n    let uid = target.uid;\n\n    if (!url) {\n      if (!uid) {\n        throw rcError(\"RC5014\", undefined, {\n          message:\n            \"CardDAV delete found no target. Provide the routecraft.carddav.url/uid headers, a VCard body with a UID, or a target extractor.\",\n        });\n      }\n      const book = await this.resolveBook(client, manager, account);\n      const existing = await this.findByUid(client, book, uid);\n      if (!existing) {\n        throw rcError(\"RC5014\", undefined, {\n          message: `CardDAV delete found no contact with uid '${uid}'.`,\n        });\n      }\n      url = existing.url;\n      etag = etag ?? existing.etag;\n      uid = uid ?? uidFromVCardData(existing.data) ?? uidFromUrl(existing.url);\n    }\n\n    const vCard: DAVVCardLike = { url };\n    if (etag) vCard.etag = etag;\n    let response: Response;\n    try {\n      response = await client.deleteVCard({ vCard });\n    } catch (error) {\n      throwCarddavError(error, \"delete contact\");\n    }\n    assertResponseOk(response, \"delete contact\");\n    const result: CarddavDeleteResult = { url };\n    const resolvedUid = uid ?? uidFromUrl(url);\n    if (resolvedUid) result.uid = resolvedUid;\n    // A uid-only delete looks the card up to find its url; the lookup also\n    // yields the etag, so carry it out for the receipt instead of dropping it.\n    if (etag) result.etag = etag;\n    return result;\n  }\n\n  // -------------------------------------------------------------------------\n  // Shared helpers\n  // -------------------------------------------------------------------------\n\n  /** Acquire a logged-in client (no address-book lookup). */\n  private async connect(context: CraftContext | undefined): Promise<{\n    client: CarddavDriverClient;\n    manager: CarddavClientManager;\n    account: string | undefined;\n  }> {\n    const manager = requireClientManager(context);\n    const account = this.options.account;\n    const client = await manager.getClient(account);\n    return { client, manager, account };\n  }\n\n  /** Acquire a client and resolve the target address book (read/create paths). */\n  private async openRead(context: CraftContext | undefined): Promise<{\n    client: CarddavDriverClient;\n    book: DAVAddressBookLike;\n    account: string | undefined;\n  }> {\n    const { client, manager, account } = await this.connect(context);\n    const book = await this.resolveBook(client, manager, account);\n    return { client, book, account };\n  }\n\n  private buildHeaders(\n    dav: DAVVCardLike,\n    account: string | undefined,\n    uid: string | undefined,\n  ): ExchangeHeaders {\n    const headers: Record<string, unknown> = {\n      [CarddavHeaders.URL]: dav.url,\n    };\n    if (uid) headers[CarddavHeaders.UID] = uid;\n    if (dav.etag) headers[CarddavHeaders.ETAG] = dav.etag;\n    if (account) headers[CarddavHeaders.ACCOUNT] = account;\n    return headers as ExchangeHeaders;\n  }\n\n  private resolveBook(\n    client: CarddavDriverClient,\n    manager: CarddavClientManager,\n    account: string | undefined,\n  ): Promise<DAVAddressBookLike> {\n    return client\n      .fetchAddressBooks()\n      .then((books) =>\n        selectAddressBook(\n          books,\n          this.options.addressBook ?? manager.resolveAddressBookName(account),\n        ),\n      )\n      .catch((error: unknown) =>\n        throwCarddavError(error, \"list address books\"),\n      );\n  }\n\n  /** Resolve the target contact from a custom extractor, the headers, or the body. */\n  private resolveTarget(exchange: Exchange<unknown>): ContactTarget {\n    const body = coerceBody(exchange.body);\n    const cardUid = body ? VCard.wrap(body).uid : undefined;\n    const headerEtag = exchange.headers[CarddavHeaders.ETAG];\n    const etag = typeof headerEtag === \"string\" ? headerEtag : undefined;\n\n    let url: string | undefined;\n    let uid: string | undefined;\n    if (this.options.target) {\n      const extracted = this.options.target(exchange);\n      url = extracted.url;\n      uid = extracted.uid ?? cardUid;\n    } else {\n      const headerUrl = exchange.headers[CarddavHeaders.URL];\n      const headerUid = exchange.headers[CarddavHeaders.UID];\n      url = typeof headerUrl === \"string\" ? headerUrl : undefined;\n      uid = cardUid ?? (typeof headerUid === \"string\" ? headerUid : undefined);\n    }\n\n    const target: ContactTarget = {};\n    if (url) target.url = url;\n    if (uid) target.uid = uid;\n    if (etag) target.etag = etag;\n    return target;\n  }\n\n  /** Locate a card by vCard UID (falls back to the resource filename). */\n  private async findByUid(\n    client: CarddavDriverClient,\n    book: DAVAddressBookLike,\n    uid: string,\n  ): Promise<DAVVCardLike | undefined> {\n    let all: DAVVCardLike[];\n    try {\n      all = await client.fetchVCards({ addressBook: book });\n    } catch (error) {\n      throwCarddavError(error, \"look up contact\");\n    }\n    for (const dav of all) {\n      if (uidFromUrl(dav.url) === uid) return dav;\n      if (typeof dav.data === \"string\") {\n        try {\n          if (VCard.parse(dav.data).uid === uid) return dav;\n        } catch {\n          // Skip cards that fail to parse while searching for a match.\n        }\n      }\n    }\n    return undefined;\n  }\n}\n","/**\n * Low-level vCard lexer and emitter primitives.\n *\n * Parses raw vCard text into a flat list of {@link RawRecord}s (one per logical\n * line, folding undone, every parameter captured verbatim) and emits a single\n * property line back to RFC 6350 wire form (escaping, folding, parameter\n * quoting). The {@link VCard} document model in `vcard.ts` is built on top of\n * these; there is no typed projection here and nothing Apple-specific.\n *\n * @experimental\n */\n\nconst CRLF = \"\\r\\n\";\n\n/** A single vCard parameter, captured verbatim (name lowercased, value dequoted). */\nexport interface VCardParam {\n  /** Parameter name, lowercased (e.g. `type`, `x-service-type`). */\n  name: string;\n  /** Parameter value with surrounding quotes removed, original casing kept. */\n  value: string;\n}\n\n/** One logical vCard line (folding undone), parsed into its parts. */\nexport interface RawRecord {\n  /** Lowercased property name without the group prefix (e.g. `tel`). */\n  name: string;\n  /** Lowercased group prefix (e.g. `item1`), or null. */\n  group: string | null;\n  /** Original property name as written (e.g. `X-SOCIALPROFILE`). */\n  rawName: string;\n  /** Original group as written (e.g. `item1`), or null. */\n  rawGroup: string | null;\n  /** Every parameter, in wire order, captured verbatim. */\n  params: VCardParam[];\n  /** Unescaped value (RFC 6350 text escapes decoded, line folding undone). */\n  value: string;\n  /** Raw (still-escaped) value, for component-accurate structured splitting. */\n  rawValue: string;\n}\n\n// ---------------------------------------------------------------------------\n// Parsing\n// ---------------------------------------------------------------------------\n\n/** Split raw vCard text into records, unfolding continuation lines. */\nexport function parseRecords(raw: string): RawRecord[] {\n  const physical = raw.split(/\\r\\n|\\r|\\n/);\n  const records: RawRecord[] = [];\n  let current: string[] | null = null;\n\n  const flush = (): void => {\n    if (current) records.push(toRecord(current));\n    current = null;\n  };\n\n  for (const line of physical) {\n    // Blank lines between records (some exporters emit them around BEGIN:VCARD)\n    // are not header lines and must not seed phantom records.\n    if (line === \"\") continue;\n    if ((line.startsWith(\" \") || line.startsWith(\"\\t\")) && current) {\n      current.push(line);\n    } else {\n      flush();\n      current = [line];\n    }\n  }\n  flush();\n  return records;\n}\n\n/** Index of the first `ch` in `s` that is not inside a double-quoted span. */\nfunction indexOfUnquoted(s: string, ch: string): number {\n  let inQuote = false;\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (c === '\"') inQuote = !inQuote;\n    else if (c === ch && !inQuote) return i;\n  }\n  return -1;\n}\n\n/** Split `s` on `;` that are not inside a double-quoted param value. */\nfunction splitUnquoted(s: string): string[] {\n  const out: string[] = [];\n  let current = \"\";\n  let inQuote = false;\n  for (const c of s) {\n    if (c === '\"') {\n      inQuote = !inQuote;\n      current += c;\n    } else if (c === \";\" && !inQuote) {\n      out.push(current);\n      current = \"\";\n    } else {\n      current += c;\n    }\n  }\n  out.push(current);\n  return out;\n}\n\n/** Strip surrounding double quotes from a parameter value (RFC 6350 3.3). */\nfunction dequoteParam(value: string): string {\n  return value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')\n    ? value.slice(1, -1)\n    : value;\n}\n\nfunction toRecord(lines: string[]): RawRecord {\n  // Undo folding to recover the logical line.\n  const logical = lines\n    .map((line, index) => (index === 0 ? line : line.slice(1)))\n    .join(\"\");\n\n  // The header/value boundary is the first colon not inside a quoted param\n  // value (e.g. `KEY;TYPE=\"a:b\":value`).\n  const colon = indexOfUnquoted(logical, \":\");\n  const header = colon >= 0 ? logical.slice(0, colon) : logical;\n  const value = colon >= 0 ? logical.slice(colon + 1) : \"\";\n\n  const segments = splitUnquoted(header);\n  const nameSegment = segments[0] ?? \"\";\n  const dot = nameSegment.indexOf(\".\");\n  const rawGroup = dot >= 0 ? nameSegment.slice(0, dot) : null;\n  const rawName = dot >= 0 ? nameSegment.slice(dot + 1) : nameSegment;\n\n  const params: VCardParam[] = [];\n  for (const segment of segments.slice(1)) {\n    if (segment === \"\") continue;\n    const eq = segment.indexOf(\"=\");\n    const name = (eq >= 0 ? segment.slice(0, eq) : segment).toLowerCase();\n    const paramValue = dequoteParam(eq >= 0 ? segment.slice(eq + 1) : \"\");\n    params.push({ name, value: paramValue });\n  }\n\n  return {\n    name: rawName.toLowerCase(),\n    group: rawGroup ? rawGroup.toLowerCase() : null,\n    rawName,\n    rawGroup,\n    params,\n    value: unescapeText(value),\n    rawValue: value,\n  };\n}\n\n/** First value of the named parameter (case-insensitive), if present. */\nexport function firstParam(\n  params: VCardParam[],\n  name: string,\n): string | undefined {\n  const lower = name.toLowerCase();\n  return params.find((p) => p.name.toLowerCase() === lower)?.value;\n}\n\n/**\n * Split a vCard value on `separator` characters that are not preceded by a\n * backslash, then unescape each segment. Explicit escape tracking handles `\\,`/\n * `\\;` (escaped separator) and `\\\\,`/`\\\\;` (escaped backslash + separator)\n * correctly, which a naive `split()` over the unescaped value does not.\n */\nexport function splitOnUnescaped(\n  rawValue: string,\n  separator: string,\n): string[] {\n  const parts: string[] = [];\n  let current = \"\";\n  for (let i = 0; i < rawValue.length; i++) {\n    const ch = rawValue[i];\n    if (ch === \"\\\\\" && i + 1 < rawValue.length) {\n      current += ch + rawValue[i + 1];\n      i++;\n    } else if (ch === separator) {\n      parts.push(current);\n      current = \"\";\n    } else {\n      current += ch;\n    }\n  }\n  parts.push(current);\n  return parts.map(unescapeText);\n}\n\n// ---------------------------------------------------------------------------\n// Escape / emit primitives\n// ---------------------------------------------------------------------------\n\n/**\n * Escape a value per RFC 6350 (backslash, comma, semicolon, newline). Used for\n * free-text values and for individual components of structured values, where the\n * literal `;`/`,` separators are added by the caller afterwards. `\\r`, `\\r\\n`\n * and `\\n` all collapse to the `\\n` escape so a stray line ending in\n * user-supplied text cannot break the on-wire grammar.\n */\nexport function escapeText(value: string): string {\n  return value\n    .replace(/\\\\/g, \"\\\\\\\\\")\n    .replace(/\\r\\n?|\\n/g, \"\\\\n\")\n    .replace(/,/g, \"\\\\,\")\n    .replace(/;/g, \"\\\\;\");\n}\n\n/** Decode RFC 6350 text escapes (`\\\\`, `\\,`, `\\;`, `\\n`). */\nexport function unescapeText(value: string): string {\n  return value.replace(/\\\\([\\\\,;nN])/g, (_m, ch: string) =>\n    ch === \"n\" || ch === \"N\" ? \"\\n\" : ch,\n  );\n}\n\n/**\n * Quote a parameter value per RFC 6350 3.3 when it contains characters that\n * would break the header grammar. Embedded double-quotes and newlines are not\n * representable in a quoted param, so they are stripped.\n */\nfunction escapeParamValue(value: string): string {\n  const cleaned = value.replace(/[\"\\r\\n]/g, \"\");\n  return /[;:,]/.test(cleaned) ? `\"${cleaned}\"` : cleaned;\n}\n\n/**\n * Fold a logical line to <=75 octets per physical line using CRLF + single\n * space continuations (RFC 6350 3.2). Counts UTF-8 byte length and never splits\n * inside a code point, so multibyte values (accents, CJK, emoji) fold safely.\n * The leading space of a continuation counts toward its 75 octets.\n */\nfunction foldLine(line: string): string {\n  if (Buffer.byteLength(line, \"utf8\") <= 75) return line;\n  const out: string[] = [];\n  let current = \"\";\n  let currentBytes = 0;\n  let isContinuation = false;\n  const maxContentBytes = (): number => (isContinuation ? 74 : 75);\n  for (const ch of line) {\n    const charBytes = Buffer.byteLength(ch, \"utf8\");\n    if (current !== \"\" && currentBytes + charBytes > maxContentBytes()) {\n      out.push(isContinuation ? ` ${current}` : current);\n      isContinuation = true;\n      current = ch;\n      currentBytes = charBytes;\n    } else {\n      current += ch;\n      currentBytes += charBytes;\n    }\n  }\n  if (current !== \"\") out.push(isContinuation ? ` ${current}` : current);\n  return out.join(CRLF);\n}\n\n/** A property to emit: group + name + params + an already-escaped value. */\nexport interface PropertySpec {\n  name: string;\n  group?: string | null;\n  params?: VCardParam[];\n  /** Value bytes as they should appear after the colon (already escaped). */\n  value: string;\n}\n\n/** Emit one property as folded wire text (no trailing CRLF). */\nexport function emitProperty(spec: PropertySpec): string {\n  const prefix = spec.group ? `${spec.group}.` : \"\";\n  let header = `${prefix}${spec.name}`;\n  for (const param of spec.params ?? []) {\n    header += `;${param.name}=${escapeParamValue(param.value)}`;\n  }\n  return foldLine(`${header}:${spec.value}`);\n}\n","/**\n * vCard document: a plain-data body plus an optional {@link VCard} wrapper.\n *\n * The exchange body is plain, serialization-safe data ({@link VCardBody}): a\n * version string and an ordered list of {@link VCardPropertyData}. It survives\n * `structuredClone`, `JSON.stringify`, queues, and `tap` with nothing lost,\n * because it is just data.\n *\n * For ergonomics, wrap a body in a {@link VCard} (`VCard.wrap(body)`,\n * `VCard.create()`, `VCard.parse(string)`). The wrapper reads and edits the\n * underlying data in place and exposes `.data` to get the plain body back. The\n * wrapper is a transient view, never the body itself, so the body stays plain.\n *\n * @experimental\n */\n\nimport {\n  emitProperty,\n  escapeText,\n  firstParam,\n  parseRecords,\n  splitOnUnescaped,\n  unescapeText,\n  type PropertySpec,\n  type VCardParam,\n} from \"./vcard-raw.ts\";\n\nconst CRLF = \"\\r\\n\";\nconst DEFAULT_VERSION = \"3.0\";\n\n/** Valid characters for a vCard property name, group, or parameter name. */\nconst NAME_PATTERN = /^[A-Za-z0-9-]+$/;\n\n/** Throw on a name/group/param that could break the header grammar on emit. */\nfunction assertValidName(value: string, kind = \"property name\"): void {\n  if (!NAME_PATTERN.test(value)) {\n    throw new SyntaxError(\n      `Invalid vCard ${kind} ${JSON.stringify(value)}: only letters, digits, and hyphens are allowed.`,\n    );\n  }\n}\n\n/**\n * A single vCard property as plain data. `value` is the escaped wire value (the\n * lossless source of truth); use {@link VCardProperty.value} on a wrapper for\n * the decoded text, or {@link VCardProperty.components} for structured values.\n */\nexport interface VCardPropertyData {\n  /** Property name as written (e.g. `\"TEL\"`, `\"X-SOCIALPROFILE\"`). */\n  name: string;\n  /** Group prefix (e.g. `\"item1\"`), if any. */\n  group?: string;\n  /** Parameters, in order, captured verbatim. */\n  params: VCardParam[];\n  /** Escaped wire value (post-unfold), exactly as it appears after the colon. */\n  value: string;\n}\n\n/** A vCard document as plain data. This is the exchange body. */\nexport interface VCardBody {\n  /** vCard version (default `\"3.0\"`). */\n  version: string;\n  /** The ordered property list. */\n  properties: VCardPropertyData[];\n}\n\n/** Options when adding a property. */\nexport interface VCardPropertyOptions {\n  /** Group prefix (e.g. `\"item1\"`) for label-grouped properties. */\n  group?: string;\n  /** Parameters to attach (e.g. `[{ name: \"type\", value: \"home\" }]`). */\n  params?: VCardParam[];\n}\n\n/**\n * A transient view over one {@link VCardPropertyData}. Reads and writes go\n * straight through to the underlying plain object, so edits are reflected in the\n * body. `value` is decoded text; `raw` is the escaped wire form.\n */\nexport class VCardProperty {\n  constructor(private readonly data: VCardPropertyData) {}\n\n  /** Property name as written. */\n  get name(): string {\n    return this.data.name;\n  }\n  /** Group prefix, or undefined. */\n  get group(): string | undefined {\n    return this.data.group;\n  }\n  /** Parameters, in order. */\n  get params(): VCardParam[] {\n    return this.data.params;\n  }\n  /** Decoded text value (RFC 6350 escapes resolved). */\n  get value(): string {\n    return unescapeText(this.data.value);\n  }\n  set value(v: string) {\n    this.data.value = escapeText(v);\n  }\n  /** The escaped wire value, exactly as it appears after the colon. */\n  get raw(): string {\n    return this.data.value;\n  }\n\n  /** Decoded components of a structured value, split on unescaped `separator`. */\n  components(separator = \";\"): string[] {\n    return splitOnUnescaped(this.data.value, separator);\n  }\n\n  /** Set a structured value from decoded components (each escaped, then joined). */\n  setComponents(parts: string[], separator = \";\"): this {\n    this.data.value = parts.map(escapeText).join(separator);\n    return this;\n  }\n\n  /** First value of the named parameter (case-insensitive), if present. */\n  param(name: string): string | undefined {\n    return firstParam(this.data.params, name);\n  }\n}\n\n/**\n * An ergonomic wrapper around a {@link VCardBody}. Construct one with\n * {@link VCard.wrap}, {@link VCard.create}, or {@link VCard.parse}; read it with\n * `get`/`first`/`text`; edit it with `set`/`add`/`remove`; and read `.data` to\n * get the plain body to put back on the exchange.\n */\nexport class VCard {\n  /** The underlying plain-data body. */\n  readonly data: VCardBody;\n\n  private constructor(data: VCardBody) {\n    this.data = data;\n  }\n\n  /** Wrap an existing plain body (edits write through to it). */\n  static wrap(body: VCardBody): VCard {\n    return new VCard(body);\n  }\n\n  /** Create a wrapper over a fresh, empty body. */\n  static create(version: string = DEFAULT_VERSION): VCard {\n    return new VCard({ version, properties: [] });\n  }\n\n  /**\n   * Parse a single vCard string into a wrapper. `.data` is the plain body.\n   *\n   * @throws If the input is not a single `BEGIN:VCARD ... END:VCARD` block.\n   */\n  static parse(raw: string): VCard {\n    const records = parseRecords(raw);\n    let beginCount = 0;\n    let hasEnd = false;\n    let version = DEFAULT_VERSION;\n    const properties: VCardPropertyData[] = [];\n\n    for (const record of records) {\n      if (\n        record.name === \"begin\" &&\n        !record.group &&\n        record.value.toUpperCase() === \"VCARD\"\n      ) {\n        beginCount++;\n        continue;\n      }\n      if (\n        record.name === \"end\" &&\n        !record.group &&\n        record.value.toUpperCase() === \"VCARD\"\n      ) {\n        hasEnd = true;\n        continue;\n      }\n      if (record.name === \"version\" && !record.group) {\n        version = record.value;\n        continue;\n      }\n      properties.push({\n        name: record.rawName,\n        ...(record.rawGroup !== null ? { group: record.rawGroup } : {}),\n        params: record.params,\n        value: record.rawValue,\n      });\n    }\n\n    if (beginCount === 0 || !hasEnd) {\n      throw new SyntaxError(\n        \"vCard payload did not contain a BEGIN:VCARD/END:VCARD block\",\n      );\n    }\n    if (beginCount > 1) {\n      throw new SyntaxError(\n        \"vCard payload contains a vCard collection; VCard.parse accepts a single card\",\n      );\n    }\n    return new VCard({ version, properties });\n  }\n\n  /** Serialize a plain body to wire form (`BEGIN:VCARD` ... `END:VCARD`). */\n  static serialize(body: VCardBody): string {\n    const lines = [\"BEGIN:VCARD\", `VERSION:${body.version}`];\n    for (const p of body.properties) {\n      const spec: PropertySpec = {\n        name: p.name,\n        params: p.params,\n        value: p.value,\n      };\n      if (p.group !== undefined) spec.group = p.group;\n      lines.push(emitProperty(spec));\n    }\n    lines.push(\"END:VCARD\");\n    return lines.join(CRLF);\n  }\n\n  // -- reads -----------------------------------------------------------------\n\n  /** vCard version. */\n  get version(): string {\n    return this.data.version;\n  }\n  set version(v: string) {\n    this.data.version = v;\n  }\n\n  /** Property views, in order. */\n  get properties(): VCardProperty[] {\n    return this.data.properties.map((p) => new VCardProperty(p));\n  }\n\n  /** All properties with the given name (case-insensitive). */\n  get(name: string): VCardProperty[] {\n    const lower = name.toLowerCase();\n    return this.data.properties\n      .filter((p) => p.name.toLowerCase() === lower)\n      .map((p) => new VCardProperty(p));\n  }\n\n  /** The first property with the given name (case-insensitive), if any. */\n  first(name: string): VCardProperty | undefined {\n    const lower = name.toLowerCase();\n    const data = this.data.properties.find(\n      (p) => p.name.toLowerCase() === lower,\n    );\n    return data ? new VCardProperty(data) : undefined;\n  }\n\n  /** Decoded value of the first property with the given name. */\n  text(name: string): string | undefined {\n    return this.first(name)?.value;\n  }\n\n  /** Decoded values of every property with the given name. */\n  values(name: string): string[] {\n    return this.get(name).map((p) => p.value);\n  }\n\n  /** The vCard `UID`, if present. */\n  get uid(): string | undefined {\n    return this.text(\"UID\");\n  }\n  set uid(value: string | undefined) {\n    if (value === undefined) this.remove(\"UID\");\n    else this.set(\"UID\", value);\n  }\n\n  // -- writes ----------------------------------------------------------------\n\n  /** Append a property (a decoded value, escaped on the way in). */\n  add(name: string, value: string, options: VCardPropertyOptions = {}): this {\n    assertValidName(name);\n    if (options.group !== undefined) assertValidName(options.group, \"group\");\n    for (const param of options.params ?? []) {\n      assertValidName(param.name, \"parameter name\");\n    }\n    this.data.properties.push({\n      name,\n      ...(options.group !== undefined ? { group: options.group } : {}),\n      params: options.params ?? [],\n      value: escapeText(value),\n    });\n    return this;\n  }\n\n  /** Replace every property of `name` with a single one (case-insensitive). */\n  set(name: string, value: string, options?: VCardPropertyOptions): this {\n    this.remove(name);\n    return this.add(name, value, options);\n  }\n\n  /** Remove every property with the given name (case-insensitive). */\n  remove(name: string): this {\n    const lower = name.toLowerCase();\n    this.data.properties = this.data.properties.filter(\n      (p) => p.name.toLowerCase() !== lower,\n    );\n    return this;\n  }\n\n  /** Serialize this card's data to wire form. */\n  toString(): string {\n    return VCard.serialize(this.data);\n  }\n\n  /** A deep, independent copy (wrapper over cloned data). */\n  clone(): VCard {\n    return new VCard(structuredClone(this.data));\n  }\n\n  /** Plain representation for `JSON.stringify` / logging (the body). */\n  toJSON(): VCardBody {\n    return this.data;\n  }\n}\n\n/** Parse a vCard string into a {@link VCard} wrapper. */\nexport function parseVCard(raw: string): VCard {\n  return VCard.parse(raw);\n}\n","/**\n * Well-known vCard property and parameter names.\n *\n * A convenience catalog of the standardized vocabulary (RFC 6350 plus the common\n * Apple `X-` extensions), NOT a constraint: every {@link VCard} method accepts an\n * arbitrary `string`, so any property name (including ones not listed here) still\n * works. Use these for autocomplete and typo-safety on the names you know.\n *\n * @experimental\n */\n\n/** Well-known vCard property names (RFC 6350 and common Apple extensions). */\nexport const VCARD = {\n  /** Formatted display name (`FN`). Mandatory in a vCard. */\n  FN: \"FN\",\n  /** Structured name: `family;given;additional;prefixes;suffixes` (`N`). */\n  N: \"N\",\n  /** Nickname(s) (`NICKNAME`). */\n  NICKNAME: \"NICKNAME\",\n  /** Organization: `org;unit1;unit2` (`ORG`). */\n  ORG: \"ORG\",\n  /** Job title (`TITLE`). */\n  TITLE: \"TITLE\",\n  /** Telephone number (`TEL`). */\n  TEL: \"TEL\",\n  /** Email address (`EMAIL`). */\n  EMAIL: \"EMAIL\",\n  /** Structured postal address (`ADR`). */\n  ADR: \"ADR\",\n  /** Associated URL (`URL`). */\n  URL: \"URL\",\n  /** Instant-messaging handle (`IMPP`). */\n  IMPP: \"IMPP\",\n  /** Birthday (`BDAY`). */\n  BDAY: \"BDAY\",\n  /** Free-form note (`NOTE`). */\n  NOTE: \"NOTE\",\n  /** Photo, inline base64 or a URI (`PHOTO`). */\n  PHOTO: \"PHOTO\",\n  /** Tags / groups, comma-separated (`CATEGORIES`). */\n  CATEGORIES: \"CATEGORIES\",\n  /** Stable unique identifier (`UID`). */\n  UID: \"UID\",\n  /** Revision timestamp (`REV`). */\n  REV: \"REV\",\n  /** Product identifier of the authoring application (`PRODID`). */\n  PRODID: \"PRODID\",\n  /** Social-media profile, iCloud extension (`X-SOCIALPROFILE`). */\n  X_SOCIALPROFILE: \"X-SOCIALPROFILE\",\n  /** IM service name, iCloud extension (`X-SERVICE-TYPE`). */\n  X_SERVICE_TYPE: \"X-SERVICE-TYPE\",\n  /** Custom label for a grouped property, iCloud extension (`X-ABLabel`). */\n  X_ABLABEL: \"X-ABLabel\",\n  /** Labeled custom date such as an anniversary, iCloud extension (`X-ABDATE`). */\n  X_ABDATE: \"X-ABDATE\",\n  /** Labeled related person, iCloud extension (`X-ABRELATEDNAMES`). */\n  X_ABRELATEDNAMES: \"X-ABRELATEDNAMES\",\n} as const;\n\n/** Well-known vCard parameter names (lowercased, matching the parsed form). */\nexport const VPARAM = {\n  /** Property kind/label, e.g. `home`, `work`, `cell` (`TYPE`). */\n  TYPE: \"type\",\n  /** Value-type override, e.g. `uri` (`VALUE`). */\n  VALUE: \"value\",\n  /** Inline binary encoding, e.g. `b` for base64 (`ENCODING`). */\n  ENCODING: \"encoding\",\n} as const;\n\n/** Union of the well-known property names in {@link VCARD}. */\nexport type KnownProperty = (typeof VCARD)[keyof typeof VCARD];\n\n/** Union of the well-known parameter names in {@link VPARAM}. */\nexport type KnownParam = (typeof VPARAM)[keyof typeof VPARAM];\n","import type { Source } from \"../../operations/from.ts\";\nimport type { Destination } from \"../../operations/to.ts\";\nimport type { Enricher } from \"../../operations/enrich.ts\";\nimport { tagAdapter, factoryArgs } from \"../shared/factory-tag.ts\";\nimport { withAdapterIdentity } from \"../shared/role-facade.ts\";\nimport { CarddavAdapter } from \"./adapter.ts\";\nimport type { VCardBody } from \"./vcard.ts\";\nimport type {\n  CarddavClientOptions,\n  CarddavOptions,\n  CarddavServerOptions,\n} from \"./types.ts\";\n\n/**\n * Create a CardDAV adapter for reading and writing contacts. Defaults to Apple\n * iCloud Contacts; works with any CardDAV server. Credentials come from context\n * `carddav` config (named accounts). The `action` flag selects the role, the\n * same way the mail adapter does.\n *\n * The body is a plain {@link VCardBody} (a `version` plus a property list), not\n * a typed contact. Wrap it in a {@link VCard} (`VCard.wrap(body)`,\n * `VCard.create()`, `VCard.parse(string)`) for ergonomic reads and edits, then\n * read `.data` to put the plain body back. Identity (`url`/`uid`/`etag`) lives\n * on the exchange headers. Reading is lossless and a write replaces the card\n * with the document you hand back.\n *\n * **Read (`.from()` / `.enrich()`):** call with no `action`. `.from(carddav())`\n * emits one {@link VCardBody} per address-book entry; `.enrich(carddav())`\n * fetches all cards and the `VCardBody[]` replaces the body (pass an\n * aggregator such as `only()` to merge instead).\n *\n * **Write (`.to()`):** `action: 'save'` upserts (writes to the card's `url`,\n * else creates), `'create'` always inserts, `'update'` writes to the card's\n * `url` (else `RC5014`). The send is void: the card body flows through\n * unchanged and the write receipt (`routecraft.carddav.url` / `.uid` /\n * `.etag`, plus `.created` for insert-vs-update) lands on the same headers\n * the read side sets.\n *\n * **Delete (`.to()`):** `action: 'delete'` removes the contact resolved from the\n * body (`url`/`uid`), the read headers, or a custom `target` extractor. The\n * deleted resource's identity lands on the receipt headers.\n *\n * @example\n * ```typescript\n * // Read all contacts (source).\n * craft().from(carddav()).to(processCard());\n *\n * // Read, edit one property, write back (everything else is preserved).\n * craft()\n *   .from(carddav())\n *   .transform((card) => card.set(\"NOTE\", \"synced from CRM\"))\n *   .to(carddav({ action: \"update\" }));\n *\n * // Delete stale contacts.\n * craft().from(carddav()).filter(isStale).to(carddav({ action: \"delete\" }));\n * ```\n *\n * @experimental\n */\nexport function carddav(\n  options?: CarddavServerOptions,\n): Source<VCardBody> & Enricher<unknown, VCardBody[]>;\nexport function carddav(\n  options: CarddavClientOptions & { action: \"save\" | \"create\" | \"update\" },\n): Destination<VCardBody>;\nexport function carddav(\n  options: CarddavClientOptions & { action: \"delete\" },\n): Destination<unknown>;\nexport function carddav(\n  options?: CarddavOptions,\n):\n  | (Source<VCardBody> & Enricher<unknown, VCardBody[]>)\n  | Destination<VCardBody>\n  | Destination<unknown> {\n  const adapter = new CarddavAdapter(options);\n  const args = factoryArgs(options);\n  // Expose only the slots that match the configured action, so the runtime\n  // object agrees with the declared type: a read-shaped carddav() has no\n  // `send` (`.to(carddav())` resolves to fetch and replaces the body), and\n  // an action-shaped one has no `subscribe`/`fetch`.\n  if (options?.action) {\n    const destination: Destination<unknown> & {\n      getSendMetadata(receipts: unknown): Record<string, unknown>;\n    } = {\n      adapterId: adapter.adapterId,\n      send: (exchange, ctx) => adapter.send(exchange, ctx),\n      getSendMetadata: (receipts) => adapter.getSendMetadata(receipts),\n    };\n    return tagAdapter(\n      withAdapterIdentity(destination, adapter),\n      carddav,\n      args,\n    ) as Destination<VCardBody>;\n  }\n  const reader: Source<VCardBody> &\n    Enricher<unknown, VCardBody[]> & {\n      getMetadata(result: unknown): Record<string, unknown>;\n    } = {\n    adapterId: adapter.adapterId,\n    subscribe: (sub) => adapter.subscribe(sub),\n    fetch: adapter.fetch,\n    getMetadata: (result) => adapter.getMetadata(result),\n  };\n  return tagAdapter(withAdapterIdentity(reader, adapter), carddav, args);\n}\n\nexport { CarddavAdapter } from \"./adapter.ts\";\nexport { CarddavClientManager } from \"./client-manager.ts\";\nexport type { ResolvedCarddavConnection } from \"./client-manager.ts\";\nexport {\n  CARDDAV_CLIENT_MANAGER,\n  DEFAULT_CARDDAV_SERVER_URL,\n  CarddavHeaders,\n} from \"./shared.ts\";\nexport type {\n  CarddavDriverClient,\n  DAVAddressBookLike,\n  DAVVCardLike,\n} from \"./shared.ts\";\nexport { VCard, VCardProperty, parseVCard } from \"./vcard.ts\";\nexport type {\n  VCardBody,\n  VCardPropertyData,\n  VCardPropertyOptions,\n} from \"./vcard.ts\";\nexport type { VCardParam } from \"./vcard-raw.ts\";\nexport { VCARD, VPARAM } from \"./constants.ts\";\nexport type { KnownProperty, KnownParam } from \"./constants.ts\";\nexport type {\n  CarddavOptions,\n  CarddavServerOptions,\n  CarddavClientOptions,\n  CarddavContextConfig,\n  CarddavAccountConfig,\n  CarddavAction,\n  CarddavTargetExtractor,\n} from \"./types.ts\";\n","import type { Comparator, CosineOptions } from \"./types.ts\";\n\nfunction cosineSimilarity(a: number[], b: number[]): number {\n  if (a.length !== b.length) return 0;\n  let dot = 0;\n  let magA = 0;\n  let magB = 0;\n  for (let i = 0; i < a.length; i++) {\n    dot += a[i] * b[i];\n    magA += a[i] * a[i];\n    magB += b[i] * b[i];\n  }\n  const denom = Math.sqrt(magA) * Math.sqrt(magB);\n  return denom === 0 ? 0 : dot / denom;\n}\n\n/**\n * Creates a comparator that groups items by cosine similarity of a numeric vector field.\n * Use with `group({ comparator: cosine(options) })`.\n *\n * @param options - `field` (path to number[] on each item), optional `threshold` (default 0.82)\n * @returns A Comparator that returns true when two items' vectors have similarity > threshold\n *\n * @example\n * ```typescript\n * .transform(group({\n *   comparator: cosine({ field: 'embedding', threshold: 0.85 }),\n *   from: (body) => body.items,\n *   map: (cluster) => ({ count: cluster.length, centroid: cluster[0] })\n * }))\n * ```\n */\nexport function cosine<T = unknown>(options: CosineOptions): Comparator<T> {\n  const { field, threshold = 0.82 } = options;\n  return {\n    compare(a: T, b: T): boolean {\n      const va = (a as Record<string, unknown>)[field];\n      const vb = (b as Record<string, unknown>)[field];\n      if (!Array.isArray(va) || !Array.isArray(vb)) return false;\n      return cosineSimilarity(va as number[], vb as number[]) > threshold;\n    },\n  };\n}\n\n// Re-export types\nexport type { Comparator, CosineOptions } from \"./types.ts\";\n","export type {\n  ExpiredScanCursor,\n  NewDeferral,\n  PendingDeferralSummary,\n  PrincipalRef,\n  SerializedExchange,\n  SerializedOutcome,\n  Deferral,\n  DeferralCasResult,\n  DeferralListCursor,\n  DeferralListQuery,\n  DeferralSummary,\n  DeferralSchema,\n  DeferralResumption,\n  DeferralState,\n  DeferralOutcome,\n  DeferralWaitingFor,\n  DeferralStore,\n} from \"./types.ts\";\nexport { claimed, resumable, summariseDeferral } from \"./types.ts\";\n\nexport { MemoryDeferralStore } from \"./memory-store.ts\";\nexport {\n  DEFAULT_DEFERRAL_DB_PATH,\n  SqliteDeferralStore,\n} from \"./sqlite-store.ts\";\nexport type {\n  SqliteDriverName,\n  ResolvedSqliteDriver,\n} from \"../shared/sqlite/driver.ts\";\n\nexport {\n  ResumeTokenSigner,\n  DEFERRAL_SECRET_ENV,\n  resolveSigningSecret,\n  deferralIdFor,\n} from \"./tokens.ts\";\nexport type {\n  ResumeTokenPayload,\n  SigningSecretOptions,\n  SigningSecretSource,\n} from \"./tokens.ts\";\n\nexport {\n  actionFingerprint,\n  continuationTailHash,\n  describeSchema,\n  stepStateFingerprint,\n} from \"./hash.ts\";\n\nexport type {\n  ResumeAuthorizer,\n  ResumeAuthorizerInput,\n  DeferralRecordView,\n} from \"./authorize.ts\";\n\nexport {\n  DATE_TAG,\n  deserializeExchange,\n  serializeExchange,\n} from \"./serialize.ts\";\n\nexport {\n  DEFERRAL_RUNTIME,\n  DEFERRAL_STORE_ENV,\n  createDeferralRuntime,\n  deferralPlugin,\n} from \"./config.ts\";\nexport type {\n  DeferralConfig,\n  DeferralRuntime,\n  DeferralStoreConfig,\n  DeferralTestSeams,\n} from \"./config.ts\";\n\nexport {\n  DEFERRED_JSON_SCHEMA,\n  isDeferred,\n  deferredSchema,\n} from \"./deferred.ts\";\nexport type { Deferred } from \"./deferred.ts\";\n\nexport { markDeferCapable, routeCanDefer } from \"./sites.ts\";\nexport type { DeferSite } from \"./sites.ts\";\n\nexport { DeferSignal, isDeferSignal } from \"./signal.ts\";\nexport type { DeferSignalRequest } from \"./signal.ts\";\n\nexport { DeferralHeaders } from \"./exchange-state.ts\";\nexport type { DeferralAffordance } from \"./exchange-state.ts\";\n\nexport type { ResumeAcknowledgment, ResumeRequest } from \"./revive.ts\";\n\n// The in-process halves of deferral and resume, for a tier that stores a\n// continuation beside a completing run and revives it itself (agent\n// sessions). Internal: the public surfaces are `.defer()` / `.resume()`.\nexport { deferAside } from \"./defer.ts\";\nexport { reviveDeferral } from \"./revive.ts\";\n"]}