@zenaigc/zenmcp 0.0.0-stage → 0.1.1

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 (66) hide show
  1. package/INSTALL.md +77 -0
  2. package/README.md +53 -2
  3. package/dist/src/acquire/download.js +152 -0
  4. package/dist/src/acquire/errors.js +8 -0
  5. package/dist/src/acquire/share.js +67 -0
  6. package/dist/src/acquire/social.js +98 -0
  7. package/dist/src/acquire/trim.js +95 -0
  8. package/dist/src/assets/files.js +29 -0
  9. package/dist/src/assets/generator.js +141 -0
  10. package/dist/src/assets/images.js +90 -0
  11. package/dist/src/assets/index.js +3 -0
  12. package/dist/src/assets/model-library.js +87 -0
  13. package/dist/src/assets/upload-cache.js +36 -0
  14. package/dist/src/contract/cloud-v1.js +334 -0
  15. package/dist/src/core/hash.js +18 -0
  16. package/dist/src/core/index.js +4 -0
  17. package/dist/src/core/job-store.js +251 -0
  18. package/dist/src/core/safety.js +43 -0
  19. package/dist/src/core/schema.js +295 -0
  20. package/dist/src/doctor.js +22 -0
  21. package/dist/src/effects/check.js +19 -0
  22. package/dist/src/effects/font.js +78 -0
  23. package/dist/src/effects/index.js +188 -0
  24. package/dist/src/engine/card.js +50 -0
  25. package/dist/src/engine/direct.js +493 -0
  26. package/dist/src/engine/generate.js +234 -0
  27. package/dist/src/engine/index.js +3 -0
  28. package/dist/src/engine/media.js +24 -0
  29. package/dist/src/engine/steps.js +444 -0
  30. package/dist/src/engine/storage.js +90 -0
  31. package/dist/src/gateway/attempt-store.js +110 -0
  32. package/dist/src/gateway/budget.js +39 -0
  33. package/dist/src/gateway/cloud-gateway.js +141 -0
  34. package/dist/src/gateway/config.js +10 -0
  35. package/dist/src/gateway/device-auth.js +53 -0
  36. package/dist/src/gateway/errors.js +105 -0
  37. package/dist/src/gateway/http.js +124 -0
  38. package/dist/src/gateway/index.js +8 -0
  39. package/dist/src/gateway/paid-runner.js +376 -0
  40. package/dist/src/gateway/types.js +42 -0
  41. package/dist/src/inspect/index.js +276 -0
  42. package/dist/src/inspect/media.js +43 -0
  43. package/dist/src/mcp/server.js +177 -0
  44. package/dist/src/models/wan3/index.js +173 -0
  45. package/dist/src/models/wan3/limits.js +25 -0
  46. package/dist/src/timeline/conform.js +255 -0
  47. package/dist/src/timeline/cuts.js +225 -0
  48. package/dist/src/timeline/diff.js +82 -0
  49. package/dist/src/timeline/errors.js +8 -0
  50. package/dist/src/timeline/ffmpeg.js +164 -0
  51. package/dist/src/timeline/index.js +6 -0
  52. package/dist/src/timeline/params.js +46 -0
  53. package/dist/src/timeline/probe.js +98 -0
  54. package/dist/src/timeline/types.js +1 -0
  55. package/dist/templates/pop-title/README.md +18 -0
  56. package/dist/templates/pop-title/index.html +102 -0
  57. package/dist/templates/pop-title/pop-title.js +97 -0
  58. package/dist/templates/pop-title/render.js +42 -0
  59. package/dist/templates/pop-title/size-1080/index.html +102 -0
  60. package/dist/templates/pop-title/variables.example.json +9 -0
  61. package/dist/templates/pop-title/vendor/FONT.md +10 -0
  62. package/dist/templates/pop-title/vendor/NotoSansCJKsc-Bold.otf +0 -0
  63. package/dist/templates/pop-title/vendor/OFL.txt +92 -0
  64. package/dist/templates/pop-title/vendor/gsap.min.js +11 -0
  65. package/package.json +35 -4
  66. package/skills/zenmcp/SKILL.md +27 -0
