@apicity/zaicoding 0.6.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Justin Tanner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,104 @@
1
+ # @apicity/zaicoding
2
+
3
+ [![npm](https://img.shields.io/npm/v/@apicity/zaicoding?color=cb0000)](https://www.npmjs.com/package/@apicity/zaicoding)
4
+ [![dependencies](https://img.shields.io/badge/dependencies-1-blue)](package.json)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-strict-blue?logo=typescript&logoColor=white)](tsconfig.json)
6
+
7
+ Z.ai GLM Coding Plan provider for Apicity — OpenAI-compatible chat completions plus coding-plan usage and quota monitoring.
8
+
9
+ Runtime dependencies:
10
+
11
+ - `zod@^4.4.3` — request schemas attached to every POST endpoint as `.schema`
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @apicity/zaicoding
17
+ # or
18
+ pnpm add @apicity/zaicoding
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ ```typescript
24
+ import { createZaiCoding } from "@apicity/zaicoding";
25
+
26
+ const zaicoding = createZaiCoding({
27
+ apiKey: process.env.ZAI_CODING_PLAN_API_KEY!,
28
+ });
29
+ ```
30
+
31
+ ## API Reference
32
+
33
+ 4 endpoints across 2 groups. Each method mirrors an upstream URL path.
34
+
35
+ ### post
36
+
37
+ <details>
38
+ <summary><code>POST</code> <b><code>zaicoding.post.api.coding.paas.v4.chat.completions</code></b></summary>
39
+
40
+ <code>POST https://api.z.ai/api/coding/paas/v4/chat/completions</code>
41
+
42
+ [Upstream docs ↗](https://docs.z.ai/api-reference/llm/chat-completion)
43
+
44
+ ```typescript
45
+ const res = await zaicoding.post.api.coding.paas.v4.chat.completions({
46
+ model: "glm-4-flash",
47
+ messages: [{ role: "user", content: "Say hello." }],
48
+ });
49
+ console.log(res.choices[0].message.content);
50
+ ```
51
+
52
+ Source: [`packages/provider/zaicoding/src/zaicoding.ts`](src/zaicoding.ts)
53
+
54
+ </details>
55
+
56
+ ### get
57
+
58
+ <details>
59
+ <summary><code>GET</code> <b><code>zaicoding.get.api.monitor.usage.quota.limit</code></b></summary>
60
+
61
+ <code>GET https://api.z.ai/api/monitor/usage/quota/limit</code>
62
+
63
+ [Upstream docs ↗](https://docs.z.ai/api-reference/introduction)
64
+
65
+ ```typescript
66
+ const res = await zaicoding.get.api.monitor.usage.quota.limit();
67
+ console.log(res.data?.level, res.data?.limits);
68
+ ```
69
+
70
+ Source: [`packages/provider/zaicoding/src/zaicoding.ts`](src/zaicoding.ts)
71
+
72
+ </details>
73
+
74
+ <details>
75
+ <summary><code>GET</code> <b><code>zaicoding.get.api.monitor.usage.modelUsage</code></b></summary>
76
+
77
+ <code>GET https://api.z.ai/api/monitor/usage/model-usage</code>
78
+
79
+ [Upstream docs ↗](https://docs.z.ai/api-reference/introduction)
80
+
81
+ ```typescript
82
+ const res = await zaicoding.get.api.monitor.usage.modelUsage();
83
+ console.log(res.data?.totalUsage);
84
+ ```
85
+
86
+ Source: [`packages/provider/zaicoding/src/zaicoding.ts`](src/zaicoding.ts)
87
+
88
+ </details>
89
+
90
+ <details>
91
+ <summary><code>GET</code> <b><code>zaicoding.get.api.monitor.usage.toolUsage</code></b></summary>
92
+
93
+ <code>GET https://api.z.ai/api/monitor/usage/tool-usage</code>
94
+
95
+ [Upstream docs ↗](https://docs.z.ai/api-reference/introduction)
96
+
97
+ ```typescript
98
+ const res = await zaicoding.get.api.monitor.usage.toolUsage();
99
+ console.log(res.data?.totalUsage);
100
+ ```
101
+
102
+ Source: [`packages/provider/zaicoding/src/zaicoding.ts`](src/zaicoding.ts)
103
+
104
+ </details>
@@ -0,0 +1,8 @@
1
+ export interface EndpointExample {
2
+ source: string;
3
+ payload: unknown;
4
+ }
5
+ declare const EXAMPLES: Record<string, EndpointExample>;
6
+ export default EXAMPLES;
7
+ export declare function attachExamples<T>(provider: T): T;
8
+ //# sourceMappingURL=example.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"example.d.ts","sourceRoot":"","sources":["../../src/example.ts"],"names":[],"mappings":"AAOA,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,QAAA,MAAM,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAa7C,CAAC;AAEF,eAAe,QAAQ,CAAC;AAOxB,wBAAgB,cAAc,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,CAAC,CA6ChD"}
@@ -0,0 +1,98 @@
1
+ // Auto-generated by `pnpm run gen:examples` — do not edit by hand.
2
+ // Source: tests/recordings/<provider>_*/<test>_*/recording.har
3
+ //
4
+ // Each entry is the green-path payload for one endpoint, mined from a real
5
+ // integration-test recording. `attachExamples` walks the provider tree and
6
+ // hangs the matching entry off each endpoint function as `.example`.
7
+ const EXAMPLES = {
8
+ "POST api.coding.paas.v4.chat.completions": {
9
+ "source": "zaicoding/chat-completions",
10
+ "payload": {
11
+ "model": "glm-4-flash",
12
+ "messages": [
13
+ {
14
+ "role": "user",
15
+ "content": "Say hello."
16
+ }
17
+ ]
18
+ }
19
+ }
20
+ };
21
+ export default EXAMPLES;
22
+ // Walks each "<METHOD> <dotPath>" key onto the provider's tree. Tries the
23
+ // standard `provider.<method>.<dotPath>` shape first, then a few fallbacks
24
+ // to cover providers with non-standard layouts (fal's `.run.` namespace,
25
+ // kie's sub-providers, `free`'s flat root). Returns the same provider for
26
+ // drop-in use as `return attachExamples({ ... });`.
27
+ export function attachExamples(provider) {
28
+ const root = provider;
29
+ const HTTP_KEYS = new Set(["post", "get", "put", "delete", "patch", "head"]);
30
+ for (const [key, example] of Object.entries(EXAMPLES)) {
31
+ const sp = key.indexOf(" ");
32
+ if (sp < 0)
33
+ continue;
34
+ const method = key.slice(0, sp).toLowerCase();
35
+ const segs = key.slice(sp + 1).split(".");
36
+ const candidates = [
37
+ root[method],
38
+ root[method]?.run,
39
+ root,
40
+ ];
41
+ if (segs.length > 1) {
42
+ const sub = root[segs[0]];
43
+ if (sub && typeof sub === "object") {
44
+ const subMethod = sub[method];
45
+ if (subMethod)
46
+ candidates.push({ __nested: subMethod, __segs: segs.slice(1) });
47
+ }
48
+ }
49
+ let attached = false;
50
+ for (const c of candidates) {
51
+ const fn = walkToFn(c, segs);
52
+ if (fn) {
53
+ Object.assign(fn, { example });
54
+ attached = true;
55
+ break;
56
+ }
57
+ }
58
+ if (attached)
59
+ continue;
60
+ for (const k of Object.keys(root)) {
61
+ if (HTTP_KEYS.has(k))
62
+ continue;
63
+ if (!segs.includes(k))
64
+ continue;
65
+ const sub = root[k];
66
+ if (!sub || typeof sub !== "object")
67
+ continue;
68
+ const subMethod = sub[method];
69
+ if (!subMethod)
70
+ continue;
71
+ const fn = walkToFn(subMethod, segs);
72
+ if (fn) {
73
+ Object.assign(fn, { example });
74
+ break;
75
+ }
76
+ }
77
+ }
78
+ return provider;
79
+ }
80
+ function walkToFn(start, segs) {
81
+ if (start && typeof start === "object" && "__nested" in start) {
82
+ const wrapper = start;
83
+ return walkToFn(wrapper.__nested, wrapper.__segs);
84
+ }
85
+ let cur = start;
86
+ for (const seg of segs) {
87
+ if (cur === null || cur === undefined)
88
+ return null;
89
+ const t = typeof cur;
90
+ if (t !== "object" && t !== "function")
91
+ return null;
92
+ cur = cur[seg];
93
+ }
94
+ return typeof cur === "function"
95
+ ? cur
96
+ : null;
97
+ }
98
+ //# sourceMappingURL=example.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"example.js","sourceRoot":"","sources":["../../src/example.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,+DAA+D;AAC/D,EAAE;AACF,2EAA2E;AAC3E,2EAA2E;AAC3E,qEAAqE;AAOrE,MAAM,QAAQ,GAAoC;IAChD,0CAA0C,EAAE;QAC1C,QAAQ,EAAE,4BAA4B;QACtC,SAAS,EAAE;YACT,OAAO,EAAE,aAAa;YACtB,UAAU,EAAE;gBACV;oBACE,MAAM,EAAE,MAAM;oBACd,SAAS,EAAE,YAAY;iBACxB;aACF;SACF;KACF;CACF,CAAC;AAEF,eAAe,QAAQ,CAAC;AAExB,0EAA0E;AAC1E,2EAA2E;AAC3E,yEAAyE;AACzE,0EAA0E;AAC1E,oDAAoD;AACpD,MAAM,UAAU,cAAc,CAAI,QAAW;IAC3C,MAAM,IAAI,GAAG,QAAmC,CAAC;IACjD,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;IAC7E,KAAK,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;QACtD,MAAM,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CAAC;IAC9C,CAAC;IACD,OAAO,OAAO,GAAG,KAAK,UAAU;QAC9B,CAAC,CAAE,GAAuC;QAC1C,CAAC,CAAC,IAAI,CAAC;AACX,CAAC"}
@@ -0,0 +1,6 @@
1
+ export { createZaiCoding } from "./zaicoding.js";
2
+ export { ZaiCodingError } from "./types.js";
3
+ export { withRetry, withFallback, withRateLimit, createRateLimiter, ZAICODING_RATE_LIMITS, } from "./middleware.js";
4
+ export type { RetryOptions, FallbackOptions, RateLimiterOptions, RateLimiter, RateLimitOptions, } from "./middleware.js";
5
+ export type { ZaiCodingOptions, ZaiCodingCallOptions, ZaiCodingMessage, ZaiCodingChatRequest, ZaiCodingChatChoice, ZaiCodingChatResponse, ZaiCodingProvider, ZaiCodingPostEndpoint, ZaiCodingGetEndpoint, ZaiCodingEnvelope, ZaiCodingQuotaLimitItem, ZaiCodingQuotaLimitData, ZaiCodingQuotaLimitResponse, ZaiCodingModelUsageData, ZaiCodingModelUsageResponse, ZaiCodingToolUsageData, ZaiCodingToolUsageResponse, } from "./types.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,OAAO,EACL,SAAS,EACT,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,cAAc,CAAC;AAEtB,YAAY,EACV,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,WAAW,EACX,gBAAgB,GACjB,MAAM,cAAc,CAAC;AAEtB,YAAY,EACV,gBAAgB,EAChB,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,EACpB,mBAAmB,EACnB,qBAAqB,EACrB,iBAAiB,EACjB,qBAAqB,EACrB,oBAAoB,EACpB,iBAAiB,EACjB,uBAAuB,EACvB,uBAAuB,EACvB,2BAA2B,EAC3B,uBAAuB,EACvB,2BAA2B,EAC3B,sBAAsB,EACtB,0BAA0B,GAC3B,MAAM,SAAS,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { createZaiCoding } from "./zaicoding.js";
2
+ export { ZaiCodingError } from "./types.js";
3
+ export { withRetry, withFallback, withRateLimit, createRateLimiter, ZAICODING_RATE_LIMITS, } from "./middleware.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,OAAO,EACL,SAAS,EACT,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,cAAc,CAAC"}
@@ -0,0 +1,56 @@
1
+ export interface RetryOptions {
2
+ retries?: number;
3
+ baseMs?: number;
4
+ factor?: number;
5
+ jitter?: boolean;
6
+ }
7
+ export interface FallbackOptions {
8
+ onFallback?: (error: unknown, index: number) => void;
9
+ }
10
+ export declare function withRetry<TReq, TRes>(fn: (req: TReq, signal?: AbortSignal) => Promise<TRes>, opts?: RetryOptions): (req: TReq, signal?: AbortSignal) => Promise<TRes>;
11
+ export declare function withFallback<TReq, TRes>(fns: Array<(req: TReq, signal?: AbortSignal) => Promise<TRes>>, opts?: FallbackOptions): (req: TReq, signal?: AbortSignal) => Promise<TRes>;
12
+ export interface RateLimiterOptions {
13
+ /** Maximum requests per minute (sliding window). Default: Infinity */
14
+ rpm?: number;
15
+ /** Maximum concurrent in-flight requests. Default: Infinity */
16
+ concurrent?: number;
17
+ /** Maximum time (ms) a request will wait in queue. Default: 60000 */
18
+ maxQueueMs?: number;
19
+ }
20
+ export interface RateLimiter {
21
+ /** Current number of in-flight requests */
22
+ readonly active: number;
23
+ /** Current number of queued requests waiting for a slot */
24
+ readonly queued: number;
25
+ /** Reject all queued requests and clean up timers */
26
+ dispose(): void;
27
+ }
28
+ export interface RateLimitOptions {
29
+ /** Override maxQueueMs for this particular wrapped function */
30
+ maxQueueMs?: number;
31
+ }
32
+ export declare function createRateLimiter(opts?: RateLimiterOptions): RateLimiter;
33
+ export declare function withRateLimit<TReq, TRes>(fn: (req: TReq, signal?: AbortSignal) => Promise<TRes>, limiter: RateLimiter, opts?: RateLimitOptions): (req: TReq, signal?: AbortSignal) => Promise<TRes>;
34
+ export declare const ZAICODING_RATE_LIMITS: {
35
+ readonly free: {
36
+ readonly rpm: 5;
37
+ readonly concurrent: 2;
38
+ };
39
+ readonly tier1: {
40
+ readonly rpm: 60;
41
+ readonly concurrent: 10;
42
+ };
43
+ readonly tier2: {
44
+ readonly rpm: 200;
45
+ readonly concurrent: 25;
46
+ };
47
+ readonly tier3: {
48
+ readonly rpm: 500;
49
+ readonly concurrent: 50;
50
+ };
51
+ readonly tier4: {
52
+ readonly rpm: 1000;
53
+ readonly concurrent: 100;
54
+ };
55
+ };
56
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/middleware.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,eAAe;IAC9B,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;CACtD;AA+BD,wBAAgB,SAAS,CAAC,IAAI,EAAE,IAAI,EAClC,EAAE,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,EACtD,IAAI,GAA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MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;CAMqB,CAAC"}
@@ -0,0 +1,226 @@
1
+ function isTransientError(e) {
2
+ const status = (typeof e === "object" &&
3
+ e !== null &&
4
+ "status" in e &&
5
+ typeof e.status === "number" &&
6
+ e.status) ||
7
+ (typeof e === "object" &&
8
+ e !== null &&
9
+ "statusCode" in e &&
10
+ typeof e.statusCode === "number" &&
11
+ e.statusCode) ||
12
+ (typeof e === "object" &&
13
+ e !== null &&
14
+ "code" in e &&
15
+ typeof e.code === "number" &&
16
+ e.code) ||
17
+ null;
18
+ if (typeof status === "number") {
19
+ return status === 429 || status >= 500;
20
+ }
21
+ return true;
22
+ }
23
+ function sleep(ms) {
24
+ return new Promise((resolve) => setTimeout(resolve, ms));
25
+ }
26
+ export function withRetry(fn, opts = {}) {
27
+ const retries = opts.retries ?? 2;
28
+ const baseMs = opts.baseMs ?? 300;
29
+ const factor = opts.factor ?? 2;
30
+ const jitter = opts.jitter ?? true;
31
+ return async (req, signal) => {
32
+ let attempt = 0;
33
+ while (true) {
34
+ try {
35
+ return await fn(req, signal);
36
+ }
37
+ catch (e) {
38
+ attempt += 1;
39
+ if (attempt > retries || !isTransientError(e) || signal?.aborted) {
40
+ throw e;
41
+ }
42
+ const delay = baseMs * Math.pow(factor, attempt - 1);
43
+ const wait = jitter
44
+ ? Math.floor(delay * (0.8 + Math.random() * 0.4))
45
+ : delay;
46
+ await sleep(wait);
47
+ }
48
+ }
49
+ };
50
+ }
51
+ export function withFallback(fns, opts = {}) {
52
+ if (fns.length === 0) {
53
+ throw new Error("withFallback requires at least one function");
54
+ }
55
+ return async (req, signal) => {
56
+ let lastError;
57
+ for (let i = 0; i < fns.length; i++) {
58
+ try {
59
+ return await fns[i](req, signal);
60
+ }
61
+ catch (e) {
62
+ lastError = e;
63
+ opts.onFallback?.(e, i);
64
+ }
65
+ }
66
+ throw lastError;
67
+ };
68
+ }
69
+ function pruneTimestamps(state, now) {
70
+ const cutoff = now - 60_000;
71
+ while (state.timestamps.length > 0 && state.timestamps[0] <= cutoff) {
72
+ state.timestamps.shift();
73
+ }
74
+ }
75
+ function tryDrain(state) {
76
+ const now = Date.now();
77
+ pruneTimestamps(state, now);
78
+ while (state.queue.length > 0) {
79
+ if (state.timestamps.length >= state.rpm)
80
+ break;
81
+ if (state.activeCount >= state.concurrent)
82
+ break;
83
+ const entry = state.queue.shift();
84
+ clearTimeout(entry.timeoutId);
85
+ if (entry.signal && entry.abortHandler) {
86
+ entry.signal.removeEventListener("abort", entry.abortHandler);
87
+ }
88
+ state.timestamps.push(now);
89
+ state.activeCount++;
90
+ entry.resolve();
91
+ }
92
+ if (state.drainTimerId !== null) {
93
+ clearTimeout(state.drainTimerId);
94
+ state.drainTimerId = null;
95
+ }
96
+ if (state.queue.length > 0 &&
97
+ state.timestamps.length >= state.rpm &&
98
+ state.timestamps.length > 0) {
99
+ const oldestExpiry = state.timestamps[0] + 60_000;
100
+ const delay = Math.max(1, oldestExpiry - now);
101
+ state.drainTimerId = setTimeout(() => {
102
+ state.drainTimerId = null;
103
+ tryDrain(state);
104
+ }, delay);
105
+ }
106
+ }
107
+ export function createRateLimiter(opts = {}) {
108
+ const state = {
109
+ rpm: opts.rpm ?? Infinity,
110
+ concurrent: opts.concurrent ?? Infinity,
111
+ maxQueueMs: opts.maxQueueMs ?? 60_000,
112
+ timestamps: [],
113
+ activeCount: 0,
114
+ queue: [],
115
+ drainTimerId: null,
116
+ disposed: false,
117
+ };
118
+ function acquire(signal, maxQueueMs) {
119
+ if (state.disposed) {
120
+ return Promise.reject(new Error("RateLimiter is disposed"));
121
+ }
122
+ const now = Date.now();
123
+ pruneTimestamps(state, now);
124
+ if (state.timestamps.length < state.rpm &&
125
+ state.activeCount < state.concurrent) {
126
+ state.timestamps.push(now);
127
+ state.activeCount++;
128
+ return Promise.resolve();
129
+ }
130
+ if (signal?.aborted) {
131
+ return Promise.reject(new DOMException("Rate limit queue aborted", "AbortError"));
132
+ }
133
+ const queueTimeout = maxQueueMs ?? state.maxQueueMs;
134
+ return new Promise((resolve, reject) => {
135
+ const entry = {
136
+ resolve,
137
+ reject,
138
+ timeoutId: setTimeout(() => {
139
+ const idx = state.queue.indexOf(entry);
140
+ if (idx !== -1) {
141
+ state.queue.splice(idx, 1);
142
+ if (entry.signal && entry.abortHandler) {
143
+ entry.signal.removeEventListener("abort", entry.abortHandler);
144
+ }
145
+ reject(new Error(`Rate limit queue timeout after ${queueTimeout}ms`));
146
+ }
147
+ }, queueTimeout),
148
+ abortHandler: null,
149
+ signal,
150
+ };
151
+ if (signal) {
152
+ const abortHandler = () => {
153
+ const idx = state.queue.indexOf(entry);
154
+ if (idx !== -1) {
155
+ state.queue.splice(idx, 1);
156
+ clearTimeout(entry.timeoutId);
157
+ reject(new DOMException("Rate limit queue aborted", "AbortError"));
158
+ }
159
+ };
160
+ signal.addEventListener("abort", abortHandler, { once: true });
161
+ entry.abortHandler = abortHandler;
162
+ }
163
+ state.queue.push(entry);
164
+ if (state.timestamps.length >= state.rpm && state.timestamps.length > 0) {
165
+ if (state.drainTimerId === null) {
166
+ const oldestExpiry = state.timestamps[0] + 60_000;
167
+ const delay = Math.max(1, oldestExpiry - now);
168
+ state.drainTimerId = setTimeout(() => {
169
+ state.drainTimerId = null;
170
+ tryDrain(state);
171
+ }, delay);
172
+ }
173
+ }
174
+ });
175
+ }
176
+ function release() {
177
+ state.activeCount--;
178
+ tryDrain(state);
179
+ }
180
+ const limiter = {
181
+ get active() {
182
+ return state.activeCount;
183
+ },
184
+ get queued() {
185
+ return state.queue.length;
186
+ },
187
+ dispose() {
188
+ state.disposed = true;
189
+ if (state.drainTimerId !== null) {
190
+ clearTimeout(state.drainTimerId);
191
+ state.drainTimerId = null;
192
+ }
193
+ for (const entry of state.queue) {
194
+ clearTimeout(entry.timeoutId);
195
+ if (entry.signal && entry.abortHandler) {
196
+ entry.signal.removeEventListener("abort", entry.abortHandler);
197
+ }
198
+ entry.reject(new Error("RateLimiter disposed"));
199
+ }
200
+ state.queue.length = 0;
201
+ },
202
+ _acquire: acquire,
203
+ _release: release,
204
+ };
205
+ return limiter;
206
+ }
207
+ export function withRateLimit(fn, limiter, opts = {}) {
208
+ const internal = limiter;
209
+ return async (req, signal) => {
210
+ await internal._acquire(signal, opts.maxQueueMs);
211
+ try {
212
+ return await fn(req, signal);
213
+ }
214
+ finally {
215
+ internal._release();
216
+ }
217
+ };
218
+ }
219
+ export const ZAICODING_RATE_LIMITS = {
220
+ free: { rpm: 5, concurrent: 2 },
221
+ tier1: { rpm: 60, concurrent: 10 },
222
+ tier2: { rpm: 200, concurrent: 25 },
223
+ tier3: { rpm: 500, concurrent: 50 },
224
+ tier4: { rpm: 1000, concurrent: 100 },
225
+ };
226
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/middleware.ts"],"names":[],"mappings":"AAWA,SAAS,gBAAgB,CAAC,CAAU;IAClC,MAAM,MAAM,GACV,CAAC,OAAO,CAAC,KAAK,QAAQ;QACpB,CAAC,KAAK,IAAI;QACV,QAAQ,IAAI,CAAC;QACb,OAAQ,CAA0B,CAAC,MAAM,KAAK,QAAQ;QACrD,CAAwB,CAAC,MAAM,CAAC;QACnC,CAAC,OAAO,CAAC,KAAK,QAAQ;YACpB,CAAC,KAAK,IAAI;YACV,YAAY,IAAI,CAAC;YACjB,OAAQ,CAA8B,CAAC,UAAU,KAAK,QAAQ;YAC7D,CAA4B,CAAC,UAAU,CAAC;QAC3C,CAAC,OAAO,CAAC,KAAK,QAAQ;YACpB,CAAC,KAAK,IAAI;YACV,MAAM,IAAI,CAAC;YACX,OAAQ,CAAwB,CAAC,IAAI,KAAK,QAAQ;YACjD,CAAsB,CAAC,IAAI,CAAC;QAC/B,IAAI,CAAC;IAEP,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC/B,OAAO,MAAM,KAAK,GAAG,IAAI,MAAM,IAAI,GAAG,CAAC;IACzC,CAA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export declare class ZaiCodingError extends Error {
2
+ readonly status?: number | undefined;
3
+ readonly body?: unknown | undefined;
4
+ constructor(message: string, status?: number | undefined, body?: unknown | undefined);
5
+ }
6
+ export interface ZaiCodingOptions {
7
+ /** Z.ai GLM Coding Plan API key. Falls back to `process.env.ZAI_CODING_PLAN_API_KEY`. */
8
+ apiKey?: string;
9
+ /** Override the API origin. Defaults to `https://api.z.ai`. */
10
+ baseUrl?: string;
11
+ }
12
+ export interface ZaiCodingMessage {
13
+ role: "system" | "user" | "assistant";
14
+ content: string;
15
+ }
16
+ export interface ZaiCodingChatRequest {
17
+ /** GLM model id, e.g. "glm-4.6" or "glm-4.5-air". */
18
+ model: string;
19
+ messages: ZaiCodingMessage[];
20
+ temperature?: number;
21
+ max_tokens?: number;
22
+ stream?: boolean;
23
+ }
24
+ export interface ZaiCodingChatChoice {
25
+ index: number;
26
+ message: ZaiCodingMessage;
27
+ finish_reason: string;
28
+ }
29
+ export interface ZaiCodingChatResponse {
30
+ id: string;
31
+ object: string;
32
+ created: number;
33
+ model: string;
34
+ choices: ZaiCodingChatChoice[];
35
+ usage?: {
36
+ prompt_tokens: number;
37
+ completion_tokens: number;
38
+ total_tokens: number;
39
+ };
40
+ }
41
+ /** A single quota line item (a token budget, a time window, etc.). */
42
+ export interface ZaiCodingQuotaLimitItem {
43
+ /** Limit type discriminator, e.g. "TOKENS_LIMIT" or "TIME_LIMIT". */
44
+ type?: string;
45
+ /**
46
+ * Unit code for the limit's window, paired with `number` to describe the
47
+ * span (e.g. the rolling 5h window and the weekly 1w window). The live API
48
+ * returns a numeric code; older/string responses are tolerated.
49
+ */
50
+ unit?: number | string;
51
+ /** The window length in `unit`s (e.g. 5 for the 5h window, 1 for the 1w). */
52
+ number?: number;
53
+ /** Consumed fraction of the limit, 0–100. */
54
+ percentage?: number;
55
+ /** Amount consumed so far in `unit`s. */
56
+ currentValue?: number;
57
+ /** Alias some responses use for the consumed amount. */
58
+ usage?: number;
59
+ /** Optional per-source breakdown of usage. */
60
+ usageDetails?: unknown;
61
+ /** Epoch-ms (or ISO string) when this limit resets. */
62
+ nextResetTime?: number | string;
63
+ }
64
+ export interface ZaiCodingQuotaLimitData {
65
+ /** Plan tier, e.g. "Lite" / "Pro" / "Max". */
66
+ level?: string;
67
+ limits?: ZaiCodingQuotaLimitItem[];
68
+ }
69
+ /** Response envelope shared by the monitor endpoints. */
70
+ export interface ZaiCodingEnvelope<T> {
71
+ code?: number;
72
+ msg?: string;
73
+ success?: boolean;
74
+ data?: T;
75
+ }
76
+ export type ZaiCodingQuotaLimitResponse = ZaiCodingEnvelope<ZaiCodingQuotaLimitData>;
77
+ export interface ZaiCodingModelUsageData {
78
+ totalUsage?: {
79
+ totalTokensUsage?: number;
80
+ totalModelCallCount?: number;
81
+ };
82
+ /** Optional per-model rows; left loose since the shape varies by plan. */
83
+ modelUsageList?: unknown[];
84
+ }
85
+ export type ZaiCodingModelUsageResponse = ZaiCodingEnvelope<ZaiCodingModelUsageData>;
86
+ export interface ZaiCodingToolUsageData {
87
+ totalUsage?: {
88
+ totalNetworkSearchCount?: number;
89
+ totalWebReadMcpCount?: number;
90
+ totalZreadMcpCount?: number;
91
+ };
92
+ toolUsageList?: unknown[];
93
+ }
94
+ export type ZaiCodingToolUsageResponse = ZaiCodingEnvelope<ZaiCodingToolUsageData>;
95
+ export interface ZaiCodingCallOptions {
96
+ signal?: AbortSignal;
97
+ }
98
+ /** A POST endpoint leaf: callable, with an attached zod `schema`. */
99
+ export type ZaiCodingPostEndpoint<Req, Res> = ((params: Req, options?: ZaiCodingCallOptions) => Promise<Res>) & {
100
+ schema: unknown;
101
+ example?: unknown;
102
+ };
103
+ /** A GET endpoint leaf: callable with no body. */
104
+ export type ZaiCodingGetEndpoint<Res> = ((options?: ZaiCodingCallOptions) => Promise<Res>) & {
105
+ example?: unknown;
106
+ };
107
+ /**
108
+ * Method-first provider tree, matching the Apicity convention
109
+ * (`provider.<method>.<dotPath>`). dotPaths mirror the URL path under
110
+ * `https://api.z.ai`.
111
+ */
112
+ export interface ZaiCodingProvider {
113
+ post: {
114
+ api: {
115
+ coding: {
116
+ paas: {
117
+ v4: {
118
+ chat: {
119
+ completions: ZaiCodingPostEndpoint<ZaiCodingChatRequest, ZaiCodingChatResponse>;
120
+ };
121
+ };
122
+ };
123
+ };
124
+ };
125
+ };
126
+ get: {
127
+ api: {
128
+ monitor: {
129
+ usage: {
130
+ quota: {
131
+ limit: ZaiCodingGetEndpoint<ZaiCodingQuotaLimitResponse>;
132
+ };
133
+ modelUsage: ZaiCodingGetEndpoint<ZaiCodingModelUsageResponse>;
134
+ toolUsage: ZaiCodingGetEndpoint<ZaiCodingToolUsageResponse>;
135
+ };
136
+ };
137
+ };
138
+ };
139
+ }
140
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,qBAAa,cAAe,SAAQ,KAAK;aAGrB,MAAM,CAAC,EAAE,MAAM;aACf,IAAI,CAAC,EAAE,OAAO;gBAF9B,OAAO,EAAE,MAAM,EACC,MAAM,CAAC,EAAE,MAAM,YAAA,EACf,IAAI,CAAC,EAAE,OAAO,YAAA;CAKjC;AAED,MAAM,WAAW,gBAAgB;IAC/B,yFAAyF;IACzF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAOD,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,QAAQ,GAAG,MAAM,GAAG,WAAW,CAAC;IACtC,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,oBAAoB;IACnC,qDAAqD;IACrD,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,gBAAgB,EAAE,CAAC;IAC7B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,CA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G,EAAE;YACH,MAAM,EAAE;gBACN,IAAI,EAAE;oBACJ,EAAE,EAAE;wBACF,IAAI,EAAE;4BACJ,WAAW,EAAE,qBAAqB,CAChC,oBAAoB,EACpB,qBAAqB,CACtB,CAAC;yBACH,CAAC;qBACH,CAAC;iBACH,CAAC;aACH,CAAC;SACH,CAAC;KACH,CAAC;IACF,GAAG,EAAE;QACH,GAAG,EAAE;YACH,OAAO,EAAE;gBACP,KAAK,EAAE;oBACL,KAAK,EAAE;wBACL,KAAK,EAAE,oBAAoB,CAAC,2BAA2B,CAAC,CAAC;qBAC1D,CAAC;oBACF,UAAU,EAAE,oBAAoB,CAAC,2BAA2B,CAAC,CAAC;oBAC9D,SAAS,EAAE,oBAAoB,CAAC,0BAA0B,CAAC,CAAC;iBAC7D,CAAC;aACH,CAAC;SACH,CAAC;KACH,CAAC;CACH"}
@@ -0,0 +1,11 @@
1
+ export class ZaiCodingError extends Error {
2
+ status;
3
+ body;
4
+ constructor(message, status, body) {
5
+ super(message);
6
+ this.status = status;
7
+ this.body = body;
8
+ this.name = "ZaiCodingError";
9
+ }
10
+ }
11
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,cAAe,SAAQ,KAAK;IAGrB;IACA;IAHlB,YACE,OAAe,EACC,MAAe,EACf,IAAc;QAE9B,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,WAAM,GAAN,MAAM,CAAS;QACf,SAAI,GAAJ,IAAI,CAAU;QAG9B,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF"}
@@ -0,0 +1,11 @@
1
+ import { ZaiCodingOptions, ZaiCodingProvider } from "./types.js";
2
+ /**
3
+ * Z.ai GLM Coding Plan provider.
4
+ *
5
+ * Wraps the coding-plan chat endpoint (OpenAI-compatible) plus the account
6
+ * usage/quota monitoring endpoints. The coding endpoint is metered against the
7
+ * GLM Coding Plan subscription; the monitor endpoints report how much of that
8
+ * quota has been consumed.
9
+ */
10
+ export declare function createZaiCoding(options?: ZaiCodingOptions): ZaiCodingProvider;
11
+ //# sourceMappingURL=zaicoding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zaicoding.d.ts","sourceRoot":"","sources":["../../src/zaicoding.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,gBAAgB,EAChB,iBAAiB,EAOlB,MAAM,SAAS,CAAC;AAIjB;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC7B,OAAO,GAAE,gBAAqB,GAC7B,iBAAiB,CAgKnB"}
@@ -0,0 +1,110 @@
1
+ import { ZaiCodingError, } from "./types.js";
2
+ import { ZaiCodingChatRequestSchema } from "./zod.js";
3
+ import { attachExamples } from "./example.js";
4
+ /**
5
+ * Z.ai GLM Coding Plan provider.
6
+ *
7
+ * Wraps the coding-plan chat endpoint (OpenAI-compatible) plus the account
8
+ * usage/quota monitoring endpoints. The coding endpoint is metered against the
9
+ * GLM Coding Plan subscription; the monitor endpoints report how much of that
10
+ * quota has been consumed.
11
+ */
12
+ export function createZaiCoding(options = {}) {
13
+ const apiKey = options.apiKey ?? process.env.ZAI_CODING_PLAN_API_KEY ?? "";
14
+ if (!apiKey) {
15
+ throw new ZaiCodingError("ZAI_CODING_PLAN_API_KEY is required");
16
+ }
17
+ const baseURL = options.baseUrl ?? "https://api.z.ai";
18
+ async function send(path, init, auth) {
19
+ const url = new URL(path, baseURL);
20
+ const headers = new Headers(init.headers);
21
+ if (!headers.has("Authorization")) {
22
+ // Chat uses a Bearer token; the monitor endpoints take the raw key.
23
+ headers.set("Authorization", auth === "bearer" ? `Bearer ${apiKey}` : apiKey);
24
+ }
25
+ if (init.body !== undefined && !headers.has("Content-Type")) {
26
+ headers.set("Content-Type", "application/json");
27
+ }
28
+ let response;
29
+ try {
30
+ response = await fetch(url.toString(), { ...init, headers });
31
+ }
32
+ catch (error) {
33
+ throw new ZaiCodingError(`Failed to reach ${url.toString()}: ${error instanceof Error ? error.message : String(error)}`, undefined, error);
34
+ }
35
+ if (!response.ok) {
36
+ let body;
37
+ let detail = response.statusText;
38
+ try {
39
+ body = await response.json();
40
+ detail = JSON.stringify(body);
41
+ }
42
+ catch {
43
+ // Non-JSON error body — fall back to the status text.
44
+ }
45
+ throw new ZaiCodingError(`HTTP ${response.status}: ${detail}`, response.status, body);
46
+ }
47
+ return response;
48
+ }
49
+ // POST helper (Bearer auth). The `make*Request` name drives both the runtime
50
+ // method and the HTTP method the endpoint-walk lint derives for each leaf.
51
+ async function makeJsonRequest(path, body, signal) {
52
+ const res = await send(path, { method: "POST", body: JSON.stringify(body), signal }, "bearer");
53
+ return (await res.json());
54
+ }
55
+ // GET helper for the coding-plan monitor reads. These endpoints authenticate
56
+ // with the raw API key in `Authorization` (no `Bearer` prefix).
57
+ async function makeGetRequest(path, signal) {
58
+ const res = await send(path, { method: "GET", headers: { "Accept-Language": "en-US,en" }, signal }, "raw");
59
+ const text = await res.text();
60
+ return text ? JSON.parse(text) : {};
61
+ }
62
+ return attachExamples({
63
+ post: {
64
+ api: {
65
+ coding: {
66
+ paas: {
67
+ v4: {
68
+ chat: {
69
+ // POST https://api.z.ai/api/coding/paas/v4/chat/completions
70
+ // Docs: https://docs.z.ai/api-reference/llm/chat-completion
71
+ completions: Object.assign(async (params, opts) => {
72
+ if (params.stream) {
73
+ throw new ZaiCodingError("Streaming is not supported by this client; set stream:false or omit it.");
74
+ }
75
+ return makeJsonRequest("/api/coding/paas/v4/chat/completions", params, opts?.signal);
76
+ }, { schema: ZaiCodingChatRequestSchema }),
77
+ },
78
+ },
79
+ },
80
+ },
81
+ },
82
+ },
83
+ get: {
84
+ api: {
85
+ monitor: {
86
+ usage: {
87
+ quota: {
88
+ // GET https://api.z.ai/api/monitor/usage/quota/limit
89
+ // Docs: https://docs.z.ai/api-reference/introduction
90
+ limit: async (opts) => {
91
+ return makeGetRequest("/api/monitor/usage/quota/limit", opts?.signal);
92
+ },
93
+ },
94
+ // GET https://api.z.ai/api/monitor/usage/model-usage
95
+ // Docs: https://docs.z.ai/api-reference/introduction
96
+ modelUsage: async (opts) => {
97
+ return makeGetRequest("/api/monitor/usage/model-usage", opts?.signal);
98
+ },
99
+ // GET https://api.z.ai/api/monitor/usage/tool-usage
100
+ // Docs: https://docs.z.ai/api-reference/introduction
101
+ toolUsage: async (opts) => {
102
+ return makeGetRequest("/api/monitor/usage/tool-usage", opts?.signal);
103
+ },
104
+ },
105
+ },
106
+ },
107
+ },
108
+ });
109
+ }
110
+ //# sourceMappingURL=zaicoding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zaicoding.js","sourceRoot":"","sources":["../../src/zaicoding.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,GASf,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,0BAA0B,EAAE,MAAM,OAAO,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C;;;;;;;GAOG;AACH,MAAM,UAAU,eAAe,CAC7B,UAA4B,EAAE;IAE9B,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,uBAAuB,IAAI,EAAE,CAAC;IAC3E,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,cAAc,CAAC,qCAAqC,CAAC,CAAC;IAClE,CAAC;IACD,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,kBAAkB,CAAC;IAEtD,KAAK,UAAU,IAAI,CACjB,IAAY,EACZ,IAAiB,EACjB,IAAsB;QAEtB,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACnC,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC1C,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,CAAC;YAClC,oEAAoE;YAC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B,EAAE,CACvC;6BACF;yBACF;qBACF;iBACF;aACF;SACF;QACD,GAAG,EAAE;YACH,GAAG,EAAE;gBACH,OAAO,EAAE;oBACP,KAAK,EAAE;wBACL,KAAK,EAAE;4BACL,qDAAqD;4BACrD,qDAAqD;4BACrD,KAAK,EAAE,KAAK,EACV,IAA2B,EACW,EAAE;gCACxC,OAAO,cAAc,CACnB,gCAAgC,EAChC,IAAI,EAAE,MAAM,CACb,CAAC;4BACJ,CAAC;yBACF;wBACD,qDAAqD;wBACrD,qDAAqD;wBACrD,UAAU,EAAE,KAAK,EACf,IAA2B,EACW,EAAE;4BACxC,OAAO,cAAc,CACnB,gCAAgC,EAChC,IAAI,EAAE,MAAM,CACb,CAAC;wBACJ,CAAC;wBACD,oDAAoD;wBACpD,qDAAqD;wBACrD,SAAS,EAAE,KAAK,EACd,IAA2B,EACU,EAAE;4BACvC,OAAO,cAAc,CACnB,+BAA+B,EAC/B,IAAI,EAAE,MAAM,CACb,CAAC;wBACJ,CAAC;qBACF;iBACF;aACF;SACF;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { z } from "zod";
2
+ export declare const ZaiCodingMessageSchema: z.ZodObject<{
3
+ role: z.ZodEnum<{
4
+ user: "user";
5
+ system: "system";
6
+ assistant: "assistant";
7
+ }>;
8
+ content: z.ZodString;
9
+ }, z.core.$strip>;
10
+ export declare const ZaiCodingChatRequestSchema: z.ZodObject<{
11
+ model: z.ZodString;
12
+ messages: z.ZodArray<z.ZodObject<{
13
+ role: z.ZodEnum<{
14
+ user: "user";
15
+ system: "system";
16
+ assistant: "assistant";
17
+ }>;
18
+ content: z.ZodString;
19
+ }, z.core.$strip>>;
20
+ temperature: z.ZodOptional<z.ZodNumber>;
21
+ max_tokens: z.ZodOptional<z.ZodNumber>;
22
+ stream: z.ZodOptional<z.ZodBoolean>;
23
+ }, z.core.$strip>;
24
+ //# sourceMappingURL=zod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zod.d.ts","sourceRoot":"","sources":["../../src/zod.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,eAAO,MAAM,sBAAsB;;;;;;;iBAGjC,CAAC;AAEH,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;iBAMrC,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { z } from "zod";
2
+ export const ZaiCodingMessageSchema = z.object({
3
+ role: z.enum(["system", "user", "assistant"]),
4
+ content: z.string(),
5
+ });
6
+ export const ZaiCodingChatRequestSchema = z.object({
7
+ model: z.string(),
8
+ messages: z.array(ZaiCodingMessageSchema),
9
+ temperature: z.number().optional(),
10
+ max_tokens: z.number().optional(),
11
+ stream: z.boolean().optional(),
12
+ });
13
+ //# sourceMappingURL=zod.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zod.js","sourceRoot":"","sources":["../../src/zod.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC7C,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;IAC7C,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE;CACpB,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC,MAAM,CAAC;IACjD,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,sBAAsB,CAAC;IACzC,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAClC,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACjC,MAAM,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,QAAQ,EAAE;CAC/B,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@apicity/zaicoding",
3
+ "version": "0.6.3",
4
+ "description": "Z.ai GLM Coding Plan provider for Apicity — standalone, OpenAI-compatible chat completions plus coding-plan usage/quota monitoring.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/justintanner/apicity.git",
9
+ "directory": "provider/zaicoding"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "main": "dist/src/index.js",
16
+ "types": "dist/src/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "import": "./dist/src/index.js",
20
+ "types": "./dist/src/index.d.ts"
21
+ },
22
+ "./zod": {
23
+ "import": "./dist/src/zod.js",
24
+ "types": "./dist/src/zod.d.ts"
25
+ }
26
+ },
27
+ "dependencies": {
28
+ "zod": "^4.4.3"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "sideEffects": false,
36
+ "keywords": [
37
+ "ai",
38
+ "zai",
39
+ "zaicoding",
40
+ "glm",
41
+ "zhipu",
42
+ "coding",
43
+ "chat",
44
+ "usage",
45
+ "apicity"
46
+ ],
47
+ "author": "Justin Tanner",
48
+ "engines": {
49
+ "node": ">=18.0.0"
50
+ },
51
+ "homepage": "https://github.com/justintanner/apicity#readme",
52
+ "bugs": {
53
+ "url": "https://github.com/justintanner/apicity/issues"
54
+ },
55
+ "scripts": {
56
+ "build": "tsc -p tsconfig.json && node scripts/dist.mjs"
57
+ }
58
+ }