@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,376 @@
|
|
|
1
|
+
import { errorRules } from "../contract/cloud-v1.js";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
|
+
import { SETTLE_WAIT_MS } from "./config.js";
|
|
5
|
+
import { CHARGE_UNCONFIRMED_NOTICE, GatewayError, PaidSubmitBlockedError, TokenInRequestError, scrub, } from "./errors.js";
|
|
6
|
+
import { generationCreateSchema, submitRequestSchema, } from "./types.js";
|
|
7
|
+
const MAX_RATE_LIMIT_RETRIES = 3;
|
|
8
|
+
const MAX_RETRY_WAIT_MS = 120_000;
|
|
9
|
+
const DEFAULT_BACKOFF_MS = 1_000;
|
|
10
|
+
const STATE_OF_STATUS = {
|
|
11
|
+
queued: "submitted",
|
|
12
|
+
generating: "submitted",
|
|
13
|
+
completed: "completed",
|
|
14
|
+
failed: "failed",
|
|
15
|
+
cancelled: "cancelled",
|
|
16
|
+
};
|
|
17
|
+
const BLOCKING_STATES = ["prepared", "ambiguous", "mismatch"];
|
|
18
|
+
const UNPROVEN_STATES = ["prepared", "ambiguous", "unconfirmed"];
|
|
19
|
+
/** User-facing status of a charge that is neither proven nor disproven; undefined otherwise. */
|
|
20
|
+
export function chargeNotice(attempt) {
|
|
21
|
+
return UNPROVEN_STATES.includes(attempt.state) ? CHARGE_UNCONFIRMED_NOTICE : undefined;
|
|
22
|
+
}
|
|
23
|
+
function canonicalize(value) {
|
|
24
|
+
if (Array.isArray(value)) {
|
|
25
|
+
return value.map(canonicalize);
|
|
26
|
+
}
|
|
27
|
+
if (value !== null && typeof value === "object") {
|
|
28
|
+
const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
29
|
+
return Object.fromEntries(entries.map(([key, item]) => [key, canonicalize(item)]));
|
|
30
|
+
}
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
function fingerprint(value) {
|
|
34
|
+
return JSON.stringify(canonicalize(value));
|
|
35
|
+
}
|
|
36
|
+
/** The work itself, without price pins or the legacy project tag. */
|
|
37
|
+
function workFingerprint(body) {
|
|
38
|
+
const { expected_price_credits: _credits, pricing_version: _version, project_id: _project, ...work } = body;
|
|
39
|
+
return fingerprint(work);
|
|
40
|
+
}
|
|
41
|
+
function isRefundConfirmed(attempt) {
|
|
42
|
+
// A free work has nothing to refund and reports refund_state "none".
|
|
43
|
+
return (attempt.state === "failed" || attempt.state === "cancelled") && (attempt.refund_state === "refunded" || attempt.quote.credits === 0);
|
|
44
|
+
}
|
|
45
|
+
/** Never rewrite what the user asked for: a body holding the credential is refused outright. */
|
|
46
|
+
function assertNoToken(value, secret) {
|
|
47
|
+
if (fingerprint(scrub(value, secret)) !== fingerprint(value)) {
|
|
48
|
+
throw new TokenInRequestError();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Classify a failed POST /generations. Everything not proven uncharged is ambiguous,
|
|
53
|
+
* including a 429 with no recognized code or mismatching HTTP status.
|
|
54
|
+
* 401/403 precede the server's idempotency lookup; business 404 responses follow
|
|
55
|
+
* the lookup but write no record. Neither proves an earlier request's outcome,
|
|
56
|
+
* so on replay they cannot release its reservation.
|
|
57
|
+
*/
|
|
58
|
+
export function classify(err, replay) {
|
|
59
|
+
if (!(err instanceof GatewayError) || err.kind !== "http" || !err.code)
|
|
60
|
+
return "ambiguous";
|
|
61
|
+
const row = errorRules[err.code];
|
|
62
|
+
if (!Object.hasOwn(errorRules, err.code) || !row || err.status !== row[0])
|
|
63
|
+
return "ambiguous";
|
|
64
|
+
if (row[3] === "key_rejected")
|
|
65
|
+
return "persisted_rejection";
|
|
66
|
+
if (row[1] === "rejected" && row[2] === "ambiguous")
|
|
67
|
+
return "request_rejection";
|
|
68
|
+
return row[replay ? 2 : 1];
|
|
69
|
+
}
|
|
70
|
+
/** Binding evidence is valid only in the original deployment and account. */
|
|
71
|
+
export function owns(attempt, gateway) {
|
|
72
|
+
return attempt.deployment === gateway.deployment && attempt.account_id !== undefined;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The only write path for paid generations of one job. Calls are serialized, so
|
|
76
|
+
* budget checks and blocking states cannot race.
|
|
77
|
+
*
|
|
78
|
+
* Prerequisite: exactly one PaidRunner per job, across all processes. AttemptStore
|
|
79
|
+
* has no lock, so a second writer can overspend the local budget. Z8 must guarantee
|
|
80
|
+
* the single writer; until then the main site's daily limit is the only backstop.
|
|
81
|
+
*/
|
|
82
|
+
export class PaidRunner {
|
|
83
|
+
jobId;
|
|
84
|
+
gateway;
|
|
85
|
+
store;
|
|
86
|
+
budget;
|
|
87
|
+
tokens;
|
|
88
|
+
sleep;
|
|
89
|
+
log;
|
|
90
|
+
maxRateLimitRetries;
|
|
91
|
+
maxRetryWaitMs;
|
|
92
|
+
settleWaitMs;
|
|
93
|
+
now;
|
|
94
|
+
tail = Promise.resolve();
|
|
95
|
+
constructor(options) {
|
|
96
|
+
this.jobId = options.jobId;
|
|
97
|
+
this.gateway = options.gateway;
|
|
98
|
+
this.store = options.store;
|
|
99
|
+
this.budget = options.budget;
|
|
100
|
+
this.tokens = options.tokens;
|
|
101
|
+
this.sleep = options.sleep ?? ((ms) => delay(ms));
|
|
102
|
+
this.log = options.log;
|
|
103
|
+
this.maxRateLimitRetries = options.maxRateLimitRetries ?? MAX_RATE_LIMIT_RETRIES;
|
|
104
|
+
this.maxRetryWaitMs = options.maxRetryWaitMs ?? MAX_RETRY_WAIT_MS;
|
|
105
|
+
this.settleWaitMs = options.settleWaitMs ?? SETTLE_WAIT_MS;
|
|
106
|
+
this.now = options.now ?? Date.now;
|
|
107
|
+
if (!(this.settleWaitMs > this.gateway.requestTimeoutMs)) {
|
|
108
|
+
throw new RangeError("settleWaitMs must exceed the gateway request timeout");
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** Resolves with the attempt in its latest state; inspect `state` for the outcome. */
|
|
112
|
+
submit(req) {
|
|
113
|
+
return this.serialize(async () => {
|
|
114
|
+
const work = submitRequestSchema.parse(req);
|
|
115
|
+
assertNoToken(work, await this.tokens.token());
|
|
116
|
+
const attempts = await this.store.list(this.jobId);
|
|
117
|
+
this.assertNotBlocked(attempts);
|
|
118
|
+
const me = await this.gateway.me();
|
|
119
|
+
const open = attempts.find(attempt => attempt.state === "unconfirmed" &&
|
|
120
|
+
workFingerprint(attempt.body) === workFingerprint(work));
|
|
121
|
+
if (open) {
|
|
122
|
+
if (!owns(open, this.gateway) || open.account_id !== me.user_id) {
|
|
123
|
+
throw new PaidSubmitBlockedError(this.jobId, [open.idempotency_key]);
|
|
124
|
+
}
|
|
125
|
+
return this.lookupThenReplay(open);
|
|
126
|
+
}
|
|
127
|
+
const { project_id: _projectId, ...priceRequest } = work;
|
|
128
|
+
const quote = await this.gateway.price(priceRequest);
|
|
129
|
+
const body = generationCreateSchema.parse(canonicalize({
|
|
130
|
+
...priceRequest,
|
|
131
|
+
expected_price_credits: quote.price_credits,
|
|
132
|
+
pricing_version: quote.pricing_version,
|
|
133
|
+
}));
|
|
134
|
+
this.budget.assertAllows(attempts, quote.price_credits);
|
|
135
|
+
this.assertNoUnsettledQueueFailure(attempts, body);
|
|
136
|
+
const now = new Date().toISOString();
|
|
137
|
+
const attempt = await this.save({
|
|
138
|
+
job_id: this.jobId,
|
|
139
|
+
idempotency_key: randomUUID(),
|
|
140
|
+
state: "prepared",
|
|
141
|
+
account_id: me.user_id,
|
|
142
|
+
deployment: this.gateway.deployment,
|
|
143
|
+
body,
|
|
144
|
+
quote: { credits: quote.price_credits, pricing_version: quote.pricing_version },
|
|
145
|
+
created_at: now,
|
|
146
|
+
updated_at: now,
|
|
147
|
+
});
|
|
148
|
+
return this.dispatch(attempt);
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/** Run after a restart, to retry anything ambiguous, and to look for unconfirmed charges. */
|
|
152
|
+
recover() {
|
|
153
|
+
return this.serialize(async () => {
|
|
154
|
+
const recovered = [];
|
|
155
|
+
for (const attempt of await this.store.list(this.jobId)) {
|
|
156
|
+
if (!owns(attempt, this.gateway))
|
|
157
|
+
continue;
|
|
158
|
+
if (attempt.state === "unconfirmed") {
|
|
159
|
+
recovered.push(await this.resolve(attempt));
|
|
160
|
+
}
|
|
161
|
+
else if (attempt.state === "prepared" || attempt.state === "ambiguous") {
|
|
162
|
+
// Prepared may or may not have reached the server before the crash.
|
|
163
|
+
recovered.push(await this.resolve(await this.save({ ...attempt, state: "ambiguous" })));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return recovered;
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/** Pull the server record. This is how a pending refund reaches the budget. */
|
|
170
|
+
refresh(idempotencyKey) {
|
|
171
|
+
return this.serialize(async () => {
|
|
172
|
+
const attempt = await this.tracked(idempotencyKey);
|
|
173
|
+
if (!owns(attempt, this.gateway))
|
|
174
|
+
return attempt;
|
|
175
|
+
return this.apply(attempt, await this.gateway.get(attempt.generation_id));
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
/** Records whatever the server returns; a cancel by itself proves no refund. */
|
|
179
|
+
cancel(idempotencyKey) {
|
|
180
|
+
return this.serialize(async () => {
|
|
181
|
+
const attempt = await this.tracked(idempotencyKey);
|
|
182
|
+
if (!owns(attempt, this.gateway))
|
|
183
|
+
return attempt;
|
|
184
|
+
return this.apply(attempt, await this.gateway.cancel(attempt.generation_id));
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
serialize(task) {
|
|
188
|
+
const run = this.tail.then(task);
|
|
189
|
+
this.tail = run.catch(() => undefined);
|
|
190
|
+
return run;
|
|
191
|
+
}
|
|
192
|
+
assertNotBlocked(attempts) {
|
|
193
|
+
const blockers = attempts.filter((attempt) => BLOCKING_STATES.includes(attempt.state));
|
|
194
|
+
if (blockers.length > 0) {
|
|
195
|
+
throw new PaidSubmitBlockedError(this.jobId, blockers.map((attempt) => `${attempt.idempotency_key}:${attempt.state}`), blockers.map(chargeNotice).find((notice) => notice !== undefined));
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** docs section 6: the same work gets a new key only once the failed one is refunded. */
|
|
199
|
+
assertNoUnsettledQueueFailure(attempts, body) {
|
|
200
|
+
const fingerprint = workFingerprint(body);
|
|
201
|
+
const held = attempts.filter((attempt) => attempt.queue_unavailable === true &&
|
|
202
|
+
!isRefundConfirmed(attempt) &&
|
|
203
|
+
workFingerprint(attempt.body) === fingerprint);
|
|
204
|
+
if (held.length > 0) {
|
|
205
|
+
throw new PaidSubmitBlockedError(this.jobId, held.map((attempt) => `${attempt.idempotency_key}:queue_unavailable`));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
async tracked(idempotencyKey) {
|
|
209
|
+
const attempts = await this.store.list(this.jobId);
|
|
210
|
+
const attempt = attempts.find((item) => item.idempotency_key === idempotencyKey);
|
|
211
|
+
if (!attempt || (owns(attempt, this.gateway) && attempt.generation_id === undefined)) {
|
|
212
|
+
throw new Error(`attempt ${idempotencyKey} has no server record`);
|
|
213
|
+
}
|
|
214
|
+
return attempt;
|
|
215
|
+
}
|
|
216
|
+
async save(attempt) {
|
|
217
|
+
const secret = await this.tokens.token();
|
|
218
|
+
assertNoToken(attempt.body, secret);
|
|
219
|
+
const next = scrub({ ...attempt, updated_at: new Date().toISOString() }, secret);
|
|
220
|
+
await this.store.put(next);
|
|
221
|
+
this.log?.(scrub({ event: "attempt", state: next.state }, secret));
|
|
222
|
+
return next;
|
|
223
|
+
}
|
|
224
|
+
async dispatch(prepared) {
|
|
225
|
+
const result = await this.post(prepared, false);
|
|
226
|
+
const { attempt } = result;
|
|
227
|
+
switch (result.kind) {
|
|
228
|
+
case "created":
|
|
229
|
+
return this.apply(attempt, result.generation);
|
|
230
|
+
case "persisted_rejection":
|
|
231
|
+
case "request_rejection":
|
|
232
|
+
case "rejected":
|
|
233
|
+
return this.reject(attempt, result.code);
|
|
234
|
+
case "queue_unavailable":
|
|
235
|
+
return this.resolve(await this.save({ ...attempt, state: "ambiguous", queue_unavailable: true }));
|
|
236
|
+
case "ambiguous":
|
|
237
|
+
return this.resolve(await this.save({ ...attempt, state: "ambiguous" }));
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Same key and same body on every path. Only the caller's next submit mints a new key.
|
|
242
|
+
* sent_at is durable before each send: a crash mid-request must not lose when it left.
|
|
243
|
+
*/
|
|
244
|
+
async post(start, replay) {
|
|
245
|
+
if (!owns(start, this.gateway))
|
|
246
|
+
throw new Error("attempt binding invariant violated");
|
|
247
|
+
let attempt = start;
|
|
248
|
+
for (let retries = 0;; retries += 1) {
|
|
249
|
+
attempt = await this.save({ ...attempt, sent_at: new Date(this.now()).toISOString() });
|
|
250
|
+
try {
|
|
251
|
+
const generation = await this.gateway.submit(attempt.body, attempt.idempotency_key, attempt.account_id);
|
|
252
|
+
return { attempt, kind: "created", generation };
|
|
253
|
+
}
|
|
254
|
+
catch (err) {
|
|
255
|
+
const verdict = classify(err, replay);
|
|
256
|
+
if (verdict === "rejected" || verdict === "persisted_rejection" || verdict === "request_rejection") {
|
|
257
|
+
return { attempt, kind: verdict, code: err.code ?? "rejected" };
|
|
258
|
+
}
|
|
259
|
+
if (verdict !== "retry") {
|
|
260
|
+
return { attempt, kind: verdict };
|
|
261
|
+
}
|
|
262
|
+
const { retryAfterMs, code } = err;
|
|
263
|
+
const waitMs = retryAfterMs ?? DEFAULT_BACKOFF_MS * 2 ** retries;
|
|
264
|
+
if (retries >= this.maxRateLimitRetries || waitMs > this.maxRetryWaitMs) {
|
|
265
|
+
// A 429 precedes any charge, but on a replay it also precedes the lookup.
|
|
266
|
+
return replay
|
|
267
|
+
? { attempt, kind: errorRules.rate_limited[5].replay }
|
|
268
|
+
: { attempt, kind: errorRules.rate_limited[5].first, code: code ?? "rate_limited" };
|
|
269
|
+
}
|
|
270
|
+
await this.sleep(waitMs);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
resolve(attempt) {
|
|
275
|
+
return attempt.settle_after === undefined
|
|
276
|
+
? this.lookupThenReplay(attempt)
|
|
277
|
+
: this.settle(attempt, attempt.settle_after);
|
|
278
|
+
}
|
|
279
|
+
/** Replay only on a definite attempt_not_found. The state stays as it is otherwise. */
|
|
280
|
+
async lookupThenReplay(attempt) {
|
|
281
|
+
const found = await this.lookup(attempt);
|
|
282
|
+
if (found !== "missing") {
|
|
283
|
+
return found === "unknown" ? attempt : "rejected" in found ? this.reject(attempt, found.rejected) : this.apply(attempt, found);
|
|
284
|
+
}
|
|
285
|
+
const result = await this.post(attempt, true);
|
|
286
|
+
switch (result.kind) {
|
|
287
|
+
case "created":
|
|
288
|
+
return this.apply(result.attempt, result.generation);
|
|
289
|
+
case "persisted_rejection":
|
|
290
|
+
return this.reject(result.attempt, result.code);
|
|
291
|
+
case "request_rejection":
|
|
292
|
+
case "rejected":
|
|
293
|
+
return this.awaitLateOriginal(attempt, result.code);
|
|
294
|
+
case "queue_unavailable":
|
|
295
|
+
case "ambiguous": {
|
|
296
|
+
const { settle_after: _settle, rejected_code: _code, ...fresh } = result.attempt;
|
|
297
|
+
return this.save({ ...fresh, state: "ambiguous" });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* A replay rejection only speaks for the replay: the earlier send may still land and
|
|
303
|
+
* charge. So nothing is released, and only a same-body submit sends another POST.
|
|
304
|
+
* `attempt` is the pre-replay record, so sent_at is the last send with no verdict.
|
|
305
|
+
*/
|
|
306
|
+
awaitLateOriginal(attempt, code) {
|
|
307
|
+
const sentAt = Date.parse(attempt.sent_at ?? attempt.created_at);
|
|
308
|
+
const settleAfter = sentAt + this.settleWaitMs;
|
|
309
|
+
const expired = attempt.state === "unconfirmed" || this.now() >= settleAfter;
|
|
310
|
+
return this.save({
|
|
311
|
+
...attempt,
|
|
312
|
+
state: expired ? "unconfirmed" : "ambiguous",
|
|
313
|
+
rejected_code: code,
|
|
314
|
+
settle_after: new Date(settleAfter).toISOString(),
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* A found record wins at any time. A miss proves nothing, however late: after the wait
|
|
319
|
+
* the attempt stops blocking but keeps its budget until the server says otherwise.
|
|
320
|
+
*/
|
|
321
|
+
async settle(attempt, settleAfter) {
|
|
322
|
+
const found = await this.lookup(attempt);
|
|
323
|
+
if (found === "unknown") {
|
|
324
|
+
return attempt;
|
|
325
|
+
}
|
|
326
|
+
if (found !== "missing") {
|
|
327
|
+
return "rejected" in found ? this.reject(attempt, found.rejected) : this.apply(attempt, found);
|
|
328
|
+
}
|
|
329
|
+
return attempt.state === "ambiguous" && this.now() >= Date.parse(settleAfter)
|
|
330
|
+
? this.save({ ...attempt, state: "unconfirmed" })
|
|
331
|
+
: attempt;
|
|
332
|
+
}
|
|
333
|
+
async lookup(attempt) {
|
|
334
|
+
try {
|
|
335
|
+
return await this.gateway.getAttempt(attempt.idempotency_key, attempt.account_id);
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
if (err instanceof GatewayError && classify(err, true) === "persisted_rejection") {
|
|
339
|
+
return { rejected: err.code };
|
|
340
|
+
}
|
|
341
|
+
const missing = err instanceof GatewayError && err.status === 404 && err.code === "attempt_not_found";
|
|
342
|
+
return missing ? "missing" : "unknown";
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
reject(current, code) {
|
|
346
|
+
const { queue_unavailable: _queue, settle_after: _settle, rejected_code: _code, ...attempt } = current;
|
|
347
|
+
return this.save({ ...attempt, state: "rejected", rejected_code: code });
|
|
348
|
+
}
|
|
349
|
+
apply(current, generation) {
|
|
350
|
+
if (generation.attempt_id !== current.idempotency_key) {
|
|
351
|
+
return this.save({ ...current, state: "mismatch", refund_state: "unknown",
|
|
352
|
+
charged_credits: Math.max(current.charged_credits ?? current.quote.credits, current.quote.credits) });
|
|
353
|
+
}
|
|
354
|
+
if (current.state === "mismatch" || generation.reserved_credits !== current.quote.credits ||
|
|
355
|
+
(generation.charged_credits !== null && generation.charged_credits > generation.reserved_credits)) {
|
|
356
|
+
return this.save({ ...current, generation_id: generation.id, status: generation.status, state: "mismatch", refund_state: "unknown",
|
|
357
|
+
charged_credits: Math.max(current.quote.credits, generation.reserved_credits, generation.charged_credits ?? 0, current.charged_credits ?? 0) });
|
|
358
|
+
}
|
|
359
|
+
const final = (status, refund, charge) => charge != null && ((status === "completed" && refund === "none") ||
|
|
360
|
+
((status === "failed" || status === "cancelled") &&
|
|
361
|
+
(refund === "not_refunded" || (refund === "refunded" && charge === 0))));
|
|
362
|
+
if (final(current.status, current.refund_state, current.charged_credits))
|
|
363
|
+
return Promise.resolve(current);
|
|
364
|
+
if (current.status && ["completed", "failed", "cancelled"].includes(current.status) &&
|
|
365
|
+
generation.status !== current.status)
|
|
366
|
+
return Promise.resolve(current);
|
|
367
|
+
const definite = final(generation.status, generation.refund_state, generation.charged_credits);
|
|
368
|
+
const { settle_after: _settle, rejected_code: _code, ...attempt } = current;
|
|
369
|
+
return this.save({
|
|
370
|
+
...attempt, state: STATE_OF_STATUS[generation.status], generation_id: generation.id, status: generation.status,
|
|
371
|
+
charged_credits: definite ? generation.charged_credits : null,
|
|
372
|
+
refund_state: definite ? generation.refund_state :
|
|
373
|
+
["refunded", "not_refunded"].includes(generation.refund_state) ? "unknown" : generation.refund_state,
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { isSafeId } from "../core/index.js";
|
|
3
|
+
import { priceRequestSchema, generationCreateSchema, uploadRequestSchema, meSchema, catalogSchema, priceSchema, generationSchema, uploadTicketSchema, assetStatusSchema, deviceBindingSchema, deviceTokenSchema } from "../contract/cloud-v1.js";
|
|
4
|
+
export { priceRequestSchema, generationCreateSchema, uploadRequestSchema, meSchema, catalogSchema, priceSchema, generationSchema, uploadTicketSchema, assetStatusSchema, deviceBindingSchema, deviceTokenSchema };
|
|
5
|
+
const uuid = z.guid();
|
|
6
|
+
const int = z.number().int();
|
|
7
|
+
const safeId = z.string().refine(isSafeId);
|
|
8
|
+
const generationStatuses = ["queued", "generating", "completed", "failed", "cancelled"];
|
|
9
|
+
export const submitRequestSchema = priceRequestSchema.extend({ project_id: uuid.nullable().default(null) });
|
|
10
|
+
export const attemptStates = [
|
|
11
|
+
"prepared",
|
|
12
|
+
"ambiguous",
|
|
13
|
+
"unconfirmed",
|
|
14
|
+
"submitted",
|
|
15
|
+
"completed",
|
|
16
|
+
"failed",
|
|
17
|
+
"cancelled",
|
|
18
|
+
"rejected",
|
|
19
|
+
"mismatch",
|
|
20
|
+
];
|
|
21
|
+
/** Durable record. Holds no output URL, upload URL or server error text. */
|
|
22
|
+
export const attemptSchema = z.strictObject({
|
|
23
|
+
job_id: safeId,
|
|
24
|
+
idempotency_key: safeId,
|
|
25
|
+
state: z.enum(attemptStates),
|
|
26
|
+
body: generationCreateSchema.extend({ project_id: uuid.nullable().optional() }),
|
|
27
|
+
account_id: uuid.optional(),
|
|
28
|
+
deployment: z.string().optional(),
|
|
29
|
+
quote: z.strictObject({ credits: int.min(0), pricing_version: z.string().min(1) }),
|
|
30
|
+
created_at: z.string(),
|
|
31
|
+
updated_at: z.string(),
|
|
32
|
+
generation_id: uuid.optional(),
|
|
33
|
+
status: z.enum(generationStatuses).optional(),
|
|
34
|
+
charged_credits: int.nullable().optional(),
|
|
35
|
+
refund_state: z.string().optional(),
|
|
36
|
+
rejected_code: z.string().optional(),
|
|
37
|
+
queue_unavailable: z.boolean().optional(),
|
|
38
|
+
/** When the latest POST left. Written before that POST, so a crash cannot lose it. */
|
|
39
|
+
sent_at: z.string().optional(),
|
|
40
|
+
/** Set once a replay was rejected: until this time has passed the attempt blocks the job. */
|
|
41
|
+
settle_after: z.string().optional(),
|
|
42
|
+
});
|