@codelia/core 0.1.67 → 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 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,
@@ -345,6 +349,14 @@ var ANTHROPIC_MODELS = [
345
349
  provider: "anthropic",
346
350
  aliases: ["default"]
347
351
  },
352
+ {
353
+ id: "claude-opus-4-8",
354
+ provider: "anthropic",
355
+ contextWindow: 1e6,
356
+ maxInputTokens: 1e6,
357
+ maxOutputTokens: 128e3,
358
+ supportsFast: true
359
+ },
348
360
  {
349
361
  id: "claude-opus-4-7",
350
362
  provider: "anthropic",
@@ -408,7 +420,8 @@ function createModelRegistry(specs) {
408
420
  openai: {},
409
421
  anthropic: {},
410
422
  openrouter: {},
411
- google: {}
423
+ google: {},
424
+ zai: {}
412
425
  }
413
426
  };
414
427
  registerModels(registry, specs);
@@ -468,7 +481,8 @@ function cloneAliases(aliasesByProvider) {
468
481
  openai: { ...aliasesByProvider.openai },
469
482
  anthropic: { ...aliasesByProvider.anthropic },
470
483
  openrouter: { ...aliasesByProvider.openrouter },
471
- google: { ...aliasesByProvider.google }
484
+ google: { ...aliasesByProvider.google },
485
+ zai: { ...aliasesByProvider.zai }
472
486
  };
473
487
  }
474
488
  function applyModelMetadata(registry, index) {
@@ -477,7 +491,7 @@ function applyModelMetadata(registry, index) {
477
491
  aliasesByProvider: cloneAliases(registry.aliasesByProvider)
478
492
  };
479
493
  for (const [providerId, providerModels] of Object.entries(index.models)) {
480
- if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google") {
494
+ if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google" && providerId !== "zai") {
481
495
  continue;
482
496
  }
483
497
  const provider = providerId;
@@ -497,11 +511,50 @@ function applyModelMetadata(registry, index) {
497
511
  return next;
498
512
  }
499
513
 
514
+ // src/models/zai.ts
515
+ var ZAI_DEFAULT_MODEL = "glm-5.2";
516
+ var ZAI_REASONING_EFFORT_MODELS = /* @__PURE__ */ new Set(["glm-5.2"]);
517
+ var zaiModel = (id, limits) => ({
518
+ id,
519
+ provider: "zai",
520
+ aliases: limits.aliases,
521
+ contextWindow: limits.contextWindow,
522
+ maxInputTokens: limits.contextWindow,
523
+ maxOutputTokens: limits.maxOutputTokens,
524
+ supportsTools: true,
525
+ supportsReasoning: true,
526
+ supportsJsonSchema: true
527
+ });
528
+ var ZAI_MODELS = [
529
+ zaiModel(ZAI_DEFAULT_MODEL, {
530
+ aliases: ["default"],
531
+ contextWindow: 1e6,
532
+ maxOutputTokens: 131072
533
+ }),
534
+ zaiModel("glm-5.1", {
535
+ contextWindow: 2e5,
536
+ maxOutputTokens: 131072
537
+ }),
538
+ zaiModel("glm-5", {
539
+ contextWindow: 2e5,
540
+ maxOutputTokens: 131072
541
+ }),
542
+ zaiModel("glm-5-turbo", {
543
+ contextWindow: 2e5,
544
+ maxOutputTokens: 131072
545
+ }),
546
+ zaiModel("glm-4.7", {
547
+ contextWindow: 2e5,
548
+ maxOutputTokens: 131072
549
+ })
550
+ ];
551
+
500
552
  // src/models/index.ts
501
553
  var DEFAULT_MODEL_REGISTRY = createModelRegistry([
502
554
  ...OPENAI_MODELS,
503
555
  ...ANTHROPIC_MODELS,
504
- ...GOOGLE_MODELS
556
+ ...GOOGLE_MODELS,
557
+ ...ZAI_MODELS
505
558
  ]);
506
559
 
507
560
  // src/services/compaction/service.ts
@@ -866,7 +919,7 @@ var parseQualifiedModelId = (modelId) => {
866
919
  if (!rest) {
867
920
  return null;
868
921
  }
869
- if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
922
+ if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
870
923
  return null;
871
924
  }
872
925
  return { provider: providerRaw, modelId: rest };
@@ -1049,7 +1102,7 @@ var parseQualifiedModelId2 = (modelId) => {
1049
1102
  if (!rest) {
1050
1103
  return null;
1051
1104
  }
1052
- if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
1105
+ if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
1053
1106
  return null;
1054
1107
  }
1055
1108
  return { provider: providerRaw, modelId: rest };
@@ -1862,7 +1915,7 @@ var parseQualifiedModelId3 = (modelId) => {
1862
1915
  if (!rest) {
1863
1916
  return null;
1864
1917
  }
1865
- if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
1918
+ if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google" && providerRaw !== "zai") {
1866
1919
  return null;
1867
1920
  }
1868
1921
  return { provider: providerRaw, modelId: rest };
@@ -5485,6 +5538,544 @@ var ChatOpenRouter = class {
5485
5538
  }
5486
5539
  };
