@zenaigc/zenmcp 0.0.0-stage → 0.1.0

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.
Files changed (64) hide show
  1. package/README.md +53 -2
  2. package/dist/src/acquire/download.js +152 -0
  3. package/dist/src/acquire/errors.js +8 -0
  4. package/dist/src/acquire/share.js +67 -0
  5. package/dist/src/acquire/social.js +98 -0
  6. package/dist/src/acquire/trim.js +95 -0
  7. package/dist/src/assets/files.js +29 -0
  8. package/dist/src/assets/generator.js +141 -0
  9. package/dist/src/assets/images.js +90 -0
  10. package/dist/src/assets/index.js +3 -0
  11. package/dist/src/assets/model-library.js +87 -0
  12. package/dist/src/assets/upload-cache.js +36 -0
  13. package/dist/src/contract/cloud-v1.js +334 -0
  14. package/dist/src/core/hash.js +18 -0
  15. package/dist/src/core/index.js +4 -0
  16. package/dist/src/core/job-store.js +251 -0
  17. package/dist/src/core/safety.js +43 -0
  18. package/dist/src/core/schema.js +295 -0
  19. package/dist/src/doctor.js +22 -0
  20. package/dist/src/effects/check.js +19 -0
  21. package/dist/src/effects/font.js +78 -0
  22. package/dist/src/effects/index.js +188 -0
  23. package/dist/src/engine/card.js +50 -0
  24. package/dist/src/engine/direct.js +493 -0
  25. package/dist/src/engine/generate.js +234 -0
  26. package/dist/src/engine/index.js +3 -0
  27. package/dist/src/engine/media.js +24 -0
  28. package/dist/src/engine/steps.js +444 -0
  29. package/dist/src/engine/storage.js +90 -0
  30. package/dist/src/gateway/attempt-store.js +110 -0
  31. package/dist/src/gateway/budget.js +39 -0
  32. package/dist/src/gateway/cloud-gateway.js +141 -0
  33. package/dist/src/gateway/config.js +10 -0
  34. package/dist/src/gateway/device-auth.js +53 -0
  35. package/dist/src/gateway/errors.js +105 -0
  36. package/dist/src/gateway/http.js +124 -0
  37. package/dist/src/gateway/index.js +8 -0
  38. package/dist/src/gateway/paid-runner.js +376 -0
  39. package/dist/src/gateway/types.js +42 -0
  40. package/dist/src/inspect/index.js +276 -0
  41. package/dist/src/inspect/media.js +43 -0
  42. package/dist/src/mcp/server.js +178 -0
  43. package/dist/src/models/wan3/index.js +173 -0
  44. package/dist/src/models/wan3/limits.js +25 -0
  45. package/dist/src/timeline/conform.js +255 -0
  46. package/dist/src/timeline/cuts.js +225 -0
  47. package/dist/src/timeline/diff.js +82 -0
  48. package/dist/src/timeline/errors.js +8 -0
  49. package/dist/src/timeline/ffmpeg.js +164 -0
  50. package/dist/src/timeline/index.js +6 -0
  51. package/dist/src/timeline/params.js +46 -0
  52. package/dist/src/timeline/probe.js +98 -0
  53. package/dist/src/timeline/types.js +1 -0
  54. package/dist/templates/pop-title/README.md +18 -0
  55. package/dist/templates/pop-title/index.html +102 -0
  56. package/dist/templates/pop-title/pop-title.js +97 -0
  57. package/dist/templates/pop-title/render.js +42 -0
  58. package/dist/templates/pop-title/size-1080/index.html +102 -0
  59. package/dist/templates/pop-title/variables.example.json +9 -0
  60. package/dist/templates/pop-title/vendor/FONT.md +10 -0
  61. package/dist/templates/pop-title/vendor/NotoSansCJKsc-Bold.otf +0 -0
  62. package/dist/templates/pop-title/vendor/OFL.txt +92 -0
  63. package/dist/templates/pop-title/vendor/gsap.min.js +11 -0
  64. package/package.json +33 -4
