@crvouga/mockingbird-service-bedrock 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../core/src/clock.ts", "../../core/src/collection.ts", "../../core/src/control.ts", "../../core/src/credentials.ts", "../../core/src/rng.ts", "../../core/src/faults.ts", "../../../openapi/core/src/refs.ts", "../../../openapi/core/src/types.ts", "../../../openapi/core/src/document.ts", "../../../openapi/core/src/schema.ts", "../../../http/codec/src/form.ts", "../../../http/codec/src/content.ts", "../../core/src/http.ts", "../../core/src/ids.ts", "../../core/src/journal.ts", "../../core/src/metrics.ts", "../../../core/src/timeline.ts", "../../../sqlite/src/default.ts", "../../../sqlite/src/migrate.ts", "../../../sqlite/src/schema.ts", "../../../openapi/metadata/src/types.ts", "../../../openapi/metadata/src/read.ts", "../../core/src/service.ts", "../../core/src/snapshot.ts", "../../core/src/version.ts", "../../core/src/signing.ts", "../../core/src/webhooks.ts", "../../core/src/runtime.ts", "../../core/src/validation.ts", "../src/analyze.ts", "../src/generated/openapi.ts", "../src/schema-sample.ts", "../src/scripts.ts", "../src/plan.ts", "../src/eventstream.ts", "../src/render.ts", "../src/audio.ts", "../src/sonic.ts", "../src/state.ts", "../src/runtime.ts", "../src/index.ts"],
4
+ "sourcesContent": ["/**\n * The single source of time for a service.\n *\n * Every timestamp a mock writes reads from here, so a suite moves time instead of\n * sleeping: appointment windows, result delays and expiries become reachable in\n * milliseconds. A frozen clock also makes timestamps reproducible from a seed.\n */\nexport type ClockState = {\n /** Current epoch milliseconds. */\n now: number\n /** True while time does not advance on its own. */\n frozen: boolean\n /** Milliseconds this clock adds to its underlying source. */\n offsetMs: number\n}\n\nexport type Clock = {\n now(): number\n /** Pin the clock to an exact instant, keeping it frozen if it already was. */\n set(epochMs: number): void\n /** Move the clock forward, or back with a negative delta. */\n advance(deltaMs: number): void\n /** Stop time at the current instant. */\n freeze(): void\n /** Resume from the current instant. */\n unfreeze(): void\n /** Drop back to the underlying source, live. */\n reset(): void\n state(): ClockState\n}\n\n/** A {@link Clock} over `source` (default `Date.now`), live and unfrozen. */\nexport const createClock = (source: () => number = Date.now): Clock => {\n let offsetMs = 0\n let frozenAt: number | undefined\n const now = () => frozenAt ?? source() + offsetMs\n return {\n now,\n set: (epochMs) => {\n if (frozenAt !== undefined) frozenAt = epochMs\n else offsetMs = epochMs - source()\n },\n advance: (deltaMs) => {\n if (frozenAt !== undefined) frozenAt += deltaMs\n else offsetMs += deltaMs\n },\n freeze: () => {\n frozenAt = now()\n },\n unfreeze: () => {\n if (frozenAt === undefined) return\n offsetMs = frozenAt - source()\n frozenAt = undefined\n },\n reset: () => {\n offsetMs = 0\n frozenAt = undefined\n },\n state: () => ({ now: now(), frozen: frozenAt !== undefined, offsetMs }),\n }\n}\n", "import type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\n/** Every stored record carries a monotonically increasing sequence for stable ordering. */\nexport type Stored<T> = { seq: number; value: T }\n\nexport type ListRecordsOptions<T> = {\n /** Keep only records passing the predicate. */\n where?: (value: T, seq: number) => boolean\n /** Sort order; default newest first. */\n order?: \"newest\" | \"oldest\"\n}\n\ntype RecordRow = { id: string; seq: number; value: string }\n\n/**\n * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion\n * sequence, never by id lexicographic order, so list semantics stay stable.\n */\nexport class Collection<T> {\n constructor(\n private readonly sqlite: SqliteClient,\n private readonly namespace: string,\n private readonly name: string,\n ) {}\n\n private bumpCollectionSeq(): number {\n const row = this.sqlite\n .prepare(\n \"SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'\",\n )\n .get<{ value: number }>(this.namespace, this.name)\n const next = (row?.value ?? 0) + 1\n this.sqlite\n .prepare(\n `INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)\n ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`,\n )\n .run(this.namespace, this.name, next)\n return next\n }\n\n nextSequence(): number {\n return this.sqlite.transaction(() => this.bumpCollectionSeq())\n }\n\n get(id: string): T | undefined {\n const row = this.sqlite\n .prepare(\n \"SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .get<{ value: string }>(this.namespace, this.name, id)\n if (!row) return undefined\n return (JSON.parse(row.value) as Stored<T>).value\n }\n\n has(id: string): boolean {\n const row = this.sqlite\n .prepare(\n \"SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .get<{ ok: number }>(this.namespace, this.name, id)\n return row !== undefined\n }\n\n /** Insert a new record, assigning it the next sequence number. */\n insert(id: string, value: T): Stored<T> {\n return this.sqlite.transaction(() => {\n const seq = this.bumpCollectionSeq()\n const stored = { seq, value }\n this.sqlite\n .prepare(\n `INSERT INTO mockingbird_records (namespace, collection, id, seq, value)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`,\n )\n .run(this.namespace, this.name, id, seq, JSON.stringify(stored))\n return stored\n })\n }\n\n /** Replace an existing record's value, keeping its position. */\n update(id: string, value: T): Stored<T> | undefined {\n return this.sqlite.transaction(() => {\n const row = this.sqlite\n .prepare(\n \"SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .get<{ seq: number; value: string }>(this.namespace, this.name, id)\n if (!row) return undefined\n const stored = { seq: row.seq, value }\n this.sqlite\n .prepare(\n \"UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .run(JSON.stringify(stored), this.namespace, this.name, id)\n return stored\n })\n }\n\n delete(id: string): boolean {\n const result = this.sqlite\n .prepare(\"DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\")\n .run(this.namespace, this.name, id)\n return result.changes > 0\n }\n\n /** How many records the collection holds, without reading them. */\n count(): number {\n const row = this.sqlite\n .prepare(\n \"SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?\",\n )\n .get<{ n: number }>(this.namespace, this.name)\n return Number(row?.n ?? 0)\n }\n\n list(options: ListRecordsOptions<T> = {}): Array<Stored<T> & { id: string }> {\n const rows = this.sqlite\n .prepare(\n \"SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?\",\n )\n .all<RecordRow>(this.namespace, this.name)\n const out: Array<Stored<T> & { id: string }> = []\n for (const row of rows) {\n const stored = JSON.parse(row.value) as Stored<T>\n if (options.where && !options.where(stored.value, stored.seq)) continue\n out.push({ id: row.id, seq: stored.seq, value: stored.value })\n }\n out.sort((a, b) => (options.order === \"oldest\" ? a.seq - b.seq : b.seq - a.seq))\n return out\n }\n}\n", "import type { Clock } from \"./clock.js\"\nimport type { FaultRegistry, FaultRule } from \"./faults.js\"\nimport type { Journal } from \"./journal.js\"\nimport type { Metrics } from \"./metrics.js\"\n\n/** Unauthenticated readiness probe, served ahead of every vendor auth gate. */\nexport const HEALTH_PATH = \"/health\"\n/** Prefix of every control-plane route; never part of a vendor contract. */\nexport const ADMIN_PREFIX = \"/__admin\"\n/** Carries the admin key, which is separate from any vendor credential. */\nexport const ADMIN_KEY_HEADER = \"x-mockingbird-admin-key\"\n/** Selects the isolated namespace a request reads and writes. */\nexport const NAMESPACE_HEADER = \"x-mockingbird-namespace\"\n\nexport type AdminRequest = {\n request: Request\n url: URL\n /** `:param` segments of the matched route. */\n params: Record<string, string>\n /** Namespace the request targets: `?namespace=`, then the header, then the default. */\n namespace: string\n /** Parsed JSON body, or `undefined` when there is none. */\n body: unknown\n}\n\nexport type AdminRoute = (request: AdminRequest) => Response | Promise<Response>\n\n/**\n * Service-specific admin routes, keyed `METHOD /path` relative to `/__admin`, with\n * `:param` segments \u2014 e.g. `\"POST /orders/:id/transition\"`.\n */\nexport type AdminRoutes = Record<string, AdminRoute>\n\nexport type ControlContext = {\n name: string\n startedAt: number\n wallNow: () => number\n clock: Clock\n faults: FaultRegistry\n metrics: Metrics\n journal: Journal\n defaultNamespace: string\n namespaces(): string[]\n reset(namespace: string | \"*\"): Promise<void>\n timeTravel: {\n checkpoint(\n namespace: string,\n branch: string,\n ): { id: string; branch: string; parent: string | null; at: number; records?: number }\n branch(\n name: string,\n options: { namespace: string; at?: string },\n ): { id: string; branch: string; parent: string | null; at: number }\n checkout(checkpoint: string, options: { namespace: string; branch: string }): void\n retain(namespace: string, checkpoint: string): void\n release(namespace: string, checkpoint: string): boolean\n inspect(namespace: string): {\n branches: Readonly<Record<string, string>>\n checkpoints: readonly { id: string; branch: string; parent: string | null; at: number }[]\n }\n }\n /** Extra fields for `GET /health`, such as the loaded corpus version. */\n describe(): Record<string, unknown>\n routes: AdminRoutes\n adminKey: string | undefined\n /** Expand a named fault preset; enables `POST /faults {\"preset\": \"<name>\"}`. */\n applyPreset?(name: string, namespace: string, overrides: Partial<FaultRule>): FaultRule[]\n}\n\nexport type ControlPlane = {\n /** The control-plane response for `request`, or `undefined` for a vendor request. */\n handle(request: Request): Promise<Response | undefined>\n /**\n * Namespace a vendor request targets, from {@link NAMESPACE_HEADER}. Only admin routes\n * also accept `?namespace=`, so a vendor query parameter of that name can never\n * silently reroute a request.\n */\n namespaceOf(request: Request): string\n}\n\nconst json = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\" },\n })\n\n/** Admin errors use one documented shape, distinct from any vendor's error body. */\nconst adminError = (status: number, message: string): Response =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst UNITS: Record<string, number> = {\n ms: 1,\n s: 1000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n}\n\n/** Milliseconds from a number, or a duration like `\"90s\"`, `\"15m\"`, `\"2h\"`, `\"3d\"`. */\nexport const parseDuration = (value: unknown): number | undefined => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value\n if (typeof value !== \"string\") return undefined\n const match = /^(-?\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/.exec(value.trim())\n if (!match) return undefined\n return Number(match[1]) * (UNITS[match[2] as string] as number)\n}\n\n/** Epoch milliseconds from a number or an ISO-8601 string. */\nconst parseInstant = (value: unknown): number | undefined => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value\n if (typeof value !== \"string\") return undefined\n const parsed = Date.parse(value)\n return Number.isNaN(parsed) ? undefined : parsed\n}\n\nconst matchRoute = (pattern: string, path: string): Record<string, string> | undefined => {\n const want = pattern.split(\"/\").filter(Boolean)\n const have = path.split(\"/\").filter(Boolean)\n if (want.length !== have.length) return undefined\n const params: Record<string, string> = {}\n for (let i = 0; i < want.length; i++) {\n const segment = want[i] as string\n const actual = have[i] as string\n if (segment.startsWith(\":\")) params[segment.slice(1)] = decodeURIComponent(actual)\n else if (segment !== actual) return undefined\n }\n return params\n}\n\nconst readJson = async (request: Request): Promise<unknown> => {\n const text = await request.text()\n if (text.trim() === \"\") return undefined\n return JSON.parse(text) as unknown\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nexport const createControlPlane = (context: ControlContext): ControlPlane => {\n // Legacy snapshot ids are opaque aliases to pinned Timeline checkpoints. Timeline remains the\n // only history owner; this map carries no state value and can be removed with the alias.\n const snapshots = new Map<string, { namespace: string; checkpoint: string }>()\n let snapshotCounter = 0\n\n const headerNamespace = (request: Request): string =>\n request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace\n const adminNamespace = (request: Request, url: URL): string =>\n url.searchParams.get(\"namespace\") ?? headerNamespace(request)\n\n const builtin: AdminRoutes = {\n \"GET /\": () =>\n json(200, {\n service: context.name,\n routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort(),\n }),\n\n \"POST /reset\": async ({ url, namespace }) => {\n const target = url.searchParams.get(\"all\") === \"1\" ? \"*\" : namespace\n await context.reset(target)\n return json(200, { status: \"ok\", reset: target === \"*\" ? context.namespaces() : [target] })\n },\n\n \"GET /namespaces\": () =>\n json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),\n\n \"GET /clock\": () => json(200, context.clock.state()),\n \"POST /clock\": ({ body }) => {\n if (!isRecord(body)) return adminError(400, \"expected a JSON object\")\n if (body.reset === true) context.clock.reset()\n if (body.set !== undefined) {\n const instant = parseInstant(body.set)\n if (instant === undefined) return adminError(400, \"set: expected epoch ms or ISO-8601\")\n context.clock.set(instant)\n }\n if (body.advance !== undefined) {\n const delta = parseDuration(body.advance)\n if (delta === undefined) return adminError(400, 'advance: expected ms or \"15m\"-style')\n context.clock.advance(delta)\n }\n if (body.freeze === true) context.clock.freeze()\n if (body.freeze === false) context.clock.unfreeze()\n return json(200, context.clock.state())\n },\n\n \"GET /faults\": () => json(200, { faults: context.faults.list() }),\n \"POST /faults\": ({ body, namespace }) => {\n if (isRecord(body) && typeof body.preset === \"string\") {\n if (!context.applyPreset) return adminError(400, `${context.name} has no fault presets`)\n const { preset, ...overrides } = body\n try {\n return json(201, {\n preset,\n rules: context.applyPreset(preset, namespace, overrides as Partial<FaultRule>),\n })\n } catch (error) {\n return adminError(404, error instanceof Error ? error.message : String(error))\n }\n }\n if (\n !isRecord(body) ||\n (typeof body.status !== \"number\" &&\n typeof body.delayMs !== \"number\" &&\n typeof body.latencyMs !== \"number\" &&\n body.drop !== true &&\n typeof body.effect !== \"string\")\n ) {\n return adminError(\n 400,\n \"a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset\",\n )\n }\n const rule = {\n // Scoped to the caller's namespace unless it asks for every one, so one worker's\n // injected failure never lands on another's request.\n namespace,\n ...body,\n id: typeof body.id === \"string\" ? body.id : `fault_${context.faults.list().length + 1}`,\n } as FaultRule\n return json(201, context.faults.add(rule))\n },\n \"DELETE /faults\": ({ url }) => {\n const id = url.searchParams.get(\"id\")\n if (id === null) {\n context.faults.clear()\n return json(200, { status: \"ok\" })\n }\n return context.faults.remove(id)\n ? json(200, { status: \"ok\" })\n : adminError(404, `no fault ${id}`)\n },\n\n \"POST /snapshots\": ({ namespace }) => {\n const point = context.timeTravel.checkpoint(namespace, \"main\")\n context.timeTravel.retain(namespace, point.id)\n snapshotCounter++\n const id = `snap_${snapshotCounter}`\n snapshots.set(id, { namespace, checkpoint: point.id })\n return json(201, { id, namespace, records: point.records ?? 0 })\n },\n \"POST /snapshots/:id/restore\": ({ params, namespace }) => {\n const alias = snapshots.get(params.id as string)\n if (!alias) return adminError(404, `no snapshot ${params.id}`)\n if (alias.namespace !== namespace) {\n return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`)\n }\n context.timeTravel.checkout(alias.checkpoint, { namespace, branch: \"main\" })\n return json(200, { status: \"ok\", id: params.id, namespace })\n },\n \"DELETE /snapshots/:id\": ({ params }) => {\n const id = params.id as string\n const alias = snapshots.get(id)\n if (!alias) return adminError(404, `no snapshot ${id}`)\n snapshots.delete(id)\n context.timeTravel.release(alias.namespace, alias.checkpoint)\n return json(200, { status: \"ok\" })\n },\n\n \"GET /timeline\": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),\n \"POST /checkpoints\": ({ body, namespace }) => {\n const branch = isRecord(body) && typeof body.branch === \"string\" ? body.branch : \"main\"\n try {\n return json(201, context.timeTravel.checkpoint(namespace, branch))\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n \"POST /branches/:name\": ({ params, body, namespace }) => {\n const at = isRecord(body) && typeof body.at === \"string\" ? body.at : undefined\n try {\n return json(\n 201,\n context.timeTravel.branch(params.name as string, {\n namespace,\n ...(at !== undefined ? { at } : {}),\n }),\n )\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n \"POST /branches/:name/checkout\": ({ params, body, namespace }) => {\n if (!isRecord(body) || typeof body.checkpoint !== \"string\") {\n return adminError(400, 'expected {\"checkpoint\":\"cp_...\"}')\n }\n try {\n context.timeTravel.checkout(body.checkpoint, {\n namespace,\n branch: params.name as string,\n })\n return json(200, { status: \"ok\", branch: params.name, checkpoint: body.checkpoint })\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n\n \"GET /requests\": ({ url, namespace }) => {\n const status = url.searchParams.get(\"status\")\n const since = url.searchParams.get(\"since\")\n const limit = url.searchParams.get(\"limit\")\n const sinceMs =\n since === null ? undefined : parseInstant(/^\\d+$/.test(since) ? Number(since) : since)\n if (since !== null && sinceMs === undefined) {\n return adminError(400, \"since: expected epoch ms or ISO-8601\")\n }\n if (status !== null && !/^\\d{3}$/.test(status))\n return adminError(400, \"status: expected an HTTP status\")\n if (limit !== null && !/^\\d+$/.test(limit)) return adminError(400, \"limit: expected a count\")\n const operationId = url.searchParams.get(\"operationId\")\n const everyNamespace = url.searchParams.get(\"all\") === \"1\"\n return json(200, {\n size: context.journal.size,\n requests: context.journal.list({\n ...(everyNamespace ? {} : { namespace }),\n ...(operationId !== null ? { operationId } : {}),\n ...(status !== null ? { status: Number(status) } : {}),\n ...(sinceMs !== undefined ? { since: sinceMs } : {}),\n ...(limit !== null ? { limit: Number(limit) } : {}),\n }),\n })\n },\n \"DELETE /requests\": ({ url, namespace }) => {\n context.journal.clear(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace)\n return json(200, { status: \"ok\" })\n },\n\n \"GET /metrics\": () => json(200, context.metrics.report()),\n \"DELETE /metrics\": () => {\n context.metrics.reset()\n return json(200, { status: \"ok\" })\n },\n }\n\n const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(\n ([key, handler]) => {\n const space = key.indexOf(\" \")\n return { method: key.slice(0, space), pattern: key.slice(space + 1), handler }\n },\n )\n\n return {\n namespaceOf: headerNamespace,\n async handle(request) {\n const url = new URL(request.url)\n if (url.pathname === HEALTH_PATH && request.method === \"GET\") {\n return json(200, {\n status: \"ok\",\n service: context.name,\n uptimeMs: context.wallNow() - context.startedAt,\n clock: context.clock.state(),\n namespaces: context.namespaces().length,\n ...context.describe(),\n })\n }\n if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {\n return undefined\n }\n if (\n context.adminKey !== undefined &&\n request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey\n ) {\n return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`)\n }\n const path = url.pathname.slice(ADMIN_PREFIX.length) || \"/\"\n for (const route of routes) {\n if (route.method !== request.method) continue\n const params = matchRoute(route.pattern, path)\n if (!params) continue\n let body: unknown\n try {\n body = await readJson(request)\n } catch {\n return adminError(400, \"request body is not valid JSON\")\n }\n return route.handler({\n request,\n url,\n params,\n namespace: adminNamespace(request, url),\n body,\n })\n }\n return adminError(\n 404,\n `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`,\n )\n },\n }\n}\n", "/**\n * Reading the vendor credential a request carries.\n *\n * Several vendor SDKs (Stripe, AWS, PostHog, Twilio) cannot add a namespace header, so a\n * runtime can also pick a request's namespace from its credential: a suite maps each\n * worker's API key, token or account SID to a namespace through `PUT /__admin/credentials`.\n * These helpers pull the credential out of the usual carriers.\n */\n\n/** The token after `Bearer `, or `undefined`. */\nexport const bearerToken = (request: Request): string | undefined => {\n const header = request.headers.get(\"authorization\")\n if (!header) return undefined\n const match = /^Bearer\\s+(.+)$/i.exec(header.trim())\n return match?.[1]?.trim() || undefined\n}\n\nexport type BasicCredentials = { username: string; password: string }\n\n/** `{ username, password }` from `Authorization: Basic \u2026`, or `undefined`. */\nexport const basicAuth = (request: Request): BasicCredentials | undefined => {\n const header = request.headers.get(\"authorization\")\n if (!header) return undefined\n const match = /^Basic\\s+(.+)$/i.exec(header.trim())\n if (!match?.[1]) return undefined\n let decoded: string\n try {\n decoded = atob(match[1].trim())\n } catch {\n return undefined\n }\n const colon = decoded.indexOf(\":\")\n if (colon < 0) return { username: decoded, password: \"\" }\n return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) }\n}\n\n/**\n * The access key id of an AWS SigV4-signed request (`Credential=AKID/date/region/service/\u2026`),\n * from the `Authorization` header or a presigned `X-Amz-Credential` query parameter.\n */\nexport const sigV4AccessKeyId = (request: Request): string | undefined => {\n const header = request.headers.get(\"authorization\")\n const fromHeader = header ? /Credential=([^/,\\s]+)\\//.exec(header)?.[1] : undefined\n if (fromHeader) return fromHeader\n const query = new URL(request.url).searchParams.get(\"X-Amz-Credential\")\n return query ? (query.split(\"/\")[0] ?? undefined) : undefined\n}\n\n/** The credential in any of the common carriers: Bearer, Basic username, SigV4, or `x-api-key`. */\nexport const anyCredential = (request: Request): string | undefined =>\n bearerToken(request) ??\n basicAuth(request)?.username ??\n sigV4AccessKeyId(request) ??\n request.headers.get(\"x-api-key\") ??\n undefined\n\n/** Credential \u2192 namespace mapping behind `PUT /__admin/credentials`. */\nexport type CredentialRegistry = {\n set(credential: string, namespace: string): void\n get(credential: string): string | undefined\n remove(credential: string): boolean\n clear(): void\n entries(): { credential: string; namespace: string }[]\n}\n\nexport const createCredentialRegistry = (): CredentialRegistry => {\n const map = new Map<string, string>()\n return {\n set: (credential, namespace) => {\n map.set(credential, namespace)\n },\n get: (credential) => map.get(credential),\n remove: (credential) => map.delete(credential),\n clear: () => map.clear(),\n entries: () =>\n [...map]\n .map(([credential, namespace]) => ({ credential, namespace }))\n .sort((a, b) => a.credential.localeCompare(b.credential)),\n }\n}\n\n/** A credential shown in admin output: enough to recognise it, never the whole secret. */\nexport const maskCredential = (credential: string): string =>\n credential.length <= 8\n ? `${credential.slice(0, 2)}\u2026`\n : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`\n", "/**\n * Seeded pseudo-random numbers, so anything a mock invents \u2014 ids, jitter, which\n * request a percentage fault hits \u2014 is reproducible from a seed.\n *\n * mulberry32: small, fast, and stable across runtimes, which matters more here\n * than statistical quality.\n */\nexport type Rng = {\n /** Next value in `[0, 1)`. */\n next(): number\n /** Next integer in `[min, max]`. */\n int(min: number, max: number): number\n /** Restart the stream from its seed. */\n reset(): void\n /** Serializable engine state used by deterministic checkpoints. */\n state(): number\n /** Restore a state previously returned by {@link state}. */\n setState(state: number): void\n seed: number\n}\n\n/** Hash an arbitrary string into a 32-bit seed, so callers can seed by name. */\nexport const seedFrom = (value: string): number => {\n let hash = 2166136261\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i)\n hash = Math.imul(hash, 16777619)\n }\n return hash >>> 0\n}\n\nexport const createRng = (seed: number | string = 0): Rng => {\n const numeric = typeof seed === \"string\" ? seedFrom(seed) : seed >>> 0\n let state = numeric\n const next = () => {\n state = (state + 0x6d2b79f5) >>> 0\n let t = state\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n return {\n next,\n int: (min, max) => min + Math.floor(next() * (max - min + 1)),\n reset: () => {\n state = numeric\n },\n state: () => state,\n setState: (next) => {\n if (!Number.isSafeInteger(next) || next < 0 || next > 0xffffffff) {\n throw new RangeError(\"rng state must be an unsigned 32-bit integer\")\n }\n state = next >>> 0\n },\n seed: numeric,\n }\n}\n", "import { createRng, type Rng } from \"./rng.js\"\n\n/**\n * A deliberate failure injected in front of an operation.\n *\n * This is how a suite reaches the vendor's failure modes without the vendor: the\n * quota error that only appears when a shared sandbox is full, the 429 that only\n * appears under load, the 5xx that proves a retry path works.\n */\nexport type FaultRule = {\n /** Stable id, so a suite can retire exactly the rule it added. */\n id: string\n /** Fault only this operation. Omit to match every operation. */\n operationId?: string\n /** Fault only this HTTP method, case-insensitive. Omit to match every method. */\n method?: string\n /** Fault only paths starting with this prefix. Omit to match every path. */\n pathPrefix?: string\n /**\n * Fault only this namespace. Omit (or `\"*\"`) to fault every namespace \u2014 which is what\n * an in-process caller usually wants, and what a parallel worker usually does not:\n * rules added through `POST /__admin/faults` default to the calling namespace.\n */\n namespace?: string\n /**\n * Status of the injected response. Omit for a rule that only delays (`delayMs` /\n * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:\n * the request then still reaches the service.\n */\n status?: number\n /** Response body, serialized as JSON. A string is sent as-is. */\n body?: unknown\n headers?: Record<string, string>\n /** Retire the rule after this many faults. Omit to keep it until removed. */\n count?: number\n /** Fault this fraction of matching requests, `0`\u2013`1`. Default `1`. */\n rate?: number\n /** Hold the response back this long, to exercise timeouts. */\n delayMs?: number\n /** Alias of `delayMs`. */\n latencyMs?: number\n /**\n * Drop the connection instead of answering: an in-process `fetch` rejects with a\n * `TypeError`, and a served mock destroys the socket. Models \"unknown outcome\" failures.\n */\n drop?: boolean\n /**\n * A named service behaviour to switch on for the matching request instead of (or\n * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services\n * read it with `faultEffects(request)`.\n */\n effect?: string\n /** Parameters for `effect`. */\n params?: Record<string, unknown>\n /** From the preset this rule was expanded from, if any. */\n preset?: string\n}\n\n/** A fault that fired for one request. */\nexport type FaultHit = {\n id: string\n /** The injected response; absent when the rule only delays, drops, or sets an effect. */\n response?: Response\n drop?: boolean\n effect?: { name: string; params: Record<string, unknown> }\n}\n\n/**\n * A named, documented fault a suite switches on by name\n * (`POST /__admin/faults {\"preset\": \"rate_limited\"}`): one or more rules, and optionally a\n * webhook delivery fault.\n */\nexport type FaultPreset = {\n description: string\n rules?: Omit<FaultRule, \"id\">[]\n webhook?: { mode: \"duplicate\" | \"reorder\" | \"drop\"; count?: number }\n}\n\n/** What a request looks like to the fault matcher. */\nexport type FaultCandidate = {\n operationId: string | undefined\n method: string\n path: string\n namespace: string\n}\n\nexport type FaultRegistry = {\n add(rule: FaultRule): FaultRule\n list(): (FaultRule & { remaining: number | null; hits: number })[]\n remove(id: string): boolean\n clear(): void\n /**\n * Every fault this request should get, in rule order, stopping at the first that answers\n * or drops (effect-only and delay-only rules let later rules match too). Consumes one of\n * each matching rule's remaining uses.\n */\n take(candidate: FaultCandidate): Promise<FaultHit[]>\n}\n\ntype Entry = { rule: FaultRule; remaining: number | null; hits: number }\n\nconst matches = (rule: FaultRule, candidate: FaultCandidate): boolean => {\n if (\n rule.namespace !== undefined &&\n rule.namespace !== \"*\" &&\n rule.namespace !== candidate.namespace\n ) {\n return false\n }\n if (rule.operationId !== undefined && rule.operationId !== candidate.operationId) return false\n if (rule.method !== undefined && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {\n return false\n }\n if (rule.pathPrefix !== undefined && !candidate.path.startsWith(rule.pathPrefix)) return false\n return true\n}\n\nconst faultResponse = (rule: FaultRule): Response => {\n const status = rule.status ?? 500\n const headers = { \"content-type\": \"application/json\", ...rule.headers }\n if (typeof rule.body === \"string\") return new Response(rule.body, { status, headers })\n if (rule.body === null) return new Response(null, { status, headers: rule.headers ?? {} })\n const body = rule.body === undefined ? { detail: \"Injected by Mockingbird\" } : rule.body\n return new Response(JSON.stringify(body), { status, headers })\n}\n\n/**\n * Rules are matched in the order they were added, so a narrow rule added first\n * wins over a later catch-all. `rate` draws from `rng`, which is seeded, so a\n * partial-failure run replays identically.\n */\nexport const createFaultRegistry = (\n rng: Rng = createRng(0),\n sleep: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n): FaultRegistry => {\n const entries: Entry[] = []\n return {\n add(rule) {\n const existing = entries.findIndex((e) => e.rule.id === rule.id)\n const entry: Entry = { rule, remaining: rule.count ?? null, hits: 0 }\n if (existing >= 0) entries[existing] = entry\n else entries.push(entry)\n return rule\n },\n list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),\n remove(id) {\n const index = entries.findIndex((e) => e.rule.id === id)\n if (index < 0) return false\n entries.splice(index, 1)\n return true\n },\n clear() {\n entries.length = 0\n },\n async take(candidate) {\n const hits: FaultHit[] = []\n for (const entry of entries) {\n if (entry.remaining === 0) continue\n if (!matches(entry.rule, candidate)) continue\n const rate = entry.rule.rate ?? 1\n // Draw even when the rule always fires, so a seeded stream stays aligned.\n if (rng.next() >= rate) continue\n entry.hits++\n if (entry.remaining !== null) entry.remaining--\n const delay = entry.rule.delayMs ?? entry.rule.latencyMs\n if (delay !== undefined && delay > 0) {\n await sleep(delay)\n }\n const hit: FaultHit = { id: entry.rule.id }\n if (entry.rule.effect !== undefined) {\n hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} }\n }\n if (entry.rule.drop === true) hit.drop = true\n else if (entry.rule.status !== undefined) hit.response = faultResponse(entry.rule)\n hits.push(hit)\n if (hit.drop || hit.response) break\n }\n return hits\n },\n }\n}\n", "import type { OpenAPIDocument, ReferenceObject } from \"./types.js\"\n\nexport class OpenAPIReferenceError extends Error {\n constructor(readonly ref: string) {\n super(`unresolvable $ref: ${ref}`)\n this.name = \"OpenAPIReferenceError\"\n }\n}\n\nconst unescapePointer = (segment: string) => segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n\n/** True when `value` is a `{ $ref }` object. */\nexport const isReference = (value: unknown): value is ReferenceObject =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { $ref?: unknown }).$ref === \"string\"\n\n/** Resolve a local JSON pointer reference (`#/components/schemas/customer`) inside `document`. */\nexport const resolveRef = (document: OpenAPIDocument, ref: string): unknown => {\n if (!ref.startsWith(\"#/\")) throw new OpenAPIReferenceError(ref)\n let cursor: unknown = document\n for (const raw of ref.slice(2).split(\"/\")) {\n const segment = unescapePointer(raw)\n if (typeof cursor !== \"object\" || cursor === null || !(segment in cursor)) {\n throw new OpenAPIReferenceError(ref)\n }\n cursor = (cursor as Record<string, unknown>)[segment]\n }\n if (cursor === undefined) throw new OpenAPIReferenceError(ref)\n return cursor\n}\n\n/**\n * Follow `$ref` chains until a concrete object is reached. Guards against cycles.\n * Sibling keys next to `$ref` are ignored, as in OpenAPI 3.0/3.1 for non-schema objects.\n */\nexport const deref = <T>(document: OpenAPIDocument, value: T | ReferenceObject): T => {\n let current: unknown = value\n const seen = new Set<string>()\n while (isReference(current)) {\n if (seen.has(current.$ref)) throw new OpenAPIReferenceError(`${current.$ref} (cycle)`)\n seen.add(current.$ref)\n current = resolveRef(document, current.$ref)\n }\n return current as T\n}\n\n/** The component name at the end of a `#/components/<kind>/<name>` reference, if any. */\nexport const componentNameOf = (ref: string): string | undefined => {\n const match = /^#\\/components\\/[^/]+\\/(.+)$/.exec(ref)\n return match?.[1] === undefined ? undefined : unescapePointer(match[1])\n}\n", "/**\n * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.\n * Unknown keys (including `x-*` extensions) are preserved on every object.\n */\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }\n\nexport type ReferenceObject = { $ref: string; description?: string; summary?: string }\n\nexport type SchemaType = \"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\" | \"null\"\n\nexport type SchemaObject = {\n $ref?: string\n type?: SchemaType | SchemaType[]\n title?: string\n description?: string\n format?: string\n enum?: JsonValue[]\n const?: JsonValue\n default?: JsonValue\n example?: JsonValue\n examples?: JsonValue[]\n nullable?: boolean\n deprecated?: boolean\n readOnly?: boolean\n writeOnly?: boolean\n minimum?: number\n maximum?: number\n exclusiveMinimum?: number\n exclusiveMaximum?: number\n multipleOf?: number\n minLength?: number\n maxLength?: number\n pattern?: string\n minItems?: number\n maxItems?: number\n uniqueItems?: boolean\n items?: SchemaObject\n prefixItems?: SchemaObject[]\n minProperties?: number\n maxProperties?: number\n required?: string[]\n properties?: Record<string, SchemaObject>\n additionalProperties?: boolean | SchemaObject\n propertyNames?: SchemaObject\n oneOf?: SchemaObject[]\n anyOf?: SchemaObject[]\n allOf?: SchemaObject[]\n not?: SchemaObject\n discriminator?: { propertyName: string; mapping?: Record<string, string> }\n [extension: `x-${string}`]: unknown\n}\n\nexport type ParameterLocation = \"path\" | \"query\" | \"header\" | \"cookie\"\n\nexport type ParameterObject = {\n name: string\n in: ParameterLocation\n description?: string\n required?: boolean\n deprecated?: boolean\n style?: string\n explode?: boolean\n schema?: SchemaObject\n content?: Record<string, MediaTypeObject>\n example?: JsonValue\n [extension: `x-${string}`]: unknown\n}\n\nexport type MediaTypeObject = {\n schema?: SchemaObject\n example?: JsonValue\n examples?: Record<string, unknown>\n encoding?: Record<string, unknown>\n [extension: `x-${string}`]: unknown\n}\n\nexport type RequestBodyObject = {\n description?: string\n required?: boolean\n content: Record<string, MediaTypeObject>\n [extension: `x-${string}`]: unknown\n}\n\nexport type HeaderObject = {\n description?: string\n required?: boolean\n schema?: SchemaObject\n [extension: `x-${string}`]: unknown\n}\n\nexport type ResponseObject = {\n description: string\n headers?: Record<string, HeaderObject | ReferenceObject>\n content?: Record<string, MediaTypeObject>\n [extension: `x-${string}`]: unknown\n}\n\nexport type ResponsesObject = Record<string, ResponseObject | ReferenceObject>\n\nexport type SecurityRequirementObject = Record<string, string[]>\n\nexport type OperationObject = {\n operationId?: string\n summary?: string\n description?: string\n tags?: string[]\n deprecated?: boolean\n parameters?: Array<ParameterObject | ReferenceObject>\n requestBody?: RequestBodyObject | ReferenceObject\n responses: ResponsesObject\n security?: SecurityRequirementObject[]\n [extension: `x-${string}`]: unknown\n}\n\nexport const HTTP_METHODS = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"options\",\n \"head\",\n \"patch\",\n \"trace\",\n] as const\nexport type HttpMethod = (typeof HTTP_METHODS)[number]\n\nexport type PathItemObject = {\n summary?: string\n description?: string\n parameters?: Array<ParameterObject | ReferenceObject>\n [extension: `x-${string}`]: unknown\n} & Partial<Record<HttpMethod, OperationObject>>\n\nexport type SecuritySchemeObject = {\n type: \"apiKey\" | \"http\" | \"oauth2\" | \"openIdConnect\" | \"mutualTLS\"\n description?: string\n name?: string\n in?: ParameterLocation\n scheme?: string\n bearerFormat?: string\n flows?: Record<string, unknown>\n openIdConnectUrl?: string\n [extension: `x-${string}`]: unknown\n}\n\nexport type ComponentsObject = {\n schemas?: Record<string, SchemaObject>\n responses?: Record<string, ResponseObject>\n parameters?: Record<string, ParameterObject>\n requestBodies?: Record<string, RequestBodyObject>\n headers?: Record<string, HeaderObject>\n securitySchemes?: Record<string, SecuritySchemeObject>\n [extension: `x-${string}`]: unknown\n}\n\nexport type ServerObject = {\n url: string\n description?: string\n variables?: Record<string, unknown>\n [extension: `x-${string}`]: unknown\n}\n\nexport type InfoObject = {\n title: string\n version: string\n description?: string\n [extension: `x-${string}`]: unknown\n}\n\nexport type OpenAPIDocument = {\n openapi: string\n info: InfoObject\n servers?: ServerObject[]\n paths: Record<string, PathItemObject>\n components?: ComponentsObject\n security?: SecurityRequirementObject[]\n tags?: Array<{ name: string; description?: string }>\n [extension: `x-${string}`]: unknown\n}\n\n/** One concrete HTTP operation discovered in a document. */\nexport type Operation = {\n operationId: string\n method: HttpMethod\n /** OpenAPI path template, e.g. `/v1/customers/{customer}`. */\n path: string\n operation: OperationObject\n /** Path-level parameters merged with operation-level ones (operation wins), `$ref`s resolved. */\n parameters: ParameterObject[]\n requestBody: RequestBodyObject | undefined\n responses: Record<string, ResponseObject>\n}\n", "import { deref, isReference, resolveRef } from \"./refs.js\"\nimport {\n HTTP_METHODS,\n type HttpMethod,\n type OpenAPIDocument,\n type Operation,\n type ParameterObject,\n type PathItemObject,\n type RequestBodyObject,\n type ResponseObject,\n} from \"./types.js\"\n\nexport class OpenAPIDocumentError extends Error {\n constructor(readonly issues: string[]) {\n super(`invalid OpenAPI document:\\n${issues.map((issue) => ` - ${issue}`).join(\"\\n\")}`)\n this.name = \"OpenAPIDocumentError\"\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\n/**\n * Accept an already-parsed JSON/YAML value and return it typed as an {@link OpenAPIDocument}.\n * Performs the structural checks Mockingbird relies on (see {@link validateOpenAPIDocument}) and\n * throws {@link OpenAPIDocumentError} listing every problem.\n */\nexport const parseOpenAPIDocument = (value: unknown): OpenAPIDocument => {\n const issues: string[] = []\n if (!isRecord(value)) throw new OpenAPIDocumentError([\"document must be an object\"])\n if (typeof value.openapi !== \"string\" || !/^3\\.[01]\\./.test(value.openapi)) {\n issues.push(\n `openapi must be a 3.0.x or 3.1.x version string, got ${JSON.stringify(value.openapi)}`,\n )\n }\n if (\n !isRecord(value.info) ||\n typeof value.info.title !== \"string\" ||\n typeof value.info.version !== \"string\"\n ) {\n issues.push(\"info.title and info.version are required strings\")\n }\n if (!isRecord(value.paths)) issues.push(\"paths must be an object\")\n if (issues.length > 0) throw new OpenAPIDocumentError(issues)\n const document = value as unknown as OpenAPIDocument\n const problems = validateOpenAPIDocument(document)\n if (problems.length > 0) throw new OpenAPIDocumentError(problems)\n return document\n}\n\nconst walkRefs = (\n document: OpenAPIDocument,\n node: unknown,\n at: string,\n issues: string[],\n seen: Set<unknown>,\n) => {\n if (typeof node !== \"object\" || node === null || seen.has(node)) return\n seen.add(node)\n if (isReference(node)) {\n try {\n resolveRef(document, node.$ref)\n } catch {\n issues.push(`${at}: unresolvable $ref ${node.$ref}`)\n }\n }\n for (const [key, child] of Object.entries(node))\n walkRefs(document, child, `${at}/${key}`, issues, seen)\n}\n\nconst templateParams = (path: string) =>\n [...path.matchAll(/\\{([^}]+)\\}/g)].map((m) => m[1] as string)\n\n/**\n * Mockingbird's document rules:\n * - every operation has a unique `operationId`\n * - every `$ref` resolves\n * - every `{param}` in a path template has a matching required path parameter\n * - every path parameter appears in the template\n */\nexport const validateOpenAPIDocument = (document: OpenAPIDocument): string[] => {\n const issues: string[] = []\n walkRefs(document, document, \"#\", issues, new Set())\n if (issues.length > 0) return issues\n const seenIds = new Map<string, string>()\n for (const [path, item] of Object.entries(document.paths)) {\n if (!isRecord(item)) {\n issues.push(`paths.${path}: must be an object`)\n continue\n }\n const inTemplate = new Set(templateParams(path))\n for (const method of HTTP_METHODS) {\n const operation = item[method]\n if (operation === undefined) continue\n const label = `${method.toUpperCase()} ${path}`\n if (typeof operation.operationId !== \"string\" || operation.operationId.length === 0) {\n issues.push(`${label}: operationId is required`)\n continue\n }\n const previous = seenIds.get(operation.operationId)\n if (previous !== undefined)\n issues.push(`${label}: duplicate operationId ${operation.operationId} (also ${previous})`)\n seenIds.set(operation.operationId, label)\n if (!isRecord(operation.responses) || Object.keys(operation.responses).length === 0) {\n issues.push(`${label}: responses must declare at least one status`)\n }\n const parameters = mergeParameters(document, item, operation.parameters)\n const declared = new Set(parameters.filter((p) => p.in === \"path\").map((p) => p.name))\n for (const name of inTemplate) {\n if (!declared.has(name)) issues.push(`${label}: path parameter {${name}} is not declared`)\n }\n for (const parameter of parameters) {\n if (parameter.in === \"path\") {\n if (!inTemplate.has(parameter.name))\n issues.push(`${label}: path parameter ${parameter.name} is not in the template`)\n if (parameter.required !== true)\n issues.push(`${label}: path parameter ${parameter.name} must be required`)\n }\n }\n }\n }\n return issues\n}\n\nconst mergeParameters = (\n document: OpenAPIDocument,\n item: PathItemObject,\n own: PathItemObject[\"parameters\"],\n): ParameterObject[] => {\n const merged = new Map<string, ParameterObject>()\n for (const raw of item.parameters ?? []) {\n const parameter = deref<ParameterObject>(document, raw)\n merged.set(`${parameter.in}:${parameter.name}`, parameter)\n }\n for (const raw of own ?? []) {\n const parameter = deref<ParameterObject>(document, raw)\n merged.set(`${parameter.in}:${parameter.name}`, parameter)\n }\n return [...merged.values()]\n}\n\n/** Enumerate every operation in the document in path, then method order. */\nexport const listOperations = (document: OpenAPIDocument): Operation[] => {\n const operations: Operation[] = []\n for (const [path, item] of Object.entries(document.paths)) {\n for (const method of HTTP_METHODS) {\n const operation = item[method]\n if (operation?.operationId === undefined) continue\n const responses: Record<string, ResponseObject> = {}\n for (const [status, response] of Object.entries(operation.responses)) {\n responses[status] = deref<ResponseObject>(document, response)\n }\n operations.push({\n operationId: operation.operationId,\n method,\n path,\n operation,\n parameters: mergeParameters(document, item, operation.parameters),\n requestBody:\n operation.requestBody === undefined\n ? undefined\n : deref<RequestBodyObject>(document, operation.requestBody),\n responses,\n })\n }\n }\n return operations\n}\n\n/** Find one operation by id. */\nexport const findOperation = (\n document: OpenAPIDocument,\n operationId: string,\n): Operation | undefined =>\n listOperations(document).find((operation) => operation.operationId === operationId)\n\n/** Parameter names inside a path template, in order. */\nexport const pathTemplateParameters = templateParams\n\n/** Substitute `{name}` placeholders. Values are percent-encoded as path segments. */\nexport const expandPathTemplate = (template: string, values: Record<string, string>): string =>\n template.replace(/\\{([^}]+)\\}/g, (_, name: string) => {\n const value = values[name]\n if (value === undefined) throw new RangeError(`missing path parameter ${name}`)\n return encodeURIComponent(value)\n })\n\n/** The response object matching an HTTP status: exact match, then `2XX`-style range, then `default`. */\nexport const responseForStatus = (\n responses: Record<string, ResponseObject>,\n status: number,\n): ResponseObject | undefined =>\n responses[String(status)] ?? responses[`${Math.floor(status / 100)}XX`] ?? responses.default\n\nexport type { HttpMethod }\n", "import { resolveRef } from \"./refs.js\"\nimport type { JsonValue, OpenAPIDocument, SchemaObject, SchemaType } from \"./types.js\"\n\n/**\n * Resolve a schema's `$ref` (merging sibling keywords, as JSON Schema 2020-12 allows) and\n * normalise OpenAPI 3.0 `nullable` into a 3.1 type array.\n */\nexport const resolveSchema = (document: OpenAPIDocument, schema: SchemaObject): SchemaObject => {\n let current = schema\n const seen = new Set<string>()\n while (typeof current.$ref === \"string\") {\n const ref = current.$ref\n if (seen.has(ref)) break\n seen.add(ref)\n const { $ref: _ignored, ...siblings } = current\n const target = resolveRef(document, ref) as SchemaObject\n current = { ...target, ...siblings }\n }\n if (current.nullable === true) {\n const { nullable: _nullable, ...rest } = current\n const types = schemaTypes(rest)\n if (types.length > 0 && !types.includes(\"null\")) current = { ...rest, type: [...types, \"null\"] }\n else current = rest\n }\n return current\n}\n\n/** Declared JSON types of a schema (empty when unconstrained). */\nexport const schemaTypes = (schema: SchemaObject): SchemaType[] => {\n if (Array.isArray(schema.type)) return schema.type\n if (schema.type !== undefined) return [schema.type]\n const inferred: SchemaType[] = []\n if (schema.properties || schema.required || schema.additionalProperties !== undefined)\n inferred.push(\"object\")\n if (\n schema.items ||\n schema.prefixItems ||\n schema.minItems !== undefined ||\n schema.maxItems !== undefined\n )\n inferred.push(\"array\")\n if (\n schema.minLength !== undefined ||\n schema.maxLength !== undefined ||\n schema.pattern !== undefined\n )\n inferred.push(\"string\")\n if (\n schema.minimum !== undefined ||\n schema.maximum !== undefined ||\n schema.multipleOf !== undefined\n )\n inferred.push(\"number\")\n return inferred\n}\n\n/** The JSON type name of a runtime value. */\nexport const jsonTypeOf = (value: unknown): SchemaType | \"undefined\" => {\n if (value === null) return \"null\"\n if (Array.isArray(value)) return \"array\"\n switch (typeof value) {\n case \"string\":\n return \"string\"\n case \"boolean\":\n return \"boolean\"\n case \"number\":\n return Number.isInteger(value) ? \"integer\" : \"number\"\n case \"object\":\n return \"object\"\n default:\n return \"undefined\"\n }\n}\n\nexport type SchemaVisitor = (schema: SchemaObject, path: string[]) => void\n\n/**\n * Depth-first walk over a schema tree, resolving `$ref`s. Each resolved schema is visited once per\n * call: the annotation consumers (identities, refs, volatile/scope marks) only care that a node is\n * reachable, and visiting per path is exponential on densely cross-referenced documents.\n */\nexport const walkSchema = (\n document: OpenAPIDocument,\n schema: SchemaObject,\n visit: SchemaVisitor,\n path: string[] = [],\n) => {\n const seen = new Set<SchemaObject>()\n const go = (node: SchemaObject, at: string[]) => {\n const resolved = resolveSchema(document, node)\n if (seen.has(resolved)) return\n seen.add(resolved)\n visit(resolved, at)\n for (const [name, child] of Object.entries(resolved.properties ?? {}))\n go(child, [...at, \"properties\", name])\n if (typeof resolved.additionalProperties === \"object\")\n go(resolved.additionalProperties, [...at, \"additionalProperties\"])\n if (resolved.items) go(resolved.items, [...at, \"items\"])\n resolved.prefixItems?.forEach((child, i) => {\n go(child, [...at, \"prefixItems\", String(i)])\n })\n resolved.propertyNames && go(resolved.propertyNames, [...at, \"propertyNames\"])\n for (const keyword of [\"oneOf\", \"anyOf\", \"allOf\"] as const) {\n resolved[keyword]?.forEach((child, i) => {\n go(child, [...at, keyword, String(i)])\n })\n }\n resolved.not && go(resolved.not, [...at, \"not\"])\n }\n go(schema, path)\n}\nexport type ValidationError = { path: Array<string | number>; message: string }\n\nconst deepEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) return true\n if (typeof a !== typeof b || a === null || b === null) return false\n if (Array.isArray(a)) {\n return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]))\n }\n if (typeof a === \"object\" && typeof b === \"object\" && !Array.isArray(b)) {\n const ka = Object.keys(a as object)\n const kb = Object.keys(b as object)\n return (\n ka.length === kb.length &&\n ka.every((k) =>\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n )\n )\n }\n return false\n}\n\nconst FORMAT_PATTERNS: Record<string, RegExp> = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,\n date: /^\\d{4}-\\d{2}-\\d{2}$/,\n \"date-time\": /^\\d{4}-\\d{2}-\\d{2}[Tt ]\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([Zz]|[+-]\\d{2}:\\d{2})$/,\n email: /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/,\n uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\\s]*$/,\n ipv4: /^(25[0-5]|2[0-4]\\d|1?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|1?\\d?\\d)){3}$/,\n}\n\nconst graphemeLength = (value: string) => [...value].length\n\n/**\n * Validate `value` against `schema`. Supports the JSON Schema subset Mockingbird generates from\n * (see `@crvouga/mockingbird-openapi-arbitrary`). Returns an empty array when valid.\n */\nexport const validateValue = (\n document: OpenAPIDocument,\n schema: SchemaObject,\n value: unknown,\n path: Array<string | number> = [],\n): ValidationError[] => {\n const errors: ValidationError[] = []\n const s = resolveSchema(document, schema)\n const fail = (message: string) => errors.push({ path, message })\n const actual = jsonTypeOf(value)\n if (actual === \"undefined\") {\n fail(\"value is undefined\")\n return errors\n }\n const types = schemaTypes(s)\n if (types.length > 0) {\n const ok = types.some((t) => t === actual || (t === \"number\" && actual === \"integer\"))\n if (!ok) {\n fail(`expected type ${types.join(\"|\")}, got ${actual}`)\n return errors\n }\n }\n // OpenAPI commonly pairs `type: [\"string\",\"null\"]` with an enum of the non-null values;\n // null is admitted by the type union and must not fail the enum check.\n if (\n s.enum &&\n !(value === null && types.includes(\"null\")) &&\n !s.enum.some((candidate) => deepEqual(candidate, value))\n ) {\n fail(\"value not in enum\")\n }\n if (s.const !== undefined && !deepEqual(s.const, value)) fail(\"value does not equal const\")\n if (typeof value === \"string\") {\n const length = graphemeLength(value)\n if (s.minLength !== undefined && length < s.minLength)\n fail(`length ${length} < minLength ${s.minLength}`)\n if (s.maxLength !== undefined && length > s.maxLength)\n fail(`length ${length} > maxLength ${s.maxLength}`)\n if (s.pattern !== undefined) {\n try {\n if (!new RegExp(s.pattern, \"u\").test(value)) fail(`does not match pattern ${s.pattern}`)\n } catch {\n // unsupported pattern syntax: skip, matching lenient validators\n }\n }\n if (s.format !== undefined) {\n const pattern = FORMAT_PATTERNS[s.format]\n if (pattern && !pattern.test(value)) fail(`does not match format ${s.format}`)\n }\n }\n if (typeof value === \"number\") {\n if (s.minimum !== undefined && value < s.minimum) fail(`${value} < minimum ${s.minimum}`)\n if (s.maximum !== undefined && value > s.maximum) fail(`${value} > maximum ${s.maximum}`)\n if (s.exclusiveMinimum !== undefined && value <= s.exclusiveMinimum)\n fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`)\n if (s.exclusiveMaximum !== undefined && value >= s.exclusiveMaximum)\n fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`)\n if (\n s.multipleOf !== undefined &&\n Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9\n ) {\n fail(`${value} is not a multiple of ${s.multipleOf}`)\n }\n }\n if (Array.isArray(value)) {\n if (s.minItems !== undefined && value.length < s.minItems)\n fail(`${value.length} items < minItems ${s.minItems}`)\n if (s.maxItems !== undefined && value.length > s.maxItems)\n fail(`${value.length} items > maxItems ${s.maxItems}`)\n if (\n s.uniqueItems &&\n value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item)))\n )\n fail(\"items are not unique\")\n value.forEach((item, i) => {\n const itemSchema = s.prefixItems?.[i] ?? s.items\n if (itemSchema) errors.push(...validateValue(document, itemSchema, item, [...path, i]))\n })\n }\n if (actual === \"object\") {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record)\n for (const name of s.required ?? [])\n if (!(name in record)) fail(`missing required property ${name}`)\n if (s.minProperties !== undefined && keys.length < s.minProperties)\n fail(`${keys.length} properties < minProperties ${s.minProperties}`)\n if (s.maxProperties !== undefined && keys.length > s.maxProperties)\n fail(`${keys.length} properties > maxProperties ${s.maxProperties}`)\n for (const key of keys) {\n const property = s.properties?.[key]\n if (property) {\n errors.push(...validateValue(document, property, record[key], [...path, key]))\n continue\n }\n if (s.additionalProperties === false) fail(`unexpected property ${key}`)\n else if (typeof s.additionalProperties === \"object\") {\n errors.push(...validateValue(document, s.additionalProperties, record[key], [...path, key]))\n }\n if (s.propertyNames) {\n const nameErrors = validateValue(document, s.propertyNames, key, [...path, key])\n if (nameErrors.length > 0)\n fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`)\n }\n }\n }\n if (s.allOf)\n for (const branch of s.allOf) errors.push(...validateValue(document, branch, value, path))\n if (s.anyOf && !s.anyOf.some((branch) => validateValue(document, branch, value).length === 0))\n fail(\"matches no anyOf branch\")\n if (s.oneOf) {\n const matches = s.oneOf.filter(\n (branch) => validateValue(document, branch, value).length === 0,\n ).length\n if (matches !== 1) fail(`matches ${matches} oneOf branches, expected exactly 1`)\n }\n if (s.not && validateValue(document, s.not, value).length === 0)\n fail(\"matches forbidden `not` schema\")\n return errors\n}\n\nexport const isValid = (document: OpenAPIDocument, schema: SchemaObject, value: unknown) =>\n validateValue(document, schema, value).length === 0\n\nexport type { JsonValue }\n", "/**\n * Rails/PHP/Stripe-style bracket notation for `application/x-www-form-urlencoded` bodies and\n * query strings:\n *\n * address[city]=Paris -> { address: { city: \"Paris\" } }\n * items[0][name]=a -> { items: [{ name: \"a\" }] }\n * tags[]=x&tags[]=y -> { tags: [\"x\", \"y\"] }\n * metadata[k]=v -> { metadata: { k: \"v\" } }\n *\n * Decoding yields only strings, arrays and plain objects \u2014 coercion is the caller's concern,\n * exactly like a real HTTP server.\n */\n\nexport type FormValue = string | FormValue[] | { [key: string]: FormValue }\n\nexport type FormObject = { [key: string]: FormValue }\n\nconst encodeComponent = (value: string) =>\n encodeURIComponent(value).replace(\n /[!'()*]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n\nconst flatten = (prefix: string, value: unknown, out: Array<[string, string]>) => {\n if (value === undefined) return\n if (value === null) {\n out.push([prefix, \"\"])\n return\n }\n if (Array.isArray(value)) {\n if (value.length === 0) {\n out.push([prefix, \"\"])\n return\n }\n value.forEach((item, index) => {\n flatten(`${prefix}[${index}]`, item, out)\n })\n return\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n if (entries.length === 0) {\n out.push([prefix, \"\"])\n return\n }\n for (const [key, item] of entries) flatten(`${prefix}[${key}]`, item, out)\n return\n }\n out.push([prefix, String(value)])\n}\n\n/**\n * Encode a JSON-like value as bracket-notation pairs. Nested arrays use explicit indices\n * (`a[0]`), which every bracket parser (including Stripe's) accepts; empty arrays/objects\n * encode as an empty string, matching how Stripe unsets fields.\n */\nexport const encodeFormPairs = (value: Record<string, unknown>): Array<[string, string]> => {\n const out: Array<[string, string]> = []\n for (const [key, item] of Object.entries(value)) flatten(key, item, out)\n return out\n}\n\n/** Encode to a full `application/x-www-form-urlencoded` string. */\nexport const encodeForm = (value: Record<string, unknown>): string =>\n encodeFormPairs(value)\n .map(([k, v]) => `${encodeComponent(k)}=${encodeComponent(v)}`)\n .join(\"&\")\n\nconst parsePath = (rawKey: string): string[] => {\n const open = rawKey.indexOf(\"[\")\n if (open === -1) return [rawKey]\n const path = [rawKey.slice(0, open)]\n const rest = rawKey.slice(open)\n const pattern = /\\[([^\\]]*)\\]/g\n let match: RegExpExecArray | null = pattern.exec(rest)\n let consumed = 0\n while (match !== null) {\n if (match.index !== consumed) return [rawKey]\n path.push(match[1] ?? \"\")\n consumed = match.index + match[0].length\n match = pattern.exec(rest)\n }\n if (consumed !== rest.length) return [rawKey]\n return path\n}\n\nconst isIndex = (segment: string) => /^(0|[1-9][0-9]*)$/.test(segment)\n\n/**\n * Write an own property. `__proto__` is the one key with an inherited setter, so it needs\n * `defineProperty`; every other key shadows its inherited namesake by plain assignment.\n */\nconst put = (target: object, key: string | number, value: FormValue): void => {\n if (key === \"__proto__\") {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n })\n return\n }\n ;(target as Record<string | number, FormValue>)[key] = value\n}\n\nconst assign = (target: FormObject, path: string[], value: string) => {\n let cursor: FormValue = target\n for (let i = 0; i < path.length; i++) {\n const segment = path[i] as string\n const last = i === path.length - 1\n if (Array.isArray(cursor)) {\n const index: number | undefined =\n segment === \"\" ? cursor.length : isIndex(segment) ? Number(segment) : undefined\n if (index === undefined) return\n if (last) {\n put(cursor, index, value)\n return\n }\n const next: FormValue | undefined = Object.hasOwn(cursor, index)\n ? (cursor as Record<number, FormValue>)[index]\n : undefined\n if (next === undefined || typeof next === \"string\") {\n const created: FormValue = path[i + 1] === \"\" || isIndex(path[i + 1] as string) ? [] : {}\n put(cursor, index, created)\n cursor = created\n } else {\n cursor = next\n }\n continue\n }\n if (typeof cursor === \"string\") return\n if (last) {\n put(cursor, segment, value)\n return\n }\n const nextSegment = path[i + 1] as string\n const existing: FormValue | undefined = Object.hasOwn(cursor, segment)\n ? (cursor as Record<string, FormValue>)[segment]\n : undefined\n if (existing === undefined || typeof existing === \"string\") {\n const created: FormValue = nextSegment === \"\" || isIndex(nextSegment) ? [] : {}\n put(cursor, segment, created)\n cursor = created\n } else {\n cursor = existing\n }\n }\n}\n\n/** Decode `key=value&...` pairs (already percent-decoded) into a nested object. */\nexport const decodeFormPairs = (pairs: Iterable<[string, string]>): FormObject => {\n const out: FormObject = {}\n for (const [rawKey, value] of pairs) assign(out, parsePath(rawKey), value)\n return densify(out) as FormObject\n}\n\n/** Sparse arrays (`a[2]=x` without `a[0]`) become dense in bracket parsers. */\nconst densify = (value: FormValue): FormValue => {\n if (typeof value === \"string\") return value\n if (Array.isArray(value)) return value.filter((item) => item !== undefined).map(densify)\n const out: FormObject = {}\n for (const [key, item] of Object.entries(value)) put(out, key, densify(item))\n return out\n}\n\n/** Decode an `application/x-www-form-urlencoded` body or a query string (with or without `?`). */\nexport const decodeForm = (text: string): FormObject => {\n const source = text.startsWith(\"?\") ? text.slice(1) : text\n return decodeFormPairs(new URLSearchParams(source).entries())\n}\n", "import { decodeForm, encodeForm } from \"./form.js\"\n\nexport const JSON_MEDIA_TYPE = \"application/json\"\nexport const FORM_MEDIA_TYPE = \"application/x-www-form-urlencoded\"\n\n/** The essence of a `Content-Type` header: lower-cased media type without parameters. */\nexport const mediaTypeOf = (contentType: string | null | undefined): string | undefined => {\n if (!contentType) return undefined\n const essence = contentType.split(\";\")[0]?.trim().toLowerCase()\n return essence ? essence : undefined\n}\n\nconst isJsonMediaType = (mediaType: string) =>\n mediaType === JSON_MEDIA_TYPE || mediaType.endsWith(\"+json\") || mediaType === \"text/json\"\n\nexport type DecodedBody =\n | { kind: \"empty\" }\n | { kind: \"json\"; value: unknown }\n | { kind: \"form\"; value: Record<string, unknown> }\n | { kind: \"text\"; value: string }\n | { kind: \"bytes\"; value: Uint8Array }\n | { kind: \"invalid\"; mediaType: string; text: string; error: string }\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: false })\n\n/**\n * Decode raw bytes according to a `Content-Type`. Never throws: malformed payloads come back as\n * `{ kind: \"invalid\" }` so callers (mock servers, the differential runner) can respond like a real\n * server would instead of crashing.\n */\nexport const decodeBody = (\n contentType: string | null | undefined,\n bytes: Uint8Array,\n): DecodedBody => {\n if (bytes.byteLength === 0) return { kind: \"empty\" }\n const mediaType = mediaTypeOf(contentType)\n if (mediaType === undefined) return { kind: \"bytes\", value: bytes }\n if (isJsonMediaType(mediaType)) {\n const text = utf8.decode(bytes)\n try {\n return { kind: \"json\", value: JSON.parse(text) }\n } catch (error) {\n return {\n kind: \"invalid\",\n mediaType,\n text,\n error: error instanceof Error ? error.message : String(error),\n }\n }\n }\n if (mediaType === FORM_MEDIA_TYPE) {\n return { kind: \"form\", value: decodeForm(utf8.decode(bytes)) }\n }\n if (mediaType.startsWith(\"text/\")) return { kind: \"text\", value: utf8.decode(bytes) }\n return { kind: \"bytes\", value: bytes }\n}\n\n/** Read and decode a Request/Response body. */\nexport const readBody = async (message: Request | Response): Promise<DecodedBody> => {\n const bytes = new Uint8Array(await message.arrayBuffer())\n return decodeBody(message.headers.get(\"content-type\"), bytes)\n}\n\nexport type EncodedBody = {\n contentType: string\n body: string\n}\n\n/** Encode a JSON-like value for the given media type. Throws for unsupported media types. */\nexport const encodeBody = (mediaType: string, value: unknown): EncodedBody => {\n const essence = mediaTypeOf(mediaType) ?? mediaType\n if (isJsonMediaType(essence)) return { contentType: essence, body: JSON.stringify(value) }\n if (essence === FORM_MEDIA_TYPE) {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${FORM_MEDIA_TYPE} bodies must be objects`)\n }\n return { contentType: essence, body: encodeForm(value as Record<string, unknown>) }\n }\n if (essence.startsWith(\"text/\")) return { contentType: essence, body: String(value) }\n throw new TypeError(`unsupported request media type: ${mediaType}`)\n}\n", "import { JSON_MEDIA_TYPE } from \"@crvouga/mockingbird-http-codec\"\n\n/** JSON response with a normalised content type. */\nexport const jsonRes = (\n status: number,\n body: unknown,\n headers: Record<string, string> = {},\n): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": JSON_MEDIA_TYPE, ...headers },\n })\n\n/** Thrown by handlers to produce a provider-shaped error response via `onError`. */\nexport class HttpError extends Error {\n constructor(\n readonly status: number,\n readonly body: unknown,\n readonly headers: Record<string, string> = {},\n ) {\n super(`HTTP ${status}`)\n this.name = \"HttpError\"\n }\n\n toResponse(): Response {\n const contentType = this.headers[\"content-type\"]?.split(\";\", 1)[0]?.trim().toLowerCase()\n if (contentType === \"text/plain\") {\n return new Response(String(this.body), {\n status: this.status,\n headers: this.headers,\n })\n }\n return jsonRes(this.status, this.body, this.headers)\n }\n}\n\nexport type FieldResult<T> = { ok: true; value: T } | { ok: false; reason: string }\n\nconst ok = <T>(value: T): FieldResult<T> => ({ ok: true, value })\nconst fail = <T>(reason: string): FieldResult<T> => ({ ok: false, reason })\n\n/** Form bodies decode to strings; these coerce the way HTTP servers do, reporting why not. */\nexport const coerce = {\n string(value: unknown): FieldResult<string> {\n return typeof value === \"string\" ? ok(value) : fail(\"expected a string\")\n },\n integer(value: unknown): FieldResult<number> {\n if (typeof value === \"number\" && Number.isInteger(value)) return ok(value)\n if (typeof value === \"string\" && /^-?\\d+$/.test(value.trim())) {\n const parsed = Number(value)\n return Number.isSafeInteger(parsed) ? ok(parsed) : fail(\"integer out of range\")\n }\n return fail(\"expected an integer\")\n },\n boolean(value: unknown): FieldResult<boolean> {\n if (typeof value === \"boolean\") return ok(value)\n if (value === \"true\" || value === \"1\") return ok(true)\n if (value === \"false\" || value === \"0\") return ok(false)\n return fail(\"expected a boolean\")\n },\n enumeration<T extends string>(value: unknown, allowed: readonly T[]): FieldResult<T> {\n const match = allowed.find((candidate) => candidate === value)\n return match === undefined ? fail(`expected one of ${allowed.join(\", \")}`) : ok(match)\n },\n /** Flat string-to-string map, the shape of Stripe-style `metadata`. */\n stringMap(value: unknown): FieldResult<Record<string, string>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value))\n return fail(\"expected an object\")\n const out: Record<string, string> = {}\n for (const [key, item] of Object.entries(value)) {\n if (typeof item !== \"string\") return fail(`expected a string at ${key}`)\n out[key] = item\n }\n return ok(out)\n },\n}\n\n/** Count Unicode code points, the way JSON Schema and most APIs measure string length. */\nexport const codePointLength = (value: string) => [...value].length\n", "import type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\nconst ALPHABET = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\n/** FNV-1a over a string, mixed once more so consecutive counters look unrelated. */\nconst mix = (input: string): number => {\n let hash = 0x811c9dc5\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n hash ^= hash >>> 16\n hash = Math.imul(hash, 0x85ebca6b) >>> 0\n hash ^= hash >>> 13\n return hash >>> 0\n}\n\n/** Deterministic, opaque-looking alphanumeric token of `length` characters derived from `input`. */\nexport const opaqueToken = (input: string, length: number): string => {\n let out = \"\"\n let round = 0\n while (out.length < length) {\n let hash = mix(`${input}:${round++}`)\n for (let i = 0; i < 5 && out.length < length; i++) {\n out += ALPHABET.charAt(hash % ALPHABET.length)\n hash = Math.floor(hash / ALPHABET.length)\n }\n }\n return out\n}\n\n/**\n * Sequential id source persisted in SQLite. Ids are deterministic for a given\n * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.\n */\nexport class IdSequence {\n constructor(\n private readonly sqlite: SqliteClient,\n private readonly namespace: string,\n private readonly salt = \"mockingbird\",\n ) {}\n\n next(prefix: string, length = 14): string {\n return this.sqlite.transaction(() => {\n const row = this.sqlite\n .prepare(\n \"SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'\",\n )\n .get<{ value: number }>(this.namespace, prefix)\n const value = (row?.value ?? 0) + 1\n this.sqlite\n .prepare(\n `INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)\n ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`,\n )\n .run(this.namespace, prefix, value)\n return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`\n })\n }\n}\n", "import type { RequestLog } from \"./metrics.js\"\n\n/** One journal entry: a request log stamped with when (on the mock clock) it was handled. */\nexport type JournalEntry = RequestLog & { at: string }\n\nexport type JournalQuery = {\n /** Only this namespace. Omit for every namespace, oldest first across all of them. */\n namespace?: string\n operationId?: string\n status?: number\n /** Only entries at or after this instant (epoch ms). */\n since?: number\n /** At most this many, the most recent kept. */\n limit?: number\n}\n\nexport type Journal = {\n readonly size: number\n record(entry: JournalEntry): void\n list(query?: JournalQuery): JournalEntry[]\n /** Forget one namespace's entries, or every namespace's. */\n clear(namespace?: string): void\n}\n\n/** Default number of entries each namespace keeps. */\nexport const DEFAULT_JOURNAL_SIZE = 1000\n\n/**\n * The last `size` requests per namespace, in a ring buffer: what the mock actually saw,\n * so a test can prove a request arrived (or never did) without reading logs.\n */\nexport const createJournal = (size: number = DEFAULT_JOURNAL_SIZE): Journal => {\n const capacity = Math.max(0, Math.floor(size))\n const rings = new Map<string, { entries: JournalEntry[]; next: number }>()\n let sequence = 0\n const order = new WeakMap<JournalEntry, number>()\n const inOrder = (ring: { entries: JournalEntry[]; next: number }): JournalEntry[] =>\n ring.entries.length < capacity\n ? ring.entries\n : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)]\n return {\n size: capacity,\n record(entry) {\n if (capacity === 0) return\n order.set(entry, sequence++)\n let ring = rings.get(entry.namespace)\n if (!ring) {\n ring = { entries: [], next: 0 }\n rings.set(entry.namespace, ring)\n }\n if (ring.entries.length < capacity) ring.entries.push(entry)\n else {\n ring.entries[ring.next] = entry\n ring.next = (ring.next + 1) % capacity\n }\n },\n list(query = {}) {\n const source =\n query.namespace !== undefined\n ? inOrder(rings.get(query.namespace) ?? { entries: [], next: 0 })\n : [...rings.values()]\n .flatMap(inOrder)\n .sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0))\n const matched = source.filter(\n (entry) =>\n (query.operationId === undefined || entry.operationId === query.operationId) &&\n (query.status === undefined || entry.status === query.status) &&\n (query.since === undefined || Date.parse(entry.at) >= query.since),\n )\n return query.limit !== undefined ? matched.slice(-Math.max(0, query.limit)) : matched\n },\n clear(namespace) {\n if (namespace === undefined) rings.clear()\n else rings.delete(namespace)\n },\n }\n}\n\n/** What a service knows about a request that the runtime cannot see from outside. */\nexport type ResponseNotes = {\n /** Resource ids the handler touched, e.g. `{ userId, orderId }`. */\n ids?: Record<string, string>\n /** Set when the handler created a resource the request referred to but did not exist. */\n adopted?: boolean\n}\n\nconst notes = new WeakMap<Response, ResponseNotes>()\n\n/**\n * Attach notes to a response for the request journal and structured log. They travel\n * beside the response, never in it, so nothing the vendor would not send reaches a client.\n */\nexport const annotateResponse = (response: Response, extra: ResponseNotes): Response => {\n const existing = notes.get(response)\n notes.set(response, {\n ...existing,\n ...extra,\n ...(existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}),\n })\n return response\n}\n\nexport const responseNotes = (response: Response): ResponseNotes | undefined => notes.get(response)\n", "/** One handled request, as the structured log sees it. */\nexport type RequestLog = {\n service: string\n namespace: string\n operationId: string | undefined\n method: string\n path: string\n status: number\n durationMs: number\n /** True when the path matched no operation in the contract. */\n unmatched: boolean\n /** Set when a fault rule produced the response. */\n faultId?: string\n /** Resource ids the handler touched (`userId`, `orderId`, \u2026), when the service reports them. */\n ids?: Record<string, string>\n /** Set when the service created a resource the request referred to but that did not exist. */\n adopted?: boolean\n}\n\nexport type MetricsReport = {\n requests: number\n /** Counts keyed `<operationId> <status>`. */\n byOperation: Record<string, number>\n /**\n * Paths that matched no operation, most frequent first.\n *\n * This is the early-warning signal: a consumer calling something the mock does\n * not implement shows up here as a count, before it fails a suite as a 404.\n */\n unmatched: { method: string; path: string; count: number }[]\n faults: number\n totalDurationMs: number\n}\n\nexport type Metrics = {\n record(entry: RequestLog): void\n report(): MetricsReport\n reset(): void\n}\n\nexport const createMetrics = (): Metrics => {\n let requests = 0\n let faults = 0\n let totalDurationMs = 0\n const byOperation = new Map<string, number>()\n const unmatched = new Map<string, number>()\n return {\n record(entry) {\n requests++\n totalDurationMs += entry.durationMs\n if (entry.faultId !== undefined) faults++\n const key = `${entry.operationId ?? \"(unmatched)\"} ${entry.status}`\n byOperation.set(key, (byOperation.get(key) ?? 0) + 1)\n if (entry.unmatched) {\n const route = `${entry.method} ${entry.path}`\n unmatched.set(route, (unmatched.get(route) ?? 0) + 1)\n }\n },\n report: () => ({\n requests,\n byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),\n unmatched: [...unmatched]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([route, count]) => {\n const space = route.indexOf(\" \")\n return { method: route.slice(0, space), path: route.slice(space + 1), count }\n }),\n faults,\n totalDurationMs,\n }),\n reset() {\n requests = 0\n faults = 0\n totalDurationMs = 0\n byOperation.clear()\n unmatched.clear()\n },\n }\n}\n", "/** A stable identifier for a point in a {@link Timeline}. */\nexport type CheckpointId = string\n\n/** An immutable node in a timeline's checkpoint DAG. */\nexport type Checkpoint<T> = Readonly<{\n id: CheckpointId\n branch: string\n parent: CheckpointId | null\n /** Logical time supplied by the timeline's injected clock. */\n at: number\n value: T\n}>\n\nexport type TimelineOptions = {\n /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */\n now?: () => number\n /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */\n maxCheckpoints?: number\n /** Customize deterministic checkpoint IDs. */\n id?: (sequence: number) => CheckpointId\n}\n\nexport type CommitOptions = {\n branch?: string\n /** Parent checkpoint. Defaults to the selected branch's current head. */\n parent?: CheckpointId | null\n}\n\nexport type ForkOptions = {\n /** Checkpoint to fork from. Defaults to the main branch's head. */\n from?: CheckpointId\n}\n\nconst BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/\n\n/**\n * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable\n * records, namespace images, or copy-on-write SQL engine snapshots.\n *\n * Values are retained by reference. Engines can therefore use persistent/COW snapshots while\n * simpler services can use immutable values. IDs and GC order are deterministic, and all IO\n * (the logical clock) is injected.\n */\nexport class Timeline<T> {\n readonly maxCheckpoints: number\n private readonly now: () => number\n private readonly makeId: (sequence: number) => CheckpointId\n private readonly nodes = new Map<CheckpointId, Checkpoint<T>>()\n private readonly heads = new Map<string, CheckpointId>()\n /** Unreferenced nodes in the exact order they became collectible. */\n private readonly evictable = new Set<CheckpointId>()\n /** Branch heads plus explicit retainers. Absent means zero. */\n private readonly references = new Map<CheckpointId, number>()\n private readonly explicitPins = new Map<CheckpointId, number>()\n private sequence = 0\n\n constructor(options: TimelineOptions = {}) {\n const max = options.maxCheckpoints ?? 1_000\n if (!Number.isSafeInteger(max) || max < 1)\n throw new RangeError(\"maxCheckpoints must be a positive integer\")\n this.maxCheckpoints = max\n this.now = options.now ?? (() => this.sequence)\n this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, \"0\")}`)\n }\n\n /** Capture a new immutable value and move `branch` to it. */\n commit(value: T, options: CommitOptions = {}): Checkpoint<T> {\n const branch = options.branch ?? \"main\"\n this.assertBranch(branch)\n const parent = options.parent === undefined ? (this.heads.get(branch) ?? null) : options.parent\n if (parent !== null && !this.nodes.has(parent)) throw new RangeError(`no checkpoint ${parent}`)\n const id = this.makeId(++this.sequence)\n if (this.nodes.has(id)) throw new RangeError(`duplicate checkpoint id ${id}`)\n const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value })\n this.nodes.set(id, checkpoint)\n this.moveHead(branch, id)\n this.collect(this.maxCheckpoints)\n return checkpoint\n }\n\n /** Create a branch pointer without copying its checkpoint value. */\n fork(branch: string, options: ForkOptions = {}): Checkpoint<T> | undefined {\n this.assertBranch(branch)\n if (this.heads.has(branch)) throw new RangeError(`branch already exists: ${branch}`)\n const from = options.from ?? this.heads.get(\"main\")\n if (from === undefined) return undefined\n const checkpoint = this.get(from)\n this.moveHead(branch, checkpoint.id)\n return checkpoint\n }\n\n /** Move a branch pointer to an existing checkpoint. */\n checkout(branch: string, id: CheckpointId): Checkpoint<T> {\n this.assertBranch(branch)\n const checkpoint = this.get(id)\n this.moveHead(branch, checkpoint.id)\n return checkpoint\n }\n\n get(id: CheckpointId): Checkpoint<T> {\n const checkpoint = this.nodes.get(id)\n if (!checkpoint) throw new RangeError(`no checkpoint ${id}`)\n return checkpoint\n }\n\n head(branch = \"main\"): Checkpoint<T> | undefined {\n const id = this.heads.get(branch)\n return id === undefined ? undefined : this.get(id)\n }\n\n hasBranch(branch: string): boolean {\n return this.heads.has(branch)\n }\n\n branches(): Readonly<Record<string, CheckpointId>> {\n return Object.freeze(\n Object.fromEntries([...this.heads].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),\n )\n }\n\n checkpoints(): readonly Checkpoint<T>[] {\n return [...this.nodes.values()]\n }\n\n /** Number of retained checkpoints without allocating an array. */\n get size(): number {\n return this.nodes.size\n }\n\n /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */\n retain(id: CheckpointId): Checkpoint<T> {\n const checkpoint = this.get(id)\n this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1)\n this.addReference(id)\n return checkpoint\n }\n\n /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */\n release(id: CheckpointId): boolean {\n if (!this.nodes.has(id)) return false\n const pins = this.explicitPins.get(id) ?? 0\n if (pins === 0) return false\n if (pins === 1) this.explicitPins.delete(id)\n else this.explicitPins.set(id, pins - 1)\n this.removeReference(id)\n this.collect(this.maxCheckpoints)\n return true\n }\n\n deleteBranch(branch: string): boolean {\n if (branch === \"main\") throw new RangeError(\"cannot delete main branch\")\n const previous = this.heads.get(branch)\n const deleted = this.heads.delete(branch)\n if (previous !== undefined) this.removeReference(previous)\n this.collect(this.maxCheckpoints)\n return deleted\n }\n\n /**\n * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):\n * commits never scan pinned nodes or the retained history. Parents are metadata rather than a\n * storage dependency, so a retained node remains usable after pruning.\n */\n gc(max = this.maxCheckpoints): CheckpointId[] {\n if (!Number.isSafeInteger(max) || max < 1)\n throw new RangeError(\"max must be a positive integer\")\n const removed: CheckpointId[] = []\n this.collect(max, removed)\n return removed\n }\n\n private collect(max: number, removed?: CheckpointId[]): void {\n while (this.nodes.size > max && this.evictable.size > 0) {\n const id = this.evictable.values().next().value as CheckpointId\n this.evictable.delete(id)\n this.nodes.delete(id)\n removed?.push(id)\n }\n }\n\n private moveHead(branch: string, id: CheckpointId): void {\n const previous = this.heads.get(branch)\n if (previous === id) return\n if (previous !== undefined) this.removeReference(previous)\n this.heads.set(branch, id)\n this.addReference(id)\n }\n\n private addReference(id: CheckpointId): void {\n this.references.set(id, (this.references.get(id) ?? 0) + 1)\n this.evictable.delete(id)\n }\n\n private removeReference(id: CheckpointId): void {\n const next = (this.references.get(id) ?? 0) - 1\n if (next > 0) this.references.set(id, next)\n else {\n this.references.delete(id)\n if (this.nodes.has(id)) this.evictable.add(id)\n }\n }\n\n private assertBranch(branch: string): void {\n if (!BRANCH_PATTERN.test(branch)) throw new RangeError(`branch must match ${BRANCH_PATTERN}`)\n }\n}\n", "import { Database } from \"@crvouga/mockingbird-service-sqlite\"\nimport type { SqliteClient } from \"./client.js\"\n\n/** Construct the default in-memory SQLite client (`@crvouga/mockingbird-service-sqlite`). */\nexport const createDefaultSqlite = (): SqliteClient => new Database()\n\n/** Use the injected client, or fall back to {@link createDefaultSqlite}. */\nexport const resolveSqlite = (sqlite?: SqliteClient): SqliteClient =>\n sqlite ?? createDefaultSqlite()\n", "import type { SqliteClient } from \"./client.js\"\n\n/** One named, ordered schema change applied exactly once per client. */\nexport type Migration = {\n /** Stable id stored in `schema_migrations`. Must be unique across the list. */\n id: string\n sql: string\n}\n\nconst ensureMigrationsTable = (sqlite: SqliteClient) => {\n sqlite.exec(`\n CREATE TABLE IF NOT EXISTS schema_migrations (\n id TEXT PRIMARY KEY NOT NULL,\n applied_at INTEGER NOT NULL\n )\n `)\n}\n\n/**\n * Apply pending migrations in order inside a single transaction.\n *\n * Idempotent: already-applied ids are skipped. Re-running with the same list\n * is a no-op after the first successful boot.\n */\nexport const migrate = (sqlite: SqliteClient, migrations: readonly Migration[]): void => {\n ensureMigrationsTable(sqlite)\n const applied = new Set(\n sqlite\n .prepare(\"SELECT id FROM schema_migrations\")\n .all<{ id: string }>()\n .map((row) => row.id),\n )\n const pending = migrations.filter((migration) => !applied.has(migration.id))\n if (pending.length === 0) return\n\n const insert = sqlite.prepare(\"INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)\")\n const now = Math.floor(Date.now() / 1000)\n sqlite.transaction(() => {\n for (const migration of pending) {\n sqlite.exec(migration.sql)\n insert.run(migration.id, now)\n }\n })\n}\n\n/** Applied migration ids in application order (by `applied_at`, then `id`). */\nexport const listAppliedMigrations = (sqlite: SqliteClient): string[] => {\n ensureMigrationsTable(sqlite)\n return sqlite\n .prepare(\"SELECT id FROM schema_migrations ORDER BY applied_at ASC, id ASC\")\n .all<{ id: string }>()\n .map((row) => row.id)\n}\n", "import type { SqliteClient } from \"./client.js\"\nimport { type Migration, migrate } from \"./migrate.js\"\n\n/**\n * Core Mockingbird service schema: namespaced JSON records and counters.\n *\n * Applied on every service boot via {@link migrateCore}.\n */\nexport const CORE_MIGRATIONS: readonly Migration[] = [\n {\n id: \"20260322_core_records_sequences\",\n sql: `\n CREATE TABLE IF NOT EXISTS mockingbird_records (\n namespace TEXT NOT NULL,\n collection TEXT NOT NULL,\n id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n value TEXT NOT NULL,\n PRIMARY KEY (namespace, collection, id)\n );\n CREATE INDEX IF NOT EXISTS mockingbird_records_seq\n ON mockingbird_records (namespace, collection, seq);\n CREATE TABLE IF NOT EXISTS mockingbird_sequences (\n namespace TEXT NOT NULL,\n name TEXT NOT NULL,\n kind TEXT NOT NULL,\n value INTEGER NOT NULL,\n PRIMARY KEY (namespace, name, kind)\n );\n `,\n },\n]\n\n/** Apply {@link CORE_MIGRATIONS} (idempotent). */\nexport const migrateCore = (sqlite: SqliteClient): void => {\n migrate(sqlite, CORE_MIGRATIONS)\n}\n\n/** Delete every record and sequence belonging to `namespace`. */\nexport const clearNamespace = (sqlite: SqliteClient, namespace: string): void => {\n sqlite.transaction(() => {\n sqlite.prepare(\"DELETE FROM mockingbird_records WHERE namespace = ?\").run(namespace)\n sqlite.prepare(\"DELETE FROM mockingbird_sequences WHERE namespace = ?\").run(namespace)\n })\n}\n", "/**\n * Mockingbird's OpenAPI extensions. They are deliberately generic: nothing here knows about any\n * particular provider. Provider specifics live in each provider's `openapi.yaml`.\n */\n\n/** `x-mockingbird` on an operation. */\nexport type OperationExtension = {\n /** `false` marks an operation the mock explicitly does not implement. Default `true`. */\n supported?: boolean\n /** Human explanation, required when `supported: false` or `parity.enabled: false`. */\n reason?: string\n parity?: {\n /** Whether the differential runner generates this operation. Defaults to `supported`. */\n enabled?: boolean\n /** `false` for operations that must never hit a real account (destructive, billing\u2026). Default `true`. */\n safe?: boolean\n reason?: string\n }\n}\n\nexport type OperationMetadata = {\n supported: boolean\n reason: string | undefined\n parity: { enabled: boolean; safe: boolean; reason: string | undefined }\n}\n\n/** `x-mockingbird-resource`: this string value is the identity of a resource. */\nexport type ResourceIdentityExtension = { type: string; identity: true }\n\n/** `x-mockingbird-resource-ref`: this value must reference an existing resource of `type`. */\nexport type ResourceRefExtension = {\n type: string\n /** A well-formed id that does not exist, used to exercise not-found behaviour. */\n missing?: string\n}\n\nexport const VOLATILE_KINDS = [\"id\", \"timestamp\", \"token\", \"url\", \"account\", \"opaque\"] as const\nexport type VolatileKind = (typeof VOLATILE_KINDS)[number]\n\n/** `x-mockingbird-volatile`: nondeterministic on the real side; compared by shape only. */\nexport type VolatileExtension = { kind: VolatileKind }\n\nexport const SCOPE_VALUES = [\"run-id\", \"walk-start-unix\", \"walk-start-iso\"] as const\nexport type ScopeValue = (typeof SCOPE_VALUES)[number]\n\n/** `x-mockingbird-scope`: always generate this run-scoped value instead of a random one. */\nexport type ScopeExtension = { value: ScopeValue }\n\n/** `x-mockingbird-unsupported`: the mock does not implement this parameter/property. */\nexport type UnsupportedExtension = true | { reason?: string }\n\nexport type SchemaMetadata = {\n resource: ResourceIdentityExtension | undefined\n resourceRef: ResourceRefExtension | undefined\n volatile: VolatileExtension | undefined\n scope: ScopeExtension | undefined\n unsupported: { reason: string | undefined } | undefined\n}\n\nexport const EXTENSION_KEYS = {\n operation: \"x-mockingbird\",\n resource: \"x-mockingbird-resource\",\n resourceRef: \"x-mockingbird-resource-ref\",\n volatile: \"x-mockingbird-volatile\",\n scope: \"x-mockingbird-scope\",\n unsupported: \"x-mockingbird-unsupported\",\n parityHeader: \"x-mockingbird-parity-header\",\n} as const\n", "import type {\n HeaderObject,\n OpenAPIDocument,\n OperationObject,\n ParameterObject,\n ResponseObject,\n SchemaObject,\n} from \"@crvouga/mockingbird-openapi\"\nimport { deref, resolveSchema } from \"@crvouga/mockingbird-openapi\"\nimport {\n EXTENSION_KEYS,\n type OperationExtension,\n type OperationMetadata,\n SCOPE_VALUES,\n type SchemaMetadata,\n VOLATILE_KINDS,\n} from \"./types.js\"\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst extensionOf = (holder: object, key: string): unknown =>\n (holder as Record<string, unknown>)[key]\n\n/** Read `x-mockingbird` from an operation, applying defaults. */\nexport const operationMetadata = (operation: OperationObject): OperationMetadata => {\n const raw = extensionOf(operation, EXTENSION_KEYS.operation)\n const ext: OperationExtension = isRecord(raw) ? (raw as OperationExtension) : {}\n const supported = ext.supported ?? true\n const parity = ext.parity ?? {}\n return {\n supported,\n reason: typeof ext.reason === \"string\" ? ext.reason : undefined,\n parity: {\n enabled: supported && (parity.enabled ?? true),\n safe: parity.safe ?? true,\n reason: typeof parity.reason === \"string\" ? parity.reason : undefined,\n },\n }\n}\n\nconst readResource = (raw: unknown): SchemaMetadata[\"resource\"] => {\n if (!isRecord(raw) || typeof raw.type !== \"string\" || raw.identity !== true) return undefined\n return { type: raw.type, identity: true }\n}\n\nconst readResourceRef = (raw: unknown): SchemaMetadata[\"resourceRef\"] => {\n if (!isRecord(raw) || typeof raw.type !== \"string\") return undefined\n return { type: raw.type, ...(typeof raw.missing === \"string\" ? { missing: raw.missing } : {}) }\n}\n\nconst readVolatile = (raw: unknown): SchemaMetadata[\"volatile\"] => {\n if (!isRecord(raw) || typeof raw.kind !== \"string\") return undefined\n const kind = VOLATILE_KINDS.find((k) => k === raw.kind)\n return kind === undefined ? undefined : { kind }\n}\n\nconst readScope = (raw: unknown): SchemaMetadata[\"scope\"] => {\n if (!isRecord(raw) || typeof raw.value !== \"string\") return undefined\n const value = SCOPE_VALUES.find((v) => v === raw.value)\n return value === undefined ? undefined : { value }\n}\n\nconst readUnsupported = (raw: unknown): SchemaMetadata[\"unsupported\"] => {\n if (raw === true) return { reason: undefined }\n if (isRecord(raw)) return { reason: typeof raw.reason === \"string\" ? raw.reason : undefined }\n return undefined\n}\n\n/**\n * Read Mockingbird's schema-level extensions from a (resolved) schema or parameter.\n * Extensions on a `$ref` wrapper win over the target's, matching {@link resolveSchema}.\n */\nexport const schemaMetadata = (holder: SchemaObject | ParameterObject): SchemaMetadata => ({\n resource: readResource(extensionOf(holder, EXTENSION_KEYS.resource)),\n resourceRef: readResourceRef(extensionOf(holder, EXTENSION_KEYS.resourceRef)),\n volatile: readVolatile(extensionOf(holder, EXTENSION_KEYS.volatile)),\n scope: readScope(extensionOf(holder, EXTENSION_KEYS.scope)),\n unsupported: readUnsupported(extensionOf(holder, EXTENSION_KEYS.unsupported)),\n})\n\n/** Metadata of a parameter: extensions on the parameter itself win over its schema's. */\nexport const parameterMetadata = (\n document: OpenAPIDocument,\n parameter: ParameterObject,\n): SchemaMetadata => {\n const own = schemaMetadata(parameter)\n const fromSchema = parameter.schema\n ? schemaMetadata(resolveSchema(document, parameter.schema))\n : undefined\n return {\n resource: own.resource ?? fromSchema?.resource,\n resourceRef: own.resourceRef ?? fromSchema?.resourceRef,\n volatile: own.volatile ?? fromSchema?.volatile,\n scope: own.scope ?? fromSchema?.scope,\n unsupported: own.unsupported ?? fromSchema?.unsupported,\n }\n}\n\n/** Lower-cased names of response headers flagged with `x-mockingbird-parity-header: true`. */\nexport const parityHeaders = (document: OpenAPIDocument, response: ResponseObject): string[] => {\n const names: string[] = []\n for (const [name, raw] of Object.entries(response.headers ?? {})) {\n const header = deref<HeaderObject>(document, raw)\n if (extensionOf(header, EXTENSION_KEYS.parityHeader) === true) names.push(name.toLowerCase())\n }\n return names.sort()\n}\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type DecodedBody,\n decodeFormPairs,\n type FormObject,\n readBody,\n} from \"@crvouga/mockingbird-http-codec\"\nimport { listOperations, type OpenAPIDocument, type Operation } from \"@crvouga/mockingbird-openapi\"\nimport { operationMetadata } from \"@crvouga/mockingbird-openapi-metadata\"\nimport {\n clearNamespace,\n migrateCore,\n resolveSqlite,\n type SqliteClient,\n} from \"@crvouga/mockingbird-sqlite\"\nimport { type Context, Hono } from \"hono\"\n\n/** Options every provider constructor accepts. */\nexport type APIOptions = {\n /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */\n sqlite?: SqliteClient\n /** Clock used for `created`-style fields. Default `Date.now`. */\n now?: () => number\n /**\n * Storage namespace for this instance's records. Instances sharing one SQLite\n * client stay isolated when their namespaces differ. Defaults to the service name.\n */\n namespace?: string\n}\n\nexport type OperationContext = {\n request: Request\n url: URL\n /** Path parameters. */\n params: Record<string, string>\n /** Query string decoded with bracket notation (`created[gte]=1` -> `{ created: { gte: \"1\" } }`). */\n query: FormObject\n body: DecodedBody\n /** Shared SQLite client for this service (already migrated). */\n sqlite: SqliteClient\n /** Service namespace used for records / sequences. */\n namespace: string\n operation: Operation\n /** The vendor contract the service was built from. */\n document: OpenAPIDocument\n now: () => number\n}\n\nexport type OperationHandler = (context: OperationContext) => Promise<Response> | Response\n\nexport type OperationHandlers = Record<string, OperationHandler>\n\n/** Identity helper that keeps handler maps type-checked against a fixed set of operation ids. */\nexport const defineOperations = <Id extends string>(\n handlers: Record<Id, OperationHandler>,\n): Record<Id, OperationHandler> => handlers\n\nexport class OperationRegistryError extends Error {\n constructor(readonly problems: string[]) {\n super(`operation registry is inconsistent:\\n${problems.map((p) => ` - ${p}`).join(\"\\n\")}`)\n this.name = \"OperationRegistryError\"\n }\n}\n\n/**\n * Cross-check handlers against the document: every supported operation needs exactly one\n * handler, no handler may target an unknown or unsupported operation, no duplicate ids.\n */\nexport const verifyOperations = (\n document: OpenAPIDocument,\n handlers: OperationHandlers,\n): string[] => {\n const problems: string[] = []\n const operations = listOperations(document)\n const seen = new Set<string>()\n for (const operation of operations) {\n if (seen.has(operation.operationId))\n problems.push(`duplicate operationId ${operation.operationId}`)\n seen.add(operation.operationId)\n const supported = operationMetadata(operation.operation).supported\n const handler = handlers[operation.operationId]\n if (supported && !handler)\n problems.push(`supported operation ${operation.operationId} has no handler`)\n if (!supported && handler)\n problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`)\n }\n for (const id of Object.keys(handlers)) {\n if (!seen.has(id)) problems.push(`handler ${id} has no OpenAPI operation`)\n }\n return problems\n}\n\nexport type ServiceOptions = {\n document: OpenAPIDocument\n handlers: OperationHandlers\n sqlite: SqliteClient\n /** Namespace isolating this service's records and sequences. */\n namespace: string\n now?: (() => number) | undefined\n /** Response for paths/methods outside the contract. */\n notFound: (request: Request) => Response | Promise<Response>\n /** Response for operations declared but marked `supported: false`. Default: `notFound`. */\n unsupported?: (request: Request, operation: Operation) => Response | Promise<Response>\n /** Convert handler exceptions into a provider-shaped response. */\n onError: (error: unknown, request: Request) => Response | Promise<Response>\n /** Runs before every operation; return a Response to short-circuit (e.g. authentication). */\n before?: (context: OperationContext) => Promise<Response | undefined> | Response | undefined\n}\n\nexport type Service = FetchAPI & {\n app: Hono\n sqlite: SqliteClient\n namespace: string\n /** Delete every record and sequence in the service namespace. */\n reset(): Promise<void>\n}\n\nconst honoPath = (template: string) => template.replace(/\\{([^}]+)\\}/g, \":$1\")\n\n/** Static segments before parameters so `/v1/customers/search` beats `/v1/customers/:id`. */\nconst routeOrder = (a: Operation, b: Operation) => {\n const sa = a.path.split(\"/\")\n const sb = b.path.split(\"/\")\n for (let i = 0; i < Math.max(sa.length, sb.length); i++) {\n const x = sa[i] ?? \"\"\n const y = sb[i] ?? \"\"\n const px = x.startsWith(\"{\")\n const py = y.startsWith(\"{\")\n if (px !== py) return px ? 1 : -1\n if (x !== y) return x < y ? -1 : 1\n }\n return 0\n}\n\nconst queryOf = (url: URL): FormObject => decodeFormPairs(url.searchParams.entries())\n\n/**\n * Resolve optional `sqlite`, run core migrations, and return the ready client.\n * Call this from every provider constructor before building state.\n */\nexport const bootSqlite = (sqlite?: SqliteClient): SqliteClient => {\n const client = resolveSqlite(sqlite)\n migrateCore(client)\n return client\n}\n\n/** Build a Fetch-native service whose routes are exactly the document's operations. */\nexport const createService = (options: ServiceOptions): Service => {\n const problems = verifyOperations(options.document, options.handlers)\n if (problems.length > 0) throw new OperationRegistryError(problems)\n migrateCore(options.sqlite)\n const now = options.now ?? (() => Date.now())\n const app = new Hono()\n app.notFound((c) => options.notFound(c.req.raw))\n app.onError((error, c) => options.onError(error, c.req.raw))\n\n const operations = [...listOperations(options.document)].sort(routeOrder)\n for (const operation of operations) {\n const metadata = operationMetadata(operation.operation)\n const handler = options.handlers[operation.operationId]\n const route = async (c: Context) => {\n const request = c.req.raw\n if (!metadata.supported || !handler) {\n return options.unsupported\n ? options.unsupported(request, operation)\n : options.notFound(request)\n }\n const url = new URL(request.url)\n const context: OperationContext = {\n request,\n url,\n params: c.req.param(),\n query: queryOf(url),\n body: await readBody(request),\n sqlite: options.sqlite,\n namespace: options.namespace,\n operation,\n document: options.document,\n now,\n }\n const short = await options.before?.(context)\n if (short) return short\n return handler(context)\n }\n app.on(operation.method.toUpperCase(), honoPath(operation.path), route)\n }\n\n return {\n app,\n sqlite: options.sqlite,\n namespace: options.namespace,\n fetch: async (request) => app.fetch(request),\n reset: async () => {\n clearNamespace(options.sqlite, options.namespace)\n },\n }\n}\n", "import { Timeline } from \"@crvouga/mockingbird-core\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\n/**\n * A point-in-time copy of everything a service namespace holds.\n *\n * All service state lives in the two core tables keyed by namespace, so a snapshot\n * is generic: any service gets per-test rollback without knowing its own schema.\n * Restoring is much cheaper than rebuilding a namespace from a corpus.\n */\nexport type NamespaceSnapshot = {\n namespace: string\n records: { collection: string; id: string; seq: number; value: string }[]\n sequences: { name: string; kind: string; value: number }[]\n}\n\n/**\n * @deprecated Low-level Timeline payload capture retained for API compatibility. Provider code\n * must use the runtime Timeline or `withNamespaceRollback`.\n */\nexport const snapshotNamespace = (sqlite: SqliteClient, namespace: string): NamespaceSnapshot => ({\n namespace,\n records: sqlite\n .prepare(\n \"SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq\",\n )\n .all<{ collection: string; id: string; seq: number; value: string }>(namespace),\n sequences: sqlite\n .prepare(\n \"SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind\",\n )\n .all<{ name: string; kind: string; value: number }>(namespace),\n})\n\n/**\n * Replace a namespace's contents with `snapshot`. The namespace is emptied first,\n * so restoring is an assignment, not a merge \u2014 records created since the snapshot\n * are gone afterwards.\n *\n * @deprecated Low-level Timeline payload restore retained for API compatibility. Provider code\n * must use the runtime Timeline or `withNamespaceRollback`.\n */\nexport const restoreNamespace = (\n sqlite: SqliteClient,\n namespace: string,\n snapshot: NamespaceSnapshot,\n): void => {\n sqlite.transaction(() => {\n sqlite.prepare(\"DELETE FROM mockingbird_records WHERE namespace = ?\").run(namespace)\n sqlite.prepare(\"DELETE FROM mockingbird_sequences WHERE namespace = ?\").run(namespace)\n const record = sqlite.prepare(\n \"INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)\",\n )\n for (const row of snapshot.records) {\n record.run(namespace, row.collection, row.id, row.seq, row.value)\n }\n const sequence = sqlite.prepare(\n \"INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)\",\n )\n for (const row of snapshot.sequences) {\n sequence.run(namespace, row.name, row.kind, row.value)\n }\n })\n}\n\n/**\n * Execute asynchronous service work atomically using the canonical Timeline rollback primitive.\n * This is the prescribed escape hatch when the SQLite adapter cannot hold a transaction across\n * `await`; service code should not coordinate raw namespace snapshots itself.\n */\nexport const withNamespaceRollback = async <T>(\n sqlite: SqliteClient,\n namespace: string,\n run: () => Promise<T>,\n): Promise<T> => {\n const rollback = new Timeline<NamespaceSnapshot>({ maxCheckpoints: 1 })\n const before = rollback.commit(snapshotNamespace(sqlite, namespace))\n try {\n return await run()\n } catch (error) {\n restoreNamespace(sqlite, namespace, before.value)\n throw error\n }\n}\n", "/**\n * Set by `scripts/bundle-service.ts` when a service is bundled, and rewritten to the\n * released version when it is published. Undefined when running from source.\n */\ndeclare const __MOCKINGBIRD_PACKAGE_VERSION__: string | undefined\n\n/** Placeholder a bundle carries until `release:publish` writes the real version over it. */\nexport const UNRELEASED_VERSION = \"0.0.0-development\"\n\n/** The published version of the service package this code is bundled into. */\nexport const PACKAGE_VERSION: string =\n typeof __MOCKINGBIRD_PACKAGE_VERSION__ === \"string\"\n ? __MOCKINGBIRD_PACKAGE_VERSION__\n : UNRELEASED_VERSION\n", "/**\n * HMAC and encoding primitives for vendor webhook signatures, over WebCrypto so they run\n * wherever the mocks do (Node, Bun, workers).\n */\n\nexport type HmacAlgorithm = \"SHA-1\" | \"SHA-256\" | \"SHA-512\"\nexport type ByteEncoding = \"hex\" | \"base64\"\n\nconst encoder = new TextEncoder()\n\nexport const toBase64 = (bytes: ArrayBuffer | Uint8Array): string => {\n let binary = \"\"\n for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {\n binary += String.fromCharCode(byte)\n }\n return btoa(binary)\n}\n\nexport const fromBase64 = (value: string): Uint8Array =>\n Uint8Array.from(atob(value), (char) => char.charCodeAt(0))\n\nexport const toHex = (bytes: ArrayBuffer | Uint8Array): string =>\n [...(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes))]\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\")\n\nconst keyBytes = (key: string | Uint8Array): Uint8Array =>\n typeof key === \"string\" ? encoder.encode(key) : key\n\n/** HMAC of `message` under `key` (a UTF-8 string or raw bytes), encoded as hex or base64. */\nexport const hmac = async (\n algorithm: HmacAlgorithm,\n key: string | Uint8Array,\n message: string | Uint8Array,\n encoding: ByteEncoding = \"hex\",\n): Promise<string> => {\n const imported = await crypto.subtle.importKey(\n \"raw\",\n keyBytes(key) as BufferSource,\n { name: \"HMAC\", hash: algorithm },\n false,\n [\"sign\"],\n )\n const signed = await crypto.subtle.sign(\n \"HMAC\",\n imported,\n (typeof message === \"string\" ? encoder.encode(message) : message) as BufferSource,\n )\n return encoding === \"hex\" ? toHex(signed) : toBase64(signed)\n}\n\n/** SHA digest of `input`, hex-encoded. */\nexport const sha = async (\n algorithm: \"SHA-1\" | \"SHA-256\" | \"SHA-512\",\n input: string | Uint8Array,\n): Promise<string> =>\n toHex(\n await crypto.subtle.digest(\n algorithm,\n (typeof input === \"string\" ? encoder.encode(input) : input) as BufferSource,\n ),\n )\n\n/**\n * The raw key of a Svix-style secret: `whsec_<base64>` (Svix, Resend, Junction) or\n * `fwhsec_<base64>` (Flex). A bare base64 secret is accepted too.\n */\nexport const svixSecretBytes = (secret: string): Uint8Array => {\n const raw = secret.replace(/^f?whsec_/, \"\")\n try {\n return fromBase64(raw)\n } catch {\n throw new TypeError(\"webhook secret must be whsec_<base64> (as Svix issues it)\")\n }\n}\n\n/** `v1,<base64 HMAC-SHA256>` over `\"<id>.<timestamp>.<body>\"`, as Svix signs. */\nexport const signSvix = async (\n secret: string,\n messageId: string,\n timestampSeconds: number,\n body: string,\n): Promise<string> =>\n `v1,${await hmac(\"SHA-256\", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, \"base64\")}`\n\n/** `t=<unix>,v1=<hex HMAC-SHA256(secret, \"<t>.<body>\")>`, as Stripe (and Persona) sign. */\nexport const signTimestamped = async (\n secret: string,\n timestampSeconds: number,\n body: string,\n): Promise<string> =>\n `t=${timestampSeconds},v1=${await hmac(\"SHA-256\", secret, `${timestampSeconds}.${body}`, \"hex\")}`\n\n/**\n * Twilio's `X-Twilio-Signature`: base64 HMAC-SHA1 of the full URL followed by every form\n * parameter as `key + value`, keys sorted. Sign against the public URL the app is\n * configured with, not the address the request is actually posted to.\n */\nexport const signTwilio = async (\n authToken: string,\n url: string,\n params: Record<string, string>,\n): Promise<string> => {\n const payload =\n url +\n Object.keys(params)\n .sort()\n .map((key) => `${key}${params[key]}`)\n .join(\"\")\n return hmac(\"SHA-1\", authToken, payload, \"base64\")\n}\n\n/** Constant-time string comparison, so a verifier in a test double does not leak timing. */\nexport const timingSafeEqual = (a: string, b: string): boolean => {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n", "import type { AdminRoutes } from \"./control.js\"\nimport { signSvix, signTimestamped, signTwilio } from \"./signing.js\"\n\n/**\n * Outbound webhooks, shared by every service that has them.\n *\n * A service publishes a message (the exact bytes the vendor would send); the hub fans it out\n * to every matching endpoint, signs each delivery with the vendor's scheme, retries on the\n * vendor's schedule, and keeps a record a suite can read, replay or flush through\n * `/__admin/webhooks*`. Signature timestamps always use the wall clock, never the mock\n * clock: receivers check them against their own time, and an advanced mock clock would\n * otherwise fail every delivery.\n */\n\n/** What a signer sees for one delivery attempt. */\nexport type SignInput = {\n messageId: string\n /** Exact bytes about to be sent. */\n body: string\n /** Wall-clock unix seconds of this attempt. */\n timestampSeconds: number\n /** Where the delivery is posted. */\n url: string\n /** The endpoint's secret, if it has one. */\n secret: string | undefined\n /** The endpoint's `signUrl` (the public URL the receiver verifies against), else `url`. */\n signUrl: string\n /** Form parameters, when the body is form-encoded (Twilio signs these, not the body). */\n form: Record<string, string> | undefined\n /** Stable event type and metadata captured with the message; avoids signer side-channel state. */\n type: string\n tags: Readonly<Record<string, string>>\n}\n\n/** Headers to add to one delivery. */\nexport type WebhookSigner = (\n input: SignInput,\n) => Record<string, string> | Promise<Record<string, string>>\n\n/** Named signers for the vendor schemes the catalog needs. */\nexport const signers = {\n /** No signature. */\n none: (): WebhookSigner => () => ({}),\n /** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */\n svix:\n (options: { prefix?: \"svix\" | \"webhook\" } = {}): WebhookSigner =>\n async ({ messageId, body, timestampSeconds, secret }) => {\n if (!secret) return {}\n const prefix = options.prefix ?? \"svix\"\n return {\n [`${prefix}-id`]: messageId,\n [`${prefix}-timestamp`]: String(timestampSeconds),\n [`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body),\n }\n },\n /** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, \"t.body\")>`: Stripe, Persona, Fullscript. */\n timestamped:\n (header = \"Stripe-Signature\"): WebhookSigner =>\n async ({ body, timestampSeconds, secret }) =>\n secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},\n /** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */\n twilio:\n (): WebhookSigner =>\n async ({ signUrl, form, secret }) =>\n secret ? { \"X-Twilio-Signature\": await signTwilio(secret, signUrl, form ?? {}) } : {},\n /** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */\n header:\n (header: string, format: (secret: string) => string = (s) => s): WebhookSigner =>\n ({ secret }) =>\n secret ? { [header]: format(secret) } : {},\n /** Anything else: the service computes the headers itself. */\n custom: (sign: WebhookSigner): WebhookSigner => sign,\n}\n\nexport type WebhookEndpoint = {\n /** Stable id; generated when omitted. */\n id?: string\n url: string\n secret?: string\n /** Event types to deliver; omit or include `\"*\"` for every type. */\n events?: string[]\n /** Deliver only messages whose tags include all of these (e.g. `{ account: \"mso\" }`). */\n tags?: Record<string, string>\n /** The public URL the receiver verifies signatures against (Twilio), when it differs. */\n signUrl?: string\n headers?: Record<string, string>\n}\n\nexport type WebhookMessage = {\n id: string\n namespace: string\n type: string\n body: string\n contentType: string\n tags: Record<string, string>\n headers?: Record<string, string>\n /** Wall-clock ISO-8601 time of publication. */\n publishedAt: string\n}\n\nexport type WebhookAttempt = {\n attempt: number\n at: string\n status: number | null\n error: string | null\n durationMs: number\n /** Exact receiver response body, when one was returned. */\n responseBody?: string | null\n}\n\nexport type WebhookDelivery = {\n id: string\n messageId: string\n namespace: string\n type: string\n endpointId: string\n url: string\n state: \"pending\" | \"delivered\" | \"failed\" | \"dropped\"\n attempts: WebhookAttempt[]\n}\n\n/** A delivery-level fault: what happens to the next `count` messages in a namespace. */\nexport type WebhookFault = {\n mode: \"duplicate\" | \"reorder\" | \"drop\"\n /** Messages affected; default 1. */\n count?: number\n}\n\nexport type PublishInput = {\n namespace: string\n type: string\n /** Exact body; objects are JSON-encoded. */\n body: string | Record<string, unknown> | unknown[]\n /** Default `application/json`, or form-encoded when `form` is given. */\n contentType?: string\n /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */\n form?: Record<string, string>\n tags?: Record<string, string>\n /** Message-specific delivery headers, captured as part of durable message state. */\n headers?: Record<string, string>\n /** Message id; generated when omitted. */\n id?: string\n}\n\nexport type WebhookHubOptions = {\n signer: WebhookSigner\n /**\n * Delay before each attempt, in ms; the first entry delays the first attempt. Default:\n * immediately, then 5 s, 5 min, 30 min, 2 h.\n */\n retryDelaysMs?: readonly number[]\n /** Abort an attempt after this long. Default 15 s. */\n timeoutMs?: number\n /** Which receiver statuses count as delivered. Default 2xx. */\n delivered?: (status: number) => boolean\n /** Endpoints every namespace delivers to (from `--webhook-url`). */\n endpoints?: WebhookEndpoint[]\n fetch?: (request: Request) => Promise<Response>\n /** Called in-process for every published message, delivered or not. */\n onMessage?: (message: WebhookMessage) => void\n /** Messages kept per namespace for `GET /__admin/webhooks/events`. Default 500. */\n keep?: number\n /** Injectable wall clock for signatures and attempt records. */\n now?: () => number\n /** Injectable deterministic identifier source. Receives `\"msg_\"` or `\"dlv_\"`. */\n id?: (prefix: string) => string\n /** Injectable scheduler used by timeouts and retries. */\n schedule?: (callback: () => void, delayMs: number) => unknown\n cancel?: (handle: unknown) => void\n}\n\nexport type WebhookHub = {\n publish(input: PublishInput): WebhookMessage\n /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */\n setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[]\n /** The endpoints a namespace delivers to: its own, plus the global ones. */\n endpoints(namespace: string): WebhookEndpoint[]\n messages(namespace?: string): WebhookMessage[]\n deliveries(namespace?: string): WebhookDelivery[]\n replay(deliveryId: string): Promise<WebhookDelivery | undefined>\n /** Run every pending retry (and release held reordered messages) now. */\n flush(): Promise<void>\n /** Resolve once nothing is in flight. */\n idle(): Promise<void>\n fault(namespace: string, fault: WebhookFault): void\n clear(namespace?: string): void\n}\n\nconst DEFAULT_DELAYS = [0, 5_000, 300_000, 1_800_000, 7_200_000] as const\n\nconst unref = (timer: unknown) => {\n ;(timer as { unref?: () => void }).unref?.()\n}\n\nconst randomId = (prefix: string) =>\n `${prefix}${crypto.randomUUID().replace(/-/g, \"\").slice(0, 24)}`\n\nconst matchesEndpoint = (endpoint: WebhookEndpoint, message: WebhookMessage): boolean => {\n const events = endpoint.events ?? [\"*\"]\n if (!events.includes(\"*\") && !events.includes(message.type)) return false\n for (const [key, value] of Object.entries(endpoint.tags ?? {})) {\n if (message.tags[key] !== value) return false\n }\n return true\n}\n\nexport const createWebhookHub = (options: WebhookHubOptions): WebhookHub => {\n const delays = options.retryDelaysMs ?? DEFAULT_DELAYS\n const timeoutMs = options.timeoutMs ?? 15_000\n const delivered = options.delivered ?? ((status: number) => status >= 200 && status < 300)\n const send = options.fetch ?? ((request: Request) => fetch(request))\n const keep = options.keep ?? 500\n const now = options.now ?? Date.now\n const id = options.id ?? randomId\n const scheduleTimer =\n options.schedule ?? ((callback: () => void, delayMs: number) => setTimeout(callback, delayMs))\n const cancel =\n options.cancel ?? ((handle: unknown) => clearTimeout(handle as ReturnType<typeof setTimeout>))\n const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }))\n const own = new Map<string, WebhookEndpoint[]>()\n const messages: WebhookMessage[] = []\n const deliveries = new Map<string, WebhookDelivery>()\n const pending = new Map<string, unknown | undefined>()\n const payloads = new Map<string, { message: WebhookMessage; endpoint: WebhookEndpoint }>()\n const faults = new Map<string, { mode: WebhookFault[\"mode\"]; remaining: number }[]>()\n const held = new Map<string, WebhookMessage[]>()\n const inFlight = new Set<Promise<void>>()\n\n const track = (work: Promise<void>) => {\n inFlight.add(work)\n void work.finally(() => inFlight.delete(work))\n }\n\n const attempt = async (delivery: WebhookDelivery): Promise<boolean> => {\n const entry = payloads.get(delivery.id)\n if (!entry) return false\n const { message, endpoint } = entry\n const timestampSeconds = Math.floor(now() / 1000)\n const started = now()\n const record: WebhookAttempt = {\n attempt: delivery.attempts.length + 1,\n at: new Date(started).toISOString(),\n status: null,\n error: null,\n durationMs: 0,\n responseBody: null,\n }\n const controller = new AbortController()\n const timer = scheduleTimer(() => controller.abort(), timeoutMs)\n try {\n const signed = await options.signer({\n messageId: message.id,\n body: message.body,\n timestampSeconds,\n url: endpoint.url,\n secret: endpoint.secret,\n signUrl: endpoint.signUrl ?? endpoint.url,\n form: message.contentType.startsWith(\"application/x-www-form-urlencoded\")\n ? Object.fromEntries(new URLSearchParams(message.body))\n : undefined,\n type: message.type,\n tags: message.tags,\n })\n const response = await send(\n new Request(endpoint.url, {\n method: \"POST\",\n headers: {\n \"content-type\": message.contentType,\n ...endpoint.headers,\n ...message.headers,\n ...signed,\n },\n body: message.body,\n signal: controller.signal,\n }),\n )\n record.status = response.status\n record.responseBody = await response.text()\n } catch (error) {\n record.error = controller.signal.aborted\n ? `timed out after ${timeoutMs}ms`\n : error instanceof Error\n ? error.message\n : String(error)\n } finally {\n cancel(timer)\n record.durationMs = now() - started\n delivery.attempts.push(record)\n }\n return record.status !== null && delivered(record.status)\n }\n\n const schedule = (delivery: WebhookDelivery) => {\n const index = delivery.attempts.length\n if (index >= delays.length) {\n delivery.state = \"failed\"\n pending.delete(delivery.id)\n return\n }\n const run = () => {\n pending.delete(delivery.id)\n track(\n attempt(delivery).then((ok) => {\n if (ok) delivery.state = \"delivered\"\n else schedule(delivery)\n }),\n )\n }\n const delay = delays[index] ?? 0\n if (delay <= 0) {\n pending.set(delivery.id, undefined)\n run()\n return\n }\n const timer = scheduleTimer(run, delay)\n unref(timer)\n pending.set(delivery.id, timer)\n }\n\n const endpointsFor = (namespace: string) => [...(own.get(namespace) ?? []), ...global]\n\n const fanOut = (message: WebhookMessage, state: WebhookDelivery[\"state\"] = \"pending\") => {\n for (const endpoint of endpointsFor(message.namespace)) {\n if (!matchesEndpoint(endpoint, message)) continue\n const delivery: WebhookDelivery = {\n id: id(\"dlv_\"),\n messageId: message.id,\n namespace: message.namespace,\n type: message.type,\n endpointId: endpoint.id ?? \"we_unknown\",\n url: endpoint.url,\n state,\n attempts: [],\n }\n deliveries.set(delivery.id, delivery)\n payloads.set(delivery.id, { message, endpoint })\n if (state === \"pending\") schedule(delivery)\n }\n }\n\n const takeFault = (namespace: string): WebhookFault[\"mode\"] | undefined => {\n const queue = faults.get(namespace)\n const head = queue?.[0]\n if (!queue || !head) return undefined\n head.remaining--\n if (head.remaining <= 0) queue.shift()\n return head.mode\n }\n\n const releaseHeld = (namespace: string) => {\n const waiting = held.get(namespace)\n if (!waiting) return\n held.delete(namespace)\n for (const message of waiting) fanOut(message)\n }\n\n const hub: WebhookHub = {\n publish(input) {\n const contentType =\n input.contentType ?? (input.form ? \"application/x-www-form-urlencoded\" : \"application/json\")\n const body =\n typeof input.body === \"string\"\n ? input.body\n : input.form\n ? new URLSearchParams(input.form).toString()\n : JSON.stringify(input.body)\n const message: WebhookMessage = {\n id: input.id ?? id(\"msg_\"),\n namespace: input.namespace,\n type: input.type,\n body,\n contentType,\n tags: input.tags ?? {},\n headers: input.headers ?? {},\n publishedAt: new Date(now()).toISOString(),\n }\n messages.push(message)\n const ofNamespace = messages.filter((m) => m.namespace === message.namespace)\n const oldest = ofNamespace[0]\n if (ofNamespace.length > keep && oldest) messages.splice(messages.indexOf(oldest), 1)\n options.onMessage?.(message)\n const fault = takeFault(message.namespace)\n if (fault === \"drop\") {\n fanOut(message, \"dropped\")\n return message\n }\n if (fault === \"reorder\") {\n // Held until the next message goes out, so the receiver sees them swapped.\n held.set(message.namespace, [...(held.get(message.namespace) ?? []), message])\n return message\n }\n fanOut(message)\n if (fault === \"duplicate\") fanOut(message)\n releaseHeld(message.namespace)\n return message\n },\n setEndpoints(namespace, endpoints) {\n const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }))\n own.set(namespace, withIds)\n return withIds\n },\n endpoints: endpointsFor,\n messages: (namespace) =>\n namespace === undefined ? [...messages] : messages.filter((m) => m.namespace === namespace),\n deliveries: (namespace) =>\n [...deliveries.values()].filter((d) => namespace === undefined || d.namespace === namespace),\n async replay(id) {\n const delivery = deliveries.get(id)\n if (!delivery) return undefined\n const ok = await attempt(delivery)\n if (ok) delivery.state = \"delivered\"\n return delivery\n },\n async flush() {\n for (const namespace of [...held.keys()]) releaseHeld(namespace)\n const waiting = [...pending.entries()]\n for (const [id, timer] of waiting) {\n if (timer === undefined) continue\n cancel(timer)\n pending.delete(id)\n const delivery = deliveries.get(id)\n if (!delivery) continue\n track(\n attempt(delivery).then((ok) => {\n if (ok) delivery.state = \"delivered\"\n else schedule(delivery)\n }),\n )\n }\n await hub.idle()\n },\n async idle() {\n while (inFlight.size > 0) await Promise.allSettled([...inFlight])\n },\n fault(namespace, fault) {\n const queue = faults.get(namespace) ?? []\n queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) })\n faults.set(namespace, queue)\n },\n clear(namespace) {\n for (const [id, delivery] of deliveries) {\n if (namespace !== undefined && delivery.namespace !== namespace) continue\n const timer = pending.get(id)\n if (timer !== undefined) cancel(timer)\n pending.delete(id)\n deliveries.delete(id)\n payloads.delete(id)\n }\n for (let i = messages.length - 1; i >= 0; i--) {\n if (namespace === undefined || messages[i]?.namespace === namespace) messages.splice(i, 1)\n }\n if (namespace === undefined) {\n held.clear()\n faults.clear()\n own.clear()\n } else {\n held.delete(namespace)\n faults.delete(namespace)\n own.delete(namespace)\n }\n },\n }\n return hub\n}\n\nconst json = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\n\nconst adminError = (status: number, message: string): Response =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst parseEndpoint = (value: unknown): WebhookEndpoint | string => {\n if (!isRecord(value) || typeof value.url !== \"string\") return \"each endpoint needs a url\"\n try {\n new URL(value.url)\n } catch {\n return `not a URL: ${value.url}`\n }\n const endpoint: WebhookEndpoint = { url: value.url }\n if (typeof value.id === \"string\") endpoint.id = value.id\n if (typeof value.secret === \"string\") endpoint.secret = value.secret\n if (typeof value.signUrl === \"string\") endpoint.signUrl = value.signUrl\n const events = value.events ?? value.enabledEvents\n if (Array.isArray(events)) endpoint.events = events.map(String)\n if (isRecord(value.tags)) {\n endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]))\n }\n if (typeof value.account === \"string\")\n endpoint.tags = { ...endpoint.tags, account: value.account }\n if (isRecord(value.headers)) {\n endpoint.headers = Object.fromEntries(\n Object.entries(value.headers).map(([k, v]) => [k, String(v)]),\n )\n }\n return endpoint\n}\n\n/**\n * The standard webhook admin routes, for a runtime that owns `hub`:\n *\n * - `GET /webhooks` deliveries, `GET /webhooks/events` published messages (with bodies:\n * they are the mock's own output), `POST /webhooks/:id/replay`, `POST /webhooks/flush`\n * - `GET|PUT|DELETE /webhook-endpoints` per namespace\n * - `POST /webhooks/faults {mode: duplicate|reorder|drop, count?}`\n */\nexport const webhookAdminRoutes = (hub: WebhookHub): AdminRoutes => ({\n \"GET /webhooks\": ({ url, namespace }) =>\n json(200, {\n deliveries: hub\n .deliveries(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace)\n .filter((d) => {\n const type = url.searchParams.get(\"type\")\n return type === null || d.type === type\n }),\n }),\n \"GET /webhooks/events\": ({ url, namespace }) => {\n const type = url.searchParams.get(\"type\")\n return json(200, {\n events: hub\n .messages(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace)\n .filter((m) => type === null || m.type === type)\n .map((m) => ({ ...m, payload: parsePayload(m) })),\n })\n },\n \"POST /webhooks/:id/replay\": async ({ params }) => {\n const replayed = await hub.replay(params.id as string)\n return replayed ? json(200, replayed) : adminError(404, `no delivery ${params.id}`)\n },\n \"POST /webhooks/flush\": async () => {\n await hub.flush()\n return json(200, { status: \"ok\" })\n },\n \"POST /webhooks/faults\": ({ body, namespace }) => {\n if (!isRecord(body) || ![\"duplicate\", \"reorder\", \"drop\"].includes(String(body.mode))) {\n return adminError(400, \"mode must be duplicate, reorder or drop\")\n }\n const fault: WebhookFault = { mode: body.mode as WebhookFault[\"mode\"] }\n if (typeof body.count === \"number\") fault.count = body.count\n hub.fault(namespace, fault)\n return json(201, { namespace, ...fault })\n },\n \"GET /webhook-endpoints\": ({ namespace }) =>\n json(200, {\n endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({\n ...rest,\n secret: secret ? \"(set)\" : null,\n })),\n }),\n \"PUT /webhook-endpoints\": ({ body, namespace }) => {\n const list = Array.isArray(body) ? body : isRecord(body) ? body.endpoints : undefined\n if (!Array.isArray(list)) return adminError(400, \"expected [{url, secret?, events?}]\")\n const parsed: WebhookEndpoint[] = []\n for (const each of list) {\n const endpoint = parseEndpoint(each)\n if (typeof endpoint === \"string\") return adminError(400, endpoint)\n parsed.push(endpoint)\n }\n const set = hub.setEndpoints(namespace, parsed)\n return json(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? \"(set)\" : null })) })\n },\n \"DELETE /webhook-endpoints\": ({ namespace }) => {\n hub.setEndpoints(namespace, [])\n return json(200, { status: \"ok\" })\n },\n})\n\nconst parsePayload = (message: WebhookMessage): unknown => {\n if (message.contentType.startsWith(\"application/json\")) {\n try {\n return JSON.parse(message.body)\n } catch {\n return message.body\n }\n }\n if (message.contentType.startsWith(\"application/x-www-form-urlencoded\")) {\n return Object.fromEntries(new URLSearchParams(message.body))\n }\n return message.body\n}\n", "import { type Checkpoint, type FetchAPI, Timeline } from \"@crvouga/mockingbird-core\"\nimport { listOperations, type OpenAPIDocument } from \"@crvouga/mockingbird-openapi\"\nimport { clearNamespace, type SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { type Clock, createClock } from \"./clock.js\"\nimport { type AdminRoutes, createControlPlane, NAMESPACE_HEADER } from \"./control.js\"\nimport { type CredentialRegistry, createCredentialRegistry, maskCredential } from \"./credentials.js\"\nimport {\n createFaultRegistry,\n type FaultHit,\n type FaultPreset,\n type FaultRegistry,\n type FaultRule,\n} from \"./faults.js\"\nimport { createJournal, DEFAULT_JOURNAL_SIZE, type Journal, responseNotes } from \"./journal.js\"\nimport { createMetrics, type Metrics, type RequestLog } from \"./metrics.js\"\nimport { createRng, type Rng, seedFrom } from \"./rng.js\"\nimport { bootSqlite } from \"./service.js\"\nimport { type NamespaceSnapshot, restoreNamespace, snapshotNamespace } from \"./snapshot.js\"\nimport { PACKAGE_VERSION } from \"./version.js\"\nimport { type WebhookHub, webhookAdminRoutes } from \"./webhooks.js\"\n\n/**\n * Stamped on every response the runtime returns \u2014 vendor, fault, admin and health alike \u2014\n * as `<service>@<version>; ns=<namespace>`, so a consumer can tell the mock from the vendor.\n */\nexport const MOCKINGBIRD_HEADER = \"x-mockingbird\"\n/** Selects a named copy-on-write history branch. `main` is the compatibility default. */\nexport const BRANCH_HEADER = \"x-mockingbird-branch\"\n/** Reads a historical checkpoint. With a branch header, initializes that branch from it. */\nexport const AT_HEADER = \"x-mockingbird-at\"\n/** Identifies the resulting checkpoint on successful mutations. */\nexport const CHECKPOINT_HEADER = \"x-mockingbird-checkpoint\"\n\n/** What the runtime needs from a service: a Fetch handler it can reset. */\nexport type ServiceInstance = FetchAPI & { reset(): Promise<void> }\n\n/** Everything an instance shares with the runtime that owns it. */\nexport type InstanceContext = {\n /** Storage namespace for this instance's records. */\n namespace: string\n /** The public namespace name a request selects it by. */\n publicNamespace: string\n sqlite: SqliteClient\n clock: Clock\n rng: Rng\n}\n\nexport type RuntimeOptions<T extends ServiceInstance> = {\n /** Service name, e.g. `\"junction\"`. Also the default namespace's storage key. */\n name: string\n /** Build the instance backing one namespace. Called once per namespace, on first use. */\n create: (context: InstanceContext) => T\n /** The vendor contract, used to name each request's operation in logs, metrics and faults. */\n document?: OpenAPIDocument\n /** Shared by every namespace. Defaults to a fresh `@crvouga/mockingbird-service-sqlite`. */\n sqlite?: SqliteClient\n /** Defaults to a live clock over `Date.now`. */\n clock?: Clock\n /** Seeds every random choice the runtime makes (fault rates). Default `0`. */\n seed?: number | string\n /** Extra `GET /health` fields, such as the loaded corpus version. */\n describe?: () => Record<string, unknown>\n /** Service-specific admin routes, given the runtime so they can reach any namespace. */\n admin?: (runtime: ServiceRuntime<T>) => AdminRoutes\n /** Require this value in `x-mockingbird-admin-key` on `/__admin/*`. Omit to leave admin open. */\n adminKey?: string\n /** Structured request log sink, called once per request. */\n onLog?: (entry: RequestLog) => void\n /** Requests each namespace's journal keeps (`GET /__admin/requests`). Default 1000; 0 turns it off. */\n journalSize?: number\n /** Reported in the `x-mockingbird` header. Default: the bundled package's version. */\n version?: string\n /**\n * The vendor credential a request carries (API key, token, account SID, AWS access key\n * id), for SDKs that cannot send `x-mockingbird-namespace`: a suite maps credentials to\n * namespaces with `PUT /__admin/credentials`. See `bearerToken`, `basicAuth`,\n * `sigV4AccessKeyId`.\n */\n credential?: (request: Request) => string | undefined\n /** Named faults, switched on with `POST /__admin/faults {\"preset\": \"<name>\"}`. */\n presets?: Record<string, FaultPreset>\n /** Outbound webhooks; adds the `/__admin/webhooks*` routes and clears on reset. */\n webhooks?: WebhookHub\n /** Retained time-travel checkpoints per namespace. Default 1,000. */\n maxCheckpoints?: number\n /** Injectable process IO used for observability and delays; logical service time uses `clock`. */\n io?: Partial<RuntimeIO>\n}\n\nexport type RuntimeIO = {\n wallNow(): number\n monotonicNow(): number\n sleep(ms: number): Promise<void>\n}\n\nexport type ServiceTimelineState = Readonly<{\n snapshot: NamespaceSnapshot\n clock: Readonly<ReturnType<Clock[\"state\"]>>\n rngState: number\n}>\n\nexport type ServiceCheckpoint = Checkpoint<ServiceTimelineState>\n\nexport type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {\n readonly name: string\n readonly sqlite: SqliteClient\n readonly clock: Clock\n readonly faults: FaultRegistry\n readonly metrics: Metrics\n readonly journal: Journal\n readonly rng: Rng\n readonly credentials: CredentialRegistry\n /** The webhook hub, when the service has outbound webhooks. */\n readonly webhooks: WebhookHub | undefined\n /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */\n applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[]\n /** The instance behind `namespace` (the default one when omitted), created on first use. */\n instance(namespace?: string): T\n /** Public names of every namespace created so far. */\n namespaces(): string[]\n /** Reset one namespace, or every namespace with `\"*\"`. */\n reset(namespace?: string): Promise<void>\n snapshot(namespace?: string): NamespaceSnapshot\n restore(snapshot: NamespaceSnapshot, namespace?: string): void\n /** Capture the current branch. Mutating HTTP calls do this automatically. */\n checkpoint(namespace?: string, branch?: string): ServiceCheckpoint\n /** Create an isolated branch, optionally from a historical checkpoint. */\n branch(name: string, options?: { namespace?: string; at?: string }): ServiceCheckpoint\n /** Restore a branch, clock, and PRNG to a checkpoint. */\n checkout(checkpoint: string, options?: { namespace?: string; branch?: string }): void\n /** Inspect the retained history for a namespace. */\n timeline(namespace?: string): Timeline<ServiceTimelineState>\n}\n\n/** The namespace used when a request names none. */\nexport const DEFAULT_NAMESPACE = \"default\"\n\nconst NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/\n\n/** `/ns/<namespace>/\u2026`: the namespace carrier for SDKs that only take a base URL. */\nconst PATH_PREFIX = /^\\/ns\\/([^/]+)(\\/.*)?$/\nconst BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/\nconst MUTATING_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"])\n\nconst effects = new WeakMap<Request, FaultHit[\"effect\"][]>()\n\n/**\n * Merge two sorted snapshot row arrays, retaining byte-identical old objects. Unlike the previous\n * Map/string-key implementation this is allocation-free apart from the result array and O(n).\n */\nconst reuseSorted = <T>(\n fresh: T[],\n previous: T[] | undefined,\n compare: (left: T, right: T) => number,\n equal: (left: T, right: T) => boolean,\n): T[] => {\n if (!previous || previous.length === 0) return fresh.map((row) => Object.freeze(row))\n const result = new Array<T>(fresh.length)\n let unchanged = fresh.length === previous.length\n let oldIndex = 0\n for (let index = 0; index < fresh.length; index++) {\n const row = fresh[index] as T\n while (oldIndex < previous.length && compare(previous[oldIndex] as T, row) < 0) {\n oldIndex++\n }\n const old = previous[oldIndex]\n result[index] =\n old !== undefined && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row)\n if (result[index] !== previous[index]) unchanged = false\n }\n return unchanged ? previous : result\n}\n\n/**\n * The fault effects (`{\"effect\": \"created_but_500\"}` rules) that fired for this request, in\n * rule order. Handlers read this to switch on a named vendor misbehaviour.\n */\nexport const faultEffects = (\n request: Request,\n): { name: string; params: Record<string, unknown> }[] =>\n (effects.get(request) ?? []).filter((e): e is NonNullable<typeof e> => e !== undefined)\n\n/** Whether the named effect fired for this request; its params when it did. */\nexport const faultEffect = (request: Request, name: string): Record<string, unknown> | undefined =>\n faultEffects(request).find((e) => e.name === name)?.params\n\n/**\n * Thrown by an in-process `runtime.fetch` when a `drop` fault fires: the same thing a real\n * `fetch` does when the connection dies mid-request. A served mock destroys the socket.\n */\nexport class DroppedConnectionError extends TypeError {\n readonly code = \"MOCKINGBIRD_DROP\"\n constructor() {\n super(\"fetch failed: connection dropped by Mockingbird fault\")\n this.name = \"TypeError\"\n }\n}\n\ntype Matcher = { operationId: string; method: string; pattern: RegExp; params: number }\n\n/** Resolve a request to its operationId: static segments beat parameters, as in routing. */\nconst operationMatcher = (document: OpenAPIDocument) => {\n const matchers: Matcher[] = listOperations(document)\n .map((operation) => ({\n operationId: operation.operationId,\n method: operation.method.toUpperCase(),\n pattern: new RegExp(\n `^${operation.path\n .split(\"/\")\n .map((segment) =>\n segment.startsWith(\"{\") ? \"[^/]+\" : segment.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"),\n )\n .join(\"/\")}/?$`,\n ),\n params: (operation.path.match(/\\{/g) ?? []).length,\n }))\n .sort((a, b) => a.params - b.params)\n return (request: Request, path: string): string | undefined =>\n matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId\n}\n\n/**\n * Wrap a service in the shared Mockingbird contract: an unauthenticated `/health`,\n * the `/__admin/*` control plane, per-request namespaces, a controllable clock,\n * fault injection, and request metrics.\n *\n * Namespaces isolate parallel workers inside one process: each gets its own\n * instance over the same SQLite database, so rows are partitioned by namespace\n * and a worker's reset or restore never touches another worker's data.\n */\nexport const createRuntime = <T extends ServiceInstance>(\n options: RuntimeOptions<T>,\n): ServiceRuntime<T> => {\n const sqlite = bootSqlite(options.sqlite)\n const clock = options.clock ?? createClock()\n const rng = createRng(options.seed ?? 0)\n const wallNow = options.io?.wallNow ?? Date.now\n const monotonicNow = options.io?.monotonicNow ?? (() => performance.now())\n const sleep =\n options.io?.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))\n const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep)\n const metrics = createMetrics()\n const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE)\n const version = options.version ?? PACKAGE_VERSION\n const instances = new Map<string, T>()\n const publicNamespaces = new Set<string>()\n const branchRngs = new Map<string, Rng>()\n const timelines = new Map<string, Timeline<ServiceTimelineState>>()\n const branchStorage = new Map<string, string>()\n const captured = new Map<string, NamespaceSnapshot>()\n const credentials = createCredentialRegistry()\n const operationIdFor = options.document ? operationMatcher(options.document) : () => undefined\n\n const storageNamespace = (name: string) =>\n name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`\n\n const instanceFor = (key: string, publicNamespace = key, isolatedRng?: Rng): T => {\n const existing = instances.get(key)\n if (existing) return existing\n if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {\n throw new RangeError(\n `namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`,\n )\n }\n const created = options.create({\n namespace: storageNamespace(key),\n publicNamespace,\n sqlite,\n clock,\n rng: isolatedRng ?? rng,\n })\n instances.set(key, created)\n publicNamespaces.add(publicNamespace)\n if (isolatedRng) branchRngs.set(key, isolatedRng)\n return created\n }\n\n const instance = (name: string = DEFAULT_NAMESPACE): T => instanceFor(name)\n\n const capture = (storage: string): ServiceTimelineState => {\n const fresh = snapshotNamespace(sqlite, storageNamespace(storage))\n const previous = captured.get(storage)\n const snapshot: NamespaceSnapshot = {\n namespace: fresh.namespace,\n records: reuseSorted(\n fresh.records,\n previous?.records,\n (left, right) =>\n left.collection < right.collection\n ? -1\n : left.collection > right.collection\n ? 1\n : left.seq - right.seq,\n (left, right) => left.id === right.id && left.value === right.value,\n ),\n sequences: reuseSorted(\n fresh.sequences,\n previous?.sequences,\n (left, right) =>\n left.name < right.name\n ? -1\n : left.name > right.name\n ? 1\n : left.kind < right.kind\n ? -1\n : left.kind > right.kind\n ? 1\n : 0,\n (left, right) => left.value === right.value,\n ),\n }\n Object.freeze(snapshot.records)\n Object.freeze(snapshot.sequences)\n Object.freeze(snapshot)\n captured.set(storage, snapshot)\n return Object.freeze({\n snapshot,\n clock: Object.freeze(clock.state()),\n rngState: (branchRngs.get(storage) ?? rng).state(),\n })\n }\n\n const timeline = (name: string = DEFAULT_NAMESPACE): Timeline<ServiceTimelineState> => {\n let found = timelines.get(name)\n if (found) return found\n instance(name)\n found = new Timeline<ServiceTimelineState>({\n now: clock.now,\n ...(options.maxCheckpoints !== undefined ? { maxCheckpoints: options.maxCheckpoints } : {}),\n })\n found.commit(capture(name))\n timelines.set(name, found)\n return found\n }\n\n const physicalBranch = (namespace: string, branch: string): string => {\n if (branch === \"main\") return namespace\n const mapKey = `${namespace}\\0${branch}`\n const existing = branchStorage.get(mapKey)\n if (existing) return existing\n // The hash keeps the internal instance key inside the 64-character namespace contract.\n const key = `branch_${seedFrom(`${options.name}\\0${namespace}\\0${branch}`).toString(36)}`\n branchStorage.set(mapKey, key)\n return key\n }\n\n const ensureBranch = (namespace: string, branch: string, at?: string): string => {\n if (!BRANCH_PATTERN.test(branch)) throw new RangeError(`branch must match ${BRANCH_PATTERN}`)\n const history = timeline(namespace)\n if (branch === \"main\") {\n if (at !== undefined) {\n const point = history.checkout(\"main\", at)\n restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot)\n captured.set(namespace, point.value.snapshot)\n rng.setState(point.value.rngState)\n clock.set(point.value.clock.now)\n if (point.value.clock.frozen) clock.freeze()\n else clock.unfreeze()\n }\n return namespace\n }\n const storage = physicalBranch(namespace, branch)\n if (!history.hasBranch(branch)) {\n // Capture unobserved background work before branching from the current main head.\n if (at === undefined) history.commit(capture(namespace))\n const point = history.fork(branch, at === undefined ? {} : { from: at })\n const branchRng = createRng(options.seed ?? 0)\n if (point) branchRng.setState(point.value.rngState)\n instanceFor(storage, namespace, branchRng)\n if (point) restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n if (point) captured.set(storage, point.value.snapshot)\n } else if (at !== undefined && history.head(branch)?.id !== at) {\n const point = history.checkout(branch, at)\n if (!instances.has(storage)) {\n const branchRng = createRng(options.seed ?? 0)\n branchRng.setState(point.value.rngState)\n instanceFor(storage, namespace, branchRng)\n }\n branchRngs.get(storage)?.setState(point.value.rngState)\n restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n captured.set(storage, point.value.snapshot)\n } else {\n if (!instances.has(storage)) {\n const point = history.head(branch)\n const branchRng = createRng(options.seed ?? 0)\n if (point) branchRng.setState(point.value.rngState)\n instanceFor(storage, namespace, branchRng)\n }\n }\n return storage\n }\n\n const checkpoint = (namespace = DEFAULT_NAMESPACE, branch = \"main\"): ServiceCheckpoint => {\n const storage = ensureBranch(namespace, branch)\n return timeline(namespace).commit(capture(storage), { branch })\n }\n\n const branch = (\n name: string,\n branchOptions: { namespace?: string; at?: string } = {},\n ): ServiceCheckpoint => {\n const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE\n ensureBranch(namespace, name, branchOptions.at)\n const head = timeline(namespace).head(name)\n if (!head) throw new RangeError(`branch ${name} has no checkpoint`)\n return head\n }\n\n const checkout = (\n checkpointId: string,\n checkoutOptions: { namespace?: string; branch?: string } = {},\n ): void => {\n const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE\n const branchName = checkoutOptions.branch ?? \"main\"\n const history = timeline(namespace)\n const point = history.checkout(branchName, checkpointId)\n const storage = ensureBranch(namespace, branchName)\n restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n captured.set(storage, point.value.snapshot)\n clock.set(point.value.clock.now)\n if (point.value.clock.frozen) clock.freeze()\n else clock.unfreeze()\n ;(branchRngs.get(storage) ?? rng).setState(point.value.rngState)\n }\n\n const reset = async (name: string = DEFAULT_NAMESPACE): Promise<void> => {\n if (name === \"*\") {\n options.webhooks?.clear()\n for (const each of instances.values()) await each.reset()\n timelines.clear()\n branchStorage.clear()\n branchRngs.clear()\n captured.clear()\n return\n }\n options.webhooks?.clear(name)\n const target = instances.get(name)\n if (target) await target.reset()\n else clearNamespace(sqlite, storageNamespace(name))\n for (const [mapping, storage] of branchStorage) {\n if (!mapping.startsWith(`${name}\\0`)) continue\n const branchInstance = instances.get(storage)\n if (branchInstance) await branchInstance.reset()\n else clearNamespace(sqlite, storageNamespace(storage))\n branchStorage.delete(mapping)\n branchRngs.delete(storage)\n captured.delete(storage)\n }\n timelines.delete(name)\n captured.delete(name)\n }\n\n const snapshot = (name: string = DEFAULT_NAMESPACE): NamespaceSnapshot => {\n return checkpoint(name, \"main\").value.snapshot\n }\n\n const restore = (from: NamespaceSnapshot, name: string = DEFAULT_NAMESPACE): void => {\n instance(name)\n restoreNamespace(sqlite, storageNamespace(name), from)\n captured.set(name, from)\n // Import legacy snapshots into the canonical history instead of creating a second rollback\n // mechanism. The compatibility method stays synchronous and keeps its original return type.\n const history = timelines.get(name)\n if (history) history.commit(capture(name), { branch: \"main\" })\n else timeline(name)\n }\n\n const runtime: ServiceRuntime<T> = {\n name: options.name,\n sqlite,\n clock,\n faults,\n metrics,\n journal,\n rng,\n credentials,\n webhooks: options.webhooks,\n applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {\n const preset = options.presets?.[name]\n if (!preset) throw new RangeError(`no fault preset ${JSON.stringify(name)}`)\n const added = (preset.rules ?? []).map((rule, index) =>\n faults.add({\n namespace,\n ...rule,\n ...overrides,\n preset: name,\n id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : \"\"}`,\n } as FaultRule),\n )\n if (preset.webhook && options.webhooks) {\n options.webhooks.fault(namespace, {\n ...preset.webhook,\n ...(overrides.count !== undefined ? { count: overrides.count } : {}),\n })\n }\n return added\n },\n instance,\n namespaces: () => [...publicNamespaces].sort(),\n reset,\n snapshot,\n restore,\n checkpoint,\n branch,\n checkout,\n timeline,\n fetch: async (incoming) => {\n let request = incoming\n // `/ns/<name>/\u2026` selects a namespace (and is stripped) for SDKs that cannot add headers.\n const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname)\n if (prefixed) {\n const url = new URL(request.url)\n url.pathname = prefixed[2] ?? \"/\"\n const headers = new Headers(request.headers)\n if (!headers.has(NAMESPACE_HEADER)) {\n headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1] as string))\n }\n const hasBody = request.method !== \"GET\" && request.method !== \"HEAD\"\n request = new Request(url, {\n method: request.method,\n headers,\n ...(hasBody ? { body: await request.arrayBuffer() } : {}),\n signal: request.signal,\n })\n }\n let namespace = control.namespaceOf(request)\n if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {\n const credential = options.credential(request)\n const mapped = credential !== undefined ? credentials.get(credential) : undefined\n if (mapped !== undefined) namespace = mapped\n }\n const selectedBranch = request.headers.get(BRANCH_HEADER) ?? \"main\"\n const at = request.headers.get(AT_HEADER) ?? undefined\n const stamp = (response: Response): Response => {\n // An invalid namespace is not echoed back.\n const value = NAMESPACE_PATTERN.test(namespace)\n ? `${options.name}@${version}; ns=${namespace}`\n : `${options.name}@${version}`\n try {\n response.headers.set(MOCKINGBIRD_HEADER, value)\n return response\n } catch {\n // Immutable headers (a response passed through from `fetch`): copy it.\n const copy = new Response(response.body, response)\n copy.headers.set(MOCKINGBIRD_HEADER, value)\n return copy\n }\n }\n const handled = await control.handle(request)\n if (handled) return stamp(handled)\n const started = monotonicNow()\n const url = new URL(request.url)\n const operationId = operationIdFor(request, url.pathname)\n const log = (status: number, faultId?: string, response?: Response) => {\n const noted = response ? responseNotes(response) : undefined\n const entry: RequestLog = {\n service: options.name,\n namespace,\n operationId,\n method: request.method,\n path: url.pathname,\n status,\n durationMs: Math.round((monotonicNow() - started) * 100) / 100,\n unmatched: options.document !== undefined && operationId === undefined,\n ...(faultId !== undefined ? { faultId } : {}),\n ...(noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {}),\n ...(noted?.adopted ? { adopted: true } : {}),\n }\n metrics.record(entry)\n journal.record({ ...entry, at: new Date(clock.now()).toISOString() })\n options.onLog?.(entry)\n }\n if (!NAMESPACE_PATTERN.test(namespace)) {\n log(400)\n return stamp(\n new Response(\n JSON.stringify({\n error: {\n type: \"mockingbird_admin\",\n message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`,\n },\n }),\n { status: 400, headers: { \"content-type\": \"application/json\" } },\n ),\n )\n }\n if (!BRANCH_PATTERN.test(selectedBranch)) {\n log(400)\n return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN}`))\n }\n let storage: string\n try {\n if (\n at !== undefined &&\n selectedBranch === \"main\" &&\n !MUTATING_METHODS.has(request.method)\n ) {\n const point = timeline(namespace).get(at)\n storage = physicalBranch(namespace, `at_${at}`)\n let viewRng = branchRngs.get(storage)\n if (!viewRng) {\n viewRng = createRng(options.seed ?? 0)\n instanceFor(storage, namespace, viewRng)\n }\n viewRng.setState(point.value.rngState)\n restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n captured.set(storage, point.value.snapshot)\n } else {\n storage = ensureBranch(namespace, selectedBranch, at)\n }\n } catch (error) {\n log(409)\n return stamp(adminFail(409, error instanceof Error ? error.message : String(error)))\n }\n const hits = await faults.take({\n operationId,\n method: request.method,\n path: url.pathname,\n namespace,\n })\n const final = hits.find((hit) => hit.drop || hit.response)\n if (final?.drop) {\n log(0, final.id)\n throw new DroppedConnectionError()\n }\n if (final?.response) {\n log(final.response.status, final.id)\n return stamp(final.response)\n }\n const fired = hits.filter((hit) => hit.effect !== undefined)\n if (fired.length > 0)\n effects.set(\n request,\n fired.map((hit) => hit.effect),\n )\n let response = await instanceFor(storage, namespace).fetch(request)\n if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {\n const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch })\n response = mutableResponse(response)\n response.headers.set(CHECKPOINT_HEADER, point.id)\n }\n if (selectedBranch !== \"main\") {\n response = mutableResponse(response)\n response.headers.set(BRANCH_HEADER, selectedBranch)\n }\n if (at !== undefined) {\n response = mutableResponse(response)\n response.headers.set(AT_HEADER, at)\n }\n log(response.status, fired[0]?.id, response)\n return stamp(response)\n },\n }\n\n const control = createControlPlane({\n name: options.name,\n startedAt: wallNow(),\n wallNow,\n clock,\n faults,\n metrics,\n journal,\n defaultNamespace: DEFAULT_NAMESPACE,\n namespaces: runtime.namespaces,\n reset,\n timeTravel: {\n checkpoint: (name, branchName) => {\n const point = checkpoint(name, branchName)\n return {\n id: point.id,\n branch: point.branch,\n parent: point.parent,\n at: point.at,\n records: point.value.snapshot.records.length,\n }\n },\n branch: (branchName, branchOptions) => {\n const point = branch(branchName, branchOptions)\n return { id: point.id, branch: point.branch, parent: point.parent, at: point.at }\n },\n checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),\n retain: (name, checkpointId) => {\n timeline(name).retain(checkpointId)\n },\n release: (name, checkpointId) => timeline(name).release(checkpointId),\n inspect: (name) => {\n const history = timeline(name)\n return {\n branches: history.branches(),\n checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({\n id,\n branch: branchName,\n parent,\n at,\n })),\n }\n },\n },\n describe: options.describe ?? (() => ({})),\n ...(options.presets\n ? {\n applyPreset: (name: string, namespace: string, overrides: Partial<FaultRule>) =>\n runtime.applyPreset(name, namespace, overrides),\n }\n : {}),\n routes: {\n ...credentialRoutes(credentials),\n ...(options.presets ? presetRoutes(options.presets, runtime) : {}),\n ...(options.webhooks ? webhookAdminRoutes(options.webhooks) : {}),\n ...(options.admin?.(runtime) ?? {}),\n },\n adminKey: options.adminKey,\n })\n\n return runtime\n}\n\nconst mutableResponse = (response: Response): Response => {\n try {\n response.headers.set(\"x-mockingbird-mutable-probe\", \"1\")\n response.headers.delete(\"x-mockingbird-mutable-probe\")\n return response\n } catch {\n return new Response(response.body, response)\n }\n}\n\nconst adminJson = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\n\nconst adminFail = (status: number, message: string): Response =>\n adminJson(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\n/**\n * `PUT /__admin/credentials` accepts `{ credentials: { \"<credential>\": \"<namespace>\" } }`,\n * `[{ credential, namespace }]`, or `{ credentials: [\"<credential>\"] }` with `?namespace=`\n * (maps each to the calling namespace). `GET` lists them masked; `DELETE` removes one\n * (`?credential=`) or all.\n */\nconst credentialRoutes = (registry: CredentialRegistry): AdminRoutes => ({\n \"GET /credentials\": () =>\n adminJson(200, {\n credentials: registry.entries().map(({ credential, namespace }) => ({\n credential: maskCredential(credential),\n namespace,\n })),\n }),\n \"PUT /credentials\": ({ body, namespace }) => {\n const pairs: [string, string][] = []\n const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : undefined\n if (Array.isArray(list)) {\n for (const each of list) {\n if (typeof each === \"string\") pairs.push([each, namespace])\n else if (isObject(each) && typeof each.credential === \"string\") {\n pairs.push([\n each.credential,\n typeof each.namespace === \"string\" ? each.namespace : namespace,\n ])\n } else return adminFail(400, \"each entry is a credential string or {credential, namespace}\")\n }\n } else if (isObject(list)) {\n for (const [credential, target] of Object.entries(list)) {\n if (typeof target !== \"string\")\n return adminFail(400, `namespace for ${credential} must be a string`)\n pairs.push([credential, target])\n }\n } else if (isObject(body) && typeof body.credential === \"string\") {\n pairs.push([body.credential, typeof body.namespace === \"string\" ? body.namespace : namespace])\n } else {\n return adminFail(400, 'expected {\"credentials\": {\"<credential>\": \"<namespace>\"}}')\n }\n for (const [credential, target] of pairs) {\n if (!NAMESPACE_PATTERN.test(target))\n return adminFail(400, `bad namespace ${JSON.stringify(target)}`)\n registry.set(credential, target)\n }\n return adminJson(200, { mapped: pairs.length })\n },\n \"DELETE /credentials\": ({ url }) => {\n const credential = url.searchParams.get(\"credential\")\n if (credential === null) registry.clear()\n else registry.remove(credential)\n return adminJson(200, { status: \"ok\" })\n },\n})\n\nconst presetRoutes = <T extends ServiceInstance>(\n presets: Record<string, FaultPreset>,\n runtime: ServiceRuntime<T>,\n): AdminRoutes => ({\n \"GET /faults/presets\": () =>\n adminJson(200, {\n presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset })),\n }),\n \"POST /faults/presets/:name\": ({ params, body, namespace }) => {\n const name = params.name as string\n if (!presets[name])\n return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`)\n const overrides = isObject(body) ? (body as Partial<FaultRule>) : {}\n return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) })\n },\n})\n", "import {\n deref,\n resolveSchema,\n type SchemaObject,\n validateValue,\n} from \"@crvouga/mockingbird-openapi\"\nimport type { OperationContext } from \"./service.js\"\n\n/** One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`). */\nexport type BodyIssue = { path: string; message: string }\n\n/**\n * Validate the decoded JSON body against the operation's `requestBody` schema in the vendor\n * contract. Returns `[]` when valid, or when the operation declares no JSON body. Services\n * turn the issues into the vendor's own validation error shape.\n */\nexport const bodyIssues = (\n context: OperationContext,\n contentType = \"application/json\",\n): BodyIssue[] => {\n const requestBody = context.operation.operation.requestBody\n if (!requestBody) return []\n const resolved = deref(context.document, requestBody) as {\n required?: boolean\n content?: Record<string, { schema?: SchemaObject }>\n }\n const schema = resolved.content?.[contentType]?.schema\n if (!schema) return []\n const value =\n context.body.kind === \"json\" || context.body.kind === \"form\" ? context.body.value : undefined\n if (context.body.kind === \"invalid\") {\n return [{ path: \"\", message: `request body is not valid ${context.body.mediaType}` }]\n }\n if (value === undefined) {\n return resolved.required ? [{ path: \"\", message: \"request body is required\" }] : []\n }\n return validateValue(context.document, resolveSchema(context.document, schema), value).map(\n (issue) => ({ path: issue.path.join(\".\"), message: issue.message }),\n )\n}\n\n/** Issues grouped Laravel-style: `{ \"patient.email\": [\"\u2026\"] }`. */\nexport const issuesByField = (issues: BodyIssue[]): Record<string, string[]> => {\n const out: Record<string, string[]> = {}\n for (const issue of issues) {\n const missing = /^missing required property (.+)$/.exec(issue.message)\n const field = missing\n ? [issue.path, missing[1]].filter(Boolean).join(\".\")\n : issue.path || \"body\"\n const message = missing\n ? `The ${field} field is required.`\n : `The ${field} field ${issue.message}.`\n out[field] = [...(out[field] ?? []), message]\n }\n return out\n}\n", "/**\n * Reading a model call: the Converse wire shape (Converse, ConverseStream) and the\n * Anthropic Messages body (InvokeModel), reduced to a {@link CallAnalysis} for matching,\n * plus the request checks Bedrock itself makes and our consumer branches on (role\n * alternation, tool pairing, assistant prefill, document-without-text, sampling params).\n */\nimport type { CallAnalysis, ModelOperation, StructuredRequest } from \"./scripts.js\"\n\ntype Json = Record<string, unknown>\n\nconst isRecord = (value: unknown): value is Json =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst array = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])\n\n/** A request Bedrock rejects with `ValidationException`. */\nexport class ValidationProblem extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"ValidationProblem\"\n }\n}\n\n/** Claude generations that reject a trailing assistant message (no prefill). */\nconst NO_PREFILL =\n /claude-(?:sonnet|opus)-4-[5-9]|claude-opus-4-1|claude-(?:sonnet|opus|haiku)-[5-9]/i\n/** Claude generations that reject `temperature` and `top_p` together. */\nconst ONE_SAMPLING_PARAM =\n /claude-(?:sonnet|opus|haiku)-4-[5-9]|claude-opus-4-1|claude-(?:sonnet|opus|haiku)-[5-9]/i\n\nconst parseSchema = (value: unknown): unknown => {\n if (typeof value !== \"string\") return value\n try {\n return JSON.parse(value) as unknown\n } catch {\n return {}\n }\n}\n\nconst textOf = (blocks: unknown[]): string =>\n blocks\n .map((block) => (isRecord(block) && typeof block.text === \"string\" ? block.text : \"\"))\n .filter((text) => text.length > 0)\n .join(\"\\n\")\n\ntype NormalMessage = {\n role: string\n /** Text of the message (text blocks only). */\n text: string\n toolUses: { id: string; name: string }[]\n toolResultIds: string[]\n hasContent: boolean\n hasDocument: boolean\n hasImage: boolean\n hasCachePoint: boolean\n chars: number\n}\n\n/** Shared tail of both analyses: turn index, tool results, last user text. */\nconst conversationFacts = (messages: NormalMessage[]) => {\n let lastSaid = -1\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i] as NormalMessage\n if (message.role === \"user\" && message.hasContent) {\n lastSaid = i\n break\n }\n }\n const turnIndex = messages.slice(lastSaid + 1).filter((m) => m.role === \"assistant\").length\n const toolNames = new Map<string, string>()\n for (const message of messages)\n for (const use of message.toolUses) toolNames.set(use.id, use.name)\n const last = messages.at(-1)\n const toolResults =\n last?.role === \"user\"\n ? last.toolResultIds.map((id) => toolNames.get(id)).filter((n): n is string => !!n)\n : []\n return {\n turnIndex,\n toolResults,\n lastUserText: lastSaid >= 0 ? (messages[lastSaid] as NormalMessage).text : \"\",\n }\n}\n\n/** Bedrock's own conversation checks, in the order it reports them. */\nconst checkConversation = (messages: NormalMessage[], modelId: string, hasToolConfig: boolean) => {\n if (messages.length === 0 || messages[0]?.role !== \"user\") {\n throw new ValidationProblem(\n \"A conversation must start with a user message. Try again with a conversation that starts with a user message.\",\n )\n }\n for (let i = 1; i < messages.length; i++) {\n if (messages[i]?.role === messages[i - 1]?.role) {\n throw new ValidationProblem(\n \"A conversation must alternate between user and assistant roles. Make sure the conversation alternates between user and assistant roles and try again.\",\n )\n }\n }\n const usesTools = messages.some((m) => m.toolUses.length > 0 || m.toolResultIds.length > 0)\n if (usesTools && !hasToolConfig) {\n throw new ValidationProblem(\n \"The toolConfig field must be defined when using toolUse and toolResult content blocks.\",\n )\n }\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as NormalMessage\n if (message.role === \"user\" && message.hasDocument && message.text.length === 0) {\n throw new ValidationProblem(\n `The model returned the following errors: messages.${i}: A text block must be included alongside a document block.`,\n )\n }\n if (message.role !== \"assistant\" || message.toolUses.length === 0) continue\n const next = messages[i + 1]\n if (!next) continue\n const missing = message.toolUses.filter((use) => !next.toolResultIds.includes(use.id))\n if (missing.length > 0) {\n throw new ValidationProblem(\n `Expected toolResult blocks at messages.${i + 1}.content for the following Ids: ${missing.map((m) => m.id).join(\", \")}`,\n )\n }\n }\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as NormalMessage\n if (message.toolResultIds.length === 0) continue\n const previous = messages[i - 1]\n const known = new Set(previous?.toolUses.map((use) => use.id) ?? [])\n const orphan = message.toolResultIds.find((id) => !known.has(id))\n if (orphan !== undefined) {\n throw new ValidationProblem(\n `messages.${i}.content: unexpected tool_use_id found in tool_result blocks: ${orphan}. Each tool_result block must have a corresponding tool_use block in the previous message.`,\n )\n }\n }\n if (messages.at(-1)?.role === \"assistant\" && NO_PREFILL.test(modelId)) {\n throw new ValidationProblem(\n \"This model does not support assistant message prefill. The conversation must end with a user message.\",\n )\n }\n}\n\nconst converseMessage = (value: unknown, index: number): NormalMessage => {\n if (!isRecord(value) || (value.role !== \"user\" && value.role !== \"assistant\")) {\n throw new ValidationProblem(`messages.${index}.role: must be one of [user, assistant]`)\n }\n const content = array(value.content)\n if (content.length === 0) {\n throw new ValidationProblem(\n `messages.${index}.content: The content field in the Message object at messages.${index} is empty. Add a ContentBlock object to the content field and try again.`,\n )\n }\n const out: NormalMessage = {\n role: value.role,\n text: textOf(content),\n toolUses: [],\n toolResultIds: [],\n hasContent: false,\n hasDocument: false,\n hasImage: false,\n hasCachePoint: false,\n chars: 0,\n }\n for (const block of content) {\n if (!isRecord(block)) continue\n out.chars += JSON.stringify(block).length\n if (typeof block.text === \"string\") out.hasContent = true\n if (isRecord(block.document)) {\n out.hasDocument = true\n out.hasContent = true\n }\n if (isRecord(block.image)) {\n out.hasImage = true\n out.hasContent = true\n }\n if (isRecord(block.video)) out.hasContent = true\n if (isRecord(block.cachePoint)) out.hasCachePoint = true\n if (isRecord(block.toolUse)) {\n out.toolUses.push({\n id: String(block.toolUse.toolUseId ?? \"\"),\n name: String(block.toolUse.name ?? \"\"),\n })\n }\n if (isRecord(block.toolResult)) out.toolResultIds.push(String(block.toolResult.toolUseId ?? \"\"))\n }\n return out\n}\n\n/** Analyse (and validate) a Converse / ConverseStream body. */\nexport const analyzeConverse = (\n operation: ModelOperation,\n modelId: string,\n body: unknown,\n): CallAnalysis => {\n if (!isRecord(body))\n throw new ValidationProblem(\n \"Malformed input request, please reformat your input and try again.\",\n )\n const messages = array(body.messages).map(converseMessage)\n const system = array(body.system)\n const toolConfig = isRecord(body.toolConfig) ? body.toolConfig : undefined\n const toolSchemas: Record<string, unknown> = {}\n for (const tool of array(toolConfig?.tools)) {\n if (!isRecord(tool) || !isRecord(tool.toolSpec)) continue\n const spec = tool.toolSpec\n const schema = isRecord(spec.inputSchema) ? spec.inputSchema.json : undefined\n toolSchemas[String(spec.name)] = parseSchema(schema) ?? {}\n }\n const tools = Object.keys(toolSchemas)\n const choice = isRecord(toolConfig?.toolChoice) ? toolConfig.toolChoice : undefined\n let toolChoice: string | undefined\n if (choice) {\n if (isRecord(choice.tool)) toolChoice = `tool:${String(choice.tool.name)}`\n else if (choice.any !== undefined) toolChoice = \"any\"\n else if (choice.auto !== undefined) toolChoice = \"auto\"\n }\n if (toolConfig && tools.length === 0) {\n throw new ValidationProblem(\n \"The value at toolConfig.tools failed to satisfy constraint: Member must have length greater than or equal to 1\",\n )\n }\n if (toolChoice?.startsWith(\"tool:\") && !tools.includes(toolChoice.slice(5))) {\n throw new ValidationProblem(\n `The provided toolChoice ${toolChoice.slice(5)} is not a tool in toolConfig.tools.`,\n )\n }\n const inference = isRecord(body.inferenceConfig) ? body.inferenceConfig : {}\n const additional = isRecord(body.additionalModelRequestFields)\n ? body.additionalModelRequestFields\n : {}\n const hasTemperature = inference.temperature !== undefined || additional.temperature !== undefined\n const hasTopP = inference.topP !== undefined || additional.top_p !== undefined\n if (hasTemperature && hasTopP && ONE_SAMPLING_PARAM.test(modelId)) {\n throw new ValidationProblem(\n \"The model returned the following errors: `temperature` and `top_p` cannot both be specified for this model. Please use only one.\",\n )\n }\n checkConversation(messages, modelId, toolConfig !== undefined)\n\n let structured: StructuredRequest | undefined\n const outputConfig = isRecord(body.outputConfig) ? body.outputConfig : undefined\n const textFormat = isRecord(outputConfig?.textFormat) ? outputConfig.textFormat : undefined\n const jsonSchema =\n textFormat && isRecord(textFormat.structure) && isRecord(textFormat.structure.jsonSchema)\n ? textFormat.structure.jsonSchema\n : undefined\n const nativeFormat =\n isRecord(additional.output_config) && isRecord(additional.output_config.format)\n ? additional.output_config.format\n : undefined\n if (jsonSchema) {\n structured = {\n form: \"outputConfig\",\n schema: parseSchema(jsonSchema.schema),\n ...(typeof jsonSchema.name === \"string\" ? { name: jsonSchema.name } : {}),\n }\n } else if (nativeFormat && nativeFormat.type === \"json_schema\") {\n structured = { form: \"outputFormat\", schema: parseSchema(nativeFormat.schema) }\n } else if (toolChoice?.startsWith(\"tool:\")) {\n const tool = toolChoice.slice(5)\n structured = { form: \"tool\", tool, schema: toolSchemas[tool] }\n } else if (toolChoice === \"any\" && tools.length > 0) {\n const tool = tools.includes(\"json\") ? \"json\" : (tools[0] as string)\n structured = { form: \"tool\", tool, schema: toolSchemas[tool] }\n }\n\n const facts = conversationFacts(messages)\n const systemText = textOf(system)\n return {\n operation,\n modelId,\n lastUserText: facts.lastUserText,\n systemText,\n tools,\n toolSchemas,\n toolChoice,\n hasDocument: messages.some((m) => m.hasDocument),\n hasImage: messages.some((m) => m.hasImage),\n hasCachePoint:\n messages.some((m) => m.hasCachePoint) ||\n system.some((b) => isRecord(b) && isRecord(b.cachePoint)) ||\n array(toolConfig?.tools).some((t) => isRecord(t) && isRecord(t.cachePoint)),\n hasGuardrail: isRecord(body.guardrailConfig),\n toolResults: facts.toolResults,\n turnIndex: facts.turnIndex,\n structured,\n inputChars:\n messages.reduce((sum, m) => sum + m.chars, 0) +\n systemText.length +\n JSON.stringify(toolSchemas).length,\n }\n}\n\nconst anthropicMessage = (value: unknown, index: number): NormalMessage => {\n if (!isRecord(value) || (value.role !== \"user\" && value.role !== \"assistant\")) {\n throw new ValidationProblem(`messages.${index}.role: Input should be 'user' or 'assistant'`)\n }\n const blocks =\n typeof value.content === \"string\"\n ? [{ type: \"text\", text: value.content }]\n : array(value.content)\n if (blocks.length === 0)\n throw new ValidationProblem(`messages.${index}: all messages must have non-empty content`)\n const out: NormalMessage = {\n role: value.role,\n text: textOf(blocks.filter((b) => isRecord(b) && b.type === \"text\")),\n toolUses: [],\n toolResultIds: [],\n hasContent: false,\n hasDocument: false,\n hasImage: false,\n hasCachePoint: false,\n chars: 0,\n }\n for (const block of blocks) {\n if (!isRecord(block)) continue\n out.chars += JSON.stringify(block).length\n if (isRecord(block.cache_control)) out.hasCachePoint = true\n switch (block.type) {\n case \"text\":\n out.hasContent = true\n break\n case \"document\":\n out.hasDocument = true\n out.hasContent = true\n break\n case \"image\":\n out.hasImage = true\n out.hasContent = true\n break\n case \"tool_use\":\n out.toolUses.push({ id: String(block.id ?? \"\"), name: String(block.name ?? \"\") })\n break\n case \"tool_result\":\n out.toolResultIds.push(String(block.tool_use_id ?? \"\"))\n break\n }\n }\n return out\n}\n\n/** Analyse (and validate) an Anthropic Messages body sent through InvokeModel. */\nexport const analyzeAnthropic = (modelId: string, body: unknown): CallAnalysis => {\n if (!isRecord(body))\n throw new ValidationProblem(\n \"Malformed input request, please reformat your input and try again.\",\n )\n if (typeof body.anthropic_version !== \"string\") {\n throw new ValidationProblem(\n \"Malformed input request: #: required key [anthropic_version] not found, please reformat your input and try again.\",\n )\n }\n if (typeof body.max_tokens !== \"number\") {\n throw new ValidationProblem(\n \"Malformed input request: #: required key [max_tokens] not found, please reformat your input and try again.\",\n )\n }\n if (\n body.temperature !== undefined &&\n body.top_p !== undefined &&\n ONE_SAMPLING_PARAM.test(modelId)\n ) {\n throw new ValidationProblem(\n \"`temperature` and `top_p` cannot both be specified for this model. Please use only one.\",\n )\n }\n const messages = array(body.messages).map(anthropicMessage)\n const toolSchemas: Record<string, unknown> = {}\n for (const tool of array(body.tools)) {\n if (isRecord(tool) && typeof tool.name === \"string\")\n toolSchemas[tool.name] = tool.input_schema ?? {}\n }\n checkConversation(messages, modelId, true)\n const system = typeof body.system === \"string\" ? body.system : textOf(array(body.system))\n const choice = isRecord(body.tool_choice) ? body.tool_choice : undefined\n const toolChoice =\n choice?.type === \"tool\"\n ? `tool:${String(choice.name)}`\n : typeof choice?.type === \"string\"\n ? choice.type\n : undefined\n const tools = Object.keys(toolSchemas)\n let structured: StructuredRequest | undefined\n const format =\n isRecord(body.output_config) && isRecord(body.output_config.format)\n ? body.output_config.format\n : undefined\n if (format?.type === \"json_schema\") structured = { form: \"outputFormat\", schema: format.schema }\n else if (toolChoice?.startsWith(\"tool:\")) {\n const tool = toolChoice.slice(5)\n structured = { form: \"tool\", tool, schema: toolSchemas[tool] }\n }\n const facts = conversationFacts(messages)\n return {\n operation: \"InvokeModel\",\n modelId,\n lastUserText: facts.lastUserText,\n systemText: system,\n tools,\n toolSchemas,\n toolChoice,\n hasDocument: messages.some((m) => m.hasDocument),\n hasImage: messages.some((m) => m.hasImage),\n hasCachePoint: messages.some((m) => m.hasCachePoint),\n hasGuardrail: false,\n toolResults: facts.toolResults,\n turnIndex: facts.turnIndex,\n structured,\n inputChars: messages.reduce((sum, m) => sum + m.chars, 0) + system.length,\n }\n}\n\n/** Analyse an AgentCore InvokeHarness body. */\nexport const analyzeHarness = (harnessArn: string, body: unknown): CallAnalysis => {\n if (!isRecord(body) || !Array.isArray(body.messages) || body.messages.length === 0) {\n throw new ValidationProblem(\n \"1 validation error detected: Value null at 'messages' failed to satisfy constraint: Member must not be null\",\n )\n }\n const messages = array(body.messages).map(converseMessage)\n const facts = conversationFacts(messages)\n const system =\n typeof body.systemPrompt === \"string\" ? body.systemPrompt : textOf(array(body.systemPrompt))\n return {\n operation: \"InvokeHarness\",\n modelId: harnessArn,\n lastUserText: facts.lastUserText,\n systemText: system,\n tools: array(body.tools)\n .map((tool) => (isRecord(tool) && typeof tool.name === \"string\" ? tool.name : undefined))\n .filter((name): name is string => name !== undefined),\n toolSchemas: {},\n toolChoice: undefined,\n hasDocument: false,\n hasImage: false,\n hasCachePoint: false,\n hasGuardrail: false,\n toolResults: facts.toolResults,\n turnIndex: facts.turnIndex,\n structured: undefined,\n inputChars: messages.reduce((sum, m) => sum + m.chars, 0) + system.length,\n }\n}\n", "// Generated by @crvouga/mockingbird-openapi-codegen from openapi.yaml. Do not edit.\n\nimport type { OpenAPIDocument } from \"@crvouga/mockingbird-openapi\"\n\nexport const document: OpenAPIDocument = JSON.parse(`{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Amazon Bedrock Runtime + AgentCore harness (Mockingbird subset)\",\"description\":\"The Bedrock Runtime data plane our consumer calls: Converse, ConverseStream (event\\\\nstream), InvokeModel (Anthropic Messages bodies and Titan text embeddings), and\\\\nInvokeModelWithBidirectionalStream (Nova Sonic, HTTP/2 duplex), plus the AgentCore\\\\n\\`InvokeHarness\\` event stream. Hand-trimmed from the Smithy models behind\\\\n\\`@aws-sdk/client-bedrock-runtime@3.1132.0\\` and \\`@aws-sdk/client-bedrock-agentcore@3.1074.0\\`\\\\nto the fields our consumer sends and reads.\\\\n\",\"version\":\"2023-09-30\",\"x-mockingbird-upstream\":{\"note\":\"Shapes follow the AWS SDK v3 Smithy schemas (restJson1). Errors carry \\`x-amzn-ErrorType: <Name>:http://internal.amazon.com/coral/com.amazon.bedrock/\\` and a \\`{\\\\\"message\\\\\"}\\` body, as Bedrock sends them.\"}},\"servers\":[{\"url\":\"https://bedrock-runtime.us-east-1.amazonaws.com\"}],\"security\":[{\"sigv4\":[]}],\"paths\":{\"/model/{modelId}/converse\":{\"parameters\":[{\"$ref\":\"#/components/parameters/ModelId\"}],\"post\":{\"operationId\":\"Converse\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ConverseRequest\"}}}},\"responses\":{\"200\":{\"description\":\"The assistant message, stop reason, usage and (with trace enabled) the guardrail trace.\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ConverseResponse\"}}}},\"400\":{\"$ref\":\"#/components/responses/Error\"},\"403\":{\"$ref\":\"#/components/responses/Error\"},\"408\":{\"$ref\":\"#/components/responses/Error\"},\"429\":{\"$ref\":\"#/components/responses/Error\"},\"500\":{\"$ref\":\"#/components/responses/Error\"},\"503\":{\"$ref\":\"#/components/responses/Error\"}}}},\"/model/{modelId}/converse-stream\":{\"parameters\":[{\"$ref\":\"#/components/parameters/ModelId\"}],\"post\":{\"operationId\":\"ConverseStream\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ConverseRequest\"}}}},\"responses\":{\"200\":{\"description\":\"An \\`application/vnd.amazon.eventstream\\` body: messageStart, contentBlockStart (tool use), contentBlockDelta (text, toolUse.input, reasoningContent), contentBlockStop, messageStop, metadata; or an exception frame mid-stream.\",\"content\":{\"application/vnd.amazon.eventstream\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"400\":{\"$ref\":\"#/components/responses/Error\"},\"403\":{\"$ref\":\"#/components/responses/Error\"},\"408\":{\"$ref\":\"#/components/responses/Error\"},\"429\":{\"$ref\":\"#/components/responses/Error\"},\"500\":{\"$ref\":\"#/components/responses/Error\"},\"503\":{\"$ref\":\"#/components/responses/Error\"}}}},\"/model/{modelId}/invoke\":{\"parameters\":[{\"$ref\":\"#/components/parameters/ModelId\"}],\"post\":{\"operationId\":\"InvokeModel\",\"description\":\"Titan text embeddings (\\`amazon.titan-embed-text-*\\`: \\`{inputText, dimensions, normalize}\\` \u2192 \\`{embedding, inputTextTokenCount}\\`) or an Anthropic Messages body for a Claude model (\\`{anthropic_version, max_tokens, system, messages}\\` \u2192 a Messages response).\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"oneOf\":[{\"$ref\":\"#/components/schemas/TitanEmbedRequest\"},{\"$ref\":\"#/components/schemas/AnthropicRequest\"}]}}}},\"responses\":{\"200\":{\"description\":\"The model's native response body.\",\"content\":{\"application/json\":{\"schema\":{\"oneOf\":[{\"$ref\":\"#/components/schemas/TitanEmbedResponse\"},{\"$ref\":\"#/components/schemas/AnthropicResponse\"}]}}}},\"400\":{\"$ref\":\"#/components/responses/Error\"},\"403\":{\"$ref\":\"#/components/responses/Error\"},\"408\":{\"$ref\":\"#/components/responses/Error\"},\"429\":{\"$ref\":\"#/components/responses/Error\"},\"500\":{\"$ref\":\"#/components/responses/Error\"},\"503\":{\"$ref\":\"#/components/responses/Error\"}}}},\"/model/{modelId}/invoke-with-response-stream\":{\"parameters\":[{\"$ref\":\"#/components/parameters/ModelId\"}],\"post\":{\"operationId\":\"InvokeModelWithResponseStream\",\"x-mockingbird\":{\"supported\":false,\"reason\":\"No consumer calls it; chat streaming goes through ConverseStream.\"},\"responses\":{\"200\":{\"description\":\"Event stream of model chunks.\",\"content\":{\"application/vnd.amazon.eventstream\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}}}}},\"/model/{modelId}/invoke-with-bidirectional-stream\":{\"parameters\":[{\"$ref\":\"#/components/parameters/ModelId\"}],\"post\":{\"operationId\":\"InvokeModelWithBidirectionalStream\",\"description\":\"Nova Sonic. HTTP/2 duplex: the request body is an event stream of \\`chunk\\` events (\\`{bytes: base64(JSON {event})}\\`, SigV4-wrapped) that stays open for the session; the response streams \\`chunk\\` events back while it does.\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"reason\":\"A duplex HTTP/2 session; random request bodies cannot drive it.\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/vnd.amazon.eventstream\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"responses\":{\"200\":{\"description\":\"Event stream of \\`chunk\\` events (completionStart, contentStart, textOutput, audioOutput, toolUse, contentEnd, usageEvent, completionEnd).\",\"content\":{\"application/vnd.amazon.eventstream\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"400\":{\"$ref\":\"#/components/responses/Error\"},\"403\":{\"$ref\":\"#/components/responses/Error\"},\"429\":{\"$ref\":\"#/components/responses/Error\"},\"500\":{\"$ref\":\"#/components/responses/Error\"},\"503\":{\"$ref\":\"#/components/responses/Error\"}}}},\"/harnesses/invoke\":{\"post\":{\"operationId\":\"InvokeHarness\",\"description\":\"AgentCore data plane (\\`bedrock-agentcore.<region>.amazonaws.com\\`).\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"harnessArn\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"string\",\"enum\":[\"arn:aws:bedrock-agentcore:us-east-1:123456789012:harness/erx-prescreen\"]}},{\"name\":\"X-Amzn-Bedrock-AgentCore-Runtime-Session-Id\",\"in\":\"header\",\"required\":false,\"schema\":{\"type\":\"string\",\"pattern\":\"^[a-zA-Z0-9-]{33,100}$\"}},{\"name\":\"X-Amzn-Bedrock-AgentCore-Runtime-User-Id\",\"in\":\"header\",\"required\":false,\"schema\":{\"type\":\"string\",\"pattern\":\"^[a-zA-Z0-9_.@-]{1,128}$\"}}],\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HarnessRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Event stream (messageStart, contentBlockDelta text/toolResult, contentBlockStop, messageStop, metadata), or validationException / internalServerException / runtimeClientError frames.\",\"content\":{\"application/vnd.amazon.eventstream\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"400\":{\"$ref\":\"#/components/responses/Error\"},\"403\":{\"$ref\":\"#/components/responses/Error\"},\"429\":{\"$ref\":\"#/components/responses/Error\"},\"500\":{\"$ref\":\"#/components/responses/Error\"},\"503\":{\"$ref\":\"#/components/responses/Error\"}}}}},\"components\":{\"securitySchemes\":{\"sigv4\":{\"type\":\"apiKey\",\"in\":\"header\",\"name\":\"Authorization\",\"description\":\"AWS SigV4 (service \\`bedrock\\` / \\`bedrock-agentcore\\`). Accepted without verification; the access key id selects a namespace.\"}},\"parameters\":{\"ModelId\":{\"name\":\"modelId\",\"in\":\"path\",\"required\":true,\"description\":\"A model id, inference-profile id (\\`global.\\` / \\`us.\\` prefixes) or a URL-encoded inference-profile / foundation-model ARN. Any value is accepted; the enum only steers generated requests.\",\"schema\":{\"type\":\"string\",\"enum\":[\"global.anthropic.claude-sonnet-4-6\",\"us.anthropic.claude-haiku-4-5-20251001-v1:0\",\"us.anthropic.claude-sonnet-4-20250514-v1:0\",\"amazon.titan-embed-text-v2:0\",\"arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.amazon.nova-pro-v1:0\"]}}},\"responses\":{\"Error\":{\"description\":\"A Bedrock error (type in \\`x-amzn-ErrorType\\`).\",\"headers\":{\"x-amzn-ErrorType\":{\"schema\":{\"type\":\"string\"}}},\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ErrorBody\"}}}}},\"schemas\":{\"ErrorBody\":{\"type\":\"object\",\"required\":[\"message\"],\"properties\":{\"message\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}}}},\"TextBlock\":{\"type\":\"object\",\"required\":[\"text\"],\"properties\":{\"text\":{\"type\":\"string\",\"minLength\":1}}},\"CachePointBlock\":{\"type\":\"object\",\"required\":[\"cachePoint\"],\"properties\":{\"cachePoint\":{\"type\":\"object\",\"required\":[\"type\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"default\"]},\"ttl\":{\"type\":\"string\",\"enum\":[\"5m\",\"1h\"]}}}}},\"ToolUseBlock\":{\"type\":\"object\",\"required\":[\"toolUse\"],\"properties\":{\"toolUse\":{\"type\":\"object\",\"required\":[\"toolUseId\",\"name\",\"input\"],\"properties\":{\"toolUseId\":{\"type\":\"string\",\"minLength\":1},\"name\":{\"type\":\"string\",\"minLength\":1},\"input\":{}}}}},\"ToolResultBlock\":{\"type\":\"object\",\"required\":[\"toolResult\"],\"properties\":{\"toolResult\":{\"type\":\"object\",\"required\":[\"toolUseId\",\"content\"],\"properties\":{\"toolUseId\":{\"type\":\"string\",\"minLength\":1},\"content\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"},\"json\":{}}}},\"status\":{\"type\":\"string\",\"enum\":[\"success\",\"error\"]}}}}},\"DocumentBlock\":{\"type\":\"object\",\"required\":[\"document\"],\"properties\":{\"document\":{\"type\":\"object\",\"required\":[\"format\",\"name\",\"source\"],\"properties\":{\"format\":{\"type\":\"string\",\"enum\":[\"pdf\",\"csv\",\"doc\",\"docx\",\"xls\",\"xlsx\",\"html\",\"txt\",\"md\"]},\"name\":{\"type\":\"string\",\"minLength\":1},\"source\":{\"type\":\"object\",\"properties\":{\"bytes\":{\"type\":\"string\",\"contentEncoding\":\"base64\"}}}}}}},\"ImageBlock\":{\"type\":\"object\",\"required\":[\"image\"],\"properties\":{\"image\":{\"type\":\"object\",\"required\":[\"format\",\"source\"],\"properties\":{\"format\":{\"type\":\"string\",\"enum\":[\"png\",\"jpeg\",\"gif\",\"webp\"]},\"source\":{\"type\":\"object\",\"properties\":{\"bytes\":{\"type\":\"string\",\"contentEncoding\":\"base64\"}}}}}}},\"GuardContentBlock\":{\"type\":\"object\",\"required\":[\"guardContent\"],\"properties\":{\"guardContent\":{\"type\":\"object\"}}},\"ContentBlock\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/TextBlock\"},{\"$ref\":\"#/components/schemas/ToolUseBlock\"},{\"$ref\":\"#/components/schemas/ToolResultBlock\"},{\"$ref\":\"#/components/schemas/DocumentBlock\"},{\"$ref\":\"#/components/schemas/ImageBlock\"},{\"$ref\":\"#/components/schemas/CachePointBlock\"},{\"$ref\":\"#/components/schemas/GuardContentBlock\"},{\"type\":\"object\",\"required\":[\"reasoningContent\"],\"properties\":{\"reasoningContent\":{\"type\":\"object\"}}},{\"type\":\"object\",\"required\":[\"video\"],\"properties\":{\"video\":{\"type\":\"object\"}}}]},\"Message\":{\"type\":\"object\",\"required\":[\"role\",\"content\"],\"properties\":{\"role\":{\"type\":\"string\",\"enum\":[\"user\",\"assistant\"]},\"content\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"$ref\":\"#/components/schemas/ContentBlock\"}}}},\"ToolSpec\":{\"type\":\"object\",\"required\":[\"toolSpec\"],\"properties\":{\"toolSpec\":{\"type\":\"object\",\"required\":[\"name\",\"inputSchema\"],\"properties\":{\"name\":{\"type\":\"string\",\"pattern\":\"^[a-zA-Z0-9_-]{1,64}$\"},\"description\":{\"type\":\"string\"},\"inputSchema\":{\"type\":\"object\",\"required\":[\"json\"],\"properties\":{\"json\":{}}}}}}},\"ConverseRequest\":{\"type\":\"object\",\"required\":[\"messages\"],\"properties\":{\"messages\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"$ref\":\"#/components/schemas/Message\"}},\"system\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/TextBlock\"},{\"$ref\":\"#/components/schemas/CachePointBlock\"},{\"$ref\":\"#/components/schemas/GuardContentBlock\"}]}},\"inferenceConfig\":{\"type\":\"object\",\"properties\":{\"maxTokens\":{\"type\":\"integer\",\"minimum\":1},\"temperature\":{\"type\":\"number\",\"minimum\":0,\"maximum\":1},\"topP\":{\"type\":\"number\",\"minimum\":0,\"maximum\":1},\"stopSequences\":{\"type\":\"array\",\"maxItems\":4,\"items\":{\"type\":\"string\"}}}},\"toolConfig\":{\"type\":\"object\",\"required\":[\"tools\"],\"properties\":{\"tools\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ToolSpec\"},{\"$ref\":\"#/components/schemas/CachePointBlock\"}]}},\"toolChoice\":{\"oneOf\":[{\"type\":\"object\",\"required\":[\"auto\"],\"properties\":{\"auto\":{\"type\":\"object\"}}},{\"type\":\"object\",\"required\":[\"any\"],\"properties\":{\"any\":{\"type\":\"object\"}}},{\"type\":\"object\",\"required\":[\"tool\"],\"properties\":{\"tool\":{\"type\":\"object\",\"required\":[\"name\"],\"properties\":{\"name\":{\"type\":\"string\"}}}}}]}}},\"guardrailConfig\":{\"type\":\"object\",\"required\":[\"guardrailIdentifier\",\"guardrailVersion\"],\"properties\":{\"guardrailIdentifier\":{\"type\":\"string\",\"minLength\":1},\"guardrailVersion\":{\"type\":\"string\",\"minLength\":1},\"trace\":{\"type\":\"string\",\"enum\":[\"enabled\",\"disabled\",\"enabled_full\"]},\"streamProcessingMode\":{\"type\":\"string\",\"enum\":[\"sync\",\"async\"]}}},\"additionalModelRequestFields\":{\"type\":\"object\"},\"outputConfig\":{\"type\":\"object\",\"properties\":{\"textFormat\":{\"type\":\"object\",\"required\":[\"type\",\"structure\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"json_schema\"]},\"structure\":{\"type\":\"object\",\"required\":[\"jsonSchema\"],\"properties\":{\"jsonSchema\":{\"type\":\"object\",\"required\":[\"schema\"],\"properties\":{\"schema\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"}}}}}}}}},\"requestMetadata\":{\"type\":\"object\",\"additionalProperties\":{\"type\":\"string\"}},\"performanceConfig\":{\"type\":\"object\",\"properties\":{\"latency\":{\"type\":\"string\",\"enum\":[\"standard\",\"optimized\"]}}}}},\"Usage\":{\"type\":\"object\",\"required\":[\"inputTokens\",\"outputTokens\",\"totalTokens\"],\"properties\":{\"inputTokens\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"outputTokens\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"totalTokens\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"cacheReadInputTokens\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"cacheWriteInputTokens\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}}}},\"ConverseResponse\":{\"type\":\"object\",\"required\":[\"output\",\"stopReason\",\"usage\",\"metrics\"],\"properties\":{\"output\":{\"type\":\"object\",\"required\":[\"message\"],\"properties\":{\"message\":{\"type\":\"object\",\"required\":[\"role\",\"content\"],\"properties\":{\"role\":{\"type\":\"string\",\"enum\":[\"assistant\"]},\"content\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"toolUse\":{\"type\":\"object\",\"required\":[\"toolUseId\",\"name\",\"input\"],\"properties\":{\"toolUseId\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"input\":{\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}}}},\"reasoningContent\":{\"type\":\"object\"}}}}}}}},\"stopReason\":{\"type\":\"string\",\"enum\":[\"end_turn\",\"tool_use\",\"max_tokens\",\"stop_sequence\",\"guardrail_intervened\",\"content_filtered\"]},\"usage\":{\"$ref\":\"#/components/schemas/Usage\"},\"metrics\":{\"type\":\"object\",\"required\":[\"latencyMs\"],\"properties\":{\"latencyMs\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}}}},\"trace\":{\"type\":\"object\",\"properties\":{\"guardrail\":{\"type\":\"object\"}}}}},\"TitanEmbedRequest\":{\"type\":\"object\",\"required\":[\"inputText\"],\"properties\":{\"inputText\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":50000},\"dimensions\":{\"type\":\"integer\",\"enum\":[256,512,1024]},\"normalize\":{\"type\":\"boolean\"},\"embeddingTypes\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"enum\":[\"float\",\"binary\"]}}}},\"TitanEmbedResponse\":{\"type\":\"object\",\"required\":[\"embedding\",\"inputTextTokenCount\"],\"properties\":{\"embedding\":{\"type\":\"array\",\"items\":{\"type\":\"number\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}}},\"inputTextTokenCount\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"embeddingsByType\":{\"type\":\"object\"}}},\"AnthropicRequest\":{\"type\":\"object\",\"required\":[\"anthropic_version\",\"max_tokens\",\"messages\"],\"properties\":{\"anthropic_version\":{\"type\":\"string\",\"enum\":[\"bedrock-2023-05-31\"]},\"max_tokens\":{\"type\":\"integer\",\"minimum\":1},\"temperature\":{\"type\":\"number\",\"minimum\":0,\"maximum\":1},\"system\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"array\",\"items\":{\"type\":\"object\"}}]},\"messages\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"type\":\"object\",\"required\":[\"role\",\"content\"],\"properties\":{\"role\":{\"type\":\"string\",\"enum\":[\"user\",\"assistant\"]},\"content\":{\"anyOf\":[{\"type\":\"string\",\"minLength\":1},{\"type\":\"array\",\"minItems\":1,\"items\":{\"type\":\"object\",\"required\":[\"type\"]}}]}}}}}},\"AnthropicResponse\":{\"type\":\"object\",\"required\":[\"id\",\"type\",\"role\",\"model\",\"content\",\"stop_reason\",\"usage\"],\"properties\":{\"id\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"type\":{\"type\":\"string\",\"enum\":[\"message\"]},\"role\":{\"type\":\"string\",\"enum\":[\"assistant\"]},\"model\":{\"type\":\"string\"},\"content\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"type\"],\"properties\":{\"type\":{\"type\":\"string\"},\"text\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}}}}},\"stop_reason\":{\"type\":\"string\"},\"stop_sequence\":{\"type\":[\"string\",\"null\"]},\"usage\":{\"type\":\"object\",\"required\":[\"input_tokens\",\"output_tokens\"],\"properties\":{\"input_tokens\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"output_tokens\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}}}}}},\"HarnessRequest\":{\"type\":\"object\",\"required\":[\"messages\"],\"properties\":{\"messages\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"type\":\"object\",\"required\":[\"role\",\"content\"],\"properties\":{\"role\":{\"type\":\"string\",\"enum\":[\"user\",\"assistant\"]},\"content\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"$ref\":\"#/components/schemas/ContentBlock\"}}}}},\"systemPrompt\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/TextBlock\"}},\"maxIterations\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":50}}}}}}`) as OpenAPIDocument\n\nexport type OperationId = \"Converse\" | \"ConverseStream\" | \"InvokeModel\" | \"InvokeModelWithResponseStream\" | \"InvokeModelWithBidirectionalStream\" | \"InvokeHarness\"\nexport type SupportedOperationId = \"Converse\" | \"ConverseStream\" | \"InvokeModel\" | \"InvokeModelWithBidirectionalStream\" | \"InvokeHarness\"\nexport const operationIds = [\"Converse\",\"ConverseStream\",\"InvokeModel\",\"InvokeModelWithResponseStream\",\"InvokeModelWithBidirectionalStream\",\"InvokeHarness\"] as const\nexport const supportedOperationIds = [\"Converse\",\"ConverseStream\",\"InvokeModel\",\"InvokeModelWithBidirectionalStream\",\"InvokeHarness\"] as const\n", "/**\n * The smallest instance of a JSON Schema: what an unscripted structured-output call\n * answers with. The model never generates language here, so a caller's schema\n * (`Output.object`, a forced tool's `inputSchema`, `outputConfig.textFormat`) is the only\n * thing that decides the shape, and the object always validates against it.\n *\n * Handles what zod-to-json-schema, the AI SDK and hand-written tool schemas emit: `type`\n * (including `[\"string\",\"null\"]`), `enum`, `const`, `anyOf`/`oneOf`/`allOf`, `$ref` into\n * `definitions`/`$defs`, required properties, array bounds and `uniqueItems`, string\n * lengths and common formats, and numeric bounds.\n */\n\ntype Schema = Record<string, unknown>\n\nconst isSchema = (value: unknown): value is Schema =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst FORMATS: Record<string, string> = {\n \"date-time\": \"2026-01-01T00:00:00.000Z\",\n date: \"2026-01-01\",\n time: \"00:00:00\",\n email: \"user@example.com\",\n uri: \"https://example.com/\",\n url: \"https://example.com/\",\n uuid: \"00000000-0000-4000-8000-000000000000\",\n ipv4: \"127.0.0.1\",\n}\n\nconst resolveRef = (root: Schema, ref: string): Schema | undefined => {\n if (!ref.startsWith(\"#\")) return undefined\n let node: unknown = root\n for (const part of ref.slice(1).split(\"/\").filter(Boolean)) {\n if (!isSchema(node)) return undefined\n node = node[decodeURIComponent(part.replace(/~1/g, \"/\").replace(/~0/g, \"~\"))]\n }\n return isSchema(node) ? node : undefined\n}\n\nconst typesOf = (schema: Schema): string[] => {\n if (Array.isArray(schema.type))\n return schema.type.filter((t): t is string => typeof t === \"string\")\n if (typeof schema.type === \"string\") return [schema.type]\n if (isSchema(schema.properties) || Array.isArray(schema.required)) return [\"object\"]\n if (schema.items !== undefined) return [\"array\"]\n return []\n}\n\nconst sampleNumber = (schema: Schema, integer: boolean): number => {\n const min = typeof schema.minimum === \"number\" ? schema.minimum : undefined\n const exclusiveMin =\n typeof schema.exclusiveMinimum === \"number\"\n ? schema.exclusiveMinimum\n : schema.exclusiveMinimum === true && min !== undefined\n ? min\n : undefined\n const max = typeof schema.maximum === \"number\" ? schema.maximum : undefined\n const exclusiveMax =\n typeof schema.exclusiveMaximum === \"number\" ? schema.exclusiveMaximum : undefined\n let value = 0\n if (exclusiveMin !== undefined)\n value = integer\n ? Math.floor(exclusiveMin) + 1\n : exclusiveMin + (max !== undefined ? Math.min(1, (max - exclusiveMin) / 2) : 1)\n else if (min !== undefined) value = integer ? Math.ceil(min) : min\n else if (max !== undefined && max < 0) value = integer ? Math.floor(max) : max\n else if (exclusiveMax !== undefined && exclusiveMax <= 0)\n value = integer ? Math.ceil(exclusiveMax) - 1 : exclusiveMax - 1\n if (typeof schema.multipleOf === \"number\" && schema.multipleOf > 0) {\n value = Math.ceil(value / schema.multipleOf) * schema.multipleOf\n }\n return value\n}\n\nconst sampleString = (schema: Schema): string => {\n const format = typeof schema.format === \"string\" ? FORMATS[schema.format] : undefined\n let value = format ?? \"\"\n const min = typeof schema.minLength === \"number\" ? schema.minLength : 0\n if (!format && typeof schema.pattern === \"string\") {\n // A pattern we cannot invert: try a few plain candidates before giving up.\n const pattern = new RegExp(schema.pattern)\n value =\n [\"x\", \"a\", \"A\", \"0\", \"a1\", \"x\".repeat(Math.max(1, min))].find((c) => pattern.test(c)) ?? \"x\"\n }\n while (value.length < min) value += \"x\"\n if (typeof schema.maxLength === \"number\" && value.length > schema.maxLength) {\n value = value.slice(0, schema.maxLength)\n }\n return value\n}\n\n/** A value that validates against `schema` (resolved against `root` for `$ref`s). */\nexport const sampleSchema = (schema: unknown, root: unknown = schema, depth = 0): unknown => {\n if (!isSchema(schema) || depth > 32) return null\n const rootSchema = isSchema(root) ? root : {}\n if (typeof schema.$ref === \"string\") {\n return sampleSchema(resolveRef(rootSchema, schema.$ref), rootSchema, depth + 1)\n }\n if (\"const\" in schema) return schema.const\n if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0]\n if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {\n const merged: Schema = { ...schema }\n delete merged.allOf\n for (const part of schema.allOf) {\n const resolved =\n isSchema(part) && typeof part.$ref === \"string\" ? resolveRef(rootSchema, part.$ref) : part\n if (!isSchema(resolved)) continue\n for (const [key, value] of Object.entries(resolved)) {\n if (key === \"properties\" && isSchema(merged.properties) && isSchema(value)) {\n merged.properties = { ...merged.properties, ...value }\n } else if (key === \"required\" && Array.isArray(merged.required) && Array.isArray(value)) {\n merged.required = [...new Set([...merged.required, ...value])]\n } else merged[key] = value\n }\n }\n return sampleSchema(merged, rootSchema, depth + 1)\n }\n const union = (\n Array.isArray(schema.anyOf)\n ? schema.anyOf\n : Array.isArray(schema.oneOf)\n ? schema.oneOf\n : undefined\n ) as unknown[] | undefined\n if (union && union.length > 0) {\n // Prefer a concrete branch over `null`, so optional-but-nullable fields still read well.\n const concrete = union.find((branch) => !(isSchema(branch) && branch.type === \"null\"))\n return sampleSchema(concrete ?? union[0], rootSchema, depth + 1)\n }\n const types = typesOf(schema)\n const type = types.find((t) => t !== \"null\") ?? types[0]\n switch (type) {\n case \"object\": {\n const properties = isSchema(schema.properties) ? schema.properties : {}\n const required = Array.isArray(schema.required)\n ? schema.required.filter((key): key is string => typeof key === \"string\")\n : []\n const out: Record<string, unknown> = {}\n for (const key of required)\n out[key] = sampleSchema(properties[key] ?? {}, rootSchema, depth + 1)\n const minProperties = typeof schema.minProperties === \"number\" ? schema.minProperties : 0\n for (const key of Object.keys(properties)) {\n if (Object.keys(out).length >= minProperties) break\n if (!(key in out)) out[key] = sampleSchema(properties[key], rootSchema, depth + 1)\n }\n return out\n }\n case \"array\": {\n const min = typeof schema.minItems === \"number\" ? schema.minItems : 0\n const items = Array.isArray(schema.prefixItems) ? schema.prefixItems : undefined\n const out: unknown[] = []\n for (let i = 0; i < min; i++) {\n const itemSchema =\n items?.[i] ?? (Array.isArray(schema.items) ? schema.items[i] : schema.items)\n let value = sampleSchema(itemSchema ?? {}, rootSchema, depth + 1)\n if (schema.uniqueItems === true && isSchema(itemSchema)) {\n const choices = Array.isArray(itemSchema.enum) ? itemSchema.enum : undefined\n if (choices && choices.length > i) value = choices[i]\n else if (typeof value === \"string\") value = `${value}${i}`\n else if (typeof value === \"number\") value = value + i\n }\n out.push(value)\n }\n return out\n }\n case \"string\":\n return sampleString(schema)\n case \"integer\":\n return sampleNumber(schema, true)\n case \"number\":\n return sampleNumber(schema, false)\n case \"boolean\":\n return false\n case \"null\":\n return null\n default:\n return {}\n }\n}\n", "/**\n * The scripting model: the mock never generates language, it replays scripts.\n *\n * A script is a `match` (which model calls it answers) and a sequence of `turns`. The turn\n * a call gets is read off the conversation itself, not from server state: it is the number\n * of assistant messages since the member last said something (a user message with any\n * content other than tool results). So the first call of a user turn gets turn 0, the call\n * that resumes after a `toolResult` gets turn 1, and a new conversation starts over \u2014 with\n * no bookkeeping that parallel workers or retries could skew.\n *\n * Only metadata is derived from a request (tool names, flags, a SHA-256 of the system\n * prompt); prompt and message text are read for matching and never stored.\n */\n\n/** Operations a script can answer. */\nexport const MODEL_OPERATIONS = [\n \"Converse\",\n \"ConverseStream\",\n \"InvokeModel\",\n \"InvokeModelWithBidirectionalStream\",\n \"InvokeHarness\",\n] as const\nexport type ModelOperation = (typeof MODEL_OPERATIONS)[number]\n\nexport const STOP_REASONS = [\n \"end_turn\",\n \"tool_use\",\n \"max_tokens\",\n \"stop_sequence\",\n \"guardrail_intervened\",\n \"content_filtered\",\n] as const\nexport type StopReason = (typeof STOP_REASONS)[number]\n\n/** Failure modes a turn (or a fault preset) can inject. */\nexport const TURN_FAULTS = [\n \"throttling\",\n \"validation\",\n \"access_denied\",\n \"model_timeout\",\n \"service_unavailable\",\n \"internal_server\",\n \"mid_stream_exception\",\n \"max_tokens\",\n \"truncated_frame\",\n \"latency\",\n] as const\nexport type TurnFaultType = (typeof TURN_FAULTS)[number]\n\nexport type TurnFault = {\n type: TurnFaultType\n /** Error / exception message. Each type has a realistic default. */\n message?: string\n /** `mid_stream_exception` / `truncated_frame`: content chunks sent before the failure. Default 1. */\n afterChunks?: number\n /** `mid_stream_exception`: the exception frame's type. Default `modelStreamErrorException`. */\n exceptionType?: string\n /** `latency`: mock-clock milliseconds before the response starts. */\n latencyMs?: number\n}\n\nexport type ScriptToolUse = {\n name: string\n input?: unknown\n /** Default: a deterministic `tooluse_\u2026` id. */\n toolUseId?: string\n}\n\nexport type ScriptUsage = {\n inputTokens?: number\n outputTokens?: number\n totalTokens?: number\n cacheReadInputTokens?: number\n cacheWriteInputTokens?: number\n}\n\nexport type ScriptTurn = {\n /** Assistant text, streamed in `chunkSize`-character deltas. */\n text?: string\n chunkSize?: number\n /** Mock-clock delay before each streamed chunk (TTFT and pacing tests). */\n delayMsPerChunk?: number\n /** Reasoning text streamed as `reasoningContent` before the answer. */\n reasoning?: string\n toolUse?: ScriptToolUse | ScriptToolUse[]\n /** Structured output, rendered in whichever form the request asked for. */\n json?: unknown\n stopReason?: StopReason\n /** `true`, or the trace / blocked text, for a `guardrail_intervened` turn. */\n guardrail?: boolean | { text?: string; trace?: unknown }\n usage?: ScriptUsage\n /** This turn only answers a call whose last user message carries this tool's result. */\n expectToolResult?: { name: string }\n fault?: TurnFaultType | TurnFault\n /** Nova Sonic: the ASR transcript echoed back for a spoken user turn. */\n userTranscript?: string\n /** AgentCore InvokeHarness: a tool-result delta (`[{text}|{json}]`) instead of text. */\n toolResult?: unknown[]\n}\n\nexport type TextMatch = { contains?: string; regex?: string; flags?: string }\n\nexport type ScriptMatch = {\n /** Glob (`*` wildcard, case-insensitive) over the decoded model id, ARN or harness ARN. */\n modelId?: string\n operation?: ModelOperation | ModelOperation[]\n lastUserText?: string | TextMatch\n /** SHA-256 hex of the system prompt (text blocks joined with \"\\n\"). */\n systemHash?: string\n toolsInclude?: string[]\n /** `auto`, `any`, `none`, or a forced tool's name. */\n toolChoice?: string\n hasDocument?: boolean\n hasImage?: boolean\n /** 0-based index of this call among the namespace's model calls. */\n callIndex?: number\n}\n\nexport type Script = {\n id: string\n match?: ScriptMatch\n turns: ScriptTurn[]\n /** Stop matching after this many calls (counted per namespace). */\n times?: number\n}\n\n/** What a model call looks like to the matcher. Never stored or logged. */\nexport type CallAnalysis = {\n operation: ModelOperation\n modelId: string\n lastUserText: string\n systemText: string\n tools: string[]\n toolSchemas: Record<string, unknown>\n /** `auto` | `any` | `none` | `tool:<name>` | undefined. */\n toolChoice: string | undefined\n hasDocument: boolean\n hasImage: boolean\n hasCachePoint: boolean\n hasGuardrail: boolean\n /** Tool names whose results the last user message carries. */\n toolResults: string[]\n turnIndex: number\n structured: StructuredRequest | undefined\n /** Characters of input, for deterministic token estimates. */\n inputChars: number\n}\n\n/** How a request asked for structured output. */\nexport type StructuredRequest =\n | { form: \"outputConfig\"; schema: unknown; name?: string }\n | { form: \"outputFormat\"; schema: unknown }\n | { form: \"tool\"; tool: string; schema: unknown }\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst escapeGlob = (value: string) =>\n new RegExp(\n `^${value\n .split(\"*\")\n .map((part) => part.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n .join(\".*\")}$`,\n \"i\",\n )\n\n/** Whether `modelId` matches the glob `pattern`. */\nexport const globMatch = (pattern: string, modelId: string): boolean =>\n escapeGlob(pattern).test(modelId)\n\nconst textMatches = (rule: string | TextMatch, value: string): boolean => {\n if (typeof rule === \"string\") return value.toLowerCase().includes(rule.toLowerCase())\n if (rule.contains !== undefined && !value.toLowerCase().includes(rule.contains.toLowerCase())) {\n return false\n }\n if (rule.regex !== undefined && !new RegExp(rule.regex, rule.flags ?? \"i\").test(value))\n return false\n return true\n}\n\n/** Whether a script's `match` accepts this call (turn selection is separate). */\nexport const matches = (\n match: ScriptMatch | undefined,\n call: CallAnalysis,\n context: { systemHash: string; callIndex: number },\n): boolean => {\n if (!match) return true\n if (match.modelId !== undefined && !globMatch(match.modelId, call.modelId)) return false\n if (match.operation !== undefined) {\n const ops = Array.isArray(match.operation) ? match.operation : [match.operation]\n if (!ops.includes(call.operation)) return false\n }\n if (match.lastUserText !== undefined && !textMatches(match.lastUserText, call.lastUserText)) {\n return false\n }\n if (match.systemHash !== undefined && match.systemHash.toLowerCase() !== context.systemHash) {\n return false\n }\n if (match.toolsInclude?.some((name) => !call.tools.includes(name))) return false\n if (match.toolChoice !== undefined) {\n const want = [\"auto\", \"any\", \"none\"].includes(match.toolChoice)\n ? match.toolChoice\n : `tool:${match.toolChoice}`\n if ((call.toolChoice ?? \"auto\") !== want) return false\n }\n if (match.hasDocument !== undefined && match.hasDocument !== call.hasDocument) return false\n if (match.hasImage !== undefined && match.hasImage !== call.hasImage) return false\n if (match.callIndex !== undefined && match.callIndex !== context.callIndex) return false\n return true\n}\n\n/** The turn a matching script plays for this call, or `undefined` when it has none left. */\nexport const selectTurn = (script: Script, call: CallAnalysis): ScriptTurn | undefined => {\n const turn = script.turns[call.turnIndex]\n if (!turn) return undefined\n if (turn.expectToolResult && !call.toolResults.includes(turn.expectToolResult.name)) {\n return undefined\n }\n return turn\n}\n\n// \u2500\u2500 validation of PUT /__admin/scripts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst fail = (path: string, message: string) => `${path}: ${message}`\n\nconst checkTurn = (turn: unknown, path: string): string | undefined => {\n if (!isRecord(turn)) return fail(path, \"a turn is an object\")\n const known = new Set([\n \"text\",\n \"chunkSize\",\n \"delayMsPerChunk\",\n \"reasoning\",\n \"toolUse\",\n \"json\",\n \"stopReason\",\n \"guardrail\",\n \"usage\",\n \"expectToolResult\",\n \"fault\",\n \"userTranscript\",\n \"toolResult\",\n ])\n for (const key of Object.keys(turn)) {\n if (!known.has(key)) return fail(`${path}.${key}`, \"unknown turn field\")\n }\n if (turn.text !== undefined && typeof turn.text !== \"string\")\n return fail(`${path}.text`, \"string\")\n for (const key of [\"chunkSize\", \"delayMsPerChunk\"] as const) {\n const value = turn[key]\n if (\n value !== undefined &&\n (typeof value !== \"number\" || value < (key === \"chunkSize\" ? 1 : 0))\n ) {\n return fail(`${path}.${key}`, key === \"chunkSize\" ? \"a positive number\" : \"ms \u2265 0\")\n }\n }\n if (turn.toolUse !== undefined) {\n const uses = Array.isArray(turn.toolUse) ? turn.toolUse : [turn.toolUse]\n for (const [i, use] of uses.entries()) {\n if (!isRecord(use) || typeof use.name !== \"string\" || use.name === \"\") {\n return fail(`${path}.toolUse[${i}]`, \"needs a name\")\n }\n }\n }\n if (turn.stopReason !== undefined && !STOP_REASONS.includes(turn.stopReason as StopReason)) {\n return fail(`${path}.stopReason`, `one of ${STOP_REASONS.join(\", \")}`)\n }\n if (turn.fault !== undefined) {\n const type = isRecord(turn.fault) ? turn.fault.type : turn.fault\n if (!TURN_FAULTS.includes(type as TurnFaultType)) {\n return fail(`${path}.fault`, `one of ${TURN_FAULTS.join(\", \")}`)\n }\n }\n if (turn.toolResult !== undefined && !Array.isArray(turn.toolResult)) {\n return fail(`${path}.toolResult`, \"an array of {text} | {json}\")\n }\n if (\n turn.expectToolResult !== undefined &&\n !(isRecord(turn.expectToolResult) && typeof turn.expectToolResult.name === \"string\")\n ) {\n return fail(`${path}.expectToolResult`, \"{name}\")\n }\n return undefined\n}\n\n/** Parse and validate one script; a string is the first problem found. */\nexport const parseScript = (value: unknown, index: number): Script | string => {\n const path = `scripts[${index}]`\n if (!isRecord(value)) return fail(path, \"a script is an object\")\n if (typeof value.id !== \"string\" || value.id === \"\")\n return fail(`${path}.id`, \"a non-empty string\")\n if (!Array.isArray(value.turns) || value.turns.length === 0) {\n return fail(`${path}.turns`, \"a non-empty array\")\n }\n for (const [i, turn] of value.turns.entries()) {\n const problem = checkTurn(turn, `${path}.turns[${i}]`)\n if (problem) return problem\n }\n if (value.match !== undefined) {\n if (!isRecord(value.match)) return fail(`${path}.match`, \"an object\")\n const match = value.match\n if (match.operation !== undefined) {\n const ops = Array.isArray(match.operation) ? match.operation : [match.operation]\n for (const op of ops) {\n if (!MODEL_OPERATIONS.includes(op as ModelOperation)) {\n return fail(`${path}.match.operation`, `one of ${MODEL_OPERATIONS.join(\", \")}`)\n }\n }\n }\n if (isRecord(match.lastUserText) && typeof match.lastUserText.regex === \"string\") {\n try {\n new RegExp(match.lastUserText.regex)\n } catch {\n return fail(`${path}.match.lastUserText.regex`, \"not a valid regular expression\")\n }\n }\n if (match.toolsInclude !== undefined && !Array.isArray(match.toolsInclude)) {\n return fail(`${path}.match.toolsInclude`, \"string[]\")\n }\n }\n if (value.times !== undefined && (typeof value.times !== \"number\" || value.times < 1)) {\n return fail(`${path}.times`, \"a positive count\")\n }\n return value as Script\n}\n\n/** The fault a turn carries, normalised. */\nexport const turnFault = (turn: ScriptTurn | undefined): TurnFault | undefined => {\n if (!turn?.fault) return undefined\n return typeof turn.fault === \"string\" ? { type: turn.fault } : turn.fault\n}\n", "/**\n * From a matched script turn (or the unscripted default) to a concrete answer: the content\n * blocks, stop reason, usage and trace, and the fault to inject. Rendering into Converse\n * JSON, event-stream frames, an Anthropic Messages body or harness events happens in\n * `render.ts`; this module decides *what* the model says, independent of the wire.\n */\nimport { sampleSchema } from \"./schema-sample.js\"\nimport type { CallAnalysis, ScriptTurn, ScriptUsage, StopReason, TurnFault } from \"./scripts.js\"\nimport { turnFault } from \"./scripts.js\"\n\nexport type PlanBlock =\n | { kind: \"text\"; text: string }\n | { kind: \"reasoning\"; text: string }\n | { kind: \"toolUse\"; toolUseId: string; name: string; input: unknown }\n | { kind: \"toolResult\"; toolUseId: string; content: unknown[] }\n\nexport type Usage = {\n inputTokens: number\n outputTokens: number\n totalTokens: number\n cacheReadInputTokens?: number\n cacheWriteInputTokens?: number\n}\n\nexport type Plan = {\n /** The script that answered, or `undefined` for the unscripted default. */\n scriptId: string | undefined\n /** Which default answered, when unscripted: `chat`, `structured`, `classifier`, `scribe`, `titan`, `harness`, `sonic`. */\n fallback?: string\n blocks: PlanBlock[]\n stopReason: StopReason\n usage: Usage\n trace?: Record<string, unknown>\n fault?: TurnFault\n chunkSize: number\n delayMsPerChunk: number\n userTranscript?: string\n}\n\n/** Bedrock's canned guardrail refusal. */\nexport const GUARDRAIL_BLOCKED_TEXT = \"Sorry, the model cannot answer this question.\"\n\n/** What an unscripted chat call says. Deliberately content-free (never an echo). */\nexport const DEFAULT_CHAT_TEXT = \"OK.\"\n\nexport const DEFAULT_CLASSIFIER = { category: \"general\", confidence: 0.9 }\n\nexport const DEFAULT_SOAP_NOTE = {\n sections: [\n {\n title: \"Subjective\",\n content: \"Patient reports no new concerns. [UNCERTAIN] Mock transcript.\",\n },\n { title: \"Objective\", content: \"No examination findings discussed.\" },\n {\n title: \"Assessment\",\n content: \"Stable. [UNCERTAIN] Generated by the Mockingbird Bedrock mock.\",\n },\n { title: \"Plan\", content: \"Continue current plan; follow up as scheduled.\" },\n ],\n summary: \"Routine follow-up visit with no new concerns (mock note).\",\n}\n\nconst tokens = (chars: number) => Math.max(1, Math.ceil(chars / 4))\n\nconst defaultTrace = (guardrailId: string | undefined): Record<string, unknown> => ({\n guardrail: {\n actionReason: \"Guardrail blocked.\",\n inputAssessment: {\n [guardrailId ?? \"mock-guardrail\"]: {\n topicPolicy: {\n topics: [{ name: \"Medical Advice\", type: \"DENY\", action: \"BLOCKED\", detected: true }],\n },\n invocationMetrics: {\n guardrailProcessingLatency: 120,\n usage: {\n topicPolicyUnits: 1,\n contentPolicyUnits: 0,\n wordPolicyUnits: 0,\n sensitiveInformationPolicyUnits: 0,\n sensitiveInformationPolicyFreeUnits: 0,\n contextualGroundingPolicyUnits: 0,\n },\n guardrailCoverage: { textCharacters: { guarded: 1, total: 1 } },\n },\n },\n },\n },\n})\n\nexport type PlanContext = {\n /** Deterministic tool-use ids. */\n nextToolUseId: () => string\n chunkSize: number\n delayMsPerChunk: number\n guardrailId?: string\n traceEnabled: boolean\n /** `inferenceConfig.maxTokens` (or `max_tokens`), when the caller capped output. */\n maxTokens?: number\n}\n\nconst withUsage = (\n call: CallAnalysis,\n blocks: PlanBlock[],\n scripted: ScriptUsage | undefined,\n): Usage => {\n const outputChars = blocks.reduce(\n (sum, block) =>\n sum +\n (block.kind === \"toolUse\"\n ? JSON.stringify(block.input ?? {}).length\n : block.kind === \"toolResult\"\n ? JSON.stringify(block.content).length\n : block.text.length),\n 0,\n )\n const inputTokens = scripted?.inputTokens ?? tokens(call.inputChars)\n const outputTokens = scripted?.outputTokens ?? tokens(outputChars)\n return {\n inputTokens,\n outputTokens,\n totalTokens: scripted?.totalTokens ?? inputTokens + outputTokens,\n ...(scripted?.cacheReadInputTokens !== undefined || call.hasCachePoint\n ? { cacheReadInputTokens: scripted?.cacheReadInputTokens ?? 0 }\n : {}),\n ...(scripted?.cacheWriteInputTokens !== undefined || call.hasCachePoint\n ? { cacheWriteInputTokens: scripted?.cacheWriteInputTokens ?? 0 }\n : {}),\n }\n}\n\n/** Structured output rendered in the form the request asked for. */\nconst renderJson = (\n call: CallAnalysis,\n value: unknown,\n context: PlanContext,\n): { blocks: PlanBlock[]; stopReason: StopReason } => {\n const structured = call.structured\n if (structured?.form === \"tool\") {\n return {\n blocks: [\n {\n kind: \"toolUse\",\n toolUseId: context.nextToolUseId(),\n name: structured.tool,\n input: value,\n },\n ],\n stopReason: \"tool_use\",\n }\n }\n return { blocks: [{ kind: \"text\", text: JSON.stringify(value) }], stopReason: \"end_turn\" }\n}\n\n/** Apply a `maxTokens` cap: text beyond it is cut and the stop reason becomes `max_tokens`. */\nconst capOutput = (\n blocks: PlanBlock[],\n stopReason: StopReason,\n maxTokens: number | undefined,\n force: boolean,\n) => {\n const budget = force ? undefined : maxTokens !== undefined ? maxTokens * 4 : undefined\n const texts = blocks.filter((b): b is PlanBlock & { kind: \"text\" } => b.kind === \"text\")\n const length = texts.reduce((sum, b) => sum + b.text.length, 0)\n if (!force && (budget === undefined || length <= budget)) return { blocks, stopReason }\n let remaining = force ? Math.max(1, Math.floor(length / 2)) : (budget as number)\n const out: PlanBlock[] = []\n for (const block of blocks) {\n if (block.kind === \"toolUse\" || block.kind === \"toolResult\") continue\n if (block.kind === \"reasoning\") {\n out.push(block)\n continue\n }\n if (remaining <= 0) break\n out.push({ kind: \"text\", text: block.text.slice(0, remaining) })\n remaining -= block.text.length\n }\n return { blocks: out, stopReason: \"max_tokens\" as StopReason }\n}\n\n/** The plan for a scripted turn. */\nexport const planTurn = (\n scriptId: string,\n turn: ScriptTurn,\n call: CallAnalysis,\n context: PlanContext,\n): Plan => {\n let blocks: PlanBlock[] = []\n let stopReason: StopReason | undefined\n let trace: Record<string, unknown> | undefined\n if (turn.reasoning) blocks.push({ kind: \"reasoning\", text: turn.reasoning })\n if (turn.guardrail) {\n const detail = typeof turn.guardrail === \"object\" ? turn.guardrail : {}\n blocks.push({ kind: \"text\", text: detail.text ?? GUARDRAIL_BLOCKED_TEXT })\n stopReason = \"guardrail_intervened\"\n if (context.traceEnabled || detail.trace !== undefined) {\n trace =\n (detail.trace as Record<string, unknown> | undefined) ?? defaultTrace(context.guardrailId)\n }\n } else {\n if (turn.text !== undefined) blocks.push({ kind: \"text\", text: turn.text })\n if (turn.json !== undefined) {\n const rendered = renderJson(call, turn.json, context)\n blocks.push(...rendered.blocks)\n stopReason = rendered.stopReason\n }\n if (turn.toolResult !== undefined) {\n blocks.push({\n kind: \"toolResult\",\n toolUseId: context.nextToolUseId(),\n content: turn.toolResult,\n })\n }\n const uses =\n turn.toolUse === undefined ? [] : Array.isArray(turn.toolUse) ? turn.toolUse : [turn.toolUse]\n for (const use of uses) {\n blocks.push({\n kind: \"toolUse\",\n toolUseId: use.toolUseId ?? context.nextToolUseId(),\n name: use.name,\n input: use.input ?? {},\n })\n stopReason = \"tool_use\"\n }\n }\n const fault = turnFault(turn)\n const capped = capOutput(\n blocks,\n turn.stopReason ?? stopReason ?? \"end_turn\",\n context.maxTokens,\n fault?.type === \"max_tokens\",\n )\n blocks = capped.blocks\n return {\n scriptId,\n blocks,\n stopReason: turn.stopReason ?? capped.stopReason,\n usage: withUsage(call, blocks, turn.usage),\n ...(trace ? { trace } : {}),\n ...(fault && fault.type !== \"max_tokens\" ? { fault } : {}),\n chunkSize: turn.chunkSize ?? context.chunkSize,\n delayMsPerChunk: turn.delayMsPerChunk ?? context.delayMsPerChunk,\n ...(turn.userTranscript !== undefined ? { userTranscript: turn.userTranscript } : {}),\n }\n}\n\n/** Heuristic: our intent classifier's system prompt asks for this exact shape. */\nconst isClassifier = (call: CallAnalysis) =>\n call.systemText.includes('\"category\"') && call.systemText.includes('\"confidence\"')\n\n/** The unscripted answer: echo-free text, or a schema-valid minimal object. */\nexport const planDefault = (\n call: CallAnalysis,\n context: PlanContext,\n defaultText: string,\n): Plan => {\n let blocks: PlanBlock[]\n let stopReason: StopReason = \"end_turn\"\n let fallback = \"chat\"\n if (call.structured) {\n const value = sampleSchema(call.structured.schema ?? {})\n const rendered = renderJson(call, value, context)\n blocks = rendered.blocks\n stopReason = rendered.stopReason\n fallback = \"structured\"\n } else if (call.operation === \"InvokeModel\") {\n blocks = [{ kind: \"text\", text: JSON.stringify(DEFAULT_SOAP_NOTE) }]\n fallback = \"scribe\"\n } else if (isClassifier(call)) {\n blocks = [{ kind: \"text\", text: JSON.stringify(DEFAULT_CLASSIFIER) }]\n fallback = \"classifier\"\n } else {\n blocks = [{ kind: \"text\", text: defaultText }]\n }\n const capped = capOutput(blocks, stopReason, context.maxTokens, false)\n return {\n scriptId: undefined,\n fallback,\n blocks: capped.blocks,\n stopReason: capped.stopReason,\n usage: withUsage(call, capped.blocks, undefined),\n chunkSize: context.chunkSize,\n delayMsPerChunk: context.delayMsPerChunk,\n }\n}\n\n/** Cut a plan's text in half and stop with `max_tokens` (the `max_tokens` fault preset). */\nexport const truncatePlan = (plan: Plan): Plan => {\n const capped = capOutput(plan.blocks, plan.stopReason, undefined, true)\n return { ...plan, blocks: capped.blocks, stopReason: capped.stopReason }\n}\n\n/** Split `text` into `size`-character chunks (at least one, possibly empty). */\nexport const chunk = (text: string, size: number): string[] => {\n if (text.length === 0) return [\"\"]\n const out: string[] = []\n for (let i = 0; i < text.length; i += Math.max(1, size))\n out.push(text.slice(i, i + Math.max(1, size)))\n return out\n}\n", "/**\n * AWS event-stream framing (`application/vnd.amazon.eventstream`), both directions.\n *\n * Every frame is: a 12-byte prelude (total length, headers length, CRC32 of those 8 bytes),\n * the headers, the payload, and a CRC32 of everything before it. `@smithy/eventstream-codec`\n * (the AWS SDKs and the AI SDK) rejects a frame whose lengths or checksums are off by one\n * byte, so this module is exact: it is the only place a frame is built or parsed.\n *\n * The same codec reads what an SDK sends on a bidirectional stream. Those frames arrive\n * wrapped in a SigV4 envelope (`:date` + `:chunk-signature` headers around the encoded\n * inner frame); {@link unwrapSigned} opens it. The signature itself is never verified.\n */\n\n/** A typed header value; plain strings encode as type 7 (string). */\nexport type HeaderValue =\n | { type: \"boolean\"; value: boolean }\n | { type: \"byte\"; value: number }\n | { type: \"short\"; value: number }\n | { type: \"integer\"; value: number }\n | { type: \"long\"; value: bigint }\n | { type: \"binary\"; value: Uint8Array }\n | { type: \"string\"; value: string }\n | { type: \"timestamp\"; value: Date }\n | { type: \"uuid\"; value: string }\n\nexport type EventStreamMessage = {\n headers: Record<string, HeaderValue>\n body: Uint8Array\n}\n\n/** What {@link encodeMessage} accepts: header values may be bare strings. */\nexport type MessageInput = {\n headers: Record<string, HeaderValue | string>\n body?: Uint8Array | string\n}\n\nexport class EventStreamError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"EventStreamError\"\n }\n}\n\nconst PRELUDE = 12\nconst TRAILER = 4\nconst utf8 = new TextEncoder()\nconst text = new TextDecoder()\n\nconst CRC_TABLE = (() => {\n const table = new Uint32Array(256)\n for (let n = 0; n < 256; n++) {\n let c = n\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1\n table[n] = c >>> 0\n }\n return table\n})()\n\n/** CRC-32 (IEEE 802.3, the one event-stream uses) of `bytes`. */\nexport const crc32 = (bytes: Uint8Array): number => {\n let crc = 0xffffffff\n for (let i = 0; i < bytes.length; i++) {\n crc = (CRC_TABLE[(crc ^ (bytes[i] as number)) & 0xff] as number) ^ (crc >>> 8)\n }\n return (crc ^ 0xffffffff) >>> 0\n}\n\nconst toBytes = (body: Uint8Array | string | undefined): Uint8Array =>\n body === undefined ? new Uint8Array(0) : typeof body === \"string\" ? utf8.encode(body) : body\n\nconst encodeHeaders = (headers: Record<string, HeaderValue | string>): Uint8Array => {\n const parts: Uint8Array[] = []\n for (const [name, raw] of Object.entries(headers)) {\n const header: HeaderValue = typeof raw === \"string\" ? { type: \"string\", value: raw } : raw\n const nameBytes = utf8.encode(name)\n if (nameBytes.length > 255) throw new EventStreamError(`header name too long: ${name}`)\n let value: Uint8Array\n switch (header.type) {\n case \"boolean\":\n value = Uint8Array.of(header.value ? 0 : 1)\n break\n case \"byte\":\n value = Uint8Array.of(2, header.value & 0xff)\n break\n case \"short\": {\n value = new Uint8Array(3)\n value[0] = 3\n new DataView(value.buffer).setInt16(1, header.value, false)\n break\n }\n case \"integer\": {\n value = new Uint8Array(5)\n value[0] = 4\n new DataView(value.buffer).setInt32(1, header.value, false)\n break\n }\n case \"long\": {\n value = new Uint8Array(9)\n value[0] = 5\n new DataView(value.buffer).setBigInt64(1, header.value, false)\n break\n }\n case \"binary\":\n case \"string\": {\n const bytes = header.type === \"binary\" ? header.value : utf8.encode(header.value)\n if (bytes.length > 0xffff) throw new EventStreamError(`header ${name} value too long`)\n value = new Uint8Array(3 + bytes.length)\n value[0] = header.type === \"binary\" ? 6 : 7\n new DataView(value.buffer).setUint16(1, bytes.length, false)\n value.set(bytes, 3)\n break\n }\n case \"timestamp\": {\n value = new Uint8Array(9)\n value[0] = 8\n new DataView(value.buffer).setBigInt64(1, BigInt(header.value.getTime()), false)\n break\n }\n case \"uuid\": {\n const hex = header.value.replace(/-/g, \"\")\n if (!/^[0-9a-f]{32}$/i.test(hex)) throw new EventStreamError(`bad uuid header ${name}`)\n value = new Uint8Array(17)\n value[0] = 9\n for (let i = 0; i < 16; i++) value[i + 1] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)\n break\n }\n }\n const entry = new Uint8Array(1 + nameBytes.length + value.length)\n entry[0] = nameBytes.length\n entry.set(nameBytes, 1)\n entry.set(value, 1 + nameBytes.length)\n parts.push(entry)\n }\n return concat(parts)\n}\n\n/** Concatenate byte arrays. */\nexport const concat = (parts: readonly Uint8Array[]): Uint8Array => {\n const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0))\n let offset = 0\n for (const part of parts) {\n out.set(part, offset)\n offset += part.length\n }\n return out\n}\n\n/** One complete frame: prelude, prelude CRC, headers, payload, message CRC. */\nexport const encodeMessage = (message: MessageInput): Uint8Array => {\n const headers = encodeHeaders(message.headers)\n const body = toBytes(message.body)\n const total = PRELUDE + headers.length + body.length + TRAILER\n const frame = new Uint8Array(total)\n const view = new DataView(frame.buffer)\n view.setUint32(0, total, false)\n view.setUint32(4, headers.length, false)\n view.setUint32(8, crc32(frame.subarray(0, 8)), false)\n frame.set(headers, PRELUDE)\n frame.set(body, PRELUDE + headers.length)\n view.setUint32(total - TRAILER, crc32(frame.subarray(0, total - TRAILER)), false)\n return frame\n}\n\nconst decodeHeaders = (bytes: Uint8Array): Record<string, HeaderValue> => {\n const headers: Record<string, HeaderValue> = {}\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let at = 0\n while (at < bytes.length) {\n const nameLength = bytes[at] as number\n const name = text.decode(bytes.subarray(at + 1, at + 1 + nameLength))\n at += 1 + nameLength\n const type = bytes[at] as number\n at += 1\n switch (type) {\n case 0:\n case 1:\n headers[name] = { type: \"boolean\", value: type === 0 }\n break\n case 2:\n headers[name] = { type: \"byte\", value: view.getInt8(at) }\n at += 1\n break\n case 3:\n headers[name] = { type: \"short\", value: view.getInt16(at, false) }\n at += 2\n break\n case 4:\n headers[name] = { type: \"integer\", value: view.getInt32(at, false) }\n at += 4\n break\n case 5:\n headers[name] = { type: \"long\", value: view.getBigInt64(at, false) }\n at += 8\n break\n case 6:\n case 7: {\n const length = view.getUint16(at, false)\n const value = bytes.slice(at + 2, at + 2 + length)\n headers[name] =\n type === 6 ? { type: \"binary\", value } : { type: \"string\", value: text.decode(value) }\n at += 2 + length\n break\n }\n case 8:\n headers[name] = { type: \"timestamp\", value: new Date(Number(view.getBigInt64(at, false))) }\n at += 8\n break\n case 9: {\n const hex = [...bytes.subarray(at, at + 16)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")\n headers[name] = {\n type: \"uuid\",\n value: `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`,\n }\n at += 16\n break\n }\n default:\n throw new EventStreamError(`unknown header type ${type} for ${name}`)\n }\n }\n return headers\n}\n\n/** Parse exactly one frame, checking both lengths and both checksums. */\nexport const decodeMessage = (frame: Uint8Array): EventStreamMessage => {\n if (frame.length < PRELUDE + TRAILER) throw new EventStreamError(\"frame shorter than a prelude\")\n const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength)\n const total = view.getUint32(0, false)\n const headersLength = view.getUint32(4, false)\n if (total !== frame.length) throw new EventStreamError(`frame length ${frame.length} \u2260 ${total}`)\n if (view.getUint32(8, false) !== crc32(frame.subarray(0, 8))) {\n throw new EventStreamError(\"prelude checksum mismatch\")\n }\n if (view.getUint32(total - TRAILER, false) !== crc32(frame.subarray(0, total - TRAILER))) {\n throw new EventStreamError(\"message checksum mismatch\")\n }\n return {\n headers: decodeHeaders(frame.subarray(PRELUDE, PRELUDE + headersLength)),\n body: frame.slice(PRELUDE + headersLength, total - TRAILER),\n }\n}\n\n/** Splits a byte stream into frames as they complete. */\nexport class FrameReader {\n private buffer: Uint8Array = new Uint8Array(0)\n\n /** Add bytes; returns every frame they complete. */\n push(chunk: Uint8Array): EventStreamMessage[] {\n this.buffer = this.buffer.length === 0 ? chunk.slice() : concat([this.buffer, chunk])\n const out: EventStreamMessage[] = []\n while (this.buffer.length >= 4) {\n const total = new DataView(\n this.buffer.buffer,\n this.buffer.byteOffset,\n this.buffer.byteLength,\n ).getUint32(0, false)\n if (total < PRELUDE + TRAILER) throw new EventStreamError(`impossible frame length ${total}`)\n if (this.buffer.length < total) break\n out.push(decodeMessage(this.buffer.subarray(0, total)))\n this.buffer = this.buffer.slice(total)\n }\n return out\n }\n\n /** Bytes of an incomplete frame still waiting for the rest. */\n get pending(): number {\n return this.buffer.length\n }\n}\n\n/** A header's value as a string, when it is one. */\nexport const headerString = (message: EventStreamMessage, name: string): string | undefined => {\n const header = message.headers[name]\n return header?.type === \"string\" ? header.value : undefined\n}\n\n/**\n * The frame inside a SigV4 event envelope (`:chunk-signature`), `null` for the empty\n * end-of-stream envelope, or the frame itself when it is not signed.\n */\nexport const unwrapSigned = (message: EventStreamMessage): EventStreamMessage | null => {\n if (message.headers[\":chunk-signature\"] === undefined) return message\n if (message.body.length === 0) return null\n return decodeMessage(message.body)\n}\n\n/** An `event` frame whose payload is JSON (or raw bytes, for blob event payloads). */\nexport const eventFrame = (\n eventType: string,\n payload: unknown,\n contentType: string = payload instanceof Uint8Array\n ? \"application/octet-stream\"\n : \"application/json\",\n): Uint8Array =>\n encodeMessage({\n headers: {\n \":event-type\": eventType,\n \":content-type\": contentType,\n \":message-type\": \"event\",\n },\n body: payload instanceof Uint8Array ? payload : JSON.stringify(payload),\n })\n\n/** An `exception` frame, as a service raises one mid-stream. */\nexport const exceptionFrame = (exceptionType: string, body: Record<string, unknown>): Uint8Array =>\n encodeMessage({\n headers: {\n \":exception-type\": exceptionType,\n \":content-type\": \"application/json\",\n \":message-type\": \"exception\",\n },\n body: JSON.stringify(body),\n })\n\n/** Decode a frame's payload as JSON (or `undefined` when it is not JSON). */\nexport const payloadJson = (message: EventStreamMessage): unknown => {\n try {\n return JSON.parse(text.decode(message.body)) as unknown\n } catch {\n return undefined\n }\n}\n\n/** An async iterator over the frames of a byte stream (a request or response body). */\nexport async function* readFrames(\n body: ReadableStream<Uint8Array> | null,\n): AsyncGenerator<EventStreamMessage> {\n if (!body) return\n const reader = new FrameReader()\n const stream = body.getReader()\n try {\n for (;;) {\n const { done, value } = await stream.read()\n if (done) break\n for (const frame of reader.push(value)) yield frame\n }\n } finally {\n stream.releaseLock()\n }\n if (reader.pending > 0) throw new EventStreamError(\"stream ended inside a frame\")\n}\n", "/**\n * Plans on the wire: the Converse JSON body, the ConverseStream event frames, the\n * Anthropic Messages body InvokeModel returns, and the AgentCore harness event frames.\n * Streams pace themselves on the mock clock (`delayMsPerChunk`) and carry the mid-stream\n * faults: an exception frame after N chunks, or a frame cut off half-way.\n */\nimport { eventFrame, exceptionFrame } from \"./eventstream.js\"\nimport { chunk, type Plan, type PlanBlock } from \"./plan.js\"\nimport type { TurnFault } from \"./scripts.js\"\n\n/** Waits `ms` on the mock clock; resolves early when `signal` aborts. */\nexport type Sleep = (ms: number, signal?: AbortSignal) => Promise<void>\n\nconst REASONING_SIGNATURE = \"mock-reasoning-signature\"\n\n/** Converse / ConverseStream content block for a plan block. */\nconst converseBlock = (block: PlanBlock): Record<string, unknown> | undefined => {\n switch (block.kind) {\n case \"text\":\n return { text: block.text }\n case \"reasoning\":\n return {\n reasoningContent: { reasoningText: { text: block.text, signature: REASONING_SIGNATURE } },\n }\n case \"toolUse\":\n return { toolUse: { toolUseId: block.toolUseId, name: block.name, input: block.input } }\n case \"toolResult\":\n return undefined\n }\n}\n\n/** The Converse response body. */\nexport const converseBody = (plan: Plan, latencyMs: number): Record<string, unknown> => ({\n output: {\n message: {\n role: \"assistant\",\n content: plan.blocks.map(converseBlock).filter((b) => b !== undefined),\n },\n },\n stopReason: plan.stopReason,\n usage: plan.usage,\n metrics: { latencyMs },\n ...(plan.trace ? { trace: plan.trace } : {}),\n})\n\n/** The Anthropic Messages body InvokeModel returns for a Claude model. */\nexport const anthropicBody = (\n plan: Plan,\n modelId: string,\n id: string,\n): Record<string, unknown> => ({\n id,\n type: \"message\",\n role: \"assistant\",\n model: modelId,\n content: plan.blocks\n .map((block) => {\n switch (block.kind) {\n case \"text\":\n return { type: \"text\", text: block.text }\n case \"reasoning\":\n return { type: \"thinking\", thinking: block.text, signature: REASONING_SIGNATURE }\n case \"toolUse\":\n return { type: \"tool_use\", id: block.toolUseId, name: block.name, input: block.input }\n default:\n return undefined\n }\n })\n .filter((b) => b !== undefined),\n stop_reason: plan.stopReason === \"guardrail_intervened\" ? \"refusal\" : plan.stopReason,\n stop_sequence: null,\n usage: {\n input_tokens: plan.usage.inputTokens,\n output_tokens: plan.usage.outputTokens,\n ...(plan.usage.cacheReadInputTokens !== undefined\n ? { cache_read_input_tokens: plan.usage.cacheReadInputTokens }\n : {}),\n ...(plan.usage.cacheWriteInputTokens !== undefined\n ? { cache_creation_input_tokens: plan.usage.cacheWriteInputTokens }\n : {}),\n },\n})\n\n/** One streamed unit: either a frame, or a content delta the pacing and faults count. */\ntype Step = { frame: Uint8Array; content: boolean }\n\nconst MESSAGES: Record<string, string> = {\n modelStreamErrorException: \"The model stream encountered an error. Try your request again.\",\n internalServerException:\n \"The system encountered an unexpected error during processing. Try your request again.\",\n throttlingException: \"Too many requests, please wait before trying again.\",\n validationException: \"The input fails to satisfy the constraints specified by the service.\",\n serviceUnavailableException: \"Bedrock is unable to process your request.\",\n runtimeClientError: \"The harness runtime failed while processing the request.\",\n}\n\n/**\n * Turn frames into a response body: waits `delayMsPerChunk` on the mock clock before each\n * content delta, and applies a mid-stream fault once `afterChunks` deltas went out.\n */\nexport const paced = (\n steps: Step[],\n options: {\n sleep: Sleep\n delayMsPerChunk: number\n fault: TurnFault | undefined\n defaultException: string\n signal?: AbortSignal\n },\n): ReadableStream<Uint8Array> => {\n const fault =\n options.fault?.type === \"mid_stream_exception\" || options.fault?.type === \"truncated_frame\"\n ? options.fault\n : undefined\n const after = fault?.afterChunks ?? 1\n let index = 0\n let sent = 0\n let done = false\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n if (done) return\n const step = steps[index]\n if (fault && sent >= after && (step === undefined || step.content)) {\n done = true\n if (fault.type === \"mid_stream_exception\") {\n const type = fault.exceptionType ?? options.defaultException\n controller.enqueue(\n exceptionFrame(type, { message: fault.message ?? MESSAGES[type] ?? \"Stream failure.\" }),\n )\n } else {\n const next = step?.frame ?? steps.at(-1)?.frame ?? new Uint8Array(16)\n controller.enqueue(next.subarray(0, Math.max(1, Math.floor(next.length / 2))))\n }\n controller.close()\n return\n }\n if (step === undefined) {\n done = true\n controller.close()\n return\n }\n if (step.content && options.delayMsPerChunk > 0) {\n await options.sleep(options.delayMsPerChunk, options.signal)\n }\n if (options.signal?.aborted) {\n done = true\n controller.close()\n return\n }\n controller.enqueue(step.frame)\n if (step.content) sent++\n index++\n },\n })\n}\n\n/** Every ConverseStream frame for a plan, in the order Bedrock sends them. */\nexport const converseStreamSteps = (plan: Plan, latencyMs: number): Step[] => {\n const steps: Step[] = [\n { frame: eventFrame(\"messageStart\", { role: \"assistant\" }), content: false },\n ]\n plan.blocks\n .filter((block) => block.kind !== \"toolResult\")\n .forEach((block, contentBlockIndex) => {\n if (block.kind === \"toolUse\") {\n steps.push({\n frame: eventFrame(\"contentBlockStart\", {\n contentBlockIndex,\n start: { toolUse: { toolUseId: block.toolUseId, name: block.name } },\n }),\n content: false,\n })\n for (const part of chunk(JSON.stringify(block.input ?? {}), Math.max(plan.chunkSize, 8))) {\n steps.push({\n frame: eventFrame(\"contentBlockDelta\", {\n contentBlockIndex,\n delta: { toolUse: { input: part } },\n }),\n content: true,\n })\n }\n } else if (block.kind === \"reasoning\") {\n for (const part of chunk(block.text, plan.chunkSize)) {\n steps.push({\n frame: eventFrame(\"contentBlockDelta\", {\n contentBlockIndex,\n delta: { reasoningContent: { text: part } },\n }),\n content: true,\n })\n }\n steps.push({\n frame: eventFrame(\"contentBlockDelta\", {\n contentBlockIndex,\n delta: { reasoningContent: { signature: REASONING_SIGNATURE } },\n }),\n content: false,\n })\n } else if (block.kind === \"text\") {\n for (const part of chunk(block.text, plan.chunkSize)) {\n steps.push({\n frame: eventFrame(\"contentBlockDelta\", { contentBlockIndex, delta: { text: part } }),\n content: true,\n })\n }\n }\n steps.push({ frame: eventFrame(\"contentBlockStop\", { contentBlockIndex }), content: false })\n })\n steps.push({ frame: eventFrame(\"messageStop\", { stopReason: plan.stopReason }), content: false })\n steps.push({\n frame: eventFrame(\"metadata\", {\n usage: plan.usage,\n metrics: { latencyMs },\n ...(plan.trace ? { trace: plan.trace } : {}),\n }),\n content: false,\n })\n return steps\n}\n\n/** Every InvokeHarness frame for a plan (AgentCore's harness stream). */\nexport const harnessSteps = (plan: Plan, latencyMs: number): Step[] => {\n const steps: Step[] = [\n { frame: eventFrame(\"messageStart\", { role: \"assistant\" }), content: false },\n ]\n plan.blocks.forEach((block, contentBlockIndex) => {\n if (block.kind === \"toolUse\") {\n steps.push({\n frame: eventFrame(\"contentBlockStart\", {\n contentBlockIndex,\n start: { toolUse: { toolUseId: block.toolUseId, name: block.name } },\n }),\n content: false,\n })\n steps.push({\n frame: eventFrame(\"contentBlockDelta\", {\n contentBlockIndex,\n delta: { toolUse: { input: JSON.stringify(block.input ?? {}) } },\n }),\n content: true,\n })\n } else if (block.kind === \"toolResult\") {\n steps.push({\n frame: eventFrame(\"contentBlockStart\", {\n contentBlockIndex,\n start: { toolResult: { toolUseId: block.toolUseId, status: \"success\" } },\n }),\n content: false,\n })\n steps.push({\n frame: eventFrame(\"contentBlockDelta\", {\n contentBlockIndex,\n delta: { toolResult: block.content },\n }),\n content: true,\n })\n } else {\n for (const part of chunk(block.text, plan.chunkSize)) {\n steps.push({\n frame: eventFrame(\"contentBlockDelta\", {\n contentBlockIndex,\n delta:\n block.kind === \"reasoning\" ? { reasoningContent: { text: part } } : { text: part },\n }),\n content: true,\n })\n }\n }\n steps.push({ frame: eventFrame(\"contentBlockStop\", { contentBlockIndex }), content: false })\n })\n steps.push({ frame: eventFrame(\"messageStop\", { stopReason: plan.stopReason }), content: false })\n steps.push({\n frame: eventFrame(\"metadata\", {\n usage: {\n inputTokens: plan.usage.inputTokens,\n outputTokens: plan.usage.outputTokens,\n totalTokens: plan.usage.totalTokens,\n },\n metrics: { latencyMs },\n }),\n content: false,\n })\n return steps\n}\n", "/**\n * Deterministic synthetic speech: a fixed 440 Hz tone as raw PCM (signed 16-bit\n * little-endian, mono). Its length grows with the text it stands for, so a caller can\n * assert \"longer reply \u2192 more audio\" without any real voice; the bytes are identical on\n * every run.\n */\n\n/** Milliseconds of audio per character of text. */\nexport const MS_PER_CHARACTER = 60\n\n/** PCM s16le mono tone of `durationMs` at `sampleRate`: always an even byte count. */\nexport const pcmTone = (durationMs: number, sampleRate: number): Uint8Array => {\n const samples = Math.max(1, Math.round((sampleRate * durationMs) / 1000))\n const out = new Uint8Array(samples * 2)\n const view = new DataView(out.buffer)\n for (let i = 0; i < samples; i++) {\n const value = Math.round(Math.sin((2 * Math.PI * 440 * i) / sampleRate) * 0.25 * 32767)\n view.setInt16(i * 2, value, true)\n }\n return out\n}\n\n/** The tone standing in for speaking `text` aloud. */\nexport const speechFor = (text: string, sampleRate: number): Uint8Array =>\n pcmTone(Math.max(1, text.length) * MS_PER_CHARACTER, sampleRate)\n\n/** Base64 without a platform `Buffer`. */\nexport const base64 = (bytes: Uint8Array): string => {\n let binary = \"\"\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n }\n return btoa(binary)\n}\n\n/** Bytes from base64 (standard alphabet). */\nexport const fromBase64 = (value: string): Uint8Array => {\n const binary = atob(value)\n const out = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i)\n return out\n}\n", "/**\n * Nova Sonic over `InvokeModelWithBidirectionalStream`: one HTTP/2 request whose body and\n * response are both event streams, open for the whole voice session.\n *\n * Input frames (`chunk` events, each `{bytes: base64(JSON {event: {...}})}`, wrapped in a\n * SigV4 envelope by the SDK) are read as they arrive. The mock answers a user turn when an\n * interactive USER text content ends, when a USER audio content ends (or after\n * `audioTurnChunks` audio frames, standing in for end-of-speech detection), and when a\n * TOOL result content ends. Each answer is a script turn (or the default): the text as\n * `textOutput`, the same text as 24 kHz PCM tone `audioOutput`, and `toolUse` events.\n * Audio bytes sent in are counted, never kept.\n */\nimport { base64, speechFor } from \"./audio.js\"\nimport {\n eventFrame,\n exceptionFrame,\n headerString,\n payloadJson,\n readFrames,\n unwrapSigned,\n} from \"./eventstream.js\"\nimport type { Plan } from \"./plan.js\"\nimport type { Sleep } from \"./render.js\"\nimport type { CallAnalysis, TurnFault } from \"./scripts.js\"\n\nexport type SonicHost = {\n /** Match a script (or fall back) for one user turn; records stats. */\n resolve(call: CallAnalysis): Promise<Plan>\n sleep: Sleep\n /** Deterministic ids for sessions, completions and contents. */\n nextId(prefix: string): string\n /** USER audio frames that end a spoken turn without a contentEnd; 0 disables. */\n audioTurnChunks: number\n /** A fault from a runtime preset, applied to the first answer. */\n fault?: TurnFault\n}\n\ntype Content = {\n type: string\n role: string\n interactive: boolean\n text: string\n audioChunks: number\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst utf8 = new TextDecoder()\n\n/** Audio per `audioOutput` event: 100 ms of 24 kHz PCM. */\nconst AUDIO_CHUNK_BYTES = 4_800\n\n/** The response body of a Nova Sonic session. */\nexport const sonicSession = (\n request: Request,\n modelId: string,\n host: SonicHost,\n): ReadableStream<Uint8Array> => {\n let controller!: ReadableStreamDefaultController<Uint8Array>\n let closed = false\n const output = new ReadableStream<Uint8Array>({\n start(c) {\n controller = c\n },\n cancel() {\n closed = true\n },\n })\n const sessionId = host.nextId(\"session\")\n const contents = new Map<string, Content>()\n const tools: string[] = []\n const toolNames = new Map<string, string>()\n let promptName = \"\"\n let systemText = \"\"\n let lastUserText = \"\"\n let sinceUser = 0\n let pendingToolResults: string[] = []\n let completionId: string | undefined\n let outputSampleRate = 24_000\n let contentEvents = 0\n let fault = host.fault\n let chain: Promise<void> = Promise.resolve()\n let inputChars = 0\n\n const close = () => {\n if (closed) return\n closed = true\n try {\n controller.close()\n } catch {\n // already closed by the reader\n }\n }\n const emitRaw = (frame: Uint8Array) => {\n if (!closed) controller.enqueue(frame)\n }\n const emit = (event: Record<string, unknown>) =>\n emitRaw(\n eventFrame(\"chunk\", { bytes: base64(new TextEncoder().encode(JSON.stringify({ event }))) }),\n )\n\n /** A content event (text, audio, tool): paced, and where mid-stream faults land. */\n const emitContent = async (event: Record<string, unknown>, delayMs: number) => {\n if (closed) return\n if (fault && (fault.type === \"mid_stream_exception\" || fault.type === \"truncated_frame\")) {\n if (contentEvents >= (fault.afterChunks ?? 1)) {\n if (fault.type === \"mid_stream_exception\") {\n emitRaw(\n exceptionFrame(fault.exceptionType ?? \"modelStreamErrorException\", {\n message:\n fault.message ?? \"The model stream encountered an error. Try your request again.\",\n }),\n )\n } else {\n const frame = eventFrame(\"chunk\", {\n bytes: base64(new TextEncoder().encode(JSON.stringify({ event }))),\n })\n emitRaw(frame.subarray(0, Math.floor(frame.length / 2)))\n }\n close()\n return\n }\n }\n if (delayMs > 0) await host.sleep(delayMs, request.signal)\n emit(event)\n contentEvents++\n }\n\n const respond = async (spoken: boolean, call: CallAnalysis) => {\n const plan = await host.resolve(call)\n if (plan.fault && !fault) fault = plan.fault\n if (fault?.type === \"latency\") await host.sleep(fault.latencyMs ?? 1_000, request.signal)\n const base = { sessionId, promptName }\n if (completionId === undefined) {\n completionId = host.nextId(\"completion\")\n emit({ completionStart: { ...base, completionId } })\n }\n const ids = { ...base, completionId }\n if (spoken && plan.userTranscript !== undefined) {\n const contentId = host.nextId(\"content\")\n emit({\n contentStart: {\n ...ids,\n contentId,\n type: \"TEXT\",\n role: \"USER\",\n textOutputConfiguration: { mediaType: \"text/plain\" },\n },\n })\n await emitContent(\n { textOutput: { ...ids, contentId, content: plan.userTranscript, role: \"USER\" } },\n 0,\n )\n emit({ contentEnd: { ...ids, contentId, type: \"TEXT\", stopReason: \"PARTIAL_TURN\" } })\n }\n for (const block of plan.blocks) {\n if (closed) return\n if (block.kind === \"text\") {\n const textId = host.nextId(\"content\")\n emit({\n contentStart: {\n ...ids,\n contentId: textId,\n type: \"TEXT\",\n role: \"ASSISTANT\",\n additionalModelFields: JSON.stringify({ generationStage: \"FINAL\" }),\n textOutputConfiguration: { mediaType: \"text/plain\" },\n },\n })\n await emitContent(\n { textOutput: { ...ids, contentId: textId, content: block.text, role: \"ASSISTANT\" } },\n plan.delayMsPerChunk,\n )\n emit({\n contentEnd: { ...ids, contentId: textId, type: \"TEXT\", stopReason: \"PARTIAL_TURN\" },\n })\n const audioId = host.nextId(\"content\")\n emit({\n contentStart: {\n ...ids,\n contentId: audioId,\n type: \"AUDIO\",\n role: \"ASSISTANT\",\n audioOutputConfiguration: {\n mediaType: \"audio/lpcm\",\n sampleRateHertz: outputSampleRate,\n sampleSizeBits: 16,\n channelCount: 1,\n encoding: \"base64\",\n audioType: \"SPEECH\",\n },\n },\n })\n const audio = speechFor(block.text, outputSampleRate)\n for (let at = 0; at < audio.length; at += AUDIO_CHUNK_BYTES) {\n await emitContent(\n {\n audioOutput: {\n ...ids,\n contentId: audioId,\n content: base64(audio.subarray(at, at + AUDIO_CHUNK_BYTES)),\n },\n },\n plan.delayMsPerChunk,\n )\n if (closed) return\n }\n emit({ contentEnd: { ...ids, contentId: audioId, type: \"AUDIO\", stopReason: \"END_TURN\" } })\n } else if (block.kind === \"toolUse\") {\n toolNames.set(block.toolUseId, block.name)\n const toolId = host.nextId(\"content\")\n emit({\n contentStart: {\n ...ids,\n contentId: toolId,\n type: \"TOOL\",\n role: \"TOOL\",\n toolUseOutputConfiguration: { mediaType: \"application/json\" },\n },\n })\n await emitContent(\n {\n toolUse: {\n ...ids,\n contentId: toolId,\n toolName: block.name,\n toolUseId: block.toolUseId,\n content: JSON.stringify(block.input ?? {}),\n },\n },\n plan.delayMsPerChunk,\n )\n emit({ contentEnd: { ...ids, contentId: toolId, type: \"TOOL\", stopReason: \"TOOL_USE\" } })\n }\n }\n if (closed) return\n emit({\n usageEvent: {\n ...ids,\n totalInputTokens: plan.usage.inputTokens,\n totalOutputTokens: plan.usage.outputTokens,\n totalTokens: plan.usage.totalTokens,\n details: {\n delta: {\n input: { speechTokens: 0, textTokens: plan.usage.inputTokens },\n output: { speechTokens: 0, textTokens: plan.usage.outputTokens },\n },\n },\n },\n })\n }\n /** Queue an answer, snapshotting the conversation as it stands now. */\n const schedule = (spoken: boolean) => {\n const call: CallAnalysis = {\n operation: \"InvokeModelWithBidirectionalStream\",\n modelId,\n lastUserText,\n systemText,\n tools: [...tools],\n toolSchemas: {},\n toolChoice: undefined,\n hasDocument: false,\n hasImage: false,\n hasCachePoint: false,\n hasGuardrail: false,\n toolResults: pendingToolResults,\n turnIndex: sinceUser,\n structured: undefined,\n inputChars,\n }\n pendingToolResults = []\n sinceUser++\n chain = chain.then(() => respond(spoken, call)).catch(() => close())\n }\n\n const handle = (event: Record<string, unknown>) => {\n const [kind] = Object.keys(event)\n const body = kind ? event[kind] : undefined\n if (!kind || !isRecord(body)) return\n switch (kind) {\n case \"promptStart\": {\n promptName = String(body.promptName ?? \"\")\n const audio = isRecord(body.audioOutputConfiguration)\n ? body.audioOutputConfiguration\n : undefined\n if (typeof audio?.sampleRateHertz === \"number\") outputSampleRate = audio.sampleRateHertz\n const config = isRecord(body.toolConfiguration) ? body.toolConfiguration : undefined\n for (const tool of Array.isArray(config?.tools) ? config.tools : []) {\n if (isRecord(tool) && isRecord(tool.toolSpec) && typeof tool.toolSpec.name === \"string\") {\n tools.push(tool.toolSpec.name)\n }\n }\n return\n }\n case \"contentStart\": {\n const name = String(body.contentName ?? \"\")\n contents.set(name, {\n type: String(body.type ?? \"\"),\n role: String(body.role ?? \"\"),\n interactive: body.interactive !== false,\n text: \"\",\n audioChunks: 0,\n })\n const config = isRecord(body.toolResultInputConfiguration)\n ? body.toolResultInputConfiguration\n : undefined\n if (config && typeof config.toolUseId === \"string\") {\n const tool = toolNames.get(config.toolUseId)\n if (tool) pendingToolResults.push(tool)\n }\n return\n }\n case \"textInput\": {\n const content = contents.get(String(body.contentName ?? \"\"))\n const text = typeof body.content === \"string\" ? body.content : \"\"\n inputChars += text.length\n if (!content) return\n content.text += text\n if (content.role === \"SYSTEM\") systemText += text\n return\n }\n case \"audioInput\": {\n const content = contents.get(String(body.contentName ?? \"\"))\n if (!content) return\n content.audioChunks++\n if (host.audioTurnChunks > 0 && content.audioChunks >= host.audioTurnChunks) {\n content.audioChunks = 0\n // A spoken turn has no text to match on (the mock does no ASR).\n lastUserText = \"\"\n sinceUser = 0\n schedule(true)\n }\n return\n }\n case \"toolResult\": {\n const text = typeof body.content === \"string\" ? body.content : \"\"\n inputChars += text.length\n return\n }\n case \"contentEnd\": {\n const content = contents.get(String(body.contentName ?? \"\"))\n if (!content) return\n if (content.role === \"USER\" && content.type === \"TEXT\" && content.interactive) {\n lastUserText = content.text\n sinceUser = 0\n schedule(false)\n } else if (content.role === \"USER\" && content.type === \"AUDIO\" && content.audioChunks > 0) {\n lastUserText = \"\"\n sinceUser = 0\n schedule(true)\n } else if (content.type === \"TOOL\") {\n schedule(false)\n }\n return\n }\n default:\n return\n }\n }\n\n void (async () => {\n let ended = false\n try {\n for await (const raw of readFrames(request.body)) {\n const frame = unwrapSigned(raw)\n if (frame === null) break\n if (headerString(frame, \":event-type\") !== \"chunk\") continue\n const payload = payloadJson(frame)\n if (!isRecord(payload) || typeof payload.bytes !== \"string\") continue\n let decoded: unknown\n try {\n decoded = JSON.parse(\n utf8.decode(Uint8Array.from(atob(payload.bytes), (c) => c.charCodeAt(0))),\n )\n } catch {\n continue\n }\n const event = isRecord(decoded) && isRecord(decoded.event) ? decoded.event : decoded\n if (!isRecord(event)) continue\n if (\"sessionEnd\" in event) {\n ended = true\n break\n }\n handle(event)\n }\n } catch {\n // The client went away or sent a broken frame: finish what is queued, then close.\n }\n await chain\n if (ended && completionId !== undefined && !closed) {\n emit({ completionEnd: { sessionId, promptName, completionId, stopReason: \"END_TURN\" } })\n }\n close()\n })()\n return output\n}\n", "import { Collection, IdSequence } from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport type { Script } from \"./scripts.js\"\n\n/** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */\nexport type Settings = {\n /** What an unscripted chat call answers. Default `\"OK.\"`. */\n defaultText: string\n /** Characters per streamed text delta when a turn gives no `chunkSize`. Default 16. */\n chunkSize: number\n /** Mock-clock delay before each streamed delta when a turn gives none. Default 0. */\n delayMsPerChunk: number\n /** Nova Sonic: USER audio frames that end a spoken turn without a contentEnd (0 = off). */\n audioTurnChunks: number\n}\n\nexport const DEFAULT_SETTINGS: Settings = {\n defaultText: \"OK.\",\n chunkSize: 16,\n delayMsPerChunk: 0,\n audioTurnChunks: 0,\n}\n\n/** Counts for `GET /__admin/scripts` (and `/health`): metadata only. */\nexport type ModelStats = {\n calls: number\n scripted: number\n /** Calls no script answered (the defaults). */\n unscripted: number\n byScript: Record<string, number>\n /** Unscripted calls by which default answered them. */\n byFallback: Record<string, number>\n byOperation: Record<string, number>\n}\n\nconst EMPTY_STATS: ModelStats = {\n calls: 0,\n scripted: 0,\n unscripted: 0,\n byScript: {},\n byFallback: {},\n byOperation: {},\n}\n\nexport class BedrockState {\n readonly scripts: Collection<Script>\n readonly uses: Collection<number>\n readonly settings: Collection<Settings>\n readonly stats: Collection<ModelStats>\n readonly ids: IdSequence\n\n constructor(\n sqlite: SqliteClient,\n namespace: string,\n private readonly seed: { settings: Partial<Settings>; scripts: readonly Script[] },\n ) {\n this.scripts = new Collection(sqlite, namespace, \"scripts\")\n this.uses = new Collection(sqlite, namespace, \"script_uses\")\n this.settings = new Collection(sqlite, namespace, \"settings\")\n this.stats = new Collection(sqlite, namespace, \"stats\")\n this.ids = new IdSequence(sqlite, namespace, \"bedrock\")\n this.ensureSeeded()\n }\n\n /** Re-apply the configured settings and scripts after a reset. */\n ensureSeeded(): void {\n if (!this.settings.has(\"settings\")) {\n this.settings.insert(\"settings\", { ...DEFAULT_SETTINGS, ...this.seed.settings })\n for (const script of this.seed.scripts) this.scripts.insert(script.id, script)\n }\n }\n\n current(): Settings {\n return this.settings.get(\"settings\") ?? DEFAULT_SETTINGS\n }\n\n update(patch: Partial<Settings>): Settings {\n const next = { ...this.current(), ...patch }\n this.settings.insert(\"settings\", next)\n return next\n }\n\n list(): Script[] {\n return this.scripts.list({ order: \"oldest\" }).map((row) => row.value)\n }\n\n /** Replace every script (`PUT`) or add/overwrite by id (`POST`). */\n put(scripts: readonly Script[], replace: boolean): Script[] {\n if (replace) {\n for (const row of this.scripts.list()) this.scripts.delete(row.id)\n for (const row of this.uses.list()) this.uses.delete(row.id)\n }\n for (const script of scripts) this.scripts.insert(script.id, script)\n return this.list()\n }\n\n remove(id?: string): number {\n const targets = id === undefined ? this.scripts.list().map((row) => row.id) : [id]\n let removed = 0\n for (const each of targets) {\n if (this.scripts.delete(each)) removed++\n this.uses.delete(each)\n }\n return removed\n }\n\n usesOf(id: string): number {\n return this.uses.get(id) ?? 0\n }\n\n use(id: string): void {\n this.uses.insert(id, this.usesOf(id) + 1)\n }\n\n /** The 0-based index of this model call in the namespace, then count it. */\n nextCallIndex(): number {\n const stats = this.currentStats()\n this.stats.insert(\"stats\", { ...stats, calls: stats.calls + 1 })\n return stats.calls\n }\n\n record(operation: string, scriptId: string | undefined, fallback: string | undefined): void {\n const stats = this.currentStats()\n const bump = (map: Record<string, number>, key: string) => ({\n ...map,\n [key]: (map[key] ?? 0) + 1,\n })\n this.stats.insert(\"stats\", {\n ...stats,\n scripted: stats.scripted + (scriptId !== undefined ? 1 : 0),\n unscripted: stats.unscripted + (scriptId === undefined ? 1 : 0),\n byScript: scriptId !== undefined ? bump(stats.byScript, scriptId) : stats.byScript,\n byFallback:\n scriptId === undefined ? bump(stats.byFallback, fallback ?? \"chat\") : stats.byFallback,\n byOperation: bump(stats.byOperation, operation),\n })\n }\n\n currentStats(): ModelStats {\n return this.stats.get(\"stats\") ?? EMPTY_STATS\n }\n}\n", "import {\n type AdminRoutes,\n type Clock,\n createRuntime as createServiceRuntime,\n type FaultPreset,\n type RequestLog,\n type ServiceRuntime,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { document } from \"./generated/openapi.js\"\nimport { accessKeyCredential, BEDROCK_NAMESPACE, BedrockAPI, clockSleep } from \"./index.js\"\nimport { parseScript, type Script } from \"./scripts.js\"\nimport type { Settings } from \"./state.js\"\n\nconst MODEL_PATH = \"/model/\"\n\n/** A preset that switches on one `bedrock_fault` for every model and harness call. */\nconst everyCall = (description: string, params: Record<string, unknown>): FaultPreset => ({\n description,\n rules: [\n { pathPrefix: MODEL_PATH, effect: \"bedrock_fault\", params },\n { pathPrefix: \"/harnesses/\", effect: \"bedrock_fault\", params },\n ],\n})\n\n/**\n * Every named Bedrock misbehaviour our consumer branches on, switched on with\n * `POST /__admin/faults {\"preset\": \"<name>\", \"count\"?: n}` (a scripted turn can carry the\n * same `fault` for one conversation step).\n */\nexport const BEDROCK_PRESETS: Record<string, FaultPreset> = {\n throttling: everyCall(\n \"429 ThrottlingException before the first chunk (our backend retries 3\u00D7 with 500 ms\u00B72^n backoff)\",\n { type: \"throttling\" },\n ),\n mid_stream_exception: everyCall(\n \"The stream starts, sends one content chunk, then a modelStreamErrorException frame\",\n { type: \"mid_stream_exception\", afterChunks: 1 },\n ),\n mid_stream_throttling: everyCall(\n \"The stream starts, sends one content chunk, then a throttlingException frame\",\n { type: \"mid_stream_exception\", afterChunks: 1, exceptionType: \"throttlingException\" },\n ),\n validation_exception: everyCall(\"400 ValidationException\", { type: \"validation\" }),\n max_tokens: everyCall(\"Output cut in half and stopReason max_tokens\", { type: \"max_tokens\" }),\n latency: everyCall(\"2 s (mock clock) before the response starts\", {\n type: \"latency\",\n latencyMs: 2_000,\n }),\n truncated_frame: everyCall(\n \"The stream ends half-way through a frame (the event-stream decoders throw)\",\n { type: \"truncated_frame\", afterChunks: 1 },\n ),\n model_timeout: everyCall(\"408 ModelTimeoutException\", { type: \"model_timeout\" }),\n service_unavailable: everyCall(\"503 ServiceUnavailableException\", {\n type: \"service_unavailable\",\n }),\n access_denied: everyCall(\"403 AccessDeniedException\", { type: \"access_denied\" }),\n internal_server: everyCall(\"500 InternalServerException\", { type: \"internal_server\" }),\n}\n\nexport type BedrockRuntimeOptions = {\n sqlite?: SqliteClient\n clock?: Clock\n seed?: number | string\n adminKey?: string\n onLog?: (entry: RequestLog) => void\n settings?: Partial<Settings>\n /** Scripts every namespace starts with (and returns to on reset). */\n scripts?: readonly Script[]\n}\n\nexport type BedrockRuntime = ServiceRuntime<BedrockAPI>\n\nconst json = (status: number, body: unknown) =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\nconst adminError = (status: number, message: string) =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst parseScripts = (body: unknown): Script[] | string => {\n const list = Array.isArray(body)\n ? body\n : isRecord(body)\n ? (body.scripts ?? (body.id ? [body] : undefined))\n : undefined\n if (!Array.isArray(list)) return 'expected {\"scripts\": [{id, match?, turns: [...]}]}'\n const out: Script[] = []\n for (const [index, each] of list.entries()) {\n const parsed = parseScript(each, index)\n if (typeof parsed === \"string\") return parsed\n out.push(parsed)\n }\n const ids = out.map((s) => s.id)\n const duplicate = ids.find((id, i) => ids.indexOf(id) !== i)\n return duplicate ? `duplicate script id ${duplicate}` : out\n}\n\nconst SETTING_CHECKS: Record<keyof Settings, (value: unknown) => boolean> = {\n defaultText: (value) => typeof value === \"string\",\n chunkSize: (value) => typeof value === \"number\" && value >= 1,\n delayMsPerChunk: (value) => typeof value === \"number\" && value >= 0,\n audioTurnChunks: (value) => typeof value === \"number\" && value >= 0,\n}\n\nconst adminRoutes = (runtime: ServiceRuntime<BedrockAPI>): AdminRoutes => {\n const store =\n (replace: boolean): AdminRoutes[string] =>\n ({ body, namespace }) => {\n const scripts = parseScripts(body)\n if (typeof scripts === \"string\") return adminError(400, scripts)\n return json(200, { scripts: runtime.instance(namespace).putScripts(scripts, replace) })\n }\n return {\n \"GET /scripts\": ({ namespace }) => {\n const api = runtime.instance(namespace)\n return json(200, { scripts: api.scripts(), stats: api.stats() })\n },\n \"PUT /scripts\": store(true),\n \"POST /scripts\": store(false),\n \"DELETE /scripts\": ({ url, namespace }) =>\n json(200, {\n removed: runtime.instance(namespace).removeScripts(url.searchParams.get(\"id\") ?? undefined),\n }),\n \"GET /model-metrics\": ({ namespace }) => json(200, runtime.instance(namespace).stats()),\n \"GET /settings\": ({ namespace }) => json(200, runtime.instance(namespace).state.current()),\n \"PUT /settings\": ({ body, namespace }) => {\n if (!isRecord(body)) return adminError(400, \"expected a JSON object\")\n const patch: Partial<Settings> = {}\n for (const [key, value] of Object.entries(body)) {\n const check = SETTING_CHECKS[key as keyof Settings]\n if (!check) return adminError(400, `unknown setting ${key}`)\n if (!check(value)) return adminError(400, `bad value for ${key}`)\n ;(patch as Record<string, unknown>)[key] = value\n }\n return json(200, runtime.instance(namespace).state.update(patch))\n },\n }\n}\n\n/**\n * The Bedrock mock with Mockingbird's full service contract: `/health`, `/__admin/*`,\n * namespaces by header, by `/ns/<name>` path prefix, or by SigV4 access key id\n * (`PUT /__admin/credentials {\"credentials\": {\"<AWS_ACCESS_KEY_ID>\": \"<namespace>\"}}`),\n * clock control (script pacing runs on it), fault presets, scripts and a request journal\n * that records metadata only.\n */\nexport const createRuntime = (options: BedrockRuntimeOptions = {}): BedrockRuntime => {\n let runtime: BedrockRuntime | undefined\n const totals = () => {\n let scripted = 0\n let unscripted = 0\n for (const name of runtime?.namespaces() ?? []) {\n const stats = runtime?.instance(name).stats()\n scripted += stats?.scripted ?? 0\n unscripted += stats?.unscripted ?? 0\n }\n return { scripted, unscripted }\n }\n runtime = createServiceRuntime<BedrockAPI>({\n name: BEDROCK_NAMESPACE,\n document,\n ...(options.sqlite ? { sqlite: options.sqlite } : {}),\n ...(options.clock ? { clock: options.clock } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.adminKey !== undefined ? { adminKey: options.adminKey } : {}),\n ...(options.onLog ? { onLog: options.onLog } : {}),\n credential: accessKeyCredential,\n presets: BEDROCK_PRESETS,\n create: ({ sqlite, namespace, clock }) =>\n new BedrockAPI({\n sqlite,\n namespace,\n now: clock.now,\n sleep: clockSleep(clock.now),\n ...(options.settings ? { settings: options.settings } : {}),\n ...(options.scripts ? { scripts: options.scripts } : {}),\n }),\n describe: () => ({ scripts: options.scripts?.length ?? 0, modelCalls: totals() }),\n admin: adminRoutes,\n })\n return runtime\n}\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type APIOptions,\n annotateResponse,\n bodyIssues,\n bootSqlite,\n createService,\n defineOperations,\n faultEffect,\n HttpError,\n jsonRes,\n type OperationContext,\n opaqueToken,\n type Service,\n sha,\n sigV4AccessKeyId,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport type { Hono } from \"hono\"\nimport { analyzeAnthropic, analyzeConverse, analyzeHarness, ValidationProblem } from \"./analyze.js\"\nimport { document, type SupportedOperationId } from \"./generated/openapi.js\"\nimport { type Plan, type PlanContext, planDefault, planTurn, truncatePlan } from \"./plan.js\"\nimport {\n anthropicBody,\n converseBody,\n converseStreamSteps,\n harnessSteps,\n paced,\n type Sleep,\n} from \"./render.js\"\nimport {\n type CallAnalysis,\n type ModelOperation,\n matches,\n type Script,\n selectTurn,\n type TurnFault,\n} from \"./scripts.js\"\nimport { sonicSession } from \"./sonic.js\"\nimport { BedrockState, type ModelStats, type Settings } from \"./state.js\"\n\nexport type { FetchAPI } from \"@crvouga/mockingbird-core\"\nexport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nexport type {\n EventStreamMessage,\n HeaderValue,\n MessageInput,\n} from \"./eventstream.js\"\nexport {\n crc32,\n decodeMessage,\n EventStreamError,\n encodeMessage,\n eventFrame,\n exceptionFrame,\n FrameReader,\n readFrames,\n unwrapSigned,\n} from \"./eventstream.js\"\nexport type { OperationId, SupportedOperationId } from \"./generated/openapi.js\"\nexport { document, operationIds, supportedOperationIds } from \"./generated/openapi.js\"\nexport type { Plan, PlanBlock, Usage } from \"./plan.js\"\nexport {\n DEFAULT_CHAT_TEXT,\n DEFAULT_CLASSIFIER,\n DEFAULT_SOAP_NOTE,\n GUARDRAIL_BLOCKED_TEXT,\n} from \"./plan.js\"\nexport { sampleSchema } from \"./schema-sample.js\"\nexport type {\n ModelOperation,\n Script,\n ScriptMatch,\n ScriptToolUse,\n ScriptTurn,\n ScriptUsage,\n StopReason,\n TextMatch,\n TurnFault,\n TurnFaultType,\n} from \"./scripts.js\"\nexport { MODEL_OPERATIONS, parseScript, STOP_REASONS, TURN_FAULTS } from \"./scripts.js\"\nexport type { ModelStats, Settings } from \"./state.js\"\nexport { DEFAULT_SETTINGS } from \"./state.js\"\n\nexport const BEDROCK_NAMESPACE = \"bedrock\"\n\n/** The `x-amzn-ErrorType` suffix Bedrock puts after the error name. */\nconst ERROR_TYPE_SUFFIX = \":http://internal.amazon.com/coral/com.amazon.bedrock/\"\n\n/** The Titan embedding models (InvokeModel with `{inputText}`). */\nconst TITAN_EMBED = /amazon\\.titan-embed-(text|g1-text)/i\n\n/** `(status, x-amzn-ErrorType, default message)` for each pre-stream fault. */\nconst FAULT_ERRORS: Record<string, [number, string, string]> = {\n throttling: [429, \"ThrottlingException\", \"Too many requests, please wait before trying again.\"],\n validation: [\n 400,\n \"ValidationException\",\n \"The input fails to satisfy the constraints specified by the service.\",\n ],\n access_denied: [\n 403,\n \"AccessDeniedException\",\n \"You don't have access to the model with the specified model ID.\",\n ],\n model_timeout: [\n 408,\n \"ModelTimeoutException\",\n \"Model has timed out in processing the request. Try your request again.\",\n ],\n service_unavailable: [\n 503,\n \"ServiceUnavailableException\",\n \"Bedrock is unable to process your request.\",\n ],\n internal_server: [\n 500,\n \"InternalServerException\",\n \"The system encountered an unexpected error during processing. Try your request again.\",\n ],\n}\n\n/** A Bedrock error response: status, `x-amzn-ErrorType`, `{message}`. */\nexport const bedrockError = (\n status: number,\n type: string,\n message: string,\n requestId?: string,\n): Response =>\n new Response(JSON.stringify({ message }), {\n status,\n headers: {\n \"content-type\": \"application/json\",\n \"x-amzn-errortype\": `${type}${ERROR_TYPE_SUFFIX}`,\n ...(requestId ? { \"x-amzn-requestid\": requestId } : {}),\n },\n })\n\n/** The fault a runtime preset switched on for this request (`effect: \"bedrock_fault\"`). */\nconst presetFault = (request: Request): TurnFault | undefined => {\n const params = faultEffect(request, \"bedrock_fault\")\n return params && typeof params.type === \"string\" ? (params as TurnFault) : undefined\n}\n\n/**\n * The namespace credential of an AWS request: its SigV4 access key id. Map it with\n * `PUT /__admin/credentials {\"credentials\": {\"<AWS_ACCESS_KEY_ID>\": \"<namespace>\"}}`.\n */\nexport const accessKeyCredential = sigV4AccessKeyId\n\n/** Real-time sleep, for instances built without a runtime clock. */\nconst realSleep: Sleep = (ms, signal) =>\n new Promise((resolve) => {\n if (ms <= 0 || signal?.aborted) return resolve()\n const timer = setTimeout(resolve, ms)\n signal?.addEventListener(\"abort\", () => {\n clearTimeout(timer)\n resolve()\n })\n })\n\n/**\n * Wait `ms` on a (possibly frozen) mock clock: polls `now()` so a frozen clock waits until\n * a test advances it, and a live clock waits in real time.\n */\nexport const clockSleep =\n (now: () => number): Sleep =>\n (ms, signal) => {\n if (ms <= 0) return Promise.resolve()\n const until = now() + ms\n return new Promise((resolve) => {\n const tick = () => {\n if (signal?.aborted || now() >= until) return resolve()\n setTimeout(tick, Math.min(5, Math.max(1, until - now())))\n }\n tick()\n })\n }\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst utf8 = new TextEncoder()\n\n/** A deterministic 1024-d (or `dims`-d) unit vector: SHA-256(inputText) in counter mode. */\nexport const titanEmbedding = async (inputText: string, dims = 1024): Promise<number[]> => {\n const seed = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", utf8.encode(inputText)))\n const values: number[] = []\n for (let block = 0; values.length < dims; block++) {\n const input = new Uint8Array(seed.length + 4)\n input.set(seed)\n new DataView(input.buffer).setUint32(seed.length, block, false)\n const digest = new DataView(await crypto.subtle.digest(\"SHA-256\", input))\n for (let at = 0; at + 4 <= 32 && values.length < dims; at += 4) {\n values.push((digest.getUint32(at, false) / 0xffffffff) * 2 - 1)\n }\n }\n const norm = Math.sqrt(values.reduce((sum, v) => sum + v * v, 0)) || 1\n return values.map((v) => v / norm)\n}\n\nexport type BedrockAPIOptions = APIOptions & {\n /** Initial per-namespace settings. */\n settings?: Partial<Settings>\n /** Scripts every namespace starts with (re-applied on reset). */\n scripts?: readonly Script[]\n /** Wait on the mock clock. Default: real time. */\n sleep?: Sleep\n}\n\n/**\n * Stateful, scriptable mock of Amazon Bedrock Runtime (and the AgentCore harness).\n *\n * It never generates language: each model call is answered by the first script whose\n * `match` accepts it and that has a turn for this point in the conversation, or by an\n * unscripted default (counted as `unscripted`). Every answer can be rendered as a Converse\n * body, a ConverseStream event stream, an Anthropic Messages body, a harness stream or a\n * Nova Sonic session.\n */\nexport class BedrockAPI implements FetchAPI {\n readonly app: Hono\n readonly sqlite: SqliteClient\n readonly state: BedrockState\n private readonly service: Service\n private readonly now: () => number\n private readonly sleep: Sleep\n\n constructor(options: BedrockAPIOptions = {}) {\n const sqlite = bootSqlite(options.sqlite)\n const namespace = options.namespace ?? BEDROCK_NAMESPACE\n this.now = options.now ?? (() => Date.now())\n this.sleep = options.sleep ?? realSleep\n this.state = new BedrockState(sqlite, namespace, {\n settings: options.settings ?? {},\n scripts: options.scripts ?? [],\n })\n const handlers = defineOperations<SupportedOperationId>({\n Converse: (context) => this.converse(context, false),\n ConverseStream: (context) => this.converse(context, true),\n InvokeModel: (context) => this.invokeModel(context),\n // Served by `fetch` before routing, so the duplex body is never buffered.\n InvokeModelWithBidirectionalStream: (context) =>\n this.bidirectional(context.request, context.params.modelId ?? \"\"),\n InvokeHarness: (context) => this.invokeHarness(context),\n })\n this.service = createService({\n document,\n handlers,\n sqlite,\n namespace,\n now: this.now,\n notFound: (request) =>\n bedrockError(\n 404,\n \"UnknownOperationException\",\n `No operation matches ${request.method} ${new URL(request.url).pathname}`,\n ),\n onError: (error) => {\n if (error instanceof HttpError) return error.toResponse()\n if (error instanceof ValidationProblem)\n return bedrockError(400, \"ValidationException\", error.message)\n throw error\n },\n })\n this.app = this.service.app\n this.sqlite = this.service.sqlite\n }\n\n fetch(request: Request): Promise<Response> {\n const path = new URL(request.url).pathname\n const bidi = /^\\/model\\/([^/]+)\\/invoke-with-bidirectional-stream\\/?$/.exec(path)\n if (bidi && request.method === \"POST\") {\n return this.bidirectional(request, decodeURIComponent(bidi[1] as string))\n }\n return this.service.fetch(request)\n }\n\n async reset(): Promise<void> {\n await this.service.reset()\n this.state.ensureSeeded()\n }\n\n // \u2500\u2500 admin surface \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n scripts(): Script[] {\n return this.state.list()\n }\n\n putScripts(scripts: readonly Script[], replace = true): Script[] {\n return this.state.put(scripts, replace)\n }\n\n removeScripts(id?: string): number {\n return this.state.remove(id)\n }\n\n stats(): ModelStats {\n return this.state.currentStats()\n }\n\n // \u2500\u2500 shared machinery \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private requestId(): string {\n const hex = opaqueToken(`request:${this.state.ids.next(\"rq_\", 8)}`, 32)\n .split(\"\")\n .map((c) => (c.charCodeAt(0) % 16).toString(16))\n .join(\"\")\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n }\n\n private planContext(body: Record<string, unknown>, maxTokens: number | undefined): PlanContext {\n const settings = this.state.current()\n const guardrail = isRecord(body.guardrailConfig) ? body.guardrailConfig : undefined\n return {\n nextToolUseId: () => this.state.ids.next(\"tooluse_\", 22),\n chunkSize: settings.chunkSize,\n delayMsPerChunk: settings.delayMsPerChunk,\n ...(typeof guardrail?.guardrailIdentifier === \"string\"\n ? { guardrailId: guardrail.guardrailIdentifier }\n : {}),\n traceEnabled: guardrail?.trace === \"enabled\" || guardrail?.trace === \"enabled_full\",\n ...(maxTokens !== undefined ? { maxTokens } : {}),\n }\n }\n\n /**\n * First script with a turn for this call, else the default (which `unscripted` may\n * replace with an operation-specific one); records stats either way.\n */\n private async resolve(\n call: CallAnalysis,\n context: PlanContext,\n unscripted: (plan: Plan) => Plan = (plan) => plan,\n ): Promise<Plan> {\n const callIndex = this.state.nextCallIndex()\n const systemHash = await sha(\"SHA-256\", call.systemText)\n for (const script of this.state.list()) {\n if (script.times !== undefined && this.state.usesOf(script.id) >= script.times) continue\n if (!matches(script.match, call, { systemHash, callIndex })) continue\n const turn = selectTurn(script, call)\n if (!turn) continue\n this.state.use(script.id)\n this.state.record(call.operation, script.id, undefined)\n return planTurn(script.id, turn, call, context)\n }\n const plan = unscripted(planDefault(call, context, this.state.current().defaultText))\n this.state.record(call.operation, undefined, plan.fallback)\n return plan\n }\n\n /** Journal notes: metadata only (never message or prompt text). */\n private notes(response: Response, call: CallAnalysis, plan: Plan | undefined): Response {\n const flags = [\n call.hasCachePoint ? \"cachePoint\" : undefined,\n call.hasGuardrail ? \"guardrail\" : undefined,\n call.hasDocument ? \"document\" : undefined,\n call.hasImage ? \"image\" : undefined,\n call.structured ? `structured:${call.structured.form}` : undefined,\n ].filter((f): f is string => f !== undefined)\n return annotateResponse(response, {\n ids: {\n modelId: call.modelId,\n script: plan?.scriptId ?? `unscripted:${plan?.fallback ?? \"chat\"}`,\n ...(call.tools.length > 0 ? { tools: call.tools.join(\",\") } : {}),\n ...(flags.length > 0 ? { flags: flags.join(\",\") } : {}),\n ...(plan\n ? {\n stopReason: plan.stopReason,\n inputTokens: String(plan.usage.inputTokens),\n outputTokens: String(plan.usage.outputTokens),\n }\n : {}),\n },\n })\n }\n\n private jsonBody(context: OperationContext): unknown {\n const body = context.body\n if (body.kind === \"json\") return body.value\n if (body.kind === \"bytes\" || body.kind === \"text\") {\n try {\n return JSON.parse(\n body.kind === \"text\" ? body.value : new TextDecoder().decode(body.value),\n ) as unknown\n } catch {\n return undefined\n }\n }\n return undefined\n }\n\n /** A pre-stream fault as the vendor's error, or `undefined` to carry on. */\n private async preStream(\n fault: TurnFault | undefined,\n requestId: string,\n signal: AbortSignal,\n streaming: boolean,\n ): Promise<Response | undefined> {\n if (!fault) return undefined\n if (fault.type === \"latency\") {\n await this.sleep(fault.latencyMs ?? 1_000, signal)\n return undefined\n }\n const known = FAULT_ERRORS[fault.type]\n if (known) return bedrockError(known[0], known[1], fault.message ?? known[2], requestId)\n if (!streaming && (fault.type === \"mid_stream_exception\" || fault.type === \"truncated_frame\")) {\n const [status, type, message] = FAULT_ERRORS.internal_server as [number, string, string]\n return bedrockError(status, type, fault.message ?? message, requestId)\n }\n return undefined\n }\n\n private eventStream(body: ReadableStream<Uint8Array>, requestId: string): Response {\n return new Response(body, {\n status: 200,\n headers: {\n \"content-type\": \"application/vnd.amazon.eventstream\",\n \"x-amzn-requestid\": requestId,\n },\n })\n }\n\n // \u2500\u2500 operations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async converse(context: OperationContext, streaming: boolean): Promise<Response> {\n const requestId = this.requestId()\n const operation: ModelOperation = streaming ? \"ConverseStream\" : \"Converse\"\n const modelId = context.params.modelId ?? \"\"\n const body = this.jsonBody(context)\n if (!isRecord(body)) {\n return bedrockError(\n 400,\n \"ValidationException\",\n \"Malformed input request, please reformat your input and try again.\",\n requestId,\n )\n }\n const issues = bodyIssues(context).filter(\n (issue) => issue.message !== \"request body is not valid application/json\",\n )\n if (issues.length > 0) {\n const first = issues[0] as { path: string; message: string }\n return bedrockError(\n 400,\n \"ValidationException\",\n `${issues.length} validation error${issues.length > 1 ? \"s\" : \"\"} detected: Value at '${first.path || \"body\"}' failed to satisfy constraint: ${first.message}`,\n requestId,\n )\n }\n let call: CallAnalysis\n try {\n call = analyzeConverse(operation, modelId, body)\n } catch (error) {\n if (error instanceof ValidationProblem)\n return bedrockError(400, \"ValidationException\", error.message, requestId)\n throw error\n }\n const inference = isRecord(body.inferenceConfig) ? body.inferenceConfig : {}\n const maxTokens = typeof inference.maxTokens === \"number\" ? inference.maxTokens : undefined\n let plan = await this.resolve(call, this.planContext(body, maxTokens))\n const fault = presetFault(context.request) ?? plan.fault\n if (fault?.type === \"max_tokens\") plan = truncatePlan(plan)\n const failed = await this.preStream(fault, requestId, context.request.signal, streaming)\n if (failed) return this.notes(failed, call, plan)\n if (!streaming) {\n return this.notes(\n jsonRes(200, converseBody(plan, 0), { \"x-amzn-requestid\": requestId }),\n call,\n plan,\n )\n }\n const stream = paced(converseStreamSteps(plan, 0), {\n sleep: this.sleep,\n delayMsPerChunk: plan.delayMsPerChunk,\n fault,\n defaultException: \"modelStreamErrorException\",\n signal: context.request.signal,\n })\n return this.notes(this.eventStream(stream, requestId), call, plan)\n }\n\n private async invokeModel(context: OperationContext): Promise<Response> {\n const requestId = this.requestId()\n const modelId = context.params.modelId ?? \"\"\n const body = this.jsonBody(context)\n if (!isRecord(body)) {\n return bedrockError(\n 400,\n \"ValidationException\",\n \"Malformed input request, please reformat your input and try again.\",\n requestId,\n )\n }\n if (TITAN_EMBED.test(modelId)) return this.titan(context, modelId, body, requestId)\n if (!/anthropic|claude/i.test(modelId)) {\n return bedrockError(\n 400,\n \"ValidationException\",\n \"The provided model identifier is invalid.\",\n requestId,\n )\n }\n let call: CallAnalysis\n try {\n call = analyzeAnthropic(modelId, body)\n } catch (error) {\n if (error instanceof ValidationProblem)\n return bedrockError(400, \"ValidationException\", error.message, requestId)\n throw error\n }\n const maxTokens = typeof body.max_tokens === \"number\" ? body.max_tokens : undefined\n let plan = await this.resolve(call, this.planContext(body, maxTokens))\n const fault = presetFault(context.request) ?? plan.fault\n if (fault?.type === \"max_tokens\") plan = truncatePlan(plan)\n const failed = await this.preStream(fault, requestId, context.request.signal, false)\n if (failed) return this.notes(failed, call, plan)\n return this.notes(\n jsonRes(200, anthropicBody(plan, modelId, `msg_bdrk_${this.state.ids.next(\"\", 24)}`), {\n \"x-amzn-requestid\": requestId,\n \"x-amzn-bedrock-input-token-count\": String(plan.usage.inputTokens),\n \"x-amzn-bedrock-output-token-count\": String(plan.usage.outputTokens),\n \"x-amzn-bedrock-invocation-latency\": \"0\",\n }),\n call,\n plan,\n )\n }\n\n private async titan(\n context: OperationContext,\n modelId: string,\n body: Record<string, unknown>,\n requestId: string,\n ): Promise<Response> {\n const v2 = /v2/i.test(modelId)\n const inputText = body.inputText\n if (typeof inputText !== \"string\" || inputText.length === 0) {\n return bedrockError(\n 400,\n \"ValidationException\",\n \"Malformed input request: #/inputText: expected minLength: 1, actual: 0, please reformat your input and try again.\",\n requestId,\n )\n }\n const dimensions = body.dimensions ?? (v2 ? 1024 : 1536)\n if (v2 && ![256, 512, 1024].includes(dimensions as number)) {\n return bedrockError(\n 400,\n \"ValidationException\",\n `Malformed input request: #/dimensions: ${String(dimensions)} is not a valid enum value, please reformat your input and try again.`,\n requestId,\n )\n }\n this.state.nextCallIndex()\n this.state.record(\"InvokeModel\", undefined, \"titan\")\n const fault = presetFault(context.request)\n const failed = await this.preStream(fault, requestId, context.request.signal, false)\n const inputTextTokenCount = Math.max(1, Math.ceil(inputText.length / 4))\n const notes = (response: Response) =>\n annotateResponse(response, {\n ids: { modelId, script: \"unscripted:titan\", inputTokens: String(inputTextTokenCount) },\n })\n if (failed) return notes(failed)\n const embedding = await titanEmbedding(inputText, dimensions as number)\n return notes(\n jsonRes(\n 200,\n {\n embedding,\n inputTextTokenCount,\n ...(Array.isArray(body.embeddingTypes) ? { embeddingsByType: { float: embedding } } : {}),\n },\n {\n \"x-amzn-requestid\": requestId,\n \"x-amzn-bedrock-input-token-count\": String(inputTextTokenCount),\n \"x-amzn-bedrock-invocation-latency\": \"0\",\n },\n ),\n )\n }\n\n private async invokeHarness(context: OperationContext): Promise<Response> {\n const requestId = this.requestId()\n const harnessArn = context.url.searchParams.get(\"harnessArn\") ?? \"\"\n if (!harnessArn) {\n return bedrockError(\n 400,\n \"ValidationException\",\n \"1 validation error detected: Value null at 'harnessArn' failed to satisfy constraint: Member must not be null\",\n requestId,\n )\n }\n const body = this.jsonBody(context)\n let call: CallAnalysis\n try {\n call = analyzeHarness(harnessArn, body)\n } catch (error) {\n if (error instanceof ValidationProblem)\n return bedrockError(400, \"ValidationException\", error.message, requestId)\n throw error\n }\n let plan = await this.resolve(call, this.planContext({}, undefined), (fallback) =>\n this.harnessDefault(call, fallback),\n )\n const fault = presetFault(context.request) ?? plan.fault\n if (fault?.type === \"max_tokens\") plan = truncatePlan(plan)\n const failed = await this.preStream(fault, requestId, context.request.signal, true)\n if (failed) return this.notes(failed, call, plan)\n const stream = paced(harnessSteps(plan, 0), {\n sleep: this.sleep,\n delayMsPerChunk: plan.delayMsPerChunk,\n fault,\n defaultException: \"internalServerException\",\n signal: context.request.signal,\n })\n const response = this.eventStream(stream, requestId)\n const session = context.request.headers.get(\"x-amzn-bedrock-agentcore-runtime-session-id\")\n if (session) response.headers.set(\"x-amzn-bedrock-agentcore-runtime-session-id\", session)\n return this.notes(response, call, plan)\n }\n\n /** The unscripted eRx prescreen answer: eligible for clinician review. */\n private harnessDefault(call: CallAnalysis, plan: Plan): Plan {\n let productKey = \"unknown\"\n try {\n const parsed = JSON.parse(call.lastUserText) as { product_key?: unknown }\n if (typeof parsed.product_key === \"string\") productKey = parsed.product_key\n } catch {\n // not the prescreen payload: keep the generic key\n }\n const summary = {\n status: \"eligible_for_clinician_review\",\n summary: \"Mock prescreen: no hard stops found; ready for clinician review.\",\n narrative: \"Generated by the Mockingbird Bedrock mock. No clinical rules were evaluated.\",\n protocolVersion: `${productKey}-mock-1`,\n ranAt: new Date(this.now()).toISOString(),\n hardStops: [],\n cautions: [],\n missingData: [],\n }\n return {\n ...plan,\n fallback: \"harness\",\n blocks: [{ kind: \"text\", text: JSON.stringify(summary) }],\n stopReason: \"end_turn\",\n }\n }\n\n private async bidirectional(request: Request, modelId: string): Promise<Response> {\n const requestId = this.requestId()\n if (!/sonic/i.test(modelId)) {\n return bedrockError(\n 400,\n \"ValidationException\",\n `The model ${modelId} does not support bidirectional streaming.`,\n requestId,\n )\n }\n const fault = presetFault(request)\n if (fault && FAULT_ERRORS[fault.type]) {\n const failed = await this.preStream(fault, requestId, request.signal, true)\n if (failed) return annotateResponse(failed, { ids: { modelId } })\n }\n const settings = this.state.current()\n const body = sonicSession(request, modelId, {\n resolve: (call) =>\n this.resolve(\n call,\n {\n nextToolUseId: () => this.state.ids.next(\"tooluse_\", 22),\n chunkSize: settings.chunkSize,\n delayMsPerChunk: settings.delayMsPerChunk,\n traceEnabled: false,\n },\n (plan) => ({ ...plan, fallback: \"sonic\" }),\n ),\n sleep: this.sleep,\n nextId: (prefix) => {\n const hex = opaqueToken(`${prefix}:${this.state.ids.next(`${prefix}_`, 8)}`, 32)\n .split(\"\")\n .map((c) => (c.charCodeAt(0) % 16).toString(16))\n .join(\"\")\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n },\n audioTurnChunks: settings.audioTurnChunks,\n ...(fault && !FAULT_ERRORS[fault.type] ? { fault } : {}),\n })\n return annotateResponse(this.eventStream(body, requestId), { ids: { modelId } })\n }\n}\n\nexport type { BedrockRuntime, BedrockRuntimeOptions } from \"./runtime.js\"\nexport { BEDROCK_PRESETS, createRuntime } from \"./runtime.js\"\n"],
5
+ "mappings": ";AAgCO,IAAM,cAAc,CAAC,SAAuB,KAAK,QAAc;AACpE,MAAI,WAAW;AACf,MAAI;AACJ,QAAM,MAAM,MAAM,YAAY,OAAM,IAAK;AACzC,SAAO;IACL;IACA,KAAK,CAAC,YAAW;AACf,UAAI,aAAa;AAAW,mBAAW;;AAClC,mBAAW,UAAU,OAAM;IAClC;IACA,SAAS,CAAC,YAAW;AACnB,UAAI,aAAa;AAAW,oBAAY;;AACnC,oBAAY;IACnB;IACA,QAAQ,MAAK;AACX,iBAAW,IAAG;IAChB;IACA,UAAU,MAAK;AACb,UAAI,aAAa;AAAW;AAC5B,iBAAW,WAAW,OAAM;AAC5B,iBAAW;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document", "document", "document", "fail", "matches", "text", "text", "isRecord", "document", "json", "adminError", "isRecord", "BRANCH_PATTERN", "document", "snapshot", "branch", "url", "response", "isRecord", "text", "resolveRef", "isRecord", "matches", "text", "utf8", "chunk", "text", "isRecord", "utf8", "text", "json", "adminError", "isRecord", "createRuntime", "isRecord", "utf8", "matches", "notes"]
7
+ }