@copilotkit/aimock 1.44.0 → 1.45.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 (272) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +31 -0
  4. package/README.md +6 -0
  5. package/dist/agui-types.d.ts.map +1 -1
  6. package/dist/aimock-cli.cjs +31 -5
  7. package/dist/aimock-cli.cjs.map +1 -1
  8. package/dist/aimock-cli.d.cts.map +1 -1
  9. package/dist/aimock-cli.d.ts.map +1 -1
  10. package/dist/aimock-cli.js +31 -5
  11. package/dist/aimock-cli.js.map +1 -1
  12. package/dist/bedrock-converse.cjs +312 -39
  13. package/dist/bedrock-converse.cjs.map +1 -1
  14. package/dist/bedrock-converse.d.cts.map +1 -1
  15. package/dist/bedrock-converse.d.ts.map +1 -1
  16. package/dist/bedrock-converse.js +313 -40
  17. package/dist/bedrock-converse.js.map +1 -1
  18. package/dist/bedrock.cjs +195 -42
  19. package/dist/bedrock.cjs.map +1 -1
  20. package/dist/bedrock.d.cts.map +1 -1
  21. package/dist/bedrock.d.ts.map +1 -1
  22. package/dist/bedrock.js +196 -43
  23. package/dist/bedrock.js.map +1 -1
  24. package/dist/chaos.cjs +1 -0
  25. package/dist/chaos.js +1 -1
  26. package/dist/cli.cjs +152 -5
  27. package/dist/cli.cjs.map +1 -1
  28. package/dist/cli.js +155 -8
  29. package/dist/cli.js.map +1 -1
  30. package/dist/cohere.cjs +132 -71
  31. package/dist/cohere.cjs.map +1 -1
  32. package/dist/cohere.d.cts.map +1 -1
  33. package/dist/cohere.d.ts.map +1 -1
  34. package/dist/cohere.js +133 -72
  35. package/dist/cohere.js.map +1 -1
  36. package/dist/config-loader.cjs +62 -4
  37. package/dist/config-loader.cjs.map +1 -1
  38. package/dist/config-loader.d.cts +37 -4
  39. package/dist/config-loader.d.cts.map +1 -1
  40. package/dist/config-loader.d.ts +37 -4
  41. package/dist/config-loader.d.ts.map +1 -1
  42. package/dist/config-loader.js +62 -4
  43. package/dist/config-loader.js.map +1 -1
  44. package/dist/fakes-plugin.cjs +131 -0
  45. package/dist/fakes-plugin.cjs.map +1 -0
  46. package/dist/fakes-plugin.d.cts +23 -0
  47. package/dist/fakes-plugin.d.cts.map +1 -0
  48. package/dist/fakes-plugin.d.ts +23 -0
  49. package/dist/fakes-plugin.d.ts.map +1 -0
  50. package/dist/fakes-plugin.js +127 -0
  51. package/dist/fakes-plugin.js.map +1 -0
  52. package/dist/fixture-loader-services.cjs +1 -1
  53. package/dist/fixture-loader-services.cjs.map +1 -1
  54. package/dist/fixture-loader-services.js +1 -1
  55. package/dist/fixture-loader-services.js.map +1 -1
  56. package/dist/fixture-loader.cjs +389 -27
  57. package/dist/fixture-loader.cjs.map +1 -1
  58. package/dist/fixture-loader.d.cts +47 -3
  59. package/dist/fixture-loader.d.cts.map +1 -1
  60. package/dist/fixture-loader.d.ts +47 -3
  61. package/dist/fixture-loader.d.ts.map +1 -1
  62. package/dist/fixture-loader.js +384 -29
  63. package/dist/fixture-loader.js.map +1 -1
  64. package/dist/gemini-interactions.cjs +250 -52
  65. package/dist/gemini-interactions.cjs.map +1 -1
  66. package/dist/gemini-interactions.d.cts.map +1 -1
  67. package/dist/gemini-interactions.d.ts.map +1 -1
  68. package/dist/gemini-interactions.js +251 -53
  69. package/dist/gemini-interactions.js.map +1 -1
  70. package/dist/gemini.cjs +226 -37
  71. package/dist/gemini.cjs.map +1 -1
  72. package/dist/gemini.d.cts.map +1 -1
  73. package/dist/gemini.d.ts.map +1 -1
  74. package/dist/gemini.js +227 -38
  75. package/dist/gemini.js.map +1 -1
  76. package/dist/helpers.cjs +881 -7
  77. package/dist/helpers.cjs.map +1 -1
  78. package/dist/helpers.d.cts +85 -4
  79. package/dist/helpers.d.cts.map +1 -1
  80. package/dist/helpers.d.ts +85 -4
  81. package/dist/helpers.d.ts.map +1 -1
  82. package/dist/helpers.js +839 -8
  83. package/dist/helpers.js.map +1 -1
  84. package/dist/index.cjs +9 -0
  85. package/dist/index.d.cts +7 -5
  86. package/dist/index.d.ts +7 -5
  87. package/dist/index.js +4 -3
  88. package/dist/jest.cjs +31 -7
  89. package/dist/jest.cjs.map +1 -1
  90. package/dist/jest.d.cts +43 -3
  91. package/dist/jest.d.cts.map +1 -1
  92. package/dist/jest.d.ts +43 -3
  93. package/dist/jest.d.ts.map +1 -1
  94. package/dist/jest.js +33 -9
  95. package/dist/jest.js.map +1 -1
  96. package/dist/journal.cjs +135 -13
  97. package/dist/journal.cjs.map +1 -1
  98. package/dist/journal.d.cts +38 -4
  99. package/dist/journal.d.cts.map +1 -1
  100. package/dist/journal.d.ts +38 -4
  101. package/dist/journal.d.ts.map +1 -1
  102. package/dist/journal.js +135 -13
  103. package/dist/journal.js.map +1 -1
  104. package/dist/live-sanitize.cjs +4 -32
  105. package/dist/live-sanitize.cjs.map +1 -1
  106. package/dist/live-sanitize.js +4 -32
  107. package/dist/live-sanitize.js.map +1 -1
  108. package/dist/llmock.cjs +123 -30
  109. package/dist/llmock.cjs.map +1 -1
  110. package/dist/llmock.d.cts +16 -1
  111. package/dist/llmock.d.cts.map +1 -1
  112. package/dist/llmock.d.ts +16 -1
  113. package/dist/llmock.d.ts.map +1 -1
  114. package/dist/llmock.js +125 -32
  115. package/dist/llmock.js.map +1 -1
  116. package/dist/mcp-fakes-mount.cjs +1 -0
  117. package/dist/mcp-fakes-mount.cjs.map +1 -1
  118. package/dist/mcp-fakes-mount.js +1 -0
  119. package/dist/mcp-fakes-mount.js.map +1 -1
  120. package/dist/mcp-fakes-report.cjs +111 -0
  121. package/dist/mcp-fakes-report.cjs.map +1 -0
  122. package/dist/mcp-fakes-report.d.cts +40 -0
  123. package/dist/mcp-fakes-report.d.cts.map +1 -0
  124. package/dist/mcp-fakes-report.d.ts +40 -0
  125. package/dist/mcp-fakes-report.d.ts.map +1 -0
  126. package/dist/mcp-fakes-report.js +107 -0
  127. package/dist/mcp-fakes-report.js.map +1 -0
  128. package/dist/mcp-fakes.cjs +331 -8
  129. package/dist/mcp-fakes.cjs.map +1 -1
  130. package/dist/mcp-fakes.d.cts +406 -3
  131. package/dist/mcp-fakes.d.cts.map +1 -1
  132. package/dist/mcp-fakes.d.ts +406 -3
  133. package/dist/mcp-fakes.d.ts.map +1 -1
  134. package/dist/mcp-fakes.js +331 -8
  135. package/dist/mcp-fakes.js.map +1 -1
  136. package/dist/mcp-handler.cjs +209 -16
  137. package/dist/mcp-handler.cjs.map +1 -1
  138. package/dist/mcp-handler.d.cts +49 -0
  139. package/dist/mcp-handler.d.cts.map +1 -0
  140. package/dist/mcp-handler.d.ts +49 -0
  141. package/dist/mcp-handler.d.ts.map +1 -0
  142. package/dist/mcp-handler.js +207 -17
  143. package/dist/mcp-handler.js.map +1 -1
  144. package/dist/mcp-mock.cjs +112 -1
  145. package/dist/mcp-mock.cjs.map +1 -1
  146. package/dist/mcp-mock.d.cts +33 -2
  147. package/dist/mcp-mock.d.cts.map +1 -1
  148. package/dist/mcp-mock.d.ts +33 -2
  149. package/dist/mcp-mock.d.ts.map +1 -1
  150. package/dist/mcp-mock.js +112 -1
  151. package/dist/mcp-mock.js.map +1 -1
  152. package/dist/mcp-recorder.cjs +1224 -0
  153. package/dist/mcp-recorder.cjs.map +1 -0
  154. package/dist/mcp-recorder.d.cts +108 -0
  155. package/dist/mcp-recorder.d.cts.map +1 -0
  156. package/dist/mcp-recorder.d.ts +108 -0
  157. package/dist/mcp-recorder.d.ts.map +1 -0
  158. package/dist/mcp-recorder.js +1215 -0
  159. package/dist/mcp-recorder.js.map +1 -0
  160. package/dist/messages.cjs +362 -56
  161. package/dist/messages.cjs.map +1 -1
  162. package/dist/messages.d.cts.map +1 -1
  163. package/dist/messages.d.ts.map +1 -1
  164. package/dist/messages.js +363 -58
  165. package/dist/messages.js.map +1 -1
  166. package/dist/misbehavior.cjs +1523 -0
  167. package/dist/misbehavior.cjs.map +1 -0
  168. package/dist/misbehavior.d.cts +43 -0
  169. package/dist/misbehavior.d.cts.map +1 -0
  170. package/dist/misbehavior.d.ts +43 -0
  171. package/dist/misbehavior.d.ts.map +1 -0
  172. package/dist/misbehavior.js +1511 -0
  173. package/dist/misbehavior.js.map +1 -0
  174. package/dist/ollama.cjs +310 -112
  175. package/dist/ollama.cjs.map +1 -1
  176. package/dist/ollama.d.cts.map +1 -1
  177. package/dist/ollama.d.ts.map +1 -1
  178. package/dist/ollama.js +311 -113
  179. package/dist/ollama.js.map +1 -1
  180. package/dist/record-sanitize.cjs +231 -0
  181. package/dist/record-sanitize.cjs.map +1 -0
  182. package/dist/record-sanitize.js +224 -0
  183. package/dist/record-sanitize.js.map +1 -0
  184. package/dist/recorder.cjs +106 -5
  185. package/dist/recorder.cjs.map +1 -1
  186. package/dist/recorder.d.cts +2 -1
  187. package/dist/recorder.d.cts.map +1 -1
  188. package/dist/recorder.d.ts +2 -1
  189. package/dist/recorder.d.ts.map +1 -1
  190. package/dist/recorder.js +107 -7
  191. package/dist/recorder.js.map +1 -1
  192. package/dist/responses.cjs +667 -171
  193. package/dist/responses.cjs.map +1 -1
  194. package/dist/responses.d.cts +5 -13
  195. package/dist/responses.d.cts.map +1 -1
  196. package/dist/responses.d.ts +5 -13
  197. package/dist/responses.d.ts.map +1 -1
  198. package/dist/responses.js +665 -174
  199. package/dist/responses.js.map +1 -1
  200. package/dist/router.cjs +24 -2
  201. package/dist/router.cjs.map +1 -1
  202. package/dist/router.d.cts.map +1 -1
  203. package/dist/router.d.ts.map +1 -1
  204. package/dist/router.js +25 -4
  205. package/dist/router.js.map +1 -1
  206. package/dist/server.cjs +572 -76
  207. package/dist/server.cjs.map +1 -1
  208. package/dist/server.d.cts.map +1 -1
  209. package/dist/server.d.ts.map +1 -1
  210. package/dist/server.js +574 -78
  211. package/dist/server.js.map +1 -1
  212. package/dist/stream-collapse.cjs +236 -34
  213. package/dist/stream-collapse.cjs.map +1 -1
  214. package/dist/stream-collapse.d.cts +39 -4
  215. package/dist/stream-collapse.d.cts.map +1 -1
  216. package/dist/stream-collapse.d.ts +39 -4
  217. package/dist/stream-collapse.d.ts.map +1 -1
  218. package/dist/stream-collapse.js +235 -35
  219. package/dist/stream-collapse.js.map +1 -1
  220. package/dist/types.cjs.map +1 -1
  221. package/dist/types.d.cts +315 -4
  222. package/dist/types.d.cts.map +1 -1
  223. package/dist/types.d.ts +315 -4
  224. package/dist/types.d.ts.map +1 -1
  225. package/dist/types.js.map +1 -1
  226. package/dist/validate-cli.cjs +36 -4
  227. package/dist/validate-cli.cjs.map +1 -1
  228. package/dist/validate-cli.js +37 -5
  229. package/dist/validate-cli.js.map +1 -1
  230. package/dist/vector-types.d.ts.map +1 -1
  231. package/dist/version.cjs +45 -0
  232. package/dist/version.cjs.map +1 -0
  233. package/dist/version.js +44 -0
  234. package/dist/version.js.map +1 -0
  235. package/dist/vitest.cjs +66 -10
  236. package/dist/vitest.cjs.map +1 -1
  237. package/dist/vitest.d.cts +35 -4
  238. package/dist/vitest.d.cts.map +1 -1
  239. package/dist/vitest.d.ts +35 -4
  240. package/dist/vitest.d.ts.map +1 -1
  241. package/dist/vitest.js +67 -11
  242. package/dist/vitest.js.map +1 -1
  243. package/dist/watcher.cjs +6 -2
  244. package/dist/watcher.cjs.map +1 -1
  245. package/dist/watcher.js +6 -2
  246. package/dist/watcher.js.map +1 -1
  247. package/dist/ws-gemini-live.cjs +210 -101
  248. package/dist/ws-gemini-live.cjs.map +1 -1
  249. package/dist/ws-gemini-live.d.cts +9 -3
  250. package/dist/ws-gemini-live.d.cts.map +1 -1
  251. package/dist/ws-gemini-live.d.ts +9 -3
  252. package/dist/ws-gemini-live.d.ts.map +1 -1
  253. package/dist/ws-gemini-live.js +211 -102
  254. package/dist/ws-gemini-live.js.map +1 -1
  255. package/dist/ws-realtime.cjs +175 -62
  256. package/dist/ws-realtime.cjs.map +1 -1
  257. package/dist/ws-realtime.d.cts +8 -3
  258. package/dist/ws-realtime.d.cts.map +1 -1
  259. package/dist/ws-realtime.d.ts +8 -3
  260. package/dist/ws-realtime.d.ts.map +1 -1
  261. package/dist/ws-realtime.js +176 -63
  262. package/dist/ws-realtime.js.map +1 -1
  263. package/dist/ws-responses.cjs +109 -16
  264. package/dist/ws-responses.cjs.map +1 -1
  265. package/dist/ws-responses.d.cts +8 -12
  266. package/dist/ws-responses.d.cts.map +1 -1
  267. package/dist/ws-responses.d.ts +8 -12
  268. package/dist/ws-responses.d.ts.map +1 -1
  269. package/dist/ws-responses.js +111 -18
  270. package/dist/ws-responses.js.map +1 -1
  271. package/package.json +10 -2
  272. package/skills/write-fixtures/SKILL.md +179 -21
