@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.
- package/INSTALL.md +77 -0
- package/README.md +53 -2
- package/dist/src/acquire/download.js +152 -0
- package/dist/src/acquire/errors.js +8 -0
- package/dist/src/acquire/share.js +67 -0
- package/dist/src/acquire/social.js +98 -0
- package/dist/src/acquire/trim.js +95 -0
- package/dist/src/assets/files.js +29 -0
- package/dist/src/assets/generator.js +141 -0
- package/dist/src/assets/images.js +90 -0
- package/dist/src/assets/index.js +3 -0
- package/dist/src/assets/model-library.js +87 -0
- package/dist/src/assets/upload-cache.js +36 -0
- package/dist/src/contract/cloud-v1.js +334 -0
- package/dist/src/core/hash.js +18 -0
- package/dist/src/core/index.js +4 -0
- package/dist/src/core/job-store.js +251 -0
- package/dist/src/core/safety.js +43 -0
- package/dist/src/core/schema.js +295 -0
- package/dist/src/doctor.js +22 -0
- package/dist/src/effects/check.js +19 -0
- package/dist/src/effects/font.js +78 -0
- package/dist/src/effects/index.js +188 -0
- package/dist/src/engine/card.js +50 -0
- package/dist/src/engine/direct.js +493 -0
- package/dist/src/engine/generate.js +234 -0
- package/dist/src/engine/index.js +3 -0
- package/dist/src/engine/media.js +24 -0
- package/dist/src/engine/steps.js +444 -0
- package/dist/src/engine/storage.js +90 -0
- package/dist/src/gateway/attempt-store.js +110 -0
- package/dist/src/gateway/budget.js +39 -0
- package/dist/src/gateway/cloud-gateway.js +141 -0
- package/dist/src/gateway/config.js +10 -0
- package/dist/src/gateway/device-auth.js +53 -0
- package/dist/src/gateway/errors.js +105 -0
- package/dist/src/gateway/http.js +124 -0
- package/dist/src/gateway/index.js +8 -0
- package/dist/src/gateway/paid-runner.js +376 -0
- package/dist/src/gateway/types.js +42 -0
- package/dist/src/inspect/index.js +276 -0
- package/dist/src/inspect/media.js +43 -0
- package/dist/src/mcp/server.js +177 -0
- package/dist/src/models/wan3/index.js +173 -0
- package/dist/src/models/wan3/limits.js +25 -0
- package/dist/src/timeline/conform.js +255 -0
- package/dist/src/timeline/cuts.js +225 -0
- package/dist/src/timeline/diff.js +82 -0
- package/dist/src/timeline/errors.js +8 -0
- package/dist/src/timeline/ffmpeg.js +164 -0
- package/dist/src/timeline/index.js +6 -0
- package/dist/src/timeline/params.js +46 -0
- package/dist/src/timeline/probe.js +98 -0
- package/dist/src/timeline/types.js +1 -0
- package/dist/templates/pop-title/README.md +18 -0
- package/dist/templates/pop-title/index.html +102 -0
- package/dist/templates/pop-title/pop-title.js +97 -0
- package/dist/templates/pop-title/render.js +42 -0
- package/dist/templates/pop-title/size-1080/index.html +102 -0
- package/dist/templates/pop-title/variables.example.json +9 -0
- package/dist/templates/pop-title/vendor/FONT.md +10 -0
- package/dist/templates/pop-title/vendor/NotoSansCJKsc-Bold.otf +0 -0
- package/dist/templates/pop-title/vendor/OFL.txt +92 -0
- package/dist/templates/pop-title/vendor/gsap.min.js +11 -0
- package/package.json +35 -4
- package/skills/zenmcp/SKILL.md +27 -0
|
@@ -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";
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { lstat, open, link, mkdir, readdir, readFile, realpath, rename, rm, stat } from "node:fs/promises";
|
|
3
|
+
import { isAbsolute, join, relative, sep } from "node:path";
|
|
4
|
+
import { isSafeId, parseJob, parseRunRecord } from "./schema.js";
|
|
5
|
+
import { assertNoSignedUrl } from "./safety.js";
|
|
6
|
+
export class JobStoreError extends Error {
|
|
7
|
+
constructor(message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = new.target.name;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export class InvalidIdError extends JobStoreError {
|
|
13
|
+
}
|
|
14
|
+
export class JobExistsError extends JobStoreError {
|
|
15
|
+
}
|
|
16
|
+
export class JobNotFoundError extends JobStoreError {
|
|
17
|
+
}
|
|
18
|
+
export class DuplicateRunError extends JobStoreError {
|
|
19
|
+
}
|
|
20
|
+
function assertId(id, label) {
|
|
21
|
+
if (!isSafeId(id)) {
|
|
22
|
+
throw new InvalidIdError(`${label} must be a single path segment`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
async function existingRoot(root) {
|
|
26
|
+
try {
|
|
27
|
+
return await realpath(root);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw new JobNotFoundError("job root does not exist");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async function ensureRoot(root) {
|
|
34
|
+
await mkdir(root, { recursive: true });
|
|
35
|
+
return realpath(root);
|
|
36
|
+
}
|
|
37
|
+
function jobDirectory(root, jobId) {
|
|
38
|
+
assertId(jobId, "job_id");
|
|
39
|
+
const dir = join(root, jobId);
|
|
40
|
+
const prefix = root.endsWith(sep) ? root : root + sep;
|
|
41
|
+
if (dir !== root && !dir.startsWith(prefix)) {
|
|
42
|
+
throw new InvalidIdError("job_id escapes the job root");
|
|
43
|
+
}
|
|
44
|
+
return dir;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Reject a symlink at this directory, and a resolved path outside root.
|
|
48
|
+
* One static check before use. This does not try to close a later replacement race.
|
|
49
|
+
*/
|
|
50
|
+
async function assertContainedDirectory(root, dir, label) {
|
|
51
|
+
let info;
|
|
52
|
+
try {
|
|
53
|
+
info = await lstat(dir);
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
if (isMissing(err)) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
throw err;
|
|
60
|
+
}
|
|
61
|
+
if (info.isSymbolicLink()) {
|
|
62
|
+
throw new InvalidIdError(`${label} must not be a symlink`);
|
|
63
|
+
}
|
|
64
|
+
const real = await realpath(dir);
|
|
65
|
+
const rel = relative(root, real);
|
|
66
|
+
if (rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
67
|
+
throw new InvalidIdError(`${label} escapes the job root`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function isMissing(err) {
|
|
71
|
+
return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
|
|
72
|
+
}
|
|
73
|
+
function isExists(err) {
|
|
74
|
+
return typeof err === "object" && err !== null && "code" in err && err.code === "EEXIST";
|
|
75
|
+
}
|
|
76
|
+
async function exists(path) {
|
|
77
|
+
try {
|
|
78
|
+
await stat(path);
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
if (isMissing(err)) {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function syncDirectory(dir) {
|
|
89
|
+
const handle = await open(dir, "r");
|
|
90
|
+
try {
|
|
91
|
+
await handle.sync();
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
await handle.close();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
async function writeTemp(dir, hint, body) {
|
|
98
|
+
await mkdir(dir, { recursive: true });
|
|
99
|
+
const tmp = join(dir, `.${hint}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
|
|
100
|
+
const handle = await open(tmp, "wx", 0o644);
|
|
101
|
+
try {
|
|
102
|
+
await handle.writeFile(body);
|
|
103
|
+
await handle.sync();
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
await handle.close();
|
|
107
|
+
await rm(tmp, { force: true });
|
|
108
|
+
throw err;
|
|
109
|
+
}
|
|
110
|
+
await handle.close();
|
|
111
|
+
return tmp;
|
|
112
|
+
}
|
|
113
|
+
/** Replace dest only after the temp file is durable. A failed rename leaves dest unchanged. */
|
|
114
|
+
async function atomicReplace(dest, body) {
|
|
115
|
+
const dir = join(dest, "..");
|
|
116
|
+
const tmp = await writeTemp(dir, "job.json", body);
|
|
117
|
+
try {
|
|
118
|
+
await rename(tmp, dest);
|
|
119
|
+
}
|
|
120
|
+
catch (err) {
|
|
121
|
+
await rm(tmp, { force: true });
|
|
122
|
+
throw err;
|
|
123
|
+
}
|
|
124
|
+
await syncDirectory(dir);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Publish a new file. link() fails with EEXIST instead of replacing the target,
|
|
128
|
+
* which is what append-only runs need. rename() would overwrite.
|
|
129
|
+
*/
|
|
130
|
+
async function atomicCreate(dest, body) {
|
|
131
|
+
const dir = join(dest, "..");
|
|
132
|
+
const tmp = await writeTemp(dir, "new", body);
|
|
133
|
+
try {
|
|
134
|
+
await link(tmp, dest);
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
await rm(tmp, { force: true });
|
|
138
|
+
throw err;
|
|
139
|
+
}
|
|
140
|
+
await rm(tmp, { force: true });
|
|
141
|
+
await syncDirectory(dir);
|
|
142
|
+
}
|
|
143
|
+
function serialize(value) {
|
|
144
|
+
return `${JSON.stringify(value, null, 2)}\n`;
|
|
145
|
+
}
|
|
146
|
+
async function readJson(path) {
|
|
147
|
+
const text = await readFile(path, "utf8");
|
|
148
|
+
try {
|
|
149
|
+
return JSON.parse(text);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
throw new JobStoreError(`invalid JSON at ${path}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
export async function createJob(root, input) {
|
|
156
|
+
const job = parseJob(input);
|
|
157
|
+
const base = await ensureRoot(root);
|
|
158
|
+
const dir = jobDirectory(base, job.job_id);
|
|
159
|
+
await assertContainedDirectory(base, dir, "job directory");
|
|
160
|
+
const dest = join(dir, "job.json");
|
|
161
|
+
if (await exists(dest)) {
|
|
162
|
+
throw new JobExistsError(`job already exists: ${job.job_id}`);
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
await atomicCreate(dest, serialize(job));
|
|
166
|
+
}
|
|
167
|
+
catch (err) {
|
|
168
|
+
if (isExists(err)) {
|
|
169
|
+
throw new JobExistsError(`job already exists: ${job.job_id}`);
|
|
170
|
+
}
|
|
171
|
+
throw err;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
export async function loadJob(root, jobId) {
|
|
175
|
+
const base = await existingRoot(root);
|
|
176
|
+
const dir = jobDirectory(base, jobId);
|
|
177
|
+
await assertContainedDirectory(base, dir, "job directory");
|
|
178
|
+
const dest = join(dir, "job.json");
|
|
179
|
+
if (!(await exists(dest))) {
|
|
180
|
+
throw new JobNotFoundError(`job not found: ${jobId}`);
|
|
181
|
+
}
|
|
182
|
+
const job = parseJob(await readJson(dest));
|
|
183
|
+
if (job.job_id !== jobId) {
|
|
184
|
+
throw new JobStoreError(`job_id mismatch: ${jobId}`);
|
|
185
|
+
}
|
|
186
|
+
return job;
|
|
187
|
+
}
|
|
188
|
+
export async function saveJob(root, input) {
|
|
189
|
+
const job = parseJob(input);
|
|
190
|
+
const base = await existingRoot(root);
|
|
191
|
+
const dir = jobDirectory(base, job.job_id);
|
|
192
|
+
await assertContainedDirectory(base, dir, "job directory");
|
|
193
|
+
const dest = join(dir, "job.json");
|
|
194
|
+
if (!(await exists(dest))) {
|
|
195
|
+
throw new JobNotFoundError(`job not found: ${job.job_id}`);
|
|
196
|
+
}
|
|
197
|
+
await atomicReplace(dest, serialize(job));
|
|
198
|
+
}
|
|
199
|
+
export async function appendRun(root, input) {
|
|
200
|
+
assertNoSignedUrl(input);
|
|
201
|
+
const run = parseRunRecord(input);
|
|
202
|
+
assertNoSignedUrl(run);
|
|
203
|
+
const base = await existingRoot(root);
|
|
204
|
+
const dir = jobDirectory(base, run.job_id);
|
|
205
|
+
await assertContainedDirectory(base, dir, "job directory");
|
|
206
|
+
if (!(await exists(join(dir, "job.json")))) {
|
|
207
|
+
throw new JobNotFoundError(`job not found: ${run.job_id}`);
|
|
208
|
+
}
|
|
209
|
+
assertId(run.run_id, "run_id");
|
|
210
|
+
const runsDir = join(dir, "runs");
|
|
211
|
+
await assertContainedDirectory(base, runsDir, "runs directory");
|
|
212
|
+
const dest = join(runsDir, `${run.run_id}.json`);
|
|
213
|
+
if (await exists(dest)) {
|
|
214
|
+
throw new DuplicateRunError(`run already exists: ${run.run_id}`);
|
|
215
|
+
}
|
|
216
|
+
try {
|
|
217
|
+
await atomicCreate(dest, serialize(run));
|
|
218
|
+
}
|
|
219
|
+
catch (err) {
|
|
220
|
+
if (isExists(err)) {
|
|
221
|
+
throw new DuplicateRunError(`run already exists: ${run.run_id}`);
|
|
222
|
+
}
|
|
223
|
+
throw err;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
export async function loadRuns(root, jobId) {
|
|
227
|
+
await loadJob(root, jobId);
|
|
228
|
+
const base = await existingRoot(root);
|
|
229
|
+
const runsDir = join(jobDirectory(base, jobId), "runs");
|
|
230
|
+
await assertContainedDirectory(base, runsDir, "runs directory");
|
|
231
|
+
if (!(await exists(runsDir))) {
|
|
232
|
+
return [];
|
|
233
|
+
}
|
|
234
|
+
const names = await readdir(runsDir);
|
|
235
|
+
const runs = [];
|
|
236
|
+
for (const name of names) {
|
|
237
|
+
if (!name.endsWith(".json") || name.startsWith(".")) {
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
const run = parseRunRecord(await readJson(join(runsDir, name)));
|
|
241
|
+
if (run.job_id !== jobId) {
|
|
242
|
+
throw new JobStoreError(`run job_id mismatch: ${name}`);
|
|
243
|
+
}
|
|
244
|
+
if (`${run.run_id}.json` !== name) {
|
|
245
|
+
throw new JobStoreError(`run_id mismatch: ${name}`);
|
|
246
|
+
}
|
|
247
|
+
runs.push(run);
|
|
248
|
+
}
|
|
249
|
+
runs.sort((a, b) => a.submitted_at.localeCompare(b.submitted_at) || a.run_id.localeCompare(b.run_id));
|
|
250
|
+
return runs;
|
|
251
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const URL_SPAN = /https?:\/\/\S+/gi;
|
|
2
|
+
const SIGNED_URL_MARKERS = ["x-amz-", "signature=", "sig=", "token="];
|
|
3
|
+
export class SignedUrlError extends Error {
|
|
4
|
+
constructor(message = "signed URL is not allowed") {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "SignedUrlError";
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/** Markers count only inside a URL span, not in surrounding text. */
|
|
10
|
+
function hasSignedUrl(value) {
|
|
11
|
+
const spans = value.match(URL_SPAN);
|
|
12
|
+
if (!spans) {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
return spans.some((span) => {
|
|
16
|
+
const url = span.toLowerCase();
|
|
17
|
+
return SIGNED_URL_MARKERS.some((marker) => url.includes(marker));
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
function rejectSignedUrl(value) {
|
|
21
|
+
if (hasSignedUrl(value)) {
|
|
22
|
+
throw new SignedUrlError("signed URL is not allowed");
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** Walk keys and values. Throw when a URL span carries a signing marker. */
|
|
26
|
+
export function assertNoSignedUrl(value) {
|
|
27
|
+
if (typeof value === "string") {
|
|
28
|
+
rejectSignedUrl(value);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (Array.isArray(value)) {
|
|
32
|
+
for (const item of value) {
|
|
33
|
+
assertNoSignedUrl(item);
|
|
34
|
+
}
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (value !== null && typeof value === "object") {
|
|
38
|
+
for (const [key, item] of Object.entries(value)) {
|
|
39
|
+
rejectSignedUrl(key);
|
|
40
|
+
assertNoSignedUrl(item);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|