@@ -0,0 +1,90 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { constants } from "node:fs";
4
+ import { copyFile, stat, rm, link } from "node:fs/promises";
5
+ import { randomUUID } from "node:crypto";
6
+ import { resolve, dirname, join } from "node:path";
7
+ import { sha256File } from "../core/hash.js";
8
+ import { assetSchema, parseJob } from "../core/schema.js";
9
+ import { child, directory, safeId } from "./files.js";
10
+ const exec = promisify(execFile);
11
+ export async function inspectImage(path) {
12
+ const { stdout } = await exec("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,codec_name", "-of", "json", resolve(path)]);
13
+ const stream = JSON.parse(stdout).streams?.[0];
14
+ if (!stream?.width || !stream.height || !stream.codec_name)
15
+ throw new Error("no image stream");
16
+ const formats = { mjpeg: "jpeg", png: "png", webp: "webp", hevc: "heif", av1: "avif", bmp: "bmp", tiff: "tiff" };
17
+ const format = formats[stream.codec_name];
18
+ if (!format)
19
+ throw new Error("unsupported image codec");
20
+ return { width: stream.width, height: stream.height, format, size_bytes: (await stat(path)).size };
21
+ }
22
+ export function validateAsset(facts, role, rules = {}) {
23
+ const issues = [];
24
+ if (role === "motion_ref")
25
+ return [{ level: "block", code: "image_role", message: "动作参考需要视频检查。" }];
26
+ if (![facts.width, facts.height, facts.size_bytes].every(n => Number.isSafeInteger(n) && n > 0))
27
+ return [{ level: "block", code: "invalid_facts", message: "图片事实无效。" }];
28
+ const add = (code, message, fallback) => issues.push({ code, message, level: rules.levels?.[code] ?? fallback });
29
+ if (Math.min(facts.width, facts.height) < (rules.minEdge ?? 256))
30
+ add("min_edge", "图片短边不足。", "warn");
31
+ if (Math.max(facts.width, facts.height) > (rules.maxLongEdge ?? 8192))
32
+ add("max_edge", "图片长边过大。", "warn");
33
+ if (facts.size_bytes > (rules.maxBytes ?? 20 * 1024 * 1024))
34
+ add("max_bytes", "图片文件过大。", "block");
35
+ if (!(rules.formats ?? ["jpeg", "png", "webp", "heif", "avif"]).includes(facts.format))
36
+ add("format", "图片格式不受支持。", "block");
37
+ return issues;
38
+ }
39
+ export async function ingestAsset(jobDir, srcPath, role, id = randomUUID()) {
40
+ safeId(id);
41
+ // Reject invalid roles before creating files, and never overwrite an existing artifact.
42
+ assetSchema.shape.role.parse(role);
43
+ const dir = await directory(jobDir, "assets");
44
+ const dest = await child(dir, id);
45
+ await copyFile(srcPath, dest, constants.COPYFILE_EXCL);
46
+ try {
47
+ return assetSchema.parse({ id, role, path: `assets/${id}`, sha256: await sha256File(dest), approved: false });
48
+ }
49
+ catch (error) {
50
+ await rm(dest, { force: true });
51
+ throw error;
52
+ }
53
+ }
54
+ export async function normalizeImage(srcPath, outPath, opts = {}) {
55
+ const edge = opts.maxLongEdge ?? 2048;
56
+ if (!Number.isSafeInteger(edge) || edge < 1)
57
+ throw new Error("invalid maximum edge");
58
+ const format = opts.format ?? "png";
59
+ const codec = { png: "png", jpeg: "mjpeg", webp: "libwebp" }[format];
60
+ if (!codec)
61
+ throw new Error("invalid output format");
62
+ await inspectImage(srcPath);
63
+ const temp = join(dirname(resolve(outPath)), `.${randomUUID()}.tmp`);
64
+ try {
65
+ // Default ffmpeg autorotation applies orientation before metadata is removed.
66
+ await exec("ffmpeg", ["-v", "error", "-i", resolve(srcPath), "-frames:v", "1", "-vf", `scale=w='min(iw,${edge})':h='min(ih,${edge})':force_original_aspect_ratio=decrease`, "-map_metadata", "-1", "-metadata:s:v:0", "rotate=0", "-c:v", codec, "-f", "image2", temp]);
67
+ const facts = await inspectImage(temp);
68
+ await link(temp, resolve(outPath));
69
+ return { ...facts, path: outPath, sha256: await sha256File(outPath) };
70
+ }
71
+ finally {
72
+ await rm(temp, { force: true });
73
+ }
74
+ }
75
+ function updateAsset(job, id, update) {
76
+ if (!job.assets.some(asset => asset.id === id))
77
+ throw new Error(`unknown asset: ${id}`);
78
+ return parseJob({ ...job, assets: job.assets.map(asset => asset.id === id ? update(asset) : asset) });
79
+ }
80
+ export function setAssetAttributes(job, assetId, text) {
81
+ return updateAsset(job, assetId, asset => asset.attributes === text ? asset : { ...asset, attributes: text, approved: false });
82
+ }
83
+ export function approvedAsset(asset) {
84
+ if (asset.role === "product" && !asset.attributes?.trim())
85
+ throw new Error("product attributes must be confirmed before approval");
86
+ return { ...asset, approved: true };
87
+ }
88
+ export function approveAsset(job, assetId) {
89
+ return updateAsset(job, assetId, approvedAsset);
90
+ }
@@ -0,0 +1,3 @@
1
+ export { inspectImage, validateAsset, ingestAsset, normalizeImage, setAssetAttributes, approveAsset } from "./images.js";
2
+ export { composeReference, GatewayImageGenerator } from "./generator.js";
3
+ export { ModelLibrary } from "./model-library.js";
@@ -0,0 +1,87 @@
1
+ import { constants } from "node:fs";
2
+ import { copyFile, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { randomUUID } from "node:crypto";
4
+ import { join } from "node:path";
5
+ import { z } from "zod";
6
+ import { parseJob, SHA256_PATTERN } from "../core/schema.js";
7
+ import { sha256File } from "../core/hash.js";
8
+ import { ingestAsset } from "./images.js";
9
+ import { child, directory, safeId } from "./files.js";
10
+ const modelSchema = z.strictObject({
11
+ id: z.string(), name: z.string().min(1), version: z.number().int().positive(), description: z.string(),
12
+ original: z.strictObject({ path: z.literal("original"), sha256: z.string().regex(SHA256_PATTERN) }),
13
+ identity: z.strictObject({ path: z.literal("identity"), sha256: z.string().regex(SHA256_PATTERN) }),
14
+ });
15
+ export class ModelLibrary {
16
+ root;
17
+ constructor(root) {
18
+ this.root = root;
19
+ }
20
+ /** Explicit user action only. Every version is immutable; model.json points to latest. */
21
+ async save(input) {
22
+ safeId(input.id);
23
+ await mkdir(this.root, { recursive: true });
24
+ const modelDir = await directory(this.root, "models", input.id);
25
+ const manifest = await child(modelDir, "model.json");
26
+ const versions = await directory(modelDir, "versions");
27
+ const numbers = (await readdir(versions)).filter(name => /^[1-9]\d*$/.test(name)).map(Number);
28
+ const version = Math.max(0, ...numbers) + 1;
29
+ const record = modelSchema.parse({ id: input.id, name: input.name, description: input.description, version,
30
+ original: { path: "original", sha256: await sha256File(input.originalImage) },
31
+ identity: { path: "identity", sha256: await sha256File(input.identityImage) } });
32
+ const stage = await directory(modelDir, `stage-${randomUUID()}`);
33
+ try {
34
+ await copyFile(input.originalImage, join(stage, "original"), constants.COPYFILE_EXCL);
35
+ await copyFile(input.identityImage, join(stage, "identity"), constants.COPYFILE_EXCL);
36
+ // Hash the copied bytes, so concurrent source edits cannot invalidate the manifest.
37
+ record.original.sha256 = await sha256File(join(stage, "original"));
38
+ record.identity.sha256 = await sha256File(join(stage, "identity"));
39
+ await writeFile(join(stage, "model.json"), JSON.stringify(record, null, 2), { flag: "wx" });
40
+ const destination = await child(versions, String(version));
41
+ await mkdir(destination); // Reserve this version; a concurrent save must fail, never replace it.
42
+ try {
43
+ await rename(stage, destination);
44
+ }
45
+ catch (error) {
46
+ await rm(destination, { recursive: true, force: true });
47
+ throw error;
48
+ }
49
+ const temp = await child(modelDir, `manifest-${randomUUID()}.json`);
50
+ try {
51
+ await writeFile(temp, JSON.stringify(record, null, 2), { flag: "wx" });
52
+ await rename(temp, manifest);
53
+ }
54
+ finally {
55
+ await rm(temp, { force: true });
56
+ }
57
+ return record;
58
+ }
59
+ finally {
60
+ await rm(stage, { recursive: true, force: true });
61
+ }
62
+ }
63
+ async get(id, version) {
64
+ safeId(id);
65
+ if (version !== undefined && (!Number.isSafeInteger(version) || version < 1))
66
+ throw new Error("invalid model version");
67
+ const parts = ["models", id, ...(version === undefined ? [] : ["versions", String(version)]), "model.json"];
68
+ const record = modelSchema.parse(JSON.parse(await readFile(await child(this.root, ...parts), "utf8")));
69
+ if (record.id !== id || (version !== undefined && record.version !== version))
70
+ throw new Error("model version mismatch");
71
+ return record;
72
+ }
73
+ async remove(id) {
74
+ safeId(id);
75
+ const dir = await child(this.root, "models", id);
76
+ // rm does not follow nested symlinks; the model directory itself must not be one.
77
+ await rm(dir, { recursive: true, force: true });
78
+ }
79
+ async useModel(job, id, version, jobDir = join(this.root, "jobs", job.job_id)) {
80
+ const record = await this.get(id, version);
81
+ const path = await child(this.root, "models", id, "versions", String(record.version), "identity");
82
+ if (await sha256File(path) !== record.identity.sha256)
83
+ throw new Error("model identity hash mismatch");
84
+ const asset = await ingestAsset(jobDir, path, "identity");
85
+ return parseJob({ ...job, assets: [...job.assets, asset] });
86
+ }
87
+ }
@@ -0,0 +1,36 @@
1
+ import { open, readFile, rename, rm } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { z } from "zod";
4
+ import { SHA256_PATTERN } from "../core/schema.js";
5
+ import { child } from "./files.js";
6
+ const uploadsSchema = z.record(z.string().regex(SHA256_PATTERN), z.guid());
7
+ export async function loadUploads(taskDir) {
8
+ const path = await child(taskDir, "uploads.json");
9
+ try {
10
+ return uploadsSchema.parse(JSON.parse(await readFile(path, "utf8")));
11
+ }
12
+ catch (error) {
13
+ if (error.code === "ENOENT")
14
+ return {};
15
+ throw error;
16
+ }
17
+ }
18
+ /** Persist each successful upload before attempting the next operation. */
19
+ export async function saveUploads(taskDir, uploads) {
20
+ const dest = await child(taskDir, "uploads.json");
21
+ const temp = await child(taskDir, `uploads-${randomUUID()}.tmp`);
22
+ try {
23
+ const handle = await open(temp, "wx");
24
+ try {
25
+ await handle.writeFile(JSON.stringify(uploadsSchema.parse(uploads), null, 2));
26
+ await handle.sync();
27
+ }
28
+ finally {
29
+ await handle.close();
30
+ }
31
+ await rename(temp, dest);
32
+ }
33
+ finally {
34
+ await rm(temp, { force: true });
35
+ }
36
+ }
@@ -0,0 +1,334 @@
1
+ import { z } from "zod";
2
+ /** Cloud v1 draft. No provider credentials or provider error text on the wire. */
3
+ const uuid = z.guid();
4
+ const int = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
5
+ const jsonObject = z.record(z.string(), z.unknown());
6
+ const safeId = z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/);
7
+ const generationFields = {
8
+ capability: z.string().min(1).max(64),
9
+ params: jsonObject.default({}),
10
+ asset_id: uuid.nullable().default(null),
11
+ assets: z.record(z.string(), uuid).default({}),
12
+ voice_authorized: z.boolean().default(false),
13
+ };
14
+ /** Parse the extracted binding header, not the whole HTTP header collection. */
15
+ export const accountBindingHeadersSchema = z.strictObject({ "X-Zen-Account": uuid.transform(value => value.toLowerCase()) });
16
+ export const priceRequestSchema = z.strictObject(generationFields);
17
+ export const generationCreateSchema = z.strictObject({
18
+ ...generationFields,
19
+ expected_price_credits: int.min(0),
20
+ pricing_version: z.string().min(1).max(32),
21
+ });
22
+ export const uploadRequestSchema = z.strictObject({
23
+ filename: z.string().max(255).nullable().default(null),
24
+ content_type: z.enum([
25
+ "image/jpeg",
26
+ "image/png",
27
+ "image/webp",
28
+ "image/heic",
29
+ "image/heif",
30
+ "video/mp4",
31
+ "video/quicktime",
32
+ "video/webm",
33
+ "audio/mpeg",
34
+ "audio/wav",
35
+ "audio/mp4",
36
+ ]),
37
+ size_bytes: int.positive(),
38
+ width: int.positive().nullable().default(null),
39
+ height: int.positive().nullable().default(null),
40
+ has_face: z.boolean().default(false),
41
+ consent_confirmed: z.literal(true),
42
+ });
43
+ export const meSchema = z.object({
44
+ user_id: uuid,
45
+ credits_available: int,
46
+ credential_id: uuid,
47
+ credential_kind: z.enum(["api_key", "device"]),
48
+ scopes: z.array(z.string()),
49
+ daily_credit_limit: int.nullable(),
50
+ total_credit_limit: int.nullable(),
51
+ used_today: int,
52
+ used_total: int,
53
+ });
54
+ const paramOptionSchema = z.object({
55
+ value: z.string(),
56
+ label: z.string(),
57
+ label_en: z.string().nullish(),
58
+ description: z.string().nullish(),
59
+ aspect_follows: z.string().nullish(),
60
+ });
61
+ const paramSchema = z.object({
62
+ key: z.string(),
63
+ type: z.enum(["segmented", "select", "slider", "text", "toggle"]),
64
+ label: z.string(),
65
+ label_en: z.string().nullish(),
66
+ description: z.string().nullish(),
67
+ options: z.array(paramOptionSchema).nullish(),
68
+ default: z.unknown().optional(),
69
+ required: z.boolean().optional(),
70
+ placeholder: z.string().nullish(),
71
+ max_length: int.nullish(),
72
+ min: z.number().nullish(),
73
+ max: z.number().nullish(),
74
+ step: z.number().nullish(),
75
+ expose: z.array(z.enum(["studio", "template", "agent"])).optional(),
76
+ binding_keys: z.array(z.string()).optional(),
77
+ });
78
+ const capabilityAssetSchema = z.object({
79
+ key: z.string(),
80
+ label: z.string().nullish(),
81
+ type: z.enum(["image", "video", "audio"]).nullish(),
82
+ hint: z.string().nullish(),
83
+ max_duration_seconds: int.nullish(),
84
+ max_size_bytes: int.nullish(),
85
+ required: z.boolean().optional(),
86
+ });
87
+ export const pricingSchema = z.discriminatedUnion("mode", [
88
+ z.object({ mode: z.literal("fixed"), credits: int }),
89
+ z.object({
90
+ mode: z.literal("tier"),
91
+ tier_param: z.string(),
92
+ tiers: z.array(z.object({ value: z.string(), credits: int })),
93
+ }),
94
+ z.object({
95
+ mode: z.literal("char_tier"),
96
+ text_param: z.string(),
97
+ tiers: z.array(z.object({ max_chars: int, credits: int })),
98
+ }),
99
+ z.object({
100
+ mode: z.literal("per_minute"),
101
+ credits_per_minute: int,
102
+ min_credits: int.optional(),
103
+ }),
104
+ z.object({
105
+ mode: z.literal("per_second"),
106
+ credits_per_second: int,
107
+ min_seconds: int.optional(),
108
+ }),
109
+ z.object({
110
+ mode: z.literal("per_second_tier"),
111
+ duration_source: z.enum(["param", "material"]).optional(),
112
+ tier_param: z.string().nullish(),
113
+ round_seconds: z.literal("ceil").nullish(),
114
+ duration_param: z.string(),
115
+ tiers: z.array(z.object({
116
+ value: z.string(),
117
+ credits_per_second: z.number().nonnegative(),
118
+ credits_per_second_with_video: z.number().nonnegative().nullish(),
119
+ max_seconds: z.number().nullish(),
120
+ })),
121
+ min_seconds: z.number().optional(),
122
+ }),
123
+ ]);
124
+ // Ignore only unsupported capability kinds; malformed supported capabilities still fail closed.
125
+ const supportedMedia = new Set(["image", "video", "audio"]);
126
+ const supportedPricingModes = new Set(["fixed", "tier", "char_tier", "per_minute", "per_second", "per_second_tier"]);
127
+ const filterCapabilities = (input) => Array.isArray(input) ? input.filter((item) => {
128
+ if (!item || typeof item !== "object")
129
+ return true;
130
+ const cap = item;
131
+ if (typeof cap.medium === "string" && !supportedMedia.has(cap.medium))
132
+ return false;
133
+ if (cap.pricing && typeof cap.pricing === "object") {
134
+ const mode = cap.pricing.mode;
135
+ if (typeof mode === "string" && !supportedPricingModes.has(mode))
136
+ return false;
137
+ }
138
+ return true;
139
+ }) : input;
140
+ const catalogBaseSchema = z.object({
141
+ catalog_version: z.string(),
142
+ currency: z.literal("ZEN_CREDIT"),
143
+ capabilities: z.preprocess(filterCapabilities, z.array(z.object({
144
+ id: z.string(),
145
+ name: z.string(),
146
+ model: z.string(),
147
+ medium: z.enum(["image", "video", "audio"]),
148
+ scope: z.string(),
149
+ params: z.array(paramSchema),
150
+ assets: z.array(capabilityAssetSchema),
151
+ spec: jsonObject.nullable(),
152
+ limits: jsonObject.nullable(),
153
+ pricing: pricingSchema.optional(),
154
+ pricing_version: z.string(),
155
+ requires_voice_authorization: z.boolean().default(false),
156
+ }))),
157
+ });
158
+ export const catalogSchema = catalogBaseSchema.superRefine((catalog, ctx) => {
159
+ const pairs = new Set();
160
+ const ids = new Set();
161
+ for (const capability of catalog.capabilities) {
162
+ const pair = JSON.stringify([capability.model, capability.medium]);
163
+ if (pairs.has(pair) || ids.has(capability.id))
164
+ ctx.addIssue({ code: "custom", message: "duplicate capability" });
165
+ pairs.add(pair);
166
+ ids.add(capability.id);
167
+ }
168
+ });
169
+ export const priceSchema = z.object({
170
+ capability: z.string(),
171
+ price_credits: int,
172
+ pricing_version: z.string(),
173
+ billing: jsonObject.nullish(),
174
+ });
175
+ const refundStates = ["none", "pending", "refunded", "not_refunded", "unknown"];
176
+ export const refundStateSchema = z.string().transform(value => refundStates.includes(value) ? value : "unknown");
177
+ const generationStatuses = ["queued", "generating", "completed", "failed", "cancelled"];
178
+ export const outputSchema = z.object({
179
+ kind: z.enum(["image", "video", "audio"]), url: z.url(), expires_at: z.iso.datetime().optional(),
180
+ width: int.positive().nullable(), height: int.positive().nullable(), duration_seconds: z.number().nonnegative().nullable(),
181
+ });
182
+ /** Internal fixture mapping only. cloud_state is never a client wire field. */
183
+ // cancel_requested retains the previous refund_state; "none" is its initial default.
184
+ export const stateMapping = {
185
+ reserved: ["queued", "none"], submitting: ["generating", "none"], running: ["generating", "none"],
186
+ unknown: ["generating", "unknown"], storing: ["generating", "none"], succeeded: ["completed", "none"], purged: ["completed", "none"],
187
+ failed_pending_release: ["failed", "pending"], failed: ["failed", "refunded"],
188
+ cancel_requested: ["generating", "none"], cancelled_pending_release: ["cancelled", "pending"],
189
+ cancelled_released: ["cancelled", "refunded"], result_expired: ["generating", "unknown"],
190
+ };
191
+ export const generationSchema = z.object({
192
+ id: uuid, attempt_id: safeId, capability: z.string().min(1),
193
+ status: z.enum(generationStatuses), progress: int.max(100).nullable(),
194
+ reserved_credits: int, charged_credits: int.nullable(), refund_state: refundStateSchema,
195
+ error: z.string().nullable(), output: outputSchema.nullable(),
196
+ created_at: z.iso.datetime(), completed_at: z.iso.datetime().nullable(),
197
+ });
198
+ /** Producer-side checks only. Client parsing must preserve anomalies for PaidRunner.apply. */
199
+ export function assertGenerationInvariants(g) {
200
+ const issue = (message) => { throw new RangeError(message); };
201
+ if (g.charged_credits !== null && g.charged_credits > g.reserved_credits)
202
+ issue("settlement exceeds reservation");
203
+ if (g.status === "completed") {
204
+ if (g.charged_credits === null || g.completed_at === null || g.refund_state === "refunded")
205
+ issue("completion requires settlement and completion time");
206
+ if ((g.output === null) !== (g.error === "output_purged"))
207
+ issue("completion requires output or explicit purge marker");
208
+ }
209
+ else {
210
+ if (g.output !== null)
211
+ issue("unfinished generation cannot expose output");
212
+ const released = g.refund_state === "refunded";
213
+ if (released) {
214
+ if ((g.status !== "failed" && g.status !== "cancelled") || g.charged_credits !== 0 || g.completed_at === null)
215
+ issue("release requires terminal status and zero charge");
216
+ }
217
+ else if (g.charged_credits !== null || g.completed_at !== null)
218
+ issue("unsettled generation retains reservation");
219
+ }
220
+ }
221
+ export const uploadTicketSchema = z.object({ asset_id: uuid, put_url: z.string() });
222
+ export const assetStatusSchema = z.object({
223
+ asset_id: uuid,
224
+ status: z.enum(["probing", "ready", "failed"]),
225
+ content_type: z.string(),
226
+ size_bytes: int,
227
+ duration_ms: int.nullable(),
228
+ width: int.nullable(),
229
+ height: int.nullable(),
230
+ });
231
+ export const deviceBindingSchema = z.object({
232
+ binding_id: z.string(),
233
+ verification_url: z.string(),
234
+ expires_in: int,
235
+ interval: int,
236
+ });
237
+ export const deviceTokenSchema = z.object({
238
+ access_token: z.string().regex(/^zk_(?:live|test)_[A-Za-z0-9_-]+$/),
239
+ token_type: z.literal("Bearer"),
240
+ expires_at: z.string(),
241
+ scopes: z.array(z.string()),
242
+ });
243
+ export const deviceBindingRequestSchema = z.strictObject({
244
+ code_challenge: z.string().regex(/^[A-Za-z0-9_-]{43}$/), code_challenge_method: z.literal("S256"),
245
+ state: safeId, installation_id: safeId, client_name: z.string().min(1), client_version: z.string().nullable(), scopes: z.array(z.string()),
246
+ });
247
+ export const deviceTokenRequestSchema = z.strictObject({ binding_id: safeId, code_verifier: z.string().regex(/^[A-Za-z0-9_-]{43,128}$/), state: safeId });
248
+ // Each row is [HTTP, first POST verdict, replay verdict, money evidence, applicable endpoints, optional retry exhaustion verdicts].
249
+ export const errorRules = {
250
+ unsupported_platform: [422, "ambiguous", "ambiguous", "not_applicable", ["social"]],
251
+ post_unavailable: [404, "ambiguous", "ambiguous", "not_applicable", ["social"]],
252
+ upstream_unavailable: [502, "ambiguous", "ambiguous", "not_applicable", ["social"]],
253
+ invalid_request: [422, "rejected", "ambiguous", "no_new_hold", ["submit", "price", "upload", "device"]],
254
+ validation_error: [422, "rejected", "ambiguous", "no_new_hold", ["social", "submit", "lookup", "price", "upload", "device"]],
255
+ invalid_credential: [401, "rejected", "ambiguous", "no_new_hold", ["social", "submit", "price", "read", "lookup", "cancel", "upload"]],
256
+ account_mismatch: [403, "rejected", "ambiguous", "no_new_hold", ["submit", "lookup"]],
257
+ access_denied: [403, "rejected", "ambiguous", "no_new_hold", ["submit", "price", "read", "lookup", "cancel", "upload"]],
258
+ capability_not_available: [404, "rejected", "ambiguous", "no_new_hold", ["submit", "price"]],
259
+ asset_not_found: [404, "rejected", "ambiguous", "no_new_hold", ["submit", "price", "upload"]],
260
+ generation_not_found: [404, "ambiguous", "ambiguous", "unknown", ["read", "cancel"]],
261
+ attempt_not_found: [404, "ambiguous", "ambiguous", "unknown", ["lookup"]],
262
+ credential_limit_exceeded: [402, "rejected", "rejected", "key_rejected", ["submit", "lookup"]],
263
+ insufficient_credits: [402, "rejected", "rejected", "key_rejected", ["submit", "lookup"]],
264
+ pricing_changed: [409, "rejected", "rejected", "key_rejected", ["submit", "lookup"]],
265
+ quote_changed: [409, "rejected", "rejected", "key_rejected", ["submit", "lookup"]],
266
+ idempotency_key_reused: [409, "ambiguous", "ambiguous", "original_unchanged", ["submit"]],
267
+ rate_limited: [429, "retry", "retry", "no_new_hold", ["social", "submit", "price", "read", "lookup", "cancel", "upload", "device"], { first: "rejected", replay: "ambiguous" }],
268
+ queue_unavailable: [503, "queue_unavailable", "ambiguous", "transaction_rolled_back", ["submit"]],
269
+ outcome_unknown: [503, "ambiguous", "ambiguous", "held", ["submit"]],
270
+ cancel_rejected: [409, "ambiguous", "ambiguous", "original_unchanged", ["cancel"]],
271
+ authorization_pending: [400, "ambiguous", "ambiguous", "not_applicable", ["device"]],
272
+ slow_down: [400, "ambiguous", "ambiguous", "not_applicable", ["device"]],
273
+ invalid_grant: [400, "ambiguous", "ambiguous", "not_applicable", ["device"]],
274
+ binding_not_found: [404, "ambiguous", "ambiguous", "not_applicable", ["device"]],
275
+ binding_closed: [400, "ambiguous", "ambiguous", "not_applicable", ["device"]],
276
+ };
277
+ export const validationErrorSchema = z.object({ detail: z.array(z.object({
278
+ loc: z.array(z.union([z.string(), z.number().int()])), type: z.string(),
279
+ })) });
280
+ export const errorSchema = z.union([
281
+ z.object({ detail: z.object({
282
+ code: z.enum(Object.keys(errorRules).filter(code => code !== "validation_error")),
283
+ pricing_version: z.string().optional(), price_credits: int.optional(), interval: int.optional(),
284
+ }) }),
285
+ validationErrorSchema,
286
+ ]);
287
+ // Required catalog positions; unavailable entries must not be advertised as executable.
288
+ export const modelPositions = [
289
+ { model: "seedance-domestic-2.0", medium: "video", protocol: "pending_hiflowt" },
290
+ { model: "seedance-domestic-2.5", medium: "video", protocol: "pending_hiflowt" },
291
+ { model: "wan3.0-video", medium: "video", protocol: "dashscope_documented" },
292
+ { model: "kling-version-pending", medium: "video", protocol: "pending_version" },
293
+ { model: "qwen3.8-max", medium: "text", protocol: "chat_documented" },
294
+ { model: "gpt-image-2.6-flare", medium: "image", protocol: "geekai_documented" },
295
+ { model: "sun-mapping-pending", medium: "image", protocol: "pending_mapping" },
296
+ ];
297
+ // Local compiler positions only; upstream support of input.media is not established.
298
+ export const wanDraftInput = {
299
+ params: ["audio", "prompt_extend", "watermark", "resolution", "ratio", "duration", "seed", "prompt"],
300
+ slots: [...Array.from({ length: 10 }, (_, index) => ({ key: `image_${index + 1}`, type: "image", upstream_support: "unverified" })),
301
+ { key: "video_1", type: "video", upstream_support: "unverified" }],
302
+ };
303
+ // ---- v1.2 additive: social post resolve ----
304
+ export const socialPlatformSchema = z.enum(["douyin", "xiaohongshu", "bilibili", "tiktok", "instagram", "x"]);
305
+ export const socialResolveRequestSchema = z.object({ share_url: z.url({ protocol: /^https?$/ }).max(2048) }).strict();
306
+ const socialRemoteMedia = z.object({ url: z.url({ protocol: /^https$/ }), width: int.positive().nullable(), height: int.positive().nullable() });
307
+ export const socialPostSchema = z.object({
308
+ platform: socialPlatformSchema,
309
+ post_id: z.string().min(1).max(128),
310
+ canonical_url: z.url(),
311
+ kind: z.enum(["video", "images"]),
312
+ title: z.string().max(1000),
313
+ text: z.string().max(10000),
314
+ hashtags: z.array(z.string().max(200)).max(100),
315
+ author: z.object({ name: z.string().max(200), id: z.string().max(128).nullable() }),
316
+ published_at: z.iso.datetime().nullable(),
317
+ video: z.object({
318
+ streams: z.array(z.object({ type: z.enum(["muxed", "video", "audio"]), url: z.url({ protocol: /^https$/ }) })).min(1).max(2),
319
+ duration_seconds: z.number().nonnegative().nullable(),
320
+ width: int.positive().nullable(), height: int.positive().nullable(),
321
+ watermark_free: z.boolean(),
322
+ }).nullable(),
323
+ images: z.array(socialRemoteMedia).max(50),
324
+ cover: socialRemoteMedia.nullable(),
325
+ download_headers: z.object({ referer: z.url().optional(), user_agent: z.string().max(300).optional() }).strict(),
326
+ }).superRefine((p, ctx) => {
327
+ if (p.kind === "video" && !p.video)
328
+ ctx.addIssue({ code: "custom", message: "video post without video" });
329
+ if (p.kind === "images" && p.images.length === 0)
330
+ ctx.addIssue({ code: "custom", message: "images post without images" });
331
+ const t = p.video?.streams.map(s => s.type).sort().join(",");
332
+ if (t && t !== "muxed" && t !== "audio,video")
333
+ ctx.addIssue({ code: "custom", message: "streams must be [muxed] or [video,audio]" });
334
+ });
@@ -0,0 +1,18 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ export function sha256String(value) {
4
+ return createHash("sha256").update(value, "utf8").digest("hex");
5
+ }
6
+ export function sha256File(path) {
7
+ return new Promise((resolve, reject) => {
8
+ const hash = createHash("sha256");
9
+ const stream = createReadStream(path);
10
+ stream.on("data", (chunk) => {
11
+ hash.update(chunk);
12
+ });
13
+ stream.on("error", reject);
14
+ stream.on("end", () => {
15
+ resolve(hash.digest("hex"));
16
+ });
17
+ });
18
+ }
@@ -0,0 +1,4 @@
1
+ export { SCHEMA_VERSION, SHA256_PATTERN, SAFE_ID_PATTERN, isSafeId, fpsSchema, segmentTagsSchema, sourceSchema, segmentSchema, effectSchema, storyboardSchema, assetRoles, assetSchema, bindingSchema, requirementSubjects, requirementLevels, requirementSchema, checkStatuses, checkResultSchema, mediaSchema, billingUnits, billingSchema, outputSchema, runRecordSchema, jobSchema, parseStoryboard, parseJob, parseRunRecord, isPass, cutsOf, } from "./schema.js";
2
+ export { assertNoSignedUrl, SignedUrlError } from "./safety.js";
3
+ export { sha256File, sha256String } from "./hash.js";
4
+ export { DuplicateRunError, InvalidIdError, JobExistsError, JobNotFoundError, JobStoreError, appendRun, createJob, loadJob, loadRuns, saveJob, } from "./job-store.js";