@@ -0,0 +1,141 @@
1
+ import { lstat, mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { GatewayError, PaidRunner } from "../gateway/index.js";
6
+ import { child, safeId } from "./files.js";
7
+ import { sha256File } from "../core/hash.js";
8
+ import { loadUploads, saveUploads } from "./upload-cache.js";
9
+ import { ingestAsset, inspectImage } from "./images.js";
10
+ export async function composeReference(input, generator) {
11
+ const id = input.id ?? randomUUID();
12
+ safeId(id);
13
+ const destination = await child(input.jobDir, "assets", id);
14
+ try {
15
+ await lstat(destination);
16
+ throw new Error("asset destination already exists");
17
+ }
18
+ catch (error) {
19
+ if (error.code !== "ENOENT")
20
+ throw error;
21
+ }
22
+ const assets = [input.model, input.product, ...(input.scene ? [input.scene] : [])];
23
+ if (input.model.role !== "identity" || input.product.role !== "product" || (input.scene && input.scene.role !== "scene"))
24
+ throw new Error("invalid composition roles");
25
+ const images = [];
26
+ for (const asset of assets) {
27
+ const path = await child(input.jobDir, ...asset.path.split("/"));
28
+ images.push({ role: asset.role, path });
29
+ }
30
+ const result = await generator.generate({
31
+ prompt: ["Create one full-body photographic dressed reference image.",
32
+ "Preserve the identity, face, hairstyle and body proportions from the identity reference.",
33
+ "Use the complete outfit and footwear from the product reference, preserving its visible details.",
34
+ input.scene ? "Use the scene reference as the background." : "Use a neutral plain background.",
35
+ "Do not add text or watermarks."].join(" "), images,
36
+ });
37
+ return ingestAsset(input.jobDir, result.path, "product", id);
38
+ }
39
+ export class GatewayImageGenerator {
40
+ options;
41
+ constructor(options) {
42
+ this.options = options;
43
+ }
44
+ async generate(req) {
45
+ const o = this.options;
46
+ if (o.consentConfirmed !== true)
47
+ throw new Error("upload consent required");
48
+ if (!Number.isSafeInteger(o.maxPolls ?? 120) || (o.maxPolls ?? 120) < 0)
49
+ throw new Error("invalid poll limit");
50
+ const result = await o.gateway.catalog();
51
+ if (!result.modified)
52
+ throw new Error("catalog required");
53
+ const capability = result.catalog.capabilities.find(item => item.id === o.capability && item.medium === "image");
54
+ if (!capability || !capability.params.some(param => param.key === "prompt" && param.type === "text"))
55
+ throw new Error("unsupported image capability");
56
+ const assigned = new Set();
57
+ const prepared = [];
58
+ for (const image of req.images) {
59
+ const key = o.slots[image.role];
60
+ const slot = capability.assets.find(item => item.key === key && item.type === "image");
61
+ if (!key || !slot || assigned.has(key))
62
+ throw new Error("invalid or duplicate catalog image slot");
63
+ assigned.add(key);
64
+ const facts = await inspectImage(image.path);
65
+ if (slot.max_size_bytes && facts.size_bytes > slot.max_size_bytes)
66
+ throw new Error("image exceeds catalog slot size");
67
+ const contentType = { jpeg: "image/jpeg", png: "image/png", webp: "image/webp", heif: "image/heif" }[facts.format];
68
+ if (!contentType)
69
+ throw new Error("unsupported upload format");
70
+ prepared.push({ key, image, facts, sha256: await sha256File(image.path), contentType: contentType });
71
+ }
72
+ if (capability.assets.some(slot => slot.required && !assigned.has(slot.key)))
73
+ throw new Error("missing required catalog slot");
74
+ // Reuse content IDs across calls/restarts so PaidRunner sees the same work.
75
+ const uploads = await loadUploads(o.outputDir);
76
+ const submit = async () => {
77
+ const assets = {};
78
+ for (const item of prepared) {
79
+ let assetId = uploads[item.sha256];
80
+ if (!assetId) {
81
+ const uploaded = await o.gateway.upload(item.image.path, { content_type: item.contentType, width: item.facts.width, height: item.facts.height, consent_confirmed: o.consentConfirmed });
82
+ if (uploaded.status !== "ready")
83
+ throw new Error("upload is not ready");
84
+ assetId = uploaded.asset_id;
85
+ uploads[item.sha256] = assetId;
86
+ await saveUploads(o.outputDir, uploads);
87
+ }
88
+ assets[item.key] = assetId;
89
+ }
90
+ return o.runner.submit({ capability: capability.id, params: { ...o.params, prompt: req.prompt }, assets });
91
+ };
92
+ const invalidate = async () => {
93
+ // Gateway exposes no offending asset ID, so invalidate only this request's entries.
94
+ for (const item of prepared)
95
+ delete uploads[item.sha256];
96
+ await saveUploads(o.outputDir, uploads);
97
+ };
98
+ let attempt;
99
+ for (let retry = 0;; retry++) {
100
+ try {
101
+ attempt = await submit();
102
+ if (retry > 0 || attempt.state !== "rejected" || attempt.rejected_code !== "asset_not_found")
103
+ break;
104
+ }
105
+ catch (error) {
106
+ if (retry > 0 || !(error instanceof GatewayError) || error.code !== "asset_not_found")
107
+ throw error;
108
+ }
109
+ await invalidate(); // Expired uploads get exactly one re-upload, not a new money state machine.
110
+ }
111
+ const polls = o.maxPolls ?? 120;
112
+ for (let n = 0; attempt.state === "submitted" && n < polls; n++) {
113
+ await (o.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))))(o.pollIntervalMs ?? 1000);
114
+ attempt = await o.runner.refresh(attempt.idempotency_key);
115
+ }
116
+ if (attempt.state !== "completed" || !attempt.generation_id)
117
+ throw new Error(`image generation did not complete: ${attempt.state}`);
118
+ const generation = await o.gateway.get(attempt.generation_id);
119
+ if (generation.status === "completed" && generation.output === null && generation.error === "output_purged")
120
+ throw new Error("output_purged:结果已过期,费用已结算;不重新下载或生成。");
121
+ if (generation.status !== "completed" || generation.output?.kind !== "image")
122
+ throw new Error("missing image output");
123
+ const tempDir = await mkdtemp(join(tmpdir(), "z7-image-"));
124
+ try {
125
+ const temp = join(tempDir, "output");
126
+ const download = o.download ?? (async (url, path) => {
127
+ const response = await fetch(url);
128
+ if (!response.ok)
129
+ throw new Error("image download failed");
130
+ await writeFile(path, Buffer.from(await response.arrayBuffer()), { flag: "wx" });
131
+ });
132
+ await download(generation.output.url, temp);
133
+ await inspectImage(temp);
134
+ const artifact = await ingestAsset(o.outputDir, temp, "product", randomUUID());
135
+ return { path: await child(o.outputDir, ...artifact.path.split("/")), charged_credits: attempt.charged_credits ?? undefined };
136
+ }
137
+ finally {
138
+ await rm(tempDir, { recursive: true, force: true });
139
+ }
140
+ }
141
+ }
@@ -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
+ }