@buildanagent/gateway 0.0.0-stage → 0.1.0-alpha.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.
Files changed (126) hide show
  1. package/LICENSE +52 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +299 -2
  5. package/dist/adapters/anthropic/adapter.d.ts +25 -0
  6. package/dist/adapters/anthropic/adapter.js +183 -0
  7. package/dist/adapters/anthropic/adapter.js.map +1 -0
  8. package/dist/adapters/anthropic/failure.d.ts +20 -0
  9. package/dist/adapters/anthropic/failure.js +46 -0
  10. package/dist/adapters/anthropic/failure.js.map +1 -0
  11. package/dist/adapters/anthropic/index.d.ts +3 -0
  12. package/dist/adapters/anthropic/index.js +3 -0
  13. package/dist/adapters/anthropic/index.js.map +1 -0
  14. package/dist/adapters/anthropic/request.d.ts +53 -0
  15. package/dist/adapters/anthropic/request.js +250 -0
  16. package/dist/adapters/anthropic/request.js.map +1 -0
  17. package/dist/adapters/anthropic/response.d.ts +31 -0
  18. package/dist/adapters/anthropic/response.js +212 -0
  19. package/dist/adapters/anthropic/response.js.map +1 -0
  20. package/dist/adapters/anthropic/usage.d.ts +26 -0
  21. package/dist/adapters/anthropic/usage.js +39 -0
  22. package/dist/adapters/anthropic/usage.js.map +1 -0
  23. package/dist/adapters/openai-chat/adapter.d.ts +18 -0
  24. package/dist/adapters/openai-chat/adapter.js +86 -0
  25. package/dist/adapters/openai-chat/adapter.js.map +1 -0
  26. package/dist/adapters/openai-chat/compat.d.ts +58 -0
  27. package/dist/adapters/openai-chat/compat.js +19 -0
  28. package/dist/adapters/openai-chat/compat.js.map +1 -0
  29. package/dist/adapters/openai-chat/failure.d.ts +25 -0
  30. package/dist/adapters/openai-chat/failure.js +33 -0
  31. package/dist/adapters/openai-chat/failure.js.map +1 -0
  32. package/dist/adapters/openai-chat/index.d.ts +4 -0
  33. package/dist/adapters/openai-chat/index.js +3 -0
  34. package/dist/adapters/openai-chat/index.js.map +1 -0
  35. package/dist/adapters/openai-chat/request.d.ts +47 -0
  36. package/dist/adapters/openai-chat/request.js +227 -0
  37. package/dist/adapters/openai-chat/request.js.map +1 -0
  38. package/dist/adapters/openai-chat/response.d.ts +22 -0
  39. package/dist/adapters/openai-chat/response.js +203 -0
  40. package/dist/adapters/openai-chat/response.js.map +1 -0
  41. package/dist/adapters/openai-chat/usage.d.ts +19 -0
  42. package/dist/adapters/openai-chat/usage.js +22 -0
  43. package/dist/adapters/openai-chat/usage.js.map +1 -0
  44. package/dist/adapters/strict-schema.d.ts +67 -0
  45. package/dist/adapters/strict-schema.js +269 -0
  46. package/dist/adapters/strict-schema.js.map +1 -0
  47. package/dist/adapters/wire.d.ts +77 -0
  48. package/dist/adapters/wire.js +137 -0
  49. package/dist/adapters/wire.js.map +1 -0
  50. package/dist/catalog.d.ts +65 -0
  51. package/dist/catalog.js +145 -0
  52. package/dist/catalog.js.map +1 -0
  53. package/dist/catalog.json +120 -0
  54. package/dist/classify.d.ts +25 -0
  55. package/dist/classify.js +37 -0
  56. package/dist/classify.js.map +1 -0
  57. package/dist/complete.d.ts +9 -0
  58. package/dist/complete.js +13 -0
  59. package/dist/complete.js.map +1 -0
  60. package/dist/cost.d.ts +42 -0
  61. package/dist/cost.js +122 -0
  62. package/dist/cost.js.map +1 -0
  63. package/dist/create-model.d.ts +7 -0
  64. package/dist/create-model.js +81 -0
  65. package/dist/create-model.js.map +1 -0
  66. package/dist/errors.d.ts +17 -0
  67. package/dist/errors.js +24 -0
  68. package/dist/errors.js.map +1 -0
  69. package/dist/index.d.ts +19 -0
  70. package/dist/index.js +17 -0
  71. package/dist/index.js.map +1 -0
  72. package/dist/middleware.d.ts +11 -0
  73. package/dist/middleware.js +22 -0
  74. package/dist/middleware.js.map +1 -0
  75. package/dist/names.d.ts +72 -0
  76. package/dist/names.js +175 -0
  77. package/dist/names.js.map +1 -0
  78. package/dist/provider-config.d.ts +15 -0
  79. package/dist/provider-config.js +23 -0
  80. package/dist/provider-config.js.map +1 -0
  81. package/dist/request-dump.d.ts +28 -0
  82. package/dist/request-dump.js +52 -0
  83. package/dist/request-dump.js.map +1 -0
  84. package/dist/request-policy.d.ts +18 -0
  85. package/dist/request-policy.js +27 -0
  86. package/dist/request-policy.js.map +1 -0
  87. package/dist/retry.d.ts +30 -0
  88. package/dist/retry.js +191 -0
  89. package/dist/retry.js.map +1 -0
  90. package/dist/runtime-types.d.ts +112 -0
  91. package/dist/runtime-types.js +2 -0
  92. package/dist/runtime-types.js.map +1 -0
  93. package/dist/spec.d.ts +67 -0
  94. package/dist/spec.js +2 -0
  95. package/dist/spec.js.map +1 -0
  96. package/dist/sse.d.ts +15 -0
  97. package/dist/sse.js +73 -0
  98. package/dist/sse.js.map +1 -0
  99. package/dist/stream-contract.d.ts +23 -0
  100. package/dist/stream-contract.js +101 -0
  101. package/dist/stream-contract.js.map +1 -0
  102. package/dist/testing/guards.d.ts +16 -0
  103. package/dist/testing/guards.js +48 -0
  104. package/dist/testing/guards.js.map +1 -0
  105. package/dist/testing/index.d.ts +12 -0
  106. package/dist/testing/index.js +13 -0
  107. package/dist/testing/index.js.map +1 -0
  108. package/dist/testing/mock-transport.d.ts +49 -0
  109. package/dist/testing/mock-transport.js +101 -0
  110. package/dist/testing/mock-transport.js.map +1 -0
  111. package/dist/testing/random.d.ts +3 -0
  112. package/dist/testing/random.js +13 -0
  113. package/dist/testing/random.js.map +1 -0
  114. package/dist/testing/setup.d.ts +1 -0
  115. package/dist/testing/setup.js +12 -0
  116. package/dist/testing/setup.js.map +1 -0
  117. package/dist/transform-messages.d.ts +32 -0
  118. package/dist/transform-messages.js +291 -0
  119. package/dist/transform-messages.js.map +1 -0
  120. package/dist/types.d.ts +130 -0
  121. package/dist/types.js +6 -0
  122. package/dist/types.js.map +1 -0
  123. package/dist/usage.d.ts +8 -0
  124. package/dist/usage.js +20 -0
  125. package/dist/usage.js.map +1 -0
  126. package/package.json +50 -3
