@codelia/core 0.1.75 → 0.1.76
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/LICENSE +19 -0
- package/dist/index.cjs +1917 -377
- package/dist/index.d.ts +142 -18
- package/dist/index.js +1905 -373
- package/package.json +6 -6
- package/dist/index.d.cts +0 -875
package/dist/index.js
CHANGED
|
@@ -6,7 +6,6 @@ var OPENAI_DEFAULT_MODEL = "gpt-5.6";
|
|
|
6
6
|
var OPENAI_DEFAULT_REASONING_EFFORT = "medium";
|
|
7
7
|
var GPT_5_6_CONTEXT_WINDOW = 105e4;
|
|
8
8
|
var GPT_5_6_CAPPED_INPUT_TOKENS = 27e4;
|
|
9
|
-
var GPT_5_6_FULL_INPUT_TOKENS = 922e3;
|
|
10
9
|
var GPT_5_6_MAX_OUTPUT_TOKENS = 128e3;
|
|
11
10
|
var GPT_5_4_CAPPED_INPUT_TOKENS = 272e3;
|
|
12
11
|
var GPT_5_6_PROVIDER_MODELS = [
|
|
@@ -15,32 +14,16 @@ var GPT_5_6_PROVIDER_MODELS = [
|
|
|
15
14
|
"gpt-5.6-terra",
|
|
16
15
|
"gpt-5.6-luna"
|
|
17
16
|
];
|
|
18
|
-
var
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
},
|
|
27
|
-
{
|
|
28
|
-
id: `${providerModelId}-1M`,
|
|
29
|
-
provider: "openai",
|
|
30
|
-
providerModelId,
|
|
31
|
-
aliases: [`${providerModelId}-1m`, `${providerModelId}-full`],
|
|
32
|
-
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
33
|
-
maxInputTokens: GPT_5_6_FULL_INPUT_TOKENS,
|
|
34
|
-
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS
|
|
35
|
-
}
|
|
36
|
-
];
|
|
17
|
+
var buildGpt56Model = (id) => ({
|
|
18
|
+
id,
|
|
19
|
+
provider: "openai",
|
|
20
|
+
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
21
|
+
maxInputTokens: GPT_5_6_CAPPED_INPUT_TOKENS,
|
|
22
|
+
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS,
|
|
23
|
+
supportsFast: true
|
|
24
|
+
});
|
|
37
25
|
var OPENAI_MODELS = [
|
|
38
|
-
|
|
39
|
-
id: OPENAI_DEFAULT_MODEL,
|
|
40
|
-
provider: "openai",
|
|
41
|
-
aliases: ["default"]
|
|
42
|
-
},
|
|
43
|
-
...GPT_5_6_PROVIDER_MODELS.flatMap(buildGpt56Models),
|
|
26
|
+
...GPT_5_6_PROVIDER_MODELS.map(buildGpt56Model),
|
|
44
27
|
{
|
|
45
28
|
id: "gpt-5.5",
|
|
46
29
|
provider: "openai",
|
|
@@ -216,6 +199,9 @@ configRegistry.registerDefaults({
|
|
|
216
199
|
}
|
|
217
200
|
});
|
|
218
201
|
|
|
202
|
+
// src/agent/agent.ts
|
|
203
|
+
import { performance } from "perf_hooks";
|
|
204
|
+
|
|
219
205
|
// src/content/stringify.ts
|
|
220
206
|
var stringifyUnknown = (value) => {
|
|
221
207
|
try {
|
|
@@ -264,9 +250,6 @@ var stringifyContent = (content, options = {}) => {
|
|
|
264
250
|
return stringifyContentParts(content, options);
|
|
265
251
|
};
|
|
266
252
|
|
|
267
|
-
// src/agent/agent.ts
|
|
268
|
-
import { performance } from "perf_hooks";
|
|
269
|
-
|
|
270
253
|
// src/history/store.ts
|
|
271
254
|
var MessageHistoryAdapter = class {
|
|
272
255
|
messages = [];
|
|
@@ -306,6 +289,429 @@ var MessageHistoryAdapter = class {
|
|
|
306
289
|
}
|
|
307
290
|
};
|
|
308
291
|
|
|
292
|
+
// src/llm/failures.ts
|
|
293
|
+
var ProviderFailureError = class extends Error {
|
|
294
|
+
failure;
|
|
295
|
+
attempts;
|
|
296
|
+
maxAttempts;
|
|
297
|
+
constructor(failure, options = {}) {
|
|
298
|
+
super(failure.safeMessage, { cause: options.cause });
|
|
299
|
+
this.name = "ProviderFailureError";
|
|
300
|
+
this.failure = failure;
|
|
301
|
+
this.attempts = options.attempts ?? 1;
|
|
302
|
+
this.maxAttempts = options.maxAttempts ?? this.attempts;
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
var ProviderTimeoutError = class extends Error {
|
|
306
|
+
constructor(message) {
|
|
307
|
+
super(message);
|
|
308
|
+
this.name = "ProviderTimeoutError";
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
var isProviderFailureError = (error) => error instanceof ProviderFailureError;
|
|
312
|
+
var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
313
|
+
var readString = (record, key) => {
|
|
314
|
+
const value = record?.[key];
|
|
315
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
316
|
+
};
|
|
317
|
+
var readStatus = (error) => {
|
|
318
|
+
const value = asRecord(error)?.status;
|
|
319
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : void 0;
|
|
320
|
+
};
|
|
321
|
+
var readHeader = (headers, name) => {
|
|
322
|
+
if (headers instanceof Headers) {
|
|
323
|
+
return headers.get(name);
|
|
324
|
+
}
|
|
325
|
+
const record = asRecord(headers);
|
|
326
|
+
if (!record) return null;
|
|
327
|
+
const direct = record[name] ?? record[name.toLowerCase()];
|
|
328
|
+
return typeof direct === "string" ? direct : null;
|
|
329
|
+
};
|
|
330
|
+
var parsePositiveNumber = (value) => {
|
|
331
|
+
if (!value) return void 0;
|
|
332
|
+
const parsed = Number(value.trim());
|
|
333
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
|
|
334
|
+
};
|
|
335
|
+
var parseRetryAfterMs = (value, nowMs) => {
|
|
336
|
+
const seconds = parsePositiveNumber(value);
|
|
337
|
+
if (seconds !== void 0) return Math.round(seconds * 1e3);
|
|
338
|
+
if (!value) return void 0;
|
|
339
|
+
const retryAtMs = Date.parse(value.trim());
|
|
340
|
+
return Number.isFinite(retryAtMs) ? Math.max(0, Math.round(retryAtMs - nowMs())) : void 0;
|
|
341
|
+
};
|
|
342
|
+
var readRetryAfterMs = (error, nowMs = Date.now) => {
|
|
343
|
+
const headers = asRecord(error)?.headers;
|
|
344
|
+
const directMs = parsePositiveNumber(readHeader(headers, "retry-after-ms"));
|
|
345
|
+
if (directMs !== void 0) return Math.round(directMs);
|
|
346
|
+
return parseRetryAfterMs(readHeader(headers, "retry-after"), nowMs);
|
|
347
|
+
};
|
|
348
|
+
var extractProviderError = (error) => {
|
|
349
|
+
const root = asRecord(error);
|
|
350
|
+
const body = asRecord(root?.error);
|
|
351
|
+
const nested = asRecord(body?.error) ?? body;
|
|
352
|
+
const type = readString(nested, "type") ?? readString(body, "type") ?? readString(root, "type");
|
|
353
|
+
const codeValue = nested?.code ?? body?.code ?? root?.code;
|
|
354
|
+
const code = typeof codeValue === "string" || typeof codeValue === "number" ? codeValue : void 0;
|
|
355
|
+
const message = readString(nested, "message") ?? readString(body, "message") ?? readString(root, "message") ?? (error instanceof Error ? error.message : "Provider request failed");
|
|
356
|
+
return {
|
|
357
|
+
status: readStatus(error),
|
|
358
|
+
type,
|
|
359
|
+
code,
|
|
360
|
+
message,
|
|
361
|
+
retryAfterMs: readRetryAfterMs(error)
|
|
362
|
+
};
|
|
363
|
+
};
|
|
364
|
+
var getRetryHint = (extracted) => extracted.retryAfterMs !== void 0 ? {
|
|
365
|
+
retryAfterMs: extracted.retryAfterMs,
|
|
366
|
+
delaySource: "retry-after"
|
|
367
|
+
} : {};
|
|
368
|
+
var isValidationStatus = (status) => status === 400 || status === 404 || status === 422;
|
|
369
|
+
var isAbortLikeProviderError = (error) => {
|
|
370
|
+
const name = error instanceof Error ? error.name : readString(asRecord(error), "name");
|
|
371
|
+
return name === "AbortError" || name === "APIUserAbortError" || name === "AbortSignal";
|
|
372
|
+
};
|
|
373
|
+
var PROVIDER_LABELS = {
|
|
374
|
+
openai: "OpenAI",
|
|
375
|
+
anthropic: "Anthropic",
|
|
376
|
+
openrouter: "OpenRouter",
|
|
377
|
+
google: "Provider",
|
|
378
|
+
moonshot: "Moonshot",
|
|
379
|
+
zai: "Z.ai",
|
|
380
|
+
xai: "xAI"
|
|
381
|
+
};
|
|
382
|
+
var safeProviderMessage = (provider, kind) => {
|
|
383
|
+
const label = PROVIDER_LABELS[provider];
|
|
384
|
+
switch (kind) {
|
|
385
|
+
case "hard_quota":
|
|
386
|
+
return `${label} quota is exhausted for the interactive retry window. Wait for reset, review billing, or switch provider.`;
|
|
387
|
+
case "rate_limit":
|
|
388
|
+
return `${label} rate limit was reached. Try again shortly or switch provider.`;
|
|
389
|
+
case "overloaded":
|
|
390
|
+
return `${label} is temporarily overloaded. Try again shortly or switch provider.`;
|
|
391
|
+
case "timeout":
|
|
392
|
+
return `${label} request timed out.`;
|
|
393
|
+
case "network":
|
|
394
|
+
return `${label} request failed because of a network error.`;
|
|
395
|
+
case "auth":
|
|
396
|
+
return `${label} authentication failed. Check the configured credentials.`;
|
|
397
|
+
case "permission":
|
|
398
|
+
return `${label} rejected the request because the account lacks permission.`;
|
|
399
|
+
case "validation":
|
|
400
|
+
return `${label} rejected the request as invalid.`;
|
|
401
|
+
case "cancelled":
|
|
402
|
+
return `${label} request was cancelled.`;
|
|
403
|
+
case "provider":
|
|
404
|
+
return `${label} request failed.`;
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
var buildProviderFailure = (provider, kind, options = {}) => ({
|
|
408
|
+
provider,
|
|
409
|
+
kind,
|
|
410
|
+
retryable: options.retryable ?? false,
|
|
411
|
+
safeMessage: safeProviderMessage(provider, kind),
|
|
412
|
+
...options.status !== void 0 ? { status: options.status } : {},
|
|
413
|
+
...options.retryAfterMs !== void 0 ? { retryAfterMs: options.retryAfterMs } : {},
|
|
414
|
+
...options.delaySource ? { delaySource: options.delaySource } : {},
|
|
415
|
+
...options.delivery ? { delivery: options.delivery } : {}
|
|
416
|
+
});
|
|
417
|
+
var MAX_SAFE_PROVIDER_MESSAGE_CHARS = 500;
|
|
418
|
+
var createProviderValidationError = (provider, message) => {
|
|
419
|
+
const boundedMessage = message.length <= MAX_SAFE_PROVIDER_MESSAGE_CHARS ? message : `${message.slice(0, MAX_SAFE_PROVIDER_MESSAGE_CHARS - 3)}...`;
|
|
420
|
+
return new ProviderFailureError({
|
|
421
|
+
...buildProviderFailure(provider, "validation"),
|
|
422
|
+
safeMessage: boundedMessage
|
|
423
|
+
});
|
|
424
|
+
};
|
|
425
|
+
var classifyTransportFailure = (provider, error) => {
|
|
426
|
+
const name = error instanceof Error ? error.name : "";
|
|
427
|
+
if (name.includes("Timeout")) {
|
|
428
|
+
return buildProviderFailure(provider, "timeout", { retryable: true });
|
|
429
|
+
}
|
|
430
|
+
if (name.includes("Connection") || error instanceof TypeError) {
|
|
431
|
+
return buildProviderFailure(provider, "network", { retryable: true });
|
|
432
|
+
}
|
|
433
|
+
return null;
|
|
434
|
+
};
|
|
435
|
+
var classifyOpenAiCompatibleFailure = (provider, error) => {
|
|
436
|
+
if (isAbortLikeProviderError(error)) {
|
|
437
|
+
return buildProviderFailure(provider, "cancelled");
|
|
438
|
+
}
|
|
439
|
+
const extracted = extractProviderError(error);
|
|
440
|
+
const status = extracted.status;
|
|
441
|
+
const code = String(extracted.code ?? "").toLowerCase();
|
|
442
|
+
const type = String(extracted.type ?? "").toLowerCase();
|
|
443
|
+
const message = extracted.message.toLowerCase();
|
|
444
|
+
const retryOptions = getRetryHint(extracted);
|
|
445
|
+
if (status === 401) return buildProviderFailure(provider, "auth", { status });
|
|
446
|
+
if (status === 403) {
|
|
447
|
+
return buildProviderFailure(provider, "permission", { status });
|
|
448
|
+
}
|
|
449
|
+
if (isValidationStatus(status)) {
|
|
450
|
+
return buildProviderFailure(provider, "validation", { status });
|
|
451
|
+
}
|
|
452
|
+
if (status === 402 || code.includes("insufficient_quota") || type.includes("payment_required") || message.includes("insufficient credit") || message.includes("quota exceeded") || message.includes("exceeded your current quota")) {
|
|
453
|
+
return buildProviderFailure(provider, "hard_quota", { status });
|
|
454
|
+
}
|
|
455
|
+
if (status === 408) {
|
|
456
|
+
return buildProviderFailure(provider, "timeout", {
|
|
457
|
+
status,
|
|
458
|
+
retryable: true,
|
|
459
|
+
...retryOptions
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
if (status === 409) {
|
|
463
|
+
return buildProviderFailure(provider, "provider", {
|
|
464
|
+
status,
|
|
465
|
+
retryable: true,
|
|
466
|
+
...retryOptions
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
if (type.includes("provider_overloaded") || type.includes("provider_unavailable") || status === 529 || status === 503) {
|
|
470
|
+
return buildProviderFailure(provider, "overloaded", {
|
|
471
|
+
status,
|
|
472
|
+
retryable: true,
|
|
473
|
+
...retryOptions
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
if (status === 429 || type.includes("rate_limit") || code.includes("rate_limit")) {
|
|
477
|
+
return buildProviderFailure(provider, "rate_limit", {
|
|
478
|
+
status,
|
|
479
|
+
retryable: true,
|
|
480
|
+
...retryOptions
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
if (status !== void 0 && status >= 500) {
|
|
484
|
+
return buildProviderFailure(provider, "provider", {
|
|
485
|
+
status,
|
|
486
|
+
retryable: true,
|
|
487
|
+
...retryOptions
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
return classifyTransportFailure(provider, error) ?? buildProviderFailure(provider, "provider");
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
// src/llm/retry.ts
|
|
494
|
+
var DEFAULT_LLM_RETRY_POLICY = {
|
|
495
|
+
maxRetries: 2,
|
|
496
|
+
baseDelayMs: 1e3,
|
|
497
|
+
maxDelayMs: 6e4,
|
|
498
|
+
maxRetryAfterMs: 6e4,
|
|
499
|
+
retryWindowMs: 20 * 60 * 1e3
|
|
500
|
+
};
|
|
501
|
+
var finitePolicyValue = (value, fallback, minimum) => typeof value === "number" && Number.isFinite(value) && value >= minimum ? Math.trunc(value) : fallback;
|
|
502
|
+
var resolveLlmRetryPolicy = (overrides = {}) => ({
|
|
503
|
+
maxRetries: finitePolicyValue(
|
|
504
|
+
overrides.maxRetries,
|
|
505
|
+
DEFAULT_LLM_RETRY_POLICY.maxRetries,
|
|
506
|
+
0
|
|
507
|
+
),
|
|
508
|
+
baseDelayMs: finitePolicyValue(
|
|
509
|
+
overrides.baseDelayMs,
|
|
510
|
+
DEFAULT_LLM_RETRY_POLICY.baseDelayMs,
|
|
511
|
+
0
|
|
512
|
+
),
|
|
513
|
+
maxDelayMs: finitePolicyValue(
|
|
514
|
+
overrides.maxDelayMs,
|
|
515
|
+
DEFAULT_LLM_RETRY_POLICY.maxDelayMs,
|
|
516
|
+
0
|
|
517
|
+
),
|
|
518
|
+
maxRetryAfterMs: finitePolicyValue(
|
|
519
|
+
overrides.maxRetryAfterMs,
|
|
520
|
+
DEFAULT_LLM_RETRY_POLICY.maxRetryAfterMs,
|
|
521
|
+
0
|
|
522
|
+
),
|
|
523
|
+
retryWindowMs: finitePolicyValue(
|
|
524
|
+
overrides.retryWindowMs,
|
|
525
|
+
DEFAULT_LLM_RETRY_POLICY.retryWindowMs,
|
|
526
|
+
1
|
|
527
|
+
)
|
|
528
|
+
});
|
|
529
|
+
var createAbortError = () => {
|
|
530
|
+
const error = new Error("Operation aborted");
|
|
531
|
+
error.name = "AbortError";
|
|
532
|
+
return error;
|
|
533
|
+
};
|
|
534
|
+
var defaultSleep = (delayMs, signal) => new Promise((resolve, reject) => {
|
|
535
|
+
if (signal?.aborted) {
|
|
536
|
+
reject(createAbortError());
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
let timeout = setTimeout(
|
|
540
|
+
() => {
|
|
541
|
+
timeout = void 0;
|
|
542
|
+
signal?.removeEventListener("abort", onAbort);
|
|
543
|
+
resolve();
|
|
544
|
+
},
|
|
545
|
+
Math.max(0, delayMs)
|
|
546
|
+
);
|
|
547
|
+
const onAbort = () => {
|
|
548
|
+
if (timeout) {
|
|
549
|
+
clearTimeout(timeout);
|
|
550
|
+
timeout = void 0;
|
|
551
|
+
}
|
|
552
|
+
signal?.removeEventListener("abort", onAbort);
|
|
553
|
+
reject(createAbortError());
|
|
554
|
+
};
|
|
555
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
556
|
+
});
|
|
557
|
+
var createRetryWindowSignal = (parent, windowMs) => {
|
|
558
|
+
const controller = new AbortController();
|
|
559
|
+
let expired = false;
|
|
560
|
+
const onParentAbort = () => controller.abort(parent?.reason);
|
|
561
|
+
if (parent?.aborted) {
|
|
562
|
+
onParentAbort();
|
|
563
|
+
} else {
|
|
564
|
+
parent?.addEventListener("abort", onParentAbort, { once: true });
|
|
565
|
+
}
|
|
566
|
+
const timeout = setTimeout(() => {
|
|
567
|
+
expired = true;
|
|
568
|
+
controller.abort(new Error("LLM retry window elapsed"));
|
|
569
|
+
}, windowMs);
|
|
570
|
+
return {
|
|
571
|
+
signal: controller.signal,
|
|
572
|
+
didExpire: () => expired,
|
|
573
|
+
cleanup: () => {
|
|
574
|
+
clearTimeout(timeout);
|
|
575
|
+
parent?.removeEventListener("abort", onParentAbort);
|
|
576
|
+
}
|
|
577
|
+
};
|
|
578
|
+
};
|
|
579
|
+
var toClassifiedFailure = (error, classifyFailure) => {
|
|
580
|
+
if (isProviderFailureError(error)) return error.failure;
|
|
581
|
+
return classifyFailure?.(error) ?? null;
|
|
582
|
+
};
|
|
583
|
+
var RETRY_STOP_SUFFIXES = {
|
|
584
|
+
retry_exhausted: " Automatic retry attempts were exhausted.",
|
|
585
|
+
retry_after_too_long: " The provider requested a wait longer than Codelia's automatic retry limit.",
|
|
586
|
+
retry_window_elapsed: " The automatic retry window elapsed before another attempt could start."
|
|
587
|
+
};
|
|
588
|
+
var withFinalMessage = (failure, reason) => {
|
|
589
|
+
return {
|
|
590
|
+
...failure,
|
|
591
|
+
retryable: false,
|
|
592
|
+
safeMessage: `${failure.safeMessage}${RETRY_STOP_SUFFIXES[reason]}`
|
|
593
|
+
};
|
|
594
|
+
};
|
|
595
|
+
var createTerminalProviderError = (options) => new ProviderFailureError(
|
|
596
|
+
options.reason ? withFinalMessage(options.failure, options.reason) : options.failure,
|
|
597
|
+
{
|
|
598
|
+
attempts: options.attempt,
|
|
599
|
+
maxAttempts: options.maxAttempts,
|
|
600
|
+
...options.cause !== void 0 ? { cause: options.cause } : {}
|
|
601
|
+
}
|
|
602
|
+
);
|
|
603
|
+
var calculateBackoffMs = (attempt, policy, random) => {
|
|
604
|
+
const exponential = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);
|
|
605
|
+
const jittered = exponential * (0.5 + Math.min(1, Math.max(0, random())) * 0.5);
|
|
606
|
+
return Math.min(policy.maxDelayMs, Math.max(0, Math.round(jittered)));
|
|
607
|
+
};
|
|
608
|
+
var planRetry = (options) => {
|
|
609
|
+
const { failure, attempt, maxAttempts, elapsedMs, policy, random } = options;
|
|
610
|
+
if (!failure.retryable) return { type: "stop", failure };
|
|
611
|
+
if (attempt >= maxAttempts) {
|
|
612
|
+
return { type: "stop", failure, reason: "retry_exhausted" };
|
|
613
|
+
}
|
|
614
|
+
if (failure.retryAfterMs !== void 0 && failure.retryAfterMs > policy.maxRetryAfterMs) {
|
|
615
|
+
return { type: "stop", failure, reason: "retry_after_too_long" };
|
|
616
|
+
}
|
|
617
|
+
const delayMs = failure.retryAfterMs ?? calculateBackoffMs(attempt, policy, random);
|
|
618
|
+
if (elapsedMs + delayMs >= policy.retryWindowMs) {
|
|
619
|
+
return { type: "stop", failure, reason: "retry_window_elapsed" };
|
|
620
|
+
}
|
|
621
|
+
return {
|
|
622
|
+
type: "retry",
|
|
623
|
+
delayMs,
|
|
624
|
+
delaySource: failure.delaySource ?? "backoff"
|
|
625
|
+
};
|
|
626
|
+
};
|
|
627
|
+
var toRetryEvent = (failure, options) => ({
|
|
628
|
+
type: "llm.retry",
|
|
629
|
+
provider: failure.provider,
|
|
630
|
+
failure_kind: failure.kind,
|
|
631
|
+
next_attempt: options.nextAttempt,
|
|
632
|
+
max_attempts: options.maxAttempts,
|
|
633
|
+
delay_ms: options.delayMs,
|
|
634
|
+
delay_source: options.delaySource,
|
|
635
|
+
...failure.status !== void 0 ? { status: failure.status } : {}
|
|
636
|
+
});
|
|
637
|
+
async function* invokeWithRetry({
|
|
638
|
+
operation,
|
|
639
|
+
classifyFailure,
|
|
640
|
+
policy,
|
|
641
|
+
signal,
|
|
642
|
+
dependencies = {}
|
|
643
|
+
}) {
|
|
644
|
+
const nowMs = dependencies.nowMs ?? Date.now;
|
|
645
|
+
const random = dependencies.random ?? Math.random;
|
|
646
|
+
const sleep = dependencies.sleep ?? defaultSleep;
|
|
647
|
+
const maxAttempts = Math.max(1, Math.trunc(policy.maxRetries) + 1);
|
|
648
|
+
const startedAt = nowMs();
|
|
649
|
+
const retryWindow = createRetryWindowSignal(signal, policy.retryWindowMs);
|
|
650
|
+
let attempt = 1;
|
|
651
|
+
try {
|
|
652
|
+
while (true) {
|
|
653
|
+
if (signal?.aborted) throw createAbortError();
|
|
654
|
+
try {
|
|
655
|
+
return await operation(signal);
|
|
656
|
+
} catch (error) {
|
|
657
|
+
if (signal?.aborted) throw createAbortError();
|
|
658
|
+
const failure = toClassifiedFailure(error, classifyFailure);
|
|
659
|
+
if (!failure) throw error;
|
|
660
|
+
if (failure.kind === "cancelled") throw createAbortError();
|
|
661
|
+
const decision = planRetry({
|
|
662
|
+
failure,
|
|
663
|
+
attempt,
|
|
664
|
+
maxAttempts,
|
|
665
|
+
elapsedMs: retryWindow.didExpire() ? policy.retryWindowMs : Math.max(0, nowMs() - startedAt),
|
|
666
|
+
policy,
|
|
667
|
+
random
|
|
668
|
+
});
|
|
669
|
+
if (decision.type === "stop") {
|
|
670
|
+
throw createTerminalProviderError({
|
|
671
|
+
failure: decision.failure,
|
|
672
|
+
attempt,
|
|
673
|
+
maxAttempts,
|
|
674
|
+
cause: error,
|
|
675
|
+
...decision.reason ? { reason: decision.reason } : {}
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
yield toRetryEvent(failure, {
|
|
679
|
+
nextAttempt: attempt + 1,
|
|
680
|
+
maxAttempts,
|
|
681
|
+
delayMs: decision.delayMs,
|
|
682
|
+
delaySource: decision.delaySource
|
|
683
|
+
});
|
|
684
|
+
try {
|
|
685
|
+
await sleep(decision.delayMs, retryWindow.signal);
|
|
686
|
+
} catch (sleepError) {
|
|
687
|
+
if (signal?.aborted) throw createAbortError();
|
|
688
|
+
if (retryWindow.didExpire()) {
|
|
689
|
+
throw createTerminalProviderError({
|
|
690
|
+
failure,
|
|
691
|
+
attempt,
|
|
692
|
+
maxAttempts,
|
|
693
|
+
cause: sleepError,
|
|
694
|
+
reason: "retry_window_elapsed"
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
throw sleepError;
|
|
698
|
+
}
|
|
699
|
+
if (retryWindow.didExpire() || Math.max(0, nowMs() - startedAt) >= policy.retryWindowMs) {
|
|
700
|
+
throw createTerminalProviderError({
|
|
701
|
+
failure,
|
|
702
|
+
attempt,
|
|
703
|
+
maxAttempts,
|
|
704
|
+
reason: "retry_window_elapsed"
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
attempt += 1;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
} finally {
|
|
711
|
+
retryWindow.cleanup();
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
309
715
|
// src/llm/openai/history.ts
|
|
310
716
|
var ResponsesHistoryAdapter = class extends MessageHistoryAdapter {
|
|
311
717
|
};
|
|
@@ -325,6 +731,14 @@ var ANTHROPIC_MODELS = [
|
|
|
325
731
|
maxInputTokens: 1e6,
|
|
326
732
|
maxOutputTokens: 128e3
|
|
327
733
|
},
|
|
734
|
+
{
|
|
735
|
+
id: "claude-opus-5",
|
|
736
|
+
provider: "anthropic",
|
|
737
|
+
contextWindow: 1e6,
|
|
738
|
+
maxInputTokens: 1e6,
|
|
739
|
+
maxOutputTokens: 128e3,
|
|
740
|
+
supportsFast: true
|
|
741
|
+
},
|
|
328
742
|
{
|
|
329
743
|
id: "claude-opus-4-8",
|
|
330
744
|
provider: "anthropic",
|
|
@@ -388,6 +802,23 @@ var GOOGLE_MODELS = [
|
|
|
388
802
|
}
|
|
389
803
|
];
|
|
390
804
|
|
|
805
|
+
// src/models/moonshot.ts
|
|
806
|
+
var MOONSHOT_DEFAULT_MODEL = "kimi-k3";
|
|
807
|
+
var MOONSHOT_MODELS = [
|
|
808
|
+
{
|
|
809
|
+
id: MOONSHOT_DEFAULT_MODEL,
|
|
810
|
+
provider: "moonshot",
|
|
811
|
+
aliases: ["default"],
|
|
812
|
+
contextWindow: 1048576,
|
|
813
|
+
maxInputTokens: 1048576,
|
|
814
|
+
maxOutputTokens: 1048576,
|
|
815
|
+
supportsTools: true,
|
|
816
|
+
supportsVision: true,
|
|
817
|
+
supportsReasoning: true,
|
|
818
|
+
supportsJsonSchema: true
|
|
819
|
+
}
|
|
820
|
+
];
|
|
821
|
+
|
|
391
822
|
// src/models/registry.ts
|
|
392
823
|
function createModelRegistry(specs) {
|
|
393
824
|
const registry = {
|
|
@@ -397,7 +828,9 @@ function createModelRegistry(specs) {
|
|
|
397
828
|
anthropic: {},
|
|
398
829
|
openrouter: {},
|
|
399
830
|
google: {},
|
|
400
|
-
|
|
831
|
+
moonshot: {},
|
|
832
|
+
zai: {},
|
|
833
|
+
xai: {}
|
|
401
834
|
}
|
|
402
835
|
};
|
|
403
836
|
registerModels(registry, specs);
|
|
@@ -458,7 +891,9 @@ function cloneAliases(aliasesByProvider) {
|
|
|
458
891
|
anthropic: { ...aliasesByProvider.anthropic },
|
|
459
892
|
openrouter: { ...aliasesByProvider.openrouter },
|
|
460
893
|
google: { ...aliasesByProvider.google },
|
|
461
|
-
|
|
894
|
+
moonshot: { ...aliasesByProvider.moonshot },
|
|
895
|
+
zai: { ...aliasesByProvider.zai },
|
|
896
|
+
xai: { ...aliasesByProvider.xai }
|
|
462
897
|
};
|
|
463
898
|
}
|
|
464
899
|
function applyModelMetadata(registry, index) {
|
|
@@ -467,7 +902,7 @@ function applyModelMetadata(registry, index) {
|
|
|
467
902
|
aliasesByProvider: cloneAliases(registry.aliasesByProvider)
|
|
468
903
|
};
|
|
469
904
|
for (const [providerId, providerModels] of Object.entries(index.models)) {
|
|
470
|
-
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google" && providerId !== "zai") {
|
|
905
|
+
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google" && providerId !== "moonshot" && providerId !== "zai" && providerId !== "xai") {
|
|
471
906
|
continue;
|
|
472
907
|
}
|
|
473
908
|
const provider = providerId;
|
|
@@ -487,6 +922,23 @@ function applyModelMetadata(registry, index) {
|
|
|
487
922
|
return next;
|
|
488
923
|
}
|
|
489
924
|
|
|
925
|
+
// src/models/xai.ts
|
|
926
|
+
var XAI_DEFAULT_MODEL = "grok-4.5";
|
|
927
|
+
var XAI_DEFAULT_REASONING_EFFORT = "high";
|
|
928
|
+
var XAI_MODELS = [
|
|
929
|
+
{
|
|
930
|
+
id: XAI_DEFAULT_MODEL,
|
|
931
|
+
provider: "xai",
|
|
932
|
+
aliases: ["grok-4.5-latest", "grok-build-latest"],
|
|
933
|
+
contextWindow: 5e5,
|
|
934
|
+
maxInputTokens: 2e5,
|
|
935
|
+
supportsTools: true,
|
|
936
|
+
supportsVision: true,
|
|
937
|
+
supportsReasoning: true,
|
|
938
|
+
supportsJsonSchema: true
|
|
939
|
+
}
|
|
940
|
+
];
|
|
941
|
+
|
|
490
942
|
// src/models/zai.ts
|
|
491
943
|
var ZAI_DEFAULT_MODEL = "glm-5.2";
|
|
492
944
|
var ZAI_REASONING_EFFORT_MODELS = /* @__PURE__ */ new Set(["glm-5.2"]);
|
|
@@ -530,7 +982,9 @@ var DEFAULT_MODEL_REGISTRY = createModelRegistry([
|
|
|
530
982
|
...OPENAI_MODELS,
|
|
531
983
|
...ANTHROPIC_MODELS,
|
|
532
984
|
...GOOGLE_MODELS,
|
|
533
|
-
...
|
|
985
|
+
...MOONSHOT_MODELS,
|
|
986
|
+
...ZAI_MODELS,
|
|
987
|
+
...XAI_MODELS
|
|
534
988
|
]);
|
|
535
989
|
|
|
536
990
|
// src/services/compaction/service.ts
|
|
@@ -895,7 +1349,7 @@ var parseQualifiedModelId = (modelId) => {
|
|
|
895
1349
|
if (!rest) {
|
|
896
1350
|
return null;
|
|
897
1351
|
}
|
|
898
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
1352
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "moonshot" && providerRaw !== "zai" && providerRaw !== "xai") {
|
|
899
1353
|
return null;
|
|
900
1354
|
}
|
|
901
1355
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -946,6 +1400,7 @@ var contentToText = (content) => {
|
|
|
946
1400
|
}
|
|
947
1401
|
}).join("");
|
|
948
1402
|
};
|
|
1403
|
+
var hasNonTextParts = (content) => Array.isArray(content) && content.some((part) => part.type !== "text");
|
|
949
1404
|
var estimateTokens = (text) => Math.ceil(Buffer.byteLength(text, "utf8") / APPROX_BYTES_PER_TOKEN);
|
|
950
1405
|
var shouldBypassImmediateTruncation = (toolName) => toolName === "tool_output_cache" || toolName === "tool_output_cache_grep";
|
|
951
1406
|
var truncateForContext = (content, maxMessageBytes) => {
|
|
@@ -978,6 +1433,13 @@ var ToolOutputCacheService = class {
|
|
|
978
1433
|
if (this.config.enabled === false) return message;
|
|
979
1434
|
const raw = contentToText(message.content);
|
|
980
1435
|
const outputRef = await this.persistToolOutput(message, raw);
|
|
1436
|
+
if (hasNonTextParts(message.content)) {
|
|
1437
|
+
return {
|
|
1438
|
+
...message,
|
|
1439
|
+
content: message.content,
|
|
1440
|
+
output_ref: outputRef
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
981
1443
|
const truncated = shouldBypassImmediateTruncation(message.tool_name) ? { output: raw, truncated: false } : truncateForContext(
|
|
982
1444
|
raw,
|
|
983
1445
|
this.config.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES
|
|
@@ -1078,7 +1540,7 @@ var parseQualifiedModelId2 = (modelId) => {
|
|
|
1078
1540
|
if (!rest) {
|
|
1079
1541
|
return null;
|
|
1080
1542
|
}
|
|
1081
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
1543
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "moonshot" && providerRaw !== "zai" && providerRaw !== "xai") {
|
|
1082
1544
|
return null;
|
|
1083
1545
|
}
|
|
1084
1546
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -1099,6 +1561,7 @@ var TokenUsageService = class {
|
|
|
1099
1561
|
by_model: {}
|
|
1100
1562
|
};
|
|
1101
1563
|
}
|
|
1564
|
+
config;
|
|
1102
1565
|
usageSummary;
|
|
1103
1566
|
lastUsage = null;
|
|
1104
1567
|
updateUsageSummary(usage) {
|
|
@@ -1139,78 +1602,115 @@ var TokenUsageService = class {
|
|
|
1139
1602
|
}
|
|
1140
1603
|
};
|
|
1141
1604
|
|
|
1142
|
-
// src/
|
|
1143
|
-
var
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1605
|
+
// src/agent/model-context.ts
|
|
1606
|
+
var calculateContextLeftPercent = ({
|
|
1607
|
+
usage,
|
|
1608
|
+
modelRegistry,
|
|
1609
|
+
provider,
|
|
1610
|
+
model
|
|
1611
|
+
}) => {
|
|
1612
|
+
if (!usage) {
|
|
1613
|
+
return null;
|
|
1614
|
+
}
|
|
1615
|
+
const usageModelSpec = usage.model ? resolveModelWithQualifiedFallback2(modelRegistry, provider, usage.model) : void 0;
|
|
1616
|
+
const modelSpec = usageModelSpec ?? resolveModelWithQualifiedFallback2(modelRegistry, provider, model);
|
|
1617
|
+
const contextLimit = modelSpec?.maxInputTokens ?? modelSpec?.contextWindow ?? null;
|
|
1618
|
+
if (!contextLimit || contextLimit <= 0) {
|
|
1619
|
+
return null;
|
|
1620
|
+
}
|
|
1621
|
+
const used = usage.total_tokens;
|
|
1622
|
+
if (!Number.isFinite(used) || used <= 0) {
|
|
1623
|
+
return 100;
|
|
1624
|
+
}
|
|
1625
|
+
const leftRatio = 1 - used / contextLimit;
|
|
1626
|
+
const percent = Math.round(leftRatio * 100);
|
|
1627
|
+
return Math.max(0, Math.min(100, percent));
|
|
1628
|
+
};
|
|
1629
|
+
var resolveModelWithQualifiedFallback2 = (modelRegistry, provider, modelId) => {
|
|
1630
|
+
const direct = resolveModel(modelRegistry, modelId, provider);
|
|
1631
|
+
if (direct) return direct;
|
|
1632
|
+
const qualified = parseQualifiedModelId3(modelId);
|
|
1633
|
+
if (!qualified) return resolveModel(modelRegistry, modelId);
|
|
1634
|
+
return resolveModel(modelRegistry, qualified.modelId, qualified.provider) ?? resolveModel(
|
|
1635
|
+
modelRegistry,
|
|
1636
|
+
`${qualified.provider}/${qualified.modelId}`,
|
|
1637
|
+
qualified.provider
|
|
1638
|
+
);
|
|
1639
|
+
};
|
|
1640
|
+
var parseQualifiedModelId3 = (modelId) => {
|
|
1641
|
+
const sep = modelId.indexOf("/");
|
|
1642
|
+
if (sep <= 0 || sep >= modelId.length - 1) {
|
|
1643
|
+
return null;
|
|
1644
|
+
}
|
|
1645
|
+
const providerRaw = modelId.slice(0, sep);
|
|
1646
|
+
const rest = modelId.slice(sep + 1);
|
|
1647
|
+
if (!rest) {
|
|
1648
|
+
return null;
|
|
1149
1649
|
}
|
|
1650
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "moonshot" && providerRaw !== "zai" && providerRaw !== "xai") {
|
|
1651
|
+
return null;
|
|
1652
|
+
}
|
|
1653
|
+
return { provider: providerRaw, modelId: rest };
|
|
1150
1654
|
};
|
|
1151
1655
|
|
|
1152
|
-
// src/agent/
|
|
1153
|
-
var
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
if (result.type === "text") return result.text;
|
|
1158
|
-
if (result.type === "parts") return result.parts;
|
|
1159
|
-
try {
|
|
1160
|
-
return JSON.stringify(result.value);
|
|
1161
|
-
} catch {
|
|
1162
|
-
return String(result.value);
|
|
1656
|
+
// src/agent/model-output.ts
|
|
1657
|
+
var buildHostedSearchSummary = (kind, status, queries, sourcesCount) => {
|
|
1658
|
+
const parts = [`${kind === "x" ? "XSearch" : "WebSearch"} status=${status}`];
|
|
1659
|
+
if (queries.length) {
|
|
1660
|
+
parts.push(`queries=${queries.join(" | ")}`);
|
|
1163
1661
|
}
|
|
1164
|
-
|
|
1662
|
+
if (typeof sourcesCount === "number") {
|
|
1663
|
+
parts.push(`sources=${sourcesCount}`);
|
|
1664
|
+
}
|
|
1665
|
+
return parts.join(" | ");
|
|
1666
|
+
};
|
|
1165
1667
|
var collectModelOutput = (messages) => {
|
|
1166
|
-
const buildWebSearchSummary = (status, queries, sourcesCount) => {
|
|
1167
|
-
const parts = [`WebSearch status=${status}`];
|
|
1168
|
-
if (queries.length) {
|
|
1169
|
-
parts.push(`queries=${queries.join(" | ")}`);
|
|
1170
|
-
}
|
|
1171
|
-
if (typeof sourcesCount === "number") {
|
|
1172
|
-
parts.push(`sources=${sourcesCount}`);
|
|
1173
|
-
}
|
|
1174
|
-
return parts.join(" | ");
|
|
1175
|
-
};
|
|
1176
1668
|
const reasoningTexts = [];
|
|
1177
1669
|
const assistantTexts = [];
|
|
1178
1670
|
const toolCalls = [];
|
|
1179
1671
|
const hostedToolCalls = [];
|
|
1180
|
-
const
|
|
1181
|
-
const
|
|
1182
|
-
|
|
1183
|
-
|
|
1672
|
+
const hostedSearchById = /* @__PURE__ */ new Map();
|
|
1673
|
+
const hostedSearchOrder = [];
|
|
1674
|
+
const anonymousSearchCounter = {
|
|
1675
|
+
web: 0,
|
|
1676
|
+
x: 0
|
|
1677
|
+
};
|
|
1678
|
+
const lastAnonymousSearchId = {
|
|
1679
|
+
web: null,
|
|
1680
|
+
x: null
|
|
1681
|
+
};
|
|
1184
1682
|
for (const message of messages) {
|
|
1185
1683
|
if (message.role === "reasoning") {
|
|
1186
1684
|
const raw = message.raw_item;
|
|
1187
|
-
if (raw && typeof raw === "object" && raw.type === "web_search_call") {
|
|
1685
|
+
if (raw && typeof raw === "object" && (raw.type === "web_search_call" || raw.type === "x_search_call")) {
|
|
1188
1686
|
const record = raw;
|
|
1687
|
+
const kind = record.type === "x_search_call" ? "x" : "web";
|
|
1189
1688
|
const statusRaw = record.status;
|
|
1190
1689
|
const status = typeof statusRaw === "string" ? statusRaw : "completed";
|
|
1191
1690
|
const action = record.action && typeof record.action === "object" ? record.action : null;
|
|
1192
|
-
const queries = Array.isArray(action?.queries) ? action
|
|
1691
|
+
const queries = Array.isArray(action?.queries) ? action.queries.filter(
|
|
1193
1692
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
1194
1693
|
) : [];
|
|
1195
|
-
const sourcesCount = Array.isArray(action?.sources) ? action
|
|
1694
|
+
const sourcesCount = Array.isArray(action?.sources) ? action.sources.length : void 0;
|
|
1196
1695
|
const explicitId = typeof record.id === "string" && record.id.length > 0 ? record.id : null;
|
|
1197
1696
|
let id = explicitId;
|
|
1198
1697
|
const hasSearchContext = queries.length > 0 || typeof sourcesCount === "number";
|
|
1199
1698
|
if (!id) {
|
|
1200
1699
|
if (hasSearchContext || status === "failed") {
|
|
1201
|
-
|
|
1202
|
-
id =
|
|
1700
|
+
anonymousSearchCounter[kind] += 1;
|
|
1701
|
+
id = `${kind === "x" ? "x" : "web"}_search_${anonymousSearchCounter[kind]}`;
|
|
1203
1702
|
if (hasSearchContext) {
|
|
1204
|
-
|
|
1703
|
+
lastAnonymousSearchId[kind] = id;
|
|
1205
1704
|
}
|
|
1206
|
-
} else if (
|
|
1207
|
-
id =
|
|
1705
|
+
} else if (lastAnonymousSearchId[kind]) {
|
|
1706
|
+
id = lastAnonymousSearchId[kind];
|
|
1208
1707
|
}
|
|
1209
1708
|
}
|
|
1210
1709
|
if (!id) {
|
|
1211
1710
|
continue;
|
|
1212
1711
|
}
|
|
1213
|
-
const
|
|
1712
|
+
const aggregateKey = `${kind}:${id}`;
|
|
1713
|
+
const existing = hostedSearchById.get(aggregateKey);
|
|
1214
1714
|
if (existing) {
|
|
1215
1715
|
existing.status = status;
|
|
1216
1716
|
if (queries.length) {
|
|
@@ -1220,13 +1720,14 @@ var collectModelOutput = (messages) => {
|
|
|
1220
1720
|
existing.sourcesCount = sourcesCount;
|
|
1221
1721
|
}
|
|
1222
1722
|
} else {
|
|
1223
|
-
|
|
1723
|
+
hostedSearchById.set(aggregateKey, {
|
|
1224
1724
|
id,
|
|
1725
|
+
kind,
|
|
1225
1726
|
status,
|
|
1226
1727
|
queries,
|
|
1227
1728
|
...typeof sourcesCount === "number" ? { sourcesCount } : {}
|
|
1228
1729
|
});
|
|
1229
|
-
|
|
1730
|
+
hostedSearchOrder.push(aggregateKey);
|
|
1230
1731
|
}
|
|
1231
1732
|
continue;
|
|
1232
1733
|
}
|
|
@@ -1252,8 +1753,8 @@ var collectModelOutput = (messages) => {
|
|
|
1252
1753
|
toolCalls.push(...message.tool_calls);
|
|
1253
1754
|
}
|
|
1254
1755
|
}
|
|
1255
|
-
for (const
|
|
1256
|
-
const aggregate =
|
|
1756
|
+
for (const aggregateKey of hostedSearchOrder) {
|
|
1757
|
+
const aggregate = hostedSearchById.get(aggregateKey);
|
|
1257
1758
|
if (!aggregate) {
|
|
1258
1759
|
continue;
|
|
1259
1760
|
}
|
|
@@ -1264,10 +1765,11 @@ var collectModelOutput = (messages) => {
|
|
|
1264
1765
|
};
|
|
1265
1766
|
hostedToolCalls.push({
|
|
1266
1767
|
id: aggregate.id,
|
|
1267
|
-
tool: "web_search",
|
|
1268
|
-
displayName: "WebSearch",
|
|
1768
|
+
tool: aggregate.kind === "x" ? "x_search" : "web_search",
|
|
1769
|
+
displayName: aggregate.kind === "x" ? "XSearch" : "WebSearch",
|
|
1269
1770
|
args,
|
|
1270
|
-
result:
|
|
1771
|
+
result: buildHostedSearchSummary(
|
|
1772
|
+
aggregate.kind,
|
|
1271
1773
|
aggregate.status,
|
|
1272
1774
|
aggregate.queries,
|
|
1273
1775
|
aggregate.sourcesCount
|
|
@@ -1277,51 +1779,200 @@ var collectModelOutput = (messages) => {
|
|
|
1277
1779
|
}
|
|
1278
1780
|
return { reasoningTexts, assistantTexts, toolCalls, hostedToolCalls };
|
|
1279
1781
|
};
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1782
|
+
|
|
1783
|
+
// src/tools/done.ts
|
|
1784
|
+
var TaskComplete = class extends Error {
|
|
1785
|
+
finalMessage;
|
|
1786
|
+
constructor(finalMessage) {
|
|
1787
|
+
super("Task complete");
|
|
1788
|
+
this.name = "TaskComplete";
|
|
1789
|
+
this.finalMessage = finalMessage;
|
|
1790
|
+
}
|
|
1285
1791
|
};
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1792
|
+
|
|
1793
|
+
// src/agent/tool-execution.ts
|
|
1794
|
+
var toolResultToContent = (result) => {
|
|
1795
|
+
if (result.type === "text") return result.text;
|
|
1796
|
+
if (result.type === "parts") return result.parts;
|
|
1797
|
+
try {
|
|
1798
|
+
return JSON.stringify(result.value);
|
|
1799
|
+
} catch {
|
|
1800
|
+
return String(result.value);
|
|
1290
1801
|
}
|
|
1291
1802
|
};
|
|
1292
|
-
var
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1803
|
+
var createToolContext = (signal) => {
|
|
1804
|
+
const deps = /* @__PURE__ */ Object.create(null);
|
|
1805
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1806
|
+
const resolve = async (key) => {
|
|
1807
|
+
if (cache.has(key.id)) {
|
|
1808
|
+
return cache.get(key.id);
|
|
1809
|
+
}
|
|
1810
|
+
const value = await key.create();
|
|
1811
|
+
cache.set(key.id, value);
|
|
1812
|
+
return value;
|
|
1813
|
+
};
|
|
1814
|
+
return {
|
|
1815
|
+
deps,
|
|
1816
|
+
resolve,
|
|
1817
|
+
signal,
|
|
1818
|
+
now: () => /* @__PURE__ */ new Date()
|
|
1819
|
+
};
|
|
1820
|
+
};
|
|
1821
|
+
var executeToolCall = async ({
|
|
1822
|
+
toolCall,
|
|
1823
|
+
tools,
|
|
1824
|
+
signal,
|
|
1825
|
+
canExecuteTool
|
|
1826
|
+
}) => {
|
|
1827
|
+
const toolName = toolCall.function.name;
|
|
1828
|
+
const tool = tools.find((candidate) => candidate.name === toolName);
|
|
1829
|
+
if (!tool) {
|
|
1830
|
+
return {
|
|
1831
|
+
message: {
|
|
1832
|
+
role: "tool",
|
|
1833
|
+
tool_call_id: toolCall.id,
|
|
1834
|
+
tool_name: toolName,
|
|
1835
|
+
content: `Error: Unknown tool '${toolName}'`,
|
|
1836
|
+
is_error: true
|
|
1837
|
+
}
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
if (canExecuteTool) {
|
|
1841
|
+
try {
|
|
1842
|
+
const decision = await canExecuteTool(
|
|
1843
|
+
toolCall,
|
|
1844
|
+
toolCall.function.arguments,
|
|
1845
|
+
createToolContext(signal)
|
|
1846
|
+
);
|
|
1847
|
+
if (decision.decision === "deny") {
|
|
1848
|
+
const deniedContent = `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
|
|
1849
|
+
return {
|
|
1850
|
+
message: {
|
|
1851
|
+
role: "tool",
|
|
1852
|
+
tool_call_id: toolCall.id,
|
|
1853
|
+
tool_name: toolName,
|
|
1854
|
+
content: deniedContent,
|
|
1855
|
+
is_error: true
|
|
1856
|
+
},
|
|
1857
|
+
...decision.stop_turn ? {
|
|
1858
|
+
done: true,
|
|
1859
|
+
finalMessage: "Permission request was denied. Turn stopped. Please send your next input to continue."
|
|
1860
|
+
} : {}
|
|
1861
|
+
};
|
|
1862
|
+
}
|
|
1863
|
+
} catch (error) {
|
|
1864
|
+
return {
|
|
1865
|
+
message: {
|
|
1866
|
+
role: "tool",
|
|
1867
|
+
tool_call_id: toolCall.id,
|
|
1868
|
+
tool_name: toolName,
|
|
1869
|
+
content: `Permission check failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1870
|
+
is_error: true
|
|
1871
|
+
}
|
|
1872
|
+
};
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
try {
|
|
1876
|
+
const result = await tool.executeRaw(
|
|
1877
|
+
toolCall.function.arguments,
|
|
1878
|
+
createToolContext(signal)
|
|
1879
|
+
);
|
|
1880
|
+
return {
|
|
1881
|
+
message: {
|
|
1882
|
+
role: "tool",
|
|
1883
|
+
tool_call_id: toolCall.id,
|
|
1884
|
+
tool_name: toolName,
|
|
1885
|
+
content: toolResultToContent(result)
|
|
1886
|
+
}
|
|
1887
|
+
};
|
|
1888
|
+
} catch (error) {
|
|
1889
|
+
if (error instanceof TaskComplete) {
|
|
1890
|
+
return {
|
|
1891
|
+
message: {
|
|
1892
|
+
role: "tool",
|
|
1893
|
+
tool_call_id: toolCall.id,
|
|
1894
|
+
tool_name: toolName,
|
|
1895
|
+
content: "Task complete"
|
|
1896
|
+
},
|
|
1897
|
+
done: true,
|
|
1898
|
+
finalMessage: error.finalMessage
|
|
1899
|
+
};
|
|
1900
|
+
}
|
|
1901
|
+
return {
|
|
1902
|
+
message: {
|
|
1903
|
+
role: "tool",
|
|
1904
|
+
tool_call_id: toolCall.id,
|
|
1905
|
+
tool_name: toolName,
|
|
1906
|
+
content: `Error: ${error instanceof Error ? error.message : String(error)}`,
|
|
1907
|
+
is_error: true
|
|
1908
|
+
}
|
|
1909
|
+
};
|
|
1910
|
+
}
|
|
1911
|
+
};
|
|
1912
|
+
|
|
1913
|
+
// src/agent/agent.ts
|
|
1914
|
+
var DEFAULT_MAX_ITERATIONS = 200;
|
|
1915
|
+
var defaultMonotonicNowMs = () => performance.now();
|
|
1916
|
+
var elapsedMilliseconds = (startedAt, monotonicNowMs) => Math.max(0, Math.round(monotonicNowMs() - startedAt));
|
|
1917
|
+
var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
1918
|
+
var createAbortError2 = () => {
|
|
1919
|
+
const error = new Error("Operation aborted");
|
|
1920
|
+
error.name = "AbortError";
|
|
1921
|
+
return error;
|
|
1922
|
+
};
|
|
1923
|
+
var isAbortError = (error) => error instanceof Error && (error.name === "AbortError" || error.name === "APIUserAbortError" || error.name === "AbortSignal");
|
|
1924
|
+
var throwIfAborted = (signal) => {
|
|
1925
|
+
if (signal?.aborted) {
|
|
1926
|
+
throw createAbortError2();
|
|
1927
|
+
}
|
|
1928
|
+
};
|
|
1929
|
+
var isResponsesHistoryProvider = (provider) => provider === "openai" || provider === "openrouter" || provider === "xai";
|
|
1930
|
+
var Agent = class {
|
|
1931
|
+
llm;
|
|
1932
|
+
tools;
|
|
1933
|
+
hostedTools;
|
|
1934
|
+
systemPrompt;
|
|
1935
|
+
maxIterations;
|
|
1936
|
+
toolChoice;
|
|
1937
|
+
requireDoneTool;
|
|
1938
|
+
compactionService;
|
|
1939
|
+
toolOutputCacheService;
|
|
1940
|
+
services;
|
|
1941
|
+
modelRegistry;
|
|
1942
|
+
canExecuteTool;
|
|
1943
|
+
monotonicNowMs;
|
|
1944
|
+
llmRetryPolicy;
|
|
1945
|
+
llmRetryDependencies;
|
|
1946
|
+
//private readonly dependencyOverrides?: DependencyOverrides;
|
|
1947
|
+
history;
|
|
1948
|
+
usageService;
|
|
1949
|
+
constructor(options) {
|
|
1950
|
+
this.llm = options.llm;
|
|
1951
|
+
this.history = isResponsesHistoryProvider(this.llm.provider) ? new ResponsesHistoryAdapter() : new MessageHistoryAdapter();
|
|
1952
|
+
this.tools = options.tools;
|
|
1953
|
+
this.hostedTools = options.hostedTools ?? [];
|
|
1954
|
+
this.systemPrompt = options.systemPrompt ?? void 0;
|
|
1955
|
+
this.maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
|
|
1956
|
+
this.toolChoice = options.toolChoice ?? void 0;
|
|
1957
|
+
this.requireDoneTool = options.requireDoneTool ?? false;
|
|
1958
|
+
this.services = options.services ?? {};
|
|
1959
|
+
this.monotonicNowMs = this.services.monotonicNowMs ?? defaultMonotonicNowMs;
|
|
1960
|
+
this.llmRetryPolicy = resolveLlmRetryPolicy({
|
|
1961
|
+
maxRetries: options.llmMaxRetries,
|
|
1962
|
+
baseDelayMs: options.llmRetryBaseDelayMs,
|
|
1963
|
+
maxDelayMs: options.llmRetryMaxDelayMs,
|
|
1964
|
+
maxRetryAfterMs: options.llmMaxRetryAfterMs,
|
|
1965
|
+
retryWindowMs: options.llmRetryWindowMs
|
|
1966
|
+
});
|
|
1967
|
+
this.llmRetryDependencies = {
|
|
1968
|
+
...this.services.llmRetryNowMs ? { nowMs: this.services.llmRetryNowMs } : {},
|
|
1969
|
+
...this.services.llmRetryRandom ? { random: this.services.llmRetryRandom } : {},
|
|
1970
|
+
...this.services.llmRetrySleep ? { sleep: this.services.llmRetrySleep } : {}
|
|
1971
|
+
};
|
|
1972
|
+
this.modelRegistry = options.modelRegistry ?? DEFAULT_MODEL_REGISTRY;
|
|
1973
|
+
this.compactionService = options.compaction === null ? null : new CompactionService(options.compaction ?? {}, {
|
|
1974
|
+
modelRegistry: this.modelRegistry
|
|
1975
|
+
});
|
|
1325
1976
|
this.toolOutputCacheService = options.toolOutputCache === null ? null : new ToolOutputCacheService(options.toolOutputCache ?? {}, {
|
|
1326
1977
|
modelRegistry: this.modelRegistry,
|
|
1327
1978
|
store: this.services.toolOutputCacheStore ?? null
|
|
@@ -1335,31 +1986,12 @@ var Agent = class {
|
|
|
1335
1986
|
return this.usageService.getUsageSummary();
|
|
1336
1987
|
}
|
|
1337
1988
|
getContextLeftPercent() {
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
this.llm.provider,
|
|
1345
|
-
usage.model
|
|
1346
|
-
) : void 0;
|
|
1347
|
-
const modelSpec = usageModelSpec ?? resolveModelWithQualifiedFallback2(
|
|
1348
|
-
this.modelRegistry,
|
|
1349
|
-
this.llm.provider,
|
|
1350
|
-
this.llm.model
|
|
1351
|
-
);
|
|
1352
|
-
const contextLimit = modelSpec?.maxInputTokens ?? modelSpec?.contextWindow ?? null;
|
|
1353
|
-
if (!contextLimit || contextLimit <= 0) {
|
|
1354
|
-
return null;
|
|
1355
|
-
}
|
|
1356
|
-
const used = usage.total_tokens;
|
|
1357
|
-
if (!Number.isFinite(used) || used <= 0) {
|
|
1358
|
-
return 100;
|
|
1359
|
-
}
|
|
1360
|
-
const leftRatio = 1 - used / contextLimit;
|
|
1361
|
-
const percent = Math.round(leftRatio * 100);
|
|
1362
|
-
return Math.max(0, Math.min(100, percent));
|
|
1989
|
+
return calculateContextLeftPercent({
|
|
1990
|
+
usage: this.usageService.getLastUsage(),
|
|
1991
|
+
modelRegistry: this.modelRegistry,
|
|
1992
|
+
provider: this.llm.provider,
|
|
1993
|
+
model: this.llm.model
|
|
1994
|
+
});
|
|
1363
1995
|
}
|
|
1364
1996
|
getHistoryMessages() {
|
|
1365
1997
|
return this.history.getViewMessages();
|
|
@@ -1419,24 +2051,6 @@ var Agent = class {
|
|
|
1419
2051
|
if (!this.toolOutputCacheService) return message;
|
|
1420
2052
|
return this.toolOutputCacheService.processToolMessage(message);
|
|
1421
2053
|
}
|
|
1422
|
-
buildToolContext(signal) {
|
|
1423
|
-
const deps = /* @__PURE__ */ Object.create(null);
|
|
1424
|
-
const cache = /* @__PURE__ */ new Map();
|
|
1425
|
-
const resolve = async (key) => {
|
|
1426
|
-
if (cache.has(key.id)) {
|
|
1427
|
-
return cache.get(key.id);
|
|
1428
|
-
}
|
|
1429
|
-
const value = await key.create();
|
|
1430
|
-
cache.set(key.id, value);
|
|
1431
|
-
return value;
|
|
1432
|
-
};
|
|
1433
|
-
return {
|
|
1434
|
-
deps,
|
|
1435
|
-
resolve,
|
|
1436
|
-
signal,
|
|
1437
|
-
now: () => /* @__PURE__ */ new Date()
|
|
1438
|
-
};
|
|
1439
|
-
}
|
|
1440
2054
|
recordLlmRequest(session, input, context) {
|
|
1441
2055
|
if (!session) return null;
|
|
1442
2056
|
const seq = (session.invoke_seq ?? 0) + 1;
|
|
@@ -1488,6 +2102,21 @@ var Agent = class {
|
|
|
1488
2102
|
}
|
|
1489
2103
|
});
|
|
1490
2104
|
}
|
|
2105
|
+
async *invokeModelWithRetry(input, context, signal) {
|
|
2106
|
+
return yield* invokeWithRetry({
|
|
2107
|
+
operation: (attemptSignal) => this.llm.ainvoke(
|
|
2108
|
+
{
|
|
2109
|
+
...input,
|
|
2110
|
+
...attemptSignal ? { signal: attemptSignal } : {}
|
|
2111
|
+
},
|
|
2112
|
+
context
|
|
2113
|
+
),
|
|
2114
|
+
classifyFailure: this.llm.classifyFailure,
|
|
2115
|
+
policy: this.llmRetryPolicy,
|
|
2116
|
+
...signal ? { signal } : {},
|
|
2117
|
+
dependencies: this.llmRetryDependencies
|
|
2118
|
+
});
|
|
2119
|
+
}
|
|
1491
2120
|
async run(message, options = {}) {
|
|
1492
2121
|
let finalResponse = "";
|
|
1493
2122
|
for await (const event of this.runStream(message, options)) {
|
|
@@ -1533,12 +2162,10 @@ var Agent = class {
|
|
|
1533
2162
|
});
|
|
1534
2163
|
const invokeContext = this.buildInvokeContext(session);
|
|
1535
2164
|
const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
|
|
1536
|
-
const response =
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
},
|
|
1541
|
-
invokeContext
|
|
2165
|
+
const response = yield* this.invokeModelWithRetry(
|
|
2166
|
+
invokeInput,
|
|
2167
|
+
invokeContext,
|
|
2168
|
+
signal
|
|
1542
2169
|
);
|
|
1543
2170
|
this.recordLlmResponse(session, seq, response);
|
|
1544
2171
|
this.usageService.updateUsageSummary(response.usage);
|
|
@@ -1645,11 +2272,12 @@ var Agent = class {
|
|
|
1645
2272
|
const monotonicStartedAt = this.monotonicNowMs();
|
|
1646
2273
|
try {
|
|
1647
2274
|
throwIfAborted(signal);
|
|
1648
|
-
const execution = await
|
|
2275
|
+
const execution = await executeToolCall({
|
|
1649
2276
|
toolCall,
|
|
1650
|
-
runTools,
|
|
1651
|
-
signal
|
|
1652
|
-
|
|
2277
|
+
tools: runTools,
|
|
2278
|
+
...signal ? { signal } : {},
|
|
2279
|
+
...this.canExecuteTool ? { canExecuteTool: this.canExecuteTool } : {}
|
|
2280
|
+
});
|
|
1653
2281
|
const rawOutput = stringifyContent(execution.message.content, {
|
|
1654
2282
|
mode: "display"
|
|
1655
2283
|
});
|
|
@@ -1791,129 +2419,84 @@ ${assistantTexts.join("\n").trim()}`;
|
|
|
1791
2419
|
return finalResponse;
|
|
1792
2420
|
} catch {
|
|
1793
2421
|
if (signal?.aborted) {
|
|
1794
|
-
throw
|
|
2422
|
+
throw createAbortError2();
|
|
1795
2423
|
}
|
|
1796
2424
|
return "[Max Iterations Reached]\n\nSummary unavailable due to an internal error.";
|
|
1797
2425
|
}
|
|
1798
2426
|
}
|
|
1799
|
-
async executeToolCall(toolCall, tools, signal) {
|
|
1800
|
-
const toolName = toolCall.function.name;
|
|
1801
|
-
const tool = tools.find((t) => t.name === toolName);
|
|
1802
|
-
if (!tool) {
|
|
1803
|
-
return {
|
|
1804
|
-
message: {
|
|
1805
|
-
role: "tool",
|
|
1806
|
-
tool_call_id: toolCall.id,
|
|
1807
|
-
tool_name: toolName,
|
|
1808
|
-
content: `Error: Unknown tool '${toolName}'`,
|
|
1809
|
-
is_error: true
|
|
1810
|
-
}
|
|
1811
|
-
};
|
|
1812
|
-
}
|
|
1813
|
-
if (this.canExecuteTool) {
|
|
1814
|
-
try {
|
|
1815
|
-
const decision = await this.canExecuteTool(
|
|
1816
|
-
toolCall,
|
|
1817
|
-
toolCall.function.arguments,
|
|
1818
|
-
this.buildToolContext(signal)
|
|
1819
|
-
);
|
|
1820
|
-
if (decision.decision === "deny") {
|
|
1821
|
-
const deniedContent = `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
|
|
1822
|
-
return {
|
|
1823
|
-
message: {
|
|
1824
|
-
role: "tool",
|
|
1825
|
-
tool_call_id: toolCall.id,
|
|
1826
|
-
tool_name: toolName,
|
|
1827
|
-
content: deniedContent,
|
|
1828
|
-
is_error: true
|
|
1829
|
-
},
|
|
1830
|
-
...decision.stop_turn ? {
|
|
1831
|
-
done: true,
|
|
1832
|
-
finalMessage: "Permission request was denied. Turn stopped. Please send your next input to continue."
|
|
1833
|
-
} : {}
|
|
1834
|
-
};
|
|
1835
|
-
}
|
|
1836
|
-
} catch (error) {
|
|
1837
|
-
return {
|
|
1838
|
-
message: {
|
|
1839
|
-
role: "tool",
|
|
1840
|
-
tool_call_id: toolCall.id,
|
|
1841
|
-
tool_name: toolName,
|
|
1842
|
-
content: `Permission check failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1843
|
-
is_error: true
|
|
1844
|
-
}
|
|
1845
|
-
};
|
|
1846
|
-
}
|
|
1847
|
-
}
|
|
1848
|
-
try {
|
|
1849
|
-
const result = await tool.executeRaw(
|
|
1850
|
-
toolCall.function.arguments,
|
|
1851
|
-
this.buildToolContext(signal)
|
|
1852
|
-
);
|
|
1853
|
-
return {
|
|
1854
|
-
message: {
|
|
1855
|
-
role: "tool",
|
|
1856
|
-
tool_call_id: toolCall.id,
|
|
1857
|
-
tool_name: toolName,
|
|
1858
|
-
content: toolResultToContent(result)
|
|
1859
|
-
}
|
|
1860
|
-
};
|
|
1861
|
-
} catch (error) {
|
|
1862
|
-
if (error instanceof TaskComplete) {
|
|
1863
|
-
return {
|
|
1864
|
-
message: {
|
|
1865
|
-
role: "tool",
|
|
1866
|
-
tool_call_id: toolCall.id,
|
|
1867
|
-
tool_name: toolName,
|
|
1868
|
-
content: "Task complete"
|
|
1869
|
-
},
|
|
1870
|
-
done: true,
|
|
1871
|
-
finalMessage: error.finalMessage
|
|
1872
|
-
};
|
|
1873
|
-
}
|
|
1874
|
-
return {
|
|
1875
|
-
message: {
|
|
1876
|
-
role: "tool",
|
|
1877
|
-
tool_call_id: toolCall.id,
|
|
1878
|
-
tool_name: toolName,
|
|
1879
|
-
content: `Error: ${error instanceof Error ? error.message : String(error)}`,
|
|
1880
|
-
is_error: true
|
|
1881
|
-
}
|
|
1882
|
-
};
|
|
1883
|
-
}
|
|
1884
|
-
}
|
|
1885
|
-
};
|
|
1886
|
-
var resolveModelWithQualifiedFallback2 = (modelRegistry, provider, modelId) => {
|
|
1887
|
-
const direct = resolveModel(modelRegistry, modelId, provider);
|
|
1888
|
-
if (direct) return direct;
|
|
1889
|
-
const qualified = parseQualifiedModelId3(modelId);
|
|
1890
|
-
if (!qualified) return resolveModel(modelRegistry, modelId);
|
|
1891
|
-
return resolveModel(modelRegistry, qualified.modelId, qualified.provider) ?? resolveModel(
|
|
1892
|
-
modelRegistry,
|
|
1893
|
-
`${qualified.provider}/${qualified.modelId}`,
|
|
1894
|
-
qualified.provider
|
|
1895
|
-
);
|
|
1896
|
-
};
|
|
1897
|
-
var parseQualifiedModelId3 = (modelId) => {
|
|
1898
|
-
const sep = modelId.indexOf("/");
|
|
1899
|
-
if (sep <= 0 || sep >= modelId.length - 1) {
|
|
1900
|
-
return null;
|
|
1901
|
-
}
|
|
1902
|
-
const providerRaw = modelId.slice(0, sep);
|
|
1903
|
-
const rest = modelId.slice(sep + 1);
|
|
1904
|
-
if (!rest) {
|
|
1905
|
-
return null;
|
|
1906
|
-
}
|
|
1907
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
1908
|
-
return null;
|
|
1909
|
-
}
|
|
1910
|
-
return { provider: providerRaw, modelId: rest };
|
|
1911
2427
|
};
|
|
1912
2428
|
|
|
1913
2429
|
// src/llm/anthropic/chat.ts
|
|
1914
2430
|
import { createHash } from "crypto";
|
|
1915
2431
|
import Anthropic from "@anthropic-ai/sdk";
|
|
1916
2432
|
|
|
2433
|
+
// src/llm/anthropic/failure.ts
|
|
2434
|
+
var PROVIDER_NAME = "anthropic";
|
|
2435
|
+
var classifyAnthropicFailure = (error) => {
|
|
2436
|
+
if (isAbortLikeProviderError(error)) {
|
|
2437
|
+
return buildProviderFailure(PROVIDER_NAME, "cancelled");
|
|
2438
|
+
}
|
|
2439
|
+
const extracted = extractProviderError(error);
|
|
2440
|
+
const status = extracted.status;
|
|
2441
|
+
const type = extracted.type?.toLowerCase() ?? "";
|
|
2442
|
+
const retryOptions = getRetryHint(extracted);
|
|
2443
|
+
if (status === 401) {
|
|
2444
|
+
return buildProviderFailure(PROVIDER_NAME, "auth", { status });
|
|
2445
|
+
}
|
|
2446
|
+
if (status === 402 || type === "billing_error") {
|
|
2447
|
+
return buildProviderFailure(PROVIDER_NAME, "hard_quota", { status });
|
|
2448
|
+
}
|
|
2449
|
+
if (status === 403) {
|
|
2450
|
+
return buildProviderFailure(PROVIDER_NAME, "permission", { status });
|
|
2451
|
+
}
|
|
2452
|
+
if (isValidationStatus(status)) {
|
|
2453
|
+
return buildProviderFailure(PROVIDER_NAME, "validation", { status });
|
|
2454
|
+
}
|
|
2455
|
+
if (status === 429 || type === "rate_limit_error") {
|
|
2456
|
+
return buildProviderFailure(PROVIDER_NAME, "rate_limit", {
|
|
2457
|
+
status,
|
|
2458
|
+
retryable: true,
|
|
2459
|
+
...retryOptions
|
|
2460
|
+
});
|
|
2461
|
+
}
|
|
2462
|
+
if (status === 408) {
|
|
2463
|
+
return buildProviderFailure(PROVIDER_NAME, "timeout", {
|
|
2464
|
+
status,
|
|
2465
|
+
retryable: true,
|
|
2466
|
+
...retryOptions
|
|
2467
|
+
});
|
|
2468
|
+
}
|
|
2469
|
+
if (status === 409) {
|
|
2470
|
+
return buildProviderFailure(PROVIDER_NAME, "provider", {
|
|
2471
|
+
status,
|
|
2472
|
+
retryable: true,
|
|
2473
|
+
...retryOptions
|
|
2474
|
+
});
|
|
2475
|
+
}
|
|
2476
|
+
if (status === 529 || type === "overloaded_error") {
|
|
2477
|
+
return buildProviderFailure(PROVIDER_NAME, "overloaded", {
|
|
2478
|
+
status,
|
|
2479
|
+
retryable: true,
|
|
2480
|
+
...retryOptions
|
|
2481
|
+
});
|
|
2482
|
+
}
|
|
2483
|
+
if (status === 504 || type === "timeout_error") {
|
|
2484
|
+
return buildProviderFailure(PROVIDER_NAME, "timeout", {
|
|
2485
|
+
status,
|
|
2486
|
+
retryable: true,
|
|
2487
|
+
...retryOptions
|
|
2488
|
+
});
|
|
2489
|
+
}
|
|
2490
|
+
if (status !== void 0 && status >= 500) {
|
|
2491
|
+
return buildProviderFailure(PROVIDER_NAME, "provider", {
|
|
2492
|
+
status,
|
|
2493
|
+
retryable: true,
|
|
2494
|
+
...retryOptions
|
|
2495
|
+
});
|
|
2496
|
+
}
|
|
2497
|
+
return classifyTransportFailure(PROVIDER_NAME, error) ?? buildProviderFailure(PROVIDER_NAME, "provider");
|
|
2498
|
+
};
|
|
2499
|
+
|
|
1917
2500
|
// src/llm/provider-log.ts
|
|
1918
2501
|
import { promises as fs } from "fs";
|
|
1919
2502
|
import path from "path";
|
|
@@ -2014,7 +2597,8 @@ function isToolResult(value) {
|
|
|
2014
2597
|
}
|
|
2015
2598
|
|
|
2016
2599
|
// src/types/llm/tools.ts
|
|
2017
|
-
var
|
|
2600
|
+
var isHostedWebSearchToolDefinition = (value) => value.type === "hosted_search" && value.search_kind !== "x";
|
|
2601
|
+
var isHostedXSearchToolDefinition = (value) => value.type === "hosted_search" && value.search_kind === "x";
|
|
2018
2602
|
var isFunctionToolDefinition = (value) => value.type !== "hosted_search";
|
|
2019
2603
|
|
|
2020
2604
|
// src/llm/anthropic/serializer.ts
|
|
@@ -2153,7 +2737,7 @@ var toAnthropicTools = (tools) => {
|
|
|
2153
2737
|
});
|
|
2154
2738
|
continue;
|
|
2155
2739
|
}
|
|
2156
|
-
if (
|
|
2740
|
+
if (isHostedWebSearchToolDefinition(tool)) {
|
|
2157
2741
|
const hosted = toAnthropicHostedSearchTool(tool);
|
|
2158
2742
|
if (hosted) {
|
|
2159
2743
|
mapped.push(hosted);
|
|
@@ -2444,7 +3028,7 @@ var toAnthropicHostedSearchTool = (tool) => {
|
|
|
2444
3028
|
};
|
|
2445
3029
|
|
|
2446
3030
|
// src/llm/anthropic/chat.ts
|
|
2447
|
-
var
|
|
3031
|
+
var PROVIDER_NAME2 = "anthropic";
|
|
2448
3032
|
var DEFAULT_MODEL = ANTHROPIC_DEFAULT_MODEL;
|
|
2449
3033
|
var DEFAULT_MAX_TOKENS = 4096;
|
|
2450
3034
|
var DEFAULT_CLIENT_TIMEOUT_MS = 20 * 60 * 1e3;
|
|
@@ -2453,8 +3037,9 @@ var DEFAULT_PROMPT_CACHE_CONTROL = {
|
|
|
2453
3037
|
};
|
|
2454
3038
|
var FAST_MODE_BETA = "fast-mode-2026-02-01";
|
|
2455
3039
|
var ChatAnthropic = class {
|
|
2456
|
-
provider =
|
|
3040
|
+
provider = PROVIDER_NAME2;
|
|
2457
3041
|
model;
|
|
3042
|
+
classifyFailure = classifyAnthropicFailure;
|
|
2458
3043
|
client;
|
|
2459
3044
|
defaultMaxTokens;
|
|
2460
3045
|
defaultInvokeOptions;
|
|
@@ -2465,7 +3050,8 @@ var ChatAnthropic = class {
|
|
|
2465
3050
|
constructor(options = {}) {
|
|
2466
3051
|
this.client = options.client ?? new Anthropic({
|
|
2467
3052
|
timeout: DEFAULT_CLIENT_TIMEOUT_MS,
|
|
2468
|
-
...options.clientOptions ?? {}
|
|
3053
|
+
...options.clientOptions ?? {},
|
|
3054
|
+
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
2469
3055
|
});
|
|
2470
3056
|
this.model = options.model ?? DEFAULT_MODEL;
|
|
2471
3057
|
this.defaultMaxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
@@ -2556,7 +3142,7 @@ var ChatAnthropic = class {
|
|
|
2556
3142
|
try {
|
|
2557
3143
|
await writeProviderLogDump(
|
|
2558
3144
|
settings,
|
|
2559
|
-
|
|
3145
|
+
PROVIDER_NAME2,
|
|
2560
3146
|
seq,
|
|
2561
3147
|
"request",
|
|
2562
3148
|
request
|
|
@@ -2573,30 +3159,522 @@ var ChatAnthropic = class {
|
|
|
2573
3159
|
}
|
|
2574
3160
|
async debugResponseIfEnabled(response, seq) {
|
|
2575
3161
|
const settings = getProviderLogSettings();
|
|
2576
|
-
if (!settings.enabled && !settings.dumpDir) {
|
|
2577
|
-
return;
|
|
2578
|
-
}
|
|
3162
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
3163
|
+
return;
|
|
3164
|
+
}
|
|
3165
|
+
if (settings.enabled) {
|
|
3166
|
+
const usage = response.usage;
|
|
3167
|
+
const inputTokens = usage?.input_tokens ?? 0;
|
|
3168
|
+
const outputTokens = usage?.output_tokens ?? 0;
|
|
3169
|
+
const cachedRead = usage?.cache_read_input_tokens ?? 0;
|
|
3170
|
+
const cachedCreate = usage?.cache_creation_input_tokens ?? 0;
|
|
3171
|
+
const blocks = Array.isArray(response.content) ? response.content : [];
|
|
3172
|
+
const blockKinds = /* @__PURE__ */ new Set();
|
|
3173
|
+
for (const block of blocks) {
|
|
3174
|
+
const kind = block && typeof block === "object" && "type" in block ? String(block.type ?? "unknown") : "unknown";
|
|
3175
|
+
blockKinds.add(kind);
|
|
3176
|
+
}
|
|
3177
|
+
console.error(
|
|
3178
|
+
`[anthropic.response] seq=${seq} id=${response.id} stop=${String(response.stop_reason ?? "unknown")} blocks=${blocks.length} kinds=${Array.from(blockKinds).join(",")} tok_in=${inputTokens} tok_out=${outputTokens} cache_read=${cachedRead} cache_create=${cachedCreate}`
|
|
3179
|
+
);
|
|
3180
|
+
}
|
|
3181
|
+
if (settings.dumpDir) {
|
|
3182
|
+
try {
|
|
3183
|
+
await writeProviderLogDump(
|
|
3184
|
+
settings,
|
|
3185
|
+
PROVIDER_NAME2,
|
|
3186
|
+
seq,
|
|
3187
|
+
"response",
|
|
3188
|
+
response
|
|
3189
|
+
);
|
|
3190
|
+
} catch (error) {
|
|
3191
|
+
if (settings.enabled) {
|
|
3192
|
+
console.error(
|
|
3193
|
+
`[anthropic.response] dump_failed seq=${seq} error=${String(error)}`
|
|
3194
|
+
);
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
}
|
|
3198
|
+
}
|
|
3199
|
+
};
|
|
3200
|
+
|
|
3201
|
+
// src/llm/moonshot/chat.ts
|
|
3202
|
+
import { createHash as createHash2 } from "crypto";
|
|
3203
|
+
import OpenAI from "openai";
|
|
3204
|
+
|
|
3205
|
+
// src/llm/moonshot/failure.ts
|
|
3206
|
+
var PROVIDER_NAME3 = "moonshot";
|
|
3207
|
+
var parseWaitHintMs = (message) => {
|
|
3208
|
+
const match = message.match(
|
|
3209
|
+
/(?:retry|wait|try again)\s+(?:after|in|for)?\s*(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|seconds?|m|minutes?)/i
|
|
3210
|
+
);
|
|
3211
|
+
if (!match) return void 0;
|
|
3212
|
+
const value = Number(match[1]);
|
|
3213
|
+
if (!Number.isFinite(value) || value < 0) return void 0;
|
|
3214
|
+
const unit = match[2]?.toLowerCase() ?? "s";
|
|
3215
|
+
if (unit.startsWith("ms")) return Math.round(value);
|
|
3216
|
+
if (unit.startsWith("m") && !unit.startsWith("ms")) {
|
|
3217
|
+
return Math.round(value * 6e4);
|
|
3218
|
+
}
|
|
3219
|
+
return Math.round(value * 1e3);
|
|
3220
|
+
};
|
|
3221
|
+
var isTpdLimit = (message) => /\btpd\b|tokens?\s+per\s+day|daily\s+(?:token\s+)?limit|next\s+day/i.test(
|
|
3222
|
+
message
|
|
3223
|
+
);
|
|
3224
|
+
var isShortWindowLimit = (message) => /\b(?:rpm|tpm)\b|requests?\s+per\s+minute|tokens?\s+per\s+minute|concurren(?:cy|t)/i.test(
|
|
3225
|
+
message
|
|
3226
|
+
);
|
|
3227
|
+
var classifyMoonshotFailure = (error) => {
|
|
3228
|
+
if (isAbortLikeProviderError(error)) {
|
|
3229
|
+
return buildProviderFailure(PROVIDER_NAME3, "cancelled");
|
|
3230
|
+
}
|
|
3231
|
+
const extracted = extractProviderError(error);
|
|
3232
|
+
const status = extracted.status;
|
|
3233
|
+
const type = extracted.type?.toLowerCase() ?? "";
|
|
3234
|
+
const message = extracted.message;
|
|
3235
|
+
const retryAfterMs = extracted.retryAfterMs ?? parseWaitHintMs(message);
|
|
3236
|
+
const delaySource = extracted.retryAfterMs !== void 0 ? "retry-after" : retryAfterMs !== void 0 ? "provider-body" : void 0;
|
|
3237
|
+
const retryOptions = retryAfterMs !== void 0 && delaySource ? { retryAfterMs, delaySource } : {};
|
|
3238
|
+
if (status === 401) {
|
|
3239
|
+
return buildProviderFailure(PROVIDER_NAME3, "auth", { status });
|
|
3240
|
+
}
|
|
3241
|
+
if (status === 403) {
|
|
3242
|
+
return buildProviderFailure(PROVIDER_NAME3, "permission", { status });
|
|
3243
|
+
}
|
|
3244
|
+
if (isValidationStatus(status)) {
|
|
3245
|
+
return buildProviderFailure(PROVIDER_NAME3, "validation", { status });
|
|
3246
|
+
}
|
|
3247
|
+
if (type === "exceeded_current_quota_error") {
|
|
3248
|
+
return buildProviderFailure(PROVIDER_NAME3, "hard_quota", { status });
|
|
3249
|
+
}
|
|
3250
|
+
if (type === "engine_overloaded_error") {
|
|
3251
|
+
return buildProviderFailure(PROVIDER_NAME3, "overloaded", {
|
|
3252
|
+
status,
|
|
3253
|
+
retryable: true,
|
|
3254
|
+
...retryOptions
|
|
3255
|
+
});
|
|
3256
|
+
}
|
|
3257
|
+
if (status === 429 && type === "rate_limit_reached_error") {
|
|
3258
|
+
if (isTpdLimit(message)) {
|
|
3259
|
+
return buildProviderFailure(PROVIDER_NAME3, "hard_quota", { status });
|
|
3260
|
+
}
|
|
3261
|
+
if (isShortWindowLimit(message) || retryAfterMs !== void 0) {
|
|
3262
|
+
return buildProviderFailure(PROVIDER_NAME3, "rate_limit", {
|
|
3263
|
+
status,
|
|
3264
|
+
retryable: true,
|
|
3265
|
+
...retryOptions
|
|
3266
|
+
});
|
|
3267
|
+
}
|
|
3268
|
+
return buildProviderFailure(PROVIDER_NAME3, "rate_limit", { status });
|
|
3269
|
+
}
|
|
3270
|
+
if (status === 429) {
|
|
3271
|
+
return buildProviderFailure(PROVIDER_NAME3, "rate_limit", { status });
|
|
3272
|
+
}
|
|
3273
|
+
if (status === 408) {
|
|
3274
|
+
return buildProviderFailure(PROVIDER_NAME3, "timeout", {
|
|
3275
|
+
status,
|
|
3276
|
+
retryable: true,
|
|
3277
|
+
...retryOptions
|
|
3278
|
+
});
|
|
3279
|
+
}
|
|
3280
|
+
if (status === 409) {
|
|
3281
|
+
return buildProviderFailure(PROVIDER_NAME3, "provider", {
|
|
3282
|
+
status,
|
|
3283
|
+
retryable: true,
|
|
3284
|
+
...retryOptions
|
|
3285
|
+
});
|
|
3286
|
+
}
|
|
3287
|
+
if (status === 503) {
|
|
3288
|
+
return buildProviderFailure(PROVIDER_NAME3, "overloaded", {
|
|
3289
|
+
status,
|
|
3290
|
+
retryable: true,
|
|
3291
|
+
...retryOptions
|
|
3292
|
+
});
|
|
3293
|
+
}
|
|
3294
|
+
if (status !== void 0 && status >= 500) {
|
|
3295
|
+
return buildProviderFailure(PROVIDER_NAME3, "provider", {
|
|
3296
|
+
status,
|
|
3297
|
+
retryable: true,
|
|
3298
|
+
...retryOptions
|
|
3299
|
+
});
|
|
3300
|
+
}
|
|
3301
|
+
return classifyTransportFailure(PROVIDER_NAME3, error) ?? buildProviderFailure(PROVIDER_NAME3, "provider");
|
|
3302
|
+
};
|
|
3303
|
+
|
|
3304
|
+
// src/llm/moonshot/serializer.ts
|
|
3305
|
+
var stringify = (content) => stringifyContent(content, { mode: "display", joiner: "" });
|
|
3306
|
+
var MOONSHOT_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
|
|
3307
|
+
"image/png",
|
|
3308
|
+
"image/jpeg",
|
|
3309
|
+
"image/webp",
|
|
3310
|
+
"image/gif"
|
|
3311
|
+
]);
|
|
3312
|
+
var BASE64_PAYLOAD = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
3313
|
+
var toMoonshotImagePart = (part) => {
|
|
3314
|
+
const url = part.image_url.url;
|
|
3315
|
+
if (url.startsWith("ms://") && url.length > "ms://".length) {
|
|
3316
|
+
return { type: "image_url", image_url: { url } };
|
|
3317
|
+
}
|
|
3318
|
+
const separator = url.indexOf(",");
|
|
3319
|
+
const header = separator >= 0 ? url.slice(0, separator) : "";
|
|
3320
|
+
const payload = separator >= 0 ? url.slice(separator + 1) : "";
|
|
3321
|
+
const mediaType = header.startsWith("data:") && header.endsWith(";base64") ? header.slice("data:".length, header.length - ";base64".length) : "";
|
|
3322
|
+
if (!header.endsWith(";base64") || !MOONSHOT_IMAGE_MEDIA_TYPES.has(mediaType) || !payload || !BASE64_PAYLOAD.test(payload)) {
|
|
3323
|
+
throw createProviderValidationError(
|
|
3324
|
+
"moonshot",
|
|
3325
|
+
"Moonshot image input must be a base64 data URL for png/jpeg/webp/gif or an ms:// file id; public image URLs are not supported"
|
|
3326
|
+
);
|
|
3327
|
+
}
|
|
3328
|
+
if (part.image_url.media_type && part.image_url.media_type !== mediaType) {
|
|
3329
|
+
throw createProviderValidationError(
|
|
3330
|
+
"moonshot",
|
|
3331
|
+
`Moonshot image media_type mismatch: declared ${part.image_url.media_type}, data URL uses ${mediaType}`
|
|
3332
|
+
);
|
|
3333
|
+
}
|
|
3334
|
+
return { type: "image_url", image_url: { url } };
|
|
3335
|
+
};
|
|
3336
|
+
var toUserContent = (content) => {
|
|
3337
|
+
if (typeof content === "string") return content;
|
|
3338
|
+
const parts = [];
|
|
3339
|
+
for (const part of content) {
|
|
3340
|
+
if (part.type === "text") {
|
|
3341
|
+
parts.push(part);
|
|
3342
|
+
} else if (part.type === "image_url") {
|
|
3343
|
+
parts.push(toMoonshotImagePart(part));
|
|
3344
|
+
} else {
|
|
3345
|
+
parts.push({ type: "text", text: stringify([part]) });
|
|
3346
|
+
}
|
|
3347
|
+
}
|
|
3348
|
+
return parts;
|
|
3349
|
+
};
|
|
3350
|
+
var isMoonshotReasoning = (message) => {
|
|
3351
|
+
if (message.role !== "reasoning" || !message.content) return false;
|
|
3352
|
+
const raw = message.raw_item;
|
|
3353
|
+
return typeof raw === "object" && raw !== null && "provider" in raw && raw.provider === "moonshot";
|
|
3354
|
+
};
|
|
3355
|
+
function toMoonshotMessages(messages) {
|
|
3356
|
+
const mapped = [];
|
|
3357
|
+
let pendingReasoning = null;
|
|
3358
|
+
const pendingToolImages = [];
|
|
3359
|
+
const flushPendingToolImages = () => {
|
|
3360
|
+
if (!pendingToolImages.length) return;
|
|
3361
|
+
const content = [];
|
|
3362
|
+
for (const pending of pendingToolImages) {
|
|
3363
|
+
content.push({
|
|
3364
|
+
type: "text",
|
|
3365
|
+
text: `Image output from tool ${pending.toolName} (call ${pending.toolCallId}).`
|
|
3366
|
+
});
|
|
3367
|
+
content.push(pending.image);
|
|
3368
|
+
}
|
|
3369
|
+
mapped.push({ role: "user", content });
|
|
3370
|
+
pendingToolImages.length = 0;
|
|
3371
|
+
};
|
|
3372
|
+
for (const message of messages) {
|
|
3373
|
+
if (message.role !== "tool") {
|
|
3374
|
+
flushPendingToolImages();
|
|
3375
|
+
}
|
|
3376
|
+
switch (message.role) {
|
|
3377
|
+
case "system":
|
|
3378
|
+
mapped.push({ role: "system", content: stringify(message.content) });
|
|
3379
|
+
pendingReasoning = null;
|
|
3380
|
+
break;
|
|
3381
|
+
case "user":
|
|
3382
|
+
mapped.push({ role: "user", content: toUserContent(message.content) });
|
|
3383
|
+
pendingReasoning = null;
|
|
3384
|
+
break;
|
|
3385
|
+
case "reasoning":
|
|
3386
|
+
pendingReasoning = isMoonshotReasoning(message) ? message.content : null;
|
|
3387
|
+
break;
|
|
3388
|
+
case "assistant": {
|
|
3389
|
+
const toolCalls = toReplayToolCalls(message.tool_calls);
|
|
3390
|
+
mapped.push({
|
|
3391
|
+
role: "assistant",
|
|
3392
|
+
content: stringify(message.content) || null,
|
|
3393
|
+
...pendingReasoning ? { reasoning_content: pendingReasoning } : {},
|
|
3394
|
+
...toolCalls.length ? { tool_calls: toolCalls } : {}
|
|
3395
|
+
});
|
|
3396
|
+
pendingReasoning = null;
|
|
3397
|
+
break;
|
|
3398
|
+
}
|
|
3399
|
+
case "tool": {
|
|
3400
|
+
const textParts = [];
|
|
3401
|
+
for (const part of typeof message.content === "string" ? [] : message.content) {
|
|
3402
|
+
if (part.type === "image_url") {
|
|
3403
|
+
pendingToolImages.push({
|
|
3404
|
+
toolName: message.tool_name,
|
|
3405
|
+
toolCallId: message.tool_call_id,
|
|
3406
|
+
image: toMoonshotImagePart(part)
|
|
3407
|
+
});
|
|
3408
|
+
} else {
|
|
3409
|
+
textParts.push(part);
|
|
3410
|
+
}
|
|
3411
|
+
}
|
|
3412
|
+
const textContent = typeof message.content === "string" ? message.content : textParts.length ? stringify(textParts) : "";
|
|
3413
|
+
mapped.push({
|
|
3414
|
+
role: "tool",
|
|
3415
|
+
tool_call_id: message.tool_call_id,
|
|
3416
|
+
content: textContent || `Tool ${message.tool_name} returned image output attached in the following user message.`
|
|
3417
|
+
});
|
|
3418
|
+
pendingReasoning = null;
|
|
3419
|
+
break;
|
|
3420
|
+
}
|
|
3421
|
+
}
|
|
3422
|
+
}
|
|
3423
|
+
flushPendingToolImages();
|
|
3424
|
+
return mapped;
|
|
3425
|
+
}
|
|
3426
|
+
function toMoonshotTools(tools) {
|
|
3427
|
+
if (!tools?.length) return void 0;
|
|
3428
|
+
const mapped = tools.filter(isFunctionToolDefinition).map((tool) => ({
|
|
3429
|
+
type: "function",
|
|
3430
|
+
function: {
|
|
3431
|
+
name: tool.name,
|
|
3432
|
+
description: tool.description,
|
|
3433
|
+
parameters: tool.parameters,
|
|
3434
|
+
...tool.strict !== void 0 ? { strict: tool.strict } : {}
|
|
3435
|
+
}
|
|
3436
|
+
}));
|
|
3437
|
+
return mapped.length ? mapped : void 0;
|
|
3438
|
+
}
|
|
3439
|
+
function toMoonshotToolChoice(choice) {
|
|
3440
|
+
if (!choice) return void 0;
|
|
3441
|
+
if (choice === "auto" || choice === "required" || choice === "none") {
|
|
3442
|
+
return choice;
|
|
3443
|
+
}
|
|
3444
|
+
return { type: "function", function: { name: choice } };
|
|
3445
|
+
}
|
|
3446
|
+
var createMoonshotStreamAccumulator = () => ({
|
|
3447
|
+
content: "",
|
|
3448
|
+
reasoningContent: "",
|
|
3449
|
+
toolCalls: [],
|
|
3450
|
+
rawChunkCount: 0
|
|
3451
|
+
});
|
|
3452
|
+
function appendMoonshotChatCompletionChunk(accumulator, chunk) {
|
|
3453
|
+
accumulator.rawChunkCount += 1;
|
|
3454
|
+
accumulator.id ??= chunk.id;
|
|
3455
|
+
accumulator.model ??= chunk.model;
|
|
3456
|
+
accumulator.usage ??= chunk.usage ?? void 0;
|
|
3457
|
+
for (const choice of chunk.choices ?? []) {
|
|
3458
|
+
if (choice.finish_reason !== void 0) {
|
|
3459
|
+
accumulator.finishReason = choice.finish_reason;
|
|
3460
|
+
}
|
|
3461
|
+
const delta = choice.delta;
|
|
3462
|
+
if (!delta) continue;
|
|
3463
|
+
if (typeof delta.reasoning_content === "string") {
|
|
3464
|
+
accumulator.reasoningContent += delta.reasoning_content;
|
|
3465
|
+
}
|
|
3466
|
+
if (typeof delta.content === "string") {
|
|
3467
|
+
accumulator.content += delta.content;
|
|
3468
|
+
}
|
|
3469
|
+
for (const toolDelta of delta.tool_calls ?? []) {
|
|
3470
|
+
const index = typeof toolDelta.index === "number" ? toolDelta.index : accumulator.toolCalls.length;
|
|
3471
|
+
let call = accumulator.toolCalls.find((entry) => entry.index === index);
|
|
3472
|
+
if (!call) {
|
|
3473
|
+
call = {
|
|
3474
|
+
index,
|
|
3475
|
+
id: toolDelta.id ?? `call_${index}`,
|
|
3476
|
+
name: "",
|
|
3477
|
+
arguments: "",
|
|
3478
|
+
rawChunkCount: 0
|
|
3479
|
+
};
|
|
3480
|
+
accumulator.toolCalls.push(call);
|
|
3481
|
+
accumulator.toolCalls.sort((left, right) => left.index - right.index);
|
|
3482
|
+
}
|
|
3483
|
+
call.rawChunkCount += 1;
|
|
3484
|
+
if (toolDelta.id) call.id = toolDelta.id;
|
|
3485
|
+
if (typeof toolDelta.function?.name === "string") {
|
|
3486
|
+
call.name = toolDelta.function.name;
|
|
3487
|
+
}
|
|
3488
|
+
if (typeof toolDelta.function?.arguments === "string") {
|
|
3489
|
+
call.arguments += toolDelta.function.arguments;
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
3492
|
+
}
|
|
3493
|
+
}
|
|
3494
|
+
function toMoonshotChatInvokeCompletion(accumulator, meta) {
|
|
3495
|
+
const messages = [];
|
|
3496
|
+
if (accumulator.reasoningContent) {
|
|
3497
|
+
messages.push({
|
|
3498
|
+
role: "reasoning",
|
|
3499
|
+
content: accumulator.reasoningContent,
|
|
3500
|
+
raw_item: {
|
|
3501
|
+
provider: "moonshot",
|
|
3502
|
+
field: "reasoning_content",
|
|
3503
|
+
response_id: accumulator.id
|
|
3504
|
+
}
|
|
3505
|
+
});
|
|
3506
|
+
}
|
|
3507
|
+
const toolCalls = accumulator.toolCalls.map(toToolCall);
|
|
3508
|
+
if (accumulator.content || toolCalls.length) {
|
|
3509
|
+
messages.push({
|
|
3510
|
+
role: "assistant",
|
|
3511
|
+
content: accumulator.content || null,
|
|
3512
|
+
...toolCalls.length ? { tool_calls: toolCalls } : {}
|
|
3513
|
+
});
|
|
3514
|
+
}
|
|
3515
|
+
return {
|
|
3516
|
+
messages,
|
|
3517
|
+
usage: normalizeUsage(accumulator),
|
|
3518
|
+
stop_reason: accumulator.finishReason ?? null,
|
|
3519
|
+
provider_meta: {
|
|
3520
|
+
response_id: accumulator.id,
|
|
3521
|
+
finish_reason: accumulator.finishReason ?? null,
|
|
3522
|
+
reasoning_requested: meta.reasoningRequested,
|
|
3523
|
+
reasoning_applied: "max",
|
|
3524
|
+
reasoning_effort: "max",
|
|
3525
|
+
reasoning_fallback: meta.reasoningFallback
|
|
3526
|
+
}
|
|
3527
|
+
};
|
|
3528
|
+
}
|
|
3529
|
+
var toReplayToolCalls = (toolCalls) => (toolCalls ?? []).map((call) => ({
|
|
3530
|
+
id: call.id,
|
|
3531
|
+
type: "function",
|
|
3532
|
+
function: { ...call.function }
|
|
3533
|
+
}));
|
|
3534
|
+
var toToolCall = (call) => ({
|
|
3535
|
+
id: call.id,
|
|
3536
|
+
type: "function",
|
|
3537
|
+
function: { name: call.name, arguments: call.arguments },
|
|
3538
|
+
provider_meta: {
|
|
3539
|
+
provider: "moonshot",
|
|
3540
|
+
index: call.index,
|
|
3541
|
+
raw_chunk_count: call.rawChunkCount
|
|
3542
|
+
}
|
|
3543
|
+
});
|
|
3544
|
+
var normalizeNumber = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0;
|
|
3545
|
+
var normalizeUsage = (accumulator) => {
|
|
3546
|
+
const usage = accumulator.usage;
|
|
3547
|
+
if (!usage) return null;
|
|
3548
|
+
const inputTokens = normalizeNumber(usage.prompt_tokens);
|
|
3549
|
+
const outputTokens = normalizeNumber(usage.completion_tokens);
|
|
3550
|
+
const cachedTokens = normalizeNumber(
|
|
3551
|
+
usage.cached_tokens ?? usage.prompt_tokens_details?.cached_tokens
|
|
3552
|
+
);
|
|
3553
|
+
return {
|
|
3554
|
+
model: accumulator.model ?? "",
|
|
3555
|
+
input_tokens: inputTokens,
|
|
3556
|
+
...cachedTokens > 0 ? { input_cached_tokens: cachedTokens } : {},
|
|
3557
|
+
output_tokens: outputTokens,
|
|
3558
|
+
total_tokens: typeof usage.total_tokens === "number" ? normalizeNumber(usage.total_tokens) : inputTokens + outputTokens
|
|
3559
|
+
};
|
|
3560
|
+
};
|
|
3561
|
+
|
|
3562
|
+
// src/llm/moonshot/chat.ts
|
|
3563
|
+
var PROVIDER_NAME4 = "moonshot";
|
|
3564
|
+
var DEFAULT_BASE_URL = "https://api.moonshot.ai/v1";
|
|
3565
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 2 * 60 * 60 * 1e3;
|
|
3566
|
+
var ChatMoonshot = class {
|
|
3567
|
+
provider = PROVIDER_NAME4;
|
|
3568
|
+
model;
|
|
3569
|
+
classifyFailure = classifyMoonshotFailure;
|
|
3570
|
+
apiKey;
|
|
3571
|
+
clientOptions;
|
|
3572
|
+
reasoningLevelRequested;
|
|
3573
|
+
debugInvokeSeq = 0;
|
|
3574
|
+
lastDebugRequestPayload = null;
|
|
3575
|
+
constructor(options = {}) {
|
|
3576
|
+
this.apiKey = options.apiKey;
|
|
3577
|
+
this.model = options.model ?? MOONSHOT_DEFAULT_MODEL;
|
|
3578
|
+
this.reasoningLevelRequested = options.reasoningLevelRequested ?? "medium";
|
|
3579
|
+
this.clientOptions = {
|
|
3580
|
+
baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
|
|
3581
|
+
timeout: options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
3582
|
+
maxRetries: options.maxRetries ?? 0,
|
|
3583
|
+
...options.fetch ? { fetch: options.fetch } : {}
|
|
3584
|
+
};
|
|
3585
|
+
}
|
|
3586
|
+
async ainvoke(input) {
|
|
3587
|
+
if (!this.apiKey) {
|
|
3588
|
+
throw new Error("Moonshot API key is required");
|
|
3589
|
+
}
|
|
3590
|
+
const tools = toMoonshotTools(input.tools);
|
|
3591
|
+
const toolChoice = toMoonshotToolChoice(input.toolChoice);
|
|
3592
|
+
const request = {
|
|
3593
|
+
model: input.model ?? this.model,
|
|
3594
|
+
messages: toMoonshotMessages(input.messages),
|
|
3595
|
+
stream: true,
|
|
3596
|
+
stream_options: { include_usage: true },
|
|
3597
|
+
reasoning_effort: "max",
|
|
3598
|
+
...input.options ?? {},
|
|
3599
|
+
...tools ? { tools } : {},
|
|
3600
|
+
...toolChoice ? { tool_choice: toolChoice } : {}
|
|
3601
|
+
};
|
|
3602
|
+
const seq = this.nextDebugInvokeSeq();
|
|
3603
|
+
await this.debugRequestIfEnabled(request, seq);
|
|
3604
|
+
const client = new OpenAI({ apiKey: this.apiKey, ...this.clientOptions });
|
|
3605
|
+
const accumulator = createMoonshotStreamAccumulator();
|
|
3606
|
+
try {
|
|
3607
|
+
const stream = await client.chat.completions.create(
|
|
3608
|
+
request,
|
|
3609
|
+
{ signal: input.signal }
|
|
3610
|
+
);
|
|
3611
|
+
for await (const chunk of stream) {
|
|
3612
|
+
appendMoonshotChatCompletionChunk(
|
|
3613
|
+
accumulator,
|
|
3614
|
+
chunk
|
|
3615
|
+
);
|
|
3616
|
+
}
|
|
3617
|
+
} catch (error) {
|
|
3618
|
+
const failure = classifyMoonshotFailure(error);
|
|
3619
|
+
throw new ProviderFailureError(
|
|
3620
|
+
accumulator.rawChunkCount > 0 ? { ...failure, retryable: false, delivery: "buffered" } : failure,
|
|
3621
|
+
{ cause: error }
|
|
3622
|
+
);
|
|
3623
|
+
}
|
|
3624
|
+
await this.debugResponseIfEnabled(accumulator, seq);
|
|
3625
|
+
return toMoonshotChatInvokeCompletion(accumulator, {
|
|
3626
|
+
reasoningRequested: this.reasoningLevelRequested,
|
|
3627
|
+
reasoningFallback: this.reasoningLevelRequested !== "max"
|
|
3628
|
+
});
|
|
3629
|
+
}
|
|
3630
|
+
nextDebugInvokeSeq() {
|
|
3631
|
+
this.debugInvokeSeq += 1;
|
|
3632
|
+
return this.debugInvokeSeq;
|
|
3633
|
+
}
|
|
3634
|
+
async debugRequestIfEnabled(request, seq) {
|
|
3635
|
+
const settings = getProviderLogSettings();
|
|
3636
|
+
if (!settings.enabled && !settings.dumpDir) return;
|
|
3637
|
+
const payload = safeJsonStringify(request);
|
|
3638
|
+
const hash = createHash2("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3639
|
+
const previous = this.lastDebugRequestPayload;
|
|
3640
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3641
|
+
if (settings.enabled) {
|
|
3642
|
+
console.error(
|
|
3643
|
+
`[moonshot.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared}`
|
|
3644
|
+
);
|
|
3645
|
+
}
|
|
3646
|
+
if (settings.dumpDir) {
|
|
3647
|
+
try {
|
|
3648
|
+
await writeProviderLogDump(
|
|
3649
|
+
settings,
|
|
3650
|
+
PROVIDER_NAME4,
|
|
3651
|
+
seq,
|
|
3652
|
+
"request",
|
|
3653
|
+
request
|
|
3654
|
+
);
|
|
3655
|
+
} catch (error) {
|
|
3656
|
+
if (settings.enabled) {
|
|
3657
|
+
console.error(
|
|
3658
|
+
`[moonshot.request] dump_failed seq=${seq} error=${String(error)}`
|
|
3659
|
+
);
|
|
3660
|
+
}
|
|
3661
|
+
}
|
|
3662
|
+
}
|
|
3663
|
+
this.lastDebugRequestPayload = payload;
|
|
3664
|
+
}
|
|
3665
|
+
async debugResponseIfEnabled(response, seq) {
|
|
3666
|
+
const settings = getProviderLogSettings();
|
|
3667
|
+
if (!settings.enabled && !settings.dumpDir) return;
|
|
2579
3668
|
if (settings.enabled) {
|
|
2580
|
-
const usage = response.usage;
|
|
2581
|
-
const inputTokens = usage?.input_tokens ?? 0;
|
|
2582
|
-
const outputTokens = usage?.output_tokens ?? 0;
|
|
2583
|
-
const cachedRead = usage?.cache_read_input_tokens ?? 0;
|
|
2584
|
-
const cachedCreate = usage?.cache_creation_input_tokens ?? 0;
|
|
2585
|
-
const blocks = Array.isArray(response.content) ? response.content : [];
|
|
2586
|
-
const blockKinds = /* @__PURE__ */ new Set();
|
|
2587
|
-
for (const block of blocks) {
|
|
2588
|
-
const kind = block && typeof block === "object" && "type" in block ? String(block.type ?? "unknown") : "unknown";
|
|
2589
|
-
blockKinds.add(kind);
|
|
2590
|
-
}
|
|
2591
3669
|
console.error(
|
|
2592
|
-
`[
|
|
3670
|
+
`[moonshot.response] seq=${seq} id=${response.id ?? "unknown"} chunks=${response.rawChunkCount} finish=${response.finishReason ?? "unknown"} tok_in=${response.usage?.prompt_tokens ?? 0} tok_out=${response.usage?.completion_tokens ?? 0}`
|
|
2593
3671
|
);
|
|
2594
3672
|
}
|
|
2595
3673
|
if (settings.dumpDir) {
|
|
2596
3674
|
try {
|
|
2597
3675
|
await writeProviderLogDump(
|
|
2598
3676
|
settings,
|
|
2599
|
-
|
|
3677
|
+
PROVIDER_NAME4,
|
|
2600
3678
|
seq,
|
|
2601
3679
|
"response",
|
|
2602
3680
|
response
|
|
@@ -2604,7 +3682,7 @@ var ChatAnthropic = class {
|
|
|
2604
3682
|
} catch (error) {
|
|
2605
3683
|
if (settings.enabled) {
|
|
2606
3684
|
console.error(
|
|
2607
|
-
`[
|
|
3685
|
+
`[moonshot.response] dump_failed seq=${seq} error=${String(error)}`
|
|
2608
3686
|
);
|
|
2609
3687
|
}
|
|
2610
3688
|
}
|
|
@@ -2613,8 +3691,8 @@ var ChatAnthropic = class {
|
|
|
2613
3691
|
};
|
|
2614
3692
|
|
|
2615
3693
|
// src/llm/openai/chat.ts
|
|
2616
|
-
import { createHash as
|
|
2617
|
-
import
|
|
3694
|
+
import { createHash as createHash3 } from "crypto";
|
|
3695
|
+
import OpenAI2 from "openai";
|
|
2618
3696
|
|
|
2619
3697
|
// src/llm/openai/response-utils.ts
|
|
2620
3698
|
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
@@ -3470,7 +4548,7 @@ function toResponsesTools(tools) {
|
|
|
3470
4548
|
});
|
|
3471
4549
|
continue;
|
|
3472
4550
|
}
|
|
3473
|
-
if (
|
|
4551
|
+
if (isHostedWebSearchToolDefinition(tool)) {
|
|
3474
4552
|
const hosted = toOpenAiHostedSearchTool(tool);
|
|
3475
4553
|
if (hosted) {
|
|
3476
4554
|
mapped.push(hosted);
|
|
@@ -3659,6 +4737,7 @@ var WsResponseError = class extends Error {
|
|
|
3659
4737
|
super(message);
|
|
3660
4738
|
this.code = code;
|
|
3661
4739
|
}
|
|
4740
|
+
code;
|
|
3662
4741
|
};
|
|
3663
4742
|
var OpenAiWsTransport = class {
|
|
3664
4743
|
client;
|
|
@@ -3807,7 +4886,7 @@ var OpenAiWsTransport = class {
|
|
|
3807
4886
|
}
|
|
3808
4887
|
settled = true;
|
|
3809
4888
|
teardown();
|
|
3810
|
-
reject(new
|
|
4889
|
+
reject(new ProviderTimeoutError("openai websocket response timeout"));
|
|
3811
4890
|
}, this.wsResponseIdleTimeoutMs);
|
|
3812
4891
|
};
|
|
3813
4892
|
rejectResponsePromise = rejectOnce;
|
|
@@ -4309,7 +5388,9 @@ var OpenAiWsTransport = class {
|
|
|
4309
5388
|
}
|
|
4310
5389
|
};
|
|
4311
5390
|
const timeout = setTimeout(() => {
|
|
4312
|
-
settleReject(
|
|
5391
|
+
settleReject(
|
|
5392
|
+
new ProviderTimeoutError("openai websocket connect timeout")
|
|
5393
|
+
);
|
|
4313
5394
|
}, this.wsConnectTimeoutMs);
|
|
4314
5395
|
addSocketListener("open", () => {
|
|
4315
5396
|
settleResolve();
|
|
@@ -4347,7 +5428,7 @@ var OpenAiWsTransport = class {
|
|
|
4347
5428
|
};
|
|
4348
5429
|
|
|
4349
5430
|
// src/llm/openai/chat.ts
|
|
4350
|
-
var
|
|
5431
|
+
var PROVIDER_NAME5 = "openai";
|
|
4351
5432
|
var DEFAULT_MODEL2 = OPENAI_DEFAULT_MODEL;
|
|
4352
5433
|
var DEFAULT_REASONING_EFFORT = OPENAI_DEFAULT_REASONING_EFFORT;
|
|
4353
5434
|
var DEFAULT_REASONING_SUMMARY = "auto";
|
|
@@ -4358,8 +5439,9 @@ var WS_SESSION_IDLE_TTL_MS = 10 * 6e4;
|
|
|
4358
5439
|
var WS_SESSION_DISABLE_TTL_MS = 6e4;
|
|
4359
5440
|
var WS_REUSE_MAX_IDLE_MS = 3e4;
|
|
4360
5441
|
var ChatOpenAI = class {
|
|
4361
|
-
provider =
|
|
5442
|
+
provider = PROVIDER_NAME5;
|
|
4362
5443
|
model;
|
|
5444
|
+
classifyFailure = (error) => classifyOpenAiCompatibleFailure(PROVIDER_NAME5, error);
|
|
4363
5445
|
providerModel;
|
|
4364
5446
|
client;
|
|
4365
5447
|
defaultReasoningEffort;
|
|
@@ -4375,7 +5457,10 @@ var ChatOpenAI = class {
|
|
|
4375
5457
|
wsDisabledUntilBySessionKey = /* @__PURE__ */ new Map();
|
|
4376
5458
|
wsReconnectCount = 0;
|
|
4377
5459
|
constructor(options = {}) {
|
|
4378
|
-
this.client = options.client ?? new
|
|
5460
|
+
this.client = options.client ?? new OpenAI2({
|
|
5461
|
+
...options.clientOptions ?? {},
|
|
5462
|
+
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
5463
|
+
});
|
|
4379
5464
|
this.model = options.model ?? DEFAULT_MODEL2;
|
|
4380
5465
|
this.providerModel = options.providerModel ?? this.model;
|
|
4381
5466
|
this.defaultReasoningEffort = options.reasoningEffort ?? DEFAULT_REASONING_EFFORT;
|
|
@@ -4455,8 +5540,8 @@ var ChatOpenAI = class {
|
|
|
4455
5540
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
4456
5541
|
const requestMeta = {
|
|
4457
5542
|
model: String(request.model ?? this.providerModel),
|
|
4458
|
-
instructionsHash:
|
|
4459
|
-
toolsHash:
|
|
5543
|
+
instructionsHash: createHash3("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12),
|
|
5544
|
+
toolsHash: createHash3("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12)
|
|
4460
5545
|
};
|
|
4461
5546
|
const transportResult = await this.invokeWithTransport({
|
|
4462
5547
|
request,
|
|
@@ -4819,14 +5904,14 @@ var ChatOpenAI = class {
|
|
|
4819
5904
|
return;
|
|
4820
5905
|
}
|
|
4821
5906
|
const payload = safeJsonStringify(request);
|
|
4822
|
-
const hash =
|
|
4823
|
-
const toolsHash =
|
|
4824
|
-
const instructionsHash =
|
|
5907
|
+
const hash = createHash3("sha256").update(payload).digest("hex").slice(0, 16);
|
|
5908
|
+
const toolsHash = createHash3("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
5909
|
+
const instructionsHash = createHash3("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
4825
5910
|
const previous = this.lastDebugRequestPayload;
|
|
4826
5911
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
4827
5912
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
4828
5913
|
if (settings.enabled) {
|
|
4829
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${
|
|
5914
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash3("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
4830
5915
|
const chainResetSuffix = typeof chainReset === "boolean" ? ` chain_reset=${chainReset ? "true" : "false"}` : "";
|
|
4831
5916
|
const wsInputModeSuffix = wsInputMode ? ` ws_input_mode=${wsInputMode}` : "";
|
|
4832
5917
|
console.error(
|
|
@@ -4837,7 +5922,7 @@ var ChatOpenAI = class {
|
|
|
4837
5922
|
try {
|
|
4838
5923
|
await writeProviderLogDump(
|
|
4839
5924
|
settings,
|
|
4840
|
-
|
|
5925
|
+
PROVIDER_NAME5,
|
|
4841
5926
|
seq,
|
|
4842
5927
|
"request",
|
|
4843
5928
|
request
|
|
@@ -4875,7 +5960,7 @@ var ChatOpenAI = class {
|
|
|
4875
5960
|
try {
|
|
4876
5961
|
await writeProviderLogDump(
|
|
4877
5962
|
settings,
|
|
4878
|
-
|
|
5963
|
+
PROVIDER_NAME5,
|
|
4879
5964
|
seq,
|
|
4880
5965
|
"response",
|
|
4881
5966
|
response
|
|
@@ -4919,8 +6004,8 @@ var ChatOpenAI = class {
|
|
|
4919
6004
|
};
|
|
4920
6005
|
|
|
4921
6006
|
// src/llm/openrouter/chat.ts
|
|
4922
|
-
import { createHash as
|
|
4923
|
-
import
|
|
6007
|
+
import { createHash as createHash4 } from "crypto";
|
|
6008
|
+
import OpenAI3 from "openai";
|
|
4924
6009
|
|
|
4925
6010
|
// src/llm/openrouter/response-utils.ts
|
|
4926
6011
|
var isRecord4 = (value) => typeof value === "object" && value !== null;
|
|
@@ -5255,7 +6340,7 @@ function toResponsesTools2(tools) {
|
|
|
5255
6340
|
});
|
|
5256
6341
|
continue;
|
|
5257
6342
|
}
|
|
5258
|
-
if (
|
|
6343
|
+
if (isHostedWebSearchToolDefinition(tool)) {
|
|
5259
6344
|
const hosted = toOpenRouterHostedSearchTool(tool);
|
|
5260
6345
|
if (hosted) {
|
|
5261
6346
|
mapped.push(hosted);
|
|
@@ -5369,7 +6454,7 @@ function toOpenRouterHostedSearchTool(tool) {
|
|
|
5369
6454
|
}
|
|
5370
6455
|
|
|
5371
6456
|
// src/llm/openrouter/chat.ts
|
|
5372
|
-
var
|
|
6457
|
+
var PROVIDER_NAME6 = "openrouter";
|
|
5373
6458
|
var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
|
|
5374
6459
|
var DEFAULT_MODEL3 = OPENAI_DEFAULT_MODEL;
|
|
5375
6460
|
var DEFAULT_REASONING_EFFORT2 = OPENAI_DEFAULT_REASONING_EFFORT;
|
|
@@ -5378,8 +6463,9 @@ var getSessionIdHeaderValue2 = (promptCacheKey) => {
|
|
|
5378
6463
|
return typeof promptCacheKey === "string" && promptCacheKey.length > 0 ? promptCacheKey : void 0;
|
|
5379
6464
|
};
|
|
5380
6465
|
var ChatOpenRouter = class {
|
|
5381
|
-
provider =
|
|
6466
|
+
provider = PROVIDER_NAME6;
|
|
5382
6467
|
model;
|
|
6468
|
+
classifyFailure = (error) => classifyOpenAiCompatibleFailure(PROVIDER_NAME6, error);
|
|
5383
6469
|
client;
|
|
5384
6470
|
defaultReasoningEffort;
|
|
5385
6471
|
reasoningLevelMeta;
|
|
@@ -5387,9 +6473,10 @@ var ChatOpenRouter = class {
|
|
|
5387
6473
|
debugInvokeSeq = 0;
|
|
5388
6474
|
lastDebugRequestPayload = null;
|
|
5389
6475
|
constructor(options = {}) {
|
|
5390
|
-
this.client = options.client ?? new
|
|
6476
|
+
this.client = options.client ?? new OpenAI3({
|
|
5391
6477
|
baseURL: OPENROUTER_BASE_URL,
|
|
5392
|
-
...options.clientOptions ?? {}
|
|
6478
|
+
...options.clientOptions ?? {},
|
|
6479
|
+
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
5393
6480
|
});
|
|
5394
6481
|
this.model = options.model ?? DEFAULT_MODEL3;
|
|
5395
6482
|
this.defaultReasoningEffort = options.reasoningEffort ?? DEFAULT_REASONING_EFFORT2;
|
|
@@ -5487,14 +6574,14 @@ var ChatOpenRouter = class {
|
|
|
5487
6574
|
return;
|
|
5488
6575
|
}
|
|
5489
6576
|
const payload = safeJsonStringify(request);
|
|
5490
|
-
const hash =
|
|
5491
|
-
const toolsHash =
|
|
5492
|
-
const instructionsHash =
|
|
6577
|
+
const hash = createHash4("sha256").update(payload).digest("hex").slice(0, 16);
|
|
6578
|
+
const toolsHash = createHash4("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
6579
|
+
const instructionsHash = createHash4("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
5493
6580
|
const previous = this.lastDebugRequestPayload;
|
|
5494
6581
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
5495
6582
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
5496
6583
|
if (settings.enabled) {
|
|
5497
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${
|
|
6584
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash4("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
5498
6585
|
console.error(
|
|
5499
6586
|
`[openrouter.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
5500
6587
|
);
|
|
@@ -5503,7 +6590,7 @@ var ChatOpenRouter = class {
|
|
|
5503
6590
|
try {
|
|
5504
6591
|
await writeProviderLogDump(
|
|
5505
6592
|
settings,
|
|
5506
|
-
|
|
6593
|
+
PROVIDER_NAME6,
|
|
5507
6594
|
seq,
|
|
5508
6595
|
"request",
|
|
5509
6596
|
request
|
|
@@ -5541,7 +6628,7 @@ var ChatOpenRouter = class {
|
|
|
5541
6628
|
try {
|
|
5542
6629
|
await writeProviderLogDump(
|
|
5543
6630
|
settings,
|
|
5544
|
-
|
|
6631
|
+
PROVIDER_NAME6,
|
|
5545
6632
|
seq,
|
|
5546
6633
|
"response",
|
|
5547
6634
|
response
|
|
@@ -5557,8 +6644,431 @@ var ChatOpenRouter = class {
|
|
|
5557
6644
|
}
|
|
5558
6645
|
};
|
|
5559
6646
|
|
|
6647
|
+
// src/llm/xai/chat.ts
|
|
6648
|
+
import { createHash as createHash5 } from "crypto";
|
|
6649
|
+
import OpenAI4 from "openai";
|
|
6650
|
+
|
|
6651
|
+
// src/llm/xai/serializer.ts
|
|
6652
|
+
var XAI_SUPPORTED_INLINE_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
|
|
6653
|
+
"image/jpeg",
|
|
6654
|
+
"image/png"
|
|
6655
|
+
]);
|
|
6656
|
+
var XAI_MAX_WEB_SEARCH_ALLOWED_DOMAINS = 5;
|
|
6657
|
+
var XAI_MAX_X_SEARCH_HANDLES = 20;
|
|
6658
|
+
var mapOtherPartProvider = (part, from, to) => part.type === "other" && part.provider === from ? { ...part, provider: to } : part;
|
|
6659
|
+
var mapMessageOtherParts = (message, from, to) => {
|
|
6660
|
+
if (!Array.isArray(message.content)) {
|
|
6661
|
+
return message;
|
|
6662
|
+
}
|
|
6663
|
+
return {
|
|
6664
|
+
...message,
|
|
6665
|
+
content: message.content.map(
|
|
6666
|
+
(part) => mapOtherPartProvider(part, from, to)
|
|
6667
|
+
)
|
|
6668
|
+
};
|
|
6669
|
+
};
|
|
6670
|
+
var assertSupportedInlineImage = (part) => {
|
|
6671
|
+
if (part.type !== "image_url") return;
|
|
6672
|
+
const declaredMediaType = part.image_url.media_type?.toLowerCase();
|
|
6673
|
+
const dataUrlMatch = /^data:([^;,]+)[;,]/i.exec(part.image_url.url);
|
|
6674
|
+
const inlineMediaType = dataUrlMatch?.[1]?.toLowerCase();
|
|
6675
|
+
const mediaType = inlineMediaType ?? declaredMediaType;
|
|
6676
|
+
if (part.image_url.url.startsWith("data:") && (!mediaType || !XAI_SUPPORTED_INLINE_IMAGE_MEDIA_TYPES.has(mediaType))) {
|
|
6677
|
+
throw createProviderValidationError(
|
|
6678
|
+
"xai",
|
|
6679
|
+
`xAI image input supports inline image/jpeg and image/png only; received ${mediaType ?? "unknown media type"}`
|
|
6680
|
+
);
|
|
6681
|
+
}
|
|
6682
|
+
};
|
|
6683
|
+
var assertSupportedImages = (messages) => {
|
|
6684
|
+
for (const message of messages) {
|
|
6685
|
+
if (!Array.isArray(message.content)) continue;
|
|
6686
|
+
for (const part of message.content) {
|
|
6687
|
+
assertSupportedInlineImage(part);
|
|
6688
|
+
}
|
|
6689
|
+
}
|
|
6690
|
+
};
|
|
6691
|
+
var toXaiResponsesInput = (messages) => {
|
|
6692
|
+
assertSupportedImages(messages);
|
|
6693
|
+
const input = [];
|
|
6694
|
+
for (const message of messages) {
|
|
6695
|
+
if (message.role === "reasoning" && isXSearchCall(message.raw_item)) {
|
|
6696
|
+
input.push(message.raw_item);
|
|
6697
|
+
continue;
|
|
6698
|
+
}
|
|
6699
|
+
input.push(
|
|
6700
|
+
...toResponsesInput([mapMessageOtherParts(message, "xai", "openai")])
|
|
6701
|
+
);
|
|
6702
|
+
}
|
|
6703
|
+
return input;
|
|
6704
|
+
};
|
|
6705
|
+
var normalizeXSearchHandles = (values, field) => {
|
|
6706
|
+
if (!values?.length) return void 0;
|
|
6707
|
+
const normalized = Array.from(
|
|
6708
|
+
new Set(values.map((value) => value.trim().replace(/^@/, "")))
|
|
6709
|
+
);
|
|
6710
|
+
if (normalized.some((value) => value.length === 0)) {
|
|
6711
|
+
throw createProviderValidationError(
|
|
6712
|
+
"xai",
|
|
6713
|
+
`xAI X Search ${field} must not contain empty handles`
|
|
6714
|
+
);
|
|
6715
|
+
}
|
|
6716
|
+
const invalid = normalized.find((value) => !/^[A-Za-z0-9_]+$/.test(value));
|
|
6717
|
+
if (invalid) {
|
|
6718
|
+
throw createProviderValidationError(
|
|
6719
|
+
"xai",
|
|
6720
|
+
`xAI X Search ${field} must contain bare X handles; received ${invalid}`
|
|
6721
|
+
);
|
|
6722
|
+
}
|
|
6723
|
+
if (normalized.length > XAI_MAX_X_SEARCH_HANDLES) {
|
|
6724
|
+
throw createProviderValidationError(
|
|
6725
|
+
"xai",
|
|
6726
|
+
`xAI X Search supports at most ${XAI_MAX_X_SEARCH_HANDLES} ${field}; received ${normalized.length}`
|
|
6727
|
+
);
|
|
6728
|
+
}
|
|
6729
|
+
return normalized;
|
|
6730
|
+
};
|
|
6731
|
+
var isIsoDate = (value) => {
|
|
6732
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
6733
|
+
if (!match) return false;
|
|
6734
|
+
const year = Number(match[1]);
|
|
6735
|
+
const month = Number(match[2]);
|
|
6736
|
+
const day = Number(match[3]);
|
|
6737
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
6738
|
+
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
|
|
6739
|
+
};
|
|
6740
|
+
var assertXSearchDate = (value, field) => {
|
|
6741
|
+
if (value !== void 0 && !isIsoDate(value)) {
|
|
6742
|
+
throw createProviderValidationError(
|
|
6743
|
+
"xai",
|
|
6744
|
+
`xAI X Search ${field} must use a valid YYYY-MM-DD date; received ${value}`
|
|
6745
|
+
);
|
|
6746
|
+
}
|
|
6747
|
+
};
|
|
6748
|
+
var toXaiXSearchTool = (tool) => {
|
|
6749
|
+
const allowedXHandles = normalizeXSearchHandles(
|
|
6750
|
+
tool.allowed_x_handles,
|
|
6751
|
+
"allowed_x_handles"
|
|
6752
|
+
);
|
|
6753
|
+
const excludedXHandles = normalizeXSearchHandles(
|
|
6754
|
+
tool.excluded_x_handles,
|
|
6755
|
+
"excluded_x_handles"
|
|
6756
|
+
);
|
|
6757
|
+
if (allowedXHandles && excludedXHandles) {
|
|
6758
|
+
throw createProviderValidationError(
|
|
6759
|
+
"xai",
|
|
6760
|
+
"xAI X Search allowed_x_handles and excluded_x_handles are mutually exclusive"
|
|
6761
|
+
);
|
|
6762
|
+
}
|
|
6763
|
+
assertXSearchDate(tool.from_date, "from_date");
|
|
6764
|
+
assertXSearchDate(tool.to_date, "to_date");
|
|
6765
|
+
if (tool.from_date && tool.to_date && tool.from_date > tool.to_date) {
|
|
6766
|
+
throw createProviderValidationError(
|
|
6767
|
+
"xai",
|
|
6768
|
+
"xAI X Search from_date must be on or before to_date"
|
|
6769
|
+
);
|
|
6770
|
+
}
|
|
6771
|
+
return {
|
|
6772
|
+
type: "x_search",
|
|
6773
|
+
...allowedXHandles ? { allowed_x_handles: allowedXHandles } : {},
|
|
6774
|
+
...excludedXHandles ? { excluded_x_handles: excludedXHandles } : {},
|
|
6775
|
+
...tool.from_date ? { from_date: tool.from_date } : {},
|
|
6776
|
+
...tool.to_date ? { to_date: tool.to_date } : {},
|
|
6777
|
+
...typeof tool.enable_image_understanding === "boolean" ? { enable_image_understanding: tool.enable_image_understanding } : {},
|
|
6778
|
+
...typeof tool.enable_video_understanding === "boolean" ? { enable_video_understanding: tool.enable_video_understanding } : {}
|
|
6779
|
+
};
|
|
6780
|
+
};
|
|
6781
|
+
var toXaiWebSearchTool = (tool) => {
|
|
6782
|
+
if ((tool.allowed_domains?.length ?? 0) > XAI_MAX_WEB_SEARCH_ALLOWED_DOMAINS) {
|
|
6783
|
+
throw createProviderValidationError(
|
|
6784
|
+
"xai",
|
|
6785
|
+
`xAI web search supports at most ${XAI_MAX_WEB_SEARCH_ALLOWED_DOMAINS} allowed_domains; received ${tool.allowed_domains?.length ?? 0}`
|
|
6786
|
+
);
|
|
6787
|
+
}
|
|
6788
|
+
return {
|
|
6789
|
+
type: "web_search",
|
|
6790
|
+
...tool.allowed_domains?.length ? { filters: { allowed_domains: tool.allowed_domains } } : {}
|
|
6791
|
+
};
|
|
6792
|
+
};
|
|
6793
|
+
var toXaiResponsesTools = (tools) => {
|
|
6794
|
+
if (!tools?.length) return void 0;
|
|
6795
|
+
const mapped = [];
|
|
6796
|
+
for (const tool of tools) {
|
|
6797
|
+
if (isHostedXSearchToolDefinition(tool)) {
|
|
6798
|
+
mapped.push(toXaiXSearchTool(tool));
|
|
6799
|
+
continue;
|
|
6800
|
+
}
|
|
6801
|
+
if (!isHostedWebSearchToolDefinition(tool) || tool.provider !== "xai") {
|
|
6802
|
+
const serialized = toResponsesTools([tool]);
|
|
6803
|
+
if (serialized?.[0]) mapped.push(serialized[0]);
|
|
6804
|
+
continue;
|
|
6805
|
+
}
|
|
6806
|
+
mapped.push(toXaiWebSearchTool(tool));
|
|
6807
|
+
}
|
|
6808
|
+
return mapped.length ? mapped : void 0;
|
|
6809
|
+
};
|
|
6810
|
+
var toXaiResponsesToolChoice = (choice) => toResponsesToolChoice(choice);
|
|
6811
|
+
var toXaiChatInvokeCompletion = (response, meta) => {
|
|
6812
|
+
const completion = toChatInvokeCompletion2(response, {
|
|
6813
|
+
transport: "http_stream",
|
|
6814
|
+
...meta
|
|
6815
|
+
});
|
|
6816
|
+
const messages = completion.messages.map((message, index) => {
|
|
6817
|
+
const item = response.output[index];
|
|
6818
|
+
if (isXSearchCall(item)) {
|
|
6819
|
+
return {
|
|
6820
|
+
role: "reasoning",
|
|
6821
|
+
content: extractXSearchSummary(item),
|
|
6822
|
+
raw_item: item
|
|
6823
|
+
};
|
|
6824
|
+
}
|
|
6825
|
+
return mapMessageOtherParts(message, "openai", "xai");
|
|
6826
|
+
});
|
|
6827
|
+
const citations = response.output.flatMap((item) => {
|
|
6828
|
+
if (item.type !== "message") return [];
|
|
6829
|
+
return item.content.flatMap(
|
|
6830
|
+
(part) => part.type === "output_text" && Array.isArray(part.annotations) ? part.annotations : []
|
|
6831
|
+
);
|
|
6832
|
+
});
|
|
6833
|
+
return {
|
|
6834
|
+
...completion,
|
|
6835
|
+
messages,
|
|
6836
|
+
provider_meta: {
|
|
6837
|
+
...completion.provider_meta,
|
|
6838
|
+
...citations.length ? { citations } : {}
|
|
6839
|
+
}
|
|
6840
|
+
};
|
|
6841
|
+
};
|
|
6842
|
+
var isXSearchCall = (value) => Boolean(
|
|
6843
|
+
value && typeof value === "object" && value.type === "x_search_call"
|
|
6844
|
+
);
|
|
6845
|
+
var extractXSearchSummary = (item) => {
|
|
6846
|
+
const status = typeof item.status === "string" ? item.status : "completed";
|
|
6847
|
+
const parts = [`XSearch status=${status}`];
|
|
6848
|
+
const queries = Array.isArray(item.action?.queries) ? item.action.queries.filter(
|
|
6849
|
+
(value) => typeof value === "string" && value.length > 0
|
|
6850
|
+
) : [];
|
|
6851
|
+
if (queries.length) parts.push(`queries=${queries.join(" | ")}`);
|
|
6852
|
+
if (Array.isArray(item.action?.sources)) {
|
|
6853
|
+
parts.push(`sources=${item.action.sources.length}`);
|
|
6854
|
+
}
|
|
6855
|
+
return parts.join(" | ");
|
|
6856
|
+
};
|
|
6857
|
+
|
|
6858
|
+
// src/llm/xai/chat.ts
|
|
6859
|
+
var PROVIDER_NAME7 = "xai";
|
|
6860
|
+
var XAI_BASE_URL = "https://api.x.ai/v1";
|
|
6861
|
+
var DEFAULT_REQUEST_TIMEOUT_MS2 = 60 * 60 * 1e3;
|
|
6862
|
+
var ChatXai = class {
|
|
6863
|
+
provider = PROVIDER_NAME7;
|
|
6864
|
+
model;
|
|
6865
|
+
classifyFailure = (error) => classifyOpenAiCompatibleFailure(PROVIDER_NAME7, error);
|
|
6866
|
+
client;
|
|
6867
|
+
defaultReasoningEffort;
|
|
6868
|
+
reasoningLevelMeta;
|
|
6869
|
+
debugInvokeSeq = 0;
|
|
6870
|
+
lastDebugRequestPayload = null;
|
|
6871
|
+
constructor(options = {}) {
|
|
6872
|
+
this.client = options.client ?? new OpenAI4({
|
|
6873
|
+
baseURL: XAI_BASE_URL,
|
|
6874
|
+
timeout: DEFAULT_REQUEST_TIMEOUT_MS2,
|
|
6875
|
+
...options.clientOptions ?? {},
|
|
6876
|
+
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
6877
|
+
});
|
|
6878
|
+
this.model = options.model ?? XAI_DEFAULT_MODEL;
|
|
6879
|
+
this.defaultReasoningEffort = options.reasoningEffort ?? XAI_DEFAULT_REASONING_EFFORT;
|
|
6880
|
+
this.reasoningLevelMeta = {
|
|
6881
|
+
requested: options.reasoningLevelRequested,
|
|
6882
|
+
applied: options.reasoningLevelApplied,
|
|
6883
|
+
fallbackApplied: options.reasoningFallbackApplied
|
|
6884
|
+
};
|
|
6885
|
+
}
|
|
6886
|
+
async ainvoke(input, context) {
|
|
6887
|
+
const {
|
|
6888
|
+
messages,
|
|
6889
|
+
tools: toolDefs,
|
|
6890
|
+
toolChoice,
|
|
6891
|
+
options,
|
|
6892
|
+
model,
|
|
6893
|
+
signal
|
|
6894
|
+
} = input;
|
|
6895
|
+
const inputItems = toXaiResponsesInput(messages);
|
|
6896
|
+
const instructions = extractInstructions(messages);
|
|
6897
|
+
const tools = toXaiResponsesTools(toolDefs);
|
|
6898
|
+
const tool_choice = toXaiResponsesToolChoice(toolChoice);
|
|
6899
|
+
const { reasoningEffort, ...rest } = options ?? {};
|
|
6900
|
+
const request = {
|
|
6901
|
+
model: model ?? this.model,
|
|
6902
|
+
input: inputItems,
|
|
6903
|
+
...rest,
|
|
6904
|
+
...tools ? { tools } : {},
|
|
6905
|
+
...tool_choice ? { tool_choice } : {},
|
|
6906
|
+
store: rest.store ?? false,
|
|
6907
|
+
reasoning: {
|
|
6908
|
+
effort: reasoningEffort ?? this.defaultReasoningEffort
|
|
6909
|
+
}
|
|
6910
|
+
};
|
|
6911
|
+
if (instructions) {
|
|
6912
|
+
request.instructions = instructions;
|
|
6913
|
+
}
|
|
6914
|
+
const includeSet = new Set(request.include ?? []);
|
|
6915
|
+
includeSet.add("reasoning.encrypted_content");
|
|
6916
|
+
if (tools?.some((tool) => tool.type === "web_search")) {
|
|
6917
|
+
includeSet.add("web_search_call.action.sources");
|
|
6918
|
+
}
|
|
6919
|
+
request.include = Array.from(includeSet);
|
|
6920
|
+
if (context?.sessionKey && !request.prompt_cache_key) {
|
|
6921
|
+
request.prompt_cache_key = context.sessionKey;
|
|
6922
|
+
}
|
|
6923
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
6924
|
+
await this.debugRequestIfEnabled(request, debugSeq);
|
|
6925
|
+
const response = await invokeOpenAiHttp(this.client, request, signal);
|
|
6926
|
+
await this.debugResponseIfEnabled(response, debugSeq);
|
|
6927
|
+
return toXaiChatInvokeCompletion(response, {
|
|
6928
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
6929
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
6930
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
6931
|
+
});
|
|
6932
|
+
}
|
|
6933
|
+
nextDebugInvokeSeq() {
|
|
6934
|
+
this.debugInvokeSeq += 1;
|
|
6935
|
+
return this.debugInvokeSeq;
|
|
6936
|
+
}
|
|
6937
|
+
async debugRequestIfEnabled(request, seq) {
|
|
6938
|
+
const settings = getProviderLogSettings();
|
|
6939
|
+
if (!settings.enabled && !settings.dumpDir) return;
|
|
6940
|
+
const payload = safeJsonStringify(request);
|
|
6941
|
+
const hash = createHash5("sha256").update(payload).digest("hex").slice(0, 16);
|
|
6942
|
+
const previous = this.lastDebugRequestPayload;
|
|
6943
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6944
|
+
const ratio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
6945
|
+
if (settings.enabled) {
|
|
6946
|
+
console.error(
|
|
6947
|
+
`[xai.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${ratio}%`
|
|
6948
|
+
);
|
|
6949
|
+
}
|
|
6950
|
+
if (settings.dumpDir) {
|
|
6951
|
+
try {
|
|
6952
|
+
await writeProviderLogDump(
|
|
6953
|
+
settings,
|
|
6954
|
+
PROVIDER_NAME7,
|
|
6955
|
+
seq,
|
|
6956
|
+
"request",
|
|
6957
|
+
request
|
|
6958
|
+
);
|
|
6959
|
+
} catch (error) {
|
|
6960
|
+
if (settings.enabled) {
|
|
6961
|
+
console.error(
|
|
6962
|
+
`[xai.request] dump_failed seq=${seq} error=${String(error)}`
|
|
6963
|
+
);
|
|
6964
|
+
}
|
|
6965
|
+
}
|
|
6966
|
+
}
|
|
6967
|
+
this.lastDebugRequestPayload = payload;
|
|
6968
|
+
}
|
|
6969
|
+
async debugResponseIfEnabled(response, seq) {
|
|
6970
|
+
const settings = getProviderLogSettings();
|
|
6971
|
+
if (!settings.enabled && !settings.dumpDir) return;
|
|
6972
|
+
if (settings.enabled) {
|
|
6973
|
+
console.error(
|
|
6974
|
+
`[xai.response] seq=${seq} id=${response.id} status=${response.status} items=${response.output.length} tok_in=${response.usage?.input_tokens ?? 0} cached_in=${response.usage?.input_tokens_details?.cached_tokens ?? 0} tok_out=${response.usage?.output_tokens ?? 0}`
|
|
6975
|
+
);
|
|
6976
|
+
}
|
|
6977
|
+
if (settings.dumpDir) {
|
|
6978
|
+
try {
|
|
6979
|
+
await writeProviderLogDump(
|
|
6980
|
+
settings,
|
|
6981
|
+
PROVIDER_NAME7,
|
|
6982
|
+
seq,
|
|
6983
|
+
"response",
|
|
6984
|
+
response
|
|
6985
|
+
);
|
|
6986
|
+
} catch (error) {
|
|
6987
|
+
if (settings.enabled) {
|
|
6988
|
+
console.error(
|
|
6989
|
+
`[xai.response] dump_failed seq=${seq} error=${String(error)}`
|
|
6990
|
+
);
|
|
6991
|
+
}
|
|
6992
|
+
}
|
|
6993
|
+
}
|
|
6994
|
+
}
|
|
6995
|
+
};
|
|
6996
|
+
|
|
5560
6997
|
// src/llm/zai/chat.ts
|
|
5561
|
-
import { createHash as
|
|
6998
|
+
import { createHash as createHash6 } from "crypto";
|
|
6999
|
+
|
|
7000
|
+
// src/llm/zai/failure.ts
|
|
7001
|
+
var PROVIDER_NAME8 = "zai";
|
|
7002
|
+
var readBusinessCode = (error) => {
|
|
7003
|
+
const record = asRecord(error);
|
|
7004
|
+
const body = asRecord(record?.body);
|
|
7005
|
+
const nested = asRecord(body?.error) ?? body;
|
|
7006
|
+
const raw = nested?.code ?? record?.code;
|
|
7007
|
+
const parsed = typeof raw === "number" ? raw : Number(raw);
|
|
7008
|
+
return Number.isFinite(parsed) ? Math.trunc(parsed) : void 0;
|
|
7009
|
+
};
|
|
7010
|
+
var classifyZaiFailure = (error) => {
|
|
7011
|
+
if (isAbortLikeProviderError(error)) {
|
|
7012
|
+
return buildProviderFailure(PROVIDER_NAME8, "cancelled");
|
|
7013
|
+
}
|
|
7014
|
+
const extracted = extractProviderError(error);
|
|
7015
|
+
const status = extracted.status;
|
|
7016
|
+
const code = readBusinessCode(error);
|
|
7017
|
+
if (status === 401)
|
|
7018
|
+
return buildProviderFailure(PROVIDER_NAME8, "auth", { status });
|
|
7019
|
+
if (status === 403) {
|
|
7020
|
+
return buildProviderFailure(PROVIDER_NAME8, "permission", { status });
|
|
7021
|
+
}
|
|
7022
|
+
if (isValidationStatus(status)) {
|
|
7023
|
+
return buildProviderFailure(PROVIDER_NAME8, "validation", { status });
|
|
7024
|
+
}
|
|
7025
|
+
if (code === 1302) {
|
|
7026
|
+
return buildProviderFailure(PROVIDER_NAME8, "rate_limit", {
|
|
7027
|
+
status,
|
|
7028
|
+
retryable: true
|
|
7029
|
+
});
|
|
7030
|
+
}
|
|
7031
|
+
if (code === 1305) {
|
|
7032
|
+
return buildProviderFailure(PROVIDER_NAME8, "overloaded", {
|
|
7033
|
+
status,
|
|
7034
|
+
retryable: true
|
|
7035
|
+
});
|
|
7036
|
+
}
|
|
7037
|
+
if (code === 1234) {
|
|
7038
|
+
return buildProviderFailure(PROVIDER_NAME8, "network", {
|
|
7039
|
+
status,
|
|
7040
|
+
retryable: true
|
|
7041
|
+
});
|
|
7042
|
+
}
|
|
7043
|
+
if (code === 1113 || code === 1308 || code === 1309 || code === 1310 || code !== void 0 && code >= 1316 && code <= 1321) {
|
|
7044
|
+
return buildProviderFailure(PROVIDER_NAME8, "hard_quota", { status });
|
|
7045
|
+
}
|
|
7046
|
+
if (code !== void 0 && code >= 1311 && code <= 1315) {
|
|
7047
|
+
return buildProviderFailure(PROVIDER_NAME8, "permission", { status });
|
|
7048
|
+
}
|
|
7049
|
+
if (status === 408 || status === 504) {
|
|
7050
|
+
return buildProviderFailure(PROVIDER_NAME8, "timeout", {
|
|
7051
|
+
status,
|
|
7052
|
+
retryable: true
|
|
7053
|
+
});
|
|
7054
|
+
}
|
|
7055
|
+
if (status === 503) {
|
|
7056
|
+
return buildProviderFailure(PROVIDER_NAME8, "overloaded", {
|
|
7057
|
+
status,
|
|
7058
|
+
retryable: true
|
|
7059
|
+
});
|
|
7060
|
+
}
|
|
7061
|
+
if (status !== void 0 && status >= 500) {
|
|
7062
|
+
return buildProviderFailure(PROVIDER_NAME8, "provider", {
|
|
7063
|
+
status,
|
|
7064
|
+
retryable: true
|
|
7065
|
+
});
|
|
7066
|
+
}
|
|
7067
|
+
if (status === 429) {
|
|
7068
|
+
return buildProviderFailure(PROVIDER_NAME8, "provider", { status });
|
|
7069
|
+
}
|
|
7070
|
+
return classifyTransportFailure(PROVIDER_NAME8, error) ?? buildProviderFailure(PROVIDER_NAME8, "provider");
|
|
7071
|
+
};
|
|
5562
7072
|
|
|
5563
7073
|
// src/llm/zai/serializer.ts
|
|
5564
7074
|
var stringifyContentForZai = (content) => stringifyContent(content, { mode: "display", joiner: "" });
|
|
@@ -5701,7 +7211,7 @@ function toZaiChatInvokeCompletion(accumulator, meta) {
|
|
|
5701
7211
|
}
|
|
5702
7212
|
});
|
|
5703
7213
|
}
|
|
5704
|
-
const toolCalls = accumulator.toolCalls.filter((call) => call.name || call.arguments || call.id).map(
|
|
7214
|
+
const toolCalls = accumulator.toolCalls.filter((call) => call.name || call.arguments || call.id).map(toToolCall2);
|
|
5705
7215
|
if (accumulator.content || toolCalls.length) {
|
|
5706
7216
|
messages.push({
|
|
5707
7217
|
role: "assistant",
|
|
@@ -5738,7 +7248,7 @@ var toZaiReplayToolCalls = (toolCalls) => {
|
|
|
5738
7248
|
}
|
|
5739
7249
|
}));
|
|
5740
7250
|
};
|
|
5741
|
-
var
|
|
7251
|
+
var toToolCall2 = (call) => ({
|
|
5742
7252
|
id: call.id,
|
|
5743
7253
|
type: "function",
|
|
5744
7254
|
function: {
|
|
@@ -5751,7 +7261,7 @@ var toToolCall = (call) => ({
|
|
|
5751
7261
|
raw_chunk_count: call.raw_chunk_count
|
|
5752
7262
|
}
|
|
5753
7263
|
});
|
|
5754
|
-
var
|
|
7264
|
+
var normalizeNumber2 = (value) => {
|
|
5755
7265
|
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
5756
7266
|
return 0;
|
|
5757
7267
|
}
|
|
@@ -5762,10 +7272,10 @@ var normalizeZaiUsage = (accumulator) => {
|
|
|
5762
7272
|
if (!usage) {
|
|
5763
7273
|
return null;
|
|
5764
7274
|
}
|
|
5765
|
-
const inputTokens =
|
|
5766
|
-
const outputTokens =
|
|
5767
|
-
const totalTokens = typeof usage.total_tokens === "number" ?
|
|
5768
|
-
const cachedTokens =
|
|
7275
|
+
const inputTokens = normalizeNumber2(usage.prompt_tokens);
|
|
7276
|
+
const outputTokens = normalizeNumber2(usage.completion_tokens);
|
|
7277
|
+
const totalTokens = typeof usage.total_tokens === "number" ? normalizeNumber2(usage.total_tokens) : inputTokens + outputTokens;
|
|
7278
|
+
const cachedTokens = normalizeNumber2(
|
|
5769
7279
|
usage.prompt_tokens_details?.cached_tokens
|
|
5770
7280
|
);
|
|
5771
7281
|
return {
|
|
@@ -5778,6 +7288,16 @@ var normalizeZaiUsage = (accumulator) => {
|
|
|
5778
7288
|
};
|
|
5779
7289
|
|
|
5780
7290
|
// src/llm/zai/transport.ts
|
|
7291
|
+
var ZaiHttpError = class extends Error {
|
|
7292
|
+
status;
|
|
7293
|
+
body;
|
|
7294
|
+
constructor(status, body) {
|
|
7295
|
+
super(`Z.ai provider request failed (${status})`);
|
|
7296
|
+
this.name = "ZaiHttpError";
|
|
7297
|
+
this.status = status;
|
|
7298
|
+
this.body = body;
|
|
7299
|
+
}
|
|
7300
|
+
};
|
|
5781
7301
|
var streamZaiChatCompletion = async ({
|
|
5782
7302
|
apiKey,
|
|
5783
7303
|
baseURL,
|
|
@@ -5873,7 +7393,7 @@ var createZaiRequestSignal = (signal, timeoutMs) => {
|
|
|
5873
7393
|
}
|
|
5874
7394
|
const controller = new AbortController();
|
|
5875
7395
|
let timeout = setTimeout(() => {
|
|
5876
|
-
controller.abort(new
|
|
7396
|
+
controller.abort(new ProviderTimeoutError("Z.ai request timeout"));
|
|
5877
7397
|
}, timeoutMs);
|
|
5878
7398
|
const onAbort = () => {
|
|
5879
7399
|
controller.abort(signal?.reason);
|
|
@@ -5901,9 +7421,15 @@ var toZaiHttpError = async (response) => {
|
|
|
5901
7421
|
} catch {
|
|
5902
7422
|
body = "";
|
|
5903
7423
|
}
|
|
5904
|
-
|
|
5905
|
-
|
|
5906
|
-
|
|
7424
|
+
let parsed = body;
|
|
7425
|
+
if (body) {
|
|
7426
|
+
try {
|
|
7427
|
+
parsed = JSON.parse(body);
|
|
7428
|
+
} catch {
|
|
7429
|
+
parsed = body.slice(0, 500);
|
|
7430
|
+
}
|
|
7431
|
+
}
|
|
7432
|
+
return new ZaiHttpError(response.status, parsed);
|
|
5907
7433
|
};
|
|
5908
7434
|
var throwIfAborted2 = (signal) => {
|
|
5909
7435
|
if (!signal?.aborted) {
|
|
@@ -5938,13 +7464,14 @@ var parseSseDataLine = (line) => {
|
|
|
5938
7464
|
};
|
|
5939
7465
|
|
|
5940
7466
|
// src/llm/zai/chat.ts
|
|
5941
|
-
var
|
|
5942
|
-
var
|
|
7467
|
+
var PROVIDER_NAME9 = "zai";
|
|
7468
|
+
var DEFAULT_BASE_URL2 = "https://api.z.ai/api/paas/v4";
|
|
5943
7469
|
var DEFAULT_REASONING_EFFORT3 = "high";
|
|
5944
|
-
var
|
|
7470
|
+
var DEFAULT_REQUEST_TIMEOUT_MS3 = 20 * 60 * 1e3;
|
|
5945
7471
|
var ChatZai = class {
|
|
5946
|
-
provider =
|
|
7472
|
+
provider = PROVIDER_NAME9;
|
|
5947
7473
|
model;
|
|
7474
|
+
classifyFailure = classifyZaiFailure;
|
|
5948
7475
|
apiKey;
|
|
5949
7476
|
baseURL;
|
|
5950
7477
|
fetchImpl;
|
|
@@ -5955,10 +7482,10 @@ var ChatZai = class {
|
|
|
5955
7482
|
lastDebugRequestPayload = null;
|
|
5956
7483
|
constructor(options = {}) {
|
|
5957
7484
|
this.apiKey = options.apiKey;
|
|
5958
|
-
this.baseURL = (options.baseURL ??
|
|
7485
|
+
this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL2).replace(/\/+$/, "");
|
|
5959
7486
|
this.fetchImpl = options.fetch ?? fetch;
|
|
5960
7487
|
this.model = options.model ?? ZAI_DEFAULT_MODEL;
|
|
5961
|
-
this.timeoutMs = options.timeoutMs ??
|
|
7488
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS3;
|
|
5962
7489
|
this.defaultReasoningEffort = options.reasoningEffort === void 0 ? DEFAULT_REASONING_EFFORT3 : options.reasoningEffort;
|
|
5963
7490
|
this.reasoningLevelMeta = {
|
|
5964
7491
|
requested: options.reasoningLevelRequested,
|
|
@@ -6029,8 +7556,8 @@ var ChatZai = class {
|
|
|
6029
7556
|
return;
|
|
6030
7557
|
}
|
|
6031
7558
|
const payload = safeJsonStringify(request);
|
|
6032
|
-
const hash =
|
|
6033
|
-
const toolsHash =
|
|
7559
|
+
const hash = createHash6("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7560
|
+
const toolsHash = createHash6("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
6034
7561
|
const previous = this.lastDebugRequestPayload;
|
|
6035
7562
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6036
7563
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -6043,7 +7570,7 @@ var ChatZai = class {
|
|
|
6043
7570
|
try {
|
|
6044
7571
|
await writeProviderLogDump(
|
|
6045
7572
|
settings,
|
|
6046
|
-
|
|
7573
|
+
PROVIDER_NAME9,
|
|
6047
7574
|
seq,
|
|
6048
7575
|
"request",
|
|
6049
7576
|
request
|
|
@@ -6075,7 +7602,7 @@ var ChatZai = class {
|
|
|
6075
7602
|
try {
|
|
6076
7603
|
await writeProviderLogDump(
|
|
6077
7604
|
settings,
|
|
6078
|
-
|
|
7605
|
+
PROVIDER_NAME9,
|
|
6079
7606
|
seq,
|
|
6080
7607
|
"response",
|
|
6081
7608
|
response.accumulated
|
|
@@ -6095,13 +7622,9 @@ var ChatZai = class {
|
|
|
6095
7622
|
import path2 from "path";
|
|
6096
7623
|
import { fileURLToPath } from "url";
|
|
6097
7624
|
var resolvePromptPath = () => {
|
|
6098
|
-
|
|
6099
|
-
|
|
6100
|
-
|
|
6101
|
-
if (typeof import.meta !== "undefined" && import.meta.url) {
|
|
6102
|
-
return fileURLToPath(new URL("../prompts/system.md", import.meta.url));
|
|
6103
|
-
}
|
|
6104
|
-
return path2.resolve("prompts/system.md");
|
|
7625
|
+
const moduleLocation = import.meta.url;
|
|
7626
|
+
const moduleFilename = moduleLocation.startsWith("file:") ? fileURLToPath(moduleLocation) : moduleLocation;
|
|
7627
|
+
return path2.resolve(path2.dirname(moduleFilename), "../prompts/system.md");
|
|
6105
7628
|
};
|
|
6106
7629
|
var promptPath = resolvePromptPath();
|
|
6107
7630
|
var getDefaultSystemPromptPath = () => promptPath;
|
|
@@ -6170,16 +7693,24 @@ export {
|
|
|
6170
7693
|
ANTHROPIC_MODELS,
|
|
6171
7694
|
Agent,
|
|
6172
7695
|
ChatAnthropic,
|
|
7696
|
+
ChatMoonshot,
|
|
6173
7697
|
ChatOpenAI,
|
|
6174
7698
|
ChatOpenRouter,
|
|
7699
|
+
ChatXai,
|
|
6175
7700
|
ChatZai,
|
|
6176
7701
|
DEFAULT_MODEL_REGISTRY,
|
|
6177
7702
|
GOOGLE_MODELS,
|
|
7703
|
+
MOONSHOT_DEFAULT_MODEL,
|
|
7704
|
+
MOONSHOT_MODELS,
|
|
6178
7705
|
OPENAI_DEFAULT_MODEL,
|
|
6179
7706
|
OPENAI_DEFAULT_REASONING_EFFORT,
|
|
6180
7707
|
OPENAI_MODELS,
|
|
7708
|
+
ProviderFailureError,
|
|
6181
7709
|
TaskComplete,
|
|
6182
7710
|
ToolOutputCacheService,
|
|
7711
|
+
XAI_DEFAULT_MODEL,
|
|
7712
|
+
XAI_DEFAULT_REASONING_EFFORT,
|
|
7713
|
+
XAI_MODELS,
|
|
6183
7714
|
ZAI_DEFAULT_MODEL,
|
|
6184
7715
|
ZAI_MODELS,
|
|
6185
7716
|
ZAI_REASONING_EFFORT_MODELS,
|
|
@@ -6187,6 +7718,7 @@ export {
|
|
|
6187
7718
|
createModelRegistry,
|
|
6188
7719
|
defineTool,
|
|
6189
7720
|
getDefaultSystemPromptPath,
|
|
7721
|
+
isProviderFailureError,
|
|
6190
7722
|
isUsableModelSpec,
|
|
6191
7723
|
listModels,
|
|
6192
7724
|
registerModels,
|