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.

Agent: a conversation between the Autopilot view and the connected agent

Bowen Xue1c4ba668147b
diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.py
index de47497..6759e81 100644
--- a/freevideo_engine/agent/guide.py
+++ b/freevideo_engine/agent/guide.py
@@ -230,7 +230,7 @@ CAPABILITIES_ZH = {
('GET', '/library/{day}/{run}/thumbnail'): '查看已保存的视频缩略图',
('GET', '/queue'): '查看队列顺序及任务属于 Agent 还是用户',
('GET', '/editor/sources/content'): '下载剪辑项目的源素材或缩略图;使用 GET /projects/{id} 返回的素材标识',
- ('GET', '/inbox'): '等待当前工作会话中用户的消息或答复,最多 25 秒',
+ ('GET', '/inbox'): '等待当前工作会话中用户的消息或答复,最多 50 秒;again=true 表示暂时没有,再调一次',
('POST', '/drama/plan'): '预览多镜头影片的剧本和各镜头拍摄条数,不保存、不提交。'
'多镜头影片可以逐镜选片;单条视频(最长 60 秒)用一个 generate 任务',
('POST', '/drama'): '确认计划后开始拍摄,进度会保存;查看各条画面并逐镜选片',
@@ -357,6 +357,9 @@ def connection_guide(root, base, lang=None, offers=None):
'# job = call("GET", "/jobs/" + job["id"] + "?wait=25")',
'# Poll the same ID until succeeded. Retry a lost submission using the same ref.',
'# Download base origin + job["result"]["video"]["url"] with the same Authorization header.',
+ '# The conversation inside FreeVideo (see below): one wait per command, never a loop inside one command.',
+ '# box = call("GET", "/inbox?wait=50") # {"session": ..., "inbox": [what the user said], "again": true if nothing yet}',
+ '# call("POST", "/sessions/" + box["session"] + "/events", {"type": "message", "text": "YOUR WORDS"})',
])
return dict(language=lang, api=base + PREFIX, token_file=token_file, claude_code=config['claude_code'],
codex=config['codex'], mcp_json=config['mcp_json'], command=config['command'],
@@ -380,6 +383,24 @@ def connection_guide(root, base, lang=None, offers=None):
'"Introduce these", only those, and give two or three requests they can say. Do not quote version '
'numbers or endpoint names. Do not start any task yourself; wait for the user to ask.',
introduce=introduction(zh, offers or {}),
+ conversation='用户会在 FreeVideo 的“AI 全自动”页里直接和你说话,你的话也显示在那里。'
+ '连接后先调一次等待接口 GET ' + base + PREFIX + '/inbox?wait=50(MCP 用不带 id 的 freevideo_wait),'
+ '回应里的 session 就是这段对话;往 POST ' + base + PREFIX + '/sessions/{session}/events 发 '
+ '{"type":"message","text":"…"}(MCP 用 freevideo_session_post),先用一句话介绍自己和能做的事。'
+ '然后一直调等待接口等用户的话:它最多约 50 秒返回,"again": true 表示暂时没有新消息,再调一次,不要停,'
+ '也不要因为没有消息去问用户。每条命令只等一次,命令的超时设到 60 秒以上。'
+ '收到话(inbox 里每条的 text)就去做;做完把结果用一两句话发回同一个 session,再接着等。'
+ '这段对话里不要新建会话。用户没让你停,就一直这样循环。' if zh else
+ 'The user talks to you inside FreeVideo, in the Autopilot view, and your words are shown there. '
+ 'After connecting, call the wait once: GET ' + base + PREFIX + '/inbox?wait=50 (MCP: freevideo_wait '
+ 'without id). Its "session" is this conversation; POST ' + base + PREFIX + '/sessions/{session}/events '
+ 'with {"type":"message","text":"..."} (MCP: freevideo_session_post) and first say one line about '
+ 'who you are and what you can do. Then keep calling the wait for the user\'s words: it answers within '
+ 'about 50 seconds, and "again": true means nothing new yet, so call it again; do not stop and do not '
+ 'ask the user because nothing came. One wait per command, with a command timeout above 60 seconds. '
+ 'When words arrive (text of each inbox row), do what they ask, post the result in one or two '
+ 'sentences to the same session, and wait again. Do not create another session for this conversation. '
+ 'Continue this loop until the user tells you to stop.',
rules=RULES_ZH if zh else RULES,
fallback='如果你无法执行命令、读取本地文件或连接到这台电脑,请如实告诉用户:'
'“我连接不到你电脑上的 FreeVideo,请改用安装在这台电脑上的 AI 助手。”'
@@ -404,6 +425,7 @@ def connection_text(value):
*['- ' + row['description'] for row in value['capabilities']], '',
'先介绍这几样:' if zh else 'Introduce these:', *['- ' + row for row in value['introduce']], '',
value['first_reply'], value['fallback'], '',
+ '在 FreeVideo 里对话:' if zh else 'The conversation inside FreeVideo:', value['conversation'], '',
'用户提出要求后的做事规则:' if zh else 'How to work once the user has asked for something:',
*['%d. %s' % (number, rule) for number, rule in enumerate(value['rules'], 1)], '',
('详细使用指南:' if zh else 'More detail: ') + value['docs']['guide'],
diff --git a/freevideo_engine/agent/mcp.py b/freevideo_engine/agent/mcp.py
index 3b672c2..c59d259 100644
--- a/freevideo_engine/agent/mcp.py
+++ b/freevideo_engine/agent/mcp.py
@@ -47,7 +47,7 @@ def tool_list():
dict(name='freevideo_generate', title='Generate a video', description='Generate one video from an H3 prompt, up to 60 seconds: a longer request continues and joins into one file automatically. Prefer a new shot with its reference pictures wherever the film can cut; continue only a take, action or sound that must stay unbroken. Use this for any single video, also after freevideo_enhance_prompt; the drama tools are only for a film of several separately chosen shots. Optionally from first/last frames or references (files, local paths, or frames of earlier jobs). Returns the job; with wait, its result (video path and URL).', annotations=write),
dict(name='freevideo_submit_batch', title='Submit a storyboard', description='Submit several jobs at once. Each row is a job object with "kind" (generate default, assemble, vlm, enhance) and an optional "ref"; later rows use "@ref" wherever a job id is expected (from_job, after, clips, refine_from). FreeVideo runs them in dependency order.', annotations=write),
dict(name='freevideo_job', title='Job status', description='Status, progress, result or error of a job.', annotations=read),
- dict(name='freevideo_wait', title='Wait for a job or the user', description="Wait at most 25 seconds for a job (with id) or, without id, for the user's words in this session. Returns early when the user says something (inbox). If the job is still active, call it again with the same ID; do not resubmit.", annotations=read),
+ dict(name='freevideo_wait', title='Wait for a job or the user', description="Wait at most 25 seconds for a job (with id) or, without id, at most 50 seconds for what the user says in FreeVideo (inbox). again=true means nothing new yet: call it again. A job wait returns early when the user says something. If the job is still active, call it again with the same ID; do not resubmit.", annotations=read),
dict(name='freevideo_jobs', title='List jobs', description='Recent agent jobs, optionally by status (comma-separated), project or kind.', annotations=read),
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),
@@ -330,8 +330,8 @@ class Server:
return c.job(args['id'], **({'wait': wait} if wait is not None else {})), []
if name == 'freevideo_wait':
if not args.get('id'):
- return c.get('/inbox', wait=min(25., float(args.get('timeout', 25)))), []
- return self.wait(identity, args['id'], args.get('timeout', 25), token), []
+ return c.get('/inbox', wait=min(50., float(args.get('timeout', 50)))), []
+ return self.wait(identity, args['id'], min(25., float(args.get('timeout', 25))), token), []
if name == 'freevideo_jobs':
return dict(jobs=c.jobs(**args)), []
if name == 'freevideo_cancel':
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
index fcd7c2f..a2b2982 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -378,6 +378,8 @@ def register():
contracts = contract.contracts()
page_sessions = {}
connection = dict(connected=False, client=None, via=None, last_seen_at=None)
+ # The conversation in the Autopilot view: the page and the connected agent talk in the agent's latest session.
+ chat = dict(client=None, waiting=0, folds={})
server._freevideo_agent_connection = connection
def problem(code, message=None, status=None, **details):
@@ -432,6 +434,7 @@ def register():
connection['client'] = connection['client'] or request.headers.get('X-FreeVideo-Client', 'HTTP client')[:80]
connection['via'] = connection['via'] or 'http'
request['agent_client'] = request.headers.get('X-FreeVideo-Client', '')[:80] or 'HTTP client'
+ chat['client'] = request['agent_client']
if definition.get('path'):
contract.validate(definition['path'], dict(request.match_info))
for key in request.query:
@@ -667,6 +670,194 @@ def register():
path=('/api' if request.path.startswith('/api/') else '') + '/freevideo/agent', max_age=12 * 3600)
return response
+ def activity_item(row, *, card=False):
+ view = jobs.view(row, detail=False)
+ value = {k: view.get(k) for k in ('id', 'kind', 'status', 'label', 'project', 'client', 'take',
+ 'created_at', 'finished_at')}
+ progress = view.get('progress') or {}
+ value['progress'] = {k: progress[k] for k in ('phase', 'step', 'fraction', 'remaining_seconds',
+ 'queue_position') + (('block',) if card else ()) if progress.get(k) is not None}
+ if view.get('waiting_for'):
+ value['waiting_for'] = len(view['waiting_for'])
+ if view.get('error'):
+ value['error'] = view['error']
+ video = (view.get('result') or {}).get('video') or {}
+ if video.get('url'):
+ value['video'] = video['url']
+ if (view.get('result') or {}).get('library_id'):
+ # The work this video became, for the page to show it in My works.
+ value['work'] = view['result']['library_id']
+ if card:
+ # A conversation card: the page plays and pictures the saved work itself, without the agent's token.
+ from urllib.parse import quote
+ value.pop('client')
+ work = value.setdefault('work', None)
+ seconds = row['spec'].get('seconds')
+ size = [row['spec'].get(k) if type(row['spec'].get(k)) is int else None for k in ('width', 'height')]
+ value.update(seconds=seconds if isinstance(seconds, (int, float)) and not isinstance(seconds, bool) else None,
+ width=size[0], height=size[1],
+ thumbnail='/freevideo/library/thumbnail?id=' + quote(work, safe='') if work else None,
+ play='/freevideo/agent/chat/video?id=' + quote(work, safe='') if work else None)
+ return value
+
+ def agent_state():
+ seen, now = connection['last_seen_at'], time.time()
+ connected = seen is not None and 0 <= now - seen < 600
+ name = (connection['client'] or '').strip()
+ # Programs report their own identifiers; the page shows the name a person knows.
+ shown = ('Claude Code' if name.lower() in ('claude-code', 'claude code', 'claude') else
+ 'Codex' if name.lower().startswith('codex') else name or None)
+ # Every answer to the agent carries the user's unread words, so a recent call will hear them too.
+ return dict(connected=connected, name=shown, listening=connected and (chat['waiting'] > 0 or now - seen < 90))
+
+ def chat_fold(store, sid):
+ """The session as the page shows it: sentences, the jobs made along the way, and questions."""
+ fold = chat['folds'].get(sid)
+ if fold is None:
+ while len(chat['folds']) >= 8:
+ chat['folds'].pop(next(iter(chat['folds'])))
+ fold = chat['folds'][sid] = dict(seq=0, items=[], jobs={}, asked={}, sent={}, ids={})
+ while store.get(sid)['last_seq'] > fold['seq']:
+ rows = store.events(sid, after=fold['seq'], limit=500)
+ if not rows:
+ break
+ for row in rows:
+ fold['seq'] = row['seq']
+ base = dict(seq=row['seq'], at=row['at'], type=row['type'])
+ if row['type'] == 'message':
+ fold['items'].append(dict(base, role='user' if row['by'] == 'user' else 'agent', text=row['text']))
+ elif row['type'] == 'step' and row['state'] == 'done':
+ job = (row.get('refs') or {}).get('job')
+ if job and job not in fold['jobs']:
+ fold['jobs'][job] = row['seq']
+ fold['items'].append(dict(base, type='job', job=job))
+ elif row['type'] == 'confirm':
+ if row['state'] == 'asked':
+ item = dict(base, id=row['id'], question=row.get('question'),
+ estimate_seconds=row.get('estimate_seconds'), state='asked')
+ fold['asked'][row['id']] = item
+ fold['items'].append(item)
+ elif row['id'] in fold['asked']:
+ fold['asked'][row['id']]['state'] = row['state']
+ return fold
+
+ def chat_current(rows, sid, fold):
+ mine = [r for r in rows if r.get('session') == sid or (fold is not None and r['id'] in fold['jobs'])]
+ active = sorted((r for r in mine if r['status'] in ACTIVE),
+ key=lambda r: (r['status'] in ('running', 'cancelling'), r['created_at']))
+ return mine, active[-1] if active else None
+
+ def chat_session(store):
+ return store.latest_for(chat['client']) if store is not None and chat['client'] is not None else None
+
+ @routes.get('/freevideo/agent/chat')
+ @guarded
+ async def chat_read(request):
+ after = request[query_key].get('after')
+ def read():
+ store = work_sessions()
+ sid = chat_session(store)
+ rows = jobs.rows()
+ value = dict(agent=agent_state(), session=sid, last_seq=0, read_seq=0, items=[], jobs={}, confirms={}, current=None,
+ active=sum(1 for r in rows if r['status'] in ACTIVE))
+ if sid is None:
+ return value
+ fold = chat_fold(store, sid)
+ known = {r['id']: r for r in rows}
+ items = [i for i in fold['items'] if i['type'] != 'job' or i['job'] in known]
+ if after is None:
+ items, more = items[-200:], False
+ else:
+ items = [i for i in items if i['seq'] > after]
+ items, more = items[:200], len(items) > 200
+ mark = store.read_until(sid, chat['client'])
+ for item in items:
+ item = dict(item)
+ if item['type'] == 'message' and item['role'] == 'user':
+ item['read'] = item['seq'] <= mark
+ if item['seq'] in fold['ids']:
+ item['id'] = fold['ids'][item['seq']]
+ value['items'].append(item)
+ value['last_seq'] = items[-1]['seq'] if more else fold['seq']
+ # For what the page already holds: how far the agent has read, and how each question stands now.
+ value['read_seq'] = mark
+ value['confirms'] = {identity: item['state'] for identity, item in list(fold['asked'].items())[-50:]}
+ mine, current = chat_current(rows, sid, fold)
+ now = time.time()
+ shown = {r['id']: r for r in mine if r['status'] in ACTIVE or (r.get('finished_at') or 0) > now - 1800}
+ shown.update((i['job'], known[i['job']]) for i in items if i['type'] == 'job')
+ value['jobs'] = {identity: activity_item(row, card=True) for identity, row in shown.items()}
+ value['current'] = current['id'] if current else None
+ if current and current['id'] not in value['jobs']:
+ value['jobs'][current['id']] = activity_item(current, card=True)
+ return value
+ return reply(await asyncio.to_thread(read))
+
+ @routes.get('/freevideo/agent/chat/now')
+ @guarded
+ async def chat_now(request):
+ def read():
+ store = work_sessions()
+ sid = chat_session(store)
+ rows = jobs.rows()
+ current = chat_current(rows, sid, chat['folds'].get(sid))[1] if sid else None
+ return dict(agent=agent_state(), current=activity_item(current, card=True) if current else None,
+ active=sum(1 for r in rows if r['status'] in ACTIVE))
+ return reply(await asyncio.to_thread(read))
+
+ @routes.post('/freevideo/agent/chat')
+ @guarded
+ async def chat_say(request):
+ value = await body(request)
+ def write():
+ store, client = work_sessions(), chat['client']
+ if store is None or client is None:
+ return None
+ sid = store.latest_for(client) or store.create(client=client, by='user')['id']
+ fold = chat_fold(store, sid)
+ if value['id'] in fold['sent']:
+ seq = fold['sent'][value['id']]
+ first = next(i for i in fold['items'] if i['seq'] == seq)
+ return 200, dict(seq=seq, id=value['id'], at=first['at'], session=sid,
+ read=seq <= store.read_until(sid, client), agent=agent_state())
+ if store.stopped(sid):
+ # Speaking again continues a conversation the user stopped earlier.
+ store.append(sid, dict(type='control', action='resumed'), by='user')
+ row = store.append(sid, dict(type='message', text=value['text']), by='user')
+ fold['sent'][value['id']] = row['seq']
+ fold['ids'][row['seq']] = value['id']
+ while len(fold['sent']) > 500:
+ fold['ids'].pop(fold['sent'].pop(next(iter(fold['sent']))), None)
+ return 201, dict(seq=row['seq'], id=value['id'], at=row['at'], session=sid, read=False, agent=agent_state())
+ done = await asyncio.to_thread(write)
+ if done is None:
+ # Nothing is kept: no agent has connected since FreeVideo started, so nobody would read it.
+ return reply({'error': dict(code='not_connected', message='No agent is connected.', retryable=True,
+ details=[], next='Connect an agent in the Autopilot view, then say it again.',
+ request_id=errors.request_id())}, 409)
+ return reply(done[1], done[0])
+
+ @routes.post('/freevideo/agent/chat/confirm')
+ @guarded
+ async def chat_confirm(request):
+ value = await body(request)
+ def write():
+ store = work_sessions()
+ sid = chat_session(store)
+ if sid is None:
+ raise JobError('not_found', 'No conversation')
+ row = store.append(sid, dict(type='confirm', id=value['id'],
+ state='approved' if value['approve'] else 'declined'), by='user')
+ return dict(id=row['id'], state=row['state'])
+ return reply(await asyncio.to_thread(write))
+
+ @routes.get('/freevideo/agent/chat/video')
+ @guarded
+ async def chat_video(request):
+ # The finished video of a work, for the local page to play in the conversation.
+ path = await asyncio.to_thread(port.library_video, request[query_key]['id'])
+ return web.FileResponse(path, headers={'Content-Type': 'video/mp4', 'Cache-Control': 'private, no-store'})
+
@routes.get('/freevideo/agent/activity')
@guarded
async def activity(request):
@@ -675,25 +866,7 @@ def register():
now = time.time()
rows = sorted(jobs.rows(), key=lambda r: r['created_at'], reverse=True)
shown = [r for r in rows if r['status'] in ACTIVE or (r.get('finished_at') or 0) > now - 1800][:12]
- def item(row):
- view = jobs.view(row, detail=False)
- value = {k: view.get(k) for k in ('id', 'kind', 'status', 'label', 'project', 'client', 'take',
- 'created_at', 'finished_at')}
- progress = view.get('progress') or {}
- value['progress'] = {k: progress[k] for k in ('phase', 'step', 'fraction', 'remaining_seconds',
- 'queue_position') if progress.get(k) is not None}
- if view.get('waiting_for'):
- value['waiting_for'] = len(view['waiting_for'])
- if view.get('error'):
- value['error'] = view['error']
- video = (view.get('result') or {}).get('video') or {}
- if video.get('url'):
- value['video'] = video['url']
- if (view.get('result') or {}).get('library_id'):
- # The work this video became, for the page to show it in My works.
- value['work'] = view['result']['library_id']
- return value
- return dict(active=sum(1 for r in rows if r['status'] in ACTIVE), jobs=[item(r) for r in shown])
+ return dict(active=sum(1 for r in rows if r['status'] in ACTIVE), jobs=[activity_item(r) for r in shown])
return reply(await asyncio.to_thread(read))
@routes.post('/freevideo/agent/activity/cancel')
@@ -1266,23 +1439,35 @@ def register():
async def inbox(request):
# The hook already attached this request to the caller's session; answer with its unread user words.
store, sid = work_sessions(), request.get('agent_session')
- deadline = time.monotonic() + min(25., float(request[query_key].get('wait', '0') or 0))
- while True:
- if store is not None and sid is not None:
- # Mark before reading so words arriving in between wake the wait below.
- def read():
- mark = store.get(sid)['last_seq']
- return mark, store.unread(sid, request['agent_client'])
- mark, pending = await asyncio.to_thread(read)
- if pending:
- return reply(dict(session=sid, inbox=pending[-20:]))
- left = deadline - time.monotonic()
- if left <= 0:
- return reply(dict(session=sid, inbox=[]))
- if store is None or sid is None:
- await asyncio.sleep(min(left, 1.))
- else:
- await store.wait(sid, after=mark, seconds=left, by='user')
+ client = request['agent_client']
+ if store is not None and sid is None:
+ # An agent that only listens has no session yet: give it one, so the page can speak into it.
+ sid = await asyncio.to_thread(lambda: store.latest_for(client) or store.create(client=client)['id'])
+ request['agent_session'] = sid
+ deadline = time.monotonic() + min(50., float(request[query_key].get('wait', '0') or 0))
+ chat['waiting'] += 1
+ try:
+ while True:
+ if store is not None and sid is not None:
+ # Mark before reading so words arriving in between wake the wait below.
+ def read():
+ mark = store.get(sid)['last_seq']
+ return mark, store.unread(sid, client)
+ mark, pending = await asyncio.to_thread(read)
+ if pending:
+ return reply(dict(session=sid, inbox=pending[-20:]))
+ left = deadline - time.monotonic()
+ if left <= 0:
+ # again: nothing new this time; the caller simply waits once more.
+ return reply(dict(session=sid, inbox=[], again=True))
+ if store is None or sid is None:
+ await asyncio.sleep(min(left, 1.))
+ else:
+ await store.wait(sid, after=mark, seconds=min(left, 25.), by='user')
+ finally:
+ chat['waiting'] -= 1
+ # The agent was here for the whole wait, not only when it began.
+ connection['last_seen_at'] = time.time()
@routes.get(PREFIX + '/queue')
@guarded
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index 76adf72..94d6dfa 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -58,6 +58,9 @@ FILE = string(1024, pattern=r'^(?!/)(?!.*(?:\\|:))(?!.*(?:^|/)\.\.(?:/|$)).+$')
FRAME = {'oneOf': [enum(('first', 'last')), number(0)]}
WAIT = number(0, default=0, description='x-clamp caps accepted wait values at 25 seconds without rejecting larger values.', **{'x-clamp': 25})
CLIENT_WAIT = number(0, 25, default=25)
+# Waiting for the user's words is longer: a person types slowly, and each wait is one tool call.
+INBOX_WAIT = number(0, default=0, description='x-clamp caps accepted wait values at 50 seconds without rejecting larger values.', **{'x-clamp': 50})
+CHAT_ID = string(64, pattern=r'^[A-Za-z0-9_-]{1,64}$')
EMPTY = obj()
@@ -291,8 +294,8 @@ def contracts(*, local=False):
('POST', '/connect/hello'): route('Report a connected client', body=obj(dict(client=string(80),
via=enum(('mcp', 'http'))), ('client', 'via'))),
('GET', '/connect/status'): route('Read recent connection status', auth=False, local=True),
- ('GET', '/inbox'): route("Wait at most 25 seconds for the user's words or answers in this session",
- query=obj({'wait': WAIT})),
+ ('GET', '/inbox'): route("Wait at most 50 seconds for the user's words or answers in this session; "
+ "again=true means nothing new yet, call it again", query=obj({'wait': INBOX_WAIT})),
}
for name, (method, suffix, summary) in DRAMA_OPERATIONS.items():
shape = drama_schema(name)
@@ -333,8 +336,14 @@ def contracts(*, local=False):
body=obj({'ref': REF}), path=obj({'id': PRODUCTION}, ('id',)), auth=False, local=True, idempotent=True)
for suffix, method, body in (('', 'GET', None), ('/session', 'GET', None), ('/activity', 'GET', None),
('/activity/cancel', 'POST', obj({'id': JOB}, ('id',))), ('/connect', 'GET', None),
- ('/connect/reset', 'POST', EMPTY)):
+ ('/connect/reset', 'POST', EMPTY), ('/chat', 'GET', None), ('/chat/now', 'GET', None),
+ ('/chat/video', 'GET', None),
+ ('/chat', 'POST', obj({'text': string(8000), 'id': CHAT_ID}, ('text', 'id'))),
+ ('/chat/confirm', 'POST', obj({'id': string(12, pattern=r'^cf[0-9a-f]{10}$'), 'approve': {'type': 'boolean'}},
+ ('id', 'approve')))):
routes[(method, '/freevideo/agent' + suffix)] = route('Studio Agent controls', body=body, auth=False, local=True)
+ routes['GET', '/freevideo/agent/chat']['query'] = obj({'after': number(0, integer=True)})
+ routes['GET', '/freevideo/agent/chat/video']['query'] = obj({'id': string(43, pattern=r'^[0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9a-f]{32}$')}, ('id',))
for suffix in ('', '/connect'):
routes['GET', '/freevideo/agent' + suffix]['query'] = obj({'lang': enum(('zh', 'en'))})
for name, (method, suffix, summary) in SESSION_OPERATIONS.items():
@@ -1363,7 +1372,7 @@ def _tool_schema(name):
value['required'].append('shot')
if name == 'freevideo_wait':
value['properties'].pop('wait')
- value['properties']['timeout'] = CLIENT_WAIT
+ value['properties']['timeout'] = number(0, 50, default=25, description='With id at most 25 seconds; without id (the user) up to 50, default 50.')
value['required'] = [k for k in value['required'] if k != 'id']
return value
if name == 'freevideo_asset':
diff --git a/freevideo_engine/agent/sessions.py b/freevideo_engine/agent/sessions.py
index 7febb1e..5d48ab0 100644
--- a/freevideo_engine/agent/sessions.py
+++ b/freevideo_engine/agent/sessions.py
@@ -316,6 +316,12 @@ class Sessions:
rows = [row for sid, row in self._meta.items() if client in self._clients[sid]]
return max(rows, key=lambda r: (r['updated_at'], r['id']))['id'] if rows else None
+ def read_until(self, sid, reader) -> int:
+ """The last event this reader has been given; unread() moves it."""
+ with self.lock:
+ self._get(sid)
+ return self._readers.get((sid, reader), self._initial_seq[sid])
+
def stopped(self, sid) -> bool:
with self.lock:
return self._get(sid)['stopped']