@goah/cli 0.11.5 → 0.13.1

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 (242) hide show
  1. package/dist/LICENSE +201 -0
  2. package/dist/THIRD-PARTY-NOTICES.md +2319 -0
  3. package/dist/anthropic-messages-WBFOHES5.js +7214 -0
  4. package/dist/azure-openai-responses-NZFH3PO6.js +253 -0
  5. package/dist/chunk-25XSBFX6.js +639 -0
  6. package/dist/chunk-2QBQZGXF.js +110 -0
  7. package/dist/chunk-2ZP2NBW3.js +345 -0
  8. package/dist/chunk-4KA63VNZ.js +2 -0
  9. package/dist/chunk-4M6TXTT5.js +86 -0
  10. package/dist/chunk-4US7ZHT3.js +20 -0
  11. package/dist/chunk-6M3OOCKO.js +11809 -0
  12. package/dist/chunk-7AXAFDPG.js +17 -0
  13. package/dist/chunk-BXA47DTF.js +548 -0
  14. package/dist/chunk-FSBUS2BI.js +26 -0
  15. package/dist/chunk-GKDRAHLI.js +4787 -0
  16. package/dist/chunk-H462EFJP.js +89 -0
  17. package/dist/chunk-IIJQ3DW4.js +35 -0
  18. package/dist/chunk-JQD5EWJY.js +34 -0
  19. package/dist/chunk-K26BVR6O.js +61 -0
  20. package/dist/chunk-KAO7WIXG.js +31 -0
  21. package/dist/chunk-LBKI23CC.js +9810 -0
  22. package/dist/chunk-LKBKZEHT.js +41 -0
  23. package/dist/chunk-MD7TLTXZ.js +18 -0
  24. package/dist/chunk-MPXK7QBL.js +868 -0
  25. package/dist/chunk-NRLGWZJC.js +11 -0
  26. package/dist/chunk-PFEV3HWI.js +1178 -0
  27. package/dist/chunk-QBD6EJ2Z.js +1746 -0
  28. package/dist/chunk-R6I3VKME.js +132 -0
  29. package/dist/chunk-TJON22J4.js +87 -0
  30. package/dist/chunk-ULY36ME4.js +33097 -0
  31. package/dist/chunk-VWEV4LTH.js +25 -0
  32. package/dist/chunk-X7UWW2PN.js +883 -0
  33. package/dist/chunk-XALZLRYK.js +9221 -0
  34. package/dist/chunk-XPQKM3L7.js +57 -0
  35. package/dist/chunk-YH6YJ2IB.js +1773 -0
  36. package/dist/cli.d.ts +0 -2
  37. package/dist/cli.js +13148 -506
  38. package/dist/console/assets/index-3sYrDMmt.css +1 -0
  39. package/dist/console/assets/index-B1vGMXKr.js +52 -0
  40. package/dist/console/assets/index-B1vGMXKr.js.map +1 -0
  41. package/dist/console/index.html +2 -2
  42. package/dist/dist-65MDQA4Q.js +1126 -0
  43. package/dist/dist-KNR2XL6J.js +39 -0
  44. package/dist/execution.d.ts +557 -2
  45. package/dist/execution.js +37 -2
  46. package/dist/faux-runner-worker.js +128 -0
  47. package/dist/google-generative-ai-YMHXZSFE.js +422 -0
  48. package/dist/google-vertex-X6DB3ZQ6.js +471 -0
  49. package/dist/index.d.ts +855 -44
  50. package/dist/index.js +84 -257
  51. package/dist/kernel.d.ts +39 -2
  52. package/dist/kernel.js +21 -2
  53. package/dist/mistral-conversations-TY3MMD6G.js +718 -0
  54. package/dist/multipart-parser-F6M4NJZU.js +373 -0
  55. package/dist/openai-codex-responses-BRDUMLN5.js +1374 -0
  56. package/dist/openai-completions-CX634XN3.js +1139 -0
  57. package/dist/openai-responses-HMCXJIHT.js +300 -0
  58. package/dist/openrouter-images-KTWET2H2.js +148 -0
  59. package/dist/pi-messages-XL5OEC4K.js +307 -0
  60. package/dist/pi-worker.js +671 -0
  61. package/dist/runner-pi.d.ts +342 -2
  62. package/dist/runner-pi.js +46 -2
  63. package/dist/runner-registry-M776E3SE.js +22 -0
  64. package/dist/sqlite.d.ts +446 -2
  65. package/dist/sqlite.js +15 -2
  66. package/dist/src-F2KBSV4T.js +1398 -0
  67. package/dist/supervisor.d.ts +625 -2
  68. package/dist/supervisor.js +39 -2
  69. package/dist/testkit.d.ts +564 -2
  70. package/dist/testkit.js +127 -2
  71. package/dist/transcript.d.ts +84 -0
  72. package/dist/transcript.js +25 -0
  73. package/dist/verification-worker.js +72 -0
  74. package/package.json +3 -28
  75. package/dist/cli.d.ts.map +0 -1
  76. package/dist/cli.js.map +0 -1
  77. package/dist/console/assets/index-BJTGvlCH.js +0 -52
  78. package/dist/console/assets/index-BJTGvlCH.js.map +0 -1
  79. package/dist/console/assets/index-msBn41Cl.css +0 -1
  80. package/dist/control.d.ts +0 -106
  81. package/dist/control.d.ts.map +0 -1
  82. package/dist/control.js +0 -215
  83. package/dist/control.js.map +0 -1
  84. package/dist/execution.d.ts.map +0 -1
  85. package/dist/execution.js.map +0 -1
  86. package/dist/index.d.ts.map +0 -1
  87. package/dist/index.js.map +0 -1
  88. package/dist/inspect.d.ts +0 -61
  89. package/dist/inspect.d.ts.map +0 -1
  90. package/dist/inspect.js +0 -110
  91. package/dist/inspect.js.map +0 -1
  92. package/dist/kernel.d.ts.map +0 -1
  93. package/dist/kernel.js.map +0 -1
  94. package/dist/live-config.d.ts +0 -10
  95. package/dist/live-config.d.ts.map +0 -1
  96. package/dist/live-config.js +0 -44
  97. package/dist/live-config.js.map +0 -1
  98. package/dist/metrics.d.ts +0 -2
  99. package/dist/metrics.d.ts.map +0 -1
  100. package/dist/metrics.js +0 -2
  101. package/dist/metrics.js.map +0 -1
  102. package/dist/prompt-queue.d.ts +0 -13
  103. package/dist/prompt-queue.d.ts.map +0 -1
  104. package/dist/prompt-queue.js +0 -30
  105. package/dist/prompt-queue.js.map +0 -1
  106. package/dist/runner-pi.d.ts.map +0 -1
  107. package/dist/runner-pi.js.map +0 -1
  108. package/dist/runner-registry.d.ts +0 -8
  109. package/dist/runner-registry.d.ts.map +0 -1
  110. package/dist/runner-registry.js +0 -12
  111. package/dist/runner-registry.js.map +0 -1
  112. package/dist/searchable-select.d.ts +0 -24
  113. package/dist/searchable-select.d.ts.map +0 -1
  114. package/dist/searchable-select.js +0 -61
  115. package/dist/searchable-select.js.map +0 -1
  116. package/dist/secret-input.d.ts +0 -8
  117. package/dist/secret-input.d.ts.map +0 -1
  118. package/dist/secret-input.js +0 -14
  119. package/dist/secret-input.js.map +0 -1
  120. package/dist/session.d.ts +0 -2
  121. package/dist/session.d.ts.map +0 -1
  122. package/dist/session.js +0 -2
  123. package/dist/session.js.map +0 -1
  124. package/dist/setup-wizard.d.ts +0 -11
  125. package/dist/setup-wizard.d.ts.map +0 -1
  126. package/dist/setup-wizard.js +0 -130
  127. package/dist/setup-wizard.js.map +0 -1
  128. package/dist/sqlite.d.ts.map +0 -1
  129. package/dist/sqlite.js.map +0 -1
  130. package/dist/supervisor.d.ts.map +0 -1
  131. package/dist/supervisor.js.map +0 -1
  132. package/dist/testkit.d.ts.map +0 -1
  133. package/dist/testkit.js.map +0 -1
  134. package/dist/tui-theme.d.ts +0 -16
  135. package/dist/tui-theme.d.ts.map +0 -1
  136. package/dist/tui-theme.js +0 -18
  137. package/dist/tui-theme.js.map +0 -1
  138. package/dist/tui.d.ts +0 -18
  139. package/dist/tui.d.ts.map +0 -1
  140. package/dist/tui.js +0 -583
  141. package/dist/tui.js.map +0 -1
  142. package/dist/update.d.ts +0 -15
  143. package/dist/update.d.ts.map +0 -1
  144. package/dist/update.js +0 -59
  145. package/dist/update.js.map +0 -1
  146. package/dist/web-console.d.ts +0 -33
  147. package/dist/web-console.d.ts.map +0 -1
  148. package/dist/web-console.js +0 -252
  149. package/dist/web-console.js.map +0 -1
  150. package/dist/welcome.d.ts +0 -30
  151. package/dist/welcome.d.ts.map +0 -1
  152. package/dist/welcome.js +0 -81
  153. package/dist/welcome.js.map +0 -1
  154. package/node_modules/goah-ledger-contract/dist/execution.d.ts +0 -402
  155. package/node_modules/goah-ledger-contract/dist/execution.d.ts.map +0 -1
  156. package/node_modules/goah-ledger-contract/dist/execution.js +0 -40
  157. package/node_modules/goah-ledger-contract/dist/execution.js.map +0 -1
  158. package/node_modules/goah-ledger-contract/dist/index.d.ts +0 -5
  159. package/node_modules/goah-ledger-contract/dist/index.d.ts.map +0 -1
  160. package/node_modules/goah-ledger-contract/dist/index.js +0 -5
  161. package/node_modules/goah-ledger-contract/dist/index.js.map +0 -1
  162. package/node_modules/goah-ledger-contract/dist/kernel.d.ts +0 -37
  163. package/node_modules/goah-ledger-contract/dist/kernel.d.ts.map +0 -1
  164. package/node_modules/goah-ledger-contract/dist/kernel.js +0 -8
  165. package/node_modules/goah-ledger-contract/dist/kernel.js.map +0 -1
  166. package/node_modules/goah-ledger-contract/dist/metrics.d.ts +0 -40
  167. package/node_modules/goah-ledger-contract/dist/metrics.d.ts.map +0 -1
  168. package/node_modules/goah-ledger-contract/dist/metrics.js +0 -25
  169. package/node_modules/goah-ledger-contract/dist/metrics.js.map +0 -1
  170. package/node_modules/goah-ledger-contract/dist/session.d.ts +0 -63
  171. package/node_modules/goah-ledger-contract/dist/session.d.ts.map +0 -1
  172. package/node_modules/goah-ledger-contract/dist/session.js +0 -115
  173. package/node_modules/goah-ledger-contract/dist/session.js.map +0 -1
  174. package/node_modules/goah-ledger-contract/package.json +0 -29
  175. package/node_modules/goah-ledger-sqlite/dist/index.d.ts +0 -77
  176. package/node_modules/goah-ledger-sqlite/dist/index.d.ts.map +0 -1
  177. package/node_modules/goah-ledger-sqlite/dist/index.js +0 -884
  178. package/node_modules/goah-ledger-sqlite/dist/index.js.map +0 -1
  179. package/node_modules/goah-ledger-sqlite/package.json +0 -26
  180. package/node_modules/goah-runner-pi/dist/configurator.d.ts +0 -20
  181. package/node_modules/goah-runner-pi/dist/configurator.d.ts.map +0 -1
  182. package/node_modules/goah-runner-pi/dist/configurator.js +0 -267
  183. package/node_modules/goah-runner-pi/dist/configurator.js.map +0 -1
  184. package/node_modules/goah-runner-pi/dist/credential-store.d.ts +0 -12
  185. package/node_modules/goah-runner-pi/dist/credential-store.d.ts.map +0 -1
  186. package/node_modules/goah-runner-pi/dist/credential-store.js +0 -69
  187. package/node_modules/goah-runner-pi/dist/credential-store.js.map +0 -1
  188. package/node_modules/goah-runner-pi/dist/env-spec.d.ts +0 -17
  189. package/node_modules/goah-runner-pi/dist/env-spec.d.ts.map +0 -1
  190. package/node_modules/goah-runner-pi/dist/env-spec.js +0 -95
  191. package/node_modules/goah-runner-pi/dist/env-spec.js.map +0 -1
  192. package/node_modules/goah-runner-pi/dist/index.d.ts +0 -64
  193. package/node_modules/goah-runner-pi/dist/index.d.ts.map +0 -1
  194. package/node_modules/goah-runner-pi/dist/index.js +0 -241
  195. package/node_modules/goah-runner-pi/dist/index.js.map +0 -1
  196. package/node_modules/goah-runner-pi/dist/model-provider.d.ts +0 -30
  197. package/node_modules/goah-runner-pi/dist/model-provider.d.ts.map +0 -1
  198. package/node_modules/goah-runner-pi/dist/model-provider.js +0 -96
  199. package/node_modules/goah-runner-pi/dist/model-provider.js.map +0 -1
  200. package/node_modules/goah-runner-pi/dist/pi-worker.d.ts +0 -29
  201. package/node_modules/goah-runner-pi/dist/pi-worker.d.ts.map +0 -1
  202. package/node_modules/goah-runner-pi/dist/pi-worker.js +0 -428
  203. package/node_modules/goah-runner-pi/dist/pi-worker.js.map +0 -1
  204. package/node_modules/goah-runner-pi/dist/test-helpers.d.ts +0 -4
  205. package/node_modules/goah-runner-pi/dist/test-helpers.d.ts.map +0 -1
  206. package/node_modules/goah-runner-pi/dist/test-helpers.js +0 -11
  207. package/node_modules/goah-runner-pi/dist/test-helpers.js.map +0 -1
  208. package/node_modules/goah-runner-pi/dist/verification-worker.d.ts +0 -2
  209. package/node_modules/goah-runner-pi/dist/verification-worker.d.ts.map +0 -1
  210. package/node_modules/goah-runner-pi/dist/verification-worker.js +0 -48
  211. package/node_modules/goah-runner-pi/dist/verification-worker.js.map +0 -1
  212. package/node_modules/goah-runner-pi/package.json +0 -28
  213. package/node_modules/goah-supervisor/dist/context-view.d.ts +0 -31
  214. package/node_modules/goah-supervisor/dist/context-view.d.ts.map +0 -1
  215. package/node_modules/goah-supervisor/dist/context-view.js +0 -71
  216. package/node_modules/goah-supervisor/dist/context-view.js.map +0 -1
  217. package/node_modules/goah-supervisor/dist/index.d.ts +0 -94
  218. package/node_modules/goah-supervisor/dist/index.d.ts.map +0 -1
  219. package/node_modules/goah-supervisor/dist/index.js +0 -888
  220. package/node_modules/goah-supervisor/dist/index.js.map +0 -1
  221. package/node_modules/goah-supervisor/dist/roles.d.ts +0 -3
  222. package/node_modules/goah-supervisor/dist/roles.d.ts.map +0 -1
  223. package/node_modules/goah-supervisor/dist/roles.js +0 -14
  224. package/node_modules/goah-supervisor/dist/roles.js.map +0 -1
  225. package/node_modules/goah-supervisor/dist/verification.d.ts +0 -82
  226. package/node_modules/goah-supervisor/dist/verification.d.ts.map +0 -1
  227. package/node_modules/goah-supervisor/dist/verification.js +0 -110
  228. package/node_modules/goah-supervisor/dist/verification.js.map +0 -1
  229. package/node_modules/goah-supervisor/package.json +0 -26
  230. package/node_modules/goah-testkit/dist/faux-runner-worker.d.ts +0 -2
  231. package/node_modules/goah-testkit/dist/faux-runner-worker.d.ts.map +0 -1
  232. package/node_modules/goah-testkit/dist/faux-runner-worker.js +0 -75
  233. package/node_modules/goah-testkit/dist/faux-runner-worker.js.map +0 -1
  234. package/node_modules/goah-testkit/dist/index.d.ts +0 -52
  235. package/node_modules/goah-testkit/dist/index.d.ts.map +0 -1
  236. package/node_modules/goah-testkit/dist/index.js +0 -113
  237. package/node_modules/goah-testkit/dist/index.js.map +0 -1
  238. package/node_modules/goah-testkit/dist/mock-connector-worker.d.ts +0 -2
  239. package/node_modules/goah-testkit/dist/mock-connector-worker.d.ts.map +0 -1
  240. package/node_modules/goah-testkit/dist/mock-connector-worker.js +0 -29
  241. package/node_modules/goah-testkit/dist/mock-connector-worker.js.map +0 -1
  242. package/node_modules/goah-testkit/package.json +0 -29
