@dexto/core 1.16.5 → 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.
@@ -1,2 +1,2 @@
1
- export type { LlmAuthResolver, LlmRuntimeAuthOverrides, ResolveLlmRuntimeAuthInput, } from './types.js';
1
+ export type { LlmAuthResolver, LlmRequestAuth, LlmRuntimeAuthOverrides, ResolveLlmRuntimeAuthInput, } from './types.js';
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/llm/auth/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACR,eAAe,EACf,uBAAuB,EACvB,0BAA0B,GAC7B,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/llm/auth/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACR,eAAe,EACf,cAAc,EACd,uBAAuB,EACvB,0BAA0B,GAC7B,MAAM,YAAY,CAAC"}
@@ -4,8 +4,22 @@ export type LlmRuntimeAuthOverrides = {
4
4
  baseURL?: string | undefined;
5
5
  headers?: Record<string, string> | undefined;
6
6
  fetch?: typeof fetch | undefined;
7
+ /** Optional host-owned credential provenance and failure classification for each request. */
8
+ requestAuth?: LlmRequestAuth | undefined;
7
9
  auth?: LlmRuntimeAuthInfo | undefined;
8
10
  };
11
+ /** Request authentication may replace the API key. The classification body is bounded to 64 KiB. */
12
+ export type LlmRequestAuth = {
13
+ fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<{
14
+ response: Response;
15
+ provenance: unknown;
16
+ }>;
17
+ isRetryableResponse: (input: {
18
+ response: Response;
19
+ provenance: unknown;
20
+ signal?: AbortSignal | null;
21
+ }) => Promise<boolean>;
22
+ };
9
23
  export type LlmRuntimeAuthInfo = {
10
24
  source: 'profile';
11
25
  profileId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/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EY_CANDIDATE_MISSING"] = "llm_api_key_candidate_missing";
28
28
  LLMErrorCode2["BASE_URL_MISSING"] = "llm_base_url_missing";
29
29
  LLMErrorCode2["BASE_URL_INVALID"] = "llm_base_url_invalid";
30
+ LLMErrorCode2["RUNTIME_AUTH_UNSUPPORTED"] = "llm_runtime_auth_unsupported";
31
+ LLMErrorCode2["RUNTIME_AUTH_CONFLICT"] = "llm_runtime_auth_conflict";
30
32
  LLMErrorCode2["CONFIG_MISSING"] = "llm_config_missing";
31
33
  LLMErrorCode2["MODEL_INCOMPATIBLE"] = "llm_model_incompatible";
32
34
  LLMErrorCode2["MODEL_UNKNOWN"] = "llm_model_unknown";
@@ -8,6 +8,8 @@ export declare enum LLMErrorCode {
8
8
  API_KEY_CANDIDATE_MISSING = "llm_api_key_candidate_missing",
9
9
  BASE_URL_MISSING = "llm_base_url_missing",
10
10
  BASE_URL_INVALID = "llm_base_url_invalid",
11
+ RUNTIME_AUTH_UNSUPPORTED = "llm_runtime_auth_unsupported",
12
+ RUNTIME_AUTH_CONFLICT = "llm_runtime_auth_conflict",
11
13
  CONFIG_MISSING = "llm_config_missing",// Required config (e.g., GOOGLE_VERTEX_PROJECT)
12
14
  MODEL_INCOMPATIBLE = "llm_model_incompatible",
13
15
  MODEL_UNKNOWN = "llm_model_unknown",
@@ -1 +1 @@
1
- {"version":3,"file":"error-codes.d.ts","sourceRoot":"","sources":["../../src/llm/error-codes.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,oBAAY,YAAY;IAEpB,eAAe,wBAAwB;IACvC,eAAe,wBAAwB,CAAE,0BAA0B;IACnE,yBAAyB,kCAAkC;IAC3D,gBAAgB,yBAAyB;IACzC,gBAAgB,yBAAyB;IACzC,cAAc,uBAAuB,CAAE,gDAAgD;IAGvF,kBAAkB,2BAA2B;IAC7C,aAAa,sBAAsB;IACnC,oBAAoB,6BAA6B;IAGjD,sBAAsB,+BAA+B;IACrD,uBAAuB,gCAAgC;IACvD,kBAAkB,2BAA2B;IAG7C,eAAe,wBAAwB;IACvC,mBAAmB,4BAA4B;IAC/C,oBAAoB,6BAA6B;IAGjD,aAAa,sBAAsB;IACnC,iBAAiB,0BAA0B;IAC3C,cAAc,uBAAuB,CAAE,0DAA0D;IACjG,cAAc,uBAAuB,CAAE,+CAA+C;IAGtF,oBAAoB,6BAA6B,CAAE,+CAA+C;IAGlG,sBAAsB,+BAA+B;CACxD"}
1
+ {"version":3,"file":"error-codes.d.ts","sourceRoot":"","sources":["../../src/llm/error-codes.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,oBAAY,YAAY;IAEpB,eAAe,wBAAwB;IACvC,eAAe,wBAAwB,CAAE,0BAA0B;IACnE,yBAAyB,kCAAkC;IAC3D,gBAAgB,yBAAyB;IACzC,gBAAgB,yBAAyB;IACzC,wBAAwB,iCAAiC;IACzD,qBAAqB,8BAA8B;IACnD,cAAc,uBAAuB,CAAE,gDAAgD;IAGvF,kBAAkB,2BAA2B;IAC7C,aAAa,sBAAsB;IACnC,oBAAoB,6BAA6B;IAGjD,sBAAsB,+BAA+B;IACrD,uBAAuB,gCAAgC;IACvD,kBAAkB,2BAA2B;IAG7C,eAAe,wBAAwB;IACvC,mBAAmB,4BAA4B;IAC/C,oBAAoB,6BAA6B;IAGjD,aAAa,sBAAsB;IACnC,iBAAiB,0BAA0B;IAC3C,cAAc,uBAAuB,CAAE,0DAA0D;IACjG,cAAc,uBAAuB,CAAE,+CAA+C;IAGtF,oBAAoB,6BAA6B,CAAE,+CAA+C;IAGlG,sBAAsB,+BAA+B;CACxD"}
@@ -5,6 +5,8 @@ var LLMErrorCode = /* @__PURE__ */ ((LLMErrorCode2) => {
5
5
  LLMErrorCode2["API_KEY_CANDIDATE_MISSING"] = "llm_api_key_candidate_missing";
6
6
  LLMErrorCode2["BASE_URL_MISSING"] = "llm_base_url_missing";
7
7
  LLMErrorCode2["BASE_URL_INVALID"] = "llm_base_url_invalid";
8
+ LLMErrorCode2["RUNTIME_AUTH_UNSUPPORTED"] = "llm_runtime_auth_unsupported";
9
+ LLMErrorCode2["RUNTIME_AUTH_CONFLICT"] = "llm_runtime_auth_conflict";
8
10
  LLMErrorCode2["CONFIG_MISSING"] = "llm_config_missing";
9
11
  LLMErrorCode2["MODEL_INCOMPATIBLE"] = "llm_model_incompatible";
10
12
  LLMErrorCode2["MODEL_UNKNOWN"] = "llm_model_unknown";
@@ -46,6 +46,33 @@ class LLMError {
46
46
  { provider }
47
47
  );
48
48
  }
49
+ static runtimeAuthUnsupported(provider) {
50
+ return new import_DextoRuntimeError.DextoRuntimeError(
51
+ import_error_codes.LLMErrorCode.RUNTIME_AUTH_UNSUPPORTED,
52
+ import_types.ErrorScope.LLM,
53
+ import_types2.ErrorType.USER,
54
+ `Provider '${provider}' cannot use these runtime gateway overrides`,
55
+ { provider }
56
+ );
57
+ }
58
+ static invalidRuntimeBaseURL(provider) {
59
+ return new import_DextoRuntimeError.DextoRuntimeError(
60
+ import_error_codes.LLMErrorCode.BASE_URL_INVALID,
61
+ import_types.ErrorScope.LLM,
62
+ import_types2.ErrorType.USER,
63
+ `Runtime baseURL for '${provider}' cannot be blank`,
64
+ { provider }
65
+ );
66
+ }
67
+ static runtimeAuthConflict(provider) {
68
+ return new import_DextoRuntimeError.DextoRuntimeError(
69
+ import_error_codes.LLMErrorCode.RUNTIME_AUTH_CONFLICT,
70
+ import_types.ErrorScope.LLM,
71
+ import_types2.ErrorType.USER,
72
+ "Runtime auth cannot supply both fetch and requestAuth",
73
+ { provider }
74
+ );
75
+ }
49
76
  static missingConfig(provider, configName) {
50
77
  return new import_DextoRuntimeError.DextoRuntimeError(
51
78
  import_error_codes.LLMErrorCode.CONFIG_MISSING,
@@ -15,6 +15,15 @@ export declare class LLMError {
15
15
  static baseUrlMissing(provider: LLMProvider): DextoRuntimeError<{
16
16
  provider: "local" | "openai" | "openai-compatible" | "anthropic" | "google" | "groq" | "xai" | "cohere" | "minimax" | "glm" | "openrouter" | "litellm" | "glama" | "vertex" | "bedrock" | "ollama" | "dexto-nova";
17
17
  }>;
18
+ static runtimeAuthUnsupported(provider: LLMProvider): DextoRuntimeError<{
19
+ provider: "local" | "openai" | "openai-compatible" | "anthropic" | "google" | "groq" | "xai" | "cohere" | "minimax" | "glm" | "openrouter" | "litellm" | "glama" | "vertex" | "bedrock" | "ollama" | "dexto-nova";
20
+ }>;
21
+ static invalidRuntimeBaseURL(provider: LLMProvider): DextoRuntimeError<{
22
+ provider: "local" | "openai" | "openai-compatible" | "anthropic" | "google" | "groq" | "xai" | "cohere" | "minimax" | "glm" | "openrouter" | "litellm" | "glama" | "vertex" | "bedrock" | "ollama" | "dexto-nova";
23
+ }>;
24
+ static runtimeAuthConflict(provider: LLMProvider): DextoRuntimeError<{
25
+ provider: "local" | "openai" | "openai-compatible" | "anthropic" | "google" | "groq" | "xai" | "cohere" | "minimax" | "glm" | "openrouter" | "litellm" | "glama" | "vertex" | "bedrock" | "ollama" | "dexto-nova";
26
+ }>;
18
27
  static missingConfig(provider: LLMProvider, configName: string): DextoRuntimeError<{
19
28
  provider: "local" | "openai" | "openai-compatible" | "anthropic" | "google" | "groq" | "xai" | "cohere" | "minimax" | "glm" | "openrouter" | "litellm" | "glama" | "vertex" | "bedrock" | "ollama" | "dexto-nova";
20
29
  configName: string;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/llm/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAKnE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C;;;;;;GAMG;AACH,qBAAa,QAAQ;IAEjB,MAAM,CAAC,YAAY,CAAC,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM;;;;IAUxD,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,WAAW;;;IAU3C,MAAM,CAAC,aAAa,CAAC,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM;;;;IAU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,EAAE,WAAW;;;IAUhD,MAAM,CAAC,aAAa,CAAC,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM;;;;IAU9D,MAAM,CAAC,mBAAmB,CAAC,QAAQ,EAAE,MAAM;;;;IAW3C;;;;OAIG;IACH,MAAM,CAAC,aAAa,CAAC,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM;;;;IAW1D,MAAM,CAAC,oBAAoB,CAAC,KAAK,EAAE,MAAM;;;;IAczC,MAAM,CAAC,iBAAiB,CAAC,QAAQ,EAAE,WAAW,EAAE,UAAU,CAAC,EAAE,MAAM;;;;;;;IAenE;;;OAGG;IACH,MAAM,CAAC,mBAAmB,CAAC,OAAO,CAAC,EAAE,MAAM;;;IAa3C,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM;;;;;;;IAU3E;;;OAGG;IACH,MAAM,CAAC,aAAa,CAAC,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;;;;;;;IAa3E,MAAM,CAAC,aAAa,CAAC,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM;;;;;;;IAchF,MAAM,CAAC,kBAAkB;CAU5B"}
@@ -24,6 +24,33 @@ class LLMError {
24
24
  { provider }
25
25
  );
26
26
  }
27
+ static runtimeAuthUnsupported(provider) {
28
+ return new DextoRuntimeError(
29
+ LLMErrorCode.RUNTIME_AUTH_UNSUPPORTED,
30
+ ErrorScope.LLM,
31
+ ErrorType.USER,
32
+ `Provider '${provider}' cannot use these runtime gateway overrides`,
33
+ { provider }
34
+ );
35
+ }
36
+ static invalidRuntimeBaseURL(provider) {
37
+ return new DextoRuntimeError(
38
+ LLMErrorCode.BASE_URL_INVALID,
39
+ ErrorScope.LLM,
40
+ ErrorType.USER,
41
+ `Runtime baseURL for '${provider}' cannot be blank`,
42
+ { provider }
43
+ );
44
+ }
45
+ static runtimeAuthConflict(provider) {
46
+ return new DextoRuntimeError(
47
+ LLMErrorCode.RUNTIME_AUTH_CONFLICT,
48
+ ErrorScope.LLM,
49
+ ErrorType.USER,
50
+ "Runtime auth cannot supply both fetch and requestAuth",
51
+ { provider }
52
+ );
53
+ }
27
54
  static missingConfig(provider, configName) {
28
55
  return new DextoRuntimeError(
29
56
  LLMErrorCode.CONFIG_MISSING,
@@ -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,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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,EACj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AA2B,EAC3B,cAAc,EACd,iBAAiB,EACjB,KAAK,aAAa,GACrB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACH,oBAAoB,EACpB,wBAAwB,EACxB,KAAK,2BAA2B,EAChC,KAAK,cAAc,EACnB,KAAK,sBAAsB,GAC9B,MAAM,iCAAiC,CAAC;AAGzC,OAAO,EACH,0BAA0B,EAC1B,uBAAuB,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,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;AAC1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAgB,KAAK,aAAa,EAAE,MAAM,IAAI,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAC7E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACzE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,KAAK,EACR,uBAAuB,EACvB,oBAAoB,EACpB,oBAAoB,EACvB,MAAM,YAAY,CAAC;AAwNpB;;;;;;;;;GASG;AACH,wBAAsB,iBAAiB,CACnC,SAAS,EAAE,kBAAkB,EAC7B,OAAO,CAAC,EAAE,oBAAoB,GAC/B,OAAO,CAAC,aAAa,CAAC,CA0bxB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,gBAAgB,CAClC,MAAM,EAAE,kBAAkB,EAC1B,WAAW,EAAE,WAAW,EACxB,mBAAmB,EAAE,mBAAmB,EACxC,iBAAiB,EAAE,iBAAiB,EACpC,eAAe,EAAE,eAAe,EAChC,eAAe,EAAE,eAAe,EAChC,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,OAAO,0BAA0B,EAAE,eAAe,EACnE,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,uBAAuB,EAChC,oBAAoB,CAAC,EAAE,oBAAoB,GAC5C,OAAO,CAAC,gBAAgB,CAAC,CA2C3B"}
@@ -1,6 +1,7 @@
1
1
  import "../../chunk-C6A6W6XS.js";
2
2
  import { LLMError } from "../errors.js";
3
3
  import { VercelLLMService } from "./vercel.js";
4
+ import { APICallError } from "ai";
4
5
  import {
5
6
  ANTHROPIC_BETA_HEADER,
6
7
  ANTHROPIC_INTERLEAVED_THINKING_BETA,
@@ -70,13 +71,111 @@ function logRuntimeAuthResolution(input) {
70
71
  model,
71
72
  auth,
72
73
  runtime: {
73
- hasRuntimeFetch: Boolean(runtimeAuth?.fetch),
74
+ hasRuntimeFetch: Boolean(runtimeAuth?.fetch || runtimeAuth?.requestAuth),
74
75
  hasRuntimeHeaders: Boolean(runtimeAuth?.headers),
75
76
  hasRuntimeBaseURL: Boolean(runtimeAuth?.baseURL),
76
77
  hasEffectiveBaseURL: Boolean(effectiveBaseURL)
77
78
  }
78
79
  });
79
80
  }
81
+ const MAX_RETRY_ERROR_BODY_BYTES = 64 * 1024;
82
+ function boundedClassificationResponse(response) {
83
+ const clone = response.clone();
84
+ if (!clone.body) return { view: clone, cancel: () => {
85
+ } };
86
+ const reader = clone.body.getReader();
87
+ let remaining = MAX_RETRY_ERROR_BODY_BYTES;
88
+ const body = new globalThis.ReadableStream({
89
+ async pull(controller) {
90
+ try {
91
+ const chunk = await reader.read();
92
+ if (chunk.done) {
93
+ controller.close();
94
+ return;
95
+ }
96
+ const part = chunk.value.subarray(0, remaining);
97
+ remaining -= part.byteLength;
98
+ if (part.byteLength) controller.enqueue(part);
99
+ if (remaining === 0) {
100
+ void reader.cancel().catch(() => {
101
+ });
102
+ controller.close();
103
+ }
104
+ } catch (error) {
105
+ controller.error(error);
106
+ }
107
+ },
108
+ cancel() {
109
+ void reader.cancel().catch(() => {
110
+ });
111
+ }
112
+ });
113
+ const view = new globalThis.Response(body, {
114
+ status: clone.status,
115
+ statusText: clone.statusText,
116
+ headers: clone.headers
117
+ });
118
+ Object.defineProperties(view, {
119
+ url: { value: response.url },
120
+ redirected: { value: response.redirected }
121
+ });
122
+ return {
123
+ view,
124
+ cancel: () => {
125
+ void reader.cancel().catch(() => {
126
+ });
127
+ }
128
+ };
129
+ }
130
+ function rethrowAbort(error, signal) {
131
+ if (signal?.aborted || error instanceof Error && error.name === "AbortError") throw error;
132
+ }
133
+ async function readRetryErrorBody(response, signal) {
134
+ if (signal?.aborted) {
135
+ void response.body?.cancel().catch(() => {
136
+ });
137
+ throw new globalThis.DOMException("Request aborted", "AbortError");
138
+ }
139
+ if (!response.body) return "";
140
+ const reader = response.body.getReader();
141
+ const decoder = new globalThis.TextDecoder();
142
+ let body = "";
143
+ let bytes = 0;
144
+ let onAbort;
145
+ const aborted = signal ? new Promise((_, reject) => {
146
+ onAbort = () => {
147
+ reject(new globalThis.DOMException("Request aborted", "AbortError"));
148
+ void reader.cancel().catch(() => {
149
+ });
150
+ };
151
+ if (signal.aborted) onAbort();
152
+ else signal.addEventListener("abort", onAbort, { once: true });
153
+ }) : void 0;
154
+ void aborted?.catch(() => {
155
+ });
156
+ try {
157
+ for (; ; ) {
158
+ if (signal?.aborted) throw new globalThis.DOMException("Request aborted", "AbortError");
159
+ const read = reader.read();
160
+ const chunk = aborted ? await Promise.race([read, aborted]) : await read;
161
+ if (chunk.done) break;
162
+ const remaining = MAX_RETRY_ERROR_BODY_BYTES - bytes;
163
+ body += decoder.decode(chunk.value.subarray(0, remaining), { stream: true });
164
+ bytes += chunk.value.byteLength;
165
+ if (bytes >= MAX_RETRY_ERROR_BODY_BYTES) {
166
+ void reader.cancel().catch(() => {
167
+ });
168
+ break;
169
+ }
170
+ }
171
+ body += decoder.decode();
172
+ } catch (error) {
173
+ rethrowAbort(error, signal);
174
+ } finally {
175
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
176
+ }
177
+ return body;
178
+ }
80
179
  async function createVercelModel(llmConfig, context) {
81
180
  const { provider, model, baseURL } = llmConfig;
82
181
  const runtimeAuth = context?.authResolver?.resolveRuntimeAuth({
@@ -89,9 +188,68 @@ async function createVercelModel(llmConfig, context) {
89
188
  const apiKey = runtimeAuth?.apiKey || llmConfig.apiKey || resolvedProviderApiKey;
90
189
  const runtimeBaseURL = runtimeAuth?.baseURL;
91
190
  const runtimeHeaders = runtimeAuth?.headers;
92
- const runtimeFetch = runtimeAuth?.fetch;
93
- const effectiveBaseURL = runtimeBaseURL?.replace(/\/$/, "") || baseURL?.replace(/\/$/, "");
191
+ if (runtimeBaseURL !== void 0 && !runtimeBaseURL.trim()) {
192
+ throw LLMError.invalidRuntimeBaseURL(provider);
193
+ }
194
+ const requestAuth = runtimeAuth?.requestAuth;
195
+ if (requestAuth && runtimeAuth?.fetch) {
196
+ throw LLMError.runtimeAuthConflict(provider);
197
+ }
198
+ const runtimeFetch = requestAuth ? async (input, init) => {
199
+ const { response, provenance } = await requestAuth.fetch(input, init);
200
+ if (response.ok) return response;
201
+ const signal = init?.signal ?? (input instanceof globalThis.Request ? input.signal : void 0);
202
+ const classification = boundedClassificationResponse(response);
203
+ let retryable;
204
+ let onAbort;
205
+ try {
206
+ const decision = requestAuth.isRetryableResponse({
207
+ response: classification.view,
208
+ provenance,
209
+ ...signal ? { signal } : {}
210
+ });
211
+ if (signal) {
212
+ const aborted = new Promise((_, reject) => {
213
+ onAbort = () => reject(new globalThis.DOMException("Request aborted", "AbortError"));
214
+ if (signal.aborted) onAbort();
215
+ else signal.addEventListener("abort", onAbort, { once: true });
216
+ });
217
+ retryable = await Promise.race([decision, aborted]);
218
+ } else retryable = await decision;
219
+ } catch (error) {
220
+ if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
221
+ void response.body?.cancel().catch(() => {
222
+ });
223
+ }
224
+ rethrowAbort(error, signal);
225
+ return response;
226
+ } finally {
227
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
228
+ classification.cancel();
229
+ }
230
+ if (!retryable) return response;
231
+ const responseHeaders = {};
232
+ response.headers.forEach((value, key) => {
233
+ responseHeaders[key] = value;
234
+ });
235
+ throw new APICallError({
236
+ message: "Host classified model request failure as retryable",
237
+ url: typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url,
238
+ requestBodyValues: {},
239
+ statusCode: response.status,
240
+ responseHeaders,
241
+ responseBody: await readRetryErrorBody(response, signal),
242
+ isRetryable: true
243
+ });
244
+ } : runtimeAuth?.fetch;
245
+ const effectiveBaseURL = runtimeBaseURL?.trim().replace(/\/$/, "") || baseURL?.trim().replace(/\/$/, "");
94
246
  const usesCodexRuntimeAuth = runtimeBaseURL ? isCodexBaseURL(runtimeBaseURL) : false;
247
+ if ((provider === "bedrock" || provider === "local") && (runtimeBaseURL !== void 0 || runtimeHeaders !== void 0 || runtimeAuth?.fetch || requestAuth)) {
248
+ throw LLMError.runtimeAuthUnsupported(provider);
249
+ }
250
+ if (usesCodexRuntimeAuth && (runtimeHeaders !== void 0 || runtimeAuth?.fetch || requestAuth)) {
251
+ throw LLMError.runtimeAuthUnsupported(provider);
252
+ }
95
253
  logRuntimeAuthResolution({
96
254
  context,
97
255
  provider,
@@ -101,7 +259,7 @@ async function createVercelModel(llmConfig, context) {
101
259
  runtimeAuth,
102
260
  effectiveBaseURL
103
261
  });
104
- if (requiresApiKey(provider) && !usesCodexRuntimeAuth && !apiKey?.trim()) {
262
+ if (requiresApiKey(provider) && !usesCodexRuntimeAuth && !apiKey?.trim() && !requestAuth) {
105
263
  const envVar = getPrimaryApiKeyEnvVar(provider);
106
264
  throw LLMError.apiKeyMissing(provider, envVar);
107
265
  }
@@ -140,12 +298,14 @@ async function createVercelModel(llmConfig, context) {
140
298
  return provider2.chatModel(model);
141
299
  }
142
300
  case "openrouter": {
143
- const orBaseURL = baseURL || "https://openrouter.ai/api/v1";
301
+ const orBaseURL = effectiveBaseURL || "https://openrouter.ai/api/v1";
144
302
  const { createOpenRouter } = await import("@openrouter/ai-sdk-provider");
145
303
  const provider2 = createOpenRouter({
146
304
  apiKey: apiKey ?? "",
147
305
  baseURL: orBaseURL,
148
- compatibility: "strict"
306
+ compatibility: "strict",
307
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
308
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
149
309
  });
150
310
  const chatModel = provider2.chat(model);
151
311
  if (!isLanguageModel(chatModel)) {
@@ -200,7 +360,9 @@ async function createVercelModel(llmConfig, context) {
200
360
  }).chat(model);
201
361
  }
202
362
  case "dexto-nova": {
203
- const dextoBaseURL = resolveDextoGatewayBaseURL(baseURL);
363
+ const dextoBaseURL = resolveDextoGatewayBaseURL(
364
+ runtimeBaseURL?.trim() ? runtimeBaseURL : baseURL
365
+ );
204
366
  const headers = {
205
367
  ...runtimeHeaders ?? {},
206
368
  [DEXTO_GATEWAY_HEADERS.CLIENT_SOURCE]: context?.clientSource ?? "cli"
@@ -216,7 +378,7 @@ async function createVercelModel(llmConfig, context) {
216
378
  baseURL: dextoBaseURL,
217
379
  compatibility: "strict",
218
380
  headers,
219
- ...apiKey?.trim() ? { apiKey } : {},
381
+ ...apiKey?.trim() ? { apiKey } : requestAuth ? { apiKey: "" } : {},
220
382
  ...runtimeFetch ? { fetch: runtimeFetch } : {}
221
383
  });
222
384
  const chatModel = provider2.chat(model);
@@ -246,18 +408,26 @@ async function createVercelModel(llmConfig, context) {
246
408
  }
247
409
  const location = process.env.GOOGLE_VERTEX_LOCATION;
248
410
  if (model.includes("claude")) {
249
- const headers = supportsAnthropicInterleavedThinking(model) ? { [ANTHROPIC_BETA_HEADER]: ANTHROPIC_INTERLEAVED_THINKING_BETA } : void 0;
411
+ const headers = mergeHeaders(
412
+ supportsAnthropicInterleavedThinking(model) ? { [ANTHROPIC_BETA_HEADER]: ANTHROPIC_INTERLEAVED_THINKING_BETA } : void 0,
413
+ runtimeHeaders
414
+ );
250
415
  const { createVertexAnthropic } = await import("@ai-sdk/google-vertex/anthropic");
251
416
  return createVertexAnthropic({
252
417
  project: projectId,
253
418
  location: location || "us-east5",
419
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
420
+ ...runtimeFetch ? { fetch: runtimeFetch } : {},
254
421
  ...headers ? { headers } : {}
255
422
  })(model);
256
423
  }
257
424
  const { createVertex } = await import("@ai-sdk/google-vertex");
258
425
  return createVertex({
259
426
  project: projectId,
260
- location: location || "us-central1"
427
+ location: location || "us-central1",
428
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
429
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
430
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
261
431
  })(model);
262
432
  }
263
433
  case "bedrock": {
@@ -292,19 +462,39 @@ async function createVercelModel(llmConfig, context) {
292
462
  }
293
463
  case "google": {
294
464
  const { createGoogleGenerativeAI } = await import("@ai-sdk/google");
295
- return createGoogleGenerativeAI({ apiKey: apiKey ?? "" })(model);
465
+ return createGoogleGenerativeAI({
466
+ apiKey: apiKey ?? "",
467
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
468
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
469
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
470
+ })(model);
296
471
  }
297
472
  case "groq": {
298
473
  const { createGroq } = await import("@ai-sdk/groq");
299
- return createGroq({ apiKey: apiKey ?? "" })(model);
474
+ return createGroq({
475
+ apiKey: apiKey ?? "",
476
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
477
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
478
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
479
+ })(model);
300
480
  }
301
481
  case "xai": {
302
482
  const { createXai } = await import("@ai-sdk/xai");
303
- return createXai({ apiKey: apiKey ?? "" })(model);
483
+ return createXai({
484
+ apiKey: apiKey ?? "",
485
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
486
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
487
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
488
+ })(model);
304
489
  }
305
490
  case "cohere": {
306
491
  const { createCohere } = await import("@ai-sdk/cohere");
307
- return createCohere({ apiKey: apiKey ?? "" })(model);
492
+ return createCohere({
493
+ apiKey: apiKey ?? "",
494
+ ...effectiveBaseURL ? { baseURL: effectiveBaseURL } : {},
495
+ ...runtimeHeaders ? { headers: runtimeHeaders } : {},
496
+ ...runtimeFetch ? { fetch: runtimeFetch } : {}
497
+ })(model);
308
498
  }
309
499
  case "ollama": {
310
500
  const ollamaBaseURL = effectiveBaseURL || "http://localhost:11434/v1";
@@ -22,6 +22,7 @@ __export(tool_output_read_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(tool_output_read_exports);
24
24
  var import_zod = require("zod");
25
+ var import_text_boundary = require("../utils/text-boundary.js");
25
26
  var import_tool_output_spill = require("../llm/executor/tool-output-spill.js");
26
27
  var import_activity = require("./activity.js");
27
28
  var import_errors = require("./errors.js");
@@ -91,8 +92,8 @@ function readLines(text, input) {
91
92
  const room = MAX_READ_CHARS - chars - prefix.length;
92
93
  if (room <= 0) break;
93
94
  const full = lines[line - 1] ?? "";
94
- const from = line === start ? Math.min(input.charOffset ?? 0, full.length) : 0;
95
- const piece = full.slice(from, from + room);
95
+ const from = line === start ? (0, import_text_boundary.safeTextBoundary)(full, Math.min(input.charOffset ?? 0, full.length)) : 0;
96
+ const piece = full.slice(from, (0, import_text_boundary.safeTextBoundary)(full, Math.min(from + room, full.length)));
96
97
  selected.push(`${prefix}${piece}`);
97
98
  chars += prefix.length + piece.length + 1;
98
99
  if (from + piece.length < full.length) {
@@ -119,7 +120,7 @@ function searchLines(text, pattern, maxMatches) {
119
120
  if (!line.toLowerCase().includes(needle)) return;
120
121
  total += 1;
121
122
  if (outOfRoom || found.length >= maxMatches) return;
122
- const match = `${index + 1}: ${line.slice(0, MAX_MATCH_LINE_CHARS)}`;
123
+ const match = `${index + 1}: ${line.slice(0, (0, import_text_boundary.safeTextBoundary)(line, MAX_MATCH_LINE_CHARS))}`;
123
124
  if (chars + match.length > MAX_READ_CHARS) {
124
125
  outOfRoom = true;
125
126
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"tool-output-read.d.ts","sourceRoot":"","sources":["../../src/tools/tool-output-read.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAMxE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAYvC,QAAA,MAAM,yBAAyB;;;;;;;kBA0ClB,CAAC;AAId,wBAAgB,wBAAwB,CAAC,MAAM,EAAE;IAC7C,YAAY,EAAE,iBAAiB,CAAC;IAChC,WAAW,EAAE,eAAe,CAAC;CAChC,GAAG,IAAI,CAAC,OAAO,yBAAyB,CAAC,CAkCzC"}
1
+ {"version":3,"file":"tool-output-read.d.ts","sourceRoot":"","sources":["../../src/tools/tool-output-read.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAMxE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAYvC,QAAA,MAAM,yBAAyB;;;;;;;kBA0ClB,CAAC;AAId,wBAAgB,wBAAwB,CAAC,MAAM,EAAE;IAC7C,YAAY,EAAE,iBAAiB,CAAC;IAChC,WAAW,EAAE,eAAe,CAAC;CAChC,GAAG,IAAI,CAAC,OAAO,yBAAyB,CAAC,CAkCzC"}
@@ -1,5 +1,6 @@
1
1
  import "../chunk-C6A6W6XS.js";
2
2
  import { z } from "zod";
3
+ import { safeTextBoundary } from "../utils/text-boundary.js";
3
4
  import { TOOL_OUTPUT_READ_TOOL_NAME } from "../llm/executor/tool-output-spill.js";
4
5
  import { TOOL_ACTIVITY } from "./activity.js";
5
6
  import { ToolError } from "./errors.js";
@@ -69,8 +70,8 @@ function readLines(text, input) {
69
70
  const room = MAX_READ_CHARS - chars - prefix.length;
70
71
  if (room <= 0) break;
71
72
  const full = lines[line - 1] ?? "";
72
- const from = line === start ? Math.min(input.charOffset ?? 0, full.length) : 0;
73
- const piece = full.slice(from, from + room);
73
+ const from = line === start ? safeTextBoundary(full, Math.min(input.charOffset ?? 0, full.length)) : 0;
74
+ const piece = full.slice(from, safeTextBoundary(full, Math.min(from + room, full.length)));
74
75
  selected.push(`${prefix}${piece}`);
75
76
  chars += prefix.length + piece.length + 1;
76
77
  if (from + piece.length < full.length) {
@@ -97,7 +98,7 @@ function searchLines(text, pattern, maxMatches) {
97
98
  if (!line.toLowerCase().includes(needle)) return;
98
99
  total += 1;
99
100
  if (outOfRoom || found.length >= maxMatches) return;
100
- const match = `${index + 1}: ${line.slice(0, MAX_MATCH_LINE_CHARS)}`;
101
+ const match = `${index + 1}: ${line.slice(0, safeTextBoundary(line, MAX_MATCH_LINE_CHARS))}`;
101
102
  if (chars + match.length > MAX_READ_CHARS) {
102
103
  outOfRoom = true;
103
104
  return;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var text_boundary_exports = {};
20
+ __export(text_boundary_exports, {
21
+ safeTextBoundary: () => safeTextBoundary
22
+ });
23
+ module.exports = __toCommonJS(text_boundary_exports);
24
+ function safeTextBoundary(text, offset) {
25
+ const before = text.charCodeAt(offset - 1);
26
+ const after = text.charCodeAt(offset);
27
+ return before >= 55296 && before <= 56319 && after >= 56320 && after <= 57343 ? offset - 1 : offset;
28
+ }
29
+ // Annotate the CommonJS export names for ESM import in node:
30
+ 0 && (module.exports = {
31
+ safeTextBoundary
32
+ });
@@ -0,0 +1,3 @@
1
+ /** Move a UTF-16 boundary back when it falls between a surrogate pair. */
2
+ export declare function safeTextBoundary(text: string, offset: number): number;
3
+ //# sourceMappingURL=text-boundary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text-boundary.d.ts","sourceRoot":"","sources":["../../src/utils/text-boundary.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAMrE"}
@@ -0,0 +1,9 @@
1
+ import "../chunk-C6A6W6XS.js";
2
+ function safeTextBoundary(text, offset) {
3
+ const before = text.charCodeAt(offset - 1);
4
+ const after = text.charCodeAt(offset);
5
+ return before >= 55296 && before <= 56319 && after >= 56320 && after <= 57343 ? offset - 1 : offset;
6
+ }
7
+ export {
8
+ safeTextBoundary
9
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dexto/core",
3
- "version": "1.16.5",
3
+ "version": "1.16.6",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -174,7 +174,7 @@
174
174
  "nanoid": "^5.1.16",
175
175
  "winston": "^3.17.0",
176
176
  "yaml": "^2.8.3",
177
- "@dexto/llm": "1.16.5"
177
+ "@dexto/llm": "1.16.6"
178
178
  },
179
179
  "devDependencies": {
180
180
  "@opentelemetry/context-async-hooks": "^2.12.0",