diff --git a/.gitignore b/.gitignore
index b6dcdf70f031c6fa6b5a483e410f559ae145b1ba..39893782eeb8439bdf33ab6abe6ec497f3487c64 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,3 +15,6 @@ output/
.env
.env.*
!.env.example
+
+# Host service dependencies for local tests (the image installs its own)
+host/server/node_modules/
diff --git a/DETAILS.md b/DETAILS.md
index 7c2187d0b9ab581e57641662349b5d7711ed9e53..7a98b079097f5845833145e39f18549976608ff0 100644
--- a/DETAILS.md
+++ b/DETAILS.md
@@ -34,3 +34,10 @@
- `docs/AI-INSTALL*.md`:供 AI 执行的部署、配置与验收指南 / AI deployment, configuration and verification guide.
- `mac/clients/desktop/local-services.mjs`:置顶与分组的原 Host 设置适配、账户缓存恢复。 / Native Host settings for pins and groups, with account cache restoration.
+
+- `host/runtime/openai-chat.mjs`、`openai-responses.mjs`、`anthropic-messages.mjs`、`model-common.mjs`:三种模型接口格式的适配 / Adapters for the three model API formats.
+- `host/runtime/reliability/tool-order.mjs`:一次模型回复中的消息按顺序送达 / Delivers the messages of one model response in order.
+- `host/deploy.py`、`host/release/platforms.py`:部署、升级、备份恢复与架构检查 / Deployment, upgrades, backup and recovery, and architecture checks.
+- `host/tools/host-admin.mjs`:命令行管理 / Command-line administration.
+- `mac/clients/desktop/platform.mjs`:桌面客户端的平台差异 / Platform differences of the desktop client.
+- `host/tests/`、`mac/tests/`、`ios/tests/`:测试,用 `node --test "host/tests/*.test.mjs"`、`node --test "mac/tests/*.test.mjs"` 运行 / Tests; run with `node --test "host/tests/*.test.mjs"` and `node --test "mac/tests/*.test.mjs"`.
diff --git a/README.en.md b/README.en.md
index 126f319bfad6ac778c98b422d0e59a3070c48a82..e06f21c9b699cde68c7a29a84e775b63b795e905 100644
--- a/README.en.md
+++ b/README.en.md
@@ -8,6 +8,8 @@
**A private server for Grok Bot.** Keep the original Grok Bot apps for Mac and iOS, and connect them to a server you host yourself.
+For Windows or Android clients, use [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus), which is based on this project.
+
@@ -17,7 +19,7 @@
[简体中文](README.md) · **English**
-[Install](#install) · [Why](#why-i-built-this) · [Feature map](#how-the-original-features-are-provided) · [Under the hood](#how-each-part-was-built) · [Release notes](RELEASE.en.md)
+[Install](#install) · [Why](#why-i-built-this) · [Feature map](#how-the-original-features-are-provided) · [Under the hood](#how-each-part-was-built) · [Compared with the official app](#compared-with-the-official-app) · [Server requirements](#server-requirements) · [Client versions](#client-versions) · [Release notes](RELEASE.en.md)
@@ -67,7 +69,7 @@ The public edition provides Mac, iOS and Host patch tools. Supply the supported
| --- | --- | --- | --- |
| 🔁 Sign-in | Official account | The Host admin page creates a six-character pairing code; enter the Host address and code in the app to connect | — |
| 🔁 Host and execution computer | Official cloud | Runs wherever you deploy it, using the original Host | Any device that can run Docker |
-| 🔁 Chat models | Official models with automatic tier selection | You choose the models. The Jev classifier can pick the model and reasoning effort for each task | An OpenAI-compatible endpoint and API key |
+| 🔁 Chat models | Official models with automatic tier selection | You choose the models. Add several model services and set the model, reasoning effort and backup models for all Bots or for one Bot | A model endpoint and API key: OpenAI Chat Completions, OpenAI Responses or Anthropic Messages |
| 🟢 Computer and browser use | Original Agent | Kept as is | A model with vision |
| 🟢 Memory, context compaction, scheduled tasks | Original Agent, partly backed by official services | Kept, now running on your models with local timers; compaction thresholds are configurable | — |
| 🟢 Approvals, human takeover, input forms | Original | Kept as is | — |
@@ -100,9 +102,14 @@ Disabled: virtual cards, external message drafts, product feedback and passkey f
| **Usage** | See how many tokens you used each day, on the admin page and in the iOS settings. |
| **Prompt management** | Edit system prompts and restore the original at any time, and see exactly which prompts and tools each role received. |
| **Per-model context** | Set each model's context size and when summarization starts. |
+| **Models per Bot** | Each Bot can have its own primary model, reasoning effort and backup models. If the primary fails before any output (quota, rate limit, service error, network), the backups are tried in order. |
+| **Manual compaction** | Summarize an idle Bot's context from the admin page. |
+| **Web client** | The Host can serve a web interface to browsers signed in with a pairing code. The bundle is built from the official Windows installer with the [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.en.md) tools and uploaded on the admin page; nothing changes until one is uploaded. |
| **Admin page** | Configure everything in the browser. It follows the original design and supports Chinese and English, light and dark themes, and phone screens. |
| **Split deployment** | Run the Host and the execution computer on different machines. |
| **Backup and restore** | Back up all data and restore it as a new instance. |
+| **Deploy tool** | `host/deploy.py` checks the environment, initializes, builds and starts, upgrades, backs up and restores, one command each. |
+| **Command-line admin** | `host/tools/host-admin.mjs` sets up the Host, configures models and creates pairing codes without the web page. |
@@ -115,7 +122,7 @@ The tools read the supported original files, apply this project's changes, and g
| Part | Implementation |
| --- | --- |
| **Host** | Reuses the original Host / Harness for task execution, tools, memory and context management. Adds administrator sign-in, pairing, providers and local scheduling. |
-| **Models** | Converts requests to an OpenAI-compatible API. Choose a fixed model and reasoning effort, or enable Jev to route by task difficulty. |
+| **Models** | Converts requests to OpenAI Chat Completions, OpenAI Responses or Anthropic Messages. The default route and Bot routes set the model, reasoning effort and backup order. A legacy configuration that routes by task difficulty with Jev keeps working, and saving it from the new model page asks for confirmation before migrating it. |
| **Execution computer** | Runs the original Linux desktop image in Docker, together with the Host or on another machine. The Mac app connects to the Host to provide local operations and Codex coding. |
| **Mac app** | Keeps the original Electron interface and replaces the connection and system integration main process. |
| **iOS app** | Injects a dylib and applies fixed byte patches, keeping the interface, widgets, sharing and notification extensions. Sign the generated IPA yourself. |
@@ -125,17 +132,72 @@ The tools read the supported original files, apply this project's changes, and g
See [Features and architecture](docs/ARCHITECTURE.en.md) for more detail.
+## Compared with the official app
+
+**Benefits**
+
+- Choose your own models and providers, billed through your own API; relays and aggregator gateways work too, and different Bots can use different models.
+- Chats, files and memory stay on your own server, with no telemetry.
+- Works where the official service isn't available, or only on your LAN.
+- Some extras the official version doesn't have: editing the system prompt (the original can be restored at any time), context length per model, usage statistics, tasks triggered by webhooks, your own apps, Bot collaboration across several Hosts, and data backup and restore.
+
+**Trade-offs**
+
+- You need a machine that runs Docker, and you do upgrades and backups yourself.
+- Versions are pinned: the Mac app at 0.71.2 and iOS at 1.16.0 (see [client versions](#client-versions)). When the official apps update, you have to wait for this project to support them; there are no automatic updates.
+- Results depend on the model you choose. The official service is tuned for its own models, so other models may feel different.
+- Some official features are turned off or replaced: virtual cards, external message drafts, product feedback and passkey forwarding are off; voice, push and image/video generation need providers you set up yourself; real-time voice calls are experimental.
+- You sign the apps yourself: the Mac app is ad-hoc signed by default and needs your own certificate before a Bot can operate that Mac; on iPhone and iPad you sign and install with your own certificate.
+- Modifying the official apps may violate the official terms of use. Use at your own risk.
+
+## Server requirements
+
+The models run at your API provider, so **the server needs no GPU**. It only runs two Docker containers: the Host and the execution computer (a Linux desktop).
+
+| | Minimum | Recommended |
+| --- | --- | --- |
+| CPU | 2 cores | 4 cores or more |
+| Memory | 4 GB | 8 GB or more |
+| Free disk space | 30 GB | 50 GB or more |
+| System | A 64-bit system with Docker Engine 26+, Compose 2.26+ and Python 3.10+ | x86_64 Linux (tested on Ubuntu 24.04 with Docker 29) |
+
+This is enough for one person or a household. Heavy use by many people at once has not been tested. These figures come from [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus) test runs on x86_64 Linux:
+
+- **2 cores and 2 GB is not enough.** Both test runs failed to finish a series of chats in time, and the background model connection dropped and the core restarted.
+- **2 cores / 4 GB and 4 cores / 8 GB both work.** Each was deployed from scratch and completed pairing, an attachment upload, several real chats and a cancellation; after a restart, chats and settings were all still there. A build from scratch takes about 9–10 minutes, depending on network speed.
+- **Actual usage.** On a server with 6 cores and 16 GB, running for about a week, the Host used about 0.7 GB of memory (peak 0.9 GB) and the execution computer about 0.8 GB (peak 1.7 GB). The images take about 13 GB of disk. Chat and file data start under 100 MB and grow with use.
+- The first deployment downloads the official files and base images from the internet, and the build needs extra temporary space. Backups also take space.
+
+| Your machines | Notes |
+| --- | --- |
+| One x86_64 Linux machine | **Recommended.** The Host and the execution computer run on the same machine; the figures above were measured this way. |
+| ARM64 Linux + x86_64 Linux | The Host runs on the ARM machine and the execution computer on the x86_64 machine (the execution computer only exists for amd64). See [split deployment](host/docs/DEPLOYMENT.en.md). Chat and the remote desktop were tested on an Oracle Ampere A1 earlier; the current version has not been retested there. |
+| ARM only (ARM64 Linux, Apple Silicon Mac) | The execution computer runs under emulation and is clearly slower; `python3 host/deploy.py doctor` checks whether it can run first. Docker Desktop on Apple Silicon Macs has not been tested. |
+| A NAS | Anything that runs Docker Compose v2; match its CPU architecture to the rows above. Not tested. |
+
## What you need
| Item | Details |
| --- | --- |
-| **Machine** | A computer or NAS with Docker Compose. Images target Linux amd64; Apple Silicon Macs use emulation |
+| **Machine** | A computer or NAS with Docker Compose; see [server requirements](#server-requirements). The Host image is built for the Docker machine's architecture (amd64 or arm64); the Linux desktop image is amd64 only and runs under emulation on ARM machines, including Apple Silicon Macs |
| **Mac** | Apple Silicon Mac; supported client version: 0.71.2 |
| **iOS** | The unsigned IPA from Releases, or your own decrypted 1.16.0 (23152) IPA; your own signing tools and certificate |
| **Software** | Python 3.10+, Docker Compose; Node.js 22.12+ for Mac patching |
-| **Required service** | An OpenAI-compatible model with tool calling; computer use needs image input |
+| **Required service** | A model with tool calling, through OpenAI Chat Completions, OpenAI Responses or Anthropic Messages; computer use needs image input |
| **Optional services** | Speech, media and search providers; Bark or your APNs credentials |
+## Client versions
+
+The patches accept only the versions below and never update themselves. The latest official releases were checked on 2026-11-19; when they are newer than the right column, wait until this project supports them.
+
+| Platform | Latest official | Version this project needs | How to get it |
+| --- | --- | --- | --- |
+| macOS (Apple Silicon) | 1.2.3 | 0.71.2 | `mac/patchers/desktop/patch.mjs` downloads and verifies it |
+| iOS / iPadOS | 1.26.0 | 1.16.0 (build 23152) | The IPA on the [releases page](https://gitee.com/ahaduoduoduo/ProkBot/releases); sign and install it yourself |
+| Linux server | n/a | Host `d0a4baa`; execution computer `9d2ac1b` (amd64) | The build tools download and verify them |
+
+For the Windows and Android clients and the web client, see the versions in [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/README.en.md#client-versions).
+
## Install
Copy the following to an AI that can run commands, using the copy button at the top right of the code block:
diff --git a/README.md b/README.md
index 01bfbb8d304c7fafe1943c0b5ca4f1fa88d2d4de..1180697107f974a9460a2f8b1164f287799d2029 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,8 @@
**一个 Grok Bot 私服。** 使用原版 Grok Bot 的 Mac 和 iOS 客户端,连接自部署服务端。
+需要 Windows 或 Android 客户端,请使用基于本项目的 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus)。
+
@@ -113,7 +120,7 @@ flowchart LR
| 部分 | 实现方式 |
| --- | --- |
| **Host** | 复用原 Host / Harness 的任务执行、工具、记忆和上下文管理,补充管理员登录、设备配对、供应商配置与本地定时触发。 |
-| **模型** | 将原模型请求转换为 OpenAI 兼容接口。可以固定模型和思考强度,也可以启用 Jev,按任务难度选择模型与强度。 |
+| **模型** | 将原模型请求转换为 OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages 格式。默认路由和 Bot 路由指定模型、思考强度和备用顺序;使用 Jev 按任务难度选择的旧配置照常工作,在新模型页保存时会先确认再迁移。 |
| **执行电脑** | 原 Linux 桌面镜像运行在 Docker 中,可以与 Host 分开部署。Mac 客户端主动连接 Host,提供本机操作与 Codex 编程。 |
| **Mac 客户端** | 保留 Electron 原界面,替换连接和系统功能的主进程,接入自己的 Host。 |
| **iOS 客户端** | 注入 dylib 并应用固定字节补丁,保留原界面、小组件、分享和通知扩展。输出的 IPA 自行签名安装。 |
@@ -123,17 +130,72 @@ flowchart LR
更完整的说明见[功能与原理](docs/ARCHITECTURE.md)。
+## 和官方版比较
+
+**好处**
+
+- 模型和服务商自己选,按你自己的接口计费,也可以用中转或聚合网关;不同的 Bot 可以用不同的模型。
+- 对话、文件、记忆都在自己的服务器上,没有遥测。
+- 官方服务用不了的地方也能用;只在局域网里用也行。
+- 多了一些官方没有的功能:修改系统提示词(随时能恢复原版)、按模型设置上下文长度、用量统计、Webhook 触发任务、自己写应用、多台 Host 之间的 Bot 协作、数据备份与恢复。
+
+**代价**
+
+- 要有一台能运行 Docker 的机器,升级和备份要自己做。
+- 版本是固定的:Mac 客户端 0.71.2,iOS 1.16.0(见[客户端版本](#客户端版本))。官方出新版后,要等本项目适配才能升级,没有自动更新。
+- 效果取决于你选的模型。官方针对自家模型做过调校,换别的模型体验可能有差距。
+- 部分官方功能关掉或换掉了:虚拟卡、外部消息草稿、产品反馈、通行密钥转发已关闭;语音、推送、生图视频要自己准备服务商;实时语音通话还是实验功能。
+- 客户端要自己签名:Mac 客户端默认 ad-hoc 签名,想让 Bot 操作这台 Mac 需要用自己的证书签名;iPhone / iPad 用自己的证书签名安装。
+- 修改官方客户端可能违反官方用户条款,风险自负。
+
+## 服务器要求
+
+模型推理走 API,在模型服务商那边,**服务器不需要显卡**。服务器只运行两个 Docker 容器:Host 和执行电脑(Linux 桌面)。
+
+| | 最低 | 推荐 |
+| --- | --- | --- |
+| CPU | 2 核 | 4 核或更多 |
+| 内存 | 4 GB | 8 GB 或更多 |
+| 硬盘可用空间 | 30 GB | 50 GB 或更多 |
+| 系统 | 64 位系统,Docker Engine 26+ 和 Compose 2.26+,Python 3.10+ | x86_64 Linux(实测环境为 Ubuntu 24.04 + Docker 29) |
+
+这个配置适合一个人或一家人日常使用;多人同时高强度使用还没有测过。以下数据来自 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus) 在 x86_64 Linux 上的实测:
+
+- **2 核 2 GB 不够用。** 实测两次都没能按时完成连续对话,还出现过后台断连、核心重启。
+- **2 核 4 GB、4 核 8 GB 都实测可用。** 各自从零部署,完成了配对、上传附件、多轮真实对话、中途取消,重启后对话和设置都还在。从零构建大约要 9~10 分钟(视网速而定)。
+- **实际占用。** 一台 6 核 16 GB 的服务器连续运行约一周:Host 平时约 0.7 GB 内存,最高 0.9 GB;执行电脑平时约 0.8 GB,最高 1.7 GB。镜像约占 13 GB 硬盘,对话和文件数据刚开始不到 100 MB,会随使用增长。
+- 首次部署要从网上下载官方原版文件和基础镜像(国内网络可能需要代理),构建时还要额外的临时空间;备份也另占空间。
+
+| 你的机器 | 说明 |
+| --- | --- |
+| 一台 x86_64 Linux | **推荐。** Host 和执行电脑装在同一台机器上,上面的数据都是这种方式测得的。 |
+| ARM64 Linux + x86_64 Linux | Host 装在 ARM 机器上,执行电脑装在 x86_64 机器上(执行电脑只有 amd64 版本),见[分开部署](host/docs/DEPLOYMENT.md)。以往在甲骨文 Ampere A1 上测过对话和远程桌面,当前版本还没有重新测过。 |
+| 只有 ARM 机器(ARM64 Linux、Apple Silicon Mac) | 执行电脑通过转译运行,明显更慢;`python3 host/deploy.py doctor` 会先检查能不能运行。Apple Silicon Mac 上的 Docker Desktop 没有测过。 |
+| NAS | 能运行 Docker Compose v2 即可,按 CPU 架构对照上面几行;没有测过。 |
+
## 你需要准备什么
| 类别 | 内容 |
| --- | --- |
-| **机器** | 支持 Docker Compose 的电脑或 NAS;镜像为 Linux amd64,Apple Silicon Mac 通过转译运行 |
+| **机器** | 支持 Docker Compose 的电脑或 NAS,配置见[服务器要求](#服务器要求)。Host 镜像按 Docker 所在机器的架构构建(amd64 或 arm64);Linux 桌面镜像只有 amd64,在 ARM 机器(包括 Apple Silicon Mac)上通过转译运行 |
| **Mac** | Apple Silicon Mac;支持的客户端版本为 0.71.2 |
| **iOS** | 使用发布页提供的未签名 IPA,或自行注入 1.16.0(23152)砸壳包;准备自己的签名工具和证书 |
| **软件** | Python 3.10+、Docker Compose;生成 Mac 客户端需要 Node.js 22.12+ |
-| **必需服务** | 支持工具调用的 OpenAI 兼容模型接口;电脑操作需要模型支持图片输入 |
+| **必需服务** | 支持工具调用的模型接口(OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages);电脑操作需要模型支持图片输入 |
| **可选服务** | 语音、图片视频、搜索供应商;Bark 或自己的 APNs 凭据 |
+## 客户端版本
+
+补丁只认下面这些版本,不会自动更新。官方最新版是 2026-11-19 核对的,比右栏新时要等本项目适配。
+
+| 平台 | 官方最新版 | 本项目需要的版本 | 怎么获得 |
+| --- | --- | --- | --- |
+| macOS(Apple Silicon) | 1.2.3 | 0.71.2 | `mac/patchers/desktop/patch.mjs` 自动下载并校验 |
+| iOS / iPadOS | 1.26.0 | 1.16.0(构建 23152) | [发行页](https://gitee.com/ahaduoduoduo/ProkBot/releases)的 IPA,自行签名安装 |
+| Linux 服务端 | 不适用 | Host `d0a4baa`;执行电脑 `9d2ac1b`(amd64) | 构建工具自动下载并校验 |
+
+Windows、Android 客户端和网页版的版本见 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus#client-versions)。
+
## 安装
复制下面内容给能执行命令的 AI,点击代码框右上角即可复制:
diff --git a/docs/AI-INSTALL.en.md b/docs/AI-INSTALL.en.md
index 75d4436b8167fc83e8fbf7bc010cbf4aa8155eb7..9b9733953b54fac5a6d4b5250bb922f1f33f1b33 100644
--- a/docs/AI-INSTALL.en.md
+++ b/docs/AI-INSTALL.en.md
@@ -4,9 +4,9 @@ Goal: deploy ProkBot, configure its model and connect the clients. Project: http
## Before starting
-Ask together for: local or remote Host and working directory; Mac / iOS clients and local Mac control; LAN / Tailcat / existing HTTPS access; model endpoint, API key and model ID; and the administrator password for a new deployment. Remote deployment also needs connection details.
+Ask together for: local or remote Host and working directory; Mac / iOS clients and local Mac control; LAN / Tailcat / existing HTTPS access; model API format (OpenAI Chat Completions, OpenAI Responses or Anthropic Messages), endpoint, API key and model ID; and the administrator password for a new deployment. Remote deployment also needs connection details.
-Check architecture, memory, disk space and existing deployments. Reuse existing configuration and back up before updating. Install missing Python 3.10+ and Docker Compose. Mac patching runs on an Apple Silicon Mac with Node.js 22.12+.
+Check architecture, memory, disk space and existing deployments. Reuse existing configuration and back up before updating. Install missing Python 3.10+, Docker Engine 26.0+ and Docker Compose 2.26.0+ (needed when the Host and Linux desktop share a machine; Ubuntu 24.04's own packages are enough). Mac patching runs on a Mac (Apple Silicon; Intel is experimental) with Node.js 22.12+.
## Inputs and outputs
@@ -25,13 +25,18 @@ The example uses a new project named `prokbot`; reuse the project name and volum
```sh
python3 host/release/build-docker.py
+docker compose --env-file .env -p prokbot -f host/release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data
docker compose --env-file .env -p prokbot -f host/release/compose.yaml up -d
docker compose --env-file .env -p prokbot -f host/release/compose.yaml exec host cat /data/setup-key
```
-Images use Linux amd64; Docker on Apple Silicon uses emulation. For a separate Host and execution computer, select the Compose files described in `host/docs/DEPLOYMENT.en.md`.
+The second command creates the memory and other directories the Linux desktop mounts, only where missing. Run it once before `up -d` for both new deployments and upgrades; otherwise the Linux desktop fails to start.
-Open the administration page, initialize the administrator account, configure the user's model endpoint and key, select a model and test it. Configure and verify Tailcat under Remote Access when selected.
+A new deployment can also use `doctor`, `init`, `up` and `status` from `python3 host/deploy.py` for the same steps; see `--help`. Existing deployments keep their current commands.
+
+The Host image is built for the Docker machine's architecture (amd64 or arm64). The Linux desktop image is amd64 only; on ARM machines Docker must run it under emulation, and the build tool checks this first. For a separate Host and execution computer, select the Compose files described in `host/docs/DEPLOYMENT.en.md`.
+
+Open the administration page and initialize the administrator account. Under Models, add a model service (API format, address, key), create a model profile (a service plus a model ID), set the default route, test each profile and save; if the user wants, give individual Bots their own primary model, reasoning effort and backup models. Configure and verify Tailcat under Remote Access when selected.
Use the administration UI or consult `host/server/index.mjs` for the current request formats and sessions:
diff --git a/docs/AI-INSTALL.md b/docs/AI-INSTALL.md
index 5745534b3f4a217f127216252474938f1fd299ee..89f3fb7b42fc988756155ad5e4f436bbf5fe0e75 100644
--- a/docs/AI-INSTALL.md
+++ b/docs/AI-INSTALL.md
@@ -4,9 +4,9 @@
## 开始前
-一次询问:Host 部署在本机还是远程机器及工作目录、需要 Mac / iOS 哪些客户端及是否控制 Mac、本机或远程的访问方式(局域网 / Tailcat / 已有 HTTPS)、模型接口地址 / API Key / 模型 ID,以及新部署的管理员密码。远程部署还需要连接方式。
+一次询问:Host 部署在本机还是远程机器及工作目录、需要 Mac / iOS 哪些客户端及是否控制 Mac、本机或远程的访问方式(局域网 / Tailcat / 已有 HTTPS)、模型接口格式(OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages)/ 地址 / API Key / 模型 ID,以及新部署的管理员密码。远程部署还需要连接方式。
-检查目标机器架构、内存、磁盘和已有部署;复用用户已有配置,更新前使用备份工具保存数据。安装缺少的 Python 3.10+、Docker Compose;Mac 补丁在 Apple Silicon Mac 上运行,需要 Node.js 22.12+。
+检查目标机器架构、内存、磁盘和已有部署;复用用户已有配置,更新前使用备份工具保存数据。安装缺少的 Python 3.10+、Docker Engine 26.0+ 和 Docker Compose 2.26.0+(Host 和 Linux 桌面同机部署时需要这些版本,Ubuntu 24.04 系统仓库的版本就够);Mac 补丁在 Mac 上运行(Apple Silicon;Intel 为实验支持),需要 Node.js 22.12+。
## 资源与输出
@@ -25,13 +25,18 @@
```sh
python3 host/release/build-docker.py
+docker compose --env-file .env -p prokbot -f host/release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data
docker compose --env-file .env -p prokbot -f host/release/compose.yaml up -d
docker compose --env-file .env -p prokbot -f host/release/compose.yaml exec host cat /data/setup-key
```
-镜像运行架构为 Linux amd64;Apple Silicon Docker 使用转译。Host 与 Linux 桌面可以分开部署,分开时按 `host/docs/DEPLOYMENT.md` 选择对应 Compose。
+第二条命令创建 Linux 桌面要挂载的记忆等目录,只建缺失的;新部署和升级后都要在 `up -d` 之前运行一次,否则 Linux 桌面启动失败。
-打开 Host 管理页,完成管理员初始化,填写用户的模型接口与 Key、选择模型并测试连接。需要 Tailcat 时,在「远程访问」配置并检查连接。
+新部署也可以用 `python3 host/deploy.py` 的 `doctor`、`init`、`up`、`status` 完成同样的步骤,选项见 `--help`;已有部署沿用原来的命令。
+
+Host 镜像按 Docker 所在机器的架构构建(amd64 或 arm64);Linux 桌面镜像只有 amd64,在 ARM 机器上要靠 Docker 转译运行,构建工具会先检查能否运行。Host 与 Linux 桌面可以分开部署,分开时按 `host/docs/DEPLOYMENT.md` 选择对应 Compose。
+
+打开 Host 管理页,完成管理员初始化。在「模型」里先添加模型服务(接口格式、地址、Key),再创建模型档案(服务 + 模型 ID),设置默认路由,逐个测试档案后保存;用户需要时再给单个 Bot 设置主模型、思考强度和备用模型。需要 Tailcat 时,在「远程访问」配置并检查连接。
可通过管理页操作,也可参考 `host/server/index.mjs` 的管理接口;请求格式与会话处理以该版本源码为准:
diff --git a/docs/ARCHITECTURE.en.md b/docs/ARCHITECTURE.en.md
index b419472307c6ce24041020e87f0994d3cedf6643..77a7da17f19f8a540a1c3e14a138751dfc9a4b8f 100644
--- a/docs/ARCHITECTURE.en.md
+++ b/docs/ARCHITECTURE.en.md
@@ -33,7 +33,7 @@ The project ships three patch tools. Together they let you build and run your ow
| --- | --- | --- | --- |
| 🔁 Sign-in | Official account | No account needed. The Host admin page creates a six-character pairing code; enter the Host address and code in the app to connect | — |
| 🔁 Host and execution computer | Official cloud | Runs wherever you deploy it, using the original Host | Any device that can run Docker |
-| 🔁 Chat models | Official models with automatic tier selection | You choose the models. The Jev classifier can pick the model and reasoning effort for each task | An OpenAI-compatible endpoint and API key |
+| 🔁 Chat models | Official models with automatic tier selection | You choose the models. Add several model services and set the model, reasoning effort and backup models for all Bots or for one Bot | A model endpoint and API key: OpenAI Chat Completions, OpenAI Responses or Anthropic Messages |
| 🟢 Computer and browser use | Original Agent | Kept as is | A model with vision |
| 🟢 Memory, context compaction, scheduled tasks | Original Agent, partly backed by official services | Kept, now running on your models with local timers; compaction thresholds are configurable | — |
| 🟢 Approvals, human takeover, input forms | Original | Kept as is | — |
@@ -66,9 +66,14 @@ These original features aren't available yet: virtual cards, external message dr
| **Usage** | See how many tokens you used each day, on the admin page and in the iOS settings. |
| **Prompt management** | Edit system prompts and restore the original at any time, and see exactly which prompts and tools each role received. |
| **Per-model context** | Set each model's context size and when summarization starts. |
+| **Models per Bot** | Each Bot can have its own primary model, reasoning effort and backup models. If the primary fails before any output (quota, rate limit, service error, network), the backups are tried in order. |
+| **Manual compaction** | Summarize an idle Bot's context from the admin page. |
+| **Web client** | The Host can serve a web interface to browsers signed in with a pairing code. The bundle is built from the official Windows installer with the [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.en.md) tools and uploaded on the admin page; nothing changes until one is uploaded. |
| **Admin page** | Configure everything in the browser. It follows the original design and supports Chinese and English, light and dark themes, and phone screens. |
| **Split deployment** | Run the Host and the execution computer on different machines. |
| **Backup and restore** | Back up all data and restore it as a new instance. |
+| **Deploy tool** | `host/deploy.py` checks the environment, initializes, builds and starts, upgrades, backs up and restores, one command each. |
+| **Command-line admin** | `host/tools/host-admin.mjs` sets up the Host, configures models and creates pairing codes without the web page. |
@@ -88,9 +93,13 @@ Around the original Host we wrote an admin service. It handles admin sign-in, de
### Models
-The original sends model requests to an official classifier, which decides which model to use (Grok most of the time). We take over just before the Host sends a request, convert the original message format to the OpenAI-compatible format, and convert the streamed reply back. Tool calls, sub-Agents and context management are still the original logic.
+The original sends model requests to an official classifier, which decides which model to use (Grok most of the time). We take over just before the Host sends a request, convert the original message format to the format you chose on the admin page (OpenAI Chat Completions, OpenAI Responses or Anthropic Messages), and convert the streamed reply back. Tool calls, sub-Agents and context management are still the original logic.
-The original picks a model tier per task, and that decision happens on the official backend. Jev replaces it: it first judges how hard the task is, then hands it to the model for that tier.
+When a provider rejects an optional parameter, the request is retried without it. Messages a Bot sends during one model response are delivered in the order the model wrote them.
+
+The original picks a model tier per task, and that decision happens on the official backend. Here you set it on the admin page instead: add model services (API format, address, key), then model profiles (a service plus a model ID). The default route applies to every Bot; a Bot can have its own primary model, reasoning effort and up to 8 backup models tried in order, and sub-Agents use their parent Bot's route. If the primary fails with 402, 408, 429, 5xx, a network error or an upstream idle timeout before it has produced any text or tool call, the next backup is tried; once output has started, the model is never switched, so replies and tool runs are not repeated.
+
+A configuration that used Jev to pick models by task difficulty keeps working after the upgrade; saving it from the new model page shows a notice and asks for confirmation before migrating it to per-Bot routes. A legacy single-model configuration that sets both a context size and a summary threshold now compacts automatically at that threshold. An idle Bot's context can also be compacted by hand on the admin page.
### Execution computer
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index c3317cbbd60c04b39aa757ff9f0428682945af89..9af8e0c0c03cba5ebe07eae09ea56dd5ebfc9def 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -33,7 +33,7 @@ flowchart LR
| --- | --- | --- | --- |
| 🔁 登录 | 官方账号 | 不需要账号。Host 管理页生成六位配对码,客户端输入 Host 地址和配对码即可连接 | — |
| 🔁 Host 和执行电脑 | 官方云端 | 运行在你部署的位置,使用原版 Host | 一台能运行 Docker 的任意设备 |
-| 🔁 对话模型 | 官方模型,自动选择等级 | 自行决定模型。可以让 Jev 分类器自动选择使用的模型和思考强度 | OpenAI 兼容接口的地址和 API Key |
+| 🔁 对话模型 | 官方模型,自动选择等级 | 自行决定模型。可添加多个模型服务,给所有 Bot 或单个 Bot 指定模型、思考强度和备用模型 | 模型接口的地址和 API Key,支持 OpenAI Chat Completions、OpenAI Responses、Anthropic Messages |
| 🟢 电脑和浏览器操作 | 原版 Agent | 保留原版 | 支持视觉能力的模型 |
| 🟢 记忆、上下文压缩、定时任务 | 原版 Agent,部分依赖官方服务 | 保留原版,改用你的模型和本地计时,上下文压缩可自行设置 | — |
| 🟢 操作审批、人工接管、交互表单 | 原版 | 保留原版 | — |
@@ -66,9 +66,14 @@ flowchart LR
| **用量统计** | 每天用了多少 Token,在管理页和 iOS 设置里都能看到。 |
| **提示词管理** | 可以修改系统提示词并随时恢复原版,还能看到每个角色实际收到的提示词和工具。 |
| **按模型设置上下文** | 每个模型的容量和开始摘要的时机可以单独设置。 |
+| **按 Bot 选模型** | 每个 Bot 可以有自己的主模型、思考强度和备用模型。主模型还没输出时出错(额度、限流、服务故障、网络),按顺序换备用模型。 |
+| **手动压缩上下文** | 在管理页把空闲 Bot 的上下文压缩成摘要。 |
+| **网页版** | Host 可以向用配对码登录的浏览器提供网页版界面。界面包用 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.md) 的工具从官方 Windows 安装包生成,再在管理页上传;不上传就没有变化。 |
| **管理网页** | 所有设置都在浏览器里完成,沿用原版的设计风格,支持中英文、深浅色和手机屏幕。 |
| **分开部署** | Host 和执行电脑可以放在不同的机器上。 |
| **备份恢复** | 备份全部数据,恢复成一个新的实例。 |
+| **部署工具** | `host/deploy.py` 用一个命令完成环境检查、初始化、构建启动、升级、备份和恢复。 |
+| **命令行管理** | `host/tools/host-admin.mjs` 不打开网页也能初始化、配置模型、生成配对码。 |
@@ -88,9 +93,13 @@ flowchart LR
### 模型
-原版的模型请求发给官方分类器,由官方决定用哪个模型(大部分时间是 Grok)。我们在 Host 发出请求前接手,把原版的消息格式转换成 OpenAI 兼容格式,再把模型的流式回复转换回来。工具调用、子 Agent 和上下文管理仍然是原版逻辑。
+原版的模型请求发给官方分类器,由官方决定用哪个模型(大部分时间是 Grok)。我们在 Host 发出请求前接手,把原版的消息格式转换成你在管理页选择的格式(OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages),再把模型的流式回复转换回来。工具调用、子 Agent 和上下文管理仍然是原版逻辑。
-原版会按任务自动选择模型等级,这一步原本在官方后端完成。我们使用 Jev 来代替:先判断任务难度,再交给对应等级的模型。
+服务商不支持某个可选参数时,会去掉它再试一次。Bot 在一次模型回复里发出的几条消息,按模型写的顺序送达。
+
+原版会按任务自动选择模型等级,这一步原本在官方后端完成。这里改成在管理页指定:先添加模型服务(接口格式、地址、Key),再创建模型档案(服务 + 模型 ID);默认路由用于所有 Bot,单个 Bot 可以另设主模型、思考强度和最多 8 个按顺序尝试的备用模型,子 Agent 沿用父 Bot 的路由。主模型还没输出文字或工具调用时,402、408、429、5xx、网络错误和上游空闲超时会换下一个备用模型;已经输出后不再切换,避免重复回复或重复执行工具。
+
+之前用 Jev 按任务难度选择模型的配置升级后照常工作;在新的模型页保存时会先提示并确认,再迁移成按 Bot 路由。旧的单模型配置如果同时设置了上下文容量和摘要阈值,升级后会按这个阈值自动压缩。空闲的 Bot 也可以在管理页手动压缩上下文。
### 执行电脑
diff --git a/docs/INSTALL.en.md b/docs/INSTALL.en.md
index 0792d5dc74dba9faa321e87bc841d3eb05d482dc..c844ac45e01db5669b17880238244a2ef4e23f8c 100644
--- a/docs/INSTALL.en.md
+++ b/docs/INSTALL.en.md
@@ -4,12 +4,13 @@
## 1. Deploy the Host
-Requires Python 3.10+ and Docker Compose. The runtime is Linux amd64; Apple Silicon Macs use emulation.
+Requires Python 3.10+, Docker Engine 26.0+ and Docker Compose 2.26.0+. The runtime is Linux amd64; Apple Silicon Macs use emulation.
-From `host/` in the repository or extracted patch archive:
+From `host/` in the repository or extracted patch archive (the second command creates the directories the Linux desktop mounts; run it again after upgrades):
```sh
python3 release/build-docker.py
+docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data
docker compose -f release/compose.yaml up -d
docker compose -f release/compose.yaml exec host cat /data/setup-key
```
@@ -20,7 +21,7 @@ Open `http://127.0.0.1:18080` and create an administrator account with the setup
| App | Original input | Instructions |
| --- | --- | --- |
-| Mac | Automatically downloads Grok Bot 0.71.2 for Apple Silicon | [Patch the app](../mac/README.en.md) and move it into Applications |
+| Mac | Automatically downloads Grok Bot 0.71.2 for the Mac's chip (Apple Silicon; Intel is experimental) | [Patch the app](../mac/README.en.md) and move it into Applications |
| iOS | Decrypted Grok Bot 1.16.0 (23152), arm64 IPA including all three decrypted extensions | [Patch the IPA](../ios/README.en.md), then sign and install it |
Open the app and enter the Host address and six-character pairing code.
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index ba8d18049b519358447015cf22721ec7469c99c5..47b3abbca015b7563dd8b11252ee66a45692d28b 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -4,12 +4,13 @@
## 1. 部署 Host
-需要 Python 3.10+、Docker Compose,运行 Linux amd64 镜像。Apple Silicon Mac 使用转译运行。
+需要 Python 3.10+、Docker Engine 26.0+ 和 Docker Compose 2.26.0+,运行 Linux amd64 镜像。Apple Silicon Mac 使用转译运行。
-进入仓库或解压后的 `host/` 目录:
+进入仓库或解压后的 `host/` 目录(第二条命令创建 Linux 桌面要挂载的目录,升级后也要再运行一次):
```sh
python3 release/build-docker.py
+docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data
docker compose -f release/compose.yaml up -d
docker compose -f release/compose.yaml exec host cat /data/setup-key
```
@@ -20,7 +21,7 @@ docker compose -f release/compose.yaml exec host cat /data/setup-key
| 客户端 | 原文件 | 操作 |
| --- | --- | --- |
-| Mac | 工具自动下载 Grok Bot 0.71.2 Apple Silicon 原版 | 按 [Mac 说明](../mac/README.md)生成 App,移入「应用程序」 |
+| Mac | 工具按本机芯片自动下载 Grok Bot 0.71.2 原版(Apple Silicon;Intel 为实验支持) | 按 [Mac 说明](../mac/README.md)生成 App,移入「应用程序」 |
| iOS | Grok Bot 1.16.0(23152)arm64 砸壳 IPA,主应用及三个扩展均已解密 | 按 [iOS 说明](../ios/README.md)生成 IPA,自行签名安装 |
打开客户端,填写 Host 地址和六位配对码。
diff --git a/host/.dockerignore b/host/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..d7873fa4c018adf808b99373d4e5c4ad05d8bc06
--- /dev/null
+++ b/host/.dockerignore
@@ -0,0 +1,9 @@
+**/__pycache__/
+**/.cache/
+**/node_modules/
+**/output/
+**/inputs/
+**/backups/
+**/secrets/
+**/.env*
+tests/
diff --git a/host/README.en.md b/host/README.en.md
index 90bbbc958d78e4f5d13aa941d88f5a12b47313f5..60a71e92d4f8e4e20df737a3ab4fd3caad03ab8e 100644
--- a/host/README.en.md
+++ b/host/README.en.md
@@ -1,6 +1,6 @@
# ProkBot Host Patch
-Self-host the Grok Bot server. Requires Python 3.10+ and Docker Compose; the runtime uses Linux amd64.
+Self-host the Grok Bot server. Requires Python 3.10+, Docker Engine 26.0+ and Docker Compose 2.26.0+ (Ubuntu 24.04's own packages are enough). The Host image is built for the Docker machine's architecture (amd64 or arm64); the Linux desktop image is amd64.
[简体中文](README.md)
@@ -8,14 +8,37 @@ Self-host the Grok Bot server. Requires Python 3.10+ and Docker Compose; the run
```sh
python3 release/build-docker.py
+docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data
docker compose -f release/compose.yaml up -d
docker compose -f release/compose.yaml exec host cat /data/setup-key
```
Open `http://127.0.0.1:18080`, use the setup code to create an administrator account, configure a model and create a six-character pairing code.
+The second command creates the memory and other directories the Linux desktop mounts from the data volume. It creates only missing ones and can be run again; without it the Linux desktop fails to start because a mount directory is missing. `deploy.py` does this step automatically.
+
For LAN access, run `export GROKBOT_LISTEN_ADDRESS=0.0.0.0` before starting Compose.
+### Deploy tool
+
+`deploy.py` wraps the steps above, plus upgrades, backups and recovery, as subcommands. Instance settings (`.env` and backups) live in `~/grokbot` by default:
+
+```sh
+python3 deploy.py doctor # check Docker, Compose, architecture and whether the Linux desktop can run
+python3 deploy.py init # create .env; never overwrites an existing deployment
+python3 deploy.py up # build and start a new deployment
+python3 deploy.py status
+python3 deploy.py setup-key # show the setup code
+```
+
+Use `update` to upgrade (it builds the new image first, then stops the old services, backs up and switches), `backup` to back up and `recover` to restore a backup as a new project. For a separate Host and Linux desktop, put `--host-only` before the subcommand. See `python3 deploy.py --help` for other options.
+
+`tools/host-admin.mjs` sets up the Host, configures models (all three API formats) and creates pairing codes from the command line; see `node tools/host-admin.mjs --help`.
+
+The admin page's Web client section accepts a web interface bundle; browsers can then sign in with a pairing code. The bundle is built from the official Windows installer with the [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.en.md) tools; nothing changes until one is uploaded.
+
+Tests: `node --test "tests/*.test.mjs"`. The web client route test needs `npm ci --prefix server --omit=dev --ignore-scripts` first; otherwise it is skipped.
+
[Remote access, separate deployment and backups](docs/DEPLOYMENT.en.md) · [Application development](PLUGINS.en.md)
## License and support
diff --git a/host/README.md b/host/README.md
index 436fb7298394807fe2edae321b2157ad1457d3e4..5747ee6c7e897bf6993313b486a5fd6917924a95 100644
--- a/host/README.md
+++ b/host/README.md
@@ -1,6 +1,6 @@
# ProkBot Host Patch
-自建 Grok Bot 服务端。需要 Python 3.10+、Docker Compose,运行架构为 Linux amd64。
+自建 Grok Bot 服务端。需要 Python 3.10+、Docker Engine 26.0+ 和 Docker Compose 2.26.0+(Ubuntu 24.04 系统仓库的版本就够)。Host 镜像按 Docker 所在机器的架构构建(amd64 或 arm64),Linux 桌面镜像为 amd64。
[English](README.en.md)
@@ -8,14 +8,37 @@
```sh
python3 release/build-docker.py
+docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data
docker compose -f release/compose.yaml up -d
docker compose -f release/compose.yaml exec host cat /data/setup-key
```
打开 `http://127.0.0.1:18080`,用初始化码设置管理员账号,配置模型并生成六位配对码。
+第二条命令在数据卷里创建 Linux 桌面要挂载的记忆等目录,只建缺失的,可以重复运行;不运行时 Linux 桌面会因为挂载目录不存在而启动失败。`deploy.py` 会自动做这一步。
+
需要局域网访问时,先设置 `export GROKBOT_LISTEN_ADDRESS=0.0.0.0`,再运行 Compose。
+### 部署工具
+
+`deploy.py` 把上面的步骤以及升级、备份、恢复做成了子命令,实例配置(`.env` 和备份)默认放在 `~/grokbot`:
+
+```sh
+python3 deploy.py doctor # 检查 Docker、Compose、架构,以及 Linux 桌面能否运行
+python3 deploy.py init # 生成 .env,不覆盖已有部署
+python3 deploy.py up # 构建并启动新部署
+python3 deploy.py status
+python3 deploy.py setup-key # 显示初始化码
+```
+
+升级用 `update`(先构建新镜像,再停止旧服务、备份并切换),备份用 `backup`,从备份恢复成新项目用 `recover`。Host 和 Linux 桌面分开部署时,在子命令前加 `--host-only`。其他选项见 `python3 deploy.py --help`。
+
+`tools/host-admin.mjs` 可以在命令行初始化、配置模型(三种接口格式)和生成配对码,见 `node tools/host-admin.mjs --help`。
+
+管理页的「网页版」可以上传网页版界面包,浏览器用配对码登录后就能使用。界面包用 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.md) 的工具从官方 Windows 安装包生成;不上传就没有变化。
+
+运行测试:`node --test "tests/*.test.mjs"`。网页版路由测试需要先执行 `npm ci --prefix server --omit=dev --ignore-scripts`,否则跳过。
+
[远程访问、分开部署与备份](docs/DEPLOYMENT.md) · [应用开发](PLUGINS.md)
## 许可与支持
diff --git a/host/bin/linux-arm64/grokbot-tailcat b/host/bin/linux-arm64/grokbot-tailcat
new file mode 100755
index 0000000000000000000000000000000000000000..1a27779811640a4f185afd9bedc78d93e75de442
Binary files /dev/null and b/host/bin/linux-arm64/grokbot-tailcat differ
diff --git a/host/deploy.py b/host/deploy.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee578bb62ed0873fc92de6ecd9dab76d8936f80c
--- /dev/null
+++ b/host/deploy.py
@@ -0,0 +1,574 @@
+#!/usr/bin/env python3
+"""Operate one local ProkBot Compose project, from a checkout or the Host release package."""
+import argparse
+from contextlib import contextmanager
+from datetime import datetime, timezone
+import ipaddress
+import json
+import os
+from pathlib import Path
+import posixpath
+import re
+import shutil
+import subprocess
+import sys
+from urllib.parse import urlsplit
+from uuid import uuid4
+
+RELEASE = Path(__file__).resolve().parent / 'release'
+MIN_DOCKER_ENGINE = (26, 0, 0)
+MIN_DOCKER_API = (1, 45, 0)
+MIN_COMPOSE = (2, 26, 0)
+sys.path.insert(0, str(RELEASE))
+from platforms import BOX, check_box_execution, docker_platform
+import backup as volume_backup
+
+
+def run(cmd, *, env=None, capture=False):
+ return subprocess.run(cmd, env=env, stdin=subprocess.DEVNULL, check=True, text=True,
+ stdout=subprocess.PIPE if capture else None)
+
+
+def endpoint(value):
+ url = urlsplit(value)
+ if (url.scheme not in ('https', 'http') or not url.hostname or url.username is not None or
+ url.password is not None or url.path not in ('', '/') or url.query or url.fragment or
+ not re.fullmatch(r'https?://[a-zA-Z0-9.\[\]:-]+/?', value) or url.port == 0):
+ raise ValueError('Public URL must be an HTTP(S) origin without credentials, a path, query or fragment.')
+ return value.rstrip('/')
+
+
+def initialise(home, args):
+ if not 1 <= args.port <= 65535:
+ raise ValueError('Port must be 1..65535')
+ listen = str(ipaddress.ip_address(args.listen))
+ if not args.public_url and listen != '127.0.0.1':
+ raise ValueError('Set --public-url to the address clients will actually enter.')
+ origin = endpoint(args.public_url or f'http://127.0.0.1:{args.port}')
+ if ':' in listen:
+ listen = f'[{listen}]'
+ # Only the local Box uses subpath mounts; a Host-only instance keeps working on older Docker.
+ if not args.host_only:
+ check_runtime_versions()
+ home.mkdir(mode=0o700, parents=True, exist_ok=True)
+ try:
+ fd = os.open(home / '.env', os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ except FileExistsError:
+ raise ValueError('Configuration already exists; init never overwrites it. Use status or update.') from None
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as config:
+ config.write(f'GROKBOT_LISTEN_ADDRESS={listen}\nGROKBOT_PUBLIC_PORT={args.port}\nGROKBOT_PUBLIC_URL={origin}\n'
+ f'PROKBOT_MODE={"remote" if args.host_only else "local"}\nPROKBOT_PROJECT={args.project}\n')
+ print(json.dumps({'configCreated': True, 'publicUrl': origin}))
+
+
+def compose(args, home):
+ if not (home / '.env').is_file():
+ raise ValueError('No .env in the instance directory. Run init first or select --home.')
+ name = 'compose.host.yaml' if args.host_only else 'compose.yaml'
+ return ['docker', 'compose', '--env-file', str(home / '.env'), '-p', args.project, '-f', str(RELEASE / name)]
+
+
+def instance_settings(args, home):
+ # Only read the two markers written by init. Docker Compose interprets all other .env fields.
+ path = home / '.env'
+ markers = {}
+ if path.is_file():
+ for line in path.read_text(encoding='utf-8').splitlines():
+ key, _, value = line.partition('=')
+ if key in ('PROKBOT_MODE', 'PROKBOT_PROJECT'):
+ markers[key] = value.strip()
+ mode = markers.get('PROKBOT_MODE')
+ if mode not in (None, 'remote', 'local') or (mode == 'local' and args.host_only):
+ raise ValueError('Instance mode conflicts with its .env; do not switch topologies during an update.')
+ args.host_only = args.host_only or mode == 'remote'
+ saved = markers.get('PROKBOT_PROJECT')
+ if saved and args.project and saved != args.project:
+ raise ValueError('Project name conflicts with the instance .env; check --home and --project.')
+ args.project = args.project or saved or 'grokbot'
+ if not volume_backup.PROJECT_NAME.fullmatch(args.project):
+ raise ValueError('Invalid Compose project name')
+
+
+def daemon_resources():
+ info = json.loads(run(['docker', 'info', '--format', '{{json .}}'], capture=True).stdout)
+ report = {'cpuCount': info.get('NCPU'), 'memoryBytes': info.get('MemTotal')}
+ # Disk usage is local-only; a remote Docker context may use the same path on a different machine.
+ endpoint = os.environ.get('DOCKER_HOST') or run(['docker', 'context', 'inspect', '--format', '{{.Endpoints.docker.Host}}'], capture=True).stdout.strip()
+ root = info.get('DockerRootDir')
+ if root and endpoint.startswith('unix://') and sys.platform.startswith('linux'):
+ try:
+ report['dockerDiskFreeBytes'] = shutil.disk_usage(root).free
+ except OSError:
+ pass
+ return report
+
+
+def backup(args, home, image, *, stopped=False):
+ stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
+ dest = home / 'backups' / f'{args.project}-{stamp}'
+ volume_backup.backup(args.project, dest, image, stopped=stopped)
+ return dest
+
+
+def volume_policy(existing, images=None):
+ # Explicit process environment takes precedence over a stale setting in an instance .env.
+ env = {**os.environ, 'PROKBOT_EXISTING_VOLUMES': 'true' if existing else 'false'}
+ for service, ref in (images or {}).items():
+ env['GROKBOT_'+service.upper()+'_IMAGE'] = ref
+ return env
+
+
+def compose_mounts(service, definition):
+ # These settings can introduce mounts not listed in service.volumes.
+ for key in ('volumes_from', 'configs', 'secrets', 'use_api_socket'):
+ if definition.get(key):
+ raise ValueError(f'Effective Compose {service}.{key} introduces unmanaged mounts.')
+ mounts = list(definition.get('volumes', []))
+ tmpfs = definition.get('tmpfs', [])
+ if isinstance(tmpfs, str):
+ tmpfs = [tmpfs]
+ mounts.extend({'type': 'tmpfs', 'target': item.partition(':')[0]} for item in tmpfs)
+
+ roots = set(volume_backup.MOUNTS[service].values())
+ data_targets = set(volume_backup.BOX_DATA_TARGETS) if service == 'box' else set()
+ allowed = roots | data_targets
+ by_target = {}
+ for mount in mounts:
+ target = mount.get('target')
+ if not isinstance(target, str) or not target.startswith('/'):
+ raise ValueError(f'Effective Compose mount on {service} needs an absolute container target.')
+ dest = posixpath.normpath('/' + target.lstrip('/'))
+ if dest in by_target:
+ raise ValueError(f'Duplicate effective Compose mount on {service} at {dest}.')
+ if dest not in allowed and (mount.get('type') != 'tmpfs' or
+ any(posixpath.commonpath((root, dest)) in (root, dest) for root in allowed)):
+ raise ValueError(f'Unmanaged mount on {service} at {dest} would be omitted from the backup.')
+ by_target[dest] = mount
+ return by_target
+
+
+def instance_images(dc, project, services, existing, pinned=None):
+ config = json.loads(run(dc + ['config', '--format', 'json'], env=volume_policy(existing, pinned), capture=True).stdout)
+ if set(config['services']) != set(services):
+ raise ValueError('Effective Compose services do not match the selected topology.')
+ for s in services:
+ mounts = compose_mounts(s, config['services'][s])
+ for suffix, dest in volume_backup.MOUNTS[s].items():
+ mount = mounts.get(dest, {})
+ volume = config.get('volumes', {}).get(suffix, {})
+ if (volume.get('name') != project+'_'+suffix or volume.get('external', False) is not existing or
+ mount.get('type') != 'volume' or mount.get('source') != suffix or
+ mount.get('target') != dest or mount.get('read_only') or (mount.get('volume') or {}).get('subpath')):
+ raise ValueError(f'Effective Compose mount {s}:{dest} does not select the root of the expected writable project volume.')
+ if s == 'box':
+ for target, tree in volume_backup.BOX_DATA_TARGETS.items():
+ mount = mounts.get(target, {})
+ subpath = (mount.get('volume') or {}).get('subpath')
+ if (mount.get('type') != 'volume' or mount.get('source') != 'host-data' or
+ mount.get('target') != target or mount.get('read_only') or
+ subpath != str(volume_backup.DATA_SOURCE_ROOT / tree)):
+ raise ValueError(f'Effective Compose mount box:{target} does not select the approved Host-data tree.')
+ images = {s: config['services'][s]['image'] for s in services}
+ if pinned is not None and images != pinned:
+ raise ValueError('Effective Compose configuration did not select the requested immutable images.')
+ if pinned is None and 'box' in images and images['box'] != BOX['localTag']:
+ raise ValueError('This deployment entry point only starts the verified desktop tag from the input manifest.')
+ return images
+
+
+def build(args, image):
+ cmd = [sys.executable, str(RELEASE / 'build-docker.py'), '--image', image]
+ if args.host_only:
+ cmd.append('--host-only')
+ for flag, path in [('host-archive', args.host_archive), ('box-archive', args.box_archive)]:
+ if path is not None:
+ cmd.extend(['--' + flag, str(path.resolve(strict=True))])
+ run(cmd)
+
+
+def inventory(project, services, *, new):
+ volumes = volume_backup.project_volumes(project)
+ expected = {f'{project}_{suffix}' for s in services for suffix in volume_backup.MOUNTS[s]}
+ if new:
+ named = set(volume_backup.output('volume', 'ls', '-q').splitlines())
+ if volumes or expected & named or volume_backup.project_ids(project):
+ raise ValueError('Instance or conflicting volume exists. Check the project and use update for an existing instance.')
+ return {}
+ if volumes != expected:
+ raise ValueError('Volume set does not match this topology; check the original project, --home and --host-only.')
+ volume_backup.verify_volumes(project, volumes)
+ containers = volume_backup.project_services(project, services, host_data=f'{project}_host-data' in volumes)
+ volume_backup.verify_users(volumes, containers)
+ return containers
+
+
+def image_id(ref):
+ identity = run(['docker', 'image', 'inspect', '--format', '{{.Id}}', ref], capture=True).stdout.strip()
+ if not re.fullmatch(r'sha256:[0-9a-f]{64}', identity):
+ raise ValueError('Docker did not return a usable local image identity.')
+ return identity
+
+
+def startup_images(services, host_id):
+ images = {'host': host_id}
+ if 'box' in services:
+ box = image_id(BOX['localTag'])
+ if box not in (BOX['manifestDigest'], BOX['configDigest']):
+ raise ValueError('Local desktop image does not match the pinned desktop digest.')
+ images['box'] = box
+ return images
+
+
+def version_tuple(value, label):
+ # Distribution builds add suffixes, e.g. Ubuntu's Compose reports 2.40.3+ds1-0ubuntu1~24.04.1.
+ match = re.match(r'v?(\d+)\.(\d+)(?:\.(\d+))?(?![\d.])', value)
+ if not match:
+ raise ValueError(f'Docker did not report a usable {label} version.')
+ return tuple(int(part or 0) for part in match.groups())
+
+
+def require_version(actual, minimum, label):
+ if actual < minimum:
+ found = '.'.join(map(str, actual))
+ required = '.'.join(map(str, minimum))
+ raise ValueError(f'{label} {found} is too old; version {required} or newer is required for Host-data subpath mounts.')
+
+
+def compose_version():
+ version = run(['docker', 'compose', 'version', '--short'], capture=True).stdout.strip()
+ # Compose labels its own volumes with the plain number, which backup lineage checks expect.
+ return '.'.join(map(str, version_tuple(version, 'Compose')))
+
+
+def check_runtime_versions():
+ try:
+ server = json.loads(run(['docker', 'version', '--format', '{{json .Server}}'], capture=True).stdout)
+ except json.JSONDecodeError as error:
+ raise ValueError('Docker did not report usable Engine version details.') from error
+ if not isinstance(server, dict):
+ raise ValueError('Docker Engine is unavailable; start it before configuring Host data mounts.')
+ engine = server.get('Version')
+ api = server.get('ApiVersion')
+ if not isinstance(engine, str) or not isinstance(api, str):
+ raise ValueError('Docker did not report both Engine and API versions.')
+ engine_version = version_tuple(engine, 'Engine')
+ api_version = version_tuple(api, 'API')
+ compose = compose_version()
+ compose_number = version_tuple(compose, 'Compose')
+ require_version(engine_version, MIN_DOCKER_ENGINE, 'Docker Engine')
+ require_version(api_version, MIN_DOCKER_API, 'Docker API')
+ require_version(compose_number, MIN_COMPOSE, 'Docker Compose')
+ return {'dockerEngineVersion': engine, 'dockerApiVersion': api, 'composeVersion': compose}
+
+
+def ensure_host_data(project, image):
+ name = project+'_host-data'
+ if name not in set(volume_backup.output('volume', 'ls', '-q').splitlines()):
+ run(['docker', 'volume', 'create',
+ '--label', f'{volume_backup.PROJECT_LABEL}={project}',
+ '--label', f'{volume_backup.VOLUME_LABEL}=host-data',
+ '--label', f'{volume_backup.VERSION_LABEL}={compose_version()}',
+ name], capture=True)
+ labels = volume_backup.volume_labels(name)
+ if labels.get(volume_backup.PROJECT_LABEL) != project or labels.get(volume_backup.VOLUME_LABEL) != 'host-data':
+ raise ValueError('The Host data volume does not belong to the selected project.')
+ run(['docker', 'run', '--rm', '--pull=never', '--network', 'none', '--read-only', '--user', '0:0',
+ '--entrypoint', 'python3', '--mount', f'type=volume,src={name},dst=/data,volume-nocopy', image,
+ '/opt/grokbot/release/data_init.py', '/data/runtime/host-data'])
+
+
+def up_and_wait(dc, project, services, images, *, existing):
+ instance_images(dc, project, services, existing, pinned=images)
+ if 'box' in services:
+ ensure_host_data(project, images['host'])
+ run(dc + ['up', '-d', '--pull', 'never', '--wait', '--wait-timeout', '180'], env=volume_policy(existing, images))
+ current = inventory(project, services, new=False)
+ if (set(current) != set(services) or any(c['State']['Status'] != 'running' for c in current.values()) or
+ any(current[s]['Image'] != images[s] for s in services)):
+ raise ValueError('Compose finished but the running services do not match the verified deployment.')
+
+
+def stop_failed_start(dc, project, services, existing, notice, error):
+ try:
+ run(dc + ['stop'], env=volume_policy(existing))
+ current = volume_backup.project_services(project, services)
+ if any(c['State']['Status'] not in ('exited', 'created') for c in current.values()):
+ raise ValueError('some services remain active')
+ except (OSError, ValueError, subprocess.SubprocessError) as stop_error:
+ raise RuntimeError(notice + ' Service shutdown NOT confirmed: ' + str(stop_error)) from error
+ raise RuntimeError(notice + ' Project services are stopped. Cause: ' + str(error)) from error
+
+
+def tag_state(tag):
+ if (not re.fullmatch(r'[a-z0-9][a-z0-9._:/-]*(?::[\w.-]+)?', tag, re.ASCII) or '@' in tag or
+ re.fullmatch(r'(?:sha256:)?[0-9a-f]{64}', tag)):
+ raise ValueError('Configured Host build target must be a local tag, not an ID, digest or pattern.')
+ if ':' not in tag.rsplit('/', 1)[-1]:
+ tag += ':latest'
+ # A successful, empty tag inventory means absent. Any inspect/daemon error is a hard failure.
+ rows = run(['docker', 'image', 'ls', '--no-trunc', '--format', '{{.ID}}', tag], capture=True).stdout.splitlines()
+ if not rows:
+ return None
+ if len(rows) != 1 or not re.fullmatch(r'sha256:[0-9a-f]{64}', rows[0]) or image_id(tag) != rows[0]:
+ raise ValueError('Host tag inventory changed or is ambiguous; refusing to switch.')
+ return rows[0]
+
+
+def revert_tag(previous, candidate, tag):
+ try:
+ actual = tag_state(tag)
+ if actual == previous:
+ return
+ if actual != candidate:
+ raise ValueError('another image owns this tag; it was not modified')
+ try:
+ if previous is None:
+ run(['docker', 'image', 'rm', '--no-prune', tag])
+ else:
+ run(['docker', 'image', 'tag', previous, tag])
+ except (OSError, subprocess.SubprocessError):
+ pass # The acknowledgement can be lost after the operation succeeds.
+ if tag_state(tag) != previous:
+ raise ValueError('previous tag state could not be verified')
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
+ raise RuntimeError('Host tag rollback NOT confirmed; inspect local image metadata before retrying.') from error
+
+
+def publish_image(previous, candidate, tag):
+ if tag_state(tag) != previous:
+ raise ValueError('Configured Host tag changed since preflight; refusing to replace it.')
+ try:
+ run(['docker', 'image', 'tag', candidate, tag])
+ if tag_state(tag) != candidate:
+ raise ValueError('Candidate tag was not installed.')
+ except (Exception, KeyboardInterrupt):
+ revert_tag(previous, candidate, tag)
+ raise
+
+
+@contextmanager
+def staged_host(args, services):
+ candidate = 'prokbot-upgrade:' + uuid4().hex
+ build(args, candidate)
+ try:
+ check_platform(candidate)
+ yield startup_images(services, image_id(candidate))
+ finally:
+ try:
+ run(['docker', 'image', 'rm', '--no-prune', candidate], capture=True)
+ except (OSError, subprocess.SubprocessError):
+ print('Could not remove temporary image tag: '+candidate, file=sys.stderr)
+
+
+def upgrade(args, home, dc, services, image, old, root, continuing):
+ def state(containers):
+ return {s: (c['Id'], c['Image'], c['State']['Status']) for s, c in containers.items()}
+
+ if any(c['State']['Status'] == 'paused' for c in old.values()):
+ raise ValueError('A project service is paused; resolve its state before upgrading.')
+ if set(old) != set(services):
+ raise ValueError('Missing original service container; cannot establish previous image identities from volume-only data. Use recover with a matching backup.')
+ previous = old['host']['Image']
+ public_before = tag_state(image)
+ if image_id(previous) != previous:
+ raise ValueError('Previous Host image identity is unavailable; refusing to switch.')
+ with staged_host(args, services) as images:
+ candidate_id = images['host']
+ current = inventory(args.project, services, new=False)
+ if state(current) != state(old) or instance_images(dc, args.project, services, True)['host'] != image:
+ raise ValueError('The instance changed during the build; no service was switched.')
+ offline_only = volume_backup.check_lineage(root, args.project, continuing=continuing)
+ if offline_only:
+ print('An unknown detached Host copy exists: automatic recovery is blocked on this daemon. '
+ 'If the candidate fails after takeover, use data-only restore into new offline volumes.',
+ file=sys.stderr, flush=True)
+ running = [old[s]['Id'] for s in services if s in old and old[s]['State']['Status'] == 'running']
+ try:
+ for cid in running: # Stop Host first so no new desktop work is dispatched.
+ run(['docker', 'stop', cid])
+ dest = backup(args, home, previous, stopped=True)
+ # Keep the old image locally addressable after Compose removes its last container.
+ recovery_image = f'prokbot-recovery:{args.project}-{previous[7:]}'
+ run(['docker', 'image', 'tag', previous, recovery_image])
+ offline_only = volume_backup.check_lineage(root, args.project, continuing=continuing)
+ publish_image(public_before, candidate_id, image)
+ except (Exception, KeyboardInterrupt):
+ # Before Compose up, only the original containers have touched the data.
+ # A manual peer start during the snapshot must not trigger a second identity on rollback.
+ volume_backup.check_lineage(root, args.project, continuing=continuing)
+ failed = []
+ for cid in reversed(running):
+ try:
+ run(['docker', 'start', cid])
+ except (OSError, subprocess.SubprocessError):
+ failed.append(cid)
+ if failed:
+ raise RuntimeError('Could not resume original containers; inspect their status: '+', '.join(failed))
+ raise
+ try:
+ up_and_wait(dc, args.project, services, images, existing=True)
+ except (Exception, KeyboardInterrupt) as error:
+ # A candidate may already have migrated data. Never restart the old image on those volumes.
+ action = (f'An unknown detached Host copy exists; automatic recovery is blocked on this daemon. '
+ f'Use data-only restore from {dest} into new offline volumes. Do not start those volumes '
+ 'until conflicting identities are resolved.' if offline_only else
+ f'Run recover --directory {dest} for a NEW project.')
+ notice = f'Upgrade failed. No automatic data rollback. {action} Previous Host: {recovery_image} ({previous}).'
+ try:
+ stop_failed_start(dc, args.project, services, True, notice, error)
+ finally:
+ revert_tag(public_before, candidate_id, image)
+
+
+def check_platform(image):
+ actual = run(['docker', 'image', 'inspect', '--format', '{{.Os}}/{{.Architecture}}', image], capture=True).stdout.strip()
+ if actual != docker_platform():
+ raise ValueError('Host image platform does not match the Docker server; refusing to start.')
+
+
+def recover(args, home, dc, services):
+ source = args.directory.expanduser().resolve(strict=True)
+ manifest = volume_backup.read_manifest(source)
+ origin = manifest['project']
+ if args.project == origin:
+ raise ValueError('Recovery requires a NEW project, never the source project.')
+ images = manifest.get('serviceImages')
+ if (not isinstance(images, dict) or set(images) != set(services) or
+ any(not isinstance(i, str) or not re.fullmatch(r'sha256:[0-9a-f]{64}', i) for i in images.values())):
+ # Backups from backup.py or an older deploy.py record no image IDs. Starting them would mean
+ # guessing which image wrote the data, so they get the data-only path with its exact command.
+ raise ValueError('Backup has no verified service image IDs for this topology, so it cannot be started '
+ 'automatically; do not guess tags. Use data-only restore: python3 release/backup.py restore '
+ f'--project --directory {source} --image , '
+ 'then start that project only after confirming no other copy of this Host identity runs.')
+ suffixes = {n for s in services for n in volume_backup.MOUNTS[s]}
+ if {r.get('suffix') for r in manifest['volumes'] if isinstance(r, dict)} != suffixes:
+ raise ValueError('Backup volumes do not match the selected recovery topology.')
+ if any(image_id(i) != i for i in images.values()):
+ raise ValueError('One of the exact recovery images is unavailable locally.')
+ check_platform(images['host'])
+ instance_images(dc, args.project, services, True, pinned=images)
+ root = manifest.get('lineageRoot')
+ with volume_backup.project_lock(origin), volume_backup.lineage_lock(root):
+ volume_backup.check_lineage(root, args.project, original=origin)
+ inventory(args.project, services, new=True)
+ volume_backup.restore(source, args.project, images['host'], manifest=manifest)
+ volume_backup.check_lineage(root, args.project, original=origin)
+ inventory(args.project, services, new=False)
+ try:
+ up_and_wait(dc, args.project, services, images, existing=True)
+ except (Exception, KeyboardInterrupt) as error:
+ stop_failed_start(dc, args.project, services, True, 'Recovery start failed. Restored volumes retained; source unchanged.', error)
+ print(json.dumps({'recoveredProject': args.project, 'sourceProject': origin, 'serviceImages': images, 'servicesStarted': True}))
+
+
+def operate(args, home, dc):
+ services = ('host',) if args.host_only else ('host', 'box')
+ if args.action == 'recover':
+ return recover(args, home, dc, services)
+ image = instance_images(dc, args.project, services, args.action != 'up')['host']
+ current = inventory(args.project, services, new=args.action == 'up')
+ if args.action == 'backup':
+ return backup(args, home, current['host']['Image'] if 'host' in current else image)
+ root = volume_backup.local_lineage(args.project) if args.action == 'update' else args.project
+ # Builders also publish fixed shared base/desktop tags. One daemon-wide writer covers aliases and rollback.
+ with volume_backup.lineage_lock(root), volume_backup.operation_lock('prokbot-image-publication-lock'):
+ # Preserve the pre-stop fact through snapshot and rollback. This exception never applies
+ # to a stopped Host, a restored Host, or recovery into a new project.
+ continuing = False
+ if (args.action == 'update' and root == args.project and 'host' in current and
+ current['host']['State']['Status'] == 'running'):
+ labels = volume_backup.volume_labels(args.project+'_host-data')
+ continuing = (labels.get(volume_backup.PROJECT_LABEL) == args.project and
+ labels.get(volume_backup.VOLUME_LABEL) == 'host-data' and
+ volume_backup.RESTORE_LABEL not in labels and volume_backup.LINEAGE_LABEL not in labels and
+ volume_backup.compose_created(labels))
+ volume_backup.check_lineage(root, args.project, fresh=args.action == 'up', continuing=continuing)
+ if args.action == 'update':
+ upgrade(args, home, dc, services, image, current, root, continuing)
+ else:
+ previous = tag_state(image)
+ with staged_host(args, services) as images:
+ inventory(args.project, services, new=True)
+ volume_backup.check_lineage(root, args.project, fresh=True)
+ publish_image(previous, images['host'], image)
+ try:
+ up_and_wait(dc, args.project, services, images, existing=False)
+ except (Exception, KeyboardInterrupt) as error:
+ try:
+ stop_failed_start(dc, args.project, services, False, 'Installation failed. No volumes were removed.', error)
+ finally:
+ revert_tag(previous, images['host'], image)
+ run(dc + ['ps'])
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--home', type=Path, default=Path.home() / 'grokbot', help='Instance directory (.env, backups); default ~/grokbot')
+ parser.add_argument('--project', help='Compose project/volume prefix; default: saved project or grokbot')
+ parser.add_argument('--host-only', action='store_true', help='Use a separately deployed execution node')
+ sub = parser.add_subparsers(dest='action', required=True)
+ init = sub.add_parser('init', help='Create .env once; never overwrite an existing deployment')
+ init.add_argument('--listen', default='127.0.0.1'); init.add_argument('--port', type=int, default=18080)
+ init.add_argument('--public-url', help='URL entered on clients; no subpath')
+ recovery = sub.add_parser('recover', help='Restore and start a NEW project from verified volumes and recorded immutable images')
+ recovery.add_argument('--directory', required=True, type=Path, help='Backup directory containing manifest.json')
+ for cmd, help_text in [('doctor', 'Check Docker, Compose, architecture and desktop compatibility'),
+ ('up', 'Build verified inputs and start a new installation'),
+ ('update', 'Stage a build, stop existing services, back up and switch to the candidate'),
+ ('backup', 'Back up all project volumes'), ('status', 'Show container status'),
+ ('logs', 'Show recent Host logs'), ('setup-key', 'Show the private, first-use setup key')]:
+ command = sub.add_parser(cmd, help=help_text)
+ if cmd in ('up', 'update'):
+ command.add_argument('--host-archive', type=Path, help='Use a previously downloaded pinned Host archive')
+ command.add_argument('--box-archive', type=Path, help='Use a previously saved pinned desktop image')
+ admin = sub.add_parser('admin', help='Run the bundled admin CLI; pass secrets via environment only')
+ admin.add_argument('arguments', nargs=argparse.REMAINDER)
+ args = parser.parse_args(argv); home = args.home.expanduser().resolve()
+ instance_settings(args, home)
+ if args.action == 'init':
+ return initialise(home, args)
+ if args.action == 'doctor':
+ report = {'ok': False, 'project': args.project, 'existingConfig': (home / '.env').is_file()}
+ try:
+ platform = docker_platform()
+ report.update(hostPlatform=platform, **({} if args.host_only else check_runtime_versions()),
+ desktop='remote' if args.host_only else 'native' if platform == BOX['platform'] else 'emulated-amd64',
+ existingVolumes=sorted(volume_backup.project_volumes(args.project)), resources=daemon_resources())
+ help_text = run(['docker', 'compose', 'up', '--help'], capture=True).stdout
+ if '--wait-timeout' not in help_text:
+ raise ValueError('This Compose version cannot wait for service health. Install a Compose v2 with up --wait-timeout.')
+ report['hostDataVolumes'] = run(['docker', 'volume', 'ls', '-q', '--filter', 'label=com.docker.compose.volume=host-data'], capture=True).stdout.splitlines()
+ if report['existingConfig']:
+ run(compose(args, home) + ['config', '--quiet'])
+ if not args.host_only:
+ check_box_execution(platform)
+ report['ok'] = True
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
+ report['error'] = str(error)
+ print(json.dumps(report))
+ if not report['ok']:
+ raise SystemExit(1)
+ return
+ if args.action in ('up', 'update', 'recover') and not args.host_only:
+ check_runtime_versions()
+ dc = compose(args, home)
+ if args.action in ('status', 'logs', 'setup-key'):
+ return run(dc + {'status': ['ps', '--all'], 'logs': ['logs', '--tail', '100', 'host'],
+ 'setup-key': ['exec', '-T', 'host', 'cat', '/data/setup-key']}[args.action])
+ if args.action == 'admin':
+ env = {**os.environ, 'GROKBOT_URL': 'http://127.0.0.1:8000'}
+ flags = [arg for k in ('GROKBOT_URL', 'GROKBOT_ADMIN_PASSWORD', 'MODEL_API_KEY') if k in env for arg in ('-e', k)]
+ extra = args.arguments or ['help']
+ if extra[0] == 'setup':
+ extra = [*extra, '--setup-key-file', '/data/setup-key']
+ return run(dc + ['exec', '-T', *flags, 'host', '/exec-daemon/node', 'tools/host-admin.mjs', *extra], env=env)
+ with volume_backup.project_lock(args.project):
+ return operate(args, home, dc)
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
+ raise SystemExit(str(error)) from error
diff --git a/host/deploy/healthcheck.mjs b/host/deploy/healthcheck.mjs
index c8b9827accd7206998d231250465972d8f5adbad..4eb9835b56dc619094cae5980478a08b75a26c81 100644
--- a/host/deploy/healthcheck.mjs
+++ b/host/deploy/healthcheck.mjs
@@ -28,6 +28,17 @@ export async function checkDeploymentHealth(env = process.env) {
!/^OPENAI_MODEL=.+$/m.test(model)
)
return true;
+ // HostSupervisor intentionally waits for the execution node on split installations.
+ if (env.GROKBOT_REQUIRE_EXECUTION_NODE === '1') {
+ const state = await readFile(join(data, 'execution-node.json'), 'utf8').catch(error => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ if (state === null) return true;
+ const saved = JSON.parse(state);
+ if (saved?.version !== 1 || typeof saved.config?.enabled !== 'boolean') return false;
+ if (!saved.config.enabled) return true;
+ }
const token = await internalCredential(
env.GROKBOT_INTERNAL_HOST_TOKEN_FILE ?? join(data, "internal-host-token"),
);
diff --git a/host/deploy/host-supervisor.mjs b/host/deploy/host-supervisor.mjs
index 9fb40c5ae27277ec9846b1c05dee19d867902959..b51a0749e2581383f795d62f6ad0fcc98007ceec 100644
--- a/host/deploy/host-supervisor.mjs
+++ b/host/deploy/host-supervisor.mjs
@@ -156,7 +156,7 @@ export class HostSupervisor {
!this.stopping
) {
await this.status(revision, "waiting", "正在启动 Host");
- this.startHost(revision);
+ if (!this.stopping) this.startHost(revision);
}
return;
}
diff --git a/host/docs/DEPLOYMENT.en.md b/host/docs/DEPLOYMENT.en.md
index 09703a16482b5e54cfa21097e4510e240eb4e6a3..a7cdb2c293a6b4e0a1c6e3d25138e03996727f60 100644
--- a/host/docs/DEPLOYMENT.en.md
+++ b/host/docs/DEPLOYMENT.en.md
@@ -1,9 +1,10 @@
# Deployment and backups
-Requires Python 3.10+, Docker and Compose. The runtime uses Linux amd64.
+Requires Python 3.10+, Docker Engine 26.0+ (API 1.45+) and Compose 2.26.0+; a standalone Host does not need these versions. Linux x86_64 and ARM64 are supported: the Host image is built for the Docker machine's architecture, and the Linux desktop image is amd64 only. On ARM machines, including Apple Silicon Macs, the desktop runs under emulation, and the build tool checks that it can run first.
```sh
python3 release/build-docker.py --host-archive /path/to/sand-host-bundle-d0a4baa.tgz
+docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data
docker compose -f release/compose.yaml up -d
docker compose -f release/compose.yaml exec host cat /data/setup-key
```
@@ -12,11 +13,14 @@ Open `http://127.0.0.1:18080`, initialize the administrator account, configure a
Use `GROKBOT_LISTEN_ADDRESS=0.0.0.0` for LAN access and `GROKBOT_PUBLIC_PORT` for a different port. For remote access, use HTTPS or optional Tailcat.
+The Linux desktop mounts only five directories from `host-data`: `agents`, `user-memory`, `workflows`, `plugins` and `managed-skills`, at `/data/runtime/host-data/`, the original Host path, so the Bot can read its memory on its own computer while the original path protection still applies and Read refuses `store.db`. `agent-transcripts`, `model.env`, `auth.json`, `connector-secrets` and `projects` stay out. Each directory is a `volume subpath`; older Compose may ignore the subpath and mount all of `host-data`, hence the minimum versions above, which `deploy.py` checks before writing or starting. `data_init.py` creates the directories (the second command above); it creates only missing ones and sets ownership only on those.
+
The `host-data`, `box-home` and `box-workspace` volumes retain data. The backup tool pauses running containers, saves all project volumes with checksums and resumes them. Restore into a new project without overwriting existing volumes:
```sh
python3 release/backup.py backup --project grokbot --directory backups/2026-10-21 --image grokbot-host:local
python3 release/backup.py restore --project grokbot-restored --directory backups/2026-10-21 --image grokbot-host:local
+docker compose -p grokbot-restored -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data
docker compose -p grokbot-restored -f release/compose.yaml up -d
```
diff --git a/host/docs/DEPLOYMENT.md b/host/docs/DEPLOYMENT.md
index 762346808582bf33cf365ae3b4a2e1d6c221fe11..386160090dfc54db4316a5ec5e9d3b5535af362a 100644
--- a/host/docs/DEPLOYMENT.md
+++ b/host/docs/DEPLOYMENT.md
@@ -2,10 +2,11 @@
## 构建
-需要 Python 3.10+、Docker 和 Compose。支持 Linux x86_64;Apple Silicon 可以构建 amd64 镜像。
+需要 Python 3.10+、Docker Engine 26.0+(API 1.45+)和 Compose 2.26.0+;只部署 Host 时不要求这些版本。支持 Linux x86_64 和 ARM64:Host 镜像按 Docker 所在机器的架构构建;Linux 桌面镜像只有 amd64,在 ARM 机器(包括 Apple Silicon Mac)上通过转译运行,构建工具会先检查能否运行。
```sh
python3 release/build-docker.py --host-archive /path/to/sand-host-bundle-d0a4baa.tgz
+docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data
docker compose -f release/compose.yaml up -d
```
@@ -21,11 +22,14 @@ docker compose -f release/compose.yaml exec host cat /data/setup-key
## 数据与更新
+Linux 桌面只挂载 `host-data` 里的 `agents`、`user-memory`、`workflows`、`plugins`、`managed-skills` 五个目录,位置是 `/data/runtime/host-data/<目录>`,和原版 Host 的路径一致,让 Bot 在自己的电脑上读记忆;原版的路径保护照样生效,Read 读不了 `store.db`。`agent-transcripts`、`model.env`、`auth.json`、`connector-secrets`、`projects` 不挂入。每个目录用一个 `volume subpath`,旧版 Compose 可能忽略子路径、把整个 `host-data` 挂进去,所以要求上面的最低版本,`deploy.py` 在写入或启动前检查。目录由 `data_init.py` 创建(见上面的第二条命令),它只建缺失的目录并设置这些新目录的属主,不改已有目录。
+
Compose 持久保存 `host-data`、`box-home`、`box-workspace` 三个卷。备份工具暂停正在运行的容器,保存卷与摘要后恢复运行。恢复到一个新的 Compose 项目,不覆盖现有卷:
```sh
python3 release/backup.py backup --project grokbot --directory backups/2026-10-21 --image grokbot-host:local
python3 release/backup.py restore --project grokbot-restored --directory backups/2026-10-21 --image grokbot-host:local
+docker compose -p grokbot-restored -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data
docker compose -p grokbot-restored -f release/compose.yaml up -d
```
diff --git a/host/network/build-tailcat.py b/host/network/build-tailcat.py
index 776e6e193b160bd7e8eb8a24db6aa7f75207db97..08ec7249b1c3119322ff33cf14e7f2e0776e1d9c 100644
--- a/host/network/build-tailcat.py
+++ b/host/network/build-tailcat.py
@@ -7,7 +7,7 @@ import subprocess
ROOT = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument('--target', choices=['native', 'linux-amd64', 'ios-arm64'], default='native')
+parser.add_argument('--target', choices=['native', 'linux-amd64', 'linux-arm64', 'darwin-amd64', 'darwin-arm64', 'windows-amd64', 'ios-arm64'], default='native')
parser.add_argument('--output', type=Path, default=ROOT / 'dist/network')
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
@@ -21,7 +21,14 @@ if args.target == 'ios-arm64':
CGO_LDFLAGS=f'-arch arm64 -isysroot {sdk} -miphoneos-version-min=15.1')
command += ['-buildmode=c-archive', '-o', str(args.output.resolve() / 'libGrokTailcat.a'), './mobile']
else:
- if args.target == 'linux-amd64':
- env.update(GOOS='linux', GOARCH='amd64', CGO_ENABLED='0')
- command += ['-ldflags=-s -w', '-o', str(args.output.resolve() / 'grokbot-tailcat'), './cmd/grokbot-tailcat']
+ name = 'grokbot-tailcat'
+ if args.target.startswith(('linux-', 'darwin-')):
+ goos, goarch = args.target.split('-')
+ env.update(GOOS=goos, GOARCH=goarch, CGO_ENABLED='0')
+ elif args.target == 'windows-amd64':
+ env.update(GOOS='windows', GOARCH='amd64', CGO_ENABLED='0')
+ name += '.exe'
+ elif args.target == 'native' and os.name == 'nt':
+ name += '.exe'
+ command += ['-ldflags=-s -w', '-o', str(args.output.resolve() / name), './cmd/grokbot-tailcat']
subprocess.run(command, cwd=ROOT / 'network/tailcat', env=env, check=True)
diff --git a/host/recipes/host/manifest.json b/host/recipes/host/manifest.json
index 5ff8cb554e47d2e2eb3dbe193b29a63d16aca613..a5bbec8cbff7d24ef63a7e0e2f2c98f1dcb6e92e 100644
--- a/host/recipes/host/manifest.json
+++ b/host/recipes/host/manifest.json
@@ -1,5 +1,16 @@
{
"schema": "grokbot-host-inputs/v1",
+ "sourceSha256": {
+ "host-main.cjs": "d7ffb02b831337f6e4618a2604fb6ecd00a7f75f4c4bf96f5075f54d473b7f67",
+ "agent-isolation/agent-store-worker.cjs": "868572888c71b317c7878b5efc81b029aa99192e3bef7402591759388a6bcf3c"
+ },
+ "box": {
+ "repository": "public.ecr.aws/k0i0n2g5/cursorenvironments/universal",
+ "platform": "linux/amd64",
+ "manifestDigest": "sha256:73c04dc8722de013fb2ad99366171e3a4c7379f1253d127348a5047d13f0ed41",
+ "configDigest": "sha256:1bdd316ac812b6647fe1163e97f200b99edb155b97d927727e85dc0c5ea3cd6f",
+ "localTag": "grokbot-box-input:9d2ac1b"
+ },
"archive": {
"version": "d0a4baa",
"url": "https://public-asphr-vm-daemon-bucket.s3.us-east-1.amazonaws.com/sand-host-bundle/sand-host-bundle-d0a4baa.tgz",
diff --git a/host/recipes/host/recovered-core__stable__harness-provenance.json.gbp.gz b/host/recipes/host/recovered-core__stable__harness-provenance.json.gbp.gz
index d55d3be0c15ff19ffa906cbbb2d5a9085b8422e1..e8687b2f97f3517767018ab82b8c11d4c5fdfd39 100644
Binary files a/host/recipes/host/recovered-core__stable__harness-provenance.json.gbp.gz and b/host/recipes/host/recovered-core__stable__harness-provenance.json.gbp.gz differ
diff --git a/host/recipes/host/recovered-core__stable__harness-turn-run-shell.mjs.gbp.gz b/host/recipes/host/recovered-core__stable__harness-turn-run-shell.mjs.gbp.gz
index 260db6f0d3591f1a827ee02674f46bbf0c954a72..2c1ccd81a376ca3af2ffd38c9f71cb4bc679136f 100644
Binary files a/host/recipes/host/recovered-core__stable__harness-turn-run-shell.mjs.gbp.gz and b/host/recipes/host/recovered-core__stable__harness-turn-run-shell.mjs.gbp.gz differ
diff --git a/host/recipes/host/release-reliability__engine-tool-stream-executor.mjs.gbp.gz b/host/recipes/host/release-reliability__engine-tool-stream-executor.mjs.gbp.gz
index b61aa2a1a48b7fc248c6dec06dc0ebc9c33f55c5..e3c348129e4d38e3d85a1ca720434c668a35e704 100644
Binary files a/host/recipes/host/release-reliability__engine-tool-stream-executor.mjs.gbp.gz and b/host/recipes/host/release-reliability__engine-tool-stream-executor.mjs.gbp.gz differ
diff --git a/host/recipes/host/release-reliability__harness-provenance.json.gbp.gz b/host/recipes/host/release-reliability__harness-provenance.json.gbp.gz
index d55d3be0c15ff19ffa906cbbb2d5a9085b8422e1..a9cb7f9795fc1d49b4ea4709f5c9512b6efeea3c 100644
Binary files a/host/recipes/host/release-reliability__harness-provenance.json.gbp.gz and b/host/recipes/host/release-reliability__harness-provenance.json.gbp.gz differ
diff --git a/host/recipes/host/release-reliability__harness-turn-run-shell.mjs.gbp.gz b/host/recipes/host/release-reliability__harness-turn-run-shell.mjs.gbp.gz
index f04ed2f295605e542582a3a705fa6d35539b45e8..3177b187f1ddb44be24d5eb89bc69affadacc67d 100644
Binary files a/host/recipes/host/release-reliability__harness-turn-run-shell.mjs.gbp.gz and b/host/recipes/host/release-reliability__harness-turn-run-shell.mjs.gbp.gz differ
diff --git a/host/recipes/host/release-reliability__manifest.json.gbp.gz b/host/recipes/host/release-reliability__manifest.json.gbp.gz
index 2c9ce3e0148439fb679c56b2514f1fbdea21f98a..2411d5509dc77885ad04560bb135ff6ea7528cd1 100644
Binary files a/host/recipes/host/release-reliability__manifest.json.gbp.gz and b/host/recipes/host/release-reliability__manifest.json.gbp.gz differ
diff --git a/host/recipes/host/release-reliability__reliability.json.gbp.gz b/host/recipes/host/release-reliability__reliability.json.gbp.gz
index 447a2e9a3c2577bb48878c8f3c7587eda0037a72..5d86239c615ab72196219c56f2130549162bc7e8 100644
Binary files a/host/recipes/host/release-reliability__reliability.json.gbp.gz and b/host/recipes/host/release-reliability__reliability.json.gbp.gz differ
diff --git a/host/release/Dockerfile.arm-runtime b/host/release/Dockerfile.arm-runtime
new file mode 100644
index 0000000000000000000000000000000000000000..9ab8d7af03d98a6acf48cfae7a1dd602a79c8599
--- /dev/null
+++ b/host/release/Dockerfile.arm-runtime
@@ -0,0 +1,11 @@
+FROM node:22-bookworm-slim AS addons
+WORKDIR /addons
+COPY release/arm-runtime/package*.json ./
+RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ && rm -rf /var/lib/apt/lists/* \
+ && npm_config_nodedir=/usr/local npm ci --no-audit --no-fund
+
+FROM node:22-bookworm-slim
+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates libfontconfig1 fonts-dejavu-core && rm -rf /var/lib/apt/lists/* \
+ && mkdir -p /exec-daemon && ln -s /usr/local/bin/node /exec-daemon/node
+COPY --from=addons /addons/node_modules/ /opt/sand/deps/
+RUN NODE_PATH=/opt/sand/deps /exec-daemon/node -e "const p=new (require('tree-sitter'))(); p.setLanguage(require('tree-sitter-bash')); if(p.parse('echo ok').rootNode.hasError) process.exit(1); const {CanvasElement}=require('@napi-rs/canvas-linux-arm64-gnu'); if(!new CanvasElement(8,8).toBuffer('image/png').length) process.exit(1)"
diff --git a/host/release/Dockerfile.base b/host/release/Dockerfile.base
index ce4d19839f1c6e17313c7b3a53ea6fe243729dfb..151ac8f0ee4c9d8d1ef2cf2828e82365fa0f90dd 100644
--- a/host/release/Dockerfile.base
+++ b/host/release/Dockerfile.base
@@ -5,11 +5,14 @@ COPY server/package*.json server/
RUN npm ci --prefix server --omit=dev --ignore-scripts --no-audit --no-fund
COPY runtime/ runtime/
COPY server/ server/
+COPY tools/ tools/
COPY clients/shared/ clients/shared/
COPY deploy/ deploy/
COPY release/ release/
COPY recipes/ recipes/
COPY network/ network/
COPY bin/ bin/
+RUN case "$(dpkg --print-architecture)" in arm64) mv bin/linux-arm64/grokbot-tailcat bin/grokbot-tailcat ;; amd64) ;; *) exit 1 ;; esac \
+ && rm -r bin/linux-arm64 && chmod 755 bin/grokbot-tailcat
COPY THIRD_PARTY/ THIRD_PARTY/
# This stage contains only project code, delta recipes and open-source dependencies.
diff --git a/host/release/Dockerfile.execution b/host/release/Dockerfile.execution
index d3c89cacf230f9320d03eab4a41e5188d40425b6..8aee276b756c8d253ae89c7efefd59329125e9ad 100644
--- a/host/release/Dockerfile.execution
+++ b/host/release/Dockerfile.execution
@@ -3,6 +3,7 @@ WORKDIR /app
COPY deploy/execution-gateway.mjs deploy/execution-tailcat.mjs deploy/
COPY clients/shared/ clients/shared/
COPY bin/grokbot-tailcat /app/bin/grokbot-tailcat
+RUN chmod 755 /app/bin/grokbot-tailcat
COPY network/TAILCAT-LICENSE /app/bin/TAILCAT-LICENSE
COPY THIRD_PARTY/ /app/THIRD_PARTY/
ENV GROKBOT_TAILCAT_BINARY=/app/bin/grokbot-tailcat
diff --git a/host/release/Dockerfile.host b/host/release/Dockerfile.host
index 5e893f48acfdaefd038d05b7070a16659e9dd883..75f4ee56e1e17083b5dd0e96bf2cc674f046efd4 100644
--- a/host/release/Dockerfile.host
+++ b/host/release/Dockerfile.host
@@ -1,18 +1,19 @@
ARG PATCH_IMAGE=grokbot-patch-base:local
-ARG BOX_IMAGE=public.ecr.aws/k0i0n2g5/cursorenvironments/universal@sha256:73c04dc8722de013fb2ad99366171e3a4c7379f1253d127348a5047d13f0ed41
+ARG RUNTIME_IMAGE=grokbot-box-input:9d2ac1b
FROM ${PATCH_IMAGE} AS patch
COPY inputs/host.tgz /inputs/host.tgz
RUN python3 release/patch-host.py --archive /inputs/host.tgz --output /generated
-FROM ${BOX_IMAGE}
+FROM ${RUNTIME_IMAGE}
+ARG HOST_REVISION
WORKDIR /opt/grokbot
COPY --from=patch /opt/grokbot /opt/grokbot
-COPY --from=patch /generated/original artifacts/host-d0a4baa/sand-host/
+COPY --from=patch /generated/original artifacts/host-${HOST_REVISION}/sand-host/
COPY --from=patch /generated/seed seed/
-ENV NODE_PATH=/opt/sand/deps:/opt/sand/sand-host/node_modules:/exec-daemon/node_modules \
+ENV NODE_PATH=/opt/sand/deps:/opt/grokbot/artifacts/host-${HOST_REVISION}/sand-host/node_modules:/opt/sand/sand-host/node_modules:/exec-daemon/node_modules \
GROKBOT_DATA_DIR=/data GROKBOT_STATE_DIR=/data/runtime \
GROKBOT_MODEL_ENV=/data/model.env GROKBOT_HOST_DATA_DIR=/data/runtime/host-data \
- GROKBOT_ORIGINAL_HOST=/opt/grokbot/artifacts/host-d0a4baa/sand-host \
+ GROKBOT_ORIGINAL_HOST=/opt/grokbot/artifacts/host-${HOST_REVISION}/sand-host \
GROKBOT_RUNTIME_DIR=/opt/grokbot/runtime GROKBOT_RECOVERED_CORE=1 \
GROKBOT_HOST_BIND=127.0.0.1 GROKBOT_HOST_PORT=1340 \
GROKBOT_INTERNAL_HOST_URL=http://127.0.0.1:1340 \
diff --git a/host/release/arm-runtime/package-lock.json b/host/release/arm-runtime/package-lock.json
new file mode 100644
index 0000000000000000000000000000000000000000..fc82520e36637f7b621554496c98bde737d1e1e2
--- /dev/null
+++ b/host/release/arm-runtime/package-lock.json
@@ -0,0 +1,83 @@
+{
+ "name": "prokbot-arm-host-runtime",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "prokbot-arm-host-runtime",
+ "dependencies": {
+ "@napi-rs/canvas-linux-arm64-gnu": "0.1.80",
+ "tree-sitter": "0.25.0",
+ "tree-sitter-bash": "0.25.0"
+ }
+ },
+ "node_modules/@napi-rs/canvas-linux-arm64-gnu": {
+ "version": "0.1.80",
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.80.tgz",
+ "integrity": "sha512-qwA63t8A86bnxhuA/GwOkK3jvb+XTQaTiVML0vAWoHyoZYTjNs7BzoOONDgTnNtr8/yHrq64XXzUoLqDzU+Uuw==",
+ "cpu": [
+ "arm64"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/node-addon-api": {
+ "version": "8.9.2",
+ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz",
+ "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==",
+ "license": "MIT",
+ "engines": {
+ "node": "^18 || ^20 || >= 21"
+ }
+ },
+ "node_modules/node-gyp-build": {
+ "version": "4.8.4",
+ "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
+ "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
+ "license": "MIT",
+ "bin": {
+ "node-gyp-build": "bin.js",
+ "node-gyp-build-optional": "optional.js",
+ "node-gyp-build-test": "build-test.js"
+ }
+ },
+ "node_modules/tree-sitter": {
+ "version": "0.25.0",
+ "resolved": "https://registry.npmjs.org/tree-sitter/-/tree-sitter-0.25.0.tgz",
+ "integrity": "sha512-PGZZzFW63eElZJDe/b/R/LbsjDDYJa5UEjLZJB59RQsMX+fo0j54fqBPn1MGKav/QNa0JR0zBiVaikYDWCj5KQ==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "node-addon-api": "^8.3.0",
+ "node-gyp-build": "^4.8.4"
+ }
+ },
+ "node_modules/tree-sitter-bash": {
+ "version": "0.25.0",
+ "resolved": "https://registry.npmjs.org/tree-sitter-bash/-/tree-sitter-bash-0.25.0.tgz",
+ "integrity": "sha512-gZtlj9+qFS81qKxpLfD6H0UssQ3QBc/F0nKkPsiFDyfQF2YBqYvglFJUzchrPpVhZe9kLZTrJ9n2J6lmka69Vg==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "node-addon-api": "^8.2.1",
+ "node-gyp-build": "^4.8.2"
+ },
+ "peerDependencies": {
+ "tree-sitter": "^0.25.0"
+ },
+ "peerDependenciesMeta": {
+ "tree-sitter": {
+ "optional": true
+ }
+ }
+ }
+ }
+}
diff --git a/host/release/arm-runtime/package.json b/host/release/arm-runtime/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..1fe8a110e8694d8ce5974667b324e8b69bda4594
--- /dev/null
+++ b/host/release/arm-runtime/package.json
@@ -0,0 +1,9 @@
+{
+ "name": "prokbot-arm-host-runtime",
+ "private": true,
+ "dependencies": {
+ "@napi-rs/canvas-linux-arm64-gnu": "0.1.80",
+ "tree-sitter": "0.25.0",
+ "tree-sitter-bash": "0.25.0"
+ }
+}
diff --git a/host/release/backup.py b/host/release/backup.py
index 7b404b217ea1e6b1b1c77cd43bee5a681a95c8a8..ec42b906d557dd359ed28fcfbc165f883558715e 100644
--- a/host/release/backup.py
+++ b/host/release/backup.py
@@ -1,23 +1,346 @@
#!/usr/bin/env python3
"""Back up a Compose project's volumes, or restore them into a new project."""
import argparse
+from contextlib import contextmanager
import hashlib
import json
-from pathlib import Path
+import os
+from pathlib import Path, PurePosixPath
import re
import shutil
import subprocess
+import sys
import time
+from uuid import uuid4
DOCKER = shutil.which('docker') or '/usr/local/bin/docker'
+PROJECT_NAME = re.compile(r'[a-z0-9][a-z0-9_-]{0,60}')
+RESTORE_LABEL = 'io.prokbot.restore-id'
+LINEAGE_LABEL = 'io.prokbot.lineage-root'
+PROJECT_LABEL = 'com.docker.compose.project'
+VOLUME_LABEL = 'com.docker.compose.volume'
+VERSION_LABEL = 'com.docker.compose.version'
+OPERATION_LABEL = 'io.prokbot.operation-id'
+MOUNTS = {'host': {'host-data': '/data'}, 'box': {'box-home': '/home/box', 'box-workspace': '/workspace'},
+ 'gateway': {'gateway-data': '/data'}}
+TOPOLOGIES = (('host',), ('host', 'box'), ('gateway', 'box'))
+DATA_TREES = ('agents', 'user-memory', 'workflows', 'plugins', 'managed-skills')
+DATA_SOURCE_ROOT = PurePosixPath('runtime/host-data')
+BOX_DATA_ROOTS = (PurePosixPath('/data/runtime/host-data'),)
+BOX_DATA_TARGETS = {str(root / tree): tree for root in BOX_DATA_ROOTS for tree in DATA_TREES}
def run(*args, **kwargs):
+ kwargs.setdefault('stdin', subprocess.DEVNULL)
return subprocess.run([DOCKER, *args], check=True, **kwargs)
def output(*args):
- return subprocess.check_output([DOCKER, *args], text=True).strip()
+ return subprocess.check_output([DOCKER, *args], text=True, stdin=subprocess.DEVNULL).strip()
+
+
+def project_volumes(project):
+ return set(output('volume', 'ls', '-q', '--filter', f'label=com.docker.compose.project={project}').splitlines())
+
+
+def topology(project, names):
+ for services in TOPOLOGIES:
+ if names == {f'{project}_{suffix}' for s in services for suffix in MOUNTS[s]}:
+ return services
+ raise ValueError('Incomplete or unexpected project volume set; check the original project and topology.')
+
+
+def label_fields(field, keys):
+ fields = ','.join('"%s":{{json (index %s "%s")}}' % (k, field, k) for k in keys)
+ return '{{if '+field+'}}{'+fields+'}{{else}}{}{{end}}'
+
+
+def volume_labels(name):
+ fmt = label_fields('.Labels', (PROJECT_LABEL, VOLUME_LABEL, VERSION_LABEL, RESTORE_LABEL, LINEAGE_LABEL, OPERATION_LABEL))
+ labels = json.loads(output('volume', 'inspect', '--format', fmt, name))
+ return {k: v for k, v in labels.items() if v}
+
+
+@contextmanager
+def operation_lock(name):
+ # The daemon's named-volume namespace is shared across homes, users and Docker clients.
+ # Never steal a stale lock: a disconnected updater may still be running.
+ token = uuid4().hex
+ try:
+ run('volume', 'create', '--label', f'{OPERATION_LABEL}={token}', name, stdout=subprocess.DEVNULL)
+ if volume_labels(name).get(OPERATION_LABEL) != token:
+ raise ValueError(f'Another operation owns {name}; do not remove an active lock.')
+ yield
+ finally:
+ try:
+ if name in output('volume', 'ls', '-q').splitlines() and volume_labels(name).get(OPERATION_LABEL) == token:
+ run('volume', 'rm', name, stdout=subprocess.DEVNULL)
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
+ raise RuntimeError(f'Could not verify/release operation lock {name}; inspect before retrying.') from error
+
+
+def project_lock(project):
+ if not PROJECT_NAME.fullmatch(project):
+ raise ValueError('Invalid Compose project name')
+ return operation_lock('prokbot-operation-'+project)
+
+
+def lineage_lock(root):
+ if not isinstance(root, str) or not PROJECT_NAME.fullmatch(root):
+ raise ValueError('Unknown backup lineage; only offline data restore is safe.')
+ return operation_lock('prokbot-lineage-operation-'+root)
+
+
+def compose_created(labels):
+ return re.fullmatch(r'v?\d+\.\d+(?:\.\d+)?(?:[-+][\w.+-]+)?', labels.get(VERSION_LABEL, '')) is not None
+
+
+def volume_lineage(project, labels):
+ root = labels.get(LINEAGE_LABEL)
+ if root is not None and (not isinstance(root, str) or not PROJECT_NAME.fullmatch(root)):
+ raise ValueError('Invalid Host volume lineage metadata.')
+ # Legacy restored volumes have no proven source, even if this is the only copy on the daemon.
+ if root is None and RESTORE_LABEL not in labels and compose_created(labels):
+ root = project
+ return root
+
+
+def volume_users(name):
+ return set(output('ps', '--all', '--no-trunc', '-q', '--filter', f'volume={name}').splitlines())
+
+
+def active_host_mount(name):
+ for c in inspect_containers(volume_users(name)):
+ if (c['State']['Status'] not in ('created', 'exited') and
+ (c['Labels'] or {}).get('com.docker.compose.service') == 'host' and
+ any(m['Type'] == 'volume' and m.get('Name') == name and m['Destination'] == '/data' for m in c['Mounts'])):
+ return True
+ return False
+
+
+def host_volume_inventory():
+ # No payloads, credentials, container environment, or client identity files are inspected.
+ names = set(output('volume', 'ls', '-q').splitlines())
+ hosts = {n for n in names if n.endswith('_host-data')}
+ hosts.update(output('volume', 'ls', '-q', '--filter', f'label={VOLUME_LABEL}=host-data').splitlines())
+ entries = {}
+ for name in hosts:
+ labels = volume_labels(name)
+ project = labels.get(PROJECT_LABEL, '')
+ role = labels.get(VOLUME_LABEL)
+ marked = RESTORE_LABEL in labels or LINEAGE_LABEL in labels
+ if not labels:
+ # Even the oldest managed restore set both Compose ownership labels. A suffix alone
+ # is not evidence of a copy; an actual Host /data mount or an exact target collision is.
+ if active_host_mount(name):
+ raise ValueError('A Host is using an unlabelled data volume; refusing activation.')
+ continue
+ if (not project and not role and not marked and re.fullmatch(r'[a-f0-9]{32}', labels.get(OPERATION_LABEL, ''))
+ and name.startswith(('prokbot-operation-', 'prokbot-lineage-operation-'))):
+ continue # A valid project name (and hence its lock name) can end in _host-data.
+ if (not marked and PROJECT_NAME.fullmatch(project) and role and compose_created(labels) and
+ (role != 'host-data' or name != project+'_host-data')):
+ continue # Explicit foreign Compose names are not managed ProkBot mounts.
+ if (not PROJECT_NAME.fullmatch(project) or name != project+'_host-data' or role != 'host-data'):
+ raise ValueError('Cannot establish lineage of an unmanaged Host volume on this daemon.')
+ entries[project] = (name, volume_lineage(project, labels))
+ return entries
+
+
+def local_lineage(project):
+ name = project+'_host-data'
+ if name not in project_volumes(project):
+ return None
+ labels = volume_labels(name)
+ if labels.get(PROJECT_LABEL) != project or labels.get(VOLUME_LABEL) != 'host-data':
+ raise ValueError('Host volume does not belong to the selected project.')
+ return volume_lineage(project, labels)
+
+
+def check_lineage(root, project, *, original=None, fresh=False, continuing=False):
+ """Reject unsafe activation. Return whether detached unknown copies limited this approval."""
+ if not isinstance(root, str) or not PROJECT_NAME.fullmatch(root):
+ raise ValueError('Unknown Host lineage; refusing automatic activation.')
+ entries = host_volume_inventory()
+ checked = set()
+ detached_unknown = False
+ for owner, (name, declared) in entries.items():
+ if declared is None:
+ # Never activate an unknown copy. An empty install or the same already-running
+ # original may proceed past a different, detached copy; even stopped attachments count.
+ if ((fresh or continuing) and owner not in (root, project, original) and
+ not project_ids(owner) and not volume_users(name)):
+ detached_unknown = True
+ continue
+ raise ValueError('Unmarked legacy Host volume on this daemon; identity is ambiguous. Use offline data restore.')
+ if declared != root:
+ if owner in (root, project, original):
+ raise ValueError('Conflicting Host lineage; refusing activation.')
+ continue
+ if owner == project:
+ continue
+ peers = set(project_ids(owner))
+ checked.update(peers | volume_users(name))
+ for owner in {root, original} - {None, project}:
+ checked.update(project_ids(owner))
+ for cid in checked:
+ if output('inspect', '--format', '{{.State.Status}}', cid) not in ('created', 'exited'):
+ raise ValueError('Another project with this Host identity is not stopped; refusing activation.')
+ return detached_unknown
+
+
+def verify_volumes(project, names):
+ for name in names:
+ labels = volume_labels(name)
+ if (labels.get('com.docker.compose.project') != project or
+ labels.get('com.docker.compose.volume') != name[len(project)+1:]):
+ raise ValueError(f'Volume {name} does not have the expected project and volume labels.')
+
+
+def project_ids(project):
+ return output('ps', '--all', '--no-trunc', '-q', '--filter', f'label=com.docker.compose.project={project}').splitlines()
+
+
+def inspect_containers(ids):
+ # Request only lifecycle metadata, not a container's environment or other configuration.
+ labels = label_fields('.Config.Labels', (PROJECT_LABEL, 'com.docker.compose.service', 'com.docker.compose.oneoff'))
+ # Docker's resolved mount list omits VolumeOptions.Subpath. Project only the affected
+ # container destinations and source identities; never request HostConfig wholesale.
+ # `docker inspect` retries a template that fails on its typed structs against the raw JSON,
+ # with missing keys as errors; `.Id` and `index` on a struct fail there, so this template
+ # always reads the raw JSON. The daemon omits empty fields from it: HostConfig.Mounts on
+ # containers created with Binds (as Compose 2.40 does), VolumeOptions or Subpath on plain
+ # volume mounts. `index` reads such a key as empty instead of failing the inspection.
+ subpaths = ('[{{$sep := ""}}{{range index .HostConfig "Mounts"}}{{$target := index . "Target"}}'
+ '{{$source := index . "Source"}}{{with index . "VolumeOptions"}}'
+ '{{if index . "Subpath"}}{{$sep}}{"Target":{{json $target}},"Source":{{json $source}},'
+ '"Subpath":{{json (index . "Subpath")}}}{{$sep = ","}}{{end}}{{end}}{{end}}]')
+ fmt = ('{"Id":{{json .Id}},"Image":{{json .Image}},"State":{"Status":{{json .State.Status}}},'
+ '"Labels":'+labels+',"Declared":{{json (index .Config "Volumes")}},"Mounts":{{json .Mounts}},'
+ '"SubpathMounts":'+subpaths+'}')
+ records = [json.loads(line) for line in output('inspect', '--format', fmt, *ids).splitlines()] if ids else []
+ if {c['Id'] for c in records} != set(ids):
+ raise ValueError('Container inventory changed during inspection.')
+ for record in records:
+ record['Mounts'] = record['Mounts'] or []
+ record['SubpathMounts'] = record['SubpathMounts'] or []
+ return records
+
+
+def _under(path, root):
+ return path == root or path.is_relative_to(root)
+
+
+def _data_source_tree(source, tree):
+ path = PurePosixPath(source or '')
+ expected = DATA_SOURCE_ROOT / tree
+ return path.is_absolute() and path.parts[-len(expected.parts):] == expected.parts
+
+
+def _validate_box_data_mounts(c, project, *, host_data):
+ subpaths = {}
+ for item in c['SubpathMounts']:
+ target, source, subpath = item.get('Target'), item.get('Source'), item.get('Subpath')
+ if not isinstance(target, str) or not isinstance(source, str) or not isinstance(subpath, str):
+ raise ValueError('Box has an invalid subdirectory mount.')
+ if target in subpaths:
+ raise ValueError('Box has duplicate subdirectory mount metadata.')
+ subpaths[target] = (source, subpath)
+
+ by_target = {}
+ for mount in c['Mounts']:
+ target = mount.get('Destination')
+ if target in BOX_DATA_TARGETS:
+ if target in by_target:
+ raise ValueError(f'Box has duplicate data mounts at {target}.')
+ by_target[target] = mount
+
+ for mount in c['Mounts']:
+ target = PurePosixPath(mount.get('Destination', ''))
+ if any(_under(target, root) for root in BOX_DATA_ROOTS) and str(target) not in BOX_DATA_TARGETS:
+ raise ValueError(f'Box has an unapproved Host-data mount at {target}.')
+ for target in subpaths:
+ if target not in BOX_DATA_TARGETS:
+ raise ValueError(f'Box has an unmanaged subdirectory mount at {target}.')
+
+ if not by_target and not subpaths:
+ return
+ if not host_data or set(by_target) != set(BOX_DATA_TARGETS):
+ raise ValueError('Box Host-data mounts are incomplete or do not belong to the local Host volume.')
+
+ identities = {}
+ for target, tree in BOX_DATA_TARGETS.items():
+ mount = by_target[target]
+ if mount.get('RW') is not True:
+ raise ValueError(f'Box Host-data mount at {target} is not writable.')
+ if mount.get('Type') == 'volume':
+ source = project+'_host-data'
+ expected = str(DATA_SOURCE_ROOT / tree)
+ if mount.get('Name') != source or subpaths.get(target) != (source, expected):
+ raise ValueError(f'Box volume mount at {target} does not select the expected Host-data tree.')
+ identities[target] = ('volume', source, expected)
+ elif mount.get('Type') == 'bind':
+ source = mount.get('Source')
+ if target in subpaths or not _data_source_tree(source, tree):
+ raise ValueError(f'Box bind mount at {target} does not select the expected Host-data tree.')
+ identities[target] = ('bind', source)
+ else:
+ raise ValueError(f'Box Host-data mount at {target} has an unsupported type.')
+
+ for root in BOX_DATA_ROOTS:
+ for tree in DATA_TREES:
+ first = identities[str(root / tree)]
+ for other in BOX_DATA_ROOTS:
+ if identities[str(other / tree)] != first:
+ raise ValueError(f'Box exposes different sources for Host-data tree {tree}.')
+
+
+def project_services(project, services, *, host_data=None):
+ result = {}
+ if host_data is None:
+ host_data = project+'_host-data' in project_volumes(project)
+ for c in inspect_containers(project_ids(project)):
+ labels = c['Labels'] or {}
+ service = labels.get('com.docker.compose.service')
+ if (labels.get('com.docker.compose.project') != project or service not in services or service in result or
+ (labels.get('com.docker.compose.oneoff') or '').lower() == 'true'):
+ raise ValueError('Unexpected or duplicate project container. Resolve it before operating on the instance.')
+ roots = {PurePosixPath(dest) for dest in MOUNTS[service].values()}
+ if any(str(PurePosixPath(item.get('Target', ''))) in MOUNTS[service].values() for item in c['SubpathMounts']):
+ raise ValueError(f'{service} uses a subdirectory instead of the managed volume root; refusing this operation.')
+ if service == 'box':
+ _validate_box_data_mounts(c, project, host_data=host_data)
+ elif c['SubpathMounts']:
+ raise ValueError(f'{service} has an unmanaged subdirectory mount; refusing this operation.')
+ box_data = set(BOX_DATA_TARGETS) if service == 'box' else set()
+ for mount in c['Mounts']:
+ dest = PurePosixPath(mount['Destination'])
+ if dest in roots or str(dest) in box_data:
+ continue
+ if service == 'box' and any(_under(dest, root) for root in BOX_DATA_ROOTS):
+ raise ValueError(f'Unmanaged Host-data mount on box at {dest}; refusing this operation.')
+ # Inherited image VOLUMEs may create anonymous scratch space outside managed data.
+ anonymous = (mount['Type'] == 'volume' and re.fullmatch(r'[0-9a-f]{64}', mount.get('Name', '')) and
+ str(dest) in (c.get('Declared') or {}))
+ if (any(dest.is_relative_to(root) or root.is_relative_to(dest) for root in roots) or
+ (mount['Type'] != 'tmpfs' and not anonymous)):
+ raise ValueError(f'Unmanaged mount on {service} at {dest} would be omitted; refusing this operation.')
+ for suffix, dest in MOUNTS[service].items():
+ mounts = [m for m in c['Mounts'] if m['Destination'] == dest]
+ if (len(mounts) != 1 or mounts[0]['Type'] != 'volume' or mounts[0].get('Name') != project+'_'+suffix
+ or mounts[0].get('RW') is not True):
+ raise ValueError(f'{service}: {dest} is not the expected writable project volume.')
+ if c['State']['Status'] not in ('running', 'paused', 'exited', 'created'):
+ raise ValueError(f'{service} is in a transient or unsupported state; check docker ps before retrying.')
+ result[service] = c
+ return result
+
+
+def verify_users(volumes, containers):
+ ids = {c['Id'] for c in containers.values()}
+ for name in volumes:
+ if volume_users(name) - ids:
+ raise ValueError(f'Another container uses {name}; detach it before taking a project snapshot.')
def sha(path):
@@ -28,60 +351,153 @@ def sha(path):
return result.hexdigest()
-def backup(project, destination, image):
+def backup(project, destination, image, *, stopped=False):
if destination.exists():
raise ValueError('Backup destination exists')
- volumes = output('volume', 'ls', '--filter', f'label=com.docker.compose.project={project}', '--format', '{{.Name}}').splitlines()
- if not volumes:
- raise ValueError('No named Compose volumes found')
- running = output('ps', '--filter', f'label=com.docker.compose.project={project}', '--filter', 'status=running', '--format', '{{.ID}}').splitlines()
+ volumes = project_volumes(project)
+ services = topology(project, volumes)
+ verify_volumes(project, volumes)
+ root = local_lineage(project) if 'host' in services else None
+ containers = project_services(project, services, host_data=project+'_host-data' in volumes)
+ verify_users(volumes, containers)
+ if stopped and any(c['State']['Status'] not in ('created', 'exited') for c in containers.values()):
+ raise ValueError('Upgrade backup requires all project containers to remain stopped.')
destination.mkdir(parents=True, mode=0o700)
paused = []
records = []
try:
- for container in running:
- if output('inspect', container, '--format', '{{.State.Paused}}') == 'false':
- run('pause', container, stdout=subprocess.DEVNULL)
- paused.append(container)
- for volume in volumes:
- if not volume.startswith(project+'_') or not re.fullmatch(r'[A-Za-z0-9_.-]+', volume):
- raise ValueError('Unexpected volume name')
+ for c in containers.values():
+ if c['State']['Status'] == 'running':
+ paused.append(c['Id']) # A failed CLI response does not prove the daemon did not pause it.
+ run('pause', c['Id'], stdout=subprocess.DEVNULL)
+ for volume in sorted(volumes):
path = destination / (volume+'.tar.gz')
with path.open('wb') as target:
- run('run', '--rm', '--network', 'none', '--read-only', '--entrypoint', 'tar', '-v', volume+':/backup:ro', image,
+ run('run', '--rm', '--pull=never', '--network', 'none', '--read-only', '--user', '0:0', '--entrypoint', 'tar',
+ '--mount', f'type=volume,src={volume},dst=/backup,readonly,volume-nocopy', image,
'-czf', '-', '-C', '/backup', '.', stdout=target)
+ os.fsync(target.fileno())
path.chmod(0o600)
records.append({'name': volume, 'suffix': volume[len(project)+1:], 'file': path.name, 'sha256': sha(path), 'bytes': path.stat().st_size})
+ current = project_services(project, services, host_data=project+'_host-data' in volumes)
+ expected = {c['Id']: 'paused' if c['Id'] in paused else c['State']['Status'] for c in containers.values()}
+ if project_volumes(project) != volumes or {c['Id']: c['State']['Status'] for c in current.values()} != expected:
+ raise ValueError('Instance changed during backup; no manifest was published.')
+ verify_users(volumes, current)
finally:
- for container in paused:
- run('unpause', container, stdout=subprocess.DEVNULL)
+ failed = []
+ for container in reversed(paused):
+ try:
+ status = output('inspect', '--format', '{{.State.Status}}', container)
+ if status == 'paused':
+ run('unpause', container, stdout=subprocess.DEVNULL)
+ elif status != 'running':
+ failed.append(container)
+ except (OSError, ValueError, subprocess.SubprocessError):
+ failed.append(container)
+ if failed:
+ raise RuntimeError('Could not resume these containers; check docker ps and unpause them: ' + ', '.join(failed))
manifest = {'schema':'grokbot-volumes/v1', 'project':project, 'image':image,
+ 'lineageRoot': root,
+ 'serviceImages': {s: c['Image'] for s, c in containers.items()},
'at':time.strftime('%Y-%m-%dT%H:%M:%S%z'), 'volumes':records}
- (destination/'manifest.json').write_text(json.dumps(manifest, indent=2)+'\n')
- (destination/'manifest.json').chmod(0o600)
+ tmp = destination/'manifest.tmp'
+ with tmp.open('x', encoding='utf-8') as target:
+ target.write(json.dumps(manifest, indent=2)+'\n')
+ target.flush()
+ os.fsync(target.fileno())
+ tmp.chmod(0o600)
+ tmp.replace(destination/'manifest.json')
+ if os.name == 'posix':
+ fd = os.open(destination, os.O_RDONLY | os.O_DIRECTORY)
+ try:
+ os.fsync(fd)
+ finally:
+ os.close(fd)
print(json.dumps({'backup':str(destination), 'volumes':len(records), 'containersResumed':len(paused)}))
-def restore(source, project, image):
- manifest = json.loads((source/'manifest.json').read_text())
- if manifest.get('schema') != 'grokbot-volumes/v1':
+def read_manifest(source):
+ manifest = json.loads((source/'manifest.json').read_text(encoding='utf-8'))
+ if not isinstance(manifest, dict) or manifest.get('schema') != 'grokbot-volumes/v1':
raise ValueError('Unsupported backup format')
+ origin = manifest.get('project')
+ if not isinstance(origin, str) or not PROJECT_NAME.fullmatch(origin) or not isinstance(manifest.get('volumes'), list):
+ raise ValueError('Invalid backup manifest')
+ root = manifest.get('lineageRoot')
+ if root is not None and (not isinstance(root, str) or not PROJECT_NAME.fullmatch(root)):
+ raise ValueError('Invalid backup lineage metadata')
+ return manifest
+
+
+def restore(source, project, image, *, manifest=None):
+ manifest = read_manifest(source) if manifest is None else manifest
+ origin = manifest['project']
prepared = []
+ suffixes = set()
for record in manifest['volumes']:
- if not re.fullmatch(r'[A-Za-z0-9_.-]+', record['suffix']) or Path(record['file']).name != record['file']:
- raise ValueError('Invalid backup filename')
- path = source/record['file']; name = project+'_'+record['suffix']
- if sha(path) != record['sha256']:
+ suffix = record.get('suffix') if isinstance(record, dict) else None
+ if not isinstance(suffix, str) or not re.fullmatch(r'[a-z0-9-]+', suffix) or suffix in suffixes:
+ raise ValueError('Invalid or duplicate backup volume')
+ suffixes.add(suffix)
+ original = origin+'_'+suffix
+ if record.get('name') != original or record.get('file') != original+'.tar.gz':
+ raise ValueError('Backup filename does not match the recorded volume')
+ path = source/record['file']; name = project+'_'+suffix
+ if not path.is_file() or path.is_symlink() or path.stat().st_size != record.get('bytes') or sha(path) != record.get('sha256'):
raise ValueError('Backup checksum mismatch: '+record['file'])
- exists = subprocess.run([DOCKER, 'volume', 'inspect', name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
- if exists:
- raise ValueError('Restore target already exists: '+name)
- prepared.append((path, name, record['suffix']))
- for path, name, suffix in prepared:
- run('volume','create','--label',f'com.docker.compose.project={project}','--label',f'com.docker.compose.volume={suffix}',name, stdout=subprocess.DEVNULL)
- with path.open('rb') as source_file:
- run('run','--rm','-i','--network','none','--read-only','--entrypoint','tar','-v',name+':/restore',image,
- '-xzf','-','-C','/restore', stdin=source_file)
+ prepared.append((path, name, suffix))
+ topology(origin, {origin+'_'+s for s in suffixes})
+ targets = {n for _, n, _ in prepared}
+ if project_ids(project) or project_volumes(project) or targets.intersection(output('volume', 'ls', '-q').splitlines()):
+ raise ValueError('Restore target already exists; choose a new project.')
+
+ # This extra project volume makes an interrupted restore fail every managed topology check.
+ claim = uuid4().hex
+ guard = project+'_restore-in-progress'
+ created = []
+
+ def reserve(name, suffix):
+ # docker volume create succeeds for an existing name, or may create one then lose the reply.
+ created.append(name)
+ root = manifest.get('lineageRoot')
+ lineage = ['--label', f'{LINEAGE_LABEL}={root}'] if root is not None else []
+ run('volume', 'create', '--label', f'{RESTORE_LABEL}={claim}', '--label', f'com.docker.compose.project={project}',
+ '--label', f'com.docker.compose.volume={suffix}', *lineage, name, stdout=subprocess.DEVNULL)
+ if volume_labels(name).get(RESTORE_LABEL) != claim:
+ raise ValueError('Restore target was created concurrently: '+name)
+
+ try:
+ reserve(guard, 'restore-in-progress')
+ for _, name, suffix in prepared:
+ reserve(name, suffix)
+ for path, name, _ in prepared:
+ if volume_labels(name).get(RESTORE_LABEL) != claim or project_ids(project):
+ raise ValueError('Restore target changed; refusing to write to '+name)
+ verify_users([name], {})
+ with path.open('rb') as source_file:
+ run('run', '--rm', '-i', '--pull=never', '--network', 'none', '--read-only', '--user', '0:0', '--entrypoint', 'tar',
+ '--mount', f'type=volume,src={name},dst=/restore,volume-nocopy', image, '-xzf', '-', '-C', '/restore', stdin=source_file)
+ if project_ids(project) or project_volumes(project) != (targets | {guard}):
+ raise ValueError('Restore target changed during extraction.')
+ verify_users(targets, {})
+ if any(volume_labels(name).get(RESTORE_LABEL) != claim for name in created):
+ raise ValueError('Restore ownership changed during extraction.')
+ run('volume', 'rm', guard, stdout=subprocess.DEVNULL)
+ except (Exception, KeyboardInterrupt):
+ failed = []
+ for name in reversed(created):
+ if name == guard and failed:
+ failed.append(guard)
+ break
+ try:
+ if name in output('volume', 'ls', '-q').splitlines() and volume_labels(name).get(RESTORE_LABEL) == claim:
+ run('volume', 'rm', name, stdout=subprocess.DEVNULL)
+ except (OSError, ValueError, subprocess.SubprocessError):
+ failed.append(name)
+ if failed:
+ raise RuntimeError('Could not verify or clean partial restore volumes; do not start this project: '+', '.join(failed))
+ raise
print(json.dumps({'restoredProject':project,'volumes':len(prepared),'servicesStarted':False}))
@@ -92,13 +508,17 @@ def main():
parser.add_argument('--directory',required=True,type=Path)
parser.add_argument('--image',default='grokbot-host:local')
args=parser.parse_args()
- if not re.fullmatch(r'[a-z0-9][a-z0-9_-]{0,60}',args.project):
+ if not PROJECT_NAME.fullmatch(args.project):
parser.error('Invalid Compose project name')
- if args.operation=='backup':
- backup(args.project,args.directory,args.image)
- else:
- restore(args.directory,args.project,args.image)
+ with project_lock(args.project):
+ if args.operation=='backup':
+ backup(args.project,args.directory,args.image)
+ else:
+ restore(args.directory,args.project,args.image)
if __name__=='__main__':
- main()
+ try:
+ main()
+ except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
+ sys.exit(str(error))
diff --git a/host/release/build-docker.py b/host/release/build-docker.py
index 7ae0f1cbbdcb7a539dda44fd0b4fbf036d8fc596..acec394c43592b53b8b6640f77b5e9836b82c71e 100644
--- a/host/release/build-docker.py
+++ b/host/release/build-docker.py
@@ -3,49 +3,95 @@
import argparse
import hashlib
import json
+import re
from pathlib import Path
import shutil
import subprocess
+import tarfile
import tempfile
import time
import urllib.request
+from bytepatch import file_digest
+from platforms import BOX as BOX_SPEC, INPUTS, check_box_execution, docker_platform
ROOT = Path(__file__).resolve().parents[1]
-BOX = 'public.ecr.aws/k0i0n2g5/cursorenvironments/universal@sha256:73c04dc8722de013fb2ad99366171e3a4c7379f1253d127348a5047d13f0ed41'
-BOX_ID = 'sha256:1bdd316ac812b6647fe1163e97f200b99edb155b97d927727e85dc0c5ea3cd6f'
+BOX = BOX_SPEC['repository'] + '@' + BOX_SPEC['manifestDigest']
+BOX_ID = BOX_SPEC['configDigest']
+BOX_MANIFEST = BOX.split('@', 1)[1]
+# The classic image store reports the config digest as the image ID; the containerd
+# image store (default on new Docker 29+ installs) reports the pinned manifest digest.
+BOX_IDENTITIES = {BOX_ID, BOX_MANIFEST}
+BOX_TAG = BOX_SPEC['localTag']
def run(*args, **kwargs):
subprocess.run(args, check=True, **kwargs)
+def image_id(reference):
+ probe = subprocess.run(['docker', 'image', 'inspect', reference, '--format', '{{.Id}}'], capture_output=True, text=True)
+ return probe.stdout.strip() if probe.returncode == 0 else None
+
+
+def load_verified_archive(path):
+ """Verify a docker-save archive by its config digest, independent of the Docker image store."""
+ with tarfile.open(path, 'r:*') as archive:
+ names = {member.name.lstrip('./'): member for member in archive}
+ entries = json.load(archive.extractfile(names['manifest.json']))
+ if len(entries) != 1:
+ raise ValueError('Box archive must contain exactly one image')
+ config = archive.extractfile(names[entries[0]['Config'].lstrip('./')]).read()
+ if 'sha256:' + hashlib.sha256(config).hexdigest() != BOX_ID:
+ raise ValueError('Unsupported Box archive identity')
+ loaded = subprocess.run(['docker', 'load', '-i', str(path)], check=True, capture_output=True, text=True).stdout
+ match = re.search(r'Loaded image(?: ID)?: (\S+)', loaded)
+ if not match:
+ raise ValueError('Docker did not report the loaded Box image')
+ return match.group(1)
+
+
+def prepare_box(box_archive):
+ if box_archive:
+ source = load_verified_archive(box_archive.resolve())
+ else:
+ source = next((ref for ref in (BOX, BOX_TAG, BOX_ID) if image_id(ref) in BOX_IDENTITIES), None)
+ if not source:
+ run('docker', 'pull', '--platform', BOX_SPEC['platform'], BOX)
+ source = BOX
+ identity = image_id(source)
+ if identity not in BOX_IDENTITIES:
+ raise ValueError('Unsupported Box image identity')
+ run('docker', 'tag', source, BOX_TAG)
+ return identity
+
+
+def choose_runtime(platform, host_only):
+ if platform == 'linux/arm64':
+ return 'grokbot-arm-runtime:local', not host_only
+ return BOX_TAG, True
+
+
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--host-archive', type=Path)
parser.add_argument('--box-archive', type=Path, help='Optional original docker-save tar or tar.gz')
- parser.add_argument('--box-only', action='store_true', help='Prepare the verified Box image for a standalone execution node')
+ modes = parser.add_mutually_exclusive_group()
+ modes.add_argument('--box-only', action='store_true', help='Prepare only the verified desktop')
+ modes.add_argument('--host-only', action='store_true', help='Build a Host for a separate execution node')
parser.add_argument('--image', default='grokbot-host:local')
parser.add_argument('--base-image', default='grokbot-patch-base:local')
args = parser.parse_args()
- manifest = json.loads((ROOT / 'recipes/host/manifest.json').read_text())
+ manifest = INPUTS
started = time.monotonic()
- if args.box_archive:
- run('docker', 'load', '-i', str(args.box_archive.resolve()))
- probe = subprocess.run(['docker', 'image', 'inspect', BOX, '--format', '{{.Id}}'], capture_output=True, text=True)
- if probe.returncode:
- local = subprocess.run(['docker', 'image', 'inspect', BOX_ID, '--format', '{{.Id}}'], capture_output=True, text=True)
- if local.returncode:
- run('docker', 'pull', '--platform', 'linux/amd64', BOX)
- else:
- run('docker', 'tag', BOX_ID, 'grokbot-box-input:9d2ac1b')
- box_image = BOX if subprocess.run(['docker', 'image', 'inspect', BOX], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0 else 'grokbot-box-input:9d2ac1b'
- identity = subprocess.check_output(['docker', 'image', 'inspect', box_image, '--format', '{{.Id}}'], text=True).strip()
- if identity != BOX_ID:
- raise ValueError('Unsupported Box image identity')
- # docker-save archives do not retain registry RepoDigests. Give Compose a
- # verified local tag so offline imports do not trigger another registry pull.
- run('docker', 'tag', identity, 'grokbot-box-input:9d2ac1b')
- box_image = 'grokbot-box-input:9d2ac1b'
+ platform = docker_platform()
+ arm = platform == 'linux/arm64'
+ if arm and args.host_only and args.box_archive:
+ raise ValueError('ARM host-only mode does not use a desktop archive.')
+ if not args.host_only:
+ check_box_execution(platform)
+ runtime_image, needs_box = choose_runtime(platform, args.host_only)
+ identity = prepare_box(args.box_archive) if needs_box else None
+ box_image = BOX_TAG if identity else None
if args.box_only:
print(json.dumps({'boxImage': box_image, 'originalImageId': identity, 'inputSeconds': round(time.monotonic()-started, 3)}))
return
@@ -56,19 +102,26 @@ def main():
archive = work / 'host.tgz'
with urllib.request.urlopen(manifest['archive']['url'], timeout=60) as response, archive.open('wb') as target:
shutil.copyfileobj(response, target)
- if hashlib.sha256(archive.read_bytes()).hexdigest() != manifest['archive']['sha256']:
+ if file_digest(archive) != manifest['archive']['sha256']:
raise ValueError('Unsupported Host archive SHA-256')
input_seconds = time.monotonic()-started
- run('docker', 'build', '--platform', 'linux/amd64', '-f', str(ROOT / 'release/Dockerfile.base'), '-t', args.base_image, str(ROOT))
+ run('docker', 'build', '--platform', platform, '-f', str(ROOT / 'release/Dockerfile.base'), '-t', args.base_image, str(ROOT))
+ if arm:
+ run('docker', 'build', '--platform', platform, '-f', str(ROOT / 'release/Dockerfile.arm-runtime'),
+ '-t', runtime_image, str(ROOT))
base_seconds = time.monotonic()-started-input_seconds
(work / 'inputs').mkdir()
shutil.copy2(archive, work / 'inputs/host.tgz')
- run('docker', 'build', '--platform', 'linux/amd64', '-f', str(ROOT / 'release/Dockerfile.host'),
- '--build-arg', f'PATCH_IMAGE={args.base_image}', '--build-arg', f'BOX_IMAGE={box_image}', '-t', args.image, str(work))
- print(json.dumps({'image': args.image, 'boxImage': box_image, 'inputSeconds': round(input_seconds, 3),
+ run('docker', 'build', '--platform', platform, '-f', str(ROOT / 'release/Dockerfile.host'),
+ '--build-arg', f'PATCH_IMAGE={args.base_image}', '--build-arg', f'RUNTIME_IMAGE={runtime_image}',
+ '--build-arg', f'HOST_REVISION={manifest["archive"]["version"]}', '-t', args.image, str(work))
+ print(json.dumps({'image': args.image, 'platform': platform, 'boxImage': box_image, 'inputSeconds': round(input_seconds, 3),
'baseBuildSeconds': round(base_seconds, 3), 'finalBuildSeconds': round(time.monotonic()-started-input_seconds-base_seconds, 3),
'originalImageId': identity, 'distribution': 'local-only'}))
if __name__ == '__main__':
- main()
+ try:
+ main()
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
+ raise SystemExit(str(error)) from error
diff --git a/host/release/bytepatch.py b/host/release/bytepatch.py
index 862458470cb7951fc036d13c50d03efcf3869926..989a3df4f85581b55ace781c5db730e4d2181a6b 100644
--- a/host/release/bytepatch.py
+++ b/host/release/bytepatch.py
@@ -4,6 +4,7 @@ import argparse
import base64
import gzip
import hashlib
+import io
import json
from pathlib import Path
@@ -15,6 +16,14 @@ def digest(data):
return hashlib.sha256(data).hexdigest()
+def file_digest(path):
+ hasher = hashlib.sha256()
+ with path.open('rb') as stream:
+ for chunk in iter(lambda: stream.read(1024 * 1024), b''):
+ hasher.update(chunk)
+ return hasher.hexdigest()
+
+
def index_source(source, width=32, stride=16):
result = {}
for offset in range(0, len(source) - width + 1, stride):
@@ -69,31 +78,47 @@ def create(source, target, index=None):
return recipe
+class PatchSource:
+ """One immutable input may feed many recipes; each still checks its own pin."""
+ def __init__(self, data):
+ self._source = memoryview(bytes(data))
+ self.sha256 = digest(self._source)
+
+ def write_verified(self, recipe, stream):
+ # The caller owns an unpublished staging stream until the final digest matches.
+ source = self._source
+ if recipe.get('schema') != SCHEMA:
+ raise ValueError('Unsupported patch schema')
+ if len(source) != recipe['sourceBytes'] or self.sha256 != recipe['sourceSha256']:
+ raise ValueError('Unsupported original: SHA-256 mismatch')
+ size = recipe['targetBytes']
+ if type(size) is not int or not 0 <= size <= MAX_BYTES:
+ raise ValueError('Invalid output size')
+ written, hasher = 0, hashlib.sha256()
+ for op in recipe['ops']:
+ if op[0] == 'copy' and len(op) == 3:
+ start, length = op[1:]
+ if type(start) is not int or type(length) is not int or start < 0 or length < 1 or start + length > len(source):
+ raise ValueError('Invalid COPY range')
+ data = source[start:start + length]
+ elif op[0] == 'add' and len(op) == 2:
+ data = base64.b64decode(op[1], validate=True)
+ else:
+ raise ValueError('Invalid patch operation')
+ written += len(data)
+ if written > size:
+ raise ValueError('Patch output overflow')
+ if stream.write(data) != len(data):
+ raise OSError('Incomplete patch output write')
+ hasher.update(data)
+ if written != size or hasher.hexdigest() != recipe['targetSha256']:
+ raise ValueError('Patch output verification failed')
+
+
def apply(source, recipe):
- if recipe.get('schema') != SCHEMA:
- raise ValueError('Unsupported patch schema')
- if len(source) != recipe['sourceBytes'] or digest(source) != recipe['sourceSha256']:
- raise ValueError('Unsupported original: SHA-256 mismatch')
- size = recipe['targetBytes']
- if type(size) is not int or not 0 <= size <= MAX_BYTES:
- raise ValueError('Invalid output size')
- result = bytearray()
- for op in recipe['ops']:
- if op[0] == 'copy' and len(op) == 3:
- start, length = op[1:]
- if type(start) is not int or type(length) is not int or start < 0 or length < 1 or start + length > len(source):
- raise ValueError('Invalid COPY range')
- data = memoryview(source)[start:start + length]
- elif op[0] == 'add' and len(op) == 2:
- data = base64.b64decode(op[1], validate=True)
- else:
- raise ValueError('Invalid patch operation')
- if len(result) + len(data) > size:
- raise ValueError('Patch output overflow')
- result.extend(data)
- if len(result) != size or digest(result) != recipe['targetSha256']:
- raise ValueError('Patch output verification failed')
- return bytes(result)
+ result = io.BytesIO()
+ PatchSource(source).write_verified(recipe, result)
+ return result.getvalue()
def load(path):
diff --git a/host/release/compose.host.yaml b/host/release/compose.host.yaml
index fc18ec2cef5b6a0aefab65040cfef00a41aa1eda..8bc22a02bdb9eff1b2c1212ed3cc889c9b819e2a 100644
--- a/host/release/compose.host.yaml
+++ b/host/release/compose.host.yaml
@@ -2,7 +2,6 @@ name: grokbot-host
services:
host:
image: ${GROKBOT_HOST_IMAGE:-grokbot-host:local}
- platform: linux/amd64
init: true
restart: unless-stopped
ports:
@@ -19,3 +18,5 @@ services:
options: { max-size: "10m", max-file: "3" }
volumes:
host-data:
+ name: ${COMPOSE_PROJECT_NAME}_host-data
+ external: ${PROKBOT_EXISTING_VOLUMES:-false}
diff --git a/host/release/compose.yaml b/host/release/compose.yaml
index 51246f214c135a9fe03a02f4e2185a970cb590f6..76bb6a2a5f36ce083406f70918d0889c89b96c1f 100644
--- a/host/release/compose.yaml
+++ b/host/release/compose.yaml
@@ -2,7 +2,6 @@ name: grokbot
services:
host:
image: ${GROKBOT_HOST_IMAGE:-grokbot-host:local}
- platform: linux/amd64
init: true
restart: unless-stopped
ports:
@@ -12,6 +11,7 @@ services:
GROKBOT_BOX_HOST: box
GROKBOT_VNC_URL: http://box:6080
GROKBOT_FORK_VNC_URL: http://box:6081
+ GROKBOT_HOST_MEMORY_MOUNTS: "1"
TZ: ${TZ:-Asia/Singapore}
volumes:
- host-data:/data
@@ -29,10 +29,37 @@ services:
volumes:
- box-home:/home/box
- box-workspace:/workspace
+ # Keep every mount below RemoteBox.protectedBoxPaths so file-tool checks still apply.
+ - type: volume
+ source: host-data
+ target: /data/runtime/host-data/agents
+ volume: { subpath: runtime/host-data/agents }
+ - type: volume
+ source: host-data
+ target: /data/runtime/host-data/user-memory
+ volume: { subpath: runtime/host-data/user-memory }
+ - type: volume
+ source: host-data
+ target: /data/runtime/host-data/workflows
+ volume: { subpath: runtime/host-data/workflows }
+ - type: volume
+ source: host-data
+ target: /data/runtime/host-data/plugins
+ volume: { subpath: runtime/host-data/plugins }
+ - type: volume
+ source: host-data
+ target: /data/runtime/host-data/managed-skills
+ volume: { subpath: runtime/host-data/managed-skills }
logging:
driver: json-file
options: { max-size: "10m", max-file: "3" }
volumes:
host-data:
+ name: ${COMPOSE_PROJECT_NAME}_host-data
+ external: ${PROKBOT_EXISTING_VOLUMES:-false}
box-home:
+ name: ${COMPOSE_PROJECT_NAME}_box-home
+ external: ${PROKBOT_EXISTING_VOLUMES:-false}
box-workspace:
+ name: ${COMPOSE_PROJECT_NAME}_box-workspace
+ external: ${PROKBOT_EXISTING_VOLUMES:-false}
diff --git a/host/release/data_init.py b/host/release/data_init.py
new file mode 100644
index 0000000000000000000000000000000000000000..52528b78d9b9bcc9f42513374ca53d18d42096f5
--- /dev/null
+++ b/host/release/data_init.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python3
+"""Create the Host data trees that the execution desktop is allowed to see."""
+import argparse
+import json
+import os
+from pathlib import Path
+import sys
+
+from backup import DATA_TREES
+
+UID = 1000
+GID = 1000
+MODE = 0o750
+
+
+def metadata(path, *, uid=UID, gid=GID, mode=MODE):
+ if os.name == 'posix':
+ os.chown(path, uid, gid, follow_symlinks=False)
+ path.chmod(mode, follow_symlinks=False)
+
+
+def ensure_directory(path, *, trusted_root=Path('/data'), uid=UID, gid=GID, mode=MODE):
+ path = Path(path)
+ if not path.is_absolute() or '..' in path.parts:
+ raise ValueError('Host data path must be an absolute path without parent traversal.')
+ trusted_root = Path(trusted_root)
+ if not path.is_relative_to(trusted_root):
+ raise ValueError(f'Host data path must stay below {trusted_root}.')
+ current = trusted_root
+ created = False
+ for part in path.relative_to(trusted_root).parts:
+ current /= part
+ try:
+ info = current.lstat()
+ except FileNotFoundError:
+ current.mkdir(mode=mode)
+ metadata(current, uid=uid, gid=gid, mode=mode)
+ created = True
+ continue
+ if current.is_symlink():
+ raise ValueError(f'Host data path contains a symlink: {current}')
+ if not current.is_dir():
+ raise ValueError(f'Host data path is not a directory: {current}')
+ return created
+
+
+def initialise(host_data, *, trusted_root=Path('/data'), uid=UID, gid=GID, mode=MODE):
+ host_data = Path(host_data)
+ root_created = ensure_directory(host_data, trusted_root=trusted_root, uid=uid, gid=gid, mode=mode)
+ created = []
+ for tree in DATA_TREES:
+ path = host_data / tree
+ if path.exists() and not path.is_dir():
+ raise ValueError(f'Host data tree is not a directory: {path}')
+ if path.is_symlink():
+ raise ValueError(f'Host data tree is a symlink: {path}')
+ if not path.exists():
+ path.mkdir(mode=mode)
+ metadata(path, uid=uid, gid=gid, mode=mode)
+ created.append(tree)
+ return {'rootCreated': root_created, 'created': created, 'trees': list(DATA_TREES)}
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('host_data', type=Path, help='Path to runtime/host-data inside the Host data volume')
+ args = parser.parse_args(argv)
+ print(json.dumps(initialise(args.host_data), sort_keys=True))
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except (OSError, ValueError) as error:
+ raise SystemExit(str(error)) from error
diff --git a/host/release/patch-host.py b/host/release/patch-host.py
index ff64ea0453ffc5b84f82dfcf5e6268392e03e4fe..11b8a340983f623481e712bff715000dde86f5a3 100644
--- a/host/release/patch-host.py
+++ b/host/release/patch-host.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""Prepare the pinned Host locally from an original archive and COPY/ADD patches."""
import argparse
+import hashlib
import json
from pathlib import Path
import shutil
@@ -8,7 +9,7 @@ import tarfile
import tempfile
import time
import urllib.request
-from bytepatch import apply, digest, load
+from bytepatch import PatchSource, file_digest, load
ROOT = Path(__file__).resolve().parents[1]
@@ -33,6 +34,30 @@ def extract(source, destination):
target.chmod(entry.mode & 0o777)
+def verify_reliability_manifest(seed):
+ """Reject generated reliability seeds whose manifest no longer matches them."""
+ directory = seed / 'release-reliability'
+ manifest_path = directory / 'manifest.json'
+ if not manifest_path.exists():
+ return
+ manifest = json.loads(manifest_path.read_text())
+ digest = manifest.get('digest')
+ if not isinstance(digest, str) or len(digest) != 64:
+ raise ValueError('Invalid prepared reliability manifest digest')
+ files = manifest.get('files')
+ if not isinstance(files, list):
+ raise ValueError('Invalid prepared reliability manifest files')
+ for entry in files:
+ if not isinstance(entry, dict) or set(entry) != {'name', 'sha256'}:
+ raise ValueError('Invalid prepared reliability manifest entry')
+ name, expected = entry['name'], entry['sha256']
+ if not isinstance(name, str) or Path(name).name != name or not isinstance(expected, str) or len(expected) != 64:
+ raise ValueError('Invalid prepared reliability manifest entry')
+ actual = hashlib.sha256((directory / name).read_bytes()).hexdigest()
+ if actual != expected:
+ raise ValueError('Prepared reliability manifest mismatch: ' + name)
+
+
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--archive', type=Path, help='User-provided stable Host archive; otherwise download the pinned URL')
@@ -50,11 +75,13 @@ def main():
archive = work / 'host.tgz'
with urllib.request.urlopen(spec['archive']['url'], timeout=60) as response, archive.open('wb') as target:
shutil.copyfileobj(response, target)
- if digest(archive.read_bytes()) != spec['archive']['sha256']:
+ if file_digest(archive) != spec['archive']['sha256']:
raise ValueError('Unsupported original Host archive: SHA-256 mismatch')
download_seconds = time.monotonic() - started
extract(archive, work / 'original')
original = work / 'original' / 'sand-host'
+ if (original / 'version').read_text().strip() != spec['archive']['version']:
+ raise ValueError('Pinned Host revision does not match the archive')
source_cache = {}
seed = work / 'seed'
for record in spec['files']:
@@ -63,11 +90,15 @@ def main():
if any(p.is_absolute() or '..' in p.parts for p in (source_path, target_path)):
raise ValueError('Unsafe patch path')
if record['source'] not in source_cache:
- source_cache[record['source']] = (original / source_path).read_bytes()
+ source_cache[record['source']] = PatchSource((original / source_path).read_bytes())
+ if source_cache[record['source']].sha256 != spec['sourceSha256'][record['source']]:
+ raise ValueError('Pinned Host source digest mismatch: ' + record['source'])
source = source_cache[record['source']]
target = seed / target_path
target.parent.mkdir(parents=True, exist_ok=True)
- target.write_bytes(apply(source, load(ROOT / 'recipes/host' / record['patch'])))
+ with target.open('xb') as output:
+ source.write_verified(load(ROOT / 'recipes/host' / record['patch']), output)
+ verify_reliability_manifest(seed)
args.output.mkdir(mode=0o700)
shutil.move(str(original), str(args.output / 'original'))
shutil.move(str(seed), str(args.output / 'seed'))
diff --git a/host/release/platforms.py b/host/release/platforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..3634e76b51b66e698e346f8686c71eec8783c73c
--- /dev/null
+++ b/host/release/platforms.py
@@ -0,0 +1,37 @@
+"""Deployment platform policy. Detect the Docker daemon, not the CLI machine."""
+import json
+from pathlib import Path
+import subprocess
+
+ROOT = Path(__file__).resolve().parents[1]
+INPUTS = json.loads((ROOT / 'recipes/host/manifest.json').read_text(encoding='utf-8'))
+BOX = INPUTS['box']
+
+
+def host_platform(os_name, architecture):
+ arch = {'amd64': 'amd64', 'x86_64': 'amd64', 'arm64': 'arm64', 'aarch64': 'arm64'}.get(architecture.lower())
+ if os_name.lower() != 'linux' or not arch:
+ raise ValueError(f'Unsupported Docker server: {os_name}/{architecture}. Use 64-bit Linux (amd64 or arm64).')
+ return 'linux/' + arch
+
+
+def docker_platform():
+ result = subprocess.run(['docker', 'info', '--format', '{{.OSType}}/{{.Architecture}}'],
+ check=True, text=True, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL)
+ return host_platform(*result.stdout.strip().split('/', 1))
+
+
+def check_box_execution(platform):
+ if platform == BOX['platform']:
+ return
+ # Probe a real amd64 process before downloading the much larger desktop. No host mounts or privileges.
+ cmd = ['docker', 'run', '--rm', '--platform', BOX['platform'], '--network', 'none', '--read-only',
+ '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', 'busybox:1.37', 'uname', '-m']
+ try:
+ result = subprocess.run(cmd, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=120)
+ except subprocess.TimeoutExpired:
+ raise ValueError('amd64 probe timed out. Check access to busybox:1.37 and binfmt, or choose a separate execution node.') from None
+ if result.returncode or result.stdout.strip() != 'x86_64':
+ detail = result.stderr.strip().splitlines()[-1:] or [result.stdout.strip() or 'no output']
+ raise ValueError('amd64 desktop probe failed: ' + detail[0] + '. Check registry access and Linux '
+ 'binfmt/QEMU x86-64 support, or use a separate amd64 execution node (host-only mode).')
diff --git a/host/runtime/anthropic-messages.mjs b/host/runtime/anthropic-messages.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..60be02234ceccf8e49bd49bad7eb7aad3725b82c
--- /dev/null
+++ b/host/runtime/anthropic-messages.mjs
@@ -0,0 +1,326 @@
+// Anthropic Messages API format for the configured model.
+// The original Harness speaks AI SDK CoreMessages; this module translates them to
+// POST /v1/messages and back, keeping images, documents, tool results and signed thinking.
+import { explicitEffort, fileKind, fileText, mediaUrl, messageParts, ModelRequestError, parseDataUrl, parseEvent,
+ parseToolArguments, postWithFallback, providerError, readSse, reasoningOrigin, reasoningProviderOptions, replayRejected,
+ streamToolCalls, textValue, toolSchema, unsupportedFileNote } from './model-common.mjs';
+
+export const FORMAT = 'anthropic';
+export const ANTHROPIC_VERSION = '2026-10-21';
+const FALLBACK_BETA = 'server-side-fallback-2026-07-01';
+const INTERLEAVED_BETA = 'interleaved-thinking-2025-05-14';
+const BUDGETS = { minimal: 1024, low: 2048, medium: 8192, high: 16384, xhigh: 24576, max: 32000 };
+
+/** Accept a host, a /v1 root or the full /v1/messages URL. */
+export function anthropicEndpoint(baseUrl, resource = 'messages') {
+ const url = new URL(baseUrl);
+ if (!['http:', 'https:'].includes(url.protocol)) throw new TypeError('baseUrl must use HTTP or HTTPS');
+ let path = url.pathname.replace(/\/+$/, '');
+ if (path.endsWith('/messages')) path = path.slice(0, -'/messages'.length);
+ if (!path.endsWith('/v1')) path += '/v1';
+ url.pathname = `${path}/${resource}`;
+ url.search = ''; url.hash = '';
+ return url.href;
+}
+
+/**
+ * Thinking controls differ by generation: Claude 4.6 and later think adaptively and take
+ * an effort level; Claude 3.7 to 4.5 take a thinking budget (Opus 4.5 also takes effort).
+ */
+export function claudeTraits(model) {
+ const id = String(model).toLowerCase();
+ const modern = /claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d{1,2}))?(?![\d.])/.exec(id);
+ const old = /claude-(\d)-(\d)-(opus|sonnet|haiku)/.exec(id);
+ const family = modern?.[1] ?? old?.[3];
+ const version = modern ? Number(modern[2]) + Number(modern[3] ?? 0) / 10 : old ? Number(old[1]) + Number(old[2]) / 10 : NaN;
+ if (!family || !Number.isFinite(version)) return { known: false, adaptive: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'], disable: 'disabled', budget: false, maxOutput: 64_000 };
+ const adaptive = version >= 4.6;
+ const efforts = adaptive ? ['low', 'medium', 'high', ...(version >= 4.7 ? ['xhigh'] : []), 'max']
+ : family === 'opus' && version === 4.5 ? ['low', 'medium', 'high'] : [];
+ // How "no thinking" is expressed: never for always-thinking models.
+ const disable = ['fable', 'mythos'].includes(family) || (family === 'opus' && version >= 5.5) ? 'never'
+ : family === 'sonnet' && version >= 5.5 ? 'between_tools' : adaptive ? 'disabled' : 'omit';
+ return { known: true, family, version, adaptive, efforts, disable, budget: !adaptive && version >= 3.7,
+ maxOutput: adaptive ? 128_000 : family === 'opus' && version < 4.5 ? 32_000 : 64_000,
+ fallbacks: /^claude-(?:opus-5-5|opus-5|fable-5-1|sonnet-5-5)$/.test(id) };
+}
+
+/** The closest supported level: minimal maps to low, unsupported upper levels step down. */
+function supportedEffort(level, efforts) {
+ if (!level || !efforts.length) return undefined;
+ const order = ['low', 'medium', 'high', 'xhigh', 'max'];
+ let index = order.indexOf(level === 'minimal' ? 'low' : level);
+ while (index >= 0 && !efforts.includes(order[index])) index--;
+ return index >= 0 ? order[index] : efforts[0];
+}
+
+/** Request parameters shared by chat, test and review requests. */
+export function anthropicOptions(model, { effort, maxTokens } = {}) {
+ const traits = claudeTraits(model), level = explicitEffort(effort);
+ let limit = Number.isSafeInteger(maxTokens) && maxTokens > 0 ? Math.min(maxTokens, traits.maxOutput) : Math.min(64_000, traits.maxOutput);
+ const options = {};
+ if (level === 'none' && traits.disable !== 'never') {
+ if (traits.disable === 'disabled' || traits.disable === 'between_tools') options.thinking = { type: traits.disable };
+ } else if (traits.adaptive) {
+ options.thinking = { type: 'adaptive', display: 'summarized' };
+ const supported = supportedEffort(level === 'none' ? 'low' : level, traits.efforts);
+ if (supported) options.output_config = { effort: supported };
+ } else if (traits.budget && level && level !== 'none') {
+ limit = Math.max(limit, Math.min(traits.maxOutput, BUDGETS[level] + 4096));
+ options.thinking = { type: 'enabled', budget_tokens: Math.max(1024, Math.min(BUDGETS[level], limit - 2048)) };
+ const supported = supportedEffort(level, traits.efforts);
+ if (supported) options.output_config = { effort: supported };
+ }
+ if (traits.fallbacks) options.fallbacks = 'default';
+ return { max_tokens: limit, ...options };
+}
+
+export function anthropicHeaders(apiKey, { stream = false, body = {} } = {}) {
+ const headers = new Headers({ 'content-type': 'application/json', 'anthropic-version': ANTHROPIC_VERSION });
+ if (stream) headers.set('accept', 'text/event-stream');
+ if (apiKey) headers.set('x-api-key', apiKey);
+ const betas = [...(body.fallbacks ? [FALLBACK_BETA] : []), ...(body.thinking?.type === 'enabled' ? [INTERLEAVED_BETA] : [])];
+ if (betas.length) headers.set('anthropic-beta', betas.join(','));
+ return headers;
+}
+
+function source(url) {
+ const parsed = parseDataUrl(url);
+ if (parsed) return { type: 'base64', media_type: parsed.mediaType, data: parsed.data };
+ if (/^https?:\/\//i.test(url)) return { type: 'url', url };
+ throw new TypeError('Unsupported media URL');
+}
+
+function userBlock(part) {
+ if (part.type === 'text') return part.text ? { type: 'text', text: part.text } : null;
+ if (part.type === 'image') return { type: 'image', source: source(mediaUrl(part)) };
+ if (part.type === 'file') {
+ const kind = fileKind(part);
+ if (kind === 'image') return { type: 'image', source: source(mediaUrl(part, part.mimeType)) };
+ if (kind === 'pdf') return { type: 'document', source: source(mediaUrl(part, part.mimeType)), ...(part.filename ? { title: part.filename } : {}) };
+ if (kind === 'text') return { type: 'document', source: { type: 'text', media_type: 'text/plain', data: fileText(part) }, ...(part.filename ? { title: part.filename } : {}) };
+ return { type: 'text', text: unsupportedFileNote(part) };
+ }
+ throw new TypeError(`Unsupported user content type: ${part.type}`);
+}
+
+/** Thinking that Anthropic wrote; other formats' reasoning is not replayed here. */
+function anthropicReasoning(part, providerId) {
+ const origin = reasoningOrigin(part);
+ // Response model IDs can differ from configured aliases (date snapshots or
+ // gateways rewriting the name), but signed Anthropic thinking is still valid
+ // for the same provider. API format and provider identity remain isolation
+ // boundaries.
+ if (origin.providerId && providerId && origin.providerId !== providerId) return false;
+ if (origin.format) return origin.format === FORMAT;
+ if (part.type === 'reasoning') return Boolean(part.signature) && !origin.summarized;
+ return !origin.model || /claude/i.test(origin.model);
+}
+
+/**
+ * Convert CoreMessages. Signed thinking is replayed only when every Anthropic reasoning
+ * part still carries its signature; otherwise all thinking is stripped, which the API
+ * accepts, instead of sending a history with blocks missing from the middle.
+ */
+export function convertAnthropicMessages(messages, { model, providerId, stripThinking = false } = {}) {
+ const reasoningParts = messages.filter(message => message.role === 'assistant' && Array.isArray(message.content))
+ .flatMap(message => message.content.filter(part => (part.type === 'reasoning' || part.type === 'redacted-reasoning') && anthropicReasoning(part, providerId)));
+ const replayThinking = !stripThinking && reasoningParts.every(part =>
+ part.type === 'redacted-reasoning' ? typeof part.data === 'string' && part.data : typeof part.signature === 'string' && part.signature);
+ const system = [], output = [];
+ let leading = true;
+ const push = (role, content) => {
+ const blocks = content.filter(Boolean);
+ if (!blocks.length) return;
+ const previous = output.at(-1);
+ if (previous?.role === role) previous.content.push(...blocks);
+ else output.push({ role, content: blocks });
+ };
+ for (const message of messages) {
+ const parts = messageParts(message);
+ if (message.role === 'system' || message.role === 'developer') {
+ const text = parts.filter(part => part.type === 'text').map(part => part.text).join('');
+ if (!text) continue;
+ if (leading) system.push({ type: 'text', text });
+ // Later operator text stays in order as user-visible context.
+ else push('user', [{ type: 'text', text: `\n${text}\n` }]);
+ continue;
+ }
+ leading = false;
+ if (message.role === 'user') {
+ push('user', parts.map(userBlock));
+ } else if (message.role === 'assistant') {
+ push('assistant', parts.map(part => {
+ if (part.type === 'text') return part.text ? { type: 'text', text: part.text } : null;
+ if (part.type === 'reasoning') return replayThinking && anthropicReasoning(part, providerId) ? { type: 'thinking', thinking: part.text ?? '', signature: part.signature } : null;
+ if (part.type === 'redacted-reasoning') {
+ if (!replayThinking || !anthropicReasoning(part, providerId)) return null;
+ return reasoningOrigin(part).emptyThinking ? { type: 'thinking', thinking: '', signature: part.data } : { type: 'redacted_thinking', data: part.data };
+ }
+ if (part.type === 'tool-call') return { type: 'tool_use', id: part.toolCallId, name: part.toolName,
+ input: typeof part.args === 'string' ? JSON.parse(part.args || '{}') : part.args ?? {} };
+ return null;
+ }));
+ } else if (message.role === 'tool') {
+ push('user', parts.map(part => {
+ if (part.type !== 'tool-result' || !part.toolCallId) throw new TypeError('Tool messages require tool-result parts and toolCallId');
+ const extra = part.experimental_content ?? [];
+ const text = part.result === undefined
+ ? extra.filter(item => item.type === 'text').map(item => item.text).join('\n') : textValue(part.result);
+ const content = [...(text ? [{ type: 'text', text }] : []),
+ ...extra.filter(item => item.type === 'image').map(item => ({ type: 'image', source: source(mediaUrl(item)) }))];
+ return { type: 'tool_result', tool_use_id: part.toolCallId, content: content.length ? content : [{ type: 'text', text: '(empty)' }],
+ ...(part.isError ? { is_error: true } : {}) };
+ }));
+ } else {
+ throw new TypeError(`Unsupported message role: ${message.role}`);
+ }
+ }
+ // Tool results must lead the user turn that answers a tool call.
+ for (const message of output) {
+ if (message.role === 'user') message.content.sort((a, b) => (a.type === 'tool_result' ? 0 : 1) - (b.type === 'tool_result' ? 0 : 1));
+ }
+ if (output[0]?.role === 'assistant') output.unshift({ role: 'user', content: [{ type: 'text', text: '(conversation start)' }] });
+ // Two cache breakpoints: tools + system, and the whole history for the next turn.
+ if (system.length) system.at(-1).cache_control = { type: 'ephemeral' };
+ const lastBlock = output.at(-1)?.content.at(-1);
+ if (lastBlock && ['text', 'image', 'document', 'tool_result'].includes(lastBlock.type)) lastBlock.cache_control = { type: 'ephemeral' };
+ return { system, messages: output, replayedThinking: replayThinking && reasoningParts.length > 0 };
+}
+
+export function convertAnthropicTools(tools = []) {
+ return tools.map(tool => {
+ const { name, description, parameters } = toolSchema(tool);
+ return { name, description, input_schema: parameters };
+ });
+}
+
+/** Normalize Anthropic usage to the OpenAI-style fields the usage ledger records. */
+export function anthropicUsage(raw = {}) {
+ const count = value => Number.isFinite(value) && value >= 0 ? value : 0;
+ const uncached = count(raw.input_tokens), cacheRead = count(raw.cache_read_input_tokens),
+ cacheWrite = count(raw.cache_creation_input_tokens), output = count(raw.output_tokens);
+ const input = uncached + cacheRead + cacheWrite;
+ return { prompt_tokens: input, completion_tokens: output, total_tokens: input + output,
+ prompt_tokens_details: { cached_tokens: cacheRead }, cache_creation_input_tokens: cacheWrite,
+ completion_tokens_details: { reasoning_tokens: count(raw.output_tokens_details?.thinking_tokens) } };
+}
+
+/** True for a 400 caused by thinking blocks that no longer match their conversation. */
+export function isThinkingReplayError(status, message) {
+ return replayRejected({ status, message });
+}
+
+const OPTIONAL = ['fallbacks', 'thinking.display', 'output_config'];
+
+/** One streamed Messages API turn; yields Harness stream parts and returns the assembled message. */
+export async function* anthropicTurn(context) {
+ const { fetchImpl, endpoint, apiKey, headers, model, messages, tools, effort, maxTokens, signal, waitForIO, state,
+ providerId, notifyRequest, onModel, onId, onUsage } = context;
+ const anthropicTools = convertAnthropicTools(tools);
+ let replayed = false;
+ const { http } = await postWithFallback({ fetchImpl, url: endpoint, apiKey, signal, waitForIO, state, optional: OPTIONAL,
+ headers: body => {
+ const value = anthropicHeaders(apiKey, { stream: true, body });
+ for (const [key, entry] of new Headers(headers)) value.set(key, entry);
+ return value;
+ },
+ // Signed thinking from an edited or summarized history: retry without it.
+ fallbacks: [{ name: 'retry without replayed thinking', applies: error => replayed && replayRejected(error), apply: () => { state.stripReasoning = true; } }],
+ build: () => {
+ const converted = convertAnthropicMessages(messages, { model, providerId, stripThinking: state.stripReasoning });
+ replayed = converted.replayedThinking;
+ return { model, ...anthropicOptions(model, { effort, maxTokens }), stream: true,
+ ...(converted.system.length ? { system: converted.system } : {}), messages: converted.messages,
+ ...(anthropicTools.length ? { tools: anthropicTools } : {}) };
+ } });
+ notifyRequest(http.headers.get('request-id') ?? http.headers.get('x-request-id'));
+ let id, responseModel = model, stopReason, stopDetails, stopped = false;
+ const rawUsage = {}, blocks = new Map();
+ const reasoningOptions = () => ({ providerOptions: reasoningProviderOptions({ format: FORMAT, model: responseModel, providerId }) });
+ const emptyOptions = () => ({ providerOptions: reasoningProviderOptions({ format: FORMAT, model: responseModel, providerId, emptyThinking: true }) });
+ const mergeUsage = usage => {
+ if (!usage) return;
+ for (const [key, value] of Object.entries(usage)) if (value !== null && value !== undefined) rawUsage[key] = value;
+ onUsage(anthropicUsage(rawUsage));
+ };
+ for await (const data of readSse(http.body, { waitForIO })) {
+ signal.throwIfAborted();
+ const event = parseEvent(data);
+ if (event.type === 'error') throw providerError(event, undefined, http.headers, apiKey);
+ if (event.type === 'message_start') {
+ const message = event.message ?? {};
+ if (message.id) { id = message.id; onId(id); notifyRequest(id); }
+ if (message.model) { responseModel = message.model; onModel(responseModel); }
+ mergeUsage(message.usage);
+ } else if (event.type === 'content_block_start') {
+ const block = event.content_block ?? {};
+ if (block.type === 'text') {
+ blocks.set(event.index, { type: 'text', text: block.text ?? '' });
+ if (block.text) yield { type: 'text-delta', textDelta: block.text };
+ } else if (block.type === 'thinking') {
+ blocks.set(event.index, { type: 'reasoning', text: block.thinking ?? '', signature: block.signature ?? '' });
+ if (block.thinking) yield { type: 'reasoning', textDelta: block.thinking, ...reasoningOptions() };
+ } else if (block.type === 'redacted_thinking') {
+ blocks.set(event.index, { type: 'redacted-reasoning', data: block.data ?? '' });
+ if (block.data) yield { type: 'redacted-reasoning', data: block.data, ...reasoningOptions() };
+ } else if (block.type === 'tool_use') {
+ blocks.set(event.index, { type: 'tool-use', id: block.id ?? '', name: block.name ?? '', input: block.input, json: '' });
+ }
+ } else if (event.type === 'content_block_delta') {
+ const block = blocks.get(event.index), delta = event.delta ?? {};
+ if (!block) continue;
+ if (delta.type === 'text_delta' && block.type === 'text' && delta.text) {
+ block.text += delta.text;
+ yield { type: 'text-delta', textDelta: delta.text };
+ } else if (delta.type === 'thinking_delta' && block.type === 'reasoning' && delta.thinking) {
+ block.text += delta.thinking;
+ yield { type: 'reasoning', textDelta: delta.thinking, ...reasoningOptions() };
+ } else if (delta.type === 'signature_delta' && block.type === 'reasoning') {
+ block.signature += delta.signature ?? '';
+ } else if (delta.type === 'input_json_delta' && block.type === 'tool-use') {
+ block.json += delta.partial_json ?? '';
+ }
+ } else if (event.type === 'content_block_stop') {
+ const block = blocks.get(event.index);
+ // The Harness keeps reasoning only with readable text; a signed block without text
+ // travels as a redacted part holding its signature and is restored on replay.
+ if (block?.type === 'reasoning' && block.signature) {
+ if (block.text) yield { type: 'reasoning-signature', signature: block.signature };
+ else yield { type: 'redacted-reasoning', data: block.signature, ...emptyOptions() };
+ }
+ } else if (event.type === 'message_delta') {
+ if (event.delta?.stop_reason) stopReason = event.delta.stop_reason;
+ if (event.delta?.stop_details) stopDetails = event.delta.stop_details;
+ mergeUsage(event.usage);
+ } else if (event.type === 'message_stop') {
+ stopped = true;
+ break;
+ }
+ }
+ signal.throwIfAborted();
+ if (stopReason === 'max_tokens') throw new ModelRequestError('Model response stopped with max_tokens', { code: 'length' });
+ if (stopReason === 'model_context_window_exceeded') throw new ModelRequestError('Model context window exceeded', { code: 'context_length_exceeded' });
+ if (stopReason === 'refusal') {
+ const category = stopDetails?.category ? ` (${stopDetails.category})` : '';
+ throw new ModelRequestError(`Model declined this request${category}`, { code: 'content_filter' });
+ }
+ if (!stopped || !stopReason) throw new ModelRequestError('Model SSE stream ended before a completion marker');
+ if (!['end_turn', 'stop_sequence', 'tool_use'].includes(stopReason)) throw new ModelRequestError(`Unsupported model stop reason: ${stopReason}`);
+ const content = [], calls = [];
+ for (const [, block] of [...blocks.entries()].sort(([a], [b]) => a - b)) {
+ if (block.type === 'text') { if (block.text) content.push(block); continue; }
+ if (block.type === 'reasoning' && !block.text) {
+ if (block.signature) content.push({ type: 'redacted-reasoning', data: block.signature, ...emptyOptions() });
+ continue;
+ }
+ if (block.type === 'reasoning' || block.type === 'redacted-reasoning') { content.push({ ...block, ...reasoningOptions() }); continue; }
+ if (!block.id || !block.name) throw new ModelRequestError('Incomplete model tool call identity');
+ const call = { type: 'tool-call', toolCallId: block.id, toolName: block.name,
+ args: parseToolArguments(block.name, block.json || JSON.stringify(block.input)) };
+ calls.push(call); content.push(call);
+ }
+ if ((stopReason === 'tool_use') !== Boolean(calls.length)) throw new ModelRequestError('Model tool calls do not match the stop reason');
+ yield* streamToolCalls(calls, messages, signal);
+ return { id, model: responseModel, content, toolCalls: calls.length, usage: anthropicUsage(rawUsage) };
+}
diff --git a/host/runtime/codex-prompt.mjs b/host/runtime/codex-prompt.mjs
index 8bdc6ad1371a7ae20b346468ab9f0dc813c66740..298d9113c57d0d0367d591bedcee7894c2aae706 100644
--- a/host/runtime/codex-prompt.mjs
+++ b/host/runtime/codex-prompt.mjs
@@ -1,9 +1,9 @@
/** Applied to both standard and slim prompt sections; official CloudAgent stays disabled. */
export const codexCodingGuidance = [
- 'For non-trivial coding work (implementing features, fixing bugs, refactoring, or broad repository investigation), delegate to Codex on a connected Mac. Discover the paired Mac codex_start, codex_status, codex_continue, codex_cancel and codex_list tools through your dynamic MCP tool catalog. The official CloudAgent service is not used.',
- 'Pass a clear task, relevant context, constraints and success criteria. Use an existing absolute project directory on the selected Mac, or omit cwd for a new isolated project. Codex uses the account and default model configured on that Mac. It may obtain a repository checkout inside the task directory when required by the user’s coding request.',
- 'codex_start returns a job ID before the task finishes. Use codex_status with waitMs:25000 to wait for progress and completion; keep the user informed and do not report success until status is completed and the result is checked. Continue the same job with codex_continue for follow-up work. Use codex_cancel when the user stops it. A disconnected Mac or interrupted task is not a completed task.',
- 'Keep the returned Mac, job and project identifiers together. Jobs and results belong to this Bot on that Mac. When Codex requests user input, ask the user and supply their actual answers. Mac local execution permissions still apply. If no Codex-capable Mac is connected, explain that it must be connected or Codex installed/signed in; do not substitute an unavailable official CloudAgent or launch Codex through a shell command.',
+ 'For non-trivial coding work (implementing features, fixing bugs, refactoring, or broad repository investigation), delegate to Codex on a connected computer. Discover the paired computer’s codex_start, codex_status, codex_continue, codex_cancel and codex_list tools through your dynamic MCP tool catalog. The official CloudAgent service is not used.',
+ 'Pass a clear task, relevant context, constraints and success criteria. Use an existing absolute project directory on the selected computer, in that computer’s path syntax, or omit cwd for a new isolated project. Codex uses the account and default model configured on that computer. It may obtain a repository checkout inside the task directory when required by the user’s coding request.',
+ 'codex_start returns a job ID before the task finishes. Use codex_status with waitMs:25000 to wait for progress and completion; keep the user informed and do not report success until status is completed and the result is checked. Continue the same job with codex_continue for follow-up work. Use codex_cancel when the user stops it. A disconnected computer or interrupted task is not a completed task.',
+ 'Keep the returned computer, job and project identifiers together. Jobs and results belong to this Bot on that computer. When Codex requests user input, ask the user and supply their actual answers. Local execution permissions on that computer still apply. If no Codex-capable computer is connected, explain that it must be connected or Codex installed/signed in; do not substitute an unavailable official CloudAgent or launch Codex through a shell command.',
];
export function localCodexSection(section, options) {
@@ -12,7 +12,7 @@ export function localCodexSection(section, options) {
if (section.heading !== '## Where you work') return section;
return { ...section, body: section.body.map(line => {
if (!line.includes('Repository work')) return line;
- return line.slice(0, line.indexOf('Repository work')) + 'Repository coding work uses the connected Mac Codex tools described in Code changes.';
+ return line.slice(0, line.indexOf('Repository work')) + 'Repository coding work uses the connected computer Codex tools described in Code changes.';
}) };
}
diff --git a/host/runtime/config.mjs b/host/runtime/config.mjs
index 48132d80f99ec946b2bb77a8f339f4aa9ce96787..ebab10f858c05034395ce92d773ac6383a3cc27c 100644
--- a/host/runtime/config.mjs
+++ b/host/runtime/config.mjs
@@ -1,27 +1,58 @@
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
-import { parseModelPolicy } from './model-policy.mjs';
+import { defaultPolicy, parseModelPolicy } from './model-policy.mjs';
+import { API_FORMATS, MODEL_ROUTING_ENV, modelRouteForAgent, parseModelRouting } from './model-routing.mjs';
export const root = resolve(import.meta.dirname, '..');
-export async function loadModelConfig({ env = process.env } = {}) {
- const path = env.GROKBOT_MODEL_ENV ?? resolve(root, '.runtime/model.env');
- const file = await readFile(path, 'utf8');
- const values = Object.fromEntries(file.split(/\r?\n/).filter(line => line && !line.startsWith('#'))
+
+function envValues(source) {
+ return Object.fromEntries(source.split(/\r?\n/).filter(line => line && !line.startsWith('#') && line.includes('='))
.map(line => { const i = line.indexOf('='); return [line.slice(0, i), line.slice(i + 1)]; }));
- if (!values.OPENAI_BASE_URL || !values.OPENAI_API_KEY) throw new Error('Missing model configuration');
- const capacity = String(env.OPENAI_CONTEXT_WINDOW_TOKENS ?? values.OPENAI_CONTEXT_WINDOW_TOKENS ?? '').trim();
- const contextWindowTokens = capacity === '' ? 0 : Number(capacity);
- if ((capacity !== '' && !/^\d+$/.test(capacity)) || !Number.isSafeInteger(contextWindowTokens)) {
+}
+
+function contextCapacity(value) {
+ const capacity = String(value ?? '').trim();
+ const parsed = capacity === '' ? 0 : Number(capacity);
+ if ((capacity !== '' && !/^\d+$/.test(capacity)) || !Number.isSafeInteger(parsed))
throw new Error('OPENAI_CONTEXT_WINDOW_TOKENS must be a nonnegative safe integer');
- }
+ return parsed;
+}
+
+function legacyConfig(values, env) {
+ const model = env.GROKBOT_MODEL ?? values.OPENAI_MODEL ?? 'deepseek-v4.1-flash';
return {
baseUrl: values.OPENAI_BASE_URL,
apiKey: values.OPENAI_API_KEY,
- model: env.GROKBOT_MODEL ?? values.OPENAI_MODEL ?? 'deepseek-v4.1-flash',
- contextWindowTokens,
- policy: parseModelPolicy(values.GROKBOT_MODEL_POLICY, env.GROKBOT_MODEL ?? values.OPENAI_MODEL),
+ apiFormat: API_FORMATS.includes(values.MODEL_API_FORMAT) ? values.MODEL_API_FORMAT : 'openai',
+ model,
+ contextWindowTokens: contextCapacity(env.OPENAI_CONTEXT_WINDOW_TOKENS ?? values.OPENAI_CONTEXT_WINDOW_TOKENS),
+ policy: parseModelPolicy(values.GROKBOT_MODEL_POLICY, model),
jevApiKey: values.JEV_API_KEY || '',
+ };
+}
+
+export async function loadModelConfig({ env = process.env } = {}) {
+ const path = env.GROKBOT_MODEL_ENV ?? resolve(root, '.runtime/model.env');
+ const values = envValues(await readFile(path, 'utf8'));
+ const legacy = legacyConfig(values, env);
+ const common = {
+ jevApiKey: legacy.jevApiKey,
usageDirectory: resolve(env.GROKBOT_DATA_DIR ?? resolve(path, '..'), 'usage'),
routingDirectory: resolve(env.GROKBOT_DATA_DIR ?? resolve(path, '..'), 'routing'),
};
+ if (!values[MODEL_ROUTING_ENV]) {
+ if (!legacy.baseUrl || !legacy.apiKey) throw new Error('Missing model configuration');
+ return { ...legacy, ...common, modelBaseUrls: [legacy.baseUrl] };
+ }
+ const { config: modelRouting } = parseModelRouting(values[MODEL_ROUTING_ENV], legacy);
+ const route = modelRouteForAgent(modelRouting);
+ if (!route.baseUrl || !route.apiKey || !route.model) throw new Error('Missing model configuration');
+ // Auto-review intentionally remains on the global primary route. It does not inherit a Bot's
+ // fallback chain because approval decisions should not change provider halfway through a review.
+ const policy = defaultPolicy(route.model);
+ policy.models = [{ id: route.model, efforts: route.efforts,
+ contextWindowTokens: route.contextWindowTokens, summaryThresholdTokens: route.summaryThresholdTokens }];
+ return { ...common, modelRouting, baseUrl: route.baseUrl, apiKey: route.apiKey, apiFormat: route.apiFormat,
+ model: route.model, contextWindowTokens: route.contextWindowTokens, policy,
+ modelBaseUrls: [...new Set(modelRouting.providers.map(provider => provider.baseUrl))] };
}
diff --git a/host/runtime/host-auto-review.mjs b/host/runtime/host-auto-review.mjs
index 66197be2d46308e625e74f514239b93871630361..35fcc714aed3308e01d88a0c5ba4f6e89eae3b30 100644
--- a/host/runtime/host-auto-review.mjs
+++ b/host/runtime/host-auto-review.mjs
@@ -1,10 +1,105 @@
import { randomUUID } from 'node:crypto';
import { recordUsage } from './usage-ledger.mjs';
+import { anthropicEndpoint, anthropicHeaders, anthropicOptions, anthropicUsage } from './anthropic-messages.mjs';
+import { chatEndpoint, chatReasoning, maxTokensParameter } from './openai-chat.mjs';
+import { reasons, responsesEndpoint, responsesUsage } from './openai-responses.mjs';
+import { postWithFallback } from './model-common.mjs';
+
+const OUTPUT_LIMIT = 16_000;
+// Classification needs little reasoning; use the lowest level the model offers.
+function reviewEffort(config) {
+ const efforts = config.policy?.models?.find(entry => entry.id === config.model)?.efforts ?? [];
+ return ['low', 'minimal', 'medium'].find(level => efforts.includes(level));
+}
+/** The model answered, but not with one valid classification; worth one more attempt. */
+class ReviewOutputError extends Error {}
+const forcedChoiceRejected = error => error.status === 400 && /tool_choice|tool choice/i.test(error.message);
+const onlyTool = name => `\n\nRespond only by calling the ${name} tool exactly once.`;
+
+function single(calls, name, truncated) {
+ if (truncated || calls.length !== 1 || calls[0].name !== name) throw new ReviewOutputError('Auto-review model did not return one complete classification');
+ if (typeof calls[0].arguments !== 'string') return calls[0].arguments;
+ try { return JSON.parse(calls[0].arguments); }
+ catch { throw new ReviewOutputError('Auto-review model returned invalid JSON'); }
+}
+
+async function classifyWithChat(config, library, tool, content, signal, fetchImpl, state) {
+ let forced = !state.autoToolChoice;
+ const { http } = await postWithFallback({ fetchImpl, url: chatEndpoint(config.baseUrl), apiKey: config.apiKey, signal, state,
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${config.apiKey}` },
+ optional: ['reasoning_effort', 'thinking', 'parallel_tool_calls', 'max_tokens', 'max_completion_tokens'],
+ fallbacks: [{ name: 'automatic tool choice', applies: error => forced && forcedChoiceRejected(error), apply: () => { forced = false; state.autoToolChoice = true; } }],
+ build: () => {
+ const limit = maxTokensParameter(config.model, state.dropped);
+ return { model: config.model, stream: false, ...chatReasoning(config.model, reviewEffort(config)), ...(limit ? { [limit]: OUTPUT_LIMIT } : {}),
+ messages: [{ role: 'system', content: library.SAND_AUTO_REVIEW_CLASSIFIER_SYSTEM_PROMPT + (forced ? '' : onlyTool(tool.function.name)) },
+ { role: 'user', content }], tools: [tool], parallel_tool_calls: false,
+ tool_choice: forced ? { type: 'function', function: { name: tool.function.name } } : 'auto' };
+ } });
+ const reply = await http.json();
+ await recordUsage(config.usageDirectory, { raw: reply.usage, model: reply.model ?? config.model, kind: 'review', requestId: reply.id });
+ const calls = (reply.choices?.[0]?.message?.tool_calls ?? []).map(call => ({ name: call.function?.name, arguments: call.function?.arguments }));
+ return { id: reply.id, decision: single(calls, tool.function.name, reply.choices?.[0]?.finish_reason === 'length') };
+}
+
+async function classifyWithResponses(config, library, tool, content, signal, fetchImpl, state) {
+ let forced = !state.autoToolChoice;
+ const efforts = config.policy?.models?.find(entry => entry.id === config.model)?.efforts, effort = reviewEffort(config);
+ const { http } = await postWithFallback({ fetchImpl, url: responsesEndpoint(config.baseUrl), apiKey: config.apiKey, signal, state,
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${config.apiKey}` },
+ optional: ['reasoning.effort', 'reasoning', 'parallel_tool_calls', 'store', 'max_output_tokens'],
+ fallbacks: [{ name: 'automatic tool choice', applies: error => forced && forcedChoiceRejected(error), apply: () => { forced = false; state.autoToolChoice = true; } }],
+ build: () => ({ model: config.model, store: false, max_output_tokens: OUTPUT_LIMIT,
+ ...(reasons(efforts) && effort ? { reasoning: { effort } } : {}),
+ instructions: library.SAND_AUTO_REVIEW_CLASSIFIER_SYSTEM_PROMPT + (forced ? '' : onlyTool(tool.function.name)),
+ input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: content }] }],
+ tools: [{ type: 'function', name: tool.function.name, description: tool.function.description ?? '', parameters: tool.function.parameters, strict: false }],
+ parallel_tool_calls: false, tool_choice: forced ? { type: 'function', name: tool.function.name } : 'auto' }) });
+ const reply = await http.json();
+ await recordUsage(config.usageDirectory, { raw: responsesUsage(reply.usage), model: reply.model ?? config.model, kind: 'review', requestId: reply.id });
+ const calls = (reply.output ?? []).filter(item => item.type === 'function_call');
+ return { id: reply.id, decision: single(calls, tool.function.name, reply.status === 'incomplete') };
+}
+
+/** Messages API classification. Forced tool choice is unavailable on current Claude models. */
+async function classifyWithAnthropic(config, library, tool, content, signal, fetchImpl, state) {
+ const { http } = await postWithFallback({ fetchImpl, url: anthropicEndpoint(config.baseUrl), apiKey: config.apiKey, signal, state,
+ headers: body => anthropicHeaders(config.apiKey, { body }), optional: ['fallbacks', 'thinking.display', 'output_config'],
+ build: () => ({ model: config.model, ...anthropicOptions(config.model, { effort: reviewEffort(config) ?? 'low', maxTokens: OUTPUT_LIMIT }),
+ system: library.SAND_AUTO_REVIEW_CLASSIFIER_SYSTEM_PROMPT + onlyTool(tool.function.name),
+ messages: [{ role: 'user', content }], tool_choice: { type: 'auto', disable_parallel_tool_use: true },
+ tools: [{ name: tool.function.name, description: tool.function.description ?? '', input_schema: tool.function.parameters }] }) });
+ const reply = await http.json();
+ await recordUsage(config.usageDirectory, { raw: anthropicUsage(reply.usage), model: reply.model ?? config.model, kind: 'review', requestId: reply.id });
+ const calls = (reply.content ?? []).filter(block => block.type === 'tool_use').map(block => ({ name: block.name, arguments: block.input }));
+ return { id: reply.id, decision: single(calls, tool.function.name, reply.stop_reason === 'max_tokens') };
+}
+
+const CLASSIFIERS = { openai: classifyWithChat, 'openai-responses': classifyWithResponses, anthropic: classifyWithAnthropic };
+
+function validate(decision, schema) {
+ if (!decision || typeof decision !== 'object' || Array.isArray(decision)) throw new ReviewOutputError('Invalid auto-review classification');
+ for (const name of schema.required) {
+ if (typeof decision[name] !== 'string' || !decision[name].trim() ||
+ (schema.properties[name].enum && !schema.properties[name].enum.includes(decision[name])))
+ throw new ReviewOutputError(`Invalid auto-review classification field: ${name}`);
+ }
+ if (decision.decision === 'BLOCK' && decision.blocked_effect === 'none')
+ throw new ReviewOutputError('Auto-review returned an inconsistent decision');
+ const outbound = ['outbound_or_binding_external_effect', 'data_or_credential_exfiltration'].includes(decision.blocked_effect);
+ if (decision.decision === 'BLOCK' && outbound &&
+ (decision.outbound_authorization !== 'unauthorized_destination' || !decision.who_sees_it?.trim()))
+ throw new ReviewOutputError('Auto-review returned an incomplete outbound decision');
+ if (decision.proposed_allow_rule !== undefined && typeof decision.proposed_allow_rule !== 'string')
+ throw new ReviewOutputError('Invalid auto-review proposed rule');
+}
/** Use the shipped classifier policy/schema and approval state machine with the configured model. */
export function createLocalClassifier(config, library, { fetchImpl = globalThis.fetch, log = () => {} } = {}) {
const tool = library.CLASSIFY_SAND_AUTO_REVIEW_ACTION_TOOL;
const schema = tool.function.parameters;
+ // Parameters a compatible service rejected stay dropped for later reviews.
+ const state = { dropped: new Set(), autoToolChoice: false };
return {
async execute(ctx, args) {
const target = args.target?.toJson ? args.target.toJson() : args.target;
@@ -20,41 +115,22 @@ export function createLocalClassifier(config, library, { fetchImpl = globalThis.
const content = JSON.stringify(input);
if (Buffer.byteLength(content) > 1024 * 1024) throw new Error('Auto-review context exceeds the supported size');
const signal = ctx?.signal ? AbortSignal.any([ctx.signal, AbortSignal.timeout(45_000)]) : AbortSignal.timeout(45_000);
- const response = await fetchImpl(`${config.baseUrl.replace(/\/$/, '')}/chat/completions`, {
- method: 'POST', redirect: 'error', signal,
- headers: { 'content-type': 'application/json', authorization: `Bearer ${config.apiKey}` },
- body: JSON.stringify({ model: config.model, stream: false, max_tokens: 4096,
- messages: [{ role: 'system', content: library.SAND_AUTO_REVIEW_CLASSIFIER_SYSTEM_PROMPT },
- { role: 'user', content }], tools: [tool],
- tool_choice: { type: 'function', function: { name: tool.function.name } }, parallel_tool_calls: false }),
- });
- if (!response.ok) {
- await response.body?.cancel();
- throw new Error(`Auto-review model returned HTTP ${response.status}`);
- }
- const reply = await response.json();
- await recordUsage(config.usageDirectory, { raw: reply.usage, model: reply.model ?? config.model, kind: 'review', requestId: reply.id });
- const calls = reply.choices?.[0]?.message?.tool_calls;
- if (reply.choices?.[0]?.finish_reason === 'length' || calls?.length !== 1 || calls[0].function?.name !== tool.function.name)
- throw new Error('Auto-review model did not return one complete classification');
- let decision;
- try { decision = JSON.parse(calls[0].function.arguments); }
- catch { throw new Error('Auto-review model returned invalid JSON'); }
- if (!decision || typeof decision !== 'object' || Array.isArray(decision)) throw new Error('Invalid auto-review classification');
- for (const name of schema.required) {
- if (typeof decision[name] !== 'string' || !decision[name].trim() ||
- (schema.properties[name].enum && !schema.properties[name].enum.includes(decision[name])))
- throw new Error(`Invalid auto-review classification field: ${name}`);
+ const classify = CLASSIFIERS[config.apiFormat] ?? classifyWithChat;
+ let replyId, decision;
+ // A malformed answer is retried once; service errors and cancellation are not.
+ for (let attempt = 1; ; attempt++) {
+ try {
+ ({ id: replyId, decision } = await classify(config, library, tool, content, signal, fetchImpl, state));
+ validate(decision, schema);
+ break;
+ } catch (error) {
+ const retry = error instanceof ReviewOutputError && attempt < 2 && !signal.aborted;
+ log(`Local auto-review ${retry ? 'retrying after' : 'failed'}: ${error.message}; model=${config.model}`);
+ if (!retry) throw error;
+ }
}
- if (decision.decision === 'BLOCK' && decision.blocked_effect === 'none')
- throw new Error('Auto-review returned an inconsistent decision');
- const outbound = ['outbound_or_binding_external_effect', 'data_or_credential_exfiltration'].includes(decision.blocked_effect);
- if (decision.decision === 'BLOCK' && outbound &&
- (decision.outbound_authorization !== 'unauthorized_destination' || !decision.who_sees_it?.trim()))
- throw new Error('Auto-review returned an incomplete outbound decision');
const proposedRule = decision.proposed_allow_rule;
- if (proposedRule !== undefined && typeof proposedRule !== 'string') throw new Error('Invalid auto-review proposed rule');
- log(`Local auto-review ${decision.decision}; model=${config.model}; request=${String(reply.id ?? 'unavailable').slice(0, 128)}`);
+ log(`Local auto-review ${decision.decision}; model=${config.model}; request=${String(replyId ?? 'unavailable').slice(0, 128)}`);
return new library.SmartModeClassifierResult({ result: { case: 'success', value: {
decision: decision.decision === 'ALLOW' ? 1 : 2,
...(decision.decision === 'BLOCK' ? { blockReason: decision.reason.slice(0, 500) } : {}),
diff --git a/host/runtime/host-computers.mjs b/host/runtime/host-computers.mjs
index 398b9f388422782f3d6b1ca2afb5ca0493f4756a..4fe9f847942e90730443e04a1c65a07bbc5b763d 100644
--- a/host/runtime/host-computers.mjs
+++ b/host/runtime/host-computers.mjs
@@ -8,7 +8,7 @@ export function observeHostComputers(bridge, { send, intervalMs = 5000 } = {}) {
try {
const computers = bridge.userComputers.list().map(({ id, label, connected }) => ({
id, label, connected: connected === true,
- platform: id.startsWith('mac-') ? 'darwin' : 'unknown',
+ platform: id.startsWith('mac-') ? 'darwin' : id.startsWith('win-') ? 'win32' : 'unknown',
capabilities: ['exec', 'files'],
}));
send({ type: 'local-computers', available: true, computers });
diff --git a/host/runtime/host-extensions.mjs b/host/runtime/host-extensions.mjs
index 20e0e6d40b9f30b5a3f62fba53126d99255d6bf5..096389296a877cb459ee3d901223f4cc722ee58f 100644
--- a/host/runtime/host-extensions.mjs
+++ b/host/runtime/host-extensions.mjs
@@ -8,6 +8,7 @@ import { startLocalAutoReview } from './host-auto-review.mjs';
import { localTemplates } from './host-local-profile.mjs';
import { createModelRouter } from './model-router.mjs';
import { recordUsage } from './usage-ledger.mjs';
+import { recordRouting } from './routing-log.mjs';
import { transcribeLocalAudio } from './host-speech.mjs';
import { createLocalCapabilities, startLocalMemory } from './host-capabilities.mjs';
import { contextPolicyFor } from './context-policy.mjs';
@@ -15,6 +16,7 @@ import { startLocalManagedSkills } from './host-skills.mjs';
import { startLocalWebhooks } from './host-webhooks.mjs';
import { startLocalFederation } from './host-federation.mjs';
import { createLocalServiceRuntime } from './media-runtime.mjs';
+import { modelRouteForAgent } from './model-routing.mjs';
const unsubscribe = () => () => {};
export function unavailable(capability) {
@@ -49,7 +51,13 @@ function localIdentity() {
};
}
-function inference(config, library, services) {
+function inferenceAgentId(options) {
+ const id = options?.agentId ?? options?.getAgentId?.() ?? options?.agentStore?.getId?.();
+ return typeof id === 'string' && id ? id : undefined;
+}
+
+export function createInference(config, library, services, { fetchImpl, sessionFactory = createModelSession } = {}) {
+ const modelFetch = fetchImpl ?? globalThis.fetch;
return {
isReady: async () => true,
port: {
@@ -58,11 +66,20 @@ function inference(config, library, services) {
videoAnalysisEnabled: services.videoAnalysisEnabled,
createSession: (onRequestId, options) => ['watchVideo', 'videoReview'].includes(options?.localMediaKind) && services.videoAnalysisEnabled(options.localMediaKind)
? services.createVideoSession(options.localMediaKind, onRequestId)
- : createModelSession({ ...config, ...contextPolicyFor(config, config.model), onRequestId,
- selectRequest: createModelRouter(options?.isSummarizationSession && config.policy ? { ...config, policy: { ...config.policy, mode: 'manual' } } : config, { onDecision: decision => console.info('[model-router]', JSON.stringify(decision)) }),
- onUsage: usage => recordUsage(config.usageDirectory, { ...usage, kind: options?.isSummarizationSession ? 'summary' : 'chat' }),
- fetchImpl: observeModelFetch(globalThis.fetch, options),
- mapError: createHarnessModelErrorMapper(library) }),
+ : (() => {
+ const agentId = inferenceAgentId(options);
+ const route = config.modelRouting ? modelRouteForAgent(config.modelRouting, agentId) : undefined;
+ const sessionConfig = route ? { ...config, ...route } : { ...config, ...contextPolicyFor(config, config.model) };
+ const routerConfig = !config.modelRouting && options?.isSummarizationSession && config.policy
+ ? { ...config, policy: { ...config.policy, mode: 'manual' } } : config;
+ return sessionFactory({ ...sessionConfig, onRequestId,
+ selectRequest: createModelRouter(routerConfig, { agentId, onDecision: decision => console.info('[model-router]', JSON.stringify(decision)) }),
+ onFallback: event => recordRouting(config.routingDirectory, { kind: 'model-fallback', status: 'fallback', agentId,
+ session: options?.isSummarizationSession ? 'summary' : 'chat', ...event }),
+ onUsage: usage => recordUsage(config.usageDirectory, { ...usage, kind: options?.isSummarizationSession ? 'summary' : 'chat' }),
+ fetchImpl: observeModelFetch(modelFetch, options),
+ mapError: createHarnessModelErrorMapper(library) });
+ })(),
// These are official analytics endpoints, disabled with Host telemetry.
recordPostTurnLabeling() {}, recordFollowupLabeling() {},
},
@@ -83,7 +100,7 @@ export function createExtensionStarter(library, modelConfig) {
'managed-setup': startLocalManagedSkills,
'bot-template-share': () => localTemplates(),
'remote-agent-messaging': context => startLocalFederation(context, { extensions: id => apis.get(id) }),
- inference: () => inference(modelConfig, library, services),
+ inference: () => createInference(modelConfig, library, services),
mcp: context => startLocalHostMcp(context, library, { nativeEnabled: () => capabilities.get().macComputer,
permission: () => apis.get('local-tool-permission') }),
'auto-review': context => startLocalAutoReview(context, library, modelConfig),
diff --git a/host/runtime/host-network.mjs b/host/runtime/host-network.mjs
index 81137e76fc29e60a98392fd9d161a7190961595a..9216c2db00b9e29d6bcd09ec0f9392e7f8b8d660 100644
--- a/host/runtime/host-network.mjs
+++ b/host/runtime/host-network.mjs
@@ -4,9 +4,10 @@ import http2 from 'node:http2';
import { syncBuiltinESMExports } from 'node:module';
/** Host background services may reach only local endpoints and the configured model. */
-export function installHostNetworkBoundary(modelBaseUrl, { additionalHosts = [] } = {}) {
- const modelHost = new URL(modelBaseUrl).hostname;
- const allowedHosts = new Set(['127.0.0.1', 'localhost', '::1', '[::1]', modelHost, ...additionalHosts]);
+export function installHostNetworkBoundary(modelBaseUrls, { additionalHosts = [] } = {}) {
+ const values = Array.isArray(modelBaseUrls) ? modelBaseUrls : [modelBaseUrls];
+ const modelHosts = values.filter(Boolean).map(value => new URL(value).hostname);
+ const allowedHosts = new Set(['127.0.0.1', 'localhost', '::1', '[::1]', ...modelHosts, ...additionalHosts]);
const assertAllowed = input => {
const url = typeof input === 'string' || input instanceof URL ? new URL(input)
: input instanceof Request ? new URL(input.url) : null;
diff --git a/host/runtime/host-resources.mjs b/host/runtime/host-resources.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..51e359866d808b0e5d39cb03da3e56f13152d2a1
--- /dev/null
+++ b/host/runtime/host-resources.mjs
@@ -0,0 +1,24 @@
+import { lstat, readlink, readdir, rename, symlink, unlink } from 'node:fs/promises';
+import { basename, dirname, join, resolve } from 'node:path';
+import { randomUUID } from 'node:crypto';
+
+// Only links pointing into a sibling image-owned Host revision may be replaced.
+export function previousImageLink(target, originalDir, name) {
+ const revision = dirname(dirname(target));
+ return basename(originalDir) === 'sand-host' && /^host-[0-9a-f]+$/.test(basename(dirname(originalDir))) &&
+ dirname(revision) === dirname(dirname(originalDir)) && /^host-[0-9a-f]+$/.test(basename(revision)) &&
+ target === join(revision, 'sand-host', name) && target !== join(originalDir, name);
+}
+
+export async function provisionResources(stateDir, originalDir) {
+ for (const entry of await readdir(originalDir, { withFileTypes: true })) {
+ if (['host-main.cjs', 'package.json', 'sand-eval-runner.cjs'].includes(entry.name)) continue;
+ const dst = join(stateDir, entry.name), src = join(originalDir, entry.name);
+ const existing = await lstat(dst).catch(error => { if (error.code !== 'ENOENT') throw error; });
+ if (!existing) { await symlink(src, dst, entry.isDirectory() ? 'dir' : 'file'); continue; }
+ if (!existing.isSymbolicLink() || !previousImageLink(resolve(stateDir, await readlink(dst)), originalDir, entry.name)) continue;
+ const tmp = `${dst}.${randomUUID()}.tmp`;
+ await symlink(src, tmp, entry.isDirectory() ? 'dir' : 'file');
+ try { await rename(tmp, dst); } catch (error) { await unlink(tmp); throw error; }
+ }
+}
diff --git a/host/runtime/host-summarize.mjs b/host/runtime/host-summarize.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..bc1d51492ccd11044c0b3492c3ae2f6d4b3351ec
--- /dev/null
+++ b/host/runtime/host-summarize.mjs
@@ -0,0 +1,74 @@
+import { check } from '../server/security.mjs';
+
+const AGENT_ID = /^[a-f0-9-]{1,128}$/i;
+// The runner requires a nonempty prompt before it asks promptGlue for an action.
+// The replacement below discards this value and emits only summarizeAction.
+const MANUAL_SUMMARY_PROMPT = 'Local administrator requested a conversation summary.';
+
+function unsupported(value, message) {
+ check(value, 501, message);
+ return value;
+}
+
+function isRunning(lifecycle, session, agentId) {
+ return lifecycle.inFlightRunCounts?.has(session) || lifecycle.runningAgentIds?.().has(agentId);
+}
+
+/**
+ * Run the Harness' native summarizeAction for one idle Bot. This preserves the
+ * original transcript and lets the normal summary handler persist its checkpoint.
+ */
+export async function summarizeAgent(host, _library, agentId) {
+ check(typeof agentId === 'string' && AGENT_ID.test(agentId), 400, 'Bot ID 无效');
+ const transcript = host?.transcript;
+ unsupported(transcript?.listAgentsSync && transcript?.sessions?.resolveBackgroundSession,
+ '当前 Host 版本不支持手动压缩');
+ const agent = transcript.listAgentsSync().find(item => item.id === agentId);
+ check(agent, 404, 'Bot 不存在');
+ check(!agent.isGroup, 400, '暂不支持压缩群组 Bot');
+
+ const lifecycle = transcript.runLifecycle, registry = transcript.runnerRegistry;
+ unsupported(lifecycle?.beginSessionRun && lifecycle?.endSessionRun && lifecycle?.enqueueExclusiveRun && registry?.getRunner,
+ '当前 Host 版本不支持手动压缩');
+ // Resolve without activating the Bot in the currently selected client session.
+ const session = await transcript.sessions.resolveBackgroundSession(agentId);
+ check(!isRunning(lifecycle, session, agentId), 409, 'Bot 正在运行,请在任务结束后再压缩');
+ const runner = registry.getRunner(session);
+ const promptGlue = runner?.promptGlue;
+ unsupported(typeof promptGlue?.assembleTurnAction === 'function' && typeof runner?.run === 'function',
+ '当前 Host 版本不支持手动压缩');
+
+ let began = false;
+ try {
+ // Mark the turn synchronously before queueing it, so a newly sent user
+ // message is placed after this isolated summary turn instead of racing it.
+ lifecycle.beginSessionRun(session);
+ began = true;
+ await lifecycle.enqueueExclusiveRun(agentId, async () => {
+ const original = promptGlue.assembleTurnAction;
+ const assembleSummaryAction = async () => ({
+ // The public Host library does not export its generated proto classes.
+ // The runner immediately redacts this shape and the summarize handler
+ // deliberately ignores the empty action payload.
+ action: { action: { case: 'summarizeAction', value: {} } },
+ });
+ promptGlue.assembleTurnAction = assembleSummaryAction;
+ try {
+ const result = await runner.run(MANUAL_SUMMARY_PROMPT, {
+ hidden: true,
+ requestSource: 'event',
+ advanceChainOnDelivery: false,
+ });
+ check(!result?.aborted && !result?.pausedForUpgrade, 409, '上下文压缩被中断,请稍后重试');
+ } finally {
+ // Do not overwrite a newer replacement if a future Harness version
+ // changes the glue while this run is completing.
+ if (promptGlue.assembleTurnAction === assembleSummaryAction) promptGlue.assembleTurnAction = original;
+ }
+ }, { lane: 'background', source: 'manual-summary' });
+ return { ok: true, agentId, status: 'completed' };
+ } finally {
+ if (began) lifecycle.endSessionRun(session);
+ await transcript.roster?.emitAgentUpdate?.(agentId);
+ }
+}
diff --git a/host/runtime/host.mjs b/host/runtime/host.mjs
index a11662185036ad5e104291b8bb46f817e3568066..b7e0f65f8238bc1c28fc31fe14c1257f3611ab1a 100644
--- a/host/runtime/host.mjs
+++ b/host/runtime/host.mjs
@@ -1,5 +1,6 @@
import { createRequire } from 'node:module';
-import { mkdir, readdir, symlink, lstat, writeFile, rename, readFile } from 'node:fs/promises';
+import { mkdir, writeFile, rename, readFile } from 'node:fs/promises';
+import { provisionResources } from './host-resources.mjs';
import { resolve, join } from 'node:path';
import { loadModelConfig } from './config.mjs';
import { createExtensionStarter } from './host-extensions.mjs';
@@ -12,9 +13,12 @@ import { loadExecutionNode, connectExecutionNode } from '../server/execution-nod
import { writePrivate } from '../server/storage.mjs';
import { decorateLocalSharingApi } from './sharing-import.mjs';
import { installLocalPromptPolicy } from './prompt-runtime.mjs';
+import { summarizeAgent } from './host-summarize.mjs';
+import { installModelRejectionGuard } from './model-rejection-guard.mjs';
const stateDir = process.env.GROKBOT_STATE_DIR ?? '/research/state';
const originalDir = process.env.GROKBOT_ORIGINAL_HOST ?? '/research/original-host';
+installModelRejectionGuard();
Object.assign(process.env, {
SAND_DATA_ROOT: join(stateDir, 'host-data'),
SAND_BACKEND_URL: 'http://127.0.0.1:9',
@@ -23,17 +27,9 @@ Object.assign(process.env, {
SAND_HOST_IN_BOX: '1', SAND_PACKAGED: '1',
});
-async function provisionResources() {
- await mkdir(process.env.SAND_DATA_ROOT, { recursive: true });
- for (const entry of await readdir(originalDir, { withFileTypes: true })) {
- if (['host-main.cjs', 'package.json', 'sand-eval-runner.cjs'].includes(entry.name)) continue;
- const destination = join(stateDir, entry.name);
- if (await lstat(destination).catch(() => null)) continue;
- await symlink(join(originalDir, entry.name), destination, entry.isDirectory() ? 'dir' : 'file');
- }
-}
-
-await provisionResources();
+await mkdir(process.env.SAND_DATA_ROOT, { recursive: true });
+await provisionResources(stateDir, originalDir);
+const revision = (await readFile(join(originalDir, 'version'), 'utf8')).trim();
const executionTransport = await connectExecutionNode(await loadExecutionNode(process.env.GROKBOT_DATA_DIR ?? stateDir), process.env.GROKBOT_DATA_DIR ?? stateDir);
const executionNode = executionTransport.config;
if (executionNode?.enabled) {
@@ -48,7 +44,7 @@ if (internalToken !== undefined && !/^[A-Za-z0-9_-]{32,256}$/.test(internalToken
const allowedHosts = process.env.GROKBOT_BOX_HOST ? [process.env.GROKBOT_BOX_HOST] : [];
if (process.env.GROKBOT_NOTIFICATION_URL) allowedHosts.push(new URL(process.env.GROKBOT_NOTIFICATION_URL).hostname);
if (model.policy.mode === 'adaptive') allowedHosts.push('api.typesafe.ai');
-installHostNetworkBoundary(model.baseUrl, { additionalHosts: allowedHosts });
+installHostNetworkBoundary(model.modelBaseUrls ?? model.baseUrl, { additionalHosts: allowedHosts });
const require = createRequire(import.meta.url);
const recovered = process.env.GROKBOT_RECOVERED_CORE === '1';
let libraryPath = resolve(stateDir, 'host-library.cjs'), repaired;
@@ -60,7 +56,7 @@ const library = require(libraryPath);
const core = recovered ? await loadRecoveredHostCore(library, repaired.directory) : { mode: 'bundled' };
if (recovered) core.reliability = repaired.status;
library.activateHostLocale();
-const prompts = await installLocalPromptPolicy(process.env.GROKBOT_DATA_DIR ?? stateDir, library);
+const prompts = await installLocalPromptPolicy(process.env.GROKBOT_DATA_DIR ?? stateDir, library, { revision });
const host = new library.SandHost({ startExtensions: createExtensionStarter(library, model) });
let gateway, computers;
let stopping = false;
@@ -93,8 +89,12 @@ process.once('SIGINT', () => void stop('SIGINT'));
try {
await host.start();
computers = observeHostComputers(host.getLocalExecBridge());
+ const localApplicationRpc = args => {
+ if (args?.action === 'grokbot.manual-summary') return summarizeAgent(host, library, args.agentId);
+ return host.requireHostExtensions().api('mcp').applicationRpc(args);
+ };
gateway = await library.startGatewayServer({
- api: decorateLocalSharingApi({ api: { ...withLibraryCleanup(host.getApi(), host, library), localApplicationRpc: args => host.requireHostExtensions().api('mcp').applicationRpc(args) }, host }), subscribe: listener => host.subscribe(listener),
+ api: decorateLocalSharingApi({ api: { ...withLibraryCleanup(host.getApi(), host, library), localApplicationRpc }, host }), subscribe: listener => host.subscribe(listener),
getHealth: () => host.getHealth(), startedAt: host.startedAt,
host: process.env.GROKBOT_HOST_BIND ?? '0.0.0.0', port: Number(process.env.GROKBOT_HOST_PORT ?? 1340),
...(internalToken ? { authToken: internalToken } : {}),
@@ -116,7 +116,7 @@ try {
onCommandError: report => host.reportGatewayCommandError(report),
onCommandComplete: report => host.reportGatewayCommandSuccess(report),
});
- const status = { ready: true, revision: 'd0a4baa', model: model.model, pid: process.pid,
+ const status = { ready: true, revision, model: model.model, pid: process.pid,
port: gateway.port, dataRoot: process.env.SAND_DATA_ROOT, identity: 'local-workspace',
officialAccount: false, officialBackend: false, telemetry: false, updates: false, core };
await saveHostStatus(status);
diff --git a/host/runtime/media-services.mjs b/host/runtime/media-services.mjs
index 91fdfab0a01525f412b417250f198e854d673444..84e2045159f86429ccec5b77edacc84026046583 100644
--- a/host/runtime/media-services.mjs
+++ b/host/runtime/media-services.mjs
@@ -52,7 +52,7 @@ export class MediaServices {
check(['image', 'video'].includes(kind), 400, 'Invalid media generation kind');
if (jobId) check(typeof jobId === 'string' && /^[0-9a-f-]{36}$/.test(jobId), 400, 'Invalid media job');
const { model, provider } = await this.resolve(kind, input.model);
- const body = mediaInput(model, input), inputHash = digest(JSON.stringify({ kind, model: model.id, body }));
+ const body = mediaInput(model, input, provider.adapter), inputHash = digest(JSON.stringify({ kind, model: model.id, body }));
if (kind === 'image') check((body.n ?? 1) === 1 && (body.max_images ?? 1) === 1 && (body.num_images ?? 1) === 1,
400, 'Configure one image per GenerateImage request');
const requestKey = requestId ? digest(String(requestId)) : randomUUID();
diff --git a/host/runtime/model-common.mjs b/host/runtime/model-common.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..03ebe7cd433fd091734868fd5ad2182ead69b3a4
--- /dev/null
+++ b/host/runtime/model-common.mjs
@@ -0,0 +1,395 @@
+// Shared pieces of the three model API formats: errors, SSE, media, reasoning
+// provenance and optional-parameter fallback.
+import { recordToolCallOrder } from './reliability/tool-order.mjs';
+
+export class ModelRequestError extends Error {
+ constructor(message, { status, code, retryAfterMs, cause, param } = {}) {
+ super(message, { cause });
+ this.name = 'ModelRequestError';
+ this.status = status;
+ this.code = code;
+ this.retryAfterMs = retryAfterMs;
+ this.param = param;
+ }
+}
+
+export function retryAfterMs(headers) {
+ const value = headers?.get('retry-after')?.trim();
+ if (!value) return undefined;
+ if (/^\d+(?:\.\d+)?$/.test(value)) {
+ const milliseconds = Number(value) * 1000;
+ return Number.isFinite(milliseconds) ? milliseconds : undefined;
+ }
+ // HTTP-date is the other Retry-After form; reject numeric-looking invalid values.
+ if (!/[a-z]/i.test(value)) return undefined;
+ const deadline = Date.parse(value);
+ return Number.isFinite(deadline) ? Math.max(0, deadline - Date.now()) : undefined;
+}
+
+/** Build a ModelRequestError from an OpenAI- or Anthropic-style error payload. */
+export function providerError(payload, status, headers, apiKey) {
+ const error = payload?.error ?? payload?.response?.error ?? payload;
+ let message = typeof error?.message === 'string' ? error.message : `Model request failed${status ? ` (HTTP ${status})` : ''}`;
+ // Redact echoed credentials; very short values would only corrupt the message.
+ if (apiKey && apiKey.length >= 8) message = message.split(apiKey).join('[redacted]');
+ const reportedStatus = error?.status ?? error?.status_code;
+ const code = typeof error?.code === 'string' || typeof error?.code === 'number' ? error.code
+ : typeof error?.type === 'string' && error.type !== 'error' ? error.type : undefined;
+ return new ModelRequestError(message, {
+ status: status ?? (Number.isInteger(reportedStatus) && reportedStatus >= 400 && reportedStatus <= 599 ? reportedStatus : undefined),
+ code, param: typeof error?.param === 'string' ? error.param : undefined, retryAfterMs: retryAfterMs(headers),
+ });
+}
+
+const MAX_ERROR_BODY_BYTES = 64 * 1024;
+
+export async function errorFromResponse(http, apiKey) {
+ if (!http.body) return providerError(undefined, http.status, http.headers, apiKey);
+ const reader = http.body.getReader();
+ let bytes, size = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (value.byteLength > MAX_ERROR_BODY_BYTES - size) {
+ await reader.cancel().catch(() => {});
+ return new ModelRequestError(`Model request failed (HTTP ${http.status}); error body exceeds 64 KiB`,
+ { status: http.status, retryAfterMs: retryAfterMs(http.headers) });
+ }
+ // One bounded buffer also handles arbitrarily fragmented or compressed error responses.
+ if (value.byteLength) {
+ bytes ??= Buffer.allocUnsafe(MAX_ERROR_BODY_BYTES);
+ bytes.set(value, size);
+ size += value.byteLength;
+ }
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ let payload;
+ if (size) {
+ try { payload = JSON.parse(new TextDecoder().decode(bytes.subarray(0, size))); }
+ catch (error) { if (!(error instanceof SyntaxError)) throw error; }
+ }
+ return providerError(payload, http.status, http.headers, apiKey);
+}
+
+const direct = action => action();
+const MAX_EVENT_CHARS = 16 * 1024 * 1024;
+
+/** SSE events can cross UTF-8 chunks and use LF, CRLF, or CR line endings. */
+export async function* readSse(body, { waitForIO = direct, maxEventChars = MAX_EVENT_CHARS } = {}) {
+ if (!body) throw new ModelRequestError('Model response has no body');
+ const reader = body.getReader();
+ const decoder = new TextDecoder('utf-8', { fatal: true });
+ let line = '', skipLF = false, data = [], buffered = 0;
+ function accept(line) {
+ if (line === '') {
+ const event = data.length ? data.join('\n') : undefined;
+ data = []; buffered = 0;
+ return event;
+ }
+ if (line === 'data' || line.startsWith('data:')) {
+ if (buffered + line.length + 1 > maxEventChars) throw new ModelRequestError('Model SSE event exceeds size limit');
+ data.push(line.slice(line[5] === ' ' ? 6 : 5));
+ buffered += line.length + 1;
+ }
+ return undefined;
+ }
+ // Some compatible gateways omit blank lines between data frames. Parse glued
+ // JSON incrementally so a large event is scanned once, not once per chunk.
+ let glued;
+ function resetGlued() { glued = undefined; }
+ function gluedEvents() {
+ const events = [];
+ while (line.startsWith('data:')) {
+ if (!glued) glued = { start: 0, scan: 0, depth: 0, quoted: false, escaped: false, doneFrom: 0 };
+ let start = glued.start || 5;
+ while (line[start] === ' ' || line[start] === '\t') start++;
+ if (start !== glued.start) glued.start = glued.start || 5;
+ if (!glued.doneFrom) glued.doneFrom = start;
+ const doneToken = '[DONE]';
+ if (line.startsWith(doneToken, start)) {
+ const end = start + doneToken.length;
+ // A terminal frame may omit its blank-line separator at EOF, but do not
+ // consume a longer literal value that merely starts with [DONE].
+ if (line.length === end || line.startsWith('data:', end)) {
+ events.push(doneToken); line = line.slice(end); resetGlued(); continue;
+ }
+ break;
+ }
+ if (!['{', '['].includes(line[start])) break;
+ let { scan, depth, quoted, escaped } = glued;
+ if (!scan) { scan = start; depth = 0; quoted = false; escaped = false; }
+ for (; scan < line.length; scan++) {
+ const character = line[scan];
+ if (quoted) {
+ if (escaped) escaped = false;
+ else if (character === '\\') escaped = true;
+ else if (character === '"') quoted = false;
+ } else if (character === '"') quoted = true;
+ else if (character === '{' || character === '[') depth++;
+ else if ((character === '}' || character === ']') && --depth === 0) {
+ scan++;
+ events.push(line.slice(start, scan));
+ line = line.slice(scan);
+ glued = undefined;
+ break;
+ }
+ }
+ if (glued) {
+ Object.assign(glued, { scan, depth, quoted, escaped });
+ if (line.length - start > maxEventChars) throw new ModelRequestError('Model SSE event exceeds size limit');
+ break;
+ }
+ }
+ return events;
+ }
+ try {
+ while (true) {
+ const { value, done } = await waitForIO(() => reader.read());
+ const chunk = done ? decoder.decode() : decoder.decode(value, { stream: true });
+ let start = !done && skipLF && chunk[0] === '\n' ? 1 : 0;
+ skipLF = false;
+ const breaks = /\r\n|\r|\n/g;
+ breaks.lastIndex = start;
+ let match;
+ while ((match = breaks.exec(chunk))) {
+ line += chunk.slice(start, match.index);
+ start = breaks.lastIndex;
+ if (!done && match[0] === '\r' && start === chunk.length) skipLF = true;
+ const event = accept(line);
+ line = ''; resetGlued();
+ if (event !== undefined) yield event;
+ breaks.lastIndex = start;
+ }
+ // `done` only flushes the decoder; EOF alone is not an SSE separator.
+ if (done) break;
+ line += chunk.slice(start);
+ for (const event of gluedEvents()) yield event;
+ if (line.length > maxEventChars) throw new ModelRequestError('Model SSE event exceeds size limit');
+ // EOF alone is not an SSE separator. Only the explicitly supported glued
+ // frame form above may complete without a normal blank line.
+ }
+ } finally {
+ await reader.cancel().catch(() => {});
+ reader.releaseLock();
+ }
+}
+
+export function parseEvent(data) {
+ try { return JSON.parse(data); }
+ catch (cause) { throw new ModelRequestError('Invalid JSON in model SSE event', { cause }); }
+}
+
+function bytesToBase64(value) {
+ const bytes = value instanceof ArrayBuffer ? Buffer.from(value) : Buffer.from(value.buffer, value.byteOffset, value.byteLength);
+ return bytes.toString('base64');
+}
+
+/** An image or file part as an http(s) URL or a data URL. */
+export function mediaUrl(part, fallbackType = 'image/png') {
+ const value = part.image ?? part.data ?? part.url;
+ const mimeType = part.mimeType ?? fallbackType;
+ if (value instanceof URL) return mediaUrl({ ...part, image: value.href }, fallbackType);
+ if (typeof value === 'string') {
+ if (/^(https?:\/\/|data:)/i.test(value)) return value;
+ if (/^[a-z][\w+.-]*:/i.test(value)) throw new TypeError('Unsupported media URL scheme');
+ if (!value.trim()) throw new TypeError('Media content is empty');
+ return `data:${mimeType};base64,${value}`;
+ }
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return `data:${mimeType};base64,${bytesToBase64(value)}`;
+ throw new TypeError('Media must contain a URL, base64 string, or bytes');
+}
+
+export function parseDataUrl(url) {
+ const match = /^data:([^;,]+)?(?:;[^,]*)?;base64,(.*)$/is.exec(url);
+ return match ? { mediaType: (match[1] ?? 'application/octet-stream').toLowerCase(), data: match[2] } : null;
+}
+
+/** File parts the model APIs read natively: PDFs and plain text. Others become a short note. */
+export function fileKind(part) {
+ const type = String(part.mimeType ?? '').toLowerCase();
+ if (type === 'application/pdf') return 'pdf';
+ if (type.startsWith('text/') || ['application/json', 'application/xml'].includes(type)) return 'text';
+ if (type.startsWith('image/')) return 'image';
+ return 'other';
+}
+
+export function fileText(part) {
+ const url = mediaUrl(part, part.mimeType);
+ const parsed = parseDataUrl(url);
+ return parsed ? Buffer.from(parsed.data, 'base64').toString('utf8') : url;
+}
+
+export function unsupportedFileNote(part) {
+ return `[Attached file ${part.filename ?? 'without a name'} (${part.mimeType ?? 'unknown type'}) cannot be read by this model API.]`;
+}
+
+export function textValue(value) {
+ return typeof value === 'string' ? value : JSON.stringify(value ?? '');
+}
+
+/** OpenAI-compatible providers reject empty or overlong function names. */
+export const validFunctionName = value => typeof value === 'string' && value.length > 0 && value.length <= 128;
+
+export function messageParts(message) {
+ return typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content ?? [];
+}
+
+export const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
+
+/** An explicit level from the policy or router; 'default' and 'auto' mean the model default. */
+export function explicitEffort(effort) {
+ return EFFORT_ORDER.includes(effort) ? effort : undefined;
+}
+
+/**
+ * Reasoning produced here is tagged with its API format and model. cursor.* mirrors the
+ * original Harness convention (it summarizes and replays by modelName); grokbot.* lets
+ * each format replay only reasoning it can read.
+ */
+export function reasoningProviderOptions({ format, model, providerId, summarized = false, itemId, emptyThinking = false }) {
+ return { cursor: { modelName: model, ...(summarized ? { isAlreadySummarizedThinking: true } : {}) },
+ grokbot: { format, model, ...(providerId ? { providerId } : {}), ...(itemId ? { itemId } : {}), ...(emptyThinking ? { emptyThinking: true } : {}) } };
+}
+
+export function reasoningOrigin(part) {
+ const own = part.providerOptions?.grokbot ?? part.experimental_providerMetadata?.grokbot;
+ const cursor = part.providerOptions?.cursor ?? part.experimental_providerMetadata?.cursor;
+ return { format: own?.format, model: own?.model ?? cursor?.modelName, providerId: own?.providerId, itemId: own?.itemId,
+ summarized: cursor?.isAlreadySummarizedThinking === true, phase: own?.phase, emptyThinking: own?.emptyThinking === true };
+}
+
+/**
+ * Optional request parameters some compatible gateways reject. When a 400 names one of
+ * them, the session removes it and retries; the decision is kept for later turns.
+ */
+export function rejectedOption(error, candidates) {
+ if (error?.status !== 400) return undefined;
+ const message = String(error.message ?? ''), param = error.param ?? '';
+ if (param) return candidates.find(name => param === name || param.startsWith(`${name}.`) || param.startsWith(`${name}[`));
+ return candidates.find(name => new RegExp(`(^|[^\\w.])${name.replace(/[.[\]]/g, '\\$&')}(?![\\w])`).test(message));
+}
+
+export function deletePath(object, path) {
+ const keys = path.split('.');
+ let target = object;
+ for (const key of keys.slice(0, -1)) {
+ if (!target || typeof target !== 'object') return;
+ target = target[key];
+ }
+ if (target && typeof target === 'object') delete target[keys.at(-1)];
+ if (keys.length > 1) {
+ const parent = keys.slice(0, -1).reduce((value, key) => value?.[key], object);
+ if (parent && typeof parent === 'object' && !Object.keys(parent).length) deletePath(object, keys.slice(0, -1).join('.'));
+ }
+}
+
+/**
+ * POST with bounded retries. Drop a named, rejected option before considering a
+ * fallback that changes conversation history (replayed reasoning or inline images).
+ */
+export async function postWithFallback({ fetchImpl, url, headers, build, signal, apiKey, optional = [], state, fallbacks = [],
+ waitForIO = direct, log = message => console.warn(message) }) {
+ for (let attempt = 0; ; attempt++) {
+ signal?.throwIfAborted();
+ const body = build();
+ for (const name of state.dropped) deletePath(body, name);
+ const http = await waitForIO(() => fetchImpl(url, { method: 'POST', headers: typeof headers === 'function' ? headers(body) : headers,
+ body: JSON.stringify(body), signal, redirect: 'error' }));
+ if (http.ok) return { http, body };
+ const error = await waitForIO(() => errorFromResponse(http, apiKey));
+ signal?.throwIfAborted();
+ if (attempt < 6) {
+ const option = rejectedOption(error, optional.filter(name => !state.dropped.has(name) &&
+ name.split('.').reduce((value, key) => value?.[key], body) !== undefined));
+ if (option) { state.dropped.add(option); log(`[model] ${new URL(url).host}: retrying without ${option}`); continue; }
+ const fallback = fallbacks.find(item => !item.used && item.applies(error, body));
+ if (fallback) { fallback.used = true; fallback.apply(); log(`[model] ${new URL(url).host}: ${fallback.name ?? 'fallback'} after HTTP ${error.status ?? 'error'}`); continue; }
+ }
+ throw error;
+ }
+}
+
+/** A 400 about reasoning that was replayed from an earlier turn. */
+export function replayRejected(error) {
+ // Gateways join words with underscores (native_thinking_replay_mismatch): no word boundaries.
+ return error?.status === 400 && /signature|thinking|encrypted|reasoning/i.test(`${error.message ?? ''} ${error.code ?? ''}`);
+}
+
+function plainUserDelivery(call) {
+ const args = call?.args;
+ if (call?.type !== 'tool-call' || call.toolName !== 'SendToUser' || args?.type !== 'text' ||
+ typeof args.content !== 'string' || !args.content || Object.keys(args).length !== 2) return undefined;
+ return args.content;
+}
+
+// A fresh provider ID does not prove fresh work. Inspect only the immediately preceding
+// successful exchange, never search across user turns, other tools or conversations.
+function isRepeatedDelivery(calls, messages) {
+ if (calls.length !== 1 || !messages || messages.length < 2) return false;
+ const text = plainUserDelivery(calls[0]);
+ if (text === undefined) return false;
+ const receipt = messages.at(-1), previous = messages.at(-2);
+ if (receipt?.role !== 'tool' || previous?.role !== 'assistant' ||
+ receipt.providerOptions?.cursor?.highLevelToolCallResult?.isError !== false) return false;
+ const parts = messageParts(receipt), sent = messageParts(previous).filter(part => part.type === 'tool-call');
+ return parts.length === 1 && sent.length === 1 && plainUserDelivery(sent[0]) === text &&
+ parts[0].type === 'tool-result' && parts[0].toolName === 'SendToUser' && !parts[0].isError &&
+ Boolean(sent[0].toolCallId) && parts[0].toolCallId === sent[0].toolCallId && receipt.id === sent[0].toolCallId;
+}
+
+export function* streamToolCalls(calls, messages, signal) {
+ if (new Set(calls.map(call => call.toolCallId)).size !== calls.length) throw new ModelRequestError('Duplicate model tool call ID');
+ if (isRepeatedDelivery(calls, messages)) {
+ throw new ModelRequestError('The model requested the same text that was already delivered. Stopped this turn before sending it again.',
+ { code: 'repeated_user_delivery' });
+ }
+ const discard = recordToolCallOrder(calls);
+ let handedOff = 0;
+ const discardUnhanded = () => {
+ for (let i = handedOff; i < calls.length; i++) discard(calls[i].toolCallId);
+ };
+ signal?.addEventListener('abort', discardUnhanded, { once: true });
+ try {
+ for (const call of calls) {
+ // The Harness consumes one argument stream at a time; serialize parallel calls.
+ yield { type: 'tool-call-streaming-start', toolCallId: call.toolCallId, toolName: call.toolName };
+ yield { type: 'tool-call-delta', toolCallId: call.toolCallId, toolName: call.toolName, argsTextDelta: JSON.stringify(call.args) };
+ handedOff++;
+ yield call;
+ }
+ } finally {
+ // Already delivered calls still need their ordering entries until journal execution.
+ signal?.removeEventListener('abort', discardUnhanded);
+ discardUnhanded();
+ }
+}
+
+export function serializeToolCalls(calls) {
+ return [...streamToolCalls(calls)];
+}
+
+/**
+ * Arguments of a model tool call. Compatible endpoints send no argument text for a call without
+ * parameters; that means {} only for a tool that requires none, so lost arguments are never run as {}.
+ */
+export function parseToolArguments(name, text, tools) {
+ if (text === undefined || (typeof text === 'string' && !text.trim())) {
+ const tool = tools?.find(item => item?.name === name);
+ const required = (tool?.parameters?.jsonSchema ?? tool?.parameters)?.required;
+ if (tool && !(Array.isArray(required) && required.length)) return {};
+ }
+ try { return JSON.parse(text); }
+ catch (cause) { throw new ModelRequestError(`Invalid tool arguments for ${name}`, { cause }); }
+}
+
+/** JSON Schema of a Harness tool. */
+export function toolSchema(tool) {
+ if (tool.type === 'provider-defined' || tool.customToolFormat) throw new TypeError('This session supports JSON function tools only');
+ if (typeof tool.name !== 'string' || !tool.name) throw new TypeError('Tool name is required');
+ const parameters = tool.parameters?.jsonSchema ?? tool.parameters;
+ if (!parameters || typeof parameters !== 'object') throw new TypeError('Tool schema is required');
+ return { name: tool.name, description: tool.description ?? '', parameters };
+}
diff --git a/host/runtime/model-errors.mjs b/host/runtime/model-errors.mjs
index 26a9d3ee7f22f3b575e3dcb46b182a338bbfc044..fc5a47eaead3a15d5b5389568cf5915a9a2bbe19 100644
--- a/host/runtime/model-errors.mjs
+++ b/host/runtime/model-errors.mjs
@@ -3,7 +3,7 @@ import { ModelRequestError } from './model-session.mjs';
const CONFIG_CODES = new Set(['invalid_api_key', 'authentication_error']);
const TERMINAL_CODES = new Set([
'invalid_request_error', 'model_not_found', 'permission_denied', 'insufficient_quota',
- 'content_filter', 'length',
+ 'content_filter', 'length', 'repeated_user_delivery',
]);
const TERMINAL_STATUSES = new Set([400, 402, 403, 404, 405, 413, 415, 422]);
const RATE_LIMIT_CODES = new Set(['rate_limit_error', 'rate_limit_exceeded']);
@@ -21,6 +21,11 @@ export function createHarnessModelErrorMapper(library) {
const status = error.status;
const code = typeof error.code === 'string' ? error.code : undefined;
const options = { cause: error, displayInfo: { detail: error.message, isRetryable: false } };
+ // Quota exhaustion is permanent until the account changes. Unlike a transient
+ // 429, sending the same request again only creates a restart/retry storm.
+ const quotaExhausted = code === 'API_KEY_QUOTA_EXHAUSTED' || code === 'insufficient_quota' ||
+ (status === 402 && !code) ||
+ /(?:api[ _-]?key|account)\s+(?:quota|credit|balance)\s+(?:is\s+)?(?:exhausted|used up|depleted|exceeded)|(?:账户|账户余额|API\s*额度|额度)\s*(?:已)?\s*(?:用完|耗尽|不足)/i.test(error.message);
const inputLimit = ['context_length_exceeded', 'input_token_limit_exceeded', 'prompt_too_long'].includes(code) ||
([400, 413, 422].includes(status) && /(?:maximum context length|input token limit|prompt (?:is )?too long|context window.*exceed)/i.test(error.message));
if (inputLimit && typeof InputTokenLimitError === 'function') {
@@ -30,11 +35,11 @@ export function createHarnessModelErrorMapper(library) {
// This is a local provider API key, so official-account login is not the remedy.
return new ActionRequiredError(error.message, 'config', options);
}
- if (TERMINAL_STATUSES.has(status) || TERMINAL_CODES.has(code)) {
+ if (quotaExhausted || TERMINAL_STATUSES.has(status) || TERMINAL_CODES.has(code)) {
return new NonRetriableError(error.message, options);
}
const rateLimited = status === 429 || RATE_LIMIT_CODES.has(code);
- const unavailable = status === 503;
+ const unavailable = status === 503 || status === 529 || code === 'overloaded_error';
if (rateLimited || unavailable || (status >= 500 && status <= 599 && error.retryAfterMs !== undefined)) {
const metadata = new Headers();
if (Number.isFinite(error.retryAfterMs) && error.retryAfterMs >= 0) {
diff --git a/host/runtime/model-observation.mjs b/host/runtime/model-observation.mjs
index 407a49c628a4924a82c45be50851be45c441bfd0..c7c9d1519cabbc8f0c8994fa3dd7866a41bc7837 100644
--- a/host/runtime/model-observation.mjs
+++ b/host/runtime/model-observation.mjs
@@ -14,7 +14,7 @@ export function observeModelFetch(fetchImpl, session = {}, stateDir = process.en
await mkdir(directory, { recursive: true, mode: 0o700 });
const body = JSON.parse(options.body);
const messages = [];
- for (const message of body.messages) {
+ for (const message of body.messages ?? body.input ?? []) {
if (message.role === 'tool') {
messages.push({ role: 'tool', tool_call_id: message.tool_call_id, content: message.content });
} else if (message.role === 'assistant' && message.tool_calls?.length) {
@@ -35,7 +35,7 @@ export function observeModelFetch(fetchImpl, session = {}, stateDir = process.en
}
capture = { directory, record: { at: new Date().toISOString(), sessionId,
requestedModel: session.modelId, inferenceReason: session.inferenceReason,
- model: body.model, tools: body.tools?.map(tool => tool.function.name), messages } };
+ model: body.model, tools: body.tools?.map(tool => tool.function?.name ?? tool.name), messages } };
} catch (error) {
if (error.code !== 'ENOENT') console.error(`[model-observation] ${error.message}`);
}
diff --git a/host/runtime/model-policy.mjs b/host/runtime/model-policy.mjs
index 7a271fc78021c7c13dd58223550e097ceb40cf1b..c8e1b1b3188180bd99df3f3823149d464bc0044f 100644
--- a/host/runtime/model-policy.mjs
+++ b/host/runtime/model-policy.mjs
@@ -1,9 +1,40 @@
import { validateContextPolicy } from './context-policy.mjs';
+import { chatReasoning } from './openai-chat.mjs';
+import { claudeTraits } from './anthropic-messages.mjs';
export const TIERS = ['routine', 'reasoning', 'expert'];
-export const EFFORTS = ['none', 'low', 'medium', 'high', 'xhigh', 'max'];
+export const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
+
+function catalogCapacity(value) {
+ return Number.isSafeInteger(value) && value > 0 && value <= 100_000_000 ? value : undefined;
+}
+
+function summaryThreshold(contextWindowTokens) {
+ if (contextWindowTokens < 2) return 0;
+ return Math.max(1, Math.floor(contextWindowTokens * 0.75 / 1_000) * 1_000);
+}
+
+/** Recommended compaction settings for a model chosen from a provider catalog. */
+export function catalogContextPolicy(model, reportedCapacity) {
+ const capacity = catalogCapacity(reportedCapacity);
+ if (capacity) return { contextWindowTokens: capacity, summaryThresholdTokens: summaryThreshold(capacity), contextSource: 'provider' };
+ return { contextWindowTokens: 0, summaryThresholdTokens: 0, contextSource: 'unknown' };
+}
+
+/** Reference levels for well-known model families; a provider catalog overrides them. */
export function effortLevels(model) {
- if (/deepseek-v4/i.test(model)) return ['none', 'low', 'high', 'max'];
- if (/claude-(opus|sonnet)-5-5/i.test(model)) return ['low', 'medium', 'high', 'xhigh', 'max'];
+ const id = String(model).toLowerCase();
+ if (/deepseek-v4/.test(id)) return ['none', 'low', 'high', 'max'];
+ if (/^claude-/.test(id)) {
+ const traits = claudeTraits(id);
+ if (!traits.known) return [];
+ // 'none' turns thinking off where the model allows it.
+ return [...(traits.disable === 'never' ? [] : ['none']), ...traits.efforts, ...(traits.budget && !traits.efforts.length ? ['low', 'medium', 'high'] : [])];
+ }
+ if (/^o[134](?:-|$)/.test(id)) return ['low', 'medium', 'high'];
+ if (/^gpt-5(?:-mini|-nano)?$/.test(id)) return ['minimal', 'low', 'medium', 'high'];
+ if (/^gpt-5\.1/.test(id)) return ['none', 'low', 'medium', 'high'];
+ if (/^gpt-5\.[2-9]/.test(id)) return ['none', 'low', 'medium', 'high', 'xhigh'];
+ if (/^grok-4/.test(id)) return ['minimal', 'low', 'medium', 'high', 'xhigh'];
return [];
}
export function defaultPolicy(model = 'deepseek-v4.1-flash') {
@@ -43,8 +74,7 @@ export function validatePolicy(value, model) {
if (typeof classifierModel !== 'string' || !/^jev-[a-zA-Z0-9._-]{1,80}$/.test(classifierModel)) fail('Invalid classifier model');
return { mode: policy.mode, effort, models, routes, classifierModel };
}
+/** OpenAI Chat reasoning parameters; other formats map the level themselves. */
export function reasoningOptions(model, effort) {
- if (!effort || effort === 'default') return {};
- return { reasoning_effort: effort,
- ...(/deepseek/i.test(model) ? { thinking: { type: effort === 'none' ? 'disabled' : 'enabled' } } : {}) };
+ return chatReasoning(model, effort);
}
diff --git a/host/runtime/model-rejection-guard.mjs b/host/runtime/model-rejection-guard.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..8f44d169da9af18fbcca5ad61891c51c5d93ded4
--- /dev/null
+++ b/host/runtime/model-rejection-guard.mjs
@@ -0,0 +1,27 @@
+// The recovered Harness can leave a rejected model-stream branch unobserved
+// after it has already turned the same failure into the current turn result.
+function modelFailureDetails(reason) {
+ for (let current = reason, depth = 0; current && depth < 5; current = current.cause, depth++) {
+ if (current?.name === 'ModelRequestError') {
+ return { name: current.name, status: current.status, code: current.code };
+ }
+ }
+ return undefined;
+}
+
+export function isContainedModelRejection(reason) {
+ return modelFailureDetails(reason) !== undefined;
+}
+
+export function installModelRejectionGuard(target = process) {
+ target.on('unhandledRejection', reason => {
+ const failure = modelFailureDetails(reason);
+ if (failure) {
+ // The request has its own error path; never include provider text or credentials in process logs.
+ console.error(`[local-host] contained unhandled model rejection ${JSON.stringify(failure)}`);
+ return;
+ }
+ // Attaching this listener changes Node's default rejection policy, so preserve it for unrelated defects.
+ throw reason;
+ });
+}
diff --git a/host/runtime/model-router.mjs b/host/runtime/model-router.mjs
index b0265456ab0cd4dad6943c66068deaba9455483b..04a9b931a34762c82a992e3e186ceeb856addbc5 100644
--- a/host/runtime/model-router.mjs
+++ b/host/runtime/model-router.mjs
@@ -3,9 +3,10 @@ import { createHash } from 'node:crypto';
import { TIERS, reasoningOptions, validatePolicy } from './model-policy.mjs';
import { recordUsage } from './usage-ledger.mjs';
import { contextPolicyFor } from './context-policy.mjs';
+import { modelRouteForAgent } from './model-routing.mjs';
const effortCriteria = {
- none: 'No deliberate reasoning is needed.', low: 'Quick, straightforward reasoning is enough.',
+ none: 'No deliberate reasoning is needed.', minimal: 'Only a brief check is needed.', low: 'Quick, straightforward reasoning is enough.',
medium: 'Several dependent reasoning steps are needed.', high: 'Substantial analysis or difficult debugging is needed.',
xhigh: 'Very challenging reasoning across interacting constraints is needed.',
max: 'Exceptionally difficult research, proofs or novel algorithmic reasoning justifies maximum effort.',
@@ -46,7 +47,17 @@ export async function classifyTask({ apiKey, model = 'jev-latest', state, policy
}));
return { difficulty: answer.choice, confidence: answer.confidence, efforts, model: data.model ?? model, usage: data.usage };
}
-export function createModelRouter(config, { fetchImpl = fetch, onDecision = () => {} } = {}) {
+export function createModelRouter(config, { fetchImpl = fetch, onDecision = () => {}, agentId } = {}) {
+ if (config.modelRouting) {
+ const route = modelRouteForAgent(config.modelRouting, agentId);
+ const select = candidate => ({ ...candidate,
+ requestOptions: reasoningOptions(candidate.model, candidate.effort) });
+ const selected = { ...select(route), fallbacks: route.fallbacks.map(select) };
+ return async ({ signal } = {}) => {
+ signal?.throwIfAborted();
+ return selected;
+ };
+ }
const policy = validatePolicy(config.policy, config.model);
let cachedKey, cachedDecision;
return async ({ messages, signal }) => {
diff --git a/host/runtime/model-routing.mjs b/host/runtime/model-routing.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..f06aaed4cc7ee72fa3671b542b683b035a2f7cf6
--- /dev/null
+++ b/host/runtime/model-routing.mjs
@@ -0,0 +1,261 @@
+// Versioned model-provider configuration and deterministic Bot route resolution.
+// Credentials stay in model.env; callers of publicModelRouting never receive them.
+import { validateContextPolicy } from './context-policy.mjs';
+import { EFFORTS, effortLevels } from './model-policy.mjs';
+
+export const API_FORMATS = Object.freeze(['openai', 'openai-responses', 'anthropic']);
+export const MODEL_ROUTING_ENV = 'GROKBOT_MODEL_ROUTING';
+
+const MAX_PROVIDERS = 32;
+const MAX_PROFILES = 128;
+const MAX_BOT_ROUTES = 512;
+const MAX_FALLBACKS = 8;
+const ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
+const AGENT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
+
+const plainObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
+const fail = message => { throw new TypeError(message); };
+
+function text(value, label, maximum = 256) {
+ if (typeof value !== 'string' || !value.trim() || value.length > maximum || /[\r\n\0]/.test(value))
+ fail(`Invalid ${label}`);
+ return value.trim();
+}
+
+function identifier(value, label = 'ID') {
+ const id = text(value, label, 64);
+ if (!ID.test(id)) fail(`Invalid ${label}`);
+ return id;
+}
+
+function endpoint(value) {
+ let url;
+ try { url = new URL(text(value, 'Base URL', 2048)); }
+ catch { fail('Invalid Base URL'); }
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash)
+ fail('Invalid Base URL');
+ return url.href.replace(/\/$/, '');
+}
+
+function key(value) {
+ return text(value, 'API Key', 8192);
+}
+
+function modelId(value) {
+ return text(value, 'model ID', 256);
+}
+
+function levels(value, model) {
+ if (value === undefined) return effortLevels(model);
+ if (!Array.isArray(value) || value.some(item => !EFFORTS.includes(item))) fail('Invalid effort levels');
+ return EFFORTS.filter(level => value.includes(level));
+}
+
+function profileContext(value) {
+ try { return validateContextPolicy(value); }
+ catch (error) { fail(error.message); }
+}
+
+function contextForProfile(value, previous) {
+ const hasContext = Object.prototype.hasOwnProperty.call(value, 'contextWindowTokens');
+ const hasThreshold = Object.prototype.hasOwnProperty.call(value, 'summaryThresholdTokens');
+ // A provider catalog is optional. Never invent a capacity: it would make the
+ // Harness defer compaction past the actual context limit of an unknown model.
+ const defaults = previous ?? {};
+ return profileContext({
+ contextWindowTokens: hasContext ? value.contextWindowTokens : (defaults.contextWindowTokens ?? 0),
+ summaryThresholdTokens: hasThreshold ? value.summaryThresholdTokens : (defaults.summaryThresholdTokens ?? 0),
+ });
+}
+
+function routeEffort(value, profile) {
+ const effort = value ?? 'default';
+ if (effort !== 'default' && !profile.efforts.includes(effort)) fail(`Unsupported effort for ${profile.id}`);
+ return effort;
+}
+
+function normalizeProvider(value, previousProviders) {
+ if (!plainObject(value)) fail('Invalid provider');
+ const id = identifier(value.id, 'provider ID');
+ const apiFormat = value.apiFormat;
+ if (!API_FORMATS.includes(apiFormat)) fail('Invalid API format');
+ const supplied = typeof value.apiKey === 'string' && value.apiKey.trim() ? key(value.apiKey) : undefined;
+ const apiKey = supplied ?? previousProviders.get(id)?.apiKey;
+ if (!apiKey) fail(`API Key is required for ${id}`);
+ return { id, name: text(value.name, 'provider name', 120), apiFormat, baseUrl: endpoint(value.baseUrl), apiKey };
+}
+
+/** Validate one provider draft, retaining its existing credential when its stable ID is unchanged. */
+export function validateModelProvider(input, { previous } = {}) {
+ const previousProviders = new Map((previous?.providers ?? []).map(item => [item.id, item]));
+ return normalizeProvider(input, previousProviders);
+}
+
+function normalizeRoute(value, profiles, label) {
+ if (!plainObject(value)) fail(`Invalid ${label}`);
+ const profileId = identifier(value.profileId, `${label} profile ID`);
+ const primary = profiles.get(profileId);
+ if (!primary) fail(`Unknown profile: ${profileId}`);
+ const effort = routeEffort(value.effort, primary);
+ const rawFallbacks = value.fallbacks ?? [];
+ if (!Array.isArray(rawFallbacks) || rawFallbacks.length > MAX_FALLBACKS) fail(`Invalid ${label} fallbacks`);
+ const seen = new Set([profileId]);
+ const fallbacks = rawFallbacks.map((item, index) => {
+ if (!plainObject(item)) fail(`Invalid ${label} fallback`);
+ const fallbackProfileId = identifier(item.profileId, `${label} fallback profile ID`);
+ if (seen.has(fallbackProfileId)) fail(`Duplicate ${label} fallback profile`);
+ seen.add(fallbackProfileId);
+ const profile = profiles.get(fallbackProfileId);
+ if (!profile) fail(`Unknown profile: ${fallbackProfileId}`);
+ return { profileId: fallbackProfileId, effort: routeEffort(item.effort, profile), order: index };
+ });
+ return { profileId, effort, fallbacks };
+}
+
+/** A usable empty draft for a new installation. It is intentionally not a persisted config. */
+export function emptyModelRouting() {
+ return { version: 1, providers: [], profiles: [], defaultRoute: null, botRoutes: {} };
+}
+
+/** Convert the old, single-provider environment shape into an editable draft. */
+export function legacyModelRouting(legacy = {}) {
+ const apiFormat = API_FORMATS.includes(legacy.apiFormat) ? legacy.apiFormat : 'openai';
+ const baseUrl = typeof legacy.baseUrl === 'string' ? legacy.baseUrl : '';
+ const apiKey = typeof legacy.apiKey === 'string' ? legacy.apiKey : '';
+ const model = typeof legacy.model === 'string' ? legacy.model : '';
+ if (!baseUrl && !apiKey && !model) return emptyModelRouting();
+ const models = legacy.policy?.models;
+ const previous = Array.isArray(models) ? models.find(item => item?.id === model) : undefined;
+ const profile = model ? {
+ id: 'default', name: '默认模型', providerId: 'default', model,
+ efforts: Array.isArray(previous?.efforts) ? previous.efforts.filter(level => EFFORTS.includes(level)) : effortLevels(model),
+ ...profileContext({ contextWindowTokens: previous?.contextWindowTokens ?? legacy.contextWindowTokens ?? 0,
+ summaryThresholdTokens: previous?.summaryThresholdTokens ?? 0 }),
+ } : null;
+ const provider = (baseUrl || apiKey || profile) ? { id: 'default', name: '默认服务', apiFormat, baseUrl, apiKey } : null;
+ return { version: 1, providers: provider ? [provider] : [], profiles: profile ? [profile] : [],
+ defaultRoute: provider && profile ? { profileId: profile.id, effort: legacy.policy?.effort ?? 'default', fallbacks: [] } : null,
+ botRoutes: {} };
+}
+
+/** Parse a persisted JSON routing configuration. Missing JSON means legacy configuration. */
+export function parseModelRouting(value, legacy) {
+ if (!value) return { config: legacyModelRouting(legacy), migrated: true };
+ let parsed;
+ try { parsed = JSON.parse(value); }
+ catch { fail('Invalid multi-provider model configuration'); }
+ return { config: validateModelRouting(parsed), migrated: false };
+}
+
+/**
+ * Validate a configuration received from the admin API. Empty API key fields retain
+ * the credential for a provider with the same stable ID; a newly added provider needs one.
+ */
+export function validateModelRouting(input, { previous } = {}) {
+ if (!plainObject(input) || input.version !== 1) fail('Unsupported model routing configuration');
+ if (!Array.isArray(input.providers) || !input.providers.length || input.providers.length > MAX_PROVIDERS)
+ fail('Invalid providers');
+ if (!Array.isArray(input.profiles) || !input.profiles.length || input.profiles.length > MAX_PROFILES)
+ fail('Invalid model profiles');
+ const providerIds = new Set();
+ const providers = input.providers.map(item => {
+ const provider = validateModelProvider(item, { previous });
+ const { id } = provider;
+ if (providerIds.has(id)) fail('Duplicate provider ID');
+ providerIds.add(id);
+ return provider;
+ });
+ const providersById = new Map(providers.map(item => [item.id, item]));
+ const previousProfiles = new Map((previous?.profiles ?? []).map(item => [item.id, item]));
+ const profileIds = new Set();
+ const profiles = input.profiles.map(item => {
+ if (!plainObject(item)) fail('Invalid model profile');
+ const id = identifier(item.id, 'profile ID');
+ if (profileIds.has(id)) fail('Duplicate profile ID');
+ profileIds.add(id);
+ const providerId = identifier(item.providerId, 'provider ID');
+ if (!providersById.has(providerId)) fail(`Unknown provider: ${providerId}`);
+ const model = modelId(item.model);
+ const context = contextForProfile(item, previousProfiles.get(id));
+ return { id, name: text(item.name, 'profile name', 120), providerId, model, efforts: levels(item.efforts, model), ...context };
+ });
+ const profilesById = new Map(profiles.map(item => [item.id, item]));
+ const defaultRoute = normalizeRoute(input.defaultRoute, profilesById, 'default route');
+ if (input.botRoutes !== undefined && !plainObject(input.botRoutes)) fail('Invalid Bot routes');
+ const entries = Object.entries(input.botRoutes ?? {});
+ if (entries.length > MAX_BOT_ROUTES) fail('Too many Bot routes');
+ const botRoutes = {};
+ for (const [agentId, route] of entries) {
+ if (!AGENT_ID.test(agentId)) fail('Invalid Bot ID');
+ botRoutes[agentId] = normalizeRoute(route, profilesById, `Bot route ${agentId}`);
+ }
+ return { version: 1, providers, profiles, defaultRoute, botRoutes };
+}
+
+/** Safe form for administration API responses. */
+export function publicModelRouting(config) {
+ return {
+ version: 1,
+ providers: (config.providers ?? []).map(({ apiKey, ...provider }) => ({ ...provider, hasApiKey: Boolean(apiKey) })),
+ profiles: (config.profiles ?? []).map(profile => ({ ...profile, efforts: [...profile.efforts] })),
+ defaultRoute: config.defaultRoute ? structuredClone(config.defaultRoute) : null,
+ botRoutes: structuredClone(config.botRoutes ?? {}),
+ };
+}
+
+function candidate(profile, provider, route) {
+ return {
+ profileId: profile.id, profileName: profile.name, providerId: provider.id, providerName: provider.name,
+ apiFormat: provider.apiFormat, baseUrl: provider.baseUrl, apiKey: provider.apiKey,
+ model: profile.model, efforts: [...profile.efforts], effort: route.effort,
+ contextWindowTokens: profile.contextWindowTokens, summaryThresholdTokens: profile.summaryThresholdTokens,
+ };
+}
+
+function routeContext(candidates) {
+ const capacities = candidates.map(item => item.contextWindowTokens).filter(value => value > 0);
+ const contextWindowTokens = capacities.length ? Math.min(...capacities) : 0;
+ const thresholds = candidates.map(item => item.summaryThresholdTokens)
+ .filter(value => value > 0 && (!contextWindowTokens || value < contextWindowTokens));
+ return { contextWindowTokens, summaryThresholdTokens: thresholds.length ? Math.min(...thresholds) : 0 };
+}
+
+/** Resolve the configured direct route for a Bot. The returned values include private transport details. */
+export function modelRouteForAgent(config, agentId) {
+ const profiles = new Map(config.profiles.map(item => [item.id, item]));
+ const providers = new Map(config.providers.map(item => [item.id, item]));
+ const botRoute = agentId && config.botRoutes?.[agentId];
+ const route = botRoute ?? config.defaultRoute;
+ if (!route) fail('No default model route');
+ const resolve = item => {
+ const profile = profiles.get(item.profileId);
+ const provider = profile ? providers.get(profile.providerId) : undefined;
+ if (!profile || !provider) fail(`Invalid configured profile: ${item.profileId}`);
+ return candidate(profile, provider, item);
+ };
+ const primary = resolve(route);
+ const fallbacks = route.fallbacks.map(resolve);
+ return { ...primary, fallbacks, routeSource: botRoute ? 'bot' : 'default', agentId: agentId || undefined,
+ ...routeContext([primary, ...fallbacks]) };
+}
+
+/** Resolve one profile for catalog and connection tests without its route fallback chain. */
+export function modelRouteForProfile(config, profileId, { effort = 'default' } = {}) {
+ const profiles = new Map(config.profiles.map(item => [item.id, item]));
+ const providers = new Map(config.providers.map(item => [item.id, item]));
+ const id = identifier(profileId, 'profile ID');
+ const profile = profiles.get(id);
+ const provider = profile ? providers.get(profile.providerId) : undefined;
+ if (!profile || !provider) fail(`Unknown profile: ${id}`);
+ const route = { profileId: id, effort: routeEffort(effort, profile), fallbacks: [] };
+ return { ...candidate(profile, provider, route), fallbacks: [], routeSource: 'profile', ...routeContext([candidate(profile, provider, route)]) };
+}
+
+export function isConfiguredModelRouting(config) {
+ try {
+ const route = modelRouteForAgent(config);
+ return Boolean(route.baseUrl && route.apiKey && route.model);
+ } catch {
+ return false;
+ }
+}
diff --git a/host/runtime/model-session.mjs b/host/runtime/model-session.mjs
index b97707490cce3fa963ca56a5513b9a366ca51461..5a43fb91cf9bec62d154cc3372f35fe03afab780 100644
--- a/host/runtime/model-session.mjs
+++ b/host/runtime/model-session.mjs
@@ -1,183 +1,139 @@
+// Model session for the original Harness: one streamed turn per call, in the configured
+// API format. Formats share request selection, cancellation, usage and completion.
import { randomUUID } from 'node:crypto';
+import { ModelRequestError } from './model-common.mjs';
+import { chatEndpoint, chatTurn, convertChatMessages, convertChatTools } from './openai-chat.mjs';
+import { responsesEndpoint, responsesTurn } from './openai-responses.mjs';
+import { anthropicEndpoint, anthropicTurn } from './anthropic-messages.mjs';
+export { ModelRequestError };
export const SUPPORTED_MODELS = Object.freeze([
'deepseek-flash', 'deepseek-v4.1-flash', 'deepseek-v4.1-flash-sg',
]);
+export const API_FORMATS = Object.freeze(['openai', 'openai-responses', 'anthropic']);
-export class ModelRequestError extends Error {
- constructor(message, { status, code, retryAfterMs, cause } = {}) {
- super(message, { cause });
- this.name = 'ModelRequestError';
- this.status = status;
- this.code = code;
- this.retryAfterMs = retryAfterMs;
- }
+/** Translate the original Harness CoreMessage representation (OpenAI Chat) without losing screenshots. */
+export const convertMessages = messages => convertChatMessages(messages);
+export const convertTools = convertChatTools;
+
+const FORMATS = {
+ openai: { endpoint: chatEndpoint, turn: chatTurn },
+ 'openai-responses': { endpoint: responsesEndpoint, turn: responsesTurn },
+ anthropic: { endpoint: baseUrl => anthropicEndpoint(baseUrl), turn: anthropicTurn },
+};
+
+function deferred() {
+ let resolve, reject;
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
+ // Consumers read several promises after fullStream; reject all without unhandled rejections.
+ promise.catch(() => {});
+ return { promise, resolve, reject };
}
-function retryAfterMs(headers) {
- const value = headers?.get('retry-after')?.trim();
- if (!value) return undefined;
- if (/^\d+(?:\.\d+)?$/.test(value)) {
- const milliseconds = Number(value) * 1000;
- return Number.isFinite(milliseconds) ? milliseconds : undefined;
- }
- // HTTP-date is the other Retry-After form; reject numeric-looking invalid values.
- if (!/[a-z]/i.test(value)) return undefined;
- const deadline = Date.parse(value);
- return Number.isFinite(deadline) ? Math.max(0, deadline - Date.now()) : undefined;
+function abortError(reason) {
+ return reason instanceof Error ? reason : new DOMException('Model stream was canceled', 'AbortError');
}
-function imageUrl(part) {
- const value = part.image ?? part.data ?? part.url;
- if (value instanceof URL) return imageUrl({ ...part, image: value.href });
- if (typeof value === 'string') {
- if (/^(https?:\/\/|data:image\/)/i.test(value)) return value;
- if (/^[a-z][\w+.-]*:/i.test(value)) throw new TypeError('Unsupported image URL scheme');
- if (!value.trim()) throw new TypeError('Image content is empty');
- return `data:${part.mimeType ?? 'image/png'};base64,${value}`;
- }
- if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
- const bytes = value instanceof ArrayBuffer ? Buffer.from(value)
- : Buffer.from(value.buffer, value.byteOffset, value.byteLength);
- return `data:${part.mimeType ?? 'image/png'};base64,${bytes.toString('base64')}`;
- }
- throw new TypeError('Image must contain a URL, base64 string, or bytes');
+// Arm a deadline only while waiting for upstream I/O, never while paused at a yield.
+function ioDeadline(controller, ms) {
+ const { signal } = controller;
+ return async action => {
+ signal.throwIfAborted();
+ let onAbort;
+ const canceled = new Promise((_, reject) => {
+ onAbort = () => reject(signal.reason);
+ signal.addEventListener('abort', onAbort, { once: true });
+ });
+ const timer = setTimeout(() => controller.abort(new DOMException(`Model upstream idle for ${ms} ms`, 'TimeoutError')), ms);
+ timer.unref();
+ try { return await Promise.race([canceled, Promise.resolve().then(() => { signal.throwIfAborted(); return action(); })]); }
+ finally { clearTimeout(timer); signal.removeEventListener('abort', onAbort); }
+ };
}
-function textValue(value) {
- return typeof value === 'string' ? value : JSON.stringify(value ?? '');
+function candidateKey(candidate) {
+ // Stable IDs keep provider URLs and credentials out of adaptation state and logs.
+ return candidate.profileId ?? `${candidate.apiFormat}\n${candidate.baseUrl}\n${candidate.model}`;
}
-/** Translate the original Harness CoreMessage representation without losing screenshots. */
-export function convertMessages(messages) {
- const output = [];
- let toolImages = [];
- const flushToolImages = () => {
- if (!toolImages.length) return;
- output.push({ role: 'user', content: [
- { type: 'text', text: 'Screenshots from the preceding tool results:' }, ...toolImages,
- ] });
- toolImages = [];
+function requestCandidate(value, defaults) {
+ const candidate = {
+ baseUrl: value?.baseUrl ?? defaults.baseUrl,
+ apiKey: value?.apiKey ?? defaults.apiKey,
+ apiFormat: value?.apiFormat ?? defaults.apiFormat,
+ model: value?.model ?? defaults.model,
+ effort: value?.effort ?? defaults.effort,
+ efforts: value?.efforts ?? defaults.efforts,
+ requestOptions: value?.requestOptions ?? defaults.requestOptions,
+ contextWindowTokens: value?.contextWindowTokens ?? defaults.contextWindowTokens,
+ summaryThresholdTokens: value?.summaryThresholdTokens ?? defaults.summaryThresholdTokens,
+ profileId: value?.profileId ?? defaults.profileId,
+ profileName: value?.profileName ?? defaults.profileName,
+ providerId: value?.providerId ?? defaults.providerId,
+ providerName: value?.providerName ?? defaults.providerName,
};
- for (const message of messages) {
- if (message.role !== 'tool') flushToolImages();
- const parts = typeof message.content === 'string'
- ? [{ type: 'text', text: message.content }] : message.content ?? [];
- if (message.role === 'tool') {
- for (const part of parts) {
- if (part.type !== 'tool-result' || !part.toolCallId) {
- throw new TypeError('Tool messages require tool-result parts and toolCallId');
- }
- const extra = part.experimental_content ?? [];
- const fallback = extra.filter(p => p.type === 'text').map(p => p.text).join('\n');
- output.push({ role: 'tool', tool_call_id: part.toolCallId,
- content: part.result === undefined ? fallback : textValue(part.result) });
- toolImages.push(...extra.filter(p => p.type === 'image').map(p => ({
- type: 'image_url', image_url: { url: imageUrl(p) },
- })));
- }
- } else if (message.role === 'assistant') {
- const content = parts.filter(p => p.type === 'text').map(p => p.text).join('');
- const reasoning = parts.filter(p => p.type === 'reasoning').map(p => p.text).join('');
- const calls = parts.filter(p => p.type === 'tool-call').map(p => ({
- id: p.toolCallId, type: 'function',
- function: { name: p.toolName, arguments: textValue(p.args ?? {}) },
- }));
- output.push({ role: 'assistant', content: content || (calls.length ? null : ''),
- ...(reasoning ? { reasoning_content: reasoning } : {}),
- ...(calls.length ? { tool_calls: calls } : {}) });
- } else if (['user', 'system', 'developer'].includes(message.role)) {
- const content = parts.map(part => {
- if (part.type === 'text') return { type: 'text', text: part.text };
- if (part.type === 'image' && message.role === 'user') {
- return { type: 'image_url', image_url: { url: imageUrl(part) } };
- }
- throw new TypeError(`Unsupported ${message.role} content type: ${part.type}`);
- });
- output.push({ role: message.role, content: content.every(p => p.type === 'text')
- ? content.map(p => p.text).join('') : content });
- } else {
- throw new TypeError(`Unsupported message role: ${message.role}`);
- }
+ if (typeof candidate.baseUrl !== 'string' || !candidate.baseUrl ||
+ (candidate.apiKey !== undefined && typeof candidate.apiKey !== 'string') ||
+ typeof candidate.model !== 'string' || !candidate.model.trim() ||
+ !FORMATS[candidate.apiFormat]) {
+ throw new TypeError('selected model must include a configured provider, format, and model');
}
- flushToolImages();
- return output;
+ return candidate;
}
-export function convertTools(tools = []) {
- return tools.map(tool => {
- if (tool.type === 'provider-defined' || tool.customToolFormat) {
- throw new TypeError('This session supports JSON function tools only');
- }
- if (typeof tool.name !== 'string' || !tool.name) throw new TypeError('Tool name is required');
- const parameters = tool.parameters?.jsonSchema ?? tool.parameters;
- if (!parameters || typeof parameters !== 'object') throw new TypeError('Tool schema is required');
- return { type: 'function', function: {
- name: tool.name, description: tool.description ?? '', parameters,
- } };
- });
+function quotaExhausted(error) {
+ const code = typeof error?.code === 'string' ? error.code : '';
+ if (code === 'API_KEY_QUOTA_EXHAUSTED' || code === 'insufficient_quota') return true;
+ // A bare 402 is a balance error, but a 429 or a model-specific quota
+ // message can be temporary and must remain retryable.
+ if (error?.status === 402 && !code) return true;
+ return /(?:api[ _-]?key|account)\s+(?:quota|credit|balance)\s+(?:is\s+)?(?:exhausted|used up|depleted|exceeded)|(?:账户|账户余额|API\s*额度|额度)\s*(?:已)?\s*(?:用完|耗尽|不足)/i.test(error?.message ?? '');
}
-function deferred() {
- let resolve, reject;
- const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
- // Consumers read several promises after fullStream; reject all without unhandled rejections.
- promise.catch(() => {});
- return { promise, resolve, reject };
+function retryableFailure(error, { controller, upstreamSignal, idleTimedOut }) {
+ if (controller.signal.aborted || upstreamSignal?.aborted) return idleTimedOut();
+ if (error?.name === 'TimeoutError') return true;
+ if (error?.name === 'AbortError') return false;
+ if (error?.status === 408 || error?.status === 402 || error?.status === 429 ||
+ (Number.isInteger(error?.status) && error.status >= 500 && error.status <= 599)) return true;
+ if (Number.isInteger(error?.status) || error instanceof ModelRequestError) return false;
+ return error?.name === 'TypeError' || ['ECONNABORTED', 'ECONNREFUSED', 'ECONNRESET', 'EHOSTUNREACH',
+ 'ENETUNREACH', 'ETIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_SOCKET'].includes(error?.code);
}
-function abortError(reason) {
- return reason instanceof Error ? reason : new DOMException('Model stream was canceled', 'AbortError');
+function distinctCredentialCandidates(candidates, { exhausted = false } = {}) {
+ if (!exhausted) return candidates;
+ const keys = new Set();
+ return candidates.filter(candidate => {
+ // A fallback sharing a key has the same quota and cannot recover an exhausted account.
+ if (keys.has(candidate.apiKey)) return false;
+ keys.add(candidate.apiKey);
+ return true;
+ });
}
-/** SSE events can cross UTF-8 chunks and use LF, CRLF, or CR line endings. */
-async function* readSse(body) {
- if (!body) throw new ModelRequestError('Model response has no body');
- const reader = body.getReader();
- const decoder = new TextDecoder();
- let pending = '', data = [];
- function accept(line) {
- if (line === '') {
- const event = data.length ? data.join('\n') : undefined;
- data = [];
- return event;
- }
- if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
- return undefined;
- }
- try {
- while (true) {
- const { value, done } = await reader.read();
- pending += done ? decoder.decode() : decoder.decode(value, { stream: true });
- let match;
- while ((match = /\r\n|\r|\n/.exec(pending))) {
- if (!done && match[0] === '\r' && match.index === pending.length - 1) break;
- const line = pending.slice(0, match.index);
- pending = pending.slice(match.index + match[0].length);
- const event = accept(line);
- if (event !== undefined) yield event;
- }
- if (done) {
- if (pending) accept(pending);
- const event = accept('');
- if (event !== undefined) yield event;
- break;
- }
- }
- } finally {
- await reader.cancel().catch(() => {});
- reader.releaseLock();
- }
+function skippedCredentialCandidates(candidates) {
+ const keys = new Set();
+ return candidates.filter(candidate => {
+ const duplicate = keys.has(candidate.apiKey);
+ keys.add(candidate.apiKey);
+ return duplicate;
+ });
+}
+
+function publicCandidate(candidate) {
+ return { profileId: candidate.profileId, profileName: candidate.profileName,
+ providerId: candidate.providerId, providerName: candidate.providerName,
+ apiFormat: candidate.apiFormat, model: candidate.model };
}
-function endpointFor(baseUrl) {
- const url = new URL(baseUrl);
- if (!['http:', 'https:'].includes(url.protocol)) throw new TypeError('baseUrl must use HTTP or HTTPS');
- url.pathname = url.pathname.replace(/\/+$/, '');
- if (!url.pathname.endsWith('/chat/completions')) url.pathname += '/chat/completions';
- return url.href;
+function compactionCapabilities({ contextWindowTokens, summaryThresholdTokens }) {
+ if (!Number.isSafeInteger(contextWindowTokens) || !Number.isSafeInteger(summaryThresholdTokens) ||
+ summaryThresholdTokens <= 0 || summaryThresholdTokens >= contextWindowTokens) return {};
+ return { supportsSelfSummary: true, earlyCompactionContextTokenThreshold: summaryThresholdTokens };
}
+/** Usage arrives normalized to OpenAI Chat fields from every format. */
function usageValues(raw = {}, contextWindowTokens = 0) {
const count = value => Number.isFinite(value) && value >= 0 ? value : 0;
const inputTokens = count(raw.prompt_tokens), outputTokens = count(raw.completion_tokens);
@@ -190,32 +146,35 @@ function usageValues(raw = {}, contextWindowTokens = 0) {
};
}
-export function createModelSession({ baseUrl, apiKey, model, onRequestId,
+export function createModelSession({ baseUrl, apiKey, model, onRequestId, apiFormat = 'openai', policy,
fetchImpl = globalThis.fetch, headers = {}, requestOptions = {}, contextWindowTokens = 0,
- summaryThresholdTokens = 0, mapError = error => error, onUsage = async () => {}, selectRequest } = {}) {
+ summaryThresholdTokens = 0, mapError = error => error, onUsage = async () => {}, selectRequest,
+ onFallback = async () => {}, idleTimeoutMs = 300_000, profileId, providerId, efforts } = {}) {
if (typeof model !== 'string' || !model.trim() || model !== model.trim() || model.length > 256 || /[\r\n\0]/.test(model)) {
throw new TypeError('model must be an explicitly selected, nonempty model ID');
}
if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
if (typeof mapError !== 'function') throw new TypeError('mapError must be a function');
+ if (!Number.isInteger(idleTimeoutMs) || idleTimeoutMs < 1 || idleTimeoutMs > 2_147_483_647) {
+ throw new TypeError('idleTimeoutMs must be a positive timer interval');
+ }
if (!Number.isSafeInteger(contextWindowTokens) || contextWindowTokens < 0) {
throw new TypeError('contextWindowTokens must be a nonnegative integer');
}
- const endpoint = endpointFor(baseUrl);
+ if (!FORMATS[apiFormat]) throw new TypeError(`apiFormat must be one of ${API_FORMATS.join(', ')}`);
+ // Adaptive routing may select models with different parameter and replay support.
+ const adaptations = new Map();
+ // Once a fallback accepts a call, keep using it for the rest of this session.
+ // The Harness opens a session per turn, so the next turn tries the primary
+ // again. Returning to a primary that expects its own signed thinking within
+ // the tool loop would make the next step invalid when the fallback stripped it.
+ let preferredKey;
+ const defaults = { baseUrl, apiKey, apiFormat, model, requestOptions, contextWindowTokens,
+ summaryThresholdTokens, profileId, providerId, efforts };
+ const effortsFor = id => policy?.models?.find(entry => entry.id === id)?.efforts;
let resolvedModelId;
let selectedContext = { contextWindowTokens, summaryThresholdTokens };
- function providerError(payload, status, responseHeaders) {
- const error = payload?.error ?? payload;
- let message = typeof error?.message === 'string' ? error.message : `Model request failed${status ? ` (HTTP ${status})` : ''}`;
- if (apiKey) message = message.split(apiKey).join('[redacted]');
- const reportedStatus = error?.status ?? error?.status_code;
- return new ModelRequestError(message, {
- status: status ?? (Number.isInteger(reportedStatus) && reportedStatus >= 400 && reportedStatus <= 599
- ? reportedStatus : undefined),
- code: typeof error?.code === 'string' || typeof error?.code === 'number' ? error.code : undefined,
- retryAfterMs: retryAfterMs(responseHeaders),
- });
- }
+ let earlyCompaction;
class Executor {
constructor(initialMessages, trackModel) {
@@ -230,24 +189,44 @@ export function createModelSession({ baseUrl, apiKey, model, onRequestId,
const slots = Object.fromEntries(['response', 'usage', 'extendedUsage', 'providerMetadata', 'invocationId'].map(key => [key, deferred()]));
const controller = new AbortController();
const signal = ctx?.signal;
+ const waitForIO = ioDeadline(controller, idleTimeoutMs);
let settled = false;
const fail = error => {
if (settled) return;
settled = true;
Object.values(slots).forEach(slot => slot.reject(error));
};
- const cancel = () => {
- const error = abortError(signal?.reason);
- controller.abort(error);
- fail(error);
- };
- if (signal?.aborted) cancel();
- else signal?.addEventListener('abort', cancel, { once: true });
const messages = this.getMessages();
const trackModel = this.trackModel;
async function* produce() {
let notified = false;
- let recordedUsage, reportedModel = model, reportedId, selectedEffort;
+ let recordedUsage, reportedModel = model, reportedId, selectedEffort, reportedCandidate;
+ let usageWrite, usagePending = false;
+ const attemptUsages = [];
+ const snapshotUsage = () => {
+ if (!recordedUsage) return;
+ attemptUsages.push({
+ raw: recordedUsage,
+ model: reportedModel,
+ requestId: reportedId,
+ effort: selectedEffort,
+ profileId: reportedCandidate?.profileId,
+ providerId: reportedCandidate?.providerId,
+ });
+ recordedUsage = undefined;
+ };
+ const recordUsage = () => {
+ snapshotUsage();
+ if (!usageWrite || usagePending) {
+ usagePending = true;
+ const queued = usageWrite ?? Promise.resolve();
+ usageWrite = queued.then(async () => {
+ for (const usage of attemptUsages.splice(0)) await onUsage(usage);
+ }).catch(error => console.error(`[usage] ${error.message}`))
+ .finally(() => { usagePending = false; });
+ }
+ return usageWrite;
+ };
const notifyRequest = id => {
if (!notified && id) {
notified = true;
@@ -256,130 +235,166 @@ export function createModelSession({ baseUrl, apiKey, model, onRequestId,
};
try {
controller.signal.throwIfAborted();
- const functions = convertTools(tools);
- const selected = await selectRequest?.({ messages, signal: controller.signal });
- const requestContext = { contextWindowTokens: selected?.contextWindowTokens ?? contextWindowTokens,
- summaryThresholdTokens: selected?.summaryThresholdTokens ?? summaryThresholdTokens };
- if (trackModel) selectedContext = requestContext;
- const selectedModel = selected?.model ?? model;
- reportedModel = selectedModel; selectedEffort = selected?.effort;
- const body = { ...requestOptions, ...selected?.requestOptions, model: selectedModel, messages: convertMessages(messages), stream: true,
- stream_options: { ...requestOptions.stream_options, include_usage: true },
- ...(functions.length ? { tools: functions } : {}),
- ...(options.maxTokens !== undefined ? { max_tokens: options.maxTokens } : {}) };
- // A caller cannot replace the original Harness tool surface through requestOptions.
- if (!functions.length) delete body.tools;
- const requestHeaders = new Headers(headers);
- requestHeaders.set('content-type', 'application/json');
- requestHeaders.set('accept', 'text/event-stream');
- if (apiKey) requestHeaders.set('authorization', `Bearer ${apiKey}`);
- const http = await fetchImpl(endpoint, { method: 'POST', headers: requestHeaders,
- body: JSON.stringify(body), signal: controller.signal });
- if (!http.ok) {
- let payload;
- try { payload = await http.json(); } catch { payload = undefined; }
- throw providerError(payload, http.status, http.headers);
- }
- notifyRequest(http.headers.get('x-request-id') ?? http.headers.get('request-id'));
- let id, responseModel = selectedModel, created, text = '', reasoning = '', rawUsage = {};
- let finishReason, receivedChoice = false, receivedDone = false;
- const toolCalls = new Map();
- for await (const data of readSse(http.body)) {
- controller.signal.throwIfAborted();
- if (data.trim() === '[DONE]') { receivedDone = true; break; }
- let chunk;
- try { chunk = JSON.parse(data); }
- catch (cause) { throw new ModelRequestError('Invalid JSON in model SSE event', { cause }); }
- if (chunk.error) throw providerError(chunk, undefined, http.headers);
- if (chunk.id) { id = chunk.id; reportedId = id; notifyRequest(id); }
- if (chunk.model) { responseModel = chunk.model; reportedModel = responseModel; }
- if (Number.isFinite(chunk.created)) created = chunk.created;
- if (chunk.usage) { rawUsage = { ...rawUsage, ...chunk.usage }; recordedUsage = rawUsage; }
- const choice = chunk.choices?.find(item => (item.index ?? 0) === 0);
- if (!choice) continue;
- receivedChoice = true;
- if (choice.finish_reason) finishReason = choice.finish_reason;
- const delta = choice.delta ?? {};
- if (typeof delta.reasoning_content === 'string' && delta.reasoning_content) {
- reasoning += delta.reasoning_content;
- yield { type: 'reasoning', textDelta: delta.reasoning_content };
- }
- if (typeof delta.content === 'string' && delta.content) {
- text += delta.content;
- yield { type: 'text-delta', textDelta: delta.content };
- }
- for (const part of delta.tool_calls ?? []) {
- const index = part.index ?? 0;
- const call = toolCalls.get(index) ?? { id: '', name: '', arguments: '' };
- if (part.id) call.id += part.id;
- if (part.function?.name) call.name += part.function.name;
- if (part.function?.arguments) call.arguments += part.function.arguments;
- toolCalls.set(index, call);
+ const selected = selectRequest ? await waitForIO(() => selectRequest({ messages, signal: controller.signal })) : undefined;
+ const requested = requestCandidate(selected, defaults);
+ const configured = [requested,
+ ...((selected?.fallbacks ?? []).map(candidate => requestCandidate(candidate, defaults)))];
+ const preferredIndex = preferredKey ? configured.findIndex(candidate => candidateKey(candidate) === preferredKey) : -1;
+ const ordered = preferredIndex > 0
+ ? [configured[preferredIndex], ...configured.filter((_, index) => index !== preferredIndex)]
+ : configured;
+ const primary = ordered[0];
+ let candidates = ordered;
+ const requestContext = { contextWindowTokens: primary.contextWindowTokens,
+ summaryThresholdTokens: primary.summaryThresholdTokens };
+ if (trackModel) { selectedContext = requestContext; earlyCompaction = undefined; }
+ let turn;
+ let activeIterator;
+ for (let attempt = 0; attempt < candidates.length; attempt++) {
+ const candidate = candidates[attempt];
+ const format = FORMATS[candidate.apiFormat];
+ const attemptController = new AbortController();
+ const onCancel = () => attemptController.abort(controller.signal.reason);
+ controller.signal.addEventListener('abort', onCancel, { once: true });
+ const attemptSignal = attemptController.signal;
+ let idleTimedOut = false;
+ attemptSignal.addEventListener('abort', () => {
+ if (attemptSignal.reason?.name === 'TimeoutError') idleTimedOut = true;
+ }, { once: true });
+ const attemptWaitForIO = ioDeadline(attemptController, idleTimeoutMs);
+ const adaptationKey = candidateKey(candidate);
+ if (!adaptations.has(adaptationKey)) adaptations.set(adaptationKey, { dropped: new Set(), stripReasoning: false, toolImagesAsMessage: false });
+ let emittedVisibleOutput = false;
+ recordedUsage = undefined;
+ reportedId = undefined;
+ reportedModel = candidate.model;
+ selectedEffort = candidate.effort;
+ reportedCandidate = candidate;
+ try {
+ const iterator = format.turn({ fetchImpl, endpoint: format.endpoint(candidate.baseUrl), apiKey: candidate.apiKey,
+ headers, model: candidate.model, messages, tools,
+ effort: candidate.effort ?? candidate.requestOptions?.reasoning_effort,
+ efforts: candidate.efforts ?? effortsFor(candidate.model), maxTokens: options.maxTokens,
+ requestOptions: candidate.requestOptions, signal: attemptSignal, waitForIO: attemptWaitForIO,
+ state: adaptations.get(adaptationKey), notifyRequest,
+ providerId: candidate.providerId,
+ onModel: value => { reportedModel = value; }, onId: value => { reportedId = value; },
+ onUsage: value => { recordedUsage = value; } });
+ activeIterator = iterator;
+ while (true) {
+ const next = await iterator.next();
+ if (next.done) { turn = next.value; break; }
+ // Reasoning is hidden. A fallback is still safe until text or a tool call escapes.
+ if (next.value?.type !== 'reasoning') emittedVisibleOutput = true;
+ yield next.value;
+ }
+ activeIterator = undefined;
+ break;
+ } catch (error) {
+ // A cancellation can arrive while onFallback() is still awaiting. Do
+ // not attach another request to an already-canceled controller.
+ controller.signal.throwIfAborted();
+ if (quotaExhausted(error)) {
+ const remaining = candidates.slice(attempt);
+ const skipped = skippedCredentialCandidates(remaining);
+ candidates = distinctCredentialCandidates(candidates, { exhausted: true });
+ const nextDistinct = candidates[attempt + 1];
+ if (skipped.length) {
+ try {
+ await onFallback({ from: publicCandidate(candidate), to: nextDistinct ? publicCandidate(nextDistinct) : undefined,
+ attempt: attempt + 1, reason: 'quota', skipped: skipped.map(publicCandidate) });
+ } catch (logError) {
+ console.warn(`[model-session] Unable to record skipped model fallback: ${logError.code ?? logError.name}`);
+ }
+ }
+ }
+ const next = candidates[attempt + 1];
+ if (emittedVisibleOutput || !next || !retryableFailure(error, {
+ controller: attemptController, upstreamSignal: signal, idleTimedOut: () => idleTimedOut,
+ })) throw error;
+ try {
+ await onFallback({ from: publicCandidate(candidate), to: publicCandidate(next), attempt: attempt + 1,
+ reason: idleTimedOut ? 'timeout'
+ : Number.isInteger(error?.status) ? `HTTP ${error.status}` : 'network' });
+ } catch (logError) {
+ console.warn(`[model-session] Unable to record model fallback: ${logError.code ?? logError.name}`);
+ }
+ preferredKey = candidateKey(next);
+ controller.signal.throwIfAborted();
+ } finally {
+ if (activeIterator) {
+ await activeIterator.return().catch(() => {});
+ activeIterator = undefined;
+ }
+ controller.signal.removeEventListener('abort', onCancel);
+ attemptController.abort();
}
}
+ if (!turn) throw new ModelRequestError('All configured model attempts failed');
controller.signal.throwIfAborted();
- if (!receivedChoice || (!receivedDone && !finishReason)) {
- throw new ModelRequestError('Model SSE stream ended before a completion marker');
- }
- if (finishReason === 'length' || finishReason === 'content_filter') {
- throw new ModelRequestError(`Model response stopped with ${finishReason}`, { code: finishReason });
- }
- const content = [];
- if (reasoning) content.push({ type: 'reasoning', text: reasoning });
- if (text) content.push({ type: 'text', text });
- const calls = [...toolCalls.entries()].sort(([a], [b]) => a - b).map(([, call]) => {
- if (!call.id || !call.name) throw new ModelRequestError('Incomplete model tool call identity');
- let args;
- try { args = JSON.parse(call.arguments || '{}'); }
- catch (cause) { throw new ModelRequestError(`Invalid tool arguments for ${call.name}`, { cause }); }
- return { type: 'tool-call', toolCallId: call.id, toolName: call.name, args };
- });
- // Original Harness consumes one argument stream at a time; serialize parallel calls.
- for (const call of calls) {
- const { toolCallId, toolName, args } = call;
- yield { type: 'tool-call-streaming-start', toolCallId, toolName };
- yield { type: 'tool-call-delta', toolCallId, toolName, argsTextDelta: JSON.stringify(args) };
- yield call;
- content.push(call);
- }
- const responseId = id ?? randomUUID();
+ const responseId = turn.id ?? randomUUID();
notifyRequest(responseId);
- const timestamp = created === undefined ? new Date() : new Date(created * 1000);
+ const timestamp = new Date();
// Harness interprets maxTokens as context capacity, not the output token limit.
- const values = usageValues(rawUsage, requestContext.contextWindowTokens);
- if (trackModel) resolvedModelId = responseModel;
- slots.response.resolve({ id: responseId, timestamp, modelId: responseModel,
- messages: [{ id: responseId, role: 'assistant', content }] });
+ const values = usageValues(turn.usage, requestContext.contextWindowTokens);
+ const compaction = compactionCapabilities(requestContext);
+ if (trackModel) {
+ resolvedModelId = turn.model;
+ earlyCompaction = compaction.earlyCompactionContextTokenThreshold === undefined ? undefined : {
+ threshold: compaction.earlyCompactionContextTokenThreshold,
+ inputTokens: values.extendedUsage.inputTokens,
+ };
+ }
+ slots.response.resolve({ id: responseId, timestamp, modelId: turn.model,
+ messages: [{ id: responseId, role: 'assistant', content: turn.content }], ...compaction });
slots.usage.resolve(values.usage);
slots.extendedUsage.resolve(values.extendedUsage);
slots.providerMetadata.resolve(undefined);
slots.invocationId.resolve(invocationId ?? responseId);
settled = true;
- yield { type: 'finish', finishReason: calls.length ? 'tool-calls' : (finishReason ?? 'stop'),
- usage: values.usage, response: { id: responseId, timestamp, modelId: responseModel } };
+ // A consumer may stop on finish without ever asking for the iterator's done step.
+ signal?.removeEventListener('abort', onAbort);
+ recordUsage();
+ yield { type: 'finish', finishReason: turn.toolCalls ? 'tool-calls' : 'stop',
+ usage: values.usage, response: { id: responseId, timestamp, modelId: turn.model } };
} catch (error) {
- const mapped = mapError(error);
+ let mapped;
+ try { mapped = controller.signal.aborted ? controller.signal.reason : mapError(error); }
+ catch (mappingError) { mapped = mappingError; }
fail(mapped);
throw mapped;
} finally {
- if (recordedUsage) {
- try { await onUsage({ raw: recordedUsage, model: reportedModel, requestId: reportedId, effort: selectedEffort }); }
- catch (error) { console.error(`[usage] ${error.message}`); }
- }
- signal?.removeEventListener('abort', cancel);
+ signal?.removeEventListener('abort', onAbort);
if (!settled) fail(abortError());
- controller.abort();
+ await recordUsage();
}
}
const iterator = produce();
+ let closing;
+ const cancel = error => {
+ signal?.removeEventListener('abort', onAbort);
+ if (!settled) { controller.abort(error); fail(controller.signal.reason); }
+ };
+ const onAbort = () => {
+ cancel(abortError(signal.reason));
+ // A paused consumer need not pull again to unlock the reader and record observed usage.
+ closing ??= iterator.return().catch(() => {});
+ };
+ if (signal?.aborted) onAbort();
+ else signal?.addEventListener('abort', onAbort, { once: true });
const fullStream = {
[Symbol.asyncIterator]() { return this; },
- next: value => iterator.next(value),
- return: value => { cancel(); signal?.removeEventListener('abort', cancel); return iterator.return(value); },
- throw: error => {
- fail(error); controller.abort(error); signal?.removeEventListener('abort', cancel);
- return iterator.throw(error);
+ async next(value) {
+ controller.signal.throwIfAborted();
+ const step = await iterator.next(value);
+ controller.signal.throwIfAborted();
+ return step;
+ },
+ async return(value) {
+ cancel(abortError());
+ return closing ? await closing : iterator.return(value);
},
+ throw: error => { cancel(error); return iterator.throw(error); },
};
return { fullStream, ...Object.fromEntries(Object.entries(slots).map(([key, slot]) => [key, slot.promise])) };
}
@@ -387,7 +402,7 @@ export function createModelSession({ baseUrl, apiKey, model, onRequestId,
return {
getModelId: () => model,
getResolvedModelId: () => resolvedModelId,
- getEarlyCompaction: () => undefined,
+ getEarlyCompaction: () => earlyCompaction && { ...earlyCompaction },
getLocalContextPolicy: () => ({ ...selectedContext }),
getExecutor: state => new Executor(state, true),
getExecutorWithoutResolvedModelTracking: state => new Executor(state, false),
diff --git a/host/runtime/native-desktop.mjs b/host/runtime/native-desktop.mjs
index 57dfb068fad941df6e742e31a23facbb329f5701..74f7194d6c3650380a96bf45536d18f9d4c91609 100644
--- a/host/runtime/native-desktop.mjs
+++ b/host/runtime/native-desktop.mjs
@@ -21,7 +21,7 @@ export async function createNativeDesktop({ permission, enabled = () => true, re
return {
list: async () => enabled() ? (await request('tools', {})).computers : [],
async call({ scope, machineId, toolId, arguments: args = {}, signal }) {
- if (!enabled()) throw new Error('Mac computer control is disabled');
+ if (!enabled()) throw new Error('Computer control is disabled');
const grants = typeof permission === 'function' ? permission() : permission;
if (!scope?.agentId || !scope.toolCallId || !grants) throw new Error('Computer calls require an agent tool scope');
const epoch = scope.directionEpoch ?? grants.directionEpoch(scope.agentId);
@@ -50,7 +50,7 @@ export async function createNativeDesktop({ permission, enabled = () => true, re
}
return { isError: true, content: [{ type: 'text', text: outcome.status === 'needs_permission'
? 'Allow the computer helper in macOS Accessibility and Screen Recording settings.'
- : outcome.status === 'ask' ? 'Approve this application on the target Mac.' : outcome.error || 'Computer action failed' }] };
+ : outcome.status === 'ask' ? 'Approve this application on the target computer.' : outcome.error || 'Computer action failed' }] };
},
};
}
diff --git a/host/runtime/openai-chat.mjs b/host/runtime/openai-chat.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..fb840382bba9eae11a8b8db1d8e2bcaba0a7f3a3
--- /dev/null
+++ b/host/runtime/openai-chat.mjs
@@ -0,0 +1,175 @@
+// OpenAI Chat Completions format (OpenAI and compatible services such as DeepSeek).
+import { explicitEffort, fileKind, fileText, mediaUrl, messageParts, ModelRequestError, parseEvent, parseToolArguments,
+ postWithFallback, providerError, readSse, reasoningOrigin, reasoningProviderOptions, rejectedOption, streamToolCalls, textValue, toolSchema,
+ unsupportedFileNote, validFunctionName } from './model-common.mjs';
+
+export const FORMAT = 'openai';
+
+export function chatEndpoint(baseUrl) {
+ const url = new URL(baseUrl);
+ if (!['http:', 'https:'].includes(url.protocol)) throw new TypeError('baseUrl must use HTTP or HTTPS');
+ url.pathname = url.pathname.replace(/\/+$/, '');
+ if (!url.pathname.endsWith('/chat/completions')) url.pathname += '/chat/completions';
+ return url.href;
+}
+
+// Reasoning models of OpenAI take max_completion_tokens; most compatible servers take max_tokens.
+const COMPLETION_TOKENS = /^(?:o\d|gpt-5|gpt-6|gpt-4\.1|codex)/i;
+export function maxTokensParameter(model, dropped = new Set()) {
+ const preferred = COMPLETION_TOKENS.test(model) ? 'max_completion_tokens' : 'max_tokens';
+ const other = preferred === 'max_tokens' ? 'max_completion_tokens' : 'max_tokens';
+ return !dropped.has(preferred) ? preferred : !dropped.has(other) ? other : undefined;
+}
+
+/** Chat reasoning parameters: reasoning_effort, plus DeepSeek's thinking switch. */
+export function chatReasoning(model, effort) {
+ const level = explicitEffort(effort);
+ if (!level) return {};
+ return { reasoning_effort: level, ...(/deepseek/i.test(model) ? { thinking: { type: level === 'none' ? 'disabled' : 'enabled' } } : {}) };
+}
+
+function contentPart(part, role) {
+ if (part.type === 'text') return { type: 'text', text: part.text };
+ if (part.type === 'image' && role === 'user') return { type: 'image_url', image_url: { url: mediaUrl(part) } };
+ if (part.type === 'file' && role === 'user') {
+ const kind = fileKind(part);
+ if (kind === 'image') return { type: 'image_url', image_url: { url: mediaUrl(part, part.mimeType) } };
+ if (kind === 'pdf') return { type: 'file', file: { filename: part.filename ?? 'document.pdf', file_data: mediaUrl(part, part.mimeType) } };
+ if (kind === 'text') return { type: 'text', text: `${part.filename ? `${part.filename}:\n` : ''}${fileText(part)}` };
+ return { type: 'text', text: unsupportedFileNote(part) };
+ }
+ throw new TypeError(`Unsupported ${role} content type: ${part.type}`);
+}
+
+/**
+ * Translate CoreMessages without losing screenshots. reasoning_content is replayed only for
+ * reasoning this format produced for the same model (DeepSeek needs it during tool use).
+ */
+export function convertChatMessages(messages, { model, providerId, replayReasoning = true } = {}) {
+ const output = [];
+ let toolImages = [];
+ const skippedToolCalls = new Set();
+ const flushToolImages = () => {
+ if (!toolImages.length) return;
+ output.push({ role: 'user', content: [{ type: 'text', text: 'Screenshots from the preceding tool results:' }, ...toolImages] });
+ toolImages = [];
+ };
+ for (const message of messages) {
+ if (message.role !== 'tool') flushToolImages();
+ const parts = messageParts(message);
+ if (message.role === 'tool') {
+ for (const part of parts) {
+ if (part.type !== 'tool-result' || !part.toolCallId) throw new TypeError('Tool messages require tool-result parts and toolCallId');
+ if (skippedToolCalls.has(part.toolCallId)) continue;
+ const extra = part.experimental_content ?? [];
+ const fallback = extra.filter(p => p.type === 'text').map(p => p.text).join('\n');
+ output.push({ role: 'tool', tool_call_id: part.toolCallId, content: part.result === undefined ? fallback : textValue(part.result) });
+ toolImages.push(...extra.filter(p => p.type === 'image').map(p => ({ type: 'image_url', image_url: { url: mediaUrl(p) } })));
+ }
+ } else if (message.role === 'assistant') {
+ const content = parts.filter(p => p.type === 'text').map(p => p.text).join('');
+ const reasoning = replayReasoning ? parts.filter(p => {
+ if (p.type !== 'reasoning' || !p.text) return false;
+ const origin = reasoningOrigin(p);
+ // Legacy parts carry no origin; signed parts belong to another API format.
+ return origin.format ? origin.format === FORMAT && (!model || origin.model === model) &&
+ (!origin.providerId || !providerId || origin.providerId === providerId) : !p.signature;
+ }).map(p => p.text).join('') : '';
+ const calls = parts.filter(p => p.type === 'tool-call' && validFunctionName(p.toolName)).map(p => ({
+ id: p.toolCallId, type: 'function', function: { name: p.toolName, arguments: textValue(p.args ?? {}) } }));
+ for (const part of parts) if (part.type === 'tool-call' && !validFunctionName(part.toolName) && part.toolCallId) skippedToolCalls.add(part.toolCallId);
+ output.push({ role: 'assistant', content: content || (calls.length ? null : ''),
+ ...(reasoning ? { reasoning_content: reasoning } : {}), ...(calls.length ? { tool_calls: calls } : {}) });
+ } else if (['user', 'system', 'developer'].includes(message.role)) {
+ const content = parts.map(part => contentPart(part, message.role));
+ output.push({ role: message.role, content: content.every(p => p.type === 'text') ? content.map(p => p.text).join('') : content });
+ } else {
+ throw new TypeError(`Unsupported message role: ${message.role}`);
+ }
+ }
+ flushToolImages();
+ return output;
+}
+
+export function convertChatTools(tools = []) {
+ return tools.map(tool => {
+ const { name, description, parameters } = toolSchema(tool);
+ return { type: 'function', function: { name, description, parameters } };
+ });
+}
+
+const OPTIONAL = ['stream_options', 'reasoning_effort', 'thinking', 'max_tokens', 'max_completion_tokens'];
+
+/** One streamed Chat Completions turn; yields Harness stream parts, returns the assembled message. */
+export async function* chatTurn(context) {
+ const { fetchImpl, endpoint, apiKey, headers, model, messages, tools, effort, maxTokens, requestOptions, signal, waitForIO, state, providerId,
+ notifyRequest, onModel, onId, onUsage } = context;
+ const functions = convertChatTools(tools);
+ const { http } = await postWithFallback({ fetchImpl, url: endpoint, apiKey, signal, waitForIO, state, optional: OPTIONAL,
+ fallbacks: [{ name: 'retry without replayed reasoning', applies: (error, body) => error.status === 400 &&
+ body.messages.some(message => message.reasoning_content) &&
+ (/(?:^|\.)reasoning_content$/.test(error.param ?? '') || rejectedOption(error, ['reasoning_content'])),
+ apply: () => { state.stripReasoning = true; } }],
+ headers: () => {
+ const value = new Headers(headers);
+ value.set('content-type', 'application/json');
+ value.set('accept', 'text/event-stream');
+ if (apiKey) value.set('authorization', `Bearer ${apiKey}`);
+ return value;
+ },
+ build: () => {
+ const limit = maxTokens === undefined ? undefined : maxTokensParameter(model, state.dropped);
+ return { ...requestOptions, ...chatReasoning(model, effort), model,
+ messages: convertChatMessages(messages, { model, providerId, replayReasoning: !state.stripReasoning }),
+ stream: true, stream_options: { ...requestOptions?.stream_options, include_usage: true },
+ ...(functions.length ? { tools: functions } : {}), ...(limit ? { [limit]: maxTokens } : {}) };
+ } });
+ notifyRequest(http.headers.get('x-request-id') ?? http.headers.get('request-id'));
+ let id, responseModel = model, text = '', reasoning = '', rawUsage = {}, finishReason, receivedChoice = false, receivedDone = false;
+ const toolCalls = new Map(), options = () => ({ providerOptions: reasoningProviderOptions({ format: FORMAT, model: responseModel, providerId }) });
+ for await (const data of readSse(http.body, { waitForIO })) {
+ signal.throwIfAborted();
+ if (data.trim() === '[DONE]') { receivedDone = true; break; }
+ const chunk = parseEvent(data);
+ if (chunk.error) throw providerError(chunk, undefined, http.headers, apiKey);
+ if (chunk.id) { id = chunk.id; onId(id); notifyRequest(id); }
+ if (chunk.model) { responseModel = chunk.model; onModel(responseModel); }
+ if (chunk.usage) { rawUsage = { ...rawUsage, ...chunk.usage }; onUsage(rawUsage); }
+ const choice = chunk.choices?.find(item => (item.index ?? 0) === 0);
+ if (!choice) continue;
+ receivedChoice = true;
+ if (choice.finish_reason) finishReason = choice.finish_reason;
+ const delta = choice.delta ?? {};
+ // DeepSeek and Qwen use reasoning_content; OpenRouter and vLLM use reasoning.
+ const thought = typeof delta.reasoning_content === 'string' ? delta.reasoning_content : typeof delta.reasoning === 'string' ? delta.reasoning : '';
+ if (thought) { reasoning += thought; yield { type: 'reasoning', textDelta: thought, ...options() }; }
+ for (const value of [delta.content, delta.refusal]) {
+ if (typeof value === 'string' && value) { text += value; yield { type: 'text-delta', textDelta: value }; }
+ }
+ for (const part of delta.tool_calls ?? []) {
+ const index = part.index ?? 0;
+ const call = toolCalls.get(index) ?? { id: '', name: '', arguments: '' };
+ if (part.id) call.id += part.id;
+ if (part.function?.name) call.name += part.function.name;
+ if (part.function?.arguments) call.arguments += part.function.arguments;
+ toolCalls.set(index, call);
+ }
+ }
+ signal.throwIfAborted();
+ if (finishReason === 'length' || finishReason === 'content_filter') {
+ throw new ModelRequestError(`Model response stopped with ${finishReason}`, { code: finishReason });
+ }
+ // Compatible endpoints differ: some omit [DONE], some omit finish_reason, and some report "stop"
+ // after tool calls. Either marker completes the stream; the tool calls received are used as sent.
+ if (!receivedChoice || (!receivedDone && !finishReason)) throw new ModelRequestError('Model SSE stream ended before a completion marker');
+ const content = [];
+ if (reasoning) content.push({ type: 'reasoning', text: reasoning, ...options() });
+ if (text) content.push({ type: 'text', text });
+ const calls = [...toolCalls.entries()].sort(([a], [b]) => a - b).map(([, call]) => {
+ if (!call.id || !validFunctionName(call.name)) throw new ModelRequestError('Model response included an invalid function name');
+ return { type: 'tool-call', toolCallId: call.id, toolName: call.name, args: parseToolArguments(call.name, call.arguments, tools) };
+ });
+ yield* streamToolCalls(calls, messages, signal);
+ content.push(...calls);
+ return { id, model: responseModel, content, toolCalls: calls.length, usage: rawUsage };
+}
diff --git a/host/runtime/openai-responses.mjs b/host/runtime/openai-responses.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..d0183fb81a678c3ccacbf6fd95104c8bdf8ca494
--- /dev/null
+++ b/host/runtime/openai-responses.mjs
@@ -0,0 +1,350 @@
+// OpenAI Responses format (POST /v1/responses), used statelessly: store=false, with
+// encrypted reasoning carried in the conversation instead of on the server.
+import { createHash } from 'node:crypto';
+import { explicitEffort, fileKind, fileText, mediaUrl, messageParts, ModelRequestError, parseEvent, parseToolArguments,
+ postWithFallback, providerError, readSse, reasoningOrigin, reasoningProviderOptions, replayRejected, streamToolCalls,
+ textValue, toolSchema, unsupportedFileNote } from './model-common.mjs';
+
+export const FORMAT = 'openai-responses';
+
+// Keep replay within the Responses provider's observed function-name limit.
+// Reject malformed model output before it reaches persisted conversation history.
+const validFunctionName = value => typeof value === 'string' && value.length > 0 && value.length <= 128;
+
+export function responsesEndpoint(baseUrl) {
+ const url = new URL(baseUrl);
+ if (!['http:', 'https:'].includes(url.protocol)) throw new TypeError('baseUrl must use HTTP or HTTPS');
+ url.pathname = url.pathname.replace(/\/+$/, '');
+ if (!url.pathname.endsWith('/responses')) url.pathname += '/responses';
+ return url.href;
+}
+
+/** A model whose catalog lists only 'none' does not reason; unknown models are assumed to. */
+export function reasons(efforts) {
+ return !(Array.isArray(efforts) && efforts.length > 0 && efforts.every(level => level === 'none'));
+}
+
+/** Request options: stateless storage, reasoning effort with summaries, encrypted reasoning. */
+export function responsesOptions(model, { effort, efforts, maxTokens } = {}) {
+ const level = explicitEffort(effort), thinking = reasons(efforts) && level !== 'none';
+ const reasoning = reasons(efforts) ? { ...(level ? { effort: level } : {}), ...(thinking ? { summary: 'auto' } : {}) } : null;
+ return { store: false, parallel_tool_calls: true,
+ ...(reasoning && Object.keys(reasoning).length ? { reasoning } : {}),
+ ...(thinking ? { include: ['reasoning.encrypted_content'] } : {}),
+ ...(Number.isSafeInteger(maxTokens) && maxTokens > 0 ? { max_output_tokens: maxTokens } : {}) };
+}
+
+function userContent(part) {
+ if (part.type === 'text') return part.text ? { type: 'input_text', text: part.text } : null;
+ if (part.type === 'image') return { type: 'input_image', image_url: mediaUrl(part), detail: 'auto' };
+ if (part.type === 'file') {
+ const kind = fileKind(part);
+ if (kind === 'image') return { type: 'input_image', image_url: mediaUrl(part, part.mimeType), detail: 'auto' };
+ if (kind === 'pdf') {
+ const url = mediaUrl(part, part.mimeType);
+ return /^https?:/i.test(url) ? { type: 'input_file', file_url: url } : { type: 'input_file', filename: part.filename ?? 'document.pdf', file_data: url };
+ }
+ if (kind === 'text') return { type: 'input_text', text: `${part.filename ? `${part.filename}:\n` : ''}${fileText(part)}` };
+ return { type: 'input_text', text: unsupportedFileNote(part) };
+ }
+ throw new TypeError(`Unsupported user content type: ${part.type}`);
+}
+
+/** Encrypted reasoning is readable only by the model that produced it. */
+function replayableReasoning(part, model, providerId) {
+ const origin = reasoningOrigin(part);
+ if (origin.model !== model) return null;
+ if (origin.providerId && providerId && origin.providerId !== providerId) return null;
+ if (part.type === 'reasoning') {
+ if (!part.signature || !(origin.format === FORMAT || (!origin.format && origin.summarized))) return null;
+ return { type: 'reasoning', ...(origin.itemId ? { id: origin.itemId } : {}),
+ summary: part.text ? [{ type: 'summary_text', text: part.text }] : [], encrypted_content: part.signature };
+ }
+ if (part.type === 'redacted-reasoning') {
+ // The original Harness turns summarized reasoning into redacted parts when it rebuilds a turn.
+ if (!part.data || (origin.format && origin.format !== FORMAT)) return null;
+ return { type: 'reasoning', ...(origin.itemId ? { id: origin.itemId } : {}), summary: [], encrypted_content: part.data };
+ }
+ return null;
+}
+
+/** CoreMessages to Responses input items and instructions. */
+export function convertResponsesInput(messages, { model, providerId, replayReasoning = true, inlineToolImages = true } = {}) {
+ const instructions = [], input = [];
+ let leading = true, pendingImages = [];
+ const skippedToolCalls = new Set();
+ const flushImages = () => {
+ if (!pendingImages.length) return;
+ input.push({ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Screenshots from the preceding tool results:' }, ...pendingImages] });
+ pendingImages = [];
+ };
+ let replayed = 0;
+ for (const message of messages) {
+ const parts = messageParts(message);
+ if (message.role !== 'tool') flushImages();
+ if (message.role === 'system' || message.role === 'developer') {
+ const text = parts.filter(part => part.type === 'text').map(part => part.text).join('');
+ if (!text) continue;
+ if (leading) instructions.push(text);
+ else input.push({ type: 'message', role: 'developer', content: [{ type: 'input_text', text }] });
+ continue;
+ }
+ leading = false;
+ if (message.role === 'user') {
+ const content = parts.map(userContent).filter(Boolean);
+ if (content.length) input.push({ type: 'message', role: 'user', content });
+ } else if (message.role === 'assistant') {
+ const items = [];
+ for (const part of parts) {
+ if (part.type === 'reasoning' || part.type === 'redacted-reasoning') {
+ const item = replayReasoning ? replayableReasoning(part, model, providerId) : null;
+ if (item) { items.push(item); replayed++; }
+ } else if (part.type === 'text') {
+ if (!part.text) continue;
+ const phase = reasoningOrigin(part).phase;
+ const previous = items.at(-1);
+ if (previous?.type === 'message' && previous.phase === phase) previous.content += part.text;
+ else items.push({ type: 'message', role: 'assistant', content: part.text, ...(phase ? { phase } : {}) });
+ } else if (part.type === 'tool-call') {
+ // Older Host versions could persist a malformed upstream function name.
+ // Omit it and its result instead of replaying an API-invalid call forever.
+ if (!validFunctionName(part.toolName)) {
+ if (typeof part.toolCallId === 'string') skippedToolCalls.add(part.toolCallId);
+ continue;
+ }
+ items.push({ type: 'function_call', call_id: part.toolCallId, name: part.toolName, arguments: textValue(part.args ?? {}) });
+ }
+ }
+ // A reasoning item must be followed by the output it led to.
+ while (items.at(-1)?.type === 'reasoning') { items.pop(); replayed--; }
+ input.push(...items);
+ } else if (message.role === 'tool') {
+ for (const part of parts) {
+ if (part.type !== 'tool-result' || !part.toolCallId) throw new TypeError('Tool messages require tool-result parts and toolCallId');
+ if (skippedToolCalls.has(part.toolCallId)) continue;
+ const extra = part.experimental_content ?? [];
+ const text = part.result === undefined ? extra.filter(item => item.type === 'text').map(item => item.text).join('\n') : textValue(part.result);
+ const images = extra.filter(item => item.type === 'image').map(item => ({ type: 'input_image', image_url: mediaUrl(item), detail: 'auto' }));
+ if (images.length && inlineToolImages) {
+ input.push({ type: 'function_call_output', call_id: part.toolCallId, output: [...(text ? [{ type: 'input_text', text }] : []), ...images] });
+ } else {
+ input.push({ type: 'function_call_output', call_id: part.toolCallId, output: text || '(empty)' });
+ pendingImages.push(...images);
+ }
+ }
+ } else {
+ throw new TypeError(`Unsupported message role: ${message.role}`);
+ }
+ }
+ flushImages();
+ return { instructions: instructions.join('\n\n'), input, replayed };
+}
+
+export function convertResponsesTools(tools = []) {
+ return tools.map(tool => ({ type: 'function', ...toolSchema(tool), strict: false }));
+}
+
+/** Normalize Responses usage to the OpenAI Chat fields recorded by the usage ledger. */
+export function responsesUsage(raw = {}) {
+ const count = value => Number.isFinite(value) && value >= 0 ? value : 0;
+ const input = count(raw.input_tokens), output = count(raw.output_tokens);
+ return { prompt_tokens: input, completion_tokens: output, total_tokens: count(raw.total_tokens ?? input + output),
+ prompt_tokens_details: { cached_tokens: count(raw.input_tokens_details?.cached_tokens) },
+ cache_creation_input_tokens: count(raw.input_tokens_details?.cache_write_tokens),
+ completion_tokens_details: { reasoning_tokens: count(raw.output_tokens_details?.reasoning_tokens) } };
+}
+
+// Routes the same conversation to the same cache shard: model, instructions and the opening request.
+function promptCacheKey(model, instructions, input) {
+ const first = input.find(item => item.type === 'message' && item.role === 'user');
+ return createHash('sha256').update(JSON.stringify([model, instructions, first?.content ?? null])).digest('hex').slice(0, 48);
+}
+
+const OPTIONAL = ['reasoning.summary', 'include', 'prompt_cache_key', 'parallel_tool_calls', 'store', 'reasoning.effort', 'max_output_tokens'];
+
+function incomplete(reason) {
+ if (reason === 'max_output_tokens') return new ModelRequestError('Model response stopped with max_output_tokens', { code: 'length' });
+ if (reason === 'content_filter') return new ModelRequestError('Model response stopped with content_filter', { code: 'content_filter' });
+ return new ModelRequestError(`Model response is incomplete${reason ? ` (${reason})` : ''}`, { code: reason });
+}
+
+/** One streamed Responses turn; yields Harness stream parts, returns the assembled message. */
+export async function* responsesTurn(context) {
+ const { fetchImpl, endpoint, apiKey, headers, model, messages, tools, effort, efforts, maxTokens, signal, waitForIO, state,
+ providerId, notifyRequest, onModel, onId, onUsage } = context;
+ const functions = convertResponsesTools(tools);
+ let replayed = 0, inlineImages = false;
+ const { http } = await postWithFallback({ fetchImpl, url: endpoint, apiKey, signal, waitForIO, state, optional: OPTIONAL,
+ headers: () => {
+ const value = new Headers(headers);
+ value.set('content-type', 'application/json');
+ value.set('accept', 'text/event-stream');
+ if (apiKey) value.set('authorization', `Bearer ${apiKey}`);
+ return value;
+ },
+ fallbacks: [
+ { name: 'retry without replayed reasoning', applies: error => replayed > 0 && replayRejected(error), apply: () => { state.stripReasoning = true; } },
+ { name: 'tool screenshots as a message', applies: error => inlineImages && error.status === 400 && /function_call_output|input_image|output/i.test(error.message),
+ apply: () => { state.toolImagesAsMessage = true; } },
+ ],
+ build: () => {
+ const converted = convertResponsesInput(messages, { model, providerId, replayReasoning: !state.stripReasoning,
+ inlineToolImages: !state.toolImagesAsMessage });
+ replayed = converted.replayed;
+ inlineImages = converted.input.some(item => item.type === 'function_call_output' && Array.isArray(item.output));
+ return { model, ...(converted.instructions ? { instructions: converted.instructions } : {}), input: converted.input,
+ ...(functions.length ? { tools: functions } : {}), stream: true,
+ ...responsesOptions(model, { effort, efforts, maxTokens }),
+ prompt_cache_key: promptCacheKey(model, converted.instructions, converted.input) };
+ } });
+ notifyRequest(http.headers.get('x-request-id') ?? http.headers.get('request-id'));
+ let id, responseModel = model, rawUsage = {}, finished = false;
+ const items = new Map();
+ const item = (index, type, id) => {
+ if (!Number.isSafeInteger(index) || index < 0) throw new ModelRequestError('Invalid model output item index');
+ if (!items.has(index)) items.set(index, { summary: [], reasoning: '', text: '', arguments: '', emitted: false });
+ const entry = items.get(index);
+ if ((type && entry.type && type !== entry.type) || (id && entry.id && id !== entry.id)) {
+ throw new ModelRequestError('Conflicting model output item identity');
+ }
+ entry.type ??= type; entry.id ??= id;
+ return entry;
+ };
+ const reasoningOptions = (entry, summarized) => ({
+ providerOptions: reasoningProviderOptions({ format: FORMAT, model: responseModel, providerId, summarized, itemId: entry.id }) });
+ const start = response => {
+ if (id && response?.id && response.id !== id) throw new ModelRequestError('Conflicting model response ID');
+ if (response?.id && response.id !== id) { id = response.id; onId(id); notifyRequest(id); }
+ if (response?.model) { responseModel = response.model; onModel(responseModel); }
+ };
+ // Both output_item.done and response.completed.output can carry the same full item.
+ // Append only previously unseen text; never replace a streamed identity or replay a signature.
+ function* finishItem(index, snapshot) {
+ if (!snapshot?.type) throw new ModelRequestError('Missing model output item');
+ const entry = item(index, snapshot.type, snapshot.id);
+ if (snapshot.status && snapshot.status !== 'completed') throw new ModelRequestError(`Model output item is ${snapshot.status}`);
+ if (entry.type === 'message') {
+ entry.phase = snapshot.phase ?? entry.phase;
+ if (!Array.isArray(snapshot.content)) return;
+ const text = snapshot.content.map(part => part.text ?? part.refusal ?? '').join('');
+ if (!text.startsWith(entry.text)) throw new ModelRequestError('Conflicting model output text');
+ const suffix = text.slice(entry.text.length);
+ entry.text = text;
+ if (suffix) yield { type: 'text-delta', textDelta: suffix };
+ } else if (entry.type === 'function_call') {
+ if ((entry.name && snapshot.name && entry.name !== snapshot.name) ||
+ (entry.callId && snapshot.call_id && entry.callId !== snapshot.call_id)) throw new ModelRequestError('Conflicting model tool call identity');
+ entry.name ??= snapshot.name; entry.callId ??= snapshot.call_id;
+ if (typeof snapshot.arguments === 'string') {
+ if (!snapshot.arguments.startsWith(entry.arguments)) throw new ModelRequestError('Conflicting model tool arguments');
+ entry.arguments = snapshot.arguments;
+ }
+ } else if (entry.type === 'reasoning') {
+ const priorSummary = entry.summary.filter(Boolean).join('\n\n'), prior = priorSummary || entry.reasoning;
+ if (snapshot.summary?.length) entry.summary = snapshot.summary.map(part => part.text ?? '');
+ if (snapshot.content?.length) entry.reasoning = snapshot.content.map(part => part.text ?? '').join('');
+ const summary = entry.summary.filter(Boolean).join('\n\n'), text = summary || entry.reasoning;
+ if (!text.startsWith(prior)) throw new ModelRequestError('Conflicting model reasoning text');
+ if (text.length > prior.length) {
+ entry.emitted = true;
+ yield { type: 'reasoning', textDelta: text.slice(prior.length), ...reasoningOptions(entry, Boolean(summary)) };
+ }
+ if (snapshot.encrypted_content && snapshot.encrypted_content !== entry.encrypted) {
+ if (entry.encrypted) throw new ModelRequestError('Conflicting model reasoning signature');
+ entry.encrypted = snapshot.encrypted_content;
+ if (entry.emitted) yield { type: 'reasoning-signature', signature: entry.encrypted };
+ else yield { type: 'redacted-reasoning', data: entry.encrypted, ...reasoningOptions(entry, true) };
+ }
+ }
+ }
+ for await (const data of readSse(http.body, { waitForIO })) {
+ signal.throwIfAborted();
+ if (data.trim() === '[DONE]') break;
+ const event = parseEvent(data);
+ switch (event.type) {
+ case 'response.created': case 'response.in_progress': case 'response.queued':
+ start(event.response); break;
+ case 'response.output_item.added': {
+ const entry = item(event.output_index, event.item?.type, event.item?.id);
+ if (entry.added) throw new ModelRequestError('Duplicate model output item');
+ Object.assign(entry, { added: true, name: event.item?.name, callId: event.item?.call_id, phase: event.item?.phase });
+ if (event.item?.arguments) entry.arguments = event.item.arguments;
+ break;
+ }
+ case 'response.reasoning_summary_text.delta': case 'response.reasoning_text.delta': {
+ if (!event.delta) break;
+ const entry = item(event.output_index, 'reasoning', event.item_id), summarized = event.type === 'response.reasoning_summary_text.delta';
+ let delta = event.delta;
+ if (summarized) {
+ const index = event.summary_index ?? 0;
+ if (entry.summary[index] === undefined && entry.summary.length) delta = `\n\n${delta}`;
+ entry.summary[index] = (entry.summary[index] ?? '') + event.delta;
+ } else entry.reasoning += event.delta;
+ entry.emitted = true;
+ yield { type: 'reasoning', textDelta: delta, ...reasoningOptions(entry, summarized) };
+ break;
+ }
+ case 'response.output_text.delta': case 'response.refusal.delta': {
+ if (!event.delta) break;
+ const entry = item(event.output_index, 'message', event.item_id);
+ entry.text += event.delta;
+ yield { type: 'text-delta', textDelta: event.delta };
+ break;
+ }
+ case 'response.function_call_arguments.delta':
+ item(event.output_index, 'function_call', event.item_id).arguments += event.delta ?? '';
+ break;
+ case 'response.function_call_arguments.done':
+ yield* finishItem(event.output_index, { type: 'function_call', id: event.item_id, name: event.name, arguments: event.arguments });
+ break;
+ case 'response.output_item.done':
+ yield* finishItem(event.output_index, event.item);
+ break;
+ case 'response.completed': case 'response.incomplete': case 'response.failed': case 'response.cancelled': {
+ const response = event.response;
+ if (!response) throw new ModelRequestError('Missing terminal model response');
+ start(response);
+ if (response.usage) { rawUsage = response.usage; onUsage(responsesUsage(rawUsage)); }
+ if (event.type === 'response.failed' || response.error || response.status === 'failed') {
+ throw providerError({ error: response.error ?? { message: 'Model response failed' } }, undefined, http.headers, apiKey);
+ }
+ if (event.type === 'response.incomplete' || response.status === 'incomplete' || response.incomplete_details) throw incomplete(response.incomplete_details?.reason);
+ if (event.type !== 'response.completed' || (response.status && response.status !== 'completed')) throw incomplete(response.status ?? event.type);
+ if (response.output !== undefined) {
+ if (!Array.isArray(response.output) || [...items.keys()].some(index => index >= response.output.length)) {
+ throw new ModelRequestError('Model output snapshot is missing a streamed item');
+ }
+ for (const [index, output] of response.output.entries()) yield* finishItem(index, output);
+ }
+ finished = true;
+ break;
+ }
+ case 'error':
+ throw providerError(event.error ? event : { error: event }, undefined, http.headers, apiKey);
+ default:
+ break;
+ }
+ if (finished) break;
+ }
+ signal.throwIfAborted();
+ if (!finished) throw new ModelRequestError('Model SSE stream ended before a completion marker');
+ const content = [], calls = [];
+ for (const [, entry] of [...items.entries()].sort(([a], [b]) => a - b)) {
+ if (entry.type === 'reasoning') {
+ const summary = entry.summary.filter(Boolean).join('\n\n'), text = summary || entry.reasoning;
+ if (!text && !entry.encrypted) continue;
+ if (!text) { content.push({ type: 'redacted-reasoning', data: entry.encrypted, ...reasoningOptions(entry, true) }); continue; }
+ content.push({ type: 'reasoning', text, ...(entry.encrypted ? { signature: entry.encrypted } : {}),
+ ...reasoningOptions(entry, Boolean(summary) || !entry.reasoning) });
+ } else if (entry.type === 'message') {
+ if (entry.text) content.push({ type: 'text', text: entry.text, ...(entry.phase ? { providerOptions: { grokbot: { phase: entry.phase } } } : {}) });
+ } else if (entry.type === 'function_call') {
+ if (!entry.callId || !validFunctionName(entry.name)) throw new ModelRequestError('Model response included an invalid function name');
+ const call = { type: 'tool-call', toolCallId: entry.callId, toolName: entry.name, args: parseToolArguments(entry.name, entry.arguments, tools) };
+ // Output order is kept: each reasoning item must precede the output it led to on replay.
+ calls.push(call); content.push(call);
+ }
+ }
+ yield* streamToolCalls(calls, messages, signal);
+ return { id, model: responseModel, content, toolCalls: calls.length, usage: responsesUsage(rawUsage) };
+}
diff --git a/host/runtime/prompt-runtime.mjs b/host/runtime/prompt-runtime.mjs
index 41bc89df045b79cdea0c434dbed4d53b26302428..a42719e539c4848a6444e38dd9d8337f17566b99 100644
--- a/host/runtime/prompt-runtime.mjs
+++ b/host/runtime/prompt-runtime.mjs
@@ -2,8 +2,21 @@ import { join } from 'node:path';
import { readJson, writePrivate } from '../server/storage.mjs';
import { promptDigest, promptId, promptRoles, validatePrompt } from '../server/prompt-settings.mjs';
+function memoryAccessDirective(memoryRoot) {
+ const root = memoryRoot.replace(/\/+$/, '') || '/';
+ return [
+ `Memory access is configured for this turn: agent memory is mounted at ${root}/agents and shared user memory at ${root}/user-memory.`,
+ 'Use memory proactively whenever it can affect the answer, without waiting for the user to ask. The normal Memory sections may already include profile and recent facts; when you need older or omitted facts, inspect the corresponding files with Read or Shell on your own computer.',
+ 'Do not repeat an earlier turn\'s "not mounted" or "not readable" result without rechecking in the current turn.',
+ 'A missing monthly log means that no file has been recorded for that month yet, not that the entire memory volume is unavailable.',
+ ].join(' ');
+}
+
/** Only base instructions are catalogued. Profile, memory, skills and user content stay in the original assembler. */
-export async function installLocalPromptPolicy(directory, library, { pollMs = 1000 } = {}) {
+export async function installLocalPromptPolicy(directory, library, {
+ pollMs = 1000, revision = 'local', memoryRoot = process.env.SAND_DATA_ROOT ?? '/data/runtime/host-data',
+ memoryMounts = process.env.GROKBOT_HOST_MEMORY_MOUNTS === '1',
+} = {}) {
const settingsPath = join(directory, 'prompt-settings.json'), catalogPath = join(directory, 'prompt-catalog.json');
let settings = { version: 1, entries: {} }, catalog = await readJson(catalogPath, { version: 1, entries: [] }), tail = Promise.resolve(), reading = false;
let stopped = false;
@@ -21,7 +34,7 @@ export async function installLocalPromptPolicy(directory, library, { pollMs = 10
return id;
}
catalog.entries.push({ id, role, original, digest: promptDigest(original), observedAt: Date.now(), observed,
- source: 'd0a4baa · system-prompt-assembly' });
+ source: `${revision} · system-prompt-assembly` });
catalog.entries = catalog.entries.slice(-100); void flush(); return id;
}
async function refresh() {
@@ -54,8 +67,16 @@ export async function installLocalPromptPolicy(directory, library, { pollMs = 10
const render = (role, original) => {
id = observe(role, original); if (!id) return original;
const selected = frozen[id]?.revisions?.at(-1)?.content;
- if (selected === undefined) return original;
- try { return validatePrompt(selected); } catch { return original; }
+ let rendered = original;
+ if (selected !== undefined) {
+ try { rendered = validatePrompt(selected); } catch { rendered = original; }
+ }
+ if (role !== 'parent' || !memoryMounts) return rendered;
+ try {
+ return validatePrompt(`${rendered.trimEnd()}\n\n${memoryAccessDirective(memoryRoot)}`);
+ } catch {
+ return rendered;
+ }
};
render.recordAssembly = value => { assembly = value; publish(); };
render.recordTools = values => {
diff --git a/host/runtime/recovered-blob-worker.mjs b/host/runtime/recovered-blob-worker.mjs
index 0c682b9edd2f4adcc4f66beb2cb071a6deba22ee..1b47671a61c39de0049e3dc58a6a23b78ce40cec 100644
--- a/host/runtime/recovered-blob-worker.mjs
+++ b/host/runtime/recovered-blob-worker.mjs
@@ -4,8 +4,9 @@ import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { isMainThread, threadId } from 'node:worker_threads';
import { constructRecoveredModules } from './recovered-modules.mjs';
+import inputs from '../recipes/host/manifest.json' with { type: 'json' };
-const sourceSha256 = '868572888c71b317c7878b5efc81b029aa99192e3bef7402591759388a6bcf3c';
+const sourceSha256 = inputs.sourceSha256['agent-isolation/agent-store-worker.cjs'];
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
export async function describeRecoveredBlobWorker(state) {
diff --git a/host/runtime/recovered-host-core.mjs b/host/runtime/recovered-host-core.mjs
index a29801c9bd76fabbac2ed35a69862e57f650ccf0..a3e94fd5ae93c91e5dd277db07fba615c2006707 100644
--- a/host/runtime/recovered-host-core.mjs
+++ b/host/runtime/recovered-host-core.mjs
@@ -12,13 +12,14 @@ import { installRecoveredStorage } from './recovered-storage.mjs';
import { installRecoveredPromptTools } from './recovered-prompt-tools.mjs';
import { installRecoveredHostKernel } from './recovered-host-kernel.mjs';
import { installRecoveredToolFramework } from './recovered-tool-framework.mjs';
+import inputs from '../recipes/host/manifest.json' with { type: 'json' };
/** Install editable recovery modules before any Host service is constructed. */
export async function loadRecoveredHostCore(library, directory) {
const modules = [];
for (const filename of ['provenance.json', 'acceptance-provenance.json', 'handoff-provenance.json', 'host-flow-provenance.json', 'storage-provenance.json', 'worker-pool-provenance.json', 'tool-framework-provenance.json', 'engine-provenance.json', 'computer-provenance.json', 'prompt-tools-provenance.json', 'harness-provenance.json', 'host-execution-provenance.json', 'host-session-provenance.json', 'host-kernel-provenance.json']) {
const manifest = JSON.parse(await readFile(join(directory, filename), 'utf8'));
- if (manifest.sourceSha256 !== 'd7ffb02b831337f6e4618a2604fb6ecd00a7f75f4c4bf96f5075f54d473b7f67') {
+ if (manifest.sourceSha256 !== inputs.sourceSha256['host-main.cjs']) {
throw new Error(`Unexpected recovered source: ${filename}`);
}
for (const entry of manifest.modules) {
diff --git a/host/runtime/recovered-host-flow.mjs b/host/runtime/recovered-host-flow.mjs
index 7ccaeec840e772d5550f923d7c29ce8a925fb786..0a676948b6637a6ed2161279ef9ea1da4c0a72e3 100644
--- a/host/runtime/recovered-host-flow.mjs
+++ b/host/runtime/recovered-host-flow.mjs
@@ -1,7 +1,35 @@
import { constructRecoveredModules } from './recovered-modules.mjs';
+const memoryFailureTags = new Set(['ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'ETIMEDOUT',
+ 'UND_ERR_SOCKET', 'UND_ERR_CONNECT_TIMEOUT', 'AbortError', 'TimeoutError']);
+
+function reportMemoryFailure(error) {
+ const tag = [error?.code, error?.cause?.code, error?.name].find(value => memoryFailureTags.has(value));
+ console.warn(`[memory] Post-turn memory model request failed (${tag ?? 'model error'})`);
+}
+
+function memoryExecutor(executor) {
+ return {
+ appendMessages(messages) { executor.appendMessages(messages); return this; },
+ stream(...args) {
+ const result = executor.stream(...args);
+ // The memory collector catches fullStream failures but never reads the new
+ // completion promises created by the Host's usage middleware above the adapter.
+ void Promise.all([result.response, result.usage, result.extendedUsage]).catch(reportMemoryFailure);
+ return result;
+ },
+ };
+}
+
export function constructRecoveredHostFlow(library, directory) {
- return constructRecoveredModules(library.hostFlowRecoveryPlan, library.getHostFlowRecoveryBindings(), directory, 'Host flow');
+ const original = library.getHostFlowRecoveryBindings();
+ if (typeof original.runTurnMemory !== 'function') throw new TypeError('Missing Host flow dependency: runTurnMemory');
+ return constructRecoveredModules(library.hostFlowRecoveryPlan, { ...original,
+ runTurnMemory(store, progress, session, ...turnArgs) {
+ const memorySession = { getExecutor: (...args) => memoryExecutor(session.getExecutor(...args)) };
+ return original.runTurnMemory(store, progress, memorySession, ...turnArgs);
+ },
+ }, directory, 'Host flow');
}
export async function installRecoveredHostFlow(library, directory) {
diff --git a/host/runtime/reliability/tool-journal.mjs b/host/runtime/reliability/tool-journal.mjs
index ade992ed750d0bba41a300edda6a0d2786611eba..11a0d1aaa621f09f7026ed9154b9e401b2bf0602 100644
--- a/host/runtime/reliability/tool-journal.mjs
+++ b/host/runtime/reliability/tool-journal.mjs
@@ -3,6 +3,7 @@ import { createHash, randomUUID } from 'node:crypto';
import { mkdir, open, readFile, readdir, rename, rm, unlink } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { deserialize, serialize } from 'node:v8';
+import { awaitToolCallTurn } from './tool-order.mjs';
const scopes = new AsyncLocalStorage();
const executions = new AsyncLocalStorage();
@@ -90,6 +91,16 @@ export async function runJournaledTool({ descriptor, argumentsText, turnId = 'un
const root = process.env.SAND_DATA_ROOT;
if (!root) throw new Error('Tool execution requires SAND_DATA_ROOT for its durable journal');
if (typeof descriptor.toolCallId !== 'string' || !descriptor.toolCallId) throw new Error('Tool call ID is required');
+ // Messages of one response run one after another in written order; other tools are not delayed.
+ const release = await awaitToolCallTurn(descriptor.toolCallId, signal);
+ try { return await runAdmitted({ descriptor, argumentsText, turnId, signal, isDeferred, execute, captureDelivery, onReplay, root }); }
+ finally { release(); }
+}
+
+async function runAdmitted({ descriptor, argumentsText, turnId, signal, isDeferred, execute, captureDelivery, onReplay, root }) {
+ const scope = scopes.getStore();
+ // The turn may have been cancelled while this message waited for an earlier one.
+ if (signal?.aborted) throw Object.assign(new Error('Tool execution aborted before admission'), { name: 'AbortError' });
let argumentsValue;
try { argumentsValue = canonical(JSON.parse(argumentsText)); } catch { argumentsValue = argumentsText; }
const fingerprint = digest(JSON.stringify({ name: descriptor.effectiveNativeToolCall?.toolName ?? descriptor.toolName,
diff --git a/host/runtime/reliability/tool-order.mjs b/host/runtime/reliability/tool-order.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..aaa1d13aabd79aec61140879b5c26fa132e4a4cd
--- /dev/null
+++ b/host/runtime/reliability/tool-order.mjs
@@ -0,0 +1,87 @@
+// Messages from one model response must reach the user in the order the model wrote them.
+// The model layer hands the Harness a response's tool calls together, and the Harness then
+// runs them concurrently (each first awaits its own durable journal admission), so without
+// this the shortest message tends to arrive first. Other tools keep running in parallel.
+
+const ORDERED_TOOLS = new Set(['SendToUser', 'SendToAgent']);
+// A predecessor that never executes (for example, rejected arguments) must not block forever.
+const MAX_WAIT_MS = 15_000;
+const STALE_MS = 10 * 60_000;
+const calls = new Map();
+// Some providers number call IDs per response, so concurrent conversations can reuse an ID. Such
+// calls run unordered (as without this module) instead of failing the turn or waiting on each other.
+// The colliding calls finish well within a minute; after that the ID is ordered normally again.
+const SHARED_MS = 60_000;
+const shared = new Map();
+let sweepTimer;
+
+function release(id, entry) {
+ entry.resolve();
+ if (calls.get(id) === entry) calls.delete(id);
+ if (!calls.size) { clearTimeout(sweepTimer); sweepTimer = undefined; }
+}
+
+// One unreferenced timer for the whole map, including when the last turn is abandoned.
+function scheduleSweep() {
+ if (sweepTimer || !calls.size) return;
+ const first = calls.values().next().value;
+ sweepTimer = setTimeout(() => {
+ sweepTimer = undefined;
+ const now = Date.now();
+ for (const [id, entry] of calls) {
+ if (entry.createdAt + STALE_MS > now) break;
+ release(id, entry);
+ }
+ scheduleSweep();
+ }, Math.max(1, first.createdAt + STALE_MS - Date.now()));
+ sweepTimer.unref?.();
+}
+
+/** Called by the model layer with one response's tool calls in written order. */
+export function recordToolCallOrder(list) {
+ const now = Date.now();
+ for (const [id, until] of shared) if (until <= now) shared.delete(id);
+ const registered = new Map();
+ const ordered = list.filter(({ toolCallId, toolName }) => ORDERED_TOOLS.has(toolName) && typeof toolCallId === 'string' && toolCallId);
+ const ids = new Set();
+ for (const { toolCallId } of ordered) {
+ if (ids.has(toolCallId)) throw new Error('Ordered tool call ID is repeated in one response');
+ ids.add(toolCallId);
+ }
+ let previous;
+ for (const { toolCallId } of ordered) {
+ const existing = calls.get(toolCallId);
+ if (existing || shared.has(toolCallId)) {
+ // Neither response may take over or wait on the other's entry for an ambiguous ID.
+ if (existing) release(toolCallId, existing);
+ shared.set(toolCallId, now + SHARED_MS);
+ continue;
+ }
+ let resolve;
+ const done = new Promise(settle => { resolve = settle; });
+ const entry = { previous, done, resolve, createdAt: now };
+ calls.set(toolCallId, entry);
+ registered.set(toolCallId, entry);
+ previous = done;
+ }
+ scheduleSweep();
+ return id => { const entry = registered.get(id); if (entry) release(id, entry); };
+}
+
+/** Wait for the previous ordered call of the same response; the returned function marks this call finished. */
+export function awaitToolCallTurn(toolCallId, signal, { maxWaitMs = MAX_WAIT_MS } = {}) {
+ const entry = calls.get(toolCallId);
+ if (!entry) return Promise.resolve(() => {});
+ return (async () => {
+ const previous = entry.previous;
+ if (previous && !signal?.aborted) {
+ let timer, onAbort;
+ await Promise.race([previous,
+ new Promise(settle => { timer = setTimeout(settle, maxWaitMs); }),
+ new Promise(settle => { onAbort = settle; signal?.addEventListener('abort', settle, { once: true }); })]);
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', onAbort);
+ }
+ return () => release(toolCallId, entry);
+ })();
+}
diff --git a/host/runtime/routing-log.mjs b/host/runtime/routing-log.mjs
index ca66241f8e39ffe6e85d1a3fb57ab45b22b02582..c05d7e0c5b959fff305d75ee65a4ef5141b1d1c1 100644
--- a/host/runtime/routing-log.mjs
+++ b/host/runtime/routing-log.mjs
@@ -5,11 +5,30 @@ export function taskPreview(state) {
return String(state.at(-1)?.text ?? '').replace(/(?:apikey_|sk-)[A-Za-z0-9_-]{16,}/g, '[redacted]')
.replace(/Bearer\s+[A-Za-z0-9._-]+/gi, 'Bearer [redacted]').replace(/\s+/g, ' ').trim().slice(0, 240);
}
+function routingTarget(value) {
+ if (!value) return undefined;
+ return {
+ profileId: value.profileId,
+ profileName: value.profileName,
+ providerId: value.providerId,
+ providerName: value.providerName,
+ apiFormat: value.apiFormat,
+ model: value.model,
+ };
+}
+function routingRecord(entry) {
+ const clean = { ...entry };
+ if (clean.from) clean.from = routingTarget(clean.from);
+ if (clean.to) clean.to = routingTarget(clean.to);
+ if (Array.isArray(clean.skipped)) clean.skipped = clean.skipped.map(routingTarget).filter(Boolean);
+ return clean;
+}
export async function recordRouting(directory, entry) {
if (!directory) return;
const at = new Date().toISOString();
await mkdir(directory, { recursive: true, mode: 0o700 });
- await appendFile(join(directory, `${at.slice(0, 10)}.jsonl`), JSON.stringify({ id: randomUUID(), at, ...entry }) + '\n', { mode: 0o600 });
+ await appendFile(join(directory, `${at.slice(0, 10)}.jsonl`), JSON.stringify({ id: randomUUID(), at,
+ ...routingRecord(entry) }) + '\n', { mode: 0o600 });
const files = (await readdir(directory)).filter(name => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(name)).sort();
for (const name of files.slice(0, -30)) await unlink(join(directory, name)).catch(() => {});
}
diff --git a/host/runtime/usage-ledger.mjs b/host/runtime/usage-ledger.mjs
index 7878df595a48c915b6677ffad0fad0eaaf10d80f..325475dae685b459ac322f65f6d48182e463e3d4 100644
--- a/host/runtime/usage-ledger.mjs
+++ b/host/runtime/usage-ledger.mjs
@@ -10,10 +10,11 @@ export function usageCounts(raw = {}) {
cached: count(raw.prompt_cache_hit_tokens ?? raw.prompt_tokens_details?.cached_tokens),
reasoning: count(raw.completion_tokens_details?.reasoning_tokens) };
}
-export async function recordUsage(directory, { raw, model, kind = 'chat', effort, requestId, at = new Date() }) {
+export async function recordUsage(directory, { raw, model, kind = 'chat', effort, requestId, profileId, providerId, at = new Date() }) {
if (!directory || !raw || !Object.keys(raw).length) return;
const timestamp = at.toISOString();
- const entry = { id: randomUUID(), at: timestamp, model, kind, effort, requestId, ...usageCounts(raw) };
+ const entry = { id: randomUUID(), at: timestamp, model, kind, effort, requestId,
+ ...(profileId ? { profileId } : {}), ...(providerId ? { providerId } : {}), ...usageCounts(raw) };
await mkdir(directory, { recursive: true, mode: 0o700 });
// Each process appends one short JSON line; no read/modify/write race with the admin server.
await appendFile(join(directory, timestamp.slice(0, 10) + '.jsonl'), JSON.stringify(entry) + '\n', { mode: 0o600 });
diff --git a/host/runtime/web-services.mjs b/host/runtime/web-services.mjs
index f1e87c789907586804aae76a78311d0fc790a91d..b8909fe31d2c3e6f2ef4f3ead9cc6e87a7364d17 100644
--- a/host/runtime/web-services.mjs
+++ b/host/runtime/web-services.mjs
@@ -28,17 +28,33 @@ async function nativeResponse(provider, query, signal) {
const citations = content.flatMap(item => item.annotations || []).filter(item => item.type === 'url_citation');
return { answer, documents: documents(citations.map(item => ({ title: item.title || item.url, url: item.url, text: '' }))) };
}
+// Models with thinking always on reject a forced tool choice; they still call the tool when the prompt names it.
+const automaticToolChoice = new Set();
async function nativeAnthropic(provider, kind, value, signal) {
const type = kind === 'search' ? 'web_search_20250305' : 'web_fetch_20250910', name = kind === 'search' ? 'web_search' : 'web_fetch';
- const response = await fetch(`${provider.baseUrl}/messages`, { method: 'POST', redirect: 'error', signal,
+ const key = `${provider.baseUrl}\n${provider.model}`;
+ const send = toolChoice => fetch(`${provider.baseUrl}/messages`, { method: 'POST', redirect: 'error', signal,
headers: { 'content-type': 'application/json', 'x-api-key': provider.apiKey, 'anthropic-version': '2023-06-01' },
body: JSON.stringify({ model: provider.model, max_tokens: 8000, tools: [{ type, name, max_uses: 1 }],
- tool_choice: { type: 'tool', name }, messages: [{ role: 'user', content: kind === 'search'
- ? `Search this query and return source-grounded findings: ${value}` : `Fetch this page and return its content: ${value}` }] }) });
+ tool_choice: toolChoice, messages: [{ role: 'user', content: kind === 'search'
+ ? `Use the ${name} tool to search this query and return source-grounded findings: ${value}`
+ : `Use the ${name} tool to fetch this page and return its content: ${value}` }] }) });
+ // Decide on what this request sent: a concurrent call may record the fallback while this one is in flight.
+ const forced = !automaticToolChoice.has(key);
+ let response = await send(forced ? { type: 'tool', name } : { type: 'auto' });
+ if (response.status === 400 && forced) {
+ const detail = (await boundedBody(response, 64 * 1024).catch(() => Buffer.alloc(0))).toString('utf8');
+ check(/tool[_ ]choice|forced tool/i.test(detail), 502, 'Service returned HTTP 400');
+ automaticToolChoice.add(key);
+ console.warn(`[web] ${provider.model} rejects a forced tool choice; using automatic tool choice`);
+ response = await send({ type: 'auto' });
+ }
if (!response.ok) { await response.body?.cancel(); check(false, 502, `Service returned HTTP ${response.status}`); }
let result; try { result = JSON.parse((await boundedBody(response)).toString('utf8')); } catch { check(false, 502, 'Invalid native web response'); }
- const toolResults = result.content?.filter(item => item.type === `${name}_tool_result`) ?? [];
- check(toolResults.length > 0 && !toolResults.some(item => item.content?.type?.endsWith('_error')), 502, `Native web ${kind} failed`);
+ // Parallel calls beyond max_uses come back as max_uses_exceeded errors; use whichever calls succeeded.
+ const toolResults = (result.content?.filter(item => item.type === `${name}_tool_result`) ?? [])
+ .filter(item => !item.content?.type?.endsWith('_error'));
+ check(toolResults.length > 0, 502, `Native web ${kind} failed`);
if (kind === 'search') {
const refs = toolResults.flatMap(item => Array.isArray(item.content) ? item.content : []);
return { answer: result.content.filter(item => item.type === 'text').map(item => item.text).join('\n'),
diff --git a/host/server/auth.mjs b/host/server/auth.mjs
index 37f5bdd9d3391dfbc0229de3e1f629691e93714b..8b88d99ad1fe56803799ace3fbd57ff806d24964 100644
--- a/host/server/auth.mjs
+++ b/host/server/auth.mjs
@@ -21,6 +21,12 @@ const publicDevice = ({
}) => ({ id, name, platform, createdAt, revokedAt, lastSeenAt });
const normalizeKey = (value) =>
typeof value === "string" ? value.replace(/[\s-]/g, "").toUpperCase() : "";
+const validDeviceName = (value) =>
+ check(
+ typeof value === "string" && value.trim().length > 0 && value.length <= 80,
+ 400,
+ "设备名称需要 1–80 个字符",
+ );
export class Auth {
constructor(
dataDir,
@@ -29,6 +35,7 @@ export class Auth {
this.dataDir = dataDir;
this.sessionMs = sessionMs;
this.pairingMs = pairingMs;
+ this.touchWrites = new Map();
this.store = new JsonStore(join(dataDir, "auth.json"), {
version: 1,
admin: null,
@@ -93,12 +100,9 @@ export class Auth {
return token;
}
adminSession(token) {
- return (
- typeof token === "string" &&
- this.store.value.sessions.some(
- (item) => item.hash === hash(token) && item.expiresAt > Date.now(),
- )
- );
+ if (typeof token !== "string") return false;
+ const fingerprint = hash(token), now = Date.now();
+ return this.store.value.sessions.some(item => item.hash === fingerprint && item.expiresAt > now);
}
async logout(token) {
await this.store.mutate((state) => {
@@ -131,34 +135,44 @@ export class Auth {
.filter((item) => item.expiresAt > Date.now())
.map(({ id, expiresAt }) => ({ id, expiresAt }));
}
- async pair({ pairingKey, deviceName, platform }) {
- check(
- typeof deviceName === "string" &&
- deviceName.trim().length > 0 &&
- deviceName.length <= 80,
- 400,
- "设备名称需要 1–80 个字符",
- );
- check(
+ /**
+ * Pairs a client with a one-time code. `web` is set only by the Host's own web client sign-in;
+ * clients pairing through /connect/pair are desktops, Android phones or iOS devices.
+ */
+ async pair({ pairingKey, deviceName, platform, clientKind }, { web = false } = {}) {
+ validDeviceName(deviceName);
+ if (!web) check(
["desktop", "ios"].includes(platform),
400,
"设备类型应为 desktop 或 ios",
);
- const token = secret();
- const id = randomUUID();
- await this.store.mutate((state) => {
+ const kind = web ? "web" : platform === "desktop" && clientKind === "android" ? "android" : platform;
+ return this.addDevice(deviceName, kind, state => {
const index = state.pairing.findIndex(
(item) =>
item.hash === hash(normalizeKey(pairingKey)) &&
item.expiresAt > Date.now(),
);
check(index >= 0, 401, "配对码无效、已使用或已过期");
+ return () => state.pairing.splice(index, 1);
+ });
+ }
+ /** A browser opened from the signed-in admin page; the administrator needs no pairing code. */
+ async addWebDevice(deviceName) {
+ return this.addDevice(deviceName, "web", () => () => {});
+ }
+ async addDevice(deviceName, platform, authorize) {
+ validDeviceName(deviceName);
+ const token = secret();
+ const id = randomUUID();
+ await this.store.mutate((state) => {
+ const consume = authorize(state);
check(
state.devices.filter((item) => !item.revokedAt).length < 100,
409,
"设备数量已达上限,请先撤销不用的设备",
);
- state.pairing.splice(index, 1);
+ consume();
state.devices.push({
id,
name: deviceName.trim(),
@@ -173,8 +187,9 @@ export class Auth {
}
authenticate(token) {
if (typeof token !== "string") return null;
+ const fingerprint = hash(token);
const device = this.store.value.devices.find(
- (item) => !item.revokedAt && item.hash === hash(token),
+ (item) => !item.revokedAt && item.hash === fingerprint,
);
return device ? publicDevice(device) : null;
}
@@ -190,12 +205,17 @@ export class Auth {
const device = this.device(id);
if (!device || Date.now() - Date.parse(device.lastSeenAt ?? 0) < 60_000)
return;
- await this.store.mutate((state) => {
+ // One page load can request many resources before the first fsync has finished.
+ const inflight = this.touchWrites.get(id);
+ if (inflight) return inflight;
+ const pending = this.store.mutate((state) => {
const current = state.devices.find(
(item) => item.id === id && !item.revokedAt,
);
if (current) current.lastSeenAt = new Date().toISOString();
});
+ this.touchWrites.set(id, pending);
+ try { await pending; } finally { this.touchWrites.delete(id); }
}
async revoke(id) {
await this.store.mutate((state) => {
diff --git a/host/server/desktop-capabilities.mjs b/host/server/desktop-capabilities.mjs
index 33749a2b8017ef42876923733c8d51a6a27705a2..f18b47ca30a45e5ff63fe1e0199a36710d82e382 100644
--- a/host/server/desktop-capabilities.mjs
+++ b/host/server/desktop-capabilities.mjs
@@ -6,6 +6,8 @@ const internalPrefix = '/internal/desktop-capabilities';
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const validId = value => typeof value === 'string' && value.length > 0 && value.length <= 160;
const maxResultBytes = 24 * 1024 * 1024;
+// Paired desktop clients announce their OS; machine IDs keep the original mac- form on macOS.
+const desktopPlatforms = { darwin: 'mac', win32: 'win' };
const computerTool = /^(computer_(screenshot|click|move|drag|type|key|scroll|wait|check_permissions|apps|resolve_app|app_state|set_value|app_action)|codex_(start|status|continue|cancel|list))$/;
/** Outbound device channels. A request is never retried after its provider leaves. */
@@ -24,7 +26,7 @@ export class DesktopCapabilities {
list() {
if (!this.enabled()) return [];
return [...this.providers.values()].filter(p => p.tools && Date.now() - p.lastSeen <= 35000)
- .map(p => ({ machineId: p.machineId, label: p.label, tools: p.tools }));
+ .map(p => ({ machineId: p.machineId, label: p.label, platform: p.platform, tools: p.tools }));
}
send(provider, value) {
check(!provider.response.destroyed, 409, 'Computer disconnected');
@@ -37,7 +39,7 @@ export class DesktopCapabilities {
error ? pending.reject(error) : pending.resolve(result);
}
async call(args, signal) {
- check(this.enabled(), 409, 'Mac computer control is disabled');
+ check(this.enabled(), 409, 'Computer control is disabled');
check(object(args) && validId(args.machineId) && validId(args.conversationId) && computerTool.test(args.toolId), 400, 'Invalid computer call');
check(object(args.arguments ?? {}) && (!args.approvalId || validId(args.approvalId)) &&
(!args.authorizedApp || validId(args.authorizedApp)), 400, 'Invalid computer arguments');
@@ -86,7 +88,10 @@ export class DesktopCapabilities {
check(request.method === 'GET', 405, 'GET required');
const previous = this.providers.get(device.id);
if (previous) { this.disconnect(previous); previous.response.destroy(); }
- const provider = { id: randomUUID(), deviceId: device.id, machineId: `mac-${device.id}`, response, lastSeen: Date.now() };
+ const requested = new URL(request.url, 'http://local').searchParams.get('platform') ?? 'darwin';
+ check(Object.hasOwn(desktopPlatforms, requested), 400, 'Unsupported desktop platform');
+ const provider = { id: randomUUID(), deviceId: device.id, platform: requested,
+ machineId: `${desktopPlatforms[requested]}-${device.id}`, response, lastSeen: Date.now() };
this.providers.set(device.id, provider);
this.connections?.track(device.id, response);
response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', 'x-accel-buffering': 'no' });
diff --git a/host/server/index.mjs b/host/server/index.mjs
index 5a249baf394509012be0b985c442157ae63243d1..936a541c236b32052e0183ad918e02e3bf1c5bcb 100644
--- a/host/server/index.mjs
+++ b/host/server/index.mjs
@@ -51,6 +51,7 @@ import { attachmentDataUrl } from "./attachments.mjs";
import { DeviceConnections, proxyHttp, proxyWebSocket } from "./proxy.mjs";
import { proxyLocalExec } from "./local-exec-proxy.mjs";
import { VncTickets, vncPath, normalizeVncUpgradeUrl } from "./vnc.mjs";
+import { WebClient, rawBody, webManifest } from "./web-client.mjs";
import {
adminMutation,
bearer,
@@ -68,7 +69,7 @@ import {
const publicDir = fileURLToPath(new URL("./public/", import.meta.url));
const assetTypes = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml" };
-const pages = new Map([["/", "index.html"], ["/admin", "index.html"], ["/connectors/result", "connector-result.html"]]);
+const pages = new Map([["/", "index.html"], ["/admin", "index.html"], ["/connectors/result", "connector-result.html"], ["/web/login", "web-login.html"]]);
// Admin assets are served from a fixed listing taken at startup.
const publicAssets = new Set(readdirSync(publicDir).filter((name) => [".js", ".css", ".svg"].includes(extname(name))));
const adminCookie = "grokbot_admin";
@@ -127,6 +128,7 @@ export async function createSelfHostServer(options = {}) {
),
};
const auth = await new Auth(dataDir, options.authOptions).load();
+ const webClient = await new WebClient(dataDir, { auth }).load();
const models = new Models(dataDir, {
filename: options.modelFile ?? process.env.GROKBOT_MODEL_ENV,
});
@@ -164,7 +166,7 @@ export async function createSelfHostServer(options = {}) {
const desktopCapabilities = new DesktopCapabilities({ authenticate: device, connections, internalToken, enabled: () => harness.current().macComputer });
const browserProviders = new DesktopBrowserProviders({ authenticate: device, connections, hostUrl, internalToken, enabled: key => harness.current()[key] });
let executionRevision = executionNode.active()?.revision;
- const limiter = new RateLimit();
+ const limiter = options.rateLimit ?? new RateLimit();
const usage = timeZone => {
try { new Intl.DateTimeFormat('en', { timeZone }).format(); }
catch { throw new HttpError(400, 'Invalid time zone'); }
@@ -173,8 +175,10 @@ export async function createSelfHostServer(options = {}) {
const sockets = new Set();
function device(request) {
check(federation.role() === 'primary', 403, 'Connect to the primary Host');
- const found = auth.authenticate(bearer(request));
- check(found, 401, "设备凭证无效,请重新配对");
+ // The web client signs in with a cookie instead of a bearer token (web-client.mjs).
+ const browser = webClient.deviceToken(request, request.grokbotOrigin);
+ const found = auth.authenticate(browser ?? bearer(request));
+ check(found && (!browser || found.platform === "web"), 401, "设备凭证无效,请重新配对");
void auth.touch(found.id).catch(() => {});
return found;
}
@@ -234,6 +238,68 @@ export async function createSelfHostServer(options = {}) {
ticketCookie: `grokbot_vnc_${route.slot}=${ticket}; Path=/vnc/${route.slot}/; HttpOnly; SameSite=Strict; Max-Age=${Math.floor(tickets.ttlMs / 1000)}${origin.startsWith("https:") ? "; Secure" : ""}`,
};
}
+ async function revokeDevice(id) {
+ await auth.revoke(id);
+ await push.revoke(id);
+ tickets.revoke(id);
+ connections.revoke(id);
+ }
+ /** Sign-in, sign-out and the bundle files of the web client (web-client.mjs); /web/login is a public page. */
+ async function webRoutes(request, response, path, origin, url) {
+ const method = request.method;
+ const fromPage = () => check(request.headers["x-grokbot-web"] === "1" &&
+ (!request.headers.origin || request.headers.origin === origin), 403, "请从网页版登录页操作");
+ if (method === "GET" && path === "/web/api/session") {
+ const signedIn = webClient.browserDevice(request), status = webClient.status();
+ return sendJson(response, 200, { available: status.available, rendererVersion: status.rendererVersion,
+ paired: Boolean(signedIn), deviceName: signedIn?.device.name ?? null, secure: origin.startsWith("https:") });
+ }
+ if (method === "POST" && path === "/web/api/pair") {
+ check(federation.role() === "primary", 403, "Connect to the primary Host");
+ fromPage();
+ check(webClient.available, 404, "网页版未启用");
+ limiter.check(`pair:${request.socket.remoteAddress}`, 6);
+ limiter.check("pair:global", 60);
+ const { pairingKey, deviceName } = await jsonBody(request);
+ const previous = webClient.browserDevice(request);
+ const result = await auth.pair({ pairingKey, deviceName }, { web: true });
+ // Signing in again replaces this browser's earlier device instead of leaving it behind.
+ if (previous) await revokeDevice(previous.device.id);
+ response.setHeader("set-cookie", webClient.sessionCookie(result.token, origin));
+ return sendJson(response, 201, { ok: true, deviceId: result.deviceId });
+ }
+ if (method === "POST" && path === "/web/api/logout") {
+ fromPage();
+ const signedIn = webClient.browserDevice(request);
+ if (signedIn) await revokeDevice(signedIn.device.id);
+ response.setHeader("set-cookie", webClient.sessionCookie("", origin));
+ return sendJson(response, 200, { ok: true });
+ }
+ if (method === "GET" && path === "/web/manifest.webmanifest") {
+ check(webClient.available, 404, "网页版未启用");
+ response.writeHead(200, { "content-type": "application/manifest+json; charset=utf-8" });
+ return response.end(JSON.stringify(webManifest()));
+ }
+ if (["GET", "HEAD"].includes(method) && (path === "/web" || path === "/web/")) {
+ response.writeHead(302, { location: `${webClient.browserDevice(request) ? "/web/renderer/index.html" : "/web/login"}${url.search}` });
+ return response.end();
+ }
+ const file = /^\/web\/((?:renderer|client)\/.+)$/.exec(path);
+ if (file && ["GET", "HEAD"].includes(method)) {
+ let name = null;
+ try { name = decodeURIComponent(file[1]); } catch {}
+ check(name && webClient.has(name), 404, "文件不存在");
+ const signedIn = webClient.browserDevice(request);
+ if (!signedIn && name === "renderer/index.html") {
+ response.writeHead(302, { location: `/web/login${url.search}` });
+ return response.end();
+ }
+ check(signedIn, 401, "请先登录网页版");
+ void auth.touch(signedIn.device.id).catch(() => {});
+ return webClient.serve(request, response, name);
+ }
+ throw new HttpError(404, "页面不存在");
+ }
async function hostStatus() {
try {
const result = await fetch(new URL("/api/listAgents", hostUrl), {
@@ -274,11 +340,9 @@ export async function createSelfHostServer(options = {}) {
validateAgentId(agentId);
const status = await hostStatus();
check(status.connected, 503, "Host 暂不可用,无法读取 Bot 资料库");
- check(
- status.agents.some((agent) => agent.id === agentId),
- 404,
- "Bot 不存在",
- );
+ const agent = status.agents.find((item) => item.id === agentId);
+ check(agent, 404, "Bot 不存在");
+ return agent;
}
async function adminRoutes(request, response, path, origin) {
const method = request.method;
@@ -358,9 +422,11 @@ export async function createSelfHostServer(options = {}) {
startedAt: bootAt,
publicUrl: origin,
model,
- host,
+ host: { ...host, waitingForExecutionNode: !host.connected &&
+ process.env.GROKBOT_REQUIRE_EXECUTION_NODE === '1' && !executionNode.store.value.config.enabled },
devices: push.devices(),
pairingKeys: auth.pairingKeys(),
+ webClient: webClient.status(),
notifications: {
...notificationSettings.current(),
count: notifications.store.value.items.length,
@@ -400,8 +466,37 @@ export async function createSelfHostServer(options = {}) {
await models.test(await jsonBody(request)),
);
}
+ const summarize = /^\/admin\/api\/agents\/([a-f0-9-]{1,128})\/summarize$/.exec(path);
+ if (method === 'POST' && summarize) {
+ const agent = await verifyAgent(summarize[1]);
+ check(!agent.isRunning, 409, 'Bot 正在运行,请在任务结束后再压缩');
+ limiter.check(`manual-summary:${summarize[1]}`, 4, 10 * 60_000);
+ const result = await internalHostClient(hostUrl, internalToken)('localApplicationRpc', {
+ action: 'grokbot.manual-summary', agentId: summarize[1],
+ });
+ return sendJson(response, 200, { ...result, message: '上下文已压缩' });
+ }
if (method === "POST" && path === "/admin/api/pairing-keys")
return sendJson(response, 201, await auth.createPairing());
+ if (path === "/admin/api/web-client") {
+ if (method === "GET") return sendJson(response, 200, webClient.status());
+ if (method === "PUT") {
+ check(String(request.headers["content-type"] ?? "").split(";")[0].trim() === "application/zip", 415, "请上传 ZIP 格式的网页版界面包");
+ return sendJson(response, 200, await webClient.install(await rawBody(request)));
+ }
+ if (method === "PATCH") return sendJson(response, 200, await webClient.setEnabled((await jsonBody(request)).enabled));
+ if (method === "DELETE") return sendJson(response, 200, await webClient.remove());
+ }
+ if (method === "POST" && path === "/admin/api/web-client/open") {
+ // Opens the web client in the administrator's own browser without a pairing code.
+ check(webClient.available, 409, "请先上传并启用网页版");
+ const { deviceName } = await jsonBody(request);
+ // A browser that is already signed in keeps its device instead of gaining another.
+ if (webClient.browserDevice(request)) return sendJson(response, 200, { ok: true, url: "/web/" });
+ const result = await auth.addWebDevice(typeof deviceName === "string" && deviceName.trim() ? deviceName : "网页版");
+ response.setHeader("set-cookie", webClient.sessionCookie(result.token, origin));
+ return sendJson(response, 201, { ok: true, url: "/web/" });
+ }
const deviceName = /^\/admin\/api\/devices\/([a-f0-9-]{36})$/.exec(path);
if (method === "PATCH" && deviceName) {
const body = await jsonBody(request);
@@ -411,10 +506,7 @@ export async function createSelfHostServer(options = {}) {
path,
);
if (method === "POST" && revoke) {
- await auth.revoke(revoke[1]);
- await push.revoke(revoke[1]);
- tickets.revoke(revoke[1]);
- connections.revoke(revoke[1]);
+ await revokeDevice(revoke[1]);
return sendJson(response, 200, { ok: true });
}
if (path === '/admin/api/notification-settings' && ['GET', 'PUT'].includes(method))
@@ -459,9 +551,17 @@ export async function createSelfHostServer(options = {}) {
const path = request.url.split("?")[0];
const origin = originFor(request, network.isIngress(request) ? '' : canonical);
delete request.headers['x-grokbot-tailcat-ingress'];
+ request.grokbotOrigin = origin;
const url = new URL(request.url, origin);
if (path.startsWith("/admin/api/"))
return adminRoutes(request, response, path, origin);
+ if ((path === "/web" || path.startsWith("/web/")) && path !== "/web/login")
+ return webRoutes(request, response, path, origin, url);
+ if (path === "/local-client/icon.png" && request.method === "GET") {
+ // The desktop settings pages load the program icon from here; the web client serves its own.
+ check(webClient.browserDevice(request) && webClient.has("client/icon.png"), 404, "页面不存在");
+ return webClient.serve(request, response, "client/icon.png");
+ }
if (await mediaInternal(request, response, path, { internalToken, mediaServices, webServices })) return;
if (request.method === 'POST' && ['/federation/v1/pair', '/federation/v1/sync', '/federation/v1/revoke'].includes(path)) {
limiter.check(`federation:${request.socket.remoteAddress}`, 120);
@@ -577,9 +677,21 @@ export async function createSelfHostServer(options = {}) {
}
if (path.startsWith("/vnc/")) {
check(["GET", "HEAD"].includes(request.method), 405, "不支持的请求方法");
+ // The web client's computer view runs the bridge the Android shell injects (android/client/vnc-bridge.js).
+ const script = /^\/vnc\/(desktop|fork)\/__grokbot-(vnc-bridge|vnc-preload)\.js$/.exec(path);
+ if (script) {
+ const value = tickets.validate(cookie(request, `grokbot_vnc_${script[1]}`), script[1]);
+ check(value && webClient.available && auth.device(value.deviceId)?.platform === "web", 401, "桌面访问票据已失效,请重新打开电脑预览");
+ const body = await webClient.vncScript(script[2], origin);
+ response.writeHead(200, { "content-type": "text/javascript; charset=utf-8", "cross-origin-resource-policy": "same-origin" });
+ return response.end(request.method === "HEAD" ? undefined : body);
+ }
const access = vncAccess(request, url, path, origin);
connections.track(access.deviceId, response);
- return proxyHttp(request, response, access);
+ const page = request.method === "GET" && /^\/vnc\/(desktop|fork)\/vnc(_lite|_auto)?\.html$/.test(path);
+ const web = page && webClient.available && auth.device(access.deviceId)?.platform === "web";
+ return proxyHttp(request, response, web
+ ? { ...access, transformHtml: html => WebClient.injectVncBridge(html, path.slice(0, path.lastIndexOf("/"))) } : access);
}
if (await desktopCapabilities.route(request, response, path)) return;
if (await browserProviders.route(request, response, path)) return;
@@ -609,7 +721,7 @@ export async function createSelfHostServer(options = {}) {
const status = options.computers?.() ?? { available: false, computers: [] }, computers = new Map(status.computers.map(item => [item.id, item]));
for (const item of desktopCapabilities.list()) {
const previous = computers.get(item.machineId);
- computers.set(item.machineId, { ...previous, id: item.machineId, label: item.label, connected: true, platform: 'darwin',
+ computers.set(item.machineId, { ...previous, id: item.machineId, label: item.label, connected: true, platform: item.platform ?? 'darwin',
capabilities: [...new Set([...(previous?.capabilities ?? []), 'gui'])] });
}
return sendJson(response, 200, { available: status.available || computers.size > 0, computers: [...computers.values()] });
@@ -766,6 +878,7 @@ export async function createSelfHostServer(options = {}) {
);
const origin = originFor(request, network.isIngress(request) ? '' : canonical);
delete request.headers['x-grokbot-tailcat-ingress'];
+ request.grokbotOrigin = origin;
const url = new URL(request.url, origin);
check(federation.role() === 'primary', 403, 'Connect to the primary Host');
if (url.pathname === '/local/voice/realtime') return voice.upgrade(request, socket, head);
@@ -802,6 +915,7 @@ export async function createSelfHostServer(options = {}) {
tickets,
library,
profile,
+ webClient,
dataDir,
async start(
port = Number(process.env.GROKBOT_PORT ?? 8000),
@@ -845,6 +959,7 @@ export async function createSelfHostServer(options = {}) {
webhooks.store.tail,
sharing.store.tail,
mediaSettings.store.tail, webSettings.store.tail, mediaServices.store.tail,
+ webClient.store.tail, webClient.installing,
]);
},
};
diff --git a/host/server/internal-host.mjs b/host/server/internal-host.mjs
index c5d77d3978a4a9443d2affbff988c3562b5b6b81..e49a764baa23f9240258685a46e1ac707cdee756 100644
--- a/host/server/internal-host.mjs
+++ b/host/server/internal-host.mjs
@@ -2,9 +2,10 @@ import { HttpError } from './security.mjs';
export function internalHostClient(url, token) {
return async (method, args, { signal } = {}) => {
if (!/^[A-Za-z][A-Za-z0-9]+$/.test(method)) throw new Error('Invalid Host method');
+ const manualSummary = method === 'localApplicationRpc' && args?.action === 'grokbot.manual-summary';
const response = await fetch(new URL(`/api/${method}`, url), { method: 'POST', redirect: 'error',
headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
- body: JSON.stringify(args), signal: signal ?? AbortSignal.timeout(method === 'localApplicationRpc' ? 110000 : 30000) });
+ body: JSON.stringify(args), signal: signal ?? AbortSignal.timeout(manualSummary ? 300000 : method === 'localApplicationRpc' ? 110000 : 30000) });
const result = await response.json();
if (!response.ok) throw new HttpError(response.status, result.error ?? 'Host request failed');
return result;
diff --git a/host/server/media-http.mjs b/host/server/media-http.mjs
index d5ee5327dbcf5fabf341402df214efd8d5f6a280..92a64c9f65715ae0e1d7d3805054c7b2e86fdbc4 100644
--- a/host/server/media-http.mjs
+++ b/host/server/media-http.mjs
@@ -20,12 +20,13 @@ export async function boundedBody(response, limit = 8 * 1024 * 1024) {
return Buffer.concat(parts);
} catch (error) { response.destroy?.(); throw error; }
}
-export async function serviceJson(url, { apiKey, signal, body, method, limit } = {}) {
- const response = await fetch(url, { method: method ?? (body === undefined ? 'GET' : 'POST'),
+/** `form` sends multipart FormData (fetch sets the boundary); `body` sends JSON. */
+export async function serviceJson(url, { apiKey, signal, body, form, method, limit } = {}) {
+ const response = await fetch(url, { method: method ?? (body === undefined && form === undefined ? 'GET' : 'POST'),
redirect: 'error', signal, headers: { accept: 'application/json',
...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),
...(body === undefined ? {} : { 'content-type': 'application/json' }) },
- ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ ...(form !== undefined ? { body: form } : body === undefined ? {} : { body: JSON.stringify(body) }) });
if (!response.ok) {
await response.body?.cancel();
throw Object.assign(new HttpError(502, `Service returned HTTP ${response.status}`), { upstreamStatus: response.status });
diff --git a/host/server/media-providers.mjs b/host/server/media-providers.mjs
index 88f2168248b139e58ef4ff65524ec261907717d0..08468bf59ad10f5cdfba65cb40f8b29b3562de81 100644
--- a/host/server/media-providers.mjs
+++ b/host/server/media-providers.mjs
@@ -8,15 +8,36 @@ function reference(value) {
&& value.data.length < 40 * 1024 * 1024 && /^[A-Za-z0-9+/]+={0,2}$/.test(value.data), 400, 'Invalid reference image');
return `data:${value.mimeType};base64,${value.data}`;
}
-export function mediaInput(model, input) {
+// Sizes every OpenAI-compatible image model accepts.
+const standardSizes = ['1024x1024', '1536x1024', '1024x1536'];
+/** The WIDTHxHEIGHT entry whose ratio is closest to `aspectRatio`; earlier entries win ties. */
+export function sizeForAspect(aspectRatio, sizes = standardSizes) {
+ const [width, height] = aspectRatio.split(':').map(Number);
+ check(width > 0 && height > 0, 400, 'Invalid aspect ratio');
+ let best;
+ for (const size of sizes) {
+ const match = /^(\d+)x(\d+)$/.exec(size);
+ if (!match) continue;
+ const distance = Math.abs(Math.log((match[1] / match[2]) / (width / height)));
+ if (!best || distance < best.distance - 1e-9) best = { size, distance };
+ }
+ check(best, 400, 'No configured size matches the aspect ratio');
+ return best.size;
+}
+export function mediaInput(model, input, adapter) {
check(typeof input.prompt === 'string' && input.prompt.trim().length > 0 && input.prompt.length <= 30_000, 400, 'Invalid media prompt');
check(!input.references || Array.isArray(input.references) && input.references.length <= 10, 400, 'Too many reference images');
const body = { ...model.parameters, prompt: input.prompt };
const properties = model.inputSchema?.properties;
if (input.aspectRatio) {
check(typeof input.aspectRatio === 'string' && /^\d{1,2}:\d{1,2}$/.test(input.aspectRatio), 400, 'Invalid aspect ratio');
- check(!properties || properties.aspect_ratio, 400, 'This model does not accept aspect_ratio; configure its size parameter');
- body.aspect_ratio = input.aspectRatio;
+ // Models that take a pixel size instead of a ratio get the closest listed size; explicit parameters still win below.
+ const sizes = Array.isArray(properties?.size?.enum) ? properties.size.enum : adapter === 'openai-images' ? standardSizes : null;
+ if (sizes && !properties?.aspect_ratio) body.size = sizeForAspect(input.aspectRatio, sizes);
+ else {
+ check(!properties || properties.aspect_ratio, 400, 'This model does not accept aspect_ratio; configure its size parameter');
+ body.aspect_ratio = input.aspectRatio;
+ }
}
if (input.references?.length) {
const images = input.references.map(reference);
@@ -43,11 +64,23 @@ export async function submitMedia(provider, model, body, signal) {
return waveResult(await serviceJson(`${provider.baseUrl}/api/v3/${model.model}`, { ...common, body }));
}
if (provider.adapter === 'openai-images') {
- check(!body.images?.length, 400, 'Configure an editing adapter for image references');
- const { aspect_ratio, ...parameters } = body;
+ const { aspect_ratio, images, image, ...parameters } = body;
check(!aspect_ratio, 400, 'OpenAI Images uses the configured size parameter');
- const result = await serviceJson(`${provider.baseUrl}/images/generations`, {
- ...common, body: { ...parameters, model: model.model, n: 1 } });
+ const request = { ...parameters, model: model.model, n: 1 }, references = images ?? (image ? [image] : []);
+ let result;
+ if (references.length) {
+ // Reference images go to the edits endpoint as multipart files.
+ const form = new FormData();
+ for (const [key, value] of Object.entries(request)) {
+ check(value === null || ['string', 'number', 'boolean'].includes(typeof value), 400, `Image edits do not accept parameter ${key}`);
+ if (value !== null) form.append(key, String(value));
+ }
+ references.forEach((url, index) => {
+ const [, mimeType, data] = /^data:(image\/[a-z]+);base64,(.*)$/.exec(url);
+ form.append('image[]', new Blob([Buffer.from(data, 'base64')], { type: mimeType }), `reference-${index + 1}.${mimeType.slice(6)}`);
+ });
+ result = await serviceJson(`${provider.baseUrl}/images/edits`, { ...common, form });
+ } else result = await serviceJson(`${provider.baseUrl}/images/generations`, { ...common, body: request });
check(Array.isArray(result.data) && result.data.length, 502, 'Image service returned no image');
return { status: 'completed', outputs: result.data.map(item => item.b64_json
? { base64: item.b64_json, mimeType: 'image/png' } : item.url) };
diff --git a/host/server/media-settings.mjs b/host/server/media-settings.mjs
index 95114295fc6b0d0eaaa2b4878aa488fd2bb3b365..29ae73e9aa3648ac26be8d6fb9283969e880be6f 100644
--- a/host/server/media-settings.mjs
+++ b/host/server/media-settings.mjs
@@ -69,7 +69,7 @@ export function mediaModels(config, kind) {
export function describeMediaModels(models) {
return models.map(model => {
const parameters = Object.fromEntries(Object.entries(model.inputSchema?.properties ?? {})
- .filter(([name]) => !['prompt', 'enable_sync_mode', 'enable_base64_output'].includes(name))
+ .filter(([name]) => !['prompt', 'images', 'image', 'enable_sync_mode', 'enable_base64_output'].includes(name))
.map(([name, schema]) => [name, Object.fromEntries(['type', 'enum', 'minimum', 'maximum', 'maxItems', 'default']
.filter(key => schema?.[key] !== undefined).map(key => [key, schema[key]]))]));
return `${model.id}: ${model.name}. ${model.description}`
diff --git a/host/server/models.mjs b/host/server/models.mjs
index 88ab5abf11a2cedc3b1cd581edb9ca50d717ef4e..e0228d259ee895f4cab95d75f27dbd2f69ef9e5f 100644
--- a/host/server/models.mjs
+++ b/host/server/models.mjs
@@ -1,220 +1,264 @@
-import { parseModelPolicy, defaultPolicy, validatePolicy, effortLevels, reasoningOptions } from '../runtime/model-policy.mjs';
+import { catalogContextPolicy, defaultPolicy, effortLevels, parseModelPolicy, validatePolicy, EFFORTS } from '../runtime/model-policy.mjs';
import { createModelRouter } from '../runtime/model-router.mjs';
+import { anthropicEndpoint, anthropicHeaders } from '../runtime/anthropic-messages.mjs';
+import { createModelSession } from '../runtime/model-session.mjs';
+import { API_FORMATS, MODEL_ROUTING_ENV, isConfiguredModelRouting, modelRouteForAgent, modelRouteForProfile,
+ parseModelRouting, publicModelRouting, validateModelProvider, validateModelRouting } from '../runtime/model-routing.mjs';
import { recordUsage } from '../runtime/usage-ledger.mjs';
-import { randomUUID } from "node:crypto";
-import { readFile } from "node:fs/promises";
-import { join } from "node:path";
-import { check } from "./security.mjs";
-import { readJson, writePrivate } from "./storage.mjs";
+import { randomUUID } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { check } from './security.mjs';
+import { readJson, writePrivate } from './storage.mjs';
+const own = (value, key) => Object.prototype.hasOwnProperty.call(value ?? {}, key);
const clean = (value, label, maximum = 2048) => {
- check(
- typeof value === "string" &&
- value.trim().length > 0 &&
- value.length <= maximum &&
- !/[\r\n\0]/.test(value),
- 400,
- `${label}不能为空,也不能包含换行`,
- );
+ check(typeof value === 'string' && value.trim().length > 0 && value.length <= maximum && !/[\r\n\0]/.test(value), 400,
+ `${label}不能为空,也不能包含换行`);
return value.trim();
};
+
+function valuesFrom(source) {
+ return Object.fromEntries(source.split(/\r?\n/).filter(line => line.includes('=') && !line.startsWith('#'))
+ .map(line => { const at = line.indexOf('='); return [line.slice(0, at), line.slice(at + 1)]; }));
+}
+
+function legacyConfig(values) {
+ return {
+ apiFormat: API_FORMATS.includes(values.MODEL_API_FORMAT) ? values.MODEL_API_FORMAT : 'openai',
+ baseUrl: values.OPENAI_BASE_URL ?? '', model: values.OPENAI_MODEL ?? '', apiKey: values.OPENAI_API_KEY ?? '',
+ contextWindowTokens: Number(values.OPENAI_CONTEXT_WINDOW_TOKENS ?? 0),
+ policy: parseModelPolicy(values.GROKBOT_MODEL_POLICY, values.OPENAI_MODEL || undefined),
+ jevApiKey: values.JEV_API_KEY || '',
+ };
+}
+
+function context(value) {
+ const parsed = Number(value ?? 0);
+ check(Number.isSafeInteger(parsed) && parsed >= 0 && parsed <= 100_000_000, 400,
+ '上下文长度应为 0–100000000 的整数');
+ return parsed;
+}
+
+function serviceUrl(value) {
+ const baseUrl = clean(value, 'Base URL');
+ let url;
+ try { url = new URL(baseUrl); }
+ catch { check(false, 400, 'Base URL 格式不正确'); }
+ check(['http:', 'https:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash,
+ 400, 'Base URL 需要 HTTP(S) 地址,不能包含凭证或查询参数');
+ return url.href.replace(/\/$/, '');
+}
+
+function publicError(error) {
+ return `模型配置无效:${String(error?.message ?? error).slice(0, 240)}`;
+}
+
+function compatibilityPolicy(route) {
+ const policy = defaultPolicy(route.model);
+ policy.effort = route.effort;
+ policy.models = [{ id: route.model, efforts: route.efforts,
+ contextWindowTokens: route.contextWindowTokens, summaryThresholdTokens: route.summaryThresholdTokens }];
+ return policy;
+}
+
export class Models {
- constructor(dataDir, { filename = join(dataDir, "model.env") } = {}) {
+ constructor(dataDir, { filename = join(dataDir, 'model.env') } = {}) {
this.filename = filename;
this.dataDir = dataDir;
this.tail = Promise.resolve();
}
async current() {
- const filename = this.filename;
- const source = await readFile(filename, "utf8").catch((error) => {
- if (error.code === "ENOENT") return "";
+ const source = await readFile(this.filename, 'utf8').catch(error => {
+ if (error.code === 'ENOENT') return '';
throw error;
});
- const values = Object.fromEntries(
- source
- .split(/\r?\n/)
- .filter((line) => line.includes("=") && !line.startsWith("#"))
- .map((line) => {
- const at = line.indexOf("=");
- return [line.slice(0, at), line.slice(at + 1)];
- }),
- );
- return {
- baseUrl: values.OPENAI_BASE_URL ?? "",
- model: values.OPENAI_MODEL ?? "",
- apiKey: values.OPENAI_API_KEY ?? "",
- contextWindowTokens: Number(values.OPENAI_CONTEXT_WINDOW_TOKENS ?? 0),
- policy: parseModelPolicy(values.GROKBOT_MODEL_POLICY, values.OPENAI_MODEL || undefined),
- jevApiKey: values.JEV_API_KEY || "",
- };
+ const values = valuesFrom(source), legacy = legacyConfig(values);
+ const parsed = parseModelRouting(values[MODEL_ROUTING_ENV], legacy);
+ let primary;
+ try { primary = modelRouteForAgent(parsed.config); }
+ catch { primary = undefined; }
+ return { ...legacy, routing: parsed.config, routingMigrated: parsed.migrated,
+ legacyAdaptiveRouting: parsed.migrated && legacy.policy?.mode === 'adaptive',
+ ...(primary ? { baseUrl: primary.baseUrl, apiKey: primary.apiKey, apiFormat: primary.apiFormat,
+ model: primary.model, contextWindowTokens: primary.contextWindowTokens, policy: compatibilityPolicy(primary) } : {}) };
}
async publicConfig() {
- const { apiKey, jevApiKey, ...config } = await this.current();
+ const current = await this.current();
+ const { apiKey, jevApiKey, routing, ...summary } = current;
return {
- ...config,
- hasApiKey: Boolean(apiKey),
- hasJevApiKey: Boolean(jevApiKey),
- configured: Boolean(config.baseUrl && config.model && apiKey),
+ ...publicModelRouting(routing),
+ ...summary,
+ hasApiKey: Boolean(apiKey), hasJevApiKey: Boolean(jevApiKey),
+ configured: isConfiguredModelRouting(routing),
reload: await this.reloadStatus(),
};
}
async reloadStatus() {
- const request = await readJson(
- join(this.dataDir, "model-reload-request.json"),
- null,
- );
- const status = await readJson(
- join(this.dataDir, "model-reload-status.json"),
- null,
- );
- if (!request) return status ?? { status: "none" };
+ const request = await readJson(join(this.dataDir, 'model-reload-request.json'), null);
+ const status = await readJson(join(this.dataDir, 'model-reload-status.json'), null);
+ if (!request) return status ?? { status: 'none' };
if (status?.revision === request.revision) {
- const allowed = ["applied", "waiting", "error", "pending"];
- return {
- revision: status.revision,
- status: allowed.includes(status.status) ? status.status : "pending",
- updatedAt: status.updatedAt,
- message:
- status.status === "error"
- ? "Host 未能应用配置,请检查服务日志"
- : undefined,
- };
+ const allowed = ['applied', 'waiting', 'error', 'pending'];
+ return { revision: status.revision, status: allowed.includes(status.status) ? status.status : 'pending',
+ updatedAt: status.updatedAt, message: status.status === 'error' ? 'Host 未能应用配置,请检查服务日志' : undefined };
}
- return {
- revision: request.revision,
- status: "pending",
- updatedAt: request.requestedAt,
- };
+ return { revision: request.revision, status: 'pending', updatedAt: request.requestedAt };
}
- async validated(input) {
- const previous = await this.current();
- const baseUrl = clean(input.baseUrl, "Base URL");
- let url;
+ legacyRouting(input, previous) {
+ const apiFormat = input.apiFormat ?? previous.apiFormat;
+ check(API_FORMATS.includes(apiFormat), 400, '接口格式无效');
+ const baseUrl = serviceUrl(input.baseUrl ?? previous.baseUrl);
+ const model = clean(input.model ?? previous.model, '模型名称', 256);
+ const active = (() => { try { return modelRouteForAgent(previous.routing); } catch { return undefined; } })();
+ const apiKey = clean(input.apiKey || active?.apiKey || previous.apiKey, 'API Key', 8192);
+ const contextWindowTokens = context(input.contextWindowTokens ?? active?.contextWindowTokens ?? previous.contextWindowTokens);
+ let policy;
try {
- url = new URL(baseUrl);
- } catch {
- check(false, 400, "Base URL 格式不正确");
+ policy = validatePolicy(input.policy ?? (previous.model === model ? previous.policy : defaultPolicy(model)), model);
+ } catch (error) { check(false, 400, error.message); }
+ check(policy.mode !== 'adaptive' || (input.jevApiKey || previous.jevApiKey), 400, '请填写 Jev API Key');
+ const providerId = active?.providerId ?? 'default', profileId = active?.profileId ?? 'default';
+ const capability = policy.models.find(item => item.id === model) ?? { efforts: effortLevels(model) };
+ const providers = (previous.routing.providers ?? []).filter(item => item.id !== providerId);
+ providers.push({ id: providerId, name: active?.providerName ?? '默认服务', apiFormat, baseUrl, apiKey });
+ const profiles = (previous.routing.profiles ?? []).filter(item => item.id !== profileId);
+ profiles.push({ id: profileId, name: active?.profileName ?? '默认模型', providerId, model,
+ efforts: capability.efforts, contextWindowTokens: capability.contextWindowTokens ?? contextWindowTokens,
+ summaryThresholdTokens: capability.summaryThresholdTokens ?? 0 });
+ let routing;
+ try {
+ routing = validateModelRouting({ version: 1, providers, profiles,
+ defaultRoute: { profileId, effort: policy.effort, fallbacks: previous.routing.defaultRoute?.fallbacks ?? [] },
+ botRoutes: previous.routing.botRoutes ?? {} }, { previous: previous.routing });
+ } catch (error) { check(false, 400, publicError(error)); }
+ return { routing, jevApiKey: input.jevApiKey ? clean(input.jevApiKey, 'Jev API Key', 8192) : previous.jevApiKey,
+ ...(previous.routingMigrated ? { legacy: { apiFormat, baseUrl, apiKey, model, contextWindowTokens, policy } } : {}) };
+ }
+ async validated(input = {}) {
+ check(input && typeof input === 'object' && !Array.isArray(input), 400, '模型配置无效');
+ const previous = await this.current();
+ const multiProvider = Array.isArray(input.providers) || own(input, 'defaultRoute') || input.version === 1;
+ if (!multiProvider) return this.legacyRouting(input, previous);
+ check(!previous.routingMigrated || input.migrateLegacyRouting === true, 409,
+ '检测到旧版模型配置。请在模型页确认迁移后再保存。');
+ let routing;
+ try { routing = validateModelRouting(input, { previous: previous.routing }); }
+ catch (error) { check(false, 400, publicError(error)); }
+ return { routing, jevApiKey: input.jevApiKey ? clean(input.jevApiKey, 'Jev API Key', 8192) : previous.jevApiKey };
+ }
+ async write(config) {
+ if (config.legacy) {
+ const { apiFormat, baseUrl, apiKey, model, contextWindowTokens, policy } = config.legacy;
+ await writePrivate(this.filename, [
+ `MODEL_API_FORMAT=${apiFormat}`,
+ `OPENAI_BASE_URL=${baseUrl}`,
+ `OPENAI_API_KEY=${apiKey}`,
+ `OPENAI_MODEL=${model}`,
+ `OPENAI_CONTEXT_WINDOW_TOKENS=${contextWindowTokens}`,
+ `GROKBOT_MODEL_POLICY=${JSON.stringify(policy)}`,
+ `JEV_API_KEY=${config.jevApiKey}`,
+ '',
+ ].join('\n'));
+ return;
}
- check(
- ["http:", "https:"].includes(url.protocol) &&
- !url.username &&
- !url.password &&
- !url.search &&
- !url.hash,
- 400,
- "Base URL 需要 HTTP(S) 地址,不能包含凭证或查询参数",
- );
- const model = clean(input.model, "模型名称", 256);
- const apiKey = clean(input.apiKey || previous.apiKey, "API Key", 8192);
- const contextWindowTokens = Number(
- input.contextWindowTokens ?? previous.contextWindowTokens ?? 0,
- );
- check(
- Number.isSafeInteger(contextWindowTokens) &&
- contextWindowTokens >= 0 &&
- contextWindowTokens <= 100_000_000,
- 400,
- "上下文长度应为 0–100000000 的整数",
- );
- let policy;
- try { policy = validatePolicy(input.policy ?? (previous.model === model ? previous.policy : defaultPolicy(model)), model); }
- catch (error) { check(false, 400, error.message); }
- const jevApiKey = input.jevApiKey ? clean(input.jevApiKey, "Jev API Key", 8192) : previous.jevApiKey;
- check(policy.mode !== 'adaptive' || jevApiKey, 400, '请填写 Jev API Key');
- return {
- policy, jevApiKey,
- baseUrl: url.href.replace(/\/$/, ""),
- model,
- apiKey,
- contextWindowTokens,
- };
+ const primary = modelRouteForAgent(config.routing);
+ const policy = compatibilityPolicy(primary);
+ await writePrivate(this.filename, [
+ `${MODEL_ROUTING_ENV}=${JSON.stringify(config.routing)}`,
+ `MODEL_API_FORMAT=${primary.apiFormat}`,
+ `OPENAI_BASE_URL=${primary.baseUrl}`,
+ `OPENAI_API_KEY=${primary.apiKey}`,
+ `OPENAI_MODEL=${primary.model}`,
+ `OPENAI_CONTEXT_WINDOW_TOKENS=${primary.contextWindowTokens}`,
+ `GROKBOT_MODEL_POLICY=${JSON.stringify(policy)}`,
+ `JEV_API_KEY=${config.jevApiKey}`,
+ '',
+ ].join('\n'));
}
save(input) {
const pending = this.tail.then(async () => {
const config = await this.validated(input);
- await writePrivate(
- this.filename,
- [
- `OPENAI_BASE_URL=${config.baseUrl}`,
- `OPENAI_API_KEY=${config.apiKey}`,
- `OPENAI_MODEL=${config.model}`,
- `OPENAI_CONTEXT_WINDOW_TOKENS=${config.contextWindowTokens}`,
- `GROKBOT_MODEL_POLICY=${JSON.stringify(config.policy)}`,
- `JEV_API_KEY=${config.jevApiKey}`,
- "",
- ].join("\n"),
- );
- const request = {
- revision: randomUUID(),
- requestedAt: new Date().toISOString(),
- };
- await writePrivate(
- join(this.dataDir, "model-reload-request.json"),
- `${JSON.stringify(request)}\n`,
- );
+ await this.write(config);
+ const request = { revision: randomUUID(), requestedAt: new Date().toISOString() };
+ await writePrivate(join(this.dataDir, 'model-reload-request.json'), `${JSON.stringify(request)}\n`);
return this.publicConfig();
});
this.tail = pending.catch(() => {});
return pending;
}
- async catalog(input) {
+ async routeFor(input = {}, { profileId, direct = false } = {}) {
+ const hasConfig = Array.isArray(input.providers) || own(input, 'defaultRoute') || input.version === 1 || own(input, 'baseUrl');
+ const config = hasConfig ? await this.validated(input) : { routing: (await this.current()).routing };
+ if (profileId) return { config, route: modelRouteForProfile(config.routing, profileId) };
+ const route = modelRouteForAgent(config.routing);
+ return { config, route: direct ? { ...route, fallbacks: [] } : route };
+ }
+ async catalog(input = {}) {
const previous = await this.current();
- const config = await this.validated({ ...previous, ...input });
+ let provider;
+ if (input.provider) {
+ try { provider = validateModelProvider(input.provider, { previous: previous.routing }); }
+ catch (error) { check(false, 400, publicError(error)); }
+ } else if (input.providerId && !Array.isArray(input.providers) && !own(input, 'baseUrl')) {
+ provider = previous.routing.providers.find(item => item.id === input.providerId);
+ check(provider, 404, '模型服务不存在');
+ } else {
+ const { route } = await this.routeFor(input, { profileId: input.profileId, direct: true });
+ provider = route;
+ }
let response;
- try { response = await fetch(`${config.baseUrl}/models`, { redirect: 'error',
- headers: { authorization: `Bearer ${config.apiKey}` }, signal: AbortSignal.timeout(15000) }); }
- catch { check(false, 502, '无法读取模型列表'); }
+ const anthropic = provider.apiFormat === 'anthropic';
+ try {
+ response = await fetch(anthropic ? anthropicEndpoint(provider.baseUrl, 'models') : `${provider.baseUrl}/models`, {
+ redirect: 'error', headers: anthropic ? anthropicHeaders(provider.apiKey) : { authorization: `Bearer ${provider.apiKey}` },
+ signal: AbortSignal.timeout(15_000),
+ });
+ } catch { check(false, 502, '无法读取模型列表'); }
check(response.ok, 502, `Model catalog HTTP ${response.status}`);
const body = await response.json();
check(Array.isArray(body.data), 502, '模型列表格式不兼容');
- return { models: body.data.filter(item => typeof item.id === 'string').slice(0, 100).map(item => {
- const supplied = item.supported_reasoning_efforts ?? item.reasoning_effort?.values ?? item.capabilities?.reasoning_efforts;
- const levels = Array.isArray(supplied) ? supplied.filter(level => ['none','low','medium','high','xhigh','max'].includes(level)) : null;
- return { id: item.id, efforts: levels ?? effortLevels(item.id), source: levels ? 'provider' : effortLevels(item.id).length ? 'reference' : 'manual' };
+ return { models: body.data.filter(item => typeof item.id === 'string').slice(0, 200).map(item => {
+ const supplied = item.supported_reasoning_efforts ?? item.supported_efforts ?? item.reasoning_effort?.values ?? item.capabilities?.reasoning_efforts;
+ const levels = Array.isArray(supplied) ? EFFORTS.filter(level => supplied.includes(level)) : null;
+ const capacity = [item.context_window, item.max_input_tokens, item.context_length]
+ .find(value => Number.isSafeInteger(value) && value > 0 && value <= 100_000_000);
+ return { id: item.id, efforts: levels ?? effortLevels(item.id), source: levels ? 'provider' : effortLevels(item.id).length ? 'reference' : 'manual',
+ ...catalogContextPolicy(item.id, capacity) };
}) };
}
async classify(input) {
- const config = await this.validated(input);
+ const current = await this.current();
+ const base = { ...current, ...(input ?? {}) };
+ const config = await this.legacyRouting(base, current);
+ const route = modelRouteForAgent(config.routing);
check(config.jevApiKey, 400, '请填写 Jev API Key');
- const route = createModelRouter({ ...config, policy: { ...config.policy, mode: 'adaptive' }, usageDirectory: join(this.dataDir, 'usage'), routingDirectory: join(this.dataDir, 'routing'), routingSource: 'test' });
- const decision = await route({ messages: [{ role: 'user', content: clean(input.task, '任务', 10000) }] });
- const { requestOptions, ...result } = decision;
+ const policy = { ...compatibilityPolicy(route), mode: 'adaptive' };
+ const router = createModelRouter({ ...route, policy, jevApiKey: config.jevApiKey,
+ usageDirectory: join(this.dataDir, 'usage'), routingDirectory: join(this.dataDir, 'routing'), routingSource: 'test' });
+ const decision = await router({ messages: [{ role: 'user', content: clean(input.task, '任务', 10000) }] });
+ const { requestOptions, apiKey, baseUrl, ...result } = decision;
return result;
}
- async test(input) {
- const config = await this.validated(input);
- let response;
+ async test(input = {}) {
+ const { config, route } = await this.routeFor(input, { profileId: input.profileId, direct: true });
+ let usage;
+ const session = createModelSession({ ...route, policy: compatibilityPolicy(route),
+ onUsage: async value => { usage = value; }, selectRequest: async () => ({ ...route, fallbacks: [] }) });
+ const result = session.getExecutor([{ role: 'user', content: 'Reply with OK.' }])
+ .stream({ signal: AbortSignal.timeout(120_000) }, 'model-test', []);
+ let text = '';
try {
- response = await fetch(`${config.baseUrl}/chat/completions`, {
- method: "POST",
- headers: {
- "content-type": "application/json",
- authorization: `Bearer ${config.apiKey}`,
- },
- body: JSON.stringify({
- ...reasoningOptions(config.model, config.policy.effort),
- model: config.model,
- messages: [{ role: "user", content: "Reply with OK." }],
- max_tokens: 1024,
- stream: false,
- }),
- signal: AbortSignal.timeout(60_000),
- redirect: "error",
- });
- } catch {
- check(false, 502, "模型服务连接失败或超时,请检查地址与网络");
- }
- if (!response.ok) {
- await response.body?.cancel();
- check(
- false,
- 502,
- `模型服务返回 HTTP ${response.status},请检查模型名称和 API Key`,
- );
+ for await (const part of result.fullStream) if (part.type === 'text-delta') text += part.textDelta;
+ await result.response;
+ } catch (error) {
+ check(false, 502, error.name === 'TimeoutError' || error.name === 'AbortError' ? '模型服务连接超时,请检查地址与网络'
+ : error.status ? `模型服务返回 HTTP ${error.status}:${String(error.message).slice(0, 300)}`
+ : `模型请求失败:${String(error.message).slice(0, 300)}`);
+ } finally {
+ if (usage) await recordUsage(join(this.dataDir, 'usage'), { ...usage, kind: 'test' }).catch(() => {});
}
- const body = await response.json().catch(() => null);
- check(body?.choices?.length, 502, "模型服务返回的格式不兼容");
- await recordUsage(join(this.dataDir, 'usage'), { raw: body.usage, model: body.model ?? config.model, kind: 'test', requestId: body.id });
- return { ok: true, model: config.model, message: "模型接口已完成真实请求" };
+ check(text.trim(), 502, '模型没有返回文字内容');
+ return { ok: true, profileId: route.profileId, model: route.model, message: '模型接口已完成真实请求' };
}
}
diff --git a/host/server/package-lock.json b/host/server/package-lock.json
index e8e1a0eda9a8794f980262290ea790f696afb296..404ebbcc8aa878ffa3a937fc473f57acb5abb902 100644
--- a/host/server/package-lock.json
+++ b/host/server/package-lock.json
@@ -14,9 +14,9 @@
}
},
"node_modules/@hono/node-server": {
- "version": "2.1.5",
- "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.5.tgz",
- "integrity": "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==",
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.9.tgz",
+ "integrity": "sha512-Sk4NQd3GFY0WZWCzndwFMPwJhtD0y9qjsQ+pjID0/03nK9pxyBCUoUHCho8QYBLBVhi0ssL8UkNPHqbgSOFPIQ==",
"license": "MIT",
"engines": {
"node": ">=20"
@@ -151,18 +151,18 @@
}
},
"node_modules/body-parser": {
- "version": "2.3.0",
- "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
- "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz",
+ "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==",
"license": "MIT",
"dependencies": {
"bytes": "^3.1.2",
- "content-type": "^2.0.0",
+ "content-type": "^2.1.0",
"debug": "^4.4.3",
"http-errors": "^2.0.1",
- "iconv-lite": "^0.7.2",
+ "iconv-lite": "^0.7.3",
"on-finished": "^2.4.1",
- "qs": "^6.15.2",
+ "qs": "^6.16.1",
"raw-body": "^3.0.2",
"type-is": "^2.1.0"
},
@@ -717,9 +717,9 @@
}
},
"node_modules/hono": {
- "version": "4.13.13",
- "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz",
- "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==",
+ "version": "4.13.19",
+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.19.tgz",
+ "integrity": "sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA==",
"license": "MIT",
"engines": {
"node": ">=16.9.0"
diff --git a/host/server/proxy.mjs b/host/server/proxy.mjs
index c2a258192a5c506dd6ee0983b9b6b6538687f744..5a2a7a0b31a5481c2eb32e813b1f033b88299ae9 100644
--- a/host/server/proxy.mjs
+++ b/host/server/proxy.mjs
@@ -129,7 +129,7 @@ export function sseRewriter(rewrite) {
export function proxyHttp(
request,
response,
- { target, path, token, rewrite, ticketCookie },
+ { target, path, token, rewrite, ticketCookie, transformHtml },
) {
const transport = target.protocol === "https:" ? https : http;
const upstream = transport.request(target, {
@@ -152,10 +152,29 @@ export function proxyHttp(
const type = String(incoming.headers["content-type"] ?? "");
const json = rewrite && type.includes("application/json");
const sse = rewrite && type.includes("text/event-stream");
- const headers = responseHeaders(incoming.headers, json || sse);
+ // A small page whose markup changes on the way, such as the web client's computer view.
+ const html = transformHtml && incoming.statusCode === 200 && type.includes("text/html");
+ const headers = responseHeaders(incoming.headers, json || sse || html);
if (ticketCookie) headers["set-cookie"] = ticketCookie;
if (type.includes("text/event-stream")) headers["x-accel-buffering"] = "no";
- if (json) {
+ if (html) {
+ const chunks = [];
+ let size = 0;
+ incoming.on("data", (chunk) => {
+ size += chunk.length;
+ if (size > 4 * 1024 * 1024) {
+ incoming.destroy();
+ sendJson(response, 502, { error: "Host 响应内容过大" });
+ } else chunks.push(chunk);
+ });
+ incoming.on("end", () => {
+ if (response.headersSent || response.destroyed) return;
+ const body = Buffer.from(transformHtml(Buffer.concat(chunks).toString("utf8")));
+ response.writeHead(200, { ...headers, "content-length": body.length });
+ response.end(body);
+ });
+ incoming.on("error", () => sendJson(response, 502, { error: "Host 响应中断" }));
+ } else if (json) {
const chunks = [];
let size = 0;
incoming.on("data", (chunk) => {
diff --git a/host/server/public/app.js b/host/server/public/app.js
index 7fd6648b8c17cff6dc22ffb292f30ca08e6d3504..8820b94378a64316cd747de1aff7ed7ee61a5436 100644
--- a/host/server/public/app.js
+++ b/host/server/public/app.js
@@ -15,6 +15,7 @@ import { createSkillsEditor } from './skills.js';
import { createApps } from './apps.js';
import { createPromptEditor } from './prompts.js';
import { createDevices } from './devices.js';
+import { createWebClientPage } from './web-client.js';
import { createNetworkEditor } from './network.js';
import { createExecutionEditor } from './execution.js';
import { createFederationEditor } from './federation.js';
@@ -22,7 +23,10 @@ import { createWebhookEditor } from './webhooks.js';
import { createSharingEditor } from './sharing.js';
const aliases = { profile: 'general', notifications: 'devices', plugins: 'apps', connectors: 'apps' };
-let initialized = false, state = null, activeView = 'overview', poll = null, toastTimer, statusPending = false;
+const sessionPaths = new Set(['/admin/api/session', '/admin/api/login', '/admin/api/setup']);
+const expiredSession = () => new Error(t('会话已过期,请重新登录。'));
+let initialized = false, state = null, activeView = 'overview', poll = null, toastTimer;
+let consoleSession = null, statusPending = null;
function toast(message, error = false) {
clearTimeout(toastTimer);
@@ -33,19 +37,38 @@ function toast(message, error = false) {
toastTimer = setTimeout(() => { element.hidden = true; }, 5000);
}
-async function api(path, { method = 'GET', body } = {}) {
+async function api(path, { method = 'GET', body, signal = consoleSession?.signal, binary = false } = {}) {
+ const session = consoleSession;
+ const publicPath = sessionPaths.has(path);
+ if (!publicPath && !session) throw expiredSession();
if (body === undefined && !['GET', 'HEAD'].includes(method)) body = {};
- const response = await fetch(path, {
- method, credentials: 'same-origin',
- headers: { 'content-type': 'application/json', 'x-grokbot-csrf': '1' },
- ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
- });
- const value = await response.text().then(text => (text ? JSON.parse(text) : {}));
+ let response;
+ try {
+ response = await fetch(path, {
+ method, credentials: 'same-origin', signal,
+ headers: { 'content-type': 'application/json', 'x-grokbot-csrf': '1' },
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
+ });
+ } catch (error) {
+ if (signal?.aborted) throw error;
+ throw new Error(t('无法连接管理服务。'));
+ }
+ if (response.status === 401 && !publicPath) {
+ const error = expiredSession();
+ if (session === consoleSession) showAuth(error.message);
+ throw error;
+ }
if (!response.ok) {
- if (response.status === 401 && !['/admin/api/login', '/admin/api/setup'].includes(path)) showAuth();
- throw new Error(t(value.error) || t('请求失败 ({0})', response.status));
+ const value = await response.json().catch(() => null);
+ throw new Error(typeof value?.error === 'string' && value.error.trim() ? t(value.error) : t('请求失败 ({0})', response.status));
+ }
+ if (binary) return response.blob();
+ if (response.status === 204) return {};
+ try { return await response.json(); }
+ catch (error) {
+ if (signal?.aborted) throw error;
+ throw new Error(t('管理服务返回了无效响应 (HTTP {0})。', response.status));
}
- return value;
}
const act = (control, work) => busy(control, async () => {
@@ -62,6 +85,7 @@ const views = {
overview: createOverview(context), general: createGeneral(context), model: createModelPage(context),
speech: createSpeechPage(context), media: createMediaEditor(context), 'web-services': createWebServicesEditor(context),
harness: createHarnessEditor(context), skills: createSkillsEditor(context), apps: createApps(context), prompts: createPromptEditor(context), devices: createDevices(context),
+ 'web-client': createWebClientPage(context),
network: createNetworkEditor(context), execution: createExecutionEditor(context), federation: createFederationEditor(context),
webhooks: createWebhookEditor(context), sharing: createSharingEditor(context),
};
@@ -70,7 +94,9 @@ const loginStage = createLoginStage();
localize(document.body);
$('#nav-toggle').innerHTML = icon('menu');
-function showAuth() {
+function showAuth(message = '') {
+ consoleSession?.abort(); consoleSession = null;
+ statusPending?.abort(); statusPending = null;
clearInterval(poll); poll = null; state = null;
$('#console').hidden = true; $('#loading').hidden = true; $('#auth-screen').hidden = false;
$('#auth-title').textContent = initialized ? t('登录 Host') : t('设置 Host');
@@ -82,17 +108,23 @@ function showAuth() {
$('#auth-submit').setAttribute('aria-label', initialized ? t('登录') : t('创建管理员'));
$('#auth-password').value = '';
for (const view of Object.values(views)) view.reset?.();
- loginStage.show();
+ for (const dialog of all('dialog[open]')) dialog.close();
+ loginStage.show(message);
+ if (message) $('#auth-password').focus();
}
async function showConsole() {
+ const session = consoleSession = new AbortController();
loginStage.hide();
$('#auth-screen').hidden = true; $('#loading').hidden = true; $('#console').hidden = false;
$('#auth-form').reset();
+ const checking = t('正在检查');
+ setHealth(checking, ''); views.overview.statusUnavailable(checking);
await refresh(true);
+ if (session !== consoleSession) return;
showView(activeView);
clearInterval(poll);
- poll = setInterval(() => { if (!document.hidden) refresh().catch(() => {}); }, 5000);
+ poll = setInterval(() => { if (!document.hidden) refresh(); }, 5000);
}
function showView(view) {
@@ -113,23 +145,49 @@ function showView(view) {
function hostTitle() {
if (state.host.connected) return state.host.busy ? [t('任务运行中'), 'accent'] : [t('Host 就绪'), 'success'];
+ if (state.model.configured && state.host.waitingForExecutionNode) return [t('需要执行节点'), 'warn'];
return state.model.configured ? [t('等待 Host'), 'warn'] : [t('等待配置'), 'warn'];
}
+function setHealth(title, tone) {
+ $('#header-health').textContent = title;
+ $('#header-health').dataset.tone = tone;
+}
+
+function statusUnavailable(detail) {
+ state = null;
+ const title = t('状态不可用');
+ setHealth(title, 'warn'); views.overview.statusUnavailable(title, detail);
+}
+
async function refresh(showError = false) {
- if (statusPending) return;
- statusPending = true;
+ if (!consoleSession || statusPending) return;
+ // Only the current probe may update health, even if an old one finishes after re-login.
+ const request = statusPending = new AbortController();
+ const timeout = setTimeout(() => request.abort(new Error(t('读取 Host 状态超时。'))), 12_000);
try {
- state = await api('/admin/api/status');
- const [title, tone] = hostTitle();
- $('#header-health').textContent = title;
- $('#header-health').dataset.tone = tone;
+ const next = await api('/admin/api/status', { signal: request.signal });
+ if (request !== statusPending) return;
+ state = next;
+ setHealth(...hostTitle());
for (const view of Object.values(views)) view.status?.(state, view === views[activeView]);
} catch (error) {
+ if (request !== statusPending) return;
+ statusUnavailable(error.message);
if (showError) toast(error.message, true);
- } finally { statusPending = false; }
+ } finally {
+ clearTimeout(timeout);
+ if (statusPending === request) statusPending = null;
+ }
}
+addEventListener('offline', () => {
+ if (!consoleSession) return;
+ statusPending?.abort(); statusPending = null;
+ statusUnavailable(t('无法连接管理服务。'));
+});
+addEventListener('online', () => { if (!document.hidden) refresh(); });
+
$('#auth-form').addEventListener('submit', event => {
event.preventDefault();
busy($('#auth-submit'), async () => {
diff --git a/host/server/public/apps.js b/host/server/public/apps.js
index a8fd603c04ee2f069dc52aa1270813b2fcb7a8ac..f05f8dc8a47dec6d42701c9bc47bb19b4e2bd24d 100644
--- a/host/server/public/apps.js
+++ b/host/server/public/apps.js
@@ -94,7 +94,7 @@ export function createApps(context) {
run: trigger => act(trigger, () => run(app, action)) }))));
const valid = /^data:image\/(png|jpeg|webp);base64,/.test(app.iconDataUrl || '');
const meta = [app.version, Number.isInteger(app.toolCount) && t('{0} 个工具', app.toolCount), app.skills?.length && t('{0} 个技能', app.skills.length)].filter(Boolean);
- const element = item({ image: valid ? app.iconDataUrl : '', tile: icon(builtin ? 'bolt' : 'plug'), title: name, badges,
+ const element = item({ image: valid ? app.iconDataUrl : '', icon: builtin ? 'bolt' : 'plug', title: name, badges,
description: appCopy(app.description), meta: meta.length ? [meta.join(' · ')] : [], actions: controls });
element.classList.add('connector-row'); element.dataset.appId = app.id;
const content = element.querySelector('.item-copy');
diff --git a/host/server/public/devices.js b/host/server/public/devices.js
index dfa78a6876f1d5a29748528ce02b3088eb9afe73..756b89c26cf1df5cd195205fc9ace1f859814bc5 100644
--- a/host/server/public/devices.js
+++ b/host/server/public/devices.js
@@ -4,7 +4,7 @@ import { icon } from './icons.js';
import { createPushEditor } from './push.js';
import { createNotifications } from './notifications.js';
-const kinds = { iphone: 'iPhone', ipad: 'iPad', mac: 'Mac', desktop: '电脑', ios: 'iPhone / iPad' };
+const kinds = { iphone: 'iPhone', ipad: 'iPad', mac: 'Mac', windows: 'Windows', android: 'Android', web: '网页版', desktop: '电脑', ios: 'iPhone / iPad' };
const permissions = { authorized: '已允许', granted: '已允许', provisional: '临时允许', ephemeral: '临时允许', denied: '已拒绝',
notDetermined: '尚未询问', not_determined: '尚未询问', unknown: '尚未报告' };
@@ -94,7 +94,7 @@ export function createDevices(context) {
}) },
]));
}
- const row = item({ tile: icon('devices'), title: device.name, badges, meta, actions });
+ const row = item({ icon: 'devices', title: device.name, badges, meta, actions });
row.classList.add('device-row'); if (device.revokedAt) row.classList.add('revoked');
row.querySelector('.item-title span').dataset.private = '';
for (const error of [notice.lastError, notice.registrationError].filter(Boolean)) row.querySelector('.item-copy').append(node('p', 'error', error));
diff --git a/host/server/public/federation.js b/host/server/public/federation.js
index 46b617f03c319bd79b06825541b29dbfd12bc686..3b7f9538a0a6255507bcef6afe21249add9df872 100644
--- a/host/server/public/federation.js
+++ b/host/server/public/federation.js
@@ -137,7 +137,7 @@ export function createFederationEditor({ api, toast, act }) {
}) },
]);
const local = peer.allowedBots.map(id => roster.find(bot => bot.id === id)?.name ?? id);
- const row = item({ tile: icon('swap'), title: peer.name,
+ const row = item({ icon: 'swap', title: peer.name,
badges: [peer.error ? badge(t('同步失败'), 'danger') : !peer.enabled ? badge(t('已停用')) : badge(t('已连接'), 'success')],
meta: [`${t('本地 Bot')}:${local.join(' · ') || t('无')}`, `${t('对方 Bot')}:${peer.remoteBots.map(bot => bot.name).join(' · ') || t('无')}`,
peer.error || `${t('最近同步')} · ${time(peer.lastSyncAt)}`],
@@ -152,7 +152,7 @@ export function createFederationEditor({ api, toast, act }) {
const peer = config.peers.find(value => value.id === entry.peerId), outgoing = entry.direction === 'outbound';
const local = roster.find(bot => bot.id === (outgoing ? entry.fromAgentId : entry.toAgentId))?.name ?? t('本地 Bot');
const remote = peer?.remoteBots.find(bot => bot.id === (outgoing ? entry.toAgentId : entry.fromAgentId))?.name ?? t('远程 Bot');
- list.append(item({ tile: icon('swap'), title: outgoing ? `${local} → ${remote}` : `${remote} → ${local}`,
+ list.append(item({ icon: 'swap', title: outgoing ? `${local} → ${remote}` : `${remote} → ${local}`,
meta: [`${peer?.name ?? ''} · ${time(entry.createdAt)}`], actions: [badge(t(states[entry.state] ?? entry.state))] }));
}
}
diff --git a/host/server/public/icons.js b/host/server/public/icons.js
index 9b52984962bc13b389cf0542b7ba0ec676c553d1..86d64f76a808868f15e6e3505718af457812bda5 100644
--- a/host/server/public/icons.js
+++ b/host/server/public/icons.js
@@ -19,6 +19,7 @@ const paths = {
share: '',
settings: '',
plus: '',
+ archive: '',
close: '',
copy: '',
refresh: '',
@@ -36,3 +37,7 @@ export function icon(name, size = 16) {
return ``;
}
+export function isBuiltinIcon(name) {
+ return Object.hasOwn(paths, name);
+}
+
diff --git a/host/server/public/ids.js b/host/server/public/ids.js
new file mode 100644
index 0000000000000000000000000000000000000000..eb63db4e53c2f714a38e9b98bf9683c45f54089f
--- /dev/null
+++ b/host/server/public/ids.js
@@ -0,0 +1,16 @@
+// crypto.randomUUID() is secure-context only. The Host admin page also runs on LAN HTTP.
+let sequence = 0;
+
+export function clientId(prefix = 'item', cryptoImpl = globalThis.crypto) {
+ try {
+ const value = cryptoImpl?.randomUUID?.();
+ if (typeof value === 'string' && value) return `${prefix}-${value.slice(0, 8)}`;
+ } catch {}
+ try {
+ const values = new Uint32Array(2);
+ cryptoImpl?.getRandomValues?.(values);
+ if (values[0] || values[1]) return `${prefix}-${values[0].toString(36)}${values[1].toString(36)}`;
+ } catch {}
+ sequence += 1;
+ return `${prefix}-${Date.now().toString(36)}${sequence.toString(36)}`;
+}
diff --git a/host/server/public/index.html b/host/server/public/index.html
index 19f819440ba9c3a62b6e43cf2522d4524ccde527..5f49a1e8d181a910f7020c2522a3cc4ffa9d43e5 100644
--- a/host/server/public/index.html
+++ b/host/server/public/index.html
@@ -60,6 +60,7 @@
+
diff --git a/host/server/public/locales-en.js b/host/server/public/locales-en.js
index 7625a7226271d8c97f3043e40e93a56d396ed3a3..7b19840433bea4427249fe3cda90d15d7918ff20 100644
--- a/host/server/public/locales-en.js
+++ b/host/server/public/locales-en.js
@@ -1,4 +1,6 @@
export default {
+ '需要执行节点': 'Execution node required', '配置执行节点': 'Set up a node', '配置节点': 'Set up node',
+ '分机部署需要连接独立的执行电脑,Bot 才能开始聊天。': 'Connect the separate execution computer before starting a chat in a split deployment.',
'通知偏好': 'Notification preferences',
'通知频率': 'Notification frequency',
'适用于手机和 Mac;授权与提问仍会提醒。': 'Applies to mobile and Mac. Approvals and questions still notify you.',
@@ -58,7 +60,7 @@ export default {
'Agent 能力': 'Agent Capabilities',
'上下文容量': 'Context Capacity',
'摘要阈值': 'Summary Threshold',
- '支持 1M、400K。留空或 0:容量未知,摘要阈值沿用原策略。': 'Accepts 1M or 400K. Blank or 0: unknown capacity, original summary policy.',
+ '支持 1M、400K。同步后会自动填入上下文容量和摘要阈值。': 'Supports 1M and 400K. Syncing automatically fills the context capacity and summary threshold.',
'请输入 0–100M 的整数 Token 数,如 1M、400K。': 'Enter a whole token count from 0 to 100M, such as 1M or 400K.',
'摘要阈值必须小于上下文容量。': 'The summary threshold must be below the context capacity.',
'请检查上下文设置。': 'Check the context settings.',
@@ -136,6 +138,11 @@ export default {
"连接应用": "Connected Apps",
"通知中心": "Notification Center",
"请求失败 ({0})": "Request failed ({0})",
+ "会话已过期,请重新登录。": "Session expired. Sign in again.",
+ "无法连接管理服务。": "Cannot reach the admin service.",
+ "管理服务返回了无效响应 (HTTP {0})。": "Invalid response from the admin service (HTTP {0}).",
+ "状态不可用": "Status unavailable",
+ "读取 Host 状态超时。": "Host status request timed out.",
"登录管理页面": "Sign in to Admin",
"设置你的 Host": "Set Up Your Host",
"创建管理员密码": "Create Admin Password",
@@ -334,6 +341,7 @@ export default {
"困难任务": "Hard tasks",
"模型默认": "Model default",
"Jev 决定": "Jev decides",
+ "极低": "Minimal",
"轻度": "Light",
"中度": "Moderate",
"高度": "High",
@@ -382,6 +390,9 @@ export default {
"正在读取用户资料…": "Loading user profile…",
"模型服务": "Model service",
"获取模型": "Fetch models",
+ "同步模型": "Sync models",
+ "从同步列表选择模型": "Select a synced model",
+ "已同步 {0} 个模型": "Synced {0} models",
"默认模型": "Default model",
"智能路由": "Smart routing",
"Jev 分类器": "Jev classifier",
@@ -556,6 +567,10 @@ export default {
"还没有模型": "No models yet",
"添加模型后选择默认模型。": "Add models, then choose the defaults.",
"兼容 OpenAI 的接口地址": "OpenAI-compatible endpoint",
+ "接口格式": "API format",
+ "OpenAI 兼容或 Anthropic Messages": "OpenAI-compatible or Anthropic Messages",
+ "与服务商提供的接口一致": "Match the API your provider offers",
+ "模型服务的接口地址": "Model service endpoint",
"按任务难度选择模型和思考强度": "Chooses the model and effort by task difficulty",
"保存后启动 Host": "Save to start the Host",
"配置应用失败,请检查 Host 日志": "Could not apply the configuration. Check the Host logs.",
@@ -667,8 +682,8 @@ export default {
"签名密钥只显示这一次,请立即保存。": "The signing key is shown only once. Save it now.",
"选择文件": "Choose file",
"Host 就绪": "Host ready",
- "还没有对话模型": "No chat model yet",
- "填写兼容 OpenAI 的接口后,Host 才会启动。": "The Host starts once an OpenAI-compatible endpoint is set.",
+ "还没有对话模型": "No model configured yet",
+ "配置 OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages 接口后,Host 才会启动。": "Set up an OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages endpoint to start the Host.",
"配置模型": "Set up model",
"还没有配对设备": "No paired devices yet",
"用配对码连接电脑或手机客户端。": "Connect a desktop or phone client with a pairing code.",
@@ -679,9 +694,135 @@ export default {
"初始化密钥,见数据目录中的 setup-key 文件": "Setup key from the setup-key file in the data directory",
"正在工作": "Working",
"今天 {0} Token,{1} 次请求": "{0} tokens, {1} requests today",
- "配置对话模型": "Set up a chat model",
+ "配置对话模型": "Set up a model",
"后启动 Host": "to start the Host",
"启动": "to start",
"{0} 个 Bot": "{0} Bots",
"{0} 个 Bot 待命": "{0} Bots standing by",
+ "对话模型": "Chat model",
+ "模型档案": "Model profiles",
+ "Bot 路由": "Bot routes",
+ "模型路由记录": "Model routing log",
+ "刷新 Bot": "Refresh Bots",
+ "当前是旧版单模型配置。保存后会转成服务和档案的格式,模型、API Key 和思考强度不变。": "This Host still uses the legacy single-model configuration. Saving converts it to services and profiles; the model, API key and thinking effort stay the same.",
+ "检测到旧版模型配置。请在模型页确认迁移后再保存。": "Legacy model configuration detected. Confirm the migration on the model page, then save.",
+ "当前仍使用旧版按任务难度路由(Jev)。保存后会迁移为按 Bot 路由,并移除智能路由界面;如需保留旧配置,请不要保存。": "This Host still uses legacy task-difficulty routing (Jev). Saving migrates it to per-Bot routing and removes the smart-routing interface. Do not save if you need to keep the legacy configuration.",
+ "迁移旧版模型路由?": "Migrate the legacy model routing?",
+ "保存后会改为按 Bot 选择模型,旧版按任务难度路由和 Jev 选择将不再生效。": "Saving switches to per-Bot model selection. Legacy task-difficulty routing and Jev selection will stop applying.",
+ "迁移并保存": "Migrate and save",
+ "默认服务": "Default service",
+ "添加模型服务": "Add model service",
+ "添加模型档案": "Add model profile",
+ "编辑模型服务": "Edit model service",
+ "编辑模型档案": "Edit model profile",
+ "{0} 个模型档案": "{0} model profiles",
+ "还没有模型服务": "No model services yet",
+ "还没有模型档案": "No model profiles yet",
+ "尚未创建模型档案": "No model profiles yet",
+ "添加一个模型服务后,再创建模型档案。": "Add a model service, then create a model profile.",
+ "每个档案绑定一个服务、模型和可用思考强度。": "Each profile binds a service, model, and available reasoning efforts.",
+ "可用思考强度": "Available reasoning efforts",
+ "仅模型默认": "Model default only",
+ "上下文 {0} · 摘要 {1}": "Context {0} · summary {1}",
+ "默认路由": "Default route",
+ "还没有可路由的模型": "No routable models yet",
+ "添加模型档案后,设置所有 Bot 的默认模型。": "After adding a model profile, choose the default model for all Bots.",
+ "主模型": "Primary model",
+ "备用模型": "Backup model",
+ "备用模型 {0}": "Backup model {0}",
+ "添加备用模型": "Add backup model",
+ "移除备用模型": "Remove backup model",
+ "仅在主模型未输出任何内容时,才会按顺序尝试备用模型。": "Backups are tried in order only when the primary model has not produced any output.",
+ "先设置默认路由": "Set a default route first",
+ "模型档案准备好后,才可为单个 Bot 覆盖路由。": "Once model profiles are ready, individual Bots can override the route.",
+ "Host 未连接或尚无 Bot": "Host is not connected or has no Bots yet",
+ "Host 连接后会在这里显示可覆盖的 Bot。": "Bots that can override the route appear here after the Host connects.",
+ "编辑 Bot 路由": "Edit Bot route",
+ "压缩上下文": "Summarize context",
+ "压缩“{0}”的上下文?": "Summarize the context for \"{0}\"?",
+ "将使用此 Bot 当前路由的模型生成摘要。原始对话会保留,并会消耗模型 Token。": "Uses this Bot's current route to generate a summary. The original conversation is retained and model tokens are used.",
+ "开始压缩": "Summarize now",
+ "上下文已压缩": "Context summarized",
+ "Bot 正在运行,请在任务结束后再压缩": "Bot is running. Wait for the task to finish before summarizing.",
+ "暂不支持压缩群组 Bot": "Group Bot summarization is not supported yet.",
+ "当前 Host 版本不支持手动压缩": "This Host version does not support manual summarization.",
+ "上下文压缩被中断,请稍后重试": "Context summarization was interrupted. Try again shortly.",
+ "使用默认": "Use default",
+ "使用默认路由": "Use default route",
+ "已覆盖": "Overridden",
+ "当前 Host 未报告此 Bot;保存时会保留其路由。": "The current Host did not report this Bot; its route will be retained when saved.",
+ "已配置": "Configured",
+ "缺少 API Key": "API key missing",
+ "请先添加模型服务。": "Add a model service first.",
+ "请先添加模型档案。": "Add a model profile first.",
+ "请设置默认路由。": "Set a default route.",
+ "请填写“{0}”的 API Key。": "Enter the API key for \"{0}\".",
+ "请先选择模型服务。": "Choose a model service first.",
+ "请先移除或改用引用此服务的模型档案。": "Remove or reassign the model profiles that use this service first.",
+ "请先从 {0} 移除此档案。": "Remove this profile from {0} first.",
+ "失败类别": "Failure class",
+ "会话": "Session",
+ "暂无路由记录": "No routing records yet",
+ "模型回退": "Model fallback",
+ "没有可用备用模型": "No usable backup model",
+ "未选择": "not selected",
+ "跳过同 API Key 的模型": "Skipped models with the same API key",
+ "网页版": "Web client",
+ "在此浏览器打开": "Open in this browser",
+ "访问": "Access",
+ "启用网页版": "Enable the web client",
+ "在任何设备的浏览器里使用 Bot,不用安装客户端;只能使用 Host 上的 Bot 电脑": "Use your Bots from a browser on any device without installing a client; only the Bot computer on the Host is available",
+ "界面包": "Interface bundle",
+ "未上传": "Not uploaded",
+ "网页地址": "Web address",
+ "在其他设备打开,输入「设备与通知」里创建的配对码登录": "Open it on another device and sign in with a pairing code from Devices & Notifications",
+ "复制网页地址": "Copy web address",
+ "当前 Host 地址是 http。网页版可以使用,但语音输入、麦克风和浏览器通知需要 https;在公网使用时请配置 https。": "This Host address uses http. The web client works, but dictation, the microphone and browser notifications need https; set up https before using it over the internet.",
+ "上传界面包": "Upload a bundle",
+ "在电脑上运行 node web/patchers/patch.mjs,生成 web/output/GrokBotLocal-web-1.1.0.zip 后上传。界面取自你自己下载的官方 Windows 安装包,只保存在这台 Host 上,未登录的访问者拿不到。": "Run node web/patchers/patch.mjs on a computer, then upload the resulting web/output/GrokBotLocal-web-1.1.0.zip. The interface comes from your own download of the official Windows installer, stays on this Host and is never served to visitors who have not signed in.",
+ "选择文件并上传": "Choose a file and upload",
+ "删除界面包": "Delete the bundle",
+ "网页版随之停用;已登录的浏览器仍列在「设备与通知」里,可在那里撤销": "The web client stops; signed-in browsers stay under Devices & Notifications, where you can revoke them",
+ "界面 {0} · {1} 个文件 · {2} MB · 上传于 {3}": "Interface {0} · {1} files · {2} MB · uploaded {3}",
+ "正在上传 {0}%": "Uploading {0}%",
+ "网页版界面包已安装": "Web client bundle installed",
+ "网页版已启用": "Web client enabled",
+ "网页版已停用": "Web client disabled",
+ "删除网页版界面包?": "Delete the web client bundle?",
+ "网页版会停用。之后要使用,需要重新上传界面包。": "The web client will stop. To use it again, upload a bundle again.",
+ "网页版界面包已删除": "Web client bundle deleted",
+ "浏览器": "Browser",
+ "登录网页版": "Sign in to the web client",
+ "在 Host 管理页「设备与通知」创建 6 位配对码,输入后即可在这个浏览器里使用你的 Bot。": "Create a six-character pairing code under Devices & Notifications on the Host admin page, then enter it to use your Bots in this browser.",
+ "6 位配对码": "Six-character pairing code",
+ "进入网页版": "Open the web client",
+ "这个地址没有加密(http)。网页版可以用,但语音输入、麦克风和浏览器通知需要 https 地址;在公网使用时请配置 https。": "This address is not encrypted (http). The web client works, but dictation, the microphone and browser notifications need an https address; set up https before using it over the internet.",
+ "请输入 6 位配对码。": "Enter the six-character pairing code.",
+ "已登录": "Signed in",
+ "这个浏览器已登录为“{0}”。": "This browser is signed in as “{0}”.",
+ "网页版还没有启用。请管理员在 Host 管理页「网页版」上传界面包并启用。": "The web client is not enabled yet. On the Host admin page, open Web client, upload a bundle and enable it.",
+ "登录已失效,请输入新的配对码。": "Your sign-in has expired. Enter a new pairing code.",
+ "无法连接 Host:{0}": "Cannot reach the Host: {0}",
+ "设备名称需要 1–80 个字符": "Device names need 1–80 characters",
+ "网页版未启用": "The web client is not enabled",
+ "请从网页版登录页操作": "Use the web client sign-in page",
+ "请从网页版发起请求": "Send this request from the web client",
+ "请先登录网页版": "Sign in to the web client first",
+ "请先上传并启用网页版": "Upload and enable the web client first",
+ "请先上传网页版界面包": "Upload a web client bundle first",
+ "请上传 ZIP 格式的网页版界面包": "Upload the web client bundle as a ZIP file",
+ "网页版界面包过大": "The web client bundle is too large",
+ "网页版界面包大小无效": "The web client bundle has an invalid size",
+ "不是网页版界面包(ZIP 目录无效)": "Not a web client bundle (invalid ZIP directory)",
+ "网页版界面包目录无效": "The web client bundle has an invalid directory",
+ "网页版界面包条目无效": "The web client bundle has an invalid entry",
+ "网页版界面包含不支持的条目": "The web client bundle has an unsupported entry",
+ "网页版界面包条目位置无效": "The web client bundle has an entry at an invalid position",
+ "缺少 web-bundle.json,请用 web/patchers/patch.mjs 生成网页版界面包": "web-bundle.json is missing; build the bundle with web/patchers/patch.mjs",
+ "web-bundle.json 格式错误": "web-bundle.json is malformed",
+ "网页版界面包格式不受支持,请用同一版本的工具重新生成": "Unsupported bundle format; build it again with the tools from the same release",
+ "网页版界面包的版本无效": "The web client bundle has an invalid version",
+ "web-bundle.json 缺少文件清单": "web-bundle.json has no file list",
+ "网页版界面包的文件与清单不一致": "The files of the web client bundle do not match its list",
+ "启用状态无效": "Invalid enabled state",
};
diff --git a/host/server/public/login.js b/host/server/public/login.js
index 027742977bd5b9f144afd6c0109ac9e70e5d7d7f..2cc6c973dd2212721f8688d380288f4ceb0cb4ef 100644
--- a/host/server/public/login.js
+++ b/host/server/public/login.js
@@ -32,7 +32,7 @@ export function createLoginStage() {
for (const type of ['focus', 'blur', 'input']) password.addEventListener(type, follow);
password.addEventListener('input', () => { if (!message.hidden) say(); });
return {
- show() { say(); stopBlink(); stopBlink = blink(() => [face]); follow(); },
+ show(message) { say(message); stopBlink(); stopBlink = blink(() => [face]); follow(); },
hide() { stopBlink(); },
thinking() { form.classList.add('pending'); state('up'); },
async error(text) {
diff --git a/host/server/public/media-editor-ui.js b/host/server/public/media-editor-ui.js
index 799844c2ca0c067f51822096643b1727a03e2989..41f3ea8ab8ecec7b53943319fe74abcef35b66fc 100644
--- a/host/server/public/media-editor-ui.js
+++ b/host/server/public/media-editor-ui.js
@@ -1,5 +1,6 @@
import { t } from './i18n.js';
import { node, iconButton, item, toggle, menu, confirmAction } from './ui.js';
+import { clientId } from './ids.js';
// Shared building blocks for the media and web tool pages: provider lists, editor dialogs and form fields.
export const labels = { image: '图片生成', video: '视频生成', watchVideo: '视频理解', videoReview: '视频审核' };
@@ -55,7 +56,7 @@ export function sectionHead(title, addLabel, onAdd) {
export const modelOptions = (config, kind) => [['', t('停用')], ...config.models.filter(entry => entry.kind === kind && entry.enabled
&& config.providers.find(provider => provider.id === entry.providerId)?.enabled).map(entry => [entry.id, entry.name])];
-export const uid = () => `service-${crypto.randomUUID().slice(0, 8)}`;
+export const uid = () => clientId('service');
export function providerDialog(panel, { adapters, save, act }) {
const { dialog, form, body, submit } = modal(panel, '供应商');
diff --git a/host/server/public/model.js b/host/server/public/model.js
index d4729c8c658a6a12ace23dcb53fbcb4153ca312a..dab074251967275b1bdbf4cbf63ea766fd7b3444 100644
--- a/host/server/public/model.js
+++ b/host/server/public/model.js
@@ -1,236 +1,466 @@
import { t, html } from './i18n.js';
-import { $, node } from './ui.js';
-import { icon } from './icons.js';
+import { $, node, item, badge, empty, iconButton, menu, confirmAction } from './ui.js';
import { createRoutingLog } from './routing-log.js';
+import { clientId } from './ids.js';
-const tiers = [['routine', '一般任务'], ['reasoning', '中等任务'], ['expert', '困难任务']];
-const levels = ['none', 'low', 'medium', 'high', 'xhigh', 'max'];
-const levelLabels = { default: '模型默认', auto: 'Jev 决定', none: '无', low: '轻度', medium: '中度', high: '高度', xhigh: '超高', max: '最高' };
-const choices = (select, values, chosen) => {
+const formats = [
+ ['openai', 'OpenAI Chat Completions'],
+ ['openai-responses', 'OpenAI Responses'],
+ ['anthropic', 'Anthropic Messages'],
+];
+const levels = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
+const levelLabels = { default: '模型默认', none: '无', minimal: '极低', low: '轻度', medium: '中度', high: '高度', xhigh: '超高', max: '最高' };
+const defaultUrls = { openai: 'https://api.openai.com/v1', 'openai-responses': 'https://api.openai.com/v1', anthropic: 'https://api.anthropic.com' };
+const defaultContextWindowTokens = 0, defaultSummaryThresholdTokens = 0;
+
+const clone = value => structuredClone(value);
+const uid = prefix => clientId(prefix);
+const choice = (select, values, selected) => {
select.replaceChildren(...values.map(([value, label]) => new Option(t(label), value)));
- select.value = values.some(([value]) => value === chosen) ? chosen : values[0]?.[0] ?? '';
+ select.value = values.some(([value]) => value === selected) ? selected : values[0]?.[0] ?? '';
};
-const row = (title, hint, control) => ``;
-
-function parseTokenCount(text) {
- if (!text.trim()) return 0;
- const match = text.trim().match(/^(\d+(?:\.\d*)?|\.\d+)\s*([km]?)$/i);
+const parseTokenCount = value => {
+ const source = String(value ?? '').trim();
+ if (!source) return 0;
+ const match = source.match(/^(\d+(?:\.\d*)?|\.\d+)\s*([km]?)$/i);
if (!match) return NaN;
const precision = { '': 0, k: 3, m: 6 }[match[2].toLowerCase()];
const [whole, decimals = ''] = match[1].split('.');
const fraction = decimals.replace(/0+$/, '');
if (fraction.length > precision) return NaN;
- const value = Number((whole || '0') + fraction.padEnd(precision, '0'));
- return Number.isSafeInteger(value) && value <= 100_000_000 ? value : NaN;
-}
-
-function formatTokenCount(value) {
+ const number = Number((whole || '0') + fraction.padEnd(precision, '0'));
+ return Number.isSafeInteger(number) && number <= 100_000_000 ? number : NaN;
+};
+const formatTokenCount = value => {
if (!value) return '';
if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(6).replace(/\.?0+$/, '')}M`;
if (value >= 1_000) return `${(value / 1_000).toFixed(3).replace(/\.?0+$/, '')}K`;
return String(value);
+};
+const emptyRouting = () => ({ version: 1, providers: [], profiles: [], defaultRoute: null, botRoutes: {} });
+
+function editor(panel, id) {
+ const dialog = node('dialog', 'dialog wide');
+ dialog.id = id;
+ const form = document.createElement('form');
+ const head = node('div', 'dialog-head'), title = node('h2'), body = node('div', 'dialog-body'), foot = node('div', 'dialog-foot');
+ const cancel = node('button', 'btn', t('取消')); cancel.type = 'button'; cancel.onclick = () => dialog.close();
+ const submit = node('button', 'btn btn-primary', t('保存')); submit.type = 'submit';
+ head.append(title, iconButton('close', t('关闭'), () => dialog.close()));
+ foot.append(cancel, submit); form.append(head, body, foot); dialog.append(form); panel.append(dialog);
+ return { dialog, form, title, body, submit };
+}
+
+function formField(parent, name, label, type = 'text') {
+ const field = node('label', 'field', t(label));
+ const input = document.createElement(type === 'textarea' ? 'textarea' : 'input');
+ if (type !== 'textarea') input.type = type;
+ input.name = name;
+ if (type === 'password') { input.autocomplete = 'new-password'; input.dataset.private = ''; }
+ if (type === 'url') { input.spellcheck = false; input.dataset.private = ''; }
+ field.append(input); parent.append(field);
+ return input;
+}
+
+function formSelect(parent, name, label) {
+ const field = node('label', 'field', t(label)), select = document.createElement('select');
+ select.name = name; field.append(select); parent.append(field); return select;
}
export function createModelPage({ api, toast, busy, refresh }) {
const panel = $('[data-panel=model]');
panel.innerHTML = html(`
对话模型
-
-
分类记录
-
- `);
- const form = $('#model-form'), routingLog = createRoutingLog({ api });
- let models = [], policy, loaded = false, active = false;
+