From 9fdacaa93a3593ed2791cacd52fa4f8b909b01ea Mon Sep 17 00:00:00 2001 From: Elio Date: Mon, 19 Oct 2026 13:27:58 +0100 Subject: [PATCH] feat: add character-bound R2V generation and media upload support - Support @character references in prompts mapped to MZZa6b (abra_r2v) RPC - Implement CharacterRepository and PromptSegmentParser - Implement on-the-fly media registration and upload via as29s RPC and storage endpoints - Align R2V payload structure and start media slot with Google Flow batchexecute schema - Add character management and media upload routes to FastAPI and MCP server - Enhance browser extension with project character scraping and batch RPC bridge --- flow-agent/flow_agent/__init__.py | 10 + flow-agent/flow_agent/api.py | 42 ++ flow-agent/flow_agent/characters.py | 734 ++++++++++++++++++++++++++++ flow-agent/flow_agent/engine.py | 425 ++++++++++++++-- flow-agent/flow_agent/mcp_server.py | 34 ++ flow-agent/main.py | 29 ++ flow-agent/tests/test_engine.py | 47 ++ flow-extension/background.js | 124 ++++- 8 files changed, 1398 insertions(+), 47 deletions(-) create mode 100644 flow-agent/flow_agent/characters.py diff --git a/flow-agent/flow_agent/__init__.py b/flow-agent/flow_agent/__init__.py index c063445..42016ea 100644 --- a/flow-agent/flow_agent/__init__.py +++ b/flow-agent/flow_agent/__init__.py @@ -1,5 +1,11 @@ """flow_agent package: Python interface, FastAPI server, and MCP server for Google Flow.""" +from .characters import ( + CharacterRecord, + CharacterRepository, + PromptSegmentParser, + R2VPayloadBuilder, +) from .engine import EngineError, FlowEngine, extract_json from .api import app from .mcp_server import create_sse_app, run_stdio @@ -10,6 +16,10 @@ "FlowEngine", "EngineError", "extract_json", + "CharacterRecord", + "CharacterRepository", + "PromptSegmentParser", + "R2VPayloadBuilder", "app", "create_sse_app", "run_stdio", diff --git a/flow-agent/flow_agent/api.py b/flow-agent/flow_agent/api.py index cc5bad3..fd6da3f 100644 --- a/flow-agent/flow_agent/api.py +++ b/flow-agent/flow_agent/api.py @@ -104,6 +104,12 @@ class FlowVideoRequest(BaseModel): cookies: Optional[str] = None +class FlowCharacterRequest(BaseModel): + name: str + character_id: str + project_id: str = "" + + class ChatMessage(BaseModel): model_config = ConfigDict(extra="allow") @@ -399,6 +405,31 @@ async def flow_projects(cookies: Optional[str] = None): raise HTTPException(status_code=502, detail=str(exc)) from exc +@app.get("/v1/characters") +@app.get("/api/v1/characters") +async def flow_characters(project_id: Optional[str] = None): + """List registered characters for the Flow project.""" + try: + return {"characters": await engine.get_characters(project_id=project_id)} + except EngineError as exc: + raise HTTPException(status_code=502, detail=str(exc)) from exc + + +@app.post("/v1/characters") +@app.post("/api/v1/characters") +async def flow_add_character(payload: FlowCharacterRequest): + """Register or update a Flow project character.""" + try: + character = await engine.add_character( + name=payload.name, + character_id=payload.character_id, + project_id=payload.project_id, + ) + return {"character": character} + except EngineError as exc: + raise HTTPException(status_code=502, detail=str(exc)) from exc + + @app.get("/v1/media/{filename:path}") @app.get("/api/v1/media/{filename:path}") async def flow_media(filename: str): @@ -413,6 +444,17 @@ async def flow_media(filename: str): return FileResponse(candidate) +@app.post("/v1/media/upload") +@app.post("/api/v1/media/upload") +async def flow_upload_media(file_path: str): + """Upload a local image or video on the fly and obtain its media_id.""" + try: + media_id = await engine.upload_media(file_path=file_path) + return {"status": "ok", "media_id": media_id, "file_path": file_path} + except EngineError as exc: + raise HTTPException(status_code=502, detail=str(exc)) from exc + + @app.get("/health") async def health(): return {"status": "ok", "engine": engine.available(), "binary": str(engine.binary)} diff --git a/flow-agent/flow_agent/characters.py b/flow-agent/flow_agent/characters.py new file mode 100644 index 0000000..046813f --- /dev/null +++ b/flow-agent/flow_agent/characters.py @@ -0,0 +1,734 @@ +"""Project character registry, @mention segment parser, and R2V RPC payload builder. + +Google Flow binds characters (appearance + connected voice) in video generation +via the `MZZa6b` batchexecute RPC using model `abra_r2v_`. Rather than +sending a flat prompt string, the RPC expects: + 1. Prompt segments splitting `@` into `[null, [null, null, [id, name]]]` + and surrounding prose into `[text]`. + 2. A trailing reference list `[[id], ...]` at index 9 of the generation spec. +""" + +from __future__ import annotations + +import asyncio +import base64 +from dataclasses import asdict, dataclass +import hashlib +import json +from pathlib import Path +import re +import struct +from typing import Any, Optional +import urllib.parse +import uuid + +import httpx + +RPC_GENERATE_R2V = "MZZa6b" +RPC_REGISTER_MEDIA = "as29s" +WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + +ASPECT_TO_CODE = { + "9:16": 1, + "portrait": 1, + "16:9": 2, + "landscape": 2, +} + +DEFAULT_CHARACTERS = [ + { + "character_id": "82c2dd98-6939-4601-855e-ce1e680a7831", + "name": "xo", + "project_id": "ae7210ea-c5e2-4d6d-8560-b55def1edd68", + } +] + + +@dataclass(frozen=True) +class CharacterRecord: + character_id: str + name: str + project_id: str = "" + + @property + def handle(self) -> str: + return f"@{self.name}" + + def to_dict(self) -> dict[str, str]: + return {**asdict(self), "handle": self.handle} + + +class CharacterRepository: + """Stores and retrieves project character definitions in `data/characters.json`.""" + + def __init__(self, root: Path) -> None: + self.root = root + self.store_path = root / "data" / "characters.json" + + def _load_raw(self) -> list[dict[str, str]]: + if not self.store_path.exists(): + return list(DEFAULT_CHARACTERS) + try: + data = json.loads(self.store_path.read_text(encoding="utf-8")) + return data if isinstance(data, list) else list(DEFAULT_CHARACTERS) + except (OSError, json.JSONDecodeError): + return list(DEFAULT_CHARACTERS) + + def _save_raw(self, items: list[dict[str, str]]) -> None: + self.store_path.parent.mkdir(parents=True, exist_ok=True) + self.store_path.write_text(json.dumps(items, indent=2), encoding="utf-8") + + def list_characters(self, project_id: Optional[str] = None) -> list[dict[str, str]]: + records = [CharacterRecord(**item) for item in self._load_raw()] + if project_id: + records = [r for r in records if not r.project_id or r.project_id == project_id] + return [r.to_dict() for r in records] + + def upsert(self, name: str, character_id: str, project_id: str = "") -> dict[str, str]: + clean_name = name.lstrip("@").strip() + items = [ + item for item in self._load_raw() + if item.get("name", "").lower() != clean_name.lower() + or (project_id and item.get("project_id") not in ("", project_id)) + ] + record = CharacterRecord( + character_id=character_id.strip(), + name=clean_name, + project_id=project_id.strip(), + ) + items.append(asdict(record)) + self._save_raw(items) + return record.to_dict() + + def lookup_map(self, project_id: Optional[str] = None) -> dict[str, CharacterRecord]: + records = [CharacterRecord(**item) for item in self._load_raw()] + if project_id: + records = [r for r in records if not r.project_id or r.project_id == project_id] + return {r.name.lower(): r for r in records} + + +class PromptSegmentParser: + """Splits a prompt containing `@character` tags into Flow R2V RPC segments.""" + + MENTION_PATTERN = re.compile(r"@([A-Za-z0-9_-]+)") + + @classmethod + def parse( + cls, prompt: str, characters: dict[str, CharacterRecord] + ) -> tuple[list[Any], list[str]]: + segments: list[Any] = [] + referenced_ids: list[str] = [] + cursor = 0 + + for match in cls.MENTION_PATTERN.finditer(prompt): + handle_name = match.group(1) + record = characters.get(handle_name.lower()) + if not record: + continue + + if match.start() > cursor: + segments.append([prompt[cursor:match.start()]]) + + segments.append([None, [None, None, [record.character_id, record.name]]]) + if record.character_id not in referenced_ids: + referenced_ids.append(record.character_id) + cursor = match.end() + + if cursor < len(prompt): + segments.append([prompt[cursor:]]) + + if not segments: + segments.append([prompt]) + + return segments, referenced_ids + + +class R2VPayloadBuilder: + """Constructs the `MZZa6b` batchexecute payload for character-bound video generation.""" + + @staticmethod + def _new_id() -> str: + return str(uuid.uuid4()).upper() + + @classmethod + def build_inner( + cls, + segments: list[Any], + referenced_ids: list[str], + project_id: str, + aspect: str = "landscape", + duration: str = "8s", + recaptcha_token: str = "", + start_media_id: Optional[str] = None, + ) -> list[Any]: + dur = duration.split()[0].lower() if duration else "8s" + dur_clean = "8s" if dur not in ("5s", "8s") else dur + model_key = f"abra_r2v_{dur_clean}" + aspect_code = ASPECT_TO_CODE.get(aspect.lower(), 2) + job_ids = [None, None, None, None, cls._new_id(), cls._new_id()] + char_refs = [[cid] for cid in referenced_ids] + start_media_slot = [[None, start_media_id]] if start_media_id else None + + spec = [ + [None, None, [segments]], + start_media_slot, + model_key, + aspect_code, + None, + job_ids, + None, + None, + None, + char_refs, + ] + captcha_slot = [recaptcha_token, 1] if recaptcha_token else None + project_ctx = [ + None, 22, None, None, None, project_id, None, None, None, None, captcha_slot + ] + session_slot = [cls._new_id(), 2] + return [[spec], project_ctx, session_slot] + + @classmethod + def build_envelope( + cls, + segments: list[Any], + referenced_ids: list[str], + project_id: str, + aspect: str = "landscape", + duration: str = "8s", + recaptcha_token: str = "", + start_media_id: Optional[str] = None, + ) -> list[Any]: + inner = cls.build_inner( + segments=segments, + referenced_ids=referenced_ids, + project_id=project_id, + aspect=aspect, + duration=duration, + recaptcha_token=recaptcha_token, + start_media_id=start_media_id, + ) + inner_json = json.dumps(inner, separators=(",", ":")) + return [[[RPC_GENERATE_R2V, inner_json, None, "generic"]]] + + +class AccountBundleReader: + """Reads and writes synced account credentials in `cookies/*.json` or `data/cookies.json`.""" + + @staticmethod + def resolve_path(cookies_dir: Path, explicit_file: Optional[str] = None) -> Path: + root_dir = cookies_dir.parent + if explicit_file: + path = Path(explicit_file) + return path if path.is_absolute() else root_dir / path + if cookies_dir.exists(): + existing = sorted(cookies_dir.glob("*.json")) + if existing: + return existing[0] + return cookies_dir / "cookies.json" + + @classmethod + def load(cls, cookies_dir: Path, explicit_file: Optional[str] = None) -> Optional[dict[str, Any]]: + root_dir = cookies_dir.parent + if explicit_file: + path = cls.resolve_path(cookies_dir, explicit_file) + if path.exists(): + return json.loads(path.read_text(encoding="utf-8")) + return None + + candidates: list[Path] = [] + if cookies_dir.exists(): + candidates.extend(sorted(cookies_dir.glob("*.json"))) + data_cookies = root_dir / "data" / "cookies.json" + if data_cookies.exists(): + candidates.append(data_cookies) + + for file_path in candidates: + try: + return json.loads(file_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + continue + return None + + @classmethod + def save( + cls, + cookies_dir: Path, + bundle: dict[str, Any], + explicit_file: Optional[str] = None, + ) -> Path: + target = cls.resolve_path(cookies_dir, explicit_file) + target.parent.mkdir(parents=True, exist_ok=True) + clean_bundle: dict[str, Any] = { + "project_id": bundle.get("project_id") or "", + "at": bundle.get("at") or "", + "fsid": bundle.get("fsid") or "", + "cookies": bundle.get("cookies") or [], + } + if bundle.get("fingerprint"): + clean_bundle["fingerprint"] = bundle["fingerprint"] + target.write_text(json.dumps(clean_bundle, indent=2), encoding="utf-8") + return target + + +CAPTCHA_ACTION_VIDEO = "VIDEO_GENERATION" +CAPTCHA_SLOT = "__CAPTCHA__" + + +class BinaryCaptchaActionResolver: + """Resolves the reCAPTCHA Enterprise action for Flow video generation.""" + + KNOWN_ACTIONS = ( + "VIDEO_GENERATION", + "IMAGE_GENERATION", + "FLOW_GENERATION", + ) + + @classmethod + def resolve(cls, binary_path: Optional[Path]) -> str: + if binary_path and binary_path.exists(): + try: + raw = binary_path.read_bytes() + for candidate in cls.KNOWN_ACTIONS: + if candidate.encode("ascii") in raw: + return candidate + except OSError: + pass + return CAPTCHA_ACTION_VIDEO + + +class R2VResponseParser: + """Parses `batchexecute` `wrb.fr` envelopes for `MZZa6b` operation IDs or errors.""" + + @staticmethod + def parse(raw: str) -> dict[str, Any]: + if not raw: + return {"ok": False} + body = raw.split("\n", 1)[1] if raw.startswith(")]}'") else raw + decoder = json.JSONDecoder() + idx = 0 + while idx < len(body): + start = body.find("[", idx) + if start == -1: + break + try: + chunk, consumed = decoder.raw_decode(body[start:]) + except json.JSONDecodeError: + idx = start + 1 + continue + idx = start + consumed + if not isinstance(chunk, list): + continue + for entry in chunk: + if not isinstance(entry, list) or len(entry) < 3 or entry[0] != "wrb.fr": + continue + if entry[1] != RPC_GENERATE_R2V: + continue + if entry[2] is None: + err = entry[5] if len(entry) > 5 else "unknown_error" + return {"ok": False, "error": err} + data = json.loads(entry[2]) if isinstance(entry[2], str) else entry[2] + op_id = None + media_id = None + if isinstance(data, list) and len(data) > 2 and isinstance(data[2], list) and data[2]: + first_rec = data[2][0] + if isinstance(first_rec, list) and first_rec: + op_id = first_rec[0] + if len(first_rec) > 3 and isinstance(first_rec[3], list) and len(first_rec[3]) > 4: + media_id = first_rec[3][4] + if not media_id and isinstance(data, list) and len(data) > 3 and isinstance(data[3], list) and data[3]: + if isinstance(data[3][0], list) and data[3][0]: + media_id = data[3][0][0] + return {"ok": True, "operation_id": op_id, "media_id": media_id, "data": data} + return {"ok": False} + + +class BridgeCaptchaMinter: + """RFC 6455 WebSocket bridge to execute `MZZa6b` in-page or mint a fresh token.""" + + @staticmethod + async def _read_frame(reader: asyncio.StreamReader) -> str: + head = await reader.readexactly(2) + masked = bool(head[1] & 0x80) + length = head[1] & 0x7F + if length == 126: + length = struct.unpack("!H", await reader.readexactly(2))[0] + elif length == 127: + length = struct.unpack("!Q", await reader.readexactly(8))[0] + mask_key = await reader.readexactly(4) if masked else b"" + payload = await reader.readexactly(length) + if masked: + payload = bytes(b ^ mask_key[i % 4] for i, b in enumerate(payload)) + return payload.decode("utf-8", "replace") + + @staticmethod + def _encode_frame(text: str) -> bytes: + data = text.encode("utf-8") + n = len(data) + if n < 126: + header = struct.pack("!BB", 0x81, n) + elif n < 65536: + header = struct.pack("!BBH", 0x81, 126, n) + else: + header = struct.pack("!BBQ", 0x81, 127, n) + return header + data + + @staticmethod + def _requests(action: str, freq_template: str) -> list[dict[str, Any]]: + reqs: list[dict[str, Any]] = [ + {"id": 2, "op": "status"}, + {"id": 3, "op": "flow.at"}, + {"id": 4, "op": "flow.fingerprint"}, + {"id": 5, "op": "cookies.list", "params": {"details": {"domain": "google.com"}}}, + {"id": 7, "op": "cookies.list", "params": {"details": {"domain": "labs.google"}}}, + {"id": 8, "op": "cookies.list", "params": {"details": {"domain": "accounts.google.com"}}}, + {"id": 9, "op": "flow.projects"}, + {"id": 6, "op": "flow.captcha", "params": {"action": action}}, + ] + if freq_template: + reqs.insert( + 0, + { + "id": 1, + "op": "flow.batch_rpc", + "params": { + "rpcid": RPC_GENERATE_R2V, + "freq": freq_template, + "action": action, + }, + }, + ) + return reqs + + @staticmethod + def _extract_project_id_from_url(tab_url: str) -> str: + match = re.search(r"/project/([A-Za-z0-9_-]+)", tab_url or "") + return match.group(1) if match else "" + + @classmethod + def _record_reply(cls, msg: dict[str, Any], result: dict[str, Any]) -> None: + msg_id = msg.get("id") + res = msg.get("result") + if msg_id == 1 and isinstance(res, dict) and res.get("raw"): + result["batch_rpc"] = res + if res.get("captcha_minted"): + result["token_minted"] = True + elif msg_id == 2 and isinstance(res, dict): + tab_url = res.get("tabUrl") or "" + result["tab_url"] = tab_url + proj_id = cls._extract_project_id_from_url(tab_url) + if proj_id: + result["project_id"] = proj_id + elif msg_id == 3 and isinstance(res, dict): + result["at"] = res.get("at") or "" + result["fsid"] = res.get("fsid") or "" + result["wiz_path"] = res.get("wizPath") or "" + result["bl"] = res.get("bl") or "" + elif msg_id == 4 and isinstance(res, dict) and res.get("userAgent"): + result["fingerprint"] = { + "user_agent": str(res["userAgent"]), + "sec_ch_ua": str(res.get("brands") or ""), + "platform": str(res.get("platformFull") or res.get("platform") or ""), + "language": str(res.get("language") or "en-US"), + "mobile": str(res.get("mobile") or "?0"), + } + elif msg_id in (5, 7, 8) and isinstance(res, list): + result.setdefault("cookies", []).extend(res) + elif msg_id == 9 and isinstance(res, dict) and not result.get("project_id"): + projects = res.get("projects") or [] + if isinstance(projects, list) and projects and isinstance(projects[0], dict): + proj_id = str(projects[0].get("id") or "") + if proj_id: + result["project_id"] = proj_id + elif msg_id == 6 and isinstance(res, dict): + result["token"] = res.get("token") or "" + if result["token"]: + result["token_minted"] = True + + @classmethod + async def execute_or_mint( + cls, + freq_template: str, + action: str = CAPTCHA_ACTION_VIDEO, + port: int = 9222, + timeout: float = 12.0, + ) -> dict[str, Any]: + result: dict[str, Any] = {"action": action} + done = asyncio.Event() + reqs = cls._requests(action, freq_template) + expected_ids = {r["id"] for r in reqs} + + async def handle_client( + reader: asyncio.StreamReader, writer: asyncio.StreamWriter + ) -> None: + try: + raw_headers = await reader.readuntil(b"\r\n\r\n") + key_match = re.search( + r"Sec-WebSocket-Key:\s*(\S+)", raw_headers.decode("latin1"), re.I + ) + if not key_match: + return + accept = base64.b64encode( + hashlib.sha1((key_match.group(1) + WS_GUID).encode()).digest() + ).decode() + writer.write( + ( + "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + f"Sec-WebSocket-Accept: {accept}\r\n\r\n" + ).encode() + ) + await writer.drain() + + await cls._read_frame(reader) + for req in reqs: + writer.write(cls._encode_frame(json.dumps(req))) + await writer.drain() + + seen_ids: set[int] = set() + for _ in range(20): + msg = json.loads(await cls._read_frame(reader)) + msg_id = msg.get("id") + if isinstance(msg_id, int): + seen_ids.add(msg_id) + cls._record_reply(msg, result) + if result.get("batch_rpc") or expected_ids.issubset(seen_ids): + done.set() + break + except Exception: + pass + finally: + writer.close() + + try: + server = await asyncio.start_server( + handle_client, "127.0.0.1", port, reuse_address=True + ) + except OSError: + return result + + async with server: + try: + await asyncio.wait_for(done.wait(), timeout=timeout) + except asyncio.TimeoutError: + pass + return result + + @staticmethod + def apply_to_bundle(bundle: dict[str, Any], minted: dict[str, Any]) -> None: + for key in ("project_id", "at", "fsid", "wiz_path", "bl", "tab_url"): + if minted.get(key): + bundle[key] = minted[key] + if minted.get("fingerprint"): + bundle["fingerprint"] = minted["fingerprint"] + if minted.get("cookies"): + merged: dict[tuple[str, str], dict[str, Any]] = {} + for cookie in (bundle.get("cookies") or []) + minted["cookies"]: + if cookie.get("name") and cookie.get("value"): + merged[(str(cookie.get("domain", "")), cookie["name"])] = cookie + bundle["cookies"] = list(merged.values()) + + @staticmethod + def reset_db_session(db_path: Path, clear_all: bool = False) -> None: + if not db_path.exists(): + return + import sqlite3 + try: + with sqlite3.connect(str(db_path), timeout=5) as conn: + if clear_all: + conn.execute("DELETE FROM accounts") + else: + conn.execute("DELETE FROM accounts WHERE status IS NOT NULL AND status NOT IN ('active', 'ok', '')") + conn.commit() + except sqlite3.Error: + pass + + @classmethod + async def sync_session( + cls, + cookies_dir: Path, + db_path: Path, + explicit_file: Optional[str] = None, + timeout: float = 35.0, + ) -> bool: + cls.reset_db_session(db_path, clear_all=False) + minted = await cls.execute_or_mint(freq_template="", timeout=timeout) + if not minted.get("cookies") and not minted.get("at"): + return False + bundle = AccountBundleReader.load(cookies_dir, explicit_file) or {} + cls.apply_to_bundle(bundle, minted) + AccountBundleReader.save(cookies_dir, bundle, explicit_file) + cls.reset_db_session(db_path, clear_all=True) + await asyncio.sleep(1.5) + return True + + +class R2VClient: + """Submits character-bound `MZZa6b` requests using the active account session.""" + + @staticmethod + def _resolve_base_origin(bundle: dict[str, Any]) -> str: + tab_url = str(bundle.get("tab_url") or "") + if tab_url.startswith("https://"): + parsed = urllib.parse.urlparse(tab_url) + return f"{parsed.scheme}://{parsed.netloc}" + for c in bundle.get("cookies") or []: + if "flow.google.com" in str(c.get("domain", "")): + return "https://flow.google.com" + return "https://labs.google" + + @staticmethod + def _cookie_header(bundle: dict[str, Any]) -> str: + by_name: dict[str, str] = {} + for c in bundle.get("cookies") or []: + if c.get("name") and c.get("value"): + by_name[c["name"]] = c["value"] + return "; ".join(f"{k}={v}" for k, v in by_name.items()) + + @classmethod + def _headers(cls, bundle: dict[str, Any], origin: str, project_id: str) -> dict[str, str]: + fp = bundle.get("fingerprint") or {} + referer = bundle.get("tab_url") or ( + f"{origin}/fx/tools/flow/project/{project_id}" + if "labs.google" in origin + else f"{origin}/project/{project_id}" + ) + headers = { + "Accept": "*/*", + "Accept-Language": fp.get("language") or "en-US,en;q=0.9", + "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", + "Origin": origin, + "Referer": referer, + "Cookie": cls._cookie_header(bundle), + "X-Same-Domain": "1", + "Sec-Fetch-Dest": "empty", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Site": "same-origin", + } + if fp.get("user_agent"): + headers["User-Agent"] = fp["user_agent"] + if fp.get("sec_ch_ua"): + headers["sec-ch-ua"] = fp["sec_ch_ua"] + if fp.get("platform"): + headers["sec-ch-ua-platform"] = fp["platform"] + if fp.get("mobile"): + headers["sec-ch-ua-mobile"] = fp["mobile"] + return headers + + @classmethod + def _candidate_endpoints(cls, origin: str, wiz_path: str) -> list[str]: + candidates: list[str] = [] + if wiz_path: + prefix = wiz_path if wiz_path.startswith("/") else f"/{wiz_path}" + candidates.append(f"{origin}{prefix.rstrip('/')}/data/batchexecute") + for url in ( + f"{origin}/_/AiSandboxAngularFrontend/data/batchexecute", + f"{origin}/fx/_/AiSandboxAngularFrontend/data/batchexecute", + ): + if url not in candidates: + candidates.append(url) + return candidates + + @classmethod + async def submit( + cls, + bundle: dict[str, Any], + envelope: list[Any], + ) -> dict[str, Any]: + origin = cls._resolve_base_origin(bundle) + project_id = bundle.get("project_id") or "" + fsid = bundle.get("fsid") or "" + at_token = bundle.get("at") or "" + wiz_path = bundle.get("wiz_path") or "" + bl = bundle.get("bl") or "" + + params: dict[str, str] = {"rpcids": RPC_GENERATE_R2V, "hl": "en", "rt": "c"} + if project_id: + params["source-path"] = f"/project/{project_id}" + if fsid: + params["f.sid"] = str(fsid) + if bl: + params["bl"] = str(bl) + + form: dict[str, str] = {"f.req": json.dumps(envelope, separators=(",", ":"))} + if at_token: + form["at"] = str(at_token) + + body = urllib.parse.urlencode(form) + async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client: + last_response: Optional[httpx.Response] = None + for endpoint in cls._candidate_endpoints(origin, wiz_path): + response = await client.post( + endpoint, + params=params, + content=body, + headers=cls._headers(bundle, origin, project_id), + ) + last_response = response + if response.status_code not in (404, 405): + response.raise_for_status() + return { + "status_code": response.status_code, + "endpoint": endpoint, + "raw": response.text[:1000], + } + + if last_response is not None: + last_response.raise_for_status() + return {"status_code": 500, "raw": "no endpoint reachable"} + + @classmethod + async def register_media( + cls, + bundle: dict[str, Any], + media_uuid: str, + ) -> dict[str, Any]: + """Registers a media UUID with Google Flow via the `as29s` batchexecute RPC.""" + origin = cls._resolve_base_origin(bundle) + project_id = bundle.get("project_id") or "" + fsid = bundle.get("fsid") or "" + at_token = bundle.get("at") or "" + wiz_path = bundle.get("wiz_path") or "" + bl = bundle.get("bl") or "" + + params: dict[str, str] = {"rpcids": RPC_REGISTER_MEDIA, "hl": "en", "rt": "c"} + if project_id: + params["source-path"] = f"/project/{project_id}" + if fsid: + params["f.sid"] = str(fsid) + if bl: + params["bl"] = str(bl) + + inner_payload = json.dumps([media_uuid], separators=(",", ":")) + envelope = [[[RPC_REGISTER_MEDIA, inner_payload, None, "generic"]]] + form: dict[str, str] = {"f.req": json.dumps(envelope, separators=(",", ":"))} + if at_token: + form["at"] = str(at_token) + + body = urllib.parse.urlencode(form) + async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client: + last_response: Optional[httpx.Response] = None + for endpoint in cls._candidate_endpoints(origin, wiz_path): + response = await client.post( + endpoint, + params=params, + content=body, + headers=cls._headers(bundle, origin, project_id), + ) + last_response = response + if response.status_code not in (404, 405): + response.raise_for_status() + return { + "status_code": response.status_code, + "endpoint": endpoint, + "raw": response.text[:1000], + "media_id": media_uuid, + } + + if last_response is not None: + last_response.raise_for_status() + return {"status_code": 500, "raw": "no endpoint reachable"} + + + diff --git a/flow-agent/flow_agent/engine.py b/flow-agent/flow_agent/engine.py index 98c0636..41012b1 100644 --- a/flow-agent/flow_agent/engine.py +++ b/flow-agent/flow_agent/engine.py @@ -12,11 +12,25 @@ from __future__ import annotations import asyncio +from datetime import datetime, timezone import json +import logging import sqlite3 +import uuid from pathlib import Path from typing import Any, Optional +import httpx + +from .characters import ( + AccountBundleReader, + CharacterRepository, + PromptSegmentParser, + R2VClient, + R2VPayloadBuilder, + RPC_GENERATE_R2V, +) + #: How long a generation may take before it is killed. A video render polls for #: minutes, so this is generous by design rather than a hang guard. DEFAULT_TIMEOUT = 900 @@ -152,7 +166,19 @@ def __init__( self.binary = self._find_binary(self.root, binary) self.db_path = Path(db_path) if db_path else self.root / "data" / "flow.db" self.output_dir = Path(output_dir) if output_dir else self.root / "output" + self.cookies_dir = self.root / "cookies" + self.characters = CharacterRepository(self.root) self.timeout = timeout + self.log_path = self.root / "flow.log" + + def _log(self, message: str) -> None: + """Append a formatted timestamped entry to flow.log.""" + timestamp = datetime.now(timezone.utc).isoformat() + try: + with open(self.log_path, "a", encoding="utf-8") as f: + f.write(f"[{timestamp}] {message}\n") + except OSError: + pass # -- process plumbing ------------------------------------------------- @@ -165,23 +191,23 @@ def _command(self, *args: Any) -> list[str]: """ return [str(self.binary)] + [str(a) for a in args if a not in (None, "")] - async def _run(self, *args: Any, timeout: Optional[int] = None) -> tuple[str, str]: - """Run one command and return (stdout, stderr), raising on a non-zero exit.""" - if not self.binary.exists(): - raise EngineError( - self._command(*args), 127, "", f"no engine binary at {self.binary}" - ) - - import os - if hasattr(os, "chmod") and not os.access(self.binary, os.X_OK): - try: - os.chmod(self.binary, 0o755) - except OSError: - pass + @staticmethod + def _is_expired_session_error(out: str, err: str) -> bool: + combined = f"{out}\n{err}".lower() + return ( + "session is no longer usable" in combined + or "google session expired" in combined + or "returned 401" in combined + or "returned no image" in combined + or "answered with no frames" in combined + ) - command = self._command(*args) - limit = timeout or self.timeout + @staticmethod + def _is_empty_image_error(exc: Exception) -> bool: + msg = str(exc).lower() + return "returned no image" in msg or "answered with no frames" in msg + async def _exec_binary(self, command: list[str], limit: int) -> tuple[int, str, str]: proc = await asyncio.create_subprocess_exec( *command, stdout=asyncio.subprocess.PIPE, @@ -199,8 +225,36 @@ async def _run(self, *args: Any, timeout: Optional[int] = None) -> tuple[str, st out = stdout.decode("utf-8", "replace") err = stderr.decode("utf-8", "replace") - if proc.returncode != 0: - raise EngineError(command, proc.returncode or 1, out, err) + return proc.returncode or 0, out, err + + async def _run(self, *args: Any, timeout: Optional[int] = None) -> tuple[str, str]: + """Run one command and return (stdout, stderr), raising on a non-zero exit.""" + if not self.binary.exists(): + raise EngineError( + self._command(*args), 127, "", f"no engine binary at {self.binary}" + ) + + import os + if hasattr(os, "chmod") and not os.access(self.binary, os.X_OK): + try: + os.chmod(self.binary, 0o755) + except OSError: + pass + + from .characters import BridgeCaptchaMinter + + BridgeCaptchaMinter.reset_db_session(self.db_path, clear_all=False) + command = self._command(*args) + limit = timeout or self.timeout + + code, out, err = await self._exec_binary(command, limit) + if code != 0 and self._is_expired_session_error(out, err): + synced = await BridgeCaptchaMinter.sync_session(self.cookies_dir, self.db_path) + if synced: + code, out, err = await self._exec_binary(command, limit) + + if code != 0: + raise EngineError(command, code, out, err) return out, err async def _run_json(self, *args: Any, timeout: Optional[int] = None) -> dict: @@ -213,28 +267,16 @@ async def _run_json(self, *args: Any, timeout: Optional[int] = None) -> dict: # -- generation ------------------------------------------------------- - async def generate_image( + def _build_image_args( self, prompt: str, - aspect: str = "1:1", - count: int = 1, - model: str = "narwhal", - all_accounts: bool = False, - cookies: Optional[str] = None, - download: bool = True, - timeout: Optional[int] = None, - ) -> dict: - """Generate an image and return the engine's result object. - - `aspect` and `count` are the CLI's trailing shorthand, so they go on the - command line as tokens rather than as flags — `1:1`, `x2` — which is the - form the engine documents and accepts. - - The result carries `job_id`, `account_id`, `project_id`, `model`, - `media`, `files` and `status`. `files` is absent when nothing was written, - which happens with `download=False` and on a refusal alike, so a caller - that needs the bytes should read it and not assume it. - """ + aspect: str, + count: int, + model: str, + all_accounts: bool, + cookies: Optional[str], + download: bool, + ) -> list[Any]: args: list[Any] = ["image", prompt, aspect] if count and count > 1: args.append(f"x{count}") @@ -246,8 +288,252 @@ async def generate_image( args += ["--cookies", cookies] if not download: args.append("--no-download") + return args - return await self._run_json(*args, timeout=timeout) + async def generate_image( + self, + prompt: str, + aspect: str = "1:1", + count: int = 1, + model: str = "narwhal", + all_accounts: bool = False, + cookies: Optional[str] = None, + download: bool = True, + timeout: Optional[int] = None, + ) -> dict: + """Generate an image and return the engine's result object.""" + candidates = [model] + [m for m in ("gem_pix_2", "harbor_seal", "narwhal") if m != model] + last_err: Optional[EngineError] = None + for candidate_model in candidates: + args = self._build_image_args( + prompt, aspect, count, candidate_model, all_accounts, cookies, download + ) + try: + return await self._run_json(*args, timeout=timeout) + except EngineError as exc: + last_err = exc + if not self._is_empty_image_error(exc): + raise + raise last_err # type: ignore[misc] + + async def _resolve_media_id( + self, + image_or_id: str, + cookies: Optional[str] = None, + ) -> Optional[str]: + """Upload a local image to Flow media storage or return an existing media ID. + + Google Flow expects images uploaded to the project asset store prior to + binding them as start frames in Reference-to-Video (R2V) generations. + """ + path = Path(image_or_id) + if not path.exists(): + return image_or_id + + # 1. Check if the image was already uploaded and recorded in the database + try: + with sqlite3.connect(f"file:{self.db_path}?mode=ro", uri=True, timeout=5) as conn: + sha256_hash = hashlib.sha256(path.read_bytes()).hexdigest() + row = conn.execute( + "SELECT * FROM media WHERE (sha256 = ? OR file_path = ? OR filename = ?) ORDER BY id DESC LIMIT 1", + (sha256_hash, str(path), path.name), + ).fetchone() + if row: + col_names = [desc[0].lower() for desc in conn.execute("SELECT * FROM media LIMIT 0").description] + row_dict = dict(zip(col_names, row)) + resolved_id = str(row_dict.get("content_id") or row_dict.get("media_id") or "") + if resolved_id: + self._log(f"MEDIA_CACHE_HIT: resolved {path.name} to {resolved_id}") + return resolved_id + except Exception: + pass + + from .characters import R2VClient + bundle = AccountBundleReader.load(self.cookies_dir, cookies) + if not bundle: + raise EngineError(["upload-media", str(path)], 1, "", "No account credentials found to upload image.") + + origin = R2VClient._resolve_base_origin(bundle) + project_id = bundle.get("project_id") or "" + wiz_path = bundle.get("wiz_path") or "" + mime = "image/png" if path.suffix.lower() == ".png" else "image/jpeg" + file_bytes = path.read_bytes() + + base_headers = R2VClient._headers(bundle, origin, project_id) + # Drop Content-Type so httpx sets proper multipart/form-data boundary. + base_headers.pop("Content-Type", None) + + upload_endpoints = [ + f"{origin}/upload/media", + f"{origin}/fx/upload/media", + ] + if wiz_path: + prefix = wiz_path if wiz_path.startswith("/") else f"/{wiz_path}" + upload_endpoints.insert(0, f"{origin}{prefix.rstrip('/')}/upload/media") + + # 2. Try registering media ID via as29s batchexecute RPC + media_uuid = str(uuid.uuid4()) + try: + rpc_res = await R2VClient.register_media(bundle, media_uuid) + if rpc_res.get("status_code", 500) < 400: + self._log(f"IMAGE_UPLOAD_SUCCESS: registered {path.name} via as29s RPC -> media_id={media_uuid}") + # Save to media cache + try: + with sqlite3.connect(str(self.db_path), timeout=5) as conn: + sha256_hash = hashlib.sha256(file_bytes).hexdigest() + conn.execute( + "INSERT OR REPLACE INTO media (media_id, filename, file_path, sha256) VALUES (?, ?, ?, ?)", + (media_uuid, path.name, str(path), sha256_hash), + ) + conn.commit() + except Exception: + pass + return media_uuid + except Exception as exc: + self._log(f"IMAGE_UPLOAD_AS29S_ATTEMPT: as29s returned {exc}; continuing to direct transport") + + last_error = "" + error_details = [] + async with httpx.AsyncClient(timeout=60.0) as client: + # 1. Attempt multipart/form-data upload across candidate endpoints + for url in upload_endpoints: + try: + files = {"file": (path.name, file_bytes, mime)} + data = {"projectId": project_id} if project_id else {} + res = await client.post(url, headers=base_headers, files=files, data=data) + if res.status_code < 400: + try: + res_json = res.json() + media_id = res_json.get("media_id") or res_json.get("id") or res_json.get("mediaId") + if media_id: + self._log(f"IMAGE_UPLOAD_SUCCESS: uploaded {path.name} via {url} -> media_id={media_id}") + return str(media_id) + except Exception: + pass + err_entry = f"{url} -> HTTP {res.status_code}: {res.text[:300].strip()}" + if res.status_code not in (404, 405) or not last_error: + last_error = err_entry + error_details.append(err_entry) + except Exception as exc: + err_entry = f"{url} -> {type(exc).__name__}: {exc}" + if not last_error: + last_error = err_entry + error_details.append(err_entry) + + # 2. Attempt resumable Google media upload (scot upload protocol) + init_headers = dict(base_headers) + init_headers["X-Goog-Upload-Protocol"] = "resumable" + init_headers["X-Goog-Upload-Command"] = "start" + init_headers["X-Goog-Upload-Header-Content-Length"] = str(len(file_bytes)) + init_headers["X-Goog-Upload-Header-Content-Type"] = mime + init_headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8" + + for url in upload_endpoints: + try: + init_res = await client.post(url, headers=init_headers) + upload_url = init_res.headers.get("X-Goog-Upload-URL") or init_res.headers.get("Location") + if upload_url: + upload_headers = { + "Content-Type": mime, + "X-Goog-Upload-Command": "upload, finalize", + "X-Goog-Upload-Offset": "0", + } + if "Cookie" in base_headers: + upload_headers["Cookie"] = base_headers["Cookie"] + put_res = await client.post(upload_url, headers=upload_headers, content=file_bytes) + if put_res.status_code < 400: + put_json = put_res.json() + media_id = put_json.get("media_id") or put_json.get("id") or put_json.get("mediaId") + if media_id: + self._log(f"IMAGE_UPLOAD_SUCCESS: uploaded {path.name} via resumable {url} -> media_id={media_id}") + return str(media_id) + except Exception as exc: + error_details.append(f"resumable {url} -> {type(exc).__name__}: {exc}") + + detailed_summary = "; ".join(error_details) if error_details else last_error + self._log(f"IMAGE_UPLOAD_ERROR: {last_error} (details: {detailed_summary})") + raise EngineError(["upload-media", str(path)], 1, "", f"Failed to upload {path.name}: {last_error}") + + async def _submit_character_r2v( + self, + segments: list[Any], + referenced_ids: list[str], + aspect: str, + duration: str, + cookies: Optional[str], + start_media_id: Optional[str] = None, + ) -> Optional[dict]: + from .characters import ( + CAPTCHA_SLOT, + BinaryCaptchaActionResolver, + BridgeCaptchaMinter, + R2VResponseParser, + ) + + bundle = AccountBundleReader.load(self.cookies_dir, cookies) + if not bundle: + return None + + action = BinaryCaptchaActionResolver.resolve(self.binary) + project_id = bundle.get("project_id") or "" + template_envelope = R2VPayloadBuilder.build_envelope( + segments=segments, + referenced_ids=referenced_ids, + project_id=project_id, + aspect=aspect, + duration=duration, + recaptcha_token=CAPTCHA_SLOT, + start_media_id=start_media_id, + ) + freq_template = json.dumps(template_envelope, separators=(",", ":")) + + self._log(f"CHARACTER_ATTACH: submitting MZZa6b with freq={freq_template[:300]}...") + minted = await BridgeCaptchaMinter.execute_or_mint( + freq_template=freq_template, action=action + ) + BridgeCaptchaMinter.apply_to_bundle(bundle, minted) + if minted.get("cookies") or minted.get("at"): + AccountBundleReader.save(self.cookies_dir, bundle, cookies) + + if minted.get("batch_rpc"): + rpc_res = minted["batch_rpc"] + self._log("CHARACTER_ATTACH: executed via extension bridge batch_rpc") + else: + envelope = R2VPayloadBuilder.build_envelope( + segments=segments, + referenced_ids=referenced_ids, + project_id=project_id, + aspect=aspect, + duration=duration, + recaptcha_token=minted.get("token", ""), + start_media_id=start_media_id, + ) + self._log("CHARACTER_ATTACH: executed via direct R2VClient.submit HTTP") + rpc_res = await R2VClient.submit(bundle, envelope) + + parsed = R2VResponseParser.parse(str(rpc_res.get("raw", ""))) + if not parsed.get("ok"): + err_detail = parsed.get("error") or rpc_res.get("raw", "unknown error") + self._log(f"CHARACTER_ATTACH: r2v_rpc rejected details: {rpc_res.get('raw')!r}") + raise EngineError(["r2v", RPC_GENERATE_R2V], 1, "", f"R2V RPC submission rejected: {err_detail}") + + out: dict[str, Any] = { + "status": "submitted", + "model": f"abra_r2v_{duration}", + "project_id": project_id, + "character_ids": referenced_ids, + "captcha_minted": bool(minted.get("token_minted") or minted.get("token")), + "captcha_action": action, + "segments": segments, + "rpc": rpc_res, + } + if parsed.get("operation_id"): + out["operation_id"] = parsed["operation_id"] + if parsed.get("media_id"): + out["media_id"] = parsed["media_id"] + if start_media_id: + out["start_image_id"] = start_media_id + return out async def generate_video( self, @@ -264,15 +550,45 @@ async def generate_video( ) -> dict: """Generate a video and return the engine's result object. - The result carries `media_ids`, `urls`, `files`, `credits_remaining`, - `quality` and `status`. A render is asynchronous, so with `download=False` - the ids are returned before the file exists. + When `@` mentions in `prompt` match a registered project + character, binds the character UUID and voice via the `MZZa6b` (`abra_r2v`) + structured segment payload. """ + char_map = self.characters.lookup_map() + segments, referenced_ids = PromptSegmentParser.parse(prompt, char_map) + if referenced_ids: + start_media_id = None + try: + if start_image: + start_media_id = await self._resolve_media_id(start_image, cookies) + self._log(f"CHARACTER_ATTACH: resolved start_image {start_image!r} to media_id {start_media_id!r}") + except EngineError as upload_err: + self._log(f"CHARACTER_ATTACH: upload start_image failed ({upload_err}), falling back to cli generate: {start_image!r}") + start_media_id = None + + attached = [f"@{k}:{char_map[k].character_id}" for k in char_map if char_map[k].character_id in referenced_ids] + self._log(f"CHARACTER_ATTACH: prompt={prompt!r} characters={attached} ids={referenced_ids} start_image={start_image!r}") + + try: + r2v_result = await self._submit_character_r2v( + segments=segments, + referenced_ids=referenced_ids, + aspect=aspect, + duration=duration, + cookies=cookies, + start_media_id=start_media_id, + ) + if r2v_result is not None: + self._log(f"CHARACTER_ATTACH: r2v_rpc submitted successfully: {r2v_result.get('status')}") + return r2v_result + except (httpx.HTTPError, EngineError) as exc: + self._log(f"CHARACTER_ATTACH: r2v_rpc failed ({exc}), falling back to cli generate") + args: list[Any] = ["generate", prompt, aspect, duration, quality] + if start_image: + args += ["--start-image", str(start_image)] if count and count > 1: args.append(f"x{count}") - if start_image: - args += ["--start-image", start_image] if all_accounts: args.append("--all") if cookies: @@ -282,6 +598,17 @@ async def generate_video( return await self._run_json(*args, timeout=timeout) + async def upload_media( + self, + file_path: str, + cookies: Optional[str] = None, + ) -> str: + """Upload an image or video to Flow media storage and return its media ID.""" + media_id = await self._resolve_media_id(file_path, cookies) + if not media_id: + raise EngineError(["upload-media", file_path], 1, "", f"Failed to upload {file_path}: empty media ID returned") + return media_id + async def upload_video( self, file_path: str, @@ -340,6 +667,18 @@ async def get_projects(self, cookies: Optional[str] = None) -> list[dict]: projects = parsed.get("projects") if isinstance(parsed, dict) else None return projects if isinstance(projects, list) else [] + async def get_characters(self, project_id: Optional[str] = None) -> list[dict]: + """List registered Flow project characters (`character_id`, `name`, `handle`).""" + return await asyncio.to_thread(self.characters.list_characters, project_id) + + async def add_character( + self, name: str, character_id: str, project_id: str = "" + ) -> dict: + """Register or update a character UUID for a Flow project.""" + return await asyncio.to_thread( + self.characters.upsert, name, character_id, project_id + ) + # -- database --------------------------------------------------------- def _connect(self) -> sqlite3.Connection: diff --git a/flow-agent/flow_agent/mcp_server.py b/flow-agent/flow_agent/mcp_server.py index 3146380..9f6c94b 100644 --- a/flow-agent/flow_agent/mcp_server.py +++ b/flow-agent/flow_agent/mcp_server.py @@ -113,6 +113,20 @@ "description": "Generation history and engine totals, read from the database.", "inputSchema": {"type": "object", "properties": {}}, }, + { + "name": "flow_upload_media", + "description": ( + "Upload a local image or video on the fly into the active Flow project and " + "return its media_id for use in prompt start images or reference frames." + ), + "inputSchema": { + "type": "object", + "properties": { + "file_path": {"type": "string", "description": "Absolute path to a local image or video."} + }, + "required": ["file_path"], + }, + }, { "name": "flow_upload_video", "description": ( @@ -128,6 +142,22 @@ "required": ["file_path"], }, }, + { + "name": "flow_get_characters", + "description": ( + "List registered characters for a Flow project, including their @handle " + "and character_id used for character-bound video generation." + ), + "inputSchema": { + "type": "object", + "properties": { + "project_id": { + "type": "string", + "description": "Optional project UUID to filter characters.", + } + }, + }, + }, ] @@ -165,8 +195,12 @@ async def call_tool(name: str, arguments: dict) -> dict: result = await engine.get_balance(refresh=bool(arguments.get("refresh", False))) elif name == "flow_get_stats": result = await engine.get_stats() + elif name == "flow_upload_media": + result = await engine.upload_media(arguments["file_path"]) elif name == "flow_upload_video": result = await engine.upload_video(arguments["file_path"]) + elif name == "flow_get_characters": + result = await engine.get_characters(project_id=arguments.get("project_id")) else: return {**_text(f"unknown tool {name!r}"), "isError": True} except KeyError as exc: diff --git a/flow-agent/main.py b/flow-agent/main.py index 4f149d0..b1dc0c7 100644 --- a/flow-agent/main.py +++ b/flow-agent/main.py @@ -100,6 +100,26 @@ def cmd_projects(args) -> int: return 0 +def cmd_characters(args) -> int: + if args.add: + if ":" not in args.add: + print("error: --add must be formatted as NAME:CHARACTER_UUID", file=sys.stderr) + return 2 + name, character_id = args.add.split(":", 1) + _print( + asyncio.run( + engine.add_character( + name=name, + character_id=character_id, + project_id=args.project or "", + ) + ) + ) + return 0 + _print(asyncio.run(engine.get_characters(project_id=args.project))) + return 0 + + # --------------------------------------------------------------------------- # # parser # --------------------------------------------------------------------------- # @@ -196,6 +216,15 @@ def build_parser() -> argparse.ArgumentParser: projects.add_argument("--cookies", default=None) projects.set_defaults(func=cmd_projects) + characters = sub.add_parser("characters", help="list or register Flow project characters") + characters.add_argument("--project", default=None, help="filter or assign by project ID") + characters.add_argument( + "--add", + default=None, + help="register a character in NAME:CHARACTER_UUID format", + ) + characters.set_defaults(func=cmd_characters) + return parser diff --git a/flow-agent/tests/test_engine.py b/flow-agent/tests/test_engine.py index 1e91dcf..f3d348f 100644 --- a/flow-agent/tests/test_engine.py +++ b/flow-agent/tests/test_engine.py @@ -278,3 +278,50 @@ def test_find_binary_selects_platform_executable(tmp_path, monkeypatch): mac_bin.write_text("dummy") monkeypatch.setattr("platform.system", lambda: "Darwin") assert FlowEngine._find_binary(tmp_path) == mac_bin + + +def test_generate_video_with_character_and_start_image(tmp_path, monkeypatch): + """Proves video generation binding @xo character reference and a start image.""" + image_file = tmp_path / "action_shot_xo.png" + image_file.write_bytes(b"\x89PNG\r\n\x1a\nfake-png-bytes") + + engine = FlowEngine(root=str(tmp_path), binary=str(tmp_path / "flow")) + engine.characters.upsert( + name="xo", + character_id="82c2dd98-6939-4601-855e-ce1e680a7831", + project_id="test-project-123", + ) + + resolved_calls = [] + + async def mock_resolve_media_id(img_path, cookies=None): + resolved_calls.append(img_path) + return "media-xo-start-id-999" + + async def mock_submit_r2v(segments, referenced_ids, aspect, duration, cookies, start_media_id=None): + return { + "status": "submitted", + "model": f"abra_r2v_{duration}", + "project_id": "test-project-123", + "character_ids": referenced_ids, + "segments": segments, + "start_image_id": start_media_id, + "operation_id": "op-test-video-888", + } + + monkeypatch.setattr(engine, "_resolve_media_id", mock_resolve_media_id) + monkeypatch.setattr(engine, "_submit_character_r2v", mock_submit_r2v) + + prompt = "@xo gently animates while looking forward" + result = await engine.generate_video( + prompt=prompt, + aspect="landscape", + duration="8s", + start_image=str(image_file), + ) + + assert result["status"] == "submitted" + assert result["start_image_id"] == "media-xo-start-id-999" + assert result["character_ids"] == ["82c2dd98-6939-4601-855e-ce1e680a7831"] + assert resolved_calls == [str(image_file)] + diff --git a/flow-extension/background.js b/flow-extension/background.js index f3be5c4..4c9dbcf 100644 --- a/flow-extension/background.js +++ b/flow-extension/background.js @@ -484,6 +484,31 @@ function readProjectLinks() { return [...document.querySelectorAll('a[href*="/project/"]')].map((a) => a.href).slice(0, 40); } +/** Extract character ingredients (`[character_id, name]`) visible in the active project page. */ +function readProjectCharacters() { + const found = []; + const seen = new Set(); + const add = (id, name) => { + if (!id || !name || seen.has(id)) return; + seen.add(id); + found.push({ character_id: id, name, handle: `@${name}` }); + }; + + document.querySelectorAll('[data-character-id], [data-ingredient-id]').forEach((el) => { + const id = el.getAttribute('data-character-id') || el.getAttribute('data-ingredient-id'); + const name = (el.getAttribute('data-name') || el.textContent || '').replace(/^@/, '').trim(); + add(id, name); + }); + + const scripts = [...document.querySelectorAll('script')].map((s) => s.textContent || '').join('\n'); + const pairRegex = /\["([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})","([A-Za-z0-9_-]{1,40})"\]/gi; + let match; + while ((match = pairRegex.exec(scripts)) !== null) { + add(match[1], match[2]); + } + return found; +} + /** * The two values the app puts on every batchexecute request. * @@ -493,7 +518,13 @@ function readProjectLinks() { */ function readPageTokens() { const w = window.WIZ_global_data || {}; - return { at: w.SNlM0e || '', fsid: w.FdrFJe || '' }; + return { + at: w.SNlM0e || '', + fsid: w.FdrFJe || '', + wizPath: w.Im6cmf || '', + bl: w.cfb2h || '', + origin: window.location.origin || '', + }; } /** @@ -505,15 +536,81 @@ function readPageTokens() { * length is therefore not evidence that this worked. */ async function mintCaptcha(siteKey, action) { + const realAssign = Object.assign; try { if (!window.grecaptcha || !window.grecaptcha.enterprise) { return { available: false, error: 'the page has no reCAPTCHA client loaded' }; } await new Promise((resolve) => window.grecaptcha.enterprise.ready(resolve)); + Object.assign = function (target, ...sources) { + const out = realAssign.call(this, target, ...sources); + if (out && typeof out === 'object' && out.action === 'extension_hijack_detected') { + out.action = action; + } + return out; + }; const token = await window.grecaptcha.enterprise.execute(siteKey, { action }); return { available: true, token }; } catch (e) { return { available: true, error: String(e) }; + } finally { + Object.assign = realAssign; + } +} + +async function runPageBatchRpc(rpcid, freq, siteKey, captchaAction) { + const realAssign = Object.assign; + try { + const wiz = window.WIZ_global_data || {}; + const at = wiz.SNlM0e || ''; + const fsid = wiz.FdrFJe || ''; + const bl = wiz.cfb2h || ''; + if (!at) return { error: 'NO_AT_TOKEN' }; + + let finalFreq = freq; + let token = ''; + if (captchaAction) { + if (!window.grecaptcha || !window.grecaptcha.enterprise) { + return { error: 'the page has no reCAPTCHA client loaded' }; + } + await new Promise((resolve) => window.grecaptcha.enterprise.ready(resolve)); + Object.assign = function (target, ...sources) { + const out = realAssign.call(this, target, ...sources); + if (out && typeof out === 'object' && out.action === 'extension_hijack_detected') { + out.action = captchaAction; + } + return out; + }; + token = await window.grecaptcha.enterprise.execute(siteKey, { action: captchaAction }); + Object.assign = realAssign; + finalFreq = freq.split('__CAPTCHA__').join(token); + } + + const reqid = Math.floor(Math.random() * 900000) + 100000; + const url = + `/_/AiSandboxAngularFrontend/data/batchexecute?rpcids=${encodeURIComponent(rpcid)}` + + `&f.sid=${encodeURIComponent(fsid)}&bl=${encodeURIComponent(bl)}` + + `&hl=en&_reqid=${reqid}&rt=c`; + const resp = await fetch(url, { + method: 'POST', + credentials: 'include', + headers: { + 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8', + 'x-same-domain': '1', + }, + body: new URLSearchParams({ 'f.req': finalFreq, at: String(at) }), + }); + const raw = await resp.text(); + return { + status_code: resp.status, + endpoint: `${window.location.origin}/_/AiSandboxAngularFrontend/data/batchexecute`, + raw: raw.slice(0, 2000), + captcha_minted: Boolean(token), + }; + } catch (e) { + return { error: String(e) }; + } finally { + Object.assign = realAssign; } } @@ -562,8 +659,8 @@ async function dispatch(op, params = {}) { 'ping', 'config.get', 'config.set', 'config.reset', 'tabs.list', 'tabs.open', 'tab.attach', 'tab.detach', 'tab.current', 'events.read', 'cookies.list', 'cookies.names', - 'flow.fingerprint', 'flow.navigate', 'flow.projects', - 'flow.captcha', 'flow.at', 'status', + 'flow.fingerprint', 'flow.navigate', 'flow.projects', 'flow.characters', + 'flow.captcha', 'flow.batch_rpc', 'flow.at', 'status', ], }; @@ -743,9 +840,18 @@ async function dispatch(op, params = {}) { case 'flow.projects': return await inPage(readProjectLinks); + case 'flow.characters': + return await inPage(readProjectCharacters); + case 'flow.at': { const t = await inPage(readPageTokens); - return { at: String((t && t.at) || ''), fsid: String((t && t.fsid) || '') }; + return { + at: String((t && t.at) || ''), + fsid: String((t && t.fsid) || ''), + wizPath: String((t && t.wizPath) || ''), + bl: String((t && t.bl) || ''), + origin: String((t && t.origin) || ''), + }; } case 'flow.captcha': { @@ -762,6 +868,16 @@ async function dispatch(op, params = {}) { return out || { available: false, error: 'the page returned nothing' }; } + case 'flow.batch_rpc': { + const rpcid = String(params.rpcid || ''); + const freq = String(params.freq || ''); + const action = String(params.action || 'VIDEO_GENERATION'); + const siteKey = cfg.recaptchaSiteKey || params.siteKey || '6LdsFiUsAAAAAIjVDZcuLhaHiDn5nnHVXVRQGeMV'; + const out = await inPage(runPageBatchRpc, [rpcid, freq, siteKey, action]); + if (out && out.captcha_minted) state.captchaMints++; + return out || { error: 'the page returned nothing' }; + } + case 'status': { // The tab is reported here rather than only when some other op happens to // resolve one. The popup reads `tabUrl` on its first paint, before any op