返回 ViMax
mcp_jobs.py
根目录 / agent_runtime / mcp_jobs.py
1 from __future__ import annotations
2
3 import asyncio
4 import json
5 import os
6 import re
7 import subprocess
8 import sys
9 from pathlib import Path
10 from tempfile import TemporaryFile
11 from threading import Thread
12 from typing import Any
13 from uuid import uuid4
14
15 try:
16 import fcntl
17 except ImportError: # pragma: no cover - checked at the entry point
18 fcntl = None
19
20 from .session_index import SessionIndex
21
22 JOB_ID = re.compile(r"[a-f0-9]{32}")
23 SESSION_ID = re.compile(r"[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*")
24 IN_PROGRESS = {"queued", "running"}
25 ARTIFACT_LIMIT = 100
26 PIPELINES = ("idea2video", "script2video", "novel2video")
27 ARTIFACT_SUFFIXES = {".json", ".txt", ".png", ".jpg", ".jpeg", ".webp", ".mp4", ".webm"}
28
29
30 class MCPJobs:
31 def __init__(self, workspace: Path, *, worker_entry: Path) -> None:
32 if fcntl is None:
33 raise RuntimeError("local MCP jobs require Linux or macOS.")
34 self.workspace = workspace.resolve()
35 self.worker_entry = worker_entry
36 self.directory = self.workspace / ".vimax" / "mcp-jobs"
37 if not self.directory.resolve().is_relative_to(self.workspace):
38 raise RuntimeError("the MCP job directory must stay inside the workspace.")
39 self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
40 self.lock_path = self.directory / "worker.lock"
41 self.sessions = SessionIndex(self.workspace)
42
43 def _state_path(self, job_id: str) -> Path:
44 if not JOB_ID.fullmatch(job_id):
45 raise ValueError("Invalid job ID.")
46 return self.directory / f"{job_id}.json"
47
48 def write(self, state: dict[str, Any]) -> None:
49 path = self._state_path(state["job_id"])
50 temp = path.with_suffix(".tmp")
51 temp.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
52 temp.replace(path)
53
54 def start(self, operation: str, request: dict[str, Any]) -> dict[str, Any]:
55 with self.lock_path.open("a+", encoding="utf-8") as lock:
56 try:
57 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
58 except BlockingIOError:
59 lock.seek(0)
60 return {"status": "busy", "job_id": lock.read().strip(), "message": "A ViMax MCP job is already running in this workspace."}
61 job_id = uuid4().hex
62 lock.seek(0)
63 lock.truncate()
64 lock.write(job_id)
65 lock.flush()
66 state = {"job_id": job_id, "operation": operation, "status": "queued", "session_id": request.get("session_id", "")}
67 self.write(state)
68 try:
69 with TemporaryFile() as input_file:
70 input_file.write(json.dumps(request).encode("utf-8"))
71 input_file.seek(0)
72 # The child inherits the held lock and keeps it after the MCP client exits.
73 child = subprocess.Popen(
74 [sys.executable, str(self.worker_entry), "--worker", job_id],
75 cwd=self.workspace,
76 stdin=input_file,
77 stdout=subprocess.DEVNULL,
78 stderr=subprocess.DEVNULL,
79 start_new_session=True,
80 pass_fds=(lock.fileno(),),
81 )
82 Thread(target=child.wait, daemon=True).start()
83 except OSError:
84 state.update(status="failed", error="worker_unavailable")
85 self.write(state)
86 return state
87
88 def _worker_owns(self, job_id: str) -> bool:
89 with self.lock_path.open("a+", encoding="utf-8") as lock:
90 try:
91 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
92 except BlockingIOError:
93 lock.seek(0)
94 return lock.read().strip() == job_id
95 return False
96
97 def read(self, job_id: str) -> dict[str, Any]:
98 path = self._state_path(job_id)
99 state = json.loads(path.read_text(encoding="utf-8"))
100 if self._worker_owns(job_id):
101 # Do not report completion until the next job can take the workspace lock.
102 if state["status"] not in IN_PROGRESS:
103 state["status"] = "running"
104 elif state["status"] in IN_PROGRESS:
105 # The worker may have written its final state just before releasing the lock.
106 state = json.loads(path.read_text(encoding="utf-8"))
107 if state["status"] in IN_PROGRESS:
108 state.update(status="interrupted", error="worker_stopped")
109 return state
110
111 def project(self, session_id: str) -> dict[str, Any]:
112 if len(session_id) > 96 or not SESSION_ID.fullmatch(session_id):
113 raise ValueError("Invalid ViMax session ID.")
114 session = self.sessions.get(session_id)
115 if session is None:
116 raise KeyError("Unknown ViMax session ID.")
117 return session
118
119 def project_root(self, session_id: str) -> Path:
120 session = self.project(session_id)
121 root = self.workspace / session["working_dir"]
122 if root != self.workspace / ".working_dir" / session_id or root.resolve() != root:
123 raise ValueError("Invalid ViMax project directory.")
124 return root
125
126 def artifacts(self, session_id: str) -> dict[str, Any]:
127 root = self.project_root(session_id)
128 artifacts: list[str] = []
129 for pipeline in PIPELINES:
130 folder = root / pipeline
131 if not folder.is_dir() or folder.is_symlink():
132 continue
133 for current, dirs, files in os.walk(folder):
134 dirs[:] = sorted(d for d in dirs if not d.startswith(".") and not (Path(current) / d).is_symlink())
135 paths = (Path(current) / filename for filename in sorted(files) if not filename.startswith("."))
136 for path in paths:
137 if path.suffix.lower() not in ARTIFACT_SUFFIXES or path.is_symlink() or not path.is_file():
138 continue
139 if len(artifacts) == ARTIFACT_LIMIT:
140 return {"artifacts": artifacts, "artifacts_truncated": True}
141 artifacts.append(path.relative_to(self.workspace).as_posix())
142 return {"artifacts": artifacts, "artifacts_truncated": False}
143
144
145 def run_worker(jobs: MCPJobs, job_id: str, request: dict[str, Any]) -> int:
146 state = jobs.read(job_id)
147 if state["status"] != "queued" or not jobs._worker_owns(job_id):
148 return 1
149 state["status"] = "running"
150 jobs.write(state)
151 try:
152 asyncio.run(_execute(jobs, state, request))
153 except Exception:
154 # Provider exceptions can include request headers, URLs or credentials.
155 state.update(status="failed", error="worker_failed")
156 jobs.write(state)
157 return int(state["status"] != "succeeded")
158
159
160 async def _execute(jobs: MCPJobs, state: dict[str, Any], request: dict[str, Any]) -> None:
161 if state["operation"] == "agent":
162 from .mcp_agent import run_agent_turn
163
164 await run_agent_turn(jobs, state, request)
165 return
166
167 from .tools import ToolRuntimeContext
168 from .vimax_adapters import ViMaxAdapters, _ready_for_render
169
170 adapter = ViMaxAdapters(jobs.workspace, jobs.sessions)
171 if state["operation"] == "plan":
172 session_id = jobs.sessions.create(project_name=request["project_name"])["session_id"]
173 workflow = request["workflow"]
174 if workflow == "novel2video":
175 handler = adapter.vimax_novel_planning
176 source_key = "novel_text"
177 else:
178 handler = adapter.vimax_narrative_planning
179 source_key = "idea" if workflow == "idea2video" else "script"
180 arguments = {
181 "session_id": session_id,
182 source_key: request["source"],
183 "style": request["style"],
184 "user_requirement": request["requirements"],
185 }
186 else:
187 session_id = request["session_id"]
188 handler = adapter.vimax_render_video
189 arguments = {"session_id": session_id}
190 state["session_id"] = session_id
191 jobs.write(state)
192
193 def progress(event: dict[str, Any]) -> None:
194 if event["type"] == "tool_progress":
195 state["stage"] = event["progress"]["stage"]
196 jobs.write(state)
197
198 tool = handler.__name__
199 result = await handler(arguments, ToolRuntimeContext(tool, tool, progress_callback=progress))
200 state["status"] = "succeeded" if result.ok else "failed"
201 state["session_id"] = result.metadata.get("session_id") or session_id
202 if state["operation"] == "plan":
203 state["ready_for_render"] = _ready_for_render(jobs.sessions.artifact_checklist(state["session_id"]))
204 if not result.ok:
205 dependency_missing = result.metadata.get("error_type") == "dependency_missing"
206 state["error"] = "dependency_missing" if dependency_missing else f'{state["operation"]}_failed'
207 if dependency_missing:
208 state["missing"] = result.metadata.get("missing", [])
209 else:
210 for output in ("final_video_path", "scene_videos_dir"):
211 if value := result.metadata.get(output):
212 path = (jobs.workspace / value).resolve()
213 if path.is_relative_to(jobs.sessions.working_dir(state["session_id"])):
214 state[output] = path.relative_to(jobs.workspace).as_posix()
215 jobs.write(state)
216
216 lines PYTHON