Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(v0.22): AI video goes live — the z-ai dialect beside the Sora one

Ashiq Hussain Mird51ab196eeb3
diff --git a/scripts/debug-video-slot.ts b/scripts/debug-video-slot.ts
new file mode 100644
index 0000000..c9fd352
--- /dev/null
+++ b/scripts/debug-video-slot.ts
@@ -0,0 +1,13 @@
+// Trace the file-layer header extraction precisely.
+import { readFileSync, existsSync } from 'node:fs'
+import { resolveProviderConfig } from '../src/lib/ai/provider'
+
+const p = '/etc/.z-ai-config'
+console.log('exists:', existsSync(p))
+const raw = JSON.parse(readFileSync(p, 'utf8')) as Record<string, unknown>
+console.log('raw keys:', Object.keys(raw).join(','))
+console.log('token truthy:', !!raw.token, 'userId truthy:', !!raw.userId)
+
+const cfg = resolveProviderConfig()
+console.log('resolved:', cfg ? { baseUrl: cfg.baseUrl, headers: cfg.headers ? Object.keys(cfg.headers) : 'NONE' } : null)
+process.exit(0)
diff --git a/scripts/verify-video-live.ts b/scripts/verify-video-live.ts
new file mode 100644
index 0000000..6d43e26
--- /dev/null
+++ b/scripts/verify-video-live.ts
@@ -0,0 +1,67 @@
+// E2E: the AI video route against the live provider (dev machine only).
+// 1) capabilities says videoGeneration:true
+// 2) POST a short prompt → task id
+// 3) poll until done (bounded)
+// 4) fetch the MP4 through the same-origin proxy → magic bytes + size
+import { request } from 'playwright'
+
+const BASE = 'http://localhost:3000'
+
+async function main() {
+ const r = await request.newContext({ baseURL: BASE, extraHTTPHeaders: { origin: BASE, referer: `${BASE}/` } })
+
+ const caps = await (await r.get('/api/ai/capabilities')).json()
+ console.log('videoGeneration:', caps.capabilities.videoGeneration)
+ if (!caps.capabilities.videoGeneration) {
+ console.log('NOT LIVE — provider not configured')
+ process.exit(1)
+ }
+
+ const t0 = Date.now()
+ const start = await r.post('/api/ai/video', { data: { prompt: 'A red paper boat drifting across calm water, gentle ripples, soft morning light, 3 seconds', duration: 3 } })
+ console.log('POST status:', start.status())
+ const body = await start.json()
+ console.log('POST body:', JSON.stringify(body).slice(0, 300))
+ if (start.status() >= 300) process.exit(1)
+ const id = body.id ?? body.taskId ?? body.data?.id
+ if (!id) {
+ console.log('no task id — abort')
+ process.exit(1)
+ }
+
+ // poll (bounded ~8 min)
+ let done: any = null
+ for (let i = 0; i < 96; i++) {
+ await new Promise((res) => setTimeout(res, 5000))
+ const st: any = await (await r.get(`/api/ai/video?id=${encodeURIComponent(id)}`)).json()
+ const s = JSON.stringify(st)
+ console.log(`poll ${i + 1}: ${s.slice(0, 160)}`)
+ if (st.status === 'succeeded' || st.status === 'completed' || st.status === 'failed' || st.status === 'error') {
+ done = st
+ break
+ }
+ }
+ if (!done) {
+ console.log('TIMEOUT waiting for the generation')
+ process.exit(1)
+ }
+ if (done.status !== 'succeeded' && done.status !== 'completed') {
+ console.log('generation ended in', done.status)
+ process.exit(1)
+ }
+ const videoUrl = done.videos?.[0]?.url ?? done.video?.url ?? done.url
+ if (!videoUrl) {
+ console.log('no video url in the result:', JSON.stringify(done).slice(0, 300))
+ process.exit(1)
+ }
+
+ const mp4 = await r.get(videoUrl.startsWith('/') ? videoUrl : `/api/ai/video?id=${encodeURIComponent(id)}&content=1&index=0`)
+ const buf = await mp4.body()
+ console.log('MP4 fetch status:', mp4.status(), 'bytes:', buf.length)
+ console.log('magic:', buf.slice(4, 12).toString())
+ console.log('TOTAL seconds:', ((Date.now() - t0) / 1000).toFixed(0))
+ const ok = buf.length > 50_000 && buf.slice(4, 8).toString() === 'ftyp'
+ console.log(ok ? 'VIDEO LIVE: PASS' : 'VIDEO LIVE: FAIL')
+ process.exit(ok ? 0 : 1)
+}
+main()
diff --git a/src/app/api/ai/video/route.test.ts b/src/app/api/ai/video/route.test.ts
index a4eb600..e3ba66f 100644
--- a/src/app/api/ai/video/route.test.ts
+++ b/src/app/api/ai/video/route.test.ts
@@ -51,4 +51,50 @@ describe('normalizeVideoStatus', () => {
)
expect(s.videos).toHaveLength(4)
})
+
+ // ── v0.22: the z-ai async-result dialect ────────────────────
+
+ it('maps the z-ai PROCESSING envelope to in_progress with zero videos', () => {
+ const s = normalizeVideoStatus(
+ { id: 'abc', model: 'cogvideox-3', task_status: 'PROCESSING' },
+ 'z:abc',
+ )
+ expect(s.status).toBe('in_progress')
+ expect(s.progress).toBe(50)
+ expect(s.videos).toEqual([])
+ })
+
+ it('maps the z-ai SUCCESS envelope to completed with proxy URLs (prefix preserved)', () => {
+ const s = normalizeVideoStatus(
+ {
+ task_status: 'SUCCESS',
+ video_result: [
+ { url: 'https://cdn.example/a.mp4', cover_image_url: 'https://cdn.example/a.png' },
+ ],
+ },
+ 'z:abc123',
+ )
+ expect(s.status).toBe('completed')
+ expect(s.progress).toBe(100)
+ // the "z:" prefix rides along — the next poll and the video element
+ // src keep routing to the z-ai dialect
+ expect(s.videos).toEqual([{ index: 0, url: '/api/ai/video?id=z%3Aabc123&content=1&index=0' }])
+ })
+
+ it('maps z-ai FAIL statuses to failed and caps video_result at 4', () => {
+ const s = normalizeVideoStatus({ task_status: 'FAIL' }, 'z:x')
+ expect(s.status).toBe('failed')
+ expect(s.progress).toBe(0)
+ const many = normalizeVideoStatus(
+ { task_status: 'SUCCESS', video_result: Array.from({ length: 7 }, (_, i) => ({ url: `u${i}` })) },
+ 'z:y',
+ )
+ expect(many.videos).toHaveLength(4)
+ expect(many.videos.map((v) => v.index)).toEqual([0, 1, 2, 3])
+ })
+
+ it('z-ai error strings ride the error field (200-char cap)', () => {
+ const s = normalizeVideoStatus({ task_status: 'FAIL', error: 'x'.repeat(400) }, 'z:e')
+ expect(s.error).toHaveLength(200)
+ })
})
diff --git a/src/app/api/ai/video/route.ts b/src/app/api/ai/video/route.ts
index 2807845..5273685 100644
--- a/src/app/api/ai/video/route.ts
+++ b/src/app/api/ai/video/route.ts
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
-import { withProvider, resolveSlot, rateLimit, describeProviderError, recordUsage } from '@/lib/ai/provider'
+import { withProvider, resolveSlot, rateLimit, describeProviderError, recordUsage, type ResolvedSlot } from '@/lib/ai/provider'
import { aiFeatureEnabled } from '@/lib/admin/config'
import { withLogging } from '@/lib/observability'
@@ -20,6 +20,40 @@ function videoBase(baseUrl: string): string {
return `${baseUrl.replace(/\/+$/, '')}/videos/generations`
}
+// ── v0.22: the second video dialect ─────────────────────────
+// The z-ai internal API speaks a different (older, GLM/CogVideoX-
+// shaped) contract than the emerging OpenAI Sora-style one:
+// POST `${baseUrl}/video/generation` → { id, task_status }
+// GET `${baseUrl}/async-result?id=…` → { task_status, video_result: [{ url, cover_image_url }] }
+// The finished MP4 sits at a plain CDN url inside video_result — no
+// provider-auth content endpoint, so our same-origin proxy re-polls
+// the async result and streams the CDN url (stateless: the task id is
+// the only server-side memory, exactly like the Sora path).
+//
+// Dialect selection is TRIED AT CREATE TIME (Sora first — back-compat
+// for deployed providers — then z-ai) and remembered statelessly by
+// prefixing the returned task id with "z:": every later poll/content
+// call routes on that prefix. No server memory, no sticky sessions.
+const ZAI_PREFIX = 'z:'
+
+function zaiCreateUrl(baseUrl: string): string {
+ return `${baseUrl.replace(/\/+$/, '')}/video/generation`
+}
+
+function zaiPollUrl(baseUrl: string, id: string): string {
+ return `${baseUrl.replace(/\/+$/, '')}/async-result?id=${encodeURIComponent(id)}`
+}
+
+/** auth headers for a provider call (Bearer + the slot's companions). */
+function providerHeaders(slot: ResolvedSlot, json = false): Record<string, string> {
+ return {
+ Authorization: `Bearer ${slot.apiKey}`,
+ 'X-Z-AI-From': 'Z',
+ ...(json ? { 'Content-Type': 'application/json' } : {}),
+ ...(slot.headers ?? {}),
+ }
+}
+
/** Normalized poll status the client polls expect. */
export interface VideoStatus {
id: string
@@ -30,9 +64,31 @@ export interface VideoStatus {
error?: string
}
-/** Coerce a provider poll reply into VideoStatus (unit-tested shape). */
+/** Coerce a provider poll reply into VideoStatus (unit-tested shape).
+ * Understands BOTH dialects: the Sora-style body (status/progress/
+ * videos) and the z-ai async-result envelope (task_status/
+ * video_result[{url}]). */
export function normalizeVideoStatus(raw: unknown, id: string): VideoStatus {
const body = (raw ?? {}) as Record<string, unknown>
+ // z-ai dialect first: task_status + video_result
+ if (typeof body.task_status === 'string' || Array.isArray(body.video_result)) {
+ const task = String(body.task_status ?? 'PROCESSING').toUpperCase()
+ const status: VideoStatus['status'] =
+ task === 'SUCCESS' ? 'completed' : task === 'FAIL' || task === 'FAILED' ? 'failed' : task === 'QUEUED' ? 'queued' : 'in_progress'
+ const resultRaw = Array.isArray(body.video_result) ? body.video_result : []
+ const videos = resultRaw
+ .slice(0, 4)
+ .map((_, i) => ({ index: i, url: `/api/ai/video?id=${encodeURIComponent(id)}&content=1&index=${i}` }))
+ const errObj = (body.error ?? body.msg) as unknown
+ const error = typeof errObj === 'string' ? errObj.slice(0, 200) : undefined
+ return {
+ id,
+ status,
+ progress: status === 'completed' ? 100 : status === 'failed' ? 0 : 50,
+ videos,
+ ...(error ? { error } : {}),
+ }
+ }
const statusRaw = typeof body.status === 'string' ? body.status : 'in_progress'
const status: VideoStatus['status'] =
statusRaw === 'completed' || statusRaw === 'failed' || statusRaw === 'queued' ? statusRaw : 'in_progress'
@@ -70,11 +126,17 @@ function isFromApp(req: NextRequest): boolean {
* GET /api/ai/video?id=… — poll status ({status, progress, videos[]}).
* GET /api/ai/video?id=…&content=1&index=N — proxy the finished MP4.
*
- * The video slot speaks the emerging OpenAI "Sora-style" async shape
- * (POST /videos/generations → id; GET …/:id → status; GET …/:id/content
- * → bytes) — the shape the VibesAI worker exposes. The SDK has no video
- * API, so this route talks to the resolved slot directly. Kill switch:
- * videoGeneration.
+ * The video slot speaks TWO upstream dialects (v0.22):
+ * 1. the emerging OpenAI "Sora-style" async shape (POST
+ * /videos/generations → id; GET …/:id → status; GET …/:id/content
+ * → bytes) — the shape the VibesAI worker exposes; tried first so
+ * deployed providers keep working unchanged.
+ * 2. the z-ai internal API (POST /video/generation; GET
+ * /async-result?id=… with X-Token companion headers; the MP4 at a
+ * plain CDN url inside video_result) — reached only when the Sora
+ * path 404s, and remembered statelessly by prefixing the task id
+ * with "z:" so polls and the content proxy route correctly.
+ * Kill switch: videoGeneration.
*/
async function __canvix_post(req: NextRequest) {
const body = (await req.json().catch(() => ({}))) as VideoBody
@@ -92,36 +154,67 @@ async function __canvix_post(req: NextRequest) {
// unreachable — withProvider already 503'd — but stay total
return NextResponse.json({ error: 'No video provider configured.' }, { status: 503 })
}
- const r = await fetch(videoBase(slot.baseUrl), {
+
+ // dialect 1 — Sora-style (the deployed shape): POST /videos/generations
+ const sora = await fetch(videoBase(slot.baseUrl), {
method: 'POST',
- headers: {
- Authorization: `Bearer ${slot.apiKey}`,
- 'Content-Type': 'application/json',
- },
+ headers: providerHeaders(slot, true),
body: JSON.stringify({ prompt, size, ...(slot.model ? { model: slot.model } : {}) }),
})
- const text = await r.text()
- let parsed: Record<string, unknown> = {}
+ const soraText = await sora.text()
+ let soraParsed: Record<string, unknown> = {}
try {
- parsed = JSON.parse(text) as Record<string, unknown>
+ soraParsed = JSON.parse(soraText) as Record<string, unknown>
} catch {
/* provider answered non-JSON */
}
- if (!r.ok || typeof parsed.id !== 'string' || !parsed.id) {
- const info = describeProviderError(new Error(`API request failed with status ${r.status}: ${text.slice(0, 200)}`))
+ if (sora.ok && typeof soraParsed.id === 'string' && soraParsed.id) {
+ return NextResponse.json({ id: String(soraParsed.id).slice(0, 128), status: 'queued', progress: 0 })
+ }
+
+ // dialect 2 — the z-ai internal API: POST /video/generation → async task.
+ // Only reached when the Sora path 404s (endpoint absent) — any other
+ // Sora failure (quota, auth, validation) is a REAL error: fall through
+ // to the honest 502 below with the Sora reason, not a dialect guess.
+ if (sora.status === 404) {
+ const zai = await fetch(zaiCreateUrl(slot.baseUrl), {
+ method: 'POST',
+ headers: providerHeaders(slot, true),
+ body: JSON.stringify({ prompt, ...(slot.model ? { model: slot.model } : {}) }),
+ })
+ const zaiText = await zai.text()
+ let zaiParsed: Record<string, unknown> = {}
+ try {
+ zaiParsed = JSON.parse(zaiText) as Record<string, unknown>
+ } catch {
+ /* non-JSON */
+ }
+ if (zai.ok && typeof zaiParsed.id === 'string' && zaiParsed.id) {
+ // the "z:" prefix routes every later poll/content call to this dialect
+ return NextResponse.json({ id: `${ZAI_PREFIX}${String(zaiParsed.id).slice(0, 128)}`, status: 'queued', progress: 0 })
+ }
+ const zaiInfo = describeProviderError(new Error(`API request failed with status ${zai.status}: ${zaiText.slice(0, 200)}`))
return NextResponse.json(
- { error: 'The video service rejected the request.', ...(info.message ? { detail: info.message } : {}) },
+ { error: 'The video service rejected the request.', ...(zaiInfo.message ? { detail: zaiInfo.message } : {}) },
{ status: 502 },
)
}
- return NextResponse.json({ id: String(parsed.id).slice(0, 128), status: 'queued', progress: 0 })
+
+ const info = describeProviderError(new Error(`API request failed with status ${sora.status}: ${soraText.slice(0, 200)}`))
+ return NextResponse.json(
+ { error: 'The video service rejected the request.', ...(info.message ? { detail: info.message } : {}) },
+ { status: 502 },
+ )
})
}
async function __canvix_get(req: NextRequest) {
const url = new URL(req.url)
- const id = (url.searchParams.get('id') ?? '').trim().slice(0, 128)
- if (!id || !/^[A-Za-z0-9_-]+$/.test(id)) {
+ const id = (url.searchParams.get('id') ?? '').trim().slice(0, 130)
+ // strip the dialect prefix — "z:HEXID" routes to the z-ai endpoints
+ const isZai = id.startsWith(ZAI_PREFIX)
+ const taskId = isZai ? id.slice(ZAI_PREFIX.length) : id
+ if (!taskId || !/^[A-Za-z0-9_-]+$/.test(taskId)) {
return NextResponse.json({ error: 'A valid generation id is required.' }, { status: 400 })
}
if (!(await aiFeatureEnabled('videoGeneration'))) {
@@ -139,11 +232,58 @@ async function __canvix_get(req: NextRequest) {
return NextResponse.json({ error: 'No video provider configured.' }, { status: 503 })
}
+ // ── z-ai dialect: one poll endpoint for both status and content ──
+ if (isZai) {
+ const r = await fetch(zaiPollUrl(slot.baseUrl, taskId), { headers: providerHeaders(slot) })
+ const text = await r.text()
+ let parsed: Record<string, unknown> = {}
+ try {
+ parsed = JSON.parse(text) as Record<string, unknown>
+ } catch {
+ /* non-JSON error body */
+ }
+ if (!r.ok) {
+ const info = describeProviderError(new Error(`API request failed with status ${r.status}: ${text.slice(0, 200)}`))
+ void recordUsage('video', slot.label ?? slot.source, false, { status: r.status, error: info.message })
+ return NextResponse.json({ error: 'Polling failed.', ...(info.message ? { detail: info.message } : {}) }, { status: 502 })
+ }
+ // content proxy: re-poll, pick the CDN url, stream it through our origin
+ if (url.searchParams.get('content') === '1') {
+ const index = Math.max(0, Math.round(Number(url.searchParams.get('index')) || 0))
+ const resultRaw = Array.isArray(parsed.video_result) ? parsed.video_result : []
+ const item = (resultRaw[index] ?? resultRaw[0]) as { url?: string } | undefined
+ if (!item?.url) {
+ return NextResponse.json({ error: 'The video is not ready yet.' }, { status: 404 })
+ }
+ const upstream = await fetch(item.url)
+ if (!upstream.ok || !upstream.body) {
+ void recordUsage('video', slot.label ?? slot.source, false, { status: upstream.status })
+ return NextResponse.json({ error: 'The video is not ready yet.' }, { status: 502 })
+ }
+ return new NextResponse(upstream.body, {
+ headers: {
+ 'Content-Type': upstream.headers.get('content-type') ?? 'video/mp4',
+ 'Cache-Control': 'private, max-age=300',
+ 'Content-Disposition': `inline; filename="canvix-video-${taskId}-${index}.mp4"`,
+ },
+ })
+ }
+ // status poll — the "z:" prefix rides along so the client's next
+ // poll (and the video element's src) keeps routing correctly
+ const status = normalizeVideoStatus(parsed, id)
+ void recordUsage('video', slot.label ?? slot.source, status.status === 'failed', {
+ status: r.status,
+ error: status.error,
+ })
+ return NextResponse.json(status)
+ }
+
+ // ── Sora dialect (unchanged) ──
// content proxy: stream the provider's MP4 through our origin
if (url.searchParams.get('content') === '1') {
const index = Math.max(0, Math.round(Number(url.searchParams.get('index')) || 0))
- const upstream = await fetch(`${videoBase(slot.baseUrl)}/${id}/content?index=${index}`, {
- headers: { Authorization: `Bearer ${slot.apiKey}` },
+ const upstream = await fetch(`${videoBase(slot.baseUrl)}/${taskId}/content?index=${index}`, {
+ headers: providerHeaders(slot),
})
if (!upstream.ok || !upstream.body) {
void recordUsage('video', slot.label ?? slot.source, false, { status: upstream.status })
@@ -153,14 +293,14 @@ async function __canvix_get(req: NextRequest) {
headers: {
'Content-Type': upstream.headers.get('content-type') ?? 'video/mp4',
'Cache-Control': 'private, max-age=300',
- 'Content-Disposition': `inline; filename="canvix-video-${id}-${index}.mp4"`,
+ 'Content-Disposition': `inline; filename="canvix-video-${taskId}-${index}.mp4"`,
},
})
}
// status poll
- const r = await fetch(`${videoBase(slot.baseUrl)}/${id}`, {
- headers: { Authorization: `Bearer ${slot.apiKey}` },
+ const r = await fetch(`${videoBase(slot.baseUrl)}/${taskId}`, {
+ headers: providerHeaders(slot),
})
const text = await r.text()
let parsed: unknown = {}
diff --git a/src/lib/admin/config.ts b/src/lib/admin/config.ts
index 1a1d58c..86d9228 100644
--- a/src/lib/admin/config.ts
+++ b/src/lib/admin/config.ts
@@ -80,6 +80,10 @@ export type AiSlot = (typeof AI_SLOTS)[number]
export interface StoredProvider {
baseUrl: string
apiKey: string
+ /** v0.22: optional companion auth headers (the z-ai internal API's
+ * X-Token / X-User-Id / X-Chat-Id) — populated by the file/env
+ * resolution layers, ignored by the DB-backed layers. */
+ headers?: Record<string, string>
}
export interface StoredModels {
text?: string
diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.ts
index 02fad81..0e5c8f1 100644
--- a/src/lib/ai/provider.ts
+++ b/src/lib/ai/provider.ts
@@ -40,6 +40,10 @@ export type AICapability =
export interface AIProviderConfig {
baseUrl: string
apiKey: string
+ /** v0.22: extra auth headers the provider's API demands beyond the
+ * Bearer key (the z-ai internal API's X-Token / X-User-Id /
+ * X-Chat-Id, read from the same config layers). Absent = none. */
+ headers?: Record<string, string>
}
/** Default multimodal model for Magic Layers analysis (v0.16 A1: overridable from /admin). */
@@ -70,7 +74,20 @@ export async function getImageModel(): Promise<string | undefined> {
export function resolveProviderConfig(): AIProviderConfig | null {
const envUrl = process.env.ZAI_BASE_URL?.trim()
const envKey = process.env.ZAI_API_KEY?.trim()
- if (envUrl && envKey) return { baseUrl: envUrl, apiKey: envKey }
+ if (envUrl && envKey) {
+ // v0.22: the internal API's companion headers ride the same env
+ // layer — ZAI_TOKEN / ZAI_USER_ID / ZAI_CHAT_ID (all optional)
+ const headers = providerHeadersFrom({
+ token: process.env.ZAI_TOKEN,
+ userId: process.env.ZAI_USER_ID,
+ chatId: process.env.ZAI_CHAT_ID,
+ })
+ return {
+ baseUrl: envUrl,
+ apiKey: envKey,
+ ...(headers ? { headers } : {}),
+ }
+ }
try {
// the SDK resolves the config file itself; mirror its lookup here
//
@@ -93,8 +110,21 @@ export function resolveProviderConfig(): AIProviderConfig | null {
// configuration is env vars (ZAI_BASE_URL / ZAI_API_KEY); the file
// fallback is a local-development convenience only.
if (!p || !existsSync(/*turbopackIgnore: true*/ p)) continue
- const raw = JSON.parse(readFileSync(/*turbopackIgnore: true*/ p, 'utf8')) as { baseUrl?: string; apiKey?: string }
- if (raw.baseUrl && raw.apiKey) return { baseUrl: raw.baseUrl, apiKey: raw.apiKey }
+ const raw = JSON.parse(readFileSync(/*turbopackIgnore: true*/ p, 'utf8')) as {
+ baseUrl?: string
+ apiKey?: string
+ token?: string
+ userId?: string
+ chatId?: string
+ }
+ if (raw.baseUrl && raw.apiKey) {
+ const headers = providerHeadersFrom(raw)
+ return {
+ baseUrl: raw.baseUrl,
+ apiKey: raw.apiKey,
+ ...(headers ? { headers } : {}),
+ }
+ }
}
} catch {
/* unreadable config — treat as absent */
@@ -102,6 +132,15 @@ export function resolveProviderConfig(): AIProviderConfig | null {
return null
}
+/** The companion headers the z-ai internal API expects (all optional). */
+function providerHeadersFrom(cfg: { token?: string; userId?: string; chatId?: string }): Record<string, string> | undefined {
+ const headers: Record<string, string> = {}
+ if (cfg.token?.trim()) headers['X-Token'] = cfg.token.trim()
+ if (cfg.userId?.trim()) headers['X-User-Id'] = cfg.userId.trim()
+ if (cfg.chatId?.trim()) headers['X-Chat-Id'] = cfg.chatId.trim()
+ return Object.keys(headers).length ? headers : undefined
+}
+
// ── per-slot resolution (v0.16.2 A2) ─────────────────────────
export type SlotSource = 'multi' | 'db' | 'env' | 'file'
@@ -117,6 +156,10 @@ export interface ResolvedSlot {
/** Human label of the answering provider (multi only). */
label?: string
source: SlotSource
+ /** v0.22: companion auth headers (the z-ai internal API's
+ * X-Token / X-User-Id / X-Chat-Id) — env/file layers only; the
+ * multi-provider table and legacy DB override stay key-only. */
+ headers?: Record<string, string>
}
/**
@@ -129,7 +172,7 @@ export function pickSlot(
multi: StoredProviders | null,
legacy: StoredProvider | null,
models: StoredModels,
- env: { baseUrl?: string; apiKey?: string },
+ env: { baseUrl?: string; apiKey?: string; headers?: Record<string, string> },
file: StoredProvider | null
): ResolvedSlot | null {
const tableSlot = multi?.slots[slot]
@@ -154,23 +197,33 @@ export function pickSlot(
slot === 'text' ? models.text : slot === 'vision' ? models.vision : slot === 'image' ? models.image : undefined
if (legacy) return { baseUrl: legacy.baseUrl, apiKey: legacy.apiKey, model: legacyModel, source: 'db' }
if (env.baseUrl && env.apiKey) {
- return { baseUrl: env.baseUrl, apiKey: env.apiKey, model: legacyModel, source: 'env' }
+ return {
+ baseUrl: env.baseUrl,
+ apiKey: env.apiKey,
+ model: legacyModel,
+ source: 'env',
+ ...(env.headers ? { headers: env.headers } : {}),
+ }
}
- if (file) return { baseUrl: file.baseUrl, apiKey: file.apiKey, model: legacyModel, source: 'file' }
+ if (file) return { baseUrl: file.baseUrl, apiKey: file.apiKey, model: legacyModel, source: 'file', ...(file.headers ? { headers: file.headers } : {}) }
return null
}
/** Resolve one capability slot through every config layer. */
export async function resolveSlot(slot: AiSlot): Promise<ResolvedSlot | null> {
const [multi, legacy, models] = await Promise.all([getProviders(), getProviderOverride(), getModels()])
- return pickSlot(
- slot,
- multi,
- legacy,
- models,
- { baseUrl: process.env.ZAI_BASE_URL?.trim(), apiKey: process.env.ZAI_API_KEY?.trim() },
- resolveProviderConfig()
- )
+ const envLayer: { baseUrl?: string; apiKey?: string; headers?: Record<string, string> } = {
+ baseUrl: process.env.ZAI_BASE_URL?.trim(),
+ apiKey: process.env.ZAI_API_KEY?.trim(),
+ }
+ // v0.22: companion headers ride the env layer (ZAI_TOKEN / ZAI_USER_ID / ZAI_CHAT_ID)
+ const envHeaders = providerHeadersFrom({
+ token: process.env.ZAI_TOKEN,
+ userId: process.env.ZAI_USER_ID,
+ chatId: process.env.ZAI_CHAT_ID,
+ })
+ if (envHeaders) envLayer.headers = envHeaders
+ return pickSlot(slot, multi, legacy, models, envLayer, resolveProviderConfig())
}
/** Feature name (withProvider's first arg) → capability slot. */