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