Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Agents import rendered clips into editor timelines over HTTP, MCP and the command line

Bowen Xueaddf3ecede53
diff --git a/freevideo_engine/agent/cli.py b/freevideo_engine/agent/cli.py
index 0625986..793729b 100644
--- a/freevideo_engine/agent/cli.py
+++ b/freevideo_engine/agent/cli.py
@@ -76,6 +76,12 @@ def build_parser():
schema.cli_arguments(command, schema.contracts()['GET', '/jobs']['query'])
command = commands.add_parser('upload', help='Copy a local media file into FreeVideo inputs')
command.add_argument('path')
+ command = commands.add_parser('imports', help='Bring local video or audio into the editing timeline')
+ imports = command.add_subparsers(dest='operation', required=True)
+ command = imports.add_parser('add', help='Upload content; poll imports list until ready before insert')
+ command.add_argument('path')
+ schema.cli_arguments(command, schema.obj({'ref': schema.REF}))
+ imports.add_parser('list', help='List imported sources and preparation progress')
command = commands.add_parser('generate-image', help='Generate or change a picture with the local image model')
schema.cli_arguments(command, schema.image(), exclude=('kind',))
command.add_argument('--wait', action='store_true', help='Wait for the picture and print the result')
@@ -280,6 +286,9 @@ def main(argv=None):
result = client.get(path, **value) if method == 'GET' else client.post(path, value)
elif args.command == 'upload':
result = client.upload(args.path)
+ elif args.command == 'imports':
+ result = (client.import_media(args.path, **({'ref': args.ref} if hasattr(args, 'ref') else {}))
+ if args.operation == 'add' else client.get('/imports'))
else:
result = client.frame(source(args.source), values.get('at', 'last'))
except ApiError as error:
diff --git a/freevideo_engine/agent/client.py b/freevideo_engine/agent/client.py
index aae0991..7bdfc67 100644
--- a/freevideo_engine/agent/client.py
+++ b/freevideo_engine/agent/client.py
@@ -281,6 +281,16 @@ class Client:
def upload(self, path):
"""Read on the client computer and upload content; never send a local path."""
+ return self._upload(path, '/media')
+
+ def import_media(self, path, *, ref=None):
+ """Import a client file into the editor. Poll /imports until its state is ready."""
+ from . import schema
+ if ref is not None:
+ schema.validate(schema.obj({'ref': schema.REF}), dict(ref=ref))
+ return self._upload(path, '/imports', ref=ref)
+
+ def _upload(self, path, endpoint, *, ref=None):
from .schema import MAX_UPLOAD_BYTES, MAX_JSON_UPLOAD_BYTES
source = local_file(path)
try:
@@ -289,7 +299,10 @@ class Client:
raise ApiError(413, 'too_large', 'File exceeds upload limit',
dict(next='Reduce the file to at most %d bytes.' % MAX_UPLOAD_BYTES, details=[dict(limit_bytes=MAX_UPLOAD_BYTES)]))
if size * 4 // 3 + 4096 <= MAX_JSON_UPLOAD_BYTES:
- return self.upload_bytes(source.name, source.read_bytes())
+ if endpoint == '/media':
+ return self.upload_bytes(source.name, source.read_bytes())
+ return self.post(endpoint, dict(name=source.name, data_base64=base64.b64encode(source.read_bytes()).decode(),
+ **({'ref': ref} if ref is not None else {})), timeout=600)
import secrets
boundary = 'freevideo-' + secrets.token_hex(16)
# Only a safe extension crosses a MIME header; local filenames stay local.
@@ -298,14 +311,15 @@ class Client:
raise ApiError(422, 'invalid_media', 'Invalid media extension')
prefix = ('--%s\r\nContent-Disposition: form-data; name="file"; filename="media%s"\r\n'
'Content-Type: application/octet-stream\r\n\r\n' % (boundary, suffix)).encode('ascii')
- ending = ('\r\n--%s--\r\n' % boundary).encode('ascii')
+ ending = (('\r\n--%s\r\nContent-Disposition: form-data; name="ref"\r\n\r\n%s' % (boundary, ref)
+ if ref is not None else '') + '\r\n--%s--\r\n' % boundary).encode('ascii')
with source.open('rb') as stream:
def chunks():
yield prefix
while data := stream.read(1024 * 1024):
yield data
yield ending
- return self.request('POST', '/freevideo/agent/v1/media', encoded=chunks(),
+ return self.request('POST', '/freevideo/agent/v1' + endpoint, encoded=chunks(),
content_type='multipart/form-data; boundary=' + boundary,
content_length=len(prefix) + size + len(ending), timeout=600)
except OSError:
diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.py
index 778d367..c274f10 100644
--- a/freevideo_engine/agent/guide.py
+++ b/freevideo_engine/agent/guide.py
@@ -128,6 +128,14 @@ GUIDE = {
],
'project_routes': [dict(operation=name, method=method, path=path, description=summary)
for name, (method, path, summary) in PROJECT_OPERATIONS.items()],
+ 'bring_your_own_footage': [
+ 'Render complete clips with ffmpeg/Canvas on your computer; bake overlays into their pixels. FreeVideo receives media, not your code. Use the project dimensions (even pixels), 24 fps and integer frame positions; seconds = frames / 24.',
+ 'Download generated shots using result.video.url, library video.url, or sources[key].video/audio from GET /projects/{id}, with the same Authorization: Bearer token (Range supported). These URLs are relative to the server origin. Render your changes locally.',
+ 'POST /imports accepts multipart file then optional ref, or JSON {name, data_base64, ref?}; HTTP never reads a local path. MCP freevideo_import_media and CLI imports add read a local path and upload content, like media upload. Limits: 2 GiB content, 96 MiB JSON body, and the same media decode limits.',
+ 'The answer is {import: {id, source: "import:<id>", state, fraction, ...}}. As on the page, poll GET /imports (MCP freevideo_imports, CLI imports list) about every two seconds. Match id in items; preparing is not insertable, ready is usable, failed is terminal with reason. Same ref or Idempotency-Key and filename/content reuses one import for that X-FreeVideo-Client, including after restart; changed content conflicts.',
+ 'The page receiver and transcode queue create an upright 24 fps H.264 preview by dropping/duplicating timestamped frames, with even dimensions and longest side at most 1920; preview audio is 32 kHz stereo AAC. Original dimensions are retained. Inserting the first video follows its original size by default (up to 8192 pixels); set project size_mode="fixed" to keep a chosen canvas. Later clips fit the canvas (cover by default). Export reads the original when available at the project output size/rate (preview fallback if missing).',
+ 'Insert with {op:"insert", source:"import:<id>", at:48} in POST /projects/{id}/operations using the current revision. Add subtitles/text and audio through project operations, then POST /projects/{id}/export and wait for the job. There is one video track; effects are baked into complete clips, not separate overlay tracks or blend modes.',
+ ],
'editing_images': [
'POST /images opens a picture as the image editor does; GET /images/{id} reads its document (layers), selection and revision.',
'POST /images/{id}/operations sends revision and 1-64 operations run with the page\'s own commands; the batch saves once or changes nothing. Layer IDs of new layers are in results[i].new_layer_ids.',
@@ -275,6 +283,8 @@ CAPABILITIES_ZH = {
('POST', '/jobs/{id}/cancel'): '取消任务',
('POST', '/jobs/{id}/resume'): '接着生成一条视频里还没完成的部分',
('POST', '/media'): '上传图片、视频或音频内容',
+ ('POST', '/imports'): '导入视频或音频到剪辑时间线;轮询 GET /imports 等待就绪',
+ ('GET', '/imports'): '列出已导入素材和准备进度',
('GET', '/media/{kind}/{file}/file'): '下载上传或处理后的素材',
('POST', '/media/inspect'): '查看素材信息',
('POST', '/media/frame'): '提取视频的一帧',
diff --git a/freevideo_engine/agent/imports.py b/freevideo_engine/agent/imports.py
new file mode 100644
index 0000000..1dfa5dd
--- /dev/null
+++ b/freevideo_engine/agent/imports.py
@@ -0,0 +1,142 @@
+"""Content uploads into the editor's import store and software transcode queue."""
+import asyncio
+import base64
+import binascii
+import hashlib
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+from urllib.parse import quote, urlencode
+
+from .. import comfy_editor as editor
+from . import media, schema, spec
+from .jobs import JobError
+
+
+def invalid(path, expected, code='invalid_media'):
+ error = spec.SpecError(schema.diagnostic(path, expected, None))
+ error.code = code
+ raise error
+
+
+def view(value):
+ fields = ('id', 'name', 'kind', 'state', 'fraction', 'reason', 'frames', 'fps', 'width', 'height',
+ 'preview_width', 'preview_height', 'has_audio')
+ row = {key: value.get(key) for key in fields}
+ row['fps'] = value.get('fps', editor.FPS)
+ row['has_audio'] = value.get('has_audio', False)
+ row['source'] = 'import:' + value['id']
+ for kind in ('preview', 'thumbnail'):
+ row[kind] = (schema.PREFIX + '/editor/sources/content?' + urlencode(dict(key=row['source'], file=kind))
+ if row['state'] == 'ready' else None)
+ return row
+
+
+def listing(root):
+ return dict(items=[view(row) for row in editor.list_imports(root)])
+
+
+def replay(root, receipt):
+ if receipt is None:
+ return None
+ for row in editor.list_imports(root):
+ value = editor._read_import(root, row['id'])
+ saved = value.get('agent_receipt')
+ if saved and (saved.get('client'), saved.get('ref')) == (receipt['client'], receipt['ref']):
+ if saved['digest'] != receipt['digest']:
+ invalid('/ref', 'the same filename and content for a replay', 'idempotency_conflict')
+ return view(row)
+ return None
+
+
+class Content:
+ """Adapt a checked upload to the page's streaming receiver, without a server-side path API."""
+ def __init__(self, path):
+ self.path = path
+
+ async def iter_chunked(self, size):
+ with self.path.open('rb') as stream:
+ while chunk := await asyncio.to_thread(stream.read, size):
+ yield chunk
+
+
+async def upload(request, value, root, manager, lock, decoders):
+ if manager is None:
+ raise JobError('not_ready', 'Editor import queue unavailable')
+ # Temporary content stays beside the destination, and is removed on rejection or disconnect.
+ with tempfile.TemporaryDirectory(prefix='.agent-import-', dir=root) as temporary:
+ multipart = request.content_type == 'multipart/form-data'
+ field = '/file' if multipart else '/data_base64'
+ ref = None if multipart else value.get('ref')
+ if multipart:
+ reader = await request.multipart()
+ part = await reader.next()
+ if part is None or getattr(part, 'name', None) != 'file' or not getattr(part, 'filename', None):
+ invalid('/file', 'one nonempty file part, followed by optional ref')
+ name = part.filename
+ else:
+ name = value['name']
+ spec.import_name(name)
+ target = Path(temporary) / ('media' + Path(name).suffix.lower())
+ digest = hashlib.sha256()
+ size = 0
+ with target.open('xb') as stream:
+ if multipart:
+ while chunk := await part.read_chunk(size=256 * 1024):
+ size += len(chunk)
+ if size > schema.MAX_UPLOAD_BYTES:
+ raise JobError('too_large', 'Upload exceeds limit', limit_bytes=schema.MAX_UPLOAD_BYTES)
+ digest.update(chunk)
+ await asyncio.to_thread(stream.write, chunk)
+ extra = await reader.next()
+ if extra is not None:
+ if getattr(extra, 'name', None) != 'ref' or getattr(extra, 'filename', None):
+ invalid('/file', 'one file part followed only by optional ref')
+ data = bytearray()
+ while chunk := await extra.read_chunk():
+ data.extend(chunk)
+ if len(data) > 1024:
+ spec.fail('/ref', 'a ref of at most 128 characters')
+ try:
+ ref = data.decode('utf-8')
+ except UnicodeDecodeError:
+ spec.fail('/ref', 'a UTF-8 ref')
+ if await reader.next() is not None:
+ invalid('/file', 'one file part followed only by optional ref')
+ else:
+ try:
+ data = base64.b64decode(value['data_base64'], validate=True)
+ except (binascii.Error, ValueError):
+ invalid(field, 'valid base64-encoded video or audio content')
+ size = len(data)
+ if size > schema.MAX_UPLOAD_BYTES:
+ raise JobError('too_large', 'Upload exceeds limit', limit_bytes=schema.MAX_UPLOAD_BYTES)
+ digest.update(data)
+ await asyncio.to_thread(stream.write, data)
+ if not size:
+ invalid(field, 'nonempty video or audio content')
+ key = request.headers.get('Idempotency-Key')
+ for where, candidate in (('/ref', ref), ('/headers/Idempotency-Key', key)):
+ if candidate is not None:
+ problems = schema.issues(schema.REF, candidate, where)
+ if problems:
+ raise spec.SpecError(problems)
+ if ref and key and ref != key:
+ invalid('/ref', 'the same value as Idempotency-Key', 'idempotency_conflict')
+ ref = key or ref
+ receipt = (dict(ref=ref, client=request.headers.get('X-FreeVideo-Client', '')[:80] or None,
+ digest=hashlib.sha256(name.encode() + b'\0' + digest.digest()).hexdigest()) if ref else None)
+ async with decoders:
+ try:
+ await asyncio.to_thread(media.validate_upload, target)
+ except (OSError, ValueError, SyntaxError):
+ invalid(field, 'decodable video or audio within the media upload limits')
+ async with lock:
+ previous = await asyncio.to_thread(replay, root, receipt)
+ if previous is not None:
+ return {'import': previous}, 200
+ adapted = SimpleNamespace(content_length=size, headers={'X-FreeVideo-Filename': quote(name, safe='')},
+ content=Content(target))
+ made = await editor.receive(adapted, root, receipt=receipt)
+ manager.submit(made['id'])
+ return {'import': view(made)}, 201
diff --git a/freevideo_engine/agent/mcp.py b/freevideo_engine/agent/mcp.py
index 62ce0d2..e94b1f8 100644
--- a/freevideo_engine/agent/mcp.py
+++ b/freevideo_engine/agent/mcp.py
@@ -31,7 +31,12 @@ Chain shots by starting the next shot from the previous one's last frame (media.
"frame": "last"}), look at results with freevideo_look, ask the local VLM with freevideo_ask, and join clips
with freevideo_assemble. For durable filming, use freevideo_drama_plan → start → get → sheet → choose/reshoot → finish.
Cast first: search freevideo_cast_list, reuse the card the user named or one that fits, create a card only if none does.
-If paused is set, wait for the user using get with since and wait=25. Only the user may pause/resume."""
+If paused is set, wait for the user using get with since and wait=25. Only the user may pause/resume.
+Bring your own footage: render complete video clips on your computer with ffmpeg/Canvas, baking effects into pixels.
+freevideo_import_media reads your local file and uploads content (up to 2 GiB); reuse ref for safe retries.
+Poll freevideo_imports about every two seconds until state=ready (failed is terminal), then insert its source=import:<id>
+at an integer frame in a 24 fps project, add subtitles/audio, and export. GET /guide bring_your_own_footage explains
+authenticated source downloads, dimensions and audio. No second video track or blend mode is needed."""
def tool_list():
@@ -53,6 +58,8 @@ def tool_list():
dict(name='freevideo_cancel', title='Cancel a job', description='Cancel a waiting, queued or running job.', annotations={'readOnlyHint': False, 'destructiveHint': True, 'openWorldHint': False}),
dict(name='freevideo_resume', title='Resume generation', description='Resume a failed, interrupted or cancelled generation; only unfinished blocks run. Poll the same job ID.', annotations=write),
dict(name='freevideo_add_media', title='Add media', description='Read a local image, video or audio file and upload its content; returns the "file" to use in media.', annotations=write),
+ dict(name='freevideo_import_media', title='Import footage', description='Read a local video or audio file and upload it into the editor. Returns import.source (import:<id>) and state. Poll freevideo_imports until ready, then insert that source into a project. Same ref and content safely replay.', annotations=write),
+ dict(name='freevideo_imports', title='Imported footage', description='List editor imports with source, state (preparing/ready/failed), fraction and authenticated preview URLs. Wait for ready before insert; failed is terminal.', annotations=read),
dict(name='freevideo_look', title='Look at media', description='Return a picture you can see: one frame of a video (at = first, last or seconds) or a contact sheet of timed frames (mode = sheet), or an image file. Use it to review shots.', annotations=read),
dict(name='freevideo_edit_image', title='Edit an image', description="Crop/rotate/flip/pad/adjust an image, add text, shapes or image overlays, or remove burned-in captions (remove_text), without the browser. The result is a new input file plus an editor document a person can reopen in FreeVideo's image editor.", annotations=write),
dict(name='freevideo_ask', title='Ask the local VLM', description='Ask FreeVideo\'s local vision-language model about images or sampled frames of a video (e.g. "Does this shot match its description? Answer as JSON {score, issues}").', annotations=write),
@@ -359,6 +366,10 @@ class Server:
return c.resume(args['id'], **({'ref': args['ref']} if 'ref' in args else {})), []
if name == 'freevideo_add_media':
return c.upload(args['path']), []
+ if name == 'freevideo_import_media':
+ return c.import_media(args['path'], **({'ref': args['ref']} if 'ref' in args else {})), []
+ if name == 'freevideo_imports':
+ return c.get('/imports'), []
if name == 'freevideo_edit_image':
made = c.edit(args['source'], args.get('recipe'), document=args.get('document'), target=args.get('target'))
return made, self.picture(made['view'])
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
index e0fa113..4def1fb 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -165,7 +165,8 @@ def features(continuation, vlm):
from .editor_runtime import available
rules = available()
return {'capabilities': True, 'plan': True, 'jobs.cancel': True, 'jobs.resume': True, 'takes': True,
- 'library.read': True, 'library.download': True, 'errors.validation': True, 'errors.missing_media': True,
+ 'library.read': True, 'library.download': True, 'imports.create': True, 'imports.read': True,
+ 'errors.validation': True, 'errors.missing_media': True,
'generate.text': True, 'generate.size': True, 'generate.first_frame': True, 'generate.seed': True,
'queue.shared': True, 'queue.busy': True, 'chain.auto': bool(continuation),
'enhance': bool(vlm.get('ready')), 'drama.film': True, 'images.edit': rules,
@@ -387,6 +388,7 @@ def register():
token_failures = set()
thumbnails = asyncio.Semaphore(1)
upload_decoders = asyncio.Semaphore(1)
+ import_lock = asyncio.Lock()
def expected(root=None):
from ..comfy_bridge import installation_root
@@ -492,7 +494,7 @@ def register():
if definition.get('multipart') and request.content_type == 'multipart/form-data':
pass
else:
- limit = contract.MAX_JSON_UPLOAD_BYTES if suffix == '/media' else contract.MAX_BODY_BYTES
+ limit = contract.MAX_JSON_UPLOAD_BYTES if suffix in ('/media', '/imports') else contract.MAX_BODY_BYTES
value = await read_body(request, limit, definition.get('optional_body', False))
try:
contract.validate(definition['body'], value)
@@ -518,8 +520,10 @@ def register():
value['next'] = value['next'].replace('{id}', request.match_info['id'])
if error.code == 'too_large':
limit = error.details.get('limit_bytes', contract.MAX_UPLOAD_BYTES)
+ location = ({'path': '/file' if request.content_type == 'multipart/form-data' else '/data_base64'}
+ if suffix == '/imports' else {})
value.update(message='The upload must be at most %d bytes; a larger payload was received.' % limit,
- details=[dict(limit_bytes=limit)], next='Reduce the payload to at most %d bytes and retry.' % limit)
+ details=[dict(limit_bytes=limit, **location)], next='Reduce the payload to at most %d bytes and retry.' % limit)
if error.code == 'busy':
entries = (await asyncio.to_thread(jobs.queue_view))['entries']
value = errors.build('busy', owner=entries[0]['owner'] if entries else 'ui')
@@ -1466,6 +1470,26 @@ def register():
made.pop('path', None)
return assets.public(dict(made, **info, file=relative, view=assets.view(relative)))
+ @routes.post(PREFIX + '/imports')
+ @guarded
+ async def import_media(request):
+ from . import imports
+ value = None if request.content_type == 'multipart/form-data' else await body(request)
+ try:
+ result, status = await imports.upload(request, value, port.output_root,
+ getattr(server, '_freevideo_editor', None), import_lock, upload_decoders)
+ except specs.SpecError:
+ raise
+ except (ValueError, AssertionError):
+ imports.invalid('/file', 'a well-formed multipart upload with video or audio content')
+ return reply(result, status)
+
+ @routes.get(PREFIX + '/imports')
+ @guarded
+ async def list_imports(request):
+ from . import imports
+ return reply(await asyncio.to_thread(imports.listing, port.output_root))
+
@routes.post(PREFIX + '/media')
@guarded
async def upload(request):
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index f0ac1cd..79fa2b4 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -316,6 +316,20 @@ def batch_schema(*, local=False):
return obj(dict(jobs=array(job_schema(local=local, refs=True), 1, 64), ref=REF), ('jobs',), description='x-batch additionally checks earlier-row references and at most 64 jobs after takes expansion.', **{'x-batch': True})
+def import_upload():
+ return obj(dict(name=string(255, pattern=r'^[^/\\:\x00-\x1f]+$'),
+ data_base64=string(MAX_JSON_UPLOAD_BYTES), ref=REF), ('name', 'data_base64'))
+
+
+def import_view():
+ return obj(dict(id=string(80), source=EDITOR_SOURCE, name=string(255), kind=enum(('video', 'audio')),
+ state=enum(('preparing', 'ready', 'failed')), fraction=number(0, 1), reason=nullable(string()),
+ frames=nullable(number(1, integer=True)), fps=number(1), width=nullable(number(0, integer=True)),
+ height=nullable(number(0, integer=True)), preview_width=nullable(number(0, integer=True)),
+ preview_height=nullable(number(0, integer=True)), has_audio=nullable({'type': 'boolean'}),
+ preview=nullable(string()), thumbnail=nullable(string())), ('id', 'source', 'name', 'kind', 'state', 'fraction'))
+
+
def contracts(*, local=False):
"""Every registered route, including the UI control plane, has a contract."""
def route(summary, body=None, query=None, **kw):
@@ -346,6 +360,9 @@ def contracts(*, local=False):
('POST', '/media'): route('Upload image, video or audio content',
body=obj(dict(name=string(255, pattern=r'^[^/\\:\x00]+$'), data_base64=string(MAX_JSON_UPLOAD_BYTES)),
('name', 'data_base64')), status=201, multipart=True),
+ ('POST', '/imports'): route('Import video or audio into the editing timeline; poll GET /imports until ready',
+ body=import_upload(), status=201, multipart=True, idempotent=True),
+ ('GET', '/imports'): route('List editor imports and preparation progress'),
('GET', '/media/{kind}/{file}/file'): route('Download uploaded or derived media'),
('POST', '/media/inspect'): route('Inspect media', body=obj(source, ('source',))),
('POST', '/media/frame'): route('Extract a video frame', body=obj(dict(source, at=dict(FRAME, default='last')), ('source',)), status=201),
@@ -1293,6 +1310,7 @@ def schemas():
drama={name: drama_schema(name) for name in DRAMA_OPERATIONS}, production_view=production_response(),
cast={name: cast_schema(name) for name in CAST_OPERATIONS}, cast_view=cast_view(),
projects={name: project_schema(name) for name in PROJECT_OPERATIONS},
+ imports=dict(upload=import_upload(), item=import_view()),
images={name: image_schema(name) for name in IMAGE_OPERATIONS},
whitebox={name: whitebox_schema(name) for name in WHITEBOX_OPERATIONS},
sessions=dict(event=session_event(stored=True), meta=session_view(),
@@ -1316,6 +1334,8 @@ def openapi():
content = {'application/json': {'schema': deepcopy(contract['body'])}}
if contract.get('multipart'):
content['multipart/form-data'] = {'schema': obj({'file': {'type': 'string', 'format': 'binary'}}, ('file',))}
+ if suffix == '/imports':
+ content['multipart/form-data']['schema']['properties']['ref'] = REF
operation['requestBody'] = dict(required=not contract.get('optional_body', False), content=content)
operation['parameters'] = [dict(name=k, **{'in': 'query'}, required=k in contract['query'].get('required', []), schema=v)
for k, v in contract['query']['properties'].items()]
@@ -1356,6 +1376,9 @@ def openapi():
if suffix == '/sessions' and method == 'GET' else session_view())
elif suffix.endswith('/events'):
content_type, response_schema = 'text/event-stream', {'type': 'string'}
+ elif suffix == '/imports':
+ response_schema = obj({'import': import_view()}, ('import',)) if method == 'POST' else obj(
+ {'items': array(import_view())}, ('items',))
elif suffix == '/editor/sources/content':
content_type, response_schema = 'application/octet-stream', {'type': 'string', 'format': 'binary'}
elif suffix.endswith('/file') or suffix.endswith('/thumbnail'):
@@ -1411,6 +1434,7 @@ TOOL_ENDPOINTS = {
'freevideo_job': ('GET', '/jobs/{id}'), 'freevideo_wait': ('GET', '/jobs/{id}'),
'freevideo_jobs': ('GET', '/jobs'), 'freevideo_cancel': ('POST', '/jobs/{id}/cancel'),
'freevideo_resume': ('POST', '/jobs/{id}/resume'), 'freevideo_add_media': ('POST', '/media'),
+ 'freevideo_import_media': ('POST', '/imports'), 'freevideo_imports': ('GET', '/imports'),
'freevideo_edit_image': ('POST', '/media/edit'), 'freevideo_library': ('GET', '/library'),
}
TOOL_ENDPOINTS.update({'freevideo_drama_' + name: (method, suffix)
@@ -1547,6 +1571,8 @@ def _tool_schema(name):
return batch_schema(local=True)
if name == 'freevideo_add_media':
return obj({'path': string(4096)}, ('path',))
+ if name == 'freevideo_import_media':
+ return obj(dict(path=string(4096), ref=REF), ('path',))
if '{id}' in suffix:
value['properties']['id'] = contract.get('path', {}).get('properties', {}).get('id', JOB)
value['required'] = list(value.get('required', [])) + ['id']
diff --git a/freevideo_engine/agent/spec.py b/freevideo_engine/agent/spec.py
index f2e508a..a5d51c0 100644
--- a/freevideo_engine/agent/spec.py
+++ b/freevideo_engine/agent/spec.py
@@ -27,6 +27,22 @@ def fail(path, message):
raise SpecError(contract.diagnostic(path, message, None))
+def import_name(name):
+ """Timeline imports accept video/audio content, with no HTTP filesystem paths."""
+ from ..comfy_assets import media_kind
+ problems = contract.issues(contract.import_upload()['properties']['name'], name, '/name')
+ if problems:
+ raise SpecError(problems)
+ try:
+ if media_kind(name) not in ('video', 'audio'):
+ raise ValueError
+ except ValueError:
+ error = SpecError(contract.diagnostic('/name', 'a supported video or audio filename', None))
+ error.code = 'invalid_media'
+ raise error from None
+ return name
+
+
# Field checks for values no route schema describes: screenplays and filming records.
def _bool(value, path):
if type(value) is not bool:
diff --git a/freevideo_engine/comfy_editor.py b/freevideo_engine/comfy_editor.py
index 1d88c67..5150f7a 100644
--- a/freevideo_engine/comfy_editor.py
+++ b/freevideo_engine/comfy_editor.py
@@ -866,7 +866,7 @@ def _display_name(value):
return name
-async def receive(request, root):
+async def receive(request, root, *, receipt=None):
if request.content_length is not None and request.content_length > MAX_IMPORT_BYTES:
raise TooLarge('Import exceeds 8 GiB')
name = _display_name(request.headers.get('X-FreeVideo-Filename'))
@@ -894,6 +894,9 @@ async def receive(request, root):
await asyncio.to_thread(os.replace, temporary, destination)
value = dict(id=identity, name=name, kind=kind, state='preparing', fraction=0., reason=None,
frames=None, fps=FPS, width=None, height=None, has_audio=False)
+ if receipt is not None:
+ # Keep the Agent replay key in the same atomic record as the import.
+ value['agent_receipt'] = receipt
await asyncio.to_thread(_write, _import_path(root, identity), value)
return {key: value[key] for key in ('id', 'name', 'kind', 'state', 'fraction')}
except BaseException: