@tbox.cn/tboxcode-dsh-llm 0.1.0-rc.5 → 0.1.0-rc.7
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.
- package/lib/index.d.ts +293 -1
- package/lib/index.js +1 -1
- package/package.json +3 -3
package/lib/index.d.ts
CHANGED
|
@@ -80,6 +80,298 @@ declare const ModelTraitsSchema: z.ZodObject<{
|
|
|
80
80
|
type ModelTraits = z.infer<typeof ModelTraitsSchema>;
|
|
81
81
|
/** box/模型目录消费名:与 dsh traits 同一形状(单一事实源)。 */
|
|
82
82
|
type TboxcodeDshModelTraits = ModelTraits;
|
|
83
|
+
/** 模型条目:protocol 可省(继承 provider)。 */
|
|
84
|
+
declare const ModelEntrySchema: z.ZodObject<{
|
|
85
|
+
provider_name: z.ZodOptional<z.ZodString>;
|
|
86
|
+
upstream_model: z.ZodOptional<z.ZodString>;
|
|
87
|
+
reasoning: z.ZodOptional<z.ZodObject<{
|
|
88
|
+
field: z.ZodOptional<z.ZodEnum<{
|
|
89
|
+
reasoning: "reasoning";
|
|
90
|
+
reasoning_content: "reasoning_content";
|
|
91
|
+
reasoning_details: "reasoning_details";
|
|
92
|
+
}>>;
|
|
93
|
+
interleaved: z.ZodOptional<z.ZodBoolean>;
|
|
94
|
+
summary: z.ZodOptional<z.ZodLiteral<"auto">>;
|
|
95
|
+
include: z.ZodOptional<z.ZodLiteral<"encrypted">>;
|
|
96
|
+
effort: z.ZodOptional<z.ZodObject<{
|
|
97
|
+
default: z.ZodOptional<z.ZodString>;
|
|
98
|
+
levels: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
99
|
+
id: z.ZodString;
|
|
100
|
+
name: z.ZodOptional<z.ZodString>;
|
|
101
|
+
description: z.ZodOptional<z.ZodString>;
|
|
102
|
+
body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
103
|
+
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
104
|
+
}, z.core.$strip>>>;
|
|
105
|
+
template: z.ZodOptional<z.ZodString>;
|
|
106
|
+
}, z.core.$loose>>;
|
|
107
|
+
}, z.core.$strip>>;
|
|
108
|
+
image: z.ZodOptional<z.ZodEnum<{
|
|
109
|
+
url: "url";
|
|
110
|
+
base64: "base64";
|
|
111
|
+
}>>;
|
|
112
|
+
image_max_bytes: z.ZodOptional<z.ZodNumber>;
|
|
113
|
+
image_max_images: z.ZodOptional<z.ZodNumber>;
|
|
114
|
+
image_byte_quantum: z.ZodOptional<z.ZodNumber>;
|
|
115
|
+
image_count_quantum: z.ZodOptional<z.ZodNumber>;
|
|
116
|
+
request_max_bytes: z.ZodOptional<z.ZodNumber>;
|
|
117
|
+
image_max_pixels: z.ZodOptional<z.ZodNumber>;
|
|
118
|
+
image_max_aspect_ratio: z.ZodOptional<z.ZodNumber>;
|
|
119
|
+
cache: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodLiteral<"anthropic">, z.ZodLiteral<"openai-compatible">, z.ZodLiteral<"bedrock">, z.ZodObject<{
|
|
120
|
+
mode: z.ZodEnum<{
|
|
121
|
+
automatic: "automatic";
|
|
122
|
+
explicit: "explicit";
|
|
123
|
+
}>;
|
|
124
|
+
ttl: z.ZodEnum<{
|
|
125
|
+
"5m": "5m";
|
|
126
|
+
"1h": "1h";
|
|
127
|
+
}>;
|
|
128
|
+
scope: z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
129
|
+
system: "system";
|
|
130
|
+
tools: "tools";
|
|
131
|
+
messages: "messages";
|
|
132
|
+
}>>>;
|
|
133
|
+
}, z.core.$strip>]>>;
|
|
134
|
+
limit: z.ZodObject<{
|
|
135
|
+
context: z.ZodNumber;
|
|
136
|
+
output: z.ZodNumber;
|
|
137
|
+
idle_timeout_ms: z.ZodOptional<z.ZodNumber>;
|
|
138
|
+
}, z.core.$strip>;
|
|
139
|
+
body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
140
|
+
body_templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
141
|
+
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
142
|
+
when: z.ZodOptional<z.ZodObject<{
|
|
143
|
+
reasoning: z.ZodOptional<z.ZodBoolean>;
|
|
144
|
+
reasoning_keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
145
|
+
}, z.core.$strip>>;
|
|
146
|
+
quirks: z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
147
|
+
"ensure-assistant-reasoning": "ensure-assistant-reasoning";
|
|
148
|
+
"scrub-tool-call-id": "scrub-tool-call-id";
|
|
149
|
+
"done-after-tool": "done-after-tool";
|
|
150
|
+
"drop-empty-content": "drop-empty-content";
|
|
151
|
+
}>>>;
|
|
152
|
+
protocol: z.ZodOptional<z.ZodEnum<{
|
|
153
|
+
openai: "openai";
|
|
154
|
+
"openai-compatible": "openai-compatible";
|
|
155
|
+
anthropic: "anthropic";
|
|
156
|
+
}>>;
|
|
157
|
+
}, z.core.$loose>;
|
|
158
|
+
declare const LlmConfigSchema: z.ZodObject<{
|
|
159
|
+
model: z.ZodOptional<z.ZodString>;
|
|
160
|
+
workspace: z.ZodOptional<z.ZodObject<{
|
|
161
|
+
init_model: z.ZodOptional<z.ZodString>;
|
|
162
|
+
}, z.core.$loose>>;
|
|
163
|
+
media_policy: z.ZodOptional<z.ZodObject<{
|
|
164
|
+
mode: z.ZodOptional<z.ZodEnum<{
|
|
165
|
+
project: "project";
|
|
166
|
+
offload: "offload";
|
|
167
|
+
}>>;
|
|
168
|
+
image_reserve_bytes: z.ZodOptional<z.ZodNumber>;
|
|
169
|
+
}, z.core.$loose>>;
|
|
170
|
+
provider: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
171
|
+
protocol: z.ZodOptional<z.ZodEnum<{
|
|
172
|
+
openai: "openai";
|
|
173
|
+
"openai-compatible": "openai-compatible";
|
|
174
|
+
anthropic: "anthropic";
|
|
175
|
+
}>>;
|
|
176
|
+
name: z.ZodOptional<z.ZodString>;
|
|
177
|
+
npm: z.ZodOptional<z.ZodString>;
|
|
178
|
+
api: z.ZodOptional<z.ZodString>;
|
|
179
|
+
options: z.ZodOptional<z.ZodObject<{
|
|
180
|
+
apiKey: z.ZodOptional<z.ZodString>;
|
|
181
|
+
baseURL: z.ZodOptional<z.ZodString>;
|
|
182
|
+
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
183
|
+
}, z.core.$loose>>;
|
|
184
|
+
retry: z.ZodOptional<z.ZodObject<{
|
|
185
|
+
mode: z.ZodEnum<{
|
|
186
|
+
normal: "normal";
|
|
187
|
+
always: "always";
|
|
188
|
+
}>;
|
|
189
|
+
maxRetries: z.ZodOptional<z.ZodNumber>;
|
|
190
|
+
retryableCodes: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
191
|
+
backoff: z.ZodOptional<z.ZodObject<{
|
|
192
|
+
initialDelayMs: z.ZodOptional<z.ZodNumber>;
|
|
193
|
+
maxDelayMs: z.ZodOptional<z.ZodNumber>;
|
|
194
|
+
jitterRatio: z.ZodOptional<z.ZodNumber>;
|
|
195
|
+
}, z.core.$strict>>;
|
|
196
|
+
}, z.core.$strict>>;
|
|
197
|
+
trace: z.ZodOptional<z.ZodObject<{
|
|
198
|
+
type: z.ZodLiteral<"sofa">;
|
|
199
|
+
}, z.core.$strict>>;
|
|
200
|
+
models: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
201
|
+
provider_name: z.ZodOptional<z.ZodString>;
|
|
202
|
+
upstream_model: z.ZodOptional<z.ZodString>;
|
|
203
|
+
reasoning: z.ZodOptional<z.ZodObject<{
|
|
204
|
+
field: z.ZodOptional<z.ZodEnum<{
|
|
205
|
+
reasoning: "reasoning";
|
|
206
|
+
reasoning_content: "reasoning_content";
|
|
207
|
+
reasoning_details: "reasoning_details";
|
|
208
|
+
}>>;
|
|
209
|
+
interleaved: z.ZodOptional<z.ZodBoolean>;
|
|
210
|
+
summary: z.ZodOptional<z.ZodLiteral<"auto">>;
|
|
211
|
+
include: z.ZodOptional<z.ZodLiteral<"encrypted">>;
|
|
212
|
+
effort: z.ZodOptional<z.ZodObject<{
|
|
213
|
+
default: z.ZodOptional<z.ZodString>;
|
|
214
|
+
levels: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
215
|
+
id: z.ZodString;
|
|
216
|
+
name: z.ZodOptional<z.ZodString>;
|
|
217
|
+
description: z.ZodOptional<z.ZodString>;
|
|
218
|
+
body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
219
|
+
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
220
|
+
}, z.core.$strip>>>;
|
|
221
|
+
template: z.ZodOptional<z.ZodString>;
|
|
222
|
+
}, z.core.$loose>>;
|
|
223
|
+
}, z.core.$strip>>;
|
|
224
|
+
image: z.ZodOptional<z.ZodEnum<{
|
|
225
|
+
url: "url";
|
|
226
|
+
base64: "base64";
|
|
227
|
+
}>>;
|
|
228
|
+
image_max_bytes: z.ZodOptional<z.ZodNumber>;
|
|
229
|
+
image_max_images: z.ZodOptional<z.ZodNumber>;
|
|
230
|
+
image_byte_quantum: z.ZodOptional<z.ZodNumber>;
|
|
231
|
+
image_count_quantum: z.ZodOptional<z.ZodNumber>;
|
|
232
|
+
request_max_bytes: z.ZodOptional<z.ZodNumber>;
|
|
233
|
+
image_max_pixels: z.ZodOptional<z.ZodNumber>;
|
|
234
|
+
image_max_aspect_ratio: z.ZodOptional<z.ZodNumber>;
|
|
235
|
+
cache: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodLiteral<"anthropic">, z.ZodLiteral<"openai-compatible">, z.ZodLiteral<"bedrock">, z.ZodObject<{
|
|
236
|
+
mode: z.ZodEnum<{
|
|
237
|
+
automatic: "automatic";
|
|
238
|
+
explicit: "explicit";
|
|
239
|
+
}>;
|
|
240
|
+
ttl: z.ZodEnum<{
|
|
241
|
+
"5m": "5m";
|
|
242
|
+
"1h": "1h";
|
|
243
|
+
}>;
|
|
244
|
+
scope: z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
245
|
+
system: "system";
|
|
246
|
+
tools: "tools";
|
|
247
|
+
messages: "messages";
|
|
248
|
+
}>>>;
|
|
249
|
+
}, z.core.$strip>]>>;
|
|
250
|
+
limit: z.ZodObject<{
|
|
251
|
+
context: z.ZodNumber;
|
|
252
|
+
output: z.ZodNumber;
|
|
253
|
+
idle_timeout_ms: z.ZodOptional<z.ZodNumber>;
|
|
254
|
+
}, z.core.$strip>;
|
|
255
|
+
body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
256
|
+
body_templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
257
|
+
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
258
|
+
when: z.ZodOptional<z.ZodObject<{
|
|
259
|
+
reasoning: z.ZodOptional<z.ZodBoolean>;
|
|
260
|
+
reasoning_keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
261
|
+
}, z.core.$strip>>;
|
|
262
|
+
quirks: z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
263
|
+
"ensure-assistant-reasoning": "ensure-assistant-reasoning";
|
|
264
|
+
"scrub-tool-call-id": "scrub-tool-call-id";
|
|
265
|
+
"done-after-tool": "done-after-tool";
|
|
266
|
+
"drop-empty-content": "drop-empty-content";
|
|
267
|
+
}>>>;
|
|
268
|
+
protocol: z.ZodOptional<z.ZodEnum<{
|
|
269
|
+
openai: "openai";
|
|
270
|
+
"openai-compatible": "openai-compatible";
|
|
271
|
+
anthropic: "anthropic";
|
|
272
|
+
}>>;
|
|
273
|
+
}, z.core.$loose>>;
|
|
274
|
+
}, z.core.$loose>>>;
|
|
275
|
+
enabled_providers: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
276
|
+
disabled_providers: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
277
|
+
effort: z.ZodOptional<z.ZodString>;
|
|
278
|
+
effort_templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
279
|
+
default: z.ZodOptional<z.ZodString>;
|
|
280
|
+
levels: z.ZodArray<z.ZodObject<{
|
|
281
|
+
id: z.ZodString;
|
|
282
|
+
name: z.ZodOptional<z.ZodString>;
|
|
283
|
+
description: z.ZodOptional<z.ZodString>;
|
|
284
|
+
body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
285
|
+
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
286
|
+
}, z.core.$strip>>;
|
|
287
|
+
}, z.core.$loose>>>;
|
|
288
|
+
trait_presets: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
289
|
+
match: z.ZodObject<{
|
|
290
|
+
provider: z.ZodOptional<z.ZodString>;
|
|
291
|
+
protocol: z.ZodOptional<z.ZodEnum<{
|
|
292
|
+
openai: "openai";
|
|
293
|
+
"openai-compatible": "openai-compatible";
|
|
294
|
+
anthropic: "anthropic";
|
|
295
|
+
}>>;
|
|
296
|
+
model: z.ZodOptional<z.ZodString>;
|
|
297
|
+
}, z.core.$strip>;
|
|
298
|
+
traits: z.ZodObject<{
|
|
299
|
+
when: z.ZodOptional<z.ZodOptional<z.ZodObject<{
|
|
300
|
+
reasoning: z.ZodOptional<z.ZodBoolean>;
|
|
301
|
+
reasoning_keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
302
|
+
}, z.core.$strip>>>;
|
|
303
|
+
body: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
|
|
304
|
+
headers: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
|
|
305
|
+
reasoning: z.ZodOptional<z.ZodOptional<z.ZodObject<{
|
|
306
|
+
field: z.ZodOptional<z.ZodEnum<{
|
|
307
|
+
reasoning: "reasoning";
|
|
308
|
+
reasoning_content: "reasoning_content";
|
|
309
|
+
reasoning_details: "reasoning_details";
|
|
310
|
+
}>>;
|
|
311
|
+
interleaved: z.ZodOptional<z.ZodBoolean>;
|
|
312
|
+
summary: z.ZodOptional<z.ZodLiteral<"auto">>;
|
|
313
|
+
include: z.ZodOptional<z.ZodLiteral<"encrypted">>;
|
|
314
|
+
effort: z.ZodOptional<z.ZodObject<{
|
|
315
|
+
default: z.ZodOptional<z.ZodString>;
|
|
316
|
+
levels: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
317
|
+
id: z.ZodString;
|
|
318
|
+
name: z.ZodOptional<z.ZodString>;
|
|
319
|
+
description: z.ZodOptional<z.ZodString>;
|
|
320
|
+
body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
321
|
+
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
322
|
+
}, z.core.$strip>>>;
|
|
323
|
+
template: z.ZodOptional<z.ZodString>;
|
|
324
|
+
}, z.core.$loose>>;
|
|
325
|
+
}, z.core.$strip>>>;
|
|
326
|
+
provider_name: z.ZodOptional<z.ZodOptional<z.ZodString>>;
|
|
327
|
+
image: z.ZodOptional<z.ZodOptional<z.ZodEnum<{
|
|
328
|
+
url: "url";
|
|
329
|
+
base64: "base64";
|
|
330
|
+
}>>>;
|
|
331
|
+
image_max_bytes: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
|
|
332
|
+
image_max_images: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
|
|
333
|
+
image_byte_quantum: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
|
|
334
|
+
image_count_quantum: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
|
|
335
|
+
request_max_bytes: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
|
|
336
|
+
image_max_pixels: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
|
|
337
|
+
image_max_aspect_ratio: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
|
|
338
|
+
cache: z.ZodOptional<z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodLiteral<"anthropic">, z.ZodLiteral<"openai-compatible">, z.ZodLiteral<"bedrock">, z.ZodObject<{
|
|
339
|
+
mode: z.ZodEnum<{
|
|
340
|
+
automatic: "automatic";
|
|
341
|
+
explicit: "explicit";
|
|
342
|
+
}>;
|
|
343
|
+
ttl: z.ZodEnum<{
|
|
344
|
+
"5m": "5m";
|
|
345
|
+
"1h": "1h";
|
|
346
|
+
}>;
|
|
347
|
+
scope: z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
348
|
+
system: "system";
|
|
349
|
+
tools: "tools";
|
|
350
|
+
messages: "messages";
|
|
351
|
+
}>>>;
|
|
352
|
+
}, z.core.$strip>]>>>;
|
|
353
|
+
limit: z.ZodOptional<z.ZodObject<{
|
|
354
|
+
context: z.ZodNumber;
|
|
355
|
+
output: z.ZodNumber;
|
|
356
|
+
idle_timeout_ms: z.ZodOptional<z.ZodNumber>;
|
|
357
|
+
}, z.core.$strip>>;
|
|
358
|
+
body_templates: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
|
|
359
|
+
quirks: z.ZodOptional<z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
360
|
+
"ensure-assistant-reasoning": "ensure-assistant-reasoning";
|
|
361
|
+
"scrub-tool-call-id": "scrub-tool-call-id";
|
|
362
|
+
"done-after-tool": "done-after-tool";
|
|
363
|
+
"drop-empty-content": "drop-empty-content";
|
|
364
|
+
}>>>>;
|
|
365
|
+
}, z.core.$loose>;
|
|
366
|
+
}, z.core.$strip>>>;
|
|
367
|
+
llm_log: z.ZodOptional<z.ZodObject<{
|
|
368
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
369
|
+
max_file_bytes: z.ZodDefault<z.ZodNumber>;
|
|
370
|
+
sanitize_headers: z.ZodDefault<z.ZodBoolean>;
|
|
371
|
+
retention_days: z.ZodDefault<z.ZodNumber>;
|
|
372
|
+
}, z.core.$strip>>;
|
|
373
|
+
}, z.core.$loose>;
|
|
374
|
+
type LlmConfig = z.infer<typeof LlmConfigSchema>;
|
|
83
375
|
//#endregion
|
|
84
376
|
//#region src/index.d.ts
|
|
85
377
|
declare const name = "tboxcode-llm";
|
|
@@ -91,4 +383,4 @@ declare const inject: string[];
|
|
|
91
383
|
*/
|
|
92
384
|
declare function apply(ctx: Context): () => void;
|
|
93
385
|
//#endregion
|
|
94
|
-
export { type TboxcodeDshModelTraits, apply, inject, name };
|
|
386
|
+
export { type LlmConfig, LlmConfigSchema, ModelEntrySchema, type ModelTraits, ModelTraitsSchema, type TboxcodeDshModelTraits, apply, inject, name };
|
package/lib/index.js
CHANGED
|
@@ -116,4 +116,4 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
116
116
|
`);if(n===-1)continue;let c=vn(s.slice(0,n));return c!==null&&mn(c)?(i.cancel(),yn(c)):_n(r,o,i)}}catch{return _n(r,o,i)}return _n(r,o,i)}}function _n(e,t,n){let r=!1;return new Response(new ReadableStream({start(e){for(let n of t){if(r)return;try{e.enqueue(n)}catch{return}}(async()=>{try{for(;!r;){let{done:t,value:r}=await n.read();if(t)break;try{e.enqueue(r)}catch{break}}}catch{}try{e.close()}catch{}})()},cancel(){r=!0,n.cancel().catch(()=>{})}}),{status:e.status,statusText:e.statusText,headers:e.headers})}function vn(e){for(let t of e.split(`
|
|
117
117
|
`)){let e=t.trim();if(e.startsWith(`data:`))try{let t=JSON.parse(e.slice(5).trim());return t.error!==void 0&&typeof t.error==`object`?t.error:t}catch{}}return null}function yn(e){let t=hn(e)??5,n=typeof e?.message==`string`?e.message:`Rate limit exceeded`;return new Response(JSON.stringify({error:{message:n,type:`rate_limit_error`,code:`rate_limit_exceeded`}}),{status:429,headers:{"content-type":`application/json`,"retry-after":String(t)}})}function bn(e){for(let t of[`providerMetadata`,`providerOptions`]){let n=e[t];if(typeof n!=`object`||!n)continue;let r=n.anthropic;if(typeof r==`object`&&r)return r}}function xn(e){let t=bn(e);if(t===void 0)return;let n=typeof t.signature==`string`&&t.signature.length>0?t.signature:void 0,r=typeof t.redactedData==`string`&&t.redactedData.length>0?t.redactedData:void 0;if(!(n===void 0&&r===void 0))return{...n===void 0?{}:{signature:n},...r===void 0?{}:{redactedData:r}}}function Sn(e){let t=e.source?.replayState;if(typeof t!=`object`||!t)return;let n=t.blocks;return Array.isArray(n)?n:void 0}function Cn(e){return e.map(e=>e.text??``).filter(e=>e.length>0).join(``)}function Q(e){let t=e.attachment,n=e.type===`image`?`image`:`file`,r=t?.mediaType??`unknown`;return`[${n}${t?.name===void 0?``:` ${t.name}`}: ${r}]`}function wn(e,t,n,r){let i=e.map(e=>{let n=e;if(n.type===`text`)return n.text??``;if(n.type===`image`&&n.attachment!==void 0){let e=t?.images?.get(n.attachment.attachmentId);if(e!==void 0&&r!==`anthropic`)return`\n${v(n.attachment,e,t?.resolveImageAccess?.(n.attachment))} This provider cannot transmit images in tool results.`}return Q(e)}).join(``);if(n)return{type:`error-text`,value:i};if(r!==`anthropic`)return{type:`text`,value:i};let a=[],o=!1;for(let n of e){let e=n;if(e.type===`text`){(e.text??``).length>0&&a.push({type:`text`,text:e.text});continue}if(e.type!==`image`||e.attachment===void 0)continue;let r=t?.images?.get(e.attachment.attachmentId);if(r===void 0){a.push({type:`text`,text:Q(n)});continue}o=!0,a.push({type:`image-data`,data:Buffer.from(r.data).toString(`base64`),mediaType:r.mediaType})}return o?{type:`content`,value:a}:{type:`text`,value:i}}function Tn(e,t,n){let r=t!==void 0&&t.length>0?[t]:[],i=r.length>0,a=[],o=new Map;for(let t of e){let e=t.content,s=Array.isArray(e)?e:[];switch(t.role){case`system`:{if(i)continue;let e=Cn(s);e.length>0&&r.push(e);continue}case`developer`:continue;case`user`:{let e=[];for(let t of s){let r=t;if(r.type===`text`){e.push({type:`text`,text:r.text??``});continue}if(r.type!==`reasoning`){if(r.type===`image`){let r=t,i=n?.images?.get(r.attachment.attachmentId);i===void 0?e.push({type:`text`,text:Q(t)}):(e.push({type:`text`,text:v(r.attachment,i,n?.resolveImageAccess?.(r.attachment))}),e.push({type:`image`,image:i.data,mediaType:i.mediaType}));continue}if(r.type===`file`){e.push({type:`text`,text:Q(t)});continue}}}a.push({role:`user`,content:e});continue}case`assistant`:{let e=[],r=n?.protocol===`anthropic`?Sn(t):void 0,i=r!==void 0&&r.length===s.length?r:void 0;for(let[t,r]of s.entries()){let a=r;if(a.type===`text`){(a.text??``).length>0&&e.push({type:`text`,text:a.text});continue}if(a.type===`reasoning`){let r=i?.[t]?.anthropic;if(n?.protocol===`anthropic`){r?.signature===void 0?r?.redactedData!==void 0&&e.push({type:`reasoning`,text:a.text??``,providerOptions:{anthropic:{redactedData:r.redactedData}}}):e.push({type:`reasoning`,text:a.text??``,providerOptions:{anthropic:{signature:r.signature}}});continue}(a.text??``).length>0&&e.push({type:`reasoning`,text:a.text});continue}if(a.type===`tool-call`){let t=a.id??``,n=a.name??``;t.length>0&&n.length>0&&o.set(t,n),e.push({type:`tool-call`,toolCallId:t,toolName:n,input:En(a.arguments??`{}`)});continue}(a.type===`image`||a.type===`file`)&&e.push({type:`text`,text:Q(r)})}a.push({role:`assistant`,content:e});continue}case`tool`:{let e=t;a.push({role:`tool`,content:[{type:`tool-result`,toolCallId:e.toolCallId,toolName:o.get(e.toolCallId)??`unknown`,output:wn(e.content,n,e.isError===!0,n?.protocol)}]});continue}default:continue}}return{system:r.join(`
|
|
118
118
|
|
|
119
|
-
`),messages:a}}function En(e){try{return JSON.parse(e)}catch{return{}}}function Dn(e){if(e===void 0||e.length===0)return;let t={};for(let n of e)t[n.name]=re({description:n.description,inputSchema:te(n.parameters)});return t}function On(e){let t=new Map;for(let n of e)if(h(n.content)){if(n.role!==`user`&&n.role!==`tool`)throw new f(`cannot represent an image in an in-history ${n.role} message`,`UNSUPPORTED_CONTENT`);for(let e of n.content)e.type!==`image`||e.offloaded===!0||t.set(e.attachment.attachmentId,e.attachment)}return t}function kn(e,t){let n=-1;for(let t=0;t<e.length;t++)e[t]?.role===`assistant`&&(n=t);let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(!(a===void 0||a.role!==`user`&&a.role!==`tool`)&&h(a.content))for(let e=0;e<a.content.length;e++){let o=a.content[e];o?.type!==`image`||o.offloaded===!0||r.push({messageIndex:i,blockIndex:e,attachmentId:o.attachment.attachmentId,role:a.role,currentTurn:i>n,counted:a.role===`user`||t===`anthropic`})}}return{occurrences:r}}function An(e){return Math.ceil(e/3)*4}function jn(e){switch(e){case`count_limit_current_turn`:return`[image omitted: request image-count limit (30); oldest current-turn image dropped]`;case`count_limit`:return`[image omitted: request image-count limit (30); oldest image dropped]`;case`byte_limit`:return`[image omitted: request-size limit (32 MiB); oldest image dropped]`}}function Mn(e,t,n){let r=n.maxImages??30,i=n.maxImageBytes??Math.max(0,(n.requestMaxBytes??32*1024*1024)-(n.imageReserveBytes??8*1024*1024)),a=kn(e,n.protocol).occurrences.filter(e=>e.counted),o=[];if(a.length>r){let e=r===0?new Set:new Set(a.slice(-r));for(let t of a)e.has(t)||o.push(t)}let s=new Set(o),c=0;for(let e of a){if(s.has(e))continue;let n=t.get(e.attachmentId);n!==void 0&&(c+=An(n.bytes))}let l=[];if(c>i)for(let e of a){if(c<=i)break;if(s.has(e))continue;let n=t.get(e.attachmentId);n!==void 0&&(l.push(e),c-=An(n.bytes))}let u=[...o,...l],d=a.length-u.length,f=[];if(o.length>0){let e=0;for(let n of o){let r=t.get(n.attachmentId);r!==void 0&&(e+=An(r.bytes))}let n=o.filter(e=>e.currentTurn).length;f.push({reason:n>0?`count_limit_current_turn`:`count_limit`,dropped:o.length,droppedCurrentTurn:n,retained:d,bytesDropped:e})}if(l.length>0){let e=0;for(let n of l){let r=t.get(n.attachmentId);r!==void 0&&(e+=An(r.bytes))}f.push({reason:`byte_limit`,dropped:l.length,droppedCurrentTurn:l.filter(e=>e.currentTurn).length,retained:d,bytesDropped:e})}if(u.length===0)return{messages:e,events:f};let p=new Map;for(let e of o){let t=p.get(e.messageIndex)??new Map;t.set(e.blockIndex,e.currentTurn?`count_limit_current_turn`:`count_limit`),p.set(e.messageIndex,t)}for(let e of l){let t=p.get(e.messageIndex)??new Map;t.set(e.blockIndex,`byte_limit`),p.set(e.messageIndex,t)}return{messages:e.map((e,t)=>{let n=p.get(t);if(n===void 0)return e;let r=e.content.map((e,t)=>{let r=n.get(t);return r===void 0?e:{type:`text`,text:jn(r)}});return{...e,content:r}}),events:f}}async function Nn(e,t,n){let r=_(e,e=>g(e,n.resolveAccess(e))),i=On(r);if(i.size===0)return{messages:r,versions:new Map};if(t===void 0)throw new f(`image input requires the mounted attachment service`,`UNSUPPORTED_CONTENT`);for(let e of i.values())n.projection?.validateRef?.(e);let a=new Map;for(let e of i.values())a.set(e.attachmentId,await t.readImageRequest(e,n.targetOf(e),n.signal));if(n.projection!==void 0){let e=Mn(r,a,n.projection);for(let t of e.events)n.projection.onProjection?.(t);let t=e.events[0];return{messages:e.messages,versions:a,...t===void 0?{}:{projection:{reason:t.reason,dropped:e.events.reduce((e,t)=>e+t.dropped,0),droppedCurrentTurn:e.events.reduce((e,t)=>e+t.droppedCurrentTurn,0),retained:t.retained,bytesDropped:e.events.reduce((e,t)=>e+t.bytesDropped,0)}}}}if(n.budget!==void 0){let e=y(r,n.budget,e=>{let t=a.get(e.attachment.attachmentId);if(t===void 0)throw new f(`missing prepared request image version`,`UNSUPPORTED_CONTENT`);return t.bytes});if(e>0)throw new f(`image request exceeds route budget; ${e} more oldest occurrence(s) must be offloaded`,u,{offloadImages:e})}return{messages:r,versions:a}}function Pn(e,t){let n=e.image_max_pixels,r=Math.max(1,t.width),i=Math.max(1,t.height);if(n===void 0||r*i<=n)return{width:r,height:i,maxBytes:t.bytes};let a=Math.sqrt(n/(r*i));return{width:Math.max(1,Math.floor(r*a)),height:Math.max(1,Math.floor(i*a)),maxBytes:t.bytes}}function Fn(e,t){if(![`image/png`,`image/jpeg`,`image/webp`,`image/gif`].includes(t.mediaType))throw new f(`unsupported image media type: ${t.mediaType}`,`UNSUPPORTED_CONTENT`);let n=e.image_max_aspect_ratio;if(n===void 0)return;let r=Math.max(1,t.width),i=Math.max(1,t.height);if(Math.max(r,i)/Math.min(r,i)>n)throw new f(`image aspect ratio exceeds ${n}: ${r}x${i}`,`UNSUPPORTED_CONTENT`)}function In(e){if(e==null)return 0;if(typeof e==`string`)return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof Blob<`u`&&e instanceof Blob)return e.size;if(typeof URLSearchParams<`u`&&e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).byteLength}function Ln(e,t=globalThis.fetch){return(async(n,r)=>{let i=In(r?.body);if(i!==void 0&&i>e)throw new f(`request body ${i} bytes exceeds request_max_bytes ${e}`,`REQUEST_TOO_LARGE`);return t(n,r)})}function Rn(){return{traceId:o(16).toString(`hex`),rpcId:`0.1`}}function zn(e){return{"sofa-traceid":e.traceId,"sofa-rpcid":e.rpcId,traceid:e.traceId,rpcid:e.rpcId}}function Bn(e,t){if(e===void 0)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r.length>0)return r}function Vn(e,t){let n=e.requestId;if(typeof n==`string`&&n.length>0)return n;let r=e.data;if(typeof r==`object`&&r){let e=r,t=e.request_id??e.requestId;if(typeof t==`string`&&t.length>0)return t}for(let e of[`x-request-id`,`request-id`,`x-correlation-id`,`openai-request-id`,`x-amzn-requestid`,`cf-ray`,`x-goog-request-id`]){let n=Bn(t,e);if(n!==void 0)return n}}function Hn(e){if(e===void 0)return;let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;let n=Number(t[`retry-after-ms`]);if(Number.isFinite(n)&&n>0)return Math.ceil(n);let r=t[`retry-after`];if(r===void 0)return;let i=Number(r);if(Number.isFinite(i)&&i>0)return Math.ceil(i*1e3);let a=Date.parse(r);if(Number.isFinite(a))return Math.max(0,a-Date.now())||void 0}function Un(e){if(e instanceof Error){let t=e.lastError??e,n=t.statusCode,r=t.responseHeaders,i=r instanceof Headers?Object.fromEntries(r.entries()):typeof r==`object`&&r?Object.fromEntries(Object.entries(r).filter(e=>typeof e[1]==`string`)):void 0;return{name:e.name,msg:e.message.toLowerCase(),statusCode:typeof n==`number`?n:void 0,responseHeaders:i,retryAfterMs:Hn(i),requestId:Vn(t,i)}}return{name:``,msg:String(e).toLowerCase(),statusCode:void 0,responseHeaders:void 0,retryAfterMs:void 0,requestId:void 0}}function Wn(e){return e.name===`TypeError`&&e.msg.includes(`terminated`)||e.msg.includes(`econnreset`)||e.msg.includes(`econnrefused`)||e.msg.includes(`socket hang up`)||e.msg.includes(`fetch failed`)||e.msg.includes(`network error`)||e.msg.includes(`other side closed`)||e.msg.includes(`cannot connect to api`)}function Gn(e){return e.statusCode===401||e.statusCode===403||e.msg.includes(`unauthorized`)||e.msg.includes(`forbidden`)||e.msg.includes(`invalid api key`)}function Kn(e){return e.statusCode===429||e.msg.includes(`rate limit`)||e.msg.includes(`rate_limit`)||e.msg.includes(`too many requests`)||pn(e.msg)}function qn(e){return e.statusCode!==void 0&&e.statusCode>=500||e.msg.includes(`server error`)||e.msg.includes(`internal server`)}function Jn(e){return e.statusCode===400&&(e.msg.includes(`context length`)||e.msg.includes(`context_window`)||e.msg.includes(`maximum context`))}function Yn(e){return e.name===`AI_NoOutputGeneratedError`||e.msg.includes(`no output generated`)}function Xn(e){return e.msg.includes(`content_filter`)||e.msg.includes(`content policy`)||e.msg.includes(`content filter`)||e.msg.includes(`safety filter`)}function Zn(e){return e.statusCode===408||e.msg.includes(`timeout`)||e.msg.includes(`timed out`)}function Qn(e){return e.statusCode===400||e.statusCode===404||e.statusCode===413||e.statusCode===422||e.msg.includes(`invalid request`)||e.msg.includes(`bad request`)}const $n=[{match:Wn,code:`TRANSPORT`,message:`与 LLM 服务的连接中断(网络异常)`},{match:Gn,code:`AUTH`,message:`模型服务鉴权失败,请检查 API Key 配置`},{match:Kn,code:`RATE_LIMIT`,message:`触发限流,请稍后重试`},{match:Jn,code:`CONTEXT_WINDOW_EXCEEDED`,message:`上下文长度超限`},{match:qn,code:`SERVER`,message:`模型服务异常`},{match:Yn,code:`EMPTY_RESPONSE`,message:`模型未产生输出`},{match:Xn,code:`INVALID_REQUEST`,message:`内容被安全策略拦截`},{match:Zn,code:`TIMEOUT`,message:`模型服务请求超时`},{match:Qn,code:`INVALID_REQUEST`,message:`模型请求无效`}];function er(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`}function tr(e){if(e instanceof f)return e;if(er(e))return new f(`请求已取消`,`ABORTED`,{cause:e});let t=Un(e),n=t.statusCode!==void 0&&Number.isInteger(t.statusCode)&&t.statusCode>=100&&t.statusCode<=599?t.statusCode:void 0,r={cause:e instanceof Error?e:void 0,...n===void 0?{}:{status:n},...t.retryAfterMs===void 0?{}:{providerRetryAfterMs:t.retryAfterMs},...t.requestId===void 0?{}:{requestId:p(t.requestId)}};for(let e of $n)if(e.match(t))return new f(e.message,e.code,r);return new f(`LLM 调用失败`,`TRANSPORT`,r)}const nr=e=>e;function $(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,Math.trunc(t)):0}function rr(e,t){let n=t?.name;return typeof n==`string`&&n.trim().length>0?n.trim():e}function ir(e){return e?.image===void 0?[`text`]:[`text`,`image`]}function ar(e){let t=e;if(!(t===void 0||t.image_max_bytes===void 0&&t.image_max_images===void 0&&t.image_byte_quantum===void 0&&t.image_count_quantum===void 0))return{representation:`base64`,...t.image_max_bytes===void 0?{}:{maxBytes:t.image_max_bytes},...t.image_max_images===void 0?{}:{maxImages:t.image_max_images},...t.image_byte_quantum===void 0?{}:{byteQuantum:t.image_byte_quantum},...t.image_count_quantum===void 0?{}:{countQuantum:t.image_count_quantum}}}function or(e){let t=e.workspace?.init_model??rn;try{if(Z(t).modelId===X)throw Error(`workspace.init_model must not reference auto`);return t}catch(e){throw new f(`workspace.init_model 非法:${t}(须为 provider/model,且不能是 auto)`,`INVALID_CONFIG`,{cause:e instanceof Error?e:void 0})}}function sr(e){try{let t=Z(e.workspace?.init_model??rn);return t.modelId===X?void 0:t}catch{return}}var cr=class extends d{#e;#t;#n;#r;#i;#a;#o;constructor(e){super(),this.#e=e.config,this.#t=e.auth,this.#n=e.llmLog,this.#r=e.callLogPaths,this.#i=e.resolveAttachments,this.#a=e.resolveImageAccess,this.#o=e.onImageProjection}refresh(e,t,n){this.#e=e,this.#t=t,this.#n=n}get llmLog(){return this.#n}providerInfo(e){let t=this.#e.provider?.[e]?.name,n=typeof t==`string`?t.trim():``;return{id:e,name:n.length>0?n:e}}listModels(e){if(!this.#c(e))return Promise.resolve([]);let t=this.#e.provider?.[e];if(t===void 0)return Promise.resolve([]);let n=[],r=new Set;for(let[i,a]of Object.entries(t.models)){if(i.length===0||r.has(i)){console.warn(`[tboxcode-llm] 跳过非法/重复模型条目: provider=${e} id="${i}"`);continue}if(i===X){console.warn(`[tboxcode-llm] 忽略显式 auto 条目(auto 是 workspace.init_model 虚拟 alias)`);continue}r.add(i);let t=rr(i,a);t.length!==0&&n.push({provider:e,id:i,name:t,inputModalities:ir(a)})}let i=sr(this.#e);if(i?.providerId===e){let r=t.models[i.modelId];r?.image===void 0?r===void 0?console.warn(`[tboxcode-llm] auto 目标模型不存在: ${i.providerId}/${i.modelId}`):console.warn(`[tboxcode-llm] auto 目标模型未声明 image: ${i.providerId}/${i.modelId}`):n.push({provider:e,id:X,name:`Auto`,inputModalities:ir(r)})}return Promise.resolve(n)}async resolveModel(e,t){return this.#s(this.#l(`${e}/${t}`))}imageRequestTarget(e,t,n){return Pn(this.#l(`${e}/${t}`).traits,n)}#s(e){let t=e.traits.reasoning?.effort,n=this.#e.effort,r=t?.levels!==void 0&&typeof n==`string`&&n.length>0&&t.levels.some(e=>e.id===n)?n:t?.default;return{provider:e.providerId,id:e.modelId,name:e.modelId===X?`Auto`:rr(e.modelId,e.traits),inputModalities:ir(e.traits),context:{contextWindow:e.traits.limit.context},defaultMaxTokens:e.traits.limit.output,...t?.levels!==void 0&&t.levels.length>0?{reasoning:{efforts:t.levels.map(e=>({id:nr(e.id),name:e.name??e.id})),...r===void 0?{}:{defaultEffort:nr(r)}}}:{}}}#c(e){if(this.#e.disabled_providers?.includes(e)===!0)return!1;let t=this.#e.enabled_providers;return t===void 0||t.length===0||t.includes(e)}providerRetryPolicy(e){let t=this.#e.provider?.[e]?.retry;return x(t??{mode:`normal`,maxRetries:2},`tboxcode-llm provider "${e}" retryPolicy`)}async*stream(e){yield*(await this.prepareCall(e.provider,e.model,e.signal)).stream(e)}async prepareCall(e,t,n){let r=this.#l(`${e}/${t}`);return{model:this.#s(r),stream:e=>this.#d(r,e)}}#l(e){try{let t=Z(e);if(t.modelId===X){let e=or(this.#e),n=Z(e);if(n.providerId!==t.providerId)throw new f(`auto 只挂在 workspace.init_model 的 provider 上:请求 ${t.providerId},目标 ${n.providerId}`,`INVALID_CONFIG`);if(!this.#c(n.providerId))throw new f(`auto 目标 provider 不可用:${n.providerId}`,`INVALID_CONFIG`);let r;try{r=fn(e,this.#e,this.#t)}catch(t){throw new f(`workspace.init_model 无法解析:${e}`,`INVALID_CONFIG`,{cause:t instanceof Error?t:void 0})}if(r.traits.image===void 0)throw new f(`workspace.init_model 必须声明 image:${e}`,`INVALID_CONFIG`);return{...r,modelId:X}}return fn(e,this.#e,this.#t)}catch(e){throw e instanceof f?e:e instanceof ft?new f(e.message,`UNKNOWN_MODEL`,{cause:e}):e instanceof Y||e instanceof pt||e instanceof mt?new f(e.message,`INVALID_CONFIG`,{cause:e}):e}}async#u(e,i){if(!this.#n.enabled||this.#r===void 0)return;let{root:a,cwdOf:s}=this.#r,c=i.sessionId===void 0?void 0:String(i.sessionId),l=`llmc_${o(8).toString(`hex`)}`,u;if(c!==void 0)try{let e=await s(c);u=e===void 0?r(a):t(a,e,c)}catch{u=r(a)}else u=r(a);let d=i.purpose,f=d===`compaction`?`compact`:d===`session-title`?`title`:`main`,p=n({enabled:!0,max_file_bytes:this.#n.max_file_bytes,sanitize_headers:this.#n.sanitize_headers,logDir:u,sessionId:c??`agentless`,trigger:f,callId:l,traitsVersion:ur(e.traits),provider_name:e.provider_name,modelId:i.model,upstream_model:e.upstream_model,protocol:e.traits.protocol,onError:(e,t)=>console.warn(`[tboxcode-llm] ${e}: ${String(t)}`)},gn(globalThis.fetch));return{fetch:p.fetch,drain:p.drain,callId:l}}async*#d(e,t){let n=e.traits,r=await this.#u(e,t),i=gt(n.reasoning?.effort,void 0,t.reasoningEffort),a=this.#e.provider?.[e.providerId]?.trace?.type===`sofa`?zn(Rn()):void 0,o={...e,credentials:{...e.credentials,headers:{...e.baseHeaders,...i===void 0?{}:e.effortHeaders?.[i],...a??{}}}},s=r?.fetch??globalThis.fetch.bind(globalThis),c=n.request_max_bytes===void 0?void 0:Ln(n.request_max_bytes,s),l=Bt(o,{headers:m(),...c===void 0&&r===void 0?{}:{fetch:c??r.fetch,...r===void 0?{}:{drain:r.drain}}}),{system:u}=t,d=this.#i?.(),p=e=>d===void 0||this.#a===void 0?void 0:this.#a(d,e),h=this.#e.media_policy,g=h?.mode===`project`,_=g?void 0:ar(n),v;try{v=await Nn(t.messages,d,{resolveAccess:p,targetOf:t=>this.imageRequestTarget(e.providerId,e.modelId,t),..._===void 0?{}:{budget:_},...g?{projection:{mode:`project`,protocol:n.protocol,requestMaxBytes:n.request_max_bytes,imageReserveBytes:h?.image_reserve_bytes,validateRef:e=>Fn(n,e),onProjection:n=>this.#o?.({...t.sessionId===void 0?{}:{sessionId:String(t.sessionId)},provider:e.providerId,model:t.model,...n})}}:{},...t.signal===void 0?{}:{signal:t.signal}})}catch(e){throw tr(e)}let y=Tn(v.messages,u,{images:v.versions,resolveImageAccess:p,protocol:n.protocol}),b=Dn(t.tools),x={sessionId:t.sessionId??`agentless`,effort:t.reasoningEffort,model:{id:t.model,context:n.limit.context,output:n.limit.output},reasoningEnabled:n.reasoning!==void 0},S=t.purpose!==`compaction`,C=Pt(y.messages,n,x,y.system,e.provider_name,{messageBreakpoints:S}),w=C.toolsCacheControl!==null&&C.toolsCacheControlKey!==null&&b!==void 0?Object.fromEntries(Object.entries(b).map(([e,t])=>[e,{...t,providerOptions:{...t.providerOptions,[C.toolsCacheControlKey]:{...t.providerOptions?.[C.toolsCacheControlKey]??{},cacheControl:C.toolsCacheControl}}}])):b,T=t.purpose===`compaction`?n.limit.output:t.maxTokens??n.limit.output,E=new AbortController,D=t.signal,ee=()=>E.abort(D?.reason);D!==void 0&&(D.aborted?E.abort(D.reason):D.addEventListener(`abort`,ee,{once:!0}));let te=l.streamText({model:{id:e.upstream_model,traits:n},system:C.system,messages:C.messages,providerOptions:C.providerOptions,tools:w,signal:E.signal,credentials:o.credentials,maxRetries:0,params:{...t.temperature===void 0?{}:{temperature:t.temperature},maxOutputTokens:T,...t.stop!==void 0&&t.stop.length>0?{stopSequences:t.stop}:{}}}),ne=0,re=()=>ne++,ie=n.protocol===`anthropic`,O=[],k=e=>{for(;O.length<=e;)O.push(null)},A=(e,t)=>{if(!ie)return;let n=xn(t);n!==void 0&&(k(e),O[e]={anthropic:n})},j=new Map,M=new Map,N=new Map,P,F=!1,I=!1,L=n.limit.idle_timeout_ms,R=te.fullStream[Symbol.asyncIterator](),z=!1,B,V=async()=>L===void 0?R.next():Promise.race([R.next(),new Promise((e,t)=>{B=setTimeout(()=>{z=!0;let e=new f(`LLM stream idle timeout`,`TIMEOUT`);E.abort(e),t(e)},L)})]);try{for(;;){let t=await V();if(B!==void 0&&(clearTimeout(B),B=void 0),t.done===!0)break;let n=t.value;switch(n.type){case`text-start`:{let e=String(n.id??``),t=re();k(t),j.set(e,{index:t,buffer:``}),F=!0,yield{type:`block-start`,index:t,blockType:`text`};break}case`text-delta`:{let e=String(n.id??``),t=j.get(e),r=String(n.text??``);if(t===void 0)break;F=!0,t.buffer+=r,yield{type:`text-delta`,index:t.index,text:r};break}case`text-end`:{let e=String(n.id??``),t=j.get(e);if(t===void 0)break;F=!0,j.delete(e),yield{type:`block-end`,index:t.index,block:{type:`text`,text:t.buffer}};break}case`reasoning-start`:{let e=String(n.id??``),t=re();k(t),A(t,n),M.set(e,{index:t,buffer:``}),F=!0,yield{type:`block-start`,index:t,blockType:`reasoning`};break}case`reasoning-delta`:{let e=String(n.id??``),t=M.get(e),r=String(n.text??``);if(t===void 0)break;A(t.index,n),F=!0,t.buffer+=r,yield{type:`reasoning-delta`,index:t.index,text:r};break}case`reasoning-end`:{let e=String(n.id??``),t=M.get(e);if(t===void 0)break;A(t.index,n),F=!0,M.delete(e),yield{type:`block-end`,index:t.index,block:{type:`reasoning`,text:t.buffer}};break}case`tool-input-start`:{let e=String(n.id??``),t=re();k(t),N.set(e,{index:t,name:String(n.toolName??``),buffer:``}),F=!0,yield{type:`block-start`,index:t,blockType:`tool-call`};break}case`tool-input-delta`:{let e=String(n.id??``),t=N.get(e);if(t===void 0)break;F=!0;let r=String(n.delta??``);t.buffer+=r,yield{type:`tool-call-delta`,index:t.index,id:nr(e),name:t.name,argumentsDelta:r};break}case`tool-call`:{let e=String(n.toolCallId??n.id??``),t=N.get(e);if(t===void 0)break;F=!0;let r=typeof n.toolName==`string`&&n.toolName.length>0?n.toolName:t.name;N.delete(e);let i=n.invalid===!0?t.buffer:JSON.stringify(n.input??{});yield{type:`block-end`,index:t.index,block:{type:`tool-call`,id:nr(e),name:r,arguments:i}};break}case`abort`:throw new f(`请求已取消`,`ABORTED`);case`error`:throw tr(n.error);case`finish-step`:P=n.usage;break;case`finish`:{let t=P??n.totalUsage??{},r=P?.raw??{},i=t.inputTokenDetails??{},a=t.outputTokenDetails??{},o=$(t.inputTokens),s=Math.max($(i.cacheReadTokens),$(r.prompt_cache_hit_tokens),$(r.cache_read_input_tokens)),c=Math.max($(i.cacheWriteTokens),$(r.cache_creation_input_tokens)),l=Math.max(o,s+c),u=Math.max(0,l-s-c),d=$(t.outputTokens),f=Math.max($(a.reasoningTokens),$(r.completion_tokens_details?.reasoning_tokens)),p=$(t.totalTokens)||$(r.total_tokens),m=l+d,h=p===m?p:m;yield{type:`usage`,usage:{inputTokens:u,outputTokens:d,...h>0?{totalTokens:h}:{},...s>0?{cacheReadTokens:s}:{},...c>0?{cacheWriteTokens:c}:{},...f>0&&f<=d?{reasoningTokens:f}:{}}};let g=lr(n.finishReason);g.kind===`stop`&&!F&&(g={kind:`error`,failure:{message:`model returned no content`,code:`EMPTY_RESPONSE`}});let _=ie&&g.kind!==`error`&&O.some(e=>e!==null);yield{type:`finish`,reason:g,..._?{replayState:{response:{provider:e.provider_name,model:e.upstream_model,...typeof n.finishReason==`string`?{finishReason:n.finishReason}:{}},blocks:O}}:{}},I=!0;break}default:break}}if(!I)throw D?.aborted?new f(`请求已取消`,`ABORTED`):new f(`LLM stream ended without a finish chunk`,`TRANSPORT`)}catch(e){throw z?new f(`LLM stream idle timeout`,`TIMEOUT`,{cause:e instanceof Error?e:void 0}):D?.aborted?new f(`请求已取消`,`ABORTED`,{cause:e instanceof Error?e:void 0}):tr(e)}finally{B!==void 0&&clearTimeout(B),D?.removeEventListener(`abort`,ee),await l.dispose()}}};function lr(e){switch(e){case`tool-calls`:return{kind:`tool-calls`};case`length`:return{kind:`max-tokens`};case`content-filter`:return{kind:`error`,failure:{message:`模型输出被内容安全策略拦截`,code:`INVALID_REQUEST`}};case`other`:case`unknown`:return{kind:`error`,failure:{message:`LLM 流以未识别的 finishReason 结束(可能被截断)`,code:`TRANSPORT`}};case`error`:return{kind:`error`,failure:{message:`stream error`,code:`SERVER`}};case`stop`:default:return{kind:`stop`}}}function ur(e){return Dt(e)}const dr=`tboxcode-llm`,fr=[`llm`];function pr(e){let t=e.get(`sessionPersistence`),n=t?.config?.root,r=t?.stat;if(!(n===void 0||r===void 0))return{root:n,cwdOf:async e=>(await r.call(t,e))?.header.cwd}}function mr(e){for(let t of[`auth.jsonc`,`auth.json`]){let n=l(e,t);if(S(n))try{w(n).mode&63&&console.warn(`[tboxcode-llm] auth 文件权限过宽(建议 0600): ${n}`);let e=ct(JSON.parse(st(C(n,`utf-8`))));return ln.parse(e)}catch(e){throw new f(`auth 文件解析失败(${n}):${e instanceof Error?e.message:String(e)}`,`INVALID_CREDENTIAL`)}}return{}}function hr(){let e=at(),t=lt(e).config;return{config:sn.parse(t),auth:mr(e)}}function gr(e){if(e instanceof E){let t=e.issues.slice(0,5).map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`),n=e.issues.length>t.length?`(共 ${e.issues.length} 项)`:``;return`config schema 校验失败:${t.join(`;`)}${n}`}return e instanceof Error?e.message:String(e)}function _r(e,t,n){let r=n?`——保存后自动注册,无需重启`:`——该配置目录为首次创建,配置后需重启进程`;if(e instanceof f&&e.code===`INVALID_ADAPTER`){console.warn(`[tboxcode-llm] config 未配置 provider——LLM 域待命(adapter 不注册,模型调用不可用)`),console.warn(`[tboxcode-llm] 编辑 ${l(t,`config.jsonc`)} 的 provider 段(示例见 tboxcode-dsh init --config 生成的模板注释)${r}`);return}if(e instanceof f&&e.code===`DUPLICATE_ADAPTER`){console.warn(`[tboxcode-llm] provider 路由注册冲突——LLM 域待命:${e.message}(路由 id 已被其他 adapter 占用,请更换 provider id)${r}`);return}console.warn(`[tboxcode-llm] config/auth 加载失败——LLM 域待命:${gr(e)}${r}`)}function vr(e,t){let n=e.provider??{},r=new Map;for(let[e,t]of Object.entries(n)){let n=typeof t.name==`string`&&t.name.trim().length>0?t.name.trim():e;r.set(n,[...r.get(n)??[],e])}for(let[e,t]of r)t.length>1&&console.warn(`[tboxcode-llm] provider 显示名重复: "${e}" (${t.join(`, `)})——GUI 分组可能同名,建议区分`);let i=Object.entries(n).filter(([,e])=>Object.values(e.models).some(e=>e.image!==void 0)).map(([e])=>e);if(i.length>0&&t.get(`attachments`)===void 0&&console.warn(`[tboxcode-llm] provider 声明了 image 但附件服务未挂载(${i.join(`, `)})——图片输入不可用`),e.model===void 0||e.model.length===0)return;let a=e.model.indexOf(`/`);if(a<=0||a===e.model.length-1){console.warn(`[tboxcode-llm] 默认模型引用格式无效: "${e.model}"(应为 provider/model)`);return}let o=e.model.slice(0,a),s=e.model.slice(a+1),c=n[o];if(c!==void 0){if(e.disabled_providers?.includes(o)===!0){console.warn(`[tboxcode-llm] 默认模型不可用: "${e.model}"(provider disabled)`);return}if(e.enabled_providers!==void 0&&e.enabled_providers.length>0&&!e.enabled_providers.includes(o)){console.warn(`[tboxcode-llm] 默认模型不可用: "${e.model}"(provider 不在 enabled_providers)`);return}c.models[s]===void 0&&console.warn(`[tboxcode-llm] 默认模型不可用: "${e.model}"(model 不存在)`)}}function yr(e){let t=at(),n=S(t),r,i,a,o=()=>{let t=hr(),n=Object.keys(t.config.provider??{});if(n.length===0)throw new f(`config 未配置 provider`,`INVALID_ADAPTER`);i=new cr({config:t.config,auth:t.auth,llmLog:dn(t.config.llm_log),callLogPaths:pr(e),resolveAttachments:()=>e.get(`attachments`),resolveImageAccess:(t,n)=>b(t,t=>e.get(`fs`)?.processPathFromHostPath?.(t),n),onImageProjection:e=>{console.warn(`[tboxcode-llm] ${JSON.stringify({event:`llm.image.projected`,...e})}`)}}),a=e.llm.registerAdapter(n,i),vr(t.config,e),r=t};try{o()}catch(e){_r(e,t,n)}let s;try{s=ut(t,[`config.jsonc`,`config.json`,`auth.jsonc`,`auth.json`],()=>{try{if(a===void 0){o(),console.warn(`[tboxcode-llm] provider 路由已注册(热载挂载):${Object.keys(r?.config.provider??{}).join(`, `)}`);return}let t=hr();i?.refresh?.(t.config,t.auth,dn(t.config.llm_log)),a.replace(Object.keys(t.config.provider??{})),vr(t.config,e),r=t}catch(e){let t=a===void 0?`维持待命`:`保留上一代`,n=e instanceof Error?e.message:String(e);console.warn(`[tboxcode-llm] 配置热载失败(${t}):${n}`)}})}catch{}return()=>{s?.dispose(),a?.()}}export{yr as apply,fr as inject,dr as name};
|
|
119
|
+
`),messages:a}}function En(e){try{return JSON.parse(e)}catch{return{}}}function Dn(e){if(e===void 0||e.length===0)return;let t={};for(let n of e)t[n.name]=re({description:n.description,inputSchema:te(n.parameters)});return t}function On(e){let t=new Map;for(let n of e)if(h(n.content)){if(n.role!==`user`&&n.role!==`tool`)throw new f(`cannot represent an image in an in-history ${n.role} message`,`UNSUPPORTED_CONTENT`);for(let e of n.content)e.type!==`image`||e.offloaded===!0||t.set(e.attachment.attachmentId,e.attachment)}return t}function kn(e,t){let n=-1;for(let t=0;t<e.length;t++)e[t]?.role===`assistant`&&(n=t);let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(!(a===void 0||a.role!==`user`&&a.role!==`tool`)&&h(a.content))for(let e=0;e<a.content.length;e++){let o=a.content[e];o?.type!==`image`||o.offloaded===!0||r.push({messageIndex:i,blockIndex:e,attachmentId:o.attachment.attachmentId,role:a.role,currentTurn:i>n,counted:a.role===`user`||t===`anthropic`})}}return{occurrences:r}}function An(e){return Math.ceil(e/3)*4}function jn(e){switch(e){case`count_limit_current_turn`:return`[image omitted: request image-count limit (30); oldest current-turn image dropped]`;case`count_limit`:return`[image omitted: request image-count limit (30); oldest image dropped]`;case`byte_limit`:return`[image omitted: request-size limit (32 MiB); oldest image dropped]`}}function Mn(e,t,n){let r=n.maxImages??30,i=n.maxImageBytes??Math.max(0,(n.requestMaxBytes??32*1024*1024)-(n.imageReserveBytes??8*1024*1024)),a=kn(e,n.protocol).occurrences.filter(e=>e.counted),o=[];if(a.length>r){let e=r===0?new Set:new Set(a.slice(-r));for(let t of a)e.has(t)||o.push(t)}let s=new Set(o),c=0;for(let e of a){if(s.has(e))continue;let n=t.get(e.attachmentId);n!==void 0&&(c+=An(n.bytes))}let l=[];if(c>i)for(let e of a){if(c<=i)break;if(s.has(e))continue;let n=t.get(e.attachmentId);n!==void 0&&(l.push(e),c-=An(n.bytes))}let u=[...o,...l],d=a.length-u.length,f=[];if(o.length>0){let e=0;for(let n of o){let r=t.get(n.attachmentId);r!==void 0&&(e+=An(r.bytes))}let n=o.filter(e=>e.currentTurn).length;f.push({reason:n>0?`count_limit_current_turn`:`count_limit`,dropped:o.length,droppedCurrentTurn:n,retained:d,bytesDropped:e})}if(l.length>0){let e=0;for(let n of l){let r=t.get(n.attachmentId);r!==void 0&&(e+=An(r.bytes))}f.push({reason:`byte_limit`,dropped:l.length,droppedCurrentTurn:l.filter(e=>e.currentTurn).length,retained:d,bytesDropped:e})}if(u.length===0)return{messages:e,events:f};let p=new Map;for(let e of o){let t=p.get(e.messageIndex)??new Map;t.set(e.blockIndex,e.currentTurn?`count_limit_current_turn`:`count_limit`),p.set(e.messageIndex,t)}for(let e of l){let t=p.get(e.messageIndex)??new Map;t.set(e.blockIndex,`byte_limit`),p.set(e.messageIndex,t)}return{messages:e.map((e,t)=>{let n=p.get(t);if(n===void 0)return e;let r=e.content.map((e,t)=>{let r=n.get(t);return r===void 0?e:{type:`text`,text:jn(r)}});return{...e,content:r}}),events:f}}async function Nn(e,t,n){let r=_(e,e=>g(e,n.resolveAccess(e))),i=On(r);if(i.size===0)return{messages:r,versions:new Map};if(t===void 0)throw new f(`image input requires the mounted attachment service`,`UNSUPPORTED_CONTENT`);for(let e of i.values())n.projection?.validateRef?.(e);let a=new Map;for(let e of i.values())a.set(e.attachmentId,await t.readImageRequest(e,n.targetOf(e),n.signal));if(n.projection!==void 0){let e=Mn(r,a,n.projection);for(let t of e.events)n.projection.onProjection?.(t);let t=e.events[0];return{messages:e.messages,versions:a,...t===void 0?{}:{projection:{reason:t.reason,dropped:e.events.reduce((e,t)=>e+t.dropped,0),droppedCurrentTurn:e.events.reduce((e,t)=>e+t.droppedCurrentTurn,0),retained:t.retained,bytesDropped:e.events.reduce((e,t)=>e+t.bytesDropped,0)}}}}if(n.budget!==void 0){let e=y(r,n.budget,e=>{let t=a.get(e.attachment.attachmentId);if(t===void 0)throw new f(`missing prepared request image version`,`UNSUPPORTED_CONTENT`);return t.bytes});if(e>0)throw new f(`image request exceeds route budget; ${e} more oldest occurrence(s) must be offloaded`,u,{offloadImages:e})}return{messages:r,versions:a}}function Pn(e,t){let n=e.image_max_pixels,r=Math.max(1,t.width),i=Math.max(1,t.height);if(n===void 0||r*i<=n)return{width:r,height:i,maxBytes:t.bytes};let a=Math.sqrt(n/(r*i));return{width:Math.max(1,Math.floor(r*a)),height:Math.max(1,Math.floor(i*a)),maxBytes:t.bytes}}function Fn(e,t){if(![`image/png`,`image/jpeg`,`image/webp`,`image/gif`].includes(t.mediaType))throw new f(`unsupported image media type: ${t.mediaType}`,`UNSUPPORTED_CONTENT`);let n=e.image_max_aspect_ratio;if(n===void 0)return;let r=Math.max(1,t.width),i=Math.max(1,t.height);if(Math.max(r,i)/Math.min(r,i)>n)throw new f(`image aspect ratio exceeds ${n}: ${r}x${i}`,`UNSUPPORTED_CONTENT`)}function In(e){if(e==null)return 0;if(typeof e==`string`)return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof Blob<`u`&&e instanceof Blob)return e.size;if(typeof URLSearchParams<`u`&&e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).byteLength}function Ln(e,t=globalThis.fetch){return(async(n,r)=>{let i=In(r?.body);if(i!==void 0&&i>e)throw new f(`request body ${i} bytes exceeds request_max_bytes ${e}`,`REQUEST_TOO_LARGE`);return t(n,r)})}function Rn(){return{traceId:o(16).toString(`hex`),rpcId:`0.1`}}function zn(e){return{"sofa-traceid":e.traceId,"sofa-rpcid":e.rpcId,traceid:e.traceId,rpcid:e.rpcId}}function Bn(e,t){if(e===void 0)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r.length>0)return r}function Vn(e,t){let n=e.requestId;if(typeof n==`string`&&n.length>0)return n;let r=e.data;if(typeof r==`object`&&r){let e=r,t=e.request_id??e.requestId;if(typeof t==`string`&&t.length>0)return t}for(let e of[`x-request-id`,`request-id`,`x-correlation-id`,`openai-request-id`,`x-amzn-requestid`,`cf-ray`,`x-goog-request-id`]){let n=Bn(t,e);if(n!==void 0)return n}}function Hn(e){if(e===void 0)return;let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;let n=Number(t[`retry-after-ms`]);if(Number.isFinite(n)&&n>0)return Math.ceil(n);let r=t[`retry-after`];if(r===void 0)return;let i=Number(r);if(Number.isFinite(i)&&i>0)return Math.ceil(i*1e3);let a=Date.parse(r);if(Number.isFinite(a))return Math.max(0,a-Date.now())||void 0}function Un(e){if(e instanceof Error){let t=e.lastError??e,n=t.statusCode,r=t.responseHeaders,i=r instanceof Headers?Object.fromEntries(r.entries()):typeof r==`object`&&r?Object.fromEntries(Object.entries(r).filter(e=>typeof e[1]==`string`)):void 0;return{name:e.name,msg:e.message.toLowerCase(),statusCode:typeof n==`number`?n:void 0,responseHeaders:i,retryAfterMs:Hn(i),requestId:Vn(t,i)}}return{name:``,msg:String(e).toLowerCase(),statusCode:void 0,responseHeaders:void 0,retryAfterMs:void 0,requestId:void 0}}function Wn(e){return e.name===`TypeError`&&e.msg.includes(`terminated`)||e.msg.includes(`econnreset`)||e.msg.includes(`econnrefused`)||e.msg.includes(`socket hang up`)||e.msg.includes(`fetch failed`)||e.msg.includes(`network error`)||e.msg.includes(`other side closed`)||e.msg.includes(`cannot connect to api`)}function Gn(e){return e.statusCode===401||e.statusCode===403||e.msg.includes(`unauthorized`)||e.msg.includes(`forbidden`)||e.msg.includes(`invalid api key`)}function Kn(e){return e.statusCode===429||e.msg.includes(`rate limit`)||e.msg.includes(`rate_limit`)||e.msg.includes(`too many requests`)||pn(e.msg)}function qn(e){return e.statusCode!==void 0&&e.statusCode>=500||e.msg.includes(`server error`)||e.msg.includes(`internal server`)}function Jn(e){return e.statusCode===400&&(e.msg.includes(`context length`)||e.msg.includes(`context_window`)||e.msg.includes(`maximum context`))}function Yn(e){return e.name===`AI_NoOutputGeneratedError`||e.msg.includes(`no output generated`)}function Xn(e){return e.msg.includes(`content_filter`)||e.msg.includes(`content policy`)||e.msg.includes(`content filter`)||e.msg.includes(`safety filter`)}function Zn(e){return e.statusCode===408||e.msg.includes(`timeout`)||e.msg.includes(`timed out`)}function Qn(e){return e.statusCode===400||e.statusCode===404||e.statusCode===413||e.statusCode===422||e.msg.includes(`invalid request`)||e.msg.includes(`bad request`)}const $n=[{match:Wn,code:`TRANSPORT`,message:`与 LLM 服务的连接中断(网络异常)`},{match:Gn,code:`AUTH`,message:`模型服务鉴权失败,请检查 API Key 配置`},{match:Kn,code:`RATE_LIMIT`,message:`触发限流,请稍后重试`},{match:Jn,code:`CONTEXT_WINDOW_EXCEEDED`,message:`上下文长度超限`},{match:qn,code:`SERVER`,message:`模型服务异常`},{match:Yn,code:`EMPTY_RESPONSE`,message:`模型未产生输出`},{match:Xn,code:`INVALID_REQUEST`,message:`内容被安全策略拦截`},{match:Zn,code:`TIMEOUT`,message:`模型服务请求超时`},{match:Qn,code:`INVALID_REQUEST`,message:`模型请求无效`}];function er(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`}function tr(e){if(e instanceof f)return e;if(er(e))return new f(`请求已取消`,`ABORTED`,{cause:e});let t=Un(e),n=t.statusCode!==void 0&&Number.isInteger(t.statusCode)&&t.statusCode>=100&&t.statusCode<=599?t.statusCode:void 0,r={cause:e instanceof Error?e:void 0,...n===void 0?{}:{status:n},...t.retryAfterMs===void 0?{}:{providerRetryAfterMs:t.retryAfterMs},...t.requestId===void 0?{}:{requestId:p(t.requestId)}};for(let e of $n)if(e.match(t))return new f(e.message,e.code,r);return new f(`LLM 调用失败`,`TRANSPORT`,r)}const nr=e=>e;function $(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,Math.trunc(t)):0}function rr(e,t){let n=t?.name;return typeof n==`string`&&n.trim().length>0?n.trim():e}function ir(e){return e?.image===void 0?[`text`]:[`text`,`image`]}function ar(e){let t=e;if(!(t===void 0||t.image_max_bytes===void 0&&t.image_max_images===void 0&&t.image_byte_quantum===void 0&&t.image_count_quantum===void 0))return{representation:`base64`,...t.image_max_bytes===void 0?{}:{maxBytes:t.image_max_bytes},...t.image_max_images===void 0?{}:{maxImages:t.image_max_images},...t.image_byte_quantum===void 0?{}:{byteQuantum:t.image_byte_quantum},...t.image_count_quantum===void 0?{}:{countQuantum:t.image_count_quantum}}}function or(e){let t=e.workspace?.init_model??rn;try{if(Z(t).modelId===X)throw Error(`workspace.init_model must not reference auto`);return t}catch(e){throw new f(`workspace.init_model 非法:${t}(须为 provider/model,且不能是 auto)`,`INVALID_CONFIG`,{cause:e instanceof Error?e:void 0})}}function sr(e){try{let t=Z(e.workspace?.init_model??rn);return t.modelId===X?void 0:t}catch{return}}var cr=class extends d{#e;#t;#n;#r;#i;#a;#o;constructor(e){super(),this.#e=e.config,this.#t=e.auth,this.#n=e.llmLog,this.#r=e.callLogPaths,this.#i=e.resolveAttachments,this.#a=e.resolveImageAccess,this.#o=e.onImageProjection}refresh(e,t,n){this.#e=e,this.#t=t,this.#n=n}get llmLog(){return this.#n}providerInfo(e){let t=this.#e.provider?.[e]?.name,n=typeof t==`string`?t.trim():``;return{id:e,name:n.length>0?n:e}}listModels(e){if(!this.#c(e))return Promise.resolve([]);let t=this.#e.provider?.[e];if(t===void 0)return Promise.resolve([]);let n=[],r=new Set;for(let[i,a]of Object.entries(t.models)){if(i.length===0||r.has(i)){console.warn(`[tboxcode-llm] 跳过非法/重复模型条目: provider=${e} id="${i}"`);continue}if(i===X){console.warn(`[tboxcode-llm] 忽略显式 auto 条目(auto 是 workspace.init_model 虚拟 alias)`);continue}r.add(i);let t=rr(i,a);t.length!==0&&n.push({provider:e,id:i,name:t,inputModalities:ir(a)})}let i=sr(this.#e);if(i?.providerId===e){let r=t.models[i.modelId];r?.image===void 0?r===void 0?console.warn(`[tboxcode-llm] auto 目标模型不存在: ${i.providerId}/${i.modelId}`):console.warn(`[tboxcode-llm] auto 目标模型未声明 image: ${i.providerId}/${i.modelId}`):n.push({provider:e,id:X,name:`Auto`,inputModalities:ir(r)})}return Promise.resolve(n)}async resolveModel(e,t){return this.#s(this.#l(`${e}/${t}`))}imageRequestTarget(e,t,n){return Pn(this.#l(`${e}/${t}`).traits,n)}#s(e){let t=e.traits.reasoning?.effort,n=this.#e.effort,r=t?.levels!==void 0&&typeof n==`string`&&n.length>0&&t.levels.some(e=>e.id===n)?n:t?.default;return{provider:e.providerId,id:e.modelId,name:e.modelId===X?`Auto`:rr(e.modelId,e.traits),inputModalities:ir(e.traits),context:{contextWindow:e.traits.limit.context},defaultMaxTokens:e.traits.limit.output,...t?.levels!==void 0&&t.levels.length>0?{reasoning:{efforts:t.levels.map(e=>({id:nr(e.id),name:e.name??e.id})),...r===void 0?{}:{defaultEffort:nr(r)}}}:{}}}#c(e){if(this.#e.disabled_providers?.includes(e)===!0)return!1;let t=this.#e.enabled_providers;return t===void 0||t.length===0||t.includes(e)}providerRetryPolicy(e){let t=this.#e.provider?.[e]?.retry;return x(t??{mode:`normal`,maxRetries:2},`tboxcode-llm provider "${e}" retryPolicy`)}async*stream(e){yield*(await this.prepareCall(e.provider,e.model,e.signal)).stream(e)}async prepareCall(e,t,n){let r=this.#l(`${e}/${t}`);return{model:this.#s(r),stream:e=>this.#d(r,e)}}#l(e){try{let t=Z(e);if(t.modelId===X){let e=or(this.#e),n=Z(e);if(n.providerId!==t.providerId)throw new f(`auto 只挂在 workspace.init_model 的 provider 上:请求 ${t.providerId},目标 ${n.providerId}`,`INVALID_CONFIG`);if(!this.#c(n.providerId))throw new f(`auto 目标 provider 不可用:${n.providerId}`,`INVALID_CONFIG`);let r;try{r=fn(e,this.#e,this.#t)}catch(t){throw new f(`workspace.init_model 无法解析:${e}`,`INVALID_CONFIG`,{cause:t instanceof Error?t:void 0})}if(r.traits.image===void 0)throw new f(`workspace.init_model 必须声明 image:${e}`,`INVALID_CONFIG`);return{...r,modelId:X}}return fn(e,this.#e,this.#t)}catch(e){throw e instanceof f?e:e instanceof ft?new f(e.message,`UNKNOWN_MODEL`,{cause:e}):e instanceof Y||e instanceof pt||e instanceof mt?new f(e.message,`INVALID_CONFIG`,{cause:e}):e}}async#u(e,i){if(!this.#n.enabled||this.#r===void 0)return;let{root:a,cwdOf:s}=this.#r,c=i.sessionId===void 0?void 0:String(i.sessionId),l=`llmc_${o(8).toString(`hex`)}`,u;if(c!==void 0)try{let e=await s(c);u=e===void 0?r(a):t(a,e,c)}catch{u=r(a)}else u=r(a);let d=i.purpose,f=d===`compaction`?`compact`:d===`session-title`?`title`:`main`,p=n({enabled:!0,max_file_bytes:this.#n.max_file_bytes,sanitize_headers:this.#n.sanitize_headers,logDir:u,sessionId:c??`agentless`,trigger:f,callId:l,traitsVersion:ur(e.traits),provider_name:e.provider_name,modelId:i.model,upstream_model:e.upstream_model,protocol:e.traits.protocol,onError:(e,t)=>console.warn(`[tboxcode-llm] ${e}: ${String(t)}`)},gn(globalThis.fetch));return{fetch:p.fetch,drain:p.drain,callId:l}}async*#d(e,t){let n=e.traits,r=await this.#u(e,t),i=gt(n.reasoning?.effort,void 0,t.reasoningEffort),a=this.#e.provider?.[e.providerId]?.trace?.type===`sofa`?zn(Rn()):void 0,o={...e,credentials:{...e.credentials,headers:{...e.baseHeaders,...i===void 0?{}:e.effortHeaders?.[i],...a??{}}}},s=r?.fetch??globalThis.fetch.bind(globalThis),c=n.request_max_bytes===void 0?void 0:Ln(n.request_max_bytes,s),l=Bt(o,{headers:m(),...c===void 0&&r===void 0?{}:{fetch:c??r.fetch,...r===void 0?{}:{drain:r.drain}}}),{system:u}=t,d=this.#i?.(),p=e=>d===void 0||this.#a===void 0?void 0:this.#a(d,e),h=this.#e.media_policy,g=h?.mode===`project`,_=g?void 0:ar(n),v;try{v=await Nn(t.messages,d,{resolveAccess:p,targetOf:t=>this.imageRequestTarget(e.providerId,e.modelId,t),..._===void 0?{}:{budget:_},...g?{projection:{mode:`project`,protocol:n.protocol,requestMaxBytes:n.request_max_bytes,imageReserveBytes:h?.image_reserve_bytes,validateRef:e=>Fn(n,e),onProjection:n=>this.#o?.({...t.sessionId===void 0?{}:{sessionId:String(t.sessionId)},provider:e.providerId,model:t.model,...n})}}:{},...t.signal===void 0?{}:{signal:t.signal}})}catch(e){throw tr(e)}let y=Tn(v.messages,u,{images:v.versions,resolveImageAccess:p,protocol:n.protocol}),b=Dn(t.tools),x={sessionId:t.sessionId??`agentless`,effort:t.reasoningEffort,model:{id:t.model,context:n.limit.context,output:n.limit.output},reasoningEnabled:n.reasoning!==void 0},S=t.purpose!==`compaction`,C=Pt(y.messages,n,x,y.system,e.provider_name,{messageBreakpoints:S}),w=C.toolsCacheControl!==null&&C.toolsCacheControlKey!==null&&b!==void 0?Object.fromEntries(Object.entries(b).map(([e,t])=>[e,{...t,providerOptions:{...t.providerOptions,[C.toolsCacheControlKey]:{...t.providerOptions?.[C.toolsCacheControlKey]??{},cacheControl:C.toolsCacheControl}}}])):b,T=t.purpose===`compaction`?n.limit.output:t.maxTokens??n.limit.output,E=new AbortController,D=t.signal,ee=()=>E.abort(D?.reason);D!==void 0&&(D.aborted?E.abort(D.reason):D.addEventListener(`abort`,ee,{once:!0}));let te=l.streamText({model:{id:e.upstream_model,traits:n},system:C.system,messages:C.messages,providerOptions:C.providerOptions,tools:w,signal:E.signal,credentials:o.credentials,maxRetries:0,params:{...t.temperature===void 0?{}:{temperature:t.temperature},maxOutputTokens:T,...t.stop!==void 0&&t.stop.length>0?{stopSequences:t.stop}:{}}}),ne=0,re=()=>ne++,ie=n.protocol===`anthropic`,O=[],k=e=>{for(;O.length<=e;)O.push(null)},A=(e,t)=>{if(!ie)return;let n=xn(t);n!==void 0&&(k(e),O[e]={anthropic:n})},j=new Map,M=new Map,N=new Map,P,F=!1,I=!1,L=n.limit.idle_timeout_ms,R=te.fullStream[Symbol.asyncIterator](),z=!1,B,V=async()=>L===void 0?R.next():Promise.race([R.next(),new Promise((e,t)=>{B=setTimeout(()=>{z=!0;let e=new f(`LLM stream idle timeout`,`TIMEOUT`);E.abort(e),t(e)},L)})]);try{for(;;){let t=await V();if(B!==void 0&&(clearTimeout(B),B=void 0),t.done===!0)break;let n=t.value;switch(n.type){case`text-start`:{let e=String(n.id??``),t=re();k(t),j.set(e,{index:t,buffer:``}),F=!0,yield{type:`block-start`,index:t,blockType:`text`};break}case`text-delta`:{let e=String(n.id??``),t=j.get(e),r=String(n.text??``);if(t===void 0)break;F=!0,t.buffer+=r,yield{type:`text-delta`,index:t.index,text:r};break}case`text-end`:{let e=String(n.id??``),t=j.get(e);if(t===void 0)break;F=!0,j.delete(e),yield{type:`block-end`,index:t.index,block:{type:`text`,text:t.buffer}};break}case`reasoning-start`:{let e=String(n.id??``),t=re();k(t),A(t,n),M.set(e,{index:t,buffer:``}),F=!0,yield{type:`block-start`,index:t,blockType:`reasoning`};break}case`reasoning-delta`:{let e=String(n.id??``),t=M.get(e),r=String(n.text??``);if(t===void 0)break;A(t.index,n),F=!0,t.buffer+=r,yield{type:`reasoning-delta`,index:t.index,text:r};break}case`reasoning-end`:{let e=String(n.id??``),t=M.get(e);if(t===void 0)break;A(t.index,n),F=!0,M.delete(e),yield{type:`block-end`,index:t.index,block:{type:`reasoning`,text:t.buffer}};break}case`tool-input-start`:{let e=String(n.id??``),t=re();k(t),N.set(e,{index:t,name:String(n.toolName??``),buffer:``}),F=!0,yield{type:`block-start`,index:t,blockType:`tool-call`};break}case`tool-input-delta`:{let e=String(n.id??``),t=N.get(e);if(t===void 0)break;F=!0;let r=String(n.delta??``);t.buffer+=r,yield{type:`tool-call-delta`,index:t.index,id:nr(e),name:t.name,argumentsDelta:r};break}case`tool-call`:{let e=String(n.toolCallId??n.id??``),t=N.get(e);if(t===void 0)break;F=!0;let r=typeof n.toolName==`string`&&n.toolName.length>0?n.toolName:t.name;N.delete(e);let i=n.invalid===!0?t.buffer:JSON.stringify(n.input??{});yield{type:`block-end`,index:t.index,block:{type:`tool-call`,id:nr(e),name:r,arguments:i}};break}case`abort`:throw new f(`请求已取消`,`ABORTED`);case`error`:throw tr(n.error);case`finish-step`:P=n.usage;break;case`finish`:{let t=P??n.totalUsage??{},r=P?.raw??{},i=t.inputTokenDetails??{},a=t.outputTokenDetails??{},o=$(t.inputTokens),s=Math.max($(i.cacheReadTokens),$(r.prompt_cache_hit_tokens),$(r.cache_read_input_tokens)),c=Math.max($(i.cacheWriteTokens),$(r.cache_creation_input_tokens)),l=Math.max(o,s+c),u=Math.max(0,l-s-c),d=$(t.outputTokens),f=Math.max($(a.reasoningTokens),$(r.completion_tokens_details?.reasoning_tokens)),p=$(t.totalTokens)||$(r.total_tokens),m=l+d,h=p===m?p:m;yield{type:`usage`,usage:{inputTokens:u,outputTokens:d,...h>0?{totalTokens:h}:{},...s>0?{cacheReadTokens:s}:{},...c>0?{cacheWriteTokens:c}:{},...f>0&&f<=d?{reasoningTokens:f}:{}}};let g=lr(n.finishReason);g.kind===`stop`&&!F&&(g={kind:`error`,failure:{message:`model returned no content`,code:`EMPTY_RESPONSE`}});let _=ie&&g.kind!==`error`&&O.some(e=>e!==null);yield{type:`finish`,reason:g,..._?{replayState:{response:{provider:e.provider_name,model:e.upstream_model,...typeof n.finishReason==`string`?{finishReason:n.finishReason}:{}},blocks:O}}:{}},I=!0;break}default:break}}if(!I)throw D?.aborted?new f(`请求已取消`,`ABORTED`):new f(`LLM stream ended without a finish chunk`,`TRANSPORT`)}catch(e){throw z?new f(`LLM stream idle timeout`,`TIMEOUT`,{cause:e instanceof Error?e:void 0}):D?.aborted?new f(`请求已取消`,`ABORTED`,{cause:e instanceof Error?e:void 0}):tr(e)}finally{B!==void 0&&clearTimeout(B),D?.removeEventListener(`abort`,ee),await l.dispose()}}};function lr(e){switch(e){case`tool-calls`:return{kind:`tool-calls`};case`length`:return{kind:`max-tokens`};case`content-filter`:return{kind:`error`,failure:{message:`模型输出被内容安全策略拦截`,code:`INVALID_REQUEST`}};case`other`:case`unknown`:return{kind:`error`,failure:{message:`LLM 流以未识别的 finishReason 结束(可能被截断)`,code:`TRANSPORT`}};case`error`:return{kind:`error`,failure:{message:`stream error`,code:`SERVER`}};case`stop`:default:return{kind:`stop`}}}function ur(e){return Dt(e)}const dr=`tboxcode-llm`,fr=[`llm`];function pr(e){let t=e.get(`sessionPersistence`),n=t?.config?.root,r=t?.stat;if(!(n===void 0||r===void 0))return{root:n,cwdOf:async e=>(await r.call(t,e))?.header.cwd}}function mr(e){for(let t of[`auth.jsonc`,`auth.json`]){let n=l(e,t);if(S(n))try{w(n).mode&63&&console.warn(`[tboxcode-llm] auth 文件权限过宽(建议 0600): ${n}`);let e=ct(JSON.parse(st(C(n,`utf-8`))));return ln.parse(e)}catch(e){throw new f(`auth 文件解析失败(${n}):${e instanceof Error?e.message:String(e)}`,`INVALID_CREDENTIAL`)}}return{}}function hr(){let e=at(),t=lt(e).config;return{config:sn.parse(t),auth:mr(e)}}function gr(e){if(e instanceof E){let t=e.issues.slice(0,5).map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`),n=e.issues.length>t.length?`(共 ${e.issues.length} 项)`:``;return`config schema 校验失败:${t.join(`;`)}${n}`}return e instanceof Error?e.message:String(e)}function _r(e,t,n){let r=n?`——保存后自动注册,无需重启`:`——该配置目录为首次创建,配置后需重启进程`;if(e instanceof f&&e.code===`INVALID_ADAPTER`){console.warn(`[tboxcode-llm] config 未配置 provider——LLM 域待命(adapter 不注册,模型调用不可用)`),console.warn(`[tboxcode-llm] 编辑 ${l(t,`config.jsonc`)} 的 provider 段(示例见 tboxcode-dsh init --config 生成的模板注释)${r}`);return}if(e instanceof f&&e.code===`DUPLICATE_ADAPTER`){console.warn(`[tboxcode-llm] provider 路由注册冲突——LLM 域待命:${e.message}(路由 id 已被其他 adapter 占用,请更换 provider id)${r}`);return}console.warn(`[tboxcode-llm] config/auth 加载失败——LLM 域待命:${gr(e)}${r}`)}function vr(e,t){let n=e.provider??{},r=new Map;for(let[e,t]of Object.entries(n)){let n=typeof t.name==`string`&&t.name.trim().length>0?t.name.trim():e;r.set(n,[...r.get(n)??[],e])}for(let[e,t]of r)t.length>1&&console.warn(`[tboxcode-llm] provider 显示名重复: "${e}" (${t.join(`, `)})——GUI 分组可能同名,建议区分`);let i=Object.entries(n).filter(([,e])=>Object.values(e.models).some(e=>e.image!==void 0)).map(([e])=>e);if(i.length>0&&t.get(`attachments`)===void 0&&console.warn(`[tboxcode-llm] provider 声明了 image 但附件服务未挂载(${i.join(`, `)})——图片输入不可用`),e.model===void 0||e.model.length===0)return;let a=e.model.indexOf(`/`);if(a<=0||a===e.model.length-1){console.warn(`[tboxcode-llm] 默认模型引用格式无效: "${e.model}"(应为 provider/model)`);return}let o=e.model.slice(0,a),s=e.model.slice(a+1),c=n[o];if(c!==void 0){if(e.disabled_providers?.includes(o)===!0){console.warn(`[tboxcode-llm] 默认模型不可用: "${e.model}"(provider disabled)`);return}if(e.enabled_providers!==void 0&&e.enabled_providers.length>0&&!e.enabled_providers.includes(o)){console.warn(`[tboxcode-llm] 默认模型不可用: "${e.model}"(provider 不在 enabled_providers)`);return}c.models[s]===void 0&&console.warn(`[tboxcode-llm] 默认模型不可用: "${e.model}"(model 不存在)`)}}function yr(e){let t=at(),n=S(t),r,i,a,o=()=>{let t=hr(),n=Object.keys(t.config.provider??{});if(n.length===0)throw new f(`config 未配置 provider`,`INVALID_ADAPTER`);i=new cr({config:t.config,auth:t.auth,llmLog:dn(t.config.llm_log),callLogPaths:pr(e),resolveAttachments:()=>e.get(`attachments`),resolveImageAccess:(t,n)=>b(t,t=>e.get(`fs`)?.processPathFromHostPath?.(t),n),onImageProjection:e=>{console.warn(`[tboxcode-llm] ${JSON.stringify({event:`llm.image.projected`,...e})}`)}}),a=e.llm.registerAdapter(n,i),vr(t.config,e),r=t};try{o()}catch(e){_r(e,t,n)}let s;try{s=ut(t,[`config.jsonc`,`config.json`,`auth.jsonc`,`auth.json`],()=>{try{if(a===void 0){o(),console.warn(`[tboxcode-llm] provider 路由已注册(热载挂载):${Object.keys(r?.config.provider??{}).join(`, `)}`);return}let t=hr();i?.refresh?.(t.config,t.auth,dn(t.config.llm_log)),a.replace(Object.keys(t.config.provider??{})),vr(t.config,e),r=t}catch(e){let t=a===void 0?`维持待命`:`保留上一代`,n=e instanceof Error?e.message:String(e);console.warn(`[tboxcode-llm] 配置热载失败(${t}):${n}`)}})}catch{}return()=>{s?.dispose(),a?.()}}export{sn as LlmConfigSchema,Qt as ModelEntrySchema,Yt as ModelTraitsSchema,yr as apply,fr as inject,dr as name};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/tboxcode-dsh-llm",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.7",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "LlmAdapter:三协议 + traits + 限流 + call-log(zstd)+ echo / scenario driver + listModels GUI 硬规格 + adapters-updated 刷新",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -45,8 +45,8 @@
|
|
|
45
45
|
"@types/ws": "^8.18.0",
|
|
46
46
|
"ws": "^8.19.0",
|
|
47
47
|
"yaml": "^2.8.0",
|
|
48
|
-
"@tbox.cn/tboxcode-dsh-runtime": "0.1.0-rc.
|
|
49
|
-
"@tbox.cn/tboxcode-dsh-cli": "0.1.0-rc.
|
|
48
|
+
"@tbox.cn/tboxcode-dsh-runtime": "0.1.0-rc.7",
|
|
49
|
+
"@tbox.cn/tboxcode-dsh-cli": "0.1.0-rc.7"
|
|
50
50
|
},
|
|
51
51
|
"dsh": {
|
|
52
52
|
"bundle": {
|