Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat(runner): support Antigravity login and harden credential refresh (#1016)
crispinhu27218db9bd9b2d
diff --git a/README.md b/README.mdindex 8141eec3..e67c3b91 100644--- a/README.md+++ b/README.md@@ -121,10 +121,11 @@ New accounts join the **LoopForge demo project**, which includes an SOP made onl| **Claude Code** | Personal key; a connected execution machine can use its local login | Installed from npm on first use, then cached || **OpenCode · Kimi Code · Pi** | Personal key only | Installed from npm on first use, then cached || **DeepSeek Harness** | Personal key only | In the Docker image |- | **Cursor CLI · Antigravity** | Personal key only | Provider installer on first chat use; not installed into SOP sandboxes |+ | **Cursor CLI** | Personal key only | Provider installer on first chat use; not installed into SOP sandboxes |+ | **Antigravity** | Personal key, or the connected execution machine owner's existing account login | Install the official CLI on the execution machine and in Docker images used for SOP runs || **ZCode** | Personal key only | Not bundled; install it on the service or execution machine PATH |- The seven agent CLIs after Claude Code keep their model and MCP configuration in a private home directory per run, so they always use the responsible user's own key and Base URL from personal settings, even on a connected execution machine. When rolling them out to a team, each member configures their own credentials. First-use installs need npm or provider access; [native deployments](docs/deployment.md#workers-and-runners) need the CLI for the executor you choose.+ The seven agent CLIs after Claude Code keep their model and MCP configuration in a private home directory per run. Antigravity can reuse the execution machine owner's account login in conversation workspaces and native or Docker SOP sandboxes. Its official CLI refreshes the credential copy, and the Runner saves the refreshed login back to its original local store. Gemini API keys use separate API billing. The other agent CLIs use the responsible user's own key and Base URL from personal settings, including on a connected execution machine. First-use installs need npm or provider access; [native deployments](docs/deployment.md#workers-and-runners) need the CLI for the executor you choose.- **GitHub is optional.** All built-in generic SOPs run without a repository: product SOPs deliver documents, and new frontend/backend projects deliver source files in the task workspace. Bug fixes still need source code and reproduction details. Connect a repository when you work on existing code or want PRs.- **Delivering to a repository.** Choose **Connect GitHub** in personal settings, approve the device code on GitHub and pick your repository (the LoopForge OAuth App is built in; no PAT required, manual PAT entry still works). Set executor credentials (or bind a local execution machine), then either run a project SOP or ask Main Bot to change the code and submit a PR/MR.- **Sandboxes.** In the default Compose installation, SOP runs and conversation workspaces both use Docker sandbox containers started through the host Docker socket. Default sandboxes reuse the installed runtime image, so nothing extra is built after installation; custom Dockerfiles still build their own images. Docker socket access grants control of the host daemon, so this setup is for trusted teams, not untrusted multi-tenant isolation. See [deployment boundaries](docs/deployment.md#accounts). Re-running the installer keeps your data.diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.jsindex 50c626ae..9b82cf40 100644--- a/chatbot/src/useChat.js+++ b/chatbot/src/useChat.js@@ -1304,7 +1304,7 @@ export function useChat() {models: executorModels,executor,executors: EXECUTORS.map((item) => {- if (!personalMachine || (item.id !== "codex" && item.id !== "claude-code")) return item;+ if (!personalMachine || !["codex", "claude-code", "agy"].includes(item.id)) return item;const runtime = personalMachine.runtimes?.find((runtime) => runtime.provider === item.id);return runtime?.authMode === "personal" ? item : { ...item, detail: "使用执行机器上的本机登录态。" };}),diff --git a/docs/conversation-native-cli.md b/docs/conversation-native-cli.mdindex f5c49027..f69bb798 100644--- a/docs/conversation-native-cli.md+++ b/docs/conversation-native-cli.md@@ -22,15 +22,19 @@ ZCode 恢复时通过官方会话协议应用当前选择的模型,再启动Runner 需要 0.10.1 或以上版本,该版本支持取消后台导出并释放工作区锁。Docker 镜像优先使用已安装的 CLI;支持官方安装器的 CLI 缺失时自动安装。ZCode 没有独立 npm 包,须在执行机器及工作区镜像内预装官方 CLI 并加入 PATH,缺失时明确报错。原生工具调用围栏与进程生命周期管理依赖 Python3。每个 Docker 会话阶段使用独立的 Linux 子进程收养进程,结束或取消时回收其全部后代,包含另建进程组的原生命令;不影响容器里的其他命令。平台会在启动前检查依赖,固定安装步骤以容器 root 用户在 `/` 中运行,实际 CLI 保留工作区的容器用户;无法准备时中止,不降级绕过调用围栏。建议在受控工作区镜像中预安装 CLI 和依赖。-个人执行机器可为 Codex 和 Claude Code 选择「账号登录」。Runner 0.10.2 起,对话按所绑定机器的认证设置启动 CLI。在运行 Runner 的系统账户下登录后,Codex 读取 `CODEX_HOME` 下的 `auth.json`,Claude Code 读取 `CLAUDE_CONFIG_DIR` 下的 `.credentials.json` 或 Runner 环境中的 `CLAUDE_CODE_OAUTH_TOKEN`。登录状态仅在该执行机器上使用。每次运行把登录文件复制进隔离的 CLI home,结束后删除;CLI 在运行中刷新了 token(Codex、Claude Code 的 refresh token 会轮换)时,删除前按内容做比较并交换写回 Runner 账户的原文件:原文件在此期间未被改动、且刷新后的文件仍是同一账号(顶层字段一致,Codex 的 `tokens.account_id` 相同)才写回,否则保留宿主机上的版本。仍需直接通过 CLI 管理登录和续期。仅存于系统钥匙串的登录需要改用 CLI 支持的文件式登录或 API Key。设置页在 CLI 行的「更多」菜单提供「测试」,按当前认证方式在该机器上发送一次短模型请求。+个人执行机器可为 Codex、Claude Code 和 Antigravity 选择「账号登录」,对话按所绑定机器的认证设置启动 CLI。在运行 Runner 的系统账户下登录后,Codex 读取 `CODEX_HOME` 下的 `auth.json`,Claude Code 读取 `CLAUDE_CONFIG_DIR` 下的 `.credentials.json` 或 Runner 环境中的 `CLAUDE_CODE_OAUTH_TOKEN`。Codex、Claude Code 仅存于系统钥匙串的登录需要改用 CLI 支持的文件式登录或 API Key;Antigravity 的凭据库支持见下文。++登录状态仅在该执行机器上使用。每次运行把登录文件复制进隔离的 CLI HOME,结束后删除;CLI 刷新 token 后,Runner 在源内容未改变时保存回原来源。当前格式与账号字段比较属于本地检查,不能证明整套 token 的服务端归属;完整的写回归属验证另行加固。设置页在 CLI 行的「更多」菜单提供「测试」,按当前认证方式在该机器上发送一次短模型请求。SOP 的 native 和 Docker 沙箱也使用所选 Runner 的认证设置。每次 CLI 调用都在节点的独立 HOME 中使用临时登录文件,结束后清理该文件,会话可在同一节点续接。Runner 0.10.2 起,机器卡片可检查并手动安装平台提供的 Runner 构建。更新在机器空闲时应用。自行安装的 CLI 如提供非交互更新命令,可以在 CLI 菜单中直接执行更新。托管安装使用托管更新。如果 CLI 无法自更新,界面会提示按原安装方式更新。-CLI 菜单中的「模型列表」与个人配置共用当前用户的模型目录。可以获取、筛选、添加、重命名和排序模型。保存后,AI 对话和角色编辑器使用该目录。API Key 模式通过个人配置里的 Key 与服务地址获取模型,留空地址时使用 CLI 的官方服务。Codex 和 Claude Code 的账号登录模式从所选机器查询,需要 Runner 0.10.2 或以上版本。+CLI 菜单中的「模型列表」与个人配置共用当前用户的模型目录。可以获取、筛选、添加、重命名和排序模型。保存后,AI 对话和角色编辑器使用该目录。API Key 模式通过个人配置里的 Key 与服务地址获取模型,留空地址时使用 CLI 的官方服务。Codex、Claude Code 和 Antigravity 的账号登录模式从所选机器查询。++Antigravity 的账号登录读取运行 Runner 的系统账号已有的凭据库或远程会话认证文件。对话工作区和 SOP 的 native、Docker 沙箱使用私有 HOME 中的认证副本,由官方 CLI 自动刷新,结束时保存回原来源并清理副本。Docker 镜像需要安装官方 agy CLI。共享对话中,只有机器所有者发言时使用该登录。实测版本为 agy 1.5.10。-其他 CLI 使用个人配置中保存的 API Key。Antigravity 将本机登录保存在系统凭据库中,LoopForge 沙箱目前无法复用。请在个人配置中填写 Gemini API Key,用量按 Gemini API 单独计费。详见 [Antigravity CLI 认证](https://antigravity.google/docs/install?tab=cli)和 [Gemini API 计费](https://ai.google.dev/gemini-api/docs/billing)。+其他 CLI 使用个人配置中保存的 API Key。Antigravity 也可切换为 API Key,读取个人配置里的 Gemini API Key,用量按 Gemini API 单独计费。详见 [Antigravity CLI 认证](https://antigravity.google/docs/install?tab=cli)和 [Gemini API 计费](https://ai.google.dev/gemini-api/docs/billing)。ZCode 可通过 GLM Coding Plan 的 API Key 和套餐专用端点使用订阅额度。Start Plan 的额度需要登录 ZCode 账号,无法通过 API Key 使用。详见 [ZCode 模型配置](https://zcode.z.ai/cn/docs/configuration)。diff --git a/docs/proposals/runner-login-writeback-verification.md b/docs/proposals/runner-login-writeback-verification.mdnew file mode 100644index 00000000..b197b428--- /dev/null+++ b/docs/proposals/runner-login-writeback-verification.md@@ -0,0 +1,245 @@+# Runner 登录凭证写回:前期验证记录++验证日期:2026-11-17。基于 `0dabc555`(Antigravity 登录支持),独立分支+`feature/runner-login-writeback-verification`。这一阶段只有测试与实验记录,未把原型验证器接入+Runner。后续正式实现位于 `feature/runner-managed-auth`,见[实现说明](../runner-login-refresh.md)。+补充验证中,经用户明确授权,使用本机 Antigravity 登录+真实刷新并保留最新凭证;未读取、刷新或修改本机 Codex / Claude Code 的真实登录。++## 结论++**身份校验能阻止换号,但“cleanup 再刷新一次以确认 refresh token 的归属”尚不适合直接作为三种 CLI 的通用实现。**++在模拟认证服务的契约下,原型保留正常轮换和后续刷新,能拒绝整套换号、伪造本地身份、+只换 refresh token、只换 access token、同工作区不同用户、同用户不同组织。+这些结果证明的是算法在明确假设下的行为,不是真实供应商兼容性认证。++同时复现了两个会影响正常续期的边界:++1. 服务端已经轮换 refresh token,但响应在客户端收到之前丢失。隔离保存的仍是已消耗的+ 旧 token,无法恢复客户端从未收到的新 token;直接重试还可能触发 token 重用检测。+2. 两个沙箱或宿主机 CLI 使用同一份一次性 refresh token。第二次使用可以导致认证服务+ 撤销整个 token family。宿主机文件的内容比较与原子 rename 不能撤销服务端的变化。++因此,先前“遇到网络错误就隔离并重试,可以避免丢失轮换凭证”的说法需要收窄:+**只有已经收到、并持久化了新凭证,之后的身份查询失败,才验证了可在重启后安全恢复。**++### Codex 三方同时刷新的具体解释++上面的严格一次性 token / family 撤销模拟,不能直接等同于 Codex 服务端的实际策略。+[OpenAI 维护者于 2026-02-01 的解释](https://github.com/openai/codex/issues/10332)指出,+其刷新服务允许旧 refresh token 在有限宽限期内多次使用,当时描述为约一小时量级。+这是维护者对当时实现的说明,不是当前时长或所有轮换细节的稳定契约;本次未用真实账号验证。++两个 SOP 与宿主机同时从同一份原凭证刷新,在该宽限机制下可以各自成功,不能断言只有+一个成功、另两个必定退出登录。当前 LoopForge 给 SOP 的是各自私有 HOME 内的文件副本,+不是三方共享同一个宿主机认证文件。若宿主机先保存新凭证,两个 SOP 后续 cleanup 会发现+宿主机已经不同于最初快照并跳过写回;SOP 不会因此自动收到宿主机的最新凭证。++仍需单独验证的正常路径是:沙箱早已复制了旧凭证,宿主机已刷新,沙箱却在宽限结束后才+首次用旧 refresh token 刷新。独立 HOME 无法通过重新读取自己的文件获得宿主机更新,+当前 cleanup 的内容比较也不能协调运行中的刷新。不能仅增加 cleanup 锁就声称解决了+两个 SOP 与宿主机 CLI 之间的刷新协调。++## 第一轮模拟测试边界++- 全部凭证由测试生成,只有 `example.test`、`fake-*` 等虚构值。+- 当前实现的验证使用真实的 `prepareConversationRunnerLogin` 和 cleanup,但覆盖 HOME、+ CODEX_HOME、CLAUDE_CONFIG_DIR、Claude OAuth 环境变量,并让 Antigravity 明确使用临时文件。+ 不读取真实凭证、不访问钥匙串、不触发真实续期。+- 协议原型仅连接 `httptest.NewTLSServer` 创建的本机服务,拒绝重定向。+- `/profile` 是测试假定存在的可信身份接口,并非声明三家都有相同的公开接口。+- 轮换、保持原 refresh token 且响应省略该字段、重用导致 family 撤销,都是分别模拟的+ 服务端策略;不代表每家目前都实施全部策略。+- 第一轮没有真实 Claude Code 订阅测试,没有对当前 Codex 账号操作。Antigravity 真实+ 续期的补充结果见下节。没有用模拟结果替代对话或 SOP native/Docker 的真实路径结果。++## 第一轮执行结果++最终合并执行 **107 个叶子场景**,全部通过,开启 `-race`,无跳过、无数据竞争报告。++| 场景 | 数量 | 结果含义 |+| --- | ---: | --- |+| 当前三种 CLI 的真实 cleanup 实现 | 12 | 复现正常写回及现有换号校验缺口,并非修复 |+| 三种文件格式 × 两类刷新策略 × 身份/续期场景 | 54 | 原型允许正常续期,拒绝换号/混合凭证,后续可继续模拟刷新 |+| 私有状态恢复、宿主机更新/退出、响应丢失 | 21 | 已收到的新凭证可恢复;响应丢失明确返回结果不明 |+| 多副本重复使用 refresh token | 1 | 确认文件 CAS 不能阻止服务端 family 撤销 |+| 官方 Codex 0.163.0 二进制、虚构账号与本机服务 | 1 | 连续两次刷新并保存/复用最新 refresh token |+| 既有凭证生命周期回归 | 18 | 保持现有行为 |++官方 Codex 项使用 `account/read(refreshToken: true)` 显式触发刷新,不调用模型。+模拟服务收到两次刷新;一次非本机目标的代理请求被本地代理拒绝。子进程没有访问真实+供应商或本机登录。因此它证实了官方 CLI 的刷新/保存协议行为,**不是生产账号自动续期验收**。++## 补充验证:官方刷新接口与真实 Antigravity++### Codex 0.163.0:官方外部认证接口可用++按照[官方 App Server 文档](https://developers.openai.com/codex/app-server/)使用实验性+`chatgptAuthTokens` 登录和 `account/chatgptAuthTokens/refresh` 回调。启动三个私有 HOME+的官方 CLI,模拟宿主机与两个任务都接入同一个 Runner 刷新入口。三方最初只拿 access token,+本机模拟服务分别拒绝旧 token 后,三个 CLI 都回调宿主。++结果:**3 次认证拒绝 → 3 次回调 → 1 次模拟发行端刷新 → 3 个 CLI 恢复**。+Runner 先原子保存并 fsync 发行端返回的新凭证,再交付 access token;三个 CLI 的私有 HOME+都没有拿到 Runner 保管的 refresh token。这是官方客户端与模拟发行端的协议实测,未使用+当前 Codex 账号。没有证明不接入 Runner 的其他宿主机 CLI 也能被这把锁协调。++### Claude Code 2.1.326:有回调实现,但受入口限制++检查官方发布的 `@anthropic-ai/[email protected]` JavaScript 和本机官方 CLI,+发现 `getOAuthToken` / `oauth_token_refresh` 路径;**公开的 sdk.d.ts 未声明此选项**。+本机 CLI 还检查客户端入口:普通 `sdk-ts` 没有启用这条回调,允许的内部入口包括 `local-agent`。++全部在隔离 HOME、虚构凭证与本机模拟服务下实测,无 Claude 订阅、无真实 Anthropic 调用:++- 普通 `sdk-ts` 负对照:收到模拟 401 后回调数为 0,认证失败。+- 显式测试内部 `local-agent` 路径:**3 次模拟 401 → 3 次宿主回调 → 1 次模拟刷新 →+ 3 次模型请求重试成功**。模型响应由本机夹具生成,没有消费订阅或 API 额度。++这证明当前客户端有可工作的协议实现,**没有证明它是稳定公开 SDK 契约,也没有完成真实+Claude 订阅、组织归属或服务端刷新策略验收**。内部入口仅用于隔离实验,正式实现不能把+未经确认的内部能力当成无条件支持。++### Antigravity 1.5.10:真实 Google 并发刷新成功++`TestWritebackProbeAntigravityLiveRefresh` 显式 opt-in 后读取本机既有 Antigravity 钥匙串+记录。只调用官方 `agy models`,通过让私有副本的 access token / expiry 失效触发真实刷新;+不修改宿主原件使其过期、不触发交互登录、不调用付费模型推理。++| 真实场景 | 结果 |+| --- | --- |+| native 单次前置刷新 | 成功,18 个模型,refresh token 未变化 |+| 两路 native + 一路 Docker 同用旧 refresh token 并发刷新 | 三路全部成功,各返回 18 个模型,refresh token 均未变化 |+| 三路完成后再用同一个 refresh token 刷新 | 成功,refresh token 仍未变化 |+| 删除 refresh token,只保留有效 access token,native 查询模型 | 成功,18 个模型 |+| 同样的 access-only 文件,Docker 查询模型 | 成功,18 个模型 |+| 最终 access token 向 Google OIDC userinfo 查询身份 | 成功,不记录账号标识 |++此处“宿主侧”是隔离的 native 凭证副本;验证的是同一个真实 Google refresh token 的+并发重用行为,没有把用户正在使用的外部宿主 CLI 改接到新的管理器。native / Docker 都是+直接执行官方 CLI,没有重新创建完整对话或 SOP 业务任务。++有效刷新结果保留到原钥匙串来源;检测到宿主源已更新且 refresh token 相同,保留宿主更新。+模型查询失败也先检查是否已生成需要保留的新凭证。所有并发进程收集结束后才清理私有副本。+Docker 使用宿主 HOME 下缓存目录的私有临时子目录和严格 bind mount;未共享的 macOS /tmp+不能被误当作已经挂载的凭证目录。测试目录 `0700`、凭证 `0600`,成功后全部删除,不写入镜像或仓库。++**结论只适用于本次账号、版本与请求范围**:没有观察到“刷新一次立即作废旧 refresh token”。+这降低了本次并发导致掉登录的担忧。access-only 查询成功还不能证明长任务中的 token 热更新、+token 到期后的自动恢复,或未来的服务端轮换策略。++### 补充实验的隔离方式++`scripts/probe-cli-auth-control.py` 为 Codex / Claude 创建临时证书和仅本机的模拟服务。+Claude 的官方主机名由本机夹具模拟,用来进入客户端第一方 OAuth 分支;代理绝不向外转发,+子进程同时由 macOS 禁止访问外网和真实认证目录。证书只传给测试子进程,不修改系统信任。+这不是生产认证代理方案。Antigravity 的真实测试在另一个进程运行,没有使用该代理或测试 CA。++## 现有实现的复现++下表为改动前的复现结果。后续 `TestRunnerLoginSandboxEditsNotWrittenBack` 已改为断言拒绝这些编辑;+托管续期的正向覆盖由刷新管理器和官方客户端测试提供。++| 改动 | Codex | Claude Code | Antigravity |+| --- | --- | --- | --- |+| 同账号正常续期(改动前) | 写回 | 写回 | 写回 |+| 整套换号,身份字段也变更 | 拒绝 | **写回** | 拒绝 |+| 换号,但保留/伪造原本的本地身份字段 | **写回** | **写回** | **写回** |+| 保留 access token,仅换另一账号的 refresh token | **写回** | **写回** | **写回** |++Codex 的 `tokens.account_id`、Antigravity 的 email、以及 Claude 的本地配置都不能单独+证明新 refresh token 的归属。尤其 Codex 的工作区 ID 不应被当成唯一的用户标识。++## 测试中的验证器++这是 `_test.go` 内的实验,不是待发布的生产验证器:++1. 在复制凭证前,向可信身份服务确认宿主机的主体、工作区、组织,保存 Runner 私有基准。+ 本地已过期凭证如何建立这一基准,尚需各 CLI 的具体协议解决。+2. 将候选文件保存到沙箱之外的 Runner 私有状态。示例目录 `0700`、文件 `0600`,+ 临时文件写入后 `fsync`、rename、目录 `fsync`。身份基准与原文件快照都不由沙箱提供。+3. 未变更的候选直接跳过,不额外刷新。宿主机已更新或已登出,直接放弃写回。+4. 候选 access token 若能验证,先拒绝不同主体。access token 已失效则不以此判断归属。+5. **兑换候选 refresh token**,保存认证服务返回的完整新凭证,再核实新 access token 的身份。+ 这一步才会暴露“access 属于 A、refresh 属于 B”的混合凭证。+6. 身份一致且宿主机仍未变更,写回服务端返回的新凭证,绝不写回已经被再次兑换的沙箱凭证。+ 响应未给新 refresh token 时保留兑换时使用的 token,不把它清空。+7. 新凭证已持久化、身份服务暂时故障:恢复后只查询身份,不重复兑换旧 refresh token。+ 刷新请求结果不明:标记 `uncertain`,不盲目重试,也不声称已恢复自动续期。++测试还保留 Claude 的 scopes、subscriptionType、rateLimitTier 等字段,并验证写回后的+凭证能在下一次模拟 CLI 调用中继续刷新。++## 接入前仍需解决++| CLI | 已确认的协议依据 | 仍缺少的验证 |+| --- | --- | --- |+| Codex | 官方外部认证回调已通过三客户端并发合并验证;接口为实验性 | 独立测试账号下的主体/工作区绑定、轮换与重用策略,以及未接入管理器的宿主客户端 |+| Claude Code | 当前客户端内部回调路径通过模拟 401 与三进程重试验证;普通 sdk-ts 不支持 | 可公开依赖的接口、真实订阅与组织归属、服务端刷新契约;不能把内部入口直接作为稳定能力 |+| Antigravity | 同一真实 refresh token 的三路并发与后续重用成功;access-only 查询成功 | 长进程跨过期时接收新 access token 的机制、更多账号/版本行为;不能只比较 email |++还需处理:刷新成功到本地状态持久化之间的进程/磁盘故障窗口、长期待验证凭证过期、+待处理记录的清理与权限隔离、宿主机非合作 CLI 的并发刷新。现有文件写入器在 rename 前+再次读取,但这不是与外部 CLI 共同参与的线性化 CAS。++更稳妥的后续方向是确认各 CLI 是否允许 Runner 管理刷新:真实 refresh token 留在可信+进程,沙箱获得短期 access token 或限于本次会话的刷新句柄。先检查官方扩展点;本次不+在正式执行路径引入认证代理、TLS 拦截或新的鉴权路径,也不关闭现有自动写回。++## 复现命令++```sh+go test ./internal/runtime -run '^TestWritebackProbe' -count=1 -v+go test -race ./internal/runtime -run '^TestWritebackProbe' -count=1+```++包含既有凭证生命周期回归:++```sh+go test -race ./internal/runtime \+ -run '^Test(WritebackProbe|RunnerLogin|ManagedLogin|ConversationRunnerLogin|Antigravity.*Login)' \+ -count=1+```++默认不会启动任何本机 CLI。`TestManagedLoginOfficialCodex` 需要显式设置+`LOOPFORGE_PROBE_CODEX_BIN`,并要求 macOS `sandbox-exec`。它给官方二进制提供全新的 HOME、+虚构的 token 和本机模拟刷新服务,同时由操作系统禁止读取真实认证目录、写入真实 HOME+和访问非本机网络。此项只验证 CLI 协议行为,不验证真实供应商策略。++```sh+LOOPFORGE_PROBE_CODEX_BIN=/absolute/path/to/official/codex \+ go test -race ./internal/runtime -run '^TestManagedLoginOfficialCodex$' -count=1 -v+```++官方 CLI 外部认证协议(全部是假凭证、本机模拟响应;需要 macOS、Python 3.9+、openssl):++```sh+python3 scripts/probe-cli-auth-control.py codex --binary /absolute/path/to/official/codex+python3 scripts/probe-cli-auth-control.py claude --binary /absolute/path/to/official/claude \+ --clients 1 --expect-unsupported-sdk+# 下面仅验证内部入口,不能据此认定公开 SDK 已支持。+python3 scripts/probe-cli-auth-control.py claude --binary /absolute/path/to/official/claude \+ --claude-entrypoint local-agent+```++以下是**会读取并刷新真实 Antigravity 登录**的单独 opt-in,要求预先准备不含凭证的官方 CLI+Docker 镜像;只在已授权的机器运行,确保 PATH 中的 docker 连接本地引擎:++```sh+LOOPFORGE_PROBE_AGY_LIVE=1 \+LOOPFORGE_PROBE_AGY_BIN=/absolute/path/to/official/agy \+LOOPFORGE_PROBE_AGY_DOCKER_IMAGE=credential-free-official-agy-image \+ go test ./internal/runtime -run '^TestWritebackProbeAntigravityLiveRefresh$' -count=1 -v+```++## 协议依据++- [Codex 官方认证实现](https://github.com/openai/codex/blob/5a4aff84319b4376658b4cac50fcd15fa976f6fa/codex-rs/login/src/auth/manager.rs):+ `persist_tokens`、`request_chatgpt_token_refresh`、`RefreshResponse`。+- [Claude Code 官方认证说明](https://code.claude.com/docs/en/authentication):登录及自动刷新。+- [Google OAuth 刷新契约](https://developers.google.com/identity/protocols/oauth2/web-server#offline):+ 刷新返回新 access token,示例响应不含 refresh token。+- [Google OIDC](https://developers.google.com/identity/openid-connect/openid-connect):userinfo 与稳定主体标识。+- [RFC 6749 §6](https://www.rfc-editor.org/rfc/rfc6749#section-6):若发行新 refresh token,客户端必须替换旧值。+- [RFC 9700 §4.14.2](https://www.rfc-editor.org/rfc/rfc9700#section-4.14.2):refresh token 轮换及重用检测可能导致当前 family 撤销。diff --git a/docs/runner-login-refresh.md b/docs/runner-login-refresh.mdnew file mode 100644index 00000000..caa73e0a--- /dev/null+++ b/docs/runner-login-refresh.md@@ -0,0 +1,83 @@+# Runner 本机登录与自动续期++对话工作区与 SOP 的 native、Docker 沙箱共用同一套登录准备逻辑。+API Key 模式沿用个人设置,不经过本机 OAuth 刷新管理器。++## Codex / Claude Code++Runner 保管宿主机原凭证。任务只能得到当前 access token 与本次任务的刷新能力,+不会得到上游 refresh token。任务在自己的 HOME 里换号、伪造身份字段或替换 refresh token,+cleanup 都不会把这些文件写回宿主机。++- **Codex**:私有 `auth.json` 中的 refresh token 是随机任务句柄,+ `CODEX_REFRESH_TOKEN_URL_OVERRIDE` 指向 Runner 的临时入口。官方 CLI 自己判断何时需要刷新,+ Runner 用宿主原凭证向 OAuth 服务申请,保存成功后返回 access token 和下一个临时句柄。+ 同一旧句柄的重试复用原响应,不会再次刷新上游。+- **Claude Code**:通过 stream-json 的 `oauth_token_refresh` 控制通道回调 Runner,+ stdin 返回 access token。任务 credential 文件不含 refresh token;临近过期的宿主凭证在启动前续期。+ 单次 SOP 收到最终结果后关闭输入;对话保留原有可继续发送消息的输入通道。++普通 Docker SOP 使用 `AGENTFLOW_DOCKER_NETWORK` 指定的网络。对话工作区和包含 Codex 账号登录节点的+Docker SOP 使用中继网络配置连接执行机器上的回调。SOP 的准备脚本、终端和执行节点共享同一个容器。++Claude Code 的回调在 **2.1.326** 的官方客户端中实测可用,但属于受入口限制的内部协议,+并不是公开稳定的 SDK 类型契约。当前绑定 `local-agent` 入口,内置安装版本为 2.1.326。+已知较旧版本或初始化失败会提示更新,不会退回向沙箱发送真实 refresh token。+未使用真实 Claude 订阅验收;测试使用官方二进制、虚构凭证与本机模拟认证/模型服务。++## 并发、持久化与账户切换++同一凭证来源使用进程内锁与跨进程文件锁。两个 SOP 同时刷新时,第一个完成上游交换,+后续请求复用宿主已经更新的凭证。已接入同一管理器的宿主进程也遵守这把锁。++刷新前记录交换状态,收到响应后先将完整新凭证保存到私有 journal,再原子替换宿主文件并同步磁盘。+最终只保留不含 token 的 hash receipt,供另一 Runner 进程识别该更新;正常完成后删除 journal。+进程重启时先恢复已收到的新凭证,避免重复使用已经轮换的旧 refresh token。+任务取消不取消已经开始的交换,最多等待独立的 30 秒期限来保存结果。++若请求已发出,但响应丢失或不可解析,旧 access token 和宿主文件保留;+同一份 refresh token 不会被自动重复兑换。此时需宿主登录源被重新登录或其他官方进程更新后才能继续续期。+客户端无法恢复从未收到的新 token。明确的 HTTP 4xx 拒绝(408 除外)允许以后重试。++宿主退出登录不会被 journal 复活;宿主切换账号时,已有任务不会接入新账号。+凭证来源为符号链接时,同时核对原路径;链接被删除或改指向后,停止使用旧目标,刷新中也不会向旧目标写回。+Codex 的用户身份与工作区共同作锚点;Claude 使用可信宿主 `.claude.json` 的账号/组织资料。+缺少账号资料时,只接受管理器自己有 receipt 的更新,其他变化需要重启任务。++默认私有状态目录为系统用户缓存目录下 `LoopForge/runner-auth`;可以用+`AGENTFLOW_RUNNER_AUTH_DIR` 指定持久目录,必须放在任务工作区之外。目录权限 `0700`,文件 `0600`。+native 托管任务遮蔽原凭证与刷新目录;Docker 只得到工作区中的私有副本。+任务结束会关闭刷新入口并移除临时凭证,不把刷新控制消息写入任务日志。++**独立启动、没有接入管理器的宿主机官方 CLI 不受这把锁约束。**+Runner 会尽量识别并保留宿主更新,文件内容复核不能等价于所有应用共同参与的事务。++## Antigravity++保持官方 CLI 在沙箱私有文件中自行刷新。当前 Google 登录实测允许并发重用同一 refresh token,+正常刷新会改变 access token,refresh token 不变。++cleanup 要求 refresh token 与宿主原件一致,并通过 Google OIDC userinfo 核验新 access token+属于原账号。access token 未变化时跳过写回。写回前检查 expiry 是尚未到期的时间戳,+显式提供的 token type 必须为 Bearer。保留宿主原有的账户资料及 refresh token。+宿主已变化、核验失败或只替换 refresh token 时继续保留宿主记录。+这没有实现 access-only 的长任务热更新,也没有把未来可能出现的 Google refresh-token 轮换当作已验证行为。++## 验证方式++普通测试不读取本机真实登录。可显式启用以下测试:++```sh+# 官方 Codex / Claude Code:仅本机虚构认证服务,macOS sandbox-exec 禁止外网与真实凭证访问+LOOPFORGE_PROBE_CODEX_BIN=/absolute/path/to/codex \+LOOPFORGE_PROBE_CLAUDE_BIN=/absolute/path/to/claude \+go test ./internal/runtime -run 'TestManagedLoginOfficial' -race -count=1++# 实际 native + Docker,对话和 SOP;使用 Python CLI 夹具与虚构 token+# 需要预先提供 python:3.13-alpine,macOS 的工作区放在 Docker 已共享的用户缓存目录+LOOPFORGE_PROBE_AUTH_SANDBOXES=1 \+go test ./internal/runtime -run TestManagedLoginRuntimePaths -race -count=1+```++Antigravity 的真实 Google 刷新实验单独 opt-in,命令及边界见+[验证记录](proposals/runner-login-writeback-verification.md)。不与虚构认证代理共用进程。diff --git a/go.mod b/go.modindex a267673c..2704c933 100644--- a/go.mod+++ b/go.mod@@ -10,6 +10,7 @@ require (github.com/goccy/go-yaml v1.19.2github.com/gorilla/websocket v1.5.3github.com/klauspost/compress v1.20.3+ github.com/zalando/go-keyring v0.2.8golang.org/x/crypto v0.58.0golang.org/x/net v0.62.0golang.org/x/sys v0.49.0@@ -23,6 +24,7 @@ require (github.com/bytedance/sonic v1.15.0 // indirectgithub.com/bytedance/sonic/loader v0.5.0 // indirectgithub.com/cloudwego/base64x v0.1.6 // indirect+ github.com/danieljoos/wincred v1.2.3 // indirectgithub.com/dustin/go-humanize v1.0.1 // indirectgithub.com/gabriel-vasile/mimetype v1.4.12 // indirectgithub.com/gin-contrib/sse v1.1.0 // indirect@@ -31,6 +33,7 @@ require (github.com/go-playground/universal-translator v0.18.1 // indirectgithub.com/go-playground/validator/v10 v10.30.1 // indirectgithub.com/goccy/go-json v0.10.5 // indirect+ github.com/godbus/dbus/v5 v5.2.2 // indirectgithub.com/google/uuid v1.3.0 // indirectgithub.com/jinzhu/inflection v1.0.0 // indirectgithub.com/jinzhu/now v1.1.5 // indirectdiff --git a/go.sum b/go.sumindex a210c63b..6cc18315 100644--- a/go.sum+++ b/go.sum@@ -10,6 +10,8 @@ github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLIgithub.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=+github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=+github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=@@ -39,6 +41,8 @@ github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=+github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=+github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=@@ -83,6 +87,7 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqgithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=+github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=@@ -95,6 +100,8 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkSgithub.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=+github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=+github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=@@ -108,6 +115,8 @@ golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=+golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=+golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=diff --git a/internal/domain/runner.go b/internal/domain/runner.goindex 14c361f9..acee4c60 100644--- a/internal/domain/runner.go+++ b/internal/domain/runner.go@@ -285,11 +285,10 @@ func (r Runner) SupportsProvider(provider string) bool {}// RuntimeAuthMode returns the configured credential source for a provider.-// CodeBuddy and the extra agent CLIs have no reusable local-login flow, so-// they always use the responsible user's personal credential. Codex and-// Claude Code default to local login.+// CLIs with reusable account authentication default to local login. Other+// CLIs always use the responsible user's personal credential.func (r Runner) RuntimeAuthMode(provider string) string {- if IsAgentCLIKind(provider) {+ if IsAgentCLIKind(provider) && !SupportsRunnerLogin(provider) {return RuntimeAuthPersonal}provider = strings.TrimSpace(provider)@@ -310,6 +309,15 @@ func (r Runner) RuntimeAuthMode(provider string) string {return RuntimeAuthLocal}+func SupportsRunnerLogin(provider string) bool {+ switch strings.ToLower(strings.TrimSpace(provider)) {+ case "codex", "claude-code", "agy":+ return true+ default:+ return false+ }+}+const (RuntimeStatusOnline = "online"RuntimeStatusOffline = "offline"@@ -407,9 +415,10 @@ type RunnerTask struct {// RunnerSandboxRequirements freezes the union needed by every run node, so// interactive terminals and script/agent tasks use the same sandbox identity.type RunnerSandboxRequirements struct {- CLIStates []RunnerCLIStateRequirement `json:"cliStates,omitempty"`- PrivateHome bool `json:"privateHome,omitempty"`- BunFS bool `json:"bunFS,omitempty"`+ CLIStates []RunnerCLIStateRequirement `json:"cliStates,omitempty"`+ PrivateHome bool `json:"privateHome,omitempty"`+ BunFS bool `json:"bunFS,omitempty"`+ RunnerLoginRelay bool `json:"runnerLoginRelay,omitempty"`}type RunnerCLIStateRequirement struct {Directory string `json:"directory"`diff --git a/internal/domain/runner_test.go b/internal/domain/runner_test.goindex 385fa6bf..8ebf0ac7 100644--- a/internal/domain/runner_test.go+++ b/internal/domain/runner_test.go@@ -81,6 +81,13 @@ func TestAgentCLIRuntimeAuthModeIsPersonal(t *testing.T) {if r.RuntimeAuthMode("codebuddy") != RuntimeAuthPersonal {t.Fatal("codebuddy still defaults to personal credentials")}+ if r.RuntimeAuthMode("agy") != RuntimeAuthLocal {+ t.Fatal("Antigravity supports local account login")+ }+ r.Runtimes = append(r.Runtimes, RunnerRuntime{Provider: "agy", AuthMode: RuntimeAuthPersonal})+ if r.RuntimeAuthMode("agy") != RuntimeAuthPersonal {+ t.Fatal("Antigravity API-key preference was ignored")+ }}func TestRunnerSupportsWorkBranchSync(t *testing.T) {diff --git a/internal/engine/execution_cleanup_cases_test.go b/internal/engine/execution_cleanup_cases_test.goindex 895f0f5f..5b806f23 100644--- a/internal/engine/execution_cleanup_cases_test.go+++ b/internal/engine/execution_cleanup_cases_test.go@@ -245,7 +245,7 @@ func TestWorkspacePreparationDirectValidationAndRemoteStates(t *testing.T) {if plan.CollaborationMode != "" || plan.Nodes[0].RunOnWorkspaceRebuild {t.Fatalf("preparation plan=%+v", plan)}- if requirements, err := workspaceConversationRequirements(st, domain.WorkflowDefinition{Nodes: []domain.WorkflowNode{{Type: "agent", AgentID: "missing"}}}); err != nil || len(requirements.CLIStates) != 0 {+ if requirements, err := workspaceConversationRequirements(st, domain.WorkflowDefinition{Nodes: []domain.WorkflowNode{{Type: "agent", AgentID: "missing"}}}, false); err != nil || len(requirements.CLIStates) != 0 {t.Fatalf("conversation requirements=%+v err=%v", requirements, err)}if _, err := e.WorkspacePreparationStatus(context.Background(), "missing"); err == nil {diff --git a/internal/engine/runner_dispatch.go b/internal/engine/runner_dispatch.goindex eef53c1b..066fbbb2 100644--- a/internal/engine/runner_dispatch.go+++ b/internal/engine/runner_dispatch.go@@ -148,7 +148,8 @@ func (e *Engine) requireWorkBranchCapabilities(runnerID string, repositories []d}func (e *Engine) runnerSandboxSpec(run domain.Run) (*domain.RunnerSandboxSpec, error) {- if err := e.requireWorkBranchCapabilities(e.defaultExecutionRunner(run), run.RepositoryContexts()); err != nil {+ runnerID := e.defaultExecutionRunner(run)+ if err := e.requireWorkBranchCapabilities(runnerID, run.RepositoryContexts()); err != nil {return nil, err}profile, resources, err := e.workspaceSandboxProfile(run)@@ -156,11 +157,20 @@ func (e *Engine) runnerSandboxSpec(run domain.Run) (*domain.RunnerSandboxSpec, ereturn nil, err}spec := resolvedSandboxSnapshot(profile, resources)- requirements, err := workspaceConversationRequirements(e.repo, run.WorkflowSnapshot)+ var codexLoginRelay bool+ if profile.Driver == domain.SandboxDriverDocker && runnerID != "" {+ runner, ok := e.repo.Runner(runnerID)+ codexLoginRelay = ok && runner.RuntimeAuthMode("codex") == domain.RuntimeAuthLocal+ }+ requirements, err := workspaceConversationRequirements(e.repo, run.WorkflowSnapshot, codexLoginRelay)if err != nil {return nil, err}- spec.Requirements = &domain.RunnerSandboxRequirements{PrivateHome: requirements.PrivateHome, BunFS: requirements.BunFS}+ spec.Requirements = &domain.RunnerSandboxRequirements{+ PrivateHome: requirements.PrivateHome,+ BunFS: requirements.BunFS,+ RunnerLoginRelay: requirements.RunnerLoginRelay,+ }for _, state := range requirements.CLIStates {spec.Requirements.CLIStates = append(spec.Requirements.CLIStates, domain.RunnerCLIStateRequirement{Directory: state.Directory, Files: append([]string(nil), state.Files...)})}diff --git a/internal/engine/runner_sandbox_test.go b/internal/engine/runner_sandbox_test.goindex f32c7202..2d1da482 100644--- a/internal/engine/runner_sandbox_test.go+++ b/internal/engine/runner_sandbox_test.go@@ -63,6 +63,51 @@ func TestRunnerSandboxSpecUsesFrozenSnapshot(t *testing.T) {}}+func TestRunnerSandboxSpecRequestsRelayForDockerCodexAccountLogin(t *testing.T) {+ s, err := repo.OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ defer s.Close()+ e := New(s, runtime.NewManager(t.TempDir()))+ for _, tc := range []struct {+ name, driver, provider, authMode string+ wantRelay bool+ }{+ {name: "Codex account login", driver: "docker", provider: "codex", authMode: domain.RuntimeAuthLocal, wantRelay: true},+ {name: "Codex API key", driver: "docker", provider: "codex", authMode: domain.RuntimeAuthPersonal},+ {name: "CodeBuddy API key", driver: "docker", provider: "codebuddy", authMode: domain.RuntimeAuthPersonal},+ {name: "Claude login uses stdio", driver: "docker", provider: "claude-code", authMode: domain.RuntimeAuthLocal},+ {name: "Antigravity refreshes inside its sandbox", driver: "docker", provider: "agy", authMode: domain.RuntimeAuthLocal},+ {name: "native Codex uses loopback", driver: "native", provider: "codex", authMode: domain.RuntimeAuthLocal},+ } {+ t.Run(tc.name, func(t *testing.T) {+ runner := domain.Runner{ID: "runner", Runtimes: []domain.RunnerRuntime{{Provider: tc.provider, AuthMode: tc.authMode}}}+ if err := s.PutRunner(runner); err != nil {+ t.Fatal(err)+ }+ agent := domain.AgentDefinition{ID: "agent-" + tc.provider, Name: tc.provider, ExecutorID: tc.provider}+ if err := s.PutAgent(agent); err != nil {+ t.Fatal(err)+ }+ run := domain.Run{+ ExecutionContext: domain.TelemetryContext{ExecutionMode: domain.ExecutionModeRunner, ExecutionRunnerID: runner.ID},+ WorkflowSnapshot: domain.WorkflowDefinition{+ SandboxSnapshot: &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{Driver: tc.driver}},+ Nodes: []domain.WorkflowNode{{Type: "script"}, {Type: "agent", AgentID: agent.ID}},+ },+ }+ spec, err := e.runnerSandboxSpec(run)+ if err != nil {+ t.Fatal(err)+ }+ if spec.Requirements.RunnerLoginRelay != tc.wantRelay {+ t.Fatalf("Runner login relay = %v, want %v", spec.Requirements.RunnerLoginRelay, tc.wantRelay)+ }+ })+ }+}+func TestDefaultExecutionRunnerUsesFrozenTarget(t *testing.T) {t.Parallel()s, err := repo.OpenTest()diff --git a/internal/engine/workspace_preparation.go b/internal/engine/workspace_preparation.goindex b7fd435a..022d97d3 100644--- a/internal/engine/workspace_preparation.go+++ b/internal/engine/workspace_preparation.go@@ -53,7 +53,7 @@ func (e *Engine) acquireConversationEnvironment(ctx context.Context, run domain.if err != nil {return nil, err}- requirements, err := workspaceConversationRequirements(e.repo, run.WorkflowSnapshot)+ requirements, err := workspaceConversationRequirements(e.repo, run.WorkflowSnapshot, false)if err != nil {return nil, err}@@ -421,7 +421,7 @@ func (e *Engine) ForwardWorkspaceRequest(ctx context.Context, run domain.Run, re// A settled historical workflow may refer to a role removed from the catalog.// Opening its files/terminal must not require resurrecting that model role.// Execution still uses the strict workflow validation and executor resolution.-func workspaceConversationRequirements(st *repo.Store, wf domain.WorkflowDefinition) (runtime.SandboxRequirements, error) {+func workspaceConversationRequirements(st *repo.Store, wf domain.WorkflowDefinition, codexLoginRelay bool) (runtime.SandboxRequirements, error) {var items []runtime.SandboxRequirementsfor _, node := range wf.Nodes {if node.Type != "agent" {@@ -435,7 +435,11 @@ func workspaceConversationRequirements(st *repo.Store, wf domain.WorkflowDefinitif err != nil {continue}- items = append(items, runtime.ProviderRequirements(executor.Kind))+ requirements := runtime.ProviderRequirements(executor.Kind)+ // Freeze the relay need for the whole workflow so preparation, scripts,+ // terminals and agents can reuse the same Docker container.+ requirements.RunnerLoginRelay = codexLoginRelay && executor.Kind == "codex"+ items = append(items, requirements)}return runtime.MergeSandboxRequirements(items...), nil}diff --git a/internal/httpapi/antigravity_runner_login_test.go b/internal/httpapi/antigravity_runner_login_test.gonew file mode 100644index 00000000..26753089--- /dev/null+++ b/internal/httpapi/antigravity_runner_login_test.go@@ -0,0 +1,59 @@+package httpapi++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "testing"++ "agentflow/internal/domain"+)++func TestAntigravityRunnerLoginRequiresMachineOwner(t *testing.T) {+ h, owner := workbenchFixture(t)+ row := domain.Runner{ID: "agy-laptop", OwnerUserID: owner.ID, Status: domain.RunnerStatusOnline, RunnerVersion: domain.RunnerVersionCLISettings, Runtimes: []domain.RunnerRuntime{{Provider: "agy", AuthMode: domain.RuntimeAuthLocal}}}+ if err := h.repo.PutRunner(row); err != nil {+ t.Fatal(err)+ }+ target := domain.AssistantExecutionTarget{Pool: domain.ExecutionModeRunner, RunnerID: row.ID}+ if !h.assistantUsesRunnerLogin(owner.ID, &target, "agy") {+ t.Fatal("machine owner could not reuse Antigravity login")+ }+ if h.assistantUsesRunnerLogin(owner.ID+1, &target, "agy") {+ t.Fatal("shared conversation member could use another user's login")+ }+ if h.assistantUsesRunnerLogin(owner.ID, &domain.AssistantExecutionTarget{Pool: domain.ExecutionModeCloud}, "agy") {+ t.Fatal("cloud target inherited a personal machine login")+ }+ called := false+ h.generate = func(context.Context, string, domain.User) (string, error) { called = true; return "account reply", nil }+ request := assistantRequest{SessionID: "agy-login", Executor: "agy", Model: "gemini-4-hydrogen-high", Messages: []assistantMessage{{Role: "user", Content: "hello"}}, ExecutionTarget: &target}+ body, _ := json.Marshal(request)+ c, rec := workbenchContext(owner, http.MethodPost, "/api/assistant/chat", bytes.NewBuffer(body))+ h.chat(c)+ if rec.Code != http.StatusOK || !called {+ t.Fatalf("account login was blocked by the API-key preflight: %d %s", rec.Code, rec.Body)+ }+ row.Runtimes[0].AuthMode = domain.RuntimeAuthPersonal+ if err := h.repo.PutRunner(row); err != nil {+ t.Fatal(err)+ }+ if h.assistantUsesRunnerLogin(owner.ID, &target, "agy") {+ t.Fatal("explicit API-key mode was ignored")+ }+}++func TestAntigravityRuntimeRegistrationKeepsAccountPreference(t *testing.T) {+ reported := []domain.RunnerRuntime{{Provider: "agy", AuthMode: domain.RuntimeAuthPersonal}, {Provider: "cursor", AuthMode: domain.RuntimeAuthLocal}}+ fresh := normalizeRunnerRuntimes(reported, nil)+ if fresh[0].AuthMode != domain.RuntimeAuthLocal || fresh[1].AuthMode != domain.RuntimeAuthPersonal {+ t.Fatalf("initial authentication modes: %+v", fresh)+ }+ for _, mode := range []string{domain.RuntimeAuthLocal, domain.RuntimeAuthPersonal} {+ existing := []domain.RunnerRuntime{{Provider: "agy", AuthMode: mode}}+ if normalized := normalizeRunnerRuntimes(reported, existing); normalized[0].AuthMode != mode {+ t.Fatalf("saved mode %s was overwritten", mode)+ }+ }+}diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.goindex 91ab0f02..5af36283 100644--- a/internal/httpapi/assistant.go+++ b/internal/httpapi/assistant.go@@ -1519,7 +1519,9 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.Uinv, err = prepareAssistantCodexInvocation(engineOpts)default:if runtime.IsAgentCLI(engine) {- engineOpts.User = runtime.AgentCLIUserCredentials(user)[engine]+ if !req.RunnerLogin {+ engineOpts.User = runtime.AgentCLIUserCredentials(user)[engine]+ }inv, err = prepareAssistantAgentCLIInvocation(engine, engineOpts)break}diff --git a/internal/httpapi/assistant_execution.go b/internal/httpapi/assistant_execution.goindex 5625706d..5f3f8351 100644--- a/internal/httpapi/assistant_execution.go+++ b/internal/httpapi/assistant_execution.go@@ -66,7 +66,7 @@ func runnerUsesLocalLogin(runner domain.Runner, engine string) bool {}func assistantSupportsRunnerLogin(engine string) bool {- return engine == assistantEngineCodex || engine == assistantEngineClaude+ return domain.SupportsRunnerLogin(engine)}func (h *assistantHandlers) sessionMode(c *gin.Context) {diff --git a/internal/httpapi/runners.go b/internal/httpapi/runners.goindex 62448efe..e80de3e7 100644--- a/internal/httpapi/runners.go+++ b/internal/httpapi/runners.go@@ -684,7 +684,7 @@ func normalizeRunnerRuntimes(reported, existing []domain.RunnerRuntime) []domainif previous.Status == domain.RuntimeStatusDisabled {out[i].Status = domain.RuntimeStatusDisabled}- if domain.IsAgentCLIKind(out[i].Provider) {+ if domain.IsAgentCLIKind(out[i].Provider) && !domain.SupportsRunnerLogin(out[i].Provider) {out[i].AuthMode = domain.RuntimeAuthPersonal} else if previous.AuthMode == domain.RuntimeAuthLocal || previous.AuthMode == domain.RuntimeAuthPersonal {out[i].AuthMode = previous.AuthModediff --git a/internal/httpapi/schedule_runner_login_test.go b/internal/httpapi/schedule_runner_login_test.goindex f0bb59ca..1831a112 100644--- a/internal/httpapi/schedule_runner_login_test.go+++ b/internal/httpapi/schedule_runner_login_test.go@@ -20,6 +20,12 @@ import ()func TestScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T) {+ for _, cliEngine := range []string{assistantEngineClaude, runtime.AgentCLIAntigravity} {+ t.Run(cliEngine, func(t *testing.T) { testScheduleJobUsesSaversDefaultRunnerLogin(t, cliEngine) })+ }+}++func testScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T, cliEngine string) {t.Setenv("TMPDIR", t.TempDir())t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true")t.Setenv("AGENTFLOW_SESSION_SECRET", "schedule-runner-login-test")@@ -32,7 +38,7 @@ func TestScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T) {joinScheduledProject(t, st, "workbench", saver.ID)machine := domain.Runner{ID: "saver-machine", OwnerUserID: saver.ID, Status: domain.RunnerStatusOnline,RunnerVersion: domain.RunnerVersionCLISettings, Runtimes: []domain.RunnerRuntime{- {Provider: assistantEngineClaude, Status: domain.RuntimeStatusOnline, AuthMode: domain.RuntimeAuthLocal},+ {Provider: cliEngine, Status: domain.RuntimeStatusOnline, AuthMode: domain.RuntimeAuthLocal},},}foreign := machine@@ -51,7 +57,7 @@ func TestScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T) {server := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "")body := domain.ScheduleJob{ID: "runner-login-job", ProjectID: "workbench", Name: "巡检", SkipDispatch: true, AssistantPrompt: "检查",- AssistantModel: "claude-code:opus", RunAsUserID: owner.ID, IntervalSec: 3600, Enabled: true,+ AssistantModel: cliEngine + ":default", RunAsUserID: owner.ID, IntervalSec: 3600, Enabled: true,}setDefault(foreign.ID)if code := scheduleAuthzStatus(t, server, saver, http.MethodPut, "/api/schedule-jobs", body); code != http.StatusBadRequest {@@ -73,11 +79,11 @@ func TestScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T) {if err := json.Unmarshal(rec.Body.Bytes(), &catalog); err != nil {t.Fatal(err)}- hasClaude := slices.ContainsFunc(catalog.Models, func(m assistantModel) bool {- return m.Engine == assistantEngineClaude+ hasEngine := slices.ContainsFunc(catalog.Models, func(m assistantModel) bool {+ return m.Engine == cliEngine})- if rec.Code != http.StatusOK || hasClaude != test.want {- t.Fatalf("catalog %q lists keyless Claude models = %v, status = %d", test.query, hasClaude, rec.Code)+ if rec.Code != http.StatusOK || hasEngine != test.want {+ t.Fatalf("catalog %q lists keyless %s models = %v, status = %d", test.query, cliEngine, hasEngine, rec.Code)}}@@ -108,12 +114,18 @@ func TestScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T) {result := runtime.ConversationProcessResult{ID: req.ID}switch req.Operation {case "start":- if req.Command == nil || !req.Command.RunnerLogin || req.Command.Credentials.ClaudeCode.APIKey != "" {+ if req.Command == nil || !req.Command.RunnerLogin || req.Command.Credentials.ClaudeCode.APIKey != "" || req.Command.Credentials.AgentCLI[cliEngine].APIKey != "" {t.Fatal("scheduled turn did not request CLI account login")}launched = truecase "poll":result.Events = []domain.TelemetryEvent{{Name: "process.stdout", Message: `{"type":"result","result":"巡检完成"}`}}+ if cliEngine == runtime.AgentCLIAntigravity {+ result.Events = []domain.TelemetryEvent{+ {Name: "process.stdout", Message: `{"event":"init","conversation_id":"schedule-agy","init":{"model":"gemini-4-hydrogen-high"}}`},+ {Name: "process.stdout", Message: `{"event":"result","result":{"status":"SUCCESS","response":"巡检完成"}}`},+ }+ }result.Sequence, result.Done = 1, truecase "stop":result.Done = true@@ -143,16 +155,24 @@ func TestScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T) {var keyError errorh.generate = func(_ context.Context, _ string, actor domain.User) (string, error) {keyAttempts++- if actor.ID != saver.ID || actor.ClaudeCodeAPIKey != saverKey {+ key := actor.ClaudeCodeAPIKey+ if cliEngine == runtime.AgentCLIAntigravity {+ key = actor.AgentCLICredentials[cliEngine].APIKey+ }+ if actor.ID != saver.ID || key != saverKey {return "", errors.New("fallback used the wrong credentials")}return "云端巡检完成", keyError}- if _, err := h.prepareScheduleJob(saved); err == nil || !strings.Contains(err.Error(), "已离线。未配置 Claude Code API Key") || keyAttempts != 0 {+ if _, err := h.prepareScheduleJob(saved); err == nil || !strings.Contains(err.Error(), "已离线。未配置 "+assistantEngineLabel(cliEngine)+" API Key") || keyAttempts != 0 {t.Fatalf("offline runner without a key = %v, attempts = %d", err, keyAttempts)}- if _, err := st.UpdateUserCredentials(saver.ID, repo.UserCredentialUpdate{ClaudeCodeAPIKey: saverKey}); err != nil {+ update := repo.UserCredentialUpdate{ClaudeCodeAPIKey: saverKey}+ if cliEngine == runtime.AgentCLIAntigravity {+ update = repo.UserCredentialUpdate{AgentCLICredentials: map[string]repo.AgentCLICredentialUpdate{cliEngine: {APIKey: saverKey}}}+ }+ if _, err := st.UpdateUserCredentials(saver.ID, update); err != nil {t.Fatal(err)}if message, err := h.prepareScheduleJob(saved); err != nil || message != "云端巡检完成" || keyAttempts != 1 {@@ -168,9 +188,9 @@ func TestScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T) {t.Fatal("offline fallback did not run the same model and user in the cloud")}- keyError = assistantCredentialError{engine: assistantEngineClaude}+ keyError = assistantCredentialError{engine: cliEngine}if _, err := h.prepareScheduleJob(saved); err == nil || !strings.Contains(err.Error(), "已离线") ||- !strings.Contains(err.Error(), "Claude Code 拒绝了你的 API Key") || keyAttempts != 2 {+ !strings.Contains(err.Error(), assistantEngineLabel(cliEngine)+" 拒绝了你的 API Key") || keyAttempts != 2 {t.Fatalf("offline fallback with rejected key = %v, attempts = %d", err, keyAttempts)}diff --git a/internal/repo/runner_store_test.go b/internal/repo/runner_store_test.goindex fcdfca20..bf4dc921 100644--- a/internal/repo/runner_store_test.go+++ b/internal/repo/runner_store_test.go@@ -108,6 +108,26 @@ func TestAgentCLIHeartbeatForcesPersonalAuth(t *testing.T) {}}+func TestAntigravityHeartbeatPreservesSelectedAuthentication(t *testing.T) {+ s := newTestRunner(t)+ now := time.Now().UTC()+ if err := s.PutRunner(domain.Runner{ID: "agy-auth", Status: domain.RunnerStatusOnline, Runtimes: []domain.RunnerRuntime{{Provider: "agy", Status: domain.RuntimeStatusOnline}}}); err != nil {+ t.Fatal(err)+ }+ for _, mode := range []string{domain.RuntimeAuthLocal, domain.RuntimeAuthPersonal} {+ if err := s.SetRunnerRuntimeAuthMode("agy-auth", "agy", mode, now); err != nil {+ t.Fatal(err)+ }+ if err := s.RunnerHeartbeat("agy-auth", []domain.RunnerRuntime{{Provider: "agy", Status: domain.RuntimeStatusOnline}}, "1", now, now.Add(time.Hour)); err != nil {+ t.Fatal(err)+ }+ runner, _ := s.Runner("agy-auth")+ if runner.RuntimeAuthMode("agy") != mode || runner.Runtimes[0].AuthMode != mode {+ t.Fatalf("selected authentication changed: %+v", runner.Runtimes)+ }+ }+}+func TestRunnerTaskClaimRespectsProviderAndTargeting(t *testing.T) {s := newTestRunner(t)putQueuedTask(t, s, "rt-codex", "codex", "", 0)diff --git a/internal/repo/runners.go b/internal/repo/runners.goindex 3cadd1d2..7b3a20bc 100644--- a/internal/repo/runners.go+++ b/internal/repo/runners.go@@ -316,7 +316,7 @@ func (r *RunnersRepo) RunnerHeartbeat(id string, runtimes []domain.RunnerRuntimeif disabled[runtimes[i].Provider] {runtimes[i].Status = domain.RuntimeStatusDisabled}- if domain.IsAgentCLIKind(runtimes[i].Provider) {+ if domain.IsAgentCLIKind(runtimes[i].Provider) && !domain.SupportsRunnerLogin(runtimes[i].Provider) {runtimes[i].AuthMode = domain.RuntimeAuthPersonal} else if mode := authModes[runtimes[i].Provider]; mode != "" {runtimes[i].AuthMode = mode@@ -357,7 +357,7 @@ func (r *RunnersRepo) SetRunnerRuntimeAuthMode(runnerID, provider, authMode striif strings.EqualFold(provider, "codebuddy") && authMode != domain.RuntimeAuthPersonal {return fmt.Errorf("CodeBuddy 仅支持个人凭证")}- if domain.IsAgentCLIKind(provider) && authMode != domain.RuntimeAuthPersonal {+ if domain.IsAgentCLIKind(provider) && !domain.SupportsRunnerLogin(provider) && authMode != domain.RuntimeAuthPersonal {return fmt.Errorf("%s 仅支持个人凭证", provider)}return r.updateRunnerRuntimes(runnerID, func(runtimes []domain.RunnerRuntime) (bool, error) {diff --git a/internal/runner/cli_auth_sandbox_test.go b/internal/runner/cli_auth_sandbox_test.goindex 370fa9ba..00540528 100644--- a/internal/runner/cli_auth_sandbox_test.go+++ b/internal/runner/cli_auth_sandbox_test.go@@ -201,6 +201,11 @@ func TestRunnerSOPCLIAuthentication(t *testing.T) {}user, _ := st.UserByLoginName("cli-auth-test")row.OwnerUserID = user.ID+ for i := range row.Runtimes {+ if runtime.IsAgentCLI(row.Runtimes[i].Provider) {+ row.Runtimes[i].AuthMode = domain.RuntimeAuthPersonal+ }+ }if err := st.PutRunner(row); err != nil {t.Fatal(err)}diff --git a/internal/runner/daemon.go b/internal/runner/daemon.goindex e745c85e..d5cde58e 100644--- a/internal/runner/daemon.go+++ b/internal/runner/daemon.go@@ -885,9 +885,21 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask)return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}, nil}if runtime.IsAgentCLI(prepared.Command.Provider) {- cred := runtime.ProviderCredential{APIKey: inv.AgentCLIAPIKey, BaseURL: inv.AgentCLIBaseURL, Protocol: inv.AgentCLIProtocol, Models: inv.AgentCLIModels}var agentEnv map[string]string- argv, agentEnv, err = runtime.BindAgentCLICommand(sandbox, workspace, prepared.Command, cred, argv)+ if inv.CredentialSource == domain.RuntimeAuthLocal && domain.SupportsRunnerLogin(prepared.Command.Provider) {+ var cleanup func() error+ agentEnv, cleanup, err = runtime.PrepareRunnerAgentCLILogin(sandbox, prepared.Command)+ if cleanup != nil {+ defer func() {+ if err := cleanup(); err != nil {+ log.Printf("task %s: clean sandbox CLI login: %v", task.ID, err)+ }+ }()+ }+ } else {+ cred := runtime.ProviderCredential{APIKey: inv.AgentCLIAPIKey, BaseURL: inv.AgentCLIBaseURL, Protocol: inv.AgentCLIProtocol, Models: inv.AgentCLIModels}+ argv, agentEnv, err = runtime.BindAgentCLICommand(sandbox, workspace, prepared.Command, cred, argv)+ }if err != nil {return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}, nil}diff --git a/internal/runner/detect.go b/internal/runner/detect.goindex de5864a9..6022b593 100644--- a/internal/runner/detect.go+++ b/internal/runner/detect.go@@ -28,15 +28,15 @@ type providerSpec struct {}// defaultProviders lists the CLIs this runner drives in non-interactive-// mode. Runner tasks can reuse Codex or Claude Code's login. CodeBuddy tasks+// mode. Runner tasks can reuse Codex, Claude Code or Antigravity login. CodeBuddy tasks// receive the configured CODEBUDDY_API_KEY from the daemon. Additional// providers can be detected by name.var defaultProviders = []providerSpec{{Kind: "claude-code", Binary: "claude", Update: "update"},{Kind: "codex", Binary: "codex", Update: "update"},{Kind: "codebuddy", Binary: "codebuddy", Update: "update"},- // Agent CLIs (domain.AgentCLIExecutorKinds) always run with the- // responsible user's key in a private HOME. cursor and agy have no npm+ // Agent CLIs run in a private HOME. Antigravity can reuse account login;+ // the others receive the responsible user's key. cursor and agy have no npm// package and are found on PATH only.{Kind: "opencode", Binary: "opencode", Update: "upgrade"},{Kind: "cursor", Binary: "cursor-agent", Update: "update"},diff --git a/internal/runner/exec_edges_cases_test.go b/internal/runner/exec_edges_cases_test.goindex d0c9c9ef..5cf7df5d 100644--- a/internal/runner/exec_edges_cases_test.go+++ b/internal/runner/exec_edges_cases_test.go@@ -186,17 +186,23 @@ func TestRunSandboxKeysAndRequirements(t *testing.T) {Sandbox: &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{Driver: "docker"},Dockerfile: &dockerfile, Environment: &environment,- Requirements: &domain.RunnerSandboxRequirements{PrivateHome: true, BunFS: true, CLIStates: []domain.RunnerCLIStateRequirement{{Directory: ".x", Files: []string{"a"}}}},+ Requirements: &domain.RunnerSandboxRequirements{PrivateHome: true, BunFS: true, RunnerLoginRelay: true, CLIStates: []domain.RunnerCLIStateRequirement{{Directory: ".x", Files: []string{"a"}}}},},}requirements, resources := taskSandboxSpec(task)- if !requirements.PrivateHome || !requirements.BunFS || len(requirements.CLIStates) != 1 || resources.Dockerfile.ID != "d" || resources.Environment.ID != "e" {+ if !requirements.PrivateHome || !requirements.BunFS || !requirements.RunnerLoginRelay || len(requirements.CLIStates) != 1 || resources.Dockerfile.ID != "d" || resources.Environment.ID != "e" {t.Fatalf("requirements=%+v resources=%+v", requirements, resources)}key, id, shared := runSandboxKey(task, requirements, resources)if !shared || key == "" || !strings.HasPrefix(id, "rt-run-run-id-") {t.Fatalf("key=%q id=%q shared=%v", key, id, shared)}+ terminal := task+ terminal.Provider = "terminal"+ terminalRequirements, terminalResources := taskSandboxSpec(terminal)+ if terminalKey, _, _ := runSandboxKey(terminal, terminalRequirements, terminalResources); terminalKey != key {+ t.Fatal("terminal and Codex did not share the frozen relay network requirement")+ }task.Workspace = "other"if _, _, shared := runSandboxKey(task, requirements, resources); shared {t.Fatal("non-shared workspace shared")@@ -210,6 +216,9 @@ func TestRunSandboxKeysAndRequirements(t *testing.T) {if provider != "mock" && len(req.CLIStates) != 1 {t.Fatalf("%s req=%+v", provider, req)}+ if req.RunnerLoginRelay != (provider == "codex") {+ t.Fatalf("%s login relay=%v", provider, req.RunnerLoginRelay)+ }}if !sharedRunWorkspace("runs/r/workspace") || sharedRunWorkspace("runs/../workspace") || containerSafe("a/b") != "a-b" {t.Fatal("workspace/container helpers")diff --git a/internal/runner/run_sandbox.go b/internal/runner/run_sandbox.goindex 60fc670b..9cd04f29 100644--- a/internal/runner/run_sandbox.go+++ b/internal/runner/run_sandbox.go@@ -183,14 +183,22 @@ func taskSandboxSpec(task domain.RunnerTask) (runtime.SandboxRequirements, runtiif task.Sandbox.Environment != nil {resources.Environment = *task.Sandbox.Environment}+ // Tasks queued before RunnerLoginRelay was added still carry their auth mode.+ codexLoginRelay := task.Invocation != nil && task.Invocation.CredentialSource == domain.RuntimeAuthLocal &&+ task.Provider == "codex" && strings.TrimSpace(task.Sandbox.Profile.Driver) == domain.SandboxDriverDockerif frozen := task.Sandbox.Requirements; frozen != nil {- requirements := runtime.SandboxRequirements{PrivateHome: frozen.PrivateHome, BunFS: frozen.BunFS}+ requirements := runtime.SandboxRequirements{+ PrivateHome: frozen.PrivateHome,+ BunFS: frozen.BunFS,+ RunnerLoginRelay: frozen.RunnerLoginRelay || codexLoginRelay,+ }for _, state := range frozen.CLIStates {requirements.CLIStates = append(requirements.CLIStates, runtime.CLIStateRequirement{Directory: state.Directory, Files: append([]string(nil), state.Files...)})}return requirements, resources}requirements := runtime.ProviderRequirements(task.Provider)+ requirements.RunnerLoginRelay = codexLoginRelayif task.Invocation != nil && task.Invocation.CredentialSource != domain.RuntimeAuthPersonal {switch task.Provider {case "codex":diff --git a/internal/runner/run_sandbox_test.go b/internal/runner/run_sandbox_test.goindex a5caffb7..0fad0855 100644--- a/internal/runner/run_sandbox_test.go+++ b/internal/runner/run_sandbox_test.go@@ -2,12 +2,56 @@ package runnerimport ("context"+ "encoding/json""testing""time""agentflow/internal/domain")+func TestQueuedTaskWithLegacyRequirementsKeepsCodexLoginRelay(t *testing.T) {+ const queued = `{+ "id": "rt-queued", "runId": "run-queued", "workspace": "runs/run-queued/workspace",+ "provider": "codex", "invocation": {"credentialSource": "local"},+ "sandbox": {"profile": {"driver": "docker"}, "requirements": {"privateHome": true}}+ }`+ for _, tc := range []struct {+ name, provider, driver, authMode string+ wantRelay bool+ }{+ {name: "Docker Codex account login", provider: "codex", driver: "docker", authMode: domain.RuntimeAuthLocal, wantRelay: true},+ {name: "Docker Codex API key", provider: "codex", driver: "docker", authMode: domain.RuntimeAuthPersonal},+ {name: "native Codex account login", provider: "codex", driver: "native", authMode: domain.RuntimeAuthLocal},+ {name: "Docker Claude account login", provider: "claude-code", driver: "docker", authMode: domain.RuntimeAuthLocal},+ } {+ t.Run(tc.name, func(t *testing.T) {+ var task domain.RunnerTask+ if err := json.Unmarshal([]byte(queued), &task); err != nil {+ t.Fatal(err)+ }+ task.Provider = tc.provider+ task.Sandbox.Profile.Driver = tc.driver+ task.Invocation.CredentialSource = tc.authMode++ requirements, resources := taskSandboxSpec(task)+ if !requirements.PrivateHome || requirements.RunnerLoginRelay != tc.wantRelay {+ t.Fatalf("sandbox requirements = %+v, want private HOME and login relay %v", requirements, tc.wantRelay)+ }+ if task.Sandbox.Requirements.RunnerLoginRelay {+ t.Fatal("loading a task changed its saved requirements")+ }+ if tc.wantRelay {+ _, withRelay, _ := runSandboxKey(task, requirements, resources)+ requirements.RunnerLoginRelay = false+ _, withoutRelay, _ := runSandboxKey(task, requirements, resources)+ if withRelay == withoutRelay {+ t.Fatal("Codex login would reuse the container without the relay network")+ }+ }+ })+ }+}+func TestSharedRunTasksReuseOneSandboxUntilCleanup(t *testing.T) {d := &Daemon{cfg: Config{DefaultWorkspaceRoot: t.TempDir()}}task := func(id, runID, workspace, provider string) domain.RunnerTask {diff --git a/internal/runtime/agent_cli.go b/internal/runtime/agent_cli.goindex d91a032a..4a1b4705 100644--- a/internal/runtime/agent_cli.go+++ b/internal/runtime/agent_cli.go@@ -15,9 +15,9 @@ import ()// Agent CLIs beyond CodeBuddy / Codex / Claude Code. Each one runs with the-// responsible user's own key from 个人配置 inside a private HOME that also-// holds the CLI's MCP and model configuration, so neither the host login nor-// the host configuration leaks into a run.+// responsible user's credential inside a private HOME that also holds MCP+// and model configuration. Antigravity may explicitly reuse the machine+// owner's account login; other agent CLIs use a key from 个人配置.const (AgentCLIOpenCode = "opencode"AgentCLICursor = "cursor"@@ -98,6 +98,7 @@ const agentCLIKeyEnv = "AGENTFLOW_CLI_API_KEY"// the host's own login, key, gateway or configuration directory.var agentCLIHostEnv = append([]string{agentCLIKeyEnv, "CURSOR_API_KEY", "CURSOR_AUTH_TOKEN", "GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_BASE_URL", "GEMINI_BASE_URL",+ "AGY_ADC_AUTH", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_GENAI_USE_VERTEXAI", "GEMINI_HOME", "AGY_ACP_FORCE_FILE_STORAGE","AGY_LLM_GATEWAY_URL", "AGY_LLM_GATEWAY_API_KEY", "AGY_LLM_GATEWAY_WIRE_PROTOCOL", "AGY_LLM_GATEWAY_MODELS","DEEPSEEK_API_KEY", "DSH_HOME", "MOONSHOT_API_KEY", "KIMI_API_KEY", "KIMI_BASE_URL", "KIMI_CODE_HOME","KIMI_MODEL_NAME", "KIMI_MODEL_API_KEY", "KIMI_MODEL_BASE_URL", "KIMI_MODEL_PROVIDER_TYPE",@@ -375,6 +376,14 @@ func ApplyAgentCLICredential(kind string, cred ProviderCredential, options Agentif key == "" {return nil, nil, fmt.Errorf("需求责任人未配置 %s API Key,请在个人配置中配置", AgentCLILabel(kind))}+ if kind == AgentCLIAntigravity {+ // A crashed account-login invocation may leave a credential copy.+ // API-key execution must not retain or inherit that account.+ login, _ := runnerLoginSpec(kind)+ if _, _, err := prepareRunnerLogin(home, login, false); err != nil {+ return nil, nil, err+ }+ }baseURL := strings.TrimRight(strings.TrimSpace(cred.BaseURL), "/")protocol := AgentCLIProtocol(kind, cred.Protocol)if baseURL == "" && AgentCLINeedsBaseURL(kind, protocol) {diff --git a/internal/runtime/claude_install.go b/internal/runtime/claude_install.goindex 7447845f..ae06ae65 100644--- a/internal/runtime/claude_install.go+++ b/internal/runtime/claude_install.go@@ -14,7 +14,7 @@ import (// ClaudeCodeVersion is installed from npm on first use. Published platform// images do not redistribute Claude Code, so each installation downloads it// from Anthropic's registry package itself.-const ClaudeCodeVersion = "2.1.300"+const ClaudeCodeVersion = "2.1.326"var claudeInstallMu sync.Mutexdiff --git a/internal/runtime/conversation_login_models.go b/internal/runtime/conversation_login_models.goindex fc887cd5..e4d19e28 100644--- a/internal/runtime/conversation_login_models.go+++ b/internal/runtime/conversation_login_models.go@@ -6,6 +6,7 @@ import ("encoding/json""fmt""io"+ "log""os""os/exec""path/filepath"@@ -27,12 +28,22 @@ func DiscoverRunnerLoginModels(ctx context.Context, provider, binary string) ([]return nil, fmt.Errorf("无法创建模型查询目录")}defer os.RemoveAll(root)- _, loginEnv, err := prepareConversationRunnerLogin(root, login, true)+ cleanup, loginEnv, err := prepareConversationRunnerLogin(root, login, true)if err != nil {return nil, err}+ if cleanup != nil {+ defer func() {+ if err := cleanup(); err != nil {+ log.Printf("runner login models: cleanup %s: %v", login.label, err)+ }+ }()+ }home := filepath.Join(root, "home")- env := map[string]string{login.configEnv: filepath.Join(home, login.dir), "NO_COLOR": "1", "CI": "1"}+ env := map[string]string{"NO_COLOR": "1", "CI": "1"}+ if login.configEnv != "" {+ env[login.configEnv] = filepath.Join(home, login.dir)+ }for _, key := range []string{"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS"} {if value, ok := os.LookupEnv(key); ok {env[key] = value@@ -47,6 +58,19 @@ func DiscoverRunnerLoginModels(ctx context.Context, provider, binary string) ([]ctx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()environment := appendEnvironment(terminalBaseEnvironment(home), env, loginEnv)+ if provider == AgentCLIAntigravity {+ cmd := exec.CommandContext(ctx, binary, "models")+ cmd.Dir, cmd.Env, cmd.WaitDelay = root, environment, time.Second+ output, err := cmd.Output()+ if err != nil || len(output) > 2<<20 {+ return nil, fmt.Errorf("Antigravity 无法返回账号模型,请检查执行机器上的 CLI 版本和登录状态")+ }+ models := antigravityLoginModels(string(output))+ if len(models) == 0 {+ return nil, fmt.Errorf("Antigravity 未返回可用的账号模型")+ }+ return models, nil+ }if login.binding == BindClaudeCode {status := exec.CommandContext(ctx, binary, "auth", "status")status.Dir, status.Env, status.WaitDelay = root, environment, time.Second@@ -93,6 +117,20 @@ func DiscoverRunnerLoginModels(ctx context.Context, provider, binary string) ([]return models, nil}+func antigravityLoginModels(output string) []domain.CLIModel {+ var models []domain.CLIModel+ seen := map[string]bool{}+ for _, line := range strings.Split(output, "\n") {+ id, name, found := strings.Cut(strings.TrimSpace(line), "\t")+ if !found || id == "" || strings.ContainsAny(id, " \r\n") || seen[id] {+ continue+ }+ seen[id] = true+ models = append(models, domain.CLIModel{ID: id, Name: strings.TrimSpace(name)})+ }+ return models+}+func codexLoginModels(send *json.Encoder, scanner *bufio.Scanner) []domain.CLIModel {if send.Encode(map[string]any{"id": 1, "method": "initialize",diff --git a/internal/runtime/conversation_process.go b/internal/runtime/conversation_process.goindex 4ed4bcc9..c85c02fd 100644--- a/internal/runtime/conversation_process.go+++ b/internal/runtime/conversation_process.go@@ -628,7 +628,7 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace strreturn ConversationProcessResult{}, fmt.Errorf("该 CLI 不支持使用执行机器的本机登录")}if supported {- cleanupLogin, localEnv, err = prepareConversationRunnerLogin(root, login, req.Command.RunnerLogin)+ cleanupLogin, localEnv, err = prepareConversationRunnerLogin(root, login, req.Command.RunnerLogin, spec != nil && spec.Profile.Driver == domain.SandboxDriverDocker)if err != nil {return ConversationProcessResult{}, err}@@ -636,6 +636,10 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace strcommand.CredentialBindings = slices.DeleteFunc(slices.Clone(command.CredentialBindings), func(binding CredentialBinding) bool {return binding == login.binding})+ if command.Provider == AgentCLIAntigravity && command.AgentCLI.ReadOnly {+ settings, _ := json.Marshal(map[string]any{"permissions": agyChatPermissions})+ command.Argv = insertBeforeFlag(command.Argv, "-p", "--settings", string(settings))+ }}}nativeArgv := append([]string(nil), command.Argv...)diff --git a/internal/runtime/conversation_runner_login.go b/internal/runtime/conversation_runner_login.goindex 08ef227f..f28b44cf 100644--- a/internal/runtime/conversation_runner_login.go+++ b/internal/runtime/conversation_runner_login.go@@ -2,6 +2,7 @@ package runtimeimport ("bytes"+ "context""crypto/sha256""encoding/json""errors"@@ -10,8 +11,8 @@ import ("log""os""path/filepath"- "slices""strings"+ "time")type conversationLoginSpec struct {@@ -25,6 +26,8 @@ func runnerLoginSpec(provider string) (conversationLoginSpec, bool) {return conversationLoginSpec{"Codex", ".codex", "auth.json", "CODEX_HOME", BindCodex}, truecase "claude-code":return conversationLoginSpec{"Claude Code", ".claude", ".credentials.json", "CLAUDE_CONFIG_DIR", BindClaudeCode}, true+ case AgentCLIAntigravity:+ return conversationLoginSpec{"Antigravity", ".gemini/antigravity-cli", "antigravity-oauth-token", "", BindAgentCLI}, truedefault:return conversationLoginSpec{}, false}@@ -33,8 +36,8 @@ func runnerLoginSpec(provider string) (conversationLoginSpec, bool) {// Copy only the native CLI's login file into its isolated conversation home.// This runs on the executing machine. The file never goes through the control// connection or enters the synchronized asset set.-func prepareConversationRunnerLogin(root string, login conversationLoginSpec, enabled bool) (func() error, map[string]string, error) {- return prepareRunnerLogin(AgentCLIHome{Base: root, Rel: "home"}, login, enabled)+func prepareConversationRunnerLogin(root string, login conversationLoginSpec, enabled bool, docker ...bool) (func() error, map[string]string, error) {+ return prepareRunnerLogin(AgentCLIHome{Base: root, Rel: "home"}, login, enabled, docker...)}// PrepareRunnerSandboxLogin stages the selected CLI's login in the node's@@ -47,7 +50,7 @@ func PrepareRunnerSandboxLogin(sandbox Sandbox, provider, runID, nodeID string)}scope := sha256.Sum256([]byte(runID + "\x00" + nodeID))home := WorkspaceAgentCLIHome(sandbox.Workspace(), fmt.Sprintf("%s-login-%x", provider, scope[:12]))- cleanup, env, err := prepareRunnerLogin(home, login, true)+ cleanup, env, err := prepareRunnerLogin(home, login, true, sandboxDriver(sandbox) == "docker")if err != nil {if cleanup != nil {err = errors.Join(err, cleanup())@@ -62,11 +65,44 @@ func PrepareRunnerSandboxLogin(sandbox Sandbox, provider, runID, nodeID string)homePath = filepath.ToSlash(filepath.Join("/workspace", home.Rel))}env["HOME"] = homePath- env[login.configEnv] = filepath.ToSlash(filepath.Join(homePath, login.dir))+ if login.configEnv != "" {+ env[login.configEnv] = filepath.ToSlash(filepath.Join(homePath, login.dir))+ }+ return env, cleanup, nil+}++// Agent CLIs keep MCP and session configuration in the agent's existing HOME.+// Stage account authentication there rather than replacing that HOME.+func PrepareRunnerAgentCLILogin(sandbox Sandbox, command CommandSpec) (map[string]string, func() error, error) {+ login, supported := runnerLoginSpec(command.Provider)+ if !supported || !IsAgentCLI(command.Provider) {+ return nil, nil, fmt.Errorf("该 CLI 不支持使用执行机器的本机登录")+ }+ home := WorkspaceAgentCLIHome(sandbox.Workspace(), PrivateHomeName(command))+ cleanup, env, err := prepareRunnerLogin(home, login, true)+ if err != nil {+ if cleanup != nil {+ err = errors.Join(err, cleanup())+ }+ return nil, nil, err+ }+ _, homeEnv := privateHomePaths(sandbox, sandbox.Workspace(), command)+ env["HOME"] = homeEnv+ tmp, err := EnsureControlDirectory(sandbox.Workspace(), "tmp", PrivateHomeName(command))+ if err != nil {+ if cleanup != nil {+ err = errors.Join(err, cleanup())+ }+ return nil, nil, err+ }+ env["TMPDIR"] = tmp+ if sandboxDriver(sandbox) == "docker" {+ env["TMPDIR"] = filepath.ToSlash(filepath.Join("/workspace", ".agentflow", "tmp", PrivateHomeName(command)))+ }return env, cleanup, nil}-func prepareRunnerLogin(home AgentCLIHome, login conversationLoginSpec, enabled bool) (func() error, map[string]string, error) {+func prepareRunnerLogin(home AgentCLIHome, login conversationLoginSpec, enabled bool, docker ...bool) (func() error, map[string]string, error) {home.Rel = filepath.Join(home.Rel, login.dir)target, err := openAgentCLIHome(home)if err != nil {@@ -99,27 +135,94 @@ func prepareRunnerLogin(home AgentCLIHome, login conversationLoginSpec, enabledconfigDir = filepath.Join(base, login.dir)}}- data, err := readRunnerLoginFile(configDir, login.file)+ var data []byte+ var keepAntigravity func([]byte) error+ if login.binding == BindAgentCLI {+ data, keepAntigravity, err = readAntigravityRunnerLogin()+ } else {+ data, err = readRunnerLoginFile(configDir, login.file)+ }if err != nil {return nil, nil, fmt.Errorf("执行机器上的 %s 本机登录态不可用,请检查 Runner 账户的 CLI 登录", login.label)}+ if login.binding == BindCodex || login.binding == BindClaudeCode {+ source := fileRunnerLoginSource(login, configDir)+ if _, parseErr := parseRunnerOAuth(source.provider, data); parseErr == nil {+ ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)+ defer cancel()+ lease, leaseErr := newRunnerLoginLease(ctx, nativeRunnerLogins, source, len(docker) > 0 && docker[0])+ if leaseErr != nil {+ return nil, nil, fmt.Errorf("执行机器上的 %s 登录暂时无法续期:%w", login.label, leaseErr)+ }+ credential, credentialErr := lease.credential()+ if credentialErr == nil {+ credentialErr = target.WriteFile(login.file, credential, 0600)+ }+ if credentialErr != nil {+ lease.close()+ return nil, nil, credentialErr+ }+ return func() error {+ lease.close()+ dir, err := openAgentCLIHome(home)+ if err != nil {+ return err+ }+ defer dir.Close()+ // Only the trusted refresh manager can update the host login.+ return remove(dir)+ }, lease.environment(), nil+ }+ var incomplete struct {+ Codex struct {+ Refresh string `json:"refresh_token"`+ } `json:"tokens"`+ Claude struct {+ Refresh string `json:"refreshToken"`+ } `json:"claudeAiOauth"`+ }+ _ = json.Unmarshal(data, &incomplete)+ if incomplete.Codex.Refresh != "" || incomplete.Claude.Refresh != "" {+ return nil, nil, fmt.Errorf("执行机器上的 %s OAuth 凭证不完整,请重新登录 CLI", login.label)+ }+ }cleanup := func() error {dir, err := openAgentCLIHome(home)if err != nil {return err}defer dir.Close()- // Codex and Claude Code rotate refresh tokens: a refresh inside the- // sandbox invalidates the host's copy, so keep the refreshed login- // before the copy is removed.- if err := writeBackRefreshedLogin(dir, login, configDir, data); err != nil {- log.Printf("runner login: keep refreshed %s login: %v", login.label, err)+ // Only Antigravity's verified, stable-refresh-token flow accepts sandbox+ // updates. Other edited files are never promoted to host credentials.+ var keepErr error+ if keepAntigravity != nil {+ if refreshed, err := readRootLoginFile(dir, login.file); err == nil {+ keepErr = keepAntigravity(refreshed)+ }+ } else {+ keepErr = writeBackRefreshedLogin(dir, login, configDir, data)+ }+ if keepErr != nil {+ log.Printf("runner login: keep refreshed %s login: %v", login.label, keepErr)}return remove(dir)}if err := target.WriteFile(login.file, data, 0600); err != nil {return cleanup, nil, fmt.Errorf("无法准备 %s 的本机登录态", login.label)}+ if login.binding == BindAgentCLI {+ // The official CLI selects file storage in remote sessions. This also+ // prevents a sandbox from trying to open the host's OS credential store.+ env := map[string]string{"SSH_CONNECTION": "127.0.0.1 0 127.0.0.1 0"}+ for _, key := range agentCLIHostEnv {+ env[key] = ""+ }+ // A prior API-key turn may have selected the direct Gemini API.+ if err := target.WriteFile("settings.json", []byte("{}"), 0600); err != nil {+ return cleanup, nil, fmt.Errorf("无法准备 Antigravity 的账号登录配置")+ }+ return cleanup, env, nil+ }return cleanup, nil, nil}@@ -151,38 +254,31 @@ func readRunnerLoginFile(dir, name string) ([]byte, error) {return data, nil}-// writeBackRefreshedLogin copies a login the CLI refreshed in its isolated home-// back to the Runner account's file. It is a compare-and-swap on content: the-// host file must still be the one copied in (otherwise the host CLI or another-// session refreshed it first and stays authoritative), and the refreshed file-// must be the same kind of login (same top-level fields and, for Codex, the-// same account) so a sandboxed agent cannot swap in another account.+// Unmanaged/static login copies cannot replace a host credential. OAuth pairs+// are refreshed by the trusted manager; sandbox JSON is never an issuer response.func writeBackRefreshedLogin(dir *os.Root, login conversationLoginSpec, configDir string, original []byte) error {refreshed, err := readRootLoginFile(dir, login.file)if err != nil || bytes.Equal(refreshed, original) {return nil}- if !sameRunnerLogin(original, refreshed) {- return fmt.Errorf("refreshed login does not match the original account; not written back")- }+ return fmt.Errorf("sandbox login changes cannot replace Runner credentials")+}++func replaceRunnerLoginFile(configDir, name string, original, refreshed []byte) error {if configDir == "" {return nil}- path := filepath.Join(configDir, login.file)- current, err := readRunnerLoginFile(configDir, login.file)+ path := filepath.Join(configDir, name)+ current, err := readRunnerLoginFile(configDir, name)if err != nil || !bytes.Equal(current, original) {return nil}- info, err := os.Stat(path)- if err != nil {- return err- }- tmp, err := os.CreateTemp(configDir, "."+login.file+".refresh-*")+ tmp, err := os.CreateTemp(configDir, "."+name+".refresh-*")if err != nil {return err}defer os.Remove(tmp.Name())- if err := tmp.Chmod(info.Mode().Perm()); err != nil {+ if err := tmp.Chmod(0600); err != nil {tmp.Close()return err}@@ -199,10 +295,18 @@ func writeBackRefreshedLogin(dir *os.Root, login conversationLoginSpec, configDi}// Re-check right before the swap to keep the window with a concurrent// host refresh as small as possible.- if current, err := readRunnerLoginFile(configDir, login.file); err != nil || !bytes.Equal(current, original) {+ if current, err := readRunnerLoginFile(configDir, name); err != nil || !bytes.Equal(current, original) {return nil}- return os.Rename(tmp.Name(), path)+ if err := os.Rename(tmp.Name(), path); err != nil {+ return err+ }+ dir, err := os.Open(configDir)+ if err != nil {+ return err+ }+ defer dir.Close()+ return dir.Sync()}// readRootLoginFile reads the login file below the isolated home through@@ -230,29 +334,3 @@ func readRootLoginFile(dir *os.Root, name string) ([]byte, error) {}return data, nil}--func sameRunnerLogin(original, refreshed []byte) bool {- var before, after map[string]json.RawMessage- if json.Unmarshal(original, &before) != nil || json.Unmarshal(refreshed, &after) != nil {- return false- }- keys := func(m map[string]json.RawMessage) []string {- out := make([]string, 0, len(m))- for key := range m {- out = append(out, key)- }- slices.Sort(out)- return out- }- if !slices.Equal(keys(before), keys(after)) {- return false- }- account := func(m map[string]json.RawMessage) string {- var tokens struct {- AccountID string `json:"account_id"`- }- _ = json.Unmarshal(m["tokens"], &tokens)- return tokens.AccountID- }- return account(before) == account(after)-}diff --git a/internal/runtime/conversation_runner_login_refresh_test.go b/internal/runtime/conversation_runner_login_refresh_test.goindex 3eeb1208..846d220f 100644--- a/internal/runtime/conversation_runner_login_refresh_test.go+++ b/internal/runtime/conversation_runner_login_refresh_test.go@@ -9,18 +9,17 @@ import ("time")-// A CLI that refreshes its rotating OAuth token inside the isolated home must-// not leave the Runner account with an invalidated refresh token: the cleanup-// writes the refreshed login back unless the host changed meanwhile or the-// refreshed file is a different account.-func TestRunnerLoginWritesBackRefreshedToken(t *testing.T) {- const original = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","refresh_token":"r1"},"last_refresh":"2026-11-01"}`- const refreshed = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","refresh_token":"r2"},"last_refresh":"2026-11-17"}`+// Sandbox file edits are not trusted issuer responses, even if an account ID+// matches. Managed renewal is exercised through the host manager separately.+func TestRunnerLoginRejectsSandboxTokenEdits(t *testing.T) {+ const original = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","access_token":"fake-access","refresh_token":"r1"},"last_refresh":"2026-11-01"}`+ const refreshed = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","access_token":"fake-access","refresh_token":"r2"},"last_refresh":"2026-11-17"}`setup := func(t *testing.T) (conversationLoginSpec, string, string, func() error) {t.Helper()login, _ := runnerLoginSpec("codex")host := t.TempDir()t.Setenv(login.configEnv, host)+ t.Setenv("AGENTFLOW_RUNNER_AUTH_DIR", t.TempDir())if err := os.WriteFile(filepath.Join(host, login.file), []byte(original), 0o600); err != nil {t.Fatal(err)}@@ -48,8 +47,8 @@ func TestRunnerLoginWritesBackRefreshedToken(t *testing.T) {if err := cleanup(); err != nil {t.Fatal(err)}- if got := read(t, filepath.Join(host, login.file)); got != refreshed {- t.Fatalf("host login = %s, want the refreshed one", got)+ if got := read(t, filepath.Join(host, login.file)); got != original {+ t.Fatal("sandbox-edited token reached the host")}if info, _ := os.Stat(filepath.Join(host, login.file)); info.Mode().Perm() != 0o600 {t.Fatalf("host login mode = %v", info.Mode().Perm())@@ -75,7 +74,7 @@ func TestRunnerLoginWritesBackRefreshedToken(t *testing.T) {})t.Run("host refreshed first", func(t *testing.T) {login, host, copy, cleanup := setup(t)- const hostRefresh = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","refresh_token":"host"},"last_refresh":"2026-11-17"}`+ const hostRefresh = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","access_token":"fake-access","refresh_token":"host"},"last_refresh":"2026-11-17"}`if err := os.WriteFile(filepath.Join(host, login.file), []byte(hostRefresh), 0o600); err != nil {t.Fatal(err)}@@ -122,15 +121,15 @@ func TestRunnerLoginWritesBackRefreshedToken(t *testing.T) {})}-// The conversation process pool (the Runner's path) keeps a login the CLI-// refreshed while it ran.-func TestConversationRunnerLoginKeepsRefreshThroughProcessPool(t *testing.T) {+// The conversation process pool must not promote arbitrary file replacements.+func TestConversationRunnerLoginRejectsEditsThroughProcessPool(t *testing.T) {login, _ := runnerLoginSpec("codex")host := t.TempDir()t.Setenv(login.configEnv, host)+ t.Setenv("AGENTFLOW_RUNNER_AUTH_DIR", t.TempDir())t.Setenv("OPENAI_API_KEY", "")- const original = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","refresh_token":"r1"}}`- const refreshed = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","refresh_token":"r2"}}`+ const original = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","access_token":"fake-access","refresh_token":"r1"}}`+ const refreshed = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","access_token":"fake-access","refresh_token":"r2"}}`if err := os.WriteFile(filepath.Join(host, login.file), []byte(original), 0o600); err != nil {t.Fatal(err)}@@ -157,7 +156,7 @@ func TestConversationRunnerLoginKeepsRefreshThroughProcessPool(t *testing.T) {t.Fatalf("isolated copy was not removed: %v", err)}data, err := os.ReadFile(filepath.Join(host, login.file))- if err != nil || string(data) != refreshed {- t.Fatalf("host login = %s, %v; want the refreshed login", data, err)+ if err != nil || string(data) != original {+ t.Fatal("sandbox file edit replaced the host login")}}diff --git a/internal/runtime/docker_cases_test.go b/internal/runtime/docker_cases_test.goindex 07125108..fb2ad564 100644--- a/internal/runtime/docker_cases_test.go+++ b/internal/runtime/docker_cases_test.go@@ -43,10 +43,28 @@ func TestDockerSandboxLifecycleWithFakeCLI(t *testing.T) {if sb.ID() != "cvR-run" || sb.Workspace() != workspace || sb.Driver() != "docker" {t.Fatalf("sandbox=%+v", sb)}- out, err := sb.Exec(context.Background(), CommandSpec{Argv: []string{"sh", "-lc", "echo ok"}, environment: map[string]string{"B": "2"}}, nil)+ const extraValue = "test-extra-credential"+ command, err := bindCommand(sb, workspace, CommandSpec{+ Argv: []string{"sh", "-lc", "echo ok"},+ CredentialBindings: []CredentialBinding{BindExtra},+ ExtraCredentialEnv: map[string]string{"DEPLOYMENT_VALUE": "registry"},+ environment: map[string]string{"B": "2"},+ }, RunCredentials{Extra: map[string]string{"registry": extraValue}})+ if err != nil {+ t.Fatal(err)+ }+ var started string+ out, err := sb.Exec(context.Background(), command, func(event domain.TelemetryEvent) {+ if event.Name == "process.started" {+ started = event.Message+ }+ })if err != nil || !strings.Contains(out, "/workspace") {t.Fatalf("exec=%q err=%v", out, err)}+ if strings.Contains(started, extraValue) || !strings.Contains(started, "DEPLOYMENT_VALUE=<redacted>") || !strings.Contains(started, "B=2") {+ t.Fatalf("process.started must redact the extra credential and keep ordinary environment variables: %q", started)+ }if !sb.started || sb.builtImage == "" {t.Fatalf("sandbox did not start: %+v", sb)}@@ -65,6 +83,61 @@ func TestDockerSandboxLifecycleWithFakeCLI(t *testing.T) {}}+func TestDockerSandboxUsesRelayNetworkOnlyWhenRequested(t *testing.T) {+ for _, tc := range []struct {+ name string+ privateHome bool+ conversation bool+ runnerLoginRelay bool+ invalidRelayConfig bool+ wantNetwork string+ }{+ {name: "SOP with private home", privateHome: true, wantNetwork: "sop-network"},+ {name: "SOP ignores invalid conversation settings", privateHome: true, invalidRelayConfig: true, wantNetwork: "sop-network"},+ {name: "conversation", conversation: true, wantNetwork: "chat-network"},+ {name: "Codex login relay", runnerLoginRelay: true, wantNetwork: "chat-network"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ workspace := t.TempDir()+ cvRInstallFakeDocker(t, workspace)+ argsFile := filepath.Join(t.TempDir(), "create-args")+ t.Setenv("CVR_DOCKER_CREATE_ARGS", argsFile)+ t.Setenv("AGENTFLOW_DOCKER_NETWORK", "sop-network")+ t.Setenv("AGENTFLOW_CONVERSATION_DOCKER_NETWORK", "chat-network")+ host := "host.docker.internal"+ if tc.invalidRelayConfig {+ host = "invalid/relay"+ }+ t.Setenv("AGENTFLOW_CONVERSATION_RELAY_HOST", host)+ requirements := SandboxRequirements{PrivateHome: tc.privateHome, RunnerLoginRelay: tc.runnerLoginRelay}+ if tc.conversation {+ requirements.ConversationRoot = t.TempDir()+ }+ ctx := context.Background()+ sandbox, err := createDocker(ctx, "network-policy", workspace, domain.SandboxProfile{Driver: "docker"}, requirements, domain.DockerfileDefinition{Content: "FROM scratch"})+ if err != nil {+ t.Fatal(err)+ }+ defer sandbox.Close(ctx)+ if err := sandbox.(*dockerSandbox).BindWorkspace(ctx); err != nil {+ t.Fatal(err)+ }+ data, err := os.ReadFile(argsFile)+ if err != nil {+ t.Fatal(err)+ }+ args := string(data)+ if strings.Count(args, "\n--network\n") != 1 || !strings.Contains(args, "\n--network\n"+tc.wantNetwork+"\n") {+ t.Fatalf("docker create used the wrong network: %s", args)+ }+ usesGateway := strings.Contains(args, "\n--add-host\nhost.docker.internal:host-gateway\n")+ if usesGateway != (tc.conversation || tc.runnerLoginRelay) {+ t.Fatalf("docker create host gateway = %v for %s", usesGateway, tc.name)+ }+ })+ }+}+func TestDockerDiscoveryImagesAndBuildHelpers(t *testing.T) {workspace := t.TempDir()cvRInstallFakeDocker(t, workspace)@@ -306,6 +379,9 @@ case "$*" in"ps -aq --filter "*) echo id1; exit 0 ;;"inspect "*) exit 1 ;;"exec "*) echo /workspace; exit 0 ;;+ "create "*)+ if [ -n "${CVR_DOCKER_CREATE_ARGS:-}" ]; then printf '%s\n' "$@" > "$CVR_DOCKER_CREATE_ARGS"; fi+ exit 0 ;;*) exit 0 ;;esac`diff --git a/internal/runtime/process.go b/internal/runtime/process.goindex 54be43a7..5be912f1 100644--- a/internal/runtime/process.go+++ b/internal/runtime/process.go@@ -16,14 +16,28 @@ const processWaitDelay = time.Secondvar errProcessNotStarted = errors.New("process was not started")-// runCommand waits for cmd and streams process telemetry. credentialEnvKeys-// names environment variables populated from Extra credentials; their values-// are redacted from the process.started command line by origin, so arbitrary-// names (for example AWS_SECRET_ACCESS_KEY) never rely on naming conventions.-func runCommand(cmd *exec.Cmd, sink EventSink, credentialEnvKeys ...string) (string, error) {+// runCommand streams process telemetry, coordinating the Claude login callback+// and redacting bound credential environment values from process.started.+func runCommand(cmd *exec.Cmd, sink EventSink, commands ...CommandSpec) (string, error) {+ var command CommandSpec+ if len(commands) > 0 {+ command = commands[0]+ }+ var bridge *claudeLoginBridge+ if isManagedClaude(command) {+ var err error+ bridge, err = newClaudeLoginBridge(cmd, command)+ if err != nil {+ return "", fmt.Errorf("%w: %w", errProcessNotStarted, err)+ }+ defer bridge.close()+ }var buf bytes.Buffervar mu sync.Mutexstdout := &processWriter{output: &buf, mu: &mu, sink: sink, name: "process.stdout", level: "info"}+ if bridge != nil {+ stdout.filter = bridge.filter+ }stderr := &processWriter{output: &buf, mu: &mu, sink: sink, name: "process.stderr", level: "error"}cmd.Stdout, cmd.Stderr = stdout, stderr// When hooks spawn detached children that inherit stdout/stderr, bound how@@ -38,10 +52,13 @@ func runCommand(cmd *exec.Cmd, sink EventSink, credentialEnvKeys ...string) (strmu.Lock()err := cmd.Start()if err == nil && sink != nil {- sink(domain.TelemetryEvent{Category: "process", Name: "process.started", Timestamp: time.Now().UTC(), Phase: "start", Message: compactCommand(cmd.Args, credentialEnvKeys...), Attributes: map[string]any{"pid": cmd.Process.Pid}})+ sink(domain.TelemetryEvent{Category: "process", Name: "process.started", Timestamp: time.Now().UTC(), Phase: "start", Message: compactCommand(cmd.Args, command.credentialEnvKeys...), Attributes: map[string]any{"pid": cmd.Process.Pid}})}mu.Unlock()if err == nil {+ if bridge != nil {+ bridge.start()+ }err = cmd.Wait()} else if sink != nil {sink(domain.TelemetryEvent{Category: "process", Name: "process.start_failed", Timestamp: time.Now().UTC(), Phase: "start", Level: "error", Message: err.Error()})@@ -63,6 +80,9 @@ func runCommand(cmd *exec.Cmd, sink EventSink, credentialEnvKeys ...string) (str}stdout.flush()stderr.flush()+ if bridge != nil && bridge.result() != nil {+ err = bridge.result()+ }if sink != nil {phase, level := "finish", "info"if err != nil {@@ -85,6 +105,7 @@ func runCommand(cmd *exec.Cmd, sink EventSink, credentialEnvKeys ...string) (str}type processWriter struct {+ filter func(string) booloutput *bytes.Buffermu *sync.Mutexsink EventSink@@ -126,6 +147,9 @@ func (w *processWriter) emitLines(includePartial bool) {}func (w *processWriter) emit(line string) {+ if w.filter != nil && !w.filter(line) {+ return+ }w.output.WriteString(line)w.output.WriteByte('\n')if w.sink != nil {@@ -168,6 +192,9 @@ func compactCommand(args []string, credentialEnvKeys ...string) string {// newly added agent CLI is redacted without being listed here.func sensitiveProcessEnvironmentKey(key string) bool {key = strings.ToUpper(key)+ if key == "CODEX_REFRESH_TOKEN_URL_OVERRIDE" {+ return true+ }for _, suffix := range []string{"_API_KEY", "_TOKEN", "_SECRET", "_PASSWORD"} {if strings.HasSuffix(key, suffix) {return truediff --git a/internal/runtime/provider.go b/internal/runtime/provider.goindex 38df8dfd..0d5fbcc2 100644--- a/internal/runtime/provider.go+++ b/internal/runtime/provider.go@@ -15,6 +15,8 @@ type SandboxRequirements struct {CLIStates []CLIStateRequirementPrivateHome boolBunFS bool+ // RunnerLoginRelay allows Docker Codex account login to reach the host refresh listener.+ RunnerLoginRelay bool `json:",omitempty"`}type CLIStateRequirement struct {@@ -168,6 +170,7 @@ func MergeSandboxRequirements(values ...SandboxRequirements) SandboxRequirementsseen := map[string]bool{}for _, value := range values {merged.BunFS = merged.BunFS || value.BunFS+ merged.RunnerLoginRelay = merged.RunnerLoginRelay || value.RunnerLoginRelaystates := append([]CLIStateRequirement(nil), value.CLIStates...)for _, state := range states {if state.Directory == "" || seen[state.Directory] {diff --git a/internal/runtime/remote_sandbox.go b/internal/runtime/remote_sandbox.goindex 4911e1c5..3f758d36 100644--- a/internal/runtime/remote_sandbox.go+++ b/internal/runtime/remote_sandbox.go@@ -45,7 +45,7 @@ func OpenRemoteSandbox(ctx context.Context, id, workspace string, profile domainfunc WithCommandEnvironment(command CommandSpec, values map[string]string) CommandSpec {bound := commandbound.environment = mergeEnvironmentMaps(command.environment, values)- return bound+ return bindRunnerLoginLease(bound)}// CommandEnvironment returns a copy of the closed task-scoped environment fordiff --git a/internal/runtime/runner_login_antigravity.go b/internal/runtime/runner_login_antigravity.gonew file mode 100644index 00000000..f5c1f9ae--- /dev/null+++ b/internal/runtime/runner_login_antigravity.go@@ -0,0 +1,215 @@+package runtime++import (+ "bytes"+ "context"+ "encoding/base64"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ goRuntime "runtime"+ "strings"+ "sync"+ "time"++ "github.com/zalando/go-keyring"+)++const antigravityTokenFile = "antigravity-oauth-token"++var antigravityKeyringMu sync.Mutex++type antigravityLogin struct {+ AuthMethod string `json:"auth_method"`+ Email string `json:"id_token_email"`+ IDToken string `json:"id_token"`+ Token struct {+ Access string `json:"access_token"`+ Refresh string `json:"refresh_token"`+ Type json.RawMessage `json:"token_type"`+ Expiry json.RawMessage `json:"expiry"`+ } `json:"token"`+}++func parseAntigravityLogin(data []byte) (antigravityLogin, error) {+ var login antigravityLogin+ if len(data) > 1<<20 || json.Unmarshal(data, &login) != nil || login.Token.Refresh == "" {+ return login, fmt.Errorf("invalid Antigravity login")+ }+ return login, nil+}++func sameAntigravityLogin(before, after []byte) bool {+ a, err := parseAntigravityLogin(before)+ if err != nil {+ return false+ }+ b, err := parseAntigravityLogin(after)+ if err != nil || a.AuthMethod != b.AuthMethod || a.Token.Refresh != b.Token.Refresh {+ return false+ }+ email := func(login antigravityLogin) string {+ if login.Email != "" {+ return strings.ToLower(strings.TrimSpace(login.Email))+ }+ parts := strings.Split(login.IDToken, ".")+ if len(parts) != 3 {+ return ""+ }+ payload, err := base64.RawURLEncoding.DecodeString(parts[1])+ if err != nil {+ return ""+ }+ var claims struct {+ Email string `json:"email"`+ }+ if json.Unmarshal(payload, &claims) != nil {+ return ""+ }+ return strings.ToLower(strings.TrimSpace(claims.Email))+ }+ aEmail, bEmail := email(a), email(b)+ if aEmail != "" && bEmail != "" {+ return aEmail == bEmail+ }+ // Legacy records without an email may be refreshed, but cannot change+ // their identity by substituting a different refresh token.+ return a.Token.Refresh == b.Token.Refresh+}++func antigravityUsesFileStorage() bool {+ for _, key := range []string{"SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "WSL_DISTRO_NAME", "WSL_INTEROP"} {+ if os.Getenv(key) != "" {+ return true+ }+ }+ if goRuntime.GOOS == "linux" {+ if os.Getenv("DBUS_SESSION_BUS_ADDRESS") == "" {+ return true+ }+ for _, path := range []string{"/.dockerenv", "/run/.containerenv"} {+ if _, err := os.Stat(path); err == nil {+ return true+ }+ }+ }+ return false+}++func readAntigravityRunnerLogin() ([]byte, func([]byte) error, error) {+ if antigravityUsesFileStorage() {+ home, err := os.UserHomeDir()+ if err != nil {+ return nil, nil, err+ }+ dir := filepath.Join(home, ".gemini", "antigravity-cli")+ original, err := readRunnerLoginFile(dir, antigravityTokenFile)+ if err != nil {+ return nil, nil, err+ }+ if _, err := parseAntigravityLogin(original); err != nil {+ return nil, nil, err+ }+ return original, func(refreshed []byte) error {+ if bytes.Equal(original, refreshed) {+ return nil+ }+ if !sameAntigravityLogin(original, refreshed) {+ return fmt.Errorf("refreshed Antigravity login belongs to a different account")+ }+ if current, err := readRunnerLoginFile(dir, antigravityTokenFile); err != nil || !bytes.Equal(current, original) {+ return nil+ }+ canonical, err := canonicalAntigravityRefresh(original, refreshed)+ if err != nil || canonical == nil {+ return err+ }+ return replaceRunnerLoginFile(dir, antigravityTokenFile, original, canonical)+ }, nil+ }+ return antigravityKeyringLogin(readAntigravityKeyring, writeAntigravityKeyring)+}++// The injectable store keeps tests away from the user's real OS credentials.+func antigravityKeyringLogin(read func() (string, error), write func(string) error) ([]byte, func([]byte) error, error) {+ stored, err := read()+ if err != nil {+ return nil, nil, fmt.Errorf("cannot read Antigravity system credentials")+ }+ original := []byte(stored)+ if _, err := parseAntigravityLogin(original); err != nil {+ return nil, nil, err+ }+ return original, func(refreshed []byte) error {+ if bytes.Equal(original, refreshed) {+ return nil+ }+ if !sameAntigravityLogin(original, refreshed) {+ return fmt.Errorf("refreshed Antigravity login belongs to a different account")+ }+ antigravityKeyringMu.Lock()+ defer antigravityKeyringMu.Unlock()+ current, err := read()+ if err != nil || current != stored {+ return nil+ }+ canonical, err := canonicalAntigravityRefresh(original, refreshed)+ if err != nil || canonical == nil {+ return err+ }+ if current, err := read(); err != nil || current != stored {+ return nil+ }+ if err := write(string(canonical)); err != nil {+ return fmt.Errorf("cannot save refreshed Antigravity system credentials")+ }+ return nil+ }, nil+}++func readAntigravityKeyring() (string, error) {+ if goRuntime.GOOS != "darwin" {+ return keyring.Get("gemini", "antigravity")+ }+ // Match agy's go-keyring encoding while bounding a locked keychain prompt.+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ data, err := exec.CommandContext(ctx, "/usr/bin/security", "find-generic-password", "-s", "gemini", "-a", "antigravity", "-w").Output()+ if err != nil {+ return "", fmt.Errorf("cannot read Antigravity keychain item")+ }+ value := strings.TrimSpace(string(data))+ if encoded, ok := strings.CutPrefix(value, "go-keyring-base64:"); ok {+ decoded, err := base64.StdEncoding.DecodeString(encoded)+ return string(decoded), err+ }+ if encoded, ok := strings.CutPrefix(value, "go-keyring-encoded:"); ok {+ decoded, err := hex.DecodeString(encoded)+ return string(decoded), err+ }+ return value, nil+}++func writeAntigravityKeyring(value string) error {+ if goRuntime.GOOS != "darwin" {+ return keyring.Set("gemini", "antigravity", value)+ }+ encoded := "go-keyring-base64:" + base64.StdEncoding.EncodeToString([]byte(value))+ command := "add-generic-password -U -s gemini -a antigravity -w " + encoded + "\n"+ if len(command) > 4000 {+ return fmt.Errorf("Antigravity keychain item is too large")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ // Updating in place preserves the existing ACL. The secret is passed only+ // through stdin, never in argv, a shell command line, or diagnostic output.+ cmd := exec.CommandContext(ctx, "/usr/bin/security", "-i")+ cmd.Stdin = strings.NewReader(command)+ if err := cmd.Run(); err != nil {+ return fmt.Errorf("cannot update Antigravity keychain item")+ }+ return nil+}diff --git a/internal/runtime/runner_login_antigravity_identity.go b/internal/runtime/runner_login_antigravity_identity.gonew file mode 100644index 00000000..cb663c7a--- /dev/null+++ b/internal/runtime/runner_login_antigravity_identity.go@@ -0,0 +1,126 @@+package runtime++import (+ "context"+ "encoding/base64"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "strings"+ "time"+)++var antigravityIdentityClient = &http.Client{Timeout: 8 * time.Second,+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}++type antigravityIdentity struct {+ Subject string `json:"sub"`+ Email string `json:"email"`+ Verified bool `json:"email_verified"`+}++func googleRunnerIdentity(access string) (antigravityIdentity, error) {+ var identity antigravityIdentity+ if access == "" {+ return identity, errors.New("Antigravity access token missing")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)+ defer cancel()+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://openidconnect.googleapis.com/v1/userinfo", nil)+ req.Header.Set("Authorization", "Bearer "+access)+ resp, err := antigravityIdentityClient.Do(req)+ if err != nil {+ return identity, errors.New("Antigravity identity verification unavailable; host login retained")+ }+ defer resp.Body.Close()+ data, err := io.ReadAll(io.LimitReader(resp.Body, (64<<10)+1))+ if err != nil || len(data) > 64<<10 || resp.StatusCode != http.StatusOK || json.Unmarshal(data, &identity) != nil || identity.Subject == "" {+ return identity, errors.New("cannot verify refreshed Antigravity identity; host login retained")+ }+ return identity, nil+}++func verifyAntigravityRefreshIdentity(before antigravityLogin, access string) error {+ identity, err := googleRunnerIdentity(access)+ if err != nil {+ return err+ }+ // Compare server-confirmed identity with trusted host metadata. Metadata+ // in the sandbox is not an identity proof, even when its email matches.+ trusted := antigravityIdentity{Email: before.Email}+ parts := strings.Split(before.IDToken, ".")+ if len(parts) == 3 {+ if data, err := base64.RawURLEncoding.DecodeString(parts[1]); err == nil {+ var claims antigravityIdentity+ if json.Unmarshal(data, &claims) == nil {+ trusted.Subject = claims.Subject+ if trusted.Email == "" {+ trusted.Email = claims.Email+ }+ }+ }+ }+ if trusted.Subject != "" {+ if identity.Subject != trusted.Subject {+ return errors.New("Antigravity account changed; host login retained")+ }+ return nil+ }+ if trusted.Email != "" {+ if !identity.Verified || !strings.EqualFold(strings.TrimSpace(identity.Email), strings.TrimSpace(trusted.Email)) {+ return errors.New("Antigravity account changed; host login retained")+ }+ return nil+ }+ baseline, err := googleRunnerIdentity(before.Token.Access)+ if err != nil {+ return err+ }+ if baseline.Subject != identity.Subject {+ return errors.New("Antigravity account changed; host login retained")+ }+ return nil+}++// canonicalAntigravityRefresh keeps host account metadata and the refresh token.+// A nil result without an error means the access token did not change.+func canonicalAntigravityRefresh(original, refreshed []byte) ([]byte, error) {+ before, err := parseAntigravityLogin(original)+ if err != nil {+ return nil, err+ }+ after, err := parseAntigravityLogin(refreshed)+ if err != nil {+ return nil, err+ }+ if before.Token.Refresh != after.Token.Refresh {+ return nil, errors.New("Antigravity refresh token changed; host login retained")+ }+ if before.Token.Access == after.Token.Access {+ return nil, nil+ }+ var expiry time.Time+ if json.Unmarshal(after.Token.Expiry, &expiry) != nil || !expiry.After(time.Now()) {+ return nil, errors.New("invalid Antigravity access token expiry; host login retained")+ }+ var tokenType string+ if after.Token.Type != nil && (json.Unmarshal(after.Token.Type, &tokenType) != nil || !strings.EqualFold(tokenType, "Bearer")) {+ return nil, errors.New("invalid Antigravity token type; host login retained")+ }+ if err := verifyAntigravityRefreshIdentity(before, after.Token.Access); err != nil {+ return nil, err+ }++ var host, token map[string]json.RawMessage+ if json.Unmarshal(original, &host) != nil || json.Unmarshal(host["token"], &token) != nil {+ return nil, errors.New("invalid Antigravity token")+ }+ token["access_token"], _ = json.Marshal(after.Token.Access)+ token["expiry"] = after.Token.Expiry+ if after.Token.Type != nil {+ token["token_type"] = json.RawMessage(`"Bearer"`)+ }+ host["token"], _ = json.Marshal(token)+ return json.Marshal(host)+}diff --git a/internal/runtime/runner_login_antigravity_test.go b/internal/runtime/runner_login_antigravity_test.gonew file mode 100644index 00000000..8c1e652b--- /dev/null+++ b/internal/runtime/runner_login_antigravity_test.go@@ -0,0 +1,271 @@+package runtime++import (+ "context"+ "encoding/base64"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"+ "time"+)++const agyOriginalLogin = `{"token":{"access_token":"old-access","refresh_token":"original-refresh","expiry":"2026-11-01T00:00:00Z"},"auth_method":"consumer","id_token_email":"[email protected]"}`++var agyRefreshedExpiry = time.Now().UTC().Add(time.Hour).Format(time.RFC3339)+var agyRefreshedLogin = `{"token":{"access_token":"new-access","refresh_token":"original-refresh","token_type":"Bearer","expiry":"` + agyRefreshedExpiry + `"},"auth_method":"consumer","id_token_email":"[email protected]"}`++func sameAgyFixtureJSON(a, b []byte) bool {+ var left, right any+ return json.Unmarshal(a, &left) == nil && json.Unmarshal(b, &right) == nil && reflect.DeepEqual(left, right)+}++func TestAntigravityRefreshKeepsTrustedMetadata(t *testing.T) {+ setAgyIdentityFixture(t, "[email protected]")+ var candidate map[string]any+ _ = json.Unmarshal([]byte(agyRefreshedLogin), &candidate)+ candidate["id_token"] = "sandbox-forged-identity"+ candidate["extra_setting"] = "sandbox-setting"+ raw, _ := json.Marshal(candidate)+ canonical, err := canonicalAntigravityRefresh([]byte(agyOriginalLogin), raw)+ if err != nil || !sameAgyFixtureJSON(canonical, []byte(agyRefreshedLogin)) {+ t.Fatal("sandbox metadata entered trusted source")+ }+}++func TestAntigravityIdentityFailureKeepsHost(t *testing.T) {+ before := antigravityIdentityClient+ antigravityIdentityClient = &http.Client{Transport: agyIdentityFixtureTransport(func(*http.Request) (*http.Response, error) { return nil, errors.New("offline") })}+ t.Cleanup(func() { antigravityIdentityClient = before })+ stored, writes := agyOriginalLogin, 0+ _, keep, err := antigravityKeyringLogin(func() (string, error) { return stored, nil }, func(value string) error { stored = value; writes++; return nil })+ if err != nil {+ t.Fatal(err)+ }+ if err := keep([]byte(agyRefreshedLogin)); err == nil || writes != 0 || stored != agyOriginalLogin {+ t.Fatal("unverified access token replaced host login")+ }+}++type agyIdentityFixtureTransport func(*http.Request) (*http.Response, error)++func (f agyIdentityFixtureTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func setAgyIdentityFixture(t *testing.T, email string) {+ t.Helper()+ previous := antigravityIdentityClient+ antigravityIdentityClient = &http.Client{Transport: agyIdentityFixtureTransport(func(r *http.Request) (*http.Response, error) {+ owner := email+ if strings.Contains(r.Header.Get("Authorization"), "foreign-access") {+ owner = "[email protected]"+ }+ body, _ := json.Marshal(map[string]any{"sub": "fixture-subject-" + owner, "email": owner, "email_verified": true})+ return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(body))), Header: make(http.Header)}, nil+ })}+ t.Cleanup(func() { antigravityIdentityClient = previous })+}++func agyFileLoginFixture(t *testing.T) string {+ t.Helper()+ setAgyIdentityFixture(t, "[email protected]")+ host := t.TempDir()+ t.Setenv("HOME", host)+ t.Setenv("SSH_CONNECTION", "test-remote-session")+ path := filepath.Join(host, ".gemini", "antigravity-cli", antigravityTokenFile)+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(agyOriginalLogin), 0600); err != nil {+ t.Fatal(err)+ }+ return path+}++func TestAntigravityRunnerLoginLifecycle(t *testing.T) {+ source := agyFileLoginFixture(t)+ root := t.TempDir()+ login, _ := runnerLoginSpec(AgentCLIAntigravity)+ settings := filepath.Join(root, "home", login.dir, "settings.json")+ if err := os.MkdirAll(filepath.Dir(settings), 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(settings, []byte(`{"modelProvider":"gemini"}`), 0600); err != nil {+ t.Fatal(err)+ }+ cleanup, env, err := prepareConversationRunnerLogin(root, login, true)+ if err != nil {+ t.Fatal(err)+ }+ if env["SSH_CONNECTION"] == "" {+ t.Fatal("sandbox did not select official file authentication")+ }+ for _, key := range []string{"GEMINI_API_KEY", "GOOGLE_API_KEY", "AGY_ADC_AUTH", "AGY_LLM_GATEWAY_API_KEY"} {+ if value, present := env[key]; !present || value != "" {+ t.Fatalf("host credential %s was not cleared", key)+ }+ }+ if raw, err := os.ReadFile(settings); err != nil || string(raw) != "{}" {+ t.Fatal("previous API billing mode was retained")+ }+ copy := filepath.Join(root, "home", login.dir, login.file)+ if info, err := os.Stat(copy); err != nil || info.Mode().Perm() != 0600 {+ t.Fatal("login copy must be private")+ }+ if err := os.WriteFile(copy, []byte(agyRefreshedLogin), 0600); err != nil {+ t.Fatal(err)+ }+ if err := cleanup(); err != nil {+ t.Fatal(err)+ }+ if raw, err := os.ReadFile(source); err != nil || !sameAgyFixtureJSON(raw, []byte(agyRefreshedLogin)) {+ t.Fatal("refreshed login was not saved to its source")+ }+ if _, err := os.Stat(copy); !os.IsNotExist(err) {+ t.Fatal("isolated credential copy survived cleanup")+ }+ cleanup, _, err = prepareConversationRunnerLogin(root, login, true)+ if err != nil {+ t.Fatal(err)+ }+ if raw, _ := os.ReadFile(copy); !sameAgyFixtureJSON(raw, []byte(agyRefreshedLogin)) {+ t.Fatal("next invocation did not use the refreshed source")+ }+ if err := cleanup(); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(copy, []byte(agyOriginalLogin), 0600); err != nil {+ t.Fatal(err)+ }+ if _, _, err := prepareConversationRunnerLogin(root, login, false); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(copy); !os.IsNotExist(err) {+ t.Fatal("API-key mode retained an account credential")+ }+ if err := os.WriteFile(copy, []byte(agyOriginalLogin), 0600); err != nil {+ t.Fatal(err)+ }+ _, keyEnv, err := ApplyAgentCLICredential(AgentCLIAntigravity, ProviderCredential{APIKey: "personal-key"}, AgentCLIOptions{Model: "gemini-test"}, HostAgentCLIHome(filepath.Join(root, "home")), filepath.Join(root, "home"), []string{"agy", "-p", "test"})+ if err != nil || keyEnv["GEMINI_API_KEY"] != "personal-key" {+ t.Fatalf("API-key configuration failed: %v", err)+ }+ if _, err := os.Stat(copy); !os.IsNotExist(err) {+ t.Fatal("API-key binding retained a credential from an interrupted account-login run")+ }+}++func TestAntigravityKeyringLoginRefresh(t *testing.T) {+ setAgyIdentityFixture(t, "[email protected]")+ expiryField := `"expiry":"` + agyRefreshedExpiry + `"`+ for _, tc := range []struct {+ name, concurrent, refreshed string+ wantWrite, wantError bool+ }{+ {name: "refresh", refreshed: agyRefreshedLogin, wantWrite: true},+ {name: "host switched accounts", concurrent: "different-host-login", refreshed: agyRefreshedLogin},+ {name: "host logged out", concurrent: "missing", refreshed: agyRefreshedLogin},+ {name: "sandbox switched accounts", refreshed: strings.ReplaceAll(agyRefreshedLogin, "[email protected]", "[email protected]"), wantError: true},+ {name: "sandbox changed only refresh token", refreshed: strings.ReplaceAll(agyOriginalLogin, "original-refresh", "foreign-refresh"), wantError: true},+ {name: "sandbox forged local identity", refreshed: strings.ReplaceAll(agyRefreshedLogin, "new-access", "foreign-access"), wantError: true},+ {name: "unchanged", refreshed: agyOriginalLogin},+ {name: "unchanged access with updated metadata", refreshed: strings.Replace(agyRefreshedLogin, "new-access", "old-access", 1)},+ {name: "refresh with malformed expiry", refreshed: strings.Replace(agyRefreshedLogin, expiryField, `"expiry":"invalid"`, 1), wantError: true},+ {name: "refresh with missing expiry", refreshed: strings.Replace(agyRefreshedLogin, ","+expiryField, "", 1), wantError: true},+ {name: "refresh with null expiry", refreshed: strings.Replace(agyRefreshedLogin, expiryField, `"expiry":null`, 1), wantError: true},+ {name: "refresh with already expired metadata", refreshed: strings.Replace(agyRefreshedLogin, expiryField, `"expiry":"2000-01-01T00:00:00Z"`, 1), wantError: true},+ {name: "refresh with invalid token type", refreshed: strings.Replace(agyRefreshedLogin, `"Bearer"`, `"unsupported"`, 1), wantError: true},+ {name: "refresh without token type", refreshed: strings.Replace(agyRefreshedLogin, `"token_type":"Bearer",`, "", 1), wantWrite: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ stored, writes := agyOriginalLogin, 0+ read := func() (string, error) {+ if stored == "missing" {+ return "", os.ErrNotExist+ }+ return stored, nil+ }+ write := func(value string) error { stored = value; writes++; return nil }+ _, keep, err := antigravityKeyringLogin(read, write)+ if err != nil {+ t.Fatal(err)+ }+ if tc.concurrent != "" {+ stored = tc.concurrent+ }+ err = keep([]byte(tc.refreshed))+ if (err != nil) != tc.wantError || (writes == 1) != tc.wantWrite {+ t.Fatalf("writes=%d error=%v", writes, err)+ }+ })+ }+ t.Run("credential errors do not expose secrets", func(t *testing.T) {+ _, _, err := antigravityKeyringLogin(func() (string, error) { return "", errors.New("private-keychain-diagnostic") }, func(string) error { return nil })+ if err == nil || strings.Contains(err.Error(), "private-keychain-diagnostic") {+ t.Fatal("raw keychain error exposed")+ }+ })+}++func TestAntigravityFileLoginIgnoresMetadataOnlyUpdate(t *testing.T) {+ path := agyFileLoginFixture(t)+ original, keep, err := readAntigravityRunnerLogin()+ if err != nil {+ t.Fatal(err)+ }+ candidate := strings.Replace(string(original), "2026-11-01T00:00:00Z", "invalid", 1)+ if err := keep([]byte(candidate)); err != nil {+ t.Fatal(err)+ }+ current, err := os.ReadFile(path)+ if err != nil || string(current) != string(original) {+ t.Fatal("metadata-only update changed the host credential file")+ }+}++func TestAntigravityLoginIdentityMigration(t *testing.T) {+ claims := base64.RawURLEncoding.EncodeToString([]byte(`{"email":"[email protected]"}`))+ var original map[string]any+ if err := json.Unmarshal([]byte(agyOriginalLogin), &original); err != nil {+ t.Fatal(err)+ }+ delete(original, "id_token_email")+ original["id_token"] = "header." + claims + ".signature"+ raw, _ := json.Marshal(original)+ if !sameAntigravityLogin(raw, []byte(agyRefreshedLogin)) {+ t.Fatal("official id_token to id_token_email migration rejected")+ }+ if sameAntigravityLogin(raw, []byte(strings.ReplaceAll(agyRefreshedLogin, "[email protected]", "[email protected]"))) {+ t.Fatal("another account accepted")+ }+}++func TestAntigravityAccountModelsSaveRefreshedLogin(t *testing.T) {+ source := agyFileLoginFixture(t)+ bin := filepath.Join(t.TempDir(), "agy")+ script := `#!/bin/sh+set -eu+test "$1" = models+test -n "$SSH_CONNECTION"+test -z "${GEMINI_API_KEY:-}${GOOGLE_API_KEY:-}${AGY_ADC_AUTH:-}"+test -f "$HOME/.gemini/antigravity-cli/antigravity-oauth-token"+printf '%s' '` + agyRefreshedLogin + `' > "$HOME/.gemini/antigravity-cli/antigravity-oauth-token"+printf 'gemini-4-hydrogen-high\tGemini 4 Hydrogen (High)\n'+printf 'gemini-4-hydrogen-high\tDuplicate\n'+printf 'Fetching available models...\n' >&2+`+ if err := os.WriteFile(bin, []byte(script), 0700); err != nil {+ t.Fatal(err)+ }+ models, err := DiscoverRunnerLoginModels(context.Background(), AgentCLIAntigravity, bin)+ if err != nil || len(models) != 1 || models[0].ID != "gemini-4-hydrogen-high" {+ t.Fatalf("models=%+v error=%v", models, err)+ }+ if raw, _ := os.ReadFile(source); !sameAgyFixtureJSON(raw, []byte(agyRefreshedLogin)) {+ t.Fatal("model query lost its refreshed credential")+ }+}diff --git a/internal/runtime/runner_login_claude.go b/internal/runtime/runner_login_claude.gonew file mode 100644index 00000000..abfc356e--- /dev/null+++ b/internal/runtime/runner_login_claude.go@@ -0,0 +1,197 @@+package runtime++import (+ "bufio"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "os/exec"+ "sync"+ "time"+)++// Claude's host-refresh control channel stays on process stdin/stdout, including+// docker exec -i. Refresh tokens never cross this channel or enter a sandbox.+type claudeLoginBridge struct {+ cmd *exec.Cmd+ command CommandSpec+ input io.Reader+ reader, writer *os.File+ writeMu sync.Mutex+ mu sync.Mutex+ err error+ ready chan struct{}+ readyOnce sync.Once+ stop context.CancelFunc+ ctx context.Context+ initializeID string+}++func newClaudeLoginBridge(cmd *exec.Cmd, command CommandSpec) (*claudeLoginBridge, error) {+ reader, writer, err := os.Pipe()+ if err != nil {+ return nil, err+ }+ ctx, stop := context.WithCancel(context.Background())+ bridge := &claudeLoginBridge{cmd: cmd, command: command, input: cmd.Stdin,+ reader: reader, writer: writer, ready: make(chan struct{}), ctx: ctx, stop: stop,+ initializeID: "runner-auth-" + command.runnerLogin.id}+ cmd.Stdin = reader // A real fd avoids os/exec waiting on an open-ended copier.+ return bridge, nil+}++func (b *claudeLoginBridge) send(value any) error {+ raw, err := json.Marshal(value)+ if err != nil {+ return err+ }+ b.writeMu.Lock()+ defer b.writeMu.Unlock()+ _, err = b.writer.Write(append(raw, '\n'))+ return err+}++func (b *claudeLoginBridge) fail(err error) {+ b.mu.Lock()+ if b.err == nil {+ b.err = err+ }+ b.mu.Unlock()+ if b.cmd.Process != nil {+ _ = b.cmd.Process.Kill()+ }+}++func (b *claudeLoginBridge) start() {+ go func() {+ if b.command.runnerLoginInitialize {+ if err := b.send(map[string]any{"type": "control_request", "request_id": b.initializeID,+ "request": map[string]string{"subtype": "initialize"}}); err != nil {+ b.fail(errors.New("无法初始化 Claude Code 自动续期接口"))+ return+ }+ select {+ case <-b.ready:+ case <-b.ctx.Done():+ return+ case <-time.After(20 * time.Second):+ b.fail(errors.New("Claude Code 未响应自动续期初始化,请更新 CLI"))+ return+ }+ if b.command.runnerLoginPrompt != "" {+ if err := b.send(map[string]any{"type": "user", "session_id": "", "message": map[string]string{+ "role": "user", "content": b.command.runnerLoginPrompt}}); err != nil {+ b.fail(errors.New("无法向 Claude Code 发送任务"))+ return+ }+ }+ }+ if b.input == nil {+ return+ }+ scanner := bufio.NewScanner(b.input)+ scanner.Buffer(make([]byte, 16<<10), 8<<20)+ for scanner.Scan() {+ b.writeMu.Lock()+ _, err := b.writer.Write(append(append([]byte(nil), scanner.Bytes()...), '\n'))+ b.writeMu.Unlock()+ if err != nil {+ return+ }+ }+ if scanner.Err() != nil && b.ctx.Err() == nil {+ b.fail(errors.New("Claude Code 输入超过限制或读取失败"))+ }+ }()+}++func (b *claudeLoginBridge) filter(line string) bool {+ var event struct {+ Type string `json:"type"`+ RequestID string `json:"request_id"`+ Request struct {+ Subtype string `json:"subtype"`+ } `json:"request"`+ Response struct {+ Subtype string `json:"subtype"`+ RequestID string `json:"request_id"`+ } `json:"response"`+ Subtype string `json:"subtype"`+ Version string `json:"claude_code_version"`+ }+ if json.Unmarshal([]byte(line), &event) != nil {+ return true+ }+ if event.Type == "result" && b.command.runnerLoginInitialize && b.input == nil {+ // Print mode with streaming input waits for EOF even after its result.+ // Interactive conversations retain their caller-owned input instead.+ b.writeMu.Lock()+ _ = b.writer.Close()+ b.writeMu.Unlock()+ }+ if event.Type == "system" && event.Subtype == "init" && event.Version != "" {+ var major, minor, patch int+ if _, err := fmt.Sscanf(event.Version, "%d.%d.%d", &major, &minor, &patch); err == nil &&+ (major < 2 || major == 2 && (minor < 1 || minor == 1 && patch < 326)) {+ b.fail(errors.New("Claude Code 自动续期需要 2.1.326 或更新版本,请更新 CLI"))+ }+ }+ if b.command.runnerLoginInitialize && event.Type == "control_response" && event.Response.RequestID == b.initializeID {+ if event.Response.Subtype != "success" {+ b.fail(errors.New("Claude Code 不支持 Runner 自动续期初始化"))+ return false+ }+ b.readyOnce.Do(func() { close(b.ready) })+ return false+ }+ if event.Type != "control_request" || event.Request.Subtype != "oauth_token_refresh" {+ return true+ }+ // The server may request a distinct cloud-sessions token through the same+ // subtype. Never answer that request with a sign-in token.+ var details struct {+ Request struct {+ Kind string `json:"kind"`+ } `json:"request"`+ }+ _ = json.Unmarshal([]byte(line), &details)+ response := map[string]any{"accessToken": nil}+ if details.Request.Kind == "" {+ ctx, cancel := context.WithTimeout(b.ctx, 30*time.Second)+ token, err := b.command.runnerLogin.renewClaude(ctx)+ cancel()+ if err == nil {+ response["accessToken"] = token+ } else {+ response["reason"] = "temporarily_unavailable"+ }+ }+ if err := b.send(map[string]any{"type": "control_response", "response": map[string]any{+ "subtype": "success", "request_id": event.RequestID, "response": response,+ }}); err != nil && b.ctx.Err() == nil {+ b.fail(errors.New("无法回复 Claude Code 自动续期请求"))+ }+ return false+}++func (b *claudeLoginBridge) close() {+ b.stop()+ _ = b.writer.Close()+ _ = b.reader.Close()+ if closer, ok := b.input.(io.Closer); ok {+ _ = closer.Close()+ }+}++func (b *claudeLoginBridge) result() error {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.err+}++func isManagedClaude(command CommandSpec) bool {+ return command.Provider == "claude-code" && command.runnerLogin != nil && valueAfter(command.Argv, "--input-format") == "stream-json"+}diff --git a/internal/runtime/runner_login_claude_integration_test.go b/internal/runtime/runner_login_claude_integration_test.gonew file mode 100644index 00000000..46bee2ee--- /dev/null+++ b/internal/runtime/runner_login_claude_integration_test.go@@ -0,0 +1,139 @@+package runtime++import (+ "bufio"+ "bytes"+ "context"+ "crypto/tls"+ "crypto/x509"+ "encoding/json"+ "net/http"+ "net/url"+ "os"+ "os/exec"+ "path/filepath"+ gort "runtime"+ "strings"+ "sync"+ "testing"+ "time"+)++// The official client, real stdin/stdout bridge, and production OAuth adapter+// run against a loopback fixture. No Claude subscription or live auth is used.+func TestManagedLoginOfficialClaude(t *testing.T) {+ binary := os.Getenv("LOOPFORGE_PROBE_CLAUDE_BIN")+ if binary == "" {+ t.Skip("set LOOPFORGE_PROBE_CLAUDE_BIN for the offline official-client test")+ }+ if gort.GOOS != "darwin" || !filepath.IsAbs(binary) {+ t.Fatal("requires macOS and an absolute official binary path")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)+ defer cancel()+ fixture := exec.CommandContext(ctx, "python3", "../../scripts/probe-cli-auth-control.py", "claude", "--serve-only")+ input, err := fixture.StdinPipe()+ if err != nil {+ t.Fatal(err)+ }+ output, err := fixture.StdoutPipe()+ if err != nil {+ t.Fatal(err)+ }+ var diagnostics bytes.Buffer+ fixture.Stderr = &diagnostics+ if err := fixture.Start(); err != nil {+ t.Fatal(err)+ }+ defer func() { _ = input.Close(); cancel(); _ = fixture.Wait() }()+ scanner := bufio.NewScanner(output)+ if !scanner.Scan() {+ t.Fatalf("offline fixture failed: %s", diagnostics.String())+ }+ var settings struct{ URL, Proxy, CA string }+ if err := json.Unmarshal(scanner.Bytes(), &settings); err != nil {+ t.Fatal(err)+ }+ ca, err := os.ReadFile(settings.CA)+ if err != nil {+ t.Fatal(err)+ }+ roots := x509.NewCertPool()+ if !roots.AppendCertsFromPEM(ca) {+ t.Fatal("invalid fixture CA")+ }+ proxy, err := url.Parse(settings.Proxy)+ if err != nil {+ t.Fatal(err)+ }+ manager := &runnerLoginManager{stateDir: t.TempDir(), client: &http.Client{Timeout: 15 * time.Second,+ Transport: &http.Transport{Proxy: http.ProxyURL(proxy), TLSClientConfig: &tls.Config{RootCAs: roots}},+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}+ source, _, _ := managedLoginFixture(t, "claude-code")+ initial, _ := json.Marshal(map[string]any{"claudeAiOauth": map[string]any{+ "accessToken": "sk-ant-" + "oat01-probe-not-a-real-token-0", "refreshToken": "runner-owned-fake-refresh-0",+ "expiresAt": time.Now().Add(time.Hour).UnixMilli(), "scopes": []string{"user:inference", "user:profile"}}})+ if err := os.WriteFile(source.path, initial, 0600); err != nil {+ t.Fatal(err)+ }+ var leases []*runnerLoginLease+ for range 3 {+ lease, err := newRunnerLoginLease(ctx, manager, source, false)+ if err != nil {+ t.Fatal(err)+ }+ defer lease.close()+ leases = append(leases, lease)+ }+ realHome, _ := os.UserHomeDir()+ profile := `(version 1) (allow default) (deny network*) (allow network-outbound (remote ip "localhost:*"))`+ for _, path := range []string{filepath.Join(realHome, ".codex"), filepath.Join(realHome, ".claude"), filepath.Join(realHome, ".gemini"), filepath.Join(realHome, "Library", "Keychains")} {+ quoted, _ := json.Marshal(path)+ profile += ` (deny file-read* file-write* (subpath ` + string(quoted) + `))`+ }+ quoted, _ := json.Marshal(realHome)+ profile += ` (deny file-write* (subpath ` + string(quoted) + `))`+ var workers sync.WaitGroup+ for _, lease := range leases {+ root := t.TempDir()+ home := filepath.Join(root, "home")+ config := filepath.Join(home, ".claude")+ if err := os.MkdirAll(config, 0700); err != nil {+ t.Fatal(err)+ }+ workers.Add(1)+ go func(lease *runnerLoginLease, root, home, config string) {+ defer workers.Done()+ command := WithCommandEnvironment(CommandSpec{Provider: "claude-code", Argv: []string{+ "/usr/bin/sandbox-exec", "-p", profile, binary, "--print", "--output-format", "stream-json", "--verbose",+ "--model", "claude-sonnet-4-6", "--max-turns", "1", "--tools", "", "--strict-mcp-config", "--setting-sources", "", "Reply OFFLINE_AUTH_OK."}}, lease.environment())+ cmd := exec.CommandContext(ctx, command.Argv[0], command.Argv[1:]...)+ cmd.Dir = root+ cmd.Env = appendEnvironment([]string{"PATH=/usr/bin:/bin", "HOME=" + home, "CLAUDE_CONFIG_DIR=" + config, "TMPDIR=" + root,+ "HTTP_PROXY=" + settings.Proxy, "HTTPS_PROXY=" + settings.Proxy, "ALL_PROXY=" + settings.Proxy, "NO_PROXY=127.0.0.1,localhost",+ "NODE_EXTRA_CA_CERTS=" + settings.CA, "SSL_CERT_FILE=" + settings.CA, "DO_NOT_TRACK=1", "NO_COLOR=1",+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", "DISABLE_AUTOUPDATER=1"}, command.environment)+ out, err := runCommand(cmd, nil, command)+ if err != nil || !strings.Contains(out, "OFFLINE_AUTH_OK") || strings.Contains(out, "oauth_token_refresh") || strings.Contains(out, "runner-owned-fake-refresh") {+ t.Errorf("official client did not recover through production bridge: %v; fake diagnostics %.800s", err, out)+ }+ }(lease, root, home, config)+ }+ workers.Wait()+ _ = input.Close()+ if !scanner.Scan() {+ t.Fatal("missing fixture results")+ }+ var result struct{ Refreshes, Refusals, Successes int }+ if err := json.Unmarshal(scanner.Bytes(), &result); err != nil {+ t.Fatal(err)+ }+ if result.Refreshes != 1 || result.Refusals != 3 || result.Successes != 3 {+ t.Fatalf("offline fixture results: %+v", result)+ }+ raw, err := os.ReadFile(source.path)+ if err != nil || !bytes.Contains(raw, []byte("runner-owned-fake-refresh-1")) {+ t.Fatal("rotated pair not saved on host")+ }+ t.Log("3 official Claude processes recovered from 401 through 1 host exchange; no live account used")+}diff --git a/internal/runtime/runner_login_lease.go b/internal/runtime/runner_login_lease.gonew file mode 100644index 00000000..c857585b--- /dev/null+++ b/internal/runtime/runner_login_lease.go@@ -0,0 +1,274 @@+package runtime++import (+ "context"+ "crypto/rand"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net"+ "net/http"+ "path/filepath"+ "strings"+ "sync"+ "sync/atomic"+ "time"+)++const runnerLoginLeaseEnv = "AGENTFLOW_RUNNER_LOGIN_TOKEN"++var runnerLoginLeases sync.Map++type runnerLoginLease struct {+ id string+ manager *runnerLoginManager+ source runnerLoginSource+ snapshot runnerLoginSnapshot+ mu sync.Mutex+ requests map[string]runnerLoginSnapshot+ replies map[string][]byte+ server *http.Server+ endpoint string+ closed atomic.Bool+ protected []string+}++func runnerLoginNonce() (string, error) {+ var data [32]byte+ if _, err := rand.Read(data[:]); err != nil {+ return "", err+ }+ return base64.RawURLEncoding.EncodeToString(data[:]), nil+}++func newRunnerLoginLease(ctx context.Context, manager *runnerLoginManager, source runnerLoginSource, docker bool) (*runnerLoginLease, error) {+ snapshot, err := manager.current(ctx, source)+ if err != nil {+ return nil, err+ }+ if source.provider == "claude-code" && !snapshot.expiry.IsZero() && time.Until(snapshot.expiry) < 2*time.Minute {+ snapshot, err = manager.renew(ctx, source, snapshot)+ if err != nil {+ return nil, err+ }+ }+ id, err := runnerLoginNonce()+ if err != nil {+ return nil, err+ }+ lease := &runnerLoginLease{id: id, manager: manager, source: source, snapshot: snapshot,+ requests: map[string]runnerLoginSnapshot{id: snapshot}, replies: make(map[string][]byte)}+ _, statePath, err := manager.entry(source)+ if err != nil {+ return nil, err+ }+ lease.protected = []string{source.path, filepath.Dir(statePath)}+ if source.origin != "" && source.origin != source.path {+ lease.protected = append(lease.protected, source.origin)+ }+ if source.provider == "codex" {+ address, host := "127.0.0.1:0", "127.0.0.1"+ if docker {+ address = "0.0.0.0:0"+ host, _, err = conversationDockerAccess(ctx)+ if err != nil {+ return nil, err+ }+ }+ listener, err := net.Listen("tcp4", address)+ if err != nil {+ return nil, err+ }+ lease.endpoint = "http://" + net.JoinHostPort(host, fmt.Sprint(listener.Addr().(*net.TCPAddr).Port)) + "/runner-login/" + id + "/refresh"+ lease.server = &http.Server{ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 40 * time.Second,+ Handler: http.HandlerFunc(lease.serveRefresh)}+ go lease.server.Serve(listener)+ }+ runnerLoginLeases.Store(id, lease)+ return lease, nil+}++func (l *runnerLoginLease) close() {+ if l.closed.Swap(true) {+ return+ }+ runnerLoginLeases.Delete(l.id)+ if l.server != nil {+ _ = l.server.Close()+ }+}++func (l *runnerLoginLease) environment() map[string]string {+ env := map[string]string{runnerLoginLeaseEnv: l.id}+ if l.source.provider == "codex" {+ env["CODEX_REFRESH_TOKEN_URL_OVERRIDE"] = l.endpoint+ } else {+ env["CLAUDE_CODE_OAUTH_TOKEN"] = l.snapshot.access+ env["CLAUDE_CODE_OAUTH_REFRESH_TOKEN"] = ""+ env["CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH"] = "1"+ env["CLAUDE_CODE_ENTRYPOINT"] = "local-agent"+ env["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST"] = "1"+ }+ return env+}++func codexLeaseCredential(snapshot runnerLoginSnapshot, nonce string) ([]byte, error) {+ var host struct {+ Tokens struct {+ ID string `json:"id_token"`+ Account string `json:"account_id"`+ } `json:"tokens"`+ Last json.RawMessage `json:"last_refresh"`+ }+ if json.Unmarshal(snapshot.raw, &host) != nil {+ return nil, errors.New("invalid Codex login")+ }+ doc := map[string]any{"auth_mode": "chatgpt", "tokens": map[string]string{+ "access_token": snapshot.access, "refresh_token": nonce, "id_token": host.Tokens.ID, "account_id": host.Tokens.Account,+ }}+ if len(host.Last) > 0 {+ doc["last_refresh"] = host.Last+ }+ return json.Marshal(doc)+}++func (l *runnerLoginLease) credential() ([]byte, error) {+ if l.source.provider == "codex" {+ return codexLeaseCredential(l.snapshot, l.id)+ }+ var doc map[string]json.RawMessage+ if json.Unmarshal(l.snapshot.raw, &doc) != nil {+ return nil, errors.New("invalid Claude login")+ }+ var oauth map[string]json.RawMessage+ if json.Unmarshal(doc["claudeAiOauth"], &oauth) != nil {+ return nil, errors.New("invalid Claude OAuth login")+ }+ delete(oauth, "refreshToken")+ raw, _ := json.Marshal(oauth)+ return json.Marshal(map[string]json.RawMessage{"claudeAiOauth": raw})+}++func (l *runnerLoginLease) renewClaude(ctx context.Context) (string, error) {+ l.mu.Lock()+ defer l.mu.Unlock()+ if l.closed.Load() {+ return "", errors.New("Runner login lease ended")+ }+ updated, err := l.manager.renew(ctx, l.source, l.snapshot)+ if err != nil {+ return "", err+ }+ l.snapshot = updated+ return updated.access, nil+}++func (l *runnerLoginLease) serveRefresh(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Cache-Control", "no-store")+ w.Header().Set("Content-Type", "application/json")+ if r.Method != http.MethodPost || r.URL.Path != "/runner-login/"+l.id+"/refresh" || l.closed.Load() {+ http.NotFound(w, r)+ return+ }+ raw, err := io.ReadAll(io.LimitReader(r.Body, 16<<10+1))+ var request struct {+ Grant string `json:"grant_type"`+ Nonce string `json:"refresh_token"`+ }+ if err != nil || len(raw) > 16<<10 || json.Unmarshal(raw, &request) != nil || request.Grant != "refresh_token" {+ w.WriteHeader(http.StatusBadRequest)+ _, _ = io.WriteString(w, `{"error":"invalid_request"}`)+ return+ }+ l.mu.Lock()+ defer l.mu.Unlock()+ if l.closed.Load() {+ http.NotFound(w, r)+ return+ }+ if cached := l.replies[request.Nonce]; cached != nil {+ _, _ = w.Write(cached) // Retrying a lost response never repeats the issuer exchange.+ return+ }+ stale, valid := l.requests[request.Nonce]+ if !valid {+ w.WriteHeader(http.StatusBadRequest)+ _, _ = io.WriteString(w, `{"error":"invalid_grant"}`)+ return+ }+ updated, err := l.manager.renew(r.Context(), l.source, stale)+ if err != nil {+ // Do not echo issuer bodies, token material or private filesystem paths.+ w.WriteHeader(http.StatusServiceUnavailable)+ _, _ = io.WriteString(w, `{"error":"temporarily_unavailable"}`)+ return+ }+ nonce, err := runnerLoginNonce()+ if err != nil {+ w.WriteHeader(http.StatusServiceUnavailable)+ return+ }+ var doc struct {+ Tokens struct {+ ID string `json:"id_token"`+ } `json:"tokens"`+ }+ _ = json.Unmarshal(updated.raw, &doc)+ reply, _ := json.Marshal(map[string]string{"access_token": updated.access, "id_token": doc.Tokens.ID, "refresh_token": nonce})+ // Bound replay history per task. The latest two generations cover a+ // transport retry; expired historical handles cannot start another refresh.+ if len(l.requests) >= 4 {+ l.requests = map[string]runnerLoginSnapshot{}+ l.replies = map[string][]byte{}+ }+ l.requests[nonce], l.replies[request.Nonce] = updated, reply+ l.snapshot = updated+ _, _ = w.Write(reply)+}++func bindRunnerLoginLease(command CommandSpec) CommandSpec {+ id := command.environment[runnerLoginLeaseEnv]+ delete(command.environment, runnerLoginLeaseEnv)+ if id == "" {+ return command+ }+ value, exists := runnerLoginLeases.Load(id)+ if !exists {+ return command+ }+ lease := value.(*runnerLoginLease)+ if lease.source.provider != command.Provider || lease.closed.Load() {+ return command+ }+ command.runnerLogin = lease+ if command.Provider != "claude-code" {+ return command+ }+ if valueAfter(command.Argv, "--input-format") == "stream-json" {+ return command+ }+ command.Argv = append([]string(nil), command.Argv...)+ // Provider invocation contracts put the print prompt last. Already+ // interactive conversations keep their caller-owned initialization/input.+ if len(command.Argv) > 1 && !strings.HasPrefix(command.Argv[len(command.Argv)-1], "-") {+ command.runnerLoginPrompt = command.Argv[len(command.Argv)-1]+ command.Argv = append([]string(nil), command.Argv[:len(command.Argv)-1]...)+ }+ command.Argv = append(dropArgWithValue(command.Argv, "--input-format"), "--input-format", "stream-json")+ command.runnerLoginInitialize = true+ return command+}++func valueAfter(argv []string, key string) string {+ for i, arg := range argv {+ if arg == key && i+1 < len(argv) {+ return argv[i+1]+ }+ if strings.HasPrefix(arg, key+"=") {+ return strings.TrimPrefix(arg, key+"=")+ }+ }+ return ""+}diff --git a/internal/runtime/runner_login_manager.go b/internal/runtime/runner_login_manager.gonew file mode 100644index 00000000..dc238178--- /dev/null+++ b/internal/runtime/runner_login_manager.go@@ -0,0 +1,582 @@+package runtime++import (+ "bytes"+ "context"+ "crypto/sha256"+ "encoding/base64"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "syscall"+ "time"+)++// A source is owned by the Runner. Sandbox credential files are never sources.+type runnerLoginSource struct {+ provider, path string+ origin string+ identity func([]byte) string+}++type runnerLoginSnapshot struct {+ raw []byte+ identity, access, refresh string+ expiry time.Time+}++type runnerLoginEntry struct {+ gate chan struct{}+ managedDigest string+}++type runnerLoginManager struct {+ stateDir string+ client *http.Client+ refresh func(context.Context, string, []byte) ([]byte, error)+ mu sync.Mutex+ entries map[string]*runnerLoginEntry+}++var nativeRunnerLogins = &runnerLoginManager{}++const claudeRunnerOAuthClientID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e" // gitleaks:allow public OAuth application ID shipped by the official Claude Code CLI.++func loginDigest(raw []byte) string {+ sum := sha256.Sum256(raw)+ return hex.EncodeToString(sum[:])+}++func fileRunnerLoginSource(login conversationLoginSpec, configDir string) runnerLoginSource {+ path := filepath.Join(configDir, login.file)+ if absolute, err := filepath.Abs(path); err == nil {+ path = absolute+ }+ origin := path+ if parent, err := filepath.EvalSymlinks(filepath.Dir(path)); err == nil {+ path = filepath.Join(parent, filepath.Base(path))+ }+ if resolved, err := filepath.EvalSymlinks(path); err == nil {+ path = resolved+ }+ provider := "codex"+ if login.binding == BindClaudeCode {+ provider = "claude-code"+ }+ source := runnerLoginSource{provider: provider, path: path, origin: origin}+ source.identity = func(raw []byte) string {+ if provider == "codex" {+ var doc struct {+ Tokens struct {+ ID string `json:"id_token"`+ Access string `json:"access_token"`+ Account string `json:"account_id"`+ } `json:"tokens"`+ }+ if json.Unmarshal(raw, &doc) != nil {+ return ""+ }+ id := jwtRunnerPrincipal(doc.Tokens.ID)+ if id == "" {+ id = jwtRunnerPrincipal(doc.Tokens.Access)+ }+ if id == "" || doc.Tokens.Account == "" {+ return ""+ }+ return id + "\x00" + doc.Tokens.Account+ }+ // This is trusted host metadata, never a sandbox .claude.json. An+ // absent anchor does not authorize adopting an external token change.+ for _, profile := range []string{filepath.Join(configDir, ".claude.json"), filepath.Join(filepath.Dir(configDir), ".claude.json")} {+ data, err := os.ReadFile(profile)+ if err != nil || len(data) > 1<<20 {+ continue+ }+ var doc struct {+ Account struct {+ User string `json:"accountUuid"`+ Org string `json:"organizationUuid"`+ } `json:"oauthAccount"`+ }+ if json.Unmarshal(data, &doc) == nil && doc.Account.User != "" {+ return doc.Account.User + "\x00" + doc.Account.Org+ }+ }+ return ""+ }+ return source+}++// JWTs are decoded here only from a trusted host source or a TLS-authenticated+// issuer response. This function must never validate sandbox-supplied tokens.+func jwtRunnerPrincipal(token string) string {+ parts := strings.Split(token, ".")+ if len(parts) != 3 {+ return ""+ }+ raw, err := base64.RawURLEncoding.DecodeString(parts[1])+ if err != nil {+ return ""+ }+ var claims struct {+ Subject string `json:"sub"`+ Auth struct {+ User string `json:"chatgpt_user_id"`+ } `json:"https://api.openai.com/auth"`+ }+ if json.Unmarshal(raw, &claims) != nil {+ return ""+ }+ if claims.Subject == "" {+ return claims.Auth.User+ }+ return claims.Subject + "\x00" + claims.Auth.User+}++func parseRunnerOAuth(provider string, raw []byte) (runnerLoginSnapshot, error) {+ snapshot := runnerLoginSnapshot{raw: bytes.Clone(raw)}+ var doc struct {+ Tokens struct {+ Access string `json:"access_token"`+ Refresh string `json:"refresh_token"`+ } `json:"tokens"`+ Claude struct {+ Access string `json:"accessToken"`+ Refresh string `json:"refreshToken"`+ Expiry int64 `json:"expiresAt"`+ } `json:"claudeAiOauth"`+ }+ if len(raw) > 1<<20 || json.Unmarshal(raw, &doc) != nil {+ return snapshot, errors.New("invalid Runner login")+ }+ switch provider {+ case "codex":+ snapshot.access, snapshot.refresh = doc.Tokens.Access, doc.Tokens.Refresh+ parts := strings.Split(snapshot.access, ".")+ if len(parts) == 3 {+ data, _ := base64.RawURLEncoding.DecodeString(parts[1])+ var claims struct {+ Expiry int64 `json:"exp"`+ }+ if json.Unmarshal(data, &claims) == nil && claims.Expiry > 0 {+ snapshot.expiry = time.Unix(claims.Expiry, 0)+ }+ }+ case "claude-code":+ snapshot.access, snapshot.refresh = doc.Claude.Access, doc.Claude.Refresh+ if doc.Claude.Expiry > 0 {+ snapshot.expiry = time.UnixMilli(doc.Claude.Expiry)+ }+ default:+ return snapshot, errors.New("unsupported managed Runner login")+ }+ if snapshot.access == "" || snapshot.refresh == "" {+ return snapshot, errors.New("Runner OAuth login has no token pair")+ }+ return snapshot, nil+}++func (source runnerLoginSource) read() (runnerLoginSnapshot, error) {+ if source.origin != "" {+ resolved, err := filepath.EvalSymlinks(source.origin)+ if err != nil {+ return runnerLoginSnapshot{}, err+ }+ if resolved != source.path {+ return runnerLoginSnapshot{}, errors.New("Runner login source changed; restart this task")+ }+ }+ raw, err := readRunnerLoginFile(filepath.Dir(source.path), filepath.Base(source.path))+ if err != nil {+ return runnerLoginSnapshot{}, err+ }+ snapshot, err := parseRunnerOAuth(source.provider, raw)+ if err == nil && source.identity != nil {+ snapshot.identity = source.identity(raw)+ }+ return snapshot, err+}++func (m *runnerLoginManager) entry(source runnerLoginSource) (*runnerLoginEntry, string, error) {+ m.mu.Lock()+ defer m.mu.Unlock()+ root := m.stateDir+ if root == "" {+ root = strings.TrimSpace(os.Getenv("AGENTFLOW_RUNNER_AUTH_DIR"))+ if root == "" {+ cache, err := os.UserCacheDir()+ if err != nil {+ return nil, "", err+ }+ root = filepath.Join(cache, "LoopForge", "runner-auth")+ }+ }+ if err := os.MkdirAll(root, 0700); err != nil {+ return nil, "", err+ }+ info, err := os.Lstat(root)+ if err != nil || !info.IsDir() {+ return nil, "", errors.New("Runner auth state must be a private directory")+ }+ if err := os.Chmod(root, 0700); err != nil {+ return nil, "", err+ }+ if m.entries == nil {+ m.entries = make(map[string]*runnerLoginEntry)+ }+ key := loginDigest([]byte(source.provider + "\x00" + source.path))+ e := m.entries[key]+ if e == nil {+ e = &runnerLoginEntry{gate: make(chan struct{}, 1)}+ m.entries[key] = e+ }+ return e, filepath.Join(root, key), nil+}++func (m *runnerLoginManager) locked(ctx context.Context, source runnerLoginSource, fn func(*runnerLoginEntry, string) (runnerLoginSnapshot, error)) (runnerLoginSnapshot, error) {+ e, path, err := m.entry(source)+ if err != nil {+ return runnerLoginSnapshot{}, err+ }+ select {+ case e.gate <- struct{}{}:+ case <-ctx.Done():+ return runnerLoginSnapshot{}, ctx.Err()+ }+ defer func() { <-e.gate }()+ file, err := os.OpenFile(path+".lock", os.O_CREATE|os.O_RDWR, 0600)+ if err != nil {+ return runnerLoginSnapshot{}, err+ }+ defer file.Close()+ for {+ if err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil {+ break+ }+ if !errors.Is(err, syscall.EWOULDBLOCK) && !errors.Is(err, syscall.EAGAIN) {+ return runnerLoginSnapshot{}, err+ }+ select {+ case <-ctx.Done():+ return runnerLoginSnapshot{}, ctx.Err()+ case <-time.After(25 * time.Millisecond):+ }+ }+ defer syscall.Flock(int(file.Fd()), syscall.LOCK_UN)+ return fn(e, path+".pending")+}++type runnerLoginPending struct {+ Expected string `json:"expected"`+ Identity string `json:"identity"`+ Login json.RawMessage `json:"login,omitempty"`+}++func writeRunnerLoginPending(path string, pending runnerLoginPending) error {+ return writeRunnerLoginState(path, pending)+}++func writeRunnerLoginState(path string, value any) error {+ raw, err := json.Marshal(value)+ if err != nil {+ return err+ }+ f, err := os.CreateTemp(filepath.Dir(path), ".runner-auth-*")+ if err != nil {+ return err+ }+ defer os.Remove(f.Name())+ defer f.Close()+ if err := f.Chmod(0600); err != nil {+ return err+ }+ if _, err := f.Write(raw); err != nil {+ return err+ }+ if err := f.Sync(); err != nil {+ return err+ }+ if err := f.Close(); err != nil {+ return err+ }+ if err := os.Rename(f.Name(), path); err != nil {+ return err+ }+ dir, err := os.Open(filepath.Dir(path))+ if err != nil {+ return err+ }+ defer dir.Close()+ return dir.Sync()+}++type runnerLoginReceipt struct {+ Digest string `json:"digest"`+ Identity string `json:"identity"`+}++func runnerLoginReceiptPath(pendingPath string) string {+ return strings.TrimSuffix(pendingPath, ".pending") + ".receipt"+}++func recordRunnerLogin(e *runnerLoginEntry, pendingPath string, snapshot runnerLoginSnapshot) error {+ receipt := runnerLoginReceipt{Digest: loginDigest(snapshot.raw), Identity: snapshot.identity}+ if err := writeRunnerLoginState(runnerLoginReceiptPath(pendingPath), receipt); err != nil {+ return errors.New("cannot record canonical Runner refresh")+ }+ e.managedDigest = receipt.Digest+ // The receipt contains only a hash. Do not retain a second live refresh+ // token after the host file has been durably updated.+ if err := os.Remove(pendingPath); err != nil && !errors.Is(err, os.ErrNotExist) {+ return err+ }+ return nil+}++func (m *runnerLoginManager) current(ctx context.Context, source runnerLoginSource) (runnerLoginSnapshot, error) {+ return m.locked(ctx, source, func(e *runnerLoginEntry, pendingPath string) (runnerLoginSnapshot, error) {+ current, _, err := m.recover(source, e, pendingPath)+ return current, err+ })+}++// A journal without Login means an exchange may have consumed the old refresh+// token. Access remains usable, but that exact pair must not be exchanged again.+func (m *runnerLoginManager) recover(source runnerLoginSource, e *runnerLoginEntry, pendingPath string) (runnerLoginSnapshot, bool, error) {+ current, err := source.read()+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ _ = os.Remove(pendingPath)+ _ = os.Remove(runnerLoginReceiptPath(pendingPath))+ e.managedDigest = ""+ }+ return current, false, err+ } // A logout must never resurrect a pending login.+ if raw, err := os.ReadFile(runnerLoginReceiptPath(pendingPath)); err == nil {+ var receipt runnerLoginReceipt+ if len(raw) > 16<<10 || json.Unmarshal(raw, &receipt) != nil {+ return current, false, errors.New("invalid Runner refresh receipt")+ }+ if receipt.Digest == loginDigest(current.raw) && receipt.Identity == current.identity {+ e.managedDigest = receipt.Digest+ }+ } else if !errors.Is(err, os.ErrNotExist) {+ return current, false, errors.New("cannot read Runner refresh receipt")+ }+ data, err := os.ReadFile(pendingPath)+ if errors.Is(err, os.ErrNotExist) {+ return current, false, nil+ }+ if err != nil || len(data) > 2<<20 {+ return current, false, errors.New("cannot read pending Runner refresh")+ }+ var pending runnerLoginPending+ if json.Unmarshal(data, &pending) != nil {+ return current, false, errors.New("invalid pending Runner refresh")+ }+ if bytes.Equal(current.raw, pending.Login) {+ return current, false, recordRunnerLogin(e, pendingPath, current)+ }+ if pending.Expected != loginDigest(current.raw) || pending.Identity != current.identity {+ return current, false, nil+ }+ if len(pending.Login) == 0 {+ return current, true, nil+ }+ if _, err := parseRunnerOAuth(source.provider, pending.Login); err != nil {+ return current, false, err+ }+ if pending.Identity != "" && source.identity(pending.Login) != pending.Identity {+ return current, false, errors.New("pending Runner refresh belongs to another account")+ }+ if err := replaceRunnerLoginFile(filepath.Dir(source.path), filepath.Base(source.path), current.raw, pending.Login); err != nil {+ return current, false, err+ }+ updated, err := source.read()+ if err == nil && bytes.Equal(updated.raw, pending.Login) {+ err = recordRunnerLogin(e, pendingPath, updated)+ }+ return updated, false, err+}++func (m *runnerLoginManager) renew(ctx context.Context, source runnerLoginSource, stale runnerLoginSnapshot) (runnerLoginSnapshot, error) {+ return m.locked(ctx, source, func(e *runnerLoginEntry, pendingPath string) (runnerLoginSnapshot, error) {+ current, uncertain, err := m.recover(source, e, pendingPath)+ if err != nil {+ return current, err+ }+ if current.identity != stale.identity {+ return current, errors.New("Runner account changed; restart this task")+ }+ if !bytes.Equal(current.raw, stale.raw) {+ if current.identity == "" && e.managedDigest != loginDigest(current.raw) {+ return current, errors.New("Runner login changed without an account anchor; restart this task")+ }+ return current, nil // Another task or the host refreshed first.+ }+ if uncertain {+ return current, errors.New("Runner refresh outcome is unknown; update the host login before retrying")+ }+ if err := ctx.Err(); err != nil {+ return current, err+ }+ if err := writeRunnerLoginPending(pendingPath, runnerLoginPending{Expected: loginDigest(current.raw), Identity: current.identity}); err != nil {+ return current, errors.New("cannot journal Runner refresh")+ }+ // Once an exchange has started, a cancelled sandbox must not discard a+ // successful rotation. Bound the trusted refresh independently.+ refreshCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)+ defer cancel()+ refresh := m.refresh+ if refresh == nil {+ refresh = m.refreshOAuth+ }+ canonical, err := refresh(refreshCtx, source.provider, current.raw)+ if err != nil {+ var rejected *runnerRefreshRejected+ if errors.As(err, &rejected) {+ _ = os.Remove(pendingPath) // The issuer definitively rejected the exchange.+ }+ return runnerLoginSnapshot{}, err+ }+ pending := runnerLoginPending{Expected: loginDigest(current.raw), Identity: current.identity, Login: canonical}+ if err := writeRunnerLoginPending(pendingPath, pending); err != nil {+ return runnerLoginSnapshot{}, errors.New("cannot preserve refreshed Runner login")+ }+ if _, err := parseRunnerOAuth(source.provider, canonical); err != nil {+ return runnerLoginSnapshot{}, err+ }+ if current.identity != "" && source.identity(canonical) != current.identity {+ return runnerLoginSnapshot{}, errors.New("refreshed Runner login belongs to another account")+ }+ if _, err := source.read(); err != nil {+ return runnerLoginSnapshot{}, errors.New("Runner login source changed during refresh; response retained privately")+ }+ if err := replaceRunnerLoginFile(filepath.Dir(source.path), filepath.Base(source.path), current.raw, canonical); err != nil {+ return runnerLoginSnapshot{}, errors.New("refreshed Runner login is pending recovery")+ }+ updated, err := source.read()+ if err != nil {+ return updated, errors.New("Runner login removed during refresh")+ }+ if !bytes.Equal(updated.raw, canonical) {+ if updated.identity == "" || updated.identity != current.identity {+ return updated, errors.New("Runner account changed during refresh")+ }+ return updated, nil // Keep the received pair private; host stays authoritative.+ }+ return updated, recordRunnerLogin(e, pendingPath, updated)+ })+}++type runnerRefreshRejected struct{ error }++func (m *runnerLoginManager) refreshOAuth(ctx context.Context, provider string, original []byte) ([]byte, error) {+ snapshot, err := parseRunnerOAuth(provider, original)+ if err != nil {+ return nil, err+ }+ endpoint, clientID := "https://auth.openai.com/oauth/token", "app_EMoamEEZ73f0CkXaXp7hrann"+ body := map[string]any{"grant_type": "refresh_token", "refresh_token": snapshot.refresh}+ if provider == "claude-code" {+ endpoint, clientID = "https://platform.claude.com/v1/oauth/token", claudeRunnerOAuthClientID+ var doc struct {+ OAuth struct {+ Scopes []string `json:"scopes"`+ } `json:"claudeAiOauth"`+ }+ _ = json.Unmarshal(original, &doc)+ if len(doc.OAuth.Scopes) > 0 {+ body["scope"] = strings.Join(doc.OAuth.Scopes, " ")+ }+ } else {+ var doc struct {+ Tokens struct {+ Provenance *struct {+ Issuer string `json:"issuer"`+ Client string `json:"client_id"`+ } `json:"oauth_provenance"`+ } `json:"tokens"`+ }+ _ = json.Unmarshal(original, &doc)+ if provenance := doc.Tokens.Provenance; provenance != nil && provenance.Issuer != "" && provenance.Client != "" {+ endpoint, clientID = strings.TrimRight(provenance.Issuer, "/")+"/oauth/token", provenance.Client+ } else if override := strings.TrimSpace(os.Getenv("CODEX_APP_SERVER_LOGIN_CLIENT_ID")); override != "" {+ clientID = override+ }+ if override := strings.TrimSpace(os.Getenv("CODEX_REFRESH_TOKEN_URL_OVERRIDE")); override != "" {+ endpoint = override // Trusted Runner environment, never a sandbox value.+ }+ }+ body["client_id"] = clientID+ raw, _ := json.Marshal(body)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(raw))+ if err != nil {+ return nil, &runnerRefreshRejected{errors.New("invalid Runner OAuth endpoint")}+ }+ req.Header.Set("Content-Type", "application/json")+ client := m.client+ if client == nil {+ client = &http.Client{Timeout: 25 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}+ }+ resp, err := client.Do(req)+ if err != nil {+ return nil, errors.New("Runner login refresh unavailable; credentials retained")+ }+ defer resp.Body.Close()+ data, err := io.ReadAll(io.LimitReader(resp.Body, (1<<20)+1))+ if err != nil || len(data) > 1<<20 || resp.StatusCode != http.StatusOK {+ failure := fmt.Errorf("Runner login refresh rejected (HTTP %d); credentials retained", resp.StatusCode)+ if err == nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusRequestTimeout {+ return nil, &runnerRefreshRejected{failure}+ }+ return nil, failure+ }+ var tokens struct {+ Access string `json:"access_token"`+ Refresh string `json:"refresh_token"`+ ID string `json:"id_token"`+ Expires int64 `json:"expires_in"`+ Scope string `json:"scope"`+ }+ if json.Unmarshal(data, &tokens) != nil || tokens.Access == "" {+ return nil, errors.New("invalid Runner OAuth response")+ }+ var doc map[string]json.RawMessage+ _ = json.Unmarshal(original, &doc)+ key, accessKey, refreshKey := "tokens", "access_token", "refresh_token"+ if provider == "claude-code" {+ key, accessKey, refreshKey = "claudeAiOauth", "accessToken", "refreshToken"+ }+ var values map[string]json.RawMessage+ if json.Unmarshal(doc[key], &values) != nil {+ return nil, errors.New("invalid Runner OAuth record")+ }+ values[accessKey], _ = json.Marshal(tokens.Access)+ if tokens.Refresh != "" {+ values[refreshKey], _ = json.Marshal(tokens.Refresh)+ }+ if provider == "codex" {+ if tokens.ID != "" {+ values["id_token"], _ = json.Marshal(tokens.ID)+ }+ doc["last_refresh"], _ = json.Marshal(time.Now().UTC().Format(time.RFC3339Nano))+ } else {+ if tokens.Expires <= 0 {+ return nil, errors.New("Runner OAuth response has no expiry")+ }+ values["expiresAt"], _ = json.Marshal(time.Now().Add(time.Duration(tokens.Expires) * time.Second).UnixMilli())+ if tokens.Scope != "" {+ values["scopes"], _ = json.Marshal(strings.Fields(tokens.Scope))+ }+ }+ doc[key], _ = json.Marshal(values)+ return json.Marshal(doc)+}diff --git a/internal/runtime/runner_login_manager_test.go b/internal/runtime/runner_login_manager_test.gonew file mode 100644index 00000000..3e8a6164--- /dev/null+++ b/internal/runtime/runner_login_manager_test.go@@ -0,0 +1,578 @@+package runtime++import (+ "bytes"+ "context"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++func managedLoginFixture(t *testing.T, provider string) (runnerLoginSource, []byte, []byte) {+ t.Helper()+ root := t.TempDir()+ jwt := func(user string, generation int) string {+ claims, _ := json.Marshal(map[string]any{"sub": user, "jti": generation,+ "exp": time.Now().Add(time.Hour).Unix(), "https://api.openai.com/auth": map[string]string{"chatgpt_user_id": user}})+ return "header." + base64.RawURLEncoding.EncodeToString(claims) + ".signature"+ }+ makeLogin := func(generation int) []byte {+ var doc any+ if provider == "codex" {+ doc = map[string]any{"auth_mode": "chatgpt", "tokens": map[string]string{+ "id_token": jwt("user-a", generation), "account_id": "account-a", "access_token": jwt("user-a", generation), "refresh_token": fmt.Sprintf("host-refresh-%d", generation)}}+ } else {+ doc = map[string]any{"claudeAiOauth": map[string]any{"accessToken": fmt.Sprintf("claude-access-%d", generation),+ "refreshToken": fmt.Sprintf("host-refresh-%d", generation), "expiresAt": time.Now().Add(time.Hour).UnixMilli(), "subscriptionType": "test"}}+ }+ raw, _ := json.Marshal(doc)+ return raw+ }+ login, _ := runnerLoginSpec(provider)+ source := fileRunnerLoginSource(login, root)+ if provider == "claude-code" {+ if err := os.WriteFile(filepath.Join(root, ".claude.json"), []byte(`{"oauthAccount":{"accountUuid":"user-a","organizationUuid":"org-a"}}`), 0600); err != nil {+ t.Fatal(err)+ }+ }+ original, renewed := makeLogin(0), makeLogin(1)+ if err := os.WriteFile(source.path, original, 0600); err != nil {+ t.Fatal(err)+ }+ return source, original, renewed+}++func TestRunnerLoginManagerCoalescesConcurrentRefresh(t *testing.T) {+ for _, provider := range []string{"codex", "claude-code"} {+ t.Run(provider, func(t *testing.T) {+ source, original, renewed := managedLoginFixture(t, provider)+ var calls atomic.Int32+ manager := &runnerLoginManager{stateDir: t.TempDir(), refresh: func(context.Context, string, []byte) ([]byte, error) { calls.Add(1); return renewed, nil }}+ stale, err := manager.current(context.Background(), source)+ if err != nil {+ t.Fatal(err)+ }+ var workers sync.WaitGroup+ for range 12 {+ workers.Add(1)+ go func() {+ defer workers.Done()+ got, err := manager.renew(context.Background(), source, stale)+ if err != nil || !bytes.Equal(got.raw, renewed) {+ t.Error("concurrent refresh did not reuse the authoritative pair")+ }+ }()+ }+ workers.Wait()+ if calls.Load() != 1 {+ t.Fatalf("issuer calls=%d", calls.Load())+ }+ current, _ := os.ReadFile(source.path)+ if bytes.Equal(current, original) || !bytes.Equal(current, renewed) {+ t.Fatal("host did not receive the renewed pair")+ }+ })+ }+}++func TestRunnerLoginManagerCoordinatesInstances(t *testing.T) {+ source, _, renewed := managedLoginFixture(t, "codex")+ state := t.TempDir()+ var calls atomic.Int32+ refresh := func(context.Context, string, []byte) ([]byte, error) {+ calls.Add(1)+ time.Sleep(40 * time.Millisecond)+ return renewed, nil+ }+ a, b := &runnerLoginManager{stateDir: state, refresh: refresh}, &runnerLoginManager{stateDir: state, refresh: refresh}+ stale, err := a.current(context.Background(), source)+ if err != nil {+ t.Fatal(err)+ }+ var wg sync.WaitGroup+ for _, manager := range []*runnerLoginManager{a, b} {+ wg.Add(1)+ go func(m *runnerLoginManager) {+ defer wg.Done()+ if _, err := m.renew(context.Background(), source, stale); err != nil {+ t.Error(err)+ }+ }(manager)+ }+ wg.Wait()+ if calls.Load() != 1 {+ t.Fatalf("issuer exchanges = %d", calls.Load())+ }+}++func TestRunnerLoginManagerRecoversBeforeRetry(t *testing.T) {+ source, original, renewed := managedLoginFixture(t, "codex")+ manager := &runnerLoginManager{stateDir: t.TempDir(), refresh: func(context.Context, string, []byte) ([]byte, error) {+ t.Error("consumed refresh token redeemed again")+ return nil, errors.New("unexpected exchange")+ }}+ stale, _ := manager.current(context.Background(), source)+ _, path, _ := manager.entry(source)+ if err := writeRunnerLoginPending(path+".pending", runnerLoginPending{Expected: loginDigest(original), Identity: stale.identity, Login: renewed}); err != nil {+ t.Fatal(err)+ }+ got, err := manager.renew(context.Background(), source, stale)+ if err != nil || !bytes.Equal(got.raw, renewed) {+ t.Fatal("renew did not recover the received pair first")+ }+}++func TestRunnerLoginManagerReceiptWithoutAccountMetadata(t *testing.T) {+ source, _, renewed := managedLoginFixture(t, "claude-code")+ source.identity = func([]byte) string { return "" }+ state := t.TempDir()+ first := &runnerLoginManager{stateDir: state, refresh: func(context.Context, string, []byte) ([]byte, error) { return renewed, nil }}+ stale, err := first.current(context.Background(), source)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := first.renew(context.Background(), source, stale); err != nil {+ t.Fatal(err)+ }+ restarted := &runnerLoginManager{stateDir: state, refresh: func(context.Context, string, []byte) ([]byte, error) {+ t.Error("unnecessary second exchange")+ return nil, errors.New("unexpected")+ }}+ got, err := restarted.renew(context.Background(), source, stale)+ if err != nil || !bytes.Equal(got.raw, renewed) {+ t.Fatal("another manager could not recognize its canonical receipt")+ }+ // A host edit without a receipt still needs a new task, even if the JSON+ // schema is unchanged. There is no account identity to safely adopt it.+ foreign := bytes.ReplaceAll(renewed, []byte("claude-access-1"), []byte("foreign-access"))+ if err := os.WriteFile(source.path, foreign, 0600); err != nil {+ t.Fatal(err)+ }+ if _, err := restarted.renew(context.Background(), source, stale); err == nil {+ t.Fatal("unanchored external change was adopted")+ }+}++type runnerOAuthTransport func(*http.Request) (*http.Response, error)++func (f runnerOAuthTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func TestRunnerLoginOAuthAdapter(t *testing.T) {+ for _, provider := range []string{"codex", "claude-code"} {+ for _, rotate := range []bool{false, true} {+ t.Run(fmt.Sprintf("%s/rotate=%v", provider, rotate), func(t *testing.T) {+ source, original, renewed := managedLoginFixture(t, provider)+ before, _ := parseRunnerOAuth(provider, original)+ after, _ := parseRunnerOAuth(provider, renewed)+ manager := &runnerLoginManager{stateDir: t.TempDir(), client: &http.Client{Transport: runnerOAuthTransport(func(req *http.Request) (*http.Response, error) {+ if req.Method != "POST" || req.URL.Scheme != "https" {+ t.Error("OAuth exchange used an unexpected transport")+ }+ var request map[string]any+ if err := json.NewDecoder(req.Body).Decode(&request); err != nil {+ t.Error(err)+ }+ if request["refresh_token"] != before.refresh || request["grant_type"] != "refresh_token" || request["client_id"] == "" {+ t.Error("exchange did not use the host grant")+ }+ response := map[string]any{"access_token": after.access, "expires_in": 3600, "scope": "user:inference user:profile"}+ if rotate {+ response["refresh_token"] = after.refresh+ }+ body, _ := json.Marshal(response)+ return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(body)), Header: make(http.Header)}, nil+ })}}+ stale, err := manager.current(context.Background(), source)+ if err != nil {+ t.Fatal(err)+ }+ got, err := manager.renew(context.Background(), source, stale)+ if err != nil {+ t.Fatal(err)+ }+ wantRefresh := before.refresh+ if rotate {+ wantRefresh = after.refresh+ }+ if got.access != after.access || got.refresh != wantRefresh {+ t.Fatal("canonical pair was not preserved")+ }+ if provider == "claude-code" && time.Until(got.expiry) < 59*time.Minute {+ t.Fatal("Claude expiry was not advanced")+ }+ _, path, _ := manager.entry(source)+ if _, err := os.Stat(path + ".pending"); !os.IsNotExist(err) {+ t.Fatal("completed exchange retained a second refresh token")+ }+ receipt, err := os.ReadFile(path + ".receipt")+ if err != nil || bytes.Contains(receipt, []byte("host-refresh")) {+ t.Fatal("receipt is missing or contains refresh material")+ }+ })+ }+ }+}++func TestRunnerLoginRejectsIncompleteOAuth(t *testing.T) {+ for _, provider := range []string{"codex", "claude-code"} {+ t.Run(provider, func(t *testing.T) {+ login, _ := runnerLoginSpec(provider)+ host := t.TempDir()+ root := t.TempDir()+ t.Setenv(login.configEnv, host)+ t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "")+ raw := `{"tokens":{"refresh_token":"host-only-refresh"}}`+ if provider == "claude-code" {+ raw = `{"claudeAiOauth":{"refreshToken":"host-only-refresh"}}`+ }+ if err := os.WriteFile(filepath.Join(host, login.file), []byte(raw), 0600); err != nil {+ t.Fatal(err)+ }+ if cleanup, _, err := prepareConversationRunnerLogin(root, login, true); err == nil {+ if cleanup != nil {+ _ = cleanup()+ }+ t.Fatal("incomplete OAuth grant entered the sandbox")+ }+ if _, err := os.Stat(filepath.Join(root, "home", login.dir, login.file)); !os.IsNotExist(err) {+ t.Fatal("host refresh token was staged")+ }+ })+ }+}++func TestRunnerLoginManagerUncertainExchange(t *testing.T) {+ for _, definitive := range []bool{false, true} {+ t.Run(fmt.Sprintf("definitive=%v", definitive), func(t *testing.T) {+ source, original, _ := managedLoginFixture(t, "codex")+ var calls atomic.Int32+ manager := &runnerLoginManager{stateDir: t.TempDir(), refresh: func(context.Context, string, []byte) ([]byte, error) {+ calls.Add(1)+ err := errors.New("no response")+ if definitive {+ return nil, &runnerRefreshRejected{err}+ }+ return nil, err+ }}+ stale, _ := manager.current(context.Background(), source)+ for range 2 {+ if _, err := manager.renew(context.Background(), source, stale); err == nil {+ t.Fatal("exchange unexpectedly succeeded")+ }+ }+ want := int32(1)+ if definitive {+ want = 2+ }+ if calls.Load() != want {+ t.Fatalf("exchanges=%d want=%d", calls.Load(), want)+ }+ // A restart preserves the uncertain marker and still permits reading+ // the existing access token. A logout is never resurrected.+ restarted := &runnerLoginManager{stateDir: manager.stateDir, refresh: manager.refresh}+ current, err := restarted.current(context.Background(), source)+ if err != nil || !bytes.Equal(current.raw, original) {+ t.Fatal("refresh failure damaged host credentials")+ }+ if !definitive {+ if _, err := restarted.renew(context.Background(), source, current); err == nil || calls.Load() != 1 {+ t.Fatal("restart retried an uncertain exchange")+ }+ }+ })+ }+}++func TestRunnerLoginLeaseKeepsRefreshTokenOnHost(t *testing.T) {+ source, _, renewed := managedLoginFixture(t, "codex")+ var calls atomic.Int32+ manager := &runnerLoginManager{stateDir: t.TempDir(), refresh: func(context.Context, string, []byte) ([]byte, error) { calls.Add(1); return renewed, nil }}+ var leases []*runnerLoginLease+ for range 3 {+ lease, err := newRunnerLoginLease(context.Background(), manager, source, false)+ if err != nil {+ t.Fatal(err)+ }+ defer lease.close()+ leases = append(leases, lease)+ credential, err := lease.credential()+ if err != nil || bytes.Contains(credential, []byte("host-refresh")) {+ t.Fatal("host refresh token entered a private HOME")+ }+ }+ request := func(lease *runnerLoginLease, nonce string) ([]byte, int, error) {+ body, _ := json.Marshal(map[string]string{"grant_type": "refresh_token", "refresh_token": nonce})+ resp, err := http.Post(lease.endpoint, "application/json", bytes.NewReader(body))+ if err != nil {+ return nil, 0, err+ }+ defer resp.Body.Close()+ var result json.RawMessage+ err = json.NewDecoder(resp.Body).Decode(&result)+ return result, resp.StatusCode, err+ }+ var workers sync.WaitGroup+ for _, lease := range leases {+ workers.Add(1)+ go func(l *runnerLoginLease) {+ defer workers.Done()+ raw, status, err := request(l, l.id)+ if err != nil || status != 200 || bytes.Contains(raw, []byte("host-refresh")) {+ t.Error("lease refresh failed or exposed a host token")+ }+ }(lease)+ }+ workers.Wait()+ if calls.Load() != 1 {+ t.Fatalf("issuer calls=%d", calls.Load())+ }+ a, status, err := request(leases[0], leases[0].id)+ if err != nil || status != 200 {+ t.Fatal("lost-response replay failed")+ }+ b, status, err := request(leases[0], leases[0].id)+ if err != nil || status != 200 || !bytes.Equal(a, b) || calls.Load() != 1 {+ t.Fatal("replay repeated the exchange or changed its response")+ }+ _, status, err = request(leases[0], "host-refresh-0")+ if err != nil || status != 400 || calls.Load() != 1 {+ t.Fatal("a sandbox supplied its own upstream refresh token")+ }+}++func TestRunnerLoginPendingRecovery(t *testing.T) {+ for _, scenario := range []string{"recover", "logout", "other account"} {+ t.Run(scenario, func(t *testing.T) {+ source, original, renewed := managedLoginFixture(t, "codex")+ manager := &runnerLoginManager{stateDir: t.TempDir()}+ _, path, err := manager.entry(source)+ if err != nil {+ t.Fatal(err)+ }+ if err := writeRunnerLoginPending(path+".pending", runnerLoginPending{Expected: loginDigest(original), Identity: source.identity(original), Login: renewed}); err != nil {+ t.Fatal(err)+ }+ switch scenario {+ case "logout":+ if err := os.Remove(source.path); err != nil {+ t.Fatal(err)+ }+ case "other account":+ if err := os.WriteFile(source.path, bytes.ReplaceAll(original, []byte("account-a"), []byte("account-b")), 0600); err != nil {+ t.Fatal(err)+ }+ }+ got, err := manager.current(context.Background(), source)+ if scenario == "recover" && (err != nil || !bytes.Equal(got.raw, renewed)) {+ t.Fatal("durable response not recovered")+ }+ if scenario == "logout" {+ if err == nil {+ t.Fatal("logout resurrected")+ }+ if _, err := os.Stat(source.path); !os.IsNotExist(err) {+ t.Fatal("logout file recreated")+ }+ }+ if scenario == "other account" && (err != nil || !bytes.Contains(got.raw, []byte("account-b"))) {+ t.Fatal("pending refresh replaced another account")+ }+ })+ }+}++func TestRunnerLoginRefreshSurvivesCallerCancellation(t *testing.T) {+ source, _, renewed := managedLoginFixture(t, "codex")+ started, release := make(chan struct{}), make(chan struct{})+ manager := &runnerLoginManager{stateDir: t.TempDir(), refresh: func(ctx context.Context, _ string, _ []byte) ([]byte, error) {+ close(started)+ <-release+ if ctx.Err() != nil {+ return nil, ctx.Err()+ }+ return renewed, nil+ }}+ stale, err := manager.current(context.Background(), source)+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() { _, err := manager.renew(ctx, source, stale); done <- err }()+ <-started+ cancel()+ close(release)+ if err := <-done; err != nil {+ t.Fatal(err)+ }+ raw, _ := os.ReadFile(source.path)+ if !bytes.Equal(raw, renewed) {+ t.Fatal("cancellation lost a rotated pair")+ }+}++func TestRunnerLoginDoesNotAdoptAnotherAccount(t *testing.T) {+ source, _, renewed := managedLoginFixture(t, "codex")+ manager := &runnerLoginManager{stateDir: t.TempDir(), refresh: func(context.Context, string, []byte) ([]byte, error) {+ t.Fatal("unexpected issuer request")+ return nil, nil+ }}+ stale, err := manager.current(context.Background(), source)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(source.path, bytes.ReplaceAll(renewed, []byte("account-a"), []byte("account-b")), 0600); err != nil {+ t.Fatal(err)+ }+ if _, err := manager.renew(context.Background(), source, stale); err == nil {+ t.Fatal("adopted another host account")+ }+}++func TestRunnerLoginSourceAliasChanges(t *testing.T) {+ for _, scenario := range []string{"logout", "retarget", "logout-during-exchange", "retarget-during-exchange"} {+ t.Run(scenario, func(t *testing.T) {+ target, original, renewed := managedLoginFixture(t, "codex")+ config := t.TempDir()+ login, _ := runnerLoginSpec("codex")+ alias := filepath.Join(config, login.file)+ if err := os.Symlink(target.path, alias); err != nil {+ t.Fatal(err)+ }+ source := fileRunnerLoginSource(login, config)+ change := func() {+ if err := os.Remove(alias); err != nil {+ t.Fatal(err)+ }+ if strings.HasPrefix(scenario, "retarget") {+ other, _, _ := managedLoginFixture(t, "codex")+ if err := os.Symlink(other.path, alias); err != nil {+ t.Fatal(err)+ }+ }+ }+ manager := &runnerLoginManager{stateDir: t.TempDir(), refresh: func(context.Context, string, []byte) ([]byte, error) {+ if !strings.HasSuffix(scenario, "during-exchange") {+ t.Error("detached source refreshed")+ return nil, errors.New("unexpected")+ }+ change()+ return renewed, nil+ }}+ stale, err := manager.current(context.Background(), source)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.HasSuffix(scenario, "during-exchange") {+ change()+ }+ if _, err := manager.renew(context.Background(), source, stale); err == nil {+ t.Fatal("continued using a detached login target")+ }+ got, err := os.ReadFile(target.path)+ if err != nil || !bytes.Equal(got, original) {+ t.Fatal("detached host source changed")+ }+ })+ }+}++func TestManagedClaudeBridge(t *testing.T) {+ source, _, renewed := managedLoginFixture(t, "claude-code")+ manager := &runnerLoginManager{stateDir: t.TempDir(), refresh: func(context.Context, string, []byte) ([]byte, error) { return renewed, nil }}+ lease, err := newRunnerLoginLease(context.Background(), manager, source, false)+ if err != nil {+ t.Fatal(err)+ }+ defer lease.close()+ root := t.TempDir()+ bin := filepath.Join(root, "claude")+ script := `#!/usr/bin/env python3+import sys,json+for line in sys.stdin:+ x=json.loads(line)+ if x.get('type')=='control_request':+ print(json.dumps({'type':'control_response','response':{'subtype':'success','request_id':x['request_id']}}),flush=True)+ elif x.get('type')=='user':+ assert x['message']['content']=='original task prompt'+ print(json.dumps({'type':'control_request','request_id':'refresh-one','request':{'subtype':'oauth_token_refresh'}}),flush=True)+ elif x.get('type')=='control_response':+ assert x['response']['response']['accessToken']=='claude-access-1'+ print(json.dumps({'type':'result','is_error':False,'result':'bridge-ok'}),flush=True)+ break+`+ if err := os.WriteFile(bin, []byte(script), 0700); err != nil {+ t.Fatal(err)+ }+ command := WithCommandEnvironment(CommandSpec{Provider: "claude-code", Argv: []string{bin, "-p", "original task prompt"}}, lease.environment())+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ out, err := (&localSandbox{workspace: root}).Exec(ctx, command, nil)+ if err != nil || !strings.Contains(out, "bridge-ok") || strings.Contains(out, "oauth_token_refresh") || strings.Contains(out, "claude-access-1") {+ t.Fatalf("managed bridge failed or leaked control messages: %v", err)+ }+}++func TestManagedLoginSandboxReplacement(t *testing.T) {+ for _, provider := range []string{"codex", "claude-code"} {+ for _, mutation := range []string{"whole-account", "refresh-only", "forged-identity"} {+ t.Run(provider+"/"+mutation, func(t *testing.T) {+ source, original, _ := managedLoginFixture(t, provider)+ login, _ := runnerLoginSpec(provider)+ t.Setenv(login.configEnv, filepath.Dir(source.path))+ t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "")+ previous := nativeRunnerLogins+ nativeRunnerLogins = &runnerLoginManager{stateDir: t.TempDir(), refresh: func(context.Context, string, []byte) ([]byte, error) {+ t.Error("sandbox caused upstream exchange")+ return nil, errors.New("unexpected")+ }}+ defer func() { nativeRunnerLogins = previous }()+ root := t.TempDir()+ cleanup, _, err := prepareConversationRunnerLogin(root, login, true)+ if err != nil {+ t.Fatal(err)+ }+ var doc map[string]any+ _ = json.Unmarshal(original, &doc)+ if provider == "codex" {+ tokens := doc["tokens"].(map[string]any)+ tokens["refresh_token"] = "foreign-refresh"+ if mutation != "refresh-only" {+ tokens["access_token"] = "foreign-access"+ tokens["id_token"] = "forged-id"+ }+ if mutation == "whole-account" {+ tokens["account_id"] = "another-account"+ }+ } else {+ tokens := doc["claudeAiOauth"].(map[string]any)+ tokens["refreshToken"] = "foreign-refresh"+ if mutation != "refresh-only" {+ tokens["accessToken"] = "foreign-access"+ }+ }+ candidate, _ := json.Marshal(doc)+ if err := os.WriteFile(filepath.Join(root, "home", login.dir, login.file), candidate, 0600); err != nil {+ t.Fatal(err)+ }+ if err := cleanup(); err != nil {+ t.Fatal(err)+ }+ got, err := os.ReadFile(source.path)+ if err != nil || !bytes.Equal(got, original) {+ t.Fatal("sandbox replacement entered host credentials")+ }+ })+ }+ }+}diff --git a/internal/runtime/runner_login_paths_test.go b/internal/runtime/runner_login_paths_test.gonew file mode 100644index 00000000..2ab6b96f--- /dev/null+++ b/internal/runtime/runner_login_paths_test.go@@ -0,0 +1,188 @@+package runtime++import (+ "bytes"+ "context"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "agentflow/internal/domain"+)++// Exercise the same preparation, process-pool and Sandbox.Exec boundaries as+// real tasks. The CLI fixture forces renewal and then plants an untrusted token+// in its HOME; only the manager's issuer response may reach the host.+func TestManagedLoginRuntimePaths(t *testing.T) {+ if os.Getenv("LOOPFORGE_PROBE_AUTH_SANDBOXES") != "1" {+ t.Skip("opt in to real native/Docker sandboxes with fake credentials")+ }+ t.Setenv("AGENTFLOW_ISOLATED_IMAGE", "python:3.13-alpine")+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", "")+ t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "")+ for _, provider := range []string{"codex", "claude-code"} {+ for _, driver := range []string{"native", "docker"} {+ for _, mode := range []string{"conversation", "sop"} {+ t.Run(provider+"/"+driver+"/"+mode, func(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)+ defer cancel()+ cache, err := os.UserCacheDir()+ if err != nil {+ t.Fatal(err)+ }+ root, err := os.MkdirTemp(cache, "lf-auth-sandbox-")+ if err != nil {+ t.Fatal(err)+ }+ defer os.RemoveAll(root)+ workspace := filepath.Join(root, "ws")+ if err := os.MkdirAll(workspace, 0700); err != nil {+ t.Fatal(err)+ }+ fixturePath := filepath.Join(workspace, "fake-cli")+ if err := os.WriteFile(fixturePath, []byte("#!/usr/bin/env python3\n"+managedAuthCLIFixture), 0755); err != nil {+ t.Fatal(err)+ }+ override := "AGENTFLOW_CODEX_BIN"+ if provider == "claude-code" {+ override = "AGENTFLOW_CLAUDE_BIN"+ }+ t.Setenv(override, fixturePath)+ source, _, renewed := managedLoginFixture(t, provider)+ login, _ := runnerLoginSpec(provider)+ t.Setenv(login.configEnv, filepath.Dir(source.path))+ commandEnv := map[string]string{"LOOPFORGE_FAKE_SOURCE": source.path}+ var exchanges atomic.Int32+ previous := nativeRunnerLogins+ nativeRunnerLogins = &runnerLoginManager{stateDir: t.TempDir(), refresh: func(context.Context, string, []byte) ([]byte, error) { exchanges.Add(1); return renewed, nil }}+ defer func() { nativeRunnerLogins = previous }()+ profile := domain.SandboxProfile{Driver: driver}+ dockerfile := domain.DockerfileDefinition{Content: IsolatedDockerfile}+ binary := fixturePath+ if driver == "docker" {+ binary = "/workspace/fake-cli"+ }+ command := CommandSpec{Provider: provider, Argv: []string{binary, "task prompt"}, environment: commandEnv}+ var out string+ if mode == "conversation" {+ pool := &ConversationProcessPool{}+ spec := &domain.RunnerSandboxSpec{Profile: profile, Dockerfile: &dockerfile}+ factory := func(ctx context.Context, _ string) (Sandbox, func(), error) {+ sb, err := OpenRemoteSandbox(ctx, fmt.Sprintf("auth-conversation-%d", time.Now().UnixNano()), workspace, profile, SandboxRequirements{ConversationRoot: root}, SandboxResources{Dockerfile: dockerfile})+ if err != nil {+ return nil, nil, err+ }+ release := func() { _ = sb.Close(context.Background()) }+ if docker, ok := sb.(*dockerSandbox); ok {+ if err := docker.BindWorkspace(ctx); err != nil {+ release()+ return nil, nil, err+ }+ // Install only this harmless fixture in the disposable container.+ out, err := exec.CommandContext(ctx, "docker", "exec", "--user", "0:0", docker.name, "cp", "/workspace/fake-cli", "/usr/local/bin/"+conversationBinary(provider)).CombinedOutput()+ if err != nil {+ release()+ return nil, nil, fmt.Errorf("fixture install: %w: %s", err, out)+ }+ }+ return sb, release, nil+ }+ started, err := pool.Handle(ctx, root, workspace, spec, ConversationProcessRequest{Operation: "start", Command: &ConversationCommand{+ Argv: command.Argv, Provider: provider, Environment: commandEnv, Bindings: []CredentialBinding{login.binding}, RunnerLogin: true}}, nil, factory)+ if err != nil {+ t.Fatal(err)+ }+ defer pool.Handle(context.Background(), root, workspace, spec, ConversationProcessRequest{Operation: "stop", ID: started.ID}, nil)+ var after int64+ for {+ result, err := pool.Handle(ctx, root, workspace, spec, ConversationProcessRequest{Operation: "poll", ID: started.ID, After: after}, nil)+ if err != nil {+ t.Fatal(err)+ }+ for _, event := range result.Events {+ out += event.Message + "\n"+ }+ after = result.Sequence+ if result.Done {+ if result.Error != "" {+ t.Fatalf("conversation: %s; fake output %.1500s", result.Error, out)+ }+ break+ }+ }+ } else {+ requirements := ProviderRequirements(provider)+ requirements.RunnerLoginRelay = driver == "docker" && provider == "codex"+ sb, err := OpenRemoteSandbox(ctx, fmt.Sprintf("auth-%d", time.Now().UnixNano()), workspace, profile, requirements, SandboxResources{Dockerfile: dockerfile})+ if err != nil {+ t.Fatal(err)+ }+ defer sb.Close(context.Background())+ if docker, ok := sb.(*dockerSandbox); ok {+ // SOP workspace preparation may start the container before the CLI has a login lease.+ if err := docker.BindWorkspace(ctx); err != nil {+ t.Fatal(err)+ }+ }+ env, cleanup, err := PrepareRunnerSandboxLogin(sb, provider, "run", "node")+ if err != nil {+ t.Fatal(err)+ }+ defer cleanup()+ command = WithCommandEnvironment(command, env)+ out, err = sb.Exec(ctx, command, nil)+ if err != nil {+ t.Fatalf("sandbox command: %v; fake output %.1200s", err, out)+ }+ }+ if !strings.Contains(out, "managed-auth-ok") || strings.Contains(out, "oauth_token_refresh") {+ t.Fatalf("missing result or leaked control frame: %.1000s", out)+ }+ host, err := os.ReadFile(source.path)+ if err != nil || !bytes.Equal(host, renewed) || exchanges.Load() != 1 {+ t.Fatalf("host refresh/preservation failed; exchanges=%d", exchanges.Load())+ }+ })+ }+ }+ }+}++const managedAuthCLIFixture = `import json,os,sys,urllib.request+try:+ open(os.environ['LOOPFORGE_FAKE_SOURCE']).read()+except OSError:+ pass+else:+ raise AssertionError('native sandbox can read host refresh token')+if os.environ.get('CODEX_HOME'):+ path=os.path.join(os.environ['CODEX_HOME'],'auth.json')+ data=json.load(open(path)); nonce=data['tokens']['refresh_token']+ assert 'host-refresh' not in nonce+ request=urllib.request.Request(os.environ['CODEX_REFRESH_TOKEN_URL_OVERRIDE'],data=json.dumps({'grant_type':'refresh_token','refresh_token':nonce}).encode(),headers={'Content-Type':'application/json'})+ response=json.load(urllib.request.build_opener(urllib.request.ProxyHandler({})).open(request,timeout=15))+ assert response.get('access_token') and 'host-refresh' not in response['refresh_token']+ data['tokens']['refresh_token']='sandbox-account-replacement'+ json.dump(data,open(path,'w'))+ print(json.dumps({'type':'result','result':'managed-auth-ok'}),flush=True)+else:+ path=os.path.join(os.environ['CLAUDE_CONFIG_DIR'],'.credentials.json')+ data=json.load(open(path)); assert 'refreshToken' not in data['claudeAiOauth']+ for line in sys.stdin:+ event=json.loads(line)+ if event.get('type')=='control_request':+ print(json.dumps({'type':'control_response','response':{'subtype':'success','request_id':event['request_id']}}),flush=True)+ elif event.get('type')=='user':+ print(json.dumps({'type':'control_request','request_id':'refresh','request':{'subtype':'oauth_token_refresh'}}),flush=True)+ elif event.get('type')=='control_response':+ assert event['response']['response']['accessToken']=='claude-access-1'+ data['claudeAiOauth']['refreshToken']='sandbox-account-replacement'+ json.dump(data,open(path,'w'))+ print(json.dumps({'type':'result','result':'managed-auth-ok'}),flush=True)+ break+`diff --git a/internal/runtime/runner_login_refresh_agy_live_probe_test.go b/internal/runtime/runner_login_refresh_agy_live_probe_test.gonew file mode 100644index 00000000..ab5fb6ab--- /dev/null+++ b/internal/runtime/runner_login_refresh_agy_live_probe_test.go@@ -0,0 +1,289 @@+package runtime++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ goRuntime "runtime"+ "strings"+ "testing"+ "time"+)++// This is the ONLY experiment that may use real credentials. It requires an+// explicit opt-in, reads only the existing Antigravity keychain item, executes+// the official CLI's model-list command, and preserves refreshed credentials.+// It never opens Codex/Claude credentials or invokes a billed model response.+func TestWritebackProbeAntigravityLiveRefresh(t *testing.T) {+ if os.Getenv("LOOPFORGE_PROBE_AGY_LIVE") != "1" {+ t.Skip("explicit Antigravity live-auth opt-in required")+ }+ if goRuntime.GOOS != "darwin" {+ t.Fatal("live probe currently requires the macOS Antigravity keychain")+ }+ binary := os.Getenv("LOOPFORGE_PROBE_AGY_BIN")+ if !filepath.IsAbs(binary) {+ t.Fatal("set LOOPFORGE_PROBE_AGY_BIN to the official absolute binary path")+ }+ image := os.Getenv("LOOPFORGE_PROBE_AGY_DOCKER_IMAGE")+ if image == "" {+ t.Fatal("set LOOPFORGE_PROBE_AGY_DOCKER_IMAGE to an existing credential-free official CLI image")+ }+ docker, err := exec.LookPath("docker")+ if err != nil {+ t.Fatal("Docker unavailable")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)+ defer cancel()+ if err := exec.CommandContext(ctx, docker, "image", "inspect", image).Run(); err != nil {+ t.Fatal("prebuilt Antigravity image unavailable")+ }+ cacheDir, err := os.UserCacheDir()+ if err != nil {+ t.Fatal(err)+ }+ root, err := os.MkdirTemp(cacheDir, "lf-agy-refresh-live-*")+ if err != nil {+ t.Fatal(err)+ }+ keepRecovery := false+ defer func() {+ if keepRecovery {+ t.Logf("private recovery credentials retained at %s", root)+ } else if err := os.RemoveAll(root); err != nil {+ t.Error("could not remove private probe credentials")+ }+ }()+ type loginRecord struct {+ Token struct {+ Access string `json:"access_token"`+ Refresh string `json:"refresh_token"`+ Expiry time.Time `json:"expiry"`+ } `json:"token"`+ }+ decode := func(raw []byte) (loginRecord, error) {+ var record loginRecord+ err := json.Unmarshal(raw, &record)+ if err == nil && record.Token.Access == "" {+ err = errors.New("no access token")+ }+ return record, err+ }+ original, err := readAntigravityKeyring()+ if err != nil {+ t.Fatal("cannot read existing Antigravity login")+ }+ initial, err := decode([]byte(original))+ if err != nil || initial.Token.Refresh == "" {+ t.Fatal("existing Antigravity login has no refresh token")+ }+ expectedHost := []byte(original)+ if err := os.WriteFile(filepath.Join(root, "original.json"), expectedHost, 0600); err != nil {+ t.Fatal(err)+ }+ preserve := func(raw []byte) bool {+ t.Helper()+ candidate, err := decode(raw)+ if err != nil {+ t.Error("official CLI produced an invalid credential")+ return false+ }+ current, keep, err := antigravityKeyringLogin(readAntigravityKeyring, writeAntigravityKeyring)+ if err != nil {+ keepRecovery = true+ t.Error("cannot re-read host Antigravity login; private responses retained")+ return false+ }+ if !bytes.Equal(current, expectedHost) {+ host, hostErr := decode(current)+ if hostErr == nil && host.Token.Refresh == candidate.Token.Refresh && sameAntigravityLogin(current, raw) {+ expectedHost = append([]byte(nil), current...)+ t.Log("host Antigravity source advanced with the same refresh token; kept the host update")+ return true+ }+ keepRecovery = true+ t.Error("host Antigravity login changed identity or refresh token; private responses retained")+ return false+ }+ err = keep(raw)+ stored, readErr := readAntigravityKeyring()+ if err != nil || readErr != nil {+ keepRecovery = true+ t.Error("could not preserve refreshed Antigravity login; private responses retained")+ return false+ }+ if !bytes.Equal([]byte(stored), raw) {+ host, hostErr := decode([]byte(stored))+ if hostErr != nil || host.Token.Refresh != candidate.Token.Refresh || !sameAntigravityLogin([]byte(stored), raw) {+ keepRecovery = true+ t.Error("host changed during preservation; private responses retained")+ return false+ }+ }+ expectedHost = []byte(stored)+ return true+ }+ type result struct {+ Name string+ Raw []byte+ Record loginRecord+ Models int+ Err error+ }+ run := func(name, driver string, seed []byte, expire, accessOnly bool) result {+ r := result{Name: name}+ home := filepath.Join(root, name)+ dir := filepath.Join(home, ".gemini", "antigravity-cli")+ if r.Err = os.MkdirAll(dir, 0700); r.Err != nil {+ return r+ }+ var doc map[string]any+ if r.Err = json.Unmarshal(seed, &doc); r.Err != nil {+ return r+ }+ token, ok := doc["token"].(map[string]any)+ if !ok {+ r.Err = errors.New("missing token record")+ return r+ }+ if expire {+ token["access_token"], token["expiry"] = "probe-expired-access", "2000-01-01T00:00:00Z"+ }+ if accessOnly {+ delete(token, "refresh_token")+ }+ raw, err := json.Marshal(doc)+ path := filepath.Join(dir, antigravityTokenFile)+ if err == nil {+ err = os.WriteFile(path, raw, 0600)+ }+ if err != nil {+ r.Err = err+ return r+ }+ childCtx, stop := context.WithTimeout(ctx, 75*time.Second)+ defer stop()+ var cmd *exec.Cmd+ if driver == "docker" {+ cmd = exec.CommandContext(childCtx, docker, "run", "--rm", "--user", fmt.Sprintf("%d:%d", os.Getuid(), os.Getgid()),+ "--mount", "type=bind,src="+home+",dst=/home/probe", "-e", "HOME=/home/probe", "-e", "SSH_CONNECTION=127.0.0.1 1 127.0.0.1 2",+ "-e", "NO_COLOR=1", "--entrypoint", "/usr/local/bin/agy", image, "models")+ } else {+ cmd = exec.CommandContext(childCtx, binary, "models")+ cmd.Dir = home+ cmd.Env = append(terminalBaseEnvironment(home), "SSH_CONNECTION=127.0.0.1 1 127.0.0.1 2", "NO_COLOR=1")+ }+ output, runErr := cmd.Output() // Never echo CLI diagnostics: they may contain account details.+ r.Raw, err = os.ReadFile(path)+ if err == nil {+ r.Record, err = decode(r.Raw)+ }+ if runErr != nil || err != nil {+ var exit *exec.ExitError+ if errors.As(runErr, &exit) {+ message := strings.ToLower(string(exit.Stderr))+ r.Err = fmt.Errorf("model-list failed: exit=%d, auth=%v, permission=%v, network=%v", exit.ExitCode(), strings.Contains(message, "auth"), strings.Contains(message, "permission"), strings.Contains(message, "connect") || strings.Contains(message, "network"))+ } else {+ r.Err = errors.New("official model-list command or credential read failed")+ }+ return r+ }+ for _, line := range strings.Split(string(output), "\n") {+ if id, _, found := strings.Cut(strings.TrimSpace(line), "\t"); found && id != "" {+ r.Models+++ }+ }+ if r.Models == 0 || r.Record.Token.Access == "probe-expired-access" || !r.Record.Token.Expiry.After(time.Now().Add(5*time.Minute)) {+ r.Err = errors.New("official CLI did not provide a usable refreshed login and model list")+ }+ return r+ }+ first := run("sequential-preflight", "native", []byte(original), true, false)+ if len(first.Raw) > 0 && first.Record.Token.Access != "" && first.Record.Token.Access != "probe-expired-access" {+ if !preserve(first.Raw) { // Preserve a rotated pair even if the later model-list request failed.+ t.Fatal("could not preserve preflight response")+ }+ }+ if first.Err != nil {+ t.Fatal(first.Err)+ }+ rotated := first.Record.Token.Refresh != initial.Token.Refresh+ t.Logf("live Antigravity preflight: models=%d, access renewed=true, refresh token rotated=%v", first.Models, rotated)+ if rotated {+ t.Log("stopped before concurrent reuse because the real provider rotated the refresh token")+ return+ }+ seed := append([]byte(nil), first.Raw...)+ outcomes := make(chan result, 3)+ start := make(chan struct{})+ for _, entry := range []struct{ name, driver string }{{"host-copy", "native"}, {"sop-native", "native"}, {"sop-docker", "docker"}} {+ go func(name, driver string) {+ <-start+ outcomes <- run(name, driver, seed, true, false)+ }(entry.name, entry.driver)+ }+ close(start)+ var last []byte+ var failures int+ for range 3 {+ r := <-outcomes+ if r.Record.Token.Access != "" && r.Record.Token.Access != "probe-expired-access" {+ if !preserve(r.Raw) {+ failures+++ }+ last = r.Raw+ }+ if r.Err != nil {+ failures+++ t.Logf("sanitized %s failure: %v", r.Name, r.Err)+ }+ changed := r.Record.Token.Refresh != first.Record.Token.Refresh+ t.Logf("live Antigravity concurrent %s: passed=%v, models=%d, refresh token rotated=%v", r.Name, r.Err == nil, r.Models, changed)+ if changed && r.Record.Token.Refresh != "" {+ keepRecovery = true+ failures+++ }+ }+ if failures != 0 || len(last) == 0 {+ t.Fatal("concurrent refresh was not uniformly reusable; inspect the sanitized results and retained private responses")+ }+ // Explicitly reuse the same refresh token after all three requests complete.+ reuse := run("reuse-after-concurrent", "native", last, true, false)+ if reuse.Record.Token.Access != "" && reuse.Record.Token.Access != "probe-expired-access" {+ if !preserve(reuse.Raw) {+ t.Fatal("could not preserve post-concurrency response")+ }+ }+ if reuse.Err != nil {+ t.Fatal("same refresh token was not reusable after the concurrent requests")+ }+ t.Logf("live Antigravity post-concurrency reuse: passed=true, refresh token rotated=%v", reuse.Record.Token.Refresh != first.Record.Token.Refresh)+ for _, driver := range []string{"native", "docker"} {+ r := run("access-only-"+driver, driver, reuse.Raw, false, true)+ t.Logf("live Antigravity access-only %s: passed=%v, models=%d, refresh token absent=%v", driver, r.Err == nil, r.Models, r.Record.Token.Refresh == "")+ if r.Err != nil {+ t.Error("access-only model-list invocation failed")+ }+ }+ client := &http.Client{Timeout: 15 * time.Second}+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://openidconnect.googleapis.com/v1/userinfo", nil)+ req.Header.Set("Authorization", "Bearer "+reuse.Record.Token.Access)+ resp, err := client.Do(req)+ if err != nil {+ t.Fatal("could not verify final access token with Google userinfo")+ }+ defer resp.Body.Close()+ var profile struct {+ Subject string `json:"sub"`+ }+ if resp.StatusCode != http.StatusOK || json.NewDecoder(resp.Body).Decode(&profile) != nil || profile.Subject == "" {+ t.Fatal("final Google identity lookup failed")+ }+ t.Log("live Antigravity final access token accepted by Google userinfo; no account identifiers logged")+}diff --git a/internal/runtime/runner_login_writeback_codex_probe_test.go b/internal/runtime/runner_login_writeback_codex_probe_test.gonew file mode 100644index 00000000..6c8fc53e--- /dev/null+++ b/internal/runtime/runner_login_writeback_codex_probe_test.go@@ -0,0 +1,252 @@+package runtime++import (+ "bufio"+ "context"+ "crypto/ed25519"+ "crypto/rand"+ "crypto/tls"+ "crypto/x509"+ "crypto/x509/pkix"+ "encoding/base64"+ "encoding/json"+ "encoding/pem"+ "fmt"+ "io"+ "math/big"+ "net"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ goRuntime "runtime"+ "strings"+ "sync"+ "testing"+ "time"+)++// Explicit opt-in: run the official binary against FAKE credentials and a+// loopback issuer, with macOS additionally denying access to real credentials+// and all non-loopback networking. This does not validate a real provider's+// policy, model inference, or the proposed identity oracle.+func TestManagedLoginOfficialCodex(t *testing.T) {+ binary := os.Getenv("LOOPFORGE_PROBE_CODEX_BIN")+ if binary == "" {+ t.Skip("set LOOPFORGE_PROBE_CODEX_BIN to explicitly test an official binary with fake auth")+ }+ if goRuntime.GOOS != "darwin" || !filepath.IsAbs(binary) {+ t.Fatal("this opt-in probe requires macOS sandbox-exec and an absolute binary path")+ }+ root := t.TempDir()+ home := filepath.Join(root, "home")+ codexHome := filepath.Join(home, ".codex")+ if err := os.MkdirAll(codexHome, 0700); err != nil {+ t.Fatal(err)+ }+ jwt := func() string {+ claims, _ := json.Marshal(map[string]any{+ "sub": "fake-user-a", "email": "[email protected]", "exp": time.Now().Add(time.Hour).Unix(),+ "https://api.openai.com/auth": map[string]any{+ "chatgpt_account_id": "fake-account-a", "chatgpt_user_id": "fake-user-a", "chatgpt_plan_type": "plus",+ },+ })+ return "eyJhbGciOiJub25lIn0." + base64.RawURLEncoding.EncodeToString(claims) + ".fake-signature"+ }+ var mu sync.Mutex+ calls, rejectedEgress := 0, 0+ latest := "fake-refresh-0"+ issuer := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ defer mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == "/token" && r.Method == http.MethodPost {+ var req struct {+ Refresh string `json:"refresh_token"`+ }+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Refresh != latest {+ w.WriteHeader(http.StatusBadRequest)+ _, _ = io.WriteString(w, `{"error":"invalid_grant"}`)+ return+ }+ calls+++ latest = fmt.Sprintf("fake-refresh-%d", calls)+ _ = json.NewEncoder(w).Encode(map[string]any{+ "access_token": jwt(), "id_token": jwt(), "refresh_token": latest, "expires_in": 3600,+ })+ return+ }+ if r.Method == http.MethodConnect || r.URL.IsAbs() {+ rejectedEgress+++ w.WriteHeader(http.StatusBadGateway)+ return+ }+ if strings.HasSuffix(r.URL.Path, "/accounts/check") {+ _ = json.NewEncoder(w).Encode(map[string]any{"accounts": []any{map[string]any{+ "id": "fake-account-a", "plan_type": "plus", "workspace_backend_origin": "https://" + r.Host,+ "account_routing_override": "NO_CONSTRAINT", "name": "Fake isolated account",+ }}})+ return+ }+ _, _ = io.WriteString(w, `{"models":[]}`)+ }))+ // rustls correctly rejects a CA certificate used directly as a TLS leaf.+ // Use a distinct test CA and server leaf, rather than httptest's default.+ _, caKey, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ ca := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "LoopForge fake issuer CA"},+ NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),+ IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature}+ caDER, err := x509.CreateCertificate(rand.Reader, ca, ca, caKey.Public(), caKey)+ if err != nil {+ t.Fatal(err)+ }+ _, leafKey, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ leaf := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "localhost"},+ NotBefore: ca.NotBefore, NotAfter: ca.NotAfter, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},+ DNSNames: []string{"localhost"}, KeyUsage: x509.KeyUsageDigitalSignature,+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true}+ leafDER, err := x509.CreateCertificate(rand.Reader, leaf, ca, leafKey.Public(), caKey)+ if err != nil {+ t.Fatal(err)+ }+ issuer.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{leafDER, caDER}, PrivateKey: leafKey}}}+ issuer.StartTLS()+ defer issuer.Close()+ caPath := filepath.Join(root, "fake-issuer-ca.pem")+ if err := os.WriteFile(caPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0600); err != nil {+ t.Fatal(err)+ }+ config := "cli_auth_credentials_store = \"file\"\nchatgpt_base_url = " + fmt.Sprintf("%q\n", issuer.URL+"/chatgpt/")+ if err := os.WriteFile(filepath.Join(codexHome, "config.toml"), []byte(config), 0600); err != nil {+ t.Fatal(err)+ }+ initial := probeCredential("codex", "fake-account-a", probeTokens{Access: jwt(), Refresh: latest, ID: jwt()})+ host := t.TempDir()+ login, _ := runnerLoginSpec("codex")+ source := fileRunnerLoginSource(login, host)+ if err := os.WriteFile(source.path, initial, 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("CODEX_REFRESH_TOKEN_URL_OVERRIDE", issuer.URL+"/token")+ manager := &runnerLoginManager{stateDir: t.TempDir(), client: issuer.Client()}+ lease, err := newRunnerLoginLease(context.Background(), manager, source, false)+ if err != nil {+ t.Fatal(err)+ }+ defer lease.close()+ staged, err := lease.credential()+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(codexHome, "auth.json"), staged, 0600); err != nil {+ t.Fatal(err)+ }+ realHome, err := os.UserHomeDir()+ if err != nil {+ t.Fatal(err)+ }+ // sandbox-exec is scoped to this child. It changes no host permissions or+ // trust settings. Literal profile strings use JSON quoting, not a shell.+ profile := `(version 1) (allow default) (deny network*) (allow network-outbound (remote ip "localhost:*"))`+ for _, path := range []string{filepath.Join(realHome, ".codex"), filepath.Join(realHome, ".claude"), filepath.Join(realHome, ".gemini"), filepath.Join(realHome, "Library", "Keychains")} {+ profile += fmt.Sprintf(" (deny file-read* file-write* (subpath %q))", path)+ }+ profile += fmt.Sprintf(" (deny file-write* (subpath %q))", realHome)+ ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, "/usr/bin/sandbox-exec", "-p", profile, binary, "app-server")+ cmd.Dir = root+ // A clean environment is essential: inherit neither the desktop app's auth+ // injection nor any API key, credential home, issuer override or proxy.+ cmd.Env = []string{+ "PATH=/usr/bin:/bin", "HOME=" + home, "CODEX_HOME=" + codexHome, "TMPDIR=" + root,+ "XDG_CONFIG_HOME=" + home, "XDG_DATA_HOME=" + home, "XDG_CACHE_HOME=" + home,+ "CODEX_REFRESH_TOKEN_URL_OVERRIDE=" + lease.endpoint,+ "CODEX_CA_CERTIFICATE=" + caPath, "SSL_CERT_FILE=" + caPath,+ "CODEX_APP_SERVER_CHATGPT_BASE_URL=" + issuer.URL + "/chatgpt/", "OPENAI_BASE_URL=" + issuer.URL + "/v1/",+ "HTTP_PROXY=" + issuer.URL, "HTTPS_PROXY=" + issuer.URL, "ALL_PROXY=" + issuer.URL,+ "NO_PROXY=127.0.0.1,localhost", "RUST_LOG=off", "DO_NOT_TRACK=1",+ }+ input, err := cmd.StdinPipe()+ if err != nil {+ t.Fatal(err)+ }+ output, err := cmd.StdoutPipe()+ if err != nil {+ t.Fatal(err)+ }+ var stderr strings.Builder+ cmd.Stderr = &stderr+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ defer func() {+ _ = input.Close()+ cancel()+ _ = cmd.Wait()+ if t.Failed() {+ text := stderr.String()+ if len(text) > 1200 {+ text = text[len(text)-1200:]+ }+ t.Logf("isolated CLI diagnostics: %s", text)+ mu.Lock()+ t.Logf("fake token calls=%d; test certificate CA=%v", calls, issuer.Certificate().IsCA)+ mu.Unlock()+ }+ }()+ send := json.NewEncoder(input)+ scanner := bufio.NewScanner(output)+ scanner.Buffer(make([]byte, 4096), 1<<20)+ result := func(id int) json.RawMessage {+ for scanner.Scan() {+ var reply struct {+ ID int `json:"id"`+ Result json.RawMessage `json:"result"`+ Error json.RawMessage `json:"error"`+ }+ if json.Unmarshal(scanner.Bytes(), &reply) == nil && reply.ID == id {+ if len(reply.Error) > 0 {+ t.Logf("isolated RPC error: %s", reply.Error)+ }+ return reply.Result+ }+ }+ return nil+ }+ if err := send.Encode(map[string]any{"id": 1, "method": "initialize", "params": map[string]any{+ "clientInfo": map[string]string{"name": "loopforge-isolated-writeback-probe", "version": "0.1.0"},+ }}); err != nil {+ t.Fatal(err)+ }+ if result(1) == nil {+ t.Fatal("isolated Codex could not initialize; check binary/sandbox support")+ }+ _ = send.Encode(map[string]string{"method": "initialized"})+ for id := 2; id <= 3; id++ {+ if err := send.Encode(map[string]any{"id": id, "method": "account/read", "params": map[string]bool{"refreshToken": true}}); err != nil {+ t.Fatal(err)+ }+ if result(id) == nil {+ t.Fatal("official Codex could not refresh against the isolated fake issuer")+ }+ }+ raw, err := os.ReadFile(filepath.Join(codexHome, "auth.json"))+ if err != nil {+ t.Fatal(err)+ }+ mu.Lock()+ defer mu.Unlock()+ hostRaw, readErr := os.ReadFile(source.path)+ if readErr != nil || calls != 2 || probeReadTokens("codex", hostRaw).Refresh != latest || strings.Contains(string(raw), "fake-refresh-") {+ t.Fatal("managed Codex did not keep the rotating token on the host")+ }+ t.Logf("official Codex completed %d fake refreshes; non-loopback proxy requests rejected: %d", calls, rejectedEgress)+}diff --git a/internal/runtime/runner_login_writeback_probe_test.go b/internal/runtime/runner_login_writeback_probe_test.gonew file mode 100644index 00000000..d39cda4b--- /dev/null+++ b/internal/runtime/runner_login_writeback_probe_test.go@@ -0,0 +1,111 @@+package runtime++// A sandbox edit is not a trusted issuer response. Legitimate refreshes are+// tested through the manager, independently of these injection attempts.++import (+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"+)++var writebackProbeProviders = []string{"codex", "claude-code", "agy"}++func probeCredential(provider, account string, tokens probeTokens) []byte {+ var doc map[string]any+ switch provider {+ case "codex":+ idToken := tokens.ID+ if idToken == "" {+ idToken = "fake-id-token"+ }+ doc = map[string]any{+ "auth_mode": "chatgpt", "last_refresh": "2026-11-17T00:00:00Z",+ "tokens": map[string]any{"account_id": account, "id_token": idToken,+ "access_token": tokens.Access, "refresh_token": tokens.Refresh},+ }+ case "claude-code":+ doc = map[string]any{"claudeAiOauth": map[string]any{+ "accessToken": tokens.Access, "refreshToken": tokens.Refresh,+ "expiresAt": tokens.Expires * 1000, "scopes": []string{"user:profile", "user:inference"},+ "subscriptionType": "fake-plan", "rateLimitTier": "fake-tier",+ }}+ case "agy":+ doc = map[string]any{"auth_method": "consumer", "id_token_email": account + "@example.test",+ "token": map[string]any{"access_token": tokens.Access, "refresh_token": tokens.Refresh,+ "expiry": "2026-12-01T00:00:00Z", "token_type": "Bearer"}}+ default:+ panic("unknown test provider")+ }+ raw, err := json.Marshal(doc)+ if err != nil {+ panic(err)+ }+ return raw+}++func TestRunnerLoginSandboxEditsNotWrittenBack(t *testing.T) {+ for _, provider := range writebackProbeProviders {+ t.Run(provider, func(t *testing.T) {+ original := probeCredential(provider, "account-a", probeTokens{Access: "fake-access-a", Refresh: "fake-refresh-a"})+ cases := []struct {+ name, metadata, access, refresh string+ accepted bool+ }{+ {"edited token pair", "account-a", "fake-renewed-a", "fake-rotated-a", false},+ {"whole account swap", "account-b", "fake-access-b", "fake-refresh-b", false},+ {"swap with forged local identity", "account-a", "fake-access-b", "fake-refresh-b", false},+ {"refresh token only", "account-a", "fake-access-a", "fake-refresh-b", false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ // Override every relevant credential source before preparing a login.+ // No native keychain or real user HOME can be consulted.+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("CODEX_HOME", filepath.Join(home, ".codex"))+ t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude"))+ t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "")+ t.Setenv("SSH_CONNECTION", "127.0.0.1 1 127.0.0.1 2")+ login, ok := runnerLoginSpec(provider)+ if !ok {+ t.Fatal("missing test provider")+ }+ source := filepath.Join(home, login.dir, login.file)+ if err := os.MkdirAll(filepath.Dir(source), 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(source, original, 0600); err != nil {+ t.Fatal(err)+ }+ workspace := t.TempDir()+ cleanup, _, err := prepareConversationRunnerLogin(workspace, login, true)+ if err != nil {+ t.Fatal(err)+ }+ candidate := probeCredential(provider, tc.metadata, probeTokens{Access: tc.access, Refresh: tc.refresh})+ copyPath := filepath.Join(workspace, "home", login.dir, login.file)+ if err := os.WriteFile(copyPath, candidate, 0600); err != nil {+ t.Fatal(err)+ }+ if err := cleanup(); err != nil {+ t.Fatal(err)+ }+ got, err := os.ReadFile(source)+ if err != nil {+ t.Fatal(err)+ }+ accepted := bytes.Equal(got, candidate)+ if accepted != tc.accepted {+ t.Fatalf("sandbox edit accepted = %v, want %v", accepted, tc.accepted)+ }+ if !accepted && !bytes.Equal(got, original) {+ t.Fatal("rejection changed the host login")+ }+ })+ }+ })+ }+}diff --git a/internal/runtime/runner_login_writeback_protocol_probe_test.go b/internal/runtime/runner_login_writeback_protocol_probe_test.gonew file mode 100644index 00000000..d12f46dd--- /dev/null+++ b/internal/runtime/runner_login_writeback_protocol_probe_test.go@@ -0,0 +1,638 @@+package runtime++// Test-only protocol experiment. There are deliberately no production OAuth+// endpoints, client IDs, keychain calls, native CLI launches or real logins.+// The /profile endpoint below is an assumed trusted identity oracle, NOT a+// claim that every provider exposes this endpoint/contract to its CLI clients.++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"+)++type probeTokens struct {+ Access string `json:"access_token"`+ Refresh string `json:"refresh_token,omitempty"`+ ID string `json:"id_token,omitempty"`+ Expires int64 `json:"expires_at"`+}++type probePrincipal struct {+ Subject, Account, Organization string+}++type probeGrant struct {+ Principal probePrincipal+ Family string+ Spent bool+}++type probeIssuer struct {+ mu sync.Mutex+ server *httptest.Server+ next int+ access map[string]probeGrant+ refresh map[string]probeGrant+ revoked map[string]bool+ rotate, revokeOnReuse bool+ dropResponse, failProfiles bool+ failProfilesAfterExchange bool+ tokenCalls int+ afterExchange func()+}++func newProbeIssuer(t *testing.T, rotate bool) *probeIssuer {+ t.Helper()+ i := &probeIssuer{rotate: rotate, access: map[string]probeGrant{}, refresh: map[string]probeGrant{}, revoked: map[string]bool{}}+ i.server = httptest.NewTLSServer(http.HandlerFunc(i.serveHTTP))+ i.server.Client().Timeout = 2 * time.Second+ i.server.Client().CheckRedirect = func(*http.Request, []*http.Request) error {+ return errors.New("probe refuses redirects")+ }+ t.Cleanup(i.server.Close)+ return i+}++func (i *probeIssuer) pairLocked(grant probeGrant, refresh string) probeTokens {+ i.next+++ p := probeTokens{Access: fmt.Sprintf("fake-access-%d", i.next), Refresh: refresh,+ ID: fmt.Sprintf("fake-id-%d", i.next), Expires: time.Now().Add(time.Hour).Unix()}+ if refresh == "" {+ p.Refresh = fmt.Sprintf("fake-refresh-%d", i.next)+ }+ i.access[p.Access] = grant+ i.refresh[p.Refresh] = grant+ return p+}++func (i *probeIssuer) issue(p probePrincipal) probeTokens {+ i.mu.Lock()+ defer i.mu.Unlock()+ return i.pairLocked(probeGrant{Principal: p, Family: fmt.Sprintf("family-%d", i.next)}, "")+}++func (i *probeIssuer) serveHTTP(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ i.mu.Lock()+ if r.URL.Path == "/profile" {+ grant, ok := i.access[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]+ failed, revoked := i.failProfiles, i.revoked[grant.Family]+ i.mu.Unlock()+ if failed {+ w.WriteHeader(http.StatusServiceUnavailable)+ } else if !ok || revoked {+ w.WriteHeader(http.StatusUnauthorized)+ } else {+ _ = json.NewEncoder(w).Encode(grant.Principal)+ }+ return+ }+ if r.URL.Path != "/token" || r.Method != http.MethodPost {+ i.mu.Unlock()+ w.WriteHeader(http.StatusNotFound)+ return+ }+ if err := r.ParseForm(); err != nil || r.Form.Get("grant_type") != "refresh_token" {+ i.mu.Unlock()+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ i.tokenCalls+++ refresh := r.Form.Get("refresh_token")+ grant, ok := i.refresh[refresh]+ if !ok || grant.Spent || i.revoked[grant.Family] {+ if grant.Spent && i.revokeOnReuse {+ i.revoked[grant.Family] = true+ }+ i.mu.Unlock()+ w.WriteHeader(http.StatusBadRequest)+ _, _ = w.Write([]byte(`{"error":"invalid_grant"}`))+ return+ }+ var response probeTokens+ if i.rotate {+ spent := grant+ spent.Spent = true+ i.refresh[refresh] = spent+ response = i.pairLocked(grant, "")+ } else {+ response = i.pairLocked(grant, refresh)+ // Model an OAuth provider that omits refresh_token on renewal.+ response.Refresh = ""+ }+ drop, hook := i.dropResponse, i.afterExchange+ i.dropResponse, i.afterExchange = false, nil+ if i.failProfilesAfterExchange {+ i.failProfiles = true+ }+ i.mu.Unlock()+ if hook != nil {+ hook()+ }+ if drop {+ conn, _, err := w.(http.Hijacker).Hijack()+ if err == nil {+ _ = conn.Close()+ }+ return+ }+ _ = json.NewEncoder(w).Encode(response)+}++type probeClient struct{ issuer *probeIssuer }++var errProbeInvalidGrant = errors.New("probe issuer rejected refresh")++func (c probeClient) profile(access string) (probePrincipal, bool, error) {+ var identity probePrincipal+ req, _ := http.NewRequest(http.MethodGet, c.issuer.server.URL+"/profile", nil)+ req.Header.Set("Authorization", "Bearer "+access)+ resp, err := c.issuer.server.Client().Do(req)+ if err != nil {+ return identity, false, err+ }+ defer resp.Body.Close()+ if resp.StatusCode == http.StatusUnauthorized {+ return identity, false, nil+ }+ if resp.StatusCode != http.StatusOK {+ return identity, false, errors.New("probe identity service unavailable")+ }+ err = json.NewDecoder(resp.Body).Decode(&identity)+ return identity, err == nil, err+}++func (c probeClient) exchange(refresh string) (probeTokens, error) {+ var tokens probeTokens+ resp, err := c.issuer.server.Client().PostForm(c.issuer.server.URL+"/token", url.Values{+ "grant_type": {"refresh_token"}, "refresh_token": {refresh},+ })+ if err != nil {+ return tokens, err+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ var failure struct {+ Error string `json:"error"`+ }+ if json.NewDecoder(resp.Body).Decode(&failure) == nil && resp.StatusCode == http.StatusBadRequest && failure.Error == "invalid_grant" {+ return tokens, errProbeInvalidGrant+ }+ return tokens, errors.New("probe refresh outcome is unknown")+ }+ if err := json.NewDecoder(resp.Body).Decode(&tokens); err != nil {+ return tokens, err+ }+ if tokens.Access == "" {+ return tokens, errors.New("probe issuer returned no access token")+ }+ if tokens.Refresh == "" {+ tokens.Refresh = refresh+ }+ return tokens, nil+}++func probeReadTokens(provider string, raw []byte) probeTokens {+ var doc struct {+ Tokens probeTokens `json:"tokens"`+ Token probeTokens `json:"token"`+ Claude struct {+ Access string `json:"accessToken"`+ Refresh string `json:"refreshToken"`+ Expires int64 `json:"expiresAt"`+ } `json:"claudeAiOauth"`+ }+ if json.Unmarshal(raw, &doc) != nil {+ panic("invalid probe credential")+ }+ switch provider {+ case "codex":+ return doc.Tokens+ case "claude-code":+ return probeTokens{Access: doc.Claude.Access, Refresh: doc.Claude.Refresh, Expires: doc.Claude.Expires / 1000}+ default:+ return doc.Token+ }+}++func probeReplaceTokens(provider string, original []byte, tokens probeTokens) []byte {+ var doc map[string]any+ if err := json.Unmarshal(original, &doc); err != nil {+ panic(err)+ }+ key := map[string]string{"codex": "tokens", "claude-code": "claudeAiOauth", "agy": "token"}[provider]+ nested := doc[key].(map[string]any)+ if provider == "claude-code" {+ nested["accessToken"], nested["refreshToken"], nested["expiresAt"] = tokens.Access, tokens.Refresh, tokens.Expires*1000+ } else {+ nested["access_token"], nested["refresh_token"] = tokens.Access, tokens.Refresh+ if provider == "codex" {+ if tokens.ID != "" {+ nested["id_token"] = tokens.ID+ }+ doc["last_refresh"] = time.Now().UTC().Format(time.RFC3339)+ } else {+ nested["expiry"] = time.Unix(tokens.Expires, 0).UTC().Format(time.RFC3339)+ }+ }+ raw, err := json.Marshal(doc)+ if err != nil {+ panic(err)+ }+ return raw+}++// This state is Runner-owned, outside the sandbox. In particular, the pinned+// principal and expected host snapshot must never be accepted from a sandbox.+type probeTransaction struct {+ Provider string+ Principal probePrincipal+ Original, Candidate json.RawMessage+ Canonical *probeTokens+ Phase string+}++func probeSave(path string, state probeTransaction) error {+ raw, err := json.Marshal(state)+ if err != nil {+ return err+ }+ f, err := os.CreateTemp(filepath.Dir(path), ".probe-*")+ if err != nil {+ return err+ }+ defer os.Remove(f.Name())+ defer f.Close()+ if err := f.Chmod(0600); err != nil {+ return err+ }+ if _, err := f.Write(raw); err != nil {+ return err+ }+ if err := f.Sync(); err != nil {+ return err+ }+ if err := f.Close(); err != nil {+ return err+ }+ if err := os.Rename(f.Name(), path); err != nil {+ return err+ }+ dir, err := os.Open(filepath.Dir(path))+ if err != nil {+ return err+ }+ defer dir.Close()+ return dir.Sync()+}++func probeFinalize(client probeClient, host, journal string, state *probeTransaction) (string, error) {+ unchanged := func() bool {+ current, err := os.ReadFile(host)+ return err == nil && bytes.Equal(current, state.Original)+ }+ if !unchanged() {+ return "superseded", nil+ }+ if bytes.Equal(state.Candidate, state.Original) {+ return "unchanged", os.Remove(journal)+ }+ if state.Phase == "exchanging" || state.Phase == "uncertain" {+ // A lost response may have consumed the refresh token. Blind retry is+ // not safe for issuers that revoke an entire family on token reuse.+ return "uncertain", nil+ }+ if state.Canonical == nil {+ candidate := probeReadTokens(state.Provider, state.Candidate)+ principal, valid, err := client.profile(candidate.Access)+ if err != nil {+ return "deferred", nil+ }+ if valid && principal != state.Principal {+ return "rejected", nil+ }+ // An expired candidate access token cannot prove identity, but does+ // not block verifying its refresh token against the pinned principal.+ state.Phase = "exchanging"+ if err := probeSave(journal, *state); err != nil {+ return "", err+ }+ canonical, err := client.exchange(candidate.Refresh)+ if errors.Is(err, errProbeInvalidGrant) {+ return "rejected", nil+ }+ if err != nil {+ state.Phase = "uncertain"+ return "uncertain", probeSave(journal, *state)+ }+ state.Canonical, state.Phase = &canonical, "received"+ // Save the replacement pair BEFORE any fallible identity lookup.+ // Never write the sandbox pair back after redeeming its refresh token.+ if err := probeSave(journal, *state); err != nil {+ return "uncertain", err+ }+ }+ principal, valid, err := client.profile(state.Canonical.Access)+ if err != nil {+ return "deferred", nil+ }+ if !valid || principal != state.Principal {+ return "rejected", nil+ }+ if !unchanged() {+ return "superseded", nil+ }+ // Reuse the existing file writer, including its pre-rename recheck. It+ // is not a linearizable CAS against a non-cooperating native CLI.+ canonical := probeReplaceTokens(state.Provider, state.Original, *state.Canonical)+ if err := replaceRunnerLoginFile(filepath.Dir(host), filepath.Base(host), state.Original, canonical); err != nil {+ return "", err+ }+ current, err := os.ReadFile(host)+ if err != nil || !bytes.Equal(current, canonical) {+ return "superseded", err+ }+ return "accepted", os.Remove(journal)+}++type probeFixture struct {+ client probeClient+ host, journal string+ state probeTransaction+ initial probeTokens+}++func newProbeFixture(t *testing.T, provider string, issuer *probeIssuer) *probeFixture {+ t.Helper()+ f := &probeFixture{client: probeClient{issuer: issuer}}+ f.initial = issuer.issue(probePrincipal{Subject: "user-a", Account: "account-a", Organization: "org-a"})+ principal, valid, err := f.client.profile(f.initial.Access)+ if err != nil || !valid {+ t.Fatal("could not establish trusted baseline")+ }+ root := t.TempDir()+ f.host = filepath.Join(root, "host-login.json")+ private := filepath.Join(root, "runner-private")+ if err := os.Mkdir(private, 0700); err != nil {+ t.Fatal(err)+ }+ f.journal = filepath.Join(private, "pending.json")+ f.state = probeTransaction{Provider: provider, Principal: principal,+ Original: probeCredential(provider, "account-a", f.initial), Phase: "staged"}+ if err := os.WriteFile(f.host, f.state.Original, 0600); err != nil {+ t.Fatal(err)+ }+ return f+}++func (f *probeFixture) stage(t *testing.T, candidate []byte) {+ t.Helper()+ f.state.Candidate = candidate+ if err := probeSave(f.journal, f.state); err != nil {+ t.Fatal(err)+ }+}++func (f *probeFixture) finish(t *testing.T, want string) {+ t.Helper()+ got, err := probeFinalize(f.client, f.host, f.journal, &f.state)+ if err != nil || got != want {+ t.Fatalf("finalize = %q, %v; want %q", got, err, want)+ }+}++func (f *probeFixture) renew(t *testing.T, tokens probeTokens) probeTokens {+ t.Helper()+ next, err := f.client.exchange(tokens.Refresh)+ if err != nil {+ t.Fatal("mock CLI could not renew its credential")+ }+ return next+}++func TestWritebackProbeIdentityAndRenewal(t *testing.T) {+ for _, provider := range writebackProbeProviders {+ for _, rotate := range []bool{true, false} {+ name := fmt.Sprintf("%s/rotate=%v", provider, rotate)+ t.Run(name, func(t *testing.T) {+ for _, scenario := range []string{"normal", "whole account swap", "forged local identity", "refresh token only", "access token only", "unknown refresh token", "same subject different organization", "same account different subject", "expired candidate access"} {+ t.Run(scenario, func(t *testing.T) {+ issuer := newProbeIssuer(t, rotate)+ f := newProbeFixture(t, provider, issuer)+ candidate := f.renew(t, f.initial) // Official-CLI-shaped refresh, not a real CLI.+ metadata, want := "account-a", "rejected"+ other := issuer.issue(probePrincipal{Subject: "user-b", Account: "account-b", Organization: "org-b"})+ switch scenario {+ case "normal":+ want = "accepted"+ case "whole account swap":+ metadata, candidate = "account-b", other+ case "forged local identity":+ candidate = other+ case "refresh token only":+ candidate.Refresh = other.Refresh+ case "access token only":+ candidate.Access = other.Access+ case "unknown refresh token":+ candidate.Refresh = "fake-unknown-refresh"+ case "same subject different organization":+ candidate = issuer.issue(probePrincipal{Subject: "user-a", Account: "account-a", Organization: "org-b"})+ case "same account different subject":+ candidate = issuer.issue(probePrincipal{Subject: "user-b", Account: "account-a", Organization: "org-a"})+ case "expired candidate access":+ candidate.Access, want = "fake-expired-access", "accepted"+ }+ f.stage(t, probeCredential(provider, metadata, candidate))+ f.finish(t, want)+ raw, err := os.ReadFile(f.host)+ if err != nil {+ t.Fatal(err)+ }+ if want != "accepted" {+ if !bytes.Equal(raw, f.state.Original) {+ t.Fatal("rejected candidate changed host login")+ }+ return+ }+ saved := probeReadTokens(provider, raw)+ if saved.Refresh != f.state.Canonical.Refresh || saved.Access != f.state.Canonical.Access {+ t.Fatal("host did not receive the issuer's canonical pair")+ }+ if rotate && saved.Refresh == candidate.Refresh {+ t.Fatal("spent sandbox refresh token was written back")+ }+ if !rotate && saved.Refresh != f.initial.Refresh {+ t.Fatal("omitted refresh_token erased the reusable token")+ }+ var before, after map[string]any+ _ = json.Unmarshal(f.state.Original, &before)+ _ = json.Unmarshal(raw, &after)+ if provider == "claude-code" {+ b, a := before["claudeAiOauth"].(map[string]any), after["claudeAiOauth"].(map[string]any)+ for _, key := range []string{"subscriptionType", "rateLimitTier", "scopes"} {+ if fmt.Sprint(b[key]) != fmt.Sprint(a[key]) {+ t.Fatal("refresh dropped Claude credential metadata")+ }+ }+ }+ // A subsequent simulated CLI can refresh the persisted pair.+ f.renew(t, saved)+ if info, _ := os.Stat(f.host); info.Mode().Perm() != 0600 {+ t.Fatal("host credential lost its private mode")+ }+ if _, err := os.Stat(f.journal); !os.IsNotExist(err) {+ t.Fatal("accepted pending credential was not removed")+ }+ })+ }+ })+ }+ }+}++func TestWritebackProbeRecoveryAndBoundaries(t *testing.T) {+ for _, provider := range writebackProbeProviders {+ t.Run(provider, func(t *testing.T) {+ t.Run("unchanged login does not trigger refresh", func(t *testing.T) {+ issuer := newProbeIssuer(t, true)+ f := newProbeFixture(t, provider, issuer)+ f.stage(t, f.state.Original)+ f.finish(t, "unchanged")+ issuer.mu.Lock()+ calls := issuer.tokenCalls+ issuer.mu.Unlock()+ if calls != 0 {+ t.Fatal("unchanged login unexpectedly consumed a refresh token")+ }+ })+ t.Run("identity outage after rotation and restart", func(t *testing.T) {+ issuer := newProbeIssuer(t, true)+ f := newProbeFixture(t, provider, issuer)+ f.stage(t, probeCredential(provider, "account-a", f.renew(t, f.initial)))+ issuer.mu.Lock()+ issuer.failProfilesAfterExchange = true+ issuer.mu.Unlock()+ f.finish(t, "deferred")+ if raw, _ := os.ReadFile(f.host); !bytes.Equal(raw, f.state.Original) {+ t.Fatal("unverified identity was committed")+ }+ raw, err := os.ReadFile(f.journal)+ if err != nil {+ t.Fatal(err)+ }+ f.state = probeTransaction{} // Simulated Runner restart; reload ONLY durable state.+ if err := json.Unmarshal(raw, &f.state); err != nil || f.state.Canonical == nil {+ t.Fatal("rotated response was not preserved before identity verification")+ }+ if info, _ := os.Stat(f.journal); info.Mode().Perm() != 0600 {+ t.Fatal("pending login was not private")+ }+ issuer.mu.Lock()+ issuer.failProfiles = false+ calls := issuer.tokenCalls+ issuer.mu.Unlock()+ f.finish(t, "accepted")+ issuer.mu.Lock()+ repeated := issuer.tokenCalls != calls+ issuer.mu.Unlock()+ if repeated {+ t.Fatal("restart redeemed an already consumed refresh token")+ }+ f.renew(t, *f.state.Canonical)+ })+ for _, event := range []string{"host refresh before verification", "host logout before verification", "host refresh during verification", "host logout during verification"} {+ t.Run(event, func(t *testing.T) {+ issuer := newProbeIssuer(t, true)+ f := newProbeFixture(t, provider, issuer)+ f.stage(t, probeCredential(provider, "account-a", f.renew(t, f.initial)))+ var changed []byte+ changeHost := func() {+ if strings.Contains(event, "logout") {+ if err := os.Remove(f.host); err != nil {+ t.Error(err)+ }+ } else {+ changed = probeCredential(provider, "account-b", issuer.issue(probePrincipal{Subject: "host-new-login"}))+ if err := os.WriteFile(f.host, changed, 0600); err != nil {+ t.Error(err)+ }+ }+ }+ if strings.Contains(event, "before") {+ changeHost()+ } else {+ issuer.mu.Lock()+ issuer.afterExchange = changeHost+ issuer.mu.Unlock()+ }+ f.finish(t, "superseded")+ raw, err := os.ReadFile(f.host)+ if strings.Contains(event, "logout") {+ if !os.IsNotExist(err) {+ t.Fatal("writeback resurrected a logged-out host")+ }+ } else if err != nil || !bytes.Equal(raw, changed) {+ t.Fatal("writeback overwrote a newer host login")+ }+ })+ }+ t.Run("lost refresh response cannot be recovered by quarantine", func(t *testing.T) {+ issuer := newProbeIssuer(t, true)+ f := newProbeFixture(t, provider, issuer)+ candidate := f.renew(t, f.initial)+ f.stage(t, probeCredential(provider, "account-a", candidate))+ issuer.mu.Lock()+ issuer.dropResponse = true+ issuer.mu.Unlock()+ f.finish(t, "uncertain")+ if f.state.Canonical != nil {+ t.Fatal("client invented the lost replacement token")+ }+ issuer.mu.Lock()+ spent := issuer.refresh[candidate.Refresh].Spent+ calls := issuer.tokenCalls+ issuer.mu.Unlock()+ if !spent {+ t.Fatal("test did not consume the candidate refresh token")+ }+ f.finish(t, "uncertain")+ issuer.mu.Lock()+ repeated := issuer.tokenCalls != calls+ issuer.mu.Unlock()+ if repeated {+ t.Fatal("ambiguous exchange was blindly retried")+ }+ })+ })+ }+}++func TestWritebackProbeParallelCopiesCanRevokeFamily(t *testing.T) {+ issuer := newProbeIssuer(t, true)+ issuer.revokeOnReuse = true+ client := probeClient{issuer: issuer}+ initial := issuer.issue(probePrincipal{Subject: "user-a"})+ rotated, err := client.exchange(initial.Refresh) // First sandbox/native CLI.+ if err != nil {+ t.Fatal(err)+ }+ if _, err := client.exchange(initial.Refresh); !errors.Is(err, errProbeInvalidGrant) {+ t.Fatal("second copy unexpectedly refreshed a spent token")+ }+ if _, err := client.exchange(rotated.Refresh); !errors.Is(err, errProbeInvalidGrant) {+ t.Fatal("test issuer did not revoke the active token family on reuse")+ }+ // File CAS cannot undo this server-side revocation. This is an explicit+ // limitation of the proposed verifier, not a production-provider assertion.+}diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.goindex fc2a0eba..5481d6c8 100644--- a/internal/runtime/runtime.go+++ b/internal/runtime/runtime.go@@ -132,6 +132,10 @@ type CommandSpec struct {privateBinds []string// Conversation preparation binds credentials before acknowledging start.bindingsPrepared bool+ // Runner-owned authentication state never enters serialized invocations.+ runnerLogin *runnerLoginLease+ runnerLoginPrompt string+ runnerLoginInitialize bool}// WithPrivateHomeDir keeps CodeBuddy/Claude isolated from the operator HOMEdiff --git a/internal/runtime/sandbox_docker.go b/internal/runtime/sandbox_docker.goindex 285d9a40..408bd66c 100644--- a/internal/runtime/sandbox_docker.go+++ b/internal/runtime/sandbox_docker.go@@ -165,7 +165,7 @@ func (s *dockerSandbox) Exec(ctx context.Context, command CommandSpec, sink Evenfunc (s *dockerSandbox) execOnce(ctx context.Context, command CommandSpec, sink EventSink) (out string, err error) {args := []string{"exec"}- if command.Stdin != nil {+ if command.Stdin != nil || isManagedClaude(command) {args = append(args, "-i")}for _, environment := range appendEnvironment(nil, s.profile.Environment, command.environment) {@@ -202,7 +202,7 @@ cd "$1" && shift && exec "$@"`, "conversation", command.WorkingDir}, dropShellLoargs = append(args, argv...)cmd := exec.CommandContext(ctx, "docker", args...)cmd.Stdin = command.Stdin- return runCommand(cmd, sink, command.credentialEnvKeys...)+ return runCommand(cmd, sink, command)}// dockerWorkspaceExecArgv runs argv inside /workspace without docker exec -w.@@ -717,18 +717,22 @@ func (s *dockerSandbox) start(ctx context.Context, recreate bool) error {args = append(args, "--user", fmt.Sprintf("%d:%d", os.Geteuid(), os.Getegid()))}}- if network := strings.TrimSpace(os.Getenv("AGENTFLOW_DOCKER_NETWORK")); network != "" && s.requirements.ConversationRoot == "" {- args = append(args, "--network", network)- }- if root := s.requirements.ConversationRoot; root != "" {- _, network, err := conversationDockerAccess(ctx)+ network := strings.TrimSpace(os.Getenv("AGENTFLOW_DOCKER_NETWORK"))+ if s.requirements.ConversationRoot != "" || s.requirements.RunnerLoginRelay {+ _, relayNetwork, err := conversationDockerAccess(ctx)if err != nil {return err}- if network != "" {- args = append(args, "--network", network)+ if relayNetwork != "" {+ network = relayNetwork}- args = append(args, "--add-host", "host.docker.internal:host-gateway", "-v", root+":"+root+":ro", "-v", filepath.Join(root, "home")+":"+filepath.Join(root, "home"), "-v", workspace+":"+filepath.Join(root, "ws"))+ args = append(args, "--add-host", "host.docker.internal:host-gateway")+ }+ if network != "" {+ args = append(args, "--network", network)+ }+ if root := s.requirements.ConversationRoot; root != "" {+ args = append(args, "-v", root+":"+root+":ro", "-v", filepath.Join(root, "home")+":"+filepath.Join(root, "home"), "-v", workspace+":"+filepath.Join(root, "ws"))guards, err := conversationGuardMounts(root)if err != nil {return errdiff --git a/internal/runtime/sandbox_local.go b/internal/runtime/sandbox_local.goindex ec854d5b..aad2bd38 100644--- a/internal/runtime/sandbox_local.go+++ b/internal/runtime/sandbox_local.go@@ -32,7 +32,7 @@ func (s *localSandbox) Exec(ctx context.Context, command CommandSpec, sink Eventif err != nil {return "", fmt.Errorf("%w: %w", errProcessNotStarted, err)}- return runCommand(cmd, sink)+ return runCommand(cmd, sink, command)}func (s *localSandbox) command(ctx context.Context, command CommandSpec, base []string) (*exec.Cmd, error) {diff --git a/internal/runtime/sandbox_process.go b/internal/runtime/sandbox_process.goindex 1b50c4f3..c44e067e 100644--- a/internal/runtime/sandbox_process.go+++ b/internal/runtime/sandbox_process.go@@ -132,7 +132,7 @@ func (s *processSandbox) Exec(ctx context.Context, command CommandSpec, sink Eveif err != nil {return "", err}- return runCommand(cmd, sink)+ return runCommand(cmd, sink, command)}func (s *processSandbox) command(ctx context.Context, command CommandSpec, base []string) (*exec.Cmd, error) {@@ -146,6 +146,13 @@ func (s *processSandbox) command(ctx context.Context, command CommandSpec, baseif err != nil {return nil, err}+ if command.runnerLogin != nil {+ for _, path := range command.runnerLogin.protected {+ for _, variant := range seatbeltPathVariants(path) {+ profile += fmt.Sprintf("\n(deny file-read* file-write* (subpath %s))\n", strconv.Quote(variant))+ }+ }+ }args := append([]string{"-p", profile}, command.Argv...)cmd = exec.CommandContext(ctx, s.binary, args...)case "bwrap":@@ -154,6 +161,21 @@ func (s *processSandbox) command(ctx context.Context, command CommandSpec, basereturn nil, err}args = bwrapPrivateBinds(args, command.privateBinds)+ if command.runnerLogin != nil {+ // Hide host sources and the private journal after all other binds.+ // The managed CLI uses only its own private HOME and host callback.+ masks := append([]string(nil), args[:len(args)-1]...)+ for _, path := range command.runnerLogin.protected {+ if info, err := os.Stat(path); err == nil {+ if info.IsDir() {+ masks = append(masks, "--tmpfs", path, "--remount-ro", path)+ } else {+ masks = append(masks, "--ro-bind", "/dev/null", path)+ }+ }+ }+ args = append(masks, "--")+ }if command.WorkingDir != "" {args = bwrapChdir(args, command.WorkingDir)}diff --git a/scripts/probe-cli-auth-control.py b/scripts/probe-cli-auth-control.pynew file mode 100644index 00000000..9cd1551a--- /dev/null+++ b/scripts/probe-cli-auth-control.py@@ -0,0 +1,486 @@+#!/usr/bin/env python3+"""Opt-in, offline official-CLI auth callback experiment (macOS only).++Uses fake tokens, private temporary homes, a local TLS issuer/model stub, and+sandbox-exec to deny real credential access and non-loopback networking. No+provider credentials are read and no real model is called. This is a protocol+experiment, not a production auth implementation or provider compatibility claim.+"""++import argparse+import base64+import contextlib+import http.server+import json+import os+from pathlib import Path+import queue+import ssl+import subprocess+import sys+import tempfile+import threading+import time+import urllib.request+++def encoded(value):+ return base64.urlsafe_b64encode(json.dumps(value).encode()).rstrip(b"=").decode()+++def access_token(kind, generation):+ if kind == "claude":+ return "sk-ant-" + "oat01-probe-not-a-real-token-" + str(generation)+ return encoded({"alg": "none"}) + "." + encoded({+ "sub": "fake-user-a", "email": "[email protected]", "jti": str(generation),+ "exp": int(time.time()) + 3600,+ "https://api.openai.com/auth": {+ "chatgpt_account_id": "fake-account-a", "chatgpt_user_id": "fake-user-a",+ "chatgpt_plan_type": "plus",+ },+ }) + ".fake-signature"+++def certificates(root):+ ca_config = root / "ca.cnf"+ ca_config.write_text("[req]\nprompt=no\ndistinguished_name=dn\nx509_extensions=ca\n"+ "[dn]\nCN=LoopForge isolated fake CA\n[ca]\n"+ "basicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign,cRLSign\n")+ extensions = root / "leaf.ext"+ extensions.write_text("basicConstraints=critical,CA:FALSE\n"+ "subjectAltName=IP:127.0.0.1,DNS:localhost,DNS:api.anthropic.com,"+ "DNS:console.anthropic.com,DNS:platform.claude.com,DNS:claude.ai\n"+ "keyUsage=critical,digitalSignature,keyEncipherment\n"+ "extendedKeyUsage=serverAuth\n")+ commands = [+ ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", "ca.key", "-out", "ca.pem",+ "-days", "1", "-config", str(ca_config)],+ ["req", "-newkey", "rsa:2048", "-nodes", "-keyout", "leaf.key", "-out", "leaf.csr",+ "-subj", "/CN=localhost"],+ ["x509", "-req", "-in", "leaf.csr", "-CA", "ca.pem", "-CAkey", "ca.key", "-CAcreateserial",+ "-out", "leaf.pem", "-days", "1", "-extfile", str(extensions)],+ ]+ for command in commands:+ subprocess.run(["/usr/bin/openssl", *command], cwd=root, check=True,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ for path in root.iterdir():+ if path.is_file():+ path.chmod(0o600)+++class Issuer:+ def __init__(self, kind):+ self.kind = kind+ self.lock = threading.Lock()+ self.refresh_calls = 0+ self.refused_requests = 0+ self.model_requests = 0+ self.successful_model_requests = 0+ self.blocked_egress = 0+ self.refresh_token = "runner-owned-fake-refresh-0"++ def handler(self):+ issuer = self++ class Handler(http.server.BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *_):+ pass++ def reply(self, code, data):+ body = json.dumps(data).encode()+ self.send_response(code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_CONNECT(self):+ with issuer.lock:+ issuer.blocked_egress += 1+ self.reply(502, {"error": "offline probe blocks external destinations"})++ def do_GET(self):+ if "/accounts/check" in self.path:+ if self.headers.get("Authorization") != "Bearer " + access_token("codex", 1):+ # The fake JWT contains an expiry timestamp, so compare its generation.+ bearer = self.headers.get("Authorization", "").removeprefix("Bearer ")+ try:+ claims = json.loads(base64.urlsafe_b64decode(bearer.split(".")[1] + "=="))+ valid = claims.get("jti") == "1"+ except (ValueError, IndexError):+ valid = False+ if not valid:+ with issuer.lock:+ issuer.refused_requests += 1+ self.reply(401, {"error": {"type": "authentication_error", "code": "token_expired"}})+ return+ self.reply(200, {"accounts": [{+ "id": "fake-account-a", "plan_type": "plus",+ "workspace_backend_origin": "https://" + self.headers["Host"],+ "account_routing_override": "NO_CONSTRAINT", "name": "Fake isolated account",+ }]})+ else:+ self.reply(200, {"models": [], "data": [], "settings": {}})++ def do_POST(self):+ body = self.rfile.read(int(self.headers.get("Content-Length", "0")))+ if self.path in {"/probe-token", "/v1/oauth/token"}:+ request = json.loads(body)+ with issuer.lock:+ if request.get("refresh_token") != issuer.refresh_token:+ self.reply(400, {"error": "invalid_grant"})+ return+ issuer.refresh_calls += 1+ issuer.refresh_token = "runner-owned-fake-refresh-" + str(issuer.refresh_calls)+ token = access_token(issuer.kind, issuer.refresh_calls)+ self.reply(200, {"access_token": token, "refresh_token": issuer.refresh_token, "expires_in": 3600})+ return+ if self.path.split("?")[0].endswith("/messages/count_tokens"):+ self.reply(200, {"input_tokens": 1})+ return+ if self.path.split("?")[0].endswith("/messages"):+ with issuer.lock:+ issuer.model_requests += 1+ if self.headers.get("Authorization") != "Bearer " + access_token("claude", 1):+ with issuer.lock:+ issuer.refused_requests += 1+ self.reply(401, {"type": "error", "error": {+ "type": "authentication_error", "message": "OAuth token has expired. Please obtain a new token or refresh your existing token.",+ }})+ return+ with issuer.lock:+ issuer.successful_model_requests += 1+ events = [+ ("message_start", {"type": "message_start", "message": {+ "id": "msg_fake_probe", "type": "message", "role": "assistant", "content": [],+ "model": "claude-sonnet-4-6", "stop_reason": None, "stop_sequence": None,+ "usage": {"input_tokens": 1, "output_tokens": 0},+ }}),+ ("content_block_start", {"type": "content_block_start", "index": 0,+ "content_block": {"type": "text", "text": ""}}),+ ("content_block_delta", {"type": "content_block_delta", "index": 0,+ "delta": {"type": "text_delta", "text": "OFFLINE_AUTH_OK"}}),+ ("content_block_stop", {"type": "content_block_stop", "index": 0}),+ ("message_delta", {"type": "message_delta", "delta": {+ "stop_reason": "end_turn", "stop_sequence": None}, "usage": {"output_tokens": 1}}),+ ("message_stop", {"type": "message_stop"}),+ ]+ payload = "".join("event: " + event + "\ndata: " + json.dumps(data) + "\n\n"+ for event, data in events).encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ return+ self.reply(200, {})++ return Handler++ def proxy_handler(self, tls):+ issuer = self++ class Proxy(http.server.BaseHTTPRequestHandler):+ def log_message(self, *_):+ pass++ def do_CONNECT(self):+ # Emulate official hostnames locally, so the CLI exercises its+ # first-party OAuth branch. Never forward to an external host.+ if self.path not in {host + ":443" for host in [+ "api.anthropic.com", "console.anthropic.com", "platform.claude.com", "claude.ai"]}:+ with issuer.lock:+ issuer.blocked_egress += 1+ self.send_error(502, "offline probe blocks this destination")+ return+ self.send_response(200, "Connection established")+ self.end_headers()+ self.wfile.flush()+ try:+ secure = tls.wrap_socket(self.connection, server_side=True)+ issuer.handler()(secure, self.client_address, self.server)+ except (ConnectionError, ssl.SSLError):+ pass+ finally:+ self.close_connection = True++ return Proxy+++class Broker:+ """Test-only single writer: all fake refresh tokens stay in this process."""+ def __init__(self, root, issuer, url, ca):+ self.root, self.issuer, self.url = root, issuer, url+ self.lock = threading.Lock()+ self.generation = 0+ self.callbacks = 0+ self.token = "runner-owned-fake-refresh-0"+ self.access = access_token(issuer.kind, 0)+ self.http = urllib.request.build_opener(+ urllib.request.ProxyHandler({}),+ urllib.request.HTTPSHandler(context=ssl.create_default_context(cafile=str(ca))),+ )++ def fresh(self, stale_generation):+ with self.lock:+ self.callbacks += 1+ if stale_generation < self.generation:+ return self.access, self.generation+ request = urllib.request.Request(self.url + "/probe-token", method="POST",+ headers={"Content-Type": "application/json"},+ data=json.dumps({"refresh_token": self.token}).encode())+ with self.http.open(request, timeout=5) as response:+ canonical = json.load(response)+ path = self.root / "runner-private.json"+ pending = self.root / "runner-private.pending"+ with pending.open("w", encoding="utf-8") as file:+ os.chmod(pending, 0o600)+ json.dump(canonical, file)+ file.flush()+ os.fsync(file.fileno())+ os.replace(pending, path)+ directory = os.open(self.root, os.O_RDONLY)+ try:+ os.fsync(directory)+ finally:+ os.close(directory)+ self.token, self.access = canonical["refresh_token"], canonical["access_token"]+ self.generation += 1+ return self.access, self.generation+++class Child:+ def __init__(self, root, binary, kind, url, ca, proxy_url, claude_entrypoint):+ self.root, self.kind = root, kind+ self.generation = 0+ self.events = queue.Queue()+ self.home = root / "home"+ self.home.mkdir(parents=True, mode=0o700)+ config = self.home / (".codex" if kind == "codex" else ".claude")+ config.mkdir(mode=0o700)+ real_home = Path.home()+ profile = '(version 1) (allow default) (deny network*) '+ profile += '(allow network-outbound (remote ip "localhost:*")) '+ for path in [real_home / ".codex", real_home / ".claude", real_home / ".gemini", real_home / "Library/Keychains"]:+ profile += '(deny file-read* file-write* (subpath ' + json.dumps(str(path)) + ')) '+ profile += '(deny file-write* (subpath ' + json.dumps(str(real_home)) + ')) '+ env = {+ "PATH": "/usr/bin:/bin", "HOME": str(self.home), "TMPDIR": str(root), "SHELL": "/bin/sh",+ "XDG_CONFIG_HOME": str(self.home), "XDG_DATA_HOME": str(self.home), "XDG_CACHE_HOME": str(self.home),+ "HTTP_PROXY": proxy_url, "HTTPS_PROXY": proxy_url, "ALL_PROXY": proxy_url, "NO_PROXY": "127.0.0.1,localhost",+ "SSL_CERT_FILE": str(ca), "NODE_EXTRA_CA_CERTS": str(ca), "DO_NOT_TRACK": "1", "NO_COLOR": "1",+ }+ if kind == "codex":+ env.update({"CODEX_HOME": str(config), "CODEX_CA_CERTIFICATE": str(ca), "RUST_LOG": "off",+ "CODEX_APP_SERVER_CHATGPT_BASE_URL": url + "/backend-api/", "OPENAI_BASE_URL": url + "/v1/"})+ (config / "config.toml").write_text('cli_auth_credentials_store = "file"\nchatgpt_base_url = '+ + json.dumps(url + "/backend-api/") + '\n')+ args = ["app-server"]+ else:+ env.update({"CLAUDE_CONFIG_DIR": str(config),+ "CLAUDE_CODE_OAUTH_TOKEN": access_token("claude", 0),+ "CLAUDE_CODE_ENTRYPOINT": claude_entrypoint, "CLAUDE_AGENT_SDK_VERSION": "0.3.326",+ "CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH": "1",+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "DISABLE_AUTOUPDATER": "1"})+ (self.home / ".claude.json").write_text(json.dumps({"hasCompletedOnboarding": True}))+ args = ["--print", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose",+ "--model", "claude-sonnet-4-6", "--max-turns", "1", "--tools", "", "--strict-mcp-config",+ "--setting-sources", ""]+ self.stderr_path = root / "stderr.log"+ self.stderr = self.stderr_path.open("wb")+ self.process = subprocess.Popen(["/usr/bin/sandbox-exec", "-p", profile, binary, *args],+ cwd=root, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=self.stderr, text=True)+ self.reader = threading.Thread(target=self.read, daemon=True)+ self.reader.start()++ def read(self):+ try:+ for line in self.process.stdout:+ try:+ self.events.put(json.loads(line))+ except ValueError:+ pass+ finally:+ self.events.put(None)++ def send(self, message):+ self.process.stdin.write(json.dumps(message) + "\n")+ self.process.stdin.flush()++ def next(self, broker):+ while True:+ event = self.events.get(timeout=45)+ if event is None:+ raise RuntimeError("isolated CLI exited before completing the probe")+ if self.kind == "codex" and event.get("method") == "account/chatgptAuthTokens/refresh":+ if event.get("params", {}).get("previousAccountId") != "fake-account-a":+ raise RuntimeError("refresh callback changed account")+ token, self.generation = broker.fresh(self.generation)+ self.send({"id": event["id"], "result": {+ "accessToken": token, "chatgptAccountId": "fake-account-a", "chatgptPlanType": "plus",+ }})+ elif self.kind == "claude" and event.get("type") == "control_request":+ subtype = event.get("request", {}).get("subtype")+ if subtype != "oauth_token_refresh":+ raise RuntimeError("unexpected control request: " + str(subtype))+ token, self.generation = broker.fresh(self.generation)+ self.send({"type": "control_response", "response": {+ "subtype": "success", "request_id": event["request_id"], "response": {"accessToken": token},+ }})+ else:+ return event++ def rpc(self, method, params, request_id, broker):+ self.send({"id": request_id, "method": method, "params": params})+ while True:+ event = self.next(broker)+ if event.get("id") == request_id:+ if "error" in event:+ raise RuntimeError("isolated RPC failed: " + json.dumps(event["error"]))+ return event.get("result")++ def exercise(self, broker):+ if self.kind == "codex":+ self.rpc("initialize", {"clientInfo": {"name": "loopforge-external-auth-probe", "version": "0.1.0"},+ "capabilities": {"experimentalApi": True}}, 1, broker)+ self.send({"method": "initialized"})+ self.rpc("account/login/start", {"type": "chatgptAuthTokens", "accessToken": access_token("codex", 0),+ "chatgptAccountId": "fake-account-a", "chatgptPlanType": "plus"}, 2, broker)+ result = self.rpc("account/read", {"refreshToken": False}, 3, broker)+ if not result.get("account") or self.generation != 1:+ raise RuntimeError("external login did not recover through a refresh callback")+ else:+ self.send({"type": "control_request", "request_id": "probe-init", "request": {"subtype": "initialize"}})+ while True:+ event = self.next(broker)+ if event.get("type") == "control_response" and event.get("response", {}).get("request_id") == "probe-init":+ if event["response"].get("subtype") != "success":+ raise RuntimeError("Claude initialization failed")+ break+ self.send({"type": "user", "session_id": "", "message": {"role": "user", "content": "Reply OFFLINE_AUTH_OK."}})+ while True:+ event = self.next(broker)+ if event.get("type") == "result":+ if event.get("is_error") or "OFFLINE_AUTH_OK" not in event.get("result", "") or self.generation != 1:+ raise RuntimeError("Claude did not recover through host refresh: " + json.dumps({+ "result": event.get("result"), "errors": event.get("errors"),+ "generation": self.generation})[:500])+ break+ for path in self.home.rglob("*"):+ if path.is_file() and "runner-owned-fake-refresh" in path.read_text(errors="ignore"):+ raise RuntimeError("a sandbox received the Runner-owned fake refresh token")+ return {"passed": True, "refreshGeneration": self.generation}++ def close(self):+ if self.process.poll() is None:+ self.process.terminate()+ try:+ self.process.wait(timeout=3)+ except subprocess.TimeoutExpired:+ self.process.kill()+ self.process.wait()+ self.stderr.close()+ self.process.stdin.close()+ self.process.stdout.close()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("kind", choices=["codex", "claude"])+ parser.add_argument("--binary", help="absolute official CLI binary path")+ parser.add_argument("--serve-only", action="store_true", help="serve an offline fixture for Go integration tests until stdin closes")+ parser.add_argument("--clients", type=int, default=3, choices=[1, 3])+ parser.add_argument("--claude-entrypoint", default="sdk-ts", choices=["sdk-ts", "local-agent"],+ help="local-agent probes a restricted internal CLI path; NOT a supported public SDK contract")+ parser.add_argument("--expect-unsupported-sdk", action="store_true",+ help="negative control: require ordinary sdk-ts to refuse auth without asking the host")+ options = parser.parse_args()+ if not options.serve_only and (not options.binary or not Path(options.binary).is_absolute() or not Path("/usr/bin/sandbox-exec").exists()):+ raise RuntimeError("an absolute binary and macOS sandbox-exec are required")+ with tempfile.TemporaryDirectory(prefix="lf-auth-control-") as directory:+ root = Path(directory)+ certificates(root)+ issuer = Issuer(options.kind)+ class QuietServer(http.server.ThreadingHTTPServer):+ def handle_error(self, *_):+ if not issubclass(sys.exc_info()[0], (ConnectionResetError, BrokenPipeError, ssl.SSLError)):+ super().handle_error(*_)+ server = QuietServer(("127.0.0.1", 0), issuer.handler())+ server.daemon_threads = True+ tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ tls.load_cert_chain(str(root / "leaf.pem"), str(root / "leaf.key"))+ server.socket = tls.wrap_socket(server.socket, server_side=True)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ proxy = QuietServer(("127.0.0.1", 0), issuer.proxy_handler(tls))+ proxy.daemon_threads = True+ threading.Thread(target=proxy.serve_forever, daemon=True).start()+ url = "https://127.0.0.1:" + str(server.server_port)+ if options.serve_only:+ try:+ print(json.dumps({"url": url, "proxy": "http://127.0.0.1:" + str(proxy.server_port), "ca": str(root / "ca.pem")}), flush=True)+ sys.stdin.readline()+ print(json.dumps({"refreshes": issuer.refresh_calls, "refusals": issuer.refused_requests,+ "successes": issuer.successful_model_requests}), flush=True)+ finally:+ server.shutdown()+ server.server_close()+ proxy.shutdown()+ proxy.server_close()+ return+ broker = Broker(root, issuer, url, root / "ca.pem")+ children, failures, results = [], [], []+ try:+ for index in range(options.clients):+ children.append(Child(root / ("client-" + str(index)), options.binary, options.kind, url,+ root / "ca.pem", "http://127.0.0.1:" + str(proxy.server_port), options.claude_entrypoint))+ def exercise(child):+ try:+ results.append(child.exercise(broker))+ except Exception as error:+ failures.append(str(error) or type(error).__name__)+ threads = [threading.Thread(target=exercise, args=(child,)) for child in children]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=55)+ if any(thread.is_alive() for thread in threads):+ failures.append("client did not complete within the probe deadline")+ passed = not failures and len(results) == options.clients and issuer.refresh_calls == 1+ expected_unavailable = False+ if options.expect_unsupported_sdk:+ expected_unavailable = (options.kind == "claude" and options.claude_entrypoint == "sdk-ts"+ and len(failures) == options.clients and not results+ and all(item.startswith("Claude did not recover through host refresh:") for item in failures)+ and broker.callbacks == 0 and issuer.refresh_calls == 0+ and issuer.refused_requests >= options.clients)+ passed = expected_unavailable+ print(json.dumps({"kind": options.kind, "clients": options.clients, "passed": passed,+ "claudeEntrypoint": options.claude_entrypoint if options.kind == "claude" else None,+ "expectedCallbackUnavailable": expected_unavailable,+ "callbacks": broker.callbacks, "issuerRefreshCalls": issuer.refresh_calls,+ "refusedRequests": issuer.refused_requests, "modelRequests": issuer.model_requests,+ "successfulFakeModelRequests": issuer.successful_model_requests,+ "blockedEgress": issuer.blocked_egress, "failures": failures}, ensure_ascii=False))+ if not passed:+ # Only fake credentials can occur here; keep diagnostics short.+ for child in children:+ child.close()+ text = child.stderr_path.read_text(errors="replace")+ if text:+ print("isolated CLI diagnostics:", text[-1600:])+ raise SystemExit(1)+ finally:+ for child in children:+ with contextlib.suppress(Exception):+ child.close()+ server.shutdown()+ server.server_close()+ proxy.shutdown()+ proxy.server_close()+++if __name__ == "__main__":+ main()diff --git a/third_party/go/THIRD_PARTY_NOTICES.txt b/third_party/go/THIRD_PARTY_NOTICES.txtindex d1fffed8..08d6efd8 100644--- a/third_party/go/THIRD_PARTY_NOTICES.txt+++ b/third_party/go/THIRD_PARTY_NOTICES.txt@@ -1063,6 +1063,32 @@ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OROTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THESOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+==============================================================================+github.com/danieljoos/wincred v1.2.3++--- LICENSE ---+The MIT License (MIT)++Copyright (c) 2014 Daniel Joos++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+==============================================================================github.com/davecgh/go-spew v1.1.1@@ -2373,6 +2399,36 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.+==============================================================================+github.com/godbus/dbus/v5 v5.2.2++--- LICENSE ---+Copyright (c) 2013, Georg Reinke (<guelfey at gmail dot com>), Google+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions+are met:++1. Redistributions of source code must retain the above copyright notice,+this list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright+notice, this list of conditions and the following disclaimer in the+documentation and/or other materials provided with the distribution.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+==============================================================================github.com/golang/protobuf v1.5.0@@ -4750,6 +4806,32 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.+==============================================================================+github.com/zalando/go-keyring v0.2.8++--- LICENSE ---+The MIT License (MIT)++Copyright (c) 2016 Zalando SE++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+==============================================================================go.mongodb.org/mongo-driver/v2 v2.5.0diff --git a/web/app/runners.js b/web/app/runners.jsindex b9d70c4c..4f193f8e 100644--- a/web/app/runners.js+++ b/web/app/runners.js@@ -59,10 +59,9 @@ function runnerStatusLabel(status,lastSeen){const runnerCLILabels={'claude-code':'Claude Code','codex':'Codex','codebuddy':'CodeBuddy',opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode'};const runnerCLIIcons={'claude-code':'claude',codex:'codex',codebuddy:'codebuddy',opencode:'opencode',cursor:'cursor',agy:'gemini',kimi:'kimi',pi:'pi',dsh:'deepseek',zcode:'glm'};const runnerAuthLabel={local:'账号登录',personal:'API Key'};-const runnerAuthDescription={local:'Claude Code 和 Codex 可以使用运行 Runner 的系统账号在这台机器上的已有登录。共享对话中,只有机器所有者发言时会使用此登录。',personal:'读取「个人配置」中保存的 API Key。对话使用当前发言人的 Key,SOP 使用运行责任人的 Key。'};+const runnerAuthDescription={local:'Claude Code、Codex 和 Antigravity 可以使用运行 Runner 的系统账号在这台机器上的已有登录,对话与 SOP 的 native、Docker 沙箱均可复用。共享对话中,只有机器所有者发言时会使用此登录。',personal:'读取「个人配置」中保存的 API Key。对话使用当前发言人的 Key,SOP 使用运行责任人的 Key。Antigravity 的 Gemini API Key 按 API 单独计费。'};const runnerOSLabels={darwin:'macOS',linux:'Linux',windows:'Windows'};function runnerKeyDescription(provider){- if(provider==='agy')return 'LoopForge 沙箱目前无法复用 Antigravity 保存在系统凭据库中的登录。请在「个人配置」中填写 Gemini API Key。用量按 Gemini API 单独计费。';if(provider==='zcode')return 'GLM Coding Plan 的 API Key 配合套餐专用地址可使用订阅额度,请在「个人配置」中填写。Start Plan 额度需要登录 ZCode 账号,无法通过 API Key 使用。';return '该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。';}@@ -74,7 +73,7 @@ function runnerPersonalCredentialConfigured(provider){return !!user.agentCliCredentials?.[provider]?.apiKeyConfigured;}function runnerRuntimeSupportsLogin(runtime){- return runtime.provider==='codex'||runtime.provider==='claude-code';+ return runtime.provider==='codex'||runtime.provider==='claude-code'||runtime.provider==='agy';}function runnerRuntimeAuthMode(runtime){return runnerRuntimeSupportsLogin(runtime)&&runtime.authMode!=='personal'?'local':'personal';diff --git a/web/app/workbench.js b/web/app/workbench.jsindex 5abfb1bc..2ef068a5 100644--- a/web/app/workbench.js+++ b/web/app/workbench.js@@ -639,6 +639,12 @@ function credentialFilterHTML(user){}function credentialPanelHTML(user){return `<header class="credential-section-head"><div><h2>个人凭证</h2><p>SOP 使用需求责任人(未指定时为项目 Owner)的个人凭证,保存后对下一次任务生效。</p></div><button type="button" class="credential-btn primary credential-ink" id="credentialAddButton" data-credential-add><span class="credential-turn">${credentialGlyph('plus',15)}</span><span>添加凭证</span></button></header>+ <div class="credential-note credential-subscription-note">+ ${credentialGlyph('monitor',16)}+ <div><strong>使用已有订阅</strong>+ <p>绑定已登录 Claude Code、Codex 或 Antigravity 的机器,选「账号登录」即可用订阅额度运行对话和 SOP,无需 API Key。</p></div>+ <a class="button ghost small" href="#/runners"><span>配置执行机器</span>${credentialGlyph('arrow-right',14)}</a>+ </div><div class="credential-progress">${credentialProgressHTML(user)}</div><div class="credential-toolbar"><div class="credential-filter" role="tablist" aria-label="筛选凭证">${credentialFilterHTML(user)}</div></div><div class="credential-list">${CREDENTIAL_GROUPS.map(group=>credentialGroupHTML(group,user)).join('')}</div>`;diff --git a/web/i18n-en.js b/web/i18n-en.jsindex 8a9a9fcb..c206952f 100644--- a/web/i18n-en.js+++ b/web/i18n-en.js@@ -228,10 +228,12 @@ Object.assign(window.LF_I18N_EN,{});Object.assign(window.LF_I18N_EN,{- "Claude Code 和 Codex 可用账号登录":"Account login for Claude Code and Codex",- "Claude Code 和 Codex 可以使用运行 Runner 的系统账号在这台机器上的已有登录。共享对话中,只有机器所有者发言时会使用此登录。":"Claude Code and Codex can reuse the login of the system user running the Runner. In a shared chat, that login applies to messages from the machine owner.",+ "使用已有订阅":"Use your existing subscription",+ "绑定已登录 Claude Code、Codex 或 Antigravity 的机器,选「账号登录」即可用订阅额度运行对话和 SOP,无需 API Key。":"Connect a machine where you are signed in to Claude Code, Codex, or Antigravity. Select Account login to use your subscription for chats and SOPs without an API key.",+ "配置执行机器":"Configure runners",+ "Claude Code、Codex 和 Antigravity 可用账号登录":"Account login for Claude Code, Codex and Antigravity",+ "Claude Code、Codex 和 Antigravity 可以使用运行 Runner 的系统账号在这台机器上的已有登录,对话与 SOP 的 native、Docker 沙箱均可复用。共享对话中,只有机器所有者发言时会使用此登录。":"Claude Code, Codex and Antigravity can reuse the login of the system user running the Runner, in both native and Docker sandboxes for chats and SOPs. In a shared chat, that login applies to messages from the machine owner.","API Key 说明":"API Key help",- "LoopForge 沙箱目前无法复用 Antigravity 保存在系统凭据库中的登录。请在「个人配置」中填写 Gemini API Key。用量按 Gemini API 单独计费。":"LoopForge sandboxes cannot currently access Antigravity's login in the system credential store. Enter a Gemini API Key in Personal Settings. Gemini API usage is billed separately.","GLM Coding Plan 的 API Key 配合套餐专用地址可使用订阅额度,请在「个人配置」中填写。Start Plan 额度需要登录 ZCode 账号,无法通过 API Key 使用。":"Enter the GLM Coding Plan API key and its dedicated endpoint in Personal Settings to use your subscription allowance. Start Plan allowance requires signing in to ZCode.","该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。":"This CLI supports API keys. With a key included in your provider's subscription, usage counts toward that plan's allowance. Enter the API key in Personal Settings."});diff --git a/web/index.html b/web/index.htmlindex 1585615f..e90e4636 100644--- a/web/index.html+++ b/web/index.html@@ -774,7 +774,7 @@<ol class="runner-steps"><li><span class="runner-step-no">1</span><div><b>安装 CLI</b><small>claude / codex 等</small></div></li><li><span class="runner-step-no">2</span><div><b>执行接入命令</b><small>绑定码 10 分钟有效</small></div></li>- <li><span class="runner-step-no">3</span><div><b>选择认证来源</b><small>Claude Code 和 Codex 可用账号登录</small></div></li>+ <li><span class="runner-step-no">3</span><div><b>选择认证来源</b><small>Claude Code、Codex 和 Antigravity 可用账号登录</small></div></li></ol><div class="runner-command-box"><pre id="bindCliCommand" class="mono">(curl -fsSL --connect-timeout 5 <span id="bindHttpsOrigin">https://</span>/runners/install.sh || curl -fsSL <span id="bindHttpOrigin">http://</span>/runners/install.sh) | bash -s -- --server <span id="bindServerHost"></span> --token <span id="bindToken">生成中…</span> --service</pre>diff --git a/web/platform.css b/web/platform.cssindex 9f8f7efe..89de6401 100644--- a/web/platform.css+++ b/web/platform.css@@ -2439,6 +2439,11 @@ html[data-theme="dark"] .credential-logo.monochrome img{filter:invert(1)}.credential-note>svg{flex:none;margin-top:3px}.credential-note.is-warn{border-color:color-mix(in srgb,#d99a2b 25%,transparent);background:var(--cr-warn-fill);color:var(--cr-warn)}.credential-note b{font-weight:600}+.credential-subscription-note{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:10px;margin-top:14px;padding:10px 12px;font-size:13px}+.credential-subscription-note>svg{align-self:start;color:var(--cr-accent)}+.credential-subscription-note strong{display:block;color:var(--cr-text);font-weight:600}+.credential-subscription-note p{margin:2px 0 0}+.credential-subscription-note .button{white-space:nowrap}.credential-vline{display:flex;align-items:center;gap:7px;margin:0;color:var(--cr-muted);font-size:12px}.credential-vline:empty{display:none}.credential-vline.is-err{color:var(--cr-err)}.credential-vline.is-info{color:var(--cr-info)}.credential-vline.is-warn{color:var(--cr-warn)}@@ -2617,6 +2622,8 @@ html[data-theme="dark"] .credential-scrim::before{background:rgb(0 0 0 / .55)}.credential-account{flex-wrap:wrap}.credential-account-note{margin-left:52px;white-space:normal}.credential-section-head{flex-direction:column;align-items:flex-start}+ .credential-subscription-note{grid-template-columns:auto minmax(0,1fr)}+ .credential-subscription-note .button{grid-column:2;justify-self:start}.credential-next,.credential-ready{width:100%;margin-left:0}.credential-row-main{flex-wrap:wrap}.credential-row-who{flex-basis:calc(100% - 60px)}diff --git a/webtest/tests/runner-codebuddy-environment.test.mjs b/webtest/tests/runner-codebuddy-environment.test.mjsindex ba737d04..9d8232d1 100644--- a/webtest/tests/runner-codebuddy-environment.test.mjs+++ b/webtest/tests/runner-codebuddy-environment.test.mjs@@ -41,8 +41,9 @@ test('runner card offers the short authentication labels with a separate explanaconst select = app.document.querySelector('[data-runner-auth="runner-cb|codex"]');assert.deepEqual([...select.options].map(option=>option.textContent), ['账号登录', 'API Key']);app.document.querySelector('[data-runner-auth-help]').click();- assert.match(app.document.querySelector('#confirmMessage').textContent, /Claude Code 和 Codex.*已有登录/);+ assert.match(app.document.querySelector('#confirmMessage').textContent, /Claude Code、Codex 和 Antigravity.*已有登录.*native、Docker 沙箱/);assert.match(app.document.querySelector('#confirmMessage').textContent, /当前发言人的 Key/);+ assert.match(app.document.querySelector('#confirmMessage').textContent, /Gemini API Key 按 API 单独计费/);});test('runner card indicates a missing CodeBuddy key on its single-line label', async (t) => {@@ -54,7 +55,7 @@ test('runner card indicates a missing CodeBuddy key on its single-line label', aassert.equal(el.classList.contains('missing'), false);});-test('only Claude Code and Codex offer account login and API Key rows explain their credentials', async (t) => {+test('Claude Code, Codex and Antigravity offer account login and API Key rows explain their credentials', async (t) => {const app = await loadApp();t.after(app.close);renderCodeBuddyRow(app, {});@@ -68,15 +69,14 @@ test('only Claude Code and Codex offer account login and API Key rows explain threnderRunnersView();`);const choices = [...app.document.querySelectorAll('[data-runner-auth]')];- assert.deepEqual(choices.map(select => select.dataset.runnerAuth), ['runner-cb|codex', 'runner-cb|claude-code']);+ assert.deepEqual(choices.map(select => select.dataset.runnerAuth), ['runner-cb|codex', 'runner-cb|claude-code', 'runner-cb|agy']);for (const select of choices) {assert.deepEqual([...select.options].map(option => option.textContent), ['账号登录', 'API Key']);}const help = [...app.document.querySelectorAll('[data-runner-key-help]')];- assert.deepEqual(help.map(button => button.dataset.runnerKeyHelp), ['codebuddy', 'cursor', 'agy', 'zcode']);+ assert.deepEqual(help.map(button => button.dataset.runnerKeyHelp), ['codebuddy', 'cursor', 'zcode']);const commonHelp = /支持 API Key.*订阅套餐.*计入对应的套餐额度.*个人配置/;const providerHelp = {- agy: /系统凭据库.*Gemini API Key.*单独计费/,zcode: /GLM Coding Plan.*订阅额度.*Start Plan.*无法通过 API Key 使用/,};for (const button of help) {