fix: make Host environment updates fast and recoverable
Published Host updates could fail while the desktop reverified Runtime against its bundled lock and repeatedly traversed remote payloads. Host preparation now verifies and extracts once, adopts Agent and Runtime on one pinned connection, and uses registered metadata for normal health, capability, and prompt paths. Interrupted commits and adoption retain bounded recovery and rollback state. Desktop and Agent versions are 0.11.8. Remote Projects remain a technical preview; the Agent targets Linux x64 and arm64, with no LoongArch preview. Release note: 修复正式环境 Host 更新失败并移除重复远端包体扫描;中断恢复与清理失败不再破坏已健康环境。
This commit is contained in:
@@ -182,6 +182,17 @@ Release note: 修复左上角项目设置与消息通道项目设置不一致的
|
||||
|
||||
## Release Packaging
|
||||
|
||||
- Unless the user explicitly requests a local Windows package, never run local
|
||||
Windows packaging or launch probes as part of release preparation. In
|
||||
particular, do not run `npm run portable`, Windows
|
||||
`npm run release:package`, direct `electron-builder` packaging, or launch a
|
||||
locally packaged Windows app before publishing a release. Source validation
|
||||
and the native GitHub Actions jobs are the release authorities.
|
||||
- After a release is published, confirm only that the expected Windows assets
|
||||
exist in the public release metadata. Do not locally rebuild or launch the
|
||||
Windows package, download or hash published installers, attach browser
|
||||
automation to a packaged app, or perform exhaustive per-asset network probes
|
||||
unless the user explicitly asks for that additional validation.
|
||||
- `.github/workflows/packages.yml` is the canonical cross-platform packaging
|
||||
workflow. It validates and builds `out` once, then packages on six native
|
||||
runners: Windows, macOS, and Linux, each for x64 and arm64.
|
||||
|
||||
@@ -173,9 +173,12 @@ JSON。签名目录、包描述符、manifest、签名和 payload 的原始字
|
||||
两种 acquisition 都把同一签名 compound `.gbagent` 交付到固定 operation staging,随后
|
||||
共用 control-plane `prepare → commit → Agent activate/health → Runtime activate →
|
||||
finalize → cleanup`。commit 终态持久化,通道丢失时只用 `commit-status` 读取恢复而不
|
||||
重放 commit。prepare 完成后、commit 前快照 Agent/Runtime 五个 metadata 文件;任一 adoption 失败恢复
|
||||
重新下载或准备包;若终态文件不完整,`commit-status` 会从已认证准备状态幂等完成剩余
|
||||
rename/metadata 发布。prepare 完成后、commit 前快照 Agent/Runtime 五个 metadata 文件;任一 adoption 失败恢复
|
||||
原字节或原缺失状态,已发布 side-by-side payload 不成为 current,确认 adoption 后显式
|
||||
cleanup。
|
||||
cleanup。Host 在 prepare 解包时完成一次完整 payload 校验;commit 只复核签名 metadata
|
||||
并原子发布,Agent/Runtime 注册后的 health、capabilities 和 prompt 启动不再遍历或哈希
|
||||
完整 payload。cleanup 失败保留为维护重试,不回滚已健康环境。
|
||||
|
||||
进入“主机与远程执行”设置页只读取本地 Host 列表,不逐台连接。用户点击某台 Host 的
|
||||
“刷新版本”后才执行远端版本和直连准备能力探测。项目切换只更新本地选择,不建立 SSH
|
||||
@@ -217,8 +220,8 @@ Agent、固定 Node 和当前桌面源码维护并适配的签名 OpenCode Runti
|
||||
独立的用户版本流。远程直连所需的有界 one-shot installer 由桌面控制面打包并通过固定
|
||||
SSH prepare channel 发送,不是 `.gbagent` 的必需条目。Host 按签名目录校验完整归档
|
||||
大小和 SHA-256 后,包内固定 Node 解码并运行 installer。两种 acquisition 都在固定
|
||||
operation staging 中执行同一 prepare/commit;commit 终态持久化并可通过只读
|
||||
`commit-status` 恢复。Agent/Runtime adoption 使用 commit 前五个 metadata 文件的原字节
|
||||
operation staging 中执行同一 prepare/commit;commit 终态持久化,`commit-status`
|
||||
可读取终态或从已认证准备状态幂等完成中断的发布。Agent/Runtime adoption 使用 commit 前五个 metadata 文件的原字节
|
||||
或原缺失状态回滚,已发布 side-by-side payload 不会因此成为 current。生产构建命令为:
|
||||
|
||||
```bash
|
||||
|
||||
+2
-2
@@ -23,8 +23,8 @@
|
||||
|
||||
- [x] **直连模型 Runtime**:支持问答、知识总结、受控工具执行和图像生成。
|
||||
- [x] **OpenCode 与 Continue**:使用隔离子进程、环境变量白名单、统一配置、取消、总执行时限、有界流式输出和活动记录;共享进程回收逻辑保留 Windows 完整进程树终止,并对采用独立进程组的 POSIX 子进程执行组回收。交互提问只由前台对话回答,定时任务、远程通道和委派等后台执行遇到提问时会立即失败并提示改为前台运行,避免无限等待。
|
||||
- [x] **托管 SSH OpenCode 闭环(技术预览)**:该能力由“设置 > 平台功能”中的独立“远程项目(技术预览)”页签控制并默认关闭;关闭时不影响任何本地项目、普通桌面功能或桌面发布。启用后可管理固定 Host Key 的 SSH Host、浏览有界远端目录并创建 Ask/Execute 项目;Ask 在 Runtime 边界通过 bubblewrap 保持 Workspace 只读,Execute 使用所选 SSH 账号的完整权限。Main 通过签名 Agent、私有 Unix socket、ACP v3、持久恢复 cursor 和 Main-only 模型桥维持长任务、重连与会话恢复,模型凭据不进入远端。远端组件不嵌入桌面包,项目切换只更新本地选择且不会连接或下载;设置页只读取小型签名目录并按 Linux x64/arm64 显示本地版本、在线最新兼容版本和“有更新/已是最新”,用户点击后才下载签名 `.gbagent`,也可导入/导出离线包。每个复合包包含 Agent、固定 Node 与由桌面源码统一维护适配的 OpenCode Runtime;在线来源跟随“关于与更新”的 GitHub/北京 OSS 选择,签名累计目录绑定最低桌面版本、Agent 协议、架构、大小、SHA-256 和固定 URL。公钥 registry 接受等价 JSON 空白和换行,但仍严格校验 schema、Ed25519 key、环境与撤销;目录、包、manifest、payload 签名和流式 SHA-256 不变。缺少某架构包只使该架构托管 SSH 不可用。项目只保存 Host、远端路径、Runtime 选择和模式;首次实际使用 Workspace/Runtime 时读取 Host current identity,同一进程内其他项目复用已确认 identity 和 Agent 连接。托管 SSH 会话只显示支持的 OpenCode 选择。同一 Host 可并行运行多个项目和对话;活动请求沿精确 resume/replay 恢复,controller 换代遗留的空闲 binding 只在 takeover 已证明且没有活动请求时换新 channel epoch 并恢复原 ACP session。Windows 到 Linux x64 的安装、provider-free 模型桥、断线重放、Session 续接和零残留清理已完成真实 Host 验证;签名 Agent 0.11.2-e2e.12 与 OpenCode Runtime 1.18.9 已完成一次只提交一遍、只调用一个 Ask 原生 read、无标题轮次且精确返回证据内容的有界真实模型验收,当前源码 lock 已更新为待发布 Agent 0.11.7。
|
||||
- [x] **SSH Host 手动环境准备源码链路**:Host Key、认证和系统探针成功后先保存 Host,并只读探测共享 Agent/Runtime;保存 Host、打开项目都不自动安装。Host 卡片只有一个按版本事实显示“安装远程环境”“更新远程环境”或“重新安装”的主按钮,次级 SegmentedControl 选择默认且不持久化的“自动”、Host 下载或 GoodBuddy 传输;“版本匹配”badge 不等同环境健康。自动模式只在 operation/prepare 前探测并择一,显式选择保持有效,任何 prepare、commit 或 adoption 失败都不跨 acquisition 自动 fallback。两种方式把同一签名 compound `.gbagent` 交付到固定 staging 后,共用 control-plane prepare、持久化 commit、Agent activate/health、Runtime activate、finalize 与显式 cleanup。GoodBuddy 路径可在同一次操作下载并验证缺失候选、缓存并取得 lease,再有界流式 SFTP 上传一个归档和其中已验证的 bootstrap Node,不把约 294 MiB 整包读入 Main `Buffer`;Host 再次校验。通道丢失通过只读 `commit-status` 恢复而不重放 commit;组件 adoption 失败恢复 Agent/Runtime 五个 metadata 文件的原字节或原缺失状态,已发布 side-by-side payload 不成为 current。已有项目在实际使用 Workspace/Runtime 时按需解析 Host current identity 并执行固定 `attach-or-bootstrap`,不安装或扫描 payload。详见 [设计说明](./docs/architecture/remote-host-environment-provisioning-design.md)。
|
||||
- [x] **托管 SSH OpenCode 闭环(技术预览)**:该能力由“设置 > 平台功能”中的独立“远程项目(技术预览)”页签控制并默认关闭;关闭时不影响任何本地项目、普通桌面功能或桌面发布。启用后可管理固定 Host Key 的 SSH Host、浏览有界远端目录并创建 Ask/Execute 项目;Ask 在 Runtime 边界通过 bubblewrap 保持 Workspace 只读,Execute 使用所选 SSH 账号的完整权限。Main 通过签名 Agent、私有 Unix socket、ACP v3、持久恢复 cursor 和 Main-only 模型桥维持长任务、重连与会话恢复,模型凭据不进入远端。远端组件不嵌入桌面包,项目切换只更新本地选择且不会连接或下载;设置页只读取小型签名目录并按 Linux x64/arm64 显示本地版本、在线最新兼容版本和“有更新/已是最新”,用户点击后才下载签名 `.gbagent`,也可导入/导出离线包。每个复合包包含 Agent、固定 Node 与由桌面源码统一维护适配的 OpenCode Runtime;在线来源跟随“关于与更新”的 GitHub/北京 OSS 选择,签名累计目录绑定最低桌面版本、Agent 协议、架构、大小、SHA-256 和固定 URL。公钥 registry 接受等价 JSON 空白和换行,但仍严格校验 schema、Ed25519 key、环境与撤销;目录、包、manifest、payload 签名和流式 SHA-256 不变。缺少某架构包只使该架构托管 SSH 不可用。项目只保存 Host、远端路径、Runtime 选择和模式;首次实际使用 Workspace/Runtime 时读取 Host current identity,同一进程内其他项目复用已确认 identity 和 Agent 连接。托管 SSH 会话只显示支持的 OpenCode 选择。同一 Host 可并行运行多个项目和对话;活动请求沿精确 resume/replay 恢复,controller 换代遗留的空闲 binding 只在 takeover 已证明且没有活动请求时换新 channel epoch 并恢复原 ACP session。Windows 到 Linux x64 的安装、provider-free 模型桥、断线重放、Session 续接和零残留清理已完成真实 Host 验证;签名 Agent 0.11.2-e2e.12 与 OpenCode Runtime 1.18.9 已完成一次只提交一遍、只调用一个 Ask 原生 read、无标题轮次且精确返回证据内容的有界真实模型验收,当前源码 lock 已更新为 Agent 0.11.8。
|
||||
- [x] **SSH Host 手动环境准备源码链路**:Host Key、认证和系统探针成功后先保存 Host,并只读探测共享 Agent/Runtime;保存 Host、打开项目都不自动安装。Host 卡片只有一个按版本事实显示“安装远程环境”“更新远程环境”或“重新安装”的主按钮,次级 SegmentedControl 选择默认且不持久化的“自动”、Host 下载或 GoodBuddy 传输;“版本匹配”badge 不等同环境健康。自动模式只在 operation/prepare 前探测并择一,显式选择保持有效,任何 prepare、commit 或 adoption 失败都不跨 acquisition 自动 fallback。两种方式把同一签名 compound `.gbagent` 交付到固定 staging 后,共用 control-plane prepare、持久化 commit、Agent activate/health、Runtime activate、finalize 与显式 cleanup。GoodBuddy 路径可在同一次操作下载并验证缺失候选、缓存并取得 lease,再有界流式 SFTP 上传一个归档和其中已验证的 bootstrap Node,不把约 294 MiB 整包读入 Main `Buffer`;Host 在解包时完成一次完整 payload 校验。通道丢失时 `commit-status` 读取终态或从已认证准备状态幂等完成中断发布;组件 adoption 失败恢复 Agent/Runtime 五个 metadata 文件的原字节或原缺失状态,已健康环境的 cleanup 失败不触发回滚。已有项目在实际使用 Workspace/Runtime 时按需解析 Host current identity 并执行固定 `attach-or-bootstrap`,注册后的 health、capabilities 和 prompt 启动不扫描完整 payload。详见 [设计说明](./docs/architecture/remote-host-environment-provisioning-design.md)。
|
||||
- [ ] **SSH Host 环境准备真实 Host 验收**:源码已可使用当前 format v1 包;仍需完成 GitHub、北京镜像、Linux x64/arm64、取消和离线 GoodBuddy 传输的真实 Host 验收。当前状态不表示已发布或已完成真实 Host 测试。
|
||||
- [x] **DeepSeek Harness(预览)**:使用 GoodBuddy 固定 Host 和 OpenAI 兼容模型连接;Ask 只允许调用 Host 中真实注册的 `read`、`skill` 以及 Main 管理的 Web Search/Fetch 代理,拒绝插件同名冒充,Execute 放行全部已启用内置及插件工具,并以当前用户权限运行。图像输入跟随所选模型连接的能力声明,文本模型在 Host 或模型调用前拒绝图片,图片模型通过有界内联内容和临时 Attachment Store 接收 JPEG/PNG。
|
||||
- [x] **DSH npm 插件市场**:市场默认关闭,由用户显式开启后搜索公共 npm 的 `dsh-plugin` 包,使用捆绑 npm 执行精确版本安装和普通 lifecycle scripts,并支持启停、JSON 配置、移除、失败启动自动停用和离线管理已安装插件;关闭市场只隐藏目录与管理界面,不改变已有插件的启停状态,第三方代码不受 Ask 初始化隔离。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"agentVersion": "0.11.7",
|
||||
"agentVersion": "0.11.8",
|
||||
"protocol": {
|
||||
"major": 2,
|
||||
"minor": 0
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## 状态
|
||||
|
||||
本文记录截至 2026-08-28 的当前代码实现,不定义额外的信任框架。“新增 Host 只探测、Host 卡片手动准备
|
||||
本文记录截至 2026-08-29 的当前代码实现,不定义额外的信任框架。“新增 Host 只探测、Host 卡片手动准备
|
||||
Agent/Runtime、Host 直接从 GitHub/北京镜像下载、项目始终使用 Host current 环境”已经完成源码接线,
|
||||
详细事务与验收边界见
|
||||
[SSH Host 远程环境准备与直连下载设计](./remote-host-environment-provisioning-design.md);
|
||||
@@ -13,10 +13,9 @@ Windows 到 Linux x64 的既有安装、
|
||||
Main-only 模型桥、断线恢复、输出重放、同一 OpenCode Session 续接与终态清理已经在真实
|
||||
Host 上完成 provider-free 验证。上一轮 Linux x64 验收使用 Agent `0.11.2-e2e.12` 与
|
||||
OpenCode Runtime `1.18.9` 完成了一次有界真实模型工具调用;加入每 helper 随机 loopback
|
||||
路径 capability 后,当前源码 lock 已更新为待发布 Agent `0.11.7`。失败的 `agent-v0.11.3`
|
||||
保持不可变且未发布。远程 OpenCode 功能仍处于发布前验证阶段;公开签名 key registry
|
||||
已供应,当前发布门槛是通过独立 Agent workflow 正式发布并公开验证 Linux x64/arm64
|
||||
复合包和签名累计目录。
|
||||
路径 capability 后,Agent `0.11.7` 已通过独立 workflow 发布 Linux x64/arm64 复合包和
|
||||
签名累计目录;当前源码准备 `0.11.8`,修复 Host 更新并消除重复 payload 验证。失败的
|
||||
`agent-v0.11.3` 保持不可变且未发布。
|
||||
|
||||
## 产品语义
|
||||
|
||||
@@ -66,17 +65,16 @@ Detached GoodBuddy Agent
|
||||
|
||||
- Agent bundle 通过 manifest、Ed25519 签名、payload digest、平台和架构校验。
|
||||
- 安装使用当前 SSH 用户目录中的 GoodBuddy-owned 路径和 side-by-side digest 目录。
|
||||
- Agent 代码与固定 Node Runtime 是独立 payload。升级时如果当前 Host Agent 的签名
|
||||
manifest、registry identity、owner/mode/size 和 Node digest 都可验证,且候选
|
||||
manifest 声明完全相同的 Node,安装器直接在新的 side-by-side 目录中复用该 Node;
|
||||
否则正常上传候选 Node。Agent 不匹配不会阻止升级,也不会覆盖旧安装。
|
||||
- Agent 代码与固定 Node Runtime 一起位于签名 compound payload。显式安装或重装从本次
|
||||
已完整校验的准备目录原子发布整个 Agent,不扫描旧安装、不创建跨版本 Node 硬链接;
|
||||
Agent 不匹配不会阻止升级,也不会覆盖 GoodBuddy-owned 路径以外的内容。
|
||||
- 桌面包只携带版本 lock 与 production 公钥,不携带远端 payload。Host 卡片只有一个按
|
||||
版本事实显示“安装远程环境”“更新远程环境”或“重新安装”的主按钮;次级
|
||||
SegmentedControl 选择“自动”“Host 下载”或“GoodBuddy 传输”,默认“自动”且不持久化。
|
||||
每个复合包绑定 Agent、固定 Node 与桌面维护的 OpenCode Runtime 精确工件。添加或重新
|
||||
验证 Host 只保存并探测,不自动传输完整包。
|
||||
- Host 管理独占 Agent/Runtime 的包准备、更新和完整 payload 验证。已有项目的打开和切换
|
||||
只更新本地项目选择。Workspace 和执行路径按需通过安装管理器解析 Host current identity,
|
||||
只更新本地项目选择。Workspace 和执行路径按需读取 Host current registry,
|
||||
执行固定 `attach-or-bootstrap` 并复用当前 Agent 连接;同一进程内复用已确认 identity。
|
||||
它们不取得安装包、不发布组件,也不通过 SFTP 重读或哈希 payload。
|
||||
- Agent 的固定 attach/按需启动命令只读取 Host 管理已提交的 installation registry 和
|
||||
@@ -110,11 +108,13 @@ Detached GoodBuddy Agent
|
||||
bootstrap Node;约 294 MiB 完整包不会一次读入 Main `Buffer`,Host 仍再次校验完整包。
|
||||
- 两种 acquisition 交付到固定 operation staging 后,完全共用 control-plane
|
||||
`prepare → commit → Agent activate/health → Runtime activate → finalize → cleanup`。
|
||||
commit 终态持久化;通道丢失只用 `commit-status` 只读恢复,不重放 commit。prepare
|
||||
commit 终态持久化;通道丢失时 `commit-status` 读取终态,或从已认证准备状态幂等完成
|
||||
中断的目录/metadata 发布,不重新下载或准备包。prepare
|
||||
完成后、commit 前快照 Agent/Runtime 五个 metadata 文件,任一组件 adoption 失败都恢复其原字节或原缺失
|
||||
状态;已经发布的 side-by-side payload 可以保留但不能成为 current。确认 adoption 后
|
||||
才显式 cleanup。首次 bootstrap 不依赖既有 Agent daemon,也不要求 format v1 归档携带
|
||||
`agent/lib/package-installer.cjs`。
|
||||
才显式 cleanup;cleanup 失败只保留维护重试,不回滚健康环境。Host 在 prepare 解包时
|
||||
完成一次完整 payload 校验,commit 和后续注册检查不再遍历包体。首次 bootstrap 不依赖
|
||||
既有 Agent daemon,也不要求 format v1 归档携带 `agent/lib/package-installer.cjs`。
|
||||
- 即使版本号均为当前版本,Host 卡片仍提供同版本“重新安装”,用于修复 registry、签名
|
||||
或安装 identity 异常。GoodBuddy-owned 同 digest 目录损坏时先隔离后替换,并在发布或
|
||||
激活失败时恢复;不要求删除 Host、凭据或引用项目。
|
||||
@@ -187,8 +187,8 @@ Execute 不经过 Ask 的 bubblewrap profile:
|
||||
|
||||
- 直接启动已签名 Runtime entrypoint;
|
||||
- 使用 Main-only 模型桥时,签名 Agent launcher 会 `exec` 候选 manifest 锁定的
|
||||
Node Runtime;完全相同且已验证的 Node 可在 Agent 版本间复用。进程 owner 校验
|
||||
最终 Node executable,而不是已经被替换的 shell launcher 路径;
|
||||
Node Runtime;进程 owner 校验最终 Node executable,而不是已经被替换的 shell
|
||||
launcher 路径;
|
||||
- `cwd` 为项目 Workspace;
|
||||
- 继承 SSH 账号的正常环境、文件系统、进程和网络能力;
|
||||
- 不进行 T2/T3、confinement attestation、approval bridge 或逐工具批准。
|
||||
@@ -245,7 +245,8 @@ Execute 不经过 Ask 的 bubblewrap profile:
|
||||
|
||||
- 2026-08 的本地 fixture 完整验证 Linux x64 Agent `0.11.2-e2e.12`、Node `24.19.0`
|
||||
和 Agent protocol `2.0`;当时没有 arm64 fixture,因此该记录不能作为当前独立发布
|
||||
的双架构验收。当前源码 lock 是待发布版本 `0.11.7`,需要由新的复合包发布流程另行验证。
|
||||
的双架构验收。Agent `0.11.7` 后续已由原生 workflow 发布并公开验证双架构工件;
|
||||
当前源码 lock 是修复候选 `0.11.8`。
|
||||
- 正常 Host 更新路径把 Linux x64 Host 的 Agent 更新为 `0.11.2-e2e.12`,并确认
|
||||
OpenCode Runtime 已安装版本与所需版本均为 `1.18.9`。
|
||||
- 一条新的 Ask 用户操作只提交一次。OpenCode 先在 build 模型轮次请求一个原生
|
||||
|
||||
@@ -150,17 +150,21 @@ daemon 参与。两种 acquisition 的差别只在于如何把同一个签名 co
|
||||
|
||||
1. Main 创建带 operation ID、总时限、输出上限和取消信号的准备操作,并通过固定
|
||||
`prepare` channel 发送有界 one-shot installer 与结构化输入。
|
||||
2. Host 校验归档大小、SHA-256、外层及内层签名、平台、架构、协议和 payload digest,
|
||||
只把候选准备到 side-by-side 目录,不改变 current。
|
||||
2. Host 在解包写入准备目录的同一遍处理中校验归档大小、SHA-256、外层及内层签名、
|
||||
平台、架构、协议和每个 payload digest;不再先完整扫描 payload、再重复解包和哈希。
|
||||
3. `prepare` 完成后、`commit` 前按原字节记录 Agent 与 Runtime 的五个
|
||||
current/registry metadata 文件,
|
||||
同时记录原本缺失的状态。
|
||||
4. `commit` 终态先持久化到 operation staging。控制通道丢失时,Main 只用同一 operation
|
||||
的 `commit-status` 恢复结果,绝不重放 `commit`。
|
||||
5. commit 后依次完成 Agent activate/health、Runtime activate 和 finalize。任一组件
|
||||
adoption 失败都停止候选,并把五个 metadata 文件恢复为原字节或原缺失状态;已经发布的
|
||||
side-by-side payload 可以保留,但不能成为 current。
|
||||
6. Main 确认 adoption 后才显式执行 cleanup,释放 staging、缓存 lease 和操作资源。
|
||||
4. `commit` 只复核有界的签名 manifest、准备回执和入口 metadata,再以目录 rename 发布
|
||||
已准备内容及包内认证的公钥 registry/Runtime lock;不会重读归档或遍历 payload。
|
||||
终态先持久化到 operation staging;控制通道丢失时,同一 operation 的
|
||||
`commit-status` 读取终态,或从已认证准备状态幂等完成中断的 rename/metadata 发布。
|
||||
5. commit 后在同一条已固定身份的 SSH lease 上执行 Agent bootstrap/readiness 和 Runtime
|
||||
activate。新 Agent 最多完整验证一次,新 Runtime 最多完整验证一次;注册成功后的
|
||||
health、capabilities 和 prompt 启动只读取 registry、签名 manifest 与入口 metadata。
|
||||
adoption 失败时停止候选,并把五个 metadata 文件恢复为原字节或原缺失状态。
|
||||
6. Main 确认 adoption 后显式执行 cleanup。cleanup 失败只保留待重试的有界 operation,
|
||||
不回滚已经健康的 Agent/Runtime。
|
||||
|
||||
这不是两个并行安装管理器,也不存在把 Agent 与 Runtime payload 逐文件走 SFTP 安装的
|
||||
第二条路径。两种 acquisition 共享相同的 prepare、commit、adoption、finalize 与 cleanup。
|
||||
@@ -182,16 +186,16 @@ Host 下载返回明确失败;本次操作不自动切换 acquisition,用户
|
||||
后也走同一缓存 lease、上传和 Host 校验流程。
|
||||
- 本地项目和普通桌面打包不依赖任何远端 Agent 工件。
|
||||
|
||||
## 完整包与复用
|
||||
## 完整包与发布
|
||||
|
||||
第一阶段继续发布和下载完整复合 `.gbagent`,不同时引入组件化增量发布:
|
||||
|
||||
- 远程直连和 GoodBuddy 本机下载都会传输完整包,其中包含 Agent、固定 Node 和 OpenCode
|
||||
Runtime。
|
||||
- 新 Agent 安装时,如果旧 manifest、registry identity、owner/mode/size 和 Node digest
|
||||
全部可验证,并且候选声明同一 Node,则使用硬链接复用,不重新写入 Node 数据。
|
||||
- 相同 Runtime bundle digest 已存在且完整时只验证并激活,不重复上传或解包。
|
||||
- Agent 其他文件或变化后的 Runtime 仍按完整候选安装。
|
||||
- 每次显式安装或重装都从本次已经校验并解包的准备目录原子替换对应 Agent 与 Runtime
|
||||
digest 目录,不为节省本机磁盘写入而重新遍历旧目录,也不使用跨安装硬链接。
|
||||
- 操作响应丢失后的同 operation 重试只检查签名 manifest、registry identity 和三份小型
|
||||
trust metadata,不重新读取归档或 payload;正常 cleanup 随后删除准备目录。
|
||||
|
||||
只有真实包体和发布频率证明网络成本仍不可接受时,才另行设计 Agent、Node 和 Runtime
|
||||
独立签名组件目录;本功能不提前引入第二套发布协议。
|
||||
@@ -216,10 +220,13 @@ Host 下载返回明确失败;本次操作不自动切换 acquisition,用户
|
||||
|
||||
同一 Host identity 同时只允许一个由用户启动、Main-owned 的准备操作。重复观察者加入
|
||||
已有操作,不启动第二次发布;窗口关闭、显式取消、Host identity 改变或 Main 退出时执行
|
||||
有界取消。Main 在 commit 前为该 Host 持久化一个不含凭据的 pending operation 记录;
|
||||
有界取消。Main 在 commit 前为该 Host 持久化一个不含凭据的 pending operation 记录,
|
||||
其中包含五份有界 metadata 的原字节/原缺失快照;
|
||||
commit 指令开始后若 SSH 通道、输出或终态丢失,当前操作保留该记录和远端 staging。
|
||||
下一次重试或应用重启后的首次操作先对同一 Host identity 执行只读 `commit-status` 和
|
||||
cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清理后删除 pending 记录。
|
||||
下一次重试或应用重启后的首次操作先对同一 Host identity 执行 `commit-status` 并
|
||||
恢复 adoption;恢复中的 Agent/Runtime adoption 失败仍使用该持久化快照回滚。它不会
|
||||
重新下载或准备包,也不开始第二条 acquisition。环境健康后再重试
|
||||
cleanup,确认清理后删除 pending 记录。
|
||||
取消在最终原子切换完成后不再伪装成回滚成功。
|
||||
|
||||
## 项目创建与切换
|
||||
@@ -264,9 +271,10 @@ cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清
|
||||
- 扩展当前 Host 系统探针和远程环境 inspector,返回瞬时下载准备能力。
|
||||
- 让当前 `RemoteEnvironmentUpdateService` 演进为 Host 环境准备编排器,统一用户手动
|
||||
启动的首次安装和后续更新、自动 acquisition 选择、进度、取消和最终失效。
|
||||
- Host 管理使用安装管理器完成准备、更新和完整验证。项目切换不调用安装管理器;
|
||||
Workspace 和执行路径按需解析 current identity,并在当前进程内复用已确认 identity 和
|
||||
Agent 连接;Host 编辑或环境更新定向清空这些缓存。这些路径不会取得安装包或发布组件。
|
||||
- Host 环境准备编排器直接完成一次 package prepare/commit 及 Agent/Runtime adoption。
|
||||
Workspace 和执行路径只读取 current registry 并调用 Host 侧轻量 identity/health 检查,
|
||||
在当前进程内复用已确认 identity 和 Agent 连接;Host 编辑或环境更新定向清空这些缓存。
|
||||
这些路径不会取得安装包、发布组件或通过 SFTP 扫描 payload。
|
||||
- Host 卡片即使显示相同版本也保留显式重装操作,用于修复 registry、签名或 payload
|
||||
identity 异常;若同一 digest 的 GoodBuddy-owned 目录校验失败,重装会先隔离旧目录,
|
||||
完整发布并验证新目录,失败时恢复旧目录。重装不要求删除 Host、凭据或项目,也不会处理
|
||||
@@ -275,8 +283,8 @@ cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清
|
||||
发送脚本及结构化输入,避免 SSH command 长度限制;既有 package format v1 归档内固定
|
||||
Node 负责解码和运行它。
|
||||
- Preload 只暴露明确的 Host 探测、准备、取消和进度方法,不暴露 URL 或任意 SSH 命令。
|
||||
- 现有 Agent/Runtime side-by-side、Node 硬链接复用、Host identity 二次核对、Host 端
|
||||
发布后复验、连接失效和项目稳定配置事务继续作为唯一实现。
|
||||
- 现有 Agent/Runtime side-by-side、固定 SSH lease、Host 端一次完整验证、注册后轻量检查、
|
||||
连接失效和项目稳定配置事务继续作为唯一实现。
|
||||
|
||||
## 迁移
|
||||
|
||||
@@ -288,6 +296,9 @@ cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清
|
||||
- 如果 Host 未就绪或版本不兼容,项目仍可在本地选择,但实际远程操作失败;不再走旧的
|
||||
隐式安装。
|
||||
- 已下载或导入的本地 `.gbagent` 保持可用,不能因加入远程直连而迁移或删除。
|
||||
- `0.11.7` 遗留的 version-1 pending operation 没有持久化 metadata 快照,也没有新格式的
|
||||
已解包准备状态;`0.11.8` 只清理其暂存并重新执行一次认证 prepare,不尝试用新 installer
|
||||
续写旧 commit。
|
||||
- 远程直连继续使用现有 package format version 1,不要求归档携带 installer,也不要求
|
||||
目录声明额外的 bootstrap 能力元数据。
|
||||
|
||||
@@ -303,7 +314,9 @@ cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清
|
||||
4. 直接下载严格匹配签名目录中的 URL、大小和 SHA-256;GoodBuddy 传输可在同一次操作中
|
||||
下载并验证缺失候选,以有界流式 SFTP 上传完整归档和已验证 bootstrap Node。Host 对
|
||||
两者完成相同的外层与内层签名、路径、架构、协议和 payload 校验。
|
||||
5. 相同 Node 在可验证且支持硬链接时不重复传输或写入;相同 Runtime digest 不重复安装。
|
||||
5. Host 对本次候选只完成一次完整 payload 校验;commit、adoption、health、capabilities
|
||||
和 prompt 启动不得再次遍历或哈希完整 Agent/Runtime,显式重装仍能用本次准备内容修复
|
||||
同 digest 的损坏目录。
|
||||
6. 创建、打开和切换项目不会产生 `.gbagent` 下载、Agent payload SFTP 上传或安装目录发布。
|
||||
7. 未就绪 Host 不能创建远程项目;已有项目仍可本地选择,但远程操作失败并引导到 Host 设置。
|
||||
8. Host 编辑或更新后,引用项目使用 Host 管理的当前连接和 current registry,不读取项目
|
||||
@@ -317,5 +330,7 @@ cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清
|
||||
仍待完成。
|
||||
12. Host 不可达或远端目录不存在时,用户仍可从项目浮动管理入口删除本地项目;删除 Host
|
||||
会列出并本地清理全部关联项目,但不会连接 Host 或删除任何远端目录和内容。
|
||||
13. commit 终态可在通道丢失后用 `commit-status` 只读恢复且不重放;Agent 或 Runtime
|
||||
adoption 失败恢复五个 metadata 文件的原字节/原缺失状态,确认 adoption 后显式 cleanup。
|
||||
13. commit 终态可在通道丢失后用 `commit-status` 读取,或从已认证准备状态幂等完成;
|
||||
Agent 或 Runtime
|
||||
adoption 失败恢复五个 metadata 文件的原字节/原缺失状态;已健康环境的 cleanup
|
||||
失败保留为维护重试,不触发环境回滚。
|
||||
|
||||
@@ -586,12 +586,15 @@ attach 并读取 current registry,不存在项目中的旧 Host revision 或
|
||||
prepare channel 发送有界 one-shot installer;Host 先验证目录绑定的归档大小和 SHA-256,
|
||||
再由 format v1 归档内固定 Node 解码并运行 installer。归档无需包含
|
||||
`agent/lib/package-installer.cjs`,目录不提供或检查额外的 bootstrap 能力元数据。
|
||||
- Agent 与 Runtime 各自维护版本,签名摘要标识精确工件;使用 side-by-side 安装、自检和
|
||||
健康切换,失败时不改变当前项目绑定。相同且可验证的 Node 使用硬链接复用,相同 Runtime
|
||||
digest 不重复安装。
|
||||
- commit 终态持久化,控制通道丢失时只用 `commit-status` 恢复而不重放。prepare 完成后、commit 前快照
|
||||
- Agent 与 Runtime 各自维护版本,签名摘要标识精确工件。Host 在解包到准备目录的同一遍
|
||||
处理中完成完整 payload 校验,commit 只复核签名 metadata 并原子替换 side-by-side
|
||||
目录,不重新读取归档、扫描旧目录或使用跨安装硬链接。
|
||||
- commit 终态持久化;控制通道丢失时,`commit-status` 读取终态,或从已认证准备状态
|
||||
幂等完成中断的目录/metadata 发布,不重新下载或准备包。prepare 完成后、commit 前快照
|
||||
Agent/Runtime 五个 metadata 文件;任一组件 adoption 失败恢复原字节或原缺失状态,
|
||||
已发布 payload 不得成为 current,确认 adoption 后显式 cleanup。
|
||||
已发布 payload 不得成为 current。新 Agent/Runtime 各自最多完整验证一次;注册后的
|
||||
health、capabilities 和 prompt 启动只检查 registry、签名 manifest 与入口 metadata。
|
||||
确认 adoption 后显式 cleanup,cleanup 失败不回滚健康环境。
|
||||
- 握手报告 installation、Daemon boot identity、协议、系统、架构、用户监督器和能力。
|
||||
- 在远程执行路径规范化、Git、文件、PTY、进程组和 Runtime 管理。
|
||||
- 持久化有界 Agent 到 Main 输出;SSH 断开后 Agent 继续运行,同一 Agent 重连时只恢复
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "goodbuddy",
|
||||
"version": "0.11.7",
|
||||
"version": "0.11.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "goodbuddy",
|
||||
"version": "0.11.7",
|
||||
"version": "0.11.8",
|
||||
"license": "0BSD",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "0.25.1",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "goodbuddy",
|
||||
"version": "0.11.7",
|
||||
"version": "0.11.8",
|
||||
"private": true,
|
||||
"description": "Secure desktop AI workspace with controlled Agent Runtimes",
|
||||
"desktopName": "GoodBuddy",
|
||||
|
||||
@@ -1,6 +1,40 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"releases": [
|
||||
{
|
||||
"version": "0.11.8",
|
||||
"releasedAt": "2026-08-29",
|
||||
"notes": {
|
||||
"zh-CN": {
|
||||
"highlights": [
|
||||
"GoodBuddy 0.11.8 修复正式环境中的 Host 更新失败,并显著缩短 Agent 与 OpenCode Runtime 的安装、恢复和日常启动校验。"
|
||||
],
|
||||
"features": [],
|
||||
"fixes": [
|
||||
"**Host 更新恢复可用。** 修复已发布 OpenCode Runtime 在采用阶段被桌面内置锁重复校验而失败的问题。Host 现在信任签名复合包中的版本锁和身份,并在同一条固定 SSH 连接上完成 Agent 启动、健康检查与 Runtime 激活。",
|
||||
"**不再重复扫描远端包体。** Host 在解包时完成完整 SHA-256 与签名校验;commit 只检查签名元数据。Main 不再通过 SFTP 逐文件读取 Agent/Runtime,后续健康检查、能力发现和每次提问只使用已登记 identity、manifest 与入口元数据。仍保留 SHA-256,提速来自消除重复读取。",
|
||||
"**中断与清理更可靠。** 中断的 commit 可从已认证准备状态继续,待恢复操作会保留五份元数据快照并在采用失败时回滚。环境已健康后,暂存清理失败只留待重试,不再错误回滚;安装错误会显示具体的有界原因。"
|
||||
],
|
||||
"notices": [
|
||||
"**技术预览与版本要求。** 远程项目仍默认关闭且为技术预览。Host 需要安装单独发布的 Agent `0.11.8`,提供 Linux x64 和 arm64;桌面包不内置 Agent 或远程 Runtime,本次不构建 LoongArch 预览。"
|
||||
]
|
||||
},
|
||||
"en-US": {
|
||||
"highlights": [
|
||||
"GoodBuddy 0.11.8 fixes Host updates in production and substantially reduces Agent and OpenCode Runtime verification during installation, recovery, and normal startup."
|
||||
],
|
||||
"features": [],
|
||||
"fixes": [
|
||||
"**Host updates work again.** Fixed published OpenCode Runtime adoption failing because it was redundantly checked against the desktop-bundled lock. The Host now uses the signed compound package's lock and identity, then starts and health-checks the Agent and activates Runtime on one pinned SSH connection.",
|
||||
"**No repeated remote payload scans.** The Host completes full SHA-256 and signature verification while extracting, and commit checks only signed metadata. Main no longer reads Agent or Runtime file trees over SFTP. Later health, capability, and prompt paths use registered identities, manifests, and entrypoint metadata. SHA-256 remains; the speedup comes from eliminating rereads.",
|
||||
"**Reliable interruption and cleanup recovery.** Interrupted commits resume from authenticated prepared state. Pending recovery keeps snapshots of all five metadata files and restores them if adoption fails. Once the environment is healthy, staging cleanup failures are retried instead of rolling it back, and bounded installer errors retain their concrete cause."
|
||||
],
|
||||
"notices": [
|
||||
"**Technical preview and version requirement.** Remote Projects remain disabled by default and in technical preview. Hosts require the separately published Agent `0.11.8` for Linux x64 or arm64. Desktop packages do not embed the Agent or remote Runtime, and this release does not build a LoongArch preview."
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "0.11.7",
|
||||
"releasedAt": "2026-08-29",
|
||||
|
||||
@@ -192,11 +192,13 @@ describe('Agent CLI fixed command contract', () => {
|
||||
state: 'ready' as const,
|
||||
installationId
|
||||
}))
|
||||
const verifyInstallation = vi.fn(async () => verified)
|
||||
const dependencies: AgentCliDependencies = {
|
||||
installationPaths: () => installationPaths,
|
||||
releaseKeyRegistry,
|
||||
installationRegistry,
|
||||
verifyInstallation: async () => verified,
|
||||
verifyInstallation,
|
||||
loadRegisteredInstallation: async () => verified,
|
||||
createLifecycle: (() => ({
|
||||
status,
|
||||
bootstrap
|
||||
@@ -227,6 +229,21 @@ describe('Agent CLI fixed command contract', () => {
|
||||
).toBe(0)
|
||||
expect(status).toHaveBeenCalledOnce()
|
||||
expect(bootstrap).toHaveBeenCalledOnce()
|
||||
expect(
|
||||
installationRegistry.snapshot().current?.installationId
|
||||
).toBe(installationId)
|
||||
|
||||
expect(
|
||||
await runAgentCli(
|
||||
buildFixedAgentCliArgv(installationId, {
|
||||
kind: 'lifecycle',
|
||||
action: 'adopt'
|
||||
}),
|
||||
{ ...dependencies, io: cliIo() }
|
||||
)
|
||||
).toBe(0)
|
||||
expect(verifyInstallation).toHaveBeenCalledOnce()
|
||||
expect(bootstrap).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('dispatches generated attach argv using only derived managed paths', async () => {
|
||||
@@ -469,6 +486,31 @@ describe('Agent CLI fixed command contract', () => {
|
||||
architecture: 'x64',
|
||||
runtimeVersion: '1.18.9'
|
||||
})
|
||||
|
||||
expect(
|
||||
await runAgentCli(
|
||||
buildFixedAgentCliArgv(
|
||||
verifyAgentInstallationId('install-1'),
|
||||
{
|
||||
kind: 'runtime-activate',
|
||||
runtimeId: 'opencode',
|
||||
bundleDigest,
|
||||
architecture: 'x64',
|
||||
forceVerification: true
|
||||
}
|
||||
),
|
||||
{
|
||||
runtimePaths: () => paths,
|
||||
runtimeReleaseKeyRegistry: releaseKeyRegistry,
|
||||
runtimeLock: {} as RemoteRuntimeLock,
|
||||
runtimeRegistry: registry,
|
||||
verifyRuntime,
|
||||
currentArchitecture: () => 'x64',
|
||||
io: cliIo()
|
||||
}
|
||||
)
|
||||
).toBe(0)
|
||||
expect(verifyRuntime).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('derives Runtime paths and rejects activation argv injection', async () => {
|
||||
|
||||
+183
-40
@@ -39,6 +39,7 @@ import {
|
||||
RuntimeBundleRegistry
|
||||
} from './runtime-bundle-registry'
|
||||
import {
|
||||
loadRegisteredRuntimeBundle,
|
||||
readRemoteRuntimeLock,
|
||||
verifyRuntimeBundle,
|
||||
type VerifiedRuntimeBundle
|
||||
@@ -111,6 +112,7 @@ export type ManagedRuntimePaths = {
|
||||
}
|
||||
|
||||
const LIFECYCLE_ACTIONS = new Set([
|
||||
'adopt',
|
||||
'bootstrap',
|
||||
'status',
|
||||
'health',
|
||||
@@ -225,7 +227,8 @@ async function runRuntime(
|
||||
'installation-id',
|
||||
'runtime-id',
|
||||
'bundle-digest',
|
||||
'architecture'
|
||||
'architecture',
|
||||
'force-verification'
|
||||
])
|
||||
requireOptions(options, [
|
||||
'installation-id',
|
||||
@@ -243,6 +246,16 @@ async function runRuntime(
|
||||
const architecture = validateRuntimeArchitecture(
|
||||
options.architecture!
|
||||
)
|
||||
const forceVerification =
|
||||
options['force-verification'] === 'true'
|
||||
if (
|
||||
options['force-verification'] !== undefined &&
|
||||
!forceVerification
|
||||
) {
|
||||
throw new Error(
|
||||
'Invalid Runtime force-verification option'
|
||||
)
|
||||
}
|
||||
const hostArchitecture =
|
||||
dependencies.currentArchitecture?.() ??
|
||||
currentAgentArchitecture()
|
||||
@@ -271,15 +284,30 @@ async function runRuntime(
|
||||
runtimeRoot: paths.runtimeRoot,
|
||||
storagePath: paths.registryPath
|
||||
})
|
||||
const verified = await (
|
||||
dependencies.verifyRuntime ?? verifyRuntimeBundle
|
||||
)(paths.bundleDirectory, {
|
||||
const verificationOptions = {
|
||||
architecture,
|
||||
releaseKeyRegistry,
|
||||
runtimeLock,
|
||||
verificationEnvironment:
|
||||
dependencies.runtimeVerificationEnvironment ?? 'production'
|
||||
})
|
||||
} as const
|
||||
const registered = registry.find(
|
||||
runtimeId,
|
||||
bundleDigest,
|
||||
architecture
|
||||
)
|
||||
const verified =
|
||||
registered === undefined || forceVerification
|
||||
? await (
|
||||
dependencies.verifyRuntime ?? verifyRuntimeBundle
|
||||
)(paths.bundleDirectory, verificationOptions)
|
||||
: await loadRegisteredRuntimeBundle(
|
||||
registered.bundleDirectory,
|
||||
{
|
||||
...verificationOptions,
|
||||
registered: registered.entry
|
||||
}
|
||||
)
|
||||
assertActivatedRuntimeIdentity(
|
||||
verified,
|
||||
runtimeId,
|
||||
@@ -352,7 +380,8 @@ async function runDaemon(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered'
|
||||
'registered',
|
||||
verified
|
||||
).recordCurrentDaemonReady(daemon.status().daemonBootId)
|
||||
await (dependencies.waitForShutdown?.() ?? waitForShutdownSignal())
|
||||
} finally {
|
||||
@@ -374,7 +403,7 @@ async function runAttach(
|
||||
installationId,
|
||||
dependencies
|
||||
)
|
||||
await loadManagedInstallation(
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
@@ -399,7 +428,8 @@ async function runAttach(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered'
|
||||
'registered',
|
||||
verified
|
||||
).bootstrap()
|
||||
}
|
||||
})
|
||||
@@ -451,10 +481,17 @@ async function runDoctor(
|
||||
options['installation-id']!
|
||||
)
|
||||
const paths = resolveInstallationPaths(installationId, dependencies)
|
||||
const status = await createDetachedLifecycle(
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const status = await createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered',
|
||||
verified
|
||||
).status()
|
||||
io.output.write(`${JSON.stringify({
|
||||
platform: process.platform,
|
||||
@@ -479,48 +516,150 @@ async function runLifecycle(
|
||||
options['installation-id']!
|
||||
)
|
||||
const paths = resolveInstallationPaths(installationId, dependencies)
|
||||
const { verified, registry } = await verifyManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
switch (action) {
|
||||
case 'bootstrap': {
|
||||
registry.stageCandidate(verified)
|
||||
prepareManagedSocketDirectory(paths)
|
||||
const status = await lifecycle.bootstrap()
|
||||
io.output.write(`${JSON.stringify(status)}\n`)
|
||||
break
|
||||
}
|
||||
case 'status': {
|
||||
registry.assertVerifiedRole(verified, ['current', 'candidate'])
|
||||
io.output.write(`${JSON.stringify(await lifecycle.status())}\n`)
|
||||
break
|
||||
}
|
||||
case 'health': {
|
||||
registry.assertVerifiedRole(verified, ['current', 'candidate'])
|
||||
const status = await lifecycle.health()
|
||||
if (
|
||||
registry.snapshot().candidate?.installationId ===
|
||||
case 'adopt': {
|
||||
const { verified, registry } =
|
||||
await verifyManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const alreadyCurrent =
|
||||
registry.snapshot().current?.installationId ===
|
||||
installationId
|
||||
) {
|
||||
if (!alreadyCurrent) {
|
||||
registry.stageCandidate(verified)
|
||||
}
|
||||
prepareManagedSocketDirectory(paths)
|
||||
const status = await createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'verified',
|
||||
verified
|
||||
).bootstrap()
|
||||
if (!alreadyCurrent) {
|
||||
registry.promoteCandidate(installationId)
|
||||
}
|
||||
io.output.write(`${JSON.stringify(status)}\n`)
|
||||
break
|
||||
}
|
||||
case 'bootstrap': {
|
||||
const agentRoot = dirname(
|
||||
dirname(dirname(paths.executablePath))
|
||||
)
|
||||
const registry =
|
||||
dependencies.installationRegistry ??
|
||||
new InstallationRegistry({
|
||||
storagePath: resolve(agentRoot, 'registry.json')
|
||||
})
|
||||
const snapshot = registry.snapshot()
|
||||
const current = snapshot.current?.installationId ===
|
||||
installationId
|
||||
? snapshot.current
|
||||
: undefined
|
||||
const candidate = snapshot.candidate?.installationId ===
|
||||
installationId
|
||||
? snapshot.candidate
|
||||
: undefined
|
||||
const registered = current ?? candidate
|
||||
const isNewInstallation = registered === undefined
|
||||
const verified = isNewInstallation
|
||||
? (
|
||||
await verifyManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
).verified
|
||||
: await (
|
||||
dependencies.loadRegisteredInstallation ??
|
||||
loadRegisteredAgentBundle
|
||||
)(dirname(paths.executablePath), {
|
||||
installationId,
|
||||
architecture: currentAgentArchitecture(),
|
||||
registered
|
||||
})
|
||||
if (isNewInstallation) {
|
||||
registry.stageCandidate(verified)
|
||||
}
|
||||
prepareManagedSocketDirectory(paths)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'verified',
|
||||
verified
|
||||
)
|
||||
const status = await lifecycle.bootstrap()
|
||||
if (current === undefined) {
|
||||
registry.promoteCandidate(installationId)
|
||||
}
|
||||
io.output.write(`${JSON.stringify(status)}\n`)
|
||||
break
|
||||
}
|
||||
case 'status': {
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered',
|
||||
verified
|
||||
)
|
||||
io.output.write(`${JSON.stringify(await lifecycle.status())}\n`)
|
||||
break
|
||||
}
|
||||
case 'health': {
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered',
|
||||
verified
|
||||
)
|
||||
const status = await lifecycle.health()
|
||||
io.output.write(`${JSON.stringify(status)}\n`)
|
||||
break
|
||||
}
|
||||
case 'stop': {
|
||||
registry.assertVerifiedRole(verified, ['current', 'candidate'])
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered',
|
||||
verified
|
||||
)
|
||||
io.output.write(`${JSON.stringify(await lifecycle.stop())}\n`)
|
||||
break
|
||||
}
|
||||
case 'retire': {
|
||||
registry.assertVerifiedRole(verified, ['current', 'candidate'])
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered',
|
||||
verified
|
||||
)
|
||||
io.output.write(`${JSON.stringify(await lifecycle.retire())}\n`)
|
||||
break
|
||||
}
|
||||
@@ -531,7 +670,8 @@ function createDetachedLifecycle(
|
||||
installationId: string,
|
||||
paths: ManagedInstallationPaths,
|
||||
dependencies: AgentCliDependencies,
|
||||
identitySource: 'verified' | 'registered' = 'verified'
|
||||
identitySource: 'verified' | 'registered' = 'verified',
|
||||
verifiedInstallation?: VerifiedInstalledAgentBundle
|
||||
): DetachedAgentLifecycle {
|
||||
const options: DetachedAgentLifecycleOptions = {
|
||||
installationId,
|
||||
@@ -539,6 +679,9 @@ function createDetachedLifecycle(
|
||||
stateDirectory: paths.stateDirectory,
|
||||
socketPath: paths.socketPath,
|
||||
verifyInstallation: async () => {
|
||||
if (verifiedInstallation !== undefined) {
|
||||
return verifiedInstallation
|
||||
}
|
||||
if (identitySource === 'registered') {
|
||||
return (
|
||||
await loadManagedInstallation(
|
||||
|
||||
@@ -116,7 +116,8 @@ describe('Agent installation registry', () => {
|
||||
installationId: 'install-a',
|
||||
agentVersion: '0.11.0',
|
||||
manifestSha256: 'a'.repeat(64),
|
||||
arch: 'x64'
|
||||
arch: 'x64',
|
||||
protocol: { major: 1, minor: 0 }
|
||||
}
|
||||
})
|
||||
expect(readFileSync(storagePath, 'utf8')).toBe(legacyBytes)
|
||||
|
||||
@@ -221,7 +221,8 @@ function entryFromVerified(
|
||||
installationId: verified.installationId,
|
||||
agentVersion: verified.manifest.agentVersion,
|
||||
manifestSha256: verified.manifestSha256,
|
||||
arch: verified.manifest.arch
|
||||
arch: verified.manifest.arch,
|
||||
protocol: verified.manifest.protocol
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -310,7 +310,16 @@ async function loadRegisteredAgentBundleUnchecked(
|
||||
manifestBytes
|
||||
) ||
|
||||
manifest.agentVersion !== registered.agentVersion ||
|
||||
manifest.arch !== registered.arch
|
||||
manifest.arch !== registered.arch ||
|
||||
(
|
||||
registered.protocol !== undefined &&
|
||||
(
|
||||
manifest.protocol.major !==
|
||||
registered.protocol.major ||
|
||||
manifest.protocol.minor !==
|
||||
registered.protocol.minor
|
||||
)
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'Agent manifest does not match the Host-managed registry'
|
||||
|
||||
@@ -268,7 +268,7 @@ function harness(input: {
|
||||
const backend = new RuntimeAcpBackend({
|
||||
journal,
|
||||
resolveRuntimeBundle: vi.fn(async () => resolved),
|
||||
reverifyRuntimeBundle: vi.fn(async () => verifiedBundle()),
|
||||
loadRegisteredRuntimeBundle: vi.fn(async () => verifiedBundle()),
|
||||
resolveWorkspace: vi.fn(async (preparation) => ({
|
||||
workspaceIdentity: preparation.workspaceIdentity,
|
||||
workspaceDirectory: '/workspace',
|
||||
|
||||
@@ -227,7 +227,7 @@ export type RuntimeAcpBackendOptions = {
|
||||
runtimeId: string,
|
||||
runtimeBundleDigest: string
|
||||
): RuntimeAcpResolvedBundle | Promise<RuntimeAcpResolvedBundle>
|
||||
reverifyRuntimeBundle(
|
||||
loadRegisteredRuntimeBundle(
|
||||
resolved: RuntimeAcpResolvedBundle,
|
||||
preparation: RemotePromptOperationPreparation
|
||||
): RuntimeAcpVerifiedBundle | Promise<RuntimeAcpVerifiedBundle>
|
||||
@@ -947,7 +947,7 @@ export class RuntimeAcpBackend {
|
||||
|
||||
let verified: RuntimeAcpVerifiedBundle
|
||||
try {
|
||||
verified = await this.#options.reverifyRuntimeBundle(
|
||||
verified = await this.#options.loadRegisteredRuntimeBundle(
|
||||
binding.resolvedBundle,
|
||||
preparation
|
||||
)
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
} from './managed-paths'
|
||||
import type { InstalledBundleVerificationEnvironment } from './installed-bundle-verifier'
|
||||
import {
|
||||
verifyRuntimeBundle,
|
||||
loadRegisteredRuntimeBundle,
|
||||
type VerifiedRuntimeBundle
|
||||
} from './runtime-bundle-verifier'
|
||||
|
||||
@@ -120,6 +120,27 @@ export class RuntimeBundleRegistry {
|
||||
entry: RuntimeRegistryEntry
|
||||
bundleDirectory: string
|
||||
} {
|
||||
const resolved = this.find(
|
||||
runtimeIdInput,
|
||||
bundleDigestInput,
|
||||
architecture
|
||||
)
|
||||
if (resolved === undefined) {
|
||||
throw new Error(
|
||||
'Runtime bundle is not the verified current bundle'
|
||||
)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
find(
|
||||
runtimeIdInput: string,
|
||||
bundleDigestInput: string,
|
||||
architecture: AgentArchitecture
|
||||
): {
|
||||
entry: RuntimeRegistryEntry
|
||||
bundleDirectory: string
|
||||
} | undefined {
|
||||
const runtimeId = agentIdentifierSchema.parse(runtimeIdInput)
|
||||
const bundleDigest = sha256DigestSchema.parse(bundleDigestInput)
|
||||
this.#state = this.#load({ createIfMissing: false })
|
||||
@@ -130,9 +151,7 @@ export class RuntimeBundleRegistry {
|
||||
candidate.architecture === architecture
|
||||
)
|
||||
if (entry === undefined) {
|
||||
throw new Error(
|
||||
'Runtime bundle is not the verified current bundle'
|
||||
)
|
||||
return undefined
|
||||
}
|
||||
return {
|
||||
entry: { ...entry },
|
||||
@@ -231,7 +250,7 @@ export class RuntimeBundleRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
export function createVerifiedRuntimeCapabilitySource(options: {
|
||||
type VerifiedRuntimeCapabilitySourceOptions = {
|
||||
registry: RuntimeBundleRegistry
|
||||
architecture: AgentArchitecture
|
||||
releaseKeyRegistry: AgentReleaseKeyRegistry
|
||||
@@ -241,53 +260,65 @@ export function createVerifiedRuntimeCapabilitySource(options: {
|
||||
filesystemPlatform?: NodeJS.Platform
|
||||
uid?: number
|
||||
reportError?: (message: string, error: unknown) => void
|
||||
}): () => Promise<DaemonCapabilities['runtimes']> {
|
||||
loadRegistered?: (
|
||||
entry: RuntimeRegistryEntry,
|
||||
bundleDirectory: string
|
||||
) => Promise<VerifiedRuntimeBundle>
|
||||
}
|
||||
|
||||
export function createVerifiedRuntimeCapabilitySource(
|
||||
options: VerifiedRuntimeCapabilitySourceOptions
|
||||
): () => Promise<DaemonCapabilities['runtimes']> {
|
||||
return async () => await loadVerifiedRuntimeCapabilities(options)
|
||||
}
|
||||
|
||||
async function loadVerifiedRuntimeCapabilities(options: {
|
||||
registry: RuntimeBundleRegistry
|
||||
architecture: AgentArchitecture
|
||||
releaseKeyRegistry: AgentReleaseKeyRegistry
|
||||
runtimeLock: RemoteRuntimeLock
|
||||
verificationEnvironment?: InstalledBundleVerificationEnvironment
|
||||
enforceFilesystemMode?: boolean
|
||||
filesystemPlatform?: NodeJS.Platform
|
||||
uid?: number
|
||||
reportError?: (message: string, error: unknown) => void
|
||||
}): Promise<DaemonCapabilities['runtimes']> {
|
||||
async function loadVerifiedRuntimeCapabilities(
|
||||
options: VerifiedRuntimeCapabilitySourceOptions
|
||||
): Promise<DaemonCapabilities['runtimes']> {
|
||||
const capabilities: DaemonCapabilities['runtimes'] = []
|
||||
for (const entry of options.registry.current(options.architecture)) {
|
||||
try {
|
||||
const verified = await verifyRuntimeBundle(
|
||||
const bundleDirectory =
|
||||
options.registry.bundleDirectory(
|
||||
entry.runtimeId,
|
||||
entry.bundleDigest
|
||||
),
|
||||
{
|
||||
architecture: options.architecture,
|
||||
releaseKeyRegistry: options.releaseKeyRegistry,
|
||||
runtimeLock: options.runtimeLock,
|
||||
...(options.verificationEnvironment === undefined
|
||||
? {}
|
||||
: {
|
||||
verificationEnvironment:
|
||||
options.verificationEnvironment
|
||||
}),
|
||||
...(options.enforceFilesystemMode === undefined
|
||||
? {}
|
||||
: {
|
||||
enforceFilesystemMode:
|
||||
options.enforceFilesystemMode
|
||||
}),
|
||||
...(options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: {
|
||||
filesystemPlatform: options.filesystemPlatform
|
||||
}),
|
||||
...(options.uid === undefined ? {} : { uid: options.uid })
|
||||
}
|
||||
)
|
||||
)
|
||||
const verified = options.loadRegistered === undefined
|
||||
? await loadRegisteredRuntimeBundle(
|
||||
bundleDirectory,
|
||||
{
|
||||
registered: entry,
|
||||
architecture: options.architecture,
|
||||
releaseKeyRegistry:
|
||||
options.releaseKeyRegistry,
|
||||
runtimeLock: options.runtimeLock,
|
||||
...(options.verificationEnvironment === undefined
|
||||
? {}
|
||||
: {
|
||||
verificationEnvironment:
|
||||
options.verificationEnvironment
|
||||
}),
|
||||
...(options.enforceFilesystemMode === undefined
|
||||
? {}
|
||||
: {
|
||||
enforceFilesystemMode:
|
||||
options.enforceFilesystemMode
|
||||
}),
|
||||
...(options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: {
|
||||
filesystemPlatform:
|
||||
options.filesystemPlatform
|
||||
}),
|
||||
...(options.uid === undefined
|
||||
? {}
|
||||
: { uid: options.uid })
|
||||
}
|
||||
)
|
||||
: await options.loadRegistered(
|
||||
entry,
|
||||
bundleDirectory
|
||||
)
|
||||
if (
|
||||
verified.manifest.runtimeVersion !== entry.runtimeVersion ||
|
||||
verified.manifestDigest !== entry.manifestDigest ||
|
||||
@@ -326,6 +357,7 @@ function entryFromVerified(
|
||||
architecture: verified.manifest.architecture,
|
||||
bundleDigest: verified.manifest.bundleDigest,
|
||||
manifestDigest: verified.manifestDigest,
|
||||
runtimeAdapterDigest: verified.manifest.adapterDigest,
|
||||
acpCapabilitiesDigest:
|
||||
verified.manifest.acpCapabilitiesDigest
|
||||
})
|
||||
|
||||
@@ -155,7 +155,7 @@ describe('Remote Runtime bundle verifier', () => {
|
||||
).rejects.toThrow(/managed directory/iu)
|
||||
})
|
||||
|
||||
it('advertises only a bundle that still verifies against its registry', async () => {
|
||||
it('uses registered metadata without rereading Runtime payload files', async () => {
|
||||
const fixture = await createBundle()
|
||||
const runtimeRoot = dirname(dirname(fixture.bundleDirectory))
|
||||
const registry = new RuntimeBundleRegistry({
|
||||
@@ -198,6 +198,18 @@ describe('Remote Runtime bundle verifier', () => {
|
||||
join(fixture.bundleDirectory, 'licenses', 'opencode.txt'),
|
||||
'mutated'
|
||||
)
|
||||
await expect(capabilities()).resolves.toHaveLength(1)
|
||||
expect(reportError).not.toHaveBeenCalled()
|
||||
|
||||
writeFileSync(
|
||||
join(fixture.bundleDirectory, 'bin', 'opencode'),
|
||||
Buffer.concat([
|
||||
readFileSync(
|
||||
join(fixture.bundleDirectory, 'bin', 'opencode')
|
||||
),
|
||||
Buffer.from('changed')
|
||||
])
|
||||
)
|
||||
await expect(capabilities()).resolves.toEqual([])
|
||||
expect(reportError).toHaveBeenCalledWith(
|
||||
'Verified Runtime unavailable: opencode',
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export {
|
||||
canonicalRuntimeManifestBytes,
|
||||
loadRegisteredRuntimeBundle,
|
||||
readRemoteRuntimeLock,
|
||||
runtimeManifestSignaturePayload,
|
||||
verifyRuntimeBundle,
|
||||
@@ -8,5 +9,6 @@ export {
|
||||
|
||||
export type {
|
||||
VerifiedRuntimeBundle,
|
||||
LoadRegisteredRuntimeBundleOptions,
|
||||
VerifyRuntimeBundleOptions
|
||||
} from '../shared/node/runtime-bundle-verifier'
|
||||
|
||||
@@ -37,7 +37,7 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('production Runtime composition', () => {
|
||||
it('keeps ACP live and reloads managed metadata installed after daemon startup', async () => {
|
||||
it('loads metadata installed after startup and caches the registered Runtime identity', async () => {
|
||||
const fixture = await createRuntimeBundleTestFixture()
|
||||
const root = fixture.root
|
||||
temporaryPaths.push(root)
|
||||
@@ -121,11 +121,8 @@ describe('production Runtime composition', () => {
|
||||
}, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
)
|
||||
await expect(protocol.runtimes()).resolves.toEqual([])
|
||||
expect(reportError).toHaveBeenCalledWith(
|
||||
'Verified Runtime unavailable: opencode',
|
||||
expect.any(Error)
|
||||
)
|
||||
await expect(protocol.runtimes()).resolves.toHaveLength(1)
|
||||
expect(reportError).not.toHaveBeenCalled()
|
||||
|
||||
await expect(protocol.dispose()).resolves.toBeUndefined()
|
||||
events.close()
|
||||
|
||||
@@ -7,6 +7,9 @@ import type {
|
||||
AgentReleaseKeyRegistry
|
||||
} from '../shared/agent-installation-contracts'
|
||||
import type { AgentFrame } from '../shared/agent-protocol'
|
||||
import type {
|
||||
RuntimeRegistryEntry
|
||||
} from '../shared/remote-environment-registry-contracts'
|
||||
import type { RemoteRuntimeLock } from '../shared/remote-runtime-launch-contracts'
|
||||
import type { EventJournal } from './event-journal'
|
||||
import {
|
||||
@@ -22,7 +25,8 @@ import {
|
||||
} from './runtime-bundle-registry'
|
||||
import {
|
||||
readRemoteRuntimeLock,
|
||||
verifyRuntimeBundle
|
||||
loadRegisteredRuntimeBundle,
|
||||
type VerifiedRuntimeBundle
|
||||
} from './runtime-bundle-verifier'
|
||||
import { RuntimeAcpBackend } from './runtime-acp-backend'
|
||||
import type { ProtocolMethodContext } from './protocol-server'
|
||||
@@ -111,37 +115,90 @@ export async function createProductionRuntimeProtocol(
|
||||
}
|
||||
return registry
|
||||
}
|
||||
const currentVerificationOptions = async () => {
|
||||
const metadataOptions =
|
||||
options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: { filesystemPlatform: options.filesystemPlatform }
|
||||
const [releaseKeyRegistry, runtimeLock] = await Promise.all([
|
||||
options.releaseKeyRegistry ??
|
||||
readManagedAgentReleaseKeyRegistry(
|
||||
join(runtimeRoot, 'release-keys.json'),
|
||||
metadataOptions
|
||||
),
|
||||
options.runtimeLock ??
|
||||
readRemoteRuntimeLock(
|
||||
join(runtimeRoot, 'remote-runtime-lock.json'),
|
||||
metadataOptions
|
||||
)
|
||||
])
|
||||
return {
|
||||
architecture: options.architecture,
|
||||
releaseKeyRegistry,
|
||||
runtimeLock,
|
||||
verificationEnvironment,
|
||||
...(options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: { filesystemPlatform: options.filesystemPlatform })
|
||||
} as const
|
||||
let verificationOptionsPromise:
|
||||
| Promise<{
|
||||
architecture: AgentArchitecture
|
||||
releaseKeyRegistry: AgentReleaseKeyRegistry
|
||||
runtimeLock: RemoteRuntimeLock
|
||||
verificationEnvironment: 'production' | 'test'
|
||||
filesystemPlatform?: NodeJS.Platform
|
||||
}>
|
||||
| undefined
|
||||
const currentVerificationOptions = () => {
|
||||
verificationOptionsPromise ??= (async () => {
|
||||
const metadataOptions =
|
||||
options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: {
|
||||
filesystemPlatform:
|
||||
options.filesystemPlatform
|
||||
}
|
||||
const [releaseKeyRegistry, runtimeLock] =
|
||||
await Promise.all([
|
||||
options.releaseKeyRegistry ??
|
||||
readManagedAgentReleaseKeyRegistry(
|
||||
join(runtimeRoot, 'release-keys.json'),
|
||||
metadataOptions
|
||||
),
|
||||
options.runtimeLock ??
|
||||
readRemoteRuntimeLock(
|
||||
join(
|
||||
runtimeRoot,
|
||||
'remote-runtime-lock.json'
|
||||
),
|
||||
metadataOptions
|
||||
)
|
||||
])
|
||||
return {
|
||||
architecture: options.architecture,
|
||||
releaseKeyRegistry,
|
||||
runtimeLock,
|
||||
verificationEnvironment,
|
||||
...(options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: {
|
||||
filesystemPlatform:
|
||||
options.filesystemPlatform
|
||||
})
|
||||
}
|
||||
})()
|
||||
void verificationOptionsPromise.catch(() => {
|
||||
verificationOptionsPromise = undefined
|
||||
})
|
||||
return verificationOptionsPromise
|
||||
}
|
||||
const verifiedRuntimeCache =
|
||||
new Map<string, Promise<VerifiedRuntimeBundle>>()
|
||||
const loadRegistered = (
|
||||
entry: RuntimeRegistryEntry,
|
||||
bundleDirectory: string
|
||||
): Promise<VerifiedRuntimeBundle> => {
|
||||
const key = `${bundleDirectory}\0${JSON.stringify(entry)}`
|
||||
const cached = verifiedRuntimeCache.get(key)
|
||||
if (cached !== undefined) {
|
||||
return cached
|
||||
}
|
||||
const loading = (async () =>
|
||||
await loadRegisteredRuntimeBundle(
|
||||
bundleDirectory,
|
||||
{
|
||||
...(await currentVerificationOptions()),
|
||||
registered: entry
|
||||
}
|
||||
))()
|
||||
verifiedRuntimeCache.set(key, loading)
|
||||
void loading.catch(() => {
|
||||
if (verifiedRuntimeCache.get(key) === loading) {
|
||||
verifiedRuntimeCache.delete(key)
|
||||
}
|
||||
})
|
||||
return loading
|
||||
}
|
||||
const verifiedCapabilities = async () => {
|
||||
const source = createVerifiedRuntimeCapabilitySource({
|
||||
registry: currentRegistry(),
|
||||
...(await currentVerificationOptions()),
|
||||
loadRegistered,
|
||||
reportError: options.reportError
|
||||
})
|
||||
return await source()
|
||||
@@ -182,10 +239,10 @@ export async function createProductionRuntimeProtocol(
|
||||
bundleDigest,
|
||||
options.architecture
|
||||
),
|
||||
reverifyRuntimeBundle: async (resolved) => {
|
||||
const verified = await verifyRuntimeBundle(
|
||||
resolved.bundleDirectory,
|
||||
await currentVerificationOptions()
|
||||
loadRegisteredRuntimeBundle: async (resolved) => {
|
||||
const verified = await loadRegistered(
|
||||
resolved.entry,
|
||||
resolved.bundleDirectory
|
||||
)
|
||||
if (
|
||||
verified.manifestDigest !== resolved.entry.manifestDigest ||
|
||||
|
||||
@@ -1260,11 +1260,6 @@ if (hasSingleInstanceLock) {
|
||||
resolver: startupRemoteAgentServices.targetResolver,
|
||||
sshPool: startupRemoteAgentServices.sshPool,
|
||||
agentPackageManager,
|
||||
agentInstallationManager:
|
||||
startupRemoteAgentServices.installationManager,
|
||||
runtimeInstallationManager:
|
||||
startupManagedRemoteExecutionServices
|
||||
.runtimeInstallationManager,
|
||||
operationStore:
|
||||
new RemoteEnvironmentOperationStore(
|
||||
app.getPath('userData')
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,21 @@
|
||||
export function boundedDiagnostic(
|
||||
value: string,
|
||||
maximumCharacters = 800
|
||||
): string {
|
||||
let printable = ''
|
||||
for (const character of value) {
|
||||
const code = character.charCodeAt(0)
|
||||
if (
|
||||
code === 9 ||
|
||||
code === 10 ||
|
||||
code === 13 ||
|
||||
(code >= 32 && code !== 127)
|
||||
) {
|
||||
printable += character
|
||||
}
|
||||
}
|
||||
return printable
|
||||
.replace(/\s+/gu, ' ')
|
||||
.trim()
|
||||
.slice(0, maximumCharacters)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,255 @@
|
||||
import { settleBoundedly } from './bounded-settlement'
|
||||
|
||||
const DISPOSE_WAIT_TIMEOUT_MS = 5_000
|
||||
|
||||
type ActiveActivation<TValue, TPhase extends string> = {
|
||||
promise: Promise<TValue>
|
||||
controller: AbortController
|
||||
progressCallbacks: Set<(phase: TPhase) => void>
|
||||
waiters: number
|
||||
settled: boolean
|
||||
}
|
||||
|
||||
export class HostActivationCoordinator<
|
||||
TValue,
|
||||
TPhase extends string
|
||||
> {
|
||||
readonly #maximumConcurrentHosts: number
|
||||
readonly #capacityError: () => Error
|
||||
readonly #disposeMessage: string
|
||||
readonly #active =
|
||||
new Map<string, ActiveActivation<TValue, TPhase>>()
|
||||
readonly #current = new Map<
|
||||
string,
|
||||
{
|
||||
targetKey: string
|
||||
variantKey: string
|
||||
value: TValue
|
||||
}
|
||||
>()
|
||||
readonly #cacheGenerations = new Map<string, number>()
|
||||
#closed = false
|
||||
#disposePromise: Promise<void> | undefined
|
||||
|
||||
constructor(options: {
|
||||
maximumConcurrentHosts?: number
|
||||
capacityError: () => Error
|
||||
disposeMessage: string
|
||||
}) {
|
||||
this.#maximumConcurrentHosts =
|
||||
options.maximumConcurrentHosts ?? 8
|
||||
this.#capacityError = options.capacityError
|
||||
this.#disposeMessage = options.disposeMessage
|
||||
if (
|
||||
!Number.isSafeInteger(this.#maximumConcurrentHosts) ||
|
||||
this.#maximumConcurrentHosts <= 0 ||
|
||||
this.#maximumConcurrentHosts > 32
|
||||
) {
|
||||
throw new Error(
|
||||
'Host activation concurrency limit is invalid'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
assertAvailable(): void {
|
||||
if (this.#closed) {
|
||||
throw new Error(this.#disposeMessage)
|
||||
}
|
||||
}
|
||||
|
||||
cached(
|
||||
hostId: string,
|
||||
targetKey: string,
|
||||
variantKey: string
|
||||
): TValue | undefined {
|
||||
this.assertAvailable()
|
||||
const cached = this.#current.get(hostId)
|
||||
return (
|
||||
cached?.targetKey === targetKey &&
|
||||
cached.variantKey === variantKey
|
||||
)
|
||||
? cached.value
|
||||
: undefined
|
||||
}
|
||||
|
||||
cachedForHost(
|
||||
hostId: string,
|
||||
variantKey: string
|
||||
): TValue | undefined {
|
||||
this.assertAvailable()
|
||||
const cached = this.#current.get(hostId)
|
||||
return cached?.variantKey === variantKey
|
||||
? cached.value
|
||||
: undefined
|
||||
}
|
||||
|
||||
run(options: {
|
||||
hostId: string
|
||||
targetKey: string
|
||||
variantKey: string
|
||||
signal?: AbortSignal
|
||||
onProgress?: (phase: TPhase) => void
|
||||
operation: (
|
||||
signal: AbortSignal,
|
||||
progress: (phase: TPhase) => void
|
||||
) => Promise<TValue>
|
||||
}): Promise<TValue> {
|
||||
this.assertAvailable()
|
||||
options.signal?.throwIfAborted()
|
||||
const operationKey =
|
||||
`${options.targetKey}\0${options.variantKey}`
|
||||
const existing = this.#active.get(operationKey)
|
||||
if (existing) {
|
||||
return this.#waitForActive(existing, options)
|
||||
}
|
||||
if (this.#active.size >= this.#maximumConcurrentHosts) {
|
||||
throw this.#capacityError()
|
||||
}
|
||||
|
||||
const cacheGeneration =
|
||||
this.#cacheGenerations.get(options.hostId) ?? 0
|
||||
const progressCallbacks = new Set<
|
||||
(phase: TPhase) => void
|
||||
>()
|
||||
if (options.onProgress) {
|
||||
progressCallbacks.add(options.onProgress)
|
||||
}
|
||||
const progress = (phase: TPhase): void => {
|
||||
for (const callback of progressCallbacks) {
|
||||
emitProgress(callback, phase)
|
||||
}
|
||||
}
|
||||
const controller = new AbortController()
|
||||
const promise = options.operation(
|
||||
controller.signal,
|
||||
progress
|
||||
).then((value) => {
|
||||
if (
|
||||
(this.#cacheGenerations.get(options.hostId) ?? 0) ===
|
||||
cacheGeneration
|
||||
) {
|
||||
this.#current.set(options.hostId, {
|
||||
targetKey: options.targetKey,
|
||||
variantKey: options.variantKey,
|
||||
value
|
||||
})
|
||||
}
|
||||
return value
|
||||
})
|
||||
const active: ActiveActivation<TValue, TPhase> = {
|
||||
promise,
|
||||
controller,
|
||||
progressCallbacks,
|
||||
waiters: 0,
|
||||
settled: false
|
||||
}
|
||||
this.#active.set(operationKey, active)
|
||||
void promise.finally(() => {
|
||||
active.settled = true
|
||||
if (this.#active.get(operationKey) === active) {
|
||||
this.#active.delete(operationKey)
|
||||
}
|
||||
}).catch(() => undefined)
|
||||
return this.#waitForActive(active, options)
|
||||
}
|
||||
|
||||
invalidate(hostId: string): void {
|
||||
this.#current.delete(hostId)
|
||||
this.#cacheGenerations.set(
|
||||
hostId,
|
||||
(this.#cacheGenerations.get(hostId) ?? 0) + 1
|
||||
)
|
||||
}
|
||||
|
||||
dispose(): Promise<void> {
|
||||
if (this.#disposePromise) {
|
||||
return this.#disposePromise
|
||||
}
|
||||
this.#closed = true
|
||||
this.#current.clear()
|
||||
this.#cacheGenerations.clear()
|
||||
const operations = [...this.#active.values()]
|
||||
const reason = new DOMException(
|
||||
this.#disposeMessage,
|
||||
'AbortError'
|
||||
)
|
||||
for (const operation of operations) {
|
||||
operation.controller.abort(reason)
|
||||
}
|
||||
this.#disposePromise = settleBoundedly(
|
||||
operations.map((operation) => operation.promise),
|
||||
DISPOSE_WAIT_TIMEOUT_MS
|
||||
)
|
||||
return this.#disposePromise
|
||||
}
|
||||
|
||||
async #waitForActive(
|
||||
active: ActiveActivation<TValue, TPhase>,
|
||||
options: {
|
||||
signal?: AbortSignal
|
||||
onProgress?: (phase: TPhase) => void
|
||||
}
|
||||
): Promise<TValue> {
|
||||
active.waiters += 1
|
||||
if (options.onProgress) {
|
||||
active.progressCallbacks.add(options.onProgress)
|
||||
}
|
||||
try {
|
||||
return await waitForOperation(
|
||||
active.promise,
|
||||
options.signal
|
||||
)
|
||||
} finally {
|
||||
if (options.onProgress) {
|
||||
active.progressCallbacks.delete(options.onProgress)
|
||||
}
|
||||
active.waiters -= 1
|
||||
if (
|
||||
active.waiters === 0 &&
|
||||
!active.settled &&
|
||||
!active.controller.signal.aborted
|
||||
) {
|
||||
active.controller.abort(
|
||||
new DOMException(
|
||||
'Host activation has no remaining waiters',
|
||||
'AbortError'
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function emitProgress<TPhase extends string>(
|
||||
callback: (phase: TPhase) => void,
|
||||
phase: TPhase
|
||||
): void {
|
||||
try {
|
||||
callback(phase)
|
||||
} catch {
|
||||
// Progress observers cannot alter activation state.
|
||||
}
|
||||
}
|
||||
|
||||
function waitForOperation<T>(
|
||||
operation: Promise<T>,
|
||||
signal?: AbortSignal
|
||||
): Promise<T> {
|
||||
if (!signal) {
|
||||
return operation
|
||||
}
|
||||
signal.throwIfAborted()
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const abort = (): void => reject(
|
||||
signal.reason ??
|
||||
new DOMException(
|
||||
'The operation was aborted',
|
||||
'AbortError'
|
||||
)
|
||||
)
|
||||
signal.addEventListener('abort', abort, { once: true })
|
||||
void operation.then(resolve, reject).finally(() => {
|
||||
signal.removeEventListener('abort', abort)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -21,13 +21,11 @@ import {
|
||||
RemoteRuntimeInstallationManager,
|
||||
type RemoteRuntimeActivator
|
||||
} from './remote-runtime-installation-manager'
|
||||
import {
|
||||
loadRemoteRuntimeVerificationMetadata
|
||||
} from './remote-runtime-resource-loader'
|
||||
import {
|
||||
createManagedModelBridge,
|
||||
reconcileStartupModelCalls
|
||||
} from './managed-model-bridge'
|
||||
import { boundedDiagnostic } from './bounded-diagnostic'
|
||||
|
||||
const RUNTIME_BINDING_DATABASE_NAME = 'remote-runtime-bindings.sqlite'
|
||||
const MODEL_CALL_DATABASE_NAME = 'remote-model-calls-v2.sqlite'
|
||||
@@ -101,19 +99,9 @@ export class ManagedRemoteExecutionServices {
|
||||
)
|
||||
).installationId
|
||||
signal.throwIfAborted()
|
||||
const current = await options.agentServices.targetResolver.resolve(
|
||||
lease.identity.hostId
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
if (
|
||||
runtimeId !== 'opencode' ||
|
||||
current.host.id !== lease.identity.hostId ||
|
||||
current.hostRevision !== lease.identity.hostRevision ||
|
||||
current.hostKeyGeneration !==
|
||||
lease.identity.hostKeyGeneration
|
||||
) {
|
||||
if (runtimeId !== 'opencode') {
|
||||
throw new Error(
|
||||
'Remote Agent or SSH host identity changed before Runtime activation'
|
||||
'Remote Runtime identity is unsupported'
|
||||
)
|
||||
}
|
||||
const result = await lease.runAgentRuntimeAction(
|
||||
@@ -127,17 +115,20 @@ export class ManagedRemoteExecutionServices {
|
||||
signal
|
||||
)
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error('Remote Runtime activation failed')
|
||||
const detail = boundedDiagnostic(
|
||||
`${result.stderr}\n${result.stdout}`
|
||||
)
|
||||
throw new Error(
|
||||
detail.length > 0
|
||||
? `Remote Runtime activation failed: ${detail}`
|
||||
: `Remote Runtime activation failed (exit ${String(result.exitCode)})`
|
||||
)
|
||||
}
|
||||
}
|
||||
this.runtimeInstallationManager =
|
||||
new RemoteRuntimeInstallationManager({
|
||||
resolver: options.agentServices.targetResolver,
|
||||
sshPool: options.agentServices.sshPool,
|
||||
loadVerificationMetadata: () =>
|
||||
loadRemoteRuntimeVerificationMetadata(
|
||||
this.runtimeResourcePaths
|
||||
),
|
||||
activate
|
||||
})
|
||||
this.runtimeValidator = new ManagedRemoteProjectRuntimeValidator({
|
||||
|
||||
@@ -42,6 +42,39 @@ describe('RemoteEnvironmentOperationStore', () => {
|
||||
await expect(store.load(operation.hostId)).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('persists bounded metadata snapshots for post-commit recovery', async () => {
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), 'goodbuddy-environment-operation-')
|
||||
)
|
||||
temporaryDirectories.push(root)
|
||||
const store = new RemoteEnvironmentOperationStore(root)
|
||||
const recovered: PendingRemoteEnvironmentOperation = {
|
||||
...operation,
|
||||
version: 2,
|
||||
metadataSnapshots: [
|
||||
'.goodbuddy/agent/release-keys.json',
|
||||
'.goodbuddy/agent/registry.json',
|
||||
'.goodbuddy/runtimes/release-keys.json',
|
||||
'.goodbuddy/runtimes/remote-runtime-lock.json',
|
||||
'.goodbuddy/runtimes/registry.json'
|
||||
].map((path, index) => ({
|
||||
path: path as never,
|
||||
uid: 1000,
|
||||
...(index === 1
|
||||
? {}
|
||||
: {
|
||||
contentsBase64:
|
||||
Buffer.from(`metadata-${index}`).toString('base64')
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
await store.save(recovered)
|
||||
await expect(store.load(operation.hostId)).resolves.toEqual(
|
||||
recovered
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a mismatched or oversized recovery record', async () => {
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), 'goodbuddy-environment-operation-')
|
||||
@@ -58,7 +91,7 @@ describe('RemoteEnvironmentOperationStore', () => {
|
||||
const [record] = await readdir(files)
|
||||
await writeFile(
|
||||
join(files, record!),
|
||||
Buffer.alloc(64 * 1024 + 1)
|
||||
Buffer.alloc(8 * 1024 * 1024 + 1)
|
||||
)
|
||||
|
||||
await expect(store.load(operation.hostId)).rejects.toThrow(
|
||||
|
||||
@@ -6,13 +6,12 @@ import {
|
||||
writeJsonFileAtomically
|
||||
} from '../settings-file-utils'
|
||||
|
||||
const MAXIMUM_RECORD_BYTES = 64 * 1024
|
||||
const MAXIMUM_RECORD_BYTES = 8 * 1024 * 1024
|
||||
const OPERATION_ID_PATTERN =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u
|
||||
const SHA256_PATTERN = /^[a-f0-9]{64}$/u
|
||||
|
||||
export type PendingRemoteEnvironmentOperation = {
|
||||
version: 1
|
||||
type PendingRemoteEnvironmentOperationBase = {
|
||||
hostId: string
|
||||
targetIdentity: string
|
||||
operationId: string
|
||||
@@ -21,6 +20,28 @@ export type PendingRemoteEnvironmentOperation = {
|
||||
urls: readonly string[]
|
||||
}
|
||||
|
||||
export type PersistedRemoteEnvironmentMetadataSnapshot = {
|
||||
path:
|
||||
| '.goodbuddy/agent/release-keys.json'
|
||||
| '.goodbuddy/agent/registry.json'
|
||||
| '.goodbuddy/runtimes/release-keys.json'
|
||||
| '.goodbuddy/runtimes/remote-runtime-lock.json'
|
||||
| '.goodbuddy/runtimes/registry.json'
|
||||
contentsBase64?: string
|
||||
uid: number
|
||||
}
|
||||
|
||||
export type PendingRemoteEnvironmentOperation =
|
||||
PendingRemoteEnvironmentOperationBase &
|
||||
(
|
||||
| { version: 1 }
|
||||
| {
|
||||
version: 2
|
||||
metadataSnapshots:
|
||||
readonly PersistedRemoteEnvironmentMetadataSnapshot[]
|
||||
}
|
||||
)
|
||||
|
||||
export class RemoteEnvironmentOperationStore {
|
||||
readonly #directory: string
|
||||
|
||||
@@ -91,11 +112,23 @@ function parsePendingOperation(
|
||||
value: unknown,
|
||||
expectedHostId: string
|
||||
): PendingRemoteEnvironmentOperation {
|
||||
if (
|
||||
typeof value !== 'object' ||
|
||||
value === null ||
|
||||
Object.keys(value).sort().join('\0') !==
|
||||
[
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
const record = value as Record<string, unknown>
|
||||
const version = record.version
|
||||
const expectedKeys = version === 2
|
||||
? [
|
||||
'hostId',
|
||||
'metadataSnapshots',
|
||||
'operationId',
|
||||
'sha256',
|
||||
'size',
|
||||
'targetIdentity',
|
||||
'urls',
|
||||
'version'
|
||||
]
|
||||
: [
|
||||
'hostId',
|
||||
'operationId',
|
||||
'sha256',
|
||||
@@ -103,13 +136,15 @@ function parsePendingOperation(
|
||||
'targetIdentity',
|
||||
'urls',
|
||||
'version'
|
||||
].sort().join('\0')
|
||||
]
|
||||
if (
|
||||
Object.keys(value).sort().join('\0') !==
|
||||
expectedKeys.sort().join('\0')
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
const record = value as Record<string, unknown>
|
||||
if (
|
||||
record.version !== 1 ||
|
||||
(version !== 1 && version !== 2) ||
|
||||
record.hostId !== expectedHostId ||
|
||||
typeof record.targetIdentity !== 'string' ||
|
||||
!SHA256_PATTERN.test(record.targetIdentity) ||
|
||||
@@ -129,8 +164,7 @@ function parsePendingOperation(
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
const base: PendingRemoteEnvironmentOperationBase = {
|
||||
hostId: expectedHostId,
|
||||
targetIdentity: record.targetIdentity,
|
||||
operationId: record.operationId,
|
||||
@@ -138,4 +172,100 @@ function parsePendingOperation(
|
||||
sha256: record.sha256,
|
||||
urls: [...record.urls] as string[]
|
||||
}
|
||||
if (version === 1) {
|
||||
return { version: 1, ...base }
|
||||
}
|
||||
return {
|
||||
version: 2,
|
||||
...base,
|
||||
metadataSnapshots: parseMetadataSnapshots(
|
||||
record.metadataSnapshots
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const metadataPaths =
|
||||
new Set<PersistedRemoteEnvironmentMetadataSnapshot['path']>([
|
||||
'.goodbuddy/agent/release-keys.json',
|
||||
'.goodbuddy/agent/registry.json',
|
||||
'.goodbuddy/runtimes/release-keys.json',
|
||||
'.goodbuddy/runtimes/remote-runtime-lock.json',
|
||||
'.goodbuddy/runtimes/registry.json'
|
||||
])
|
||||
|
||||
function parseMetadataSnapshots(
|
||||
value: unknown
|
||||
): readonly PersistedRemoteEnvironmentMetadataSnapshot[] {
|
||||
if (!Array.isArray(value) || value.length !== metadataPaths.size) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
const paths = new Set<string>()
|
||||
let totalBytes = 0
|
||||
const snapshots = value.map((item) => {
|
||||
if (
|
||||
typeof item !== 'object' ||
|
||||
item === null ||
|
||||
!(
|
||||
Object.keys(item).sort().join('\0') ===
|
||||
['path', 'uid'].sort().join('\0') ||
|
||||
Object.keys(item).sort().join('\0') ===
|
||||
['contentsBase64', 'path', 'uid'].sort().join('\0')
|
||||
)
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
const snapshot = item as Record<string, unknown>
|
||||
if (
|
||||
typeof snapshot.path !== 'string' ||
|
||||
!metadataPaths.has(
|
||||
snapshot.path as PersistedRemoteEnvironmentMetadataSnapshot['path']
|
||||
) ||
|
||||
paths.has(snapshot.path) ||
|
||||
!Number.isSafeInteger(snapshot.uid) ||
|
||||
Number(snapshot.uid) < 0
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
paths.add(snapshot.path)
|
||||
if (snapshot.contentsBase64 === undefined) {
|
||||
return {
|
||||
path:
|
||||
snapshot.path as PersistedRemoteEnvironmentMetadataSnapshot['path'],
|
||||
uid: Number(snapshot.uid)
|
||||
}
|
||||
}
|
||||
if (
|
||||
typeof snapshot.contentsBase64 !== 'string' ||
|
||||
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u
|
||||
.test(snapshot.contentsBase64)
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
const contents = Buffer.from(
|
||||
snapshot.contentsBase64,
|
||||
'base64'
|
||||
)
|
||||
if (
|
||||
contents.toString('base64') !==
|
||||
snapshot.contentsBase64 ||
|
||||
contents.byteLength > 1024 * 1024
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
totalBytes += contents.byteLength
|
||||
return {
|
||||
path:
|
||||
snapshot.path as PersistedRemoteEnvironmentMetadataSnapshot['path'],
|
||||
contentsBase64: snapshot.contentsBase64,
|
||||
uid: Number(snapshot.uid)
|
||||
}
|
||||
})
|
||||
if (
|
||||
paths.size !== metadataPaths.size ||
|
||||
[...metadataPaths].some((path) => !paths.has(path)) ||
|
||||
totalBytes > 5 * 1024 * 1024
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
return snapshots
|
||||
}
|
||||
|
||||
@@ -100,6 +100,8 @@ type FixtureOptions = {
|
||||
prepare?: ReturnType<typeof vi.fn>
|
||||
prepareUploaded?: ReturnType<typeof vi.fn>
|
||||
commit?: ReturnType<typeof vi.fn>
|
||||
commitStatus?: ReturnType<typeof vi.fn>
|
||||
cleanup?: ReturnType<typeof vi.fn>
|
||||
uploadFile?: ReturnType<typeof vi.fn>
|
||||
activateAgent?: ReturnType<typeof vi.fn>
|
||||
activateRuntime?: ReturnType<typeof vi.fn>
|
||||
@@ -200,9 +202,22 @@ function fixture(options: FixtureOptions = {}) {
|
||||
close: vi.fn(() => calls.push('close-upload'))
|
||||
}
|
||||
const regularRelease = vi.fn(() => calls.push('release-probe'))
|
||||
const stopCandidate = vi.fn(async () => {
|
||||
const stopCandidate = vi.fn(async (
|
||||
_installationId?: string,
|
||||
_action?: string
|
||||
) => {
|
||||
void _installationId
|
||||
void _action
|
||||
calls.push('stop-candidate')
|
||||
})
|
||||
const activateAgent = options.activateAgent ?? vi.fn(async () => {
|
||||
calls.push('agent')
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
})
|
||||
const activateRuntime = options.activateRuntime ?? vi.fn(async () => {
|
||||
calls.push('runtime')
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
})
|
||||
const regularLease = {
|
||||
identity: leaseIdentity,
|
||||
isUsable: vi.fn(() => true),
|
||||
@@ -226,7 +241,26 @@ function fixture(options: FixtureOptions = {}) {
|
||||
calls.push('open-metadata')
|
||||
return metadata
|
||||
}),
|
||||
runAgentLifecycleAction: stopCandidate,
|
||||
runAgentLifecycleAction: vi.fn(async (
|
||||
installationId: string,
|
||||
action: string
|
||||
) => {
|
||||
if (action === 'stop') {
|
||||
await stopCandidate(installationId, action)
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
}
|
||||
return (activateAgent as (
|
||||
installationId: string,
|
||||
action: string
|
||||
) => Promise<unknown>)(installationId, action)
|
||||
}),
|
||||
runAgentRuntimeAction: vi.fn(async (
|
||||
installationId: string,
|
||||
action: unknown
|
||||
) => (activateRuntime as (
|
||||
installationId: string,
|
||||
action: unknown
|
||||
) => Promise<unknown>)(installationId, action)),
|
||||
release: regularRelease
|
||||
}
|
||||
const prepare = options.prepare ?? vi.fn(async (
|
||||
@@ -264,11 +298,11 @@ function fixture(options: FixtureOptions = {}) {
|
||||
identity: structuredClone(identity)
|
||||
}
|
||||
})
|
||||
const cleanup = vi.fn(async (operationId: string) => {
|
||||
const cleanup = options.cleanup ?? vi.fn(async (operationId: string) => {
|
||||
calls.push('cleanup')
|
||||
return { cleaned: true, operationId }
|
||||
})
|
||||
const commitStatus = vi.fn(async (
|
||||
const commitStatus = options.commitStatus ?? vi.fn(async (
|
||||
input: { operationId: string }
|
||||
) => ({
|
||||
committed: true,
|
||||
@@ -326,13 +360,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
calls.push('acquire-archive')
|
||||
return archive
|
||||
})
|
||||
const activateAgent = options.activateAgent ?? vi.fn(async () => {
|
||||
calls.push('agent')
|
||||
return identity.agent
|
||||
})
|
||||
const activateRuntime = options.activateRuntime ?? vi.fn(async () => {
|
||||
calls.push('runtime')
|
||||
})
|
||||
let pendingOperation = options.pendingOperation
|
||||
const operationStore = {
|
||||
load: vi.fn(async () => pendingOperation),
|
||||
@@ -367,12 +394,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
acquireInstallArchive,
|
||||
acquireGoodBuddyInstallArchive
|
||||
},
|
||||
agentInstallationManager: {
|
||||
activatePublished: activateAgent
|
||||
} as never,
|
||||
runtimeInstallationManager: {
|
||||
activatePublished: activateRuntime
|
||||
} as never,
|
||||
operationStore
|
||||
})
|
||||
return {
|
||||
@@ -425,13 +446,11 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
'save-operation',
|
||||
'prepare',
|
||||
'open-metadata',
|
||||
'save-operation',
|
||||
'resolve',
|
||||
'commit',
|
||||
'resolve',
|
||||
'agent',
|
||||
'resolve',
|
||||
'runtime',
|
||||
'resolve',
|
||||
'cleanup',
|
||||
'remove-operation',
|
||||
'close-metadata',
|
||||
@@ -447,23 +466,24 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(remoteCandidate.operationId).toMatch(/^[0-9a-f-]{36}$/u)
|
||||
expect(value.commit.mock.calls[0]?.[0]).toEqual(remoteCandidate)
|
||||
expect(value.activateAgent).toHaveBeenCalledWith(
|
||||
HOST_ID,
|
||||
identity.agent,
|
||||
expect.objectContaining({ signal: controller.signal })
|
||||
identity.agent.installationId,
|
||||
'adopt'
|
||||
)
|
||||
expect(value.activateRuntime).toHaveBeenCalledWith(
|
||||
HOST_ID,
|
||||
identity.runtime,
|
||||
expect.objectContaining({
|
||||
agentInstallationId: identity.agent.installationId,
|
||||
signal: controller.signal
|
||||
})
|
||||
identity.agent.installationId,
|
||||
{
|
||||
kind: 'runtime-activate',
|
||||
runtimeId: identity.runtime.runtimeId,
|
||||
bundleDigest: identity.runtime.bundleDigest,
|
||||
architecture: identity.runtime.architecture,
|
||||
forceVerification: true
|
||||
}
|
||||
)
|
||||
expect(value.cleanup).toHaveBeenCalledWith(
|
||||
remoteCandidate.operationId,
|
||||
{ signal: controller.signal }
|
||||
)
|
||||
expect(value.operationStore.save).toHaveBeenCalledOnce()
|
||||
expect(value.operationStore.save).toHaveBeenCalledTimes(2)
|
||||
expect(value.operationStore.remove).toHaveBeenCalledOnce()
|
||||
expect(progress.some((event) =>
|
||||
event.method === 'remote-download' &&
|
||||
@@ -495,6 +515,27 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(value.archiveRelease).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps an adopted environment healthy when staging cleanup must be retried', async () => {
|
||||
const value = fixture({
|
||||
cleanup: vi.fn(async (operationId: string) => ({
|
||||
cleaned: false,
|
||||
operationId,
|
||||
reason: 'cleanup-failed'
|
||||
}))
|
||||
})
|
||||
|
||||
await expect(value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)).resolves.toBeUndefined()
|
||||
expect(value.activateAgent).toHaveBeenCalledOnce()
|
||||
expect(value.activateRuntime).toHaveBeenCalledOnce()
|
||||
expect(value.stopCandidate).not.toHaveBeenCalled()
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('releases the archive and cleans the operation when a GoodBuddy upload fails', async () => {
|
||||
const uploadFailure = new Error('upload failed')
|
||||
const value = fixture({
|
||||
@@ -684,12 +725,39 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
new AbortController().signal
|
||||
)).rejects.toBeInstanceOf(SshRemotePackageCommitIndeterminateError)
|
||||
expect(value.cleanup).not.toHaveBeenCalled()
|
||||
expect(value.operationStore.save).toHaveBeenCalledOnce()
|
||||
expect(value.operationStore.save).toHaveBeenCalledTimes(2)
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
expect(value.activateAgent).not.toHaveBeenCalled()
|
||||
expect(value.activateRuntime).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rolls metadata back when cancellation arrives with a successful commit result', async () => {
|
||||
const controller = new AbortController()
|
||||
const cancellation =
|
||||
new DOMException('cancelled after commit', 'AbortError')
|
||||
const value = fixture({
|
||||
commit: vi.fn(async (input: { operationId: string }) => {
|
||||
controller.abort(cancellation)
|
||||
return {
|
||||
committed: true,
|
||||
operationId: input.operationId,
|
||||
identity
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
await expect(value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
controller.signal
|
||||
)).rejects.toBe(cancellation)
|
||||
expect(value.stopCandidate).toHaveBeenCalledOnce()
|
||||
expect(value.cleanup).toHaveBeenCalledOnce()
|
||||
expect(value.operationStore.remove).toHaveBeenCalledOnce()
|
||||
expect(value.activateAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps rollback-incomplete commits recoverable without cleanup', async () => {
|
||||
const value = fixture({
|
||||
commit: vi.fn(async () => ({
|
||||
@@ -710,7 +778,7 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reconciles and cleans a pending commit before starting new work', async () => {
|
||||
it('resumes adoption for a committed operation instead of reinstalling it', async () => {
|
||||
const pendingOperationId =
|
||||
'00000000-0000-4000-8000-000000000777'
|
||||
const originalTarget = target()
|
||||
@@ -724,14 +792,21 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
const value = fixture({
|
||||
targets: [renamedTarget],
|
||||
pendingOperation: {
|
||||
version: 1,
|
||||
version: 2,
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId: pendingOperationId,
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls
|
||||
urls: candidate.urls,
|
||||
metadataSnapshots:
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map(
|
||||
(path) => ({
|
||||
path,
|
||||
uid: 1000
|
||||
})
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -751,10 +826,158 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(value.cleanup.mock.calls[0]?.[0]).toBe(
|
||||
pendingOperationId
|
||||
)
|
||||
expect(value.activateAgent).toHaveBeenCalledOnce()
|
||||
expect(value.activateRuntime).toHaveBeenCalledOnce()
|
||||
expect(value.prepare).not.toHaveBeenCalled()
|
||||
expect(value.operationStore.remove).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('cleans a legacy pending operation and starts a fresh authenticated prepare', async () => {
|
||||
const originalTarget = target()
|
||||
const pendingOperationId =
|
||||
'00000000-0000-4000-8000-000000000780'
|
||||
const value = fixture({
|
||||
targets: [originalTarget],
|
||||
pendingOperation: {
|
||||
version: 1,
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId: pendingOperationId,
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls
|
||||
}
|
||||
})
|
||||
|
||||
await value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)
|
||||
|
||||
expect(value.commitStatus).not.toHaveBeenCalled()
|
||||
expect(value.cleanup.mock.calls[0]?.[0]).toBe(
|
||||
pendingOperationId
|
||||
)
|
||||
expect(value.prepare).toHaveBeenCalledOnce()
|
||||
expect(value.operationStore.remove).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('restores the durable snapshot when resumed commit does not complete', async () => {
|
||||
const originalTarget = target()
|
||||
const originals = new Map<string, Buffer>(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map(
|
||||
(path, index) => [
|
||||
path,
|
||||
Buffer.from(`before-commit-${index}`)
|
||||
]
|
||||
)
|
||||
)
|
||||
const files = new Map<string, Buffer>(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map(
|
||||
(path) => [path, Buffer.from('partial-commit')]
|
||||
)
|
||||
)
|
||||
const value = fixture({
|
||||
targets: [originalTarget],
|
||||
metadataFiles: files,
|
||||
pendingOperation: {
|
||||
version: 2,
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId:
|
||||
'00000000-0000-4000-8000-000000000781',
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls,
|
||||
metadataSnapshots: [...originals].map(
|
||||
([path, contents]) => ({
|
||||
path: path as never,
|
||||
uid: 1000,
|
||||
contentsBase64: contents.toString('base64')
|
||||
})
|
||||
)
|
||||
},
|
||||
commitStatus: vi.fn(async () => ({
|
||||
committed: false,
|
||||
reason: 'installer-failed'
|
||||
}))
|
||||
})
|
||||
|
||||
await value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)
|
||||
|
||||
expect([...files]).toEqual([...originals])
|
||||
expect(value.prepare).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('restores persisted pre-commit metadata when resumed Runtime adoption fails', async () => {
|
||||
const originalTarget = target()
|
||||
const originals = new Map<string, Buffer>(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map(
|
||||
(path, index) => [
|
||||
path,
|
||||
Buffer.from(`original-${index}`)
|
||||
]
|
||||
)
|
||||
)
|
||||
const files = new Map<string, Buffer>(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map(
|
||||
(path) => [path, Buffer.from('published')]
|
||||
)
|
||||
)
|
||||
const runtimeFailure = new Error('runtime recovery failed')
|
||||
const value = fixture({
|
||||
targets: [originalTarget],
|
||||
metadataFiles: files,
|
||||
pendingOperation: {
|
||||
version: 2,
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId:
|
||||
'00000000-0000-4000-8000-000000000779',
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls,
|
||||
metadataSnapshots: [...originals].map(
|
||||
([path, contents]) => ({
|
||||
path: path as never,
|
||||
uid: 1000,
|
||||
contentsBase64: contents.toString('base64')
|
||||
})
|
||||
)
|
||||
},
|
||||
activateAgent: vi.fn(async () => {
|
||||
for (const path of REMOTE_ENVIRONMENT_METADATA_PATHS) {
|
||||
files.set(path, Buffer.from('adopting'))
|
||||
}
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
}),
|
||||
activateRuntime: vi.fn(async () => {
|
||||
throw runtimeFailure
|
||||
})
|
||||
})
|
||||
|
||||
await expect(value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)).rejects.toThrow('runtime recovery failed')
|
||||
expect([...files]).toEqual([...originals])
|
||||
expect(value.stopCandidate).toHaveBeenCalledOnce()
|
||||
expect(value.cleanup).not.toHaveBeenCalled()
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('retains pending recovery evidence when the real SSH target changes', async () => {
|
||||
const originalTarget = target()
|
||||
const changedTarget = target({
|
||||
@@ -802,12 +1025,12 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
const value = fixture({
|
||||
metadataFiles: files,
|
||||
activateAgent: vi.fn(async () => {
|
||||
value.calls.push('agent')
|
||||
value.metadataFiles.clear()
|
||||
for (const path of REMOTE_ENVIRONMENT_METADATA_PATHS) {
|
||||
value.metadataFiles.set(path, Buffer.from('new'))
|
||||
}
|
||||
return identity.agent
|
||||
value.calls.push('agent')
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
}),
|
||||
activateRuntime: vi.fn(async () => {
|
||||
throw runtimeFailure
|
||||
@@ -838,7 +1061,7 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
metadataReplaceFailure: rollbackFailure,
|
||||
activateAgent: vi.fn(async () => {
|
||||
files.set(path, Buffer.from('changed'))
|
||||
return identity.agent
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
}),
|
||||
activateRuntime: vi.fn(async () => {
|
||||
throw runtimeFailure
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
import type { StagedSftp } from '../ssh/bounded-sftp'
|
||||
import { verifyAgentInstallationId } from '../ssh/ssh-agent-command'
|
||||
import type {
|
||||
AgentDiagnosticResult,
|
||||
SshConnectionLease,
|
||||
SshConnectionPool,
|
||||
SshRemotePackageBootstrapLease
|
||||
@@ -25,7 +26,6 @@ import {
|
||||
type SshRemotePackageIdentity
|
||||
} from '../ssh/ssh-remote-package-bootstrap'
|
||||
import type {
|
||||
AgentInstallationManager,
|
||||
AgentInstallationTargetResolver
|
||||
} from './agent-installation-manager'
|
||||
import type {
|
||||
@@ -38,26 +38,41 @@ import {
|
||||
snapshotRemoteEnvironmentMetadata,
|
||||
type RemoteEnvironmentMetadataSnapshot
|
||||
} from './remote-environment-metadata'
|
||||
import {
|
||||
mapAgentInstallationPhase,
|
||||
mapRuntimeInstallationPhase
|
||||
} from './remote-environment-progress'
|
||||
import type {
|
||||
PersistedRemoteEnvironmentMetadataSnapshot,
|
||||
RemoteEnvironmentOperationStore
|
||||
} from './remote-environment-operation-store'
|
||||
import type {
|
||||
RemoteEnvironmentPreparer as Preparer,
|
||||
RemoteEnvironmentUpdateProgressObserver
|
||||
} from './remote-environment-update-service'
|
||||
import type {
|
||||
RemoteRuntimeInstallationManager
|
||||
} from './remote-runtime-installation-manager'
|
||||
import {
|
||||
remoteHostRecoveryIdentityKey
|
||||
} from './remote-host-target-identity'
|
||||
import { boundedDiagnostic } from './bounded-diagnostic'
|
||||
|
||||
const MAXIMUM_PACKAGE_BYTES = 512 * 1024 * 1024
|
||||
const MAXIMUM_METADATA_BYTES = 1024 * 1024
|
||||
const MAXIMUM_DIAGNOSTIC_CHARACTERS = 800
|
||||
|
||||
function assertAgentCommandSucceeded(
|
||||
result: AgentDiagnosticResult,
|
||||
label: string
|
||||
): void {
|
||||
if (result.exitCode === 0) {
|
||||
return
|
||||
}
|
||||
const detail = `${result.stderr}\n${result.stdout}`
|
||||
const bounded = boundedDiagnostic(
|
||||
detail,
|
||||
MAXIMUM_DIAGNOSTIC_CHARACTERS
|
||||
)
|
||||
throw new Error(
|
||||
bounded.length > 0
|
||||
? `${label}失败:${bounded}`
|
||||
: `${label}失败,退出码 ${String(result.exitCode)}`
|
||||
)
|
||||
}
|
||||
|
||||
export type RemoteEnvironmentPreparerOptions = {
|
||||
resolver: AgentInstallationTargetResolver
|
||||
@@ -71,14 +86,6 @@ export type RemoteEnvironmentPreparerOptions = {
|
||||
| 'acquireInstallArchive'
|
||||
| 'acquireGoodBuddyInstallArchive'
|
||||
>
|
||||
agentInstallationManager: Pick<
|
||||
AgentInstallationManager,
|
||||
'activatePublished'
|
||||
>
|
||||
runtimeInstallationManager: Pick<
|
||||
RemoteRuntimeInstallationManager,
|
||||
'activatePublished'
|
||||
>
|
||||
operationStore: Pick<
|
||||
RemoteEnvironmentOperationStore,
|
||||
'load' | 'save' | 'remove'
|
||||
@@ -95,10 +102,6 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
readonly #sshPool: RemoteEnvironmentPreparerOptions['sshPool']
|
||||
readonly #agentPackageManager:
|
||||
RemoteEnvironmentPreparerOptions['agentPackageManager']
|
||||
readonly #agentInstallationManager:
|
||||
RemoteEnvironmentPreparerOptions['agentInstallationManager']
|
||||
readonly #runtimeInstallationManager:
|
||||
RemoteEnvironmentPreparerOptions['runtimeInstallationManager']
|
||||
readonly #operationStore:
|
||||
RemoteEnvironmentPreparerOptions['operationStore']
|
||||
|
||||
@@ -106,10 +109,6 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
this.#resolver = options.resolver
|
||||
this.#sshPool = options.sshPool
|
||||
this.#agentPackageManager = options.agentPackageManager
|
||||
this.#agentInstallationManager =
|
||||
options.agentInstallationManager
|
||||
this.#runtimeInstallationManager =
|
||||
options.runtimeInstallationManager
|
||||
this.#operationStore = options.operationStore
|
||||
}
|
||||
|
||||
@@ -135,12 +134,15 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
const target = await this.#resolver.resolve(hostId)
|
||||
signal.throwIfAborted()
|
||||
assertValidSshConnectionTarget(hostId, target)
|
||||
await this.#reconcilePendingOperation(
|
||||
const recovered = await this.#reconcilePendingOperation(
|
||||
hostId,
|
||||
target,
|
||||
emit,
|
||||
signal
|
||||
)
|
||||
if (recovered) {
|
||||
return
|
||||
}
|
||||
|
||||
let probeLease: SshConnectionLease | undefined
|
||||
let bootstrapLease:
|
||||
@@ -304,6 +306,17 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
probe.uid,
|
||||
signal
|
||||
)
|
||||
await this.#operationStore.save({
|
||||
version: 2,
|
||||
hostId,
|
||||
targetIdentity: remoteHostRecoveryIdentityKey(target),
|
||||
operationId,
|
||||
size: remoteCandidate.size,
|
||||
sha256: remoteCandidate.sha256,
|
||||
urls: [...remoteCandidate.urls],
|
||||
metadataSnapshots:
|
||||
persistMetadataSnapshots(metadataSnapshots)
|
||||
})
|
||||
|
||||
// Keep the full target re-resolution immediately adjacent to commit.
|
||||
await assertTargetCurrent(this.#resolver, target, signal)
|
||||
@@ -319,7 +332,6 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
}
|
||||
}
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
if (!committed.committed) {
|
||||
if (
|
||||
committed.reason ===
|
||||
@@ -330,7 +342,7 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
)
|
||||
}
|
||||
throw new Error(
|
||||
`远端安装提交失败:${committed.reason}`
|
||||
`远端安装提交失败:${committed.detail ?? committed.reason}`
|
||||
)
|
||||
}
|
||||
if (
|
||||
@@ -344,52 +356,34 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
}
|
||||
assertPackageIdentity(committed.identity, candidate)
|
||||
committedIdentity = committed.identity
|
||||
|
||||
await assertTargetCurrent(this.#resolver, target, signal)
|
||||
const activeAgent =
|
||||
await this.#agentInstallationManager.activatePublished(
|
||||
hostId,
|
||||
committed.identity.agent,
|
||||
{
|
||||
signal,
|
||||
onProgress: (phase) => {
|
||||
const mapped = mapAgentInstallationPhase(phase)
|
||||
if (mapped) {
|
||||
emit(method, mapped)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
await assertTargetCurrent(this.#resolver, target, signal)
|
||||
|
||||
await this.#runtimeInstallationManager.activatePublished(
|
||||
hostId,
|
||||
committed.identity.runtime,
|
||||
{
|
||||
agentInstallationId: activeAgent.installationId,
|
||||
signal,
|
||||
onProgress: (phase) => {
|
||||
const mapped = mapRuntimeInstallationPhase(phase)
|
||||
if (mapped) {
|
||||
emit(method, mapped)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
await assertTargetCurrent(this.#resolver, target, signal)
|
||||
|
||||
const cleanup = await bootstrapLease.cleanup(operationId, {
|
||||
await this.#adoptCommittedEnvironment(
|
||||
probeLease,
|
||||
committed.identity,
|
||||
method,
|
||||
emit,
|
||||
signal
|
||||
})
|
||||
if (!cleanup.cleaned) {
|
||||
throw new Error(
|
||||
`远程环境已安装,但暂存文件清理失败:${cleanup.reason}`
|
||||
)
|
||||
|
||||
emit(method, 'finalizing')
|
||||
try {
|
||||
const cleanup = await bootstrapLease.cleanup(
|
||||
operationId,
|
||||
{ signal }
|
||||
)
|
||||
if (cleanup.cleaned) {
|
||||
operationCleaned = true
|
||||
try {
|
||||
await this.#operationStore.remove(hostId)
|
||||
} catch {
|
||||
// A stale local receipt is harmless after remote cleanup.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// The environment is already healthy. Leave the bounded
|
||||
// operation for a later maintenance retry.
|
||||
}
|
||||
operationCleaned = true
|
||||
await this.#operationStore.remove(hostId)
|
||||
} catch (error) {
|
||||
let rollbackError: unknown
|
||||
if (
|
||||
@@ -440,6 +434,48 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
}
|
||||
}
|
||||
|
||||
async #adoptCommittedEnvironment(
|
||||
lease: SshConnectionLease,
|
||||
identity: SshRemotePackageIdentity,
|
||||
method: RemoteEnvironmentPreparationMethod,
|
||||
emit: (
|
||||
method: RemoteEnvironmentPreparationMethod,
|
||||
phase: RemoteEnvironmentUpdateProgress['phase']
|
||||
) => void,
|
||||
signal: AbortSignal
|
||||
): Promise<void> {
|
||||
const installationId = verifyAgentInstallationId(
|
||||
identity.agent.installationId
|
||||
)
|
||||
emit(method, 'installing-agent')
|
||||
assertAgentCommandSucceeded(
|
||||
await lease.runAgentLifecycleAction(
|
||||
installationId,
|
||||
'adopt',
|
||||
signal
|
||||
),
|
||||
'GoodBuddy Agent 启动与健康检查'
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
|
||||
emit(method, 'installing-runtime')
|
||||
assertAgentCommandSucceeded(
|
||||
await lease.runAgentRuntimeAction(
|
||||
installationId,
|
||||
{
|
||||
kind: 'runtime-activate',
|
||||
runtimeId: identity.runtime.runtimeId,
|
||||
bundleDigest: identity.runtime.bundleDigest,
|
||||
architecture: identity.runtime.architecture,
|
||||
forceVerification: true
|
||||
},
|
||||
signal
|
||||
),
|
||||
'OpenCode Runtime 激活'
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
}
|
||||
|
||||
async #prepareUploadedArchive(options: {
|
||||
probeLease: SshConnectionLease
|
||||
bootstrapLease: SshRemotePackageBootstrapLease
|
||||
@@ -567,10 +603,10 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
phase: RemoteEnvironmentUpdateProgress['phase']
|
||||
) => void,
|
||||
signal: AbortSignal
|
||||
): Promise<void> {
|
||||
): Promise<boolean> {
|
||||
const pending = await this.#operationStore.load(hostId)
|
||||
if (!pending) {
|
||||
return
|
||||
return false
|
||||
}
|
||||
if (
|
||||
pending.targetIdentity !==
|
||||
@@ -587,16 +623,42 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
sha256: pending.sha256,
|
||||
urls: pending.urls
|
||||
}
|
||||
const lease =
|
||||
const bootstrapLease =
|
||||
await this.#sshPool.acquireRemotePackageBootstrap(
|
||||
target,
|
||||
signal
|
||||
)
|
||||
let commandLease: SshConnectionLease | undefined
|
||||
let recoveryMetadataSftp: StagedSftp | undefined
|
||||
try {
|
||||
assertLeaseMatchesTarget(lease, target)
|
||||
const status = await lease.commitStatus(candidate, {
|
||||
signal
|
||||
})
|
||||
assertLeaseMatchesTarget(bootstrapLease, target)
|
||||
if (pending.version === 1) {
|
||||
const cleanup = await bootstrapLease.cleanup(
|
||||
pending.operationId,
|
||||
{ signal }
|
||||
)
|
||||
if (
|
||||
!cleanup.cleaned &&
|
||||
cleanup.reason !== 'operation-unavailable'
|
||||
) {
|
||||
throw new Error(
|
||||
`旧版远程环境暂存清理失败:${cleanup.reason}`
|
||||
)
|
||||
}
|
||||
await this.#operationStore.remove(hostId)
|
||||
return false
|
||||
}
|
||||
const status = await bootstrapLease.commitStatus(
|
||||
candidate,
|
||||
{ signal }
|
||||
)
|
||||
if (
|
||||
!status.committed &&
|
||||
status.reason === 'operation-unavailable'
|
||||
) {
|
||||
await this.#operationStore.remove(hostId)
|
||||
return false
|
||||
}
|
||||
if (
|
||||
!status.committed &&
|
||||
status.reason === 'installer-rollback-incomplete'
|
||||
@@ -605,19 +667,83 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
'上一次远程环境发布失败且回滚结果不完整,请检查 Host 状态'
|
||||
)
|
||||
}
|
||||
const cleanup = await lease.cleanup(
|
||||
commandLease = await this.#sshPool.acquire(
|
||||
target,
|
||||
signal
|
||||
)
|
||||
assertLeaseMatchesTarget(commandLease, target)
|
||||
const probe =
|
||||
await commandLease.runAgentBootstrapProbe(signal)
|
||||
if (!probe.ready) {
|
||||
throw new Error(
|
||||
`远端系统不能恢复 GoodBuddy 环境:${probe.reason}`
|
||||
)
|
||||
}
|
||||
recoveryMetadataSftp =
|
||||
await commandLease.openStagedSftp(
|
||||
probe.canonicalHomeDirectory,
|
||||
{
|
||||
maximumFileBytes: MAXIMUM_METADATA_BYTES,
|
||||
maximumTotalBytes:
|
||||
MAXIMUM_METADATA_BYTES * 24,
|
||||
maximumOperations: 128
|
||||
},
|
||||
signal
|
||||
)
|
||||
const recoverySnapshots =
|
||||
restorePersistedMetadataSnapshots(
|
||||
pending.metadataSnapshots,
|
||||
probe.uid
|
||||
)
|
||||
if (status.committed) {
|
||||
try {
|
||||
await this.#adoptCommittedEnvironment(
|
||||
commandLease,
|
||||
status.identity,
|
||||
'auto',
|
||||
emit,
|
||||
signal
|
||||
)
|
||||
} catch (error) {
|
||||
await stopCandidateBestEffort(
|
||||
commandLease,
|
||||
status.identity.agent.installationId
|
||||
)
|
||||
try {
|
||||
await restoreRemoteEnvironmentMetadata(
|
||||
recoveryMetadataSftp,
|
||||
recoverySnapshots
|
||||
)
|
||||
} catch (rollbackError) {
|
||||
throw new AggregateError(
|
||||
[error, rollbackError],
|
||||
'上一次远程环境恢复失败,且原有环境元数据未能完整恢复',
|
||||
{ cause: rollbackError }
|
||||
)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
} else {
|
||||
await restoreRemoteEnvironmentMetadata(
|
||||
recoveryMetadataSftp,
|
||||
recoverySnapshots
|
||||
)
|
||||
}
|
||||
const cleanup = await bootstrapLease.cleanup(
|
||||
pending.operationId,
|
||||
{ signal }
|
||||
)
|
||||
if (
|
||||
!cleanup.cleaned &&
|
||||
cleanup.reason !== 'operation-unavailable'
|
||||
cleanup.cleaned ||
|
||||
cleanup.reason === 'operation-unavailable'
|
||||
) {
|
||||
await this.#operationStore.remove(hostId)
|
||||
} else if (!status.committed) {
|
||||
throw new Error(
|
||||
`上一次远程环境暂存清理失败:${cleanup.reason}`
|
||||
`上一次未提交的远程环境暂存清理失败:${cleanup.reason}`
|
||||
)
|
||||
}
|
||||
await this.#operationStore.remove(hostId)
|
||||
return status.committed
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof
|
||||
@@ -625,15 +751,59 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
) {
|
||||
throw error
|
||||
}
|
||||
const detail = error instanceof Error
|
||||
? error.message
|
||||
: String(error)
|
||||
throw new SshRemotePackageCommitIndeterminateError(
|
||||
'上一次远程环境提交结果仍不确定,请稍后重试'
|
||||
`上一次远程环境恢复失败:${detail}`
|
||||
)
|
||||
} finally {
|
||||
lease.release()
|
||||
recoveryMetadataSftp?.close()
|
||||
commandLease?.release()
|
||||
bootstrapLease.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function persistMetadataSnapshots(
|
||||
snapshots: readonly RemoteEnvironmentMetadataSnapshot[]
|
||||
): readonly PersistedRemoteEnvironmentMetadataSnapshot[] {
|
||||
return snapshots.map((snapshot) => ({
|
||||
path: snapshot.path,
|
||||
uid: snapshot.uid,
|
||||
...(snapshot.contents === undefined
|
||||
? {}
|
||||
: {
|
||||
contentsBase64:
|
||||
snapshot.contents.toString('base64')
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
function restorePersistedMetadataSnapshots(
|
||||
snapshots:
|
||||
readonly PersistedRemoteEnvironmentMetadataSnapshot[],
|
||||
uid: number
|
||||
): readonly RemoteEnvironmentMetadataSnapshot[] {
|
||||
if (snapshots.some((snapshot) => snapshot.uid !== uid)) {
|
||||
throw new Error(
|
||||
'远程环境恢复元数据与当前 SSH 用户不匹配'
|
||||
)
|
||||
}
|
||||
return snapshots.map((snapshot) => ({
|
||||
path: snapshot.path,
|
||||
uid: snapshot.uid,
|
||||
...(snapshot.contentsBase64 === undefined
|
||||
? {}
|
||||
: {
|
||||
contents: Buffer.from(
|
||||
snapshot.contentsBase64,
|
||||
'base64'
|
||||
)
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
async function resolvePreparationMethod(
|
||||
requested: RemoteEnvironmentPreparationMethod,
|
||||
lease: SshRemotePackageBootstrapLease,
|
||||
@@ -660,7 +830,7 @@ function assertPrepared(
|
||||
throw new Error(
|
||||
prepared.unavailable
|
||||
? `远端环境准备不可用:${prepared.reason}`
|
||||
: `远端环境准备失败:${prepared.reason}`
|
||||
: `远端环境准备失败:${prepared.detail ?? prepared.reason}`
|
||||
)
|
||||
}
|
||||
if (prepared.operationId !== operationId) {
|
||||
@@ -809,7 +979,6 @@ function mapBootstrapPhase(
|
||||
case 'verifying-zip':
|
||||
case 'verifying-payload':
|
||||
case 'validating-prepared-state':
|
||||
case 'revalidating-archive':
|
||||
return 'verifying'
|
||||
case 'extracting':
|
||||
case 'preparing':
|
||||
@@ -819,6 +988,7 @@ function mapBootstrapPhase(
|
||||
case 'persisting-prepared-state':
|
||||
case 'extracting-payload':
|
||||
case 'publishing-content':
|
||||
case 'publishing-metadata':
|
||||
case 'cleaning':
|
||||
return 'applying'
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import type { RemoteEnvironmentUpdateProgress } from '../../shared/ssh-host-contracts'
|
||||
import type { AgentInstallationPhase } from './agent-installation-manager'
|
||||
import type { RemoteRuntimeInstallationPhase } from './remote-runtime-installation-manager'
|
||||
|
||||
export function mapAgentInstallationPhase(
|
||||
phase: AgentInstallationPhase
|
||||
): RemoteEnvironmentUpdateProgress['phase'] | undefined {
|
||||
switch (phase) {
|
||||
case 'inspecting-host':
|
||||
return 'probing'
|
||||
case 'verifying-bundle':
|
||||
return 'verifying'
|
||||
case 'starting-agent':
|
||||
return 'installing-agent'
|
||||
case 'checking-health':
|
||||
return 'checking-health'
|
||||
case 'complete':
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function mapRuntimeInstallationPhase(
|
||||
phase: RemoteRuntimeInstallationPhase
|
||||
): RemoteEnvironmentUpdateProgress['phase'] | undefined {
|
||||
switch (phase) {
|
||||
case 'inspecting-host':
|
||||
return 'probing'
|
||||
case 'verifying-bundle':
|
||||
return 'verifying'
|
||||
case 'activating-runtime':
|
||||
return 'installing-runtime'
|
||||
case 'complete':
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -24,6 +24,7 @@ export const AGENT_BOOTSTRAP_PROBE_COMMAND = [
|
||||
].join('; ')
|
||||
|
||||
const lifecycleActions = [
|
||||
'adopt',
|
||||
'bootstrap',
|
||||
'health',
|
||||
'status',
|
||||
@@ -48,6 +49,7 @@ export type AgentRuntimeActivationAction = {
|
||||
runtimeId: typeof RUNTIME_ID
|
||||
bundleDigest: string
|
||||
architecture: AgentRuntimeArchitecture
|
||||
forceVerification?: true
|
||||
}
|
||||
|
||||
export type FixedAgentSshAction =
|
||||
@@ -232,7 +234,10 @@ export function buildFixedAgentCliArgv(
|
||||
'--bundle-digest',
|
||||
action.bundleDigest,
|
||||
'--architecture',
|
||||
action.architecture
|
||||
action.architecture,
|
||||
...(action.forceVerification === true
|
||||
? ['--force-verification', 'true']
|
||||
: [])
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -508,10 +508,13 @@ describe("fixed SSH remote package bootstrap", () => {
|
||||
SSH_REMOTE_PACKAGE_BOOTSTRAP_SCRIPT.match(
|
||||
/\[ "\$installer_output_size" -gt 0 \]/gu,
|
||||
),
|
||||
).toHaveLength(4);
|
||||
).toHaveLength(3);
|
||||
expect(SSH_REMOTE_PACKAGE_BOOTSTRAP_SCRIPT).toContain(
|
||||
'[ "$installer_output_size" -le 49152 ]',
|
||||
);
|
||||
expect(SSH_REMOTE_PACKAGE_BOOTSTRAP_SCRIPT).toContain(
|
||||
'action=commit',
|
||||
);
|
||||
});
|
||||
|
||||
it("parses bounded split NDJSON progress and a prepared result", async () => {
|
||||
@@ -677,6 +680,7 @@ describe("fixed SSH remote package bootstrap", () => {
|
||||
prepared: false,
|
||||
unavailable: false,
|
||||
reason: "installer-failed",
|
||||
detail: "archive verification failed",
|
||||
});
|
||||
|
||||
const rollbackFailure = createChannel((_payload, active) => {
|
||||
@@ -692,6 +696,7 @@ describe("fixed SSH remote package bootstrap", () => {
|
||||
).resolves.toEqual({
|
||||
committed: false,
|
||||
reason: "installer-rollback-incomplete",
|
||||
detail: "managed destination restore failed",
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -46,9 +46,9 @@ const progressPhases = [
|
||||
"verifying-payload",
|
||||
"persisting-prepared-state",
|
||||
"validating-prepared-state",
|
||||
"revalidating-archive",
|
||||
"extracting-payload",
|
||||
"publishing-content",
|
||||
"publishing-metadata",
|
||||
] as const;
|
||||
|
||||
const unavailableReasons = [
|
||||
@@ -166,6 +166,7 @@ export type SshRemotePackageBootstrapPrepareResult =
|
||||
prepared: false;
|
||||
unavailable: false;
|
||||
reason: SshRemotePackageBootstrapFailureReason;
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
export type SshRemotePackageUploadStagingResult =
|
||||
@@ -195,6 +196,7 @@ export type SshRemotePackageBootstrapCommitResult =
|
||||
| {
|
||||
committed: false;
|
||||
reason: SshRemotePackageBootstrapFailureReason;
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
export type SshRemotePackageBootstrapCleanupResult =
|
||||
@@ -268,6 +270,7 @@ type TerminalMessage =
|
||||
type: "result";
|
||||
status: "failed";
|
||||
reason: SshRemotePackageBootstrapFailureReason;
|
||||
detail?: string;
|
||||
}
|
||||
| {
|
||||
type: "result";
|
||||
@@ -467,23 +470,29 @@ if [ "$action" = prepare-status ]; then
|
||||
fi
|
||||
if [ "$action" = commit-status ]; then
|
||||
installer_output="$operation_root/installer-commit.ndjson"
|
||||
if [ ! -d "$operation_root" ] || [ -L "$operation_root" ] ||
|
||||
[ ! -f "$installer_output" ] || [ -L "$installer_output" ]; then
|
||||
stop failed operation-unavailable
|
||||
if [ -d "$operation_root" ] && [ ! -L "$operation_root" ] &&
|
||||
[ -f "$installer_output" ] && [ ! -L "$installer_output" ]; then
|
||||
installer_output_size=$(wc -c < "$installer_output" 2>/dev/null) ||
|
||||
stop failed operation-unavailable
|
||||
set -- $installer_output_size
|
||||
installer_output_size=${SHELL_FIRST_POSITIONAL_OR_EMPTY}
|
||||
case "$installer_output_size" in
|
||||
""|*[!0-9]*) stop failed operation-unavailable ;;
|
||||
esac
|
||||
[ "$installer_output_size" -le 49152 ] ||
|
||||
stop failed operation-unavailable
|
||||
terminal_line=$(tail -n 1 "$installer_output" 2>/dev/null) ||
|
||||
stop failed operation-unavailable
|
||||
if printf %s "$terminal_line" | grep '"type":"result"' >/dev/null 2>&1 ||
|
||||
printf %s "$terminal_line" | grep '"type":"error"' >/dev/null 2>&1; then
|
||||
cat -- "$installer_output" || stop failed operation-unavailable
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
installer_output_size=$(wc -c < "$installer_output" 2>/dev/null) ||
|
||||
stop failed operation-unavailable
|
||||
set -- $installer_output_size
|
||||
installer_output_size=${SHELL_FIRST_POSITIONAL_OR_EMPTY}
|
||||
case "$installer_output_size" in
|
||||
""|*[!0-9]*) stop failed operation-unavailable ;;
|
||||
esac
|
||||
[ "$installer_output_size" -gt 0 ] ||
|
||||
stop failed operation-unavailable
|
||||
[ "$installer_output_size" -le 49152 ] ||
|
||||
stop failed operation-unavailable
|
||||
cat -- "$installer_output" || stop failed operation-unavailable
|
||||
exit 0
|
||||
# A process or channel loss may leave a partial publication without a
|
||||
# terminal line. The installer commit is idempotent and completes it from
|
||||
# the authenticated prepared state.
|
||||
action=commit
|
||||
fi
|
||||
if [ "$action" = commit ]; then
|
||||
if [ ! -d "$operation_root" ] || [ -L "$operation_root" ] ||
|
||||
@@ -1109,6 +1118,7 @@ function parseMessage(
|
||||
message.status === "rollback-incomplete"
|
||||
? "installer-rollback-incomplete"
|
||||
: "installer-failed",
|
||||
detail: message.message,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1444,6 +1454,9 @@ export function createSshRemotePackageBootstrapExecutor(
|
||||
prepared: false,
|
||||
unavailable: false,
|
||||
reason: result.reason,
|
||||
...(result.detail === undefined
|
||||
? {}
|
||||
: { detail: result.detail }),
|
||||
};
|
||||
}
|
||||
throw new Error("Agent 远程安装准备返回了无效结果");
|
||||
@@ -1473,7 +1486,13 @@ export function createSshRemotePackageBootstrapExecutor(
|
||||
};
|
||||
}
|
||||
if (result.status === "failed") {
|
||||
return { committed: false, reason: result.reason };
|
||||
return {
|
||||
committed: false,
|
||||
reason: result.reason,
|
||||
...(result.detail === undefined
|
||||
? {}
|
||||
: { detail: result.detail }),
|
||||
};
|
||||
}
|
||||
throw new Error("Agent 远程安装提交状态返回了无效结果");
|
||||
};
|
||||
@@ -1582,7 +1601,13 @@ export function createSshRemotePackageBootstrapExecutor(
|
||||
};
|
||||
}
|
||||
if (result.status === "failed") {
|
||||
return { committed: false, reason: result.reason };
|
||||
return {
|
||||
committed: false,
|
||||
reason: result.reason,
|
||||
...(result.detail === undefined
|
||||
? {}
|
||||
: { detail: result.detail }),
|
||||
};
|
||||
}
|
||||
throw new Error("Agent 远程安装提交返回了无效结果");
|
||||
},
|
||||
|
||||
@@ -33,6 +33,10 @@ import {
|
||||
type RemoteRuntimeBundleManifest,
|
||||
type RemoteRuntimeLock
|
||||
} from '../remote-runtime-launch-contracts'
|
||||
import {
|
||||
runtimeRegistryEntrySchema,
|
||||
type RuntimeRegistryEntry
|
||||
} from '../remote-environment-registry-contracts'
|
||||
|
||||
export type InstalledBundleVerificationEnvironment =
|
||||
| 'production'
|
||||
@@ -63,6 +67,11 @@ export type VerifyRuntimeBundleOptions = {
|
||||
uid?: number
|
||||
}
|
||||
|
||||
export type LoadRegisteredRuntimeBundleOptions =
|
||||
VerifyRuntimeBundleOptions & {
|
||||
registered: RuntimeRegistryEntry
|
||||
}
|
||||
|
||||
export async function verifyRuntimeBundle(
|
||||
bundleDirectoryInput: string,
|
||||
options: VerifyRuntimeBundleOptions
|
||||
@@ -179,6 +188,121 @@ export async function verifyRuntimeBundle(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstructs a Runtime identity that was fully verified when it was
|
||||
* registered. Normal capabilities and prompt launches use this bounded
|
||||
* metadata path instead of hashing the complete Runtime payload again.
|
||||
*/
|
||||
export async function loadRegisteredRuntimeBundle(
|
||||
bundleDirectoryInput: string,
|
||||
options: LoadRegisteredRuntimeBundleOptions
|
||||
): Promise<VerifiedRuntimeBundle> {
|
||||
const bundleDirectory = assertAbsoluteManagedPath(
|
||||
resolve(bundleDirectoryInput)
|
||||
)
|
||||
const registered = runtimeRegistryEntrySchema.parse(
|
||||
options.registered
|
||||
)
|
||||
const rootStat = await lstat(bundleDirectory)
|
||||
assertOwnedDirectory(
|
||||
rootStat,
|
||||
'Runtime bundle directory',
|
||||
options.uid
|
||||
)
|
||||
if (
|
||||
shouldEnforceMode(options) &&
|
||||
modeString(rootStat.mode) !== '0700'
|
||||
) {
|
||||
throw new Error(
|
||||
'Runtime bundle directory permissions must be 0700'
|
||||
)
|
||||
}
|
||||
if (
|
||||
basename(bundleDirectory) !==
|
||||
registered.bundleDigest.slice('sha256:'.length)
|
||||
) {
|
||||
throw new Error(
|
||||
'Registered Runtime digest does not match its managed directory'
|
||||
)
|
||||
}
|
||||
|
||||
const manifestBytes = await readMetadataFile(
|
||||
join(bundleDirectory, MANIFEST_FILE_NAME),
|
||||
'Runtime manifest',
|
||||
options
|
||||
)
|
||||
const signatureBytes = await readSignature(
|
||||
join(bundleDirectory, SIGNATURE_FILE_NAME),
|
||||
options
|
||||
)
|
||||
const manifest = await verifyRuntimeManifestSignature(
|
||||
manifestBytes,
|
||||
signatureBytes,
|
||||
options.releaseKeyRegistry,
|
||||
options.verificationEnvironment ?? 'production'
|
||||
)
|
||||
assertRuntimeManifestMatchesLock(
|
||||
manifest,
|
||||
remoteRuntimeLockSchema.parse(options.runtimeLock),
|
||||
options.architecture
|
||||
)
|
||||
const manifestDigest =
|
||||
await digestRemoteRuntimeBundleManifest(manifest)
|
||||
if (
|
||||
manifest.runtimeId !== registered.runtimeId ||
|
||||
manifest.runtimeVersion !== registered.runtimeVersion ||
|
||||
manifest.architecture !== registered.architecture ||
|
||||
manifest.bundleDigest !== registered.bundleDigest ||
|
||||
manifestDigest !== registered.manifestDigest ||
|
||||
(
|
||||
registered.runtimeAdapterDigest !== undefined &&
|
||||
manifest.adapterDigest !== registered.runtimeAdapterDigest
|
||||
) ||
|
||||
manifest.acpCapabilitiesDigest !==
|
||||
registered.acpCapabilitiesDigest
|
||||
) {
|
||||
throw new Error(
|
||||
'Runtime manifest does not match its registered identity'
|
||||
)
|
||||
}
|
||||
|
||||
const executableRecord = manifest.files.find(
|
||||
(file) => file.path === manifest.entrypoint.path
|
||||
)
|
||||
if (executableRecord === undefined) {
|
||||
throw new Error(
|
||||
'Registered Runtime entrypoint is not declared'
|
||||
)
|
||||
}
|
||||
const executablePath = join(
|
||||
bundleDirectory,
|
||||
...manifest.entrypoint.path.split('/')
|
||||
)
|
||||
const executableStat = await lstat(executablePath)
|
||||
assertOwnedRegularFile(
|
||||
executableStat,
|
||||
'Runtime executable',
|
||||
options.uid
|
||||
)
|
||||
if (
|
||||
executableStat.size !== executableRecord.size ||
|
||||
(
|
||||
shouldEnforceMode(options) &&
|
||||
modeString(executableStat.mode) !== executableRecord.mode
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'Registered Runtime entrypoint metadata changed'
|
||||
)
|
||||
}
|
||||
return {
|
||||
bundleDirectory,
|
||||
executablePath,
|
||||
manifest,
|
||||
manifestDigest
|
||||
}
|
||||
}
|
||||
|
||||
export function canonicalRuntimeManifestBytes(
|
||||
manifest: RemoteRuntimeBundleManifest
|
||||
): Buffer {
|
||||
|
||||
@@ -16,7 +16,14 @@ export const installationRegistryEntrySchema = z
|
||||
installationId: installationRegistryIdSchema,
|
||||
agentVersion: componentVersionSchema,
|
||||
manifestSha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
arch: z.enum(['x64', 'arm64'])
|
||||
arch: z.enum(['x64', 'arm64']),
|
||||
protocol: z
|
||||
.object({
|
||||
major: z.number().int().min(0).max(65_535),
|
||||
minor: z.number().int().min(0).max(65_535)
|
||||
})
|
||||
.strict()
|
||||
.optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
@@ -137,6 +144,7 @@ export const runtimeRegistryEntrySchema = z
|
||||
architecture: z.enum(['x64', 'arm64']),
|
||||
bundleDigest: sha256DigestSchema,
|
||||
manifestDigest: sha256DigestSchema,
|
||||
runtimeAdapterDigest: sha256DigestSchema.optional(),
|
||||
acpCapabilitiesDigest: sha256DigestSchema
|
||||
})
|
||||
.strict()
|
||||
@@ -219,7 +227,10 @@ function canonicalInstallationEntry(
|
||||
installationId: entry.installationId,
|
||||
agentVersion: entry.agentVersion,
|
||||
manifestSha256: entry.manifestSha256,
|
||||
arch: entry.arch
|
||||
arch: entry.arch,
|
||||
...(entry.protocol === undefined
|
||||
? {}
|
||||
: { protocol: entry.protocol })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -233,6 +244,12 @@ function canonicalRuntimeEntry(
|
||||
architecture: entry.architecture,
|
||||
bundleDigest: entry.bundleDigest,
|
||||
manifestDigest: entry.manifestDigest,
|
||||
...(entry.runtimeAdapterDigest === undefined
|
||||
? {}
|
||||
: {
|
||||
runtimeAdapterDigest:
|
||||
entry.runtimeAdapterDigest
|
||||
}),
|
||||
acpCapabilitiesDigest: entry.acpCapabilitiesDigest
|
||||
})
|
||||
}
|
||||
@@ -245,6 +262,7 @@ function installationEntryEquals(
|
||||
left.installationId === right.installationId &&
|
||||
left.agentVersion === right.agentVersion &&
|
||||
left.manifestSha256 === right.manifestSha256 &&
|
||||
left.arch === right.arch
|
||||
left.arch === right.arch &&
|
||||
JSON.stringify(left.protocol) === JSON.stringify(right.protocol)
|
||||
)
|
||||
}
|
||||
|
||||
+127
-12
@@ -12,6 +12,7 @@ import {
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync
|
||||
@@ -497,7 +498,15 @@ describe('compound Agent packages', () => {
|
||||
})
|
||||
expect(events.at(-1)).toEqual(prepared)
|
||||
expect(readdirSync(join(operationRoot, 'prepared')))
|
||||
.toEqual(['result.json'])
|
||||
.toEqual([
|
||||
'agent-package.json',
|
||||
'agent-package.sig',
|
||||
'agent-release-keys.json',
|
||||
'agent-runtime-lock.json',
|
||||
'payload',
|
||||
'remote-runtime-lock.json',
|
||||
'result.json'
|
||||
])
|
||||
expectGlobalMetadataUnchanged(globalMetadata)
|
||||
|
||||
const cliOperationRoot = join(temporaryRoot, 'remote-cli-operation')
|
||||
@@ -569,13 +578,23 @@ describe('compound Agent packages', () => {
|
||||
commitEvents.filter(
|
||||
(event) =>
|
||||
event.type === 'progress' &&
|
||||
event.phase === 'extracting-payload'
|
||||
event.phase === 'publishing-content'
|
||||
)
|
||||
).toHaveLength(1)
|
||||
expect(readdirSync(join(operationRoot, 'prepared')))
|
||||
.toEqual(['result.json'])
|
||||
.toEqual([
|
||||
'agent-package.json',
|
||||
'agent-package.sig',
|
||||
'agent-release-keys.json',
|
||||
'agent-runtime-lock.json',
|
||||
'payload',
|
||||
'remote-runtime-lock.json',
|
||||
'result.json'
|
||||
])
|
||||
expect(readdirSync(operationRoot)).toEqual(['prepared'])
|
||||
expectGlobalMetadataUnchanged(globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
globalMetadata
|
||||
)
|
||||
|
||||
packageInstaller.preparePackage({
|
||||
operationRoot,
|
||||
@@ -591,7 +610,76 @@ describe('compound Agent packages', () => {
|
||||
homeDirectory
|
||||
})
|
||||
).not.toThrow()
|
||||
expectGlobalMetadataUnchanged(globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
globalMetadata
|
||||
)
|
||||
})
|
||||
|
||||
it('resumes commit after an Agent directory was already published', () => {
|
||||
const operationRoot = join(
|
||||
temporaryRoot,
|
||||
'partial-commit-operation'
|
||||
)
|
||||
const homeDirectory = join(
|
||||
temporaryRoot,
|
||||
'partial-commit-home'
|
||||
)
|
||||
const prepared = packageInstaller.preparePackage({
|
||||
operationRoot,
|
||||
archive: packagePath,
|
||||
expectedSha256: packageResult.sha256,
|
||||
homeDirectory
|
||||
})
|
||||
const agentSource = join(
|
||||
operationRoot,
|
||||
'prepared',
|
||||
'payload',
|
||||
'agent'
|
||||
)
|
||||
const agentDestination = join(
|
||||
homeDirectory,
|
||||
'.goodbuddy',
|
||||
'agent',
|
||||
'installations',
|
||||
prepared.agent.installationId
|
||||
)
|
||||
mkdirSync(dirname(agentDestination), {
|
||||
recursive: true,
|
||||
mode: 0o700
|
||||
})
|
||||
renameSync(agentSource, agentDestination)
|
||||
|
||||
expect(
|
||||
packageInstaller.commitPackage({
|
||||
operationRoot,
|
||||
archive: packagePath,
|
||||
expectedSha256: packageResult.sha256,
|
||||
homeDirectory
|
||||
})
|
||||
).toMatchObject({
|
||||
status: 'committed',
|
||||
agent: prepared.agent,
|
||||
runtime: prepared.runtime
|
||||
})
|
||||
expect(
|
||||
lstatSync(join(agentDestination, 'goodbuddy-agent'))
|
||||
.isFile()
|
||||
).toBe(true)
|
||||
expect(
|
||||
lstatSync(
|
||||
join(
|
||||
homeDirectory,
|
||||
'.goodbuddy',
|
||||
'runtimes',
|
||||
'opencode',
|
||||
prepared.runtime.bundleDigest.slice(
|
||||
'sha256:'.length
|
||||
),
|
||||
'bin',
|
||||
'opencode'
|
||||
)
|
||||
).isFile()
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('requires untampered prepared state before commit mutation', () => {
|
||||
@@ -816,7 +904,9 @@ describe('compound Agent packages', () => {
|
||||
expect(
|
||||
readFileSync(join(agentDestination, 'manifest.json'))
|
||||
).toBeTruthy()
|
||||
expectGlobalMetadataUnchanged(globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
globalMetadata
|
||||
)
|
||||
})
|
||||
|
||||
it('restores a replaced Agent directory when Runtime publication fails', () => {
|
||||
@@ -861,7 +951,7 @@ describe('compound Agent packages', () => {
|
||||
expect(readdirSync(agentDestination)).toEqual(['old-marker'])
|
||||
})
|
||||
|
||||
it('reuses only an identical trusted installed Node without changing global metadata', () => {
|
||||
it('publishes each Agent payload independently of existing installations', () => {
|
||||
const variantAgent = join(temporaryRoot, 'reuse-variant-agent')
|
||||
writeAgentBundle(variantAgent, 'x64')
|
||||
writeFileSync(
|
||||
@@ -999,7 +1089,7 @@ describe('compound Agent packages', () => {
|
||||
)
|
||||
expect(
|
||||
lstatSync(identical.currentNode).ino
|
||||
).toBe(
|
||||
).not.toBe(
|
||||
lstatSync(
|
||||
installedVariantNode(
|
||||
identical.homeDirectory,
|
||||
@@ -1007,7 +1097,9 @@ describe('compound Agent packages', () => {
|
||||
)
|
||||
).ino
|
||||
)
|
||||
expectGlobalMetadataUnchanged(identical.globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
identical.globalMetadata
|
||||
)
|
||||
|
||||
const changed = installCurrent('changed')
|
||||
const changedResult = prepareAndCommit({
|
||||
@@ -1029,7 +1121,9 @@ describe('compound Agent packages', () => {
|
||||
)
|
||||
).ino
|
||||
)
|
||||
expectGlobalMetadataUnchanged(changed.globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
changed.globalMetadata
|
||||
)
|
||||
|
||||
const corrupt = installCurrent('corrupt')
|
||||
writeFileSync(corrupt.currentNode, Buffer.from('corrupt Node'))
|
||||
@@ -1044,7 +1138,9 @@ describe('compound Agent packages', () => {
|
||||
)
|
||||
).ino
|
||||
)
|
||||
expectGlobalMetadataUnchanged(corrupt.globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
corrupt.globalMetadata
|
||||
)
|
||||
|
||||
const untrusted = installCurrent('untrusted')
|
||||
const currentRoot = dirname(untrusted.currentNode)
|
||||
@@ -1063,7 +1159,9 @@ describe('compound Agent packages', () => {
|
||||
)
|
||||
).ino
|
||||
)
|
||||
expectGlobalMetadataUnchanged(untrusted.globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
untrusted.globalMetadata
|
||||
)
|
||||
})
|
||||
|
||||
it('fails the remote installer closed on traversal, duplicates, corruption, and hash mismatch', () => {
|
||||
@@ -2285,3 +2383,20 @@ function expectGlobalMetadataUnchanged(
|
||||
expect(readFileSync(path)).toEqual(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
function expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
files: ReadonlyMap<string, Buffer>
|
||||
): void {
|
||||
for (const [path, bytes] of files) {
|
||||
if (path.endsWith('registry.json')) {
|
||||
expect(readFileSync(path)).toEqual(bytes)
|
||||
continue
|
||||
}
|
||||
const actual = JSON.parse(readFileSync(path, 'utf8'))
|
||||
expect(actual).toEqual(
|
||||
path.endsWith('remote-runtime-lock.json')
|
||||
? remoteRuntimeLock
|
||||
: registry
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user