@@ -0,0 +1,1139 @@
1
+ import { createRequire as __goahCreateRequire } from "node:module";
2
+ const require = __goahCreateRequire(import.meta.url);
3
+ import {
4
+ buildCopilotDynamicHeaders,
5
+ hasCopilotVisionInput
6
+ } from "./chunk-JQD5EWJY.js";
7
+ import {
8
+ clampOpenAIPromptCacheKey
9
+ } from "./chunk-7AXAFDPG.js";
10
+ import {
11
+ shortHash
12
+ } from "./chunk-4US7ZHT3.js";
13
+ import {
14
+ OpenAI
15
+ } from "./chunk-LBKI23CC.js";
16
+ import {
17
+ formatProviderError,
18
+ normalizeProviderError
19
+ } from "./chunk-H462EFJP.js";
20
+ import {
21
+ MIN_ANSWER_TOKENS,
22
+ appendGrammarToolInputJsonDelta,
23
+ buildBaseOptions,
24
+ clampReasoning,
25
+ createGrammarToolInputProperties,
26
+ getGrammarToolInput,
27
+ getJsonSchemaToolParameters,
28
+ resolveGrammarConstrainedSampling,
29
+ resolveJsonSchemaStrictSampling,
30
+ transformMessages
31
+ } from "./chunk-BXA47DTF.js";
32
+ import {
33
+ retryProviderRequest
34
+ } from "./chunk-4M6TXTT5.js";
35
+ import {
36
+ sanitizeSurrogates
37
+ } from "./chunk-NRLGWZJC.js";
38
+ import {
39
+ headersToRecord
40
+ } from "./chunk-FSBUS2BI.js";
41
+ import {
42
+ getProviderEnvValue
43
+ } from "./chunk-IIJQ3DW4.js";
44
+ import {
45
+ parseStreamingJson
46
+ } from "./chunk-2ZP2NBW3.js";
47
+ import {
48
+ calculateCost,
49
+ clampThinkingLevel
50
+ } from "./chunk-MPXK7QBL.js";
51
+ import {
52
+ AssistantMessageEventStream
53
+ } from "./chunk-2QBQZGXF.js";
54
+ import "./chunk-XPQKM3L7.js";
55
+
56
+ // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js
57
+ function hasHeader(headers, name) {
58
+ if (!headers)
59
+ return false;
60
+ const expected = name.toLowerCase();
61
+ for (const [key, value] of Object.entries(headers)) {
62
+ if (key.toLowerCase() === expected && value !== null && value.trim().length > 0)
63
+ return true;
64
+ }
65
+ return false;
66
+ }
67
+ function getClientApiKey(provider, apiKey, headers) {
68
+ if (apiKey)
69
+ return apiKey;
70
+ if (hasHeader(headers, "authorization") || hasHeader(headers, "cf-aig-authorization"))
71
+ return "unused";
72
+ throw new Error(`No API key for provider: ${provider}`);
73
+ }
74
+ function hasToolHistory(messages) {
75
+ for (const msg of messages) {
76
+ if (msg.role === "toolResult") {
77
+ return true;
78
+ }
79
+ if (msg.role === "assistant") {
80
+ if (msg.content.some((block) => block.type === "toolCall")) {
81
+ return true;
82
+ }
83
+ }
84
+ }
85
+ return false;
86
+ }
87
+ function getDeferredToolNames(messages) {
88
+ const names = /* @__PURE__ */ new Set();
89
+ for (const message of messages) {
90
+ if (message.role === "toolResult") {
91
+ for (const name of message.addedToolNames ?? []) {
92
+ names.add(name);
93
+ }
94
+ }
95
+ }
96
+ return names;
97
+ }
98
+ function getToolsByName(tools, names) {
99
+ if (!tools)
100
+ return [];
101
+ const toolsByName = new Map(tools.map((tool) => [tool.name, tool]));
102
+ return Array.from(names).map((name) => toolsByName.get(name)).filter((tool) => tool !== void 0);
103
+ }
104
+ function isTextContentBlock(block) {
105
+ return block.type === "text";
106
+ }
107
+ function isThinkingContentBlock(block) {
108
+ return block.type === "thinking";
109
+ }
110
+ function isToolCallBlock(block) {
111
+ return block.type === "toolCall";
112
+ }
113
+ function isImageContentBlock(block) {
114
+ return block.type === "image";
115
+ }
116
+ function isEncryptedReasoningDetail(detail) {
117
+ if (typeof detail !== "object" || detail === null) {
118
+ return false;
119
+ }
120
+ const candidate = detail;
121
+ return candidate.type === "reasoning.encrypted" && typeof candidate.id === "string" && candidate.id.length > 0 && typeof candidate.data === "string" && candidate.data.length > 0;
122
+ }
123
+ function resolveCacheRetention(cacheRetention, env) {
124
+ if (cacheRetention) {
125
+ return cacheRetention;
126
+ }
127
+ if (getProviderEnvValue("PI_CACHE_RETENTION", env) === "long") {
128
+ return "long";
129
+ }
130
+ return "short";
131
+ }
132
+ var stream = (model, context, options) => {
133
+ const stream2 = new AssistantMessageEventStream();
134
+ (async () => {
135
+ const output = {
136
+ role: "assistant",
137
+ content: [],
138
+ api: model.api,
139
+ provider: model.provider,
140
+ model: model.id,
141
+ usage: {
142
+ input: 0,
143
+ output: 0,
144
+ cacheRead: 0,
145
+ cacheWrite: 0,
146
+ totalTokens: 0,
147
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
148
+ },
149
+ stopReason: "pending",
150
+ timestamp: Date.now()
151
+ };
152
+ try {
153
+ const apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers);
154
+ const compat = getCompat(model);
155
+ const grammarToolInputProperties = createGrammarToolInputProperties(context.tools, compat.supportsOpenAIGrammarTools);
156
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
157
+ const cacheSessionId = cacheRetention === "none" ? void 0 : options?.sessionId;
158
+ const client = createClient(model, context, apiKey, options?.headers, options?.fetch, cacheSessionId, compat);
159
+ let params = buildParams(model, context, options, compat, cacheRetention, grammarToolInputProperties);
160
+ const nextParams = await options?.onPayload?.(params, model);
161
+ if (nextParams !== void 0) {
162
+ params = nextParams;
163
+ }
164
+ const requestOptions = {
165
+ ...options?.signal ? { signal: options.signal } : {},
166
+ ...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
167
+ maxRetries: 0
168
+ };
169
+ const { data: openaiStream, response } = await retryProviderRequest(() => client.chat.completions.create(params, requestOptions).withResponse(), {
170
+ maxRetries: options?.maxRetries,
171
+ maxRetryDelayMs: options?.maxRetryDelayMs,
172
+ signal: options?.signal
173
+ });
174
+ await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
175
+ stream2.push({ type: "start", partial: output });
176
+ let textBlock = null;
177
+ let thinkingBlock = null;
178
+ let hasFinishReason = false;
179
+ const toolCallBlocksByIndex = /* @__PURE__ */ new Map();
180
+ const toolCallBlocksById = /* @__PURE__ */ new Map();
181
+ const pendingReasoningDetailsByToolCallId = /* @__PURE__ */ new Map();
182
+ const blocks = output.content;
183
+ const getContentIndex = (block) => blocks.indexOf(block);
184
+ const getCustomToolCallInput = (block) => {
185
+ const property = block.customInput?.property;
186
+ if (property === void 0)
187
+ return "";
188
+ const value = block.arguments[property];
189
+ return typeof value === "string" ? value : "";
190
+ };
191
+ const appendCustomToolCallInput = (block, nextInput, close) => {
192
+ const customInput = block.customInput;
193
+ if (!customInput)
194
+ return void 0;
195
+ const delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);
196
+ block.arguments = { [customInput.property]: nextInput };
197
+ return delta;
198
+ };
199
+ const finishBlock = (block) => {
200
+ const contentIndex = getContentIndex(block);
201
+ if (contentIndex === -1) {
202
+ return;
203
+ }
204
+ if (block.type === "text") {
205
+ stream2.push({
206
+ type: "text_end",
207
+ contentIndex,
208
+ content: block.text,
209
+ partial: output
210
+ });
211
+ } else if (block.type === "thinking") {
212
+ stream2.push({
213
+ type: "thinking_end",
214
+ contentIndex,
215
+ content: block.thinking,
216
+ partial: output
217
+ });
218
+ } else if (block.type === "toolCall") {
219
+ if (block.customInput) {
220
+ const delta = appendCustomToolCallInput(block, getCustomToolCallInput(block), true);
221
+ if (delta !== void 0) {
222
+ stream2.push({
223
+ type: "toolcall_delta",
224
+ contentIndex,
225
+ delta,
226
+ partial: output
227
+ });
228
+ }
229
+ } else {
230
+ block.arguments = parseStreamingJson(block.partialArgs);
231
+ }
232
+ delete block.partialArgs;
233
+ delete block.customInput;
234
+ delete block.streamIndex;
235
+ stream2.push({
236
+ type: "toolcall_end",
237
+ contentIndex,
238
+ toolCall: block,
239
+ partial: output
240
+ });
241
+ }
242
+ };
243
+ const ensureTextBlock = () => {
244
+ if (!textBlock) {
245
+ textBlock = { type: "text", text: "" };
246
+ blocks.push(textBlock);
247
+ stream2.push({ type: "text_start", contentIndex: getContentIndex(textBlock), partial: output });
248
+ }
249
+ return textBlock;
250
+ };
251
+ const ensureThinkingBlock = (thinkingSignature) => {
252
+ if (!thinkingBlock) {
253
+ thinkingBlock = {
254
+ type: "thinking",
255
+ thinking: "",
256
+ thinkingSignature
257
+ };
258
+ blocks.push(thinkingBlock);
259
+ stream2.push({ type: "thinking_start", contentIndex: getContentIndex(thinkingBlock), partial: output });
260
+ }
261
+ return thinkingBlock;
262
+ };
263
+ const applyPendingReasoningDetail = (block) => {
264
+ if (!block.id) {
265
+ return;
266
+ }
267
+ const pendingReasoningDetail = pendingReasoningDetailsByToolCallId.get(block.id);
268
+ if (pendingReasoningDetail) {
269
+ block.thoughtSignature = pendingReasoningDetail;
270
+ pendingReasoningDetailsByToolCallId.delete(block.id);
271
+ }
272
+ };
273
+ const ensureToolCallBlock = (toolCall) => {
274
+ const streamIndex = typeof toolCall.index === "number" ? toolCall.index : void 0;
275
+ const name = toolCall.function?.name ?? toolCall.custom?.name ?? "";
276
+ let block = streamIndex !== void 0 ? toolCallBlocksByIndex.get(streamIndex) : void 0;
277
+ if (!block && toolCall.id) {
278
+ block = toolCallBlocksById.get(toolCall.id);
279
+ }
280
+ if (!block) {
281
+ const customInputProperty = toolCall.custom && !toolCall.function ? grammarToolInputProperties.get(name) ?? "input" : void 0;
282
+ const hasCustomInput = customInputProperty !== void 0;
283
+ block = {
284
+ type: "toolCall",
285
+ id: toolCall.id || "",
286
+ name,
287
+ arguments: hasCustomInput ? { [customInputProperty]: "" } : {},
288
+ partialArgs: hasCustomInput ? void 0 : "",
289
+ customInput: hasCustomInput ? { property: customInputProperty, jsonBuffer: { input: "", started: false, closed: false } } : void 0,
290
+ streamIndex
291
+ };
292
+ if (streamIndex !== void 0) {
293
+ toolCallBlocksByIndex.set(streamIndex, block);
294
+ }
295
+ if (toolCall.id) {
296
+ toolCallBlocksById.set(toolCall.id, block);
297
+ }
298
+ blocks.push(block);
299
+ stream2.push({
300
+ type: "toolcall_start",
301
+ contentIndex: getContentIndex(block),
302
+ partial: output
303
+ });
304
+ }
305
+ if (streamIndex !== void 0 && block.streamIndex === void 0) {
306
+ block.streamIndex = streamIndex;
307
+ toolCallBlocksByIndex.set(streamIndex, block);
308
+ }
309
+ if (toolCall.id) {
310
+ toolCallBlocksById.set(toolCall.id, block);
311
+ }
312
+ if (!block.name && name) {
313
+ block.name = name;
314
+ }
315
+ if (toolCall.custom && !toolCall.function && !block.customInput) {
316
+ const customInputProperty = grammarToolInputProperties.get(block.name) ?? "input";
317
+ block.arguments = { [customInputProperty]: "" };
318
+ block.customInput = {
319
+ property: customInputProperty,
320
+ jsonBuffer: { input: "", started: false, closed: false }
321
+ };
322
+ delete block.partialArgs;
323
+ }
324
+ applyPendingReasoningDetail(block);
325
+ return block;
326
+ };
327
+ for await (const chunk of openaiStream) {
328
+ if (!chunk || typeof chunk !== "object")
329
+ continue;
330
+ output.responseId ||= chunk.id;
331
+ if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) {
332
+ output.responseModel ||= chunk.model;
333
+ }
334
+ if (chunk.usage) {
335
+ output.usage = parseChunkUsage(chunk.usage, model);
336
+ }
337
+ const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : void 0;
338
+ if (!choice)
339
+ continue;
340
+ if (!chunk.usage && choice.usage) {
341
+ output.usage = parseChunkUsage(choice.usage, model);
342
+ }
343
+ if (choice.finish_reason) {
344
+ output.rawStopReason = choice.finish_reason;
345
+ const finishReasonResult = mapStopReason(choice.finish_reason);
346
+ output.stopReason = finishReasonResult.stopReason;
347
+ if (finishReasonResult.errorMessage) {
348
+ output.errorMessage = finishReasonResult.errorMessage;
349
+ }
350
+ hasFinishReason = true;
351
+ }
352
+ if (choice.delta) {
353
+ if (choice.delta.content !== null && choice.delta.content !== void 0 && choice.delta.content.length > 0) {
354
+ const block = ensureTextBlock();
355
+ block.text += choice.delta.content;
356
+ stream2.push({
357
+ type: "text_delta",
358
+ contentIndex: getContentIndex(block),
359
+ delta: choice.delta.content,
360
+ partial: output
361
+ });
362
+ }
363
+ const reasoningFields = ["reasoning_content", "reasoning", "reasoning_text"];
364
+ const deltaFields = choice.delta;
365
+ let foundReasoningField = null;
366
+ for (const field of reasoningFields) {
367
+ const value = deltaFields[field];
368
+ if (typeof value === "string" && value.length > 0) {
369
+ foundReasoningField = field;
370
+ break;
371
+ }
372
+ }
373
+ if (foundReasoningField) {
374
+ const delta = deltaFields[foundReasoningField];
375
+ if (typeof delta === "string" && delta.length > 0) {
376
+ const thinkingSignature = model.provider === "opencode-go" && foundReasoningField === "reasoning" ? "reasoning_content" : foundReasoningField;
377
+ const block = ensureThinkingBlock(thinkingSignature);
378
+ block.thinking += delta;
379
+ stream2.push({
380
+ type: "thinking_delta",
381
+ contentIndex: getContentIndex(block),
382
+ delta,
383
+ partial: output
384
+ });
385
+ }
386
+ }
387
+ if (choice?.delta?.tool_calls) {
388
+ for (const toolCall of choice.delta.tool_calls) {
389
+ const block = ensureToolCallBlock(toolCall);
390
+ if (!block.id && toolCall.id) {
391
+ block.id = toolCall.id;
392
+ toolCallBlocksById.set(toolCall.id, block);
393
+ }
394
+ const name = toolCall.function?.name ?? toolCall.custom?.name;
395
+ if (!block.name && name) {
396
+ block.name = name;
397
+ }
398
+ let delta = "";
399
+ if (toolCall.function?.arguments) {
400
+ delta = toolCall.function.arguments;
401
+ block.partialArgs = (block.partialArgs ?? "") + toolCall.function.arguments;
402
+ block.arguments = parseStreamingJson(block.partialArgs);
403
+ } else if (toolCall.custom?.input) {
404
+ const nextInput = getCustomToolCallInput(block) + toolCall.custom.input;
405
+ delta = appendCustomToolCallInput(block, nextInput, false) ?? "";
406
+ }
407
+ stream2.push({
408
+ type: "toolcall_delta",
409
+ contentIndex: getContentIndex(block),
410
+ delta,
411
+ partial: output
412
+ });
413
+ }
414
+ }
415
+ const reasoningDetails = choice.delta.reasoning_details;
416
+ if (Array.isArray(reasoningDetails)) {
417
+ for (const detail of reasoningDetails) {
418
+ if (isEncryptedReasoningDetail(detail)) {
419
+ const serializedDetail = JSON.stringify(detail);
420
+ const matchingToolCall = toolCallBlocksById.get(detail.id);
421
+ if (matchingToolCall) {
422
+ matchingToolCall.thoughtSignature = serializedDetail;
423
+ } else {
424
+ pendingReasoningDetailsByToolCallId.set(detail.id, serializedDetail);
425
+ }
426
+ }
427
+ }
428
+ }
429
+ }
430
+ }
431
+ for (const block of blocks) {
432
+ finishBlock(block);
433
+ }
434
+ if (options?.signal?.aborted) {
435
+ throw new Error("Request was aborted");
436
+ }
437
+ if (output.stopReason === "aborted") {
438
+ throw new Error("Request was aborted");
439
+ }
440
+ if (!hasFinishReason && !compat.supportsFinishReason) {
441
+ output.stopReason = output.content.some((block) => block.type === "toolCall") ? "toolUse" : "stop";
442
+ }
443
+ if (output.stopReason === "error") {
444
+ throw new Error(output.errorMessage || "Provider returned an error stop reason");
445
+ }
446
+ if (compat.supportsFinishReason && !hasFinishReason || output.stopReason === "pending") {
447
+ throw new Error("Stream ended without finish_reason");
448
+ }
449
+ stream2.push({ type: "done", reason: output.stopReason, message: output });
450
+ stream2.end();
451
+ } catch (error) {
452
+ for (const block of output.content) {
453
+ delete block.index;
454
+ delete block.partialArgs;
455
+ delete block.customInput;
456
+ delete block.streamIndex;
457
+ }
458
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
459
+ output.errorMessage = formatProviderError(normalizeProviderError(error));
460
+ const rawMetadata = error?.error?.metadata?.raw;
461
+ if (rawMetadata && !output.errorMessage.includes(String(rawMetadata))) {
462
+ output.errorMessage += `
463
+ ${rawMetadata}`;
464
+ }
465
+ stream2.push({ type: "error", reason: output.stopReason, error: output });
466
+ stream2.end();
467
+ }
468
+ })();
469
+ return stream2;
470
+ };
471
+ var streamSimple = (model, context, options) => {
472
+ getClientApiKey(model.provider, options?.apiKey, options?.headers);
473
+ const base = buildBaseOptions(model, context, options, options?.apiKey);
474
+ const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : void 0;
475
+ const reasoningEffort = clampedReasoning === "off" ? void 0 : clampedReasoning;
476
+ const toolChoice = options?.toolChoice;
477
+ return stream(model, context, {
478
+ ...base,
479
+ reasoningEffort,
480
+ toolChoice,
481
+ thinkingBudgets: options?.thinkingBudgets
482
+ });
483
+ };
484
+ function createClient(model, context, apiKey, optionsHeaders, fetch, sessionId, compat = getCompat(model)) {
485
+ const headers = { ...model.headers };
486
+ if (model.provider === "github-copilot") {
487
+ const hasImages = hasCopilotVisionInput(context.messages);
488
+ const copilotHeaders = buildCopilotDynamicHeaders({
489
+ messages: context.messages,
490
+ hasImages
491
+ });
492
+ Object.assign(headers, copilotHeaders);
493
+ }
494
+ if (sessionId && compat.sendSessionAffinityHeaders) {
495
+ if (compat.sessionAffinityFormat === "openrouter") {
496
+ headers["x-session-id"] = sessionId;
497
+ } else {
498
+ if (compat.sessionAffinityFormat === "openai") {
499
+ headers.session_id = sessionId;
500
+ }
501
+ headers["x-client-request-id"] = sessionId;
502
+ headers["x-session-affinity"] = sessionId;
503
+ }
504
+ }
505
+ if (optionsHeaders) {
506
+ Object.assign(headers, optionsHeaders);
507
+ }
508
+ return new OpenAI({
509
+ apiKey,
510
+ baseURL: model.baseUrl,
511
+ dangerouslyAllowBrowser: true,
512
+ fetch,
513
+ defaultHeaders: headers
514
+ });
515
+ }
516
+ function buildParams(model, context, options, compat = getCompat(model), cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env), grammarToolInputProperties = createGrammarToolInputProperties(context.tools, compat.supportsOpenAIGrammarTools)) {
517
+ const messages = convertMessages(model, context, compat, { grammarToolInputProperties });
518
+ const cacheControl = getCompatCacheControl(compat, cacheRetention);
519
+ const params = {
520
+ model: model.id,
521
+ messages,
522
+ stream: true,
523
+ prompt_cache_key: model.baseUrl.includes("api.openai.com") && cacheRetention !== "none" || cacheRetention === "long" && compat.supportsLongCacheRetention ? clampOpenAIPromptCacheKey(options?.sessionId) : void 0,
524
+ prompt_cache_retention: cacheRetention === "long" && compat.supportsLongCacheRetention ? "24h" : void 0
525
+ };
526
+ if (compat.supportsUsageInStreaming !== false) {
527
+ params.stream_options = { include_usage: true };
528
+ }
529
+ if (compat.supportsStore) {
530
+ params.store = false;
531
+ }
532
+ if (options?.maxTokens) {
533
+ if (compat.maxTokensField === "max_tokens") {
534
+ params.max_tokens = options.maxTokens;
535
+ } else {
536
+ params.max_completion_tokens = options.maxTokens;
537
+ }
538
+ }
539
+ if (options?.temperature !== void 0) {
540
+ params.temperature = options.temperature;
541
+ }
542
+ const deferredToolNames = compat.deferredToolsMode === "kimi" ? getDeferredToolNames(context.messages) : /* @__PURE__ */ new Set();
543
+ const activeTools = context.tools?.filter((tool) => !deferredToolNames.has(tool.name));
544
+ if (activeTools && activeTools.length > 0) {
545
+ params.tools = convertTools(activeTools, compat);
546
+ if (compat.zaiToolStream) {
547
+ params.tool_stream = true;
548
+ }
549
+ } else if (hasToolHistory(context.messages)) {
550
+ params.tools = [];
551
+ }
552
+ if (cacheControl) {
553
+ applyAnthropicCacheControl(messages, params.tools, cacheControl);
554
+ }
555
+ if (options?.toolChoice) {
556
+ params.tool_choice = options.toolChoice;
557
+ }
558
+ if (compat.thinkingFormat === "zai" && model.reasoning) {
559
+ const zaiParams = params;
560
+ zaiParams.thinking = options?.reasoningEffort ? { type: "enabled", clear_thinking: false } : { type: "disabled" };
561
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) {
562
+ const mappedEffort = model.thinkingLevelMap?.[options.reasoningEffort];
563
+ const effort = mappedEffort === void 0 ? options.reasoningEffort : mappedEffort;
564
+ if (typeof effort === "string") {
565
+ zaiParams.reasoning_effort = effort;
566
+ }
567
+ }
568
+ } else if (compat.thinkingFormat === "qwen" && model.reasoning) {
569
+ params.enable_thinking = !!options?.reasoningEffort;
570
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) {
571
+ const effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
572
+ if (typeof effort === "string") {
573
+ params.reasoning_effort = effort;
574
+ }
575
+ }
576
+ } else if (compat.thinkingFormat === "qwen-chat-template" && model.reasoning) {
577
+ params.chat_template_kwargs = {
578
+ enable_thinking: !!options?.reasoningEffort,
579
+ preserve_thinking: true
580
+ };
581
+ } else if (compat.thinkingFormat === "chat-template" && model.reasoning) {
582
+ const chatTemplateKwargs = buildChatTemplateValues(model, options, compat.chatTemplateKwargs);
583
+ if (chatTemplateKwargs) {
584
+ params.chat_template_kwargs = chatTemplateKwargs;
585
+ }
586
+ } else if (compat.thinkingFormat === "baseten" && model.reasoning) {
587
+ const basetenParams = params;
588
+ const chatTemplateArgs = buildChatTemplateValues(model, options, compat.chatTemplateArgs);
589
+ if (chatTemplateArgs) {
590
+ basetenParams.chat_template_args = chatTemplateArgs;
591
+ }
592
+ if (compat.supportsReasoningEffort) {
593
+ const requestedEffort = options?.reasoningEffort;
594
+ const mappedEffort = requestedEffort ? model.thinkingLevelMap?.[requestedEffort] : model.thinkingLevelMap?.off;
595
+ const effort = mappedEffort === void 0 ? requestedEffort : mappedEffort;
596
+ if (typeof effort === "string") {
597
+ basetenParams.reasoning_effort = effort;
598
+ }
599
+ }
600
+ } else if (compat.thinkingFormat === "deepseek" && model.reasoning) {
601
+ if (options?.reasoningEffort) {
602
+ params.thinking = { type: "enabled" };
603
+ } else if (model.thinkingLevelMap?.off !== null) {
604
+ params.thinking = { type: "disabled" };
605
+ }
606
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) {
607
+ params.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
608
+ }
609
+ } else if (compat.thinkingFormat === "openrouter" && model.reasoning) {
610
+ const openRouterParams = params;
611
+ if (options?.reasoningEffort) {
612
+ openRouterParams.reasoning = {
613
+ effort: model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort
614
+ };
615
+ } else if (model.thinkingLevelMap?.off !== null) {
616
+ openRouterParams.reasoning = { effort: model.thinkingLevelMap?.off ?? "none" };
617
+ }
618
+ } else if (compat.thinkingFormat === "ant-ling" && model.reasoning && options?.reasoningEffort) {
619
+ const effort = model.thinkingLevelMap?.[options.reasoningEffort];
620
+ if (typeof effort === "string") {
621
+ params.reasoning = { effort };
622
+ }
623
+ } else if (compat.thinkingFormat === "together" && model.reasoning) {
624
+ const togetherParams = params;
625
+ togetherParams.reasoning = { enabled: !!options?.reasoningEffort };
626
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) {
627
+ togetherParams.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
628
+ }
629
+ } else if (compat.thinkingFormat === "string-thinking" && model.reasoning) {
630
+ const stringThinkingParams = params;
631
+ if (options?.reasoningEffort) {
632
+ stringThinkingParams.thinking = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
633
+ } else if (model.thinkingLevelMap?.off !== null) {
634
+ stringThinkingParams.thinking = model.thinkingLevelMap?.off ?? "none";
635
+ }
636
+ } else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
637
+ params.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
638
+ } else if (!options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
639
+ const offValue = model.thinkingLevelMap?.off;
640
+ if (typeof offValue === "string") {
641
+ params.reasoning_effort = offValue;
642
+ }
643
+ }
644
+ if (compat.supportsThinkingTokenBudget && options?.reasoningEffort && model.reasoning) {
645
+ const level = clampReasoning(options.reasoningEffort);
646
+ const budgets = {
647
+ minimal: 1024,
648
+ low: 2048,
649
+ medium: 8192,
650
+ high: 16384,
651
+ ...options.thinkingBudgets
652
+ };
653
+ const ceiling = params.max_tokens ?? params.max_completion_tokens ?? model.maxTokens;
654
+ const budget = Math.min(budgets[level], Math.max(0, ceiling - MIN_ANSWER_TOKENS));
655
+ if (budget > 0) {
656
+ params.thinking_token_budget = budget;
657
+ }
658
+ }
659
+ if (model.compat?.openRouterRouting) {
660
+ params.provider = model.compat.openRouterRouting;
661
+ }
662
+ if (model.compat?.vercelGatewayRouting) {
663
+ const routing = model.compat.vercelGatewayRouting;
664
+ if (routing.only || routing.order) {
665
+ const gatewayOptions = {};
666
+ if (routing.only)
667
+ gatewayOptions.only = routing.only;
668
+ if (routing.order)
669
+ gatewayOptions.order = routing.order;
670
+ params.providerOptions = { gateway: gatewayOptions };
671
+ }
672
+ }
673
+ if (options?.samplingParams) {
674
+ Object.assign(params, options.samplingParams);
675
+ }
676
+ return params;
677
+ }
678
+ function buildChatTemplateValues(model, options, values) {
679
+ const resolvedValues = {};
680
+ for (const [key, value] of Object.entries(values)) {
681
+ const resolved = resolveChatTemplateKwargValue(model, options, value);
682
+ if (resolved !== void 0) {
683
+ resolvedValues[key] = resolved;
684
+ }
685
+ }
686
+ return Object.keys(resolvedValues).length > 0 ? resolvedValues : void 0;
687
+ }
688
+ function resolveChatTemplateKwargValue(model, options, value) {
689
+ if (typeof value !== "object" || value === null) {
690
+ return value;
691
+ }
692
+ const reasoningEffort = options?.reasoningEffort;
693
+ if (!reasoningEffort && value.omitWhenOff) {
694
+ return void 0;
695
+ }
696
+ if (value.$var === "thinking.enabled") {
697
+ return !!reasoningEffort;
698
+ }
699
+ const mappedValue = reasoningEffort ? model.thinkingLevelMap?.[reasoningEffort] : model.thinkingLevelMap?.off;
700
+ return mappedValue === void 0 ? reasoningEffort : typeof mappedValue === "string" ? mappedValue : void 0;
701
+ }
702
+ function getCompatCacheControl(compat, cacheRetention) {
703
+ if (compat.cacheControlFormat !== "anthropic" || cacheRetention === "none") {
704
+ return void 0;
705
+ }
706
+ const ttl = cacheRetention === "long" && compat.supportsLongCacheRetention ? "1h" : void 0;
707
+ return { type: "ephemeral", ...ttl ? { ttl } : {} };
708
+ }
709
+ function applyAnthropicCacheControl(messages, tools, cacheControl) {
710
+ addCacheControlToSystemPrompt(messages, cacheControl);
711
+ addCacheControlToLastTool(tools, cacheControl);
712
+ addCacheControlToLastConversationMessage(messages, cacheControl);
713
+ }
714
+ function addCacheControlToSystemPrompt(messages, cacheControl) {
715
+ for (const message of messages) {
716
+ if (message.role === "system" || message.role === "developer") {
717
+ addCacheControlToInstructionMessage(message, cacheControl);
718
+ return;
719
+ }
720
+ }
721
+ }
722
+ function addCacheControlToLastConversationMessage(messages, cacheControl) {
723
+ for (let i = messages.length - 1; i >= 0; i--) {
724
+ const message = messages[i];
725
+ if (message.role === "user" || message.role === "assistant" || message.role === "tool") {
726
+ if (addCacheControlToMessage(message, cacheControl)) {
727
+ return;
728
+ }
729
+ }
730
+ }
731
+ }
732
+ function addCacheControlToLastTool(tools, cacheControl) {
733
+ if (!tools || tools.length === 0) {
734
+ return;
735
+ }
736
+ const lastTool = tools[tools.length - 1];
737
+ lastTool.cache_control = cacheControl;
738
+ }
739
+ function addCacheControlToInstructionMessage(message, cacheControl) {
740
+ return addCacheControlToTextContent(message, cacheControl);
741
+ }
742
+ function addCacheControlToMessage(message, cacheControl) {
743
+ if (message.role === "user" || message.role === "assistant" || message.role === "tool") {
744
+ return addCacheControlToTextContent(message, cacheControl);
745
+ }
746
+ return false;
747
+ }
748
+ function addCacheControlToTextContent(message, cacheControl) {
749
+ const content = message.content;
750
+ if (typeof content === "string") {
751
+ if (content.length === 0) {
752
+ return false;
753
+ }
754
+ message.content = [
755
+ {
756
+ type: "text",
757
+ text: content,
758
+ cache_control: cacheControl
759
+ }
760
+ ];
761
+ return true;
762
+ }
763
+ if (!Array.isArray(content)) {
764
+ return false;
765
+ }
766
+ for (let i = content.length - 1; i >= 0; i--) {
767
+ const part = content[i];
768
+ if (part?.type === "text") {
769
+ const textPart = part;
770
+ textPart.cache_control = cacheControl;
771
+ return true;
772
+ }
773
+ }
774
+ return false;
775
+ }
776
+ function convertMessages(model, context, compat, options) {
777
+ const params = [];
778
+ const normalizeToolCallId = (id) => {
779
+ if (id.includes("|")) {
780
+ const separatorIndex = id.indexOf("|");
781
+ const callId = id.slice(0, separatorIndex).replace(/[^a-zA-Z0-9_-]/g, "_");
782
+ const itemId = id.slice(separatorIndex + 1).replace(/[^a-zA-Z0-9_-]/g, "_");
783
+ const combinedId = itemId.length > 0 ? `${callId}_${itemId}` : callId;
784
+ if (combinedId.length <= 40) {
785
+ return combinedId;
786
+ }
787
+ const hash = shortHash(id).slice(0, 8);
788
+ const prefix = callId.slice(0, Math.max(1, 40 - hash.length - 1));
789
+ return `${prefix}_${hash}`;
790
+ }
791
+ if (model.provider === "openai")
792
+ return id.length > 40 ? id.slice(0, 40) : id;
793
+ return id;
794
+ };
795
+ const transformedMessages = transformMessages(context.messages, model, (id) => normalizeToolCallId(id));
796
+ if (context.systemPrompt) {
797
+ const useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;
798
+ const role = useDeveloperRole ? "developer" : "system";
799
+ params.push({ role, content: sanitizeSurrogates(context.systemPrompt) });
800
+ }
801
+ let lastRole = null;
802
+ for (let i = 0; i < transformedMessages.length; i++) {
803
+ const msg = transformedMessages[i];
804
+ if (compat.requiresAssistantAfterToolResult && lastRole === "toolResult" && msg.role === "user") {
805
+ params.push({
806
+ role: "assistant",
807
+ content: "I have processed the tool results."
808
+ });
809
+ }
810
+ if (msg.role === "user") {
811
+ if (typeof msg.content === "string") {
812
+ params.push({
813
+ role: "user",
814
+ content: sanitizeSurrogates(msg.content)
815
+ });
816
+ } else {
817
+ const content = msg.content.map((item) => {
818
+ if (item.type === "text") {
819
+ return {
820
+ type: "text",
821
+ text: sanitizeSurrogates(item.text)
822
+ };
823
+ } else {
824
+ return {
825
+ type: "image_url",
826
+ image_url: {
827
+ url: `data:${item.mimeType};base64,${item.data}`
828
+ }
829
+ };
830
+ }
831
+ });
832
+ if (content.length === 0)
833
+ continue;
834
+ params.push({
835
+ role: "user",
836
+ content
837
+ });
838
+ }
839
+ } else if (msg.role === "assistant") {
840
+ const assistantMsg = {
841
+ role: "assistant",
842
+ content: compat.requiresAssistantAfterToolResult ? "" : null
843
+ };
844
+ const assistantTextParts = msg.content.filter(isTextContentBlock).filter((block) => block.text.trim().length > 0).map((block) => ({
845
+ type: "text",
846
+ text: sanitizeSurrogates(block.text)
847
+ }));
848
+ const assistantText = assistantTextParts.map((part) => part.text).join("");
849
+ const nonEmptyThinkingBlocks = msg.content.filter(isThinkingContentBlock).filter((block) => block.thinking.trim().length > 0);
850
+ if (nonEmptyThinkingBlocks.length > 0) {
851
+ if (compat.requiresThinkingAsText) {
852
+ const thinkingText = nonEmptyThinkingBlocks.map((block) => sanitizeSurrogates(block.thinking)).join("\n\n");
853
+ assistantMsg.content = [{ type: "text", text: thinkingText }, ...assistantTextParts];
854
+ } else {
855
+ if (assistantText.length > 0) {
856
+ assistantMsg.content = assistantText;
857
+ }
858
+ let signature = nonEmptyThinkingBlocks[0].thinkingSignature;
859
+ if (model.provider === "opencode-go" && signature === "reasoning") {
860
+ signature = "reasoning_content";
861
+ }
862
+ if (signature && signature.length > 0) {
863
+ assistantMsg[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join("\n");
864
+ }
865
+ }
866
+ } else if (assistantText.length > 0) {
867
+ assistantMsg.content = assistantText;
868
+ }
869
+ const toolCalls = msg.content.filter(isToolCallBlock);
870
+ if (toolCalls.length > 0) {
871
+ assistantMsg.tool_calls = toolCalls.map((tc) => {
872
+ const customInputProperty = options?.grammarToolInputProperties?.get(tc.name);
873
+ if (customInputProperty !== void 0) {
874
+ return {
875
+ id: tc.id,
876
+ type: "custom",
877
+ custom: {
878
+ name: tc.name,
879
+ input: sanitizeSurrogates(getGrammarToolInput(tc.name, tc.arguments, customInputProperty))
880
+ }
881
+ };
882
+ }
883
+ return {
884
+ id: tc.id,
885
+ type: "function",
886
+ function: {
887
+ name: tc.name,
888
+ arguments: JSON.stringify(tc.arguments)
889
+ }
890
+ };
891
+ });
892
+ const reasoningDetails = toolCalls.filter((tc) => tc.thoughtSignature).map((tc) => {
893
+ try {
894
+ return JSON.parse(tc.thoughtSignature);
895
+ } catch {
896
+ return null;
897
+ }
898
+ }).filter(Boolean);
899
+ if (reasoningDetails.length > 0) {
900
+ assistantMsg.reasoning_details = reasoningDetails;
901
+ }
902
+ }
903
+ if (compat.requiresReasoningContentOnAssistantMessages && model.reasoning && assistantMsg.reasoning_content === void 0) {
904
+ assistantMsg.reasoning_content = "";
905
+ }
906
+ const content = assistantMsg.content;
907
+ const hasContent = content !== null && content !== void 0 && (typeof content === "string" ? content.length > 0 : content.length > 0);
908
+ if (!hasContent && !assistantMsg.tool_calls) {
909
+ continue;
910
+ }
911
+ params.push(assistantMsg);
912
+ } else if (msg.role === "toolResult") {
913
+ const imageBlocks = [];
914
+ const deferredToolNames = /* @__PURE__ */ new Set();
915
+ let j = i;
916
+ for (; j < transformedMessages.length && transformedMessages[j].role === "toolResult"; j++) {
917
+ const toolMsg = transformedMessages[j];
918
+ const textResult = toolMsg.content.filter(isTextContentBlock).map((block) => block.text).join("\n");
919
+ const hasImages = toolMsg.content.some((c) => c.type === "image");
920
+ const hasText = textResult.length > 0;
921
+ const toolResultText = hasText ? textResult : hasImages ? "(see attached image)" : "(no tool output)";
922
+ const toolResultMsg = {
923
+ role: "tool",
924
+ content: sanitizeSurrogates(toolResultText),
925
+ tool_call_id: toolMsg.toolCallId
926
+ };
927
+ if (compat.requiresToolResultName && toolMsg.toolName) {
928
+ toolResultMsg.name = toolMsg.toolName;
929
+ }
930
+ params.push(toolResultMsg);
931
+ if (compat.deferredToolsMode === "kimi") {
932
+ for (const name of toolMsg.addedToolNames ?? []) {
933
+ deferredToolNames.add(name);
934
+ }
935
+ }
936
+ if (hasImages && model.input.includes("image")) {
937
+ for (const block of toolMsg.content) {
938
+ if (isImageContentBlock(block)) {
939
+ imageBlocks.push({
940
+ type: "image_url",
941
+ image_url: {
942
+ url: `data:${block.mimeType};base64,${block.data}`
943
+ }
944
+ });
945
+ }
946
+ }
947
+ }
948
+ }
949
+ i = j - 1;
950
+ if (imageBlocks.length > 0) {
951
+ if (compat.requiresAssistantAfterToolResult) {
952
+ params.push({
953
+ role: "assistant",
954
+ content: "I have processed the tool results."
955
+ });
956
+ }
957
+ params.push({
958
+ role: "user",
959
+ content: [
960
+ {
961
+ type: "text",
962
+ text: "Attached image(s) from tool result:"
963
+ },
964
+ ...imageBlocks
965
+ ]
966
+ });
967
+ lastRole = "user";
968
+ } else {
969
+ lastRole = "toolResult";
970
+ }
971
+ if (deferredToolNames.size > 0) {
972
+ const deferredTools = getToolsByName(context.tools, deferredToolNames);
973
+ if (deferredTools.length > 0) {
974
+ const kimiToolMessage = {
975
+ role: "system",
976
+ tools: convertTools(deferredTools, compat)
977
+ };
978
+ params.push(kimiToolMessage);
979
+ }
980
+ }
981
+ continue;
982
+ }
983
+ lastRole = msg.role;
984
+ }
985
+ return params;
986
+ }
987
+ function convertTools(tools, compat) {
988
+ return tools.map((tool) => {
989
+ const grammar = resolveGrammarConstrainedSampling(tool, compat.supportsOpenAIGrammarTools);
990
+ if (grammar) {
991
+ return {
992
+ type: "custom",
993
+ custom: {
994
+ name: tool.name,
995
+ description: tool.description,
996
+ format: {
997
+ type: "grammar",
998
+ grammar: {
999
+ syntax: grammar.format,
1000
+ definition: grammar.definition
1001
+ }
1002
+ }
1003
+ }
1004
+ };
1005
+ }
1006
+ const strict = resolveJsonSchemaStrictSampling(tool, compat.supportsStrictMode !== false);
1007
+ return {
1008
+ type: "function",
1009
+ function: {
1010
+ name: tool.name,
1011
+ description: tool.description,
1012
+ parameters: getJsonSchemaToolParameters(tool, strict),
1013
+ // Only include strict if provider supports it. Some reject unknown fields.
1014
+ ...compat.supportsStrictMode !== false && { strict: strict ?? false }
1015
+ }
1016
+ };
1017
+ });
1018
+ }
1019
+ function parseChunkUsage(rawUsage, model) {
1020
+ const promptTokens = rawUsage.prompt_tokens || 0;
1021
+ const cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? 0;
1022
+ const cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;
1023
+ const input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);
1024
+ const outputTokens = rawUsage.completion_tokens || 0;
1025
+ const usage = {
1026
+ input,
1027
+ output: outputTokens,
1028
+ cacheRead: cacheReadTokens,
1029
+ cacheWrite: cacheWriteTokens,
1030
+ reasoning: rawUsage.completion_tokens_details?.reasoning_tokens || 0,
1031
+ totalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,
1032
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
1033
+ };
1034
+ calculateCost(model, usage);
1035
+ return usage;
1036
+ }
1037
+ function mapStopReason(reason) {
1038
+ if (reason === null)
1039
+ return { stopReason: "stop" };
1040
+ switch (reason) {
1041
+ case "stop":
1042
+ case "end":
1043
+ return { stopReason: "stop" };
1044
+ case "length":
1045
+ return { stopReason: "length" };
1046
+ case "function_call":
1047
+ case "tool_calls":
1048
+ return { stopReason: "toolUse" };
1049
+ case "content_filter":
1050
+ return { stopReason: "error", errorMessage: "Provider finish_reason: content_filter" };
1051
+ case "network_error":
1052
+ return { stopReason: "error", errorMessage: "Provider finish_reason: network_error" };
1053
+ default:
1054
+ return {
1055
+ stopReason: "error",
1056
+ errorMessage: `Provider finish_reason: ${reason}`
1057
+ };
1058
+ }
1059
+ }
1060
+ function detectCompat(model) {
1061
+ const provider = model.provider;
1062
+ const baseUrl = model.baseUrl;
1063
+ const isZai = provider === "zai" || provider === "zai-coding-cn" || baseUrl.includes("api.z.ai") || baseUrl.includes("open.bigmodel.cn");
1064
+ const isTogether = provider === "together" || baseUrl.includes("api.together.ai") || baseUrl.includes("api.together.xyz");
1065
+ const isMoonshot = provider === "moonshotai" || provider === "moonshotai-cn" || baseUrl.includes("api.moonshot.");
1066
+ const isOpenRouter = provider === "openrouter" || baseUrl.includes("openrouter.ai");
1067
+ const isCloudflareWorkersAI = provider === "cloudflare-workers-ai" || baseUrl.includes("api.cloudflare.com");
1068
+ const isCloudflareAiGateway = provider === "cloudflare-ai-gateway" || baseUrl.includes("gateway.ai.cloudflare.com");
1069
+ const isNvidia = provider === "nvidia" || baseUrl.includes("integrate.api.nvidia.com");
1070
+ const isAntLing = provider === "ant-ling" || baseUrl.includes("api.ant-ling.com");
1071
+ const isDeepSeek = provider === "deepseek" || baseUrl.toLowerCase().includes("deepseek.com");
1072
+ const isNonStandard = isNvidia || provider === "cerebras" || baseUrl.includes("cerebras.ai") || provider === "xai" || baseUrl.includes("api.x.ai") || isTogether || baseUrl.includes("chutes.ai") || isDeepSeek || isZai || isMoonshot || provider === "opencode" || baseUrl.includes("opencode.ai") || isCloudflareWorkersAI || isCloudflareAiGateway || isAntLing;
1073
+ const useMaxTokens = baseUrl.includes("chutes.ai") || isDeepSeek || isMoonshot || isCloudflareAiGateway || isTogether || isNvidia || isAntLing || isZai;
1074
+ const isGrok = provider === "xai" || baseUrl.includes("api.x.ai");
1075
+ const isOpenRouterDeveloperRoleModel = isOpenRouter && (model.id.startsWith("anthropic/") || model.id.startsWith("openai/"));
1076
+ const cacheControlFormat = provider === "openrouter" && model.id.startsWith("anthropic/") ? "anthropic" : void 0;
1077
+ return {
1078
+ supportsStore: !isNonStandard,
1079
+ supportsDeveloperRole: isOpenRouterDeveloperRoleModel || !isNonStandard && !isOpenRouter,
1080
+ supportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia && !isAntLing,
1081
+ supportsUsageInStreaming: true,
1082
+ supportsFinishReason: true,
1083
+ maxTokensField: useMaxTokens ? "max_tokens" : "max_completion_tokens",
1084
+ requiresToolResultName: false,
1085
+ requiresAssistantAfterToolResult: false,
1086
+ requiresThinkingAsText: false,
1087
+ requiresReasoningContentOnAssistantMessages: isDeepSeek,
1088
+ thinkingFormat: isDeepSeek ? "deepseek" : isZai ? "zai" : isTogether ? "together" : isAntLing ? "ant-ling" : isOpenRouter ? "openrouter" : "openai",
1089
+ openRouterRouting: {},
1090
+ vercelGatewayRouting: {},
1091
+ chatTemplateKwargs: {},
1092
+ chatTemplateArgs: {},
1093
+ zaiToolStream: false,
1094
+ supportsThinkingTokenBudget: false,
1095
+ supportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia,
1096
+ supportsOpenAIGrammarTools: false,
1097
+ cacheControlFormat,
1098
+ sendSessionAffinityHeaders: false,
1099
+ deferredToolsMode: void 0,
1100
+ sessionAffinityFormat: isOpenRouter ? "openrouter" : "openai",
1101
+ supportsLongCacheRetention: !(isTogether || isCloudflareWorkersAI || isCloudflareAiGateway || isNvidia || isAntLing)
1102
+ };
1103
+ }
1104
+ function getCompat(model) {
1105
+ const detected = detectCompat(model);
1106
+ if (!model.compat)
1107
+ return detected;
1108
+ return {
1109
+ supportsStore: model.compat.supportsStore ?? detected.supportsStore,
1110
+ supportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,
1111
+ supportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,
1112
+ supportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,
1113
+ supportsFinishReason: model.compat.supportsFinishReason ?? detected.supportsFinishReason,
1114
+ maxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,
1115
+ requiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,
1116
+ requiresAssistantAfterToolResult: model.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,
1117
+ requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,
1118
+ requiresReasoningContentOnAssistantMessages: model.compat.requiresReasoningContentOnAssistantMessages ?? detected.requiresReasoningContentOnAssistantMessages,
1119
+ thinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,
1120
+ openRouterRouting: model.compat.openRouterRouting ?? {},
1121
+ vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,
1122
+ chatTemplateKwargs: model.compat.chatTemplateKwargs ?? detected.chatTemplateKwargs,
1123
+ chatTemplateArgs: model.compat.chatTemplateArgs ?? detected.chatTemplateArgs,
1124
+ zaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,
1125
+ supportsThinkingTokenBudget: model.compat.supportsThinkingTokenBudget ?? detected.supportsThinkingTokenBudget,
1126
+ supportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,
1127
+ supportsOpenAIGrammarTools: model.compat.supportsOpenAIGrammarTools ?? detected.supportsOpenAIGrammarTools,
1128
+ cacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,
1129
+ sendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,
1130
+ deferredToolsMode: model.compat.deferredToolsMode ?? detected.deferredToolsMode,
1131
+ sessionAffinityFormat: model.compat.sessionAffinityFormat ?? detected.sessionAffinityFormat,
1132
+ supportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention
1133
+ };
1134
+ }
1135
+ export {
1136
+ convertMessages,
1137
+ stream,
1138
+ streamSimple
1139
+ };