@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,234 @@
1
+ import { open, rename, rm, stat } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { sha256File } from '../core/index.js';
4
+ import { inspectImage, validateAsset } from '../assets/index.js';
5
+ import { child } from '../assets/files.js';
6
+ import { loadUploads, saveUploads } from '../assets/upload-cache.js';
7
+ import { probe } from '../timeline/index.js';
8
+ import { GatewayError, owns } from '../gateway/index.js';
9
+ /** Compare parameter objects independently of catalog and cloud asset IDs. */
10
+ export const same = (body) => JSON.stringify(Object.fromEntries(Object.entries(body).sort(([a], [b]) => a.localeCompare(b))));
11
+ export function mapRequest(compiled, catalog, slots) {
12
+ const capability = catalog.capabilities.find(c => c.model === compiled.model && c.medium === 'video');
13
+ if (!capability)
14
+ throw new Error(`capability_not_available:catalog 未列出 ${compiled.model},不能生成或报价。`);
15
+ const assigned = new Set();
16
+ let previousImageIndex = -1;
17
+ for (const media of compiled.media) {
18
+ const key = slots[media.slot];
19
+ if (!key)
20
+ throw new Error(`catalog_slot_mapping_required:${media.slot}`);
21
+ const slot = capability.assets.find(s => s.key === key);
22
+ if (!slot || slot.type !== (media.type === 'reference_video' ? 'video' : 'image') || assigned.has(key))
23
+ throw new Error(`catalog_slot_unavailable:${media.slot}`);
24
+ if (media.type === 'reference_image') {
25
+ const index = capability.assets.indexOf(slot);
26
+ if (index <= previousImageIndex)
27
+ throw new Error(`catalog_slot_order:${media.slot}`);
28
+ previousImageIndex = index;
29
+ }
30
+ assigned.add(key);
31
+ }
32
+ if (capability.assets.some(s => s.required && !assigned.has(s.key)))
33
+ throw new Error('catalog_slot_missing');
34
+ const params = { ...compiled.params, prompt: compiled.prompt };
35
+ if (Object.keys(params).some(key => !capability.params.some(p => p.key === key)))
36
+ throw new Error('catalog_param_unavailable');
37
+ return { capability: capability.id, params, assets: {} };
38
+ }
39
+ export async function validateMedia(dir, job) {
40
+ for (const a of job.assets) {
41
+ if (!a.approved)
42
+ throw new Error(`素材 ${a.id} 尚未确认,需用户决定;可先使用素材模块生成定稿。`);
43
+ const path = await child(dir, ...a.path.split('/'));
44
+ if (await sha256File(path) !== a.sha256)
45
+ throw new Error(`asset_hash_mismatch:${a.id}`);
46
+ if (a.role === 'motion_ref')
47
+ await probe(path);
48
+ else {
49
+ const issues = validateAsset(await inspectImage(path), a.role);
50
+ if (issues.some(i => i.level === 'block'))
51
+ throw new Error(`invalid_asset:${a.id}`);
52
+ }
53
+ }
54
+ }
55
+ /** Refresh only existing server attempts; PaidRunner remains the budget authority. */
56
+ export async function refreshUnsettledRefunds(runner, store, jobId) {
57
+ for (const attempt of await store.list(jobId)) {
58
+ if (attempt.generation_id && (attempt.refund_state === 'pending' || attempt.refund_state === 'unknown')) {
59
+ await runner.refresh(attempt.idempotency_key);
60
+ }
61
+ }
62
+ }
63
+ export async function generateVideo(o) {
64
+ await refreshUnsettledRefunds(o.runner, o.store, o.job.job_id);
65
+ const req = mapRequest(o.compiled, o.catalog, o.slots);
66
+ await validateMedia(o.dir, o.job);
67
+ const cap = o.catalog.capabilities.find(c => c.id === req.capability);
68
+ const cache = await loadUploads(o.dir);
69
+ const submit = async () => {
70
+ // Inputs and media are immutable after an attempt exists in this job directory.
71
+ const prior = (await o.store.list(o.job.job_id)).filter(a => same(a.body.params) === same(req.params) && a.state !== 'rejected' && a.refund_state !== 'refunded');
72
+ if (prior.some(a => !owns(a, o.gateway)))
73
+ throw new Error('prior_payment_unresolved:相同工作已有付款记录,当前云无法核验;停止生成,请先核实原付款。');
74
+ const previous = prior.find(a => a.state === 'unconfirmed') ?? prior.at(-1);
75
+ if (previous) {
76
+ if (previous.state === 'unconfirmed') {
77
+ return o.runner.submit(replayRequest(previous));
78
+ }
79
+ return previous;
80
+ }
81
+ for (const m of o.compiled.media) {
82
+ const a = o.job.assets.find(a => a.id === m.asset);
83
+ const path = await child(o.dir, ...a.path.split('/'));
84
+ const key = o.slots[m.slot];
85
+ if (!key)
86
+ throw new Error(`catalog_slot_mapping_required:${m.slot}`);
87
+ const slot = cap.assets.find(s => s.key === key);
88
+ const size = (await stat(path)).size;
89
+ if (slot.max_size_bytes && size > slot.max_size_bytes)
90
+ throw new Error('catalog_asset_size_exceeded');
91
+ if (m.type === 'reference_video') {
92
+ const p = await probe(path);
93
+ if (slot.max_duration_seconds && p.frames * p.fps.den / p.fps.num > slot.max_duration_seconds)
94
+ throw new Error('catalog_asset_duration_exceeded');
95
+ }
96
+ const contentType = await uploadContentType(path, m.type === 'reference_video' ? 'video' : 'image');
97
+ if (!cache[a.sha256]) {
98
+ const uploaded = await o.gateway.upload(path, { consent_confirmed: true, content_type: contentType });
99
+ if (uploaded.status !== 'ready')
100
+ throw new Error('asset_not_ready');
101
+ cache[a.sha256] = uploaded.asset_id;
102
+ await saveUploads(o.dir, cache);
103
+ }
104
+ req.assets[key] = cache[a.sha256];
105
+ }
106
+ return o.runner.submit(req);
107
+ };
108
+ let attempt;
109
+ for (let retry = 0;; retry++) {
110
+ try {
111
+ attempt = await submit();
112
+ if (retry > 0 || attempt.state !== 'rejected' || attempt.rejected_code !== 'asset_not_found')
113
+ break;
114
+ }
115
+ catch (error) {
116
+ if (retry > 0 || !(error instanceof GatewayError) || error.code !== 'asset_not_found')
117
+ throw error;
118
+ }
119
+ for (const media of o.compiled.media)
120
+ delete cache[media.sha256];
121
+ await saveUploads(o.dir, cache);
122
+ }
123
+ attempt = await pollAttempt(o.runner, attempt, o.poll);
124
+ if (attempt.state !== 'completed' || !attempt.generation_id)
125
+ throw await terminalError(attempt, o.gateway);
126
+ const url = await fetchOutput(o.gateway, attempt, 'video');
127
+ await o.download(url, o.output);
128
+ await probe(o.output);
129
+ return { path: o.output, attempt: attempt.idempotency_key };
130
+ }
131
+ const OUTPUT_DOWNLOAD_TIMEOUT_MS = 300_000;
132
+ const OUTPUT_VIDEO_LIMIT_BYTES = 500 * 1024 * 1024;
133
+ export async function download(url, path, options) {
134
+ const part = `${path}.${randomUUID()}.part`;
135
+ let file;
136
+ let body = null;
137
+ const maxBytes = options?.maxBytes ?? OUTPUT_VIDEO_LIMIT_BYTES;
138
+ const timeoutMs = options?.timeoutMs ?? OUTPUT_DOWNLOAD_TIMEOUT_MS;
139
+ try {
140
+ const response = await (options?.fetch ?? fetch)(url, {
141
+ redirect: 'error',
142
+ signal: AbortSignal.timeout(timeoutMs),
143
+ });
144
+ body = response.body;
145
+ if (!response.ok || !body)
146
+ throw new Error('output_download_failed');
147
+ const contentLength = response.headers.get('content-length');
148
+ if (contentLength !== null && (!/^\d+$/.test(contentLength) || Number(contentLength) > maxBytes)) {
149
+ throw new Error('output_download_failed');
150
+ }
151
+ file = await open(part, 'wx', 0o600);
152
+ let bytes = 0;
153
+ for await (const chunk of body) {
154
+ bytes += chunk.byteLength;
155
+ if (bytes > maxBytes)
156
+ throw new Error('output_download_failed');
157
+ await file.writeFile(chunk);
158
+ }
159
+ await file.sync();
160
+ await file.close();
161
+ file = undefined;
162
+ await rename(part, path);
163
+ }
164
+ catch {
165
+ await body?.cancel().catch(() => undefined);
166
+ await file?.close().catch(() => undefined);
167
+ await rm(part, { force: true });
168
+ throw new Error('output_download_failed');
169
+ }
170
+ }
171
+ export async function uploadContentType(path, type) {
172
+ if (type === 'video') {
173
+ const file = await open(path, 'r');
174
+ try {
175
+ const header = Buffer.alloc(12);
176
+ const { bytesRead } = await file.read(header, 0, 12, 0);
177
+ return bytesRead === 12 && header.toString('latin1', 4, 8) === 'ftyp' && header.toString('latin1', 8, 12) === 'qt ' ? 'video/quicktime' : 'video/mp4';
178
+ }
179
+ finally {
180
+ await file.close();
181
+ }
182
+ }
183
+ const f = await inspectImage(path);
184
+ const types = { png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp', heif: 'image/heif' };
185
+ const contentType = types[f.format];
186
+ if (!contentType)
187
+ throw new Error('unsupported upload format');
188
+ return contentType;
189
+ }
190
+ export function replayRequest(attempt) {
191
+ return Object.fromEntries(['capability', 'params', 'asset_id', 'assets', 'voice_authorized'].filter(k => attempt.body[k] !== undefined).map(k => [k, attempt.body[k]]));
192
+ }
193
+ export async function pollAttempt(runner, attempt, poll = { intervalMs: 5000, timeoutMs: 30 * 60 * 1000 }) {
194
+ const deadline = Date.now() + poll.timeoutMs;
195
+ while (attempt.state === 'submitted' && Date.now() < deadline) {
196
+ await new Promise(resolve => setTimeout(resolve, Math.min(poll.intervalMs, Math.max(0, deadline - Date.now()))));
197
+ attempt = await runner.refresh(attempt.idempotency_key);
198
+ }
199
+ return attempt;
200
+ }
201
+ export async function terminalError(attempt, gateway) {
202
+ if (attempt.state === 'rejected')
203
+ return new Error(`generation_rejected:${attempt.rejected_code};预算已释放,可续跑重试。`);
204
+ if (attempt.state === 'failed' || attempt.state === 'cancelled') {
205
+ let reason = 'unknown';
206
+ if (attempt.generation_id && owns(attempt, gateway)) {
207
+ const generation = await gateway.get(attempt.generation_id).catch(() => undefined);
208
+ if (typeof generation?.error === 'string' && /^[a-z][a-z0-9_]*$/.test(generation.error))
209
+ reason = generation.error;
210
+ }
211
+ const tail = attempt.refund_state === 'refunded' ? '费用已退回,预算已释放,可续跑重试。'
212
+ : attempt.refund_state === 'not_refunded' ? '费用已结算未退回,不自动重试,需用户决定。'
213
+ : '退款待确认,保留预算,请续跑查询。';
214
+ return new Error(`generation_${attempt.state}:${reason};${tail}`);
215
+ }
216
+ if (attempt.state !== 'completed' || !attempt.generation_id) {
217
+ if (owns(attempt, gateway) && ['ambiguous', 'prepared', 'unconfirmed'].includes(attempt.state)) {
218
+ // Account lookup is advisory: failure must preserve the unsettled verdict.
219
+ const me = await gateway.me().catch(() => undefined);
220
+ if (me && me.user_id !== attempt.account_id)
221
+ return new Error('generation_account_mismatch:该付款记录属于另一账户,继续运行无法查询;请换回原账户的平台 Key。预算保留。');
222
+ }
223
+ return new Error(`generation_unsettled:${attempt.state};保留预算,请续跑查询。`);
224
+ }
225
+ return new Error('generation_unsettled');
226
+ }
227
+ export async function fetchOutput(gateway, attempt, kind) {
228
+ const generation = await gateway.get(attempt.generation_id);
229
+ if (generation.status === 'completed' && generation.output === null && generation.error === 'output_purged')
230
+ throw new Error('output_purged:结果已过期,费用已结算;不重新下载或生成。');
231
+ if (generation.status !== 'completed' || generation.output?.kind !== kind)
232
+ throw new Error(`missing_${kind}_output`);
233
+ return generation.output.url;
234
+ }
@@ -0,0 +1,3 @@
1
+ export { Engine, STEP_NAMES, analyzeReference, computePlanDigest, draftJob } from './steps.js';
2
+ export { planCard } from './card.js';
3
+ export { DirectGeneration, validateEvidence, assertNewAttemptAllowed } from './direct.js';
@@ -0,0 +1,24 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { probe } from '../timeline/index.js';
4
+ const exec = promisify(execFile);
5
+ export async function mixAudio(video, audio, output) {
6
+ const meta = await probe(video);
7
+ const duration = meta.frames * meta.fps.den / meta.fps.num;
8
+ if (!audio) {
9
+ await exec('ffmpeg', ['-y', '-v', 'error', '-i', video, '-map', '0:v:0', '-c:v', 'copy', '-an', output]);
10
+ return { path: output, silent: true };
11
+ }
12
+ const fade = Math.min(0.25, duration);
13
+ const filter = `asetpts=PTS-STARTPTS,apad,atrim=duration=${duration},afade=t=out:st=${duration - fade}:d=${fade},loudnorm=I=-14:TP=-1:LRA=11`;
14
+ // Measure after padding/fade, then apply a linear second pass at the final duration.
15
+ const measured = await exec('ffmpeg', ['-hide_banner', '-nostats', '-i', audio, '-map', '0:a:0', '-af', `${filter}:print_format=json`, '-f', 'null', '-']);
16
+ const json = measured.stderr.match(/\{[^{}]*"input_i"[^{}]*\}/s)?.[0];
17
+ if (!json)
18
+ throw new Error('音频响度测量失败');
19
+ const m = JSON.parse(json);
20
+ const finite = ['input_i', 'input_tp', 'input_lra', 'input_thresh', 'target_offset'].every(k => Number.isFinite(Number(m[k])));
21
+ const finalFilter = finite ? `${filter}:measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:measured_thresh=${m.input_thresh}:offset=${m.target_offset}:linear=true` : filter;
22
+ await exec('ffmpeg', ['-y', '-v', 'error', '-i', video, '-i', audio, '-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-af', finalFilter, '-t', String(duration), '-ar', '48000', '-c:a', 'aac', output]);
23
+ return { path: output, silent: false };
24
+ }