@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,1169 @@
1
+ import { Hono } from 'hono';
2
+
3
+ /**
4
+ * Anything that can answer a Fetch `Request` with a `Response`.
5
+ *
6
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
7
+ * It is the only contract shared across the whole graph.
8
+ */
9
+ interface FetchAPI$1 {
10
+ fetch(request: Request): Promise<Response>;
11
+ }
12
+
13
+ /**
14
+ * The single source of time for a service.
15
+ *
16
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
17
+ * sleeping: appointment windows, result delays and expiries become reachable in
18
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
19
+ */
20
+ type ClockState = {
21
+ /** Current epoch milliseconds. */
22
+ now: number;
23
+ /** True while time does not advance on its own. */
24
+ frozen: boolean;
25
+ /** Milliseconds this clock adds to its underlying source. */
26
+ offsetMs: number;
27
+ };
28
+ type Clock = {
29
+ now(): number;
30
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
31
+ set(epochMs: number): void;
32
+ /** Move the clock forward, or back with a negative delta. */
33
+ advance(deltaMs: number): void;
34
+ /** Stop time at the current instant. */
35
+ freeze(): void;
36
+ /** Resume from the current instant. */
37
+ unfreeze(): void;
38
+ /** Drop back to the underlying source, live. */
39
+ reset(): void;
40
+ state(): ClockState;
41
+ };
42
+
43
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
44
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
45
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
46
+ type SqliteRunResult$1 = {
47
+ changes: number;
48
+ lastInsertRowid: number | bigint;
49
+ };
50
+ /**
51
+ * Prepared statement bound to a {@link SqliteClient}.
52
+ *
53
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
54
+ */
55
+ interface SqliteStatement$1 {
56
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
57
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
58
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
59
+ }
60
+ /**
61
+ * Sync SQLite client port owned by Mockingbird.
62
+ *
63
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
64
+ * `bun:sqlite` instances all work when they expose this surface.
65
+ */
66
+ interface SqliteClient$1 {
67
+ exec(sql: string): void;
68
+ prepare(sql: string): SqliteStatement$1;
69
+ transaction<T>(fn: () => T): T;
70
+ }
71
+
72
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
73
+ type Stored<T> = {
74
+ seq: number;
75
+ value: T;
76
+ };
77
+ type ListRecordsOptions<T> = {
78
+ /** Keep only records passing the predicate. */
79
+ where?: (value: T, seq: number) => boolean;
80
+ /** Sort order; default newest first. */
81
+ order?: "newest" | "oldest";
82
+ };
83
+ /**
84
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
85
+ * sequence, never by id lexicographic order, so list semantics stay stable.
86
+ */
87
+ declare class Collection<T> {
88
+ private readonly sqlite;
89
+ private readonly namespace;
90
+ private readonly name;
91
+ constructor(sqlite: SqliteClient$1, namespace: string, name: string);
92
+ private bumpCollectionSeq;
93
+ nextSequence(): number;
94
+ get(id: string): T | undefined;
95
+ has(id: string): boolean;
96
+ /** Insert a new record, assigning it the next sequence number. */
97
+ insert(id: string, value: T): Stored<T>;
98
+ /** Replace an existing record's value, keeping its position. */
99
+ update(id: string, value: T): Stored<T> | undefined;
100
+ delete(id: string): boolean;
101
+ /** How many records the collection holds, without reading them. */
102
+ count(): number;
103
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
104
+ id: string;
105
+ }>;
106
+ }
107
+
108
+ /**
109
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
110
+ * request a percentage fault hits — is reproducible from a seed.
111
+ *
112
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
113
+ * than statistical quality.
114
+ */
115
+ type Rng = {
116
+ /** Next value in `[0, 1)`. */
117
+ next(): number;
118
+ /** Next integer in `[min, max]`. */
119
+ int(min: number, max: number): number;
120
+ /** Restart the stream from its seed. */
121
+ reset(): void;
122
+ /** Serializable engine state used by deterministic checkpoints. */
123
+ state(): number;
124
+ /** Restore a state previously returned by {@link state}. */
125
+ setState(state: number): void;
126
+ seed: number;
127
+ };
128
+
129
+ /**
130
+ * A deliberate failure injected in front of an operation.
131
+ *
132
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
133
+ * quota error that only appears when a shared sandbox is full, the 429 that only
134
+ * appears under load, the 5xx that proves a retry path works.
135
+ */
136
+ type FaultRule = {
137
+ /** Stable id, so a suite can retire exactly the rule it added. */
138
+ id: string;
139
+ /** Fault only this operation. Omit to match every operation. */
140
+ operationId?: string;
141
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
142
+ method?: string;
143
+ /** Fault only paths starting with this prefix. Omit to match every path. */
144
+ pathPrefix?: string;
145
+ /**
146
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
147
+ * an in-process caller usually wants, and what a parallel worker usually does not:
148
+ * rules added through `POST /__admin/faults` default to the calling namespace.
149
+ */
150
+ namespace?: string;
151
+ /**
152
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
153
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
154
+ * the request then still reaches the service.
155
+ */
156
+ status?: number;
157
+ /** Response body, serialized as JSON. A string is sent as-is. */
158
+ body?: unknown;
159
+ headers?: Record<string, string>;
160
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
161
+ count?: number;
162
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
163
+ rate?: number;
164
+ /** Hold the response back this long, to exercise timeouts. */
165
+ delayMs?: number;
166
+ /** Alias of `delayMs`. */
167
+ latencyMs?: number;
168
+ /**
169
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
170
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
171
+ */
172
+ drop?: boolean;
173
+ /**
174
+ * A named service behaviour to switch on for the matching request instead of (or
175
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
176
+ * read it with `faultEffects(request)`.
177
+ */
178
+ effect?: string;
179
+ /** Parameters for `effect`. */
180
+ params?: Record<string, unknown>;
181
+ /** From the preset this rule was expanded from, if any. */
182
+ preset?: string;
183
+ };
184
+ /** A fault that fired for one request. */
185
+ type FaultHit = {
186
+ id: string;
187
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
188
+ response?: Response;
189
+ drop?: boolean;
190
+ effect?: {
191
+ name: string;
192
+ params: Record<string, unknown>;
193
+ };
194
+ };
195
+ /**
196
+ * A named, documented fault a suite switches on by name
197
+ * (`POST /__admin/faults {"preset": "rate_limited"}`): one or more rules, and optionally a
198
+ * webhook delivery fault.
199
+ */
200
+ type FaultPreset = {
201
+ description: string;
202
+ rules?: Omit<FaultRule, "id">[];
203
+ webhook?: {
204
+ mode: "duplicate" | "reorder" | "drop";
205
+ count?: number;
206
+ };
207
+ };
208
+ /** What a request looks like to the fault matcher. */
209
+ type FaultCandidate = {
210
+ operationId: string | undefined;
211
+ method: string;
212
+ path: string;
213
+ namespace: string;
214
+ };
215
+ type FaultRegistry = {
216
+ add(rule: FaultRule): FaultRule;
217
+ list(): (FaultRule & {
218
+ remaining: number | null;
219
+ hits: number;
220
+ })[];
221
+ remove(id: string): boolean;
222
+ clear(): void;
223
+ /**
224
+ * Every fault this request should get, in rule order, stopping at the first that answers
225
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
226
+ * each matching rule's remaining uses.
227
+ */
228
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
229
+ };
230
+
231
+ /** One handled request, as the structured log sees it. */
232
+ type RequestLog = {
233
+ service: string;
234
+ namespace: string;
235
+ operationId: string | undefined;
236
+ method: string;
237
+ path: string;
238
+ status: number;
239
+ durationMs: number;
240
+ /** True when the path matched no operation in the contract. */
241
+ unmatched: boolean;
242
+ /** Set when a fault rule produced the response. */
243
+ faultId?: string;
244
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
245
+ ids?: Record<string, string>;
246
+ /** Set when the service created a resource the request referred to but that did not exist. */
247
+ adopted?: boolean;
248
+ };
249
+ type MetricsReport = {
250
+ requests: number;
251
+ /** Counts keyed `<operationId> <status>`. */
252
+ byOperation: Record<string, number>;
253
+ /**
254
+ * Paths that matched no operation, most frequent first.
255
+ *
256
+ * This is the early-warning signal: a consumer calling something the mock does
257
+ * not implement shows up here as a count, before it fails a suite as a 404.
258
+ */
259
+ unmatched: {
260
+ method: string;
261
+ path: string;
262
+ count: number;
263
+ }[];
264
+ faults: number;
265
+ totalDurationMs: number;
266
+ };
267
+ type Metrics = {
268
+ record(entry: RequestLog): void;
269
+ report(): MetricsReport;
270
+ reset(): void;
271
+ };
272
+
273
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
274
+ type JournalEntry = RequestLog & {
275
+ at: string;
276
+ };
277
+ type JournalQuery = {
278
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
279
+ namespace?: string;
280
+ operationId?: string;
281
+ status?: number;
282
+ /** Only entries at or after this instant (epoch ms). */
283
+ since?: number;
284
+ /** At most this many, the most recent kept. */
285
+ limit?: number;
286
+ };
287
+ type Journal = {
288
+ readonly size: number;
289
+ record(entry: JournalEntry): void;
290
+ list(query?: JournalQuery): JournalEntry[];
291
+ /** Forget one namespace's entries, or every namespace's. */
292
+ clear(namespace?: string): void;
293
+ };
294
+
295
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
296
+ type CredentialRegistry = {
297
+ set(credential: string, namespace: string): void;
298
+ get(credential: string): string | undefined;
299
+ remove(credential: string): boolean;
300
+ clear(): void;
301
+ entries(): {
302
+ credential: string;
303
+ namespace: string;
304
+ }[];
305
+ };
306
+
307
+ /**
308
+ * Sequential id source persisted in SQLite. Ids are deterministic for a given
309
+ * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
310
+ */
311
+ declare class IdSequence {
312
+ private readonly sqlite;
313
+ private readonly namespace;
314
+ private readonly salt;
315
+ constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
316
+ next(prefix: string, length?: number): string;
317
+ }
318
+
319
+ /** A stable identifier for a point in a {@link Timeline}. */
320
+ type CheckpointId = string;
321
+ /** An immutable node in a timeline's checkpoint DAG. */
322
+ type Checkpoint<T> = Readonly<{
323
+ id: CheckpointId;
324
+ branch: string;
325
+ parent: CheckpointId | null;
326
+ /** Logical time supplied by the timeline's injected clock. */
327
+ at: number;
328
+ value: T;
329
+ }>;
330
+ type TimelineOptions = {
331
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
332
+ now?: () => number;
333
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
334
+ maxCheckpoints?: number;
335
+ /** Customize deterministic checkpoint IDs. */
336
+ id?: (sequence: number) => CheckpointId;
337
+ };
338
+ type CommitOptions = {
339
+ branch?: string;
340
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
341
+ parent?: CheckpointId | null;
342
+ };
343
+ type ForkOptions = {
344
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
345
+ from?: CheckpointId;
346
+ };
347
+ /**
348
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
349
+ * records, namespace images, or copy-on-write SQL engine snapshots.
350
+ *
351
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
352
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
353
+ * (the logical clock) is injected.
354
+ */
355
+ declare class Timeline<T> {
356
+ readonly maxCheckpoints: number;
357
+ private readonly now;
358
+ private readonly makeId;
359
+ private readonly nodes;
360
+ private readonly heads;
361
+ /** Unreferenced nodes in the exact order they became collectible. */
362
+ private readonly evictable;
363
+ /** Branch heads plus explicit retainers. Absent means zero. */
364
+ private readonly references;
365
+ private readonly explicitPins;
366
+ private sequence;
367
+ constructor(options?: TimelineOptions);
368
+ /** Capture a new immutable value and move `branch` to it. */
369
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
370
+ /** Create a branch pointer without copying its checkpoint value. */
371
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
372
+ /** Move a branch pointer to an existing checkpoint. */
373
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
374
+ get(id: CheckpointId): Checkpoint<T>;
375
+ head(branch?: string): Checkpoint<T> | undefined;
376
+ hasBranch(branch: string): boolean;
377
+ branches(): Readonly<Record<string, CheckpointId>>;
378
+ checkpoints(): readonly Checkpoint<T>[];
379
+ /** Number of retained checkpoints without allocating an array. */
380
+ get size(): number;
381
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
382
+ retain(id: CheckpointId): Checkpoint<T>;
383
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
384
+ release(id: CheckpointId): boolean;
385
+ deleteBranch(branch: string): boolean;
386
+ /**
387
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
388
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
389
+ * storage dependency, so a retained node remains usable after pruning.
390
+ */
391
+ gc(max?: number): CheckpointId[];
392
+ private collect;
393
+ private moveHead;
394
+ private addReference;
395
+ private removeReference;
396
+ private assertBranch;
397
+ }
398
+
399
+ /**
400
+ * Anything that can answer a Fetch `Request` with a `Response`.
401
+ *
402
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
403
+ * It is the only contract shared across the whole graph.
404
+ */
405
+ interface FetchAPI {
406
+ fetch(request: Request): Promise<Response>;
407
+ }
408
+
409
+ /**
410
+ * A point-in-time copy of everything a service namespace holds.
411
+ *
412
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
413
+ * is generic: any service gets per-test rollback without knowing its own schema.
414
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
415
+ */
416
+ type NamespaceSnapshot = {
417
+ namespace: string;
418
+ records: {
419
+ collection: string;
420
+ id: string;
421
+ seq: number;
422
+ value: string;
423
+ }[];
424
+ sequences: {
425
+ name: string;
426
+ kind: string;
427
+ value: number;
428
+ }[];
429
+ };
430
+
431
+ type WebhookEndpoint = {
432
+ /** Stable id; generated when omitted. */
433
+ id?: string;
434
+ url: string;
435
+ secret?: string;
436
+ /** Event types to deliver; omit or include `"*"` for every type. */
437
+ events?: string[];
438
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
439
+ tags?: Record<string, string>;
440
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
441
+ signUrl?: string;
442
+ headers?: Record<string, string>;
443
+ };
444
+ type WebhookMessage = {
445
+ id: string;
446
+ namespace: string;
447
+ type: string;
448
+ body: string;
449
+ contentType: string;
450
+ tags: Record<string, string>;
451
+ headers?: Record<string, string>;
452
+ /** Wall-clock ISO-8601 time of publication. */
453
+ publishedAt: string;
454
+ };
455
+ type WebhookAttempt = {
456
+ attempt: number;
457
+ at: string;
458
+ status: number | null;
459
+ error: string | null;
460
+ durationMs: number;
461
+ /** Exact receiver response body, when one was returned. */
462
+ responseBody?: string | null;
463
+ };
464
+ type WebhookDelivery = {
465
+ id: string;
466
+ messageId: string;
467
+ namespace: string;
468
+ type: string;
469
+ endpointId: string;
470
+ url: string;
471
+ state: "pending" | "delivered" | "failed" | "dropped";
472
+ attempts: WebhookAttempt[];
473
+ };
474
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
475
+ type WebhookFault = {
476
+ mode: "duplicate" | "reorder" | "drop";
477
+ /** Messages affected; default 1. */
478
+ count?: number;
479
+ };
480
+ type PublishInput = {
481
+ namespace: string;
482
+ type: string;
483
+ /** Exact body; objects are JSON-encoded. */
484
+ body: string | Record<string, unknown> | unknown[];
485
+ /** Default `application/json`, or form-encoded when `form` is given. */
486
+ contentType?: string;
487
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
488
+ form?: Record<string, string>;
489
+ tags?: Record<string, string>;
490
+ /** Message-specific delivery headers, captured as part of durable message state. */
491
+ headers?: Record<string, string>;
492
+ /** Message id; generated when omitted. */
493
+ id?: string;
494
+ };
495
+ type WebhookHub = {
496
+ publish(input: PublishInput): WebhookMessage;
497
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
498
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
499
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
500
+ endpoints(namespace: string): WebhookEndpoint[];
501
+ messages(namespace?: string): WebhookMessage[];
502
+ deliveries(namespace?: string): WebhookDelivery[];
503
+ replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
504
+ /** Run every pending retry (and release held reordered messages) now. */
505
+ flush(): Promise<void>;
506
+ /** Resolve once nothing is in flight. */
507
+ idle(): Promise<void>;
508
+ fault(namespace: string, fault: WebhookFault): void;
509
+ clear(namespace?: string): void;
510
+ };
511
+
512
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
513
+ type ServiceInstance = FetchAPI & {
514
+ reset(): Promise<void>;
515
+ };
516
+ type ServiceTimelineState = Readonly<{
517
+ snapshot: NamespaceSnapshot;
518
+ clock: Readonly<ReturnType<Clock["state"]>>;
519
+ rngState: number;
520
+ }>;
521
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
522
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
523
+ readonly name: string;
524
+ readonly sqlite: SqliteClient$1;
525
+ readonly clock: Clock;
526
+ readonly faults: FaultRegistry;
527
+ readonly metrics: Metrics;
528
+ readonly journal: Journal;
529
+ readonly rng: Rng;
530
+ readonly credentials: CredentialRegistry;
531
+ /** The webhook hub, when the service has outbound webhooks. */
532
+ readonly webhooks: WebhookHub | undefined;
533
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
534
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
535
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
536
+ instance(namespace?: string): T;
537
+ /** Public names of every namespace created so far. */
538
+ namespaces(): string[];
539
+ /** Reset one namespace, or every namespace with `"*"`. */
540
+ reset(namespace?: string): Promise<void>;
541
+ snapshot(namespace?: string): NamespaceSnapshot;
542
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
543
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
544
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
545
+ /** Create an isolated branch, optionally from a historical checkpoint. */
546
+ branch(name: string, options?: {
547
+ namespace?: string;
548
+ at?: string;
549
+ }): ServiceCheckpoint;
550
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
551
+ checkout(checkpoint: string, options?: {
552
+ namespace?: string;
553
+ branch?: string;
554
+ }): void;
555
+ /** Inspect the retained history for a namespace. */
556
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
557
+ };
558
+
559
+ /** Options every provider constructor accepts. */
560
+ type APIOptions = {
561
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
562
+ sqlite?: SqliteClient$1;
563
+ /** Clock used for `created`-style fields. Default `Date.now`. */
564
+ now?: () => number;
565
+ /**
566
+ * Storage namespace for this instance's records. Instances sharing one SQLite
567
+ * client stay isolated when their namespaces differ. Defaults to the service name.
568
+ */
569
+ namespace?: string;
570
+ };
571
+
572
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
573
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
574
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
575
+ type SqliteRunResult = {
576
+ changes: number;
577
+ lastInsertRowid: number | bigint;
578
+ };
579
+ /**
580
+ * Prepared statement bound to a {@link SqliteClient}.
581
+ *
582
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
583
+ */
584
+ interface SqliteStatement {
585
+ run(...params: SqliteValue[]): SqliteRunResult;
586
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
587
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
588
+ }
589
+ /**
590
+ * Sync SQLite client port owned by Mockingbird.
591
+ *
592
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
593
+ * `bun:sqlite` instances all work when they expose this surface.
594
+ */
595
+ interface SqliteClient {
596
+ exec(sql: string): void;
597
+ prepare(sql: string): SqliteStatement;
598
+ transaction<T>(fn: () => T): T;
599
+ }
600
+
601
+ /**
602
+ * The scripting model: the mock never generates language, it replays scripts.
603
+ *
604
+ * A script is a `match` (which model calls it answers) and a sequence of `turns`. The turn
605
+ * a call gets is read off the conversation itself, not from server state: it is the number
606
+ * of assistant messages since the member last said something (a user message with any
607
+ * content other than tool results). So the first call of a user turn gets turn 0, the call
608
+ * that resumes after a `toolResult` gets turn 1, and a new conversation starts over — with
609
+ * no bookkeeping that parallel workers or retries could skew.
610
+ *
611
+ * Only metadata is derived from a request (tool names, flags, a SHA-256 of the system
612
+ * prompt); prompt and message text are read for matching and never stored.
613
+ */
614
+ /** Operations a script can answer. */
615
+ declare const MODEL_OPERATIONS: readonly ["Converse", "ConverseStream", "InvokeModel", "InvokeModelWithBidirectionalStream", "InvokeHarness"];
616
+ type ModelOperation = (typeof MODEL_OPERATIONS)[number];
617
+ declare const STOP_REASONS: readonly ["end_turn", "tool_use", "max_tokens", "stop_sequence", "guardrail_intervened", "content_filtered"];
618
+ type StopReason = (typeof STOP_REASONS)[number];
619
+ /** Failure modes a turn (or a fault preset) can inject. */
620
+ declare const TURN_FAULTS: readonly ["throttling", "validation", "access_denied", "model_timeout", "service_unavailable", "internal_server", "mid_stream_exception", "max_tokens", "truncated_frame", "latency"];
621
+ type TurnFaultType = (typeof TURN_FAULTS)[number];
622
+ type TurnFault = {
623
+ type: TurnFaultType;
624
+ /** Error / exception message. Each type has a realistic default. */
625
+ message?: string;
626
+ /** `mid_stream_exception` / `truncated_frame`: content chunks sent before the failure. Default 1. */
627
+ afterChunks?: number;
628
+ /** `mid_stream_exception`: the exception frame's type. Default `modelStreamErrorException`. */
629
+ exceptionType?: string;
630
+ /** `latency`: mock-clock milliseconds before the response starts. */
631
+ latencyMs?: number;
632
+ };
633
+ type ScriptToolUse = {
634
+ name: string;
635
+ input?: unknown;
636
+ /** Default: a deterministic `tooluse_…` id. */
637
+ toolUseId?: string;
638
+ };
639
+ type ScriptUsage = {
640
+ inputTokens?: number;
641
+ outputTokens?: number;
642
+ totalTokens?: number;
643
+ cacheReadInputTokens?: number;
644
+ cacheWriteInputTokens?: number;
645
+ };
646
+ type ScriptTurn = {
647
+ /** Assistant text, streamed in `chunkSize`-character deltas. */
648
+ text?: string;
649
+ chunkSize?: number;
650
+ /** Mock-clock delay before each streamed chunk (TTFT and pacing tests). */
651
+ delayMsPerChunk?: number;
652
+ /** Reasoning text streamed as `reasoningContent` before the answer. */
653
+ reasoning?: string;
654
+ toolUse?: ScriptToolUse | ScriptToolUse[];
655
+ /** Structured output, rendered in whichever form the request asked for. */
656
+ json?: unknown;
657
+ stopReason?: StopReason;
658
+ /** `true`, or the trace / blocked text, for a `guardrail_intervened` turn. */
659
+ guardrail?: boolean | {
660
+ text?: string;
661
+ trace?: unknown;
662
+ };
663
+ usage?: ScriptUsage;
664
+ /** This turn only answers a call whose last user message carries this tool's result. */
665
+ expectToolResult?: {
666
+ name: string;
667
+ };
668
+ fault?: TurnFaultType | TurnFault;
669
+ /** Nova Sonic: the ASR transcript echoed back for a spoken user turn. */
670
+ userTranscript?: string;
671
+ /** AgentCore InvokeHarness: a tool-result delta (`[{text}|{json}]`) instead of text. */
672
+ toolResult?: unknown[];
673
+ };
674
+ type TextMatch = {
675
+ contains?: string;
676
+ regex?: string;
677
+ flags?: string;
678
+ };
679
+ type ScriptMatch = {
680
+ /** Glob (`*` wildcard, case-insensitive) over the decoded model id, ARN or harness ARN. */
681
+ modelId?: string;
682
+ operation?: ModelOperation | ModelOperation[];
683
+ lastUserText?: string | TextMatch;
684
+ /** SHA-256 hex of the system prompt (text blocks joined with "\n"). */
685
+ systemHash?: string;
686
+ toolsInclude?: string[];
687
+ /** `auto`, `any`, `none`, or a forced tool's name. */
688
+ toolChoice?: string;
689
+ hasDocument?: boolean;
690
+ hasImage?: boolean;
691
+ /** 0-based index of this call among the namespace's model calls. */
692
+ callIndex?: number;
693
+ };
694
+ type Script = {
695
+ id: string;
696
+ match?: ScriptMatch;
697
+ turns: ScriptTurn[];
698
+ /** Stop matching after this many calls (counted per namespace). */
699
+ times?: number;
700
+ };
701
+ /** Parse and validate one script; a string is the first problem found. */
702
+ declare const parseScript: (value: unknown, index: number) => Script | string;
703
+
704
+ type PlanBlock = {
705
+ kind: "text";
706
+ text: string;
707
+ } | {
708
+ kind: "reasoning";
709
+ text: string;
710
+ } | {
711
+ kind: "toolUse";
712
+ toolUseId: string;
713
+ name: string;
714
+ input: unknown;
715
+ } | {
716
+ kind: "toolResult";
717
+ toolUseId: string;
718
+ content: unknown[];
719
+ };
720
+ type Usage = {
721
+ inputTokens: number;
722
+ outputTokens: number;
723
+ totalTokens: number;
724
+ cacheReadInputTokens?: number;
725
+ cacheWriteInputTokens?: number;
726
+ };
727
+ type Plan = {
728
+ /** The script that answered, or `undefined` for the unscripted default. */
729
+ scriptId: string | undefined;
730
+ /** Which default answered, when unscripted: `chat`, `structured`, `classifier`, `scribe`, `titan`, `harness`, `sonic`. */
731
+ fallback?: string;
732
+ blocks: PlanBlock[];
733
+ stopReason: StopReason;
734
+ usage: Usage;
735
+ trace?: Record<string, unknown>;
736
+ fault?: TurnFault;
737
+ chunkSize: number;
738
+ delayMsPerChunk: number;
739
+ userTranscript?: string;
740
+ };
741
+ /** Bedrock's canned guardrail refusal. */
742
+ declare const GUARDRAIL_BLOCKED_TEXT = "Sorry, the model cannot answer this question.";
743
+ /** What an unscripted chat call says. Deliberately content-free (never an echo). */
744
+ declare const DEFAULT_CHAT_TEXT = "OK.";
745
+ declare const DEFAULT_CLASSIFIER: {
746
+ category: string;
747
+ confidence: number;
748
+ };
749
+ declare const DEFAULT_SOAP_NOTE: {
750
+ sections: {
751
+ title: string;
752
+ content: string;
753
+ }[];
754
+ summary: string;
755
+ };
756
+
757
+ /** Waits `ms` on the mock clock; resolves early when `signal` aborts. */
758
+ type Sleep = (ms: number, signal?: AbortSignal) => Promise<void>;
759
+
760
+ /** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */
761
+ type Settings = {
762
+ /** What an unscripted chat call answers. Default `"OK."`. */
763
+ defaultText: string;
764
+ /** Characters per streamed text delta when a turn gives no `chunkSize`. Default 16. */
765
+ chunkSize: number;
766
+ /** Mock-clock delay before each streamed delta when a turn gives none. Default 0. */
767
+ delayMsPerChunk: number;
768
+ /** Nova Sonic: USER audio frames that end a spoken turn without a contentEnd (0 = off). */
769
+ audioTurnChunks: number;
770
+ };
771
+ declare const DEFAULT_SETTINGS: Settings;
772
+ /** Counts for `GET /__admin/scripts` (and `/health`): metadata only. */
773
+ type ModelStats = {
774
+ calls: number;
775
+ scripted: number;
776
+ /** Calls no script answered (the defaults). */
777
+ unscripted: number;
778
+ byScript: Record<string, number>;
779
+ /** Unscripted calls by which default answered them. */
780
+ byFallback: Record<string, number>;
781
+ byOperation: Record<string, number>;
782
+ };
783
+ declare class BedrockState {
784
+ private readonly seed;
785
+ readonly scripts: Collection<Script>;
786
+ readonly uses: Collection<number>;
787
+ readonly settings: Collection<Settings>;
788
+ readonly stats: Collection<ModelStats>;
789
+ readonly ids: IdSequence;
790
+ constructor(sqlite: SqliteClient, namespace: string, seed: {
791
+ settings: Partial<Settings>;
792
+ scripts: readonly Script[];
793
+ });
794
+ /** Re-apply the configured settings and scripts after a reset. */
795
+ ensureSeeded(): void;
796
+ current(): Settings;
797
+ update(patch: Partial<Settings>): Settings;
798
+ list(): Script[];
799
+ /** Replace every script (`PUT`) or add/overwrite by id (`POST`). */
800
+ put(scripts: readonly Script[], replace: boolean): Script[];
801
+ remove(id?: string): number;
802
+ usesOf(id: string): number;
803
+ use(id: string): void;
804
+ /** The 0-based index of this model call in the namespace, then count it. */
805
+ nextCallIndex(): number;
806
+ record(operation: string, scriptId: string | undefined, fallback: string | undefined): void;
807
+ currentStats(): ModelStats;
808
+ }
809
+
810
+ /**
811
+ * AWS event-stream framing (`application/vnd.amazon.eventstream`), both directions.
812
+ *
813
+ * Every frame is: a 12-byte prelude (total length, headers length, CRC32 of those 8 bytes),
814
+ * the headers, the payload, and a CRC32 of everything before it. `@smithy/eventstream-codec`
815
+ * (the AWS SDKs and the AI SDK) rejects a frame whose lengths or checksums are off by one
816
+ * byte, so this module is exact: it is the only place a frame is built or parsed.
817
+ *
818
+ * The same codec reads what an SDK sends on a bidirectional stream. Those frames arrive
819
+ * wrapped in a SigV4 envelope (`:date` + `:chunk-signature` headers around the encoded
820
+ * inner frame); {@link unwrapSigned} opens it. The signature itself is never verified.
821
+ */
822
+ /** A typed header value; plain strings encode as type 7 (string). */
823
+ type HeaderValue = {
824
+ type: "boolean";
825
+ value: boolean;
826
+ } | {
827
+ type: "byte";
828
+ value: number;
829
+ } | {
830
+ type: "short";
831
+ value: number;
832
+ } | {
833
+ type: "integer";
834
+ value: number;
835
+ } | {
836
+ type: "long";
837
+ value: bigint;
838
+ } | {
839
+ type: "binary";
840
+ value: Uint8Array;
841
+ } | {
842
+ type: "string";
843
+ value: string;
844
+ } | {
845
+ type: "timestamp";
846
+ value: Date;
847
+ } | {
848
+ type: "uuid";
849
+ value: string;
850
+ };
851
+ type EventStreamMessage = {
852
+ headers: Record<string, HeaderValue>;
853
+ body: Uint8Array;
854
+ };
855
+ /** What {@link encodeMessage} accepts: header values may be bare strings. */
856
+ type MessageInput = {
857
+ headers: Record<string, HeaderValue | string>;
858
+ body?: Uint8Array | string;
859
+ };
860
+ declare class EventStreamError extends Error {
861
+ constructor(message: string);
862
+ }
863
+ /** CRC-32 (IEEE 802.3, the one event-stream uses) of `bytes`. */
864
+ declare const crc32: (bytes: Uint8Array) => number;
865
+ /** One complete frame: prelude, prelude CRC, headers, payload, message CRC. */
866
+ declare const encodeMessage: (message: MessageInput) => Uint8Array;
867
+ /** Parse exactly one frame, checking both lengths and both checksums. */
868
+ declare const decodeMessage: (frame: Uint8Array) => EventStreamMessage;
869
+ /** Splits a byte stream into frames as they complete. */
870
+ declare class FrameReader {
871
+ private buffer;
872
+ /** Add bytes; returns every frame they complete. */
873
+ push(chunk: Uint8Array): EventStreamMessage[];
874
+ /** Bytes of an incomplete frame still waiting for the rest. */
875
+ get pending(): number;
876
+ }
877
+ /**
878
+ * The frame inside a SigV4 event envelope (`:chunk-signature`), `null` for the empty
879
+ * end-of-stream envelope, or the frame itself when it is not signed.
880
+ */
881
+ declare const unwrapSigned: (message: EventStreamMessage) => EventStreamMessage | null;
882
+ /** An `event` frame whose payload is JSON (or raw bytes, for blob event payloads). */
883
+ declare const eventFrame: (eventType: string, payload: unknown, contentType?: string) => Uint8Array;
884
+ /** An `exception` frame, as a service raises one mid-stream. */
885
+ declare const exceptionFrame: (exceptionType: string, body: Record<string, unknown>) => Uint8Array;
886
+ /** An async iterator over the frames of a byte stream (a request or response body). */
887
+ declare function readFrames(body: ReadableStream<Uint8Array> | null): AsyncGenerator<EventStreamMessage>;
888
+
889
+ /**
890
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
891
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
892
+ */
893
+ type JsonPrimitive = string | number | boolean | null;
894
+ type JsonValue = JsonPrimitive | JsonValue[] | {
895
+ [key: string]: JsonValue;
896
+ };
897
+ type ReferenceObject = {
898
+ $ref: string;
899
+ description?: string;
900
+ summary?: string;
901
+ };
902
+ type SchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
903
+ type SchemaObject = {
904
+ $ref?: string;
905
+ type?: SchemaType | SchemaType[];
906
+ title?: string;
907
+ description?: string;
908
+ format?: string;
909
+ enum?: JsonValue[];
910
+ const?: JsonValue;
911
+ default?: JsonValue;
912
+ example?: JsonValue;
913
+ examples?: JsonValue[];
914
+ nullable?: boolean;
915
+ deprecated?: boolean;
916
+ readOnly?: boolean;
917
+ writeOnly?: boolean;
918
+ minimum?: number;
919
+ maximum?: number;
920
+ exclusiveMinimum?: number;
921
+ exclusiveMaximum?: number;
922
+ multipleOf?: number;
923
+ minLength?: number;
924
+ maxLength?: number;
925
+ pattern?: string;
926
+ minItems?: number;
927
+ maxItems?: number;
928
+ uniqueItems?: boolean;
929
+ items?: SchemaObject;
930
+ prefixItems?: SchemaObject[];
931
+ minProperties?: number;
932
+ maxProperties?: number;
933
+ required?: string[];
934
+ properties?: Record<string, SchemaObject>;
935
+ additionalProperties?: boolean | SchemaObject;
936
+ propertyNames?: SchemaObject;
937
+ oneOf?: SchemaObject[];
938
+ anyOf?: SchemaObject[];
939
+ allOf?: SchemaObject[];
940
+ not?: SchemaObject;
941
+ discriminator?: {
942
+ propertyName: string;
943
+ mapping?: Record<string, string>;
944
+ };
945
+ [extension: `x-${string}`]: unknown;
946
+ };
947
+ type ParameterLocation = "path" | "query" | "header" | "cookie";
948
+ type ParameterObject = {
949
+ name: string;
950
+ in: ParameterLocation;
951
+ description?: string;
952
+ required?: boolean;
953
+ deprecated?: boolean;
954
+ style?: string;
955
+ explode?: boolean;
956
+ schema?: SchemaObject;
957
+ content?: Record<string, MediaTypeObject>;
958
+ example?: JsonValue;
959
+ [extension: `x-${string}`]: unknown;
960
+ };
961
+ type MediaTypeObject = {
962
+ schema?: SchemaObject;
963
+ example?: JsonValue;
964
+ examples?: Record<string, unknown>;
965
+ encoding?: Record<string, unknown>;
966
+ [extension: `x-${string}`]: unknown;
967
+ };
968
+ type RequestBodyObject = {
969
+ description?: string;
970
+ required?: boolean;
971
+ content: Record<string, MediaTypeObject>;
972
+ [extension: `x-${string}`]: unknown;
973
+ };
974
+ type HeaderObject = {
975
+ description?: string;
976
+ required?: boolean;
977
+ schema?: SchemaObject;
978
+ [extension: `x-${string}`]: unknown;
979
+ };
980
+ type ResponseObject = {
981
+ description: string;
982
+ headers?: Record<string, HeaderObject | ReferenceObject>;
983
+ content?: Record<string, MediaTypeObject>;
984
+ [extension: `x-${string}`]: unknown;
985
+ };
986
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
987
+ type SecurityRequirementObject = Record<string, string[]>;
988
+ type OperationObject = {
989
+ operationId?: string;
990
+ summary?: string;
991
+ description?: string;
992
+ tags?: string[];
993
+ deprecated?: boolean;
994
+ parameters?: Array<ParameterObject | ReferenceObject>;
995
+ requestBody?: RequestBodyObject | ReferenceObject;
996
+ responses: ResponsesObject;
997
+ security?: SecurityRequirementObject[];
998
+ [extension: `x-${string}`]: unknown;
999
+ };
1000
+ declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
1001
+ type HttpMethod = (typeof HTTP_METHODS)[number];
1002
+ type PathItemObject = {
1003
+ summary?: string;
1004
+ description?: string;
1005
+ parameters?: Array<ParameterObject | ReferenceObject>;
1006
+ [extension: `x-${string}`]: unknown;
1007
+ } & Partial<Record<HttpMethod, OperationObject>>;
1008
+ type SecuritySchemeObject = {
1009
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
1010
+ description?: string;
1011
+ name?: string;
1012
+ in?: ParameterLocation;
1013
+ scheme?: string;
1014
+ bearerFormat?: string;
1015
+ flows?: Record<string, unknown>;
1016
+ openIdConnectUrl?: string;
1017
+ [extension: `x-${string}`]: unknown;
1018
+ };
1019
+ type ComponentsObject = {
1020
+ schemas?: Record<string, SchemaObject>;
1021
+ responses?: Record<string, ResponseObject>;
1022
+ parameters?: Record<string, ParameterObject>;
1023
+ requestBodies?: Record<string, RequestBodyObject>;
1024
+ headers?: Record<string, HeaderObject>;
1025
+ securitySchemes?: Record<string, SecuritySchemeObject>;
1026
+ [extension: `x-${string}`]: unknown;
1027
+ };
1028
+ type ServerObject = {
1029
+ url: string;
1030
+ description?: string;
1031
+ variables?: Record<string, unknown>;
1032
+ [extension: `x-${string}`]: unknown;
1033
+ };
1034
+ type InfoObject = {
1035
+ title: string;
1036
+ version: string;
1037
+ description?: string;
1038
+ [extension: `x-${string}`]: unknown;
1039
+ };
1040
+ type OpenAPIDocument = {
1041
+ openapi: string;
1042
+ info: InfoObject;
1043
+ servers?: ServerObject[];
1044
+ paths: Record<string, PathItemObject>;
1045
+ components?: ComponentsObject;
1046
+ security?: SecurityRequirementObject[];
1047
+ tags?: Array<{
1048
+ name: string;
1049
+ description?: string;
1050
+ }>;
1051
+ [extension: `x-${string}`]: unknown;
1052
+ };
1053
+
1054
+ declare const document: OpenAPIDocument;
1055
+ type OperationId = "Converse" | "ConverseStream" | "InvokeModel" | "InvokeModelWithResponseStream" | "InvokeModelWithBidirectionalStream" | "InvokeHarness";
1056
+ type SupportedOperationId = "Converse" | "ConverseStream" | "InvokeModel" | "InvokeModelWithBidirectionalStream" | "InvokeHarness";
1057
+ declare const operationIds: readonly ["Converse", "ConverseStream", "InvokeModel", "InvokeModelWithResponseStream", "InvokeModelWithBidirectionalStream", "InvokeHarness"];
1058
+ declare const supportedOperationIds: readonly ["Converse", "ConverseStream", "InvokeModel", "InvokeModelWithBidirectionalStream", "InvokeHarness"];
1059
+
1060
+ /**
1061
+ * The smallest instance of a JSON Schema: what an unscripted structured-output call
1062
+ * answers with. The model never generates language here, so a caller's schema
1063
+ * (`Output.object`, a forced tool's `inputSchema`, `outputConfig.textFormat`) is the only
1064
+ * thing that decides the shape, and the object always validates against it.
1065
+ *
1066
+ * Handles what zod-to-json-schema, the AI SDK and hand-written tool schemas emit: `type`
1067
+ * (including `["string","null"]`), `enum`, `const`, `anyOf`/`oneOf`/`allOf`, `$ref` into
1068
+ * `definitions`/`$defs`, required properties, array bounds and `uniqueItems`, string
1069
+ * lengths and common formats, and numeric bounds.
1070
+ */
1071
+ /** A value that validates against `schema` (resolved against `root` for `$ref`s). */
1072
+ declare const sampleSchema: (schema: unknown, root?: unknown, depth?: number) => unknown;
1073
+
1074
+ /**
1075
+ * Every named Bedrock misbehaviour our consumer branches on, switched on with
1076
+ * `POST /__admin/faults {"preset": "<name>", "count"?: n}` (a scripted turn can carry the
1077
+ * same `fault` for one conversation step).
1078
+ */
1079
+ declare const BEDROCK_PRESETS: Record<string, FaultPreset>;
1080
+ type BedrockRuntimeOptions = {
1081
+ sqlite?: SqliteClient;
1082
+ clock?: Clock;
1083
+ seed?: number | string;
1084
+ adminKey?: string;
1085
+ onLog?: (entry: RequestLog) => void;
1086
+ settings?: Partial<Settings>;
1087
+ /** Scripts every namespace starts with (and returns to on reset). */
1088
+ scripts?: readonly Script[];
1089
+ };
1090
+ type BedrockRuntime = ServiceRuntime<BedrockAPI>;
1091
+ /**
1092
+ * The Bedrock mock with Mockingbird's full service contract: `/health`, `/__admin/*`,
1093
+ * namespaces by header, by `/ns/<name>` path prefix, or by SigV4 access key id
1094
+ * (`PUT /__admin/credentials {"credentials": {"<AWS_ACCESS_KEY_ID>": "<namespace>"}}`),
1095
+ * clock control (script pacing runs on it), fault presets, scripts and a request journal
1096
+ * that records metadata only.
1097
+ */
1098
+ declare const createRuntime: (options?: BedrockRuntimeOptions) => BedrockRuntime;
1099
+
1100
+ declare const BEDROCK_NAMESPACE = "bedrock";
1101
+ /** A Bedrock error response: status, `x-amzn-ErrorType`, `{message}`. */
1102
+ declare const bedrockError: (status: number, type: string, message: string, requestId?: string) => Response;
1103
+ /**
1104
+ * The namespace credential of an AWS request: its SigV4 access key id. Map it with
1105
+ * `PUT /__admin/credentials {"credentials": {"<AWS_ACCESS_KEY_ID>": "<namespace>"}}`.
1106
+ */
1107
+ declare const accessKeyCredential: (request: Request) => string | undefined;
1108
+ /**
1109
+ * Wait `ms` on a (possibly frozen) mock clock: polls `now()` so a frozen clock waits until
1110
+ * a test advances it, and a live clock waits in real time.
1111
+ */
1112
+ declare const clockSleep: (now: () => number) => Sleep;
1113
+ /** A deterministic 1024-d (or `dims`-d) unit vector: SHA-256(inputText) in counter mode. */
1114
+ declare const titanEmbedding: (inputText: string, dims?: number) => Promise<number[]>;
1115
+ type BedrockAPIOptions = APIOptions & {
1116
+ /** Initial per-namespace settings. */
1117
+ settings?: Partial<Settings>;
1118
+ /** Scripts every namespace starts with (re-applied on reset). */
1119
+ scripts?: readonly Script[];
1120
+ /** Wait on the mock clock. Default: real time. */
1121
+ sleep?: Sleep;
1122
+ };
1123
+ /**
1124
+ * Stateful, scriptable mock of Amazon Bedrock Runtime (and the AgentCore harness).
1125
+ *
1126
+ * It never generates language: each model call is answered by the first script whose
1127
+ * `match` accepts it and that has a turn for this point in the conversation, or by an
1128
+ * unscripted default (counted as `unscripted`). Every answer can be rendered as a Converse
1129
+ * body, a ConverseStream event stream, an Anthropic Messages body, a harness stream or a
1130
+ * Nova Sonic session.
1131
+ */
1132
+ declare class BedrockAPI implements FetchAPI$1 {
1133
+ readonly app: Hono;
1134
+ readonly sqlite: SqliteClient;
1135
+ readonly state: BedrockState;
1136
+ private readonly service;
1137
+ private readonly now;
1138
+ private readonly sleep;
1139
+ constructor(options?: BedrockAPIOptions);
1140
+ fetch(request: Request): Promise<Response>;
1141
+ reset(): Promise<void>;
1142
+ scripts(): Script[];
1143
+ putScripts(scripts: readonly Script[], replace?: boolean): Script[];
1144
+ removeScripts(id?: string): number;
1145
+ stats(): ModelStats;
1146
+ private requestId;
1147
+ private planContext;
1148
+ /**
1149
+ * First script with a turn for this call, else the default (which `unscripted` may
1150
+ * replace with an operation-specific one); records stats either way.
1151
+ */
1152
+ private resolve;
1153
+ /** Journal notes: metadata only (never message or prompt text). */
1154
+ private notes;
1155
+ private jsonBody;
1156
+ /** A pre-stream fault as the vendor's error, or `undefined` to carry on. */
1157
+ private preStream;
1158
+ private eventStream;
1159
+ private converse;
1160
+ private invokeModel;
1161
+ private titan;
1162
+ private invokeHarness;
1163
+ /** The unscripted eRx prescreen answer: eligible for clinician review. */
1164
+ private harnessDefault;
1165
+ private bidirectional;
1166
+ }
1167
+
1168
+ export { BEDROCK_NAMESPACE, BEDROCK_PRESETS, BedrockAPI, DEFAULT_CHAT_TEXT, DEFAULT_CLASSIFIER, DEFAULT_SETTINGS, DEFAULT_SOAP_NOTE, EventStreamError, FrameReader, GUARDRAIL_BLOCKED_TEXT, MODEL_OPERATIONS, STOP_REASONS, TURN_FAULTS, accessKeyCredential, bedrockError, clockSleep, crc32, createRuntime, decodeMessage, document, encodeMessage, eventFrame, exceptionFrame, operationIds, parseScript, readFrames, sampleSchema, supportedOperationIds, titanEmbedding, unwrapSigned };
1169
+ export type { BedrockAPIOptions, BedrockRuntime, BedrockRuntimeOptions, EventStreamMessage, FetchAPI$1 as FetchAPI, HeaderValue, MessageInput, ModelOperation, ModelStats, OperationId, Plan, PlanBlock, Script, ScriptMatch, ScriptToolUse, ScriptTurn, ScriptUsage, Settings, SqliteClient, StopReason, SupportedOperationId, TextMatch, TurnFault, TurnFaultType, Usage };