@dexto/core 1.16.4 → 1.16.6

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 (37) hide show
  1. package/dist/context/manager.cjs +50 -36
  2. package/dist/context/manager.d.ts +18 -0
  3. package/dist/context/manager.d.ts.map +1 -1
  4. package/dist/context/manager.js +50 -36
  5. package/dist/llm/auth/index.d.ts +1 -1
  6. package/dist/llm/auth/index.d.ts.map +1 -1
  7. package/dist/llm/auth/types.d.ts +14 -0
  8. package/dist/llm/auth/types.d.ts.map +1 -1
  9. package/dist/llm/error-codes.cjs +2 -0
  10. package/dist/llm/error-codes.d.ts +2 -0
  11. package/dist/llm/error-codes.d.ts.map +1 -1
  12. package/dist/llm/error-codes.js +2 -0
  13. package/dist/llm/errors.cjs +27 -0
  14. package/dist/llm/errors.d.ts +9 -0
  15. package/dist/llm/errors.d.ts.map +1 -1
  16. package/dist/llm/errors.js +27 -0
  17. package/dist/llm/executor/stream-processor.cjs +7 -0
  18. package/dist/llm/executor/stream-processor.d.ts +1 -0
  19. package/dist/llm/executor/stream-processor.d.ts.map +1 -1
  20. package/dist/llm/executor/stream-processor.js +7 -0
  21. package/dist/llm/executor/tool-output-spill.cjs +46 -14
  22. package/dist/llm/executor/tool-output-spill.d.ts.map +1 -1
  23. package/dist/llm/executor/tool-output-spill.js +46 -14
  24. package/dist/llm/index.d.ts +1 -1
  25. package/dist/llm/index.d.ts.map +1 -1
  26. package/dist/llm/services/factory.cjs +204 -14
  27. package/dist/llm/services/factory.d.ts +1 -1
  28. package/dist/llm/services/factory.d.ts.map +1 -1
  29. package/dist/llm/services/factory.js +204 -14
  30. package/dist/tools/tool-output-read.cjs +4 -3
  31. package/dist/tools/tool-output-read.d.ts.map +1 -1
  32. package/dist/tools/tool-output-read.js +4 -3
  33. package/dist/utils/text-boundary.cjs +32 -0
  34. package/dist/utils/text-boundary.d.ts +3 -0
  35. package/dist/utils/text-boundary.d.ts.map +1 -0
  36. package/dist/utils/text-boundary.js +9 -0
  37. package/package.json +2 -2
@@ -25,12 +25,12 @@ __export(tool_output_spill_exports, {
25
25
  withToolOutputPreview: () => withToolOutputPreview
26
26
  });
27
27
  module.exports = __toCommonJS(tool_output_spill_exports);
28
+ var import_text_boundary = require("../../utils/text-boundary.js");
28
29
  const TOOL_OUTPUT_READ_TOOL_NAME = "tool_output_read";
29
30
  const CHARS_PER_TOKEN = 4;
30
31
  const MAX_INLINE_TOKENS = 4e3;
31
32
  const INLINE_WINDOW_RATIO = 0.1;
32
33
  const STEP_WINDOW_RATIO = 0.4;
33
- const STEP_SPILL_PREVIEW_CHARS = 16e3;
34
34
  const PREVIEW_HEAD_RATIO = 0.75;