package/dist/helpers.js CHANGED
@@ -3,9 +3,256 @@ import { cutText } from "./echo-text.js";
3
3
  import { build, fixed, msg, quote } from "./message-text.js";
4
4
  import { isReasoningModel } from "./model-utils.js";
5
5
  import { isRecognizedApiKeyHeader } from "./api-key-auth.js";
6
+ import { AsyncLocalStorage } from "node:async_hooks";
6
7
  import { createHash, randomBytes } from "node:crypto";
7
8
 
8
9
  //#region src/helpers.ts
10
+ /** Preserve authored text for string wires without silently repairing invalid JSON. */
11
+ function toolArgsForWire(tc) {
12
+ const raw = tc.arguments || "{}";
13
+ try {
14
+ const value = JSON.parse(raw);
15
+ return {
16
+ kind: "parsed",
17
+ value,
18
+ text: JSON.stringify(value),
19
+ raw
20
+ };
21
+ } catch {
22
+ return {
23
+ kind: "verbatim",
24
+ raw
25
+ };
26
+ }
27
+ }
28
+ /** Object wires reject the verbatim branch; string wires never need this error. */
29
+ var InvalidToolArgumentsError = class extends Error {
30
+ toolName;
31
+ parseDiagnostic;
32
+ constructor(tc) {
33
+ let parseDiagnostic = "";
34
+ try {
35
+ JSON.parse(tc.arguments || "{}");
36
+ } catch (error) {
37
+ parseDiagnostic = error instanceof Error ? error.message : String(error);
38
+ }
39
+ super(`aimock: fixture tool call "${tc.name}" has invalid JSON arguments; this wire carries arguments as an object. Use a wire that carries tool arguments as a string to test malformed JSON. (${parseDiagnostic})`);
40
+ this.name = "InvalidToolArgumentsError";
41
+ this.toolName = tc.name;
42
+ this.parseDiagnostic = parseDiagnostic;
43
+ }
44
+ };
45
+ const toolArgumentsScope = new AsyncLocalStorage();
46
+ /** Run `fn` with the `strictToolArguments` setting and logger of one request. */
47
+ function runWithToolArgumentsScope(scope, fn) {
48
+ return toolArgumentsScope.run(scope, fn);
49
+ }
50
+ /** Whether `strictToolArguments` is on for the request being served (default off). */
51
+ function strictToolArgumentsEnabled() {
52
+ return toolArgumentsScope.getStore()?.strict === true;
53
+ }
54
+ /**
55
+ * Serve the rest of this request's tool arguments as authored (the
56
+ * `strictToolArguments` behavior). An applied misbehavior fault calls this so
57
+ * that the malformed arguments it injects are not replaced with `{}`; the
58
+ * planner only applies a fault to a fixture whose own arguments are valid
59
+ * wherever the default would replace them.
60
+ */
61
+ function keepAuthoredToolArguments() {
62
+ const scope = toolArgumentsScope.getStore();
63
+ if (scope) scope.strict = true;
64
+ }
65
+ /**
66
+ * The fixture tool-call arguments a wire serves on its normal (no misbehavior)
67
+ * path. Valid JSON gives the parsed value, its re-serialized text, and the
68
+ * authored text. Invalid JSON logs one warning and, by default, is served as
69
+ * `{}` / `"{}"`, as in 1.44.0. With `strictToolArguments`, an object wire
70
+ * (`"object"`) throws {@link InvalidToolArgumentsError} and a string wire
71
+ * (`"string"`) serves the authored text unchanged.
72
+ */
73
+ function servedToolArgs(tc, wire, logger) {
74
+ const args = toolArgsForWire(tc);
75
+ if (args.kind === "parsed") return args;
76
+ const scope = toolArgumentsScope.getStore();
77
+ (logger ?? scope?.logger)?.warn(`Malformed JSON in fixture tool call arguments for "${tc.name}": ${tc.arguments}`);
78
+ if (scope?.strict !== true) return {
79
+ value: {},
80
+ text: "{}",
81
+ raw: "{}"
82
+ };
83
+ if (wire === "object") throw new InvalidToolArgumentsError(tc);
84
+ return {
85
+ value: void 0,
86
+ text: args.raw,
87
+ raw: args.raw
88
+ };
89
+ }
90
+ /**
91
+ * A custom (freeform) tool call reached a wire that has no faithful projection
92
+ * for it. Only the OpenAI Responses API (HTTP and WebSocket) emits custom tool
93
+ * calls, from a fixture's `customToolCalls` or a `customToolCall` block in its
94
+ * `responsesBlocks`. The handlers of the other wires raise this through
95
+ * {@link rejectResponsesOnlyToolCalls} (usually via
96
+ * {@link requireEmittedFunctionToolCalls}) before they write any content.
97
+ * Ollama `/api/generate` is the exception: it rejects every tool-call fixture
98
+ * with a 400 before this check.
99
+ */
100
+ var UnsupportedToolCallError = class extends Error {
101
+ toolName;
102
+ wire;
103
+ constructor(toolName, wire) {
104
+ super(`aimock: fixture tool call "${toolName}" is a custom tool call, which only the OpenAI Responses API supports; this request arrived on ${wire}`);
105
+ this.name = "UnsupportedToolCallError";
106
+ this.toolName = toolName;
107
+ this.wire = wire;
108
+ }
109
+ };
110
+ /**
111
+ * A fixture tool call is malformed: a `toolCalls` entry that is not an object,
112
+ * a malformed `customToolCalls` entry, or a malformed tool block in
113
+ * `responsesBlocks`. Programmatic and factory fixtures skip load validation,
114
+ * so this request-time guard is their validation for the rules
115
+ * {@link assertResponsesToolCalls} and {@link resolveResponsesBlocks} check.
116
+ * An HTTP request then fails with a 500 that carries this message and `code`;
117
+ * a WebSocket turn gets the transport's error message with the code. A
118
+ * malformed legacy `blocks` entry keeps the plain Error of
119
+ * {@link resolveFixtureBlocks}.
120
+ */
121
+ var InvalidFixtureToolCallError = class extends Error {
122
+ code = "aimock_invalid_fixture_tool_call";
123
+ constructor(index, problem, carrier = "toolCalls") {
124
+ super(carrier === "blocks" ? `Invalid fixture block at index ${index}: ${problem}` : `Invalid fixture tool call: ${problem} (${carrier}[${index}])`);
125
+ this.name = "InvalidFixtureToolCallError";
126
+ }
127
+ };
128
+ /**
129
+ * Request-time guard for one custom tool call (a `customToolCalls` entry).
130
+ * Programmatic and factory fixtures skip load validation, so this is their
131
+ * validation: an object with a non-empty string `name`, a string `input`, no
132
+ * `arguments`, a string `id` when present and a non-empty string `namespace`
133
+ * when present.
134
+ */
135
+ function assertCustomToolCall(call, index) {
136
+ const fail = (problem) => {
137
+ throw new InvalidFixtureToolCallError(index, problem, "customToolCalls");
138
+ };
139
+ if (!isPlainObject(call)) fail("expected an object");
140
+ const tc = call;
141
+ if (tc.namespace !== void 0 && (typeof tc.namespace !== "string" || tc.namespace === "")) fail("\"namespace\" must be a non-empty string when present");
142
+ if (typeof tc.name !== "string" || tc.name === "") fail("custom tool call requires a non-empty string \"name\" field");
143
+ if (typeof tc.input !== "string") fail("\"input\" must be a string for a custom tool call");
144
+ if (tc.arguments !== void 0) fail("custom tool call takes \"input\", not \"arguments\"");
145
+ if (tc.id !== void 0 && typeof tc.id !== "string") fail("custom tool call \"id\" must be a string when present");
146
+ }
147
+ /**
148
+ * Validate a response's `customToolCalls` (OpenAI Responses only) before it is
149
+ * served. Throws {@link InvalidFixtureToolCallError} on the first malformed
150
+ * entry. The key is new, so no fixture of an earlier release reaches this.
151
+ */
152
+ function assertCustomToolCalls(response) {
153
+ const list = response.customToolCalls;
154
+ if (list === void 0) return;
155
+ if (!Array.isArray(list)) throw new InvalidFixtureToolCallError(0, "customToolCalls must be an array", "customToolCalls");
156
+ list.forEach((call, i) => assertCustomToolCall(call, i));
157
+ }
158
+ /**
159
+ * Validate the custom calls among the tool calls the OpenAI Responses API is
160
+ * about to serve (see {@link servedToolCalls}). Function calls are not
161
+ * checked here: they keep the handling of earlier releases (a non-string
162
+ * `arguments` fails with the uncoded error of the Responses builders).
163
+ */
164
+ function assertResponsesToolCalls(calls) {
165
+ let customIndex = 0;
166
+ for (const tc of calls) if (isPlainObject(tc) && tc.type === "custom") assertCustomToolCall(tc, customIndex++);
167
+ }
168
+ /**
169
+ * A fixture's `toolCalls` for a wire that cannot carry custom tool calls.
170
+ * Every entry is a function call and passes through unchanged, exactly as in
171
+ * earlier releases (the builders read its `name`, `arguments` and `id`; its
172
+ * Responses-only `namespace` is not emitted). Custom calls live in
173
+ * `customToolCalls`, which {@link rejectResponsesOnlyToolCalls} rejects.
174
+ */
175
+ function requireFunctionToolCalls(calls) {
176
+ return calls;
177
+ }
178
+ /**
179
+ * Reject the Responses-only custom tool calls on a wire that cannot carry
180
+ * them: a non-empty `customToolCalls`, or a `customToolCall` block in
181
+ * `responsesBlocks`. Throws {@link UnsupportedToolCallError} naming `wire`.
182
+ * Both keys are new, so no fixture of an earlier release reaches this error.
183
+ */
184
+ function rejectResponsesOnlyToolCalls(response, wire) {
185
+ const r = response;
186
+ if (Array.isArray(r.customToolCalls) && r.customToolCalls.length > 0) {
187
+ const first = r.customToolCalls[0];
188
+ throw new UnsupportedToolCallError(isPlainObject(first) && typeof first.name === "string" ? first.name : "", wire);
189
+ }
190
+ if (Array.isArray(r.responsesBlocks)) {
191
+ for (const block of r.responsesBlocks) if (isPlainObject(block) && block.type === "customToolCall") throw new UnsupportedToolCallError(typeof block.name === "string" ? block.name : "", wire);
192
+ }
193
+ }
194
+ /**
195
+ * {@link rejectResponsesOnlyToolCalls}, then {@link requireFunctionToolCalls}
196
+ * on the response's `toolCalls` (ignoring any `blocks`).
197
+ */
198
+ function requireServedFunctionToolCalls(response, wire) {
199
+ rejectResponsesOnlyToolCalls(response, wire);
200
+ return requireFunctionToolCalls(response.toolCalls ?? []);
201
+ }
202
+ /**
203
+ * The function calls a non-Responses wire emits for this response, after
204
+ * {@link rejectResponsesOnlyToolCalls}. Non-empty ordered `blocks` are
205
+ * authoritative: the builders stream them (and validate them through
206
+ * {@link resolveFixtureBlocks}) and never emit the legacy `toolCalls`, so the
207
+ * result is empty. Without blocks, `toolCalls` is checked by
208
+ * {@link requireFunctionToolCalls}.
209
+ */
210
+ function requireEmittedFunctionToolCalls(response, wire) {
211
+ rejectResponsesOnlyToolCalls(response, wire);
212
+ if (Array.isArray(response.blocks) && response.blocks.length > 0) return [];
213
+ return requireFunctionToolCalls(response.toolCalls ?? []);
214
+ }
215
+ /** True for the fixture tool-call errors a handler surfaces as a coded 500. */
216
+ function isFixtureToolCallError(error) {
217
+ return error instanceof InvalidToolArgumentsError || error instanceof UnsupportedToolCallError || error instanceof InvalidFixtureToolCallError;
218
+ }
219
+ /** The aimock error code carried in every provider envelope for a fixture tool-call error. */
220
+ function fixtureToolCallErrorCode(error) {
221
+ if (error instanceof UnsupportedToolCallError) return "aimock_unsupported_tool_call";
222
+ if (error instanceof InvalidFixtureToolCallError) return error.code;
223
+ return "aimock_invalid_tool_arguments";
224
+ }
225
+ /**
226
+ * Google RPC error `details` carrying an aimock fixture tool-call code, for the
227
+ * Gemini, Vertex AI and Gemini Live envelopes (`google.rpc.ErrorInfo`: an
228
+ * UPPER_SNAKE `reason`, a `domain`, and string `metadata`).
229
+ */
230
+ function googleFixtureToolCallErrorDetails(code) {
231
+ return [{
232
+ "@type": "type.googleapis.com/google.rpc.ErrorInfo",
233
+ reason: code.toUpperCase(),
234
+ domain: "aimock",
235
+ metadata: { code }
236
+ }];
237
+ }
238
+ /**
239
+ * Run a WebSocket preflight `check` that may raise a fixture tool-call error
240
+ * ({@link InvalidToolArgumentsError}, {@link UnsupportedToolCallError} or
241
+ * {@link InvalidFixtureToolCallError}).
242
+ * Such an error marks the already-journaled entry as a 500 carrying the
243
+ * message, then propagates to the transport's error handler.
244
+ */
245
+ function journalFixtureToolCallError(journalEntry, check) {
246
+ try {
247
+ return check();
248
+ } catch (error) {
249
+ if (isFixtureToolCallError(error)) {
250
+ journalEntry.response.status = 500;
251
+ journalEntry.response.error = error.message;
252
+ }
253
+ throw error;
254
+ }
255
+ }
9
256
  /**
10
257
  * Resolve effective strict mode from per-request header and server default.
11
258
  * Header values override the server default — same precedence pattern as chaos
@@ -182,14 +429,192 @@ function isLiveResponse(value) {
182
429
  function isResponseFactory(r) {
183
430
  return typeof r === "function";
184
431
  }
432
+ const serverFixtureLists = /* @__PURE__ */ new WeakMap();
433
+ /**
434
+ * Array methods that read elements and write them back. On a server list
435
+ * they run on the caller's array, so the extended view of an element is
436
+ * never written into it.
437
+ */
438
+ const ELEMENT_MOVING_METHODS = new Set([
439
+ "copyWithin",
440
+ "fill",
441
+ "pop",
442
+ "push",
443
+ "reverse",
444
+ "shift",
445
+ "sort",
446
+ "splice",
447
+ "unshift"
448
+ ]);
449
+ /**
450
+ * The fixture list one server reads and writes: a live view of the caller's
451
+ * `fixtures` array, with its own identity. The matcher reads the server's
452
+ * `responsesTools` mode from the list it is given, so every handler on every
453
+ * wire sees that server's mode without extra parameters, and two servers that
454
+ * share one array each keep their own mode. With `"extended"`, reading an
455
+ * element gives `extendedView(element)` (the fixture with its held keys
456
+ * applied); the caller's array and its fixtures are never changed for it.
457
+ * Writes (push, splice, `length = 0`, ...) reach the caller's array.
458
+ */
459
+ function createServerFixtureList(fixtures, mode, extendedView) {
460
+ const boundMethods = /* @__PURE__ */ new Map();
461
+ const list = new Proxy(fixtures, { get(target, key) {
462
+ const value = Reflect.get(target, key);
463
+ if (typeof value === "function") {
464
+ if (!ELEMENT_MOVING_METHODS.has(key)) return value;
465
+ let bound = boundMethods.get(key);
466
+ if (bound === void 0) {
467
+ bound = value.bind(target);
468
+ boundMethods.set(key, bound);
469
+ }
470
+ return bound;
471
+ }
472
+ if (typeof key !== "string" || mode() !== "extended") return value;
473
+ const first = key.charCodeAt(0);
474
+ if (first < 48 || first > 57 || value === null || typeof value !== "object") return value;
475
+ return extendedView(value);
476
+ } });
477
+ serverFixtureLists.set(list, {
478
+ target: fixtures,
479
+ mode
480
+ });
481
+ return list;
482
+ }
483
+ /** Fixture arrays that only their own server reads: see {@link markServerOwnedFixtures}. */
484
+ const serverOwnedFixtureArrays = /* @__PURE__ */ new WeakSet();
485
+ /**
486
+ * @internal Mark `fixtures` as an array no other server reads (LLMock's own
487
+ * array). A server may change the fixtures it makes itself (the control API)
488
+ * in place only in such an array; in a caller's array, which another server
489
+ * may share, they stay as made and an extended server reads them through its
490
+ * view.
491
+ */
492
+ function markServerOwnedFixtures(fixtures) {
493
+ serverOwnedFixtureArrays.add(fixtures);
494
+ }
495
+ /** Whether the array behind `fixtures` (a server list or an array) is server-owned. */
496
+ function isServerOwnedFixtures(fixtures) {
497
+ return serverOwnedFixtureArrays.has(fixtureListTarget(fixtures));
498
+ }
499
+ /** Whether `fixtures` is the list of a server running with `responsesTools: "extended"`. */
500
+ function isExtendedResponsesToolsList(fixtures) {
501
+ return serverFixtureLists.get(fixtures)?.mode() === "extended";
502
+ }
503
+ /** The caller's array behind a server list; any other array is itself. */
504
+ function fixtureListTarget(fixtures) {
505
+ return serverFixtureLists.get(fixtures)?.target ?? fixtures;
506
+ }
507
+ /**
508
+ * Requests matched against an extended fixture list. {@link resolveResponse}
509
+ * reads it, so the response a handler serves follows the same mode as the
510
+ * match that chose its fixture.
511
+ */
512
+ const extendedResponsesToolsRequests = /* @__PURE__ */ new WeakSet();
513
+ /** Mark `request` as matched with `responsesTools: "extended"`. */
514
+ function markExtendedResponsesToolsRequest(request) {
515
+ extendedResponsesToolsRequests.add(request);
516
+ }
517
+ /**
518
+ * Drop `customToolCalls` and `responsesBlocks`, for responses served without
519
+ * `responsesTools: "extended"`. Earlier releases ignored both keys, so a
520
+ * fixture that carries them serves exactly as before. Returns the same object
521
+ * when neither key is set.
522
+ */
523
+ function withoutResponsesToolKeys(response) {
524
+ if (!isPlainObject(response)) return response;
525
+ if (!("customToolCalls" in response) && !("responsesBlocks" in response)) return response;
526
+ const copy = { ...response };
527
+ delete copy.customToolCalls;
528
+ delete copy.responsesBlocks;
529
+ return copy;
530
+ }
185
531
  async function resolveResponse(fixture, request) {
186
- if (typeof fixture.response === "function") try {
187
- return normalizeFactoryResponse(await fixture.response(request));
188
- } catch (err) {
189
- const msg = err instanceof Error ? err.message : String(err);
190
- throw new Error(`Response factory threw: ${msg}`, { cause: err });
532
+ const served = (response) => sanitizeFixtureResponse(extendedResponsesToolsRequests.has(request) ? response : withoutResponsesToolKeys(response));
533
+ if (typeof fixture.response === "function") {
534
+ let normalized;
535
+ try {
536
+ normalized = normalizeFactoryResponse(await fixture.response(request));
537
+ } catch (err) {
538
+ const msg = err instanceof Error ? err.message : String(err);
539
+ throw new Error(`Response factory threw: ${msg}`, { cause: err });
540
+ }
541
+ return served(normalized);
191
542
  }
192
- return fixture.response;
543
+ return served(fixture.response);
544
+ }
545
+ function isPlainObject(value) {
546
+ return value !== null && typeof value === "object" && !Array.isArray(value);
547
+ }
548
+ /** A non-empty string, the only valid value of a tool call's `namespace`. */
549
+ function isValidNamespace(value) {
550
+ return typeof value === "string" && value !== "";
551
+ }
552
+ /**
553
+ * Drop the keys a served `toolCalls` entry or `toolCall` block ignores, so
554
+ * no handler reads them: on a `toolCalls` entry, `type` and `input` (a
555
+ * `toolCalls` entry is always a function call; custom calls live in
556
+ * `customToolCalls`) and an invalid `namespace` (not a non-empty string); on a
557
+ * `toolCall` block, `input` and an invalid `namespace`. Earlier releases
558
+ * ignored all of these, so fixtures that carry them serve exactly as before.
559
+ * Returns the same object when nothing needs dropping. `customToolCalls` and
560
+ * `responsesBlocks` are new keys and are validated, not sanitized.
561
+ */
562
+ function sanitizeFixtureResponse(response) {
563
+ if (!isPlainObject(response)) return response;
564
+ const r = response;
565
+ const dropKeys = (entry, keys) => {
566
+ if (!isPlainObject(entry)) return entry;
567
+ const drop = keys.filter((key) => key in entry && (key !== "namespace" || !isValidNamespace(entry.namespace)));
568
+ if (drop.length === 0) return entry;
569
+ const copy = { ...entry };
570
+ for (const key of drop) delete copy[key];
571
+ return copy;
572
+ };
573
+ const sanitizeList = (list, pick) => {
574
+ if (!Array.isArray(list)) return list;
575
+ const next = list.map(pick);
576
+ return next.some((entry, k) => entry !== list[k]) ? next : list;
577
+ };
578
+ const toolCalls = sanitizeList(r.toolCalls, (entry) => dropKeys(entry, [
579
+ "type",
580
+ "input",
581
+ "namespace"
582
+ ]));
583
+ let blocks = sanitizeList(r.blocks, (entry) => isPlainObject(entry) && entry.type === "toolCall" ? dropKeys(entry, ["input", "namespace"]) : entry);
584
+ if (!(Array.isArray(r.blocks) && r.blocks.length > 0) && Array.isArray(r.responsesBlocks) && r.responsesBlocks.length > 0 && !r.responsesBlocks.some((entry) => isPlainObject(entry) && entry.type === "customToolCall")) blocks = r.responsesBlocks;
585
+ if (toolCalls === r.toolCalls && blocks === r.blocks) return response;
586
+ const copy = { ...r };
587
+ if (toolCalls !== r.toolCalls) copy.toolCalls = toolCalls;
588
+ if (blocks !== r.blocks) copy.blocks = blocks;
589
+ return copy;
590
+ }
591
+ /**
592
+ * Drop `namespace` from every `toolCalls` entry and `toolCall` block, for
593
+ * OpenAI Responses requests served without `responsesTools: "extended"`:
594
+ * earlier releases never emitted it. (Without that mode, resolveResponse has
595
+ * already dropped `customToolCalls` and `responsesBlocks`.) Returns the same
596
+ * object when no namespace is set.
597
+ */
598
+ function withoutLegacyNamespaces(response) {
599
+ if (!isPlainObject(response)) return response;
600
+ const r = response;
601
+ const strip = (list, isTarget) => {
602
+ if (!Array.isArray(list)) return list;
603
+ if (!list.some((entry) => isPlainObject(entry) && isTarget(entry) && "namespace" in entry)) return list;
604
+ return list.map((entry) => {
605
+ if (!isPlainObject(entry) || !isTarget(entry) || !("namespace" in entry)) return entry;
606
+ const copy = { ...entry };
607
+ delete copy.namespace;
608
+ return copy;
609
+ });
610
+ };
611
+ const toolCalls = strip(r.toolCalls, () => true);
612
+ const blocks = strip(r.blocks, (entry) => entry.type === "toolCall");
613
+ if (toolCalls === r.toolCalls && blocks === r.blocks) return response;
614
+ const copy = { ...r };
615
+ if (toolCalls !== r.toolCalls) copy.toolCalls = toolCalls;
616
+ if (blocks !== r.blocks) copy.blocks = blocks;
617
+ return copy;
193
618
  }
194
619
  function normalizeFactoryResponse(raw) {
195
620
  const r = { ...raw };
@@ -208,6 +633,10 @@ function normalizeFactoryResponse(raw) {
208
633
  };
209
634
  return { ...block };
210
635
  });
