@xiaoso/dsh-tool-plus 0.1.16 → 0.1.17-beta.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 (109) hide show
  1. package/lib/{abort-DZ54CaKU.mjs → abort-BTblp0Rt.mjs} +2 -2
  2. package/lib/{alibaba-coding-plan-DODpkcqi.mjs → alibaba-coding-plan-t3R4YKCB.mjs} +3 -3
  3. package/lib/{alibaba-token-plan-C6lpKCda.mjs → alibaba-token-plan-CO4djG1y.mjs} +4 -4
  4. package/lib/{alibaba-token-plan-CHGyWOfX.mjs → alibaba-token-plan-CUjYJX0-.mjs} +1 -1
  5. package/lib/{anthropic-Dv_GGX6g.mjs → anthropic-nf7w6so1.mjs} +48 -21
  6. package/lib/{api-key-validation-MnMf_ihX.mjs → api-key-validation-C_tZ7Y9a.mjs} +2 -2
  7. package/lib/behavior-BwvTUtag.mjs +111 -0
  8. package/lib/{browser-render-BZXt548F.mjs → browser-render-BQaEVK_n.mjs} +4 -4
  9. package/lib/{reference-CtvM4zLU.mjs → bundled-references-CrQ4dQcT.mjs} +57 -4
  10. package/lib/cascade-BWjRTD1q.mjs +30265 -0
  11. package/lib/{cline-pass-BT9CBEOj.mjs → cline-pass-Bjm-O8GG.mjs} +2 -2
  12. package/lib/cloudflare-CKXRJ0l9.mjs +37 -0
  13. package/lib/{cloudflare-ai-gateway-DReN6ohJ.mjs → cloudflare-ai-gateway-BpnBSjwV.mjs} +8 -4
  14. package/lib/cloudflare-workers-ai-odj9XswL.mjs +32 -0
  15. package/lib/collapse-_nkb2dn7.mjs +1945 -0
  16. package/lib/{coreweave-C82HrLpb.mjs → coreweave-CGDZOD8-.mjs} +1 -1
  17. package/lib/{coreweave-C68UgRQO.mjs → coreweave-DwffcgW5.mjs} +4 -4
  18. package/lib/cursor-BgOuV7Qf.mjs +794 -0
  19. package/lib/{cursor-_gHHq-Dq.mjs → cursor-CF1iHHbv.mjs} +68 -19
  20. package/lib/{cursor-proto-Cr_WEMuv.mjs → cursor-proto-BuNTjX3L.mjs} +823 -23
  21. package/lib/{devin-QpfTSl9H.mjs → devin-7OEeEb80.mjs} +112 -31
  22. package/lib/{devin-proto-DYhp4Ty6.mjs → devin-proto-C-QreeAv.mjs} +71 -5
  23. package/lib/{dom-DG3sPESc.mjs → dom-BmbZv4v9.mjs} +598 -182
  24. package/lib/{error-O63pC8zg.mjs → error-8LVo7tug.mjs} +725 -104
  25. package/lib/factory-droid-ChhmsGWb.mjs +71 -0
  26. package/lib/{fs-promises-shim-B2YFWkcd.mjs → fs-promises-shim-CANAxFWh.mjs} +10 -1
  27. package/lib/{github-copilot-BMEcw8N1.mjs → github-copilot-QwevdT30.mjs} +4 -4
  28. package/lib/{github-copilot-headers-DnjGEbko.mjs → github-copilot-headers-CAUZ0rUD.mjs} +138 -26
  29. package/lib/{gitlab-duo-DnHqJjFY.mjs → gitlab-duo-DigV7k_o.mjs} +2 -2
  30. package/lib/{google-antigravity-B1mSckrK.mjs → google-antigravity-D-oe0r8A.mjs} +6 -7
  31. package/lib/{google-gemini-cli-DJwThCCn.mjs → google-gemini-cli-CQBHgGJT.mjs} +5 -6
  32. package/lib/{google-oauth-shared-BctLpVUN.mjs → google-oauth-shared-CvgVIUwJ.mjs} +2 -2
  33. package/lib/google-validation-CdvRj4ec.mjs +126 -0
  34. package/lib/id-EJwVLDHE.mjs +2548 -0
  35. package/lib/index.mjs +248 -258
  36. package/lib/{kilo-BEgEwMJQ.mjs → kilo-5r6OffCa.mjs} +2 -2
  37. package/lib/{kimi-T9NldEIJ.mjs → kimi-DOOtbXmm.mjs} +9 -10
  38. package/lib/{launch-BIWNyrBB.mjs → launch-DkAjib7h.mjs} +1 -1
  39. package/lib/{markit-Dvp2JPdT.mjs → markit-CCcyeAds.mjs} +359 -140
  40. package/lib/{models-DnXMYGcJ.mjs → models-DCpDT_im.mjs} +199203 -112275
  41. package/lib/{muse-code-CNvqqAp6.mjs → muse-code-CYf8zj_B.mjs} +5 -5
  42. package/lib/{openai-codex-D5-CyTxa.mjs → openai-codex-Cj-TvSFh.mjs} +13 -10
  43. package/lib/{perplexity-A2PEoGaC.mjs → perplexity-Dh_Qgsmx.mjs} +68 -25
  44. package/lib/{pkce-BYjmugmw.mjs → pkce-DO-jBJLV.mjs} +1 -1
  45. package/lib/pricing-DusBEhwm.mjs +593 -0
  46. package/lib/{readability-uGhqb4GC.mjs → readability-XHK0o3bv.mjs} +287 -27
  47. package/lib/{scrapers-C1ujjV8k.mjs → scrapers-B6PADOVm.mjs} +13 -13
  48. package/lib/slugify-ynYWBIA5.mjs +11 -0
  49. package/lib/snowflake-B_jap6lz.mjs +666 -0
  50. package/lib/snowflake-Cu1ZyOp6.mjs +151 -0
  51. package/lib/{src-AELUUb5U.mjs → src-BhinCSpi.mjs} +1172 -458
  52. package/lib/{stream-AVOoe5Hj.mjs → stream-D2ivg3GH.mjs} +3740 -5311
  53. package/lib/{turndown-D6fof1OX.mjs → turndown-Vya8SavL.mjs} +82 -30
  54. package/lib/types/tools/hashline/native/index.d.ts +2 -2
  55. package/lib/types/tools/hashline/native/policy.d.ts +19 -21
  56. package/lib/types/tools/omp/session/agent-storage.d.ts +3 -3
  57. package/lib/types/tools/shared/bun-named-shim.d.ts +5 -0
  58. package/lib/{types-BLrLohwK.mjs → types-tH1v9uRm.mjs} +2 -2
  59. package/lib/{utils-cZX3f_Ls.mjs → utils-C_Ncya1r.mjs} +1737 -509
  60. package/lib/utils-D2tK38xq.mjs +34006 -0
  61. package/lib/{utils-I4I8azHN.mjs → utils-DrDwmNtu.mjs} +8 -3
  62. package/lib/{xai-oauth-CbeldUSV.mjs → xai-oauth-DLLzX6my.mjs} +4 -4
  63. package/lib/{xiaomi-Dl3VSs04.mjs → xiaomi-CqK-KivK.mjs} +2 -2
  64. package/lib/{zai-FyjGSypr.mjs → zai-DoJ2xPIH.mjs} +2 -2
  65. package/lib/{zip-DRrycScC.mjs → zip-DG1mUV6X.mjs} +1 -1
  66. package/package.json +8 -8
  67. package/lib/amazon-bedrock-Dx0rr9dY.mjs +0 -996
  68. package/lib/anthropic-ClCw0PV_.mjs +0 -3624
  69. package/lib/anthropic-wire-lbGAFzYb.mjs +0 -927
  70. package/lib/azure-openai-responses-WE_bgFWp.mjs +0 -285
  71. package/lib/bundled-references-DY3EJxZV.mjs +0 -56
  72. package/lib/cloudflare-ai-gateway-CrMa97Ap.mjs +0 -44
  73. package/lib/collapse-CkMNRNr7.mjs +0 -2304
  74. package/lib/cursor-C6jaIJDg.mjs +0 -283
  75. package/lib/cursor-D-XZYDf_.mjs +0 -4544
  76. package/lib/deterministic-id-CUEIMSqR.mjs +0 -17
  77. package/lib/devin-ExGIghmx.mjs +0 -69
  78. package/lib/devin-u0ljw5P6.mjs +0 -628
  79. package/lib/effort-BdtQMN-_.mjs +0 -23
  80. package/lib/event-stream-BKEtb45Y.mjs +0 -167
  81. package/lib/gemini-headers-Co9cVvex.mjs +0 -54
  82. package/lib/google-auth-qAN-6DMW.mjs +0 -232
  83. package/lib/google-gemini-cli-B2Aw1S5w.mjs +0 -844
  84. package/lib/google-lTxuq28n.mjs +0 -38
  85. package/lib/google-shared-Y01j9xOr.mjs +0 -856
  86. package/lib/google-validation-BEkNs-Bx.mjs +0 -18
  87. package/lib/google-vertex-DcM-FRC5.mjs +0 -99
  88. package/lib/hosts-00rjRzUD.mjs +0 -203
  89. package/lib/id-AL5obQzR.mjs +0 -71
  90. package/lib/idle-iterator-D0ZXEcUq.mjs +0 -366
  91. package/lib/ollama-6R0oXZks.mjs +0 -574
  92. package/lib/openai-codex-responses-C8bnBWOe.mjs +0 -3232
  93. package/lib/openai-completions-DNr3mUsn.mjs +0 -1430
  94. package/lib/openai-configuration-update-xMYUjaK_.mjs +0 -150
  95. package/lib/openai-reasoning-fallback-Ju-5pSR8.mjs +0 -380
  96. package/lib/openai-responses-CjpafAEr.mjs +0 -861
  97. package/lib/protobuf-BMgDYu_U.mjs +0 -717
  98. package/lib/provider-response-SqKSkkUc.mjs +0 -22
  99. package/lib/proxy-DxvCQOCA.mjs +0 -230
  100. package/lib/request-debug-BwPOqN_j.mjs +0 -183
  101. package/lib/sanitize-text-BCf5KmCf.mjs +0 -33
  102. package/lib/sse-debug-B-tkLCPW.mjs +0 -11
  103. package/lib/stream-markup-healing-CN3RsqG9.mjs +0 -267
  104. package/lib/strict-tool-validation-CBTz1dAA.mjs +0 -105
  105. package/lib/taxonomy-DSIM99rS.mjs +0 -15392
  106. package/lib/thinking-ngMwf_1Y.mjs +0 -336
  107. package/lib/type-guards-CttAANEx.mjs +0 -11
  108. package/lib/utils-CE3DSebh.mjs +0 -11763
  109. package/lib/vision-guard-BCpXWUj3.mjs +0 -77