5487
5540
 
5541
+ // src/llm/zai/chat.ts
5542
+ var import_node_crypto4 = require("crypto");
5543
+
5544
+ // src/llm/zai/serializer.ts
5545
+ var stringifyContentForZai = (content) => stringifyContent(content, { mode: "display", joiner: "" });
5546
+ function toZaiMessages(messages) {
5547
+ const mapped = [];
5548
+ for (const message of messages) {
5549
+ switch (message.role) {
5550
+ case "system":
5551
+ case "user": {
5552
+ mapped.push({
5553
+ role: message.role,
5554
+ content: stringifyContentForZai(message.content)
5555
+ });
5556
+ break;
5557
+ }
5558
+ case "assistant": {
5559
+ const content = stringifyContentForZai(message.content);
5560
+ const toolCalls = toZaiReplayToolCalls(message.tool_calls);
5561
+ mapped.push({
5562
+ role: "assistant",
5563
+ content: content || null,
5564
+ ...toolCalls.length ? { tool_calls: toolCalls } : {}
5565
+ });
5566
+ break;
5567
+ }
5568
+ case "tool": {
5569
+ mapped.push({
5570
+ role: "tool",
5571
+ tool_call_id: message.tool_call_id,
5572
+ content: stringifyContentForZai(message.content)
5573
+ });
5574
+ break;
5575
+ }
5576
+ case "reasoning":
5577
+ break;
5578
+ }
5579
+ }
5580
+ return mapped;
5581
+ }
5582
+ function toZaiTools(tools) {
5583
+ if (!tools || tools.length === 0) {
5584
+ return void 0;
5585
+ }
5586
+ const mapped = [];
5587
+ for (const tool of tools) {
5588
+ if (isFunctionToolDefinition(tool)) {
5589
+ mapped.push({
5590
+ type: "function",
5591
+ function: {
5592
+ name: tool.name,
5593
+ description: tool.description,
5594
+ parameters: tool.parameters
5595
+ }
5596
+ });
5597
+ continue;
5598
+ }
5599
+ if (isHostedSearchToolDefinition(tool)) {
5600
+ continue;
5601
+ }
5602
+ }
5603
+ return mapped.length ? mapped : void 0;
5604
+ }
5605
+ function toZaiToolChoice(choice) {
5606
+ if (!choice) {
5607
+ return void 0;
5608
+ }
5609
+ if (choice === "auto" || choice === "required" || choice === "none") {
5610
+ return choice;
5611
+ }
5612
+ return { type: "function", function: { name: choice } };
5613
+ }
5614
+ var createZaiStreamAccumulator = (options) => ({
5615
+ content: "",
5616
+ reasoningContent: "",
5617
+ toolCalls: [],
5618
+ rawChunkCount: 0,
5619
+ rawChunks: [],
5620
+ captureRawChunks: options?.captureRawChunks ?? false
5621
+ });
5622
+ function appendZaiChatCompletionChunk(accumulator, chunk) {
5623
+ accumulator.rawChunkCount += 1;
5624
+ if (accumulator.captureRawChunks) {
5625
+ accumulator.rawChunks.push(chunk);
5626
+ }
5627
+ accumulator.id ??= chunk.id;
5628
+ accumulator.model ??= chunk.model;
5629
+ accumulator.created ??= chunk.created;
5630
+ accumulator.usage ??= chunk.usage ?? void 0;
5631
+ for (const choice of chunk.choices ?? []) {
5632
+ if (choice.finish_reason !== void 0) {
5633
+ accumulator.finishReason = choice.finish_reason;
5634
+ }
5635
+ const delta = choice.delta;
5636
+ if (!delta) {
5637
+ continue;
5638
+ }
5639
+ if (typeof delta.reasoning_content === "string") {
5640
+ accumulator.reasoningContent += delta.reasoning_content;
5641
+ }
5642
+ if (typeof delta.content === "string") {
5643
+ accumulator.content += delta.content;
5644
+ }
5645
+ for (const toolCallDelta of delta.tool_calls ?? []) {
5646
+ const index = typeof toolCallDelta.index === "number" ? toolCallDelta.index : accumulator.toolCalls.length;
5647
+ let call = accumulator.toolCalls.find((entry) => entry.index === index);
5648
+ if (!call) {
5649
+ call = {
5650
+ index,
5651
+ id: toolCallDelta.id ?? `call_${index}`,
5652
+ type: "function",
5653
+ name: "",
5654
+ arguments: "",
5655
+ raw_chunk_count: 0
5656
+ };
5657
+ accumulator.toolCalls.push(call);
5658
+ accumulator.toolCalls.sort((left, right) => left.index - right.index);
5659
+ }
5660
+ call.raw_chunk_count += 1;
5661
+ if (typeof toolCallDelta.id === "string" && toolCallDelta.id) {
5662
+ call.id = toolCallDelta.id;
5663
+ }
5664
+ if (toolCallDelta.type === "function") {
5665
+ call.type = "function";
5666
+ }
5667
+ if (typeof toolCallDelta.function?.name === "string") {
5668
+ call.name = toolCallDelta.function.name;
5669
+ }
5670
+ if (typeof toolCallDelta.function?.arguments === "string") {
5671
+ call.arguments += toolCallDelta.function.arguments;
5672
+ }
5673
+ }
5674
+ }
5675
+ }
5676
+ function toZaiChatInvokeCompletion(accumulator, meta) {
5677
+ const messages = [];
5678
+ if (accumulator.reasoningContent) {
5679
+ messages.push({
5680
+ role: "reasoning",
5681
+ content: accumulator.reasoningContent,
5682
+ raw_item: {
5683
+ provider: "zai",
5684
+ field: "reasoning_content",
5685
+ response_id: accumulator.id
5686
+ }
5687
+ });
5688
+ }
5689
+ const toolCalls = accumulator.toolCalls.filter((call) => call.name || call.arguments || call.id).map(toToolCall);
5690
+ if (accumulator.content || toolCalls.length) {
5691
+ messages.push({
5692
+ role: "assistant",
5693
+ content: accumulator.content || null,
5694
+ ...toolCalls.length ? { tool_calls: toolCalls } : {}
5695
+ });
5696
+ }
5697
+ const usage = normalizeZaiUsage(accumulator);
5698
+ return {
5699
+ messages,
5700
+ usage,
5701
+ stop_reason: accumulator.finishReason ?? null,
5702
+ provider_meta: {
5703
+ response_id: accumulator.id,
5704
+ request_id: meta?.request_id ?? void 0,
5705
+ finish_reason: accumulator.finishReason ?? null,
5706
+ reasoning_requested: meta?.reasoning_requested,
5707
+ reasoning_applied: meta?.reasoning_applied,
5708
+ reasoning_effort: meta?.reasoning_effort,
5709
+ reasoning_fallback: meta?.reasoning_fallback
5710
+ }
5711
+ };
5712
+ }
5713
+ var toZaiReplayToolCalls = (toolCalls) => {
5714
+ if (!toolCalls?.length) {
5715
+ return [];
5716
+ }
5717
+ return toolCalls.map((call) => ({
5718
+ id: call.id,
5719
+ type: "function",
5720
+ function: {
5721
+ name: call.function.name,
5722
+ arguments: call.function.arguments
5723
+ }
5724
+ }));
5725
+ };
5726
+ var toToolCall = (call) => ({
5727
+ id: call.id,
5728
+ type: "function",
5729
+ function: {
5730
+ name: call.name,
5731
+ arguments: call.arguments
5732
+ },
5733
+ provider_meta: {
5734
+ provider: "zai",
5735
+ index: call.index,
5736
+ raw_chunk_count: call.raw_chunk_count
5737
+ }
5738
+ });
5739
+ var normalizeNumber = (value) => {
5740
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
5741
+ return 0;
5742
+ }
5743
+ return Math.trunc(value);
5744
+ };
5745
+ var normalizeZaiUsage = (accumulator) => {
5746
+ const usage = accumulator.usage;
5747
+ if (!usage) {
5748
+ return null;
5749
+ }
5750
+ const inputTokens = normalizeNumber(usage.prompt_tokens);
5751
+ const outputTokens = normalizeNumber(usage.completion_tokens);
5752
+ const totalTokens = typeof usage.total_tokens === "number" ? normalizeNumber(usage.total_tokens) : inputTokens + outputTokens;
5753
+ const cachedTokens = normalizeNumber(
5754
+ usage.prompt_tokens_details?.cached_tokens
5755
+ );
5756
+ return {
5757
+ model: accumulator.model ?? "",
5758
+ input_tokens: inputTokens,
5759
+ ...cachedTokens > 0 ? { input_cached_tokens: cachedTokens } : {},
5760
+ output_tokens: outputTokens,
5761
+ total_tokens: totalTokens
5762
+ };
5763
+ };
5764
+
5765
+ // src/llm/zai/transport.ts
5766
+ var streamZaiChatCompletion = async ({
5767
+ apiKey,
5768
+ baseURL,
5769
+ fetchImpl,
5770
+ request,
5771
+ signal,
5772
+ timeoutMs,
5773
+ captureRawChunks
5774
+ }) => {
5775
+ const requestSignal = createZaiRequestSignal(signal, timeoutMs);
5776
+ try {
5777
+ const response = await fetchImpl(`${baseURL}/chat/completions`, {
5778
+ method: "POST",
5779
+ headers: {
5780
+ Authorization: `Bearer ${apiKey}`,
5781
+ "Content-Type": "application/json"
5782
+ },
5783
+ body: safeJsonStringify(request),
5784
+ signal: requestSignal.signal
5785
+ });
5786
+ if (!response.ok) {
5787
+ throw await toZaiHttpError(response);
5788
+ }
5789
+ const accumulated = createZaiStreamAccumulator({
5790
+ captureRawChunks: captureRawChunks ?? false
5791
+ });
5792
+ for await (const chunk of readZaiChatCompletionStream(
5793
+ response,
5794
+ requestSignal.signal
5795
+ )) {
5796
+ appendZaiChatCompletionChunk(accumulated, chunk);
5797
+ }
5798
+ return {
5799
+ status: response.status,
5800
+ request_id: response.headers.get("x-request-id"),
5801
+ accumulated
5802
+ };
5803
+ } finally {
5804
+ requestSignal.cleanup();
5805
+ }
5806
+ };
5807
+ async function* readZaiChatCompletionStream(response, signal) {
5808
+ if (!response.body) {
5809
+ throw new Error("Z.ai provider error: response body is empty");
5810
+ }
5811
+ const reader = response.body.getReader();
5812
+ throwIfAborted2(signal);
5813
+ const cancelOnAbort = () => {
5814
+ void reader.cancel(signal?.reason).catch(() => void 0);
5815
+ };
5816
+ signal?.addEventListener("abort", cancelOnAbort, { once: true });
5817
+ const decoder = new TextDecoder();
5818
+ let buffer = "";
5819
+ try {
5820
+ while (true) {
5821
+ throwIfAborted2(signal);
5822
+ const { done, value } = await reader.read();
5823
+ throwIfAborted2(signal);
5824
+ if (done) {
5825
+ break;
5826
+ }
5827
+ buffer += decoder.decode(value, { stream: true });
5828
+ let newlineIndex = buffer.indexOf("\n");
5829
+ while (newlineIndex >= 0) {
5830
+ const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
5831
+ buffer = buffer.slice(newlineIndex + 1);
5832
+ const chunk = parseSseDataLine(line);
5833
+ if (chunk === "done") {
5834
+ return;
5835
+ }
5836
+ if (chunk) {
5837
+ yield chunk;
5838
+ }
5839
+ newlineIndex = buffer.indexOf("\n");
5840
+ }
5841
+ }
5842
+ buffer += decoder.decode();
5843
+ const trailing = buffer.trim();
5844
+ if (trailing) {
5845
+ const chunk = parseSseDataLine(trailing);
5846
+ if (chunk && chunk !== "done") {
5847
+ yield chunk;
5848
+ }
5849
+ }
5850
+ } finally {
5851
+ signal?.removeEventListener("abort", cancelOnAbort);
5852
+ reader.releaseLock();
5853
+ }
5854
+ }
5855
+ var createZaiRequestSignal = (signal, timeoutMs) => {
5856
+ if (!timeoutMs || timeoutMs <= 0) {
5857
+ return { signal, cleanup: () => void 0 };
5858
+ }
5859
+ const controller = new AbortController();
5860
+ let timeout = setTimeout(() => {
5861
+ controller.abort(new Error("Z.ai request timeout"));
5862
+ }, timeoutMs);
5863
+ const onAbort = () => {
5864
+ controller.abort(signal?.reason);
5865
+ };
5866
+ if (signal?.aborted) {
5867
+ onAbort();
5868
+ } else {
5869
+ signal?.addEventListener("abort", onAbort, { once: true });
5870
+ }
5871
+ return {
5872
+ signal: controller.signal,
5873
+ cleanup: () => {
5874
+ if (timeout) {
5875
+ clearTimeout(timeout);
5876
+ timeout = void 0;
5877
+ }
5878
+ signal?.removeEventListener("abort", onAbort);
5879
+ }
5880
+ };
5881
+ };
5882
+ var toZaiHttpError = async (response) => {
5883
+ let body = "";
5884
+ try {
5885
+ body = await response.text();
5886
+ } catch {
5887
+ body = "";
5888
+ }
5889
+ const snippet = body ? body.slice(0, 500) : "(empty)";
5890
+ 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";
5891
+ return new Error(`${prefix} (${response.status}): ${snippet}`);
5892
+ };
5893
+ var throwIfAborted2 = (signal) => {
5894
+ if (!signal?.aborted) {
5895
+ return;
5896
+ }
5897
+ const reason = signal.reason;
5898
+ if (reason instanceof Error) {
5899
+ throw reason;
5900
+ }
5901
+ throw new Error("Z.ai request aborted");
5902
+ };
5903
+ var parseSseDataLine = (line) => {
5904
+ const trimmed = line.trim();
5905
+ if (!trimmed || trimmed.startsWith(":")) {
5906
+ return null;
5907
+ }
5908
+ if (!trimmed.startsWith("data:")) {
5909
+ return null;
5910
+ }
5911
+ const data = trimmed.slice("data:".length).trim();
5912
+ if (!data) {
5913
+ return null;
5914
+ }
5915
+ if (data === "[DONE]") {
5916
+ return "done";
5917
+ }
5918
+ try {
5919
+ return JSON.parse(data);
5920
+ } catch {
5921
+ throw new Error(`Malformed Z.ai stream chunk: ${data.slice(0, 300)}`);
5922
+ }
5923
+ };
5924
+
5925
+ // src/llm/zai/chat.ts
5926
+ var PROVIDER_NAME4 = "zai";
5927
+ var DEFAULT_BASE_URL = "https://api.z.ai/api/paas/v4";
5928
+ var DEFAULT_REASONING_EFFORT3 = "high";
5929
+ var DEFAULT_REQUEST_TIMEOUT_MS = 20 * 60 * 1e3;
5930
+ var ChatZai = class {
5931
+ provider = PROVIDER_NAME4;
5932
+ model;
5933
+ apiKey;
5934
+ baseURL;
5935
+ fetchImpl;
5936
+ timeoutMs;
5937
+ defaultReasoningEffort;
5938
+ reasoningLevelMeta;
5939
+ debugInvokeSeq = 0;
5940
+ lastDebugRequestPayload = null;
5941
+ constructor(options = {}) {
5942
+ this.apiKey = options.apiKey;
5943
+ this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
5944
+ this.fetchImpl = options.fetch ?? fetch;
5945
+ this.model = options.model ?? ZAI_DEFAULT_MODEL;
5946
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
5947
+ this.defaultReasoningEffort = options.reasoningEffort === void 0 ? DEFAULT_REASONING_EFFORT3 : options.reasoningEffort;
5948
+ this.reasoningLevelMeta = {
5949
+ requested: options.reasoningLevelRequested,
5950
+ applied: options.reasoningLevelApplied,
5951
+ fallbackApplied: options.reasoningFallbackApplied
5952
+ };
5953
+ }
5954
+ async ainvoke(input, _context) {
5955
+ const apiKey = this.apiKey;
5956
+ if (!apiKey) {
5957
+ throw new Error("Z.ai API key is required");
5958
+ }
5959
+ const {
5960
+ messages,
5961
+ tools: toolDefs,
5962
+ toolChoice,
5963
+ options,
5964
+ model,
5965
+ signal
5966
+ } = input;
5967
+ const { reasoningEffort, ...rest } = options ?? {};
5968
+ const effectiveReasoningEffort = reasoningEffort === void 0 ? this.defaultReasoningEffort : reasoningEffort;
5969
+ const tools = toZaiTools(toolDefs);
5970
+ const toolChoiceParam = toZaiToolChoice(toolChoice);
5971
+ const request = {
5972
+ model: model ?? this.model,
5973
+ messages: toZaiMessages(messages),
5974
+ stream: true,
5975
+ thinking: { type: "enabled" },
5976
+ ...rest,
5977
+ ...effectiveReasoningEffort ? { reasoning_effort: effectiveReasoningEffort } : {},
5978
+ ...tools ? { tools } : {},
5979
+ ...tools ? { tool_stream: true } : {},
5980
+ ...toolChoiceParam ? { tool_choice: toolChoiceParam } : {}
5981
+ };
5982
+ const debugSeq = this.nextDebugInvokeSeq();
5983
+ await this.debugRequestIfEnabled(request, debugSeq);
5984
+ const terminal = await this.streamRequest(apiKey, request, signal);
5985
+ await this.debugResponseIfEnabled(terminal, debugSeq);
5986
+ return toZaiChatInvokeCompletion(terminal.accumulated, {
5987
+ request_id: terminal.request_id ?? null,
5988
+ reasoning_requested: this.reasoningLevelMeta.requested,
5989
+ reasoning_applied: this.reasoningLevelMeta.applied,
5990
+ reasoning_effort: request.reasoning_effort,
5991
+ reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
5992
+ });
5993
+ }
5994
+ async streamRequest(apiKey, request, signal) {
5995
+ const logSettings = getProviderLogSettings();
5996
+ return streamZaiChatCompletion({
5997
+ apiKey,
5998
+ baseURL: this.baseURL,
5999
+ fetchImpl: this.fetchImpl,
6000
+ request,
6001
+ signal,
6002
+ timeoutMs: this.timeoutMs,
6003
+ captureRawChunks: Boolean(logSettings.dumpDir)
6004
+ });
6005
+ }
6006
+ nextDebugInvokeSeq() {
6007
+ const seq = this.debugInvokeSeq + 1;
6008
+ this.debugInvokeSeq = seq;
6009
+ return seq;
6010
+ }
6011
+ async debugRequestIfEnabled(request, seq) {
6012
+ const settings = getProviderLogSettings();
6013
+ if (!settings.enabled && !settings.dumpDir) {
6014
+ return;
6015
+ }
6016
+ const payload = safeJsonStringify(request);
6017
+ const hash = (0, import_node_crypto4.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
6018
+ const toolsHash = (0, import_node_crypto4.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
6019
+ const previous = this.lastDebugRequestPayload;
6020
+ const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
6021
+ const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
6022
+ if (settings.enabled) {
6023
+ console.error(
6024
+ `[zai.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash}`
6025
+ );
6026
+ }
6027
+ if (settings.dumpDir) {
6028
+ try {
6029
+ await writeProviderLogDump(
6030
+ settings,
6031
+ PROVIDER_NAME4,
6032
+ seq,
6033
+ "request",
6034
+ request
6035
+ );
6036
+ } catch (error) {
6037
+ if (settings.enabled) {
6038
+ console.error(
6039
+ `[zai.request] dump_failed seq=${seq} error=${String(error)}`
6040
+ );
6041
+ }
6042
+ }
6043
+ }
6044
+ this.lastDebugRequestPayload = payload;
6045
+ }
6046
+ async debugResponseIfEnabled(response, seq) {
6047
+ const settings = getProviderLogSettings();
6048
+ if (!settings.enabled && !settings.dumpDir) {
6049
+ return;
6050
+ }
6051
+ const usage = response.accumulated.usage;
6052
+ if (settings.enabled) {
6053
+ const inputTokens = usage?.prompt_tokens ?? 0;
6054
+ const outputTokens = usage?.completion_tokens ?? 0;
6055
+ console.error(
6056
+ `[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}`
6057
+ );
6058
+ }
6059
+ if (settings.dumpDir) {
6060
+ try {
6061
+ await writeProviderLogDump(
6062
+ settings,
6063
+ PROVIDER_NAME4,
6064
+ seq,
6065
+ "response",
6066
+ response.accumulated
6067
+ );
6068
+ } catch (error) {
6069
+ if (settings.enabled) {
6070
+ console.error(
6071
+ `[zai.response] dump_failed seq=${seq} error=${String(error)}`
6072
+ );
6073
+ }
6074
+ }
6075
+ }
6076
+ }
6077
+ };
6078
+
5488
6079
  // src/prompts.ts
5489
6080
  var import_node_path2 = __toESM(require("path"), 1);
5490
6081
  var import_node_url = require("url");
@@ -5626,6 +6217,7 @@ function defineTool(toolOptions) {
5626
6217
  ChatAnthropic,
5627
6218
  ChatOpenAI,
5628
6219
  ChatOpenRouter,
6220
+ ChatZai,
5629
6221
  DEFAULT_MODEL_REGISTRY,
5630
6222
  GOOGLE_MODELS,
5631
6223
  OPENAI_DEFAULT_MODEL,
@@ -5633,6 +6225,9 @@ function defineTool(toolOptions) {
5633
6225
  OPENAI_MODELS,
5634
6226
  TaskComplete,
5635
6227
  ToolOutputCacheService,
6228
+ ZAI_DEFAULT_MODEL,
6229
+ ZAI_MODELS,
6230
+ ZAI_REASONING_EFFORT_MODELS,
5636
6231
  applyModelMetadata,
5637
6232
  createModelRegistry,
5638
6233
  defineTool,