@codelia/core 0.1.68 → 0.1.70
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/dist/index.cjs +638 -8
- package/dist/index.d.cts +71 -22
- package/dist/index.d.ts +71 -22
- package/dist/index.js +634 -8
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -2,8 +2,11 @@
|
|
|
2
2
|
import { configRegistry } from "@codelia/config";
|
|
3
3
|
|
|
4
4
|
// src/models/openai.ts
|
|
5
|
-
var OPENAI_DEFAULT_MODEL = "gpt-5.
|
|
5
|
+
var OPENAI_DEFAULT_MODEL = "gpt-5.6";
|
|
6
6
|
var OPENAI_DEFAULT_REASONING_EFFORT = "medium";
|
|
7
|
+
var GPT_5_6_CONTEXT_WINDOW = 105e4;
|
|
8
|
+
var GPT_5_6_MAX_INPUT_TOKENS = 922e3;
|
|
9
|
+
var GPT_5_6_MAX_OUTPUT_TOKENS = 128e3;
|
|
7
10
|
var GPT_5_4_CAPPED_INPUT_TOKENS = 272e3;
|
|
8
11
|
var OPENAI_MODELS = [
|
|
9
12
|
{
|
|
@@ -11,6 +14,38 @@ var OPENAI_MODELS = [
|
|
|
11
14
|
provider: "openai",
|
|
12
15
|
aliases: ["default"]
|
|
13
16
|
},
|
|
17
|
+
{
|
|
18
|
+
id: "gpt-5.6",
|
|
19
|
+
provider: "openai",
|
|
20
|
+
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
21
|
+
maxInputTokens: GPT_5_6_MAX_INPUT_TOKENS,
|
|
22
|
+
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS,
|
|
23
|
+
supportsFast: true
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
id: "gpt-5.6-sol",
|
|
27
|
+
provider: "openai",
|
|
28
|
+
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
29
|
+
maxInputTokens: GPT_5_6_MAX_INPUT_TOKENS,
|
|
30
|
+
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS,
|
|
31
|
+
supportsFast: true
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
id: "gpt-5.6-terra",
|
|
35
|
+
provider: "openai",
|
|
36
|
+
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
37
|
+
maxInputTokens: GPT_5_6_MAX_INPUT_TOKENS,
|
|
38
|
+
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS,
|
|
39
|
+
supportsFast: true
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
id: "gpt-5.6-luna",
|
|
43
|
+
provider: "openai",
|
|
44
|
+
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
45
|
+
maxInputTokens: GPT_5_6_MAX_INPUT_TOKENS,
|
|
46
|
+
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS,
|
|
47
|
+
supportsFast: true
|
|
48
|
+
},
|
|
14
49
|
{
|
|
15
50
|
id: "gpt-5.5",
|
|
16
51
|
provider: "openai",
|
|
@@ -285,6 +320,14 @@ var ANTHROPIC_MODELS = [
|
|
|
285
320
|
provider: "anthropic",
|
|
286
321
|
aliases: ["default"]
|
|
287
322
|
},
|
|
323
|
+
{
|
|
324
|
+
id: "claude-opus-4-8",
|
|
325
|
+
provider: "anthropic",
|
|
326
|
+
contextWindow: 1e6,
|
|
327
|
+
maxInputTokens: 1e6,
|
|
328
|
+
maxOutputTokens: 128e3,
|
|
329
|
+
supportsFast: true
|
|
330
|
+
},
|
|
288
331
|
{
|
|
289
332
|
id: "claude-opus-4-7",
|
|
290
333
|
provider: "anthropic",
|
|
@@ -348,7 +391,8 @@ function createModelRegistry(specs) {
|
|
|
348
391
|
openai: {},
|
|
349
392
|
anthropic: {},
|
|
350
393
|
openrouter: {},
|
|
351
|
-
google: {}
|
|
394
|
+
google: {},
|
|
395
|
+
zai: {}
|
|
352
396
|
}
|
|
353
397
|
};
|
|
354
398
|
registerModels(registry, specs);
|
|
@@ -408,7 +452,8 @@ function cloneAliases(aliasesByProvider) {
|
|
|
408
452
|
openai: { ...aliasesByProvider.openai },
|
|
409
453
|
anthropic: { ...aliasesByProvider.anthropic },
|
|
410
454
|
openrouter: { ...aliasesByProvider.openrouter },
|
|
411
|
-
google: { ...aliasesByProvider.google }
|
|
455
|
+
google: { ...aliasesByProvider.google },
|
|
456
|
+
zai: { ...aliasesByProvider.zai }
|
|
412
457
|
};
|
|
413
458
|
}
|
|
414
459
|
function applyModelMetadata(registry, index) {
|
|
@@ -417,7 +462,7 @@ function applyModelMetadata(registry, index) {
|
|
|
417
462
|
aliasesByProvider: cloneAliases(registry.aliasesByProvider)
|
|
418
463
|
};
|
|
419
464
|
for (const [providerId, providerModels] of Object.entries(index.models)) {
|
|
420
|
-
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google") {
|
|
465
|
+
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google" && providerId !== "zai") {
|
|
421
466
|
continue;
|
|
422
467
|
}
|
|
423
468
|
const provider = providerId;
|
|
@@ -437,11 +482,50 @@ function applyModelMetadata(registry, index) {
|
|
|
437
482
|
return next;
|
|
438
483
|
}
|
|
439
484
|
|
|
485
|
+
// src/models/zai.ts
|
|
486
|
+
var ZAI_DEFAULT_MODEL = "glm-5.2";
|
|
487
|
+
var ZAI_REASONING_EFFORT_MODELS = /* @__PURE__ */ new Set(["glm-5.2"]);
|
|
488
|
+
var zaiModel = (id, limits) => ({
|
|
489
|
+
id,
|
|
490
|
+
provider: "zai",
|
|
491
|
+
aliases: limits.aliases,
|
|
492
|
+
contextWindow: limits.contextWindow,
|
|
493
|
+
maxInputTokens: limits.contextWindow,
|
|
494
|
+
maxOutputTokens: limits.maxOutputTokens,
|
|
495
|
+
supportsTools: true,
|
|
496
|
+
supportsReasoning: true,
|
|
497
|
+
supportsJsonSchema: true
|
|
498
|
+
});
|
|
499
|
+
var ZAI_MODELS = [
|
|
500
|
+
zaiModel(ZAI_DEFAULT_MODEL, {
|
|
501
|
+
aliases: ["default"],
|
|
502
|
+
contextWindow: 1e6,
|
|
503
|
+
maxOutputTokens: 131072
|
|
504
|
+
}),
|
|
505
|
+
zaiModel("glm-5.1", {
|
|
506
|
+
contextWindow: 2e5,
|
|
507
|
+
maxOutputTokens: 131072
|
|
508
|
+
}),
|
|
509
|
+
zaiModel("glm-5", {
|
|
510
|
+
contextWindow: 2e5,
|
|
511
|
+
maxOutputTokens: 131072
|
|
512
|
+
}),
|
|
513
|
+
zaiModel("glm-5-turbo", {
|
|
514
|
+
contextWindow: 2e5,
|
|
515
|
+
maxOutputTokens: 131072
|
|
516
|
+
}),
|
|
517
|
+
zaiModel("glm-4.7", {
|
|
518
|
+
contextWindow: 2e5,
|
|
519
|
+
maxOutputTokens: 131072
|
|
520
|
+
})
|
|
521
|
+
];
|
|
522
|
+
|
|
440
523
|
// src/models/index.ts
|
|
441
524
|
var DEFAULT_MODEL_REGISTRY = createModelRegistry([
|
|
442
525
|
...OPENAI_MODELS,
|
|
443
526
|
...ANTHROPIC_MODELS,
|
|
444
|
-
...GOOGLE_MODELS
|
|
527
|
+
...GOOGLE_MODELS,
|
|
528
|
+
...ZAI_MODELS
|
|
445
529
|
]);
|
|
446
530
|
|
|
447
531
|
// src/services/compaction/service.ts
|
|
@@ -806,7 +890,7 @@ var parseQualifiedModelId = (modelId) => {
|
|
|
806
890
|
if (!rest) {
|
|
807
891
|
return null;
|
|
808
892
|
}
|
|
809
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
893
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
810
894
|
return null;
|
|
811
895
|
}
|
|
812
896
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -989,7 +1073,7 @@ var parseQualifiedModelId2 = (modelId) => {
|
|
|
989
1073
|
if (!rest) {
|
|
990
1074
|
return null;
|
|
991
1075
|
}
|
|
992
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
1076
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
993
1077
|
return null;
|
|
994
1078
|
}
|
|
995
1079
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -1802,7 +1886,7 @@ var parseQualifiedModelId3 = (modelId) => {
|
|
|
1802
1886
|
if (!rest) {
|
|
1803
1887
|
return null;
|
|
1804
1888
|
}
|
|
1805
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
1889
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
1806
1890
|
return null;
|
|
1807
1891
|
}
|
|
1808
1892
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -5425,6 +5509,544 @@ var ChatOpenRouter = class {
|
|
|
5425
5509
|
}
|
|
5426
5510
|
};
|
|
5427
5511
|
|
|
5512
|
+
// src/llm/zai/chat.ts
|
|
5513
|
+
import { createHash as createHash4 } from "crypto";
|
|
5514
|
+
|
|
5515
|
+
// src/llm/zai/serializer.ts
|
|
5516
|
+
var stringifyContentForZai = (content) => stringifyContent(content, { mode: "display", joiner: "" });
|
|
5517
|
+
function toZaiMessages(messages) {
|
|
5518
|
+
const mapped = [];
|
|
5519
|
+
for (const message of messages) {
|
|
5520
|
+
switch (message.role) {
|
|
5521
|
+
case "system":
|
|
5522
|
+
case "user": {
|
|
5523
|
+
mapped.push({
|
|
5524
|
+
role: message.role,
|
|
5525
|
+
content: stringifyContentForZai(message.content)
|
|
5526
|
+
});
|
|
5527
|
+
break;
|
|
5528
|
+
}
|
|
5529
|
+
case "assistant": {
|
|
5530
|
+
const content = stringifyContentForZai(message.content);
|
|
5531
|
+
const toolCalls = toZaiReplayToolCalls(message.tool_calls);
|
|
5532
|
+
mapped.push({
|
|
5533
|
+
role: "assistant",
|
|
5534
|
+
content: content || null,
|
|
5535
|
+
...toolCalls.length ? { tool_calls: toolCalls } : {}
|
|
5536
|
+
});
|
|
5537
|
+
break;
|
|
5538
|
+
}
|
|
5539
|
+
case "tool": {
|
|
5540
|
+
mapped.push({
|
|
5541
|
+
role: "tool",
|
|
5542
|
+
tool_call_id: message.tool_call_id,
|
|
5543
|
+
content: stringifyContentForZai(message.content)
|
|
5544
|
+
});
|
|
5545
|
+
break;
|
|
5546
|
+
}
|
|
5547
|
+
case "reasoning":
|
|
5548
|
+
break;
|
|
5549
|
+
}
|
|
5550
|
+
}
|
|
5551
|
+
return mapped;
|
|
5552
|
+
}
|
|
5553
|
+
function toZaiTools(tools) {
|
|
5554
|
+
if (!tools || tools.length === 0) {
|
|
5555
|
+
return void 0;
|
|
5556
|
+
}
|
|
5557
|
+
const mapped = [];
|
|
5558
|
+
for (const tool of tools) {
|
|
5559
|
+
if (isFunctionToolDefinition(tool)) {
|
|
5560
|
+
mapped.push({
|
|
5561
|
+
type: "function",
|
|
5562
|
+
function: {
|
|
5563
|
+
name: tool.name,
|
|
5564
|
+
description: tool.description,
|
|
5565
|
+
parameters: tool.parameters
|
|
5566
|
+
}
|
|
5567
|
+
});
|
|
5568
|
+
continue;
|
|
5569
|
+
}
|
|
5570
|
+
if (isHostedSearchToolDefinition(tool)) {
|
|
5571
|
+
continue;
|
|
5572
|
+
}
|
|
5573
|
+
}
|
|
5574
|
+
return mapped.length ? mapped : void 0;
|
|
5575
|
+
}
|
|
5576
|
+
function toZaiToolChoice(choice) {
|
|
5577
|
+
if (!choice) {
|
|
5578
|
+
return void 0;
|
|
5579
|
+
}
|
|
5580
|
+
if (choice === "auto" || choice === "required" || choice === "none") {
|
|
5581
|
+
return choice;
|
|
5582
|
+
}
|
|
5583
|
+
return { type: "function", function: { name: choice } };
|
|
5584
|
+
}
|
|
5585
|
+
var createZaiStreamAccumulator = (options) => ({
|
|
5586
|
+
content: "",
|
|
5587
|
+
reasoningContent: "",
|
|
5588
|
+
toolCalls: [],
|
|
5589
|
+
rawChunkCount: 0,
|
|
5590
|
+
rawChunks: [],
|
|
5591
|
+
captureRawChunks: options?.captureRawChunks ?? false
|
|
5592
|
+
});
|
|
5593
|
+
function appendZaiChatCompletionChunk(accumulator, chunk) {
|
|
5594
|
+
accumulator.rawChunkCount += 1;
|
|
5595
|
+
if (accumulator.captureRawChunks) {
|
|
5596
|
+
accumulator.rawChunks.push(chunk);
|
|
5597
|
+
}
|
|
5598
|
+
accumulator.id ??= chunk.id;
|
|
5599
|
+
accumulator.model ??= chunk.model;
|
|
5600
|
+
accumulator.created ??= chunk.created;
|
|
5601
|
+
accumulator.usage ??= chunk.usage ?? void 0;
|
|
5602
|
+
for (const choice of chunk.choices ?? []) {
|
|
5603
|
+
if (choice.finish_reason !== void 0) {
|
|
5604
|
+
accumulator.finishReason = choice.finish_reason;
|
|
5605
|
+
}
|
|
5606
|
+
const delta = choice.delta;
|
|
5607
|
+
if (!delta) {
|
|
5608
|
+
continue;
|
|
5609
|
+
}
|
|
5610
|
+
if (typeof delta.reasoning_content === "string") {
|
|
5611
|
+
accumulator.reasoningContent += delta.reasoning_content;
|
|
5612
|
+
}
|
|
5613
|
+
if (typeof delta.content === "string") {
|
|
5614
|
+
accumulator.content += delta.content;
|
|
5615
|
+
}
|
|
5616
|
+
for (const toolCallDelta of delta.tool_calls ?? []) {
|
|
5617
|
+
const index = typeof toolCallDelta.index === "number" ? toolCallDelta.index : accumulator.toolCalls.length;
|
|
5618
|
+
let call = accumulator.toolCalls.find((entry) => entry.index === index);
|
|
5619
|
+
if (!call) {
|
|
5620
|
+
call = {
|
|
5621
|
+
index,
|
|
5622
|
+
id: toolCallDelta.id ?? `call_${index}`,
|
|
5623
|
+
type: "function",
|
|
5624
|
+
name: "",
|
|
5625
|
+
arguments: "",
|
|
5626
|
+
raw_chunk_count: 0
|
|
5627
|
+
};
|
|
5628
|
+
accumulator.toolCalls.push(call);
|
|
5629
|
+
accumulator.toolCalls.sort((left, right) => left.index - right.index);
|
|
5630
|
+
}
|
|
5631
|
+
call.raw_chunk_count += 1;
|
|
5632
|
+
if (typeof toolCallDelta.id === "string" && toolCallDelta.id) {
|
|
5633
|
+
call.id = toolCallDelta.id;
|
|
5634
|
+
}
|
|
5635
|
+
if (toolCallDelta.type === "function") {
|
|
5636
|
+
call.type = "function";
|
|
5637
|
+
}
|
|
5638
|
+
if (typeof toolCallDelta.function?.name === "string") {
|
|
5639
|
+
call.name = toolCallDelta.function.name;
|
|
5640
|
+
}
|
|
5641
|
+
if (typeof toolCallDelta.function?.arguments === "string") {
|
|
5642
|
+
call.arguments += toolCallDelta.function.arguments;
|
|
5643
|
+
}
|
|
5644
|
+
}
|
|
5645
|
+
}
|
|
5646
|
+
}
|
|
5647
|
+
function toZaiChatInvokeCompletion(accumulator, meta) {
|
|
5648
|
+
const messages = [];
|
|
5649
|
+
if (accumulator.reasoningContent) {
|
|
5650
|
+
messages.push({
|
|
5651
|
+
role: "reasoning",
|
|
5652
|
+
content: accumulator.reasoningContent,
|
|
5653
|
+
raw_item: {
|
|
5654
|
+
provider: "zai",
|
|
5655
|
+
field: "reasoning_content",
|
|
5656
|
+
response_id: accumulator.id
|
|
5657
|
+
}
|
|
5658
|
+
});
|
|
5659
|
+
}
|
|
5660
|
+
const toolCalls = accumulator.toolCalls.filter((call) => call.name || call.arguments || call.id).map(toToolCall);
|
|
5661
|
+
if (accumulator.content || toolCalls.length) {
|
|
5662
|
+
messages.push({
|
|
5663
|
+
role: "assistant",
|
|
5664
|
+
content: accumulator.content || null,
|
|
5665
|
+
...toolCalls.length ? { tool_calls: toolCalls } : {}
|
|
5666
|
+
});
|
|
5667
|
+
}
|
|
5668
|
+
const usage = normalizeZaiUsage(accumulator);
|
|
5669
|
+
return {
|
|
5670
|
+
messages,
|
|
5671
|
+
usage,
|
|
5672
|
+
stop_reason: accumulator.finishReason ?? null,
|
|
5673
|
+
provider_meta: {
|
|
5674
|
+
response_id: accumulator.id,
|
|
5675
|
+
request_id: meta?.request_id ?? void 0,
|
|
5676
|
+
finish_reason: accumulator.finishReason ?? null,
|
|
5677
|
+
reasoning_requested: meta?.reasoning_requested,
|
|
5678
|
+
reasoning_applied: meta?.reasoning_applied,
|
|
5679
|
+
reasoning_effort: meta?.reasoning_effort,
|
|
5680
|
+
reasoning_fallback: meta?.reasoning_fallback
|
|
5681
|
+
}
|
|
5682
|
+
};
|
|
5683
|
+
}
|
|
5684
|
+
var toZaiReplayToolCalls = (toolCalls) => {
|
|
5685
|
+
if (!toolCalls?.length) {
|
|
5686
|
+
return [];
|
|
5687
|
+
}
|
|
5688
|
+
return toolCalls.map((call) => ({
|
|
5689
|
+
id: call.id,
|
|
5690
|
+
type: "function",
|
|
5691
|
+
function: {
|
|
5692
|
+
name: call.function.name,
|
|
5693
|
+
arguments: call.function.arguments
|
|
5694
|
+
}
|
|
5695
|
+
}));
|
|
5696
|
+
};
|
|
5697
|
+
var toToolCall = (call) => ({
|
|
5698
|
+
id: call.id,
|
|
5699
|
+
type: "function",
|
|
5700
|
+
function: {
|
|
5701
|
+
name: call.name,
|
|
5702
|
+
arguments: call.arguments
|
|
5703
|
+
},
|
|
5704
|
+
provider_meta: {
|
|
5705
|
+
provider: "zai",
|
|
5706
|
+
index: call.index,
|
|
5707
|
+
raw_chunk_count: call.raw_chunk_count
|
|
5708
|
+
}
|
|
5709
|
+
});
|
|
5710
|
+
var normalizeNumber = (value) => {
|
|
5711
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
5712
|
+
return 0;
|
|
5713
|
+
}
|
|
5714
|
+
return Math.trunc(value);
|
|
5715
|
+
};
|
|
5716
|
+
var normalizeZaiUsage = (accumulator) => {
|
|
5717
|
+
const usage = accumulator.usage;
|
|
5718
|
+
if (!usage) {
|
|
5719
|
+
return null;
|
|
5720
|
+
}
|
|
5721
|
+
const inputTokens = normalizeNumber(usage.prompt_tokens);
|
|
5722
|
+
const outputTokens = normalizeNumber(usage.completion_tokens);
|
|
5723
|
+
const totalTokens = typeof usage.total_tokens === "number" ? normalizeNumber(usage.total_tokens) : inputTokens + outputTokens;
|
|
5724
|
+
const cachedTokens = normalizeNumber(
|
|
5725
|
+
usage.prompt_tokens_details?.cached_tokens
|
|
5726
|
+
);
|
|
5727
|
+
return {
|
|
5728
|
+
model: accumulator.model ?? "",
|
|
5729
|
+
input_tokens: inputTokens,
|
|
5730
|
+
...cachedTokens > 0 ? { input_cached_tokens: cachedTokens } : {},
|
|
5731
|
+
output_tokens: outputTokens,
|
|
5732
|
+
total_tokens: totalTokens
|
|
5733
|
+
};
|
|
5734
|
+
};
|
|
5735
|
+
|
|
5736
|
+
// src/llm/zai/transport.ts
|
|
5737
|
+
var streamZaiChatCompletion = async ({
|
|
5738
|
+
apiKey,
|
|
5739
|
+
baseURL,
|
|
5740
|
+
fetchImpl,
|
|
5741
|
+
request,
|
|
5742
|
+
signal,
|
|
5743
|
+
timeoutMs,
|
|
5744
|
+
captureRawChunks
|
|
5745
|
+
}) => {
|
|
5746
|
+
const requestSignal = createZaiRequestSignal(signal, timeoutMs);
|
|
5747
|
+
try {
|
|
5748
|
+
const response = await fetchImpl(`${baseURL}/chat/completions`, {
|
|
5749
|
+
method: "POST",
|
|
5750
|
+
headers: {
|
|
5751
|
+
Authorization: `Bearer ${apiKey}`,
|
|
5752
|
+
"Content-Type": "application/json"
|
|
5753
|
+
},
|
|
5754
|
+
body: safeJsonStringify(request),
|
|
5755
|
+
signal: requestSignal.signal
|
|
5756
|
+
});
|
|
5757
|
+
if (!response.ok) {
|
|
5758
|
+
throw await toZaiHttpError(response);
|
|
5759
|
+
}
|
|
5760
|
+
const accumulated = createZaiStreamAccumulator({
|
|
5761
|
+
captureRawChunks: captureRawChunks ?? false
|
|
5762
|
+
});
|
|
5763
|
+
for await (const chunk of readZaiChatCompletionStream(
|
|
5764
|
+
response,
|
|
5765
|
+
requestSignal.signal
|
|
5766
|
+
)) {
|
|
5767
|
+
appendZaiChatCompletionChunk(accumulated, chunk);
|
|
5768
|
+
}
|
|
5769
|
+
return {
|
|
5770
|
+
status: response.status,
|
|
5771
|
+
request_id: response.headers.get("x-request-id"),
|
|
5772
|
+
accumulated
|
|
5773
|
+
};
|
|
5774
|
+
} finally {
|
|
5775
|
+
requestSignal.cleanup();
|
|
5776
|
+
}
|
|
5777
|
+
};
|
|
5778
|
+
async function* readZaiChatCompletionStream(response, signal) {
|
|
5779
|
+
if (!response.body) {
|
|
5780
|
+
throw new Error("Z.ai provider error: response body is empty");
|
|
5781
|
+
}
|
|
5782
|
+
const reader = response.body.getReader();
|
|
5783
|
+
throwIfAborted2(signal);
|
|
5784
|
+
const cancelOnAbort = () => {
|
|
5785
|
+
void reader.cancel(signal?.reason).catch(() => void 0);
|
|
5786
|
+
};
|
|
5787
|
+
signal?.addEventListener("abort", cancelOnAbort, { once: true });
|
|
5788
|
+
const decoder = new TextDecoder();
|
|
5789
|
+
let buffer = "";
|
|
5790
|
+
try {
|
|
5791
|
+
while (true) {
|
|
5792
|
+
throwIfAborted2(signal);
|
|
5793
|
+
const { done, value } = await reader.read();
|
|
5794
|
+
throwIfAborted2(signal);
|
|
5795
|
+
if (done) {
|
|
5796
|
+
break;
|
|
5797
|
+
}
|
|
5798
|
+
buffer += decoder.decode(value, { stream: true });
|
|
5799
|
+
let newlineIndex = buffer.indexOf("\n");
|
|
5800
|
+
while (newlineIndex >= 0) {
|
|
5801
|
+
const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
|
|
5802
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
5803
|
+
const chunk = parseSseDataLine(line);
|
|
5804
|
+
if (chunk === "done") {
|
|
5805
|
+
return;
|
|
5806
|
+
}
|
|
5807
|
+
if (chunk) {
|
|
5808
|
+
yield chunk;
|
|
5809
|
+
}
|
|
5810
|
+
newlineIndex = buffer.indexOf("\n");
|
|
5811
|
+
}
|
|
5812
|
+
}
|
|
5813
|
+
buffer += decoder.decode();
|
|
5814
|
+
const trailing = buffer.trim();
|
|
5815
|
+
if (trailing) {
|
|
5816
|
+
const chunk = parseSseDataLine(trailing);
|
|
5817
|
+
if (chunk && chunk !== "done") {
|
|
5818
|
+
yield chunk;
|
|
5819
|
+
}
|
|
5820
|
+
}
|
|
5821
|
+
} finally {
|
|
5822
|
+
signal?.removeEventListener("abort", cancelOnAbort);
|
|
5823
|
+
reader.releaseLock();
|
|
5824
|
+
}
|
|
5825
|
+
}
|
|
5826
|
+
var createZaiRequestSignal = (signal, timeoutMs) => {
|
|
5827
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
5828
|
+
return { signal, cleanup: () => void 0 };
|
|
5829
|
+
}
|
|
5830
|
+
const controller = new AbortController();
|
|
5831
|
+
let timeout = setTimeout(() => {
|
|
5832
|
+
controller.abort(new Error("Z.ai request timeout"));
|
|
5833
|
+
}, timeoutMs);
|
|
5834
|
+
const onAbort = () => {
|
|
5835
|
+
controller.abort(signal?.reason);
|
|
5836
|
+
};
|
|
5837
|
+
if (signal?.aborted) {
|
|
5838
|
+
onAbort();
|
|
5839
|
+
} else {
|
|
5840
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
5841
|
+
}
|
|
5842
|
+
return {
|
|
5843
|
+
signal: controller.signal,
|
|
5844
|
+
cleanup: () => {
|
|
5845
|
+
if (timeout) {
|
|
5846
|
+
clearTimeout(timeout);
|
|
5847
|
+
timeout = void 0;
|
|
5848
|
+
}
|
|
5849
|
+
signal?.removeEventListener("abort", onAbort);
|
|
5850
|
+
}
|
|
5851
|
+
};
|
|
5852
|
+
};
|
|
5853
|
+
var toZaiHttpError = async (response) => {
|
|
5854
|
+
let body = "";
|
|
5855
|
+
try {
|
|
5856
|
+
body = await response.text();
|
|
5857
|
+
} catch {
|
|
5858
|
+
body = "";
|
|
5859
|
+
}
|
|
5860
|
+
const snippet = body ? body.slice(0, 500) : "(empty)";
|
|
5861
|
+
const prefix = response.status === 401 || response.status === 403 ? "Z.ai auth/config error" : response.status === 402 ? "Z.ai credits/payment error" : response.status === 408 || response.status === 429 || response.status >= 500 ? "Z.ai transient/rate-limit error" : "Z.ai provider error";
|
|
5862
|
+
return new Error(`${prefix} (${response.status}): ${snippet}`);
|
|
5863
|
+
};
|
|
5864
|
+
var throwIfAborted2 = (signal) => {
|
|
5865
|
+
if (!signal?.aborted) {
|
|
5866
|
+
return;
|
|
5867
|
+
}
|
|
5868
|
+
const reason = signal.reason;
|
|
5869
|
+
if (reason instanceof Error) {
|
|
5870
|
+
throw reason;
|
|
5871
|
+
}
|
|
5872
|
+
throw new Error("Z.ai request aborted");
|
|
5873
|
+
};
|
|
5874
|
+
var parseSseDataLine = (line) => {
|
|
5875
|
+
const trimmed = line.trim();
|
|
5876
|
+
if (!trimmed || trimmed.startsWith(":")) {
|
|
5877
|
+
return null;
|
|
5878
|
+
}
|
|
5879
|
+
if (!trimmed.startsWith("data:")) {
|
|
5880
|
+
return null;
|
|
5881
|
+
}
|
|
5882
|
+
const data = trimmed.slice("data:".length).trim();
|
|
5883
|
+
if (!data) {
|
|
5884
|
+
return null;
|
|
5885
|
+
}
|
|
5886
|
+
if (data === "[DONE]") {
|
|
5887
|
+
return "done";
|
|
5888
|
+
}
|
|
5889
|
+
try {
|
|
5890
|
+
return JSON.parse(data);
|
|
5891
|
+
} catch {
|
|
5892
|
+
throw new Error(`Malformed Z.ai stream chunk: ${data.slice(0, 300)}`);
|
|
5893
|
+
}
|
|
5894
|
+
};
|
|
5895
|
+
|
|
5896
|
+
// src/llm/zai/chat.ts
|
|
5897
|
+
var PROVIDER_NAME4 = "zai";
|
|
5898
|
+
var DEFAULT_BASE_URL = "https://api.z.ai/api/paas/v4";
|
|
5899
|
+
var DEFAULT_REASONING_EFFORT3 = "high";
|
|
5900
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 20 * 60 * 1e3;
|
|
5901
|
+
var ChatZai = class {
|
|
5902
|
+
provider = PROVIDER_NAME4;
|
|
5903
|
+
model;
|
|
5904
|
+
apiKey;
|
|
5905
|
+
baseURL;
|
|
5906
|
+
fetchImpl;
|
|
5907
|
+
timeoutMs;
|
|
5908
|
+
defaultReasoningEffort;
|
|
5909
|
+
reasoningLevelMeta;
|
|
5910
|
+
debugInvokeSeq = 0;
|
|
5911
|
+
lastDebugRequestPayload = null;
|
|
5912
|
+
constructor(options = {}) {
|
|
5913
|
+
this.apiKey = options.apiKey;
|
|
5914
|
+
this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
5915
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
5916
|
+
this.model = options.model ?? ZAI_DEFAULT_MODEL;
|
|
5917
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
5918
|
+
this.defaultReasoningEffort = options.reasoningEffort === void 0 ? DEFAULT_REASONING_EFFORT3 : options.reasoningEffort;
|
|
5919
|
+
this.reasoningLevelMeta = {
|
|
5920
|
+
requested: options.reasoningLevelRequested,
|
|
5921
|
+
applied: options.reasoningLevelApplied,
|
|
5922
|
+
fallbackApplied: options.reasoningFallbackApplied
|
|
5923
|
+
};
|
|
5924
|
+
}
|
|
5925
|
+
async ainvoke(input, _context) {
|
|
5926
|
+
const apiKey = this.apiKey;
|
|
5927
|
+
if (!apiKey) {
|
|
5928
|
+
throw new Error("Z.ai API key is required");
|
|
5929
|
+
}
|
|
5930
|
+
const {
|
|
5931
|
+
messages,
|
|
5932
|
+
tools: toolDefs,
|
|
5933
|
+
toolChoice,
|
|
5934
|
+
options,
|
|
5935
|
+
model,
|
|
5936
|
+
signal
|
|
5937
|
+
} = input;
|
|
5938
|
+
const { reasoningEffort, ...rest } = options ?? {};
|
|
5939
|
+
const effectiveReasoningEffort = reasoningEffort === void 0 ? this.defaultReasoningEffort : reasoningEffort;
|
|
5940
|
+
const tools = toZaiTools(toolDefs);
|
|
5941
|
+
const toolChoiceParam = toZaiToolChoice(toolChoice);
|
|
5942
|
+
const request = {
|
|
5943
|
+
model: model ?? this.model,
|
|
5944
|
+
messages: toZaiMessages(messages),
|
|
5945
|
+
stream: true,
|
|
5946
|
+
thinking: { type: "enabled" },
|
|
5947
|
+
...rest,
|
|
5948
|
+
...effectiveReasoningEffort ? { reasoning_effort: effectiveReasoningEffort } : {},
|
|
5949
|
+
...tools ? { tools } : {},
|
|
5950
|
+
...tools ? { tool_stream: true } : {},
|
|
5951
|
+
...toolChoiceParam ? { tool_choice: toolChoiceParam } : {}
|
|
5952
|
+
};
|
|
5953
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
5954
|
+
await this.debugRequestIfEnabled(request, debugSeq);
|
|
5955
|
+
const terminal = await this.streamRequest(apiKey, request, signal);
|
|
5956
|
+
await this.debugResponseIfEnabled(terminal, debugSeq);
|
|
5957
|
+
return toZaiChatInvokeCompletion(terminal.accumulated, {
|
|
5958
|
+
request_id: terminal.request_id ?? null,
|
|
5959
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
5960
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
5961
|
+
reasoning_effort: request.reasoning_effort,
|
|
5962
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
5963
|
+
});
|
|
5964
|
+
}
|
|
5965
|
+
async streamRequest(apiKey, request, signal) {
|
|
5966
|
+
const logSettings = getProviderLogSettings();
|
|
5967
|
+
return streamZaiChatCompletion({
|
|
5968
|
+
apiKey,
|
|
5969
|
+
baseURL: this.baseURL,
|
|
5970
|
+
fetchImpl: this.fetchImpl,
|
|
5971
|
+
request,
|
|
5972
|
+
signal,
|
|
5973
|
+
timeoutMs: this.timeoutMs,
|
|
5974
|
+
captureRawChunks: Boolean(logSettings.dumpDir)
|
|
5975
|
+
});
|
|
5976
|
+
}
|
|
5977
|
+
nextDebugInvokeSeq() {
|
|
5978
|
+
const seq = this.debugInvokeSeq + 1;
|
|
5979
|
+
this.debugInvokeSeq = seq;
|
|
5980
|
+
return seq;
|
|
5981
|
+
}
|
|
5982
|
+
async debugRequestIfEnabled(request, seq) {
|
|
5983
|
+
const settings = getProviderLogSettings();
|
|
5984
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
5985
|
+
return;
|
|
5986
|
+
}
|
|
5987
|
+
const payload = safeJsonStringify(request);
|
|
5988
|
+
const hash = createHash4("sha256").update(payload).digest("hex").slice(0, 16);
|
|
5989
|
+
const toolsHash = createHash4("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
5990
|
+
const previous = this.lastDebugRequestPayload;
|
|
5991
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
5992
|
+
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
5993
|
+
if (settings.enabled) {
|
|
5994
|
+
console.error(
|
|
5995
|
+
`[zai.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash}`
|
|
5996
|
+
);
|
|
5997
|
+
}
|
|
5998
|
+
if (settings.dumpDir) {
|
|
5999
|
+
try {
|
|
6000
|
+
await writeProviderLogDump(
|
|
6001
|
+
settings,
|
|
6002
|
+
PROVIDER_NAME4,
|
|
6003
|
+
seq,
|
|
6004
|
+
"request",
|
|
6005
|
+
request
|
|
6006
|
+
);
|
|
6007
|
+
} catch (error) {
|
|
6008
|
+
if (settings.enabled) {
|
|
6009
|
+
console.error(
|
|
6010
|
+
`[zai.request] dump_failed seq=${seq} error=${String(error)}`
|
|
6011
|
+
);
|
|
6012
|
+
}
|
|
6013
|
+
}
|
|
6014
|
+
}
|
|
6015
|
+
this.lastDebugRequestPayload = payload;
|
|
6016
|
+
}
|
|
6017
|
+
async debugResponseIfEnabled(response, seq) {
|
|
6018
|
+
const settings = getProviderLogSettings();
|
|
6019
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
6020
|
+
return;
|
|
6021
|
+
}
|
|
6022
|
+
const usage = response.accumulated.usage;
|
|
6023
|
+
if (settings.enabled) {
|
|
6024
|
+
const inputTokens = usage?.prompt_tokens ?? 0;
|
|
6025
|
+
const outputTokens = usage?.completion_tokens ?? 0;
|
|
6026
|
+
console.error(
|
|
6027
|
+
`[zai.response] seq=${seq} id=${response.accumulated.id ?? "unknown"} status=${response.status} chunks=${response.accumulated.rawChunkCount} finish=${String(response.accumulated.finishReason ?? "unknown")} tok_in=${inputTokens} tok_out=${outputTokens}`
|
|
6028
|
+
);
|
|
6029
|
+
}
|
|
6030
|
+
if (settings.dumpDir) {
|
|
6031
|
+
try {
|
|
6032
|
+
await writeProviderLogDump(
|
|
6033
|
+
settings,
|
|
6034
|
+
PROVIDER_NAME4,
|
|
6035
|
+
seq,
|
|
6036
|
+
"response",
|
|
6037
|
+
response.accumulated
|
|
6038
|
+
);
|
|
6039
|
+
} catch (error) {
|
|
6040
|
+
if (settings.enabled) {
|
|
6041
|
+
console.error(
|
|
6042
|
+
`[zai.response] dump_failed seq=${seq} error=${String(error)}`
|
|
6043
|
+
);
|
|
6044
|
+
}
|
|
6045
|
+
}
|
|
6046
|
+
}
|
|
6047
|
+
}
|
|
6048
|
+
};
|
|
6049
|
+
|
|
5428
6050
|
// src/prompts.ts
|
|
5429
6051
|
import path2 from "path";
|
|
5430
6052
|
import { fileURLToPath } from "url";
|
|
@@ -5564,6 +6186,7 @@ export {
|
|
|
5564
6186
|
ChatAnthropic,
|
|
5565
6187
|
ChatOpenAI,
|
|
5566
6188
|
ChatOpenRouter,
|
|
6189
|
+
ChatZai,
|
|
5567
6190
|
DEFAULT_MODEL_REGISTRY,
|
|
5568
6191
|
GOOGLE_MODELS,
|
|
5569
6192
|
OPENAI_DEFAULT_MODEL,
|
|
@@ -5571,6 +6194,9 @@ export {
|
|
|
5571
6194
|
OPENAI_MODELS,
|
|
5572
6195
|
TaskComplete,
|
|
5573
6196
|
ToolOutputCacheService,
|
|
6197
|
+
ZAI_DEFAULT_MODEL,
|
|
6198
|
+
ZAI_MODELS,
|
|
6199
|
+
ZAI_REASONING_EFFORT_MODELS,
|
|
5574
6200
|
applyModelMetadata,
|
|
5575
6201
|
createModelRegistry,
|
|
5576
6202
|
defineTool,
|