35
35
  function toolOutputBudget(maxInputTokens) {
36
36
  return {
@@ -46,32 +46,57 @@ function planToolOutputSpills(results, budget) {
46
46
  let inlineChars = 0;
47
47
  for (const result of results) {
48
48
  if (result.textLength > budget.inlineCapChars) {
49
- previewChars.set(result.toolCallId, budget.inlineCapChars);
50
- inlineChars += budget.inlineCapChars;
49
+ const cap = Math.max(
50
+ budget.inlineCapChars,
51
+ outputMarker(result.toolCallId, result.textLength, 0, 0).length
52
+ );
53
+ if (cap < result.textLength) {
54
+ previewChars.set(result.toolCallId, cap);
55
+ inlineChars += cap;
56
+ } else {
57
+ inlineChars += result.textLength;
58
+ }
51
59
  } else {
52
60
  inlineChars += result.textLength;
53
61
  }
54
62
  }
55
- const stepPreviewChars = Math.min(budget.inlineCapChars, STEP_SPILL_PREVIEW_CHARS);
63
+ const stepPreviewChars = Math.floor(budget.inlineCapChars / 2);
56
64
  const largestFirst = results.filter((result) => result.textLength > stepPreviewChars).sort((left, right) => right.textLength - left.textLength);
57
65
  for (const result of largestFirst) {
58
66
  if (inlineChars <= budget.stepBudgetChars) break;
59
67
  const inlineNow = previewChars.get(result.toolCallId) ?? result.textLength;
60
- if (inlineNow <= stepPreviewChars) continue;
61
- previewChars.set(result.toolCallId, stepPreviewChars);
62
- inlineChars -= inlineNow - stepPreviewChars;
68
+ const target = Math.max(
69
+ stepPreviewChars,
70
+ outputMarker(result.toolCallId, result.textLength, 0, 0).length
71
+ );
72
+ if (inlineNow <= target) continue;
73
+ previewChars.set(result.toolCallId, target);
74
+ inlineChars -= inlineNow - target;
75
+ }
76
+ if (inlineChars <= budget.stepBudgetChars) return previewChars;
77
+ for (const result of [...results].sort(
78
+ (a, b) => (previewChars.get(b.toolCallId) ?? b.textLength) - (previewChars.get(a.toolCallId) ?? a.textLength)
79
+ )) {
80
+ if (inlineChars <= budget.stepBudgetChars) break;
81
+ const inlineNow = previewChars.get(result.toolCallId) ?? result.textLength;
82
+ const minimum = outputMarker(result.toolCallId, result.textLength, 0, 0).length;
83
+ const target = Math.max(minimum, inlineNow - (inlineChars - budget.stepBudgetChars));
84
+ if (target >= inlineNow) continue;
85
+ previewChars.set(result.toolCallId, target);
86
+ inlineChars -= inlineNow - target;
63
87
  }
64
88
  return previewChars;
65
89
  }
66
90
  function withToolOutputPreview(result, fullText, previewChars) {
67
- const headChars = Math.floor(previewChars * PREVIEW_HEAD_RATIO);
68
- const tailChars = previewChars - headChars;
69
91
  const id = result.meta.toolCallId;
70
- const preview = `${fullText.slice(0, headChars)}
71
-
72
- [Output truncated: showing the first ${headChars} and last ${tailChars} of ${fullText.length} characters. The full output is stored. Read any part with ${TOOL_OUTPUT_READ_TOOL_NAME}({ "id": "${id}", "offset": <line> }) or search it with ${TOOL_OUTPUT_READ_TOOL_NAME}({ "id": "${id}", "pattern": "<text>" }) instead of re-running the tool.]
73
-
74
- ` + fullText.slice(fullText.length - tailChars);
92
+ const marker = (head, tail) => outputMarker(id, fullText.length, head, tail);
93
+ const available = Math.max(0, previewChars - marker(previewChars, previewChars).length);
94
+ const headChars = (0, import_text_boundary.safeTextBoundary)(fullText, Math.floor(available * PREVIEW_HEAD_RATIO));
95
+ const tailStart = fullText.length - (available - Math.floor(available * PREVIEW_HEAD_RATIO));
96
+ const safeTailStart = (0, import_text_boundary.safeTextBoundary)(fullText, tailStart) === tailStart ? tailStart : tailStart + 1;
97
+ const tailChars = fullText.length - safeTailStart;
98
+ const previewMarker = marker(headChars, tailChars);
99
+ const preview = fullText.slice(0, headChars) + previewMarker + fullText.slice(safeTailStart);
75
100
  const content = [];
76
101
  let previewAdded = false;
77
102
  for (const part of result.content) {
@@ -84,6 +109,13 @@ function withToolOutputPreview(result, fullText, previewChars) {
84
109
  }
85
110
  return { ...result, content };
86
111
  }
112
+ function outputMarker(id, length, head, tail) {
113
+ return `
114
+
115
+ [Output truncated: showing the first ${head} and last ${tail} of ${length} characters. The full output is stored. Read any part with ${TOOL_OUTPUT_READ_TOOL_NAME}({ "id": "${id}", "offset": <line> }) or search it with ${TOOL_OUTPUT_READ_TOOL_NAME}({ "id": "${id}", "pattern": "<text>" }) instead of re-running the tool.]
116
+
117
+ `;
118
+ }
87
119
  // Annotate the CommonJS export names for ESM import in node:
88
120
  0 && (module.exports = {
89
121
  TOOL_OUTPUT_READ_TOOL_NAME,
@@ -1 +1 @@
1
- {"version":3,"file":"tool-output-spill.d.ts","sourceRoot":"","sources":["../../../src/llm/executor/tool-output-spill.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAe,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAE/E,2DAA2D;AAC3D,eAAO,MAAM,0BAA0B,qBAAqB,CAAC;AAgB7D,MAAM,WAAW,gBAAgB;IAC7B,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,MAAM,CAAC;CAC3B;AAED,wBAAgB,gBAAgB,CAAC,cAAc,EAAE,MAAM,GAAG,gBAAgB,CAOzE;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,mBAAmB,GAAG,MAAM,CAElE;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAChC,OAAO,EAAE,aAAa,CAAC;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,EAClE,MAAM,EAAE,gBAAgB,GACzB,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAwBrB;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACjC,MAAM,EAAE,mBAAmB,EAC3B,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,MAAM,GACrB,mBAAmB,CAqBrB"}
1
+ {"version":3,"file":"tool-output-spill.d.ts","sourceRoot":"","sources":["../../../src/llm/executor/tool-output-spill.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAe,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAE/E,2DAA2D;AAC3D,eAAO,MAAM,0BAA0B,qBAAqB,CAAC;AAc7D,MAAM,WAAW,gBAAgB;IAC7B,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,MAAM,CAAC;CAC3B;AAED,wBAAgB,gBAAgB,CAAC,cAAc,EAAE,MAAM,GAAG,gBAAgB,CAOzE;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,mBAAmB,GAAG,MAAM,CAElE;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAChC,OAAO,EAAE,aAAa,CAAC;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,EAClE,MAAM,EAAE,gBAAgB,GACzB,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAqDrB;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACjC,MAAM,EAAE,mBAAmB,EAC3B,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,MAAM,GACrB,mBAAmB,CAuBrB"}
@@ -1,10 +1,10 @@
1
1
  import "../../chunk-C6A6W6XS.js";
2
+ import { safeTextBoundary } from "../../utils/text-boundary.js";
2
3
  const TOOL_OUTPUT_READ_TOOL_NAME = "tool_output_read";
3
4
  const CHARS_PER_TOKEN = 4;
4
5
  const MAX_INLINE_TOKENS = 4e3;
5
6
  const INLINE_WINDOW_RATIO = 0.1;
6
7
  const STEP_WINDOW_RATIO = 0.4;
7
- const STEP_SPILL_PREVIEW_CHARS = 16e3;
8
8
  const PREVIEW_HEAD_RATIO = 0.75;
9
9
  function toolOutputBudget(maxInputTokens) {
10
10
  return {
@@ -20,32 +20,57 @@ function planToolOutputSpills(results, budget) {
20
20
  let inlineChars = 0;
21
21
  for (const result of results) {
22
22
  if (result.textLength > budget.inlineCapChars) {
23
- previewChars.set(result.toolCallId, budget.inlineCapChars);
24
- inlineChars += budget.inlineCapChars;
23
+ const cap = Math.max(
24
+ budget.inlineCapChars,
25
+ outputMarker(result.toolCallId, result.textLength, 0, 0).length
26
+ );
27
+ if (cap < result.textLength) {
28
+ previewChars.set(result.toolCallId, cap);
29
+ inlineChars += cap;
30
+ } else {
31
+ inlineChars += result.textLength;
32
+ }
25
33
  } else {
26
34
  inlineChars += result.textLength;
27
35
  }
28
36
  }
29
- const stepPreviewChars = Math.min(budget.inlineCapChars, STEP_SPILL_PREVIEW_CHARS);
37
+ const stepPreviewChars = Math.floor(budget.inlineCapChars / 2);
30
38
  const largestFirst = results.filter((result) => result.textLength > stepPreviewChars).sort((left, right) => right.textLength - left.textLength);
31
39
  for (const result of largestFirst) {
32
40
  if (inlineChars <= budget.stepBudgetChars) break;
33
41
  const inlineNow = previewChars.get(result.toolCallId) ?? result.textLength;
34
- if (inlineNow <= stepPreviewChars) continue;
35
- previewChars.set(result.toolCallId, stepPreviewChars);
36
- inlineChars -= inlineNow - stepPreviewChars;
42
+ const target = Math.max(
43
+ stepPreviewChars,
44
+ outputMarker(result.toolCallId, result.textLength, 0, 0).length
45
+ );
46
+ if (inlineNow <= target) continue;
47
+ previewChars.set(result.toolCallId, target);
48
+ inlineChars -= inlineNow - target;
49
+ }
50
+ if (inlineChars <= budget.stepBudgetChars) return previewChars;
51
+ for (const result of [...results].sort(
52
+ (a, b) => (previewChars.get(b.toolCallId) ?? b.textLength) - (previewChars.get(a.toolCallId) ?? a.textLength)
53
+ )) {
54
+ if (inlineChars <= budget.stepBudgetChars) break;
55
+ const inlineNow = previewChars.get(result.toolCallId) ?? result.textLength;
56
+ const minimum = outputMarker(result.toolCallId, result.textLength, 0, 0).length;
57
+ const target = Math.max(minimum, inlineNow - (inlineChars - budget.stepBudgetChars));
58
+ if (target >= inlineNow) continue;
59
+ previewChars.set(result.toolCallId, target);
60
+ inlineChars -= inlineNow - target;
37
61
  }
38
62
  return previewChars;
39
63
  }
40
64
  function withToolOutputPreview(result, fullText, previewChars) {
41
- const headChars = Math.floor(previewChars * PREVIEW_HEAD_RATIO);
42
- const tailChars = previewChars - headChars;
43
65
  const id = result.meta.toolCallId;
44
- const preview = `${fullText.slice(0, headChars)}
45
-
46
- [Output truncated: showing the first ${headChars} and last ${tailChars} of ${fullText.length} characters. The full output is stored. Read any part with ${TOOL_OUTPUT_READ_TOOL_NAME}({ "id": "${id}", "offset": <line> }) or search it with ${TOOL_OUTPUT_READ_TOOL_NAME}({ "id": "${id}", "pattern": "<text>" }) instead of re-running the tool.]
47
-
48
- ` + fullText.slice(fullText.length - tailChars);
66
+ const marker = (head, tail) => outputMarker(id, fullText.length, head, tail);
67
+ const available = Math.max(0, previewChars - marker(previewChars, previewChars).length);
68
+ const headChars = safeTextBoundary(fullText, Math.floor(available * PREVIEW_HEAD_RATIO));
69
+ const tailStart = fullText.length - (available - Math.floor(available * PREVIEW_HEAD_RATIO));
70
+ const safeTailStart = safeTextBoundary(fullText, tailStart) === tailStart ? tailStart : tailStart + 1;
71
+ const tailChars = fullText.length - safeTailStart;
72
+ const previewMarker = marker(headChars, tailChars);
73
+ const preview = fullText.slice(0, headChars) + previewMarker + fullText.slice(safeTailStart);
49
74
  const content = [];
50
75
  let previewAdded = false;
51
76
  for (const part of result.content) {
@@ -58,6 +83,13 @@ function withToolOutputPreview(result, fullText, previewChars) {
58
83
  }
59
84
  return { ...result, content };
60
85
  }
86
+ function outputMarker(id, length, head, tail) {
87
+ return `
88
+
89
+ [Output truncated: showing the first ${head} and last ${tail} of ${length} characters. The full output is stored. Read any part with ${TOOL_OUTPUT_READ_TOOL_NAME}({ "id": "${id}", "offset": <line> }) or search it with ${TOOL_OUTPUT_READ_TOOL_NAME}({ "id": "${id}", "pattern": "<text>" }) instead of re-running the tool.]
90
+
91
+ `;
92
+ }
61
93
  export {
62
94
  TOOL_OUTPUT_READ_TOOL_NAME,
63
95
  planToolOutputSpills,
@@ -6,7 +6,7 @@ export * from './validation.js';
6
6
  export * from './usage-metadata.js';
7
7
  export * from './usage-scope.js';
8
8
  export * from './usage-summary.js';
9
- export type { LlmAuthResolver, LlmRuntimeAuthOverrides, ResolveLlmRuntimeAuthInput, } from './auth/index.js';
9
+ export type { LlmAuthResolver, LlmRequestAuth, LlmRuntimeAuthOverrides, ResolveLlmRuntimeAuthInput, } from './auth/index.js';
10
10
  export * from './services/index.js';
11
11
  export * from './executor/index.js';
12
12
  export * from './schemas.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/llm/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AACpC,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,YAAY,EACR,eAAe,EACf,uBAAuB,EACvB,0BAA0B,GAC7B,MAAM,iBAAiB,CAAC;AACzB,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,cAAc,CAAC;AAC7B,OAAO,EACH,iCAAiC,EACjC,qBAAqB,EACrB,8BAA8B,EAC9B,2BAA2B,EAC3B,2BAA2B,EAC3B,+BAA+B,EAC/B,sBAAsB,EACtB,KAAK,YAAY,EACjB,KAAK,mBAAmB,GAC3B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACH,kBAAkB,EAClB,qBAAqB,EACrB,2BAA2B,EAC3B,cAAc,EACd,iBAAiB,EACj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BAAuB,EACvB,oBAAoB,EACpB,8BAA8B,EAC9B,KAAK,2BAA2B,GACnC,MAAM,2BAA2B,CAAC;AAGnC,cAAc,4BAA4B,CAAC"}
@@ -34,6 +34,7 @@ __export(factory_exports, {
34
34
  module.exports = __toCommonJS(factory_exports);
35
35
  var import_errors = require("../errors.js");
36
36
  var import_vercel = require("./vercel.js");
37
+ var import_ai = require("ai");
37
38
  var import_llm = require("@dexto/llm");
38
39
  var import_api_key_resolver = require("../../utils/api-key-resolver.js");
39
40
  var import_codex_base_url = require("../providers/codex-base-url.js");
@@ -98,13 +99,111 @@ function logRuntimeAuthResolution(input) {
98
99
  model,
99
100
  auth,
100
101
  runtime: {
101
- hasRuntimeFetch: Boolean(runtimeAuth?.fetch),
102
+ hasRuntimeFetch: Boolean(runtimeAuth?.fetch || runtimeAuth?.requestAuth),
102
103
  hasRuntimeHeaders: Boolean(runtimeAuth?.headers),
103
104
  hasRuntimeBaseURL: Boolean(runtimeAuth?.baseURL),
104
105
  hasEffectiveBaseURL: Boolean(effectiveBaseURL)
105
106
  }
106
107
  });
107
108
  }
109
+ const MAX_RETRY_ERROR_BODY_BYTES = 64 * 1024;
110
+ function boundedClassificationResponse(response) {
111
+ const clone = response.clone();
112
+ if (!clone.body) return { view: clone, cancel: () => {
113
+ } };
114
+ const reader = clone.body.getReader();
115
+ let remaining = MAX_RETRY_ERROR_BODY_BYTES;
116
+ const body = new globalThis.ReadableStream({
117
+ async pull(controller) {
118
+ try {
119
+ const chunk = await reader.read();
120
+ if (chunk.done) {
121
+ controller.close();
122
+ return;
123
+ }
124
+ const part = chunk.value.subarray(0, remaining);
125
+ remaining -= part.byteLength;
126
+ if (part.byteLength) controller.enqueue(part);
127
+ if (remaining === 0) {
128
+ void reader.cancel().catch(() => {
129
+ });
130
+ controller.close();
131
+ }
132
+ } catch (error) {
133
+ controller.error(error);
134
+ }
135
+ },
136
+ cancel() {
137
+ void reader.cancel().catch(() => {
138
+ });
139
+ }
140
+ });
141
+ const view = new globalThis.Response(body, {
142
+ status: clone.status,
143
+ statusText: clone.statusText,
144
+ headers: clone.headers
145
+ });
146
+ Object.defineProperties(view, {
147
+ url: { value: response.url },
148
+ redirected: { value: response.redirected }
149
+ });
150
+ return {
151
+ view,
152
+ cancel: () => {
153
+ void reader.cancel().catch(() => {
154
+ });
155
+ }
156
+ };
157
+ }
158
+ function rethrowAbort(error, signal) {
159
+ if (signal?.aborted || error instanceof Error && error.name === "AbortError") throw error;
160
+ }
161
+ async function readRetryErrorBody(response, signal) {
162
+ if (signal?.aborted) {
163
+ void response.body?.cancel().catch(() => {
164
+ });
165
+ throw new globalThis.DOMException("Request aborted", "AbortError");
166
+ }
167
+ if (!response.body) return "";
168
+ const reader = response.body.getReader();
169
+ const decoder = new globalThis.TextDecoder();
170
+ let body = "";
171
+ let bytes = 0;
172
+ let onAbort;
173
+ const aborted = signal ? new Promise((_, reject) => {
174
+ onAbort = () => {
175
+ reject(new globalThis.DOMException("Request aborted", "AbortError"));
176
+ void reader.cancel().catch(() => {
177
+ });
178
+ };
179
+ if (signal.aborted) onAbort();
180
+ else signal.addEventListener("abort", onAbort, { once: true });
181
+ }) : void 0;
182
+ void aborted?.catch(() => {
183
+ });
184
+ try {
185
+ for (; ; ) {
186
+ if (signal?.aborted) throw new globalThis.DOMException("Request aborted", "AbortError");
187
+ const read = reader.read();
188
+ const chunk = aborted ? await Promise.race([read, aborted]) : await read;
189
+ if (chunk.done) break;
190
+ const remaining = MAX_RETRY_ERROR_BODY_BYTES - bytes;
191
+ body += decoder.decode(chunk.value.subarray(0, remaining), { stream: true });
192
+ bytes += chunk.value.byteLength;
193
+ if (bytes >= MAX_RETRY_ERROR_BODY_BYTES) {
194
+ void reader.cancel().catch(() => {
195
+ });
196
+ break;
197
+ }
198
+ }
199
+ body += decoder.decode();
200
+ } catch (error) {
201
+ rethrowAbort(error, signal);
202
+ } finally {
203
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
204
+ }
205
+ return body;
206
+ }
108
207
  async function createVercelModel(llmConfig, context) {
109
208
  const { provider, model, baseURL } = llmConfig;
110
209
  const runtimeAuth = context?.authResolver?.resolveRuntimeAuth({
@@ -117,9 +216,68 @@ async function createVercelModel(llmConfig, context) {
117
216
  const apiKey = runtimeAuth?.apiKey || llmConfig.apiKey || resolvedProviderApiKey;
118
217
  const runtimeBaseURL = runtimeAuth?.baseURL;
119
218
  const runtimeHeaders = runtimeAuth?.headers;
120
- const runtimeFetch = runtimeAuth?.fetch;
121
- const effectiveBaseURL = runtimeBaseURL?.replace(/\/$/, "") || baseURL?.replace(/\/$/, "");
219
+ if (runtimeBaseURL !== void 0 && !runtimeBaseURL.trim()) {
220
+ throw import_errors.LLMError.invalidRuntimeBaseURL(provider);
221
+ }
222
+ const requestAuth = runtimeAuth?.requestAuth;
223
+ if (requestAuth && runtimeAuth?.fetch) {
224
+ throw import_errors.LLMError.runtimeAuthConflict(provider);
225
+ }
226
+ const runtimeFetch = requestAuth ? async (input, init) => {
227
+ const { response, provenance } = await requestAuth.fetch(input, init);
228
+ if (response.ok) return response;
229
+ const signal = init?.signal ?? (input instanceof globalThis.Request ? input.signal : void 0);
230
+ const classification = boundedClassificationResponse(response);
231
+ let retryable;
232
+ let onAbort;
233
+ try {
234
+ const decision = requestAuth.isRetryableResponse({
235
+ response: classification.view,
236
+ provenance,
237
+ ...signal ? { signal } : {}
238
+ });
239
+ if (signal) {
240
+ const aborted = new Promise((_, reject) => {
241
+ onAbort = () => reject(new globalThis.DOMException("Request aborted", "AbortError"));
242
+ if (signal.aborted) onAbort();
243
+ else signal.addEventListener("abort", onAbort, { once: true });
244
+ });
245
+ retryable = await Promise.race([decision, aborted]);
246
+ } else retryable = await decision;
247
+ } catch (error) {
248
+ if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
249
+ void response.body?.cancel().catch(() => {
250
+ });
251
+ }
252
+ rethrowAbort(error, signal);
253
+ return response;
254
+ } finally {
255
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
256
+ classification.cancel();
257
+ }
258
+ if (!retryable) return response;
259
+ const responseHeaders = {};
260
+ response.headers.forEach((value, key) => {
261
+ responseHeaders[key] = value;
262
+ });
263
+ throw new import_ai.APICallError({
264
+ message: "Host classified model request failure as retryable",
265
+ url: typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url,
266
+ requestBodyValues: {},
267
+ statusCode: response.status,
268
+ responseHeaders,
269
+ responseBody: await readRetryErrorBody(response, signal),
270
+ isRetryable: true
271
+ });
272
+ } : runtimeAuth?.fetch;
273
+ const effectiveBaseURL = runtimeBaseURL?.trim().replace(/\/$/, "") || baseURL?.trim().replace(/\/$/, "");
122
274
  const usesCodexRuntimeAuth = runtimeBaseURL ? (0, import_codex_base_url.isCodexBaseURL)(runtimeBaseURL) : false;
275
+ if ((provider === "bedrock" || provider === "local") && (runtimeBaseURL !== void 0 || runtimeHeaders !== void 0 || runtimeAuth?.fetch || requestAuth)) {
276
+ throw import_errors.LLMError.runtimeAuthUnsupported(provider);
277
+ }
278
+ if (usesCodexRuntimeAuth && (runtimeHeaders !== void 0 || runtimeAuth?.fetch || requestAuth)) {
279
+ throw import_errors.LLMError.runtimeAuthUnsupported(provider);
280
+ }
123
281
  logRuntimeAuthResolution({
124
282
  context,
125
283
  provider,
@@ -129,7 +287,7 @@ async function createVercelModel(llmConfig, context) {
129
287
  runtimeAuth,
130
288
  effectiveBaseURL
131
289
  });
132
- if ((0, import_llm.requiresApiKey)(provider) && !usesCodexRuntimeAuth && !apiKey?.trim()) {
290
+ if ((0, import_llm.requiresApiKey)(provider) && !usesCodexRuntimeAuth && !apiKey?.trim() && !requestAuth) {
133
291
  const envVar = (0, import_api_key_resolver.getPrimaryApiKeyEnvVar)(provider);
134
292
  throw import_errors.LLMError.apiKeyMissing(provider, envVar);
135
293
  }
@@ -168,12 +326,14 @@ async function createVercelModel(llmConfig, context) {
168
326
  return provider2.chatModel(model);
169
327
  }
170
328
  case "openrouter": {
171
- const orBaseURL = baseURL || "https://openrouter.ai/api/v1";
329
+ const orBaseURL = effectiveBaseURL || "https://openrouter.ai/api/v1";
172
330
  const { createOpenRouter } = await import("@openrouter/ai-sdk-provider");
173
331
  const provider2 = createOpenRouter({
174
332
  apiKey: apiKey ?? "",
175
333
  baseURL: orBaseURL,
176
- compatibility: "strict"
334
+ compatibility: "strict",
335
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
336
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
177
337
  });
178
338
  const chatModel = provider2.chat(model);
179
339
  if (!isLanguageModel(chatModel)) {
@@ -228,7 +388,9 @@ async function createVercelModel(llmConfig, context) {
228
388
  }).chat(model);
229
389
  }
230
390
  case "dexto-nova": {
231
- const dextoBaseURL = resolveDextoGatewayBaseURL(baseURL);
391
+ const dextoBaseURL = resolveDextoGatewayBaseURL(
392
+ runtimeBaseURL?.trim() ? runtimeBaseURL : baseURL
393
+ );
232
394
  const headers = {
233
395
  ...runtimeHeaders ?? {},
234
396
  [DEXTO_GATEWAY_HEADERS.CLIENT_SOURCE]: context?.clientSource ?? "cli"
@@ -244,7 +406,7 @@ async function createVercelModel(llmConfig, context) {
244
406
  baseURL: dextoBaseURL,
245
407
  compatibility: "strict",
246
408
  headers,
247
- ...apiKey?.trim() ? { apiKey } : {},
409
+ ...apiKey?.trim() ? { apiKey } : requestAuth ? { apiKey: "" } : {},
248
410
  ...runtimeFetch ? { fetch: runtimeFetch } : {}
249
411
  });
250
412
  const chatModel = provider2.chat(model);
@@ -274,18 +436,26 @@ async function createVercelModel(llmConfig, context) {
274
436
  }
275
437
  const location = process.env.GOOGLE_VERTEX_LOCATION;
276
438
  if (model.includes("claude")) {
277
- const headers = (0, import_llm.supportsAnthropicInterleavedThinking)(model) ? { [import_llm.ANTHROPIC_BETA_HEADER]: import_llm.ANTHROPIC_INTERLEAVED_THINKING_BETA } : void 0;
439
+ const headers = mergeHeaders(
440
+ (0, import_llm.supportsAnthropicInterleavedThinking)(model) ? { [import_llm.ANTHROPIC_BETA_HEADER]: import_llm.ANTHROPIC_INTERLEAVED_THINKING_BETA } : void 0,
441
+ runtimeHeaders
442
+ );
278
443
  const { createVertexAnthropic } = await import("@ai-sdk/google-vertex/anthropic");
279
444
  return createVertexAnthropic({
280
445
  project: projectId,
281
446
  location: location || "us-east5",
447
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
448
+ ...runtimeFetch ? { fetch: runtimeFetch } : {},
282
449
  ...headers ? { headers } : {}
283
450
  })(model);
284
451
  }
285
452
  const { createVertex } = await import("@ai-sdk/google-vertex");
286
453
  return createVertex({
287
454
  project: projectId,
288
- location: location || "us-central1"
455
+ location: location || "us-central1",
456
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
457
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
458
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
289
459
  })(model);
290
460
  }
291
461
  case "bedrock": {
@@ -320,19 +490,39 @@ async function createVercelModel(llmConfig, context) {
320
490
  }
321
491
  case "google": {
322
492
  const { createGoogleGenerativeAI } = await import("@ai-sdk/google");
323
- return createGoogleGenerativeAI({ apiKey: apiKey ?? "" })(model);
493
+ return createGoogleGenerativeAI({
494
+ apiKey: apiKey ?? "",
495
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
496
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
497
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
498
+ })(model);
324
499
  }
325
500
  case "groq": {
326
501
  const { createGroq } = await import("@ai-sdk/groq");
327
- return createGroq({ apiKey: apiKey ?? "" })(model);
502
+ return createGroq({
503
+ apiKey: apiKey ?? "",
504
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
505
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
506
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
507
+ })(model);
328
508
  }
329
509
  case "xai": {
330
510
  const { createXai } = await import("@ai-sdk/xai");
331
- return createXai({ apiKey: apiKey ?? "" })(model);
511
+ return createXai({
512
+ apiKey: apiKey ?? "",
513
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
514
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
515
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
516
+ })(model);
332
517
  }
333
518
  case "cohere": {
334
519
  const { createCohere } = await import("@ai-sdk/cohere");
335
- return createCohere({ apiKey: apiKey ?? "" })(model);
520
+ return createCohere({
521
+ apiKey: apiKey ?? "",
522
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
523
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
524
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
525
+ })(model);
336
526
  }
337
527
  case "ollama": {
338
528
  const ollamaBaseURL = effectiveBaseURL || "http://localhost:11434/v1";
@@ -2,7 +2,7 @@ import type { ToolOutputStore } from '../../storage/tool-outputs/types.js';
2
2
  import { ToolManager } from '../../tools/tool-manager.js';
3
3
  import { ValidatedLLMConfig } from '../schemas.js';
4
4
  import { VercelLLMService } from './vercel.js';
5
- import type { LanguageModel } from 'ai';
5
+ import { type LanguageModel } from 'ai';
6
6
  import { SessionEventBus } from '../../events/index.js';
7
7
  import type { ConversationStore } from '../../storage/conversation/types.js';
8
8
  import type { SystemPromptManager } from '../../systemPrompt/manager.js';
@@ -1 +1 @@
1
- {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../../src/llm/services/factory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CA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