@codelia/core 0.1.68 → 0.1.69
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 +602 -7
- package/dist/index.d.cts +58 -11
- package/dist/index.d.ts +58 -11
- package/dist/index.js +598 -7
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -285,6 +285,14 @@ var ANTHROPIC_MODELS = [
|
|
|
285
285
|
provider: "anthropic",
|
|
286
286
|
aliases: ["default"]
|
|
287
287
|
},
|
|
288
|
+
{
|
|
289
|
+
id: "claude-opus-4-8",
|
|
290
|
+
provider: "anthropic",
|
|
291
|
+
contextWindow: 1e6,
|
|
292
|
+
maxInputTokens: 1e6,
|
|
293
|
+
maxOutputTokens: 128e3,
|
|
294
|
+
supportsFast: true
|
|
295
|
+
},
|
|
288
296
|
{
|
|
289
297
|
id: "claude-opus-4-7",
|
|
290
298
|
provider: "anthropic",
|
|
@@ -348,7 +356,8 @@ function createModelRegistry(specs) {
|
|
|
348
356
|
openai: {},
|
|
349
357
|
anthropic: {},
|
|
350
358
|
openrouter: {},
|
|
351
|
-
google: {}
|
|
359
|
+
google: {},
|
|
360
|
+
zai: {}
|
|
352
361
|
}
|
|
353
362
|
};
|
|
354
363
|
registerModels(registry, specs);
|
|
@@ -408,7 +417,8 @@ function cloneAliases(aliasesByProvider) {
|
|
|
408
417
|
openai: { ...aliasesByProvider.openai },
|
|
409
418
|
anthropic: { ...aliasesByProvider.anthropic },
|
|
410
419
|
openrouter: { ...aliasesByProvider.openrouter },
|
|
411
|
-
google: { ...aliasesByProvider.google }
|
|
420
|
+
google: { ...aliasesByProvider.google },
|
|
421
|
+
zai: { ...aliasesByProvider.zai }
|
|
412
422
|
};
|
|
413
423
|
}
|
|
414
424
|
function applyModelMetadata(registry, index) {
|
|
@@ -417,7 +427,7 @@ function applyModelMetadata(registry, index) {
|
|
|
417
427
|
aliasesByProvider: cloneAliases(registry.aliasesByProvider)
|
|
418
428
|
};
|
|
419
429
|
for (const [providerId, providerModels] of Object.entries(index.models)) {
|
|
420
|
-
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google") {
|
|
430
|
+
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google" && providerId !== "zai") {
|
|
421
431
|
continue;
|
|
422
432
|
}
|
|
423
433
|
const provider = providerId;
|
|
@@ -437,11 +447,50 @@ function applyModelMetadata(registry, index) {
|
|
|
437
447
|
return next;
|
|
438
448
|
}
|
|
439
449
|
|
|
450
|
+
// src/models/zai.ts
|
|
451
|
+
var ZAI_DEFAULT_MODEL = "glm-5.2";
|
|
452
|
+
var ZAI_REASONING_EFFORT_MODELS = /* @__PURE__ */ new Set(["glm-5.2"]);
|
|
453
|
+
var zaiModel = (id, limits) => ({
|
|
454
|
+
id,
|
|
455
|
+
provider: "zai",
|
|
456
|
+
aliases: limits.aliases,
|
|
457
|
+
contextWindow: limits.contextWindow,
|
|
458
|
+
maxInputTokens: limits.contextWindow,
|
|
459
|
+
maxOutputTokens: limits.maxOutputTokens,
|
|
460
|
+
supportsTools: true,
|
|
461
|
+
supportsReasoning: true,
|
|
462
|
+
supportsJsonSchema: true
|
|
463
|
+
});
|
|
464
|
+
var ZAI_MODELS = [
|
|
465
|
+
zaiModel(ZAI_DEFAULT_MODEL, {
|
|
466
|
+
aliases: ["default"],
|
|
467
|
+
contextWindow: 1e6,
|
|
468
|
+
maxOutputTokens: 131072
|
|
469
|
+
}),
|
|
470
|
+
zaiModel("glm-5.1", {
|
|
471
|
+
contextWindow: 2e5,
|
|
472
|
+
maxOutputTokens: 131072
|
|
473
|
+
}),
|
|
474
|
+
zaiModel("glm-5", {
|
|
475
|
+
contextWindow: 2e5,
|
|
476
|
+
maxOutputTokens: 131072
|
|
477
|
+
}),
|
|
478
|
+
zaiModel("glm-5-turbo", {
|
|
479
|
+
contextWindow: 2e5,
|
|
480
|
+
maxOutputTokens: 131072
|
|
481
|
+
}),
|
|
482
|
+
zaiModel("glm-4.7", {
|
|
483
|
+
contextWindow: 2e5,
|
|
484
|
+
maxOutputTokens: 131072
|
|
485
|
+
})
|
|
486
|
+
];
|
|
487
|
+
|
|
440
488
|
// src/models/index.ts
|
|
441
489
|
var DEFAULT_MODEL_REGISTRY = createModelRegistry([
|
|
442
490
|
...OPENAI_MODELS,
|
|
443
491
|
...ANTHROPIC_MODELS,
|
|
444
|
-
...GOOGLE_MODELS
|
|
492
|
+
...GOOGLE_MODELS,
|
|
493
|
+
...ZAI_MODELS
|
|
445
494
|
]);
|
|
446
495
|
|
|
447
496
|
// src/services/compaction/service.ts
|
|
@@ -806,7 +855,7 @@ var parseQualifiedModelId = (modelId) => {
|
|
|
806
855
|
if (!rest) {
|
|
807
856
|
return null;
|
|
808
857
|
}
|
|
809
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
858
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
810
859
|
return null;
|
|
811
860
|
}
|
|
812
861
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -989,7 +1038,7 @@ var parseQualifiedModelId2 = (modelId) => {
|
|
|
989
1038
|
if (!rest) {
|
|
990
1039
|
return null;
|
|
991
1040
|
}
|
|
992
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
1041
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
993
1042
|
return null;
|
|
994
1043
|
}
|
|
995
1044
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -1802,7 +1851,7 @@ var parseQualifiedModelId3 = (modelId) => {
|
|
|
1802
1851
|
if (!rest) {
|
|
1803
1852
|
return null;
|
|
1804
1853
|
}
|
|
1805
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
1854
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
|
|
1806
1855
|
return null;
|
|
1807
1856
|
}
|
|
1808
1857
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -5425,6 +5474,544 @@ var ChatOpenRouter = class {
|
|
|
5425
5474
|
}
|
|
5426
5475
|
};
|
|
5427
5476
|
|
|
5477
|
+
// src/llm/zai/chat.ts
|
|
5478
|
+
import { createHash as createHash4 } from "crypto";
|
|
5479
|
+
|
|
5480
|
+
// src/llm/zai/serializer.ts
|
|
5481
|
+
var stringifyContentForZai = (content) => stringifyContent(content, { mode: "display", joiner: "" });
|
|
5482
|
+
function toZaiMessages(messages) {
|
|
5483
|
+
const mapped = [];
|
|
5484
|
+
for (const message of messages) {
|
|
5485
|
+
switch (message.role) {
|
|
5486
|
+
case "system":
|
|
5487
|
+
case "user": {
|
|
5488
|
+
mapped.push({
|
|
5489
|
+
role: message.role,
|
|
5490
|
+
content: stringifyContentForZai(message.content)
|
|
5491
|
+
});
|
|
5492
|
+
break;
|
|
5493
|
+
}
|
|
5494
|
+
case "assistant": {
|
|
5495
|
+
const content = stringifyContentForZai(message.content);
|
|
5496
|
+
const toolCalls = toZaiReplayToolCalls(message.tool_calls);
|
|
5497
|
+
mapped.push({
|
|
5498
|
+
role: "assistant",
|
|
5499
|
+
content: content || null,
|
|
5500
|
+
...toolCalls.length ? { tool_calls: toolCalls } : {}
|
|
5501
|
+
});
|
|
5502
|
+
break;
|
|
5503
|
+
}
|
|
5504
|
+
case "tool": {
|
|
5505
|
+
mapped.push({
|
|
5506
|
+
role: "tool",
|
|
5507
|
+
tool_call_id: message.tool_call_id,
|
|
5508
|
+
content: stringifyContentForZai(message.content)
|
|
5509
|
+
});
|
|
5510
|
+
break;
|
|
5511
|
+
}
|
|
5512
|
+
case "reasoning":
|
|
5513
|
+
break;
|
|
5514
|
+
}
|
|
5515
|
+
}
|
|
5516
|
+
return mapped;
|
|
5517
|
+
}
|
|
5518
|
+
function toZaiTools(tools) {
|
|
5519
|
+
if (!tools || tools.length === 0) {
|
|
5520
|
+
return void 0;
|
|
5521
|
+
}
|
|
5522
|
+
const mapped = [];
|
|
5523
|
+
for (const tool of tools) {
|
|
5524
|
+
if (isFunctionToolDefinition(tool)) {
|
|
5525
|
+
mapped.push({
|
|
5526
|
+
type: "function",
|
|
5527
|
+
function: {
|
|
5528
|
+
name: tool.name,
|
|
5529
|
+
description: tool.description,
|
|
5530
|
+
parameters: tool.parameters
|
|
5531
|
+
}
|
|
5532
|
+
});
|
|
5533
|
+
continue;
|
|
5534
|
+
}
|
|
5535
|
+
if (isHostedSearchToolDefinition(tool)) {
|
|
5536
|
+
continue;
|
|
5537
|
+
}
|
|
5538
|
+
}
|
|
5539
|
+
return mapped.length ? mapped : void 0;
|
|
5540
|
+
}
|
|
5541
|
+
function toZaiToolChoice(choice) {
|
|
5542
|
+
if (!choice) {
|
|
5543
|
+
return void 0;
|
|
5544
|
+
}
|
|
5545
|
+
if (choice === "auto" || choice === "required" || choice === "none") {
|
|
5546
|
+
return choice;
|
|
5547
|
+
}
|
|
5548
|
+
return { type: "function", function: { name: choice } };
|
|
5549
|
+
}
|
|
5550
|
+
var createZaiStreamAccumulator = (options) => ({
|
|
5551
|
+
content: "",
|
|
5552
|
+
reasoningContent: "",
|
|
5553
|
+
toolCalls: [],
|
|
5554
|
+
rawChunkCount: 0,
|
|
5555
|
+
rawChunks: [],
|
|
5556
|
+
captureRawChunks: options?.captureRawChunks ?? false
|
|
5557
|
+
});
|
|
5558
|
+
function appendZaiChatCompletionChunk(accumulator, chunk) {
|
|
5559
|
+
accumulator.rawChunkCount += 1;
|
|
5560
|
+
if (accumulator.captureRawChunks) {
|
|
5561
|
+
accumulator.rawChunks.push(chunk);
|
|
5562
|
+
}
|
|
5563
|
+
accumulator.id ??= chunk.id;
|
|
5564
|
+
accumulator.model ??= chunk.model;
|
|
5565
|
+
accumulator.created ??= chunk.created;
|
|
5566
|
+
accumulator.usage ??= chunk.usage ?? void 0;
|
|
5567
|
+
for (const choice of chunk.choices ?? []) {
|
|
5568
|
+
if (choice.finish_reason !== void 0) {
|
|
5569
|
+
accumulator.finishReason = choice.finish_reason;
|
|
5570
|
+
}
|
|
5571
|
+
const delta = choice.delta;
|
|
5572
|
+
if (!delta) {
|
|
5573
|
+
continue;
|
|
5574
|
+
}
|
|
5575
|
+
if (typeof delta.reasoning_content === "string") {
|
|
5576
|
+
accumulator.reasoningContent += delta.reasoning_content;
|
|
5577
|
+
}
|
|
5578
|
+
if (typeof delta.content === "string") {
|
|
5579
|
+
accumulator.content += delta.content;
|
|
5580
|
+
}
|
|
5581
|
+
for (const toolCallDelta of delta.tool_calls ?? []) {
|
|
5582
|
+
const index = typeof toolCallDelta.index === "number" ? toolCallDelta.index : accumulator.toolCalls.length;
|
|
5583
|
+
let call = accumulator.toolCalls.find((entry) => entry.index === index);
|
|
5584
|
+
if (!call) {
|
|
5585
|
+
call = {
|
|
5586
|
+
index,
|
|
5587
|
+
id: toolCallDelta.id ?? `call_${index}`,
|
|
5588
|
+
type: "function",
|
|
5589
|
+
name: "",
|
|
5590
|
+
arguments: "",
|
|
5591
|
+
raw_chunk_count: 0
|
|
5592
|
+
};
|
|
5593
|
+
accumulator.toolCalls.push(call);
|
|
5594
|
+
accumulator.toolCalls.sort((left, right) => left.index - right.index);
|
|
5595
|
+
}
|
|
5596
|
+
call.raw_chunk_count += 1;
|
|
5597
|
+
if (typeof toolCallDelta.id === "string" && toolCallDelta.id) {
|
|
5598
|
+
call.id = toolCallDelta.id;
|
|
5599
|
+
}
|
|
5600
|
+
if (toolCallDelta.type === "function") {
|
|
5601
|
+
call.type = "function";
|
|
5602
|
+
}
|
|
5603
|
+
if (typeof toolCallDelta.function?.name === "string") {
|
|
5604
|
+
call.name = toolCallDelta.function.name;
|
|
5605
|
+
}
|
|
5606
|
+
if (typeof toolCallDelta.function?.arguments === "string") {
|
|
5607
|
+
call.arguments += toolCallDelta.function.arguments;
|
|
5608
|
+
}
|
|
5609
|
+
}
|
|
5610
|
+
}
|
|
5611
|
+
}
|
|
5612
|
+
function toZaiChatInvokeCompletion(accumulator, meta) {
|
|
5613
|
+
const messages = [];
|
|
5614
|
+
if (accumulator.reasoningContent) {
|
|
5615
|
+
messages.push({
|
|
5616
|
+
role: "reasoning",
|
|
5617
|
+
content: accumulator.reasoningContent,
|
|
5618
|
+
raw_item: {
|
|
5619
|
+
provider: "zai",
|
|
5620
|
+
field: "reasoning_content",
|
|
5621
|
+
response_id: accumulator.id
|
|
5622
|
+
}
|
|
5623
|
+
});
|
|
5624
|
+
}
|
|
5625
|
+
const toolCalls = accumulator.toolCalls.filter((call) => call.name || call.arguments || call.id).map(toToolCall);
|
|
5626
|
+
if (accumulator.content || toolCalls.length) {
|
|
5627
|
+
messages.push({
|
|
5628
|
+
role: "assistant",
|
|
5629
|
+
content: accumulator.content || null,
|
|
5630
|
+
...toolCalls.length ? { tool_calls: toolCalls } : {}
|
|
5631
|
+
});
|
|
5632
|
+
}
|
|
5633
|
+
const usage = normalizeZaiUsage(accumulator);
|
|
5634
|
+
return {
|
|
5635
|
+
messages,
|
|
5636
|
+
usage,
|
|
5637
|
+
stop_reason: accumulator.finishReason ?? null,
|
|
5638
|
+
provider_meta: {
|
|
5639
|
+
response_id: accumulator.id,
|
|
5640
|
+
request_id: meta?.request_id ?? void 0,
|
|
5641
|
+
finish_reason: accumulator.finishReason ?? null,
|
|
5642
|
+
reasoning_requested: meta?.reasoning_requested,
|
|
5643
|
+
reasoning_applied: meta?.reasoning_applied,
|
|
5644
|
+
reasoning_effort: meta?.reasoning_effort,
|
|
5645
|
+
reasoning_fallback: meta?.reasoning_fallback
|
|
5646
|
+
}
|
|
5647
|
+
};
|
|
5648
|
+
}
|
|
5649
|
+
var toZaiReplayToolCalls = (toolCalls) => {
|
|
5650
|
+
if (!toolCalls?.length) {
|
|
5651
|
+
return [];
|
|
5652
|
+
}
|
|
5653
|
+
return toolCalls.map((call) => ({
|
|
5654
|
+
id: call.id,
|
|
5655
|
+
type: "function",
|
|
5656
|
+
function: {
|
|
5657
|
+
name: call.function.name,
|
|
5658
|
+
arguments: call.function.arguments
|
|
5659
|
+
}
|
|
5660
|
+
}));
|
|
5661
|
+
};
|
|
5662
|
+
var toToolCall = (call) => ({
|
|
5663
|
+
id: call.id,
|
|
5664
|
+
type: "function",
|
|
5665
|
+
function: {
|
|
5666
|
+
name: call.name,
|
|
5667
|
+
arguments: call.arguments
|
|
5668
|
+
},
|
|
5669
|
+
provider_meta: {
|
|
5670
|
+
provider: "zai",
|
|
5671
|
+
index: call.index,
|
|
5672
|
+
raw_chunk_count: call.raw_chunk_count
|
|
5673
|
+
}
|
|
5674
|
+
});
|
|
5675
|
+
var normalizeNumber = (value) => {
|
|
5676
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
5677
|
+
return 0;
|
|
5678
|
+
}
|
|
5679
|
+
return Math.trunc(value);
|
|
5680
|
+
};
|
|
5681
|
+
var normalizeZaiUsage = (accumulator) => {
|
|
5682
|
+
const usage = accumulator.usage;
|
|
5683
|
+
if (!usage) {
|
|
5684
|
+
return null;
|
|
5685
|
+
}
|
|
5686
|
+
const inputTokens = normalizeNumber(usage.prompt_tokens);
|
|
5687
|
+
const outputTokens = normalizeNumber(usage.completion_tokens);
|
|
5688
|
+
const totalTokens = typeof usage.total_tokens === "number" ? normalizeNumber(usage.total_tokens) : inputTokens + outputTokens;
|
|
5689
|
+
const cachedTokens = normalizeNumber(
|
|
5690
|
+
usage.prompt_tokens_details?.cached_tokens
|
|
5691
|
+
);
|
|
5692
|
+
return {
|
|
5693
|
+
model: accumulator.model ?? "",
|
|
5694
|
+
input_tokens: inputTokens,
|
|
5695
|
+
...cachedTokens > 0 ? { input_cached_tokens: cachedTokens } : {},
|
|
5696
|
+
output_tokens: outputTokens,
|
|
5697
|
+
total_tokens: totalTokens
|
|
5698
|
+
};
|
|
5699
|
+
};
|
|
5700
|
+
|
|
5701
|
+
// src/llm/zai/transport.ts
|
|
5702
|
+
var streamZaiChatCompletion = async ({
|
|
5703
|
+
apiKey,
|
|
5704
|
+
baseURL,
|
|
5705
|
+
fetchImpl,
|
|
5706
|
+
request,
|
|
5707
|
+
signal,
|
|
5708
|
+
timeoutMs,
|
|
5709
|
+
captureRawChunks
|
|
5710
|
+
}) => {
|
|
5711
|
+
const requestSignal = createZaiRequestSignal(signal, timeoutMs);
|
|
5712
|
+
try {
|
|
5713
|
+
const response = await fetchImpl(`${baseURL}/chat/completions`, {
|
|
5714
|
+
method: "POST",
|
|
5715
|
+
headers: {
|
|
5716
|
+
Authorization: `Bearer ${apiKey}`,
|
|
5717
|
+
"Content-Type": "application/json"
|
|
5718
|
+
},
|
|
5719
|
+
body: safeJsonStringify(request),
|
|
5720
|
+
signal: requestSignal.signal
|
|
5721
|
+
});
|
|
5722
|
+
if (!response.ok) {
|
|
5723
|
+
throw await toZaiHttpError(response);
|
|
5724
|
+
}
|
|
5725
|
+
const accumulated = createZaiStreamAccumulator({
|
|
5726
|
+
captureRawChunks: captureRawChunks ?? false
|
|
5727
|
+
});
|
|
5728
|
+
for await (const chunk of readZaiChatCompletionStream(
|
|
5729
|
+
response,
|
|
5730
|
+
requestSignal.signal
|
|
5731
|
+
)) {
|
|
5732
|
+
appendZaiChatCompletionChunk(accumulated, chunk);
|
|
5733
|
+
}
|
|
5734
|
+
return {
|
|
5735
|
+
status: response.status,
|
|
5736
|
+
request_id: response.headers.get("x-request-id"),
|
|
5737
|
+
accumulated
|
|
5738
|
+
};
|
|
5739
|
+
} finally {
|
|
5740
|
+
requestSignal.cleanup();
|
|
5741
|
+
}
|
|
5742
|
+
};
|
|
5743
|
+
async function* readZaiChatCompletionStream(response, signal) {
|
|
5744
|
+
if (!response.body) {
|
|
5745
|
+
throw new Error("Z.ai provider error: response body is empty");
|
|
5746
|
+
}
|
|
5747
|
+
const reader = response.body.getReader();
|
|
5748
|
+
throwIfAborted2(signal);
|
|
5749
|
+
const cancelOnAbort = () => {
|
|
5750
|
+
void reader.cancel(signal?.reason).catch(() => void 0);
|
|
5751
|
+
};
|
|
5752
|
+
signal?.addEventListener("abort", cancelOnAbort, { once: true });
|
|
5753
|
+
const decoder = new TextDecoder();
|
|
5754
|
+
let buffer = "";
|
|
5755
|
+
try {
|
|
5756
|
+
while (true) {
|
|
5757
|
+
throwIfAborted2(signal);
|
|
5758
|
+
const { done, value } = await reader.read();
|
|
5759
|
+
throwIfAborted2(signal);
|
|
5760
|
+
if (done) {
|
|
5761
|
+
break;
|
|
5762
|
+
}
|
|
5763
|
+
buffer += decoder.decode(value, { stream: true });
|
|
5764
|
+
let newlineIndex = buffer.indexOf("\n");
|
|
5765
|
+
while (newlineIndex >= 0) {
|
|
5766
|
+
const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
|
|
5767
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
5768
|
+
const chunk = parseSseDataLine(line);
|
|
5769
|
+
if (chunk === "done") {
|
|
5770
|
+
return;
|
|
5771
|
+
}
|
|
5772
|
+
if (chunk) {
|
|
5773
|
+
yield chunk;
|
|
5774
|
+
}
|
|
5775
|
+
newlineIndex = buffer.indexOf("\n");
|
|
5776
|
+
}
|
|
5777
|
+
}
|
|
5778
|
+
buffer += decoder.decode();
|
|
5779
|
+
const trailing = buffer.trim();
|
|
5780
|
+
if (trailing) {
|
|
5781
|
+
const chunk = parseSseDataLine(trailing);
|
|
5782
|
+
if (chunk && chunk !== "done") {
|
|
5783
|
+
yield chunk;
|
|
5784
|
+
}
|
|
5785
|
+
}
|
|
5786
|
+
} finally {
|
|
5787
|
+
signal?.removeEventListener("abort", cancelOnAbort);
|
|
5788
|
+
reader.releaseLock();
|
|
5789
|
+
}
|
|
5790
|
+
}
|
|
5791
|
+
var createZaiRequestSignal = (signal, timeoutMs) => {
|
|
5792
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
5793
|
+
return { signal, cleanup: () => void 0 };
|
|
5794
|
+
}
|
|
5795
|
+
const controller = new AbortController();
|
|
5796
|
+
let timeout = setTimeout(() => {
|
|
5797
|
+
controller.abort(new Error("Z.ai request timeout"));
|
|
5798
|
+
}, timeoutMs);
|
|
5799
|
+
const onAbort = () => {
|
|
5800
|
+
controller.abort(signal?.reason);
|
|
5801
|
+
};
|
|
5802
|
+
if (signal?.aborted) {
|
|
5803
|
+
onAbort();
|
|
5804
|
+
} else {
|
|
5805
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
5806
|
+
}
|
|
5807
|
+
return {
|
|
5808
|
+
signal: controller.signal,
|
|
5809
|
+
cleanup: () => {
|
|
5810
|
+
if (timeout) {
|
|
5811
|
+
clearTimeout(timeout);
|
|
5812
|
+
timeout = void 0;
|
|
5813
|
+
}
|
|
5814
|
+
signal?.removeEventListener("abort", onAbort);
|
|
5815
|
+
}
|
|
5816
|
+
};
|
|
5817
|
+
};
|
|
5818
|
+
var toZaiHttpError = async (response) => {
|
|
5819
|
+
let body = "";
|
|
5820
|
+
try {
|
|
5821
|
+
body = await response.text();
|
|
5822
|
+
} catch {
|
|
5823
|
+
body = "";
|
|
5824
|
+
}
|
|
5825
|
+
const snippet = body ? body.slice(0, 500) : "(empty)";
|
|
5826
|
+
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";
|
|
5827
|
+
return new Error(`${prefix} (${response.status}): ${snippet}`);
|
|
5828
|
+
};
|
|
5829
|
+
var throwIfAborted2 = (signal) => {
|
|
5830
|
+
if (!signal?.aborted) {
|
|
5831
|
+
return;
|
|
5832
|
+
}
|
|
5833
|
+
const reason = signal.reason;
|
|
5834
|
+
if (reason instanceof Error) {
|
|
5835
|
+
throw reason;
|
|
5836
|
+
}
|
|
5837
|
+
throw new Error("Z.ai request aborted");
|
|
5838
|
+
};
|
|
5839
|
+
var parseSseDataLine = (line) => {
|
|
5840
|
+
const trimmed = line.trim();
|
|
5841
|
+
if (!trimmed || trimmed.startsWith(":")) {
|
|
5842
|
+
return null;
|
|
5843
|
+
}
|
|
5844
|
+
if (!trimmed.startsWith("data:")) {
|
|
5845
|
+
return null;
|
|
5846
|
+
}
|
|
5847
|
+
const data = trimmed.slice("data:".length).trim();
|
|
5848
|
+
if (!data) {
|
|
5849
|
+
return null;
|
|
5850
|
+
}
|
|
5851
|
+
if (data === "[DONE]") {
|
|
5852
|
+
return "done";
|
|
5853
|
+
}
|
|
5854
|
+
try {
|
|
5855
|
+
return JSON.parse(data);
|
|
5856
|
+
} catch {
|
|
5857
|
+
throw new Error(`Malformed Z.ai stream chunk: ${data.slice(0, 300)}`);
|
|
5858
|
+
}
|
|
5859
|
+
};
|
|
5860
|
+
|
|
5861
|
+
// src/llm/zai/chat.ts
|
|
5862
|
+
var PROVIDER_NAME4 = "zai";
|
|
5863
|
+
var DEFAULT_BASE_URL = "https://api.z.ai/api/paas/v4";
|
|
5864
|
+
var DEFAULT_REASONING_EFFORT3 = "high";
|
|
5865
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 20 * 60 * 1e3;
|
|
5866
|
+
var ChatZai = class {
|
|
5867
|
+
provider = PROVIDER_NAME4;
|
|
5868
|
+
model;
|
|
5869
|
+
apiKey;
|
|
5870
|
+
baseURL;
|
|
5871
|
+
fetchImpl;
|
|
5872
|
+
timeoutMs;
|
|
5873
|
+
defaultReasoningEffort;
|
|
5874
|
+
reasoningLevelMeta;
|
|
5875
|
+
debugInvokeSeq = 0;
|
|
5876
|
+
lastDebugRequestPayload = null;
|
|
5877
|
+
constructor(options = {}) {
|
|
5878
|
+
this.apiKey = options.apiKey;
|
|
5879
|
+
this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
5880
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
5881
|
+
this.model = options.model ?? ZAI_DEFAULT_MODEL;
|
|
5882
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
5883
|
+
this.defaultReasoningEffort = options.reasoningEffort === void 0 ? DEFAULT_REASONING_EFFORT3 : options.reasoningEffort;
|
|
5884
|
+
this.reasoningLevelMeta = {
|
|
5885
|
+
requested: options.reasoningLevelRequested,
|
|
5886
|
+
applied: options.reasoningLevelApplied,
|
|
5887
|
+
fallbackApplied: options.reasoningFallbackApplied
|
|
5888
|
+
};
|
|
5889
|
+
}
|
|
5890
|
+
async ainvoke(input, _context) {
|
|
5891
|
+
const apiKey = this.apiKey;
|
|
5892
|
+
if (!apiKey) {
|
|
5893
|
+
throw new Error("Z.ai API key is required");
|
|
5894
|
+
}
|
|
5895
|
+
const {
|
|
5896
|
+
messages,
|
|
5897
|
+
tools: toolDefs,
|
|
5898
|
+
toolChoice,
|
|
5899
|
+
options,
|
|
5900
|
+
model,
|
|
5901
|
+
signal
|
|
5902
|
+
} = input;
|
|
5903
|
+
const { reasoningEffort, ...rest } = options ?? {};
|
|
5904
|
+
const effectiveReasoningEffort = reasoningEffort === void 0 ? this.defaultReasoningEffort : reasoningEffort;
|
|
5905
|
+
const tools = toZaiTools(toolDefs);
|
|
5906
|
+
const toolChoiceParam = toZaiToolChoice(toolChoice);
|
|
5907
|
+
const request = {
|
|
5908
|
+
model: model ?? this.model,
|
|
5909
|
+
messages: toZaiMessages(messages),
|
|
5910
|
+
stream: true,
|
|
5911
|
+
thinking: { type: "enabled" },
|
|
5912
|
+
...rest,
|
|
5913
|
+
...effectiveReasoningEffort ? { reasoning_effort: effectiveReasoningEffort } : {},
|
|
5914
|
+
...tools ? { tools } : {},
|
|
5915
|
+
...tools ? { tool_stream: true } : {},
|
|
5916
|
+
...toolChoiceParam ? { tool_choice: toolChoiceParam } : {}
|
|
5917
|
+
};
|
|
5918
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
5919
|
+
await this.debugRequestIfEnabled(request, debugSeq);
|
|
5920
|
+
const terminal = await this.streamRequest(apiKey, request, signal);
|
|
5921
|
+
await this.debugResponseIfEnabled(terminal, debugSeq);
|
|
5922
|
+
return toZaiChatInvokeCompletion(terminal.accumulated, {
|
|
5923
|
+
request_id: terminal.request_id ?? null,
|
|
5924
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
5925
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
5926
|
+
reasoning_effort: request.reasoning_effort,
|
|
5927
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
5928
|
+
});
|
|
5929
|
+
}
|
|
5930
|
+
async streamRequest(apiKey, request, signal) {
|
|
5931
|
+
const logSettings = getProviderLogSettings();
|
|
5932
|
+
return streamZaiChatCompletion({
|
|
5933
|
+
apiKey,
|
|
5934
|
+
baseURL: this.baseURL,
|
|
5935
|
+
fetchImpl: this.fetchImpl,
|
|
5936
|
+
request,
|
|
5937
|
+
signal,
|
|
5938
|
+
timeoutMs: this.timeoutMs,
|
|
5939
|
+
captureRawChunks: Boolean(logSettings.dumpDir)
|
|
5940
|
+
});
|
|
5941
|
+
}
|
|
5942
|
+
nextDebugInvokeSeq() {
|
|
5943
|
+
const seq = this.debugInvokeSeq + 1;
|
|
5944
|
+
this.debugInvokeSeq = seq;
|
|
5945
|
+
return seq;
|
|
5946
|
+
}
|
|
5947
|
+
async debugRequestIfEnabled(request, seq) {
|
|
5948
|
+
const settings = getProviderLogSettings();
|
|
5949
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
5950
|
+
return;
|
|
5951
|
+
}
|
|
5952
|
+
const payload = safeJsonStringify(request);
|
|
5953
|
+
const hash = createHash4("sha256").update(payload).digest("hex").slice(0, 16);
|
|
5954
|
+
const toolsHash = createHash4("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
5955
|
+
const previous = this.lastDebugRequestPayload;
|
|
5956
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
5957
|
+
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
5958
|
+
if (settings.enabled) {
|
|
5959
|
+
console.error(
|
|
5960
|
+
`[zai.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash}`
|
|
5961
|
+
);
|
|
5962
|
+
}
|
|
5963
|
+
if (settings.dumpDir) {
|
|
5964
|
+
try {
|
|
5965
|
+
await writeProviderLogDump(
|
|
5966
|
+
settings,
|
|
5967
|
+
PROVIDER_NAME4,
|
|
5968
|
+
seq,
|
|
5969
|
+
"request",
|
|
5970
|
+
request
|
|
5971
|
+
);
|
|
5972
|
+
} catch (error) {
|
|
5973
|
+
if (settings.enabled) {
|
|
5974
|
+
console.error(
|
|
5975
|
+
`[zai.request] dump_failed seq=${seq} error=${String(error)}`
|
|
5976
|
+
);
|
|
5977
|
+
}
|
|
5978
|
+
}
|
|
5979
|
+
}
|
|
5980
|
+
this.lastDebugRequestPayload = payload;
|
|
5981
|
+
}
|
|
5982
|
+
async debugResponseIfEnabled(response, seq) {
|
|
5983
|
+
const settings = getProviderLogSettings();
|
|
5984
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
5985
|
+
return;
|
|
5986
|
+
}
|
|
5987
|
+
const usage = response.accumulated.usage;
|
|
5988
|
+
if (settings.enabled) {
|
|
5989
|
+
const inputTokens = usage?.prompt_tokens ?? 0;
|
|
5990
|
+
const outputTokens = usage?.completion_tokens ?? 0;
|
|
5991
|
+
console.error(
|
|
5992
|
+
`[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}`
|
|
5993
|
+
);
|
|
5994
|
+
}
|
|
5995
|
+
if (settings.dumpDir) {
|
|
5996
|
+
try {
|
|
5997
|
+
await writeProviderLogDump(
|
|
5998
|
+
settings,
|
|
5999
|
+
PROVIDER_NAME4,
|
|
6000
|
+
seq,
|
|
6001
|
+
"response",
|
|
6002
|
+
response.accumulated
|
|
6003
|
+
);
|
|
6004
|
+
} catch (error) {
|
|
6005
|
+
if (settings.enabled) {
|
|
6006
|
+
console.error(
|
|
6007
|
+
`[zai.response] dump_failed seq=${seq} error=${String(error)}`
|
|
6008
|
+
);
|
|
6009
|
+
}
|
|
6010
|
+
}
|
|
6011
|
+
}
|
|
6012
|
+
}
|
|
6013
|
+
};
|
|
6014
|
+
|
|
5428
6015
|
// src/prompts.ts
|
|
5429
6016
|
import path2 from "path";
|
|
5430
6017
|
import { fileURLToPath } from "url";
|
|
@@ -5564,6 +6151,7 @@ export {
|
|
|
5564
6151
|
ChatAnthropic,
|
|
5565
6152
|
ChatOpenAI,
|
|
5566
6153
|
ChatOpenRouter,
|
|
6154
|
+
ChatZai,
|
|
5567
6155
|
DEFAULT_MODEL_REGISTRY,
|
|
5568
6156
|
GOOGLE_MODELS,
|
|
5569
6157
|
OPENAI_DEFAULT_MODEL,
|
|
@@ -5571,6 +6159,9 @@ export {
|
|
|
5571
6159
|
OPENAI_MODELS,
|
|
5572
6160
|
TaskComplete,
|
|
5573
6161
|
ToolOutputCacheService,
|
|
6162
|
+
ZAI_DEFAULT_MODEL,
|
|
6163
|
+
ZAI_MODELS,
|
|
6164
|
+
ZAI_REASONING_EFFORT_MODELS,
|
|
5574
6165
|
applyModelMetadata,
|
|
5575
6166
|
createModelRegistry,
|
|
5576
6167
|
defineTool,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codelia/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.69",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -25,8 +25,8 @@
|
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"@anthropic-ai/sdk": "^0.78.0",
|
|
28
|
-
"@codelia/config": "0.1.
|
|
29
|
-
"@codelia/shared-types": "0.1.
|
|
28
|
+
"@codelia/config": "0.1.69",
|
|
29
|
+
"@codelia/shared-types": "0.1.69",
|
|
30
30
|
"@google-cloud/vertexai": "^1.10.0",
|
|
31
31
|
"@google/genai": "^1.43.0",
|
|
32
32
|
"json-schema": "^0.4.0",
|