Files
OmniRoute/open-sse/executors/zai-web.ts
Diego Rodrigues de Sa e Souza d259d9fcba fix(ci): clear base-reds on release/v3.8.50 (round 3) (#10213)
* fix(ci): clear base-reds on release/v3.8.50 (round 3)

- CHANGELOG.md: restore the top [Unreleased] section dropped by the #10189
  reconcile (docs-sync gate: first section must be Unreleased)
- env-doc-sync: document CONDUCTOR_ORCHESTRATOR_TOKEN + CONDUCTOR_SPOKESPERSON_URL
  in .env.example/ENVIRONMENT.md; allowlist the CI-only GITHUB_STEP_SUMMARY and
  TS7_BASE_REF (ts7 ratchet signals); drop a stray merge artifact line
- providers: restore the audited chatanywhere metadata entry that base-reds
  round 2 dropped together with its duplicate — the provider was half-wired
  (registry+endpoint without APIKEY metadata), which is what the wave3 test
  catches; re-pin providers-constants-split at the measured 228
- docs counts: 338 -> 339 (today's +2 void-ai/helixmind, -1 Puter) via
  gen:provider-reference + README/AGENTS/llm.txt/package.json/diagrams/i18n mirrors
- file-size ratchet: annotated rebaseline for the two pre-existing drifts
  (ModelSelectModal 1138, gateways 1250) following the 2026-08-11 precedent

Refs #9985

* fix(ci): base-reds round 3b — stale sibling tests + mode-pack weight contract

- check-docs-counts-sync.test.ts: drop the imports/subtests of the four helpers
  #10196 removed from the gate script (readMcpFactsFromSource, listLocalizedDocs,
  makeRequiredCountsValidator, checkFreeTierInventory) — the new-API tests that
  #10196 added stay; the file now loads again under the node runner
- quota-connection-recovery.test.ts: convert from vitest APIs to node:test —
  the file lives in tests/unit/*.test.ts (node-runner glob) and the vitest
  runtime crashes when imported outside vitest, killing the whole shard entry
- modePacks.ts: re-normalize all six mode packs to sum 1.0 — #8940 added
  sessionAvailability: 0.05 to every pack without rebalancing (1.05 total);
  ratios preserved exactly (÷1.05), so post-normalizeScoringWeights behavior
  is unchanged; restores the declared sum-to-1.0 contract the 4235 test pins

Refs #9985

* fix(ci): base-reds round 3c — vitest siblings, weights default, secrets FP, mutation tap

- DistributeProxiesButton.test.tsx: wrap renders in NextIntlClientProvider —
  #9245 localized the component (useTranslations) and left the test without
  the intl context, failing all 14 cases
- scoring.ts: re-normalize DEFAULT_WEIGHTS to sum 1.0 (same #8940 class as the
  mode packs — sessionAvailability added without rebalancing; ratios preserved)
- .gitleaks.toml: generalize the kimi sponsor-banner localStorage-key allowlist
  to -v\d+ — #10200 bumped v1→v2 and the stale regex regressed the secrets
  ratchet with a false positive
- stryker.conf.json: register 6 covering unit tests in tap.testFiles (4 modules)
  so their mutant kills count — unblocks check:mutation-test-coverage --strict

Refs #9985

* fix(ci): base-reds round 3d — inspector factor gap, stale registry/gap tests, i18n key sync

- comboScoringInspector: add cacheAffinity/sessionAvailability/connectionDensity
  to FACTOR_KEYS + the factor-key type — calculateScore() weighs them but the
  breakdown omitted them, so the explained contributions never summed to the
  reported score (inspector bug, red on the pure tip)
- combo-scoring-inspector.test: make the explicit-weights override sum-neutral
  (±0.05 shift) so it stays valid for any DEFAULT_WEIGHTS values — the hardcoded
  override only summed to 1.0 against the pre-#8940 defaults, which is also why
  explicit weights silently fell back to 'default' on the tip
- unorouter-registry.test: align to the canonical .com host (api.unorouter.ai
  301-redirects there, verified live) and to wave4's live model discovery
  (passthrough, no static seed) — the .ai/auto-model expectations were stale
- check-migration-numbering.test: 147 left KNOWN_GAPS when
  147_api_keys_model_access_mode.sql landed — assert absent (same as 143)
- i18n: sync-ui pass — 35,914 missing UI keys stamped as __MISSING__ placeholders
  across 42 locales (mechanical; greens the pt-BR key-presence integrity test;
  coverage pct unchanged by design — translation is a separate workstream)

Refs #9985

* fix(ci): base-reds round 3e — 2 real defects + 14 stale sibling tests (waves A-E)

Real defects fixed:
- src/lib/db/apiKeys.ts: #9313's empty-allowlist early return bypassed the group
  permission check, silently disabling group deny rules (#8817) for every key
  without a per-key allowlist; fall-through restored, restricted+[] deny-all kept
- open-sse/utils/proxyFetch.ts: #10032 re-appended the raw transport error to the
  propagated message, reintroducing the proxy user:password leak #9837 closed;
  new redactProxyDetailsInMessage() keeps the reason, redacts URL/credentials
- .github/workflows/quality.yml: #10134 added the TS7 ratchet as a separate
  blocking step AFTER the aggregated gates — the exact #8542 masking mechanism;
  folded into the non-fail-fast loop (still blocking, still PR-only) ⚠️ CI edit,
  gate-strengthening — explicit owner sign-off requested on the PR
- src/i18n/messages/ko.json: 3 machine-mistranslation regressions caught by the
  #8244 glossary checker (장애인→비활성화됨, 양말5://→socks5://, 비클로드→Claude가 아닌)

Stale sibling tests aligned to deliberately-moved contracts (each cites its mover):
request-log-detail-layout + -stream (#9245 intl provider), repro-8542 pin update,
quality-rail-gate-membership (#10134 shape), agentSkills-routes 45→46 (#9058),
cloudflare-ai-catalog-8717 (#8804 supersedes #8808), executor-xai (#9994),
vision-bridge-claude-wire (#9463 minimax→openai), sse-auth forced-pin (#8893),
tls-proxy-context (strengthened leak guards), rate-limit-local-error-classification
(#9164/#9342), minimax-thinking-signature (#9463), codebuddy-cn (#9723 +1 test),
github-copilot-custom-model (#9050), providers-g4f-batch3 (#9584),
synced-capability-warmup (#9199, stricter), sidebar-tools-group (#8221),
oauth-modal-grok-cli-paste (#9245); agentSkills/catalog.ts comment 45→46;
file-size rebaseline for proxyFetch (+19, annotated)

Refs #9985

* fix(ci): base-reds round 3f — waves F-J: 9 more real defects + stale sibling sweep

Real production defects fixed (all red on the pure tip, each with its origin):
- routeGuard.ts: #8949 accidentally DELETED the /api/providers/[id]/login
  local-only pattern — the route spawns a browser, so the loopback gate for a
  process-spawning route was gone (Hard Rules #15/#17); restored (314 guard
  tests green)
- agentSkills generator: #9058's category dispatch gave the config category an
  empty body, wiping skills/config-codex-cli/SKILL.md at the #10131 sync;
  fixed + SKILL.md regenerated via the official generator
- imageRegistry: #9982 broke same-provider bare aliasing (antigravity preview
  id sent upstream unresolved); new resolveSameProviderBareAlias() keeps the
  fal cross-provider fix intact
- imageRegistry: #9982's prefix strip handed the bare nano-banana ids to fal-ai,
  violating the pinned 2026-07-31 operator decision (adobe-firefly owns them);
  fal entries made prefix-only (dispatch already re-prefixes)
- mediaGeneration/fal.ts: the missing-credential 401 guard was lost when #10198
  deleted the superseded falHandler — tests were hitting the live network
- bottleneckPatch/rateLimitManager: #9041's merge clobbered #9604, resurrecting
  the Bottleneck v2.19.5 heartbeat bug (reservoir never refills); patched the
  library defect at the root and re-aligned chat-rate-limit-body-lock to the
  working reservoir contract
- processSupervisor.mjs: #9761 regressed the Node spawn to bare "node" (the
  #9156 launchd bug) and dropped #9209's ipv4first args; both restored
- openai-responses/pureHelpers: #9423's Agent null-sentinel was unreachable on
  the schemaless JSON-string path; gate extended
- i18n en.json: #8222's regen reverted the #9976 unclosed-tag fix and #8559's
  combo-cooldown copy; #9038 shipped 40 t() calls with no messages (runtime
  MISSING_MESSAGE); all restored/added + official sync-ui stamps, and vi's
  zero-marker policy re-established via the sanctioned translation backend

Stale sibling tests aligned (movers cited inline): chat-helpers (#9447),
executor-antigravity (#9351), video-fal-grok (#9982), visionBridge (#9759),
web-session-credentials (#8974), production-build-module-integrity (positive
anchor added), agentSkills-generator/skillManifestsLint/skills-injection/
agentSkillTools-mcp/listCapabilities-a2a (#9058), memory-settings (#10010),
model-catalog-policy-invalidation (#8906), model-alias-seed (#9485),
reactive-context-compaction (#8949), combo-provider-wildcard (broken upsert
helper), oauth-google-loopback (43-locale resurrected-key removal)

Validation: 501/501 across the 47 touched test files; typecheck:core, lint,
file-size, docs-sync all green.

Refs #9985

* fix(ci): base-reds round 3g — wave K/L: 4 more real defects + stale alignments

Real defects:
- base/reasoningEffort.ts: the stale duplicate cherry-pick #9612 re-added the
  codex minimal→low rewrite that #9883 had deliberately removed (OMP minimal
  passthrough); block removed again
- cursorImages.ts: #9840 wired prepareCursorImageForWire (sharp re-encode,
  fail-closed) into the SHARED resolveCursorImages, breaking zai-web and
  conol-web image uploads (HTTP 400 'undecodable'); new prepareForWire opt-out,
  Cursor default path unchanged (8 cursor suites green)
- modelCapabilities/snapshot: catalog prepare still issued 323 per-model reads
  of model_context_overrides + max_input_tokens overrides, violating #9199's
  bulk-load contract; both now resolve from the snapshot single pass
- v1-models-discovery-conformance: re-pinned to the bounded 30s SWR window
  (#9199/#10198) — the old 'stale-first regardless of age' contract is gone

Stale tests aligned (movers cited inline): codex-tools-strict-default (#9828
redundant-oneOf strip), devin-providers (#9245 i18n), db-migrationrunner-
constants-split (147→151 renumber #8228), gitlab-duo-oauth-setup (#9245),
chatcore-extracted-modules (#9161 outbound-protocol keying)

compression-api CI failures were cascade artifacts of codex-tools-strict-default
failing in the same force-exit shard process — no own defect (171/171 local).

Refs #9985

* fix(test): compression-api — register both describes before the runner starts

The DATA_DIR setup + route/db top-level awaits sat BETWEEN the two describes;
under --test-force-exit (the CI unit-runner flag) the process exits once the
already-registered tests finish, so on slow CI machines the whole second
describe died as 'Promise resolution is still pending' — the recurring
CI-only shard-2 failure that never reproduced locally without the flag.
Moved to the top of the file; 10/10 under --test-force-exit locally.

Refs #9985

* fix(quality): freeze modelCapabilities.ts at 1006 (annotated) — snapshot routing growth

Refs #9985

* fix(quality): move the modelCapabilities freeze into the frozen map (nested schema)

Refs #9985

* fix(i18n): translate all 39,718 pending UI keys across 42 locales (owner-approved)

Mass-translated every __MISSING__ placeholder via the official i18n:sync-ui
--translate-markers pipeline (operator backend), restoring i18nUiCoverage to the
100 baseline (was 89.9 after the merge-storm UI landings + the 42 keys #9038
never shipped).

Post-pass repairs, all caught by the existing gates:
- glossary: retired renderings the machine reintroduced normalized again
  (提供商→提供者 zh-CN/zh-TW, 鏈接→連結, 文檔→文件, 調用→呼叫, 供應商→提供者,
  響應→回應, 不活躍→未啟用 zh-TW; 클로드→Claude, 옴니루트→OmniRoute ko);
  DATA_DIR forbidden rendering avoided via 数据文件夹 rephrase
- ICU integrity: 120 values with renamed/dropped {params} repaired (39
  positional renames, 81 reset to the en source — functional over fluent)

Validation: glossary/pt-BR/vi/deno-relay/settings-keys/value-drift/google-
loopback suites 76/76; placeholder diff en×42 locales = 0; worst-locale
coverage = 100.0%.

Refs #9985

---------

Co-authored-by: backryun <bakryun0718@proton.me>
2026-08-13 00:02:25 -03:00

599 lines
19 KiB
TypeScript

/**
* ZaiWebExecutor — Z.ai consumer chat (chat.z.ai).
*
* The consumer frontend stores a Bearer JWT in localStorage and requires a
* browser-issued CAPTCHA proof for chat completions. The browser transport is
* the default; callers with a short-lived proof can use the direct HTTP path.
*
* Completions go to /api/v2/chat/completions; the older unversioned
* /api/chat/completions path is stale and 404s model-independently (#8014).
*/
import { createHash, randomUUID } from "node:crypto";
import { BaseExecutor, type ExecuteInput } from "./base.ts";
import { configureZaiBrowserRequest } from "./zai-web/browserAutomation.ts";
import {
asRecord,
browserModelName,
browserPrompt,
buildZaiCompletionUrl,
buildZaiHeaders,
buildZaiNewChatBody,
buildZaiRequestBody,
buildZaiSignature,
collectZaiImageUrls,
describeZaiBrowserFailure,
extractZaiToken,
extractZaiUserId,
foldMessages,
getZaiModelCapabilities,
latestUserPrompt,
parseZaiFrontendVersion,
resolveZaiCaptchaVerifyParam,
resolveZaiThinkingConfig,
resolveZaiVlmConfig,
unprefixedModelId,
zaiImageFileName,
ZAI_BASE_URL,
ZAI_CHAT_URL,
ZAI_DEFAULT_FE_VERSION,
ZAI_DEFAULT_MODEL,
ZAI_FE_VERSION_CACHE_TTL_MS,
ZAI_NEW_CHAT_URL,
ZAI_USER_AGENT,
type ZaiReasoningEffort,
type ZaiThinkingConfig,
type ZaiVlmConfig,
} from "./zai-web/protocol.ts";
import {
buildZaiStreamingBody,
collectZaiNonStreaming,
makeZaiChunkEmitter,
} from "./zai-web/stream.ts";
import { browserBackedChat } from "../services/browserBackedChat.ts";
import { CursorImageError, resolveCursorImages } from "../utils/cursorImages.ts";
import {
makeExecutorErrorResult as makeErrorResult,
sanitizeErrorMessage,
} from "../utils/error.ts";
export {
buildZaiSignature,
describeZaiBrowserFailure,
extractZaiCaptchaVerifyParam,
extractZaiToken,
extractZaiUserId,
foldMessages,
getZaiModelCapabilities,
parseZaiFrontendVersion,
resolveZaiThinkingConfig,
resolveZaiVlmConfig,
} from "./zai-web/protocol.ts";
export type {
ZaiModelCapabilities,
ZaiReasoningEffort,
ZaiThinkingConfig,
ZaiVlmConfig,
} from "./zai-web/protocol.ts";
export { parseZaiFrame } from "./zai-web/stream.ts";
export type { ZaiDelta } from "./zai-web/stream.ts";
let cachedFeVersion: { value: string; expiresAt: number } | null = null;
type ZaiBrowserAttachments = NonNullable<Parameters<typeof browserBackedChat>[0]["attachments"]>;
/** Decode the request's image URLs into browser upload attachments. */
async function resolveZaiBrowserAttachments(
imageUrls: string[],
body: unknown
): Promise<
{ attachments: ZaiBrowserAttachments } | { errorResult: ReturnType<typeof makeErrorResult> }
> {
try {
// Browser-page upload: keep the original bytes/mimeType (no Cursor wire prep).
const images = await resolveCursorImages(imageUrls, { prepareForWire: false });
return {
attachments: images.map((image, index) => ({
name: zaiImageFileName(image.mimeType, index),
mimeType: image.mimeType,
buffer: image.data,
})),
};
} catch (error) {
const message =
error instanceof CursorImageError
? error.message
: sanitizeErrorMessage(error instanceof Error ? error.message : "invalid image input");
return {
errorResult: makeErrorResult(
error instanceof CursorImageError ? error.status : 400,
`Z.ai image input error: ${message}`,
body,
ZAI_CHAT_URL
),
};
}
}
/**
* The call-log body for a browser-transport turn. There is no real upstream
* request payload to record here, so this reconstructs the equivalent shape the
* signed-API path logs, from the settings the browser UI was driven with.
*/
function buildZaiBrowserAuditBody(input: {
messages: Array<{ role: string; content: unknown }>;
modelId: string;
thinkingConfig: ZaiThinkingConfig;
vlmConfig: ZaiVlmConfig;
imageCount: number;
}): Record<string, unknown> {
const { thinkingConfig: thinking, vlmConfig: vlm } = input;
return {
browser_backed: true,
image_count: input.imageCount,
model: input.modelId,
messages: foldMessages(input.messages),
enable_thinking: thinking.enabled,
auto_web_search: vlm.websiteModeEnabled ? false : vlm.webSearchEnabled,
vlm_tools_enable: vlm.toolsEnabled,
vlm_web_search_enable: vlm.websiteModeEnabled && vlm.webSearchEnabled,
vlm_website_mode: vlm.websiteModeEnabled,
...(thinking.enabled && thinking.effortSupported ? { reasoning_effort: thinking.effort } : {}),
};
}
/**
* Drive-the-real-UI options for chat.z.ai: which selectors to type into and click,
* and the localStorage token the page reads at boot. `beforeSubmit` flips the
* Deep Think / web-search / tools switches to match the request.
*/
function buildZaiBrowserChatOptions(input: {
attachments: ZaiBrowserAttachments;
messages: Array<{ role: string; content: unknown }>;
modelId: string;
signal?: AbortSignal | null;
thinkingConfig: ZaiThinkingConfig;
token: string;
vlmConfig: ZaiVlmConfig;
}): Parameters<typeof browserBackedChat>[0] {
const poolKey = `zai-web:${createHash("sha256").update(input.token).digest("hex").slice(0, 24)}`;
return {
poolKey,
chatUrl: ZAI_CHAT_URL,
chatPageUrl: `${ZAI_BASE_URL}/?model=${encodeURIComponent(browserModelName(input.modelId))}`,
userMessage: browserPrompt(input.messages),
localStorage: { token: input.token },
localStorageOrigin: ZAI_BASE_URL,
cookieDomain: "chat.z.ai",
chatUrlMatchDomain: "chat.z.ai",
userAgent: ZAI_USER_AGENT,
locale: "en-US",
timezone: "Asia/Seoul",
inputSelector: "#chat-input",
submitButtonSelector: '[aria-label="Send Message"] button:not([disabled])',
submitButtonMode: "dom",
attachments: input.attachments,
beforeSubmit: (page) =>
configureZaiBrowserRequest(page, {
modelId: input.modelId,
thinking: input.thinkingConfig,
vlm: input.vlmConfig,
}),
postSubmitWaitMs: 30_000,
signal: input.signal,
reuseContext: true,
};
}
/** What either transport hands back: the upstream stream plus its call-log pair. */
type ZaiTransportResult = {
upstream: Response;
auditHeaders: Record<string, string>;
auditBody: Record<string, unknown>;
};
type ZaiResolvedRequest = {
captchaVerifyParam: string;
imageUrls: string[];
messages: Array<{ role: string; content: unknown }>;
modelId: string;
prompt: string;
thinkingConfig: ZaiThinkingConfig;
token: string;
userId: string;
vlmConfig: ZaiVlmConfig;
};
/**
* Validate the credential and body, and resolve everything both transports need.
*
* All four rejections are client errors that must never reach the upstream: no
* usable session token, no user turn, an image sent to a text-only model, and a
* JWT with no user id (which the signed-API path needs to build its signature).
*/
function resolveZaiRequest(
input: ExecuteInput
): { request: ZaiResolvedRequest } | { errorResult: ReturnType<typeof makeErrorResult> } {
const { body, credentials, model } = input;
const bodyObj = (body || {}) as Record<string, unknown>;
const fail = (message: string) => ({
errorResult: makeErrorResult(400, message, body, ZAI_CHAT_URL),
});
const rawCredential = String(credentials?.apiKey ?? credentials?.accessToken ?? "").trim();
const token = extractZaiToken(rawCredential);
if (!token) {
return fail(
'Missing Z.ai web-session credential — copy the "token" value from chat.z.ai Local Storage.'
);
}
const messages = (bodyObj.messages as Array<{ role: string; content: unknown }>) || [];
const prompt = latestUserPrompt(messages);
const imageUrls = collectZaiImageUrls(messages);
if (!prompt && imageUrls.length === 0) {
return fail("Z.ai requires at least one user message");
}
const modelId = (bodyObj.model as string) || model || ZAI_DEFAULT_MODEL;
if (imageUrls.length > 0 && !getZaiModelCapabilities(modelId).vision) {
return fail(
`Z.ai model ${unprefixedModelId(modelId)} does not accept image input; use GLM-5V-Turbo.`
);
}
const userId = extractZaiUserId(token);
if (!userId) {
return fail(
"Invalid Z.ai web-session credential — its JWT payload does not contain the required user id."
);
}
return {
request: {
captchaVerifyParam: resolveZaiCaptchaVerifyParam(credentials, bodyObj),
imageUrls,
messages,
modelId,
prompt,
thinkingConfig: resolveZaiThinkingConfig(modelId, bodyObj),
token,
userId,
vlmConfig: resolveZaiVlmConfig(modelId, bodyObj),
},
};
}
export class ZaiWebExecutor extends BaseExecutor {
constructor() {
super("zai-web", { id: "zai-web", baseUrl: ZAI_BASE_URL });
}
private async resolveFrontendVersion(signal?: AbortSignal | null): Promise<string> {
if (cachedFeVersion && cachedFeVersion.expiresAt > Date.now()) {
return cachedFeVersion.value;
}
let version = ZAI_DEFAULT_FE_VERSION;
try {
const response = await fetch(`${ZAI_BASE_URL}/`, {
headers: { Accept: "text/html", "User-Agent": ZAI_USER_AGENT },
signal,
});
if (response.ok) {
version = parseZaiFrontendVersion(await response.text()) ?? version;
}
} catch {
// The current verified version remains a safe fallback when homepage probing fails.
}
cachedFeVersion = {
value: version,
expiresAt: Date.now() + ZAI_FE_VERSION_CACHE_TTL_MS,
};
return version;
}
private async createRemoteChat(input: {
messages: Array<{ role: string; content: unknown }>;
modelId: string;
token: string;
enableThinking: boolean;
reasoningEffort: ZaiReasoningEffort;
vlmConfig: ZaiVlmConfig;
signal?: AbortSignal | null;
originalBody: unknown;
}): Promise<
{ chatId: string; userMessageId: string } | { errorResult: ReturnType<typeof makeErrorResult> }
> {
const { userMessageId, payload } = buildZaiNewChatBody(
input.messages,
input.modelId,
input.enableThinking,
input.reasoningEffort,
input.vlmConfig
);
let response: Response;
try {
response = await fetch(ZAI_NEW_CHAT_URL, {
method: "POST",
headers: buildZaiHeaders(input.token, {
accept: "application/json",
}),
body: JSON.stringify(payload),
signal: input.signal,
});
} catch (error) {
const message = sanitizeErrorMessage(
error instanceof Error ? error.message : "unknown network error"
);
return {
errorResult: makeErrorResult(
502,
`Z.ai chat creation failed: ${message}`,
input.originalBody,
ZAI_NEW_CHAT_URL
),
};
}
if (!response.ok) {
const errorText = await response.text().catch(() => "");
return {
errorResult: makeErrorResult(
response.status,
`Z.ai chat creation error: ${sanitizeErrorMessage(errorText)}`,
input.originalBody,
ZAI_NEW_CHAT_URL
),
};
}
const result = asRecord(await response.json().catch(() => null));
const chatId = typeof result?.id === "string" ? result.id : "";
if (!chatId) {
return {
errorResult: makeErrorResult(
502,
"Z.ai chat creation returned no chat id",
input.originalBody,
ZAI_NEW_CHAT_URL
),
};
}
return { chatId, userMessageId };
}
private async fetchUpstream(
completionUrl: string,
reqHeaders: Record<string, string>,
reqBody: Record<string, unknown>,
body: unknown,
signal: AbortSignal | null | undefined
): Promise<{ upstream: Response } | { errorResult: ReturnType<typeof makeErrorResult> }> {
let upstream: Response;
try {
upstream = await fetch(completionUrl, {
method: "POST",
headers: reqHeaders,
body: JSON.stringify(reqBody),
signal,
});
} catch (error) {
const message = sanitizeErrorMessage(
error instanceof Error ? error.message : "unknown network error"
);
return {
errorResult: makeErrorResult(502, `Z.ai fetch failed: ${message}`, body, ZAI_CHAT_URL),
};
}
if (!upstream.ok) {
const errorText = await upstream.text().catch(() => "");
return {
errorResult: makeErrorResult(
upstream.status,
`Z.ai error: ${sanitizeErrorMessage(errorText)}`,
body,
ZAI_CHAT_URL
),
};
}
return { upstream };
}
private async fetchThroughBrowser(input: {
body: unknown;
messages: Array<{ role: string; content: unknown }>;
modelId: string;
imageUrls: string[];
signal?: AbortSignal | null;
thinkingConfig: ZaiThinkingConfig;
token: string;
vlmConfig: ZaiVlmConfig;
}): Promise<ZaiTransportResult | { errorResult: ReturnType<typeof makeErrorResult> }> {
const resolved = await resolveZaiBrowserAttachments(input.imageUrls, input.body);
if ("errorResult" in resolved) return resolved;
const { attachments } = resolved;
let result: Awaited<ReturnType<typeof browserBackedChat>>;
try {
result = await browserBackedChat(buildZaiBrowserChatOptions({ ...input, attachments }));
} catch (error) {
const message = sanitizeErrorMessage(
error instanceof Error ? error.message : "browser transport unavailable"
);
return {
errorResult: makeErrorResult(
502,
`Z.ai browser transport failed: ${message}`,
input.body,
ZAI_CHAT_URL
),
};
}
if (result.status < 200 || result.status >= 300) {
return {
errorResult: makeErrorResult(
result.status || 502,
describeZaiBrowserFailure(result),
input.body,
ZAI_CHAT_URL
),
};
}
return {
upstream: new Response(new Uint8Array(result.body), {
status: result.status,
headers: {
"Content-Type": result.contentType || "text/event-stream",
},
}),
auditHeaders: {
Authorization: "Bearer [REDACTED]",
"X-OmniRoute-Transport": "browser",
},
auditBody: buildZaiBrowserAuditBody({
messages: input.messages,
modelId: input.modelId,
thinkingConfig: input.thinkingConfig,
vlmConfig: input.vlmConfig,
imageCount: attachments.length,
}),
};
}
/**
* Signed-API transport: create a chat server-side, then POST the completion with
* a CAPTCHA proof and a per-request signature. Only reachable when the caller
* supplied a proof and sent no images.
*/
private async fetchViaSignedApi(
request: ZaiResolvedRequest,
input: ExecuteInput
): Promise<ZaiTransportResult | { errorResult: ReturnType<typeof makeErrorResult> }> {
const { body, signal } = input;
const bodyObj = (body || {}) as Record<string, unknown>;
const { messages, modelId, prompt, thinkingConfig, token, userId, vlmConfig } = request;
const frontendVersion = await this.resolveFrontendVersion(signal);
const createdChat = await this.createRemoteChat({
messages,
modelId,
token,
enableThinking: thinkingConfig.enabled,
reasoningEffort: thinkingConfig.effort,
vlmConfig,
signal,
originalBody: body,
});
if ("errorResult" in createdChat) return createdChat;
const timestamp = Date.now();
const requestId = randomUUID();
const signature = buildZaiSignature({ prompt, requestId, timestamp, userId });
const completionUrl = buildZaiCompletionUrl({ requestId, timestamp, token, userId });
const reqHeaders = buildZaiHeaders(token, {
accept: "text/event-stream",
frontendVersion,
signature,
});
const reqBody = buildZaiRequestBody({
body: bodyObj,
captchaVerifyParam: request.captchaVerifyParam,
chatId: createdChat.chatId,
messages,
modelId,
prompt,
userMessageId: createdChat.userMessageId,
enableThinking: thinkingConfig.enabled,
reasoningEffort: thinkingConfig.effort,
reasoningEffortSupported: thinkingConfig.effortSupported,
vlmConfig,
});
const fetched = await this.fetchUpstream(completionUrl, reqHeaders, reqBody, body, signal);
if ("errorResult" in fetched) return fetched;
return {
upstream: fetched.upstream,
auditHeaders: {
...reqHeaders,
Authorization: "Bearer [REDACTED]",
"X-Signature": "[REDACTED]",
},
auditBody: { ...reqBody, captcha_verify_param: "[REDACTED]" },
};
}
async execute(input: ExecuteInput) {
const { body, signal, stream: wantStream } = input;
const resolved = resolveZaiRequest(input);
if ("errorResult" in resolved) return resolved.errorResult;
const request = resolved.request;
const { imageUrls, messages, modelId, thinkingConfig, token, vlmConfig } = request;
const useSignedApi = Boolean(request.captchaVerifyParam) && imageUrls.length === 0;
const fetched = useSignedApi
? await this.fetchViaSignedApi(request, input)
: await this.fetchThroughBrowser({
body,
imageUrls,
messages,
modelId,
signal,
thinkingConfig,
token,
vlmConfig,
});
if ("errorResult" in fetched) return fetched.errorResult;
const { upstream, auditHeaders, auditBody } = fetched;
const id = `chatcmpl-zai-${Date.now()}`;
const created = Math.floor(Date.now() / 1000);
const sourceBody =
upstream.body ?? new ReadableStream({ start: (controller) => controller.close() });
const emitChunk = makeZaiChunkEmitter(id, created, modelId);
if (wantStream) {
const outStream = buildZaiStreamingBody(sourceBody, emitChunk, signal);
return {
response: new Response(outStream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
}),
url: ZAI_CHAT_URL,
headers: auditHeaders,
transformedBody: auditBody,
};
}
let answer: string;
let reasoning: string;
try {
({ answer, reasoning } = await collectZaiNonStreaming(sourceBody));
} catch (error) {
const message = sanitizeErrorMessage(
error instanceof Error ? error.message : "invalid upstream stream"
);
return makeErrorResult(502, `Z.ai stream failed: ${message}`, body, ZAI_CHAT_URL);
}
const message: Record<string, unknown> = { role: "assistant", content: answer };
if (reasoning) message.reasoning_content = reasoning;
const completion = {
id,
object: "chat.completion",
created,
model: modelId,
choices: [{ index: 0, message, finish_reason: "stop" }],
};
return {
response: new Response(JSON.stringify(completion), {
headers: { "Content-Type": "application/json" },
}),
url: ZAI_CHAT_URL,
headers: auditHeaders,
transformedBody: auditBody,
};
}
}