// A model vendor's turn, matched with the pack's own vocabulary (architecture, "Scenarios"; ADR 0036). The World's // programs place turn decisions and faults in its record of placements (placements.ts); scenario-serve.ts hands the ones not // used up to this engine as ordered rules `{ on, respond | fault }`, and the first whose `on` conditions ALL hold, and // whose answer the request admits, decides the turn. No match is the miss: the pack's labelled deterministic stub. // // The GRAMMAR (strict validation, ordering, the fault vocabulary) is this module's and the same for every vendor; the // VOCABULARY (which `on` keys exist and how each matches, what `respond` may contain, which routes are stateful and so // refuse success-shaped answers) is the pack's, declared through a PackScenarioAdapter. A typo fails loudly at load, // naming the valid vocabulary, never silently mis-matches at serve. /** A vendor-agnostic bag of facts about one request, produced by the pack's adapter. Powers * matching context, miss records (the authoring signal), and the self-teaching stub text. */ export type ScenarioFeatures = Record; /** One matcher: does THIS request satisfy `condition`? Pure — no state, no IO. */ export type ScenarioMatcher = (req: Req, condition: unknown) => boolean; /** The pack's declaration of its vocabulary — the ONLY vendor-specific surface. */ export type PackScenarioAdapter = { /** Vendor key, e.g. "anthropic" — used in errors and the manifest. */ vendor: string; /** Extract the feature bag for miss records / stub teaching. Pure. */ features: (req: Req) => ScenarioFeatures; /** The legal `on` keys and their per-request semantics. Pure. */ matchers: Record>; /** Validate `on` CONDITION VALUES at load (key membership is the kernel's; VALUE typing is * the pack's — a mistyped value silently never matching is the misfire strict loading exists * to prevent). Return an error string to refuse. */ validateOn?: (on: Record) => string | null; /** Validate a handler's `respond` payload at load; return an error string to refuse. * This is ALSO where a pack refuses success-shaped handlers on stateful routes * ("seed that through the vendor's API instead"). */ validateRespond?: (respond: unknown, handler: ScenarioHandler) => string | null; /** Whether the request admits a handler's answer (OpenAI's `tool_choice: 'none'` admits no tool call): a handler whose * answer it does not admit is passed over, and the next that matches answers, else the stub. Absent, every answer. */ admits?: (req: Req, respond: unknown) => boolean; /** Opt-in scope check for post-admission model generation failures; absent rejects them. */ validateGenerationFault?: (fault: ScenarioGenerationFault, handler: ScenarioHandler) => string | null; /** The VENDOR'S error envelope for a `status` fault — a 429 from this vendor looks like this * vendor's 429. Omitted → the kernel's envelope `{ error: { message, type: "twin_fault" } }`. */ renderFault?: (fault: ScenarioStatusFault, req: Req) => { body: unknown; headers?: Record }; }; /** THE FAULT VOCABULARY (runtime contract R15 — outage rehearsal as a world-level value). One * grammar every pack's engine honors, so a 429 or a hung request is authored the same way for * every vendor instead of improvised per realizer: * slow — hold the answer `ms` before serving it (the response is whatever the handler's * `respond` or the twin's own path produces; timing is not content, R9 holds); * status — answer this HTTP status instead of serving: a 4xx/5xx the vendor's own envelope * (the pack's adapter renders it; a kernel envelope when it declares none), with * `Retry-After` when `retryAfterSeconds` is set; * generation — opt-in post-admission compute failure, carried to the handler for its SDK error wire; * drop — never answer: the request hangs until the client's own timeout ends it (what an * outage looks like from the client; a TCP reset is not something a fetch can do), * released after `holdMs` (default 300 000) so a socket is not held forever. */ export type ScenarioFault = | { kind: "slow"; ms: number } | { kind: "status"; status: number; retryAfterSeconds?: number; message?: string; errorType?: string; metadata?: Record } | { kind: "generation"; status: number; message: string; errorType: string; metadata?: Record; partialText?: string; event?: string } | { kind: "drop"; holdMs?: number }; export type ScenarioGenerationFault = Extract; export type ScenarioStatusFault = Extract; /** What a `status` fault serves: the pack's rendered envelope, or the kernel's. */ export type ScenarioFaultResult = { status: number; headers: Record; body: unknown }; export type ScenarioHandler = { /** The rule's id: `entry-`, the placement it came from. */ id?: string; /** Conditions — ALL must hold. `{}` matches every request. */ on: Record; /** The turn's answer, which the pack realizes into the vendor's envelope; absent on a fault. */ respond?: unknown; /** The fault that answers the turn instead (ScenarioFault). */ fault?: ScenarioFault; }; /** The ordered rules of one turn. */ export type ScenarioDocument = { handlers: ScenarioHandler[] }; export type ScenarioMissRecord = { features: ScenarioFeatures }; export type ScenarioDecision = | { kind: "handler"; handler: ScenarioHandler; respond: unknown; ruleId: string; fault?: ScenarioFault } | { kind: "miss"; miss: ScenarioMissRecord }; export class ScenarioError extends Error {} const HANDLER_KEYS = new Set(["id", "on", "respond", "fault"]); /** Strict-loud parse of a turn's rules. Every refusal names the valid vocabulary. */ export function parseScenarioDocument(raw: ScenarioDocument, adapter: PackScenarioAdapter): ScenarioDocument { return { handlers: raw.handlers.map((h, i) => parseHandler(h, i, adapter)) }; } function parseHandler(raw: unknown, index: number, adapter: PackScenarioAdapter): ScenarioHandler { const h = raw as Record; const at = typeof h.id === "string" ? h.id : `rule ${index + 1}`; for (const key of Object.keys(h)) { if (!HANDLER_KEYS.has(key)) throw new ScenarioError(`${adapter.vendor} scenario: ${at}: unknown key "${key}" (valid: ${[...HANDLER_KEYS].join(", ")})`); } if (typeof h.on !== "object" || h.on === null || Array.isArray(h.on)) throw new ScenarioError(`${adapter.vendor} scenario: ${at}: \`on\` is an object of conditions ({} matches all)`); const validOn = Object.keys(adapter.matchers); for (const key of Object.keys(h.on as Record)) { if (!validOn.includes(key)) throw new ScenarioError(`${adapter.vendor} scenario: ${at}: unknown \`on\` key "${key}" (valid here: ${validOn.join(", ")})`); } const onRefusal = adapter.validateOn?.(h.on as Record); if (onRefusal) throw new ScenarioError(`${adapter.vendor} scenario: ${at}: ${onRefusal}`); if (h.fault !== undefined && (h.fault as ScenarioFault).kind === "generation") { if (!adapter.validateGenerationFault) throw new ScenarioError(`${adapter.vendor} scenario: ${at}: generation faults require a compute-only adapter`); const refusal = adapter.validateGenerationFault(h.fault as ScenarioGenerationFault, h as unknown as ScenarioHandler); if (refusal) throw new ScenarioError(`${adapter.vendor} scenario: ${at}: ${refusal}`); } const refusal = "respond" in h ? adapter.validateRespond?.(h.respond, h as ScenarioHandler) : null; if (refusal) throw new ScenarioError(`${adapter.vendor} scenario: ${at}: ${refusal}`); return h as ScenarioHandler; } /** The engine over one turn's rules: pure, the same rules and request giving the same decision. */ export class ScenarioEngine { constructor(private readonly adapter: PackScenarioAdapter, private readonly document: ScenarioDocument) {} /** Decide one request: the first rule that matches and whose answer the request admits, else the miss. */ next(req: Req): ScenarioDecision { for (const [i, handler] of this.document.handlers.entries()) { if (!Object.entries(handler.on).every(([key, condition]) => this.adapter.matchers[key]!(req, condition))) continue; if ("respond" in handler && this.adapter.admits && !this.adapter.admits(req, handler.respond)) continue; return { kind: "handler", handler, respond: handler.respond, ruleId: handler.id ?? `rule-${i + 1}`, ...(handler.fault !== undefined ? { fault: handler.fault } : {}) }; } return { kind: "miss", miss: { features: this.adapter.features(req) } }; } } /** Honor a fault outside the engine (hand-written serve paths): `slow` waits and returns null * (serve normally now); `status` returns what to serve; `drop` holds the request for `holdMs` * (default 300 000) and then throws, so the socket is released and nothing is ever answered. */ function throwIfScenarioAborted(signal?: AbortSignal): void { signal?.throwIfAborted(); } function waitForScenarioFault(ms: number, signal?: AbortSignal): Promise { throwIfScenarioAborted(signal); return new Promise((resolve, reject) => { const cleanup = () => signal?.removeEventListener('abort', onAbort); const onAbort = () => { clearTimeout(timer); cleanup(); reject(signal?.reason); }; const timer = setTimeout(() => { cleanup(); resolve(); }, ms); signal?.addEventListener('abort', onAbort, { once: true }); if (signal?.aborted) onAbort(); }); } export async function scenarioFaultResult(fault: ScenarioFault, render?: () => { body: unknown; headers?: Record } | undefined, signal?: AbortSignal): Promise { throwIfScenarioAborted(signal); if (fault.kind === "generation") return null; // compute handler renders the admitted generation failure if (fault.kind === "slow") { await waitForScenarioFault(fault.ms, signal); throwIfScenarioAborted(signal); return null; } if (fault.kind === "drop") { await waitForScenarioFault(fault.holdMs ?? 300_000, signal); throwIfScenarioAborted(signal); throw new ScenarioError("scenario drop: the request was held unanswered for its hold and is now released without a response"); } const rendered = render?.(); throwIfScenarioAborted(signal); const headers: Record = { ...(rendered?.headers ?? {}) }; if (fault.retryAfterSeconds !== undefined) headers["retry-after"] = String(fault.retryAfterSeconds); return { status: fault.status, headers, body: rendered?.body ?? { error: { message: fault.message ?? `twin fault: ${fault.status}`, type: "twin_fault" } } }; } export function statefulTwinManifest(input: { vendor: string; twinOf: string; stores: string; identity?: string; behavior?: string; notes?: string; doors?: ReadonlyArray<{ method: string; path: string; note?: string }> }): Record { // the World's doors the pack declares (what the vendor's own pages do that its API does not: issuing an account's key) const doors = input.doors ?? []; return { twin: true, vendor: input.vendor, twinOf: input.twinOf, program: { state: doors.length ? `Stateful: it stores ${input.stores}. Create state through the vendor's OWN API with the real SDK or plain fetch pointed here; what the vendor does on its own pages (not its API) is a door of the World, listed under doors. There is no fixture language.` : `Stateful: it stores ${input.stores}. Create state through the vendor's OWN API with the real SDK or plain fetch pointed here — there is no fixture language and no write door besides the vendor's.`, identity: input.identity ?? 'Authenticate as the vendor does; the twin accepts any non-sentinel credential.', time: 'Writes are stamped from the WORLD CLOCK (volter world clock --branch set/advance) — deterministic history is clock-set, seed, clock-advance.', behavior: input.behavior ?? 'This twin is state, not scripting — answers are functions of what you seeded. Judgment/fault scripting lives on the scripted vendor twins (their GET /twin explains).', ...(input.notes ? { notes: input.notes } : {}), }, doors: { manifest: 'GET /twin', ...Object.fromEntries(doors.map((d) => [`${d.method} ${d.path}`, d.note ?? 'a door of the World'])) }, }; } /** The GET /twin manifest — the discovery door's body. Education ships INSIDE the twin: * in-world agents have no repos or skills, only HTTP. */ export function twinManifest(input: { vendor: string; twinOf: string; stateSentence: string; behaviorSentence: string; exampleHandler: ScenarioHandler | null }): Record { return { twin: true, vendor: input.vendor, twinOf: input.twinOf, program: { state: input.stateSentence, behavior: input.behaviorSentence, invariant: "Nothing answers in place of this twin: a World's scenario places turn decisions (point \"turn\") on its timeline, and the twin answers and records them; stored data is seeded through the vendor's own API. Serving is deterministic.", ...(input.exampleHandler ? { exampleDecision: { at: "0s", decision: { vendor: input.vendor, point: "turn", on: input.exampleHandler.on, outcome: input.exampleHandler.respond } } } : {}), }, doors: { manifest: "GET /twin", scenario: "GET /twin/scenario (read-only: what the World's scenario placed on this twin, and what it consumed)" }, }; }