@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.cjs
CHANGED
|
@@ -36,6 +36,7 @@ __export(index_exports, {
|
|
|
36
36
|
ChatAnthropic: () => ChatAnthropic,
|
|
37
37
|
ChatOpenAI: () => ChatOpenAI,
|
|
38
38
|
ChatOpenRouter: () => ChatOpenRouter,
|
|
39
|
+
ChatZai: () => ChatZai,
|
|
39
40
|
DEFAULT_MODEL_REGISTRY: () => DEFAULT_MODEL_REGISTRY,
|
|
40
41
|
GOOGLE_MODELS: () => GOOGLE_MODELS,
|
|
41
42
|
OPENAI_DEFAULT_MODEL: () => OPENAI_DEFAULT_MODEL,
|
|
@@ -43,6 +44,9 @@ __export(index_exports, {
|
|
|
43
44
|
OPENAI_MODELS: () => OPENAI_MODELS,
|
|
44
45
|
TaskComplete: () => TaskComplete,
|
|
45
46
|
ToolOutputCacheService: () => ToolOutputCacheService,
|
|
47
|
+
ZAI_DEFAULT_MODEL: () => ZAI_DEFAULT_MODEL,
|
|
48
|
+
ZAI_MODELS: () => ZAI_MODELS,
|
|
49
|
+
ZAI_REASONING_EFFORT_MODELS: () => ZAI_REASONING_EFFORT_MODELS,
|
|
46
50
|
applyModelMetadata: () => applyModelMetadata,
|
|
47
51
|
createModelRegistry: () => createModelRegistry,
|
|
48
52
|
defineTool: () => defineTool,
|
|
@@ -62,8 +66,11 @@ module.exports = __toCommonJS(index_exports);
|
|
|
62
66
|
var import_config = require("@codelia/config");
|
|
63
67
|
|
|
64
68
|
// src/models/openai.ts
|
|
65
|
-
var OPENAI_DEFAULT_MODEL = "gpt-5.
|
|
69
|
+
var OPENAI_DEFAULT_MODEL = "gpt-5.6";
|
|
66
70
|
var OPENAI_DEFAULT_REASONING_EFFORT = "medium";
|
|
71
|
+
var GPT_5_6_CONTEXT_WINDOW = 105e4;
|
|
72
|
+
var GPT_5_6_MAX_INPUT_TOKENS = 922e3;
|
|
73
|
+
var GPT_5_6_MAX_OUTPUT_TOKENS = 128e3;
|
|
67
74
|
var GPT_5_4_CAPPED_INPUT_TOKENS = 272e3;
|
|
68
75
|
var OPENAI_MODELS = [
|
|
69
76
|
{
|
|
@@ -71,6 +78,38 @@ var OPENAI_MODELS = [
|
|
|
71
78
|
provider: "openai",
|
|
72
79
|
aliases: ["default"]
|
|
73
80
|
},
|
|
81
|
+
{
|
|
82
|
+
id: "gpt-5.6",
|
|
83
|
+
provider: "openai",
|
|
84
|
+
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
85
|
+
maxInputTokens: GPT_5_6_MAX_INPUT_TOKENS,
|
|
86
|
+
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS,
|
|
87
|
+
supportsFast: true
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
id: "gpt-5.6-sol",
|
|
91
|
+
provider: "openai",
|
|
92
|
+
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
93
|
+
maxInputTokens: GPT_5_6_MAX_INPUT_TOKENS,
|
|
94
|
+
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS,
|
|
95
|
+
supportsFast: true
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
id: "gpt-5.6-terra",
|
|
99
|
+
provider: "openai",
|
|
100
|
+
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
101
|
+
maxInputTokens: GPT_5_6_MAX_INPUT_TOKENS,
|
|
102
|
+
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS,
|
|
103
|
+
supportsFast: true
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
id: "gpt-5.6-luna",
|
|
107
|
+
provider: "openai",
|
|
108
|
+
contextWindow: GPT_5_6_CONTEXT_WINDOW,
|
|
109
|
+
maxInputTokens: GPT_5_6_MAX_INPUT_TOKENS,
|
|
110
|
+
maxOutputTokens: GPT_5_6_MAX_OUTPUT_TOKENS,
|
|
111
|
+
supportsFast: true
|
|
112
|
+
},
|
|
74
113
|
{
|
|
75
114
|
id: "gpt-5.5",
|
|
76
115
|
provider: "openai",
|
|
@@ -345,6 +384,14 @@ var ANTHROPIC_MODELS = [
|
|
|
345
384
|
provider: "anthropic",
|
|
346
385
|
aliases: ["default"]
|
|
347
386
|
},
|
|
387
|
+
{
|
|
388
|
+
id: "claude-opus-4-8",
|
|
389
|
+
provider: "anthropic",
|
|
390
|
+
contextWindow: 1e6,
|
|
391
|
+
maxInputTokens: 1e6,
|
|
392
|
+
maxOutputTokens: 128e3,
|
|
393
|
+
supportsFast: true
|
|
394
|
+
},
|
|
348
395
|
{
|
|
349
396
|
id: "claude-opus-4-7",
|
|
350
397
|
provider: "anthropic",
|
|
@@ -408,7 +455,8 @@ function createModelRegistry(specs) {
|
|
|
408
455
|
openai: {},
|
|
409
456
|
anthropic: {},
|
|
410
457
|
openrouter: {},
|
|
411
|
-
google: {}
|
|
458
|
+
google: {},
|
|
459
|
+
zai: {}
|
|
412
460
|
}
|
|
413
461
|
};
|
|
414
462
|
registerModels(registry, specs);
|
|
@@ -468,7 +516,8 @@ function cloneAliases(aliasesByProvider) {
|
|
|
468
516
|
openai: { ...aliasesByProvider.openai },
|
|
469
517
|
anthropic: { ...aliasesByProvider.anthropic },
|
|
470
518
|
openrouter: { ...aliasesByProvider.openrouter },
|
|
471
|
-
google: { ...aliasesByProvider.google }
|
|
519
|
+
google: { ...aliasesByProvider.google },
|
|
520
|
+
zai: { ...aliasesByProvider.zai }
|
|
472
521
|
};
|
|
473
522
|
}
|
|
474
523
|
function applyModelMetadata(registry, index) {
|
|
@@ -477,7 +526,7 @@ function applyModelMetadata(registry, index) {
|
|
|
477
526
|
aliasesByProvider: cloneAliases(registry.aliasesByProvider)
|
|
478
527
|
};
|
|
479
528
|
for (const [providerId, providerModels] of Object.entries(index.models)) {
|
|
480
|
-
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google") {
|
|
529
|
+
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google" && providerId !== "zai") {
|
|
481
530
|
continue;
|
|
482
531
|
}
|
|
483
532
|
const provider = providerId;
|
|
@@ -497,11 +546,50 @@ function applyModelMetadata(registry, index) {
|
|
|
497
546
|
return next;
|
|
498
547
|
}
|
|
499
548
|
|
|
549
|
+
// src/models/zai.ts
|
|
550
|
+
var ZAI_DEFAULT_MODEL = "glm-5.2";
|
|
551
|
+
var ZAI_REASONING_EFFORT_MODELS = /* @__PURE__ */ new Set(["glm-5.2"]);
|
|
552
|
+
var zaiModel = (id, limits) => ({
|
|
553
|
+
id,
|
|
554
|
+
provider: "zai",
|
|
555
|
+
aliases: limits.aliases,
|
|
556
|
+
contextWindow: limits.contextWindow,
|
|
557
|
+
maxInputTokens: limits.contextWindow,
|
|
558
|
+
maxOutputTokens: limits.maxOutputTokens,
|
|
559
|
+
supportsTools: true,
|
|
560
|
+
supportsReasoning: true,
|
|
561
|
+
supportsJsonSchema: true
|
|
562
|
+
});
|
|
563
|
+
var ZAI_MODELS = [
|
|
564
|
+
zaiModel(ZAI_DEFAULT_MODEL, {
|
|
565
|
+
aliases: ["default"],
|
|
566
|
+
contextWindow: 1e6,
|
|
567
|
+
maxOutputTokens: 131072
|
|
568
|
+
}),
|
|
569
|
+
zaiModel("glm-5.1", {
|
|
570
|
+
contextWindow: 2e5,
|
|
571
|
+
maxOutputTokens: 131072
|
|
572
|
+
}),
|
|
573
|
+
zaiModel("glm-5", {
|
|
574
|
+
contextWindow: 2e5,
|
|
575
|
+
maxOutputTokens: 131072
|
|
576
|
+
}),
|
|
577
|
+
zaiModel("glm-5-turbo", {
|
|
578
|
+
contextWindow: 2e5,
|
|
579
|
+
maxOutputTokens: 131072
|
|
580
|
+
}),
|
|
581
|
+
zaiModel("glm-4.7", {
|
|
582
|
+
contextWindow: 2e5,
|
|
583
|
+
maxOutputTokens: 131072
|
|
584
|
+
})
|
|
585
|
+
];
|
|
586
|
+
|
|
500
587
|
// src/models/index.ts
|
|
501
588
|
var DEFAULT_MODEL_REGISTRY = createModelRegistry([
|
|
502
589
|
...OPENAI_MODELS,
|
|
503
590
|
...ANTHROPIC_MODELS,
|
|
504
|
-
...GOOGLE_MODELS
|
|
591
|
+
...GOOGLE_MODELS,
|
|
592
|
+
...ZAI_MODELS
|
|
505
593
|
]);
|
|
506
594
|
|
|
507
595
|
// src/services/compaction/service.ts
|
|
@@ -866,7 +954,7 @@ var parseQualifiedModelId = (modelId) => {
|
|
|
866
954
|
if (!rest) {
|
|
867
955
|
return null;
|
|
868
956
|
}
|
|
869
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
957
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
870
958
|
return null;
|
|
871
959
|
}
|
|
872
960
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -1049,7 +1137,7 @@ var parseQualifiedModelId2 = (modelId) => {
|
|
|
1049
1137
|
if (!rest) {
|
|
1050
1138
|
return null;
|
|
1051
1139
|
}
|
|
1052
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
1140
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
1053
1141
|
return null;
|
|
1054
1142
|
}
|
|
1055
1143
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -1862,7 +1950,7 @@ var parseQualifiedModelId3 = (modelId) => {
|
|
|
1862
1950
|
if (!rest) {
|
|
1863
1951
|
return null;
|
|
1864
1952
|
}
|
|
1865
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
1953
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
1866
1954
|
return null;
|
|
1867
1955
|
}
|
|
1868
1956
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -5485,6 +5573,544 @@ var ChatOpenRouter = class {
|
|
|
5485
5573
|
}
|
|
5486
5574
|
};
|
|
5487
5575
|
|
|
5576
|
+
// src/llm/zai/chat.ts
|
|
5577
|
+
var import_node_crypto4 = require("crypto");
|
|
5578
|
+
|
|
5579
|
+
// src/llm/zai/serializer.ts
|
|
5580
|
+
var stringifyContentForZai = (content) => stringifyContent(content, { mode: "display", joiner: "" });
|
|
5581
|
+
function toZaiMessages(messages) {
|
|
5582
|
+
const mapped = [];
|
|
5583
|
+
for (const message of messages) {
|
|
5584
|
+
switch (message.role) {
|
|
5585
|
+
case "system":
|
|
5586
|
+
case "user": {
|
|
5587
|
+
mapped.push({
|
|
5588
|
+
role: message.role,
|
|
5589
|
+
content: stringifyContentForZai(message.content)
|
|
5590
|
+
});
|
|
5591
|
+
break;
|
|
5592
|
+
}
|
|
5593
|
+
case "assistant": {
|
|
5594
|
+
const content = stringifyContentForZai(message.content);
|
|
5595
|
+
const toolCalls = toZaiReplayToolCalls(message.tool_calls);
|
|
5596
|
+
mapped.push({
|
|
5597
|
+
role: "assistant",
|
|
5598
|
+
content: content || null,
|
|
5599
|
+
...toolCalls.length ? { tool_calls: toolCalls } : {}
|
|
5600
|
+
});
|
|
5601
|
+
break;
|
|
5602
|
+
}
|
|
5603
|
+
case "tool": {
|
|
5604
|
+
mapped.push({
|
|
5605
|
+
role: "tool",
|
|
5606
|
+
tool_call_id: message.tool_call_id,
|
|
5607
|
+
content: stringifyContentForZai(message.content)
|
|
5608
|
+
});
|
|
5609
|
+
break;
|
|
5610
|
+
}
|
|
5611
|
+
case "reasoning":
|
|
5612
|
+
break;
|
|
5613
|
+
}
|
|
5614
|
+
}
|
|
5615
|
+
return mapped;
|
|
5616
|
+
}
|
|
5617
|
+
function toZaiTools(tools) {
|
|
5618
|
+
if (!tools || tools.length === 0) {
|
|
5619
|
+
return void 0;
|
|
5620
|
+
}
|
|
5621
|
+
const mapped = [];
|
|
5622
|
+
for (const tool of tools) {
|
|
5623
|
+
if (isFunctionToolDefinition(tool)) {
|
|
5624
|
+
mapped.push({
|
|
5625
|
+
type: "function",
|
|
5626
|
+
function: {
|
|
5627
|
+
name: tool.name,
|
|
5628
|
+
description: tool.description,
|
|
5629
|
+
parameters: tool.parameters
|
|
5630
|
+
}
|
|
5631
|
+
});
|
|
5632
|
+
continue;
|
|
5633
|
+
}
|
|
5634
|
+
if (isHostedSearchToolDefinition(tool)) {
|
|
5635
|
+
continue;
|
|
5636
|
+
}
|
|
5637
|
+
}
|
|
5638
|
+
return mapped.length ? mapped : void 0;
|
|
5639
|
+
}
|
|
5640
|
+
function toZaiToolChoice(choice) {
|
|
5641
|
+
if (!choice) {
|
|
5642
|
+
return void 0;
|
|
5643
|
+
}
|
|
5644
|
+
if (choice === "auto" || choice === "required" || choice === "none") {
|
|
5645
|
+
return choice;
|
|
5646
|
+
}
|
|
5647
|
+
return { type: "function", function: { name: choice } };
|
|
5648
|
+
}
|
|
5649
|
+
var createZaiStreamAccumulator = (options) => ({
|
|
5650
|
+
content: "",
|
|
5651
|
+
reasoningContent: "",
|
|
5652
|
+
toolCalls: [],
|
|
5653
|
+
rawChunkCount: 0,
|
|
5654
|
+
rawChunks: [],
|
|
5655
|
+
captureRawChunks: options?.captureRawChunks ?? false
|
|
5656
|
+
});
|
|
5657
|
+
function appendZaiChatCompletionChunk(accumulator, chunk) {
|
|
5658
|
+
accumulator.rawChunkCount += 1;
|
|
5659
|
+
if (accumulator.captureRawChunks) {
|
|
5660
|
+
accumulator.rawChunks.push(chunk);
|
|
5661
|
+
}
|
|
5662
|
+
accumulator.id ??= chunk.id;
|
|
5663
|
+
accumulator.model ??= chunk.model;
|
|
5664
|
+
accumulator.created ??= chunk.created;
|
|
5665
|
+
accumulator.usage ??= chunk.usage ?? void 0;
|
|
5666
|
+
for (const choice of chunk.choices ?? []) {
|
|
5667
|
+
if (choice.finish_reason !== void 0) {
|
|
5668
|
+
accumulator.finishReason = choice.finish_reason;
|
|
5669
|
+
}
|
|
5670
|
+
const delta = choice.delta;
|
|
5671
|
+
if (!delta) {
|
|
5672
|
+
continue;
|
|
5673
|
+
}
|
|
5674
|
+
if (typeof delta.reasoning_content === "string") {
|
|
5675
|
+
accumulator.reasoningContent += delta.reasoning_content;
|
|
5676
|
+
}
|
|
5677
|
+
if (typeof delta.content === "string") {
|
|
5678
|
+
accumulator.content += delta.content;
|
|
5679
|
+
}
|
|
5680
|
+
for (const toolCallDelta of delta.tool_calls ?? []) {
|
|
5681
|
+
const index = typeof toolCallDelta.index === "number" ? toolCallDelta.index : accumulator.toolCalls.length;
|
|
5682
|
+
let call = accumulator.toolCalls.find((entry) => entry.index === index);
|
|
5683
|
+
if (!call) {
|
|
5684
|
+
call = {
|
|
5685
|
+
index,
|
|
5686
|
+
id: toolCallDelta.id ?? `call_${index}`,
|
|
5687
|
+
type: "function",
|
|
5688
|
+
name: "",
|
|
5689
|
+
arguments: "",
|
|
5690
|
+
raw_chunk_count: 0
|
|
5691
|
+
};
|
|
5692
|
+
accumulator.toolCalls.push(call);
|
|
5693
|
+
accumulator.toolCalls.sort((left, right) => left.index - right.index);
|
|
5694
|
+
}
|
|
5695
|
+
call.raw_chunk_count += 1;
|
|
5696
|
+
if (typeof toolCallDelta.id === "string" && toolCallDelta.id) {
|
|
5697
|
+
call.id = toolCallDelta.id;
|
|
5698
|
+
}
|
|
5699
|
+
if (toolCallDelta.type === "function") {
|
|
5700
|
+
call.type = "function";
|
|
5701
|
+
}
|
|
5702
|
+
if (typeof toolCallDelta.function?.name === "string") {
|
|
5703
|
+
call.name = toolCallDelta.function.name;
|
|
5704
|
+
}
|
|
5705
|
+
if (typeof toolCallDelta.function?.arguments === "string") {
|
|
5706
|
+
call.arguments += toolCallDelta.function.arguments;
|
|
5707
|
+
}
|
|
5708
|
+
}
|
|
5709
|
+
}
|
|
5710
|
+
}
|
|
5711
|
+
function toZaiChatInvokeCompletion(accumulator, meta) {
|
|
5712
|
+
const messages = [];
|
|
5713
|
+
if (accumulator.reasoningContent) {
|
|
5714
|
+
messages.push({
|
|
5715
|
+
role: "reasoning",
|
|
5716
|
+
content: accumulator.reasoningContent,
|
|
5717
|
+
raw_item: {
|
|
5718
|
+
provider: "zai",
|
|
5719
|
+
field: "reasoning_content",
|
|
5720
|
+
response_id: accumulator.id
|
|
5721
|
+
}
|
|
5722
|
+
});
|
|
5723
|
+
}
|
|
5724
|
+
const toolCalls = accumulator.toolCalls.filter((call) => call.name || call.arguments || call.id).map(toToolCall);
|
|
5725
|
+
if (accumulator.content || toolCalls.length) {
|
|
5726
|
+
messages.push({
|
|
5727
|
+
role: "assistant",
|
|
5728
|
+
content: accumulator.content || null,
|
|
5729
|
+
...toolCalls.length ? { tool_calls: toolCalls } : {}
|
|
5730
|
+
});
|
|
5731
|
+
}
|
|
5732
|
+
const usage = normalizeZaiUsage(accumulator);
|
|
5733
|
+
return {
|
|
5734
|
+
messages,
|
|
5735
|
+
usage,
|
|
5736
|
+
stop_reason: accumulator.finishReason ?? null,
|
|
5737
|
+
provider_meta: {
|
|
5738
|
+
response_id: accumulator.id,
|
|
5739
|
+
request_id: meta?.request_id ?? void 0,
|
|
5740
|
+
finish_reason: accumulator.finishReason ?? null,
|
|
5741
|
+
reasoning_requested: meta?.reasoning_requested,
|
|
5742
|
+
reasoning_applied: meta?.reasoning_applied,
|
|
5743
|
+
reasoning_effort: meta?.reasoning_effort,
|
|
5744
|
+
reasoning_fallback: meta?.reasoning_fallback
|
|
5745
|
+
}
|
|
5746
|
+
};
|
|
5747
|
+
}
|
|
5748
|
+
var toZaiReplayToolCalls = (toolCalls) => {
|
|
5749
|
+
if (!toolCalls?.length) {
|
|
5750
|
+
return [];
|
|
5751
|
+
}
|
|
5752
|
+
return toolCalls.map((call) => ({
|
|
5753
|
+
id: call.id,
|
|
5754
|
+
type: "function",
|
|
5755
|
+
function: {
|
|
5756
|
+
name: call.function.name,
|
|
5757
|
+
arguments: call.function.arguments
|
|
5758
|
+
}
|
|
5759
|
+
}));
|
|
5760
|
+
};
|
|
5761
|
+
var toToolCall = (call) => ({
|
|
5762
|
+
id: call.id,
|
|
5763
|
+
type: "function",
|
|
5764
|
+
function: {
|
|
5765
|
+
name: call.name,
|
|
5766
|
+
arguments: call.arguments
|
|
5767
|
+
},
|
|
5768
|
+
provider_meta: {
|
|
5769
|
+
provider: "zai",
|
|
5770
|
+
index: call.index,
|
|
5771
|
+
raw_chunk_count: call.raw_chunk_count
|
|
5772
|
+
}
|
|
5773
|
+
});
|
|
5774
|
+
var normalizeNumber = (value) => {
|
|
5775
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
5776
|
+
return 0;
|
|
5777
|
+
}
|
|
5778
|
+
return Math.trunc(value);
|
|
5779
|
+
};
|
|
5780
|
+
var normalizeZaiUsage = (accumulator) => {
|
|
5781
|
+
const usage = accumulator.usage;
|
|
5782
|
+
if (!usage) {
|
|
5783
|
+
return null;
|
|
5784
|
+
}
|
|
5785
|
+
const inputTokens = normalizeNumber(usage.prompt_tokens);
|
|
5786
|
+
const outputTokens = normalizeNumber(usage.completion_tokens);
|
|
5787
|
+
const totalTokens = typeof usage.total_tokens === "number" ? normalizeNumber(usage.total_tokens) : inputTokens + outputTokens;
|
|
5788
|
+
const cachedTokens = normalizeNumber(
|
|
5789
|
+
usage.prompt_tokens_details?.cached_tokens
|
|
5790
|
+
);
|
|
5791
|
+
return {
|
|
5792
|
+
model: accumulator.model ?? "",
|
|
5793
|
+
input_tokens: inputTokens,
|
|
5794
|
+
...cachedTokens > 0 ? { input_cached_tokens: cachedTokens } : {},
|
|
5795
|
+
output_tokens: outputTokens,
|
|
5796
|
+
total_tokens: totalTokens
|
|
5797
|
+
};
|
|
5798
|
+
};
|
|
5799
|
+
|
|
5800
|
+
// src/llm/zai/transport.ts
|
|
5801
|
+
var streamZaiChatCompletion = async ({
|
|
5802
|
+
apiKey,
|
|
5803
|
+
baseURL,
|
|
5804
|
+
fetchImpl,
|
|
5805
|
+
request,
|
|
5806
|
+
signal,
|
|
5807
|
+
timeoutMs,
|
|
5808
|
+
captureRawChunks
|
|
5809
|
+
}) => {
|
|
5810
|
+
const requestSignal = createZaiRequestSignal(signal, timeoutMs);
|
|
5811
|
+
try {
|
|
5812
|
+
const response = await fetchImpl(`${baseURL}/chat/completions`, {
|
|
5813
|
+
method: "POST",
|
|
5814
|
+
headers: {
|
|
5815
|
+
Authorization: `Bearer ${apiKey}`,
|
|
5816
|
+
"Content-Type": "application/json"
|
|
5817
|
+
},
|
|
5818
|
+
body: safeJsonStringify(request),
|
|
5819
|
+
signal: requestSignal.signal
|
|
5820
|
+
});
|
|
5821
|
+
if (!response.ok) {
|
|
5822
|
+
throw await toZaiHttpError(response);
|
|
5823
|
+
}
|
|
5824
|
+
const accumulated = createZaiStreamAccumulator({
|
|
5825
|
+
captureRawChunks: captureRawChunks ?? false
|
|
5826
|
+
});
|
|
5827
|
+
for await (const chunk of readZaiChatCompletionStream(
|
|
5828
|
+
response,
|
|
5829
|
+
requestSignal.signal
|
|
5830
|
+
)) {
|
|
5831
|
+
appendZaiChatCompletionChunk(accumulated, chunk);
|
|
5832
|
+
}
|
|
5833
|
+
return {
|
|
5834
|
+
status: response.status,
|
|
5835
|
+
request_id: response.headers.get("x-request-id"),
|
|
5836
|
+
accumulated
|
|
5837
|
+
};
|
|
5838
|
+
} finally {
|
|
5839
|
+
requestSignal.cleanup();
|
|
5840
|
+
}
|
|
5841
|
+
};
|
|
5842
|
+
async function* readZaiChatCompletionStream(response, signal) {
|
|
5843
|
+
if (!response.body) {
|
|
5844
|
+
throw new Error("Z.ai provider error: response body is empty");
|
|
5845
|
+
}
|
|
5846
|
+
const reader = response.body.getReader();
|
|
5847
|
+
throwIfAborted2(signal);
|
|
5848
|
+
const cancelOnAbort = () => {
|
|
5849
|
+
void reader.cancel(signal?.reason).catch(() => void 0);
|
|
5850
|
+
};
|
|
5851
|
+
signal?.addEventListener("abort", cancelOnAbort, { once: true });
|
|
5852
|
+
const decoder = new TextDecoder();
|
|
5853
|
+
let buffer = "";
|
|
5854
|
+
try {
|
|
5855
|
+
while (true) {
|
|
5856
|
+
throwIfAborted2(signal);
|
|
5857
|
+
const { done, value } = await reader.read();
|
|
5858
|
+
throwIfAborted2(signal);
|
|
5859
|
+
if (done) {
|
|
5860
|
+
break;
|
|
5861
|
+
}
|
|
5862
|
+
buffer += decoder.decode(value, { stream: true });
|
|
5863
|
+
let newlineIndex = buffer.indexOf("\n");
|
|
5864
|
+
while (newlineIndex >= 0) {
|
|
5865
|
+
const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
|
|
5866
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
5867
|
+
const chunk = parseSseDataLine(line);
|
|
5868
|
+
if (chunk === "done") {
|
|
5869
|
+
return;
|
|
5870
|
+
}
|
|
5871
|
+
if (chunk) {
|
|
5872
|
+
yield chunk;
|
|
5873
|
+
}
|
|
5874
|
+
newlineIndex = buffer.indexOf("\n");
|
|
5875
|
+
}
|
|
5876
|
+
}
|
|
5877
|
+
buffer += decoder.decode();
|
|
5878
|
+
const trailing = buffer.trim();
|
|
5879
|
+
if (trailing) {
|
|
5880
|
+
const chunk = parseSseDataLine(trailing);
|
|
5881
|
+
if (chunk && chunk !== "done") {
|
|
5882
|
+
yield chunk;
|
|
5883
|
+
}
|
|
5884
|
+
}
|
|
5885
|
+
} finally {
|
|
5886
|
+
signal?.removeEventListener("abort", cancelOnAbort);
|
|
5887
|
+
reader.releaseLock();
|
|
5888
|
+
}
|
|
5889
|
+
}
|
|
5890
|
+
var createZaiRequestSignal = (signal, timeoutMs) => {
|
|
5891
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
5892
|
+
return { signal, cleanup: () => void 0 };
|
|
5893
|
+
}
|
|
5894
|
+
const controller = new AbortController();
|
|
5895
|
+
let timeout = setTimeout(() => {
|
|
5896
|
+
controller.abort(new Error("Z.ai request timeout"));
|
|
5897
|
+
}, timeoutMs);
|
|
5898
|
+
const onAbort = () => {
|
|
5899
|
+
controller.abort(signal?.reason);
|
|
5900
|
+
};
|
|
5901
|
+
if (signal?.aborted) {
|
|
5902
|
+
onAbort();
|
|
5903
|
+
} else {
|
|
5904
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
5905
|
+
}
|
|
5906
|
+
return {
|
|
5907
|
+
signal: controller.signal,
|
|
5908
|
+
cleanup: () => {
|
|
5909
|
+
if (timeout) {
|
|
5910
|
+
clearTimeout(timeout);
|
|
5911
|
+
timeout = void 0;
|
|
5912
|
+
}
|
|
5913
|
+
signal?.removeEventListener("abort", onAbort);
|
|
5914
|
+
}
|
|
5915
|
+
};
|
|
5916
|
+
};
|
|
5917
|
+
var toZaiHttpError = async (response) => {
|
|
5918
|
+
let body = "";
|
|
5919
|
+
try {
|
|
5920
|
+
body = await response.text();
|
|
5921
|
+
} catch {
|
|
5922
|
+
body = "";
|
|
5923
|
+
}
|
|
5924
|
+
const snippet = body ? body.slice(0, 500) : "(empty)";
|
|
5925
|
+
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";
|
|
5926
|
+
return new Error(`${prefix} (${response.status}): ${snippet}`);
|
|
5927
|
+
};
|
|
5928
|
+
var throwIfAborted2 = (signal) => {
|
|
5929
|
+
if (!signal?.aborted) {
|
|
5930
|
+
return;
|
|
5931
|
+
}
|
|
5932
|
+
const reason = signal.reason;
|
|
5933
|
+
if (reason instanceof Error) {
|
|
5934
|
+
throw reason;
|
|
5935
|
+
}
|
|
5936
|
+
throw new Error("Z.ai request aborted");
|
|
5937
|
+
};
|
|
5938
|
+
var parseSseDataLine = (line) => {
|
|
5939
|
+
const trimmed = line.trim();
|
|
5940
|
+
if (!trimmed || trimmed.startsWith(":")) {
|
|
5941
|
+
return null;
|
|
5942
|
+
}
|
|
5943
|
+
if (!trimmed.startsWith("data:")) {
|
|
5944
|
+
return null;
|
|
5945
|
+
}
|
|
5946
|
+
const data = trimmed.slice("data:".length).trim();
|
|
5947
|
+
if (!data) {
|
|
5948
|
+
return null;
|
|
5949
|
+
}
|
|
5950
|
+
if (data === "[DONE]") {
|
|
5951
|
+
return "done";
|
|
5952
|
+
}
|
|
5953
|
+
try {
|
|
5954
|
+
return JSON.parse(data);
|
|
5955
|
+
} catch {
|
|
5956
|
+
throw new Error(`Malformed Z.ai stream chunk: ${data.slice(0, 300)}`);
|
|
5957
|
+
}
|
|
5958
|
+
};
|
|
5959
|
+
|
|
5960
|
+
// src/llm/zai/chat.ts
|
|
5961
|
+
var PROVIDER_NAME4 = "zai";
|
|
5962
|
+
var DEFAULT_BASE_URL = "https://api.z.ai/api/paas/v4";
|
|
5963
|
+
var DEFAULT_REASONING_EFFORT3 = "high";
|
|
5964
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 20 * 60 * 1e3;
|
|
5965
|
+
var ChatZai = class {
|
|
5966
|
+
provider = PROVIDER_NAME4;
|
|
5967
|
+
model;
|
|
5968
|
+
apiKey;
|
|
5969
|
+
baseURL;
|
|
5970
|
+
fetchImpl;
|
|
5971
|
+
timeoutMs;
|
|
5972
|
+
defaultReasoningEffort;
|
|
5973
|
+
reasoningLevelMeta;
|
|
5974
|
+
debugInvokeSeq = 0;
|
|
5975
|
+
lastDebugRequestPayload = null;
|
|
5976
|
+
constructor(options = {}) {
|
|
5977
|
+
this.apiKey = options.apiKey;
|
|
5978
|
+
this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
5979
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
5980
|
+
this.model = options.model ?? ZAI_DEFAULT_MODEL;
|
|
5981
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
5982
|
+
this.defaultReasoningEffort = options.reasoningEffort === void 0 ? DEFAULT_REASONING_EFFORT3 : options.reasoningEffort;
|
|
5983
|
+
this.reasoningLevelMeta = {
|
|
5984
|
+
requested: options.reasoningLevelRequested,
|
|
5985
|
+
applied: options.reasoningLevelApplied,
|
|
5986
|
+
fallbackApplied: options.reasoningFallbackApplied
|
|
5987
|
+
};
|
|
5988
|
+
}
|
|
5989
|
+
async ainvoke(input, _context) {
|
|
5990
|
+
const apiKey = this.apiKey;
|
|
5991
|
+
if (!apiKey) {
|
|
5992
|
+
throw new Error("Z.ai API key is required");
|
|
5993
|
+
}
|
|
5994
|
+
const {
|
|
5995
|
+
messages,
|
|
5996
|
+
tools: toolDefs,
|
|
5997
|
+
toolChoice,
|
|
5998
|
+
options,
|
|
5999
|
+
model,
|
|
6000
|
+
signal
|
|
6001
|
+
} = input;
|
|
6002
|
+
const { reasoningEffort, ...rest } = options ?? {};
|
|
6003
|
+
const effectiveReasoningEffort = reasoningEffort === void 0 ? this.defaultReasoningEffort : reasoningEffort;
|
|
6004
|
+
const tools = toZaiTools(toolDefs);
|
|
6005
|
+
const toolChoiceParam = toZaiToolChoice(toolChoice);
|
|
6006
|
+
const request = {
|
|
6007
|
+
model: model ?? this.model,
|
|
6008
|
+
messages: toZaiMessages(messages),
|
|
6009
|
+
stream: true,
|
|
6010
|
+
thinking: { type: "enabled" },
|
|
6011
|
+
...rest,
|
|
6012
|
+
...effectiveReasoningEffort ? { reasoning_effort: effectiveReasoningEffort } : {},
|
|
6013
|
+
...tools ? { tools } : {},
|
|
6014
|
+
...tools ? { tool_stream: true } : {},
|
|
6015
|
+
...toolChoiceParam ? { tool_choice: toolChoiceParam } : {}
|
|
6016
|
+
};
|
|
6017
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
6018
|
+
await this.debugRequestIfEnabled(request, debugSeq);
|
|
6019
|
+
const terminal = await this.streamRequest(apiKey, request, signal);
|
|
6020
|
+
await this.debugResponseIfEnabled(terminal, debugSeq);
|
|
6021
|
+
return toZaiChatInvokeCompletion(terminal.accumulated, {
|
|
6022
|
+
request_id: terminal.request_id ?? null,
|
|
6023
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
6024
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
6025
|
+
reasoning_effort: request.reasoning_effort,
|
|
6026
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
6027
|
+
});
|
|
6028
|
+
}
|
|
6029
|
+
async streamRequest(apiKey, request, signal) {
|
|
6030
|
+
const logSettings = getProviderLogSettings();
|
|
6031
|
+
return streamZaiChatCompletion({
|
|
6032
|
+
apiKey,
|
|
6033
|
+
baseURL: this.baseURL,
|
|
6034
|
+
fetchImpl: this.fetchImpl,
|
|
6035
|
+
request,
|
|
6036
|
+
signal,
|
|
6037
|
+
timeoutMs: this.timeoutMs,
|
|
6038
|
+
captureRawChunks: Boolean(logSettings.dumpDir)
|
|
6039
|
+
});
|
|
6040
|
+
}
|
|
6041
|
+
nextDebugInvokeSeq() {
|
|
6042
|
+
const seq = this.debugInvokeSeq + 1;
|
|
6043
|
+
this.debugInvokeSeq = seq;
|
|
6044
|
+
return seq;
|
|
6045
|
+
}
|
|
6046
|
+
async debugRequestIfEnabled(request, seq) {
|
|
6047
|
+
const settings = getProviderLogSettings();
|
|
6048
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
6049
|
+
return;
|
|
6050
|
+
}
|
|
6051
|
+
const payload = safeJsonStringify(request);
|
|
6052
|
+
const hash = (0, import_node_crypto4.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
6053
|
+
const toolsHash = (0, import_node_crypto4.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
6054
|
+
const previous = this.lastDebugRequestPayload;
|
|
6055
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6056
|
+
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
6057
|
+
if (settings.enabled) {
|
|
6058
|
+
console.error(
|
|
6059
|
+
`[zai.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash}`
|
|
6060
|
+
);
|
|
6061
|
+
}
|
|
6062
|
+
if (settings.dumpDir) {
|
|
6063
|
+
try {
|
|
6064
|
+
await writeProviderLogDump(
|
|
6065
|
+
settings,
|
|
6066
|
+
PROVIDER_NAME4,
|
|
6067
|
+
seq,
|
|
6068
|
+
"request",
|
|
6069
|
+
request
|
|
6070
|
+
);
|
|
6071
|
+
} catch (error) {
|
|
6072
|
+
if (settings.enabled) {
|
|
6073
|
+
console.error(
|
|
6074
|
+
`[zai.request] dump_failed seq=${seq} error=${String(error)}`
|
|
6075
|
+
);
|
|
6076
|
+
}
|
|
6077
|
+
}
|
|
6078
|
+
}
|
|
6079
|
+
this.lastDebugRequestPayload = payload;
|
|
6080
|
+
}
|
|
6081
|
+
async debugResponseIfEnabled(response, seq) {
|
|
6082
|
+
const settings = getProviderLogSettings();
|
|
6083
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
6084
|
+
return;
|
|
6085
|
+
}
|
|
6086
|
+
const usage = response.accumulated.usage;
|
|
6087
|
+
if (settings.enabled) {
|
|
6088
|
+
const inputTokens = usage?.prompt_tokens ?? 0;
|
|
6089
|
+
const outputTokens = usage?.completion_tokens ?? 0;
|
|
6090
|
+
console.error(
|
|
6091
|
+
`[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}`
|
|
6092
|
+
);
|
|
6093
|
+
}
|
|
6094
|
+
if (settings.dumpDir) {
|
|
6095
|
+
try {
|
|
6096
|
+
await writeProviderLogDump(
|
|
6097
|
+
settings,
|
|
6098
|
+
PROVIDER_NAME4,
|
|
6099
|
+
seq,
|
|
6100
|
+
"response",
|
|
6101
|
+
response.accumulated
|
|
6102
|
+
);
|
|
6103
|
+
} catch (error) {
|
|
6104
|
+
if (settings.enabled) {
|
|
6105
|
+
console.error(
|
|
6106
|
+
`[zai.response] dump_failed seq=${seq} error=${String(error)}`
|
|
6107
|
+
);
|
|
6108
|
+
}
|
|
6109
|
+
}
|
|
6110
|
+
}
|
|
6111
|
+
}
|
|
6112
|
+
};
|
|
6113
|
+
|
|
5488
6114
|
// src/prompts.ts
|
|
5489
6115
|
var import_node_path2 = __toESM(require("path"), 1);
|
|
5490
6116
|
var import_node_url = require("url");
|
|
@@ -5626,6 +6252,7 @@ function defineTool(toolOptions) {
|
|
|
5626
6252
|
ChatAnthropic,
|
|
5627
6253
|
ChatOpenAI,
|
|
5628
6254
|
ChatOpenRouter,
|
|
6255
|
+
ChatZai,
|
|
5629
6256
|
DEFAULT_MODEL_REGISTRY,
|
|
5630
6257
|
GOOGLE_MODELS,
|
|
5631
6258
|
OPENAI_DEFAULT_MODEL,
|
|
@@ -5633,6 +6260,9 @@ function defineTool(toolOptions) {
|
|
|
5633
6260
|
OPENAI_MODELS,
|
|
5634
6261
|
TaskComplete,
|
|
5635
6262
|
ToolOutputCacheService,
|
|
6263
|
+
ZAI_DEFAULT_MODEL,
|
|
6264
|
+
ZAI_MODELS,
|
|
6265
|
+
ZAI_REASONING_EFFORT_MODELS,
|
|
5636
6266
|
applyModelMetadata,
|
|
5637
6267
|
createModelRegistry,
|
|
5638
6268
|
defineTool,
|