@codelia/core 0.1.75 → 0.1.77
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.cjs
CHANGED
|
@@ -34,16 +34,24 @@ __export(index_exports, {
|
|
|
34
34
|
ANTHROPIC_MODELS: () => ANTHROPIC_MODELS,
|
|
35
35
|
Agent: () => Agent,
|
|
36
36
|
ChatAnthropic: () => ChatAnthropic,
|
|
37
|
+
ChatMoonshot: () => ChatMoonshot,
|
|
37
38
|
ChatOpenAI: () => ChatOpenAI,
|
|
38
39
|
ChatOpenRouter: () => ChatOpenRouter,
|
|
40
|
+
ChatXai: () => ChatXai,
|
|
39
41
|
ChatZai: () => ChatZai,
|
|
40
42
|
DEFAULT_MODEL_REGISTRY: () => DEFAULT_MODEL_REGISTRY,
|
|
41
43
|
GOOGLE_MODELS: () => GOOGLE_MODELS,
|
|
44
|
+
MOONSHOT_DEFAULT_MODEL: () => MOONSHOT_DEFAULT_MODEL,
|
|
45
|
+
MOONSHOT_MODELS: () => MOONSHOT_MODELS,
|
|
42
46
|
OPENAI_DEFAULT_MODEL: () => OPENAI_DEFAULT_MODEL,
|
|
43
47
|
OPENAI_DEFAULT_REASONING_EFFORT: () => OPENAI_DEFAULT_REASONING_EFFORT,
|
|
44
48
|
OPENAI_MODELS: () => OPENAI_MODELS,
|
|
49
|
+
ProviderFailureError: () => ProviderFailureError,
|
|
45
50
|
TaskComplete: () => TaskComplete,
|
|
46
51
|
ToolOutputCacheService: () => ToolOutputCacheService,
|
|
52
|
+
XAI_DEFAULT_MODEL: () => XAI_DEFAULT_MODEL,
|
|
53
|
+
XAI_DEFAULT_REASONING_EFFORT: () => XAI_DEFAULT_REASONING_EFFORT,
|
|
54
|
+
XAI_MODELS: () => XAI_MODELS,
|
|
47
55
|
ZAI_DEFAULT_MODEL: () => ZAI_DEFAULT_MODEL,
|
|
48
56
|
ZAI_MODELS: () => ZAI_MODELS,
|
|
49
57
|
ZAI_REASONING_EFFORT_MODELS: () => ZAI_REASONING_EFFORT_MODELS,
|
|
@@ -51,6 +59,7 @@ __export(index_exports, {
|
|
|
51
59
|
createModelRegistry: () => createModelRegistry,
|
|
52
60
|
defineTool: () => defineTool,
|
|
53
61
|
getDefaultSystemPromptPath: () => getDefaultSystemPromptPath,
|
|
62
|
+
isProviderFailureError: () => isProviderFailureError,
|
|
54
63
|
isUsableModelSpec: () => isUsableModelSpec,
|
|
55
64
|
listModels: () => listModels,
|
|
56
65
|
registerModels: () => registerModels,
|
|
@@ -70,7 +79,6 @@ var OPENAI_DEFAULT_MODEL = "gpt-5.6";
|
|
|
70
79
|
var OPENAI_DEFAULT_REASONING_EFFORT = "medium";
|
|
71
80
|
var GPT_5_6_CONTEXT_WINDOW = 105e4;
|
|
72
81
|
var GPT_5_6_CAPPED_INPUT_TOKENS = 27e4;
|
|
73
|
-
var GPT_5_6_FULL_INPUT_TOKENS = 922e3;
|
|
74
82
|
var GPT_5_6_MAX_OUTPUT_TOKENS = 128e3;
|
|
75
83
|
var GPT_5_4_CAPPED_INPUT_TOKENS = 272e3;
|
|
76
84
|
var GPT_5_6_PROVIDER_MODELS = [
|
|
@@ -79,32 +87,16 @@ var GPT_5_6_PROVIDER_MODELS = [
|
|
|
79
87
|
"gpt-5.6-terra",
|
|
80
88
|
"gpt-5.6-luna"
|
|
81
89
|
];
|
|
82
|
-
var
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
},
|
|
91
|
-
{
|
|
92
|
-
id: `${providerModelId}-1M`,
|
|
93
|
-
provider: "openai",
|
|
94
|
-
providerModelId,
|
|
95
|
-
aliases: [`${providerModelId}-1m`, `${providerModelId}-full`],
|
|
96
|
-
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
97
|
-
maxInputTokens: GPT_5_6_FULL_INPUT_TOKENS,
|
|
98
|
-
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS
|
|
99
|
-
}
|
|
100
|
-
];
|
|
90
|
+
var buildGpt56Model = (id) => ({
|
|
91
|
+
id,
|
|
92
|
+
provider: "openai",
|
|
93
|
+
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
94
|
+
maxInputTokens: GPT_5_6_CAPPED_INPUT_TOKENS,
|
|
95
|
+
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS,
|
|
96
|
+
supportsFast: true
|
|
97
|
+
});
|
|
101
98
|
var OPENAI_MODELS = [
|
|
102
|
-
|
|
103
|
-
id: OPENAI_DEFAULT_MODEL,
|
|
104
|
-
provider: "openai",
|
|
105
|
-
aliases: ["default"]
|
|
106
|
-
},
|
|
107
|
-
...GPT_5_6_PROVIDER_MODELS.flatMap(buildGpt56Models),
|
|
99
|
+
...GPT_5_6_PROVIDER_MODELS.map(buildGpt56Model),
|
|
108
100
|
{
|
|
109
101
|
id: "gpt-5.5",
|
|
110
102
|
provider: "openai",
|
|
@@ -280,6 +272,9 @@ import_config.configRegistry.registerDefaults({
|
|
|
280
272
|
}
|
|
281
273
|
});
|
|
282
274
|
|
|
275
|
+
// src/agent/agent.ts
|
|
276
|
+
var import_node_perf_hooks = require("perf_hooks");
|
|
277
|
+
|
|
283
278
|
// src/content/stringify.ts
|
|
284
279
|
var stringifyUnknown = (value) => {
|
|
285
280
|
try {
|
|
@@ -328,9 +323,6 @@ var stringifyContent = (content, options = {}) => {
|
|
|
328
323
|
return stringifyContentParts(content, options);
|
|
329
324
|
};
|
|
330
325
|
|
|
331
|
-
// src/agent/agent.ts
|
|
332
|
-
var import_node_perf_hooks = require("perf_hooks");
|
|
333
|
-
|
|
334
326
|
// src/history/store.ts
|
|
335
327
|
var MessageHistoryAdapter = class {
|
|
336
328
|
messages = [];
|
|
@@ -370,6 +362,429 @@ var MessageHistoryAdapter = class {
|
|
|
370
362
|
}
|
|
371
363
|
};
|
|
372
364
|
|
|
365
|
+
// src/llm/failures.ts
|
|
366
|
+
var ProviderFailureError = class extends Error {
|
|
367
|
+
failure;
|
|
368
|
+
attempts;
|
|
369
|
+
maxAttempts;
|
|
370
|
+
constructor(failure, options = {}) {
|
|
371
|
+
super(failure.safeMessage, { cause: options.cause });
|
|
372
|
+
this.name = "ProviderFailureError";
|
|
373
|
+
this.failure = failure;
|
|
374
|
+
this.attempts = options.attempts ?? 1;
|
|
375
|
+
this.maxAttempts = options.maxAttempts ?? this.attempts;
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
var ProviderTimeoutError = class extends Error {
|
|
379
|
+
constructor(message) {
|
|
380
|
+
super(message);
|
|
381
|
+
this.name = "ProviderTimeoutError";
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
var isProviderFailureError = (error) => error instanceof ProviderFailureError;
|
|
385
|
+
var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
386
|
+
var readString = (record, key) => {
|
|
387
|
+
const value = record?.[key];
|
|
388
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
389
|
+
};
|
|
390
|
+
var readStatus = (error) => {
|
|
391
|
+
const value = asRecord(error)?.status;
|
|
392
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : void 0;
|
|
393
|
+
};
|
|
394
|
+
var readHeader = (headers, name) => {
|
|
395
|
+
if (headers instanceof Headers) {
|
|
396
|
+
return headers.get(name);
|
|
397
|
+
}
|
|
398
|
+
const record = asRecord(headers);
|
|
399
|
+
if (!record) return null;
|
|
400
|
+
const direct = record[name] ?? record[name.toLowerCase()];
|
|
401
|
+
return typeof direct === "string" ? direct : null;
|
|
402
|
+
};
|
|
403
|
+
var parsePositiveNumber = (value) => {
|
|
404
|
+
if (!value) return void 0;
|
|
405
|
+
const parsed = Number(value.trim());
|
|
406
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
|
|
407
|
+
};
|
|
408
|
+
var parseRetryAfterMs = (value, nowMs) => {
|
|
409
|
+
const seconds = parsePositiveNumber(value);
|
|
410
|
+
if (seconds !== void 0) return Math.round(seconds * 1e3);
|
|
411
|
+
if (!value) return void 0;
|
|
412
|
+
const retryAtMs = Date.parse(value.trim());
|
|
413
|
+
return Number.isFinite(retryAtMs) ? Math.max(0, Math.round(retryAtMs - nowMs())) : void 0;
|
|
414
|
+
};
|
|
415
|
+
var readRetryAfterMs = (error, nowMs = Date.now) => {
|
|
416
|
+
const headers = asRecord(error)?.headers;
|
|
417
|
+
const directMs = parsePositiveNumber(readHeader(headers, "retry-after-ms"));
|
|
418
|
+
if (directMs !== void 0) return Math.round(directMs);
|
|
419
|
+
return parseRetryAfterMs(readHeader(headers, "retry-after"), nowMs);
|
|
420
|
+
};
|
|
421
|
+
var extractProviderError = (error) => {
|
|
422
|
+
const root = asRecord(error);
|
|
423
|
+
const body = asRecord(root?.error);
|
|
424
|
+
const nested = asRecord(body?.error) ?? body;
|
|
425
|
+
const type = readString(nested, "type") ?? readString(body, "type") ?? readString(root, "type");
|
|
426
|
+
const codeValue = nested?.code ?? body?.code ?? root?.code;
|
|
427
|
+
const code = typeof codeValue === "string" || typeof codeValue === "number" ? codeValue : void 0;
|
|
428
|
+
const message = readString(nested, "message") ?? readString(body, "message") ?? readString(root, "message") ?? (error instanceof Error ? error.message : "Provider request failed");
|
|
429
|
+
return {
|
|
430
|
+
status: readStatus(error),
|
|
431
|
+
type,
|
|
432
|
+
code,
|
|
433
|
+
message,
|
|
434
|
+
retryAfterMs: readRetryAfterMs(error)
|
|
435
|
+
};
|
|
436
|
+
};
|
|
437
|
+
var getRetryHint = (extracted) => extracted.retryAfterMs !== void 0 ? {
|
|
438
|
+
retryAfterMs: extracted.retryAfterMs,
|
|
439
|
+
delaySource: "retry-after"
|
|
440
|
+
} : {};
|
|
441
|
+
var isValidationStatus = (status) => status === 400 || status === 404 || status === 422;
|
|
442
|
+
var isAbortLikeProviderError = (error) => {
|
|
443
|
+
const name = error instanceof Error ? error.name : readString(asRecord(error), "name");
|
|
444
|
+
return name === "AbortError" || name === "APIUserAbortError" || name === "AbortSignal";
|
|
445
|
+
};
|
|
446
|
+
var PROVIDER_LABELS = {
|
|
447
|
+
openai: "OpenAI",
|
|
448
|
+
anthropic: "Anthropic",
|
|
449
|
+
openrouter: "OpenRouter",
|
|
450
|
+
google: "Provider",
|
|
451
|
+
moonshot: "Moonshot",
|
|
452
|
+
zai: "Z.ai",
|
|
453
|
+
xai: "xAI"
|
|
454
|
+
};
|
|
455
|
+
var safeProviderMessage = (provider, kind) => {
|
|
456
|
+
const label = PROVIDER_LABELS[provider];
|
|
457
|
+
switch (kind) {
|
|
458
|
+
case "hard_quota":
|
|
459
|
+
return `${label} quota is exhausted for the interactive retry window. Wait for reset, review billing, or switch provider.`;
|
|
460
|
+
case "rate_limit":
|
|
461
|
+
return `${label} rate limit was reached. Try again shortly or switch provider.`;
|
|
462
|
+
case "overloaded":
|
|
463
|
+
return `${label} is temporarily overloaded. Try again shortly or switch provider.`;
|
|
464
|
+
case "timeout":
|
|
465
|
+
return `${label} request timed out.`;
|
|
466
|
+
case "network":
|
|
467
|
+
return `${label} request failed because of a network error.`;
|
|
468
|
+
case "auth":
|
|
469
|
+
return `${label} authentication failed. Check the configured credentials.`;
|
|
470
|
+
case "permission":
|
|
471
|
+
return `${label} rejected the request because the account lacks permission.`;
|
|
472
|
+
case "validation":
|
|
473
|
+
return `${label} rejected the request as invalid.`;
|
|
474
|
+
case "cancelled":
|
|
475
|
+
return `${label} request was cancelled.`;
|
|
476
|
+
case "provider":
|
|
477
|
+
return `${label} request failed.`;
|
|
478
|
+
}
|
|
479
|
+
};
|
|
480
|
+
var buildProviderFailure = (provider, kind, options = {}) => ({
|
|
481
|
+
provider,
|
|
482
|
+
kind,
|
|
483
|
+
retryable: options.retryable ?? false,
|
|
484
|
+
safeMessage: safeProviderMessage(provider, kind),
|
|
485
|
+
...options.status !== void 0 ? { status: options.status } : {},
|
|
486
|
+
...options.retryAfterMs !== void 0 ? { retryAfterMs: options.retryAfterMs } : {},
|
|
487
|
+
...options.delaySource ? { delaySource: options.delaySource } : {},
|
|
488
|
+
...options.delivery ? { delivery: options.delivery } : {}
|
|
489
|
+
});
|
|
490
|
+
var MAX_SAFE_PROVIDER_MESSAGE_CHARS = 500;
|
|
491
|
+
var createProviderValidationError = (provider, message) => {
|
|
492
|
+
const boundedMessage = message.length <= MAX_SAFE_PROVIDER_MESSAGE_CHARS ? message : `${message.slice(0, MAX_SAFE_PROVIDER_MESSAGE_CHARS - 3)}...`;
|
|
493
|
+
return new ProviderFailureError({
|
|
494
|
+
...buildProviderFailure(provider, "validation"),
|
|
495
|
+
safeMessage: boundedMessage
|
|
496
|
+
});
|
|
497
|
+
};
|
|
498
|
+
var classifyTransportFailure = (provider, error) => {
|
|
499
|
+
const name = error instanceof Error ? error.name : "";
|
|
500
|
+
if (name.includes("Timeout")) {
|
|
501
|
+
return buildProviderFailure(provider, "timeout", { retryable: true });
|
|
502
|
+
}
|
|
503
|
+
if (name.includes("Connection") || error instanceof TypeError) {
|
|
504
|
+
return buildProviderFailure(provider, "network", { retryable: true });
|
|
505
|
+
}
|
|
506
|
+
return null;
|
|
507
|
+
};
|
|
508
|
+
var classifyOpenAiCompatibleFailure = (provider, error) => {
|
|
509
|
+
if (isAbortLikeProviderError(error)) {
|
|
510
|
+
return buildProviderFailure(provider, "cancelled");
|
|
511
|
+
}
|
|
512
|
+
const extracted = extractProviderError(error);
|
|
513
|
+
const status = extracted.status;
|
|
514
|
+
const code = String(extracted.code ?? "").toLowerCase();
|
|
515
|
+
const type = String(extracted.type ?? "").toLowerCase();
|
|
516
|
+
const message = extracted.message.toLowerCase();
|
|
517
|
+
const retryOptions = getRetryHint(extracted);
|
|
518
|
+
if (status === 401) return buildProviderFailure(provider, "auth", { status });
|
|
519
|
+
if (status === 403) {
|
|
520
|
+
return buildProviderFailure(provider, "permission", { status });
|
|
521
|
+
}
|
|
522
|
+
if (isValidationStatus(status)) {
|
|
523
|
+
return buildProviderFailure(provider, "validation", { status });
|
|
524
|
+
}
|
|
525
|
+
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")) {
|
|
526
|
+
return buildProviderFailure(provider, "hard_quota", { status });
|
|
527
|
+
}
|
|
528
|
+
if (status === 408) {
|
|
529
|
+
return buildProviderFailure(provider, "timeout", {
|
|
530
|
+
status,
|
|
531
|
+
retryable: true,
|
|
532
|
+
...retryOptions
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
if (status === 409) {
|
|
536
|
+
return buildProviderFailure(provider, "provider", {
|
|
537
|
+
status,
|
|
538
|
+
retryable: true,
|
|
539
|
+
...retryOptions
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
if (type.includes("provider_overloaded") || type.includes("provider_unavailable") || status === 529 || status === 503) {
|
|
543
|
+
return buildProviderFailure(provider, "overloaded", {
|
|
544
|
+
status,
|
|
545
|
+
retryable: true,
|
|
546
|
+
...retryOptions
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
if (status === 429 || type.includes("rate_limit") || code.includes("rate_limit")) {
|
|
550
|
+
return buildProviderFailure(provider, "rate_limit", {
|
|
551
|
+
status,
|
|
552
|
+
retryable: true,
|
|
553
|
+
...retryOptions
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
if (status !== void 0 && status >= 500) {
|
|
557
|
+
return buildProviderFailure(provider, "provider", {
|
|
558
|
+
status,
|
|
559
|
+
retryable: true,
|
|
560
|
+
...retryOptions
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
return classifyTransportFailure(provider, error) ?? buildProviderFailure(provider, "provider");
|
|
564
|
+
};
|
|
565
|
+
|
|
566
|
+
// src/llm/retry.ts
|
|
567
|
+
var DEFAULT_LLM_RETRY_POLICY = {
|
|
568
|
+
maxRetries: 2,
|
|
569
|
+
baseDelayMs: 1e3,
|
|
570
|
+
maxDelayMs: 6e4,
|
|
571
|
+
maxRetryAfterMs: 6e4,
|
|
572
|
+
retryWindowMs: 20 * 60 * 1e3
|
|
573
|
+
};
|
|
574
|
+
var finitePolicyValue = (value, fallback, minimum) => typeof value === "number" && Number.isFinite(value) && value >= minimum ? Math.trunc(value) : fallback;
|
|
575
|
+
var resolveLlmRetryPolicy = (overrides = {}) => ({
|
|
576
|
+
maxRetries: finitePolicyValue(
|
|
577
|
+
overrides.maxRetries,
|
|
578
|
+
DEFAULT_LLM_RETRY_POLICY.maxRetries,
|
|
579
|
+
0
|
|
580
|
+
),
|
|
581
|
+
baseDelayMs: finitePolicyValue(
|
|
582
|
+
overrides.baseDelayMs,
|
|
583
|
+
DEFAULT_LLM_RETRY_POLICY.baseDelayMs,
|
|
584
|
+
0
|
|
585
|
+
),
|
|
586
|
+
maxDelayMs: finitePolicyValue(
|
|
587
|
+
overrides.maxDelayMs,
|
|
588
|
+
DEFAULT_LLM_RETRY_POLICY.maxDelayMs,
|
|
589
|
+
0
|
|
590
|
+
),
|
|
591
|
+
maxRetryAfterMs: finitePolicyValue(
|
|
592
|
+
overrides.maxRetryAfterMs,
|
|
593
|
+
DEFAULT_LLM_RETRY_POLICY.maxRetryAfterMs,
|
|
594
|
+
0
|
|
595
|
+
),
|
|
596
|
+
retryWindowMs: finitePolicyValue(
|
|
597
|
+
overrides.retryWindowMs,
|
|
598
|
+
DEFAULT_LLM_RETRY_POLICY.retryWindowMs,
|
|
599
|
+
1
|
|
600
|
+
)
|
|
601
|
+
});
|
|
602
|
+
var createAbortError = () => {
|
|
603
|
+
const error = new Error("Operation aborted");
|
|
604
|
+
error.name = "AbortError";
|
|
605
|
+
return error;
|
|
606
|
+
};
|
|
607
|
+
var defaultSleep = (delayMs, signal) => new Promise((resolve, reject) => {
|
|
608
|
+
if (signal?.aborted) {
|
|
609
|
+
reject(createAbortError());
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
let timeout = setTimeout(
|
|
613
|
+
() => {
|
|
614
|
+
timeout = void 0;
|
|
615
|
+
signal?.removeEventListener("abort", onAbort);
|
|
616
|
+
resolve();
|
|
617
|
+
},
|
|
618
|
+
Math.max(0, delayMs)
|
|
619
|
+
);
|
|
620
|
+
const onAbort = () => {
|
|
621
|
+
if (timeout) {
|
|
622
|
+
clearTimeout(timeout);
|
|
623
|
+
timeout = void 0;
|
|
624
|
+
}
|
|
625
|
+
signal?.removeEventListener("abort", onAbort);
|
|
626
|
+
reject(createAbortError());
|
|
627
|
+
};
|
|
628
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
629
|
+
});
|
|
630
|
+
var createRetryWindowSignal = (parent, windowMs) => {
|
|
631
|
+
const controller = new AbortController();
|
|
632
|
+
let expired = false;
|
|
633
|
+
const onParentAbort = () => controller.abort(parent?.reason);
|
|
634
|
+
if (parent?.aborted) {
|
|
635
|
+
onParentAbort();
|
|
636
|
+
} else {
|
|
637
|
+
parent?.addEventListener("abort", onParentAbort, { once: true });
|
|
638
|
+
}
|
|
639
|
+
const timeout = setTimeout(() => {
|
|
640
|
+
expired = true;
|
|
641
|
+
controller.abort(new Error("LLM retry window elapsed"));
|
|
642
|
+
}, windowMs);
|
|
643
|
+
return {
|
|
644
|
+
signal: controller.signal,
|
|
645
|
+
didExpire: () => expired,
|
|
646
|
+
cleanup: () => {
|
|
647
|
+
clearTimeout(timeout);
|
|
648
|
+
parent?.removeEventListener("abort", onParentAbort);
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
};
|
|
652
|
+
var toClassifiedFailure = (error, classifyFailure) => {
|
|
653
|
+
if (isProviderFailureError(error)) return error.failure;
|
|
654
|
+
return classifyFailure?.(error) ?? null;
|
|
655
|
+
};
|
|
656
|
+
var RETRY_STOP_SUFFIXES = {
|
|
657
|
+
retry_exhausted: " Automatic retry attempts were exhausted.",
|
|
658
|
+
retry_after_too_long: " The provider requested a wait longer than Codelia's automatic retry limit.",
|
|
659
|
+
retry_window_elapsed: " The automatic retry window elapsed before another attempt could start."
|
|
660
|
+
};
|
|
661
|
+
var withFinalMessage = (failure, reason) => {
|
|
662
|
+
return {
|
|
663
|
+
...failure,
|
|
664
|
+
retryable: false,
|
|
665
|
+
safeMessage: `${failure.safeMessage}${RETRY_STOP_SUFFIXES[reason]}`
|
|
666
|
+
};
|
|
667
|
+
};
|
|
668
|
+
var createTerminalProviderError = (options) => new ProviderFailureError(
|
|
669
|
+
options.reason ? withFinalMessage(options.failure, options.reason) : options.failure,
|
|
670
|
+
{
|
|
671
|
+
attempts: options.attempt,
|
|
672
|
+
maxAttempts: options.maxAttempts,
|
|
673
|
+
...options.cause !== void 0 ? { cause: options.cause } : {}
|
|
674
|
+
}
|
|
675
|
+
);
|
|
676
|
+
var calculateBackoffMs = (attempt, policy, random) => {
|
|
677
|
+
const exponential = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);
|
|
678
|
+
const jittered = exponential * (0.5 + Math.min(1, Math.max(0, random())) * 0.5);
|
|
679
|
+
return Math.min(policy.maxDelayMs, Math.max(0, Math.round(jittered)));
|
|
680
|
+
};
|
|
681
|
+
var planRetry = (options) => {
|
|
682
|
+
const { failure, attempt, maxAttempts, elapsedMs, policy, random } = options;
|
|
683
|
+
if (!failure.retryable) return { type: "stop", failure };
|
|
684
|
+
if (attempt >= maxAttempts) {
|
|
685
|
+
return { type: "stop", failure, reason: "retry_exhausted" };
|
|
686
|
+
}
|
|
687
|
+
if (failure.retryAfterMs !== void 0 && failure.retryAfterMs > policy.maxRetryAfterMs) {
|
|
688
|
+
return { type: "stop", failure, reason: "retry_after_too_long" };
|
|
689
|
+
}
|
|
690
|
+
const delayMs = failure.retryAfterMs ?? calculateBackoffMs(attempt, policy, random);
|
|
691
|
+
if (elapsedMs + delayMs >= policy.retryWindowMs) {
|
|
692
|
+
return { type: "stop", failure, reason: "retry_window_elapsed" };
|
|
693
|
+
}
|
|
694
|
+
return {
|
|
695
|
+
type: "retry",
|
|
696
|
+
delayMs,
|
|
697
|
+
delaySource: failure.delaySource ?? "backoff"
|
|
698
|
+
};
|
|
699
|
+
};
|
|
700
|
+
var toRetryEvent = (failure, options) => ({
|
|
701
|
+
type: "llm.retry",
|
|
702
|
+
provider: failure.provider,
|
|
703
|
+
failure_kind: failure.kind,
|
|
704
|
+
next_attempt: options.nextAttempt,
|
|
705
|
+
max_attempts: options.maxAttempts,
|
|
706
|
+
delay_ms: options.delayMs,
|
|
707
|
+
delay_source: options.delaySource,
|
|
708
|
+
...failure.status !== void 0 ? { status: failure.status } : {}
|
|
709
|
+
});
|
|
710
|
+
async function* invokeWithRetry({
|
|
711
|
+
operation,
|
|
712
|
+
classifyFailure,
|
|
713
|
+
policy,
|
|
714
|
+
signal,
|
|
715
|
+
dependencies = {}
|
|
716
|
+
}) {
|
|
717
|
+
const nowMs = dependencies.nowMs ?? Date.now;
|
|
718
|
+
const random = dependencies.random ?? Math.random;
|
|
719
|
+
const sleep = dependencies.sleep ?? defaultSleep;
|
|
720
|
+
const maxAttempts = Math.max(1, Math.trunc(policy.maxRetries) + 1);
|
|
721
|
+
const startedAt = nowMs();
|
|
722
|
+
const retryWindow = createRetryWindowSignal(signal, policy.retryWindowMs);
|
|
723
|
+
let attempt = 1;
|
|
724
|
+
try {
|
|
725
|
+
while (true) {
|
|
726
|
+
if (signal?.aborted) throw createAbortError();
|
|
727
|
+
try {
|
|
728
|
+
return await operation(signal);
|
|
729
|
+
} catch (error) {
|
|
730
|
+
if (signal?.aborted) throw createAbortError();
|
|
731
|
+
const failure = toClassifiedFailure(error, classifyFailure);
|
|
732
|
+
if (!failure) throw error;
|
|
733
|
+
if (failure.kind === "cancelled") throw createAbortError();
|
|
734
|
+
const decision = planRetry({
|
|
735
|
+
failure,
|
|
736
|
+
attempt,
|
|
737
|
+
maxAttempts,
|
|
738
|
+
elapsedMs: retryWindow.didExpire() ? policy.retryWindowMs : Math.max(0, nowMs() - startedAt),
|
|
739
|
+
policy,
|
|
740
|
+
random
|
|
741
|
+
});
|
|
742
|
+
if (decision.type === "stop") {
|
|
743
|
+
throw createTerminalProviderError({
|
|
744
|
+
failure: decision.failure,
|
|
745
|
+
attempt,
|
|
746
|
+
maxAttempts,
|
|
747
|
+
cause: error,
|
|
748
|
+
...decision.reason ? { reason: decision.reason } : {}
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
yield toRetryEvent(failure, {
|
|
752
|
+
nextAttempt: attempt + 1,
|
|
753
|
+
maxAttempts,
|
|
754
|
+
delayMs: decision.delayMs,
|
|
755
|
+
delaySource: decision.delaySource
|
|
756
|
+
});
|
|
757
|
+
try {
|
|
758
|
+
await sleep(decision.delayMs, retryWindow.signal);
|
|
759
|
+
} catch (sleepError) {
|
|
760
|
+
if (signal?.aborted) throw createAbortError();
|
|
761
|
+
if (retryWindow.didExpire()) {
|
|
762
|
+
throw createTerminalProviderError({
|
|
763
|
+
failure,
|
|
764
|
+
attempt,
|
|
765
|
+
maxAttempts,
|
|
766
|
+
cause: sleepError,
|
|
767
|
+
reason: "retry_window_elapsed"
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
throw sleepError;
|
|
771
|
+
}
|
|
772
|
+
if (retryWindow.didExpire() || Math.max(0, nowMs() - startedAt) >= policy.retryWindowMs) {
|
|
773
|
+
throw createTerminalProviderError({
|
|
774
|
+
failure,
|
|
775
|
+
attempt,
|
|
776
|
+
maxAttempts,
|
|
777
|
+
reason: "retry_window_elapsed"
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
attempt += 1;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
} finally {
|
|
784
|
+
retryWindow.cleanup();
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
373
788
|
// src/llm/openai/history.ts
|
|
374
789
|
var ResponsesHistoryAdapter = class extends MessageHistoryAdapter {
|
|
375
790
|
};
|
|
@@ -389,6 +804,14 @@ var ANTHROPIC_MODELS = [
|
|
|
389
804
|
maxInputTokens: 1e6,
|
|
390
805
|
maxOutputTokens: 128e3
|
|
391
806
|
},
|
|
807
|
+
{
|
|
808
|
+
id: "claude-opus-5",
|
|
809
|
+
provider: "anthropic",
|
|
810
|
+
contextWindow: 1e6,
|
|
811
|
+
maxInputTokens: 1e6,
|
|
812
|
+
maxOutputTokens: 128e3,
|
|
813
|
+
supportsFast: true
|
|
814
|
+
},
|
|
392
815
|
{
|
|
393
816
|
id: "claude-opus-4-8",
|
|
394
817
|
provider: "anthropic",
|
|
@@ -452,6 +875,23 @@ var GOOGLE_MODELS = [
|
|
|
452
875
|
}
|
|
453
876
|
];
|
|
454
877
|
|
|
878
|
+
// src/models/moonshot.ts
|
|
879
|
+
var MOONSHOT_DEFAULT_MODEL = "kimi-k3";
|
|
880
|
+
var MOONSHOT_MODELS = [
|
|
881
|
+
{
|
|
882
|
+
id: MOONSHOT_DEFAULT_MODEL,
|
|
883
|
+
provider: "moonshot",
|
|
884
|
+
aliases: ["default"],
|
|
885
|
+
contextWindow: 1048576,
|
|
886
|
+
maxInputTokens: 1048576,
|
|
887
|
+
maxOutputTokens: 1048576,
|
|
888
|
+
supportsTools: true,
|
|
889
|
+
supportsVision: true,
|
|
890
|
+
supportsReasoning: true,
|
|
891
|
+
supportsJsonSchema: true
|
|
892
|
+
}
|
|
893
|
+
];
|
|
894
|
+
|
|
455
895
|
// src/models/registry.ts
|
|
456
896
|
function createModelRegistry(specs) {
|
|
457
897
|
const registry = {
|
|
@@ -461,7 +901,9 @@ function createModelRegistry(specs) {
|
|
|
461
901
|
anthropic: {},
|
|
462
902
|
openrouter: {},
|
|
463
903
|
google: {},
|
|
464
|
-
|
|
904
|
+
moonshot: {},
|
|
905
|
+
zai: {},
|
|
906
|
+
xai: {}
|
|
465
907
|
}
|
|
466
908
|
};
|
|
467
909
|
registerModels(registry, specs);
|
|
@@ -522,7 +964,9 @@ function cloneAliases(aliasesByProvider) {
|
|
|
522
964
|
anthropic: { ...aliasesByProvider.anthropic },
|
|
523
965
|
openrouter: { ...aliasesByProvider.openrouter },
|
|
524
966
|
google: { ...aliasesByProvider.google },
|
|
525
|
-
|
|
967
|
+
moonshot: { ...aliasesByProvider.moonshot },
|
|
968
|
+
zai: { ...aliasesByProvider.zai },
|
|
969
|
+
xai: { ...aliasesByProvider.xai }
|
|
526
970
|
};
|
|
527
971
|
}
|
|
528
972
|
function applyModelMetadata(registry, index) {
|
|
@@ -531,7 +975,7 @@ function applyModelMetadata(registry, index) {
|
|
|
531
975
|
aliasesByProvider: cloneAliases(registry.aliasesByProvider)
|
|
532
976
|
};
|
|
533
977
|
for (const [providerId, providerModels] of Object.entries(index.models)) {
|
|
534
|
-
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google" && providerId !== "zai") {
|
|
978
|
+
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google" && providerId !== "moonshot" && providerId !== "zai" && providerId !== "xai") {
|
|
535
979
|
continue;
|
|
536
980
|
}
|
|
537
981
|
const provider = providerId;
|
|
@@ -551,6 +995,23 @@ function applyModelMetadata(registry, index) {
|
|
|
551
995
|
return next;
|
|
552
996
|
}
|
|
553
997
|
|
|
998
|
+
// src/models/xai.ts
|
|
999
|
+
var XAI_DEFAULT_MODEL = "grok-4.5";
|
|
1000
|
+
var XAI_DEFAULT_REASONING_EFFORT = "high";
|
|
1001
|
+
var XAI_MODELS = [
|
|
1002
|
+
{
|
|
1003
|
+
id: XAI_DEFAULT_MODEL,
|
|
1004
|
+
provider: "xai",
|
|
1005
|
+
aliases: ["grok-4.5-latest", "grok-build-latest"],
|
|
1006
|
+
contextWindow: 5e5,
|
|
1007
|
+
maxInputTokens: 2e5,
|
|
1008
|
+
supportsTools: true,
|
|
1009
|
+
supportsVision: true,
|
|
1010
|
+
supportsReasoning: true,
|
|
1011
|
+
supportsJsonSchema: true
|
|
1012
|
+
}
|
|
1013
|
+
];
|
|
1014
|
+
|
|
554
1015
|
// src/models/zai.ts
|
|
555
1016
|
var ZAI_DEFAULT_MODEL = "glm-5.2";
|
|
556
1017
|
var ZAI_REASONING_EFFORT_MODELS = /* @__PURE__ */ new Set(["glm-5.2"]);
|
|
@@ -594,7 +1055,9 @@ var DEFAULT_MODEL_REGISTRY = createModelRegistry([
|
|
|
594
1055
|
...OPENAI_MODELS,
|
|
595
1056
|
...ANTHROPIC_MODELS,
|
|
596
1057
|
...GOOGLE_MODELS,
|
|
597
|
-
...
|
|
1058
|
+
...MOONSHOT_MODELS,
|
|
1059
|
+
...ZAI_MODELS,
|
|
1060
|
+
...XAI_MODELS
|
|
598
1061
|
]);
|
|
599
1062
|
|
|
600
1063
|
// src/services/compaction/service.ts
|
|
@@ -959,7 +1422,7 @@ var parseQualifiedModelId = (modelId) => {
|
|
|
959
1422
|
if (!rest) {
|
|
960
1423
|
return null;
|
|
961
1424
|
}
|
|
962
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
1425
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "moonshot" && providerRaw !== "zai" && providerRaw !== "xai") {
|
|
963
1426
|
return null;
|
|
964
1427
|
}
|
|
965
1428
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -1010,6 +1473,7 @@ var contentToText = (content) => {
|
|
|
1010
1473
|
}
|
|
1011
1474
|
}).join("");
|
|
1012
1475
|
};
|
|
1476
|
+
var hasNonTextParts = (content) => Array.isArray(content) && content.some((part) => part.type !== "text");
|
|
1013
1477
|
var estimateTokens = (text) => Math.ceil(Buffer.byteLength(text, "utf8") / APPROX_BYTES_PER_TOKEN);
|
|
1014
1478
|
var shouldBypassImmediateTruncation = (toolName) => toolName === "tool_output_cache" || toolName === "tool_output_cache_grep";
|
|
1015
1479
|
var truncateForContext = (content, maxMessageBytes) => {
|
|
@@ -1042,6 +1506,13 @@ var ToolOutputCacheService = class {
|
|
|
1042
1506
|
if (this.config.enabled === false) return message;
|
|
1043
1507
|
const raw = contentToText(message.content);
|
|
1044
1508
|
const outputRef = await this.persistToolOutput(message, raw);
|
|
1509
|
+
if (hasNonTextParts(message.content)) {
|
|
1510
|
+
return {
|
|
1511
|
+
...message,
|
|
1512
|
+
content: message.content,
|
|
1513
|
+
output_ref: outputRef
|
|
1514
|
+
};
|
|
1515
|
+
}
|
|
1045
1516
|
const truncated = shouldBypassImmediateTruncation(message.tool_name) ? { output: raw, truncated: false } : truncateForContext(
|
|
1046
1517
|
raw,
|
|
1047
1518
|
this.config.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES
|
|
@@ -1142,7 +1613,7 @@ var parseQualifiedModelId2 = (modelId) => {
|
|
|
1142
1613
|
if (!rest) {
|
|
1143
1614
|
return null;
|
|
1144
1615
|
}
|
|
1145
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
1616
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "moonshot" && providerRaw !== "zai" && providerRaw !== "xai") {
|
|
1146
1617
|
return null;
|
|
1147
1618
|
}
|
|
1148
1619
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -1163,6 +1634,7 @@ var TokenUsageService = class {
|
|
|
1163
1634
|
by_model: {}
|
|
1164
1635
|
};
|
|
1165
1636
|
}
|
|
1637
|
+
config;
|
|
1166
1638
|
usageSummary;
|
|
1167
1639
|
lastUsage = null;
|
|
1168
1640
|
updateUsageSummary(usage) {
|
|
@@ -1203,78 +1675,115 @@ var TokenUsageService = class {
|
|
|
1203
1675
|
}
|
|
1204
1676
|
};
|
|
1205
1677
|
|
|
1206
|
-
// src/
|
|
1207
|
-
var
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1678
|
+
// src/agent/model-context.ts
|
|
1679
|
+
var calculateContextLeftPercent = ({
|
|
1680
|
+
usage,
|
|
1681
|
+
modelRegistry,
|
|
1682
|
+
provider,
|
|
1683
|
+
model
|
|
1684
|
+
}) => {
|
|
1685
|
+
if (!usage) {
|
|
1686
|
+
return null;
|
|
1687
|
+
}
|
|
1688
|
+
const usageModelSpec = usage.model ? resolveModelWithQualifiedFallback2(modelRegistry, provider, usage.model) : void 0;
|
|
1689
|
+
const modelSpec = usageModelSpec ?? resolveModelWithQualifiedFallback2(modelRegistry, provider, model);
|
|
1690
|
+
const contextLimit = modelSpec?.maxInputTokens ?? modelSpec?.contextWindow ?? null;
|
|
1691
|
+
if (!contextLimit || contextLimit <= 0) {
|
|
1692
|
+
return null;
|
|
1693
|
+
}
|
|
1694
|
+
const used = usage.total_tokens;
|
|
1695
|
+
if (!Number.isFinite(used) || used <= 0) {
|
|
1696
|
+
return 100;
|
|
1697
|
+
}
|
|
1698
|
+
const leftRatio = 1 - used / contextLimit;
|
|
1699
|
+
const percent = Math.round(leftRatio * 100);
|
|
1700
|
+
return Math.max(0, Math.min(100, percent));
|
|
1701
|
+
};
|
|
1702
|
+
var resolveModelWithQualifiedFallback2 = (modelRegistry, provider, modelId) => {
|
|
1703
|
+
const direct = resolveModel(modelRegistry, modelId, provider);
|
|
1704
|
+
if (direct) return direct;
|
|
1705
|
+
const qualified = parseQualifiedModelId3(modelId);
|
|
1706
|
+
if (!qualified) return resolveModel(modelRegistry, modelId);
|
|
1707
|
+
return resolveModel(modelRegistry, qualified.modelId, qualified.provider) ?? resolveModel(
|
|
1708
|
+
modelRegistry,
|
|
1709
|
+
`${qualified.provider}/${qualified.modelId}`,
|
|
1710
|
+
qualified.provider
|
|
1711
|
+
);
|
|
1712
|
+
};
|
|
1713
|
+
var parseQualifiedModelId3 = (modelId) => {
|
|
1714
|
+
const sep = modelId.indexOf("/");
|
|
1715
|
+
if (sep <= 0 || sep >= modelId.length - 1) {
|
|
1716
|
+
return null;
|
|
1717
|
+
}
|
|
1718
|
+
const providerRaw = modelId.slice(0, sep);
|
|
1719
|
+
const rest = modelId.slice(sep + 1);
|
|
1720
|
+
if (!rest) {
|
|
1721
|
+
return null;
|
|
1213
1722
|
}
|
|
1723
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "moonshot" && providerRaw !== "zai" && providerRaw !== "xai") {
|
|
1724
|
+
return null;
|
|
1725
|
+
}
|
|
1726
|
+
return { provider: providerRaw, modelId: rest };
|
|
1214
1727
|
};
|
|
1215
1728
|
|
|
1216
|
-
// src/agent/
|
|
1217
|
-
var
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
if (result.type === "text") return result.text;
|
|
1222
|
-
if (result.type === "parts") return result.parts;
|
|
1223
|
-
try {
|
|
1224
|
-
return JSON.stringify(result.value);
|
|
1225
|
-
} catch {
|
|
1226
|
-
return String(result.value);
|
|
1729
|
+
// src/agent/model-output.ts
|
|
1730
|
+
var buildHostedSearchSummary = (kind, status, queries, sourcesCount) => {
|
|
1731
|
+
const parts = [`${kind === "x" ? "XSearch" : "WebSearch"} status=${status}`];
|
|
1732
|
+
if (queries.length) {
|
|
1733
|
+
parts.push(`queries=${queries.join(" | ")}`);
|
|
1227
1734
|
}
|
|
1228
|
-
|
|
1735
|
+
if (typeof sourcesCount === "number") {
|
|
1736
|
+
parts.push(`sources=${sourcesCount}`);
|
|
1737
|
+
}
|
|
1738
|
+
return parts.join(" | ");
|
|
1739
|
+
};
|
|
1229
1740
|
var collectModelOutput = (messages) => {
|
|
1230
|
-
const buildWebSearchSummary = (status, queries, sourcesCount) => {
|
|
1231
|
-
const parts = [`WebSearch status=${status}`];
|
|
1232
|
-
if (queries.length) {
|
|
1233
|
-
parts.push(`queries=${queries.join(" | ")}`);
|
|
1234
|
-
}
|
|
1235
|
-
if (typeof sourcesCount === "number") {
|
|
1236
|
-
parts.push(`sources=${sourcesCount}`);
|
|
1237
|
-
}
|
|
1238
|
-
return parts.join(" | ");
|
|
1239
|
-
};
|
|
1240
1741
|
const reasoningTexts = [];
|
|
1241
1742
|
const assistantTexts = [];
|
|
1242
1743
|
const toolCalls = [];
|
|
1243
1744
|
const hostedToolCalls = [];
|
|
1244
|
-
const
|
|
1245
|
-
const
|
|
1246
|
-
|
|
1247
|
-
|
|
1745
|
+
const hostedSearchById = /* @__PURE__ */ new Map();
|
|
1746
|
+
const hostedSearchOrder = [];
|
|
1747
|
+
const anonymousSearchCounter = {
|
|
1748
|
+
web: 0,
|
|
1749
|
+
x: 0
|
|
1750
|
+
};
|
|
1751
|
+
const lastAnonymousSearchId = {
|
|
1752
|
+
web: null,
|
|
1753
|
+
x: null
|
|
1754
|
+
};
|
|
1248
1755
|
for (const message of messages) {
|
|
1249
1756
|
if (message.role === "reasoning") {
|
|
1250
1757
|
const raw = message.raw_item;
|
|
1251
|
-
if (raw && typeof raw === "object" && raw.type === "web_search_call") {
|
|
1758
|
+
if (raw && typeof raw === "object" && (raw.type === "web_search_call" || raw.type === "x_search_call")) {
|
|
1252
1759
|
const record = raw;
|
|
1760
|
+
const kind = record.type === "x_search_call" ? "x" : "web";
|
|
1253
1761
|
const statusRaw = record.status;
|
|
1254
1762
|
const status = typeof statusRaw === "string" ? statusRaw : "completed";
|
|
1255
1763
|
const action = record.action && typeof record.action === "object" ? record.action : null;
|
|
1256
|
-
const queries = Array.isArray(action?.queries) ? action
|
|
1764
|
+
const queries = Array.isArray(action?.queries) ? action.queries.filter(
|
|
1257
1765
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
1258
1766
|
) : [];
|
|
1259
|
-
const sourcesCount = Array.isArray(action?.sources) ? action
|
|
1767
|
+
const sourcesCount = Array.isArray(action?.sources) ? action.sources.length : void 0;
|
|
1260
1768
|
const explicitId = typeof record.id === "string" && record.id.length > 0 ? record.id : null;
|
|
1261
1769
|
let id = explicitId;
|
|
1262
1770
|
const hasSearchContext = queries.length > 0 || typeof sourcesCount === "number";
|
|
1263
1771
|
if (!id) {
|
|
1264
1772
|
if (hasSearchContext || status === "failed") {
|
|
1265
|
-
|
|
1266
|
-
id =
|
|
1773
|
+
anonymousSearchCounter[kind] += 1;
|
|
1774
|
+
id = `${kind === "x" ? "x" : "web"}_search_${anonymousSearchCounter[kind]}`;
|
|
1267
1775
|
if (hasSearchContext) {
|
|
1268
|
-
|
|
1776
|
+
lastAnonymousSearchId[kind] = id;
|
|
1269
1777
|
}
|
|
1270
|
-
} else if (
|
|
1271
|
-
id =
|
|
1778
|
+
} else if (lastAnonymousSearchId[kind]) {
|
|
1779
|
+
id = lastAnonymousSearchId[kind];
|
|
1272
1780
|
}
|
|
1273
1781
|
}
|
|
1274
1782
|
if (!id) {
|
|
1275
1783
|
continue;
|
|
1276
1784
|
}
|
|
1277
|
-
const
|
|
1785
|
+
const aggregateKey = `${kind}:${id}`;
|
|
1786
|
+
const existing = hostedSearchById.get(aggregateKey);
|
|
1278
1787
|
if (existing) {
|
|
1279
1788
|
existing.status = status;
|
|
1280
1789
|
if (queries.length) {
|
|
@@ -1284,13 +1793,14 @@ var collectModelOutput = (messages) => {
|
|
|
1284
1793
|
existing.sourcesCount = sourcesCount;
|
|
1285
1794
|
}
|
|
1286
1795
|
} else {
|
|
1287
|
-
|
|
1796
|
+
hostedSearchById.set(aggregateKey, {
|
|
1288
1797
|
id,
|
|
1798
|
+
kind,
|
|
1289
1799
|
status,
|
|
1290
1800
|
queries,
|
|
1291
1801
|
...typeof sourcesCount === "number" ? { sourcesCount } : {}
|
|
1292
1802
|
});
|
|
1293
|
-
|
|
1803
|
+
hostedSearchOrder.push(aggregateKey);
|
|
1294
1804
|
}
|
|
1295
1805
|
continue;
|
|
1296
1806
|
}
|
|
@@ -1316,8 +1826,8 @@ var collectModelOutput = (messages) => {
|
|
|
1316
1826
|
toolCalls.push(...message.tool_calls);
|
|
1317
1827
|
}
|
|
1318
1828
|
}
|
|
1319
|
-
for (const
|
|
1320
|
-
const aggregate =
|
|
1829
|
+
for (const aggregateKey of hostedSearchOrder) {
|
|
1830
|
+
const aggregate = hostedSearchById.get(aggregateKey);
|
|
1321
1831
|
if (!aggregate) {
|
|
1322
1832
|
continue;
|
|
1323
1833
|
}
|
|
@@ -1328,10 +1838,11 @@ var collectModelOutput = (messages) => {
|
|
|
1328
1838
|
};
|
|
1329
1839
|
hostedToolCalls.push({
|
|
1330
1840
|
id: aggregate.id,
|
|
1331
|
-
tool: "web_search",
|
|
1332
|
-
displayName: "WebSearch",
|
|
1841
|
+
tool: aggregate.kind === "x" ? "x_search" : "web_search",
|
|
1842
|
+
displayName: aggregate.kind === "x" ? "XSearch" : "WebSearch",
|
|
1333
1843
|
args,
|
|
1334
|
-
result:
|
|
1844
|
+
result: buildHostedSearchSummary(
|
|
1845
|
+
aggregate.kind,
|
|
1335
1846
|
aggregate.status,
|
|
1336
1847
|
aggregate.queries,
|
|
1337
1848
|
aggregate.sourcesCount
|
|
@@ -1341,51 +1852,200 @@ var collectModelOutput = (messages) => {
|
|
|
1341
1852
|
}
|
|
1342
1853
|
return { reasoningTexts, assistantTexts, toolCalls, hostedToolCalls };
|
|
1343
1854
|
};
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1855
|
+
|
|
1856
|
+
// src/tools/done.ts
|
|
1857
|
+
var TaskComplete = class extends Error {
|
|
1858
|
+
finalMessage;
|
|
1859
|
+
constructor(finalMessage) {
|
|
1860
|
+
super("Task complete");
|
|
1861
|
+
this.name = "TaskComplete";
|
|
1862
|
+
this.finalMessage = finalMessage;
|
|
1863
|
+
}
|
|
1349
1864
|
};
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1865
|
+
|
|
1866
|
+
// src/agent/tool-execution.ts
|
|
1867
|
+
var toolResultToContent = (result) => {
|
|
1868
|
+
if (result.type === "text") return result.text;
|
|
1869
|
+
if (result.type === "parts") return result.parts;
|
|
1870
|
+
try {
|
|
1871
|
+
return JSON.stringify(result.value);
|
|
1872
|
+
} catch {
|
|
1873
|
+
return String(result.value);
|
|
1354
1874
|
}
|
|
1355
1875
|
};
|
|
1356
|
-
var
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1876
|
+
var createToolContext = (signal) => {
|
|
1877
|
+
const deps = /* @__PURE__ */ Object.create(null);
|
|
1878
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1879
|
+
const resolve = async (key) => {
|
|
1880
|
+
if (cache.has(key.id)) {
|
|
1881
|
+
return cache.get(key.id);
|
|
1882
|
+
}
|
|
1883
|
+
const value = await key.create();
|
|
1884
|
+
cache.set(key.id, value);
|
|
1885
|
+
return value;
|
|
1886
|
+
};
|
|
1887
|
+
return {
|
|
1888
|
+
deps,
|
|
1889
|
+
resolve,
|
|
1890
|
+
signal,
|
|
1891
|
+
now: () => /* @__PURE__ */ new Date()
|
|
1892
|
+
};
|
|
1893
|
+
};
|
|
1894
|
+
var executeToolCall = async ({
|
|
1895
|
+
toolCall,
|
|
1896
|
+
tools,
|
|
1897
|
+
signal,
|
|
1898
|
+
canExecuteTool
|
|
1899
|
+
}) => {
|
|
1900
|
+
const toolName = toolCall.function.name;
|
|
1901
|
+
const tool = tools.find((candidate) => candidate.name === toolName);
|
|
1902
|
+
if (!tool) {
|
|
1903
|
+
return {
|
|
1904
|
+
message: {
|
|
1905
|
+
role: "tool",
|
|
1906
|
+
tool_call_id: toolCall.id,
|
|
1907
|
+
tool_name: toolName,
|
|
1908
|
+
content: `Error: Unknown tool '${toolName}'`,
|
|
1909
|
+
is_error: true
|
|
1910
|
+
}
|
|
1911
|
+
};
|
|
1912
|
+
}
|
|
1913
|
+
if (canExecuteTool) {
|
|
1914
|
+
try {
|
|
1915
|
+
const decision = await canExecuteTool(
|
|
1916
|
+
toolCall,
|
|
1917
|
+
toolCall.function.arguments,
|
|
1918
|
+
createToolContext(signal)
|
|
1919
|
+
);
|
|
1920
|
+
if (decision.decision === "deny") {
|
|
1921
|
+
const deniedContent = `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
|
|
1922
|
+
return {
|
|
1923
|
+
message: {
|
|
1924
|
+
role: "tool",
|
|
1925
|
+
tool_call_id: toolCall.id,
|
|
1926
|
+
tool_name: toolName,
|
|
1927
|
+
content: deniedContent,
|
|
1928
|
+
is_error: true
|
|
1929
|
+
},
|
|
1930
|
+
...decision.stop_turn ? {
|
|
1931
|
+
done: true,
|
|
1932
|
+
finalMessage: "Permission request was denied. Turn stopped. Please send your next input to continue."
|
|
1933
|
+
} : {}
|
|
1934
|
+
};
|
|
1935
|
+
}
|
|
1936
|
+
} catch (error) {
|
|
1937
|
+
return {
|
|
1938
|
+
message: {
|
|
1939
|
+
role: "tool",
|
|
1940
|
+
tool_call_id: toolCall.id,
|
|
1941
|
+
tool_name: toolName,
|
|
1942
|
+
content: `Permission check failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1943
|
+
is_error: true
|
|
1944
|
+
}
|
|
1945
|
+
};
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
try {
|
|
1949
|
+
const result = await tool.executeRaw(
|
|
1950
|
+
toolCall.function.arguments,
|
|
1951
|
+
createToolContext(signal)
|
|
1952
|
+
);
|
|
1953
|
+
return {
|
|
1954
|
+
message: {
|
|
1955
|
+
role: "tool",
|
|
1956
|
+
tool_call_id: toolCall.id,
|
|
1957
|
+
tool_name: toolName,
|
|
1958
|
+
content: toolResultToContent(result)
|
|
1959
|
+
}
|
|
1960
|
+
};
|
|
1961
|
+
} catch (error) {
|
|
1962
|
+
if (error instanceof TaskComplete) {
|
|
1963
|
+
return {
|
|
1964
|
+
message: {
|
|
1965
|
+
role: "tool",
|
|
1966
|
+
tool_call_id: toolCall.id,
|
|
1967
|
+
tool_name: toolName,
|
|
1968
|
+
content: "Task complete"
|
|
1969
|
+
},
|
|
1970
|
+
done: true,
|
|
1971
|
+
finalMessage: error.finalMessage
|
|
1972
|
+
};
|
|
1973
|
+
}
|
|
1974
|
+
return {
|
|
1975
|
+
message: {
|
|
1976
|
+
role: "tool",
|
|
1977
|
+
tool_call_id: toolCall.id,
|
|
1978
|
+
tool_name: toolName,
|
|
1979
|
+
content: `Error: ${error instanceof Error ? error.message : String(error)}`,
|
|
1980
|
+
is_error: true
|
|
1981
|
+
}
|
|
1982
|
+
};
|
|
1983
|
+
}
|
|
1984
|
+
};
|
|
1985
|
+
|
|
1986
|
+
// src/agent/agent.ts
|
|
1987
|
+
var DEFAULT_MAX_ITERATIONS = 200;
|
|
1988
|
+
var defaultMonotonicNowMs = () => import_node_perf_hooks.performance.now();
|
|
1989
|
+
var elapsedMilliseconds = (startedAt, monotonicNowMs) => Math.max(0, Math.round(monotonicNowMs() - startedAt));
|
|
1990
|
+
var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
1991
|
+
var createAbortError2 = () => {
|
|
1992
|
+
const error = new Error("Operation aborted");
|
|
1993
|
+
error.name = "AbortError";
|
|
1994
|
+
return error;
|
|
1995
|
+
};
|
|
1996
|
+
var isAbortError = (error) => error instanceof Error && (error.name === "AbortError" || error.name === "APIUserAbortError" || error.name === "AbortSignal");
|
|
1997
|
+
var throwIfAborted = (signal) => {
|
|
1998
|
+
if (signal?.aborted) {
|
|
1999
|
+
throw createAbortError2();
|
|
2000
|
+
}
|
|
2001
|
+
};
|
|
2002
|
+
var isResponsesHistoryProvider = (provider) => provider === "openai" || provider === "openrouter" || provider === "xai";
|
|
2003
|
+
var Agent = class {
|
|
2004
|
+
llm;
|
|
2005
|
+
tools;
|
|
2006
|
+
hostedTools;
|
|
2007
|
+
systemPrompt;
|
|
2008
|
+
maxIterations;
|
|
2009
|
+
toolChoice;
|
|
2010
|
+
requireDoneTool;
|
|
2011
|
+
compactionService;
|
|
2012
|
+
toolOutputCacheService;
|
|
2013
|
+
services;
|
|
2014
|
+
modelRegistry;
|
|
2015
|
+
canExecuteTool;
|
|
2016
|
+
monotonicNowMs;
|
|
2017
|
+
llmRetryPolicy;
|
|
2018
|
+
llmRetryDependencies;
|
|
2019
|
+
//private readonly dependencyOverrides?: DependencyOverrides;
|
|
2020
|
+
history;
|
|
2021
|
+
usageService;
|
|
2022
|
+
constructor(options) {
|
|
2023
|
+
this.llm = options.llm;
|
|
2024
|
+
this.history = isResponsesHistoryProvider(this.llm.provider) ? new ResponsesHistoryAdapter() : new MessageHistoryAdapter();
|
|
2025
|
+
this.tools = options.tools;
|
|
2026
|
+
this.hostedTools = options.hostedTools ?? [];
|
|
2027
|
+
this.systemPrompt = options.systemPrompt ?? void 0;
|
|
2028
|
+
this.maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
|
|
2029
|
+
this.toolChoice = options.toolChoice ?? void 0;
|
|
2030
|
+
this.requireDoneTool = options.requireDoneTool ?? false;
|
|
2031
|
+
this.services = options.services ?? {};
|
|
2032
|
+
this.monotonicNowMs = this.services.monotonicNowMs ?? defaultMonotonicNowMs;
|
|
2033
|
+
this.llmRetryPolicy = resolveLlmRetryPolicy({
|
|
2034
|
+
maxRetries: options.llmMaxRetries,
|
|
2035
|
+
baseDelayMs: options.llmRetryBaseDelayMs,
|
|
2036
|
+
maxDelayMs: options.llmRetryMaxDelayMs,
|
|
2037
|
+
maxRetryAfterMs: options.llmMaxRetryAfterMs,
|
|
2038
|
+
retryWindowMs: options.llmRetryWindowMs
|
|
2039
|
+
});
|
|
2040
|
+
this.llmRetryDependencies = {
|
|
2041
|
+
...this.services.llmRetryNowMs ? { nowMs: this.services.llmRetryNowMs } : {},
|
|
2042
|
+
...this.services.llmRetryRandom ? { random: this.services.llmRetryRandom } : {},
|
|
2043
|
+
...this.services.llmRetrySleep ? { sleep: this.services.llmRetrySleep } : {}
|
|
2044
|
+
};
|
|
2045
|
+
this.modelRegistry = options.modelRegistry ?? DEFAULT_MODEL_REGISTRY;
|
|
2046
|
+
this.compactionService = options.compaction === null ? null : new CompactionService(options.compaction ?? {}, {
|
|
2047
|
+
modelRegistry: this.modelRegistry
|
|
2048
|
+
});
|
|
1389
2049
|
this.toolOutputCacheService = options.toolOutputCache === null ? null : new ToolOutputCacheService(options.toolOutputCache ?? {}, {
|
|
1390
2050
|
modelRegistry: this.modelRegistry,
|
|
1391
2051
|
store: this.services.toolOutputCacheStore ?? null
|
|
@@ -1399,31 +2059,12 @@ var Agent = class {
|
|
|
1399
2059
|
return this.usageService.getUsageSummary();
|
|
1400
2060
|
}
|
|
1401
2061
|
getContextLeftPercent() {
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
this.llm.provider,
|
|
1409
|
-
usage.model
|
|
1410
|
-
) : void 0;
|
|
1411
|
-
const modelSpec = usageModelSpec ?? resolveModelWithQualifiedFallback2(
|
|
1412
|
-
this.modelRegistry,
|
|
1413
|
-
this.llm.provider,
|
|
1414
|
-
this.llm.model
|
|
1415
|
-
);
|
|
1416
|
-
const contextLimit = modelSpec?.maxInputTokens ?? modelSpec?.contextWindow ?? null;
|
|
1417
|
-
if (!contextLimit || contextLimit <= 0) {
|
|
1418
|
-
return null;
|
|
1419
|
-
}
|
|
1420
|
-
const used = usage.total_tokens;
|
|
1421
|
-
if (!Number.isFinite(used) || used <= 0) {
|
|
1422
|
-
return 100;
|
|
1423
|
-
}
|
|
1424
|
-
const leftRatio = 1 - used / contextLimit;
|
|
1425
|
-
const percent = Math.round(leftRatio * 100);
|
|
1426
|
-
return Math.max(0, Math.min(100, percent));
|
|
2062
|
+
return calculateContextLeftPercent({
|
|
2063
|
+
usage: this.usageService.getLastUsage(),
|
|
2064
|
+
modelRegistry: this.modelRegistry,
|
|
2065
|
+
provider: this.llm.provider,
|
|
2066
|
+
model: this.llm.model
|
|
2067
|
+
});
|
|
1427
2068
|
}
|
|
1428
2069
|
getHistoryMessages() {
|
|
1429
2070
|
return this.history.getViewMessages();
|
|
@@ -1483,24 +2124,6 @@ var Agent = class {
|
|
|
1483
2124
|
if (!this.toolOutputCacheService) return message;
|
|
1484
2125
|
return this.toolOutputCacheService.processToolMessage(message);
|
|
1485
2126
|
}
|
|
1486
|
-
buildToolContext(signal) {
|
|
1487
|
-
const deps = /* @__PURE__ */ Object.create(null);
|
|
1488
|
-
const cache = /* @__PURE__ */ new Map();
|
|
1489
|
-
const resolve = async (key) => {
|
|
1490
|
-
if (cache.has(key.id)) {
|
|
1491
|
-
return cache.get(key.id);
|
|
1492
|
-
}
|
|
1493
|
-
const value = await key.create();
|
|
1494
|
-
cache.set(key.id, value);
|
|
1495
|
-
return value;
|
|
1496
|
-
};
|
|
1497
|
-
return {
|
|
1498
|
-
deps,
|
|
1499
|
-
resolve,
|
|
1500
|
-
signal,
|
|
1501
|
-
now: () => /* @__PURE__ */ new Date()
|
|
1502
|
-
};
|
|
1503
|
-
}
|
|
1504
2127
|
recordLlmRequest(session, input, context) {
|
|
1505
2128
|
if (!session) return null;
|
|
1506
2129
|
const seq = (session.invoke_seq ?? 0) + 1;
|
|
@@ -1552,6 +2175,21 @@ var Agent = class {
|
|
|
1552
2175
|
}
|
|
1553
2176
|
});
|
|
1554
2177
|
}
|
|
2178
|
+
async *invokeModelWithRetry(input, context, signal) {
|
|
2179
|
+
return yield* invokeWithRetry({
|
|
2180
|
+
operation: (attemptSignal) => this.llm.ainvoke(
|
|
2181
|
+
{
|
|
2182
|
+
...input,
|
|
2183
|
+
...attemptSignal ? { signal: attemptSignal } : {}
|
|
2184
|
+
},
|
|
2185
|
+
context
|
|
2186
|
+
),
|
|
2187
|
+
classifyFailure: this.llm.classifyFailure,
|
|
2188
|
+
policy: this.llmRetryPolicy,
|
|
2189
|
+
...signal ? { signal } : {},
|
|
2190
|
+
dependencies: this.llmRetryDependencies
|
|
2191
|
+
});
|
|
2192
|
+
}
|
|
1555
2193
|
async run(message, options = {}) {
|
|
1556
2194
|
let finalResponse = "";
|
|
1557
2195
|
for await (const event of this.runStream(message, options)) {
|
|
@@ -1597,12 +2235,10 @@ var Agent = class {
|
|
|
1597
2235
|
});
|
|
1598
2236
|
const invokeContext = this.buildInvokeContext(session);
|
|
1599
2237
|
const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
|
|
1600
|
-
const response =
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
},
|
|
1605
|
-
invokeContext
|
|
2238
|
+
const response = yield* this.invokeModelWithRetry(
|
|
2239
|
+
invokeInput,
|
|
2240
|
+
invokeContext,
|
|
2241
|
+
signal
|
|
1606
2242
|
);
|
|
1607
2243
|
this.recordLlmResponse(session, seq, response);
|
|
1608
2244
|
this.usageService.updateUsageSummary(response.usage);
|
|
@@ -1709,11 +2345,12 @@ var Agent = class {
|
|
|
1709
2345
|
const monotonicStartedAt = this.monotonicNowMs();
|
|
1710
2346
|
try {
|
|
1711
2347
|
throwIfAborted(signal);
|
|
1712
|
-
const execution = await
|
|
2348
|
+
const execution = await executeToolCall({
|
|
1713
2349
|
toolCall,
|
|
1714
|
-
runTools,
|
|
1715
|
-
signal
|
|
1716
|
-
|
|
2350
|
+
tools: runTools,
|
|
2351
|
+
...signal ? { signal } : {},
|
|
2352
|
+
...this.canExecuteTool ? { canExecuteTool: this.canExecuteTool } : {}
|
|
2353
|
+
});
|
|
1717
2354
|
const rawOutput = stringifyContent(execution.message.content, {
|
|
1718
2355
|
mode: "display"
|
|
1719
2356
|
});
|
|
@@ -1855,129 +2492,84 @@ ${assistantTexts.join("\n").trim()}`;
|
|
|
1855
2492
|
return finalResponse;
|
|
1856
2493
|
} catch {
|
|
1857
2494
|
if (signal?.aborted) {
|
|
1858
|
-
throw
|
|
2495
|
+
throw createAbortError2();
|
|
1859
2496
|
}
|
|
1860
2497
|
return "[Max Iterations Reached]\n\nSummary unavailable due to an internal error.";
|
|
1861
2498
|
}
|
|
1862
2499
|
}
|
|
1863
|
-
async executeToolCall(toolCall, tools, signal) {
|
|
1864
|
-
const toolName = toolCall.function.name;
|
|
1865
|
-
const tool = tools.find((t) => t.name === toolName);
|
|
1866
|
-
if (!tool) {
|
|
1867
|
-
return {
|
|
1868
|
-
message: {
|
|
1869
|
-
role: "tool",
|
|
1870
|
-
tool_call_id: toolCall.id,
|
|
1871
|
-
tool_name: toolName,
|
|
1872
|
-
content: `Error: Unknown tool '${toolName}'`,
|
|
1873
|
-
is_error: true
|
|
1874
|
-
}
|
|
1875
|
-
};
|
|
1876
|
-
}
|
|
1877
|
-
if (this.canExecuteTool) {
|
|
1878
|
-
try {
|
|
1879
|
-
const decision = await this.canExecuteTool(
|
|
1880
|
-
toolCall,
|
|
1881
|
-
toolCall.function.arguments,
|
|
1882
|
-
this.buildToolContext(signal)
|
|
1883
|
-
);
|
|
1884
|
-
if (decision.decision === "deny") {
|
|
1885
|
-
const deniedContent = `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
|
|
1886
|
-
return {
|
|
1887
|
-
message: {
|
|
1888
|
-
role: "tool",
|
|
1889
|
-
tool_call_id: toolCall.id,
|
|
1890
|
-
tool_name: toolName,
|
|
1891
|
-
content: deniedContent,
|
|
1892
|
-
is_error: true
|
|
1893
|
-
},
|
|
1894
|
-
...decision.stop_turn ? {
|
|
1895
|
-
done: true,
|
|
1896
|
-
finalMessage: "Permission request was denied. Turn stopped. Please send your next input to continue."
|
|
1897
|
-
} : {}
|
|
1898
|
-
};
|
|
1899
|
-
}
|
|
1900
|
-
} catch (error) {
|
|
1901
|
-
return {
|
|
1902
|
-
message: {
|
|
1903
|
-
role: "tool",
|
|
1904
|
-
tool_call_id: toolCall.id,
|
|
1905
|
-
tool_name: toolName,
|
|
1906
|
-
content: `Permission check failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1907
|
-
is_error: true
|
|
1908
|
-
}
|
|
1909
|
-
};
|
|
1910
|
-
}
|
|
1911
|
-
}
|
|
1912
|
-
try {
|
|
1913
|
-
const result = await tool.executeRaw(
|
|
1914
|
-
toolCall.function.arguments,
|
|
1915
|
-
this.buildToolContext(signal)
|
|
1916
|
-
);
|
|
1917
|
-
return {
|
|
1918
|
-
message: {
|
|
1919
|
-
role: "tool",
|
|
1920
|
-
tool_call_id: toolCall.id,
|
|
1921
|
-
tool_name: toolName,
|
|
1922
|
-
content: toolResultToContent(result)
|
|
1923
|
-
}
|
|
1924
|
-
};
|
|
1925
|
-
} catch (error) {
|
|
1926
|
-
if (error instanceof TaskComplete) {
|
|
1927
|
-
return {
|
|
1928
|
-
message: {
|
|
1929
|
-
role: "tool",
|
|
1930
|
-
tool_call_id: toolCall.id,
|
|
1931
|
-
tool_name: toolName,
|
|
1932
|
-
content: "Task complete"
|
|
1933
|
-
},
|
|
1934
|
-
done: true,
|
|
1935
|
-
finalMessage: error.finalMessage
|
|
1936
|
-
};
|
|
1937
|
-
}
|
|
1938
|
-
return {
|
|
1939
|
-
message: {
|
|
1940
|
-
role: "tool",
|
|
1941
|
-
tool_call_id: toolCall.id,
|
|
1942
|
-
tool_name: toolName,
|
|
1943
|
-
content: `Error: ${error instanceof Error ? error.message : String(error)}`,
|
|
1944
|
-
is_error: true
|
|
1945
|
-
}
|
|
1946
|
-
};
|
|
1947
|
-
}
|
|
1948
|
-
}
|
|
1949
|
-
};
|
|
1950
|
-
var resolveModelWithQualifiedFallback2 = (modelRegistry, provider, modelId) => {
|
|
1951
|
-
const direct = resolveModel(modelRegistry, modelId, provider);
|
|
1952
|
-
if (direct) return direct;
|
|
1953
|
-
const qualified = parseQualifiedModelId3(modelId);
|
|
1954
|
-
if (!qualified) return resolveModel(modelRegistry, modelId);
|
|
1955
|
-
return resolveModel(modelRegistry, qualified.modelId, qualified.provider) ?? resolveModel(
|
|
1956
|
-
modelRegistry,
|
|
1957
|
-
`${qualified.provider}/${qualified.modelId}`,
|
|
1958
|
-
qualified.provider
|
|
1959
|
-
);
|
|
1960
|
-
};
|
|
1961
|
-
var parseQualifiedModelId3 = (modelId) => {
|
|
1962
|
-
const sep = modelId.indexOf("/");
|
|
1963
|
-
if (sep <= 0 || sep >= modelId.length - 1) {
|
|
1964
|
-
return null;
|
|
1965
|
-
}
|
|
1966
|
-
const providerRaw = modelId.slice(0, sep);
|
|
1967
|
-
const rest = modelId.slice(sep + 1);
|
|
1968
|
-
if (!rest) {
|
|
1969
|
-
return null;
|
|
1970
|
-
}
|
|
1971
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
1972
|
-
return null;
|
|
1973
|
-
}
|
|
1974
|
-
return { provider: providerRaw, modelId: rest };
|
|
1975
2500
|
};
|
|
1976
2501
|
|
|
1977
2502
|
// src/llm/anthropic/chat.ts
|
|
1978
2503
|
var import_node_crypto = require("crypto");
|
|
1979
2504
|
var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
|
|
1980
2505
|
|
|
2506
|
+
// src/llm/anthropic/failure.ts
|
|
2507
|
+
var PROVIDER_NAME = "anthropic";
|
|
2508
|
+
var classifyAnthropicFailure = (error) => {
|
|
2509
|
+
if (isAbortLikeProviderError(error)) {
|
|
2510
|
+
return buildProviderFailure(PROVIDER_NAME, "cancelled");
|
|
2511
|
+
}
|
|
2512
|
+
const extracted = extractProviderError(error);
|
|
2513
|
+
const status = extracted.status;
|
|
2514
|
+
const type = extracted.type?.toLowerCase() ?? "";
|
|
2515
|
+
const retryOptions = getRetryHint(extracted);
|
|
2516
|
+
if (status === 401) {
|
|
2517
|
+
return buildProviderFailure(PROVIDER_NAME, "auth", { status });
|
|
2518
|
+
}
|
|
2519
|
+
if (status === 402 || type === "billing_error") {
|
|
2520
|
+
return buildProviderFailure(PROVIDER_NAME, "hard_quota", { status });
|
|
2521
|
+
}
|
|
2522
|
+
if (status === 403) {
|
|
2523
|
+
return buildProviderFailure(PROVIDER_NAME, "permission", { status });
|
|
2524
|
+
}
|
|
2525
|
+
if (isValidationStatus(status)) {
|
|
2526
|
+
return buildProviderFailure(PROVIDER_NAME, "validation", { status });
|
|
2527
|
+
}
|
|
2528
|
+
if (status === 429 || type === "rate_limit_error") {
|
|
2529
|
+
return buildProviderFailure(PROVIDER_NAME, "rate_limit", {
|
|
2530
|
+
status,
|
|
2531
|
+
retryable: true,
|
|
2532
|
+
...retryOptions
|
|
2533
|
+
});
|
|
2534
|
+
}
|
|
2535
|
+
if (status === 408) {
|
|
2536
|
+
return buildProviderFailure(PROVIDER_NAME, "timeout", {
|
|
2537
|
+
status,
|
|
2538
|
+
retryable: true,
|
|
2539
|
+
...retryOptions
|
|
2540
|
+
});
|
|
2541
|
+
}
|
|
2542
|
+
if (status === 409) {
|
|
2543
|
+
return buildProviderFailure(PROVIDER_NAME, "provider", {
|
|
2544
|
+
status,
|
|
2545
|
+
retryable: true,
|
|
2546
|
+
...retryOptions
|
|
2547
|
+
});
|
|
2548
|
+
}
|
|
2549
|
+
if (status === 529 || type === "overloaded_error") {
|
|
2550
|
+
return buildProviderFailure(PROVIDER_NAME, "overloaded", {
|
|
2551
|
+
status,
|
|
2552
|
+
retryable: true,
|
|
2553
|
+
...retryOptions
|
|
2554
|
+
});
|
|
2555
|
+
}
|
|
2556
|
+
if (status === 504 || type === "timeout_error") {
|
|
2557
|
+
return buildProviderFailure(PROVIDER_NAME, "timeout", {
|
|
2558
|
+
status,
|
|
2559
|
+
retryable: true,
|
|
2560
|
+
...retryOptions
|
|
2561
|
+
});
|
|
2562
|
+
}
|
|
2563
|
+
if (status !== void 0 && status >= 500) {
|
|
2564
|
+
return buildProviderFailure(PROVIDER_NAME, "provider", {
|
|
2565
|
+
status,
|
|
2566
|
+
retryable: true,
|
|
2567
|
+
...retryOptions
|
|
2568
|
+
});
|
|
2569
|
+
}
|
|
2570
|
+
return classifyTransportFailure(PROVIDER_NAME, error) ?? buildProviderFailure(PROVIDER_NAME, "provider");
|
|
2571
|
+
};
|
|
2572
|
+
|
|
1981
2573
|
// src/llm/provider-log.ts
|
|
1982
2574
|
var import_node_fs = require("fs");
|
|
1983
2575
|
var import_node_path = __toESM(require("path"), 1);
|
|
@@ -2078,7 +2670,8 @@ function isToolResult(value) {
|
|
|
2078
2670
|
}
|
|
2079
2671
|
|
|
2080
2672
|
// src/types/llm/tools.ts
|
|
2081
|
-
var
|
|
2673
|
+
var isHostedWebSearchToolDefinition = (value) => value.type === "hosted_search" && value.search_kind !== "x";
|
|
2674
|
+
var isHostedXSearchToolDefinition = (value) => value.type === "hosted_search" && value.search_kind === "x";
|
|
2082
2675
|
var isFunctionToolDefinition = (value) => value.type !== "hosted_search";
|
|
2083
2676
|
|
|
2084
2677
|
// src/llm/anthropic/serializer.ts
|
|
@@ -2217,7 +2810,7 @@ var toAnthropicTools = (tools) => {
|
|
|
2217
2810
|
});
|
|
2218
2811
|
continue;
|
|
2219
2812
|
}
|
|
2220
|
-
if (
|
|
2813
|
+
if (isHostedWebSearchToolDefinition(tool)) {
|
|
2221
2814
|
const hosted = toAnthropicHostedSearchTool(tool);
|
|
2222
2815
|
if (hosted) {
|
|
2223
2816
|
mapped.push(hosted);
|
|
@@ -2508,7 +3101,7 @@ var toAnthropicHostedSearchTool = (tool) => {
|
|
|
2508
3101
|
};
|
|
2509
3102
|
|
|
2510
3103
|
// src/llm/anthropic/chat.ts
|
|
2511
|
-
var
|
|
3104
|
+
var PROVIDER_NAME2 = "anthropic";
|
|
2512
3105
|
var DEFAULT_MODEL = ANTHROPIC_DEFAULT_MODEL;
|
|
2513
3106
|
var DEFAULT_MAX_TOKENS = 4096;
|
|
2514
3107
|
var DEFAULT_CLIENT_TIMEOUT_MS = 20 * 60 * 1e3;
|
|
@@ -2517,8 +3110,9 @@ var DEFAULT_PROMPT_CACHE_CONTROL = {
|
|
|
2517
3110
|
};
|
|
2518
3111
|
var FAST_MODE_BETA = "fast-mode-2026-02-01";
|
|
2519
3112
|
var ChatAnthropic = class {
|
|
2520
|
-
provider =
|
|
3113
|
+
provider = PROVIDER_NAME2;
|
|
2521
3114
|
model;
|
|
3115
|
+
classifyFailure = classifyAnthropicFailure;
|
|
2522
3116
|
client;
|
|
2523
3117
|
defaultMaxTokens;
|
|
2524
3118
|
defaultInvokeOptions;
|
|
@@ -2529,7 +3123,8 @@ var ChatAnthropic = class {
|
|
|
2529
3123
|
constructor(options = {}) {
|
|
2530
3124
|
this.client = options.client ?? new import_sdk.default({
|
|
2531
3125
|
timeout: DEFAULT_CLIENT_TIMEOUT_MS,
|
|
2532
|
-
...options.clientOptions ?? {}
|
|
3126
|
+
...options.clientOptions ?? {},
|
|
3127
|
+
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
2533
3128
|
});
|
|
2534
3129
|
this.model = options.model ?? DEFAULT_MODEL;
|
|
2535
3130
|
this.defaultMaxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
@@ -2610,17 +3205,522 @@ var ChatAnthropic = class {
|
|
|
2610
3205
|
const systemHash = (0, import_node_crypto.createHash)("sha256").update(safeJsonStringify(request.system ?? "")).digest("hex").slice(0, 12);
|
|
2611
3206
|
const previous = this.lastDebugRequestPayload;
|
|
2612
3207
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
2613
|
-
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
3208
|
+
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
3209
|
+
if (settings.enabled) {
|
|
3210
|
+
console.error(
|
|
3211
|
+
`[anthropic.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} system_sha=${systemHash}`
|
|
3212
|
+
);
|
|
3213
|
+
}
|
|
3214
|
+
if (settings.dumpDir) {
|
|
3215
|
+
try {
|
|
3216
|
+
await writeProviderLogDump(
|
|
3217
|
+
settings,
|
|
3218
|
+
PROVIDER_NAME2,
|
|
3219
|
+
seq,
|
|
3220
|
+
"request",
|
|
3221
|
+
request
|
|
3222
|
+
);
|
|
3223
|
+
} catch (error) {
|
|
3224
|
+
if (settings.enabled) {
|
|
3225
|
+
console.error(
|
|
3226
|
+
`[anthropic.request] dump_failed seq=${seq} error=${String(error)}`
|
|
3227
|
+
);
|
|
3228
|
+
}
|
|
3229
|
+
}
|
|
3230
|
+
}
|
|
3231
|
+
this.lastDebugRequestPayload = payload;
|
|
3232
|
+
}
|
|
3233
|
+
async debugResponseIfEnabled(response, seq) {
|
|
3234
|
+
const settings = getProviderLogSettings();
|
|
3235
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
3236
|
+
return;
|
|
3237
|
+
}
|
|
3238
|
+
if (settings.enabled) {
|
|
3239
|
+
const usage = response.usage;
|
|
3240
|
+
const inputTokens = usage?.input_tokens ?? 0;
|
|
3241
|
+
const outputTokens = usage?.output_tokens ?? 0;
|
|
3242
|
+
const cachedRead = usage?.cache_read_input_tokens ?? 0;
|
|
3243
|
+
const cachedCreate = usage?.cache_creation_input_tokens ?? 0;
|
|
3244
|
+
const blocks = Array.isArray(response.content) ? response.content : [];
|
|
3245
|
+
const blockKinds = /* @__PURE__ */ new Set();
|
|
3246
|
+
for (const block of blocks) {
|
|
3247
|
+
const kind = block && typeof block === "object" && "type" in block ? String(block.type ?? "unknown") : "unknown";
|
|
3248
|
+
blockKinds.add(kind);
|
|
3249
|
+
}
|
|
3250
|
+
console.error(
|
|
3251
|
+
`[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}`
|
|
3252
|
+
);
|
|
3253
|
+
}
|
|
3254
|
+
if (settings.dumpDir) {
|
|
3255
|
+
try {
|
|
3256
|
+
await writeProviderLogDump(
|
|
3257
|
+
settings,
|
|
3258
|
+
PROVIDER_NAME2,
|
|
3259
|
+
seq,
|
|
3260
|
+
"response",
|
|
3261
|
+
response
|
|
3262
|
+
);
|
|
3263
|
+
} catch (error) {
|
|
3264
|
+
if (settings.enabled) {
|
|
3265
|
+
console.error(
|
|
3266
|
+
`[anthropic.response] dump_failed seq=${seq} error=${String(error)}`
|
|
3267
|
+
);
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
}
|
|
3271
|
+
}
|
|
3272
|
+
};
|
|
3273
|
+
|
|
3274
|
+
// src/llm/moonshot/chat.ts
|
|
3275
|
+
var import_node_crypto2 = require("crypto");
|
|
3276
|
+
var import_openai3 = __toESM(require("openai"), 1);
|
|
3277
|
+
|
|
3278
|
+
// src/llm/moonshot/failure.ts
|
|
3279
|
+
var PROVIDER_NAME3 = "moonshot";
|
|
3280
|
+
var parseWaitHintMs = (message) => {
|
|
3281
|
+
const match = message.match(
|
|
3282
|
+
/(?:retry|wait|try again)\s+(?:after|in|for)?\s*(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|seconds?|m|minutes?)/i
|
|
3283
|
+
);
|
|
3284
|
+
if (!match) return void 0;
|
|
3285
|
+
const value = Number(match[1]);
|
|
3286
|
+
if (!Number.isFinite(value) || value < 0) return void 0;
|
|
3287
|
+
const unit = match[2]?.toLowerCase() ?? "s";
|
|
3288
|
+
if (unit.startsWith("ms")) return Math.round(value);
|
|
3289
|
+
if (unit.startsWith("m") && !unit.startsWith("ms")) {
|
|
3290
|
+
return Math.round(value * 6e4);
|
|
3291
|
+
}
|
|
3292
|
+
return Math.round(value * 1e3);
|
|
3293
|
+
};
|
|
3294
|
+
var isTpdLimit = (message) => /\btpd\b|tokens?\s+per\s+day|daily\s+(?:token\s+)?limit|next\s+day/i.test(
|
|
3295
|
+
message
|
|
3296
|
+
);
|
|
3297
|
+
var isShortWindowLimit = (message) => /\b(?:rpm|tpm)\b|requests?\s+per\s+minute|tokens?\s+per\s+minute|concurren(?:cy|t)/i.test(
|
|
3298
|
+
message
|
|
3299
|
+
);
|
|
3300
|
+
var classifyMoonshotFailure = (error) => {
|
|
3301
|
+
if (isAbortLikeProviderError(error)) {
|
|
3302
|
+
return buildProviderFailure(PROVIDER_NAME3, "cancelled");
|
|
3303
|
+
}
|
|
3304
|
+
const extracted = extractProviderError(error);
|
|
3305
|
+
const status = extracted.status;
|
|
3306
|
+
const type = extracted.type?.toLowerCase() ?? "";
|
|
3307
|
+
const message = extracted.message;
|
|
3308
|
+
const retryAfterMs = extracted.retryAfterMs ?? parseWaitHintMs(message);
|
|
3309
|
+
const delaySource = extracted.retryAfterMs !== void 0 ? "retry-after" : retryAfterMs !== void 0 ? "provider-body" : void 0;
|
|
3310
|
+
const retryOptions = retryAfterMs !== void 0 && delaySource ? { retryAfterMs, delaySource } : {};
|
|
3311
|
+
if (status === 401) {
|
|
3312
|
+
return buildProviderFailure(PROVIDER_NAME3, "auth", { status });
|
|
3313
|
+
}
|
|
3314
|
+
if (status === 403) {
|
|
3315
|
+
return buildProviderFailure(PROVIDER_NAME3, "permission", { status });
|
|
3316
|
+
}
|
|
3317
|
+
if (isValidationStatus(status)) {
|
|
3318
|
+
return buildProviderFailure(PROVIDER_NAME3, "validation", { status });
|
|
3319
|
+
}
|
|
3320
|
+
if (type === "exceeded_current_quota_error") {
|
|
3321
|
+
return buildProviderFailure(PROVIDER_NAME3, "hard_quota", { status });
|
|
3322
|
+
}
|
|
3323
|
+
if (type === "engine_overloaded_error") {
|
|
3324
|
+
return buildProviderFailure(PROVIDER_NAME3, "overloaded", {
|
|
3325
|
+
status,
|
|
3326
|
+
retryable: true,
|
|
3327
|
+
...retryOptions
|
|
3328
|
+
});
|
|
3329
|
+
}
|
|
3330
|
+
if (status === 429 && type === "rate_limit_reached_error") {
|
|
3331
|
+
if (isTpdLimit(message)) {
|
|
3332
|
+
return buildProviderFailure(PROVIDER_NAME3, "hard_quota", { status });
|
|
3333
|
+
}
|
|
3334
|
+
if (isShortWindowLimit(message) || retryAfterMs !== void 0) {
|
|
3335
|
+
return buildProviderFailure(PROVIDER_NAME3, "rate_limit", {
|
|
3336
|
+
status,
|
|
3337
|
+
retryable: true,
|
|
3338
|
+
...retryOptions
|
|
3339
|
+
});
|
|
3340
|
+
}
|
|
3341
|
+
return buildProviderFailure(PROVIDER_NAME3, "rate_limit", { status });
|
|
3342
|
+
}
|
|
3343
|
+
if (status === 429) {
|
|
3344
|
+
return buildProviderFailure(PROVIDER_NAME3, "rate_limit", { status });
|
|
3345
|
+
}
|
|
3346
|
+
if (status === 408) {
|
|
3347
|
+
return buildProviderFailure(PROVIDER_NAME3, "timeout", {
|
|
3348
|
+
status,
|
|
3349
|
+
retryable: true,
|
|
3350
|
+
...retryOptions
|
|
3351
|
+
});
|
|
3352
|
+
}
|
|
3353
|
+
if (status === 409) {
|
|
3354
|
+
return buildProviderFailure(PROVIDER_NAME3, "provider", {
|
|
3355
|
+
status,
|
|
3356
|
+
retryable: true,
|
|
3357
|
+
...retryOptions
|
|
3358
|
+
});
|
|
3359
|
+
}
|
|
3360
|
+
if (status === 503) {
|
|
3361
|
+
return buildProviderFailure(PROVIDER_NAME3, "overloaded", {
|
|
3362
|
+
status,
|
|
3363
|
+
retryable: true,
|
|
3364
|
+
...retryOptions
|
|
3365
|
+
});
|
|
3366
|
+
}
|
|
3367
|
+
if (status !== void 0 && status >= 500) {
|
|
3368
|
+
return buildProviderFailure(PROVIDER_NAME3, "provider", {
|
|
3369
|
+
status,
|
|
3370
|
+
retryable: true,
|
|
3371
|
+
...retryOptions
|
|
3372
|
+
});
|
|
3373
|
+
}
|
|
3374
|
+
return classifyTransportFailure(PROVIDER_NAME3, error) ?? buildProviderFailure(PROVIDER_NAME3, "provider");
|
|
3375
|
+
};
|
|
3376
|
+
|
|
3377
|
+
// src/llm/moonshot/serializer.ts
|
|
3378
|
+
var stringify = (content) => stringifyContent(content, { mode: "display", joiner: "" });
|
|
3379
|
+
var MOONSHOT_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
|
|
3380
|
+
"image/png",
|
|
3381
|
+
"image/jpeg",
|
|
3382
|
+
"image/webp",
|
|
3383
|
+
"image/gif"
|
|
3384
|
+
]);
|
|
3385
|
+
var BASE64_PAYLOAD = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
3386
|
+
var toMoonshotImagePart = (part) => {
|
|
3387
|
+
const url = part.image_url.url;
|
|
3388
|
+
if (url.startsWith("ms://") && url.length > "ms://".length) {
|
|
3389
|
+
return { type: "image_url", image_url: { url } };
|
|
3390
|
+
}
|
|
3391
|
+
const separator = url.indexOf(",");
|
|
3392
|
+
const header = separator >= 0 ? url.slice(0, separator) : "";
|
|
3393
|
+
const payload = separator >= 0 ? url.slice(separator + 1) : "";
|
|
3394
|
+
const mediaType = header.startsWith("data:") && header.endsWith(";base64") ? header.slice("data:".length, header.length - ";base64".length) : "";
|
|
3395
|
+
if (!header.endsWith(";base64") || !MOONSHOT_IMAGE_MEDIA_TYPES.has(mediaType) || !payload || !BASE64_PAYLOAD.test(payload)) {
|
|
3396
|
+
throw createProviderValidationError(
|
|
3397
|
+
"moonshot",
|
|
3398
|
+
"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"
|
|
3399
|
+
);
|
|
3400
|
+
}
|
|
3401
|
+
if (part.image_url.media_type && part.image_url.media_type !== mediaType) {
|
|
3402
|
+
throw createProviderValidationError(
|
|
3403
|
+
"moonshot",
|
|
3404
|
+
`Moonshot image media_type mismatch: declared ${part.image_url.media_type}, data URL uses ${mediaType}`
|
|
3405
|
+
);
|
|
3406
|
+
}
|
|
3407
|
+
return { type: "image_url", image_url: { url } };
|
|
3408
|
+
};
|
|
3409
|
+
var toUserContent = (content) => {
|
|
3410
|
+
if (typeof content === "string") return content;
|
|
3411
|
+
const parts = [];
|
|
3412
|
+
for (const part of content) {
|
|
3413
|
+
if (part.type === "text") {
|
|
3414
|
+
parts.push(part);
|
|
3415
|
+
} else if (part.type === "image_url") {
|
|
3416
|
+
parts.push(toMoonshotImagePart(part));
|
|
3417
|
+
} else {
|
|
3418
|
+
parts.push({ type: "text", text: stringify([part]) });
|
|
3419
|
+
}
|
|
3420
|
+
}
|
|
3421
|
+
return parts;
|
|
3422
|
+
};
|
|
3423
|
+
var isMoonshotReasoning = (message) => {
|
|
3424
|
+
if (message.role !== "reasoning" || !message.content) return false;
|
|
3425
|
+
const raw = message.raw_item;
|
|
3426
|
+
return typeof raw === "object" && raw !== null && "provider" in raw && raw.provider === "moonshot";
|
|
3427
|
+
};
|
|
3428
|
+
function toMoonshotMessages(messages) {
|
|
3429
|
+
const mapped = [];
|
|
3430
|
+
let pendingReasoning = null;
|
|
3431
|
+
const pendingToolImages = [];
|
|
3432
|
+
const flushPendingToolImages = () => {
|
|
3433
|
+
if (!pendingToolImages.length) return;
|
|
3434
|
+
const content = [];
|
|
3435
|
+
for (const pending of pendingToolImages) {
|
|
3436
|
+
content.push({
|
|
3437
|
+
type: "text",
|
|
3438
|
+
text: `Image output from tool ${pending.toolName} (call ${pending.toolCallId}).`
|
|
3439
|
+
});
|
|
3440
|
+
content.push(pending.image);
|
|
3441
|
+
}
|
|
3442
|
+
mapped.push({ role: "user", content });
|
|
3443
|
+
pendingToolImages.length = 0;
|
|
3444
|
+
};
|
|
3445
|
+
for (const message of messages) {
|
|
3446
|
+
if (message.role !== "tool") {
|
|
3447
|
+
flushPendingToolImages();
|
|
3448
|
+
}
|
|
3449
|
+
switch (message.role) {
|
|
3450
|
+
case "system":
|
|
3451
|
+
mapped.push({ role: "system", content: stringify(message.content) });
|
|
3452
|
+
pendingReasoning = null;
|
|
3453
|
+
break;
|
|
3454
|
+
case "user":
|
|
3455
|
+
mapped.push({ role: "user", content: toUserContent(message.content) });
|
|
3456
|
+
pendingReasoning = null;
|
|
3457
|
+
break;
|
|
3458
|
+
case "reasoning":
|
|
3459
|
+
pendingReasoning = isMoonshotReasoning(message) ? message.content : null;
|
|
3460
|
+
break;
|
|
3461
|
+
case "assistant": {
|
|
3462
|
+
const toolCalls = toReplayToolCalls(message.tool_calls);
|
|
3463
|
+
mapped.push({
|
|
3464
|
+
role: "assistant",
|
|
3465
|
+
content: stringify(message.content) || null,
|
|
3466
|
+
...pendingReasoning ? { reasoning_content: pendingReasoning } : {},
|
|
3467
|
+
...toolCalls.length ? { tool_calls: toolCalls } : {}
|
|
3468
|
+
});
|
|
3469
|
+
pendingReasoning = null;
|
|
3470
|
+
break;
|
|
3471
|
+
}
|
|
3472
|
+
case "tool": {
|
|
3473
|
+
const textParts = [];
|
|
3474
|
+
for (const part of typeof message.content === "string" ? [] : message.content) {
|
|
3475
|
+
if (part.type === "image_url") {
|
|
3476
|
+
pendingToolImages.push({
|
|
3477
|
+
toolName: message.tool_name,
|
|
3478
|
+
toolCallId: message.tool_call_id,
|
|
3479
|
+
image: toMoonshotImagePart(part)
|
|
3480
|
+
});
|
|
3481
|
+
} else {
|
|
3482
|
+
textParts.push(part);
|
|
3483
|
+
}
|
|
3484
|
+
}
|
|
3485
|
+
const textContent = typeof message.content === "string" ? message.content : textParts.length ? stringify(textParts) : "";
|
|
3486
|
+
mapped.push({
|
|
3487
|
+
role: "tool",
|
|
3488
|
+
tool_call_id: message.tool_call_id,
|
|
3489
|
+
content: textContent || `Tool ${message.tool_name} returned image output attached in the following user message.`
|
|
3490
|
+
});
|
|
3491
|
+
pendingReasoning = null;
|
|
3492
|
+
break;
|
|
3493
|
+
}
|
|
3494
|
+
}
|
|
3495
|
+
}
|
|
3496
|
+
flushPendingToolImages();
|
|
3497
|
+
return mapped;
|
|
3498
|
+
}
|
|
3499
|
+
function toMoonshotTools(tools) {
|
|
3500
|
+
if (!tools?.length) return void 0;
|
|
3501
|
+
const mapped = tools.filter(isFunctionToolDefinition).map((tool) => ({
|
|
3502
|
+
type: "function",
|
|
3503
|
+
function: {
|
|
3504
|
+
name: tool.name,
|
|
3505
|
+
description: tool.description,
|
|
3506
|
+
parameters: tool.parameters,
|
|
3507
|
+
...tool.strict !== void 0 ? { strict: tool.strict } : {}
|
|
3508
|
+
}
|
|
3509
|
+
}));
|
|
3510
|
+
return mapped.length ? mapped : void 0;
|
|
3511
|
+
}
|
|
3512
|
+
function toMoonshotToolChoice(choice) {
|
|
3513
|
+
if (!choice) return void 0;
|
|
3514
|
+
if (choice === "auto" || choice === "required" || choice === "none") {
|
|
3515
|
+
return choice;
|
|
3516
|
+
}
|
|
3517
|
+
return { type: "function", function: { name: choice } };
|
|
3518
|
+
}
|
|
3519
|
+
var createMoonshotStreamAccumulator = () => ({
|
|
3520
|
+
content: "",
|
|
3521
|
+
reasoningContent: "",
|
|
3522
|
+
toolCalls: [],
|
|
3523
|
+
rawChunkCount: 0
|
|
3524
|
+
});
|
|
3525
|
+
function appendMoonshotChatCompletionChunk(accumulator, chunk) {
|
|
3526
|
+
accumulator.rawChunkCount += 1;
|
|
3527
|
+
accumulator.id ??= chunk.id;
|
|
3528
|
+
accumulator.model ??= chunk.model;
|
|
3529
|
+
accumulator.usage ??= chunk.usage ?? void 0;
|
|
3530
|
+
for (const choice of chunk.choices ?? []) {
|
|
3531
|
+
if (choice.finish_reason !== void 0) {
|
|
3532
|
+
accumulator.finishReason = choice.finish_reason;
|
|
3533
|
+
}
|
|
3534
|
+
const delta = choice.delta;
|
|
3535
|
+
if (!delta) continue;
|
|
3536
|
+
if (typeof delta.reasoning_content === "string") {
|
|
3537
|
+
accumulator.reasoningContent += delta.reasoning_content;
|
|
3538
|
+
}
|
|
3539
|
+
if (typeof delta.content === "string") {
|
|
3540
|
+
accumulator.content += delta.content;
|
|
3541
|
+
}
|
|
3542
|
+
for (const toolDelta of delta.tool_calls ?? []) {
|
|
3543
|
+
const index = typeof toolDelta.index === "number" ? toolDelta.index : accumulator.toolCalls.length;
|
|
3544
|
+
let call = accumulator.toolCalls.find((entry) => entry.index === index);
|
|
3545
|
+
if (!call) {
|
|
3546
|
+
call = {
|
|
3547
|
+
index,
|
|
3548
|
+
id: toolDelta.id ?? `call_${index}`,
|
|
3549
|
+
name: "",
|
|
3550
|
+
arguments: "",
|
|
3551
|
+
rawChunkCount: 0
|
|
3552
|
+
};
|
|
3553
|
+
accumulator.toolCalls.push(call);
|
|
3554
|
+
accumulator.toolCalls.sort((left, right) => left.index - right.index);
|
|
3555
|
+
}
|
|
3556
|
+
call.rawChunkCount += 1;
|
|
3557
|
+
if (toolDelta.id) call.id = toolDelta.id;
|
|
3558
|
+
if (typeof toolDelta.function?.name === "string") {
|
|
3559
|
+
call.name = toolDelta.function.name;
|
|
3560
|
+
}
|
|
3561
|
+
if (typeof toolDelta.function?.arguments === "string") {
|
|
3562
|
+
call.arguments += toolDelta.function.arguments;
|
|
3563
|
+
}
|
|
3564
|
+
}
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
function toMoonshotChatInvokeCompletion(accumulator, meta) {
|
|
3568
|
+
const messages = [];
|
|
3569
|
+
if (accumulator.reasoningContent) {
|
|
3570
|
+
messages.push({
|
|
3571
|
+
role: "reasoning",
|
|
3572
|
+
content: accumulator.reasoningContent,
|
|
3573
|
+
raw_item: {
|
|
3574
|
+
provider: "moonshot",
|
|
3575
|
+
field: "reasoning_content",
|
|
3576
|
+
response_id: accumulator.id
|
|
3577
|
+
}
|
|
3578
|
+
});
|
|
3579
|
+
}
|
|
3580
|
+
const toolCalls = accumulator.toolCalls.map(toToolCall);
|
|
3581
|
+
if (accumulator.content || toolCalls.length) {
|
|
3582
|
+
messages.push({
|
|
3583
|
+
role: "assistant",
|
|
3584
|
+
content: accumulator.content || null,
|
|
3585
|
+
...toolCalls.length ? { tool_calls: toolCalls } : {}
|
|
3586
|
+
});
|
|
3587
|
+
}
|
|
3588
|
+
return {
|
|
3589
|
+
messages,
|
|
3590
|
+
usage: normalizeUsage(accumulator),
|
|
3591
|
+
stop_reason: accumulator.finishReason ?? null,
|
|
3592
|
+
provider_meta: {
|
|
3593
|
+
response_id: accumulator.id,
|
|
3594
|
+
finish_reason: accumulator.finishReason ?? null,
|
|
3595
|
+
reasoning_requested: meta.reasoningRequested,
|
|
3596
|
+
reasoning_applied: "max",
|
|
3597
|
+
reasoning_effort: "max",
|
|
3598
|
+
reasoning_fallback: meta.reasoningFallback
|
|
3599
|
+
}
|
|
3600
|
+
};
|
|
3601
|
+
}
|
|
3602
|
+
var toReplayToolCalls = (toolCalls) => (toolCalls ?? []).map((call) => ({
|
|
3603
|
+
id: call.id,
|
|
3604
|
+
type: "function",
|
|
3605
|
+
function: { ...call.function }
|
|
3606
|
+
}));
|
|
3607
|
+
var toToolCall = (call) => ({
|
|
3608
|
+
id: call.id,
|
|
3609
|
+
type: "function",
|
|
3610
|
+
function: { name: call.name, arguments: call.arguments },
|
|
3611
|
+
provider_meta: {
|
|
3612
|
+
provider: "moonshot",
|
|
3613
|
+
index: call.index,
|
|
3614
|
+
raw_chunk_count: call.rawChunkCount
|
|
3615
|
+
}
|
|
3616
|
+
});
|
|
3617
|
+
var normalizeNumber = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0;
|
|
3618
|
+
var normalizeUsage = (accumulator) => {
|
|
3619
|
+
const usage = accumulator.usage;
|
|
3620
|
+
if (!usage) return null;
|
|
3621
|
+
const inputTokens = normalizeNumber(usage.prompt_tokens);
|
|
3622
|
+
const outputTokens = normalizeNumber(usage.completion_tokens);
|
|
3623
|
+
const cachedTokens = normalizeNumber(
|
|
3624
|
+
usage.cached_tokens ?? usage.prompt_tokens_details?.cached_tokens
|
|
3625
|
+
);
|
|
3626
|
+
return {
|
|
3627
|
+
model: accumulator.model ?? "",
|
|
3628
|
+
input_tokens: inputTokens,
|
|
3629
|
+
...cachedTokens > 0 ? { input_cached_tokens: cachedTokens } : {},
|
|
3630
|
+
output_tokens: outputTokens,
|
|
3631
|
+
total_tokens: typeof usage.total_tokens === "number" ? normalizeNumber(usage.total_tokens) : inputTokens + outputTokens
|
|
3632
|
+
};
|
|
3633
|
+
};
|
|
3634
|
+
|
|
3635
|
+
// src/llm/moonshot/chat.ts
|
|
3636
|
+
var PROVIDER_NAME4 = "moonshot";
|
|
3637
|
+
var DEFAULT_BASE_URL = "https://api.moonshot.ai/v1";
|
|
3638
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 2 * 60 * 60 * 1e3;
|
|
3639
|
+
var ChatMoonshot = class {
|
|
3640
|
+
provider = PROVIDER_NAME4;
|
|
3641
|
+
model;
|
|
3642
|
+
classifyFailure = classifyMoonshotFailure;
|
|
3643
|
+
apiKey;
|
|
3644
|
+
clientOptions;
|
|
3645
|
+
reasoningLevelRequested;
|
|
3646
|
+
debugInvokeSeq = 0;
|
|
3647
|
+
lastDebugRequestPayload = null;
|
|
3648
|
+
constructor(options = {}) {
|
|
3649
|
+
this.apiKey = options.apiKey;
|
|
3650
|
+
this.model = options.model ?? MOONSHOT_DEFAULT_MODEL;
|
|
3651
|
+
this.reasoningLevelRequested = options.reasoningLevelRequested ?? "medium";
|
|
3652
|
+
this.clientOptions = {
|
|
3653
|
+
baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
|
|
3654
|
+
timeout: options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
3655
|
+
maxRetries: options.maxRetries ?? 0,
|
|
3656
|
+
...options.fetch ? { fetch: options.fetch } : {}
|
|
3657
|
+
};
|
|
3658
|
+
}
|
|
3659
|
+
async ainvoke(input) {
|
|
3660
|
+
if (!this.apiKey) {
|
|
3661
|
+
throw new Error("Moonshot API key is required");
|
|
3662
|
+
}
|
|
3663
|
+
const tools = toMoonshotTools(input.tools);
|
|
3664
|
+
const toolChoice = toMoonshotToolChoice(input.toolChoice);
|
|
3665
|
+
const request = {
|
|
3666
|
+
model: input.model ?? this.model,
|
|
3667
|
+
messages: toMoonshotMessages(input.messages),
|
|
3668
|
+
stream: true,
|
|
3669
|
+
stream_options: { include_usage: true },
|
|
3670
|
+
reasoning_effort: "max",
|
|
3671
|
+
...input.options ?? {},
|
|
3672
|
+
...tools ? { tools } : {},
|
|
3673
|
+
...toolChoice ? { tool_choice: toolChoice } : {}
|
|
3674
|
+
};
|
|
3675
|
+
const seq = this.nextDebugInvokeSeq();
|
|
3676
|
+
await this.debugRequestIfEnabled(request, seq);
|
|
3677
|
+
const client = new import_openai3.default({ apiKey: this.apiKey, ...this.clientOptions });
|
|
3678
|
+
const accumulator = createMoonshotStreamAccumulator();
|
|
3679
|
+
try {
|
|
3680
|
+
const stream = await client.chat.completions.create(
|
|
3681
|
+
request,
|
|
3682
|
+
{ signal: input.signal }
|
|
3683
|
+
);
|
|
3684
|
+
for await (const chunk of stream) {
|
|
3685
|
+
appendMoonshotChatCompletionChunk(
|
|
3686
|
+
accumulator,
|
|
3687
|
+
chunk
|
|
3688
|
+
);
|
|
3689
|
+
}
|
|
3690
|
+
} catch (error) {
|
|
3691
|
+
const failure = classifyMoonshotFailure(error);
|
|
3692
|
+
throw new ProviderFailureError(
|
|
3693
|
+
accumulator.rawChunkCount > 0 ? { ...failure, retryable: false, delivery: "buffered" } : failure,
|
|
3694
|
+
{ cause: error }
|
|
3695
|
+
);
|
|
3696
|
+
}
|
|
3697
|
+
await this.debugResponseIfEnabled(accumulator, seq);
|
|
3698
|
+
return toMoonshotChatInvokeCompletion(accumulator, {
|
|
3699
|
+
reasoningRequested: this.reasoningLevelRequested,
|
|
3700
|
+
reasoningFallback: this.reasoningLevelRequested !== "max"
|
|
3701
|
+
});
|
|
3702
|
+
}
|
|
3703
|
+
nextDebugInvokeSeq() {
|
|
3704
|
+
this.debugInvokeSeq += 1;
|
|
3705
|
+
return this.debugInvokeSeq;
|
|
3706
|
+
}
|
|
3707
|
+
async debugRequestIfEnabled(request, seq) {
|
|
3708
|
+
const settings = getProviderLogSettings();
|
|
3709
|
+
if (!settings.enabled && !settings.dumpDir) return;
|
|
3710
|
+
const payload = safeJsonStringify(request);
|
|
3711
|
+
const hash = (0, import_node_crypto2.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3712
|
+
const previous = this.lastDebugRequestPayload;
|
|
3713
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
2614
3714
|
if (settings.enabled) {
|
|
2615
3715
|
console.error(
|
|
2616
|
-
`[
|
|
3716
|
+
`[moonshot.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared}`
|
|
2617
3717
|
);
|
|
2618
3718
|
}
|
|
2619
3719
|
if (settings.dumpDir) {
|
|
2620
3720
|
try {
|
|
2621
3721
|
await writeProviderLogDump(
|
|
2622
3722
|
settings,
|
|
2623
|
-
|
|
3723
|
+
PROVIDER_NAME4,
|
|
2624
3724
|
seq,
|
|
2625
3725
|
"request",
|
|
2626
3726
|
request
|
|
@@ -2628,7 +3728,7 @@ var ChatAnthropic = class {
|
|
|
2628
3728
|
} catch (error) {
|
|
2629
3729
|
if (settings.enabled) {
|
|
2630
3730
|
console.error(
|
|
2631
|
-
`[
|
|
3731
|
+
`[moonshot.request] dump_failed seq=${seq} error=${String(error)}`
|
|
2632
3732
|
);
|
|
2633
3733
|
}
|
|
2634
3734
|
}
|
|
@@ -2637,30 +3737,17 @@ var ChatAnthropic = class {
|
|
|
2637
3737
|
}
|
|
2638
3738
|
async debugResponseIfEnabled(response, seq) {
|
|
2639
3739
|
const settings = getProviderLogSettings();
|
|
2640
|
-
if (!settings.enabled && !settings.dumpDir)
|
|
2641
|
-
return;
|
|
2642
|
-
}
|
|
3740
|
+
if (!settings.enabled && !settings.dumpDir) return;
|
|
2643
3741
|
if (settings.enabled) {
|
|
2644
|
-
const usage = response.usage;
|
|
2645
|
-
const inputTokens = usage?.input_tokens ?? 0;
|
|
2646
|
-
const outputTokens = usage?.output_tokens ?? 0;
|
|
2647
|
-
const cachedRead = usage?.cache_read_input_tokens ?? 0;
|
|
2648
|
-
const cachedCreate = usage?.cache_creation_input_tokens ?? 0;
|
|
2649
|
-
const blocks = Array.isArray(response.content) ? response.content : [];
|
|
2650
|
-
const blockKinds = /* @__PURE__ */ new Set();
|
|
2651
|
-
for (const block of blocks) {
|
|
2652
|
-
const kind = block && typeof block === "object" && "type" in block ? String(block.type ?? "unknown") : "unknown";
|
|
2653
|
-
blockKinds.add(kind);
|
|
2654
|
-
}
|
|
2655
3742
|
console.error(
|
|
2656
|
-
`[
|
|
3743
|
+
`[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}`
|
|
2657
3744
|
);
|
|
2658
3745
|
}
|
|
2659
3746
|
if (settings.dumpDir) {
|
|
2660
3747
|
try {
|
|
2661
3748
|
await writeProviderLogDump(
|
|
2662
3749
|
settings,
|
|
2663
|
-
|
|
3750
|
+
PROVIDER_NAME4,
|
|
2664
3751
|
seq,
|
|
2665
3752
|
"response",
|
|
2666
3753
|
response
|
|
@@ -2668,7 +3755,7 @@ var ChatAnthropic = class {
|
|
|
2668
3755
|
} catch (error) {
|
|
2669
3756
|
if (settings.enabled) {
|
|
2670
3757
|
console.error(
|
|
2671
|
-
`[
|
|
3758
|
+
`[moonshot.response] dump_failed seq=${seq} error=${String(error)}`
|
|
2672
3759
|
);
|
|
2673
3760
|
}
|
|
2674
3761
|
}
|
|
@@ -2677,8 +3764,8 @@ var ChatAnthropic = class {
|
|
|
2677
3764
|
};
|
|
2678
3765
|
|
|
2679
3766
|
// src/llm/openai/chat.ts
|
|
2680
|
-
var
|
|
2681
|
-
var
|
|
3767
|
+
var import_node_crypto3 = require("crypto");
|
|
3768
|
+
var import_openai4 = __toESM(require("openai"), 1);
|
|
2682
3769
|
|
|
2683
3770
|
// src/llm/openai/response-utils.ts
|
|
2684
3771
|
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
@@ -3534,7 +4621,7 @@ function toResponsesTools(tools) {
|
|
|
3534
4621
|
});
|
|
3535
4622
|
continue;
|
|
3536
4623
|
}
|
|
3537
|
-
if (
|
|
4624
|
+
if (isHostedWebSearchToolDefinition(tool)) {
|
|
3538
4625
|
const hosted = toOpenAiHostedSearchTool(tool);
|
|
3539
4626
|
if (hosted) {
|
|
3540
4627
|
mapped.push(hosted);
|
|
@@ -3723,6 +4810,7 @@ var WsResponseError = class extends Error {
|
|
|
3723
4810
|
super(message);
|
|
3724
4811
|
this.code = code;
|
|
3725
4812
|
}
|
|
4813
|
+
code;
|
|
3726
4814
|
};
|
|
3727
4815
|
var OpenAiWsTransport = class {
|
|
3728
4816
|
client;
|
|
@@ -3871,7 +4959,7 @@ var OpenAiWsTransport = class {
|
|
|
3871
4959
|
}
|
|
3872
4960
|
settled = true;
|
|
3873
4961
|
teardown();
|
|
3874
|
-
reject(new
|
|
4962
|
+
reject(new ProviderTimeoutError("openai websocket response timeout"));
|
|
3875
4963
|
}, this.wsResponseIdleTimeoutMs);
|
|
3876
4964
|
};
|
|
3877
4965
|
rejectResponsePromise = rejectOnce;
|
|
@@ -4373,7 +5461,9 @@ var OpenAiWsTransport = class {
|
|
|
4373
5461
|
}
|
|
4374
5462
|
};
|
|
4375
5463
|
const timeout = setTimeout(() => {
|
|
4376
|
-
settleReject(
|
|
5464
|
+
settleReject(
|
|
5465
|
+
new ProviderTimeoutError("openai websocket connect timeout")
|
|
5466
|
+
);
|
|
4377
5467
|
}, this.wsConnectTimeoutMs);
|
|
4378
5468
|
addSocketListener("open", () => {
|
|
4379
5469
|
settleResolve();
|
|
@@ -4411,7 +5501,7 @@ var OpenAiWsTransport = class {
|
|
|
4411
5501
|
};
|
|
4412
5502
|
|
|
4413
5503
|
// src/llm/openai/chat.ts
|
|
4414
|
-
var
|
|
5504
|
+
var PROVIDER_NAME5 = "openai";
|
|
4415
5505
|
var DEFAULT_MODEL2 = OPENAI_DEFAULT_MODEL;
|
|
4416
5506
|
var DEFAULT_REASONING_EFFORT = OPENAI_DEFAULT_REASONING_EFFORT;
|
|
4417
5507
|
var DEFAULT_REASONING_SUMMARY = "auto";
|
|
@@ -4422,8 +5512,9 @@ var WS_SESSION_IDLE_TTL_MS = 10 * 6e4;
|
|
|
4422
5512
|
var WS_SESSION_DISABLE_TTL_MS = 6e4;
|
|
4423
5513
|
var WS_REUSE_MAX_IDLE_MS = 3e4;
|
|
4424
5514
|
var ChatOpenAI = class {
|
|
4425
|
-
provider =
|
|
5515
|
+
provider = PROVIDER_NAME5;
|
|
4426
5516
|
model;
|
|
5517
|
+
classifyFailure = (error) => classifyOpenAiCompatibleFailure(PROVIDER_NAME5, error);
|
|
4427
5518
|
providerModel;
|
|
4428
5519
|
client;
|
|
4429
5520
|
defaultReasoningEffort;
|
|
@@ -4439,7 +5530,10 @@ var ChatOpenAI = class {
|
|
|
4439
5530
|
wsDisabledUntilBySessionKey = /* @__PURE__ */ new Map();
|
|
4440
5531
|
wsReconnectCount = 0;
|
|
4441
5532
|
constructor(options = {}) {
|
|
4442
|
-
this.client = options.client ?? new
|
|
5533
|
+
this.client = options.client ?? new import_openai4.default({
|
|
5534
|
+
...options.clientOptions ?? {},
|
|
5535
|
+
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
5536
|
+
});
|
|
4443
5537
|
this.model = options.model ?? DEFAULT_MODEL2;
|
|
4444
5538
|
this.providerModel = options.providerModel ?? this.model;
|
|
4445
5539
|
this.defaultReasoningEffort = options.reasoningEffort ?? DEFAULT_REASONING_EFFORT;
|
|
@@ -4519,8 +5613,8 @@ var ChatOpenAI = class {
|
|
|
4519
5613
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
4520
5614
|
const requestMeta = {
|
|
4521
5615
|
model: String(request.model ?? this.providerModel),
|
|
4522
|
-
instructionsHash: (0,
|
|
4523
|
-
toolsHash: (0,
|
|
5616
|
+
instructionsHash: (0, import_node_crypto3.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12),
|
|
5617
|
+
toolsHash: (0, import_node_crypto3.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12)
|
|
4524
5618
|
};
|
|
4525
5619
|
const transportResult = await this.invokeWithTransport({
|
|
4526
5620
|
request,
|
|
@@ -4883,14 +5977,14 @@ var ChatOpenAI = class {
|
|
|
4883
5977
|
return;
|
|
4884
5978
|
}
|
|
4885
5979
|
const payload = safeJsonStringify(request);
|
|
4886
|
-
const hash = (0,
|
|
4887
|
-
const toolsHash = (0,
|
|
4888
|
-
const instructionsHash = (0,
|
|
5980
|
+
const hash = (0, import_node_crypto3.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
5981
|
+
const toolsHash = (0, import_node_crypto3.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
5982
|
+
const instructionsHash = (0, import_node_crypto3.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
4889
5983
|
const previous = this.lastDebugRequestPayload;
|
|
4890
5984
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
4891
5985
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
4892
5986
|
if (settings.enabled) {
|
|
4893
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0,
|
|
5987
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto3.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
4894
5988
|
const chainResetSuffix = typeof chainReset === "boolean" ? ` chain_reset=${chainReset ? "true" : "false"}` : "";
|
|
4895
5989
|
const wsInputModeSuffix = wsInputMode ? ` ws_input_mode=${wsInputMode}` : "";
|
|
4896
5990
|
console.error(
|
|
@@ -4901,7 +5995,7 @@ var ChatOpenAI = class {
|
|
|
4901
5995
|
try {
|
|
4902
5996
|
await writeProviderLogDump(
|
|
4903
5997
|
settings,
|
|
4904
|
-
|
|
5998
|
+
PROVIDER_NAME5,
|
|
4905
5999
|
seq,
|
|
4906
6000
|
"request",
|
|
4907
6001
|
request
|
|
@@ -4939,7 +6033,7 @@ var ChatOpenAI = class {
|
|
|
4939
6033
|
try {
|
|
4940
6034
|
await writeProviderLogDump(
|
|
4941
6035
|
settings,
|
|
4942
|
-
|
|
6036
|
+
PROVIDER_NAME5,
|
|
4943
6037
|
seq,
|
|
4944
6038
|
"response",
|
|
4945
6039
|
response
|
|
@@ -4983,8 +6077,8 @@ var ChatOpenAI = class {
|
|
|
4983
6077
|
};
|
|
4984
6078
|
|
|
4985
6079
|
// src/llm/openrouter/chat.ts
|
|
4986
|
-
var
|
|
4987
|
-
var
|
|
6080
|
+
var import_node_crypto4 = require("crypto");
|
|
6081
|
+
var import_openai6 = __toESM(require("openai"), 1);
|
|
4988
6082
|
|
|
4989
6083
|
// src/llm/openrouter/response-utils.ts
|
|
4990
6084
|
var isRecord4 = (value) => typeof value === "object" && value !== null;
|
|
@@ -5319,7 +6413,7 @@ function toResponsesTools2(tools) {
|
|
|
5319
6413
|
});
|
|
5320
6414
|
continue;
|
|
5321
6415
|
}
|
|
5322
|
-
if (
|
|
6416
|
+
if (isHostedWebSearchToolDefinition(tool)) {
|
|
5323
6417
|
const hosted = toOpenRouterHostedSearchTool(tool);
|
|
5324
6418
|
if (hosted) {
|
|
5325
6419
|
mapped.push(hosted);
|
|
@@ -5433,7 +6527,7 @@ function toOpenRouterHostedSearchTool(tool) {
|
|
|
5433
6527
|
}
|
|
5434
6528
|
|
|
5435
6529
|
// src/llm/openrouter/chat.ts
|
|
5436
|
-
var
|
|
6530
|
+
var PROVIDER_NAME6 = "openrouter";
|
|
5437
6531
|
var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
|
|
5438
6532
|
var DEFAULT_MODEL3 = OPENAI_DEFAULT_MODEL;
|
|
5439
6533
|
var DEFAULT_REASONING_EFFORT2 = OPENAI_DEFAULT_REASONING_EFFORT;
|
|
@@ -5442,8 +6536,9 @@ var getSessionIdHeaderValue2 = (promptCacheKey) => {
|
|
|
5442
6536
|
return typeof promptCacheKey === "string" && promptCacheKey.length > 0 ? promptCacheKey : void 0;
|
|
5443
6537
|
};
|
|
5444
6538
|
var ChatOpenRouter = class {
|
|
5445
|
-
provider =
|
|
6539
|
+
provider = PROVIDER_NAME6;
|
|
5446
6540
|
model;
|
|
6541
|
+
classifyFailure = (error) => classifyOpenAiCompatibleFailure(PROVIDER_NAME6, error);
|
|
5447
6542
|
client;
|
|
5448
6543
|
defaultReasoningEffort;
|
|
5449
6544
|
reasoningLevelMeta;
|
|
@@ -5451,9 +6546,10 @@ var ChatOpenRouter = class {
|
|
|
5451
6546
|
debugInvokeSeq = 0;
|
|
5452
6547
|
lastDebugRequestPayload = null;
|
|
5453
6548
|
constructor(options = {}) {
|
|
5454
|
-
this.client = options.client ?? new
|
|
6549
|
+
this.client = options.client ?? new import_openai6.default({
|
|
5455
6550
|
baseURL: OPENROUTER_BASE_URL,
|
|
5456
|
-
...options.clientOptions ?? {}
|
|
6551
|
+
...options.clientOptions ?? {},
|
|
6552
|
+
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
5457
6553
|
});
|
|
5458
6554
|
this.model = options.model ?? DEFAULT_MODEL3;
|
|
5459
6555
|
this.defaultReasoningEffort = options.reasoningEffort ?? DEFAULT_REASONING_EFFORT2;
|
|
@@ -5551,14 +6647,14 @@ var ChatOpenRouter = class {
|
|
|
5551
6647
|
return;
|
|
5552
6648
|
}
|
|
5553
6649
|
const payload = safeJsonStringify(request);
|
|
5554
|
-
const hash = (0,
|
|
5555
|
-
const toolsHash = (0,
|
|
5556
|
-
const instructionsHash = (0,
|
|
6650
|
+
const hash = (0, import_node_crypto4.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
6651
|
+
const toolsHash = (0, import_node_crypto4.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
6652
|
+
const instructionsHash = (0, import_node_crypto4.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
5557
6653
|
const previous = this.lastDebugRequestPayload;
|
|
5558
6654
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
5559
6655
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
5560
6656
|
if (settings.enabled) {
|
|
5561
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0,
|
|
6657
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto4.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
5562
6658
|
console.error(
|
|
5563
6659
|
`[openrouter.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
5564
6660
|
);
|
|
@@ -5567,7 +6663,7 @@ var ChatOpenRouter = class {
|
|
|
5567
6663
|
try {
|
|
5568
6664
|
await writeProviderLogDump(
|
|
5569
6665
|
settings,
|
|
5570
|
-
|
|
6666
|
+
PROVIDER_NAME6,
|
|
5571
6667
|
seq,
|
|
5572
6668
|
"request",
|
|
5573
6669
|
request
|
|
@@ -5605,7 +6701,7 @@ var ChatOpenRouter = class {
|
|
|
5605
6701
|
try {
|
|
5606
6702
|
await writeProviderLogDump(
|
|
5607
6703
|
settings,
|
|
5608
|
-
|
|
6704
|
+
PROVIDER_NAME6,
|
|
5609
6705
|
seq,
|
|
5610
6706
|
"response",
|
|
5611
6707
|
response
|
|
@@ -5621,8 +6717,431 @@ var ChatOpenRouter = class {
|
|
|
5621
6717
|
}
|
|
5622
6718
|
};
|
|
5623
6719
|
|
|
6720
|
+
// src/llm/xai/chat.ts
|
|
6721
|
+
var import_node_crypto5 = require("crypto");
|
|
6722
|
+
var import_openai8 = __toESM(require("openai"), 1);
|
|
6723
|
+
|
|
6724
|
+
// src/llm/xai/serializer.ts
|
|
6725
|
+
var XAI_SUPPORTED_INLINE_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
|
|
6726
|
+
"image/jpeg",
|
|
6727
|
+
"image/png"
|
|
6728
|
+
]);
|
|
6729
|
+
var XAI_MAX_WEB_SEARCH_ALLOWED_DOMAINS = 5;
|
|
6730
|
+
var XAI_MAX_X_SEARCH_HANDLES = 20;
|
|
6731
|
+
var mapOtherPartProvider = (part, from, to) => part.type === "other" && part.provider === from ? { ...part, provider: to } : part;
|
|
6732
|
+
var mapMessageOtherParts = (message, from, to) => {
|
|
6733
|
+
if (!Array.isArray(message.content)) {
|
|
6734
|
+
return message;
|
|
6735
|
+
}
|
|
6736
|
+
return {
|
|
6737
|
+
...message,
|
|
6738
|
+
content: message.content.map(
|
|
6739
|
+
(part) => mapOtherPartProvider(part, from, to)
|
|
6740
|
+
)
|
|
6741
|
+
};
|
|
6742
|
+
};
|
|
6743
|
+
var assertSupportedInlineImage = (part) => {
|
|
6744
|
+
if (part.type !== "image_url") return;
|
|
6745
|
+
const declaredMediaType = part.image_url.media_type?.toLowerCase();
|
|
6746
|
+
const dataUrlMatch = /^data:([^;,]+)[;,]/i.exec(part.image_url.url);
|
|
6747
|
+
const inlineMediaType = dataUrlMatch?.[1]?.toLowerCase();
|
|
6748
|
+
const mediaType = inlineMediaType ?? declaredMediaType;
|
|
6749
|
+
if (part.image_url.url.startsWith("data:") && (!mediaType || !XAI_SUPPORTED_INLINE_IMAGE_MEDIA_TYPES.has(mediaType))) {
|
|
6750
|
+
throw createProviderValidationError(
|
|
6751
|
+
"xai",
|
|
6752
|
+
`xAI image input supports inline image/jpeg and image/png only; received ${mediaType ?? "unknown media type"}`
|
|
6753
|
+
);
|
|
6754
|
+
}
|
|
6755
|
+
};
|
|
6756
|
+
var assertSupportedImages = (messages) => {
|
|
6757
|
+
for (const message of messages) {
|
|
6758
|
+
if (!Array.isArray(message.content)) continue;
|
|
6759
|
+
for (const part of message.content) {
|
|
6760
|
+
assertSupportedInlineImage(part);
|
|
6761
|
+
}
|
|
6762
|
+
}
|
|
6763
|
+
};
|
|
6764
|
+
var toXaiResponsesInput = (messages) => {
|
|
6765
|
+
assertSupportedImages(messages);
|
|
6766
|
+
const input = [];
|
|
6767
|
+
for (const message of messages) {
|
|
6768
|
+
if (message.role === "reasoning" && isXSearchCall(message.raw_item)) {
|
|
6769
|
+
input.push(message.raw_item);
|
|
6770
|
+
continue;
|
|
6771
|
+
}
|
|
6772
|
+
input.push(
|
|
6773
|
+
...toResponsesInput([mapMessageOtherParts(message, "xai", "openai")])
|
|
6774
|
+
);
|
|
6775
|
+
}
|
|
6776
|
+
return input;
|
|
6777
|
+
};
|
|
6778
|
+
var normalizeXSearchHandles = (values, field) => {
|
|
6779
|
+
if (!values?.length) return void 0;
|
|
6780
|
+
const normalized = Array.from(
|
|
6781
|
+
new Set(values.map((value) => value.trim().replace(/^@/, "")))
|
|
6782
|
+
);
|
|
6783
|
+
if (normalized.some((value) => value.length === 0)) {
|
|
6784
|
+
throw createProviderValidationError(
|
|
6785
|
+
"xai",
|
|
6786
|
+
`xAI X Search ${field} must not contain empty handles`
|
|
6787
|
+
);
|
|
6788
|
+
}
|
|
6789
|
+
const invalid = normalized.find((value) => !/^[A-Za-z0-9_]+$/.test(value));
|
|
6790
|
+
if (invalid) {
|
|
6791
|
+
throw createProviderValidationError(
|
|
6792
|
+
"xai",
|
|
6793
|
+
`xAI X Search ${field} must contain bare X handles; received ${invalid}`
|
|
6794
|
+
);
|
|
6795
|
+
}
|
|
6796
|
+
if (normalized.length > XAI_MAX_X_SEARCH_HANDLES) {
|
|
6797
|
+
throw createProviderValidationError(
|
|
6798
|
+
"xai",
|
|
6799
|
+
`xAI X Search supports at most ${XAI_MAX_X_SEARCH_HANDLES} ${field}; received ${normalized.length}`
|
|
6800
|
+
);
|
|
6801
|
+
}
|
|
6802
|
+
return normalized;
|
|
6803
|
+
};
|
|
6804
|
+
var isIsoDate = (value) => {
|
|
6805
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
6806
|
+
if (!match) return false;
|
|
6807
|
+
const year = Number(match[1]);
|
|
6808
|
+
const month = Number(match[2]);
|
|
6809
|
+
const day = Number(match[3]);
|
|
6810
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
6811
|
+
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
|
|
6812
|
+
};
|
|
6813
|
+
var assertXSearchDate = (value, field) => {
|
|
6814
|
+
if (value !== void 0 && !isIsoDate(value)) {
|
|
6815
|
+
throw createProviderValidationError(
|
|
6816
|
+
"xai",
|
|
6817
|
+
`xAI X Search ${field} must use a valid YYYY-MM-DD date; received ${value}`
|
|
6818
|
+
);
|
|
6819
|
+
}
|
|
6820
|
+
};
|
|
6821
|
+
var toXaiXSearchTool = (tool) => {
|
|
6822
|
+
const allowedXHandles = normalizeXSearchHandles(
|
|
6823
|
+
tool.allowed_x_handles,
|
|
6824
|
+
"allowed_x_handles"
|
|
6825
|
+
);
|
|
6826
|
+
const excludedXHandles = normalizeXSearchHandles(
|
|
6827
|
+
tool.excluded_x_handles,
|
|
6828
|
+
"excluded_x_handles"
|
|
6829
|
+
);
|
|
6830
|
+
if (allowedXHandles && excludedXHandles) {
|
|
6831
|
+
throw createProviderValidationError(
|
|
6832
|
+
"xai",
|
|
6833
|
+
"xAI X Search allowed_x_handles and excluded_x_handles are mutually exclusive"
|
|
6834
|
+
);
|
|
6835
|
+
}
|
|
6836
|
+
assertXSearchDate(tool.from_date, "from_date");
|
|
6837
|
+
assertXSearchDate(tool.to_date, "to_date");
|
|
6838
|
+
if (tool.from_date && tool.to_date && tool.from_date > tool.to_date) {
|
|
6839
|
+
throw createProviderValidationError(
|
|
6840
|
+
"xai",
|
|
6841
|
+
"xAI X Search from_date must be on or before to_date"
|
|
6842
|
+
);
|
|
6843
|
+
}
|
|
6844
|
+
return {
|
|
6845
|
+
type: "x_search",
|
|
6846
|
+
...allowedXHandles ? { allowed_x_handles: allowedXHandles } : {},
|
|
6847
|
+
...excludedXHandles ? { excluded_x_handles: excludedXHandles } : {},
|
|
6848
|
+
...tool.from_date ? { from_date: tool.from_date } : {},
|
|
6849
|
+
...tool.to_date ? { to_date: tool.to_date } : {},
|
|
6850
|
+
...typeof tool.enable_image_understanding === "boolean" ? { enable_image_understanding: tool.enable_image_understanding } : {},
|
|
6851
|
+
...typeof tool.enable_video_understanding === "boolean" ? { enable_video_understanding: tool.enable_video_understanding } : {}
|
|
6852
|
+
};
|
|
6853
|
+
};
|
|
6854
|
+
var toXaiWebSearchTool = (tool) => {
|
|
6855
|
+
if ((tool.allowed_domains?.length ?? 0) > XAI_MAX_WEB_SEARCH_ALLOWED_DOMAINS) {
|
|
6856
|
+
throw createProviderValidationError(
|
|
6857
|
+
"xai",
|
|
6858
|
+
`xAI web search supports at most ${XAI_MAX_WEB_SEARCH_ALLOWED_DOMAINS} allowed_domains; received ${tool.allowed_domains?.length ?? 0}`
|
|
6859
|
+
);
|
|
6860
|
+
}
|
|
6861
|
+
return {
|
|
6862
|
+
type: "web_search",
|
|
6863
|
+
...tool.allowed_domains?.length ? { filters: { allowed_domains: tool.allowed_domains } } : {}
|
|
6864
|
+
};
|
|
6865
|
+
};
|
|
6866
|
+
var toXaiResponsesTools = (tools) => {
|
|
6867
|
+
if (!tools?.length) return void 0;
|
|
6868
|
+
const mapped = [];
|
|
6869
|
+
for (const tool of tools) {
|
|
6870
|
+
if (isHostedXSearchToolDefinition(tool)) {
|
|
6871
|
+
mapped.push(toXaiXSearchTool(tool));
|
|
6872
|
+
continue;
|
|
6873
|
+
}
|
|
6874
|
+
if (!isHostedWebSearchToolDefinition(tool) || tool.provider !== "xai") {
|
|
6875
|
+
const serialized = toResponsesTools([tool]);
|
|
6876
|
+
if (serialized?.[0]) mapped.push(serialized[0]);
|
|
6877
|
+
continue;
|
|
6878
|
+
}
|
|
6879
|
+
mapped.push(toXaiWebSearchTool(tool));
|
|
6880
|
+
}
|
|
6881
|
+
return mapped.length ? mapped : void 0;
|
|
6882
|
+
};
|
|
6883
|
+
var toXaiResponsesToolChoice = (choice) => toResponsesToolChoice(choice);
|
|
6884
|
+
var toXaiChatInvokeCompletion = (response, meta) => {
|
|
6885
|
+
const completion = toChatInvokeCompletion2(response, {
|
|
6886
|
+
transport: "http_stream",
|
|
6887
|
+
...meta
|
|
6888
|
+
});
|
|
6889
|
+
const messages = completion.messages.map((message, index) => {
|
|
6890
|
+
const item = response.output[index];
|
|
6891
|
+
if (isXSearchCall(item)) {
|
|
6892
|
+
return {
|
|
6893
|
+
role: "reasoning",
|
|
6894
|
+
content: extractXSearchSummary(item),
|
|
6895
|
+
raw_item: item
|
|
6896
|
+
};
|
|
6897
|
+
}
|
|
6898
|
+
return mapMessageOtherParts(message, "openai", "xai");
|
|
6899
|
+
});
|
|
6900
|
+
const citations = response.output.flatMap((item) => {
|
|
6901
|
+
if (item.type !== "message") return [];
|
|
6902
|
+
return item.content.flatMap(
|
|
6903
|
+
(part) => part.type === "output_text" && Array.isArray(part.annotations) ? part.annotations : []
|
|
6904
|
+
);
|
|
6905
|
+
});
|
|
6906
|
+
return {
|
|
6907
|
+
...completion,
|
|
6908
|
+
messages,
|
|
6909
|
+
provider_meta: {
|
|
6910
|
+
...completion.provider_meta,
|
|
6911
|
+
...citations.length ? { citations } : {}
|
|
6912
|
+
}
|
|
6913
|
+
};
|
|
6914
|
+
};
|
|
6915
|
+
var isXSearchCall = (value) => Boolean(
|
|
6916
|
+
value && typeof value === "object" && value.type === "x_search_call"
|
|
6917
|
+
);
|
|
6918
|
+
var extractXSearchSummary = (item) => {
|
|
6919
|
+
const status = typeof item.status === "string" ? item.status : "completed";
|
|
6920
|
+
const parts = [`XSearch status=${status}`];
|
|
6921
|
+
const queries = Array.isArray(item.action?.queries) ? item.action.queries.filter(
|
|
6922
|
+
(value) => typeof value === "string" && value.length > 0
|
|
6923
|
+
) : [];
|
|
6924
|
+
if (queries.length) parts.push(`queries=${queries.join(" | ")}`);
|
|
6925
|
+
if (Array.isArray(item.action?.sources)) {
|
|
6926
|
+
parts.push(`sources=${item.action.sources.length}`);
|
|
6927
|
+
}
|
|
6928
|
+
return parts.join(" | ");
|
|
6929
|
+
};
|
|
6930
|
+
|
|
6931
|
+
// src/llm/xai/chat.ts
|
|
6932
|
+
var PROVIDER_NAME7 = "xai";
|
|
6933
|
+
var XAI_BASE_URL = "https://api.x.ai/v1";
|
|
6934
|
+
var DEFAULT_REQUEST_TIMEOUT_MS2 = 60 * 60 * 1e3;
|
|
6935
|
+
var ChatXai = class {
|
|
6936
|
+
provider = PROVIDER_NAME7;
|
|
6937
|
+
model;
|
|
6938
|
+
classifyFailure = (error) => classifyOpenAiCompatibleFailure(PROVIDER_NAME7, error);
|
|
6939
|
+
client;
|
|
6940
|
+
defaultReasoningEffort;
|
|
6941
|
+
reasoningLevelMeta;
|
|
6942
|
+
debugInvokeSeq = 0;
|
|
6943
|
+
lastDebugRequestPayload = null;
|
|
6944
|
+
constructor(options = {}) {
|
|
6945
|
+
this.client = options.client ?? new import_openai8.default({
|
|
6946
|
+
baseURL: XAI_BASE_URL,
|
|
6947
|
+
timeout: DEFAULT_REQUEST_TIMEOUT_MS2,
|
|
6948
|
+
...options.clientOptions ?? {},
|
|
6949
|
+
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
6950
|
+
});
|
|
6951
|
+
this.model = options.model ?? XAI_DEFAULT_MODEL;
|
|
6952
|
+
this.defaultReasoningEffort = options.reasoningEffort ?? XAI_DEFAULT_REASONING_EFFORT;
|
|
6953
|
+
this.reasoningLevelMeta = {
|
|
6954
|
+
requested: options.reasoningLevelRequested,
|
|
6955
|
+
applied: options.reasoningLevelApplied,
|
|
6956
|
+
fallbackApplied: options.reasoningFallbackApplied
|
|
6957
|
+
};
|
|
6958
|
+
}
|
|
6959
|
+
async ainvoke(input, context) {
|
|
6960
|
+
const {
|
|
6961
|
+
messages,
|
|
6962
|
+
tools: toolDefs,
|
|
6963
|
+
toolChoice,
|
|
6964
|
+
options,
|
|
6965
|
+
model,
|
|
6966
|
+
signal
|
|
6967
|
+
} = input;
|
|
6968
|
+
const inputItems = toXaiResponsesInput(messages);
|
|
6969
|
+
const instructions = extractInstructions(messages);
|
|
6970
|
+
const tools = toXaiResponsesTools(toolDefs);
|
|
6971
|
+
const tool_choice = toXaiResponsesToolChoice(toolChoice);
|
|
6972
|
+
const { reasoningEffort, ...rest } = options ?? {};
|
|
6973
|
+
const request = {
|
|
6974
|
+
model: model ?? this.model,
|
|
6975
|
+
input: inputItems,
|
|
6976
|
+
...rest,
|
|
6977
|
+
...tools ? { tools } : {},
|
|
6978
|
+
...tool_choice ? { tool_choice } : {},
|
|
6979
|
+
store: rest.store ?? false,
|
|
6980
|
+
reasoning: {
|
|
6981
|
+
effort: reasoningEffort ?? this.defaultReasoningEffort
|
|
6982
|
+
}
|
|
6983
|
+
};
|
|
6984
|
+
if (instructions) {
|
|
6985
|
+
request.instructions = instructions;
|
|
6986
|
+
}
|
|
6987
|
+
const includeSet = new Set(request.include ?? []);
|
|
6988
|
+
includeSet.add("reasoning.encrypted_content");
|
|
6989
|
+
if (tools?.some((tool) => tool.type === "web_search")) {
|
|
6990
|
+
includeSet.add("web_search_call.action.sources");
|
|
6991
|
+
}
|
|
6992
|
+
request.include = Array.from(includeSet);
|
|
6993
|
+
if (context?.sessionKey && !request.prompt_cache_key) {
|
|
6994
|
+
request.prompt_cache_key = context.sessionKey;
|
|
6995
|
+
}
|
|
6996
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
6997
|
+
await this.debugRequestIfEnabled(request, debugSeq);
|
|
6998
|
+
const response = await invokeOpenAiHttp(this.client, request, signal);
|
|
6999
|
+
await this.debugResponseIfEnabled(response, debugSeq);
|
|
7000
|
+
return toXaiChatInvokeCompletion(response, {
|
|
7001
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
7002
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
7003
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
7004
|
+
});
|
|
7005
|
+
}
|
|
7006
|
+
nextDebugInvokeSeq() {
|
|
7007
|
+
this.debugInvokeSeq += 1;
|
|
7008
|
+
return this.debugInvokeSeq;
|
|
7009
|
+
}
|
|
7010
|
+
async debugRequestIfEnabled(request, seq) {
|
|
7011
|
+
const settings = getProviderLogSettings();
|
|
7012
|
+
if (!settings.enabled && !settings.dumpDir) return;
|
|
7013
|
+
const payload = safeJsonStringify(request);
|
|
7014
|
+
const hash = (0, import_node_crypto5.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7015
|
+
const previous = this.lastDebugRequestPayload;
|
|
7016
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
7017
|
+
const ratio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
7018
|
+
if (settings.enabled) {
|
|
7019
|
+
console.error(
|
|
7020
|
+
`[xai.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${ratio}%`
|
|
7021
|
+
);
|
|
7022
|
+
}
|
|
7023
|
+
if (settings.dumpDir) {
|
|
7024
|
+
try {
|
|
7025
|
+
await writeProviderLogDump(
|
|
7026
|
+
settings,
|
|
7027
|
+
PROVIDER_NAME7,
|
|
7028
|
+
seq,
|
|
7029
|
+
"request",
|
|
7030
|
+
request
|
|
7031
|
+
);
|
|
7032
|
+
} catch (error) {
|
|
7033
|
+
if (settings.enabled) {
|
|
7034
|
+
console.error(
|
|
7035
|
+
`[xai.request] dump_failed seq=${seq} error=${String(error)}`
|
|
7036
|
+
);
|
|
7037
|
+
}
|
|
7038
|
+
}
|
|
7039
|
+
}
|
|
7040
|
+
this.lastDebugRequestPayload = payload;
|
|
7041
|
+
}
|
|
7042
|
+
async debugResponseIfEnabled(response, seq) {
|
|
7043
|
+
const settings = getProviderLogSettings();
|
|
7044
|
+
if (!settings.enabled && !settings.dumpDir) return;
|
|
7045
|
+
if (settings.enabled) {
|
|
7046
|
+
console.error(
|
|
7047
|
+
`[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}`
|
|
7048
|
+
);
|
|
7049
|
+
}
|
|
7050
|
+
if (settings.dumpDir) {
|
|
7051
|
+
try {
|
|
7052
|
+
await writeProviderLogDump(
|
|
7053
|
+
settings,
|
|
7054
|
+
PROVIDER_NAME7,
|
|
7055
|
+
seq,
|
|
7056
|
+
"response",
|
|
7057
|
+
response
|
|
7058
|
+
);
|
|
7059
|
+
} catch (error) {
|
|
7060
|
+
if (settings.enabled) {
|
|
7061
|
+
console.error(
|
|
7062
|
+
`[xai.response] dump_failed seq=${seq} error=${String(error)}`
|
|
7063
|
+
);
|
|
7064
|
+
}
|
|
7065
|
+
}
|
|
7066
|
+
}
|
|
7067
|
+
}
|
|
7068
|
+
};
|
|
7069
|
+
|
|
5624
7070
|
// src/llm/zai/chat.ts
|
|
5625
|
-
var
|
|
7071
|
+
var import_node_crypto6 = require("crypto");
|
|
7072
|
+
|
|
7073
|
+
// src/llm/zai/failure.ts
|
|
7074
|
+
var PROVIDER_NAME8 = "zai";
|
|
7075
|
+
var readBusinessCode = (error) => {
|
|
7076
|
+
const record = asRecord(error);
|
|
7077
|
+
const body = asRecord(record?.body);
|
|
7078
|
+
const nested = asRecord(body?.error) ?? body;
|
|
7079
|
+
const raw = nested?.code ?? record?.code;
|
|
7080
|
+
const parsed = typeof raw === "number" ? raw : Number(raw);
|
|
7081
|
+
return Number.isFinite(parsed) ? Math.trunc(parsed) : void 0;
|
|
7082
|
+
};
|
|
7083
|
+
var classifyZaiFailure = (error) => {
|
|
7084
|
+
if (isAbortLikeProviderError(error)) {
|
|
7085
|
+
return buildProviderFailure(PROVIDER_NAME8, "cancelled");
|
|
7086
|
+
}
|
|
7087
|
+
const extracted = extractProviderError(error);
|
|
7088
|
+
const status = extracted.status;
|
|
7089
|
+
const code = readBusinessCode(error);
|
|
7090
|
+
if (status === 401)
|
|
7091
|
+
return buildProviderFailure(PROVIDER_NAME8, "auth", { status });
|
|
7092
|
+
if (status === 403) {
|
|
7093
|
+
return buildProviderFailure(PROVIDER_NAME8, "permission", { status });
|
|
7094
|
+
}
|
|
7095
|
+
if (isValidationStatus(status)) {
|
|
7096
|
+
return buildProviderFailure(PROVIDER_NAME8, "validation", { status });
|
|
7097
|
+
}
|
|
7098
|
+
if (code === 1302) {
|
|
7099
|
+
return buildProviderFailure(PROVIDER_NAME8, "rate_limit", {
|
|
7100
|
+
status,
|
|
7101
|
+
retryable: true
|
|
7102
|
+
});
|
|
7103
|
+
}
|
|
7104
|
+
if (code === 1305) {
|
|
7105
|
+
return buildProviderFailure(PROVIDER_NAME8, "overloaded", {
|
|
7106
|
+
status,
|
|
7107
|
+
retryable: true
|
|
7108
|
+
});
|
|
7109
|
+
}
|
|
7110
|
+
if (code === 1234) {
|
|
7111
|
+
return buildProviderFailure(PROVIDER_NAME8, "network", {
|
|
7112
|
+
status,
|
|
7113
|
+
retryable: true
|
|
7114
|
+
});
|
|
7115
|
+
}
|
|
7116
|
+
if (code === 1113 || code === 1308 || code === 1309 || code === 1310 || code !== void 0 && code >= 1316 && code <= 1321) {
|
|
7117
|
+
return buildProviderFailure(PROVIDER_NAME8, "hard_quota", { status });
|
|
7118
|
+
}
|
|
7119
|
+
if (code !== void 0 && code >= 1311 && code <= 1315) {
|
|
7120
|
+
return buildProviderFailure(PROVIDER_NAME8, "permission", { status });
|
|
7121
|
+
}
|
|
7122
|
+
if (status === 408 || status === 504) {
|
|
7123
|
+
return buildProviderFailure(PROVIDER_NAME8, "timeout", {
|
|
7124
|
+
status,
|
|
7125
|
+
retryable: true
|
|
7126
|
+
});
|
|
7127
|
+
}
|
|
7128
|
+
if (status === 503) {
|
|
7129
|
+
return buildProviderFailure(PROVIDER_NAME8, "overloaded", {
|
|
7130
|
+
status,
|
|
7131
|
+
retryable: true
|
|
7132
|
+
});
|
|
7133
|
+
}
|
|
7134
|
+
if (status !== void 0 && status >= 500) {
|
|
7135
|
+
return buildProviderFailure(PROVIDER_NAME8, "provider", {
|
|
7136
|
+
status,
|
|
7137
|
+
retryable: true
|
|
7138
|
+
});
|
|
7139
|
+
}
|
|
7140
|
+
if (status === 429) {
|
|
7141
|
+
return buildProviderFailure(PROVIDER_NAME8, "provider", { status });
|
|
7142
|
+
}
|
|
7143
|
+
return classifyTransportFailure(PROVIDER_NAME8, error) ?? buildProviderFailure(PROVIDER_NAME8, "provider");
|
|
7144
|
+
};
|
|
5626
7145
|
|
|
5627
7146
|
// src/llm/zai/serializer.ts
|
|
5628
7147
|
var stringifyContentForZai = (content) => stringifyContent(content, { mode: "display", joiner: "" });
|
|
@@ -5765,7 +7284,7 @@ function toZaiChatInvokeCompletion(accumulator, meta) {
|
|
|
5765
7284
|
}
|
|
5766
7285
|
});
|
|
5767
7286
|
}
|
|
5768
|
-
const toolCalls = accumulator.toolCalls.filter((call) => call.name || call.arguments || call.id).map(
|
|
7287
|
+
const toolCalls = accumulator.toolCalls.filter((call) => call.name || call.arguments || call.id).map(toToolCall2);
|
|
5769
7288
|
if (accumulator.content || toolCalls.length) {
|
|
5770
7289
|
messages.push({
|
|
5771
7290
|
role: "assistant",
|
|
@@ -5802,7 +7321,7 @@ var toZaiReplayToolCalls = (toolCalls) => {
|
|
|
5802
7321
|
}
|
|
5803
7322
|
}));
|
|
5804
7323
|
};
|
|
5805
|
-
var
|
|
7324
|
+
var toToolCall2 = (call) => ({
|
|
5806
7325
|
id: call.id,
|
|
5807
7326
|
type: "function",
|
|
5808
7327
|
function: {
|
|
@@ -5815,7 +7334,7 @@ var toToolCall = (call) => ({
|
|
|
5815
7334
|
raw_chunk_count: call.raw_chunk_count
|
|
5816
7335
|
}
|
|
5817
7336
|
});
|
|
5818
|
-
var
|
|
7337
|
+
var normalizeNumber2 = (value) => {
|
|
5819
7338
|
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
5820
7339
|
return 0;
|
|
5821
7340
|
}
|
|
@@ -5826,10 +7345,10 @@ var normalizeZaiUsage = (accumulator) => {
|
|
|
5826
7345
|
if (!usage) {
|
|
5827
7346
|
return null;
|
|
5828
7347
|
}
|
|
5829
|
-
const inputTokens =
|
|
5830
|
-
const outputTokens =
|
|
5831
|
-
const totalTokens = typeof usage.total_tokens === "number" ?
|
|
5832
|
-
const cachedTokens =
|
|
7348
|
+
const inputTokens = normalizeNumber2(usage.prompt_tokens);
|
|
7349
|
+
const outputTokens = normalizeNumber2(usage.completion_tokens);
|
|
7350
|
+
const totalTokens = typeof usage.total_tokens === "number" ? normalizeNumber2(usage.total_tokens) : inputTokens + outputTokens;
|
|
7351
|
+
const cachedTokens = normalizeNumber2(
|
|
5833
7352
|
usage.prompt_tokens_details?.cached_tokens
|
|
5834
7353
|
);
|
|
5835
7354
|
return {
|
|
@@ -5842,6 +7361,16 @@ var normalizeZaiUsage = (accumulator) => {
|
|
|
5842
7361
|
};
|
|
5843
7362
|
|
|
5844
7363
|
// src/llm/zai/transport.ts
|
|
7364
|
+
var ZaiHttpError = class extends Error {
|
|
7365
|
+
status;
|
|
7366
|
+
body;
|
|
7367
|
+
constructor(status, body) {
|
|
7368
|
+
super(`Z.ai provider request failed (${status})`);
|
|
7369
|
+
this.name = "ZaiHttpError";
|
|
7370
|
+
this.status = status;
|
|
7371
|
+
this.body = body;
|
|
7372
|
+
}
|
|
7373
|
+
};
|
|
5845
7374
|
var streamZaiChatCompletion = async ({
|
|
5846
7375
|
apiKey,
|
|
5847
7376
|
baseURL,
|
|
@@ -5937,7 +7466,7 @@ var createZaiRequestSignal = (signal, timeoutMs) => {
|
|
|
5937
7466
|
}
|
|
5938
7467
|
const controller = new AbortController();
|
|
5939
7468
|
let timeout = setTimeout(() => {
|
|
5940
|
-
controller.abort(new
|
|
7469
|
+
controller.abort(new ProviderTimeoutError("Z.ai request timeout"));
|
|
5941
7470
|
}, timeoutMs);
|
|
5942
7471
|
const onAbort = () => {
|
|
5943
7472
|
controller.abort(signal?.reason);
|
|
@@ -5965,9 +7494,15 @@ var toZaiHttpError = async (response) => {
|
|
|
5965
7494
|
} catch {
|
|
5966
7495
|
body = "";
|
|
5967
7496
|
}
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
|
|
7497
|
+
let parsed = body;
|
|
7498
|
+
if (body) {
|
|
7499
|
+
try {
|
|
7500
|
+
parsed = JSON.parse(body);
|
|
7501
|
+
} catch {
|
|
7502
|
+
parsed = body.slice(0, 500);
|
|
7503
|
+
}
|
|
7504
|
+
}
|
|
7505
|
+
return new ZaiHttpError(response.status, parsed);
|
|
5971
7506
|
};
|
|
5972
7507
|
var throwIfAborted2 = (signal) => {
|
|
5973
7508
|
if (!signal?.aborted) {
|
|
@@ -6002,13 +7537,14 @@ var parseSseDataLine = (line) => {
|
|
|
6002
7537
|
};
|
|
6003
7538
|
|
|
6004
7539
|
// src/llm/zai/chat.ts
|
|
6005
|
-
var
|
|
6006
|
-
var
|
|
7540
|
+
var PROVIDER_NAME9 = "zai";
|
|
7541
|
+
var DEFAULT_BASE_URL2 = "https://api.z.ai/api/paas/v4";
|
|
6007
7542
|
var DEFAULT_REASONING_EFFORT3 = "high";
|
|
6008
|
-
var
|
|
7543
|
+
var DEFAULT_REQUEST_TIMEOUT_MS3 = 20 * 60 * 1e3;
|
|
6009
7544
|
var ChatZai = class {
|
|
6010
|
-
provider =
|
|
7545
|
+
provider = PROVIDER_NAME9;
|
|
6011
7546
|
model;
|
|
7547
|
+
classifyFailure = classifyZaiFailure;
|
|
6012
7548
|
apiKey;
|
|
6013
7549
|
baseURL;
|
|
6014
7550
|
fetchImpl;
|
|
@@ -6019,10 +7555,10 @@ var ChatZai = class {
|
|
|
6019
7555
|
lastDebugRequestPayload = null;
|
|
6020
7556
|
constructor(options = {}) {
|
|
6021
7557
|
this.apiKey = options.apiKey;
|
|
6022
|
-
this.baseURL = (options.baseURL ??
|
|
7558
|
+
this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL2).replace(/\/+$/, "");
|
|
6023
7559
|
this.fetchImpl = options.fetch ?? fetch;
|
|
6024
7560
|
this.model = options.model ?? ZAI_DEFAULT_MODEL;
|
|
6025
|
-
this.timeoutMs = options.timeoutMs ??
|
|
7561
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS3;
|
|
6026
7562
|
this.defaultReasoningEffort = options.reasoningEffort === void 0 ? DEFAULT_REASONING_EFFORT3 : options.reasoningEffort;
|
|
6027
7563
|
this.reasoningLevelMeta = {
|
|
6028
7564
|
requested: options.reasoningLevelRequested,
|
|
@@ -6093,8 +7629,8 @@ var ChatZai = class {
|
|
|
6093
7629
|
return;
|
|
6094
7630
|
}
|
|
6095
7631
|
const payload = safeJsonStringify(request);
|
|
6096
|
-
const hash = (0,
|
|
6097
|
-
const toolsHash = (0,
|
|
7632
|
+
const hash = (0, import_node_crypto6.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7633
|
+
const toolsHash = (0, import_node_crypto6.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
6098
7634
|
const previous = this.lastDebugRequestPayload;
|
|
6099
7635
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6100
7636
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -6107,7 +7643,7 @@ var ChatZai = class {
|
|
|
6107
7643
|
try {
|
|
6108
7644
|
await writeProviderLogDump(
|
|
6109
7645
|
settings,
|
|
6110
|
-
|
|
7646
|
+
PROVIDER_NAME9,
|
|
6111
7647
|
seq,
|
|
6112
7648
|
"request",
|
|
6113
7649
|
request
|
|
@@ -6139,7 +7675,7 @@ var ChatZai = class {
|
|
|
6139
7675
|
try {
|
|
6140
7676
|
await writeProviderLogDump(
|
|
6141
7677
|
settings,
|
|
6142
|
-
|
|
7678
|
+
PROVIDER_NAME9,
|
|
6143
7679
|
seq,
|
|
6144
7680
|
"response",
|
|
6145
7681
|
response.accumulated
|
|
@@ -6158,15 +7694,10 @@ var ChatZai = class {
|
|
|
6158
7694
|
// src/prompts.ts
|
|
6159
7695
|
var import_node_path2 = __toESM(require("path"), 1);
|
|
6160
7696
|
var import_node_url = require("url");
|
|
6161
|
-
var import_meta = {};
|
|
6162
7697
|
var resolvePromptPath = () => {
|
|
6163
|
-
|
|
6164
|
-
|
|
6165
|
-
|
|
6166
|
-
if (typeof import_meta !== "undefined" && import_meta.url) {
|
|
6167
|
-
return (0, import_node_url.fileURLToPath)(new URL("../prompts/system.md", import_meta.url));
|
|
6168
|
-
}
|
|
6169
|
-
return import_node_path2.default.resolve("prompts/system.md");
|
|
7698
|
+
const moduleLocation = __filename;
|
|
7699
|
+
const moduleFilename = moduleLocation.startsWith("file:") ? (0, import_node_url.fileURLToPath)(moduleLocation) : moduleLocation;
|
|
7700
|
+
return import_node_path2.default.resolve(import_node_path2.default.dirname(moduleFilename), "../prompts/system.md");
|
|
6170
7701
|
};
|
|
6171
7702
|
var promptPath = resolvePromptPath();
|
|
6172
7703
|
var getDefaultSystemPromptPath = () => promptPath;
|
|
@@ -6236,16 +7767,24 @@ function defineTool(toolOptions) {
|
|
|
6236
7767
|
ANTHROPIC_MODELS,
|
|
6237
7768
|
Agent,
|
|
6238
7769
|
ChatAnthropic,
|
|
7770
|
+
ChatMoonshot,
|
|
6239
7771
|
ChatOpenAI,
|
|
6240
7772
|
ChatOpenRouter,
|
|
7773
|
+
ChatXai,
|
|
6241
7774
|
ChatZai,
|
|
6242
7775
|
DEFAULT_MODEL_REGISTRY,
|
|
6243
7776
|
GOOGLE_MODELS,
|
|
7777
|
+
MOONSHOT_DEFAULT_MODEL,
|
|
7778
|
+
MOONSHOT_MODELS,
|
|
6244
7779
|
OPENAI_DEFAULT_MODEL,
|
|
6245
7780
|
OPENAI_DEFAULT_REASONING_EFFORT,
|
|
6246
7781
|
OPENAI_MODELS,
|
|
7782
|
+
ProviderFailureError,
|
|
6247
7783
|
TaskComplete,
|
|
6248
7784
|
ToolOutputCacheService,
|
|
7785
|
+
XAI_DEFAULT_MODEL,
|
|
7786
|
+
XAI_DEFAULT_REASONING_EFFORT,
|
|
7787
|
+
XAI_MODELS,
|
|
6249
7788
|
ZAI_DEFAULT_MODEL,
|
|
6250
7789
|
ZAI_MODELS,
|
|
6251
7790
|
ZAI_REASONING_EFFORT_MODELS,
|
|
@@ -6253,6 +7792,7 @@ function defineTool(toolOptions) {
|
|
|
6253
7792
|
createModelRegistry,
|
|
6254
7793
|
defineTool,
|
|
6255
7794
|
getDefaultSystemPromptPath,
|
|
7795
|
+
isProviderFailureError,
|
|
6256
7796
|
isUsableModelSpec,
|
|
6257
7797
|
listModels,
|
|
6258
7798
|
registerModels,
|