Resume a video API task: bounded polling and verified download
A complete inline Node.js 24 client that resumes an existing public API task, handles 429 and terminal states, and saves output with a checkpoint, size limit and SHA-256. Includes 24 executed localhost fixture scenarios.
Recover a known public API task after a client restart, finish polling within a fixed budget, and save one verifiable local output without submitting another generation.
Previously recorded numerical observations below describe the original local fixture runs. For a reproduction, use the new receipt and its actual tool versions and hashes; an old observation is not a guaranteed result on every installation.
Preparation
- Save client.mjs and run-fixture.mjs from the complete code blocks below in one empty local folder. Run node run-fixture.mjs there: it constructs all synthetic bytes and request cases itself. The existing-task command later in this page is a separate user-operated step and needs the stated task ID and credential.
- Use Node.js 24 and save both complete scripts below in the same folder.
- Choose an existing public API task ID and its owner’s API key; browser-generated tasks may be outside this endpoint’s scope.
- Set SEEDANCE_API_KEY only in the server-side process environment, then choose a controlled output directory.
- Verify the exact managed HTTPS media origin before allowing a delivery host different from minimaxh3.studio.
Run the offline contract fixture
Execute node run-fixture.mjs first. Its server uses only 127.0.0.1 and synthetic MP4-prefix bytes. The recorded Node v24.14.0 run passed 24 scenarios; this tests client control flow, not generation or video playback.
Resume the original task ID
Run node client.mjs --task YOUR_EXISTING_API_TASK_ID --out ./saved-video. The client uses only GET /api/v1/tasks/{id}; a restart never submits a new video-generation request. Checkpoint data excludes credentials, raw responses and delivery URLs.
Handle the exact public statuses
Read the direct task object, without a data envelope. processing keeps polling; completed requires output.video_url; failed exits with the task error code. A missing or differently owned public API task returns 404 and stops.
Keep retries within a finite budget
Normal polling waits five seconds. 429 and 503 respect a bounded Retry-After or exponential fallback; all requests share a ten-minute deadline and a 120-request limit. A timeout is a reason to inspect and resume the existing task, not to replace it.
Download only from a verified origin
If required, add --media-origin https://YOUR_VERIFIED_MEDIA_HOST after checking the managed delivery origin. Download requests carry no API key and reject redirects, URL user information, unexpected hosts and non-MP4 Content-Type.
Verify the local file and retain the checkpoint
Media is streamed through an exclusive temporary file with a 256 MiB default limit. The client checks its MP4 ftyp prefix and SHA-256, refuses overwrite, and records final bytes/hash. Re-running a completed checkpoint first verifies the saved file. A real video still needs separate playback and content review.
Acceptance
- The fixture passes all 24 recorded scenarios, uses only localhost GET requests, and closes its server after completion.
- The original task ID survives restart; no POST or paid task submission is present in the client.
- Checkpoint files contain no API key, raw task response or signed delivery URL.
- The completed local copy matches its recorded byte count and SHA-256; partial media is removed after a rejected download.
- 401/404, terminal failure, poll/deadline exhaustion, unapproved hosts, redirects, unsafe names/symlinks, oversize output and checksum mismatch stop without a replacement generation.
Troubleshooting
A valid-looking task returns not_found.
Confirm it was created by the public API and belongs to the same API key owner. Do not assume browser tasks are queryable here or generate a replacement automatically.
Polling reaches its deadline while the task is processing.
Keep the checkpoint, inspect service state, then rerun with the same task ID. Adjust --timeout-ms only within a finite operating budget.
The result URL is blocked or the saved file fails validation.
Verify the actual managed media origin, expected size and MP4 format before modifying --media-origin or --max-bytes. Supply --sha256 only with an independently trusted hash.
The task reports failed and a refund is expected.
Inspect the actual error, credits_refunded and billing_status separately. The local fixture does not verify live billing and the client neither submits another task nor executes a refund.
Keep with the result
The source-backed API contract and executed fixture establish how the client resumes, stops and saves bytes. Live credentials, provider completion, billing/refunds, video decoding and model quality remain untested; validate those with a known existing task before production integration.
Complete source and input construction
Save every file below with its exact filename in the same folder. The source includes the input definitions and construction logic; code blocks are complete, including all companion modules.
client.mjs
#!/usr/bin/env node
// Resume an existing public API task. There is intentionally no POST operation.
import { createHash, randomUUID } from 'node:crypto';
import { constants } from 'node:fs';
import { mkdir, lstat, readFile, open, rename, unlink, link, realpath } from 'node:fs/promises';
import { resolve, join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { setTimeout as pause } from 'node:timers/promises';
export class RecipeError extends Error {
constructor(code) { super(code); this.name = 'RecipeError'; this.code = code; }
}
const reject = (code) => { throw new RecipeError(code); };
const validId = (value) => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,120}$/.test(value);
const validName = (value) => typeof value === 'string' && /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{0,119}$/.test(value) && !value.includes('..');
const safeCode = (value, fallback) => typeof value === 'string' && /^[a-z_]{1,64}$/.test(value) ? value : fallback;
const finiteInteger = (value, min, max) => Number.isSafeInteger(value) && value >= min && value <= max;
async function existsRegular(path) {
try { const stat = await lstat(path); if (!stat.isFile() || stat.isSymbolicLink()) reject('unsafe_file'); return true; }
catch (error) { if (error.code === 'ENOENT') return false; throw error; }
}
async function checkpoint(path, state) {
await existsRegular(path);
const tmp = `${path}.${randomUUID()}.tmp`;
let handle;
try {
handle = await open(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
await handle.writeFile(`${JSON.stringify(state, null, 2)}\n`);
await handle.sync(); await handle.close(); handle = null;
await rename(tmp, path);
} finally { await handle?.close(); await unlink(tmp).catch(() => {}); }
}
async function boundedJson(response, maxBytes = 65536) {
const parts = []; let size = 0;
for await (const part of response.body) { size += part.length; if (size > maxBytes) { reject('response_too_large'); } parts.push(part); }
try { return JSON.parse(Buffer.concat(parts).toString('utf8')); } catch { reject('invalid_response'); }
}
function allowedOrigin(input, fixture) {
let url;
try { url = new URL(input); } catch { reject('invalid_origin'); }
const loopback = fixture && url.protocol === 'http:' && url.hostname === '127.0.0.1';
if (!(url.protocol === 'https:' || loopback) || url.username || url.password || url.pathname !== '/' || url.search || url.hash) reject('invalid_origin');
return url.origin;
}
function retryDelay(response, defaultMs, maximumMs) {
const raw = response.headers.get('retry-after');
if (!raw) return Math.min(defaultMs, maximumMs);
const seconds = Number(raw);
const ms = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : Date.parse(raw) - Date.now();
return Number.isFinite(ms) && ms >= 0 ? Math.min(ms, maximumMs) : Math.min(defaultMs, maximumMs);
}
export async function resumeTask(options) {
const {
taskId, apiKey, outputDirectory, apiOrigin = 'https://minimaxh3.studio',
allowedMediaOrigins = ['https://minimaxh3.studio'],
filename = `${taskId}.mp4`, checkpointName = `${taskId}.checkpoint.json`,
timeoutMs = 600000, requestTimeoutMs = 30000, pollIntervalMs = 5000,
maxPolls = 120, maxDownloadBytes = 256 * 1024 * 1024, expectedSha256,
fixtureMode = false,
} = options;
if (!validId(taskId) || !validName(filename) || !validName(checkpointName) || filename === checkpointName) reject('invalid_task_or_path');
if (typeof apiKey !== 'string' || !apiKey || /[\r\n]/.test(apiKey)) reject('missing_api_key');
if (!outputDirectory || !finiteInteger(timeoutMs, 1, 3600000) || !finiteInteger(requestTimeoutMs, 1, 60000) || !finiteInteger(pollIntervalMs, fixtureMode ? 0 : 2000, 60000) || !finiteInteger(maxPolls, 1, 1000) || !finiteInteger(maxDownloadBytes, 1, 256 * 1024 * 1024)) reject('invalid_limits');
if (expectedSha256 && !/^[a-f0-9]{64}$/.test(expectedSha256)) reject('invalid_checksum');
const origin = allowedOrigin(apiOrigin, fixtureMode);
// Production API credentials are only sent to this audited API origin.
if (!fixtureMode && origin !== 'https://minimaxh3.studio') reject('unapproved_api_origin');
const approved = new Set(allowedMediaOrigins.map(value => allowedOrigin(value, fixtureMode)));
const requestedDirectory = resolve(outputDirectory);
await mkdir(requestedDirectory, { recursive: true, mode: 0o700 });
const directoryStat = await lstat(requestedDirectory);
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) reject('unsafe_directory');
const directory = await realpath(requestedDirectory);
const destination = join(directory, filename);
const checkpointPath = join(directory, checkpointName);
let prior;
if (await existsRegular(checkpointPath)) {
const stat = await lstat(checkpointPath); if (stat.size > 4096) reject('invalid_checkpoint');
try { prior = JSON.parse(await readFile(checkpointPath, 'utf8')); } catch { reject('invalid_checkpoint'); }
if (prior.schemaVersion !== 1 || prior.taskId !== taskId || !['processing', 'completed', 'failed'].includes(prior.lastStatus)) reject('checkpoint_task_mismatch');
}
// A completed local copy may be reused only after its recorded bytes/hash match.
if (await existsRegular(destination)) {
const stat = await lstat(destination);
if (!prior?.download || prior.download.filename !== filename || stat.size > maxDownloadBytes || stat.size !== prior.download.bytes) reject('output_exists');
const handle = await open(destination, constants.O_RDONLY | constants.O_NOFOLLOW);
const hash = createHash('sha256');
try { for await (const chunk of handle.createReadStream()) hash.update(chunk); } finally { await handle.close().catch(() => {}); }
const checksum = hash.digest('hex');
if (checksum !== prior.download.sha256 || (expectedSha256 && checksum !== expectedSha256)) reject('checksum_mismatch');
return { taskId, status: 'completed', resumedLocalFile: true, download: prior.download };
}
const deadline = Date.now() + timeoutMs;
const remaining = () => { const left = deadline - Date.now(); if (left <= 0) reject('deadline_exceeded'); return left; };
const wait = async (ms) => { if (ms >= remaining()) reject('deadline_exceeded'); if (ms) await pause(ms); };
const request = async (url, headers) => {
try { return await fetch(url, { headers, redirect: 'manual', signal: AbortSignal.timeout(Math.min(remaining(), requestTimeoutMs)) }); }
catch (error) { if (error instanceof RecipeError) throw error; reject(Date.now() >= deadline ? 'deadline_exceeded' : 'request_failed'); }
};
let task;
for (let count = 1; count <= maxPolls; count++) {
const response = await request(`${origin}/api/v1/tasks/${taskId}`, { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' });
if (response.status === 429 || response.status === 503) {
await response.body?.cancel();
if (count === maxPolls) reject('poll_limit_exceeded');
await wait(retryDelay(response, pollIntervalMs * Math.min(2 ** (count - 1), 8), 60000)); continue;
}
if (!response.ok) {
const body = await boundedJson(response);
reject(safeCode(body?.error?.code, 'http_error'));
}
task = await boundedJson(response);
if (task?.id !== taskId || !['processing', 'completed', 'failed'].includes(task.status)) reject('invalid_task_response');
// Save only identifiers and state; never persist raw response, output URL, or key.
await checkpoint(checkpointPath, { schemaVersion: 1, taskId, lastStatus: task.status, updatedAt: new Date().toISOString() });
if (task.status === 'failed') reject(`task_failed_${safeCode(task.error?.code, 'generation_failed')}`);
if (task.status === 'completed') break;
if (count === maxPolls) reject('poll_limit_exceeded');
await wait(pollIntervalMs);
}
let media;
try { media = new URL(task.output?.video_url); } catch { reject('missing_output_url'); }
if (media.username || media.password || media.hash || !approved.has(media.origin)) reject('unapproved_output_url');
// No Authorization header is ever forwarded to media hosts; redirects are refused.
const response = await request(media.href, { Accept: 'video/mp4' });
if (!response.ok || response.status !== 200) { await response.body?.cancel(); reject('download_http_error'); }
const length = response.headers.get('content-length');
if (length && (!/^\d+$/.test(length) || Number(length) > maxDownloadBytes)) { await response.body?.cancel(); reject('download_too_large'); }
if (response.headers.get('content-type')?.split(';')[0].trim() !== 'video/mp4') { await response.body?.cancel(); reject('invalid_media_type'); }
const tmp = join(directory, `.${filename}.${randomUUID()}.part`);
const hash = createHash('sha256'); let handle; let bytes = 0; let prefix = Buffer.alloc(0);
try {
handle = await open(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
for await (const chunk of response.body) {
remaining(); bytes += chunk.length;
if (bytes > maxDownloadBytes) reject('download_too_large');
if (prefix.length < 12) prefix = Buffer.concat([prefix, chunk]).subarray(0, 12);
hash.update(chunk);
let offset = 0;
while (offset < chunk.length) {
const written = await handle.write(chunk, offset, chunk.length - offset);
if (!written.bytesWritten) reject('write_failed');
offset += written.bytesWritten;
}
}
if (bytes < 12 || prefix.toString('ascii', 4, 8) !== 'ftyp') reject('invalid_mp4_prefix');
const sha256 = hash.digest('hex');
if (expectedSha256 && expectedSha256 !== sha256) reject('checksum_mismatch');
await handle.sync(); await handle.close(); handle = null;
// link() publishes atomically and refuses to replace an existing file/symlink.
await link(tmp, destination);
const download = { filename, bytes, sha256 };
await checkpoint(checkpointPath, { schemaVersion: 1, taskId, lastStatus: 'completed', updatedAt: new Date().toISOString(), download });
return { taskId, status: 'completed', resumedLocalFile: false, download };
} catch (error) { if (error.code === 'EEXIST') reject('output_exists'); throw error; }
finally { await handle?.close(); await unlink(tmp).catch(() => {}); }
}
async function cli() {
const args = process.argv.slice(2); const values = {};
const allowed = new Set(['task', 'out', 'media-origin', 'sha256', 'timeout-ms', 'max-bytes']);
for (let i = 0; i < args.length; i += 2) {
const key = args[i]?.replace(/^--/, '');
if (!args[i]?.startsWith('--') || !allowed.has(key) || !args[i + 1] || values[key] !== undefined) reject('invalid_arguments');
values[key] = args[i + 1];
}
const result = await resumeTask({ taskId: values.task, apiKey: process.env.SEEDANCE_API_KEY, outputDirectory: values.out,
allowedMediaOrigins: values['media-origin'] ? [values['media-origin']] : ['https://minimaxh3.studio'],
expectedSha256: values.sha256, timeoutMs: values['timeout-ms'] ? Number(values['timeout-ms']) : undefined,
maxDownloadBytes: values['max-bytes'] ? Number(values['max-bytes']) : undefined });
process.stdout.write(`${JSON.stringify(result)}\n`);
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
cli().catch(error => { process.stderr.write(`${error instanceof RecipeError ? error.code : 'client_error'}\n`); process.exitCode = 1; });
}
run-fixture.mjs
#!/usr/bin/env node
// Synthetic localhost contract tests. No provider, paid task, or external request.
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { mkdtemp, mkdir, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { resumeTask, RecipeError } from './client.mjs';
const directory = await mkdtemp(join(tmpdir(), 'pseo-async-fixture-'));
const plans = new Map(); const requests = []; const scenarios = [];
const fakeCredential = 'fixture-only-not-a-real-api-key';
const media = Buffer.alloc(64); media.writeUInt32BE(24, 0); media.write('ftypisom', 4, 'ascii');
const checksum = createHash('sha256').update(media).digest('hex');
let origin;
function payload(id, status = 'completed', overrides = {}) {
return { id, status, model: 'seedance-2.0-fast', mode: 'text-to-video', credits_used: 250,
credits_refunded: 0, billing_status: status === 'completed' ? 'settled' : 'reserved',
output: status === 'completed' ? { video_url: `${origin}/media/${id}.mp4` } : null,
error: status === 'failed' ? { code: 'generation_failed', message: 'Synthetic failure' } : null,
created_at: '2026-10-14T00:00:00.000Z', updated_at: '2026-10-14T00:00:01.000Z', ...overrides };
}
const server = createServer((request, response) => {
try {
const url = new URL(request.url, origin);
requests.push({ method: request.method, path: url.pathname, authorizationPresent: Boolean(request.headers.authorization) });
if (request.method !== 'GET') { response.writeHead(405).end(); return; }
const apiMatch = /^\/api\/v1\/tasks\/([a-zA-Z0-9_-]+)$/.exec(url.pathname);
if (apiMatch) {
if (request.headers.authorization !== `Bearer ${fakeCredential}`) { response.writeHead(401, { 'content-type': 'application/json' }).end(JSON.stringify({ error: { code: 'unauthorized', message: 'Synthetic' } })); return; }
const id = apiMatch[1]; const plan = plans.get(id); const index = plan.apiCalls++;
const action = plan.sequence[Math.min(index, plan.sequence.length - 1)];
if (typeof action === 'number') {
response.writeHead(action, { 'content-type': 'application/json', 'Retry-After': plan.retryAfter ?? '0' }).end(JSON.stringify({ error: { code: action === 429 ? 'rate_limited' : action === 404 ? 'not_found' : 'service_busy', message: 'Synthetic' } })); return;
}
response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(payload(id, action, plan.overrides))); return;
}
const mediaMatch = /^\/media\/([a-zA-Z0-9_-]+)\.mp4$/.exec(url.pathname);
if (mediaMatch) {
const plan = plans.get(mediaMatch[1]); plan.mediaCalls++;
if (plan.redirect) { response.writeHead(302, { Location: `${origin}/media/unexpected.mp4` }).end(); return; }
const bytes = plan.invalidPrefix ? Buffer.alloc(64) : plan.large ? Buffer.concat([media, media]) : media;
const headers = { 'content-type': plan.mime ?? 'video/mp4' };
if (!plan.chunked) headers['content-length'] = String(bytes.length);
response.writeHead(200, headers).end(bytes); return;
}
response.writeHead(404).end();
} catch { response.writeHead(500).end(); }
});
const currentDir = dirname(fileURLToPath(import.meta.url));
const receiptPath = process.argv[2] ? resolve(process.argv[2]) : join(currentDir, 'execution-receipt.json');
async function run(name, plan, expectedCode, extra = {}, before) {
const id = name.replaceAll('-', '_');
const out = join(directory, id); await mkdir(out);
const actual = { sequence: ['completed'], apiCalls: 0, mediaCalls: 0, ...plan }; plans.set(id, actual);
const options = { taskId: id, apiKey: fakeCredential, outputDirectory: out, apiOrigin: origin,
allowedMediaOrigins: [origin], fixtureMode: true, timeoutMs: 1000, requestTimeoutMs: 500,
pollIntervalMs: 0, maxPolls: 8, expectedSha256: checksum, ...extra };
await before?.(out, id);
let result;
if (expectedCode) {
await assert.rejects(resumeTask(options), error => error instanceof RecipeError && error.code === expectedCode);
assert.equal((await readdir(out)).some(file => file.endsWith('.part')), false, 'temporary media cleaned');
} else {
result = await resumeTask(options);
assert.equal(result.status, 'completed'); assert.equal(result.download.sha256, checksum);
assert.deepEqual(await readFile(join(out, `${id}.mp4`)), media);
const savedText = await readFile(join(out, `${id}.checkpoint.json`), 'utf8');
assert.equal(savedText.includes(fakeCredential), false); assert.equal(savedText.includes('video_url'), false);
assert.equal(savedText.includes(origin), false);
const saved = JSON.parse(savedText); assert.equal(saved.taskId, id); assert.equal(saved.download.bytes, 64);
}
scenarios.push({ name, passed: true, expectedOutcome: expectedCode || 'completed', apiGets: actual.apiCalls, mediaGets: actual.mediaCalls });
return { options, actual, result, out, id };
}
try {
await new Promise((done, fail) => { server.once('error', fail); server.listen(0, '127.0.0.1', done); });
origin = `http://127.0.0.1:${server.address().port}`;
await run('processing-to-completed', { sequence: ['processing', 'processing', 'completed'] });
await run('resume-existing-checkpoint', { sequence: ['completed'] }, null, {}, async (out, id) => {
await writeFile(join(out, `${id}.checkpoint.json`), JSON.stringify({ schemaVersion: 1, taskId: id, lastStatus: 'processing' }));
});
const completed = await run('completed-local-file-reuse', {});
const priorGets = completed.actual.apiCalls;
const reused = await resumeTask(completed.options);
assert.equal(reused.resumedLocalFile, true); assert.equal(completed.actual.apiCalls, priorGets);
await run('rate-limit-retry', { sequence: [429, 'processing', 'completed'] });
await run('service-busy-retry', { sequence: [503, 'completed'] });
await run('terminal-failure', { sequence: ['failed'] }, 'task_failed_generation_failed');
await run('poll-attempt-limit', { sequence: ['processing'] }, 'poll_limit_exceeded', { maxPolls: 3 });
await run('deadline-retry-after', { sequence: [429], retryAfter: '60' }, 'deadline_exceeded', { timeoutMs: 10 });
await run('ownership-not-found', { sequence: [404] }, 'not_found');
await run('unauthorized-key', {}, 'unauthorized', { apiKey: 'different-fixture-only-value' });
await run('unknown-status', { sequence: ['succeeded'] }, 'invalid_task_response');
await run('task-id-mismatch', { overrides: { id: 'another_task' } }, 'invalid_task_response');
await run('missing-output', { overrides: { output: null } }, 'missing_output_url');
await run('unapproved-media-host', { overrides: { output: { video_url: 'https://unapproved.invalid/test.mp4' } } }, 'unapproved_output_url');
await run('media-url-userinfo', { overrides: { output: { video_url: 'https://user:secret@minimaxh3.studio/test.mp4' } } }, 'unapproved_output_url');
await run('download-redirect-refused', { redirect: true }, 'download_http_error');
await run('media-content-type', { mime: 'text/html' }, 'invalid_media_type');
await run('media-invalid-mp4-prefix', { invalidPrefix: true }, 'invalid_mp4_prefix');
await run('download-header-size-limit', { large: true }, 'download_too_large', { maxDownloadBytes: 64 });
await run('download-stream-size-limit', { large: true, chunked: true }, 'download_too_large', { maxDownloadBytes: 64 });
await run('expected-checksum-mismatch', {}, 'checksum_mismatch', { expectedSha256: '0'.repeat(64) });
await run('path-traversal-refused', {}, 'invalid_task_or_path', { filename: '../escape.mp4' });
await run('output-symlink-refused', {}, 'unsafe_file', {}, async (out, id) => {
const victim = join(directory, 'safe-original'); await writeFile(victim, 'unchanged');
await symlink(victim, join(out, `${id}.mp4`));
});
await run('checkpoint-task-mismatch', {}, 'checkpoint_task_mismatch', {}, async (out, id) => {
await writeFile(join(out, `${id}.checkpoint.json`), JSON.stringify({ schemaVersion: 1, taskId: 'other', lastStatus: 'processing' }));
});
assert.equal(requests.every(request => request.method === 'GET'), true);
assert.equal(requests.filter(request => request.path.startsWith('/media/')).every(request => !request.authorizationPresent), true);
assert.equal(await readFile(join(directory, 'safe-original'), 'utf8'), 'unchanged');
const receipt = { schemaVersion: 1, blueprintId: 'blueprint-25', evidenceClass: 'fixture-run',
executedAt: new Date().toISOString(), nodeVersion: process.version,
command: 'node run-fixture.mjs', sourceCommit: 'a4818c0862ec04ac75e871ab114bcb5fa3152550',
contractFiles: ['src/app/api/v1/tasks/[id]/route.ts', 'src/shared/services/public-api.ts', 'src/shared/lib/public-api-contract.ts'],
productionTaskRun: false, externalNetworkRequests: 0, paidTaskSubmissions: 0,
requestMethods: ['GET'], fixtureMedia: '64 synthetic bytes with an MP4 ftyp prefix; not a generated or decoded video',
allPassed: true, scenarioCount: scenarios.length, scenarios,
artifactHashes: {
'client.mjs': createHash('sha256').update(await readFile(join(currentDir, 'client.mjs'))).digest('hex'),
'run-fixture.mjs': createHash('sha256').update(await readFile(join(currentDir, 'run-fixture.mjs'))).digest('hex'),
},
securityChecks: { apiKeySaved: false, mediaRequestsAuthenticated: false, temporaryFilesCleaned: true, symlinkTargetUnchanged: true },
limitations: ['No live API key, production task, provider completion, billing/refund, video decoding, or provider output quality was tested.'] };
await writeFile(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`);
process.stdout.write(`Passed ${scenarios.length} localhost fixture scenarios; receipt: ${receiptPath}\n`);
} finally {
await new Promise(done => { server.close(done); server.closeAllConnections(); });
await rm(directory, { recursive: true, force: true });
}