636
+ if (Array.isArray(r.responsesBlocks)) r.responsesBlocks = r.responsesBlocks.map((block) => isPlainObject(block) && block.type === "toolCall" && typeof block.arguments === "object" && block.arguments !== null ? {
637
+ ...block,
638
+ arguments: JSON.stringify(block.arguments)
639
+ } : block);
211
640
  return r;
212
641
  }
213
642
  function generateId(prefix = "chatcmpl") {
@@ -279,6 +708,12 @@ function isTextResponse(r) {
279
708
  function isToolCallResponse(r) {
280
709
  return "toolCalls" in r && Array.isArray(r.toolCalls) && !("content" in r && typeof r.content === "string");
281
710
  }
711
+ /**
712
+ * Whether `r` is a combined content + tool calls response: a string `content`
713
+ * with a `toolCalls` array, or a non-empty `blocks` array. Public, with the
714
+ * 1.44.0 result for every input; `responsesBlocks` does not count. aimock's
715
+ * own handlers use {@link isCombinedFixtureResponse}, which also counts it.
716
+ */
282
717
  function isContentWithToolCallsResponse(r) {
283
718
  const o = r;
284
719
  const hasContentAndToolCalls = "content" in r && typeof o.content === "string" && "toolCalls" in r && Array.isArray(o.toolCalls);
@@ -286,6 +721,19 @@ function isContentWithToolCallsResponse(r) {
286
721
  return hasContentAndToolCalls || hasNonEmptyBlocks;
287
722
  }
288
723
  /**
724
+ * @internal The combined-response guard aimock's handlers, validation and
725
+ * misbehavior use: {@link isContentWithToolCallsResponse} plus a non-empty
726
+ * `responsesBlocks`. In legacy mode those keys are dropped before serving, so
727
+ * only `responsesTools: "extended"` sees the extra clause.
728
+ */
729
+ function isCombinedFixtureResponse(r) {
730
+ const o = r;
731
+ const hasContentAndToolCalls = "content" in r && typeof o.content === "string" && "toolCalls" in r && Array.isArray(o.toolCalls);
732
+ const hasNonEmptyBlocks = Array.isArray(o.blocks) && o.blocks.length > 0;
733
+ const hasNonEmptyResponsesBlocks = Array.isArray(o.responsesBlocks) && o.responsesBlocks.length > 0;
734
+ return hasContentAndToolCalls || hasNonEmptyBlocks || hasNonEmptyResponsesBlocks;
735
+ }
736
+ /**
289
737
  * Validate and pass through the ordered `blocks` field of a combined
290
738
  * content+toolCalls fixture. Used ONLY on the new block-iteration path (when a
291
739
  * fixture explicitly sets `blocks`); it is NOT a legacy-order reconstructor —
@@ -312,7 +760,9 @@ function isContentWithToolCallsResponse(r) {
312
760
  * optional string `id`. The return type guarantees `arguments: string` — every
313
761
  * caller relies on that. Throws on a malformed array or entry — same fail-fast
314
762
  * idiom as the other fixture validators in this module (see e.g. the factory
315
- * guard at {@link resolveResponse}).
763
+ * guard at {@link resolveResponse}). A `customToolCall` block is not a
764
+ * `blocks` entry (it belongs in `responsesBlocks`, see
765
+ * {@link resolveResponsesBlocks}) and fails as an unknown type.
316
766
  */
317
767
  function resolveFixtureBlocks(blocks) {
318
768
  if (!Array.isArray(blocks)) throw new Error(`Invalid fixture blocks: expected an array, got ${typeof blocks}`);
@@ -342,6 +792,130 @@ function resolveFixtureBlocks(blocks) {
342
792
  } else throw new Error(`Invalid fixture block at index ${i}: unknown type ${JSON.stringify(b.type)} (expected "text" or "toolCall")`);
343
793
  });
344
794
  }
795
+ /**
796
+ * Validate and normalize a fixture's `responsesBlocks` (OpenAI Responses
797
+ * only). Same rules and normalized copy as {@link resolveFixtureBlocks}, plus:
798
+ * a `customToolCall` block with a non-empty string `name`, a string `input`
799
+ * (never parsed or stringified), no `arguments` and an optional string `id`;
800
+ * on either tool block, `namespace` must be a non-empty string when present,
801
+ * and a `toolCall` block carries no `input`. The key is new, so a malformed
802
+ * tool block throws the coded {@link InvalidFixtureToolCallError}; a malformed
803
+ * text block or an unknown type throws a plain Error.
804
+ */
805
+ function resolveResponsesBlocks(blocks) {
806
+ if (!Array.isArray(blocks)) throw new Error(`Invalid fixture responsesBlocks: expected an array, got ${typeof blocks}`);
807
+ return blocks.map((block, i) => {
808
+ if (!isPlainObject(block)) throw new Error(`Invalid fixture block at index ${i}: expected an object`);
809
+ const b = block;
810
+ const failToolCall = (problem) => {
811
+ throw new InvalidFixtureToolCallError(i, problem, "blocks");
812
+ };
813
+ if ((b.type === "toolCall" || b.type === "customToolCall") && b.namespace !== void 0 && (typeof b.namespace !== "string" || b.namespace === "")) failToolCall("\"namespace\" must be a non-empty string when present");
814
+ const namespace = typeof b.namespace === "string" ? { namespace: b.namespace } : {};
815
+ const id = typeof b.id === "string" ? { id: b.id } : {};
816
+ if (b.type === "text") {
817
+ if (typeof b.text !== "string") throw new Error(`Invalid fixture block at index ${i}: "text" block requires a string "text" field`);
818
+ return {
819
+ type: "text",
820
+ text: b.text
821
+ };
822
+ }
823
+ if (b.type === "toolCall") {
824
+ if (b.input !== void 0) failToolCall("\"input\" is only valid on a \"customToolCall\" block");
825
+ if (typeof b.name !== "string") failToolCall("\"toolCall\" block requires a string \"name\" field");
826
+ if (b.id !== void 0 && typeof b.id !== "string") failToolCall("\"toolCall\" block \"id\" must be a string when present");
827
+ const args = typeof b.arguments === "object" && b.arguments !== null ? JSON.stringify(b.arguments) : b.arguments;
828
+ if (typeof args !== "string") failToolCall("\"toolCall\" block requires a string or object \"arguments\" field");
829
+ return {
830
+ type: "toolCall",
831
+ name: b.name,
832
+ arguments: args,
833
+ ...id,
834
+ ...namespace
835
+ };
836
+ }
837
+ if (b.type === "customToolCall") {
838
+ if (typeof b.name !== "string" || b.name === "") failToolCall("\"customToolCall\" block requires a non-empty string \"name\" field");
839
+ if (typeof b.input !== "string") failToolCall("\"customToolCall\" block requires a string \"input\" field");
840
+ if (b.arguments !== void 0) failToolCall("\"customToolCall\" block takes \"input\", not \"arguments\"");
841
+ if (b.id !== void 0 && typeof b.id !== "string") failToolCall("\"customToolCall\" block \"id\" must be a string when present");
842
+ return {
843
+ type: "customToolCall",
844
+ name: b.name,
845
+ input: b.input,
846
+ ...id,
847
+ ...namespace
848
+ };
849
+ }
850
+ throw new Error(`Invalid fixture block at index ${i}: unknown type ${JSON.stringify(b.type)} (expected "text", "toolCall" or "customToolCall")`);
851
+ });
852
+ }
853
+ /** Allocate the exact OpenAI call identities once for both wire output and observations. */
854
+ function prepareOpenAIChatMisbehavior(plan) {
855
+ const response = plan.response;
856
+ const combined = isCombinedFixtureResponse(response);
857
+ const outcome = combined ? resolveServedBlockOutcome(response) : void 0;
858
+ const calls = outcome?.toolCalls ?? (combined || isToolCallResponse(response) ? servedToolCalls(response) : []);
859
+ const duplicate = plan.duplicateId;
860
+ const toolCalls = calls.map((call, index) => ({
861
+ ...call,
862
+ ...index === duplicate?.destinationIndex ? {} : { id: call.id || generateToolCallId() }
863
+ }));
864
+ if (duplicate) toolCalls[duplicate.destinationIndex].id = toolCalls[duplicate.sourceIndex].id;
865
+ let preparedResponse = { ...response };
866
+ if ("usage" in preparedResponse) delete preparedResponse.usage;
867
+ if (plan.stop === "length") preparedResponse = {
868
+ ...preparedResponse,
869
+ finishReason: "length"
870
+ };
871
+ if (outcome) preparedResponse = withServedToolCalls({
872
+ ...preparedResponse,
873
+ content: outcome.content
874
+ }, toolCalls, rebuildOrderedBlocks(outcome.ordered, toolCalls));
875
+ else if (combined || isToolCallResponse(response)) preparedResponse = withServedToolCalls(preparedResponse, toolCalls);
876
+ return {
877
+ ...plan,
878
+ response: preparedResponse,
879
+ summary: {
880
+ ...plan.summary,
881
+ servedToolCalls: toolCalls.map(servedMisbehaviorToolCall)
882
+ }
883
+ };
884
+ }
885
+ /**
886
+ * The journaled form of a served misbehavior tool call: `{ name, arguments,
887
+ * id }`. A Responses custom tool call adds `type: "custom"` and carries its
888
+ * free-text `input` in `arguments`; `namespace` is recorded only when set.
889
+ */
890
+ function servedMisbehaviorToolCall(call) {
891
+ const namespace = call.namespace !== void 0 ? { namespace: call.namespace } : {};
892
+ return call.type === "custom" ? {
893
+ type: "custom",
894
+ name: call.name,
895
+ arguments: call.input,
896
+ id: call.id,
897
+ ...namespace
898
+ } : {
899
+ name: call.name,
900
+ arguments: call.arguments,
901
+ id: call.id,
902
+ ...namespace
903
+ };
904
+ }
905
+ /** The text a tool call contributes to an estimated completion: name plus arguments or input. */
906
+ function toolCallUsageText(call) {
907
+ return call.name + (call.type === "custom" ? call.input : call.arguments);
908
+ }
909
+ /** Estimate once from the full applied output, before any delivery interruption. */
910
+ function resolveOpenAIChatMisbehaviorUsage(plan, request, exposeReasoning = true) {
911
+ const response = plan.response;
912
+ const combined = isCombinedFixtureResponse(response);
913
+ const outcome = combined ? resolveServedBlockOutcome(response) : void 0;
914
+ const calls = outcome?.toolCalls ?? (combined || isToolCallResponse(response) ? servedToolCalls(response) : []);
915
+ const content = outcome?.content ?? ("content" in response && typeof response.content === "string" ? response.content : "");
916
+ const reasoning = plan.reasoning ?? ("reasoning" in response && typeof response.reasoning === "string" ? response.reasoning : "");
917
+ return resolveUsage(void 0, request.messages.map((message) => typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content.map((part) => part.text ?? "").join("") : "").join(""), content + calls.map(toolCallUsageText).join("") + (plan.refusal ?? "") + (exposeReasoning ? reasoning : ""));
918
+ }
345
919
  /** Project normalized ordered blocks without changing the fixture or generating ids. */
346
920
  function resolveFixtureBlockOutcome(blocks) {
347
921
  const ordered = resolveFixtureBlocks(blocks);
@@ -360,6 +934,118 @@ function resolveFixtureBlockOutcome(blocks) {
360
934
  hasToolCalls: toolCalls.length > 0
361
935
  };
362
936
  }
937
+ /**
938
+ * Every tool call a response serves, in order: the function calls of
939
+ * `toolCalls`, then the custom calls of `customToolCalls` (each tagged
940
+ * `type: "custom"`). Only the OpenAI Responses API may serve the custom ones;
941
+ * the other wires reject a non-empty `customToolCalls` first
942
+ * ({@link rejectResponsesOnlyToolCalls}).
943
+ */
944
+ function servedToolCalls(response) {
945
+ const calls = [...response.toolCalls ?? []];
946
+ for (const call of Array.isArray(response.customToolCalls) ? response.customToolCalls : []) calls.push(isPlainObject(call) ? {
947
+ ...call,
948
+ type: "custom"
949
+ } : call);
950
+ return calls;
951
+ }
952
+ /**
953
+ * Resolve the ordered blocks a response serves, with each tool block projected
954
+ * to its {@link FixtureToolCall}: a non-empty `responsesBlocks` (OpenAI
955
+ * Responses only, through {@link resolveResponsesBlocks}), else a non-empty
956
+ * legacy `blocks` (through {@link resolveFixtureBlocks}, which rejects a
957
+ * `customToolCall` block with the error of earlier releases). Undefined when
958
+ * the response has neither.
959
+ */
960
+ function resolveServedBlockOutcome(response) {
961
+ const r = response;
962
+ let ordered;
963
+ let source;
964
+ if (Array.isArray(r.responsesBlocks) && r.responsesBlocks.length > 0) {
965
+ ordered = resolveResponsesBlocks(r.responsesBlocks);
966
+ source = "responsesBlocks";
967
+ } else if (Array.isArray(r.blocks) && r.blocks.length > 0) {
968
+ ordered = resolveFixtureBlocks(r.blocks);
969
+ source = "blocks";
970
+ } else return void 0;
971
+ let content = "";
972
+ const toolCalls = [];
973
+ for (const block of ordered) if (block.type === "text") content += block.text;
974
+ else toolCalls.push(fixtureBlockToolCall(block));
975
+ return {
976
+ ordered,
977
+ content,
978
+ toolCalls,
979
+ hasToolCalls: toolCalls.length > 0,
980
+ source
981
+ };
982
+ }
983
+ /**
984
+ * Write rewritten served tool calls (and, with `ordered`, rebuilt ordered
985
+ * blocks) back into a copy of `response`, split by carrier: function calls go
986
+ * to `toolCalls`, custom calls to `customToolCalls`, and the blocks to
987
+ * `responsesBlocks` when the response served those, else to `blocks`.
988
+ */
989
+ function withServedToolCalls(response, toolCalls, ordered) {
990
+ const functionCalls = [];
991
+ const customCalls = [];
992
+ for (const call of toolCalls) if (call.type === "custom") customCalls.push(call);
993
+ else functionCalls.push(call);
994
+ const out = {
995
+ ...response,
996
+ toolCalls: functionCalls
997
+ };
998
+ if (customCalls.length > 0 || "customToolCalls" in response) out.customToolCalls = customCalls;
999
+ if (ordered) {
1000
+ const r = response;
1001
+ if (Array.isArray(r.responsesBlocks) && r.responsesBlocks.length > 0) out.responsesBlocks = ordered;
1002
+ else out.blocks = ordered;
1003
+ }
1004
+ return out;
1005
+ }
1006
+ /** Project one normalized tool block to the matching served tool call. */
1007
+ function fixtureBlockToolCall(block) {
1008
+ const id = block.id !== void 0 ? { id: block.id } : {};
1009
+ const namespace = block.namespace !== void 0 ? { namespace: block.namespace } : {};
1010
+ return block.type === "customToolCall" ? {
1011
+ type: "custom",
1012
+ name: block.name,
1013
+ input: block.input,
1014
+ ...id,
1015
+ ...namespace
1016
+ } : {
1017
+ name: block.name,
1018
+ arguments: block.arguments,
1019
+ ...id,
1020
+ ...namespace
1021
+ };
1022
+ }
1023
+ /** Project one served tool call back to its ordered tool block. */
1024
+ function toolCallFixtureBlock(call) {
1025
+ const id = call.id !== void 0 ? { id: call.id } : {};
1026
+ const namespace = call.namespace !== void 0 ? { namespace: call.namespace } : {};
1027
+ return call.type === "custom" ? {
1028
+ type: "customToolCall",
1029
+ name: call.name,
1030
+ input: call.input,
1031
+ ...id,
1032
+ ...namespace
1033
+ } : {
1034
+ type: "toolCall",
1035
+ name: call.name,
1036
+ arguments: call.arguments,
1037
+ ...id,
1038
+ ...namespace
1039
+ };
1040
+ }
1041
+ /**
1042
+ * Rebuild ordered blocks after their tool calls were rewritten one-for-one:
1043
+ * text blocks are copied and the Nth tool block becomes `toolCalls[N]`.
1044
+ */
1045
+ function rebuildOrderedBlocks(ordered, toolCalls) {
1046
+ let callIndex = 0;
1047
+ return ordered.map((block) => block.type === "text" ? { ...block } : toolCallFixtureBlock(toolCalls[callIndex++]));
1048
+ }
363
1049
  function isErrorResponse(r) {
364
1050
  return "error" in r && r.error !== null && typeof r.error === "object" && "message" in r.error && typeof r.error.message === "string";
365
1051
  }
@@ -437,6 +1123,17 @@ function estimateTokens(text) {
437
1123
  return Math.max(1, Math.ceil(text.length / 4));
438
1124
  }
439
1125
  /**
1126
+ * Estimate prompt tokens from a request's messages array.
1127
+ */
1128
+ function estimatePromptTokens(messages) {
1129
+ let totalChars = 0;
1130
+ for (const msg of messages) if (typeof msg.content === "string") totalChars += msg.content.length;
1131
+ else if (Array.isArray(msg.content)) {
1132
+ for (const part of msg.content) if (part.text) totalChars += part.text.length;
1133
+ }
1134
+ return Math.max(1, Math.ceil(totalChars / 4));
1135
+ }
1136
+ /**
440
1137
  * Build usage object: use explicit overrides if provided, otherwise estimate.
441
1138
  *
442
1139
  * Shared by BOTH the non-streaming completion builders (below) and the
@@ -551,6 +1248,140 @@ function buildTextChunks(content, model, chunkSize, reasoning, overrides) {
551
1248
  });
552
1249
  return chunks;
553
1250
  }
1251
+ /** K9 exposure is selected by the provider path, never the echoed response model. */
1252
+ function buildOpenAIReasoningChunks(reasoning, model, chunkSize, exposeReasoning, overrides) {
1253
+ return buildTextChunks(exposeReasoning ? reasoning : "", model, chunkSize, void 0, {
1254
+ ...overrides,
1255
+ role: "assistant",
1256
+ finishReason: "length"
1257
+ }).map((chunk) => ({
1258
+ ...chunk,
1259
+ choices: chunk.choices.map((choice) => ({
1260
+ ...choice,
1261
+ delta: choice.delta.role !== void 0 ? {
1262
+ role: "assistant",
1263
+ content: null
1264
+ } : typeof choice.delta.content === "string" ? {
1265
+ role: "assistant",
1266
+ content: "",
1267
+ reasoning: choice.delta.content,
1268
+ reasoning_details: [{
1269
+ type: "reasoning.text",
1270
+ text: choice.delta.content,
1271
+ format: "unknown",
1272
+ index: 0
1273
+ }]
1274
+ } : {}
1275
+ }))
1276
+ }));
1277
+ }
1278
+ /** Render exposed reasoning or native OpenAI's empty length completion. */
1279
+ function buildOpenAIReasoningCompletion(reasoning, model, exposeReasoning, overrides, requestMessages) {
1280
+ const visible = exposeReasoning ? reasoning : "";
1281
+ const completion = buildTextCompletion(visible, model, void 0, {
1282
+ ...overrides,
1283
+ role: "assistant",
1284
+ finishReason: "length",
1285
+ usage: void 0
1286
+ }, requestMessages);
1287
+ return {
1288
+ ...completion,
1289
+ choices: completion.choices.map((choice) => ({
1290
+ ...choice,
1291
+ message: {
1292
+ role: "assistant",
1293
+ content: null,
1294
+ refusal: null,
1295
+ ...exposeReasoning ? {
1296
+ reasoning: visible,
1297
+ reasoning_details: [{
1298
+ type: "reasoning.text",
1299
+ text: visible,
1300
+ format: "unknown",
1301
+ index: 0
1302
+ }]
1303
+ } : {}
1304
+ }
1305
+ }))
1306
+ };
1307
+ }
1308
+ /** Render withheld output with only the role and native content-filter terminal. */
1309
+ function buildOpenAIContentFilterChunks(model, overrides) {
1310
+ return buildTextChunks("", model, 1, void 0, {
1311
+ ...overrides,
1312
+ role: "assistant",
1313
+ finishReason: "content_filter"
1314
+ }).map((chunk) => ({
1315
+ ...chunk,
1316
+ choices: chunk.choices.map((choice) => ({
1317
+ ...choice,
1318
+ delta: choice.delta.role !== void 0 ? {
1319
+ role: "assistant",
1320
+ content: null
1321
+ } : {}
1322
+ }))
1323
+ }));
1324
+ }
1325
+ /** Non-streaming filtered output contains no answer, refusal text, reasoning, or calls. */
1326
+ function buildOpenAIContentFilterCompletion(model, overrides, requestMessages) {
1327
+ const completion = buildTextCompletion("", model, void 0, {
1328
+ ...overrides,
1329
+ role: "assistant",
1330
+ finishReason: "content_filter",
1331
+ usage: void 0
1332
+ }, requestMessages);
1333
+ return {
1334
+ ...completion,
1335
+ choices: completion.choices.map((choice) => ({
1336
+ ...choice,
1337
+ message: {
1338
+ role: "assistant",
1339
+ content: null,
1340
+ refusal: null
1341
+ }
1342
+ }))
1343
+ };
1344
+ }
1345
+ /** Render an applied refusal on its own channel without ordinary content or reasoning. */
1346
+ function buildOpenAIRefusalChunks(refusal, model, chunkSize, overrides) {
1347
+ return buildTextChunks(refusal, model, chunkSize, void 0, {
1348
+ ...overrides,
1349
+ role: "assistant",
1350
+ finishReason: "stop"
1351
+ }).map((chunk) => ({
1352
+ ...chunk,
1353
+ choices: chunk.choices.map((choice) => {
1354
+ const delta = choice.delta.role !== void 0 ? {
1355
+ role: "assistant",
1356
+ content: null
1357
+ } : typeof choice.delta.content === "string" ? { refusal: choice.delta.content } : {};
1358
+ return {
1359
+ ...choice,
1360
+ delta
1361
+ };
1362
+ })
1363
+ }));
1364
+ }
1365
+ /** Refusal-only counterpart of the ordinary text completion builder. */
1366
+ function buildOpenAIRefusalCompletion(refusal, model, overrides, requestMessages) {
1367
+ const completion = buildTextCompletion(refusal, model, void 0, {
1368
+ ...overrides,
1369
+ role: "assistant",
1370
+ finishReason: "stop",
1371
+ usage: void 0
1372
+ }, requestMessages);
1373
+ return {
1374
+ ...completion,
1375
+ choices: completion.choices.map((choice) => ({
1376
+ ...choice,
1377
+ message: {
1378
+ role: "assistant",
1379
+ content: null,
1380
+ refusal
1381
+ }
1382
+ }))
1383
+ };
1384
+ }
554
1385
  function buildToolCallChunks(toolCalls, model, chunkSize, reasoning, overrides) {
555
1386
  const id = overrides?.id ?? generateId();
556
1387
  const created = overrides?.created ?? Math.floor(Date.now() / 1e3);
@@ -1598,5 +2429,5 @@ function parseMcpUndeclared(raw) {
1598
2429
  }
1599
2430
 
1600
2431
  //#endregion
1601
- export { FORMAT_TO_CONTENT_TYPE, MAX_EMBEDDING_DIMENSIONS, RequestBodyTooLargeError, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildToolCallChunks, buildToolCallCompletion, buildUsageChunk, decodeMcpHeaderValue, describeMatch, extractOverrides, flattenHeaders, formatToMime, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getContext, getTestId, hasMintedRequestId, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isJSONResponse, isJsonObject, isLiveResponse, isResponseFactory, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, markMintedRequestId, matchesPattern, normalizeEmbeddingInput, normalizeTextInput, parseStrictIntegerText, readBody, readBodyBufferBounded, resolveFixtureBlockOutcome, resolveFixtureBlocks, resolveMcpIdentity, resolveReasoningArtifactsForModel, resolveReasoningForModel, resolveRequestId, resolveResponse, resolveStrictMode, resolveTestId, resolveUsage, serializeErrorResponse, slugifyContext, slugifyTestId, strictNoMatchLogLine, strictNoMatchMessage, strictOverrideField, validateChatMessages, validateEmbeddingDimensions, validateToolsField, wouldProxyMiss };
2432
+ export { FORMAT_TO_CONTENT_TYPE, InvalidFixtureToolCallError, InvalidToolArgumentsError, MAX_EMBEDDING_DIMENSIONS, RequestBodyTooLargeError, UnsupportedToolCallError, assertCustomToolCalls, assertResponsesToolCalls, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildEmbeddingResponse, buildOpenAIContentFilterChunks, buildOpenAIContentFilterCompletion, buildOpenAIReasoningChunks, buildOpenAIReasoningCompletion, buildOpenAIRefusalChunks, buildOpenAIRefusalCompletion, buildTextChunks, buildTextCompletion, buildToolCallChunks, buildToolCallCompletion, buildUsageChunk, createServerFixtureList, decodeMcpHeaderValue, describeMatch, estimatePromptTokens, estimateTokens, extractOverrides, fixtureListTarget, fixtureToolCallErrorCode, flattenHeaders, formatToMime, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getContext, getTestId, googleFixtureToolCallErrorDetails, hasMintedRequestId, isAudioResponse, isCombinedFixtureResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isExtendedResponsesToolsList, isFixtureToolCallError, isImageResponse, isJSONResponse, isJsonObject, isLiveResponse, isResponseFactory, isServerOwnedFixtures, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, journalFixtureToolCallError, keepAuthoredToolArguments, markExtendedResponsesToolsRequest, markMintedRequestId, markServerOwnedFixtures, matchesPattern, normalizeEmbeddingInput, normalizeTextInput, parseStrictIntegerText, prepareOpenAIChatMisbehavior, readBody, readBodyBufferBounded, rebuildOrderedBlocks, rejectResponsesOnlyToolCalls, requireEmittedFunctionToolCalls, requireFunctionToolCalls, requireServedFunctionToolCalls, resolveFixtureBlockOutcome, resolveFixtureBlocks, resolveMcpIdentity, resolveOpenAIChatMisbehaviorUsage, resolveReasoningArtifactsForModel, resolveReasoningForModel, resolveRequestId, resolveResponse, resolveResponsesBlocks, resolveServedBlockOutcome, resolveStrictMode, resolveTestId, resolveUsage, runWithToolArgumentsScope, serializeErrorResponse, servedToolArgs, servedToolCalls, slugifyContext, slugifyTestId, strictNoMatchLogLine, strictNoMatchMessage, strictOverrideField, strictToolArgumentsEnabled, toolArgsForWire, toolCallFixtureBlock, validateChatMessages, validateEmbeddingDimensions, validateToolsField, withServedToolCalls, withoutLegacyNamespaces, withoutResponsesToolKeys, wouldProxyMiss };
1602
2433
  //# sourceMappingURL=helpers.js.map