@@ -0,0 +1,101 @@
1
+ export class StreamContractError extends Error {
2
+ name = "StreamContractError";
3
+ /** Position of the offending event in the stream, or the stream length when the stream ended early. */
4
+ position;
5
+ constructor(message, position) {
6
+ super(message);
7
+ this.position = position;
8
+ }
9
+ }
10
+ function blockPhase(type) {
11
+ const match = /^(text|reasoning|tool_input)_(start|delta|end)$/.exec(type);
12
+ if (!match)
13
+ return undefined;
14
+ return { kind: match[1], phase: match[2] };
15
+ }
16
+ /** Tracks one stream's state and checks each event against the stream rule. */
17
+ class StreamChecker {
18
+ seen = [];
19
+ #open = new Map();
20
+ #closed = new Set();
21
+ #terminal = false;
22
+ #output = false;
23
+ get ended() {
24
+ return this.#terminal;
25
+ }
26
+ check(event) {
27
+ const position = this.seen.length;
28
+ this.seen.push(event);
29
+ const fail = (message) => {
30
+ throw new StreamContractError(`${message} (event ${position}: ${event.type})`, position);
31
+ };
32
+ this.#checkOrder(event, position, fail);
33
+ if (event.type === "done" || event.type === "error") {
34
+ this.#checkTerminal(event, fail);
35
+ return;
36
+ }
37
+ if (event.type === "retry" && this.#output)
38
+ fail("a retry arrived after output was streamed");
39
+ const block = blockPhase(event.type);
40
+ if (!block)
41
+ return;
42
+ this.#output = true;
43
+ this.#checkBlock(event.index, block.kind, block.phase, fail);
44
+ }
45
+ #checkOrder(event, position, fail) {
46
+ if (this.#terminal)
47
+ fail("an event followed the terminal event");
48
+ if (position === 0 && event.type !== "start")
49
+ fail("the stream must begin with start");
50
+ if (position > 0 && event.type === "start")
51
+ fail("start appeared twice");
52
+ }
53
+ #checkTerminal(event, fail) {
54
+ this.#terminal = true;
55
+ const { stopReason } = event.message;
56
+ const failed = stopReason === "error" || stopReason === "aborted";
57
+ if (event.type === "error" && !failed)
58
+ fail(`an error terminal needs stopReason error or aborted, got ${stopReason}`);
59
+ if (event.type === "done" && failed)
60
+ fail(`a done terminal cannot have stopReason ${stopReason}`);
61
+ if (event.type === "done" && this.#open.size > 0) {
62
+ fail(`done arrived with open blocks at index ${[...this.#open.keys()].join(", ")}`);
63
+ }
64
+ }
65
+ #checkBlock(index, kind, phase, fail) {
66
+ if (phase === "start") {
67
+ if (this.#open.has(index) || this.#closed.has(index))
68
+ fail(`index ${index} started twice`);
69
+ this.#open.set(index, kind);
70
+ return;
71
+ }
72
+ if (this.#closed.has(index))
73
+ fail(`a ${kind}_${phase} arrived after index ${index} ended`);
74
+ const openKind = this.#open.get(index);
75
+ if (openKind === undefined)
76
+ fail(`a ${kind}_${phase} arrived before index ${index} started`);
77
+ if (openKind !== kind)
78
+ fail(`index ${index} started as ${openKind} but got ${kind}_${phase}`);
79
+ if (phase === "end") {
80
+ this.#open.delete(index);
81
+ this.#closed.add(index);
82
+ }
83
+ }
84
+ }
85
+ /**
86
+ * Consumes the stream, throws `StreamContractError` at the first violation, and returns every event it read. It
87
+ * checks an adapter's stream and a `Model.stream()` with its `retry` events alike.
88
+ */
89
+ export async function assertStreamContract(events) {
90
+ const checker = new StreamChecker();
91
+ const seen = [];
92
+ for await (const event of events) {
93
+ checker.check(event);
94
+ seen.push(event);
95
+ }
96
+ if (!checker.ended) {
97
+ throw new StreamContractError("the stream ended without a done or error event", checker.seen.length);
98
+ }
99
+ return seen;
100
+ }
101
+ //# sourceMappingURL=stream-contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-contract.js","sourceRoot":"","sources":["../src/stream-contract.ts"],"names":[],"mappings":"AAcA,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC1B,IAAI,GAAG,qBAAqB,CAAC;IAC/C,uGAAuG;IAC9F,QAAQ,CAAS;IAE1B,YAAY,OAAe,EAAE,QAAgB;QAC3C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;CACF;AAKD,SAAS,UAAU,CAAC,IAA0B;IAC5C,MAAM,KAAK,GAAG,iDAAiD,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3E,IAAI,CAAC,KAAK;QAAE,O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AC;IACnB,CAAC;IACD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACnB,MAAM,IAAI,mBAAmB,CAAC,gDAAgD,EAAE,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvG,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * `assertStreamContract()`: checks the stream rule every adapter and test model must follow (SDK plan §3.2).\n *\n * 1. `start` comes first, once.\n * 2. Each content index goes `*_start` → `*_delta`* → `*_end`, with one kind (text, reasoning or tool input) per index.\n * 3. Exactly one terminal event, `done` or `error`, ends the stream, and nothing follows it.\n * 4. An `error` terminal's message has `stopReason` `\"error\"` or `\"aborted\"`; a `done` terminal's has neither, and\n * every block it started has ended.\n * 5. A gateway `retry` event comes after `start` and before any block event, because output is never retried.\n * 6. A `warning` may come anywhere between `start` and the terminal event. It is not output, so a retry may follow it.\n */\nimport type { GatewayEvent } from \"./runtime-types.js\";\nimport type { ModelEvent } from \"./spec.js\";\n\nexport class StreamContractError extends Error {\n override readonly name = \"StreamContractError\";\n /** Position of the offending event in the stream, or the stream length when the stream ended early. */\n readonly position: number;\n\n constructor(message: string, position: number) {\n super(message);\n this.position = position;\n }\n}\n\ntype BlockKind = \"text\" | \"reasoning\" | \"tool_input\";\ntype BlockPhase = \"start\" | \"delta\" | \"end\";\n\nfunction blockPhase(type: GatewayEvent[\"type\"]): { kind: BlockKind; phase: BlockPhase } | undefined {\n const match = /^(text|reasoning|tool_input)_(start|delta|end)$/.exec(type);\n if (!match) return undefined;\n return { kind: match[1] as BlockKind, phase: match[2] as BlockPhase };\n}\n\n/** Tracks one stream's state and checks each event against the stream rule. */\nclass StreamChecker {\n readonly seen: GatewayEvent[] = [];\n readonly #open = new Map<number, BlockKind>();\n readonly #closed = new Set<number>();\n #terminal = false;\n #output = false;\n\n get ended(): boolean {\n return this.#terminal;\n }\n\n check(event: GatewayEvent): void {\n const position = this.seen.length;\n this.seen.push(event);\n const fail = (message: string): never => {\n throw new StreamContractError(`${message} (event ${position}: ${event.type})`, position);\n };\n this.#checkOrder(event, position, fail);\n if (event.type === \"done\" || event.type === \"error\") {\n this.#checkTerminal(event, fail);\n return;\n }\n if (event.type === \"retry\" && this.#output) fail(\"a retry arrived after output was streamed\");\n const block = blockPhase(event.type);\n if (!block) return;\n this.#output = true;\n this.#checkBlock((event as { index: number }).index, block.kind, block.phase, fail);\n }\n\n #checkOrder(event: GatewayEvent, position: number, fail: (message: string) => never): void {\n if (this.#terminal) fail(\"an event followed the terminal event\");\n if (position === 0 && event.type !== \"start\") fail(\"the stream must begin with start\");\n if (position > 0 && event.type === \"start\") fail(\"start appeared twice\");\n }\n\n #checkTerminal(event: Extract<ModelEvent, { type: \"done\" | \"error\" }>, fail: (message: string) => never): void {\n this.#terminal = true;\n const { stopReason } = event.message;\n const failed = stopReason === \"error\" || stopReason === \"aborted\";\n if (event.type === \"error\" && !failed)\n fail(`an error terminal needs stopReason error or aborted, got ${stopReason}`);\n if (event.type === \"done\" && failed) fail(`a done terminal cannot have stopReason ${stopReason}`);\n if (event.type === \"done\" && this.#open.size > 0) {\n fail(`done arrived with open blocks at index ${[...this.#open.keys()].join(\", \")}`);\n }\n }\n\n #checkBlock(index: number, kind: BlockKind, phase: BlockPhase, fail: (message: string) => never): void {\n if (phase === \"start\") {\n if (this.#open.has(index) || this.#closed.has(index)) fail(`index ${index} started twice`);\n this.#open.set(index, kind);\n return;\n }\n if (this.#closed.has(index)) fail(`a ${kind}_${phase} arrived after index ${index} ended`);\n const openKind = this.#open.get(index);\n if (openKind === undefined) fail(`a ${kind}_${phase} arrived before index ${index} started`);\n if (openKind !== kind) fail(`index ${index} started as ${openKind} but got ${kind}_${phase}`);\n if (phase === \"end\") {\n this.#open.delete(index);\n this.#closed.add(index);\n }\n }\n}\n\n/**\n * Consumes the stream, throws `StreamContractError` at the first violation, and returns every event it read. It\n * checks an adapter's stream and a `Model.stream()` with its `retry` events alike.\n */\nexport async function assertStreamContract<E extends GatewayEvent>(events: AsyncIterable<E>): Promise<E[]> {\n const checker = new StreamChecker();\n const seen: E[] = [];\n for await (const event of events) {\n checker.check(event);\n seen.push(event);\n }\n if (!checker.ended) {\n throw new StreamContractError(\"the stream ended without a done or error event\", checker.seen.length);\n }\n return seen;\n}\n"]}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Offline guards for every test in `packages/` (SDK plan §5.4).
3
+ *
4
+ * Tests must never reach a real model provider. The guards refuse any `fetch` to a non-loopback host, and they fail
5
+ * fast when a provider key variable is set, so a misconfigured machine cannot send a test to a real provider.
6
+ */
7
+ /** Environment variables that hold real provider credentials. Their presence fails the test run. */
8
+ export declare const PROVIDER_KEY_VARIABLES: readonly ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"];
9
+ /** True for hosts that resolve to this machine: `localhost`, `*.localhost`, 127.0.0.0/8 and `::1`. */
10
+ export declare function isLoopbackHost(hostname: string): boolean;
11
+ /** Throws if any provider key variable is set in `env`. */
12
+ export declare function assertNoProviderKeys(env?: Record<string, string | undefined>): void;
13
+ /** Wraps `fetch` so that only loopback hosts are reachable. */
14
+ export declare function guardedFetch(inner: typeof fetch): typeof fetch;
15
+ /** Installs the guards once per process: checks provider keys and replaces `globalThis.fetch`. */
16
+ export declare function installTestGuards(): void;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Offline guards for every test in `packages/` (SDK plan §5.4).
3
+ *
4
+ * Tests must never reach a real model provider. The guards refuse any `fetch` to a non-loopback host, and they fail
5
+ * fast when a provider key variable is set, so a misconfigured machine cannot send a test to a real provider.
6
+ */
7
+ /** Environment variables that hold real provider credentials. Their presence fails the test run. */
8
+ export const PROVIDER_KEY_VARIABLES = ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"];
9
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
10
+ /** True for hosts that resolve to this machine: `localhost`, `*.localhost`, 127.0.0.0/8 and `::1`. */
11
+ export function isLoopbackHost(hostname) {
12
+ const host = hostname.toLowerCase();
13
+ return LOOPBACK_HOSTS.has(host) || host.endsWith(".localhost") || /^127(?:\.\d{1,3}){3}$/.test(host);
14
+ }
15
+ /** Throws if any provider key variable is set in `env`. */
16
+ export function assertNoProviderKeys(env = process.env) {
17
+ const present = PROVIDER_KEY_VARIABLES.filter((name) => env[name] !== undefined && env[name] !== "");
18
+ if (present.length > 0) {
19
+ throw new Error(`Refusing to run tests with provider credentials set (${present.join(", ")}). Unset them; tests run offline.`);
20
+ }
21
+ }
22
+ function urlOf(input) {
23
+ if (input instanceof URL)
24
+ return input;
25
+ if (typeof input === "string")
26
+ return new URL(input);
27
+ return new URL(input.url);
28
+ }
29
+ /** Wraps `fetch` so that only loopback hosts are reachable. */
30
+ export function guardedFetch(inner) {
31
+ return async (input, init) => {
32
+ const url = urlOf(input);
33
+ if (!isLoopbackHost(url.hostname)) {
34
+ throw new Error(`Blocked outbound request to ${url.host}: tests may only reach loopback hosts.`);
35
+ }
36
+ return inner(input, init);
37
+ };
38
+ }
39
+ let installed = false;
40
+ /** Installs the guards once per process: checks provider keys and replaces `globalThis.fetch`. */
41
+ export function installTestGuards() {
42
+ if (installed)
43
+ return;
44
+ assertNoProviderKeys();
45
+ globalThis.fetch = guardedFetch(globalThis.fetch.bind(globalThis));
46
+ installed = true;
47
+ }
48
+ //# sourceMappingURL=guards.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guards.js","sourceRoot":"","sources":["../../src/testing/guards.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,oGAAoG;AACpG,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,mBAAmB,EAAE,gBAAgB,CAAU,CAAC;AAEvF,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AAE3E,sGAAsG;AACtG,MAAM,UAAU,cAAc,CAAC,QAAgB;IAC7C,MAAM,IAAI,GAAG,QAAQ,C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;AACJ,CAAC;AAED,IAAI,SAAS,GAAG,KAAK,CAAC;AAEtB,kGAAkG;AAClG,MAAM,UAAU,iBAAiB;IAC/B,IAAI,SAAS;QAAE,OAAO;IACtB,oBAAoB,EAAE,CAAC;IACvB,UAAU,CAAC,KAAK,GAAG,YAAY,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IACnE,SAAS,GAAG,IAAI,CAAC;AACnB,CAAC","sourcesContent":["/**\n * Offline guards for every test in `packages/` (SDK plan §5.4).\n *\n * Tests must never reach a real model provider. The guards refuse any `fetch` to a non-loopback host, and they fail\n * fast when a provider key variable is set, so a misconfigured machine cannot send a test to a real provider.\n */\n\n/** Environment variables that hold real provider credentials. Their presence fails the test run. */\nexport const PROVIDER_KEY_VARIABLES = [\"ANTHROPIC_API_KEY\", \"OPENAI_API_KEY\"] as const;\n\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\", \"::1\"]);\n\n/** True for hosts that resolve to this machine: `localhost`, `*.localhost`, 127.0.0.0/8 and `::1`. */\nexport function isLoopbackHost(hostname: string): boolean {\n const host = hostname.toLowerCase();\n return LOOPBACK_HOSTS.has(host) || host.endsWith(\".localhost\") || /^127(?:\\.\\d{1,3}){3}$/.test(host);\n}\n\n/** Throws if any provider key variable is set in `env`. */\nexport function assertNoProviderKeys(env: Record<string, string | undefined> = process.env): void {\n const present = PROVIDER_KEY_VARIABLES.filter((name) => env[name] !== undefined && env[name] !== \"\");\n if (present.length > 0) {\n throw new Error(\n `Refusing to run tests with provider credentials set (${present.join(\", \")}). Unset them; tests run offline.`,\n );\n }\n}\n\nfunction urlOf(input: Parameters<typeof fetch>[0]): URL {\n if (input instanceof URL) return input;\n if (typeof input === \"string\") return new URL(input);\n return new URL(input.url);\n}\n\n/** Wraps `fetch` so that only loopback hosts are reachable. */\nexport function guardedFetch(inner: typeof fetch): typeof fetch {\n return async (input, init) => {\n const url = urlOf(input);\n if (!isLoopbackHost(url.hostname)) {\n throw new Error(`Blocked outbound request to ${url.host}: tests may only reach loopback hosts.`);\n }\n return inner(input, init);\n };\n}\n\nlet installed = false;\n\n/** Installs the guards once per process: checks provider keys and replaces `globalThis.fetch`. */\nexport function installTestGuards(): void {\n if (installed) return;\n assertNoProviderKeys();\n globalThis.fetch = guardedFetch(globalThis.fetch.bind(globalThis));\n installed = true;\n}\n"]}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@buildanagent/gateway/testing`: test doubles for the gateway.
3
+ *
4
+ * It exposes the offline guards, `allowModelRequests()`, `assertStreamContract()`, `mockTransport()` with its
5
+ * `serverSentEvents()` and `chatCompletionEvents()` body writers, and `seededRandom()`; `startMockServer()` is planned
6
+ * here (SDK plan §3.2).
7
+ */
8
+ export { isMockTransport, ModelRequestsDisabledError, markMockTransport, setModelRequestsAllowed as allowModelRequests, } from "../request-policy.js";
9
+ export { assertStreamContract, StreamContractError } from "../stream-contract.js";
10
+ export { assertNoProviderKeys, guardedFetch, installTestGuards, isLoopbackHost, PROVIDER_KEY_VARIABLES, } from "./guards.js";
11
+ export { chatCompletionEvents, type MockTransport, mockTransport, type RecordedRequest, serverSentEvents, type WireApi, type WireResponse, type WireScript, } from "./mock-transport.js";
12
+ export { seededRandom } from "./random.js";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `@buildanagent/gateway/testing`: test doubles for the gateway.
3
+ *
4
+ * It exposes the offline guards, `allowModelRequests()`, `assertStreamContract()`, `mockTransport()` with its
5
+ * `serverSentEvents()` and `chatCompletionEvents()` body writers, and `seededRandom()`; `startMockServer()` is planned
6
+ * here (SDK plan §3.2).
7
+ */
8
+ export { isMockTransport, ModelRequestsDisabledError, markMockTransport, setModelRequestsAllowed as allowModelRequests, } from "../request-policy.js";
9
+ export { assertStreamContract, StreamContractError } from "../stream-contract.js";
10
+ export { assertNoProviderKeys, guardedFetch, installTestGuards, isLoopbackHost, PROVIDER_KEY_VARIABLES, } from "./guards.js";
11
+ export { chatCompletionEvents, mockTransport, serverSentEvents, } from "./mock-transport.js";
12
+ export { seededRandom } from "./random.js";
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EACL,eAAe,EACf,0BAA0B,EAC1B,iBAAiB,EACjB,uBAAuB,IAAI,kBAAkB,GAC9C,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAClF,OAAO,EACL,oBAAoB,EACpB,YAAY,EACZ,iBAAiB,EACjB,cAAc,EACd,sBAAsB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,oBAAoB,EAEpB,aAAa,EAEb,gBAAgB,GAIjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC","sourcesContent":["/**\n * `@buildanagent/gateway/testing`: test doubles for the gateway.\n *\n * It exposes the offline guards, `allowModelRequests()`, `assertStreamContract()`, `mockTransport()` with its\n * `serverSentEvents()` and `chatCompletionEvents()` body writers, and `seededRandom()`; `startMockServer()` is planned\n * here (SDK plan §3.2).\n */\n\nexport {\n isMockTransport,\n ModelRequestsDisabledError,\n markMockTransport,\n setModelRequestsAllowed as allowModelRequests,\n} from \"../request-policy.js\";\nexport { assertStreamContract, StreamContractError } from \"../stream-contract.js\";\nexport {\n assertNoProviderKeys,\n guardedFetch,\n installTestGuards,\n isLoopbackHost,\n PROVIDER_KEY_VARIABLES,\n} from \"./guards.js\";\nexport {\n chatCompletionEvents,\n type MockTransport,\n mockTransport,\n type RecordedRequest,\n serverSentEvents,\n type WireApi,\n type WireResponse,\n type WireScript,\n} from \"./mock-transport.js\";\nexport { seededRandom } from \"./random.js\";\n"]}
@@ -0,0 +1,49 @@
1
+ /** The wire protocols a mock transport can stand in for. */
2
+ export type WireApi = "anthropic-messages" | "openai-chat";
3
+ /** One scripted HTTP response. */
4
+ export interface WireResponse {
5
+ /** The HTTP status. Defaults to 200. */
6
+ readonly status?: number;
7
+ /**
8
+ * Response headers. `content-type` defaults to `text/event-stream` for a 2xx status and `application/json`
9
+ * otherwise.
10
+ */
11
+ readonly headers?: Readonly<Record<string, string>>;
12
+ /** The body: server-sent events or JSON as text, or a value that is sent as JSON. */
13
+ readonly body: string | object;
14
+ /** Splits the body into chunks of this many bytes. Without it or `splitAt`, the body arrives in one chunk. */
15
+ readonly chunkSize?: number;
16
+ /** Splits the body at these byte offsets, in ascending order. Takes precedence over `chunkSize`. */
17
+ readonly splitAt?: readonly number[];
18
+ }
19
+ /** The responses a mock transport plays, one per request, in order. */
20
+ export type WireScript = readonly WireResponse[];
21
+ /** A request as the mock transport received it. A JSON body is parsed; any other body stays text. */
22
+ export interface RecordedRequest {
23
+ readonly url: string;
24
+ readonly method: string;
25
+ /** The request headers, with lower-case names. */
26
+ readonly headers: Readonly<Record<string, string>>;
27
+ readonly body: unknown;
28
+ }
29
+ /** A transport that replays a script, with the requests it has received so far. */
30
+ export interface MockTransport {
31
+ (request: Request): Promise<Response>;
32
+ /** Every request received so far, in order. */
33
+ readonly requests: readonly RecordedRequest[];
34
+ }
35
+ /**
36
+ * Creates a transport that answers the n-th request with the n-th scripted response. It is marked as a mock, so it
37
+ * works while real model requests are turned off. A request to a path other than the protocol's endpoint, or one
38
+ * past the end of the script, throws a `GatewayError` with code `unexpected_request`.
39
+ */
40
+ export declare function mockTransport(api: WireApi, script: WireScript): MockTransport;
41
+ /** Writes events as a server-sent event stream, naming each event after its `type` field. */
42
+ export declare function serverSentEvents(events: readonly {
43
+ readonly type: string;
44
+ }[]): string;
45
+ /**
46
+ * Writes Chat Completions chunks as a server-sent event stream: one unnamed `data:` event per chunk, then the
47
+ * `data: [DONE]` event that ends an OpenAI stream.
48
+ */
49
+ export declare function chatCompletionEvents(chunks: readonly object[]): string;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * `mockTransport()`: an in-process fake of a provider's HTTP API that replays scripted responses, so adapter tests run
3
+ * the real wire format with no socket. It records every request it receives, and it can split a response body into
4
+ * chunks anywhere, including inside a multi-byte character or a tool call's JSON.
5
+ */
6
+ import { GatewayError } from "../errors.js";
7
+ import { markMockTransport } from "../request-policy.js";
8
+ // The request path each protocol posts to, so a test fails when an adapter calls the wrong endpoint.
9
+ const PATHS = {
10
+ "anthropic-messages": "/v1/messages",
11
+ "openai-chat": "/chat/completions",
12
+ };
13
+ function chunksOf(bytes, response) {
14
+ const cuts = response.splitAt ?? [];
15
+ const size = response.chunkSize;
16
+ const offsets = cuts.length > 0
17
+ ? [...cuts]
18
+ : size !== undefined && size > 0
19
+ ? Array.from({ length: Math.ceil(bytes.length / size) - 1 }, (_, i) => (i + 1) * size)
20
+ : [];
21
+ const bounds = [0, ...offsets.filter((offset) => offset > 0 && offset < bytes.length), bytes.length];
22
+ return bounds.slice(1).map((end, i) => bytes.slice(bounds[i], end));
23
+ }
24
+ /** A body stream that enqueues one chunk per read and fails with the signal's reason once the request is aborted. */
25
+ function bodyStream(chunks, signal) {
26
+ let next = 0;
27
+ return new ReadableStream({
28
+ pull(controller) {
29
+ if (signal.aborted) {
30
+ controller.error(signal.reason);
31
+ return;
32
+ }
33
+ const chunk = chunks[next];
34
+ next += 1;
35
+ if (chunk === undefined)
36
+ controller.close();
37
+ else
38
+ controller.enqueue(chunk);
39
+ },
40
+ });
41
+ }
42
+ async function record(request) {
43
+ const headers = {};
44
+ request.headers.forEach((value, name) => {
45
+ headers[name] = value;
46
+ });
47
+ const text = await request.clone().text();
48
+ let body = text;
49
+ if (headers["content-type"]?.includes("json")) {
50
+ try {
51
+ body = JSON.parse(text);
52
+ }
53
+ catch {
54
+ // A body that claims to be JSON and isn't stays text, so the test can see what was sent.
55
+ }
56
+ }
57
+ return { url: request.url, method: request.method, headers, body };
58
+ }
59
+ function responseFor(scripted, signal) {
60
+ const status = scripted.status ?? 200;
61
+ const text = typeof scripted.body === "string" ? scripted.body : JSON.stringify(scripted.body);
62
+ const contentType = status >= 200 && status < 300 ? "text/event-stream" : "application/json";
63
+ const headers = new Headers({ "content-type": contentType, ...scripted.headers });
64
+ const chunks = chunksOf(new TextEncoder().encode(text), scripted);
65
+ return new Response(bodyStream(chunks, signal), { status, headers });
66
+ }
67
+ /**
68
+ * Creates a transport that answers the n-th request with the n-th scripted response. It is marked as a mock, so it
69
+ * works while real model requests are turned off. A request to a path other than the protocol's endpoint, or one
70
+ * past the end of the script, throws a `GatewayError` with code `unexpected_request`.
71
+ */
72
+ export function mockTransport(api, script) {
73
+ const path = PATHS[api];
74
+ if (path === undefined)
75
+ throw new GatewayError("invalid_options", `mockTransport(): unknown wire API ${String(api)}`);
76
+ const requests = [];
77
+ const transport = async (request) => {
78
+ requests.push(await record(request));
79
+ if (!new URL(request.url).pathname.endsWith(path)) {
80
+ throw new GatewayError("unexpected_request", `mockTransport(${api}): expected a request to ${path}, got ${request.url}`);
81
+ }
82
+ const scripted = script[requests.length - 1];
83
+ if (scripted === undefined) {
84
+ throw new GatewayError("unexpected_request", `mockTransport(${api}): request ${requests.length} has no scripted response (the script has ${script.length})`);
85
+ }
86
+ return responseFor(scripted, request.signal);
87
+ };
88
+ return markMockTransport(Object.assign(transport, { requests }));
89
+ }
90
+ /** Writes events as a server-sent event stream, naming each event after its `type` field. */
91
+ export function serverSentEvents(events) {
92
+ return events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join("");
93
+ }
94
+ /**
95
+ * Writes Chat Completions chunks as a server-sent event stream: one unnamed `data:` event per chunk, then the
96
+ * `data: [DONE]` event that ends an OpenAI stream.
97
+ */
98
+ export function chatCompletionEvents(chunks) {
99
+ return `${chunks.map((chunk) => `data: ${JSON.stringify(chunk)}\n\n`).join("")}data: [DONE]\n\n`;
100
+ }
101
+ //# sourceMappingURL=mock-transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mock-transport.js","sourceRoot":"","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C,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAClD,MAAM,IAAI,YAAY,CACpB,oBAAoB,EACpB,iBAAiB,GAAG,4BAA4B,IAAI,SAAS,OAAO,CAAC,GAAG,EAAE,CAC3E,CAAC;QACJ,CAAC;QACD,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC7C,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,MAAM,IAAI,YAAY,CACpB,oBAAoB,EACpB,iBAAiB,GAAG,cAAc,QAAQ,CAAC,MAAM,6CAA6C,MAAM,CAAC,MAAM,GAAG,CAC/G,CAAC;QACJ,CAAC;QACD,OAAO,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/C,CAAC,CAAC;IACF,OAAO,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;AACnE,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,gBAAgB,CAAC,MAA4C;IAC3E,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,UAAU,KAAK,CAAC,IAAI,WAAW,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACpG,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,MAAyB;IAC5D,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,kBAAkB,CAAC;AACnG,CAAC","sourcesContent":["/**\n * `mockTransport()`: an in-process fake of a provider's HTTP API that replays scripted responses, so adapter tests run\n * the real wire format with no socket. It records every request it receives, and it can split a response body into\n * chunks anywhere, including inside a multi-byte character or a tool call's JSON.\n */\nimport { GatewayError } from \"../errors.js\";\nimport { markMockTransport } from \"../request-policy.js\";\n\n/** The wire protocols a mock transport can stand in for. */\nexport type WireApi = \"anthropic-messages\" | \"openai-chat\";\n\n/** One scripted HTTP response. */\nexport interface WireResponse {\n /** The HTTP status. Defaults to 200. */\n readonly status?: number;\n /**\n * Response headers. `content-type` defaults to `text/event-stream` for a 2xx status and `application/json`\n * otherwise.\n */\n readonly headers?: Readonly<Record<string, string>>;\n /** The body: server-sent events or JSON as text, or a value that is sent as JSON. */\n readonly body: string | object;\n /** Splits the body into chunks of this many bytes. Without it or `splitAt`, the body arrives in one chunk. */\n readonly chunkSize?: number;\n /** Splits the body at these byte offsets, in ascending order. Takes precedence over `chunkSize`. */\n readonly splitAt?: readonly number[];\n}\n\n/** The responses a mock transport plays, one per request, in order. */\nexport type WireScript = readonly WireResponse[];\n\n/** A request as the mock transport received it. A JSON body is parsed; any other body stays text. */\nexport interface RecordedRequest {\n readonly url: string;\n readonly method: string;\n /** The request headers, with lower-case names. */\n readonly headers: Readonly<Record<string, string>>;\n readonly body: unknown;\n}\n\n/** A transport that replays a script, with the requests it has received so far. */\nexport interface MockTransport {\n (request: Request): Promise<Response>;\n /** Every request received so far, in order. */\n readonly requests: readonly RecordedRequest[];\n}\n\n// The request path each protocol posts to, so a test fails when an adapter calls the wrong endpoint.\nconst PATHS: Readonly<Record<WireApi, string>> = {\n \"anthropic-messages\": \"/v1/messages\",\n \"openai-chat\": \"/chat/completions\",\n};\n\nfunction chunksOf(bytes: Uint8Array, response: WireResponse): Uint8Array[] {\n const cuts = response.splitAt ?? [];\n const size = response.chunkSize;\n const offsets =\n cuts.length > 0\n ? [...cuts]\n : size !== undefined && size > 0\n ? Array.from({ length: Math.ceil(bytes.length / size) - 1 }, (_, i) => (i + 1) * size)\n : [];\n const bounds = [0, ...offsets.filter((offset) => offset > 0 && offset < bytes.length), bytes.length];\n return bounds.slice(1).map((end, i) => bytes.slice(bounds[i], end));\n}\n\n/** A body stream that enqueues one chunk per read and fails with the signal's reason once the request is aborted. */\nfunction bodyStream(chunks: Uint8Array[], signal: AbortSignal): ReadableStream<Uint8Array> {\n let next = 0;\n return new ReadableStream<Uint8Array>({\n pull(controller) {\n if (signal.aborted) {\n controller.error(signal.reason);\n return;\n }\n const chunk = chunks[next];\n next += 1;\n if (chunk === undefined) controller.close();\n else controller.enqueue(chunk);\n },\n });\n}\n\nasync function record(request: Request): Promise<RecordedRequest> {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name] = value;\n });\n const text = await request.clone().text();\n let body: unknown = text;\n if (headers[\"content-type\"]?.includes(\"json\")) {\n try {\n body = JSON.parse(text);\n } catch {\n // A body that claims to be JSON and isn't stays text, so the test can see what was sent.\n }\n }\n return { url: request.url, method: request.method, headers, body };\n}\n\nfunction responseFor(scripted: WireResponse, signal: AbortSignal): Response {\n const status = scripted.status ?? 200;\n const text = typeof scripted.body === \"string\" ? scripted.body : JSON.stringify(scripted.body);\n const contentType = status >= 200 && status < 300 ? \"text/event-stream\" : \"application/json\";\n const headers = new Headers({ \"content-type\": contentType, ...scripted.headers });\n const chunks = chunksOf(new TextEncoder().encode(text), scripted);\n return new Response(bodyStream(chunks, signal), { status, headers });\n}\n\n/**\n * Creates a transport that answers the n-th request with the n-th scripted response. It is marked as a mock, so it\n * works while real model requests are turned off. A request to a path other than the protocol's endpoint, or one\n * past the end of the script, throws a `GatewayError` with code `unexpected_request`.\n */\nexport function mockTransport(api: WireApi, script: WireScript): MockTransport {\n const path = PATHS[api];\n if (path === undefined) throw new GatewayError(\"invalid_options\", `mockTransport(): unknown wire API ${String(api)}`);\n const requests: RecordedRequest[] = [];\n const transport = async (request: Request): Promise<Response> => {\n requests.push(await record(request));\n if (!new URL(request.url).pathname.endsWith(path)) {\n throw new GatewayError(\n \"unexpected_request\",\n `mockTransport(${api}): expected a request to ${path}, got ${request.url}`,\n );\n }\n const scripted = script[requests.length - 1];\n if (scripted === undefined) {\n throw new GatewayError(\n \"unexpected_request\",\n `mockTransport(${api}): request ${requests.length} has no scripted response (the script has ${script.length})`,\n );\n }\n return responseFor(scripted, request.signal);\n };\n return markMockTransport(Object.assign(transport, { requests }));\n}\n\n/** Writes events as a server-sent event stream, naming each event after its `type` field. */\nexport function serverSentEvents(events: readonly { readonly type: string }[]): string {\n return events.map((event) => `event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`).join(\"\");\n}\n\n/**\n * Writes Chat Completions chunks as a server-sent event stream: one unnamed `data:` event per chunk, then the\n * `data: [DONE]` event that ends an OpenAI stream.\n */\nexport function chatCompletionEvents(chunks: readonly object[]): string {\n return `${chunks.map((chunk) => `data: ${JSON.stringify(chunk)}\\n\\n`).join(\"\")}data: [DONE]\\n\\n`;\n}\n"]}
@@ -0,0 +1,3 @@
1
+ /** Seeded randomness for tests. Nothing here reads `Math.random`, so a seed gives the same numbers on every target. */
2
+ /** A seeded generator in [0, 1) (mulberry32), for tests that need randomness without `Math.random()`. */
3
+ export declare function seededRandom(seed: number): () => number;
@@ -0,0 +1,13 @@
1
+ /** Seeded randomness for tests. Nothing here reads `Math.random`, so a seed gives the same numbers on every target. */
2
+ /** A seeded generator in [0, 1) (mulberry32), for tests that need randomness without `Math.random()`. */
3
+ export function seededRandom(seed) {
4
+ let a = seed >>> 0;
5
+ return () => {
6
+ a = (a + 0x6d2b79f5) >>> 0;
7
+ let x = a;
8
+ x = Math.imul(x ^ (x >>> 15), x | 1);
9
+ x ^= x + Math.imul(x ^ (x >>> 7), x | 61);
10
+ return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
11
+ };
12
+ }
13
+ //# sourceMappingURL=random.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"random.js","sourceRoot":"","sources":["../../src/testing/random.ts"],"names":[],"mappings":"AAAA,uHAAuH;AAEvH,yGAAyG;AACzG,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,IAAI,CAAC,GAAG,IAAI,KAAK,CAAC,CAAC;IACnB,OAAO,GAAG,EAAE;QACV,CAAC,GAAG,CAAC,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;QAC3B,IAAI,CAAC,GAAG,CAAC,CAAC;QACV,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QACrC,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC;QAC1C,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,UAAU,CAAC;IAC/C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/** Seeded randomness for tests. Nothing here reads `Math.random`, so a seed gives the same numbers on every target. */\n\n/** A seeded generator in [0, 1) (mulberry32), for tests that need randomness without `Math.random()`. */\nexport function seededRandom(seed: number): () => number {\n let a = seed >>> 0;\n return () => {\n a = (a + 0x6d2b79f5) >>> 0;\n let x = a;\n x = Math.imul(x ^ (x >>> 15), x | 1);\n x ^= x + Math.imul(x ^ (x >>> 7), x | 61);\n return ((x ^ (x >>> 14)) >>> 0) / 4294967296;\n };\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Shared test setup. Import it first in every test file under `packages/`:
3
+ *
4
+ * import "@buildanagent/gateway/testing/setup";
5
+ *
6
+ * It installs the network guard, checks for provider keys and turns real model requests off.
7
+ */
8
+ import { setModelRequestsAllowed } from "../request-policy.js";
9
+ import { installTestGuards } from "./guards.js";
10
+ installTestGuards();
11
+ setModelRequestsAllowed(false);
12
+ //# sourceMappingURL=setup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.js","sourceRoot":"","sources":["../../src/testing/setup.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,iBAAiB,EAAE,CAAC;AACpB,uBAAuB,CAAC,KAAK,CAAC,CAAC","sourcesContent":["/**\n * Shared test setup. Import it first in every test file under `packages/`:\n *\n * import \"@buildanagent/gateway/testing/setup\";\n *\n * It installs the network guard, checks for provider keys and turns real model requests off.\n */\nimport { setModelRequestsAllowed } from \"../request-policy.js\";\nimport { installTestGuards } from \"./guards.js\";\n\ninstallTestGuards();\nsetModelRequestsAllowed(false);\n"]}
@@ -0,0 +1,32 @@
1
+ import type { Message, ModelCaps, ModelRef } from "./types.js";
2
+ /**
3
+ * Prepares a transcript for one target model, so a conversation recorded on any provider can be sent to it. The
4
+ * pass returns a new array and never changes `messages`; the result may share unchanged blocks with the input.
5
+ *
6
+ * It applies five rules:
7
+ *
8
+ * 1. It skips assistant turns that ended in an error or an abort, together with the tool results that answer their
9
+ * calls, so a resumed request asks the model again.
10
+ * 2. It drops every reasoning block when `caps.reasoning` is false. Otherwise it drops reasoning written by another
11
+ * provider, and strips a signature the target cannot verify. An Anthropic target keeps every Anthropic-signed
12
+ * block unchanged, even one whose text is empty, and drops every block it cannot send signed. When one block must
13
+ * go, every older reasoning block goes with it, because Anthropic lets a request omit earlier thinking but not a
14
+ * block between two kept blocks. Any other target keeps the text of a block it cannot verify, unless the text is
15
+ * empty.
16
+ * 3. It replaces each image with a short text note when `caps.images` is false.
17
+ * 4. It rewrites tool-call ids that are not 1–64 letters, digits, `_` or `-`, or that repeat an earlier id, and
18
+ * updates each matching tool result.
19
+ * 5. It moves each tool result next to its call, however much later the result appears, drops results that answer
20
+ * no call, and gives every call that lacks a result a synthetic error result. A result answers the newest earlier
21
+ * call with its id from a completed turn, and answers a skipped turn's call only when no such call is waiting.
22
+ *
23
+ * It also keeps each message to the shape both providers accept. A user message carries no reasoning or tool calls,
24
+ * no message carries an empty text block, and a message left with no content is dropped. Adjacent user messages are
25
+ * merged into one, and so are adjacent assistant messages: the merged message takes the later one's stop reason,
26
+ * usage and cost, and drops the later one's reasoning if the earlier one has text or tool calls, so reasoning never
27
+ * follows a block it did not follow before. If the input holds a user message, the output starts with one, using a
28
+ * short placeholder note when the opening user message was emptied. An input left with nothing to send returns `[]`.
29
+ *
30
+ * Running the pass on its own output returns the same transcript.
31
+ */
32
+ export declare function transformMessages(messages: readonly Message[], target: ModelRef, caps: ModelCaps): Message[];