From 418e25c1ee29f708cbd2661399786302a2b7460f Mon Sep 17 00:00:00 2001 From: Redivesue Date: Mon, 30 Nov 2026 00:41:41 +0800 Subject: [PATCH 1/6] [feat] harness: add Antigravity CLI runtime - Run Antigravity as an external harness: one `agy` process per turn with stream-json input and output. The prompt goes to stdin as an `{"event":"user"}` message, because `-p` does not read stdin and a full replay exceeds the Windows command-line limit. - The CLI has no system prompt flag, so a fresh native conversation carries the runtime instructions in its first message; a resumed one does not repeat them. - Stream `agent_response` deltas for display and reconcile with `result.response`, emitting only text the stream did not show. A non-SUCCESS status fails the turn, and so does a SUCCESS result with an empty response: headless mode reports denied tools that way, listed in `denied_actions`. - Grant permissions for this run only through `--settings`: shell commands, reads, and writes inside the turn's execution directory; browser URL actions are denied and anything else needing approval is soft-denied by headless mode. `--dangerously-skip-permissions` is not used. - Resume with `--conversation` in the same execution directory. Native conversations live in `~/.gemini/antigravity-cli/conversations`; a missing file keeps the workspace and replays the full history. - Discover `agy` on PATH, then in `~/.gemini/bin`, where the installer puts it without adding it to PATH. Probe readiness by version and `agy models`; a sign-in error maps to needs_login. - Add the picker entry, Lobe Icons logo, bilingual setup hint and error codes, a trace projection, runtime identifiers in the API contract, and docs. Keep Antigravity out of the credential-free release visual gate. Refs: #585 --- CONTRIBUTING.md | 2 +- apps/api/src/opendirector_api/agent.py | 6 +- apps/api/src/opendirector_api/localization.py | 5 + docs/architecture/agent-runtime.md | 4 + docs/development/validation.md | 4 +- docs/guides/user-guide.md | 2 +- docs/guides/user-guide.zh-CN.md | 2 +- .../src/opendirector/agent/antigravity.py | 175 ++++++++++++ .../core/src/opendirector/agent/catalog.py | 6 + .../src/opendirector/agent/cli_discovery.py | 5 +- .../core/src/opendirector/agent/native.py | 30 +- .../core/src/opendirector/agent/runtime.py | 4 + .../src/opendirector/domain/agent_runtime.py | 2 +- .../opendirector/domain/creation/assets.py | 2 +- src/backend/chat.ts | 3 +- src/canvas/AgentPicker.tsx | 11 +- src/canvas/HarnessLogo.tsx | 3 +- src/canvas/agentPreferences.ts | 4 +- src/canvas/antigravityTrace.ts | 93 +++++++ src/canvas/traceCursor.ts | 2 + src/canvas/traceTurns.ts | 2 +- src/contracts/creation.schema.json | 6 +- src/contracts/generated.ts | 4 +- src/i18n/messages/en-US/assistant.ts | 2 + src/i18n/messages/zh-CN/assistant.ts | 2 + tests/antigravityTrace.test.ts | 63 +++++ tests/test_agent_visual_gate.py | 4 +- tests/test_antigravity_runtime.py | 257 ++++++++++++++++++ tests/test_assistant_conversation_trace.py | 2 +- tests/test_runtime_readiness.py | 4 +- 30 files changed, 677 insertions(+), 34 deletions(-) create mode 100644 packages/core/src/opendirector/agent/antigravity.py create mode 100644 src/canvas/antigravityTrace.ts create mode 100644 tests/antigravityTrace.test.ts create mode 100644 tests/test_antigravity_runtime.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7739c8130..81407bef3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,7 +29,7 @@ Labels are short, English and prefixed by dimension, so issues and PRs can be fi | --- | --- | | `area:canvas` | Canvas, nodes, direct manipulation | | `area:agent` | Agent runtime, assistant chat, tools | -| `area:harness` | Harness and skill integration (Default, OpenCode, Codex, Claude Code, JiuwenSwarm, DSH, Pi) | +| `area:harness` | Harness and skill integration (Default, OpenCode, Codex, Claude Code, JiuwenSwarm, DSH, Pi, Antigravity) | | `area:provider` | Model providers and generation protocols | | `area:assets` | Assets, library, reference inputs | | `area:timeline` | Timeline, subtitles, export | diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index b311d8f03..0384cfc7c 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -53,7 +53,7 @@ class Draft(BaseModel): assets: list[dict[str, JsonValue]] = Field(default_factory=list, max_length=MAX_REFERENCES) runtime: Runtime = 'default' runtimeModel: str | None = Field(default=None, max_length=200) - harnessModels: dict[Literal["opencode", "codex", "claude", "jiuwenswarm", "deepseek", "pi"], Annotated[str, Field(max_length=200)] | None] = Field(default_factory=dict) + harnessModels: dict[Literal["opencode", "codex", "claude", "jiuwenswarm", "deepseek", "pi", "antigravity"], Annotated[str, Field(max_length=200)] | None] = Field(default_factory=dict) thinking: Literal['auto', 'low', 'medium', 'high'] = 'auto' builtinModelThinking: dict[str, Literal['auto', 'low', 'medium', 'high']] = Field(default_factory=dict) modelSelections: dict[str, str | None] = Field(default_factory=dict) @@ -514,7 +514,7 @@ def trace_input(project_id: UUID, turn_id: UUID): @router.get('/traces/{turn_id}/{source}') def trace(project_id: UUID, turn_id: UUID, - source: Literal['opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi', 'model'], + source: Literal['opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi', 'antigravity', 'model'], cursor: Annotated[str | None, Query(pattern=r'^(?:[0-9]+:[0-9]+:[0-9]+)?$', max_length=64)] = None): folder = child(conversations.path(project_id), 'agent-runs') filename = normpath(join(folder, f'{turn_id}.{source}.jsonl')) @@ -615,7 +615,7 @@ async def runtime_detail(project_id: UUID, runtime: Runtime): return {**item, 'status': await runtime_status(runtime)} @router.get('/runtimes/{runtime}/models') - async def runtime_models(project_id: UUID, runtime: Literal['opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi'], selected: str | None = None): + async def runtime_models(project_id: UUID, runtime: Literal['opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi', 'antigravity'], selected: str | None = None): await asyncio.to_thread(conversations.path, project_id) if runtime == 'deepseek': from opendirector.agent.deepseek import model_choices as deepseek_models diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index cf7a982f5..1f8ec9e5c 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -121,6 +121,11 @@ "bigmodel_image_prompt": "Enter a GLM-Image prompt.", "bigmodel_image_size": "GLM-Image requires a preset size, or dimensions of 1024–2048 in multiples of 32.", "moss_layout_reference": "MOSS layout JSON does not accept additional text references. Put the requirements in the JSON or remove the text references.", + "antigravity_login": "Antigravity CLI is not signed in or its sign-in expired. Run agy in a terminal to sign in, then try again.", + "antigravity_models": "Could not read the Antigravity model list. Check the local agy installation.", + "antigravity_failed": "Antigravity did not finish this turn. Check its sign-in, the selected model, or the native trace.", + "antigravity_denied": "Antigravity requested a tool outside OpenDirector's allowed scope. It was denied and this turn has no reply.", + "antigravity_empty": "Antigravity returned no reply for this turn. Check the native trace.", "agent_dependency_unavailable": "Bundled Agent is unavailable. Reinstall with pip install --force-reinstall opendirector; for a source checkout, use pip install -e .", "invalid_input": "The request is invalid. Check the required fields and their formats.", "invalid_project": "The project or asset identifier is invalid.", diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index 1d38e48f7..34c4a159d 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -15,11 +15,14 @@ Harness 指承担模型调用、工具执行和上下文管理的 Agent 执行 | JiuwenSwarm | jiuwenswarm-process,优先 PATH,再查找常见 CLI 安装目录,通过 stdin/stdout JSONL 直接调用 | 本机 Jiuwen 模型目录、配置与环境变量 | | DeepSeek Harness | dsh,优先 PATH,再查找常见 CLI 安装目录,以 acp profile 运行标准 JSON-RPC | CLI 原生 profile、模型目录与认证 | | Pi | pi,优先 PATH,再查找 `~/.pi/agent/bin`,每轮一个 `--mode json` 进程读取原生 JSONL 事件流 | 本机 `~/.pi` 的 provider 认证、设置与模型目录 | +| Antigravity | agy,优先 PATH,再查找安装器使用的 `~/.gemini/bin`,每轮一个 `--input-format stream-json --output-format stream-json` 进程,提示从 stdin 输入 | 本机 agy 的账号登录、模型目录与全局设置 | Default 与 OpenCode CLI 分别配置。外部 CLI 不读取 OpenDirector 保存的模型凭证。进程继承服务端环境,包括 PATH 和第三方 API 配置。 Pi 沿用用户自己的 `~/.pi` 认证与设置,因此命令行里不传模型凭证。它以 `--mode json --print` 在一次运行中输出 JSONL 事件,适配层读取 `session`、`message_update`、`message_end` 和 `agent_end`:增量只用于显示,完成的助手消息是正文依据,被重试的失败尝试不结束本轮,只有 `agent_end` 最后一条助手消息的错误才作为失败原因返回。pi 在 print/json 模式下不询问信任,启动时显式传 `--approve`;否则本工程的 `.agents/skills`、`AGENTS.md` 与 `.pi` 设置会被静默跳过。会话写入工程内的 `agent-runs/pi-sessions/native/`,续聊用 `--session-id` 复用同一执行目录,不写入用户全局会话列表。 +Antigravity 沿用本机 agy 的账号登录,命令行里不传模型凭证。`-p` 不读 stdin,而完整的对话回放会超过 Windows 命令行长度上限,所以提示以一条 `{"event":"user"}` 的 stream-json 消息写入 stdin。CLI 没有系统提示参数,新会话把运行说明放在第一条消息里,续聊时不再重复。适配层把 `agent_response` 步骤的 `text_delta` 作为显示增量,以 `result.response` 为正文依据,只补出流里没有显示的部分。`result.status` 不是 `SUCCESS` 时本轮失败;headless 模式下被拒绝的工具会让 CLI 返回 `SUCCESS` 但 `response` 为空,并附带 `denied_actions`,这种情况同样判为失败并列出被拒绝的动作。续聊用 `--conversation` 复用同一执行目录;原生会话固定写在 `~/.gemini/antigravity-cli/conversations/`,CLI 不提供改到工程目录的参数,因此会出现在用户的 agy 会话列表中。续接前检查该会话文件,缺失时保留执行目录并以完整历史重新开始。agy 还会加载用户全局的 Skill、插件与 MCP 配置,CLI 没有按次关闭的参数。 + 会话保存 runtime、模型和推理强度,浏览器偏好用于辅助恢复选择。适配层不指定固定迭代轮数,沿用 harness 的预算和停止机制。 ## 执行链路 @@ -99,6 +102,7 @@ English summary: a Job created by an Agent `generation.submit` records `agentRun | JiuwenSwarm | 明确允许 skill_tool、list_skill、read_file、bash 和业务 CLI | | DeepSeek Harness | 沿用原生工具与权限;Skill 限于本轮快照,业务操作通过 Shell 调用 opendirector,未承接的审批不自动批准 | | Pi | `--approve --tools read,bash,write,edit`:只读、Shell 和文件编辑;Skill 与 `AGENTS.md` 由原生加载器从本轮目录读取,业务操作通过 Shell 调用 opendirector | +| Antigravity | `--settings` 仅本次生效:允许 `command(*)`、`read_file(*)` 和写入本轮执行目录,拒绝 `execute_url(*)`、`download_url(*)`;其余需审批的动作在 headless 模式下自动拒绝,不使用 `--dangerously-skip-permissions`。Skill 由原生加载器从本轮目录的 `.agents/skills` 读取,业务操作通过 Shell 调用 opendirector | 工具允许列表与操作系统沙箱提供不同约束。业务工具独立校验工程范围和输入;原生文件访问权限不授予直接改写工程存储的业务权限。 diff --git a/docs/development/validation.md b/docs/development/validation.md index 9783028d7..c62a5dea9 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -244,9 +244,9 @@ The image browser workflow covers pinned, followed and mixed references. With an ## Agent 原生视觉读取 / Agent native visual inspection -发布检查使用真实 Bundled、OpenCode、Codex、Claude Code、JiuwenSwarm 和 DeepSeek Harness CLI 以及本地模型夹具,检查原图和 FFmpeg 抽帧是否以正确顺序作为可解码图片到达模型。Bundled 还检查纯文本模型不会收到图片。CI 安装固定版本的外部 CLI,所需 CLI 缺失即失败。Pi 不在此门禁内:它依赖 release CI 未提供的本机服务商凭证。 +发布检查使用真实 Bundled、OpenCode、Codex、Claude Code、JiuwenSwarm 和 DeepSeek Harness CLI 以及本地模型夹具,检查原图和 FFmpeg 抽帧是否以正确顺序作为可解码图片到达模型。Bundled 还检查纯文本模型不会收到图片。CI 安装固定版本的外部 CLI,所需 CLI 缺失即失败。Pi 和 Antigravity 不在此门禁内:它们依赖 release CI 未提供的本机服务商凭证或账号登录。 -Release checks use the real Bundled, OpenCode, Codex, Claude Code, JiuwenSwarm and DeepSeek Harness CLIs with local model fixtures. They verify that decodable pixels from the still and FFmpeg frame reach the model in order. The Bundled check also verifies that a text-only model receives no pixels. CI installs pinned external CLI versions and fails if a required CLI is unavailable. Pi stays out of this gate: it needs provider credentials that release CI does not provision. +Release checks use the real Bundled, OpenCode, Codex, Claude Code, JiuwenSwarm and DeepSeek Harness CLIs with local model fixtures. They verify that decodable pixels from the still and FFmpeg frame reach the model in order. The Bundled check also verifies that a text-only model receives no pixels. CI installs pinned external CLI versions and fails if a required CLI is unavailable. Pi and Antigravity stay out of this gate: they need provider credentials or an account sign-in that release CI does not provision. ```bash OPENDIRECTOR_HARNESS_CI=1 python -m pytest tests/test_agent_visual_gate.py::test_harness_native_visual_input diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index e65932e51..71b72381f 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -12,7 +12,7 @@ Select **Edit in this window** to request edit access. In the editing window, se On the welcome screen, select **Get started**. Set up a language model for the built-in assistant or choose an existing harness. Then check one or more tasks. Each checked task shows its saved models or opens its setup form if you have none. **Start creating** places a node for each checked task on the same canvas. **Import media** opens the file picker. **Open an example canvas** opens an editable example project directly, with download progress in step two. Cancelling keeps your task selections. You can add more models in Settings anytime. -For external agent harnesses (Codex, OpenCode, Claude Code, DeepSeek Harness, JiuwenSwarm and Pi), OpenDirector checks the backend's `PATH` first, then common CLI installation directories. These include user bins, npm/nvm, Bun, Volta, Windows Scoop and Python Scripts, and macOS Homebrew and user Python bins. It also checks Codex desktop installs, OpenCode's `.opencode/bin`, Claude's `.claude/local`, Pi's `~/.pi/agent/bin`, and configured npm, pipx and uv bin directories. It checks known directories without scanning the whole disk. Finding a CLI does not establish authentication or configuration readiness. For other locations, add the CLI directory to the backend's `PATH` and restart the backend. The Default agent continues to use the bundled OpenCode. +For external agent harnesses (Codex, OpenCode, Claude Code, DeepSeek Harness, JiuwenSwarm, Pi and Antigravity), OpenDirector checks the backend's `PATH` first, then common CLI installation directories. These include user bins, npm/nvm, Bun, Volta, Windows Scoop and Python Scripts, and macOS Homebrew and user Python bins. It also checks Codex desktop installs, OpenCode's `.opencode/bin`, Claude's `.claude/local`, Pi's `~/.pi/agent/bin`, Antigravity's `~/.gemini/bin`, and configured npm, pipx and uv bin directories. It checks known directories without scanning the whole disk. Finding a CLI does not establish authentication or configuration readiness. For other locations, add the CLI directory to the backend's `PATH` and restart the backend. The Default agent continues to use the bundled OpenCode. Click the gear at the bottom left to open **Settings**, then open **Model connections**. Add models for chat, image, video, or audio generation as needed. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index f6dc6a095..f679827a3 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -12,7 +12,7 @@ 首次打开时,在欢迎页选择「开始设置」。为内置助手配置一个语言模型,或选择已有的 Harness。接着勾选一项或多项任务。每个勾选项可以选用已有模型,缺模型时直接显示对应的配置表单。点击「开始创作」后,画布会为每项任务添加一个节点。点「导入素材」可直接选文件,点「打开示例画布」可直接进入可编辑的示例项目,下载进度在第二步显示。取消时会保留已勾选的任务。之后可随时在设置中添加其他模型。 -选择外部 Agent harness(Codex、OpenCode、Claude Code、DeepSeek Harness、JiuwenSwarm 和 Pi)时,OpenDirector 优先检查后端的 `PATH`,再查找常见 CLI 安装目录,包括用户命令目录、npm/nvm、Bun、Volta、Windows Scoop 与 Python Scripts,以及 macOS Homebrew 和用户 Python 命令目录。同时检查 Codex 桌面版、OpenCode 的 `.opencode/bin`、Claude 的 `.claude/local`,Pi 的 `~/.pi/agent/bin`,以及配置的 npm、pipx 和 uv 命令目录。检测仅访问已知目录,不扫描整个磁盘;找到 CLI 后仍需检查认证与配置是否就绪。其他安装位置可加入后端的 `PATH`,然后重启后端。Default Agent 仍使用应用内置的 OpenCode。 +选择外部 Agent harness(Codex、OpenCode、Claude Code、DeepSeek Harness、JiuwenSwarm、Pi 和 Antigravity)时,OpenDirector 优先检查后端的 `PATH`,再查找常见 CLI 安装目录,包括用户命令目录、npm/nvm、Bun、Volta、Windows Scoop 与 Python Scripts,以及 macOS Homebrew 和用户 Python 命令目录。同时检查 Codex 桌面版、OpenCode 的 `.opencode/bin`、Claude 的 `.claude/local`,Pi 的 `~/.pi/agent/bin`、Antigravity 的 `~/.gemini/bin`,以及配置的 npm、pipx 和 uv 命令目录。检测仅访问已知目录,不扫描整个磁盘;找到 CLI 后仍需检查认证与配置是否就绪。其他安装位置可加入后端的 `PATH`,然后重启后端。Default Agent 仍使用应用内置的 OpenCode。 点击左下角齿轮进入“设置”,打开“模型接入”,按用途添加对话、图片、视频或音频模型。 diff --git a/packages/core/src/opendirector/agent/antigravity.py b/packages/core/src/opendirector/agent/antigravity.py new file mode 100644 index 000000000..169e4aaad --- /dev/null +++ b/packages/core/src/opendirector/agent/antigravity.py @@ -0,0 +1,175 @@ +"""Antigravity CLI: one `agy` print process per turn over its stream-json events.""" +import asyncio +import json +from pathlib import Path + +from opendirector.agent.process import terminate +from opendirector.domain.projects import ProjectError + + +# Antigravity has no system prompt flag. Its instructions travel in the first +# user message of a native conversation, like the DeepSeek Harness blocks. +APPENDIX = ( + 'Video creation work belongs to the OpenDirector project: change it only through the ' + 'opendirector command on PATH, never by editing project storage directly or with built-in ' + 'image generation. Pass --operation-id to every command that changes project content.\n' + 'For local visual inspection, use the native view_file tool on image files. ' + 'Extract video frames into the execution directory with FFmpeg before viewing them. ' + 'Obtain audio and other media facts through project media commands before describing them; ' + 'never claim to have watched a video or heard audio.\n' +) + + +def settings(work: Path) -> str: + """Session-only permissions: shell, reads anywhere, writes inside this turn's directory. + + Headless mode soft-denies everything else instead of prompting, so nothing + outside this list is approved on the user's behalf. + """ + return json.dumps({'permissions': { + 'allow': ['command(*)', 'read_file(*)', f'write_file({work}/)'], + 'deny': ['execute_url(*)', 'download_url(*)'], + }}) + + +def command(binary: str, work: Path, *, model: str | None = None, + session_id: str | None = None) -> list[str]: + # The prompt is read from stdin as stream-json: `-p` takes no stdin, and a + # full conversation replay exceeds the Windows command-line limit. + args = [binary, '--input-format', 'stream-json', '--output-format', 'stream-json', + '--disable-slash-commands', '--settings', settings(work), '-p='] + if model: + args += ['--model', model] + if session_id: + args += ['--conversation', session_id] + return args + + +def message(prompt: str) -> bytes: + return (json.dumps({'event': 'user', 'message': {'content': prompt}}, ensure_ascii=False) + '\n').encode() + + +def conversation_available(session_id: str, home: Path | None = None) -> bool: + folder = (home or Path.home()) / '.gemini/antigravity-cli/conversations' + return (folder / f'{session_id}.db').is_file() + + +def _denied(actions) -> str: + names = [] + for item in actions or []: + if isinstance(item, dict): + label = item.get('action') or '' + if item.get('display_name'): + label += f'({item["display_name"]})' + names.append(label) + return '、'.join(name for name in names if name) or '工具调用' + + +def events(raw: dict, state: dict) -> list[dict]: + """Stream response deltas, then reconcile with the authoritative result. + + The CLI reports SUCCESS with an empty response when headless mode denied a + tool it needed, so only a non-empty response completes the turn. + """ + kind = raw.get('event') + if kind == 'step_update': + step = raw.get('step_update') or {} + delta = step.get('text_delta') + if step.get('step_type') != 'agent_response' or not delta: + return [] + steps = state.setdefault('steps', {}) + index = step.get('step_index') + text = delta + if index not in steps and state.get('shown'): + # Separate answer steps that are interrupted by tool calls. + text = '\n\n' + delta + steps[index] = steps.get(index, '') + delta + state['last'] = index + state['shown'] = state.get('shown', '') + text + return [{'type': 'delta', 'text': text}] + if kind != 'result': + return [] + result = raw.get('result') or {} + status = result.get('status') + if status != 'SUCCESS': + detail = str(result.get('error') or status or '') + if 'authentication' in detail.lower(): + raise ProjectError('Antigravity CLI 未登录或登录已过期,请在终端运行 agy 完成登录后重试。', 401, + code='antigravity_login') + raise ProjectError(f'Antigravity 运行失败({status}):{detail}', 502, code='antigravity_failed') + response = result.get('response') or '' + if not response.strip(): + if result.get('denied_actions'): + raise ProjectError(f'Antigravity 请求的{_denied(result["denied_actions"])}超出 OpenDirector 的放行范围,已被拒绝,本轮没有回复。', + 502, code='antigravity_denied') + raise ProjectError('Antigravity 本轮没有返回回复,请查看原生轨迹。', 502, code='antigravity_empty') + shown = state.get('shown', '') + last = state.get('steps', {}).get(state.get('last'), '') + if not shown: + return [{'type': 'delta', 'text': response}] + for base in (last, shown): + if base and response.startswith(base): + rest = response[len(base):] + return [{'type': 'delta', 'text': rest}] if rest.strip() else [] + return [] + + +def parse_models(output: str) -> list[dict]: + """Rows are `idlabel`; the leading progress line has no tab.""" + choices = [] + for line in output.splitlines(): + if '\t' not in line: + continue + identifier, label = (part.strip() for part in line.split('\t', 1)) + if not identifier: + raise ValueError(f'unexpected models row: {line!r}') + # Reasoning effort is part of each model ID, so no separate control is offered. + choices.append({'id': identifier, 'label': label or identifier, 'efforts': []}) + return choices + + +async def _run(binary: str, args: list[str], timeout: float) -> tuple[int, str, str]: + process = await asyncio.create_subprocess_exec( + binary, *args, stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, start_new_session=True) + try: + output, error = await asyncio.wait_for(process.communicate(), timeout) + return process.returncode, output.decode('utf-8', 'replace'), error.decode('utf-8', 'replace') + finally: + await terminate(process, group=True) + + +def _logged_out(text: str) -> bool: + text = text.lower() + return 'authentication' in text or 'not logged in' in text or 'sign in' in text + + +async def model_choices(binary: str) -> list[dict]: + try: + code, output, error = await _run(binary, ['models'], 30) + except (OSError, TimeoutError) as failure: + raise ProjectError('无法读取 Antigravity 模型列表,请检查本机 agy 配置。', 503, + code='antigravity_models') from failure + if code: + if _logged_out(output + error): + raise ProjectError('Antigravity CLI 未登录或登录已过期,请在终端运行 agy 完成登录后重试。', 401, + code='antigravity_login') + raise ProjectError('读取 Antigravity 模型列表失败,请检查本机 agy 配置。', 503, code='antigravity_models') + try: + return parse_models(output) + except ValueError as failure: + raise ProjectError('无法读取 Antigravity 模型列表,请检查本机 agy 配置。', 503, + code='antigravity_models') from failure + + +async def readiness(binary: str) -> str: + try: + code, _, _ = await _run(binary, ['--version'], 10) + if code: + return 'unknown' + choices = await model_choices(binary) + except ProjectError as error: + return 'needs_login' if error.status == 401 else 'unknown' + except (OSError, TimeoutError): + return 'unknown' + return 'ready' if choices else 'needs_configuration' diff --git a/packages/core/src/opendirector/agent/catalog.py b/packages/core/src/opendirector/agent/catalog.py index 7267069d0..da9a3fe7d 100644 --- a/packages/core/src/opendirector/agent/catalog.py +++ b/packages/core/src/opendirector/agent/catalog.py @@ -62,6 +62,12 @@ async def model_choices(runtime: str) -> list[dict]: if binary is None: raise ProjectError('CLI 尚未安装。', 503) return await pi_models(binary) + if runtime == 'antigravity': + from opendirector.agent.antigravity import model_choices as antigravity_models + binary = executable('antigravity') + if binary is None: + raise ProjectError('CLI 尚未安装。', 503) + return await antigravity_models(binary) if runtime not in {'opencode', 'codex', 'claude'}: raise ProjectError('此引擎使用模型设置中的模型。') binary = executable(runtime) diff --git a/packages/core/src/opendirector/agent/cli_discovery.py b/packages/core/src/opendirector/agent/cli_discovery.py index b6bec1ead..2ee6d7bb5 100644 --- a/packages/core/src/opendirector/agent/cli_discovery.py +++ b/packages/core/src/opendirector/agent/cli_discovery.py @@ -32,6 +32,9 @@ def common_candidates(name: str, home: Path, platform: str, env: Mapping[str, st bins.insert(0, home / '.opencode/bin') elif name == 'pi': bins.insert(0, home / '.pi/agent/bin') + elif name == 'agy': + # The Antigravity installer does not add its bin directory to PATH. + bins.insert(0, home / '.gemini/bin') elif name == 'claude': bins.append(home / '.claude/local') for key in ('PIPX_BIN_DIR', 'UV_TOOL_BIN_DIR'): @@ -75,7 +78,7 @@ def cli_executable(name: str) -> str | None: if path := shutil.which(name): return path # Names are internal command IDs, never shell input or user-provided paths. - if name not in {'codex', 'claude', 'opencode', 'dsh', 'jiuwenswarm-process', 'pi'}: + if name not in {'codex', 'claude', 'opencode', 'dsh', 'jiuwenswarm-process', 'pi', 'agy'}: return None candidates = (codex_candidates(Path.home(), sys.platform, os.environ) if name == 'codex' else common_candidates(name, Path.home(), sys.platform, os.environ)) diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index 5b23f3c5c..5d221cea2 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -13,7 +13,7 @@ from uuid import UUID from opendirector.agent.model_gateway import ModelGateway -from opendirector.agent import cli_transport, deepseek, pi, windows_powershell +from opendirector.agent import antigravity, cli_transport, deepseek, pi, windows_powershell from opendirector.agent.cli_discovery import cli_executable from opendirector.agent.context import RunContext from opendirector.agent.citations import search_sources @@ -39,7 +39,7 @@ def executable(runtime: str) -> str | None: return str(path) path = BUNDLED / 'bin' / ('opencode.exe' if os.name == 'nt' else 'opencode') return str(path) if path.is_file() else None - return cli_executable('dsh' if runtime == 'deepseek' else runtime) + return cli_executable({'deepseek': 'dsh', 'antigravity': 'agy'}.get(runtime, runtime)) _CODEX_ISOLATION: dict[tuple[str, ...], tuple[str, ...]] = {} @@ -128,6 +128,8 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None args = pi.command(binary, session_dir=work.parent.parent / 'pi-sessions' / 'native', system=runtime_instructions(runtime), model=model) return args, env + if runtime == 'antigravity': + return antigravity.command(binary, work, model=model), env if runtime == 'codex': settings = ['features.shell_tool=true', 'features.apply_patch_freeform=false', 'web_search="disabled"', 'sandbox_workspace_write.network_access=true', @@ -194,7 +196,8 @@ async def stream(self, run: RunContext, gateway: ToolGateway): # Unverifiable session directories cannot be resumed. Preserve the # old session and start with authoritative conversation context. session_id = None - if session_id and runtime == 'codex' and not codex_session_available(session_id): + if session_id and (runtime == 'codex' and not codex_session_available(session_id) + or runtime == 'antigravity' and not antigravity.conversation_available(session_id)): # Retain the validated workspace while rebuilding a missing native # conversation from the full authoritative history. session_id = None @@ -203,7 +206,7 @@ async def stream(self, run: RunContext, gateway: ToolGateway): token = secrets.token_urlsafe(32) process = pump = stderr_task = None with TemporaryDirectory(prefix='od-agent-', dir=None if os.name == 'nt' else '/tmp') as temporary: - reuse_workspace = session_directory is not None and runtime in {'codex', 'claude', 'deepseek', 'pi'} + reuse_workspace = session_directory is not None and runtime in {'codex', 'claude', 'deepseek', 'pi', 'antigravity'} work = session_directory if reuse_workspace else (directory / 'agent-runs' / str(turn_id) / 'work').resolve() work.mkdir(parents=True, exist_ok=reuse_workspace) gateway.execution_directory = work @@ -258,7 +261,9 @@ async def stream(self, run: RunContext, gateway: ToolGateway): elif thinking != 'auto' and runtime == 'pi': args += ['--thinking', thinking] if session_id and runtime != 'deepseek': - if runtime == 'codex': + if runtime == 'antigravity': + args += ['--conversation', session_id] + elif runtime == 'codex': args += ['resume', session_id, '-'] elif runtime == 'pi': args += ['--session-id', session_id] @@ -281,7 +286,7 @@ async def stream(self, run: RunContext, gateway: ToolGateway): prompt = f'/opendirector:{name}\n' + prompt elif runtime == 'deepseek': skill_instruction = f'Use the native skill tool to load {name} from {work / ".agents/skills"} before proceeding.' - elif runtime == 'pi': + elif runtime in {'pi', 'antigravity'}: prompt = f'Read and follow {work / ".agents/skills" / name / "SKILL.md"} before proceeding.\n' + prompt else: prompt = f'Use the native skill tool to load {name} before proceeding.\n' + prompt @@ -300,7 +305,14 @@ async def drain_stderr(): stderr_tail.extend(chunk) del stderr_tail[:-8192] stderr_task = asyncio.create_task(drain_stderr()) - if runtime != 'deepseek': + if runtime == 'antigravity': + # No system prompt flag: a fresh conversation carries the + # instructions in its first message; a resumed one has them. + instructions = '' if session_id else runtime_instructions(runtime) + '\n' + antigravity.APPENDIX + '\n' + process.stdin.write(antigravity.message(instructions + prompt)) + await process.stdin.drain() + process.stdin.close() + elif runtime != 'deepseek': process.stdin.write(prompt.encode() + b'\n') await process.stdin.drain() process.stdin.close() @@ -338,6 +350,8 @@ async def observe(raw): reported_session = raw.get('session_id') or reported_session elif runtime == 'pi' and raw['type'] == 'session': reported_session = raw.get('id') or reported_session + elif runtime == 'antigravity' and raw.get('event') == 'init': + reported_session = raw.get('conversation_id') or reported_session if (previous_session and reported_session != previous_session or session_id and reported_session and reported_session != session_id): raise ProjectError('Harness 返回了不同的会话 ID。', 502) @@ -360,6 +374,7 @@ async def observe(raw): run_dir.mkdir(exist_ok=True) native_calls = {} pi_state = {} + antigravity_state = {} with (run_dir / f'{turn_id}.{runtime}.jsonl').open('a', encoding='utf-8') as trace: while (event := await queue.get()) is not None: trace.write(json.dumps(event, ensure_ascii=False) + '\n') @@ -367,6 +382,7 @@ async def observe(raw): if 'native' in event: for item in (deepseek.events(event['native'], native_calls) if runtime == 'deepseek' else pi.events(event['native'], pi_state) if runtime == 'pi' + else antigravity.events(event['native'], antigravity_state) if runtime == 'antigravity' else text_events(runtime, event['native'])): yield item else: diff --git a/packages/core/src/opendirector/agent/runtime.py b/packages/core/src/opendirector/agent/runtime.py index 1622c4b3c..f8d9f8899 100644 --- a/packages/core/src/opendirector/agent/runtime.py +++ b/packages/core/src/opendirector/agent/runtime.py @@ -34,6 +34,7 @@ class RuntimeSpec: 'codex': RuntimeSpec(id='codex', label='Codex', group='harness', modelSource='cli', modelOverride=True, engine='codex'), 'claude': RuntimeSpec(id='claude', label='Claude Code', group='harness', modelSource='cli', modelOverride=True, engine='claude'), 'pi': RuntimeSpec(id='pi', label='Pi', group='harness', modelSource='cli', modelOverride=True, engine='pi'), + 'antigravity': RuntimeSpec(id='antigravity', label='Antigravity', group='harness', modelSource='cli', modelOverride=True, engine='antigravity'), } @@ -91,6 +92,9 @@ async def runtime_readiness(engine: str) -> str: if engine == 'pi': from opendirector.agent.pi import readiness return await readiness(executable) + if engine == 'antigravity': + from opendirector.agent.antigravity import readiness as antigravity_readiness + return await antigravity_readiness(executable) if engine == 'opencode': return 'ready' args = ['--version'] if engine == 'default' else ['login', 'status'] if engine == 'codex' else ['auth', 'status', '--json'] diff --git a/packages/core/src/opendirector/domain/agent_runtime.py b/packages/core/src/opendirector/domain/agent_runtime.py index a529aa3e6..394ca27f6 100644 --- a/packages/core/src/opendirector/domain/agent_runtime.py +++ b/packages/core/src/opendirector/domain/agent_runtime.py @@ -2,4 +2,4 @@ from typing import Literal -RuntimeId = Literal['default', 'opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi'] +RuntimeId = Literal['default', 'opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi', 'antigravity'] diff --git a/packages/core/src/opendirector/domain/creation/assets.py b/packages/core/src/opendirector/domain/creation/assets.py index 2dc056a0e..31a942a64 100644 --- a/packages/core/src/opendirector/domain/creation/assets.py +++ b/packages/core/src/opendirector/domain/creation/assets.py @@ -65,7 +65,7 @@ class AssetProvenance(Contract): sources: tuple[AssetRef, ...] = Field(default=(), description='Ordered source asset versions.') inputFingerprint: str | None = Field(default=None, pattern=r'^[0-9a-f]{64}$', description='Fingerprint of the fixed execution input.') agentRunId: UUID | None = Field(default=None, description='Agent turn ID.') - agentRuntime: Literal['opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi'] | None = Field(default=None, description='Native Agent runtime that produced this asset.') + agentRuntime: Literal['opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi', 'antigravity'] | None = Field(default=None, description='Native Agent runtime that produced this asset.') modelSnapshot: ModelSnapshot | None = Field(default=None, description='Fixed model connection recorded for provenance.') prompt: str | None = Field(default=None, max_length=PROMPT_MAX_LENGTH, description='Generation prompt text.') importedFrom: Literal['generated', 'edited'] | None = Field(default=None, description='Original source recorded by a canvas archive this asset was imported from.') diff --git a/src/backend/chat.ts b/src/backend/chat.ts index 02afe1f93..6fe7ff594 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -11,7 +11,8 @@ export type AgentRuntime = | "claude" | "jiuwenswarm" | "deepseek" - | "pi"; + | "pi" + | "antigravity"; export interface RuntimeInfo { id: AgentRuntime; label: string; diff --git a/src/canvas/AgentPicker.tsx b/src/canvas/AgentPicker.tsx index 77f0128ae..fe6cf7754 100644 --- a/src/canvas/AgentPicker.tsx +++ b/src/canvas/AgentPicker.tsx @@ -57,7 +57,7 @@ export function AgentPicker({ (item): item is RuntimeInfo & { id: Harness } => item.group === "harness" && item.id !== "default", ).sort((a, b) => { - const order: Harness[] = ["opencode", "deepseek", "jiuwenswarm", "codex", "claude", "pi"]; + const order: Harness[] = ["opencode", "deepseek", "jiuwenswarm", "codex", "claude", "pi", "antigravity"]; const rank = (id: Harness) => { const index = order.indexOf(id); return index < 0 ? order.length : index; @@ -108,7 +108,7 @@ export function AgentPicker({ : item.status === "unsupported_version" ? t("assistant.agent.status.unsupportedVersion") : item.status === "unknown" - ? item.id === "jiuwenswarm" || item.id === "pi" + ? item.id === "jiuwenswarm" || item.id === "pi" || item.id === "antigravity" ? t("assistant.agent.status.catalogUnreadable") : t("assistant.agent.status.unknown") : t("assistant.agent.status.needsConfiguration"); @@ -129,6 +129,8 @@ export function AgentPicker({ ? "claude auth login" : setup === "pi" ? "pi auth login " + : setup === "antigravity" + ? "agy" : "opencode"; const setupLink = setup === "deepseek" @@ -141,6 +143,8 @@ export function AgentPicker({ ? "https://code.claude.com/docs/en/setup" : setup === "pi" ? "https://github.com/earendil-works/pi" + : setup === "antigravity" + ? "https://antigravity.google/docs/cli/" : "https://opencode.ai/docs/"; const editingSpec = harnesses.find((item) => item.id === editing); const runtime = value.runtime ?? "default"; @@ -383,6 +387,9 @@ export function AgentPicker({ {setupSpec.id === "pi" && (

{t("assistant.agent.piHint")}

)} + {setupSpec.id === "antigravity" && ( +

{t("assistant.agent.antigravityHint")}

+ )} {setupSpec.modelSource === "settings" && setupSpec.available ? (