@@ -1,574 +0,0 @@
1
- import { installBunShim as __installBunShim } from "./bun-shim.mjs";
2
- __installBunShim();
3
- import { r as __exportAll } from "./fs-promises-shim-B2YFWkcd.mjs";
4
- import { _ as parseStreamingJson, i as readJsonl } from "./src-AELUUb5U.mjs";
5
- import { G as fetchWithRetry, c as finalize, h as MissingApiKeyError, y as LLAMA_CPP_TOOL_CALL_PARSE_PATTERN, z as OllamaApiError } from "./error-O63pC8zg.mjs";
6
- import { A as toolWireSchema, R as sanitizeSchemaForOllama, g as clearStreamingPartialJson, h as transformMessages, o as normalizeSystemPrompts, w as kStreamingPartialJson } from "./utils-cZX3f_Ls.mjs";
7
- import { At as withReplaySafeStreamRetry, n as getEnvApiKey } from "./stream-AVOoe5Hj.mjs";
8
- import { i as partitionVisionContent, r as joinTextWithImagePlaceholder } from "./vision-guard-BCpXWUj3.mjs";
9
- import { t as AssistantMessageEventStream } from "./event-stream-BKEtb45Y.mjs";
10
- import { n as getOpenAIStreamFirstEventTimeoutMs, r as getOpenAIStreamIdleTimeoutMs, t as armPreResponseTimeout } from "./idle-iterator-D0ZXEcUq.mjs";
11
- import { n as getStreamMarkupHealingPattern, t as StreamMarkupHealing } from "./stream-markup-healing-CN3RsqG9.mjs";
12
- //#region node_modules/.pnpm/@oh-my-pi+pi-ai@18.1.17/node_modules/@oh-my-pi/pi-ai/src/providers/ollama.ts
13
- var ollama_exports = /* @__PURE__ */ __exportAll({ streamOllama: () => streamOllama });
14
- function normalizeBaseUrl(baseUrl) {
15
- const value = baseUrl?.trim();
16
- if (!value) return "https://ollama.com";
17
- const trimmed = value.endsWith("/") ? value.slice(0, -1) : value;
18
- return trimmed.endsWith("/api") ? trimmed.slice(0, -4) : trimmed;
19
- }
20
- function mapReasoning(model, reasoning, disableReasoning) {
21
- const modelReasoning = model.reasoning;
22
- if (disableReasoning && modelReasoning) return false;
23
- switch (model.provider === "ollama-cloud" && reasoning ? model.thinking?.effortMap?.[reasoning] ?? reasoning : reasoning) {
24
- case "minimal":
25
- case "low": return "low";
26
- case "medium": return "medium";
27
- case "high": return "high";
28
- case "max": return "max";
29
- case "xhigh": return "high";
30
- default: return;
31
- }
32
- }
33
- function mapToolChoice(toolChoice) {
34
- if (!toolChoice || toolChoice === "auto") return;
35
- if (toolChoice === "none") return "none";
36
- if (toolChoice === "required" || toolChoice === "any") return "required";
37
- if (typeof toolChoice === "object" && toolChoice.type === "computer") return void 0;
38
- if (typeof toolChoice === "object") return "required";
39
- }
40
- function getNamedToolChoiceName(toolChoice) {
41
- if (!toolChoice || typeof toolChoice === "string") return;
42
- if (toolChoice.type === "computer") return void 0;
43
- if ("function" in toolChoice) return toolChoice.function.name;
44
- return toolChoice.name;
45
- }
46
- function selectToolsForToolChoice(tools, toolChoice) {
47
- const toolName = getNamedToolChoiceName(toolChoice);
48
- if (!toolName || !tools) return tools;
49
- for (const tool of tools) if (tool.name === toolName) return [tool];
50
- return [];
51
- }
52
- function toPlainContent(content, supportsImages) {
53
- if (typeof content === "string") return { content };
54
- const { textBlocks, imageBlocks, omittedImages } = partitionVisionContent(content, supportsImages);
55
- const text = textBlocks.map((block) => block.text).join("\n");
56
- return {
57
- content: joinTextWithImagePlaceholder(text, omittedImages),
58
- ...imageBlocks.length > 0 ? { images: imageBlocks.map((block) => block.data) } : {}
59
- };
60
- }
61
- function convertMessage(message, supportsImages, developerRole = "user") {
62
- if (message.role === "user") return {
63
- role: "user",
64
- ...toPlainContent(message.content, supportsImages)
65
- };
66
- if (message.role === "developer") return {
67
- role: developerRole,
68
- ...toPlainContent(message.content, supportsImages)
69
- };
70
- if (message.role === "toolResult") {
71
- const converted = toPlainContent(message.content, supportsImages);
72
- return {
73
- role: "tool",
74
- tool_name: message.toolName,
75
- ...converted
76
- };
77
- }
78
- const text = [];
79
- const thinking = [];
80
- const toolCalls = [];
81
- for (const block of message.content) {
82
- if (block.type === "text") {
83
- text.push(block.text);
84
- continue;
85
- }
86
- if (block.type === "thinking") {
87
- thinking.push(block.thinking);
88
- continue;
89
- }
90
- if (block.type === "toolCall") toolCalls.push({
91
- type: "function",
92
- function: {
93
- name: block.name,
94
- arguments: block.arguments
95
- }
96
- });
97
- }
98
- return {
99
- role: "assistant",
100
- content: text.join("\n"),
101
- ...thinking.length > 0 ? { thinking: thinking.join("\n") } : {},
102
- ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
103
- };
104
- }
105
- function convertMessages(model, context) {
106
- const systemPrompts = normalizeSystemPrompts(context.systemPrompt);
107
- const messages = [...systemPrompts.map((systemPrompt) => ({
108
- role: "developer",
109
- content: systemPrompt,
110
- timestamp: Date.now()
111
- })), ...context.messages];
112
- const isCloud = model.provider === "ollama-cloud";
113
- const supportsImages = model.input.includes("image");
114
- const converted = transformMessages(messages, model).map((msg, index) => {
115
- const developerRole = msg.role === "developer" && (index < systemPrompts.length || msg.attribution !== "user") ? "system" : "user";
116
- const converted = convertMessage(msg, supportsImages, developerRole);
117
- if (isCloud && converted.role === "assistant" && converted.thinking) {
118
- const { thinking: _t, ...rest } = converted;
119
- return rest;
120
- }
121
- return converted;
122
- });
123
- if (!converted.some((m) => m.role === "user")) {
124
- for (let i = converted.length - 1; i >= systemPrompts.length; i--) if (converted[i].role === "system") {
125
- converted[i].role = "user";
126
- break;
127
- }
128
- }
129
- return converted;
130
- }
131
- function convertTools(tools) {
132
- if (!tools || tools.length === 0) return;
133
- return tools.map((tool) => ({
134
- type: "function",
135
- function: {
136
- name: tool.name,
137
- description: tool.description,
138
- parameters: sanitizeSchemaForOllama(toolWireSchema(tool))
139
- }
140
- }));
141
- }
142
- function createChatBody(model, context, options) {
143
- const think = mapReasoning(model, options?.reasoning, options?.disableReasoning);
144
- const toolChoice = mapToolChoice(options?.toolChoice);
145
- const tools = convertTools(selectToolsForToolChoice(context.tools, options?.toolChoice));
146
- const runtimeOptions = {};
147
- let hasRuntimeOptions = false;
148
- if (options?.maxTokens !== void 0 && !model.omitMaxOutputTokens) {
149
- runtimeOptions.num_predict = model.provider === "ollama-cloud" ? Math.min(options.maxTokens, 65536) : options.maxTokens;
150
- hasRuntimeOptions = true;
151
- }
152
- if (options?.temperature !== void 0) {
153
- runtimeOptions.temperature = options.temperature;
154
- hasRuntimeOptions = true;
155
- }
156
- if (options?.topP !== void 0) {
157
- runtimeOptions.top_p = options.topP;
158
- hasRuntimeOptions = true;
159
- }
160
- return {
161
- model: model.id,
162
- messages: convertMessages(model, context),
163
- ...tools ? { tools } : {},
164
- ...think !== void 0 ? { think } : {},
165
- ...toolChoice !== void 0 ? { tool_choice: toolChoice } : {},
166
- ...hasRuntimeOptions ? { options: runtimeOptions } : {},
167
- stream: true
168
- };
169
- }
170
- function shouldRetryOllamaResponse(response, bodyText) {
171
- return response.status < 500 || !LLAMA_CPP_TOOL_CALL_PARSE_PATTERN.test(bodyText);
172
- }
173
- async function captureHttpErrorResponse(response) {
174
- let bodyText;
175
- let bodyJson;
176
- try {
177
- bodyText = await response.text();
178
- if (bodyText.trim()) try {
179
- bodyJson = JSON.parse(bodyText);
180
- } catch {}
181
- } catch {}
182
- return {
183
- status: response.status,
184
- headers: response.headers,
185
- bodyText,
186
- bodyJson
187
- };
188
- }
189
- function createEmptyOutput(model) {
190
- return {
191
- role: "assistant",
192
- content: [],
193
- api: "ollama-chat",
194
- provider: model.provider,
195
- model: model.id,
196
- usage: {
197
- input: 0,
198
- output: 0,
199
- cacheRead: 0,
200
- cacheWrite: 0,
201
- totalTokens: 0,
202
- cost: {
203
- input: 0,
204
- output: 0,
205
- cacheRead: 0,
206
- cacheWrite: 0,
207
- total: 0
208
- }
209
- },
210
- stopReason: "stop",
211
- timestamp: Date.now()
212
- };
213
- }
214
- function endThinkingBlock(stream, output, index) {
215
- const block = output.content[index];
216
- if (block?.type === "thinking") stream.push({
217
- type: "thinking_end",
218
- contentIndex: index,
219
- content: block.thinking,
220
- partial: output
221
- });
222
- }
223
- function endTextBlock(stream, output, index) {
224
- const block = output.content[index];
225
- if (block?.type === "text") stream.push({
226
- type: "text_end",
227
- contentIndex: index,
228
- content: block.text,
229
- partial: output
230
- });
231
- }
232
- function endToolCallBlock(stream, output, index) {
233
- const block = output.content[index];
234
- if (block?.type !== "toolCall") return;
235
- const toolCall = block;
236
- if (toolCall[kStreamingPartialJson]) {
237
- toolCall.arguments = parseStreamingJson(toolCall[kStreamingPartialJson]);
238
- clearStreamingPartialJson(toolCall);
239
- }
240
- stream.push({
241
- type: "toolcall_end",
242
- contentIndex: index,
243
- toolCall,
244
- partial: output
245
- });
246
- }
247
- function mapDoneReason(doneReason, output) {
248
- if (doneReason === "length") return "length";
249
- if (doneReason === "tool_calls") return "toolUse";
250
- if (doneReason === "load") return "error";
251
- if (doneReason === void 0 && output.content.some((block) => block.type === "toolCall")) return "toolUse";
252
- return "stop";
253
- }
254
- const EMPTY_OLLAMA_LENGTH_COMPLETION_MESSAGE = "Model returned no content: prompt filled the context window; raise Ollama num_ctx or shorten the prompt.";
255
- const EMPTY_OLLAMA_LOAD_COMPLETION_MESSAGE = "Ollama loaded the model but generated nothing (done_reason: load): the request contained no user-role message.";
256
- function hasVisibleAssistantContent(output) {
257
- return output.content.some((block) => {
258
- if (block.type === "text") return block.text.trim().length > 0;
259
- if (block.type === "thinking") return block.thinking.trim().length > 0;
260
- return block.type === "toolCall";
261
- });
262
- }
263
- const OLLAMA_RETRY_DELAYS_MS = [
264
- 2e3,
265
- 5e3,
266
- 1e4
267
- ];
268
- const streamOllamaOnce = (model, context, options = {}) => {
269
- const stream = new AssistantMessageEventStream();
270
- (async () => {
271
- const startTime = performance.now();
272
- let firstTokenTime;
273
- const output = createEmptyOutput(model);
274
- let rawRequestDump;
275
- let capturedErrorResponse;
276
- let activeThinkingIndex;
277
- let activeTextIndex;
278
- const activeToolIndices = /* @__PURE__ */ new Set();
279
- const streamMarkupHealingPattern = getStreamMarkupHealingPattern(model);
280
- const streamMarkupHealing = streamMarkupHealingPattern ? new StreamMarkupHealing({ pattern: streamMarkupHealingPattern }) : void 0;
281
- let healedToolCallEmitted = false;
282
- let suppressHealedThinking = false;
283
- const endActiveTextBlock = () => {
284
- if (activeTextIndex === void 0) return;
285
- endTextBlock(stream, output, activeTextIndex);
286
- activeTextIndex = void 0;
287
- };
288
- const endActiveThinkingBlock = () => {
289
- if (activeThinkingIndex === void 0) return;
290
- endThinkingBlock(stream, output, activeThinkingIndex);
291
- activeThinkingIndex = void 0;
292
- };
293
- const appendVisibleText = (text) => {
294
- if (text.length === 0) return;
295
- endActiveThinkingBlock();
296
- if (activeTextIndex === void 0) {
297
- output.content.push({
298
- type: "text",
299
- text: ""
300
- });
301
- activeTextIndex = output.content.length - 1;
302
- stream.push({
303
- type: "text_start",
304
- contentIndex: activeTextIndex,
305
- partial: output
306
- });
307
- }
308
- const block = output.content[activeTextIndex];
309
- if (block?.type === "text") {
310
- block.text += text;
311
- stream.push({
312
- type: "text_delta",
313
- contentIndex: activeTextIndex,
314
- delta: text,
315
- partial: output
316
- });
317
- }
318
- if (!firstTokenTime) firstTokenTime = performance.now();
319
- };
320
- const appendVisibleThinking = (thinking) => {
321
- if (thinking.length === 0) return;
322
- endActiveTextBlock();
323
- if (activeThinkingIndex === void 0) {
324
- output.content.push({
325
- type: "thinking",
326
- thinking: ""
327
- });
328
- activeThinkingIndex = output.content.length - 1;
329
- stream.push({
330
- type: "thinking_start",
331
- contentIndex: activeThinkingIndex,
332
- partial: output
333
- });
334
- }
335
- const block = output.content[activeThinkingIndex];
336
- if (block?.type === "thinking") {
337
- block.thinking += thinking;
338
- stream.push({
339
- type: "thinking_delta",
340
- contentIndex: activeThinkingIndex,
341
- delta: thinking,
342
- partial: output
343
- });
344
- }
345
- if (!firstTokenTime) firstTokenTime = performance.now();
346
- };
347
- const emitHealedToolCall = (call) => {
348
- endActiveThinkingBlock();
349
- endActiveTextBlock();
350
- const toolCall = {
351
- type: "toolCall",
352
- id: call.id,
353
- name: call.name,
354
- arguments: parseStreamingJson(call.arguments),
355
- [kStreamingPartialJson]: call.arguments
356
- };
357
- output.content.push(toolCall);
358
- const index = output.content.length - 1;
359
- stream.push({
360
- type: "toolcall_start",
361
- contentIndex: index,
362
- partial: output
363
- });
364
- stream.push({
365
- type: "toolcall_delta",
366
- contentIndex: index,
367
- delta: call.arguments,
368
- partial: output
369
- });
370
- endToolCallBlock(stream, output, index);
371
- healedToolCallEmitted = true;
372
- if (!firstTokenTime) firstTokenTime = performance.now();
373
- };
374
- const emitHealingEvent = (event) => {
375
- if (event.type === "text") appendVisibleText(event.text);
376
- else if (event.type === "thinking") {
377
- if (!suppressHealedThinking) appendVisibleThinking(event.thinking);
378
- } else emitHealedToolCall(event.call);
379
- };
380
- const drainHealedToolCalls = () => {
381
- if (!streamMarkupHealing) return;
382
- for (const call of streamMarkupHealing.drainCompleted()) emitHealedToolCall(call);
383
- };
384
- try {
385
- const apiKey = options.apiKey || getEnvApiKey(model.provider);
386
- if (!apiKey) throw new MissingApiKeyError(model.provider);
387
- const baseUrl = normalizeBaseUrl(model.baseUrl);
388
- let body = createChatBody(model, context, options);
389
- const replacementPayload = await options.onPayload?.(body, model);
390
- if (replacementPayload !== void 0) body = replacementPayload;
391
- rawRequestDump = {
392
- provider: model.provider,
393
- api: model.api,
394
- model: model.id,
395
- method: "POST",
396
- url: `${baseUrl}/api/chat`,
397
- body
398
- };
399
- const idleTimeoutMs = options.streamIdleTimeoutMs ?? getOpenAIStreamIdleTimeoutMs();
400
- const firstEventTimeoutMs = options.streamFirstEventTimeoutMs ?? getOpenAIStreamFirstEventTimeoutMs(idleTimeoutMs);
401
- const watchdog = armPreResponseTimeout(options.signal, firstEventTimeoutMs);
402
- let response;
403
- try {
404
- response = await fetchWithRetry(`${baseUrl}/api/chat`, {
405
- method: "POST",
406
- headers: {
407
- ...model.headers,
408
- ...options.headers,
409
- Authorization: `Bearer ${apiKey}`,
410
- "Content-Type": "application/json"
411
- },
412
- body: JSON.stringify(body),
413
- signal: watchdog.signal,
414
- defaultDelayMs: OLLAMA_RETRY_DELAYS_MS,
415
- shouldRetryResponse: shouldRetryOllamaResponse,
416
- fetch: options.fetch,
417
- timeout: false
418
- });
419
- } finally {
420
- watchdog.clear();
421
- }
422
- if (!response.ok) {
423
- capturedErrorResponse = await captureHttpErrorResponse(response);
424
- throw new OllamaApiError(`HTTP ${response.status} from ${baseUrl}/api/chat`, response.status, { headers: response.headers });
425
- }
426
- if (!response.body) throw new OllamaApiError("Ollama returned an empty response body", response.status, { headers: response.headers });
427
- stream.push({
428
- type: "start",
429
- partial: output
430
- });
431
- for await (const chunk of readJsonl(response.body)) {
432
- if (chunk.message?.thinking) {
433
- suppressHealedThinking = true;
434
- endActiveTextBlock();
435
- if (activeThinkingIndex === void 0) {
436
- output.content.push({
437
- type: "thinking",
438
- thinking: ""
439
- });
440
- activeThinkingIndex = output.content.length - 1;
441
- stream.push({
442
- type: "thinking_start",
443
- contentIndex: activeThinkingIndex,
444
- partial: output
445
- });
446
- }
447
- const block = output.content[activeThinkingIndex];
448
- if (block?.type === "thinking") {
449
- block.thinking += chunk.message.thinking;
450
- stream.push({
451
- type: "thinking_delta",
452
- contentIndex: activeThinkingIndex,
453
- delta: chunk.message.thinking,
454
- partial: output
455
- });
456
- }
457
- if (!firstTokenTime) firstTokenTime = performance.now();
458
- }
459
- const chunkContent = chunk.message?.content;
460
- const structuredCalls = chunk.message?.tool_calls?.length ? chunk.message.tool_calls : void 0;
461
- if (chunkContent) {
462
- if (streamMarkupHealing) {
463
- const healingEvents = structuredCalls ? streamMarkupHealing.feedEventsWithoutCalls(chunkContent) : streamMarkupHealing.feedEvents(chunkContent);
464
- for (const event of healingEvents) emitHealingEvent(event);
465
- } else appendVisibleText(chunkContent);
466
- }
467
- if (structuredCalls) {
468
- endActiveThinkingBlock();
469
- endActiveTextBlock();
470
- for (const call of structuredCalls) {
471
- const name = call.function?.name ?? "unknown_tool";
472
- const rawArgs = call.function?.arguments;
473
- const partialJson = typeof rawArgs === "string" ? rawArgs : JSON.stringify(rawArgs ?? {});
474
- const toolCall = {
475
- type: "toolCall",
476
- id: `ollama:${output.content.length}:${name}`,
477
- name,
478
- arguments: parseStreamingJson(partialJson),
479
- [kStreamingPartialJson]: partialJson
480
- };
481
- output.content.push(toolCall);
482
- const index = output.content.length - 1;
483
- activeToolIndices.add(index);
484
- stream.push({
485
- type: "toolcall_start",
486
- contentIndex: index,
487
- partial: output
488
- });
489
- stream.push({
490
- type: "toolcall_delta",
491
- contentIndex: index,
492
- delta: partialJson,
493
- partial: output
494
- });
495
- if (!firstTokenTime) firstTokenTime = performance.now();
496
- }
497
- }
498
- if (chunk.done) {
499
- if (streamMarkupHealing) {
500
- for (const event of streamMarkupHealing.flushEvents()) emitHealingEvent(event);
501
- drainHealedToolCalls();
502
- }
503
- endActiveThinkingBlock();
504
- endActiveTextBlock();
505
- for (const index of activeToolIndices) endToolCallBlock(stream, output, index);
506
- activeToolIndices.clear();
507
- output.stopReason = mapDoneReason(chunk.done_reason, output);
508
- if (healedToolCallEmitted && output.stopReason === "stop") output.stopReason = "toolUse";
509
- output.usage.cacheRead = chunk.prompt_eval_cached_count ?? 0;
510
- output.usage.input = (chunk.prompt_eval_count ?? 0) - output.usage.cacheRead;
511
- output.usage.output = chunk.eval_count ?? 0;
512
- output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead;
513
- }
514
- }
515
- if (streamMarkupHealing) {
516
- for (const event of streamMarkupHealing.flushEvents()) emitHealingEvent(event);
517
- drainHealedToolCalls();
518
- if (healedToolCallEmitted && output.stopReason === "stop") output.stopReason = "toolUse";
519
- }
520
- endActiveThinkingBlock();
521
- endActiveTextBlock();
522
- if (output.stopReason === "length" && !hasVisibleAssistantContent(output)) {
523
- output.stopReason = "error";
524
- output.errorMessage = EMPTY_OLLAMA_LENGTH_COMPLETION_MESSAGE;
525
- }
526
- if (output.stopReason === "error" && !output.errorMessage) output.errorMessage = EMPTY_OLLAMA_LOAD_COMPLETION_MESSAGE;
527
- if (output.stopReason === "stop" && output.content.some((block) => block.type === "toolCall")) output.stopReason = "toolUse";
528
- output.duration = performance.now() - startTime;
529
- if (firstTokenTime) output.ttft = firstTokenTime - startTime;
530
- if (output.stopReason === "error") {
531
- stream.push({
532
- type: "error",
533
- reason: "error",
534
- error: output
535
- });
536
- stream.end();
537
- return;
538
- }
539
- const doneReason = output.stopReason === "length" ? "length" : output.stopReason === "toolUse" ? "toolUse" : "stop";
540
- stream.push({
541
- type: "done",
542
- reason: doneReason,
543
- message: output
544
- });
545
- stream.end();
546
- } catch (error) {
547
- for (const block of output.content) if (block.type === "toolCall") clearStreamingPartialJson(block);
548
- const result = await finalize(error, {
549
- api: model.api,
550
- provider: model.provider,
551
- signal: options.signal,
552
- rawRequestDump,
553
- capturedErrorResponse
554
- });
555
- output.stopReason = result.stopReason;
556
- output.errorStatus = result.status;
557
- output.errorId = result.id;
558
- output.errorMessage = result.message;
559
- output.duration = performance.now() - startTime;
560
- if (firstTokenTime) output.ttft = firstTokenTime - startTime;
561
- stream.push({
562
- type: "error",
563
- reason: output.stopReason,
564
- error: output
565
- });
566
- stream.end();
567
- }
568
- })();
569
- return stream;
570
- };
571
- /** Retry EOS-only Ollama completions before the agent loop sees an empty stop. */
572
- const streamOllama = (model, context, options) => withReplaySafeStreamRetry(model, context, options, streamOllamaOnce, { retryEmptyCompletion: true });
573
- //#endregion
574
- export { ollama_exports as t };