Go implementation of DeepSeek Harness and self-hosted personal agent.
Go
feat: add plugin ecosystem and expand agent integrations
xycb9c10700a416
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1875c11..b5c5ea6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -24,6 +24,24 @@ jobs:go-version: '1.26.x'cache: true+ - uses: actions/setup-node@v4+ with:+ node-version: '24.22.3'+ cache: npm+ cache-dependency-path: |+ frontend/package-lock.json+ mobile/package-lock.json+ - name: Prepare the Cordis runtime and plugin SDK+ run: |+ npm install --global --ignore-scripts --no-audit --no-fund [email protected]+ pnpm --dir extensions/cordis install --frozen-lockfile --ignore-scripts+ pnpm --dir extensions/sdk install --frozen-lockfile --ignore-scripts+ npm --prefix extensions/plugins/x ci --ignore-scripts --no-audit --no-fund+ - name: Test the Cordis runtime and plugin SDK+ run: |+ pnpm --dir extensions/cordis test+ pnpm --dir extensions/sdk test+- name: Check Go formattingrun: |unformatted="$(git ls-files -z '*.go' | xargs -0 gofmt -l)"@@ -37,13 +55,6 @@ jobs:if: github.event_name == 'workflow_dispatch'run: make race- - uses: actions/setup-node@v4- with:- node-version: '22'- cache: npm- cache-dependency-path: |- frontend/package-lock.json- mobile/package-lock.json- name: Build and test Webrun: |make build-webdiff --git a/.gitignore b/.gitignoreindex 75796b7..642dd51 100644--- a/.gitignore+++ b/.gitignore@@ -26,6 +26,8 @@ __pycache__/controller.lockstate.json*.token+.credentials.yaml+.credential-write-*.write-*# Private cloud deployment and replay notesdiff --git a/Makefile b/Makefileindex bb41b32..eac4cb5 100644--- a/Makefile+++ b/Makefile@@ -16,7 +16,7 @@ image:test:go test ./...race:- go test -race ./harness/agent ./harness/session ./harness/schedule ./internal/hostruntime ./internal/controller ./internal/config+ go test -race ./harness/agent ./harness/session ./harness/schedule ./internal/hostruntime ./internal/controller ./internal/config ./internal/plugins ./internal/mcpclient ./internal/credentials ./internal/authorizationvet:go vet ./...run:diff --git a/README.md b/README.mdindex 0e4290b..fdf8536 100644--- a/README.md+++ b/README.md@@ -133,13 +133,15 @@ Open the browser after startup. Controller already serves the web app.1. Open [http://127.0.0.1:8080](http://127.0.0.1:8080) and create an account byname. Opening the account starts its Host in a separate Docker container.-2. In **Model settings**, add an OpenAI-compatible Responses endpoint, API key,+2. In **Model settings**, choose **OpenAI Responses** or **Anthropic Messages** in the protocol dropdown, then add the endpoint URL, API key,and at least one model ID. Then select **New chat** and send a message.-3. For web search, save a key for DeepSeek, Zhipu, or Doubao under **Settings → Web search**. For image generation, configure Seedream, OpenAI Images, or Google Nano Banana under **Settings → Image generation**. Choose **Use provider** to activate a saved service. [Provider setup](docs/providers.md)+3. For web search, save a key for DeepSeek, Zhipu, Doubao, Tavily, or Brave Search under **Settings → Web search**. For image generation, configure Seedream, OpenAI Images, or Google Nano Banana under **Settings → Image generation**. Choose **Use provider** to activate a saved service. [Provider setup](docs/providers.md)Choose **English** or **简体中文** on the account page or in **Settings**. The browser remembers your choice.-### Phone via Tailscale+Install and enable **agent-browser** and **OfficeCLI** from the sidebar **Plugins** entry to use browser and Office tasks. First installation downloads their official CLI dependencies.++## Phone via TailscaleTailscale connects your phone and the computerrunning Controller over a private network called a tailnet. This gives the phone@@ -173,11 +175,15 @@ the Go agent, calls model providers directly, and manages tools, v4 sessionjournals, memory, schedules, attachments, and the workspace. Each account hasits own Host, started when the account is opened.-The Host includes OfficeCLI, agent-browser with Chromium, Python and Node.js.-The OfficeCLI and agent-browser skills are installed into-`/root/harness/.dsh/skills/` on first use of each data directory. They can be-edited or deleted like any other skill. The model discovers skills by their-names and descriptions and loads their instructions on demand.+The Host includes Chromium, Python, Node.js and the general document environment.+Install **agent-browser** and **OfficeCLI** from **Plugins → Plugin market**, then+enable them. Installation prepares the fixed official CLI and its original+Skills; activation only loads those capabilities. No API key is needed.+OfficeCLI contributes 11 original Skills; agent-browser contributes its official+discovery Skill. They remain in their plugin packages under+`/root/harness/.dsh/plugins/profile/node_modules/`, rather than being copied into+user Skill directories. Disabling withdraws the Skills and retains installed CLI+software. The model discovers Skill names/descriptions and loads instructions on demand.| Runtime | Where Host data lives | What **Stop Host** does || --- | --- | --- |@@ -285,7 +291,7 @@ creation, storage and Controller-to-Host connectivity.| Develop outside Docker | Go 1.26 or newer for the backend, a Redis instance for a native Controller, and Node.js 22.12+ with npm for frontend development. |Compose runs Redis and builds the frontend. Python, Node.js, Chromium and-OfficeCLI for agent tasks are included in the Host image.+the general document environment are included in the Host image. Install OfficeCLI and agent-browser through the plugin market.## Develop and extend@@ -299,6 +305,7 @@ credentials and bind access to the authenticated account.- **Add a Skill** with a `SKILL.md` file to describe a repeatable workflow that uses existing tools. Put account-level skills under `/root/harness/.dsh/skills/` on the Host.- **Add tools and selected third-party services** in a custom Host build. Implement the Go tool contract and include the tool in the Host's tool set. Keep external SDK and HTTP calls in `thirdparty/`, and use `providers/` for adapters to the runtime, model, search, or image provider contracts. [Tool interface](harness/agent/native_contract.go) · [Host tool assembly](harness/assembly/native_runtime.go) · [Provider guide](docs/providers.md)+- **Add business plugins** with native Cordis and asynchronous `ctx.host` APIs for tools, Skills, prompts, credentials, authorization and MCP. The Harness core stays in Go. [Plugin SDK](extensions/sdk/README.md) · [Examples](examples/plugins/README.md)- **Build the product interface** on HTTP and SSE. Connect your own chat frontend or messaging channel and handle account authentication, connection permissions, and user approval for actions such as booking or payment. [API guide](docs/api.md) · [Personal-agent integration research](docs/personal-agent-research.zh-CN.md)[Documentation](docs/README.md) · [Contributing](CONTRIBUTING.md) · [Security policy](SECURITY.md) · [MIT License](LICENSE) · [Third-party notices](THIRD_PARTY_NOTICES.md)diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 708891c..0c7c4b7 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -130,12 +130,14 @@ go-bot 是用 Go 实现的 DeepSeek Harness,也是一款可自托管的 Person1. 打开 [http://127.0.0.1:8080](http://127.0.0.1:8080),输入账号名创建账号。打开账号时,Controller 会启动独立的 Docker Host 容器。-2. 在 **Model settings** 添加 OpenAI 兼容的 Responses 端点、API Key 和至少一个模型 ID,+2. 在 **Model settings** 通过协议下拉框选择 **OpenAI Responses** 或 **Anthropic Messages**,填写端点地址、API Key 和至少一个模型 ID,然后点击 **New chat** 发消息。-3. 在 **Settings → Web search** 可配置 DeepSeek、智谱或豆包搜索。在 **Settings → Image generation** 可配置 Seedream、OpenAI Images 或 Google Nano Banana。保存凭证后点击 **Use provider** 选用。 [供应商配置](docs/providers.md)+3. 在 **Settings → Web search** 可配置 DeepSeek、智谱、豆包、Tavily 或 Brave Search。在 **Settings → Image generation** 可配置 Seedream、OpenAI Images 或 Google Nano Banana。保存凭证后点击 **Use provider** 选用。 [供应商配置](docs/providers.md)可在账号页或「设置」选择简体中文或 English。浏览器会记住语言偏好。+需要浏览器和 Office 能力时,从侧栏「插件市场」安装并启用 **agent-browser** 和 **OfficeCLI**;安装会准备官方 CLI 和原始 Skills。+### 手机通过 Tailscale 连接Tailscale 会让手机和运行 Controller 的电脑加入同一个私有网络@@ -167,9 +169,12 @@ Tailscale 会让手机和运行 Controller 的电脑加入同一个私有网络Host 状态。**Host** 运行 Go Agent 并直接访问模型服务,管理工具、v4 会话日志、记忆、定时任务、附件和工作区。每个账号有自己的 Host,打开账号时按需启动。-Host 预装 OfficeCLI、agent-browser、Chromium、Python 和 Node.js。首次使用某个数据目录时,-Host 将 OfficeCLI 和 agent-browser 的 Skill 安装到 `/root/harness/.dsh/skills/`,-之后可以像普通 Skill 一样修改或删除。模型先看到 Skill 名称和简介,选中后再加载正文。+Host 预装 Chromium、Python、Node.js 与通用文档处理环境。+在「插件市场」安装 **agent-browser** 和 **OfficeCLI** 后启用即可使用,无需 API Key。+安装时准备固定版本的官方 CLI 和原始 Skills,启用只加载能力。+OfficeCLI 提供 11 个原始 Skills,agent-browser 提供官方发现 Skill;资源保存在+`/root/harness/.dsh/plugins/profile/node_modules/` 的对应包内,不再复制到用户 Skill 目录。+停用会撤销 Skills,保留已安装的 CLI。模型先看到名称和摘要,再按需加载正文。| 运行模式 | Host 数据存在哪里 | 点击 **Stop Host** 后 || --- | --- | --- |@@ -264,10 +269,12 @@ go run ./cmd/controller doctor --env-file .env.eci| 用 `buildeci.sh` 制作 ECI 缓存 | Go 1.26 或更高版本、Bash。使用 `prepare` 构建和推送镜像时还需要带 Buildx 的 Docker。 || 在 Docker 外开发 | 后端需要 Go 1.26 或更高版本,原生 Controller 需要 Redis,前端开发需要 Node.js 22.12+ 和 npm。 |-Compose 负责启动 Redis 并构建前端。Agent 使用的 Python、Node.js、Chromium 和 OfficeCLI 已包含在 Host 镜像中。+Compose 负责启动 Redis 并构建前端。Agent 使用的 Python、Node.js、Chromium 和通用文档环境已包含在 Host 镜像中;OfficeCLI 与 agent-browser 从插件市场安装。## 开发与扩展+业务插件使用原生 Cordis 和异步 `ctx.host` 接口,可贡献工具、Skills、附加提示及接入凭证、授权和 MCP;Harness 核心仍由 Go 内置实现。[插件 SDK](extensions/sdk/README.md) · [示例](examples/plugins/README.md)+可以用 Host 已有工具组合工作流,也可以接入第三方服务。例如,旅行助手可以查询火车票和机票、对比酒店价格及取消条款,再整理成行程。若要实现预订,可接入供应商 API,并在下单前单独展示日期、总价和取消条款,让用户确认。接入方自行提供服务凭证,并将连接权限绑定到已认证的账号。diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 0b4cacd..577b6e8 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -18,6 +18,22 @@ The embedded renderer includes Turndown 7.2.4, Joplin Turndown GFM 1.0.67and Domino 2.2.0. The original notices are in [build/web-markdown/NOTICES](build/web-markdown/NOTICES).The build recipe and package integrity hashes are tracked with the source.+The optional plugin process uses DeepSeek's MIT-licensed Cordis 4.1.0 and+Cordis Loader 1.1.0 for native dependency injection and plugin lifetimes. Go+implements the Harness core, tool stages, credentials, authorization and MCP;+the Node process only runs business plugin callbacks through the Host Bridge.+There is no runtime dependency on upstream Harness core service packages or a+second Node Agent/Session implementation. Exact dependencies, integrity hashes+and transitive license notices are retained in `extensions/cordis/pnpm-lock.yaml`+and the installed dependency tree in the Host image.++The local TypeScript SDK defines this project's asynchronous `ctx.host` contract.+Its compiler/type dependencies are locked in `extensions/sdk/pnpm-lock.yaml`.+TypeScript 7.0.2 is Apache-2.0; Node type declarations retain their MIT notice.+Go credential/authorization behavior and the internal tool phase audit reference+upstream commit ca33fd6843b205e279c7ccb6cb73a472c78f5760. Preserve the following+MIT notice with upstream-derived source and fixtures.+MIT LicenseCopyright (c) 2026 DeepSeek@@ -43,8 +59,11 @@ SOFTWARE.## OfficeCLI and image componentsOfficial OfficeCLI: https://github.com/iOfficeAI/OfficeCLI (Apache-2.0).-The build downloads official release assets; version and SHA256 checksums are in-`build/dependencies.lock.yaml` and `build/officecli.sha256`. The image includes official skill bundles and their resources generated by the verified release binary.+The OfficeCLI plugin uses the official `npm install -g @officecli/officecli`.+It does not add a CLI version/checksum lock or disable upstream updates. Original+Skills and resources are exported by the official installer in a disposable build+stage and supplied unchanged with the wrapper. The upstream license ships at+`/usr/share/go-bot/plugins/officecli/UPSTREAM_LICENSE`.Debian packages, Chromium, LibreOffice, fonts, Python/Node runtimes and installedlanguage libraries retain their respective upstream licenses in the image's@@ -59,7 +78,34 @@ The Web Controller serves bundled JavaScript dependency notices at`/assets/licenses.txt`. Vite generates the file from the installed packages,including the ISC notice for Lucide icons.-The Host includes the official Vercel agent-browser CLI and skill files from+The agent-browser plugin installs the official CLI and contributes original Skill files fromhttps://github.com/vercel-labs/agent-browser (Apache-2.0). The image includes-the upstream license at `/usr/share/doc/go-bot/agent-browser-LICENSE`.+the upstream license at `/usr/share/go-bot/plugins/agent-browser/UPSTREAM_LICENSE`.The npm release and Skill source revision are recorded in `build/dependencies.lock.yaml`.++The plugin market uses the full-color Chrome mark from gilbarbara/logos at+commit d6960edc1b73 (CC0) for agent-browser, as configured in its plugin.json.+OfficeCLI uses the original iOfficeAI repository-owner avatar+(https://avatars.githubusercontent.com/u/145246968?v=4). Product names and+logos belong to their respective owners; these images identify integrations.+The image resources ship in the plugin packages under assets/ and are served by+the Controller at the image paths declared in plugin.json. Clients render those+URLs without bundled per-plugin icon mappings.++## X / xurl++The X plugin installs [xdevplatform/xurl](https://github.com/xdevplatform/xurl)+through its official npm package under MIT; its license is bundled with the+wrapper. The X App icon is from X's official App icon resource at+https://abs.twimg.com/responsive-web/client-web/icon-ios.77d25eba.png.+X trademarks remain owned by X Corp.++## Google Workspace CLI++The Google Workspace plugin installs [googleworkspace/cli](https://github.com/googleworkspace/cli)+through its official npm package. Original Skills/resources and the upstream+Apache-2.0 license are bundled. Its icon is the official `googleworkspace`+GitHub organization avatar, obtained from+<https://avatars.githubusercontent.com/u/3708359?v=4>.+Google names and marks belong to their owners. This CLI is not an officially+supported Google product.diff --git a/api/openapi.yaml b/api/openapi.yamlindex a34b42a..e6cf92f 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -7,6 +7,456 @@ info:servers:- url: http://127.0.0.1:8080paths:+ /assets/plugins/{pluginId}/{file}:+ get:+ summary: Read a catalog plugin image declared in plugin.json+ parameters:+ - {name: pluginId, in: path, required: true, schema: {type: string}}+ - {name: file, in: path, required: true, schema: {type: string}}+ responses:+ '200':+ description: Public plugin image; no running Host is required+ content:+ image/png:+ schema: {type: string, format: binary}+ '404': {description: Image not found}+ /v1/host/extensions/authorization:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ get:+ tags: [Extensions]+ summary: List plugin authorization flows without other clients' interaction details+ operationId: listPluginAuthorization+ responses:+ '200':+ description: Registered methods, in-flight state and account configuration reported by the native integration or Go credential store+ content:+ application/json:+ schema: {type: array, items: {$ref: '#/components/schemas/AuthorizationEntry'}}+ '409': {description: Host is not running}+ '503': {description: Plugin runtime is not running}+ delete:+ tags: [Extensions]+ summary: Cancel a key's active attempt even when its initiating page has closed+ operationId: cancelPluginAuthorizationKey+ description: Uses the original cancel(key) seam. No interaction details from another surface are returned; an admitted commit finishes before settlement.+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ additionalProperties: false+ required: [key]+ properties:+ key: {type: string}+ responses:+ '200':+ description: Settlement or a no-op when no attempt is running+ content:+ application/json:+ schema:+ type: object+ properties:+ status: {type: string, enum: [authorized, cancelled, failed]}+ post:+ tags: [Extensions]+ summary: Start an explicit authorization using the bundled client's own interaction surface+ operationId: startPluginAuthorization+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [key]+ additionalProperties: false+ properties:+ key: {type: string, description: CredentialKey of the registered flow}+ method: {type: string, description: Defaults to the first declared method}+ responses:+ '202':+ description: An admitted attempt; this response is not an authorization success+ content:+ application/json:+ schema: {$ref: '#/components/schemas/AuthorizationAttempt'}+ '404': {description: No such registered flow}+ '409': {description: Host unavailable or this key already has an active attempt}+ '422': {description: Invalid method or key}+ /v1/host/extensions/authorization/disconnect:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ post:+ tags: [Extensions]+ summary: Disconnect an account using the integration's native logout+ operationId: disconnectPluginAuthorization+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ additionalProperties: false+ required: [key]+ properties:+ key: {type: string}+ responses:+ '200':+ description: Native account is no longer configured+ content:+ application/json:+ schema:+ type: object+ properties:+ configured: {type: boolean}+ accountLabel: {type: string}+ '409': {description: Host unavailable or another authorization operation is in progress}+ '404': {description: No registered disconnect operation for this account}+ '422': {description: The native account is still configured}+ /v1/host/extensions/authorization/{attemptId}:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ - {name: attemptId, in: path, required: true, schema: {type: string, format: uuid}}+ get:+ tags: [Extensions]+ summary: Read notices and unanswered prompts using the initiating surface's transient handle+ operationId: getPluginAuthorization+ responses:+ '200':+ description: Current attempt; never contains entered answers or credential values+ content:+ application/json:+ schema: {$ref: '#/components/schemas/AuthorizationAttempt'}+ '404': {description: Unknown handle or runtime restarted}+ '409': {description: Host is not running}+ delete:+ tags: [Extensions]+ summary: Withdraw this attempt and wait for its authorization outcome+ operationId: cancelPluginAuthorization+ description: An admitted record commit finishes. Cancellation does not remove an earlier credential record. There is no framework-wide timeout.+ responses:+ '200':+ description: Settled outcome, including authorized when a commit was already admitted+ content:+ application/json:+ schema: {$ref: '#/components/schemas/AuthorizationAttempt'}+ '404': {description: Unknown handle or runtime restarted}+ /v1/host/extensions/authorization/{attemptId}/answer:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ - {name: attemptId, in: path, required: true, schema: {type: string, format: uuid}}+ post:+ tags: [Extensions]+ summary: Answer or decline one prompt in this authorization+ operationId: answerPluginAuthorization+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [promptId]+ additionalProperties: false+ properties:+ promptId: {type: string, format: uuid}+ answer: {type: string, maxLength: 16384, description: Sent only to the waiting flow; never echoed or stored by Controller}+ decline: {type: boolean, description: Reject this prompt with the original AuthorizationDeclinedError}+ responses:+ '200':+ description: Updated interaction; the flow can continue asynchronously+ content:+ application/json:+ schema: {$ref: '#/components/schemas/AuthorizationAttempt'}+ '404': {description: Unknown attempt or prompt no longer pending}+ '422': {description: Invalid answer or unoffered select option}+ /v1/host/mcp:+ get:+ tags: [Extensions]+ summary: Plugin-owned MCP runtime diagnostics; configured through the owning plugin+ operationId: getMCPStatus+ parameters:+ - {$ref: '#/components/parameters/AccountName'}+ responses:+ '200':+ description: Actual Host connection state without independent account settings+ content:+ application/json:+ schema: {$ref: '#/components/schemas/MCPView'}+ /v1/host/mcp/servers/{name}/restart:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ - name: name+ in: path+ required: true+ schema: {type: string, pattern: '^[A-Za-z0-9_-]{1,32}$'}+ post:+ summary: Reconnect a managed MCP server after completing prior cleanup+ operationId: restartMCPServer+ responses:+ '200':+ description: Actual state after the initial reconnect attempt.+ content:+ application/json:+ schema: {$ref: '#/components/schemas/MCPView'}+ '409': {description: Host is not running}+ '502': {description: Restart failed}+ /v1/host/mcp/servers/{name}/probe:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ - name: name+ in: path+ required: true+ schema: {type: string, pattern: '^[A-Za-z0-9_-]{1,32}$'}+ post:+ summary: Inspect and close a temporary MCP connection without publishing tools+ operationId: probeMCPServer+ responses:+ '200':+ description: Temporary probe state, independent of the managed server state. OAuth never starts implicitly.+ content:+ application/json:+ schema:+ type: object+ required: [name, source, state, toolCount, resources]+ properties:+ name: {type: string}+ source: {type: string, enum: [user, plugin]}+ owner: {type: string}+ state: {type: string, enum: [connected, failed, waiting-credentials, waiting-authorization, stopping]}+ error: {type: string}+ missing: {type: array, items: {type: string}}+ toolCount: {type: integer, minimum: 0}+ resources: {type: boolean}+ protocolVersion: {type: string}+ serverName: {type: string}+ oauthEnabled: {type: boolean, description: The plugin declared standard MCP OAuth for this connection.}+ '409': {description: Host is not running}+ '502': {description: Host probe request or cleanup failed}+ /v1/host/mcp/servers/{name}/authorize:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ - name: name+ in: path+ required: true+ schema: {type: string, pattern: '^[A-Za-z0-9_-]{1,32}$'}+ post:+ summary: Start an explicit MCP OAuth authorization-code flow with PKCE+ operationId: authorizeMCPServer+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ origin:+ type: string+ description: Visible Controller origin; must match the actual request Host. HTTPS or loopback HTTP only. Forwarded destination headers are not trusted.+ responses:+ '200':+ description: Authorization URL is ready, or the attempt completed without further browser interaction.+ content:+ application/json:+ schema: {$ref: '#/components/schemas/MCPOAuthAuthorization'}+ '400': {description: Invalid origin or callback requirements}+ '409': {description: Host is not running}+ '502': {description: Authorization preparation failed}+ /v1/host/mcp/servers/{name}/authorization:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ - name: name+ in: path+ required: true+ schema: {type: string, pattern: '^[A-Za-z0-9_-]{1,32}$'}+ delete:+ summary: Cancel a pending browser authorization without deleting an existing grant+ operationId: cancelMCPAuthorization+ parameters:+ - name: id+ in: query+ schema: {type: string, maxLength: 128}+ description: Select this attempt only; stale identities are ignored. Omission cancels the current attempt.+ responses:+ '200':+ description: Attempt cleanup completed; saved credentials remain independent.+ content:+ application/json:+ schema: {$ref: '#/components/schemas/MCPView'}+ '409': {description: Host is not running}+ '502': {description: Authorization cleanup failed}+ /v1/host/mcp/servers/{name}/grant:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ - name: name+ in: path+ required: true+ schema: {type: string, pattern: '^[A-Za-z0-9_-]{1,32}$'}+ delete:+ summary: Disconnect MCP and remove its local OAuth grant+ operationId: disconnectMCPOAuth+ responses:+ '200':+ description: Connection stopped and local grant removed; no remote provider revocation is implied.+ content:+ application/json:+ schema: {$ref: '#/components/schemas/MCPView'}+ '409': {description: Host is not running}+ '502': {description: Local cleanup or grant deletion failed}+ /v1/mcp/oauth/callback/{userId}:+ parameters:+ - name: userId+ in: path+ required: true+ schema: {type: string}+ - name: state+ in: query+ required: true+ schema: {type: string}+ - name: code+ in: query+ schema: {type: string}+ - name: iss+ in: query+ schema: {type: string}+ - name: error+ in: query+ schema: {type: string}+ get:+ summary: Forward a browser callback to the already-running account Host for one-time state validation+ operationId: completeMCPOAuthCallback+ description: No X-User-ID header is required. Only this callback is exempted from browser-origin checks. A stopped Host is never started by the callback.+ responses:+ '200':+ description: Fixed confirmation page, or a request to continue additional provider authorization in Go Bot. Does not echo codes, tokens or state.+ content:+ text/html:+ schema: {type: string}+ '400': {description: Invalid, expired, replayed or failed authorization}+ '404': {description: Account unavailable}+ '409': {description: Host is not running}+ /v1/plugins/authorization/callback/{userId}/{token}:+ get:+ tags: [Extensions]+ summary: Receive a single-use browser callback for an active plugin authorization+ operationId: receivePluginAuthorizationCallback+ parameters:+ - {in: path, name: userId, required: true, schema: {type: string}}+ - {in: path, name: token, required: true, schema: {type: string, format: uuid}}+ - {in: query, name: state, required: true, schema: {type: string}}+ description: Provider query parameters are forwarded privately to the current flow. Receipt does not mean authorization succeeded. This endpoint does not require X-User-ID and never starts a Host.+ responses:+ '200':+ description: Callback received; return to the app for the actual authorization outcome.+ content:+ text/html:+ schema: {type: string}+ '400': {description: Invalid, expired, replayed or rejected callback}+ '409': {description: The account has no running Host}+ /v1/settings/plugins:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ get:+ summary: Saved plugin settings and actual Host runtime state+ operationId: getPluginSettings+ responses:+ '200':+ description: Credential values are never returned; a stopped Host reports unavailable.+ content:+ application/json:+ schema: {$ref: '#/components/schemas/PluginView'}+ /v1/settings/plugins/packages:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ post:+ summary: Install a reviewed plugin and its dependencies; initially disabled+ operationId: installPluginPackage+ requestBody:+ required: true+ content:+ application/json:+ schema: {$ref: '#/components/schemas/PluginPackageInput'}+ responses:+ '200':+ description: Package and approved native installation scripts completed.+ content:+ application/json:+ schema: {$ref: '#/components/schemas/PluginView'}+ '409': {description: Host is stopped or package is already configured}+ '422': {description: Package preparation failed}+ '502': {description: Intent was saved but the Host could not confirm application}+ /v1/settings/plugins/packages/{name}:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ - {in: path, name: name, required: true, schema: {type: string}, description: URL-encode the complete npm package name as one segment.}+ put:+ summary: Enable or disable an installed plugin package+ operationId: setPluginEnabled+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ additionalProperties: false+ required: [enabled]+ properties:+ enabled: {type: boolean}+ responses:+ '200':+ description: Saved selection and actual Host status+ content:+ application/json:+ schema: {$ref: '#/components/schemas/PluginView'}+ '400': {description: Invalid input}+ '404': {description: Plugin is not installed}+ '502': {description: Selection saved but activation failed}+ delete:+ summary: Remove package intent and stop its code before uninstalling+ operationId: removePluginPackage+ responses:+ '200':+ description: Credentials and workspace data are retained.+ content:+ application/json:+ schema: {$ref: '#/components/schemas/PluginView'}+ '404': {description: Package not configured}+ '409': {description: Host is not running}+ '502': {description: Intent was saved but Host removal failed}+ /v1/settings/plugins/packages/{name}/update:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ - {in: path, name: name, required: true, schema: {type: string}}+ post:+ summary: Prepare and explicitly apply a new package version+ operationId: updatePluginPackage+ requestBody:+ required: true+ content:+ application/json:+ schema: {$ref: '#/components/schemas/PluginPackageInput'}+ responses:+ '200':+ description: Actual state after applying the new saved source+ content:+ application/json:+ schema: {$ref: '#/components/schemas/PluginView'}+ '404': {description: Package not configured}+ '409': {description: Host is not running}+ '502': {description: New intent was saved but application failed}+ /v1/host/plugins/runtime/restart:+ parameters:+ - $ref: '#/components/parameters/AccountName'+ post:+ summary: Apply saved intent and restart the Host extension process+ operationId: restartPlugins+ responses:+ '200':+ description: Actual state after cleanup and restart+ content:+ application/json:+ schema: {$ref: '#/components/schemas/PluginView'}+ '409': {description: Host is not running}+ '502': {description: Application or restart failed}/healthz:get:summary: Process liveness@@ -249,6 +699,25 @@ paths:summary: Remove all ended tasks and their delivery historiesresponses:'200': {description: Count of deleted tasks}+ /v1/host/stream:+ parameters:+ - $ref: "#/components/parameters/AccountName"+ - $ref: "#/components/parameters/ControllerOrigin"+ get:+ summary: Stream all account session updates and task catalog changes over one SSE connection+ parameters:+ - name: cursors+ in: query+ description: URL-encoded JSON object mapping up to 20 cached session IDs to their last durable sequence or null+ schema: {type: string, maxLength: 8192}+ responses:+ '200':+ description: "event: host records containing sessionId (for session events), type and data; connection restores pending interactions"+ content:+ text/event-stream:+ schema: {type: string}+ '400': {description: Invalid session cursor map}+ '503': {description: Host unavailable}/v1/host/schedules/stream:parameters:- $ref: "#/components/parameters/AccountName"@@ -476,7 +945,7 @@ paths:schema:type: objectproperties:- provider: {type: string, default: deepseek, enum: [deepseek, zhipu, doubao]}+ provider: {type: string, default: deepseek, enum: [deepseek, zhipu, doubao, tavily, brave]}activate:type: booleandescription: Set false to save without changing the active provider. Set true to use this provider with a saved key. Omit for legacy save-and-select behavior.@@ -624,6 +1093,14 @@ paths:description: When true, return only the most recently created unarchived session, if one exists.schema:type: boolean+ - name: limit+ in: query+ schema:+ type: integer+ - name: cursor+ in: query+ schema:+ type: stringresponses:'200':description: Success@@ -661,15 +1138,6 @@ paths:description: State conflict'503':description: Service unavailable- parameters:- - name: limit- in: query- schema:- type: integer- - name: cursor- in: query- schema:- type: string/v1/sessions/{id}:parameters:- $ref: "#/components/parameters/AccountName"@@ -1500,6 +1968,12 @@ paths:type: stringcomponents:parameters:+ ControllerOrigin:+ in: header+ name: X-Go-Bot-Controller-Origin+ required: false+ description: Actual Controller origin visible to the client. Must match the request Host; HTTPS or loopback HTTP enables the Host's private OAuth callback channel. Bundled clients send this automatically, including when TLS terminates at a proxy.+ schema: {type: string, format: uri, maxLength: 4096}AccountName:in: headername: X-User-ID@@ -1509,6 +1983,221 @@ components:type: stringpattern: '^[a-z0-9][a-z0-9_-]{0,63}$'schemas:+ AuthorizationEntry:+ type: object+ required: [key, label, methods, inFlight, configured]+ properties:+ key: {type: string}+ label: {type: string}+ methods:+ type: array+ minItems: 1+ items:+ type: object+ required: [id, label]+ properties:+ id: {type: string}+ label: {type: string}+ inFlight: {type: boolean}+ configured: {type: boolean, description: Native integration or Go credential store reports an account; does not assert external service availability}+ canDisconnect: {type: boolean}+ accountLabel: {type: string}+ attemptId: {type: string, format: uuid, description: Latest resumable interaction handle retained by the Host surface.}+ attemptStatus: {type: string, enum: [running, authorized, cancelled, failed]}+ AuthorizationAttempt:+ type: object+ required: [id, key, label, method, status, notices, prompts]+ properties:+ id: {type: string, format: uuid, description: Transient Host interaction handle; absent from Redis and client storage}+ key: {type: string}+ label: {type: string}+ method: {type: string}+ status: {type: string, enum: [running, authorized, cancelled, failed]}+ notices:+ type: array+ items:+ type: object+ required: [message]+ properties:+ message: {type: string}+ url: {type: string}+ code: {type: string}+ prompts:+ type: array+ items:+ type: object+ required: [id, kind, message]+ properties:+ id: {type: string, format: uuid}+ kind: {type: string, enum: [text, secret, select]}+ message: {type: string}+ placeholder: {type: string}+ webInput: {type: string, enum: [json-file], description: "Optional Web file chooser hint; native clients retain the declared text/secret input."}+ options:+ type: array+ items:+ type: object+ required: [id, label]+ properties:+ id: {type: string}+ label: {type: string}+ description: {type: string}+ error: {type: string, description: Diagnostic with captured secret answers redacted}+ MCPServer:+ type: object+ required: [transport]+ additionalProperties: false+ description: Process and HTTP fields are mutually exclusive. Credential templates are resolved only in args, env and headers.+ properties:+ enabled: {type: boolean, default: true}+ transport: {type: string, enum: [stdio, streamable-http]}+ command: {type: string}+ args: {type: array, items: {type: string}}+ env: {type: object, additionalProperties: {type: string}}+ cwd: {type: string, description: Absolute Host directory for stdio}+ url: {type: string, description: HTTP(S) MCP endpoint for streamable-http}+ headers: {type: object, additionalProperties: {type: string}}+ toolLoading: {type: string, enum: [eager, on-demand], default: eager}+ oauth:+ type: object+ additionalProperties: false+ description: Explicit authorization code with PKCE. Omit clientId for dynamic registration; confidential clients use a static credential reference. Grants remain private Host files.+ properties:+ clientId: {type: string}+ clientSecretRef: {type: string}+ credentialKey: {type: string}+ scope: {type: string, description: Explicit scope; omission uses the server challenge}+ requestTimeoutMs: {type: integer, minimum: 1, maximum: 2147483647, default: 10000}+ authorizationTimeoutMs: {type: integer, minimum: 1, maximum: 2147483647, default: 600000}+ scopes: {type: array, items: {type: string}}+ MCPOAuthAuthorization:+ type: object+ required: [name, state]+ properties:+ name: {type: string}+ id: {type: string, description: Opaque attempt identity; distinct from OAuth state and PKCE values}+ phase: {type: string, enum: [starting, waiting-browser, exchanging, committing, authorized, cancelled, failed]}+ state: {type: string, enum: [preparing, pending, connecting, authorized, failed, cancelled, expired]}+ url: {type: string, description: Provider authorization URL, present only while user interaction is needed}+ expiresAt: {type: integer, format: int64, description: Authorization attempt expiry in Unix milliseconds}+ error: {type: string}+ MCPView:+ type: object+ required: [status]+ properties:+ status:+ type: object+ properties:+ error: {type: string}+ servers:+ type: array+ items:+ type: object+ properties:+ name: {type: string}+ source: {type: string, enum: [user, plugin]}+ owner: {type: string}+ state: {type: string, enum: [disabled, waiting-credentials, waiting-authorization, connecting, connected, reconnecting, stopping, failed]}+ error: {type: string}+ missing: {type: array, items: {type: string}}+ toolCount: {type: integer}+ resources: {type: boolean}+ protocolVersion: {type: string}+ serverName: {type: string}+ oauthEnabled: {type: boolean, description: The plugin declared standard MCP OAuth for this connection.}+ authorization: {$ref: '#/components/schemas/MCPOAuthAuthorization'}+ PluginSource:+ type: object+ required: [type, spec]+ properties:+ type: {type: string, enum: [registry, git, directory, tarball, bundled]}+ spec: {type: string, description: Fixed source snapshot resolved by the Controller and Host.}+ registry: {type: string}+ authRef: {type: string, description: Reference to an explicitly saved installation credential.}+ username: {type: string}+ PluginPackageInput:+ type: object+ additionalProperties: false+ required: [pluginId]+ properties:+ pluginId: {type: string, description: Stable ID from the Controller's built-in reviewed catalog.}+ PluginLocalized:+ type: object+ required: [en, zh-CN]+ properties:+ en: {type: string}+ zh-CN: {type: string}+ PluginCatalogEntry:+ type: object+ required: [pluginId, package, name, description, version, icon, maintainer, license]+ properties:+ pluginId: {type: string}+ package: {type: string}+ name: {type: string}+ description: {$ref: '#/components/schemas/PluginLocalized'}+ version: {type: string}+ icon: {type: string, description: Controller-relative image path declared by plugin.json}+ maintainer: {type: string}+ license: {type: string}+ tutorials:+ type: array+ items:+ type: object+ required: [language, title, video]+ properties:+ language: {type: string, enum: [en, zh-CN]}+ title: {type: string}+ video: {type: string, description: Backend-relative MP4 asset from plugin.json}+ poster: {type: string, description: Optional backend-relative poster image}+ PluginPackageInfo:+ type: object+ properties:+ name: {type: string}+ version: {type: string}+ description: {type: string}+ license: {type: string}+ source: {$ref: '#/components/schemas/PluginSource'}+ api: {type: string, enum: ['1']}+ title: {type: string}+ availableVersion: {type: string, description: Present only when the reviewed release is newer than the actual installed package.}+ configSchema: {type: object, additionalProperties: true}+ present: {type: boolean}+ PluginSettings:+ type: object+ additionalProperties: false+ required: [packages]+ properties:+ packages:+ type: object+ additionalProperties:+ type: object+ additionalProperties: false+ required: [catalogId, version, enabled]+ properties:+ catalogId: {type: string}+ version: {type: string}+ enabled: {type: boolean}+ PluginView:+ type: object+ required: [catalog, settings, status]+ properties:+ catalog: {type: array, items: {$ref: '#/components/schemas/PluginCatalogEntry'}}+ settings: {$ref: '#/components/schemas/PluginSettings'}+ status:+ type: object+ properties:+ runtime: {type: string, enum: [stopped, running, failed, unavailable]}+ packages: {type: array, items: {$ref: '#/components/schemas/PluginPackageInfo'}}+ instances:+ type: array+ items:+ type: object+ properties:+ id: {type: string}+ package: {type: string}+ state: {type: string, enum: [ready, pending, loading, stopping, disposed, failed, disabled, unavailable]}+ error: {type: string}+ error: {type: string}ScheduleEntry:type: objectrequired: [record, status, scheduledAtLocal]@@ -1621,6 +2310,11 @@ components:ModelEndpointInput:type: objectproperties:+ protocol:+ type: string+ enum: [responses, anthropic_messages]+ default: responses+ description: Endpoint API format; independent of the model name.name: {type: string}baseUrl: {type: string, format: uri}apiKey: {type: string, writeOnly: true}diff --git a/build/Dockerfile.host b/build/Dockerfile.hostindex a827301..cf6c829 100644--- a/build/Dockerfile.host+++ b/build/Dockerfile.host@@ -1,7 +1,19 @@# syntax=docker/dockerfile:1.7-FROM node:22-trixie-slim AS node+FROM node:24.22.3-trixie-slim AS node# Bootstrap modern trust roots before Debian's ca-certificates package exists.RUN node -e 'process.stdout.write(require("tls").rootCertificates.join("\n"))' > /tmp/bootstrap-ca.crt++# Pure Cordis runtime dependencies; installation does not load business plugins+# and lifecycle scripts remain disabled. The Host starts Node only as needed.+FROM node AS cordis+WORKDIR /opt/cordis+COPY extensions/cordis/package.json extensions/cordis/pnpm-lock.yaml extensions/cordis/pnpm-workspace.yaml ./+RUN --mount=type=secret,id=build_ca,required=false \+ if [ -s /run/secrets/build_ca ]; then cat /run/secrets/build_ca >> /tmp/bootstrap-ca.crt; fi; \+ npm --cafile=/tmp/bootstrap-ca.crt install --global --ignore-scripts --no-audit --no-fund [email protected] \+ && NODE_EXTRA_CA_CERTS=/tmp/bootstrap-ca.crt pnpm install --frozen-lockfile --prod --ignore-scripts+COPY extensions/cordis/src/ ./src/+COPY extensions/sdk/package.json extensions/sdk/index.mjs extensions/sdk/index.d.ts extensions/sdk/LICENSE extensions/sdk/README.md /opt/sdk/FROM golang:1.26-trixie AS toolchainFROM toolchain AS sourceWORKDIR /src@@ -14,37 +26,6 @@ ARG TARGETOS=linux TARGETARCHRUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build -trimpath -o /out/host ./cmd/host-FROM debian:trixie-slim AS asset-downloads-COPY --from=node /tmp/bootstrap-ca.crt /etc/ssl/certs/ca-certificates.crt-RUN --mount=type=secret,id=build_ca,required=false \- if [ -s /run/secrets/build_ca ]; then cat /run/secrets/build_ca >> /etc/ssl/certs/ca-certificates.crt; fi; \- sed -i 's#http://deb.debian.org#https://deb.debian.org#g' /etc/apt/sources.list.d/debian.sources \- && apt-get -o Acquire::https::CaInfo=/etc/ssl/certs/ca-certificates.crt -o Acquire::Retries=5 update && apt-get -o Acquire::https::CaInfo=/etc/ssl/certs/ca-certificates.crt -o Acquire::Retries=5 install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/* \- && if [ -s /run/secrets/build_ca ]; then cat /run/secrets/build_ca >> /etc/ssl/certs/ca-certificates.crt; fi-FROM asset-downloads AS officecli-ARG TARGETARCH-ARG OFFICECLI_VERSION=v1.0.160-COPY build/officecli.sha256 /tmp/SHA256SUMS-RUN case "$TARGETARCH" in amd64) asset=officecli-linux-x64;; arm64) asset=officecli-linux-arm64;; *) exit 1;; esac \- && curl -fL --retry 5 --connect-timeout 15 "https://github.com/iOfficeAI/OfficeCLI/releases/download/${OFFICECLI_VERSION}/${asset}" -o "/tmp/${asset}" \- && cd /tmp && grep " ${asset}$" SHA256SUMS | sha256sum -c - \- && install -m 0755 "/tmp/${asset}" /usr/local/bin/officecli--# Use the official Codex installer layout and embedded resources from the same-# verified binary. The isolated HOME is only used to assemble the image seed.-RUN --network=none set -eu; \- export HOME=/tmp/officecli-home OFFICECLI_SKIP_UPDATE=1 DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1; \- mkdir -p "$HOME/.agents" /out; \- officecli skills codex; \- for skill in word excel pptx academic-paper data-dashboard financial-model pitch-deck word-form morph-ppt morph-ppt-3d; do \- officecli skills install "$skill" codex; \- done; \- for bundle in officecli officecli-docx officecli-xlsx officecli-pptx officecli-academic-paper officecli-data-dashboard officecli-financial-model officecli-pitch-deck officecli-word-form morph-ppt morph-ppt-3d; do \- test -s "$HOME/.agents/skills/$bundle/SKILL.md"; \- done; \- test -s "$HOME/.agents/skills/morph-ppt/reference/styles/INDEX.md"; \- mv "$HOME/.agents/skills" /out/skills-FROM debian:trixie-slim AS computerENV DEBIAN_FRONTEND=noninteractiveCOPY --from=node /tmp/bootstrap-ca.crt /etc/ssl/certs/ca-certificates.crt@@ -52,7 +33,7 @@ RUN --mount=type=secret,id=build_ca,required=false \if [ -s /run/secrets/build_ca ]; then cat /run/secrets/build_ca >> /etc/ssl/certs/ca-certificates.crt; fi; \sed -i 's#http://deb.debian.org#https://deb.debian.org#g' /etc/apt/sources.list.d/debian.sources \&& apt-get -o Acquire::https::CaInfo=/etc/ssl/certs/ca-certificates.crt -o Acquire::Retries=5 update && apt-get -o Acquire::https::CaInfo=/etc/ssl/certs/ca-certificates.crt -o Acquire::Retries=5 install -y --no-install-recommends \- ca-certificates bash git curl ripgrep tzdata python3 python3-pip python3-venv \+ ca-certificates bash git curl ripgrep tzdata libatomic1 python3 python3-pip python3-venv \chromium libicu76 fontconfig fonts-liberation fonts-noto-cjk fonts-crosextra-carlito fonts-crosextra-caladea \libreoffice-writer libreoffice-calc libreoffice-impress poppler-utils poppler-data qpdf mupdf-tools \tesseract-ocr tesseract-ocr-chi-sim tesseract-ocr-chi-tra \@@ -63,33 +44,34 @@ COPY --from=node /usr/local/bin/node /usr/local/bin/nodeCOPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modulesRUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \&& ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx-ENV HOME=/root PATH="/opt/agent-venv/bin:/root/.local/bin:${PATH}" NPM_CONFIG_PREFIX=/root/.local NODE_PATH=/root/.local/lib/node_modules OFFICECLI_SKIP_UPDATE=1+ENV HOME=/root PATH="/opt/agent-venv/bin:${PATH}"RUN python -m pip install --cert /etc/ssl/certs/ca-certificates.crt --no-cache-dir pypdf pdfplumber reportlab PyMuPDF pypdfium2 python-pptx numpy lxml defusedxml pdf2image Pillow pytesseract \&& npm --cafile=/etc/ssl/certs/ca-certificates.crt install --global --ignore-scripts --no-audit --no-fund [email protected] [email protected]-COPY --from=officecli /usr/local/bin/officecli /usr/local/bin/officecliCOPY build/fontconfig/60-office-fonts.conf /etc/fonts/conf.d/60-office-fonts.confRUN mkdir -p /root/harness && fc-cache -f+# Package resources are assembled with official installers in a disposable stage.+# The final Host ships wrapper packages only; package installation prepares each CLI.+FROM computer AS plugin-packages+COPY extensions/plugins/ /opt/plugins/+RUN --mount=type=secret,id=build_ca,required=false \+ if [ -s /run/secrets/build_ca ]; then cat /run/secrets/build_ca >> /etc/ssl/certs/ca-certificates.crt; fi; \+ NODE_EXTRA_CA_CERTS=/etc/ssl/certs/ca-certificates.crt bash /opt/plugins/prepare-assets.sh+FROM computer AS host-ARG AGENT_BROWSER_VERSION=0.43.0-ARG AGENT_BROWSER_SKILL_REF=1cc19526f3641c8543d55aa6700e7c55b37ac356-ARG SKILLS_CLI_VERSION=1.8.1-COPY --from=officecli /out/skills/ /usr/share/go-bot/skill-seed/-RUN set -eu; \- npm --cafile=/etc/ssl/certs/ca-certificates.crt install --global --prefix /usr/local --no-audit --no-fund "agent-browser@${AGENT_BROWSER_VERSION}"; \- agent-browser --version; \- agent-browser skills get core > /dev/null; \- install -Dm0644 /usr/local/lib/node_modules/agent-browser/LICENSE /usr/share/doc/go-bot/agent-browser-LICENSE; \- skill_project="$(mktemp -d)"; \- cd "$skill_project"; \- DISABLE_TELEMETRY=1 NODE_EXTRA_CA_CERTS=/etc/ssl/certs/ca-certificates.crt \- npx --yes "skills@${SKILLS_CLI_VERSION}" add "vercel-labs/agent-browser#${AGENT_BROWSER_SKILL_REF}" --skill agent-browser --agent codex --copy --yes; \- test -s .agents/skills/agent-browser/SKILL.md; \- mv .agents/skills/agent-browser /usr/share/go-bot/skill-seed/; \- cd /; \- rm -rf "$skill_project"+COPY --from=plugin-packages /opt/plugins/agent-browser/ /usr/share/go-bot/plugins/agent-browser/+COPY --from=plugin-packages /opt/plugins/officecli/ /usr/share/go-bot/plugins/officecli/+COPY --from=plugin-packages /opt/plugins/x/ /usr/share/go-bot/plugins/x/+COPY --from=plugin-packages /opt/plugins/google-workspace/ /usr/share/go-bot/plugins/google-workspace/++# Plugin runtime dependencies are shared; business modules load only after activation.+COPY --from=cordis /opt/cordis/ /usr/share/go-bot/cordis/+COPY --from=cordis /opt/sdk/ /usr/share/go-bot/sdk/+COPY --from=cordis /usr/local/lib/node_modules/pnpm /usr/local/lib/node_modules/pnpm+RUN node -e 'const fs = require("node:fs"), path = require("node:path"); const root = "/usr/local/lib/node_modules/pnpm"; fs.symlinkSync(path.join(root, require(root + "/package.json").bin.pnpm), "/usr/local/bin/pnpm")' \+ && pnpm --version-ENV GIN_MODE=release DSH_HOME=/root/harness/.dsh DSH_AGENTS_HOME=/root/harness/.agents \+ENV NODE_PATH=/usr/local/lib/node_modules GIN_MODE=release DSH_HOME=/root/harness/.dsh DSH_AGENTS_HOME=/root/harness/.agents \AGENT_BROWSER_EXECUTABLE_PATH=/usr/bin/chromiumCOPY --from=compile /out/host /usr/local/bin/hostCOPY LICENSE THIRD_PARTY_NOTICES.md /usr/share/doc/go-bot/diff --git a/build/dependencies.lock.yaml b/build/dependencies.lock.yamlindex 31ff34e..1ce465e 100644--- a/build/dependencies.lock.yaml+++ b/build/dependencies.lock.yaml@@ -1,7 +1,7 @@-officecli:- repository: iOfficeAI/OfficeCLI- version: v1.0.160- checksums: build/officecli.sha256+cordis-runtime:+ node: 24.22.3+ pnpm: 11.25.0+ dependency_lockfile: extensions/cordis/pnpm-lock.yamlagent-browser:repository: vercel-labs/agent-browserversion: v0.43.0diff --git a/build/officecli.sha256 b/build/officecli.sha256deleted file mode 100644index 14181c6..0000000--- a/build/officecli.sha256+++ /dev/null@@ -1,2 +0,0 @@-e8f06aff6c59f11a73a1a1218bda3ce170299201fd56bce6d62ecd4d0c024e53 officecli-linux-arm64-baa084b64ec634bd9d41a0592db3ed85f11658b358bab898679537ea7f3e73a9 officecli-linux-x64diff --git a/build/plugin-tutorials/README.md b/build/plugin-tutorials/README.mdnew file mode 100644index 0000000..5a95ad2--- /dev/null+++ b/build/plugin-tutorials/README.md@@ -0,0 +1,28 @@+# Plugin tutorial media++Capture the real vendor console with the approved browser/computer tool. Store+raw screenshots and the JSON editing recipe outside Git, for example in `.cache`.+Never publish browser tabs, account identifiers, keys, tokens or private project+names. The renderer removes only explicitly reviewed regions and overlays focus+and captions; it does not invent vendor interface states.++Each scene in the private recipe has `image`, `crop: [left,top,right,bottom]`,+`redactions: [[left,top,right,bottom], ...]`, `focus`, optional `zoom` / `seconds`,+and `captions: {"en": [title, body], "zh-CN": [title, body]}`.++```sh+python3 build/plugin-tutorials/render.py .cache/tutorial-recipe.json \+ --language en --font /path/to/a/unicode-font.ttf \+ --output extensions/plugins/x/assets/account-setup.en.mp4+```++Requires Pillow and ffmpeg with libx264. Review extracted full-page and zoomed+frames, decode the full result, and verify playback through Controller and the+mobile player. Only then add the MP4/poster paths to `plugin.json.tutorials`.+The project keeps the X tutorial before the Save action, by user instruction.++The Google Workspace tutorial records the real API library, branding, audience,+test-user form and Desktop-client form without submitting Cloud configuration.+The last scene shows the current console restriction on downloading old secrets;+it reminds users to keep the JSON at creation time. It does not fabricate a+post-creation download screen or generate another application for the recording.diff --git a/build/plugin-tutorials/render.py b/build/plugin-tutorials/render.pynew file mode 100644index 0000000..fa4cc84--- /dev/null+++ b/build/plugin-tutorials/render.py@@ -0,0 +1,83 @@+#!/usr/bin/env python3+"""Render a reviewed screenshot recording into a focused, captioned MP4.++Input recipe is private (raw console captures must stay out of Git). Each scene+specifies a screenshot, crop, redactions, focus rectangle, captions and duration.+Only reviewed output media is copied into a plugin's public assets directory.+Requires Pillow, ffmpeg and a font supporting the requested caption language.+"""+import argparse+import json+import subprocess+import tempfile+from pathlib import Path+from PIL import Image, ImageDraw, ImageFont+++def wrap(draw, text, font, width):+ lines=[]+ for paragraph in text.split('\n'):+ line=''+ for char in paragraph:+ if draw.textlength(line+char,font=font)>width and line:+ lines.append(line.strip());line=''+ line+=char+ lines.append(line.strip())+ return lines+++def render(recipe, language, output, font_path):+ with tempfile.TemporaryDirectory(prefix='go-bot-tutorial-') as temp:+ work=Path(temp);clips=[]+ for index,scene in enumerate(recipe['scenes']):+ picture=Image.open(scene['image']).convert('RGB')+ draw=ImageDraw.Draw(picture)+ for box in scene.get('redactions',[]):+ draw.rounded_rectangle(tuple(box),radius=6,fill='#e4e7ec')+ left,top,right,bottom=scene['crop']+ picture=picture.crop((left,top,right,bottom))+ width,height=picture.size+ padded_height=round(width*9/16)+ pad_y=(padded_height-height)//2+ canvas=Image.new('RGB',(width,padded_height),'#f4f5f8')+ canvas.paste(picture,(0,pad_y));draw=ImageDraw.Draw(canvas)+ x1,y1,x2,y2=scene['focus']+ box=(x1-left,y1-top+pad_y,x2-left,y2-top+pad_y)+ draw.rounded_rectangle(box,radius=10,outline='#7466c4',width=5)+ image=work/f'{index}.png';canvas.save(image)+ caption=Image.new('RGBA',(1920,180),(20,28,43,238));draw=ImageDraw.Draw(caption)+ title_font=ImageFont.truetype(font_path,35)+ body_font=ImageFont.truetype(font_path,27)+ title,body=scene['captions'][language]+ draw.text((48,24),title,font=title_font,fill='white')+ for line_index,line in enumerate(wrap(draw,body,body_font,1810)[:2]):+ draw.text((48,79+line_index*36),line,font=body_font,fill='#e1e5ee')+ overlay=work/f'caption-{index}.png';caption.save(overlay)+ frames=round(scene.get('seconds',6)*30)+ focus_x=(box[0]+box[2])/2;focus_y=(box[1]+box[3])/2+ amount=scene.get('zoom',1.5)-1+ # Establish full-page context, zoom to the control, hold, then pull+ # back before the next real recorded page. No synthetic UI frames.+ rise=f'min(max((on-24)/45,0),1)'+ fall=f'min(max((on-{frames-42})/30,0),1)'+ zoom=f'1+{amount}*({rise}-{fall})'+ x=f'max(0,min(iw-iw/zoom,{focus_x}-iw/(2*zoom)))'+ y=f'max(0,min(ih-ih/zoom,{focus_y}-ih/(2*zoom)))'+ video=work/f'{index}.mp4'+ graph=f"[0:v]zoompan=z='{zoom}':x='{x}':y='{y}':d={frames}:s=1920x1080:fps=30[shot];[shot][1:v]overlay=0:0,format=yuv420p[v]"+ subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-i',str(image),'-i',str(overlay),'-filter_complex',graph,'-map','[v]','-frames:v',str(frames),'-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(video)],check=True)+ clips.append(video)+ listing=work/'clips.txt';listing.write_text(''.join("file '"+str(clip)+"'\n" for clip in clips))+ output.parent.mkdir(parents=True,exist_ok=True)+ subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','concat','-safe','0','-i',str(listing),'-c','copy','-movflags','+faststart',str(output)],check=True)+ subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-ss','1','-i',str(output),'-frames:v','1',str(output.with_suffix('.png'))],check=True)+++if __name__=='__main__':+ parser=argparse.ArgumentParser(description=__doc__)+ parser.add_argument('recipe',type=Path)+ parser.add_argument('--language',choices=['en','zh-CN'],required=True)+ parser.add_argument('--font',type=Path,required=True)+ parser.add_argument('--output',type=Path,required=True)+ args=parser.parse_args()+ render(json.loads(args.recipe.read_text()),args.language,args.output,str(args.font))diff --git a/client/client.go b/client/client.goindex 429379d..c9fd027 100644--- a/client/client.go+++ b/client/client.go@@ -10,6 +10,8 @@ import ("net/http""net/url""strings"++ mcpconfig "go-bot/mcp")type HTTPError struct {@@ -48,6 +50,7 @@ func (c Client) Do(ctx context.Context, method, path string, body any) (*http.Re}if c.UserID != "" {request.Header.Set("X-User-ID", c.UserID)+ request.Header.Set(mcpconfig.ControllerOriginHeader, request.URL.Scheme+"://"+request.URL.Host)}transport := c.HTTPif transport == nil {@@ -104,3 +107,18 @@ func (c Client) Stream(ctx context.Context, sessionID string, after *uint64) (io}return res.Body, nil}++// HostStream multiplexes all of the account's Sessions and Schedule changes.+// Decode event: host records by sessionId/type/data. Cursors belong only to+// cached transcripts; the caller owns closing and reconnecting the stream.+func (c Client) HostStream(ctx context.Context, cursors map[string]*uint64) (io.ReadCloser, error) {+ data, err := json.Marshal(cursors)+ if err != nil {+ return nil, err+ }+ res, err := c.Do(ctx, http.MethodGet, "/v1/host/stream?cursors="+url.QueryEscape(string(data)), nil)+ if err != nil {+ return nil, err+ }+ return res.Body, nil+}diff --git a/client/mcp.go b/client/mcp.gonew file mode 100644index 0000000..0885f74--- /dev/null+++ b/client/mcp.go@@ -0,0 +1,46 @@+package client++import (+ "context"+ "errors"+ "net/http"+ "net/url"++ mcpconfig "go-bot/mcp"+)++// GetMCPStatus reads plugin-owned connections. Configure connections through+// the owning plugin; there is no independent account MCP configuration.+func (c Client) GetMCPStatus(ctx context.Context) (view mcpconfig.View, err error) {+ err = c.readJSON(ctx, http.MethodGet, mcpconfig.RuntimePath, nil, &view)+ return+}+func (c Client) RestartMCPServer(ctx context.Context, name string) (view mcpconfig.View, err error) {+ err = c.readJSON(ctx, http.MethodPost, mcpconfig.RuntimePath+"/servers/"+url.PathEscape(name)+"/restart", nil, &view)+ return+}++func (c Client) ProbeMCPServer(ctx context.Context, name string) (result mcpconfig.ServerStatus, err error) {+ err = c.readJSON(ctx, http.MethodPost, mcpconfig.RuntimePath+"/servers/"+url.PathEscape(name)+"/probe", nil, &result)+ return+}++func (c Client) AuthorizeMCPServer(ctx context.Context, name, origin string) (view mcpconfig.OAuthAuthorization, err error) {+ err = c.readJSON(ctx, http.MethodPost, mcpconfig.RuntimePath+"/servers/"+url.PathEscape(name)+"/authorize", map[string]string{"origin": origin}, &view)+ return+}+func (c Client) CancelMCPAuthorization(ctx context.Context, name string) (view mcpconfig.View, err error) {+ err = c.readJSON(ctx, http.MethodDelete, mcpconfig.RuntimePath+"/servers/"+url.PathEscape(name)+"/authorization", nil, &view)+ return+}+func (c Client) CancelMCPAuthorizationAttempt(ctx context.Context, name, id string) (view mcpconfig.View, err error) {+ if id == "" {+ return view, errors.New("authorization attempt ID is required")+ }+ err = c.readJSON(ctx, http.MethodDelete, mcpconfig.RuntimePath+"/servers/"+url.PathEscape(name)+"/authorization?id="+url.QueryEscape(id), nil, &view)+ return+}+func (c Client) DisconnectMCPOAuth(ctx context.Context, name string) (view mcpconfig.View, err error) {+ err = c.readJSON(ctx, http.MethodDelete, mcpconfig.RuntimePath+"/servers/"+url.PathEscape(name)+"/grant", nil, &view)+ return+}diff --git a/client/models.go b/client/models.goindex a07395d..d043d22 100644--- a/client/models.go+++ b/client/models.go@@ -15,6 +15,7 @@ type ModelSelection struct {}type ModelEndpoint struct {+ Protocol string `json:"protocol"`Name string `json:"name"`BaseURL string `json:"baseUrl"`Models []string `json:"models"`@@ -32,10 +33,12 @@ type SessionModel struct {}type ModelEndpointInput struct {- Name string `json:"name"`- BaseURL string `json:"baseUrl"`- Models []string `json:"models"`- APIKey string `json:"apiKey,omitempty"`+ // Protocol is responses (the default) or anthropic_messages.+ Protocol string `json:"protocol,omitempty"`+ Name string `json:"name"`+ BaseURL string `json:"baseUrl"`+ Models []string `json:"models"`+ APIKey string `json:"apiKey,omitempty"`}type ModelUpdate struct {diff --git a/client/plugins.go b/client/plugins.gonew file mode 100644index 0000000..fd4315e--- /dev/null+++ b/client/plugins.go@@ -0,0 +1,38 @@+package client++import (+ "context"+ "net/http"+ "net/url"++ "go-bot/plugin"+)++type PluginPackageInput struct {+ PluginID string `json:"pluginId"`+}++func (c Client) GetPluginSettings(ctx context.Context) (view plugin.View, err error) {+ err = c.readJSON(ctx, http.MethodGet, plugin.SettingsPath, nil, &view)+ return+}+func (c Client) InstallPluginPackage(ctx context.Context, input PluginPackageInput) (view plugin.View, err error) {+ err = c.readJSON(ctx, http.MethodPost, plugin.SettingsPath+"/packages", input, &view)+ return+}+func (c Client) UpdatePluginPackage(ctx context.Context, name string, input PluginPackageInput) (view plugin.View, err error) {+ err = c.readJSON(ctx, http.MethodPost, plugin.SettingsPath+"/packages/"+url.PathEscape(name)+"/update", input, &view)+ return+}+func (c Client) RemovePluginPackage(ctx context.Context, name string) (view plugin.View, err error) {+ err = c.readJSON(ctx, http.MethodDelete, plugin.SettingsPath+"/packages/"+url.PathEscape(name), nil, &view)+ return+}+func (c Client) SetPluginEnabled(ctx context.Context, name string, enabled bool) (view plugin.View, err error) {+ err = c.readJSON(ctx, http.MethodPut, plugin.SettingsPath+"/packages/"+url.PathEscape(name), plugin.PackageInput{Enabled: enabled}, &view)+ return+}+func (c Client) RestartPlugins(ctx context.Context) (view plugin.View, err error) {+ err = c.readJSON(ctx, http.MethodPost, "/v1/host/plugins/runtime/restart", nil, &view)+ return+}diff --git a/docs/README.md b/docs/README.mdindex 53d85be..4786e23 100644--- a/docs/README.md+++ b/docs/README.md@@ -10,7 +10,10 @@| [HTTP API](api.md) · [OpenAPI](../api/openapi.yaml) | Accounts, sessions, messages, streaming, and files || [Architecture](architecture.md) | Controller, Redis, Host, and data layout || [Schedule and workspaces](schedule-parity-plan.zh-CN.md) | Upstream behavior, delivery receipts, chat archiving, and mobile task management |+| [Proactive service research and proposal](proactive-service-research-and-plan.zh-CN.md) | Official Muse, Grok Bot and dots behavior, open-source wake mechanisms, and a Go Bot proposal || [Extending capabilities](providers.md) · [Contributing](../CONTRIBUTING.md) | Provider contracts and development workflow |+| [X / Google account setup](plugin-account-setup.md) | Obtain your application credentials and connect native accounts |+| [Business plugin SDK](../extensions/sdk/README.md) · [Examples](../examples/plugins/README.md) | Native Cordis plugins, async Host APIs, credentials and MCP || [Frontend development](../frontend/README.md) | Develop the UI with Vite against Controller || [Upstream compatibility](compatibility.md) · [Validation](validation.md) | Upstream fixtures and historical verification results || [License](../LICENSE) · [Third-party notices](../THIRD_PARTY_NOTICES.md) | License terms and upstream attribution |diff --git a/docs/agent-browser-officecli-plugin-plan.zh-CN.md b/docs/agent-browser-officecli-plugin-plan.zh-CN.mdnew file mode 100644index 0000000..110dee7--- /dev/null+++ b/docs/agent-browser-officecli-plugin-plan.zh-CN.md@@ -0,0 +1,393 @@+# agent-browser 与 OfficeCLI 官方能力插件化方案++日期:2026-11-20。状态:已实现并完成本地验收;2026-11-20 按上游核对结果使用 pnpm 标准安装流程,依赖准备不放在 Cordis apply。已确定采用官方默认全局 CLI 安装;按最新决定保留当前 `$DSH_HOME/plugins/profile/node_modules` 的插件包目录。++## 1. 结论与范围++将两者分别包装为本项目的正式 Cordis 插件,接入现有插件市场。采用 **官方 CLI + 官方 Skills**,由 Agent 继续通过 Go 内置 Shell 使用;不自行重写浏览器动作、Office 文档操作或 Skill 正文。++插件负责按官方方式安装软件、可用性检查与 Skill 贡献;Cordis 负责插件生命周期。Go 继续负责 Shell 执行、权限、沙箱、Jobs、会话以及图片读取和文件交付。++用户管理模型收敛为“每个账号对每个插件包一份安装选择和启停状态”。Redis 只保存这类用户状态及所选版本;包自身的配置定义、默认值和准备逻辑随包提供,认证数据使用 Go credentials。不再向用户提供一个包创建多份运行实例的模型。++本方案不处理 ECI/NAS 下安装文件丢失的保存、备份和自动恢复。也不同时接入第二套 MCP 工具集,不引入插件自己的 AgentLoop、模型配置或会话管理。++## 2. 官方已经提供什么++### 2.1 agent-browser++已核对官方 GitHub、安装文档及目前镜像使用的固定提交 `1cc19526f3641c8543d55aa6700e7c55b37ac356`:++| 官方入口 | 作用 | 本项目采用方式 |+| --- | --- | --- |+| `npm install -g agent-browser` | 安装 CLI,由官方包选择平台二进制 | 直接使用官方 npm 全局安装,固定版本,不传自定义 prefix |+| `agent-browser install` | 安装默认浏览器 | 复用 Host 已有 `/usr/bin/chromium`,按官方 custom-browser 方式传入路径,无需再下载一套浏览器 |+| `npx skills add vercel-labs/agent-browser` | 安装发现 Skill | 使用官方安装器取得原始 `skills/agent-browser`,纳入插件发布包 |+| `agent-browser skills get core` | 读取与 CLI 匹配的操作指南 | 保留原流程,由模型按官方 Skill 指示读取 |+| `agent-browser mcp` | 提供 stdio MCP 入口 | 已确认存在,但本次不选用,避免与 CLI 重复提供浏览器操作 |+| `.claude-plugin/marketplace.json` | Claude Code 的 Skill 市场声明 | 参考其原始 Skill 来源;不是可直接加载的 Cordis 模块 |++重要区别:官方发现 Skill 很薄,真正的工作流、命令参考和专项知识由 CLI 随版本提供。我们不把整个命令手册改写进系统提示,也不把所有专项内容一股脑放入 Harness 的 Skill 清单。++来源:[官方 GitHub](https://github.com/vercel-labs/agent-browser)、[安装与已有浏览器](https://agent-browser.dev/installation)、[Skills 机制](https://agent-browser.dev/skills)、[官方 Claude 市场声明](https://github.com/vercel-labs/agent-browser/blob/1cc19526f3641c8543d55aa6700e7c55b37ac356/.claude-plugin/marketplace.json)。++### 2.2 OfficeCLI++已核对官方 GitHub、固定版本 `v1.0.160` 的源码,以及 npm registry 中实际发布的 `@officecli/[email protected]`:++| 官方入口 | 作用 | 本项目采用方式 |+| --- | --- | --- |+| `npm install -g @officecli/officecli` | 安装官方启动器并取得平台二进制 | 直接使用官方 npm 全局安装,复用官方启动器与下载逻辑,不传自定义 prefix |+| GitHub Release / 官方安装脚本 | 直接安装二进制 | 作为官方来源依据,不维护第二套下载实现 |+| `officecli skills codex` | 导出总入口 Skill | 在插件制作阶段使用隔离 HOME 导出 |+| `officecli skills install <name> codex` | 导出某个专用 Skill 及配套资源 | 保留多个 Skill 目录与完整资源,不合并成一个自写 Skill |+| `officecli load_skill <name>` | 从 CLI 读取内置指南 | 保留官方命令,不新增同义 Harness 工具 |+| 内置 MCP、Node/Python SDK | 其他程序化接入方式 | 已确认存在,本次采用 CLI 路线即可,不同时注册重复工具 |++官方源码树内的 `npm/package.json` 版本与发布版本可能不同:核对安装对象应以实际发布的 npm 包及其二进制版本为准,不能仅从 Git tag 下的 manifest 推断。本次已读取实际 `1.0.160` npm 包,并通过两种 Linux 架构的安装执行核对版本与二进制校验值。++另外,OfficeCLI 仓库 `plugins/plugin-protocol.md` 描述的是 OfficeCLI 自身的文档格式扩展协议,并非我们的 Cordis 插件格式,不能把该目录当成现成的 go-bot 插件。++来源:[官方用法](https://github.com/iOfficeAI/OfficeCLI/tree/v1.0.160)、[官方 npm 说明](https://github.com/iOfficeAI/OfficeCLI/blob/v1.0.160/npm/README.md)、[启动器](https://github.com/iOfficeAI/OfficeCLI/blob/v1.0.160/npm/officecli.js)、[Skill 安装器](https://github.com/iOfficeAI/OfficeCLI/blob/v1.0.160/src/officecli/Core/SkillInstaller.cs)、[OfficeCLI 格式插件协议](https://github.com/iOfficeAI/OfficeCLI/blob/v1.0.160/plugins/plugin-protocol.md)。++### 2.3 为什么仍需要我们包装++官方 npm 包提供可执行程序、安装逻辑或客户端约定,不提供本项目的 `goBot.api` 与 Cordis `apply(ctx)`。我们的插件只做这一层装配:准备官方程序、提供原始 Skills、核实全局命令能在 Host 执行环境中使用,随后按原生 Cordis 生命周期撤销 Skill 等贡献。++## 3. 当前代码的真实缺口++| 当前位置 | 当前行为 | 插件化调整 |+| --- | --- | --- |+| `build/Dockerfile.host` | 构建时安装两套 CLI,导出并复制 Skills 到 seed | 移出两套专用安装和 seed 步骤,交给插件准备与发布流程 |+| `harness/skills/seed.go` | 首次启动将 seed 复制到用户 Skill 根,并使用初始化标记 | 两套官方插件不再复制到用户目录;若已无其他 seed 使用者,删除这套专用启动依赖与旧标记分支 |+| `extensions/sdk/index.d.ts` | 已有 Skill 目录注册 | 直接复用;不增加 commands.register 或命令执行 RPC |+| `internal/plugins/manager.go` 及运行目录参数 | 包管理项目使用 `.dsh/plugins/profile` | 保留当前根目录及标准 node_modules,不因这两个业务插件重做包存储 |+| `plugin.Settings`、Controller/Redis 与两端管理 DTO | packages 与 instances 分开,instances.config 随用户设置写入 Redis | 收敛为按插件包记录用户安装选择、所选版本和 enabled;移除公开多实例管理与 Redis 中的任意业务 config,保留 Cordis 内部必要的加载条目 |+| `internal/executor/browser.go` | 固定 `/usr/local/bin/agent-browser`;管理会话 socket 与清理 | 改为通过 PATH 查找官方命令,保留 Go 资源隔离与清理 |+| `internal/executor/builder.go` | Host 启动时缓存浏览器 CLI 是否存在 | 移除该启动时判断,保证已经打开的会话也能使用后来启用的插件 |+| `extensions/catalog/plugins.json` | 正式清单为空 | 加入两个真正发布的插件;不是加入开发目录或未发布地址 |++## 4. 包与安装方式++建议源代码位置:++```text+extensions/+ plugins/+ agent-browser/+ package.json+ src/index.mjs # Cordis 装配+ src/prepare.mjs # 本地就绪检查+ scripts/install.mjs # npm/pnpm 标准 postinstall:准备官方运行包+ upstream.lock.json # agent-browser 的来源信息;OfficeCLI 不设额外版本/校验锁+ scripts/prepare-skills.mjs+ skills/ # 发布时由官方安装器生成,正文原样+ THIRD_PARTY_NOTICES.md+ officecli/+ ... # 相同职责划分,不要求建立空文件+```++插件包名建议为 `@go-bot/plugin-agent-browser`、`@go-bot/plugin-officecli`,各有自己的插件版本;插件版本与上游 CLI 版本分别记录。++安装包来源继续走现有受审清单。本次两份第一方包装包随 Host 镜像分发,清单使用受控 bundled 来源,从镜像内安装到 profile/node_modules。它们是随产品构建的正式包,不是用户指定的开发目录,也不依赖尚未发布的 npm 包或占位 release URL。后续独立发布可改为固定 HTTPS tarball。++用户操作为:**插件市场 → 安装 → 启用**。安装同时取得包装包、安装官方 CLI 并验证依赖,全部成功才返回安装完成;启用只验证并加载已安装的能力。正常使用无需填写 API Key 或 OAuth,也不显示授权入口。++建议取消这两项能力在基础镜像中的强制预装,改成市场中的推荐插件。首次安装后仍沿用现有“默认停用”的规则,不额外引入启动时自动安装或后台重试。++### 4.1 直接采用官方全局安装++在 Host 容器内,由插件自己的标准安装脚本决定 npm 安装命令。OfficeCLI 直接采用官方无版本号安装:++```sh+npm install -g [email protected]+npm install -g @officecli/officecli+```++不传 `--prefix`,不创建插件私有运行目录,不自行生成命令软链接或 launcher。npm 按自己的全局配置选择安装位置并创建命令入口。原生 Linux 下,全局命令位于 npm `{prefix}/bin`;具体 prefix 由 npm 环境决定,不在插件中写死 `/usr/local` 或 `/root/.local`。++OfficeCLI 官方 shell 安装脚本也是自行决定位置:已有命令则使用其原目录,否则使用 `$HOME/.local/bin`,不要求调用方提供目录。该脚本还会尝试配置 Shell 启动文件;但修改 `.bashrc` 不会改变已经运行的 Go Host 环境。本方案统一选官方 npm 安装,避免两条安装流程叠加。++插件安装和启用:++1. 安装、更新或重装 OfficeCLI 包时,标准 postinstall 直接执行 `npm install -g @officecli/officecli`,等待安装完成。版本由 npm 官方发布及插件自己的安装逻辑决定,Host 不附加 CLI 版本策略。+2. 启用只检查命令可以执行 `--version`、必需资源可用,并注册原始 Skills;不在 apply 内下载软件。不因 OfficeCLI 自身版本变化拒绝启用。+3. npm 沿用默认全局命令目录,Host 无需为 OfficeCLI 设置额外 PATH。基础镜像中的 Python 虚拟环境 PATH 与 OfficeCLI 无关。+4. 不增加 OfficeCLI 二进制 SHA256/版本锁,不设置 OFFICECLI_SKIP_UPDATE,不干预官方自身更新行为。官方 npm 安装器原本提供的下载与完整性校验保持原样。+5. 插件包版本与 CLI 版本相互独立。市场的“可更新”只对比包装插件的受审版本与实际已安装包版本;停用、启用不执行 npm 安装。++agent-browser 目前仍由它自己的安装脚本选择版本与官方 core 指南,不由 Go Host 硬编码 CLI 版本。++官方依据:[agent-browser 全局安装](https://agent-browser.dev/installation)、[OfficeCLI npm 用法](https://github.com/iOfficeAI/OfficeCLI/blob/v1.0.160/npm/README.md)、[OfficeCLI 官方 shell 安装脚本](https://github.com/iOfficeAI/OfficeCLI/blob/main/install.sh)、[npm 全局安装与命令目录](https://docs.npmjs.com/cli/v11/configuring-npm/folders/)。++### 4.2 统一安装框架与插件自有安装逻辑(最新决定)++**Host 统一编排安装,每个包声明自己的可选安装逻辑。安装不是 Cordis apply 的职责。**++职责分为三层:++| 层 | 职责 |+| --- | --- |+| Controller | 只接受受审 pluginId,确定固定版本和来源,保存用户安装选择,等待 Host 返回成功/失败;不执行 npm 或插件安装代码 |+| Go Host 包管理器 | 串行管理安装/更新/重装/卸载;检查包身份,调用统一 Node 包安装器;把最终结果与错误返回给 Controller |+| 插件包 | 声明自己需要的安装入口,完成该插件特有的 CLI/系统依赖准备与校验;普通纯 JS 插件无需额外安装入口 |++#### 4.2.1 直接使用 pnpm 标准安装机制++插件 package.json 声明普通 dependencies,并可提供标准 lifecycle scripts:++```json+{+ "name": "@go-bot/plugin-officecli",+ "version": "0.1.0",+ "type": "module",+ "exports": "./src/index.mjs",+ "scripts": { "postinstall": "node ./scripts/install.mjs" },+ "goBot": { "api": "1" }+}+```++具体准备代码在插件自己的 scripts/install.mjs 中,pnpm 在统一安装步骤执行。删除本轮中间实现的 goBot.install 字段、专用安装模块 RPC 和手动 import 调用;不另造一套安装生命周期。++Host 的统一包管理入口负责调用并等待 pnpm;执行权限使用原生 pnpm-workspace.yaml 的 allowBuilds。受审清单内部声明允许的包/依赖脚本,转换成精确 pnpm resolution;普通用户不能自行提交脚本放行规则。未获准的必需构建脚本使安装失败,不能全局允许所有脚本。纯 JS/API 插件无需额外脚本。++浏览、检查包必须禁用脚本;正式安装按受审规则执行脚本,pnpmfile 仍禁用。禁用 sideEffectsCache,防止包缓存命中跳过修改全局安装目录的 CLI 安装步骤。安装脚本先检查,满足版本即复用;失败抛错,不后台补装,不在安装中等待凭证交互。该机制是安装期包管理,与 Agent 工具审批无关。++#### 4.2.2 完整安装流程++1. 前端选择清单 pluginId;Controller 确认身份、版本和来源,要求 Host 已运行。+2. 仅检查包装包元数据,不运行其 apply 或安装脚本。+3. Redis 保存每个包一份 `{catalogId, version, enabled:false}` 用户选择。它表示用户意图,不等于已安装成功。+4. Host 统一安装包装包及 package.json 依赖到 profile/node_modules,由 pnpm 原生 allowBuilds 限定可执行的安装脚本。+5. pnpm 执行包中获准的 postinstall 等标准安装脚本,并等待完成;Host 核对实际包身份和版本。+6. OfficeCLI postinstall 执行无版本号的官方全局 npm 安装并确认命令可用;agent-browser postinstall 执行自身声明的官方全局 npm 安装及 core 指南检查。完整原始 Skills 随各包装包分发。+7. 包和运行依赖均检查成功才响应安装成功。安装期间前端显示进行中,失败显示错误并提供“重新安装插件”。不把“包文件存在”当作依赖安装成功。++#### 4.2.3 更新、重试和卸载++- **启用**:检查已经安装的 CLI 和资源,Cordis 执行 apply 注册 Skills;不下载、不安装依赖。缺依赖报错,要求重新安装。正常启用只包含本地检查和注册。+- **停用**:Cordis 撤销该包贡献;不卸载 CLI,不运行安装代码。+- **更新**:用户明确选择清单新版本;先撤销旧贡献,安装新包装包,再执行它的 install 并校验;原本启用的插件在成功后重新加载。失败明确返回,不伪称已回滚外部安装副作用。+- **重新安装**:显式重跑当前受审包的安装与依赖检查,修复失败或缺依赖;不新增后台重试任务。+- **卸载**:先撤销 Cordis 贡献,再删除包装包依赖;保留用户工作区、凭证和全局 CLI。软件依赖不等同于插件贡献,避免隐式删除其他流程仍在使用的命令。框架不增加自动删除系统依赖的通用逻辑。+- **Host 重启**:Controller 传入保存的选择;Host 恢复包和加载已启用插件。已有包不会因 apply 或停用而反复安装;本方案不处理 ECI/NAS 下 CLI 安装文件丢失的自动恢复。++普通 JavaScript 依赖由包管理器统一处理;这两个 CLI 插件用自身标准 postinstall;远程 API/MCP 包装插件通常没有系统依赖,不必声明安装脚本。Cordis 原生负责加载、依赖注入和资源生命周期,不接管上述包安装过程。++### 4.3 配置、凭证与 Redis 的明确边界++| 数据 | 负责方与保存位置 |+| --- | --- |+| 支持哪些插件、正式版本和安装来源 | 项目维护的 `extensions/catalog/plugins.json`,随 Controller 分发 |+| 插件代码、配置 schema/默认值、安装与初始化逻辑、原始 Skills | 插件包本身;安装到 Host 后随包保存 |+| 用户选择安装哪些插件、选择的版本、enabled | 账号 Redis Hash 的 plugins 字段;表示用户期望,不冒充实际运行状态 |+| 实际包是否存在、真实版本、加载成功/失败及错误 | Host 包管理器与 Cordis 实际状态,接口返回给前端,不作为 Redis 中的第二套运行状态机 |+| API Key、AccessKey/Secret、密码、OAuth client secret/token 等 | Go credentials 唯一存储;通过 authorization 或插件已有凭证流程取得,不放入 Redis 的插件设置或写回发布包 |+| 将来某具体插件确需的非凭证用户业务数据 | 由该插件按实际业务声明并在 Host 侧保存;不修改发布包源码,不因此预设通用 config 存储、表单或新 storage SDK |++包的配置定义与用户填写值不是同一份数据。当前这两个 CLI 插件无需用户输入业务参数或凭证,采用官方默认行为,不新增空泛的配置表单。账号名、项目名等若是某个授权流程采集的账号资料,也可作为该流程的 credential grant payload,不必另设业务配置。++Controller 的公开管理界面按插件包提供安装、启用、停用、更新和卸载;不再要求用户选择实例引用哪个包或创建第二份实例。Cordis 内部仍可使用其原生 entry/fiber 来装配一次插件,内部加载身份不等于 Redis 必须保存一套用户可管理的 instances。++Redis JSON、Controller/Host 管理合同、Go Client/OpenAPI、Web/Mobile 管理页面与测试均按此包选择模型实现。开发期直接更换该模型,不做旧 instances/config 的兼容或迁移。Cordis 内部装配身份仅用于运行与诊断,不成为用户配置。++### 4.4 不生成 Host 本地 plugins.json++仓库 extensions/catalog/plugins.json 是受审市场清单,继续保留。删除 Host 本地 plugins/profile/plugins.json 及其写入代码;Redis → Controller → Host → runtime.apply 已经完整传递期望配置,无需再落一份副本。Host 的 package.json、锁文件和 node_modules 只负责已安装包与依赖。++GET /v1/settings/plugins 的 settings 字段仅返回用户包选择、版本和启停;status 返回真实安装和 Cordis 运行结果。不存在第二份用户可编辑的 Host 设置文件。++## 5. Agent 最终获得的内容++### 5.1 agent-browser 插件++- 一个原生官方 `agent-browser` 发现 Skill,保留原始名称、摘要和正文。+- 一个可在 Go Shell 中直接使用的 `agent-browser` 命令。+- 命令继续读取官方 `skills get core`,再按需读取 reference、专项指南,不将这些指南预加载成另一套常驻系统提示。+- 使用 Host Chromium,默认无头运行;截图写工作区后仍用内置 readimage,交付仍用 present。+- 浏览器 socket、不同会话间的隔离、受限沙箱的临时环境继续由 Go 处理;不把 Shell 改为通过 Node 执行。++### 5.2 OfficeCLI 插件++一个 `officecli` 命令,加上当前官方完整的 11 个 Skill 目录:++```text+officecli+officecli-docx+officecli-xlsx+officecli-pptx+officecli-academic-paper+officecli-data-dashboard+officecli-financial-model+officecli-pitch-deck+officecli-word-form+morph-ppt+morph-ppt-3d+```++发布阶段使用插件安装的官方 CLI,在隔离 HOME 中运行已有官方 Codex 安装命令,再将生成目录完整放入插件包。包括 references、脚本、模板和二进制素材,不能只复制 SKILL.md,不能把目录合并或改写正文。++运行时使用 `ctx.host.skills.registerDirectory('skills')` 交给 Go 原生发现器。模型经现有 skill 工具加载,工作区文档继续由 Go Shell 调用 OfficeCLI 创建、编辑、验证和保存。没有自写的 Word/PPT/Excel 工具集合。++### 5.3 Skill 管理的变化++插件 Skill 是包贡献,不再作为首次启动 seed 复制到 `.dsh/skills` 或 `.agents/skills`。所以停用/卸载会撤销插件贡献,升级会随包切换。++用户自行安装或修改的 Skill 仍位于现有用户根,遵守原优先级;插件不会覆盖或删除它们。若用户主动复制了一份同名 Skill 到用户根,该副本属于用户,停用插件不会删除副本,CLI 的安装状态按下节的依赖管理规则处理。++本次不设计旧 seed 的自动迁移、目录猜测或覆盖删除;使用干净测试账号验证新流程。已有数据中的人工副本不会被当成插件文件清理。++## 6. 安装依赖与启停的边界++**不增加 `ctx.host.commands.register()`。** 官方全局安装已经完成程序位置选择和命令入口创建。Go Shell 通过标准 PATH 调用即可,SDK 不需要再登记一次命令。++安装插件时准备官方依赖;启用时仅核对就绪状态并注册原始 Skills;停用/卸载包装插件时撤销它贡献的 Skills。CLI 作为已安装的软件依赖保留,不把“停用插件”实现为系统命令权限开关,也不自动卸载可能被其他脚本或用户使用的软件。++如用户需要移除 CLI,使用对应官方卸载方式,例如 `npm uninstall -g agent-browser`,不为此建立 Go 命令所有权注册表或新管理接口。包装插件升级与系统 CLI 升级分别检查和报告,不能将前者成功等同于后者已升级。++### 6.1 Go 仍需保留的环境适配++- 浏览器命令通过 PATH 查找,去掉固定 `/usr/local/bin/agent-browser`。+- 不再于 Host 启动时缓存 CLI 是否存在;已有会话也能发现后来安装的命令。+- 保留不同会话的 socket 环境、受限沙箱的独立临时环境、会话关闭时的浏览器清理。+- Shell/Jobs 的执行、审批、取消与资源收尾仍由 Go 原有机制处理;不改为 Node 直接执行 Agent 的业务命令。+- 复用系统 Chromium时仅配置官方支持的浏览器路径;这与 CLI 的全局安装路径是两件事,不需要自定义 CLI launcher。++## 7. 文件与镜像边界++**按最新决定保留当前目录结构。** `$DSH_HOME/plugins/profile` 作为唯一的插件包管理项目:++```text+/root/harness/.dsh/plugins/profile/+ package.json+ pnpm-lock.yaml+ pnpm-workspace.yaml+ node_modules/+ @go-bot/+ plugin-agent-browser/+ package.json+ skills/agent-browser/SKILL.md+ plugin-officecli/+ package.json+ skills/+ officecli/SKILL.md+ officecli-docx/SKILL.md+ officecli-pptx/SKILL.md+ …其他官方 Skill 及配套资源+```++这是 npm/pnpm 包的逻辑访问路径;内部实际文件布局仍由包管理器负责。插件无需知道 pnpm store 的具体位置。++插件包附带原始 Skills,Go 从包内发现并加载;CLI 及其平台二进制使用官方/npm 全局安装位置,和上面的插件包位置分别管理。不建立 `plugins/runtimes`、managed-bin 或自有 launcher。++Manager、包管理 manifest 写入、Node 进程工作目录及包解析基准继续使用已有 profile 根;无需目录迁移。用户状态合同按第 4.3 节调整;`ctx.host.skills.registerDirectory('skills')` 的调用方式保持不变。++### 7.1 上游插件保存机制与本项目取舍++核对上游并澄清 profile 的 npm 项目含义后,用户决定当前目录没有问题。此前去掉 profile 层的提议已撤销;保留现有实现。++2026-11-20 查询上游默认分支 `master`,固定到 `2e39e70496aa02986ca6a820c5d497e816b69d7e`。上游将外部插件保存为某个 profile 的 pnpm 依赖:++```text+$DSH_HOME/profiles/<name>/+ package.json # 外部依赖与 dsh.profile.bundles 选择+ pnpm-lock.yaml # 依赖解析锁+ pnpm-workspace.yaml # 包管理配置+ cordis.patch.yml # 用户对插件条目的配置/启停覆盖+ node_modules/+ <package>/ # 插件包及其自带资源+```++`profile` 表示一套具名运行组合,例如 web、headless 或 sdk;不是所有插件都分别拥有一个 profile。`runProfilePnpm` 在 profile 目录执行 pnpm,包代码进入其 `node_modules`。上游还可使用安装发行物随附的包,并非所有内置核心包都重新下载到每个 profile。++需要补充 npm 层面的准确含义:`profiles/web` 本身确实是一个私有 npm 项目。`initProfile()` 默认生成名字为 `dsh-profile-web`、`private: true`、带 `dependencies` 和 `dsh.profile.bundles` 的 manifest;因此其 `node_modules` 存的确实是这个项目的依赖。这里的依赖包括安装进来的插件包,以及包管理器解析的第三方依赖。它在业务上不是“一个外部插件自己的源码根”。例如 web 模板同时选择 `@deepseek-ai/dsh-base` 与 `@deepseek-ai/dsh-web-app`;用户还可往同一 profile 安装其他 bundle。++应分清三个层次:profile 是组合/安装项目;bundle 是被该组合选择的 npm 包,可装配多个插件条目;Cordis 插件条目是实际加载的模块/实例。不能把“一个 profile 是一个 npm 项目”推断成“一个 profile 对应一个业务插件”。插件自身声明的库依赖可以被提升到 profile 的 node_modules,也可以依包管理结果位于更深位置;不保证每个插件都独占一份 node_modules。++本项目只有一个插件包管理项目,不提供上游的多 profile 产品模式。继续使用 `.dsh/plugins/profile`;`node_modules` 由 pnpm 管理,保留标准依赖安装与 Node 包解析。++另需区分:`npm install -g agent-browser` 安装的是 CLI 软件,沿用 npm 全局位置;Cordis 业务插件本身的安装是 profile 内的依赖安装。CLI 全局命令可访问,并不说明 Cordis 插件包也不需要依赖目录。++本次不改包管理目录,也不引入独立归档安装器或自定义模块解析体系。++源码依据:[profile 定义与初始化](https://github.com/deepseek-ai/deepseek-harness/blob/2e39e70496aa02986ca6a820c5d497e816b69d7e/packages/boot/app-boot/src/profile.ts)、[profile 内 pnpm 操作](https://github.com/deepseek-ai/deepseek-harness/blob/2e39e70496aa02986ca6a820c5d497e816b69d7e/packages/boot/plugin-manager/src/operations.ts)。++两者的官方安装器负责选择当前 Linux 架构。本文不额外设计安装文件的 ECI/NAS 持久化、备份或自动恢复。++Host 镜像本次保留 Go、Node/npm/pnpm、Python、Chromium、字体、LibreOffice 与现有通用文件处理环境。只移出两套 CLI 和专用 Skills seed 的预装步骤,不把基础 Linux 环境也扩展成插件安装系统。基础 PATH 保证官方全局安装后的命令可由非交互 Go Shell 访问,不要求用户配置路径。++删除专用 scripts/update-officecli.py 与 OfficeCLI 的额外版本/校验锁。安装策略归 OfficeCLI 包自己的 postinstall;build/dependencies.lock.yaml 只保留其他仍需记录的依赖。++## 8. 前端、文档与发布++- 两端沿用插件市场入口,Web 桌面两列条目、窄屏一列,移动端单列竖向。+- 每个条目按包内 plugin.json 显示图标、原始名称和 description 摘要;点击主体进入独立详情。未安装右侧 + 执行安装,已安装 … 打开详情/重装/卸载菜单;点击外部和 Escape 收起,移动端使用既有底部 Sheet。+- 详情显示身份、description、版本/维护者/许可证;安装和启停为主操作,不再在列表内展开长说明。安装中给出进度与禁用重复操作,失败显示诊断、可重新安装。+- 图标由插件包 plugin.json 的 icon 指定后端图片路径,例如 /assets/plugins/agent-browser/icon.png。图片资源保存在各插件的 assets/ 目录,由 Controller 直接提供;两端只渲染返回的图片 URL,不维护品牌枚举、产品映射或 SVG 绘制逻辑。agent-browser 使用 Chrome 图标,OfficeCLI 使用原始 GitHub 仓库所属 iOfficeAI 的头像;原始名称为 agent-browser 和 OfficeCLI,不翻译产品名称。+- 视觉参考用户截图与 Taste Skill 的等边界、真实图标、克制线框、层次和 44px 点击区;保留当前应用整体浅色风格。[Taste Skill](https://github.com/Leonxlnx/taste-skill/blob/main/skills/taste-skill/SKILL.md)+- 按包展示启停与安装结果,移除新增/选择/删除多实例的用户入口;这两个插件不显示业务配置表单。认证入口仍只按插件实际提供的 authorization/MCP OAuth 能力展示。+- 不新增 Settings 页面、API Key 表单或 MCP 传输方式选择。+- 准备期间沿用加载状态,失败展示安装/版本/网络错误;准备成功才显示就绪。安装操作是同步等待结果,不引入后台循环。+- README 的能力介绍仍说明支持浏览器和 Office,但 Quickstart 增加“在插件市场安装并启用这两个插件”的操作;不能继续声称基础 Host 镜像已预装。+- 插件发布包保留上游 LICENSE/NOTICE 和来源版本;上游 Skills 原文随对应插件版本分发。+- 已有镜像冒烟改为基础环境检查;两套 CLI/Skills 检查移到安装插件之后。沿用已有 CI 作业,不增加新的 CI 作业类别。++## 9. 实施顺序与验收++1. 保留包管理目录,先收敛 Redis/管理接口/前端的按包用户状态合同,清理多实例业务配置;核对官方默认全局 CLI 安装、标准 PATH 和动态浏览器发现。+2. 制作两个 Cordis 包,由包自己的 postinstall 声明官方 npm 安装方式,并生成原始 Skill 资源。+3. 先在干净 Host 完成安装和真实调用,再移除镜像的专用预装;避免删掉旧入口后新入口仍不可用。+4. 将真实包装包随 Host 构建分发,内置市场引用受控 bundled 来源;更新双语文档和两端说明。++验收项目:++- Redis 插件字段仅记录用户安装选择、所选版本和 enabled;无用户可管理的 instances 列表、任意业务 config 或明文凭证。实际状态来自 Host;两端按包管理,凭证流程继续使用唯一 Go Store。+- 插件包装包位于现有 `$DSH_HOME/plugins/profile/node_modules`;完整安装/更新/卸载和 Skills 加载正确。+- amd64/arm64 的官方二进制安装、实际版本输出与 CLI 帮助均正常;不额外限制 OfficeCLI 版本或二进制校验值。+- agent-browser discovery Skill 与上游一致,`skills get core` 由相同版本提供;OfficeCLI 11 个目录及引用资源完整。+- 真实浏览器打开、snapshot、交互、截图和下载;不同会话浏览器隔离,归档/会话关闭后的清理仍正确。+- 创建并多轮编辑 Word、PPT、Excel;保存后用现有读取/渲染能力验证成品,readimage 与 present 仍按原协议展示。+- 已打开会话在插件启用后能使用命令;停用后 Skill 贡献消失,已安装 CLI 保留;重新启用、更新与卸载不误删用户数据。+- read-only、workspace-write、danger-full-access 的执行语义不因 CLI 来自插件而改变,受限命令不能连接此前全权限的浏览器 daemon。+- 下载失败、命令不可执行、PATH 不可见、缺资源和插件准备取消均明确报错,不出现假就绪;OfficeCLI 正常的版本变化不作为错误。+- Host、Controller 与 Android 现有构建/回归通过;Web/Mobile 插件安装、启停和失败表现真实可见。++本方案已按后续更新决定实施,验收记录见第 11 节。++## 10. 上游包安装管理核对++固定上游提交 2e39e70496aa02986ca6a820c5d497e816b69d7e。++- app-boot/initProfile 创建私有 npm 项目、package.json、pnpm-workspace.yaml 与用户 patch。node_modules 同时保存插件及其依赖。+- plugin-manager/installBundle 检查源、平台和兼容性,统一调用 runProfilePnpm 执行 pnpm add;不要求插件导出 Harness 专用 install 函数。+- 普通库依赖使用 package.json.dependencies;安装/构建步骤使用 npm/pnpm lifecycle scripts。上游记录被阻止的构建项,用户批准后写入原生 allowBuilds 并重新安装。不是把全部依赖脚本无条件放开。+- 包安装成功后,再选择 bundle、读取 dsh.bundle.patch 并更新 Cordis;installBundle 默认可激活,也支持 enabled:false。用户单独启停时改配置并重载,不执行 pnpm add/remove。+- 卸载先取消选择、撤销运行条目,再 pnpm remove。更新有自己的旧版本撤销、安装新版本和失败恢复流程;包文件回滚不代表任意外部副作用能自动回滚。+- 上游保留安装日志、取消、兼容检查与结果阶段;本项目保留同步等待/明确失败,不复制多 profile、核心插件 bundle/patch、任意市场地址、运行时 HMR 等产品组织形式。++对应本项目:Go Host 持有安装操作和取消;Node 适配仅调用 pnpm,按原生构建规则执行包内脚本;Cordis 负责加载和撤销贡献。两个包装插件仍采用官方全局 npm CLI 安装,作为各自 postinstall 的业务内容,不放在 apply 中。项目受审市场预先提供这两个包装包声明的标准安装脚本的放行,不额外增加用户审批页面。++源码:[统一包操作](https://github.com/deepseek-ai/deepseek-harness/blob/2e39e70496aa02986ca6a820c5d497e816b69d7e/packages/boot/plugin-manager/src/operations.ts)、[包管理与启停](https://github.com/deepseek-ai/deepseek-harness/blob/2e39e70496aa02986ca6a820c5d497e816b69d7e/packages/boot/plugin-manager/src/index.ts)、[原生构建批准](https://github.com/deepseek-ai/deepseek-harness/blob/2e39e70496aa02986ca6a820c5d497e816b69d7e/packages/boot/plugin-manager/src/build-approval.ts)。++### 展示元数据与可更新状态(2026-11-20 补充)++每个插件包提供 plugin.json:name(原始名称字符串)、description(中英文描述)、icon(后端图片路径)、version、maintainer、license。不再提供 capabilities、setup、connection 三套重复展示字段。version/license 与 package.json 一致,构建时校验;市场清单只记录包身份、固定来源和构建脚本策略。Controller 构建内置包内元数据,通过管理 API 提供给两端,前端按字段渲染。++Web 详情返回与顶部返回都回插件市场;移动端详情返回同样回市场。市场版本比 Host 实际已安装版本更高时,后端按 SemVer 提供 availableVersion,两端列表标记“可更新”,详情展示当前/可用版本及更新操作。不能用 Redis 中的期望版本代替实际安装版本;相同版本、构建元数据变化、降级均不标记可更新。++这里对比的是市场中受审版本的 plugin.json 元数据与 Host 实际安装包的版本,而不是读取已安装包自身的 plugin.json 与自身比较。只有市场发布了更高版本才显示更新。用户点击后走统一 pnpm 更新流程;更新成功保留原 enabled 状态,并用新包替换旧贡献。失败返回实际错误,实际安装版本不因 Redis 已保存目标版本而被虚报为更新成功。+++## 11. 最终实现与本地验收(2026-11-20)++- OfficeCLI 和 agent-browser 均为受审市场中的可选 Cordis 包。安装通过统一 pnpm 流程执行各包的标准 postinstall;启用只检查现有能力并注册原始 Skills,停用撤销贡献,卸载保留全局 CLI 与用户文件。+- OfficeCLI 的安装命令为 `npm install -g @officecli/officecli`。已移除额外二进制 SHA256/版本锁、专用更新脚本、OFFICECLI_SKIP_UPDATE,以及 Host 对 CLI 版本变化的拒绝。两种 Linux 架构实际安装取得 1.0.163,官方安装器均导出完整 11 个 Skills;官方自身安装校验与更新行为保持原样。+- Host 保留 Node、Python、Chromium、LibreOffice 等基础环境,基础镜像没有两套 CLI;包装包和原始 Skills 随镜像分发。已删除 seed 初始化及本地 plugins.json。Redis 仅保存每个包的 catalogId/version/enabled。+- plugin.json 提供原始名称、中英文 description、后端 icon 路径、包装包 version、maintainer、license。图标位于各插件 assets/,Controller 提供图片端点;两端使用返回 URL 渲染,不维护品牌图标映射或 SVG 绘制。未安装插件或未运行 Host 时也能读取市场图标。+- 市场版本与 Host 实际已安装包按 SemVer 对比。更新测试覆盖旧版本仍可启停、明确更新、保留 enabled、新工具回调替换和消除可更新标记;不以 Redis 的目标版本冒充成功安装。+- Go 全量测试与 vet 通过;Node 契约与原生 pnpm 生命周期测试 12 项通过;Web 测试 19 项通过,Web 构建及移动端类型检查通过。+- Host、Controller 镜像与 Android ARM64 QA APK 构建成功;基础镜像冒烟及 Docker 全量回归通过。回归包含插件安装、动态浏览器发现、真实 Chromium 操作/截图/下载及会话隔离、Office 会话恢复、Redis 用户字段、SSE、权限、模型设置、记忆与定时任务。最终 Docker 全量运行约 84 秒。+- 真实 OfficeCLI 创建并再次编辑 Word、PPT、Excel,核对修改后的 OOXML 文本、单元格值、公式与计算值,并分别导出 PDF。无版本限制的 1.0.163 仍可读取已有验收文件。+- Web 实测双列市场、窄屏单列、原始名称和描述、真实安装/重装进度、启停、菜单外部收起、详情返回市场;确认图片 DOM 指向后端路径并成功加载。Android 模拟器已安装最新 QA 包,实测单列市场、后端图片加载、详情、停用/就绪状态切换及返回市场。截图与日志保留在本地忽略目录,不作为项目运行依赖。++本轮未验证 ECI/NAS、iOS 或发布新的商店/Release 安装包;未提交或推送仓库内容。diff --git a/docs/anthropic-model-protocol-plan.zh-CN.md b/docs/anthropic-model-protocol-plan.zh-CN.mdnew file mode 100644index 0000000..8303606--- /dev/null+++ b/docs/anthropic-model-protocol-plan.zh-CN.md@@ -0,0 +1,229 @@+# OpenAI / Anthropic 模型协议接入与设置交互方案++状态:已实施并完成本地验收。日期:2026-11-18。++## 1. 目标与范围++在现有“一个端点对应一个 API Key、多个模型”的模型设置中,增加 Anthropic Messages 兼容协议。Web 和移动端均可配置,并可在同一会话中切换两类协议的端点。++本次面向 Anthropic 官方 API,以及实现相同 Messages 协议的第三方服务。使用 API Key 认证;Bedrock、Vertex、Claude 订阅登录和云平台 IAM 不属于这个适配器。++接口协议属于端点,不属于模型或会话。模型名字不能决定协议:提供 Claude 模型的服务也可能使用 OpenAI 协议,应以服务商提供的接口为准。++## 2. 当前实现与需要修改的位置++- `internal/modelsettings/settings.go`:端点包含 name、baseUrl、apiKey、models,没有协议。+- `internal/controller/models.go`:负责端点校验、保存、公开视图和同步;读取设置只返回 hasApiKey,不返回密钥。+- `internal/controller/model_store.go`:Redis 的 `user:<userId>` Hash 中,`llm` 存端点目录,`sessionModels` 存会话选择。+- `internal/host/model_settings.go`:按会话选择构建模型路由,但当前把协议固定成 `llm.Responses`。+- `providers/model/mainmodel/model.go`:按当前 turn 的模型配置创建调用客户端。+- `thirdparty/llm`:已有 Responses 和 Chat Completions 编解码、流式调用,没有 Anthropic 实现。+- `harness/agent/llm_adapter.go`:完成模型上下文和内部消息的转换;工具返回的图片当前会拆为额外用户图片消息。+- `harness/agent/llm_stream_projection.go`:将供应商增量转成 Harness 的有序内容块。+- `frontend/src/settings/Models.tsx`、`mobile/src/Me.tsx`:目前明确提示只支持 OpenAI Responses。++继续复用现有 Controller → Host 配置同步和按 turn 固定模型的机制,不增加进程、Redis key 或配置文件。++## 3. 数据结构++端点只增加 `protocol`,使用值:++| 值 | 设置页名称 | 请求路径 |+| --- | --- | --- |+| `responses` | OpenAI Responses | `<baseUrl>/responses` |+| `anthropic_messages` | Anthropic Messages | `<baseUrl>/messages` |++底层已有 `chat_completions` 继续作为内部能力保留,本次不顺带增加第三个设置页选项。未提供 protocol 的既有端点按 Responses 解析;显式提供未知值直接报错。++Redis 示例,仍为 `user:<userId>` 的 `llm` 字段:++```json+{+ "defaultEndpointId": "endpoint-a",+ "endpoints": {+ "endpoint-a": {+ "name": "Main endpoint",+ "protocol": "responses",+ "baseUrl": "https://api.example.com/v1",+ "apiKey": "<用户保存的密钥>",+ "models": ["model-a", "model-b"]+ },+ "endpoint-b": {+ "name": "Claude",+ "protocol": "anthropic_messages",+ "baseUrl": "https://api.anthropic.com/v1",+ "apiKey": "<用户保存的密钥>",+ "models": ["<服务商提供的模型 ID>"]+ }+ }+}+```++`sessionModels` 保持:++```json+{+ "session-id": { "endpointId": "endpoint-b", "modelId": "model-id" }+}+```++不在 sessionModels 重复存协议、URL 或 API Key。公开设置接口增加 protocol,密钥仍只返回 hasApiKey。Host 获取包含协议的既有设置快照;镜像和客户端静态资源不包含密钥。++## 4. Web 设置交互++### 4.1 端点列表++沿用当前清爽的设置页及侧栏。每张端点卡展示:++- 名称,默认端点标记。+- 次要信息:协议标签、Base URL、密钥是否已保存。+- 模型列表,第一项标为默认模型。+- 编辑、设为默认、删除继续使用现有操作体系。++协议标签使用小号中性描边,不为不同协议引入大面积品牌色。页面说明改为“支持 OpenAI Responses 和 Anthropic Messages 兼容接口”。++### 4.2 新增与编辑++字段顺序:名称 → 接口协议 → Base URL → API Key → 模型列表。++协议使用下拉表单(用户最终确认),包含两个选项,附短说明:++- OpenAI Responses:适用于提供 Responses 接口的服务。+- Anthropic Messages:适用于 Anthropic 官方及 Messages 兼容服务。++新增端点默认 Responses;没有默认模型名。新建表单的官方地址按协议预填;用户可填写代理地址。编辑已保存端点时不自动替换已有 URL、模型和密钥。++切换协议时,仅当 URL 仍为空或为表单自动填入且未编辑的官方地址,才跟随切换默认地址。用户手填的代理地址保留。协议变化后仍需明确点击保存,不即时影响运行。++Base URL 约定包含 API 前缀,不包含最终操作路径。例如 Anthropic 填 `https://api.anthropic.com/v1`,下方展示只读的最终请求地址 `https://api.anthropic.com/v1/messages`。若填入 `/messages`、`/responses` 等操作路径,提示填写 API 基础地址,不静默产生双重路径。++模型列表以一行一个模型的轻量行编辑呈现,提供添加、移除、上移/下移;第一项有“默认”标记。保留模型 ID 手动填写,不依赖服务商模型发现接口。模型列表示意文字不能作为真实配置自动保存。++保存只做配置校验及同步,不偷偷发起付费模型测试。保存成功也不表述为“模型调用验证成功”。请求中的鉴权或模型错误在实际调用时明确显示。++编辑密钥留空表示保留;更换 URL 的来源时沿用现有逻辑,要求重新提供密钥。新增端点无密钥不能保存。字段错误展示在字段附近,避免只有一个泛化失败提示。++下拉菜单点外部或 Esc 收起;全表单编辑不是点背景就丢弃输入。若使用关闭按钮且有未保存修改,需确认是否放弃。++## 5. 移动端设置与会话模型选择++移动端沿用“我的 → Settings → 模型”的底部面板风格,列表卡片展示名称、协议、默认标记和模型摘要。编辑面板内使用与 Web 同样的字段、校验和默认值规则。++协议下拉表单撑满可用宽度,展开为锚定字段的选项面板,点外部收起;输入 API Key 和 URL 时关闭自动纠正。键盘弹起后可滚动到保存按钮,避免层叠多个底部面板。轻量选择面板点遮罩收起;有修改的编辑表单通过关闭或返回处理放弃确认。++Web 与移动端会话输入框继续展示“端点 / 模型”。展开后在端点名称旁展示小号协议标签,模型列表维持单选。不让用户在每次发消息时重复选择协议。++选择模型成功后收起;失败时保留选择面板并展示原因。不新增全局“当前协议”。语言文案同步支持简体中文、英文,使用既有本地语言设置。++## 6. Host 与协议适配++### 6.1 职责++Controller 校验并同步协议;Host 使用当前 turn 选定的端点直接访问模型。Harness 负责 Agent 循环、工具执行、审批、队列、记忆和 compaction。++Anthropic 编解码、鉴权、HTTP/SSE 处理放在 `thirdparty/llm`,如 `encode_anthropic.go`、`decode_anthropic.go`、`stream_anthropic.go`。沿用统一 Request、Response 和调用入口;文件分离即可,不再包一套多层 provider 注册框架。++HTTP 请求默认采用 `x-api-key`、`anthropic-version: 2023-06-01`,请求 `/messages`。该兼容基线由代码固定,不增加设置项;不自动转发用户自定义任意 Header,也不将凭证发送到重定向来源。新 API 版本和平台专用认证可作为独立扩展。++### 6.2 请求与工具++| Harness 内容 | Anthropic Messages 投影 |+| --- | --- |+| 系统提示、记忆及技能说明 | 顶层 `system`,保留既有内容与优先级 |+| 用户文本、图片 | user.content 中的 text / image |+| 助手文本、工具调用 | 同一 assistant.content 内有序的 text / tool_use |+| 工具返回 | 随后的 user.content 中的 tool_result,按 tool_use_id 对应 |+| 工具 JSON Schema | tools[].input_schema |+| 工具错误 | tool_result.is_error |++并行调用的一组工具结果放在同一后续用户消息内,结果块在普通文本之前。不得把 steer 文本插入工具调用和对应结果之间。++工具返回的图片在 Anthropic 路径下保留在对应 tool_result 内,复用附件系统读取字节;不复制一套文件,也不拆成不相关的用户图片消息。需调整现有公共投影,保留工具结果与图片的关联,再由各协议编码器决定 wire 格式,避免破坏 Responses 行为。++普通 file 交付继续使用当前 present 和路径下载机制,不顺带接入 Anthropic Files API。工具由 Host 执行,不自动开启 Anthropic 的托管搜索、代码执行或托管电脑。++### 6.3 必填参数与停止原因++Anthropic 的 max_tokens 在调用侧填入:默认 16,384;compaction 等内部调用有显式预算时使用其预算。不新增 env 或用户表单字段。供应商或特定模型不接受该预算时明确报错,不静默改模型。++不把现有 OpenAI reasoning.effort 原样发送给 Anthropic。通用兼容路径默认不发送专属 thinking、缓存及 beta 参数;模型自己返回的 thinking 仍须正确处理。特定模型额外参数的支持不靠模糊匹配模型名字猜测。++end_turn / stop_sequence 表示正常结束;tool_use 进入既有工具循环;max_tokens 映射为既有截断处理,未完整的工具参数禁止执行。refusal、pause_turn、context-window 错误等分别识别,不把任意 stop_reason 都当完成,也不自动引入服务商托管工具续跑。++### 6.4 流式事件++解析 message_start、content_block_start/delta/stop、message_delta、message_stop、ping、error,按 block index 累积文本与工具参数。收到半个 JSON 时只更新流式显示;完整成功响应后才能提交可执行工具调用。++在 `llm_stream_projection.go` 增加显式 Anthropic 映射,输出当前 Harness block-start、text-delta、reasoning-delta、tool-call-delta、block-end 和完成事件。前端继续使用现有内容块和 SSE,不解析原始 Anthropic 协议。++message_stop 是一次模型请求结束,tool_use 情况下不是整个 Agent turn 结束。使用既有 turn 生命周期决定“生成中”何时结束。++流中 error、异常 EOF、超时与取消正确落为失败或中断,不能把部分输出误认成功。已产生可见输出后的重试必须遵循现有 attempt 隔离,不能重复追加文本或执行工具。++Token 统计合并消息起始及增量 usage;正确区分普通输入、缓存读取、缓存写入,避免把缓存重复计入。缺少 thinking token 数量时不伪造。++## 7. Thinking、会话恢复与跨协议切换++当前通用助手块没有原生 thinking signature 等信息,不能只加入一个 HTTP 编码器就宣称完整支持。++在现有会话日志中的助手记录旁增加可选、带来源标记的协议数据,保存原始有序助手 content,包括 thinking signature、redacted_thinking。来源包含 endpointId、modelId、protocol 和端点地址。数据随现有助手提交一起保存,不增加 memory-snapshot.json 或另一套会话文件,不含 API Key。++这部分是模型回放元数据,不作为普通 file/image 或聊天文字发送给前端。同一路由继续调用或恢复时,按 API 要求回传原始块;不从 UI reasoning 摘要重建 signature,不修改原始 thinking 内容。++换端点或模型后,仅复用可移植的用户消息、助手文本、工具调用/结果、附件和 compaction 摘要,不把原服务商的签名、响应 ID 当新服务商可接受的参数。来源不同的 thinking 不伪造签名;如需保留其可见语义,只作为普通历史说明,不作为已验证 thinking。++当前 turn 的端点、协议、模型与凭证按现有 pinTurnModel 固定。生成时切换会话模型,当前 turn 继续用原快照,下一轮生效;UI 提示“将在下一轮使用”。不会在工具执行一半时切换供应商。子 Agent 继承当前主 Agent 的模型路由,不增加 profiles 配置。++Compaction 继续由 Harness 管理,摘要是普通文本,不启用服务商原生压缩替代它。原生 thinking 不能只裁剪一半;保留区间维持完整助手消息和工具配对,压缩掉的部分不在恢复时重新拼回。切换协议后继续使用同一长期记忆和工具体系。++现有 100 万 token 上下文默认值不因本次新增协议而偷偷调整,也不把它宣传为所有兼容模型都支持。较小窗口模型可能提前返回上下文超限;需接入明确的上下文错误识别及有限的 compaction 恢复,恢复失败明确提示。若要完整适配任意窗口,需另行决定模型容量信息的配置或发现方式,不能仅凭协议推断容量。++## 8. 配置检查与错误表现++保存时检查协议枚举、URL、密钥、非空去重模型列表;GET 不泄露密钥。未知协议不回退成 Responses。++Host 同步时再次检查协议与目录有效性;正常 Docker / ECI 启动与 Redis 结构不变。没有默认端点时继续阻止创建会话,不构造隐式模型。++实际调用区分:鉴权失败、余额或限流、模型不可用、路径/协议错误、上下文超限、图片不被支持、流中错误。不展示含密钥的原始请求。配置已保存但 Host 应用失败,沿用当前明确提示,不能显示为已成功生效。++删除端点后,引用它的会话显示模型不可用,提示重新选择,不擅自换到另一个可能计费的供应商。++## 9. 实施顺序与验收++1. 扩展端点字段、Controller API、Redis JSON 和 Host 路由;保留现有 Responses 默认。+2. 实现 Anthropic 非流式、流式与工具/图片编解码;接入现有错误与 token 统计。+3. 完成有来源的原生块持久化、恢复、compaction 和跨协议切换。+4. 修改 Web 与移动端模型设置、选择器、中英文提示。+5. 更新模型接入文档和 README 中的兼容协议说明。+6. 全量构建 Controller、Host、Web 与移动端测试包,再做端到端检查。++自动测试使用本地 HTTP/SSE fixture,覆盖文本、并行工具、参数分片、工具图片、thinking 原样回传、截断、失败、usage、取消及双向协议切换。额外覆盖会话重载、Host 重启后的同路由恢复和 compaction 后工具配对,不能只有单轮问答。++真实调用使用已确认可用的 Anthropic 兼容端点,不假定 OpenAI Key 同时适用。真实验收控制为一次简短 shell 工具任务及一次无工具追问,其余协议边界、恢复和切换使用本地 fixture 验证,避免额外模型开销。++Web 与移动端都查看新增、编辑、协议选择、外部点击收起、错误、生成时切换提示的真实截图;沿用现有清爽浅色风格,不为本次协议能力重做整体主题。++## 10. 官方参考++- [Anthropic Messages:2023-06-01 兼容基线](https://platform.claude.com/docs/en/api/messages/create?version=2023-06-01)+- [API 版本](https://platform.claude.com/docs/en/api/versioning)+- [工具调用与工具结果顺序](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls)+- [流式 Messages](https://platform.claude.com/docs/en/build-with-claude/streaming)+- [Thinking 文档](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)++上述官方说明用于确认协议约束;本方案中的设置布局、Redis 字段和实施步骤是 go-bot 的设计选择。++## 11. 本地验收记录++2026-11-18:++- `make test vet check` 通过;普通测试不需要真实模型凭证。+- `go test -race ./thirdparty/llm ./harness/agent ./internal/controller ./internal/host` 通过。+- Web 构建及 11 项前端测试通过;移动端 TypeScript 检查通过。+- Controller、Host Docker 镜像构建通过;Android ARM64 Debug 和 iOS 模拟器 Debug 构建通过。+- Docker fixture 验证跨协议切换、当前轮固定路由、Host 重启后的模型选择恢复,以及 Web 聊天链路。+- 使用阿里云 Anthropic 兼容接口与 `deepseek-v4.1-flash` 完成两轮真实会话:一次 shell 工具调用产生 `anthropic-tool-ok`,后续追问正确引用结果;三个助手模型步骤、一次工具执行,两轮正常结束,无失败 attempt。+- 通过浏览器与 iOS 模拟器检查协议下拉表单、选项切换、自定义地址保留、保存回显和移动端点外部收起;移动端可读取同一真实测试会话。+- Anthropic 官方 Claude 服务和 ECI 本次未作真实调用验证;兼容协议边界由本地 HTTP/SSE fixture 覆盖。++截图、构建日志与真实凭证均未加入源码仓库。Go 客户端和 OpenAPI 定义也已补齐端点协议字段。diff --git a/docs/api.md b/docs/api.mdindex 9b0ec5f..c7c58f3 100644--- a/docs/api.md+++ b/docs/api.md@@ -25,7 +25,8 @@ Serve a custom browser UI from the same origin as the Controller API, or use the| POST /v1/sessions/{id}/messages | JSON content or multipart content/files/images || GET /v1/sessions/{id}/events?after=&limit= | Durable events and nextCursor for active or cold sessions || GET /v1/sessions/{id}/transcript?before=&limit= | Web transcript, paged by whole turns for active and cold sessions |-| GET /v1/sessions/{id}/stream?view=chat | One Web SSE stream for the session, including the transcript projection, queue, permissions and questions |+| GET /v1/host/stream?cursors= | One account Host SSE per client, multiplexing all session chat events and task catalog changes |+| GET /v1/sessions/{id}/stream?view=chat | Optional single-session chat projection for specialized clients; bundled clients use the Host stream || GET /v1/sessions/{id}/stream | Native SSE, with `Last-Event-ID` or `after` for both views || POST /v1/sessions/{id}/queue/{messageId}/steer | Move one queued user message into the current turn's next step || DELETE /v1/sessions/{id}/queue/{messageId} | Remove one queued user message |@@ -74,9 +75,14 @@ the tool, original tool call ID, reason, operation detail and optional targetmode. The pending item's top-level `callId` identifies the decision.POST an answer like `{"answers":[{"id":"approval","selected":["Allow once"]}]}`to allow the pending operation. Use `"Deny"` to reject it. An approval never-changes the saved mode. A turn without an interactive chat stream fails a-request for approval closed, including scheduled work targeting an unopened-chat. A pending decision expires after two minutes.+changes the saved mode. A Host stream provides an interactive audience for all+its sessions, including scheduled work in newly created or unopened chats.+Without any interactive answerer, an approval returns unavailable and the+action does not run. Pending approvals have no fixed timeout. Disconnecting+after a request was created does not cancel it; reconnecting restores the+pending state. Turn cancellation or Host shutdown ends the wait. The bundled+clients show approvals inside their owning chat, with pending indicators in+the chat list; they never present a global approval dialog.The chat stream and transcript expose successful `present` calls as`assistant/message` events with `delivery: true` and `file` blocks. A block@@ -121,6 +127,183 @@ running Host. Public responses omit keys. A response of`503 settings_saved_host_apply_failed` means the setting was saved but therunning Host did not confirm it. Retry or reopen the account.+## Plugins++The account Redis `plugins` field contains only per-package selections:++```json+{"packages":{"@go-bot/plugin-officecli":{"catalogId":"officecli","version":"0.1.0","enabled":false}}}+```++The Controller resolves reviewed sources while sending Host-private commands.+Go owns installation and the core Harness; Cordis owns plugin loading and+resource lifetimes. No Host Redis client, local plugins.json, public multi-instance+configuration or background retry is used.++| Method/path | Purpose |+| --- | --- |+| GET /assets/plugins/{pluginId}/{file} | Public static image declared by plugin.json; available before Host startup or plugin installation |+| GET /v1/settings/plugins | Reviewed catalog, user package selections, actual Host state |+| POST /v1/settings/plugins/packages | Install `{pluginId}`, including declared CLI dependencies; disabled initially |+| PUT /v1/settings/plugins/packages/{name} | Set `{enabled}` for one installed plugin |+| POST /v1/settings/plugins/packages/{name}/update | Explicit update or reinstall from the reviewed `{pluginId}` |+| DELETE /v1/settings/plugins/packages/{name} | Withdraw contributions and remove package; retain credentials, files and globally installed CLI dependencies |+| POST /v1/host/plugins/runtime/restart | Restart Cordis and apply saved selections |++The catalog includes the first-party agent-browser and OfficeCLI packages shipped+with the Host. Other reviewed sources may be fixed npm versions, pinned Git commits+or fixed HTTPS archives. Clients cannot submit source URLs, directories or arbitrary+business config. Catalog maintainers must retain selected versions for supported+releases; users explicitly update to a new version.++Installation checks metadata without executing business setup, saves user intent,+installs the wrapper and dependencies through pnpm, including native lifecycle+scripts allowed by the reviewed build policy. pnpmfile hooks remain disabled. Only success of all steps+completes installation. Activation only checks local readiness and registers+capabilities. A failed setup requires explicit reinstall; no automatic background+retry is scheduled. Enabled plugins are reloaded after a successful update.++The response has catalog, settings and status. status.packages describes real+package files; status.instances is diagnostic information from native Cordis+entries, not user-editable instances. A package file being present alone does+not certify successful dependency setup. A failure after saving returns+502 settings_saved_host_apply_failed with actual status. Plugin install methods+are synchronous requests and may take several minutes.++Package mutations serialize separately from account operations. Installation does+not block chat, model settings or read-only plugin views, and adding a new package+keeps existing Cordis contributions available during dependency preparation. Web+and mobile retain the pending request when navigating away from the plugin screen;+returning shows its progress or result without submitting it again. Other package+mutations remain disabled while that client's request is pending. This does not+turn installation into a detached server job: closing/reloading the browser or+terminating the app can still cancel its request.++### Developing a plugin++Use the [local SDK](../extensions/sdk/README.md) and [examples](../examples/plugins/README.md).+A compiled JavaScript package registers business capabilities through `ctx.host`:++```ts+export const inject = ['host']+export async function apply(ctx) {+ await ctx.host.tools.register({+ name: 'lookup', description: 'Look up information in an external service.',+ inputSchema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] },+ async execute(args, call) {+ call.signal.throwIfAborted()+ return { content: [{ type: 'text', text: 'Service result' }], data: { found: true } }+ },+ })+}+```++All Go-facing SDK methods return Promises. Cordis owns dependencies, fibers and+cleanup. Registration becomes visible after Go confirms it, and native disposal+retracts it. Tools are named `<instanceId>__<toolName>` and execute through the same+Go stages as built-ins. Only their business callback crosses RPC; no tool-stage+middleware, `next`, global guard or Agent/Session proxy is exposed. Plugin results+contain ordered text blocks and optional JSON data. Existing Go tools handle+images and `present` file delivery; plugins cannot invent attachment/log facts.++The SDK also exposes Skills, appended prompts, credentials, authorization, MCP,+and active-tool approval/question requests. See [the full type contract](../extensions/sdk/index.d.ts).+Native `ctx.on` subscribes to the documented `host/*` state notifications; their+return values do not change execution. Local Cordis services/events keep their+native semantics. Plugins are trusted container code, not sandboxed subprocesses.++### Credentials and authorization++Plugin records are stored in `$DSH_HOME/.credentials.yaml`, keyed by instance+and the plugin's local credential key. API keys and OAuth grants share the Go+Store. A plugin can register an acquisition flow that prompts for a key, opens+an OAuth/device flow, exchanges tokens and commits a validated record. The Go+authorization service controls admission, cancellation, prompts and persistence.+The plugin validates the supplier protocol; successful persistence is not proof+that an arbitrary supplier token is valid.++The self-owned Web/Mobile plugin pages expose this management surface:++| Request | Purpose |+| --- | --- |+| GET /v1/host/extensions/authorization | Flow labels/methods, configured/in-flight state and the latest resumable attempt handle; no tokens or answers |+| POST /v1/host/extensions/authorization | Start `{key,method?}`; return the attempt and pending interaction |+| GET /v1/host/extensions/authorization/{id} | Current attempt state, notices and prompts |+| POST /v1/host/extensions/authorization/{id}/answer | Answer `{promptId,answer?,decline?}` |+| DELETE /v1/host/extensions/authorization/{id} | Cancel the attempt |+| DELETE /v1/host/extensions/authorization | Cancel `{key}` |+| POST /v1/host/extensions/authorization/disconnect | Disconnect the native account for `{key}`; available when `canDisconnect` is true |++Open the plugin market from the Web sidebar or the mobile Chat workspace menu.+Each installed plugin shows only its registered authorization methods. A single+method has a direct entry; multiple methods offer a choice. A plugin without+authentication has no authorization entry. Ordinary flows and declared MCP+OAuth connections appear within the owning plugin, not in a separate MCP page.++The list includes optional `accountLabel` and `canDisconnect`. For native CLI+flows, `configured` is queried through the plugin's `inspect` callback, not a+placeholder Go credential record. A successful `run` is confirmed with `inspect`.+Ordinary flows keep their credential commit requirement. Explicit disconnect is+separate from cancelling a pending attempt: it calls the integration's native+logout and confirms that it no longer reports an authorized account.++Closing a panel or disconnecting a client does not cancel an authorization.+The flow listing exposes transient `attemptId`/`attemptStatus`; another view can+retrieve that attempt and its still-pending prompts. The flow ends on completion,+failure, explicit cancellation, plugin disposal or Host shutdown. Attempts stay in Host memory, not+browser storage or Redis. `configured` means a credential record exists, not+that a third-party service is currently reachable.++For an OAuth authorization-code flow, `session.callback({state})` returns+`{url,wait()}`. The provider library supplies its generated state; Go allocates a+single-use callback for the current attempt. `await callback.wait()` returns the+query as `Record<string,string[]>` to the plugin only. The plugin must validate+the provider response/issuer, exchange the code using its PKCE/client settings,+and then call `session.commit(record)`. A callback receipt is not authorization.++The browser callback is+`GET /v1/plugins/authorization/callback/{userId}/{token}`. Controller forwards it+to that account's authenticated Host, which checks the active attempt, token+and expected state and rejects replay. The callback does not start a Host or+expose arbitrary plugin HTTP routes. Its public base comes from the verified+Controller origin (HTTPS or localhost HTTP). API-key and device-code flows use+normal prompts/notices without this callback. Callback query/code data never+enter frontend attempt views or Redis configuration.++Credential authorization is separate from tool execution approval. A tool can+await `ctx.host.approvals.request(call, request)` before its business side effect;+only `allowed` means it should proceed. `questions.ask` waits for a real answer+within the active call. Neither adds a short RPC timeout to the human wait.++## MCP++MCP Client is a built-in Go service. Plugins register connections with+`await ctx.host.mcp.register({name,connection,toolLoading?})`. `stdio` accepts a+command/args/env/cwd and `streamable-http` accepts a URL/headers. Transport fields+are mutually exclusive. No independent end-user MCP configuration page is needed.++The Go client resolves explicit `${credential:NAME}` references, connects,+initializes, discovers and executes tools directly. It also owns MCP protocol+OAuth: discovery, PKCE, token exchange/refresh and grant persistence in the same+credential Store. Its grant addresses are separate from business OAuth records.+Missing credentials/authorization and connection failures are distinct states.+Disposing the owning Cordis instance releases the Go connection and tools.++`register` returns a Registration after initial handling; it does not promise+`connected`. Plugins can await `list`/`inspect`/`restart`, start protocol OAuth with+`authorize`, cancel a specific attempt, or `signOut`. These are SDK operations,+not a second Node MCP client. A declared `toolLoading` defaults to `eager`; the+existing Go on-demand discovery mode remains available.++The project's low-level `/v1/host/mcp` diagnostics and explicit restart/probe/OAuth+operations remain for specialized clients. They do not create servers. The+browser OAuth callback is `GET /v1/mcp/oauth/callback/{userId}`; the running Host+validates state, PKCE and issuer and is never started by a callback. The callback+uses a verified HTTPS or loopback HTTP Controller origin. Ordinary HTTP Host/chat+access keeps its existing behavior. Full request shapes are in [OpenAPI](../api/openapi.yaml).++## Files and streams+The Host file listing starts at `/root/harness`. Pass a relative directorypath and use `nextOffset` to read the rest of a directory. The response includes`rootPath`, `path`, `files` and `truncated`. Entries contain `name`, `path`,@@ -137,14 +320,31 @@ when an intermediate page contains no public events. Durable inbox admissionreturns messageId before a turn is assigned. Persisted event sequence numbers arethe reconnect cursor; live attempt chunks have a separate transient sequence.-The first transcript page includes `events`, `throughSeq`, `before`, `queue`-and `questions`. Pass `before` to get the previous page. Start the chat SSE-with `after=throughSeq` and use the last processed durable event sequence to-reconnect. The projected `session` events carry ordered user and assistant-blocks, tool outcomes and turn boundaries. The transient frames-`assistant-stream-baseline` and `assistant-stream` cover the active model-attempt. `queue.state` and `questions.state` carry current snapshots.-`chat.idle` indicates a session has no active runtime.+Bundled Web and Mobile clients open one `GET /v1/host/stream` for the signed-in+workspace, independently of the selected chat or tab. Each SSE record uses+`event: host` and JSON `{sessionId?, type, data}`. Session records carry their+own `sessionId`; `sessions.changed`, `schedule/changed` and `extensions.changed`+invalidate their Host-level lists or settings. Session switches do not reconnect.+No separate task or plugin stream is needed.++The first transcript page includes `events`, `throughSeq`, `before`, `queue`,+`questions`, optional live `baseline`, and `permission`. Pass `before` for older+pages. On connection/reconnection, URL-encode `cursors` as a JSON map from each+cached session ID to its last processed durable sequence (or null for an empty+journal). At most 20 entries are accepted. Omitted cursors overlap the same+bounded recent 20-turn page used for initial history, covering messages that+arrive while a session is being discovered. Clients deduplicate by session ID+and sequence, and buffer events while fetching history. Unopened chats keep+only in-memory activity/pending summaries, not whole transcripts.++The projected `session` events carry ordered user and assistant blocks, tool+outcomes and turn boundaries. `assistant-stream-baseline` and+`assistant-stream` cover provisional model output. `session.state` carries the+current `activeTurn`; `queue.state`, `permissions.state` and `questions.state`+synchronize controls. `session.cursor` advances over filtered private records+without revealing them. `session.unavailable` invalidates an unavailable cached+chat. Per-session durable sequences remain the recovery authority; no global+journal, Redis event queue or client receipt acknowledgement is introduced.A successful message POST returns 202 with a `messageId`. Queue operationsuse that ID and return 204 on success. A queue entry that is no longer@@ -164,3 +364,14 @@ The bundled Web UI uses the Controller's own origin. Browser requests fromother origins are denied by default. For local Vite development, pass`--web-dev-origin http://127.0.0.1:5173` to the Controller. CLI requestswithout a browser origin still work. See the [frontend README](../frontend/README.md).++## Model endpoint protocols++`POST /v1/settings/models/endpoints` and `PATCH /v1/settings/models/endpoints/{endpointId}`+accept `protocol: "responses" | "anthropic_messages"` alongside `name`, `baseUrl`,+`apiKey` and `models`. Omitted protocol defaults to Responses for a new endpoint+and stays unchanged on an existing endpoint. GET settings returns protocol and+`hasApiKey`, never the stored key. A session continues to select only+`{ "endpointId": "...", "modelId": "..." }` through its `/model` endpoint.+Base URLs include the API prefix, such as `/v1`, but exclude `/messages` or+`/responses`. See [model provider configuration](providers.md#language-models).diff --git a/docs/architecture.md b/docs/architecture.mdindex d0af6d6..451e508 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -57,7 +57,7 @@ same instance.The driver supplies an address reachable from Controller. DockerHosts use dynamic published ports. ECI uses the private IP. After a successful-`/readyz` probe, Controller synchronizes model settings and saves the endpoint+`/readyz` probe, Controller synchronizes model and saved extension settings and saves the endpointin Redis for session forwarding and readiness checks.The Host checks its startup configuration and writable filesystem operations@@ -111,3 +111,24 @@ model/search keys and other Sessions. It is not a multi-tenant isolation layer.See [configuration](configuration.md), [deployment](deployment.md),[provider extension](providers.md) and [validation evidence](validation.md).++## Business plugins++Each Host may start one private Node/Cordis process. The built-in Host Bridge+provides `ctx.host` through bidirectional asynchronous JSON-RPC over a private+Unix socket. Go owns AgentLoop, Sessions and the unified PreExecute → Execute →+PostExecute → Result flow. Only selected plugin business callbacks cross RPC;+normal Go Session creation, checkpointing and result commits do not wait for+Node compatibility listeners. No pre-stage guard or remote middleware is used.++Cordis Loader/Fiber/effect owns plugin dependencies and lifecycle. Go tracks+resource registrations and active calls, not a second plugin-instance state+machine. Controller Redis stores only per-package selections (catalog ID, version and enabled). Installed packages+live under `$DSH_HOME/plugins/profile`; no local plugins.json is generated. The Host+unifies package/dependency installation through pnpm and reviewed standard+lifecycle scripts before reporting installation success. Cordis activation+registers capabilities without installing software. Plugin credentials and+business/MCP grants use the one built-in Go credentials Store. Host has no Redis+access. Public SDK methods are Promise-based; native `host/*` notifications only+observe state and cannot replace tool results. See [plugin API](api.md#plugins)+and [SDK](../extensions/sdk/README.md).diff --git a/docs/configuration.md b/docs/configuration.mdindex 8ea8c48..d9dcc91 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -94,6 +94,7 @@ Each account has one Redis Hash at `user:<userId>` with no expiration.| `llm` | JSON | `defaultEndpointId` and `endpoints`. Each endpoint stores its name, URL, API key and ordered model list || `webSearch` | JSON | Active `provider` and per-provider `entries` with API keys || `imageGeneration` | JSON | Active `provider` and per-provider `entries` with API keys and model names |+| `plugins` | JSON | Per-package user selections: catalogId, fixed version and enabled. No instance configs, sources or secrets; credentials remain in the Host || `sessionModels` | JSON | Map from session ID to `{endpointId, modelId}` || `modelRevision` | Integer | Version of the model catalog and session selections synchronized with the Host |@@ -104,7 +105,7 @@ from the previous development storage format.Controller supplies `HOST_ACCOUNT_ID`, `HOST_ID`, `HOST_API_TOKEN` and`HOST_DATA_MOUNTED` when it starts the Host. It synchronizes the selected search-and image settings, model catalog and session selections over the authenticated+and image settings, model catalog, session selections and saved plugin intent over the authenticatedHost control channel. Open an account to start or reconnect itsHost. Use the stop request to stop it. Host-created scheduled sessionsstore their model selections in the Host data directory.diff --git a/docs/deployment.md b/docs/deployment.mdindex 5304ab2..377df8d 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -124,29 +124,31 @@ existing mount target hostname. Create `/go-bot/<userId>` on NAS and allowthe Host to write to it before opening that account. The driver mounts it at`/root/harness`. Session journals live at`<nasPath>/.dsh/sessions/<project-key>/<session-id>/session.v4.jsonl`.-Schedules, attachments and user skills share that account's NAS directory. On-first use, the Host copies the image's OfficeCLI and agent-browser skill bundles-to `<nasPath>/.dsh/skills/`. The `<nasPath>/.dsh/.skills-seeded` marker keeps-later Host instances from resetting edits or restoring deleted skills.+Schedules, attachments and user skills share that account's NAS directory.+OfficeCLI and agent-browser are optional plugins installed from the plugin market.+Their original Skills are contributed from the installed plugin packages; the Host+no longer copies a first-start skill seed into user directories.ECI container storage uses the writable layer for the lifetime of the instance.See [validation](validation.md) for real Docker coverage and the remainingcloud checks.-## Image dependency updates--During the build, the verified OfficeCLI release binary generates its skill-bundles and the official Skills CLI fetches the upstream agent-browser bundle.-The image stores both sets under `/usr/share/go-bot/skill-seed`. The Host-installs them into `/root/harness/.dsh/skills` on first use of each data root. Both user-skill roots persist across instance replacement in the account's Docker volume-or ECI NAS mount.-To use the official specialized installer inside a running Host, direct its-Codex installation to the mounted shared root with-`HOME=/root/harness officecli skills install pptx codex`. A same-named bundle-already installed in `$DSH_HOME/skills` has higher precedence.--Version and SHA256 locks are in `build/dependencies.lock.yaml`, `build/officecli.sha256` and-the Dockerfile. Use `scripts/update-officecli.py` to propose an update from the-official stable release, review its diff, rebuild and run image smokes before-publishing. No third-party binary or SDK source is committed.+## Plugin and image dependencies++The base Host supplies Go, Node/npm/pnpm, Python, Chromium, LibreOffice and general+file-processing libraries. OfficeCLI and agent-browser CLIs are installed when the+user installs their plugins, rather than being preinstalled in the runtime image.++A disposable build stage exports the upstream Skills using official installers and+includes their complete resources in each wrapper package. Enabling a plugin+registers its Skills from the package; disabling it withdraws that contribution.+User-created Skills remain in the existing user Skill roots.++OfficeCLI installation runs `npm install -g @officecli/officecli`, without an added+version/checksum lock or an automatic-update override. Plugin package updates are+separate from CLI version selection. Installation policy belongs to the plugin;+the Host only coordinates package installation and reports the result.++Other build dependency versions are recorded in `build/dependencies.lock.yaml`+and the respective package lockfiles. No third-party binary or SDK source is+committed.diff --git a/docs/google-workspace-app-setup.md b/docs/google-workspace-app-setup.mdnew file mode 100644index 0000000..991aa3b--- /dev/null+++ b/docs/google-workspace-app-setup.md@@ -0,0 +1,68 @@+# Set up your Google Workspace application++Each user supplies their own Google OAuth application, just as X users supply+an X application. Go Bot does not distribute a shared Google client or require+application credentials in deployment `.env` files.++## Create the application++1. Create or select a project in the [Google Cloud Console](https://console.cloud.google.com/).+2. In **APIs & Services → Library**, enable APIs **as needed**. Drive operations+ use Google Drive API; email uses Gmail API; calendars use Google Calendar API;+ Docs, Sheets and Slides use their corresponding APIs. You do not need to+ enable every API before connecting. A disabled API returns an error when used.+3. In **Google Auth Platform → Branding**, configure your application name,+ support email and developer contact. Follow the console's requirements for+ the application information you provide.+4. Configure an **External** audience to use personal Google accounts or accounts+ outside an organization. While the application is in **Testing**, add the+ **Google account email** you will authorize under **Audience → Test users**.+ This whitelist is stored by Google, not in Go Bot or Redis. It is unrelated+ to your local Go Bot username. Workspace organization policies may also apply.+5. Open **Clients → Create client** and choose **Desktop app**. Download and keep its JSON immediately after creation; existing clients may no+ longer offer the original secret for download.+ Do not choose Web application, create a service-account key or put this JSON+ in the plugin source directory.+6. In Go Bot's Google Workspace plugin, select **Accounts and authorization →+ Connect Google account**. On Web, select the downloaded JSON file; it is parsed and submitted automatically.+ On mobile, paste the JSON in the protected input on first connection. Then select permissions, open the Google link and consent.+7. Copy the browser's complete localhost redirect URL into the panel even if+ its localhost page cannot open. Wait for the plugin to confirm connection.++The plugin validates the downloaded `installed` configuration and standard Google+endpoints, and saves it as native `~/.config/gws/client_secret.json` with private+permissions. That directory points into your Host data. Later connections reuse+it; account disconnect uses native gws logout and retains the application config.+User access and refresh tokens remain in the same native gws directory. Neither+Redis nor Go credentials receives a second copy.++## Testing and public use++Testing is suitable for your own application and nominated test accounts. An+unverified testing app can display a Google warning, and its grants can be+subject to testing limits. Only continue with an application you recognize.+A maintainer publishing an application for other people must separately satisfy+Google's publishing and applicable sensitive/restricted-scope verification+requirements. Downloading a client JSON does not grant public availability.++Gmail, Drive, Calendar, Docs, Sheets and Slides support personal Google accounts;+these features do not require a paid Workspace enterprise subscription. API+access still depends on enabled APIs, scopes, quotas and organization policies.++## Upstream setup option++On a trusted computer with an authenticated `gcloud` CLI, upstream+`gws auth setup` can guide project selection/creation and API enablement. Its+current Desktop-client stage still directs you to the Cloud Console. You can+also follow the manual steps above without installing gcloud on your phone or+inside the Host. Existing native gws authorization can be imported as described+in the [connection guide](plugin-account-setup.md).++Retrieved service data can enter the Agent context and the selected model+provider. Review requested permissions before consenting. Never put application+JSON, account exports, callback URLs or tokens in chat, source files or Git.++[Google Desktop credentials](https://developers.google.com/workspace/guides/create-credentials#desktop-app)+· [Consent screen and audience](https://developers.google.com/workspace/guides/configure-oauth-consent)+· [Google publishing requirements](https://developers.google.com/identity/protocols/oauth2/production-readiness/policy-compliance)+· [gws authentication](https://github.com/googleworkspace/cli#authentication)diff --git a/docs/host-bridge-plugin-system-plan.zh-CN.md b/docs/host-bridge-plugin-system-plan.zh-CN.mdnew file mode 100644index 0000000..2047a72--- /dev/null+++ b/docs/host-bridge-plugin-system-plan.zh-CN.md@@ -0,0 +1,1068 @@+# Go Bot 插件系统重新设计:Cordis + Host Bridge++方案日期:2026-11-19;最近核对:2026-11-20。状态:Go 四环节、Host Bridge、内置市场及 Web/Mobile 授权交互均已实施;最终部署回归与交付核对见第 14 节。++2026-11-20 方案调整:从目标设计中移除 PreExecute 的独立 guard 和插件 guard 接口。该次请求只更新方案;随后恢复的实施任务按此决定核对并清理代码。保留执行前策略、审批、取消检查、工具自身权限判断与沙箱,PostExecute 的重复调用提醒也保持独立。++总原则:**核心能力内置到 Go,不向业务插件开放通用的 `pre/execute/post + next` 执行链。还原上游的功能和行为,不复制它为了“一切插件化”采用的组织形式。** Go 以统一的 PreExecute → Execute → PostExecute → Result 管完整调用流程,工具实现自己的业务,Cordis 管插件装配和生命周期,Host 事件供观察。第 1.1 节汇总本次讨论的正式决定;第 15 节保留源码审计依据。++本文重新定义插件系统,不沿用之前方案的接口兼容目标。后续实施以本文为准;`plugin-framework-plan.zh-CN.md`、`go-bot-plugin-system-redesign.zh-CN.md` 和 `cordis-go-host-plugin-plan.zh-CN.md` 不再作为实施规范。++**恢复执行依据:**执行当前 Goal 时继续使用本文件的最新正文,特别是第 1、2.3、6、8.1、12、13 节;不回退到旧的阶段事件链或跨进程 next 方案。Goal 概述中较早的“guard”要求已取消,实施中已删除 PreExecute 的独立 guard 检查及插件 guard 接口,不另设同义的最终限制层;“资产适配”按第 6.8 节收缩为保留内置能力、删除新增插件 Assets 通道,不据此重新开放接口。第 15 节只提供上游调研证据,已排除模块不是实施需求。++本文的“交互”主要指 **Go Host 与 Node 插件进程之间的通信、请求、回调、通知和生命周期**。前端人机交互沿用现有机制,不在本次重新设计界面。++**本次收口规则:**第 1—13 节是目标合同,第 14 节仅记录实施现状,第 15 节仅记录上游研究。研究中出现的接口、旧代码已经实现的接口,都不能自动成为本轮公开能力。公开入口以第 6 节、公开通知以第 7.2 节为完整白名单;实施步骤、删除清单和验收不得重新扩大这两个边界。本轮不开放 Assets 服务,也不为插件新增二进制 spool 或图片/文件交付结果协议。++## 1. 设计决定++采用 **Go 内置 Harness + 独立 Cordis 进程 + 一个内置 Host Bridge 插件**。++Host Bridge 是一个运行在 Cordis 中的基础插件,向业务插件提供 `ctx.host`。Go Host 进程本身不变成 Cordis 子插件,不由业务插件启动,也不搬入 Node。++```text+Go Host:核心实现、状态与执行权+ ⇅ 一条双向异步 JSON-RPC 连接+Node/Cordis+ ├─ 内置 Host Bridge:提供 ctx.host,转发调用和通知+ ├─ 邮件插件+ ├─ 旅行服务插件+ └─ 其他第三方插件/插件自己的 Cordis 服务+```++具体选择:++1. Cordis 只负责插件的装配、服务注入、配置、事件注册和生命周期。+2. `ctx.host` 是本项目定义的 SDK。接口依据 Go 内置模块及业务扩展需求设计;上游服务的功能和行为应先核对,再决定 Go 内部实现和必要的对外接口,不整套照搬其核心插件装配方式。+3. 所有需要 Go 确认的方法均返回 Promise。`await` 只暂停当前调用函数,不阻塞 Node 线程。+4. 工具业务回调与观测通知分开。Go 不通过 Cordis pre/execute/post 事件推进工具调用;ctx.on 订阅本项目 host/* 观测通知,返回值不改变当前执行结果。+5. Go 保留 PreExecute、Execute、PostExecute 和最终 Result 四个处理点,在对应环节内置上游相关核心模块的处理逻辑;Go 负责顺序、权限、审批、结果校验、事实提交和 Agent 推进,Node 只运行插件提供的业务函数。+6. 不提供跨进程 next、工具阶段 continuation、完整 Agent/Session 代理或另一份 Node 核心执行器。插件工具由 Go 在调用其业务函数时通过 RPC 直接执行回调。+7. 不提供插件客户端代码、通用 actions 或 storage;插件仍可提供普通 Cordis 服务给其他插件使用。+8. 开发期直接更换协议、SDK 和配置,不维护旧插件或旧配置迁移。+9. 本次不引入上游 `packages/experimental/*` 的包或实现,也不以其监听器作为必须补齐的核心行为;本项目已有的独立功能继续保留。++### 1.1 本次讨论的正式结论++**核心能力归属:**AgentLoop、Session、工具系统、权限/沙箱、审批、Skills、提示组装、凭证、授权及 MCP 等基础模块在 Go Host 内实现。与现有项目相关的上游核心监听逻辑,应逐项归入相应 Go 模块,保持所需功能与行为;不将这些逻辑重新包装成 Node 核心插件。业务插件通过 Bridge 使用基础能力,不能接管核心流程或会话提交。++| 上游通过核心插件实现的能力 | 我们的实现位置 |+| --- | --- |+| 执行前 checkpoint、调用记录 | Go 会话与工具调用流程 |+| 参数校验、权限和审批 | Go 工具系统及权限模块 |+| 超时、取消、并发控制 | Go 工具执行器 |+| 输出限制、错误规范化、结果校验 | Go 结果处理逻辑 |+| 文件交付、日志提交、前端投影 | Go 会话提交逻辑 |+| 重复调用提醒等运行保障 | Go Agent 运行逻辑 |++PreExecute、Execute、PostExecute 是三个执行处理阶段,Result 是最终结果确认环节;四个处理点共同组成 Go 工具系统的统一流程,并不与某个工具绑定。上游相关核心插件在各事件阶段承担的逻辑,应在对应 Go 阶段直接调用;不只是把逻辑任意分散进各工具函数,也不只是借用阶段名称。这些能力必须在没有 Node 监听器时正常工作。不能只删除上游事件桥接,却遗漏原先借事件完成的 checkpoint、取消收尾、输出治理或结果提交行为;实现时应核对 Go 现状、补齐缺口并验证。此处要求按职责承载已有范围内的核心行为,不扩大成引入全部上游实验模块或运行任意上游插件。++**业务插件:**插件提供自己的工具、Skill、附加提示、MCP 声明和授权业务。提供工具时只需登记定义及业务 `execute()`;不要求每个工具实现三个固定的 pre/execute/post 接口。工具自己的检查、资源准备、实际操作和清理可直接写在业务函数中。++```ts+await ctx.host.tools.register({+ name: 'send_mail',+ description: '发送邮件',+ inputSchema: { type: 'object', properties: {} }, // 由插件定义真实业务参数+ async execute(args, call) {+ // 检查本次业务参数、准备资源;需要审批时先请求 Go 审批服务。+ // 实际发送与清理在此完成,返回 SDK 规定的 ToolResult。+ return { content: [{ type: 'text', text: '业务执行结果' }] }+ },+})+```++**公开事件:**不额外新增工具开始/完成的插件通知。Host 仅按第 7 节公开 Skill、凭证、授权、MCP 等状态变化,插件通过原生 `ctx.on(...)` 订阅并按实例标识等字段筛选;返回值不改变工具执行决定或结果。Go Result 环节与现有前端会话中的工具调用/结果消息保持独立,不增加替代名称的工具事件。Cordis 自身和插件之间的本地事件仍保留原生语义。++**执行前处理范围:**PreExecute 保留调用准备、执行前策略、必要审批和取消检查,不设置独立 guard 检查,也不开放插件 guard 接口。工具自己的业务限制留在 execute 内;权限和沙箱由既有 Go 模块处理。需要用户决定的操作通过统一 Go 审批服务完成。本轮不增加“结构化结果提交后禁止所有后续工具”的公共检查。++**Cordis 与通信:**插件装配、依赖注入、作用域、配置更新、卸载及生命周期使用原生 Loader/Fiber/effect。Host Bridge 提供统一异步 JSON-RPC 适配;Go 调用业务回调,插件可 await 已开放的 Go 服务。不增加跨进程 next、Node 工具执行器、Agent/Session 代理或 Go 自建插件生命周期状态机。++恢复实施时删除与上述边界冲突的旧阶段桥接、全局 guard 接口、重复 Node 核心服务及专属测试;保留 Go 核心处理及业务回调所需的通信能力。方案调整不表示这些删除和生产切换已经完成。++### 1.2 工具主链:Go 统一注册与执行++内置、插件和 MCP 工具共用 Go 工具接口与实际调用流程;工具来源不改变执行权归属。++**注册与发现:**++- 内置工具由 Go 装配,得到包含定义、参数校验、实际执行函数的 Go Tool。+- 业务插件调用 `await ctx.host.tools.register({name, description, inputSchema, execute})`。Node 保留函数;Go 登记名称、定义与回调句柄,产生同一种 Go Tool 接口的 RPC 适配对象。+- MCP 工具同样由 Go MCP Client 提供 Go Tool;不先绕经 Node 再请求同一个 MCP 服务。+- Go 在模型 step 开始时把上述工具合并到同一实际工具表,冲突拒绝、生成统一模型声明。不是三套 AgentLoop 或三套执行管线。++**调用:**++```text+AI tool call+ → Go PreExecute:调用准备、内置策略/必要审批、取消检查+ → Go Execute:执行边界保障,调用固定的工具,取得规范化结果+ ├─ 内置 Tool:调用 Go 函数+ ├─ 插件 Tool:RPC → Node 已登记的 execute 回调+ └─ MCP Tool:Go MCP Client 调用服务端工具+ → Go PostExecute:对应核心结果处理、最终校验/物化+ → Go Result:确认最终结果、执行对应核心收尾、提交事实+ → Agent 继续+```++具体超时、并发、取消和错误分支继续由 Go 管线管理,不为插件工具另造一套。插件卸载后通过 Cordis effect 撤销 Go 登记;已捕获的调用不得解析到另一个同名新实现。++**公共处理与业务逻辑:**工具系统的超时、取消、并发、checkpoint、权限和结果提交直接留在 Go 的对应阶段,具体顺序、来源模块与返回类型见第 8.1 节。工具特有的参数检查、资源准备和清理写在该工具的业务实现中,不要求每个工具实现额外 pre/post 接口。插件若需要确认某个业务操作,在自己的 execute 中、实际副作用之前 await Go 审批服务。++**审批规则来源:**Go 内置执行前策略可依据明确规则返回 allow/deny/ask,由 Go 审批服务处理 ask;不是 Go 自动推断所有业务风险。内置工具自己的权限判断和插件工具自己的业务判断也可申请同一服务。当前源码已有 Go 策略入口,但生产装配尚未配置通用风险规则,不能宣称已默认对全部工具做风险审批。++**对外扩展边界:**本轮不公开通用 pre/execute/post 中间件或 registerGuard,也不在 Go PreExecute 保留独立 guard 调用;既有执行前策略、审批、权限和沙箱继续有效。外部插件贡献工具、Skill、附加提示、MCP 和授权流程;状态观察走 host/* 通知。此前新建的 host-tool-events/host_tool_events 阶段桥接及专属测试应在恢复实施后删除,不作为第二种运行方式保留。++## 2. 当前代码核对与职责归属++本节依据当前工作树,而非根据旧方案推测。核心装配入口是 `internal/host/host.go`、`harness/assembly/native_runtime.go` 和 `harness/assembly/resources.go`。++| 当前模块 | 代码位置 | 新设计中的职责与开放方式 |+| --- | --- | --- |+| Host 与用户运行环境 | `internal/host` | Go 创建基础模块和 Bridge;只开放非敏感的运行环境说明 |+| AgentLoop、step/turn、模型重试、压缩 | `harness/agent` | 完全内置;插件不能替换或手动驱动 |+| 会话事实、队列、工作目录、恢复、归档 | `harness/session`、`internal/hostruntime` | 完全内置;回调只获得当前调用的必要数据 |+| 工具管线 | `harness/agent/tool_pipeline.go`、`native_tool_pipeline.go` | Go 统一执行内置与插件工具;开放工具业务注册,公共处理直接内置 |+| 文件、Shell、沙箱、权限 | `internal/agentfs`、`internal/executor`、`harness/permission` | 保留现有实现,不包装成插件执行器;Bridge 不提供提权和执行器替换 |+| 审批、问题、Plan | `harness/permission/approval.go`、`harness/interaction`、`harness/plan` | 申请审批/提问可复用 Go 服务;Plan 状态仍由内置流程管理 |+| Skills 与种子初始化 | `harness/skills`、`harness/tools/skill.go` | Go 是最终发现/加载主体;插件可贡献目录、虚拟 Skill 或 Provider |+| 系统提示和运行上下文 | `harness/assembly/prompt.go`、`harness/agent/native_prompt_assembly.go` | Go 最终组装;插件只能贡献附加说明 |+| 长期记忆、会话检索 | `harness/memory`、`harness/sessionsearch` | 保留 USER.md/MEMORY.md、FTS 与内置工具;本轮不另开服务 |+| Goal、Todo | `harness/goal`、`harness/session/todo.go` | 保留内置状态与工具,不让插件改自动续轮或日志事实 |+| Subagent、Workflow、结构化输出 | `harness/subagent`、`harness/workflow`、`internal/hostruntime/native_subagents.go` | 保留 Go 生命周期,不提供 Agent 工厂或工作流执行器替换 |+| Jobs | `harness/jobs` | 保留现有 managed Job;插件 Promise 不自动成为 Go Job |+| Schedule | `harness/schedule` | Go 调度/投递和工具保持不变;定时任务中的 Agent 可以正常使用插件工具 |+| 图片附件、上传文件 | `harness/attachments`、`harness/content` | 保留 Go 内置存储与工具使用;本轮不开放插件资产入口 |+| present 和文件下载 | `harness/tools/present.go`、`internal/agentfs/presented.go` | 保留内置 present 的校验、事实提交和投影;不新增插件文件交付通道 |+| 模型、网页搜索、抓取、生图 | `providers/model`、`providers/web`、`providers/image` | 内置 Provider 保持不变;插件可以新增自己的工具,不替换用户模型/供应商配置 |+| 凭证与授权 | `internal/credentials`、`internal/authorization` | Go 唯一实现,Bridge 提供按插件归属的调用入口 |+| MCP 及协议 OAuth | `internal/mcpclient`、`mcp` | Go 唯一实现,插件注册服务,由 Go 发现并接入工具 |+| 插件配置、安装和管理 | `plugin`、`internal/plugins`、`extensions` | 保留有用包管理基础,替换旧协议/SDK 和上游兼容装配 |+| Controller、Redis、Docker/ECI/NAS | `internal/controller`、`providers/runtime` | 属于管理/部署面,不向业务插件开放 |+| OfficeCLI、agent-browser、Node、Python | Host 镜像及预装 Skills | 保持基础环境,不重新插件化 |++开放原则是“贡献能力、复用基础服务”,不是“将每个 Go 导出方法变成 RPC”。没有开放的核心模块仍正常工作,也没有被移到 Node。++### 2.1 上游的插件化组织与我们的区别++已核对 DeepSeek Harness 固定提交 `ca33fd6843b205e279c7ccb6cb73a472c78f5760` 的架构说明、完整 packages 目录、工具定义和 MCP/凭证服务文档。固定版本用于让调研可复查,不构成 SDK 兼容目标。++上游的模型适配、工具系统、会话和 AgentLoop 都能通过 Cordis 包装配/替换;业务插件和基础服务位于同一插件装配体系。它的公共 ctx 因而同时承载核心内部依赖和第三方扩展入口。[上游架构](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/docs/architecture.md)++我们将这些核心职责固定在自己管理的 Go Host 中。Go 内部模块之间直接调用;第三方插件只通过 Bridge 使用明确选出的能力。上游核心插件之间的接口不能整套复制成我们对第三方的 RPC 接口。++### 2.2 上游模块 → Go 内置模块 → 对外功能++下列是职责对应,不是宣称全部特性逐项等价。“内部”表示模块留在 Go 并正常提供能力,但不把其管理对象交给插件。++| 上游包/职责 | 当前 Go 内置对应 | 应向插件提供的功能 | 保持内部的部分 |+| --- | --- | --- | --- |+| core/agent、core/agent-loop | NativeLoop、NativeHost、NativeRuntime | execute 回调中的必要调用数据 | 驱动、创建/恢复 Agent、step/turn、队列、续轮、Agent 注册表 |+| core/session;session/session-persistence-jsonl、session-format、session-projection | `harness/session` 事实日志/恢复/投影 | 当前 sessionId;Go 提交工具结果时自动产生所需事实 | append/flush、writer、格式修复、投影控制、持久事件发布 |+| session/working-directory;workspace/workspace | header cwd、实际工作区与安全文件读取 | 当前 call.cwd/workspace 数据 | 改其他会话目录、管理全部工作区、归档/删除、文件交付校验服务 |+| core/tools、core/tool-executor-native | Go Registry、调度器、ToolPipeline | tools.register;业务 execute;host/* 状态观测 | 通用 pre/execute/post 中间件、跨进程 next、全局 guard、executor 替换、任意工具 dispatch、事实提交 |+| core/scope | 当前调用绑定及插件实例生命周期 | 自动 owner/fiber 归属、invocation | 不引入完整上游 Agent scope,也不要求插件创建 scope 才能注册 |+| core/system-prompt;context/agent-instructions、time-context | Go prompt/runtime context/时间组装 | prompts.register 的附加 system/context 文本 | 核心 system 替换、压缩策略、请求头和模型消息重建 |+| llm/llm、llm-retry、token-meter 及各模型适配 | `thirdparty/llm`、NativeLoop retry/pressure、模型路由 | 仅必要的只读模型描述,不提供模型 client | LLM 请求、密钥、Responses/Chat/Anthropic 协议、token 预算、重试 |+| compaction/compaction-* | native_compaction、prune、image_offload | 无独立插件接口 | 上下文保留/压缩、图片 offload、日志事实和请求投影 |+| fs/fs、fs-local、fs-observation-policy、fs-sandbox、tool-fs | agentfs、Go 文件工具与权限包装 | 当前调用的 cwd/workspace 数据;不新增文件服务 | 文件观察版本、任意 mutation API、绕过权限的文件执行服务 |+| shell/*、subprocess/*、sandbox/* | executor、shell 工具、Linux 沙箱与 permission | 工具回调取消信号、Go 审批申请 | shell executor、环境覆盖、放宽沙箱、权限模式设置 |+| guard/timeout-policy、repeat-tool-reminder | Go 工具 timeout、repeat-tool 检查 | 工具声明 timeoutMs、concurrency;运行保障由 Go 直接处理 | 原生默认策略和结果终结,不由 Node 中间件替换 |+| interaction/user-approval、permission-presets | Go ApprovalService、会话权限策略 | approvals.request;插件业务在操作前主动申请 | 策略修改、用户同意/拒绝答复、越权执行授权来源 |+| interaction/user-questions、tool-ask-user;plan/plan-mode | NativeQuestions、Native Plan 与内置工具 | questions.ask;活动工具内提问 | Plan 状态转换、用户答复入口和非限时 Plan 审查 |+| jobs/jobs、jobs-local、tool-jobs | Go Jobs Registry、job_output/list/kill | 无独立 ctx.host.jobs;插件 body 自己遵循 signal 并返回 | managed Job 身份、完成投递、输出游标和跨会话取消 |+| goal/goal、goal-round-driver、tool-goal;todo/tool-todo | NativeGoal、Todo 日志与工具 | 无独立插件服务 | 目标预算/完成、自动续轮、Todo 事实写入 |+| subagent/*、workflow/* | Native children/fork、Go Workflow 与结构化输出 | 普通插件工具可在子 Agent 中运行,无需额外接口 | 子 Agent 工厂、父子关系、控制消息和 Workflow driver |+| schedule/schedule、tool-schedule | Host Schedule、目标准备与投递 | 到期会话可使用插件工具;不新增 Node 定时器替代调度器 | 创建/编辑/投递服务对象,本轮不向普通插件开放 |+| skill/skill、skill-filesystem、tool-skill | Go Registry、目录扫描、加载工具 | skills.register/registerDirectory/registerProvider/list/get/invalidate | 最终目录合并、用户覆盖优先级、seed 初始化 |+| attachment/attachment、attachment-local | Go 图片对象和上传文件附件 | 本轮无插件接口 | 现有图片入库/读取、上传附件、元数据验证 |+| deliverables/tool-present、deliverable-file-references | Go Present、PresentedPath/OpenPresented、前端 file 投影 | 本轮无插件接口 | 内置 present 与 Go 交付事实提交;不恢复工作区扫描/产物推测 |+| credentials/credentials、credentials-local | `internal/credentials` | 本实例记录的 get/put/update/remove/describe/list;显式引用的 resolve | 底层写入器、任意 owner 批改、全局环境枚举 |+| credentials/authorization | `internal/authorization` | flow 注册与状态/取消;Go 调 run、notify/prompt/commit | 准入、活动尝试、提交确认和答复归属 |+| mcp/mcp-client、mcp-manager、mcp-resources | `internal/mcpclient` Manager/Connection/Scope | mcp.register/list/inspect/restart/authorize/cancelAuthorization/signOut | 连接、协议、工具发现和执行;不因职责对应宣称资源特性已全量实现 |+| session-query/*(本项目已有会话检索独立保留) | `harness/sessionsearch` 的现有 FTS | 无独立插件查询 API | 全会话检索索引和正文;由内置 session_search 使用 |+| document/office-kit、skill-office、browser-use 及实验驱动 | 本项目 OfficeCLI/agent-browser CLI + Skills | 注册额外 Skill/工具,可调用自身业务 SDK | 不引入上游另一套 Office/browser runtime,不强求实现一一相同 |+| boot/plugin-manager、plugin-market、app-boot、hmr | 当前 Go Manager/包管理 + 新 Cordis loader | 当前包的 apply/config/lifecycle;自有 SDK | 安装/启停其他插件、上游 bundle/patch 全树控制 |+| settings/settings;api/*、host/webserver、sdk/server、client/* | Controller、HTTP/SSE、自有 Web/Mobile | 配置 schema 由管理器展示;不提供插件前端代码 | 路由、前端会话、全局 SSE、账号和端口管理 |+| storage/*(不新增公共 storage/actions) | 不作为新的公共基础能力 | 本轮不提供 storage/actions | 不能因上游存在就恢复已决定删除的接口 |+| 本项目 USER.md/MEMORY.md 长期记忆 | `harness/memory`,参考 Hermes 的本项目实现 | 本轮不另开服务,内置 memory 工具继续可用 | 不将这套实现误称为来自上述上游核心插件的直接对应 |++调研来源除架构说明外,还包括固定提交的 [packages 目录树](https://api.github.com/repos/deepseek-ai/deepseek-harness/git/trees/ca33fd6843b205e279c7ccb6cb73a472c78f5760?recursive=1)、[基础装配](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/bundle/base/README.md)、[工具合同](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/docs/subsystems/tools.md)、[凭证服务](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/credentials/credentials/README.md)、[MCP 管理](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/mcp/mcp-manager/README.md)。目录存在只证明模块存在;上表的 Go 责任和开放决定是本项目设计,不从包名推断行为等价。++### 2.3 不应顺带恢复的其他上游模块++上游目录还存在 Agent Teams、LSP、SSH backend、PTC executor、远端控制面、桌面载体、遥测等模块。当前 Go Host 没有全量对应实现,本方案不为了复制插件目录顺带引入它们。将来需要某项能力,先决定其属于 Go 核心还是业务扩展,再设计与已有模块的边界。++**experimental 范围约束:**本次统一排除上游 `packages/experimental/*`,包括 Auto Review、`experimental/hooks-claude-code`、`experimental/hooks-codex`、其他外部 hooks/mods、Liveshare 和实验浏览器/CUA 驱动;其源码只可作为调研参考,不进入实现清单或验收要求。本项目已经独立实现的会话检索、长期记忆等能力继续保留,不能因为上游相似功能位于 experimental 就删除现有功能。++**本次明确排除的上游阶段监听能力:**Stagehand/浏览器 MCP/CUA 资源监听、上游 Office 工具按需激活、实验 mods/hooks 兼容层及上游 UI 的结果监听,不进入第 8 节的 Go 核心迁移清单。浏览器继续由 agent-browser 提供,Office 继续由 OfficeCLI + Skills 提供,自有 Web/Mobile 继续负责展示。第 15 节列出这些上游源文件仅说明调研事实,均不是待实现需求。++因此本次不把上游完整的 ctx 对象作为目标,也不保留兼容别名。“关键运行机制按 Go 核心实现”与“任意上游插件原样可运行”是不同要求,本方案只采用前者所需的职责划分。++## 3. Cordis 与 Host Bridge 的关系++### 3.1 Bridge 是基础插件,不是另一套 Host++Cordis 启动时先加载 Host Bridge,再加载声明 `inject: ['host']` 的业务插件。Bridge 必须握手成功后才提供可用服务;连接失效后让依赖方感知服务不可用。++```ts+// 业务插件写法。类型由 @go-bot/plugin-sdk 提供。+export const name = 'mail'+export const inject = ['host']++export async function apply(ctx, config) {+ await ctx.host.tools.register({+ name: 'send',+ description: 'Send an email through the configured mailbox.',+ inputSchema: mailInputSchema,+ async execute(args, call) {+ const credential = await ctx.host.credentials.get('mailbox')+ const result = await sendMail(credential, args, call.signal)+ return { content: [{ type: 'text', text: `Sent: ${result.id}` }] }+ },+ })+}+```++所有远程贡献自动绑定到发起注册的真实 Cordis 插件实例。卸载自动撤销,业务插件不需要为正常注册再写一套手动清理。register 返回的 Registration 可以用于提前撤销。++业务插件可以照常 `ctx.provide` 自己的服务、`ctx.inject` 其他业务服务或使用本地自定义事件。这些是 Cordis 的本地能力,不需要 Go 为每种业务服务提供 RPC。++### 3.2 基础库选择++本轮保留当前已锁定的 `@deepseek-ai/cordis` 作为 Cordis 基础运行库,避免同时更换容器内核。它的包名不意味着继续兼容 DeepSeek Harness 服务。保留所需的 Cordis loader 基础库;删除不再需要的 `dsh-tools/skill/system-prompt/credentials/authorization/scope/llm` 等运行依赖,类型也不再引用这些包。++将来如换成 `cordis` 官方发行包,是基础库升级,不是插件框架的第二种运行模式。新 SDK 只依赖选定的单一 Cordis 身份,防止插件各带一份运行内核。++依据:[Cordis 服务](https://github.com/cordiverse/cordis/blob/main/packages/core/src/service.ts)、[插件依赖注入](https://github.com/cordiverse/cordis/blob/main/packages/core/src/registry.ts)、[事件机制](https://github.com/cordiverse/cordis/blob/main/packages/core/src/events.ts)。本项目使用锁定版本的真实实现,不修改事件注册函数来模拟另一套内核。++### 3.3 服务归属不能固定为 Bridge 自己++Host Bridge 可使用 Cordis Service 实现并以 host 命名提供服务。每次访问 `ctx.host.tools` 等子入口时,基于 Cordis 跟踪到的调用 Context 创建轻量 façade,从真实所属实例和 fiber 得到 owner/lifetime;不能让所有注册都归到 Host Bridge 的根 fiber。++子入口只绑定通信端与所属上下文,不缓存 Go 的工具、凭证或会话状态作为查询结果;本地 callback handles、pending、Cordis 生命周期清理记录仍是必要的通信数据,不是第二套 Go 状态镜像。业务插件内部子 fiber 的贡献随该 fiber 回收,根实例卸载回收全部所属贡献。两个配置实例使用同一包时也必须有独立 owner、凭证地址和撤销范围。++Bridge 自己的启动/维护调用使用单独的内部入口,不伪装成第三方 owner;来自无有效业务实例的注册直接失败。++## 4. 统一异步通信框架++### 4.1 一个连接,两种消息语义++Go 启动一个 Node 进程,通过容器私有 Unix socket 建立一条双向连接。双方均可发起请求和响应。无需额外公开端口、Redis 消息队列、同步 Worker 或共享内存。++采用 JSON-RPC 2.0:有 id 的 request 必须有成功/失败响应;无 id 的 notification 不等待业务确认。这是传输语义,不是两套同步/异步实现。[协议规范](https://www.jsonrpc.org/specification)++| 用途 | 消息形式 | 何时完成 |+| --- | --- | --- |+| 插件查询/修改 Go 能力 | request → response | Go 完成方法定义的操作后 resolve/reject |+| Go 调用插件工具、Provider、授权流程等 | 反向 request → response | 对应 JS 函数完成后返回结果 |+| Go 通知已发生的状态变化 | notification | 只表示按序排出,不等待监听器完成 |+| 请求取消、连接关闭 | notification / socket 生命周期 | 对方终止对应工作;具体终结结果仍按请求处理 |++RPC 框架只负责 framing、请求分发、id 匹配、pending、错误和取消。工具策略、凭证写入和结果提交的含义由 Go 模块定义,不放进通用 RPC 层。++### 4.2 握手与注册++启动过程:++1. Go 创建私有 socket 和本次扩展运行期,启动 Node;socket 位于临时目录,不进入 NAS。+2. Node 发送 `bridge.initialize`,确认协议主版本、SDK 版本及消息大小限制。+3. Go 返回支持的能力名称及非敏感环境信息。版本不匹配明确失败,不猜测旧字段。+4. Node 完成 Host Bridge 服务装配。+5. 加载器依次/按依赖加载业务插件,等待 async apply。+6. 各 register 的 Promise 必须对应 Go 的实际确认,确认后该贡献即登记可用;async apply 的完成及实例状态由 Cordis 原生 Loader/Fiber 表达,不增加 Go 的 ready 状态或批量激活门槛。++初始化能力列表是兼容协商,不是 Go 运行状态缓存。没有启用业务插件时,Go 不必启动空 Node 进程。++### 4.3 一次普通调用++```text+插件调用 ctx.host.credentials.get('mailbox')+ → Bridge 得到调用插件实例 owner+ → 生成 n42,保存 pending[n42]+ → 发出 request,立即返回 Promise+ → Go 按白名单分派,解析 owner 和 key,读取唯一凭证服务+ → response(id=n42, result=...)+ → Bridge resolve pending[n42],await 后的代码继续+```++request id 使用方向前缀 n/g 防止双向冲突。收到请求时独立执行 handler,不在 socket 读循环里 await 业务完成;写帧只短暂串行化。等待响应时仍能接收新的反向请求。++### 4.4 一次工具回调与嵌套请求++```text+Go 工具管线 → callback.invoke(executeHandle, args, invocation)+Node execute → await ctx.host.credentials.get(...)+Go 继续处理该 get 请求并响应+Node execute → 返回 ToolResult+Go 收到 callback.invoke 的响应 → 继续校验和提交+```++Go 等待 Node 时不能持有 Session writer、工具注册表、凭证读取锁等对回调所需方法有影响的锁。异步通信不自动解决业务循环:同一工具不能等待自己完成,凭证 update 回调不能递归等待同一 Store 写队列中的其他 mutation。++### 4.5 私有协议清单++插件 SDK 不暴露任意 `ctx.host.call(method, params)`。Bridge 内部使用以下白名单协议;名字不是第三方插件 API:++| 私有方法 | 方向 | 数据/含义 |+| --- | --- | --- |+| `bridge.initialize` | Node → Go request | 协议和能力协商 |+| `contribution.register` | Node → Go request | owner、kind、声明、callback handles;返回 registrationId |+| `contribution.remove` | Node → Go request | 撤销 owner 自己的 registrationId |+| `host.invoke` | Node → Go request | 枚举的 service/method、参数、可选活动调用凭据 |+| `callback.invoke` | Go → Node request | callbackId、所属实例、参数、可选 invocation;返回该函数的结果 |+| `host.event` | Go → Node notification | event name 与只读 payload |+| `request.cancel` | 双向 notification | 原请求 id 和规范化取消原因 |+| `runtime.apply` | Go → Node request | 让原生 Loader 应用实例配置,等待其原生完成/清理结果;不承担 npm 包安装 |+| `runtime.inspect` | Go → Node request | 读取 Loader 实际实例状态和公开诊断;不读 Go 自建实例状态副本 |+| `runtime.shutdown` | Go → Node request | 停止注册、卸载实例并异步清理 |++不提供 tools.stage、tools.continue、dispatch continuation 或任意对象反射。Go 发 callback.invoke 时直接指定登记的业务回调;业务插件只调用第 6 节的 SDK 方法,Bridge 内部再编码为 host.invoke 等私有请求。Go Session 代理和 Node 核心提交回调均不提供。++### 4.6 返回、错误和取消++- 普通成功必须有 `result`;void 编码为 null,缺失业务记录也返回显式 null。不能把没有 result 的畸形响应当成功,不再跨进程模拟任意 undefined 对象。+- 错误使用标准 error envelope,data 包含本项目 code,如 INVALID_ARGUMENT、CONFLICT、NOT_FOUND、UNAVAILABLE、CANCELLED。SDK 还原 HostError,不依赖上游错误类身份。+- AbortSignal 在本地重建,通过 request.cancel 传播,不序列化 signal 对象。插件回调的 signal 同时受调用与插件实例生命周期约束。+- 管理查询/注册使用有限超时;工具 body 继承 Go 工具执行预算;普通审批不套短 RPC 超时。通知不等待响应,不将异步监听器结果当决策。+- 发出变更请求后丢失响应,结果可能未知。不能自动重发邮件、注册或写入。相关运行期失效后由 Go 清理其贡献;业务副作用需要插件按业务 id 自行检查,框架不造通用重试任务表。+- 取消工具 body 后等待它停止/收尾,不能将仍在改文件或发请求的 body 当作已结束。超过有限清理预算则终止共享 Node 进程并报告未知结果,不伪造正常成功。++### 4.7 消息大小与数据范围++保留小 JSON 控制帧,默认 1 MiB 上限,超限明确拒绝。本轮 SDK 只传已定义的 JSON 参数、文本及结构化数据;不提供图片/文件字节或 base64 传输,不建立二进制 spool 协议。++现有 Go 内置附件、生成图片、read_image、present 及前端下载链路继续使用原实现,不经过插件 RPC。业务插件可以在自己的业务代码中处理文件,但写出文件或返回路径文本不自动产生助手 image/file 块或交付事实。将来出现明确的插件资产需求时另行设计,不在本轮预设通道。++## 5. 所有权、注册与调用身份++### 5.1 三种运行期标识++| 标识 | 用途 | 是否插件配置 |+| --- | --- | --- |+| instanceId | 同一个包的某个配置实例,例如 work-mail | 是,创建实例时确定,Host 内唯一 |+| registrationId | 某项工具/Skill/提示等贡献的本次注册 | 否,Go 生成;卸载后失效 |+| invocation | Go 接受某次工具调用后给 Node 的不透明调用凭据 | 否;不能用 sessionId 自造 |++它们不替代现有 userId、hostId 或 sessionId。owner 从 Cordis 实例上下文绑定,Node façade 不接受业务插件传入“替别人操作”的 owner 字段。受信任插件的命名归属不是 OS 安全隔离。++```ts+interface Registration {+ readonly id: string+ dispose(): Promise<void>+}++interface ToolCall {+ readonly id: string+ readonly sessionId: string+ readonly cwd: string+ readonly workspace: string+ readonly signal: AbortSignal+ // SDK 私有保存 invocation;不存在可用字符串重建调用的公共构造器。+}+```++### 5.2 生命周期与注册可见性++所有 register 先在 Node 保存函数 handle,再请求 Go 校验/注册。resolve 表示 Go 已接纳此贡献,后续工具快照/查询即可使用;不等整个 apply 完成后再批量发布。失败清理函数 handle。一个工具被捕获到当前 step 后,后续卸载不能悄悄将其换成同名的新实现。++插件注册的工具在同一账号 Host 内统一可用,不提供 Agent 级 scope、工具 shadow 或 available 回调。Skill 查询仍可按实际工作目录读取文件,这是目录语义,不是插件 Agent 作用域。++register 的 Promise 对应 Go 资源登记确认,初始化成功/失败及回收使用 Cordis 原生状态和 effect。Go 不维护 initializing/ready/failed 等插件实例副本,不新建贡献激活协议或插件就绪状态机。启动/配置请求等待 Cordis Loader 的原生完成/清理 Promise,再返回其实际结果。插件必须 await 必需的注册操作;未等待的 Promise 不被假定为初始化成功。++async apply 后续失败时,由 Cordis 原生清理撤销此前已登记的资源。不保证这些资源在失败前从未被查询/调用,也不回滚已发生的外部业务副作用;本轮没有跨注册原子发布事务。管理器只返回原生状态及应用错误,不重新实现一套实例状态机。++卸载由 Cordis 发起并执行 effect:Bridge 的清理函数撤销 Go 资源、传播取消并释放 callback handles。未完成注册返回时若原生 scope 已关闭,Bridge 仍撤销相应 Go 资源,不能泄漏。Registration.dispose 幂等;Go 只处理资源自身的撤销/取消,不接管插件卸载流程,也不等待正在调用自身的回调造成死锁。++### 5.3 单个进程的实际边界++每个 Host 一个共享 Node 进程,插件间不做进程级隔离。插件代码按受信任扩展处理;不能宣称 Go 的 shell 沙箱会自动限制插件自行使用 node:fs 或 child_process。++Bridge 的白名单、owner 和 invocation 主要保证框架调用正确,不是面对恶意 Node 代码的秘密隔离。当前不引入插件权限弹窗、独立容器或第二套安全沙箱。++## 6. `ctx.host` 公共接口清单++下表是本方案的完整公共边界。所有 Go 请求都返回 Promise;本地 ctx.on 注册和纯函数除外。正式 SDK 自行定义 JSON-safe 类型,不继承上游完整服务类型。++### 6.1 环境与工具++| 方法 | Promise 结果 | 说明 |+| --- | --- | --- |+| `ctx.host.info()` | HostInfo | userId、hostId、dataRoot、apiVersion;不返回密钥、内部 token 或连接句柄 |+| `ctx.host.tools.register(definition)` | Registration | 注册插件工具与 execute 函数 |++```ts+interface ToolDefinition {+ name: string+ description: string+ inputSchema: JsonSchema+ concurrency?: 'exclusive' | 'parallel' // 默认 exclusive+ timeoutMs?: number // 省略不增加工具专属 deadline,仍受调用/生命周期取消约束+ execute(args: JsonValue, call: ToolCall): Promise<ToolResult>+}++interface ToolResult {+ content: ResultBlock[]+ data?: JsonValue // 可选结构化结果,不能替代必须的展示/模型内容+}++type ResultBlock = { type: 'text'; text: string }+```++工具有效名为 `<instanceId>__<name>`,只接受模型协议允许的名称字符,最终长度不超过 64;冲突或超长直接报错,不截断、不 shadow 内置工具。不把 businessId 强制塞进每个参数。Go 验证输入 schema 和结果结构;当前 step 捕获实际工具定义,不因执行途中重注册同名工具而换实现。这是执行一致性,不是 Agent 级可见范围。++本项目不要求插件提供 output.render/projectContent/finalizeContent 等多层函数。本轮插件返回有序 text 块和可选 data,Go 转换到已有 canonical result、日志和 UI 投影;不接受 image/file 块、任意 Meta 或伪造的附件/交付引用。data 是附加结构化值,不作为会话事实或交付命令解释;错误通过 throw HostError/普通 Error,由 Go 规范化。现有内置工具的 image/file 能力不受此 SDK 范围限制。没有必需的新 maxOutputTokens、模型 profile 等配置。++Go 执行前策略直接服务于统一工具流程;插件自己的业务限制写在 execute 内,需要用户决定时使用 approvals.request。工具被注册并不自动表示需要审批,也不需要通过某个事件监听器才能执行。+### 6.2 Skills++| 方法 | Promise 结果 | 说明 |+| --- | --- | --- |+| `ctx.host.skills.register(skill)` | Registration | 注册 name、description、content、可选资源目录和调用属性 |+| `ctx.host.skills.registerDirectory(path)` | Registration | 将包内 Skill 根目录交给 Go 现有发现器;支持多个 SKILL.md |+| `ctx.host.skills.registerProvider(provider)` | Registration | 动态 list/get 来源;函数保留在 Node |+| `ctx.host.skills.list({cwd?}?)` | `{items: SkillSummary[], complete: boolean}` | Go 最终目录及完整性,不是 Node 的局部目录 |+| `ctx.host.skills.get(name, {cwd?}?)` | SkillDefinition 或 null | Go 最终胜出的正文和资源信息 |+| `ctx.host.skills.invalidate()` | void | 标记本实例来源变化并通知后续查询;已有相关缓存才失效,不新建第二个目录缓存 |++Provider 为 `{id, list(context), get(key, context)}`,二者均可 Promise;list 返回 `{items, complete}`,item 带稳定 JSON key 和摘要,get 使用该 key 返回正文。无需跨进程搬运任意 JS locator 对象。context 包含 cwd 和 signal,不包含 Agent 实例。++公共 SkillSummary/SkillDefinition 统一使用第 6.11 节的平铺字段;Go 适配器转换原生 catalog 中的 invocation 等嵌套结构,不把内部结构直接泄漏到 SDK。Provider 失败可按现有发现语义使目录 complete=false,但必须保留诊断;调用取消应传播取消,不能伪装为空目录成功。Provider 的 list/get 回调内不能递归调用合并后的 skills.list/get,避免再次进入自身发现;允许读取凭证等无循环的 Go 服务。++registerDirectory 解析相对于安装包根的路径并检查存在;包安装目录是资源来源,不复制到预装 seed,也不让 Node 执行另一套全局 Skill 排序。Go 为插件目录赋现有 bundled 来源优先级,用户文件覆盖规则继续有效。OfficeCLI/agent-browser 的 seed 和用户动态安装流程保持原样。++### 6.3 附加提示++| 方法 | Promise 结果 | 说明 |+| --- | --- | --- |+| `ctx.host.prompts.register({id, location, text, order?})` | Registration | location 为 system 或 context;追加插件说明 |++text 可以是字符串或 `(context) => string | Promise<string>`;Go 在当前组装时调用,context 仅含 cwd、sessionId、必要模型描述和 signal。返回空字符串不贡献正文。按 order、instanceId、id 稳定排序。++不存在 complete 覆盖、变量注册表、section 常量同步查询和 assemble waterfall。插件在 text 中直接组装自己的文案,Go 继续负责原核心提示、记忆、Skill 目录、沙箱指导和上下文压缩。++### 6.4 Credentials++| 方法 | Promise 结果 | 说明 |+| --- | --- | --- |+| `ctx.host.credentials.get(key)` | CredentialRecord 或 null | 读取本实例的记录 |+| `ctx.host.credentials.put(key, record)` | void | 提交本实例记录 |+| `ctx.host.credentials.update(key, mutate)` | CredentialRecord 或 null | Go 串行读—回调—写,支持 token refresh |+| `ctx.host.credentials.remove(key)` | void | 删除本实例记录 |+| `ctx.host.credentials.describe(key)` | CredentialDescription | configured、kind、可写性;无原始值 |+| `ctx.host.credentials.list()` | CredentialSummary[] | 只列本实例记录,不含值 |+| `ctx.host.credentials.resolve(ref)` | string 或 null | 按 Go Store 解析配置中的显式命名凭证引用;不枚举进程环境 |++key 为插件内部短名称,例如 mailbox;Bridge 映射为稳定的本实例 owner/key。CredentialRecord 沿用 Go 已有 api-key/grant 数据能力:api-key 保存 key/env,grant 保存业务 JSON payload;MCP 的专用记录由 Go 内部 owner 管理。owner 标准化和地址校验由框架完成,不让每个插件手工拼 scope。++resolve 的 ref 是 Go 凭证 Store 中的命名引用,不是任意 os.Getenv 接口,也不是本实例记录的 key;解析沿用现有文件引用优先、Controller 提供值后备的规则,SDK 仅返回 value 或 null。它是显式引用查询,与本实例 records 的 get/list 边界不同,不宣称这两者存在相同的 owner 过滤。业务 OAuth grant 与 MCP OAuth 记录由各自协议模块解释,但都使用同一个 Go Store。++update 的 mutate 异步接收当前记录并返回替换记录;null 表示保持不变,删除用 remove。复用当前 Store 的串行写队列,不在等待 Node 时持普通读取锁;回调允许读取已提交记录,但不能嵌套等待任何该 Store 写操作,包括另一个 key 或授权 commit。Bridge 传递 mutation 上下文并对这类重入明确报错,避免死锁;本轮不改成多 key 事务或 CAS。写入成功后才发变更通知。授权提交复用同一 Go Store,不复制第二份令牌库。++这些 API 的归属过滤是避免误用,不是恶意插件隔离;受信任插件在同一容器内的权限边界见 5.3。++### 6.5 Authorization++| 方法 | Promise 结果 | 说明 |+| --- | --- | --- |+| `ctx.host.authorization.register(flow)` | Registration | 贡献获取本实例某个凭证的协议流程 |+| `ctx.host.authorization.list()` | AuthorizationSummary[] | 本实例可用方法和活动状态 |+| `ctx.host.authorization.cancel(key)` | void | 确认取消已被 Go 接受;收尾由所属授权调用完成 |++flow 为 `{key, title, methods, run(session)}`。run 是 Node 回调;Go 根据自有管理请求启动它,session 提供 method、signal、`notify(notice): Promise<void>`、`prompt(request): Promise<string>`、`commit(record): Promise<void>`。commit 仅对 Go 当前接纳的授权尝试及其本实例凭证有效;没有任意设置另一授权尝试为成功的入口。++浏览器授权还可调用 `const callback = await session.callback({state})`,得到只属于当前尝试的 `callback.url`,再以 `await callback.wait()` 接收 query 参数数组。state 来自插件所用服务商库,Go 绑定尝试并校验匹配与一次性接收;插件仍校验 issuer、响应和 PKCE,并交换、验证、提交凭证。URL 的公开入口由 Controller 验证后的地址派生,插件不能选择其他账号或注册任意 HTTP 路由。接收到回调不表示授权完成,query/code 不出现在前端的授权视图或 Redis 中。等待回调和等待 prompt 一样不套管理请求的短超时。++本项目 notify 也采用有确认的 Go 请求:await 只确认通知已交给 Go 交互 surface,不表示用户已阅读,更不等待用户回答。prompt/commit 则分别等待真实答复/实际持久化。没有通用 120 秒 RPC 超时。++Go 控制同一 key 的授权准入、取消、记录提交和结束。Node 只实现具体供应商的跳转、设备码、交换 token 等协议。Go 返回成功前确认该次授权确实提交了记录;run 正常返回不等于已授权。++供应商响应和 token 有效性的业务验证仍由 flow 实现;Go 的提交校验保证记录格式、归属及活动尝试一致,不等于 Go 能独立证明任意第三方 token 有效。凭证授权与工具执行权限审批是不同服务,不能相互替代。++### 6.5.1 上游与当前 Go 实现的实际关系(2026-11-20 源码核对)++**MCP OAuth 与业务插件共用通用 authorization 和 credentials;协议实现各自负责。** 不能将模块不同或管理请求入口不同,表述成两套独立授权基础设施。++上游固定版本 `ca33fd6843b205e279c7ccb6cb73a472c78f5760`:++1. `McpOAuthAuthorization.start()` 获取 `ctx.authorization` 与 `ctx.webServer`。+2. 临时 `registerFlow({key, label, methods, run})`,调用 `authorization.begin(...)`。+3. 通用服务管理本次流程与取消;`run(session)` 回到 MCP 实现,负责发现、回调、PKCE、换取 token 等协议工作。+4. MCP 通过 `session.commit(oauthRecord(grant))` 写入共享 credentials,通用服务确认提交后才报告成功;之后清理临时 flow 和回调。+5. MCP token 刷新由其凭证适配器通过共享 Store 的 `modifyRecord` 串行处理,不要求所有业务插件采用 MCP 的 grant payload。++当前 Go:`internal/host/host.go` 创建唯一 `credentialStore` 和 `commonAuthorization`,同时传给 MCP Manager 与插件 Manager。`internal/mcpclient/oauth.go` 已使用同一个服务的 `Register(Flow)`、`BeginDrained`、`Session.Commit/AdmitCommit`;MCP 协议由 Go MCP 模块和所用 OAuth/MCP 库处理。Node 业务插件的 flow 则经 RPC 在同一个 Go 服务中注册与运行。MCP 与普通 flow 的状态投影和前端入口已按第 9.5 节组合到所属插件详情。++上游通用词汇是 methods、notice 和 prompt:method 提供 id/label;notice 提供 message/url/code;prompt 提供 text/secret/select。它协调与人的交互,不自动知道任意服务商的 OAuth 端点与业务规则。前端优先复用这些合同,不为了每个供应商另写一套页面。++依据:[通用 authorization](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/credentials/authorization/src/index.ts)、[交互类型](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/credentials/authorization/src/types.ts)、[MCP OAuth](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/mcp/mcp-client/src/oauth.ts)、[MCP 凭证与刷新](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/mcp/mcp-client/src/oauth-credentials.ts)。++### 6.6 MCP++| 方法 | Promise 结果 | 说明 |+| --- | --- | --- |+| `ctx.host.mcp.register({name, connection, toolLoading?})` | Registration | 注册本实例服务,由 Go 连接、发现、管理工具 |+| `ctx.host.mcp.list()` | McpServiceView[] | 本实例所属服务的实时 Go 状态 |+| `ctx.host.mcp.inspect(name)` | McpServiceView 或 null | 单项查询 |+| `ctx.host.mcp.restart(name)` | McpServiceView | 等待旧连接清理和新一代初始连接处理,返回实际状态 |+| `ctx.host.mcp.authorize(name)` | AuthorizationAttempt | 启动协议级授权;等待创建尝试,不等待用户整个授权完成 |+| `ctx.host.mcp.cancelAuthorization(name, attemptId)` | void | 取消指定尝试 |+| `ctx.host.mcp.signOut(name)` | void | 按 Go 现有机制清理对应授权,不删除整个插件 |++connection 使用现有 Go 支持的 stdio/Streamable HTTP 配置、凭证引用和协议 OAuth 参数,逐字段校验;没有实现的 transport 明确拒绝。不继承上游宽泛服务对象,不暴露 Connection 指针、任意 MCP RPC 透传或单独的 probeFromClient。++MCP 服务名为 `<instanceId>__<name>`,按当前 Go 规则检查最终名称不超过 32 字符;工具名仍另按 Go/模型名称空间规则校验,不能与服务名长度限制混用,也不静默截断。MCP 工具加入 Go 统一工具表,不由 Bridge 增加另一套 Agent 可见范围。++复用当前 Go Register/Restart 的初始连接等待和取消清理,不新增后台准入队列。register 返回 Registration 表示 Go 已接受资源并完成本次初始处理,不保证 connected;Go 允许保留的等待凭证/授权等状态,通过 list/inspect 及状态通知读取。Go Register 返回错误时,Bridge reject 并清理未成功的登记,不改成“返回成功但偷偷保留失败连接”。之后已登记服务的状态变化由 Go 维护;restart 返回实际状态或明确错误,错误后的状态仍可 inspect。协议 OAuth 由 Go 处理,普通插件不必重复实现它。++不额外提供 watch 与事件两种并行订阅入口;状态通知使用统一 ctx.on 机制。用户仍通过插件接入 MCP,不新增面向用户的独立 MCP 配置界面。++### 6.7 审批与问题服务的通信入口++| 方法 | Promise 结果 | 说明 |+| --- | --- | --- |+| `ctx.host.approvals.request(call, {reason, detail?})` | ApprovalOutcome | 仅活动工具 body 内复用 Go 单次审批 |+| `ctx.host.questions.ask(call, request)` | QuestionAnswer | 等待回答或取消;复用 Go 非限时问题服务 |++审批结果为 allowed/rejected/cancelled/unavailable,Bridge 映射 Go 既有 outcome;只有 allowed 可继续本次操作。审批不是通用有限超时 RPC。当前权限策略和答复通道仍由 Go 判断,插件不能自己答复。++插件 questions.ask 只提供等待真实回答的 Promise,不在本轮暴露 timed/pending 变体;call.signal 或工具生命周期取消时结束。它等待业务结果,但不阻塞 Node 事件循环。现有内置 ask_user_question 的限时与迟到回答机制保持原样。++原因来自当前代码:`harness/interaction/projection.go` 的限时恢复依赖 ask_user_question 的工具名、请求 schema 和 tool/call/result;任意插件工具内部发问不能直接假定已具备相同恢复事实。此处选择不复制它的特殊时序合同,也不为插件询问新增一套持久事件。Plan 审查仍为 Go 内置非限时流程,不暴露给插件作为权限提升。++此处仅定义进程通信入口,不重新设计问题 UI、SSE 或前端审批入口。++### 6.8 图片与文件:本轮不开放 Assets 服务++图片附件、文件读取、生成图片、显式 present 及下载是已有 Go 内置能力,保留原实现;它们不因存在第三方插件就需要各增加一个公开 RPC 接口。++本轮不提供 ctx.host.assets,不提供图片读写 spool、插件 ImageRef/PresentedFileRef 或插件 file/image 结果块。此前为这些接口新增的 Bridge、SDK 类型及专属测试应清理,不作为待补齐功能。第 8 节中的图片输出治理和 present 最终成功确认仍属于内置工具执行流程,不能连带删除。++插件可以用自身代码生成工作区文件,在文本中说明路径;需要交付时仍由 Agent 调用既有内置 present。文本路径、Markdown 链接和 data 不会自动转换为交付事实。此处不允许插件任意调用 Go 工具,也不引入自动产物扫描。++### 6.9 当前调用的范围++call 是数据与活动调用凭据,核心状态仍在 Go;不包含 `.agent.ctx`、`.session`、writer、model client 或 Redis。凭据只对当前 body 有效。sessionId/cwd 可以作为业务说明,不能当作权限凭据传回创建有效调用。++本轮不提供 `concludeTurn`、`deferContext` 等额外控制方法;插件结果正常返回即可,普通附加说明放 content,长期说明用 prompts/skills。将来确有控制执行流的业务再单独设计,不因旧 SDK 曾经存在就保留。++### 6.10 明确不开放的服务++不提供 ctx.host.agents/sessions/jobs/schedule/memory/models/runtime/redis/shell 等完整管理服务,不开放日志提交、任意工具调用、全局 post-result 改写、核心提示覆盖、用户答复者和插件客户端代码。++这些能力的已有内置工具和 Go 模块保持不变。插件工具可以被普通会话、子 Agent 或 Schedule 投递启动的会话调用;第三方不必拥有这些模块的执行权才能提供外部应用能力。++### 6.11 公共数据类型与状态含义++| 类型 | 应提供的字段/语义 |+| --- | --- |+| HostInfo | userId、hostId、dataRoot、apiVersion;属于只读说明,不是控制凭据 |+| PreparationContext | sessionId、cwd、workspace、signal,以及可选 model:{provider,name} 的非敏感描述;不包含 API Key、请求头或可调用模型对象 |+| SkillSummary | name、description、来源/provider、可选 path/resourceBase/whenToUse、modelInvocable/userInvocable |+| SkillDefinition | SkillSummary 加正文 content;资源信息由 Go 规范化 |+| CredentialRecord | api-key 的 key/env,或 grant 的 JSON payload;数据内容由所属业务解释 |+| AuthorizationSummary | key、title、methods、phase;不返回 token,phase 不等于工具执行权限 |+| McpServiceView | 本实例逻辑 name、实际状态、工具数量、可选授权尝试和公开错误;不用布尔 connected 混淆等待凭证/授权/连接失败 |+| QuestionRequest | Go 现有问题字段:questions 中各项 id、question、header、options、multiSelect;不允许插件将 intent=approval/plan-review 当作授权 |+| QuestionAnswer | 逐项 id、selected、自定义文本,使用当前 Go Answer 的结构;不存在插件替用户填写答案的方法 |++所有 DTO 是序列化快照,修改 JS 对象不会改变 Go 核心状态。需要改变已公开能力时必须调用相应方法;不存在自动同步“属性赋值”的代理机制。字段的 JSON 编码和最大长度需在正式 SDK/Go decoder 中共同定义并测试,禁止直接导出整个 Go 内部 struct。++## 7. 原生 `ctx.on` 与 Host 事件派发++### 7.0 与上游 Cordis 事件语义的区别++上游 `ctx.on` 本身不是“只读通知”接口;它负责注册监听函数。事件是否等待监听器、是否采用返回值以及是否允许影响执行,由事件定义和触发方使用的派发方式决定。Cordis 原生提供 `emit`、`parallel`、`serial`、`bail` 和 `waterfall`。例如,上游 `tools/pre-execute`、`tools/execute`、`tools/post-execute` 是使用 `waterfall` 的执行扩展点;`tools/result`、`tools/change` 则是 `emit` 通知。依据:上游固定版本 `ca33fd6843b205e279c7ccb6cb73a472c78f5760` 的 `packages/core/tools/src/events.ts`、`pipeline.ts` 和 `vendor/cordis/src/events.ts`。++本项目不复制上游工具 waterfall。上游工具系统是事件的派发者,不是靠监听事件驱动自身;next 是它选择的中间件组合方式,与核心服务是否插件化并无必然关系。我们的 Go 工具系统直接调用公共处理和具体工具函数。++公开 host/* 事件只用于观测,返回值不修改工具执行决定。插件仍可在通知内调用公开 ctx.host 方法产生独立操作,不能据此接管当前 Go 调用。Cordis 自身与插件之间的本地事件语义保持原生,并不被统一改成只读。+### 7.1 注册与派发++```ts+ctx.on('host/skills-changed', event => {+ // 观察来源变化;需要最新内容时查询 Go Skills 服务。+ ctx.logger.info('skills changed', event.instanceId)+})+```++ctx.on/once 使用 Cordis 原生本地注册和 disposer,不发注册 RPC、不覆盖 events.register、不伪造同步 Go 调用。Bridge 接收 host.event 后使用真实 Cordis 监听表向当前 Host 的活动监听器派发;不广播 token、密钥、任意工具参数或全部会话正文。++host/* 是同一账号 Host 内的公共观测事件;涉及插件资源的 payload 带 instanceId,监听方可以筛选自身或观察其他业务扩展的公开状态。方法调用中的 owner 限定不等于事件总线天然私有;这里不伪造 Cordis 的“每个 child Context 自动拥有独立事件总线”语义。++Go 每个 Host 的状态通知按输出队列顺序发送;涉及资源的通知带 instanceId 及对应 key/name 等标识。Node 按接收顺序开始分发,不承诺异步监听器完成顺序。原生监听参数和 prepend 可保留;通知的业务返回值一律忽略。++### 7.2 开放的 Host 事件++| 事件 | payload | 何时发送 |+| --- | --- | --- |+| `host/skills-changed` | instanceId、来源变更标识 | Go 接受贡献变更/失效后 |+| `host/credential-changed` | instanceId、key、configured | 凭证已提交变更,不含值 |+| `host/authorization-changed` | instanceId、key、phase、可公开错误 | 授权状态变化 |+| `host/mcp-changed` | instanceId、name、state、可公开错误、toolCount | MCP 状态变化 |+| `host/stopping` | reason | Go 正常关闭前的尽力通知;不保证崩溃时存在 |++通知中需要时间戳时使用 Unix 毫秒,不改变 Go 模块已有事实的原始时间编码。状态通知不提供可执行 invocation,不能借通知发起当前工具调用的提问或审批。不为工具执行另建开始/结束通知、耗时统计或配对事件合同。++本轮不把 agent/session 所有内部事件逐条输出到插件层。上表是完整的 Host 公开通知白名单,不等于新增一个前端消息流或持久事件系统。++### 7.3 返回值、异常与慢监听器++Host 事件由 Bridge 使用当前锁定 Cordis 的 events.dispatch 取得真实活动监听器快照,再逐个隔离同步异常和异步 reject;不因裸 emit 的某个抛错中断其他监听,也不接管事件注册/卸载。Go 不 await 这些函数,因此它们不能批准、拒绝、替换结果或阻塞会话事实提交。++事件队列有界;慢插件造成积压时,状态类通知按 key 合并并记录必要诊断,不逐 delta 无界堆积。不做自动历史重放;插件重连后需要实时状态就调用对应查询。通知不用于任务保证投递或触发必须执行一次的业务。++### 7.4 审批与结果处理不依赖通知++Go 内置执行前策略直接返回决定;需要审批时 Go 调用自己的 ApprovalService 等待结果。内置工具和插件工具也可在实际操作前主动申请同一服务。上述请求有业务返回值,和 ctx.on 通知是不同通信入口。++Go 直接做输出限制、交付校验、结果规范化和日志提交。不将它们包装成 Node post-execute 监听器,也不向插件提供替换其他工具执行器或结果的通用入口。++## 8. 实际调用流程++### 8.1 四个内部处理点:PreExecute → Execute → PostExecute → Result++本节为统一调用流程的实施规范。**Go 保留三个执行阶段和一个最终结果处理环节,对应上游 tools/pre-execute、tools/execute、tools/post-execute、tools/result;所有内置、插件、MCP 工具共用,不要求每个工具实现四组回调,也不向 Cordis 暴露四个阶段事件。** 上游把核心模块装配成插件并在阶段事件中调用它们,我们在相应 Go 阶段直接调用内置模块。插件工具只在执行本体时经过业务 RPC,不经 Node 的阶段派发或 continuation。++| 上游对应 | 我们的 Go 内部阶段 | 处理目标 | 阶段返回 |+| --- | --- | --- | --- |+| prepare、tools/pre-execute、审批解析 | PreExecute(可复用 Prepare) | 完成本次调用准备及执行前策略判断,得到执行或拒绝/取消结果 | Go PreToolDecision;解析审批并形成 ToolPreparation |+| tools/execute、dispatchToolBody、核心执行保障 | Execute(可复用 Dispatch) | 在可靠执行边界内调用既定工具,取得成功/失败结果 | Go ToolPipelineResult,外加原生 NeedsPost 流转标记 |+| tools/post-execute、finalize/materialize | PostExecute(可复用 Complete 的结果处理和 finish 的最终校验) | 应用核心结果处理,确定不可再被观察者修改的最终结果 | 最终 Go ToolPipelineResult |+| tools/result 及所采用的核心结果监听逻辑 | Result(由 Go 直接调用最终处理与提交) | 根据最终成功/失败处理核心收尾,按现有顺序提交事实、完成既有前端投影 | 不返回处理决定;核心提交错误返回调用者,不当作观察者错误忽略 |++顺序固定为 PreExecute → Execute → PostExecute(末尾完成最终校验/物化)→ Result,最终校验不是第五个阶段。上游 post 在 result 之前;post 可以决定如何处理结果,result 的监听器只接收最终冻结结果,不再返回 accept/block 或替换内容。Go 的 Result 单独承担对应核心模块的最终处理,不能笼统合并成 post 后任意一个通知。已有批调度器继续负责有序写入,不要求搬走 Session writer 或新增执行状态机。++#### 8.1.1 PreExecute:上游在执行前具体做什么、Go 如何对应++| 上游模块/位置 | 在 pre-execute 附近的实际逻辑 | Go 对应处理 |+| --- | --- | --- |+| core/tools 的 prepare | 固定调用身份及参数快照,检查取消,保留本次调用使用的定义和上下文 | Go 准备当前调用,保留 callId、sessionId、turn/step、工具定义和参数;不允许执行中重写已记录的名称/参数或切换到同名新工具 |+| jobs/tool-jobs 的 pre 监听 | 捕获本次调用使用的可见输出上限,供后续 Job 输出终结使用 | Go Job/输出模块在 PreExecute 捕获所需输出限制,PostExecute 使用同一份规则;不依赖 Node WeakMap 保存此状态 |+| deliverables/workspace-changes 的 pre 监听 | 找到该会话的变更记录器,等待已有变更处理稳定,保存与本次调用的关联 | 这是上游文件变更追踪能力;当前项目已选择显式 present,不在本次恢复自动扫描/推测产物。若已有 Go 文件观察状态需要同步,由对应内置模块在此处理;不能为复制监听器额外新增 artifact-probe |+| core/tools 的审批解析与取消检查 | ask 转交统一审批服务;获准后重新检查取消 | Go ApprovalService 等待真实答复,未获允许不执行;获准后检查取消并进入 Execute |++PreExecute 不执行被调用工具的业务副作用,不因阶段划分额外创建业务资源或自动重试工具。所需核心处理由 Go 已有模块按适用条件运行;上游 experimental 的风险审查、外部 hooks、协作授权等不进入本次阶段处理清单。++输入 JSON/schema 校验必须在实际工具副作用前完成。当前 Go 的 schema/Tool.Validate 位于 executeNativeToolDirect 入口;本方案可保留这个位置,对应上游工具调用入口的校验,而不是为了给阶段凑功能强行迁入 PreExecute。PreExecute 的参数快照、策略判断与 Execute 入口的参数合法性检查必须区分。++**上游固定返回格式及 Go 采用方式:**++| PreToolDecision 形状 | 含义 | Go 下一步 |+| --- | --- | --- |+| `{kind:'allow'}` | 策略允许继续 | 检查取消后进入 Execute |+| `{kind:'deny', reason, info?}` | 策略拒绝,带原因及可选错误身份 | 生成拒绝结果;不调用工具 |+| `{kind:'cancel'}` | 取消此次执行 | 生成取消结果;不把取消伪装成业务拒绝 |+| `{kind:'ask', reason?, displayReason?}` | 请求用户决定 | 调 Go 审批服务;同意后才继续,其余结果转拒绝/取消 |++复用当前 Go PreToolDecision;这是 Go 内部策略结果,不是向插件暴露的新 JSON-RPC 协议。策略返回非法 kind 或执行异常时失败关闭,不能默认允许;没有配置的通用策略默认为 allow,真实权限与工具自身的限制仍照常生效。++#### 8.1.2 Execute:上游执行期间的核心保障与真实工具调用++| 上游模块/位置 | 实际逻辑 | Go 对应处理 |+| --- | --- | --- |+| session/session-checkpoint-policy 的 tools/execute 监听 | 顶层工具副作用前 flush 会话;失败则不调本体;嵌套调用复用外层持久边界 | 将“调用事实已可靠落盘”作为 Go Execute 的副作用前置条件。当前 appendNativeToolIntent 已提前记录并 Flush,可满足该边界;不为阶段命名重复落盘,也不移到 Node |+| guard/timeout-policy 的 tools/execute 监听 | 依据 timeoutMs 派生取消信号,等待操作收尾,再把自身到期归类成 TOOL_TIMEOUT | Go 在 Execute 内管理 deadline/cause,传递给实际 Go 操作、插件 RPC 或 MCP;取消后等待在途操作收尾,不只返回一个超时而放任后台副作用继续 |+| core/tools 的 dispatchToolBody | 保留调用身份、合并原始取消信号,解析既定工具并调用其 execute;把返回或异常变成规范结果 | Go 只调用本次固定的 Tool;统一入口先做 schema/Tool.Validate,随后进入业务函数;取消、错误和上下文保持 Go 所有 |+| 工具自己的 execute | 执行业务,必要时主动申请审批后才产生副作用;可返回结构化业务值 | 内置工具运行 Go 函数;插件工具 RPC 调 Node 回调;MCP 工具由 Go Client 调服务端。工具业务内部审批仍使用同一个 Go ApprovalService |++Execute 的阶段入口与工具业务 execute 不是同一个概念:前者属于 Go 执行器,包含上述执行边界保障;后者是阶段内被调用的一项业务实现。bodyStarted 应反映是否已调用业务函数/外部适配器,不能仅凭进入阶段就认定已执行。远端操作是否真的产生副作用可能无法确认,断连时保留未知结果语义,禁止自动重发。++并发调度继续由 Go 批调度器管理:按调用顺序准备、只有明确可并行的工具允许重叠 Execute、按原调用顺序完成和提交。不是每个工具另造一个队列,也不是让 Node 管整个批次。++**上游与 Go 的固定结果形状:**上游的工具业务函数返回其声明的 canonical value,工具系统验证/渲染后才得到 ToolExecutionResult;并非所有工具 execute 自行构造整个系统结果。其规范结果分为:++| 结果 | 必要内容 | 可选内容/约束 |+| --- | --- | --- |+| 成功 | `isError:false`、JSON `value`、有序 `content` | meta、additionalContexts、concludesTurn;没有 error |+| 失败 | `isError:true`、`error:{message, info?}`、有序 `content` | meta、additionalContexts;没有成功 value,不得声明成功结束 turn |++Go 复用现有 ToolPipelineResult/codec 作为内部规范结果,不再建立一套 Node 阶段结果协议。公共插件 SDK 的 ToolResult 仅为 text content + 可选 data,异常通过 throw 返回;Go 适配器验证并转换为上述内部成功/失败格式,不接收插件生成的会话 Meta、图片引用或交付声明。Go 内置工具仍按既有内部合同处理 image/file 等内容,不受插件 SDK 的结果子集限制。++执行前 ask 已在 PreExecute 解决后才启动工具执行预算。工具内部发起的审批不新增独立的 120 秒超时,但仍受本次调用取消和工具已声明预算的约束;不将工具 deadline 和普通审批服务的超时混为同一概念。++#### 8.1.3 PostExecute:结果变换、输出治理与最终物化++| 上游模块/位置 | 在 post-execute 及其终结处理中的实际逻辑 | Go 对应处理 |+| --- | --- | --- |+| guard/repeat-tool-reminder | 统计同工具、同参数的连续调用,达到阈值附加模型上下文提醒;不阻止调用、不改写业务结果 | Go 重复调用状态在 PostExecute 收尾更新,提醒按原调用顺序放进下一次模型上下文;当前 repeatGuard/commitNativeToolResult 已有对应路径,应保留重置条件和适用分支 |+| fs/tool-fs-search 的 grep/glob | 对过长搜索结果保留受限预览,必要时保存完整结果并返回恢复引用 | 对应 Go 搜索/输出模块负责相同的结果保留行为,由 PostExecute 统一接入;不能用 Node post 监听器补,也不能只截断就宣称已还原可恢复输出 |+| spill/spill-policy | 按输出预算限制文本/图片展示,将完整文本和图片访问引用写入 spill,产生可读取的恢复提示;失败按其规定保留可用内容 | Go 输出治理模块在 PostExecute 承担。当前只有部分工具的截断/spill 路径,通用预算与恢复引用需逐项核对补齐,不宣称已经全量等价 |+| jobs/tool-jobs 的输出终结逻辑 | 使用 pre 捕获的上限保留 Job 状态后缀、限制可见输出 | Go Job 输出处理器使用 PreExecute 捕获的同一限制,在 PostExecute 应用;不丢 Job 状态或重复附加后缀 |+| core/tools 的 project/finalize/materialize | 将工具值变成模型内容、执行适用的内置变换、验证并物化最终 JSON,区分成功与错误 | Go 保留必要的转换和最终校验;不公开插件 render/project/finalize 全局回调,不因删除远端 post hook 而删除 Go 终结逻辑 |++这些是同一 PostExecute 的适用处理器,不是要求每个结果被每个处理器重复截断。搜索/Job 的特有输出处理和通用 spill 必须共享本次预算及完整输出来源,明确处理顺序,保留恢复引用和 Job 状态;已经受限的预览不能冒充完整原文再次保存。重复调用提醒在按原调用顺序收尾时只计算一次,所产生的附加上下文随本次最终结果交给 Result 提交。++上游 PostToolDecision 有固定格式:++| PostToolDecision 形状 | 行为与限制 |+| --- | --- |+| `{kind:'accept'}` | 保留当前结果 |+| `{kind:'accept', content, additionalContexts?}` | 替换模型可见内容,可附加合法上下文 |+| `{kind:'accept', value, additionalContexts?}` | 替换成功业务值,再经过该工具的输出校验和渲染;不能用于把失败结果改成成功 |+| `{kind:'block', feedback, info?, additionalContexts?}` | 以反馈生成失败结果;不能撤销已经发生的工具副作用 |++accept 也可仅附加 additionalContexts;value 与 content 不能同时替换。Go 可复用现有 PostToolDecision 作为内置结果处理器的返回,统一应用后由 PostExecute 返回最终 ToolPipelineResult。这个决定只供 Go 模块直接调用,不暴露通用 post 注册接口或 RPC。没有相应已验证输出 renderer 的工具,不凭空允许 value 替换;插件 content/data 走自己的已校验适配合同。++最终校验要求包括错误身份、合法 JSON 和内容块、合法的附加上下文;对 Go 内置图片/交付结果还包括不可变图片引用、工作区交付路径。Go 内部输出规则可调整可见内容;不得据此静默重跑工具或将失败交付标为成功。++#### 8.1.4 Result:最终结果确认、核心模块收尾与提交++上游 tools/result 是 emit 型最终结果通知:它在普通 post 处理、最终内容转换和物化之后发生,监听器不能通过返回值再修改结果。上游所采用核心模块在此做的事情,在我们这里仍必须由 Go Result 环节直接完成;对外观测通知不能代替这些核心步骤。++| 上游模块/位置 | 根据最终结果做什么 | Go Result 对应处理 |+| --- | --- | --- |+| deliverables/tool-present 的 tools/result | 仅最终成功时确认交付事实,失败则丢弃暂存交付 | 内置 present 根据已校验文件和最终结果形成交付事实,经既有 writer 提交;不在业务 execute 刚返回时提前发布,不新增插件交付入口 |+| subagent/structured 的 tools/result | 只有最终成功的结构化输出才成为正式捕获结果,失败不确认 | Go 对暂存的结构化输出做最终确认/撤销;保留该工具自身防止重复提交的业务检查,不新增 PreExecute guard 或禁止其他工具的公共限制 |+| context/agent-instructions 的 tools/result | 归集最终成功调用触及的文件路径,为后续指令上下文更新状态 | Go 指令观察模块根据最终结果处理触及路径;取消/失败不确认成功触及,必要的嵌套归并仍归 Go |+| 工具系统及会话提交方 | 最终结果供调用者、日志和 UI 使用 | Go 批调度/会话路径按既有顺序写 tool/result、交付事实及适用上下文,并在规定边界 Flush |++上游重复调用提醒的计算位于 post-execute,我们也归入有序 PostExecute;当前 commit 收尾处若仍包含计算,应抽到该职责位置,不能在 Result 再计算一次。Result 只提交已经形成的提醒及上下文,保留原有适用分支。++**Result 的固定输入/输出:**输入是最终的只读 ToolPipelineResult;正常完成不返回业务决定,Go 核心收尾失败可返回 error。上游 emit 监听器的业务返回值被忽略,我们同样不接受 Result 返回 accept/block 或内容替换。此处不再接受 PostToolDecision,不重新渲染/改写结果,不重跑工具。内存核心状态的确认应与持久化边界协调,不能在提交失败时继续按已成功保存推进;所需现有 writer/状态模块由 Go 直接调用。++**提交边界:**先根据最终结果准备本次适用的交付/结构化确认/指令更新,再由现有有序会话提交路径写入所需事实并在规定边界 Flush;依赖这些事实成功的内存确认及正常推进必须在该边界成功之后。可由已有事实恢复的状态继续由事实恢复,不增加另一份结果日志或跨模块事务。失败不发布成功交付,不重跑已产生副作用的 body;本轮不承诺多条 JSONL 事实具备数据库事务式的原子提交。++核心提交错误和外部观察者错误必须区分:tool/result、交付事实或所需持久状态写入失败要返回错误并停止正常推进;插件观测回调失败只做异常隔离,不能使已提交事实失效。++Result 不额外向插件发送工具开始/完成通知,也不靠 Node 的工具结果监听器执行 present、结构化确认或其他核心提交。既有会话日志及面向前端的 HTTP/SSE 工具消息继续使用原实现;删除自定义插件通知不删除这些能力。++#### 8.1.5 失败、拒绝、取消的固定流转++| 情况 | Execute 本体 | PostExecute 处理方式 | Result / 会话投影 |+| --- | --- | --- | --- |+| 正常返回 | 一次 | 完整结果处理与最终校验 | 按序提交,沿既有会话链路向前端投影 |+| 工具抛错、业务失败、工具超时 | 已调用;取消时先收尾 | 规范错误、执行适用的失败处理,不执行成功交付 | 提交失败结果,保留错误身份 |+| Pre 决定拒绝、审批未获允许 | 不调用 | 对拒绝/取消结果执行适用的结果处理;不可恢复成放行 | 可提交拒绝/取消结果,保留工具本体未被调用的内部事实 |+| Pre 内部异常、非法决定、进入执行前已取消 | 不调用 | 直接最终物化;跳过会造成业务变换的普通处理 | 按已有事实边界提交明确错误/取消,不假称工具已运行 |+| 调用预算拦截 | 不调用 | 使用内置终结路径,不增加一次“重复调用”统计 | 按既有批次规则提交预算结果 |+| checkpoint 失败 | 不调用 | 返回持久化失败;不伪造可可靠提交的业务结果 | 停止正常推进,不向调用方或前端伪称成功 |+| 插件/服务断连 | 根据实际是否已派发判断 | 未派发则不可用;已派发且无法确认则保留未知结果 | 不自动重试副作用,不伪称确定没执行 |++沿用当前 NeedsPost 对 post-result/final-result 的区分:不是所有异常都执行普通 post 变换,但都需要最终物化/资源清理;由工具系统接纳并形成最终结果的调用,仍进入适用的 Result 收尾。调用预算等在 AgentLoop 提前合成的结果保留原有分支,不能新增不适用的重复统计或成功确认。四个处理点不表示每次调用都必定执行业务 body 或所有成功处理器。++#### 8.1.6 当前 Go 代码对应与必须核实的缺口++| 当前代码 | 对应阶段/职责 | 实施要求 |+| --- | --- | --- |+| native_tool_source.go 的 refreshTools/installTools | step 工具集合 | 合并内置、插件和 MCP 工具;同一步保留实际对象,不能按名称重新绑定另一实现 |+| native_tool_pipeline.go、ToolInvocation.Prepare | PreExecute | 保留调用准备、Go 执行前策略、审批与取消检查;移除 Node pre waterfall。独立 guard 相关代码按第 12 节清理,不属于目标执行流程 |+| ToolInvocation.Dispatch、executeNativeToolDirect | Execute | 保留 Go 超时/取消/业务调用;删 Node around/next。准确区分入口校验与本体开始 |+| native_tool_scheduler.go 的 appendNativeToolIntent | Execute 的持久化前置边界 | 验证每个真实工具在副作用前均已有可靠调用事实;已有 Flush 不无意义重复 |+| ToolInvocation.Complete/finish、tool_pipeline_codec.go | PostExecute | 保留规范化与最终物化;把必要输出处理接成 Go 内置处理器,不留远端阶段控制 |+| result_limits.go、Shell/Web/Search/Job 现有输出处理 | PostExecute 对应能力 | 核实各入口覆盖、完整结果恢复、状态后缀和图片引用;当前分散实现不等于通用 spill 已完成 |+| repeatGuard、commitNativeToolResult | PostExecute 收尾 | 保留顺序、阈值、用户新消息重置及跳过分支;避免重复更新 |+| NativeStructuredOutput、present、instruction 相关模块 | Result 最终确认 | 核实最终成功才确认及必要状态更新;结构化工具自身防重复提交保持在工具业务内,不在 Pre 增设公共限制 |+| logNativeToolOutcome/commitNativeToolResult | Result 提交收尾 | 工具结果、内置 present 交付、上下文沿既有 writer 提交;不为插件结果新增交付 Meta |++这是基于当前源码的实施核对清单,不是已经完成/测试通过的声明。额外业务能力仍按第 2 节范围;不因为列出上游可选插件就自动引入。++### 8.2 Skill 与提示查询++Go 组装 step → 读取本地与预装 Skill → 必要时 RPC 调用插件 Provider → Go 合并目录/优先级 → 模型按需读取正文。动态提示同样只贡献当前附加文本,最终记忆/上下文和工具声明仍由 Go 生成。++静态目录无需每轮经过 Node 重新扫描;由 Go 发现器读取包内文件,按现有缓存/失效机制处理。++### 8.3 MCP 插件++插件 apply → await mcp.register → Go 接受并进行初始连接/发现处理 → 根据实际状态注册可用工具 → 模型调用某个 MCP 工具 → Go 的工具管线和 MCP Client 执行。不再先回 Node 再由 Node 调同一个 MCP 服务;缺少授权等状态通过管理入口处理。++MCP status 变化通过 host.event 给对应实例;协议 OAuth 调用 Go 内置授权/凭证服务,插件无需持有 Go 连接对象。++### 8.4 授权流程回调++自有管理请求到 Go → Go 准入授权 → RPC 调用 flow.run → Node 实现供应商协议 → session.prompt/notify/commit 请求回 Go → Go 完成对应操作 → run 返回 → Go 确认提交并结束。++调用方正在 await flow.run 时,Go 仍能处理该 flow 发回的请求。不得将同一账号/插件整个 RPC handler 串行锁住,否则会在此处死锁。++## 9. 包、配置与存储++### 9.1 包形态++一个插件包是普通 npm JS 模块,可以包含多项工具、Skill、提示、MCP 声明和业务 Cordis 服务。TypeScript 编译后发布 JS;Go/Python 业务可通过 Node 入口调用本地程序或远程服务。++package.json 增加本项目 metadata:`goBot.api: '1'`,与 `@go-bot/plugin-sdk` 主版本匹配。可选 title/description 和 configSchema 供自有管理表单读取;入口通过 exports/main 解析。无需 dsh manifest、cordis.patch.yml 或上游包身份 pinning。++```json+{+ "name": "@example/go-bot-mail",+ "version": "0.1.0",+ "type": "module",+ "exports": "./dist/index.js",+ "peerDependencies": { "@go-bot/plugin-sdk": "^1.0.0" },+ "goBot": { "api": "1", "title": "Mail" }+}+```++SDK 提供运行所需的唯一 Cordis 类型/帮助导出,业务包不再依赖 dsh-*。普通 npm registry、私有 registry、固定 Git 提交、tarball 和 Host 内开发目录仍可作为安装源;安装器固定版本和锁文件,不要求都发布到 npm 官方 registry。++SDK 仍为 private 包,由 Host 镜像一并提供完整 package.json、类型、运行时导出及许可证。安装器将 profile 中的 SDK 根依赖和同名依赖解析固定到这份本地包,业务插件可声明 SDK peer dependency;不依赖不存在的公共 npm 发布。开发阶段使用仓库内 SDK,TypeScript 的 import type 编译后移除,HostError 等运行时导出也可从 Host 提供的包解析。SDK 不列入用户插件列表,也不能作为业务包卸载。++### 9.2 配置模型++保留简单的 packages/instances,不向用户暴露 Cordis 的 intercept/isolate/patch 组合图:++```json+{+ "packages": {+ "@example/go-bot-mail": {+ "source": { "type": "registry", "spec": "@example/[email protected]" }+ }+ },+ "instances": [+ {+ "id": "work-mail",+ "package": "@example/go-bot-mail",+ "enabled": true,+ "config": { "mailbox": "work", "apiKeyRef": "MAIL_API_KEY" }+ }+ ]+}+```++config 按包 schema 校验;凭证值走 Go credentials,Redis 配置只放引用和非敏感业务参数。新方案不保留 Settings.Credentials 明文 map、Bundles/Patch/ApprovedBuilds/IndexSources 等旧公开配置。安装脚本默认禁用;确需安装构建的包按部署者明确的包安装策略处理,不新建复杂的审批后台。++普通用户的插件发现和安装以第 9.4 节的项目维护清单为准。输入包名、GitHub 地址、tarball 或 Host 目录不再是普通用户的安装流程;底层来源解析器只供项目分发及受控开发测试使用。UI 不保留上游组合/补丁管理概念。++### 9.3 数据归属++| 数据 | 归属 |+| --- | --- |+| packages/instances 期望配置 | Controller Redis user hash 的 plugins 字段 |+| 包版本和安装结果 | Go 包管理器;请求返回给 Controller,自有 UI 展示 |+| 实例加载/应用结果 | Cordis Loader 原生状态;Go 经 runtime.inspect/apply 读取并返回 UI,不另建实例状态机 |+| 包文件、包锁和必要配置投影 | `$DSH_HOME/plugins`;同一 Host 数据根由 volume/NAS 承载 |+| 插件凭证和授权记录 | `$DSH_HOME/.credentials.yaml`,Go 唯一 Store |+| 图片、用户上传文件 | 既有 `$DSH_HOME/attachments/v1`,不另建插件附件库 |+| 插件业务生成的工作区文件 | 当前调用实际 workspace;需要交付时由 Agent 调用内置 present,之后沿既有路径下载 |+| callback handles、invocation、pending、通知队列 | 仅内存,不进 Redis |+| RPC socket | 容器临时目录,不进 NAS,退出清理;本轮不创建资产 spool |++Host 不访问 Redis;Controller 调用 Host 应用配置并等待结果。保存期望配置成功不等于插件已经生效,API 返回二者的实际结果;失败明确标记,不靠五分钟后台循环偷偷重试。++移除插件默认保留用户凭证和工作区文件,便于明确重装;真正删除凭证使用独立 credentials 操作。不提供通用插件 KV/文件 storage,业务包若需要自己的业务数据可以使用自身代码和外部服务。++### 9.4 项目维护的插件市场(已实施并完成定向验收)++**市场展示本项目提供和审核通过的可用插件。** 普通用户从列表选择,不搜索 npm/GitHub,也不填写下载源。底层仍使用既定包管理器与 Cordis,不重新设计插件执行和生命周期。++- 在 `extensions/catalog/plugins.json` 维护可用清单,随 Controller 构建内置。新增或更新条目通过项目 PR 审核;本轮不新增远端清单地址配置、用户自定义市场源或自动后台更新任务。+- 条目提供稳定 pluginId、原始名称、中英文 description、版本、图标路径、维护者、许可证,以及内部使用的包名和安装源。展示字段由包内 plugin.json 提供,不额外增加 capabilities/setup/connection。icon 指定 Controller 提供的静态图片路径,资源随插件包保存;两端按 URL 显示,不维护图标枚举、品牌映射或插件客户端代码。+- 包可来自已支持的 npm registry、固定 Git 提交或分发包;这些是维护者的分发决定,不作为普通用户的安装输入。发布版本必须可重复定位,不能把 latest/浮动分支存成已安装版本。+- 正式业务插件才进入市场。内置浏览器、Office、模型、搜索、记忆、AgentLoop 等不改装为市场插件;`examples/plugins` 的开发示例不冒充可用产品。+- 清单只是可选项;Redis 的 `user.plugins` 仍只保存该用户实际安装的 packages 和实例配置。package 增加 catalogId 以关联条目,并保留当次安装的固定 source 快照,确保重启不会被市场的新版本静默替换。凭证不进入清单或 Redis config。++普通流程:**浏览市场 → 查看能力及连接要求 → 安装 → 配置实例 → 启用 → 按该插件提供的方式连接账号。** 安装包不等于已配置或已授权;插件初始化必须能先注册授权入口,不能因为尚无账号凭证而让用户永远无法发起授权。工具业务在凭证缺失时明确报错,不擅自访问第三方。++Web 与移动端均提供“插件市场/已安装”。详情展示能力、版本、配置、连接与授权、启停和卸载;默认实例名由框架给出,普通使用不要求手填技术标识。多个实例能力保留在详情的扩展操作中。配置基于包 metadata 的 schema 和必要说明;不加载任意插件前端脚本,也不把 JSON、来源类型或私有 registry 认证作为市场主界面。++市场入口不放在设置中:Web 侧边栏提供独立的“插件市场”入口,页面为 `/plugins`;手机会话页右上角提供组合菜单,包含“文件系统”和“插件市场”。从这些入口打开默认显示市场页签,已安装管理仍在同一页面。手机“我的”的设置列表不增加插件市场。++公开安装/更新 API 接收 pluginId,由 Controller 查清单并解析来源;服务端也要限制,不能仅删除前端输入框而继续允许提交任意 source。普通实例修改只接收 config/enabled 等业务设置。Host 私有安装与完整 settings 应用接口仍供 Controller 和受控测试使用。更新必须由用户明确操作,不自动更换在用版本。清单暂不可用或某包下架时,已有固定安装记录不被静默删除;界面可展示现有包信息、停用或卸载。++### 9.5 插件的连接方式与认证交互(已实施并完成定向验收)++前端只展示该插件当前实际注册的授权方式:单方式直接进入,多方式供用户选择,无认证需求不显示授权入口。不预设每个插件都支持 API Key 或 OAuth;具体字段由选定流程运行时的 prompt 请求生成,授权输入不进入聊天或模型上下文。++**统一交互词汇和凭证基础设施,供应商协议由对应实现负责。** 不统一成一个固定 API Key 框,不要求用户知道背后是否为 MCP,也不因为接入 MCP 就一律显示 OAuth 按钮。++| 接入情况 | 协议与凭证处理者 | 插件详情里的用户入口 |+| --- | --- | --- |+| 不需认证的 MCP/API | 插件或 Go MCP 直接连接 | 配置或启用;不显示多余授权表单 |+| MCP 标准 OAuth | Go MCP OAuth,复用 Go authorization 与同一 credentials Store | 授权连接按钮、服务商授权链接、结果与重试 |+| MCP 要求 API Key/固定 token | 包装插件通过通用 flow 收集和验证;Go Store 保存;Host 私有 headers/env 或受控引用用于连接 | 该服务声明的密钥输入和保存入口 |+| 非 MCP 的 API Key、应用凭证、账号密码等 | 业务插件的 flow,复用 Go authorization/credentials | 插件定义字段;secret 掩码、text 输入、select 选择,支持分步或多个待输入项 |+| 非 MCP 的 OAuth/设备码等 | 业务插件使用供应商 SDK/OAuth 库实现协议;通用服务管理交互与提交 | 浏览器授权、复制设备码、等待、成功/失败及取消 |++MCP 官方规范将认证定义为可选能力;标准 HTTP 授权规范不代表每个 MCP 都支持 OAuth。stdio 通常从环境取得凭证。还应区分“访问 MCP 服务的凭证”和“MCP 背后第三方应用的凭证”,由包装插件说明真正需要连接的账号。[MCP 认证规范](https://modelcontextprotocol.io/specification/latest/basic/authorization)++#### 9.5.1 方法与页面由谁决定++- 业务插件通过 flow 的 methods 声明可选认证方式,label 直接说明“使用 API Key”“浏览器授权”等。只支持一种时直接显示对应入口;支持多种时让用户选择,不出现所有供应商共有的固定字段集合。+- 用户选择后启动已有 Go 授权服务。插件通过 notice/prompt 描述下一步,前端按 text/secret/select、url、code 等内容渲染。多个字段可以分步收集,也可以展示同时等待的多个 prompt;不因为要支持表单就先引入另一套认证服务。+- MCP 包装插件声明连接,由 Go MCP 模块承担标准 OAuth;前端根据该实例实际注册的 MCP 资源与其授权能力提供入口。MCP OAuth 的通用 flow 在启动时才临时注册,不能只读取 `authorization.list()` 就声称已找全所有可授权连接。+- 统一的插件详情可组合普通 flow 和 MCP 原有授权视图。适配层只映射展示/请求,不复制 MCP OAuth 状态机,不在普通 flow 外再启动一个包裹它的独立授权流程,也不复制一份 token。+- MCP 的技术连接状态、传输方式和工具数量不作为用户必须理解的配置。界面显示“未配置/授权进行中/已配置/失败”等实际状态;Cordis 已就绪、凭证已保存和第三方当前可访问是不同事实,不能互相冒充。++Web 使用与现有风格一致的授权面板,移动端使用底部面板;二者使用相同数据和动作语义。跳转系统浏览器后返回应用可刷新当前授权结果。收起界面与主动取消要明确;Host 保存活动授权状态,前端不持有协议运行状态或 token。尚未实际支持的交互应明确报错,不能根据“点击过授权”就展示成功。++#### 9.5.2 OAuth 细节、回调与存储边界++OAuth 的协议细节包括授权/令牌端点、应用 ID 与权限范围、回调、state/PKCE、授权码交换、令牌刷新及撤销/错误处理。MCP 标准 OAuth 复用 Go 内置实现。普通业务插件优先复用供应商 SDK 或 OAuth 库,而非每个插件手写;通用 authorization 本身不自动知道这些服务商规则。++Go 提供当前授权尝试的准入、取消、凭证提交和受控回调转交;供应商协议逻辑仍属于插件。MCP 继续使用原有 Controller→Host 回调链;普通业务 flow 使用第 6.5 节的 session.callback,Controller 的 `/v1/plugins/authorization/callback/{userId}/{token}` 只将当前尝试的回调转交 Host。二者共享同一 authorization/credentials,不互相包裹为新的授权流程。普通回调已接通 Go 与 Promise RPC,并有匹配 state、拒绝重放和不伪造授权完成的测试;Web 和 Android 已完成本地受控服务的浏览器授权验收,证据见第 14 节。不能因 notice.url 或单次收件成功就宣称任意服务商 OAuth 已验证。++所有凭证继续进入唯一 `$DSH_HOME/.credentials.yaml`。MCP 保留其 client/grant payload 与绑定规则;业务插件保留自身记录格式。统一 Store 不等于统一各服务商的 token JSON。MCP 的标准刷新由 MCP 模块处理;业务插件的刷新由供应商 SDK/业务代码处理,并复用 Go Store 的安全更新入口。前端只获得已配置标志和脱敏结果,不回显保存的密钥;Redis 保存非敏感配置及引用。保存凭证、获得授权与重新连接的结果要分别按实际情况报告,失败不靠后台定时循环静默重试。++协议依据:[OAuth 授权框架](https://www.rfc-editor.org/rfc/rfc6749)、[PKCE](https://www.rfc-editor.org/rfc/rfc7636)、[OAuth 安全实践](https://www.rfc-editor.org/rfc/rfc9700)、[设备授权](https://www.rfc-editor.org/rfc/rfc8628)。++## 10. 故障与一致性边界++- 无 Node/未启用插件:Go 原生 Agent、会话和工具照常工作,不为核心发布/提交等待兼容回调。+- 某工具回调报错:Go 按这次工具失败处理;不误判成模型协议错误,不自动重试副作用。+- 插件初始化失败:通过 Cordis 原生状态报告失败,原生 effect 撤销此前已接受的贡献;其他成功插件不回滚。注册确认前后可见性按第 5.2 节,不承诺 apply 级原子发布,也不回滚已发生的外部副作用。+- Node 崩溃:所有该进程 pending/callback 失败,插件工具不可用;Go 核心保留,已接纳运行的副作用结果可能未知。共享进程意味着所有业务插件均受影响。+- 重连:不复用旧 callback handle 或 invocation,不重放工具执行;明确重载实例以重建注册。Go 内置策略和限制不依赖 Node 连接状态。+- 并发配置变更:由现有管理请求串行准入;不增加每次操作持久化流水、后台重试和跨组件事务。++## 11. 目录与实现拆分++```text+internal/plugins/+ manager.go # 期望配置应用、包和实例管理+ runtime.go # Node 进程与连接生命周期+ rpc.go # 通用双向 RPC+ bridge/ # 白名单 service handlers、owner/调用身份校验+ contributions/ # Go 工具、Skill、prompt 等注册适配++extensions/cordis/+ src/main.mjs # Cordis 进程入口+ src/rpc.mjs # 双向 Promise RPC+ src/host-plugin/ # 唯一 ctx.host 服务和本地 façade+ src/loader/ # 包加载、配置与实例生命周期++extensions/sdk/ # 自有 TS 类型、HostError、包开发帮助+examples/plugins/ # 邮件风格工具、Skill 目录、MCP、授权等最小示例+```++这是职责目标,不要求为了文件名完全一致创建大量空目录。Go credentials/authorization/MCP 继续留在已有模块;thirdparty 仍承载调用外部库的业务适配,不承载下载的 SDK 源码。++## 12. 旧代码的保留、改写与删除++实施前按引用关系处理,不能整目录回退与模型/SSE/前端功能交叉的改动。用户已明确允许清理不需要的旧实现,不做历史兼容层。++| 当前内容 | 决定 |+| --- | --- |+| `harness/agent`、`session`、`hostruntime` 等核心实现 | 保留;只拆除旧 Node 兼容调用,保留 Go 自身必要执行阶段 |+| `internal/credentials`、`internal/authorization`、`internal/mcpclient` | 保留唯一基础实现;按新 owner/调用契约做必要适配 |+| `internal/plugins/rpc.go`、`extensions/cordis/src/rpc.mjs` | 复用 framing/pending/双向分发基础;删除旧 next/probe 特判和上游错误身份处理,补 JSON-RPC 合法响应检查 |+| `internal/plugins/sync_rpc.go`、`sync-client.mjs`、`sync-worker.mjs` 与 sync fixtures | 删除,包括 socket、启动参数、SAB/Atomics 逻辑和专属测试 |+| `extensions/cordis/src/tools-service.mjs`、`tool-hooks.mjs` | 替换为 ctx.host façade 与 callback registry;删除上游 ToolsService 重复实现及工具阶段/continuation 适配 |+| `internal/plugins/tool_pipeline.go`、`tool_selection.go` | 保留可用的 Go 执行身份/取消基础,只保留实际需要的业务调用/取消适配;删除 Node pre/around/post/result 阶段接管与重复 Agent scope |+| 新增 `host-tool-events.mjs`、`host_tool_events.go` 及阶段专属测试 | 删除实验性 next/stage/continuation 桥接,不替换为新的一套阶段协议 |+| 已排除的 PreExecute guard 及插件 guard 接口 | 已删除 Go CheckGuards/ToolGuardDenial、旧 ctx.tools.guard 与新 registerGuard、对应 Node/RPC 适配和专属测试;保留执行前策略/审批/取消、工具自身权限和沙箱。Post 阶段 repeatGuard 是重复调用提醒,不属于本项删除范围 |+| 新增 `host_assets.go`、资产 spool 桥接、SDK Assets/图片/文件引用及专属测试 | 删除本轮扩张的插件资产接口;内置附件、read_image/生图、present、下载链路及它们实际需要的受控内部结构保留,按引用核对,不整段回退共享代码 |+| 方案自行新增的工具开始/完成插件通知及专属示例/测试 | 删除,不改名补回;保留 Go 内部 Result 和现有前端会话工具消息 |+| `harness/agent/tool_pipeline*.go` 等 | 保留 Go 必要管线;删除只为外部 middleware 存在的 continuation 分支。不能因去掉插件 post hook 而删原生结果校验和终结 |+| `runtime.mjs` 中 PromptService/ToolsService/SkillsService 核心继承和 scope 模拟 | 删除,替换 Host Bridge;Go 提供最终查询/组装 |+| `credentials-service.mjs`、`authorization-service.mjs`、`mcp-service.mjs` | 仅保留可用通信逻辑,重写为 ctx.host 子入口;删除上游服务类依赖和状态镜像 |+| `package-identities.mjs` 及上游 core 包身份固定 | 删除;新 SDK 自己定义类型,不为上游 plugin 身份做兼容 |+| `execution-context.mjs` 中完整上游 scope/policy 适配 | 删除不再需要部分;用简单只读 DTO 和 invocation 取代 |+| `internal/plugins/actions.go`、`storage.go`、`plugin/actions.go` 及对应 Node 服务/路由 | 删除,含 SDK、Controller/client 和前端入口引用;不改名恢复 |+| 旧 SDK `index.d.ts/index.mjs` 与上游类型依赖 | 重写为 ctx.host API,不保留 ctx.tools 等 alias、createScope overload 或旧模板 |+| `composition.mjs`、Bundle/Patch/Isolate/Intercept 配置桥 | 删除公开模型与旧兼容逻辑,使用自有 packages/instances 驱动真实 Cordis loader |+| 包来源解析与 pnpm 安装基础 | 有用部分保留;改自有 metadata 校验,不保留 dsh manifest/市场为必需项 |+| 旧市场/Bundle/Patch/Actions 等 Web/Mobile 页面 | 删除不再使用入口;插件列表、配置、状态和已有通用授权交互组件按新结构复用 |+| 旧同步/任意上游插件兼容测试、pipeline oracle | 删除相应内容,换成自有框架契约验收 |+| `tests/upstream-plugins/model-selection-oracle.mjs` 等非插件框架 oracle | 先查引用;属于模型等独立功能的保留,不能因目录名直接整目录删除 |+| 旧示例 catalog-app/cordis.patch 等 | 删除或重写;不留无法在新框架运行的示例 |+| Host 镜像复制、依赖锁、NOTICES 与 CI 命令 | 随最终依赖更新;保留 Node/Python/Chromium/Office/浏览器基础环境,不新增无关 CI 测试 |+| 旧三份插件方案 | 新方案实施完成后删除,正式文档只保留当前架构和开发指南;不留互相矛盾的有效方案 |++## 13. 实施顺序与验证++### 13.1 实施顺序++1. 新建自有 SDK 类型和协议合同,确定 ctx.host/ToolResult/Registration/HostEvent;先不把旧 SDK 当新方案继续补丁。+2. 收敛通用双向 RPC,删除阻塞同步通道,建立 Host Bridge 插件和 async apply/卸载生命周期。+3. 按第 8.1 节建立统一 Go PreExecute/Execute/PostExecute/Result 四环节,将已采用的上游核心模块行为放入对应位置;接通工具注册、业务 execute 和 host/* 通知,删除远端阶段/next 链、PreExecute guard 及其插件接口。+4. 接通 credentials、authorization、MCP,清理 Node 中重复服务和旧错误类型依赖。+5. 接通 Go Skill 目录/Provider、附加 prompt;清理新增插件 Assets/spool,保留内置图片和 present 投影。+6. 替换 packages/instances 管理合同、Controller 与自有 UI 数据调用;沿用现有视觉风格,不在本任务重新设计前端。+7. 按第 12 节删除旧服务、兼容逻辑、依赖和示例;更新开发文档、构建和既有 CI 引用。+8. 本地完整重建验证;不将方案完成等同于代码已完成,不额外进行未授权的生产部署。++### 13.2 验证清单++| 范围 | 必须证明的行为 |+| --- | --- |+| 通用通信 | 双向请求、乱序响应、反向嵌套请求、错误、void/null、断连和取消;读循环不被业务 await 堵住 |+| 生命周期 | register 确认后贡献可被后续快照使用;原生 apply 失败/途中卸载无贡献泄漏;不假设原子发布;dispose 幂等;无自建实例状态机、Worker/SAB/sync socket |+| 工具四环节 | Pre 调用准备/策略/审批/取消、Execute 持久边界/超时/真实业务、Post 输出治理/规范化、Result 最终核心确认/提交;无独立 guard 步骤,顺序与失败分支符合第 8.1 节,Result 不再修改最终结果 |+| 工具执行 | 注册函数由 Go 业务入口直接调用;无远端阶段/next;输入/内容校验、并发限制、取消收尾;checkpoint 失败不执行 |+| 核心阶段能力 | Job 输出上限捕获及终结、重复提醒、完整输出恢复、成功后交付/结构化确认/指令观察;不能仅以阶段函数存在作为还原证明 |+| 内置规则与审批 | Go 执行前策略的 allow/deny/ask 决定、审批结果处理及取消仍正常;工具业务内部审批发生在实际副作用之前;无 PreExecute guard、插件 guard 接口或跨进程 next;工具权限/沙箱和 Post 重复调用提醒保持原能力 |+| ctx.on | 同一 Host 的公开元数据通知及 instanceId 过滤、异常隔离、顺序起始、有限队列、无密钥/全部会话内容泄漏;不以通知承担可靠命令 |+| Skill/prompt | Go 最终合并、动态 Provider、目录失效、动态附加提示;没有 Node 第二个全局核心注册表 |+| 凭证/授权 | 真实 Go 存储、owner 地址、原子 update、run 中请求回 Go 不死锁、提交成功才 authorized |+| MCP | 注册声明和连接结果区分;Go 直接执行 MCP 工具;OAuth 复用基础模块;Node 无双重 Client |+| 结果与范围 | 插件仅接收/返回已定义 JSON 和 text/data,拒绝 image/file/任意交付 Meta 及超限帧;无 Assets/spool 公共入口;内置图片和 present/下载/投影仍正常 |+| 清理 | rg/依赖图确认旧重复服务/同步调用/SDK alias 不再被生产路径引用;没有未使用文件或废弃示例 |+| 核心回归 | 会话创建/恢复、模型调用、权限、Schedule、记忆、present、全 Host SSE 和自有前端保持原能力 |++以自有最小插件分别覆盖工具、Skill 目录、动态 Provider、MCP 和授权,不再以原样运行上游任意插件为验收标准。集成时使用受控服务/模型 mock 验证通信,真实模型验收沿用户另行指定的范围进行。++## 14. 实施与验收记录++核对日期:2026-11-20。下表对应本文的目标合同;日志与真实客户端截图保存在本地忽略目录 `.cache/bridge-validation/`,不作为开源运行依赖。++| 目标 | 当前实现及验收依据 |+| --- | --- |+| Go 核心职责与统一四环节 | `harness/agent/tool_pipeline.go`、`native_tool_pipeline.go`;管线、checkpoint、固定工具选择、取消/超时、长输出恢复、Job 输出和结构化结果测试通过。插件 body 仅在 Execute 通过 RPC 调用,不参与会话提交。 |+| 异步通信与 SDK | `internal/plugins/host_bridge.go`、`rpc.go` 与 `extensions/cordis/src/`;版本/能力/帧限制握手、反向请求、失联、取消、超限、JSON 无损校验及晚到注册撤销测试通过。普通调用均为 Promise,无阻塞同步通道。 |+| 工具、Skills 与附加提示 | 真实 Node/Go Bridge 测试覆盖工具登记与本体执行、动态 Provider、目录更新、用户覆盖、invalidate、动态模型上下文及稳定提示排序;原生 Cordis 卸载会撤销贡献。 |+| 凭证、授权与 MCP | `internal/credentials`、`internal/authorization`、`internal/mcpclient` 仍为唯一 Go 服务。测试覆盖实例凭证地址、查询/更新、嵌套 RPC、授权提交、回调 state/重放、取消和已准入写入;MCP 由 Go 连接并执行。 |+| 审批与问题 | Bridge 测试覆盖四种 Go 审批结果、普通审批不套短 RPC 超时、真实 Go turn 内提问及回答进入模型上下文。保留已有前端审批/问题机制。 |+| 生命周期与公开通知 | 原生 Loader/Fiber/effect 负责装配和撤销;真实 Cordis 测试覆盖依赖注入、加载失败及卸载。Host 通知有界、可合并、异常隔离,返回值不改变执行;无工具阶段通知或 next。 |+| 安装、分发与正式示例 | Host 随镜像提供本地 SDK,实际镜像验证带 SDK peer dependency 的包安装、运行时导入、工具调用和卸载;三个 JavaScript 示例及编译后的 TypeScript 示例通过真实 Cordis 测试。无需预先发布 npm SDK。 |+| 项目内置市场 | 正式 `extensions/catalog/plugins.json` 当前为 `[]`。公开安装/更新仅接受受审 pluginId,默认停用;Web/Mobile 覆盖安装、配置、启停、显式更新、卸载及空状态。测试目录源和条目只用于隔离验收。 |+| 认证交互 | 两端已覆盖无认证、API Key、并行 text/secret/select、普通业务 OAuth、标准 MCP OAuth、失败、取消、收起后继续和浏览器返回刷新。Android 使用真实 Chrome;仅测试本地受控供应商。 |+| 恢复与管理 | 最新 QA Host/Controller 镜像已实际运行,重建 Host 后会话和凭证保留、MCP 恢复连接。Web 操作插件重启后实例恢复就绪。重启直接携带 Redis 当前配置,不以失败实例再次 apply 成功为前置条件。 |+| 旧实现清理 | 第 12 节列出的旧同步通道、阶段/next、guard、Assets/spool、Agent/Session 代理、Actions/Storage、重复 Node 核心服务及上游 core 类型依赖已移除。三份旧插件方案已删除。清理扫描仅命中用于拒绝旧接口的负向测试。 |+| 文档与既有 CI | SDK、示例、市场维护说明、API、OpenAPI、架构及双语 README 已对应当前合同;已有 CI 改为安装和测试当前 Cordis/SDK,未为本任务增加额外 CI 作业。 |++最终验证:++- [x] `go test ./... -count=1`、`make vet check`、`make race`;授权模块另连续 30 轮 race 测试,覆盖取消传播前的提交拒绝与已准入提交继续完成。+- [x] Cordis 11 项测试、SDK 类型与真实编译示例、Web 20 项测试及生产构建、移动端类型检查。+- [x] Host 和 Controller Docker 镜像重建;镜像内 OfficeCLI/LibreOffice、Python、Chromium、agent-browser 冒烟及 SDK 包分发测试通过。+- [x] 最新 Host 镜像的全部 10 项 Docker 集成测试通过,覆盖会话恢复/文件、记忆/检索、模型切换、Schedule/附件恢复、全 Host SSE 审批重连、队列/问题、浏览器及内置工具。+- [x] `python3 scripts/smoke-cli.py`:真实 Compose Controller + Redis + 独立 Hosts,覆盖账号 Hash、隔离、Redis 重启、停止和释放。+- [x] 最新 Android arm64 QA APK 重建、安装,并连接隔离 Controller;真实 Web/Android 授权矩阵和截图已核验。QA APK 使用测试签名,不是公开 release。+- [x] `git diff --check`、所有 Go 源文件格式检查及依赖边界检查通过;测试插件、日志、截图均被忽略。++范围说明:ECI 按用户要求未验收;未验证任意第三方供应商或任意上游插件,也未发布正式业务插件。没有修改 LifeClaw、生产部署或远端 Git,没有提交和推送。本地受控 OAuth 成功仅证明本方案的协议与交互链路。++核心结论:**Go 管核心执行和状态,Cordis 管插件装配与生命周期,Host Bridge 提供自有异步能力接口;业务工具回调与状态观察分开。**++## 15. 工具阶段事件职责审计:先理解业务,再决定开放边界++日期:2026-11-19。此节记录用户暂停实施后要求的源码研究。正式四环节职责、返回类型和代码对应已收敛在第 8.1 节;这里的上游监听器仅作为调研证据,不作为 Cordis 阶段桥接实施指令。凡 experimental 及已明确排除的浏览器/CUA、Office 激活和上游 UI 内容均不迁入。实施已恢复,按本方案当前正文执行。++### 15.1 研究范围和证据++核对上游固定提交 `ca33fd6843b205e279c7ccb6cb73a472c78f5760`。下载该提交源码到仓库外的研究临时目录,扫描 `packages/**/src` 中实际监听注册,并排除测试和文档示例;对下表源文件校验 Git blob SHA 与该提交完整树一致。结果为 7 个源文件、8 处 `tools/execute` 监听注册。不是所有外部 npm 插件的生态普查,不能据此声称第三方不存在其他用途。++### 15.2 上游 tools/execute 监听器到底做什么++| 上游源文件 | 实际工作 | 工具过滤 | 我们应如何承载 |+| --- | --- | --- | --- |+| `guard/timeout-policy/src/index.ts` | 读取工具 timeoutMs,派生取消信号,等待真实操作收尾后将自身到期归类为 TOOL_TIMEOUT,恢复原始信号 | 按当前工具声明判断是否有超时预算 | Go 统一工具执行器内置;现有 native_loop 已有 context deadline/cause,不应再重复加载 Node 超时插件 |+| `session/session-checkpoint-policy/src/index.ts` | 顶层工具开始副作用前 flush 会话;flush 失败不执行;嵌套调用复用外层持久边界 | 有 Agent 且非嵌套调用 | Go 会话/工具提交边界内置;现有 appendNativeToolIntent 已在 dispatch 前 Flush |+| `experimental/browser-use-stagehand-native/src/index.ts` | 浏览器资源取得、参数预检、Agent 身份确认、资源互斥与取消绑定、调用结束清理 | 所注册工具名称的 Set | 若采用该业务能力,应由相应 Go 模块或该插件自身 execute 包装处理;当前 agent-browser 不是这个 Stagehand 模块,不因审计直接迁入 |+| `experimental/browser-use-runtime/src/mcp.ts`,两处 | 浏览器 MCP 与会话资源归属检查、可用性检查、独占操作和资源取消信号合并 | 工具前缀;资源工具还检查参数中的 server | MCP 连接/工具执行由 Go MCP 模块管理;特定浏览器资源策略留在对应模块,不自动引入上游 Agent scope |+| `experimental/computer-use-cua-driver-native/src/index.ts` | 将插件资源生命周期信号与工具信号合并,跟踪在途操作,结束时移除跟踪 | 所注册工具名称的 Set | 框架负责已有调用/插件生命周期取消;业务资源可在插件 execute 中 try/finally 处理,不需要为此开放全局 around |+| `experimental/cua-macos/src/held-keys.ts` | 保持程序执行期间的按键状态,在取消或结束时释放,避免按键残留 | run_code/cua_run_code | 特定电脑控制模块的业务资源逻辑;当前未提供相同模块,不扩充 Go 核心来模拟 |+| `experimental/claude-code-mods/src/index.ts` | 桥接另一套 mods 的 tool.call 拦截体系,可拒绝、委托或替代结果,并禁止重写已记录的工具名称/参数 | mods 注册表、调用来源和工具别名 | 兼容另一套 hook/mods 生态的可选能力,不属于我们的基础执行必需项;当前无需迁入 |++以上没有一个监听器承担“根据工具名称寻找某个插件登记的 execute 函数”的通用注册表职责。上游工具系统的 pipeline 仍提供末端 dispatchToolBody,并由该函数解析、校验和调用工具本体。事件监听器包裹这个函数。++### 15.3 通用事件如何判断关注哪些工具++上游事件给监听器传入 exec,其中有 name、arguments、调用标识、signal,以及上游自身的 Agent/嵌套调用信息。监听器自己判断名称、前缀、参数或状态;例如 Stagehand 用 names.has(exec.name),浏览器 MCP 用前缀及 arguments.server,按键清理只关注 run_code/cua_run_code。无匹配时调用 next 委托后续逻辑。++上游原生 scope 可以按 Agent 过滤,并不等于“一个插件只收到它自己登记的工具”。这是对上游监听器行为的解释;本方案不开放这些工具阶段事件,也不向插件广播全部工具参数,因此不需要为其新增工具选择规则或 Agent 作用域。第 7 节的状态通知仍按自己的公开 payload 派发。++### 15.4 pre/post 的现成逻辑也不都该成为外部插件++- pre:tool-jobs 捕获输出限制;workspace-changes 等待文件变更记录器稳定;experimental auto-review 做风险审查;hooks-codex/hooks-claude-code 接另一套外部 hooks。+- post:repeat-tool-reminder 注入重复调用提醒;grep/glob 控制搜索输出并保存完整结果;spill-policy 限制长工具结果;外部 hooks 对结果给出决定。+- result:present 提交交付事实;structured output 提交最终捕获结果;agent-instructions 更新触及路径;另有 UI/实验模块的观测处理。++其中会话持久化、交付事实、Agent 上下文、输出治理和工具资源管理应由我们的 Go 内置模块完成;不能因为上游用 ctx.on 做这些事情,就让 Node 参与我们的事实提交。其他可选生态兼容功能按需引入,不属于为了插件工具能运行必须开放的接口。++### 15.5 调研结论归入统一四环节++按第 8.1 节执行:Go 保留统一 PreExecute/Execute/PostExecute/Result,相关核心模块的行为在对应位置直接调用;不公开通用 Cordis 阶段事件或跨进程 next。执行前策略、审批、取消和结果处理保留明确的内部合同;PreExecute guard 不属于本轮采用的行为,其现有 Go/Node 实现与插件接口按第 12 节删除。插件只实现业务回调及基础能力调用。恢复实施时按模块与行为逐项核对缺口,不能用删除 Node 钩子代替完成 Go 内置逻辑。实施已恢复,按本方案当前正文执行。++主要依据:[timeout](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/guard/timeout-policy/src/index.ts)、[checkpoint](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/session/session-checkpoint-policy/src/index.ts)、[Stagehand](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/experimental/browser-use-stagehand-native/src/index.ts)、[浏览器 MCP](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/experimental/browser-use-runtime/src/mcp.ts)、[工具契约](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/core/tools/src/contracts.ts)。diff --git a/docs/host-event-stream-plan.zh-CN.md b/docs/host-event-stream-plan.zh-CN.mdnew file mode 100644index 0000000..15577c2--- /dev/null+++ b/docs/host-event-stream-plan.zh-CN.md@@ -0,0 +1,47 @@+# Host 统一事件流与会话内人工交互++状态:已实施并完成本地验证。++每个已连接的 Web / Mobile 客户端与当前账号的 Host 维护一条 SSE,经 Controller 透明转发。切换会话、进入设置、任务或文件系统不切换连接。消息、工具、队列、问题、审批依旧属于各会话;不提供全局审批弹窗,不自动跳转会话。++## 协议与职责++- `GET /v1/host/stream` 统一发送 `host` 事件,数据为 `{sessionId?, type, data}`。+- 会话事件保留既有公开投影及脱敏规则;`sessionId` 标识归属。Host 级 `sessions.changed`、`schedule/changed` 没有 `sessionId`。+- Host 直接订阅本地运行时,不为各会话建立内部 HTTP SSE。新激活的会话(包含定时任务创建的会话)自动加入。+- 历史通过现有 HTTP 分页读取。连接使用 `cursors` 携带已缓存会话的各自游标,补齐断线期间的事实;不新增跨会话日志或 Redis 消息队列。+- 初次连接、重连同步队列、执行权限、待处理问题及当前生成快照。未提供游标的会话与最近 20 轮历史重叠发送,前端按序号去重,覆盖会话创建到订阅就绪之间产生的消息。历史读取期间缓冲该会话到达的增量,读取完成后合并,避免丢消息。+- 尚未加载的会话只在前端内存保存生成中、待审批、待回答等摘要,首次打开再读取历史。已加载会话继续更新原有最多 20 个会话的缓存。摘要不是本地持久化文件,也不写 Redis。+- 会话列表显示轻量待处理标记。审批、方案审阅、问答仅在对应会话内展示;多个客户端中一个完成后,其他客户端同步撤下已处理项。+- 任务列表使用同一连接的变更通知刷新,不另建任务 SSE。移动端在前台保持连接,后台断开,回到前台重连。++## 人工交互++普通执行权限审批依照上游:不设置固定超时,等待允许一次、拒绝或调用取消。发起时无任何 Host 客户端且无其他交互处理方,返回 `unavailable`,不执行。已发起后客户端断线不取消;重连同步仍待处理项。取消 turn、停止 Host 会结束等待。不得由普通问答的补答路径放行权限。++`exit_plan_mode` 是方案审阅:复用问答表现,展示完整方案,允许按方案执行或输入意见继续规划,无固定超时,不提高执行权限。++`ask_user_question` 保留现有默认 120 秒等待、`timeout: -1`、超时后继续及补答消息机制。无客户端也可以发起;连接不会重置计时。++## 验证++覆盖多会话事件隔离、新会话自动发现、多个客户端、只建立 Host 流时的权限审批、无客户端时不可用、连接断开后原审批保留、重连快照、取消清理、私有内容脱敏、历史与实时增量合并,以及任务列表不额外建立 SSE。++用真实 Web 操作验证:切换会话时连接不变;其他会话待审批只显示列表标记;进入后显示可读的操作详情并允许/拒绝;普通问答恢复;方案审阅;新会话投递。截图检查桌面和窄屏中的正文、操作选项、问题面板及侧栏标记。++上游参考:[执行权限审批](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/interaction/user-approval/src/index.ts)、[问答与方案审阅](https://github.com/deepseek-ai/deepseek-harness/blob/ca33fd6843b205e279c7ccb6cb73a472c78f5760/packages/interaction/user-questions/src/index.ts)。+++## 已完成的验证结果++- `make test vet check` 通过。+- `go test -race ./harness/assembly ./harness/interaction ./internal/hostruntime ./internal/httpapi ./internal/controller` 通过。+- Web 构建及 15 项测试通过;移动端 TypeScript 检查通过。+- 标准 Dockerfile 构建 Controller 与 Host 镜像成功;使用真实 Docker Host 验证统一事件流、新会话自动发现、仅 Host 连接下的审批、原审批断线重连、普通问答超时继续及无客户端时返回 unavailable。+- 现有 Docker 模型切换与 Web 聊天集成检查通过。+- 模拟时钟验证审批等待超过三分钟且客户端断开后仍保留,重连批准后才执行;真实 Web 再次等待约 158 秒,确认未自动结束,之后提交拒绝成功。+- 真实浏览器验证了两客户端处理结果同步、切换会话不出现全局审批、返回会话恢复面板、重新登录恢复原审批、普通问答补答、定时任务新会话的待回答标记,以及方案确认后 Plan 模式为 false。+- 从设置页直接登录也会启动/连接 Host 并维护统一流;设置页和聊天页共用同一连接。+- 视觉检查后将方案正文改为复用现有 Markdown 渲染,调整滚动区域,使选项及提交入口在桌面和 390px 窄屏均可见。截图保存在忽略目录 `.local/validation/host-stream/`。++测试使用本地可控的模拟模型端点,Controller、Redis、Host、Linux 工具执行及 Web 请求均真实运行;本次未额外调用收费模型。移动端已接入共享连接并通过类型检查,本次没有重新构建原生 App 或验证 ECI。会话日志格式和 Redis 数据结构不变。diff --git a/docs/model-settings-and-session-routing-plan.zh-CN.md b/docs/model-settings-and-session-routing-plan.zh-CN.mdindex 162eb5b..6233066 100644--- a/docs/model-settings-and-session-routing-plan.zh-CN.md+++ b/docs/model-settings-and-session-routing-plan.zh-CN.md@@ -13,7 +13,7 @@| 聊天输入框左下角 | 显示「端点名称 / 模型 ID」。打开后先选端点,再选该端点内的模型。同名模型按端点区分。保存后只更新当前会话,并显示从下一轮生效。 || 新会话 | 点击 **New chat** 或从欢迎页直接发送时,由 Controller 读取账号默认模型。缺少可用默认模型时,页面显示「请先在模型设置中配置端点并选择默认模型」,提供 **打开模型设置** 入口,并保留已输入的内容。创建成功后,可通过输入框左下角的选择器切换当前会话。 |-设置页标注 **仅支持 OpenAI 兼容的 Responses API**。Base URL 示例为 `https://api.example.com/v1`,Host 调用该地址下的 `POST /responses`。首版手填模型清单,保存时校验字段格式和引用,实际请求失败时在聊天中显示相应错误。OpenAI 兼容服务需要支持 Responses 接口及所用模型对应的工具调用能力。+设置页支持通过下拉表单选择 **OpenAI Responses / Anthropic Messages**;协议属于端点。Base URL 示例为 `https://api.example.com/v1`,Host 根据协议调用 `POST /responses` 或 `POST /messages`。具体适配见 [Anthropic 协议方案](anthropic-model-protocol-plan.zh-CN.md)。首版手填模型清单,保存时校验字段格式和引用,实际请求失败时在聊天中显示相应错误。OpenAI 兼容服务需要支持 Responses 接口及所用模型对应的工具调用能力。## Redis 数据diff --git a/docs/permission-parity-plan.zh-CN.md b/docs/permission-parity-plan.zh-CN.mdindex 1f9f28c..7218a6a 100644--- a/docs/permission-parity-plan.zh-CN.md+++ b/docs/permission-parity-plan.zh-CN.md@@ -10,7 +10,7 @@Host 执行限制。Shell、后台 Job 和写入/编辑工具使用 Linux 内核沙箱,复用上游也支持的 Landlock 后端语义。部署时验证内核和容器策略是否支持;不可用时明确失败。Host 自己仍负责日志、附件等运行状态。不把文件沙箱当成网络策略或租户身份认证。-工具定义和沙箱拒绝结果指导模型在必要时发起提权,Host 在运行该调用前等待决策。审批卡复用现有 SSE 和问题交互的交付机制,显示请求权限、具体命令或路径和理由,提供「拒绝」与「仅允许一次」。关闭、超时、没有前端或取消 turn 均不能放行。批准不切换会话权限,也不授权子 Agent 或后续调用。会话忙时前端暂时关闭权限切换,避免正在运行的操作与选择含义冲突。+工具定义和沙箱拒绝结果指导模型在必要时发起提权,Host 在运行该调用前等待决策。审批卡复用现有 SSE 和问题交互的交付机制,显示请求权限、具体命令或路径和理由,提供「拒绝」与「仅允许一次」。拒绝、没有审批渠道或取消 turn 均不能放行。普通权限审批不设置固定超时。批准不切换会话权限,也不授权子 Agent 或后续调用。会话忙时前端暂时关闭权限切换,避免正在运行的操作与选择含义冲突。验收覆盖新会话默认值、会话隔离与重启恢复,真实 Linux 下的写入、重命名、链接与后台执行,真实 Controller 请求的拒绝和单次放行,以及浏览器和 iOS 模拟器中的选择器、审批卡和结果截图。@@ -25,7 +25,7 @@ Host 执行限制。Shell、后台 Job 和写入/编辑工具使用 Linux 内`NativeFactory.ToolApproval` 是已注册工具执行前的审批策略入口。它接收已经验证的工具名与参数,可返回一个带理由和操作详情的审批请求,也可返回空请求让调用继续。Host 复用同一个单次审批服务。现有工具没有配置主动审批策略。-客户端登录账号,聊天页只订阅当前会话的 SSE。定时任务也走同一套工具权限。目标会话有交互订阅时可提交审批,尚未打开时返回审批渠道不可用。客户端切回时可重新查看仍待决策的审批;未处理的审批将在两分钟后取消。+客户端登录账号后维护一条 Host SSE,按 sessionId 接收所有会话的公开事件。定时任务也走同一套工具权限;只要有 Host 交互连接,尚未打开的会话也可以发起审批。审批仅在对应会话展示,其他会话只在列表显示待处理标记。已发起后断线不取消,重连同步仍待决策项。普通权限审批不设置固定超时,允许一次、拒绝或调用取消才结束等待。没有任何交互处理方时返回 unavailable,不执行。详见 [统一事件流方案](host-event-stream-plan.zh-CN.md)。子 Agent 默认沿用委派时的上限,禁用交互提权,并继续受主会话权限上限约束。Shell Job 继承启动调用的沙箱。会话运行期间及仍有子 Agent 或 Job 在工作时,禁止切换档位。diff --git a/docs/plugin-account-setup.md b/docs/plugin-account-setup.mdnew file mode 100644index 0000000..ba21277--- /dev/null+++ b/docs/plugin-account-setup.md@@ -0,0 +1,99 @@+# Connect X and Google Workspace++X uses each user's own developer application, entered inside the plugin's+Accounts and authorization panel. Google Workspace also uses each user's own+application: create a Desktop OAuth client and provide its downloaded JSON on+first connection. Account+tokens for both services stay in each user's native CLI store, never in Redis or+Go credentials. Do not put user credentials in chat, deployment `.env` or Git.++## X++1. Open the [X Developer Console](https://developer.x.com/), create an app and+ enable OAuth 2.0 user authentication. Select the app permissions you need.+2. Register `http://localhost:8080/callback` exactly as a callback URL. Obtain your+ **Client ID** and, for a confidential client, **Client Secret**. A Native App+ is a public client: leave the Secret empty, even if the console still shows a+ secret value. Supplying one makes xurl use confidential-client authentication.+ **Website URL** is the application's homepage, for example+ `https://github.com/xyc999-ai/go-bot`. It introduces the app; it is not the+ Controller address or OAuth callback and does not need another deployed server.+3. Install and enable X in the plugin market. Open **Accounts and authorization →+ Connect X account**. On first connection, enter the Client ID and Secret (leave+ the latter empty only if you chose a public Native App).+4. Open the authorization link in your own browser, sign in to X and approve+ access. Copy the **complete redirect URL** from the address bar into the panel,+ even if its localhost page cannot open. Submit it immediately: X documents a+ **30-second authorization-code lifetime**. An expired/used code requires a new+ authorization attempt.+5. Wait for the native authorization result. Subsequent connections reuse the+ native application configuration, and xurl refreshes account tokens.++If an attempt fails or is cancelled, select **Connect X account** again. No Host+restart is needed. Open the new authorization link and submit that attempt's new+redirect URL; do not reuse an earlier URL or authorization code.++X API usage is billed to the developer application/account. Connecting your own+X account does not make API calls free. Review your developer account's credits,+API access and spending limit. The MCP bridge only exposes the tools supported+by the current X API and your app's scopes; it does not promise every xurl action.++[X OAuth client types](https://docs.x.com/fundamentals/authentication/oauth-2-0/authorization-code)+· [xurl authentication](https://github.com/xdevplatform/xurl#authentication)+· [X MCP](https://docs.x.com/tools/mcp)+· [X API pricing](https://docs.x.com/x-api/getting-started/pricing)++## Google Workspace++Personal Google accounts can connect Gmail, Drive, Calendar, Docs, Sheets and+Slides; a paid Workspace enterprise subscription is not required for these+features. Enterprise directory and administrator features are outside the+plugin's default permission request.++1. Follow [Google application setup](google-workspace-app-setup.md) to create your+ Cloud project, enable the APIs you need, configure the audience and download+ a **Desktop app** OAuth client JSON. While testing, add your Google email as+ a test user. This is not the Go Bot account name.+2. Install and enable Google Workspace. Open **Accounts and authorization → Connect+ Google account**. On Web, select the downloaded JSON file; it is parsed and submitted automatically.+ On mobile, paste the JSON in the protected input. It is saved+ only in your native Host directory; later connections reuse it.+3. Choose read-only or read-and-write permissions. Open the link in your own+ browser, sign in to Google and approve access.+4. Copy the complete localhost redirect URL from your browser address bar into+ the panel, even if that local page cannot open.++There is no shared project OAuth application. The plugin runs native+`gws auth login --scopes ...` and relays the redirect only to that command's+current local listener. gws exchanges the code, saves the account tokens and+refreshes them. This is not an upstream `--headless` flag and does not use Google's+deprecated OOB redirect URI. Enable APIs as needed; authorization does not enable+APIs or bypass app audience restrictions.++Standard API usage is generally available at no additional charge within the+published quotas. Google controls app verification, organization access, quotas+and billing changes for high usage. The CLI is not an officially supported Google+product. See [Google application setup](google-workspace-app-setup.md).++[gws authentication](https://github.com/googleworkspace/cli#authentication)+· [Drive quotas/pricing](https://developers.google.com/workspace/drive/api/guides/limits)++## Account data and disconnect++```text+/root/harness/.dsh/credentials/x/ # ~/.xurl -> this directory+/root/harness/.dsh/credentials/google-workspace/ # ~/.config/gws -> this directory+```++These complete native directories, including the gws encryption key and cache+where used, live with the user's existing Host data. Go credentials and Redis do+not receive another token copy, account flag or file-reference grant.++Disable/uninstall retains account data. **Disconnect account** invokes native+logout/clear and checks that the active account is no longer configured. It is+different from cancelling an unfinished authorization. This is local disconnect;+users may also revoke provider access from their X/Google account settings.++Retrieved service content enters the Agent context and may be processed by the+model provider selected by the user. Application credentials, callback answers and+tokens collected in the authorization panel are not added to chat/model context.diff --git a/docs/proactive-service-research-and-plan.zh-CN.md b/docs/proactive-service-research-and-plan.zh-CN.mdnew file mode 100644index 0000000..c1ac6a3--- /dev/null+++ b/docs/proactive-service-research-and-plan.zh-CN.md@@ -0,0 +1,208 @@+# 主动服务:现有产品机制调研与 Go Bot 方案++调研日期:2026-11-21。状态:**调研及提案,尚未实现主动服务功能**。++本文先记录别家的实际做法,再给出 Go Bot 的设计建议。闭源产品依据官方披露,不将产品表现推断成未公开的调度实现;开源项目同时核对源代码。++## 1. 主动服务实际上包含哪些环节++不能只增加一个“定时向模型发送消息”的循环。需要分别回答:++1. **为什么再次工作**:用户交办了持续职责、时间到了、外部数据变化、之前的工作结束了,还是系统发现了新的关联?+2. **如何继续工作**:找到原职责、会话、工作目录和最新信息,进入正常 Agent 执行流程。+3. **是否告诉用户**:没有变化可以静默;有重要进展、风险或需要决策时才形成可见消息。+4. **如何到达用户**:会话内消息、在线客户端实时更新、手机系统通知是不同能力。++其中,长期记忆解决“记得什么”,调度解决“什么时候运行”,它们本身都不等于主动服务。++## 2. Muse:围绕目标持续工作,完成后再决定是否通知++官方设计文章明确披露:设定目标或任务之后,Muse 会根据计划及相关事件继续推进;后台工作完成后,再评估结果是否值得展示。只有出现有意义的新信息或需要用户输入,才通知用户。用户也可以要求减少、增加或关闭主动联系。[来源:How We Designed Muse](https://muse.ai/blog/how-we-designed-muse)++官方技术文章进一步说明:Harness、浏览器、命令和文件在用户专属 VM 的运行环境中;该环境支持并发子 Agent 和 cron,客户端连接 VM。连接器提供外部服务能力,动作权限由独立的 Sentinel 判断,而不是因为任务在后台运行就自动获得更高权限。[来源:How We Built Safety Into Muse](https://muse.ai/blog/security-and-safety-for-ai-agents-our-approach-with-muse)++可确认的流程是:++```text+用户目标 / 相关事件 / 到期计划+ → 在持续存在的运行环境内推进工作+ → 评估结果的新意和重要性+ → 必要时主动联系;后续动作仍受权限约束+```++**未披露**:通用检查周期、事件订阅内部实现、任务队列及通知评分算法。不能宣称 Muse 使用某个固定间隔的 heartbeat,也不能将 Sentinel 的实现直接当成我们现有权限模块的能力。++对 Go Bot 的启示:围绕用户目标安排后续工作;把“后台做完”与“需要发消息”分开。无需复制其专属 VM 内全部安全基础设施。++## 3. Grok Bot:主动跟进与明确的 routine 分开++### 3.1 主动跟进++官方说明主动联系通常由 primary Bot 发起,包括提出可以接手的工作、发现应用掉线、跟进对话。它会先提出建议,用户接受后再执行;敏感动作仍需审批。关闭通知只影响提醒,并不等于关闭后台 check-in。[来源:When Your Bot Takes Initiative](https://docs.x.ai/grok-bot/initiative)++这揭示了两个独立开关:**是否执行主动检查**、**是否提醒用户**。它们不能混成一个“通知”开关。++### 3.2 Routine 的具体触发机制++Routine 保存工作指令及运行条件,在云端执行;条件可以是时间,也可以是 Slack、邮件、GitHub 等事件或 webhook。官方特别区分“连接应用以便调用它”和“配置触发器以启动工作”。Webhook 被接受代表开始一次运行,不代表任务已经成功完成。用户可以查看、暂停、测试或删除 routine。[来源:Skills and routines](https://docs.x.ai/grok-bot/skills-routines-and-automations)++```text+保存指令 + 触发条件+ → 云端接收匹配的新事件 / 到达计划时间+ → 创建运行+ → 正常调用工具及审批+ → 结果进入聊天;运行结果与触发成功分别记录+```++**未披露**:自主 check-in 的确切唤醒算法,以及内部队列、存储结构。Routine 的公开触发规则不能证明 check-in 采用相同调度方式。++对 Go Bot 的启示:安装 Google Workspace 或 X 插件只代表可以调用服务,不应自动监听全部账号活动。监听何种事件、满足什么条件才工作,需要单独建立明确职责。++## 4. OpenAI dots:持续职责、自主再次唤醒与后台研究++官方说明 dots 可以在对话之间继续职责,自行决定暂停及再次唤醒;也支持指定时间或支持的事件。它能将工作交给后台 Agent,并由主 dot 协调结果。定期工作需要保存计划;仅连接应用不会自动创建事件监控任务。[来源:Tasks and memory](https://learn.chatgpt.com/docs/dots/tasks-and-memory)++后台研究有单独边界:读取允许访问的信息、保存私有笔记、关联先前工作;研究本身不发送消息、不修改外部应用,也不控制浏览器或电脑。研究结果汇报给主 dot,由它提出建议或问题。后续行动再适用相应权限和审批。[来源:Proactive research](https://learn.chatgpt.com/docs/dots/tasks-and-memory#proactive-research)++```text+持续职责 / 时间 / 支持的事件+ → dot 安排推进或后台研究+ → 后台结果回到主 dot+ → 主 dot 决定如何告知、询问或继续+```++**未披露**:决定再次唤醒的模型输出契约、底层计时器、队列及私有笔记数据库。上图是官方描述的行为关系,不是其服务端源码架构。++对 Go Bot 的启示:固定周期不是唯一选择,可以在完成一次检查后安排一个具体的下次检查时间。研究阶段与对外行动应有明确边界;不能靠提示词声称已经强制实现这个边界。++## 5. 开源代码如何完成唤醒++### 5.1 Hermes Agent:空闲时进入原会话++核对版本:`f6c3eb1a79ed769d1d4a978ec454dd690166e82d`。++`HeartbeatManager` 保存每个会话的检查指令、间隔和上次触发信息。驱动在会话空闲时检查 `due_prompt()`,有到期请求才注入普通 user-role 消息。它先保存领取信息,避免重复领取;错过多个周期合并为一次,不补发积压。状态在会话存储中,重启可恢复。[源码:heartbeat.py](https://github.com/NousResearch/hermes-agent/blob/f6c3eb1a79ed769d1d4a978ec454dd690166e82d/hermes_cli/heartbeat.py)++驱动还要求用户输入队列先清空。Gateway 对无变化的 heartbeat 可以不发送聊天输出,普通用户消息不套用这种静默规则。其 heartbeat 使用原会话;cron 则适合独立工作。[官方说明](https://github.com/NousResearch/hermes-agent/blob/f6c3eb1a79ed769d1d4a978ec454dd690166e82d/website/docs/user-guide/features/heartbeat.md)++另一个有用的具体机制是 cron 的脚本前置检查:`_parse_wake_gate()` 接受脚本末行的 `{"wakeAgent": false}`,跳过本次模型运行。即“先用确定性代码判断是否变化,必要时再叫模型”。[源码:scheduler_prompt.py](https://github.com/NousResearch/hermes-agent/blob/f6c3eb1a79ed769d1d4a978ec454dd690166e82d/cron/scheduler_prompt.py)++### 5.2 OpenClaw:当前版本已将主动检查纳入普通自动化++核对版本:`2aca1a1c1595e25d3cdb0bc7ce098bdcc92efb87`。++`createDefaultProactiveJob()` 创建普通 `agentTurn` 自动化任务,默认每 30 分钟、目标为主会话、`idleOnly: true`,检查提示允许无消息结束。它由显式 setup 创建一次,启动及重载不会重新生成用户删除的任务。[源码:default-proactive-job.ts](https://github.com/openclaw/openclaw/blob/2aca1a1c1595e25d3cdb0bc7ce098bdcc92efb87/src/cron/default-proactive-job.ts)++当前官方文档已将 heartbeat 迁移为可编辑的 automation;`HEARTBEAT.md` 不再作为运行时调度输入。任务支持静默结果、活跃时间及空闲运行。不能套用早期教程,声称当前实现仍是独立 heartbeat 循环加 `HEARTBEAT.md`。[官方说明:Heartbeat migration](https://docs.openclaw.ai/gateway/heartbeat)++这些实现证明:唤醒由模型外的常驻运行服务完成;模型不需要一直生成,客户端也不需要一直打开。周期检查可以复用已有调度设施。++## 6. 几种做法的对应关系++| 问题 | 已确认的外部做法 | Go Bot 建议 |+| --- | --- | --- |+| 为什么再次运行 | Muse 的计划/相关事件;Grok routine;dots 的时间/事件/自行跟进 | 明确职责对应时间或事件;不默认扫描全部用户数据 |+| 如何持续理解目标 | 产品使用持续上下文和记忆;Hermes 可进入原会话 | 复用保存的会话、实际工作目录及现有记忆/历史检索 |+| 如何避免忙时打断 | Hermes 空闲且用户输入优先;OpenClaw `idleOnly` | 主动检查只在会话空闲时启动,不使用 steer 抢占 |+| 如何避免每次都叫模型 | Hermes 脚本 wake gate | 能确定性检查变化的插件先比较事件或游标 |+| 如何避免每次都发消息 | Muse 判断是否值得展示;Hermes/OpenClaw 支持静默 | 执行结果与用户可见消息分开决定 |+| 谁决定对外行动 | 各产品另有授权和审批 | 继续由 Go 工具系统、权限及审批模块负责 |++表中 Go Bot 一列是本项目提案,不是外部产品已公开的内部实现。++## 7. 我们当前已具备什么++以下依据当前 Go Bot 源码,不是待实现能力:++- `harness/schedule` 已保存时间规则并向目标会话投递;`internal/hostruntime/native_schedule_delivery.go` 处理会话恢复及投递执行观察。+- `NativeRuntime.DeliverSchedule()` 将到期工作持久化进入会话 inbox,再由现有 Agent Loop 领取;并非由前端发起模型调用。+- 会话保存实际工作目录,定时任务可使用已有会话或其目标创建规则,不需要重新将会话与工作目录强绑定。+- Host 已有长期记忆及会话历史 FTS 检索;记忆更新本身不会唤醒 Agent。+- Web/Mobile 已通过账号级 SSE 接收各会话消息;客户端断开不等于 Host 停止运行。+- 插件目前可提供工具、Skill、MCP、授权等能力;SDK 尚无外部事件订阅和主动唤醒契约。++仍缺少:持续职责的明确管理、服务事件到 Agent 的入口、无变化静默展示规则,以及手机在后台/被关闭时的系统推送。SSE 不能代替 APNs/FCM 等手机推送。++现有 `goal` 用来推进当前执行目标,不应直接当作无限期监控职责。现有 schedule 负责用户保存的定时工作,也不应被偷偷改成全用户的周期扫描。++## 8. Go Bot 建议架构++### 8.1 保持当前职责边界++```text+已有时间任务 ───────────┐+插件提供的已订阅事件 ──┼→ Go 主动服务入口 → 会话 inbox → Go Agent Loop+明确保存的后续检查 ────┘ │+ ├→ 工具 / Skill / MCP+ ├→ 原有权限及审批+ └→ 结果判断 → 可见消息 / 静默+ │+ Controller → 客户端+```++Go 管调度接入、会话、执行及结果提交。Cordis 继续管理业务插件生命周期;插件决定如何连接第三方服务和解释服务事件,不接管核心 Agent Loop。不新增 Controller 五分钟轮询,不恢复之前删除的闲置回收机制,也不另建 Redis 定时任务系统。++### 8.2 从明确委托的持续职责开始++例如:“未来一周关注这个项目的 CI,失败时说明原因,成功且没有变化就不要打扰。”++保存时明确工作范围、通知条件、目标会话及何时停止。能够用现有 schedule 表达的时间检查,直接复用原任务;不要另写一套 cron 引擎。检查完成后需要晚些时候继续的,可保存下一次一次性检查,到期仍经相同入口执行。模型建议时间,Go 验证并保存。++先支持这种明确职责,再考虑没有具体委托的自主研究。后者需要额外的数据访问及行动边界,不能因默认 `danger-full-access` 就自动扫描邮件并对外行动。++### 8.3 事件由插件采集,Host 接受后进入普通执行++以 Google Workspace 为例:Google 插件负责选择 Gmail 的事件/增量接口、刷新原生凭证、读取游标和整理必要输入;Host 负责把已订阅职责的事件送进目标会话。X 插件同理,但必须按官方实际支持的能力实现,不能假定 MCP 自动提供订阅。++建议增加一个窄的异步 SDK 入口,例如 `ctx.host.wake.enqueue({ responsibilityId, eventKey, summary })`,供插件报告已匹配事件。**这只是待设计接口,当前不存在。** Host 从保存的职责解析会话及工作目录,不允许事件随意指定别人的会话、覆盖权限或注入 system prompt。++仅当服务需要时才提供 webhook;本地私网部署可由插件主动拉取。无需为了主动服务要求所有部署者先开公网回调。++### 8.4 公共准入与运行规则++1. 检查职责仍启用、目标会话有效、必要模型及插件已配置。+2. 根据服务事件 ID/游标排除已接受的重复事件;一个检查尚未开始时,可合并同一职责的多次变化。+3. 会话有 turn 或用户输入时等待,不抢占,不产生多个积压的周期检查。+4. 到执行时读取最新的职责、会话事实、记忆及工具结果,避免保存一套长期不变的上下文快照。+5. 使用正常 Go 工具执行流程,插件工具只在其业务入口经 RPC 调用。+6. 结果是“无变化”“有进展”“需要输入”还是失败,分别处理;失败不能记为无变化。++这些是主动工作的准入规则,不是给业务插件重新开放通用 guard 或 pre/execute/post 中间件。++### 8.5 静默结果与通知++“无变化”属于一次合法的检查结果,可以保留执行事实,但不追加助手气泡、不展示短暂的“生成中”,也不发送系统通知。普通用户发出的消息不适用静默规则。++实现时要由 Go 接受明确的后台结果声明,例如内部结果 `no_change`,而不是前端在任意文本中搜索 `NO_REPLY` 并删除内容。需要可见输出时,继续使用现有 assistant 内容块与 SSE 投影,不另造一套聊天消息协议。后台检查详细过程可在任务详情查看。++同一事项没有新的进展,不重复提醒。用户应能暂停职责,并分别控制主动检查及通知。检查频率、每日模型调用额度和静默时间需要有限默认值;具体默认数值在实施前确定,不从闭源产品猜测。++在线客户端继续走现有账号级 SSE。App 后台或关闭后的提醒需要单独接入系统推送;点击通知再进入对应会话。尚未实现推送前,只能承诺会话中保存结果、重新打开可见,不能承诺手机锁屏时会收到通知。++### 8.6 权限、审批与 Host 生命周期++显式交办任务沿用现有执行权限。主动研究如果要承诺只读,必须在 Go 执行器限制可用操作;仅写“不要修改”不构成限制。无法可靠分类的 shell/MCP 操作不能直接宣称只读。++普通权限审批继续走原有机制:没有交互渠道时不执行需审批的操作;已发起后断线的等待与恢复规则保持现状。不把普通审批改成 120 秒超时,也不借主动任务绕过审批。具体授权及问题仍在所属会话回答。++Host 运行时,客户端关闭不影响其本地计划。**用户主动 Stop Host 后,Host 内计划及插件监听都停止。** Controller 不偷偷重启它。若未来要支持停止 Host 仍接收外部事件并唤醒,需要另行设计 Controller 事件入口及明确的自动启动授权,不能算当前已有能力。++### 8.7 数据保持最少++复用现有位置:++- 时间规则:`/root/harness/.dsh/storages/schedule.json`。+- 工作过程与可见回复:原会话日志及实际工作目录。+- 长期偏好与事实:现有 `.dsh/memories`;不把定时状态塞进记忆文本。+- 第三方账号令牌:插件对应的现有凭证/原生 CLI 存储;不复制进 Redis 或职责记录。++只有事件订阅、持续职责或通知去重无法由现有事实表达时,才增加一份 Host 内职责状态。其最少字段是职责 ID、指令、目标会话、启停状态、关联 schedule ID/事件来源、事件游标及上次提醒标识;时间使用 Unix 毫秒。确切存储文件与 SDK 契约留到实施设计收口,不先增加快照文件、第二份会话历史或复杂的运行状态机。++## 9. 建议实施顺序与验收++1. **明确职责 + 时间检查 + 静默结果**:复用现有 schedule/会话,验证忙时等待、无变化无气泡、有结果正常交付、暂停后不再触发。+2. **一个真实外部事件来源**:由 Google Workspace 插件实现一个范围明确的监听;验证重复事件不重复工作、未订阅不会运行、凭证过期能说明原因。+3. **Web/Mobile 提醒**:在线 SSE、未读入口、跳转原会话;再完成真实设备的系统推送及权限流程。+4. **有限的自主跟进**:在已有职责内让 Agent 选择下一次检查时间;验证完成/取消后不再安排,Host 重启后按保存事实恢复,不补发大量旧检查。++先完成一条真实的“事件变化 → Agent 判断 → 必要时提醒 → 用户继续处理”闭环,再扩展服务种类。整个过程中保持现有 schedule 上游语义,不将研究提案当作已经实现的功能。diff --git a/docs/providers.md b/docs/providers.mdindex ec51af3..1238415 100644--- a/docs/providers.md+++ b/docs/providers.md@@ -33,6 +33,37 @@ For providers with a separate image preparation step, add a command under`cmd/build<provider>`. It can reuse `internal/imagebuild` for image publication.The runtime driver consumes the prepared artifact through its own configuration.+## Language models++Model settings supports **OpenAI Responses** (`responses`) and **Anthropic+Messages** (`anthropic_messages`). Choose the API protocol in the endpoint form's+dropdown, then enter its base URL, API key and ordered model IDs. The first model+is the endpoint default. The account default endpoint applies to new chats;+existing chats keep their selection and can switch endpoints/models independently.+A switch during generation applies to the next turn.++For Anthropic, use `https://api.anthropic.com/v1` or your provider's compatible+base URL; do not append `/messages`. The Host appends `/messages`, sends+`x-api-key` and `anthropic-version: 2023-06-01`, and normalizes text, tool use,+images and SSE into the existing Harness contracts. Model IDs are entered as+provided by the service; a Claude model name alone does not determine its API+format. The adapter targets API-key-based Messages endpoints, not Bedrock,+Vertex or Claude subscription login.++Keys stay in the account's Redis `llm` field and are synchronized to the Host.+Public settings return `hasApiKey`, not the key. Saving validates configuration+and applies it to the Host without issuing a billable model request. Missing+protocol on existing endpoints defaults to Responses. Chat Completions remains+an internal adapter and is not offered by this settings form.++Extend `thirdparty/llm` for wire encoding, decoding and streaming, and+`providers/model/mainmodel` for model routing. Keep credentials out of Session+logs. Signed native Anthropic blocks are stored as replay metadata on assistant+messages, separate from visible content, and only replayed to the same endpoint+address and model. Cross-protocol history uses portable content; compaction stays+in the Harness. General model context defaults do not guarantee that a custom+model accepts that context length. [Anthropic Messages reference](https://platform.claude.com/docs/en/api/messages/create?version=2023-06-01)+## SearchAdd `providers/web/<engine>` implementing web.SearchProvider and use thirdparty@@ -44,6 +75,31 @@ Host uses that registry to resolve the provider.| `deepseek` (default) | DeepSeek Search | DeepSeek search key || `zhipu` | BigModel Web Search API, using `search_std` | BigModel platform key authorized for Web Search. [Official docs](https://docs.bigmodel.cn/cn/guide/tools/web-search) || `doubao` | Doubao Search Custom, text-to-web | Dedicated Doubao Search Custom key. [Official docs](https://docs.volcengine.com/docs/networked-search/networked-search?lang=zh) |+| `tavily` | Tavily Search, Basic depth | Tavily API key from [Tavily dashboard](https://app.tavily.com/). [Official API](https://docs.tavily.com/documentation/api-reference/endpoint/search) |+| `brave` | Brave Search, LLM Context endpoint | Search API key with LLM Context access from [Brave dashboard](https://api-dashboard.search.brave.com/). [Official API](https://api-dashboard.search.brave.com/documentation/services/llm-context) |++In **Settings → Web search**, set up a service, save its API key, then choose+**Use provider**. Mobile uses **Me → Web search**, with **Save settings** and+**Save and use**. Saving does not make a search request. The same account catalog+supplies both clients; no extra environment variables or model names are needed.+The default provider remains DeepSeek until another saved provider is selected.++Tavily calls `POST https://api.tavily.com/search` with Bearer authentication,+`search_depth: basic`, `topic: general`, publication dates enabled and at most+20 results. Automatic parameter selection, generated answers and raw page content+are disabled. Relevant `content` passages become source summaries. Publication+dates are provider estimates and may be absent. HTTP 432/433 map to quota errors;+434 maps to temporary rate/capacity limiting.++Brave calls `POST https://api.search.brave.com/res/v1/llm/context` with+`X-Subscription-Token`. It returns source-linked excerpts rather than a generated+answer. The adapter defaults to an 8,192-token context budget and a 1,024-token+per-URL budget, with URL/result counts capped at 50. These are internal defaults,+not extra user settings. Queries must fit 600 characters and 75 words. Source+metadata supplies optional titles, descriptions and absolute dates; relative+ages and content-fetch timestamps are not used as publication dates. The API's+default country/language preferences apply; the adapter does not infer a locale+from UI language or rewrite the Agent's query.Search and extraction remain distinct:search-only providers are not forced to fetch pages. Results use URL/title,diff --git a/docs/x-google-workspace-plugin-plan.zh-CN.md b/docs/x-google-workspace-plugin-plan.zh-CN.mdnew file mode 100644index 0000000..25c426e--- /dev/null+++ b/docs/x-google-workspace-plugin-plan.zh-CN.md@@ -0,0 +1,327 @@+# X 与 Google Workspace 插件接入方案++日期:2026-11-21。状态:两个插件已实现;X 已完成真实账号授权、官方 MCP 发现及一次只读请求。Google Workspace 已完成真实浏览器授权与一次 Drive 账号信息只读请求。按最新决定,两者都使用用户自己的应用配置,不再分发 Google 公共应用;首次配置(Web 选择 JSON 文件,移动端保留受保护输入)、原生配置复用与中英文前置视频已交付。++## 1. 结论++分别提供两个 Cordis 包,复用当前市场、pnpm 安装、Go 内置 MCP/授权交互和原生 Skills 发现机制。++| 项目 | X | Google Workspace |+| --- | --- | --- |+| pluginId | `x` | `google-workspace` |+| 包名 | `@go-bot/plugin-x` | `@go-bot/plugin-google-workspace` |+| 展示名 | X | Google Workspace |+| 上游 | `xdevplatform/xurl` | `googleworkspace/cli` |+| 官方安装命令 | `npm install -g @xdevplatform/xurl` | `npm install -g @googleworkspace/cli` |+| Agent 接入 | Go MCP Client → stdio `xurl mcp` → X 官方远端 MCP | 原生 `gws` CLI + 上游 Skills |+| 应用配置来源 | 用户首次授权填写自己的 X 应用 | 用户首次授权提交自己的 Desktop OAuth 客户端 JSON |+| 认证执行者 | xurl | gws |+| Token 保存与刷新 | xurl 原生存储 | gws 原生存储及 Token 缓存 |++不为这两个 CLI 的 Token 再写一份 Go credentials 记录,也不创建指向原生凭证文件的占位 grant。Go authorization 管交互和流程状态;原生 CLI 管自己的认证数据。++“安装了 CLI”与“Agent 通过 CLI 使用业务”是两件事。Google Workspace 的业务入口是 Shell/CLI + Skills;X 的业务入口是 MCP,xurl 是其本地认证及协议桥。X 插件只向 Go 注册 MCP 声明,不在 Node 里再实现 MCP Client 或逐次代理业务工具调用。现有 Go MCP Client 已通过官方 Go SDK CommandTransport 原生支持 stdio JSON-RPC,业务链路为 Go Agent → Go MCP Client → stdio xurl mcp → HTTPS X MCP。插件直接启动 xurl 子进程只用于安装检查、headless 授权和原生授权状态/退出操作。++Google Workspace 在此指 [googleworkspace/cli](https://github.com/googleworkspace/cli)。仓库明确声明它并非 Google 正式支持的产品。其 `gws mcp` 已在 0.8.0 移除,不能依赖旧版本教程中的这个入口。[当前说明](https://github.com/googleworkspace/cli/blob/main/README.md)、[变更记录](https://github.com/googleworkspace/cli/blob/main/CHANGELOG.md#080)++## 2. OAuth 在哪里打开浏览器++按用户最新确认,保留当前手动粘贴完整回跳 URL 的流程。Web 不要求安装浏览器扩展,移动端不新增本地回跳监听器;不实施之前讨论的自动回跳草案。校验与交接边界见第 15 节。++运行 CLI 的位置与用户打开授权网页的位置可以不同。++```text+Host 插件运行原生授权命令+ → 获得 OAuth URL+ → Go authorization / Controller 将 URL 提供给前端+ → 用户点击,在自己的电脑或手机浏览器打开+ → 用户在服务商网页登录、选择账号并授权+ → 用户把完整回跳地址粘贴回插件授权面板+ → Host 插件交给原生 CLI 完成认证+```++关键区别是:浏览器里的 `localhost` 指用户设备,不是远端 Host。单纯把授权链接复制到本机浏览器并不能让远端 CLI 的 localhost 回调自动收到请求。需要原生 headless 输入,或本项目明确实现的回调转投。++本方案不在 Host 启动可视浏览器替用户登录,不要求用户安装 SSH 隧道,也不发布 CLI 的随机回调端口。HTTP/Tailscale 部署使用相同的复制回跳地址流程,不要求为了认证改变 Controller 端口。++## 3. X:采用官方 xurl MCP 桥++### 3.1 已确认的上游行为++- 名称是 `xurl`,npm 包为 `@xdevplatform/xurl`。+- X API 的远端 MCP 是 `https://api.x.com/mcp`;它不提供可让通用 MCP Client 直接完成认证的 OAuth 发现及动态客户端注册。+- 官方推荐以 `xurl mcp` 承担用户 OAuth 和 Bearer 注入。`https://docs.x.com/mcp` 是文档检索服务,不等于 X 账号业务服务。+- 官方支持 `xurl auth oauth2 --headless`。授权 URL 输出到 stderr,输入由 stdin 读取,认证交换及保存继续由 xurl 完成。++依据:[X 官方 MCP 文档](https://docs.x.com/tools/mcp)、[xurl 用法](https://github.com/xdevplatform/xurl/blob/main/README.md)、[headless 命令](https://github.com/xdevplatform/xurl/blob/main/cli/auth.go)、[认证实现](https://github.com/xdevplatform/xurl/blob/main/auth/auth.go)。++### 3.2 安装与启用++包的 postinstall 执行上表中的官方 npm 安装,不追加 CLI 版本号、自定义安装目录或额外 SHA256 锁。启用只检查 CLI 可执行,并注册授权流程。++已有可用授权时,插件通过现有 `ctx.host.mcp.register()` 注册:++```js+{+ name: 'api',+ connection: {+ transport: 'stdio',+ command: 'xurl',+ args: ['mcp', 'https://api.x.com/mcp']+ },+ toolLoading: 'on-demand'+}+```++这里不添加 `oauth` 配置:OAuth 已经在 xurl 内,不再让 Go MCP OAuth 跑第二次认证。内部 MCP 名称为 `x__api`,前端只展示 X 的账号授权情况,不展示桥接器、stdio 或 MCP 连接状态。++Go MCP 系统负责 initialize、分页 tools/list、工具定义校验、转换为 Go 工具、工具列表变化后的重新发现,以及通过现有工具来源接入 Agent。on-demand 控制何时向模型提供具体工具,不改变发现和调用由 Go 管理的边界。X 插件不逐个调用 ctx.host.tools.register,也不硬编码一份 X 工具清单。++未授权时先保留可用的授权入口,不启动会自动尝试登录并阻塞初始化的 MCP 桥。授权成功后注册桥;停用时由 Cordis 撤销注册,Go 关闭相应连接。++### 3.3 用户连接流程++1. 用户在 X 开发者平台创建自己的应用,启用 OAuth 2.0,登记 `http://localhost:8080/callback`,获取 Client ID 和按应用类型所需的 Client Secret。Native App 是公共客户端,Secret 留空,即使控制台显示了 Secret;Web App 等机密客户端才填写。+2. 插件首次授权通过表单收集上述值,不放到部署 `.env`、命令行参数、会话消息、Go credentials 或 Redis;不提供项目共享应用。+3. 插件通过专用 child env 启动 `xurl auth oauth2 --headless`,捕获完整授权 URL,并在用户本机浏览器中打开。+4. 用户登录自己的 X 账号并同意授权,将完整回跳地址粘贴回授权面板。插件核对回调目标及 state 后,通过 stdin 交给本次 xurl 进程。+5. xurl 成功并原生保存授权后,Go 用 inspect 确认完成;已有授权事件触发 MCP 注册。首次原生登录后再通过 xurl status 的原生 backfill 保存应用凭证,使后续刷新无需环境副本。+6. 已有应用配置时跳过开发者凭证输入,直接账号授权。退出授权只清理当前账号令牌,保留应用配置。++X 授权码在用户同意后只有 30 秒有效,需立即提交完整回跳地址。失败或取消后释放进行中状态,用户可从连接入口重新开始,无需重启 Host;新一轮使用新的授权 URL、state 和 PKCE,不复用旧回跳地址。本次真实失败只得到 `invalid_request`,后续成功同时调整了 Secret 与提交时机,因此不将历史失败唯一归因于某一项。[官方客户端类型与有效期](https://docs.x.com/fundamentals/authentication/oauth-2-0/authorization-code)++X MCP 不是免费 API 替代入口,底层调用按用户自己开发者应用对应的访问权限、额度与计费规则执行。插件详情明确介绍获取凭证和连接步骤。++xurl 负责 PKCE、授权码交换、Token 保存、过期刷新及桥接请求。我们不重写这套认证算法,也不从普通 MCP 初始化中偷偷发起登录。++授权完成与 MCP 连通性分开:原生登录成功并经 inspect 确认后即为已授权;随后注册桥失败、API 配额不足或业务请求失败,不应改写成“OAuth 授权失败”,也不删除有效原生凭证。可使用已有授权状态事件触发连接注册,不引入后台定时扫描或 Token 同步任务。++### 3.4 能力范围++按官方 MCP 的实际 `tools/list` 暴露搜索、用户及帖子读取、书签、趋势和 Articles 等能力。不因为 xurl CLI 支持更多 API,就声称官方 MCP 一定提供普通发帖、私信等所有动作。验收时记录实际工具清单;需要扩大范围时再明确引入原生 Skill/CLI 能力,不伪造 MCP 工具。++## 4. Google Workspace:原生 CLI 与 Skills++### 4.1 安装与能力++使用 `npm install -g @googleworkspace/cli`,启用时检查 `gws`。通过官方 Skills 安装方式取得上游内容及引用资源,原样随包装包分发,并交给现有 Go Skills 发现、按需加载机制。不重写 Gmail、Drive、Calendar、Docs、Sheets、Slides 等操作,也不另造一套同名 MCP 工具。++Google API 的可用范围取决于用户实际授权的 scopes、已启用的 API 和组织策略;包里带某个 Skill 不代表账号自动拥有该服务权限。授权页面展示本次要连接的服务和权限,不默认申请 Admin/组织级能力。++依据:[上游安装与认证](https://github.com/googleworkspace/cli/blob/main/README.md)、[原始 Skills](https://github.com/googleworkspace/cli/blob/main/docs/skills.md)。++### 4.2 云端授权适配++已核对的当前实现有 `login/setup/status/export/logout`,没有可直接照搬的 `gws auth login --headless`。其登录流程会输出 URL,并等待 Host 内 localhost 上的临时 HTTP 回调。普通路径的 URL 由原生 flow delegate 输出;配置代理时另有原生回环监听路径。[源码](https://github.com/googleworkspace/cli/blob/main/crates/google-workspace-cli/src/auth_commands.rs)++已实现“浏览器授权 + 回跳转投”适配,沿用原生 gws 认证:++1. 用户创建自己的 Google Cloud 项目,按需启用 API、配置 consent/受众与测试用户,注册 Desktop app OAuth 客户端并下载 JSON。首次连接时 Web 选择本地 JSON 文件并自动解析提交,移动端通过受保护输入框提交 JSON,插件校验标准端点和 installed 结构,私有权限写入原生 gws/client_secret.json,后续连接复用。不在插件包、镜像或部署 env 中提供共享应用。+2. 插件将客户端配置交给原生 gws,运行带明确 scopes 的 `gws auth login`,避免在无 TTY 环境里停在终端权限选择器。+3. 插件从进程输出捕获本次授权 URL 和其中的 `redirect_uri`,通过既有授权面板在用户设备打开 URL。+4. 用户授权后,复制浏览器最终的完整 localhost 回跳地址并粘贴回面板;页面无法打开不等于授权码没有生成。+5. 插件只向本次 gws 进程已公布的 loopback 地址、端口和路径转投回调。不请求用户随意填写的 URL,不跟随重定向;核对原生 URL 中存在的 state。原生进程继续完成代码交换、校验和保存。+6. 命令成功且原生授权检查通过,流程才完成。取消会终止本次子进程和回调监听;CLI 自行失败也结束当前流程,不让用户继续回答已经失效的问题。++这是本项目需要实现、验证的 CLI 适配,不是声称上游已提供通用远程授权接口。需先验证无代理和有代理两条原生登录路径,以及桌面、iOS、Android 浏览器回跳粘贴的可行性,再将它标为“浏览器连接”可用。++Google Workspace 只提供浏览器连接账号的授权入口,不提供已有 gws 授权令牌的导入入口。首次上传/填写的 JSON 是应用客户端配置,不是账号令牌。++服务账号或组织域级代理不是默认登录方式,不将它们包装成个人 OAuth 的等价替代。++## 5. 凭证:以原生 CLI 为唯一保存者++### 5.1 不重复持久化++明确采纳最新决定:这两个插件的 OAuth Token 不再写入 `.credentials.yaml`,也不在其中保存 `native-file`、文件路径指针、connected 布尔值或占位 grant。不添加 Token 双向同步、文件监听回写或后台定时复制。++- X:原生 `~/.xurl/auth.yml` 保存应用和用户 Token,刷新仍由 xurl 负责。+- Google:原生 `~/.config/gws/` 保存客户端配置、认证文件、密钥文件及缓存,沿用其加密和刷新逻辑。+- Go credentials 继续为直接使用它的普通插件及 Go MCP 标准 OAuth 提供原有能力。这两类原生 CLI 插件不为“格式统一”再造第二份记录。+- Redis `plugins` 仍只有 catalogId/version/enabled,不加第三方授权秘密或连接状态。++依据:[xurl 原生存储](https://github.com/xdevplatform/xurl/blob/main/store/tokens.go)、[gws 凭证加载](https://github.com/googleworkspace/cli/blob/main/crates/google-workspace-cli/src/auth.rs)、[gws 加密存储](https://github.com/googleworkspace/cli/blob/main/crates/google-workspace-cli/src/credential_store.rs)。++### 5.2 Host 路径++原生认证数据要属于用户数据。建议由各插件在启用时准备:++```text+/root/harness/.dsh/credentials/x/ # xurl 原生目录内容+/root/harness/.dsh/credentials/google-workspace/ # gws 原生目录内容++/root/.xurl -> /root/harness/.dsh/credentials/x+/root/.config/gws -> /root/harness/.dsh/credentials/google-workspace+```++保持 Agent 的 HOME=/root 和官方命令名,普通 Shell 直接执行 CLI 时也读到同一份数据,不另造命令 launcher,不全局改 HOME。gws 的官方配置目录选项可以用于授权子进程,但不能让授权进程和 Agent CLI 最终读到不同目录。++这是认证数据目录,与 CLI 软件安装目录分开。它由账号现有 Docker 卷/NAS 的数据根承载;不要求新增用户路径配置。目录设为私有权限,gws 的文件型加密密钥必须与认证目录一起保留。目录或链接已有不属于插件的内容时明确报错,不覆盖或删除未知文件。++## 6. 授权框架的必要调整++### 6.1 完成条件++原生 CLI 自己保存账号凭证,authorization 通过插件提供的 inspect 确认是否已连接。未提供 inspect 的普通流程仍以 Go credentials 中成功提交记录作为完成条件。两种完成条件分开,不要求原生 CLI 额外调用 `session.commit()`,也不保存假 grant。++### 6.2 最小扩展++`AuthorizationFlow` 增加以下可选回调,通过 Go RPC 调用:++```ts+interface AuthorizationFlow {+ key: string+ title: string+ methods: AuthorizationMethod[]+ run(session: AuthorizationSession): Promise<void>+ inspect?(context: {signal: AbortSignal}): Promise<{ configured: boolean; accountLabel?: string }>+ disconnect?(context: {signal: AbortSignal}): Promise<void>+}+```++- 原有写 Go credentials 的流程继续使用 `session.commit(record)`。+- 提供 inspect 的原生流程:run 成功返回后再次调用 inspect;只有 configured=true 才确认成功,不要求写 Go 凭证。+- 打开授权页面和流程结束时调用 inspect 获取状态,不定时轮询、不持久化一份副本。不以“访问 Token 已到期但可以刷新”误判为账号未连接;配置存在也不等于服务商永远不会撤销授权。+- 读取失败与明确未配置应区分,错误不能被吞成假成功。+- disconnect 先由插件关闭自己正在使用的连接,再调用原生 CLI 的退出/清理逻辑,最后复查状态。它是授权生命周期,不恢复已删除的通用 actions 框架。+- 回调仍由 Cordis 插件注册,Go 通过现有异步 RPC 调用;Go 不引入 X/Google 业务分支。停用时按 Cordis 生命周期撤销回调。++表层 API/UI 补齐这两个可选能力与账号显示;保留现有 run/cancel/notice/prompt。不提供任意命令执行的前端 RPC,也不把授权错误、密钥和验证码塞进 Agent 会话。++## 7. 前端表现++- 继续使用侧栏/移动端工作区菜单中的插件市场;不新增 Settings 页面或独立 MCP 配置入口。+- 包内 plugin.json 提供名称、description、version 和 icon。图标采用后端 `/assets/plugins/x/icon.png`、`/assets/plugins/google-workspace/icon.png` 路径,两端仅渲染图片 URL。Google Workspace 使用仓库名称旁的官方 googleworkspace 组织彩色 G 头像,不使用 README 横幅裁剪图。 Controller 在展示 URL 附加图片内容版本,避免移动端继续命中旧图缓存;源路径仍由 plugin.json 指定。+- 插件详情中的账号卡显示“未连接 / 已连接”、账号标签及实际可用的授权方法。X 显示连接 X;Google 显示浏览器连接和导入授权数据;未通过适配验收的方法不得伪装可用。+- 授权面板包含服务商链接、在本机浏览器打开、完整回跳地址输入、继续和取消。移动端使用已有底部 Sheet,点击遮罩按现有规则收起,不把登录页嵌进 Host Chromium。+- X 开发者平台链接保留在插件详情的连接步骤中;账号授权流程只提供实际登录链接,避免两个相同的“在浏览器中继续”入口。回跳输入提示明确要求先在浏览器授权,再复制完整 callback 地址,提供地址格式占位,不让用户误以为这里需要填写登录账号。+- Google 的客户端 JSON 和导入授权 JSON:Web 通过本地文件选择器读取、校验 JSON 对象并自动作为现有授权答案发送,不存入聊天附件区,也不新增文件上传存储 API;移动端继续使用 kind=secret 的受保护输入。SDK 的可选 webInput=json-file 仅为 Web 表现提示,插件仍负责结构及服务商校验,Go 保留并转发该字段。+- X/Google 的回跳地址输入框明文显示,Client Secret 和移动端授权 JSON 仍隐藏。显示方式不代表可记录:authorization 对所有自由输入答案进行错误回显脱敏,客户端历史不保存答案。原生 CLI 失败只显示经审核的错误分类,不返回可能含密钥或授权码的 stdout/stderr。+- 关闭面板与取消授权不同:保留当前已有的流程恢复规则;显式取消终止等待与子进程。只有原生认证确认后才显示已连接。+- 安装不等于授权,插件启用成功不等于账号已连接。未授权时仍保留连接入口,不让整个插件 apply 因“缺少账号”失败后连授权按钮都消失。+- Google 原生 Skills 保持原文;插件可通过现有 prompts 服务补充一条认证使用说明,避免 Agent 在普通 Shell 中自行发起交互登录或输出凭证。++## 8. 生命周期与目录++源码仍在现有结构内:++```text+extensions/plugins/x/+ package.json, plugin.json, assets/, scripts/install.mjs+ src/index.mjs, src/native-cli.mjs+extensions/plugins/google-workspace/+ package.json, plugin.json, assets/, scripts/install.mjs+ src/index.mjs, src/native-cli.mjs+ skills/ # 镜像构建阶段由官方 Skills 安装命令生成,不提交生成副本+```++统一 pnpm 管包装包与依赖;postinstall 管各自官方 CLI 安装,apply 只检查并注册。两套 CLI 不放入基础 Host 的强制预装步骤。包装包及 Google 原始 Skills 可沿用已有 bundled 分发,保留上游许可证与出处,不虚构尚未发布的 npm 包。++停用关闭本插件的连接和贡献,保留认证文件;卸载移除包装包,沿用当前保留全局 CLI、凭证及用户文件的规则。用户明确“断开账号”才清理该账号的原生授权。++本次界面管理各插件当前使用的账号,不新增多账号切换产品界面。原生工具中已有的其他账号或应用记录不属于本次断开操作的删除范围,不能直接清空整个原生认证目录。++## 9. 实施与验收++1. 完成 authorization 的 inspect/disconnect 适配及契约测试:原生成功无需 commit、原有 commit 路径仍正常,不将失败/取消的尝试标为授权成功;已有有效账号不因重新授权失败而被清除。断开不伪称只是取消流程。+2. 验证 xurl headless 的 URL/stderr/stdin 桥接、state 错误及退出行为,再接 Go MCP;验收未授权不启动交互 MCP、授权后 tools/list 和一次只读请求。+3. 验证 gws 两种登录路径的本地回调转投,确认桌面和移动浏览器回跳粘贴可用;验证官方导出数据导入。不能以模拟请求代替真实授权验收结论。+4. 验证原生 Token 刷新、Host 重启后的原目录恢复、停用重新启用及原生目录丢失时的明确提示;确认 `.credentials.yaml` 和 Redis 没有这两个 CLI 的 Token 副本。+5. 验证 Google 原始 Skills 发现、按需加载及一次实际只读业务请求;缺 scopes、未启用 API、账号撤销或配额不足时显示原始业务原因。+6. Web 与 Android 完整检查:安装、详情、连接、外部浏览器、返回输入、成功、取消、重新连接、断开、详情返回市场。CLI 安装验证 Linux amd64/arm64,权限模式沿用现有 Go 执行器。++真实验收需要用户自己的 X 测试应用与测试账号,以及用户自己的 Google Desktop OAuth 应用。X 获取和填写步骤见 [账号连接指引](plugin-account-setup.md),Google 前置配置见 [应用配置指引](google-workspace-app-setup.md)。X 私有应用凭证与两者的账号令牌不保存在源码、部署环境文件或 Redis;Google 客户端 JSON 也属于用户自己的原生配置,不随项目分发。默认不发帖、不发邮件,不把远端有副作用的动作当成读连接测试。各写操作可先用模拟服务覆盖,真实发布另按用户明确要求执行。++## 10. 调研基线++调研时 xurl 默认分支提交为 `707f076ab7df7f264803b42a2d3f9fc0e802f25c`;googleworkspace/cli 为 `cd3697e07eb520056dcf142d0c7439bbb9ba32e9`。这些是源码核对基线,不是新增 CLI 安装版本锁。实际实现前复核所安装版本的命令、输出和认证文件布局,避免把旧教程的参数当作现成功能。++授权 URL 适配依据服务商地址及 OAuth 参数识别,不只匹配某句终端英文提示。若所装上游版本的命令或输出不兼容,应明确提示并停止该次授权,不把未知输出当成成功,也不静默改用另一套 OAuth 实现。++## 11. 最新配置收口++- X 不提供共享应用或计费账户;用户首次连接填写自己的 Client ID 与可选 Client Secret。Google 用户首次连接提交自己的 Desktop OAuth JSON,后续复用原生应用配置。+- 前端详情描述由 plugin.json 给出简短介绍、获取凭证步骤、官方指引与连接方法;列表只展示第一段简介。+- 连接前告知用户:检索内容会进入 Agent 上下文,并可能交给其选择的模型服务处理。+- 分开报告每个插件的模拟、原生 CLI 和真实账号验收结果;Google 应用配置已接入,但尚未因此宣称 Google 真实账号也已通过。++## 12. 凭证获取视频++- 详情页按 plugin.json 的 `tutorials` 显示预制视频,字段为 language、title、video、可选 poster;视频位于同一插件后端 assets 路径,不放 Redis,也不由前端写死。+- 使用真实开发者控制台画面,保留全景定位,围绕具体点击/输入区域做平滑放大、缩小和焦点提示,并提供中英文步骤字幕。发布前遮挡账号私密信息与密钥。+- Web 使用带控制条的内嵌播放器,移动端使用 Expo Video 原生播放器与全屏入口;不自动播放,也不加载尚不存在的教程。+- X 使用已捕获的真实控制台画面,用户明确要求录到保存前,不提交设置或生成凭证。Google 教程展示用户自建应用前置步骤:按需启用 API、配置受众/测试用户、选择 Desktop 类型、创建时下载 JSON 的说明;不录制密钥值,不擅自提交控制台变更。视频使用真实控制台画面,停在创建提交前,最后展示旧客户端不允许重新下载原始密钥的现行限制;没有伪造创建成功或下载按钮画面。不能用假控制台或文字动画冒充实录。++## 13. 实施证据与待验收范围++截至 2026-11-21,以下结果已经验证:++- 两个正式包装包经统一 pnpm 安装、Cordis 启用,在 Linux arm64 和 amd64 上安装了实际官方 CLI:xurl 1.3.4、gws 0.22.5。Host 打包包含 95 个原始 Google Workspace Skills,基础镜像不提前安装这两个 CLI。+- authorization 原生 inspect/disconnect 通过 Go、Cordis RPC 和 Controller HTTP 契约测试;没有为了连接状态写入 Go 假凭证或 Redis 账号令牌。+- 实际 xurl 二进制连接本地模拟 OAuth/API,完成 PKCE 授权码交换、应用配置回填、清除临时环境变量后自动刷新、读取账号及单账号退出。退出使用官方 `--oauth2-username`,保留应用配置。这证明原生文件适配和刷新调用,不证明真实 X 账号或 X 云端 MCP 已可用。+- Go MCP Manager 启动真实 xurl stdio 桥,对接本地 Go SDK 模拟服务,完成初始化、tools/list、按需加载、一次工具调用、Go 参数校验及远端会话释放。原生桥在 7 次本地请求中携带 Bearer;没有访问 X 云端。此验证使用隔离临时 HOME,未改动用户账号凭证。+- 使用用户自己的 Native App,用户在自己的浏览器完成 X 同意授权,xurl 原生保存账号。Go authorization inspect 返回已连接,Web 与 Android 显示真实账号标签。实际连接 `https://api.x.com/mcp`,发现 101 个工具,Go MCP Tool 调用一次 `get_users_me` 成功返回当前账号;未发帖、发私信或调用其他写操作。+- 重启本次 QA Host 后,原生授权仍可读取,Go MCP 自动恢复连接并再次发现 101 个工具,无需重新登录;Controller 重启后仍通过 Redis 中的 Host 记录访问它。原生 X 文件确认 Secret 为空;Redis 用户 Hash 仍只有 Host 运行记录及插件选择,Go `.credentials.yaml` 未生成,不存在两份 X Token。 正式 pnpm 重新安装包装包后授权不丢失;停用撤销授权入口并关闭 MCP,再启用从原生目录恢复 101 个工具。Web 实测错误回跳失败后可立即新建授权尝试,取消该尝试不会清除已连接账号。Android 最新 APK 也实测回跳地址明文输入与错误回跳的失败提示,原有账号授权保持连接。+- 实际 Google 包经 Cordis 启用后,Go Registry 发现 95 个 Skill;抽查 gws-shared、gws-gmail、gws-drive、gws-docs、gws-slides 的正文加载及资源目录,停用后撤销、再次启用后全部恢复。+- gws 浏览器回调转投、权限选择及退出通过模拟 CLI 测试;真实 gws 的无账号状态检查和目录链接通过运行验证。原生状态明确 token_valid=false 时不会显示已连接;没有在线校验结果时不会仅凭离线误判授权失效。+- 新版 Web 已实测本地文件选择及自动解析提交:格式错误留在当前流程提示重选,有效的用户原始 JSON 自动进入权限选择并交给原生 CLI;没有复制文本或点击第二次提交。Android 保留受保护输入;Android 通过受保护输入框提交用户自己的有效配置后进入权限选择及原生回跳等待,配置保存与原文件 ID/Secret 一致,权限为 0600。重新授权直接进入权限选择,不重复索取 JSON;取消保留原有真实授权。无效 JSON 失败后能重新开始。Android QA APK 已重新构建并安装。+- X 中英文教程来自真实控制台截图,带焦点缩放和字幕;完整 MP4 解码、后端 Range/HEAD、Web 内嵌播放、Android 内嵌及全屏播放已验证。遵照要求,没有保存 X OAuth 配置或生成新凭证。+- 用户在 Google 控制台添加测试邮箱后,已亲自在真实浏览器完成同意授权并将回跳提交到插件面板。现有 gws 经 HTTP 转投完成代码交换,authorization 状态为 authorized,原生 inspect 返回已连接邮箱。实际 gws drive about get 只请求 user(displayName,emailAddress),成功返回账号基本信息;未读取文件正文、邮件或执行写操作。先前 403 已解除。此证据证明原生认证与业务链路;新版首次配置入口由独立的真实两端 UI 验收覆盖。+- 项目源码中的公共 oauth-client.json 已删除,插件不再加载或打包共享客户端;首次提交 JSON 与后续原生配置复用通过模拟 CLI 测试。真实账号测试所用应用留在用户的原生目录,不能重新写回源码。+- 用户配置保存后重启 QA Host,X 与 Google 原生账号均恢复;X MCP 再次连接且工具数为 101。Google 停用撤销授权入口,重新启用后从原生目录恢复账号。实际 gws auth status 返回 token_valid=true、encryption_valid=true 和账号邮箱;已对照上游实现确认该命令通过 refresh_token 向 Google Token 端点换取 access token,而不是仅检查离线文件。+- Google 原生退出在真实授权目录的隔离临时副本上验证:插件 inspect 识别真实授权,disconnect 调用实际 gws logout,随后 inspect=false,客户端应用配置仍在。临时副本测试结束删除,原账号仍连接;没有调用服务商撤销接口,不将该项写成原账号云端撤销验收。+- Google 中英文教程均为 48 秒,末尾说明已对齐 Web 选择文件、移动端粘贴,来源为真实控制台截图序列,带字幕、全景与焦点缩放,账号信息和密钥已遮挡。Web 语言切换选择对应视频,Android 实际解码播放;两份 MP4 全量解码与后端 HEAD/Range 读取通过。没有新建额外客户端,没有虚构创建成功后的下载屏幕。+- `make test vet check`、Cordis/SDK/Web 测试、Web 构建、移动端类型检查及最新 Host 镜像基础环境检查通过。Host/Controller QA 镜像及 Android arm64 QA APK 已构建;最新 JSON 类型校验补充测试通过。源码检查未发现用户提供的真实 Client ID/Secret;公共配置文件已从源码、打包清单与实际安装包移除。++### 13.1 真实验收边界++- 真实云端业务调用仅包括 X get_users_me 和 Google Drive about 的账号基本信息读取;没有读取邮件/文件正文或发起写操作,不将 Skills 清单等同于所有 Workspace 业务已逐项验收。+- Google 已验证真实授权、刷新与重启恢复;退出在真实凭证隔离副本上验证。X 的刷新和单账号退出采用真实 xurl 对接隔离模拟服务,不宣称实际撤销了原账号的云端授权。+- 新版首次 JSON 配置与复用、错误/取消在 UI 和针对性测试中验证;用户此次真实同意授权在桌面 Chrome 完成,不宣称又在 Android 重新完成了一次 Google 云端同意。+- 教程没有提交新的 Cloud 配置或创建额外客户端;创建后的下载动作以明确字幕说明,非伪造实录。若后续希望补录完整创建后下载过程,需先授权创建教程用的额外 Desktop 客户端。该补录不是插件运行的依赖。++## 14. 完成核对++| 要求 | 当前证据与结论 |+| --- | --- |+| 两个正式插件、官方安装与图标 | 两个包的 package.json/postinstall/plugin.json 已提供;实际 Linux amd64/arm64 CLI 安装通过,后端图标在两端详情及列表显示。 |+| X 通过 Go 内置 MCP 接入 | 真实官方 MCP 的 101 个工具发现及 get_users_me 已通过;业务请求不经 Node 自造 MCP Client。 |+| gws 原始 Skills 与按需加载 | 官方安装命令生成 95 个 Skill;Go Registry 实测发现、正文与资源加载、停用撤销及再次启用恢复。 |+| 原生凭证与 inspect/disconnect | Go native_test、Cordis 适配测试及真实 CLI 隔离测试通过;X 实际重启恢复,Redis/Go 无 Token 副本。Google 已完成真实授权、原生刷新与重启恢复;退出使用真实凭证隔离副本,原账号保留。 |+| Web/Android 交互与教程 | 已验证列表、详情、外部链接、输入、失败、取消、恢复与真实 X 已连接展示;X 中英文焦点视频播放通过。新版 Web 文件选择、自动解析与提交,以及 Android 受保护输入和账号恢复已验证;中英文 48 秒前置教程已接入并验证播放,未额外创建客户端。 |+| 构建与检查 | 最新 Host/Controller QA 镜像及 Android arm64 QA 包构建通过;make test vet check、Cordis 24 项、SDK、Web 22 项、移动端类型检查与相关 race 检查通过。 |+| Google 真实授权及只读业务 | 已通过真实浏览器登录、代码交换及 gws Drive about 的账号基本信息只读请求。该次应用属于用户自己,不再由项目分发。 |++该核对不把原生 CLI 对模拟服务的成功等同于服务商真实账号通过,也不把已有 X 授权的保留等同于真实撤销/重授权验收。本次实现与必要验收已完成;上述未覆盖范围为真实账号验证边界,不宣称全部业务 API 或服务商云端撤销均已验收。+++## 15. 最终回跳流程与校验边界++按用户最新确认,保留手动粘贴回跳 URL 的交互。删除此前浏览器扩展、手机本地 HTTP 接收器、session.browser 和 browser-result 接口草案;这些不属于本次实施范围,也不要求用户额外安装授权辅助程序。已有 session.callback 继续服务原本支持服务端回调的插件,不用于截获 X/gws 的客户端 localhost。++### 15.1 每次授权如何确定回跳地址++插件启动原生 CLI,读取它输出的授权 URL,从该 URL 的 redirect_uri 提取本次预期回跳地址;如果原生链接包含 state,也保留本次 state。随后通过 session.notify 将授权链接交给前端,前端只负责打开用户浏览器和展示输入表单。++服务商让浏览器跳转的地址由原生 CLI 的授权请求指定,不由前端随意生成。不同插件或不同授权尝试可以使用不同的端口和路径,不维护全局固定回跳地址:++| 插件 | 预期地址来源 | 用户输入之后的交接 |+| --- | --- | --- |+| X | 本次 xurl 授权 URL 的 redirect_uri;当前应用登记为 http://localhost:8080/callback | 插件校验后,将完整 URL 写入本次 xurl --headless 的 stdin |+| Google Workspace | 本次 gws 授权 URL 的 redirect_uri,端口由 gws 动态选择 | 插件校验后,在 Host 内向本次 gws 回环监听器发送 HTTP GET |++浏览器所在设备的 localhost 与 Host 的 localhost 不同。用户本机回跳页无法打开时,仍可复制地址栏中的完整 URL,回到插件面板提交。插件在 Host 内完成交接,不需要把 Host 回调端口对外发布。++### 15.2 插件校验与服务商验证++插件的 validateRedirect 使用 URL 解析器比较用户输入与原生 CLI 提供的预期地址:origin(协议、主机、端口)和 pathname 必须相同;不接受用户名、密码或 fragment;必须恰有一个非空 code。本次原生授权 URL 包含 state 时,输入必须恰有一个相同的 state;原生 URL 未包含 state 时,不宣称已有额外 state 保护。++Google 的 relayRedirect 还限制目标只能是本次 CLI 给出的 HTTP loopback 地址和明确端口,只向该目标发送 GET,不跟随 HTTP 重定向,不把用户输入变成任意 URL 请求。X 校验后仅写入本次进程 stdin。++这一步证明输入的格式和回跳目标符合本次流程,不能证明 code 是真实、未过期或未使用的。原生 CLI 继续调用服务商 Token 端点;X 使用原生 PKCE,Google 使用原生 gws 的交换逻辑。授权码是否有效由服务商最终决定。CLI 退出成功后,authorization 通过插件 inspect 再确认原生授权状态,才向前端报告已连接。++### 15.3 交互与失败++回跳 URL 用明文输入,Client Secret 和导入授权 JSON 用密钥输入;授权输入不进入聊天、Redis、客户端历史或错误原文。X 短期授权码需要用户同意后尽快提交,失败后提供重新开始入口,新一轮使用新的原生授权链接。++插件通过 session.prompt 等待输入;Go authorization 和 Controller 只负责通用传输、等待、取消及流程恢复,不实现 X/Google 专属提交逻辑。取消终止本次原生子进程,失败或取消不清除已有有效账号授权。Google 的实际应用访问限制、scopes、API 开关等由服务商决定,输入框或 HTTP 转投不能绕过这些限制。diff --git a/examples/plugins/README.md b/examples/plugins/README.mdnew file mode 100644index 0000000..3e0c2dd--- /dev/null+++ b/examples/plugins/README.md@@ -0,0 +1,45 @@+# Plugin examples++These examples use the new Host Bridge SDK (`goBot.api: "1"`). They run as+trusted JavaScript packages in Cordis. Go owns all Harness core execution.++- **typescript-tool**: a text/JSON tool, compiled to JavaScript. Install the local+ SDK development dependency and run `pnpm build` in this directory first.+- **catalog-provider**: a normal Cordis service with no Go-specific business enum.+- **catalog-tools**: injects that service and `host`, then awaits tool registration.+- **mcp-service**: registers an HTTP MCP declaration; Go connects and executes it.+ Its optional `apiKey` config names an existing Go credential reference, never a+ literal key. The plugin does not run a Node MCP client or provide an MCP UI.++Packages can be installed from a registry, a pinned Git revision, a tarball or an+absolute Host development directory. Local paths refer to the Host container,+not the workstation running the browser.++The following is the **Host-private development contract** used in tests to exercise+Cordis entries with custom example configuration. It is not Redis data or a public+user API. Normal users manage one catalog package selection (version/enabled),+with no instance or arbitrary-config form:++```json+{+ "packages": {+ "@go-bot-example/catalog-provider": {+ "source": { "type": "directory", "spec": "/opt/examples/catalog-provider" }+ },+ "@go-bot-example/catalog-tools": {+ "source": { "type": "directory", "spec": "/opt/examples/catalog-tools" }+ }+ },+ "instances": [+ { "id": "catalog", "package": "@go-bot-example/catalog-provider", "enabled": true,+ "config": { "entries": { "support": "Contact the support team" } } },+ { "id": "lookup", "package": "@go-bot-example/catalog-tools", "enabled": true,+ "config": { "toolName": "catalog_lookup", "prefix": "" } }+ ]+}+```++Cordis resolves native dependencies and retracts effects on removal. Each Host+tool is namespaced by instance ID; plugins provide a business `execute` callback,+not a pre/execute/post middleware chain. Do not add actions, storage, Asset RPC,+Agent/Session proxies, client slots or an upstream bundle/patch file.diff --git a/examples/plugins/catalog-provider/index.mjs b/examples/plugins/catalog-provider/index.mjsnew file mode 100644index 0000000..df42336--- /dev/null+++ b/examples/plugins/catalog-provider/index.mjs@@ -0,0 +1,28 @@+export const name = 'example-catalog-provider'++// Standard Schema is a Cordis configuration contract. This example has no+// runtime dependencies; real plugins may use Schemastery, Zod or another+// Standard Schema implementation instead.+export const Config = {+ '~standard': {+ version: 1,+ vendor: 'go-bot-example',+ validate(input) {+ const value = input ?? {}+ if (!value || typeof value !== 'object' || Array.isArray(value) ||+ !value.entries || typeof value.entries !== 'object' || Array.isArray(value.entries) ||+ Object.values(value.entries).some(text => typeof text !== 'string')) {+ return { issues: [{ message: 'entries must be an object of string values', path: ['entries'] }] }+ }+ return { value: { entries: { ...value.entries } } }+ },+ },+}++export function apply(ctx, config) {+ // Cordis withdraws the service when this instance is disabled or removed.+ // Consumers declare the dependency instead of polling for it.+ ctx.provide('exampleCatalog', {+ lookup(key) { return Object.hasOwn(config.entries, key) ? config.entries[key] : undefined },+ })+}diff --git a/examples/plugins/catalog-provider/package.json b/examples/plugins/catalog-provider/package.jsonnew file mode 100644index 0000000..357facb--- /dev/null+++ b/examples/plugins/catalog-provider/package.json@@ -0,0 +1,12 @@+{+ "name": "@go-bot-example/catalog-provider",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "exports": "./index.mjs",+ "license": "MIT",+ "description": "Example of a Cordis service unknown to the Go core",+ "goBot": {+ "api": "1"+ }+}diff --git a/examples/plugins/catalog-tools/index.mjs b/examples/plugins/catalog-tools/index.mjsnew file mode 100644index 0000000..1857ddd--- /dev/null+++ b/examples/plugins/catalog-tools/index.mjs@@ -0,0 +1,33 @@+export const name = 'example-catalog-tools'+export const inject = ['exampleCatalog', 'host']++export const Config = {+ '~standard': {+ version: 1,+ vendor: 'go-bot-example',+ validate(input) {+ const value = input ?? {}+ if (!value || typeof value !== 'object' || Array.isArray(value) ||+ typeof value.toolName !== 'string' || !/^[a-z][a-z0-9_]{0,63}$/.test(value.toolName) ||+ (value.prefix !== undefined && typeof value.prefix !== 'string')) {+ return { issues: [{ message: 'Provide toolName (letters, digits, underscores) and an optional string prefix' }] }+ }+ return { value: { toolName: value.toolName, prefix: value.prefix ?? '' } }+ },+ },+}++export async function apply(ctx, config) {+ await ctx.host.tools.register({+ name: config.toolName,+ description: 'Look up a key in the example catalog. Returns whether the key exists and its description.',+ concurrency: 'parallel',+ inputSchema: { type: 'object', properties: { key: { type: 'string' } }, required: ['key'], additionalProperties: false },+ async execute(args, execution) {+ execution.signal.throwIfAborted()+ const text = ctx.exampleCatalog.lookup(args.key)+ const message = text === undefined ? 'No matching entry.' : config.prefix + text+ return { content: [{ type: 'text', text: message }], data: { found: text !== undefined, text: message } }+ },+ })+}diff --git a/examples/plugins/catalog-tools/package.json b/examples/plugins/catalog-tools/package.jsonnew file mode 100644index 0000000..b1c3e74--- /dev/null+++ b/examples/plugins/catalog-tools/package.json@@ -0,0 +1,12 @@+{+ "name": "@go-bot-example/catalog-tools",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "exports": "./index.mjs",+ "license": "MIT",+ "description": "Example service consumer that registers a model tool",+ "goBot": {+ "api": "1"+ }+}diff --git a/examples/plugins/mcp-service/index.mjs b/examples/plugins/mcp-service/index.mjsnew file mode 100644index 0000000..38f25c7--- /dev/null+++ b/examples/plugins/mcp-service/index.mjs@@ -0,0 +1,32 @@+export const name = 'example-mcp-service'+export const inject = ['host']++export const Config = {+ '~standard': {+ version: 1,+ vendor: 'go-bot-example',+ validate(input) {+ const value = input ?? {}+ const issues = []+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { issues: [{ message: 'Provide an object configuration.' }] }+ if (typeof value.serverName !== 'string' || !/^[A-Za-z0-9_-]{1,32}$/.test(value.serverName)) issues.push({ message: 'Use a serverName of letters, digits, underscores or hyphens.', path: ['serverName'] })+ try {+ const url = new URL(value.url)+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('invalid URL')+ } catch { issues.push({ message: 'Provide an HTTP(S) MCP URL without embedded credentials.', path: ['url'] }) }+ if (value.apiKey !== undefined && typeof value.apiKey !== 'string') issues.push({ message: 'apiKey must name a credential reference, not contain a secret.', path: ['apiKey'] })+ if (issues.length) return { issues }+ return { value: { serverName: value.serverName, url: value.url, apiKey: value.apiKey ?? '' } }+ },+ },+}++export async function apply(ctx, config) {+ // Registration uses the built-in Go MCP client. It does not start a second+ // MCP manager in Node. The plugin's lifetime owns this contribution.+ await ctx.host.mcp.register({name: config.serverName, connection: {+ transport: 'streamable-http',+ url: config.url,+ headers: config.apiKey ? { Authorization: 'Bearer ${credential:' + config.apiKey + '}' } : {},+ } })+}diff --git a/examples/plugins/mcp-service/package.json b/examples/plugins/mcp-service/package.jsonnew file mode 100644index 0000000..f0ccb1f--- /dev/null+++ b/examples/plugins/mcp-service/package.json@@ -0,0 +1,12 @@+{+ "name": "@go-bot-example/mcp-service",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "exports": "./index.mjs",+ "license": "MIT",+ "description": "Example plugin contributing an HTTP server to Go Bot's built-in MCP manager",+ "goBot": {+ "api": "1"+ }+}diff --git a/examples/plugins/typescript-tool/.gitignore b/examples/plugins/typescript-tool/.gitignorenew file mode 100644index 0000000..12c18d4--- /dev/null+++ b/examples/plugins/typescript-tool/.gitignore@@ -0,0 +1 @@+/lib/diff --git a/examples/plugins/typescript-tool/package.json b/examples/plugins/typescript-tool/package.jsonnew file mode 100644index 0000000..1e75a9a--- /dev/null+++ b/examples/plugins/typescript-tool/package.json@@ -0,0 +1,22 @@+{+ "name": "@go-bot-example/typescript-tool",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "license": "MIT",+ "exports": "./lib/index.js",+ "files": [+ "lib"+ ],+ "scripts": {+ "build": "tsc"+ },+ "devDependencies": {+ "@go-bot/plugin-sdk": "file:../../../extensions/sdk",+ "@types/node": "24.10.0",+ "typescript": "7.0.2"+ },+ "goBot": {+ "api": "1"+ }+}diff --git a/examples/plugins/typescript-tool/pnpm-lock.yaml b/examples/plugins/typescript-tool/pnpm-lock.yamlnew file mode 100644index 0000000..6e05235--- /dev/null+++ b/examples/plugins/typescript-tool/pnpm-lock.yaml@@ -0,0 +1,281 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .:+ devDependencies:+ '@go-bot/plugin-sdk':+ specifier: file:../../../extensions/sdk+ version: file:../../../extensions/sdk+ '@types/node':+ specifier: 24.10.0+ version: 24.10.0+ typescript:+ specifier: 7.0.2+ version: 7.0.2++packages:++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-CJrjNyBkKn1SfvBQUcgFYKFnLjS+uKrhdMsbHU60xabvi12d+xQ+IQSNlME5Z+B+4Zi6n4BDknKY94tEPeo47w==}+ hasBin: true+ peerDependencies:+ '@deepseek-ai/cordis-plugin-include': ~1.1.0+ '@deepseek-ai/cordis-plugin-loader': ~1.1.0+ peerDependenciesMeta:+ '@deepseek-ai/cordis-plugin-include':+ optional: true+ '@deepseek-ai/cordis-plugin-loader':+ optional: true++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-5O1S53mZiJyZYcvxxD0Qv1EY7qFPSxbGyD8CbVK6gw7W9FvcXZj2YIX1ZkOqyQQ3Xt2rFkZDHJv0+V3Zmmp8CA==}++ '@go-bot/plugin-sdk@file:../../../extensions/sdk':+ resolution: {directory: ../../../extensions/sdk, type: directory}+ engines: {node: '>=24.9.0'}++ '@standard-schema/[email protected]':+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}++ '@types/[email protected]':+ resolution: {integrity: sha512-qzQZRBqkFsYyaSWXuEHc2WR9c0a0CXwiE5FWUvn7ZM+vdy1uZLfCunD38UzhuB7YN/J11ndbDBcTmOdxJo9Q7A==}++ '@typescript/[email protected]':+ resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}+ engines: {node: '>=16.20.0'}+ cpu: [ppc64]+ os: [aix]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [darwin]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [darwin]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [freebsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [freebsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==}+ engines: {node: '>=16.20.0'}+ cpu: [loong64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==}+ engines: {node: '>=16.20.0'}+ cpu: [mips64el]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==}+ engines: {node: '>=16.20.0'}+ cpu: [ppc64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==}+ engines: {node: '>=16.20.0'}+ cpu: [riscv64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==}+ engines: {node: '>=16.20.0'}+ cpu: [s390x]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [netbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [netbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [openbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [openbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [sunos]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [win32]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [win32]++ resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==}+ engines: {node: '>=16.20.0'}+ hasBin: true++ resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}++snapshots:++ '@deepseek-ai/[email protected]':+ dependencies:+ '@deepseek-ai/cosmokit': 1.9.0+ '@standard-schema/spec': 1.1.0++ '@deepseek-ai/[email protected]': {}++ '@go-bot/plugin-sdk@file:../../../extensions/sdk':+ dependencies:+ '@deepseek-ai/cordis': 4.1.0+ transitivePeerDependencies:+ - '@deepseek-ai/cordis-plugin-include'+ - '@deepseek-ai/cordis-plugin-loader'++ '@standard-schema/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ undici-types: 7.16.0++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ optionalDependencies:+ '@typescript/typescript-aix-ppc64': 7.0.2+ '@typescript/typescript-darwin-arm64': 7.0.2+ '@typescript/typescript-darwin-x64': 7.0.2+ '@typescript/typescript-freebsd-arm64': 7.0.2+ '@typescript/typescript-freebsd-x64': 7.0.2+ '@typescript/typescript-linux-arm': 7.0.2+ '@typescript/typescript-linux-arm64': 7.0.2+ '@typescript/typescript-linux-loong64': 7.0.2+ '@typescript/typescript-linux-mips64el': 7.0.2+ '@typescript/typescript-linux-ppc64': 7.0.2+ '@typescript/typescript-linux-riscv64': 7.0.2+ '@typescript/typescript-linux-s390x': 7.0.2+ '@typescript/typescript-linux-x64': 7.0.2+ '@typescript/typescript-netbsd-arm64': 7.0.2+ '@typescript/typescript-netbsd-x64': 7.0.2+ '@typescript/typescript-openbsd-arm64': 7.0.2+ '@typescript/typescript-openbsd-x64': 7.0.2+ '@typescript/typescript-sunos-x64': 7.0.2+ '@typescript/typescript-win32-arm64': 7.0.2+ '@typescript/typescript-win32-x64': 7.0.2++ [email protected]: {}diff --git a/examples/plugins/typescript-tool/src/index.ts b/examples/plugins/typescript-tool/src/index.tsnew file mode 100644index 0000000..f4e21b3--- /dev/null+++ b/examples/plugins/typescript-tool/src/index.ts@@ -0,0 +1,27 @@+import type { Context, JSONValue } from '@go-bot/plugin-sdk'++export const name = 'example-typescript-tool'+export const inject = ['host']++export async function apply(ctx: Context) {+ await ctx.host.tools.register({+ name: 'echo',+ description: 'Return a short note from this example integration.',+ inputSchema: {+ type: 'object', properties: { text: { type: 'string', maxLength: 1000 } },+ required: ['text'], additionalProperties: false,+ },+ async execute(args, call) {+ call.signal.throwIfAborted()+ const text = readNote(args)+ return { content: [{ type: 'text', text }], data: { text } }+ },+ })+}++function readNote(value: JSONValue): string {+ if (!value || typeof value !== 'object' || !('text' in value) || typeof value.text !== 'string') {+ throw new TypeError('A note needs a string text field')+ }+ return value.text+}diff --git a/examples/plugins/typescript-tool/tsconfig.json b/examples/plugins/typescript-tool/tsconfig.jsonnew file mode 100644index 0000000..3d6944b--- /dev/null+++ b/examples/plugins/typescript-tool/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "ES2023",+ "lib": ["ES2023", "ESNext.Disposable", "DOM"],+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "strict": true,+ "skipLibCheck": false,+ "rootDir": "src",+ "outDir": "lib",+ "declaration": true+ },+ "include": ["src"]+}diff --git a/extensions/catalog/README.md b/extensions/catalog/README.mdnew file mode 100644index 0000000..722c523--- /dev/null+++ b/extensions/catalog/README.md@@ -0,0 +1,13 @@+# Reviewed plugin catalog / 经审核的插件清单++plugins.json is compiled into Controller. Clients choose pluginId, never a user-supplied package address. The first-party agent-browser and OfficeCLI wrappers ship as bundled sources in the Host image; users install and enable them through the same market.++plugins.json 随 Controller 构建内置。用户选择 pluginId,不提交包地址。agent-browser 和 OfficeCLI 包装包随 Host 镜像分发,通过统一市场安装、启用。++First-party plugin.json files supply original name, bilingual description, icon, version, maintainer and license. The catalog selects the package/release and installation policy; Controller assembles display metadata at build time. Sources are reviewed bundled packages, exact npm versions, full Git commits or fixed HTTPS release archives. No floating branches, latest tags, placeholder URLs, development directories or credential values.++展示字段来自各包 plugin.json:原始名称、双语 description、icon、version、maintainer、license;清单只记录包身份、版本选择、来源和脚本放行策略。来源使用随 Host 分发的 bundled 包、固定 npm 版本、完整 Git commit 或固定 HTTPS 发布归档,不能使用占位地址、开发目录或凭证。++Redis stores only user catalogId/version/enabled selections. Maintain selected releases for the product versions that support them; updates require a user action. Package source resolution is Host-private. goBot.api must equal "1". Standard npm lifecycle scripts, approved through pnpm allowBuilds, prepare dependencies during installation, never during inspection or Cordis activation. See ../sdk/README.md.++Redis 只存用户的 catalogId/version/enabled。维护受支持的已选版本,更新由用户主动执行。安装时由 pnpm 调用包声明并经审核放行的标准安装脚本;浏览、检查包与 Cordis apply 不安装软件。diff --git a/extensions/catalog/catalog.go b/extensions/catalog/catalog.gonew file mode 100644index 0000000..5a73b22--- /dev/null+++ b/extensions/catalog/catalog.go@@ -0,0 +1,105 @@+// Package catalog embeds the project's reviewed business plugin releases.+// It is build-time data, never a user-configured remote index.+package catalog++import (+ "bytes"+ _ "embed"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "net/url"+ "regexp"+ "strings"++ bundled "go-bot/extensions/plugins"+ "go-bot/plugin"+)++//go:embed plugins.json+var manifest []byte++type Entry struct {+ plugin.CatalogEntry+ Source plugin.Source `json:"source"`+ Builds []string `json:"builds,omitempty"`+}++var idPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,63}$`)+var versionPattern = regexp.MustCompile(`^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$`)++// Entries returns a fresh copy so request processing cannot mutate the catalog.+func Entries() []Entry {+ entries, err := Parse(manifest)+ if err != nil {+ panic("invalid bundled plugin catalog: " + err.Error())+ }+ return entries+}++func Parse(data []byte) ([]Entry, error) {+ var entries []Entry+ d := json.NewDecoder(bytes.NewReader(data))+ d.DisallowUnknownFields()+ if err := d.Decode(&entries); err != nil {+ return nil, err+ }+ if !errors.Is(d.Decode(new(any)), io.EOF) || entries == nil || len(entries) > 200 {+ return nil, errors.New("catalog must be one array of at most 200 releases")+ }+ ids, packages := map[string]bool{}, map[string]bool{}+ for i := range entries {+ entry := &entries[i]+ if entry.Source.Type == "bundled" {+ display, err := bundled.Metadata(entry.Source.Spec)+ if err != nil {+ return nil, err+ }+ if display.ID != entry.ID || display.Package != entry.Package || display.Version != entry.Version {+ return nil, fmt.Errorf("%s: bundled identity differs from the catalog", entry.ID)+ }+ entry.CatalogEntry = display+ }+ if !idPattern.MatchString(entry.ID) || ids[entry.ID] || packages[entry.Package] {+ return nil, errors.New("catalog plugin IDs and package names must be unique")+ }+ ids[entry.ID], packages[entry.Package] = true, true+ if !versionPattern.MatchString(entry.Version) || entry.Maintainer == "" || entry.License == "" || strings.TrimSpace(entry.Name) == "" {+ return nil, fmt.Errorf("%s: version, maintainer and license are required", entry.ID)+ }+ for _, text := range []plugin.Localized{entry.Description} {+ if strings.TrimSpace(text.EN) == "" || strings.TrimSpace(text.ZH) == "" {+ return nil, fmt.Errorf("%s: English and Simplified Chinese copy are required", entry.ID)+ }+ }+ if !strings.HasPrefix(entry.Icon, bundled.AssetPrefix) || !fs.ValidPath(strings.TrimPrefix(entry.Icon, bundled.AssetPrefix)) || strings.ContainsAny(entry.Icon, "\\?#") {+ return nil, fmt.Errorf("%s: icon must reference a backend plugin asset", entry.ID)+ }++ settings := plugin.RuntimeSettings{Packages: map[string]plugin.RuntimePackage{entry.Package: {Source: entry.Source, Builds: entry.Builds}}}+ if err := settings.Validate(); err != nil {+ return nil, fmt.Errorf("%s: %w", entry.ID, err)+ }+ switch entry.Source.Type {+ case "registry":+ if entry.Source.Spec != entry.Package+"@"+entry.Version {+ return nil, fmt.Errorf("%s: registry source must match the catalog release", entry.ID)+ }+ case "bundled":+ if entry.Source.Spec != entry.ID {+ return nil, fmt.Errorf("%s: bundled source must match plugin ID", entry.ID)+ }+ case "git": // Settings.Validate requires a full commit, never a branch.+ case "tarball":+ u, err := url.Parse(entry.Source.Spec)+ if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {+ return nil, fmt.Errorf("%s: distribution archives require a fixed HTTPS release URL", entry.ID)+ }+ default:+ return nil, fmt.Errorf("%s: development directories are not market releases", entry.ID)+ }+ }+ return entries, nil+}diff --git a/extensions/catalog/catalog_test.go b/extensions/catalog/catalog_test.gonew file mode 100644index 0000000..07a36f1--- /dev/null+++ b/extensions/catalog/catalog_test.go@@ -0,0 +1,48 @@+package catalog++import (+ "encoding/json"+ "testing"++ "go-bot/plugin"+)++func reviewed() Entry {+ text := plugin.Localized{EN: "Mail", ZH: "邮件"}+ return Entry{CatalogEntry: plugin.CatalogEntry{ID: "mail", Package: "@fixture/mail", Version: "1.0.0", Name: "Mail", Description: text, Icon: "/assets/plugins/mail/icon.png", Maintainer: "Fixture", License: "MIT"}, Source: plugin.Source{Type: "registry", Spec: "@fixture/[email protected]"}}+}++func TestCatalogRequiresReviewedPinnedBilingualReleases(t *testing.T) {+ for _, test := range []struct {+ name string+ edit func(*Entry)+ }{+ {"floating-version", func(e *Entry) { e.Source.Spec = "@fixture/mail@latest" }},+ {"wrong-version", func(e *Entry) { e.Version = "2.0.0" }},+ {"floating-git", func(e *Entry) { e.Source = plugin.Source{Type: "git", Spec: "https://example.com/mail.git#main"} }},+ {"host-directory", func(e *Entry) { e.Source = plugin.Source{Type: "directory", Spec: "/tmp/mail"} }},+ {"untranslated", func(e *Entry) { e.Description.ZH = "" }},+ {"unreviewed-icon", func(e *Entry) { e.Icon = "https://example.com/icon.svg" }},+ } {+ t.Run(test.name, func(t *testing.T) {+ entry := reviewed()+ test.edit(&entry)+ data, _ := json.Marshal([]Entry{entry})+ if _, err := Parse(data); err == nil {+ t.Fatal("accepted invalid release")+ }+ })+ }+ data, _ := json.Marshal([]Entry{reviewed()})+ if entries, err := Parse(data); err != nil || len(entries) != 1 {+ t.Fatal(entries, err)+ }+ data, _ = json.Marshal([]Entry{reviewed(), reviewed()})+ if _, err := Parse(data); err == nil {+ t.Fatal("accepted duplicate identity")+ }+ // An empty real catalog is preferable to publishing demo placeholders.+ if Entries() == nil {+ t.Fatal("catalog must serialize as an array")+ }+}diff --git a/extensions/catalog/plugins.json b/extensions/catalog/plugins.jsonnew file mode 100644index 0000000..0816843--- /dev/null+++ b/extensions/catalog/plugins.json@@ -0,0 +1,50 @@+[+ {+ "pluginId": "agent-browser",+ "package": "@go-bot/plugin-agent-browser",+ "version": "0.1.0",+ "source": {+ "type": "bundled",+ "spec": "agent-browser"+ },+ "builds": [+ "@go-bot/plugin-agent-browser"+ ]+ },+ {+ "pluginId": "officecli",+ "package": "@go-bot/plugin-officecli",+ "version": "0.1.0",+ "source": {+ "type": "bundled",+ "spec": "officecli"+ },+ "builds": [+ "@go-bot/plugin-officecli"+ ]+ },+ {+ "pluginId": "x",+ "package": "@go-bot/plugin-x",+ "version": "0.1.0",+ "source": {+ "type": "bundled",+ "spec": "x"+ },+ "builds": [+ "@go-bot/plugin-x"+ ]+ },+ {+ "pluginId": "google-workspace",+ "package": "@go-bot/plugin-google-workspace",+ "version": "0.1.0",+ "source": {+ "type": "bundled",+ "spec": "google-workspace"+ },+ "builds": [+ "@go-bot/plugin-google-workspace"+ ]+ }+]diff --git a/extensions/cordis/package.json b/extensions/cordis/package.jsonnew file mode 100644index 0000000..78867aa--- /dev/null+++ b/extensions/cordis/package.json@@ -0,0 +1,17 @@+{+ "name": "go-bot-cordis-runtime",+ "private": true,+ "type": "module",+ "engines": {+ "node": ">=24.9.0"+ },+ "packageManager": "[email protected]",+ "scripts": {+ "test": "node --test test/*.test.mjs"+ },+ "dependencies": {+ "@deepseek-ai/cordis": "4.1.0",+ "@deepseek-ai/cordis-plugin-loader": "1.1.0",+ "semver": "7.8.6"+ }+}diff --git a/extensions/cordis/pnpm-lock.yaml b/extensions/cordis/pnpm-lock.yamlnew file mode 100644index 0000000..2223863--- /dev/null+++ b/extensions/cordis/pnpm-lock.yaml@@ -0,0 +1,82 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: false+ excludeLinksFromLockfile: false++importers:++ .:+ dependencies:+ '@deepseek-ai/cordis':+ specifier: 4.1.0+ version: 4.1.0(@deepseek-ai/[email protected])+ '@deepseek-ai/cordis-plugin-loader':+ specifier: 1.1.0+ version: 1.1.0(@deepseek-ai/[email protected])+ semver:+ specifier: 7.8.6+ version: 7.8.6++packages:++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-154u0LnADauDvOdQ41QtoOrRFQtvP2Ih68aYYaXzI/l7gRPwX/5MDtDDsJWeDffQA3ELn2xt3MUYsyizi+O9KA==}+ peerDependencies:+ '@deepseek-ai/cordis': ~4.1.0+ node-addon-require-builtin: ^0.1.9+ peerDependenciesMeta:+ node-addon-require-builtin:+ optional: true++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-CJrjNyBkKn1SfvBQUcgFYKFnLjS+uKrhdMsbHU60xabvi12d+xQ+IQSNlME5Z+B+4Zi6n4BDknKY94tEPeo47w==}+ hasBin: true+ peerDependencies:+ '@deepseek-ai/cordis-plugin-include': ~1.1.0+ '@deepseek-ai/cordis-plugin-loader': ~1.1.0+ peerDependenciesMeta:+ '@deepseek-ai/cordis-plugin-include':+ optional: true+ '@deepseek-ai/cordis-plugin-loader':+ optional: true++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-5O1S53mZiJyZYcvxxD0Qv1EY7qFPSxbGyD8CbVK6gw7W9FvcXZj2YIX1ZkOqyQQ3Xt2rFkZDHJv0+V3Zmmp8CA==}++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-bDXoYQa7ghAhmdYD5VPlzKxEzJV/aKkz5l4V5h1u06z8GAPN1ROewSjvR9WiXhpa52E9fng8lpH5QdCRIQgnyQ==}++ '@standard-schema/[email protected]':+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}++ resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==}+ engines: {node: '>=10'}+ hasBin: true++snapshots:++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/[email protected])+ '@deepseek-ai/cosmokit': 1.9.0+ '@deepseek-ai/schemastery': 3.19.0++ '@deepseek-ai/[email protected](@deepseek-ai/[email protected])':+ dependencies:+ '@deepseek-ai/cosmokit': 1.9.0+ '@standard-schema/spec': 1.1.0+ optionalDependencies:+ '@deepseek-ai/cordis-plugin-loader': 1.1.0(@deepseek-ai/[email protected])++ '@deepseek-ai/[email protected]': {}++ '@deepseek-ai/[email protected]':+ dependencies:+ '@deepseek-ai/cosmokit': 1.9.0+ '@standard-schema/spec': 1.1.0++ '@standard-schema/[email protected]': {}++ [email protected]: {}diff --git a/extensions/cordis/pnpm-workspace.yaml b/extensions/cordis/pnpm-workspace.yamlnew file mode 100644index 0000000..1aec1d9--- /dev/null+++ b/extensions/cordis/pnpm-workspace.yaml@@ -0,0 +1 @@+autoInstallPeers: falsediff --git a/extensions/cordis/src/errors.mjs b/extensions/cordis/src/errors.mjsnew file mode 100644index 0000000..17d3e33--- /dev/null+++ b/extensions/cordis/src/errors.mjs@@ -0,0 +1,2 @@+// The runtime and installed plugins use the same public error contract.+export { HostError as RuntimeError } from '../../sdk/index.mjs'diff --git a/extensions/cordis/src/host-plugin.mjs b/extensions/cordis/src/host-plugin.mjsnew file mode 100644index 0000000..21ff3b0--- /dev/null+++ b/extensions/cordis/src/host-plugin.mjs@@ -0,0 +1,202 @@+import { Service } from '@deepseek-ai/cordis'+import { AsyncLocalStorage } from 'node:async_hooks'+import { RuntimeError } from './errors.mjs'++const invocation = Symbol('go-bot.invocation')+const callbackContext = new AsyncLocalStorage()+const lifetimes = new WeakMap()+const fail = (code, message) => { throw new RuntimeError(code, message) }+const managementSignal = (...signals) => AbortSignal.any([...signals.filter(Boolean), AbortSignal.timeout(30_000)])++export function assertJSON(value, ancestors = new Set(), depth = 0) {+ if (depth > 64) fail('INVALID_ARGUMENT', 'JSON nesting exceeds 64 levels')+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return+ if (typeof value === 'number' && Number.isFinite(value)) return+ if (!value || typeof value !== 'object' || ancestors.has(value) ||+ (!Array.isArray(value) && ![Object.prototype, null].includes(Object.getPrototypeOf(value)))) fail('INVALID_ARGUMENT', 'Expected lossless JSON data')+ if (Reflect.ownKeys(value).some(key => typeof key === 'symbol')) fail('INVALID_ARGUMENT', 'Symbols are not JSON data')+ ancestors.add(value)+ for (const item of Array.isArray(value) ? value : Object.values(value)) assertJSON(item, ancestors, depth + 1)+ ancestors.delete(value)+}++export function ownerOf(ctx, loader) {+ const id = loader.locate(ctx.fiber)+ if (!id || [3, 4, 5].includes(ctx.fiber.state)) fail('UNAVAILABLE', 'An active plugin instance is required')+ let controller = lifetimes.get(ctx.fiber)+ if (!controller || controller.signal.aborted) {+ controller = new AbortController()+ lifetimes.set(ctx.fiber, controller)+ ctx.effect(() => () => controller.abort(new RuntimeError('CANCELLED', 'The Cordis plugin scope was disposed')), 'Host requests')+ }+ return { id, signal: controller.signal }+}++export class HostService extends Service {+ constructor(ctx, runtime) { super(ctx, 'host'); this.runtime = runtime }++ async invoke(ctx, service, method, input = {}, { signal, call } = {}) {+ const owner = ownerOf(ctx, this.runtime.root.loader)+ if (call && !call[invocation]) fail('INVALID_ARGUMENT', 'A live tool invocation is required')+ assertJSON(input)+ const current = callbackContext.getStore()+ const signals = [owner.signal, signal, current?.signal].filter(Boolean)+ // Human decisions have their own Go lifecycle, not a management deadline.+ const waitingForUser = service === 'approvals' || service === 'questions' ||+ service === 'authorization' && (method === 'prompt' || method === 'waitCallback')+ return this.runtime.call('host.invoke', {+ owner: owner.id, service, method, input,+ invocation: call?.[invocation], mutation: current?.mutation, discovery: current?.discovery,+ }, waitingForUser ? AbortSignal.any(signals) : managementSignal(...signals))+ }++ info() { return this.invoke(this.ctx, 'info', 'get') }++ get tools() {+ const ctx = this.ctx+ return {+ register: definition => {+ if (typeof definition?.execute !== 'function') fail('INVALID_ARGUMENT', 'A tool needs execute(args, call)')+ const { execute, ...descriptor } = definition+ return this.register(ctx, 'tool', descriptor, { execute })+ },+ }+ }++ get skills() {+ const ctx = this.ctx+ return {+ register: skill => this.register(ctx, 'skill', skill),+ registerDirectory: async path => this.register(ctx, 'skill-directory', { path: await this.runtime.skillDirectory(ctx, path) }),+ registerProvider: provider => {+ if (typeof provider?.list !== 'function' || typeof provider?.get !== 'function') fail('INVALID_ARGUMENT', 'A Skill provider needs list and get')+ return this.register(ctx, 'skill-provider', { id: provider.id }, { list: provider.list, get: provider.get })+ },+ list: (options = {}) => this.invoke(ctx, 'skills', 'list', options),+ get: (name, options = {}) => this.invoke(ctx, 'skills', 'get', { ...options, name }),+ invalidate: () => this.invoke(ctx, 'skills', 'invalidate'),+ }+ }++ get prompts() {+ const ctx = this.ctx+ return { register: definition => {+ const { text, ...descriptor } = definition+ if (typeof text !== 'string' && typeof text !== 'function') fail('INVALID_ARGUMENT', 'A prompt needs text')+ return this.register(ctx, 'prompt', typeof text === 'string' ? { ...descriptor, text } : descriptor,+ typeof text === 'function' ? { text } : {})+ } }+ }++ get credentials() {+ const ctx = this.ctx+ const request = (method, input) => this.invoke(ctx, 'credentials', method, input)+ return {+ get: key => request('get', { key }), put: (key, record) => request('put', { key, record }),+ remove: key => request('remove', { key }), describe: key => request('describe', { key }),+ list: () => request('list', {}), resolve: ref => request('resolve', { ref }),+ update: async (key, mutate) => {+ if (typeof mutate !== 'function') fail('INVALID_ARGUMENT', 'A credential update needs a callback')+ const callback = this.runtime.remember(ctx, { mutate })+ try { return await request('update', { key, callback }) }+ finally { this.runtime.forget(callback) }+ },+ }+ }++ get authorization() {+ const ctx = this.ctx+ return {+ register: flow => {+ if (typeof flow?.run !== 'function') fail('INVALID_ARGUMENT', 'An authorization flow needs run(session)')+ const { run, inspect, disconnect, title, ...descriptor } = flow+ const optional = {}+ if (inspect && typeof inspect !== 'function' || disconnect && typeof disconnect !== 'function') fail('INVALID_ARGUMENT', 'Authorization inspect and disconnect must be callbacks')+ if (inspect) optional.inspect = (_, context) => inspect({ signal: context.signal })+ if (disconnect) optional.disconnect = async (_, context) => { await disconnect({ signal: context.signal }); return null }+ return this.register(ctx, 'authorization', { ...descriptor, title }, { ...optional, run: async (input, context) => {+ const request = (method, data) => this.invoke(ctx, 'authorization', method,+ { id: input.id, ...data }, { signal: context.signal })+ return run(Object.freeze({+ method: input.method, signal: context.signal,+ notify: notice => request('notify', { notice }),+ prompt: prompt => request('prompt', { prompt }),+ callback: async ({ state }) => {+ const url = await request('callback', { state })+ return Object.freeze({ url, wait: () => request('waitCallback', {}) })+ },+ commit: record => request('commit', { record }),+ }))+ } })+ },+ list: () => this.invoke(ctx, 'authorization', 'list'),+ cancel: key => this.invoke(ctx, 'authorization', 'cancel', { key }),+ }+ }++ get mcp() {+ const ctx = this.ctx+ const request = (method, input = {}) => this.invoke(ctx, 'mcp', method, input)+ return {+ register: definition => this.register(ctx, 'mcp', definition),+ list: () => request('list'), inspect: name => request('inspect', { name }),+ restart: name => request('restart', { name }), authorize: name => request('authorize', { name }),+ cancelAuthorization: (name, attemptId) => request('cancelAuthorization', { name, attemptId }),+ signOut: name => request('signOut', { name }),+ }+ }++ get approvals() {+ const ctx = this.ctx+ return { request: (call, request) => this.invoke(ctx, 'approvals', 'request', request, { call, signal: call.signal }) }+ }++ get questions() {+ const ctx = this.ctx+ return { ask: (call, request) => this.invoke(ctx, 'questions', 'ask', request, { call, signal: call.signal }) }+ }++ async register(ctx, kind, descriptor, functions = {}) {+ const owner = ownerOf(ctx, this.runtime.root.loader)+ assertJSON(descriptor)+ const id = this.runtime.remember(ctx, functions)+ let registrationId, closed = false, cleanup+ const dispose = () => cleanup ??= (async () => {+ closed = true+ try {+ if (registrationId && !this.runtime.closed) await this.runtime.call('contribution.remove', { owner: owner.id, registrationId }, managementSignal())+ } finally { this.runtime.forget(id) }+ })()+ ctx.effect(() => dispose, `ctx.host.${kind} registration`)+ try {+ const signal = managementSignal(owner.signal)+ const registered = await this.runtime.call('contribution.register', { owner: owner.id, callbackId: id, kind,+ descriptor, callbacks: Object.keys(functions) }, signal, { drain: true })+ if (typeof registered?.id !== 'string' || !registered.id) fail('INVALID_RESULT', 'Host registration has no id')+ registrationId = registered.id+ if (closed || signal.aborted) {+ await this.runtime.call('contribution.remove', { owner: owner.id, registrationId }, managementSignal())+ fail('CANCELLED', 'The plugin closed during registration')+ }+ return Object.freeze({ id: registrationId, dispose })+ } catch (error) { this.runtime.forget(id); throw error }+ }+}++export function invocationContext(context, signal) {+ const { invocation: token, mutation: _, discovery: __, ...view } = context ?? {}+ return Object.freeze({ ...view, signal, ...(token ? { [invocation]: token } : {}) })+}++export async function runCallback(entry, params, signal) {+ const callback = entry.functions[params.method]+ if (!callback) fail('NOT_FOUND', 'Plugin callback is unavailable')+ const combined = AbortSignal.any([signal, entry.owner.signal])+ combined.throwIfAborted()+ const context = invocationContext(params.context, combined)+ return callbackContext.run({ mutation: params.context?.mutation, discovery: params.context?.discovery, signal: combined }, async () => {+ if (params.method === 'text' || params.method === 'list') return callback(Object.freeze({ ...params.args, signal: combined }))+ if (params.method === 'get') return callback(params.args.key, Object.freeze({ ...params.args.context, signal: combined }))+ return callback(params.args, context)+ })+}diff --git a/extensions/cordis/src/host-runtime.mjs b/extensions/cordis/src/host-runtime.mjsnew file mode 100644index 0000000..b0bfe60--- /dev/null+++ b/extensions/cordis/src/host-runtime.mjs@@ -0,0 +1,142 @@+import { Context } from '@deepseek-ai/cordis'+import Loader from '@deepseek-ai/cordis-plugin-loader'+import { pathToFileURL } from 'node:url'+import { isAbsolute, join, relative, resolve } from 'node:path'+import { realpath, stat } from 'node:fs/promises'+import { randomUUID } from 'node:crypto'+import { HostService, assertJSON, ownerOf, runCallback } from './host-plugin.mjs'+import { readManifest } from './manifest.mjs'+import { RuntimeError } from './errors.mjs'++const hostEvents = new Set(['host/skills-changed', 'host/credential-changed', 'host/authorization-changed', 'host/mcp-changed', 'host/stopping'])+const states = ['pending', 'loading', 'ready', 'failed', 'disposed', 'stopping']+const instanceName = /^[a-z][a-z0-9-]{0,23}$/+const builtinPrefix = 'cordis:go-bot:'++// Cordis owns entries, dependencies, fibers and disposal. The adapter only+// resolves packages and translates calls; it does not own another plugin tree.+export class HostRuntime {+ constructor({ directory, call, loadPackage, onLog = () => {} }) {+ this.directory = directory+ this.call = call+ this.loadPackage = loadPackage ?? (async name => {+ const value = await readManifest(directory, name)+ return { ...value, module: await import(pathToFileURL(value.entry).href) }+ })+ this.onLog = onLog+ this.root = new Context()+ this.callbacks = new Map()+ this.failures = new Map()+ this.closed = false+ }++ static async create(options) {+ const runtime = new HostRuntime(options)+ runtime.root.logger.exporter({ export: options.onLog ?? (() => {}) })+ await runtime.root.plugin(Loader, { baseUrl: pathToFileURL(join(options.directory, 'package.json')).href })+ await runtime.root.plugin({ name: 'go-bot-host-bridge', apply(ctx) { new HostService(ctx, runtime) } })+ return runtime+ }++ remember(ctx, functions) {+ const owner = ownerOf(ctx, this.root.loader)+ if (this.closed) throw new RuntimeError('UNAVAILABLE', 'Plugin runtime is closed')+ const id = randomUUID(), controller = new AbortController()+ this.callbacks.set(id, { ctx, owner, functions, controller })+ ctx.effect(() => () => this.forget(id), 'Host callback lifetime')+ return id+ }++ forget(id) {+ const entry = this.callbacks.get(id)+ if (!entry) return+ this.callbacks.delete(id)+ entry.controller.abort(new RuntimeError('CANCELLED', 'Plugin registration was disposed'))+ }++ async invoke(params, signal) {+ const entry = this.callbacks.get(params.callbackId)+ if (!entry || entry.owner.signal.aborted || (params.owner && params.owner !== entry.owner.id)) throw new RuntimeError('UNAVAILABLE', 'Plugin callback is no longer available')+ const returned = await runCallback(entry, params, AbortSignal.any([signal, entry.controller.signal]))+ const result = returned === undefined && params.method === 'run' ? null : returned+ try { assertJSON(result) }+ catch (error) { throw new RuntimeError('INVALID_RESULT', error.message) }+ return result+ }++ async skillDirectory(ctx, path) {+ if (typeof path !== 'string' || !path) throw new RuntimeError('INVALID_ARGUMENT', 'A Skill directory is required')+ const owner = ownerOf(ctx, this.root.loader)+ const entry = [...this.root.loader.entries()].find(entry => entry.id === owner.id)+ const { root } = await this.loadPackage(entry.options.name.slice(builtinPrefix.length))+ const directory = await realpath(resolve(root, path)), local = relative(root, directory)+ if (local === '..' || local.startsWith('../') || isAbsolute(local) || !(await stat(directory)).isDirectory()) {+ throw new RuntimeError('INVALID_ARGUMENT', 'A Skill directory must be inside the installed package')+ }+ owner.signal.throwIfAborted()+ return directory+ }++ async apply(settings) {+ if (this.closed) throw new RuntimeError('UNAVAILABLE', 'Plugin runtime has closed')+ if (this.applying) throw new RuntimeError('CONFLICT', 'A plugin configuration is already being applied')+ this.applying = true+ try {+ const rows = settings.instances ?? [], ids = new Set(), desired = []+ this.failures.clear()+ for (const row of rows) {+ if (!instanceName.test(row.id) || ids.has(row.id)) throw new RuntimeError('INVALID_ARGUMENT', 'Invalid or duplicate plugin instance id')+ ids.add(row.id)+ const name = builtinPrefix + row.package+ if (row.enabled) {+ try { this.root.loader.builtins[name.slice(7)] = (await this.loadPackage(row.package)).module }+ catch (error) { this.failures.set(row.id, { package: row.package, error: String(error?.message ?? error) }); continue }+ }+ desired.push({ id: row.id, name, disabled: !row.enabled, config: row.config ?? {} })+ }+ const loader = this.root.loader+ const previous = [...loader.entries()].map(entry => entry.fiber).filter(Boolean)+ await loader.root.update(desired)+ await loader.await()+ // Removed entries no longer appear in Loader.await(). Join Cordis's+ // actual cleanup promise rather than tracking our own disposal states.+ await Promise.all(previous.map(fiber => fiber.inertia))+ for (const entry of loader.entries()) {+ try { await entry.fiber?.await() }+ catch (error) { this.failures.set(entry.id, { package: entry.options.name.slice(builtinPrefix.length), error: String(error?.message ?? error) }) }+ }+ return { instances: this.inspect(), warnings: [] }+ } finally { this.applying = false }+ }++ inspect() {+ const result = [...this.root.loader.entries()].map(entry => ({+ id: entry.id, package: entry.options.name.slice(builtinPrefix.length), name: entry.options.name.slice(builtinPrefix.length),+ state: entry.disabled ? 'disabled' : states[entry.fiber?.state] ?? 'failed',+ }))+ for (const [id, failure] of this.failures) {+ const existing = result.find(row => row.id === id)+ if (existing) Object.assign(existing, { state: 'failed', error: failure.error })+ else result.push({ id, package: failure.package, name: failure.package, state: 'failed', error: failure.error })+ }+ return result+ }++ notify(name, data) {+ if (!hostEvents.has(name) || this.closed) return+ const value = Object.freeze(structuredClone(data))+ for (const callback of this.root.events.dispatch('emit', [name, value])) {+ try { Promise.resolve(callback(value)).catch(error => this.onLog({ type: 'warn', args: [name, String(error?.message ?? error)] })) }+ catch (error) { this.onLog({ type: 'warn', args: [name, String(error?.message ?? error)] }) }+ }+ }++ async close() {+ if (this.closing) return this.closing+ this.closing = (async () => {+ await this.root.fiber.dispose()+ this.closed = true+ })()+ return this.closing+ }+}diff --git a/extensions/cordis/src/main.mjs b/extensions/cordis/src/main.mjsnew file mode 100644index 0000000..486c049--- /dev/null+++ b/extensions/cordis/src/main.mjs@@ -0,0 +1,38 @@+import { connect } from 'node:net'+import { HostRuntime } from './host-runtime.mjs'+import { MAX_FRAME, Peer } from './rpc.mjs'+import { RuntimeError } from './errors.mjs'++const path = process.argv[2]+if (!path || process.argv[3]) throw new Error('One private Host Unix socket path is required')+const socket = connect(path)+let runtime+const peer = new Peer(socket, async (method, params, signal) => {+ const active = await ready+ switch (method) {+ case 'runtime.apply': return active.apply(params)+ case 'runtime.inspect': return active.inspect()+ case 'callback.invoke': return active.invoke(params, signal)+ case 'host.event': active.notify(params.name, params.data); return null+ case 'runtime.shutdown': active.notify('host/stopping', { reason: 'Host is stopping' }); await active.close(); return null+ default: throw new RuntimeError('NOT_FOUND', 'Unknown plugin runtime method')+ }+})++const ready = (async () => {+ const initialized = await peer.call('bridge.initialize', { protocol: 1, api: '1' })+ const services = ['info', 'tools', 'skills', 'prompts', 'credentials', 'authorization', 'mcp', 'approvals', 'questions']+ if (initialized?.protocol !== 1 || initialized?.api !== '1' || initialized.maxFrameBytes !== MAX_FRAME ||+ !Array.isArray(initialized.capabilities) || services.some(name => !initialized.capabilities.includes(name))) {+ throw new RuntimeError('INCOMPATIBLE_PLUGIN', 'Unsupported Host protocol or capabilities')+ }+ runtime = await HostRuntime.create({ directory: initialized.directory,+ call: (method, input, signal, options) => peer.call(method, input, signal, options),+ onLog: record => peer.notify('runtime.log', { level: record.type, message: record.args.map(String).join(' ') }).catch(() => {}),+ })+ return runtime+})()+ready.catch(() => peer.close())+socket.once('close', () => { void runtime?.close().catch(() => {}) })+process.once('SIGTERM', () => peer.close())+process.once('SIGINT', () => peer.close())diff --git a/extensions/cordis/src/manifest.mjs b/extensions/cordis/src/manifest.mjsnew file mode 100644index 0000000..7b0895c--- /dev/null+++ b/extensions/cordis/src/manifest.mjs@@ -0,0 +1,19 @@+import { readFile, realpath } from 'node:fs/promises'+import { isAbsolute, join, relative, resolve } from 'node:path'+import { RuntimeError } from './errors.mjs'++export const packageName = /^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/++export async function readManifest(directory, name, { checkCompatibility = true } = {}) {+ if (!packageName.test(name) || name.length > 214) throw new RuntimeError('INVALID_PACKAGE', 'Invalid package name')+ const root = await realpath(join(directory, 'node_modules', name))+ const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'))+ if (manifest.name !== name) throw new RuntimeError('INVALID_PACKAGE', 'Installed package name does not match')+ if (checkCompatibility && manifest.goBot?.api !== '1') throw new RuntimeError('INCOMPATIBLE_PLUGIN', 'A plugin must declare goBot.api "1"')+ const exports = manifest.exports?.['.'] ?? manifest.exports+ const target = typeof exports === 'string' ? exports : exports?.import ?? exports?.default ?? manifest.main ?? './index.js'+ if (typeof target !== 'string' || isAbsolute(target)) throw new RuntimeError('INVALID_PACKAGE', 'A JavaScript module entry is required')+ const entry = resolve(root, target), local = relative(root, entry)+ if (!local || local.startsWith('../') || isAbsolute(local)) throw new RuntimeError('INVALID_PACKAGE', 'The module entry must be inside its package')+ return { root, manifest, entry }+}diff --git a/extensions/cordis/src/package-main.mjs b/extensions/cordis/src/package-main.mjsnew file mode 100644index 0000000..11feaf7--- /dev/null+++ b/extensions/cordis/src/package-main.mjs@@ -0,0 +1,23 @@+import { Packages } from './packages.mjs'+import { RuntimeError } from './errors.mjs'++let data=''+try{+ for await(const chunk of process.stdin){data+=chunk;if(data.length>4<<20)throw new RuntimeError('INPUT_LIMIT','Package request exceeds 4 MiB')}+ const request=JSON.parse(data)+ const manager=new Packages({directory:request.directory,pnpm:request.pnpm,credentials:request.credentials})+ let result+ switch(request.method){+ case 'inspect':result=await manager.inspect(request.name,request.source);break+ case 'install':result=await manager.install(request.name,request.source,{builds:request.builds??[]});break+ case 'remove':result=await manager.remove(request.name);break+ case 'list':result=await manager.installed();break+ default:throw new RuntimeError('METHOD_NOT_FOUND','Unknown package operation')+ }+ process.stdout.write(JSON.stringify({result})+'\n')+}catch(error){+ let message=String(error?.message??error)+ try{for(const secret of Object.values(JSON.parse(data).credentials??{}))if(secret)message=message.replaceAll(secret,'[redacted]')}catch{}+ process.stdout.write(JSON.stringify({error:{code:typeof error?.code==='string'?error.code:'PACKAGE_ERROR',message:message.slice(0,6000)}})+'\n')+ process.exitCode=1+}diff --git a/extensions/cordis/src/packages.mjs b/extensions/cordis/src/packages.mjsnew file mode 100644index 0000000..1c71757--- /dev/null+++ b/extensions/cordis/src/packages.mjs@@ -0,0 +1,253 @@+import { spawn } from 'node:child_process'+import { mkdir, mkdtemp, readFile, writeFile, rm, realpath, rename } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { fileURLToPath } from 'node:url'+import { isAbsolute, join, relative } from 'node:path'+import semver from 'semver'+import { packageName, readManifest } from './manifest.mjs'+import { RuntimeError } from './errors.mjs'+++const hostSDKName = '@go-bot/plugin-sdk'+const hostSDKPath = fileURLToPath(new URL('../../sdk/', import.meta.url))+const MAX_OUTPUT = 1 << 20+const allowedEnv = ['PATH','HOME','LANG','LC_ALL','TMPDIR','HTTP_PROXY','HTTPS_PROXY','NO_PROXY','http_proxy','https_proxy','no_proxy','SSL_CERT_FILE','SSL_CERT_DIR','NODE_EXTRA_CA_CERTS']+export function baseEnvironment() {+ return Object.fromEntries(allowedEnv.filter(name => process.env[name] !== undefined).map(name => [name,process.env[name]]))+}++// No shell, no user-supplied pnpm options, and no package-manager startup hooks.+// Output stays bounded and errors are redacted before leaving this process.+async function command(binary,args,{directory,environment={},signal,secrets=[]}={}) {+ return new Promise((accept,reject) => {+ const child=spawn(binary,args,{cwd:directory,env:{...baseEnvironment(),...environment},stdio:['ignore','pipe','pipe'],signal,killSignal:'SIGTERM'})+ const chunks=[];let length=0;let overflow=false+ const collect=chunk=>{length+=chunk.length;if(length>MAX_OUTPUT){overflow=true;child.kill('SIGKILL')}else chunks.push(chunk)}+ child.stdout.on('data',collect);child.stderr.on('data',collect)+ child.once('error',reject)+ child.once('close',code=>{+ let output=Buffer.concat(chunks).toString('utf8')+ for(const secret of secrets)if(secret)output=output.replaceAll(secret,'[redacted]')+ if(overflow)return reject(new RuntimeError('PACKAGE_OUTPUT_LIMIT','Package manager output exceeds 1 MiB'))+ if(code!==0)return reject(new RuntimeError('PACKAGE_COMMAND_FAILED',output.trim().slice(-6000)||`Package manager exited with code ${code}`))+ accept(output)+ })+ })+}++function safeURL(value,protocols=['https:']) {+ let url+ try{url=new URL(value)}catch{throw new RuntimeError('INVALID_SOURCE','Source URL is invalid')}+ if(!protocols.includes(url.protocol)||url.password||url.search||url.hash||(url.protocol!=='ssh:'&&url.username))throw new RuntimeError('INVALID_SOURCE','Source URLs cannot contain passwords, query strings or fragments')+ return url+}++export function validateSource(name,source,{fixed=false}={}) {+ if(!packageName.test(name)||name.length>214||!source||typeof source.spec!=='string'||source.spec.length>4096||/[\0\r\n]/.test(source.spec))throw new RuntimeError('INVALID_SOURCE','Enter a valid package name and source')+ if(source.registry)safeURL(source.registry,['http:','https:'])+ if(source.authRef && (typeof source.authRef!=='string'||source.authRef.length>256||/[\0\r\n]/.test(source.authRef)))throw new RuntimeError('INVALID_SOURCE','Invalid credential reference')+ switch(source.type){+ case 'registry':{+ if(source.spec!==name&&!source.spec.startsWith(name+'@'))throw new RuntimeError('INVALID_SOURCE','Registry source must name the selected package')+ if(fixed&&!semver.valid(source.spec.slice(name.length+1)))throw new RuntimeError('UNPINNED_SOURCE','Registry packages must use an exact version')+ if(source.spec!==name&&!source.spec.slice(name.length+1))throw new RuntimeError('INVALID_SOURCE','A version or tag is required after @')+ break+ }+ case 'bundled':+ if (!/^[a-z][a-z0-9-]{0,23}$/.test(source.spec)) throw new RuntimeError('INVALID_SOURCE', 'Invalid bundled plugin ID')+ break+ case 'directory':+ if(!isAbsolute(source.spec))throw new RuntimeError('INVALID_SOURCE','A development directory must be an absolute Host path')+ break+ case 'tarball':+ if(!isAbsolute(source.spec))safeURL(source.spec)+ break+ case 'git':{+ const split=source.spec.lastIndexOf('#')+ if(split<0)throw new RuntimeError('UNPINNED_SOURCE','Git sources require a commit or ref after #')+ const repository=source.spec.slice(0,split).replace(/^git\+/,'')+ safeURL(repository,['https:','ssh:'])+ gitPackageRef(source.spec.slice(split+1), fixed)+ break+ }+ default:throw new RuntimeError('INVALID_SOURCE','Unsupported package source type')+ }+}++function packageDirectory(source) {+ return source.type === 'bundled' ? fileURLToPath(new URL(`../../plugins/${source.spec}/`, import.meta.url)) : source.spec+}++async function atomic(path,value) {+ const temporary=path+'.writing'+ await writeFile(temporary,value,{mode:0o600})+ await rename(temporary,path)+}++async function manifest(directory) {+ try{return JSON.parse(await readFile(join(directory,'package.json'),'utf8'))}+ catch(error){if(error.code!=='ENOENT')throw error;return {name:'go-bot-host-profile',private:true,type:'module',dependencies:{}}}+}++function information(name,source,manifest) {+ if(manifest.goBot?.api!=='1')throw new RuntimeError('INCOMPATIBLE_PLUGIN','A plugin must declare goBot.api "1"')+ return {name,version:manifest.version??'',description:manifest.description??'',license:typeof manifest.license==='string'?manifest.license:'',+ source,api:manifest.goBot?.api??'',title:manifest.goBot?.title??'',configSchema:manifest.goBot?.configSchema}+}++export class Packages {+ constructor({directory,pnpm='pnpm',credentials={},signal}={}){this.directory=directory;this.pnpm=pnpm;this.credentials=credentials;this.signal=signal}++ async #authentication(source,run){+ const secret=source.authRef?this.credentials[source.authRef]:undefined+ if(source.authRef&&!secret)throw new RuntimeError('CREDENTIAL_REQUIRED',`Missing installation credential: ${source.authRef}`)+ if(secret && /[\r\n\0]/.test(secret))throw new RuntimeError('INVALID_CREDENTIAL','Installation credentials cannot contain control characters')+ const directory=await mkdtemp(join(tmpdir(),'go-bot-install-'))+ try{+ const environment={CI:'true',NPM_CONFIG_USERCONFIG:join(directory,'npmrc'),NPM_CONFIG_GLOBALCONFIG:join(directory,'globalrc')}+ await writeFile(environment.NPM_CONFIG_GLOBALCONFIG,'',{mode:0o600})+ let npmrc=''+ if(source.type==='registry'){+ const registry=source.registry||'https://registry.npmjs.org/'+ const url=safeURL(registry,['http:','https:'])+ if(!url.pathname.endsWith('/'))url.pathname+='/'+ npmrc=`registry=${url.href}\n`+ if(secret)npmrc+=`//${url.host}${url.pathname}:_authToken=${secret}\n`+ }+ await writeFile(environment.NPM_CONFIG_USERCONFIG,npmrc,{mode:0o600})+ if(source.type==='git'&&secret){+ const base=source.spec.slice(0,source.spec.lastIndexOf('#')).replace(/^git\+/,'')+ const url=safeURL(base,['https:','ssh:'])+ if(url.protocol!=='https:')throw new RuntimeError('INVALID_CREDENTIAL','Token authentication is only supported for HTTPS Git sources')+ const username=source.username||'git'+ if(/[\r\n\0:]/.test(username))throw new RuntimeError('INVALID_CREDENTIAL','Invalid Git username')+ environment.GIT_CONFIG_COUNT='1'+ environment.GIT_CONFIG_KEY_0=`http.${url.href}.extraHeader`+ environment.GIT_CONFIG_VALUE_0=`Authorization: Basic ${Buffer.from(username+':'+secret).toString('base64')}`+ environment.GIT_TERMINAL_PROMPT='0'+ }+ return await run(environment,secret?[secret,environment.GIT_CONFIG_VALUE_0].filter(Boolean):[])+ }finally{await rm(directory,{recursive:true,force:true})}+ }++ async #run(args,source,directory=this.directory){+ return this.#authentication(source,(environment,secrets)=>command(this.pnpm,args,{directory,environment,secrets,signal:this.signal}))+ }++ async resolve(name,source){+ validateSource(name,source)+ if(source.type==='registry'){+ const text=await this.#run(['view',source.spec,'version','--json'],source)+ const versions=JSON.parse(text)+ const version=typeof versions==='string'?versions:Array.isArray(versions)?versions.filter(v=>semver.valid(v)).sort(semver.rcompare)[0]:undefined+ if(!semver.valid(version))throw new RuntimeError('PACKAGE_NOT_FOUND','Package version could not be resolved')+ return {...source,spec:name+'@'+version,registry:source.registry||'https://registry.npmjs.org/'}+ }+ if(source.type==='git'){+ const split=source.spec.lastIndexOf('#')+ const base=source.spec.slice(0,split)+ let {ref,suffix}=gitPackageRef(source.spec.slice(split+1))+ if(!/^[a-f0-9]{40}$/i.test(ref)){+ const text=await this.#authentication(source,(environment,secrets)=>command('git',['ls-remote','--exit-code',base.replace(/^git\+/,''),ref,ref+'^{}'],{directory:this.directory,environment,secrets,signal:this.signal}))+ ref=text.trim().split('\n').at(-1)?.split(/\s/)[0]+ if(!/^[a-f0-9]{40}$/i.test(ref))throw new RuntimeError('PACKAGE_NOT_FOUND','Git ref could not be resolved to a commit')+ }+ return {...source,spec:base+'#'+ref.toLowerCase()+suffix}+ }+ return {...source,spec:source.type==='directory'?await realpath(source.spec):source.spec}+ }++ async inspect(name,source){+ const resolved=await this.resolve(name,source)+ if(resolved.type==='registry'){+ const metadata=JSON.parse(await this.#run(['view',resolved.spec,'--json'],resolved))+ if(metadata.name!==name)throw new RuntimeError('INVALID_PACKAGE','Package metadata name does not match')+ return information(name,resolved,metadata)+ }+ if(resolved.type==='directory'||resolved.type==='bundled'){+ const metadata=JSON.parse(await readFile(join(packageDirectory(resolved),'package.json'),'utf8'))+ if(metadata.name!==name)throw new RuntimeError('INVALID_PACKAGE','Directory package name does not match')+ return information(name,resolved,metadata)+ }+ const directory=await mkdtemp(join(tmpdir(),'go-bot-inspect-'))+ try{return await new Packages({directory,pnpm:this.pnpm,credentials:this.credentials,signal:this.signal}).install(name,resolved,{scripts:false})}+ finally{await rm(directory,{recursive:true,force:true})}+ }++ async install(name,source,{scripts=true,builds=[]}={}){+ validateSource(name,source,{fixed:true})+ if(name===hostSDKName)throw new RuntimeError('INVALID_PACKAGE','The Host supplies its own plugin SDK')+ await mkdir(this.directory,{recursive:true,mode:0o700})+ const prior=await manifest(this.directory)+ prior.private=true;prior.type='module';prior.scripts={}+ // The SDK is shipped with the Host, not fetched from an unpublished npm+ // name. Root and transitive imports resolve the same supported API.+ const sdkSpec='file:'+hostSDKPath+ prior.dependencies={...(prior.dependencies??{}),[hostSDKName]:sdkSpec}+ prior.pnpm={...(prior.pnpm??{}),overrides:{...(prior.pnpm?.overrides??{}),[hostSDKName]:sdkSpec}}++ await atomic(join(this.directory,'package.json'),JSON.stringify(prior,null,2)+'\n')+ const previous=prior.goBotSources?.[name]+ if(prior.dependencies?.[name] && (source.type==='directory'||source.type==='bundled'||previous?.type!==source.type||previous?.spec!==source.spec||previous?.registry!==source.registry)){+ // pnpm may retain the old file dependency resolution while updating its+ // specifier. Remove that importer's old edge before resolving a new one.+ await this.#run(['--config.ignore-scripts=true','--config.ignore-pnpmfile=true','remove','--reporter=silent','--',name],source)+ }+ const local = source.type==='directory'||source.type==='bundled'+ const spec=source.type==='registry'?source.spec:local?name+'@file:'+packageDirectory(source):name+'@'+source.spec+ if (scripts) {+ // Use pnpm's native per-resolution script policy. The reviewed catalog+ // supplies build permissions; public clients cannot grant them.+ const text = await this.#run(['config','get','allowBuilds','--json'], source)+ const existing = text.trim() && text.trim() !== 'undefined' ? JSON.parse(text) : {}+ const allowBuilds = Object.fromEntries(Object.entries(existing ?? {}).filter(([, value]) => typeof value === 'boolean'))+ for (const build of builds) {+ if (build === name) {+ if (local) allowBuilds[name+'@file:'+relative(await realpath(this.directory),packageDirectory(source))] = true+ else if (source.type === 'registry') allowBuilds[source.spec] = true+ else throw new RuntimeError('BUILD_NOT_APPROVED', 'Archive/Git script approvals require a reviewed exact pnpm resolution')+ } else {+ const split = build.lastIndexOf('@')+ if (split <= 0 || !packageName.test(build.slice(0,split)) || !semver.valid(build.slice(split+1))) throw new RuntimeError('BUILD_NOT_APPROVED','Dependency build permissions require exact package versions')+ allowBuilds[build] = true+ }+ }+ await atomic(join(this.directory,'pnpm-workspace.yaml'), JSON.stringify({packages:['.'],autoInstallPeers:false,strictDepBuilds:true,sideEffectsCache:false,allowBuilds},null,2)+'\n')+ }+ await this.#run(['add','--save-exact','--ignore-pnpmfile',...scripts?[]:['--ignore-scripts'],'--reporter=append-only','--',spec],source)+ const {manifest:installed}=await readManifest(this.directory,name,{checkCompatibility:true})+ const updated=await manifest(this.directory)+ updated.goBotSources={...(updated.goBotSources??{}),[name]:source}+ await atomic(join(this.directory,'package.json'),JSON.stringify(updated,null,2)+'\n')+ return {...information(name,source,installed),present:true}+ }++ async remove(name){+ if(!packageName.test(name)||name===hostSDKName)throw new RuntimeError('INVALID_PACKAGE','Invalid plugin package name')+ await this.#run(['--config.ignore-scripts=true','--config.ignore-pnpmfile=true','remove','--reporter=silent','--',name],{type:'registry',spec:name})+ return {name,removed:true}+ }++ async installed(){+ const data=await manifest(this.directory)+ const packages=[]+ for(const [name,spec]of Object.entries(data.dependencies??{})){+ if(name===hostSDKName)continue+ try{const {manifest:m}=await readManifest(this.directory,name,{checkCompatibility:true});packages.push({...information(name,data.goBotSources?.[name]??{type:'installed',spec},m),present:true})}+ catch{packages.push({name,present:false})}+ }+ return packages+ }++}++const pathSegment = /^[A-Za-z0-9._@+-]+$/+export function gitPackageRef(value, fixed = false) {+ const parts = value.split('&path:/')+ if (parts.length > 2 || !parts[0] || /[\s\0&]/.test(parts[0]) || parts[0].startsWith('-') ||+ (parts[1] !== undefined && parts[1].split('/').some(part => !pathSegment.test(part) || part === '.' || part === '..'))) {+ throw new RuntimeError('INVALID_SOURCE', 'Invalid Git ref or package directory')+ }+ if (fixed && !/^[a-f0-9]{40}$/i.test(parts[0])) throw new RuntimeError('UNPINNED_SOURCE', 'Git sources must use a full commit')+ return { ref: parts[0], suffix: parts.length === 2 ? '&path:/' + parts[1] : '' }+}diff --git a/extensions/cordis/src/rpc.mjs b/extensions/cordis/src/rpc.mjsnew file mode 100644index 0000000..73325cc--- /dev/null+++ b/extensions/cordis/src/rpc.mjs@@ -0,0 +1,124 @@+import { RuntimeError } from './errors.mjs'++export const MAX_FRAME = 1 << 20+const classifiedRemoteErrors = new WeakSet()++export class Peer {+ #buffer = Buffer.alloc(0)+ #pending = new Map()+ #active = new Map()+ #sequence = 0+ #closed = false++ constructor(socket, handler) {+ this.socket = socket+ this.handler = handler+ socket.on('data', chunk => this.#read(chunk))+ socket.on('close', () => this.close())+ socket.on('error', error => this.close(error))+ }++ async call(method, params, signal, { drain = false } = {}) {+ if (this.#closed) throw new Error('Host connection closed')+ signal?.throwIfAborted()+ const id = `n${++this.#sequence}`+ return new Promise((resolve, reject) => {+ let drainTimer+ const cancel = () => {+ this.#send({ jsonrpc: '2.0', method: 'request.cancel', params: { id } }).catch(() => {})+ if(drain){+ drainTimer=setTimeout(()=>this.close(new Error('Go capability did not settle after cancellation')),6000)+ return+ }+ this.#pending.get(id)?.cleanup()+ this.#pending.delete(id)+ signal?.removeEventListener('abort', cancel)+ reject(signal.reason)+ }+ this.#pending.set(id, { resolve, reject, cleanup: () => {signal?.removeEventListener('abort', cancel);clearTimeout(drainTimer)} })+ signal?.addEventListener('abort', cancel, { once: true })+ this.#send({ jsonrpc: '2.0', id, method, params }).catch(error => {+ const pending = this.#pending.get(id)+ if (pending) { this.#pending.delete(id); pending.cleanup(); reject(error) }+ })+ })+ }++ notify(method, params) { return this.#send({ jsonrpc: '2.0', method, params }) }++ async #send(message) {+ if (this.#closed) throw new Error('Host connection closed')+ const bytes = Buffer.from(JSON.stringify(message) + '\n')+ if (bytes.length > MAX_FRAME) throw new Error('Extension frame exceeds 1 MiB')+ await new Promise((resolve, reject) => this.socket.write(bytes, error => error ? reject(error) : resolve()))+ }++ #read(chunk) {+ this.#buffer = Buffer.concat([this.#buffer, chunk])+ while (true) {+ const end = this.#buffer.indexOf(10)+ if (end < 0) break+ if (end + 1 > MAX_FRAME) return this.close(new Error('Extension frame exceeds 1 MiB'))+ const frame = this.#buffer.subarray(0, end)+ this.#buffer = this.#buffer.subarray(end + 1)+ let message+ try { message = JSON.parse(frame.toString('utf8')) } catch { return this.close(new Error('Invalid extension JSON')) }+ if (!message || message.jsonrpc !== '2.0') return this.close(new Error('Invalid extension RPC envelope'))+ this.#dispatch(message)+ }+ if (this.#buffer.length >= MAX_FRAME) this.close(new Error('Extension frame exceeds 1 MiB'))+ }++ #dispatch(message) {+ if (!message.method) {+ if (typeof message.id !== 'string' ||+ Object.hasOwn(message, 'result') === Object.hasOwn(message, 'error')) {+ this.close(new RuntimeError('INVALID_RESULT', 'Invalid JSON-RPC response'))+ return+ }+ const pending = this.#pending.get(message.id)+ if (!pending) return+ this.#pending.delete(message.id)+ pending.cleanup()+ if (message.error) {+ const error = new RuntimeError(message.error.data?.code ?? 'HOST_ERROR', message.error.message)+ if (message.error.data?.classified === true) classifiedRemoteErrors.add(error)+ pending.reject(error)+ } else pending.resolve(message.result)+ return+ }+ if (message.method === 'request.cancel') {+ this.#active.get(message.params?.id)?.abort(new Error('Caller cancelled extension operation'))+ return+ }+ if (message.id !== undefined && (typeof message.id !== 'string' || this.#active.has(message.id))) {+ this.close(new RuntimeError('INVALID_ARGUMENT', 'Invalid or duplicate JSON-RPC request id'))+ return+ }+ const controller = new AbortController()+ if (message.id !== undefined) this.#active.set(message.id, controller)+ Promise.resolve().then(async () => {+ try {+ const result = await this.handler(message.method, message.params, controller.signal)+ if (message.id !== undefined) await this.#send({ jsonrpc: '2.0', id: message.id, result: result ?? null })+ } catch (error) {+ if (message.id !== undefined) await this.#send({ jsonrpc: '2.0', id: message.id,+ error: { code: -32000, message: String(error?.message ?? error).slice(0, 2048),+ data: { code: typeof error?.code==='string'?error.code:'EXTENSION_ERROR',+ classified: error instanceof RuntimeError || (error instanceof Error &&+ (classifiedRemoteErrors.has(error) || error.name === 'HostError' && typeof error.code === 'string')),+ ...(typeof error?.name==='string'?{name:error.name}:{}) } } })+ }+ }).catch(() => {}).finally(() => this.#active.delete(message.id))+ }++ close(reason = new Error('Host connection closed')) {+ if (this.#closed) return+ this.#closed = true+ for (const pending of this.#pending.values()) { pending.cleanup(); pending.reject(reason) }+ this.#pending.clear()+ for (const active of this.#active.values()) active.abort(reason)+ this.#active.clear()+ this.socket.destroy()+ }+}diff --git a/extensions/cordis/test/cli-plugins.test.mjs b/extensions/cordis/test/cli-plugins.test.mjsnew file mode 100644index 0000000..3b78ee6--- /dev/null+++ b/extensions/cordis/test/cli-plugins.test.mjs@@ -0,0 +1,19 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { mkdtemp, writeFile, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { verifyCLI } from '../../plugins/officecli/src/cli.mjs'++test('Office activation requires a working CLI and accepts upstream version changes', async t => {+ const directory = await mkdtemp(join(tmpdir(), 'go-bot-cli-'))+ t.after(() => rm(directory, {recursive:true, force:true}))+ const command = join(directory, 'officecli')+ await assert.rejects(verifyCLI(command), /Reinstall the plugin/)+ await writeFile(command, '#!/bin/sh\nprintf "1.0.163\\n"\n', {mode:0o755})+ await verifyCLI(command)+ await writeFile(command, '#!/bin/sh\nprintf "1.0.160\\n"\n', {mode:0o755})+ await verifyCLI(command)+ await writeFile(command, '#!/bin/sh\nexit 1\n', {mode:0o755})+ await assert.rejects(verifyCLI(command), /Reinstall the plugin/)+})diff --git a/extensions/cordis/test/examples.test.mjs b/extensions/cordis/test/examples.test.mjsnew file mode 100644index 0000000..aa682dd--- /dev/null+++ b/extensions/cordis/test/examples.test.mjs@@ -0,0 +1,34 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { HostRuntime } from '../src/host-runtime.mjs'++test('shipped JavaScript examples run with native Cordis configuration and service injection', async t => {+ const contributions = new Map()+ const names = { provider: 'catalog-provider', lookup: 'catalog-tools', mcp: 'mcp-service' }+ const runtime = await HostRuntime.create({ directory: '/unused',+ loadPackage: async name => ({ module: await import(new URL(`../../../examples/plugins/${names[name]}/index.mjs`, import.meta.url)) }),+ call: async (method, input) => {+ if (method === 'contribution.register') { const id = input.owner + '/' + input.callbackId; contributions.set(id, input); return { id } }+ if (method === 'contribution.remove') contributions.delete(input.registrationId)+ return null+ },+ })+ t.after(() => runtime.close())+ const settings = { instances: [+ { id: 'lookup', package: 'lookup', enabled: true, config: { toolName: 'lookup', prefix: 'Found: ' } },+ { id: 'catalog', package: 'provider', enabled: true, config: { entries: { support: 'Contact support' } } },+ { id: 'docs', package: 'mcp', enabled: true, config: { serverName: 'docs', url: 'https://example.com/mcp', apiKey: 'DOCS_KEY' } },+ ] }+ const loaded = await runtime.apply(settings)+ assert.deepEqual(loaded.instances.map(row => row.state), ['ready', 'ready', 'ready'])+ const tool = [...contributions.values()].find(row => row.kind === 'tool')+ const result = await runtime.invoke({ owner: tool.owner, callbackId: tool.callbackId, method: 'execute', args: { key: 'support' }, context: {} }, new AbortController().signal)+ assert.deepEqual(result, { content: [{ type: 'text', text: 'Found: Contact support' }], data: { found: true, text: 'Found: Contact support' } })+ const mcp = [...contributions.values()].find(row => row.kind === 'mcp')+ assert.deepEqual(mcp.descriptor.connection.headers, { Authorization: 'Bearer ${credential:DOCS_KEY}' })+ await runtime.apply({ instances: [] })+ assert.equal(contributions.size, 0)+ const failed = await runtime.apply({ instances: [{ id: 'invalid', package: 'mcp', enabled: true, config: { serverName: 'docs', url: 'not-a-url' } }] })+ assert.equal(failed.instances[0].state, 'failed')+ assert.equal(contributions.size, 0, 'invalid native config must not register an MCP connection')+})diff --git a/extensions/cordis/test/host-bridge.test.mjs b/extensions/cordis/test/host-bridge.test.mjsnew file mode 100644index 0000000..b164e9e--- /dev/null+++ b/extensions/cordis/test/host-bridge.test.mjs@@ -0,0 +1,197 @@+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { HostRuntime } from '../src/host-runtime.mjs'++function deferred() {+ let resolve, reject+ const promise = new Promise((yes, no) => { resolve = yes; reject = no })+ return { promise, resolve, reject }+}++async function fixture(module, overrides = {}) {+ const contributions = new Map(), calls = []+ const runtime = await HostRuntime.create({ directory: '/unused',+ loadPackage: async () => ({ module }),+ call: async (method, input, signal, options) => {+ calls.push({ method, input, options })+ signal?.throwIfAborted()+ if (overrides[method]) return overrides[method](input, signal)+ if (method === 'contribution.register') {+ const id = `go-${contributions.size + 1}`+ contributions.set(id, input)+ return { id }+ }+ if (method === 'contribution.remove') contributions.delete(input.registrationId)+ if (method === 'host.invoke') return { owner: input.owner, key: input.input?.key }+ return null+ },+ })+ return { runtime, contributions, calls }+}++test('async registration waits for Go and binds each Cordis instance to its own owner', async () => {+ const entered = deferred(), host = deferred(), owners = []+ const module = { name: 'mail', inject: ['host'], async apply(ctx) {+ const pending = ctx.host.tools.register({ name: 'send', description: 'Send', inputSchema: { type: 'object' },+ async execute() { return { content: [{ type: 'text', text: 'sent' }] } } })+ assert.equal(typeof pending.then, 'function')+ entered.resolve()+ await pending+ owners.push((await ctx.host.credentials.get('mailbox')).owner)+ } }+ const f = await fixture(module, { 'contribution.register': async () => { await host.promise; return { id: 'registered' } } })+ try {+ const loading = f.runtime.apply({ instances: [{ id: 'work', package: 'mail', enabled: true }] })+ await entered.promise+ assert.equal(f.runtime.inspect()[0].state, 'loading')+ // While one plugin awaits Go, the Node event loop is available.+ await new Promise(resolve => setImmediate(resolve))+ host.resolve()+ await loading+ assert.equal(f.runtime.inspect()[0].state, 'ready')+ assert.deepEqual(owners, ['work'])+ await f.runtime.apply({ instances: [+ { id: 'personal', package: 'mail', enabled: true },+ { id: 'work', package: 'mail', enabled: true },+ ] })+ assert.deepEqual(owners, ['work', 'personal'])+ assert.equal(f.runtime.inspect().filter(row => row.state === 'ready').length, 2)+ } finally { await f.runtime.close() }+})++test('Cordis resolves service dependencies and unregisters only the removed entry', async () => {+ const f = await fixture(null)+ const modules = {+ consumer: { name: 'consumer', inject: ['host', 'mailClient'], async apply(ctx) {+ await ctx.host.tools.register({ name: 'send', description: 'Send', inputSchema: { type: 'object' },+ async execute() { return { content: [{ type: 'text', text: ctx.mailClient.name }] } } })+ } },+ provider: { name: 'provider', apply(ctx) { ctx.provide('mailClient', { name: 'native Cordis service' }) } },+ }+ f.runtime.loadPackage = async name => ({ module: modules[name] })+ try {+ await f.runtime.apply({ instances: [+ { id: 'consumer', package: 'consumer', enabled: true },+ { id: 'provider', package: 'provider', enabled: true },+ ] })+ assert.equal(f.contributions.size, 1)+ assert.equal([...f.contributions.values()][0].owner, 'consumer')+ assert.equal(f.runtime.inspect().filter(row => row.state === 'ready').length, 2)+ await f.runtime.apply({ instances: [{ id: 'provider', package: 'provider', enabled: true }] })+ assert.equal(f.contributions.size, 0)+ assert.deepEqual(f.runtime.inspect().map(row => row.id), ['provider'])+ } finally { await f.runtime.close() }+})++test('tool body is a direct callback and can await a nested Host request', async () => {+ let events = 0+ const f = await fixture({ name: 'nested', inject: ['host'], async apply(ctx) {+ ctx.on('host/skills-changed', () => { events++ })+ await ctx.host.tools.register({ name: 'lookup', description: 'Lookup', inputSchema: { type: 'object' },+ async execute(args, call) {+ assert.equal(call.sessionId, 'session-a')+ const record = await ctx.host.credentials.get(args.key)+ return { content: [{ type: 'text', text: `${record.owner}/${record.key}` }] }+ } })+ } })+ try {+ await f.runtime.apply({ instances: [{ id: 'nested', package: 'nested', enabled: true }] })+ const row = [...f.contributions.values()][0]+ const result = await f.runtime.invoke({ owner: 'nested', callbackId: row.callbackId, method: 'execute',+ args: { key: 'mailbox' }, context: { sessionId: 'session-a', invocation: 'live-go-call' } }, new AbortController().signal)+ assert.equal(events, 0)+ assert.deepEqual(result, { content: [{ type: 'text', text: 'nested/mailbox' }] })+ f.runtime.notify('host/skills-changed', { callId: 'a' })+ assert.equal(events, 1)+ } finally { await f.runtime.close() }+})++test('initialization failure withdraws accepted contributions and cannot report ready', async () => {+ const f = await fixture({ name: 'broken', inject: ['host'], async apply(ctx) {+ await ctx.host.prompts.register({ id: 'hint', location: 'system', text: 'hint' })+ throw new Error('invalid account')+ } })+ try {+ await f.runtime.apply({ instances: [{ id: 'broken', package: 'broken', enabled: true }] })+ assert.equal(f.contributions.size, 0)+ assert.equal(f.runtime.inspect()[0].state, 'failed')+ assert.equal(f.runtime.callbacks.size, 0)+ } finally { await f.runtime.close() }+})++test('Host notification return values and listener failures cannot become tool decisions', async () => {+ const seen = [], warnings = []+ const f = await fixture({ name: 'observer', inject: ['host'], apply(ctx) {+ ctx.on('host/credential-changed', () => { throw new Error('observer failed') })+ ctx.on('host/credential-changed', async () => { seen.push('second'); return { kind: 'deny' } })+ } })+ f.runtime.onLog = record => warnings.push(record)+ try {+ await f.runtime.apply({ instances: [{ id: 'observer', package: 'observer', enabled: true }] })+ assert.equal(f.runtime.notify('host/credential-changed', { outcome: 'success' }), undefined)+ await new Promise(resolve => setImmediate(resolve))+ assert.deepEqual(seen, ['second'])+ assert.equal(warnings.length, 1)+ } finally { await f.runtime.close() }+})++test('Host inputs and callback results reject lossy JSON while authorization run may return void', async () => {+ const f = await fixture({ name: 'json', inject: ['host'], async apply(ctx) {+ await assert.rejects(ctx.host.credentials.put('account', { kind: 'grant', payload: new Date() }), error => error.code === 'INVALID_ARGUMENT')+ await ctx.host.tools.register({ name: 'missing', description: 'Missing return', inputSchema: { type: 'object' }, async execute() {} })+ await ctx.host.tools.register({ name: 'date', description: 'Non JSON return', inputSchema: { type: 'object' }, async execute() { return new Date() } })+ await ctx.host.authorization.register({ key: 'account', title: 'Account', methods: [{ id: 'test', label: 'Test' }], async run() {} })+ } })+ try {+ await f.runtime.apply({ instances: [{ id: 'json', package: 'json', enabled: true }] })+ assert.equal(f.calls.some(({ method, input }) => method === 'host.invoke' && input.service === 'credentials'), false, 'invalid data must not reach Go')+ for (const row of f.contributions.values()) {+ const invoke = () => f.runtime.invoke({ owner: row.owner, callbackId: row.callbackId, method: row.kind === 'authorization' ? 'run' : 'execute', args: {}, context: {} }, new AbortController().signal)+ if (row.kind === 'authorization') assert.equal(await invoke(), null)+ else await assert.rejects(invoke(), error => error.code === 'INVALID_RESULT')+ }+ } finally { await f.runtime.close() }+})++test('disposing during registration removes a late Go acceptance instead of losing its handle', async () => {+ const entered = deferred(), accepted = deferred()+ let scope+ const f = await fixture({ name: 'late', inject: ['host'], async apply(ctx) {+ scope = ctx+ const pending = ctx.host.tools.register({ name: 'late', description: 'Late acceptance', inputSchema: { type: 'object' }, async execute() { return { content: [] } } })+ entered.resolve()+ await pending+ } }, { 'contribution.register': async () => {+ await accepted.promise+ f.contributions.set('late-id', {})+ return { id: 'late-id' }+ } })+ try {+ const loading = f.runtime.apply({ instances: [{ id: 'late', package: 'late', enabled: true }] })+ await entered.promise+ const disposing = scope.fiber.dispose()+ accepted.resolve()+ await Promise.all([loading, disposing])+ assert.equal(f.calls.find(call => call.method === 'contribution.register').options.drain, true)+ assert.equal(f.contributions.size, 0)+ assert.equal(f.runtime.callbacks.size, 0)+ } finally { await f.runtime.close() }+})++test('native authorization inspect/disconnect stay asynchronous and do not invent a Go credential record',async()=>{+ let disconnected=false+ const f=await fixture({name:'native',inject:['host'],async apply(ctx){+ await ctx.host.authorization.register({key:'account',title:'Native account',methods:[{id:'login',label:'Connect'}],async run(){},async inspect({signal}){assert.ok(signal instanceof AbortSignal);return {configured:!disconnected,accountLabel:'alice'}},async disconnect({signal}){assert.ok(signal instanceof AbortSignal);disconnected=true}})+ }})+ try{+ await f.runtime.apply({instances:[{id:'native',package:'native',enabled:true}]})+ const row=[...f.contributions.values()][0]+ assert.deepEqual(row.callbacks.sort(),['disconnect','inspect','run'])+ assert.equal('inspect' in row.descriptor,false,'functions must be callbacks, not serialized JSON')+ const invoke=method=>f.runtime.invoke({owner:row.owner,callbackId:row.callbackId,method,args:{},context:{}},new AbortController().signal)+ assert.deepEqual(await invoke('inspect'),{configured:true,accountLabel:'alice'})+ assert.equal(await invoke('disconnect'),null)+ assert.deepEqual(await invoke('inspect'),{configured:false,accountLabel:'alice'})+ assert.equal(f.calls.some(row=>row.method==='host.invoke'&&row.input.service==='credentials'),false)+ }finally{await f.runtime.close()}+})diff --git a/extensions/cordis/test/native-account-plugins.test.mjs b/extensions/cordis/test/native-account-plugins.test.mjsnew file mode 100644index 0000000..03cb2c6--- /dev/null+++ b/extensions/cordis/test/native-account-plugins.test.mjs@@ -0,0 +1,166 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import {mkdtemp,writeFile,mkdir,rm,readlink,stat} from 'node:fs/promises'+import {tmpdir} from 'node:os'+import path from 'node:path'+import http from 'node:http'+import {once} from 'node:events'+import {apply as applyX,authorize as authorizeX,nativeAccount} from '../../plugins/x/src/index.mjs'+import {apply as applyGoogle,authorize as authorizeGoogle,inspectAccount,desktopClient} from '../../plugins/google-workspace/src/index.mjs'+import {interactive,relayRedirect,validateRedirect,nativeDirectory} from '../../plugins/x/src/native-cli.mjs'++async function fixture(t){+ const directory=await mkdtemp(path.join(tmpdir(),'go-bot-native-auth-'))+ const previous={...process.env}+ process.env.HOME=path.join(directory,'home');process.env.DSH_HOME=path.join(directory,'data')+ await mkdir(process.env.HOME,{recursive:true});await mkdir(path.join(directory,'bin'))+ process.env.PATH=path.join(directory,'bin')+path.delimiter+process.env.PATH+ t.after(async()=>{for(const key of Object.keys(process.env))if(!(key in previous))delete process.env[key];Object.assign(process.env,previous);await rm(directory,{recursive:true,force:true})})+ return {directory,async binary(name,source){await writeFile(path.join(directory,'bin',name),'#!'+process.execPath+'\n'+source,{mode:0o755})}}+}+const fakeX=`+const fs=require('node:fs'),path=require('node:path');const args=process.argv.slice(2),file=path.join(process.env.HOME,'.xurl','auth.yml');+if(args[0]==='--version'){console.log('xurl test');process.exit(0)}+if(args[1]==='oauth2'){+ if(process.env.CLIENT_ID!=='project-x-client'||process.env.CLIENT_SECRET!=='')process.exit(3);+ const url='https://x.com/i/oauth2/authorize?client_id=project-x-client&redirect_uri='+encodeURIComponent('http://localhost:8080/callback')+'&state=attempt-state&code_challenge=test';+ process.stderr.write(url.slice(0,75));setTimeout(()=>process.stderr.write(url.slice(75)+'\\n'),10);+ let input='';process.stdin.on('data',v=>input+=v);process.stdin.on('end',()=>{+ const value=new URL(input.trim());if(value.searchParams.get('code')!=='accepted'||value.searchParams.get('state')!=='attempt-state')process.exit(4);+ fs.writeFileSync(file,JSON.stringify({default_app:'default',apps:{default:{client_id:process.env.CLIENT_ID,default_user:'alice',oauth2_tokens:{alice:{oauth2:{access_token:'private-access',refresh_token:'private-refresh',expiration_time:1}}}}}}),{mode:0o600});+ });+}else if(args[1]==='clear'){+ if(args.at(-2)!=='--oauth2-username')process.exit(5);+ const json=JSON.parse(fs.readFileSync(file));delete json.apps.default.oauth2_tokens[args.at(-1)];fs.writeFileSync(file,JSON.stringify(json));+}else if(args[1]==='status'){console.log('X status')}+`+const fakeGoogle=`+const fs=require('node:fs'),path=require('node:path'),http=require('node:http');const args=process.argv.slice(2),root=process.env.GOOGLE_WORKSPACE_CLI_CONFIG_DIR||path.join(process.env.HOME,'.config','gws'),file=path.join(root,'credentials.json');+if(args[0]==='--version'){console.log('gws test');process.exit(0)}+if(args[1]==='login'){+ if(!args.includes('--scopes'))process.exit(2);+ const server=http.createServer((req,res)=>{+ const query=new URL(req.url,'http://localhost').searchParams;+ if(query.get('code')!=='accepted'||query.get('state')!=='attempt-state'){res.writeHead(400);res.end();return}+ fs.writeFileSync(file,JSON.stringify({type:'authorized_user',refresh_token:'native-refresh',client_id:'project-google-client',client_secret:'public-desktop-id'}),{mode:0o600});+ res.end('Done');server.close();+ });+ server.listen(0,'127.0.0.1',()=>console.log('Open this URL: https://accounts.google.com/o/oauth2/v2/auth?client_id=project-google-client&state=attempt-state&redirect_uri='+encodeURIComponent('http://localhost:'+server.address().port+'/callback')));+}else if(args[1]==='status'){+ const grant=fs.existsSync(file)?JSON.parse(fs.readFileSync(file)):{};+ console.log(JSON.stringify({auth_method:grant.refresh_token?'oauth2':'none',has_refresh_token:!!grant.refresh_token,token_valid:grant.refresh_token==='native-refresh',user:grant.refresh_token?'[email protected]':undefined}));+}else if(args[1]==='logout'){fs.rmSync(file,{force:true});console.log('{}')}+`+function context(){+ const registration=Promise.withResolvers()+ const state={flows:[],mcps:[],skills:[],events:new Map(),removed:0,registered:registration.promise}+ const ctx={host:{info:async()=>({instanceId:'x'}),authorization:{register:async row=>state.flows.push(row)},mcp:{register:async row=>{state.mcps.push(row);registration.resolve();return {dispose:async()=>state.removed++}}},skills:{registerDirectory:async dir=>state.skills.push(dir)},prompts:{register:async()=>{}}},on:(name,handler)=>state.events.set(name,handler),logger:{warn:()=>{}}}+ return {ctx,state}+}+function session(provider){+ const notices=[],prompts=[],signal=new AbortController().signal+ return {notices,prompts,method:'oauth',signal,notify:async value=>notices.push(value),prompt:async prompt=>{+ prompts.push(prompt)+ if(prompt.kind==='select')return 'readonly'+ if(prompt.message.includes('Google Desktop OAuth client JSON'))return JSON.stringify({installed:{client_id:'project-google-client',client_secret:'desktop-public-value'}})+ if(prompt.message==='Enter your X app Client ID.')return 'project-x-client'+ if(prompt.message.includes('Client Secret'))return ''+ const url=new URL(notices.at(-1).url),redirect=new URL(url.searchParams.get('redirect_uri'));redirect.searchParams.set('code','accepted');redirect.searchParams.set('state',url.searchParams.get('state'));return redirect.href+ }}+}+test('native X authorization uses child env, keeps tokens native and only starts MCP after authorization',{timeout:15000},async t=>{+ const f=await fixture(t);await f.binary('xurl',fakeX)+ const {ctx,state}=context();await applyX(ctx)+ assert.equal(state.mcps.length,0);assert.deepEqual(await state.flows[0].inspect(),{configured:false})+ const s=session('x'),root=path.join(process.env.DSH_HOME,'credentials','x')+ await authorizeX(s,root)+ assert.equal(s.prompts.length,3,'first connection collects application ID, optional secret and callback')+ assert.equal(s.notices.filter(n=>n.url).length,1,'only the actual account login URL should be offered during authorization')+ assert.match(s.prompts[2].message,/First open the authorization link/)+ assert.match(s.prompts[2].placeholder,/localhost:8080\/callback/)+ assert.equal(s.prompts[1].kind,'secret');assert.equal(s.prompts[2].kind,'text')+ assert.equal((await nativeAccount(root)).configured,true,'expired access tokens with refresh tokens remain configured')+ state.events.get('host/authorization-changed')({instanceId:'google-workspace',key:'account',phase:'authorized'})+ assert.equal(state.mcps.length,0,'another plugin authorization must not activate this bridge')+ state.events.get('host/authorization-changed')({instanceId:'x',key:'account',phase:'authorized'})+ await state.registered+ assert.equal(state.mcps.length,1)+ assert.equal(state.mcps[0].connection.oauth,undefined)+ assert.deepEqual(state.mcps[0].connection.args,['mcp','https://api.x.com/mcp'])+ await state.flows[0].disconnect({signal:s.signal})+ assert.equal(state.removed,1);assert.deepEqual(await state.flows[0].inspect(),{configured:false})+ assert.equal(process.env.CLIENT_ID,undefined)+})+test('native Google authorization relays only the current callback and stores an actual native grant',async t=>{+ const f=await fixture(t);await f.binary('gws',fakeGoogle)+ const {ctx,state}=context();await applyGoogle(ctx)+ assert.deepEqual(state.skills,['skills']);assert.deepEqual(await inspectAccount(),{configured:false})+ assert.deepEqual(state.flows[0].methods,[{id:'oauth',label:'Connect Google account'}])+ const s=session('google'),root=path.join(process.env.DSH_HOME,'credentials','google-workspace')+ await authorizeGoogle(s,root)+ assert.equal(s.prompts.length,3);assert.equal(s.prompts[0].kind,'secret');assert.equal(s.prompts[0].webInput,'json-file');assert.equal(s.prompts[1].kind,'select')+ assert.equal(s.prompts[2].kind,'text')+ assert.deepEqual(await inspectAccount(),{configured:true,accountLabel:'[email protected]'})+ assert.equal((await stat(path.join(root,'client_secret.json'))).mode&0o777,0o600)+ await state.flows[0].disconnect({signal:s.signal});assert.deepEqual(await inspectAccount(),{configured:false})+ const again=session('google');await authorizeGoogle(again,root)+ assert.equal(again.prompts.length,2,'subsequent authorization reuses the user native client configuration')+ assert.equal(again.prompts[0].kind,'select')+})+test('Google status distinguishes a revoked token from an unavailable live check',async t=>{+ const f=await fixture(t)+ await f.binary('gws',`console.log(JSON.stringify({auth_method:'oauth2',has_refresh_token:true,token_valid:false}))`)+ assert.deepEqual(await inspectAccount(),{configured:false})+ await f.binary('gws',`console.log(JSON.stringify({auth_method:'oauth2',has_refresh_token:true}))`)+ assert.deepEqual(await inspectAccount(),{configured:true})+ await f.binary('gws',`console.log(JSON.stringify({auth_method:'oauth2',has_refresh_token:true,encryption_valid:false}))`)+ await assert.rejects(inspectAccount(),/cannot be decrypted/)+})+test('callback relay rejects unexpected destinations, mismatched or duplicated state and redirects',async t=>{+ let hits=0+ const server=http.createServer((req,res)=>{hits++;res.writeHead(302,{Location:'http://example.invalid/'});res.end()})+ server.listen(0,'127.0.0.1');await once(server,'listening');t.after(()=>server.close())+ const expected='http://127.0.0.1:'+server.address().port+'/callback'+ assert.throws(()=>validateRedirect(expected+'?code=a&state=wrong',expected,'right'))+ assert.throws(()=>validateRedirect(expected+'?code=a&state=right&state=wrong',expected,'right'))+ await assert.rejects(relayRedirect('http://example.com/callback?code=a','http://example.com/callback'))+ assert.equal(hits,0)+ await assert.rejects(relayRedirect(expected+'?code=a',expected),/not accepted/);assert.equal(hits,1)+})+test('fragmented native URLs are not used before a complete line and cancellation closes the process',async t=>{+ await fixture(t)+ const controller=new AbortController()+ const cli=interactive(process.execPath,['-e',`process.stderr.write('https://example.test/auth?redirect_uri=');setTimeout(()=>{process.stderr.write('http%3A%2F%2Flocalhost%3A3212%2Fcallback\\n')},20);setInterval(()=>{},1000)`],{signal:controller.signal,acceptURL:u=>u.searchParams.has('redirect_uri')})+ const url=await cli.url;assert.equal(url.searchParams.get('redirect_uri'),'http://localhost:3212/callback')+ controller.abort();await assert.rejects(cli.done,/did not complete/)+ const failed=interactive('/does-not-exist',[],{acceptURL:()=>true});await assert.rejects(failed.url);await assert.rejects(failed.done)+})+test('native authorization errors expose provider categories without returning raw credential output',async()=>{+ const cli=interactive(process.execPath,['-e',`console.log('https://example.test/auth?redirect_uri=http%3A%2F%2Flocalhost%3A3212%2Fcallback');console.error('TokenExchangeError: invalid_grant private-client-secret private-code');process.exit(1)`],{acceptURL:()=>true})+ await cli.url+ await assert.rejects(cli.done,error=>error.message.includes('invalid_grant')&&!error.message.includes('private-client-secret')&&!error.message.includes('private-code'))+})+test('native directory preparation refuses unknown existing directories and preserves the data root link',async t=>{+ const f=await fixture(t),target=path.join(process.env.HOME,'native')+ const dir=await nativeDirectory('example',target);assert.equal(await readlink(target),dir)+ await nativeDirectory('example',target)+ const empty=path.join(f.directory,'empty');await mkdir(empty);await nativeDirectory('empty',empty);assert.ok(await readlink(empty))+ const unknown=path.join(f.directory,'unknown');await mkdir(unknown);await writeFile(path.join(unknown,'auth.yml'),'private')+ await assert.rejects(nativeDirectory('example',unknown),/Refusing/)+})+test('Google client import rejects wrong client types and arbitrary token endpoints',()=>{+ for(const value of ['{}','null','[]','{"installed":{"client_id":42,"client_secret":true}}'])assert.throws(()=>desktopClient(value),/Desktop app/)+ assert.throws(()=>desktopClient(JSON.stringify({web:{client_id:'id',client_secret:'secret'}})),/Desktop app/)+ assert.throws(()=>desktopClient(JSON.stringify({installed:{client_id:'id',client_secret:'secret',token_uri:'https://evil.invalid/token'}})),/Unsupported/)+ assert.equal(desktopClient(JSON.stringify({installed:{client_id:'id',client_secret:'secret'}})).installed.client_id,'id')+})++test('Google refuses invalid application JSON without starting login or persisting it',async t=>{+ const f=await fixture(t);await f.binary('gws',fakeGoogle)+ const {ctx}=context();await applyGoogle(ctx)+ const root=path.join(process.env.DSH_HOME,'credentials','google-workspace')+ const s={...session('google'),prompt:async()=>'{"web":{"client_id":"wrong","client_secret":"private"}}'}+ await assert.rejects(authorizeGoogle(s,root),/Desktop app/)+ await assert.rejects(stat(path.join(root,'client_secret.json')), {code:'ENOENT'})+ assert.deepEqual(await inspectAccount(),{configured:false})+})diff --git a/extensions/cordis/test/packages.test.mjs b/extensions/cordis/test/packages.test.mjsnew file mode 100644index 0000000..8080da9--- /dev/null+++ b/extensions/cordis/test/packages.test.mjs@@ -0,0 +1,68 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { mkdtemp, mkdir, writeFile, readFile, access, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { Packages, validateSource } from '../src/packages.mjs'+import { HostRuntime } from '../src/host-runtime.mjs'++test('a native plugin package runs only approved native pnpm scripts, activates, withdraws and retains workspace files', async t => {+ const directory=await mkdtemp(join(tmpdir(),'go-bot-packages-'))+ t.after(()=>rm(directory,{recursive:true,force:true}))+ const source=join(directory,'source');const profile=join(directory,'profile')+ await mkdir(source)+ await mkdir(profile)+ const name='@fixture/inventory'+ await writeFile(join(source,'package.json'),JSON.stringify({name,version:'1.0.0',type:'module',exports:'./index.mjs',files:['index.mjs'],+ peerDependencies:{'@go-bot/plugin-sdk':'^1.0.0'},+ scripts:{postinstall:'node -e "require(\'fs\').writeFileSync(\'built.txt\',\'built\')"'},+ goBot:{api:'1'}}))+ await writeFile(join(source,'index.mjs'),`import {HostError,apiVersion} from '@go-bot/plugin-sdk';export const inject=['host'];export async function apply(ctx){await ctx.host.tools.register({name:'inventory_lookup',description:'Inventory',inputSchema:{type:'object'},async execute(){if(apiVersion!=='1')throw new HostError('VERSION','Wrong SDK');return{content:[{type:'text',text:'available'}],data:{available:true}}}})}`)+ const manager=new Packages({directory:profile})+ const declared={type:'directory',spec:source}+ assert.equal((await manager.inspect(name,declared)).version,'1.0.0')+ await assert.rejects(manager.install(name,declared), /Ignored build scripts/ )+ const installed=await manager.install(name,declared,{builds:[name]})+ assert.equal(installed.name,name)+ assert.equal(installed.api,'1')+ assert.equal((await manager.installed()).length,1)+ assert.equal((await manager.installed())[0].present,true)+ assert.equal(await readFile(join(profile,'node_modules',name,'built.txt'),'utf8'),'built')+ const contributions=new Map()+ const runtime=await HostRuntime.create({directory:profile,call:async(method,p)=>{+ const id=p.owner+'/'+p.callbackId+ if(method==='contribution.register'){contributions.set(id,p);return{id}}+ if(method==='contribution.remove')contributions.delete(p.registrationId)+ return null+ }})+ t.after(()=>runtime.close())+ const state=await runtime.apply({instances:[{id:'inventory',package:name,enabled:true}]})+ assert.equal(state.instances[0].state,'ready')+ assert.equal(contributions.size,1)+ const contribution=[...contributions.values()][0]+ const output=await runtime.invoke({owner:contribution.owner,callbackId:contribution.callbackId,method:'execute',args:{},context:{}},new AbortController().signal)+ assert.deepEqual(output.data,{available:true})+ await runtime.apply({instances:[]})+ assert.equal(contributions.size,0)+ await runtime.close()+ const data=join(directory,'data','inventory')+ await mkdir(data,{recursive:true})+ await writeFile(join(data,'business.json'),'{"retained":true}')+ await manager.remove(name)+ assert.equal((await manager.installed()).length,0)+ assert.equal(await readFile(join(data,'business.json'),'utf8'),'{"retained":true}')+})++test('package sources reject credentials in URLs, floating persisted versions and command-shaped input',()=>{+ for(const [name,source]of [+ ['../escape',{type:'directory',spec:'/tmp/pkg'}],+ ['valid',{type:'directory',spec:'relative'}],+ ['valid',{type:'registry',spec:'[email protected]'}],+ ['valid',{type:'registry',spec:'valid@latest'}],+ ['valid',{type:'registry',spec:'[email protected]',registry:'https://[email protected]'}],+ ['valid',{type:'git',spec:'git+https://example.com/repo.git#main'}],+ ['valid',{type:'tarball',spec:'https://example.com/pkg.tgz?token=secret'}],+ ])assert.throws(()=>validateSource(name,source,{fixed:true}))+ assert.doesNotThrow(()=>validateSource('@fixture/provider',{type:'registry',spec:'@fixture/[email protected]'},{fixed:true}))+ assert.doesNotThrow(()=>validateSource('valid',{type:'git',spec:'git+https://example.com/repo.git#'+'a'.repeat(40)},{fixed:true}))+})diff --git a/extensions/cordis/test/rpc.test.mjs b/extensions/cordis/test/rpc.test.mjsnew file mode 100644index 0000000..e076035--- /dev/null+++ b/extensions/cordis/test/rpc.test.mjs@@ -0,0 +1,23 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { createServer, connect } from 'node:net'+import { once } from 'node:events'+import { Peer } from '../src/rpc.mjs'+import { HostError } from '../../sdk/index.mjs'++test('JSON-RPC returns public HostError and preserves nested error codes', async t => {+ const server = createServer()+ server.listen(0, '127.0.0.1')+ await once(server, 'listening')+ t.after(() => server.close())+ const accepted = once(server, 'connection')+ const clientSocket = connect(server.address().port, '127.0.0.1')+ const [serverSocket] = await accepted+ const host = new Peer(serverSocket, async method => {+ if (method === 'lookup') throw new HostError('NOT_FOUND', 'Record not found')+ })+ const plugin = new Peer(clientSocket, async () => { await plugin.call('lookup', {}) })+ t.after(() => { host.close(); plugin.close() })+ await assert.rejects(plugin.call('lookup', {}), error => error instanceof HostError && error.code === 'NOT_FOUND')+ await assert.rejects(host.call('nested', {}), error => error instanceof HostError && error.code === 'NOT_FOUND')+})diff --git a/extensions/plugins/agent-browser/LICENSE b/extensions/plugins/agent-browser/LICENSEnew file mode 100644index 0000000..09f7d46--- /dev/null+++ b/extensions/plugins/agent-browser/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Go Harness contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/extensions/plugins/agent-browser/THIRD_PARTY_NOTICES.md b/extensions/plugins/agent-browser/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..79b6c50--- /dev/null+++ b/extensions/plugins/agent-browser/THIRD_PARTY_NOTICES.md@@ -0,0 +1,3 @@+# Third-party notices++Original Skills are supplied unchanged by [agent-browser](https://github.com/vercel-labs/agent-browser) under its Apache-2.0 license. The upstream LICENSE is included with the assembled Skills. CLI installation uses the official package at the locked version.diff --git a/extensions/plugins/agent-browser/UPSTREAM_LICENSE b/extensions/plugins/agent-browser/UPSTREAM_LICENSEnew file mode 100644index 0000000..8226d36--- /dev/null+++ b/extensions/plugins/agent-browser/UPSTREAM_LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONS++APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++Copyright 2025 Vercel Inc.++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.diff --git a/extensions/plugins/agent-browser/assets/icon.png b/extensions/plugins/agent-browser/assets/icon.pngnew file mode 100644index 0000000..090f6b2Binary files /dev/null and b/extensions/plugins/agent-browser/assets/icon.png differdiff --git a/extensions/plugins/agent-browser/package.json b/extensions/plugins/agent-browser/package.jsonnew file mode 100644index 0000000..9746611--- /dev/null+++ b/extensions/plugins/agent-browser/package.json@@ -0,0 +1,25 @@+{+ "name": "@go-bot/plugin-agent-browser",+ "version": "0.1.0",+ "type": "module",+ "description": "Official agent-browser CLI and upstream Skills for Go Bot",+ "license": "MIT",+ "exports": "./src/index.mjs",+ "files": [+ "src/",+ "skills/",+ "upstream.lock.json",+ "THIRD_PARTY_NOTICES.md",+ "LICENSE",+ "UPSTREAM_LICENSE",+ "scripts/",+ "plugin.json",+ "assets/"+ ],+ "goBot": {+ "api": "1"+ },+ "scripts": {+ "postinstall": "node ./scripts/install.mjs"+ }+}diff --git a/extensions/plugins/agent-browser/plugin.json b/extensions/plugins/agent-browser/plugin.jsonnew file mode 100644index 0000000..791c9a4--- /dev/null+++ b/extensions/plugins/agent-browser/plugin.json@@ -0,0 +1,11 @@+{+ "name": "agent-browser",+ "description": {+ "en": "Browse websites, interact with pages, capture screenshots and download files with the official CLI and upstream Skill.",+ "zh-CN": "通过官方 CLI 和原始 Skill 浏览网页、操作页面、截图与下载文件。"+ },+ "icon": "/assets/plugins/agent-browser/icon.png",+ "version": "0.1.0",+ "maintainer": "Go Bot",+ "license": "MIT"+}diff --git a/extensions/plugins/agent-browser/scripts/install.mjs b/extensions/plugins/agent-browser/scripts/install.mjsnew file mode 100644index 0000000..52dda03--- /dev/null+++ b/extensions/plugins/agent-browser/scripts/install.mjs@@ -0,0 +1,11 @@+import upstream from '../upstream.lock.json' with { type: 'json' }+import { ensureCLI } from '../src/cli.mjs'+import { verify } from '../src/prepare.mjs'+// Standard npm/pnpm lifecycle script; never called from Cordis apply/dispose.+try {+ await verify()+} catch {+ // Explicit reinstallation can also repair a partial/corrupt dependency.+ await ensureCLI('agent-browser', 'agent-browser', upstream.version, true)+ await verify()+}diff --git a/extensions/plugins/agent-browser/src/cli.mjs b/extensions/plugins/agent-browser/src/cli.mjsnew file mode 100644index 0000000..4e7c48e--- /dev/null+++ b/extensions/plugins/agent-browser/src/cli.mjs@@ -0,0 +1,26 @@+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+const exec = promisify(execFile)+export async function run(binary, args, options = {}) {+ return exec(binary, args, { encoding: 'utf8', timeout: 10 * 60_000, maxBuffer: 2 << 20, ...options })+}+export async function ensureCLI(command, packageName, version, force = false) {+ let present+ try { present = (await run(command, ['--version'])).stdout.trim() }+ catch (error) { if (error.code !== 'ENOENT') throw error }+ if (!force && present !== undefined && new RegExp('(^|[^0-9])' + version.replaceAll('.', '\\.') + '([^0-9]|$)').test(present)) return+ // This function runs only during explicit package installation/reinstallation.+ // Reinstall the locked dependency when an external update changed its version.+ await run('npm', ['install', '-g', '--no-audit', '--no-fund', `${packageName}@${version}`])+ const actual = (await run(command, ['--version'])).stdout.trim()+ if (!actual.includes(version)) throw new Error(`${command} did not install the required version ${version}: ${actual}`)+}++export async function verifyCLI(command, version) {+ try {+ const value = (await run(command, ['--version'])).stdout.trim()+ if (!new RegExp('(^|[^0-9])' + version.replaceAll('.', '\\.') + '([^0-9]|$)').test(value)) throw new Error(`Expected ${command} ${version}, got ${value}`)+ } catch (error) {+ throw new Error(`${command} is not ready. Reinstall the plugin to prepare its dependencies. ${error.message}`)+ }+}diff --git a/extensions/plugins/agent-browser/src/index.mjs b/extensions/plugins/agent-browser/src/index.mjsnew file mode 100644index 0000000..5f5448a--- /dev/null+++ b/extensions/plugins/agent-browser/src/index.mjs@@ -0,0 +1,7 @@+import { verify } from './prepare.mjs'+export const name = 'agent-browser'+export const inject = ['host']+export async function apply(ctx) {+ await verify()+ await ctx.host.skills.registerDirectory('skills')+}diff --git a/extensions/plugins/agent-browser/src/prepare.mjs b/extensions/plugins/agent-browser/src/prepare.mjsnew file mode 100644index 0000000..1d017d8--- /dev/null+++ b/extensions/plugins/agent-browser/src/prepare.mjs@@ -0,0 +1,6 @@+import upstream from '../upstream.lock.json' with { type: 'json' }+import { verifyCLI, run } from './cli.mjs'+export async function verify() {+ await verifyCLI('agent-browser', upstream.version)+ await run('agent-browser', ['skills', 'get', 'core'])+}diff --git a/extensions/plugins/agent-browser/upstream.lock.json b/extensions/plugins/agent-browser/upstream.lock.jsonnew file mode 100644index 0000000..4d0778e--- /dev/null+++ b/extensions/plugins/agent-browser/upstream.lock.json@@ -0,0 +1,7 @@+{+ "repository": "https://github.com/vercel-labs/agent-browser",+ "version": "0.43.0",+ "installation": "npm install -g [email protected]",+ "skillRef": "1cc19526f3641c8543d55aa6700e7c55b37ac356",+ "skillsCLI": "1.8.1"+}diff --git a/extensions/plugins/assets.go b/extensions/plugins/assets.gonew file mode 100644index 0000000..2b93bd6--- /dev/null+++ b/extensions/plugins/assets.go@@ -0,0 +1,18 @@+package plugins++import (+ "io/fs"+ "strings"+)++const AssetPrefix = "/assets/plugins/"++// Asset reads published plugin image resources without installing or loading Node.+func Asset(urlPath string) ([]byte, error) {+ rel, ok := strings.CutPrefix(urlPath, AssetPrefix)+ if !ok || !fs.ValidPath(rel) || strings.Count(rel, "/") != 1 || strings.ContainsAny(rel, "\\?#") {+ return nil, fs.ErrNotExist+ }+ id, name, _ := strings.Cut(rel, "/")+ return files.ReadFile(id + "/assets/" + name)+}diff --git a/extensions/plugins/google-workspace/LICENSE b/extensions/plugins/google-workspace/LICENSEnew file mode 100644index 0000000..09f7d46--- /dev/null+++ b/extensions/plugins/google-workspace/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Go Harness contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/extensions/plugins/google-workspace/THIRD_PARTY_NOTICES.md b/extensions/plugins/google-workspace/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..0675d78--- /dev/null+++ b/extensions/plugins/google-workspace/THIRD_PARTY_NOTICES.md@@ -0,0 +1,3 @@+# Third-party notices++Uses the official [googleworkspace/cli](https://github.com/googleworkspace/cli) CLI. Its original license is in UPSTREAM_LICENSE. Unmodified upstream Skills and their resources are assembled at image build time. The unmodified Google G icon is the official googleworkspace GitHub organization avatar, obtained from https://avatars.githubusercontent.com/u/3708359?v=4. Google names and marks belong to their respective owners. This CLI is not an officially supported Google product.diff --git a/extensions/plugins/google-workspace/UPSTREAM_LICENSE b/extensions/plugins/google-workspace/UPSTREAM_LICENSEnew file mode 100644index 0000000..d645695--- /dev/null+++ b/extensions/plugins/google-workspace/UPSTREAM_LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/extensions/plugins/google-workspace/assets/account-setup.en.mp4 b/extensions/plugins/google-workspace/assets/account-setup.en.mp4new file mode 100644index 0000000..eb258f5Binary files /dev/null and b/extensions/plugins/google-workspace/assets/account-setup.en.mp4 differdiff --git a/extensions/plugins/google-workspace/assets/account-setup.en.png b/extensions/plugins/google-workspace/assets/account-setup.en.pngnew file mode 100644index 0000000..ad0ce91Binary files /dev/null and b/extensions/plugins/google-workspace/assets/account-setup.en.png differdiff --git a/extensions/plugins/google-workspace/assets/account-setup.zh-CN.mp4 b/extensions/plugins/google-workspace/assets/account-setup.zh-CN.mp4new file mode 100644index 0000000..2763a69Binary files /dev/null and b/extensions/plugins/google-workspace/assets/account-setup.zh-CN.mp4 differdiff --git a/extensions/plugins/google-workspace/assets/account-setup.zh-CN.png b/extensions/plugins/google-workspace/assets/account-setup.zh-CN.pngnew file mode 100644index 0000000..bb6850cBinary files /dev/null and b/extensions/plugins/google-workspace/assets/account-setup.zh-CN.png differdiff --git a/extensions/plugins/google-workspace/assets/icon.png b/extensions/plugins/google-workspace/assets/icon.pngnew file mode 100644index 0000000..b204fe2Binary files /dev/null and b/extensions/plugins/google-workspace/assets/icon.png differdiff --git a/extensions/plugins/google-workspace/package.json b/extensions/plugins/google-workspace/package.jsonnew file mode 100644index 0000000..bc27787--- /dev/null+++ b/extensions/plugins/google-workspace/package.json@@ -0,0 +1,24 @@+{+ "name": "@go-bot/plugin-google-workspace",+ "version": "0.1.0",+ "type": "module",+ "description": "Use Gmail, Drive, Calendar, Docs, Sheets and Slides with the official gws CLI and upstream Skills.",+ "license": "MIT",+ "exports": "./src/index.mjs",+ "files": [+ "src/",+ "scripts/",+ "skills/",+ "plugin.json",+ "assets/",+ "LICENSE",+ "UPSTREAM_LICENSE",+ "THIRD_PARTY_NOTICES.md"+ ],+ "goBot": {+ "api": "1"+ },+ "scripts": {+ "postinstall": "node ./scripts/install.mjs"+ }+}diff --git a/extensions/plugins/google-workspace/plugin.json b/extensions/plugins/google-workspace/plugin.jsonnew file mode 100644index 0000000..32f40ed--- /dev/null+++ b/extensions/plugins/google-workspace/plugin.json@@ -0,0 +1,25 @@+{+ "name": "Google Workspace",+ "description": {+ "en": "Use Gmail, Drive, Calendar, Docs, Sheets and Slides with the official gws CLI and upstream Skills.\n\n1. Create or select your own project at [Google Cloud Console](https://console.cloud.google.com/). In APIs & Services → Library, enable only the APIs you need: Drive, Gmail, Calendar, Docs, Sheets or Slides.\n2. Configure Google Auth Platform branding and an External audience. While the app is in Testing, add the Google account email you will sign in with under Audience → Test users. This is your Google email, not your Go Bot username.\n3. Open Clients → Create client → Desktop app. Download and keep the OAuth client JSON immediately after creation; an existing client may no longer offer the original secret for download. See [Desktop OAuth client guide](https://developers.google.com/workspace/guides/create-credentials#desktop-app).\n4. Install and enable this plugin. Open Accounts and authorization → Connect Google account. On Web, choose the downloaded JSON file to parse and submit it automatically. On mobile, paste its contents into the protected input on first connection; later connections reuse your native configuration.\n5. Choose read-only or read-and-write permissions. Open the link in your browser, sign in to Google and approve access.\n6. Copy the complete localhost redirect URL from the address bar into the panel, even if the local page cannot open.\n\nThe project does not supply a shared OAuth application. gws stores your application configuration and account tokens in your Host and refreshes tokens natively. Never paste credentials in chat.\n\nEnable APIs as needed; a disabled API cannot be used even after account authorization. Google controls quotas, app verification and organization access. Personal Google accounts are supported; these features do not require a paid Workspace subscription. The upstream CLI is not an officially supported Google product.\n\nUpstream guide: [gws authentication](https://github.com/googleworkspace/cli#authentication)\n\nRetrieved content enters your Agent context and may be processed by your selected model provider.",+ "zh-CN": "通过原生 gws CLI 和上游 Skills 使用 Gmail、Drive、日历、文档、表格与幻灯片。\n\n1. 在 [Google Cloud Console](https://console.cloud.google.com/) 创建或选择自己的项目。在「API 和服务 → 库」中按需启用 Drive、Gmail、Calendar、Docs、Sheets 或 Slides API,无需一次全部开启。\n2. 配置 Google Auth Platform 的品牌信息与「外部」受众。应用处于「测试」状态时,在「受众 → 测试用户」中添加准备登录的 Google 邮箱。这里不是 Go Bot 本地账号名。\n3. 打开「客户端 → 创建客户端」,类型选择「桌面应用(Desktop app)」,创建成功后立即下载并保管 OAuth 客户端 JSON,旧客户端页面可能无法再次下载原始密钥。官方说明:[Desktop OAuth client guide](https://developers.google.com/workspace/guides/create-credentials#desktop-app)。\n4. 安装并启用插件,打开「账号与授权 → 连接 Google 账号」,首次连接时,Web 选择下载的 JSON 文件后自动解析并提交;移动端在受保护输入框中粘贴 JSON 内容,后续连接复用原生配置。\n5. 选择只读或读写权限,在自己的浏览器中打开链接,登录 Google 并同意授权。\n6. 将地址栏中的完整 localhost 回跳地址粘贴回面板,即使该页面打不开。\n\n项目不提供共享 OAuth 应用。gws 在你的 Host 中原生保存应用配置与账号令牌,并刷新令牌。凭证不要粘贴到聊天中。\n\nAPI 按需启用:账号授权成功不代表未开启的 API 也能使用。Google 控制配额、应用验证与组织访问。支持个人 Google 账号,上述能力无需购买 Workspace 企业订阅。上游 CLI 并非 Google 正式支持的产品。\n\n上游指引:[gws authentication](https://github.com/googleworkspace/cli#authentication)\n\n检索内容会进入你的 Agent 上下文,并可能交给你选择的模型服务处理。"+ },+ "icon": "/assets/plugins/google-workspace/icon.png",+ "version": "0.1.0",+ "maintainer": "Go Bot",+ "license": "MIT",+ "tutorials": [+ {+ "language": "en",+ "title": "Set up your Google application and enable APIs as needed",+ "video": "/assets/plugins/google-workspace/account-setup.en.mp4",+ "poster": "/assets/plugins/google-workspace/account-setup.en.png"+ },+ {+ "language": "zh-CN",+ "title": "创建自己的 Google 应用并按需启用 API",+ "video": "/assets/plugins/google-workspace/account-setup.zh-CN.mp4",+ "poster": "/assets/plugins/google-workspace/account-setup.zh-CN.png"+ }+ ]+}diff --git a/extensions/plugins/google-workspace/scripts/install.mjs b/extensions/plugins/google-workspace/scripts/install.mjsnew file mode 100644index 0000000..dba4de1--- /dev/null+++ b/extensions/plugins/google-workspace/scripts/install.mjs@@ -0,0 +1,6 @@+import { nativeDirectory } from '../src/native-cli.mjs'+import path from 'node:path'+import { execFileSync } from 'node:child_process'+await nativeDirectory('google-workspace',path.join(process.env.HOME||'/root','.config','gws'))+execFileSync('npm', ['install', '-g', '@googleworkspace/cli'], { stdio: 'inherit' })+execFileSync('gws', ['--version'], { stdio: 'inherit' })diff --git a/extensions/plugins/google-workspace/src/index.mjs b/extensions/plugins/google-workspace/src/index.mjsnew file mode 100644index 0000000..43d4294--- /dev/null+++ b/extensions/plugins/google-workspace/src/index.mjs@@ -0,0 +1,70 @@+import { readFile } from 'node:fs/promises'+import path from 'node:path'+import { nativeDirectory, privateJSON, run, interactive, relayRedirect } from './native-cli.mjs'+export const name='google-workspace'+export const inject=['host']+const scopes={+ readonly:['https://www.googleapis.com/auth/drive.readonly','https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/calendar.readonly','https://www.googleapis.com/auth/documents.readonly','https://www.googleapis.com/auth/spreadsheets.readonly','https://www.googleapis.com/auth/presentations.readonly'],+ readwrite:['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/documents','https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/presentations'],+}+export function desktopClient(value){+ let json;try{json=JSON.parse(value)}catch{throw new Error('Enter a valid Google Desktop OAuth client JSON.')}+ if(typeof json?.installed?.client_id!=='string'||!json.installed.client_id.trim()||typeof json.installed.client_secret!=='string'||!json.installed.client_secret.trim())throw new Error('Use a Google OAuth client of type Desktop app, with an installed object.')+ if(json.installed.auth_uri && json.installed.auth_uri!=='https://accounts.google.com/o/oauth2/auth')throw new Error('Unsupported Google authorization endpoint.')+ if(json.installed.token_uri && !['https://oauth2.googleapis.com/token','https://accounts.google.com/o/oauth2/token'].includes(json.installed.token_uri))throw new Error('Unsupported Google token endpoint.')+ return {installed:{client_id:json.installed.client_id,client_secret:json.installed.client_secret,project_id:json.installed.project_id||'',auth_uri:'https://accounts.google.com/o/oauth2/auth',token_uri:'https://oauth2.googleapis.com/token',redirect_uris:['http://localhost']}}+}+// Application configuration belongs to this user's native gws directory.+async function nativeClient(directory){+ try { return desktopClient(await readFile(path.join(directory,'client_secret.json'),'utf8')) }+ catch(error){+ if(error.code==='ENOENT')return undefined+ throw new Error('Could not read the saved Google Desktop application configuration. Restore its client_secret.json and try again.')+ }+}+async function nativeStatus(signal,env=process.env){+ const {stdout}=await run('gws',['auth','status'],{signal,env})+ let status;try{status=JSON.parse(stdout)}catch{throw new Error('Could not read the native Google Workspace authorization status.')}+ if(status.encryption_valid===false)throw new Error('Google Workspace credentials cannot be decrypted. Restore the original native encryption key or reconnect.')+ return status+}+export async function inspectAccount(signal){+ const status=await nativeStatus(signal)+ // A missing live check may just mean the network is unavailable. An explicit+ // native invalid-token result, however, must not be displayed as connected.+ const configured=status.auth_method==='oauth2'&&status.has_refresh_token===true&&status.token_valid!==false+ return {configured,...(configured&&typeof status.user==='string'?{accountLabel:status.user}:{})}+}+export async function apply(ctx){+ const directory=await nativeDirectory('google-workspace',path.join(process.env.HOME||'/root','.config','gws'))+ await run('gws',['--version'])+ await ctx.host.skills.registerDirectory('skills')+ await ctx.host.authorization.register({key:'account',title:'Google Workspace',methods:[{id:'oauth',label:'Connect Google account'}],+ inspect:({signal})=>inspectAccount(signal),+ disconnect:async({signal})=>{await run('gws',['auth','logout'],{signal})},+ run:async session=>authorize(session,directory),+ })+ await ctx.host.prompts.register({id:'account-access',location:'system',text:'Use the installed upstream Google Workspace Skills and gws CLI for Workspace tasks. Account connection and permission changes belong in the Google Workspace plugin authorization panel. Never run interactive gws auth commands, export tokens, or ask for OAuth secrets in chat. If access is missing or insufficient, ask the user to connect or authorize again in the plugin market.'})+}++export async function authorize(session,directory){+ let client=await nativeClient(directory)+ const firstConnection=!client+ if(firstConnection){+ client=desktopClient(await session.prompt({kind:'secret',webInput:'json-file',message:'Paste your Google Desktop OAuth client JSON downloaded from Google Cloud.',placeholder:'{"installed":{"client_id":"…","client_secret":"…"}}'}))+ }+ const permission=await session.prompt({kind:'select',message:'Choose the Google Workspace permissions to request.',options:[{id:'readonly',label:'Read only',description:'Read Gmail, Drive, Calendar, Docs, Sheets and Slides.'},{id:'readwrite',label:'Read and write',description:'Also edit documents, manage files and calendars, and modify Gmail. No Admin permissions.'}]})+ if(!scopes[permission])throw new Error('Select an offered permission level.')+ if(firstConnection)await privateJSON(path.join(directory,'client_secret.json'),client)+ const cli=interactive('gws',['auth','login','--scopes',scopes[permission].join(',')],{signal:session.signal,acceptURL:u=>u.protocol==='https:'&&u.hostname==='accounts.google.com'&&u.searchParams.has('redirect_uri')})+ try{+ const url=await cli.url, redirect=url.searchParams.get('redirect_uri')+ // Validate the generated listener before asking a user to open the URL.+ const local=new URL(redirect)+ if(local.protocol!=='http:'||!['localhost','127.0.0.1','[::1]'].includes(local.hostname)||!local.port)throw new Error('gws did not offer a supported loopback callback.')+ await session.notify({url:url.href,message:'Sign in to Google in your browser. After consent, copy the complete localhost redirect URL from the address bar, even if that page cannot open.'})+ const pasted=await Promise.race([session.prompt({kind:'text',message:'First open the authorization link above and approve access in your browser. Then paste the complete Google redirect URL from the address bar.',placeholder:'http://localhost:PORT/callback?state=…&code=…'}),cli.done.then(()=>{throw new Error('The authorization process ended. Start again.')})])+ await relayRedirect(pasted,redirect,url.searchParams.get('state'),session.signal)+ await cli.done+ }finally{cli.stop()}+}diff --git a/extensions/plugins/google-workspace/src/native-cli.mjs b/extensions/plugins/google-workspace/src/native-cli.mjsnew file mode 100644index 0000000..9531bba--- /dev/null+++ b/extensions/plugins/google-workspace/src/native-cli.mjs@@ -0,0 +1,94 @@+import { execFile, spawn } from 'node:child_process'+import { promisify } from 'node:util'+import { mkdir, lstat, readlink, symlink, chmod, writeFile, rename, rmdir } from 'node:fs/promises'+import path from 'node:path'+import http from 'node:http'+const exec = promisify(execFile)+export async function run(command, args, {signal, env = process.env} = {}) {+ try { return await exec(command, args, {signal, env, encoding:'utf8', timeout:30_000, maxBuffer:128 << 10}) }+ catch (error) { if (signal?.aborted) throw signal.reason; throw new Error(`${command} failed. Check the native application configuration and try again.`) }+}+export async function nativeDirectory(id, nativePath) {+ const root = path.resolve(process.env.DSH_HOME || '/root/harness/.dsh', 'credentials', id)+ await mkdir(root,{recursive:true,mode:0o700}); await chmod(root,0o700)+ await mkdir(path.dirname(nativePath),{recursive:true,mode:0o700})+ try {+ const info = await lstat(nativePath)+ if(info.isDirectory()) {+ // Some official CLI version checks create an empty default directory.+ // rmdir is atomic and refuses nonempty directories; never move/delete+ // unknown credential data to make activation appear successful.+ try { await rmdir(nativePath) } catch { throw new Error(`Refusing to replace an existing native credential location: ${nativePath}`) }+ await symlink(root,nativePath,'dir')+ } else if (!info.isSymbolicLink() || path.resolve(path.dirname(nativePath),await readlink(nativePath)) !== root) throw new Error(`Refusing to replace an existing native credential location: ${nativePath}`)+ } catch (error) {+ if(error.code !== 'ENOENT') throw error+ await symlink(root,nativePath,'dir')+ }+ return root+}+export async function privateJSON(file, value) { return privateBytes(file, JSON.stringify(value)) }+export async function privateBytes(file, value) {+ const temp = file + '.tmp'+ try { await writeFile(temp, value, {mode:0o600}); await chmod(temp,0o600); await rename(temp,file) }+ finally { const {rm} = await import('node:fs/promises'); await rm(temp,{force:true}) }+}+// Return only reviewed diagnostic categories, never native stdout/stderr:+// OAuth failures may otherwise echo application secrets or one-time codes.+function authorizationFailure(command, output) {+ for (const [code, message] of [+ ['invalid_client', 'The provider rejected the application credentials (invalid_client). Check the app Client ID and Client Secret.'],+ ['unauthorized_client', 'The provider does not allow this application to use this authorization flow (unauthorized_client). Check the app type and OAuth settings.'],+ ['invalid_grant', 'The provider rejected the authorization code (invalid_grant). Start again and use the new redirect URL once.'],+ ['invalid_request', 'The provider rejected the authorization request (invalid_request). Check the app callback URL and use a new redirect URL from this attempt.'],+ ['invalid_scope', 'The provider rejected the requested permissions (invalid_scope). Check the app permissions.'],+ ['access_denied', 'The provider denied account access (access_denied). Check the permissions on the authorization page.'],+ ['redirect_uri_mismatch', 'The provider rejected the callback URL (redirect_uri_mismatch). Check the callback registered for this app.'],+ ]) {+ if (new RegExp('\\b' + code + '\\b', 'i').test(output)) return message+ }+ if (/TokenExchangeError/.test(output)) return 'The provider could not exchange the authorization code. Check the application settings and start a new authorization attempt.'+ if (/dial tcp|connection refused|TLS handshake timeout|no such host|network is unreachable/i.test(output)) return 'Could not reach the authorization provider. Check the Host network and try again.'+ return `${command} authorization did not complete. Check your application settings or start again.`+}+export function interactive(command, args, {signal,env=process.env,acceptURL} = {}) {+ const child = spawn(command,args,{env,stdio:['pipe','pipe','pipe'],detached:process.platform !== 'win32'})+ let text='', selected=false, resolveURL,rejectURL+ const url = new Promise((resolve,reject)=>{resolveURL=resolve;rejectURL=reject})+ // Prevent early process errors from becoming unhandled while the UI awaits input.+ url.catch(()=>{})+ const stop = () => { if(child.exitCode!==null||child.signalCode!==null||!child.pid)return; try { process.kill(-child.pid,'SIGTERM') } catch { child.kill() } }+ const kill = () => { if(child.exitCode!==null||child.signalCode!==null||!child.pid)return; stop(); const timer=setTimeout(()=>{try{process.kill(-child.pid,'SIGKILL')}catch{}},2000); timer.unref(); child.once('close',()=>clearTimeout(timer)) }+ const done = new Promise((resolve,reject)=>{+ const fail=()=>reject(new Error(authorizationFailure(command,text)))+ child.once('error',fail)+ child.once('close',code=>{signal?.removeEventListener('abort',kill);if(!selected)rejectURL(new Error(`${command} did not provide an authorization URL.`));if(code===0)resolve();else fail()})+ })+ done.catch(()=>{})+ const collect = data => {+ text += data.toString('utf8')+ if(Buffer.byteLength(text)>128<<10){kill();return}+ for(const raw of text.match(/https?:\/\/[^\s<>"\x1b]+(?=[\s<>"\x1b])/g)||[]) {+ try { const candidate=new URL(raw); if(!selected&&acceptURL(candidate)){selected=true;resolveURL(candidate)} } catch {}+ }+ }+ child.stdout.on('data',collect);child.stderr.on('data',collect)+ child.stdin.on('error',()=>{})+ signal?.addEventListener('abort',kill,{once:true});if(signal?.aborted)kill()+ return {url,done,stop:kill,write:value=>{if(child.exitCode!==null||child.signalCode!==null)throw new Error('Authorization process has ended. Start again.');child.stdin.end(value+'\n')}}+}+export function validateRedirect(value, expected, state) {+ const target=new URL(expected), actual=new URL(value.trim())+ if(actual.origin!==target.origin || actual.pathname!==target.pathname || actual.username || actual.password || actual.hash || !actual.searchParams.get('code') || actual.searchParams.getAll('code').length!==1 || (state && (actual.searchParams.getAll('state').length!==1 || actual.searchParams.get('state')!==state))) throw new Error('Paste the complete redirect URL from this authorization attempt.')+ return actual+}+// Relay only to the current native CLI listener. Never follow redirects or fetch+// arbitrary user URLs; provider token exchange remains entirely in the CLI.+export async function relayRedirect(value, expected, state, signal) {+ const actual=validateRedirect(value,expected,state), target=new URL(expected)+ if(target.protocol!=='http:' || !['localhost','127.0.0.1','[::1]'].includes(target.hostname) || !target.port) throw new Error('The native application did not provide a supported loopback callback.')+ await new Promise((resolve,reject)=>{+ const request=http.request({hostname:target.hostname==='localhost'?'127.0.0.1':target.hostname.replace(/^\[|\]$/g,''),port:target.port,path:actual.pathname+actual.search,method:'GET',signal,timeout:10_000},response=>{response.resume();response.on('end',()=>response.statusCode>=200&&response.statusCode<300?resolve():reject(new Error('The native callback was not accepted.')))})+ request.on('error',()=>reject(new Error('Could not reach the native authorization callback. Start again.')));request.on('timeout',()=>request.destroy());request.end()+ })+}diff --git a/extensions/plugins/manifest.go b/extensions/plugins/manifest.gonew file mode 100644index 0000000..92d0852--- /dev/null+++ b/extensions/plugins/manifest.go@@ -0,0 +1,76 @@+// Package plugins supplies reviewed first-party display metadata without loading JavaScript.+package plugins++import (+ "embed"+ "encoding/json"+ "fmt"+ "go-bot/plugin"+ "strings"+)++//go:embed */plugin.json */package.json */assets/*+var files embed.FS++// Metadata reads display copy from plugin.json and package identity from package.json.+// The catalog contains only the release selection and installation policy.+func Metadata(id string) (plugin.CatalogEntry, error) {+ var display struct {+ Name string `json:"name"`+ Description plugin.Localized `json:"description"`+ Version string `json:"version"`+ Maintainer string `json:"maintainer"`+ License string `json:"license"`+ Icon string `json:"icon"`+ Tutorials []plugin.Tutorial `json:"tutorials"`+ }+ raw, err := files.ReadFile(id + "/plugin.json")+ if err != nil {+ return plugin.CatalogEntry{}, err+ }+ if err = json.Unmarshal(raw, &display); err != nil {+ return plugin.CatalogEntry{}, err+ }+ raw, err = files.ReadFile(id + "/package.json")+ if err != nil {+ return plugin.CatalogEntry{}, err+ }+ var pkg struct{ Name, Version, License string }+ if err = json.Unmarshal(raw, &pkg); err != nil {+ return plugin.CatalogEntry{}, err+ }+ if display.Version != pkg.Version || display.License != pkg.License {+ return plugin.CatalogEntry{}, fmt.Errorf("%s: plugin.json version/license must match package.json", id)+ }+ if display.Name == "" {+ return plugin.CatalogEntry{}, fmt.Errorf("%s: plugin display name is missing", id)+ }+ if !strings.HasPrefix(display.Icon, AssetPrefix+id+"/") {+ return plugin.CatalogEntry{}, fmt.Errorf("%s: icon must reference the plugin's backend assets", id)+ }+ if _, err := Asset(display.Icon); err != nil {+ return plugin.CatalogEntry{}, fmt.Errorf("%s: plugin icon: %w", id, err)+ }+ languages := map[string]bool{}+ for _, tutorial := range display.Tutorials {+ if (tutorial.Language != "en" && tutorial.Language != "zh-CN") || languages[tutorial.Language] || strings.TrimSpace(tutorial.Title) == "" {+ return plugin.CatalogEntry{}, fmt.Errorf("%s: invalid tutorial language/title", id)+ }+ languages[tutorial.Language] = true+ for _, asset := range []string{tutorial.Video, tutorial.Poster} {+ if asset == "" && asset == tutorial.Poster {+ continue+ }+ if !strings.HasPrefix(asset, AssetPrefix+id+"/") {+ return plugin.CatalogEntry{}, fmt.Errorf("%s: tutorial must reference its backend assets", id)+ }+ if _, err := Asset(asset); err != nil {+ return plugin.CatalogEntry{}, fmt.Errorf("%s: tutorial asset: %w", id, err)+ }+ }+ if !strings.HasSuffix(tutorial.Video, ".mp4") {+ return plugin.CatalogEntry{}, fmt.Errorf("%s: tutorial video must be MP4", id)+ }+ }+ return plugin.CatalogEntry{Tutorials: display.Tutorials, ID: id, Package: pkg.Name, Version: display.Version, Name: display.Name, Description: display.Description, Icon: display.Icon, Maintainer: display.Maintainer, License: display.License}, nil+}diff --git a/extensions/plugins/officecli/LICENSE b/extensions/plugins/officecli/LICENSEnew file mode 100644index 0000000..09f7d46--- /dev/null+++ b/extensions/plugins/officecli/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Go Harness contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/extensions/plugins/officecli/THIRD_PARTY_NOTICES.md b/extensions/plugins/officecli/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..cdf3b7c--- /dev/null+++ b/extensions/plugins/officecli/THIRD_PARTY_NOTICES.md@@ -0,0 +1,3 @@+# Third-party notices++Original Skills are supplied unchanged by [officecli](https://github.com/iOfficeAI/OfficeCLI) under its Apache-2.0 license. The upstream LICENSE is included with the assembled Skills. CLI installation uses the official npm package without a version pin; the upstream installer retains its own integrity checks.diff --git a/extensions/plugins/officecli/UPSTREAM_LICENSE b/extensions/plugins/officecli/UPSTREAM_LICENSEnew file mode 100644index 0000000..1155f8a--- /dev/null+++ b/extensions/plugins/officecli/UPSTREAM_LICENSE@@ -0,0 +1,203 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to the Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by the Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding any notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. Please also get an+ OpenSourceInitiative.org approved license identifier and put it+ in the first line of your license text file.++ SPDX-License-Identifier: Apache-2.0++ Copyright 2026 OfficeCLI (https://OfficeCLI.AI)++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied. See the License for the specific language governing+ permissions and limitations under the License.diff --git a/extensions/plugins/officecli/assets/icon.png b/extensions/plugins/officecli/assets/icon.pngnew file mode 100644index 0000000..760b366Binary files /dev/null and b/extensions/plugins/officecli/assets/icon.png differdiff --git a/extensions/plugins/officecli/package.json b/extensions/plugins/officecli/package.jsonnew file mode 100644index 0000000..e54d7e3--- /dev/null+++ b/extensions/plugins/officecli/package.json@@ -0,0 +1,24 @@+{+ "name": "@go-bot/plugin-officecli",+ "version": "0.1.0",+ "type": "module",+ "description": "Official officecli CLI and upstream Skills for Go Bot",+ "license": "MIT",+ "exports": "./src/index.mjs",+ "files": [+ "src/",+ "skills/",+ "THIRD_PARTY_NOTICES.md",+ "LICENSE",+ "UPSTREAM_LICENSE",+ "scripts/",+ "plugin.json",+ "assets/"+ ],+ "goBot": {+ "api": "1"+ },+ "scripts": {+ "postinstall": "node ./scripts/install.mjs"+ }+}diff --git a/extensions/plugins/officecli/plugin.json b/extensions/plugins/officecli/plugin.jsonnew file mode 100644index 0000000..1142093--- /dev/null+++ b/extensions/plugins/officecli/plugin.json@@ -0,0 +1,11 @@+{+ "name": "OfficeCLI",+ "description": {+ "en": "Create, read and edit Word, PowerPoint and Excel with the official CLI and 11 upstream Skills.",+ "zh-CN": "通过官方 CLI 和 11 个原始 Skills 创建、读取和编辑 Word、PPT、Excel。"+ },+ "icon": "/assets/plugins/officecli/icon.png",+ "version": "0.1.0",+ "maintainer": "Go Bot",+ "license": "MIT"+}diff --git a/extensions/plugins/officecli/scripts/install.mjs b/extensions/plugins/officecli/scripts/install.mjsnew file mode 100644index 0000000..78aecd6--- /dev/null+++ b/extensions/plugins/officecli/scripts/install.mjs@@ -0,0 +1,5 @@+import { run } from '../src/cli.mjs'+import { verify } from '../src/prepare.mjs'+// Standard lifecycle installation. Cordis apply/dispose never installs software.+await run('npm', ['install', '-g', '@officecli/officecli'])+await verify()diff --git a/extensions/plugins/officecli/src/cli.mjs b/extensions/plugins/officecli/src/cli.mjsnew file mode 100644index 0000000..c207f42--- /dev/null+++ b/extensions/plugins/officecli/src/cli.mjs@@ -0,0 +1,14 @@+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+const exec = promisify(execFile)+export async function run(binary, args, options = {}) {+ return exec(binary, args, { encoding: 'utf8', timeout: 10 * 60_000, maxBuffer: 2 << 20, ...options })+}+export async function verifyCLI(command) {+ try {+ const value = (await run(command, ['--version'])).stdout.trim()+ if (!value) throw new Error(`${command} did not report its version`)+ } catch (error) {+ throw new Error(`${command} is not ready. Reinstall the plugin to prepare its dependencies. ${error.message}`)+ }+}diff --git a/extensions/plugins/officecli/src/index.mjs b/extensions/plugins/officecli/src/index.mjsnew file mode 100644index 0000000..8e4c23d--- /dev/null+++ b/extensions/plugins/officecli/src/index.mjs@@ -0,0 +1,7 @@+import { verify } from './prepare.mjs'+export const name = 'officecli'+export const inject = ['host']+export async function apply(ctx) {+ await verify()+ await ctx.host.skills.registerDirectory('skills')+}diff --git a/extensions/plugins/officecli/src/prepare.mjs b/extensions/plugins/officecli/src/prepare.mjsnew file mode 100644index 0000000..3267a7e--- /dev/null+++ b/extensions/plugins/officecli/src/prepare.mjs@@ -0,0 +1,4 @@+import { verifyCLI } from './cli.mjs'+export async function verify() {+ await verifyCLI('officecli')+}diff --git a/extensions/plugins/prepare-assets.sh b/extensions/plugins/prepare-assets.shnew file mode 100755index 0000000..6bb48af--- /dev/null+++ b/extensions/plugins/prepare-assets.sh@@ -0,0 +1,43 @@+#!/usr/bin/env bash+# Assemble original upstream Skills into first-party plugin packages.+# Runs in a disposable Docker build stage; no CLI is copied into the Host image.+set -euo pipefail+cd "$(dirname "$0")"+export DISABLE_TELEMETRY=1+node agent-browser/scripts/install.mjs+node officecli/scripts/install.mjs+work="$(mktemp -d)"+trap 'rm -rf "$work"' EXIT+(+ cd "$work"+ npx --yes [email protected] add vercel-labs/agent-browser#1cc19526f3641c8543d55aa6700e7c55b37ac356 --skill agent-browser --agent codex --copy --yes+)+mkdir -p agent-browser/skills+cp -a "$work/.agents/skills/agent-browser" agent-browser/skills/+mkdir -p "$work/home/.agents"+export HOME="$work/home" DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1+# Official installer exports complete embedded resources, not just SKILL.md.+officecli skills codex+for skill in word excel pptx academic-paper data-dashboard financial-model pitch-deck word-form morph-ppt morph-ppt-3d; do+ officecli skills install "$skill" codex+done+cp -a "$HOME/.agents/skills" officecli/+for skill in officecli officecli-docx officecli-xlsx officecli-pptx officecli-academic-paper officecli-data-dashboard officecli-financial-model officecli-pitch-deck officecli-word-form morph-ppt morph-ppt-3d; do+ test -s "officecli/skills/$skill/SKILL.md"+done+test -s officecli/skills/morph-ppt/reference/styles/INDEX.md+test -s agent-browser/skills/agent-browser/SKILL.md+# Original upstream licenses are source-controlled with each wrapper.+test -s agent-browser/UPSTREAM_LICENSE+test -s officecli/UPSTREAM_LICENSE++# Official Skills CLI copies complete original Google Workspace Skills/resources.+mkdir -p "$work/gws"+(+ cd "$work/gws"+ npx --yes [email protected] add googleworkspace/cli#cd3697e07eb520056dcf142d0c7439bbb9ba32e9 --skill '*' --agent codex --copy --yes+)+cp -a "$work/gws/.agents/skills" google-workspace/+test -s google-workspace/skills/gws-shared/SKILL.md+test -s google-workspace/skills/gws-gmail/SKILL.md+test -s google-workspace/UPSTREAM_LICENSEdiff --git a/extensions/plugins/x/LICENSE b/extensions/plugins/x/LICENSEnew file mode 100644index 0000000..09f7d46--- /dev/null+++ b/extensions/plugins/x/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Go Harness contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/extensions/plugins/x/THIRD_PARTY_NOTICES.md b/extensions/plugins/x/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..0848c38--- /dev/null+++ b/extensions/plugins/x/THIRD_PARTY_NOTICES.md@@ -0,0 +1,3 @@+# Third-party notices++Uses the official [xdevplatform/xurl](https://github.com/xdevplatform/xurl) CLI. Its original license is in UPSTREAM_LICENSE. The unmodified X App icon is from https://abs.twimg.com/responsive-web/client-web/icon-ios.77d25eba.png. X names and marks belong to X Corp.diff --git a/extensions/plugins/x/UPSTREAM_LICENSE b/extensions/plugins/x/UPSTREAM_LICENSEnew file mode 100644index 0000000..06ed0e5--- /dev/null+++ b/extensions/plugins/x/UPSTREAM_LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2024 Santiago Medina Rolong++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.\ No newline at end of filediff --git a/extensions/plugins/x/assets/account-setup.en.mp4 b/extensions/plugins/x/assets/account-setup.en.mp4new file mode 100644index 0000000..4fad8d0Binary files /dev/null and b/extensions/plugins/x/assets/account-setup.en.mp4 differdiff --git a/extensions/plugins/x/assets/account-setup.en.png b/extensions/plugins/x/assets/account-setup.en.pngnew file mode 100644index 0000000..1c70c7cBinary files /dev/null and b/extensions/plugins/x/assets/account-setup.en.png differdiff --git a/extensions/plugins/x/assets/account-setup.zh-CN.mp4 b/extensions/plugins/x/assets/account-setup.zh-CN.mp4new file mode 100644index 0000000..5c356c6Binary files /dev/null and b/extensions/plugins/x/assets/account-setup.zh-CN.mp4 differdiff --git a/extensions/plugins/x/assets/account-setup.zh-CN.png b/extensions/plugins/x/assets/account-setup.zh-CN.pngnew file mode 100644index 0000000..1ef38b3Binary files /dev/null and b/extensions/plugins/x/assets/account-setup.zh-CN.png differdiff --git a/extensions/plugins/x/assets/icon.png b/extensions/plugins/x/assets/icon.pngnew file mode 100644index 0000000..9b423c6Binary files /dev/null and b/extensions/plugins/x/assets/icon.png differdiff --git a/extensions/plugins/x/package-lock.json b/extensions/plugins/x/package-lock.jsonnew file mode 100644index 0000000..ccb1825--- /dev/null+++ b/extensions/plugins/x/package-lock.json@@ -0,0 +1,32 @@+{+ "name": "@go-bot/plugin-x",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@go-bot/plugin-x",+ "version": "0.1.0",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "yaml": "^2.8.1"+ }+ },+ "node_modules/yaml": {+ "version": "2.9.1",+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz",+ "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==",+ "license": "ISC",+ "bin": {+ "yaml": "bin.mjs"+ },+ "engines": {+ "node": ">= 14.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/eemeli"+ }+ }+ }+}diff --git a/extensions/plugins/x/package.json b/extensions/plugins/x/package.jsonnew file mode 100644index 0000000..d869133--- /dev/null+++ b/extensions/plugins/x/package.json@@ -0,0 +1,27 @@+{+ "name": "@go-bot/plugin-x",+ "version": "0.1.0",+ "type": "module",+ "description": "Connect X with the official xurl MCP bridge and native account authorization.",+ "license": "MIT",+ "exports": "./src/index.mjs",+ "files": [+ "src/",+ "scripts/",+ "skills/",+ "plugin.json",+ "assets/",+ "LICENSE",+ "UPSTREAM_LICENSE",+ "THIRD_PARTY_NOTICES.md"+ ],+ "goBot": {+ "api": "1"+ },+ "scripts": {+ "postinstall": "node ./scripts/install.mjs"+ },+ "dependencies": {+ "yaml": "^2.8.1"+ }+}diff --git a/extensions/plugins/x/plugin.json b/extensions/plugins/x/plugin.jsonnew file mode 100644index 0000000..e58c524--- /dev/null+++ b/extensions/plugins/x/plugin.json@@ -0,0 +1,25 @@+{+ "name": "X",+ "description": {+ "en": "Connect X with the official xurl MCP bridge and native account authorization.\n\n1. Create an app at [X Developer Portal](https://developer.x.com/) and enable OAuth 2.0 user authentication. Choose the app permissions you need.\n2. Register `http://localhost:8080/callback` as the callback URL. Obtain your Client ID and Client Secret (for a public Native App, leave the secret empty even if the console shows a secret value).\n3. Install and enable X. Open Accounts and authorization → Connect X account. Enter your application credentials when prompted on first connection.\n4. Open the authorization link in your browser, sign in to X and approve access. Paste the complete redirect URL back into the panel, even if its localhost page cannot open. Submit it immediately: X authorization codes expire after 30 seconds.\n\nxurl saves the application settings and account tokens in your Host and refreshes tokens natively. Subsequent authorization reuses the application configuration. Disconnect removes only the active account token. X API usage is billed to your developer application/account; review its access, credits and spending limit.\n\nUpstream guide: [xurl authentication](https://github.com/xdevplatform/xurl#authentication)\n\nRetrieved content enters your Agent context and may be processed by your selected model provider.",+ "zh-CN": "通过官方 xurl MCP 桥连接 X,使用原生账号授权。\n\n1. 在 [X Developer Portal](https://developer.x.com/) 创建应用,启用 OAuth 2.0 用户认证并选择需要的应用权限。\n2. 登记回调地址 `http://localhost:8080/callback`,获取 Client ID 和 Client Secret(公共 Native App 请将 Secret 留空,即使控制台仍显示 Secret 值)。\n3. 安装并启用 X,打开「账号与授权」→「连接 X 账号」,首次连接按提示填写应用凭证。\n4. 在自己的浏览器中打开授权链接,登录 X 并同意权限。将完整回跳地址粘贴回面板,即使 localhost 页面打不开。请立即提交,X 授权码只有 30 秒有效。\n\nxurl 在你的 Host 中原生保存应用配置与账号令牌,并刷新令牌;后续授权复用应用配置。退出授权只移除当前账号令牌。X API 调用由你自己的开发者应用/账户计费,请核对访问权限、额度与消费限额。\n\n上游指引:[xurl authentication](https://github.com/xdevplatform/xurl#authentication)\n\n检索内容会进入你的 Agent 上下文,并可能交给你选择的模型服务处理。"+ },+ "icon": "/assets/plugins/x/icon.png",+ "version": "0.1.0",+ "maintainer": "Go Bot",+ "license": "MIT",+ "tutorials": [+ {+ "language": "en",+ "title": "Configure your X OAuth application (before Save)",+ "video": "/assets/plugins/x/account-setup.en.mp4",+ "poster": "/assets/plugins/x/account-setup.en.png"+ },+ {+ "language": "zh-CN",+ "title": "配置自己的 X OAuth 应用(录至保存前)",+ "video": "/assets/plugins/x/account-setup.zh-CN.mp4",+ "poster": "/assets/plugins/x/account-setup.zh-CN.png"+ }+ ]+}diff --git a/extensions/plugins/x/scripts/install.mjs b/extensions/plugins/x/scripts/install.mjsnew file mode 100644index 0000000..1e0c10f--- /dev/null+++ b/extensions/plugins/x/scripts/install.mjs@@ -0,0 +1,6 @@+import { nativeDirectory } from '../src/native-cli.mjs'+import path from 'node:path'+import { execFileSync } from 'node:child_process'+await nativeDirectory('x',path.join(process.env.HOME||'/root','.xurl'))+execFileSync('npm', ['install', '-g', '@xdevplatform/xurl'], { stdio: 'inherit' })+execFileSync('xurl', ['--version'], { stdio: 'inherit' })diff --git a/extensions/plugins/x/src/index.mjs b/extensions/plugins/x/src/index.mjsnew file mode 100644index 0000000..02bef51--- /dev/null+++ b/extensions/plugins/x/src/index.mjs@@ -0,0 +1,68 @@+import { readFile } from 'node:fs/promises'+import path from 'node:path'+import { parse } from 'yaml'+import { nativeDirectory, run, interactive, validateRedirect } from './native-cli.mjs'+export const name = 'x'+export const inject = ['host']+export async function nativeAccount(directory) {+ let source+ try { source = await readFile(path.join(directory,'auth.yml'),'utf8') }+ catch(error) { if(error.code==='ENOENT') return {};throw new Error('Could not read the native X authorization store.') }+ if(Buffer.byteLength(source)>2<<20) throw new Error('The native X authorization store is too large.')+ let store+ try {store = parse(source,{maxAliasCount:50})} catch {throw new Error('The native X authorization store is invalid.')}+ const appName=store?.default_app || 'default', app=store?.apps?.[appName]+ const tokens=app?.oauth2_tokens||{}, user=app?.default_user && tokens[app.default_user] ? app.default_user : Object.keys(tokens)[0]+ const token=tokens[user]?.oauth2+ return {appName,app,user,configured:!!(token?.access_token && (token.refresh_token || token.expiration_time*1000>Date.now()))}+}+export async function apply(ctx) {+ const directory=await nativeDirectory('x',path.join(process.env.HOME||'/root','.xurl'))+ await run('xurl',['--version'])+ const inspect=async()=>{const row=await nativeAccount(directory);return {configured:!!row.configured,...(row.configured?{accountLabel:row.user}:{})}}+ const {instanceId}=await ctx.host.info()+ let bridge, connecting=Promise.resolve()+ const closeBridge=async()=>{await connecting; if(bridge){const old=bridge;bridge=undefined;await old.dispose()}}+ const connect=()=>connecting=connecting.catch(()=>{}).then(async()=>{+ if(bridge || !(await inspect()).configured)return+ bridge=await ctx.host.mcp.register({name:'api',connection:{transport:'stdio',command:'xurl',args:['mcp','https://api.x.com/mcp']},toolLoading:'on-demand'})+ })+ await ctx.host.authorization.register({key:'account',title:'X',methods:[{id:'oauth',label:'Connect X account'}],inspect,+ disconnect:async({signal})=>{+ await closeBridge()+ const row=await nativeAccount(directory)+ if(row.user)await run('xurl',['auth','clear','--app',row.appName,'--oauth2-username',row.user],{signal})+ },+ run:async session=>authorize(session,directory),+ })+ ctx.on('host/authorization-changed',event=>{+ if(event.instanceId===instanceId&&event.key==='account'&&event.phase==='authorized') void connect().catch(()=>ctx.logger.warn('X is authorized, but its MCP bridge could not start. Re-enable the plugin to retry.'))+ })+ await ctx.host.prompts.register({id:'account-access',location:'system',text:'Use the X MCP tools for X account actions. If X authorization is missing, ask the user to connect X in the plugin market. Never request OAuth secrets, tokens or callback URLs in chat, and never run interactive X login from an Agent shell.'})+ try{await connect()}catch{ctx.logger.warn('X is authorized, but its MCP bridge could not start. Re-enable the plugin to retry.')}+}++export async function authorize(session,directory){+ const row=await nativeAccount(directory)+ const env={...process.env}+ if(!row.app?.client_id){+ // The setup link already lives in the plugin detail. Keeping it as a+ // second "Continue in browser" notice obscures the real login link.+ await session.notify({message:'Create your X Developer App and enable OAuth 2.0. Register http://localhost:8080/callback as its callback URL. API usage is billed to your developer account.'})+ env.CLIENT_ID=(await session.prompt({kind:'text',message:'Enter your X app Client ID.'})).trim()+ if(!env.CLIENT_ID)throw new Error('X Client ID is required.')+ env.CLIENT_SECRET=(await session.prompt({kind:'secret',message:'Enter the Client Secret only for a Web App / confidential client. For a Native App / public client, leave this empty.'})).trim()+ env.REDIRECT_URI='http://localhost:8080/callback'+ }+ const cli=interactive('xurl',['auth','oauth2','--headless','--app',row.appName||'default'],{signal:session.signal,env,acceptURL:u=>u.protocol==='https:'&&['x.com','twitter.com'].includes(u.hostname)&&u.searchParams.has('redirect_uri')})+ try{+ const url=await cli.url, redirect=url.searchParams.get('redirect_uri'), state=url.searchParams.get('state')+ await session.notify({url:url.href,message:'Sign in to X in your browser. After approval, immediately copy the complete redirect URL here, even if the local page cannot open. X authorization codes expire after 30 seconds.'})+ const pasted=await Promise.race([session.prompt({kind:'text',message:'First open the authorization link above and approve access in your browser. Then paste the complete X redirect URL from the address bar.',placeholder:'http://localhost:8080/callback?state=…&code=…'}),cli.done.then(()=>{throw new Error('The authorization process ended. Start again.')})])+ validateRedirect(pasted,redirect,state)+ cli.write(pasted.trim());await cli.done+ // Native xurl backfills env credentials into the app that now has tokens,+ // so refresh and MCP work without keeping an environment secret around.+ await run('xurl',['auth','status'],{signal:session.signal,env})+ } finally {cli.stop()}+}diff --git a/extensions/plugins/x/src/native-cli.mjs b/extensions/plugins/x/src/native-cli.mjsnew file mode 100644index 0000000..720c2a3--- /dev/null+++ b/extensions/plugins/x/src/native-cli.mjs@@ -0,0 +1,93 @@+import { execFile, spawn } from 'node:child_process'+import { promisify } from 'node:util'+import { mkdir, lstat, readlink, symlink, chmod, writeFile, rename, rmdir } from 'node:fs/promises'+import path from 'node:path'+import http from 'node:http'+const exec = promisify(execFile)+export async function run(command, args, {signal, env = process.env} = {}) {+ try { return await exec(command, args, {signal, env, encoding:'utf8', timeout:30_000, maxBuffer:128 << 10}) }+ catch (error) { if (signal?.aborted) throw signal.reason; throw new Error(`${command} failed. Check the native application configuration and try again.`) }+}+export async function nativeDirectory(id, nativePath) {+ const root = path.resolve(process.env.DSH_HOME || '/root/harness/.dsh', 'credentials', id)+ await mkdir(root,{recursive:true,mode:0o700}); await chmod(root,0o700)+ await mkdir(path.dirname(nativePath),{recursive:true,mode:0o700})+ try {+ const info = await lstat(nativePath)+ if(info.isDirectory()) {+ // Some official CLI version checks create an empty default directory.+ // rmdir is atomic and refuses nonempty directories; never move/delete+ // unknown credential data to make activation appear successful.+ try { await rmdir(nativePath) } catch { throw new Error(`Refusing to replace an existing native credential location: ${nativePath}`) }+ await symlink(root,nativePath,'dir')+ } else if (!info.isSymbolicLink() || path.resolve(path.dirname(nativePath),await readlink(nativePath)) !== root) throw new Error(`Refusing to replace an existing native credential location: ${nativePath}`)+ } catch (error) {+ if(error.code !== 'ENOENT') throw error+ await symlink(root,nativePath,'dir')+ }+ return root+}+export async function privateJSON(file, value) {+ const temp = file + '.tmp'+ try { await writeFile(temp, JSON.stringify(value), {mode:0o600}); await chmod(temp,0o600); await rename(temp,file) }+ finally { const {rm} = await import('node:fs/promises'); await rm(temp,{force:true}) }+}+// Return only reviewed diagnostic categories, never native stdout/stderr:+// OAuth failures may otherwise echo application secrets or one-time codes.+function authorizationFailure(command, output) {+ for (const [code, message] of [+ ['invalid_client', 'The provider rejected the application credentials (invalid_client). Check the app Client ID and Client Secret.'],+ ['unauthorized_client', 'The provider does not allow this application to use this authorization flow (unauthorized_client). Check the app type and OAuth settings.'],+ ['invalid_grant', 'The provider rejected the authorization code (invalid_grant). Start again and use the new redirect URL once.'],+ ['invalid_request', 'The provider rejected the authorization request (invalid_request). Check the app callback URL and use a new redirect URL from this attempt.'],+ ['invalid_scope', 'The provider rejected the requested permissions (invalid_scope). Check the app permissions.'],+ ['access_denied', 'The provider denied account access (access_denied). Check the permissions on the authorization page.'],+ ['redirect_uri_mismatch', 'The provider rejected the callback URL (redirect_uri_mismatch). Check the callback registered for this app.'],+ ]) {+ if (new RegExp('\\b' + code + '\\b', 'i').test(output)) return message+ }+ if (/TokenExchangeError/.test(output)) return 'The provider could not exchange the authorization code. Check the application settings and start a new authorization attempt.'+ if (/dial tcp|connection refused|TLS handshake timeout|no such host|network is unreachable/i.test(output)) return 'Could not reach the authorization provider. Check the Host network and try again.'+ return `${command} authorization did not complete. Check your application settings or start again.`+}+export function interactive(command, args, {signal,env=process.env,acceptURL} = {}) {+ const child = spawn(command,args,{env,stdio:['pipe','pipe','pipe'],detached:process.platform !== 'win32'})+ let text='', selected=false, resolveURL,rejectURL+ const url = new Promise((resolve,reject)=>{resolveURL=resolve;rejectURL=reject})+ // Prevent early process errors from becoming unhandled while the UI awaits input.+ url.catch(()=>{})+ const stop = () => { if(child.exitCode!==null||child.signalCode!==null||!child.pid)return; try { process.kill(-child.pid,'SIGTERM') } catch { child.kill() } }+ const kill = () => { if(child.exitCode!==null||child.signalCode!==null||!child.pid)return; stop(); const timer=setTimeout(()=>{try{process.kill(-child.pid,'SIGKILL')}catch{}},2000); timer.unref(); child.once('close',()=>clearTimeout(timer)) }+ const done = new Promise((resolve,reject)=>{+ const fail=()=>reject(new Error(authorizationFailure(command,text)))+ child.once('error',fail)+ child.once('close',code=>{signal?.removeEventListener('abort',kill);if(!selected)rejectURL(new Error(`${command} did not provide an authorization URL.`));if(code===0)resolve();else fail()})+ })+ done.catch(()=>{})+ const collect = data => {+ text += data.toString('utf8')+ if(Buffer.byteLength(text)>128<<10){kill();return}+ for(const raw of text.match(/https?:\/\/[^\s<>"\x1b]+(?=[\s<>"\x1b])/g)||[]) {+ try { const candidate=new URL(raw); if(!selected&&acceptURL(candidate)){selected=true;resolveURL(candidate)} } catch {}+ }+ }+ child.stdout.on('data',collect);child.stderr.on('data',collect)+ child.stdin.on('error',()=>{})+ signal?.addEventListener('abort',kill,{once:true});if(signal?.aborted)kill()+ return {url,done,stop:kill,write:value=>{if(child.exitCode!==null||child.signalCode!==null)throw new Error('Authorization process has ended. Start again.');child.stdin.end(value+'\n')}}+}+export function validateRedirect(value, expected, state) {+ const target=new URL(expected), actual=new URL(value.trim())+ if(actual.origin!==target.origin || actual.pathname!==target.pathname || actual.username || actual.password || actual.hash || !actual.searchParams.get('code') || actual.searchParams.getAll('code').length!==1 || (state && (actual.searchParams.getAll('state').length!==1 || actual.searchParams.get('state')!==state))) throw new Error('Paste the complete redirect URL from this authorization attempt.')+ return actual+}+// Relay only to the current native CLI listener. Never follow redirects or fetch+// arbitrary user URLs; provider token exchange remains entirely in the CLI.+export async function relayRedirect(value, expected, state, signal) {+ const actual=validateRedirect(value,expected,state), target=new URL(expected)+ if(target.protocol!=='http:' || !['localhost','127.0.0.1','[::1]'].includes(target.hostname) || !target.port) throw new Error('The native application did not provide a supported loopback callback.')+ await new Promise((resolve,reject)=>{+ const request=http.request({hostname:target.hostname==='localhost'?'127.0.0.1':target.hostname.replace(/^\[|\]$/g,''),port:target.port,path:actual.pathname+actual.search,method:'GET',signal,timeout:10_000},response=>{response.resume();response.on('end',()=>response.statusCode>=200&&response.statusCode<300?resolve():reject(new Error('The native callback was not accepted.')))})+ request.on('error',()=>reject(new Error('Could not reach the native authorization callback. Start again.')));request.on('timeout',()=>request.destroy());request.end()+ })+}diff --git a/extensions/sdk/LICENSE b/extensions/sdk/LICENSEnew file mode 100644index 0000000..09f7d46--- /dev/null+++ b/extensions/sdk/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Go Harness contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/extensions/sdk/README.md b/extensions/sdk/README.mdnew file mode 100644index 0000000..4c3de00--- /dev/null+++ b/extensions/sdk/README.md@@ -0,0 +1,148 @@+# Go Bot plugin SDK++The SDK defines `ctx.host`, the asynchronous interface to the Go Host. Plugins+run as trusted JavaScript modules in the Host's shared Cordis process. Go owns+AgentLoop, Sessions, tool execution, permissions, sandboxing and persistence;+Cordis owns dependency injection and plugin lifetimes.++```ts+import type { Context } from '@go-bot/plugin-sdk'+export const inject = ['host']+export async function apply(ctx: Context) {+ await ctx.host.tools.register({+ name: 'ping', description: 'Contact an external integration.',+ inputSchema: { type: 'object', additionalProperties: false },+ async execute(args, call) {+ call.signal.throwIfAborted()+ return { content: [{ type: 'text', text: 'Hello' }] }+ },+ })+}+```++Declare `"goBot": { "api": "1" }` in package.json. Compile TypeScript to JavaScript+before installing the package. For TypeScript development, use the repository-local SDK dependency shown in the+example project. The Host ships this package and its installer pins+`@go-bot/plugin-sdk` to that local copy, including when a business package declares+it as a peer dependency. No published npm SDK is required. Type-only imports are+removed during compilation; runtime exports such as `HostError` also resolve to+the Host-supplied SDK. The SDK itself is not a market plugin.++Normal users install reviewed releases from the project's built-in plugin+market. See [catalog maintenance](../catalog/README.md) for publishing a real+business plugin to that list. Development examples are not market products;+arbitrary source inspection and full settings application are Host-private.++All Go methods return Promises, including registration and queries. Await required+registrations during `apply`. Registrations are accepted individually; Cordis+withdraws their resources on disposal or initialization failure. This is not an+atomic batch activation or a rollback of external side effects.++Registration cancellation waits for Go to settle so a late accepted resource can+still be removed. Non-JSON values such as `Date`, `BigInt` or functions are+rejected instead of silently converted. Return explicit `null` for missing+records. Among callbacks invoked by Go, only authorization `run` may omit a+return value; ordinary Cordis `apply` functions retain their native semantics.++`ctx.host` exposes tools, Skills, appended prompts, credentials, authorization,+MCP, tool-bound approval requests and questions. See `index.d.ts` for signatures.+Tools return ordered text blocks and optional JSON data. Image attachments and+file presentation remain internal Go tools. There are no actions/storage APIs,+Agent/Session proxies, global guards, tool-stage middleware or cross-process next.++Use native Cordis `ctx.on` for the typed `host/*` state notifications. Their return+values do not affect execution. Native local business services and events retain+Cordis semantics. Plugin code can use its own libraries; the Go shell sandbox does+not isolate Node plugins from the container operating system.++## Plugin display metadata++Ship plugin.json with the package. It declares name (original product name),+bilingual description (`en`, `zh-CN`), icon, version, maintainer and license.+The first-party catalog embeds this file and checks version/license against+package.json. Clients render those fields rather than maintaining capability+lists or product copy in components. Host package inspection supplies actual+installed versions; Controller reports availableVersion only for a newer reviewed+SemVer release. Updating reuses the package installation pipeline and preserves+the enabled flag.++## Package installation and activation++Users select one version and enabled flag per reviewed catalog package. Redis+stores that selection only. Go Host serializes operations and waits for pnpm to+install each package and its dependencies. Custom dependency setup belongs in+standard package.json lifecycle scripts, for example:++```json+{"scripts":{"postinstall":"node ./scripts/install.mjs"},"goBot":{"api":"1"}}+```++The reviewed catalog's private builds list grants exact pnpm allowBuilds entries+for that package or explicitly versioned dependency scripts. Public clients+cannot grant script permissions. Unapproved required builds fail installation;+inspection always disables scripts. pnpmfile hooks remain disabled. Side-effect+caching is disabled because first-party CLI installers change global locations.++A package's postinstall must be idempotent and verify its dependencies before+exiting successfully. Go waits for the same pnpm operation; there is no custom+goBot.install API or second installer callback. Native scripts run as trusted+container processes and are cancelled with the package operation. They must not+wait for credential prompts; service authorization happens after activation.++Cordis apply only checks local prerequisites and registers capabilities. Disposal+withdraws registrations without uninstalling software. Uninstall withdraws the+Cordis entry and removes the wrapper with pnpm; credentials, workspaces and+shared/global CLI dependencies are retained. See the first-party packages in+../plugins/agent-browser and ../plugins/officecli.++## Authorization interactions++A plugin registers only the authorization methods its integration implements.+The built-in clients show those methods in that plugin's detail page; they do+not infer OAuth support or display a fixed API-key form for every plugin.+After the user chooses a method, the plugin's `run(session)` requests any inputs+with `await session.prompt(...)` (`text`, `secret` or `select`). The answer+resumes that Promise. Validate it with the service before `session.commit(...)`;+ordinary flows complete only after a committed credential. Native CLI integrations+can instead register `inspect({signal})` and `disconnect({signal})`: after `run`,+Go requires `inspect` to report `{configured:true,accountLabel?}`. Do not create a+fake grant to satisfy completion. `disconnect` performs the CLI logout; Go checks+that `configured` is false. Both callbacks return Promises and stay in the plugin. These inputs are not chat+messages and are not added to model context. Closing the client panel preserves+an active attempt; cancelling explicitly withdraws it. Attempts are transient+Host state and do not survive a Host restart.++Business OAuth implementations can request a controlled browser callback:++```ts+const callback = await session.callback({ state })+// Use callback.url as the provider redirect_uri and session.notify({ message,+// url }) to show the provider's authorization URL.+const query = await callback.wait()+```++Generate `state` and the PKCE verifier with the provider's library. The Host+matches state and accepts a callback once; the plugin remains responsible for+issuer and provider-error validation, PKCE/token exchange, scope checks, refresh+and credential format. Receiving a callback does not save a token or mark the+attempt authorized. Do not put tokens or secrets in notices. Browser callbacks+require HTTPS or localhost HTTP. MCP wrappers use Go's existing MCP OAuth client+rather than implementing this provider flow again.++X and Google Workspace collect each user's own developer application configuration+during authorization. Google requires a downloaded Desktop OAuth client JSON on+first connection and reuses it from the native gws directory thereafter. A text/secret+prompt may set `webInput: "json-file"`: Web offers a JSON file chooser, parses the+file locally and sends the JSON as the same prompt answer; mobile retains the+normal text/secret input. The file is not stored as a chat attachment. The+[connection guide](../../docs/plugin-account-setup.md) explains both. Account tokens+remain in the native CLI store. `ctx.host.info().instanceId` identifies the caller's+existing Cordis instance when filtering Host state notifications; it does not add+another plugin lifecycle manager.++Plugin display metadata can include `tutorials`, an array of+`{language: "en" | "zh-CN", title, video, poster?}`. Media paths refer to backend+plugin assets, for example `/assets/plugins/x/account-setup.zh-CN.mp4`. Only+publish a tutorial entry once its video exists and has been reviewed for exposed+credentials. Web and mobile choose the local interface language, then English,+then the first supplied tutorial. The clients do not hardcode provider media.diff --git a/extensions/sdk/index.d.ts b/extensions/sdk/index.d.tsnew file mode 100644index 0000000..3dadaec--- /dev/null+++ b/extensions/sdk/index.d.ts@@ -0,0 +1,130 @@+import type { Context as CordisContext } from '@deepseek-ai/cordis'++export declare const apiVersion: '1'+export type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }+export type JSONSchema = { [key: string]: JSONValue }+export declare class HostError extends Error {+ readonly code: string+ constructor(code: string, message: string)+}+export interface Registration { readonly id: string; dispose(): Promise<void> }+export interface ToolCall {+ readonly id: string+ readonly sessionId: string+ readonly cwd: string+ readonly workspace: string+ readonly signal: AbortSignal+}+export interface ToolResult { content: { type: 'text'; text: string }[]; data?: JSONValue }+export interface ToolDefinition {+ name: string; description: string; inputSchema: JSONSchema+ concurrency?: 'exclusive' | 'parallel'+ /** Omitted: no additional tool deadline; invocation cancellation still applies. */+ timeoutMs?: number+ execute(args: JSONValue, call: ToolCall): Promise<ToolResult>+}+export interface PreparationContext {+ readonly sessionId: string; readonly cwd: string; readonly workspace: string+ readonly signal: AbortSignal+ readonly model?: { readonly provider: string; readonly name: string }+}+export type ResourceBase = { kind: 'directory'; path: string } | { kind: 'url'; url: string; description?: string }+export interface Skill {+ name: string; description: string; whenToUse?: string+ modelInvocable?: boolean; userInvocable?: boolean; resourceBase?: ResourceBase+}+export interface SkillDefinition extends Skill { content: string }+export interface SkillSummary extends Skill { source: string; provider: string; path?: string }+export interface SkillContext { readonly cwd: string; readonly signal: AbortSignal }+export interface SkillProvider {+ id: string+ list(context: SkillContext): { items: (Skill & { key: JSONValue })[]; complete: boolean } | Promise<{ items: (Skill & { key: JSONValue })[]; complete: boolean }>+ get(key: JSONValue, context: SkillContext): SkillDefinition | null | Promise<SkillDefinition | null>+}+export type CredentialRecord = { kind: 'api-key'; key?: string; env?: Record<string, string> } | { kind: 'grant'; payload: JSONValue }+export interface CredentialDescription { configured: boolean; kind?: CredentialRecord['kind']; writable: boolean }+export interface CredentialSummary { key: string; kind: CredentialRecord['kind'] }+export interface AuthorizationMethod { id: string; label: string }+export interface AuthorizationNotice { message: string; url?: string; code?: string }+export type AuthorizationPrompt = { kind: 'text' | 'secret'; message: string; placeholder?: string; webInput?: 'json-file' }+ | { kind: 'select'; message: string; options: { id: string; label: string; description?: string }[] }+export interface AuthorizationSession {+ readonly method: string; readonly signal: AbortSignal+ notify(notice: AuthorizationNotice): Promise<void>+ prompt(request: AuthorizationPrompt): Promise<string>+ /** One browser callback for this attempt. The provider library supplies state+ * and owns issuer/PKCE/token validation; receiving a callback is not a grant. */+ callback(options: { state: string }): Promise<{ readonly url: string; wait(): Promise<Record<string, string[]>> }>+ commit(record: CredentialRecord): Promise<void>+}+export interface AuthorizationFlow {+ key: string; title: string; methods: AuthorizationMethod[]+ run(session: AuthorizationSession): Promise<void>+ /** Native credential stores may confirm completion without commit(). */+ inspect?(context: {signal: AbortSignal}): Promise<{configured:boolean; accountLabel?:string}>+ disconnect?(context: {signal: AbortSignal}): Promise<void>+}+export interface AuthorizationSummary { key: string; title: string; methods: AuthorizationMethod[]; phase: string }+export interface AuthorizationAttempt { id: string; phase: string; authorizationUrl?: string; lastError?: string }+export interface McpOAuth {+ credentialKey?: string; clientId?: string; clientSecretRef?: string+ scopes?: string[]; scope?: string; requestTimeoutMs?: number; authorizationTimeoutMs?: number+}+export type McpConnection = ({ transport: 'stdio'; command: string; args?: string[]; env?: Record<string, string>; cwd?: string }+ | { transport: 'streamable-http'; url: string; headers?: Record<string, string> }) & { oauth?: McpOAuth }+export interface McpServiceView { name: string; state: string; toolCount: number; error?: string; authorization?: AuthorizationAttempt }+export interface QuestionRequest {+ questions: { id: string; question: string; header?: string; detail?: string; multiSelect?: boolean; options?: { label: string; description?: string }[] }[]+}+export interface QuestionAnswer { answers: { id: string; selected: string[]; custom?: string }[] }+export type ApprovalOutcome = 'allowed' | 'rejected' | 'cancelled' | 'unavailable'+export interface Host {+ info(): Promise<{ userId: string; hostId: string; dataRoot: string; instanceId: string; apiVersion: '1' }>+ tools: { register(definition: ToolDefinition): Promise<Registration> }+ skills: {+ register(skill: SkillDefinition): Promise<Registration>+ registerDirectory(path: string): Promise<Registration>+ registerProvider(provider: SkillProvider): Promise<Registration>+ list(options?: { cwd?: string }): Promise<{ items: SkillSummary[]; complete: boolean }>+ get(name: string, options?: { cwd?: string }): Promise<(SkillSummary & SkillDefinition) | null>+ invalidate(): Promise<void>+ }+ prompts: { register(definition: { id: string; location: 'system' | 'context'; order?: number; text: string | ((context: PreparationContext) => string | Promise<string>) }): Promise<Registration> }+ credentials: {+ get(key: string): Promise<CredentialRecord | null>+ put(key: string, record: CredentialRecord): Promise<void>+ update(key: string, mutate: (current: CredentialRecord | null) => CredentialRecord | null | Promise<CredentialRecord | null>): Promise<CredentialRecord | null>+ remove(key: string): Promise<void>+ describe(key: string): Promise<CredentialDescription>+ list(): Promise<CredentialSummary[]>+ resolve(ref: string): Promise<string | null>+ }+ authorization: {+ register(flow: AuthorizationFlow): Promise<Registration>+ list(): Promise<AuthorizationSummary[]>+ cancel(key: string): Promise<void>+ }+ mcp: {+ register(definition: { name: string; connection: McpConnection; toolLoading?: 'eager' | 'on-demand' }): Promise<Registration>+ list(): Promise<McpServiceView[]>+ inspect(name: string): Promise<McpServiceView | null>+ restart(name: string): Promise<McpServiceView>+ authorize(name: string): Promise<AuthorizationAttempt>+ cancelAuthorization(name: string, attemptId: string): Promise<void>+ signOut(name: string): Promise<void>+ }+ approvals: { request(call: ToolCall, request: { reason: string; detail?: string }): Promise<ApprovalOutcome> }+ questions: { ask(call: ToolCall, request: QuestionRequest): Promise<QuestionAnswer> }+}+export interface HostEvents {+ 'host/skills-changed': (event: { instanceId: string; source?: string }) => void+ 'host/credential-changed': (event: { instanceId: string; key: string; configured: boolean }) => void+ 'host/authorization-changed': (event: { instanceId: string; key: string; phase: string; error?: string }) => void+ 'host/mcp-changed': (event: { instanceId: string; name: string; state: string; error?: string; toolCount: number }) => void+ 'host/stopping': (event: { reason: string }) => void+}+declare module '@deepseek-ai/cordis' {+ interface Context { host: Host }+ interface Events extends HostEvents {}+}+export type Context = CordisContextdiff --git a/extensions/sdk/index.mjs b/extensions/sdk/index.mjsnew file mode 100644index 0000000..6e8ef6c--- /dev/null+++ b/extensions/sdk/index.mjs@@ -0,0 +1,8 @@+export const apiVersion = '1'+export class HostError extends Error {+ constructor(code, message) {+ super(message)+ this.name = 'HostError'+ this.code = code+ }+}diff --git a/extensions/sdk/package.json b/extensions/sdk/package.jsonnew file mode 100644index 0000000..2046c10--- /dev/null+++ b/extensions/sdk/package.json@@ -0,0 +1,34 @@+{+ "name": "@go-bot/plugin-sdk",+ "version": "1.0.0",+ "private": true,+ "description": "TypeScript contracts for plugins running in the Go Bot Host",+ "type": "module",+ "license": "MIT",+ "exports": {+ ".": {+ "types": "./index.d.ts",+ "default": "./index.mjs"+ }+ },+ "files": [+ "index.d.ts",+ "index.mjs",+ "LICENSE",+ "README.md"+ ],+ "scripts": {+ "test": "tsc --noEmit && node --test test/*.test.mjs"+ },+ "dependencies": {+ "@deepseek-ai/cordis": "4.1.0"+ },+ "devDependencies": {+ "@types/node": "24.10.0",+ "typescript": "7.0.2"+ },+ "engines": {+ "node": ">=24.9.0"+ },+ "packageManager": "[email protected]"+}diff --git a/extensions/sdk/pnpm-lock.yaml b/extensions/sdk/pnpm-lock.yamlnew file mode 100644index 0000000..3efb05f--- /dev/null+++ b/extensions/sdk/pnpm-lock.yaml@@ -0,0 +1,271 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: false+ excludeLinksFromLockfile: false++importers:++ .:+ dependencies:+ '@deepseek-ai/cordis':+ specifier: 4.1.0+ version: 4.1.0+ devDependencies:+ '@types/node':+ specifier: 24.10.0+ version: 24.10.0+ typescript:+ specifier: 7.0.2+ version: 7.0.2++packages:++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-CJrjNyBkKn1SfvBQUcgFYKFnLjS+uKrhdMsbHU60xabvi12d+xQ+IQSNlME5Z+B+4Zi6n4BDknKY94tEPeo47w==}+ hasBin: true+ peerDependencies:+ '@deepseek-ai/cordis-plugin-include': ~1.1.0+ '@deepseek-ai/cordis-plugin-loader': ~1.1.0+ peerDependenciesMeta:+ '@deepseek-ai/cordis-plugin-include':+ optional: true+ '@deepseek-ai/cordis-plugin-loader':+ optional: true++ '@deepseek-ai/[email protected]':+ resolution: {integrity: sha512-5O1S53mZiJyZYcvxxD0Qv1EY7qFPSxbGyD8CbVK6gw7W9FvcXZj2YIX1ZkOqyQQ3Xt2rFkZDHJv0+V3Zmmp8CA==}++ '@standard-schema/[email protected]':+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}++ '@types/[email protected]':+ resolution: {integrity: sha512-qzQZRBqkFsYyaSWXuEHc2WR9c0a0CXwiE5FWUvn7ZM+vdy1uZLfCunD38UzhuB7YN/J11ndbDBcTmOdxJo9Q7A==}++ '@typescript/[email protected]':+ resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}+ engines: {node: '>=16.20.0'}+ cpu: [ppc64]+ os: [aix]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [darwin]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [darwin]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [freebsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [freebsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==}+ engines: {node: '>=16.20.0'}+ cpu: [loong64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==}+ engines: {node: '>=16.20.0'}+ cpu: [mips64el]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==}+ engines: {node: '>=16.20.0'}+ cpu: [ppc64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==}+ engines: {node: '>=16.20.0'}+ cpu: [riscv64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==}+ engines: {node: '>=16.20.0'}+ cpu: [s390x]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [netbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [netbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [openbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [openbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [sunos]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [win32]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [win32]++ resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==}+ engines: {node: '>=16.20.0'}+ hasBin: true++ resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}++snapshots:++ '@deepseek-ai/[email protected]':+ dependencies:+ '@deepseek-ai/cosmokit': 1.9.0+ '@standard-schema/spec': 1.1.0++ '@deepseek-ai/[email protected]': {}++ '@standard-schema/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ undici-types: 7.16.0++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ optionalDependencies:+ '@typescript/typescript-aix-ppc64': 7.0.2+ '@typescript/typescript-darwin-arm64': 7.0.2+ '@typescript/typescript-darwin-x64': 7.0.2+ '@typescript/typescript-freebsd-arm64': 7.0.2+ '@typescript/typescript-freebsd-x64': 7.0.2+ '@typescript/typescript-linux-arm': 7.0.2+ '@typescript/typescript-linux-arm64': 7.0.2+ '@typescript/typescript-linux-loong64': 7.0.2+ '@typescript/typescript-linux-mips64el': 7.0.2+ '@typescript/typescript-linux-ppc64': 7.0.2+ '@typescript/typescript-linux-riscv64': 7.0.2+ '@typescript/typescript-linux-s390x': 7.0.2+ '@typescript/typescript-linux-x64': 7.0.2+ '@typescript/typescript-netbsd-arm64': 7.0.2+ '@typescript/typescript-netbsd-x64': 7.0.2+ '@typescript/typescript-openbsd-arm64': 7.0.2+ '@typescript/typescript-openbsd-x64': 7.0.2+ '@typescript/typescript-sunos-x64': 7.0.2+ '@typescript/typescript-win32-arm64': 7.0.2+ '@typescript/typescript-win32-x64': 7.0.2++ [email protected]: {}diff --git a/extensions/sdk/pnpm-workspace.yaml b/extensions/sdk/pnpm-workspace.yamlnew file mode 100644index 0000000..1aec1d9--- /dev/null+++ b/extensions/sdk/pnpm-workspace.yaml@@ -0,0 +1 @@+autoInstallPeers: falsediff --git a/extensions/sdk/test/contracts.ts b/extensions/sdk/test/contracts.tsnew file mode 100644index 0000000..d035ea2--- /dev/null+++ b/extensions/sdk/test/contracts.ts@@ -0,0 +1,42 @@+import { HostError } from '@go-bot/plugin-sdk'+import type { Context, ToolDefinition } from '@go-bot/plugin-sdk'++async function contracts(ctx: Context) {+ const definition: ToolDefinition = {+ name: 'echo', description: 'Echo', inputSchema: { type: 'object' },+ async execute(args, call) {+ call.signal.throwIfAborted()+ const result = await ctx.host.approvals.request(call, { reason: 'Confirm business action' })+ if (result !== 'allowed') throw new HostError('NOT_ALLOWED', 'Action was not approved')+ return { content: [{ type: 'text', text: call.cwd }], data: args }+ },+ }+ const registration = await ctx.host.tools.register(definition)+ await registration.dispose()+ const snapshot = await ctx.host.skills.list()+ snapshot.items[0]?.modelInvocable satisfies boolean | undefined+ await ctx.host.credentials.put('mailbox', { kind: 'grant', payload: { refreshToken: 'example' } })+ await ctx.host.credentials.update('mailbox', async current => current)+ await ctx.host.authorization.register({ key: 'login', title: 'Account', methods: [{ id: 'oauth', label: 'Browser' }], async run(session) {+ const callback = await session.callback({ state: 'generated-by-provider-library' })+ callback.url satisfies string+ const query = await callback.wait()+ query.state satisfies string[] | undefined+ // The real provider library validates its response and exchanges the code+ // before the plugin can commit a credential.+ } })+ const services = await ctx.host.mcp.list()+ services[0]?.state satisfies string | undefined+ ctx.on('host/credential-changed', event => { event.key satisfies string })+ // @ts-expect-error The SDK does not expose arbitrary Go calls.+ ctx.host.call('sessions.append', {})+ // @ts-expect-error Core Session management remains in Go.+ ctx.host.sessions.create({})+ // @ts-expect-error There is no global plugin guard.+ ctx.host.tools.registerGuard({})+ // @ts-expect-error Assets are internal Go capabilities.+ ctx.host.assets.image(new Uint8Array(), {})+ // @ts-expect-error Plugins return text/data, not invented attachment references.+ await ctx.host.tools.register({ ...definition, async execute() { return { content: [{ type: 'image', image: {} }] } } })+}+void contractsdiff --git a/extensions/sdk/test/template.test.mjs b/extensions/sdk/test/template.test.mjsnew file mode 100644index 0000000..534fe34--- /dev/null+++ b/extensions/sdk/test/template.test.mjs@@ -0,0 +1,44 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { mkdtemp, rm, writeFile, readFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'+import { HostRuntime } from '../../cordis/src/host-runtime.mjs'++const run = promisify(execFile)+const sdk = fileURLToPath(new URL('../', import.meta.url))+const repository = fileURLToPath(new URL('../../../', import.meta.url))++test('the TypeScript example runs as JavaScript through native Cordis and Promise Host registration', async t => {+ const directory = await mkdtemp(join(tmpdir(), 'go-bot-sdk-'))+ t.after(() => rm(directory, { recursive: true, force: true }))+ await writeFile(join(directory, 'package.json'), '{"type":"module","private":true}')+ await run(process.execPath, [join(sdk, 'node_modules/typescript/lib/tsc.js'), '-p', join(sdk, 'tsconfig.json'),+ '--noEmit', 'false', '--declaration', '--outDir', directory, '--rootDir', repository])+ const entry = join(directory, 'examples/plugins/typescript-tool/src/index.js')+ assert.ok(!(await readFile(entry, 'utf8')).includes('@go-bot/plugin-sdk'), 'type-only SDK imports leave no deployment dependency')+ const module = await import(pathToFileURL(entry).href)+ const contributions = new Map()+ const runtime = await HostRuntime.create({ directory, loadPackage: async () => ({ module }), call: async (method, input) => {+ if (method === 'contribution.register') {+ const id = input.owner + '/' + input.callbackId+ contributions.set(id, input)+ return { id }+ }+ if (method === 'contribution.remove') contributions.delete(input.registrationId)+ return null+ } })+ t.after(() => runtime.close())+ const loaded = await runtime.apply({ instances: [{ id: 'first', package: 'example', enabled: true }, { id: 'second', package: 'example', enabled: true }] })+ assert.deepEqual(loaded.instances.map(row => row.state), ['ready', 'ready'])+ assert.equal(contributions.size, 2)+ const row = [...contributions.values()][0]+ const result = await runtime.invoke({ owner: row.owner, callbackId: row.callbackId, method: 'execute', args: { text: 'Real compiled plugin' },+ context: { sessionId: 'session', cwd: '/root/harness', workspace: '/root/harness', invocation: 'current-body' } }, new AbortController().signal)+ assert.deepEqual(result, { content: [{ type: 'text', text: 'Real compiled plugin' }], data: { text: 'Real compiled plugin' } })+ await runtime.apply({ instances: [] })+ assert.equal(contributions.size, 0)+})diff --git a/extensions/sdk/tsconfig.json b/extensions/sdk/tsconfig.jsonnew file mode 100644index 0000000..931cf95--- /dev/null+++ b/extensions/sdk/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "ES2023",+ "lib": ["ES2023", "ESNext.Disposable", "DOM"],+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "strict": true,+ "noEmit": true,+ "skipLibCheck": false,+ "types": ["node"],+ "paths": { "@go-bot/plugin-sdk": ["./index.d.ts"] }+ },+ "include": ["index.d.ts", "test/**/*.ts", "../../examples/plugins/typescript-tool/src/*.ts"]+}diff --git a/frontend/README.md b/frontend/README.mdindex 46474f5..eb22768 100644--- a/frontend/README.md+++ b/frontend/README.md@@ -3,7 +3,7 @@Follow the [local Quickstart](../README.md#quickstart) from the repository root and open[http://127.0.0.1:8080/](http://127.0.0.1:8080/). The Controller serves thepage and relays API calls and SSE to the selected account's Docker or ECI Host.-Create or open an account by name. Configure Responses endpoints in Model settings, and use the model picker below a chat to change its model. Add a DeepSeek search API key under **Settings → Web search**.+Create or open an account by name. Configure OpenAI Responses or Anthropic Messages endpoints using the protocol dropdown in Model settings, and use the model picker below a chat to change its model. Under **Settings → Web search**, save a key for DeepSeek, Zhipu, Doubao, Tavily, or Brave Search and choose **Use provider**.For a custom mobile, desktop or web interface, use the Controller's[HTTP and SSE API](../docs/api.md). The [minimal example](../examples/frontend-minimal/index.html)@@ -27,7 +27,10 @@ and Agent responses keep their original language.You can send more messages while a reply is generating. They appear above thecomposer. **Steer** adds that message to the current reply's next Agent step.**Delete** removes just that queued message. Questions from the Agent appear-above the composer and can be answered there.+above the composer and can be answered there. One Host SSE stays connected+while switching chats or opening settings. A pending question or approval in+another chat adds a chat-list indicator; open that chat to respond. Execution+approvals have no fixed timeout and reappear after reconnecting.Use the plus button to choose attachments, or paste files when your browserprovides them in the clipboard. The composer keeps them in the draft until@@ -47,7 +50,8 @@ npm --prefix frontend run dev```Open [http://127.0.0.1:5173/](http://127.0.0.1:5173/). Vite proxies `/v1`-to Controller on port 8080. Set the exact loopback origin in+to Controller on port 8080 and preserves the browser-facing Host, so local OAuth+callbacks return through the same `/v1` proxy. Set the exact loopback origin in`--web-dev-origin` when changing the Vite port. The production UI uses theController's own origin.diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex c3e76e6..cef3ba7 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -1,21 +1,29 @@import { useCallback, useEffect, useRef, useState } from 'react'import { LanguagePicker, useLocale } from './locale'import { ArrowLeft, Globe, Image, Menu, SlidersHorizontal } from 'lucide-react'-import { APIError, archiveSession, createSession, listSessions, openAccount, stopHost, type ProviderPage, type SessionRow } from './api/controller'+import { APIError, archiveSession, createSession, listSessions, openAccount, readHostStream, stopHost, type ProviderPage, type SessionRow } from './api/controller'import { AccountEntry } from './AccountEntry'import { Chat } from './chat/Chat'import { TranscriptCache } from './chat/transcriptCache'+import { HostConnection } from './chat/hostConnection'import { Sidebar } from './sessions/Sidebar'import { Models } from './settings/Models'import { ToolProviders } from './settings/ToolProviders'import { HostFiles } from './files/HostFiles'+import { Plugins } from './extensions/Plugins'+import { ExtensionDialogs } from './extensions/Dialogs'-type SettingsPage = 'models' | ProviderPage+type SettingsPage = 'models' | ProviderPage | 'plugins'function currentSettings(): SettingsPage | undefined {if (window.location.pathname === '/settings/models') return 'models'if (window.location.pathname === '/settings/web-search') return 'web-search'if (window.location.pathname === '/settings/image-generation') return 'image-generation'+ if (window.location.pathname === '/plugins') return 'plugins'+}++function settingsNavigationAllowed(resume: () => void) {+ return window.dispatchEvent(new CustomEvent('go-bot:settings-navigation', { cancelable: true, detail: { resume } }))}function currentSession() {@@ -30,16 +38,18 @@ function errorDeleting(error: unknown) {export function App() {const [userId, setUserID] = useState<string>()- return userId ? <AccountChat userId={userId} onExit={() => setUserID(undefined)} /> : <AccountEntry onOpen={(id, created) => {+ return <ExtensionDialogs>{userId ? <AccountChat userId={userId} onExit={() => setUserID(undefined)} /> : <AccountEntry onOpen={(id, created) => {if (created) window.history.pushState({ returnTo: '/' }, '', '/settings/models')setUserID(id)- }} />+ }} />}</ExtensionDialogs>}function AccountChat({ userId, onExit }: { userId: string; onExit: () => void }) {- const { t } = useLocale()+ const { t, language } = useLocale()const [transcriptCache] = useState(() => new TranscriptCache())+ const [, updateSummaries] = useState(0)const [settingsPage, setSettingsPage] = useState(currentSettings)+ const [selectedPlugin, setSelectedPlugin] = useState<string>()const settingsOpen = settingsPage !== undefinedconst [settingsVersion, setSettingsVersion] = useState(0)const [hostReady, setHostReady] = useState(false)@@ -62,6 +72,23 @@ function AccountChat({ userId, onExit }: { userId: string; onExit: () => void })const createInFlight = useRef(false)const listRequest = useRef<AbortController | null>(null)const removed = useRef(new Set<string>())+ const settingsNav = useRef<HTMLElement>(null)++ useEffect(() => {+ const nav = settingsNav.current+ if (!nav) return+ const revealCurrent = () => {+ const current = nav.querySelector<HTMLElement>('[aria-current="page"]')+ if (!current) return+ const row = nav.getBoundingClientRect(), tab = current.getBoundingClientRect()+ const left = tab.left < row.left ? tab.left - row.left : tab.right > row.right ? tab.right - row.right : 0+ if (left) nav.scrollBy({ left, behavior: 'auto' })+ }+ revealCurrent()+ const resize = new ResizeObserver(revealCurrent)+ resize.observe(nav)+ return () => resize.disconnect()+ }, [settingsPage, language])async function exitHost() {setStoppingHost(true)@@ -88,7 +115,7 @@ function AccountChat({ userId, onExit }: { userId: string; onExit: () => void })if (!loadedMore.current || after) setCursor(page.nextCursor ?? '')if (after) loadedMore.current = truesetRows(previous => {- const merged = new Map(previous.map(row => [row.sessionId, row]))+ const merged = new Map(previous.filter(row => !transcriptCache.isUnavailable(row.sessionId)).map(row => [row.sessionId, row]))for (const row of page.sessions) if (!removed.current.has(row.sessionId)) merged.set(row.sessionId, row)return [...merged.values()].sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.sessionId.localeCompare(b.sessionId))})@@ -100,10 +127,24 @@ function AccountChat({ userId, onExit }: { userId: string; onExit: () => void })setLoading(false)}}- }, [userId])+ }, [userId, transcriptCache])++ useEffect(() => {+ if (!hostReady) return+ const connection = new HostConnection(transcriptCache, (cursors, signal, opened, receive) =>+ readHostStream(userId, cursors, signal, opened, receive))+ let refreshTimer: ReturnType<typeof setTimeout> | undefined+ const unsubscribe = transcriptCache.subscribe('@sessions', () => {+ clearTimeout(refreshTimer)+ refreshTimer = setTimeout(() => void refresh(), 150)+ })+ const unsubscribeSummaries = transcriptCache.subscribe('@summaries', () => updateSummaries(version => version + 1))+ connection.start()+ return () => { connection.stop(); unsubscribe(); unsubscribeSummaries(); clearTimeout(refreshTimer) }+ }, [hostReady, userId, transcriptCache, refresh])useEffect(() => {- if (settingsOpen || hostReady) return+ if (hostReady) returnlet active = truevoid openAccount(userId).then(() => {if (active) {@@ -117,7 +158,7 @@ function AccountChat({ userId, onExit }: { userId: string; onExit: () => void })}})return () => { active = false }- }, [settingsOpen, hostReady, hostAttempt, userId])+ }, [hostReady, hostAttempt, userId])useEffect(() => {if (hostReady) void refresh()@@ -172,14 +213,17 @@ function AccountChat({ userId, onExit }: { userId: string; onExit: () => void })}function choose(id?: string) {- const path = id ? '/chat/' + id : '/'- if (window.location.pathname !== path) window.history.pushState(null, '', path)- setSelected(id)- setDrawerOpen(false)- if (settingsOpen) {- setSettingsPage(undefined)- setSettingsVersion(value => value + 1)+ const complete = () => {+ const path = id ? '/chat/' + id : '/'+ if (window.location.pathname !== path) window.history.pushState(null, '', path)+ setSelected(id)+ setDrawerOpen(false)+ if (settingsOpen) {+ setSettingsPage(undefined)+ setSettingsVersion(value => value + 1)+ }}+ if (!settingsOpen || settingsNavigationAllowed(complete)) complete()}function unavailable(id: string) {@@ -195,6 +239,7 @@ function AccountChat({ userId, onExit }: { userId: string; onExit: () => void })}function showSettings() {+ if (settingsPage === 'plugins') { selectSettings('models'); setDrawerOpen(false); return }if (settingsOpen) {setDrawerOpen(false)return@@ -204,17 +249,37 @@ function AccountChat({ userId, onExit }: { userId: string; onExit: () => void })setSettingsPage('models')}+ function showPlugins() {+ const complete = () => {+ const returnTo = settingsOpen ? window.history.state?.returnTo || '/' : window.location.pathname+ window.history.pushState({ returnTo }, '', '/plugins')+ setSettingsPage('plugins')+ setDrawerOpen(false)+ }+ if (settingsPage === 'plugins') { setSelectedPlugin(undefined); setDrawerOpen(false); return }+ if (settingsNavigationAllowed(complete)) complete()+ }+function selectSettings(page: SettingsPage) {- window.history.replaceState(window.history.state, '', '/settings/' + page)- setSettingsPage(page)+ if (page === settingsPage) return+ const complete = () => {+ window.history.replaceState(window.history.state, '', page === 'plugins' ? '/plugins' : '/settings/' + page)+ setSettingsPage(page)+ }+ if (settingsNavigationAllowed(complete)) complete()}function closeSettings() {- const target = typeof window.history.state?.returnTo === 'string' ? window.history.state.returnTo : '/'- window.history.replaceState(null, '', target)- setNeedsModel(false)- setSettingsPage(undefined)- setSettingsVersion(value => value + 1)+ if (settingsPage === 'plugins' && selectedPlugin) { setSelectedPlugin(undefined); return }+ const complete = () => {+ const target = typeof window.history.state?.returnTo === 'string' ? window.history.state.returnTo : '/'+ window.history.replaceState(null, '', target)+ setNeedsModel(false)+ setSettingsPage(undefined)+ setSettingsVersion(value => value + 1)+ requestAnimationFrame(() => document.getElementById('account-menu-toggle')?.focus())+ }+ if (settingsNavigationAllowed(complete)) complete()}function markTitle(id: string, text: string) {@@ -285,10 +350,10 @@ function AccountChat({ userId, onExit }: { userId: string; onExit: () => void })return (<div className={filesOpen ? 'app app-files-open' : 'app'}>- <Sidebar userId={userId} rows={rows} selected={selected} hasMore={Boolean(cursor)} isLoading={loading} creating={creating || !hostReady}+ <Sidebar userId={userId} cache={transcriptCache} rows={rows} selected={selected} hasMore={Boolean(cursor)} isLoading={loading} creating={creating || !hostReady}filesOpen={filesOpen} filesAvailable={hostReady} filesOverlay={filesOverlay} onFiles={toggleFiles}hostReady={hostReady} stoppingHost={stoppingHost} stopHostError={stopHostError} onStopHost={exitHost}- error={error} needsModel={needsModel} drawerOpen={drawerOpen} onSettings={showSettings} onCreate={() => { void start().catch(() => {}) }} onChoose={choose}+ error={error} needsModel={needsModel} drawerOpen={drawerOpen} onSettings={showSettings} onPlugins={showPlugins} pluginsOpen={settingsPage === 'plugins'} onCreate={() => { void start().catch(() => {}) }} onChoose={choose}onDelete={remove} onMore={() => { void refresh(cursor) }} onClose={closeDrawer}onRetry={() => { setError(''); if (hostReady) void refresh(); else setHostAttempt(attempt => attempt + 1) }} />{settingsPage && <main className="model-settings" inert={drawerOpen || filesOverlay}>@@ -296,24 +361,25 @@ function AccountChat({ userId, onExit }: { userId: string; onExit: () => void })<button type="button" className="icon-button drawer-toggle" onClick={() => setDrawerOpen(true)}aria-expanded={drawerOpen} aria-controls="chat-sidebar" aria-label={t('Open chats')}><Menu size={22} /></button></div>- <div className="model-settings-panel">+ <div className={settingsPage === 'plugins' ? 'model-settings-panel plugin-settings-panel' : 'model-settings-panel'}><header className="settings-header"><div className="settings-header-actions">- <button type="button" className="settings-back" onClick={closeSettings}><ArrowLeft size={17} /> {t('Back to chats')}</button>+ <button type="button" className="settings-back" onClick={closeSettings}><ArrowLeft size={17} /> {t(settingsPage === 'plugins' && selectedPlugin ? 'Plugin market' : 'Back to chats')}</button><LanguagePicker /></div>- <h1>{t('Settings')}</h1>+ {!(settingsPage === 'plugins' && selectedPlugin) && <h1>{t(settingsPage === 'plugins' ? 'Plugin market' : 'Settings')}</h1>}</header>- <nav className="settings-nav" aria-label={t('Settings')}>+ {settingsPage !== 'plugins' && <nav ref={settingsNav} className="settings-nav" aria-label={t('Settings')}><button type="button" aria-current={settingsPage === 'models' ? 'page' : undefined}onClick={() => selectSettings('models')}><SlidersHorizontal size={16} /> {t('Models')}</button><button type="button" aria-current={settingsPage === 'web-search' ? 'page' : undefined}onClick={() => selectSettings('web-search')}><Globe size={16} /> {t('Web search')}</button><button type="button" aria-current={settingsPage === 'image-generation' ? 'page' : undefined}onClick={() => selectSettings('image-generation')}><Image size={16} /> {t('Image generation')}</button>- </nav>+ </nav>}<div className="settings-content">- {settingsPage === 'models' ? <Models userId={userId} /> : <ToolProviders key={settingsPage} userId={userId} page={settingsPage} />}+ {settingsPage === 'models' ? <Models userId={userId} /> : settingsPage === 'plugins' ? <Plugins userId={userId} cache={transcriptCache} selected={selectedPlugin} onSelect={setSelectedPlugin} />+ : <ToolProviders key={settingsPage} userId={userId} page={settingsPage} />}</div></div></main>}diff --git a/frontend/src/api/controller.ts b/frontend/src/api/controller.tsindex 2c6a011..3d9d33f 100644--- a/frontend/src/api/controller.ts+++ b/frontend/src/api/controller.ts@@ -1,3 +1,4 @@+import type { ModelProtocol } from "../settings/modelProtocol"import type { PermissionMode, SessionPermission } from '../chat/permissions'import { messageRequest } from '../chat/attachments'import { EventSourceParserStream } from 'eventsource-parser/stream'@@ -23,14 +24,18 @@ export type TranscriptPage = {throughSeq: number | nullqueue: QueueItem[]questions: PendingQuestion[] | null+ baseline?: { revision: number; activeAttempt?: unknown }+ permission?: SessionPermission}export class APIError extends Error {status: number+ details?: unknown- constructor(status: number, message: string) {+ constructor(status: number, message: string, details?: unknown) {super(message)this.status = status+ this.details = details}}@@ -41,19 +46,25 @@ export function settingsApplyFailed(error: unknown) {async function requireSuccess(response: Response) {if (response.ok) return responseconst failure = await response.json().catch(() => null)- throw new APIError(response.status, typeof failure?.error === 'string' ? failure.error : '')+ throw new APIError(response.status, typeof failure?.error === 'string' ? failure.error : '', failure)}-async function request<T>(path: string, options?: RequestInit, userId?: string): Promise<T> {- const headers = new Headers(options?.headers)+function controllerHeaders(input?: HeadersInit, userId?: string) {+ const headers = new Headers(input)if (userId) headers.set('X-User-ID', userId)+ if (typeof window !== 'undefined') headers.set('X-Go-Bot-Controller-Origin', window.location.origin)+ return headers+}++export async function request<T>(path: string, options?: RequestInit, userId?: string): Promise<T> {+ const headers = controllerHeaders(options?.headers, userId)const response = await requireSuccess(await fetch(path, { ...options, headers }))if (response.status === 204) return undefined as Treturn response.json() as Promise<T>}export type ModelSelection = { endpointId: string; modelId: string }-export type ModelEndpoint = { name: string; baseUrl: string; hasApiKey: boolean; models: string[] }+export type ModelEndpoint = { protocol?: ModelProtocol; name: string; baseUrl: string; hasApiKey: boolean; models: string[] }export type ModelSettings = { defaultEndpointId: string; endpoints: Record<string, ModelEndpoint> }export type SessionModel = { selection: ModelSelection | null; status: 'ready' | 'unconfigured' | 'unavailable' }@@ -201,18 +212,16 @@ export async function fetchChatFile(userId: string, id: string, file: FileRef, nreturn response.blob()}-export async function readStream(+export async function readHostStream(userId: string,- id: string,- after: number | null,+ cursors: Record<string, number | null>,signal: AbortSignal,onOpen: () => void,onEvent: (event: string, data: unknown) => void,) {- const query = new URLSearchParams({ view: 'chat' })- if (after !== null) query.set('after', String(after))- const response = await fetch(sessionPath(id) + '/stream?' + query, {- headers: { Accept: 'text/event-stream', 'X-User-ID': userId },+ const query = new URLSearchParams({ cursors: JSON.stringify(cursors) })+ const response = await fetch('/v1/host/stream?' + query, {+ headers: controllerHeaders({ Accept: 'text/event-stream' }, userId),signal,})await requireSuccess(response)diff --git a/frontend/src/api/extensions.ts b/frontend/src/api/extensions.tsnew file mode 100644index 0000000..1b70842--- /dev/null+++ b/frontend/src/api/extensions.ts@@ -0,0 +1,56 @@+import { request } from './controller'+export type PackageSource = { type: 'registry' | 'git' | 'directory' | 'tarball' | 'bundled'; spec: string; registry?: string; authRef?: string; username?: string }+export type PackageInfo = { name: string; version: string; description: string; license: string; source: PackageSource; api: string; title?: string; configSchema?: Record<string, unknown>; present: boolean; availableVersion?: string }+export type PluginInstance = { id: string; package: string; state: string; error?: string }+export type Localized = { en: string; 'zh-CN': string }+export type PluginTutorial = { language: 'en' | 'zh-CN'; title: string; video: string; poster?: string }+export type CatalogEntry = { pluginId: string; package: string; name: string; description: Localized; version: string; icon: string; maintainer: string; license: string; tutorials?: PluginTutorial[] }+export type PluginSettings = { packages: Record<string, { catalogId: string; version: string; enabled: boolean }> }+export type PluginView = { catalog: CatalogEntry[]; settings: PluginSettings; status: { runtime: string; packages: PackageInfo[]; instances: PluginInstance[]; error?: string } }+const plugins = '/v1/settings/plugins'+function body(method: string, value?: unknown): RequestInit { return { method, ...(value === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(value) }) } }+export const getPlugins = (user: string, signal?: AbortSignal) => request<PluginView>(plugins, { signal }, user)+export const installPackage = (user: string, pluginId: string) => request<PluginView>(plugins + '/packages', body('POST', { pluginId }), user)+export const updatePackage = (user: string, name: string, pluginId: string) => request<PluginView>(plugins + '/packages/' + encodeURIComponent(name) + '/update', body('POST', { pluginId }), user)+export const removePackage = (user: string, name: string) => request<PluginView>(plugins + '/packages/' + encodeURIComponent(name), body('DELETE'), user)+export const setPluginEnabled = (user: string, name: string, enabled: boolean) => request<PluginView>(plugins + '/packages/' + encodeURIComponent(name), body('PUT', { enabled }), user)+export const restartPlugins = (user: string) => request<PluginView>('/v1/host/plugins/runtime/restart', body('POST'), user)++export type AuthorizationEntry = { key: string; label: string; methods: { id: string; label: string }[]; inFlight: boolean; configured: boolean; canDisconnect?: boolean; accountLabel?: string; attemptId?: string; attemptStatus?: AuthorizationAttempt['status'] }+export type AuthorizationPrompt = { id: string; message: string } & ({ kind: 'text' | 'secret'; placeholder?: string; webInput?: 'json-file' } | { kind: 'select'; options: { id: string; label: string; description?: string }[] })+export type AuthorizationAttempt = { id: string; key: string; label: string; method: string; status: 'running' | 'authorized' | 'cancelled' | 'failed'; notices: { message: string; url?: string; code?: string }[]; prompts: AuthorizationPrompt[]; error?: string }+export type AuthorizationAPI = {+ list(signal?: AbortSignal): Promise<AuthorizationEntry[]>+ get(id: string, signal?: AbortSignal): Promise<AuthorizationAttempt>+ start(key: string, method: string): Promise<AuthorizationAttempt>+ answer(id: string, promptId: string, answer?: string, decline?: boolean): Promise<AuthorizationAttempt>+ cancel(id: string): Promise<AuthorizationAttempt>+ cancelKey(key: string): Promise<unknown>+ disconnect(key: string): Promise<unknown>+}+const authorization = '/v1/host/extensions/authorization'+export const authorizationAPI = (user: string): AuthorizationAPI => ({+ list: signal => request(authorization, { signal }, user),+ get: (id, signal) => request(authorization + '/' + encodeURIComponent(id), { signal }, user),+ start: (key, method) => request(authorization, body('POST', { key, method }), user),+ answer: (id, promptId, answer, decline) => request(authorization + '/' + encodeURIComponent(id) + '/answer', body('POST', { promptId, answer, decline }), user),+ cancel: id => request(authorization + '/' + encodeURIComponent(id), { ...body('DELETE'), keepalive: true }, user),+ cancelKey: key => request(authorization, body('DELETE', { key }), user),+ disconnect: key => request(authorization + '/disconnect', body('POST', {key}), user),+})++export type MCPOAuthAttempt = { id?: string; name: string; state: string; phase?: string; url?: string; expiresAt?: number; error?: string }+export type MCPServer = { name: string; source: string; owner?: string; serverName?: string; state: string; error?: string; oauthEnabled: boolean; authorization?: MCPOAuthAttempt }+export type MCPAuthorizationAPI = {+ list(signal?: AbortSignal): Promise<{ status: { servers: MCPServer[]; error?: string } }>+ start(name: string): Promise<MCPOAuthAttempt>+ cancel(name: string, attemptId: string): Promise<unknown>+ signOut(name: string): Promise<unknown>+}+const mcp = '/v1/host/mcp'+export const mcpAuthorizationAPI = (user: string): MCPAuthorizationAPI => ({+ list: signal => request(mcp, { signal }, user),+ start: name => request(mcp + '/servers/' + encodeURIComponent(name) + '/authorize', body('POST', { origin: window.location.origin }), user),+ cancel: (name, attemptId) => request(mcp + '/servers/' + encodeURIComponent(name) + '/authorization?id=' + encodeURIComponent(attemptId), body('DELETE'), user),+ signOut: name => request(mcp + '/servers/' + encodeURIComponent(name) + '/grant', body('DELETE'), user),+})diff --git a/frontend/src/chat/Chat.tsx b/frontend/src/chat/Chat.tsxindex da51b79..df44906 100644--- a/frontend/src/chat/Chat.tsx+++ b/frontend/src/chat/Chat.tsx@@ -2,14 +2,14 @@ import { useEffect, useLayoutEffect, useRef, useState } from 'react'import { useLocale } from '../locale'import { ArrowUp, FileText, LoaderCircle, Menu, Plus, Square, X } from 'lucide-react'import { HarnessAvatar } from '../HarnessAvatar'-import { APIError, readTranscript, readStream, sendMessage, stopTurn, updateQueue } from '../api/controller'+import { APIError, readTranscript, sendMessage, stopTurn, updateQueue } from '../api/controller'import { MessageBubble } from './ChatContent'import { ApprovalPanel, PermissionPicker } from './PermissionControls'import { QuestionPanel } from './QuestionPanel'import { addMessageFiles, isMessageImage } from './attachments'import { ModelPicker } from './ModelPicker'import { attemptMessage, emptyTranscript, groupAssistantReplies, messageText, textMessage, visibleQueue, type Message } from './transcript'-import { cacheTranscript, prependTranscriptPage, updateCachedTranscript, type TranscriptCache } from './transcriptCache'+import { prependTranscriptPage, type TranscriptCache } from './transcriptCache'function greeting() {const hour = new Date().getHours()@@ -69,7 +69,6 @@ export function Chat({ hidden, userId, cache, id, drawerOpen, filesOverlay, settconst [atBottom, setAtBottom] = useState(true)const scrollAnchor = useRef<{ height: number; top: number } | null>(null)const [loadAttempt, setLoadAttempt] = useState(0)- const kick = useRef<() => void>(() => {})const historySignal = useRef<AbortSignal>(undefined)const composer = useRef<HTMLTextAreaElement>(null)const scroll = useRef<HTMLDivElement>(null)@@ -90,85 +89,39 @@ export function Chat({ hidden, userId, cache, id, drawerOpen, filesOverlay, settif (!id) returnconst sessionId = idconst abort = new AbortController()- const signal = abort.signal- historySignal.current = signal+ historySignal.current = abort.signalsetLoadingOlder(false)- let entry = cache.get(sessionId)- let running = false- let retryTimer: number | undefined- let wait = 500-- function scheduleReconnect() {- retryTimer = window.setTimeout(() => { void follow() }, wait)- wait = Math.min(wait * 2, 4000)- }-- async function follow() {- if (running || !entry || signal.aborted) return- const current = entry- window.clearTimeout(retryTimer)- running = true- try {- await readStream(userId, sessionId, current.cursor, signal, () => {- if (signal.aborted) return- wait = 500- setConnecting(false)- }, (kind, data) => {- if (signal.aborted || cache.get(sessionId) !== current) return- setTranscript(updateCachedTranscript(current, kind, data))- })- if (!signal.aborted) {- setConnecting(true)- scheduleReconnect()- }- } catch (error) {- if (signal.aborted) return- if (error instanceof APIError && error.status === 404) {- cache.delete(sessionId)- entry = undefined- missing.current(sessionId)- } else {- setConnecting(true)- scheduleReconnect()- }- } finally {- running = false- }+ const update = () => {+ if (cache.isUnavailable(sessionId)) { missing.current(sessionId); return }+ const entry = cache.get(sessionId)+ if (entry) { setTranscript(entry.transcript); setBefore(entry.before) }}-- kick.current = () => { void follow() }-- async function loadHistory() {+ const unsubscribe = cache.subscribe(sessionId, update)+ const connection = () => setConnecting(cache.connecting)+ const unsubscribeConnection = cache.subscribe('@connection', connection)+ connection()+ const entry = cache.get(sessionId)+ if (entry) {+ cache.keep(sessionId, entry)+ update()+ setLoading(false)+ setHistoryError('')+ } else {+ cache.beginLoad(sessionId)setLoading(true)setHistoryError('')- try {- const page = await readTranscript(userId, sessionId, null, signal)- if (signal.aborted) return- entry = cacheTranscript(page)- cache.keep(sessionId, entry)- setBefore(entry.before)- setTranscript(entry.transcript)- if (entry.cursor !== null) refresh.current()- void follow()- } catch (error) {- if (signal.aborted) return+ void readTranscript(userId, sessionId, null, abort.signal).then(page => {+ if (abort.signal.aborted) return+ cache.finishLoad(sessionId, page)+ refresh.current()+ }).catch(error => {+ if (abort.signal.aborted) return+ cache.cancelLoad(sessionId)if (error instanceof APIError && error.status === 404) missing.current(sessionId)else setHistoryError('Chat history could not be loaded.')- } finally {- if (!signal.aborted) setLoading(false)- }- }-- if (entry) {- cache.keep(sessionId, entry)- setHistoryError('')- void follow()- } else void loadHistory()- return () => {- abort.abort()- window.clearTimeout(retryTimer)- kick.current = () => {}+ }).finally(() => { if (!abort.signal.aborted) setLoading(false) })}+ return () => { abort.abort(); unsubscribe(); unsubscribeConnection(); cache.cancelLoad(sessionId) }}, [cache, id, loadAttempt, userId])const pendingMessages = pending.filter(item => !transcript.messages.some(message => message.id === item.id))@@ -282,7 +235,6 @@ export function Chat({ hidden, userId, cache, id, drawerOpen, filesOverlay, settsetAwaitingMessage(result.messageId)if (!files.length) setPending(items => [...items, textMessage(result.messageId, text)])}- kick.current()setInput(value => value.trim() === text ? '' : value)setFiles([])setFileIssues([])@@ -341,7 +293,7 @@ export function Chat({ hidden, userId, cache, id, drawerOpen, filesOverlay, sett<div className="composer-tools"><button type="button" className="attachment-button" aria-label={t('Add attachments')} title={t('Add attachments')}disabled={submitting} onClick={() => filePicker.current?.click()}><Plus size={21} /></button>- <ModelPicker userId={userId} id={id} settingsVersion={settingsVersion} onSettings={onSettings} onSaving={setModelSaving} />+ <ModelPicker generating={activeTurn !== null} userId={userId} id={id} settingsVersion={settingsVersion} onSettings={onSettings} onSaving={setModelSaving} />{id && <PermissionPicker key={id} userId={userId} sessionId={id} streamState={transcript.permission}disabled={activeTurn !== null || submitting} onSaving={setPermissionSaving} />}</div>diff --git a/frontend/src/chat/ChatContent.tsx b/frontend/src/chat/ChatContent.tsxindex ceaae71..770a4ee 100644--- a/frontend/src/chat/ChatContent.tsx+++ b/frontend/src/chat/ChatContent.tsx@@ -38,7 +38,7 @@ export function MessageBubble({ message, tools, ...address }: SessionAddress & {)}-function MarkdownText({ text }: { text: string }) {+export function MarkdownText({ text }: { text: string }) {const { t } = useLocale()return <div><ReactMarkdown remarkPlugins={[remarkGfm]} skipHtml components={{@@ -58,6 +58,7 @@ function MarkdownText({ text }: { text: string }) {}const toolLabels: Record<string, string> = {+ exit_plan_mode: 'Review the plan',read_file: 'Read file', write_file: 'Write file', edit_file: 'Edit file',readimage: 'Read image', generateimage: 'Generate image',bash: 'Run command', shell: 'Run command', shellexecute: 'Run command',diff --git a/frontend/src/chat/ModelPicker.tsx b/frontend/src/chat/ModelPicker.tsxindex 3319d0d..a00096b 100644--- a/frontend/src/chat/ModelPicker.tsx+++ b/frontend/src/chat/ModelPicker.tsx@@ -1,14 +1,16 @@+import { modelProtocol, protocolNames } from '../settings/modelProtocol'import { useEffect, useRef, useState } from 'react'import { useLocale } from '../locale'import { Check, ChevronDown, Cpu } from 'lucide-react'import { getModelSettings, getSessionModel, saveSessionModel, settingsApplyFailed, type ModelSelection, type ModelSettings, type SessionModel } from '../api/controller'-export function ModelPicker({ userId, id, settingsVersion, onSettings, onSaving }: {+export function ModelPicker({ userId, id, settingsVersion, onSettings, onSaving, generating }: {userId: stringid?: stringsettingsVersion: numberonSettings: () => voidonSaving: (value: boolean) => void+ generating?: boolean}) {const { t } = useLocale()const [catalog, setCatalog] = useState<ModelSettings>()@@ -17,6 +19,7 @@ export function ModelPicker({ userId, id, settingsVersion, onSettings, onSavingconst [endpointId, setEndpointID] = useState('')const [busy, setBusy] = useState(false)const [error, setError] = useState('')+ const [notice, setNotice] = useState('')useEffect(() => {const controller = new AbortController()@@ -34,6 +37,9 @@ export function ModelPicker({ userId, id, settingsVersion, onSettings, onSavingreturn () => controller.abort()}, [userId, id, settingsVersion])+ useEffect(() => { setNotice('') }, [userId, id])+ useEffect(() => { if (!generating) setNotice('') }, [generating])+const picker = useRef<HTMLDivElement>(null)const trigger = useRef<HTMLButtonElement>(null)useEffect(() => {@@ -53,6 +59,7 @@ export function ModelPicker({ userId, id, settingsVersion, onSettings, onSavingtry {const next = await saveSessionModel(userId, id, selection)setRoute(next)+ setNotice(generating ? 'This model will be used from the next turn.' : '')setOpen(false)requestAnimationFrame(() => trigger.current?.focus())} catch (failure) {@@ -94,7 +101,7 @@ export function ModelPicker({ userId, id, settingsVersion, onSettings, onSaving</button>{open && catalog && <div className="model-picker-menu"><label>{t('Endpoint')}<select value={endpointId} onChange={event => setEndpointID(event.target.value)}>- {choices.map(([id, endpoint]) => <option key={id} value={id}>{endpoint.name}</option>)}+ {choices.map(([id, endpoint]) => <option key={id} value={id}>{endpoint.name} · {protocolNames[modelProtocol(endpoint.protocol)]}</option>)}</select></label><div className="model-picker-options">{catalog.endpoints[endpointId]?.models.map(modelId => <button type="button" key={modelId} disabled={busy}@@ -104,6 +111,7 @@ export function ModelPicker({ userId, id, settingsVersion, onSettings, onSaving</button>)}</div></div>}+ {notice && <small role="status">{t(notice)}</small>}{error && <small role="alert">{t(error)}</small>}</div>}diff --git a/frontend/src/chat/QuestionPanel.tsx b/frontend/src/chat/QuestionPanel.tsxindex b27a81a..2745338 100644--- a/frontend/src/chat/QuestionPanel.tsx+++ b/frontend/src/chat/QuestionPanel.tsx@@ -1,6 +1,7 @@import { useState } from 'react'import { useLocale } from '../locale'import { answerQuestion } from '../api/controller'+import { MarkdownText } from './ChatContent'import type { Answer, PendingQuestion } from './transcript'export function QuestionPanel({ item, userId, sessionId }: { item: PendingQuestion; userId: string; sessionId: string }) {@@ -9,6 +10,7 @@ export function QuestionPanel({ item, userId, sessionId }: { item: PendingQuesticonst [sending, setSending] = useState(false)const [submitted, setSubmitted] = useState(false)const [error, setError] = useState('')+ const review = item.questions.some(question => question.id === 'plan-review')const ready = answers.every(answer => answer.selected.length > 0 || Boolean(answer.custom?.trim()))function update(index: number, patch: Partial<Answer>) {@@ -29,11 +31,11 @@ export function QuestionPanel({ item, userId, sessionId }: { item: PendingQuesti}}- return <form className="question-panel" aria-label={t('Agent question')} onSubmit={event => { event.preventDefault(); void submit() }}>- <strong>{item.state === 'continued' ? t('You can still answer') : t('The agent has a question')}</strong>+ return <form className={review ? "question-panel plan-review" : "question-panel"} aria-label={t(review ? 'Plan review' : 'Agent question')} onSubmit={event => { event.preventDefault(); void submit() }}>+ <strong>{review ? t('Review the plan') : item.state === 'continued' ? t('You can still answer') : t('The agent has a question')}</strong>{item.questions.map((question, index) => <fieldset key={question.id} disabled={sending || submitted}>- <legend>{question.question}</legend>- {question.detail && <p>{question.detail}</p>}+ <legend>{t(question.question)}</legend>+ {question.detail && <div className="question-detail markdown"><MarkdownText text={question.detail} /></div>}{question.options?.map(option => <label className="question-option" key={option.label}><input type={question.multiSelect ? 'checkbox' : 'radio'} name={question.id}checked={answers[index].selected.includes(option.label)}@@ -41,13 +43,13 @@ export function QuestionPanel({ item, userId, sessionId }: { item: PendingQuesticonst selected = answers[index].selectedupdate(index, { selected: question.multiSelect? event.target.checked ? [...selected, option.label] : selected.filter(label => label !== option.label)- : [option.label] })+ : [option.label], ...(!question.multiSelect && { custom: undefined }) })}} />- <span>{option.label}{option.description && <small>{option.description}</small>}</span>+ <span>{t(option.label)}{option.description && <small>{t(option.description)}</small>}</span></label>)}<input className="question-custom" type="text" value={answers[index].custom ?? ''}- aria-label={t('Custom answer for {question}', { question: question.question })} placeholder={t('Type your own answer')}- onChange={event => update(index, { custom: event.target.value })} />+ aria-label={t('Custom answer for {question}', { question: t(question.question) })} placeholder={t('Type your own answer')}+ onChange={event => update(index, { custom: event.target.value, ...(!question.multiSelect && { selected: [] }) })} /></fieldset>)}{error && <p className="feedback" role="alert">{t(error)}</p>}<button className="text-button" type="submit" disabled={!ready || sending || submitted}>{submitted ? t('Answer sent') : t('Send answer')}</button>diff --git a/frontend/src/chat/hostConnection.ts b/frontend/src/chat/hostConnection.tsnew file mode 100644index 0000000..fee43bd--- /dev/null+++ b/frontend/src/chat/hostConnection.ts@@ -0,0 +1,53 @@+import type { HostEvent, TranscriptCache } from './transcriptCache.ts'++export type HostStreamReader = (+ cursors: Record<string, number | null>, signal: AbortSignal,+ onOpen: () => void, onEvent: (kind: string, data: unknown) => void,+) => Promise<void>++// One owner per signed-in workspace. Session switches never start a reader.+export class HostConnection {+ private controller?: AbortController+ private timer?: ReturnType<typeof setTimeout>+ private stopped = true+ private wait = 500+ private cache: TranscriptCache+ private read: HostStreamReader+ constructor(cache: TranscriptCache, read: HostStreamReader) { this.cache = cache; this.read = read }+ start() {+ if (!this.stopped) return+ this.stopped = false+ void this.follow()+ }+ stop() {+ this.stopped = true+ clearTimeout(this.timer)+ this.controller?.abort()+ this.cache.connection(true)+ }+ private async follow() {+ if (this.stopped) return+ const controller = new AbortController()+ this.controller = controller+ this.cache.connection(true)+ try {+ await this.read(this.cache.cursors(), controller.signal, () => {+ if (controller.signal.aborted) return+ this.wait = 500+ this.cache.connection(false)+ this.cache.receive({ type: 'sessions.changed', data: {} })+ }, (kind, data) => {+ if (!controller.signal.aborted && kind === 'host') this.cache.receive(data as HostEvent)+ })+ } catch {+ // HTTP reads and mutations surface actionable errors. This connection+ // retries without resending any user message or approval decision.+ } finally {+ if (!controller.signal.aborted && !this.stopped) {+ this.cache.connection(true)+ this.timer = setTimeout(() => void this.follow(), this.wait)+ this.wait = Math.min(this.wait * 2, 5000)+ }+ }+ }+}diff --git a/frontend/src/chat/transcript.ts b/frontend/src/chat/transcript.tsindex 0ba01da..795419d 100644--- a/frontend/src/chat/transcript.ts+++ b/frontend/src/chat/transcript.ts@@ -201,6 +201,12 @@ export function attemptMessage(attempt: Attempt): Message {export function applyStreamEvent(state: Transcript, kind: string, data: unknown): Transcript {if (kind === 'session') return applySessionEvent(state, data as SessionEvent)+ const through = (data as { throughSeq?: number | null })?.throughSeq+ if (through !== undefined && through !== null && through < state.seenThrough) return state+ if (kind === 'session.state') {+ const { activeTurn } = data as { activeTurn: number | null }+ return { ...state, activeTurn, draft: activeTurn === null ? null : state.draft }+ }if (kind === 'chat.idle') return { ...state, draft: null, activeTurn: null }if (kind === 'queue.state') return { ...state, queue: (data as { queue: QueueItem[] }).queue }if (kind === 'permissions.state') return { ...state, permission: data as SessionPermission }@@ -223,13 +229,16 @@ export function applyStreamEvent(state: Transcript, kind: string, data: unknown)if (kind !== 'assistant-stream') return stateconst { frame } = data as { frame: Frame }if (frame.type === 'start') {+ if (state.draft && frame.revision < state.draft.revision) return state+ if (state.draft?.attemptId === frame.attemptId) return statereturn { ...state, draft: { ...frame, nextIndex: 0, texts: {} } }}const draft = state.draft- if (!draft || frame.attemptId !== draft.attemptId || frame.revision !== draft.revision) return state+ if (!draft || frame.attemptId !== draft.attemptId || frame.revision < draft.revision) return state+ if (frame.index !== undefined && frame.index < draft.nextIndex) return stateif (frame.index !== draft.nextIndex) return { ...state, draft: null }if (frame.type === 'end') return stateconst texts = { ...draft.texts }if (frame.chunk) applyChunk(texts, frame.chunk)- return { ...state, draft: { ...draft, texts, nextIndex: draft.nextIndex + 1 } }+ return { ...state, draft: { ...draft, revision: frame.revision, texts, nextIndex: draft.nextIndex + 1 } }}diff --git a/frontend/src/chat/transcriptCache.ts b/frontend/src/chat/transcriptCache.tsindex c805f17..0e61e4b 100644--- a/frontend/src/chat/transcriptCache.ts+++ b/frontend/src/chat/transcriptCache.ts@@ -11,21 +11,97 @@ const maxCachedChats = 20// A cache belongs to one signed-in workspace. Each entry keeps only the// pages the user has opened, plus the events received by the live stream.+export type HostEvent = { sessionId?: string; type: string; data: unknown }+export type SessionSummary = { generating: boolean; pending: 'approval' | 'question' | null }+type BufferedEvent = { type: string; data: unknown }+export class TranscriptCache {private readonly chats = new Map<string, CachedTranscript>()+ private readonly summaries = new Map<string, SessionSummary>()+ private readonly loading = new Map<string, BufferedEvent[]>()+ private readonly listeners = new Map<string, Set<() => void>>()+ private readonly unavailable = new Set<string>()+ connecting = trueget(id: string) { return this.chats.get(id) }-+ summary(id: string) { return this.summaries.get(id) }+ isUnavailable(id: string) { return this.unavailable.has(id) }+ cursors() { return Object.fromEntries([...this.chats].map(([id, entry]) => [id, entry.cursor])) }+ subscribe(key: string, listener: () => void) {+ let listeners = this.listeners.get(key)+ if (!listeners) this.listeners.set(key, listeners = new Set())+ listeners.add(listener)+ return () => { listeners.delete(listener); if (!listeners.size) this.listeners.delete(key) }+ }+ private notify(key: string) { this.listeners.get(key)?.forEach(listener => listener()) }+ connection(connecting: boolean) {+ if (this.connecting !== connecting) { this.connecting = connecting; this.notify('@connection') }+ }keep(id: string, entry: CachedTranscript) {+ this.unavailable.delete(id)this.chats.delete(id)this.chats.set(id, entry)if (this.chats.size > maxCachedChats) {- const oldest = this.chats.keys().next().value+ const oldest = [...this.chats.keys()].find(key => !this.listeners.has(key))if (oldest !== undefined) this.chats.delete(oldest)}}-- delete(id: string) { this.chats.delete(id) }+ delete(id: string) {+ this.chats.delete(id)+ this.summaries.delete(id)+ this.loading.delete(id)+ this.notify('@summaries')+ }+ beginLoad(id: string) { this.loading.set(id, []) }+ cancelLoad(id: string) { this.loading.delete(id) }+ finishLoad(id: string, page: TranscriptPage) {+ const buffered = this.loading.get(id) ?? []+ this.loading.delete(id)+ const entry = cacheTranscript(page)+ if (page.permission) entry.transcript = { ...entry.transcript, permission: page.permission }+ if (page.baseline) updateCachedTranscript(entry, 'assistant-stream-baseline', { baseline: page.baseline })+ // A frame already represented in the snapshot is ignored by its index;+ // durable events already represented in history are ignored by sequence.+ for (const event of buffered) {+ if (event.type === 'assistant-stream-baseline' && page.baseline &&+ (event.data as { baseline: { revision: number } }).baseline.revision < page.baseline.revision) continue+ updateCachedTranscript(entry, event.type, event.data)+ }+ this.keep(id, entry)+ this.notify(id)+ return entry+ }+ receive(event: HostEvent) {+ const { sessionId: id, type, data } = event+ if (!id) {+ if (type === 'schedule/changed') this.notify('@schedule')+ else if (type === 'extensions.changed' || type === 'plugins.state' || type === 'mcp.state') this.notify('@extensions')+ else if (type === 'sessions.changed') this.notify('@sessions')+ return+ }+ if (type === 'session.unavailable') {+ this.delete(id); this.unavailable.add(id); this.notify(id); this.notify('@sessions'); return+ }+ this.loading.get(id)?.push({ type, data })+ const entry = this.chats.get(id)+ if (entry) { updateCachedTranscript(entry, type, data); this.notify(id) }+ const previous = this.summaries.get(id) ?? { generating: false, pending: null }+ let next = previous+ if (type === 'session.state') next = { ...next, generating: (data as { activeTurn: number | null }).activeTurn !== null }+ if (type === 'session') {+ const event = data as SessionEvent+ if (event.type === 'turn/start' || event.type === 'turn/end') next = { ...next, generating: event.type === 'turn/start' }+ if (event.type === 'user/message') this.notify('@sessions')+ }+ if (type === 'questions.state') {+ const questions = (data as { questions?: Transcript['questions'] }).questions ?? []+ next = { ...next, pending: questions.some(question => question.approval) ? 'approval' : questions.length ? 'question' : null }+ }+ if (next.generating !== previous.generating || next.pending !== previous.pending) {+ this.summaries.set(id, next)+ this.notify('@summaries')+ }+ }}export function cacheTranscript(page: TranscriptPage): CachedTranscript {@@ -38,6 +114,10 @@ export function cacheTranscript(page: TranscriptPage): CachedTranscript {}export function updateCachedTranscript(entry: CachedTranscript, kind: string, data: unknown): Transcript {+ if (kind === 'session.cursor') {+ const cursor = (data as { cursor: number | null }).cursor+ if (cursor !== null) entry.cursor = Math.max(entry.cursor ?? -1, cursor)+ }if (kind === 'session') entry.cursor = Math.max(entry.cursor ?? -1, (data as SessionEvent).seq)entry.transcript = applyStreamEvent(entry.transcript, kind, data)return entry.transcriptdiff --git a/frontend/src/extensions/Authorizations.tsx b/frontend/src/extensions/Authorizations.tsxnew file mode 100644index 0000000..6b2713f--- /dev/null+++ b/frontend/src/extensions/Authorizations.tsx@@ -0,0 +1,110 @@+import { useEffect, useMemo, useRef, useState } from 'react'+import { Check, ChevronDown, ExternalLink, KeyRound, LoaderCircle, Upload, X } from 'lucide-react'+import { authorizationAPI, mcpAuthorizationAPI, type AuthorizationEntry, type AuthorizationPrompt, type MCPServer } from '../api/extensions'+import type { TranscriptCache } from '../chat/transcriptCache'+import { useLocale } from '../locale'+import { authorizationLabel, authorizationURL, useAuthorization } from './useAuthorization'+import { useReturnFocus } from './shared'+import { readAuthorizationJSON } from './authorizationFile'+import { useMCPAuthorization } from './useMCPAuthorization'+import { connectionLabel, connectionTitle, mcpAuthorizationLabel, mcpAuthorizationRunning } from './connections'++export function Authorizations({ user, cache, instanceIds }: { user: string; cache: TranscriptCache; instanceIds: string[] }) {+ const api = useMemo(() => authorizationAPI(user), [user]), mcpAPI = useMemo(() => mcpAuthorizationAPI(user), [user])+ const state = useAuthorization(api, cache), mcp = useMCPAuthorization(mcpAPI, cache, instanceIds), { t } = useLocale()+ const entries = state.entries.filter(entry => instanceIds.some(id => entry.key.startsWith(id + '/')))+ const attempt = state.attempt+ const reload = () => { state.reload(); mcp.reload() }+ useEffect(() => { const focus = () => { state.reload(); mcp.reload() }; window.addEventListener('focus', focus); return () => window.removeEventListener('focus', focus) }, [state.reload, mcp.reload])+ if (!entries.length && !mcp.servers.length && !state.error && !mcp.error) return null+ return <>+ <details className="extension-details extension-authorization-list"><summary><KeyRound size={17} />{t('Accounts and authorization')}<span>{entries.length + mcp.servers.length}</span><ChevronDown size={15} /></summary>+ <div className="extension-details-body"><p className="model-muted">{t('Connect accounts using the authorization methods provided by your plugins.')}</p>+ {entries.map(entry => <AuthorizationRow key={entry.key} entry={entry} onDisconnect={() => { void state.disconnect(entry.key) }} busy={state.busy || mcp.busy || !!attempt || !!mcp.attempt} onCancel={() => { void state.cancelKey(entry.key) }} onStart={method => { if (entry.inFlight && entry.attemptId) void state.open(entry.attemptId); else void state.start(entry.key, method) }} onView={() => { if (entry.attemptId) void state.open(entry.attemptId) }} />)}+ {mcp.servers.map(server => <MCPConnection key={server.name} server={server} busy={state.busy || mcp.busy || !!attempt || !!mcp.attempt} onOpen={() => { void mcp.open(server) }} onView={() => mcp.resume(server)} />)}+ {!entries.length && !mcp.servers.length && <p className="model-muted">{t('No account authorization methods are available.')}</p>}+ {!attempt && !mcp.attempt && (state.error || mcp.error) && <p role="alert" className="extension-diagnostic">{t(state.error || mcp.error)}</p>}+ <button className="extension-text" type="button" disabled={state.busy || mcp.busy} onClick={reload}>{t('Refresh')}</button>+ </div>+ </details>+ {attempt && <AuthorizationDialog state={state} />}+ {mcp.attempt && mcp.selected && <MCPAuthorizationDialog state={mcp} />}+ </>+}+function AuthorizationRow({ entry, busy, onStart, onCancel, onView, onDisconnect }: { entry: AuthorizationEntry; busy: boolean; onStart: (method: string) => void; onCancel: () => void; onView: () => void; onDisconnect: () => void }) {+ const { t } = useLocale(), [method, setMethod] = useState(entry.methods[0]?.id ?? '')+ return <div className="extension-account-row"><KeyRound size={18} strokeWidth={1.6} /><div className="extension-identity"><strong>{entry.label}</strong><small>{t(entry.inFlight ? 'Authorization in progress' : entry.configured ? 'Connected' : 'Not configured')}{entry.accountLabel && <> · {entry.accountLabel}</>}</small></div>+ {entry.methods.length > 1 && <select className="extension-auth-method" aria-label={t('Authorization method') + ': ' + entry.label} value={method} disabled={busy || entry.inFlight} onChange={event => setMethod(event.target.value)}>{entry.methods.map(method => <option key={method.id} value={method.id}>{t(method.label)}</option>)}</select>}+ <button className="model-secondary" type="button" disabled={busy} onClick={() => onStart(method)}>{t(entry.inFlight ? 'Continue authorization' : entry.configured ? 'Authorize again' : entry.methods.length === 1 ? entry.methods[0].label : 'Authorize')}</button>+ {entry.configured && entry.canDisconnect && !entry.inFlight && <button type="button" className="extension-text" disabled={busy} onClick={onDisconnect}>{t('Disconnect account')}</button>}+ {entry.inFlight && <button className="extension-text" type="button" disabled={busy} onClick={onCancel}>{t('Cancel authorization')}</button>}+ {!entry.inFlight && entry.attemptId && <button className="extension-text" type="button" disabled={busy} onClick={onView}>{t('View last result')}</button>}+ </div>+}+function AuthorizationDialog({ state }: { state: ReturnType<typeof useAuthorization> }) {+ const { t } = useLocale(), dialog = useRef<HTMLDialogElement>(null)+ const attempt = state.attempt!+ useReturnFocus()+ useEffect(() => { dialog.current?.showModal(); dialog.current?.querySelector<HTMLInputElement>('input')?.focus() }, [])+ return <dialog ref={dialog} className="extension-auth-dialog" aria-labelledby="authorization-title" onCancel={event => { event.preventDefault(); void state.close() }} onClick={event => {+ if (event.target !== event.currentTarget) return+ const rect = event.currentTarget.getBoundingClientRect()+ if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) void state.close()+ }}>+ <header className="extension-auth-heading"><KeyRound size={21} strokeWidth={1.6} /><div><h2 id="authorization-title">{attempt.label}</h2><p>{t(authorizationLabel[attempt.status])}</p></div><button type="button" className="extension-icon" aria-label={t('Close')} disabled={state.busy} onClick={() => { void state.close() }}><X size={19} /></button></header>+ <div className="extension-auth-content">+ {attempt.notices.map((notice, index) => <div className="extension-auth-notice" key={index}><p>{t(notice.message)}</p>{attempt.status === 'running' && notice.code && <code tabIndex={0}>{notice.code}</code>}{attempt.status === 'running' && authorizationURL(notice.url) && <a href={authorizationURL(notice.url)} target="_blank" rel="noopener noreferrer">{t('Continue in browser')}<ExternalLink size={14} /></a>}</div>)}+ {attempt.prompts.map(prompt => <AuthorizationQuestion key={prompt.id} prompt={prompt} busy={state.busy} onAnswer={(answer, decline) => { void state.answer(prompt.id, answer, decline) }} />)}+ {attempt.status === 'running' && !attempt.prompts.length && <p className="extension-auth-wait" role="status"><LoaderCircle size={17} className="extension-auth-spinner" />{t('Waiting for authorization to finish…')}</p>}+ {attempt.status === 'authorized' && <p className="extension-auth-complete" role="status"><Check size={19} />{t('Authorization is ready.')}</p>}+ {attempt.status === 'running' && <p className="model-muted">{t('Closing this panel keeps the authorization running. You can return to it from this plugin.')}</p>}+ {(state.error || attempt.error) && <p role="alert" className="extension-diagnostic">{state.error ? t(state.error) : attempt.error ? t(attempt.error) : undefined}</p>}+ <div className="extension-actions"><button className="model-secondary" type="button" disabled={state.busy} onClick={() => { if (attempt.status === 'running') void state.cancel(); else state.close() }}>{t(attempt.status === 'running' ? 'Cancel authorization' : 'Done')}</button><button type="button" className="extension-text" disabled={state.busy} onClick={state.reload}>{t('Refresh')}</button></div>+ </div>+ </dialog>+}+function AuthorizationQuestion({ prompt, busy, onAnswer }: { prompt: AuthorizationPrompt; busy: boolean; onAnswer: (answer?: string, decline?: boolean) => void }) {+ const { t } = useLocale(), [answer, setAnswer] = useState(''), fields = useRef<HTMLFieldSetElement>(null)+ const fileInput = useRef<HTMLInputElement>(null), [fileBusy, setFileBusy] = useState(false), [fileError, setFileError] = useState('')+ const jsonFile = prompt.kind !== 'select' && prompt.webInput === 'json-file'+ useEffect(() => { fields.current?.querySelector<HTMLElement>(jsonFile ? 'button' : 'input')?.focus() }, [])+ return <form className="extension-auth-question model-form" onSubmit={event => { event.preventDefault(); if (jsonFile) return; onAnswer(answer); setAnswer('') }}>+ <fieldset ref={fields} disabled={busy || fileBusy}><legend>{t(jsonFile ? 'Select a JSON configuration file.' : prompt.message)}</legend>+ {jsonFile ? <div className="extension-auth-file">+ <Upload size={23} strokeWidth={1.5} /><p>{t('Choose the client JSON downloaded from your provider. It will be parsed and submitted automatically.')}</p>+ <input ref={fileInput} className="extension-file-input" aria-hidden="true" tabIndex={-1} type="file" accept=".json,application/json" onChange={async event => {+ const input = event.currentTarget, file = input.files?.[0]+ if (!file) return+ setFileError(''); setFileBusy(true)+ try { const value = await readAuthorizationJSON(file); onAnswer(value) }+ catch (error) { setFileError(error instanceof Error ? error.message : 'Could not read this configuration file.') }+ finally { input.value = ''; setFileBusy(false) }+ }} />+ <button type="button" className="model-secondary" onClick={() => fileInput.current?.click()}>{fileBusy ? <LoaderCircle size={16} className="extension-auth-spinner" /> : null}{t('Choose JSON file')}</button>+ {fileError && <p role="alert" className="extension-diagnostic">{t(fileError)}</p>}+ </div> : prompt.kind === 'select' ? <div className="extension-auth-options">{prompt.options.map(option => <label key={option.id} className={answer === option.id ? 'is-selected' : undefined}><input type="radio" name={prompt.id} value={option.id} checked={answer === option.id} onChange={() => setAnswer(option.id)} /><span><strong>{t(option.label)}</strong>{option.description && <small>{t(option.description)}</small>}</span></label>)}</div>+ : <input aria-label={t(prompt.message)} autoFocus type={prompt.kind === 'secret' ? 'password' : 'text'} value={answer} maxLength={16384} placeholder={prompt.placeholder} autoComplete="off" onChange={event => setAnswer(event.target.value)} />}+ <div className="extension-actions">{!jsonFile && <button type="submit" className="account-submit" disabled={busy || (prompt.kind === 'select' && !answer)}>{t('Continue')}</button>}<button type="button" className="extension-text" onClick={() => onAnswer(undefined, true)}>{t('Not now')}</button></div>+ </fieldset>+ </form>+}++function MCPConnection({ server, busy, onOpen, onView }: { server: MCPServer; busy: boolean; onOpen: () => void; onView: () => void }) {+ const { t } = useLocale(), active = mcpAuthorizationRunning(server.authorization)+ return <div className="extension-account-row"><KeyRound size={18} strokeWidth={1.6} /><div className="extension-identity"><strong>{connectionTitle(server)}</strong><small>{t(connectionLabel(server))}</small></div><button type="button" className="model-secondary" disabled={busy} onClick={onOpen}>{t(active ? 'Continue authorization' : 'Connect in browser')}</button>{!active && server.authorization?.id && <button type="button" className="extension-text" disabled={busy} onClick={onView}>{t('View last result')}</button>}</div>+}+function MCPAuthorizationDialog({ state }: { state: ReturnType<typeof useMCPAuthorization> }) {+ const { t } = useLocale(), dialog = useRef<HTMLDialogElement>(null), server = state.selected!, attempt = state.attempt!, active = mcpAuthorizationRunning(attempt)+ useReturnFocus()+ useEffect(() => { dialog.current?.showModal() }, [])+ return <dialog ref={dialog} className="extension-auth-dialog" aria-labelledby="mcp-authorization-title" onCancel={event => { event.preventDefault(); state.close() }} onClick={event => { if (event.target !== event.currentTarget) return; const rect = event.currentTarget.getBoundingClientRect(); if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) state.close() }}>+ <header className="extension-auth-heading"><KeyRound size={21} strokeWidth={1.6} /><div><h2 id="mcp-authorization-title">{connectionTitle(server)}</h2><p>{t(mcpAuthorizationLabel(attempt))}</p></div><button type="button" className="extension-icon" aria-label={t('Close')} disabled={state.busy} onClick={state.close}><X size={19} /></button></header>+ <div className="extension-auth-content">+ {active && authorizationURL(attempt.url) && <div className="extension-auth-notice"><p>{t('Complete authorization with the service in your browser, then return here.')}</p><a href={authorizationURL(attempt.url)} target="_blank" rel="noopener noreferrer">{t('Continue in browser')}<ExternalLink size={14} /></a></div>}+ {active && <p className="extension-auth-wait" role="status"><LoaderCircle size={17} className="extension-auth-spinner" />{t('Waiting for authorization to finish…')}</p>}+ {attempt.phase === 'authorized' && <p className="extension-auth-complete" role="status"><Check size={19} />{t('Authorization is ready.')}</p>}+ {(state.error || attempt.error || server.error) && <p className="extension-diagnostic" role="alert">{state.error ? t(state.error) : attempt.error || server.error}</p>}+ <div className="extension-actions">{active ? <button className="model-secondary" disabled={state.busy} onClick={() => { void state.cancel() }}>{t('Cancel authorization')}</button> : <button className="model-secondary" disabled={state.busy} onClick={state.close}>{t('Done')}</button>}<button className="extension-text" disabled={state.busy} onClick={state.reload}>{t('Refresh')}</button></div><p className="model-muted">{t('Closing this panel keeps the authorization running. You can return to it from this plugin.')}</p>+ </div>+ </dialog>+}diff --git a/frontend/src/extensions/Dialogs.tsx b/frontend/src/extensions/Dialogs.tsxnew file mode 100644index 0000000..50a26fa--- /dev/null+++ b/frontend/src/extensions/Dialogs.tsx@@ -0,0 +1,45 @@+import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from 'react'+import { useLocale } from '../locale'+import './extensions.css'++type Confirmation = { message: string; resolve: (accepted: boolean) => void }+const ConfirmContext = createContext<((message: string) => Promise<boolean>) | undefined>(undefined)++// Use the app's own dialog surface. Native window.confirm blocks the renderer+// and prevents live extension state from updating while the user is deciding.+export function ExtensionDialogs({ children }: { children: ReactNode }) {+ const { t } = useLocale()+ const [pending, setPending] = useState<Confirmation>()+ const current = useRef<Confirmation | undefined>(undefined)+ const dialog = useRef<HTMLDialogElement>(null)+ const opener = useRef<Element | null>(null)+ useEffect(() => { if (pending) dialog.current?.showModal() }, [pending])+ useEffect(() => () => { current.current?.resolve(false) }, [])+ function finish(accepted: boolean) {+ const request = current.current+ current.current = undefined+ dialog.current?.close()+ setPending(undefined)+ request?.resolve(accepted)+ requestAnimationFrame(() => { if (opener.current instanceof HTMLElement && opener.current.isConnected) opener.current.focus() })+ }+ function confirm(message: string) {+ if (current.current) return Promise.resolve(false)+ opener.current = document.activeElement+ return new Promise<boolean>(resolve => { const request = { message, resolve }; current.current = request; setPending(request) })+ }+ return <ConfirmContext.Provider value={confirm}>{children}+ <dialog ref={dialog} className="extension-confirm" aria-labelledby="extension-confirm-title" aria-describedby="extension-confirm-copy" onCancel={event => { event.preventDefault(); finish(false) }} onClick={event => {+ if (event.target !== event.currentTarget) return+ const rect = event.currentTarget.getBoundingClientRect()+ if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) finish(false)+ }}>+ {pending && <><h2 id="extension-confirm-title">{t('Confirm change')}</h2><p id="extension-confirm-copy">{t(pending.message)}</p><div className="extension-actions"><button className="model-secondary" type="button" autoFocus onClick={() => finish(false)}>{t('Cancel')}</button><button className="account-submit" type="button" onClick={() => finish(true)}>{t('Confirm')}</button></div></>}+ </dialog>+ </ConfirmContext.Provider>+}+export function useExtensionConfirm() {+ const confirm = useContext(ConfirmContext)+ if (!confirm) throw new Error('ExtensionDialogs is required')+ return confirm+}diff --git a/frontend/src/extensions/PluginIcon.tsx b/frontend/src/extensions/PluginIcon.tsxnew file mode 100644index 0000000..f4291e0--- /dev/null+++ b/frontend/src/extensions/PluginIcon.tsx@@ -0,0 +1,4 @@+import { Puzzle } from 'lucide-react'+export function PluginIcon({ icon, large = false }: { icon?: string; large?: boolean }) {+ return <span className={`plugin-mark${large ? ' plugin-mark-large' : ''}`} aria-hidden="true">{icon ? <img src={icon} alt="" /> : <Puzzle size={large ? 30 : 24} strokeWidth={1.65} />}</span>+}diff --git a/frontend/src/extensions/PluginTutorial.tsx b/frontend/src/extensions/PluginTutorial.tsxnew file mode 100644index 0000000..9902edb--- /dev/null+++ b/frontend/src/extensions/PluginTutorial.tsx@@ -0,0 +1,15 @@+import {useState} from 'react'+import {PlayCircle} from 'lucide-react'+import type {PluginTutorial as Tutorial} from '../api/extensions'+import {useLocale} from '../locale'+import {selectTutorial} from './catalog'+export function PluginTutorial({tutorials}:{tutorials?:Tutorial[]}) {+ const {language,t}=useLocale(),tutorial=selectTutorial(tutorials,language)+ const [playing,setPlaying]=useState(false),[error,setError]=useState(false)+ if(!tutorial)return null+ return <section className="plugin-tutorial"><div className="plugin-tutorial-heading"><h2>{t('Video guide')}</h2><p>{tutorial.title}</p></div>+ {playing ? <video key={tutorial.video} controls playsInline autoPlay preload="metadata" poster={tutorial.poster} onError={()=>setError(true)} src={tutorial.video} /> : <button className="plugin-tutorial-preview" type="button" onClick={()=>{setError(false);setPlaying(true)}} aria-label={t('Play video guide')}>+ {tutorial.poster && <img src={tutorial.poster} alt="" />}<span><PlayCircle size={42} strokeWidth={1.5} />{t('Play video guide')}</span></button>}+ {error && <p role="alert" className="extension-diagnostic">{t('Could not load this video. Try again.')}</p>}+ </section>+}diff --git a/frontend/src/extensions/Plugins.tsx b/frontend/src/extensions/Plugins.tsxnew file mode 100644index 0000000..5638911--- /dev/null+++ b/frontend/src/extensions/Plugins.tsx@@ -0,0 +1,94 @@+import { useEffect, useRef, useState } from 'react'+import { ArrowLeft, ChevronRight, LoaderCircle, MoreHorizontal, Plus, Puzzle, RefreshCw, Trash2 } from 'lucide-react'+import { getPlugins, installPackage, removePackage, restartPlugins, setPluginEnabled, updatePackage, type CatalogEntry } from '../api/extensions'+import type { TranscriptCache } from '../chat/transcriptCache'+import { useLocale } from '../locale'+import { ExtensionFeedback, ExtensionLoading, ExtensionState, useManagedView } from './shared'+import { useExtensionConfirm } from './Dialogs'+import { Authorizations } from './Authorizations'+import { localize } from './catalog'+import { MarkdownText } from '../chat/ChatContent'+import { PluginTutorial } from './PluginTutorial'+import { PluginIcon } from './PluginIcon'++export function Plugins({ userId, cache, selected, onSelect }: { userId: string; cache: TranscriptCache; selected?: string; onSelect: (name: string | undefined) => void }) {+ const { t, language } = useLocale(), confirm = useExtensionConfirm(), managed = useManagedView(userId, getPlugins, cache)+ const { view, busy, run } = managed+ const selectedBusy = !!selected && busy.endsWith(':' + selected)+ const busyName = view?.catalog.find(row => busy.endsWith(':' + row.package))?.name+ const [tab, setTab] = useState<'market' | 'installed'>('market'), [menu, setMenu] = useState<string>()+ const menuRef = useRef<HTMLDivElement>(null), menuTrigger = useRef<HTMLButtonElement | null>(null)+ const detailHeading = useRef<HTMLHeadingElement>(null)+ const names = Object.keys(view?.settings.packages ?? {}).sort()+ useEffect(() => {+ if (!menu) return+ const outside = (event: PointerEvent) => { if (!menuRef.current?.contains(event.target as Node)) setMenu(undefined) }+ const escape = (event: KeyboardEvent) => { if (event.key === 'Escape') { setMenu(undefined); menuTrigger.current?.focus() } }+ document.addEventListener('pointerdown', outside); document.addEventListener('keydown', escape)+ return () => { document.removeEventListener('pointerdown', outside); document.removeEventListener('keydown', escape) }+ }, [menu])+ useEffect(() => { if (selected) detailHeading.current?.focus(); else setTab('market') }, [selected])+ const open = (name: string) => { setMenu(undefined); onSelect(name) }+ const selection = selected ? view?.settings.packages[selected] : undefined+ const release = view?.catalog.find(row => row.package === selected)+ const info = view?.status.packages.find(row => row.name === selected)+ const actual = view?.status.instances.find(row => row.package === selected)+ const title = release ? release.name : info?.title || selected+ const install = async (entry: CatalogEntry) => {+ await run('install:' + entry.package, () => installPackage(userId, entry.pluginId), 'Plugin and dependencies installed. Enable it to use its capabilities.')+ }+ const uninstall = async (name: string) => {+ setMenu(undefined)+ if (await confirm('Uninstall this package? Its credentials and workspace files will stay on disk.')) {+ if (await run('remove:' + name, () => removePackage(userId, name))) onSelect(undefined)+ }+ }+ const more = (name: string, entry?: CatalogEntry) => <div className="plugin-more" ref={menu === name ? menuRef : undefined}>+ <button type="button" className="plugin-icon-button" aria-label={t('More options')} aria-haspopup="menu" aria-expanded={menu === name} disabled={!!busy} onClick={event => { menuTrigger.current = event.currentTarget; setMenu(menu === name ? undefined : name) }}><MoreHorizontal size={20} /></button>+ {menu === name && <div className="plugin-action-menu" role="menu">+ {!selected && <button role="menuitem" onClick={() => open(name)}><ChevronRight size={16} />{t('Plugin details')}</button>}+ {view?.status.packages.find(row => row.name === name)?.availableVersion && entry && <button role="menuitem" onClick={() => { setMenu(undefined); void run('install:' + name, () => updatePackage(userId, name, entry.pluginId)) }}><RefreshCw size={16} />{t('Update plugin')}</button>}+ {entry && <button role="menuitem" onClick={() => { setMenu(undefined); void run('install:' + name, () => updatePackage(userId, name, entry.pluginId)) }}><RefreshCw size={16} />{t('Reinstall plugin')}</button>}+ <button role="menuitem" className="danger" onClick={() => { void uninstall(name) }}><Trash2 size={16} />{t('Uninstall')}</button>+ </div>}+ </div>+ return <section className={`extensions-settings plugin-market${selected ? ' plugin-show-detail' : ''}`}>+ {selected ? <>+ <div className="plugin-detail-navigation">{selection && more(selected, release)}</div>+ <header className="plugin-detail-header"><PluginIcon icon={release?.icon} large /><div><h1 ref={detailHeading} tabIndex={-1}>{title}</h1><p>{release ? localize(release.description, language).split('\n')[0] : info?.description}</p></div></header>+ {release && localize(release.description, language).includes('\n') && <details className="plugin-setup-guide markdown"><summary>{t('Connection setup')}</summary><MarkdownText text={localize(release.description, language).split('\n').slice(1).join('\n').trim()} /></details>}+ {release && <PluginTutorial tutorials={release.tutorials} />}+ <ExtensionFeedback error={managed.error} notice={managed.notice} />+ {busy && <p className="plugin-progress" role="status"><LoaderCircle size={15} />{busyName ? busyName + ' · ' : ''}{t(busy.startsWith('install:') ? 'Installing…' : 'Applying plugin changes…')}</p>}+ {info?.availableVersion && release && <div className="plugin-update-banner"><div><strong>{t('Update available')}</strong><small>{info.version} → {info.availableVersion}</small></div><button className="model-secondary" disabled={!!busy} onClick={() => { void run('install:' + selected, () => updatePackage(userId, selected!, release.pluginId)) }}>{t('Update plugin')}</button></div>}+ {!selection && release ? <button className="account-submit plugin-primary" disabled={!!busy} onClick={() => { void install(release) }}>{selectedBusy ? <LoaderCircle size={16} /> : <Plus size={16} />}{t('Install plugin')}</button> : selection && <div className="plugin-activation">+ <div><strong>{t('Enable plugin')}</strong>{!selectedBusy && <ExtensionState state={actual?.state ?? (selection.enabled ? 'unavailable' : 'disabled')} />}</div>+ <button type="button" className="plugin-switch" role="switch" aria-label={t('Enable plugin')} aria-checked={selection.enabled} disabled={!!busy} onClick={() => { void run('settings:' + selected, () => setPluginEnabled(userId, selected, !selection.enabled)) }}><span /></button>+ </div>}+ {!selectedBusy && (actual?.error || view?.status.error) && <p className="extension-diagnostic" role="alert">{actual?.error || view?.status.error}</p>}+ {release && <>+ <dl className="plugin-detail-facts"><div><dt>{t('Version')}</dt><dd>{info?.present ? info.version : release.version}</dd></div><div><dt>{t('Maintainer')}</dt><dd>{release.maintainer}</dd></div><div><dt>{t('License')}</dt><dd>{release.license}</dd></div></dl>++ </>}+ {selection?.enabled && actual && <Authorizations user={userId} cache={cache} instanceIds={[actual.id]} />}+ </> : <>+ <div className="plugin-market-intro"><p>{t('Extend your agent with plugins reviewed for this project.')}</p><button type="button" className="plugin-icon-button" aria-label={t('Refresh extensions')} onClick={managed.reload}><RefreshCw size={17} /></button></div>+ <div className="extension-tabs" role="tablist" aria-label={t('Plugins')}>{(['market', 'installed'] as const).map(value => <button key={value} type="button" role="tab" aria-selected={tab === value} onClick={() => { setMenu(undefined); setTab(value) }}>{t(value === 'market' ? 'Plugin market' : 'Installed')}{value === 'installed' && <span>{names.length}</span>}</button>)}</div>+ <ExtensionFeedback error={managed.error} notice={managed.notice} />+ {busy && <p className="plugin-progress" role="status"><LoaderCircle size={15} />{busyName ? busyName + ' · ' : ''}{t('Plugin changes continue while you use other features.')}</p>}+ {!view && managed.loading && <ExtensionLoading />}+ {view && <>+ {!(tab === 'market' ? view.catalog.length : names.length) && <div className="extension-empty"><Puzzle size={30} strokeWidth={1.4} /><h3>{t(tab === 'market' ? 'More capabilities are on the way' : 'No plugins installed')}</h3><p>{t('Your built-in agent works without plugins. Add packages when you need more capabilities.')}</p></div>}+ <div className="plugin-grid">{(tab === 'market' ? view.catalog.map(entry => entry.package) : names).map(name => {+ const entry = view.catalog.find(row => row.package === name), saved = view.settings.packages[name], state = view.status.instances.find(row => row.package === name)+ const label = entry ? entry.name : view.status.packages.find(row => row.name === name)?.title || name+ return <article className="plugin-tile" key={name}>+ <button type="button" className="plugin-tile-main" onClick={() => open(name)}><PluginIcon icon={entry?.icon} /><span className="plugin-tile-copy"><strong>{label}</strong><small>{entry ? localize(entry.description, language).split('\n')[0] : name}</small>{view.status.packages.find(row => row.name === name)?.availableVersion && <span className="plugin-update-tag">{t('Update available')}</span>}{tab === 'installed' && <ExtensionState state={state?.state ?? (saved?.enabled ? 'unavailable' : 'disabled')} />}</span></button>+ {busy === 'install:' + name ? <span className="plugin-icon-button plugin-progress" role="status" aria-label={t('Installing…')}><LoaderCircle size={19} /></span> : saved ? more(name, entry) : <button type="button" className="plugin-icon-button" disabled={!!busy} aria-label={t('Install plugin') + ': ' + label} onClick={() => { if (entry) void install(entry) }}><Plus size={22} /></button>}+ </article>+ })}</div>+ {tab === 'installed' && <details className="plugin-runtime-details"><summary>{t('Plugin runtime')}</summary><div className="extension-runtime"><ExtensionState state={view.status.runtime} /><button className="extension-text" disabled={!!busy} onClick={() => { void run('restart', () => restartPlugins(userId)) }}>{t('Restart')}</button></div>{view.status.error && <p className="extension-diagnostic">{view.status.error}</p>}</details>}+ </>}+ </>}+ </section>+}diff --git a/frontend/src/extensions/authorizationFile.ts b/frontend/src/extensions/authorizationFile.tsnew file mode 100644index 0000000..be34b01--- /dev/null+++ b/frontend/src/extensions/authorizationFile.ts@@ -0,0 +1,11 @@+// Configuration is an authorization answer, never a chat attachment or upload.+export async function readAuthorizationJSON(file: { size: number; text(): Promise<string> }): Promise<string> {+ if (file.size > 16384) throw new Error('The configuration file must be 16 KB or smaller.')+ let value: unknown+ try { value = JSON.parse((await file.text()).replace(/^\uFEFF/, '')) }+ catch { throw new Error('Select a valid JSON configuration file.') }+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Select a valid JSON configuration file.')+ const answer = JSON.stringify(value)+ if (new TextEncoder().encode(answer).byteLength > 16384) throw new Error('The configuration file must be 16 KB or smaller.')+ return answer+}diff --git a/frontend/src/extensions/catalog.ts b/frontend/src/extensions/catalog.tsnew file mode 100644index 0000000..38207b6--- /dev/null+++ b/frontend/src/extensions/catalog.ts@@ -0,0 +1,10 @@+import type { Localized, PluginTutorial } from '../api/extensions'++export function localize(text: Localized, language: string): string {+ return language === 'zh-CN' ? text['zh-CN'] : text.en+}+++export function selectTutorial(items: PluginTutorial[] | undefined, language: string): PluginTutorial | undefined {+ return items?.find(item=>item.language===language) ?? items?.find(item=>item.language==='en') ?? items?.[0]+}diff --git a/frontend/src/extensions/connections.ts b/frontend/src/extensions/connections.tsnew file mode 100644index 0000000..31f5f4a--- /dev/null+++ b/frontend/src/extensions/connections.ts@@ -0,0 +1,29 @@+import type { MCPServer, MCPOAuthAttempt } from '../api/extensions'++export function pluginOAuthConnections(servers: MCPServer[], instances: string[]): MCPServer[] {+ return servers.filter(server => server.source === 'plugin' && server.oauthEnabled && instances.some(id => server.name.startsWith(id + '__')))+}+export function mcpAuthorizationRunning(attempt?: MCPOAuthAttempt): boolean {+ return !!attempt && ['starting', 'waiting-browser', 'exchanging', 'committing'].includes(attempt.phase ?? '')+}+export function mcpAuthorizationLabel(attempt: MCPOAuthAttempt): string {+ if (mcpAuthorizationRunning(attempt)) return 'Authorization in progress'+ if (attempt.phase === 'authorized') return 'Authorization complete'+ if (attempt.phase === 'cancelled') return 'Authorization cancelled'+ return 'Authorization failed'+}+export function connectionLabel(server: MCPServer): string {+ if (mcpAuthorizationRunning(server.authorization)) return 'Authorization in progress'+ if (server.state === 'connected') return 'Connected'+ if (server.authorization?.phase === 'authorized') return 'Credential saved'+ if (server.state === 'failed') return 'Connection needs attention'+ return 'Authorization needed'+}+export function connectionTitle(server: MCPServer): string {+ return server.serverName || server.name.slice(server.name.indexOf('__') + 2)+}+export function connectionFailure(error: unknown): string {+ const code = error && typeof error === 'object' ? ('code' in error ? error.code : 'message' in error ? error.message : undefined) : undefined+ if (code === 'oauth_requires_https_or_loopback_http') return 'OAuth requires HTTPS or localhost HTTP. Open the Controller through one of these addresses.'+ return 'Could not complete service authorization. Refresh to check the current state.'+}diff --git a/frontend/src/extensions/extensions.css b/frontend/src/extensions/extensions.cssnew file mode 100644index 0000000..9b4a21d--- /dev/null+++ b/frontend/src/extensions/extensions.css@@ -0,0 +1,211 @@+.extensions-settings { min-width: 0; }+.extension-account-row { display: flex; align-items: center; gap: 14px; padding: 18px 0; border-top: 1px solid #dce2ec; }+.extension-account-row > svg { color: var(--muted); flex: none; }+.extension-auth-method { min-width: 0; max-width: 160px; padding: 9px; font: inherit; font-size: 12px; border: 1px solid #d8dfeb; border-radius: 10px; background: #ffffff80; color: inherit; }+.extension-auth-dialog { width: min(540px, calc(100vw - 36px)); max-height: calc(100dvh - 64px); margin: auto; padding: 0; border: 1px solid #ffffffdc; border-radius: 25px; background: #f8f9fdf7; color: var(--ink); box-shadow: 0 20px 90px #23375320; }+.extension-auth-dialog::backdrop { background: #1e294849; backdrop-filter: blur(7px); }+.extension-auth-heading { display: flex; align-items: center; gap: 13px; padding: 24px 24px 20px; border-bottom: 1px solid #e1e5ef; }+.extension-auth-heading > svg { color: var(--muted); }+.extension-auth-heading > div { flex: 1; min-width: 0; }+.extension-auth-heading h2 { margin: 0; font-size: 18px; font-weight: 600; letter-spacing: -.025em; overflow-wrap: anywhere; }+.extension-auth-heading p { margin: 6px 0 0; font-size: 12px; color: var(--muted); }+.extension-auth-content { display: grid; gap: 24px; padding: 24px; }+.extension-auth-content p { margin: 0; font-size: 14px; line-height: 1.7; overflow-wrap: anywhere; }+.extension-auth-notice { display: grid; gap: 12px; }+.extension-auth-notice code { justify-self: start; padding: 10px 14px; border: 1px solid #dde2ef; border-radius: 12px; background: #ffffffc9; font-size: 17px; letter-spacing: .06em; overflow-wrap: anywhere; }+.extension-auth-notice a { display: inline-flex; align-items: center; gap: 7px; justify-self: start; font-size: 13px; color: var(--accent); text-underline-offset: 4px; }+.extension-auth-question { margin: 0; }+.extension-auth-question fieldset { display: grid; gap: 16px; border: 0; padding: 0; margin: 0; min-width: 0; }+.extension-auth-question legend { margin-bottom: 14px; padding: 0; font-size: 14px; font-weight: 550; }+.extension-auth-question .account-submit { min-height: 42px; width: auto; margin: 0; padding: 10px 20px; font-size: 13px; }+.extension-auth-options { display: grid; gap: 10px; }+.extension-auth-question .extension-auth-options label { display: flex; flex-direction: row; align-items: center; gap: 12px; padding: 14px; border: 1px solid #dce2ed; border-radius: 12px; background: #ffffffb3; }+.extension-auth-question .extension-auth-options label.is-selected { border-color: #bab9d2; background: #f1f0fa; }+.extension-auth-question .extension-auth-options input { width: 16px; height: 16px; min-width: 16px; min-height: 0; flex: none; padding: 0; margin: 0; accent-color: var(--accent); }+.extension-auth-options span { display: grid; gap: 5px; }+.extension-auth-options strong { font-size: 13px; font-weight: 550; }+.extension-auth-options small { color: var(--muted); font-size: 12px; line-height: 1.5; font-weight: 400; }+.extension-auth-wait, .extension-auth-complete { display: flex; gap: 10px; align-items: center; color: var(--muted); }+.extension-auth-complete { color: #397863; }+.extension-auth-spinner { animation: extension-auth-spin 1.2s linear infinite; flex: none; }+@keyframes extension-auth-spin { to { transform: rotate(360deg); } }+@media (prefers-reduced-motion: reduce) { .extension-auth-spinner { animation: none; } }+@media (max-width: 560px) { .extension-account-row { flex-wrap: wrap; } .extension-account-row .extension-identity { min-width: 55%; } .extension-auth-method { margin-left: 32px; } .extension-auth-content, .extension-auth-heading { padding: 20px; } }+.extension-header { display: flex; align-items: start; justify-content: space-between; gap: 20px; margin-bottom: 26px; }+.extension-header .model-muted { max-width: 42ch; margin-bottom: 0; }+.extension-header-actions, .extension-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }+.extension-header-actions { flex: none; }+.extension-header-actions .model-secondary { display: inline-flex; align-items: center; gap: 7px; }+.extension-icon { display: grid; place-items: center; border: 0; background: transparent; color: var(--muted); min-width: 44px; min-height: 44px; border-radius: 10px; }+.extension-icon:hover { background: #e4eaf5; }+.extension-runtime { display: flex; align-items: center; gap: 12px; margin: 4px 0 20px; color: var(--muted); font-size: 12px; }+.extension-runtime .extension-text { margin-left: auto; }+.extension-state { display: inline-flex; align-items: center; gap: 6px; color: #6c7382; font-size: 11px; font-weight: 550; white-space: nowrap; }+.extension-state i { width: 5px; height: 5px; border-radius: 50%; background: currentColor; flex: none; }+.extension-state-good { color: #397863; }+.extension-state-bad { color: #a04b56; }+.extension-list { display: grid; border-top: 1px solid #d8e1ee; }+.extension-row { min-width: 0; border-bottom: 1px solid #d8e1ee; }+.extension-row-toggle { display: flex; align-items: center; gap: 14px; width: 100%; min-height: 87px; padding: 17px 5px; border: 0; text-align: left; background: transparent; color: inherit; }+.extension-row-toggle:hover:not(:disabled) { background: #ffffff50; }+.extension-row-icon { display: grid; place-items: center; flex: none; width: 32px; color: #64728e; }+.extension-identity { flex: 1; display: grid; gap: 6px; min-width: 0; }+.extension-identity strong { font-size: 14px; font-weight: 610; overflow-wrap: anywhere; }+.extension-identity small { color: var(--muted); font-size: 12px; }+.extension-chevron { flex: none; color: var(--muted); transition: transform .18s ease; }+.extension-row-toggle[aria-expanded="true"] .extension-chevron { transform: rotate(180deg); }+.extension-row-body { min-width: 0; padding: 0 13px 25px 51px; }+.extension-facts { display: grid; gap: 12px; margin: 20px 0; font-size: 12px; }+.extension-facts > div { display: grid; grid-template-columns: 118px minmax(0, 1fr); gap: 12px; }+.extension-facts dt { color: var(--muted); }+.extension-facts dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }+.extension-text { display: inline-flex; align-items: center; gap: 6px; padding: 7px 5px; min-height: 44px; border: 0; background: transparent; font-size: 12px; color: #4c5b82; text-align: left; border-radius: 8px; }+.extension-text:hover:not(:disabled) { color: var(--accent); background: #e7edf6; }+.extension-text.danger { color: #9b4c58; }+.extension-actions .account-submit { padding: 10px 18px; font-size: 13px; }+.extension-actions .model-secondary { font-size: 12px; min-height: 44px; }+.extension-feedback { display: flex; align-items: start; gap: 9px; padding: 12px 14px; border-radius: 12px; background: #e9f0ec; font-size: 12px; line-height: 1.65; color: #3f6a59; margin: 0 0 18px; overflow-wrap: anywhere; flex-wrap: wrap; }+.extension-feedback svg { flex: none; margin-top: 2px; }+.extension-error { color: #924854; background: #f6e9ed; }+.extension-diagnostic { font-size: 12px; line-height: 1.7; color: #896d50; overflow-wrap: anywhere; white-space: pre-wrap; }+.extension-empty { display: grid; justify-items: center; text-align: center; padding: 48px 20px 54px; color: #7b879b; }+.extension-empty h3 { margin: 19px 0 8px; font-size: 16px; font-weight: 590; color: #40506b; }+.extension-empty p { max-width: 44ch; margin: 0; font-size: 13px; line-height: 1.75; }+.extension-details { margin: 24px 0; border-top: 1px solid #d8e1ee; }+.extension-details > summary { display: flex; align-items: center; gap: 9px; min-height: 57px; font-size: 13px; color: #596980; cursor: pointer; list-style: none; }+.extension-details > summary::-webkit-details-marker, .extension-advanced > summary::-webkit-details-marker { display: none; }+.extension-details > summary > :last-child { margin-left: auto; }+.extension-details > summary > span { font-size: 11px; color: #7a879b; }+.extension-details[open] > summary > :last-child, .extension-advanced[open] > summary > svg { transform: rotate(180deg); }+.extension-details-body { padding: 3px 0 10px; }+.extension-editor { padding: 23px; margin: 9px 0 22px; border-radius: 18px; background: #ffffff9c; border: 1px solid #ffffffd9; box-shadow: 0 5px 22px #3c537006, inset 0 1px 0 #ffffff; }+.extension-editor h3 { margin: 0 0 23px; font-weight: 600; font-size: 16px; letter-spacing: -.025em; }+.extension-editor label small { color: var(--muted); font-weight: 400; font-size: 11px; line-height: 1.6; }+.model-form .extension-check { display: flex; align-items: center; gap: 9px; font-size: 12px; font-weight: 500; }+.model-form .extension-check input { width: 16px; min-height: 16px; height: 16px; margin: 0; accent-color: var(--accent); }+.extension-advanced { margin: 0; }+.extension-advanced > summary { display: flex; justify-content: space-between; align-items: center; min-height: 44px; cursor: pointer; color: #5e6b82; font-size: 12px; list-style: none; }+.extension-advanced > div { display: grid; gap: 16px; padding: 10px 0 17px; }+.model-form textarea.extension-code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; line-height: 1.7; tab-size: 2; }+.extension-package-review { padding-top: 19px; border-top: 1px solid #e0e6f0; }+.extension-package-review > strong { font-size: 13px; overflow-wrap: anywhere; }+.extension-package-review > strong > span { color: var(--muted); font-weight: 400; margin-left: 8px; }+.extension-package-review > p { font-size: 12px; line-height: 1.7; color: var(--muted); }+.extension-authorization { padding: 16px; margin: 16px 0; border-radius: 12px; background: #e9eef8; }+.extension-authorization p { color: var(--muted); font-size: 12px; line-height: 1.7; margin-top: 0; }+.extension-authorization a { display: inline-flex; align-items: center; gap: 7px; color: var(--accent); text-decoration: none; font-size: 12px; }+.extension-authorization .extension-text { margin-left: 12px; }+.extension-skeleton { display: grid; gap: 16px; margin: 28px 0; }+.extension-skeleton span { height: 63px; border-radius: 12px; background: linear-gradient(90deg, #e3e9f3, #f7f9fc, #e3e9f3); background-size: 200% 100%; animation: extension-loading 1.8s ease infinite; }+.extension-editor-back { margin-top: 16px; }+.extension-confirm { width: min(410px, calc(100vw - 36px)); padding: 27px; border: 1px solid #ffffffd9; border-radius: 21px; background: #f6f8fd; color: #354158; box-shadow: 0 24px 90px #2d3c6a28; }+.extension-confirm::backdrop { background: #27345437; backdrop-filter: blur(3px); }+.extension-confirm h2 { margin: 0 0 13px; font-size: 19px; font-weight: 610; letter-spacing: -.03em; }+.extension-confirm p { font-size: 14px; line-height: 1.75; color: var(--muted); margin: 0 0 23px; }+.extension-confirm .extension-actions { justify-content: flex-end; }+@keyframes extension-loading { to { background-position: -200% 0; } }+@media (prefers-reduced-motion: reduce) { .extension-skeleton span { animation: none; } .extension-chevron { transition: none; } }+@media (max-width: 680px) {+ .extension-header { flex-direction: column; gap: 14px; }+ .extension-header-actions { width: 100%; justify-content: flex-end; }+ .extension-header-actions .model-secondary { margin-left: auto; }+ .extension-row-toggle { gap: 9px; min-height: 84px; flex-wrap: wrap; }+ .extension-row-icon { width: 25px; }+ .extension-identity { min-width: 100px; }+ .extension-identity strong { font-size: 13px; }+ .extension-row-body { padding: 0 2px 23px; }+ .extension-editor { padding: 20px 16px; }+ .extension-facts > div { grid-template-columns: 92px minmax(0, 1fr); }+ .extension-authorization .extension-text { margin-left: 0; display: flex; }+}+++.extension-schema { white-space: pre-wrap; overflow-wrap: anywhere; color: var(--muted); font: 12px/1.7 ui-monospace, monospace; }++.extension-tabs { display: flex; gap: 6px; align-self: flex-start; padding: 4px; margin: 2px 0 22px; border-radius: 15px; background: #e8ecf555; }+.extension-tabs button { display: flex; align-items: center; gap: 9px; min-height: 40px; padding: 9px 18px; border: 1px solid transparent; border-radius: 11px; background: transparent; color: #748097; font: inherit; font-size: 14px; }+.extension-tabs button[aria-selected="true"] { background: #ffffffc7; color: #354567; border-color: #dce3ef77; box-shadow: 0 2px 5px #26344705; }+.extension-tabs button span { font-size: 12px; font-variant-numeric: tabular-nums; opacity: .7; }+.extension-capabilities { color: #586780; padding-left: 19px; font-size: 14px; line-height: 1.85; margin: 12px 0 20px; }+.extension-editor input[type="checkbox"] { width: 18px; min-height: 18px; padding: 0; align-self: flex-start; accent-color: #47598c; }+/* Plugin catalog: quiet application rows, two columns on desktop. */+.plugin-settings-panel { width: min(100%, 1040px); }+.plugin-market-intro { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-bottom: 20px; }+.plugin-market-intro p { margin: 0; color: var(--muted); font-size: 14px; line-height: 1.7; }+.plugin-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); column-gap: 46px; row-gap: 12px; margin: 22px -10px 0; }+.plugin-tile { display: flex; align-items: center; min-width: 0; gap: 5px; border-radius: 16px; padding: 3px 4px 3px 0; transition: background .18s ease; }+.plugin-tile:hover, .plugin-tile:focus-within { background: #ffffff70; }+.plugin-tile-main { display: flex; gap: 16px; align-items: center; flex: 1; min-width: 0; min-height: 112px; padding: 17px 10px; border: 0; border-radius: 14px; background: transparent; text-align: left; color: var(--ink); }+.plugin-mark { display: grid; place-items: center; flex: none; width: 48px; height: 48px; border: 1px solid #26334c12; border-radius: 14px; background: #fff; color: #68738b; overflow: hidden; box-shadow: 0 1px 2px #25314a04; }+.plugin-mark img { display: block; width: 100%; height: 100%; object-fit: contain; }+.plugin-mark-large { width: 66px; height: 66px; border-radius: 18px; }+.plugin-tile-copy { display: grid; gap: 7px; min-width: 0; }+.plugin-tile-copy strong { font-size: 15px; font-weight: 600; letter-spacing: -.015em; line-height: 1.4; }+.plugin-tile-copy small { color: var(--muted); font-size: 13px; line-height: 1.6; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }+.plugin-icon-button { display: grid; place-items: center; width: 44px; height: 44px; min-width: 44px; border: 0; border-radius: 12px; color: #697387; background: transparent; cursor: pointer; transition: background .15s, color .15s, transform .15s; }+.plugin-icon-button:hover:not(:disabled) { background: #ffffffc9; color: var(--ink); }+.plugin-icon-button:active:not(:disabled) { transform: scale(.96); }+.plugin-more { position: relative; flex: none; }+.plugin-action-menu { position: absolute; top: calc(100% + 5px); right: 0; z-index: 5; width: 205px; padding: 6px; border: 1px solid #dfe3eb; border-radius: 15px; background: #fcfcfef5; backdrop-filter: blur(20px); box-shadow: 0 12px 38px #27354a18, 0 2px 6px #27354a09; }+.plugin-action-menu button { width: 100%; min-height: 44px; display: flex; align-items: center; gap: 11px; padding: 11px 12px; border: 0; border-radius: 10px; color: var(--ink); background: transparent; text-align: left; font: inherit; font-size: 13px; }+.plugin-action-menu button:hover { background: #edf0f7; }+.plugin-action-menu button.danger { color: #ab5260; }+.plugin-runtime-details { margin-top: 36px; border-top: 1px solid #26334c10; padding-top: 10px; color: var(--muted); font-size: 12px; }+.plugin-runtime-details summary { min-height: 44px; display: flex; align-items: center; cursor: pointer; }+.plugin-show-detail { max-width: 720px; margin: 0 auto; }+.plugin-detail-navigation { display: flex; align-items: center; justify-content: space-between; margin: -12px 0 23px; }+.plugin-detail-navigation .extension-text { display: inline-flex; align-items: center; gap: 9px; min-height: 44px; }+.plugin-detail-header { display: flex; align-items: flex-start; gap: 20px; margin-bottom: 30px; }+.plugin-detail-header h1 { margin: 1px 0 9px; font-size: 25px; font-weight: 600; letter-spacing: -.035em; outline: none; }+.plugin-detail-header p, .plugin-detail-section p { margin: 0; font-size: 14px; color: var(--muted); line-height: 1.8; }+.plugin-activation { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 20px 23px; margin: 24px 0; border: 1px solid #ffffffdc; border-radius: 18px; background: #ffffff85; box-shadow: 0 1px 7px #2f416004; }+.plugin-activation > div { display: grid; gap: 9px; }+.plugin-activation strong { font-size: 14px; font-weight: 550; }+.plugin-switch { width: 43px; min-height: 26px; padding: 3px; border: 0; border-radius: 20px; background: #cbd0dc; transition: background .2s; }+.plugin-switch span { display: block; width: 20px; height: 20px; border-radius: 100%; background: white; box-shadow: 0 1px 3px #24304b25; transition: transform .2s; }+.plugin-switch[aria-checked="true"] { background: #7983ac; }+.plugin-switch[aria-checked="true"] span { transform: translateX(17px); }+.plugin-detail-section { padding: 25px 0; border-bottom: 1px solid #26334c0e; }+.plugin-detail-section h3 { margin: 0 0 15px; font-size: 14px; font-weight: 600; }+.plugin-detail-section ul { list-style: none; padding: 0; margin: 0; display: grid; gap: 14px; }+.plugin-detail-section li { display: flex; align-items: flex-start; gap: 11px; font-size: 14px; line-height: 1.6; color: var(--muted); }+.plugin-detail-section li svg { flex: none; margin-top: 4px; color: #6a8d80; }+.plugin-detail-section p + p { margin-top: 12px; }+.plugin-detail-facts { display: flex; flex-wrap: wrap; gap: 24px 46px; margin: 26px 0; font-size: 12px; }+.plugin-detail-facts > div { display: grid; gap: 9px; }+.plugin-detail-facts dt { color: var(--muted); }+.plugin-detail-facts dd { margin: 0; color: var(--ink); }+.plugin-market .plugin-primary { display: inline-flex; align-items: center; gap: 9px; width: auto; min-height: 44px; font-size: 14px; padding: 10px 19px; margin: 0 0 8px; }+.plugin-progress { display: inline-flex; align-items: center; gap: 9px; font-size: 13px; color: var(--muted); }+.plugin-progress svg { animation: extension-auth-spin 1.2s linear infinite; }+.plugin-market button:focus-visible { outline: 2px solid #8c98be; outline-offset: 3px; }+@media (max-width: 700px) { .plugin-grid { grid-template-columns: minmax(0, 1fr); gap: 5px; margin-top: 15px; } .plugin-tile-main { min-height: 104px; } .plugin-detail-header { gap: 16px; } .plugin-detail-header h1 { font-size: 23px; } .plugin-detail-facts { gap: 24px; } }+@media (prefers-reduced-motion: reduce) { .plugin-market * { animation: none !important; transition: none !important; } }++.plugin-update-tag { color: #5d70a0; font-size: 11px; font-weight: 600; }+.plugin-update-banner { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 18px 21px; border: 1px solid #d9e1ef; border-radius: 16px; background: #f8faffb3; margin: 20px 0; }+.plugin-update-banner > div { display: grid; gap: 7px; }+.plugin-update-banner strong { font-size: 13px; font-weight: 550; }+.plugin-update-banner small { color: var(--muted); font-size: 12px; }++.plugin-detail-navigation { justify-content: flex-end; margin-bottom: 12px; min-height: 30px; }++.plugin-setup-guide { margin: 0 0 28px; padding: 23px 26px; border-radius: 20px; background: rgba(255,255,255,.5); border: 1px solid rgba(105,115,151,.10); color: var(--muted); font-size: 14px; line-height: 1.8; }+.plugin-setup-guide h2 { margin: 0 0 14px; font-size: 15px; font-weight: 600; color: var(--ink); }+.plugin-setup-guide ol { padding-left: 22px; }+.plugin-setup-guide li { padding: 3px 0 7px 4px; }+.plugin-setup-guide a { overflow-wrap: anywhere; }+.plugin-tutorial { margin: 0 0 28px; max-width: 800px; }+.plugin-tutorial-heading h2 { font-size: 15px; font-weight: 600; margin: 0 0 6px; }+.plugin-tutorial-heading p { color: var(--muted); font-size: 13px; line-height: 1.6; margin: 0 0 14px; }+.plugin-tutorial video, .plugin-tutorial-preview { display: block; width: 100%; aspect-ratio: 16 / 9; border-radius: 18px; overflow: hidden; background: #e9edf3; border: 1px solid rgba(105,115,151,.10); }+.plugin-tutorial-preview { position: relative; padding: 0; cursor: pointer; }+.plugin-tutorial-preview img { width:100%; height:100%; object-fit:contain; }+.plugin-tutorial-preview span { position:absolute; inset:0; display:flex; gap:12px; flex-direction:column; align-items:center; justify-content:center; background:rgba(21,31,47,.27); color:white; font-size:13px; }++.plugin-setup-guide summary { cursor: pointer; font-size: 14px; font-weight: 600; color: var(--ink); }+.plugin-setup-guide[open] summary { margin-bottom: 16px; }++.extension-auth-file { display: grid; justify-items: start; gap: 12px; padding: 22px; border: 1px dashed #c8ccda; border-radius: 15px; background: #ffffff80; color: var(--muted); }+.extension-auth-file p { margin: 0; font-size: 13px; line-height: 1.65; }+.extension-auth-file .extension-file-input { position: absolute; width: 1px; height: 1px; padding: 0; border: 0; opacity: 0; overflow: hidden; }diff --git a/frontend/src/extensions/messages.ts b/frontend/src/extensions/messages.tsnew file mode 100644index 0000000..80302b6--- /dev/null+++ b/frontend/src/extensions/messages.ts@@ -0,0 +1,139 @@+// Shared with Expo; Android's bundle inputs include this external source tree.+export const extensionChinese: Readonly<Record<string, string>> = {+ 'Plugin changes continue while you use other features.': '插件操作会继续进行,你可以使用其他功能。',+ 'Workspace menu': '工作区菜单', 'Close menu': '收起菜单',+ 'Credential saved': '凭证已保存', 'Not configured': '尚未配置', 'The credential has been saved.': '凭证已保存。',+ 'View last result': '查看上次结果', 'Connect in browser': '在浏览器中连接', 'Connection needs attention': '连接需要处理',+ 'Authorize access on the service website, then return here.': '请在服务商网站上授权访问,完成后返回这里。',+ 'Closing this panel keeps the authorization running. You can return to it from this plugin.': '收起面板不会取消授权,可以从此插件重新进入。',+ 'Could not load service connections. Refresh to try again.': '无法读取服务连接,请刷新后重试。',+ 'Could not complete service authorization. Refresh to check the current state.': '未能完成服务授权,请刷新查看当前状态。',+ 'Available version': '\u53ef\u7528\u7248\u672c', 'Enter a valid number.': '\u8bf7\u8f93\u5165\u6709\u6548\u7684\u6570\u5b57\u3002',+ 'Select an option': '请选择',+ 'This plugin has no simple configuration fields. Use its connection options below, or review advanced configuration.': '此插件没有简单配置项。请使用连接与授权入口,或查看高级配置。',+ 'Add another configuration when you need separate accounts for this plugin.': '需要为插件连接不同账号时,可以添加另一份配置实例。',+ 'Maintainer': '维护者',+ 'Advanced configuration': '高级配置',+ 'Advanced': '高级选项',+ 'Update this plugin to the reviewed release?': '更新至当前审核发布的版本?',+ 'Update plugin': '更新插件',+ 'Plugin installed. Configure its instance before enabling it.': '插件已安装,请先配置实例,再启用。',+ 'View installed plugin': '查看已安装插件',+ 'Reviewed business plugins will appear here. Your built-in agent is ready to use.': '经过审核的业务插件将在这里提供。内置助手已可直接使用。',+ 'More capabilities are on the way': '更多能力,即将到来',+ 'Browse plugin market': '浏览插件市场',+ 'Plugin market': '插件市场',+ 'Extend your agent with plugins reviewed for this project.': '通过本项目审核的插件扩展助手能力。',+ 'Refresh': '刷新', 'Close': '关闭', 'Done': '完成', 'Continue': '继续',+ 'Accounts and authorization': '账号与授权', 'Connect accounts using the authorization methods provided by your plugins.': '通过插件提供的授权方式连接外部账号。',+ 'No account authorization methods are available.': '当前没有可用的账号授权方式。', 'Authorization method': '授权方式', 'Authorized': '已授权', 'Not authorized': '未授权', 'Authorize again': '重新授权',+ 'Authorization in progress': '授权进行中', 'Authorization complete': '授权完成', 'Authorization cancelled': '授权已取消', 'Authorization failed': '授权失败',+ 'Continue in browser': '在浏览器中继续', 'Waiting for authorization to finish…': '等待授权完成…', 'The account is ready to use.': '账号已就绪,可以开始使用。', 'Not now': '暂不回答',+ 'Could not load account authorizations. Refresh to try again.': '无法加载账号授权,请刷新后重试。',+ 'Authorization is unavailable. Close this panel and start again if the Host restarted.': '本次授权暂不可用。如果 Host 已重启,请关闭面板并重新发起。',+ 'Could not start authorization. Refresh the account state and try again.': '无法发起授权,请刷新账号状态后重试。',+ 'Could not submit this answer. Check the current question before trying again.': '无法提交回答,请确认当前问题后重试。',+ 'Could not cancel authorization. Refresh to check the current state.': '无法取消授权,请刷新以确认当前状态。',++ 'Some MCP configuration could not be applied. Review the server settings.': '部分 MCP 配置未能应用,请检查对应服务的设置。',+ 'Discover plugins': '发现插件', 'Browse an index, choose a version, then check the package before installing.': '浏览索引、选择版本,再检查包的信息并确认安装。',+ 'Plugin index URL': '插件索引地址', 'Plugin index': '插件索引', 'Add index': '添加索引', 'Remove index': '移除索引',+ 'Search plugins': '搜索插件', 'Search': '搜索', 'Loading plugin index…': '正在读取插件索引…', 'Review package': '查看并检查包',+ 'No indexes configured. Add a reviewed index URL to browse packages.': '尚未配置索引。添加经过审核的索引地址后即可浏览插件。',+ 'No matching plugins.': '没有找到匹配的插件。', 'Could not load plugin index.': '无法读取插件索引。',+ 'An index listing is not a compatibility review. Package checks and your approval are still required.': '收录在索引中不代表已通过兼容性审核。安装前仍需检查包并由你确认。',+ 'Previous': '上一页', 'Next': '下一页', 'Registry': '仓库地址',+ 'Confirm change': '确认修改', 'Confirm': '确认',+ 'Version': '版本', 'Operation in progress': '操作正在执行', 'Wait for the current operation to finish.': '请等待当前操作完成。', 'Could not open the authorization page.': '无法打开授权页面。',+ 'Remove': '移除',+ 'Module entry': '模块入口', 'Use the package export or a module path documented by the plugin author.': '使用插件作者提供的包导出名或模块路径。',+ 'Plugins': '插件', 'MCP': 'MCP', 'Active': '已启用', 'Running': '运行中', 'Connected': '已连接', 'Starting': '启动中', 'Connecting': '连接中', 'Needs setup': '待配置', 'Needs credentials': '缺少凭证', 'Authorization needed': '需要授权', 'Failed': '失败', 'Unavailable': '不可用', 'Stopped': '已停止', 'Disabled': '已停用', 'Stopping': '停止中', 'Disconnected': '未连接',+ 'Install backend capabilities and manage their running instances.': '安装后端扩展能力,管理各个插件实例。',+ 'Connect tools and data sources to your agent.': '为助手连接工具与数据服务。',+ 'Refresh extensions': '刷新扩展状态', 'Install plugin': '安装插件', 'Add server': '添加服务', 'Reinstall plugin': '重新安装插件', 'Update available': '可更新', 'More options': '更多选项', 'Plugin details': '插件详情', 'All plugins': '全部插件', 'Capabilities': '能力', 'Getting started': '开始使用', 'Enable plugin': '启用插件', 'Disable plugin': '停用插件', 'Plugin status': '插件状态', 'Plugin and dependencies installed. Enable it to use its capabilities.': '插件及依赖已安装,启用即可使用。', 'Plugin runtime': '插件运行环境', 'Restart': '重启',+ 'Runtime restart finished. Review the state below.': '重启请求已完成,请查看下方运行状态。',+ 'Could not load extensions. Try again.': '无法读取扩展配置,请重试。',+ 'Could not complete this operation. Refresh the actual state before trying again.': '操作未能完成,请刷新实际状态后重试。',+ 'Settings were saved, but the Host could not apply them. Refresh to check the actual state.': '配置已保存,但 Host 未能应用。请刷新以查看实际状态。',+ 'Configuration saved. Review the runtime state below.': '配置已保存,请查看下方实际运行状态。',+ 'Start your Host before managing extensions.': '请先启动 Host,再管理扩展。',+ 'Host status is unavailable. Saved configuration is shown below.': '暂时无法读取 Host 状态,下方显示已保存的配置。',+ 'No plugins installed': '尚未安装插件', 'Your built-in agent works without plugins. Add packages when you need more capabilities.': '内置助手可直接使用,需要更多能力时再添加插件。',+ 'Bundle enabled': '组合已启用', 'Installed': '已安装', 'Source': '来源', 'License': '许可证', 'Required services': '所需服务', 'Enable bundle': '启用组合', 'Disable bundle': '停用组合', 'Change source or version': '修改来源或版本', 'Add instance': '添加实例', 'Uninstall': '卸载',+ 'Uninstall this package? Its instance data will stay on disk.': '卸载此插件包?实例的业务数据会保留在磁盘上。',+ 'Missing credentials': '缺少凭证', 'Missing dependencies': '缺少依赖', 'Configure': '配置', 'Enable instance': '启用实例', 'Disable instance': '停用实例',+ 'Composition and advanced settings': '组合与高级配置', 'Manage bundles, instance patches, approved package builds and index sources.': '管理组合、实例补丁、允许执行构建的依赖包及索引来源。', 'Edit composition': '编辑组合', 'Composition (JSON)': '组合配置(JSON)', 'Save composition': '保存组合',+ 'Enter bundles, patch, approvedBuilds and indexSources as JSON arrays.': 'bundles、patch、approvedBuilds 和 indexSources 必须为 JSON 数组。',+ 'Change package source': '修改插件包来源', 'Package name': '插件包名', 'Source type': '来源类型', 'Host directory': 'Host 内目录', 'Archive URL or Host path': '归档地址或 Host 内路径', 'Version or tag (optional)': '版本或标签(可选)', 'Source URL or absolute Host path': '来源地址或 Host 内绝对路径',+ 'This directory must exist inside the Host. A path on your phone or computer is not a Host path.': '该目录必须存在于 Host 内。手机或电脑上的路径不等于 Host 内的路径。',+ 'Private source authentication': '私有来源认证', 'Registry URL (optional)': 'Registry 地址(可选)', 'Credential reference (optional)': '凭证引用名(可选)', 'Username (optional)': '用户名(可选)', 'Pinned source': '固定来源', 'Enable bundle after installation': '安装完成后启用组合',+ 'Install packages you trust. Plugins run code inside your Host.': '请安装可信任的插件包。插件会在 Host 内执行代码。',+ 'Check package': '检查插件包', 'Checking…': '检查中…', 'Applying plugin changes…': '正在应用插件变更…', 'Installing…': '安装中…', 'Confirm installation': '确认安装', 'Package checked. Review its details before installing.': '检查已完成,请核对插件包信息后安装。', 'Package installed. Review its instances below.': '插件包已安装,请查看下方实例状态。',+ 'Instance configuration': '实例配置', 'Instance ID': '实例 ID', 'This instance ID is already in use.': '该实例 ID 已被使用。', 'Configuration override (JSON)': '配置覆盖项(JSON)',+ 'Only overrides are shown. Bundle defaults remain in the package. Use credential references for secrets.': '这里只显示覆盖项,组合默认值仍由插件包提供。私密值请使用凭证引用。',+ 'Save configuration': '保存配置', 'Could not save configuration.': '无法保存配置。', 'Enter a JSON object.': '请输入 JSON 对象。',+ 'Credentials': '凭证', 'Values stay private. Reference them in configuration as ${credential:name}.': '凭证值不会回显。在配置中通过 ${credential:name} 引用。', 'Saved': '已保存', 'Reference name': '引用名称', 'Secret value': '凭证值', 'Save credential': '保存凭证',+ 'Remove this credential? Extensions using it may need setup again.': '删除此凭证?使用该凭证的扩展可能需要重新配置。',+ 'No MCP servers yet': '尚未添加 MCP 服务', 'Add an HTTP service or a process that runs inside your Host.': '可以连接 HTTP 服务,或启动在 Host 内运行的进程。', 'Provided by {name}': '由 {name} 提供', 'Host process': 'Host 内进程', 'HTTP connection': 'HTTP 连接', 'Connection': '连接', 'Tools': '工具', 'Protocol version': '协议版本', 'Resources': '资源', 'Available': '可用', 'Probe result': '探测结果', '{count} tools': '{count} 个工具',+ 'Continue in your browser to authorize this connection.': '请在浏览器中继续,完成此连接的授权。', 'Continue authorization': '继续授权', 'Cancel authorization': '取消授权', 'Open plugin settings': '打开插件配置', 'Edit configuration': '编辑配置', 'Test connection': '测试连接', 'Connection probe finished.': '连接探测已完成。', 'Reconnect': '重新连接', 'Authorize': '授权', 'Authorization request prepared.': '授权请求已准备好。', 'Disconnect authorization': '断开授权',+ 'Disconnect this authorization? Saved server configuration will be kept.': '断开此授权?已保存的服务配置会保留。', 'Remove this MCP server?': '移除此 MCP 服务?',+ 'Add MCP server': '添加 MCP 服务', 'Edit MCP server': '编辑 MCP 服务', 'Server name': '服务名称', 'Use letters, digits, underscores or hyphens.': '使用字母、数字、下划线或连字符。', 'Transport': '连接方式', 'Host process (stdio)': 'Host 内进程(stdio)', 'Server URL': '服务地址', 'Executable': '可执行程序', 'Arguments (JSON array)': '参数(JSON 数组)',+ 'This command runs inside the Host, not on your computer or phone.': '此命令在 Host 内运行,不会在你的电脑或手机上执行。', 'Enable this server': '启用此服务', 'Advanced options': '高级选项', 'Tool loading': '工具加载方式', 'Load on connection': '连接时加载', 'Load on demand': '按需加载', 'Working directory': '工作目录', 'Environment (JSON object)': '环境变量(JSON 对象)', 'Headers (JSON object)': '请求头(JSON 对象)',+ 'Use credential references for API keys. Do not paste keys into configuration.': 'API 密钥请使用凭证引用,不要将密钥直接粘贴到配置中。', 'Use OAuth': '使用 OAuth', 'OAuth client ID (optional)': 'OAuth 客户端 ID(可选)', 'Client secret reference (optional)': '客户端密钥引用(可选)', 'Scopes (one per line)': '授权范围(每行一个)',+ 'Leave the client ID blank when the provider supports dynamic registration.': '如果服务商支持动态注册,可将客户端 ID 留空。', 'Save server': '保存服务', 'Back to server': '返回服务详情', 'This server name is already in use.': '该服务名已被使用。',+ 'Use string values for environment variables and headers.': '环境变量和请求头的值必须是字符串。', 'Replace redacted values with credential references before saving.': '请先将已隐藏的值替换为凭证引用,再保存。', 'Enter arguments as a JSON array of strings.': '参数必须是由字符串组成的 JSON 数组。', 'Enter valid JSON in the advanced fields.': '请在高级字段中输入有效的 JSON。',+ 'OAuth requires HTTPS or localhost HTTP. Open the Controller through one of these addresses.': 'OAuth 需要 HTTPS 或 localhost HTTP 地址,请通过其中一种地址打开 Controller。',+ 'Instances': '实例', 'Installed packages': '已安装插件包',+ 'Ready': '就绪', 'Pending': '等待加载', 'Configuration (JSON)': '配置(JSON)', 'Configuration schema': '配置格式说明', 'Registry username (optional)': '仓库用户名(可选)',+ 'Use credential references in configuration. Complete service authorization below.': '配置中请使用凭证引用,并在服务授权区域完成授权。',+ 'Uninstall this package? Its credentials and workspace files will stay on disk.': '卸载此插件包?凭证和工作区文件将保留在磁盘中。',+ 'Remove this instance? Credentials and workspace files are retained.': '移除此实例?凭证和工作区文件将保留。',+ 'Inspect package': '检查插件包',+ "Connection setup": "连接步骤",+ "Connect X account": "连接 X 账号",+ "Connect Google account": "连接 Google 账号",+ "Disconnect account": "退出账号授权",+ "Authorization is ready.": "账号授权已就绪。",+ "Could not disconnect this account. Refresh to check the current state.": "无法退出账号授权,请刷新检查当前状态。",+ "Choose the Google Workspace permissions to request.": "选择本次请求的 Google Workspace 权限。",+ "Read and write": "读写",+ "Read Gmail, Drive, Calendar, Docs, Sheets and Slides.": "读取 Gmail、Drive、日历、文档、表格与幻灯片。",+ "Also edit documents, manage files and calendars, and modify Gmail. No Admin permissions.": "还可编辑文档、管理文件与日历、修改 Gmail,不申请管理员权限。",+ "Sign in to X in your browser. After approval, copy the complete redirect URL, even if the local page cannot open.": "在浏览器中登录 X 并同意授权,然后复制完整回跳地址,即使本地页面打不开。",+ "Sign in to Google in your browser. After consent, copy the complete localhost redirect URL from the address bar, even if that page cannot open.": "在浏览器中登录 Google 并同意授权,然后从地址栏复制完整 localhost 回跳地址,即使该页面打不开。",+ "Paste the complete X redirect URL from your browser address bar.": "粘贴浏览器地址栏中的完整 X 回跳地址。",+ "First open the authorization link above and approve access in your browser. Then paste the complete X redirect URL from the address bar.": "先打开上方授权链接,在浏览器中同意授权。完成后,再粘贴地址栏中的完整 X 回跳地址。",+ "Paste the complete Google redirect URL from your browser address bar.": "粘贴浏览器地址栏中的完整 Google 回跳地址。",+ "First open the authorization link above and approve access in your browser. Then paste the complete Google redirect URL from the address bar.": "先打开上方授权链接,在浏览器中同意授权。完成后,再粘贴地址栏中的完整 Google 回跳地址。",+ "The authorization process ended. Start again.": "授权进程已结束,请重新开始。",+ "Video guide": "视频指引",+ "Play video guide": "播放视频指引",+ "Could not load this video. Try again.": "无法加载视频,请重试。",+ "Create your X Developer App and enable OAuth 2.0. Register http://localhost:8080/callback as its callback URL. API usage is billed to your developer account.": "创建自己的 X 开发者应用并启用 OAuth 2.0,登记回调地址 http://localhost:8080/callback。API 调用由你的开发者账户计费。",+ "Enter your X app Client ID.": "填写你的 X 应用 Client ID。",+ "Enter your X app Client Secret. Leave empty only for a public Native App.": "填写你的 X 应用 Client Secret;只有公共 Native App 可留空。",+ 'Enter the Client Secret only for a Web App / confidential client. For a Native App / public client, leave this empty.': '只有 Web App/机密客户端才填写 Client Secret。Native App/公共客户端请留空。',+ 'Sign in to X in your browser. After approval, immediately copy the complete redirect URL here, even if the local page cannot open. X authorization codes expire after 30 seconds.': '在浏览器中登录 X 并授权后,请立即将完整回跳地址复制到这里,即使本地页面打不开。X 授权码只有 30 秒有效。',+ 'Could not verify the imported Google authorization. Check the export and Host network. Your existing account has not been changed.': '无法验证导入的 Google 授权,请检查导出数据和 Host 网络。原有账号未被修改。',+ 'Select a JSON configuration file.': '选择 JSON 配置文件。',+ 'Choose JSON file': '选择 JSON 文件',+ 'Choose the client JSON downloaded from your provider. It will be parsed and submitted automatically.': '选择从服务商下载的客户端 JSON 文件,系统会自动解析并提交配置。',+ 'Select a valid JSON configuration file.': '请选择有效的 JSON 配置文件。',+ 'The configuration file must be 16 KB or smaller.': '配置文件不能超过 16 KB。',+ 'Could not read this configuration file.': '无法读取此配置文件。',+ 'Paste your Google Desktop OAuth client JSON downloaded from Google Cloud.': '粘贴你从 Google Cloud 下载的 Desktop OAuth 客户端 JSON。',+ 'Could not read the saved Google Desktop application configuration. Restore its client_secret.json and try again.': '无法读取已保存的 Google Desktop 应用配置,请恢复其 client_secret.json 后重试。',+ 'Enter a valid Google Desktop OAuth client JSON.': '请填写有效的 Google Desktop OAuth 客户端 JSON。',+ 'Use a Google OAuth client of type Desktop app, with an installed object.': '请使用包含 installed 对象的桌面应用(Desktop app)OAuth 客户端配置。',+ 'Unsupported Google authorization endpoint.': '不支持该 Google 授权端点。',+ 'Unsupported Google token endpoint.': '不支持该 Google 令牌端点。',+ 'The provider rejected the application credentials (invalid_client). Check the app Client ID and Client Secret.': '服务商拒绝了应用凭证(invalid_client),请核对应用的 Client ID 和 Client Secret。',+ 'The provider does not allow this application to use this authorization flow (unauthorized_client). Check the app type and OAuth settings.': '服务商不允许此应用使用该授权流程(unauthorized_client),请核对应用类型和 OAuth 设置。',+ 'The provider rejected the authorization code (invalid_grant). Start again and use the new redirect URL once.': '服务商拒绝了授权码(invalid_grant)。请重新开始,并且只使用一次新的回跳地址。',+ 'The provider rejected the authorization request (invalid_request). Check the app callback URL and use a new redirect URL from this attempt.': '服务商拒绝了授权请求(invalid_request)。请核对应用回调地址,并使用本次新生成的回跳地址。',+ 'The provider rejected the requested permissions (invalid_scope). Check the app permissions.': '服务商拒绝了请求的权限(invalid_scope),请核对应用权限。',+ 'The provider denied account access (access_denied). Check the permissions on the authorization page.': '服务商拒绝账号访问(access_denied),请检查授权页面上的权限。',+ 'The provider rejected the callback URL (redirect_uri_mismatch). Check the callback registered for this app.': '服务商拒绝了回调地址(redirect_uri_mismatch),请核对应用中登记的回调地址。',+ 'The provider could not exchange the authorization code. Check the application settings and start a new authorization attempt.': '服务商未能完成授权码交换,请核对应用设置后重新发起授权。',+ 'Could not reach the authorization provider. Check the Host network and try again.': '无法连接授权服务商,请检查 Host 网络后重试。',+}diff --git a/frontend/src/extensions/operations.ts b/frontend/src/extensions/operations.tsnew file mode 100644index 0000000..10e5217--- /dev/null+++ b/frontend/src/extensions/operations.ts@@ -0,0 +1,25 @@+// One signed-in client keeps its request alive when the plugin screen closes.+// Reads/navigation stay independent; only package mutations are serialized.+export type OperationState = { busy: string; error: string; notice: string; revision: number }+export class ExtensionOperations {+ private state: OperationState = { busy: '', error: '', notice: '', revision: 0 }+ private listeners = new Set<() => void>()+ snapshot = () => this.state+ subscribe = (listener: () => void) => { this.listeners.add(listener); return () => { this.listeners.delete(listener) } }+ private update(change: Partial<OperationState>) { this.state = { ...this.state, ...change }; this.listeners.forEach(listener => listener()) }+ setError = (error: string) => this.update({ error })+ setNotice = (notice: string) => this.update({ notice })+ async run(label: string, work: () => Promise<unknown>, failure: (error: unknown) => string, success: string) {+ if (this.state.busy) return false+ this.update({ busy: label, error: '', notice: '' })+ try { await work(); this.update({ notice: success }); return true }+ catch (error) { this.update({ error: failure(error) }); return false }+ finally { this.update({ busy: '', revision: this.state.revision + 1 }) }+ }+}+const clients = new WeakMap<object, ExtensionOperations>()+export function extensionOperations(client: object) {+ let state = clients.get(client)+ if (!state) { state = new ExtensionOperations(); clients.set(client, state) }+ return state+}diff --git a/frontend/src/extensions/shared.tsx b/frontend/src/extensions/shared.tsxnew file mode 100644index 0000000..f4b45b6--- /dev/null+++ b/frontend/src/extensions/shared.tsx@@ -0,0 +1,85 @@+import { useCallback, useEffect, useState, useSyncExternalStore, type ReactNode } from 'react'+import { AlertCircle, RefreshCw } from 'lucide-react'+import { APIError, settingsApplyFailed } from '../api/controller'+import { useLocale } from '../locale'+import type { TranscriptCache } from '../chat/transcriptCache'+import './extensions.css'+import { extensionOperations } from './operations'+import { useExtensionConfirm } from './Dialogs'++const states: Record<string, string> = { installed: 'Installed', active: 'Active', running: 'Running', connected: 'Connected', ready: 'Ready', loading: 'Starting', connecting: 'Connecting', pending: 'Pending', failed: 'Failed', error: 'Failed', unavailable: 'Unavailable', stopped: 'Stopped', disabled: 'Disabled', stopping: 'Stopping', disconnected: 'Disconnected', 'waiting-credentials': 'Needs credentials', 'waiting-authorization': 'Authorization needed' }+export function ExtensionState({ state }: { state: string }) {+ const { t } = useLocale()+ const tone = ['active', 'running', 'connected', 'ready'].includes(state) ? 'good' : ['failed', 'error'].includes(state) ? 'bad' : 'quiet'+ return <span className={'extension-state extension-state-' + tone}><i aria-hidden="true" />{t(states[state] ?? state)}</span>+}++export function extensionFailure(error: unknown) {+ if (settingsApplyFailed(error)) return 'Settings were saved, but the Host could not apply them. Refresh to check the actual state.'+ if (error instanceof APIError && error.message === 'host_not_running') return 'Start your Host before managing extensions.'+ if (error instanceof APIError && error.message === 'oauth_requires_https_or_loopback_http') return 'OAuth requires HTTPS or localhost HTTP. Open the Controller through one of these addresses.'+ if (error instanceof APIError && [400, 422].includes(error.status) && /\s/.test(error.message)) return error.message.slice(0, 1024)+ return 'Could not complete this operation. Refresh the actual state before trying again.'+}++export function useManagedView<T>(user: string, load: (user: string, signal?: AbortSignal) => Promise<T>, cache: TranscriptCache) {+ const [view, setView] = useState<T>()+ const operations = extensionOperations(cache)+ const { busy, error, notice, revision } = useSyncExternalStore(operations.subscribe, operations.snapshot)+ const [loading, setLoading] = useState(true)+ const [version, setVersion] = useState(0)+ const reload = useCallback(() => setVersion(value => value + 1), [])+ useEffect(() => cache.subscribe('@extensions', reload), [cache, reload])+ useEffect(() => {+ const request = new AbortController()+ setLoading(true)+ void load(user, request.signal).then(value => { if (!request.signal.aborted) { setView(value); if (operations.snapshot().error === 'Could not load extensions. Try again.') operations.setError('') } }, () => {+ if (!request.signal.aborted) operations.setError('Could not load extensions. Try again.')+ }).finally(() => { if (!request.signal.aborted) setLoading(false) })+ return () => request.abort()+ }, [user, load, version, revision, operations])+ useEffect(() => { window.addEventListener('focus', reload); return () => window.removeEventListener('focus', reload) }, [reload])+ const run = (label: string, action: () => Promise<unknown>, success = 'Configuration saved. Review the runtime state below.') =>+ operations.run(label, action, extensionFailure, success)+ return { view, error, notice, busy, loading, reload, run, setError: operations.setError, setNotice: operations.setNotice }+}++export function useUnsavedChanges(dirty: boolean) {+ const confirm = useExtensionConfirm()+ useEffect(() => {+ if (!dirty) return+ const leave = (event: Event) => {+ if (event.defaultPrevented) return+ event.preventDefault()+ const resume = (event as CustomEvent<{ resume: () => void }>).detail?.resume+ if (resume) void confirm('Discard unsaved changes?').then(accepted => { if (accepted) resume() })+ }+ const unload = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' }+ window.addEventListener('go-bot:settings-navigation', leave)+ window.addEventListener('beforeunload', unload)+ return () => { window.removeEventListener('go-bot:settings-navigation', leave); window.removeEventListener('beforeunload', unload) }+ }, [dirty, confirm])+}++export function useReturnFocus() {+ const [opener] = useState(() => document.activeElement)+ useEffect(() => () => { requestAnimationFrame(() => { if (opener instanceof HTMLElement && opener.isConnected) opener.focus() }) }, [opener])+}++export function ExtensionFeedback({ error, notice }: { error: string; notice: string }) {+ const { t } = useLocale()+ return <>{error && <p className="extension-feedback extension-error" role="alert"><AlertCircle size={17} />{t(error)}</p>}+ {notice && <p className="extension-feedback" role="status">{t(notice)}</p>}</>+}+export function ExtensionHeader({ title, description, busy, onRefresh, children }: { title: string; description: string; busy: boolean; onRefresh: () => void; children?: ReactNode }) {+ const { t } = useLocale()+ return <header className="extension-header"><div>{title && <h2 className="settings-section-title">{t(title)}</h2>}<p className="model-muted">{t(description)}</p></div>+ <div className="extension-header-actions"><button type="button" className="extension-icon" disabled={busy} onClick={onRefresh} aria-label={t('Refresh extensions')}><RefreshCw size={17} /></button>{children}</div></header>+}+export function ExtensionLoading() { return <div className="extension-skeleton" aria-busy="true"><span /><span /><span /></div> }++export function parseObject(value: string): Record<string, unknown> {+ const parsed: unknown = JSON.parse(value)+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('Enter a JSON object.')+ return parsed as Record<string, unknown>+}diff --git a/frontend/src/extensions/useAuthorization.ts b/frontend/src/extensions/useAuthorization.tsnew file mode 100644index 0000000..c1ff6f2--- /dev/null+++ b/frontend/src/extensions/useAuthorization.ts@@ -0,0 +1,85 @@+import { useCallback, useEffect, useRef, useState } from 'react'+import type { AuthorizationAPI, AuthorizationAttempt, AuthorizationEntry } from '../api/extensions'+import type { TranscriptCache } from '../chat/transcriptCache'++// Both self-owned clients consume the same upstream interaction vocabulary.+// No credential, answer or attempt handle is persisted in client storage.+export function useAuthorization(api: AuthorizationAPI, cache: TranscriptCache) {+ const [entries, setEntries] = useState<AuthorizationEntry[]>([])+ const [attempt, setAttempt] = useState<AuthorizationAttempt>()+ const [error, setError] = useState(''), [busy, setBusy] = useState(false)+ const [version, setVersion] = useState(0)+ const alive = useRef(true), locked = useRef(false), current = useRef<AuthorizationAttempt | undefined>(undefined)+ const reload = useCallback(() => setVersion(value => value + 1), [])+ const adopt = useCallback((value?: AuthorizationAttempt) => { current.current = value; setAttempt(value) }, [])+ useEffect(() => { alive.current = true; return () => { alive.current = false } }, [api])+ useEffect(() => cache.subscribe('@extensions', reload), [cache, reload])+ useEffect(() => {+ const request = new AbortController()+ void api.list(request.signal).then(next => { if (!request.signal.aborted) { setEntries(next); setError(previous => previous === 'Could not load account authorizations. Refresh to try again.' ? '' : previous) } }, () => {+ if (!request.signal.aborted) setError('Could not load account authorizations. Refresh to try again.')+ })+ return () => request.abort()+ }, [api, version])+ const id = attempt?.id+ useEffect(() => {+ if (!id) return+ const request = new AbortController()+ void api.get(id, request.signal).then(next => { if (!request.signal.aborted) { adopt(next); setError(previous => previous === 'Authorization is unavailable. Close this panel and start again if the Host restarted.' ? '' : previous) } }, () => {+ if (!request.signal.aborted) setError('Authorization is unavailable. Close this panel and start again if the Host restarted.')+ })+ return () => request.abort()+ }, [api, id, version, adopt])+ async function run(work: () => Promise<AuthorizationAttempt>, message: string, closeMissing = false) {+ if (locked.current) return+ locked.current = true; setBusy(true); setError('')+ try {+ const next = await work()+ if (alive.current) { adopt(next); reload() }++ } catch (error) {+ if (alive.current) {+ if (closeMissing && typeof error === 'object' && error && 'status' in error && [404, 409, 503].includes(Number(error.status))) { adopt(undefined); setError('') }+ else setError(message)+ reload()+ }+ }+ finally { locked.current = false; if (alive.current) setBusy(false) }+ }+ const start = (key: string, method: string) => run(() => api.start(key, method), 'Could not start authorization. Refresh the account state and try again.')+ const answer = (promptId: string, value?: string, decline?: boolean) => {+ const attempt = current.current+ return attempt && run(() => api.answer(attempt.id, promptId, value, decline), 'Could not submit this answer. Check the current question before trying again.')+ }+ async function cancelKey(key: string) {+ if (locked.current) return+ locked.current = true; setBusy(true); setError('')+ try { await api.cancelKey(key) }+ catch { if (alive.current) setError('Could not cancel authorization. Refresh to check the current state.') }+ finally { locked.current = false; if (alive.current) { setBusy(false); reload() } }+ }+ async function disconnect(key: string) {+ if (locked.current) return+ locked.current = true; setBusy(true); setError('')+ try { await api.disconnect(key) }+ catch { if (alive.current) setError('Could not disconnect this account. Refresh to check the current state.') }+ finally { locked.current = false; if (alive.current) { setBusy(false); reload() } }+ }+ function close() {+ if (locked.current) return+ adopt(undefined); setError(''); reload()+ }+ const open = (id: string) => run(() => api.get(id), 'Authorization is unavailable. Close this panel and start again if the Host restarted.')+ const cancel = () => {+ const value = current.current+ return value && run(() => api.cancel(value.id), 'Could not cancel authorization. Refresh to check the current state.', true)+ }+ return { entries, attempt, error, busy, reload, start, answer, close, open, cancel, cancelKey, disconnect }++}++export function authorizationURL(value?: string) {+ try { const url = new URL(value ?? ''); return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password ? url.href : undefined }+ catch { return undefined }+}+export const authorizationLabel = { running: 'Authorization in progress', authorized: 'Authorization complete', cancelled: 'Authorization cancelled', failed: 'Authorization failed' }diff --git a/frontend/src/extensions/useMCPAuthorization.ts b/frontend/src/extensions/useMCPAuthorization.tsnew file mode 100644index 0000000..1b93675--- /dev/null+++ b/frontend/src/extensions/useMCPAuthorization.ts@@ -0,0 +1,55 @@+import { useCallback, useEffect, useRef, useState } from 'react'+import type { MCPAuthorizationAPI, MCPServer } from '../api/extensions'+import type { TranscriptCache } from '../chat/transcriptCache'+import { connectionFailure, mcpAuthorizationRunning, pluginOAuthConnections } from './connections'++// A view adapter only: OAuth discovery, callback state, PKCE, token exchange+// and persistence remain in the existing Go MCP/authorization services.+export function useMCPAuthorization(api: MCPAuthorizationAPI, cache: TranscriptCache, instanceIds: string[]) {+ const [all, setAll] = useState<MCPServer[]>([]), [version, setVersion] = useState(0)+ const [opened, setOpened] = useState<string>()+ const [busy, setBusy] = useState(false), [error, setError] = useState('')+ const alive = useRef(true), locked = useRef(false)+ const reload = useCallback(() => setVersion(value => value + 1), [])+ useEffect(() => { alive.current = true; return () => { alive.current = false } }, [api])+ useEffect(() => cache.subscribe('@extensions', reload), [cache, reload])+ useEffect(() => {+ const call = new AbortController()+ void api.list(call.signal).then(view => {+ if (call.signal.aborted) return+ setAll(view.status.servers); setError(view.status.error ? 'Could not load service connections. Refresh to try again.' : '')+ }, () => { if (!call.signal.aborted) setError('Could not load service connections. Refresh to try again.') })+ return () => call.abort()+ }, [api, version])+ const servers = pluginOAuthConnections(all, instanceIds)+ const selected = opened ? servers.find(server => server.name === opened) : undefined+ const attempt = selected?.authorization+ async function run(work: () => Promise<void>) {+ if (locked.current) return+ locked.current = true; setBusy(true); setError('')+ try { await work() }+ catch (error) { if (alive.current) setError(connectionFailure(error)) }+ finally { locked.current = false; if (alive.current) { setBusy(false); reload() } }+ }+ const open = (server: MCPServer) => run(async () => {+ const current = server.authorization+ if (!mcpAuthorizationRunning(current)) {+ await api.start(server.name)+ const view = await api.list()+ if (alive.current) setAll(view.status.servers)+ }+ if (alive.current) setOpened(server.name)+ })+ function resume(server: MCPServer) {+ if (server.authorization?.id) { setOpened(server.name); setError(''); reload() }+ }+ const cancel = () => run(async () => {+ if (opened && attempt?.id) await api.cancel(opened, attempt.id)+ })+ const signOut = (server: MCPServer) => run(async () => {+ await api.signOut(server.name)+ if (alive.current && opened === server.name) setOpened(undefined)+ })+ const close = () => { if (!locked.current) { setOpened(undefined); setError(''); reload() } }+ return { servers, selected, attempt, busy, error, reload, open, resume, cancel, signOut, close }+}diff --git a/frontend/src/messages.ts b/frontend/src/messages.tsindex 16b0ddc..1b8e67f 100644--- a/frontend/src/messages.ts+++ b/frontend/src/messages.ts@@ -1,6 +1,28 @@+import { extensionChinese } from './extensions/messages'+export type Language = 'en' | 'zh-CN'const chinese: Readonly<Record<string, string>> = {+ ...extensionChinese,+ "Brave Search API key": "Brave 搜索 API 密钥", "Tavily API key": "Tavily API 密钥",+ "Approve this plan and leave plan mode?": "确认方案后开始执行,或提出修改意见继续规划。",+ "Approve": "按此方案执行", "Keep planning": "继续完善方案",+ "Leave plan mode; the plan is carried out from the next step.": "退出规划模式,从下一步开始执行方案。",+ "Stay in plan mode; feedback goes back to the model.": "保持规划模式,将修改意见交给助手。",+ "Plan review": "方案审阅", "Review the plan": "审阅方案",+ "Approval needed": "待审批", "Answer needed": "待回答",+ "Model ID": "模型 ID", "Add model": "添加模型", "Remove model": "移除模型", "Move up": "上移", "Move down": "下移",+ "The first model is the endpoint default.": "第一个模型是此端点的默认模型。",+ "Discard unsaved changes?": "放弃未保存的修改?",++ "Supports OpenAI Responses and Anthropic Messages compatible endpoints.": "支持 OpenAI Responses 和 Anthropic Messages 兼容接口。",+ "API protocol": "接口协议",+ "Choose the API format provided by your service, regardless of the model name.": "按服务商提供的接口格式选择,与模型名称无关。",+ "Request URL": "请求地址",+ "Choose a supported API protocol.": "请选择支持的接口协议。",+ "Enter a base URL without /messages, /responses, or /chat/completions.": "请填写基础地址,不包含 /messages、/responses 或 /chat/completions。",+ "This model will be used from the next turn.": "将在下一轮使用此模型。",+"Language": "语言","Go Bot Chat": "Go Bot 会话","Create an account": "创建账号",diff --git a/frontend/src/sessions/Sidebar.tsx b/frontend/src/sessions/Sidebar.tsxindex 0b3b1f0..92147ac 100644--- a/frontend/src/sessions/Sidebar.tsx+++ b/frontend/src/sessions/Sidebar.tsx@@ -1,10 +1,12 @@import { useEffect, useRef, useState } from 'react'import { useLocale } from '../locale'-import { ChevronDown, Ellipsis, FolderTree, MessageSquare, MessageSquarePlus, Power, Settings, Trash2, X } from 'lucide-react'+import { ChevronDown, Ellipsis, FolderTree, MessageSquare, MessageSquarePlus, Power, Puzzle, Settings, Trash2, X } from 'lucide-react'import { HarnessAvatar } from '../HarnessAvatar'import type { SessionRow } from '../api/controller'+import type { TranscriptCache } from '../chat/transcriptCache'type Props = {+ cache: TranscriptCacheuserId: stringrows: SessionRow[]selected?: string@@ -14,6 +16,8 @@ type Props = {error: stringneedsModel: booleanonSettings: () => void+ onPlugins: () => void+ pluginsOpen: booleanfilesOpen: booleanfilesAvailable: booleanfilesOverlay: boolean@@ -129,6 +133,7 @@ export function Sidebar(props: Props) {}}><MessageSquare size={16} strokeWidth={1.65} /><span className="chat-label">{rowTitle(row)}+ {props.cache.summary(row.sessionId)?.pending && <small className="session-attention"><span aria-hidden="true" />{t(props.cache.summary(row.sessionId)?.pending === 'approval' ? 'Approval needed' : 'Answer needed')}</small>}{!row.title && <small>{new Date(row.createdAt).toLocaleString(language, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</small>}</span></button>@@ -143,6 +148,8 @@ export function Sidebar(props: Props) {))}{props.hasMore && <button type="button" className="text-button more" disabled={props.isLoading} onClick={props.onMore}>{t('Load more')}</button>}</div>+ <div className="sidebar-footer">+ <button id="plugin-market-link" type="button" className="sidebar-destination" aria-current={props.pluginsOpen ? 'page' : undefined} onClick={props.onPlugins}><Puzzle size={19} strokeWidth={1.7} /><span>{t('Plugin market')}</span></button><div className="account-dock" ref={accountDock} onBlur={event => {if (!event.currentTarget.contains(event.relatedTarget)) setAccountOpen(false)}} onKeyDown={event => {@@ -175,6 +182,7 @@ export function Sidebar(props: Props) {</div>}{props.stopHostError && <p className="sidebar-feedback" role="alert">{t(props.stopHostError)}</p>}</div>+ </div></aside>{menu && (<div className="context-menu" role="menu" aria-label={t('Chat actions')}diff --git a/frontend/src/settings/Models.tsx b/frontend/src/settings/Models.tsxindex ecbdc23..80b61f3 100644--- a/frontend/src/settings/Models.tsx+++ b/frontend/src/settings/Models.tsx@@ -1,6 +1,7 @@import { useEffect, useState, type FormEvent } from 'react'import { useLocale } from '../locale'-import { Plus } from 'lucide-react'+import { changeProtocolURL, modelProtocol, modelRequestURL, protocolNames, protocolURLs, type ModelProtocol } from './modelProtocol'+import { ArrowDown, ArrowUp, Plus, X } from 'lucide-react'import { APIError, deleteEndpoint, getModelSettings, saveDefaultEndpoint, saveEndpoint, settingsApplyFailed, type ModelEndpoint, type ModelSettings } from '../api/controller'export function Models({ userId }: { userId: string }) {@@ -35,6 +36,10 @@ export function Models({ userId }: { userId: string }) {setError('Settings were saved, but the Host could not apply them. Reopen the account to load the saved settings.')} else if (error instanceof APIError && error.message === 'api_key_required_for_new_origin') {setError('Enter an API key for the new endpoint address.')+ } else if (error instanceof APIError && error.message === 'invalid_model_protocol') {+ setError('Choose a supported API protocol.')+ } else if (error instanceof APIError && error.message === 'model_base_url_required') {+ setError('Enter a base URL without /messages, /responses, or /chat/completions.')} else if (error instanceof APIError && error.message === 'invalid_model_endpoint') {setError('Check the endpoint URL, API key, and model IDs. Model IDs must be unique.')} else {@@ -48,7 +53,7 @@ export function Models({ userId }: { userId: string }) {return (<><h2 className="settings-section-title">{t('Models')}</h2>- <p className="model-muted">{t('Only OpenAI-compatible Responses API endpoints are supported.')}</p>+ <p className="model-muted">{t('Supports OpenAI Responses and Anthropic Messages compatible endpoints.')}</p>{error && <p role="alert" className="account-error">{t(error)}</p>}{notice && <p role="status">{t(notice)}</p>}{!settings && !error && <p role="status">{t('Loading model settings…')}</p>}@@ -59,7 +64,7 @@ export function Models({ userId }: { userId: string }) {{editing === id ? <EndpointForm endpoint={endpoint} busy={busy} onCancel={() => setEditing(undefined)}onSave={value => { void update(() => saveEndpoint(userId, id, value), 'Endpoint saved.') }} /> : <><h2>{endpoint.name} {settings.defaultEndpointId === id && <span className="model-default">{t('Default endpoint')}</span>}</h2>- <p className="model-muted">{endpoint.baseUrl} · {endpoint.hasApiKey ? t('API key saved') : t('API key missing')}</p>+ <p className="model-muted"><span className="model-protocol-badge">{protocolNames[modelProtocol(endpoint.protocol)]}</span> {endpoint.baseUrl} · {endpoint.hasApiKey ? t('API key saved') : t('API key missing')}</p><ul className="model-list">{endpoint.models.map((model, index) => <li key={model}>{model}{index === 0 && <span> · {t('Default model')}</span>}</li>)}</ul><div className="model-settings-actions"><button type="button" disabled={busy} className="model-secondary" onClick={() => setEditing(id)}>{t('Edit')}</button>@@ -92,13 +97,22 @@ function EndpointForm({ endpoint, busy, onSave, onCancel }: {}) {const { t } = useLocale()const [name, setName] = useState(endpoint?.name ?? '')- const [baseUrl, setBaseURL] = useState(endpoint?.baseUrl ?? '')+ const [protocol, setProtocol] = useState<ModelProtocol>(modelProtocol(endpoint?.protocol))+ const [baseUrl, setBaseURL] = useState(endpoint?.baseUrl ?? protocolURLs.responses)const [key, setKey] = useState('')- const [models, setModels] = useState(endpoint?.models.join('\n') ?? '')+ const [models, setModels] = useState<string[]>(endpoint?.models ?? [''])++ function moveModel(index: number, direction: number) {+ const next = [...models]; [next[index], next[index + direction]] = [next[index + direction], next[index]]; setModels(next)+ }+ function cancel() {+ const changed = name !== (endpoint?.name ?? '') || protocol !== modelProtocol(endpoint?.protocol) || baseUrl !== (endpoint?.baseUrl ?? protocolURLs.responses) || key !== '' || JSON.stringify(models) !== JSON.stringify(endpoint?.models ?? [''])+ if (!changed || window.confirm(t('Discard unsaved changes?'))) onCancel()+ }function submit(event: FormEvent<HTMLFormElement>) {event.preventDefault()- onSave({ name: name.trim(), baseUrl: baseUrl.trim(), models: models.split('\n').map(model => model.trim()).filter(Boolean),+ onSave({ protocol, name: name.trim(), baseUrl: baseUrl.trim(), models: models.map(model => model.trim()).filter(Boolean),...(key.trim() ? { apiKey: key.trim() } : {}) })}@@ -106,14 +120,29 @@ function EndpointForm({ endpoint, busy, onSave, onCancel }: {<h2>{endpoint ? t('Edit endpoint') : t('Add endpoint')}</h2><fieldset disabled={busy}><label>{t('Name')}<input value={name} required maxLength={128} onChange={event => setName(event.target.value)} /></label>- <label>{t('Base URL')}<input type="url" value={baseUrl} required placeholder="https://api.example.com/v1" onChange={event => setBaseURL(event.target.value)} /></label>+ <label>{t('API protocol')}<select value={protocol} onChange={event => {+ const next = event.target.value as ModelProtocol+ setBaseURL(changeProtocolURL(baseUrl, protocol, next)); setProtocol(next)+ }}><option value="responses">OpenAI Responses</option><option value="anthropic_messages">Anthropic Messages</option></select></label>+ <small>{t('Choose the API format provided by your service, regardless of the model name.')}</small>+ <label>{t('Base URL')}<input type="url" value={baseUrl} required placeholder={protocolURLs[protocol]} onChange={event => setBaseURL(event.target.value)} /></label>+ <small className="model-request-url">{t('Request URL')}: {modelRequestURL(baseUrl, protocol)}</small><label>{t('API key')}<input type="password" value={key} required={!endpoint?.hasApiKey} autoComplete="new-password"placeholder={endpoint?.hasApiKey ? t('Leave blank to keep saved key') : undefined} onChange={event => setKey(event.target.value)} /></label>- <label>{t('Model IDs')}<textarea rows={4} value={models} required onChange={event => setModels(event.target.value)}- aria-describedby="model-order" /><small id="model-order">{t('One model per line. The first model is the endpoint default.')}</small></label>+ <div className="model-id-editor"><span>{t('Model IDs')}</span>+ {models.map((model, index) => <div className="model-id-row" key={index}>+ <input aria-label={t('Model ID') + ' ' + (index + 1)} value={model} required maxLength={256} onChange={event => setModels(models.map((value, i) => i === index ? event.target.value : value))} placeholder="model-id" />+ {index === 0 && <small>{t('Default model')}</small>}+ <button type="button" className="model-row-action" title={t('Move up')} aria-label={t('Move up')} disabled={index === 0} onClick={() => moveModel(index, -1)}><ArrowUp size={15} /></button>+ <button type="button" className="model-row-action" title={t('Move down')} aria-label={t('Move down')} disabled={index === models.length - 1} onClick={() => moveModel(index, 1)}><ArrowDown size={15} /></button>+ <button type="button" className="model-row-action" title={t('Remove model')} aria-label={t('Remove model')} disabled={models.length === 1} onClick={() => setModels(models.filter((_, i) => i !== index))}><X size={15} /></button>+ </div>)}+ <button type="button" className="model-secondary settings-add" onClick={() => setModels([...models, ''])}><Plus size={15} />{t('Add model')}</button>+ <small>{t('The first model is the endpoint default.')}</small>+ </div><div className="model-settings-actions"><button type="submit" className="account-submit">{busy ? t('Saving…') : t('Save endpoint')}</button>- <button type="button" className="model-secondary" onClick={onCancel}>{t('Cancel')}</button>+ <button type="button" className="model-secondary" onClick={cancel}>{t('Cancel')}</button></div></fieldset></form>diff --git a/frontend/src/settings/ToolProviders.tsx b/frontend/src/settings/ToolProviders.tsxindex 4db1179..10ad064 100644--- a/frontend/src/settings/ToolProviders.tsx+++ b/frontend/src/settings/ToolProviders.tsx@@ -6,6 +6,8 @@ import { APIError, getProviderSettings, removeProviderKey, saveProviderSettings,import providerDocs from '../../../docs/providers.md?url&no-inline'const keyHelp: Record<string, { label: string; url: string }> = {+ brave: { label: 'Brave Search API key', url: 'https://api-dashboard.search.brave.com/' },+ tavily: { label: 'Tavily API key', url: 'https://app.tavily.com/' },deepseek: { label: 'DeepSeek Search API', url: 'https://platform.deepseek.com/' },zhipu: { label: 'BigModel API key', url: 'https://bigmodel.cn/usercenter/proj-mgmt/apikeys' },doubao: { label: 'Doubao Search Custom API key', url: 'https://docs.volcengine.com/docs/networked-search/networked-search?lang=zh' },diff --git a/frontend/src/settings/modelProtocol.ts b/frontend/src/settings/modelProtocol.tsnew file mode 100644index 0000000..0f51bfb--- /dev/null+++ b/frontend/src/settings/modelProtocol.ts@@ -0,0 +1,10 @@+export type ModelProtocol = 'responses' | 'anthropic_messages'+export const protocolNames: Record<ModelProtocol, string> = { responses: 'OpenAI Responses', anthropic_messages: 'Anthropic Messages' }+export const protocolURLs: Record<ModelProtocol, string> = { responses: 'https://api.openai.com/v1', anthropic_messages: 'https://api.anthropic.com/v1' }+export function modelProtocol(value?: ModelProtocol): ModelProtocol { return value ?? 'responses' }+export function changeProtocolURL(url: string, previous: ModelProtocol, next: ModelProtocol) {+ return !url || url === protocolURLs[previous] ? protocolURLs[next] : url+}+export function modelRequestURL(url: string, protocol: ModelProtocol) {+ return url.trim().replace(/\/+$/, '') + (protocol === 'anthropic_messages' ? '/messages' : '/responses')+}diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.cssindex 2cb6715..df20d70 100644--- a/frontend/src/styles/app.css+++ b/frontend/src/styles/app.css@@ -674,3 +674,30 @@ button:focus-visible, textarea:focus-visible, a:focus-visible {.permission-decisions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 12px; }.permission-decisions button { padding: 7px 12px; border: 1px solid #d6dff8; border-radius: 9px; background: #fff; color: #334269; font-weight: 650; }.permission-decisions button:last-child { background: #455ca0; color: #fff; border-color: #455ca0; }++.model-form select { width: 100%; min-height: 44px; padding: 10px 12px; border: 1px solid var(--line, #dddce8); border-radius: 12px; background: rgba(255,255,255,.8); color: inherit; font: inherit; }+.model-protocol-badge { display: inline-block; font-size: 11px; line-height: 1.7; padding: 1px 7px; margin-right: 5px; border: 1px solid rgba(98,81,138,.14); border-radius: 6px; vertical-align: middle; }+.model-request-url { overflow-wrap: anywhere; }++.model-id-editor { display: grid; gap: 10px; }+.model-id-row { display: flex; gap: 6px; align-items: center; }+.model-id-row input { min-width: 0; flex: 1; }+.model-id-row small { white-space: nowrap; color: #5c6072; }+.model-row-action { display: grid; place-items: center; padding: 8px; border: none; border-radius: 8px; background: transparent; color: #5c6072; }+.model-row-action:hover { background: #eeecf6; }+.model-row-action:disabled { opacity: .3; }++.chat-label .session-attention { display: flex; align-items: center; gap: 5px; padding-top: 4px; color: #8a6138; font-size: 11px; font-weight: 500; }+.session-attention > span { width: 5px; height: 5px; border-radius: 50%; background: #bc8b55; flex: none; }++.question-detail { max-height: 30vh; overflow: auto; padding: 6px 12px; margin: 10px 0; border: 1px solid rgba(112,122,163,.12); border-radius: 10px; background: rgba(255,255,255,.65); }+.question-detail.markdown h1 { font-size: 18px; margin: 8px 0 12px; }+.question-detail.markdown h2 { font-size: 15px; margin: 14px 0 6px; }+.question-panel .question-option { padding: 7px 2px; gap: 8px; }++.question-dock:has(.plan-review) { max-height: min(60vh, 480px); }+.plan-review .question-detail { max-height: min(18vh, 160px); }++.sidebar-footer { flex: none; margin-top: auto; padding-top: 12px; }+.sidebar-destination { display: flex; align-items: center; gap: 11px; width: 100%; min-height: 45px; padding: 11px 14px; border: 0; border-radius: 13px; background: transparent; color: #53617b; text-align: left; font: inherit; font-size: 14px; }+.sidebar-destination:hover, .sidebar-destination[aria-current="page"] { background: #ffffff70; color: #35496f; }diff --git a/frontend/tests/authorizationFile.test.ts b/frontend/tests/authorizationFile.test.tsnew file mode 100644index 0000000..c849931--- /dev/null+++ b/frontend/tests/authorizationFile.test.ts@@ -0,0 +1,13 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { readAuthorizationJSON } from '../src/extensions/authorizationFile.ts'+const file = (text: string) => ({size: new TextEncoder().encode(text).length, text: async () => text})+test('client JSON file is parsed and sent as the existing authorization answer', async () => {+ assert.equal(await readAuthorizationJSON(file('\uFEFF{\n "installed": {"client_id":"test", "client_secret":"private"}\n}')), '{"installed":{"client_id":"test","client_secret":"private"}}')+})+test('invalid and oversized files are rejected locally without echoing their contents', async () => {+ for (const content of ['private-invalid-json', 'null', '[]', '"private"']) {+ await assert.rejects(readAuthorizationJSON(file(content)), error => error instanceof Error && error.message === 'Select a valid JSON configuration file.')+ }+ await assert.rejects(readAuthorizationJSON({size:16385,text:async()=>{throw new Error('must not read oversized file')}}), /16 KB/)+})diff --git a/frontend/tests/hostConnection.test.ts b/frontend/tests/hostConnection.test.tsnew file mode 100644index 0000000..03a32e2--- /dev/null+++ b/frontend/tests/hostConnection.test.ts@@ -0,0 +1,87 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { HostConnection } from '../src/chat/hostConnection.ts'+import { TranscriptCache, cacheTranscript } from '../src/chat/transcriptCache.ts'+import { messageText, attemptMessage } from '../src/chat/transcript.ts'++const page = (throughSeq = 3) => ({ events: [], before: null, throughSeq, queue: [], questions: [] })+const question = { callId: 'ask', turn: 1, step: 1, questions: [{ id: 'choice', question: 'Choose?' }] }++test('Host extension events invalidate management state without touching chat or session lists', () => {+ const cache = new TranscriptCache()+ cache.keep('a', cacheTranscript(page()))+ let extensions = 0, sessions = 0, chats = 0+ cache.subscribe('@extensions', () => extensions++)+ cache.subscribe('@sessions', () => sessions++)+ cache.subscribe('a', () => chats++)+ cache.receive({ type: 'extensions.changed', data: {} })+ assert.equal(extensions, 1)+ assert.equal(sessions, 0)+ assert.equal(chats, 0)+ assert.equal(cache.get('a')?.transcript.messages.length, 0)+})++test('multiplexes sessions without loading unopened histories or sharing their questions', () => {+ const cache = new TranscriptCache()+ cache.keep('a', cacheTranscript(page()))+ cache.receive({ sessionId: 'b', type: 'questions.state', data: { questions: [question] } })+ assert.equal(cache.summary('b')?.pending, 'question')+ assert.equal(cache.get('b'), undefined)+ assert.deepEqual(cache.get('a')?.transcript.questions, [])+ cache.receive({ sessionId: 'b', type: 'questions.state', data: { questions: [] } })+ assert.equal(cache.summary('b')?.pending, null)+ assert.deepEqual(cache.cursors(), { a: 3 })+})++test('merges messages received while history loads exactly once and rejects older control snapshots', () => {+ const cache = new TranscriptCache()+ cache.beginLoad('a')+ cache.receive({ sessionId: 'a', type: 'session.state', data: { throughSeq: 1, activeTurn: 1 } })+ const event = { seq: 4, type: 'user/message', data: { id: 'new', blocks: [{ id: 'text', type: 'text', text: 'new message' }] } }+ cache.receive({ sessionId: 'a', type: 'session', data: event })+ cache.receive({ sessionId: 'a', type: 'questions.state', data: { throughSeq: 4, questions: [question] } })+ cache.finishLoad('a', page())+ assert.deepEqual(cache.get('a')?.transcript.messages.map(messageText), ['new message'])+ assert.equal(cache.get('a')?.transcript.activeTurn, null)+ assert.equal(cache.get('a')?.transcript.questions.length, 1)+ cache.receive({ sessionId: 'a', type: 'session', data: event })+ assert.equal(cache.get('a')?.transcript.messages.length, 1)+})++test('merges a live snapshot and increasing stream revisions without losing its prefix', () => {+ const cache = new TranscriptCache()+ cache.beginLoad('a')+ cache.receive({ sessionId: 'a', type: 'assistant-stream', data: { frame: {+ type: 'start', attemptId: 'one', revision: 1, turn: 1, step: 1, startedAfterSeq: 3,+ } } })+ for (const [index, text] of ['Hello', ' world'].entries()) cache.receive({ sessionId: 'a', type: 'assistant-stream', data: { frame: {+ type: 'chunk', attemptId: 'one', revision: index + 2, index, chunk: { type: 'text-delta', text },+ } } })+ const entry = cache.finishLoad('a', { ...page(), baseline: { revision: 2, activeAttempt: {+ attemptId: 'one', turn: 1, step: 1, startedAfterSeq: 3, nextIndex: 1,+ stream: [{ type: 'text-chunks', texts: ['Hello'] }],+ } } })+ assert.ok(entry.transcript.draft)+ assert.equal(messageText(attemptMessage(entry.transcript.draft)), 'Hello world')+})++test('one connection survives session changes and reconnects using all cached cursors', async () => {+ const cache = new TranscriptCache()+ let calls = 0+ let terminate: (() => void) | undefined+ const controller = new HostConnection(cache, async (cursors, signal, opened) => {+ calls+++ if (calls === 2) assert.deepEqual(cursors, { a: 3, b: 9 })+ opened()+ await new Promise<void>(resolve => { terminate = resolve; signal.addEventListener('abort', () => resolve(), { once: true }) })+ })+ controller.start()+ cache.keep('a', cacheTranscript(page()))+ cache.keep('b', cacheTranscript(page(9)))+ assert.equal(calls, 1)+ assert.equal(cache.connecting, false)+ terminate?.()+ await new Promise(resolve => setTimeout(resolve, 550))+ assert.equal(calls, 2)+ controller.stop()+})diff --git a/frontend/tests/modelProtocol.test.ts b/frontend/tests/modelProtocol.test.tsnew file mode 100644index 0000000..1c9899f--- /dev/null+++ b/frontend/tests/modelProtocol.test.ts@@ -0,0 +1,10 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { changeProtocolURL, modelProtocol, modelRequestURL } from '../src/settings/modelProtocol.ts'++test('protocol switch preserves custom URLs and replaces untouched defaults', () => {+ assert.equal(modelProtocol(), 'responses')+ assert.equal(changeProtocolURL('https://api.openai.com/v1', 'responses', 'anthropic_messages'), 'https://api.anthropic.com/v1')+ assert.equal(changeProtocolURL('https://proxy.example/prefix/v1', 'responses', 'anthropic_messages'), 'https://proxy.example/prefix/v1')+ assert.equal(modelRequestURL('https://proxy.example/apps/anthropic/v1/', 'anthropic_messages'), 'https://proxy.example/apps/anthropic/v1/messages')+})diff --git a/frontend/tests/pluginCatalog.test.ts b/frontend/tests/pluginCatalog.test.tsnew file mode 100644index 0000000..b514fc5--- /dev/null+++ b/frontend/tests/pluginCatalog.test.ts@@ -0,0 +1,18 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { localize } from '../src/extensions/catalog.ts'+test('reviewed plugin copy follows the local interface language', () => {+ assert.equal(localize({en:'Browser','zh-CN':'浏览器'}, 'zh-CN'), '浏览器')+ assert.equal(localize({en:'Browser','zh-CN':'浏览器'}, 'en'), 'Browser')+})++test('tutorial selection follows interface language without provider-specific URLs', async()=>{+ const {selectTutorial}=await import('../src/extensions/catalog.ts')+ const en={language:'en' as const,title:'Connect account',video:'/assets/plugins/service/setup.en.mp4'}+ const zh={language:'zh-CN' as const,title:'连接账号',video:'/assets/plugins/service/setup.zh-CN.mp4'}+ assert.equal(selectTutorial([en,zh],'zh-CN'),zh)+ assert.equal(selectTutorial([en,zh],'en'),en)+ assert.equal(selectTutorial([en],'zh-CN'),en)+ assert.equal(selectTutorial([zh],'en'),zh)+ assert.equal(selectTutorial(undefined,'en'),undefined)+})diff --git a/frontend/tests/pluginConnections.test.ts b/frontend/tests/pluginConnections.test.tsnew file mode 100644index 0000000..9ac7f97--- /dev/null+++ b/frontend/tests/pluginConnections.test.ts@@ -0,0 +1,21 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { connectionLabel, mcpAuthorizationRunning, pluginOAuthConnections } from '../src/extensions/connections.ts'+import type { MCPServer } from '../src/api/extensions.ts'++const server = (overrides: Partial<MCPServer> = {}): MCPServer => ({ name: 'mail__account', source: 'plugin', state: 'waiting-authorization', oauthEnabled: true, ...overrides })++test('connection choices follow declared OAuth and exact plugin instance namespaces', () => {+ const services = [server(), server({ name: 'mail__public', oauthEnabled: false }), server({ name: 'mailbox__other' }), server({ name: 'mail__manual', source: 'user' })]+ assert.deepEqual(pluginOAuthConnections(services, ['mail']).map(item => item.name), ['mail__account'])+ assert.deepEqual(pluginOAuthConnections(services, []), [])+})++test('credential authorization and an actual service connection remain distinct', () => {+ const grant = { id: 'attempt', name: 'mail__account', state: 'authorized', phase: 'authorized' }+ assert.equal(connectionLabel(server({ state: 'failed', authorization: grant })), 'Credential saved')+ assert.equal(connectionLabel(server({ state: 'connected' })), 'Connected')+ assert.equal(mcpAuthorizationRunning({ ...grant, phase: 'committing' }), true)+ assert.equal(mcpAuthorizationRunning({ ...grant, phase: 'failed' }), false)+ assert.equal(mcpAuthorizationRunning(undefined), false)+})diff --git a/frontend/tests/pluginOperations.test.ts b/frontend/tests/pluginOperations.test.tsnew file mode 100644index 0000000..574f0a9--- /dev/null+++ b/frontend/tests/pluginOperations.test.ts@@ -0,0 +1,32 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { extensionOperations } from '../src/extensions/operations.ts'++test('installation survives leaving and reopening the plugin screen without starting twice', async () => {+ const client = {}, operations = extensionOperations(client)+ let finish!: () => void, calls = 0, notifications = 0+ const unsubscribe = operations.subscribe(() => notifications++)+ const pending = operations.run('install:browser', () => new Promise<void>(resolve => { calls++; finish = resolve }), () => 'failed', 'installed')+ assert.equal(operations.snapshot().busy, 'install:browser')+ unsubscribe() // The screen closes while the request stays in flight.+ const reopened = extensionOperations(client)+ assert.equal(reopened, operations)+ assert.equal(reopened.snapshot().busy, 'install:browser')+ assert.equal(await reopened.run('install:office', async () => { calls++ }, () => 'failed', 'installed'), false)+ assert.equal(calls, 1)+ assert.equal(extensionOperations({}).snapshot().busy, '')+ finish()+ assert.equal(await pending, true)+ assert.deepEqual(reopened.snapshot(), { busy: '', error: '', notice: 'installed', revision: 1 })+ assert.equal(notifications, 1)+})++test('a failed background install remains visible on return and permits a retry', async () => {+ const operations = extensionOperations({})+ assert.equal(await operations.run('install:x', async () => { throw new Error('download failed') }, () => 'Could not install', 'installed'), false)+ assert.equal(operations.snapshot().error, 'Could not install')+ assert.equal(operations.snapshot().busy, '')+ assert.equal(await operations.run('install:x', async () => {}, () => 'failed', 'installed'), true)+ assert.equal(operations.snapshot().error, '')+ assert.equal(operations.snapshot().notice, 'installed')+})diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 3050460..3dc76b2 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -14,7 +14,8 @@ export default defineConfig({strictPort: true,fs: { allow: [searchForWorkspaceRoot(process.cwd()), fileURLToPath(new URL('../docs/providers.md', import.meta.url))] },proxy: {- '/v1': { target: 'http://127.0.0.1:8080', changeOrigin: true },+ // OAuth callbacks return through this same public /v1 route.+ '/v1': { target: 'http://127.0.0.1:8080', changeOrigin: false },},},})diff --git a/go.mod b/go.modindex 8357283..575bd99 100644--- a/go.mod+++ b/go.mod@@ -8,12 +8,14 @@ require (github.com/gen2brain/webp v0.6.4github.com/gin-gonic/gin v1.10.1github.com/google/uuid v1.6.0+ github.com/modelcontextprotocol/go-sdk v1.8.0github.com/nlnwa/whatwg-url v0.6.2github.com/redis/go-redis/v9 v9.23.0github.com/santhosh-tekuri/jsonschema/v6 v6.0.3github.com/teambition/rrule-go v1.8.2golang.org/x/image v0.33.0golang.org/x/net v0.49.0+ golang.org/x/oauth2 v0.35.0golang.org/x/sys v0.49.0gopkg.in/yaml.v3 v3.0.1modernc.org/sqlite v1.62.0@@ -32,11 +34,18 @@ require (github.com/clbanning/mxj/v2 v2.7.0 // indirectgithub.com/dustin/go-humanize v1.1.0 // indirectgithub.com/ebitengine/purego v0.10.1 // indirect+ github.com/google/jsonschema-go v0.4.3 // indirectgithub.com/gorilla/websocket v1.5.3 // indirectgithub.com/ncruces/go-strftime v1.1.0 // indirectgithub.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect+ github.com/segmentio/asm v1.1.3 // indirect+ github.com/segmentio/encoding v0.5.4 // indirectgithub.com/tjfoc/gmsm v1.4.1 // indirect+ github.com/yosida95/uritemplate/v3 v3.0.2 // indirectgo.uber.org/atomic v1.12.0 // indirect+ golang.org/x/mod v0.43.0 // indirect+ golang.org/x/sync v0.24.0 // indirect+ golang.org/x/time v0.15.0 // indirectgopkg.in/ini.v1 v1.67.0 // indirectmodernc.org/libc v1.80.1 // indirectmodernc.org/mathutil v1.7.1 // indirectdiff --git a/go.sum b/go.sumindex 2a36df6..a2d5668 100644--- a/go.sum+++ b/go.sum@@ -113,6 +113,8 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=@@ -128,9 +130,12 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5agithub.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=-github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=+github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=+github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs=github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=@@ -156,6 +161,8 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=+github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=+github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=@@ -179,6 +186,10 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=+github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=+github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=+github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=+github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=github.com/smartystreets/assertions v1.1.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo=github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=@@ -206,6 +217,8 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkSgithub.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=@@ -249,6 +262,8 @@ golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=+golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=+golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=@@ -274,6 +289,8 @@ golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=+golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=+golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=@@ -336,6 +353,8 @@ golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=diff --git a/harness/agent/anthropic_test.go b/harness/agent/anthropic_test.gonew file mode 100644index 0000000..a1ad412--- /dev/null+++ b/harness/agent/anthropic_test.go@@ -0,0 +1,138 @@+package agent++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ agentcontent "go-bot/harness/content"+ "go-bot/harness/session"+ "go-bot/internal/modeldata"+ "go-bot/thirdparty/llm"+)++type anthropicNonstreamModel struct{ adapter LLMAdapter }++func (m anthropicNonstreamModel) Complete(ctx context.Context, messages []Message, specs []ToolSpec) (modeldata.AssistantMessage, error) {+ return m.adapter.Complete(ctx, messages, specs)+}++func TestAnthropicNativeReplaySurvivesRestoreAndCrossProtocolSwitch(t *testing.T) {+ calls := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ raw, _ := io.ReadAll(r.Body)+ calls+++ if calls == 1 {+ _, _ = io.WriteString(w, `{"id":"m1","stop_reason":"tool_use","content":[{"type":"thinking","thinking":"consider","signature":"native-signature"},{"type":"tool_use","id":"call_1","name":"echo","input":{}}],"usage":{}}`)+ return+ }+ if calls == 2 || calls == 3 {+ if !strings.Contains(string(raw), `"signature":"native-signature"`) {+ t.Errorf("signed thinking absent after tool/restart: %s", raw)+ }+ }+ if calls == 5 {+ if strings.Contains(string(raw), "native-signature") {+ t.Error("compaction replayed signed thinking instead of portable context")+ }+ _, _ = io.WriteString(w, `{"stop_reason":"end_turn","content":[{"type":"text","text":"## Primary Request and Intent\nContinue the task."}],"usage":{}}`)+ return+ }+ if calls == 4 {+ if r.URL.Path != "/responses" || strings.Contains(string(raw), "native-signature") || strings.Contains(string(raw), "anthropic_message") {+ t.Error("native data leaked across protocol")+ }+ _, _ = io.WriteString(w, `{"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"switched"}]}]}`)+ return+ }+ _, _ = io.WriteString(w, `{"id":"m2","stop_reason":"end_turn","content":[{"type":"text","text":"done"}],"usage":{}}`)+ }))+ defer server.Close()+ client, _ := llm.NewClient(llm.Endpoint{BaseURL: server.URL, APIKey: "k"}, "model", server.Client())+ model := anthropicNonstreamModel{LLMAdapter{Transport: client, Protocol: llm.AnthropicMessages}}+ header := sessionformat.Header{Type: "session", Version: 4, ID: "anthropic-replay", CreatedAt: 1}+ journal := &nativeTestJournal{}+ live, err := sessionformat.NewLiveSession(header, journal)+ if err != nil {+ t.Fatal(err)+ }+ loop, err := NewNativeLoop(live, model, "endpoint", "model", "prompt", []Tool{&nativeTestTool{}}, 4, 4)+ if err != nil {+ t.Fatal(err)+ }+ ctx := WithModelRoute(t.Context(), ModelRoute{Provider: "endpoint", Model: "model"})+ if answer, err := loop.RunTextTurn(ctx, "use echo "+strings.Repeat("old-context ", 300)); err != nil || answer != "done" {+ t.Fatalf("tool turn: %s %v", answer, err)+ }+ events := live.DurableEvents()+ reopened := &nativeTestJournal{events: append([]sessionformat.Event(nil), events...)}+ restored, err := sessionformat.RestoreLiveSession(sessionformat.PhysicalArtifact{Header: header, Events: events}, reopened)+ if err != nil {+ t.Fatal(err)+ }+ next, err := NewNativeLoop(restored, model, "endpoint", "model", "prompt", []Tool{&nativeTestTool{}}, 4, 4)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := next.RunTextTurn(ctx, "continue"); err != nil {+ t.Fatal(err)+ }+ messages, err := nativeModelMessages(restored, nil)+ if err != nil {+ t.Fatal(err)+ }+ adapter := LLMAdapter{Transport: client, Protocol: llm.Responses}+ if _, err := adapter.Complete(ctx, messages, nil); err != nil {+ t.Fatal(err)+ }+ if calls != 4 {+ t.Fatalf("unexpected model calls %d", calls)+ }+ if compacted, err := next.CompactNow(ctx); err != nil || !compacted {+ t.Fatalf("Anthropic compaction: %v %v", compacted, err)+ }+ if err := sessionformat.ValidateV4Relationships(restored.DurableEvents()); err != nil {+ t.Fatal(err)+ }+ // A different Anthropic endpoint/model receives portable history only.+ capture := &capturingLLMTransport{response: &llm.Response{Status: "completed", Output: []llm.Item{{Type: "message", Content: []llm.ContentBlock{{Type: "text", Text: "ok"}}}}}}+ _, err = (LLMAdapter{Transport: capture, Protocol: llm.AnthropicMessages}).Complete(WithModelRoute(ctx, ModelRoute{Provider: "other", Model: "model"}), messages, nil)+ if err != nil {+ t.Fatal(err)+ }+ for _, item := range capture.request.Input {+ if item.Type == "anthropic_message" {+ t.Fatal("replayed native data into another endpoint")+ }+ }+}++func TestAnthropicReplayIsBoundToEndpointAddress(t *testing.T) {+ capture := &capturingLLMTransport{response: &llm.Response{Status: "completed", Output: []llm.Item{{Type: "message", Content: []llm.ContentBlock{{Type: "text", Text: "ok"}}}}}}+ message := Message{Role: "assistant", Content: "portable", ProviderReplay: &modeldata.ProviderReplay{Protocol: string(llm.AnthropicMessages), EndpointID: "same-id", EndpointURL: "https://old.example/v1", ModelID: "model", Content: []json.RawMessage{json.RawMessage(`{"type":"text","text":"native"}`)}}}+ adapter := LLMAdapter{Transport: capture, Protocol: llm.AnthropicMessages, EndpointURL: "https://new.example/v1"}+ _, err := adapter.Complete(WithModelRoute(t.Context(), ModelRoute{Provider: "same-id", Model: "model"}), []Message{message}, nil)+ if err != nil {+ t.Fatal(err)+ }+ if len(capture.request.Input) != 1 || capture.request.Input[0].Type != "message" || capture.request.Input[0].Content[0].Text != "portable" {+ t.Fatal("native replay followed an edited endpoint address")+ }+}++func TestAnthropicToolImageStaysInResult(t *testing.T) {+ capture := &capturingLLMTransport{response: &llm.Response{Status: "completed", Output: []llm.Item{{Type: "message", Content: []llm.ContentBlock{{Type: "text", Text: "ok"}}}}}}+ ref := agentcontent.ImageAttachment{ID: "image", MIMEType: "image/png", Bytes: 5, Width: 1, Height: 1}+ adapter := LLMAdapter{Transport: capture, Protocol: llm.AnthropicMessages, Images: &recordingImageReader{data: []byte("image")}, ImageInputEnabled: true}+ _, err := adapter.Complete(t.Context(), []Message{{Role: "tool", ToolCallID: "call-1", IsError: true, ContentBlocks: []agentcontent.ContentBlock{{Type: "text", Text: "result"}, agentcontent.ImageBlock(ref)}}}, nil)+ if err != nil {+ t.Fatal(err)+ }+ if len(capture.request.Input) != 1 || capture.request.Input[0].Type != "tool_result" || !capture.request.Input[0].IsError || len(capture.request.Input[0].Content) != 2 || capture.request.Input[0].Content[1].Source == nil {+ t.Fatalf("detached image or error flag: %+v", capture.request.Input)+ }+}diff --git a/harness/agent/execution_sandbox.go b/harness/agent/execution_sandbox.gonew file mode 100644index 0000000..e34d97c--- /dev/null+++ b/harness/agent/execution_sandbox.go@@ -0,0 +1,28 @@+package agent++import "path/filepath"++// ExecutionSandboxPolicy carries the current Go session policy across a+// capability boundary. It is not another permission store or Session projection.+// The filesystem provider accepts the same per-call shape as upstream.+type ExecutionSandboxPolicy struct {+ Mode string `json:"mode"`+ WorkspaceRoot string `json:"workspaceRoot"`+ SessionID string `json:"sessionId,omitempty"`+}++// SetSandboxModeSource binds the existing permission owner at Host assembly.+// The source is read at each operation boundary; the Agent keeps no mode copy.+func (a *NativeLoop) SetSandboxModeSource(source func() string) { a.sandboxMode = source }++func (a *nativeTools) executionSandboxPolicy() *ExecutionSandboxPolicy {+ header := a.header()+ if !filepath.IsAbs(header.CWD) {+ return nil+ }+ mode := "danger-full-access"+ if a.sandboxMode != nil {+ mode = a.sandboxMode()+ }+ return &ExecutionSandboxPolicy{Mode: mode, WorkspaceRoot: header.CWD, SessionID: header.ID}+}diff --git a/harness/agent/llm_adapter.go b/harness/agent/llm_adapter.goindex 08a8a99..e07655f 100644--- a/harness/agent/llm_adapter.go+++ b/harness/agent/llm_adapter.go@@ -3,6 +3,7 @@ package agentimport ("context""encoding/base64"+ "encoding/json""errors""fmt""slices"@@ -26,6 +27,7 @@ type LLMStreamTransport interface {}type LLMAdapter struct {+ EndpointURL stringTransport LLMTransportProtocol llm.ProtocolImages ImageAttachmentReader@@ -130,7 +132,16 @@ func (a LLMAdapter) complete(ctx context.Context, messages []Message, specs []ToreferenceIDs := slices.ContainsFunc(specs, func(spec ToolSpec) bool { return spec.Name == "generateimage" })resolved := make(map[string]resolvedModelImage)metadata := make(map[string]agentcontent.ImageAttachment)+ route, _ := ModelRouteFromContext(ctx)for _, message := range messages {+ if replay := message.ProviderReplay; message.Role == "assistant" && a.Protocol == llm.AnthropicMessages && replay != nil && replay.Protocol == string(a.Protocol) && replay.EndpointID == route.Provider && replay.ModelID == route.Model && replay.EndpointURL == a.EndpointURL && ModelCallOptionsFromContext(ctx).Purpose != "compaction" {+ raw, err := json.Marshal(replay.Content)+ if err != nil {+ return modeldata.AssistantMessage{}, err+ }+ input = append(input, llm.Item{Type: "anthropic_message", Role: "assistant", Raw: raw})+ continue+ }if message.Role == "assistant" && len(message.OrderedAssistantBlocks) > 0 {ordered, err := orderedAssistantRequestItems(message.OrderedAssistantBlocks)if err != nil {@@ -193,6 +204,13 @@ func (a LLMAdapter) complete(ctx context.Context, messages []Message, specs []Toreturn modeldata.AssistantMessage{}, fmt.Errorf("unsupported model content block %q", block.Type)}}+ if message.Role == "tool" && a.Protocol == llm.AnthropicMessages {+ input = append(input, llm.Item{Type: "tool_result", CallID: message.ToolCallID, Content: blocks, IsError: message.IsError})+ for index := startImages; index < len(images); index++ {+ images[index].itemIndex = len(input) - 1+ }+ continue+ }if message.Role == "tool" {var resultText strings.Builderfor index, block := range blocks {@@ -254,7 +272,6 @@ func (a LLMAdapter) complete(ctx context.Context, messages []Message, specs []Toprotocol = llm.Responses}options := ModelCallOptionsFromContext(ctx)- route, _ := ModelRouteFromContext(ctx)request := llm.Request{Input: input, Tools: tools, Purpose: options.Purpose, MaxOutputTokens: options.MaxOutputTokens,ReasoningEffort: route.ReasoningEffort,@@ -316,6 +333,9 @@ func (a LLMAdapter) complete(ctx context.Context, messages []Message, specs []To}}output.Content = content.String()+ if protocol == llm.AnthropicMessages && !output.MaxTokens && options.Purpose != "compaction" && len(response.NativeContent) > 0 {+ output.ProviderReplay = &modeldata.ProviderReplay{EndpointURL: a.EndpointURL, Protocol: string(protocol), EndpointID: route.Provider, ModelID: route.Model, Content: response.NativeContent}+ }return output, nil}@@ -363,13 +383,13 @@ func transportUsage(response *llm.Response) *modeldata.ModelUsage {}usage := response.Usagereturn &modeldata.ModelUsage{InputTokens: usage.InputTokens, OutputTokens: usage.OutputTokens, TotalTokens: usage.TotalTokens,- CachedInputTokens: usage.CachedTokens, ReasoningTokens: usage.ReasoningTokens}+ CachedInputTokens: usage.CachedTokens, CacheCreationInputTokens: usage.CacheCreationTokens, ReasoningTokens: usage.ReasoningTokens}}func normalizeTransportError(err error, response *llm.Response) error {result := llm.NormalizeModelError("endpoint", "", err)result.OutputObserved = response != nil && len(response.Output) > 0- if response != nil && response.Status != "" && response.Status != "completed" {+ if response != nil && response.Status != "" && response.Status != "completed" && result.Code == llm.ModelErrorUnknown {result.Code = llm.ModelErrorResponseIncomplete}return resultdiff --git a/harness/agent/llm_stream_projection.go b/harness/agent/llm_stream_projection.goindex cb223f9..69eeb74 100644--- a/harness/agent/llm_stream_projection.go+++ b/harness/agent/llm_stream_projection.go@@ -9,7 +9,7 @@ import ("go-bot/thirdparty/llm")-// llmStreamProjection translates OpenAI-compatible SSE events into the block+// llmStreamProjection translates model-provider SSE events into the block// vocabulary used by DeepSeek's AssistantStreamAttempt. It emits only deltas// actually observed on the wire; a provider's completed item may close a// block, but it never retroactively invents token deltas.@@ -165,7 +165,7 @@ func (p *llmStreamProjection) finish(response *llm.Response) error {usage, err := nativeUsage(&modeldata.ModelUsage{InputTokens: response.Usage.InputTokens, OutputTokens: response.Usage.OutputTokens,TotalTokens: response.Usage.TotalTokens, CachedInputTokens: response.Usage.CachedTokens,- ReasoningTokens: response.Usage.ReasoningTokens,+ ReasoningTokens: response.Usage.ReasoningTokens, CacheCreationInputTokens: response.Usage.CacheCreationTokens,})if err != nil {return err@@ -215,6 +215,24 @@ func (p *llmStreamProjection) push(event llm.StreamEvent) error {}key := llmStreamKey{event.OutputIndex, event.ContentIndex}switch event.Type {+ case "anthropic.block.start":+ if event.Item != nil {+ switch event.Item.Type {+ case "message", "reasoning":+ if len(event.Item.Content) > 0 {+ kind := "text"+ if event.Item.Type == "reasoning" {+ kind = "reasoning"+ }+ _, err := p.begin(key, kind)+ return err+ }+ case "tool_call":+ _, err := p.begin(key, "tool-call")+ return err+ }+ }+ return nilcase "response.output_item.added":if event.Item != nil && event.Item.Type == "tool_call" {_, err := p.begin(llmStreamKey{event.OutputIndex, 0}, "tool-call")@@ -233,7 +251,7 @@ func (p *llmStreamProjection) push(event llm.StreamEvent) error {return err}return p.toolDelta(llmStreamKey{event.OutputIndex, 0}, event.Item, event.Delta)- case "response.output_item.done":+ case "response.output_item.done", "anthropic.block.stop":return p.endItem(event.OutputIndex, event.Item)case "response.completed", "response.incomplete", "response.failed", "response.cancelled", "completed":return p.finish(event.Response)diff --git a/harness/agent/native_contract.go b/harness/agent/native_contract.goindex 6088ea4..20395ff 100644--- a/harness/agent/native_contract.go+++ b/harness/agent/native_contract.go@@ -15,6 +15,8 @@ import (// Message is the model-facing projection of the durable v4 session surface.type Message struct {+ ProviderReplay *modeldata.ProviderReplay `json:"providerReplay,omitempty"`+ IsError bool `json:"isError,omitempty"`Role string `json:"role"`Content string `json:"content"`ContentBlocks []content.ContentBlock `json:"contentBlocks,omitempty"`@@ -82,6 +84,36 @@ type Tool interface {Execute(context.Context, json.RawMessage) (string, error)}+// SettledTool confirms provisional core state after the final tool result has+// been durably committed. Failure (including a failed commit) discards it.+// This is an optional built-in Go capability, not a plugin lifecycle callback.+type SettledTool interface {+ Tool+ SettleResult(callID string, success bool)+}++// RetainedOutputTool owns a specialized recoverable preview (for example+// grep/glob) or a Job status suffix. Generic retention must not save an+// already limited preview as though it were the original output.+type RetainedOutputTool interface {+ Tool+ RetainsOutput() bool+}++// PreparedOutputTool captures built-in output state before execution and+// applies it at PostExecute. No such callbacks are exposed by the plugin SDK.+type PreparedOutputTool interface {+ Tool+ PrepareOutput(json.RawMessage) func(modeldata.ToolResult) modeldata.ToolResult+}++// ConcurrencyTool supplies the upstream per-arguments overlap classifier.+// Only a successful true opts into overlap; failures remain exclusive.+type ConcurrencyTool interface {+ Tool+ IsConcurrencySafe(context.Context, json.RawMessage) (bool, error)+}+type ContentTool interface {ToolExecuteContent(context.Context, json.RawMessage) (string, []content.ContentBlock, error)@@ -93,6 +125,21 @@ type PresentedTool interface {ExecutePresented(context.Context, json.RawMessage) (string, json.RawMessage, error)}+// RichTool retains structured presentation metadata and durable image content+// together. The Agent still owns the checkpoint, error and result journal.+type RichTool interface {+ PresentedTool+ ExecuteRich(context.Context, json.RawMessage) (string, []content.ContentBlock, json.RawMessage, error)+}++// ResultTool preserves a protocol's normalized failure content as well as its+// successful content. An MCP isError response is a tool outcome, not a Go+// transport exception; its ordered text/images must survive both cases.+type ResultTool interface {+ Tool+ ExecuteResult(context.Context, json.RawMessage) (modeldata.ToolResult, error)+}+type Limits struct {MaxSteps intMaxToolCalls intdiff --git a/harness/agent/native_loop.go b/harness/agent/native_loop.goindex 2af35a5..02915e1 100644--- a/harness/agent/native_loop.go+++ b/harness/agent/native_loop.go@@ -22,6 +22,7 @@ import (// the shared model and tool implementations while writing DeepSeek's native// Session events directly, including inbox, attachments and compaction.type NativeLoop struct {+ *nativeTools// mu orders inbox admission against the first-step claim checkpoint. A// later message may be admitted while a model or tool call is running.mu sync.Mutex@@ -34,45 +35,50 @@ type NativeLoop struct {streamRevision uint64streamActive *nativeActiveAssistantAttempt// runMu permits only one driver to execute turns for this Agent.- runMu sync.Mutex- session *sessionformat.LiveSession- model Model- resolveTurnModel func(context.Context) (TurnModel, error)- provider string- modelID string- reasoningEffort string- systemPrompt string- tools map[string]Tool- toolSpecs []ToolSpec- toolSchemas map[string]*jsonschema.Schema- parallelSafe map[string]bool- maxParallelToolCalls int- maxSteps int- maxToolCalls int- maxModelCalls int- modelCalls int- repeatGuard repeatToolReminder- repeatReminders []map[string]any- contextWindowTokens int- reservedOutputTokens int- contextHeadroomTokens int- pressureMeter *nativePressureMeter- requestLogged bool- retryPolicy nativeRetryPolicy- filePath NativeFilePathResolver- goalClaim func(json.RawMessage, sessionformat.InboxState) (bool, error)- runtimeContext func() []RuntimeContextSection- preTool func(context.Context, string, json.RawMessage) error- preStep func(context.Context) (NativePreStepDecision, error)- promptForStep func() (string, error)- instructionsForStep func(context.Context, []string) (NativeInstructionSnapshot, error)- skillCatalogTool Tool- skillCatalogForStep func(context.Context) (NativeSkillCatalogSnapshot, error)- skillInvocationLoader func(context.Context, string) (string, bool, error)- timeContext *nativeTimeContext- instructionScanned int- instructionCalls map[string]string- instructionTouched []string+ runMu sync.Mutex+ session *sessionformat.LiveSession+ model Model+ resolveTurnModel func(context.Context) (TurnModel, error)+ resolveSelectedModel ModelSelectionResolver+ provider string+ modelID string+ reasoningEffort string+ configuredReasoningEffort string+ systemPrompt string+ baseTools []Tool+ toolSource ToolSource+ toolInvocationSource ToolInvocationSource+ toolSpecs []ToolSpec+ maxSteps int+ maxToolCalls int+ maxModelCalls int+ modelCalls int+ repeatGuard repeatToolReminder+ repeatReminders []map[string]any+ contextWindowTokens int+ reservedOutputTokens int+ contextHeadroomTokens int+ pressureMeter *nativePressureMeter+ requestLogged bool+ retryPolicy nativeRetryPolicy+ filePath NativeFilePathResolver+ goalClaim func(json.RawMessage, sessionformat.InboxState) (bool, error)+ runtimeContext func() []RuntimeContextSection+ runtimeContextSource func(context.Context, string) ([]RuntimeContextSection, error)+ systemContextSource func(context.Context, string) ([]RuntimeContextSection, error)+ promptAssembler PromptAssemblySource+ assembledContexts []RuntimeContextSection+ finishToolStep func(context.Context, string) error+ preStep func(context.Context) (NativePreStepDecision, error)+ promptForStep func() (string, error)+ instructionsForStep func(context.Context, []string) (NativeInstructionSnapshot, error)+ skillCatalogTool Tool+ skillCatalogForStep func(context.Context) (NativeSkillCatalogSnapshot, error)+ skillInvocationLoader func(context.Context, string) (string, bool, error)+ timeContext *nativeTimeContext+ instructionScanned int+ instructionCalls map[string]string+ instructionTouched []string}// NativeInstructionSnapshot is the current, bounded workspace-instruction@@ -104,6 +110,17 @@ func (a *NativeLoop) SetTurnModelResolver(resolve func(context.Context) (TurnModa.resolveTurnModel = resolve}+// SessionHeader and DurableSessionEventPage expose detached, read-only Host+// capabilities. The existing Go Session remains the journal and lifecycle owner.+func (a *NativeLoop) SessionHeader() sessionformat.Header { return a.session.Header() }++// SessionRecord lends the existing Go owner to Host capability adapters; it+// does not construct another session or transfer writer ownership.+func (a *NativeLoop) SessionRecord() *sessionformat.LiveSession { return a.session }+func (a *NativeLoop) DurableSessionEventPage(after *uint64, limit int) []sessionformat.Event {+ return a.session.DurableEventPage(after, limit)+}+// pinTurnModel is called with runMu held, before claiming durable work.func (a *NativeLoop) pinTurnModel(ctx context.Context) (context.Context, error) {if a.resolveTurnModel == nil {@@ -121,6 +138,19 @@ func (a *NativeLoop) pinTurnModel(ctx context.Context) (context.Context, error)a.requestLogged = false}a.model, a.provider, a.modelID = model.Model, model.Route.Provider, model.Route.Model+ if a.resolveSelectedModel != nil {+ // The web/mobile model setting remains an explicit Host-owned input+ // for these manually managed turns. Record that input before step+ // preparation, so synchronous SDK reads agree with the real request.+ effort := model.Route.ReasoningEffort+ if effort == "" {+ effort = a.configuredReasoningEffort+ }+ a.reasoningEffort = effort+ if err := a.session.SelectModel(sessionformat.ModelSelection{Provider: model.Route.Provider, Model: model.Route.Model, ReasoningEffort: effort}); err != nil {+ return ctx, err+ }+ }ctx = context.WithValue(ctx, turnModelKey{}, model)return WithModelRoute(ctx, model.Route), nil}@@ -171,6 +201,7 @@ func (a *NativeLoop) SetParallelToolLimit(limit int) error {// and model. The effective value is part of the durable request header.func (a *NativeLoop) SetReasoningEffort(effort string) {a.reasoningEffort = effort+ a.configuredReasoningEffort = effort}// SetContextPressure enables DeepSeek-style pre-request pressure checks for a@@ -217,11 +248,6 @@ func (a *NativeLoop) SetSystemPromptProvider(provider func() (string, error)) {a.promptForStep = provider}-// SetToolApproval installs a pre-dispatch policy for model tool calls.-func (a *NativeLoop) SetToolApproval(policy func(context.Context, string, json.RawMessage) error) {- a.preTool = policy-}-func (a *NativeLoop) completeModel(ctx context.Context, messages []Message) (modeldata.AssistantMessage, error) {if a.maxModelCalls > 0 && a.modelCalls >= a.maxModelCalls {return modeldata.AssistantMessage{}, ErrModelCallBudget@@ -306,26 +332,13 @@ func NewNativeLoop(s *sessionformat.LiveSession, model Model, provider, modelID,if err != nil {return nil, err}- loop := &NativeLoop{session: s, model: model, provider: provider, modelID: modelID, systemPrompt: systemPrompt,- tools: make(map[string]Tool), toolSchemas: make(map[string]*jsonschema.Schema), parallelSafe: make(map[string]bool),- maxParallelToolCalls: 4, maxSteps: maxSteps, maxToolCalls: maxToolCalls, retryPolicy: defaultNativeRetryPolicy(), repeatGuard: repeatGuard}- for _, tool := range tools {- if tool == nil {- return nil, errors.New("native Agent tool is nil")- }- spec := tool.Spec()- if spec.Name == "" || loop.tools[spec.Name] != nil || !json.Valid(spec.Parameters) {- return nil, fmt.Errorf("invalid native Agent tool %q", spec.Name)- }- schema, err := compileToolParameters(spec.Parameters)- if err != nil {- return nil, fmt.Errorf("compile native Agent tool %q parameters: %w", spec.Name, err)- }- loop.tools[spec.Name] = tool- loop.toolSpecs = append(loop.toolSpecs, spec)- loop.toolSchemas[spec.Name] = schema- loop.parallelSafe[spec.Name] = spec.ParallelSafe+ loop := &NativeLoop{nativeTools: &nativeTools{header: s.Header, tools: make(map[string]Tool), toolSchemas: make(map[string]*jsonschema.Schema), parallelSafe: make(map[string]bool), maxParallelToolCalls: 4}, session: s, model: model, provider: provider, modelID: modelID, systemPrompt: systemPrompt,+ maxSteps: maxSteps, maxToolCalls: maxToolCalls, retryPolicy: defaultNativeRetryPolicy(), repeatGuard: repeatGuard}+ loop.nativeTools.postResult = loop.observeRepeatedToolResult+ if err := loop.installTools(tools); err != nil {+ return nil, err}+ loop.baseTools = append([]Tool(nil), tools...)return loop, nil}@@ -533,6 +546,7 @@ func (a *NativeLoop) runClaimed(ctx context.Context, releaseAdmission func()) (amaxTokensSeen := falseblocked := falsedefer func() {+ err = errors.Join(err, a.releaseToolStep(ctx))if !claimLocked {a.mu.Lock()claimLocked = true@@ -567,7 +581,9 @@ func (a *NativeLoop) runClaimed(ctx context.Context, releaseAdmission func()) (aerr = errors.Join(err, closeErr, a.session.Flush(settle))}()toolCount := 0+ turnContext := ctxfor step := 1; step <= a.maxSteps; step++ {+ ctx = turnContextif err = ctx.Err(); err != nil {return "", err}@@ -587,6 +603,10 @@ func (a *NativeLoop) runClaimed(ctx context.Context, releaseAdmission func()) (areturn "", err}}+ ctx, err = a.captureStepModel(ctx)+ if err != nil {+ return "", err+ }if a.preStep != nil {var decision NativePreStepDecisionif decision, err = a.preStep(ctx); err != nil {@@ -600,11 +620,17 @@ func (a *NativeLoop) runClaimed(ctx context.Context, releaseAdmission func()) (areturn "", errors.New("invalid native pre-step decision")}}+ if err = a.refreshTools(ctx); err != nil {+ return "", err+ }+ if err = a.refreshToolInvocationSource(ctx); err != nil {+ return "", err+ }if _, err = a.append("step/start", map[string]any{"turn": turn, "step": step}, nil, nil); err != nil {return "", err}stepOpen = true- if err = a.ensureSystem(turn, step); err != nil {+ if err = a.ensureSystem(ctx, turn, step); err != nil {return "", err}if err = a.ensureSkillCatalog(ctx); err != nil {@@ -628,7 +654,7 @@ func (a *NativeLoop) runClaimed(ctx context.Context, releaseAdmission func()) (aif err = a.ensureInstructions(ctx); err != nil {return "", err}- if err = a.ensureRuntimeContext(); err != nil {+ if err = a.ensureRuntimeContext(ctx); err != nil {return "", err}if err = a.ensureTimeContext(ctx, turn, step); err != nil {@@ -692,6 +718,7 @@ func (a *NativeLoop) runClaimed(ctx context.Context, releaseAdmission func()) (areturn latestToolQuestion(a.session)}))budgetExceeded, concluded, toolErr := a.executeNativeStepTools(toolCtx, turn, step, response.ToolCalls, &toolCount)+ toolErr = errors.Join(toolErr, a.releaseToolStep(ctx))if toolErr != nil {a.repeatReminders = nilreturn "", toolErr@@ -778,7 +805,7 @@ func (a *NativeLoop) append(eventType string, data any, surfaceOp json.RawMessagreturn a.session.Append(sessionformat.EventInput{Type: eventType, Data: encoded, SurfaceOp: surfaceOp, SourceEventSeqs: sources})}-func (a *NativeLoop) ensureSystem(turn uint64, step int) error {+func (a *NativeLoop) ensureSystem(ctx context.Context, turn uint64, step int) error {prompt := a.systemPromptif a.promptForStep != nil {var err error@@ -787,6 +814,22 @@ func (a *NativeLoop) ensureSystem(turn uint64, step int) error {return err}}+ if a.systemContextSource != nil {+ sections, err := a.systemContextSource(ctx, a.session.Header().ID)+ if err != nil {+ return err+ }+ for _, section := range sections {+ if section.Text != "" {+ prompt += "\n\n" + section.Text+ }+ }+ }+ var assemblyErr error+ prompt, assemblyErr = a.assemblePrompt(ctx, prompt)+ if assemblyErr != nil {+ return assemblyErr+ }surface, err := a.session.Surface()if err != nil {return err@@ -920,6 +963,9 @@ func (a *NativeLoop) logAssistant(turn uint64, step int, response modeldata.Assi}}message := map[string]any{"id": uuid.NewString(), "role": "assistant", "source": map[string]any{"kind": "model", "provider": a.provider, "model": a.modelID}, "content": content}+ if response.ProviderReplay != nil && !response.Interrupted && !response.MaxTokens {+ message["providerReplay"] = response.ProviderReplay+ }stream := response.StreamRecordsstreamed := stream != nilstamp := time.Now().UnixMilli()@@ -982,16 +1028,15 @@ func nativeUsage(usage *modeldata.ModelUsage) (map[string]any, error) {return result, nil}-func (a *NativeLoop) executeNativeTool(ctx context.Context, turn, step uint64, call modeldata.ToolRequest) (result modeldata.ToolResult) {+func (a *nativeTools) executeNativeToolDirect(ctx context.Context, turn, step uint64, call modeldata.ToolRequest, tool Tool, schema *jsonschema.Schema) (result modeldata.ToolResult) {result = modeldata.ToolResult{ID: call.ID, Name: call.Name}defer func() {if recovered := recover(); recovered != nil {result.IsError, result.Code, result.Content = true, modeldata.ToolOutcomeUnknown, fmt.Sprintf("Tool panicked; its outcome is unknown: %v", recovered)}}()- tool := a.tools[call.Name]if tool == nil {- result.IsError, result.Code, result.Content = true, "TOOL_NOT_FOUND", "Unknown tool: "+call.Name+ result.IsError, result.Code, result.ErrorName, result.Content = true, "UNKNOWN_TOOL", "ToolNotFoundError", fmt.Sprintf("Error: unknown tool %q", call.Name)return result}presented, hasPresentation := tool.(PresentedTool)@@ -1007,7 +1052,7 @@ func (a *NativeLoop) executeNativeTool(ctx context.Context, turn, step uint64, c}return result}- if schema := a.toolSchemas[call.Name]; schema == nil {+ if schema == nil {result.IsError, result.Code, result.Content = true, "TOOL_ERROR", "Tool parameter schema was not compiled."return result} else if err := validateToolParameters(schema, arguments); err != nil {@@ -1025,6 +1070,11 @@ func (a *NativeLoop) executeNativeTool(ctx context.Context, turn, step uint64, c}return result}+ if ctx.Err() != nil {+ result.IsError, result.Code, result.ErrorName, result.Content = true, "ABORTED_BEFORE_DISPATCH", "AbortError", "tool call aborted before dispatch"+ return result+ }+ markToolBodyStarted(ctx)control := &toolControl{}executionCtx := withToolPosition(ctx, turn, step)executionCtx = withToolCallID(executionCtx, call.ID)@@ -1032,19 +1082,30 @@ func (a *NativeLoop) executeNativeTool(ctx context.Context, turn, step uint64, ccancel := func() {}var toolTimeoutCause errortimeout := tool.Spec().Timeout- if timeout > 0 {- toolTimeoutCause = errors.New("Harness tool call deadline")- executionCtx, cancel = context.WithTimeoutCause(executionCtx, timeout, toolTimeoutCause)- }- defer cancel()var content stringvar blocks []agentcontent.ContentBlock+ canonicalResult := falsevar err error- if a.preTool != nil {- err = a.preTool(executionCtx, call.Name, arguments)++ // A tool request budget is not an ordinary user-approval timeout.+ // Start it only after the pre-dispatch approval has settled.+ if err == nil && timeout > 0 {+ toolTimeoutCause = errors.New("Harness tool call deadline")+ executionCtx, cancel = context.WithTimeoutCause(executionCtx, timeout, toolTimeoutCause)}+ defer cancel()if err != nil {// Process policy denial as a normal tool failure.+ } else if normalized, ok := tool.(ResultTool); ok {+ var body modeldata.ToolResult+ body, err = normalized.ExecuteResult(executionCtx, arguments)+ content, blocks, result.Meta = body.Content, body.ContentBlocks, body.Meta+ result.IsError, result.Code, result.ErrorName, result.ErrorReason = body.IsError, body.Code, body.ErrorName, body.ErrorReason+ result.AdditionalContexts = body.AdditionalContexts+ result.ConcludeTurn = body.ConcludeTurn+ canonicalResult = true+ } else if rich, ok := tool.(RichTool); ok {+ content, blocks, result.Meta, err = rich.ExecuteRich(executionCtx, arguments)} else if hasPresentation {content, result.Meta, err = presented.ExecutePresented(executionCtx, arguments)} else if structured, ok := tool.(ContentTool); ok {@@ -1088,10 +1149,9 @@ func (a *NativeLoop) executeNativeTool(ctx context.Context, turn, step uint64, c}result.Content = contentresult.ContentBlocks = agentcontent.CloneContentBlocks(blocks)- result.ConcludeTurn = control.concludeTurn+ result.ConcludeTurn = !result.IsError && (result.ConcludeTurn || control.concludeTurn)if hasPresentation {- result = boundedToolResult(result)- if result.IsError {+ if result.IsError && !canonicalResult {result.Meta = nil}}@@ -1138,6 +1198,9 @@ func (a *NativeLoop) logToolResult(turn uint64, step int, callSeq uint64, result}}data["error"] = map[string]any{"name": name, "code": result.Code}+ if result.ErrorReason != nil {+ data["error"].(map[string]any)["reason"] = *result.ErrorReason+ }}_, err := a.append("tool/result", data, json.RawMessage(`"append"`), []uint64{callSeq})return err@@ -1189,9 +1252,11 @@ func nativeModelMessages(s *sessionformat.LiveSession, resolveFile NativeFilePatmessages := make([]Message, 0, len(surface.Messages))for _, raw := range surface.Messages {var value struct {- Role string `json:"role"`- ToolCallID string `json:"toolCallId"`- Content []struct {+ ProviderReplay *modeldata.ProviderReplay `json:"providerReplay"`+ IsError bool `json:"isError"`+ Role string `json:"role"`+ ToolCallID string `json:"toolCallId"`+ Content []struct {Type string `json:"type"`Text string `json:"text"`ID string `json:"id"`@@ -1212,7 +1277,7 @@ func nativeModelMessages(s *sessionformat.LiveSession, resolveFile NativeFilePatif err := json.Unmarshal(raw, &value); err != nil {return nil, err}- message := Message{Role: value.Role, ToolCallID: value.ToolCallID}+ message := Message{Role: value.Role, ToolCallID: value.ToolCallID, IsError: value.IsError, ProviderReplay: value.ProviderReplay}var textParts []stringvar orderedBlocks []agentcontent.ContentBlockvar assistantOrder []modeldata.AssistantOutputBlockdiff --git a/harness/agent/native_model_selection.go b/harness/agent/native_model_selection.gonew file mode 100644index 0000000..58a90af--- /dev/null+++ b/harness/agent/native_model_selection.go@@ -0,0 +1,46 @@+package agent++import (+ "context"+ "errors"+)++type ModelSelectionResolver func(context.Context, ModelRoute) (Model, error)++func (a *NativeLoop) SetModelSelectionResolver(resolve ModelSelectionResolver) {+ a.resolveSelectedModel = resolve+}++func (a *NativeLoop) captureStepModel(ctx context.Context) (context.Context, error) {+ if a.resolveSelectedModel == nil {+ return ctx, nil+ }+ state, err := a.session.ModelSelection()+ if err != nil {+ return ctx, err+ }+ selected := state.Current()+ if selected == nil {+ return WithModelRoute(ctx, ModelRoute{Provider: a.provider, Model: a.modelID, ReasoningEffort: a.reasoningEffort}), nil+ }++ route := ModelRoute{Provider: selected.Provider, Model: selected.Model, ReasoningEffort: selected.ReasoningEffort}+ model := a.model+ changed := a.provider != route.Provider || a.modelID != route.Model || a.reasoningEffort != route.ReasoningEffort+ if a.resolveSelectedModel != nil && changed {+ model, err = a.resolveSelectedModel(ctx, route)+ if err != nil {+ return ctx, err+ }+ if model == nil {+ return ctx, errors.New("selected model is unavailable")+ }+ }+ if changed {+ a.requestLogged = false+ }+ a.model, a.provider, a.modelID, a.reasoningEffort = model, route.Provider, route.Model, route.ReasoningEffort+ // The same captured route reaches tools, prompt assembly, retries and the+ // real adapter. A later select affects only the next preparation boundary.+ return WithModelRoute(WithTurnModel(ctx, TurnModel{Model: model, Route: route}), route), nil+}diff --git a/harness/agent/native_model_selection_test.go b/harness/agent/native_model_selection_test.gonew file mode 100644index 0000000..da023ea--- /dev/null+++ b/harness/agent/native_model_selection_test.go@@ -0,0 +1,46 @@+package agent++import (+ "context"+ "testing"++ "go-bot/harness/session"+ "go-bot/internal/modeldata"+)++type modelOptionsProbe struct {+ routes []ModelRoute+ caps []int+}++func (m *modelOptionsProbe) Complete(ctx context.Context, _ []Message, _ []ToolSpec) (modeldata.AssistantMessage, error) {+ route, _ := ModelRouteFromContext(ctx)+ m.routes = append(m.routes, route)+ m.caps = append(m.caps, ModelCallOptionsFromContext(ctx).MaxOutputTokens)+ return modeldata.AssistantMessage{Content: "done"}, nil+}++func TestRecordedModelSelectionUsesNativeGoResolver(t *testing.T) {+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, CreatedAt: 1, ID: "selection", CWD: "/tmp"}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ defer live.Close()+ probe := &modelOptionsProbe{}+ loop, err := NewNativeLoop(live, probe, "p", "initial", "prompt", nil, 2, 2)+ if err != nil {+ t.Fatal(err)+ }+ loop.SetModelSelectionResolver(func(_ context.Context, route ModelRoute) (Model, error) { return probe, nil })+ for _, name := range []string{"first", "second"} {+ if err := live.SelectModel(sessionformat.ModelSelection{Provider: "p", Model: name}); err != nil {+ t.Fatal(err)+ }+ if _, err := loop.RunTextTurn(t.Context(), "hello"); err != nil {+ t.Fatal(err)+ }+ }+ if len(probe.routes) != 2 || probe.routes[0].Model != "first" || probe.routes[1].Model != "second" {+ t.Fatal(probe.routes)+ }+}diff --git a/harness/agent/native_prompt_assembly.go b/harness/agent/native_prompt_assembly.gonew file mode 100644index 0000000..7d080fe--- /dev/null+++ b/harness/agent/native_prompt_assembly.go@@ -0,0 +1,84 @@+package agent++import (+ "context"+ "errors"+ "fmt"+ "slices"+ "time"++ "github.com/santhosh-tekuri/jsonschema/v6"+)++type PromptAssemblyInput struct {+ SessionID string `json:"sessionId"`+ CWD string `json:"cwd"`+ SystemPrompt string `json:"systemPrompt"`+ Tools []ToolSpec `json:"tools"`+ ModelSelection ModelRoute `json:"modelSelection"`+ SandboxPolicy *ExecutionSandboxPolicy `json:"sandboxPolicy,omitempty"`+}+type PromptAssembly struct {+ SystemPrompt string `json:"systemPrompt"`+ Contexts []RuntimeContextSection `json:"contexts"`+ Tools []ToolSpec `json:"tools"`+}+type PromptAssemblySource func(context.Context, PromptAssemblyInput) (PromptAssembly, error)++func (a *NativeLoop) SetPromptAssembler(source PromptAssemblySource) { a.promptAssembler = source }++func (a *NativeLoop) SetToolStepFinalizer(finalize func(context.Context, string) error) {+ a.finishToolStep = finalize+}+func (a *NativeLoop) releaseToolStep(ctx context.Context) error {+ if a.finishToolStep == nil {+ return nil+ }+ cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)+ defer cancel()+ return a.finishToolStep(cleanup, a.session.Header().ID)+}++// A prompt provider may declare only tools backed by this step's real tool+// table. The original handler, validation, approval and execution metadata stay+// pinned. Assemble everything before replacing the visible table.+func (a *NativeLoop) assemblePrompt(ctx context.Context, prompt string) (string, error) {+ if a.promptAssembler == nil {+ return prompt, nil+ }+ input := PromptAssemblyInput{SessionID: a.session.Header().ID, CWD: a.session.Header().CWD, SystemPrompt: prompt, Tools: slices.Clone(a.toolSpecs), ModelSelection: ModelRoute{Provider: a.provider, Model: a.modelID, ReasoningEffort: a.reasoningEffort}}+ input.SandboxPolicy = a.executionSandboxPolicy()+ assembly, err := a.promptAssembler(ctx, input)+ if err != nil {+ return "", err+ }+ if len(assembly.SystemPrompt) > 1<<20 || len(assembly.Contexts) > 1024 {+ return "", errors.New("plugin prompt assembly exceeds supported limits")+ }+ tools := map[string]Tool{}+ schemas := map[string]*jsonschema.Schema{}+ safe := map[string]bool{}+ for i, spec := range assembly.Tools {+ tool := a.tools[spec.Name]+ if tool == nil || tools[spec.Name] != nil {+ return "", fmt.Errorf("prompt assembly names unknown or duplicate tool %q", spec.Name)+ }+ schema, err := compileToolParameters(spec.Parameters)+ if err != nil {+ return "", fmt.Errorf("prompt assembly tool %q: %w", spec.Name, err)+ }+ tools[spec.Name], schemas[spec.Name], safe[spec.Name] = tool, schema, a.parallelSafe[spec.Name]+ assembly.Tools[i].ParallelSafe = safe[spec.Name]+ assembly.Tools[i].Timeout = tool.Spec().Timeout+ }+ size := 0+ for _, section := range assembly.Contexts {+ size += len(section.Name) + len(section.Text)+ }+ if size > 256<<10 {+ return "", errors.New("plugin prompt context exceeds 256 KiB")+ }+ a.tools, a.toolSchemas, a.parallelSafe, a.toolSpecs = tools, schemas, safe, assembly.Tools+ a.assembledContexts = slices.Clone(assembly.Contexts)+ return assembly.SystemPrompt, nil+}diff --git a/harness/agent/native_prompt_assembly_test.go b/harness/agent/native_prompt_assembly_test.gonew file mode 100644index 0000000..0c77b61--- /dev/null+++ b/harness/agent/native_prompt_assembly_test.go@@ -0,0 +1,71 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "testing"++ sessionformat "go-bot/harness/session"+)++func TestPromptAssemblyPinsRealHandlersAndCanRestoreDeclarationsNextStep(t *testing.T) {+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, CreatedAt: 1, ID: "assembly", CWD: "/tmp"}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ probe := &dynamicProbe{label: "real"}+ loop, err := NewNativeLoop(live, &nativeAnswerModel{}, "provider", "model", "base", []Tool{probe}, 3, 3)+ if err != nil {+ t.Fatal(err)+ }+ hidden := true+ loop.SetPromptAssembler(func(_ context.Context, input PromptAssemblyInput) (PromptAssembly, error) {+ if input.SessionID != "assembly" || input.CWD != "/tmp" || input.SystemPrompt != "base" || len(input.Tools) != 1 {+ t.Errorf("incomplete input %+v", input)+ }+ tools := input.Tools+ if hidden {+ tools = []ToolSpec{}+ }+ return PromptAssembly{SystemPrompt: "assembled policy", Contexts: []RuntimeContextSection{{Name: "state", Text: "registered context"}}, Tools: tools}, nil+ })+ if err = loop.refreshTools(t.Context()); err != nil {+ t.Fatal(err)+ }+ if err = loop.ensureSystem(t.Context(), 1, 1); err != nil {+ t.Fatal(err)+ }+ if len(loop.tools) != 0 {+ t.Fatal("hidden declarations were still dispatchable")+ }+ if err = loop.ensureRuntimeContext(t.Context()); err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(live.Events()[0].Data), "assembled policy") || !strings.Contains(string(live.Events()[1].Data), "registered context") {+ t.Fatal("assembled prompt/context were not committed through existing logs")+ }+ hidden = false+ if err = loop.refreshTools(t.Context()); err != nil {+ t.Fatal(err)+ }+ if err = loop.ensureSystem(t.Context(), 1, 2); err != nil {+ t.Fatal(err)+ }+ if loop.tools[probe.Spec().Name] != probe {+ t.Fatal("assembly lost original Go handler")+ }+ loop.SetPromptAssembler(func(context.Context, PromptAssemblyInput) (PromptAssembly, error) {+ return PromptAssembly{Tools: []ToolSpec{{Name: "invented", Parameters: json.RawMessage(`{"type":"object"}`)}}}, nil+ })+ if err = loop.ensureSystem(t.Context(), 1, 3); err == nil || loop.tools[probe.Spec().Name] != probe {+ t.Fatalf("unknown tool changed pinned table: %v", err)+ }+ loop.SetPromptAssembler(func(context.Context, PromptAssemblyInput) (PromptAssembly, error) {+ return PromptAssembly{}, errors.New("provider unavailable")+ })+ if err = loop.ensureSystem(t.Context(), 1, 3); err == nil {+ t.Fatal("prompt failure was hidden")+ }+}diff --git a/harness/agent/native_result_tool_test.go b/harness/agent/native_result_tool_test.gonew file mode 100644index 0000000..7fe10c4--- /dev/null+++ b/harness/agent/native_result_tool_test.go@@ -0,0 +1,70 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "testing"+ "time"++ "go-bot/harness/content"+ "go-bot/harness/session"+ "go-bot/internal/modeldata"+)++type normalizedProbe struct{ failure bool }++func (normalizedProbe) Spec() ToolSpec {+ return ToolSpec{Name: "protocol_result", Parameters: json.RawMessage(`{"type":"object"}`), Timeout: 100 * time.Millisecond}+}+func (normalizedProbe) Validate(json.RawMessage) error { return nil }+func (normalizedProbe) Execute(context.Context, json.RawMessage) (string, error) {+ return "", errors.New("normalized dispatch was bypassed")+}+func (normalizedProbe) ExecutePresented(context.Context, json.RawMessage) (string, json.RawMessage, error) {+ return "", nil, errors.New("normalized dispatch was bypassed")+}+func (p normalizedProbe) ExecuteResult(context.Context, json.RawMessage) (modeldata.ToolResult, error) {+ return modeldata.ToolResult{IsError: p.failure, Code: "PROTOCOL_ERROR", ErrorName: "ProtocolError", ContentBlocks: []content.ContentBlock{{Type: "text", Text: "before"}, {Type: "image", ImageRefID: "sha256:0000000000000000000000000000000000000000000000000000000000000000", MIMEType: "image/png", Width: 2, Height: 2, Bytes: 10}, {Type: "text", Text: "after"}}, Meta: json.RawMessage(`{"protocol":"retained"}`)}, nil+}++func TestNormalizedProtocolFailureKeepsItsOrderedContentAndMetadata(t *testing.T) {+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "protocol", CreatedAt: 1}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ loop, err := NewNativeLoop(live, &nativeAnswerModel{}, "p", "m", "prompt", []Tool{normalizedProbe{failure: true}}, 2, 2)+ if err != nil {+ t.Fatal(err)+ }+ result := loop.executeNativeTool(t.Context(), 1, 1, modeldata.ToolRequest{ID: "call", Name: "protocol_result", Arguments: `{}`})+ if !result.IsError || len(result.ContentBlocks) != 3 || result.ContentBlocks[1].Type != "image" || len(result.Meta) == 0 {+ t.Fatalf("normalized failure=%+v", result)+ }+}++func TestToolRequestTimeoutStartsAfterOrdinaryApproval(t *testing.T) {+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "approval-budget", CreatedAt: 1}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ loop, err := NewNativeLoop(live, &nativeAnswerModel{}, "p", "m", "prompt", []Tool{normalizedProbe{}}, 2, 2)+ if err != nil {+ t.Fatal(err)+ }+ loop.SetToolPreExecutePolicy(func(context.Context, ToolExecution) (PreToolDecision, error) {+ return PreToolDecision{Kind: "ask"}, nil+ })+ loop.SetToolPolicyApprover(func(ctx context.Context, _ ToolExecution, _ ToolPolicyAsk) error {+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(200 * time.Millisecond):+ return nil+ }+ })+ result := loop.executeNativeTool(t.Context(), 1, 1, modeldata.ToolRequest{ID: "call", Name: "protocol_result", Arguments: `{}`})+ if result.IsError {+ t.Fatalf("tool deadline incorrectly bounded user approval: %+v", result)+ }+}diff --git a/harness/agent/native_runtime_context.go b/harness/agent/native_runtime_context.goindex 79da3ed..206ccc0 100644--- a/harness/agent/native_runtime_context.go+++ b/harness/agent/native_runtime_context.go@@ -1,6 +1,7 @@package agentimport (+ "context""encoding/json""slices""strings"@@ -13,22 +14,42 @@ type RuntimeContextSection struct {Text string `json:"text"`}+// SetSystemContextSource supplies dynamic system sections at each model step.+// ensureSystem commits their assembled text through the existing v4+// system/message replacement mechanism, including withdrawal and compaction.+func (a *NativeLoop) SetSystemContextSource(source func(context.Context, string) ([]RuntimeContextSection, error)) {+ a.systemContextSource = source+}+func (a *NativeLoop) SetRuntimeContext(provider func() []RuntimeContextSection) {a.runtimeContext = provider}-func (a *NativeLoop) ensureRuntimeContext() error {- if a.runtimeContext == nil {+func (a *NativeLoop) SetRuntimeContextSource(source func(context.Context, string) ([]RuntimeContextSection, error)) {+ a.runtimeContextSource = source+}++func (a *NativeLoop) ensureRuntimeContext(ctx context.Context) error {+ if a.runtimeContext == nil && a.runtimeContextSource == nil && a.promptAssembler == nil {return nil}- sections := a.runtimeContext()- if len(sections) == 0 {- return nil+ var sections []RuntimeContextSection+ sections = append(sections, a.assembledContexts...)+ if a.runtimeContext != nil {+ sections = append(sections, a.runtimeContext()...)+ }+ if a.runtimeContextSource != nil {+ extra, err := a.runtimeContextSource(ctx, a.session.Header().ID)+ if err != nil {+ return err+ }+ sections = append(sections, extra...)}surface, err := a.session.Surface()if err != nil {return err}+ previous := falsefor _, messageData := range slices.Backward(surface.Messages) {// Use retained model messages so a compacted snapshot is reannounced.var message struct {@@ -44,8 +65,12 @@ func (a *NativeLoop) ensureRuntimeContext() error {if slices.Equal(message.Source.Sections, sections) {return nil}+ previous = truebreak}+ if len(sections) == 0 && !previous {+ return nil+ }paragraphs := []string{"Current runtime context. This snapshot supersedes earlier runtime-context snapshots."}for _, section := range sections {paragraphs = append(paragraphs, section.Text)diff --git a/harness/agent/native_runtime_context_test.go b/harness/agent/native_runtime_context_test.gonew file mode 100644index 0000000..ad51383--- /dev/null+++ b/harness/agent/native_runtime_context_test.go@@ -0,0 +1,56 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "testing"++ sessionformat "go-bot/harness/session"+)++func TestWithdrawnRuntimeContextPublishesAnEmptyReplacement(t *testing.T) {+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "context-source", CreatedAt: 1}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ loop := &NativeLoop{session: live}+ sections := []RuntimeContextSection{{Name: "plugin:calendar", Text: "Connected calendar: work"}}+ loop.SetRuntimeContextSource(func(_ context.Context, id string) ([]RuntimeContextSection, error) {+ if id != "context-source" {+ t.Fatalf("wrong scope: %s", id)+ }+ return sections, nil+ })+ if err := loop.ensureRuntimeContext(t.Context()); err != nil {+ t.Fatal(err)+ }+ if err := loop.ensureRuntimeContext(t.Context()); err != nil {+ t.Fatal(err)+ }+ if len(live.Events()) != 1 {+ t.Fatal("Unchanged context should not append a duplicate")+ }+ sections = nil+ if err := loop.ensureRuntimeContext(t.Context()); err != nil {+ t.Fatal(err)+ }+ if len(live.Events()) != 2 {+ t.Fatal("Withdrawal did not supersede the previous snapshot")+ }+ var message struct {+ Source struct{ Sections []RuntimeContextSection }+ }+ if err := json.Unmarshal(live.Events()[1].Data, &message); err != nil {+ t.Fatal(err)+ }+ if len(message.Source.Sections) != 0 {+ t.Fatal("Withdrawn section survived")+ }+ loop.SetRuntimeContextSource(func(context.Context, string) ([]RuntimeContextSection, error) {+ return nil, errors.New("provider unavailable")+ })+ if err := loop.ensureRuntimeContext(t.Context()); err == nil {+ t.Fatal("Provider failure was hidden")+ }+}diff --git a/harness/agent/native_tool_pipeline.go b/harness/agent/native_tool_pipeline.gonew file mode 100644index 0000000..a9797b5--- /dev/null+++ b/harness/agent/native_tool_pipeline.go@@ -0,0 +1,210 @@+package agent++import (+ "context"+ "encoding/json"+ "fmt"+ "go-bot/harness/interaction"+ "go-bot/harness/session"+ "go-bot/internal/modeldata"+)++type ToolExecution struct {+ Unavailable bool `json:"unavailable,omitempty"`+ SessionID string `json:"sessionId"`+ CWD string `json:"cwd"`+ CallID string `json:"callId"`+ Name string `json:"name"`+ Arguments json.RawMessage `json:"arguments"`+ Turn uint64 `json:"turn"`+ Step uint64 `json:"step"`+ SandboxPolicy *ExecutionSandboxPolicy `json:"sandboxPolicy,omitempty"`+}++type ToolPolicyAsk struct {+ Reason string `json:"reason,omitempty"`+ DisplayReason map[string]string `json:"displayReason,omitempty"`+}++type NativePreToolPolicy func(context.Context, ToolExecution) (PreToolDecision, error)+type ToolInvocationFactory func(context.Context, ToolExecution, func(context.Context) modeldata.ToolResult, func(context.Context, ToolPolicyAsk) error) (*ToolInvocation, error)+type ToolInvocationSource func(context.Context, string) (ToolInvocationFactory, error)++func (a *NativeLoop) SetToolQuestions(questions *interaction.NativeQuestions) {+ a.questions = questions+}++func (a *NativeLoop) SetToolInvocationSource(source ToolInvocationSource) {+ a.toolInvocationSource = source+}+func (a *NativeLoop) SetToolPreExecutePolicy(policy NativePreToolPolicy) { a.preExecutePolicy = policy }+func (a *NativeLoop) SetToolPolicyApprover(approve func(context.Context, ToolExecution, ToolPolicyAsk) error) {+ a.toolPolicyApprover = approve+}+func (a *NativeLoop) refreshToolInvocationSource(ctx context.Context) error {+ if a.toolInvocationSource == nil {+ a.nativeTools.mu.Lock()+ a.toolInvocationFactory = nil+ a.nativeTools.mu.Unlock()+ return nil+ }+ factory, err := a.toolInvocationSource(ctx, a.session.Header().ID)+ if err != nil {+ return fmt.Errorf("resolve tool execution policy: %w", err)+ }+ a.nativeTools.mu.Lock()+ a.toolInvocationFactory = factory+ a.nativeTools.mu.Unlock()+ return nil+}++type nativePreparedTool struct {+ call modeldata.ToolRequest+ invocation *ToolInvocation+ preparation ToolPreparation+ fallback *modeldata.ToolResult+ canonical *ToolPipelineResult+ settler SettledTool+ settled bool+ postResult func(modeldata.ToolRequest, *modeldata.ToolResult)+ output func(modeldata.ToolResult) modeldata.ToolResult+}++func (a *nativeTools) prepareNativeTool(ctx context.Context, turn, step uint64, call modeldata.ToolRequest) *nativePreparedTool {+ prepared := &nativePreparedTool{call: call, postResult: a.postResult}+ args := json.RawMessage(call.Arguments)+ if len(args) == 0 {+ args = json.RawMessage(`{}`)+ }+ // Match upstream argument parsing: malformed JSON is a string that policy+ // can inspect; the tool's original argument diagnostic remains its own job.+ if !json.Valid(args) {+ args, _ = json.Marshal(call.Arguments)+ }+ header := a.header()+ tool, schema, resolveErr := a.lookupTool(ctx, call.Name)+ if resolveErr != nil {+ result := nativePolicyFailure(call, resolveErr)+ prepared.fallback = &result+ return prepared+ }+ prepared.settler, _ = tool.(SettledTool)+ prepared.output = prepareToolOutput(ctx, a.header().CWD, tool, call)+ execution := ToolExecution{Unavailable: tool == nil, SessionID: header.ID, CWD: header.CWD, CallID: call.ID, Name: call.Name, Arguments: append(json.RawMessage(nil), args...), Turn: turn, Step: step}+ execution.SandboxPolicy = a.executionSandboxPolicy()+ ctx = withToolPosition(ctx, turn, step)+ ctx = withToolCallID(ctx, call.ID)+ ctx = context.WithValue(ctx, toolQuestionsKey{}, a.questions)+ dispatch := func(ctx context.Context) modeldata.ToolResult {+ return a.executeNativeToolDirect(ctx, turn, step, call, tool, schema)+ }+ approve := func(ctx context.Context, ask ToolPolicyAsk) error {+ if a.toolPolicyApprover == nil {+ return toolPolicyError{"APPROVAL_UNAVAILABLE", "No interactive approval service is available"}+ }+ return a.toolPolicyApprover(ctx, execution, ask)+ }+ var err error+ if a.toolInvocationFactory != nil {+ prepared.invocation, err = a.toolInvocationFactory(ctx, execution, dispatch, approve)+ } else {+ prepared.invocation = NewToolInvocation(ctx, execution, ToolPipelineProcessors{}, func(ctx context.Context) (ToolPipelineResult, error) { return EncodeToolPipelineResult(dispatch(ctx)) }, approve)+ }+ if err != nil || prepared.invocation == nil {+ if err == nil {+ err = fmt.Errorf("tool execution factory returned no invocation")+ }+ result := nativePolicyFailure(call, err)+ prepared.fallback = &result+ return prepared+ }+ if a.preExecutePolicy != nil {+ prepared.invocation.SetPreExecutePolicy(func(ctx context.Context) (PreToolDecision, error) { return a.preExecutePolicy(ctx, execution) })+ }+ prepared.invocation.trackBody = true+ prepared.preparation = prepared.invocation.Prepare()+ return prepared+}++func (p *nativePreparedTool) dispatch() ToolDispatchOutcome {+ if p.fallback != nil {+ return ToolDispatchOutcome{}+ }+ if !p.preparation.Dispatch {+ return p.preparation.Outcome+ }+ return p.invocation.Dispatch()+}++func (p *nativePreparedTool) settle(success bool) {+ if !p.settled && p.settler != nil {+ p.settler.SettleResult(p.call.ID, success)+ }+ p.settled = true+}+func (p *nativePreparedTool) complete(outcome ToolDispatchOutcome) (result modeldata.ToolResult) {+ if p.fallback != nil {+ return *p.fallback+ }+ canonical := p.invocation.Complete(outcome)+ p.canonical = &canonical+ decoded, err := DecodeToolPipelineResult(canonical)+ if err == nil {+ for _, message := range decoded.AdditionalContexts {+ var fields struct{ ID, Role string }+ if json.Unmarshal(message, &fields) != nil || fields.ID == "" || fields.Role != "user" {+ err = fmt.Errorf("tool policy context must be a user message with an identity")+ break+ }+ if err = sessionformat.ValidateV4Rows([]sessionformat.Event{{Type: "user/message", Data: message}}); err != nil {+ break+ }+ }+ }+ if err != nil {+ p.canonical = nil+ return nativePolicyFailure(p.call, err)+ }+ decoded.ID, decoded.Name = p.call.ID, p.call.Name+ if outcome.NeedsPost && p.output != nil {+ decoded = p.output(decoded)+ updated, encodeErr := EncodeToolPipelineResult(decoded)+ if encodeErr != nil {+ p.canonical = nil+ return nativePolicyFailure(p.call, encodeErr)+ }+ // Retention changes presentation only; preserve the canonical value.+ updated.Value = canonical.Value+ canonical, err = materializePipelineResult(updated)+ if err != nil {+ p.canonical = nil+ return nativePolicyFailure(p.call, err)+ }+ decoded, err = DecodeToolPipelineResult(canonical)+ if err != nil {+ p.canonical = nil+ return nativePolicyFailure(p.call, err)+ }+ decoded.ID, decoded.Name = p.call.ID, p.call.Name+ }+ if outcome.NeedsPost && p.postResult != nil {+ p.postResult(p.call, &decoded)+ p.canonical.AdditionalContexts = decoded.AdditionalContexts+ }+ return decoded+}+func nativePolicyFailure(call modeldata.ToolRequest, err error) modeldata.ToolResult {+ return modeldata.ToolResult{ID: call.ID, Name: call.Name, IsError: true, Code: "TOOL_POLICY_ERROR", Content: "Error: " + err.Error()}+}+func (a *nativeTools) executeNativeTool(ctx context.Context, turn, step uint64, call modeldata.ToolRequest) modeldata.ToolResult {+ p := a.prepareNativeTool(ctx, turn, step, call)+ defer p.settle(false)+ result := p.complete(p.dispatch())+ p.settle(!result.IsError)+ return result+}++type toolPolicyError struct{ code, message string }++func (e toolPolicyError) Error() string { return e.message }+func (e toolPolicyError) ToolErrorInfo() (string, string) { return "ToolPolicyError", e.code }diff --git a/harness/agent/native_tool_pipeline_test.go b/harness/agent/native_tool_pipeline_test.gonew file mode 100644index 0000000..1b8ff56--- /dev/null+++ b/harness/agent/native_tool_pipeline_test.go@@ -0,0 +1,118 @@+package agent++import (+ "context"+ "encoding/json"+ "testing"++ "go-bot/harness/session"+ "go-bot/internal/modeldata"+)++func TestToolPipelineResultAndDeferredContextEnterTheExistingJournalInOrder(t *testing.T) {+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "policy-loop", CWD: "/tmp", CreatedAt: 1}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ probe := &dynamicProbe{label: "raw"}+ steps, resolutions := 0, 0+ model := dynamicModel(func(_ context.Context, messages []Message, _ []ToolSpec) (modeldata.AssistantMessage, error) {+ steps+++ if steps == 1 {+ return modeldata.AssistantMessage{ToolCalls: []modeldata.ToolRequest{{ID: "native-policy-call", Name: "extension_probe", Arguments: `{}`}}}, nil+ }+ toolIndex, contextIndex := -1, -1+ for i, message := range messages {+ if message.Role == "tool" && message.Content == "reviewed" {+ toolIndex = i+ }+ if message.Role == "user" && message.Content == "policy context" {+ contextIndex = i+ }+ }+ if toolIndex < 0 || contextIndex <= toolIndex {+ t.Errorf("policy outcome/context missing or unordered: %+v", messages)+ }+ return modeldata.AssistantMessage{Content: "done"}, nil+ })+ loop, err := NewNativeLoop(live, model, "provider", "model", "prompt", []Tool{probe}, 3, 3)+ if err != nil {+ t.Fatal(err)+ }+ loop.SetToolInvocationSource(func(_ context.Context, id string) (ToolInvocationFactory, error) {+ resolutions+++ if id != "policy-loop" {+ t.Error("wrong policy Session")+ }+ return func(ctx context.Context, execution ToolExecution, dispatch func(context.Context) modeldata.ToolResult, approve func(context.Context, ToolPolicyAsk) error) (*ToolInvocation, error) {+ turn, step, ok := ToolPositionFromContext(ctx)+ if !ok || turn != execution.Turn || step != execution.Step || execution.CWD != "/tmp" || execution.CallID != "native-policy-call" {+ t.Errorf("wrong execution context: %+v", execution)+ }+ return NewToolInvocation(ctx, execution, ToolPipelineProcessors{PostExecute: func(context.Context, ToolPipelineResult) (PostToolDecision, error) {+ return PostToolDecision{Kind: "accept", Content: pipelineText("reviewed"), AdditionalContexts: []json.RawMessage{json.RawMessage(`{"id":"context","role":"user","source":{"kind":"test-policy","form":"notice"},"content":[{"type":"text","text":"policy context"}]}`)}}, nil+ }}, func(ctx context.Context) (ToolPipelineResult, error) { return EncodeToolPipelineResult(dispatch(ctx)) }, approve), nil+ }, nil+ })+ if _, err = loop.AcceptText(t.Context(), "run probe"); err != nil {+ t.Fatal(err)+ }+ if ran, answer, err := loop.RunNext(t.Context()); !ran || answer != "done" || err != nil {+ t.Fatalf("ran=%v answer=%q err=%v", ran, answer, err)+ }+ if probe.calls != 1 || resolutions != 2 {+ t.Fatalf("calls=%d resolutions=%d", probe.calls, resolutions)+ }+ if err = sessionformat.ValidateV4Relationships(live.DurableEvents()); err != nil {+ t.Fatal(err)+ }+}++func TestToolPreparationCapturesActualToolBeforeTableChanges(t *testing.T) {+ first, replacement := &dynamicProbe{label: "first"}, &dynamicProbe{label: "replacement"}+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "fixed-tool", CreatedAt: 1, CWD: t.TempDir()}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ loop, err := NewNativeLoop(live, &nativeAnswerModel{}, "p", "m", "prompt", []Tool{first}, 2, 2)+ if err != nil {+ t.Fatal(err)+ }+ prepared := loop.prepareNativeTool(t.Context(), 1, 1, modeldata.ToolRequest{ID: "fixed", Name: first.Spec().Name, Arguments: `{}`})+ loop.tools[first.Spec().Name] = replacement+ result := prepared.complete(prepared.dispatch())+ if result.IsError || first.calls != 1 || replacement.calls != 0 {+ t.Fatalf("first=%d replacement=%d result=%+v", first.calls, replacement.calls, result)+ }+}++func TestNativeDispatchMarksOnlyTheBusinessBodyAsStarted(t *testing.T) {+ for _, tc := range []struct {+ name, tool, args string+ started bool+ }{+ {"invalid-json", "extension_probe", "{", false},+ {"unknown-tool", "missing", "{}", false},+ {"business-body", "extension_probe", "{}", true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "body-boundary", CreatedAt: 1, CWD: t.TempDir()}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ probe := &dynamicProbe{label: "body"}+ loop, err := NewNativeLoop(live, &nativeAnswerModel{}, "p", "m", "prompt", []Tool{probe}, 2, 2)+ if err != nil {+ t.Fatal(err)+ }+ prepared := loop.prepareNativeTool(t.Context(), 1, 1, modeldata.ToolRequest{ID: "call", Name: tc.tool, Arguments: tc.args})+ result := prepared.complete(prepared.dispatch())+ if got := prepared.invocation.started.Load(); got != tc.started {+ t.Fatalf("bodyStarted=%v want=%v result=%+v", got, tc.started, result)+ }+ if (probe.calls > 0) != tc.started {+ t.Fatalf("business calls=%d", probe.calls)+ }+ })+ }+}diff --git a/harness/agent/native_tool_scheduler.go b/harness/agent/native_tool_scheduler.goindex ffa6e19..be85e7c 100644--- a/harness/agent/native_tool_scheduler.go+++ b/harness/agent/native_tool_scheduler.go@@ -3,7 +3,6 @@ package agentimport ("context""encoding/json"- "errors""fmt""github.com/google/uuid"@@ -11,51 +10,71 @@ import ("go-bot/internal/modeldata")-// executeNativeStepTools overlaps only consecutive calls whose static tool-// specs declare parallel-safe execution. An exclusive call waits for the pool-// to drain. Dispatch can overlap, while intent and result commits stay in-// model order and each intent is flushed before its tool can have effects.-func (a *NativeLoop) executeNativeStepTools(- ctx context.Context, turn uint64, step int, calls []modeldata.ToolRequest, toolCount *int,-) (budgetExceeded, concluded bool, err error) {- for index := 0; index < len(calls); {- if a.maxParallelToolCalls > 1 && a.parallelSafe[calls[index].Name] && ctx.Err() == nil {- end := index + 1- for end < len(calls) && a.parallelSafe[calls[end].Name] {- end+++// executeNativeStepTools owns the upstream ordered prepare / overlapping+// dispatch / ordered complete contract. Completing in order includes policy+// callbacks and final observers, not merely the journal append.+func (a *NativeLoop) executeNativeStepTools(ctx context.Context, turn uint64, step int, calls []modeldata.ToolRequest, toolCount *int) (budgetExceeded, concluded bool, err error) {+ sequences := make([]uint64, len(calls))+ err = runToolBatch(calls, a.maxParallelToolCalls, batchCallbacks{+ parallel: func(call modeldata.ToolRequest) bool { return a.nativeToolParallel(ctx, call) },+ start: func(index int, call modeldata.ToolRequest) (*modeldata.ToolResult, error) {+ *toolCount+++ seq, err := a.appendNativeToolIntent(context.WithoutCancel(ctx), turn, step, call)+ if err != nil {+ return nil, err}- over, done, groupErr := a.executeNativeParallelGroup(ctx, turn, step, calls[index:end], toolCount)- budgetExceeded = budgetExceeded || over- concluded = concluded || done- if groupErr != nil {- return budgetExceeded, concluded, groupErr+ sequences[index] = seq+ if ctx.Err() != nil {+ result := nativeSkippedToolResult(call)+ return &result, nil}- index = end- continue- }- call := calls[index]- index++- *toolCount++- callSeq, appendErr := a.appendNativeToolIntent(ctx, turn, step, call)- if appendErr != nil {- return budgetExceeded, concluded, appendErr- }- var result modeldata.ToolResult- switch {- case ctx.Err() != nil:- result = nativeSkippedToolResult(call)- case *toolCount > a.maxToolCalls:- budgetExceeded = true- result = nativeBudgetToolResult(call)- default:- result = a.executeNativeTool(ctx, turn, uint64(step), call)- }- concluded = concluded || result.ConcludeTurn- if commitErr := a.commitNativeToolResult(turn, step, callSeq, call, result); commitErr != nil {- return budgetExceeded, concluded, commitErr+ if *toolCount > a.maxToolCalls {+ budgetExceeded = true+ result := nativeBudgetToolResult(call)+ return &result, nil+ }+ return nil, nil+ },+ prepare: func(call modeldata.ToolRequest) *nativePreparedTool {+ return a.prepareNativeTool(ctx, turn, uint64(step), call)+ },+ commit: func(index int, result modeldata.ToolResult, _ *ToolPipelineResult) error {+ if err := a.commitNativeToolResult(turn, step, sequences[index], calls[index], result); err != nil {+ return err+ }+ concluded = concluded || result.ConcludeTurn+ return nil+ },+ })+ return budgetExceeded, concluded, err+}++func (a *nativeTools) nativeToolParallel(ctx context.Context, call modeldata.ToolRequest) (safe bool) {+ defer func() {+ if recover() != nil {+ safe = false}+ }()+ if ctx.Err() != nil {+ return false+ }+ tool, schema, err := a.lookupTool(ctx, call.Name)+ if err != nil || tool == nil {+ return false}- return budgetExceeded, concluded, nil+ classifier, ok := tool.(ConcurrencyTool)+ if !ok {+ return tool.Spec().ParallelSafe+ }+ args := json.RawMessage(call.Arguments)+ if len(args) == 0 {+ args = json.RawMessage(`{}`)+ }+ if schema == nil || !json.Valid(args) || validateToolParameters(schema, args) != nil || classifier.Validate(args) != nil {+ return false+ }+ safe, err = classifier.IsConcurrencySafe(ctx, args)+ return safe && err == nil}func (a *NativeLoop) appendNativeToolIntent(ctx context.Context, turn uint64, step int, call modeldata.ToolRequest) (uint64, error) {@@ -75,7 +94,9 @@ func (a *NativeLoop) appendNativeToolIntent(ctx context.Context, turn uint64, streturn event.Seq, nil}-func (a *NativeLoop) commitNativeToolResult(turn uint64, step int, callSeq uint64, call modeldata.ToolRequest, result modeldata.ToolResult) error {+// logNativeToolOutcome commits the frozen result and applicable built-in+// presentation facts. Output processing and repeat reminders are already settled.+func (a *NativeLoop) logNativeToolOutcome(turn uint64, step int, callSeq uint64, call modeldata.ToolRequest, result modeldata.ToolResult) error {var delivery sessionformat.PresentedFilesif call.Name == "present" && !result.IsError && len(result.Meta) > 0 {if err := json.Unmarshal(result.Meta, &delivery); err != nil {@@ -91,23 +112,50 @@ func (a *NativeLoop) commitNativeToolResult(turn uint64, step int, callSeq uint6return err}}+ return nil+}++func (a *NativeLoop) commitNativeToolResult(turn uint64, step int, callSeq uint64, call modeldata.ToolRequest, result modeldata.ToolResult) error {+ if err := a.logNativeToolOutcome(turn, step, callSeq, call, result); err != nil {+ return err+ }+ // Match the upstream batch FIFO: contexts follow the batch's tool results+ // and retain call order even when tool bodies overlap.+ contexts := make([]map[string]any, 0, len(result.AdditionalContexts))+ for _, message := range result.AdditionalContexts {+ var value map[string]any+ if err := json.Unmarshal(message, &value); err != nil {+ return err+ }+ contexts = append(contexts, value)+ }if err := a.session.Flush(context.Background()); err != nil {return err}+ a.repeatReminders = append(a.repeatReminders, contexts...)+ if a.instructionsForStep != nil {+ return a.scanInstructionFileTouches()+ }+ return nil+}++// observeRepeatedToolResult is an ordered PostExecute processor. Result only+// commits its already formed contexts; it never updates the repeat counter.+func (a *NativeLoop) observeRepeatedToolResult(call modeldata.ToolRequest, result *modeldata.ToolResult) {// These two results are synthesized by the loop before entering the tool// runtime. DeepSeek's guard observes post-execute attempts, including tool// denials, but not calls skipped by turn cancellation or our local budget.if result.Code == "TOOL_ABORTED_BEFORE_DISPATCH" || result.Code == "TOOL_BUDGET_EXCEEDED" {- return nil+ return}if reminder := a.repeatGuard.observe(call); reminder != nil {- a.repeatReminders = append(a.repeatReminders, nativeTextMessage(+ message, _ := json.Marshal(nativeTextMessage(uuid.NewString(), "user", map[string]any{"kind": "repeat-tool-reminder", "form": "notice","summary": call.Name + " × " + fmt.Sprint(a.repeatGuard.count),}, reminder.Content))+ result.AdditionalContexts = append(result.AdditionalContexts, message)}- return nil}func nativeSkippedToolResult(call modeldata.ToolRequest) modeldata.ToolResult {@@ -119,103 +167,3 @@ func nativeBudgetToolResult(call modeldata.ToolRequest) modeldata.ToolResult {return modeldata.ToolResult{ID: call.ID, Name: call.Name, IsError: true,Code: "TOOL_BUDGET_EXCEEDED", Content: "Tool call budget exceeded."}}--func (a *NativeLoop) executeNativeParallelGroup(- ctx context.Context, turn uint64, step int, calls []modeldata.ToolRequest, toolCount *int,-) (budgetExceeded, concluded bool, err error) {- type completion struct {- index int- result modeldata.ToolResult- }- completed := make(chan completion, len(calls))- results := make([]modeldata.ToolResult, len(calls))- sequences := make([]uint64, len(calls))- ready := make([]bool, len(calls))- nextStart, nextCommit, running := 0, 0, 0- // Even a persistence failure must not let the turn close while dispatched- // tools are still changing the world. Reopen repairs any unpaired intents.- defer func() {- for running > 0 {- <-completed- running--- }- }()- commitReady := func() error {- for nextCommit < len(calls) && ready[nextCommit] {- if err := a.commitNativeToolResult(turn, step, sequences[nextCommit], calls[nextCommit], results[nextCommit]); err != nil {- return err- }- concluded = concluded || results[nextCommit].ConcludeTurn- nextCommit++- }- return nil- }- startReady := func() error {- for nextStart < len(calls) && running < a.maxParallelToolCalls && ctx.Err() == nil {- index := nextStart- call := calls[index]- *toolCount++- callSeq, err := a.appendNativeToolIntent(ctx, turn, step, call)- if err != nil {- return err- }- sequences[index] = callSeq- nextStart++- switch {- case ctx.Err() != nil:- results[index] = nativeSkippedToolResult(call)- ready[index] = true- case *toolCount > a.maxToolCalls:- budgetExceeded = true- results[index] = nativeBudgetToolResult(call)- ready[index] = true- default:- running++- go func() {- completed <- completion{index: index, result: a.executeNativeTool(ctx, turn, uint64(step), call)}- }()- }- if err := commitReady(); err != nil {- return err- }- }- return nil- }- if err := startReady(); err != nil {- return budgetExceeded, concluded, err- }- for running > 0 {- outcome := <-completed- running--- results[outcome.index] = outcome.result- ready[outcome.index] = true- if err := commitReady(); err != nil {- return budgetExceeded, concluded, err- }- if err := startReady(); err != nil {- return budgetExceeded, concluded, err- }- }- if ctx.Err() != nil {- for nextStart < len(calls) {- index := nextStart- call := calls[index]- *toolCount++- callSeq, err := a.appendNativeToolIntent(context.Background(), turn, step, call)- if err != nil {- return budgetExceeded, concluded, err- }- sequences[index] = callSeq- results[index] = nativeSkippedToolResult(call)- ready[index] = true- nextStart++- if err := commitReady(); err != nil {- return budgetExceeded, concluded, err- }- }- }- if nextCommit != len(calls) {- return budgetExceeded, concluded, errors.New("native parallel scheduler left uncommitted results")- }- return budgetExceeded, concluded, nil-}diff --git a/harness/agent/native_tool_source.go b/harness/agent/native_tool_source.gonew file mode 100644index 0000000..88b7c40--- /dev/null+++ b/harness/agent/native_tool_source.go@@ -0,0 +1,90 @@+package agent++import (+ "bytes"+ "context"+ "errors"+ "fmt"++ "github.com/santhosh-tekuri/jsonschema/v6"+)++// ToolSource resolves additional capabilities for this Session at the start of+// each model step. Retries and tool dispatch retain that exact set. Configure+// the source before driving the Agent; implementations must support concurrent+// reads by different Sessions and reject calls through disposed registrations.+type ToolSource func(context.Context, string) ([]Tool, error)++type ToolSourceInfo struct {+ SessionID string `json:"sessionId"`+ CWD string `json:"cwd"`+ Tools []ToolSpec `json:"tools"`+ ModelSelection ModelRoute `json:"modelSelection"`+ SandboxPolicy *ExecutionSandboxPolicy `json:"sandboxPolicy,omitempty"`+}+type toolSourceInfoKey struct{}++func ToolSourceInfoFromContext(ctx context.Context) (ToolSourceInfo, bool) {+ value, ok := ctx.Value(toolSourceInfoKey{}).(ToolSourceInfo)+ return value, ok+}++func (a *NativeLoop) SetToolSource(source ToolSource) { a.toolSource = source }++func (a *NativeLoop) refreshTools(ctx context.Context) error {+ if a.toolSource == nil {+ if a.promptAssembler != nil {+ return a.installTools(a.baseTools)+ }+ return nil+ }+ info := ToolSourceInfo{SessionID: a.session.Header().ID, CWD: a.session.Header().CWD, ModelSelection: ModelRoute{Provider: a.provider, Model: a.modelID, ReasoningEffort: a.reasoningEffort}, Tools: []ToolSpec{}}+ info.SandboxPolicy = a.executionSandboxPolicy()+ for _, tool := range a.baseTools {+ info.Tools = append(info.Tools, tool.Spec())+ }+ ctx = context.WithValue(ctx, toolSourceInfoKey{}, info)+ additional, err := a.toolSource(ctx, a.session.Header().ID)+ if err != nil {+ return fmt.Errorf("resolve Session tools: %w", err)+ }+ tools := append(append([]Tool(nil), a.baseTools...), additional...)+ return a.installTools(tools)+}++// Publish only after every definition validates. A bad extension cannot leave+// a partially replaced table, shadow a built-in, or cause schema I/O.+func (a *NativeLoop) installTools(tools []Tool) error {+ a.nativeTools.mu.Lock()+ defer a.nativeTools.mu.Unlock()+ byName := make(map[string]Tool, len(tools))+ schemas := make(map[string]*jsonschema.Schema, len(tools))+ safe := make(map[string]bool, len(tools))+ specs := make([]ToolSpec, 0, len(tools))+ previous := make(map[string]ToolSpec, len(a.toolSpecs))+ for _, spec := range a.toolSpecs {+ previous[spec.Name] = spec+ }+ for _, tool := range tools {+ if tool == nil {+ return errors.New("native Agent tool is nil")+ }+ spec := tool.Spec()+ if spec.Name == "" || byName[spec.Name] != nil {+ return fmt.Errorf("invalid or duplicate native Agent tool %q", spec.Name)+ }+ schema := a.toolSchemas[spec.Name]+ if old, ok := previous[spec.Name]; !ok || !bytes.Equal(old.Parameters, spec.Parameters) || schema == nil {+ var err error+ schema, err = compileToolParameters(spec.Parameters)+ if err != nil {+ return fmt.Errorf("compile native Agent tool %q parameters: %w", spec.Name, err)+ }+ }+ spec.Parameters = bytes.Clone(spec.Parameters)+ byName[spec.Name], schemas[spec.Name], safe[spec.Name] = tool, schema, spec.ParallelSafe+ specs = append(specs, spec)+ }+ a.tools, a.toolSchemas, a.parallelSafe, a.toolSpecs = byName, schemas, safe, specs+ return nil+}diff --git a/harness/agent/native_tool_source_test.go b/harness/agent/native_tool_source_test.gonew file mode 100644index 0000000..1b7e8af--- /dev/null+++ b/harness/agent/native_tool_source_test.go@@ -0,0 +1,104 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "testing"++ "go-bot/harness/session"+ "go-bot/internal/modeldata"+)++type dynamicProbe struct {+ label string+ calls int+}++func (p *dynamicProbe) Spec() ToolSpec {+ return ToolSpec{Name: "extension_probe", Description: p.label, Parameters: json.RawMessage(`{"type":"object","additionalProperties":false}`)}+}+func (*dynamicProbe) Validate(json.RawMessage) error { return nil }+func (p *dynamicProbe) Execute(context.Context, json.RawMessage) (string, error) {+ p.calls+++ return p.label, nil+}++type dynamicModel func(context.Context, []Message, []ToolSpec) (modeldata.AssistantMessage, error)++func (f dynamicModel) Complete(ctx context.Context, messages []Message, specs []ToolSpec) (modeldata.AssistantMessage, error) {+ return f(ctx, messages, specs)+}++func TestStepPinsDynamicHandlerAndRefreshesNextStep(t *testing.T) {+ ctx := context.Background()+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "dynamic-steps", CreatedAt: 1}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ old, next := &dynamicProbe{label: "old"}, &dynamicProbe{label: "next"}+ current := old+ steps := 0+ model := dynamicModel(func(_ context.Context, _ []Message, specs []ToolSpec) (modeldata.AssistantMessage, error) {+ steps+++ want := "old"+ if steps > 1 {+ want = "next"+ }+ if len(specs) != 1 || specs[0].Description != want {+ t.Fatalf("step %d has wrong definition: %+v", steps, specs)+ }+ if steps == 1 {+ // A config change during a model request must not retarget its call.+ current = next+ return modeldata.AssistantMessage{ToolCalls: []modeldata.ToolRequest{{ID: "probe-call", Name: "extension_probe", Arguments: `{}`}}}, nil+ }+ return modeldata.AssistantMessage{Content: "done"}, nil+ })+ loop, err := NewNativeLoop(live, model, "provider", "model", "prompt", nil, 4, 4)+ if err != nil {+ t.Fatal(err)+ }+ sources := 0+ loop.SetToolSource(func(_ context.Context, id string) ([]Tool, error) {+ if id != "dynamic-steps" {+ t.Fatalf("wrong Session scope: %q", id)+ }+ sources+++ return []Tool{current}, nil+ })+ if _, err := loop.AcceptText(ctx, "probe"); err != nil {+ t.Fatal(err)+ }+ if ran, answer, err := loop.RunNext(ctx); !ran || err != nil || answer != "done" {+ t.Fatalf("dynamic turn: ran=%v answer=%q err=%v", ran, answer, err)+ }+ if old.calls != 1 || next.calls != 0 || sources != 2 {+ t.Fatalf("handler changed within step: old=%d next=%d resolutions=%d", old.calls, next.calls, sources)+ }+ if err := sessionformat.ValidateV4Relationships(live.DurableEvents()); err != nil {+ t.Fatal(err)+ }+}++func TestBadDynamicSetDoesNotShadowBuiltInOrPartiallyPublish(t *testing.T) {+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "dynamic-failure", CreatedAt: 1}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ builtin := &dynamicProbe{label: "built-in"}+ loop, err := NewNativeLoop(live, &nativeAnswerModel{}, "provider", "model", "prompt", []Tool{builtin}, 2, 2)+ if err != nil {+ t.Fatal(err)+ }+ loop.SetToolSource(func(context.Context, string) ([]Tool, error) {+ return []Tool{&dynamicProbe{label: "shadow"}}, nil+ })+ if err := loop.refreshTools(context.Background()); err == nil || loop.tools["extension_probe"] != builtin {+ t.Fatalf("shadow registered: %v", err)+ }+ loop.SetToolSource(func(context.Context, string) ([]Tool, error) { return nil, errors.New("extension unavailable") })+ if err := loop.refreshTools(context.Background()); err == nil || len(loop.toolSpecs) != 1 {+ t.Fatalf("source failure changed current set: %v", err)+ }+}diff --git a/harness/agent/result_limits.go b/harness/agent/result_limits.goindex cbc5f16..083a96c 100644--- a/harness/agent/result_limits.go+++ b/harness/agent/result_limits.go@@ -2,6 +2,7 @@ package agentimport ("fmt"+ "strings""go-bot/internal/modeldata")@@ -21,16 +22,33 @@ const (// Success content is not silently truncated: the model receives an explicit// error telling it to save large output in the workspace and return a path.func boundedToolResult(result modeldata.ToolResult) modeldata.ToolResult {- if len(result.Content) <= maxDurableToolContentBytes {+ size := len(result.Content)+ for _, block := range result.ContentBlocks {+ size += len(block.Text)+ }+ if size <= maxDurableToolContentBytes {return result}if result.IsError {- result.Content = result.Content[:maxDurableToolErrorBytes] + fmt.Sprintf("\n[error detail truncated: %d bytes total]", len(result.Content))+ var detail strings.Builder+ appendDetail := func(text string) {+ remaining := maxDurableToolErrorBytes - detail.Len()+ if remaining > 0 {+ detail.WriteString(text[:min(len(text), remaining)])+ }+ }+ appendDetail(result.Content)+ for _, block := range result.ContentBlocks {+ appendDetail(block.Text)+ }+ result.Content = strings.ToValidUTF8(detail.String(), "") + fmt.Sprintf("\n[error detail truncated: %d bytes total]", size)+ result.ContentBlocks = nilreturn result}result.IsError = trueresult.Code = "TOOL_OUTPUT_TOO_LARGE"- result.Content = fmt.Sprintf("Tool returned %d bytes, exceeding the %d-byte durable result limit. Save large output to the workspace and return a bounded summary or file path.", len(result.Content), maxDurableToolContentBytes)+ result.Content = fmt.Sprintf("Tool returned %d bytes, exceeding the %d-byte durable result limit. Save large output to the workspace and return a bounded summary or file path.", size, maxDurableToolContentBytes)+ result.ContentBlocks = nilreturn result}diff --git a/harness/agent/tool_batch.go b/harness/agent/tool_batch.gonew file mode 100644index 0000000..454b774--- /dev/null+++ b/harness/agent/tool_batch.go@@ -0,0 +1,139 @@+package agent++import (+ "context"+ "errors"+ "github.com/santhosh-tekuri/jsonschema/v6"+ "go-bot/harness/interaction"+ sessionformat "go-bot/harness/session"+ "go-bot/internal/modeldata"+ "sync"+)++// nativeTools is the Go-owned tool execution context of an Agent. There is no+// plugin Agent proxy, arbitrary dispatch API, or second Session store.+type nativeTools struct {+ mu sync.RWMutex+ header func() sessionformat.Header+ questions *interaction.NativeQuestions+ sandboxMode func() string+ tools map[string]Tool+ toolSchemas map[string]*jsonschema.Schema+ parallelSafe map[string]bool+ toolInvocationFactory ToolInvocationFactory+ toolPolicyApprover func(context.Context, ToolExecution, ToolPolicyAsk) error+ preExecutePolicy NativePreToolPolicy+ postResult func(modeldata.ToolRequest, *modeldata.ToolResult)+ maxParallelToolCalls int+}++func (a *nativeTools) lookupTool(_ context.Context, name string) (Tool, *jsonschema.Schema, error) {+ a.mu.RLock()+ defer a.mu.RUnlock()+ return a.tools[name], a.toolSchemas[name], nil+}++type batchCallbacks struct {+ parallel func(modeldata.ToolRequest) bool+ start func(int, modeldata.ToolRequest) (*modeldata.ToolResult, error)+ prepare func(modeldata.ToolRequest) *nativePreparedTool+ commit func(int, modeldata.ToolResult, *ToolPipelineResult) error+}++func runToolBatch(calls []modeldata.ToolRequest, limit int, callbacks batchCallbacks) error {+ type completion struct {+ index int+ outcome ToolDispatchOutcome+ }+ completed := make(chan completion, len(calls))+ prepared := make([]*nativePreparedTool, len(calls))+ results := make([]modeldata.ToolResult, len(calls))+ outcomes := make([]ToolDispatchOutcome, len(calls))+ ready := make([]bool, len(calls))+ nextStart, nextCommit, running := 0, 0, 0+ exclusive := false+ if limit < 1 {+ limit = 1+ }+ defer func() {+ for running > 0 {+ <-completed+ running--+ }+ for _, call := range prepared {+ if call != nil && call.invocation != nil {+ call.settle(false)+ }+ }+ }()+ commitReady := func() error {+ for nextCommit < len(calls) && ready[nextCommit] {+ i := nextCommit+ var canonical *ToolPipelineResult+ if prepared[i] != nil {+ results[i] = prepared[i].complete(outcomes[i])+ canonical = prepared[i].canonical+ }+ if err := callbacks.commit(i, results[i], canonical); err != nil {+ return err+ }+ if prepared[i] != nil {+ prepared[i].settle(!results[i].IsError)+ }+ nextCommit+++ }+ return nil+ }+ fill := func() error {+ for nextStart < len(calls) && running < limit && !exclusive {+ i := nextStart+ call := calls[i]+ parallel := callbacks.parallel(call)+ if !parallel && running > 0 {+ break+ }+ skip, err := callbacks.start(i, call)+ if err != nil {+ return err+ }+ nextStart+++ if skip != nil {+ results[i] = *skip+ ready[i] = true+ } else {+ prepared[i] = callbacks.prepare(call)+ if prepared[i].fallback != nil || !prepared[i].preparation.Dispatch {+ outcomes[i] = prepared[i].dispatch()+ ready[i] = true+ } else {+ running+++ exclusive = !parallel+ go func(index int) { completed <- completion{index, prepared[index].dispatch()} }(i)+ }+ }+ if err := commitReady(); err != nil {+ return err+ }+ }+ return nil+ }+ if err := fill(); err != nil {+ return err+ }+ for running > 0 {+ done := <-completed+ running--+ exclusive = false+ outcomes[done.index], ready[done.index] = done.outcome, true+ if err := commitReady(); err != nil {+ return err+ }+ if err := fill(); err != nil {+ return err+ }+ }+ if nextCommit != len(calls) {+ return errors.New("tool scheduler left uncommitted results")+ }+ return nil+}diff --git a/harness/agent/tool_context.go b/harness/agent/tool_context.goindex ff4cd1c..138599b 100644--- a/harness/agent/tool_context.go+++ b/harness/agent/tool_context.go@@ -1,12 +1,23 @@package agent-import "context"+import (+ "context"+ "go-bot/harness/interaction"+)type toolPositionKey struct{}type turnSourceKey struct{}type toolCallIDKey struct{}type toolControlKey struct{}type toolQuestionKey struct{}+type toolQuestionsKey struct{}++// ToolQuestionsFromContext is available only inside a real Go tool body. The+// channel belongs to the running Session and is never exported to plugins.+func ToolQuestionsFromContext(ctx context.Context) *interaction.NativeQuestions {+ value, _ := ctx.Value(toolQuestionsKey{}).(*interaction.NativeQuestions)+ return value+}type toolControl struct{ concludeTurn bool }@@ -49,7 +60,8 @@ func ConcludeTurn(ctx context.Context) {}}-// ToolCallIDFromContext identifies the exact durable assistant tool call.+// ToolCallIDFromContext identifies the current tool invocation. Model calls+// have a durable assistant record.func ToolCallIDFromContext(ctx context.Context) (string, bool) {callID, ok := ctx.Value(toolCallIDKey{}).(string)return callID, ok && callID != ""@@ -63,7 +75,7 @@ func TurnSourceFromContext(ctx context.Context) (MessageSource, bool) {}// ToolPositionFromContext identifies the step that admitted a tool call. It is-// available only during AgentLoop tool execution, never in external requests.+// available to tools bound to the AgentLoop's real open step.func ToolPositionFromContext(ctx context.Context) (turn, step uint64, ok bool) {position, ok := ctx.Value(toolPositionKey{}).(toolPosition)if !ok || position.turn == 0 || position.step == 0 {diff --git a/harness/agent/tool_output.go b/harness/agent/tool_output.gonew file mode 100644index 0000000..fe0841d--- /dev/null+++ b/harness/agent/tool_output.go@@ -0,0 +1,58 @@+package agent++import (+ "context"+ "log/slog"+ "strings"++ "go-bot/harness/output"+ "go-bot/internal/modeldata"+)++// The output policy is selected and any Job limit captured in PreExecute.+// Execution may overlap; this processor runs only in ordered PostExecute.+func prepareToolOutput(ctx context.Context, cwd string, tool Tool, call modeldata.ToolRequest) func(modeldata.ToolResult) modeldata.ToolResult {+ var specialized func(modeldata.ToolResult) modeldata.ToolResult+ if prepared, ok := tool.(PreparedOutputTool); ok {+ specialized = prepared.PrepareOutput([]byte(call.Arguments))+ }+ retained := false+ if managed, ok := tool.(RetainedOutputTool); ok {+ retained = managed.RetainsOutput()+ }+ return func(result modeldata.ToolResult) modeldata.ToolResult {+ if specialized != nil {+ result = specialized(result)+ }+ if retained {+ return boundedToolResult(result)+ }+ var text strings.Builder+ text.WriteString(result.Content)+ hasImage := false+ for _, block := range result.ContentBlocks {+ if block.Type != "text" {+ hasImage = true+ continue+ }+ text.WriteString(block.Text)+ }+ // Upstream preserves mixed content when the model has no image pricing+ // contract. Do not guess an image cost or discard its attachment.+ if hasImage {+ if output.Estimate(text.String()) > output.InlineTokens {+ slog.Warn("tool output retention unavailable: model has no image pricing", "tool", call.Name)+ }+ return boundedToolResult(result)+ }+ preview, err := output.RetainText(context.WithoutCancel(ctx), cwd, ".agent/tool-spill", call.Name, text.String(), output.InlineTokens)+ if err != nil {+ slog.Warn("tool output retention unavailable", "tool", call.Name, "error", err)+ }+ if preview != text.String() {+ result.Content = preview+ result.ContentBlocks = nil+ }+ return boundedToolResult(result)+ }+}diff --git a/harness/agent/tool_output_test.go b/harness/agent/tool_output_test.gonew file mode 100644index 0000000..32632e6--- /dev/null+++ b/harness/agent/tool_output_test.go@@ -0,0 +1,68 @@+package agent++import (+ "context"+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "go-bot/harness/content"+ "go-bot/harness/output"+ sessionformat "go-bot/harness/session"+ "go-bot/internal/modeldata"+)++type retainedProbe struct {+ normalizedProbe+ text string+}++func (p retainedProbe) ExecuteResult(context.Context, json.RawMessage) (modeldata.ToolResult, error) {+ return modeldata.ToolResult{ContentBlocks: []content.ContentBlock{{Type: "text", Text: p.text[:len(p.text)/2]}, {Type: "text", Text: p.text[len(p.text)/2:]}}, Meta: json.RawMessage(`{"source":"original"}`)}, nil+}+func TestNativeToolPostRetainsExactLongOutputInWorkspace(t *testing.T) {+ cwd := t.TempDir()+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "retained", CreatedAt: 1, CWD: cwd}, &nativeTestJournal{})+ if err != nil {+ t.Fatal(err)+ }+ original := strings.Repeat("Unicode output: 报告内容\n", 6000)+ loop, err := NewNativeLoop(live, &nativeAnswerModel{}, "p", "m", "core", []Tool{retainedProbe{text: original}}, 2, 2)+ if err != nil {+ t.Fatal(err)+ }+ result := loop.executeNativeTool(t.Context(), 1, 1, modeldata.ToolRequest{ID: "spill", Name: "protocol_result", Arguments: `{}`})+ if result.IsError || output.Estimate(result.Content) > output.InlineTokens || !strings.Contains(result.Content, "Full formatted result stored at:") {+ t.Fatalf("retention failed: %+v", result)+ }+ files, err := filepath.Glob(filepath.Join(cwd, ".agent", "tool-spill", "*"))+ if err != nil || len(files) != 1 {+ t.Fatalf("spill files: %v %v", files, err)+ }+ data, err := os.ReadFile(files[0])+ if err != nil || string(data) != original {+ t.Fatal("full output was not recoverable", err)+ }+ if string(result.Meta) != `{"source":"original"}` {+ t.Fatal("retention replaced tool metadata")+ }+}+func TestHardOutputLimitCoversMixedContentAndPreservesSmallImages(t *testing.T) {+ image := content.ImageBlock(content.ImageAttachment{ID: "sha256:" + strings.Repeat("0", 64), MIMEType: "image/png", Bytes: 10, Width: 2, Height: 2})+ small := modeldata.ToolResult{ContentBlocks: []content.ContentBlock{{Type: "text", Text: "before"}, image, {Type: "text", Text: "after"}}}+ if got := boundedToolResult(small); got.IsError || len(got.ContentBlocks) != 3 || got.ContentBlocks[1].ImageRefID != image.ImageRefID {+ t.Fatal("ordinary mixed result was damaged")+ }+ for _, failure := range []bool{false, true} {+ large := modeldata.ToolResult{IsError: failure, Content: "short prefix", ContentBlocks: []content.ContentBlock{{Type: "text", Text: strings.Repeat("大", maxDurableToolContentBytes/3)}, image, {Type: "text", Text: "tail"}}}+ got := boundedToolResult(large)+ if !got.IsError || len(got.ContentBlocks) != 0 || len(got.Content) > maxDurableToolErrorBytes+256 {+ t.Fatalf("unbounded mixed result survived: bytes=%d blocks=%d", len(got.Content), len(got.ContentBlocks))+ }+ if !failure && got.Code != "TOOL_OUTPUT_TOO_LARGE" {+ t.Fatal(got.Code)+ }+ }+}diff --git a/harness/agent/tool_pipeline.go b/harness/agent/tool_pipeline.gonew file mode 100644index 0000000..8f8e353--- /dev/null+++ b/harness/agent/tool_pipeline.go@@ -0,0 +1,394 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "sync/atomic"+)++// ToolPipelineResult is the lossless, execution-local result owned by Go. Value is not another Session fact: the existing journal+// records Content, Meta and the structured failure identity after settlement.+type ToolPipelineResult struct {+ IsError bool `json:"isError"`+ Value json.RawMessage `json:"value,omitempty"`+ Content []json.RawMessage `json:"content"`+ Error *ToolPipelineError `json:"error,omitempty"`+ Meta json.RawMessage `json:"meta,omitempty"`+ AdditionalContexts []json.RawMessage `json:"additionalContexts,omitempty"`+ ConcludesTurn bool `json:"concludesTurn,omitempty"`+}++type ToolPipelineError struct {+ Message string `json:"message"`+ Info *ToolPipelineErrorInfo `json:"info,omitempty"`+}++type ToolPipelineErrorInfo struct {+ Name string `json:"name"`+ Code string `json:"code"`+ Reason *string `json:"reason,omitempty"`+}++type PreToolDecision struct {+ Kind string `json:"kind"`+ Reason string `json:"reason,omitempty"`+ DisplayReason map[string]string `json:"displayReason,omitempty"`+ Info *ToolPipelineErrorInfo `json:"info,omitempty"`+}++type PostToolDecision struct {+ Kind string `json:"kind"`+ Value json.RawMessage `json:"value,omitempty"`+ Content []json.RawMessage `json:"content,omitempty"`+ Feedback []json.RawMessage `json:"feedback,omitempty"`+ Info *ToolPipelineErrorInfo `json:"info,omitempty"`+ AdditionalContexts []json.RawMessage `json:"additionalContexts,omitempty"`+}++// ToolPipelineProcessors are Go-internal result processors. They are not+// plugin hooks: the Bridge exposes neither registration nor stage dispatch.+// Go owns preparation, one body invocation, post-processing and settlement.+type ToolPipelineProcessors struct {+ Normalize func(context.Context, ToolPipelineResult) (ToolPipelineResult, error)+ Project func(context.Context, ToolPipelineResult) ([]json.RawMessage, error)+ PostExecute func(context.Context, ToolPipelineResult) (PostToolDecision, error)+ ReplaceValue func(context.Context, json.RawMessage) (ToolPipelineResult, error)+ Finalize func(context.Context, ToolPipelineResult) ([]json.RawMessage, error)+}++// ToolDispatchOutcome retains the upstream post-result/final-result distinction.+// Preparation and completion are ordered by the batch owner; only Dispatch may+// overlap sibling calls. Immediate preparation failures do not dispatch a body.+type ToolDispatchOutcome struct {+ Result ToolPipelineResult+ NeedsPost bool+}++type ToolPreparation struct {+ Dispatch bool+ Outcome ToolDispatchOutcome+}++type ToolInvocation struct {+ ctx context.Context+ execution ToolExecution+ hooks ToolPipelineProcessors+ body func(context.Context) (ToolPipelineResult, error)+ approve func(context.Context, ToolPolicyAsk) error+ defaultPre func(context.Context) (PreToolDecision, error)+ dispatched atomic.Bool+ started atomic.Bool+ trackBody bool+}++func NewToolInvocation(ctx context.Context, execution ToolExecution, hooks ToolPipelineProcessors,+ body func(context.Context) (ToolPipelineResult, error), approve func(context.Context, ToolPolicyAsk) error,+) *ToolInvocation {+ execution.Arguments = append(json.RawMessage(nil), execution.Arguments...)+ return &ToolInvocation{ctx: ctx, execution: execution, hooks: hooks, body: body, approve: approve}+}++// SetPreExecutePolicy installs the Go execution policy before preparation.+func (p *ToolInvocation) SetPreExecutePolicy(policy func(context.Context) (PreToolDecision, error)) {+ p.defaultPre = policy+}++func (p *ToolInvocation) Prepare() (prepared ToolPreparation) {+ defer func() {+ if value := recover(); value != nil {+ prepared = ToolPreparation{Outcome: ToolDispatchOutcome{Result: pipelineFailure(fmt.Errorf("tool preparation panicked: %v", value))}}+ }+ }()+ if p.ctx.Err() != nil {+ return ToolPreparation{Outcome: ToolDispatchOutcome{Result: pipelineAborted(false)}}+ }+ defaultPre := p.defaultPre+ if defaultPre == nil {+ defaultPre = func(context.Context) (PreToolDecision, error) { return PreToolDecision{Kind: "allow"}, nil }+ }+ decision, err := defaultPre(p.ctx)+ if err != nil {+ return ToolPreparation{Outcome: ToolDispatchOutcome{Result: pipelineFailure(err)}}+ }+ if decision.Kind == "ask" {+ decision, err = p.resolveAsk(decision)+ if err != nil {+ return ToolPreparation{Outcome: ToolDispatchOutcome{Result: pipelineFailure(err)}}+ }+ }+ switch decision.Kind {+ case "allow":+ case "deny":+ return ToolPreparation{Outcome: ToolDispatchOutcome{Result: pipelineDenial(decision.Reason, decision.Info), NeedsPost: true}}+ case "cancel":+ return ToolPreparation{Outcome: ToolDispatchOutcome{Result: pipelineAborted(false), NeedsPost: true}}+ default:+ return ToolPreparation{Outcome: ToolDispatchOutcome{Result: pipelineFailure(fmt.Errorf("invalid pre-execute decision %q", decision.Kind))}}+ }+ if p.ctx.Err() != nil {+ return ToolPreparation{Outcome: ToolDispatchOutcome{Result: pipelineAborted(false), NeedsPost: true}}+ }+ return ToolPreparation{Dispatch: true}+}++func (p *ToolInvocation) resolveAsk(ask PreToolDecision) (PreToolDecision, error) {+ if p.approve == nil || p.execution.SessionID == "" {+ return PreToolDecision{Kind: "deny", Reason: "tool requires approval, but no approval channel is available", Info: &ToolPipelineErrorInfo{Name: "ApprovalError", Code: "APPROVAL_UNAVAILABLE"}}, nil+ }+ err := p.approve(p.ctx, ToolPolicyAsk{Reason: ask.Reason, DisplayReason: ask.DisplayReason})+ if err == nil {+ return PreToolDecision{Kind: "allow"}, nil+ }+ var info interface{ ToolErrorInfo() (string, string) }+ if errors.As(err, &info) {+ _, code := info.ToolErrorInfo()+ if code == "APPROVAL_CANCELLED" && p.ctx.Err() != nil {+ return PreToolDecision{Kind: "cancel"}, nil+ }+ if code == "APPROVAL_REJECTED" || code == "APPROVAL_CANCELLED" || code == "APPROVAL_UNAVAILABLE" {+ return PreToolDecision{Kind: "deny", Reason: err.Error(), Info: &ToolPipelineErrorInfo{Name: "ApprovalError", Code: code}}, nil+ }+ }+ return PreToolDecision{}, err+}++func (p *ToolInvocation) Dispatch() (outcome ToolDispatchOutcome) {+ defer func() {+ if value := recover(); value != nil {+ outcome = ToolDispatchOutcome{Result: pipelineFailure(fmt.Errorf("tool dispatch panicked: %v", value))}+ }+ }()+ // A recorded invocation has exactly one dispatch; no middleware can+ // suppress, replay or replace the selected tool body.+ if !p.dispatched.CompareAndSwap(false, true) {+ return ToolDispatchOutcome{Result: pipelineFailure(errors.New("tool was already dispatched"))}+ }+ if p.ctx.Err() != nil {+ return ToolDispatchOutcome{Result: pipelineAborted(false), NeedsPost: true}+ }+ callCtx := p.ctx+ if p.trackBody {+ callCtx = context.WithValue(callCtx, toolBodyStartedKey{}, &p.started)+ } else {+ p.started.Store(true)+ }+ result, err := p.dispatchBody(callCtx)+ if err != nil {+ if p.ctx.Err() != nil && (errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)) {+ result = pipelineAborted(p.started.Load())+ } else {+ result = pipelineFailure(err)+ }+ }+ if p.hooks.Normalize != nil {+ result, err = p.hooks.Normalize(p.ctx, clonePipelineResult(result))+ if err != nil {+ return ToolDispatchOutcome{Result: pipelineFailure(err)}+ }+ }+ if p.ctx.Err() != nil && !result.IsError {+ result = abortedWithPresentation(result, p.started.Load())+ }+ return ToolDispatchOutcome{Result: result, NeedsPost: true}+}++func (p *ToolInvocation) Complete(outcome ToolDispatchOutcome) (result ToolPipelineResult) {+ result = outcome.Result+ defer func() {+ if value := recover(); value != nil {+ result = p.finish(pipelineFailure(fmt.Errorf("tool completion panicked: %v", value)))+ }+ }()+ if !outcome.NeedsPost {+ return p.finish(result)+ }+ if p.hooks.Project != nil {+ content, err := p.hooks.Project(p.ctx, clonePipelineResult(result))+ if err != nil {+ return p.finish(pipelineFailure(err))+ }+ if content != nil {+ result.Content = content+ }+ }+ if p.hooks.PostExecute != nil {+ decision, err := p.hooks.PostExecute(p.ctx, clonePipelineResult(result))+ if err != nil {+ return p.finish(pipelineFailure(err))+ }+ result, err = p.applyPost(result, decision)+ if err != nil {+ return p.finish(pipelineFailure(err))+ }+ }+ if p.ctx.Err() != nil && !result.IsError {+ result = abortedWithPresentation(result, p.started.Load())+ }+ return p.finish(result)+}++func (p *ToolInvocation) applyPost(result ToolPipelineResult, decision PostToolDecision) (ToolPipelineResult, error) {+ switch decision.Kind {+ case "block":+ message := "tool result blocked by post-execute policy"+ var feedback []string+ for _, raw := range decision.Feedback {+ var block struct{ Type, Text string }+ if err := json.Unmarshal(raw, &block); err != nil {+ return ToolPipelineResult{}, err+ }+ if block.Type == "text" {+ feedback = append(feedback, block.Text)+ } else {+ feedback = append(feedback, "["+block.Type+" content]")+ }+ }+ if text := strings.Join(feedback, "\n"); text != "" {+ message = text+ }+ return ToolPipelineResult{IsError: true, Content: decision.Feedback, Error: &ToolPipelineError{Message: message, Info: decision.Info}, AdditionalContexts: decision.AdditionalContexts}, nil+ case "accept":+ if decision.Value != nil && decision.Content != nil {+ return ToolPipelineResult{}, errors.New("tools/post-execute accept decision cannot replace both value and content")+ }+ contexts := append(append([]json.RawMessage(nil), result.AdditionalContexts...), decision.AdditionalContexts...)+ if decision.Value != nil {+ if result.IsError {+ return ToolPipelineResult{}, errors.New("tools/post-execute cannot replace the value of a failed result")+ }+ if p.hooks.ReplaceValue == nil {+ return ToolPipelineResult{}, errors.New("tool output renderer is unavailable")+ }+ var err error+ result, err = p.hooks.ReplaceValue(p.ctx, decision.Value)+ if err != nil {+ return ToolPipelineResult{}, err+ }+ } else if decision.Content != nil {+ result.Content = decision.Content+ }+ result.AdditionalContexts = contexts+ return result, nil+ default:+ return ToolPipelineResult{}, fmt.Errorf("invalid post-execute decision %q", decision.Kind)+ }+}++func (p *ToolInvocation) finish(candidate ToolPipelineResult) (result ToolPipelineResult) {+ result, err := materializePipelineResult(candidate)+ if err != nil {+ result = pipelineFailure(err)+ }+ if p.hooks.Finalize != nil {+ func() {+ defer func() {+ if value := recover(); value != nil {+ result = pipelineFailure(fmt.Errorf("tool finalizer panicked: %v", value))+ }+ }()+ content, finalizeErr := p.hooks.Finalize(p.ctx, clonePipelineResult(result))+ if finalizeErr != nil {+ result = pipelineFailure(finalizeErr)+ } else if content != nil {+ result.Content = content+ }+ }()+ }+ if materialized, err := materializePipelineResult(result); err != nil {+ result = pipelineFailure(err)+ } else {+ result = materialized+ }+ return result+}++func (p *ToolInvocation) dispatchBody(ctx context.Context) (result ToolPipelineResult, err error) {+ defer func() {+ if value := recover(); value != nil {+ result, err = pipelineFailure(fmt.Errorf("tool body panicked: %v", value)), nil+ }+ }()+ if p.body == nil {+ return ToolPipelineResult{}, errors.New("tool body is unavailable")+ }+ return p.body(ctx)+}++func materializePipelineResult(result ToolPipelineResult) (ToolPipelineResult, error) {+ if result.IsError {+ if result.Error == nil {+ return ToolPipelineResult{}, errors.New("failed tool result lacks an error")+ }+ result.Value, result.ConcludesTurn = nil, false+ } else if !json.Valid(result.Value) {+ return ToolPipelineResult{}, errors.New("successful tool result lacks a JSON value")+ }+ if result.Content == nil {+ result.Content = []json.RawMessage{}+ }+ data, err := json.Marshal(result)+ if err != nil {+ return ToolPipelineResult{}, err+ }+ var detached ToolPipelineResult+ err = json.Unmarshal(data, &detached)+ return detached, err+}++func clonePipelineResult(result ToolPipelineResult) ToolPipelineResult {+ // Invalid values are retained for the owning stage to diagnose rather than+ // accidentally converted to a valid empty result by a failed clone.+ data, err := json.Marshal(result)+ if err != nil {+ return result+ }+ var detached ToolPipelineResult+ if json.Unmarshal(data, &detached) != nil {+ return result+ }+ return detached+}++func pipelineFailure(err error) ToolPipelineResult {+ result := pipelineDenial(err.Error(), nil)+ var info interface{ ToolErrorInfo() (string, string) }+ if errors.As(err, &info) {+ name, code := info.ToolErrorInfo()+ if code != "" {+ result.Error.Info = &ToolPipelineErrorInfo{Name: name, Code: code}+ }+ }+ return result+}++func pipelineDenial(reason string, info *ToolPipelineErrorInfo) ToolPipelineResult {+ block, _ := json.Marshal(map[string]string{"type": "text", "text": "Error: " + reason})+ return ToolPipelineResult{IsError: true, Content: []json.RawMessage{block}, Error: &ToolPipelineError{Message: reason, Info: info}}+}++func pipelineAborted(started bool) ToolPipelineResult {+ message, code := "tool call aborted before dispatch", "ABORTED_BEFORE_DISPATCH"+ if started {+ message, code = "tool call aborted", "ABORTED"+ }+ return pipelineDenial(message, &ToolPipelineErrorInfo{Name: "AbortError", Code: code})+}++func abortedWithPresentation(result ToolPipelineResult, started bool) ToolPipelineResult {+ aborted := pipelineAborted(started)+ aborted.AdditionalContexts = result.AdditionalContexts+ return aborted+}++// Native dispatch includes argument validation before the selected business+// function. Its body marker is set only after that validation succeeds.+type toolBodyStartedKey struct{}++func markToolBodyStarted(ctx context.Context) {+ if started, ok := ctx.Value(toolBodyStartedKey{}).(*atomic.Bool); ok {+ started.Store(true)+ }+}diff --git a/harness/agent/tool_pipeline_codec.go b/harness/agent/tool_pipeline_codec.gonew file mode 100644index 0000000..33689e8--- /dev/null+++ b/harness/agent/tool_pipeline_codec.go@@ -0,0 +1,124 @@+package agent++import (+ "encoding/json"+ "fmt"+ "go-bot/harness/content"+ "go-bot/internal/modeldata"+ "strings"+)++func pipelineCodecFailure(code, message string) error { return fmt.Errorf("%s: %s", code, message) }+func EncodeToolPipelineResult(result modeldata.ToolResult) (ToolPipelineResult, error) {+ output := ToolPipelineResult{IsError: result.IsError, Meta: result.Meta, AdditionalContexts: result.AdditionalContexts, ConcludesTurn: result.ConcludeTurn, Content: []json.RawMessage{}}+ if result.IsError {+ output.Error = &ToolPipelineError{Message: strings.TrimPrefix(result.Content, "Error: ")}+ if output.Error.Message == "" {+ var text []string+ for _, block := range result.ContentBlocks {+ if block.Type == "text" {+ text = append(text, block.Text)+ }+ }+ output.Error.Message = strings.TrimPrefix(strings.Join(text, "\n"), "Error: ")+ }+ if result.Code != "" {+ output.Error.Info = &ToolPipelineErrorInfo{Name: result.ErrorName, Code: result.Code, Reason: result.ErrorReason}+ if output.Error.Info.Name == "" {+ output.Error.Info.Name = "Error"+ if result.Code == "TOOL_TIMEOUT" {+ output.Error.Info.Name = "ToolTimeoutError"+ }+ }+ }+ } else {+ output.Value, _ = json.Marshal(result.Content)+ var meta struct {+ CanonicalValue json.RawMessage `json:"canonicalValue"`+ }+ if json.Unmarshal(result.Meta, &meta) == nil && json.Valid(meta.CanonicalValue) {+ output.Value = meta.CanonicalValue+ }+ }+ blocks := append([]content.ContentBlock(nil), result.ContentBlocks...)+ if result.Content != "" {+ blocks = append([]content.ContentBlock{{Type: "text", Text: result.Content}}, blocks...)+ }+ for _, block := range blocks {+ var value any+ switch block.Type {+ case "text":+ value = map[string]any{"type": "text", "text": block.Text}+ case "image":+ attachment := map[string]any{"attachmentId": block.ImageRefID, "mediaType": block.MIMEType, "bytes": block.Bytes, "width": block.Width, "height": block.Height}+ if block.Name != "" {+ attachment["name"] = block.Name+ }+ if block.OriginalDimensions != nil {+ attachment["originalDimensions"] = block.OriginalDimensions+ }+ value = map[string]any{"type": "image", "attachment": attachment}+ default:+ return ToolPipelineResult{}, pipelineCodecFailure("INVALID_RESULT", "Unsupported tool policy content type")+ }+ data, err := json.Marshal(value)+ if err != nil {+ return ToolPipelineResult{}, err+ }+ output.Content = append(output.Content, data)+ }+ return output, nil+}++func DecodeToolPipelineResult(output ToolPipelineResult) (modeldata.ToolResult, error) {+ result := modeldata.ToolResult{IsError: output.IsError, Meta: output.Meta, AdditionalContexts: output.AdditionalContexts, ConcludeTurn: output.ConcludesTurn}+ if output.IsError {+ if output.Error == nil {+ return result, pipelineCodecFailure("INVALID_RESULT", "Failed tool policy result lacks an error")+ }+ if output.Error.Info != nil {+ result.ErrorName, result.Code = output.Error.Info.Name, output.Error.Info.Code+ result.ErrorReason = output.Error.Info.Reason+ }+ } else if !json.Valid(output.Value) {+ return result, pipelineCodecFailure("INVALID_RESULT", "Successful tool policy result lacks a value")+ }+ for _, raw := range output.Content {+ var block struct {+ Type string `json:"type"`+ Text string `json:"text"`+ Attachment struct {+ ID string `json:"attachmentId"`+ MIMEType string `json:"mediaType"`+ Bytes int64 `json:"bytes"`+ Width int `json:"width"`+ Height int `json:"height"`+ Name string `json:"name"`+ OriginalDimensions *content.ImageDimensions `json:"originalDimensions"`+ } `json:"attachment"`+ }+ if err := json.Unmarshal(raw, &block); err != nil {+ return result, err+ }+ switch block.Type {+ case "text":+ if block.Text != "" {+ result.ContentBlocks = append(result.ContentBlocks, content.ContentBlock{Type: "text", Text: block.Text})+ }+ case "image":+ a := block.Attachment+ result.ContentBlocks = append(result.ContentBlocks, content.ImageBlock(content.ImageAttachment{ID: a.ID, MIMEType: a.MIMEType, Bytes: a.Bytes, Width: a.Width, Height: a.Height, Name: a.Name, OriginalDimensions: a.OriginalDimensions}))+ default:+ return result, pipelineCodecFailure("INVALID_RESULT", "Unsupported tool policy content type: "+block.Type)+ }+ }+ if err := content.ValidateDurableContentBlocks(result.ContentBlocks); err != nil {+ return result, err+ }+ // Retain the single-text legacy projection without duplicating model text.+ if len(result.ContentBlocks) == 1 && result.ContentBlocks[0].Type == "text" {+ result.Content = result.ContentBlocks[0].Text+ result.ContentBlocks = nil+ }+ return result, nil+}diff --git a/harness/agent/tool_pipeline_test.go b/harness/agent/tool_pipeline_test.gonew file mode 100644index 0000000..536af3c--- /dev/null+++ b/harness/agent/tool_pipeline_test.go@@ -0,0 +1,150 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "reflect"+ "testing"+)++func pipelineText(text string) []json.RawMessage {+ block, _ := json.Marshal(map[string]string{"type": "text", "text": text})+ return []json.RawMessage{block}+}+func pipelineSuccess(text string) ToolPipelineResult {+ value, _ := json.Marshal(text)+ return ToolPipelineResult{Value: value, Content: pipelineText(text)}+}+func runToolInvocation(p *ToolInvocation) ToolPipelineResult {+ prepared := p.Prepare()+ outcome := prepared.Outcome+ if prepared.Dispatch {+ outcome = p.Dispatch()+ }+ return p.Complete(outcome)+}++func TestGoToolPipelineOwnsApprovalAndSettlementOrder(t *testing.T) {+ var trace []string+ processors := ToolPipelineProcessors{+ Project: func(context.Context, ToolPipelineResult) ([]json.RawMessage, error) {+ trace = append(trace, "project")+ return pipelineText("projected"), nil+ },+ PostExecute: func(_ context.Context, result ToolPipelineResult) (PostToolDecision, error) {+ trace = append(trace, "post")+ if string(result.Content[0]) != string(pipelineText("projected")[0]) {+ t.Error("post lost projected content")+ }+ return PostToolDecision{Kind: "accept", Content: pipelineText("accepted")}, nil+ },+ Finalize: func(_ context.Context, result ToolPipelineResult) ([]json.RawMessage, error) {+ trace = append(trace, "finalize")+ if string(result.Content[0]) != string(pipelineText("accepted")[0]) {+ t.Error("finalizer lost accepted content")+ }+ return nil, nil+ },+ }+ p := NewToolInvocation(t.Context(), ToolExecution{SessionID: "session"}, processors,+ func(context.Context) (ToolPipelineResult, error) {+ trace = append(trace, "body")+ return pipelineSuccess("raw"), nil+ },+ func(_ context.Context, ask ToolPolicyAsk) error {+ trace = append(trace, "approval")+ if ask.Reason != "confirm" {+ t.Error("reason lost")+ }+ return nil+ })+ p.SetPreExecutePolicy(func(context.Context) (PreToolDecision, error) {+ trace = append(trace, "pre")+ return PreToolDecision{Kind: "ask", Reason: "confirm"}, nil+ })+ result := runToolInvocation(p)+ if want := []string{"pre", "approval", "body", "project", "post", "finalize"}; !reflect.DeepEqual(trace, want) || result.IsError {+ t.Fatalf("trace=%v result=%+v", trace, result)+ }+ if second := p.Dispatch(); !second.Result.IsError {+ t.Fatal("a recorded body was dispatched twice")+ }+}++func TestGoToolPipelineKeepsFailureBranchPostSemantics(t *testing.T) {+ for _, where := range []string{"pre-denial", "pre-exception", "invalid-decision", "body-error", "body-panic", "cancel-before-prepare"} {+ t.Run(where, func(t *testing.T) {+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ post, finalized, bodies := 0, 0, 0+ p := NewToolInvocation(ctx, ToolExecution{}, ToolPipelineProcessors{+ PostExecute: func(context.Context, ToolPipelineResult) (PostToolDecision, error) {+ post+++ return PostToolDecision{Kind: "accept"}, nil+ },+ Finalize: func(context.Context, ToolPipelineResult) ([]json.RawMessage, error) { finalized++; return nil, nil },+ }, func(context.Context) (ToolPipelineResult, error) {+ bodies+++ if where == "body-panic" {+ panic("body failed")+ }+ return ToolPipelineResult{}, errors.New("body failed")+ }, nil)+ p.SetPreExecutePolicy(func(context.Context) (PreToolDecision, error) {+ switch where {+ case "pre-denial":+ return PreToolDecision{Kind: "deny", Reason: "denied"}, nil+ case "pre-exception":+ return PreToolDecision{}, errors.New("policy failed")+ case "invalid-decision":+ return PreToolDecision{Kind: "unexpected"}, nil+ }+ return PreToolDecision{Kind: "allow"}, nil+ })+ if where == "cancel-before-prepare" {+ cancel()+ }+ result := runToolInvocation(p)+ wantPost, wantBodies := 0, 0+ if where == "pre-denial" || where == "body-error" || where == "body-panic" {+ wantPost = 1+ }+ if where == "body-error" || where == "body-panic" {+ wantBodies = 1+ }+ if !result.IsError || post != wantPost || finalized != 1 || bodies != wantBodies {+ t.Fatalf("result=%+v post=%d final=%d bodies=%d", result, post, finalized, bodies)+ }+ })+ }+}++func TestGoToolPipelineBlockDiscardsToolContextsAndConcludeTurn(t *testing.T) {+ contextJSON := json.RawMessage(`{"id":"policy-context","role":"user","content":[]}`)+ result := runToolInvocation(NewToolInvocation(t.Context(), ToolExecution{}, ToolPipelineProcessors{+ PostExecute: func(context.Context, ToolPipelineResult) (PostToolDecision, error) {+ return PostToolDecision{Kind: "block", Feedback: pipelineText("redacted"), AdditionalContexts: []json.RawMessage{contextJSON}}, nil+ },+ }, func(context.Context) (ToolPipelineResult, error) {+ result := pipelineSuccess("private")+ result.ConcludesTurn = true+ result.AdditionalContexts = []json.RawMessage{json.RawMessage(`{"id":"tool-context"}`)}+ return result, nil+ }, nil))+ if !result.IsError || result.ConcludesTurn || len(result.AdditionalContexts) != 1 || string(result.AdditionalContexts[0]) != string(contextJSON) {+ t.Fatalf("blocked=%+v", result)+ }+}++func TestGoToolPipelineAskWithoutApprovalChannelNeverDispatches(t *testing.T) {+ p := NewToolInvocation(t.Context(), ToolExecution{SessionID: "s"}, ToolPipelineProcessors{}, func(context.Context) (ToolPipelineResult, error) {+ t.Fatal("unavailable approval dispatched")+ return ToolPipelineResult{}, nil+ }, nil)+ p.SetPreExecutePolicy(func(context.Context) (PreToolDecision, error) { return PreToolDecision{Kind: "ask"}, nil })+ result := runToolInvocation(p)+ if !result.IsError || result.Error.Info.Code != "APPROVAL_UNAVAILABLE" {+ t.Fatalf("result=%+v", result)+ }+}diff --git a/harness/assembly/native_creation.go b/harness/assembly/native_creation.gonew file mode 100644index 0000000..d14d30e--- /dev/null+++ b/harness/assembly/native_creation.go@@ -0,0 +1,120 @@+package assembly++import (+ "context"+ "encoding/json"+ "errors"+ "path/filepath"+ "time"++ "go-bot/harness/permission"+ "go-bot/harness/session"+)++// NativeSessionMeta mirrors the creation-only metadata accepted by upstream's+// Agent factory. createdAt is deliberately absent: the factory owns that clock.+type NativeSessionMeta struct {+ CWD *string `json:"cwd,omitempty"`+ ParentSession *string `json:"parentSession,omitempty"`+ IsSeeded *bool `json:"isSeeded,omitempty"`+ Origin *string `json:"origin,omitempty"`+ DelegationDepth *int `json:"delegationDepth,omitempty"`+ AgentPreset *string `json:"agentPreset,omitempty"`+}++type NativeParentSource struct {+ SessionID string `json:"sessionId"`+ EndSeq uint64 `json:"endSeq"`+}++// Session inputs only. Runtime Agent options, owner/setup callbacks and their+// publication commit are separate capabilities, not serialized Session data.+type NativeSessionOptions struct {+ Meta *NativeSessionMeta `json:"meta,omitempty"`+ Seed []sessionformat.Event `json:"seed"`+ InheritedEventCount *uint64 `json:"inheritedEventCount,omitempty"`+ ParentSource *NativeParentSource `json:"parentSource,omitempty"`+}++func (options NativeSessionOptions) Snapshot() (NativeSessionOptions, error) {+ data, err := json.Marshal(options)+ if err != nil {+ return NativeSessionOptions{}, err+ }+ var detached NativeSessionOptions+ err = json.Unmarshal(data, &detached)+ return detached, err+}++func (f NativeFactory) ActivateWithSessionOptions(ctx context.Context, identity NativeRuntimeIdentity, options NativeSessionOptions) (*NativeLive, error) {+ header := sessionformat.Header{Type: "session", Version: sessionformat.Version, ID: identity.SessionID, CreatedAt: time.Now().UnixMilli(), CWD: nativeCWD(identity), AgentPreset: identity.AgentPreset}+ if meta := options.Meta; meta != nil {+ if meta.CWD != nil {+ if !filepath.IsAbs(*meta.CWD) {+ return nil, errors.New("Session cwd must be absolute")+ }+ identity.CWD = *meta.CWD+ header.CWD = *meta.CWD+ }+ if meta.ParentSession != nil {+ header.ParentSession = *meta.ParentSession+ }+ if meta.IsSeeded != nil {+ header.IsSeeded = *meta.IsSeeded+ }+ if meta.Origin != nil {+ if *meta.Origin != "subagent" {+ return nil, errors.New("Session origin must be subagent")+ }+ header.Origin = *meta.Origin+ }+ if meta.DelegationDepth != nil {+ header.DelegationDepth = *meta.DelegationDepth+ }+ if meta.AgentPreset != nil {+ header.AgentPreset = *meta.AgentPreset+ identity.AgentPreset = *meta.AgentPreset+ }+ }+ if err := f.validate(identity); err != nil {+ return nil, err+ }+ prepared, err := sessionformat.PrepareSession(header, options.Seed, options.InheritedEventCount)+ if err != nil {+ return nil, err+ }+ events := prepared.Events()+ // Like upstream's copying JSONL backend, storage receives the full+ // constructor history. ParentSource's identity/cut are sharing hints; no+ // parent lookup or live-parent claim is needed to copy this snapshot.+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ var journal sessionformat.EventJournal+ storedCount := 0+ if storage, ok := f.Storage.(NativePreparedStorage); ok {+ journal, err = storage.CreatePreparedNative(ctx, prepared.Header(), events)+ storedCount = len(events)+ } else {+ journal, err = f.Storage.CreateNative(ctx, prepared.Header())+ }+ if err != nil {+ return nil, err+ }+ s, err := prepared.Attach(journal, storedCount)+ if err != nil {+ return nil, errors.Join(err, journal.Close())+ }+ // Store the constructor's complete history before Session entry/observers.+ if err := s.Flush(ctx); err != nil {+ return nil, errors.Join(err, s.Close())+ }+ return f.publishSession(ctx, identity, s, "activation", nil, func() error {+ for _, event := range s.Events() {+ if event.Type == "permission/preset" || event.Type == "sandbox/mode" || event.Type == "approval/policy" {+ return nil+ }+ }+ return permission.Save(ctx, s, permission.FullAccess, false, true)+ })+}diff --git a/harness/assembly/native_runtime.go b/harness/assembly/native_runtime.goindex 447a07d..d111c58 100644--- a/harness/assembly/native_runtime.go+++ b/harness/assembly/native_runtime.go@@ -46,52 +46,80 @@ type NativeChildStorageFactory interface {ChildNativeStorage(string) (NativeStorage, error)}+type NativePreparedStorage interface {+ CreatePreparedNative(context.Context, sessionformat.Header, []sessionformat.Event) (sessionformat.EventJournal, error)+}+type NativeBuilder interface {BuildNative(context.Context, NativeRuntimeIdentity, string) (Resources, error)}+// NativeExtensionScope is owned by one live Agent, including a fork or+// restored Agent. It is not persisted or shared by session ID.+type NativeExtensionScope interface {+ Tools(context.Context, string) ([]agent.Tool, error)+ Context(context.Context, string) ([]agent.RuntimeContextSection, error)+ Close()+}+// NativeFactory assembles one v4 Session and Agent inside the user Host.type NativeFactory struct {- Storage NativeStorage- Builder NativeBuilder- Model agent.Model- ResolveTurnModel func(context.Context) (agent.TurnModel, error)- Provider string- ModelID string- ReasoningEffort string- SystemPrompt string- Limits agent.Limits- Children tools.ChildCoordinator- Schedule *schedule.Service- FileAttachments attachments.FileStore- Memory *memory.Store- SessionSearch *sessionsearch.Index+ Storage NativeStorage+ Builder NativeBuilder+ Model agent.Model+ ResolveTurnModel func(context.Context) (agent.TurnModel, error)+ ResolveSelectedModel agent.ModelSelectionResolver+ ToolSource agent.ToolSource+ ToolInvocationSource agent.ToolInvocationSource+ ContextSource func(context.Context, string) ([]agent.RuntimeContextSection, error)+ SystemContextSource func(context.Context, string) ([]agent.RuntimeContextSection, error)+ ExtensionScope func() NativeExtensionScope+ PromptSource agent.PromptAssemblySource+ // BeforePublish composes the real, unpublished Go Agent. It runs before+ // extension binding and before any driver starts; a failure closes the+ // prepared resources while retaining already committed Session facts.+ SessionReady func(*sessionformat.LiveSession)+ BeforePublish func(context.Context, *NativeLive) error+ Provider string+ ModelID string+ ReasoningEffort string+ SystemPrompt string+ Limits agent.Limits+ Children tools.ChildCoordinator+ Schedule *schedule.Service+ FileAttachments attachments.FileStore+ Memory *memory.Store+ SessionSearch *sessionsearch.Index// WorkflowSchema is an activation-only child contract. It is not persisted// and must not leak into ordinary or resumed child Sessions.WorkflowSchema map[string]any- // ToolApproval may request an explicit pre-dispatch decision for a tool.- // An empty request lets normal execution proceed.- ToolApproval func(context.Context, string, json.RawMessage) *permission.Request+ // ToolPreExecutePolicy is the Go-owned execution policy. Business plugins+ // cannot wrap it or register global execution middleware.+ ToolPreExecutePolicy agent.NativePreToolPolicy}type NativeLive struct {- Agent *agent.NativeLoop- Session *sessionformat.LiveSession- Goals *goal.NativeService- Plan *plan.NativeService- Questions *interaction.NativeQuestions- Resource Resources- Structured *tools.NativeStructuredOutput- closeMu sync.Once- closeErr error+ Agent *agent.NativeLoop+ Session *sessionformat.LiveSession+ Goals *goal.NativeService+ Plan *plan.NativeService+ Questions *interaction.NativeQuestions+ Resource Resources+ Structured *tools.NativeStructuredOutput+ closeMu sync.Once+ closeErr error+ extensionScope NativeExtensionScope}func (l *NativeLive) Close() error {l.closeMu.Do(func() {+ if l.extensionScope != nil {+ l.extensionScope.Close()+ }if l.Questions != nil {l.Questions.Close()}- l.closeErr = errors.Join(l.Session.Close(), l.Resource.close())+ l.closeErr = errors.Join(l.closeErr, l.Session.Close(), l.Resource.close())})return l.closeErr}@@ -123,27 +151,7 @@ func nativeCWD(identity NativeRuntimeIdentity) string {}func (f NativeFactory) Activate(ctx context.Context, identity NativeRuntimeIdentity) (*NativeLive, error) {- if err := f.validate(identity); err != nil {- return nil, err- }- header := sessionformat.Header{- Type: "session", Version: sessionformat.Version,- ID: identity.SessionID, CreatedAt: time.Now().UTC().UnixMilli(), CWD: nativeCWD(identity), AgentPreset: identity.AgentPreset,- }- journal, err := f.Storage.CreateNative(ctx, header)- if err != nil {- return nil, err- }- s, err := sessionformat.NewLiveSession(header, journal)- if err != nil {- _ = journal.Close()- return nil, err- }- if err := permission.Save(ctx, s, permission.FullAccess, false, true); err != nil {- _ = s.Close()- return nil, err- }- return f.publish(ctx, identity, s, "activation", nil)+ return f.ActivateWithSessionOptions(ctx, identity, NativeSessionOptions{})}func (f NativeFactory) Resume(ctx context.Context, identity NativeRuntimeIdentity) (*NativeLive, error) {@@ -154,7 +162,7 @@ func (f NativeFactory) Resume(ctx context.Context, identity NativeRuntimeIdentitif err != nil {return nil, err}- if artifact.Header.ID != identity.SessionID || artifact.Header.CWD != nativeCWD(identity) || artifact.Header.Origin == "subagent" {+ if artifact.Header.ID != identity.SessionID || artifact.Header.CWD != nativeCWD(identity) {_ = journal.Close()return nil, errors.New("native Session header differs from its worker identity")}@@ -167,7 +175,7 @@ func (f NativeFactory) Resume(ctx context.Context, identity NativeRuntimeIdentit_ = s.Close()return nil, err}- return f.publish(ctx, identity, s, "resume", nil)+ return f.publishSession(ctx, identity, s, "resume", nil, nil)}// ActivateChild creates a separate child Session inside the same Host. It has@@ -263,26 +271,25 @@ func (f NativeFactory) activateChild(ctx context.Context, root NativeRuntimeIden_ = journal.Close()return nil, err}- if err := permission.Save(ctx, s, permission.Read(parent.Session.Events()).Mode, true, true); err != nil {- _ = s.Close()- return nil, err- }- if identity.CWD != header.CWD {- data, err := json.Marshal(struct {- CWD string `json:"cwd"`- }{CWD: identity.CWD})- if err != nil {- _ = s.Close()- return nil, err+ initialize := func() error {+ if err := permission.Save(ctx, s, permission.Read(parent.Session.Events()).Mode, true, true); err != nil {+ return err}- if _, err := s.Append(sessionformat.EventInput{Type: "working-directory/change", Data: data}); err != nil {- _ = s.Close()- return nil, err- }- if err := s.Flush(ctx); err != nil {- _ = s.Close()- return nil, err+ if identity.CWD != header.CWD {+ data, err := json.Marshal(struct {+ CWD string `json:"cwd"`+ }{CWD: identity.CWD})+ if err != nil {+ return err+ }+ if _, err := s.Append(sessionformat.EventInput{Type: "working-directory/change", Data: data}); err != nil {+ return err+ }+ if err := s.Flush(ctx); err != nil {+ return err+ }}+ return nil}descriptor := &sessionformat.SubagentDescriptor{Version: 3, Mode: "continuable", Provider: "native", Label: &label,@@ -291,7 +298,7 @@ func (f NativeFactory) activateChild(ctx context.Context, root NativeRuntimeIdenif f.ReasoningEffort != "" {descriptor.AgentReasoningEffort = &f.ReasoningEffort}- return childFactory.publish(ctx, identity, s, "activation", descriptor)+ return childFactory.publishSession(ctx, identity, s, "activation", descriptor, initialize)}// ResumeChild reopens only a v4 child already cataloged by its live direct@@ -352,7 +359,23 @@ func (f NativeFactory) ResumeChild(ctx context.Context, root NativeRuntimeIdenti_ = s.Close()return nil, err}- return childFactory.publish(ctx, identity, s, "resume", nil)+ return childFactory.publishSession(ctx, identity, s, "resume", nil, nil)+}++func (f NativeFactory) publishSession(ctx context.Context, identity NativeRuntimeIdentity, s *sessionformat.LiveSession, reason string, descriptor *sessionformat.SubagentDescriptor, initialize func() error) (_ *NativeLive, resultErr error) {+ if f.SessionReady != nil {+ f.SessionReady(s)+ }+ if initialize != nil {+ if err := initialize(); err != nil {+ return nil, errors.Join(err, s.Close())+ }+ }+ live, err := f.publish(ctx, identity, s, reason, descriptor)+ if err != nil {+ return nil, err+ }+ return live, nil}// DeepSeek keeps the original project cwd in the immutable Session header;@@ -391,7 +414,7 @@ func (f NativeFactory) publish(ctx context.Context, identity NativeRuntimeIdentireturn nil, err}skillLookup := func() skills.Lookup {- return skills.Lookup{CWD: nativeSessionCWD(s.Header().CWD, s.Events()), Workspace: identity.Workspace}+ return skills.Lookup{CWD: nativeSessionCWD(s.Header().CWD, s.Events()), Workspace: identity.Workspace, SessionID: s.Header().ID}}skillTool := &tools.Skill{Registry: resource.Skills, Lookup: skillLookup}toolset = append(toolset, skillTool, tools.Present{@@ -506,7 +529,14 @@ func (f NativeFactory) publish(ctx context.Context, identity NativeRuntimeIdentireturn nil, fmt.Errorf("assemble native Agent loop: %w", err)}loop.SetReasoningEffort(f.ReasoningEffort)+ loop.SetSandboxModeSource(func() string { return string(permissionState().Mode) })loop.SetTurnModelResolver(f.ResolveTurnModel)+ loop.SetModelSelectionResolver(f.ResolveSelectedModel)+ loop.SetToolSource(f.ToolSource)+ loop.SetToolInvocationSource(f.ToolInvocationSource)+ loop.SetToolQuestions(questions)+ loop.SetRuntimeContextSource(f.ContextSource)+ loop.SetPromptAssembler(f.PromptSource)// The clock is standard-preset context for every Agent, including a child;// only the four Schedule management tools are root-only.if f.Schedule != nil {@@ -558,17 +588,17 @@ func (f NativeFactory) publish(ctx context.Context, identity NativeRuntimeIdenti})}- if f.ToolApproval != nil {- loop.SetToolApproval(func(ctx context.Context, name string, args json.RawMessage) error {- request := f.ToolApproval(ctx, name, args)- if request == nil {- return nil- }- action := *request- action.Tool = name- return approval.Request(ctx, action)- })- }+ loop.SetToolPolicyApprover(func(ctx context.Context, execution agent.ToolExecution, ask agent.ToolPolicyAsk) error {+ reason := ask.Reason+ if reason == "" {+ reason = ask.DisplayReason["en"]+ }+ if reason == "" {+ reason = "This tool requires approval before executing."+ }+ return approval.Request(ctx, permission.Request{Tool: execution.Name, Reason: reason, Detail: string(execution.Arguments)})+ })+ loop.SetToolPreExecutePolicy(f.ToolPreExecutePolicy)loop.SetSkillCatalogProvider(skillTool, func(stepCtx context.Context) (agent.NativeSkillCatalogSnapshot, error) {discovery, err := resource.Skills.Snapshot(stepCtx, skillLookup())@@ -645,5 +675,47 @@ func (f NativeFactory) publish(ctx context.Context, identity NativeRuntimeIdentiloop.SetFilePathResolver(func(ref agent.NativeFileAttachmentRef) string {return f.FileAttachments.Path(attachments.FileRef{ID: ref.ID, Name: ref.Name, Bytes: ref.Bytes})})- return &NativeLive{Agent: loop, Session: s, Goals: goals, Plan: plans, Questions: questions, Resource: resource, Structured: structured}, nil+ var scope NativeExtensionScope+ if f.ExtensionScope != nil {+ scope = f.ExtensionScope()+ }+ loop.SetSystemContextSource(func(ctx context.Context, sid string) ([]agent.RuntimeContextSection, error) {+ var sections []agent.RuntimeContextSection+ if f.SystemContextSource != nil {+ rows, err := f.SystemContextSource(ctx, sid)+ if err != nil {+ return nil, err+ }+ sections = append(sections, rows...)+ }+ if scope != nil {+ rows, err := scope.Context(ctx, sid)+ if err != nil {+ return nil, err+ }+ sections = append(sections, rows...)+ }+ return sections, nil+ })+ if scope != nil {+ loop.SetToolSource(func(ctx context.Context, sid string) ([]agent.Tool, error) {+ var tools []agent.Tool+ if f.ToolSource != nil {+ rows, err := f.ToolSource(ctx, sid)+ if err != nil {+ return nil, err+ }+ tools = append(tools, rows...)+ }+ rows, err := scope.Tools(ctx, sid)+ return append(tools, rows...), err+ })+ }+ live := &NativeLive{Agent: loop, Session: s, Goals: goals, Plan: plans, Questions: questions, Resource: resource, Structured: structured, extensionScope: scope}+ if f.BeforePublish != nil {+ if err := f.BeforePublish(ctx, live); err != nil {+ return nil, errors.Join(err, live.Close())+ }+ }+ return live, nil}diff --git a/harness/assembly/native_runtime_test.go b/harness/assembly/native_runtime_test.goindex 573b7a0..1f2635c 100644--- a/harness/assembly/native_runtime_test.go+++ b/harness/assembly/native_runtime_test.go@@ -10,8 +10,11 @@ import ("strings""sync""testing"+ "testing/synctest"+ "time""go-bot/harness/agent"+ "go-bot/harness/interaction""go-bot/harness/permission""go-bot/harness/plan""go-bot/harness/schedule"@@ -245,11 +248,11 @@ func TestToolPolicyCanRequireApprovalBeforeDispatch(t *testing.T) {Storage: &nativeMemoryStorage{}, Builder: nativeTestBuilder{newContainerTestBuilder(t, t.TempDir())},Model: &nativeGoalModel{}, Provider: "test-provider", ModelID: "test-model", SystemPrompt: "Help the user.",Limits: agent.Limits{MaxSteps: 2, MaxToolCalls: 2},- ToolApproval: func(_ context.Context, name string, _ json.RawMessage) *permission.Request {- if name != "create_goal" {- return nil+ ToolPreExecutePolicy: func(_ context.Context, execution agent.ToolExecution) (agent.PreToolDecision, error) {+ if execution.Name != "create_goal" {+ return agent.PreToolDecision{Kind: "allow"}, nil}- return &permission.Request{Reason: "Verify pre-dispatch approval", Detail: "Create the report goal"}+ return agent.PreToolDecision{Kind: "ask", Reason: "Verify pre-dispatch approval"}, nil},}live, err := factory.Activate(ctx, NativeRuntimeIdentity{UserID: "alice", SessionID: "approval-test", Workspace: "/workspace"})@@ -277,6 +280,61 @@ func TestToolPolicyCanRequireApprovalBeforeDispatch(t *testing.T) {}}+func TestInteractiveApprovalHasNoDeadlineAndSurvivesClientDetach(t *testing.T) {+ factory := NativeFactory{+ Storage: &nativeMemoryStorage{}, Builder: nativeTestBuilder{newContainerTestBuilder(t, t.TempDir())},+ Model: &nativeGoalModel{}, Provider: "test", ModelID: "test", SystemPrompt: "Help.",+ Limits: agent.Limits{MaxSteps: 2, MaxToolCalls: 2},+ ToolPreExecutePolicy: func(context.Context, agent.ToolExecution) (agent.PreToolDecision, error) {+ return agent.PreToolDecision{Kind: "ask", Reason: "Test approval"}, nil+ },+ }+ live, err := factory.Activate(t.Context(), NativeRuntimeIdentity{UserID: "alice", SessionID: "no-approval-timeout", Workspace: "/workspace"})+ if err != nil {+ t.Fatal(err)+ }+ defer live.Close()+ live.Questions.Enable()+ if err := permission.Save(t.Context(), live.Session, permission.ReadOnly, false, false); err != nil {+ t.Fatal(err)+ }+ synctest.Test(t, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ detach := live.Questions.AttachApprovalClient()+ result := make(chan error, 1)+ go func() { _, err := live.Agent.RunTextTurn(ctx, "Create a report goal"); result <- err }()+ synctest.Wait()+ if len(live.Questions.Pending()) != 1 {+ t.Fatal("approval was not pending")+ }+ detach()+ time.Sleep(3 * time.Minute)+ synctest.Wait()+ select {+ case err := <-result:+ t.Fatalf("approval ended without a decision: %v", err)+ default:+ }+ pending := live.Questions.Pending()+ if len(pending) != 1 {+ t.Fatal("approval expired or disappeared after disconnect")+ }+ detach = live.Questions.AttachApprovalClient()+ defer detach()+ if err := live.Questions.Answer(ctx, pending[0].CallID, interaction.Answer{Answers: []interaction.AnswerItem{{ID: "approval", Selected: []string{permission.Approve}}}}); err != nil {+ t.Fatal(err)+ }+ synctest.Wait()+ if err := <-result; err != nil {+ t.Fatal(err)+ }+ if _, found, err := live.Goals.Get(); err != nil || !found {+ t.Fatalf("late approval failed to execute: found=%t err=%v", found, err)+ }+ })+}+func TestNativeFactoryGoalToolWritesV4AndResumesDisarmed(t *testing.T) {ctx := context.Background()storage := &nativeMemoryStorage{}diff --git a/harness/jobs/registry.go b/harness/jobs/registry.goindex 5b21668..b523da3 100644--- a/harness/jobs/registry.go+++ b/harness/jobs/registry.go@@ -88,6 +88,15 @@ func New(parent context.Context, maxConcurrent, retainBytes int, onSettle func(Sfunc terminal(status Status) bool { return status == Completed || status == Failed || status == Killed }+// OutputLimit captures the visible producer buffer budget before a Job tool+// starts waiting or consumes output. It remains usable if the Job disappears.+func (r *Registry) OutputLimit(id string) (int, bool) {+ r.mu.Lock()+ defer r.mu.Unlock()+ _, exists := r.jobs[id]+ return r.retain, exists+}+// Start reserves capacity before running producer code. A failed admission// starts no goroutine or external effect.func (r *Registry) Start(kind, label string, run Runner) (Snapshot, error) {diff --git a/harness/output/retention.go b/harness/output/retention.gonew file mode 100644index 0000000..934c78a--- /dev/null+++ b/harness/output/retention.go@@ -0,0 +1,110 @@+package output++import (+ "context"+ "crypto/rand"+ "encoding/hex"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "unicode/utf16"+ "unicode/utf8"+)++const InlineTokens = 12_500++// RetainText returns a token-bounded preview backed by an exact readable copy.+// On unavailable storage the original content is returned with an error, so+// callers can diagnose degraded retention without losing a successful result.+func RetainText(ctx context.Context, workdir, directory, name, text string, maxTokens int) (string, error) {+ if Estimate(text) <= maxTokens {+ return text, nil+ }+ if err := ctx.Err(); err != nil {+ return text, err+ }+ if workdir == "" {+ return text, errors.New("tool output has no recovery workspace")+ }+ const gap = "\n\n[...]\n\n"+ locator, err := saveText(workdir, directory, name, text)+ if err != nil {+ return text, err+ }+ notice := func(omitted int) string {+ return fmt.Sprintf("(Omitted %d bytes. Full formatted result stored at: %s. Use readfile with offset/limit, or grep this path to search within it.)", omitted, locator)+ }+ worstNotice := notice(len(text))+ if Estimate(worstNotice) > maxTokens {+ return text, errors.New("recovery notice exceeds tool output budget")+ }+ available := max(0, maxTokens-Estimate(gap)-Estimate("\n\n"+worstNotice))+ head := truncateUTF16(text, max(0, ((available+1)/2-4)*4))+ tail := suffixUTF16(text[len(head):], max(0, (available/2-4)*4))+ footer := notice(len(text) - len(head) - len(tail))+ if head == "" && tail == "" {+ return footer, nil+ }+ return head + gap + tail + "\n\n" + footer, nil+}++func Estimate(text string) int { return (utf16Length(text)+3)/4 + 4 }++func suffixUTF16(text string, maxChars int) string {+ chars := 0+ for i := len(text); i > 0; {+ r, bytes := utf8.DecodeLastRuneInString(text[:i])+ chars += utf16.RuneLen(r)+ if chars > maxChars {+ return text[i:]+ }+ i -= bytes+ }+ return text+}++func saveText(workdir, dir, name, text string) (string, error) {+ root, err := os.OpenRoot(workdir)+ if err != nil {+ return "", err+ }+ defer root.Close()+ if err := root.MkdirAll(dir, 0o700); err != nil {+ return "", err+ }+ var id [6]byte+ if _, err := rand.Read(id[:]); err != nil {+ return "", err+ }+ path := filepath.Join(dir, hex.EncodeToString(id[:])+"-"+name+".txt")+ file, err := root.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)+ if err != nil {+ return "", err+ }+ _, writeErr := io.WriteString(file, text)+ if err := errors.Join(writeErr, file.Sync(), file.Close()); err != nil {+ _ = root.Remove(path)+ return "", err+ }+ return filepath.Join(workdir, path), nil+}++func utf16Length(text string) int {+ n := 0+ for _, r := range text {+ n += utf16.RuneLen(r)+ }+ return n+}+func truncateUTF16(text string, maxChars int) string {+ count := 0+ for index, r := range text {+ count += utf16.RuneLen(r)+ if count > maxChars {+ return text[:index]+ }+ }+ return text+}diff --git a/harness/output/retention_test.go b/harness/output/retention_test.gonew file mode 100644index 0000000..aa65302--- /dev/null+++ b/harness/output/retention_test.go@@ -0,0 +1,60 @@+package output++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "unicode/utf8"+)++func TestRecoverablePreviewPreservesUnicodeAndExactOriginal(t *testing.T) {+ root := t.TempDir()+ text := strings.Repeat("调研🙂结果\n", 12000)+ preview, err := RetainText(t.Context(), root, ".agent/tool-spill", "research", text, InlineTokens)+ if err != nil {+ t.Fatal(err)+ }+ if !utf8.ValidString(preview) || Estimate(preview) > InlineTokens || !strings.Contains(preview, "Full formatted result stored at:") {+ t.Fatalf("invalid preview tokens=%d", Estimate(preview))+ }+ files, err := filepath.Glob(filepath.Join(root, ".agent", "tool-spill", "*.txt"))+ if err != nil || len(files) != 1 {+ t.Fatalf("files=%v error=%v", files, err)+ }+ full, err := os.ReadFile(files[0])+ if err != nil || string(full) != text || !strings.Contains(preview, files[0]) {+ t.Fatal("recovery path does not expose the exact original")+ }+ info, err := os.Stat(files[0])+ if err != nil || info.Mode().Perm() != 0600 {+ t.Fatal("spill is not private")+ }+ // Passing an already retained preview does not produce another spill copy.+ second, err := RetainText(t.Context(), root, ".agent/tool-spill", "research", preview, InlineTokens)+ if err != nil || second != preview {+ t.Fatal("retained preview was modified again")+ }+ files, _ = filepath.Glob(filepath.Join(root, ".agent", "tool-spill", "*.txt"))+ if len(files) != 1 {+ t.Fatal("output was double-spilled")+ }+}+func TestUnavailableRecoveryKeepsOutput(t *testing.T) {+ text := strings.Repeat("data", 20000)+ for _, ctx := range []context.Context{t.Context(), func() context.Context { ctx, cancel := context.WithCancel(t.Context()); cancel(); return ctx }()} {+ actual, err := RetainText(ctx, "/nonexistent/go-bot-output", ".agent/tool-spill", "tool", text, InlineTokens)+ if err == nil || actual != text {+ t.Fatal("missing recovery storage lost original content")+ }+ }+}+func TestJobTailRetainsStatusWithinByteBudget(t *testing.T) {+ text := strings.Repeat("运行🙂", 100)+ suffix := "\njob_id=known status=completed exit_code=0"+ got := FitTail(text, suffix, 120)+ if !utf8.ValidString(got) || len(got) > 120 || !strings.HasSuffix(got, suffix) || !strings.Contains(got, "truncated") {+ t.Fatalf("tail=%q", got)+ }+}diff --git a/harness/output/tail.go b/harness/output/tail.gonew file mode 100644index 0000000..fadb1d2--- /dev/null+++ b/harness/output/tail.go@@ -0,0 +1,36 @@+package output++import (+ "strings"+ "unicode/utf8"+)++// FitTail preserves a Job's final status after truncation, counting UTF-8+// bytes and avoiding broken multibyte characters at the retained boundary.+func FitTail(text, suffix string, limit int) string {+ if len(text)+len(suffix) <= limit {+ return text + suffix+ }+ notice := "\n[output truncated]"+ if strings.HasSuffix(text, strings.TrimSpace(notice)) {+ notice = ""+ }+ fixed := notice + suffix+ if len(fixed) >= limit {+ return tailBytes(fixed, limit)+ }+ return tailBytes(text, limit-len(fixed)) + fixed+}+func tailBytes(text string, limit int) string {+ if limit <= 0 {+ return ""+ }+ if len(text) <= limit {+ return text+ }+ index := len(text) - limit+ for index < len(text) && !utf8.RuneStart(text[index]) {+ index+++ }+ return text[index:]+}diff --git a/harness/permission/approval.go b/harness/permission/approval.goindex 6e25ec7..dce5588 100644--- a/harness/permission/approval.go+++ b/harness/permission/approval.go@@ -4,7 +4,6 @@ import ("context""encoding/json""errors"- "time""go-bot/harness/agent""go-bot/harness/interaction"@@ -47,11 +46,9 @@ func (s ApprovalService) Request(ctx context.Context, request Request) error {}outcome := "rejected"if Read(s.Session.Events()).Approval == "ask" {- decisionCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)- answer, err := s.Questions.AskApproval(decisionCtx, turn, step, id,+ answer, err := s.Questions.AskApproval(ctx, turn, step, id,interaction.Approval{Tool: request.Tool, Reason: request.Reason, Detail: request.Detail, Target: string(request.Target), ToolCallID: callID},[]interaction.Question{{ID: "approval", Question: "Allow this operation?", Options: []interaction.Option{{Label: Approve}, {Label: Reject}}}})- cancel()switch {case errors.Is(err, interaction.ErrUnavailable):outcome = "unavailable"diff --git a/harness/session/append.go b/harness/session/append.gonew file mode 100644index 0000000..b80ee84--- /dev/null+++ b/harness/session/append.go@@ -0,0 +1,45 @@+package sessionformat++import (+ "encoding/json"+ "time"+)++// AppendBatch validates the complete suffix before making it visible. The+// journal remains Go-owned and is persisted separately by Flush/checkpoints.+func (s *LiveSession) AppendBatch(inputs []EventInput) ([]Event, error) {+ return s.appendInputs(inputs, time.Now().UnixMilli())+}+func (s *LiveSession) appendInputs(inputs []EventInput, timestamp int64) ([]Event, error) {+ s.appendMu.Lock()+ defer s.appendMu.Unlock()+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.appendInputsLocked(inputs, timestamp)+}+func (s *LiveSession) appendInputsLocked(inputs []EventInput, timestamp int64) ([]Event, error) {+ if s.closed || s.closing || s.poison {+ return nil, ErrV4UncertainWrite+ }+ surface := *s.surface+ for _, input := range inputs {+ if input.Type == "image/offload" {+ surface.projected = make(map[uint64]json.RawMessage, len(s.surface.projected))+ for key, value := range s.surface.projected {+ surface.projected[key] = value+ }+ break+ }+ }+ shadow := &LiveSession{header: s.header, events: s.events, surface: &surface, inbox: s.inbox.Clone()}+ events := make([]Event, 0, len(inputs))+ for _, input := range inputs {+ event, err := shadow.appendLocked(input, timestamp)+ if err != nil {+ return nil, err+ }+ events = append(events, event)+ }+ s.events, s.surface, s.inbox = shadow.events, shadow.surface, shadow.inbox+ return cloneV4Events(events), nil+}diff --git a/harness/session/append_test.go b/harness/session/append_test.gonew file mode 100644index 0000000..a06d92e--- /dev/null+++ b/harness/session/append_test.go@@ -0,0 +1,25 @@+package sessionformat++import (+ "encoding/json"+ "testing"+)++func TestAppendBatchValidationIsAtomic(t *testing.T) {+ s, err := NewLiveSession(Header{Type: "session", Version: 4, CreatedAt: 1, ID: "atomic", CWD: "/tmp"}, &memoryV4Journal{})+ if err != nil {+ t.Fatal(err)+ }+ defer s.Close()+ title := EventInput{Type: "session/title", Data: json.RawMessage(`{"title":"report"}`)}+ before := len(s.Events())+ if _, err := s.AppendBatch([]EventInput{title, {Type: "user/message", Data: json.RawMessage(`{}`)}}); err == nil {+ t.Fatal("invalid batch accepted")+ }+ if len(s.Events()) != before {+ t.Fatal("invalid batch committed a partial prefix")+ }+ if events, err := s.AppendBatch([]EventInput{title, title}); err != nil || len(events) != 2 {+ t.Fatal(events, err)+ }+}diff --git a/harness/session/artifact.go b/harness/session/artifact.goindex b41f839..61c34ab 100644--- a/harness/session/artifact.go+++ b/harness/session/artifact.go@@ -100,10 +100,10 @@ func DecodePhysicalJSONL(input io.Reader) (PhysicalArtifact, error) {if row == 0 {return PhysicalArtifact{}, errors.New("Session v4 log has no complete header")}- if artifact.Header.IsSeeded != (inheritedMarker != nil) {+ if artifact.Header.IsSeeded && inheritedMarker == nil {return PhysicalArtifact{}, errors.New("Session v4 seeded header disagrees with inherited end-seed marker")}- if inheritedMarker != nil {+ if artifact.Header.IsSeeded && inheritedMarker != nil {artifact.InheritedEventCount = *inheritedMarker}return artifact, nildiff --git a/harness/session/artifact_test.go b/harness/session/artifact_test.goindex 8b9614e..c436b83 100644--- a/harness/session/artifact_test.go+++ b/harness/session/artifact_test.go@@ -78,7 +78,8 @@ func TestDecodePhysicalV4SeedCut(t *testing.T) {if _, err := DecodePhysicalJSONL(strings.NewReader(unseeded + "\n" + rows[3] + "\n")); err == nil {t.Fatal("seeded header with a sequence gap was accepted")}- if _, err := DecodePhysicalJSONL(strings.NewReader(physicalV4Header + "\n" + `{"type":"session/end-seed","seq":0,"time":2,"data":{"inherited":true}}` + "\n")); err == nil {- t.Fatal("unseeded header with inherited marker was accepted")+ replayed, err := DecodePhysicalJSONL(strings.NewReader(physicalV4Header + "\n" + `{"type":"session/end-seed","seq":0,"time":2,"data":{"inherited":true}}` + "\n"))+ if err != nil || replayed.InheritedEventCount != 0 || replayed.Header.IsSeeded {+ t.Fatal("a replayed prior marker invented new fork lineage", err)}}diff --git a/harness/session/file_store.go b/harness/session/file_store.goindex 232c1b2..b6e94f0 100644--- a/harness/session/file_store.go+++ b/harness/session/file_store.go@@ -21,7 +21,7 @@ import (type FileStore struct {Root stringProjectCWD string- RootSessionID string // Nonempty for a child Session.+ RootSessionID string // Optional built-in coordinator ancestor; not a metadata classification.Claim OwnerClaim}@@ -41,7 +41,7 @@ func (s FileStore) validateHeader(header Header) error {if err := header.Validate(); err != nil {return err}- return validateSessionLineage(s.ProjectCWD, s.RootSessionID, header)+ return validateSessionProject(s.ProjectCWD, header)}// ReadHeader inspects only the canonical first line. History listing must@@ -114,6 +114,33 @@ func (s FileStore) claim(ctx context.Context, sessionID string) (func(), error)}func (s FileStore) Create(ctx context.Context, header Header) (*FileJournal, error) {+ return s.create(ctx, header, nil)+}++// CreatePrepared atomically publishes the header with the complete validated+// constructor seed. Readers can never observe a seeded header without its cut.+// This backend copies the entire prefix; it does not borrow a live parent file.+func (s FileStore) CreatePrepared(ctx context.Context, header Header, events []Event) (*FileJournal, error) {+ var cut uint64+ if header.IsSeeded {+ for _, event := range events {+ if event.Type == "session/end-seed" {+ var marker struct {+ Inherited bool `json:"inherited"`+ }+ if json.Unmarshal(event.Data, &marker) == nil && marker.Inherited {+ cut = event.Seq+ }+ }+ }+ }+ if _, err := replaySession(PhysicalArtifact{Header: header, Events: events, InheritedEventCount: cut}, nil, 0); err != nil {+ return nil, err+ }+ return s.create(ctx, header, events)+}++func (s FileStore) create(ctx context.Context, header Header, events []Event) (*FileJournal, error) {if err := s.validateHeader(header); err != nil {return nil, err}@@ -160,7 +187,18 @@ func (s FileStore) Create(ctx context.Context, header Header) (*FileJournal, errif err := file.Chmod(0600); err != nil {return nil, err}- data := append(line, '\n')+ var body bytes.Buffer+ body.Write(line)+ body.WriteByte('\n')+ for index, event := range events {+ row, err := EncodeEvent(event, uint64(index))+ if err != nil {+ return nil, err+ }+ body.Write(row)+ body.WriteByte('\n')+ }+ data := body.Bytes()n, err := file.Write(data)if err == nil && n != len(data) {err = io.ErrShortWrite@@ -183,7 +221,7 @@ func (s FileStore) Create(ctx context.Context, header Header) (*FileJournal, err// The canonical link is durable. Removing its redundant temporary link is// best-effort and must not turn a successful Session creation into failure.owned = true- return &FileJournal{file: file, filename: filename, release: release, repairAt: -1}, nil+ return &FileJournal{file: file, filename: filename, release: release, nextSeq: uint64(len(events)), repairAt: -1}, nil}func (s FileStore) Open(ctx context.Context, sessionID string) (*FileJournal, PhysicalArtifact, error) {diff --git a/harness/session/file_store_test.go b/harness/session/file_store_test.goindex 3a5dc0f..d001db4 100644--- a/harness/session/file_store_test.go+++ b/harness/session/file_store_test.go@@ -294,36 +294,31 @@ func TestFileStoreKeepsChildSiblingAndRejectsOverwrite(t *testing.T) {}}-func TestFileStoreDoesNotPromoteParentLinkedHeaderToTopLevel(t *testing.T) {+func TestFileStorePersistsParentMetadataIndependentlyOfSubagentCoordinator(t *testing.T) {ctx := context.Background()cwd := "/root/harness/workspaces/not-a-root"store := FileStore{Root: filepath.Join(t.TempDir(), "sessions"), ProjectCWD: cwd, Claim: v4Claim}header := v4TestHeader("not-a-root")header.CWD = cwdheader.ParentSession = "another-session"- if _, err := store.Create(ctx, header); err == nil {- t.Fatal("top-level storage created a header linked to a parent")- }- filename, err := store.Path(header.ID)+ journal, err := store.Create(ctx, header)if err != nil {- t.Fatal(err)+ t.Fatal("independent parent metadata was treated as a subagent-only path", err)}- if err := os.MkdirAll(filepath.Dir(filename), 0o700); err != nil {+ if err := journal.Close(); err != nil {t.Fatal(err)}- line, err := EncodeHeader(header)- if err != nil {- t.Fatal(err)+ stored, err := store.ReadHeader(ctx, header.ID)+ if err != nil || stored != header {+ t.Fatal("header metadata changed across storage", stored, err)}- if err := os.WriteFile(filename, append(line, '\n'), 0o600); err != nil {+ opened, artifact, err := store.Open(ctx, header.ID)+ if err != nil {t.Fatal(err)}- if _, err := store.ReadHeader(ctx, header.ID); err == nil {- t.Fatal("top-level history listed a parent-linked header")- }- if journal, _, err := store.Open(ctx, header.ID); err == nil {- _ = journal.Close()- t.Fatal("top-level resume opened a parent-linked header")+ defer opened.Close()+ if artifact.Header != header {+ t.Fatal("opening a journal reclassified its lineage", artifact.Header)}}diff --git a/harness/session/live.go b/harness/session/live.goindex 823fc9f..d5c210a 100644--- a/harness/session/live.go+++ b/harness/session/live.go@@ -31,20 +31,23 @@ type EventInput struct {// Append does not perform I/O; Flush persists its accepted suffix, matching// the separation between DeepSeek's live Session and checkpoint policy.type LiveSession struct {- mu sync.Mutex- flushMu sync.Mutex- header Header- events []Event- surface *SurfaceState- inbox InboxState- durable int- inheritedCount uint64- journal EventJournal- poison bool- closing bool- closed bool- closeOnce sync.Once- closeErr error+ appendMu sync.Mutex+ mu sync.Mutex+ flushMu sync.Mutex+ header Header+ events []Event+ surface *SurfaceState+ inbox InboxState+ modelSelection ModelSelectionState+ modelSelectionCursor int+ durable int+ inheritedCount uint64+ journal EventJournal+ poison bool+ closing bool+ closed bool+ closeOnce sync.Once+ closeErr error}func NewLiveSession(header Header, journal EventJournal) (*LiveSession, error) {@@ -67,6 +70,29 @@ func NewLiveSession(header Header, journal EventJournal) (*LiveSession, error) {// lifecycle starts with an untagged end-seed marker. A stored end-seed marker// is retained without adding another.func RestoreLiveSession(artifact PhysicalArtifact, journal EventJournal) (*LiveSession, error) {+ if journal == nil {+ return nil, errors.New("Session v4 journal is required")+ }+ s, err := replaySession(artifact, journal, len(artifact.Events))+ if err != nil {+ return nil, err+ }+ // Repair belongs to resume, never to fresh constructor seed preparation.+ if _, err := appendInterruptedTurnClosers(s); err != nil {+ return nil, err+ }+ if len(s.events) == 0 || s.events[len(s.events)-1].Type != "session/end-seed" {+ if _, err := s.Append(EventInput{Type: "session/end-seed", Data: json.RawMessage(`{}`)}); err != nil {+ return nil, err+ }+ }+ return s, nil+}++func replaySession(artifact PhysicalArtifact, journal EventJournal, durable int) (*LiveSession, error) {+ if err := artifact.Header.Validate(); err != nil {+ return nil, err+ }if err := validateLiveSeedBoundary(artifact); err != nil {return nil, err}@@ -96,31 +122,15 @@ func RestoreLiveSession(artifact PhysicalArtifact, journal EventJournal) (*LiveSif _, err := FoldSubagentDescriptor(artifact.Events); err != nil {return nil, err}- s, err := NewLiveSession(artifact.Header, journal)- if err != nil {- return nil, err- }- s.surface = surface- s.inbox = inbox- s.events = make([]Event, len(artifact.Events))+ s := &LiveSession{header: artifact.Header, journal: journal, surface: surface, inbox: inbox, events: make([]Event, len(artifact.Events))}for index, event := range artifact.Events {if event.Seq != uint64(index) || !knownV4EventTypes[event.Type] && !event.Ignorable {return nil, fmt.Errorf("invalid Session v4 event %d", index)}s.events[index] = cloneV4Event(event)}- s.durable = len(s.events)+ s.durable = durables.inheritedCount = artifact.InheritedEventCount- // The interrupted turn belongs to the stored lifecycle. Close it before- // appending this resumed lifecycle's end-seed marker, as upstream does.- if _, err := appendInterruptedTurnClosers(s); err != nil {- return nil, err- }- if len(s.events) == 0 || s.events[len(s.events)-1].Type != "session/end-seed" {- if _, err := s.Append(EventInput{Type: "session/end-seed", Data: json.RawMessage(`{}`)}); err != nil {- return nil, err- }- }return s, nil}@@ -146,7 +156,7 @@ func validateLiveSeedBoundary(artifact PhysicalArtifact) error {if lastTagged == nil || *lastTagged != artifact.InheritedEventCount {return errors.New("seeded Session v4 has no marker at its inherited cut")}- } else if artifact.InheritedEventCount != 0 || lastTagged != nil {+ } else if artifact.InheritedEventCount != 0 {return errors.New("unseeded Session v4 has inherited events")}return nil@@ -160,12 +170,37 @@ func (s *LiveSession) InheritedEventCount() uint64 {return s.inheritedCount}+type Position struct {+ Seq uint64 `json:"seq"`+ InheritedEventCount uint64 `json:"inheritedEventCount"`+}++// Position reads the live log, including accepted events not yet flushed. It+// neither clones history nor performs I/O or observer dispatch. A borrowed+// Session remains readable after it has left the loaded-session registry.+func (s *LiveSession) Position() Position {+ s.mu.Lock()+ defer s.mu.Unlock()+ return Position{Seq: uint64(len(s.events)), InheritedEventCount: s.inheritedCount}+}+func (s *LiveSession) Events() []Event {s.mu.Lock()defer s.mu.Unlock()return cloneV4Events(s.events)}+// EventRange returns a detached immutable-prefix read, including accepted facts+// not yet flushed. An exact upper bound stays valid while later appends occur.+func (s *LiveSession) EventRange(from, to uint64) ([]Event, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if from > to || to > uint64(len(s.events)) {+ return nil, errors.New("Session event range is out of bounds")+ }+ return cloneV4Events(s.events[from:to]), nil+}+func (s *LiveSession) DurableEvents() []Event {s.mu.Lock()defer s.mu.Unlock()@@ -234,8 +269,14 @@ func (s *LiveSession) Append(input EventInput) (Event, error) {// appendAt is reserved for deterministic synthetic repair events. Ordinary// producers use Append, which stamps the current time at acceptance.func (s *LiveSession) appendAt(input EventInput, timestamp int64) (Event, error) {- s.mu.Lock()- defer s.mu.Unlock()+ events, err := s.appendInputs([]EventInput{input}, timestamp)+ if err != nil {+ return Event{}, err+ }+ return events[0], nil+}++func (s *LiveSession) appendLocked(input EventInput, timestamp int64) (Event, error) {if s.closed || s.closing || s.poison {return Event{}, ErrV4UncertainWrite}@@ -319,6 +360,8 @@ func (s *LiveSession) flushLocked(ctx context.Context) error {func (s *LiveSession) Close() error {s.closeOnce.Do(func() {+ s.appendMu.Lock()+ defer s.appendMu.Unlock()s.mu.Lock()s.closing = trues.mu.Unlock()diff --git a/harness/session/model_selection.go b/harness/session/model_selection.gonew file mode 100644index 0000000..9740077--- /dev/null+++ b/harness/session/model_selection.go@@ -0,0 +1,131 @@+package sessionformat++import (+ "encoding/json"+ "errors"+ "time"+)++// ModelSelection is an explicit route choice, not a resolved adapter config.+// Empty effort means omission; adapter-defaulted effort is never pinned here.+type ModelSelection struct {+ Provider string `json:"provider"`+ Model string `json:"model"`+ ReasoningEffort string `json:"reasoningEffort,omitempty"`+}++type ModelSelectionState struct {+ LastUsed *ModelSelection `json:"lastUsed"`+ Pending *ModelSelection `json:"pending"`+}++func (s ModelSelectionState) Current() *ModelSelection {+ if s.Pending != nil {+ copy := *s.Pending+ return ©+ }+ if s.LastUsed != nil {+ copy := *s.LastUsed+ return ©+ }+ return nil+}++func sameModelSelection(left, right *ModelSelection) bool {+ return left == right || left != nil && right != nil && *left == *right+}++func (s ModelSelectionState) Next(event Event) (ModelSelectionState, error) {+ switch event.Type {+ case "model/selection":+ var selected *ModelSelection+ if err := json.Unmarshal(event.Data, &selected); err != nil {+ return s, errors.New("invalid model selection")+ }+ if selected != nil && (selected.Provider == "" || selected.Model == "") {+ return s, errors.New("model selection requires provider and model")+ }+ // Null clears a pending choice; it does not erase the last request.+ s.Pending = selected+ case "request/header":+ var value struct {+ Header struct {+ Config ModelSelection+ AdapterDefaults struct{ ReasoningEffort bool }+ }+ }+ if json.Unmarshal(event.Data, &value) != nil || value.Header.Config.Provider == "" || value.Header.Config.Model == "" {+ return s, errors.New("request header requires provider and model")+ }+ selected := value.Header.Config+ if value.Header.AdapterDefaults.ReasoningEffort {+ selected.ReasoningEffort = ""+ }+ s.LastUsed = &selected+ if sameModelSelection(s.Pending, s.LastUsed) {+ s.Pending = nil+ }+ }+ return s, nil+}++func FoldModelSelection(events []Event) (ModelSelectionState, error) {+ var state ModelSelectionState+ for _, event := range events {+ next, err := state.Next(event)+ if err != nil {+ return ModelSelectionState{}, err+ }+ state = next+ }+ return state, nil+}++// ModelSelection reads the original live log, advancing only the missing+// suffix. Its state is process-local derived data, never a snapshot file.+func (s *LiveSession) ModelSelection() (ModelSelectionState, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ state, err := s.modelSelectionLocked()+ return ModelSelectionState{LastUsed: cloneSelection(state.LastUsed), Pending: cloneSelection(state.Pending)}, err+}++func cloneSelection(value *ModelSelection) *ModelSelection {+ if value == nil {+ return nil+ }+ copy := *value+ return ©+}++func (s *LiveSession) modelSelectionLocked() (ModelSelectionState, error) {+ for s.modelSelectionCursor < len(s.events) {+ next, err := s.modelSelection.Next(s.events[s.modelSelectionCursor])+ if err != nil {+ return ModelSelectionState{}, err+ }+ s.modelSelection = next+ s.modelSelectionCursor+++ }+ return s.modelSelection, nil+}++// SelectModel appends synchronously through the existing writer's live log.+// Only an equal recorded selection is a no-op; an options-only fallback still+// needs its first durable fact. Checkpoint/Flush remains the writer's policy.+func (s *LiveSession) SelectModel(selection ModelSelection) error {+ if selection.Provider == "" || selection.Model == "" {+ return errors.New("model selection requires provider and model")+ }+ s.appendMu.Lock()+ defer s.appendMu.Unlock()+ s.mu.Lock()+ defer s.mu.Unlock()+ state, err := s.modelSelectionLocked()+ if err != nil || sameModelSelection(state.Current(), &selection) {+ return err+ }+ data, _ := json.Marshal(selection)+ _, err = s.appendInputsLocked([]EventInput{{Type: "model/selection", Data: data}}, time.Now().UnixMilli())+ return err+}diff --git a/harness/session/model_selection_test.go b/harness/session/model_selection_test.gonew file mode 100644index 0000000..6427ecd--- /dev/null+++ b/harness/session/model_selection_test.go@@ -0,0 +1,143 @@+package sessionformat++import (+ "encoding/json"+ "os"+ "reflect"+ "sync"+ "testing"+)++func TestModelSelectionMatchesPinnedUpstreamProjectionAndAgentModel(t *testing.T) {+ data, err := os.ReadFile("testdata/model-selection-cases.json")+ if err != nil {+ t.Fatal(err)+ }+ var actions []struct {+ Kind string+ Value json.RawMessage+ }+ if err := json.Unmarshal(data, &actions); err != nil {+ t.Fatal(err)+ }+ store := newLiveFileStore(t)+ header := v4TestHeader("model-selection")+ header.CWD = store.ProjectCWD+ journal, err := store.Create(t.Context(), header)+ if err != nil {+ t.Fatal(err)+ }+ live, err := NewLiveSession(header, journal)+ if err != nil {+ t.Fatal(err)+ }+ defer live.Close()+ for _, input := range []EventInput{{Type: "turn/start", Data: json.RawMessage(`{"turn":1}`)}, {Type: "step/start", Data: json.RawMessage(`{"turn":1,"step":1}`)}} {+ if _, err := live.Append(input); err != nil {+ t.Fatal(err)+ }+ }+ type snapshot struct {+ Current *ModelSelection `json:"current"`+ State ModelSelectionState `json:"state"`+ Seq uint64 `json:"seq"`+ SelectionEvents int `json:"selectionEvents"`+ }+ var snapshots []snapshot+ var options ModelSelection+ for _, action := range actions {+ switch action.Kind {+ case "options":+ options = ModelSelection{}+ err = json.Unmarshal(action.Value, &options)+ case "select":+ var selection ModelSelection+ if err = json.Unmarshal(action.Value, &selection); err == nil {+ err = live.SelectModel(selection)+ }+ case "header":+ value, _ := json.Marshal(map[string]json.RawMessage{"header": action.Value})+ _, err = live.Append(EventInput{Type: "request/header", Data: value})+ case "clear":+ _, err = live.Append(EventInput{Type: "model/selection", Data: json.RawMessage(`null`)})+ }+ if err != nil {+ t.Fatal(action.Kind, err)+ }+ state, err := live.ModelSelection()+ if err != nil {+ t.Fatal(err)+ }+ current := state.Current()+ if current == nil && options.Provider != "" && options.Model != "" {+ copy := options+ current = ©+ }+ selected := 0+ for _, event := range live.Events() {+ if event.Type == "model/selection" {+ selected+++ }+ }+ snapshots = append(snapshots, snapshot{current, state, live.Position().Seq, selected})+ }+ data, err = os.ReadFile("testdata/model-selection-upstream.json")+ if err != nil {+ t.Fatal(err)+ }+ var expected []snapshot+ if err := json.Unmarshal(data, &expected); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(snapshots, expected) {+ actual, _ := json.MarshalIndent(snapshots, "", " ")+ t.Fatalf("Go model selection differs from the pinned upstream oracle:\n%s", actual)+ }+ for _, input := range []EventInput{{Type: "step/end", Data: json.RawMessage(`{"turn":1,"step":1}`)}, {Type: "turn/end", Data: json.RawMessage(`{"turn":1,"reason":{"kind":"completed"}}`)}} {+ if _, err := live.Append(input); err != nil {+ t.Fatal(err)+ }+ }+ if err := live.Close(); err != nil {+ t.Fatal(err)+ }+ journal, artifact, err := store.Open(t.Context(), header.ID)+ if err != nil {+ t.Fatal(err)+ }+ restored, err := RestoreLiveSession(artifact, journal)+ if err != nil {+ t.Fatal(err)+ }+ defer restored.Close()+ state, err := restored.ModelSelection()+ if err != nil || !reflect.DeepEqual(state, expected[len(expected)-1].State) {+ t.Fatal("actual disk restore changed the model projection", state, err)+ }+ state.LastUsed.Model = "caller mutation"+ again, err := restored.ModelSelection()+ if err != nil || again.LastUsed.Model == "caller mutation" {+ t.Fatal("model projection leaked mutable state", err)+ }+}++func TestConcurrentModelSelectRecordsOnceWithoutFlushing(t *testing.T) {+ live, err := NewLiveSession(v4TestHeader("model-select"), &memoryV4Journal{})+ if err != nil {+ t.Fatal(err)+ }+ defer live.Close()+ selection := ModelSelection{Provider: "p", Model: "m"}+ var group sync.WaitGroup+ for index := 0; index < 16; index++ {+ group.Go(func() {+ if err := live.SelectModel(selection); err != nil {+ t.Error(err)+ }+ })+ }+ group.Wait()+ if live.Position().Seq != 1 || live.DurableCursor() != -1 {+ t.Fatal("equal selections were duplicated or select introduced an implicit checkpoint")+ }+}diff --git a/harness/session/preparation.go b/harness/session/preparation.gonew file mode 100644index 0000000..c73e040--- /dev/null+++ b/harness/session/preparation.go@@ -0,0 +1,96 @@+package sessionformat++import (+ "encoding/json"+ "errors"+ "sync"+ "time"+)++// Preparation owns one validated, unpublished Go Session. It has no writer or+// registry entry until Attach. Failed validation therefore creates no disk data.+type Preparation struct {+ mu sync.Mutex+ session *LiveSession+ attached bool+}++// PrepareSession snapshots borrowed seed data and applies the upstream fresh+// constructor marker rules. Nil seed means omitted; a non-nil empty seed is an+// explicit replay seed and receives an end-seed marker. It does not repair an+// interrupted turn: only resume owns that operation.+func PrepareSession(header Header, seed []Event, inherited *uint64) (*Preparation, error) {+ return prepareSessionAt(header, seed, inherited, time.Now().UnixMilli())+}++func prepareSessionAt(header Header, seed []Event, inherited *uint64, timestamp int64) (*Preparation, error) {+ if err := header.Validate(); err != nil {+ return nil, err+ }+ if header.IsSeeded && (seed == nil || inherited == nil) {+ return nil, errors.New("seeded Session requires an explicit seed and inherited event count")+ }+ count := uint64(0)+ if inherited != nil {+ count = *inherited+ }+ if count > uint64(len(seed)) || count > uint64(maxSafeInteger) || (!header.IsSeeded && count != 0) {+ return nil, errors.New("invalid Session inherited event count")+ }+ events := cloneV4Events(seed)+ marked := false+ if count < uint64(len(events)) && events[count].Type == "session/end-seed" {+ var data struct {+ Inherited bool `json:"inherited"`+ }+ if json.Unmarshal(events[count].Data, &data) == nil {+ marked = data.Inherited+ }+ }+ if header.IsSeeded && count != uint64(len(events)) && !marked {+ return nil, errors.New("seed must equal the inherited prefix or mark its inherited cut")+ }+ if marked {+ for _, event := range events[count+1:] {+ if event.Type != "session/end-seed" {+ continue+ }+ var data struct {+ Inherited bool `json:"inherited"`+ }+ if json.Unmarshal(event.Data, &data) == nil && data.Inherited {+ return nil, errors.New("inherited cut must identify the final inherited marker")+ }+ }+ }+ if seed != nil {+ if header.IsSeeded && !marked {+ events = append(events, Event{Type: "session/end-seed", Seq: uint64(len(events)), Time: timestamp, Data: json.RawMessage(`{"inherited":true}`)})+ } else if !header.IsSeeded && (len(events) == 0 || events[len(events)-1].Type != "session/end-seed") {+ events = append(events, Event{Type: "session/end-seed", Seq: uint64(len(events)), Time: timestamp, Data: json.RawMessage(`{}`)})+ }+ }+ s, err := replaySession(PhysicalArtifact{Header: header, Events: events, InheritedEventCount: count}, nil, 0)+ if err != nil {+ return nil, err+ }+ return &Preparation{session: s}, nil+}++func (p *Preparation) Header() Header { return p.session.Header() }+func (p *Preparation) Events() []Event { return p.session.Events() }++// Attach transfers the exact prepared Session to its single real write handle.+// storedCount identifies the prefix already atomically persisted by storage;+// any remaining constructor events still need the caller's checkpoint.+func (p *Preparation) Attach(journal EventJournal, storedCount int) (*LiveSession, error) {+ p.mu.Lock()+ defer p.mu.Unlock()+ if journal == nil || p.attached || storedCount < 0 || storedCount > len(p.session.events) {+ return nil, errors.New("Session preparation already attached or writer missing")+ }+ p.attached = true+ p.session.journal = journal+ p.session.durable = storedCount+ return p.session, nil+}diff --git a/harness/session/preparation_test.go b/harness/session/preparation_test.gonew file mode 100644index 0000000..7d9104b--- /dev/null+++ b/harness/session/preparation_test.go@@ -0,0 +1,127 @@+package sessionformat++import (+ "encoding/json"+ "os"+ "reflect"+ "testing"+)++// Expected rows were produced by the original published dsh-session+// 0.2.2-rc.4 SessionStore.prepare, not by this Go implementation. The one-off+// oracle/provenance lives in the ignored plugin-framework QA directory.+func TestPreparedSessionMatchesOriginalConstructorCases(t *testing.T) {+ var scenarios []struct {+ Name string `json:"name"`+ IsSeeded bool `json:"isSeeded"`+ Inherited *uint64 `json:"inheritedEventCount"`+ Seed []Event `json:"seed"`+ }+ var expected []struct {+ Name string `json:"name"`+ OK bool `json:"ok"`+ Inherited uint64 `json:"inheritedEventCount"`+ Events []Event `json:"events"`+ }+ read := func(path string, target any) {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if err = json.Unmarshal(data, target); err != nil {+ t.Fatal(err)+ }+ }+ read("testdata/preparation-cases.json", &scenarios)+ read("testdata/preparation-upstream.json", &expected)+ if len(scenarios) != len(expected) {+ t.Fatal("oracle cases are incomplete")+ }+ for index, scenario := range scenarios {+ t.Run(scenario.Name, func(t *testing.T) {+ want := expected[index]+ if scenario.Name != want.Name {+ t.Fatal("oracle case order differs")+ }+ header := Header{Type: "session", Version: 4, ID: scenario.Name, CreatedAt: 1, CWD: "/workspace", IsSeeded: scenario.IsSeeded}+ prepared, err := prepareSessionAt(header, scenario.Seed, scenario.Inherited, 1000)+ if want.OK != (err == nil) {+ t.Fatal("upstream acceptance differs", err)+ }+ if err != nil {+ return+ }+ if prepared.session.InheritedEventCount() != want.Inherited {+ t.Fatal("inherited cut differs")+ }+ if position := prepared.session.Position(); position.Seq != uint64(len(want.Events)) || position.InheritedEventCount != want.Inherited {+ t.Fatal("synchronous Session position differs from original constructor", position)+ }+ normalize := func(events []Event) any {+ data, _ := json.Marshal(events)+ var value any+ if err := json.Unmarshal(data, &value); err != nil {+ t.Fatal(err)+ }+ return value+ }+ if !reflect.DeepEqual(normalize(prepared.Events()), normalize(want.Events)) {+ t.Fatal("constructor events differ from upstream", prepared.Events())+ }+ if prepared.Header() != header {+ t.Fatal("preparation changed immutable metadata")+ }+ if len(scenario.Seed) > 0 {+ scenario.Seed[0].Data = json.RawMessage(`{"caller":"changed"}`)+ if reflect.DeepEqual(prepared.Events()[0].Data, scenario.Seed[0].Data) {+ t.Fatal("caller retained mutable seed ownership")+ }+ }+ })+ }+}++func TestPreparedSeedIsPublishedAtomicallyAndAttachedOnlyOnce(t *testing.T) {+ store := newLiveFileStore(t)+ header := v4TestHeader("prepared-seed")+ header.CWD = store.ProjectCWD+ header.IsSeeded = true+ count := uint64(1)+ seed := []Event{{Type: "permission/preset", Seq: 0, Time: 1, Data: json.RawMessage(`{"preset":"read-only"}`)}}+ prepared, err := PrepareSession(header, seed, &count)+ if err != nil {+ t.Fatal(err)+ }+ journal, err := store.CreatePrepared(t.Context(), header, prepared.Events())+ if err != nil {+ t.Fatal(err)+ }+ // Read the canonical file before attaching the live writer. The full seed+ // and inherited marker must already be present, rather than only a header.+ artifact, err := store.ReadArtifact(t.Context(), header.ID)+ if err != nil || artifact.InheritedEventCount != 1 || len(artifact.Events) != 2 {+ t.Fatal("partial seed publication", artifact, err)+ }+ live, err := prepared.Attach(journal, len(artifact.Events))+ if err != nil {+ t.Fatal(err)+ }+ defer live.Close()+ if _, err := prepared.Attach(journal, len(artifact.Events)); err == nil {+ t.Fatal("writer attached twice")+ }+ if _, err := live.Append(EventInput{Type: "approval/policy", Data: json.RawMessage(`{"policy":"ask"}`)}); err != nil {+ t.Fatal(err)+ }+ if err := live.Flush(t.Context()); err != nil {+ t.Fatal("attached writer duplicated constructor events", err)+ }+ artifact, err = store.ReadArtifact(t.Context(), header.ID)+ if err != nil || len(artifact.Events) != 3 || artifact.Events[2].Type != "approval/policy" {+ t.Fatal("prepared writer cursor differs from the journal", artifact, err)+ }+ if _, err := store.CreatePrepared(t.Context(), header, prepared.Events()); err == nil {+ t.Fatal("existing journal replaced")+ }+}diff --git a/harness/session/store_contract.go b/harness/session/store_contract.goindex 3234466..bff6d00 100644--- a/harness/session/store_contract.go+++ b/harness/session/store_contract.go@@ -17,18 +17,12 @@ var ErrV4WriteRolledBack = errors.New("Session v4 append was rolled back; retryvar v4KeyComponent = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)-func validateSessionLineage(projectCWD, rootSessionID string, header Header) error {+func validateSessionProject(projectCWD string, header Header) error {if projectCWD != "" && header.CWD != projectCWD {return errors.New("Session v4 header cwd differs from its project directory")}- if rootSessionID == "" {- if header.ParentSession != "" || header.Origin == "subagent" || header.DelegationDepth != 0 {- return errors.New("top-level Session v4 header declares child lineage")- }- return nil- }- if header.ParentSession == "" || header.Origin != "subagent" || header.DelegationDepth < 1 {- return errors.New("child Session v4 header lacks lineage")- }+ // Lineage is Session metadata, not a filesystem mode. Programmatic creates+ // may seed/fork or name a parent independently of the built-in subagent+ // coordinator. UI listing and coordinator admission own their own checks.return nil}diff --git a/harness/session/testdata/model-selection-cases.json b/harness/session/testdata/model-selection-cases.jsonnew file mode 100644index 0000000..cb8a12e--- /dev/null+++ b/harness/session/testdata/model-selection-cases.json@@ -0,0 +1,141 @@+[+ {+ "kind": "read"+ },+ {+ "kind": "options",+ "value": {+ "provider": "p"+ }+ },+ {+ "kind": "options",+ "value": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ }+ },+ {+ "kind": "select",+ "value": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ }+ },+ {+ "kind": "select",+ "value": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ }+ },+ {+ "kind": "options",+ "value": {+ "provider": "other",+ "model": "other",+ "reasoningEffort": "low"+ }+ },+ {+ "kind": "header",+ "value": {+ "config": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ },+ "adapterDefaults": {+ "reasoningEffort": true+ }+ }+ },+ {+ "kind": "header",+ "value": {+ "config": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ }+ }+ },+ {+ "kind": "select",+ "value": {+ "provider": "p",+ "model": "b"+ }+ },+ {+ "kind": "header",+ "value": {+ "config": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "medium"+ }+ }+ },+ {+ "kind": "header",+ "value": {+ "config": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "low"+ },+ "adapterDefaults": {+ "reasoningEffort": true+ }+ }+ },+ {+ "kind": "clear"+ },+ {+ "kind": "select",+ "value": {+ "provider": "p",+ "model": "b"+ }+ },+ {+ "kind": "options",+ "value": {}+ },+ {+ "kind": "select",+ "value": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ }+ },+ {+ "kind": "header",+ "value": {+ "config": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ }+ }+ },+ {+ "kind": "select",+ "value": {+ "provider": "new",+ "model": "b"+ }+ },+ {+ "kind": "clear"+ },+ {+ "kind": "read"+ }+]diff --git a/harness/session/testdata/model-selection-upstream.json b/harness/session/testdata/model-selection-upstream.jsonnew file mode 100644index 0000000..835d523--- /dev/null+++ b/harness/session/testdata/model-selection-upstream.json@@ -0,0 +1,309 @@+[+ {+ "current": null,+ "state": {+ "lastUsed": null,+ "pending": null+ },+ "seq": 2,+ "selectionEvents": 0+ },+ {+ "current": null,+ "state": {+ "lastUsed": null,+ "pending": null+ },+ "seq": 2,+ "selectionEvents": 0+ },+ {+ "current": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ },+ "state": {+ "lastUsed": null,+ "pending": null+ },+ "seq": 2,+ "selectionEvents": 0+ },+ {+ "current": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ },+ "state": {+ "lastUsed": null,+ "pending": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ }+ },+ "seq": 3,+ "selectionEvents": 1+ },+ {+ "current": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ },+ "state": {+ "lastUsed": null,+ "pending": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ }+ },+ "seq": 3,+ "selectionEvents": 1+ },+ {+ "current": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ },+ "state": {+ "lastUsed": null,+ "pending": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ }+ },+ "seq": 3,+ "selectionEvents": 1+ },+ {+ "current": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "a"+ },+ "pending": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ }+ },+ "seq": 4,+ "selectionEvents": 1+ },+ {+ "current": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ },+ "pending": null+ },+ "seq": 5,+ "selectionEvents": 1+ },+ {+ "current": {+ "provider": "p",+ "model": "b"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "high"+ },+ "pending": {+ "provider": "p",+ "model": "b"+ }+ },+ "seq": 6,+ "selectionEvents": 2+ },+ {+ "current": {+ "provider": "p",+ "model": "b"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "a",+ "reasoningEffort": "medium"+ },+ "pending": {+ "provider": "p",+ "model": "b"+ }+ },+ "seq": 7,+ "selectionEvents": 2+ },+ {+ "current": {+ "provider": "p",+ "model": "b"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "b"+ },+ "pending": null+ },+ "seq": 8,+ "selectionEvents": 2+ },+ {+ "current": {+ "provider": "p",+ "model": "b"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "b"+ },+ "pending": null+ },+ "seq": 9,+ "selectionEvents": 3+ },+ {+ "current": {+ "provider": "p",+ "model": "b"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "b"+ },+ "pending": null+ },+ "seq": 9,+ "selectionEvents": 3+ },+ {+ "current": {+ "provider": "p",+ "model": "b"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "b"+ },+ "pending": null+ },+ "seq": 9,+ "selectionEvents": 3+ },+ {+ "current": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "b"+ },+ "pending": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ }+ },+ "seq": 10,+ "selectionEvents": 4+ },+ {+ "current": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ },+ "pending": null+ },+ "seq": 11,+ "selectionEvents": 4+ },+ {+ "current": {+ "provider": "new",+ "model": "b"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ },+ "pending": {+ "provider": "new",+ "model": "b"+ }+ },+ "seq": 12,+ "selectionEvents": 5+ },+ {+ "current": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ },+ "pending": null+ },+ "seq": 13,+ "selectionEvents": 6+ },+ {+ "current": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ },+ "state": {+ "lastUsed": {+ "provider": "p",+ "model": "b",+ "reasoningEffort": "high"+ },+ "pending": null+ },+ "seq": 13,+ "selectionEvents": 6+ }+]diff --git a/harness/session/testdata/preparation-cases.json b/harness/session/testdata/preparation-cases.jsonnew file mode 100644index 0000000..3e709b9--- /dev/null+++ b/harness/session/testdata/preparation-cases.json@@ -0,0 +1,21 @@+[+ {"name":"omitted"},+ {"name":"explicit-empty","seed":[]},+ {"name":"ordinary-replay","seed":[{"type":"permission/preset","seq":0,"time":1,"data":{"preset":"workspace-write"}}]},+ {"name":"existing-end","seed":[{"type":"session/end-seed","seq":0,"time":1,"data":{}}]},+ {"name":"empty-fork","isSeeded":true,"inheritedEventCount":0,"seed":[]},+ {"name":"closed-fork","isSeeded":true,"inheritedEventCount":2,"seed":[{"type":"turn/start","seq":0,"time":1,"data":{"turn":1}},{"type":"turn/end","seq":1,"time":2,"data":{"turn":1,"reason":{"kind":"completed"}}}]},+ {"name":"marked-fork-with-tail","isSeeded":true,"inheritedEventCount":1,"seed":[{"type":"permission/preset","seq":0,"time":1,"data":{"preset":"read-only"}},{"type":"session/end-seed","seq":1,"time":2,"data":{"inherited":true}},{"type":"approval/policy","seq":2,"time":3,"data":{"policy":"ask"}}]},+ {"name":"nested-fork","isSeeded":true,"inheritedEventCount":2,"seed":[{"type":"session/end-seed","seq":0,"time":1,"data":{"inherited":true}},{"type":"permission/preset","seq":1,"time":2,"data":{"preset":"read-only"}}]},+ {"name":"unseeded-replay-of-fork","seed":[{"type":"session/end-seed","seq":0,"time":1,"data":{"inherited":true}},{"type":"permission/preset","seq":1,"time":2,"data":{"preset":"read-only"}}]},+ {"name":"open-turn-replay","seed":[{"type":"turn/start","seq":0,"time":1,"data":{"turn":1}}]},+ {"name":"open-turn-fork","isSeeded":true,"inheritedEventCount":1,"seed":[{"type":"turn/start","seq":0,"time":1,"data":{"turn":1}}]},+ {"name":"opaque-plugin-record","seed":[{"type":"plugin:qa/seed","seq":0,"time":1,"ignorable":true,"data":{"nested":[1,"二",true]}}]},+ {"name":"missing-seed","isSeeded":true,"inheritedEventCount":0},+ {"name":"missing-inherited-count","isSeeded":true,"seed":[]},+ {"name":"inherited-count-past-seed","isSeeded":true,"inheritedEventCount":2,"seed":[]},+ {"name":"unseeded-nonzero-inheritance","inheritedEventCount":1,"seed":[{"type":"session/end-seed","seq":0,"time":1,"data":{}}]},+ {"name":"unmarked-cut-before-tail","isSeeded":true,"inheritedEventCount":0,"seed":[{"type":"permission/preset","seq":0,"time":1,"data":{"preset":"read-only"}}]},+ {"name":"later-inherited-marker","isSeeded":true,"inheritedEventCount":0,"seed":[{"type":"session/end-seed","seq":0,"time":1,"data":{"inherited":true}},{"type":"session/end-seed","seq":1,"time":2,"data":{"inherited":true}}]},+ {"name":"sequence-gap","seed":[{"type":"session/end-seed","seq":1,"time":1,"data":{}}]}+]diff --git a/harness/session/testdata/preparation-upstream.json b/harness/session/testdata/preparation-upstream.jsonnew file mode 100644index 0000000..5267d74--- /dev/null+++ b/harness/session/testdata/preparation-upstream.json@@ -0,0 +1,293 @@+[+ {+ "name": "omitted",+ "ok": true,+ "inheritedEventCount": 0,+ "events": []+ },+ {+ "name": "explicit-empty",+ "ok": true,+ "inheritedEventCount": 0,+ "events": [+ {+ "type": "session/end-seed",+ "seq": 0,+ "time": 1000,+ "data": {}+ }+ ]+ },+ {+ "name": "ordinary-replay",+ "ok": true,+ "inheritedEventCount": 0,+ "events": [+ {+ "type": "permission/preset",+ "seq": 0,+ "time": 1,+ "data": {+ "preset": "workspace-write"+ }+ },+ {+ "type": "session/end-seed",+ "seq": 1,+ "time": 1000,+ "data": {}+ }+ ]+ },+ {+ "name": "existing-end",+ "ok": true,+ "inheritedEventCount": 0,+ "events": [+ {+ "type": "session/end-seed",+ "seq": 0,+ "time": 1,+ "data": {}+ }+ ]+ },+ {+ "name": "empty-fork",+ "ok": true,+ "inheritedEventCount": 0,+ "events": [+ {+ "type": "session/end-seed",+ "seq": 0,+ "time": 1000,+ "data": {+ "inherited": true+ }+ }+ ]+ },+ {+ "name": "closed-fork",+ "ok": true,+ "inheritedEventCount": 2,+ "events": [+ {+ "type": "turn/start",+ "seq": 0,+ "time": 1,+ "data": {+ "turn": 1+ }+ },+ {+ "type": "turn/end",+ "seq": 1,+ "time": 2,+ "data": {+ "turn": 1,+ "reason": {+ "kind": "completed"+ }+ }+ },+ {+ "type": "session/end-seed",+ "seq": 2,+ "time": 1000,+ "data": {+ "inherited": true+ }+ }+ ]+ },+ {+ "name": "marked-fork-with-tail",+ "ok": true,+ "inheritedEventCount": 1,+ "events": [+ {+ "type": "permission/preset",+ "seq": 0,+ "time": 1,+ "data": {+ "preset": "read-only"+ }+ },+ {+ "type": "session/end-seed",+ "seq": 1,+ "time": 2,+ "data": {+ "inherited": true+ }+ },+ {+ "type": "approval/policy",+ "seq": 2,+ "time": 3,+ "data": {+ "policy": "ask"+ }+ }+ ]+ },+ {+ "name": "nested-fork",+ "ok": true,+ "inheritedEventCount": 2,+ "events": [+ {+ "type": "session/end-seed",+ "seq": 0,+ "time": 1,+ "data": {+ "inherited": true+ }+ },+ {+ "type": "permission/preset",+ "seq": 1,+ "time": 2,+ "data": {+ "preset": "read-only"+ }+ },+ {+ "type": "session/end-seed",+ "seq": 2,+ "time": 1000,+ "data": {+ "inherited": true+ }+ }+ ]+ },+ {+ "name": "unseeded-replay-of-fork",+ "ok": true,+ "inheritedEventCount": 0,+ "events": [+ {+ "type": "session/end-seed",+ "seq": 0,+ "time": 1,+ "data": {+ "inherited": true+ }+ },+ {+ "type": "permission/preset",+ "seq": 1,+ "time": 2,+ "data": {+ "preset": "read-only"+ }+ },+ {+ "type": "session/end-seed",+ "seq": 2,+ "time": 1000,+ "data": {}+ }+ ]+ },+ {+ "name": "open-turn-replay",+ "ok": true,+ "inheritedEventCount": 0,+ "events": [+ {+ "type": "turn/start",+ "seq": 0,+ "time": 1,+ "data": {+ "turn": 1+ }+ },+ {+ "type": "session/end-seed",+ "seq": 1,+ "time": 1000,+ "data": {}+ }+ ]+ },+ {+ "name": "open-turn-fork",+ "ok": true,+ "inheritedEventCount": 1,+ "events": [+ {+ "type": "turn/start",+ "seq": 0,+ "time": 1,+ "data": {+ "turn": 1+ }+ },+ {+ "type": "session/end-seed",+ "seq": 1,+ "time": 1000,+ "data": {+ "inherited": true+ }+ }+ ]+ },+ {+ "name": "opaque-plugin-record",+ "ok": true,+ "inheritedEventCount": 0,+ "events": [+ {+ "type": "plugin:qa/seed",+ "seq": 0,+ "time": 1,+ "ignorable": true,+ "data": {+ "nested": [+ 1,+ "二",+ true+ ]+ }+ },+ {+ "type": "session/end-seed",+ "seq": 1,+ "time": 1000,+ "data": {}+ }+ ]+ },+ {+ "name": "missing-seed",+ "ok": false+ },+ {+ "name": "missing-inherited-count",+ "ok": false+ },+ {+ "name": "inherited-count-past-seed",+ "ok": false+ },+ {+ "name": "unseeded-nonzero-inheritance",+ "ok": false+ },+ {+ "name": "unmarked-cut-before-tail",+ "ok": false+ },+ {+ "name": "later-inherited-marker",+ "ok": false+ },+ {+ "name": "sequence-gap",+ "ok": false+ }+]diff --git a/harness/skills/catalog.go b/harness/skills/catalog.gonew file mode 100644index 0000000..823e608--- /dev/null+++ b/harness/skills/catalog.go@@ -0,0 +1,61 @@+package skills++import "path/filepath"++// CatalogSkill is the invocation-neutral public Skills service projection.+// Locators and provider functions stay in their owner process.+type CatalogSkill struct {+ Name string `json:"name"`+ Description string `json:"description"`+ WhenToUse string `json:"whenToUse,omitempty"`+ Invocation struct {+ ModelInvocable bool `json:"modelInvocable"`+ UserInvocable bool `json:"userInvocable"`+ } `json:"invocation"`+ Source string `json:"source"`+ Provider string `json:"provider"`+ Path string `json:"path,omitempty"`+ ResourceBase *ResourceBase `json:"resourceBase,omitempty"`+}++type CatalogDefinition struct {+ CatalogSkill+ Content string `json:"content"`+ Metadata map[string]any `json:"metadata,omitempty"`+}++func (c Candidate) Catalog() CatalogSkill {+ var value CatalogSkill+ if c.presentation != nil {+ value = *c.presentation+ } else if c.loader != nil {+ value.Source, value.Provider = "custom", c.providerName+ } else {+ value.Provider = "filesystem"+ value.Path = filepath.Join(c.root, c.path)+ value.ResourceBase = &ResourceBase{Kind: "directory", Path: filepath.Join(c.root, c.base)}+ switch c.source.rank {+ case 100:+ value.Source = "project-dsh"+ case 200:+ value.Source = "project-agents"+ case 400:+ value.Source = "user-dsh"+ case 500:+ value.Source = "user-agents"+ default:+ value.Source = "custom"+ }+ }+ value.Name, value.Description, value.WhenToUse = c.Name, c.Description, c.WhenToUse+ value.Invocation.ModelInvocable, value.Invocation.UserInvocable = c.ModelInvocable, c.UserInvocable+ return value+}++func (c Candidate) Definition(loaded Loaded) CatalogDefinition {+ value := c.Catalog()+ value.Name, value.Description, value.WhenToUse = loaded.Name, loaded.Description, loaded.WhenToUse+ value.Invocation.ModelInvocable, value.Invocation.UserInvocable = loaded.ModelInvocable, loaded.UserInvocable+ value.Provider, value.ResourceBase = loaded.Value.Provider, loaded.Value.ResourceBase+ return CatalogDefinition{CatalogSkill: value, Content: loaded.Value.Content, Metadata: loaded.Metadata}+}diff --git a/harness/skills/registry.go b/harness/skills/registry.goindex 8bfb17a..4beee8e 100644--- a/harness/skills/registry.go+++ b/harness/skills/registry.go@@ -2,7 +2,9 @@ package skillsimport ("context"+ "encoding/json""errors"+ "fmt""io""io/fs""log/slog"@@ -22,7 +24,6 @@ const (UserDSHHomeDir = ".dsh"UserDSHHome = "/root/harness/" + UserDSHHomeDirUserAgentsHome = "/root/harness/.agents"- SeedDir = "/usr/share/go-bot/skill-seed"maxSkillBytes = 256 << 10)@@ -41,8 +42,10 @@ func IsSpace(r rune) bool {}type Lookup struct {- CWD string- Workspace string+ CWD string `json:"cwd"`+ Workspace string `json:"workspace"`+ SessionID string `json:"sessionId,omitempty"`+ ScopeID string `json:"scopeId,omitempty"`}// Registry discovers filesystem skills in precedence order. Custom and bundled@@ -51,6 +54,27 @@ type Registry struct {DSHHome stringAgentsHome stringCustomDirs []string+ Providers func(context.Context, Lookup) ([]Provider, error)+}++// Provider supplements filesystem discovery. Candidates retain the selected+// provider's loader; a later same-name registration cannot replace that loader.+type Provider struct {+ Name string+ List func(context.Context, Lookup) (ProviderSnapshot, error)+ Load func(context.Context, Lookup, ProviderEntry) (Loaded, error)+}++type ProviderEntry struct {+ Summary+ Rank float64 `json:"rank"`+ Data json.RawMessage `json:"data"`+ Priority int `json:"priority,omitempty"`+ Presentation *CatalogSkill `json:"presentation,omitempty"`+}+type ProviderSnapshot struct {+ Entries []ProviderEntry `json:"entries"`+ Complete bool `json:"complete"`}type Summary struct {@@ -63,8 +87,10 @@ type Summary struct {}type ResourceBase struct {- Kind string `json:"kind"`- Path string `json:"path"`+ Kind string `json:"kind"`+ Path string `json:"path,omitempty"`+ URL string `json:"url,omitempty"`+ Description string `json:"description,omitempty"`}type Value struct {@@ -81,10 +107,15 @@ type Loaded struct {type Candidate struct {Summary- source skillRoot- root string- path string- base string+ source skillRoot+ root string+ path string+ base string+ loader func(context.Context) (Loaded, error)+ rank float64+ priority int+ presentation *CatalogSkill+ providerName string}type Snapshot struct {@@ -96,24 +127,25 @@ type skillRoot struct {path stringboundary stringskipSystem bool+ rank float64}func (r *Registry) roots(lookup Lookup) []skillRoot {var roots []skillRootif project, workspace := projectRoot(lookup); project != "" {roots = append(roots,- skillRoot{path: filepath.Join(project, ".dsh", "skills"), boundary: workspace},- skillRoot{path: filepath.Join(project, ".agents", "skills"), boundary: workspace},+ skillRoot{path: filepath.Join(project, ".dsh", "skills"), boundary: workspace, rank: 100},+ skillRoot{path: filepath.Join(project, ".agents", "skills"), boundary: workspace, rank: 200},)}for _, path := range r.CustomDirs {- roots = append(roots, skillRoot{path: path})+ roots = append(roots, skillRoot{path: path, rank: 300})}if r.DSHHome != "" {- roots = append(roots, skillRoot{path: filepath.Join(r.DSHHome, "skills"), boundary: r.DSHHome, skipSystem: true})+ roots = append(roots, skillRoot{path: filepath.Join(r.DSHHome, "skills"), boundary: r.DSHHome, skipSystem: true, rank: 400})}if r.AgentsHome != "" {- roots = append(roots, skillRoot{path: filepath.Join(r.AgentsHome, "skills"), boundary: r.AgentsHome})+ roots = append(roots, skillRoot{path: filepath.Join(r.AgentsHome, "skills"), boundary: r.AgentsHome, rank: 500})}return roots}@@ -164,6 +196,28 @@ func (r *Registry) Snapshot(ctx context.Context, lookup Lookup) (Snapshot, error}}}+ if r.Providers != nil {+ providers, err := r.Providers(ctx, lookup)+ if err != nil {+ return Snapshot{}, err+ }+ for _, provider := range providers {+ entries, err := provider.List(ctx, lookup)+ if err != nil {+ return Snapshot{}, fmt.Errorf("discover skill provider %s: %w", provider.Name, err)+ }+ snapshot.Complete = snapshot.Complete && entries.Complete+ for _, entry := range entries.Entries {+ if !IsName(entry.Name) || entry.Description == "" {+ return Snapshot{}, errors.New("skill provider returned an invalid summary")+ }+ if prior, exists := winners[entry.Name]; exists && (prior.priority > entry.Priority || (prior.priority == entry.Priority && prior.rank <= entry.Rank)) {+ continue+ }+ winners[entry.Name] = Candidate{Summary: entry.Summary, rank: entry.Rank, priority: entry.Priority, presentation: entry.Presentation, providerName: provider.Name, loader: func(ctx context.Context) (Loaded, error) { return provider.Load(ctx, lookup, entry) }}+ }+ }+ }for _, entry := range winners {snapshot.Entries = append(snapshot.Entries, entry)}@@ -193,6 +247,16 @@ func (c Candidate) Load(ctx context.Context) (Loaded, bool, error) {if err := ctx.Err(); err != nil {return Loaded{}, false, err}+ if c.loader != nil {+ loaded, err := c.loader(ctx)+ if errors.Is(err, os.ErrNotExist) {+ return Loaded{}, false, nil+ }+ if err == nil && (loaded.Name != c.Name || loaded.Value.Name != c.Name || len(loaded.Value.Content) > maxSkillBytes || loaded.Value.Provider == "") {+ return Loaded{}, false, errors.New("skill provider returned an invalid identity or content")+ }+ return loaded, err == nil, err+ }root, err := openSkillRoot(c.source)if err != nil {return Loaded{}, false, ctx.Err()@@ -303,7 +367,7 @@ func discover(ctx context.Context, source skillRoot) ([]Candidate, error) {if err != nil {return nil, err}- candidates = append(candidates, Candidate{Summary: loaded.Summary, source: source, root: root.Name(), path: locator, base: base})+ candidates = append(candidates, Candidate{Summary: loaded.Summary, source: source, root: root.Name(), path: locator, base: base, rank: source.rank})}return candidates, nil}diff --git a/harness/skills/registry_test.go b/harness/skills/registry_test.goindex 852a7d0..52053e6 100644--- a/harness/skills/registry_test.go+++ b/harness/skills/registry_test.go@@ -113,83 +113,3 @@ func TestDiscoveryPublishesPartialRootsAndFallsBack(t *testing.T) {t.Fatalf("recovered discovery: %+v, %v", snapshot, err)}}--func TestBootstrapPreservesExistingEditsAndDeletion(t *testing.T) {- for _, existing := range []bool{false, true} {- t.Run(map[bool]string{false: "fresh", true: "user override"}[existing], func(t *testing.T) {- ctx := context.Background()- data := t.TempDir()- seed := t.TempDir()- write(t, filepath.Join(seed, "officecli/SKILL.md"), document("officecli", "", "Official body"))- write(t, filepath.Join(seed, "officecli-docx/SKILL.md"), document("officecli-docx", "", "Word"))- write(t, filepath.Join(seed, "officecli-docx/reference/template.md"), "Template")- browser := filepath.Join(data, ".dsh/skills/agent-browser/SKILL.md")- write(t, filepath.Join(seed, "agent-browser/SKILL.md"), document("agent-browser", "", "Browser"))- destination := filepath.Join(data, ".dsh/skills/officecli/SKILL.md")- expected := "Official body"- if existing {- destination = filepath.Join(data, ".agents/skills/my-office.md")- expected = "User body"- write(t, destination, document("officecli", "", expected))- }- if err := Bootstrap(ctx, data, seed); err != nil {- t.Fatal(err)- }- if asset, err := os.ReadFile(filepath.Join(data, ".dsh/skills/officecli-docx/reference/template.md")); err != nil || string(asset) != "Template" {- t.Fatalf("specialized bundle asset: %s, %v", asset, err)- }- if content, err := os.ReadFile(browser); err != nil || !strings.Contains(string(content), "Browser") {- t.Fatalf("browser skill: %s, %v", content, err)- }- if content, err := os.ReadFile(destination); err != nil || !strings.Contains(string(content), expected) {- t.Fatalf("installed skill: %s, %v", content, err)- }- if existing {- if _, err := os.Stat(filepath.Join(data, ".dsh/skills/officecli/SKILL.md")); !os.IsNotExist(err) {- t.Fatalf("existing shared skill was shadowed: %v", err)- }- }- write(t, destination, document("officecli", "", "Edited body"))- if err := Bootstrap(ctx, data, seed); err != nil {- t.Fatal(err)- }- if content, err := os.ReadFile(destination); err != nil || !strings.Contains(string(content), "Edited body") {- t.Fatalf("edited skill: %s, %v", content, err)- }- if err := os.Remove(destination); err != nil {- t.Fatal(err)- }- if err := os.Remove(browser); err != nil {- t.Fatal(err)- }- if err := Bootstrap(ctx, data, seed); err != nil {- t.Fatal(err)- }- if _, err := os.Stat(destination); !os.IsNotExist(err) {- t.Fatalf("removed skill reappeared: %v", err)- }- if _, err := os.Stat(browser); !os.IsNotExist(err) {- t.Fatalf("removed browser skill reappeared: %v", err)- }- })- }-}--func TestBootstrapAddsBrowserToPreviouslySeededData(t *testing.T) {- data, seed := t.TempDir(), t.TempDir()- write(t, filepath.Join(data, legacyOfficeMarker), "")- write(t, filepath.Join(seed, "officecli/SKILL.md"), document("officecli", "", "Deleted by user"))- write(t, filepath.Join(seed, "agent-browser/SKILL.md"), document("agent-browser", "", "Browser"))- if err := Bootstrap(context.Background(), data, seed); err != nil {- t.Fatal(err)- }- if _, err := os.Stat(filepath.Join(data, ".dsh/skills/officecli/SKILL.md")); !os.IsNotExist(err) {- t.Fatalf("deleted OfficeCLI skill reappeared: %v", err)- }- if _, err := os.Stat(filepath.Join(data, ".dsh/skills/agent-browser/SKILL.md")); err != nil {- t.Fatalf("browser skill missing: %v", err)- }- if _, err := os.Stat(filepath.Join(data, seedMarker)); err != nil {- t.Fatalf("skill initialization marker missing: %v", err)- }-}diff --git a/harness/skills/seed.go b/harness/skills/seed.godeleted file mode 100644index 9e81d19..0000000--- a/harness/skills/seed.go+++ /dev/null@@ -1,230 +0,0 @@-package skills--import (- "context"- "errors"- "fmt"- "io"- "io/fs"- "os"- "path/filepath"- "slices"- "syscall"-- "github.com/google/uuid"-)--const seedMarker = ".dsh/.skills-seeded"-const legacyOfficeMarker = ".dsh/.officecli-seeded"--// Bootstrap installs the image's initial skills after the runtime has verified-// the Host data directory.-func Bootstrap(ctx context.Context, dataRoot, seedDir string) error {- dataRoot, err := filepath.EvalSymlinks(dataRoot)- if err != nil {- return err- }- root, err := os.OpenRoot(dataRoot)- if err != nil {- return err- }- defer root.Close()- for _, directory := range []string{".dsh", ".dsh/skills", ".agents", ".agents/skills"} {- if err := ensureDir(root, directory); err != nil {- return err- }- }- marker, err := root.Lstat(seedMarker)- switch {- case err == nil && marker.Mode().IsRegular():- return nil- case err == nil:- return errors.New("skill initialization marker must be a regular file")- case !errors.Is(err, os.ErrNotExist):- return err- }-- legacyMarker, err := root.Lstat(legacyOfficeMarker)- if err != nil && !errors.Is(err, os.ErrNotExist) {- return err- }- officeAlreadySeeded := err == nil && legacyMarker.Mode().IsRegular()-- registry := Registry{DSHHome: filepath.Join(dataRoot, ".dsh"), AgentsHome: filepath.Join(dataRoot, ".agents")}- snapshot, err := registry.Snapshot(ctx, Lookup{})- if err != nil {- return err- }- if !snapshot.Complete {- return errors.New("cannot check existing user skills")- }- installed := make(map[string]Candidate, len(snapshot.Entries))- for _, entry := range snapshot.Entries {- installed[entry.Name] = entry- }-- seedDir, err = filepath.EvalSymlinks(seedDir)- if err != nil {- return err- }- seed, err := os.OpenRoot(seedDir)- if err != nil {- return err- }- defer seed.Close()- bundles, err := fs.ReadDir(seed.FS(), ".")- if err != nil {- return err- }- if len(bundles) == 0 {- return errors.New("Host image contains no seed skills")- }- for _, bundle := range bundles {- if err := ctx.Err(); err != nil {- return err- }- name := bundle.Name()- if !bundle.IsDir() || !IsName(name) {- return fmt.Errorf("invalid image skill bundle %q", name)- }- // Older data roots seeded OfficeCLI already. Seed only the browser- // skill so previously deleted OfficeCLI skills stay deleted.- if officeAlreadySeeded && name != "agent-browser" {- continue- }- loaded, err := load(seed, filepath.Join(name, "SKILL.md"), name)- if err != nil || loaded.Name != name {- return fmt.Errorf("invalid image skill %q", name)- }- if entry, ok := installed[name]; ok {- // A previous startup may have stopped after publishing this bundle.- for _, directory := range []string{filepath.Dir(filepath.Join(entry.root, entry.path)), entry.root} {- directory, err := filepath.EvalSymlinks(directory)- if err != nil {- return err- }- relative, err := filepath.Rel(dataRoot, directory)- if err != nil {- return err- }- if err := syncDir(root, relative); err != nil {- return err- }- }- continue- }- if err := installBundle(ctx, root, seed, name); err != nil {- return fmt.Errorf("install image skill %q: %w", name, err)- }- }- return publishMarker(root)-}--func installBundle(ctx context.Context, root, seed *os.Root, name string) error {- source, err := seed.OpenRoot(name)- if err != nil {- return err- }- defer source.Close()-- stage := ".dsh/.skill-stage-" + uuid.NewString()- if err := root.Mkdir(stage, 0700); err != nil {- return err- }- defer root.RemoveAll(stage)- var dirs []string- err = fs.WalkDir(source.FS(), ".", func(path string, entry fs.DirEntry, err error) error {- if err != nil {- return err- }- if err := ctx.Err(); err != nil {- return err- }- target := filepath.Join(stage, filepath.FromSlash(path))- if entry.IsDir() {- dirs = append(dirs, target)- if path == "." {- return nil- }- return root.Mkdir(target, 0700)- }- info, err := entry.Info()- if err != nil {- return err- }- if !info.Mode().IsRegular() {- return fmt.Errorf("unsupported skill bundle resource %q", path)- }- file, err := source.Open(filepath.FromSlash(path))- if err != nil {- return err- }- defer file.Close()- return writeFile(root, target, file, 0600|info.Mode().Perm()&0100)- })- if err != nil {- return err- }- for _, path := range slices.Backward(dirs) {- if err := syncDir(root, path); err != nil {- return err- }- }- destination := filepath.Join(".dsh/skills", name)- if _, err := root.Lstat(destination); err == nil {- // Preserve a user directory whose entry is invalid or has another name.- destination += "-" + uuid.NewString()- } else if !errors.Is(err, os.ErrNotExist) {- return err- }- if err := root.Rename(stage, destination); err != nil {- return err- }- return errors.Join(syncDir(root, ".dsh/skills"), syncDir(root, ".dsh"))-}--func ensureDir(root *os.Root, path string) error {- if err := root.Mkdir(path, 0700); err != nil && !errors.Is(err, os.ErrExist) {- return err- }- info, err := root.Lstat(path)- if err != nil {- return err- }- if !info.IsDir() {- return fmt.Errorf("%s must be a real directory", path)- }- return syncDir(root, filepath.Dir(path))-}--func publishMarker(root *os.Root) error {- stage := ".dsh/.skills-marker-" + uuid.NewString()- if err := writeFile(root, stage, nil, 0600); err != nil {- return err- }- defer root.Remove(stage)- if err := root.Link(stage, seedMarker); err != nil {- return err- }- return syncDir(root, ".dsh")-}--func writeFile(root *os.Root, path string, data io.Reader, mode os.FileMode) error {- file, err := root.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY|syscall.O_NONBLOCK, mode)- if err != nil {- return err- }- var writeErr error- if data != nil {- _, writeErr = io.Copy(file, data)- }- return errors.Join(writeErr, file.Sync(), file.Close())-}--func syncDir(root *os.Root, path string) error {- directory, err := root.Open(path)- if err != nil {- return err- }- return errors.Join(directory.Sync(), directory.Close())-}diff --git a/harness/tools/jobs.go b/harness/tools/jobs.goindex db5cf43..9fab120 100644--- a/harness/tools/jobs.go+++ b/harness/tools/jobs.go@@ -6,16 +6,52 @@ import ("errors""fmt""math"+ "strings""time""go-bot/harness/agent""go-bot/harness/jobs"+ "go-bot/harness/output"+ "go-bot/internal/modeldata")type JobOutput struct{ Registry *jobs.Registry }type JobList struct{ Registry *jobs.Registry }type JobKill struct{ Registry *jobs.Registry }+func (JobOutput) RetainsOutput() bool { return true }+func (JobKill) RetainsOutput() bool { return true }++func (t JobOutput) PrepareOutput(raw json.RawMessage) func(modeldata.ToolResult) modeldata.ToolResult {+ return prepareJobOutput(t.Registry, raw, true)+}+func (t JobKill) PrepareOutput(raw json.RawMessage) func(modeldata.ToolResult) modeldata.ToolResult {+ return prepareJobOutput(t.Registry, raw, false)+}+func prepareJobOutput(registry *jobs.Registry, raw json.RawMessage, hasStatusSuffix bool) func(modeldata.ToolResult) modeldata.ToolResult {+ var args struct {+ JobID string `json:"job_id"`+ }+ if registry == nil || json.Unmarshal(raw, &args) != nil {+ return nil+ }+ limit, exists := registry.OutputLimit(args.JobID)+ if !exists {+ return nil+ }+ return func(result modeldata.ToolResult) modeldata.ToolResult {+ suffix := ""+ text := result.Content+ if hasStatusSuffix && !result.IsError {+ if index := strings.LastIndex(text, "\njob_id="); index >= 0 {+ text, suffix = text[:index], text[index:]+ }+ }+ result.Content = output.FitTail(text, suffix, limit)+ return result+ }+}+type jobOutputArgs struct {JobID string `json:"job_id"`Wait bool `json:"wait"`@@ -69,7 +105,7 @@ func (t JobOutput) Execute(ctx context.Context, raw json.RawMessage) (string, erif output.Job.Status == jobs.Completed || output.Job.Status == jobs.Failed || output.Job.Status == jobs.Killed {t.Registry.SuppressNotice(args.JobID)}- return fmt.Sprintf("job_id=%s status=%s exit_code=%d lossy=%t next_cursor=%d\n%s", output.Job.ID, output.Job.Status, output.Job.ExitCode, output.Lossy, output.Cursor, output.Text), nil+ return fmt.Sprintf("%s\njob_id=%s status=%s exit_code=%d lossy=%t next_cursor=%d", output.Text, output.Job.ID, output.Job.Status, output.Job.ExitCode, output.Lossy, output.Cursor), nil}func (JobList) Spec() agent.ToolSpec {diff --git a/harness/tools/jobs_output_test.go b/harness/tools/jobs_output_test.gonew file mode 100644index 0000000..5285971--- /dev/null+++ b/harness/tools/jobs_output_test.go@@ -0,0 +1,33 @@+package tools++import (+ "context"+ "encoding/json"+ "strings"+ "testing"++ "go-bot/harness/jobs"+ "go-bot/internal/modeldata"+)++func TestJobOutputFinalizerCapturesLimitBeforeConsumption(t *testing.T) {+ registry, err := jobs.New(t.Context(), 1, 256, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer registry.Close(context.Background())+ snapshot, err := registry.Start("test", "bounded", func(context.Context, func([]byte)) (int, error) { return 0, nil })+ if err != nil {+ t.Fatal(err)+ }+ raw, _ := json.Marshal(map[string]string{"job_id": snapshot.ID})+ process := (JobOutput{Registry: registry}).PrepareOutput(raw)+ if process == nil {+ t.Fatal("PreExecute did not capture Job output policy")+ }+ suffix := "\njob_id=" + snapshot.ID + " status=completed exit_code=0 lossy=false next_cursor=999"+ result := process(modeldata.ToolResult{Content: strings.Repeat("output\n", 1000) + suffix})+ if len(result.Content) > 256 || !strings.HasSuffix(result.Content, suffix) {+ t.Fatalf("status was lost: %q", result.Content)+ }+}diff --git a/harness/tools/native_structured_output.go b/harness/tools/native_structured_output.goindex 859a016..e9dad08 100644--- a/harness/tools/native_structured_output.go+++ b/harness/tools/native_structured_output.go@@ -14,9 +14,11 @@ const NativeStructuredOutputInstruction = "When you have your final answer, you// NativeStructuredOutput is scoped to one workflow child activation. It is// never installed on a resumed child or shared across sibling Sessions.type NativeStructuredOutput struct {- schema json.RawMessage- mu sync.Mutex- value json.RawMessage+ schema json.RawMessage+ mu sync.Mutex+ value json.RawMessage+ pending json.RawMessage+ callID string}func NewNativeStructuredOutput(schema map[string]any) (*NativeStructuredOutput, error) {@@ -43,14 +45,29 @@ func (*NativeStructuredOutput) Validate(json.RawMessage) error { return nil }func (t *NativeStructuredOutput) Execute(ctx context.Context, raw json.RawMessage) (string, error) {t.mu.Lock()defer t.mu.Unlock()- if t.value != nil {+ if t.value != nil || t.pending != nil {return "", errors.New("structured output was already recorded")}- t.value = append(json.RawMessage(nil), raw...)+ t.pending = append(json.RawMessage(nil), raw...)+ t.callID, _ = agent.ToolCallIDFromContext(ctx)agent.ConcludeTurn(ctx)return "Structured output recorded.", nil}+// SettleResult runs in Go's Result phase, after the ordered journal flush.+// Rejected output or a failed commit must not become a workflow result.+func (t *NativeStructuredOutput) SettleResult(callID string, success bool) {+ t.mu.Lock()+ defer t.mu.Unlock()+ if t.pending == nil || t.callID != callID {+ return+ }+ if success {+ t.value = t.pending+ }+ t.pending, t.callID = nil, ""+}+func (t *NativeStructuredOutput) Captured() (any, bool) {t.mu.Lock()defer t.mu.Unlock()diff --git a/harness/tools/native_structured_output_test.go b/harness/tools/native_structured_output_test.gonew file mode 100644index 0000000..8679a6b--- /dev/null+++ b/harness/tools/native_structured_output_test.go@@ -0,0 +1,89 @@+package tools++import (+ "context"+ "encoding/json"+ "errors"+ "testing"++ "go-bot/harness/agent"+ sessionformat "go-bot/harness/session"+ "go-bot/internal/modeldata"+)++type structuredResultModel struct{ calls int }++func (m *structuredResultModel) Complete(context.Context, []agent.Message, []agent.ToolSpec) (modeldata.AssistantMessage, error) {+ m.calls+++ if m.calls == 1 {+ return modeldata.AssistantMessage{ToolCalls: []modeldata.ToolRequest{{ID: "answer", Name: "structured_output", Arguments: `{"answer":42}`}}}, nil+ }+ return modeldata.AssistantMessage{Content: "done"}, nil+}++type structuredResultJournal struct {+ nativeTodoJournal+ tool *NativeStructuredOutput+ fail bool+ sawResult bool+ t *testing.T+}++func (j *structuredResultJournal) Append(ctx context.Context, events []sessionformat.Event) error {+ for _, event := range events {+ if event.Type == "tool/result" {+ j.sawResult = true+ if _, ok := j.tool.Captured(); ok {+ j.t.Error("structured output confirmed before durable result commit")+ }+ if j.fail {+ return errors.New("result journal unavailable")+ }+ }+ }+ return j.nativeTodoJournal.Append(ctx, events)+}+func TestStructuredOutputConfirmsOnlyFinalDurablyCommittedSuccess(t *testing.T) {+ for _, mode := range []string{"success", "post-block", "commit-failure"} {+ t.Run(mode, func(t *testing.T) {+ tool, err := NewNativeStructuredOutput(map[string]any{"type": "object", "properties": map[string]any{"answer": map[string]any{"type": "integer"}}, "required": []string{"answer"}})+ if err != nil {+ t.Fatal(err)+ }+ journal := &structuredResultJournal{tool: tool, t: t, fail: mode == "commit-failure"}+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "structured-" + mode, CreatedAt: 1, CWD: t.TempDir()}, journal)+ if err != nil {+ t.Fatal(err)+ }+ loop, err := agent.NewNativeLoop(live, &structuredResultModel{}, "p", "m", "prompt", []agent.Tool{tool}, 3, 3)+ if err != nil {+ t.Fatal(err)+ }+ if mode == "post-block" {+ loop.SetToolInvocationSource(func(context.Context, string) (agent.ToolInvocationFactory, error) {+ return func(ctx context.Context, execution agent.ToolExecution, dispatch func(context.Context) modeldata.ToolResult, approve func(context.Context, agent.ToolPolicyAsk) error) (*agent.ToolInvocation, error) {+ return agent.NewToolInvocation(ctx, execution, agent.ToolPipelineProcessors{PostExecute: func(context.Context, agent.ToolPipelineResult) (agent.PostToolDecision, error) {+ return agent.PostToolDecision{Kind: "block", Feedback: []json.RawMessage{json.RawMessage(`{"type":"text","text":"result rejected"}`)}}, nil+ }}, func(ctx context.Context) (agent.ToolPipelineResult, error) {+ return agent.EncodeToolPipelineResult(dispatch(ctx))+ }, approve), nil+ }, nil+ })+ }+ _, err = loop.RunTextTurn(t.Context(), "Return the structured answer")+ if (err != nil) != (mode == "commit-failure") {+ t.Fatalf("run error=%v", err)+ }+ value, captured := tool.Captured()+ if !journal.sawResult || captured != (mode == "success") {+ t.Fatalf("result attempted=%v captured=%v value=%v", journal.sawResult, captured, value)+ }+ if captured && value.(map[string]any)["answer"] != float64(42) {+ t.Fatalf("value=%v", value)+ }+ if mode != "success" && tool.pending != nil {+ t.Fatal("provisional state survived rejection or commit failure")+ }+ })+ }+}diff --git a/harness/tools/search_rg.go b/harness/tools/search_rg.goindex c15c296..1528fec 100644--- a/harness/tools/search_rg.go+++ b/harness/tools/search_rg.go@@ -16,12 +16,12 @@ import ("unicode/utf8""go-bot/harness/agent"+ "go-bot/harness/output")const (rgRawLimit = 20_000_000rgStderrLimit = 64 << 10- rgOutputLimit = 512 << 10rgGlobMaxResults = 100rgGrepMaxMatches = 250rgGrepLineBytes = 2000@@ -38,6 +38,8 @@ type RipgrepSearch struct {Binary string // empty selects the ripgrep binary from PATH}+func (RipgrepSearch) RetainsOutput() bool { return true }+type searchArgs struct {Pattern string `json:"pattern"`Path *string `json:"path"`@@ -239,19 +241,20 @@ func (t RipgrepSearch) renderGlob(raw []byte) (string, error) {if len(paths) == 0 {return "No files found", nil}+ full := strings.Join(paths, "\n")shown := min(len(paths), rgGlobMaxResults)- for shown > 0 && len(strings.Join(paths[:shown], "\n")) > rgOutputLimit {+ if shown == len(paths) && output.Estimate(full) <= output.InlineTokens {+ return full, nil+ }+ fullPath := t.spill("glob-results-*.txt", full)+ for {+ footer := fmt.Sprintf("\n\n(Showing %d of %d paths. %s)", shown, len(paths), spillHint(fullPath, "Narrow pattern or path to see more."))+ preview := strings.Join(paths[:shown], "\n") + footer+ if output.Estimate(preview) <= output.InlineTokens || shown == 0 {+ return preview, nil+ }shown--}- if shown == 0 {- return "", &SearchToolError{Code: "SEARCH_FAILED", Err: errors.New("glob path exceeds result limit")}- }- if shown == len(paths) {- return strings.Join(paths, "\n"), nil- }- fullPath := t.spill("glob-results-*.txt", strings.Join(paths, "\n"))- footer := fmt.Sprintf("\n\n(Showing %d of %d paths. %s)", shown, len(paths), spillHint(fullPath, "Narrow pattern or path to see more."))- return strings.Join(paths[:shown], "\n") + footer, nil}type rgJSONText struct {@@ -305,19 +308,19 @@ func (t RipgrepSearch) renderGrep(raw []byte) (string, error) {if len(matches) == 0 {return "No matches found", nil}- full := formatGrep(matches)+ full := fmt.Sprintf("Found %d matches\n\n%s", len(matches), formatGrep(matches))shown := min(len(matches), rgGrepMaxMatches)- for shown > 0 && len(formatGrep(matches[:shown])) > rgOutputLimit {+ if shown == len(matches) && output.Estimate(full) <= output.InlineTokens {+ return full, nil+ }+ fullPath := t.spill("grep-results-*.txt", full)+ for {+ preview := fmt.Sprintf("Found %d of %d matches\n\n%s\n\n(%s)", shown, len(matches), formatGrep(matches[:shown]), spillHint(fullPath, "Narrow pattern, path, or include to see more."))+ if output.Estimate(preview) <= output.InlineTokens || shown == 0 {+ return preview, nil+ }shown--}- if shown == 0 {- return "", &SearchToolError{Code: "SEARCH_FAILED", Err: errors.New("grep match exceeds result limit")}- }- if shown == len(matches) {- return fmt.Sprintf("Found %d matches\n\n%s", len(matches), full), nil- }- fullPath := t.spill("grep-results-*.txt", fmt.Sprintf("Found %d matches\n\n%s", len(matches), full))- return fmt.Sprintf("Found %d of %d matches\n\n%s\n\n(%s)", shown, len(matches), formatGrep(matches[:shown]), spillHint(fullPath, "Narrow pattern, path, or include to see more.")), nil}func formatGrep(matches []grepMatch) string {diff --git a/harness/tools/skill.go b/harness/tools/skill.goindex 94e37ad..7d079fa 100644--- a/harness/tools/skill.go+++ b/harness/tools/skill.go@@ -81,7 +81,14 @@ var skillAttribute = strings.NewReplacer("&", "&", "\"", """, "<", "<func RenderSkillContent(value skills.Value) string {resources := fmt.Sprintf("Resources for this skill are managed by provider \"%s\".\nLoad referenced resources only as needed.", skills.EscapeText(value.Provider))if value.ResourceBase != nil {- resources = fmt.Sprintf("Base directory for this skill: %s\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.", skills.EscapeText(value.ResourceBase.Path))+ switch value.ResourceBase.Kind {+ case "directory":+ resources = fmt.Sprintf("Base directory for this skill: %s\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.", skills.EscapeText(value.ResourceBase.Path))+ case "url":+ resources = fmt.Sprintf("Base URL for this skill: %s\nResolve relative URLs mentioned by this skill against the base URL before using them. Load referenced resources only as needed.", skills.EscapeText(value.ResourceBase.URL))+ case "opaque":+ resources = fmt.Sprintf("Resources for this skill: %s\nLoad referenced resources only as needed.", skills.EscapeText(value.ResourceBase.Description))+ }}return fmt.Sprintf("<skill_content name=\"%s\">\n<skill_resources>\n%s\n</skill_resources>\n\n<skill_instructions>\n%s\n</skill_instructions>\n</skill_content>",skillAttribute.Replace(value.Name), resources, value.Content)diff --git a/harness/tools/skill_test.go b/harness/tools/skill_test.goindex 6a7f8eb..9912c93 100644--- a/harness/tools/skill_test.go+++ b/harness/tools/skill_test.go@@ -51,3 +51,22 @@ func TestSkillStructuredResultAndPolicy(t *testing.T) {}}}++func TestSkillRendersProviderResourceBasesInTheModelInstructions(t *testing.T) {+ for _, test := range []struct {+ name string+ base *skills.ResourceBase+ want string+ }{+ {"url", &skills.ResourceBase{Kind: "url", URL: "https://example.com/skills/?a=1&b=2"}, "Base URL for this skill: https://example.com/skills/?a=1&b=2\nResolve relative URLs"},+ {"opaque", &skills.ResourceBase{Kind: "opaque", Description: "Use provider <documents>"}, "Resources for this skill: Use provider <documents>"},+ {"none", nil, "Resources for this skill are managed by provider \"example\"."},+ } {+ t.Run(test.name, func(t *testing.T) {+ result := RenderSkillContent(skills.Value{Name: "remote-skill", Provider: "example", ResourceBase: test.base, Content: "Original instructions"})+ if !strings.Contains(result, test.want) || !strings.Contains(result, "<skill_instructions>\nOriginal instructions\n</skill_instructions>") {+ t.Fatalf("model-facing provider instructions lost their resource base: %s", result)+ }+ })+ }+}diff --git a/harness/tools/web.go b/harness/tools/web.goindex 665b605..397142c 100644--- a/harness/tools/web.go+++ b/harness/tools/web.go@@ -42,6 +42,8 @@ func (WebFetch) Validate(raw json.RawMessage) error {return err}+func (WebFetch) RetainsOutput() bool { return true }+func (t WebFetch) Execute(ctx context.Context, raw json.RawMessage) (string, error) {value, err := t.ExecuteValue(ctx, raw)if err != nil {diff --git a/harness/tools/web_spill.go b/harness/tools/web_spill.goindex 4642535..e4bc7ee 100644--- a/harness/tools/web_spill.go+++ b/harness/tools/web_spill.go@@ -2,87 +2,17 @@ package toolsimport ("context"- "crypto/rand"- "encoding/hex"- "errors"- "fmt"- "io"- "os"- "path/filepath"- "unicode/utf16"- "unicode/utf8"+ "go-bot/harness/output"+ "log/slog")-const webInlineTokens = 12_500+const webInlineTokens = output.InlineTokens-// retainWebText applies the shared upstream text-only spill policy at the-// Host tool-result boundary. The full rendering stays readable in the workspace.+func webTextTokens(text string) int { return output.Estimate(text) }func retainWebText(ctx context.Context, workdir, name, text string) string {- if workdir == "" || webTextTokens(text) <= webInlineTokens || ctx.Err() != nil {- return text- }- locator, err := saveWebText(workdir, name, text)+ retained, err := output.RetainText(ctx, workdir, ".agent/web-spill", name, text, webInlineTokens)if err != nil {- return text- }- const gap = "\n\n[...]\n\n"- notice := func(omitted int) string {- return fmt.Sprintf("(Omitted %d bytes. Full formatted result stored at: %s. Use read with offset/limit, or grep this path to search within it.)", omitted, locator)- }- worstNotice := notice(len(text))- if webTextTokens(worstNotice) > webInlineTokens {- return text- }- available := max(0, webInlineTokens-webTextTokens(gap)-webTextTokens("\n\n"+worstNotice))- headBudget := max(0, ((available+1)/2-4)*4)- tailBudget := max(0, (available/2-4)*4)- head := truncateUTF16(text, headBudget)- tail := suffixUTF16(text[len(head):], tailBudget)- footer := notice(len(text) - len(head) - len(tail))- if head == "" && tail == "" {- return footer- }- return head + gap + tail + "\n\n" + footer-}--func webTextTokens(text string) int { return (utf16Length(text)+3)/4 + 4 }--func suffixUTF16(text string, maxChars int) string {- chars := 0- for i := len(text); i > 0; {- r, bytes := utf8.DecodeLastRuneInString(text[:i])- chars += utf16.RuneLen(r)- if chars > maxChars {- return text[i:]- }- i -= bytes- }- return text-}--func saveWebText(workdir, name, text string) (string, error) {- root, err := os.OpenRoot(workdir)- if err != nil {- return "", err- }- defer root.Close()- const dir = ".agent/web-spill"- if err := root.MkdirAll(dir, 0o700); err != nil {- return "", err- }- var id [6]byte- if _, err := rand.Read(id[:]); err != nil {- return "", err- }- path := filepath.Join(dir, hex.EncodeToString(id[:])+"-"+name+".txt")- file, err := root.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)- if err != nil {- return "", err- }- _, writeErr := io.WriteString(file, text)- if err := errors.Join(writeErr, file.Sync(), file.Close()); err != nil {- _ = root.Remove(path)- return "", err+ slog.Warn("tool output retention unavailable", "tool", name, "error", err)}- return filepath.Join(workdir, path), nil+ return retained}diff --git a/harness/tools/websearch.go b/harness/tools/websearch.goindex 8d84f7b..bead382 100644--- a/harness/tools/websearch.go+++ b/harness/tools/websearch.go@@ -23,6 +23,8 @@ type WebSearch struct {SpillWorkdir string}+func (WebSearch) RetainsOutput() bool { return true }+const (webSearchMaxQueries = 10webSearchMaxResults = 10diff --git a/internal/authorization/callback.go b/internal/authorization/callback.gonew file mode 100644index 0000000..9f6b351--- /dev/null+++ b/internal/authorization/callback.go@@ -0,0 +1,140 @@+package authorization++import (+ "context"+ "crypto/subtle"+ "encoding/json"+ "net"+ "net/url"+ "strings"++ "github.com/google/uuid"+)++type callbackBaseKey struct{}++// WithCallbackBase is called by the authenticated Controller-to-Host adapter.+// A business plugin cannot select another account or an arbitrary HTTP route.+func WithCallbackBase(ctx context.Context, base string) context.Context {+ return context.WithValue(ctx, callbackBaseKey{}, base)+}+func callbackBase(ctx context.Context) string {+ value, _ := ctx.Value(callbackBaseKey{}).(string)+ return value+}++type surfaceCallback struct {+ token, state, url string+ ready chan struct{}+ query map[string][]string+}++func (s *Surface) prepareCallback(ctx context.Context, a *surfaceAttempt, state string) (string, error) {+ if err := ctx.Err(); err != nil {+ return "", err+ }+ if state == "" || len(state) > 1024 || strings.ContainsAny(state, "\x00\r\n") {+ return "", failure("INVALID_CALLBACK", "Provide the provider library's expected authorization state")+ }+ u, err := url.Parse(a.callbackBase)+ if err != nil || u == nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || !strings.HasSuffix(u.Path, "/") || len(a.callbackBase) > 4096 {+ return "", failure("CALLBACK_UNAVAILABLE", "Browser authorization requires a verified Controller callback through HTTPS or localhost HTTP")+ }+ loopback := strings.EqualFold(u.Hostname(), "localhost") || net.ParseIP(u.Hostname()).IsLoopback()+ if u.Scheme != "https" && !(u.Scheme == "http" && loopback) {+ return "", failure("CALLBACK_UNAVAILABLE", "Browser authorization requires HTTPS or localhost HTTP")+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ if a.ctx.Err() != nil || a.view.Status != "running" {+ return "", context.Canceled+ }+ if a.callback != nil {+ if a.callback.state != state {+ return "", failure("CALLBACK_CONFLICT", "This authorization attempt already has a callback")+ }+ return a.callback.url, nil+ }+ token := uuid.NewString()+ a.callback = &surfaceCallback{token: token, state: state, url: a.callbackBase + token, ready: make(chan struct{})}+ return a.callback.url, nil+}++func (s *Surface) waitCallback(ctx context.Context, a *surfaceAttempt) (map[string][]string, error) {+ s.mu.Lock()+ callback := a.callback+ s.mu.Unlock()+ if callback == nil {+ return nil, failure("CALLBACK_UNAVAILABLE", "Create an authorization callback before waiting for it")+ }+ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-a.ctx.Done():+ return nil, a.ctx.Err()+ case <-callback.ready:+ }+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ if a.ctx.Err() != nil || a.callback != callback || a.view.Status != "running" {+ return nil, context.Canceled+ }+ query := make(map[string][]string, len(callback.query))+ for key, value := range callback.query {+ query[key] = append([]string(nil), value...)+ }+ return query, nil+}++// Receiving a callback is not proof of authorization. Only the business flow+// can validate its provider response, exchange tokens and commit a credential.+func (s *Surface) receiveCallback(token string, query map[string][]string) (any, error) {+ data, err := json.Marshal(query)+ if err != nil || len(data) > 24<<10 || len(query) > 64 || len(query["state"]) != 1 {+ return nil, failure("INVALID_CALLBACK", "Invalid authorization callback")+ }+ if _, err := uuid.Parse(token); err != nil {+ return nil, failure("INVALID_CALLBACK", "Invalid authorization callback")+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ for _, a := range s.attempts {+ c := a.callback+ if c == nil || c.token != token {+ continue+ }+ if a.ctx.Err() != nil || a.view.Status != "running" || c.query != nil || subtle.ConstantTimeCompare([]byte(c.state), []byte(query["state"][0])) != 1 {+ return nil, failure("INVALID_CALLBACK", "Authorization callback expired, was already used, or has an invalid state")+ }+ c.query = make(map[string][]string, len(query))+ for key, value := range query {+ c.query[key] = append([]string(nil), value...)+ }+ close(c.ready)+ return map[string]bool{"received": true}, nil+ }+ return nil, failure("INVALID_CALLBACK", "Authorization callback is no longer available")+}++func (a *Session) Callback(ctx context.Context, state string) (string, error) {+ if err := a.Context.Err(); err != nil {+ return "", err+ }+ if a.interaction.Callback == nil {+ return "", failure("CALLBACK_UNAVAILABLE", "This authorization surface does not provide browser callbacks")+ }+ return a.interaction.Callback(ctx, state)+}+func (a *Session) WaitCallback(ctx context.Context) (map[string][]string, error) {+ if a.interaction.WaitCallback == nil {+ return nil, failure("CALLBACK_UNAVAILABLE", "This authorization surface does not provide browser callbacks")+ }+ call, cancel := context.WithCancel(ctx)+ stop := context.AfterFunc(a.Context, cancel)+ defer stop()+ defer cancel()+ return a.interaction.WaitCallback(call)+}diff --git a/internal/authorization/callback_test.go b/internal/authorization/callback_test.gonew file mode 100644index 0000000..440cf5d--- /dev/null+++ b/internal/authorization/callback_test.go@@ -0,0 +1,158 @@+package authorization++import (+ "encoding/json"+ "net/url"+ "strings"+ "testing"+ "time"++ "go-bot/internal/credentials"+)++func TestCallbackIsBoundToAttemptAndDoesNotAuthorizeWithoutCommit(t *testing.T) {+ service, store := fixture(t)+ surface := NewSurface(t.Context(), service, nil)+ t.Cleanup(surface.Close)+ prepared := make(chan string, 1)+ received := make(chan map[string][]string, 1)+ commit := make(chan struct{})+ register(t, service, "mail/account", func(session *Session) error {+ address, err := session.Callback(session.Context, "library-generated-state")+ if err != nil {+ return err+ }+ prepared <- address+ query, err := session.WaitCallback(session.Context)+ if err != nil {+ return err+ }+ received <- query+ select {+ case <-commit:+ case <-session.Context.Done():+ return session.Context.Err()+ }+ return session.Commit(&credentials.Record{Kind: "grant", Payload: json.RawMessage(`{"access_token":"test-token-after-validation"}`)})+ })+ ctx := WithCallbackBase(t.Context(), "https://controller.example/v1/plugins/authorization/callback/alice/")+ result, err := surface.Handle(ctx, "start", json.RawMessage(`{"key":"mail/account"}`))+ if err != nil {+ t.Fatal(err)+ }+ view := result.(View)+ var address string+ select {+ case address = <-prepared:+ case <-time.After(3 * time.Second):+ t.Fatal("callback not prepared")+ }+ u, err := url.Parse(address)+ if err != nil {+ t.Fatal(err)+ }+ token := u.Path[strings.LastIndex(u.Path, "/")+1:]+ query := map[string][]string{"state": {"wrong"}, "code": {"test-code"}, "iss": {"https://provider.example"}}+ if _, err := surface.receiveCallback(token, query); err == nil {+ t.Fatal("accepted a foreign state")+ }+ query["state"][0] = "library-generated-state"+ if _, err := surface.receiveCallback(token, query); err != nil {+ t.Fatal(err)+ }+ if _, err := surface.receiveCallback(token, query); err == nil {+ t.Fatal("accepted callback replay")+ }+ select {+ case values := <-received:+ if values["code"][0] != "test-code" {+ t.Fatal(values)+ }+ case <-time.After(3 * time.Second):+ t.Fatal("plugin did not receive callback")+ }+ if record, err := store.ReadRecord("mail/account"); err != nil || record != nil {+ t.Fatal("callback receipt fabricated a credential", err)+ }+ current, err := surface.Handle(t.Context(), "get", json.RawMessage(`{"id":"`+view.ID+`"}`))+ if err != nil || current.(View).Status != "running" {+ t.Fatal("callback receipt fabricated success", current, err)+ }+ close(commit)+ deadline := time.Now().Add(3 * time.Second)+ for time.Now().Before(deadline) {+ current, _ = surface.Handle(t.Context(), "get", json.RawMessage(`{"id":"`+view.ID+`"}`))+ if current.(View).Status == "authorized" {+ break+ }+ time.Sleep(time.Millisecond)+ }+ if current.(View).Status != "authorized" {+ t.Fatalf("callback flow did not commit: %+v", current)+ }+ data, _ := json.Marshal(current)+ if strings.Contains(string(data), "test-code") || strings.Contains(string(data), "test-token-after-validation") {+ t.Fatal("private callback data entered the UI view")+ }+}++func TestCallbackCancellationWithdrawsPendingReceiver(t *testing.T) {+ service, store := fixture(t)+ surface := NewSurface(t.Context(), service, nil)+ t.Cleanup(surface.Close)+ prepared := make(chan string, 1)+ returned := make(chan error, 1)+ register(t, service, "mail/account", func(session *Session) error {+ address, err := session.Callback(session.Context, "expected-state")+ if err != nil {+ return err+ }+ prepared <- address+ _, err = session.WaitCallback(session.Context)+ returned <- err+ return err+ })+ ctx := WithCallbackBase(t.Context(), "http://localhost:8080/v1/plugins/authorization/callback/alice/")+ value, err := surface.Handle(ctx, "start", json.RawMessage(`{"key":"mail/account"}`))+ if err != nil {+ t.Fatal(err)+ }+ var address string+ select {+ case address = <-prepared:+ case <-time.After(3 * time.Second):+ t.Fatal("no callback")+ }+ attempt := value.(View)+ value, err = surface.Handle(t.Context(), "cancel", json.RawMessage(`{"id":"`+attempt.ID+`"}`))+ if err != nil || value.(View).Status != "cancelled" {+ t.Fatalf("cancel: %+v %v", value, err)+ }+ select {+ case err = <-returned:+ if err == nil {+ t.Fatal("wait reported success after cancellation")+ }+ case <-time.After(3 * time.Second):+ t.Fatal("callback wait leaked")+ }+ token := address[strings.LastIndex(address, "/")+1:]+ if _, err := surface.receiveCallback(token, map[string][]string{"state": {"expected-state"}, "code": {"late-code"}}); err == nil {+ t.Fatal("accepted callback after cancellation")+ }+ if record, err := store.ReadRecord("mail/account"); err != nil || record != nil {+ t.Fatal("cancel saved a credential", err)+ }+}++func TestCallbackRejectsUnverifiedOrigins(t *testing.T) {+ for _, base := range []string{"", "http://controller.example/callback/", "https://user:[email protected]/callback/", "https://controller.example/callback/?injected=1", "https://controller.example/callback/#fragment", "https://controller.example/callback"} {+ t.Run(base, func(t *testing.T) {+ surface := &Surface{}+ attempt := &surfaceAttempt{ctx: t.Context(), view: View{Status: "running"}, callbackBase: base}+ if _, err := surface.prepareCallback(t.Context(), attempt, "state"); err == nil {+ t.Fatal("accepted unverified callback base")+ }+ })+ }+}diff --git a/internal/authorization/native.go b/internal/authorization/native.gonew file mode 100644index 0000000..6dff9f8--- /dev/null+++ b/internal/authorization/native.go@@ -0,0 +1,45 @@+package authorization++import "context"++// Inspect consults the integration's native store, or the ordinary Go store.+// Integration callbacks always run outside the service mutex.+func (s *Service) Inspect(ctx context.Context, key string) (AccountState, error) {+ s.mu.Lock()+ f := s.flows[key]+ s.mu.Unlock()+ if f == nil {+ return AccountState{}, failure("NO_FLOW", "Authorization flow is unavailable")+ }+ if f.Inspect != nil {+ return f.Inspect(ctx)+ }+ info, err := s.store.DescribeRecord(key)+ return AccountState{Configured: info.Configured}, err+}+func (s *Service) Disconnect(ctx context.Context, key string) (AccountState, error) {+ s.mu.Lock()+ f := s.flows[key]+ if f == nil || f.Disconnect == nil {+ s.mu.Unlock()+ return AccountState{}, failure("NO_FLOW", "This integration does not support disconnect")+ }+ if s.running[key] != nil || s.disconnecting[key] {+ s.mu.Unlock()+ return AccountState{}, failure("ALREADY_IN_FLIGHT", "Authorization is already in progress")+ }+ s.disconnecting[key] = true+ s.mu.Unlock()+ defer func() { s.mu.Lock(); delete(s.disconnecting, key); s.mu.Unlock() }()+ if err := f.Disconnect(ctx); err != nil {+ return AccountState{}, err+ }+ state, err := s.Inspect(ctx, key)+ if err == nil && state.Configured {+ return state, failure("STILL_CONFIGURED", "The application still reports an authorized account")+ }+ if err == nil {+ s.settled(key, "disconnected")+ }+ return state, err+}diff --git a/internal/authorization/native_test.go b/internal/authorization/native_test.gonew file mode 100644index 0000000..199a0fd--- /dev/null+++ b/internal/authorization/native_test.go@@ -0,0 +1,74 @@+package authorization++import (+ "context"+ "errors"+ "sync/atomic"+ "testing"+)++func TestNativeAuthorizationDoesNotDuplicateCredentials(t *testing.T) {+ s, store := fixture(t)+ var configured atomic.Bool+ off, err := s.Register(Flow{Key: "native/account", Label: "Native CLI", Methods: []Method{{ID: "login", Label: "Sign in"}},+ Run: func(*Session) error { configured.Store(true); return nil },+ Inspect: func(context.Context) (AccountState, error) {+ return AccountState{Configured: configured.Load(), AccountLabel: "example"}, nil+ },+ Disconnect: func(context.Context) error { configured.Store(false); return nil },+ })+ if err != nil {+ t.Fatal(err)+ }+ defer off()+ result, err := s.Begin(t.Context(), "native/account", "login", Interaction{})+ if err != nil || result.Status != "authorized" {+ t.Fatal(result, err)+ }+ info, err := store.DescribeRecord("native/account")+ if err != nil || info.Configured {+ t.Fatal("native grant was copied into Go storage", info, err)+ }+ state, err := s.Inspect(t.Context(), "native/account")+ if err != nil || !state.Configured || state.AccountLabel != "example" {+ t.Fatal(state, err)+ }+ state, err = s.Disconnect(t.Context(), "native/account")+ if err != nil || state.Configured {+ t.Fatal(state, err)+ }+}+func TestNativeAuthorizationRequiresInspectConfirmation(t *testing.T) {+ s, _ := fixture(t)+ off, err := s.Register(Flow{Key: "native/account", Label: "Native", Methods: []Method{{ID: "login", Label: "Sign in"}}, Run: func(*Session) error { return nil }, Inspect: func(context.Context) (AccountState, error) { return AccountState{}, nil }})+ if err != nil {+ t.Fatal(err)+ }+ defer off()+ _, err = s.Begin(t.Context(), "native/account", "login", Interaction{})+ var detail *Error+ if !errors.As(err, &detail) || detail.Code != "NOT_CONFIGURED" {+ t.Fatal(err)+ }+}+func TestNativeDisconnectExcludesConcurrentLogin(t *testing.T) {+ s, _ := fixture(t)+ entered, release := make(chan struct{}), make(chan struct{})+ off, err := s.Register(Flow{Key: "native/account", Label: "Native", Methods: []Method{{ID: "login", Label: "Sign in"}}, Run: func(*Session) error { return nil }, Inspect: func(context.Context) (AccountState, error) { return AccountState{}, nil }, Disconnect: func(context.Context) error { close(entered); <-release; return nil }})+ if err != nil {+ t.Fatal(err)+ }+ defer off()+ done := make(chan error, 1)+ go func() { _, err := s.Disconnect(t.Context(), "native/account"); done <- err }()+ <-entered+ _, err = s.Begin(t.Context(), "native/account", "login", Interaction{})+ close(release)+ if final := <-done; final != nil {+ t.Fatal(final)+ }+ var detail *Error+ if !errors.As(err, &detail) || detail.Code != "ALREADY_IN_FLIGHT" {+ t.Fatal(err)+ }+}diff --git a/internal/authorization/service.go b/internal/authorization/service.gonew file mode 100644index 0000000..1f9136f--- /dev/null+++ b/internal/authorization/service.go@@ -0,0 +1,423 @@+// Package authorization owns the Host's channel-neutral credential acquisition+// lifecycle. Integrations provide protocol callbacks; credentials owns storage.+package authorization++import (+ "context"+ "errors"+ "fmt"+ "sync"+ "sync/atomic"++ "github.com/google/uuid"+ "go-bot/internal/credentials"+)++type Error struct{ Code, Message string }++func (e *Error) Error() string { return e.Message }+func failure(code, message string) error { return &Error{code, message} }++type Method struct {+ ID string `json:"id"`+ Label string `json:"label"`+}+type Notice struct {+ Message string `json:"message"`+ URL string `json:"url,omitempty"`+ Code string `json:"code,omitempty"`+}+type Option struct {+ ID string `json:"id"`+ Label string `json:"label"`+ Description string `json:"description,omitempty"`+}+type Prompt struct {+ Kind string `json:"kind"`+ Message string `json:"message"`+ Placeholder string `json:"placeholder,omitempty"`+ WebInput string `json:"webInput,omitempty"`+ Options []Option `json:"options,omitempty"`+}+type Interaction struct {+ Notify func(context.Context, Notice) error+ Prompt func(context.Context, Prompt) (string, error)+ Callback func(context.Context, string) (string, error)+ WaitCallback func(context.Context) (map[string][]string, error)+}+type AccountState struct {+ Configured bool `json:"configured"`+ AccountLabel string `json:"accountLabel,omitempty"`+}++type Flow struct {+ Key string `json:"key"`+ Label string `json:"label"`+ Methods []Method `json:"methods"`+ Run func(*Session) error `json:"-"`+ Inspect func(context.Context) (AccountState, error) `json:"-"`+ Disconnect func(context.Context) error `json:"-"`+}+type Entry struct {+ Key string `json:"key"`+ Label string `json:"label"`+ Methods []Method `json:"methods"`+ InFlight bool `json:"inFlight"`+ CanDisconnect bool `json:"canDisconnect"`+}+type Outcome struct {+ Status string `json:"status"`+}++type Service struct {+ store *credentials.Store+ mu sync.Mutex+ flows map[string]*Flow+ order []string+ running map[string]*Session+ disconnecting map[string]bool+ observers map[uint64]func(string, string)+ nextObserver uint64+}++func New(store *credentials.Store) *Service {+ return &Service{store: store, disconnecting: map[string]bool{}, flows: map[string]*Flow{}, running: map[string]*Session{}, observers: map[uint64]func(string, string){}}+}+func (s *Service) Register(flow Flow) (func(), error) {+ if !credentials.ValidKey(flow.Key) || flow.Label == "" || len(flow.Methods) == 0 || flow.Run == nil {+ return nil, failure("INVALID_FLOW", "A flow requires a credential key, label, methods and callback")+ }+ seen := map[string]bool{}+ for _, m := range flow.Methods {+ if m.ID == "" || m.Label == "" || seen[m.ID] {+ return nil, failure("INVALID_FLOW", "Invalid authorization methods")+ }+ seen[m.ID] = true+ }+ flow.Methods = append([]Method(nil), flow.Methods...)+ s.mu.Lock()+ if s.flows[flow.Key] != nil {+ s.mu.Unlock()+ return nil, failure("DUPLICATE_FLOW", "This credential already has an authorization flow")+ }+ s.flows[flow.Key] = &flow+ s.order = append(s.order, flow.Key)+ s.mu.Unlock()+ var once sync.Once+ return func() {+ once.Do(func() {+ s.mu.Lock()+ if s.flows[flow.Key] == &flow {+ delete(s.flows, flow.Key)+ for i, k := range s.order {+ if k == flow.Key {+ s.order = append(s.order[:i], s.order[i+1:]...)+ break+ }+ }+ }+ s.mu.Unlock()+ s.Cancel(flow.Key)+ })+ }, nil+}+func (s *Service) List() []Entry {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.listLocked()+}+func (s *Service) listLocked() []Entry {+ out := make([]Entry, 0, len(s.order))+ for _, key := range s.order {+ out = append(out, s.entry(s.flows[key]))+ }+ return out+}+func (s *Service) entry(f *Flow) Entry {+ return Entry{Key: f.Key, Label: f.Label, Methods: append([]Method(nil), f.Methods...), InFlight: s.running[f.Key] != nil, CanDisconnect: f.Disconnect != nil}+}+func (s *Service) Describe(key string) *Entry {+ s.mu.Lock()+ defer s.mu.Unlock()+ if f := s.flows[key]; f != nil {+ v := s.entry(f)+ return &v+ }+ return nil+}+func (s *Service) Cancel(key string) bool {+ s.mu.Lock()+ a := s.running[key]+ s.mu.Unlock()+ if a != nil {+ a.mu.Lock()+ cancelled := !a.committing+ if cancelled {+ a.cancel()+ }+ a.mu.Unlock()+ return cancelled+ }+ return false+}+func (s *Service) Session(id string) *Session {+ s.mu.Lock()+ defer s.mu.Unlock()+ for _, a := range s.running {+ if a.ID == id {+ return a+ }+ }+ return nil+}++// Begin returns promptly on withdrawal unless a credential commit was already+// admitted. An ignored cancellation may leave provider work settling, never a+// second core authorization lifecycle or a persisted attempt record.+func (s *Service) Begin(ctx context.Context, key, method string, interaction Interaction) (Outcome, error) {+ return s.begin(ctx, key, method, interaction, nil, false)+}+func (s *Service) begin(ctx context.Context, key, method string, interaction Interaction, admitted func(), drain bool) (out Outcome, err error) {+ s.mu.Lock()+ f := s.flows[key]+ if f == nil {+ s.mu.Unlock()+ return out, failure("NO_FLOW", "No authorization flow is registered for this credential")+ }+ if method == "" {+ method = f.Methods[0].ID+ }+ offered := false+ for _, m := range f.Methods {+ offered = offered || m.ID == method+ }+ if !offered {+ s.mu.Unlock()+ return out, failure("UNKNOWN_METHOD", "Unknown authorization method")+ }+ if s.running[key] != nil || s.disconnecting[key] {+ s.mu.Unlock()+ return out, failure("ALREADY_IN_FLIGHT", "Authorization is already in progress")+ }+ if ctx.Err() != nil {+ s.mu.Unlock()+ return Outcome{"cancelled"}, nil+ }+ call, cancel := context.WithCancel(context.WithoutCancel(ctx))+ a := &Session{ID: uuid.NewString(), Key: key, Method: method, Context: call, caller: ctx, cancel: cancel, service: s, interaction: interaction, done: make(chan struct{})}+ s.running[key] = a+ s.mu.Unlock()+ stop := context.AfterFunc(ctx, func() {+ a.mu.Lock()+ if !a.committing {+ a.cancel()+ }+ a.mu.Unlock()+ })+ defer func() {+ stop()+ cancel()+ s.mu.Lock()+ if s.running[key] == a {+ delete(s.running, key)+ }+ s.mu.Unlock()+ status := "failed"+ if err == nil {+ status = out.Status+ }+ a.settlement = status+ close(a.done)+ s.settled(key, status)+ }()+ off := s.store.Subscribe(func(update credentials.Update) {+ for _, k := range update.Records {+ if k == key {+ a.observed.Store(true)+ break+ }+ }+ })+ defer off()+ if admitted != nil {+ admitted()+ }+ finished := make(chan error, 1)+ go func() {+ var failure error+ defer func() {+ if recover() != nil {+ failure = fmt.Errorf("authorization callback failed")+ }+ finished <- failure+ }()+ failure = f.Run(a)+ }()+ select {+ case err = <-finished:+ case <-call.Done():+ if drain {+ <-finished+ }+ return Outcome{"cancelled"}, nil+ }+ if a.withdrawn() {+ return Outcome{"cancelled"}, nil+ }+ if err != nil {+ if a.declined.Load() {+ return Outcome{"cancelled"}, nil+ }+ return out, err+ }+ if f.Inspect != nil {+ state, inspectErr := f.Inspect(call)+ if a.withdrawn() {+ return Outcome{"cancelled"}, nil+ }+ if inspectErr != nil {+ return out, inspectErr+ }+ if !state.Configured {+ return out, failure("NOT_CONFIGURED", "The native application did not save a usable authorization")+ }+ return Outcome{"authorized"}, nil+ }+ if !a.observed.Load() {+ return out, failure("NOT_COMMITTED", "Authorization finished without committing a credential in this attempt")+ }+ info, e := s.store.DescribeRecord(key)+ if e != nil {+ return out, e+ }+ if !info.Configured {+ return out, failure("NOT_COMMITTED", "Authorization removed its credential instead of committing one")+ }+ return Outcome{"authorized"}, nil+}++type Session struct {+ ID, Key, Method string+ Context context.Context+ caller context.Context+ service *Service+ cancel context.CancelFunc+ interaction Interaction+ mu sync.Mutex+ committing bool+ done chan struct{}+ settlement string+ observed, declined atomic.Bool+}++func (a *Session) Commit(record *credentials.Record) error {+ if record == nil {+ return failure("INVALID_CREDENTIAL", "Authorization returned no credential")+ }+ if err := record.Validate(); err != nil {+ return err+ }+ if err := a.AdmitCommit(); err != nil {+ return err+ }+ _, err := a.service.store.ModifyRecord(context.WithoutCancel(a.Context), a.Key, func(*credentials.Record) (*credentials.Record, error) { return record, nil })+ return err+}+func (a *Session) Notify(ctx context.Context, notice Notice) {+ if a.interaction.Notify != nil {+ _ = a.interaction.Notify(ctx, notice)+ }+}+func (a *Session) Prompt(ctx context.Context, prompt Prompt) (string, error) {+ if a.interaction.Prompt == nil {+ a.declined.Store(true)+ return "", failure("DECLINED", "No authorization interaction is available")+ }+ if err := ctx.Err(); err != nil {+ return "", err+ }+ call, cancel := context.WithCancel(ctx)+ stop := context.AfterFunc(a.Context, cancel)+ defer stop()+ defer cancel()+ value, err := a.interaction.Prompt(call, prompt)+ var detail interface{ AuthorizationDeclined() bool }+ var auth *Error+ if errors.As(err, &auth) && auth.Code == "DECLINED" || errors.As(err, &detail) && detail.AuthorizationDeclined() {+ a.declined.Store(true)+ }+ return value, err+}++func (s *Service) Subscribe(observer func(string, string)) func() {+ s.mu.Lock()+ s.nextObserver+++ id := s.nextObserver+ s.observers[id] = observer+ s.mu.Unlock()+ return func() { s.mu.Lock(); delete(s.observers, id); s.mu.Unlock() }+}++func (s *Service) settled(key, status string) {+ s.mu.Lock()+ listeners := make([]func(string, string), 0, len(s.observers))+ for _, fn := range s.observers {+ listeners = append(listeners, fn)+ }+ s.mu.Unlock()+ for _, fn := range listeners {+ func() { defer func() { _ = recover() }(); fn(key, status) }()+ }+}++// CancelAndWait also reports a commit that was already admitted as authorized.+func (s *Service) CancelAndWait(ctx context.Context, key string) (Outcome, error) {+ s.mu.Lock()+ a := s.running[key]+ s.mu.Unlock()+ if a == nil {+ return Outcome{"cancelled"}, nil+ }+ a.mu.Lock()+ if !a.committing {+ a.cancel()+ }+ a.mu.Unlock()+ select {+ case <-a.done:+ return Outcome{a.settlement}, nil+ case <-ctx.Done():+ return Outcome{}, ctx.Err()+ }+}++// BeginDrained is for native protocol owners whose cleanup must complete before+// their connection/attempt state can be released. Human/plugin flows use Begin.+func (s *Service) BeginDrained(ctx context.Context, key, method string, interaction Interaction) (Outcome, error) {+ return s.begin(ctx, key, method, interaction, nil, true)+}++// AdmitCommit marks a native protocol's durable-write boundary before it+// announces that boundary. Cancellation cannot retract an already admitted write.+func (a *Session) AdmitCommit() error {+ a.mu.Lock()+ defer a.mu.Unlock()+ if err := a.Context.Err(); err != nil {+ return err+ }+ // AfterFunc propagates cancellation asynchronously. Inspect the caller at+ // the admission boundary so an already withdrawn request cannot commit.+ if !a.committing && a.caller != nil {+ if err := a.caller.Err(); err != nil {+ return err+ }+ }+ a.committing = true+ return nil+}++func (a *Session) withdrawn() bool {+ a.mu.Lock()+ defer a.mu.Unlock()+ return a.Context.Err() != nil || !a.committing && a.caller != nil && a.caller.Err() != nil+}diff --git a/internal/authorization/service_test.go b/internal/authorization/service_test.gonew file mode 100644index 0000000..9588e06--- /dev/null+++ b/internal/authorization/service_test.go@@ -0,0 +1,201 @@+package authorization++import (+ "context"+ "errors"+ "path/filepath"+ "testing"+ "time"++ "go-bot/internal/credentials"+)++func fixture(t *testing.T) (*Service, *credentials.Store) {+ t.Helper()+ store, err := credentials.Open(filepath.Join(t.TempDir(), credentials.Filename), credentials.Options{})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = store.Close() })+ return New(store), store+}+func register(t *testing.T, s *Service, key string, run func(*Session) error) func() {+ t.Helper()+ off, err := s.Register(Flow{Key: key, Label: "Account", Methods: []Method{{ID: "oauth", Label: "Sign in"}}, Run: run})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(off)+ return off+}+func TestAuthorizationRequiresObservedCommittedCredential(t *testing.T) {+ for _, kind := range []string{"stale", "commit", "direct", "same", "deleted"} {+ t.Run(kind, func(t *testing.T) {+ s, store := fixture(t)+ key := "mail/account"+ _, err := store.ModifyRecord(t.Context(), key, func(*credentials.Record) (*credentials.Record, error) {+ return &credentials.Record{Kind: "api-key"}, nil+ })+ if err != nil {+ t.Fatal(err)+ }+ register(t, s, key, func(a *Session) error {+ if kind == "stale" {+ return nil+ }+ value := "new-key"+ record := &credentials.Record{Kind: "api-key", Key: &value}+ if kind == "same" {+ record.Key = nil+ }+ if kind == "direct" {+ _, err := store.ModifyRecord(t.Context(), key, func(*credentials.Record) (*credentials.Record, error) { return record, nil })+ return err+ }+ if err := a.Commit(record); err != nil {+ return err+ }+ if kind == "deleted" {+ return store.DeleteRecord(t.Context(), key)+ }+ return nil+ })+ out, err := s.Begin(t.Context(), key, "", Interaction{})+ if kind == "stale" || kind == "deleted" {+ var detail *Error+ if !errors.As(err, &detail) || detail.Code != "NOT_COMMITTED" {+ t.Fatal(out, err)+ }+ } else if err != nil || out.Status != "authorized" {+ t.Fatal(out, err)+ }+ })+ }+}+func TestAuthorizationDeclinePromptWithdrawalAndObserverIsolation(t *testing.T) {+ s, _ := fixture(t)+ register(t, s, "mail/decline", func(a *Session) error {+ _, err := a.Prompt(t.Context(), Prompt{Kind: "secret", Message: "Key"})+ if err != nil {+ return errors.New("provider wrapped decline")+ }+ return nil+ })+ off := s.Subscribe(func(key, status string) {+ if s.Describe(key).InFlight {+ t.Error("settlement fired before release")+ }+ panic("observer failure")+ })+ defer off()+ out, err := s.Begin(t.Context(), "mail/decline", "", Interaction{Prompt: func(context.Context, Prompt) (string, error) { return "", &Error{Code: "DECLINED", Message: "No"} }})+ if err != nil || out.Status != "cancelled" {+ t.Fatal(out, err)+ }+ register(t, s, "mail/withdrawn", func(a *Session) error {+ ctx, cancel := context.WithCancel(t.Context())+ cancel()+ if _, err := a.Prompt(ctx, Prompt{Kind: "text"}); err == nil {+ t.Error("withdrawn prompt ran")+ }+ return a.Commit(&credentials.Record{Kind: "api-key"})+ })+ out, err = s.Begin(t.Context(), "mail/withdrawn", "", Interaction{})+ if err != nil || out.Status != "authorized" {+ t.Fatal(out, err)+ }+}+func TestAuthorizationCancellationAndCommitAdmission(t *testing.T) {+ s, store := fixture(t)+ entered, release := make(chan struct{}), make(chan struct{})+ register(t, s, "mail/waiting", func(*Session) error { close(entered); <-release; return nil })+ result := make(chan Outcome, 1)+ go func() { out, _ := s.Begin(t.Context(), "mail/waiting", "", Interaction{}); result <- out }()+ <-entered+ _, err := s.Begin(t.Context(), "mail/waiting", "", Interaction{})+ var detail *Error+ if !errors.As(err, &detail) || detail.Code != "ALREADY_IN_FLIGHT" {+ t.Fatal(err)+ }+ s.Cancel("mail/waiting")+ select {+ case out := <-result:+ if out.Status != "cancelled" {+ t.Fatal(out)+ }+ case <-time.After(time.Second):+ t.Fatal("ignored cancellation kept credential busy")+ }+ close(release)+ lock, unlock := make(chan struct{}), make(chan struct{})+ writeDone := make(chan error, 1)+ go func() {+ _, err := store.ModifyRecord(t.Context(), "mail/lock", func(*credentials.Record) (*credentials.Record, error) {+ close(lock)+ <-unlock+ return &credentials.Record{Kind: "api-key"}, nil+ })+ writeDone <- err+ }()+ <-lock+ register(t, s, "mail/commit", func(a *Session) error { return a.Commit(&credentials.Record{Kind: "api-key"}) })+ go func() { out, _ := s.Begin(t.Context(), "mail/commit", "", Interaction{}); result <- out }()+ deadline := time.Now().Add(time.Second)+ for {+ a := s.SessionByKey("mail/commit")+ if a != nil {+ a.mu.Lock()+ committing := a.committing+ a.mu.Unlock()+ if committing {+ break+ }+ }+ if time.Now().After(deadline) {+ close(unlock)+ t.Fatal("commit not admitted")+ }+ time.Sleep(time.Millisecond)+ }+ s.Cancel("mail/commit")+ if !s.Describe("mail/commit").InFlight {+ t.Fatal("admitted write was abandoned")+ }+ close(unlock)+ if err := <-writeDone; err != nil {+ t.Fatal(err)+ }+ if out := <-result; out.Status != "authorized" {+ t.Fatal(out)+ }+}+func (s *Service) SessionByKey(key string) *Session {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.running[key]+}++func TestCallerCancellationDoesNotWaitForPropagation(t *testing.T) {+ caller, cancel := context.WithCancel(t.Context())+ // Model the interval before AfterFunc has propagated cancellation to the+ // session context. The caller's cancellation is already authoritative.+ a := &Session{Context: context.WithoutCancel(caller), caller: caller}+ cancel()+ if !a.withdrawn() {+ t.Fatal("withdrawal depends on asynchronous cancellation propagation")+ }+ if err := a.AdmitCommit(); !errors.Is(err, context.Canceled) {+ t.Fatalf("commit admitted after caller cancellation: %v", err)+ }+ if a.committing {+ t.Fatal("rejected commit crossed the write boundary")+ }+ // A write admitted before cancellation must still be allowed to settle.+ a.committing = true+ if a.withdrawn() {+ t.Fatal("caller cancellation abandoned an admitted write")+ }+ if err := a.AdmitCommit(); err != nil {+ t.Fatalf("admitted commit was withdrawn: %v", err)+ }+}diff --git a/internal/authorization/surface.go b/internal/authorization/surface.gonew file mode 100644index 0000000..3053704--- /dev/null+++ b/internal/authorization/surface.go@@ -0,0 +1,326 @@+package authorization++import (+ "context"+ "encoding/json"+ "strings"+ "sync"++ "github.com/google/uuid"+)++type PendingPrompt struct {+ ID string `json:"id"`+ Prompt+}+type View struct {+ ID string `json:"id"`+ Key string `json:"key"`+ Label string `json:"label"`+ Method string `json:"method"`+ Status string `json:"status"`+ Notices []Notice `json:"notices"`+ Prompts []PendingPrompt `json:"prompts"`+ Error string `json:"error,omitempty"`+}++// EntryView adds only this HTTP surface's resumable interaction handle. The+// common Service remains the owner of authorization admission and completion.+type EntryView struct {+ Entry+ Configured bool `json:"configured"`+ AccountLabel string `json:"accountLabel,omitempty"`+ AttemptID string `json:"attemptId,omitempty"`+ AttemptStatus string `json:"attemptStatus,omitempty"`+}+type answer struct {+ value string+ decline bool+}+type pendingPrompt struct {+ view PendingPrompt+ answer chan answer+}+type surfaceAttempt struct {+ view View+ cancel context.CancelFunc+ done chan struct{}+ failure error+ pending map[string]*pendingPrompt+ promptOrder []string+ secrets []string+ ctx context.Context+ callbackBase string+ callback *surfaceCallback+}++// Surface owns transient interaction data for the Host's own HTTP clients.+// Nothing here is persisted or copied into account configuration.+type Surface struct {+ service *Service+ ctx context.Context+ mu sync.Mutex+ attempts map[string]*surfaceAttempt+ latest map[string]string+ changed func()+}++func NewSurface(ctx context.Context, service *Service, changed func()) *Surface {+ return &Surface{service: service, ctx: ctx, attempts: map[string]*surfaceAttempt{}, latest: map[string]string{}, changed: changed}+}+func (s *Surface) change() {+ if s.changed != nil {+ s.changed()+ }+}+func (s *Surface) copy(a *surfaceAttempt) View {+ v := a.view+ v.Notices = append([]Notice{}, v.Notices...)+ v.Prompts = make([]PendingPrompt, 0, len(a.pending))+ for _, id := range a.promptOrder {+ p := a.pending[id]+ if p == nil {+ continue+ }+ copy := p.view+ copy.Options = append([]Option(nil), p.view.Options...)+ v.Prompts = append(v.Prompts, copy)+ }+ return v+}+func (s *Surface) start(key, method string) (View, error) {+ return s.startWithCallback(key, method, "")+}++func (s *Surface) startWithCallback(key, method, callbackBase string) (View, error) {+ entry := s.service.Describe(key)+ if entry == nil {+ return View{}, failure("NO_FLOW", "No authorization flow is registered for this credential")+ }+ if method == "" {+ method = entry.Methods[0].ID+ }+ s.mu.Lock()+ for id, a := range s.attempts {+ if len(s.attempts) < 32 {+ break+ }+ if a.view.Status != "running" {+ delete(s.attempts, id)+ if s.latest[a.view.Key] == id {+ delete(s.latest, a.view.Key)+ }+ }+ }+ if len(s.attempts) >= 64 {+ s.mu.Unlock()+ return View{}, failure("AUTHORIZATION_BUSY", "Too many authorization attempts")+ }+ ctx, cancel := context.WithCancel(s.ctx)+ a := &surfaceAttempt{view: View{ID: uuid.NewString(), Key: key, Label: entry.Label, Method: method, Status: "running", Notices: []Notice{}}, cancel: cancel, done: make(chan struct{}), pending: map[string]*pendingPrompt{}}+ a.ctx, a.callbackBase = ctx, callbackBase+ s.attempts[a.view.ID] = a+ s.mu.Unlock()+ admitted := make(chan struct{})+ go func() {+ out, err := s.service.begin(ctx, key, method, Interaction{+ Notify: func(_ context.Context, n Notice) error {+ s.mu.Lock()+ a.view.Notices = append(a.view.Notices, n)+ if len(a.view.Notices) > 8 {+ a.view.Notices = a.view.Notices[len(a.view.Notices)-8:]+ }+ s.mu.Unlock()+ s.change()+ return nil+ },+ Prompt: func(ctx context.Context, p Prompt) (string, error) { return s.prompt(ctx, a, p) },+ Callback: func(ctx context.Context, state string) (string, error) { return s.prepareCallback(ctx, a, state) },+ WaitCallback: func(ctx context.Context) (map[string][]string, error) { return s.waitCallback(ctx, a) },+ }, func() { close(admitted) }, false)+ s.mu.Lock()+ a.failure = err+ if err != nil {+ a.view.Status = "failed"+ a.view.Error = err.Error()+ for _, secret := range a.secrets {+ a.view.Error = strings.ReplaceAll(a.view.Error, secret, "[redacted]")+ }+ } else {+ a.view.Status = out.Status+ }+ a.pending = map[string]*pendingPrompt{}+ a.secrets = nil+ a.callback = nil+ s.mu.Unlock()+ cancel()+ close(a.done)+ s.change()+ }()+ select {+ case <-admitted:+ case <-a.done:+ if a.failure != nil {+ s.mu.Lock()+ delete(s.attempts, a.view.ID)+ s.mu.Unlock()+ return View{}, a.failure+ }+ case <-s.ctx.Done():+ return View{}, s.ctx.Err()+ }+ s.mu.Lock()+ v := s.copy(a)+ s.latest[key] = a.view.ID+ s.mu.Unlock()+ s.change()+ return v, nil+}+func (s *Surface) prompt(ctx context.Context, a *surfaceAttempt, p Prompt) (string, error) {+ if err := ctx.Err(); err != nil {+ return "", err+ }+ if (p.Kind != "text" && p.Kind != "secret" && p.Kind != "select") ||+ (p.WebInput != "" && (p.WebInput != "json-file" || p.Kind == "select")) {+ return "", failure("INVALID_PROMPT", "Unsupported authorization prompt")+ }+ pending := &pendingPrompt{PendingPrompt{uuid.NewString(), p}, make(chan answer, 1)}+ s.mu.Lock()+ if len(a.pending) >= 16 {+ s.mu.Unlock()+ return "", failure("AUTHORIZATION_BUSY", "Too many pending questions")+ }+ a.pending[pending.view.ID] = pending+ a.promptOrder = append(a.promptOrder, pending.view.ID)+ s.mu.Unlock()+ s.change()+ defer func() { s.mu.Lock(); s.removePrompt(a, pending.view.ID); s.mu.Unlock(); s.change() }()+ select {+ case <-ctx.Done():+ return "", ctx.Err()+ case answer := <-pending.answer:+ if answer.decline {+ return "", failure("DECLINED", "Authorization declined")+ }+ return answer.value, nil+ }+}+func (s *Surface) Handle(ctx context.Context, method string, raw json.RawMessage) (any, error) {+ var input struct {+ ID string `json:"id"`+ Key string `json:"key"`+ Method string `json:"method"`+ PromptID string `json:"promptId"`+ Answer *string `json:"answer"`+ Decline bool `json:"decline"`+ Token string `json:"token"`+ Query map[string][]string `json:"query"`+ }+ if err := json.Unmarshal(raw, &input); err != nil {+ return nil, err+ }+ if method == "list" {+ rows := s.service.List()+ out := make([]EntryView, 0, len(rows))+ for _, row := range rows {+ info, err := s.service.Inspect(ctx, row.Key)+ if err != nil {+ return nil, err+ }+ entry := EntryView{Entry: row, Configured: info.Configured, AccountLabel: info.AccountLabel}+ s.mu.Lock()+ if a := s.attempts[s.latest[row.Key]]; a != nil {+ entry.AttemptID, entry.AttemptStatus = a.view.ID, a.view.Status+ }+ s.mu.Unlock()+ out = append(out, entry)+ }+ return out, nil+ }+ if method == "disconnect" {+ state, err := s.service.Disconnect(ctx, input.Key)+ s.change()+ return state, err+ }+ if method == "start" {+ return s.startWithCallback(input.Key, input.Method, callbackBase(ctx))+ }+ if method == "callback" {+ return s.receiveCallback(input.Token, input.Query)+ }+ if method == "cancelKey" {+ return s.service.CancelAndWait(ctx, input.Key)+ }+ s.mu.Lock()+ a := s.attempts[input.ID]+ if a == nil {+ s.mu.Unlock()+ return nil, failure("AUTHORIZATION_NOT_FOUND", "Authorization is no longer available; start again")+ }+ if method == "cancel" {+ s.mu.Unlock()+ a.cancel()+ select {+ case <-a.done:+ case <-ctx.Done():+ return nil, ctx.Err()+ }+ s.mu.Lock()+ v := s.copy(a)+ s.mu.Unlock()+ return v, nil+ }+ defer s.mu.Unlock()+ if method == "answer" {+ pending := a.pending[input.PromptID]+ if pending == nil {+ return nil, failure("PROMPT_NOT_FOUND", "This question is no longer awaiting an answer")+ }+ if !input.Decline {+ if input.Answer == nil || len(*input.Answer) > 16384 {+ return nil, failure("INVALID_ANSWER", "Provide a valid authorization answer")+ }+ if pending.view.Kind == "select" {+ found := false+ for _, o := range pending.view.Options {+ found = found || o.ID == *input.Answer+ }+ if !found {+ return nil, failure("INVALID_ANSWER", "Choose an offered option")+ }+ }+ // Presentation is independent of privacy: visible callback URLs can+ // contain one-time codes, just as masked fields can contain API keys.+ if pending.view.Kind != "select" && *input.Answer != "" {+ a.secrets = append(a.secrets, *input.Answer)+ }+ }+ value := ""+ if input.Answer != nil {+ value = *input.Answer+ }+ pending.answer <- answer{value, input.Decline}+ s.removePrompt(a, input.PromptID)+ } else if method != "get" {+ return nil, failure("METHOD_NOT_FOUND", "Unknown authorization operation")+ }+ return s.copy(a), nil+}+func (s *Surface) Close() {+ s.mu.Lock()+ for _, a := range s.attempts {+ a.cancel()+ }+ s.mu.Unlock()+}++// Called with Surface.mu held; preserve the original request order in views.+func (s *Surface) removePrompt(a *surfaceAttempt, id string) {+ delete(a.pending, id)+ for i, key := range a.promptOrder {+ if key == id {+ a.promptOrder = append(a.promptOrder[:i], a.promptOrder[i+1:]...)+ break+ }+ }+}diff --git a/internal/authorization/surface_test.go b/internal/authorization/surface_test.gonew file mode 100644index 0000000..2e92cf3--- /dev/null+++ b/internal/authorization/surface_test.go@@ -0,0 +1,144 @@+package authorization++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"+ "testing"+ "time"++ "go-bot/internal/credentials"+)++func TestSurfaceResumesMultiplePromptsWithoutOwningClientConnection(t *testing.T) {+ service, _ := fixture(t)+ surface := NewSurface(t.Context(), service, nil)+ t.Cleanup(surface.Close)+ register(t, service, "mail/account", func(session *Session) error {+ answers := make(chan error, 2)+ for _, kind := range []string{"text", "secret"} {+ go func(kind string) {+ hint := ""+ if kind == "secret" {+ hint = "json-file"+ }+ _, err := session.Prompt(session.Context, Prompt{Kind: kind, Message: kind, WebInput: hint})+ answers <- err+ }(kind)+ }+ for range 2 {+ if err := <-answers; err != nil {+ return err+ }+ }+ key := "test-only"+ return session.Commit(&credentials.Record{Kind: "api-key", Key: &key})+ })+ initial, err := surface.start("mail/account", "oauth")+ if err != nil {+ t.Fatal(err)+ }+ deadline := time.Now().Add(3 * time.Second)+ var view View+ for time.Now().Before(deadline) {+ value, err := surface.Handle(t.Context(), "get", json.RawMessage(`{"id":"`+initial.ID+`"}`))+ if err != nil {+ t.Fatal(err)+ }+ view = value.(View)+ if len(view.Prompts) == 2 {+ break+ }+ time.Sleep(time.Millisecond)+ }+ if len(view.Prompts) != 2 {+ t.Fatalf("pending prompts: %+v", view)+ }+ // The creating HTTP request can disappear. Another client discovers the+ // same attempt and pending questions using the normal list/get contract.+ value, err := surface.Handle(context.Background(), "list", json.RawMessage(`{}`))+ if err != nil {+ t.Fatal(err)+ }+ entries := value.([]EntryView)+ if len(entries) != 1 || entries[0].AttemptID != initial.ID || entries[0].AttemptStatus != "running" {+ t.Fatalf("cannot resume: %+v", entries)+ }+ for _, prompt := range view.Prompts {+ if prompt.Kind == "secret" && prompt.WebInput != "json-file" {+ t.Fatal("web presentation hint was lost")+ }+ input, _ := json.Marshal(map[string]string{"id": initial.ID, "promptId": prompt.ID, "answer": "local-test"})+ if _, err := surface.Handle(t.Context(), "answer", input); err != nil {+ t.Fatal(err)+ }+ }+ for time.Now().Before(deadline) {+ value, _ := surface.Handle(t.Context(), "list", json.RawMessage(`{}`))+ entries = value.([]EntryView)+ if entries[0].AttemptStatus == "authorized" {+ break+ }+ time.Sleep(time.Millisecond)+ }+ if entries[0].AttemptStatus != "authorized" || entries[0].InFlight || !entries[0].Configured || entries[0].AttemptID != initial.ID {+ t.Fatalf("completion not discoverable: %+v", entries)+ }+}++func TestSurfaceKeepsVisibleCallbackAnswersOutOfErrors(t *testing.T) {+ for _, kind := range []string{"text", "secret"} {+ t.Run(kind, func(t *testing.T) {+ service, _ := fixture(t)+ surface := NewSurface(t.Context(), service, nil)+ t.Cleanup(surface.Close)+ register(t, service, "native/account", func(session *Session) error {+ value, err := session.Prompt(session.Context, Prompt{Kind: kind, Message: "Callback URL"})+ if err != nil {+ return err+ }+ return fmt.Errorf("native error: %s", value)+ })+ initial, err := surface.start("native/account", "oauth")+ if err != nil {+ t.Fatal(err)+ }+ deadline := time.After(3 * time.Second)+ var prompt PendingPrompt+ for prompt.ID == "" {+ value, err := surface.Handle(t.Context(), "get", json.RawMessage(`{"id":"`+initial.ID+`"}`))+ if err != nil {+ t.Fatal(err)+ }+ if prompts := value.(View).Prompts; len(prompts) > 0 {+ prompt = prompts[0]+ break+ }+ select {+ case <-deadline:+ t.Fatal("prompt did not appear")+ case <-time.After(time.Millisecond):+ }+ }+ answer := "http://localhost:8080/callback?code=private-one-time-code&state=attempt"+ input, _ := json.Marshal(map[string]string{"id": initial.ID, "promptId": prompt.ID, "answer": answer})+ if _, err := surface.Handle(t.Context(), "answer", input); err != nil {+ t.Fatal(err)+ }+ select {+ case <-surface.attempts[initial.ID].done:+ case <-deadline:+ t.Fatal("flow did not finish")+ }+ value, err := surface.Handle(t.Context(), "get", json.RawMessage(`{"id":"`+initial.ID+`"}`))+ if err != nil {+ t.Fatal(err)+ }+ data, _ := json.Marshal(value)+ if strings.Contains(string(data), "private-one-time-code") || !strings.Contains(value.(View).Error, "[redacted]") {+ t.Fatal("authorization answer leaked through an error")+ }+ })+ }+}diff --git a/internal/controller/authorization.go b/internal/controller/authorization.gonew file mode 100644index 0000000..08982fd--- /dev/null+++ b/internal/controller/authorization.go@@ -0,0 +1,77 @@+package controller++import (+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "strings"++ "github.com/google/uuid"+ "go-bot/plugin"+)++func (m *Manager) authorizationHTTP(w http.ResponseWriter, r *http.Request, id string) {+ suffix := strings.TrimPrefix(r.URL.Path, plugin.AuthorizationPath)+ if suffix == "" {+ if r.Method != http.MethodGet && r.Method != http.MethodPost && r.Method != http.MethodDelete {+ http.NotFound(w, r)+ return+ }+ } else if suffix != "/disconnect" || r.Method != http.MethodPost {+ attempt, action, _ := strings.Cut(strings.TrimPrefix(suffix, "/"), "/")+ _, err := uuid.Parse(attempt)+ if err != nil || !((action == "" && (r.Method == http.MethodGet || r.Method == http.MethodDelete)) || (action == "answer" && r.Method == http.MethodPost)) {+ http.NotFound(w, r)+ return+ }+ }+ // No account management lock is held while a credential flow progresses;+ // answering and cancelling must remain independent requests.+ record, err := m.Store.Get(r.Context(), id)+ if errors.Is(err, ErrAccountNotFound) {+ http.NotFound(w, r)+ return+ }+ if err != nil || record.DesiredState != running || record.HostEndpoint == "" {+ httpError(w, http.StatusConflict, "host_not_running")+ return+ }+ var input any+ if r.Method == http.MethodPost || (suffix == "" && r.Method == http.MethodDelete) {+ d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 128<<10))+ d.DisallowUnknownFields()+ if r.Method == http.MethodDelete {+ input = &struct {+ Key string `json:"key"`+ }{}+ } else if suffix == "/disconnect" {+ input = &struct {+ Key string `json:"key"`+ }{}+ } else if suffix == "" {+ input = &plugin.AuthorizationStart{}+ } else {+ input = &plugin.AuthorizationAnswer{}+ }+ if d.Decode(input) != nil || !errors.Is(d.Decode(new(any)), io.EOF) {+ httpError(w, 400, "invalid_authorization_request")+ return+ }+ }+ var result json.RawMessage+ if err = m.requestPlugins(r.Context(), record, r.Method, "/authorization"+suffix, input, &result); err != nil {+ status := http.StatusBadGateway+ var upstream *extensionHTTPError+ if errors.As(err, &upstream) {+ status = upstream.Status+ }+ writeJSON(w, status, map[string]string{"error": "plugin_authorization_failed", "message": err.Error()})+ return+ }+ status := http.StatusOK+ if r.Method == http.MethodPost && suffix == "" {+ status = http.StatusAccepted+ }+ writeJSON(w, status, result)+}diff --git a/internal/controller/authorization_callback.go b/internal/controller/authorization_callback.gonew file mode 100644index 0000000..5975819--- /dev/null+++ b/internal/controller/authorization_callback.go@@ -0,0 +1,59 @@+package controller++import (+ "net/http"+ "net/url"+ "strings"++ "github.com/google/uuid"+ mcpconfig "go-bot/mcp"+ "go-bot/plugin"+)++// Derive the second callback from the already validated public Controller+// origin and account. It is routing metadata, not another authorization flow.+func pluginCallbackBase(redirect string) string {+ u, err := url.Parse(redirect)+ if err != nil || !strings.HasPrefix(u.Path, mcpconfig.OAuthCallbackPath) {+ return ""+ }+ account := strings.TrimPrefix(u.Path, mcpconfig.OAuthCallbackPath)+ if !userName.MatchString(account) {+ return ""+ }+ u.Path = plugin.AuthorizationCallbackPath + account + "/"+ return u.String()+}++func (m *Manager) pluginAuthorizationCallbackHTTP(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ w.Header().Set("Allow", http.MethodGet)+ writeOAuthCallbackPage(w, r, http.StatusMethodNotAllowed, "")+ return+ }+ accountID, token, found := strings.Cut(strings.TrimPrefix(r.URL.Path, plugin.AuthorizationCallbackPath), "/")+ if !found || !userName.MatchString(accountID) || uuid.Validate(token) != nil || len(r.URL.RawQuery) > 24<<10 {+ writeOAuthCallbackPage(w, r, http.StatusBadRequest, "")+ return+ }+ query, err := url.ParseQuery(r.URL.RawQuery)+ if err != nil || len(query["state"]) != 1 || query.Get("state") == "" {+ writeOAuthCallbackPage(w, r, http.StatusBadRequest, "")+ return+ }+ account, err := m.Store.Get(r.Context(), accountID)+ if err != nil || account.DesiredState != running || account.HostEndpoint == "" {+ writeOAuthCallbackPage(w, r, http.StatusConflict, "")+ return+ }+ var receipt struct {+ Received bool `json:"received"`+ }+ if err := m.requestPlugins(r.Context(), account, http.MethodPost, "/authorization/callback", map[string]any{"token": token, "query": query}, &receipt); err != nil || !receipt.Received {+ writeOAuthCallbackPage(w, r, http.StatusBadRequest, "")+ return+ }+ // This says only that Go received the callback. The plugin still validates+ // the provider response and exchanges tokens before it can commit a grant.+ writeOAuthCallbackPage(w, r, http.StatusOK, "received")+}diff --git a/internal/controller/authorization_callback_test.go b/internal/controller/authorization_callback_test.gonew file mode 100644index 0000000..9af4c58--- /dev/null+++ b/internal/controller/authorization_callback_test.go@@ -0,0 +1,55 @@+package controller++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/google/uuid"+ "go-bot/internal/config"+ "go-bot/internal/httpapi"+ "go-bot/plugin"+)++func TestPluginCallbackForwardsOnlyToTheAccountsAuthenticatedHost(t *testing.T) {+ token := uuid.NewString()+ host := httptest.NewServer(httpapi.Authenticate("host-private", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != "POST" || r.URL.Path != plugin.InternalPath+"/authorization/callback" {+ http.NotFound(w, r)+ return+ }+ var input struct {+ Token string+ Query map[string][]string+ }+ if err := json.NewDecoder(r.Body).Decode(&input); err != nil {+ t.Error(err)+ }+ if input.Token != token || input.Query["state"][0] != "provider-state" || input.Query["code"][0] != "private-code" {+ t.Errorf("incorrect callback routing: %+v", input)+ }+ writeJSON(w, 200, map[string]bool{"received": true})+ })))+ defer host.Close()+ store := &memoryStore{records: map[string]Account{"alice": {DesiredState: running, HostEndpoint: host.URL, HostToken: "host-private"}}}+ manager := New(config.Default(), nil, store)+ r := httptest.NewRequest("GET", plugin.AuthorizationCallbackPath+"alice/"+token+"?state=provider-state&code=private-code", nil)+ r.Header.Set("Origin", "https://provider.example")+ w := httptest.NewRecorder()+ manager.Handler().ServeHTTP(w, r)+ if w.Code != 200 || !strings.Contains(w.Body.String(), "Authorization received") || strings.Contains(w.Body.String(), "private-code") || strings.Contains(w.Body.String(), "host-private") {+ t.Fatalf("callback page: %d %s", w.Code, w.Body)+ }+ for _, path := range []string{"alice/not-a-token?state=x", "alice/" + token + "?state=x&state=y", "unknown/" + token + "?state=x"} {+ w := httptest.NewRecorder()+ manager.Handler().ServeHTTP(w, httptest.NewRequest("GET", plugin.AuthorizationCallbackPath+path, nil))+ if w.Code < 400 {+ t.Fatalf("accepted invalid callback: %s", path)+ }+ }+ if actual := pluginCallbackBase("https://controller.example/v1/mcp/oauth/callback/alice"); actual != "https://controller.example"+plugin.AuthorizationCallbackPath+"alice/" {+ t.Fatal(actual)+ }+}diff --git a/internal/controller/authorization_test.go b/internal/controller/authorization_test.gonew file mode 100644index 0000000..4158c1c--- /dev/null+++ b/internal/controller/authorization_test.go@@ -0,0 +1,191 @@+package controller++import (+ "encoding/json"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "go-bot/extensions/catalog"+ "go-bot/internal/config"+ "go-bot/internal/httpapi"+ "go-bot/internal/plugins"+ "go-bot/plugin"+)++func TestControllerAuthorizationUsesHostFlowsWithoutSavingAnswersInRedis(t *testing.T) {+ main, err := filepath.Abs("../../extensions/cordis/src/main.mjs")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(filepath.Dir(main), "../node_modules/@deepseek-ai/cordis/package.json")); err != nil {+ t.Skip("Install the Cordis runtime dependencies")+ }+ extensions, err := plugins.NewManager(t.Context(), plugins.ManagerConfig{Directory: t.TempDir(), Runtime: plugins.RuntimeConfig{Main: main}, PackageMain: filepath.Join(filepath.Dir(main), "package-main.mjs")})+ if err != nil {+ t.Fatal(err)+ }+ defer extensions.Close()+ host := httptest.NewServer(httpapi.Authenticate("authorization-host-token", extensions.Handler()))+ defer host.Close()+ store := &memoryStore{records: map[string]Account{"alice": {DesiredState: running, HostToken: "authorization-host-token", HostEndpoint: host.URL}}}+ manager := New(config.Default(), nil, store)+ request := func(method, path string, input any, status int) json.RawMessage {+ t.Helper()+ body, _ := json.Marshal(input)+ r := httptest.NewRequest(method, path, strings.NewReader(string(body)))+ r.Header.Set(UserHeader, "alice")+ out := httptest.NewRecorder()+ manager.Handler().ServeHTTP(out, r)+ if out.Code != status {+ t.Fatalf("%s %s: %d %s", method, path, out.Code, out.Body.String())+ }+ return out.Body.Bytes()+ }+ directory := t.TempDir()+ files := map[string]string{+ "package.json": `{"name":"@fixture/authorization","version":"1.0.0","type":"module","exports":"./index.mjs","dsh":{"manifestVersion":1,"bundle":{"patch":"./cordis.patch.yml"}},"goBot":{"api":"1","requires":{"authorization":"^1.0.0","credentials":"^1.0.0"}}}`,+ "index.mjs": `export const inject=['host'];export async function apply(ctx){await ctx.host.authorization.register({key:'account',title:'Fixture account',methods:[{id:'key',label:'API key'}],async run(session){const key=await session.prompt({kind:'secret',message:'Service API key'});await session.commit({kind:'api-key',key})}})}`,+ }+ for name, content := range files {+ if err := os.WriteFile(filepath.Join(directory, name), []byte(content), 0600); err != nil {+ t.Fatal(err)+ }+ }+ manager.pluginCatalog = []catalog.Entry{{CatalogEntry: plugin.CatalogEntry{ID: "fixture", Package: "@fixture/authorization", Version: "1.0.0"}, Source: plugin.Source{Type: "directory", Spec: directory}}}+ request("POST", plugin.SettingsPath+"/packages", map[string]string{"pluginId": "fixture"}, 200)+ request("PUT", plugin.SettingsPath+"/packages/%40fixture%2Fauthorization", map[string]bool{"enabled": true}, 200)++ listed := request("GET", plugin.AuthorizationPath, nil, 200)+ if !strings.Contains(string(listed), `"key":"fixture/account"`) || !strings.Contains(string(listed), `"configured":false`) {+ t.Fatal("Controller did not read the actual registered flow", string(listed))+ }+ var attempt struct {+ ID string `json:"id"`+ Status string `json:"status"`+ Prompts []struct{ ID string } `json:"prompts"`+ }+ if err := json.Unmarshal(request("POST", plugin.AuthorizationPath, plugin.AuthorizationStart{Key: "fixture/account"}, 202), &attempt); err != nil {+ t.Fatal("Real Host did not prompt the initiating surface", err)+ }+ readyDeadline := time.Now().Add(4 * time.Second)+ for len(attempt.Prompts) == 0 {+ if err := json.Unmarshal(request("GET", plugin.AuthorizationPath+"/"+attempt.ID, nil, 200), &attempt); err != nil {+ t.Fatal(err)+ }+ if time.Now().After(readyDeadline) {+ t.Fatal("Host did not publish its pending question")+ }+ time.Sleep(5 * time.Millisecond)+ }+ request("POST", plugin.AuthorizationPath, plugin.AuthorizationStart{Key: "fixture/account"}, 409)+ request("GET", plugin.AuthorizationPath+"/00000000-0000-0000-0000-000000000000", nil, 404)+ secret := "private-authorization-answer"+ response := request("POST", plugin.AuthorizationPath+"/"+attempt.ID+"/answer", plugin.AuthorizationAnswer{PromptID: attempt.Prompts[0].ID, Answer: &secret}, 200)+ if strings.Contains(string(response), secret) {+ t.Fatal("Answer endpoint echoed the private value")+ }+ deadline := time.Now().Add(4 * time.Second)+ for {+ if err := json.Unmarshal(request("GET", plugin.AuthorizationPath+"/"+attempt.ID, nil, 200), &attempt); err != nil {+ t.Fatal(err)+ }+ if attempt.Status == "authorized" {+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("Controller did not observe the real Go credential commit")+ }+ time.Sleep(5 * time.Millisecond)+ }+ listed = request("GET", plugin.AuthorizationPath, nil, 200)+ if strings.Contains(string(listed), secret) || !strings.Contains(string(listed), `"configured":true`) || strings.Contains(string(listed), "Service API key") {+ t.Fatal("Flow list leaked interaction or missed configuration", string(listed))+ }+ account, err := store.Get(t.Context(), "alice")+ if err != nil {+ t.Fatal(err)+ }+ stored, _ := json.Marshal(account)+ if strings.Contains(string(stored), secret) || strings.Contains(string(stored), attempt.ID) {+ t.Fatal("Controller persisted a Host authorization answer or transient handle")+ }+ request("POST", plugin.AuthorizationPath, map[string]any{"key": "fixture/account", "unexpected": true}, 400)+}++func TestControllerDisconnectsNativeAuthorizationWithoutCredentialPlaceholder(t *testing.T) {+ main, err := filepath.Abs("../../extensions/cordis/src/main.mjs")+ if err != nil {+ t.Fatal(err)+ }+ if _, err = os.Stat(filepath.Join(filepath.Dir(main), "../node_modules/@deepseek-ai/cordis/package.json")); err != nil {+ t.Skip("Install Cordis runtime dependencies")+ }+ directory := t.TempDir()+ for name, body := range map[string]string{+ "package.json": `{"name":"@fixture/native","version":"1.0.0","type":"module","exports":"./index.mjs","goBot":{"api":"1"}}`,+ "index.mjs": `export const inject=['host'];export async function apply(ctx){let configured=false;await ctx.host.authorization.register({key:'account',title:'Native CLI account',methods:[{id:'login',label:'Connect'}],async run(){configured=true},async inspect(){return {configured,accountLabel:configured?'[email protected]':''}},async disconnect(){configured=false}})}`,+ } {+ if err = os.WriteFile(filepath.Join(directory, name), []byte(body), 0600); err != nil {+ t.Fatal(err)+ }+ }+ extensions, err := plugins.NewManager(t.Context(), plugins.ManagerConfig{Directory: t.TempDir(), Runtime: plugins.RuntimeConfig{Main: main}, PackageMain: filepath.Join(filepath.Dir(main), "package-main.mjs")})+ if err != nil {+ t.Fatal(err)+ }+ defer extensions.Close()+ host := httptest.NewServer(httpapi.Authenticate("native-host", extensions.Handler()))+ defer host.Close()+ store := &memoryStore{records: map[string]Account{"alice": {DesiredState: running, HostToken: "native-host", HostEndpoint: host.URL}}}+ manager := New(config.Default(), nil, store)+ manager.pluginCatalog = []catalog.Entry{{CatalogEntry: plugin.CatalogEntry{ID: "native", Package: "@fixture/native", Version: "1.0.0"}, Source: plugin.Source{Type: "directory", Spec: directory}}}+ request := func(method, path string, input any, status int) json.RawMessage {+ t.Helper()+ body, _ := json.Marshal(input)+ req := httptest.NewRequest(method, path, strings.NewReader(string(body)))+ req.Header.Set(UserHeader, "alice")+ out := httptest.NewRecorder()+ manager.Handler().ServeHTTP(out, req)+ if out.Code != status {+ t.Fatalf("%s %s: %d %s", method, path, out.Code, out.Body.String())+ }+ return out.Body.Bytes()+ }+ request("POST", plugin.SettingsPath+"/packages", map[string]string{"pluginId": "native"}, 200)+ request("PUT", plugin.SettingsPath+"/packages/%40fixture%2Fnative", map[string]bool{"enabled": true}, 200)+ listed := request("GET", plugin.AuthorizationPath, nil, 200)+ if !strings.Contains(string(listed), `"canDisconnect":true`) || !strings.Contains(string(listed), `"configured":false`) {+ t.Fatal(string(listed))+ }+ var attempt struct{ ID, Status string }+ if err = json.Unmarshal(request("POST", plugin.AuthorizationPath, plugin.AuthorizationStart{Key: "native/account"}, 202), &attempt); err != nil {+ t.Fatal(err)+ }+ deadline := time.Now().Add(4 * time.Second)+ for attempt.Status != "authorized" {+ if time.Now().After(deadline) {+ t.Fatalf("native authorization did not settle: %+v", attempt)+ }+ if err = json.Unmarshal(request("GET", plugin.AuthorizationPath+"/"+attempt.ID, nil, 200), &attempt); err != nil {+ t.Fatal(err)+ }+ time.Sleep(5 * time.Millisecond)+ }+ listed = request("GET", plugin.AuthorizationPath, nil, 200)+ if !strings.Contains(string(listed), `"accountLabel":"[email protected]"`) || !strings.Contains(string(listed), `"configured":true`) {+ t.Fatal(string(listed))+ }+ response := request("POST", plugin.AuthorizationPath+"/disconnect", map[string]string{"key": "native/account"}, 200)+ if !strings.Contains(string(response), `"configured":false`) {+ t.Fatal(string(response))+ }+ listed = request("GET", plugin.AuthorizationPath, nil, 200)+ if !strings.Contains(string(listed), `"configured":false`) {+ t.Fatal(string(listed))+ }+ request("POST", plugin.AuthorizationPath+"/disconnect", map[string]string{"key": "missing/account"}, 404)+}diff --git a/internal/controller/controller.go b/internal/controller/controller.goindex fb402d1..7f05cae 100644--- a/internal/controller/controller.go+++ b/internal/controller/controller.go@@ -15,6 +15,7 @@ import ("time""github.com/google/uuid"+ "go-bot/extensions/catalog""go-bot/internal/config"dock "go-bot/providers/runtime/docker"cloud "go-bot/providers/runtime/eci"@@ -38,7 +39,9 @@ type Manager struct {Client *http.ClientaccountLocks [64]sync.Mutex+ pluginLocks [64]sync.Mutexcontainerized bool+ pluginCatalog []catalog.Entry}func InContainer() bool { return os.Getenv("CONTROLLER_CONTAINER") == "1" }@@ -65,6 +68,7 @@ func New(c config.Config, driver runtime.Driver, store AccountStore) *Manager {return &Manager{Config: c, Driver: driver, Store: store,containerized: InContainer(),+ pluginCatalog: catalog.Entries(),Client: &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }},}}@@ -73,6 +77,11 @@ func (m *Manager) accountLock(id string) *sync.Mutex {return &m.accountLocks[crc32.ChecksumIEEE([]byte(id))%uint32(len(m.accountLocks))]}+// Package downloads serialize only plugin mutations, never ordinary account work.+func (m *Manager) pluginLock(id string) *sync.Mutex {+ return &m.pluginLocks[crc32.ChecksumIEEE([]byte(id))%uint32(len(m.pluginLocks))]+}+func (m *Manager) CreateAccount(ctx context.Context, id string) error {if !userName.MatchString(id) {return errInvalidAccountdiff --git a/internal/controller/controller_test.go b/internal/controller/controller_test.goindex 1512837..1f56607 100644--- a/internal/controller/controller_test.go+++ b/internal/controller/controller_test.go@@ -14,6 +14,7 @@ import ("go-bot/internal/config""go-bot/internal/modelsettings""go-bot/internal/providersettings"+ "go-bot/plugin""go-bot/runtime")@@ -47,10 +48,24 @@ func (s *memoryStore) Save(_ context.Context, id string, account Account) errorsaved := s.records[id]account.WebSearch = saved.WebSearchaccount.ImageGeneration = saved.ImageGeneration+ account.Plugins = saved.Pluginss.records[id] = accountreturn nil}+func (s *memoryStore) SavePluginSettings(_ context.Context, id string, settings plugin.Settings) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ record, ok := s.records[id]+ if !ok {+ return ErrAccountNotFound+ }+ settings = settings.Clone()+ record.Plugins = &settings+ s.records[id] = record+ return nil+}+func (s *memoryStore) SaveProviderSettings(_ context.Context, id, field string, settings providersettings.Settings) error {s.mu.Lock()defer s.mu.Unlock()diff --git a/internal/controller/http.go b/internal/controller/http.goindex f4ea1fc..fcb25ce 100644--- a/internal/controller/http.go+++ b/internal/controller/http.go@@ -5,6 +5,8 @@ import ("encoding/json""errors""github.com/google/uuid"+ mcpconfig "go-bot/mcp"+ "go-bot/plugin""io""net/http""net/http/httputil"@@ -45,6 +47,17 @@ func (m *Manager) Handler() http.Handler {func (m *Manager) HandlerWithWeb(web WebOptions) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // The provider redirects without an account header and from another+ // origin. Only this exact GET callback uses its one-time Host state;+ // ordinary APIs retain their existing browser-origin checks.+ if strings.HasPrefix(r.URL.Path, mcpconfig.OAuthCallbackPath) {+ m.mcpOAuthCallbackHTTP(w, r)+ return+ }+ if strings.HasPrefix(r.URL.Path, plugin.AuthorizationCallbackPath) {+ m.pluginAuthorizationCallbackHTTP(w, r)+ return+ }if strings.HasPrefix(r.URL.Path, "/v1/") {w.Header().Add("Vary", "Origin")w.Header().Add("Vary", "Sec-Fetch-Site")@@ -62,6 +75,9 @@ func (m *Manager) HandlerWithWeb(web WebOptions) http.Handler {w.WriteHeader(http.StatusOK)return}+ if servePluginAsset(w, r) {+ return+ }if serveWeb(w, r, web.Files) {return}@@ -71,7 +87,8 @@ func (m *Manager) HandlerWithWeb(web WebOptions) http.Handler {}isHost := r.URL.Path == "/v1/host" || strings.HasPrefix(r.URL.Path, "/v1/host/") || strings.HasPrefix(r.URL.Path, "/v1/hosts/")isSession := r.URL.Path == "/v1/capabilities" || r.URL.Path == "/v1/sessions" || strings.HasPrefix(r.URL.Path, "/v1/sessions/")- isSettings := r.URL.Path == settingsPath || strings.HasPrefix(r.URL.Path, settingsPath+"/") || r.URL.Path == webSearchSettingsPath || r.URL.Path == imageSettingsPath+ isPlugins := r.URL.Path == plugin.SettingsPath || strings.HasPrefix(r.URL.Path, plugin.SettingsPath+"/")+ isSettings := isPlugins || r.URL.Path == settingsPath || strings.HasPrefix(r.URL.Path, settingsPath+"/") || r.URL.Path == webSearchSettingsPath || r.URL.Path == imageSettingsPathif !isHost && !isSession && !isSettings {http.NotFound(w, r)return@@ -81,7 +98,20 @@ func (m *Manager) HandlerWithWeb(web WebOptions) http.Handler {httpError(w, http.StatusBadRequest, "provide a valid X-User-ID")return}+ // Keep the actual, validated public callback with this request. Invalid+ // or ordinary non-loopback HTTP origins do not enable OAuth, but still+ // support normal Host operations and static credentials.+ redirect, _ := mcpOAuthRedirect(r, r.Header.Get(mcpconfig.ControllerOriginHeader), id)+ r = r.WithContext(withOAuthCallback(r.Context(), redirect))switch {+ case r.URL.Path == plugin.AuthorizationPath || strings.HasPrefix(r.URL.Path, plugin.AuthorizationPath+"/"):+ m.authorizationHTTP(w, r, id)+ case r.URL.Path == mcpconfig.RuntimePath || strings.HasPrefix(r.URL.Path, mcpconfig.RuntimePath+"/"):+ m.mcpHTTP(w, r, id)+ case isPlugins:+ m.pluginsHTTP(w, r, id)+ case r.URL.Path == "/v1/host/plugins/runtime/restart":+ m.restartPluginsHTTP(w, r, id)case isHost:m.hostHTTP(w, r, id)case r.URL.Path == webSearchSettingsPath:@@ -130,6 +160,7 @@ func (m *Manager) hostHTTP(w http.ResponseWriter, r *http.Request, id string) {var err errorswitch {case (r.URL.Path == hostFilesPath && r.Method == http.MethodGet) ||+ (r.URL.Path == "/v1/host/stream" && r.Method == http.MethodGet) ||r.URL.Path == "/v1/host/schedules" || strings.HasPrefix(r.URL.Path, "/v1/host/schedules/"):m.forward(w, r, id)return@@ -244,6 +275,11 @@ func (m *Manager) forward(w http.ResponseWriter, r *http.Request, id string) {Rewrite: func(req *httputil.ProxyRequest) {req.SetURL(target)req.Out.Header.Del(UserHeader)+ req.Out.Header.Del(mcpconfig.ControllerOriginHeader)+ req.Out.Header.Del(mcpconfig.OAuthCallbackHeader)+ if redirect := oauthCallbackFromContext(req.In.Context()); redirect != "" {+ req.Out.Header.Set(mcpconfig.OAuthCallbackHeader, redirect)+ }req.Out.Header.Set("Authorization", "Bearer "+record.HostToken)},ModifyResponse: func(response *http.Response) error {diff --git a/internal/controller/mcp.go b/internal/controller/mcp.gonew file mode 100644index 0000000..0df3999--- /dev/null+++ b/internal/controller/mcp.go@@ -0,0 +1,98 @@+package controller++import (+ "context"+ "errors"+ "net/http"+ "net/url"+ "strings"+ "time"++ mcpconfig "go-bot/mcp"+)++func (m *Manager) mcpView(ctx context.Context, account Account) mcpconfig.View {+ status := mcpconfig.Status{Servers: []mcpconfig.ServerStatus{}}+ if account.DesiredState == running && account.HostEndpoint != "" {+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ if err := m.requestExtension(ctx, account, http.MethodGet, mcpconfig.InternalPath, nil, &status); err != nil {+ status.Error = "host_mcp_unavailable"+ }+ } else {+ status.Error = "host_not_running"+ }+ return mcpconfig.View{Status: status}+}+func (m *Manager) mcpHTTP(w http.ResponseWriter, r *http.Request, id string) {+ account, err := m.Store.Get(r.Context(), id)+ if errors.Is(err, ErrAccountNotFound) {+ httpError(w, 404, "account not found")+ return+ }+ if err != nil {+ httpError(w, 503, "mcp_settings_unavailable")+ return+ }+ runtimeSuffix, runtimeRequest := strings.CutPrefix(r.URL.EscapedPath(), mcpconfig.RuntimePath)+ if runtimeRequest && runtimeSuffix != "" {+ name, action, found := strings.Cut(strings.TrimPrefix(runtimeSuffix, "/servers/"), "/")+ postAction := r.Method == http.MethodPost && (action == "restart" || action == "probe" || action == "authorize")+ deleteAction := r.Method == http.MethodDelete && (action == "authorization" || action == "grant")+ if !strings.HasPrefix(runtimeSuffix, "/servers/") || !found || (!postAction && !deleteAction) {+ http.NotFound(w, r)+ return+ }+ if !mcpconfig.ValidServerName(name) {+ httpError(w, 400, "invalid_mcp_server")+ return+ }+ if account.DesiredState != running || account.HostEndpoint == "" {+ httpError(w, 409, "host_not_running")+ return+ }+ if action == "authorize" {+ m.startMCPOAuthHTTP(w, r, id, name, account)+ return+ }+ if deleteAction {+ target := mcpconfig.InternalPath + "/servers/" + name + "/" + action+ if action == "authorization" {+ attemptID := r.URL.Query().Get("id")+ if len(attemptID) > 128 {+ httpError(w, 400, "invalid_authorization_id")+ return+ }+ if attemptID != "" {+ target += "?id=" + url.QueryEscape(attemptID)+ }+ }+ if err = m.requestExtension(r.Context(), account, http.MethodDelete, target, nil, nil); err != nil {+ writeJSON(w, 502, map[string]string{"error": "mcp_authorization_failed", "message": err.Error()})+ return+ }+ writeJSON(w, 200, m.mcpView(r.Context(), account))+ return+ }+ if action == "probe" {+ var result mcpconfig.ServerStatus+ if err = m.requestExtension(r.Context(), account, http.MethodPost, mcpconfig.InternalPath+"/servers/"+name+"/probe", nil, &result); err != nil {+ httpError(w, 502, "host_mcp_probe_failed")+ return+ }+ writeJSON(w, 200, result)+ return+ }+ if err = m.requestExtension(r.Context(), account, http.MethodPost, mcpconfig.InternalPath+"/servers/"+name+"/restart", nil, nil); err != nil {+ httpError(w, 502, "host_mcp_restart_failed")+ return+ }+ writeJSON(w, 200, m.mcpView(r.Context(), account))+ return+ }+ if r.URL.Path == mcpconfig.RuntimePath && r.Method == http.MethodGet {+ writeJSON(w, http.StatusOK, m.mcpView(r.Context(), account))+ return+ }+ http.NotFound(w, r)+}diff --git a/internal/controller/mcp_oauth.go b/internal/controller/mcp_oauth.gonew file mode 100644index 0000000..c3e9f26--- /dev/null+++ b/internal/controller/mcp_oauth.go@@ -0,0 +1,154 @@+package controller++import (+ "context"+ "errors"+ "net/http"+ "net/url"+ "strings"++ "go-bot/internal/config"+ mcpconfig "go-bot/mcp"+)++type oauthCallbackContextKey struct{}++func withOAuthCallback(ctx context.Context, redirect string) context.Context {+ return context.WithValue(ctx, oauthCallbackContextKey{}, redirect)+}++func oauthCallbackFromContext(ctx context.Context) string {+ value, _ := ctx.Value(oauthCallbackContextKey{}).(string)+ return value+}++// The client supplies only its visible origin, never a free-form redirect.+// Host is the actual request Host; forwarded host/proto headers are not trusted+// to select an OAuth destination. A proxy should preserve the public Host.+func mcpOAuthRedirect(r *http.Request, origin, user string) (string, error) {+ if origin == "" {+ origin = r.Header.Get("Origin")+ }+ if origin == "" {+ scheme := "http"+ if r.TLS != nil {+ scheme = "https"+ }+ origin = scheme + "://" + r.Host+ }+ u, err := url.Parse(origin)+ if err != nil || u.Hostname() == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || len(origin) > 4096 {+ return "", errors.New("invalid_controller_origin")+ }+ defaultPort := ":80"+ if u.Scheme == "https" {+ defaultPort = ":443"+ }+ if !strings.EqualFold(strings.TrimSuffix(u.Host, defaultPort), strings.TrimSuffix(r.Host, defaultPort)) {+ return "", errors.New("controller_origin_must_match_request_host")+ }+ if u.Scheme != "https" && (u.Scheme != "http" || !config.IsLoopbackHost(u.Hostname())) {+ return "", errors.New("oauth_requires_https_or_loopback_http")+ }+ return u.Scheme + "://" + u.Host + mcpconfig.OAuthCallbackPath + url.PathEscape(user), nil+}++func (m *Manager) startMCPOAuthHTTP(w http.ResponseWriter, r *http.Request, id, name string, account Account) {+ var input struct {+ Origin string `json:"origin"`+ }+ if decodeJSON(http.MaxBytesReader(w, r.Body, 16<<10), &input) != nil {+ httpError(w, 400, "invalid_mcp_authorization_request")+ return+ }+ redirect, err := mcpOAuthRedirect(r, input.Origin, id)+ if err != nil {+ httpError(w, 400, err.Error())+ return+ }+ var authorization mcpconfig.OAuthAuthorization+ if err := m.requestExtension(withOAuthCallback(r.Context(), redirect), account, http.MethodPost, mcpconfig.InternalPath+"/servers/"+name+"/authorize", map[string]string{"redirectUrl": redirect}, &authorization); err != nil {+ writeJSON(w, 502, map[string]string{"error": "mcp_authorization_failed", "message": err.Error()})+ return+ }+ writeJSON(w, 200, authorization)+}++func writeOAuthCallbackPage(w http.ResponseWriter, r *http.Request, status int, state string) {+ title, text := "Authorization could not be completed", "Return to Go Bot and start authorization again."+ if state == "received" {+ title, text = "Authorization received", "You can close this page and check the connection in Go Bot."+ }+ if state == "authorized" {+ title, text = "Authorization completed", "You can close this page and return to Go Bot."+ }+ if state == "pending" {+ title, text = "Additional authorization needed", "Return to Go Bot to continue the provider authorization."+ }+ lang := "en"+ if strings.HasPrefix(strings.ToLower(r.Header.Get("Accept-Language")), "zh") {+ lang = "zh-CN"+ title, text = "未能完成授权", "请返回 Go Bot,重新发起授权。"+ if state == "received" {+ title, text = "已收到授权", "可以关闭此页面,返回 Go Bot 查看连接结果。"+ }+ if state == "authorized" {+ title, text = "授权已完成", "可以关闭此页面,返回 Go Bot。"+ }+ if state == "pending" {+ title, text = "需要补充授权", "请返回 Go Bot,继续服务商要求的授权。"+ }+ }+ w.Header().Set("Content-Type", "text/html; charset=utf-8")+ w.Header().Set("Cache-Control", "no-store")+ w.Header().Set("Referrer-Policy", "no-referrer")+ w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'")+ w.WriteHeader(status)+ // All interpolated strings are fixed application copy, never provider or+ // callback input. Authorization codes and state do not enter the page.+ _, _ = w.Write([]byte(`<!doctype html><html lang="` + lang + `"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>` + title + `</title><style>body{font:16px system-ui,sans-serif;color:#263145;background:#f6f8fc;max-width:520px;margin:16vh auto;padding:32px}h1{font-size:24px;letter-spacing:-.4px}p{line-height:1.7;color:#637087}</style><h1>` + title + `</h1><p>` + text + `</p></html>`))+}++func (m *Manager) mcpOAuthCallbackHTTP(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ w.Header().Set("Allow", http.MethodGet)+ writeOAuthCallbackPage(w, r, 405, "")+ return+ }+ id := strings.TrimPrefix(r.URL.Path, mcpconfig.OAuthCallbackPath)+ if !userName.MatchString(id) {+ writeOAuthCallbackPage(w, r, 400, "")+ return+ }+ query, err := url.ParseQuery(r.URL.RawQuery)+ if err != nil || len(r.URL.RawQuery) > 24<<10 {+ writeOAuthCallbackPage(w, r, 400, "")+ return+ }+ for _, name := range []string{"state", "code", "iss", "error"} {+ if len(query[name]) > 1 {+ writeOAuthCallbackPage(w, r, 400, "")+ return+ }+ }+ if query.Get("state") == "" || query.Has("code") == query.Has("error") || (query.Has("code") && query.Get("code") == "") || (query.Has("error") && query.Get("error") == "") {+ writeOAuthCallbackPage(w, r, 400, "")+ return+ }+ account, err := m.Store.Get(r.Context(), id)+ if err != nil {+ writeOAuthCallbackPage(w, r, 404, "")+ return+ }+ if account.DesiredState != running || account.HostEndpoint == "" {+ writeOAuthCallbackPage(w, r, 409, "")+ return+ }+ var view mcpconfig.OAuthCallbackReceipt+ err = m.requestExtension(r.Context(), account, http.MethodPost, mcpconfig.InternalPath+"/oauth/callback", mcpconfig.OAuthCallback{State: query.Get("state"), Code: query.Get("code"), Issuer: query.Get("iss"), Error: query.Get("error")}, &view)+ if err != nil || (view.State != "received" && view.State != "rejected") {+ writeOAuthCallbackPage(w, r, 400, "")+ return+ }+ writeOAuthCallbackPage(w, r, 200, view.State)+}diff --git a/internal/controller/mcp_oauth_test.go b/internal/controller/mcp_oauth_test.gonew file mode 100644index 0000000..08bbe55--- /dev/null+++ b/internal/controller/mcp_oauth_test.go@@ -0,0 +1,310 @@+package controller++import (+ "context"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ "go-bot/internal/config"+ "go-bot/internal/hostruntime"+ "go-bot/internal/httpapi"+ "go-bot/internal/mcpclient"+ mcpconfig "go-bot/mcp"+)++func TestMCPOAuthRedirectUsesActualHostWithoutTrustingForwardedDestination(t *testing.T) {+ for _, test := range []struct {+ target, origin, forwardedHost, forwardedProto, want string+ valid bool+ }{+ {"http://127.0.0.1:8080/start", "", "attacker.example", "https", "http://127.0.0.1:8080" + mcpconfig.OAuthCallbackPath + "alice", true},+ {"http://controller.example/start", "https://controller.example", "attacker.example", "http", "https://controller.example" + mcpconfig.OAuthCallbackPath + "alice", true},+ {"http://controller.example/start", "", "controller.example", "https", "", false},+ {"https://controller.example/start", "https://attacker.example", "", "", "", false},+ {"https://controller.example/start", "https://controller.example/elsewhere", "", "", "", false},+ {"https://controller.example/start", "https://[email protected]", "", "", "", false},+ } {+ r := httptest.NewRequest(http.MethodPost, test.target, nil)+ r.Header.Set("X-Forwarded-Host", test.forwardedHost)+ r.Header.Set("X-Forwarded-Proto", test.forwardedProto)+ redirect, err := mcpOAuthRedirect(r, test.origin, "alice")+ if (err == nil) != test.valid || redirect != test.want {+ t.Fatalf("%+v -> %q %v", test, redirect, err)+ }+ }+}++func TestControllerRejectsAmbiguousOAuthParametersBeforeHostAdmission(t *testing.T) {+ var calls atomic.Int32+ host := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls.Add(1)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"state":"received"}`))+ }))+ defer host.Close()+ store := &memoryStore{records: map[string]Account{"alice": {DesiredState: running, HostID: "callback-run", HostEndpoint: host.URL, HostToken: "private-fixture-token"}}}+ manager := New(config.Default(), nil, store)+ for _, query := range []string{+ "state=s&code=c&error=", "state=s&code=&error=access_denied", "state=s&code=c&error=server_error", "state=s&code=", "state=s&error=", "state=s", "code=c", "state=s&state=s&code=c", "state=s&code=c&code=c", "state=s&error=access_denied&error=access_denied", "state=s&code=c&iss=a&iss=b",+ } {+ response := httptest.NewRecorder()+ manager.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, mcpconfig.OAuthCallbackPath+"alice?"+query, nil))+ if response.Code != 400 {+ t.Fatalf("ambiguous callback admitted: %q status=%d", query, response.Code)+ }+ }+ if calls.Load() != 0 {+ t.Fatal("invalid query reached Host")+ }+ response := httptest.NewRecorder()+ manager.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, mcpconfig.OAuthCallbackPath+"alice?state=s&code=c", nil))+ if response.Code != 200 || calls.Load() != 1 || !strings.Contains(response.Body.String(), "Authorization received") {+ t.Fatal("valid callback could not reach Host")+ }+}++func TestControllerSuppliesVerifiedCallbackOnPrivateAndProxiedHostRequests(t *testing.T) {+ for _, path := range []string{mcpconfig.RuntimePath, "/v1/host/stream"} {+ for _, item := range []struct{ target, origin, want string }{+ {"https://controller.example", "", "https://controller.example"},+ {"http://controller.example", "https://controller.example", "https://controller.example"},+ {"http://127.0.0.1:8080", "", "http://127.0.0.1:8080"},+ {"http://controller.example", "", ""},+ {"http://controller.example", "https://attacker.example", ""},+ } {+ t.Run(path+"/"+item.target+"/"+item.origin, func(t *testing.T) {+ observed := make(chan string, 1)+ host := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ observed <- r.Header.Get(mcpconfig.OAuthCallbackHeader)+ if r.Header.Get("Authorization") != "Bearer private-callback-token" || r.Header.Get(UserHeader) != "" || r.Header.Get(mcpconfig.ControllerOriginHeader) != "" {+ t.Error("private routing identity was copied from external headers")+ }+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"servers":[]}`))+ }))+ defer host.Close()+ store := &memoryStore{records: map[string]Account{"alice": {DesiredState: running, HostID: "callback-run", HostEndpoint: host.URL, HostToken: "private-callback-token"}}}+ manager := New(config.Default(), nil, store)+ r := httptest.NewRequest(http.MethodGet, item.target+path, nil)+ r.Header.Set(UserHeader, "alice")+ r.Header.Set(mcpconfig.ControllerOriginHeader, item.origin)+ r.Header.Set(mcpconfig.OAuthCallbackHeader, "https://attacker.example"+mcpconfig.OAuthCallbackPath+"other")+ r.Header.Set("X-Forwarded-Host", "attacker.example")+ r.Header.Set("X-Forwarded-Proto", "https")+ out := httptest.NewRecorder()+ manager.Handler().ServeHTTP(out, r)+ want := item.want+ if want != "" {+ want += mcpconfig.OAuthCallbackPath + "alice"+ }+ var callback string+ select {+ case callback = <-observed:+ default:+ t.Fatal("Controller did not reach the Host")+ }+ if out.Code != 200 || callback != want {+ t.Fatalf("callback routing: status=%d got=%q want=%q", out.Code, callback, want)+ }+ })+ }+ }+}++func TestOAuthProviderBrowserCallbackPassesControllerToRealHostAndKeepsOtherAPIsProtected(t *testing.T) {+ testControllerOAuthFlow(t)+}++func testControllerOAuthFlow(t *testing.T) {+ var service *httptest.Server+ var tokenRequests atomic.Int32+ var challengeMu sync.Mutex+ challenge := ""+ remote := sdk.NewServer(&sdk.Implementation{Name: "full-oauth-fixture", Version: "1"}, nil)+ remote.AddTool(&sdk.Tool{Name: "ping", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {+ return &sdk.CallToolResult{}, nil+ })+ mcpHTTP := sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return remote }, nil)+ service = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ write := func(value any) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(value)+ }+ switch r.URL.Path {+ case "/.well-known/oauth-protected-resource/mcp":+ write(map[string]any{"resource": service.URL + "/mcp", "authorization_servers": []string{service.URL}, "scopes_supported": []string{"read"}})+ case "/.well-known/oauth-authorization-server":+ write(map[string]any{"issuer": service.URL, "authorization_endpoint": service.URL + "/authorize", "token_endpoint": service.URL + "/token", "response_types_supported": []string{"code"}, "grant_types_supported": []string{"authorization_code", "refresh_token"}, "token_endpoint_auth_methods_supported": []string{"none"}, "code_challenge_methods_supported": []string{"S256"}, "authorization_response_iss_parameter_supported": true})+ case "/authorize":+ values := r.URL.Query()+ challengeMu.Lock()+ challenge = values.Get("code_challenge")+ challengeMu.Unlock()+ callback, _ := url.Parse(values.Get("redirect_uri"))+ query := callback.Query()+ query.Set("code", "one-time-test-code")+ query.Set("state", values.Get("state"))+ query.Set("iss", service.URL)+ callback.RawQuery = query.Encode()+ http.Redirect(w, r, callback.String(), http.StatusFound)+ case "/token":+ tokenRequests.Add(1)+ _ = r.ParseForm()+ digest := sha256.Sum256([]byte(r.Form.Get("code_verifier")))+ challengeMu.Lock()+ expected := challenge+ challengeMu.Unlock()+ if r.Form.Get("code") != "one-time-test-code" || expected == "" || base64.RawURLEncoding.EncodeToString(digest[:]) != expected {+ http.Error(w, "invalid PKCE exchange", 400)+ return+ }+ write(map[string]any{"access_token": "controller-fixture-private-token", "refresh_token": "controller-fixture-private-refresh", "expires_in": 3600, "token_type": "Bearer"})+ case "/mcp":+ if r.Header.Get("Authorization") != "Bearer controller-fixture-private-token" {+ w.Header().Set("WWW-Authenticate", `Bearer resource_metadata="`+service.URL+`/.well-known/oauth-protected-resource/mcp"`)+ http.Error(w, "authorization required", 401)+ return+ }+ mcpHTTP.ServeHTTP(w, r)+ default:+ http.NotFound(w, r)+ }+ }))+ defer service.Close()+ hostManager := mcpclient.NewManager(t.Context(), mcpclient.ManagerOptions{CWD: t.TempDir()})+ defer hostManager.Close()+ settings := mcpconfig.Settings{Servers: map[string]mcpconfig.Server{"oauth": {Transport: "streamable-http", URL: service.URL + "/mcp", OAuth: &mcpconfig.OAuth{ClientID: "fixture-client"}}}}+ if _, err := hostManager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ native := &hostruntime.NativeHost{UserID: "alice", MCPChanges: hostManager.Changes}+ streamHandler := httpapi.NewNativeHostHTTP(native, httpapi.NativeWorkerHTTPOptions{})+ hostHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/v1/host/stream" {+ streamHandler.ServeHTTP(w, r)+ return+ }+ hostManager.Handler().ServeHTTP(w, r)+ })+ host := httptest.NewServer(httpapi.Authenticate("private-oauth-host", hostManager.ControllerOAuth(hostHandler)))+ defer host.Close()+ store := &memoryStore{records: map[string]Account{+ "alice": {DesiredState: running, HostID: "oauth-fixture-run", HostEndpoint: host.URL, HostToken: "private-oauth-host"},+ "stopped": {DesiredState: stopped},+ }}+ controller := New(config.Default(), nil, store)+ public := httptest.NewServer(controller.Handler())+ defer public.Close()+ ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)+ defer cancel()+ client := &http.Client{Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}+ var authorization mcpconfig.OAuthAuthorization+ var response *http.Response+ var err error++ request, _ := http.NewRequestWithContext(ctx, http.MethodPost, public.URL+mcpconfig.RuntimePath+"/servers/oauth/authorize", strings.NewReader(`{"origin":"`+public.URL+`"}`))+ request.Header.Set(UserHeader, "alice")+ request.Header.Set("Content-Type", "application/json")+ response, err = client.Do(request)+ if err != nil {+ t.Fatal(err)+ }+ if response.StatusCode != 200 {+ data, _ := io.ReadAll(response.Body)+ response.Body.Close()+ t.Fatalf("start=%d %s", response.StatusCode, data)+ }+ err = json.NewDecoder(response.Body).Decode(&authorization)+ response.Body.Close()+ if err != nil {+ t.Fatal(err)+ }++ if authorization.ID == "" || authorization.Phase != "waiting-browser" {+ t.Fatalf("authorization identity missing: %+v", authorization)+ }+ staleCancel, _ := http.NewRequestWithContext(ctx, http.MethodDelete, public.URL+mcpconfig.RuntimePath+"/servers/oauth/authorization?id=older-attempt", nil)+ staleCancel.Header.Set(UserHeader, "alice")+ staleResponse, err := client.Do(staleCancel)+ if err != nil {+ t.Fatal(err)+ }+ staleResponse.Body.Close()+ if staleResponse.StatusCode != http.StatusOK {+ t.Fatalf("stale cancellation failed: %d", staleResponse.StatusCode)+ }+ response, err = client.Get(authorization.URL)+ if err != nil {+ t.Fatal(err)+ }+ callback, err := response.Location()+ response.Body.Close()+ if err != nil {+ t.Fatal(err)+ }+ wrong := *callback+ wrong.Path = mcpconfig.OAuthCallbackPath + "stopped"+ response, err = client.Get(wrong.String())+ if err != nil {+ t.Fatal(err)+ }+ response.Body.Close()+ if response.StatusCode != 409 || tokenRequests.Load() != 0 {+ t.Fatal("callback started a stopped Host or exchanged another account's code")+ }+ callbackRequest, _ := http.NewRequestWithContext(ctx, http.MethodGet, callback.String(), nil)+ callbackRequest.Header.Set("Origin", service.URL)+ callbackRequest.Header.Set("Sec-Fetch-Site", "cross-site")+ response, err = client.Do(callbackRequest)+ if err != nil {+ t.Fatal(err)+ }+ page, _ := io.ReadAll(response.Body)+ response.Body.Close()+ if response.StatusCode != 200 || !strings.Contains(string(page), "Authorization received") || strings.Contains(string(page), "one-time-test-code") || strings.Contains(string(page), "private-token") {+ t.Fatalf("callback=%d %s", response.StatusCode, page)+ }+ for {+ changed, _ := hostManager.Changes()+ servers := hostManager.Status().Servers+ if len(servers) == 1 && servers[0].State == "connected" && tokenRequests.Load() == 1 {+ break+ }+ select {+ case <-changed:+ case <-ctx.Done():+ t.Fatal("Controller callback did not activate the real Host connection", ctx.Err())+ }+ }+ response, err = client.Get(callback.String())+ if err != nil {+ t.Fatal(err)+ }+ response.Body.Close()+ if response.StatusCode != 400 || tokenRequests.Load() != 1 {+ t.Fatal("callback replay reached token exchange")+ }+ ordinary, _ := http.NewRequest(http.MethodGet, public.URL+mcpconfig.RuntimePath, nil)+ ordinary.Header.Set(UserHeader, "alice")+ ordinary.Header.Set("Origin", service.URL)+ ordinary.Header.Set("Sec-Fetch-Site", "cross-site")+ response, err = client.Do(ordinary)+ if err != nil {+ t.Fatal(err)+ }+ response.Body.Close()+ if response.StatusCode != 403 {+ t.Fatal("OAuth callback exemption relaxed ordinary API origin checks")+ }+}diff --git a/internal/controller/mcp_test.go b/internal/controller/mcp_test.gonew file mode 100644index 0000000..8b1e667--- /dev/null+++ b/internal/controller/mcp_test.go@@ -0,0 +1,124 @@+package controller++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ "go-bot/internal/config"+ "go-bot/internal/httpapi"+ "go-bot/internal/mcpclient"+ mcpconfig "go-bot/mcp"+)++func TestMCPIsPluginOwnedAndHasNoAccountConfigurationAPI(t *testing.T) {+ remote := sdk.NewServer(&sdk.Implementation{Name: "controller-fixture", Version: "1"}, nil)+ remote.AddTool(&sdk.Tool{Name: "ping", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {+ return &sdk.CallToolResult{}, nil+ })+ remoteHTTP := httptest.NewServer(sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return remote }, nil))+ defer remoteHTTP.Close()+ fleet := mcpclient.NewManager(t.Context(), mcpclient.ManagerOptions{})+ defer fleet.Close()+ // Same Go entry point used by a Cordis plugin contribution. The account+ // stores no parallel MCP intent or credential document.+ if err := fleet.Register(t.Context(), "knowledge", "knowledge-plugin:1", mcpconfig.Server{Transport: "streamable-http", URL: remoteHTTP.URL, Headers: map[string]string{"Authorization": "Bearer fixture-private"}}); err != nil {+ t.Fatal(err)+ }+ host := httptest.NewServer(httpapi.Authenticate("private-host-token", fleet.Handler()))+ defer host.Close()+ store := &memoryStore{records: map[string]Account{"alice": {DesiredState: running, HostEndpoint: host.URL, HostToken: "private-host-token"}}}+ controller := New(config.Default(), nil, store)+ request := func(method, path string) *httptest.ResponseRecorder {+ r := httptest.NewRequest(method, path, nil)+ r.Header.Set(UserHeader, "alice")+ w := httptest.NewRecorder()+ controller.Handler().ServeHTTP(w, r)+ return w+ }+ for _, path := range []string{"/v1/settings/mcp", "/v1/settings/mcp/servers/knowledge", "/v1/settings/mcp/credentials/key"} {+ for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodDelete} {+ if w := request(method, path); w.Code != http.StatusNotFound {+ t.Fatalf("removed configuration API %s %s = %d", method, path, w.Code)+ }+ }+ }+ for _, path := range []string{mcpconfig.RuntimePath, mcpconfig.RuntimePath + "/servers/knowledge/probe", mcpconfig.RuntimePath + "/servers/knowledge/restart"} {+ method := http.MethodPost+ if path == mcpconfig.RuntimePath {+ method = http.MethodGet+ }+ w := request(method, path)+ if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "fixture-private") || strings.Contains(w.Body.String(), "private-host-token") || strings.Contains(w.Body.String(), `"settings"`) {+ t.Fatalf("runtime response %s = %d %s", path, w.Code, w.Body)+ }+ }+ if status := fleet.Status(); len(status.Servers) != 1 || status.Servers[0].Owner != "knowledge-plugin:1" {+ t.Fatalf("ownership missing: %+v", status)+ }+ if err := fleet.Release(t.Context(), "knowledge", "knowledge-plugin:1"); err != nil {+ t.Fatal(err)+ }+ if len(fleet.Status().Servers) != 0 {+ t.Fatal("plugin disposal retained MCP")+ }+}++func TestStoppedHostMCPStatusDoesNotStartHost(t *testing.T) {+ store := &memoryStore{records: map[string]Account{"alice": {DesiredState: stopped}}}+ controller := New(config.Default(), nil, store)+ for _, tc := range []struct {+ method, path string+ code int+ }{+ {http.MethodGet, mcpconfig.RuntimePath, 200},+ {http.MethodPost, mcpconfig.RuntimePath + "/servers/test/restart", 409},+ {http.MethodPost, mcpconfig.RuntimePath + "/servers/test/probe", 409},+ } {+ r := httptest.NewRequest(tc.method, tc.path, nil)+ r.Header.Set(UserHeader, "alice")+ w := httptest.NewRecorder()+ controller.Handler().ServeHTTP(w, r)+ if w.Code != tc.code {+ t.Fatalf("%s: %d %s", tc.path, w.Code, w.Body)+ }+ }+}++func TestRuntimeMCPProbeDoesNotWaitForAccountMutationLock(t *testing.T) {+ host := httptest.NewServer(httpapi.Authenticate("probe-token", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != mcpconfig.InternalPath+"/servers/test/probe" {+ http.NotFound(w, r)+ return+ }+ writeJSON(w, 200, mcpconfig.ServerStatus{Name: "test", Source: "plugin", State: "connected", ToolCount: 1})+ })))+ defer host.Close()+ store := &memoryStore{records: map[string]Account{"alice": {DesiredState: running, HostEndpoint: host.URL, HostToken: "probe-token"}}}+ controller := New(config.Default(), nil, store)+ lock := controller.accountLock("alice")+ lock.Lock()+ finished := make(chan *httptest.ResponseRecorder, 1)+ go func() {+ r := httptest.NewRequest(http.MethodPost, mcpconfig.RuntimePath+"/servers/test/probe", nil)+ r.Header.Set(UserHeader, "alice")+ w := httptest.NewRecorder()+ controller.Handler().ServeHTTP(w, r)+ finished <- w+ }()+ select {+ case response := <-finished:+ lock.Unlock()+ if response.Code != 200 {+ t.Fatalf("probe=%d %s", response.Code, response.Body)+ }+ case <-time.After(2 * time.Second):+ lock.Unlock()+ <-finished+ t.Fatal("runtime probe was serialized behind the account mutation lock")+ }+}diff --git a/internal/controller/model_protocol_test.go b/internal/controller/model_protocol_test.gonew file mode 100644index 0000000..d090028--- /dev/null+++ b/internal/controller/model_protocol_test.go@@ -0,0 +1,43 @@+package controller++import (+ "encoding/json"+ "net/http"+ "strings"+ "testing"++ "go-bot/internal/modelsettings"+)++func TestModelProtocolPersistsAndPublicViewHidesKey(t *testing.T) {+ manager := newTestManager(t, "docker", &fakeDriver{}, func(w http.ResponseWriter, r *http.Request) { controlReply(w, r) })+ if err := manager.CreateAccount(t.Context(), "protocol-test"); err != nil {+ t.Fatal(err)+ }+ out := controllerCall(manager, http.MethodPost, settingsPath+"/endpoints", "protocol-test", `{"name":"Anthropic","protocol":"anthropic_messages","baseUrl":"https://models.example/v1/","apiKey":"secret-should-not-leak","models":["custom-model"]}`)+ if out.Code != http.StatusCreated {+ t.Fatalf("%d %s", out.Code, out.Body)+ }+ var saved struct {+ EndpointID string `json:"endpointId"`+ }+ _ = json.Unmarshal(out.Body.Bytes(), &saved)+ state, err := manager.Store.LoadModels(t.Context(), "protocol-test")+ if err != nil || state.Catalog.Endpoints[saved.EndpointID].Protocol != modelsettings.AnthropicMessages {+ t.Fatalf("protocol not persisted: %v", err)+ }+ view := controllerCall(manager, http.MethodGet, settingsPath, "protocol-test", "")+ if !strings.Contains(view.Body.String(), `"protocol":"anthropic_messages"`) || strings.Contains(view.Body.String(), "secret-should-not-leak") {+ t.Fatal("public view lost protocol or exposed secret")+ }+ for _, body := range []string{`{"protocol":"guess"}`, `{"baseUrl":"https://models.example/v1/messages"}`} {+ bad := controllerCall(manager, http.MethodPatch, settingsPath+"/endpoints/"+saved.EndpointID, "protocol-test", body)+ if bad.Code != http.StatusBadRequest {+ t.Fatalf("accepted invalid config: %d %s", bad.Code, bad.Body)+ }+ }+ defaultProtocol, err := (endpointPatch{}).apply(modelsettings.Endpoint{Name: "Existing", BaseURL: "https://models.example/v1", APIKey: "k", Models: []string{"model"}})+ if err != nil || defaultProtocol.Protocol != modelsettings.Responses {+ t.Fatal("existing Responses endpoint changed")+ }+}diff --git a/internal/controller/models.go b/internal/controller/models.goindex c99d50d..b4d5e08 100644--- a/internal/controller/models.go+++ b/internal/controller/models.go@@ -19,6 +19,7 @@ import (const settingsPath = "/v1/settings/models"type publicEndpoint struct {+ Protocol string `json:"protocol"`Name string `json:"name"`BaseURL string `json:"baseUrl"`HasAPIKey bool `json:"hasApiKey"`@@ -86,7 +87,13 @@ func (m *Manager) syncAccountSettings(ctx context.Context, id string, record Accif err := m.syncModels(ctx, record, state); err != nil {return err}- return errors.Join(m.syncProviderSettings(ctx, record, searchSettings), m.syncProviderSettings(ctx, record, imageSettings))+ if err := errors.Join(m.syncProviderSettings(ctx, record, searchSettings), m.syncProviderSettings(ctx, record, imageSettings)); err != nil {+ return err+ }+ // A failed optional plugin is visible in its actual Host status. Keep the+ // personal computer available for ordinary built-in chat and configuration.+ _ = m.syncPlugins(ctx, id, record)+ return nil}func (m *Manager) hostHasModelRevision(ctx context.Context, record Account, revision int64) bool {@@ -121,13 +128,21 @@ func (m *Manager) sessionModelSelection(ctx context.Context, record Account, sta}type endpointPatch struct {- Name *string `json:"name"`- BaseURL *string `json:"baseUrl"`- APIKey *string `json:"apiKey"`- Models *[]string `json:"models"`+ Protocol *string `json:"protocol"`+ Name *string `json:"name"`+ BaseURL *string `json:"baseUrl"`+ APIKey *string `json:"apiKey"`+ Models *[]string `json:"models"`}func (p endpointPatch) apply(endpoint modelsettings.Endpoint) (modelsettings.Endpoint, error) {+ if p.Protocol != nil {+ endpoint.Protocol = *p.Protocol+ }+ endpoint.Protocol = modelsettings.NormalizeProtocol(endpoint.Protocol)+ if !modelsettings.ValidProtocol(endpoint.Protocol) {+ return endpoint, errors.New("invalid_model_protocol")+ }if p.Name != nil {endpoint.Name = strings.TrimSpace(*p.Name)}@@ -147,6 +162,10 @@ func (p endpointPatch) apply(endpoint modelsettings.Endpoint) (modelsettings.Endif p.Models != nil {endpoint.Models = *p.Models}+ parsed, parseErr := url.Parse(endpoint.BaseURL)+ if parseErr != nil || parsed == nil || strings.HasSuffix(parsed.Path, "/messages") || strings.HasSuffix(parsed.Path, "/responses") || strings.HasSuffix(parsed.Path, "/chat/completions") {+ return endpoint, errors.New("model_base_url_required")+ }if endpoint.Name == "" || len(endpoint.Name) > 128 || len(endpoint.BaseURL) > 2048 ||len(endpoint.APIKey) > 4096 || strings.ContainsAny(endpoint.APIKey, "\r\n\x00") ||len(endpoint.Models) == 0 || len(endpoint.Models) > 100 {@@ -189,7 +208,7 @@ func (m *Manager) modelSettingsHTTP(w http.ResponseWriter, r *http.Request, id scase path == "" && r.Method == http.MethodGet:endpoints := make(map[string]publicEndpoint, len(catalog.Endpoints))for key, endpoint := range catalog.Endpoints {- endpoints[key] = publicEndpoint{endpoint.Name, endpoint.BaseURL, endpoint.APIKey != "", endpoint.Models}+ endpoints[key] = publicEndpoint{Protocol: modelsettings.NormalizeProtocol(endpoint.Protocol), Name: endpoint.Name, BaseURL: endpoint.BaseURL, HasAPIKey: endpoint.APIKey != "", Models: endpoint.Models}}writeJSON(w, http.StatusOK, struct {DefaultEndpointID string `json:"defaultEndpointId"`diff --git a/internal/controller/plugin_assets.go b/internal/controller/plugin_assets.gonew file mode 100644index 0000000..20c048f--- /dev/null+++ b/internal/controller/plugin_assets.go@@ -0,0 +1,44 @@+package controller++import (+ "bytes"+ "crypto/sha256"+ "fmt"+ "net/http"+ "path"+ "strings"+ "time"++ pluginassets "go-bot/extensions/plugins"+)++// A content version prevents native image caches from retaining an old icon+// after a deployment replaces the resource named by plugin.json.+func pluginIconURL(path string) string {+ data, err := pluginassets.Asset(path)+ if err != nil {+ return path+ }+ digest := sha256.Sum256(data)+ return fmt.Sprintf("%s?v=%x", path, digest[:8])+}++func servePluginAsset(w http.ResponseWriter, r *http.Request) bool {+ if !strings.HasPrefix(r.URL.Path, pluginassets.AssetPrefix) {+ return false+ }+ if r.Method != http.MethodGet && r.Method != http.MethodHead {+ w.Header().Set("Allow", "GET, HEAD")+ w.WriteHeader(http.StatusMethodNotAllowed)+ return true+ }+ data, err := pluginassets.Asset(r.URL.Path)+ if err != nil {+ http.NotFound(w, r)+ return true+ }+ w.Header().Set("X-Content-Type-Options", "nosniff")+ w.Header().Set("Cache-Control", "no-cache")+ http.ServeContent(w, r, path.Base(r.URL.Path), time.Time{}, bytes.NewReader(data))+ return true+}diff --git a/internal/controller/plugin_assets_test.go b/internal/controller/plugin_assets_test.gonew file mode 100644index 0000000..06c6abb--- /dev/null+++ b/internal/controller/plugin_assets_test.go@@ -0,0 +1,73 @@+package controller++import (+ "bytes"+ "image/png"+ "net/http"+ "net/http/httptest"+ "strconv"+ "testing"++ "go-bot/extensions/catalog"+ pluginassets "go-bot/extensions/plugins"+)++func TestPluginManifestIconsAreServedWithoutAHost(t *testing.T) {+ handler := (&Manager{}).Handler()+ for _, plugin := range catalog.Entries() {+ res := httptest.NewRecorder()+ handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, plugin.Icon, nil))+ if res.Code != http.StatusOK || res.Header().Get("Content-Type") != "image/png" {+ t.Fatalf("%s: %d %s", plugin.Icon, res.Code, res.Header().Get("Content-Type"))+ }+ if _, err := png.Decode(res.Body); err != nil {+ t.Fatalf("%s: invalid image: %v", plugin.Icon, err)+ }+ head := httptest.NewRecorder()+ handler.ServeHTTP(head, httptest.NewRequest(http.MethodHead, plugin.Icon, nil))+ if head.Code != http.StatusOK || head.Body.Len() != 0 {+ t.Fatalf("HEAD %s: %d", plugin.Icon, head.Code)+ }+ }+ for _, path := range []string{"/assets/plugins/missing/icon.png", "/assets/plugins/agent-browser/../package.json"} {+ res := httptest.NewRecorder()+ handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, path, nil))+ if res.Code != http.StatusNotFound {+ t.Fatalf("unexpected asset %s: %d", path, res.Code)+ }+ }+}++func TestPluginTutorialVideoSupportsNativePlayerRequests(t *testing.T) {+ handler := (&Manager{}).Handler()+ count := 0+ for _, entry := range catalog.Entries() {+ for _, tutorial := range entry.Tutorials {+ count+++ t.Run(entry.ID+"/"+tutorial.Language, func(t *testing.T) {+ data, err := pluginassets.Asset(tutorial.Video)+ if err != nil {+ t.Fatal(err)+ }+ if len(data) < 32 || string(data[4:8]) != "ftyp" {+ t.Fatal("tutorial must be an actual MP4")+ }+ request := httptest.NewRequest(http.MethodGet, tutorial.Video, nil)+ request.Header.Set("Range", "bytes=0-31")+ res := httptest.NewRecorder()+ handler.ServeHTTP(res, request)+ if res.Code != http.StatusPartialContent || !bytes.Equal(res.Body.Bytes(), data[:32]) || res.Header().Get("Content-Range") != "bytes 0-31/"+strconv.Itoa(len(data)) || res.Header().Get("Content-Type") != "video/mp4" {+ t.Fatalf("video range: %d %v", res.Code, res.Header())+ }+ head := httptest.NewRecorder()+ handler.ServeHTTP(head, httptest.NewRequest(http.MethodHead, tutorial.Video, nil))+ if head.Code != http.StatusOK || head.Body.Len() != 0 || head.Header().Get("Content-Length") != strconv.Itoa(len(data)) {+ t.Fatalf("video HEAD: %d %v", head.Code, head.Header())+ }+ })+ }+ }+ if count == 0 {+ t.Fatal("no tutorial videos exercised")+ }+}diff --git a/internal/controller/plugin_concurrency_test.go b/internal/controller/plugin_concurrency_test.gonew file mode 100644index 0000000..1a36945--- /dev/null+++ b/internal/controller/plugin_concurrency_test.go@@ -0,0 +1,91 @@+package controller++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "go-bot/extensions/catalog"+ "go-bot/internal/config"+ "go-bot/plugin"+)++func TestSlowPluginInstallDoesNotBlockAccountRequests(t *testing.T) {+ started, release := make(chan struct{}), make(chan struct{})+ var once sync.Once+ unblock := func() { once.Do(func() { close(release) }) }+ defer unblock()+ host := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.URL.Path == plugin.InternalPath+"/packages/inspect":+ close(started)+ select {+ case <-release:+ case <-r.Context().Done():+ return+ }+ writeJSON(w, 200, plugin.PackageInfo{Name: "fixture", Version: "1.0.0", API: "1"})+ case r.URL.Path == "/readyz":+ w.WriteHeader(200)+ case r.Method == http.MethodPut:+ w.WriteHeader(http.StatusNoContent)+ default:+ writeJSON(w, 200, plugin.Status{Runtime: "running"})+ }+ }))+ defer host.Close()+ // Unblock the fake Host before its server cleanup if an assertion fails.+ defer unblock()+ store := &memoryStore{records: map[string]Account{"alice": {DesiredState: running, HostEndpoint: host.URL, HostToken: "fixture"}}}+ manager := New(config.Default(), nil, store)+ manager.pluginCatalog = []catalog.Entry{{CatalogEntry: plugin.CatalogEntry{ID: "fixture", Package: "fixture", Version: "1.0.0"}, Source: plugin.Source{Type: "registry", Spec: "[email protected]"}}}+ request := func(method, path, body string) *httptest.ResponseRecorder {+ r := httptest.NewRequest(method, path, strings.NewReader(body))+ r.Header.Set(UserHeader, "alice")+ out := httptest.NewRecorder()+ manager.Handler().ServeHTTP(out, r)+ return out+ }+ installed := make(chan *httptest.ResponseRecorder, 1)+ go func() { installed <- request("POST", plugin.SettingsPath+"/packages", `{"pluginId":"fixture"}`) }()+ select {+ case <-started:+ case <-time.After(3 * time.Second):+ t.Fatal("install did not reach the Host")+ }+ for _, path := range []string{plugin.SettingsPath, settingsPath} {+ done := make(chan *httptest.ResponseRecorder, 1)+ go func() { done <- request("GET", path, "") }()+ select {+ case response := <-done:+ if response.Code != 200 {+ t.Fatalf("%s: %d %s", path, response.Code, response.Body)+ }+ case <-time.After(time.Second):+ t.Fatalf("%s blocked behind package installation", path)+ }+ }+ opened := make(chan error, 1)+ go func() { opened <- manager.Ensure(context.Background(), "alice") }()+ select {+ case err := <-opened:+ if err != nil {+ t.Fatal(err)+ }+ case <-time.After(time.Second):+ t.Fatal("opening the account waited for plugin installation")+ }+ unblock()+ select {+ case response := <-installed:+ if response.Code != 200 {+ t.Fatalf("install: %d %s", response.Code, response.Body)+ }+ case <-time.After(3 * time.Second):+ t.Fatal("install did not finish")+ }+}diff --git a/internal/controller/plugins.go b/internal/controller/plugins.gonew file mode 100644index 0000000..36cd5ee--- /dev/null+++ b/internal/controller/plugins.go@@ -0,0 +1,350 @@+package controller++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/url"+ "sort"+ "strings"+ "time"++ "go-bot/extensions/catalog"++ mcpconfig "go-bot/mcp"++ "go-bot/plugin"+)++func accountPlugins(account Account) plugin.Settings {+ if account.Plugins != nil {+ return account.Plugins.Clone()+ }+ return plugin.Settings{}.Clone()+}++// Package preparation may take minutes. It is synchronous and cancellable,+// independently of the normal ten-second Host control request budget.+func (m *Manager) requestPlugins(ctx context.Context, record Account, method, suffix string, input, output any) error {+ return m.requestExtension(ctx, record, method, plugin.InternalPath+suffix, input, output)+}++type extensionHTTPError struct {+ Status int+ Message string+}++func (e *extensionHTTPError) Error() string { return e.Message }++func (m *Manager) requestExtension(ctx context.Context, record Account, method, path string, input, output any) error {+ target, err := url.Parse(record.HostEndpoint)+ if err != nil || target.Scheme != "http" || target.Host == "" {+ return errHostUnavailable+ }+ var body io.Reader+ if input != nil {+ data, err := json.Marshal(input)+ if err != nil {+ return err+ }+ body = bytes.NewReader(data)+ }+ ctx, cancel := context.WithTimeout(ctx, 15*time.Minute)+ defer cancel()+ req, err := http.NewRequestWithContext(ctx, method, record.HostEndpoint+path, body)+ if err != nil {+ return err+ }+ req.Header.Set("Authorization", "Bearer "+record.HostToken)+ if redirect := oauthCallbackFromContext(ctx); redirect != "" {+ req.Header.Set(mcpconfig.OAuthCallbackHeader, redirect)+ if callback := pluginCallbackBase(redirect); callback != "" {+ req.Header.Set(plugin.AuthorizationCallbackHeader, callback)+ }+ }+ if body != nil {+ req.Header.Set("Content-Type", "application/json")+ }+ client := *m.Client+ client.Timeout = 0+ res, err := client.Do(req)+ if err != nil {+ return errors.New("host_plugins_unavailable")+ }+ defer res.Body.Close()+ if res.StatusCode < 200 || res.StatusCode >= 300 {+ var failure struct{ Error, Message string }+ if decodeJSON(io.LimitReader(res.Body, 8<<10), &failure) == nil {+ if failure.Message != "" {+ return &extensionHTTPError{res.StatusCode, failure.Message}+ }+ if failure.Error != "" {+ return &extensionHTTPError{res.StatusCode, failure.Error}+ }+ }+ return &extensionHTTPError{res.StatusCode, "host_plugin_operation_failed"}+ }+ if output != nil {+ return decodeJSON(io.LimitReader(res.Body, 2<<20), output)+ }+ return nil+}++func (m *Manager) syncPlugins(ctx context.Context, id string, account Account) error {+ lock := m.pluginLock(id)+ // An explicit package operation is already applying the saved selection.+ // Opening the account must not wait for its downloads under accountLock.+ if !lock.TryLock() {+ return nil+ }+ defer lock.Unlock()+ current, err := m.Store.Get(ctx, id)+ if err != nil {+ return err+ }+ account.Plugins = current.Plugins+ if account.Plugins == nil {+ return nil+ }+ resolved, err := m.resolvePlugins(*account.Plugins)+ if err != nil {+ return err+ }+ return m.requestPlugins(ctx, account, http.MethodPut, "/settings", resolved, nil)+}++// Resolve reviewed package sources only while sending private Host commands.+// Redis stores neither installation sources nor Cordis entry/config objects.+func (m *Manager) resolvePlugins(settings plugin.Settings) (plugin.RuntimeSettings, error) {+ resolved := plugin.RuntimeSettings{Packages: map[string]plugin.RuntimePackage{}, Instances: []plugin.InstanceConfig{}}+ for name, selection := range settings.Packages {+ var release *catalog.Entry+ for i := range m.pluginCatalog {+ entry := &m.pluginCatalog[i]+ if entry.ID == selection.CatalogID && entry.Package == name {+ release = entry+ break+ }+ }+ if release == nil {+ return resolved, errors.New("selected_plugin_release_unavailable")+ }+ resolved.Packages[name] = plugin.RuntimePackage{Version: selection.Version, CatalogID: release.ID, Source: release.Source, Builds: release.Builds}+ resolved.Instances = append(resolved.Instances, plugin.InstanceConfig{ID: release.ID, Package: name, Enabled: selection.Enabled})+ }+ sort.Slice(resolved.Instances, func(i, j int) bool { return resolved.Instances[i].ID < resolved.Instances[j].ID })+ return resolved, nil+}++func (m *Manager) pluginView(ctx context.Context, record Account, settings plugin.Settings) plugin.View {+ status := plugin.Status{Runtime: "unavailable", Packages: []plugin.PackageInfo{}, Instances: []plugin.Instance{}}+ if record.DesiredState == running && record.HostEndpoint != "" {+ readCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ if err := m.requestPlugins(readCtx, record, http.MethodGet, "", nil, &status); err != nil {+ status.Runtime = "unavailable"+ status.Error = "host_plugins_unavailable"+ }+ }+ entries := make([]plugin.CatalogEntry, 0, len(m.pluginCatalog))+ for _, entry := range m.pluginCatalog {+ display := entry.CatalogEntry+ display.Icon = pluginIconURL(display.Icon)+ entries = append(entries, display)+ for i := range status.Packages {+ actual := &status.Packages[i]+ if actual.Name == entry.Package && actual.Present {+ actual.AvailableVersion = plugin.NewerVersion(actual.Version, entry.Version)+ }+ }+ }+ return plugin.View{Catalog: entries, Settings: settings.Clone(), Status: status}+}++func (m *Manager) savePlugins(w http.ResponseWriter, r *http.Request, id string, record Account, settings plugin.Settings, operation, name string) {+ if err := settings.Validate(); err != nil {+ httpError(w, http.StatusBadRequest, err.Error())+ return+ }+ if err := m.Store.SavePluginSettings(r.Context(), id, settings); err != nil {+ httpError(w, http.StatusServiceUnavailable, "plugin_settings_save_failed")+ return+ }+ if record.DesiredState == running && record.HostEndpoint != "" {+ resolved, resolveErr := m.resolvePlugins(settings)+ if resolveErr != nil {+ httpError(w, 422, resolveErr.Error())+ return+ }+ var err error+ if operation != "" {+ err = m.requestPlugins(r.Context(), record, http.MethodPost, operation, map[string]any{"name": name, "settings": resolved}, nil)+ } else {+ err = m.requestPlugins(r.Context(), record, http.MethodPut, "/settings", resolved, nil)+ }+ if err != nil {+ writeJSON(w, http.StatusBadGateway, map[string]any{"error": settingsSavedHostApplyFailed, "message": err.Error(), "view": m.pluginView(r.Context(), record, settings)})+ return+ }+ }+ writeJSON(w, http.StatusOK, m.pluginView(r.Context(), record, settings))+}++func (m *Manager) pluginsHTTP(w http.ResponseWriter, r *http.Request, id string) {+ if r.Method != http.MethodGet {+ lock := m.pluginLock(id)+ lock.Lock()+ defer lock.Unlock()+ }+ record, err := m.Store.Get(r.Context(), id)+ if errors.Is(err, ErrAccountNotFound) {+ httpError(w, 404, "account not found")+ return+ }+ if err != nil {+ httpError(w, 503, "plugin_settings_unavailable")+ return+ }+ settings := accountPlugins(record)+ suffix := strings.TrimPrefix(r.URL.EscapedPath(), plugin.SettingsPath)+ if r.Method == http.MethodGet && suffix == "" {+ writeJSON(w, 200, m.pluginView(r.Context(), record, settings))+ return+ }+ decode := func(value any) bool {+ d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))+ d.DisallowUnknownFields()+ if d.Decode(value) != nil || !errors.Is(d.Decode(new(any)), io.EOF) {+ httpError(w, 400, "invalid_plugin_request")+ return false+ }+ return true+ }+ // Clients choose reviewed packages and enabled state only.+ if r.Method == http.MethodPost && (suffix == "/packages" || (strings.HasPrefix(suffix, "/packages/") && strings.HasSuffix(suffix, "/update"))) {+ var input struct {+ PluginID string `json:"pluginId"`+ }+ if !decode(&input) {+ return+ }+ var release *catalog.Entry+ for i := range m.pluginCatalog {+ if m.pluginCatalog[i].ID == input.PluginID {+ release = &m.pluginCatalog[i]+ break+ }+ }+ if release == nil {+ httpError(w, 404, "plugin_not_in_catalog")+ return+ }+ updating := suffix != "/packages"+ installed, exists := settings.Packages[release.Package]+ if updating {+ name, err := url.PathUnescape(strings.TrimSuffix(strings.TrimPrefix(suffix, "/packages/"), "/update"))+ if err != nil || name != release.Package || !exists || installed.CatalogID != release.ID {+ httpError(w, 404, "installed_plugin_not_found")+ return+ }+ } else if exists {+ httpError(w, 409, "plugin_package_already_installed")+ return+ }+ if record.DesiredState != running || record.HostEndpoint == "" {+ httpError(w, 409, "host_not_running")+ return+ }+ var info plugin.PackageInfo+ if err = m.requestPlugins(r.Context(), record, http.MethodPost, "/packages/inspect", map[string]any{"name": release.Package, "source": release.Source}, &info); err != nil {+ httpError(w, 422, err.Error())+ return+ }+ if info.Name != release.Package || info.Version != release.Version || info.API != "1" {+ httpError(w, 422, "incompatible_plugin_package")+ return+ }+ settings.Packages[release.Package] = plugin.PackageSelection{CatalogID: release.ID, Version: release.Version, Enabled: installed.Enabled}+ operation := ""+ if updating {+ operation = "/packages/reinstall"+ }+ m.savePlugins(w, r, id, record, settings, operation, release.Package)+ return+ }+ if r.Method == http.MethodPut && strings.HasPrefix(suffix, "/packages/") {+ name, err := url.PathUnescape(strings.TrimPrefix(suffix, "/packages/"))+ selection, exists := settings.Packages[name]+ if err != nil || !exists {+ http.NotFound(w, r)+ return+ }+ var input struct {+ Enabled *bool `json:"enabled"`+ }+ if !decode(&input) {+ return+ }+ if input.Enabled == nil {+ httpError(w, 400, "enabled_is_required")+ return+ }+ selection.Enabled = *input.Enabled+ settings.Packages[name] = selection+ m.savePlugins(w, r, id, record, settings, "", "")+ return+ }+ if r.Method == http.MethodDelete && strings.HasPrefix(suffix, "/packages/") {+ name, err := url.PathUnescape(strings.TrimPrefix(suffix, "/packages/"))+ if err != nil || !plugin.ValidPackageName(name) {+ httpError(w, 400, "invalid_package_name")+ return+ }+ if _, ok := settings.Packages[name]; !ok {+ http.NotFound(w, r)+ return+ }+ delete(settings.Packages, name)+ m.savePlugins(w, r, id, record, settings, "/packages/remove", name)+ return+ }+ http.NotFound(w, r)+}++func (m *Manager) restartPluginsHTTP(w http.ResponseWriter, r *http.Request, id string) {+ if r.Method != http.MethodPost {+ http.NotFound(w, r)+ return+ }+ lock := m.pluginLock(id)+ lock.Lock()+ defer lock.Unlock()+ record, err := m.Store.Get(r.Context(), id)+ if errors.Is(err, ErrAccountNotFound) {+ http.NotFound(w, r)+ return+ }+ if err != nil || record.DesiredState != running || record.HostEndpoint == "" {+ httpError(w, http.StatusConflict, "host_not_running")+ return+ }+ var status plugin.Status+ // Apply saved settings as part of the restart. Applying them first can+ // repeat a failed Cordis load and prevent the recovery command itself.+ input := struct {+ Settings plugin.RuntimeSettings `json:"settings"`+ }{}+ input.Settings, err = m.resolvePlugins(accountPlugins(record))+ if err != nil {+ httpError(w, 422, err.Error())+ return+ }+ if err = m.requestPlugins(r.Context(), record, http.MethodPost, "/runtime/restart", input, &status); err != nil {+ httpError(w, http.StatusBadGateway, err.Error())+ return+ }+ writeJSON(w, http.StatusOK, m.pluginView(r.Context(), record, accountPlugins(record)))+}diff --git a/internal/controller/plugins_test.go b/internal/controller/plugins_test.gonew file mode 100644index 0000000..2a8c39a--- /dev/null+++ b/internal/controller/plugins_test.go@@ -0,0 +1,233 @@+package controller++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"++ "go-bot/extensions/catalog"++ "go-bot/harness/agent"+ "go-bot/internal/config"+ "go-bot/internal/httpapi"+ "go-bot/internal/modeldata"+ "go-bot/internal/plugins"+ "go-bot/plugin"+)++type pluginFailureStore struct {+ *memoryStore+ fail bool+}++func TestPluginRestartDoesNotRequireFailedApplyToSucceed(t *testing.T) {+ settings := plugin.Settings{Packages: map[string]plugin.PackageSelection{"fixture": {CatalogID: "fixture", Version: "1.0.0", Enabled: true}}}++ restarts := 0+ host := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPut:+ t.Error("recovery tried to apply failed instances before restarting")+ http.Error(w, "previous load failed", http.StatusUnprocessableEntity)+ case r.Method == http.MethodPost && r.URL.Path == plugin.InternalPath+"/runtime/restart":+ var input struct{ Settings *plugin.RuntimeSettings }+ if err := json.NewDecoder(r.Body).Decode(&input); err != nil || input.Settings == nil ||+ len(input.Settings.Instances) != 1 || input.Settings.Instances[0].ID != "fixture" || !input.Settings.Instances[0].Enabled {+ t.Errorf("restart did not carry saved settings: %v", err)+ http.Error(w, "missing settings", http.StatusBadRequest)+ return+ }+ restarts+++ writeJSON(w, 200, plugin.Status{Runtime: "running"})+ case r.Method == http.MethodGet:+ writeJSON(w, 200, plugin.Status{Runtime: "running"})+ default:+ http.NotFound(w, r)+ }+ }))+ defer host.Close()+ store := &memoryStore{records: map[string]Account{"alice": {+ DesiredState: running, HostEndpoint: host.URL, HostToken: "fixture", Plugins: &settings,+ }}}+ manager := New(config.Default(), nil, store)+ manager.pluginCatalog = []catalog.Entry{{CatalogEntry: plugin.CatalogEntry{ID: "fixture", Package: "fixture", Version: "1.0.0"}, Source: plugin.Source{Type: "registry", Spec: "[email protected]"}}}++ req := httptest.NewRequest(http.MethodPost, "/v1/host/plugins/runtime/restart", nil)+ req.Header.Set(UserHeader, "alice")+ out := httptest.NewRecorder()+ manager.Handler().ServeHTTP(out, req)+ if out.Code != http.StatusOK || restarts != 1 {+ t.Fatalf("restart failed: %d %s, calls=%d", out.Code, out.Body, restarts)+ }+}++func (s *pluginFailureStore) SavePluginSettings(ctx context.Context, id string, value plugin.Settings) error {+ if s.fail {+ return errors.New("Redis write failed")+ }+ return s.memoryStore.SavePluginSettings(ctx, id, value)+}+func TestPluginHTTPPersistsPackageSelectionBeforeNativeCordisApply(t *testing.T) {+ node, err := exec.LookPath("node")+ if err != nil {+ t.Skip("Node is required")+ }+ main, _ := filepath.Abs("../../extensions/cordis/src/main.mjs")+ if _, err = os.Stat(filepath.Join(filepath.Dir(main), "../node_modules/@deepseek-ai/cordis/package.json")); err != nil {+ t.Skip("Install Cordis dependencies")+ }+ pluginDirectory := t.TempDir()+ extensions, err := plugins.NewManager(t.Context(), plugins.ManagerConfig{Directory: pluginDirectory, Runtime: plugins.RuntimeConfig{Node: node, Main: main, Workspace: t.TempDir()}, PackageMain: filepath.Join(filepath.Dir(main), "package-main.mjs")})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = extensions.Close() })+ memory := &memoryStore{records: map[string]Account{"alice": {DesiredState: running, HostToken: "private-host-token"}}}+ store := &pluginFailureStore{memoryStore: memory}+ applied := 0+ private := extensions.Handler()+ host := httptest.NewServer(httpapi.Authenticate("private-host-token", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == http.MethodPut && r.URL.Path == plugin.InternalPath+"/settings" {+ record, _ := store.Get(r.Context(), "alice")+ if record.Plugins == nil {+ t.Error("Host apply preceded Redis save")+ }+ applied+++ }+ private.ServeHTTP(w, r)+ })))+ defer host.Close()+ memory.records["alice"] = Account{DesiredState: running, HostToken: "private-host-token", HostEndpoint: host.URL}+ manager := New(config.Default(), nil, store)+ request := func(method, path string, input any, want int) []byte {+ t.Helper()+ data, _ := json.Marshal(input)+ r := httptest.NewRequest(method, path, strings.NewReader(string(data)))+ r.Header.Set(UserHeader, "alice")+ out := httptest.NewRecorder()+ manager.Handler().ServeHTTP(out, r)+ if out.Code != want {+ t.Fatalf("%s %s: %d %s", method, path, out.Code, out.Body.String())+ }+ return out.Body.Bytes()+ }+ directory := t.TempDir()+ for name, body := range map[string]string{+ "package.json": `{"name":"@fixture/mail","version":"1.0.0","type":"module","exports":"./index.mjs","goBot":{"api":"1"}}`,+ "index.mjs": `export const inject=['host'];export async function apply(ctx,config){await ctx.host.tools.register({name:'echo',description:'Echo',inputSchema:{type:'object'},async execute(){return{content:[{type:'text',text:'Hello'}]}}})}`,+ } {+ if err = os.WriteFile(filepath.Join(directory, name), []byte(body), 0600); err != nil {+ t.Fatal(err)+ }+ }+ // Only trusted test setup can inject a directory release. The public API+ // cannot accept this source, even when it points to a valid package.+ manager.pluginCatalog = []catalog.Entry{{CatalogEntry: plugin.CatalogEntry{ID: "mail", Package: "@fixture/mail", Version: "1.0.0"}, Source: plugin.Source{Type: "directory", Spec: directory}}}+ request("POST", plugin.SettingsPath+"/packages", map[string]any{"name": "@fixture/mail", "source": plugin.Source{Type: "directory", Spec: directory}}, 400)+ request("PUT", plugin.SettingsPath, plugin.Settings{}, 404)+ request("POST", plugin.SettingsPath+"/packages", map[string]string{"pluginId": "unknown"}, 404)+ installed := request("POST", plugin.SettingsPath+"/packages", map[string]string{"pluginId": "mail"}, 200)+ var view plugin.View+ if err := json.Unmarshal(installed, &view); err != nil || len(view.Settings.Packages) != 1 || view.Settings.Packages["@fixture/mail"].Enabled {+ t.Fatalf("install must save one disabled package selection: %s", installed)+ }+ if len(view.Catalog) != 1 || view.Settings.Packages["@fixture/mail"].CatalogID != "mail" {+ t.Fatal("missing catalog association", string(installed))+ }+ packagePath := plugin.SettingsPath + "/packages/%40fixture%2Fmail"+ request("PUT", packagePath, map[string]any{"source": plugin.Source{Type: "directory", Spec: directory}}, 400)+ request("POST", plugin.SettingsPath+"/instances", map[string]string{"package": "@fixture/mail"}, 404)+ request("PUT", packagePath, map[string]any{"enabled": true, "config": map[string]string{"label": "initial"}}, 400)+ request("PUT", packagePath, map[string]bool{"enabled": true}, 200)+ tools, err := extensions.Tools(t.Context(), "session")+ if err != nil || len(tools) != 1 {+ t.Fatal(tools, err)+ }+ if text, err := tools[0].Execute(t.Context(), json.RawMessage(`{}`)); err != nil || text != "Hello" {+ t.Fatal(text, err)+ }++ // A real package version update must preserve enablement and replace the+ // old Cordis callback, rather than merely saving a newer Redis selection.+ prior := tools[0]+ nextDirectory := t.TempDir()+ if err = os.WriteFile(filepath.Join(nextDirectory, "package.json"), []byte(`{"name":"@fixture/mail","version":"2.0.0","type":"module","exports":"./index.mjs","goBot":{"api":"1"}}`), 0600); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(nextDirectory, "index.mjs"), []byte(`export const inject=['host'];export async function apply(ctx){await ctx.host.tools.register({name:'echo',description:'Echo',inputSchema:{type:'object'},async execute(){return{content:[{type:'text',text:'Updated'}]}}})}`), 0600); err != nil {+ t.Fatal(err)+ }+ manager.pluginCatalog[0].Version = "2.0.0"+ manager.pluginCatalog[0].Source.Spec = nextDirectory+ // A market refresh does not force an upgrade when the user only toggles+ // the installed release. This also exercises restore against a newer catalog.+ request("PUT", packagePath, map[string]bool{"enabled": false}, 200)+ request("PUT", packagePath, map[string]bool{"enabled": true}, 200)+ body := request("GET", plugin.SettingsPath, nil, 200)+ var beforeUpdate plugin.View+ if err = json.Unmarshal(body, &beforeUpdate); err != nil || beforeUpdate.Status.Packages[0].AvailableVersion != "2.0.0" {+ t.Fatalf("missing actual update status: %s", body)+ }+ body = request("POST", packagePath+"/update", map[string]string{"pluginId": "mail"}, 200)+ var updated plugin.View+ if err = json.Unmarshal(body, &updated); err != nil || updated.Settings.Packages["@fixture/mail"].Version != "2.0.0" || !updated.Settings.Packages["@fixture/mail"].Enabled || updated.Status.Packages[0].AvailableVersion != "" {+ t.Fatalf("update state: %s", body)+ }+ tools, err = extensions.Tools(t.Context(), "session")+ if err != nil || len(tools) != 1 {+ t.Fatal(tools, err)+ }+ if text, err := tools[0].Execute(t.Context(), json.RawMessage(`{}`)); err != nil || text != "Updated" {+ t.Fatal(text, err)+ }+ if _, err = prior.Execute(t.Context(), json.RawMessage(`{}`)); err == nil {+ t.Error("update retained the old callback")+ }+ store.fail = true+ before := applied+ request("PUT", packagePath, map[string]bool{"enabled": false}, 503)+ if applied != before {+ t.Fatal("failed Redis save still applied to Host")+ }+ store.fail = false+ saved, _ := store.Get(t.Context(), "alice")+ data, _ := json.Marshal(saved.Plugins)+ if strings.Contains(string(data), "source") || strings.Contains(string(data), "instances") || strings.Contains(string(data), "config") {+ t.Fatal("Redis selection contains runtime configuration", string(data))+ }+ if _, err := os.Stat(filepath.Join(pluginDirectory, "profile", "plugins.json")); err == nil {+ t.Fatal("unexpected plugin state file")+ }+ request("PUT", packagePath, map[string]bool{"enabled": false}, 200)+ request("DELETE", packagePath, nil, 200)+ if tools, err := extensions.Tools(t.Context(), "session"); err != nil || len(tools) != 0 {+ t.Fatal(tools, err)+ }+ // Ordinary core preparation is Go-only, even with no Node runtime.+ factory, err := extensions.ToolInvocations(t.Context(), "session")+ if err != nil {+ t.Fatal(err)+ }+ bodyCalls := 0+ invocation, err := factory(t.Context(), agent.ToolExecution{SessionID: "session", Name: "core_probe"}, func(context.Context) modeldata.ToolResult {+ bodyCalls+++ return modeldata.ToolResult{Content: "Go core remains available"}+ }, nil)+ if err != nil {+ t.Fatal(err)+ }+ if !invocation.Prepare().Dispatch {+ t.Fatal("core preparation required Node")+ }+ outcome := invocation.Complete(invocation.Dispatch())+ if outcome.IsError || bodyCalls != 1 {+ t.Fatalf("core outcome=%+v calls=%d", outcome, bodyCalls)+ }+}diff --git a/internal/controller/provider_settings_test.go b/internal/controller/provider_settings_test.goindex 4936151..c23ece6 100644--- a/internal/controller/provider_settings_test.go+++ b/internal/controller/provider_settings_test.go@@ -136,6 +136,46 @@ func TestAdditionalProviderUsesTheSameSettingsContract(t *testing.T) {}}+func TestInternationalSearchSettingsSaveSelectAndRestore(t *testing.T) {+ store := &memoryStore{records: map[string]Account{"alice": {}, "bob": {}}}+ m := New(config.Default(), nil, store)+ call := func(user, method, body string) string {+ t.Helper()+ r := httptest.NewRequest(method, webSearchSettingsPath, strings.NewReader(body))+ w := httptest.NewRecorder()+ m.providerSettingsHTTP(w, r, user, searchSettings)+ if w.Code != 200 || strings.Contains(w.Body.String(), "fixture-secret") {+ t.Fatalf("provider settings status=%d body=%s", w.Code, w.Body)+ }+ return w.Body.String()+ }+ catalog := call("alice", "GET", "")+ if !strings.Contains(catalog, `"id":"brave"`) || !strings.Contains(catalog, `"id":"tavily"`) {+ t.Fatal("new providers missing from client catalog")+ }+ for _, id := range []string{"tavily", "brave"} {+ got := call("alice", "PUT", `{"provider":"`+id+`","apiKey":"`+id+`-fixture-secret","activate":false}`)+ if !strings.Contains(got, `"provider":"deepseek"`) {+ t.Fatal("saving an inactive key changed the chosen provider")+ }+ }+ for _, id := range []string{"brave", "tavily"} {+ call("alice", "PUT", `{"provider":"`+id+`","activate":true}`)+ saved, err := store.Get(t.Context(), "alice")+ if err != nil || saved.WebSearch.Provider != id || len(saved.WebSearch.Entries) != 2 || saved.WebSearch.Entries[id].APIKey != id+"-fixture-secret" {+ t.Fatalf("selection/credentials not persisted: %v", err)+ }+ // Reopening a Controller reads the same selected provider and only key presence.+ m = New(config.Default(), nil, store)+ if got := call("alice", "GET", ""); !strings.Contains(got, `"provider":"`+id+`"`) || !strings.Contains(got, `"hasApiKey":true`) {+ t.Fatal("saved settings were not restored")+ }+ }+ if got := call("bob", "GET", ""); strings.Contains(got, `"hasApiKey":true`) {+ t.Fatal("credentials crossed accounts")+ }+}+func TestSearchProviderSaveAndSelectAreSeparate(t *testing.T) {var applied []providersettings.Selectionhost := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/internal/controller/store.go b/internal/controller/store.goindex 0698f61..dbbc1d1 100644--- a/internal/controller/store.go+++ b/internal/controller/store.go@@ -9,6 +9,7 @@ import ("github.com/redis/go-redis/v9""go-bot/internal/modelsettings""go-bot/internal/providersettings"+ "go-bot/plugin")var ErrAccountNotFound = errors.New("account not found")@@ -21,6 +22,7 @@ type Account struct {HostEndpoint string `json:"hostEndpoint,omitempty"`WebSearch *providersettings.Settings `json:"webSearch,omitempty"`ImageGeneration *providersettings.Settings `json:"imageGeneration,omitempty"`+ Plugins *plugin.Settings `json:"plugins,omitempty"`}type AccountStore interface {@@ -28,6 +30,7 @@ type AccountStore interface {Get(context.Context, string) (Account, error)Save(context.Context, string, Account) error // Save only Host lifecycle fields.SaveProviderSettings(context.Context, string, string, providersettings.Settings) error+ SavePluginSettings(context.Context, string, plugin.Settings) errorLoadModels(context.Context, string) (modelsettings.Snapshot, error)SaveModelCatalog(context.Context, string, modelsettings.Catalog) (int64, error)SaveSessionModel(context.Context, string, string, modelsettings.Selection) (int64, error)@@ -37,6 +40,7 @@ const (accountPrefix = "user:"webSearchField = "webSearch"imageGenerationField = "imageGeneration"+ pluginsField = "plugins")type RedisStore struct{ client *redis.Client }@@ -70,6 +74,13 @@ func (a Account) fields() ([]any, error) {fields = append(fields, item.name, data)}}+ if a.Plugins != nil {+ data, err := json.Marshal(a.Plugins)+ if err != nil {+ return nil, err+ }+ fields = append(fields, pluginsField, data)+ }return fields, nil}@@ -96,7 +107,7 @@ func (s *RedisStore) Create(ctx context.Context, id string, record Account) erro}func (s *RedisStore) Get(ctx context.Context, id string) (Account, error) {- fields, err := s.client.HMGet(ctx, accountPrefix+id, "desiredState", "hostId", "hostToken", "hostEndpoint", webSearchField, imageGenerationField).Result()+ fields, err := s.client.HMGet(ctx, accountPrefix+id, "desiredState", "hostId", "hostToken", "hostEndpoint", webSearchField, imageGenerationField, pluginsField).Result()if err != nil {return Account{}, err}@@ -110,9 +121,38 @@ func (s *RedisStore) Get(ctx context.Context, id string) (Account, error) {if !decodeField(fields[4], &record.WebSearch) || !decodeField(fields[5], &record.ImageGeneration) {return Account{}, errors.New("invalid Redis provider settings")}+ if !decodeField(fields[6], &record.Plugins) {+ return Account{}, errors.New("invalid Redis plugin settings")+ }return record, nil}+func (s *RedisStore) SavePluginSettings(ctx context.Context, id string, settings plugin.Settings) error {+ if err := settings.Validate(); err != nil {+ return err+ }+ return s.saveExtensionSettings(ctx, id, pluginsField, settings)+}++func (s *RedisStore) saveExtensionSettings(ctx context.Context, id, field string, settings any) error {+ data, err := json.Marshal(settings)+ if err != nil {+ return err+ }+ key := accountPrefix + id+ return s.watch(ctx, []string{key}, func(tx *redis.Tx) error {+ exists, err := tx.HExists(ctx, key, "desiredState").Result()+ if err != nil {+ return err+ }+ if !exists {+ return ErrAccountNotFound+ }+ _, err = tx.TxPipelined(ctx, func(pipe redis.Pipeliner) error { pipe.HSet(ctx, key, field, data); return nil })+ return err+ })+}+func (s *RedisStore) Save(ctx context.Context, id string, record Account) error {return s.client.HSet(ctx, accountPrefix+id, record.hostFields()...).Err()}diff --git a/internal/controller/web.go b/internal/controller/web.goindex 4e02a53..5369599 100644--- a/internal/controller/web.go+++ b/internal/controller/web.go@@ -12,6 +12,7 @@ import ("github.com/google/uuid""go-bot/internal/config"+ mcpconfig "go-bot/mcp")type WebOptions struct {@@ -50,7 +51,7 @@ func controllerBrowserOrigin(w http.ResponseWriter, r *http.Request, devOrigin s}if devOrigin != "" && origin == devOrigin && config.IsLoopbackHost((&url.URL{Host: r.Host}).Hostname()) {w.Header().Set("Access-Control-Allow-Origin", origin)- w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Last-Event-ID, X-Client-Time-Zone, X-User-ID")+ w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Last-Event-ID, X-Client-Time-Zone, X-User-ID, "+mcpconfig.ControllerOriginHeader)w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")if r.URL.Path == hostFilesPath {w.Header().Set("Access-Control-Expose-Headers", hostStorageHeader+", "+hostStorageSourceHeader)@@ -80,7 +81,7 @@ func serveWeb(w http.ResponseWriter, r *http.Request, files fs.FS) bool {http.FileServerFS(files).ServeHTTP(w, r)return true}- if r.URL.Path != "/" && r.URL.Path != "/settings/models" && r.URL.Path != "/settings/web-search" && r.URL.Path != "/settings/image-generation" {+ if r.URL.Path != "/" && r.URL.Path != "/settings/models" && r.URL.Path != "/settings/web-search" && r.URL.Path != "/settings/image-generation" && r.URL.Path != "/plugins" {id, chat := strings.CutPrefix(r.URL.Path, "/chat/")if !chat || len(id) != 36 || uuid.Validate(id) != nil {return falsediff --git a/internal/controller/web_test.go b/internal/controller/web_test.goindex 2a64655..b4d437a 100644--- a/internal/controller/web_test.go+++ b/internal/controller/web_test.go@@ -21,6 +21,9 @@ func TestControllerServesWebRoutesAndLeavesAPIRoutesDistinct(t *testing.T) {status int}{{"/", "GET", "text/html", "no-cache", 200},+ {"/plugins", "GET", "text/html", "no-cache", 200},+ {"/plugins/not-a-page", "GET", "text/plain", "", 404},+ {"/settings/plugins", "GET", "text/plain", "", 404},{"/chat/6c265cac-35e2-471a-80e1-45e066a909be", "GET", "text/html", "no-cache", 200},{"/", "HEAD", "text/html", "no-cache", 200},{"/assets/main.js", "GET", "javascript", "immutable", 200},diff --git a/internal/credentials/store.go b/internal/credentials/store.gonew file mode 100644index 0000000..9356225--- /dev/null+++ b/internal/credentials/store.go@@ -0,0 +1,792 @@+// Package credentials implements the Host's built-in credential provider.+// Plugins use this service through an adapter; neither Cordis nor the MCP+// client owns a second credential database.+package credentials++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "reflect"+ "regexp"+ "sort"+ "strings"+ "sync"+ "time"++ "go-bot/internal/durablefs"+ "gopkg.in/yaml.v3"+)++const Filename = ".credentials.yaml"+const documentLimit = 4 << 20+const recordLimit = 512 << 10++var refPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)+var keyPattern = regexp.MustCompile(`^[a-z][a-z0-9-]*/[a-z][a-z0-9-]*$`)++func ValidRef(ref string) bool { return refPattern.MatchString(ref) }+func ValidKey(key string) bool { return keyPattern.MatchString(key) }++type Record struct {+ Kind string `json:"kind" yaml:"kind"`+ Key *string `json:"key,omitempty" yaml:"key,omitempty"`+ Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"`+ Payload json.RawMessage `json:"payload,omitempty" yaml:"-"`+}++// Reject unknown fields at every JSON ingress, including Node callback results,+// rather than silently dropping part of a purportedly lossless record.+func (r *Record) UnmarshalJSON(data []byte) error {+ type wire Record+ var value wire+ decoder := json.NewDecoder(bytes.NewReader(data))+ decoder.DisallowUnknownFields()+ if err := decoder.Decode(&value); err != nil {+ return errors.New("invalid credential record")+ }+ if !errors.Is(decoder.Decode(new(any)), io.EOF) {+ return errors.New("invalid credential record")+ }+ next := Record(value)+ if err := next.Validate(); err != nil {+ return err+ }+ *r = next+ return nil+}++func (r Record) Validate() error {+ switch r.Kind {+ case "api-key":+ if r.Payload != nil || (r.Key != nil && *r.Key == "") {+ return errors.New("invalid api-key credential record")+ }+ for name := range r.Env {+ if !ValidRef(name) {+ return errors.New("invalid credential environment name")+ }+ }+ case "grant":+ if r.Key != nil || r.Env != nil || !json.Valid(r.Payload) {+ return errors.New("invalid grant credential record")+ }+ default:+ return errors.New("unknown credential record kind")+ }+ data, err := json.Marshal(r)+ if err != nil || len(data) > recordLimit {+ return errors.New("credential record exceeds supported limits")+ }+ return nil+}++type Resolved struct {+ Value string `json:"value"`+ Source string `json:"source"`+}+type Info struct {+ Configured bool `json:"configured"`+ Source string `json:"source,omitempty"`+ Writable bool `json:"writable"`+ Masked string `json:"masked,omitempty"`+}+type RecordInfo struct {+ Configured bool `json:"configured"`+ Kind string `json:"kind,omitempty"`+ Writable bool `json:"writable"`+}+type RecordEntry struct {+ Key string `json:"key"`+ Kind string `json:"kind"`+}+type Update struct {+ References []string `json:"references"`+ Records []string `json:"records"`+}+type document struct {+ refs map[string]string+ records map[string]Record+ node *yaml.Node+}+type Options struct {+ Watch bool+ Warn func(error)+}++// Store serializes all writes and read-modify-write callbacks in the one Go+// Host. Reads expose committed snapshots, so a mutation callback can inspect+// other committed records without re-entering its own mutation queue.+type Store struct {+ path string+ gate chan struct{}+ mu sync.RWMutex+ doc document+ provided map[string]string+ observers map[uint64]func(Update)+ secrets map[string]bool+ next uint64+ closed bool+ stop chan struct{}+ watchDone chan struct{}+ closeOnce sync.Once+ warn func(error)+}++func Open(path string, options Options) (*Store, error) {+ if !filepath.IsAbs(path) {+ return nil, errors.New("credential path must be absolute")+ }+ s := &Store{path: filepath.Clean(path), gate: make(chan struct{}, 1), provided: map[string]string{}, observers: map[uint64]func(Update){}, stop: make(chan struct{}), watchDone: make(chan struct{}), warn: options.Warn}+ doc, err := readDocument(s.path)+ if err != nil {+ return nil, err+ }+ s.doc = doc+ s.rememberLocked(doc)+ if options.Watch {+ go s.watch()+ } else {+ close(s.watchDone)+ }+ return s, nil+}++func emptyDocument() document {+ return document{refs: map[string]string{}, records: map[string]Record{}, node: &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{{Kind: yaml.MappingNode, Tag: "!!map"}}}}+}++func readDocument(path string) (document, error) {+ file, err := os.Open(path)+ if errors.Is(err, os.ErrNotExist) {+ return emptyDocument(), nil+ }+ if err != nil {+ return document{}, errors.New("cannot read Host credential document")+ }+ defer file.Close()+ info, err := file.Stat()+ if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() > documentLimit {+ return document{}, errors.New("Host credential document must be a private regular file up to 4 MiB")+ }+ data, err := io.ReadAll(io.LimitReader(file, documentLimit+1))+ if err != nil || len(data) > documentLimit {+ return document{}, errors.New("cannot read Host credential document")+ }+ if len(bytes.TrimSpace(data)) == 0 {+ return emptyDocument(), nil+ }+ doc := emptyDocument()+ decoder := yaml.NewDecoder(bytes.NewReader(data))+ if decoder.Decode(doc.node) != nil || len(doc.node.Content) != 1 || doc.node.Content[0].Kind != yaml.MappingNode || !errors.Is(decoder.Decode(new(any)), io.EOF) {+ return document{}, errors.New("invalid Host credential document")+ }+ var raw struct {+ Refs map[string]string `yaml:"refs"`+ Records map[string]any `yaml:"records"`+ }+ // Node.Decode also rejects duplicate mapping keys. Inspect node tags below+ // so a number/bool is never silently coerced into a secret string.+ if doc.node.Decode(&raw) != nil {+ return document{}, errors.New("invalid Host credential document")+ }+ root := doc.node.Content[0]+ for i := 0; i < len(root.Content); i += 2 {+ name, value := root.Content[i].Value, root.Content[i+1]+ if name != "refs" && name != "records" {+ return document{}, errors.New("unknown Host credential document field")+ }+ if value.Kind != yaml.MappingNode {+ return document{}, errors.New("credential sections must be mappings")+ }+ if name == "refs" {+ for j := 0; j < len(value.Content); j += 2 {+ if !ValidRef(value.Content[j].Value) || value.Content[j+1].Kind != yaml.ScalarNode || value.Content[j+1].Tag != "!!str" {+ return document{}, errors.New("invalid stored credential reference")+ }+ }+ }+ }+ for ref, value := range raw.Refs {+ if value != "" {+ doc.refs[ref] = value+ }+ }+ for key, value := range raw.Records {+ if !ValidKey(key) {+ return document{}, errors.New("invalid stored credential key")+ }+ data, err := json.Marshal(value)+ if err != nil {+ return document{}, errors.New("credential record must be JSON")+ }+ var record Record+ dec := json.NewDecoder(bytes.NewReader(data))+ dec.DisallowUnknownFields()+ if dec.Decode(&record) != nil || record.Validate() != nil {+ return document{}, errors.New("invalid stored credential record")+ }+ doc.records[key] = cloneRecord(record)+ }+ return doc, nil+}++func cloneRecord(record Record) Record {+ data, _ := json.Marshal(record)+ var copy Record+ _ = json.Unmarshal(data, ©)+ if copy.Kind == "grant" {+ decoder := json.NewDecoder(bytes.NewReader(copy.Payload))+ decoder.UseNumber()+ var payload any+ if decoder.Decode(&payload) == nil {+ copy.Payload, _ = json.Marshal(payload)+ }+ }+ return copy+}+func cloneRecords(records map[string]Record) map[string]Record {+ out := make(map[string]Record, len(records))+ for k, v := range records {+ out[k] = cloneRecord(v)+ }+ return out+}+func cloneStrings(values map[string]string) map[string]string {+ out := make(map[string]string, len(values))+ for k, v := range values {+ out[k] = v+ }+ return out+}++// SetProvided installs the Controller-supplied fallback layer in Go memory.+// It is not written into the managed document. SDK set/unset owns that file,+// which, as upstream, outranks supplied fallback values.+func (s *Store) SetProvided(values map[string]string) {+ s.mu.Lock()+ if s.closed {+ s.mu.Unlock()+ return+ }+ before := s.provided+ s.provided = cloneStrings(values)+ for _, value := range values {+ if value != "" {+ s.secrets[value] = true+ }+ }+ update := Update{}+ for key, value := range before {+ if values[key] != value {+ update.References = append(update.References, key)+ }+ }+ for key, value := range values {+ if before[key] != value {+ update.References = append(update.References, key)+ }+ }+ s.mu.Unlock()+ s.publish(update)+}++// Lookup also supports existing Go Bot credential-reference aliases. Standard+// resolve/describe validates the upstream POSIX reference grammar at the RPC+// adapter; aliases never become entries in the upstream-format document.+func (s *Store) Lookup(ref string) (*Resolved, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()+ if s.closed {+ return nil, errors.New("credential service is closed")+ }+ if value := s.doc.refs[ref]; value != "" {+ return &Resolved{value, "file"}, nil+ }+ if value := s.provided[ref]; value != "" {+ return &Resolved{value, "controller"}, nil+ }+ return nil, nil+}+func (s *Store) Resolve(ref string) (*Resolved, error) {+ if !ValidRef(ref) {+ return nil, errors.New("invalid credential reference")+ }+ return s.Lookup(ref)+}+func (s *Store) Describe(ref string) (Info, error) {+ value, err := s.Resolve(ref)+ if err != nil {+ return Info{}, err+ }+ info := Info{Writable: true}+ if value != nil {+ info.Configured = true+ info.Source = value.Source+ if value.Source == "file" {+ info.Masked = "********"+ }+ }+ return info, nil+}+func (s *Store) Set(ctx context.Context, ref, value string) error {+ if !ValidRef(ref) || value == "" || len(value) > 16384 || strings.ContainsRune(value, 0) {+ return errors.New("invalid nonempty credential value; use unset to remove it")+ }+ return s.mutate(ctx, func(doc *document) error { doc.refs[ref] = value; return nil })+}+func (s *Store) Unset(ctx context.Context, ref string) error {+ if !ValidRef(ref) {+ return errors.New("invalid credential reference")+ }+ return s.mutate(ctx, func(doc *document) error { delete(doc.refs, ref); return nil })+}+func (s *Store) ReadRecord(key string) (*Record, error) {+ if !ValidKey(key) {+ return nil, errors.New("invalid credential key")+ }+ s.mu.RLock()+ defer s.mu.RUnlock()+ if s.closed {+ return nil, errors.New("credential service is closed")+ }+ value, ok := s.doc.records[key]+ if !ok {+ return nil, nil+ }+ copy := cloneRecord(value)+ return ©, nil+}+func (s *Store) DescribeRecord(key string) (RecordInfo, error) {+ value, err := s.ReadRecord(key)+ info := RecordInfo{Writable: true}+ if value != nil {+ info.Configured = true+ info.Kind = value.Kind+ }+ return info, err+}+func (s *Store) ListRecords() ([]RecordEntry, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()+ if s.closed {+ return nil, errors.New("credential service is closed")+ }+ rows := make([]RecordEntry, 0, len(s.doc.records))+ for key, value := range s.doc.records {+ rows = append(rows, RecordEntry{key, value.Kind})+ }+ sort.Slice(rows, func(i, j int) bool { return rows[i].Key < rows[j].Key })+ return rows, nil+}+func (s *Store) ModifyRecord(ctx context.Context, key string, mutate func(*Record) (*Record, error)) (*Record, error) {+ if !ValidKey(key) || mutate == nil {+ return nil, errors.New("invalid credential mutation")+ }+ var result *Record+ update := Update{}+ err := s.mutateWithUpdates(ctx, func(doc *document) error {+ var current *Record+ if value, ok := doc.records[key]; ok {+ copy := cloneRecord(value)+ current = ©+ }+ next, err := mutate(current)+ if err != nil {+ return err+ }+ if next == nil {+ result = current+ return nil+ }+ if err := next.Validate(); err != nil {+ return err+ }+ copy := cloneRecord(*next)+ doc.records[key] = copy+ update.Records = []string{key}+ detached := cloneRecord(copy)+ result = &detached+ return nil+ }, &update)+ return result, err+}+func (s *Store) DeleteRecord(ctx context.Context, key string) error {+ if !ValidKey(key) {+ return errors.New("invalid credential key")+ }+ return s.mutate(ctx, func(doc *document) error { delete(doc.records, key); return nil })+}++// UpdateRecords is the internal Go counterpart of the serialized callback.+// Returning an error aborts every change; unrelated refs/records are retained.+func (s *Store) UpdateRecords(ctx context.Context, fn func(map[string]Record) error) error {+ return s.mutate(ctx, func(doc *document) error {+ if err := fn(doc.records); err != nil {+ return err+ }+ for key, record := range doc.records {+ if !ValidKey(key) {+ return errors.New("invalid credential key")+ }+ if err := record.Validate(); err != nil {+ return err+ }+ }+ return nil+ })+}++func changes(before, after document) Update {+ u := Update{}+ for key, value := range before.refs {+ if after.refs[key] != value {+ u.References = append(u.References, key)+ }+ }+ for key, value := range after.refs {+ if before.refs[key] != value {+ u.References = append(u.References, key)+ }+ }+ for key, value := range before.records {+ if !reflect.DeepEqual(after.records[key], value) {+ u.Records = append(u.Records, key)+ }+ }+ for key, value := range after.records {+ if !reflect.DeepEqual(before.records[key], value) {+ u.Records = append(u.Records, key)+ }+ }+ return u+}+func (s *Store) mutate(ctx context.Context, fn func(*document) error) error {+ return s.mutateWithUpdates(ctx, fn, nil)+}++// Explicit record writes notify after commit even when the value is unchanged,+// matching the upstream provider's authorization commit-observation contract.+func (s *Store) mutateWithUpdates(ctx context.Context, fn func(*document) error, forced *Update) error {+ select {+ case s.gate <- struct{}{}:+ case <-ctx.Done():+ return ctx.Err()+ case <-s.stop:+ return errors.New("credential service is closed")+ }+ locked := true+ defer func() {+ if locked {+ <-s.gate+ }+ }()+ s.mu.RLock()+ closed := s.closed+ s.mu.RUnlock()+ if closed {+ return errors.New("credential service is closed")+ }+ if err := ctx.Err(); err != nil {+ return err+ }+ doc, err := readDocument(s.path)+ if err != nil {+ return err+ }+ before := document{refs: cloneStrings(doc.refs), records: cloneRecords(doc.records)}+ if err = fn(&doc); err != nil {+ return err+ }+ if err = ctx.Err(); err != nil {+ return err+ }+ u := changes(before, doc)+ if forced != nil {+ u.References = append(u.References, forced.References...)+ u.Records = append(u.Records, forced.Records...)+ }+ if len(u.References)+len(u.Records) > 0 {+ if err = s.write(ctx, &doc); err != nil {+ return err+ }+ }+ s.mu.Lock()+ prior := s.doc+ s.doc = doc+ s.rememberLocked(doc)+ s.mu.Unlock()+ u = changes(prior, doc)+ if forced != nil {+ u.References = append(u.References, forced.References...)+ u.Records = append(u.Records, forced.Records...)+ }+ <-s.gate+ locked = false+ s.publish(u)+ return nil+}++// Update the YAML nodes for changed values rather than re-serializing the whole+// document; unrelated comments, entry order and opaque grant fields survive.+func section(root *yaml.Node, name string) *yaml.Node {+ for i := 0; i < len(root.Content); i += 2 {+ if root.Content[i].Value == name {+ return root.Content[i+1]+ }+ }+ node := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}+ root.Content = append(root.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: name}, node)+ return node+}+func syncMapping(node *yaml.Node, values map[string]any) error {+ seen := map[string]bool{}+ for i := 0; i < len(node.Content); {+ key := node.Content[i].Value+ value, ok := values[key]+ if !ok {+ node.Content = append(node.Content[:i], node.Content[i+2:]...)+ continue+ }+ seen[key] = true+ var next yaml.Node+ if err := next.Encode(value); err != nil {+ return err+ }+ var old any+ if err := node.Content[i+1].Decode(&old); err != nil {+ return err+ }+ oldJSON, oldErr := json.Marshal(old)+ nextJSON, nextErr := json.Marshal(value)+ if oldErr != nil || nextErr != nil || !bytes.Equal(oldJSON, nextJSON) {+ next.HeadComment = node.Content[i+1].HeadComment+ next.LineComment = node.Content[i+1].LineComment+ next.FootComment = node.Content[i+1].FootComment+ node.Content[i+1] = &next+ }+ i += 2+ }+ keys := make([]string, 0)+ for key := range values {+ if !seen[key] {+ keys = append(keys, key)+ }+ }+ sort.Strings(keys)+ for _, key := range keys {+ var next yaml.Node+ if err := next.Encode(values[key]); err != nil {+ return err+ }+ node.Content = append(node.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key}, &next)+ }+ return nil+}+func (s *Store) write(ctx context.Context, doc *document) error {+ refs := map[string]any{}+ for key, value := range doc.refs {+ refs[key] = value+ }+ records := map[string]any{}+ for key, value := range doc.records {+ data, _ := json.Marshal(value)+ var raw any+ if json.Unmarshal(data, &raw) != nil {+ return errors.New("credential record must be JSON")+ }+ records[key] = raw+ }+ if err := syncMapping(section(doc.node.Content[0], "refs"), refs); err != nil {+ return err+ }+ if err := syncMapping(section(doc.node.Content[0], "records"), records); err != nil {+ return err+ }+ data, err := yaml.Marshal(doc.node)+ if err != nil || len(data) > documentLimit {+ return errors.New("Host credential document exceeds supported limits")+ }+ directory := filepath.Dir(s.path)+ if err = durablefs.EnsureDirectory(directory); err != nil {+ return errors.New("cannot create private credential directory")+ }+ file, err := os.CreateTemp(directory, ".credential-write-")+ if err != nil {+ return errors.New("cannot prepare credential write")+ }+ defer os.Remove(file.Name())+ _, writeErr := file.Write(data)+ if writeErr == nil {+ writeErr = file.Sync()+ }+ if err = errors.Join(writeErr, file.Close(), ctx.Err()); err != nil {+ return errors.New("cannot persist Host credentials")+ }+ if err = os.Rename(file.Name(), s.path); err != nil {+ return errors.New("cannot publish Host credentials")+ }+ return durablefs.SyncDirectory(directory)+}++func (s *Store) Subscribe(observer func(Update)) func() {+ s.mu.Lock()+ s.next+++ id := s.next+ if !s.closed {+ s.observers[id] = observer+ }+ s.mu.Unlock()+ return func() { s.mu.Lock(); delete(s.observers, id); s.mu.Unlock() }+}+func (s *Store) publish(update Update) {+ unique := func(rows []string) []string {+ sort.Strings(rows)+ out := rows[:0]+ for _, key := range rows {+ if len(out) == 0 || out[len(out)-1] != key {+ out = append(out, key)+ }+ }+ return out+ }+ update.References = unique(update.References)+ update.Records = unique(update.Records)+ if len(update.References)+len(update.Records) == 0 {+ return+ }+ s.mu.RLock()+ observers := make([]func(Update), 0, len(s.observers))+ for _, observer := range s.observers {+ observers = append(observers, observer)+ }+ s.mu.RUnlock()+ for _, observer := range observers {+ func() {+ defer func() {+ if recover() != nil && s.warn != nil {+ s.warn(errors.New("credential observer failed"))+ }+ }()+ observer(Update{append([]string(nil), update.References...), append([]string(nil), update.Records...)})+ }()+ }+}+func (s *Store) watch() {+ defer close(s.watchDone)+ ticker := time.NewTicker(100 * time.Millisecond)+ defer ticker.Stop()+ var previous os.FileInfo+ initialized := false+ for {+ select {+ case <-s.stop:+ return+ case <-ticker.C:+ select {+ case s.gate <- struct{}{}:+ default:+ continue+ }+ info, statErr := os.Stat(s.path)+ same := initialized && ((errors.Is(statErr, os.ErrNotExist) && previous == nil) || (statErr == nil && previous != nil && os.SameFile(info, previous) && info.Size() == previous.Size() && info.ModTime().Equal(previous.ModTime()) && info.Mode() == previous.Mode()))+ if same {+ <-s.gate+ continue+ }+ // Save the signature from before the read. A concurrent atomic replacement+ // during loading is then observed on the next tick, closing the startup gap.+ previous = info+ initialized = true+ doc, err := readDocument(s.path)+ if err == nil {+ s.mu.Lock()+ prior := s.doc+ s.doc = doc+ s.rememberLocked(doc)+ s.mu.Unlock()+ <-s.gate+ s.publish(changes(prior, doc))+ } else {+ <-s.gate+ if s.warn != nil {+ s.warn(fmt.Errorf("credential reload failed: %w", err))+ }+ }+ }+ }+}+func (s *Store) Close() error {+ s.closeOnce.Do(func() {+ s.mu.Lock()+ s.closed = true+ s.mu.Unlock()+ close(s.stop)+ <-s.watchDone+ s.gate <- struct{}{}+ <-s.gate+ })+ return nil+}++func (s *Store) rememberLocked(doc document) {+ if s.secrets == nil {+ s.secrets = map[string]bool{}+ }+ for _, value := range doc.refs {+ if value != "" {+ s.secrets[value] = true+ }+ }+ var visit func(any)+ visit = func(value any) {+ switch value := value.(type) {+ case string:+ if value != "" {+ s.secrets[value] = true+ }+ case []any:+ for _, v := range value {+ visit(v)+ }+ case map[string]any:+ for _, v := range value {+ visit(v)+ }+ }+ }+ for _, record := range doc.records {+ if record.Key != nil && *record.Key != "" {+ s.secrets[*record.Key] = true+ }+ for _, value := range record.Env {+ if value != "" {+ s.secrets[value] = true+ }+ }+ if record.Kind == "grant" {+ var payload any+ if json.Unmarshal(record.Payload, &payload) == nil {+ visit(payload)+ }+ }+ }+}+func (s *Store) Redact(text string) string {+ s.mu.RLock()+ values := make([]string, 0, len(s.secrets))+ for value := range s.secrets {+ values = append(values, value)+ }+ s.mu.RUnlock()+ sort.Slice(values, func(i, j int) bool { return len(values[i]) > len(values[j]) })+ for _, value := range values {+ text = strings.ReplaceAll(text, value, "[redacted]")+ }+ return text+}diff --git a/internal/credentials/store_test.go b/internal/credentials/store_test.gonew file mode 100644index 0000000..f8caa71--- /dev/null+++ b/internal/credentials/store_test.go@@ -0,0 +1,292 @@+package credentials++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"+)++func openTestStore(t *testing.T, watch bool) *Store {+ t.Helper()+ s, err := Open(filepath.Join(t.TempDir(), Filename), Options{Watch: watch})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { s.Close() })+ return s+}+func grant(value string) *Record { return &Record{Kind: "grant", Payload: json.RawMessage(value)} }++func TestReferencesAndRecordsKeepUpstreamLayeringAndPresence(t *testing.T) {+ s := openTestStore(t, false)+ s.SetProvided(map[string]string{"MAIL_KEY": "provided", "EMPTY": ""})+ if value, err := s.Resolve("MAIL_KEY"); err != nil || value.Value != "provided" || value.Source != "controller" {+ t.Fatalf("fallback: %+v %v", value, err)+ }+ if value, _ := s.Resolve("EMPTY"); value != nil {+ t.Fatal("blank supplied credential is present")+ }+ if err := s.Set(t.Context(), "MAIL_KEY", "managed"); err != nil {+ t.Fatal(err)+ }+ if value, _ := s.Resolve("MAIL_KEY"); value.Value != "managed" || value.Source != "file" {+ t.Fatal(value)+ }+ if info, _ := s.Describe("MAIL_KEY"); !info.Writable || !info.Configured || strings.Contains(info.Masked, "managed") {+ t.Fatalf("unsafe descriptor: %+v", info)+ }+ if err := s.Set(t.Context(), "MAIL_KEY", ""); err == nil {+ t.Fatal("empty write succeeded")+ }+ if err := s.Unset(t.Context(), "MAIL_KEY"); err != nil {+ t.Fatal(err)+ }+ if value, _ := s.Resolve("MAIL_KEY"); value.Value != "provided" {+ t.Fatal(value)+ }+ if _, err := s.ModifyRecord(t.Context(), "mail/personal", func(*Record) (*Record, error) { return &Record{Kind: "api-key"}, nil }); err != nil {+ t.Fatal(err)+ }+ if info, _ := s.DescribeRecord("mail/personal"); !info.Configured || info.Kind != "api-key" {+ t.Fatalf("empty api-key record must remain present: %+v", info)+ }+ if _, err := s.ModifyRecord(t.Context(), "mail/personal", func(*Record) (*Record, error) { return nil, nil }); err != nil {+ t.Fatal(err)+ }+ if entries, _ := s.ListRecords(); len(entries) != 1 || entries[0].Key != "mail/personal" {+ t.Fatal(entries)+ }+ info, err := os.Stat(s.path)+ if err != nil || info.Mode().Perm() != 0600 {+ t.Fatalf("mode=%v %v", info, err)+ }+ if err := s.Close(); err != nil {+ t.Fatal(err)+ }+ next, err := Open(s.path, Options{})+ if err != nil {+ t.Fatal(err)+ }+ defer next.Close()+ if info, _ := next.DescribeRecord("mail/personal"); !info.Configured {+ t.Fatal("record did not survive restart")+ }+ if value, _ := next.Resolve("MAIL_KEY"); value != nil {+ t.Fatal("Controller fallback leaked into durable document")+ }+}++func TestSerializedMutationReadsLatestRecordAndNeverLeaksMutableSnapshots(t *testing.T) {+ s := openTestStore(t, false)+ var wg sync.WaitGroup+ failures := make(chan error, 24)+ for range 24 {+ wg.Add(1)+ go func() {+ defer wg.Done()+ _, err := s.ModifyRecord(t.Context(), "calendar/account", func(current *Record) (*Record, error) {+ n := 0+ if current != nil {+ if err := json.Unmarshal(current.Payload, &n); err != nil {+ return nil, err+ }+ }+ data, _ := json.Marshal(n + 1)+ return &Record{Kind: "grant", Payload: data}, nil+ })+ failures <- err+ }()+ }+ wg.Wait()+ close(failures)+ for err := range failures {+ if err != nil {+ t.Fatal(err)+ }+ }+ result, err := s.ReadRecord("calendar/account")+ if err != nil || string(result.Payload) != "24" {+ t.Fatalf("lost update: %+v %v", result, err)+ }+ returned, err := s.ModifyRecord(t.Context(), "calendar/account", func(current *Record) (*Record, error) { return current, nil })+ if err != nil {+ t.Fatal(err)+ }+ returned.Payload[0] = '0'+ if stored, _ := s.ReadRecord("calendar/account"); string(stored.Payload) != "24" {+ t.Fatal("mutation result leaked authoritative memory")+ }+ result.Payload[0] = '0'+ result, _ = s.ReadRecord("calendar/account")+ if string(result.Payload) != "24" {+ t.Fatal("read mutated authoritative record")+ }+ _, err = s.ModifyRecord(t.Context(), "calendar/account", func(current *Record) (*Record, error) {+ current.Payload[0] = '0'+ return nil, errors.New("provider rejected")+ })+ if err == nil {+ t.Fatal("callback failure disappeared")+ }+ result, _ = s.ReadRecord("calendar/account")+ if string(result.Payload) != "24" {+ t.Fatal("failed callback changed record")+ }+ ctx, cancel := context.WithCancel(t.Context())+ _, err = s.ModifyRecord(ctx, "calendar/account", func(*Record) (*Record, error) { cancel(); return grant(`99`), nil })+ if !errors.Is(err, context.Canceled) {+ t.Fatalf("cancelled mutation=%v", err)+ }+ result, _ = s.ReadRecord("calendar/account")+ if string(result.Payload) != "24" {+ t.Fatal("cancelled callback committed")+ }+}++func TestRecordCallbacksCanReadCommittedStateAndCloseDrains(t *testing.T) {+ s := openTestStore(t, false)+ admitted := make(chan struct{})+ release := make(chan struct{})+ done := make(chan error, 1)+ go func() {+ _, err := s.ModifyRecord(context.Background(), "mail/primary", func(*Record) (*Record, error) {+ close(admitted)+ if _, err := s.ListRecords(); err != nil {+ return nil, err+ }+ <-release+ return grant(`{"refresh":"private"}`), nil+ })+ done <- err+ }()+ <-admitted+ closed := make(chan struct{})+ go func() { s.Close(); close(closed) }()+ select {+ case <-closed:+ t.Fatal("close did not drain admitted mutation")+ case <-time.After(15 * time.Millisecond):+ }+ close(release)+ if err := <-done; err != nil {+ t.Fatal(err)+ }+ <-closed+ if _, err := s.Resolve("MAIL_KEY"); err == nil {+ t.Fatal("closed store still accepts reads")+ }+ next, err := Open(s.path, Options{})+ if err != nil {+ t.Fatal(err)+ }+ defer next.Close()+ if record, _ := next.ReadRecord("mail/primary"); record == nil {+ t.Fatal("admitted commit lost during close")+ }+}++func TestPrivateDocumentEditsAndObserversFollowCommittedFacts(t *testing.T) {+ s := openTestStore(t, true)+ updates := make(chan Update, 20)+ s.Subscribe(func(Update) { panic("observer failure") })+ s.Subscribe(func(u Update) { updates <- u })+ if _, err := s.ModifyRecord(t.Context(), "mail/primary", func(*Record) (*Record, error) { return grant(`{"token":"secret","nested":[1,null,true]}`), nil }); err != nil {+ t.Fatal(err)+ }+ select {+ case u := <-updates:+ if len(u.Records) != 1 || u.Records[0] != "mail/primary" {+ t.Fatal(u)+ }+ case <-time.After(time.Second):+ t.Fatal("committed update missing")+ }+ data, err := os.ReadFile(s.path)+ if err != nil {+ t.Fatal(err)+ }+ data = append([]byte("# user documentation\n"), data...)+ data = []byte(strings.Replace(string(data), "refs: {}", "refs:\n MAIL_KEY: from-editor # keep this note", 1))+ if err = os.WriteFile(s.path, data, 0600); err != nil {+ t.Fatal(err)+ }+ deadline := time.After(2 * time.Second)+ for {+ select {+ case u := <-updates:+ if len(u.References) > 0 {+ goto observed+ }+ case <-deadline:+ t.Fatal("external edit was not observed")+ }+ }+observed:+ if value, _ := s.Resolve("MAIL_KEY"); value == nil || value.Value != "from-editor" {+ t.Fatal(value)+ }+ if err = s.Set(t.Context(), "OTHER_KEY", "another"); err != nil {+ t.Fatal(err)+ }+ data, _ = os.ReadFile(s.path)+ if !strings.Contains(string(data), "# user documentation") || !strings.Contains(string(data), "# keep this note") {+ t.Fatal("unrelated comments were lost")+ }+ if err = s.DeleteRecord(t.Context(), "mail/primary"); err != nil {+ t.Fatal(err)+ }+ if err = s.DeleteRecord(t.Context(), "mail/primary"); err != nil {+ t.Fatal("absent delete must be a no-op", err)+ }+}++func TestInvalidRecordNeverPoisonsNextBoot(t *testing.T) {+ s := openTestStore(t, false)+ for _, record := range []*Record{{Kind: "other"}, {Kind: "grant", Payload: json.RawMessage(`{`)}, {Kind: "api-key", Key: new(string)}, {Kind: "api-key", Env: map[string]string{"bad-name": "value"}}} {+ if _, err := s.ModifyRecord(t.Context(), "mail/primary", func(*Record) (*Record, error) { return record, nil }); err == nil {+ t.Fatalf("invalid record stored: %+v", record)+ }+ }+ if record, _ := s.ReadRecord("mail/primary"); record != nil {+ t.Fatal("failed record was published")+ }+ if _, err := s.ModifyRecord(t.Context(), "mail/primary", func(*Record) (*Record, error) { return grant(`null`), nil }); err != nil {+ t.Fatal("JSON null grant payload must be valid", err)+ }+ for _, text := range []string{"refs:\n X: true\n", "refs:\n X: a\n X: b\n", "refs: {}\n---\nrefs: {}\n", "records:\n bad: {kind: api-key}\n"} {+ path := filepath.Join(t.TempDir(), Filename)+ if err := os.WriteFile(path, []byte(text), 0600); err != nil {+ t.Fatal(err)+ }+ if next, err := Open(path, Options{}); err == nil {+ next.Close()+ t.Fatalf("invalid document accepted: %s", text)+ }+ }+}++func TestGrantObjectOrderingDoesNotEmitPhantomReloadChanges(t *testing.T) {+ s := openTestStore(t, true)+ events := make(chan Update, 8)+ s.Subscribe(func(u Update) { events <- u })+ _, err := s.ModifyRecord(t.Context(), "mail/primary", func(*Record) (*Record, error) { return grant(`{"z":1,"a":{"second":2,"first":1}}`), nil })+ if err != nil {+ t.Fatal(err)+ }+ select {+ case <-events:+ case <-time.After(time.Second):+ t.Fatal("write notification missing")+ }+ select {+ case extra := <-events:+ t.Fatalf("YAML/JSON ordering emitted an uncommitted change: %+v", extra)+ case <-time.After(250 * time.Millisecond):+ }+}diff --git a/internal/executor/browser.go b/internal/executor/browser.goindex 35e00ff..fa2c3ea 100644--- a/internal/executor/browser.go+++ b/internal/executor/browser.go@@ -8,7 +8,7 @@ import ("time")-const browserCLI = "/usr/local/bin/agent-browser"+const browserCLI = "agent-browser"type browserSession struct {socketDir stringdiff --git a/internal/executor/builder.go b/internal/executor/builder.goindex 2744543..ed4a26d 100644--- a/internal/executor/builder.go+++ b/internal/executor/builder.go@@ -3,7 +3,6 @@ package executorimport ("context""errors"- "os""path/filepath""time"@@ -19,7 +18,6 @@ import (type Builder struct {RuntimeMode stringverifiedMode string- browserAvailable boolSkills *skills.RegistryWebFetcher tools.WebFetcherWebSearcher tools.WebSearcher@@ -40,11 +38,7 @@ func NewVerifiedBuilder(mode string) (Builder, error) {return Builder{}, err}registry := &skills.Registry{DSHHome: skills.UserDSHHome, AgentsHome: skills.UserAgentsHome}- _, err := os.Stat(browserCLI)- if err != nil && !os.IsNotExist(err) {- return Builder{}, err- }- return Builder{RuntimeMode: mode, verifiedMode: mode, browserAvailable: err == nil, Skills: registry}, nil+ return Builder{RuntimeMode: mode, verifiedMode: mode, Skills: registry}, nil}func (b Builder) BuildNative(ctx context.Context, identity assembly.NativeRuntimeIdentity, reason string) (assembly.Resources, error) {@@ -75,13 +69,10 @@ func (b Builder) build(ctx context.Context, userID, cwd string) (assembly.Resourif err != nil {return assembly.Resources{}, err}- var browser browserSession- if b.browserAvailable {- browser, err = newBrowserSession()- if err != nil {- _ = jobRegistry.Close(ctx)- return assembly.Resources{}, err- }+ browser, err := newBrowserSession()+ if err != nil {+ _ = jobRegistry.Close(ctx)+ return assembly.Resources{}, err}resources := assembly.Resources{Files: agentfs.ContainerView{DefaultWorkdir: cwd},diff --git a/internal/executor/file_storage.go b/internal/executor/file_storage.goindex c69c6a9..7a27edb 100644--- a/internal/executor/file_storage.go+++ b/internal/executor/file_storage.go@@ -18,6 +18,14 @@ type NativeFileStorage struct {var _ assembly.NativeStorage = NativeFileStorage{}var _ assembly.NativeChildStorageFactory = NativeFileStorage{}+var _ assembly.NativePreparedStorage = NativeFileStorage{}++func (s NativeFileStorage) CreatePreparedNative(ctx context.Context, header sessionformat.Header, events []sessionformat.Event) (sessionformat.EventJournal, error) {+ if header.ID != s.SessionID {+ return nil, errors.New("local Session storage ID mismatch")+ }+ return s.Store.CreatePrepared(ctx, header, events)+}func (s NativeFileStorage) CreateNative(ctx context.Context, header sessionformat.Header) (sessionformat.EventJournal, error) {if header.ID != s.SessionID {diff --git a/internal/host/history.go b/internal/host/history.goindex f14277b..1edeb6f 100644--- a/internal/host/history.go+++ b/internal/host/history.go@@ -10,7 +10,7 @@ import (func historySnapshot(host *hostruntime.NativeHost) func(context.Context, string, sessionsearch.Cursor) (sessionsearch.Snapshot, error) {return func(ctx context.Context, id string, cursor sessionsearch.Cursor) (snapshot sessionsearch.Snapshot, err error) {- err = host.WithSessionHistory(func() error {+ err = host.WithSessionHistory(ctx, id, func() error {snapshot, err = readHistorySnapshot(ctx, host, id, cursor)return err})@@ -26,8 +26,7 @@ func readHistorySnapshot(ctx context.Context, host *hostruntime.NativeHost, id sif archived {return sessionsearch.Snapshot{}, os.ErrNotExist}- if live, ok := host.Session(id); ok {- events, reset, err := live.DurableSessionSuffix(cursor.Next)+ if events, reset, found, err := host.DurableSessionSuffix(id, cursor.Next); found {if err == nil {next := cursor.Next + len(events)if reset {diff --git a/internal/host/host.go b/internal/host/host.goindex 97cdaf3..e3ec68f 100644--- a/internal/host/host.go+++ b/internal/host/host.go@@ -23,18 +23,23 @@ import ("go-bot/harness/sessionsearch""go-bot/harness/skills""go-bot/harness/tools"+ "go-bot/internal/authorization""go-bot/internal/config"+ "go-bot/internal/credentials""go-bot/internal/durablefs""go-bot/internal/executor""go-bot/internal/hostruntime""go-bot/internal/httpapi"+ "go-bot/internal/mcpclient""go-bot/internal/modelsettings"+ "go-bot/internal/plugins""go-bot/internal/websearchsettings"+ mcpconfig "go-bot/mcp"+ "go-bot/plugin"imageproviders "go-bot/providers/image""go-bot/providers/model/mainmodel"webproviders "go-bot/providers/web"builtin "go-bot/providers/web/builtin"- "go-bot/thirdparty/llm""go-bot/web")@@ -70,9 +75,6 @@ func run(ctx context.Context, c config.Config, newSearchProvider web.Factory, feif err != nil {return err}- if err := skills.Bootstrap(ctx, root, skills.SeedDir); err != nil {- return fmt.Errorf("initialize Host skills: %w", err)- }search := &hostWebSearch{defaultFactory: newSearchProvider}imageGeneration := &hostImageGeneration{}dshHome := filepath.Join(root, skills.UserDSHHomeDir)@@ -93,6 +95,28 @@ func run(ctx context.Context, c config.Config, newSearchProvider web.Factory, febuilder.WebSearcher = searchbuilder.ImageGenerator = imageGenerationnative := &hostruntime.NativeHost{UserID: c.Host.AccountID, Mode: "host", StartedAt: time.Now().UTC(), ReserveScheduleModel: models.reserve}+ runCtx, cancel := context.WithCancel(ctx)+ defer cancel()+ credentialStore, err := credentials.Open(filepath.Join(dshHome, credentials.Filename), credentials.Options{Watch: true})+ if err != nil {+ return err+ }+ defer credentialStore.Close()+ commonAuthorization := authorization.New(credentialStore)+ mcpManager := mcpclient.NewManager(runCtx, mcpclient.ManagerOptions{Authorization: commonAuthorization, Credentials: credentialStore, Images: images, CWD: root, Changed: native.WakeSessions})+ defer mcpManager.Close()+ extensions, err := plugins.NewManager(runCtx, plugins.ManagerConfig{+ Directory: filepath.Join(dshHome, "plugins"),+ Runtime: plugins.RuntimeConfig{UserID: c.Host.AccountID, HostID: c.Host.RunID, Authorization: commonAuthorization, Credentials: credentialStore, Main: "/usr/share/go-bot/cordis/src/main.mjs", Home: "/root", DSHHome: dshHome, MCP: mcpManager, Skills: builder.Skills, Workspace: root},+ PackageMain: "/usr/share/go-bot/cordis/src/package-main.mjs", Changed: native.WakeSessions,+ })+ if err != nil {+ return err+ }+ defer extensions.Close()+ builder.Skills.Providers = extensions.Skills+ native.PluginsChanges = extensions.Changes+ native.MCPChanges = mcpManager.ChangesscheduleStore := schedule.FileStore{Path: filepath.Join(dshHome, "storages", "schedule.json")}native.Schedule, err = schedule.NewHostService(scheduleStore, native.PrepareSchedule, native.DeliverSchedule)if err != nil {@@ -189,8 +213,10 @@ func run(ctx context.Context, c config.Config, newSearchProvider web.Factory, fereturn &hostruntime.NativeRuntime{Factory: assembly.NativeFactory{Storage: executor.NativeFileStorage{Store: atWorkspace(workspace), SessionID: sid},- Builder: builder, Model: model, ResolveTurnModel: models.resolver(sid),- Provider: "unconfigured", ModelID: "unconfigured", SystemPrompt: assembly.DefaultCoreSystemPrompt,+ Builder: builder, Model: model, ResolveTurnModel: models.resolver(sid), ResolveSelectedModel: models.selected,+ ToolSource: extensions.Tools, PromptSource: extensions.AssemblePrompt, ToolInvocationSource: extensions.ToolInvocations,+ ExtensionScope: func() assembly.NativeExtensionScope { return mcpManager.NewScope() },+ Provider: "unconfigured", ModelID: "unconfigured", SystemPrompt: assembly.DefaultCoreSystemPrompt,Limits: agent.Limits{MaxSteps: 128, MaxToolCalls: 256, MaxModelCalls: 160, MaxParallelToolCalls: 4,ContextWindowTokens: config.ModelContextWindow, ReservedOutputTokens: 16 * 1024, ContextHeadroomTokens: 8 * 1024},Schedule: native.Schedule, FileAttachments: files, Memory: accountMemory, SessionSearch: history,@@ -224,8 +250,6 @@ func run(ctx context.Context, c config.Config, newSearchProvider web.Factory, fe}return native.BuildInWorkspace(sid, schedule.TargetCreate{CWD: defaultSessionWorkspace(root, sid)})}- runCtx, cancel := context.WithCancel(ctx)- defer cancel()if err = native.Schedule.Start(runCtx); err != nil {return err}@@ -240,6 +264,8 @@ func run(ctx context.Context, c config.Config, newSearchProvider web.Factory, fenative.WakeSessions()native.Schedule.NotifyModelChange()}+ pluginHTTP := extensions.Handler()+ mcpHTTP := mcpManager.Handler()mux := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {case websearchsettings.InternalPath:@@ -256,7 +282,7 @@ func run(ctx context.Context, c config.Config, newSearchProvider web.Factory, few.Header().Set("Content-Type", "application/json")_ = json.NewEncoder(w).Encode(ready)case "/v1/capabilities":- _ = json.NewEncoder(w).Encode(map[string]any{"model": models.defaultModel(), "protocol": llm.Responses, "search": search.configured(), "apiVersion": "v1"})+ _ = json.NewEncoder(w).Encode(map[string]any{"model": models.defaultModel(), "protocol": models.defaultProtocol(), "protocols": []string{modelsettings.Responses, modelsettings.AnthropicMessages}, "search": search.configured(), "apiVersion": "v1"})case "/internal/host/shutdown":if r.Method != http.MethodPost {http.Error(w, "method not allowed", 405)@@ -266,6 +292,14 @@ func run(ctx context.Context, c config.Config, newSearchProvider web.Factory, few.WriteHeader(202)cancel()default:+ if r.URL.Path == mcpconfig.InternalPath || strings.HasPrefix(r.URL.Path, mcpconfig.InternalPath+"/") {+ mcpHTTP.ServeHTTP(w, r)+ return+ }+ if r.URL.Path == plugin.InternalPath || strings.HasPrefix(r.URL.Path, plugin.InternalPath+"/") {+ pluginHTTP.ServeHTTP(w, r)+ return+ }if id, ok := strings.CutPrefix(r.URL.Path, modelsettings.ScheduledSelectionPrefix); ok {models.handleScheduledSelection(w, r, id, wakeForModelChange)return@@ -273,7 +307,7 @@ func run(ctx context.Context, c config.Config, newSearchProvider web.Factory, febase.ServeHTTP(w, r)}})- server := &http.Server{Handler: httpapi.Authenticate(c.Auth.HostToken, mux), BaseContext: func(net.Listener) context.Context { return runCtx }, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10}+ server := &http.Server{Handler: httpapi.Authenticate(c.Auth.HostToken, mcpManager.ControllerOAuth(mux)), BaseContext: func(net.Listener) context.Context { return runCtx }, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10}listener, err := net.Listen("tcp", config.HostListen)if err != nil {native.Schedule.Close()diff --git a/internal/host/model_selection_test.go b/internal/host/model_selection_test.gonew file mode 100644index 0000000..553b475--- /dev/null+++ b/internal/host/model_selection_test.go@@ -0,0 +1,62 @@+package host++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "sync/atomic"+ "testing"++ "go-bot/harness/agent"+ "go-bot/internal/modelsettings"+ "go-bot/providers/model/mainmodel"+)++func TestHostExplicitModelSelectionUsesOnlyTheConfiguredEndpointAndProtocol(t *testing.T) {+ var calls atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls.Add(1)+ var input struct{ Model string }+ if err := json.NewDecoder(r.Body).Decode(&input); err != nil {+ t.Error(err)+ }+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == "/responses-api/responses" && input.Model == "second" && r.Header.Get("Authorization") == "Bearer responses-fixture" {+ _, _ = w.Write([]byte(`{"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"responses selected"}]}]}`))+ return+ }+ if r.URL.Path == "/anthropic-api/messages" && input.Model == "third" && r.Header.Get("x-api-key") == "anthropic-fixture" {+ _, _ = w.Write([]byte(`{"id":"reply","type":"message","role":"assistant","content":[{"type":"text","text":"anthropic selected"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`))+ return+ }+ t.Error("selection reached a different endpoint, model or authentication mode", r.URL.Path, input.Model)+ http.Error(w, "wrong selection", 400)+ }))+ defer server.Close()+ models := hostModels{base: mainmodel.Model{Transport: server.Client().Transport}, snapshot: modelsettings.Snapshot{Catalog: modelsettings.Catalog{+ DefaultEndpointID: "responses",+ Endpoints: map[string]modelsettings.Endpoint{+ "responses": {BaseURL: server.URL + "/responses-api", APIKey: "responses-fixture", Protocol: modelsettings.Responses, Models: []string{"first", "second"}},+ "anthropic": {BaseURL: server.URL + "/anthropic-api", APIKey: "anthropic-fixture", Protocol: modelsettings.AnthropicMessages, Models: []string{"third"}},+ },+ }}}+ for _, row := range []struct{ provider, model, answer string }{{"responses", "second", "responses selected"}, {"anthropic", "third", "anthropic selected"}} {+ route := agent.ModelRoute{Provider: row.provider, Model: row.model}+ model, err := models.selected(t.Context(), route)+ if err != nil {+ t.Fatal(err)+ }+ result, err := model.Complete(agent.WithModelRoute(t.Context(), route), []agent.Message{{Role: "user", Content: "hello"}}, nil)+ if err != nil || result.Content != row.answer {+ t.Fatal("Host did not use the selected endpoint's actual adapter", result.Content, err)+ }+ }+ for _, route := range []agent.ModelRoute{{Provider: "unknown", Model: "second"}, {Provider: "responses", Model: "not-configured"}, {}} {+ if _, err := models.selected(t.Context(), route); err == nil {+ t.Fatal("an unavailable SDK route fell back to the default model", route)+ }+ }+ if calls.Load() != 2 {+ t.Fatal("unavailable selection reached a remote service", calls.Load())+ }+}diff --git a/internal/host/model_settings.go b/internal/host/model_settings.goindex c2575b7..f78107d 100644--- a/internal/host/model_settings.go+++ b/internal/host/model_settings.go@@ -41,19 +41,39 @@ func (m *hostModels) route(sessionID string) (agent.TurnModel, error) {if !ok {choice = m.scheduled[sessionID]}- endpoint, err := m.snapshot.Catalog.Resolve(choice)+ route := agent.ModelRoute{Provider: choice.EndpointID, Model: choice.ModelID}+ model, err := m.selectedLocked(route)if err != nil {return agent.TurnModel{}, err}- route := agent.ModelRoute{Provider: choice.EndpointID, Model: choice.ModelID}+ return agent.TurnModel{Model: model, Route: route}, nil+}++func (m *hostModels) selected(_ context.Context, route agent.ModelRoute) (agent.Model, error) {+ m.mu.RLock()+ defer m.mu.RUnlock()+ return m.selectedLocked(route)+}++func (m *hostModels) selectedLocked(route agent.ModelRoute) (agent.Model, error) {+ endpoint, err := m.snapshot.Catalog.Resolve(modelsettings.Selection{EndpointID: route.Provider, ModelID: route.Model})+ if err != nil {+ return nil, err+ }model := m.basemodel.Config = mainmodel.Config{Default: route,Endpoints: map[string]mainmodel.Endpoint{route.Provider: {- BaseURL: endpoint.BaseURL, APIKey: endpoint.APIKey, Protocol: llm.Responses,+ BaseURL: endpoint.BaseURL, APIKey: endpoint.APIKey, Protocol: llm.Protocol(modelsettings.NormalizeProtocol(endpoint.Protocol)),}},}- return agent.TurnModel{Model: model, Route: route}, nil+ return model, nil+}++func (m *hostModels) defaultProtocol() string {+ m.mu.RLock()+ defer m.mu.RUnlock()+ return modelsettings.NormalizeProtocol(m.snapshot.Catalog.Endpoints[m.snapshot.Catalog.DefaultEndpointID].Protocol)}// Host-created Schedule Sessions keep their credential-free selection on disk.@@ -185,6 +205,13 @@ func (m *hostModels) handle(w http.ResponseWriter, r *http.Request, wake func())return}m.mu.Lock()+ for _, endpoint := range snapshot.Catalog.Endpoints {+ if !modelsettings.ValidProtocol(endpoint.Protocol) {+ m.mu.Unlock()+ http.Error(w, "invalid model protocol", http.StatusBadRequest)+ return+ }+ }if snapshot.Revision < m.snapshot.Revision {m.mu.Unlock()http.Error(w, "stale model settings", http.StatusConflict)diff --git a/internal/hostruntime/native_archive.go b/internal/hostruntime/native_archive.goindex d5e1743..ed456f2 100644--- a/internal/hostruntime/native_archive.go+++ b/internal/hostruntime/native_archive.go@@ -40,6 +40,16 @@ func (h *NativeHost) ArchiveSessionWithActivity(ctx context.Context, id string,commit := func() error {h.operationMu.Lock()defer h.operationMu.Unlock()+ h.mu.Lock()+ pending := h.operations[id] != nil+ closed := h.closed+ h.mu.Unlock()+ if closed {+ return ErrHostClosed+ }+ if pending {+ return ErrHostSessionBusy+ }if err := h.CheckScheduleTarget(ctx, id); errors.Is(err, ErrHostSessionArchived) {return nil} else if err != nil {diff --git a/internal/hostruntime/native_creation_test.go b/internal/hostruntime/native_creation_test.gonew file mode 100644index 0000000..aa54626--- /dev/null+++ b/internal/hostruntime/native_creation_test.go@@ -0,0 +1,192 @@+package hostruntime++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "testing"++ "go-bot/harness/assembly"+ "go-bot/harness/permission"+ "go-bot/harness/session"+)++func TestNativeFactoryCreatesFromExactSeedAndMetadataUsingActualGoJournal(t *testing.T) {+ host, store := lifecycleFileHost(t)+ runtime, err := host.Build("programmatic", false)+ if err != nil {+ t.Fatal(err)+ }+ cwd, parent, preset := store.ProjectCWD, "parent-metadata", "reporter"+ seeded, count := true, uint64(4)+ seed := []sessionformat.Event{+ {Type: "permission/preset", Seq: 0, Time: 1, Data: json.RawMessage(`{"preset":"read-only"}`)},+ {Type: "sandbox/mode", Seq: 1, Time: 2, Data: json.RawMessage(`{"mode":"read-only"}`)},+ {Type: "approval/policy", Seq: 2, Time: 3, Data: json.RawMessage(`{"policy":"ask"}`)},+ {Type: "plugin:qa/seed", Seq: 3, Time: 4, Ignorable: true, Data: json.RawMessage(`{"fact":"保留此事实"}`)},+ }+ options := assembly.NativeSessionOptions{Meta: &assembly.NativeSessionMeta{CWD: &cwd, ParentSession: &parent, AgentPreset: &preset, IsSeeded: &seeded}, Seed: seed, InheritedEventCount: &count, ParentSource: &assembly.NativeParentSource{SessionID: "copied-source", EndSeq: 4}}+ entered := false+ runtime.Factory.SessionReady = func(s *sessionformat.LiveSession) {+ ctx := t.Context()+ entered = true+ artifact, err := store.ReadArtifact(ctx, s.Header().ID)+ if err != nil || len(artifact.Events) != 5 || artifact.InheritedEventCount != 4 {+ t.Fatal("seed was not fully durable before Session entry", artifact, err)+ }+ }+ runtime.Factory.BeforePublish = func(_ context.Context, live *assembly.NativeLive) error {+ seed[0].Data = json.RawMessage(`{"preset":"danger-full-access"}`)+ preset = "caller-mutated"+ if live.Session.Header().AgentPreset != "reporter" || permission.Read(live.Session.Events()).Mode != permission.ReadOnly {+ return errors.New("caller mutation or default initialization replaced the prepared input")+ }+ return nil+ }+ live, err := runtime.Factory.ActivateWithSessionOptions(t.Context(), runtime.Identity, options)+ if err != nil {+ t.Fatal(err)+ }+ if !entered {+ t.Fatal("actual Session entry hook was skipped")+ }+ header := live.Session.Header()+ if header.CWD != cwd || header.ParentSession != parent || header.Origin != "" || header.AgentPreset != "reporter" {+ t.Fatal("programmatic metadata was reclassified as an internal subagent", header)+ }+ if err := live.Close(); err != nil {+ t.Fatal(err)+ }+ artifact, err := store.ReadArtifact(t.Context(), header.ID)+ if err != nil || len(artifact.Events) != 5 || permission.Read(artifact.Events).Mode != permission.ReadOnly {+ t.Fatal("prepared facts differed after close", artifact, err)+ }+ runtime.Factory.BeforePublish = nil+ resumed, err := runtime.Factory.Resume(t.Context(), runtime.Identity)+ if err != nil {+ t.Fatal("programmatic lineage could not reopen", err)+ }+ if resumed.Session.Header() != header || resumed.Session.InheritedEventCount() != 4 {+ t.Fatal("resume changed creation metadata or inherited cut")+ }+ if err := resumed.Close(); err != nil {+ t.Fatal(err)+ }+}++func TestNativeFactoryRefusesInvalidCreationBeforePublishingAnyJournal(t *testing.T) {+ host, store := lifecycleFileHost(t)+ seeded := true+ for _, scenario := range []struct {+ name string+ options assembly.NativeSessionOptions+ }{+ {"gap", assembly.NativeSessionOptions{Seed: []sessionformat.Event{{Type: "session/end-seed", Seq: 3, Time: 1, Data: json.RawMessage(`{}`)}}}},+ {"missing-cut", assembly.NativeSessionOptions{Meta: &assembly.NativeSessionMeta{IsSeeded: &seeded}, Seed: []sessionformat.Event{}}},+ } {+ runtime, err := host.Build(scenario.name, false)+ if err != nil {+ t.Fatal(err)+ }+ if live, err := runtime.Factory.ActivateWithSessionOptions(t.Context(), runtime.Identity, scenario.options); err == nil {+ _ = live.Close()+ t.Fatal("invalid creation was accepted", scenario.name)+ }+ path, err := store.Path(scenario.name)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("rejected creation left a canonical journal", scenario.name, err)+ }+ }+}++func TestNativeFactoryCreatesFromIndependentSubagentOrigin(t *testing.T) {+ host, _ := lifecycleFileHost(t)+ runtime, err := host.Build("origin-metadata", false)+ if err != nil {+ t.Fatal(err)+ }+ origin, parent, depth := "subagent", "metadata-parent", 1+ live, err := runtime.Factory.ActivateWithSessionOptions(t.Context(), runtime.Identity, assembly.NativeSessionOptions{Meta: &assembly.NativeSessionMeta{Origin: &origin, ParentSession: &parent, DelegationDepth: &depth}})+ if err != nil {+ t.Fatal(err)+ }+ header := live.Session.Header()+ if err := live.Close(); err != nil {+ t.Fatal(err)+ }+ resumed, err := runtime.Factory.Resume(t.Context(), runtime.Identity)+ if err != nil {+ t.Fatal("generic resume incorrectly required an internal child descriptor", err)+ }+ defer resumed.Close()+ if resumed.Session.Header() != header || header.Origin != origin || header.ParentSession != parent || header.DelegationDepth != depth {+ t.Fatal("generic resume altered lineage metadata", resumed.Session.Header())+ }+}++func TestHostProgrammaticCreationUsesActualRuntimeAndReleasesBorrowedInputs(t *testing.T) {+ host, _ := lifecycleFileHost(t)+ preset := "initial-preset"+ options := assembly.NativeSessionOptions{Meta: &assembly.NativeSessionMeta{AgentPreset: &preset}, Seed: []sessionformat.Event{}}+ runtime, err := host.ActivateWithSessionOptions(t.Context(), "programmatic-host", options, func(ctx context.Context, live *assembly.NativeLive) error {+ preset = "late-caller-change"+ if _, visible := host.Session("programmatic-host"); visible {+ return errors.New("Agent published before setup")+ }+ artifact, err := host.SessionArtifact(ctx, "programmatic-host")+ if err != nil || artifact.Header.AgentPreset != "initial-preset" || len(artifact.Events) == 0 || artifact.Events[0].Type != "session/end-seed" {+ return errors.New("explicit empty seed or snapshot metadata lost before setup")+ }+ return nil+ })+ if err != nil {+ t.Fatal(err)+ }+ if runtime.sessionCreation != nil {+ t.Fatal("runtime retained a second copy of creation history")+ }+ if active, ok := host.Session("programmatic-host"); !ok || active != runtime {+ t.Fatal("programmatic creation bypassed Host ownership")+ }+ if err := host.StopSession(t.Context(), "programmatic-host"); err != nil {+ t.Fatal(err)+ }+ if _, err := host.Activate(t.Context(), "programmatic-host", true); err != nil {+ t.Fatal("programmatic Session could not resume through normal Host admission", err)+ }+}++func TestProgrammaticCreationAndResumeSetupFailurePreservePendingInbox(t *testing.T) {+ host, store := lifecycleFileHost(t)+ seed := []sessionformat.Event{{Type: "agent/inbox/spliced", Seq: 0, Time: 1, Data: json.RawMessage(`{"target":"next-turn","start":0,"inserted":[{"id":"pending-message","role":"user","source":{"kind":"user"},"content":[{"type":"text","text":"do not lose this accepted input"}]}]}`)}}+ veto := errors.New("setup intentionally rejected")+ setup := func(_ context.Context, live *assembly.NativeLive) error {+ if len(live.Session.Inbox().NextTurn) != 1 {+ return errors.New("pending input lost before setup")+ }+ return veto+ }+ if _, err := host.ActivateWithSessionOptions(t.Context(), "pending-failure", assembly.NativeSessionOptions{Seed: seed}, setup); !errors.Is(err, veto) {+ t.Fatal("unexpected creation result", err)+ }+ if _, err := host.ActivateWithSetup(t.Context(), "pending-failure", true, setup); !errors.Is(err, veto) {+ t.Fatal("unexpected resume result", err)+ }+ artifact, err := store.ReadArtifact(t.Context(), "pending-failure")+ if err != nil {+ t.Fatal(err)+ }+ inbox, err := sessionformat.FoldInbox(artifact.Events)+ if err != nil || len(inbox.NextTurn) != 1 {+ t.Fatal("initialization rollback discarded accepted input", inbox, err)+ }+ for _, event := range artifact.Events {+ if event.Type == "turn/start" {+ t.Fatal("failed initialization released queued work into the driver")+ }+ }+}diff --git a/internal/hostruntime/native_host.go b/internal/hostruntime/native_host.goindex 2f2d131..a76ffce 100644--- a/internal/hostruntime/native_host.go+++ b/internal/hostruntime/native_host.go@@ -10,6 +10,7 @@ import ("sync""time"+ "go-bot/harness/assembly""go-bot/harness/schedule""go-bot/harness/session")@@ -45,54 +46,95 @@ type NativeHost struct {Schedule *schedule.ServiceStartedAt time.TimeReserveScheduleModel func(string) error+ PluginsChanges func() (<-chan struct{}, <-chan struct{})+ MCPChanges func() (<-chan struct{}, <-chan struct{})approvalMu sync.MutexapprovalStreams map[string]int+ hostStreams intoperationMu sync.Mutex- historyMu sync.RWMutex // Keeps cold history readers outside Session activation.+ historyLocks map[string]*hostHistoryGate+ operations map[string]*hostSessionOperationscheduleClose sync.Oncemu sync.Mutexsessions map[string]*NativeRuntime- activating boolclosed boollastActivity time.Time}func (h *NativeHost) Activate(ctx context.Context, sessionID string, resume bool) (*NativeRuntime, error) {- return h.activate(ctx, sessionID, resume, nil)+ return h.activate(ctx, sessionID, resume, nil, nil, nil)}func (h *NativeHost) ActivateInWorkspace(ctx context.Context, sessionID string, create schedule.TargetCreate) (*NativeRuntime, error) {- return h.activate(ctx, sessionID, false, &create)+ return h.activate(ctx, sessionID, false, &create, nil, nil)}-func (h *NativeHost) activate(ctx context.Context, sessionID string, resume bool, create *schedule.TargetCreate) (*NativeRuntime, error) {+func (h *NativeHost) ActivateWithSetup(ctx context.Context, sessionID string, resume bool, setup NativeSetup) (*NativeRuntime, error) {+ return h.activate(ctx, sessionID, resume, nil, setup, nil)+}++func (h *NativeHost) ActivateInWorkspaceWithSetup(ctx context.Context, sessionID string, create schedule.TargetCreate, setup NativeSetup) (*NativeRuntime, error) {+ return h.activate(ctx, sessionID, false, &create, setup, nil)+}++// ActivateWithSessionOptions uses the same Host admission, Go driver and+// rollback path, while allowing programmatic metadata/seed independent of the+// manual chat workspace convention. Setup still receives the actual Go Agent.+func (h *NativeHost) ActivateWithSessionOptions(ctx context.Context, id string, options assembly.NativeSessionOptions, setup NativeSetup) (*NativeRuntime, error) {+ detached, err := options.Snapshot()+ if err != nil {+ return nil, err+ }+ create := schedule.TargetCreate{}+ if meta := detached.Meta; meta != nil {+ if meta.CWD != nil {+ create.CWD = *meta.CWD+ }+ if meta.AgentPreset != nil {+ create.AgentPreset = *meta.AgentPreset+ }+ }+ return h.activate(ctx, id, false, &create, setup, &detached)+}++func (h *NativeHost) activate(ctx context.Context, sessionID string, resume bool, create *schedule.TargetCreate, setup NativeSetup, options *assembly.NativeSessionOptions) (_ *NativeRuntime, resultErr error) {if h.UserID == "" || h.Build == nil || !hostSessionID.MatchString(sessionID) {return nil, errors.New("invalid native Host Session activation")}h.operationMu.Lock()- defer h.operationMu.Unlock()if err := h.CheckScheduleTarget(ctx, sessionID); err != nil {+ h.operationMu.Unlock()return nil, err}h.mu.Lock()if h.closed {h.mu.Unlock()+ h.operationMu.Unlock()return nil, ErrHostClosed}- if h.sessions[sessionID] != nil {+ if h.sessions[sessionID] != nil || h.operations[sessionID] != nil {h.mu.Unlock()+ h.operationMu.Unlock()return nil, ErrHostSessionActive}- h.activating = true+ ctx, cancel := context.WithCancel(ctx)+ operation := &hostSessionOperation{done: make(chan struct{}), cancel: cancel}+ if h.operations == nil {+ h.operations = make(map[string]*hostSessionOperation)+ }+ h.operations[sessionID] = operationh.mu.Unlock()+ h.operationMu.Unlock()defer func() {- h.mu.Lock()- h.activating = false- h.mu.Unlock()+ cancel()+ h.finishOperation(sessionID, operation, resultErr)}()- h.historyMu.Lock()- defer h.historyMu.Unlock()+ releaseHistory := h.historyGate(sessionID, true)+ defer releaseHistory()+ if err := ctx.Err(); err != nil {+ return nil, err+ }var runtime *NativeRuntimevar err errorif create != nil && h.BuildInWorkspace != nil {@@ -107,10 +149,57 @@ func (h *NativeHost) activate(ctx context.Context, sessionID string, resume boolreturn nil, errors.New("native Host builder returned a foreign Session")}runtime.approvalAudience = func() bool { return h.hasChatStream(sessionID) }- if err := runtime.Start(ctx, resume); err != nil {+ runtime.sessionCreation = options+ h.mu.Lock()+ operation.runtime = runtime+ h.mu.Unlock()+ err = runtime.start(ctx, resume, func(s *sessionformat.LiveSession) {+ h.mu.Lock()+ operation.session = s+ h.mu.Unlock()+ releaseHistory()+ }, func(live *assembly.NativeLive) {+ h.mu.Lock()+ operation.live = live+ h.mu.Unlock()+ releaseHistory()+ }, setup)+ if err != nil {+ runtime.mu.Lock()+ retained := runtime.live != nil+ runtime.mu.Unlock()+ if retained {+ h.mu.Lock()+ if h.sessions == nil {+ h.sessions = make(map[string]*NativeRuntime)+ }+ h.sessions[sessionID] = runtime+ h.mu.Unlock()+ return runtime, fmt.Errorf("activate native Session %s: %w", sessionID, err)+ }return nil, fmt.Errorf("activate native Session %s: %w", sessionID, err)}h.mu.Lock()+ publicationErr := ctx.Err()+ if h.closed {+ publicationErr = ErrHostClosed+ }+ if publicationErr != nil {+ h.mu.Unlock()+ runtime.Abort()+ cleanup, stop := context.WithTimeout(context.Background(), 10*time.Second)+ defer stop()+ if err := runtime.Stop(cleanup); err != nil {+ h.mu.Lock()+ if h.sessions == nil {+ h.sessions = make(map[string]*NativeRuntime)+ }+ h.sessions[sessionID] = runtime+ h.mu.Unlock()+ return runtime, errors.Join(publicationErr, err)+ }+ return nil, publicationErr+ }if h.sessions == nil {h.sessions = make(map[string]*NativeRuntime)}@@ -151,7 +240,35 @@ func (h *NativeHost) AttachChatStream(sessionID string) func() {func (h *NativeHost) hasChatStream(sessionID string) bool {h.approvalMu.Lock()defer h.approvalMu.Unlock()- return h.approvalStreams[sessionID] > 0+ return h.hostStreams > 0 || h.approvalStreams[sessionID] > 0+}++// AttachHostStream marks an interactive client for all current and future+// Sessions. Detaching never cancels a question that has already been asked.+func (h *NativeHost) AttachHostStream() func() {+ h.approvalMu.Lock()+ h.hostStreams+++ h.approvalMu.Unlock()+ var once sync.Once+ return func() {+ once.Do(func() {+ h.approvalMu.Lock()+ h.hostStreams--+ h.approvalMu.Unlock()+ })+ }+}++// StreamSessions returns handles without activating cold Sessions. Callers+// must not hold the Host lock while reading or subscribing to a runtime.+func (h *NativeHost) StreamSessions() (map[string]*NativeRuntime, bool) {+ h.mu.Lock()+ defer h.mu.Unlock()+ result := make(map[string]*NativeRuntime, len(h.sessions))+ for id, runtime := range h.sessions {+ result[id] = runtime+ }+ return result, h.closed}func (h *NativeHost) Session(sessionID string) (*NativeRuntime, bool) {@@ -164,11 +281,14 @@ func (h *NativeHost) Session(sessionID string) (*NativeRuntime, bool) {return runtime, ok}-// WithSessionHistory keeps a cold read outside the interval where a runtime-// may be writing its journal but has not yet been published to Session().-func (h *NativeHost) WithSessionHistory(read func() error) error {- h.historyMu.RLock()- defer h.historyMu.RUnlock()+// WithSessionHistory protects cold initialization for one Session. Readers+// use DurableSessionSuffix/SessionArtifact once a real Go Session is prepared.+func (h *NativeHost) WithSessionHistory(ctx context.Context, id string, read func() error) error {+ release := h.historyGate(id, false)+ defer release()+ if err := ctx.Err(); err != nil {+ return err+ }return read()}@@ -186,10 +306,7 @@ func (h *NativeHost) scheduleRuntime(ctx context.Context, sessionID string) (*Navar err errorruntime, err = h.Activate(ctx, sessionID, true)if errors.Is(err, ErrHostSessionActive) {- runtime, found = h.Session(sessionID)- if found {- err = nil- }+ runtime, err = h.AwaitSession(ctx, sessionID)}if err != nil {return nil, err@@ -211,7 +328,11 @@ func (h *NativeHost) EnsureScheduleDestination(ctx context.Context, sessionID streturn err}}- if _, err := h.ActivateInWorkspace(ctx, sessionID, create); err != nil && !errors.Is(err, ErrHostSessionActive) {+ _, err := h.ActivateInWorkspace(ctx, sessionID, create)+ if errors.Is(err, ErrHostSessionActive) {+ _, err = h.AwaitSession(ctx, sessionID)+ }+ if err != nil {return err}} else if err != nil {@@ -242,23 +363,73 @@ func (h *NativeHost) DeliverSchedule(ctx context.Context, sessionID, text string// StopSession drains only this top-level Session and its own children/jobs.// Other Session runtimes remain live and continue accepting messages.func (h *NativeHost) StopSession(ctx context.Context, sessionID string) error {+ return h.stopSession(ctx, sessionID, false)+}++func (h *NativeHost) stopSession(ctx context.Context, sessionID string, closing bool) (resultErr error) {+ return h.stopOwnedSession(ctx, sessionID, closing, nil)+}++// StopRuntime releases an exact factory-owned live Agent. Reusing a Session ID+// never transfers an old creator's ownership to its replacement. UI stop-by-ID+// remains the separate StopSession operation.+func (h *NativeHost) StopRuntime(ctx context.Context, runtime *NativeRuntime) error {+ if runtime == nil || runtime.Identity.UserID != h.UserID || !hostSessionID.MatchString(runtime.Identity.SessionID) {+ return errors.New("invalid owned native Agent")+ }+ return h.stopOwnedSession(ctx, runtime.Identity.SessionID, false, runtime)+}++func (h *NativeHost) stopOwnedSession(ctx context.Context, sessionID string, closing bool, expected *NativeRuntime) (resultErr error) {h.operationMu.Lock()- defer h.operationMu.Unlock()h.mu.Lock()- if h.closed {+ if expected != nil && h.sessions[sessionID] != expected && (h.operations[sessionID] == nil || h.operations[sessionID].runtime != expected) {h.mu.Unlock()+ h.operationMu.Unlock()+ return nil // This lifetime has already been withdrawn, even after Host close.+ }+ if h.closed && !closing && expected == nil {+ h.mu.Unlock()+ h.operationMu.Unlock()return ErrHostClosed}+ if operation := h.operations[sessionID]; operation != nil {+ h.mu.Unlock()+ h.operationMu.Unlock()+ if !operation.stopping {+ return ErrHostSessionBusy+ }+ select {+ case <-operation.done:+ return operation.err+ case <-ctx.Done():+ return ctx.Err()+ }+ }runtime := h.sessions[sessionID]if runtime == nil {h.mu.Unlock()+ h.operationMu.Unlock()return ErrHostSessionAbsent}+ operation := &hostSessionOperation{done: make(chan struct{}), runtime: runtime, stopping: true}+ if h.operations == nil {+ h.operations = make(map[string]*hostSessionOperation)+ }+ h.operations[sessionID] = operationh.mu.Unlock()- if err := runtime.Stop(ctx); err != nil {+ h.operationMu.Unlock()+ defer func() { h.finishOperation(sessionID, operation, resultErr) }()+ var stopErr error+ if expected != nil {+ stopErr = runtime.Dispose(ctx)+ } else {+ stopErr = runtime.Stop(ctx)+ }+ if stopErr != nil {// A timed-out stop may still be draining its turn or child Jobs. Keep// the runtime visible so Host activity cannot report false idleness.- return err+ return stopErr}h.mu.Lock()delete(h.sessions, sessionID)@@ -279,7 +450,7 @@ func (h *NativeHost) Activity() (sessionformat.ActivitySnapshot, error) {return sessionformat.ActivitySnapshot{}, ErrHostClosed}runtimes := make([]*NativeRuntime, 0, len(h.sessions))- activating := h.activating+ activating := len(h.operations) != 0since := h.lastActivityif h.StartedAt.After(since) {since = h.StartedAt@@ -314,7 +485,7 @@ func (h *NativeHost) Activity() (sessionformat.ActivitySnapshot, error) {result.Since = h.lastActivityresult.Idle = false}- if h.activating {+ if len(h.operations) != 0 {result.Idle = false}h.mu.Unlock()@@ -328,8 +499,17 @@ func (h *NativeHost) Close(ctx context.Context) error {h.operationMu.Lock()h.mu.Lock()h.closed = true+ var cancel []context.CancelFunc+ for _, operation := range h.operations {+ if operation.cancel != nil {+ cancel = append(cancel, operation.cancel)+ }+ }h.mu.Unlock()h.operationMu.Unlock()+ for _, stop := range cancel {+ stop()+ }// A due Schedule delivery may be waiting to activate a Session. Release// operationMu before waiting for that dispatcher to stop; closed admission// makes any late activation fail without constructing another runtime.@@ -338,8 +518,39 @@ func (h *NativeHost) Close(ctx context.Context) error {h.Schedule.Close()}})- h.operationMu.Lock()- defer h.operationMu.Unlock()+ // Setup/disposal may reenter Host services. Wait for admitted operations+ // without a Host mutex; a caller deadline leaves their ownership intact.+ for {+ h.mu.Lock()+ var pending <-chan struct{}+ for _, operation := range h.operations {+ pending = operation.done+ break+ }+ h.mu.Unlock()+ if pending == nil {+ break+ }+ select {+ case <-pending:+ case <-ctx.Done():+ h.mu.Lock()+ unfinished := make(map[*NativeRuntime]bool)+ for _, runtime := range h.sessions {+ unfinished[runtime] = true+ }+ for _, operation := range h.operations {+ if operation.runtime != nil {+ unfinished[operation.runtime] = true+ }+ }+ h.mu.Unlock()+ for runtime := range unfinished {+ runtime.Abort()+ }+ return ctx.Err()+ }+ }h.mu.Lock()runtimes := make(map[string]*NativeRuntime, len(h.sessions))for id, runtime := range h.sessions {@@ -347,14 +558,10 @@ func (h *NativeHost) Close(ctx context.Context) error {}h.mu.Unlock()var failures []error- for id, runtime := range runtimes {- if err := runtime.Stop(ctx); err != nil {+ for id := range runtimes {+ if err := h.stopSession(ctx, id, true); err != nil && !errors.Is(err, ErrHostSessionAbsent) {failures = append(failures, fmt.Errorf("stop Session %s: %w", id, err))- continue}- h.mu.Lock()- delete(h.sessions, id)- h.mu.Unlock()}return errors.Join(failures...)}diff --git a/internal/hostruntime/native_host_test.go b/internal/hostruntime/native_host_test.goindex fe4836d..8812cbc 100644--- a/internal/hostruntime/native_host_test.go+++ b/internal/hostruntime/native_host_test.go@@ -11,6 +11,26 @@ import ("go-bot/harness/interaction")+func TestHostStreamAudienceIncludesFutureSessionsAndMultipleClients(t *testing.T) {+ host := &NativeHost{}+ if host.hasChatStream("new-session") {+ t.Fatal("offline Host has an audience")+ }+ first, second := host.AttachHostStream(), host.AttachHostStream()+ if !host.hasChatStream("new-session") {+ t.Fatal("Host client did not cover a future Session")+ }+ first()+ first() // A teardown must never decrement twice.+ if !host.hasChatStream("another-session") {+ t.Fatal("one remaining client was ignored")+ }+ second()+ if host.hasChatStream("new-session") {+ t.Fatal("closed clients remained online")+ }+}+func TestNativeHostOwnsMultipleIndependentSessions(t *testing.T) {ctx := context.Background()stores := map[string]*nativeRuntimeStore{diff --git a/internal/hostruntime/native_lifecycle.go b/internal/hostruntime/native_lifecycle.gonew file mode 100644index 0000000..1ad3ff1--- /dev/null+++ b/internal/hostruntime/native_lifecycle.go@@ -0,0 +1,157 @@+package hostruntime++import (+ "context"+ "errors"+ "sync"++ "go-bot/harness/assembly"+ "go-bot/harness/session"+)++type hostSessionOperation struct {+ done chan struct{}+ cancel context.CancelFunc // Creation only; stop has its caller's budget.+ runtime *NativeRuntime+ live *assembly.NativeLive+ session *sessionformat.LiveSession+ stopping bool+ err error // Read only after done.+}++type hostHistoryGate struct {+ mu sync.RWMutex+ users int+}++// AwaitSession waits for an already admitted creation without starting another+// Agent or reading an incompletely prepared journal.+func (h *NativeHost) AwaitSession(ctx context.Context, id string) (*NativeRuntime, error) {+ h.mu.Lock()+ pending := h.operations[id]+ h.mu.Unlock()+ if pending != nil && !pending.stopping {+ select {+ case <-pending.done:+ if pending.err != nil {+ return nil, pending.err+ }+ case <-ctx.Done():+ return nil, ctx.Err()+ }+ }+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ h.mu.Lock()+ defer h.mu.Unlock()+ if h.closed {+ return nil, ErrHostClosed+ }+ if runtime := h.sessions[id]; runtime != nil {+ return runtime, nil+ }+ return nil, ErrHostSessionAbsent+}++// Only the actual Session file's preparation excludes cold readers. The+// write gate is released as soon as a real Go LiveSession can serve reads,+// before setup or extension callbacks. Other Session IDs never share it.+func (h *NativeHost) historyGate(id string, write bool) func() {+ h.mu.Lock()+ if h.historyLocks == nil {+ h.historyLocks = make(map[string]*hostHistoryGate)+ }+ gate := h.historyLocks[id]+ if gate == nil {+ gate = &hostHistoryGate{}+ h.historyLocks[id] = gate+ }+ gate.users+++ h.mu.Unlock()+ if write {+ gate.mu.Lock()+ } else {+ gate.mu.RLock()+ }+ var once sync.Once+ return func() {+ once.Do(func() {+ if write {+ gate.mu.Unlock()+ } else {+ gate.mu.RUnlock()+ }+ h.mu.Lock()+ gate.users--+ if gate.users == 0 {+ delete(h.historyLocks, id)+ }+ h.mu.Unlock()+ })+ }+}++func (h *NativeHost) sessionHistory(id string) *sessionformat.LiveSession {+ h.mu.Lock()+ if operation := h.operations[id]; operation != nil && operation.session != nil {+ s := operation.session+ h.mu.Unlock()+ return s+ }+ if operation := h.operations[id]; operation != nil && operation.live != nil {+ live := operation.live.Session+ h.mu.Unlock()+ return live+ }+ runtime := h.sessions[id]+ h.mu.Unlock()+ if runtime == nil {+ return nil+ }+ runtime.mu.Lock()+ defer runtime.mu.Unlock()+ if runtime.live == nil {+ return nil+ }+ return runtime.live.Session+}++// DurableSessionSuffix includes a prepared Session without publishing its+// Agent or exposing a mutable Session handle to history consumers.+func (h *NativeHost) DurableSessionSuffix(id string, next int) ([]sessionformat.Event, bool, bool, error) {+ live := h.sessionHistory(id)+ if live == nil {+ return nil, false, false, nil+ }+ if int64(next) > live.DurableCursor()+1 {+ return live.DurableEvents(), true, true, nil+ }+ events, err := live.DurableEventsFrom(next)+ return events, false, true, err+}++// SessionArtifact chooses the actual Go fsync watermark during preparation,+// execution and teardown, using disk only when no such owner exists.+func (h *NativeHost) SessionArtifact(ctx context.Context, id string) (artifact sessionformat.PhysicalArtifact, err error) {+ err = h.WithSessionHistory(ctx, id, func() error {+ if live := h.sessionHistory(id); live != nil {+ artifact = sessionformat.PhysicalArtifact{Header: live.Header(), Events: live.DurableEvents(), InheritedEventCount: live.InheritedEventCount()}+ return nil+ }+ if h.ReadSession == nil {+ return errors.New("Session history storage is unavailable")+ }+ artifact, err = h.ReadSession(ctx, id)+ return err+ })+ return artifact, err+}++func (h *NativeHost) finishOperation(id string, operation *hostSessionOperation, err error) {+ h.mu.Lock()+ operation.err = err+ delete(h.operations, id)+ close(operation.done)+ h.mu.Unlock()+}diff --git a/internal/hostruntime/native_lifecycle_test.go b/internal/hostruntime/native_lifecycle_test.gonew file mode 100644index 0000000..2b7bfa6--- /dev/null+++ b/internal/hostruntime/native_lifecycle_test.go@@ -0,0 +1,442 @@+package hostruntime++import (+ "context"+ "encoding/json"+ "errors"+ "sync/atomic"+ "testing"+ "time"++ "go-bot/harness/agent"+ "go-bot/harness/assembly"+ "go-bot/harness/permission"+ "go-bot/harness/session"+ "go-bot/internal/executor"+ "go-bot/internal/modeldata"+)++type lifecycleBuilder struct {+ nativeRuntimeBuilder+ closed func()+}++type lifecycleFailureBuilder struct {+ nativeRuntimeBuilder+ err error+}++func (b lifecycleFailureBuilder) BuildNative(ctx context.Context, identity assembly.NativeRuntimeIdentity, mode string) (assembly.Resources, error) {+ resource, err := b.nativeRuntimeBuilder.BuildNative(ctx, identity, mode)+ resource.Close = func() error { return b.err }+ return resource, err+}++func (b lifecycleBuilder) BuildNative(ctx context.Context, identity assembly.NativeRuntimeIdentity, mode string) (assembly.Resources, error) {+ resource, err := b.nativeRuntimeBuilder.BuildNative(ctx, identity, mode)+ resource.Close = func() error { b.closed(); return nil }+ return resource, err+}++func lifecycleFileHost(t *testing.T) (*NativeHost, sessionformat.FileStore) {+ t.Helper()+ claims := &sessionformat.ProcessClaims{}+ store := sessionformat.FileStore{Root: t.TempDir(), ProjectCWD: t.TempDir(), Claim: claims.Acquire}+ host := &NativeHost{UserID: "lifecycle-test"}+ host.Build = func(id string, _ bool) (*NativeRuntime, error) {+ factory := nativeRuntimeTestFactory(t, nil, nativeRuntimeModel{})+ factory.Storage = executor.NativeFileStorage{Store: store, SessionID: id}+ return &NativeRuntime{Factory: factory, Identity: assembly.NativeRuntimeIdentity{UserID: host.UserID, SessionID: id, Workspace: store.ProjectCWD}}, nil+ }+ host.ReadSession = store.ReadArtifact+ t.Cleanup(func() {+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer cancel()+ if err := host.Close(ctx); err != nil {+ t.Error(err)+ }+ })+ return host, store+}++func TestOwnedAgentDisposalCannotStopASameIDReplacement(t *testing.T) {+ host, _ := lifecycleFileHost(t)+ first, err := host.Activate(t.Context(), "owned", false)+ if err != nil {+ t.Fatal(err)+ }+ if err := host.StopRuntime(t.Context(), first); err != nil {+ t.Fatal(err)+ }+ second, err := host.Activate(t.Context(), "owned", true)+ if err != nil {+ t.Fatal(err)+ }+ if first == second {+ t.Fatal("resume reused the disposed runtime")+ }+ for _, old := range []*NativeRuntime{first, {Identity: first.Identity}} {+ if err := host.StopRuntime(t.Context(), old); err != nil {+ t.Fatal(err)+ }+ if current, ok := host.Session("owned"); !ok || current != second {+ t.Fatal("a stale or unowned handle stopped the replacement")+ }+ }+ if err := host.StopRuntime(t.Context(), second); err != nil {+ t.Fatal(err)+ }+ if err := host.Close(t.Context()); err != nil {+ t.Fatal(err)+ }+ if err := host.StopRuntime(t.Context(), second); err != nil {+ t.Fatal("disposal of an already released Agent is not idempotent", err)+ }+ if err := host.StopRuntime(t.Context(), nil); err == nil {+ t.Fatal("missing owner accepted")+ }+}++type ownedAgentBlockModel struct {+ started chan struct{}+ calls atomic.Int32+}++func (m *ownedAgentBlockModel) Complete(ctx context.Context, _ []agent.Message, _ []agent.ToolSpec) (modeldata.AssistantMessage, error) {+ if m.calls.Add(1) == 1 {+ close(m.started)+ }+ <-ctx.Done()+ return modeldata.AssistantMessage{}, ctx.Err()+}++func TestOwnedAgentDisposalCancelsActiveTurnAndClearsReadyInbox(t *testing.T) {+ host, store := lifecycleFileHost(t)+ model := &ownedAgentBlockModel{started: make(chan struct{})}+ build := host.Build+ host.Build = func(id string, resume bool) (*NativeRuntime, error) {+ runtime, err := build(id, resume)+ runtime.Factory.Model = model+ return runtime, err+ }+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ runtime, err := host.Activate(ctx, "owned-cancel", false)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := runtime.SubmitText(ctx, "active"); err != nil {+ t.Fatal(err)+ }+ select {+ case <-model.started:+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }+ if _, err := runtime.SubmitText(ctx, "queued"); err != nil {+ t.Fatal(err)+ }+ if err := host.StopRuntime(ctx, runtime); err != nil {+ t.Fatal(err)+ }+ artifact, err := store.ReadArtifact(ctx, "owned-cancel")+ if err != nil {+ t.Fatal(err)+ }+ inbox, err := sessionformat.FoldInbox(artifact.Events)+ if err != nil || len(inbox.NextStep) != 0 || len(inbox.NextTurn) != 0 || model.calls.Load() != 1 {+ t.Fatal("owner teardown drained queued work instead of cancelling it", inbox, model.calls.Load(), err)+ }+ var reason struct {+ Reason struct {+ Kind string+ Reason struct{ Kind string }+ }+ }+ for _, event := range artifact.Events {+ if event.Type == "turn/end" {+ if err := json.Unmarshal(event.Data, &reason); err != nil {+ t.Fatal(err)+ }+ }+ }+ if reason.Reason.Kind != "aborted" || reason.Reason.Reason.Kind != "disposed" {+ t.Fatal("owner teardown lost the disposed cancellation cause", reason)+ }+}++func TestAwaitSessionWaitsForPreparedGoAgentAndPropagatesFailure(t *testing.T) {+ for _, fail := range []bool{false, true} {+ t.Run(map[bool]string{false: "published", true: "failed"}[fail], func(t *testing.T) {+ host, _ := lifecycleFileHost(t)+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ entered, release := make(chan struct{}), make(chan struct{})+ defer func() {+ select {+ case <-release:+ default:+ close(release)+ }+ }()+ activation := make(chan error, 1)+ rejected := errors.New("setup rejected")+ go func() {+ _, err := host.ActivateWithSetup(ctx, "awaited", false, func(context.Context, *assembly.NativeLive) error {+ close(entered)+ <-release+ if fail {+ return rejected+ }+ return nil+ })+ activation <- err+ }()+ <-entered+ waited := make(chan error, 1)+ go func() { _, err := host.AwaitSession(ctx, "awaited"); waited <- err }()+ select {+ case err := <-waited:+ t.Fatal("unpublished Agent escaped the creation barrier", err)+ case <-time.After(20 * time.Millisecond):+ }+ close(release)+ if err := <-activation; fail != errors.Is(err, rejected) {+ t.Fatal("unexpected setup outcome", err)+ }+ if err := <-waited; fail != errors.Is(err, rejected) {+ t.Fatal("waiting caller lost setup outcome", err)+ }+ })+ }+}++func TestPreparedGoSessionIsReadableBeforeAgentPublicationAndSetupRollbackRetainsFacts(t *testing.T) {+ host, store := lifecycleFileHost(t)+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ var bound, closed atomic.Int32+ build := host.Build+ host.Build = func(id string, resume bool) (*NativeRuntime, error) {+ runtime, err := build(id, resume)+ runtime.Factory.BeforePublish = func(context.Context, *assembly.NativeLive) error { bound.Add(1); return nil }+ runtime.Factory.Builder = lifecycleBuilder{nativeRuntimeBuilder{store.ProjectCWD}, func() { closed.Add(1) }}+ return runtime, err+ }+ failed := errors.New("setup rejected")+ _, err := host.ActivateWithSetup(ctx, "prepared", false, func(ctx context.Context, live *assembly.NativeLive) error {+ if _, active := host.Session("prepared"); active {+ return errors.New("Agent published before setup")+ }+ activity, err := host.Activity()+ if err != nil || activity.Idle {+ return errors.New("preparation reported idle")+ }+ artifact, err := host.SessionArtifact(ctx, "prepared")+ if err != nil || artifact.Header != live.Session.Header() {+ return errors.New("prepared history did not use the actual Go Session")+ }+ if err := host.WithSessionHistory(ctx, "other", func() error { return nil }); err != nil {+ return err+ }+ if _, err := host.Activate(ctx, "nested", false); err != nil {+ return err+ }+ if err := permission.Save(ctx, live.Session, permission.ReadOnly, false, true); err != nil {+ return err+ }+ return failed+ })+ if !errors.Is(err, failed) {+ t.Fatal("setup did not return its original failure", err)+ }+ if _, found := host.Session("prepared"); found || bound.Load() != 2 || closed.Load() != 1 {+ t.Fatal("failed setup published/bound the Agent or retained resources")+ }+ artifact, err := store.ReadArtifact(ctx, "prepared")+ if err != nil || permission.Read(artifact.Events).Mode != permission.ReadOnly {+ t.Fatal("rollback deleted committed Session facts", err)+ }+ resumed, err := host.Activate(ctx, "prepared", true)+ if err != nil {+ t.Fatal("failed setup left the file claim owned", err)+ }+ state, err := resumed.GetPermission()+ if err != nil || state.Mode != permission.ReadOnly {+ t.Fatal("resume did not restore the actual journal state", state, err)+ }+ if bound.Load() != 3 {+ t.Fatal("resume did not publish once")+ }+ host.mu.Lock()+ defer host.mu.Unlock()+ if len(host.historyLocks) != 0 || len(host.operations) != 0 {+ t.Fatal("completed preparation retained a gate or operation")+ }+}++func TestCloseCancelsAndDrainsPreparedGoAgentWithoutLatePublication(t *testing.T) {+ host, _ := lifecycleFileHost(t)+ entered, release := make(chan struct{}), make(chan struct{})+ var bound atomic.Int32+ build := host.Build+ host.Build = func(id string, resume bool) (*NativeRuntime, error) {+ runtime, err := build(id, resume)+ runtime.Factory.BeforePublish = func(context.Context, *assembly.NativeLive) error { bound.Add(1); return nil }+ return runtime, err+ }+ finished := make(chan error, 1)+ go func() {+ _, err := host.ActivateWithSetup(t.Context(), "pending", false, func(context.Context, *assembly.NativeLive) error {+ close(entered)+ <-release // Deliberately ignores cancellation; cleanup must wait.+ return nil+ })+ finished <- err+ }()+ <-entered+ released := false+ defer func() {+ if !released {+ close(release)+ }+ }()+ if _, err := host.Activate(t.Context(), "pending", false); !errors.Is(err, ErrHostSessionActive) {+ t.Fatal("duplicate prepared lifetime was admitted", err)+ }+ if err := host.StopSession(t.Context(), "pending"); !errors.Is(err, ErrHostSessionBusy) {+ t.Fatal("unpublished creation exposed an ordinary stop capability", err)+ }+ host.SaveArchive = func(context.Context, string) error { t.Error("archived a pending creation"); return nil }+ if err := host.ArchiveSession(t.Context(), "pending"); !errors.Is(err, ErrHostSessionBusy) {+ t.Fatal("archive did not guard pending creation", err)+ }+ short, cancel := context.WithTimeout(t.Context(), 30*time.Millisecond)+ defer cancel()+ if err := host.Close(short); !errors.Is(err, context.DeadlineExceeded) {+ t.Fatal("close did not honor its cleanup budget", err)+ }+ host.mu.Lock()+ pending := host.operations["pending"] != nil+ host.mu.Unlock()+ if !pending {+ t.Fatal("timed-out close abandoned ownership")+ }+ close(release)+ released = true+ if err := <-finished; !errors.Is(err, context.Canceled) {+ t.Fatal("cancelled setup succeeded", err)+ }+ if bound.Load() != 1 {+ t.Fatal("cancelled setup published extension bindings")+ }+ ctx, stop := context.WithTimeout(t.Context(), time.Second)+ defer stop()+ if err := host.Close(ctx); err != nil {+ t.Fatal(err)+ }+ host.mu.Lock()+ defer host.mu.Unlock()+ if len(host.sessions) != 0 || len(host.operations) != 0 || len(host.historyLocks) != 0 {+ t.Fatal("closed Host retained a prepared lifetime")+ }+}++func TestStoppingAgentCanReenterHostCreationFromItsResourceDisposer(t *testing.T) {+ host, store := lifecycleFileHost(t)+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ build := host.Build+ var callbackErr error+ host.Build = func(id string, resume bool) (*NativeRuntime, error) {+ runtime, err := build(id, resume)+ if id == "first" {+ runtime.Factory.Builder = lifecycleBuilder{nativeRuntimeBuilder{store.ProjectCWD}, func() { _, callbackErr = host.Activate(ctx, "from-disposer", false) }}+ }+ return runtime, err+ }+ if _, err := host.Activate(ctx, "first", false); err != nil {+ t.Fatal(err)+ }+ if err := host.StopSession(ctx, "first"); err != nil {+ t.Fatal(err)+ }+ if callbackErr != nil {+ t.Fatal("disposal reentry failed", callbackErr)+ }+ if _, found := host.Session("from-disposer"); !found {+ t.Fatal("disposer's actual Agent was not published")+ }+}++func TestSchedulePreparationWaitsForTheAlreadyAdmittedGoCreation(t *testing.T) {+ host, _ := lifecycleFileHost(t)+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ entered, release := make(chan struct{}), make(chan struct{})+ activation := make(chan error, 1)+ go func() {+ _, err := host.ActivateWithSetup(ctx, "scheduled", false, func(context.Context, *assembly.NativeLive) error {+ close(entered)+ <-release+ return nil+ })+ activation <- err+ }()+ <-entered+ released := false+ defer func() {+ if !released {+ close(release)+ }+ }()+ prepared := make(chan error, 1)+ go func() { prepared <- host.PrepareSchedule(ctx, "scheduled") }()+ select {+ case err := <-prepared:+ t.Fatal("Schedule did not await the admitted creation", err)+ case <-time.After(20 * time.Millisecond):+ }+ close(release)+ released = true+ if err := <-activation; err != nil {+ t.Fatal(err)+ }+ if err := <-prepared; err != nil {+ t.Fatal("Schedule lost its original destination", err)+ }+}++func TestFailedPreparedAgentCleanupRetainsOwnershipAndRejectsReplacement(t *testing.T) {+ ctx, cancel := context.WithTimeout(t.Context(), time.Second)+ defer cancel()+ setupFailure, cleanupFailure := errors.New("setup failed"), errors.New("cleanup was not confirmed")+ host := &NativeHost{UserID: "cleanup-owner"}+ host.Build = func(id string, _ bool) (*NativeRuntime, error) {+ factory := nativeRuntimeTestFactory(t, &nativeRuntimeStore{}, nativeRuntimeModel{})+ factory.Builder = lifecycleFailureBuilder{nativeRuntimeBuilder{t.TempDir()}, cleanupFailure}+ return &NativeRuntime{Factory: factory, Identity: assembly.NativeRuntimeIdentity{UserID: host.UserID, SessionID: id, Workspace: t.TempDir()}}, nil+ }+ _, err := host.ActivateWithSetup(ctx, "retained", false, func(context.Context, *assembly.NativeLive) error { return setupFailure })+ if !errors.Is(err, setupFailure) || !errors.Is(err, cleanupFailure) {+ t.Fatal("creation concealed a failed rollback", err)+ }+ if _, retained := host.Session("retained"); !retained {+ t.Fatal("failed cleanup lost its owner")+ }+ activity, err := host.Activity()+ if err != nil || activity.Idle {+ t.Fatal("failed cleanup reported idle", err)+ }+ if _, err := host.Activate(ctx, "retained", false); !errors.Is(err, ErrHostSessionActive) {+ t.Fatal("replacement overlapped unconfirmed cleanup", err)+ }+ if err := host.Close(ctx); !errors.Is(err, cleanupFailure) {+ t.Fatal("close reported unconfirmed cleanup as success", err)+ }+ host.mu.Lock()+ defer host.mu.Unlock()+ if host.sessions["retained"] == nil {+ t.Fatal("failed close abandoned ownership")+ }+}diff --git a/internal/hostruntime/native_runtime.go b/internal/hostruntime/native_runtime.goindex 3acef47..76a9cd8 100644--- a/internal/hostruntime/native_runtime.go+++ b/internal/hostruntime/native_runtime.go@@ -60,39 +60,137 @@ type NativeRuntime struct {closeOnce sync.OncecloseError erroractivatedAt time.Time+ startDone chan struct{}+ startCancel context.CancelFunc+ sessionCreation *assembly.NativeSessionOptionstimedQuestions []interaction.PendingtimedQuestionsThrough int64}+type NativeSetup func(context.Context, *assembly.NativeLive) error+func (r *NativeRuntime) Start(ctx context.Context, resume bool) error {+ return r.start(ctx, resume, nil, nil, nil)+}++func (r *NativeRuntime) StartWithSetup(ctx context.Context, resume bool, setup NativeSetup) error {+ return r.start(ctx, resume, nil, nil, setup)+}++func (r *NativeRuntime) start(ctx context.Context, resume bool, sessionReady func(*sessionformat.LiveSession), readable func(*assembly.NativeLive), setup NativeSetup) (err error) {+ ctx, cancel := context.WithCancel(ctx)r.mu.Lock()- defer r.mu.Unlock()- if r.live != nil || r.stopping {+ if r.live != nil || r.stopping || r.startDone != nil {+ r.mu.Unlock()+ cancel()return errors.New("native worker already started")}- var live *assembly.NativeLive- var err error+ r.startDone, r.startCancel = make(chan struct{}), cancel+ r.mu.Unlock()+ var prepared *assembly.NativeLive+ defer func() {+ cancel()+ if err != nil && prepared != nil {+ cleanup := prepared.Close()+ if cleanup != nil && !errors.Is(err, cleanup) {+ err = errors.Join(err, cleanup)+ }+ if cleanup != nil {+ // Retain ownership if cleanup was not confirmed. Host must not+ // permit a second same-id lifetime over these resources.+ r.mu.Lock()+ r.live, r.fatalErr, r.stopping = prepared, err, true+ r.mu.Unlock()+ } else {+ r.mu.Lock()+ if r.live == prepared {+ r.live = nil+ }+ r.mu.Unlock()+ }+ }+ r.mu.Lock()+ r.startCancel = nil+ close(r.startDone)+ r.mu.Unlock()+ }()_, hasChildStorage := r.Factory.Storage.(assembly.NativeChildStorageFactory)r.Factory.Children = nilif hasChildStorage {r.Factory.Children = r}+ factory := r.Factory+ ready := factory.SessionReady+ factory.SessionReady = func(s *sessionformat.LiveSession) {+ if sessionReady != nil {+ sessionReady(s)+ }+ if ready != nil {+ ready(s)+ }+ }+ beforePublish := factory.BeforePublish+ factory.BeforePublish = func(ctx context.Context, live *assembly.NativeLive) error {+ prepared = live+ if readable != nil {+ readable(live)+ }+ if beforePublish != nil {+ if err := beforePublish(ctx, live); err != nil {+ return err+ }+ }+ if setup != nil {+ if err := setup(ctx, live); err != nil {+ return err+ }+ }+ return ctx.Err()+ }+ var live *assembly.NativeLiveif resume {- live, err = r.Factory.Resume(ctx, r.Identity)+ live, err = factory.Resume(ctx, r.Identity)} else {- live, err = r.Factory.Activate(ctx, r.Identity)+ options := r.sessionCreation+ r.sessionCreation = nil+ if options == nil {+ live, err = factory.Activate(ctx, r.Identity)+ } else {+ live, err = factory.ActivateWithSessionOptions(ctx, r.Identity, *options)+ }}if err != nil {return err}+ // Schedule delivery can synchronously reenter admission during Start.+ // It may enqueue into the real Session, but no driver runs until commit.+ r.mu.Lock()+ if err := ctx.Err(); err != nil || r.stopping {+ r.mu.Unlock()+ if err != nil {+ return err+ }+ return context.Canceled+ }r.live = live+ r.mu.Unlock()if r.Factory.Schedule != nil && !r.HostOwnsSchedule {if err := r.Factory.Schedule.Start(ctx); err != nil {- r.live = nil- _ = live.Close()+ r.Factory.Schedule.Close()return fmt.Errorf("start native Schedule: %w", err)}}+ r.mu.Lock()+ if err := ctx.Err(); err != nil || r.stopping {+ r.mu.Unlock()+ if r.Factory.Schedule != nil && !r.HostOwnsSchedule {+ r.Factory.Schedule.Close()+ }+ if err != nil {+ return err+ }+ return context.Canceled+ }r.activatedAt = time.Now().UTC()if hasChildStorage {r.children = newNativeChildManager(r.Factory, r.Identity, live, r.kick)@@ -106,15 +204,15 @@ func (r *NativeRuntime) Start(ctx context.Context, resume bool) error {r.done = make(chan struct{})var runCtx context.ContextrunCtx, r.cancel = context.WithCancel(context.Background())+ r.startCancel = nil // Publication detaches the creation-only signal.go r.drive(runCtx)if live.Resource.Jobs != nil {go r.watchJobs(runCtx, live.Resource.Jobs)}// A resumed journal can have an interrupted turn even with an empty inbox.// Wake once so RunNext repairs that tail before this worker becomes idle.- if resume {- r.kick()- }+ r.kick() // Also observes input accepted by creation listeners before start.+ r.mu.Unlock()return nil}@@ -829,13 +927,63 @@ func (r *NativeRuntime) TerminationError() error {// closes the Session. A caller deadline converts the stop to an abort; the// durable inbox and interrupted-turn repair determine recovery afterward.func (r *NativeRuntime) Stop(ctx context.Context) error {+ // Preparation/setup may call back into other Go services. Never hold the+ // stop or state mutex while waiting for that creation transaction to drain.+ for {+ r.mu.Lock()+ starting := r.startDone+ if starting != nil {+ select {+ case <-starting:+ starting = nil+ default:+ }+ }+ cancel := r.startCancel+ if starting != nil && cancel != nil {+ r.stopping = true+ }+ r.mu.Unlock()+ if starting == nil {+ break+ }+ if cancel != nil {+ cancel()+ }+ select {+ case <-starting:+ case <-ctx.Done():+ r.Abort()+ return ctx.Err()+ }+ }r.stopMu.Lock()- defer r.stopMu.Unlock()r.mu.Lock()+ if r.startDone != nil {+ select {+ case <-r.startDone:+ default:+ r.mu.Unlock()+ r.stopMu.Unlock()+ return r.Stop(ctx) // Start was admitted after the barrier check.+ }+ }+ defer r.stopMu.Unlock()if r.live == nil {+ attempted := r.startDone != nilr.mu.Unlock()+ if attempted {+ return nil // Failed preparation already released its resources.+ }return errors.New("native worker is not started")}+ if r.done == nil {+ live := r.live+ r.stopping = true+ r.mu.Unlock()+ r.closeOnce.Do(func() { r.closeError = live.Close() })+ return r.closeError+ }if !r.stopping {r.stopping = trueif r.live.Questions != nil && r.live.Questions.Disable() && r.activeCancel != nil {@@ -865,15 +1013,44 @@ func (r *NativeRuntime) Stop(ctx context.Context) error {return r.closeError}+// Dispose is factory-owner teardown, rather than the UI's draining Stop.+// Upstream clears a ready machine's inbox on disposal, but failed/unpublished+// creation retains accepted input for recovery. Stop still drains every writer+// and resource; cancellation alone never transfers ownership of them.+func (r *NativeRuntime) Dispose(ctx context.Context) error {+ r.Abort()+ r.mu.Lock()+ live, ready, compactDone := r.live, r.done != nil, r.compactDone+ r.mu.Unlock()+ var err error+ if live != nil && ready {+ err = live.Agent.CancelPending(ctx)+ }+ // A manual compaction runs outside the turn driver. Its cancellation must+ // settle before scoped effects or the Session writer can be closed.+ if compactDone != nil {+ select {+ case <-compactDone:+ case <-ctx.Done():+ return errors.Join(err, ctx.Err())+ }+ }+ return errors.Join(err, r.Stop(ctx))+}+// Abort is for owner loss or process shutdown. It cancels the active turn;// unlike Stop, it does not consume queued user messages before exiting.func (r *NativeRuntime) Abort() {r.mu.Lock()r.stopping = truecancel := r.cancel+ startCancel := r.startCancelcompactCancel := r.compactCancelchildren := r.childrenr.mu.Unlock()+ if startCancel != nil {+ startCancel()+ }if cancel != nil {cancel()}diff --git a/internal/hostruntime/native_schedule_delivery.go b/internal/hostruntime/native_schedule_delivery.goindex e9dd6cb..1dce67a 100644--- a/internal/hostruntime/native_schedule_delivery.go+++ b/internal/hostruntime/native_schedule_delivery.go@@ -31,7 +31,7 @@ func (h *NativeHost) ValidateScheduleDestination(ctx context.Context, id string)}return nil}- artifact, err := h.ReadSession(ctx, id)+ artifact, err := h.SessionArtifact(ctx, id)if err != nil {return err}@@ -53,7 +53,7 @@ func (h *NativeHost) ObserveScheduleExecution(ctx context.Context, receipt sched} else if err != nil {return false, err}- artifact, err := h.ReadSession(ctx, receipt.TargetSessionID)+ artifact, err := h.SessionArtifact(ctx, receipt.TargetSessionID)if err != nil {return false, err}diff --git a/internal/httpapi/chat_transcript.go b/internal/httpapi/chat_transcript.goindex df4ca80..67078f5 100644--- a/internal/httpapi/chat_transcript.go+++ b/internal/httpapi/chat_transcript.go@@ -16,6 +16,7 @@ import ("go-bot/harness/attachments""go-bot/harness/content""go-bot/harness/interaction"+ "go-bot/harness/permission""go-bot/harness/session""go-bot/internal/hostruntime")@@ -248,11 +249,13 @@ func publicChatEvent(event sessionformat.Event) (sessionformat.Event, bool) {}type chatTranscriptPage struct {- Events []sessionformat.Event `json:"events"`- Before *uint64 `json:"before"`- ThroughSeq *uint64 `json:"throughSeq"`- Queue []chatQueueItem `json:"queue"`- Questions []interaction.Pending `json:"questions"`+ Events []sessionformat.Event `json:"events"`+ Before *uint64 `json:"before"`+ ThroughSeq *uint64 `json:"throughSeq"`+ Queue []chatQueueItem `json:"queue"`+ Questions []interaction.Pending `json:"questions"`+ Baseline *agent.NativeAssistantStreamBaseline `json:"baseline,omitempty"`+ Permission *permission.State `json:"permission,omitempty"`}func makeChatTranscript(events []sessionformat.Event, before *uint64, limit int) (chatTranscriptPage, error) {@@ -330,7 +333,17 @@ func serveChatTranscript(w http.ResponseWriter, r *http.Request, events []sessiowriteSessionJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "agent_questions_unavailable"})return}+ baseline, _, unsubscribe, snapshotErr := runtime.SubscribeAssistantStreamSnapshot()+ if snapshotErr != nil {+ writeSessionJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "assistant_stream_unavailable"})+ return+ }+ unsubscribe()+ baseline = publicNativeAssistantBaseline(baseline, true)+ page.Baseline = &baseline}+ state := permission.Read(events)+ page.Permission = &stateif len(page.Questions) == 0 {page.Questions = nil}diff --git a/internal/httpapi/host_stream.go b/internal/httpapi/host_stream.gonew file mode 100644index 0000000..3552dba--- /dev/null+++ b/internal/httpapi/host_stream.go@@ -0,0 +1,438 @@+package httpapi++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "time"++ "github.com/google/uuid"+ "go-bot/harness/permission"+ "go-bot/harness/session"+ "go-bot/internal/hostruntime"+)++// Host events multiplex the existing public chat projection. There is no+// second journal or global sequence: recovery uses each cached Session cursor.+type hostStreamEvent struct {+ SessionID string `json:"sessionId,omitempty"`+ Type string `json:"type"`+ Data any `json:"data"`+}++func streamHostEvents(w http.ResponseWriter, r *http.Request, host *hostruntime.NativeHost) {+ cursors := map[string]*uint64{}+ if raw := r.URL.Query().Get("cursors"); raw != "" {+ if len(raw) > 8192 || json.Unmarshal([]byte(raw), &cursors) != nil || len(cursors) > 20 {+ http.Error(w, "invalid Session cursors", http.StatusBadRequest)+ return+ }+ for id := range cursors {+ if uuid.Validate(id) != nil {+ http.Error(w, "invalid Session cursor ID", http.StatusBadRequest)+ return+ }+ }+ }+ if _, closed := host.StreamSessions(); closed {+ http.Error(w, "Host closed", http.StatusServiceUnavailable)+ return+ }+ if _, ok := w.(http.Flusher); !ok {+ http.Error(w, "stream unavailable", http.StatusServiceUnavailable)+ return+ }+ ctx, cancel := context.WithCancel(r.Context())+ defer cancel()+ defer host.AttachHostStream()()+ w.Header().Set("Content-Type", "text/event-stream")+ w.Header().Set("Cache-Control", "no-cache, no-transform")+ w.Header().Set("X-Accel-Buffering", "no")+ controller := http.NewResponseController(w)+ send := func(event hostStreamEvent) error {+ data, err := json.Marshal(event)+ if err != nil {+ return err+ }+ if _, err = fmt.Fprintf(w, "event: host\ndata: %s\n\n", data); err != nil {+ return err+ }+ return controller.Flush()+ }+ if send(hostStreamEvent{Type: "sessions.changed", Data: struct{}{}}) != nil {+ return+ }+ events := make(chan hostStreamEvent, 64)+ failures := make(chan error, 1)+ // Producers only write to a bounded local channel. One goroutine owns the+ // HTTP writer; cancellation releases producers even when a client is slow.+ emit := func(event hostStreamEvent) error {+ select {+ case events <- event:+ return nil+ case <-ctx.Done():+ return ctx.Err()+ }+ }+ type subscription struct {+ runtime *hostruntime.NativeRuntime+ stop context.CancelFunc+ }+ watching := map[string]subscription{}+ defer func() {+ for _, sub := range watching {+ sub.stop()+ }+ }()+ discover := func() (bool, bool) {+ live, closed := host.StreamSessions()+ changed := false+ for id, runtime := range live {+ if previous, ok := watching[id]; ok {+ if previous.runtime == runtime {+ continue+ }+ previous.stop()+ }+ changed = true+ childCtx, stop := context.WithCancel(ctx)+ watching[id] = subscription{runtime, stop}+ after, replay := cursors[id]+ go func(id string, worker *hostruntime.NativeRuntime, after *uint64, replay bool) {+ err := followHostSession(childCtx, worker, after, replay, func(kind string, data any) error {+ return emit(hostStreamEvent{SessionID: id, Type: kind, Data: data})+ })+ if err != nil && childCtx.Err() == nil {+ select {+ case failures <- err:+ default:+ }+ }+ }(id, runtime, after, replay)+ }+ for id, sub := range watching {+ if _, ok := live[id]; !ok {+ sub.stop()+ delete(watching, id)+ changed = true+ }+ }+ return changed, closed+ }+ if _, closed := discover(); closed {+ return+ }+ // A cached cold Session may have acquired a final result while disconnected.+ // Read only the requested cached journals; do not activate or load all history.+ for id, after := range cursors {+ if _, ok := watching[id]; ok {+ continue+ }+ if host.ReadSession == nil {+ continue+ }+ artifact, err := host.SessionArtifact(ctx, id)+ if err != nil || host.CheckScheduleTarget(ctx, id) != nil {+ if send(hostStreamEvent{SessionID: id, Type: "session.unavailable", Data: struct{}{}}) != nil {+ return+ }+ continue+ }+ for _, event := range artifact.Events {+ if after != nil && event.Seq <= *after {+ continue+ }+ if projected, ok := publicChatEvent(event); ok {+ if send(hostStreamEvent{SessionID: id, Type: "session", Data: projected}) != nil {+ return+ }+ }+ }+ if send(hostStreamEvent{SessionID: id, Type: "questions.state", Data: map[string]any{"questions": coldChatQuestions(artifact.Events)}}) != nil {+ return+ }+ inbox, err := sessionformat.FoldInbox(artifact.Events)+ if err != nil {+ return+ }+ state := permission.Read(artifact.Events)+ for _, event := range []hostStreamEvent{+ {SessionID: id, Type: "session.state", Data: map[string]any{"activeTurn": nil}},+ {SessionID: id, Type: "permissions.state", Data: state},+ {SessionID: id, Type: "queue.state", Data: map[string]any{"queue": chatQueue(inbox)}},+ } {+ if send(event) != nil {+ return+ }+ }+ }+ var scheduleChanged, scheduleDone <-chan struct{}+ var pluginsChanged, pluginsDone <-chan struct{}+ if host.PluginsChanges != nil {+ pluginsChanged, pluginsDone = host.PluginsChanges()+ if send(hostStreamEvent{Type: "extensions.changed", Data: struct{}{}}) != nil {+ return+ }+ }+ var mcpChanged, mcpDone <-chan struct{}+ if host.MCPChanges != nil {+ mcpChanged, mcpDone = host.MCPChanges()+ if host.PluginsChanges == nil && send(hostStreamEvent{Type: "extensions.changed", Data: struct{}{}}) != nil {+ return+ }+ }+ if host.Schedule != nil {+ scheduleChanged, scheduleDone = host.Schedule.Changes()+ }+ if send(hostStreamEvent{Type: "schedule/changed", Data: struct{}{}}) != nil {+ return+ }+ tick := time.NewTicker(500 * time.Millisecond)+ defer tick.Stop()+ heartbeat := time.NewTicker(15 * time.Second)+ defer heartbeat.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-pluginsDone:+ return+ case <-mcpDone:+ return+ case <-mcpChanged:+ mcpChanged, mcpDone = host.MCPChanges()+ if send(hostStreamEvent{Type: "extensions.changed", Data: struct{}{}}) != nil {+ return+ }+ case <-pluginsChanged:+ pluginsChanged, pluginsDone = host.PluginsChanges()+ if send(hostStreamEvent{Type: "extensions.changed", Data: struct{}{}}) != nil {+ return+ }+ case <-failures:+ return // Reconnect resumes from client-owned cursors.+ case <-scheduleDone:+ return+ case <-scheduleChanged:+ scheduleChanged, scheduleDone = host.Schedule.Changes()+ if send(hostStreamEvent{Type: "schedule/changed", Data: struct{}{}}) != nil {+ return+ }+ case event := <-events:+ if send(event) != nil {+ return+ }+ case <-tick.C:+ changed, closed := discover()+ if closed {+ return+ }+ if changed && send(hostStreamEvent{Type: "sessions.changed", Data: struct{}{}}) != nil {+ return+ }+ case <-heartbeat.C:+ if _, err := fmt.Fprint(w, ": heartbeat\n\n"); err != nil || controller.Flush() != nil {+ return+ }+ }+ }+}++func followHostSession(ctx context.Context, worker NativeWorkerHTTPRuntime, after *uint64, replay bool, send func(string, any) error) error {+ baseline, frames, unsubscribe, err := worker.SubscribeAssistantStreamSnapshot()+ if err != nil {+ return err+ }+ defer unsubscribe()+ events, err := worker.DurableSessionEvents()+ if err != nil {+ return err+ }+ inbox, err := sessionformat.FoldInbox(events)+ if err != nil {+ return err+ }+ if after != nil && (len(events) == 0 || *after >= uint64(len(events))) {+ return errors.New("Session cursor is ahead of journal")+ }+ // A Session can produce events between its creation/history response and+ // discovery by this Host stream. With no supplied cursor, overlap the same+ // bounded recent history page as the client; sequence deduplication makes+ // this safe. Never silently skip the first message or tool call.+ var recentStart uint64+ if !replay && len(events) > 0 {+ page, err := makeChatTranscript(events, nil, 20)+ if err != nil {+ return err+ }+ if len(page.Events) > 0 {+ recentStart = page.Events[0].Seq+ }+ }+ if err := send("assistant-stream-baseline", map[string]any{"baseline": publicNativeAssistantBaseline(baseline, true)}); err != nil {+ return err+ }+ var activeTurn *uint64+ for _, event := range events {+ if event.Type == "turn/start" {+ var row struct {+ Turn uint64 `json:"turn"`+ }+ _ = json.Unmarshal(event.Data, &row)+ activeTurn = &row.Turn+ } else if event.Type == "turn/end" {+ activeTurn = nil+ }+ if replay && (after == nil || event.Seq > *after) || !replay && event.Seq >= recentStart {+ if projected, ok := publicChatEvent(event); ok {+ if err := send("session", projected); err != nil {+ return err+ }+ }+ }+ }+ if len(events) > 0 {+ seq := events[len(events)-1].Seq+ after = &seq+ }+ if err := send("session.state", map[string]any{"activeTurn": activeTurn, "throughSeq": after}); err != nil {+ return err+ }+ if err := send("queue.state", map[string]any{"queue": chatQueue(inbox), "throughSeq": after}); err != nil {+ return err+ }+ var previousQuestions string+ var previousPermission permission.State+ syncQuestions := func() error {+ if runtime, ok := worker.(permissionRuntime); ok {+ state, err := runtime.GetPermission()+ if err != nil {+ return err+ }+ if state != previousPermission {+ if err := send("permissions.state", map[string]any{"mode": state.Mode, "approval": state.Approval, "throughSeq": after}); err != nil {+ return err+ }+ previousPermission = state+ }+ }+ questions, err := worker.PendingQuestions()+ if err != nil {+ return err+ }+ data := map[string]any{"questions": questions, "throughSeq": after}+ encoded, err := json.Marshal(data)+ if err != nil {+ return err+ }+ if string(encoded) != previousQuestions {+ if err := send("questions.state", data); err != nil {+ return err+ }+ previousQuestions = string(encoded)+ }+ return nil+ }+ if err := syncQuestions(); err != nil {+ return err+ }+ if err := send("session.cursor", map[string]any{"cursor": after}); err != nil {+ return err+ }+ openAttempts := map[string]int{}+ if active := baseline.ActiveAttempt; active != nil {+ openAttempts[active.AttemptID] = active.NextIndex+ }+ poll := func() error {+ moved, queueDirty := false, false+ for {+ page, err := worker.DurableEventsAfter(after, 200)+ if err != nil {+ return err+ }+ for _, event := range page {+ if ctx.Err() != nil {+ return ctx.Err()+ }+ seq := event.Seq+ after = &seq+ moved = true+ if event.Type == "agent/inbox/spliced" {+ inbox, err = inbox.Next(event)+ if err != nil {+ return err+ }+ queueDirty = true+ }+ if projected, ok := publicChatEvent(event); ok {+ if err := send("session", projected); err != nil {+ return err+ }+ }+ }+ if len(page) < 200 {+ break+ }+ }+ if queueDirty {+ if err := send("queue.state", map[string]any{"queue": chatQueue(inbox), "throughSeq": after}); err != nil {+ return err+ }+ }+ if err := syncQuestions(); err != nil {+ return err+ }+ if moved {+ return send("session.cursor", map[string]any{"cursor": after})+ }+ return nil+ }+ tick := time.NewTicker(500 * time.Millisecond)+ defer tick.Stop()+ for {+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-worker.Done():+ return poll()+ case <-tick.C:+ if err := poll(); err != nil {+ return err+ }+ case frame, ok := <-frames:+ if !ok {+ select {+ case <-worker.Done():+ return poll()+ default:+ }+ return errors.New("assistant stream overflow: reconnect from snapshot")+ }+ switch frame.Type {+ case "start":+ openAttempts[frame.AttemptID] = 0+ case "chunk", "end":+ next, seen := openAttempts[frame.AttemptID]+ if !seen || frame.Index == nil || *frame.Index != next {+ delete(openAttempts, frame.AttemptID)+ continue+ }+ if frame.Type == "end" {+ delete(openAttempts, frame.AttemptID)+ } else {+ openAttempts[frame.AttemptID] = next + 1+ }+ default:+ continue+ }+ if projected, ok := publicNativeAssistantFrame(frame); ok {+ projected.Chunk = chatAssistantChunk(projected.Chunk)+ if err := send("assistant-stream", map[string]any{"frame": projected}); err != nil {+ return err+ }+ }+ }+ }+}diff --git a/internal/httpapi/host_stream_test.go b/internal/httpapi/host_stream_test.gonew file mode 100644index 0000000..ee4c960--- /dev/null+++ b/internal/httpapi/host_stream_test.go@@ -0,0 +1,147 @@+package httpapi++import (+ "bufio"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "go-bot/harness/agent"+ "go-bot/harness/interaction"+ "go-bot/harness/session"+ "go-bot/internal/hostruntime"+)++func TestHostStreamPublishesExtensionInvalidationWithoutASession(t *testing.T) {+ var mu sync.Mutex+ changed := make(chan struct{})+ host := &hostruntime.NativeHost{PluginsChanges: func() (<-chan struct{}, <-chan struct{}) {+ mu.Lock()+ defer mu.Unlock()+ return changed, t.Context().Done()+ }}+ server := httptest.NewServer(NewNativeHostHTTP(host, NativeWorkerHTTPOptions{}))+ defer server.Close()+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ request, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/v1/host/stream", nil)+ response, err := server.Client().Do(request)+ if err != nil {+ t.Fatal(err)+ }+ defer response.Body.Close()+ reader := bufio.NewScanner(response.Body)+ next := func() {+ t.Helper()+ for reader.Scan() {+ data, ok := strings.CutPrefix(reader.Text(), "data: ")+ if !ok {+ continue+ }+ var event hostStreamEvent+ if err := json.Unmarshal([]byte(data), &event); err != nil {+ t.Fatal(err)+ }+ if event.Type != "extensions.changed" {+ continue+ }+ if event.SessionID != "" {+ t.Fatal("extension invalidation was attributed to a chat")+ }+ return+ }+ t.Fatalf("no extension event: %v", reader.Err())+ }+ next()+ mu.Lock()+ old := changed+ changed = make(chan struct{})+ close(old)+ mu.Unlock()+ next()+}++type hostStreamQuestionWorker struct{ *nativeHTTPWorker }++func (*hostStreamQuestionWorker) PendingQuestions() ([]interaction.Pending, error) {+ return []interaction.Pending{{CallID: "pending", Turn: 1, Step: 1, Questions: []interaction.Question{{ID: "choice", Question: "Choose?"}}}}, nil+}++func TestHostSessionFollowerRestoresControlsAndFiltersPrivateContent(t *testing.T) {+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ worker := &hostStreamQuestionWorker{&nativeHTTPWorker{+ events: []sessionformat.Event{+ {Seq: 0, Type: "turn/start", Data: json.RawMessage(`{"turn":1}`)},+ {Seq: 1, Type: "system/message", Data: json.RawMessage(`{"secret":"private-system"}`)},+ {Seq: 2, Type: "turn/end", Data: json.RawMessage(`{"turn":1,"reason":{"kind":"completed"}}`)},+ },+ baseline: agent.NativeAssistantStreamBaseline{Revision: 2, ActiveAttempt: &agent.NativeAssistantStreamAttemptBaseline{+ AttemptID: "active", NextIndex: 1, Stream: []any{map[string]any{"type": "reasoning-chunks", "texts": []any{"private-reasoning"}}},+ }},+ stream: make(chan agent.NativeAssistantStreamFrame), done: make(chan struct{}),+ }}+ type result struct {+ kind string+ data []byte+ }+ output := make(chan result, 16)+ done := make(chan error, 1)+ after := uint64(1)+ go func() {+ done <- followHostSession(ctx, worker, &after, true, func(kind string, data any) error {+ encoded, err := json.Marshal(data)+ if err != nil {+ return err+ }+ output <- result{kind, encoded}+ return nil+ })+ }()+ questions, replay, state := false, false, false+ for {+ select {+ case event := <-output:+ if strings.Contains(string(event.data), "private-") {+ t.Fatalf("private content escaped: %s", event.data)+ }+ switch event.kind {+ case "session":+ replay = strings.Contains(string(event.data), `"seq":2`)+ case "questions.state":+ questions = strings.Contains(string(event.data), `"callId":"pending"`)+ case "session.state":+ state = strings.Contains(string(event.data), `"activeTurn":null`)+ case "session.cursor":+ if !questions || !replay || !state {+ t.Fatalf("incomplete snapshot: questions=%t replay=%t state=%t", questions, replay, state)+ }+ cancel()+ select {+ case <-done:+ return+ case <-time.After(time.Second):+ t.Fatal("follower did not cancel")+ }+ }+ case <-time.After(3 * time.Second):+ t.Fatal("snapshot did not arrive")+ }+ }+}++func TestHostStreamValidatesSessionCursorsBeforeOpeningAudience(t *testing.T) {+ for _, query := range []string{"cursors=broken", "cursors=%7B%22not-a-session%22%3A1%7D", "cursors=%7B%22b231fb9e-976a-42c6-b191-a4bf627c88bd%22%3A-1%7D"} {+ host := &hostruntime.NativeHost{}+ out := httptest.NewRecorder()+ streamHostEvents(out, httptest.NewRequest(http.MethodGet, "/v1/host/stream?"+query, nil), host)+ if out.Code != http.StatusBadRequest {+ t.Fatalf("%s: status %d", query, out.Code)+ }+ }+}diff --git a/internal/httpapi/native_host_http.go b/internal/httpapi/native_host_http.goindex d466966..9c1703b 100644--- a/internal/httpapi/native_host_http.go+++ b/internal/httpapi/native_host_http.go@@ -33,6 +33,10 @@ func NewNativeHostHTTP(host *hostruntime.NativeHost, options NativeWorkerHTTPOptvar historyCache coldHistoryCachepublicHandlers := make(map[string]cached)return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == http.MethodGet && r.URL.Path == "/v1/host/stream" {+ streamHostEvents(w, r, host)+ return+ }if r.Method == http.MethodGet && r.URL.Path == "/v1/host/files" {serveHostFiles(w, r, options.HostFilesRoot)return@@ -136,7 +140,10 @@ func NewNativeHostHTTP(host *hostruntime.NativeHost, options NativeWorkerHTTPOptreturn}}- if err != nil && !errors.Is(err, hostruntime.ErrHostSessionActive) {+ if errors.Is(err, hostruntime.ErrHostSessionActive) {+ _, err = host.AwaitSession(r.Context(), request.SessionID)+ }+ if err != nil {http.Error(w, "Session creation failed", http.StatusServiceUnavailable)return}@@ -371,10 +378,7 @@ func NewNativeHostHTTP(host *hostruntime.NativeHost, options NativeWorkerHTTPOptvar err errorruntime, err = host.Activate(r.Context(), id, true)if errors.Is(err, hostruntime.ErrHostSessionActive) {- runtime, ok = host.Session(id)- if ok {- err = nil- }+ runtime, err = host.AwaitSession(r.Context(), id)}if errors.Is(err, os.ErrNotExist) || errors.Is(err, hostruntime.ErrHostSessionArchived) {http.NotFound(w, r)diff --git a/internal/httpapi/native_host_http_test.go b/internal/httpapi/native_host_http_test.goindex bec204f..7c7781b 100644--- a/internal/httpapi/native_host_http_test.go+++ b/internal/httpapi/native_host_http_test.go@@ -22,6 +22,46 @@ import ("github.com/google/uuid")+func TestRetriedCreateDoesNotReturnCreatedBeforeAdmittedCreationFails(t *testing.T) {+ entered, release := make(chan struct{}), make(chan struct{})+ defer func() {+ select {+ case <-release:+ default:+ close(release)+ }+ }()+ host := &hostruntime.NativeHost{UserID: "retry-test", Build: func(string, bool) (*hostruntime.NativeRuntime, error) {+ close(entered)+ <-release+ return nil, errors.New("preparation failed")+ }}+ handler := NewNativeHostHTTP(host, NativeWorkerHTTPOptions{})+ id := uuid.NewString()+ call := func(output chan<- int) {+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ out := httptest.NewRecorder()+ handler.ServeHTTP(out, httptest.NewRequest(http.MethodPost, "/internal/host/sessions", strings.NewReader(`{"sessionId":"`+id+`"}`)).WithContext(ctx))+ output <- out.Code+ }+ first, second := make(chan int, 1), make(chan int, 1)+ go call(first)+ <-entered+ go call(second)+ select {+ case status := <-second:+ t.Fatal("retry returned before the actual creation settled", status)+ case <-time.After(20 * time.Millisecond):+ }+ close(release)+ for _, result := range []<-chan int{first, second} {+ if status := <-result; status != http.StatusServiceUnavailable {+ t.Fatal("failed creation reported success", status)+ }+ }+}+func TestHostFilesListsColdWorkspacesAndRejectsPathsOutsideRoot(t *testing.T) {root := t.TempDir()workspace := filepath.Join(root, "workspaces", "cold-session")diff --git a/internal/httpapi/session_attachment.go b/internal/httpapi/session_attachment.goindex 045e69c..20d01ec 100644--- a/internal/httpapi/session_attachment.go+++ b/internal/httpapi/session_attachment.go@@ -92,7 +92,7 @@ func sessionAttachmentReference(ctx context.Context, host *hostruntime.NativeHosif host.ReadSession == nil {return sessionAttachment{}, false, nil}- artifact, err := host.ReadSession(ctx, sessionID)+ artifact, err := host.SessionArtifact(ctx, sessionID)if errors.Is(err, os.ErrNotExist) {return sessionAttachment{}, false, nil}diff --git a/internal/httpapi/session_history_http.go b/internal/httpapi/session_history_http.goindex b922b79..2181c4d 100644--- a/internal/httpapi/session_history_http.go+++ b/internal/httpapi/session_history_http.go@@ -70,14 +70,14 @@ func sameHistoryVersion(a, b os.FileInfo) bool {func (c *coldHistoryCache) load(ctx context.Context, host *hostruntime.NativeHost, id string) (sessionformat.PhysicalArtifact, error) {if host.SessionLogInfo == nil {- return host.ReadSession(ctx, id)+ return host.SessionArtifact(ctx, id)}version, err := host.SessionLogInfo(id)if err != nil {return sessionformat.PhysicalArtifact{}, err}if version.Size() > maxCachedHistoryBytes {- return host.ReadSession(ctx, id)+ return host.SessionArtifact(ctx, id)}c.mu.Lock()if c.id == id && sameHistoryVersion(c.version, version) {@@ -86,7 +86,7 @@ func (c *coldHistoryCache) load(ctx context.Context, host *hostruntime.NativeHosreturn artifact, nil}c.mu.Unlock()- artifact, err := host.ReadSession(ctx, id)+ artifact, err := host.SessionArtifact(ctx, id)if err != nil {return sessionformat.PhysicalArtifact{}, err}diff --git a/internal/mcpclient/connection.go b/internal/mcpclient/connection.gonew file mode 100644index 0000000..b64090f--- /dev/null+++ b/internal/mcpclient/connection.go@@ -0,0 +1,342 @@+package mcpclient++import (+ "context"+ "errors"+ "io"+ "log/slog"+ "net/http"+ "net/url"+ "os"+ "os/exec"+ "strings"+ "sync"+ "sync/atomic"+ "syscall"+ "time"++ "github.com/modelcontextprotocol/go-sdk/auth"+ "github.com/modelcontextprotocol/go-sdk/jsonrpc"+ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ mcpconfig "go-bot/mcp"+ "golang.org/x/oauth2"+)++const RequestTimeout = 60 * time.Second+const CloseTimeout = 5 * time.Second++type Error struct {+ Code, Message, AuthorizationReason string+ // Keep protocol error identity for lifecycle decisions without exposing+ // the provider's raw response through public error serialization.+ Cause error `json:"-"`+}++func (e *Error) Error() string { return e.Message }+func (e *Error) Unwrap() error { return e.Cause }+func (e *Error) ToolErrorInfo() (string, string) { return "McpError", e.Code }+func fail(code, message string) error { return &Error{Code: code, Message: message} }+func authorizationFailure(reason, message string) error {+ return &Error{Code: "MCP_AUTHORIZATION_REQUIRED", Message: message, AuthorizationReason: reason}+}++type ConnectionOptions struct {+ // Transport is an in-process test/embedding seam. Deployments use the+ // validated stdio or HTTP configuration, never an extra public listener.+ Transport sdk.Transport+ HTTPClient *http.Client+ Secrets []string+ OAuth auth.OAuthHandler+ StartupTimeout time.Duration+ // Internal observation of failed negotiation cleanup for one-shot probes.+ connectCleanup func(error)+}++type Connection struct {+ Session *sdk.ClientSession+ Name string+ Changes chan struct{}+ ctx context.Context+ cancel context.CancelFunc+ command *exec.Cmd+ secrets []string+ secretsMu sync.RWMutex+ closeOnce sync.Once+ closeDone chan struct{}+ closeErr error+ idle func()+ needsAuthorization atomic.Bool+ authorizationError atomic.Pointer[Error]+}++func (c *Connection) redact(message string) string {+ c.secretsMu.RLock()+ defer c.secretsMu.RUnlock()+ for _, secret := range c.secrets {+ if secret != "" {+ message = strings.ReplaceAll(message, secret, "[redacted]")+ }+ }+ if len(message) > 4096 {+ message = message[:4096] + "…"+ }+ return message+}++func (c *Connection) rememberOAuthToken(token *oauth2.Token) {+ if token == nil {+ return+ }+ c.secretsMu.Lock()+ defer c.secretsMu.Unlock()+ for _, value := range []string{token.AccessToken, token.RefreshToken} {+ if value == "" {+ continue+ }+ found := false+ for _, previous := range c.secrets {+ found = found || previous == value+ }+ if !found {+ c.secrets = append(c.secrets, value)+ }+ }+}++func (c *Connection) requestError(ctx context.Context, err error) error {+ if c.needsAuthorization.Load() {+ return c.authorizationFailure()+ }+ if ctx.Err() != nil {+ return ctx.Err()+ }+ if c.ctx.Err() != nil || errors.Is(err, sdk.ErrConnectionClosed) {+ return fail("MCP_SERVER_UNAVAILABLE", "MCP server is disconnected")+ }+ if errors.Is(err, context.DeadlineExceeded) {+ return fail("MCP_REQUEST_TIMEOUT", "MCP request timed out")+ }+ var protocol *jsonrpc.Error+ if errors.As(err, &protocol) {+ return fail("MCP_PROTOCOL_ERROR", c.redact(err.Error()))+ }+ return fail("MCP_REQUEST_FAILED", c.redact(err.Error()))+}++type trackedTransport struct {+ base sdk.Transport+ connection sdk.Connection+}++func (t *trackedTransport) Connect(ctx context.Context) (sdk.Connection, error) {+ connection, err := t.base.Connect(ctx)+ t.connection = connection+ return connection, err+}++// Connect initializes a real SDK session before returning. Cancelling an+// initialization cannot leave a child or half-open transport behind. The+// returned connection outlives this management request and is closed by Host.+func Connect(ctx context.Context, name string, config mcpconfig.Server, options ConnectionOptions) (*Connection, error) {+ if !mcpconfig.ValidServerName(name) {+ return nil, fail("MCP_INVALID_CONFIG", "Invalid configured MCP server name")+ }+ if err := config.Validate(); err != nil {+ return nil, err+ }+ if config.OAuth != nil && options.OAuth == nil {+ return nil, authorizationFailure("missing", "MCP server requires an explicit OAuth connection")+ }+ lifetime, cancel := context.WithCancel(context.WithoutCancel(ctx))+ c := &Connection{Name: name, Changes: make(chan struct{}, 1), ctx: lifetime, cancel: cancel, secrets: append([]string(nil), options.Secrets...), closeDone: make(chan struct{})}+ c.secrets = append(c.secrets, config.SecretValues()...)+ if options.OAuth != nil {+ options.OAuth = &observedOAuthHandler{base: options.OAuth, issued: c.rememberOAuthToken, required: func(err error) {+ var detail *Error+ if errors.As(err, &detail) {+ c.authorizationError.Store(detail)+ }+ c.needsAuthorization.Store(true)+ c.cancel()+ }}+ }+ var transport sdk.Transport = options.Transport+ if transport == nil {+ switch config.Transport {+ case "stdio":+ command := exec.Command(config.Command, config.Args...)+ command.Dir = config.CWD+ command.Env = processEnvironment(config.Env)+ command.Stderr = io.Discard+ command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}+ c.command = command+ transport = &sdk.CommandTransport{Command: command, TerminateDuration: time.Second}+ case "streamable-http":+ base := http.DefaultTransport.(*http.Transport).Clone()+ c.idle = base.CloseIdleConnections+ client := &http.Client{Transport: base}+ if options.HTTPClient != nil {+ copy := *options.HTTPClient+ client = ©+ }+ if client.Transport == nil {+ client.Transport = base+ }+ endpoint, _ := url.Parse(config.URL)+ client.Transport = &headerTransport{base: client.Transport, origin: endpoint, headers: config.Headers}+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }+ client.Timeout = 0 // Per-call contexts bound requests; notification streams remain live.+ transport = &sdk.StreamableClientTransport{Endpoint: config.URL, HTTPClient: client, OAuthHandler: options.OAuth, MaxRetries: -1, MaxEventSize: 8 << 20}+ }+ }+ tracked := &trackedTransport{base: transport}+ changed := func() {+ select {+ case c.Changes <- struct{}{}:+ default:+ }+ }+ client := sdk.NewClient(&sdk.Implementation{Name: "go-bot", Version: "0.0.1"}, &sdk.ClientOptions{+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ Capabilities: &sdk.ClientCapabilities{},+ ToolListChangedHandler: func(context.Context, *sdk.ToolListChangedRequest) { changed() },+ ResourceListChangedHandler: func(context.Context, *sdk.ResourceListChangedRequest) { changed() },+ })+ budget := options.StartupTimeout+ if budget <= 0 {+ budget = RequestTimeout+ }+ startup, stop := context.WithTimeout(ctx, budget)+ defer stop()+ session, err := client.Connect(startup, tracked, nil)+ if err != nil {+ cancel()+ // Connect may fail after a transport starts but before returning its+ // ClientSession. Track that transport so this branch also owns cleanup.+ var cleanupErr error+ if tracked.connection != nil {+ cleanupErr = tracked.connection.Close()+ }+ c.killGroup()+ if c.idle != nil {+ c.idle()+ }+ if options.connectCleanup != nil {+ options.connectCleanup(cleanupErr)+ }+ var authorization *Error+ if c.needsAuthorization.Load() {+ return nil, c.authorizationFailure()+ }+ if errors.As(err, &authorization) && authorization.Code == "MCP_AUTHORIZATION_REQUIRED" {+ return nil, authorization+ }+ return nil, &Error{Code: "MCP_CONNECT_FAILED", Message: c.redact(err.Error()), Cause: err}+ }+ c.Session = session+ go func() { _ = session.Wait(); c.cancel() }()+ return c, nil+}++func processEnvironment(extra map[string]string) []string {+ var environment []string+ for _, key := range []string{"PATH", "HOME", "LANG", "LC_ALL", "TZ", "TMPDIR", "DSH_HOME", "DSH_AGENTS_HOME", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS"} {+ if value, ok := os.LookupEnv(key); ok {+ environment = append(environment, key+"="+value)+ }+ }+ for key, value := range extra {+ environment = append(environment, key+"="+value)+ }+ return environment+}++type headerTransport struct {+ base http.RoundTripper+ origin *url.URL+ headers map[string]string+}++func (t *headerTransport) RoundTrip(request *http.Request) (*http.Response, error) {+ if !strings.EqualFold(request.URL.Host, t.origin.Host) || request.URL.Scheme != t.origin.Scheme {+ return nil, errors.New("MCP transport refused an unexpected origin")+ }+ copy := request.Clone(request.Context())+ copy.Header = request.Header.Clone()+ for key, value := range t.headers {+ copy.Header.Set(key, value)+ }+ return t.base.RoundTrip(copy)+}++func (c *Connection) killGroup() {+ if c.command != nil && c.command.Process != nil {+ _ = syscall.Kill(-c.command.Process.Pid, syscall.SIGKILL)+ }+}++// A cleanup timeout remains an error. Callers must keep the server namespace+// reserved until Closed fires instead of overlapping another process.+func (c *Connection) Close() error {+ c.closeOnce.Do(func() {+ c.cancel()+ go func() {+ c.closeErr = c.Session.Close()+ // OAuth expiry can prevent the best-effort remote session DELETE.+ // A completed local HTTP transport close still releases our client;+ // it must not prevent deleting the local grant and reconnecting.+ if c.command == nil && (authorizationRequired(c.closeErr) || errors.Is(c.closeErr, context.Canceled)) {+ c.closeErr = nil+ }+ // CommandTransport terminates a child that does not exit after stdin+ // closes. Completed intentional cleanup is not a failed connection.+ var exit *exec.ExitError+ if c.command != nil && errors.As(c.closeErr, &exit) {+ if status, ok := exit.Sys().(syscall.WaitStatus); ok && status.Signaled() && (status.Signal() == syscall.SIGTERM || status.Signal() == syscall.SIGKILL) {+ c.closeErr = nil+ }+ }+ c.killGroup()+ if c.idle != nil {+ c.idle()+ }+ close(c.closeDone)+ }()+ })+ timer := time.NewTimer(CloseTimeout)+ defer timer.Stop()+ select {+ case <-c.closeDone:+ if c.closeErr != nil {+ return fail("MCP_CLEANUP_FAILED", c.redact(c.closeErr.Error()))+ }+ return nil+ case <-timer.C:+ c.killGroup()+ return fail("MCP_CLEANUP_TIMEOUT", "MCP connection cleanup has not finished")+ }+}+func (c *Connection) Closed() <-chan struct{} { return c.closeDone }+func (c *Connection) Disconnected() <-chan struct{} { return c.ctx.Done() }++func (c *Connection) request(ctx context.Context) (context.Context, func()) {+ ctx, cancel := context.WithTimeout(ctx, RequestTimeout)+ stop := context.AfterFunc(c.ctx, cancel)+ if c.ctx.Err() != nil {+ cancel()+ }+ return ctx, func() { stop(); cancel() }+}++func (c *Connection) Call(ctx context.Context, name string, arguments any) (*sdk.CallToolResult, error) {+ if c.ctx.Err() != nil {+ return nil, fail("MCP_SERVER_UNAVAILABLE", "MCP server is disconnected")+ }+ call, done := c.request(ctx)+ defer done()+ result, err := c.Session.CallTool(call, &sdk.CallToolParams{Name: name, Arguments: arguments})+ if err != nil {+ return nil, c.requestError(ctx, err)+ }+ return result, nil+}diff --git a/internal/mcpclient/connection_test.go b/internal/mcpclient/connection_test.gonew file mode 100644index 0000000..5a1bce5--- /dev/null+++ b/internal/mcpclient/connection_test.go@@ -0,0 +1,170 @@+package mcpclient++import (+ "context"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ mcpconfig "go-bot/mcp"+)++func testServer() *sdk.Server {+ server := sdk.NewServer(&sdk.Implementation{Name: "remote-name-is-not-our-namespace", Version: "1.0.0"}, &sdk.ServerOptions{PageSize: 1, Instructions: "Literal server instruction: {{not_a_template}}"})+ for _, name := range []string{"one", "two"} {+ server.AddTool(&sdk.Tool{Name: name, Description: "A fixture tool", InputSchema: map[string]any{"type": "object"}}, func(_ context.Context, request *sdk.CallToolRequest) (*sdk.CallToolResult, error) {+ return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: request.Params.Name}}}, nil+ })+ }+ for _, name := range []string{"one", "two"} {+ server.AddResource(&sdk.Resource{Name: name, URI: "memo://" + name}, func(_ context.Context, request *sdk.ReadResourceRequest) (*sdk.ReadResourceResult, error) {+ return &sdk.ReadResourceResult{Contents: []*sdk.ResourceContents{{URI: request.Params.URI, MIMEType: "text/plain", Text: "resource content"}}}, nil+ })+ }+ server.AddResourceTemplate(&sdk.ResourceTemplate{Name: "memo", URITemplate: "memo://{name}"}, func(_ context.Context, request *sdk.ReadResourceRequest) (*sdk.ReadResourceResult, error) {+ return &sdk.ReadResourceResult{Contents: []*sdk.ResourceContents{{URI: request.Params.URI, Text: "template content"}}}, nil+ })+ return server+}++func TestMCPHTTPDiscoversEveryPageCallsRawNamesAndReadsResources(t *testing.T) {+ server := testServer()+ handler := sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil)+ var authenticated atomic.Int32+ httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "Bearer fixture-private" {+ t.Error("configured credential was not supplied")+ w.WriteHeader(401)+ return+ }+ authenticated.Add(1)+ handler.ServeHTTP(w, r)+ }))+ t.Cleanup(httpServer.Close)+ connection, err := Connect(t.Context(), "local_namespace", mcpconfig.Server{Transport: "streamable-http", URL: httpServer.URL, Headers: map[string]string{"Authorization": "Bearer fixture-private"}}, ConnectionOptions{Secrets: []string{"fixture-private"}})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = connection.Close() })+ discovery, err := connection.Discover(t.Context())+ if err != nil || len(discovery.Tools) != 2 || !discovery.Resources || !strings.Contains(discovery.Instructions, "{{not_a_template}}") {+ t.Fatalf("discovery=%+v err=%v", discovery, err)+ }+ for _, tool := range discovery.Tools {+ if tool.PublicName != "mcp__local_namespace__"+tool.RawName {+ t.Fatal("remote implementation name replaced local namespace")+ }+ }+ result, err := connection.Call(t.Context(), discovery.Tools[0].RawName, map[string]any{})+ if err != nil || result.Content[0].(*sdk.TextContent).Text != discovery.Tools[0].RawName {+ t.Fatalf("result=%+v err=%v", result, err)+ }+ resources, err := connection.Resources(t.Context())+ if err != nil || len(resources) != 2 {+ t.Fatalf("resources=%+v err=%v", resources, err)+ }+ templates, err := connection.ResourceTemplates(t.Context())+ if err != nil || len(templates) != 1 {+ t.Fatalf("templates=%+v err=%v", templates, err)+ }+ read, err := connection.ReadResource(t.Context(), "memo://one")+ if err != nil || len(read.Contents) != 1 || read.Contents[0].Text != "resource content" {+ t.Fatalf("read=%+v err=%v", read, err)+ }+ if authenticated.Load() < 5 {+ t.Fatal("test did not exercise real HTTP MCP requests")+ }+ for {+ select {+ case <-connection.Changes:+ continue+ default:+ goto drained+ }+ }+drained:+ server.AddTool(&sdk.Tool{Name: "three", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {+ return &sdk.CallToolResult{}, nil+ })+ select {+ case <-connection.Changes:+ case <-time.After(3 * time.Second):+ t.Fatal("tool-list notification was not delivered")+ }+ updated, err := connection.Discover(t.Context())+ if err != nil || len(updated.Tools) != 3 {+ t.Fatalf("updated=%+v err=%v", updated, err)+ }+}++func TestMCPDoesNotForwardConfiguredHeadersAcrossRedirects(t *testing.T) {+ var reached atomic.Bool+ other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached.Store(true); w.WriteHeader(500) }))+ defer other.Close()+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, other.URL, http.StatusTemporaryRedirect)+ }))+ defer origin.Close()+ connection, err := Connect(t.Context(), "redirect", mcpconfig.Server{Transport: "streamable-http", URL: origin.URL, Headers: map[string]string{"X-Key": "fixture-secret"}}, ConnectionOptions{Secrets: []string{"fixture-secret"}})+ if connection != nil {+ _ = connection.Close()+ }+ if err == nil || reached.Load() {+ t.Fatalf("redirect was followed: reached=%v err=%v", reached.Load(), err)+ }+ if strings.Contains(err.Error(), "fixture-secret") {+ t.Fatal("transport error exposed a configured credential")+ }+}++func TestMCPStdioFixture(t *testing.T) {+ if os.Getenv("GO_BOT_MCP_STDIO_FIXTURE") != "1" {+ return+ }+ if os.Getenv("MODEL_API_KEY") != "" {+ os.Exit(3)+ }+ if err := testServer().Run(context.Background(), &sdk.StdioTransport{}); err != nil {+ os.Exit(2)+ }+ os.Exit(0)+}++func TestMCPStdioUsesSeparateArgumentsAndMinimalEnvironment(t *testing.T) {+ t.Setenv("MODEL_API_KEY", "must-not-be-inherited")+ connection, err := Connect(t.Context(), "stdio", mcpconfig.Server{Transport: "stdio", Command: os.Args[0], Args: []string{"-test.run=^TestMCPStdioFixture$"}, Env: map[string]string{"GO_BOT_MCP_STDIO_FIXTURE": "1"}, CWD: t.TempDir()}, ConnectionOptions{})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = connection.Close() })+ discovery, err := connection.Discover(t.Context())+ if err != nil || len(discovery.Tools) != 2 {+ t.Fatalf("discovery=%+v err=%v", discovery, err)+ }+ if err = connection.Close(); err != nil {+ t.Fatal(err)+ }+ if _, err = connection.Call(t.Context(), "one", map[string]any{}); err == nil {+ t.Fatal("closed subprocess remained callable")+ }+}++func TestMCPNameNormalizationMatchesUpstreamJavaScript(t *testing.T) {+ for _, tc := range []struct{ raw, want string }{+ {"search", "mcp__github__search"},+ {"a.b", "mcp__github__a_b_531a020b8a5f"},+ {"a/b", "mcp__github__a_b_b36899572871"},+ {"天气", "mcp__github_____cc803593d7fc"},+ {"📄", "mcp__github_____7a12b78977cb"},+ {strings.Repeat("x", 100), "mcp__github__xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_3accac3b9402"},+ } {+ if got := PublicToolName("github", tc.raw); got != tc.want {+ t.Errorf("%q: got %q want %q", tc.raw, got, tc.want)+ }+ }+}diff --git a/internal/mcpclient/discovery.go b/internal/mcpclient/discovery.gonew file mode 100644index 0000000..e6d8c3f--- /dev/null+++ b/internal/mcpclient/discovery.go@@ -0,0 +1,179 @@+package mcpclient++import (+ "context"+ "encoding/json"+ "fmt"+ "unicode/utf8"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/santhosh-tekuri/jsonschema/v6"+)++type ToolDefinition struct {+ PublicName string+ RawName string+ Description string+ InputSchema json.RawMessage+ OutputSchema json.RawMessage+ input *jsonschema.Schema+ output *jsonschema.Schema+}++type Discovery struct {+ Tools []ToolDefinition+ Instructions string+ Resources bool+ ServerInfo *sdk.Implementation+ ProtocolVersion string+}++type denyLoader struct{}++func (denyLoader) Load(url string) (any, error) {+ return nil, fmt.Errorf("external MCP schema references are not supported: %s", url)+}++func compileSchema(value any) (json.RawMessage, *jsonschema.Schema, error) {+ data, err := json.Marshal(value)+ if err != nil {+ return nil, nil, err+ }+ if len(data) > 1<<20 {+ return nil, nil, fail("MCP_INVALID_SCHEMA", "MCP tool schema exceeds 1 MiB")+ }+ c := jsonschema.NewCompiler()+ c.DefaultDraft(jsonschema.Draft2020)+ c.UseLoader(denyLoader{})+ const location = "https://go-bot.invalid/mcp-schema.json"+ if err = c.AddResource(location, value); err != nil {+ return nil, nil, err+ }+ schema, err := c.Compile(location)+ return data, schema, err+}++func collectPages[T any](fetch func(string) ([]T, string, error)) ([]T, error) {+ all := []T{}+ cursor := ""+ seen := map[string]bool{}+ for {+ if seen[cursor] {+ return nil, fail("MCP_INVALID_LIST", "MCP server repeated a pagination cursor")+ }+ seen[cursor] = true+ rows, next, err := fetch(cursor)+ if err != nil {+ return nil, err+ }+ if len(all)+len(rows) > 10000 {+ return nil, fail("MCP_LIST_LIMIT", "MCP discovery exceeds 10000 items")+ }+ all = append(all, rows...)+ if next == "" {+ return all, nil+ }+ cursor = next+ }+}++// Discover constructs and validates the entire next definition set. It never+// publishes part of a failed list or mutates an earlier generation.+func (c *Connection) Discover(ctx context.Context) (Discovery, error) {+ call, done := c.request(ctx)+ defer done()+ info := c.Session.InitializeResult()+ result := Discovery{Tools: []ToolDefinition{}, Instructions: info.Instructions, ServerInfo: info.ServerInfo, ProtocolVersion: info.ProtocolVersion, Resources: info.Capabilities != nil && info.Capabilities.Resources != nil}+ if len(result.Instructions) > 32<<10 {+ result.Instructions = result.Instructions[:32<<10]+ for !utf8.ValidString(result.Instructions) {+ result.Instructions = result.Instructions[:len(result.Instructions)-1]+ }+ }+ if info.Capabilities == nil || info.Capabilities.Tools == nil {+ return result, nil+ }+ tools, err := collectPages(func(cursor string) ([]*sdk.Tool, string, error) {+ page, err := c.Session.ListTools(call, &sdk.ListToolsParams{Cursor: cursor})+ if err != nil {+ return nil, "", err+ }+ return page.Tools, page.NextCursor, nil+ })+ if err != nil {+ return Discovery{}, c.requestError(ctx, err)+ }+ names := map[string]bool{}+ for _, tool := range tools {+ if tool == nil || tool.Name == "" {+ return Discovery{}, fail("MCP_INVALID_LIST", "MCP server returned an unnamed tool")+ }+ public := PublicToolName(c.Name, tool.Name)+ if names[public] {+ return Discovery{}, fail("MCP_INVALID_LIST", "MCP server returned duplicate tool identities")+ }+ names[public] = true+ input, inputCheck, err := compileSchema(tool.InputSchema)+ if err != nil {+ return Discovery{}, fail("MCP_INVALID_SCHEMA", c.redact(err.Error()))+ }+ var object map[string]any+ if json.Unmarshal(input, &object) != nil || object["type"] != "object" {+ return Discovery{}, fail("MCP_INVALID_SCHEMA", "MCP tool parameters must have an object root")+ }+ definition := ToolDefinition{PublicName: public, RawName: tool.Name, Description: tool.Description, InputSchema: input, input: inputCheck}+ if tool.OutputSchema != nil {+ definition.OutputSchema, definition.output, err = compileSchema(tool.OutputSchema)+ if err != nil {+ return Discovery{}, fail("MCP_INVALID_SCHEMA", c.redact(err.Error()))+ }+ }+ result.Tools = append(result.Tools, definition)+ }+ return result, nil+}++func (c *Connection) Resources(ctx context.Context) ([]*sdk.Resource, error) {+ call, done := c.request(ctx)+ defer done()+ rows, err := collectPages(func(cursor string) ([]*sdk.Resource, string, error) {+ page, err := c.Session.ListResources(call, &sdk.ListResourcesParams{Cursor: cursor})+ if err != nil {+ return nil, "", err+ }+ return page.Resources, page.NextCursor, nil+ })+ if err != nil {+ return nil, c.requestError(ctx, err)+ }+ return rows, nil+}++func (c *Connection) ResourceTemplates(ctx context.Context) ([]*sdk.ResourceTemplate, error) {+ call, done := c.request(ctx)+ defer done()+ rows, err := collectPages(func(cursor string) ([]*sdk.ResourceTemplate, string, error) {+ page, err := c.Session.ListResourceTemplates(call, &sdk.ListResourceTemplatesParams{Cursor: cursor})+ if err != nil {+ return nil, "", err+ }+ return page.ResourceTemplates, page.NextCursor, nil+ })+ if err != nil {+ return nil, c.requestError(ctx, err)+ }+ return rows, nil+}++func (c *Connection) ReadResource(ctx context.Context, uri string) (*sdk.ReadResourceResult, error) {+ if uri == "" || len(uri) > 16384 {+ return nil, fail("MCP_INVALID_RESOURCE", "Enter an MCP resource URI")+ }+ call, done := c.request(ctx)+ defer done()+ result, err := c.Session.ReadResource(call, &sdk.ReadResourceParams{URI: uri})+ if err != nil {+ return nil, c.requestError(ctx, err)+ }+ return result, nil+}diff --git a/internal/mcpclient/http.go b/internal/mcpclient/http.gonew file mode 100644index 0000000..862b011--- /dev/null+++ b/internal/mcpclient/http.go@@ -0,0 +1,121 @@+package mcpclient++import (+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "strings"++ mcpconfig "go-bot/mcp"+)++// Handler is private Host control, protected by the existing Host token.+func (m *Manager) Handler() http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ write := func(code int, value any) {+ w.Header().Set("Content-Type", "application/json")+ w.Header().Set("Cache-Control", "no-store")+ w.WriteHeader(code)+ _ = json.NewEncoder(w).Encode(value)+ }+ failure := func(err error) {+ write(http.StatusUnprocessableEntity, map[string]any{"error": "mcp_operation_failed", "message": m.redact(err.Error()), "status": m.Status()})+ }+ suffix := strings.TrimPrefix(r.URL.Path, mcpconfig.InternalPath)+ decode := func(value any) bool {+ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))+ decoder.DisallowUnknownFields()+ if decoder.Decode(value) != nil || !errors.Is(decoder.Decode(new(any)), io.EOF) {+ write(400, map[string]string{"error": "invalid_mcp_request"})+ return false+ }+ return true+ }+ switch {+ case suffix == "/oauth/callback" && r.Method == http.MethodPost:+ var input mcpconfig.OAuthCallback+ if !decode(&input) {+ return+ }+ view, err := m.ReceiveAuthorization(input)+ if err != nil {+ failure(err)+ return+ }+ write(200, view)+ case suffix == "" && r.Method == http.MethodGet:+ write(http.StatusOK, m.Status())+ case (r.Method == http.MethodPost || r.Method == http.MethodDelete) && strings.HasPrefix(suffix, "/servers/"):+ name, action, found := strings.Cut(strings.TrimPrefix(suffix, "/servers/"), "/")+ if !mcpconfig.ValidServerName(name) {+ write(http.StatusBadRequest, map[string]string{"error": "invalid_mcp_server"})+ return+ }+ if !found {+ http.NotFound(w, r)+ return+ }+ if r.Method == http.MethodDelete {+ var status mcpconfig.Status+ var err error+ switch action {+ case "authorization":+ if id := r.URL.Query().Get("id"); id != "" {+ err = m.CancelAuthorizationAttempt(r.Context(), name, id)+ status = m.Status()+ } else {+ status, err = m.CancelAuthorization(r.Context(), name)+ }+ case "grant":+ status, err = m.DisconnectAuthorization(r.Context(), name)+ default:+ http.NotFound(w, r)+ return+ }+ if err != nil {+ failure(err)+ return+ }+ write(200, status)+ return+ }+ if action == "authorize" {+ var input struct {+ RedirectURL string `json:"redirectUrl"`+ }+ if !decode(&input) {+ return+ }+ view, err := m.Authorize(r.Context(), name, input.RedirectURL)+ if err != nil {+ failure(err)+ return+ }+ write(200, view)+ return+ }+ if action != "restart" && action != "probe" {+ http.NotFound(w, r)+ return+ }+ if action == "probe" {+ result, err := m.Probe(r.Context(), name)+ if err != nil {+ failure(err)+ return+ }+ write(http.StatusOK, result)+ return+ }+ status, err := m.Restart(r.Context(), name)+ if err != nil {+ failure(err)+ return+ }+ write(http.StatusOK, status)+ default:+ http.NotFound(w, r)+ }+ })+}diff --git a/internal/mcpclient/manager.go b/internal/mcpclient/manager.gonew file mode 100644index 0000000..0b66b28--- /dev/null+++ b/internal/mcpclient/manager.go@@ -0,0 +1,762 @@+package mcpclient++import (+ "context"+ "errors"+ "path/filepath"+ "reflect"+ "sort"+ "strings"+ "sync"+ "time"++ authservice "go-bot/internal/authorization"+ "go-bot/internal/credentials"+ mcpconfig "go-bot/mcp"+)++type ManagerOptions struct {+ Authorization *authservice.Service+ Credentials *credentials.Store+ Images ImageWriter+ CWD string+ Connection ConnectionOptions+ Changed func()+ OAuthCredentialsPath string+}++type serverEntry struct {+ name, owner string+ registered bool // Plugin registration intent, independent of connection lifetime.+ config mcpconfig.Server+ ctx context.Context+ cancel context.CancelFunc+ done chan struct{}+ connection *Connection+ generationCancel context.CancelFunc+ generation context.Context+ discovery Discovery+ tools []*Tool+ status mcpconfig.ServerStatus+ probes map[*serverProbe]struct{}+ cleanupFailure *mcpconfig.CloseResult+ oauthBinding string+ attempt int+ nextRetryAt int64+ connectedAt int64+ publishedConnection *Connection+ authorizationReason string+}++// Manager owns both user and plugin connections in the same Host namespace.+// Configuration requests serialize; live calls, discovery and notifications+// do not hold the management gate. Only connection supervision retries, never+// a model's tool operation or a Controller configuration request.+type Manager struct {+ ctx context.Context+ cancel context.CancelFunc+ options ManagerOptions+ gate chan struct{}+ mu sync.RWMutex+ entries map[string]*serverEntry+ desired mcpconfig.Settings+ secrets map[string]bool+ changes chan struct{}+ lastError string+ closed bool+ oauthStore *oauthGrantStore+ oauthStoreError error+ ownsCredentials bool+ authorizations map[string]*oauthAttempt+ oauthCallback string // Last verified Controller callback; Host memory only.+}++func NewManager(ctx context.Context, options ManagerOptions) *Manager {+ ctx, cancel := context.WithCancel(ctx)+ m := &Manager{ctx: ctx, cancel: cancel, options: options, gate: make(chan struct{}, 1), entries: map[string]*serverEntry{}, secrets: map[string]bool{}, changes: make(chan struct{}), authorizations: map[string]*oauthAttempt{}}+ path := options.OAuthCredentialsPath+ if path == "" && options.CWD != "" {+ path = filepath.Join(options.CWD, ".dsh", credentials.Filename)+ }+ if options.Credentials != nil {+ m.oauthStore = &oauthGrantStore{credentials: options.Credentials}+ } else if path != "" {+ m.oauthStore, m.oauthStoreError = newOAuthGrantStore(path)+ m.ownsCredentials = m.oauthStore != nil+ }++ if m.options.Authorization == nil && m.oauthStore != nil {+ m.options.Authorization = authservice.New(m.oauthStore.credentials)+ }+ return m+}++func (m *Manager) enter(ctx context.Context) (func(), error) {+ select {+ case m.gate <- struct{}{}:+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-m.ctx.Done():+ return nil, m.ctx.Err()+ }+ if m.ctx.Err() != nil {+ <-m.gate+ return nil, m.ctx.Err()+ }+ return func() { <-m.gate }, nil+}+func (m *Manager) changed() {+ m.mu.Lock()+ close(m.changes)+ m.changes = make(chan struct{})+ m.mu.Unlock()+ if m.options.Changed != nil {+ m.options.Changed()+ }+}+func (m *Manager) Changes() (<-chan struct{}, <-chan struct{}) {+ m.mu.RLock()+ defer m.mu.RUnlock()+ return m.changes, m.ctx.Done()+}+func (m *Manager) redact(message string) string {+ if m.options.Credentials != nil {+ message = m.options.Credentials.Redact(message)+ }+ m.mu.RLock()+ defer m.mu.RUnlock()+ for secret := range m.secrets {+ message = strings.ReplaceAll(message, secret, "[redacted]")+ }+ if len(message) > 4096 {+ message = message[:4096] + "…"+ }+ return message+}+func (m *Manager) state(entry *serverEntry, state string, err error) {+ m.stateUpdate(entry, state, err, nil)+}++func (m *Manager) stateUpdate(entry *serverEntry, state string, err error, update func()) {+ message := ""+ if err != nil {+ message = m.redact(err.Error())+ }+ m.mu.Lock()+ if update != nil {+ update()+ }+ entry.status.State, entry.status.Error = state, message+ if state == "waiting-authorization" {+ var detail *Error+ if errors.As(err, &detail) {+ entry.authorizationReason = detail.AuthorizationReason+ }+ }+ if state == "stopping" && entry.cleanupFailure == nil {+ entry.cleanupFailure = &mcpconfig.CloseResult{CloseConfirmed: transportClosed(entry.connection), CleanupError: message}+ }+ if entry.cleanupFailure != nil {+ entry.status.State, entry.status.Error = "failed", entry.cleanupFailure.CleanupError+ }+ m.mu.Unlock()+ m.changed()+}+func (m *Manager) Status() mcpconfig.Status {+ m.mu.RLock()+ defer m.mu.RUnlock()+ return m.statusLocked()+}++func (m *Manager) statusLocked() mcpconfig.Status {+ status := mcpconfig.Status{Servers: []mcpconfig.ServerStatus{}, Error: m.lastError}+ for _, entry := range m.entries {+ value := entry.status+ value.OAuthEnabled = entry.config.OAuth != nil+ if value.Authorization != nil {+ copy := *value.Authorization+ value.Authorization = ©+ }+ value.Missing = append([]string(nil), value.Missing...)+ status.Servers = append(status.Servers, value)+ }+ sort.Slice(status.Servers, func(i, j int) bool { return status.Servers[i].Name < status.Servers[j].Name })+ return status+}++func (m *Manager) ListViews() []mcpconfig.ManagedServerView {+ m.mu.RLock()+ defer m.mu.RUnlock()+ views := []mcpconfig.ManagedServerView{}+ seen := map[string]bool{}+ for _, status := range m.statusLocked().Servers {+ entry := m.entries[status.Name]+ _, configured := m.desired.Servers[status.Name]+ if entry.owner != "" {+ configured = entry.registered+ }+ seen[status.Name] = true+ var authorization *mcpconfig.OAuthAttemptView+ if status.Authorization != nil {+ authorization = status.Authorization.AttemptView()+ }+ views = append(views, mcpconfig.ManagedServerView{Name: status.Name, Configured: configured, Status: m.runtimeStatusLocked(entry), Authorization: authorization})+ }+ // Configuration intent is visible before sequential connection setup has+ // reached each server, just as upstream list() reads entries and records.+ for name, config := range m.desired.Servers {+ if seen[name] {+ continue+ }+ state := "connecting"+ if !config.IsEnabled() {+ state = "disabled"+ }+ status := mcpconfig.ManagedServerStatus{State: state}+ if m.ctx.Err() != nil {+ status = mcpconfig.ManagedServerStatus{State: "closed", Result: &mcpconfig.CloseResult{CloseConfirmed: true}}+ }+ views = append(views, mcpconfig.ManagedServerView{Name: name, Configured: true, Status: status})+ }+ sort.Slice(views, func(i, j int) bool { return views[i].Name < views[j].Name })+ return views+}++func (m *Manager) Apply(ctx context.Context, settings mcpconfig.Settings) (mcpconfig.Status, error) {+ if err := settings.Validate(); err != nil {+ return m.Status(), err+ }+ leave, err := m.enter(ctx)+ if err != nil {+ return m.Status(), err+ }+ defer leave()+ settings = settings.Clone()+ m.mu.Lock()+ for name := range settings.Servers {+ if entry := m.entries[name]; entry != nil && entry.owner != "" {+ m.mu.Unlock()+ return m.Status(), fail("MCP_NAME_CONFLICT", "MCP server name is owned by a plugin: "+name)+ }+ }+ m.desired = settings+ for _, secret := range settings.Credentials {+ if secret != "" {+ m.secrets[secret] = true+ }+ }+ var remove []string+ for name, entry := range m.entries {+ if entry.owner == "" {+ if _, ok := settings.Servers[name]; !ok {+ remove = append(remove, name)+ }+ }+ }+ m.mu.Unlock()+ for _, name := range remove {+ if err = m.remove(ctx, name, ""); err != nil {+ return m.Status(), err+ }+ }+ var names []string+ for name := range settings.Servers {+ names = append(names, name)+ }+ sort.Strings(names)+ var combined, unresolved error+ for _, name := range names {+ resolved, missing, err := settings.Resolve(name)+ if err != nil {+ combined = errors.Join(combined, err)+ unresolved = errors.Join(unresolved, err)+ continue+ }+ if resolved.CWD == "" && resolved.Transport == "stdio" {+ resolved.CWD = m.options.CWD+ }+ if err = m.upsert(ctx, name, "", resolved, missing); err != nil {+ combined = errors.Join(combined, err)+ }+ }+ message := ""+ // Connection failures already belong to each live server's status. Keeping+ // them as a fleet error would survive recovery and disable unrelated servers+ // in clients. Only configuration that could not become an entry stays here.+ if unresolved != nil {+ message = m.redact(unresolved.Error())+ }+ m.mu.Lock()+ m.lastError = message+ m.mu.Unlock()+ m.changed()+ return m.Status(), combined+}++func (m *Manager) upsert(ctx context.Context, name, owner string, config mcpconfig.Server, missing []string) error {+ binding := m.oauthConfigBinding(name, owner, config)+ m.mu.RLock()+ old := m.entries[name]+ m.mu.RUnlock()+ if old != nil {+ if old.owner != owner {+ return fail("MCP_NAME_CONFLICT", "MCP server name is already registered: "+name)+ }+ m.mu.RLock()+ same := reflect.DeepEqual(old.config, config) && reflect.DeepEqual(old.status.Missing, missing) && old.oauthBinding == binding+ state := old.status.State+ m.mu.RUnlock()+ if same && state != "failed" && state != "stopping" {+ return nil+ }+ if err := m.remove(ctx, name, owner); err != nil {+ return err+ }+ }+ lifetime, cancel := context.WithCancel(m.ctx)+ entry := &serverEntry{name: name, owner: owner, registered: owner != "", config: config, ctx: lifetime, cancel: cancel, done: make(chan struct{}), oauthBinding: binding}+ entry.status = mcpconfig.ServerStatus{Name: name, State: "connecting", Source: "user", Missing: append([]string(nil), missing...)}+ if owner != "" {+ entry.status.Source, entry.status.Owner = "plugin", owner+ }+ m.mu.Lock()+ for _, secret := range config.SecretValues() {+ m.secrets[secret] = true+ }+ m.entries[name] = entry+ m.mu.Unlock()+ if !config.IsEnabled() {+ close(entry.done)+ m.state(entry, "disabled", nil)+ return nil+ }+ if len(missing) > 0 {+ close(entry.done)+ m.state(entry, "waiting-credentials", nil)+ return nil+ }+ m.changed()+ ready := make(chan error, 1)+ go m.supervise(entry, ctx, ready)+ select {+ case err := <-ready:+ return err+ case <-ctx.Done():+ entry.cancel()+ select {+ case <-entry.done:+ case <-time.After(CloseTimeout):+ }+ m.state(entry, "failed", ctx.Err())+ return ctx.Err()+ }+}++func (m *Manager) supervise(entry *serverEntry, first context.Context, ready chan<- error) {+ defer close(entry.done)+ firstAttempt := true+ attempts := 0+ notifyReady := func(err error) {+ if !firstAttempt {+ return+ }+ if authorizationRequired(err) {+ ready <- nil+ } else {+ ready <- err+ }+ firstAttempt = false+ }+ for {+ if entry.ctx.Err() != nil {+ return+ }+ m.stateUpdate(entry, "connecting", nil, func() { entry.attempt = attempts; entry.nextRetryAt = 0 })+ call := entry.ctx+ if firstAttempt {+ call = first+ }+ connectCtx, done := context.WithCancel(call)+ stop := context.AfterFunc(entry.ctx, done)+ options, err := m.connectionOptions(entry)+ var connection *Connection+ if err == nil {+ previous := options.connectCleanup+ options.connectCleanup = func(cleanupErr error) {+ if previous != nil {+ previous(cleanupErr)+ }+ if cleanupErr != nil {+ m.retainCleanup(entry, mcpconfig.CloseResult{CloseConfirmed: false, CleanupError: m.redact(cleanupErr.Error())})+ }+ }+ connection, err = Connect(connectCtx, entry.name, entry.config, options)+ }+ var discovery Discovery+ if err == nil {+ m.mu.Lock()+ entry.connection = connection+ m.mu.Unlock()+ discovery, err = connection.Discover(connectCtx)+ }+ stop()+ done()+ if err == nil && entry.ctx.Err() == nil {+ m.publish(entry, connection, discovery)+ attempts = 0+ } else {+ if connection != nil {+ _ = m.closeGeneration(entry, connection)+ }+ if err == nil {+ err = entry.ctx.Err()+ }+ if authorizationRequired(err) {+ m.state(entry, "waiting-authorization", err)+ }+ }+ if err == nil || authorizationRequired(err) {+ notifyReady(err)+ }+ if entry.ctx.Err() != nil {+ notifyReady(err)+ return+ }+ m.mu.RLock()+ cleanupFailed := entry.cleanupFailure != nil+ m.mu.RUnlock()+ if cleanupFailed {+ notifyReady(err)+ return+ }+ if authorizationRequired(err) {+ return+ }+ if err == nil {+ for err == nil {+ select {+ case <-entry.ctx.Done():+ m.withdraw(entry)+ _ = m.closeGeneration(entry, connection)+ return+ case <-connection.Disconnected():+ if connection.needsAuthorization.Load() {+ err = connection.authorizationFailure()+ } else {+ err = fail("MCP_SERVER_UNAVAILABLE", "MCP server disconnected")+ }+ case <-connection.Changes:+ var next Discovery+ next, err = connection.Discover(entry.ctx)+ if err == nil {+ m.publish(entry, connection, next)+ }+ }+ }+ m.withdraw(entry)+ if authorizationRequired(err) {+ m.state(entry, "waiting-authorization", err)+ }+ if closeErr := m.closeGeneration(entry, connection); closeErr != nil {+ return+ }+ }+ if authorizationRequired(err) {+ return+ }+ if attempts >= 10 {+ m.state(entry, "failed", err)+ notifyReady(err)+ return+ }+ delay := 500 * time.Millisecond << attempts+ if delay > 30*time.Second {+ delay = 30 * time.Second+ }+ attempts+++ m.stateUpdate(entry, "reconnecting", err, func() { entry.attempt = attempts; entry.nextRetryAt = time.Now().Add(delay).UnixMilli() })+ // Publish the first failure before Apply/Register returns it. Otherwise+ // its status snapshot can still say connecting with no diagnostic.+ notifyReady(err)+ timer := time.NewTimer(delay)+ select {+ case <-entry.ctx.Done():+ timer.Stop()+ return+ case <-timer.C:+ }+ }+}++func (m *Manager) publish(entry *serverEntry, connection *Connection, discovery Discovery) {+ lifetime, cancel := context.WithCancel(entry.ctx)+ tools := make([]*Tool, 0, len(discovery.Tools))+ for _, definition := range discovery.Tools {+ tools = append(tools, NewTool(connection, definition, ToolOptions{Images: m.options.Images, Lifetime: lifetime}))+ }+ m.mu.Lock()+ if entry.ctx.Err() != nil || m.entries[entry.name] != entry {+ m.mu.Unlock()+ cancel()+ return+ }+ if entry.generationCancel != nil {+ entry.generationCancel()+ }+ if entry.publishedConnection != connection {+ entry.connectedAt = time.Now().UnixMilli()+ entry.publishedConnection = connection+ }+ entry.connection, entry.generationCancel, entry.generation, entry.discovery, entry.tools = connection, cancel, lifetime, discovery, tools+ entry.status.State, entry.status.Error = "connected", ""+ if entry.cleanupFailure != nil {+ entry.status.State, entry.status.Error = "failed", entry.cleanupFailure.CleanupError+ }+ entry.status.ToolCount, entry.status.Resources, entry.status.ProtocolVersion = len(tools), discovery.Resources, discovery.ProtocolVersion+ if discovery.ServerInfo != nil {+ entry.status.ServerName = discovery.ServerInfo.Name+ }+ m.mu.Unlock()+ m.changed()+}++func (m *Manager) withdraw(entry *serverEntry) {+ m.mu.Lock()+ if entry.generationCancel != nil {+ entry.generationCancel()+ }+ m.mu.Unlock()+}++func (m *Manager) remove(ctx context.Context, name, owner string) error {+ m.mu.RLock()+ entry := m.entries[name]+ cleanupFailed := entry != nil && entry.cleanupFailure != nil+ closing := m.closed+ m.mu.RUnlock()+ if entry == nil {+ return nil+ }+ if entry.owner != owner {+ return fail("MCP_INVALID_OWNER", "Only the owning source can remove this MCP server")+ }+ if cleanupFailed && !closing {+ return fail("MCP_CLEANUP_INCOMPLETE", "MCP connection or probe cleanup failed; restart the Host before replacing this server")+ }+ entry.cancel()+ if err := m.cancelOAuthAttempt(ctx, name); err != nil {+ return err+ }+ m.withdraw(entry)+ m.mu.RLock()+ probes := make([]*serverProbe, 0, len(entry.probes))+ for probe := range entry.probes {+ probes = append(probes, probe)+ }+ m.mu.RUnlock()+ for _, probe := range probes {+ probe.cancel()+ }+ timer := time.NewTimer(CloseTimeout)+ defer timer.Stop()+ select {+ case <-entry.done:+ case <-ctx.Done():+ return ctx.Err()+ case <-timer.C:+ m.state(entry, "stopping", fail("MCP_CLEANUP_TIMEOUT", "MCP cleanup has not finished"))+ return fail("MCP_CLEANUP_TIMEOUT", "MCP cleanup has not finished")+ }+ for _, probe := range probes {+ select {+ case <-probe.done:+ case <-ctx.Done():+ return ctx.Err()+ case <-timer.C:+ m.state(entry, "stopping", fail("MCP_CLEANUP_TIMEOUT", "MCP probe cleanup has not finished"))+ return fail("MCP_CLEANUP_TIMEOUT", "MCP probe cleanup has not finished")+ }+ }+ // A probe can discover a cleanup failure while this removal is waiting+ // for it. Recheck after the drain before allowing a replacement to proceed.+ m.mu.RLock()+ cleanupFailed = entry.cleanupFailure != nil+ closing = m.closed+ m.mu.RUnlock()+ if cleanupFailed && !closing {+ return fail("MCP_CLEANUP_INCOMPLETE", "MCP connection or probe cleanup failed; restart the Host before replacing this server")+ }+ m.mu.RLock()+ connection := entry.connection+ m.mu.RUnlock()+ if connection != nil {+ if err := connection.Close(); err != nil {+ m.state(entry, "stopping", err)+ return err+ }+ }+ m.mu.Lock()+ if m.entries[name] == entry {+ delete(m.entries, name)+ }+ m.mu.Unlock()+ m.changed()+ if cleanupFailed {+ return fail("MCP_CLEANUP_INCOMPLETE", "MCP connection or probe cleanup failed before Host shutdown")+ }+ return nil+}++func (m *Manager) Register(ctx context.Context, name, owner string, config mcpconfig.Server) error {+ return m.register(ctx, name, owner, config)+}++func (m *Manager) register(ctx context.Context, name, owner string, config mcpconfig.Server) error {+ if !mcpconfig.ValidServerName(name) || owner == "" || len(owner) > 256 {+ return fail("MCP_INVALID_CONFIG", "Plugin MCP registration needs a server name and owner")+ }+ if err := config.Validate(); err != nil {+ return err+ }+ resolved, missing, err := m.resolvePluginConfig(name, config)+ if err != nil {+ return err+ }+ config = resolved+ leave, err := m.enter(ctx)+ if err != nil {+ return err+ }+ defer leave()+ m.mu.RLock()+ taken := m.entries[name] != nil+ m.mu.RUnlock()+ if taken {+ return fail("MCP_NAME_CONFLICT", "MCP server name is already configured or registered: "+name)+ }+ if config.CWD == "" && config.Transport == "stdio" {+ config.CWD = m.options.CWD+ }+ if err = m.upsert(ctx, name, owner, config, missing); err != nil {+ m.mu.Lock()+ if entry := m.entries[name]; entry != nil && entry.owner == owner {+ entry.registered = false+ }+ m.mu.Unlock()+ cleanup, cancel := context.WithTimeout(context.Background(), CloseTimeout)+ defer cancel()+ return errors.Join(err, m.remove(cleanup, name, owner))+ }+ return nil+}+func (m *Manager) Release(ctx context.Context, name, owner string) error {+ leave, err := m.enter(ctx)+ if err != nil {+ return err+ }+ defer leave()+ m.mu.Lock()+ if entry := m.entries[name]; entry != nil && entry.owner == owner {+ entry.registered = false+ }+ m.mu.Unlock()+ m.changed()+ if err := m.remove(ctx, name, owner); err != nil {+ return err+ }+ m.mu.Lock()+ m.mu.Unlock()+ return nil+}+func (m *Manager) Restart(ctx context.Context, name string) (mcpconfig.Status, error) {+ leave, err := m.enter(ctx)+ if err != nil {+ return m.Status(), err+ }+ defer leave()+ m.mu.RLock()+ entry := m.entries[name]+ m.mu.RUnlock()+ if entry == nil || (entry.owner != "" && !entry.registered) {+ return m.Status(), fail("MCP_NOT_FOUND", "MCP server not configured")+ }+ config, owner := entry.config, entry.owner+ var missing []string+ if owner == "" {+ m.mu.RLock()+ settings := m.desired.Clone()+ m.mu.RUnlock()+ config, missing, err = settings.Resolve(name)+ if err != nil {+ return m.Status(), err+ }+ if config.CWD == "" && config.Transport == "stdio" {+ config.CWD = m.options.CWD+ }+ }+ if err = m.remove(ctx, name, owner); err == nil {+ err = m.upsert(ctx, name, owner, config, missing)+ }+ return m.Status(), err+}+func (m *Manager) Close() error {+ m.cancel()+ m.gate <- struct{}{}+ defer func() { <-m.gate }()+ m.mu.Lock()+ m.closed = true+ var entries []*serverEntry+ for _, entry := range m.entries {+ entries = append(entries, entry)+ }+ m.mu.Unlock()+ var wg sync.WaitGroup+ var mu sync.Mutex+ var combined error+ for _, entry := range entries {+ wg.Add(1)+ go func() {+ defer wg.Done()+ ctx, cancel := context.WithTimeout(context.Background(), CloseTimeout)+ defer cancel()+ err := m.remove(ctx, entry.name, entry.owner)+ if err != nil {+ mu.Lock()+ combined = errors.Join(combined, err)+ mu.Unlock()+ }+ }()+ }+ wg.Wait()+ if m.ownsCredentials {+ combined = errors.Join(combined, m.oauthStore.credentials.Close())+ }+ return combined+}++func (e *serverEntry) credentialKey() string {+ if e.config.OAuth != nil && e.config.OAuth.CredentialKey != "" {+ return e.config.OAuth.CredentialKey+ }+ return e.name+}++// Plugin declarations resolve explicit references through the same built-in+// credential Store as authorization. Node never owns an MCP secret table.+func (m *Manager) resolvePluginConfig(name string, config mcpconfig.Server) (mcpconfig.Server, []string, error) {+ settings := mcpconfig.Settings{Servers: map[string]mcpconfig.Server{name: config}, Credentials: map[string]string{}}+ resolved, missing, err := settings.Resolve(name)+ if err != nil || m.options.Credentials == nil {+ return resolved, missing, err+ }+ for _, ref := range missing {+ value, err := m.options.Credentials.Lookup(ref)+ if err != nil {+ return mcpconfig.Server{}, nil, err+ }+ if value != nil {+ settings.Credentials[ref] = value.Value+ }+ }+ return settings.Resolve(name)+}diff --git a/internal/mcpclient/manager_test.go b/internal/mcpclient/manager_test.gonew file mode 100644index 0000000..48bf625--- /dev/null+++ b/internal/mcpclient/manager_test.go@@ -0,0 +1,220 @@+package mcpclient++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ "go-bot/harness/agent"+ mcpconfig "go-bot/mcp"+)++func TestRecoveredMCPConnectionDoesNotKeepAFleetUnavailableError(t *testing.T) {+ server := testServer()+ handler := sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil)+ var online atomic.Bool+ httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if !online.Load() {+ http.Error(w, "temporary QA outage", http.StatusServiceUnavailable)+ return+ }+ handler.ServeHTTP(w, r)+ }))+ defer httpServer.Close()+ manager := NewManager(t.Context(), ManagerOptions{Connection: ConnectionOptions{StartupTimeout: 300 * time.Millisecond}})+ defer manager.Close()+ settings := mcpconfig.Settings{Servers: map[string]mcpconfig.Server{"recovering": {Transport: "streamable-http", URL: httpServer.URL}}}+ status, err := manager.Apply(t.Context(), settings)+ if err == nil || len(status.Servers) != 1 || status.Servers[0].Error == "" {+ t.Fatalf("initial connection failure was hidden: %+v %v", status, err)+ }+ if status.Error != "" {+ t.Fatalf("one server failure was reported as a fleet availability error: %+v", status)+ }+ online.Store(true)+ status, err = manager.Restart(t.Context(), "recovering")+ if err != nil || len(status.Servers) != 1 || status.Servers[0].State != "connected" || status.Servers[0].Error != "" || status.Error != "" {+ t.Fatalf("recovery retained the old unavailable state: %+v %v", status, err)+ }+ // Invalid resolved configuration has no live entry and remains a fleet+ // configuration diagnostic, rather than being silently discarded.+ settings.Credentials = map[string]string{"header": "invalid\nheader"}+ settings.Servers["invalid"] = mcpconfig.Server{Transport: "streamable-http", URL: httpServer.URL, Headers: map[string]string{"X-QA": "${credential:header}"}}+ status, err = manager.Apply(t.Context(), settings)+ if err == nil || status.Error == "" || status.Servers[0].State != "connected" {+ t.Fatalf("unapplied configuration diagnostic was lost: %+v %v", status, err)+ }+}++func managedFixture(t *testing.T, loading string) (*Manager, *sdk.Server, mcpconfig.Settings) {+ t.Helper()+ server := testServer()+ httpServer := httptest.NewServer(sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil))+ t.Cleanup(httpServer.Close)+ manager := NewManager(t.Context(), ManagerOptions{})+ t.Cleanup(func() {+ if err := manager.Close(); err != nil {+ t.Error(err)+ }+ })+ settings := mcpconfig.Settings{Servers: map[string]mcpconfig.Server{"fixture": {Transport: "streamable-http", URL: httpServer.URL, ToolLoading: loading}}}+ status, err := manager.Apply(t.Context(), settings)+ if err != nil || len(status.Servers) != 1 || status.Servers[0].State != "connected" {+ t.Fatalf("initial apply status=%+v err=%v", status, err)+ }+ return manager, server, settings+}++func findTool(t *testing.T, scope *Scope, name string) agent.Tool {+ t.Helper()+ tools, err := scope.Tools(t.Context(), "unused")+ if err != nil {+ t.Fatal(err)+ }+ for _, tool := range tools {+ if tool.Spec().Name == name {+ return tool+ }+ }+ return nil+}++func TestOnDemandToolsBelongToLiveAgentAndLoadAtomically(t *testing.T) {+ manager, _, _ := managedFixture(t, "on-demand")+ first, second := manager.NewScope(), manager.NewScope()+ defer first.Close()+ defer second.Close()+ name := PublicToolName("fixture", "one")+ if findTool(t, first, name) != nil {+ t.Fatal("on-demand tool exposed before loading")+ }+ loader := findTool(t, first, PublicToolName("fixture", "load_tools"))+ if loader == nil {+ t.Fatal("missing loader")+ }+ if _, err := loader.Execute(t.Context(), json.RawMessage(`{"tools":["one","unknown"]}`)); err == nil {+ t.Fatal("unknown tool was accepted")+ }+ if findTool(t, first, name) != nil {+ t.Fatal("failed load partially changed scope")+ }+ message, err := loader.Execute(t.Context(), json.RawMessage(`{"tools":["one","one"]}`))+ if err != nil || message != "Loaded: "+name+"." {+ t.Fatalf("load=%q err=%v", message, err)+ }+ tool := findTool(t, first, name)+ if tool == nil || findTool(t, second, name) != nil {+ t.Fatal("loaded tools leaked across Agent instances")+ }+ if result, err := tool.Execute(t.Context(), json.RawMessage(`{}`)); err != nil || result != "one" {+ t.Fatalf("result=%q err=%v", result, err)+ }+ message, err = loader.Execute(t.Context(), json.RawMessage(`{"tools":["one"]}`))+ if err != nil || message != "Already loaded: "+name+"." {+ t.Fatalf("repeat load=%q err=%v", message, err)+ }+ sections, err := first.Context(t.Context(), "unused")+ if err != nil || len(sections) != 3 || !strings.Contains(sections[1].Text, "{{not_a_template}}") || !strings.Contains(sections[2].Text, "- one: A fixture tool") {+ t.Fatalf("context=%+v err=%v", sections, err)+ }+ first.Close()+ if _, err := loader.Execute(t.Context(), json.RawMessage(`{"tools":["two"]}`)); err == nil {+ t.Fatal("closed scope accepted a load")+ }+}++func TestCatalogChangeWithdrawsOldToolGenerationAndKeepsScopedLoads(t *testing.T) {+ manager, server, settings := managedFixture(t, "on-demand")+ scope := manager.NewScope()+ defer scope.Close()+ loader := findTool(t, scope, PublicToolName("fixture", "load_tools"))+ if _, err := loader.Execute(t.Context(), json.RawMessage(`{"tools":["one"]}`)); err != nil {+ t.Fatal(err)+ }+ old := findTool(t, scope, PublicToolName("fixture", "one"))+ server.AddTool(&sdk.Tool{Name: "three", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {+ return &sdk.CallToolResult{}, nil+ })+ deadline := time.NewTimer(4 * time.Second)+ defer deadline.Stop()+ for {+ changes, _ := manager.Changes()+ if manager.Status().Servers[0].ToolCount == 3 {+ break+ }+ select {+ case <-changes:+ case <-deadline.C:+ t.Fatal("manager did not refresh notified catalog")+ }+ }+ if _, err := old.Execute(t.Context(), json.RawMessage(`{}`)); err == nil {+ t.Fatal("withdrawn generation was still callable")+ }+ fresh := findTool(t, scope, PublicToolName("fixture", "one"))+ if fresh == nil || fresh == old {+ t.Fatal("scope lost loaded name or retained stale handler")+ }+ if result, err := fresh.Execute(t.Context(), json.RawMessage(`{}`)); err != nil || result != "one" {+ t.Fatalf("new result=%q err=%v", result, err)+ }+ if _, err := manager.Apply(t.Context(), mcpconfig.Settings{}); err != nil {+ t.Fatal(err)+ }+ if tools, err := scope.Tools(t.Context(), ""); err != nil || len(tools) != 0 {+ t.Fatalf("removed tools=%v err=%v", tools, err)+ }+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+}++func TestManagedResourcesAndOwnershipAndWaitingStates(t *testing.T) {+ manager, _, settings := managedFixture(t, "eager")+ scope := manager.NewScope()+ defer scope.Close()+ list := findTool(t, scope, "list_mcp_resources")+ result, err := list.(agent.ResultTool).ExecuteResult(t.Context(), json.RawMessage(`{"server":"fixture"}`))+ if err != nil || !strings.Contains(string(result.Meta), "memo://one") || !strings.Contains(string(result.Meta), "memo://two") {+ t.Fatalf("resources=%+v err=%v", result, err)+ }+ read := findTool(t, scope, "read_mcp_resource")+ result, err = read.(agent.ResultTool).ExecuteResult(t.Context(), json.RawMessage(`{"server":"fixture","uri":"memo://one"}`))+ if err != nil || len(result.ContentBlocks) != 1 || !strings.Contains(result.ContentBlocks[0].Text, "resource content") {+ t.Fatalf("read=%+v err=%v", result, err)+ }+ if err := manager.Release(t.Context(), "fixture", "wrong-owner"); err == nil {+ t.Fatal("plugin removed user-owned server")+ }+ pluginConfig := settings.Servers["fixture"]+ if err := manager.Register(t.Context(), "owned", "instance-a", pluginConfig); err != nil {+ t.Fatal(err)+ }+ settings.Servers["owned"] = pluginConfig+ if _, err := manager.Apply(t.Context(), settings); err == nil {+ t.Fatal("user overwrote plugin-owned namespace")+ }+ if err := manager.Release(t.Context(), "owned", "instance-b"); err == nil {+ t.Fatal("wrong plugin removed server")+ }+ if err := manager.Release(t.Context(), "owned", "instance-a"); err != nil {+ t.Fatal(err)+ }+ settings.Servers = map[string]mcpconfig.Server{+ "key": {Transport: "streamable-http", URL: pluginConfig.URL, Headers: map[string]string{"Authorization": "Bearer ${credential:key}"}},+ "oauth": {Transport: "streamable-http", URL: pluginConfig.URL, OAuth: &mcpconfig.OAuth{ClientID: "fixture"}},+ }+ status, err := manager.Apply(t.Context(), settings)+ if err != nil || len(status.Servers) != 2 || status.Servers[0].State != "waiting-credentials" || status.Servers[1].State != "waiting-authorization" {+ t.Fatalf("waiting status=%+v err=%v", status, err)+ }+ if _, err := manager.Restart(t.Context(), "key"); err != nil || manager.Status().Servers[0].State != "waiting-credentials" {+ t.Fatalf("restart lost credential waiting state: %v", err)+ }+}diff --git a/internal/mcpclient/names.go b/internal/mcpclient/names.gonew file mode 100644index 0000000..fdacbc3--- /dev/null+++ b/internal/mcpclient/names.go@@ -0,0 +1,34 @@+package mcpclient++import (+ "crypto/sha256"+ "encoding/hex"+ "unicode/utf16"+)++// PublicToolName follows DeepSeek Harness's pinned naming contract. JS's+// non-Unicode regexp replaces UTF-16 units, including both halves of an emoji.+// Wire calls always retain the separately stored raw name.+func PublicToolName(server, raw string) string {+ joined := "mcp__" + server + "__" + raw+ units := utf16.Encode([]rune(joined))+ normalized := make([]byte, len(units))+ clean := true+ for i, unit := range units {+ if unit >= 'a' && unit <= 'z' || unit >= 'A' && unit <= 'Z' || unit >= '0' && unit <= '9' || unit == '_' || unit == '-' {+ normalized[i] = byte(unit)+ } else {+ normalized[i] = '_'+ clean = false+ }+ }+ if clean && len(normalized) <= 64 {+ return string(normalized)+ }+ sum := sha256.Sum256([]byte(server + "\x00" + raw))+ suffix := hex.EncodeToString(sum[:])[:12]+ if len(normalized) > 51 {+ normalized = normalized[:51]+ }+ return string(normalized) + "_" + suffix+}diff --git a/internal/mcpclient/oauth.go b/internal/mcpclient/oauth.gonew file mode 100644index 0000000..09f594b--- /dev/null+++ b/internal/mcpclient/oauth.go@@ -0,0 +1,939 @@+package mcpclient++import (+ "context"+ "crypto/sha256"+ "crypto/subtle"+ "encoding/hex"+ "encoding/json"+ "errors"+ "net/http"+ "net/url"+ "strings"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/modelcontextprotocol/go-sdk/auth"+ "github.com/modelcontextprotocol/go-sdk/oauthex"+ authservice "go-bot/internal/authorization"+ "go-bot/internal/credentials"+ mcpconfig "go-bot/mcp"+ "golang.org/x/oauth2"+)++const OAuthAuthorizationTimeout = 10 * time.Minute++type AuthorizationCommit func(*credentials.Record) error+type oauthAttempt struct {+ entry *serverEntry+ ctx context.Context+ cancel context.CancelFunc+ done chan struct{}+ ready chan struct{}+ answer chan oauthCallbackResult+ state string+ issuer string+ issuerRequired bool+ consumed bool+ deadline *time.Timer+ committing bool+ committed bool+ view mcpconfig.OAuthAuthorization+ err error+}++type oauthCallbackResult struct {+ value *auth.AuthorizationResult+ err error+}++func authorizationRequired(err error) bool {+ var detail *Error+ return errors.As(err, &detail) && detail.Code == "MCP_AUTHORIZATION_REQUIRED"+}++func (m *Manager) oauthConfigBinding(_, _ string, config mcpconfig.Server) string {+ if config.OAuth == nil {+ return ""+ }+ // The credential key selects the owner. Upstream binds the grant only to+ // the resolved endpoint, configured client ID and configured scope;+ // runtime handles, budgets and secret rotation are not new identities.+ var clientID *string+ if config.OAuth.ClientID != "" {+ clientID = &config.OAuth.ClientID+ }+ return oauthIdentityBinding(config.URL, clientID, config.OAuth.RequestedScope())+}++func oauthIdentityBinding(serverURL string, clientID, scope *string) string {+ data, _ := json.Marshal(struct {+ URL string+ ClientID, Scope *string+ }{serverURL, clientID, scope})+ digest := sha256.Sum256(data)+ return hex.EncodeToString(digest[:])+}++func (m *Manager) oauthHTTPClient(options *mcpconfig.OAuth) *http.Client {+ client := &http.Client{}+ if m.options.Connection.HTTPClient != nil {+ copy := *m.options.Connection.HTTPClient+ client = ©+ }+ client.Timeout = 10 * time.Second+ if options != nil && options.RequestTimeoutMS != nil {+ client.Timeout = time.Duration(*options.RequestTimeoutMS) * time.Millisecond+ }+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }+ return client+}++func oauthAuthorizationTimeout(options *mcpconfig.OAuth) time.Duration {+ if options != nil && options.AuthorizationTimeoutMS != nil {+ return time.Duration(*options.AuthorizationTimeoutMS) * time.Millisecond+ }+ return OAuthAuthorizationTimeout+}++type storedOAuthHandler struct{ source oauth2.TokenSource }++// The Go SDK otherwise infers requested scopes from resource metadata. The+// upstream MCP owner uses only configured scope or the actual Bearer challenge.+type challengeScopeOAuthHandler struct {+ base auth.OAuthHandler+ observe func(*http.Response)+}++func (h challengeScopeOAuthHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) {+ return h.base.TokenSource(ctx)+}+func (h challengeScopeOAuthHandler) Authorize(ctx context.Context, request *http.Request, response *http.Response) error {+ h.observe(response)+ return h.base.Authorize(ctx, request, response)+}++func (h *storedOAuthHandler) TokenSource(context.Context) (oauth2.TokenSource, error) {+ return h.source, nil+}+func (h *storedOAuthHandler) Authorize(ctx context.Context, request *http.Request, response *http.Response) error {+ if response.Body != nil {+ _ = response.Body.Close()+ }+ if response.StatusCode == http.StatusForbidden {+ challenges, err := oauthex.ParseWWWAuthenticate(response.Header.Values("WWW-Authenticate"))+ stepUp := false+ if err == nil {+ for _, challenge := range challenges {+ if challenge.Scheme == "bearer" && challenge.Params["error"] == "insufficient_scope" {+ stepUp = true+ }+ }+ }+ if !stepUp {+ return nil+ }+ }+ if response.StatusCode == http.StatusForbidden {+ return authorizationFailure("scope", "MCP server requires additional OAuth scopes")+ }+ if source, ok := h.source.(*persistentOAuthTokenSource); ok {+ access, present := strings.CutPrefix(request.Header.Get("Authorization"), "Bearer ")+ if !present || access == "" {+ return fail("MCP_OAUTH_FAILED", "MCP OAuth response has no credential binding")+ }+ return source.refreshRejected(ctx, access)+ }+ return authorizationFailure("rejected", "MCP server requires an explicit OAuth connection")+}++type observedOAuthHandler struct {+ base auth.OAuthHandler+ required func(error)+ issued func(*oauth2.Token)+ authorizeMu sync.Mutex+ authorizationError error+}++func (h *observedOAuthHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) {+ source, err := h.base.TokenSource(ctx)+ if authorizationRequired(err) {+ h.required(err)+ }+ if source == nil || err != nil {+ return source, err+ }+ return &observedOAuthTokenSource{base: source, required: h.required, issued: h.issued}, nil+}+func (h *observedOAuthHandler) Authorize(ctx context.Context, request *http.Request, response *http.Response) error {+ h.authorizeMu.Lock()+ defer h.authorizeMu.Unlock()+ if h.authorizationError != nil {+ if response.Body != nil {+ _ = response.Body.Close()+ }+ return h.authorizationError+ }+ // Multiple transport requests may have observed the old token before an+ // explicit browser flow finished. Retry those with the newly issued token,+ // rather than opening another consent flow or replacing its state.+ source, sourceErr := h.base.TokenSource(ctx)+ if sourceErr != nil {+ if response.Body != nil {+ _ = response.Body.Close()+ }+ if authorizationRequired(sourceErr) {+ h.required(sourceErr)+ }+ h.authorizationError = sourceErr+ return sourceErr+ }+ if sourceErr == nil && source != nil {+ if token, err := source.Token(); err == nil {+ h.issued(token)+ probe := request.Clone(ctx)+ probe.Header = request.Header.Clone()+ token.SetAuthHeader(probe)+ if probe.Header.Get("Authorization") != request.Header.Get("Authorization") {+ if response.Body != nil {+ _ = response.Body.Close()+ }+ return nil+ }+ } else if authorizationRequired(err) {+ if response.Body != nil {+ _ = response.Body.Close()+ }+ h.required(err)+ h.authorizationError = err+ return err+ }+ }+ err := h.base.Authorize(ctx, request, response)+ h.authorizationError = err+ if authorizationRequired(err) {+ h.required(err)+ }+ return err+}++type observedOAuthTokenSource struct {+ base oauth2.TokenSource+ required func(error)+ issued func(*oauth2.Token)+}++func (s *observedOAuthTokenSource) Token() (*oauth2.Token, error) {+ token, err := s.base.Token()+ if err == nil {+ s.issued(token)+ }+ if authorizationRequired(err) {+ s.required(err)+ }+ return token, err+}++func (m *Manager) connectionOptions(entry *serverEntry) (ConnectionOptions, error) {+ options := m.options.Connection+ options.Secrets = append([]string(nil), options.Secrets...)+ m.mu.RLock()+ for secret := range m.secrets {+ options.Secrets = append(options.Secrets, secret)+ }+ m.mu.RUnlock()+ if entry.config.OAuth == nil {+ return options, nil+ }+ if m.oauthStoreError != nil {+ return options, m.oauthStoreError+ }+ if m.oauthStore == nil {+ return options, authorizationFailure("missing", "Connect this MCP server with OAuth")+ }+ grant, err := m.oauthStore.connectionGrant(entry.credentialKey(), entry.oauthBinding)+ if err != nil {+ return options, err+ }+ m.rememberOAuthSecrets(grant)+ options.Secrets = append(options.Secrets, grant.Token.AccessToken, grant.Token.RefreshToken, grant.Config.ClientSecret)+ options.OAuth = &storedOAuthHandler{source: m.oauthStore.tokenSource(m.ctx, entry.credentialKey(), grant, m.oauthHTTPClient(entry.config.OAuth))}+ return options, nil+}++func (m *Manager) rememberOAuthSecrets(grant oauthGrant) {+ m.mu.Lock()+ defer m.mu.Unlock()+ for _, value := range []string{grant.Token.AccessToken, grant.Token.RefreshToken, grant.Config.ClientSecret} {+ if value != "" {+ m.secrets[value] = true+ }+ }+}++func validOAuthURL(raw string) bool {+ u, err := url.Parse(raw)+ if err != nil || u.Hostname() == "" || u.User != nil || u.Fragment != "" || len(raw) > 8192 {+ return false+ }+ if u.Scheme == "https" {+ return true+ }+ return u.Scheme == "http" && (u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1" || u.Hostname() == "::1")+}++func (m *Manager) authorizationView(attempt *oauthAttempt, view mcpconfig.OAuthAuthorization) {+ if view.Phase == "" || view.State == "pending" || view.State == "failed" || view.State == "expired" || view.State == "cancelled" || view.State == "authorized" {+ switch view.State {+ case "preparing":+ view.Phase = "starting"+ case "pending":+ view.Phase = "waiting-browser"+ case "failed", "expired":+ view.Phase = "failed"+ case "cancelled":+ view.Phase = "cancelled"+ case "authorized":+ view.Phase = "authorized"+ }+ }+ m.mu.Lock()+ attempt.view = view+ owner := m.authorizations[attempt.entry.name]+ currentView := attempt.entry.status.Authorization+ if m.entries[attempt.entry.name] == attempt.entry && (owner == attempt || (owner == nil && (currentView == nil || currentView.ID == view.ID))) {+ copy := view+ attempt.entry.status.Authorization = ©+ }+ m.mu.Unlock()+ m.changed()+}++// Authorize starts one explicit browser flow and returns once its authorization+// URL is ready. Waiting for the browser happens in Host memory, never Redis.+func (m *Manager) Authorize(ctx context.Context, name, redirect string) (mcpconfig.OAuthAuthorization, error) {+ attempt, fresh, err := m.beginAuthorization(ctx, name, redirect)+ if err != nil {+ return mcpconfig.OAuthAuthorization{}, err+ }+ if !fresh {+ m.mu.RLock()+ view := attempt.view+ m.mu.RUnlock()+ return view, nil+ }+ select {+ case <-attempt.ready:+ m.mu.RLock()+ view := attempt.view+ m.mu.RUnlock()+ return view, nil+ case <-attempt.done:+ m.mu.RLock()+ view, err := attempt.view, attempt.err+ m.mu.RUnlock()+ return view, err+ case <-ctx.Done():+ attempt.cancel()+ return mcpconfig.OAuthAuthorization{}, ctx.Err()+ }+}++func (m *Manager) beginAuthorization(ctx context.Context, name, redirect string) (*oauthAttempt, bool, error) {+ if err := validateOAuthCallback(redirect); err != nil {+ return nil, false, err+ }+ leave, err := m.enter(ctx)+ if err != nil {+ return nil, false, err+ }+ defer leave()+ m.mu.RLock()+ previous := m.authorizations[name]+ var activeView mcpconfig.OAuthAuthorization+ if previous != nil {+ activeView = previous.view+ }+ m.mu.RUnlock()+ if previous != nil {+ switch activeView.Phase {+ case "starting", "waiting-browser", "exchanging", "committing":+ // A second start observes the same active authorization; only an+ // explicit cancellation or owner retirement withdraws its state.+ return previous, false, nil+ }+ }+ if err := m.cancelOAuthAttempt(ctx, name); err != nil {+ return nil, false, err+ }+ m.mu.RLock()+ entry := m.entries[name]+ cleanupFailed := entry != nil && entry.cleanupFailure != nil+ m.mu.RUnlock()+ if cleanupFailed {+ return nil, false, fail("MCP_CLEANUP_INCOMPLETE", "MCP authorization cleanup failed; restart the Host before authorizing again")+ }+ if entry == nil || entry.config.OAuth == nil {+ return nil, false, fail("MCP_NOT_FOUND", "OAuth MCP server is not configured")+ }+ if len(entry.status.Missing) > 0 {+ return nil, false, fail("MCP_CREDENTIAL_REQUIRED", "Configure the missing MCP credentials first")+ }+ if m.oauthStoreError != nil {+ return nil, false, m.oauthStoreError+ }+ if m.oauthStore == nil {+ return nil, false, fail("MCP_OAUTH_STORE_UNAVAILABLE", "Host OAuth credential storage is not configured")+ }+ lifetime, cancelCause := context.WithCancelCause(m.ctx)+ cancel := func() { cancelCause(context.Canceled) }+ budget := oauthAuthorizationTimeout(entry.config.OAuth)+ attempt := &oauthAttempt{entry: entry, ctx: lifetime, cancel: cancel, done: make(chan struct{}), ready: make(chan struct{}, 1), answer: make(chan oauthCallbackResult, 1), view: mcpconfig.OAuthAuthorization{ID: uuid.NewString(), Phase: "starting", Name: name, State: "preparing", ExpiresAt: time.Now().Add(budget).UnixMilli()}}+ m.mu.Lock()+ attempt.deadline = time.AfterFunc(budget, func() {+ m.mu.Lock()+ defer m.mu.Unlock()+ if !attempt.committing {+ cancelCause(context.DeadlineExceeded)+ }+ })+ m.authorizations[name] = attempt+ m.mu.Unlock()+ m.authorizationView(attempt, attempt.view)+ go m.runAuthorization(attempt, redirect)+ return attempt, true, nil+}++func (m *Manager) runAuthorization(attempt *oauthAttempt, redirect string) {+ entry := attempt.entry+ client, registration := m.registrationClient(entry, redirect)+ var operationErr error+ var cleanupErr error+ defer func() {+ cause := context.Cause(attempt.ctx)+ var rejection *oauth2.RetrieveError+ if errors.As(operationErr, &rejection) && rejection.ErrorCode == "invalid_client" {+ cleanup, cancel := context.WithTimeout(context.WithoutCancel(attempt.ctx), CloseTimeout)+ operationErr = errors.Join(operationErr, registration.invalidate(cleanup))+ cancel()+ }+ attempt.cancel()+ // Registration secrets can be learned after the temporary Connection+ // was created; redact once more with the owner's complete secret set.+ var publicErr error+ if operationErr != nil {+ publicErr = &Error{Code: "MCP_OAUTH_FAILED", Message: m.redact(operationErr.Error()), Cause: operationErr}+ }+ m.mu.Lock()+ if attempt.deadline != nil {+ attempt.deadline.Stop()+ }+ // Cancellation cannot retract a credential commit already admitted.+ // A cleanup failure remains a failure independently of that commit.+ // Authorization is a credential outcome. Subsequent MCP connection+ // failures are reported by the supervisor, not as a retracted grant.+ if attempt.committed && cleanupErr == nil {+ operationErr = nil+ publicErr = nil+ }+ attempt.err = publicErr+ view := attempt.view+ committed := attempt.committed+ m.mu.Unlock()+ if operationErr != nil {+ view.State = "failed"+ if cleanupErr == nil && errors.Is(cause, context.DeadlineExceeded) {+ view.State = "expired"+ } else if cleanupErr == nil && errors.Is(cause, context.Canceled) {+ view.State = "cancelled"+ }+ view.URL = ""+ view.Error = m.redact(operationErr.Error())+ m.authorizationView(attempt, view)+ } else if committed {+ view.URL, view.State = "", "authorized"+ m.authorizationView(attempt, view)+ }+ close(attempt.done)+ }()+ acquire := func(ctx context.Context, commit AuthorizationCommit, admit func() error) error {+ if err := ctx.Err(); err != nil {+ attempt.cancel()+ return err+ }+ stop := context.AfterFunc(ctx, func() {+ m.mu.Lock()+ defer m.mu.Unlock()+ if !attempt.committing {+ attempt.cancel()+ }+ })+ defer stop()+ options := m.options.Connection+ options.StartupTimeout = oauthAuthorizationTimeout(entry.config.OAuth)+ previousCleanup := options.connectCleanup+ options.connectCleanup = func(err error) {+ if previousCleanup != nil {+ previousCleanup(err)+ }+ cleanupErr = err+ if err != nil {+ m.retainCleanup(entry, mcpconfig.CloseResult{CloseConfirmed: false, CleanupError: m.redact(err.Error())})+ }+ }+ oauthConfig := entry.config.OAuth+ var resource string+ handlerConfig := &auth.AuthorizationCodeHandlerConfig{RedirectURL: redirect, Client: client,+ AuthorizationCodeFetcher: func(ctx context.Context, args *auth.AuthorizationArgs) (*auth.AuthorizationResult, error) {+ m.mu.RLock()+ committed := attempt.committed+ m.mu.RUnlock()+ if committed {+ // The explicit flow ends at credential commit. Subsequent scope+ // challenges belong to the managed connection and a new explicit+ // authorization, not an unbounded second browser wait here.+ return nil, authorizationFailure("scope", "MCP server requires another explicit OAuth authorization")+ }+ if !validOAuthURL(args.URL) {+ return nil, fail("MCP_INVALID_AUTHORIZATION_URL", "OAuth provider returned an invalid authorization URL")+ }+ if err := registration.admit(ctx, args.URL); err != nil {+ return nil, err+ }+ parsed, _ := url.Parse(args.URL)+ resource = parsed.Query().Get("resource")+ state := parsed.Query().Get("state")+ if state == "" || len(state) > 512 {+ return nil, fail("MCP_INVALID_AUTHORIZATION_URL", "OAuth provider returned an invalid state")+ }+ issuer, issuerRequired := registration.callbackIssuer()+ m.mu.Lock()+ attempt.state, attempt.consumed = state, false+ attempt.issuer, attempt.issuerRequired = issuer, issuerRequired+ view := attempt.view+ m.mu.Unlock()+ view.URL, view.State = args.URL, "pending"+ m.authorizationView(attempt, view)+ select {+ case attempt.ready <- struct{}{}:+ default:+ }+ select {+ case result := <-attempt.answer:+ if result.value != nil && issuer == "" {+ result.value.Iss = ""+ }+ return result.value, result.err+ case <-ctx.Done():+ return nil, ctx.Err()+ }+ },+ NewTokenSource: func(_ context.Context, config *oauth2.Config, token *oauth2.Token) (oauth2.TokenSource, error) {+ m.mu.Lock()+ if err := attempt.ctx.Err(); err != nil {+ m.mu.Unlock()+ return nil, err+ }+ current := m.entries[entry.name] == entry+ if !current {+ m.mu.Unlock()+ return nil, fail("MCP_AUTHORIZATION_REQUIRED", "MCP configuration changed during authorization")+ }+ if admit != nil {+ if err := admit(); err != nil {+ m.mu.Unlock()+ return nil, err+ }+ }+ attempt.committing = true+ if attempt.deadline != nil {+ attempt.deadline.Stop()+ }+ view := attempt.view+ m.mu.Unlock()+ scope, scopePresent := token.Extra("scope").(string)+ metadata, rawMetadata := registration.authorizationMetadata()+ grant := oauthGrant{ID: uuid.NewString(), Binding: entry.oauthBinding, ServerURL: entry.config.URL, Issuer: metadata.Issuer,+ ClientKey: m.oauthClientKey(entry, metadata.Issuer, redirect), ConfiguredScope: oauthConfig.RequestedScope(), Metadata: rawMetadata,+ Config: *config, Token: *token, Resource: resource, Scope: scope, ScopePresent: scopePresent}+ if oauthConfig.ClientID != "" {+ grant.ConfiguredClientID = &oauthConfig.ClientID+ }+ view.Phase = "committing"+ m.authorizationView(attempt, view)+ m.rememberOAuthSecrets(grant)+ // Once admitted, publication finishes even if cancellation or Host+ // shutdown arrives. The cancelling owner drains attempt.done before+ // deleting credentials or replacing this configuration.+ var commitErr error+ if commit != nil {+ record, err := oauthRecord("mcp-oauth-grant", grant)+ if err != nil {+ return nil, err+ }+ commitErr = commit(record)+ } else {+ // Low-level Go-only manager fixtures have no Cordis service.+ commitErr = m.oauthStore.put(context.WithoutCancel(attempt.ctx), entry.credentialKey(), grant)+ }+ if commitErr != nil {+ return nil, commitErr+ }+ m.mu.Lock()+ attempt.committed = true+ m.mu.Unlock()+ return m.oauthStore.tokenSource(m.ctx, entry.credentialKey(), grant, m.oauthHTTPClient(entry.config.OAuth)), nil+ },+ // The TypeScript SDK accepts a matching iss even when the server did+ // not advertise it. Go SDK's default is stricter; use the same table.+ AcceptUnadvertisedIss: true,+ }+ var challengeScope []string+ var scopeMu sync.Mutex+ handlerConfig.ScopeFilter = func([]string) []string {+ if scope := oauthConfig.RequestedScope(); scope != nil {+ return strings.Fields(*scope)+ }+ scopeMu.Lock()+ defer scopeMu.Unlock()+ return append([]string(nil), challengeScope...)+ }+ if oauthConfig.ClientID != "" {+ credentials := &oauthex.ClientCredentials{ClientID: oauthConfig.ClientID}+ if oauthConfig.ClientSecretRef != "" || oauthConfig.ClientSecret != "" {+ secret := oauthConfig.ClientSecret+ if secret == "" {+ m.mu.RLock()+ secret = m.desired.Credentials[oauthConfig.ClientSecretRef]+ m.mu.RUnlock()+ }+ if secret == "" {+ operationErr = fail("MCP_CREDENTIAL_REQUIRED", "OAuth client secret is missing")+ return operationErr+ }+ credentials.ClientSecretAuth = &oauthex.ClientSecretAuth{ClientSecret: secret}+ }+ handlerConfig.PreregisteredClient = credentials+ } else {+ handlerConfig.DynamicClientRegistrationConfig = &auth.DynamicClientRegistrationConfig{Metadata: &oauthex.ClientRegistrationMetadata{RedirectURIs: []string{redirect}, ClientName: "Go Bot", GrantTypes: []string{"authorization_code", "refresh_token"}, ResponseTypes: []string{"code"}, TokenEndpointAuthMethod: "none"}}+ if scope := oauthConfig.RequestedScope(); scope != nil {+ handlerConfig.DynamicClientRegistrationConfig.Metadata.Scope = *scope+ }+ }+ registration.preregistered = handlerConfig.PreregisteredClient+ handler, err := auth.NewAuthorizationCodeHandler(handlerConfig)+ if err != nil {+ operationErr = err+ return operationErr+ }+ options.OAuth = challengeScopeOAuthHandler{base: handler, observe: func(response *http.Response) {+ var scopes []string+ if challenges, err := oauthex.ParseWWWAuthenticate(response.Header.Values("WWW-Authenticate")); err == nil {+ for _, challenge := range challenges {+ if challenge.Scheme == "bearer" {+ scopes = strings.Fields(challenge.Params["scope"])+ break+ }+ }+ }+ scopeMu.Lock()+ challengeScope = scopes+ scopeMu.Unlock()+ }}+ connection, err := Connect(attempt.ctx, entry.name, entry.config, options)+ if connection != nil {+ cleanupErr = connection.Close()+ if cleanupErr != nil {+ m.retainCleanup(entry, mcpconfig.CloseResult{CloseConfirmed: transportClosed(connection), CleanupError: m.redact(cleanupErr.Error())})+ }+ }+ if cleanupErr != nil {+ operationErr = cleanupErr+ return operationErr+ }+ m.mu.RLock()+ committed := attempt.committed+ m.mu.RUnlock()+ if !committed {+ if err == nil {+ err = fail("MCP_OAUTH_NOT_REQUIRED", "This endpoint did not request OAuth; check its configuration")+ }+ operationErr = err+ return operationErr+ }+ return nil+ }+ if service := m.options.Authorization; service != nil {+ key := oauthGrantKey(entry.credentialKey())+ dispose, err := service.Register(authservice.Flow{Key: key, Label: entry.name, Methods: []authservice.Method{{ID: "oauth", Label: "OAuth"}}, Run: func(session *authservice.Session) error {+ return acquire(session.Context, session.Commit, session.AdmitCommit)+ }})+ if err != nil {+ operationErr = err+ } else {+ outcome, err := service.BeginDrained(attempt.ctx, key, "oauth", authservice.Interaction{})+ dispose()+ operationErr = err+ if err == nil && outcome.Status == "cancelled" {+ operationErr = context.Canceled+ }+ }+ } else {+ operationErr = acquire(attempt.ctx, nil, nil)+ }++ if operationErr != nil {+ return+ }+ if err := attempt.ctx.Err(); err != nil {+ operationErr = err+ return+ }+ // The flow no longer needs cancellation through entry replacement. Remove+ // it before Restart so its own cleanup cannot wait for its own completion.+ m.mu.Lock()+ if m.authorizations[entry.name] == attempt {+ delete(m.authorizations, entry.name)+ }+ view := attempt.view+ view.URL, view.State = "", "connecting"+ attempt.view = view+ if m.entries[entry.name] == entry {+ copy := view+ entry.status.Authorization = ©+ }+ m.mu.Unlock()+ m.changed()+ if entry.config.IsEnabled() {+ if err := m.activateAuthorized(attempt.ctx, attempt); err != nil {+ m.mu.RLock()+ retained := attempt.entry.cleanupFailure != nil+ m.mu.RUnlock()+ if retained {+ cleanupErr = err+ }+ operationErr = err+ return+ }+ }+ m.mu.RLock()+ view = attempt.view+ m.mu.RUnlock()+ view.URL, view.State = "", "authorized"+ m.authorizationView(attempt, view)+}++func (m *Manager) activateAuthorized(ctx context.Context, attempt *oauthAttempt) error {+ leave, err := m.enter(ctx)+ if err != nil {+ return err+ }+ defer leave()+ return m.activateAuthorizedLocked(ctx, attempt)+}++// The caller owns the manager gate. This is also used after a cancellation+// drained an admitted commit, without re-entering that same gate.+func (m *Manager) activateAuthorizedLocked(ctx context.Context, attempt *oauthAttempt) error {+ entry := attempt.entry+ m.mu.RLock()+ current := m.entries[entry.name] == entry+ m.mu.RUnlock()+ if !current {+ return fail("MCP_AUTHORIZATION_REQUIRED", "MCP configuration changed during authorization")+ }+ if err := m.remove(ctx, entry.name, entry.owner); err != nil {+ return err+ }+ err := m.upsert(ctx, entry.name, entry.owner, entry.config, entry.status.Missing)+ m.mu.Lock()+ if next := m.entries[entry.name]; next != nil {+ attempt.entry = next+ copy := attempt.view+ next.status.Authorization = ©+ }+ m.mu.Unlock()+ m.changed()+ return err+}++func (m *Manager) acceptAuthorization(input mcpconfig.OAuthCallback) (*oauthAttempt, error) {+ if input.State == "" || len(input.State) > 512 || len(input.Code) > 8192 || len(input.Issuer) > 8192 || len(input.Error) > 256 || (input.Code == "") == (input.Error == "") {+ return nil, fail("MCP_INVALID_AUTHORIZATION", "Invalid OAuth callback")+ }+ m.mu.Lock()+ var attempt *oauthAttempt+ for _, candidate := range m.authorizations {+ if subtle.ConstantTimeCompare([]byte(candidate.state), []byte(input.State)) == 1 && !candidate.consumed && candidate.ctx.Err() == nil && candidate.view.Phase == "waiting-browser" {+ attempt = candidate+ break+ }+ }+ if attempt == nil {+ m.mu.Unlock()+ return nil, fail("MCP_INVALID_AUTHORIZATION", "OAuth state is invalid, expired or already used")+ }+ // Upstream validates the issuer before consuming the callback, including+ // error callbacks. A malformed callback cannot withdraw a valid browser flow.+ if attempt.issuer != "" && ((input.Issuer == "" && attempt.issuerRequired) || (input.Issuer != "" && input.Issuer != attempt.issuer)) {+ m.mu.Unlock()+ return nil, fail("MCP_INVALID_AUTHORIZATION", "OAuth callback issuer does not match the authorization server")+ }+ attempt.consumed = true+ view := attempt.view+ m.mu.Unlock()+ if input.Error == "access_denied" {+ attempt.cancel()+ } else if input.Error != "" {+ var err error = fail("MCP_OAUTH_FAILED", "MCP OAuth authorization was rejected")+ if input.Error == "invalid_client" {+ // Preserve the protocol error category for dynamic-client invalidation;+ // never copy callback descriptions or arbitrary error text into logs.+ err = &oauth2.RetrieveError{ErrorCode: "invalid_client", ErrorDescription: "MCP OAuth client registration was rejected"}+ }+ attempt.answer <- oauthCallbackResult{err: err}+ } else {+ view.URL, view.State = "", "connecting"+ view.Phase = "exchanging"+ m.authorizationView(attempt, view)+ m.mu.Lock()+ m.secrets[input.Code] = true+ m.mu.Unlock()+ attempt.answer <- oauthCallbackResult{value: &auth.AuthorizationResult{Code: input.Code, State: input.State, Iss: input.Issuer}}+ }+ return attempt, nil+}++// ReceiveAuthorization acknowledges a valid callback independently of token+// exchange, credential commit and managed reconnection, as upstream's HTTP route+// does. The owning flow and its existing status stream report the final outcome.+func (m *Manager) ReceiveAuthorization(input mcpconfig.OAuthCallback) (mcpconfig.OAuthCallbackReceipt, error) {+ _, err := m.acceptAuthorization(input)+ if err != nil {+ return mcpconfig.OAuthCallbackReceipt{}, err+ }+ state := "received"+ if input.Error != "" {+ state = "rejected"+ }+ return mcpconfig.OAuthCallbackReceipt{State: state}, nil+}++// CompleteAuthorization is the internal synchronous Go/test seam. It admits+// exactly the same callback, then waits for the owning authorization to settle.+func (m *Manager) CompleteAuthorization(ctx context.Context, input mcpconfig.OAuthCallback) (mcpconfig.OAuthAuthorization, error) {+ attempt, err := m.acceptAuthorization(input)+ if err != nil {+ return mcpconfig.OAuthAuthorization{}, err+ }+ select {+ case <-attempt.done:+ m.mu.RLock()+ view, err := attempt.view, attempt.err+ m.mu.RUnlock()+ return view, err+ case <-ctx.Done():+ return mcpconfig.OAuthAuthorization{}, ctx.Err()+ }+}++func (m *Manager) cancelOAuthAttempt(ctx context.Context, name string) error {+ m.mu.RLock()+ attempt := m.authorizations[name]+ m.mu.RUnlock()+ if attempt == nil {+ return nil+ }+ attempt.cancel()+ timer := time.NewTimer(CloseTimeout)+ defer timer.Stop()+ select {+ case <-attempt.done:+ case <-ctx.Done():+ return ctx.Err()+ case <-timer.C:+ return fail("MCP_CLEANUP_TIMEOUT", "OAuth authorization cleanup has not finished")+ }+ m.mu.Lock()+ if m.authorizations[name] == attempt {+ delete(m.authorizations, name)+ }+ m.mu.Unlock()+ return nil+}++func (m *Manager) CancelAuthorization(ctx context.Context, name string) (mcpconfig.Status, error) {+ leave, err := m.enter(ctx)+ if err != nil {+ return m.Status(), err+ }+ defer leave()+ err = m.cancelAuthorizationLocked(ctx, name)+ return m.Status(), err+}++func (m *Manager) cancelAuthorizationLocked(ctx context.Context, name string) error {+ m.mu.RLock()+ attempt := m.authorizations[name]+ m.mu.RUnlock()+ if err := m.cancelOAuthAttempt(ctx, name); err != nil {+ return err+ }+ if attempt == nil {+ return nil+ }+ m.mu.RLock()+ activate := attempt.committed && attempt.err == nil && m.entries[name] == attempt.entry && attempt.entry.config.IsEnabled()+ m.mu.RUnlock()+ if activate {+ return m.activateAuthorizedLocked(ctx, attempt)+ }+ return nil+}++// CancelAuthorizationAttempt never cancels a replacement attempt selected by+// another client. The public all-current-attempt HTTP operation remains separate.+func (m *Manager) CancelAuthorizationAttempt(ctx context.Context, name, id string) error {+ leave, err := m.enter(ctx)+ if err != nil {+ return err+ }+ defer leave()+ m.mu.RLock()+ attempt := m.authorizations[name]+ selected := attempt != nil && id != "" && attempt.view.ID == id+ m.mu.RUnlock()+ if !selected {+ return nil+ }+ return m.cancelAuthorizationLocked(ctx, name)+}++func (m *Manager) DisconnectAuthorization(ctx context.Context, name string) (mcpconfig.Status, error) {+ leave, err := m.enter(ctx)+ if err != nil {+ return m.Status(), err+ }+ defer leave()+ m.mu.RLock()+ entry := m.entries[name]+ m.mu.RUnlock()+ if entry == nil || entry.config.OAuth == nil {+ return m.Status(), fail("MCP_NOT_FOUND", "OAuth MCP server is not configured")+ }+ if err := m.cancelOAuthAttempt(ctx, name); err != nil {+ return m.Status(), err+ }+ if err := m.remove(ctx, name, entry.owner); err != nil {+ return m.Status(), err+ }+ var deleteErr error+ if m.oauthStore != nil {+ deleteErr = m.oauthStore.remove(ctx, entry.credentialKey())+ }+ // Even a failed credential deletion must leave the configured namespace+ // managed, so inspection and a later explicit retry remain possible.+ err = m.upsert(ctx, name, entry.owner, entry.config, entry.status.Missing)+ return m.Status(), errors.Join(deleteErr, err)+}diff --git a/internal/mcpclient/oauth_callback.go b/internal/mcpclient/oauth_callback.gonew file mode 100644index 0000000..abdb205--- /dev/null+++ b/internal/mcpclient/oauth_callback.go@@ -0,0 +1,81 @@+package mcpclient++import (+ "context"+ "net/http"+ "net/url"+ "strings"++ mcpconfig "go-bot/mcp"+)++func validateOAuthCallback(redirect string) error {+ if !validOAuthURL(redirect) {+ return fail("MCP_INVALID_CALLBACK", "OAuth callback must use HTTPS or loopback HTTP")+ }+ u, _ := url.Parse(redirect)+ account := strings.TrimPrefix(u.Path, mcpconfig.OAuthCallbackPath)+ if !strings.HasPrefix(u.Path, mcpconfig.OAuthCallbackPath) || account == "" || strings.Contains(account, "/") || u.RawQuery != "" || u.ForceQuery {+ return fail("MCP_INVALID_CALLBACK", "Invalid Controller OAuth callback path")+ }+ return nil+}++// ControllerOAuth belongs inside Host authentication. Only the Controller+// supplies this verified routing metadata, never a plugin or a model argument.+// Remembering the actual route lets a later background plugin action start a+// flow without guessing a public address or persisting deployment metadata.+func (m *Manager) ControllerOAuth(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if redirect := r.Header.Get(mcpconfig.OAuthCallbackHeader); redirect != "" {+ if err := validateOAuthCallback(redirect); err != nil {+ http.Error(w, "Invalid Controller OAuth callback", http.StatusBadRequest)+ return+ }+ m.mu.Lock()+ if !m.closed {+ m.oauthCallback = redirect+ }+ m.mu.Unlock()+ }+ next.ServeHTTP(w, r)+ })+}++// StartAuthorization mirrors the plugin start contract: admission returns the+// current attempt immediately; URL preparation and completion publish status.+// The browser-facing HTTP Authorize operation additionally waits for its URL.+func (m *Manager) StartAuthorization(ctx context.Context, name string) (mcpconfig.OAuthAttemptView, error) {+ if err := ctx.Err(); err != nil {+ return mcpconfig.OAuthAttemptView{}, err+ }+ if err := m.ctx.Err(); err != nil {+ return mcpconfig.OAuthAttemptView{}, err+ }+ m.mu.RLock()+ redirect := m.oauthCallback+ if entry := m.entries[name]; entry != nil && entry.cleanupFailure != nil {+ m.mu.RUnlock()+ return mcpconfig.OAuthAttemptView{}, fail("MCP_CLEANUP_INCOMPLETE", "MCP authorization cleanup failed; restart the Host before authorizing again")+ }+ if previous := m.authorizations[name]; previous != nil {+ switch previous.view.Phase {+ case "starting", "waiting-browser", "exchanging", "committing":+ view := previous.view.AttemptView()+ m.mu.RUnlock()+ return *view, nil+ }+ }+ m.mu.RUnlock()+ if redirect == "" {+ return mcpconfig.OAuthAttemptView{}, fail("MCP_OAUTH_CALLBACK_UNAVAILABLE", "Starting MCP OAuth requires a verified Controller callback; connect through HTTPS or loopback HTTP first")+ }+ attempt, _, err := m.beginAuthorization(ctx, name, redirect)+ if err != nil {+ return mcpconfig.OAuthAttemptView{}, err+ }+ m.mu.RLock()+ view := attempt.view.AttemptView()+ m.mu.RUnlock()+ return *view, nil+}diff --git a/internal/mcpclient/oauth_callback_contract_test.go b/internal/mcpclient/oauth_callback_contract_test.gonew file mode 100644index 0000000..7258b03--- /dev/null+++ b/internal/mcpclient/oauth_callback_contract_test.go@@ -0,0 +1,244 @@+package mcpclient++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ mcpconfig "go-bot/mcp"+)++type oauthTokenExchangeBarrier struct {+ endpoint string+ entered, release chan struct{}+ once sync.Once+}++func (b *oauthTokenExchangeBarrier) RoundTrip(request *http.Request) (*http.Response, error) {+ if request.URL.String() == b.endpoint && request.Method == http.MethodPost {+ b.once.Do(func() { close(b.entered) })+ select {+ case <-b.release:+ case <-request.Context().Done():+ return nil, request.Context().Err()+ }+ }+ return http.DefaultTransport.RoundTrip(request)+}++func TestOAuthHTTPCallbackAcknowledgesBeforeExchangeAndDoesNotOwnTheFlow(t *testing.T) {+ f := oauthServiceFixture(t)+ barrier := &oauthTokenExchangeBarrier{endpoint: f.provider.URL + "/token", entered: make(chan struct{}), release: make(chan struct{})}+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir(), Connection: ConnectionOptions{HTTPClient: &http.Client{Transport: barrier}}})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), f.settings("fixture")); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ callback := visitOAuthAuthorization(t, view)+ data, _ := json.Marshal(callback)+ requestCtx, requestCancel := context.WithCancel(ctx)+ req := httptest.NewRequest(http.MethodPost, mcpconfig.InternalPath+"/oauth/callback", bytes.NewReader(data)).WithContext(requestCtx)+ result := httptest.NewRecorder()+ answered := make(chan struct{})+ go func() { manager.Handler().ServeHTTP(result, req); close(answered) }()+ select {+ case <-answered:+ case <-ctx.Done():+ t.Fatal("callback waited for token exchange", ctx.Err())+ }+ requestCancel() // Closing the browser page does not cancel the admitted flow.+ var receipt mcpconfig.OAuthCallbackReceipt+ if result.Code != http.StatusOK || json.Unmarshal(result.Body.Bytes(), &receipt) != nil || receipt.State != "received" {+ t.Fatal("callback did not acknowledge admission")+ }+ select {+ case <-barrier.entered:+ case <-ctx.Done():+ t.Fatal("actual token exchange did not start", ctx.Err())+ }+ if row, err := manager.oauthStore.credentials.ReadRecord(oauthGrantKey("oauth")); err != nil || row != nil {+ t.Fatal("receipt was confused with a credential commit", err)+ }+ if _, err := manager.ReceiveAuthorization(callback); err == nil {+ t.Fatal("pending callback could be replayed")+ }+ close(barrier.release)+ for {+ changed, _ := manager.Changes()+ servers := manager.Status().Servers+ if len(servers) == 1 && servers[0].State == "connected" && servers[0].Authorization != nil && servers[0].Authorization.Phase == "authorized" {+ break+ }+ select {+ case <-changed:+ case <-ctx.Done():+ t.Fatal("browser disconnection cancelled the accepted authorization", ctx.Err())+ }+ }+}++func TestOAuthInvalidCallbacksLeaveTheSameBrowserFlowUsable(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), f.settings("test-client")); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ callback := visitOAuthAuthorization(t, view)+ for _, scenario := range []struct {+ name string+ change func(*mcpconfig.OAuthCallback)+ }{+ {"wrong-state", func(v *mcpconfig.OAuthCallback) { v.State += "-wrong" }},+ {"wrong-issuer", func(v *mcpconfig.OAuthCallback) { v.Issuer += "/" }},+ {"missing-required-issuer", func(v *mcpconfig.OAuthCallback) { v.Issuer = "" }},+ {"neither-code-nor-error", func(v *mcpconfig.OAuthCallback) { v.Code = "" }},+ {"both-code-and-error", func(v *mcpconfig.OAuthCallback) { v.Error = "access_denied" }},+ {"unverified-denial", func(v *mcpconfig.OAuthCallback) {+ v.Code = ""+ v.Error = "access_denied"+ v.Issuer = "https://unrelated.example"+ }},+ } {+ t.Run(scenario.name, func(t *testing.T) {+ invalid := callback+ scenario.change(&invalid)+ if _, err := manager.CompleteAuthorization(ctx, invalid); err == nil {+ t.Fatal("invalid callback admitted")+ }+ manager.mu.RLock()+ attempt := manager.authorizations["oauth"]+ unchanged := attempt != nil && attempt.view.ID == view.ID && attempt.view.Phase == "waiting-browser" && !attempt.consumed && attempt.ctx.Err() == nil+ manager.mu.RUnlock()+ if !unchanged {+ t.Fatal("rejected callback consumed or cancelled the pending flow")+ }+ f.mu.Lock()+ exchanged := f.lastAccess != ""+ f.mu.Unlock()+ if exchanged {+ t.Fatal("rejected callback exchanged an authorization code")+ }+ })+ }+ if result, err := manager.CompleteAuthorization(ctx, callback); err != nil || result.Phase != "authorized" {+ t.Fatalf("valid callback after rejected inputs: phase=%s err=%v", result.Phase, err)+ }+ if _, err := manager.CompleteAuthorization(ctx, callback); err == nil {+ t.Fatal("accepted callback could be replayed")+ }+}++func TestOAuthCallbackIssuerUsesUpstreamDecisionTable(t *testing.T) {+ for _, omitted := range []bool{false, true} {+ for _, returned := range []bool{false, true} {+ name := "advertised"+ if omitted {+ name = "not-advertised"+ }+ if returned {+ name += "/returned"+ } else {+ name += "/absent"+ }+ t.Run(name, func(t *testing.T) {+ f := oauthServiceFixture(t)+ f.omitIssuerAdvertisement.Store(omitted)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), f.settings("fixture")); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ callback := visitOAuthAuthorization(t, view)+ if !returned {+ callback.Issuer = ""+ }+ result, err := manager.CompleteAuthorization(ctx, callback)+ if !omitted && !returned {+ if err == nil {+ t.Fatal("required iss was not enforced")+ }+ callback.Issuer = f.provider.URL+ result, err = manager.CompleteAuthorization(ctx, callback)+ }+ if err != nil || result.Phase != "authorized" {+ t.Fatalf("issuer table: phase=%s err=%v", result.Phase, err)+ }+ })+ }+ }+}++func TestOAuthCallbackSeparatesDeclineProviderFailureAndRejectedClient(t *testing.T) {+ for _, scenario := range []struct {+ code, phase string+ registrations int32+ }{+ {"access_denied", "cancelled", 1},+ {"server_error", "failed", 1},+ {"invalid_client", "failed", 2},+ {"private-provider-error-must-not-be-displayed", "failed", 1},+ } {+ t.Run(scenario.code, func(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), f.settings("")); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)+ defer cancel()+ redirect := "http://127.0.0.1:9090" + mcpconfig.OAuthCallbackPath + "alice"+ view, err := manager.Authorize(ctx, "oauth", redirect)+ if err != nil {+ t.Fatal(err)+ }+ callback := visitOAuthAuthorization(t, view)+ callback.Code, callback.Error = "", scenario.code+ result, err := manager.CompleteAuthorization(ctx, callback)+ if result.Phase != scenario.phase {+ t.Fatalf("callback outcome: phase=%s err=%v", result.Phase, err)+ }+ if scenario.phase == "failed" && err == nil {+ t.Fatal("provider error was not reported")+ }+ if strings.Contains(result.Error, "private-provider-error") || (err != nil && strings.Contains(err.Error(), "private-provider-error")) {+ t.Fatal("untrusted provider error copied into diagnostics")+ }+ if grant, _ := manager.oauthStore.credentials.ReadRecord(oauthGrantKey("oauth")); grant != nil {+ t.Fatal("failed flow committed a grant")+ }+ view, err = manager.Authorize(ctx, "oauth", redirect)+ if err != nil || f.registrations.Load() != scenario.registrations {+ t.Fatalf("client registration lifecycle: calls=%d err=%v", f.registrations.Load(), err)+ }+ if result, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err != nil || result.Phase != "authorized" {+ t.Fatalf("retry could not authorize: phase=%s err=%v", result.Phase, err)+ }+ })+ }+}diff --git a/internal/mcpclient/oauth_callback_test.go b/internal/mcpclient/oauth_callback_test.gonew file mode 100644index 0000000..e1a5771--- /dev/null+++ b/internal/mcpclient/oauth_callback_test.go@@ -0,0 +1,116 @@+package mcpclient++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "net/url"+ "sync"+ "testing"+ "time"++ mcpconfig "go-bot/mcp"+)++type oauthDiscoveryBarrier struct {+ entered chan struct{}+ release chan struct{}+ once sync.Once+}++func (b *oauthDiscoveryBarrier) RoundTrip(r *http.Request) (*http.Response, error) {+ b.once.Do(func() { close(b.entered) })+ select {+ case <-b.release:+ return http.DefaultTransport.RoundTrip(r)+ case <-r.Context().Done():+ return nil, r.Context().Err()+ }+}++func TestOAuthPluginStartRequiresVerifiedChannelAndAdmitsBeforeDiscovery(t *testing.T) {+ f := oauthServiceFixture(t)+ cwd := t.TempDir()+ barrier := &oauthDiscoveryBarrier{entered: make(chan struct{}), release: make(chan struct{})}+ manager := NewManager(t.Context(), ManagerOptions{CWD: cwd, Connection: ConnectionOptions{HTTPClient: &http.Client{Transport: barrier}}})+ defer manager.Close()+ settings := f.settings("test-client")+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ if _, err := manager.StartAuthorization(t.Context(), "oauth"); err == nil {+ t.Fatal("plugin guessed a callback without a Controller channel")+ } else {+ var detail *Error+ if !errors.As(err, &detail) || detail.Code != "MCP_OAUTH_CALLBACK_UNAVAILABLE" {+ t.Fatal("wrong absent-channel failure", err)+ }+ }+ observe := func(redirect string) int {+ t.Helper()+ r := httptest.NewRequest(http.MethodGet, "http://private-host/v1/host/stream", nil)+ r.Header.Set(mcpconfig.OAuthCallbackHeader, redirect)+ out := httptest.NewRecorder()+ manager.ControllerOAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) })).ServeHTTP(out, r)+ return out.Code+ }+ if observe("http://public-controller.example"+mcpconfig.OAuthCallbackPath+"alice") != http.StatusBadRequest {+ t.Fatal("non-loopback HTTP enabled OAuth")+ }+ redirect := "http://127.0.0.1:9090" + mcpconfig.OAuthCallbackPath + "alice"+ if observe(redirect) != http.StatusNoContent {+ t.Fatal("verified channel rejected")+ }+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ view, err := manager.StartAuthorization(ctx, "oauth")+ if err != nil || view.ID == "" || view.Phase != "starting" {+ t.Fatalf("start did not admit independently of blocked discovery: %+v %v", view, err)+ }+ select {+ case <-barrier.entered:+ case <-ctx.Done():+ t.Fatal("actual discovery did not start", ctx.Err())+ }+ secondRedirect := "http://127.0.0.1:9091" + mcpconfig.OAuthCallbackPath + "alice"+ if observe(secondRedirect) != http.StatusNoContent {+ t.Fatal("new Controller route rejected")+ }+ if second, err := manager.StartAuthorization(ctx, "oauth"); err != nil || second.ID != view.ID {+ t.Fatal("route refresh replaced in-flight authorization", err)+ }+ close(barrier.release)+ var authorization mcpconfig.OAuthAuthorization+ for {+ changed, _ := manager.Changes()+ current := manager.Status().Servers[0].Authorization+ if current != nil && current.Phase == "waiting-browser" {+ authorization = *current+ break+ }+ select {+ case <-changed:+ case <-ctx.Done():+ t.Fatal("discovery did not publish URL", ctx.Err())+ }+ }+ parsed, _ := url.Parse(authorization.URL)+ if parsed.Query().Get("redirect_uri") != redirect {+ t.Fatal("a route refresh changed a running flow's bound redirect")+ }+ if result, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, authorization)); err != nil || result.State != "authorized" {+ t.Fatalf("async start could not finish actual exchange: %+v %v", result, err)+ }+ if err := manager.Close(); err != nil {+ t.Fatal(err)+ }+ reopened := NewManager(t.Context(), ManagerOptions{CWD: cwd})+ defer reopened.Close()+ if _, err := reopened.Apply(ctx, settings); err != nil {+ t.Fatal(err)+ }+ if _, err := reopened.StartAuthorization(ctx, "oauth"); err == nil {+ t.Fatal("live Controller callback was incorrectly persisted as deployment configuration")+ }+}diff --git a/internal/mcpclient/oauth_clients.go b/internal/mcpclient/oauth_clients.gonew file mode 100644index 0000000..db10cd8--- /dev/null+++ b/internal/mcpclient/oauth_clients.go@@ -0,0 +1,292 @@+package mcpclient++import (+ "bytes"+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "io"+ "net/http"+ "net/url"+ "reflect"+ "strings"+ "sync"++ "github.com/modelcontextprotocol/go-sdk/oauthex"+ "go-bot/internal/credentials"+)++// Registrations outlive grants, including a cancelled browser flow. The key+// binds resource, issuer, redirect URI and configured client ID/scope.+type oauthClientRegistration struct {+ Issuer string `json:"issuer"`+ Response *oauthex.ClientRegistrationResponse `json:"information"`+}++func (m *Manager) oauthClientKey(entry *serverEntry, issuer, redirect string) string {+ var clientID *string+ if entry.config.OAuth.ClientID != "" {+ clientID = &entry.config.OAuth.ClientID+ }+ // JSON.stringify([serverUrl, issuer, redirectUri, clientId, scope])+ // uses null for omitted optional array values and does not HTML-escape URLs.+ var encoded bytes.Buffer+ encoder := json.NewEncoder(&encoded)+ encoder.SetEscapeHTML(false)+ _ = encoder.Encode([]any{entry.config.URL, issuer, redirect, clientID, entry.config.OAuth.RequestedScope()})+ data := bytes.TrimSuffix(encoded.Bytes(), []byte("\n"))+ sum := sha256.Sum256(data)+ return oauthGrantKey(entry.credentialKey()) + "-client-" + hex.EncodeToString(sum[:])+}++func (s *oauthGrantStore) client(key string) (oauthClientRegistration, bool, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.readClient(key)+}++// Reads may run inside the shared credential mutation callback. They inspect+// committed data without reentering the mutation queue or its admission lock.+func (s *oauthGrantStore) readClient(key string) (oauthClientRegistration, bool, error) {+ record, err := s.credentials.ReadRecord(oauthClientRecordKey(key))+ var registration oauthClientRegistration+ if err != nil || record == nil {+ return registration, false, err+ }+ if err = decodeOAuthRecord(record, "mcp-oauth-client", ®istration); err != nil {+ return registration, false, authorizationFailure("binding", "Stored OAuth client information is incompatible")+ }+ if registration.Response == nil || registration.Response.ClientID == "" || !validOAuthURL(registration.Issuer) {+ return registration, false, fail("MCP_OAUTH_STORE_INVALID", "Stored OAuth client registration is incomplete")+ }+ return registration, true, nil+}++func (s *oauthGrantStore) saveClient(ctx context.Context, key string, registration oauthClientRegistration) error {+ if registration.Response == nil || registration.Response.ClientID == "" || !validOAuthURL(registration.Issuer) {+ return fail("MCP_OAUTH_STORE_INVALID", "Cannot persist incomplete OAuth client registration")+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ record, err := oauthRecord("mcp-oauth-client", registration)+ if err != nil {+ return err+ }+ _, err = s.credentials.ModifyRecord(ctx, oauthClientRecordKey(key), func(current *credentials.Record) (*credentials.Record, error) {+ if current != nil {+ var previous oauthClientRegistration+ if err := decodeOAuthRecord(current, "mcp-oauth-client", &previous); err != nil {+ return nil, fail("MCP_OAUTH_FAILED", "MCP OAuth client record is incompatible")+ }+ }+ return record, nil+ })+ return err+}++func (s *oauthGrantStore) invalidateClient(ctx context.Context, key string, known oauthClientRegistration) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.credentials.UpdateRecords(ctx, func(records map[string]credentials.Record) error {+ record, found := records[oauthClientRecordKey(key)]+ if !found {+ return nil+ }+ var current oauthClientRegistration+ if err := decodeOAuthRecord(&record, "mcp-oauth-client", ¤t); err != nil {+ return err+ }+ if reflect.DeepEqual(current, known) {+ delete(records, oauthClientRecordKey(key))+ }+ return nil+ })+}++// The official SDK has no registration persistence hook. This transport caches+// only its DCR exchange, preserving the SDK's original registration response and+// auth-method selection. Discovery, validation, PKCE and exchange remain SDK-owned.+// A new response is persisted only when the SDK admits it to its browser callback.+type oauthRegistrationTransport struct {+ base http.RoundTripper+ store *oauthGrantStore+ key func(string) string+ resource, redirect string+ remember func(string)+ mu sync.Mutex+ metadata oauthex.AuthServerMeta+ metadataDiscovered bool+ metadataRaw json.RawMessage+ preregistered *oauthex.ClientCredentials+ used *oauthClientRegistration+ usedKey string+ fromCache bool+}++func (m *Manager) registrationClient(entry *serverEntry, redirect string) (*http.Client, *oauthRegistrationTransport) {+ client := m.oauthHTTPClient(entry.config.OAuth)+ base := client.Transport+ if base == nil {+ base = http.DefaultTransport+ }+ u, _ := url.Parse(entry.config.URL)+ u.Path = ""+ u.RawPath = ""+ u.RawQuery = ""+ u.ForceQuery = false+ u.Fragment = ""+ issuer := u.String()+ cache := &oauthRegistrationTransport{base: base, store: m.oauthStore, resource: entry.config.URL, redirect: redirect, key: func(issuer string) string { return m.oauthClientKey(entry, issuer, redirect) },+ metadata: oauthex.AuthServerMeta{Issuer: issuer, AuthorizationEndpoint: issuer + "/authorize", TokenEndpoint: issuer + "/token", RegistrationEndpoint: issuer + "/register"},+ remember: func(secret string) {+ if secret != "" {+ m.mu.Lock()+ m.secrets[secret] = true+ m.mu.Unlock()+ }+ },+ }+ client.Transport = cache+ return client, cache+}++type replayOAuthBody struct {+ io.Reader+ io.Closer+}++func peekOAuthJSON(response *http.Response) ([]byte, error) {+ data, err := io.ReadAll(io.LimitReader(response.Body, (1<<20)+1))+ if err != nil {+ response.Body.Close()+ return nil, err+ }+ response.Body = replayOAuthBody{Reader: io.MultiReader(bytes.NewReader(data), response.Body), Closer: response.Body}+ if len(data) > 1<<20 {+ return nil, nil+ }+ return data, nil+}++func (c *oauthRegistrationTransport) RoundTrip(request *http.Request) (*http.Response, error) {+ c.mu.Lock()+ metadata := c.metadata+ c.mu.Unlock()+ registrationRequest := request.Method == http.MethodPost && request.URL.String() == metadata.RegistrationEndpoint+ if registrationRequest {+ key := c.key(metadata.Issuer)+ registration, found, err := c.store.client(key)+ if err != nil {+ return nil, err+ }+ if found && registration.Issuer == metadata.Issuer {+ body, err := json.Marshal(registration.Response)+ if err != nil {+ return nil, err+ }+ c.mu.Lock()+ c.used, c.usedKey, c.fromCache = ®istration, key, true+ c.mu.Unlock()+ c.remember(registration.Response.ClientSecret)+ return &http.Response{StatusCode: http.StatusCreated, Status: "201 Created", Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(bytes.NewReader(body)), ContentLength: int64(len(body)), Request: request}, nil+ }+ }+ response, err := c.base.RoundTrip(request)+ if err != nil {+ return response, err+ }+ if response.StatusCode < 200 || response.StatusCode >= 300 {+ return response, nil+ }+ discovery := request.Method == http.MethodGet && (strings.Contains(request.URL.Path, "/.well-known/oauth-authorization-server") || strings.Contains(request.URL.Path, "/.well-known/openid-configuration"))+ if !registrationRequest && !discovery {+ return response, nil+ }+ data, err := peekOAuthJSON(response)+ if err != nil {+ return nil, err+ }+ if len(data) == 0 {+ return response, nil+ }+ if discovery {+ var next oauthex.AuthServerMeta+ if json.Unmarshal(data, &next) == nil && next.Issuer != "" && next.AuthorizationEndpoint != "" && next.TokenEndpoint != "" {+ // The SDK validates this document before it can issue the matching+ // registration request. We do not publish or persist metadata here.+ c.mu.Lock()+ c.metadata = next+ c.metadataDiscovered = true+ c.metadataRaw = append(json.RawMessage(nil), data...)+ c.mu.Unlock()+ }+ } else {+ var registered oauthex.ClientRegistrationResponse+ if json.Unmarshal(data, ®istered) == nil && registered.ClientID != "" {+ candidate := oauthClientRegistration{Issuer: metadata.Issuer, Response: ®istered}+ c.mu.Lock()+ c.used, c.usedKey, c.fromCache = &candidate, c.key(metadata.Issuer), false+ c.mu.Unlock()+ c.remember(registered.ClientSecret)+ }+ }+ return response, nil+}++// Only metadata actually discovered and subsequently admitted by the SDK is an+// issuer baseline. The fallback endpoints used during discovery are not one.+func (c *oauthRegistrationTransport) callbackIssuer() (string, bool) {+ c.mu.Lock()+ defer c.mu.Unlock()+ if !c.metadataDiscovered {+ return "", false+ }+ return c.metadata.Issuer, c.metadata.AuthorizationResponseIssParameterSupported+}++func (c *oauthRegistrationTransport) authorizationMetadata() (oauthex.AuthServerMeta, json.RawMessage) {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.metadata, append(json.RawMessage(nil), c.metadataRaw...)+}++func (c *oauthRegistrationTransport) admit(ctx context.Context, authorizationURL string) error {+ c.mu.Lock()+ used, key, cached, metadata := c.used, c.usedKey, c.fromCache, c.metadata+ c.mu.Unlock()+ if used == nil && c.preregistered != nil {+ information := &oauthex.ClientRegistrationResponse{ClientID: c.preregistered.ClientID, ClientRegistrationMetadata: oauthex.ClientRegistrationMetadata{TokenEndpointAuthMethod: "none", RedirectURIs: []string{c.redirect}}}+ if c.preregistered.ClientSecretAuth != nil {+ information.ClientSecret = c.preregistered.ClientSecretAuth.ClientSecret+ information.TokenEndpointAuthMethod = "client_secret_post"+ }+ used = &oauthClientRegistration{Issuer: metadata.Issuer, Response: information}+ key = c.key(metadata.Issuer)+ }+ if used == nil || cached {+ return nil+ }+ actual, err := url.Parse(authorizationURL)+ if err != nil {+ return err+ }+ expected, err := url.Parse(metadata.AuthorizationEndpoint)+ if err != nil {+ return err+ }+ if actual.Scheme != expected.Scheme || actual.Host != expected.Host || actual.Path != expected.Path || actual.Query().Get("client_id") != used.Response.ClientID || actual.Query().Get("redirect_uri") != c.redirect {+ return fail("MCP_OAUTH_CLIENT_BINDING", "OAuth client registration does not match the admitted authorization")+ }+ return c.store.saveClient(ctx, key, *used)+}++func (c *oauthRegistrationTransport) invalidate(ctx context.Context) error {+ c.mu.Lock()+ used, key := c.used, c.usedKey+ c.mu.Unlock()+ if used == nil {+ return nil+ }+ return c.store.invalidateClient(ctx, key, *used)+}diff --git a/internal/mcpclient/oauth_clients_test.go b/internal/mcpclient/oauth_clients_test.gonew file mode 100644index 0000000..702ee90--- /dev/null+++ b/internal/mcpclient/oauth_clients_test.go@@ -0,0 +1,202 @@+package mcpclient++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/modelcontextprotocol/go-sdk/oauthex"+ "go-bot/internal/credentials"+ mcpconfig "go-bot/mcp"+)++func TestOAuthClientSaveDoesNotOverwriteAnotherCredentialKind(t *testing.T) {+ store, err := newOAuthGrantStore(filepath.Join(t.TempDir(), credentials.Filename))+ if err != nil {+ t.Fatal(err)+ }+ defer store.credentials.Close()+ key := "mcp-client/mail-client-test"+ if _, err := store.credentials.ModifyRecord(t.Context(), key, func(*credentials.Record) (*credentials.Record, error) {+ return &credentials.Record{Kind: "api-key"}, nil+ }); err != nil {+ t.Fatal(err)+ }+ registration := oauthClientRegistration{Issuer: "https://issuer.example", Response: &oauthex.ClientRegistrationResponse{ClientID: "fixture"}}+ if err := store.saveClient(t.Context(), key, registration); err == nil {+ t.Fatal("incompatible credential record overwritten")+ }+ if record, err := store.credentials.ReadRecord(key); err != nil || record == nil || record.Kind != "api-key" {+ t.Fatal("original record was lost", err)+ }+}++func TestOAuthRegistrationSurvivesCancellationRestartAndSignOut(t *testing.T) {+ t.Run("public", func(t *testing.T) { testOAuthRegistrationLifecycle(t, false) })+ t.Run("confidential", func(t *testing.T) { testOAuthRegistrationLifecycle(t, true) })+}++func testOAuthRegistrationLifecycle(t *testing.T, confidential bool) {+ t.Helper()+ f := oauthServiceFixture(t)+ f.dynamicConfidential.Store(confidential)+ cwd := t.TempDir()+ manager := NewManager(t.Context(), ManagerOptions{CWD: cwd})+ t.Cleanup(func() { _ = manager.Close() })+ settings := f.settings("")+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)+ defer cancel()+ redirect := "http://127.0.0.1:9090" + mcpconfig.OAuthCallbackPath + "alice"+ view, err := manager.Authorize(ctx, "oauth", redirect)+ if err != nil || view.State != "pending" || f.registrations.Load() != 1 {+ t.Fatalf("initial dynamic registration: %+v, %v, calls=%d", view, err, f.registrations.Load())+ }+ if _, err := manager.CancelAuthorization(ctx, "oauth"); err != nil {+ t.Fatal(err)+ }+ if _, found, err := manager.oauthStore.get("oauth", manager.entries["oauth"].oauthBinding); err != nil || found {+ t.Fatal("cancelled consent persisted a grant", err)+ }+ if err := manager.Close(); err != nil {+ t.Fatal(err)+ }+ manager = NewManager(t.Context(), ManagerOptions{CWD: cwd})+ if _, err := manager.Apply(ctx, settings); err != nil {+ t.Fatal(err)+ }+ view, err = manager.Authorize(ctx, "oauth", redirect)+ if err != nil || f.registrations.Load() != 1 {+ t.Fatalf("restart registered a second client before consent: %v, calls=%d", err, f.registrations.Load())+ }+ if _, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err != nil {+ t.Fatal(err)+ }+ if _, err := manager.DisconnectAuthorization(ctx, "oauth"); err != nil {+ t.Fatal(err)+ }+ if status := manager.Status().Servers[0]; status.State != "waiting-authorization" {+ t.Fatalf("sign-out did not withdraw authorized connection: %+v", status)+ }+ view, err = manager.Authorize(ctx, "oauth", redirect)+ if err != nil || f.registrations.Load() != 1 {+ t.Fatalf("sign-out discarded registration: %v, calls=%d", err, f.registrations.Load())+ }+ if _, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err != nil {+ t.Fatal(err)+ }+ if status := manager.Status().Servers[0]; status.State != "connected" {+ t.Fatalf("cached DCR response did not authorize real SDK connection: %+v", status)+ }+ if _, err := manager.Authorize(ctx, "oauth", redirect+"-new"); err != nil || f.registrations.Load() != 2 {+ t.Fatalf("different callback reused previous registration: %v, calls=%d", err, f.registrations.Load())+ }+}++func TestOAuthRejectedClientIsRegisteredAgainOnNextExplicitAttempt(t *testing.T) {+ f := oauthServiceFixture(t)+ f.dynamicConfidential.Store(true)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), f.settings("")); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)+ defer cancel()+ redirect := "http://127.0.0.1:9090" + mcpconfig.OAuthCallbackPath + "alice"+ view, err := manager.Authorize(ctx, "oauth", redirect)+ if err != nil {+ t.Fatal(err)+ }+ f.denyClient.Store(true)+ if _, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err == nil {+ t.Fatal("invalid_client exchange unexpectedly authorized")+ } else if strings.Contains(err.Error(), "private-dynamic-client-secret") {+ t.Fatal("learned registration secret leaked through callback error")+ }+ f.denyClient.Store(false)+ view, err = manager.Authorize(ctx, "oauth", redirect)+ if err != nil || f.registrations.Load() != 2 {+ t.Fatalf("rejected client registration was reused: %v, calls=%d", err, f.registrations.Load())+ }+ if _, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err != nil {+ t.Fatal(err)+ }+}++func TestOAuthRepeatedStartRetainsTheActiveBrowserFlow(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), f.settings("")); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)+ defer cancel()+ redirect := "http://127.0.0.1:9090" + mcpconfig.OAuthCallbackPath + "alice"+ first, err := manager.Authorize(ctx, "oauth", redirect)+ if err != nil {+ t.Fatal(err)+ }+ second, err := manager.Authorize(ctx, "oauth", redirect+"-different-origin-request")+ if err != nil || second.ID != first.ID || second.URL != first.URL || f.registrations.Load() != 1 {+ t.Fatalf("repeated start withdrew the active browser flow: %v", err)+ }+ if result, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, first)); err != nil || result.State != "authorized" {+ t.Fatalf("initial consent was invalidated by another start: %+v %v", result, err)+ }+}++func TestOAuthRegistrationPersistenceAndInvalidationBindings(t *testing.T) {+ path := filepath.Join(t.TempDir(), "credentials.json")+ store, _ := newOAuthGrantStore(path)+ registration := oauthClientRegistration{Issuer: "https://issuer.example", Response: &oauthex.ClientRegistrationResponse{+ ClientID: "registered", ClientSecret: "private-registration-secret", ClientIDIssuedAt: time.Unix(1700000000, 0), ClientSecretExpiresAt: time.Now().Add(time.Hour).Truncate(time.Second),+ ClientRegistrationMetadata: oauthex.ClientRegistrationMetadata{TokenEndpointAuthMethod: "client_secret_post"},+ }}+ if err := store.saveClient(t.Context(), "key", registration); err != nil {+ t.Fatal(err)+ }+ reopened, err := newOAuthGrantStore(path)+ if err != nil {+ t.Fatal(err)+ }+ stored, err := reopened.credentials.ReadRecord(oauthClientRecordKey("key"))+ if err != nil || stored == nil {+ t.Fatal("client registration missing from shared credential service", err)+ }+ info, _ := os.Stat(path)+ if info.Mode().Perm() != 0600 {+ t.Fatal("registration secret file is not private")+ }+ loaded, found, err := reopened.client("key")+ if err != nil || !found || loaded.Response.ClientSecret != registration.Response.ClientSecret || loaded.Response.TokenEndpointAuthMethod != "client_secret_post" || !loaded.Response.ClientIDIssuedAt.Equal(registration.Response.ClientIDIssuedAt) {+ t.Fatal("cached registration lost secret, auth method or timestamp", err)+ }+ previous := loaded+ replacement := registration+ response := *registration.Response+ response.ClientID = "replacement"+ replacement.Response = &response+ if err := store.saveClient(t.Context(), "key", replacement); err != nil {+ t.Fatal(err)+ }+ if err := store.invalidateClient(t.Context(), "key", previous); err != nil {+ t.Fatal(err)+ }+ if current, found, err := store.client("key"); err != nil || !found || current.Response.ClientID != "replacement" {+ t.Fatal("stale rejection deleted replacement registration", err)+ }+ response.ClientSecretExpiresAt = time.Now().Add(-time.Hour)+ if err := store.saveClient(t.Context(), "key", replacement); err != nil {+ t.Fatal(err)+ }+ if current, found, err := store.client("key"); err != nil || !found || current.Response.ClientSecretExpiresAt.Unix() != response.ClientSecretExpiresAt.Unix() {+ t.Fatal("client provider changed the upstream opaque registration read contract", err)+ }+}diff --git a/internal/mcpclient/oauth_commit_test.go b/internal/mcpclient/oauth_commit_test.gonew file mode 100644index 0000000..75210d1--- /dev/null+++ b/internal/mcpclient/oauth_commit_test.go@@ -0,0 +1,169 @@+package mcpclient++import (+ "context"+ "go-bot/internal/credentials"+ "path/filepath"+ "testing"+ "time"++ mcpconfig "go-bot/mcp"+)++func TestOAuthAdmittedCommitDrainsBeforeCancelSignOutOrShutdown(t *testing.T) {+ for _, operation := range []string{"cancel", "sign-out", "shutdown"} {+ t.Run(operation, func(t *testing.T) {+ f := oauthServiceFixture(t)+ cwd := t.TempDir()+ manager := NewManager(t.Context(), ManagerOptions{CWD: cwd})+ defer manager.Close()+ settings := f.settings("test-client")+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ callback := visitOAuthAuthorization(t, view)+ // Hold the shared Go credential provider immediately before publication. This+ // observes actual SDK exchange/commit admission, without timing sleeps+ // or replacing the credential writer with a successful test double.+ barrier, releaseBarrier := make(chan struct{}), make(chan struct{})+ barrierDone := make(chan error, 1)+ go func() {+ _, err := manager.oauthStore.credentials.ModifyRecord(t.Context(), "mcp/commit-barrier", func(*credentials.Record) (*credentials.Record, error) {+ close(barrier)+ <-releaseBarrier+ return &credentials.Record{Kind: "api-key"}, nil+ })+ barrierDone <- err+ }()+ <-barrier+ locked := true+ defer func() {+ if locked {+ close(releaseBarrier)+ <-barrierDone+ }+ }()+ type completion struct {+ view mcpconfig.OAuthAuthorization+ err error+ }+ completed := make(chan completion, 1)+ go func() {+ result, err := manager.CompleteAuthorization(ctx, callback)+ completed <- completion{result, err}+ }()+ var attempt *oauthAttempt+ for {+ changed, _ := manager.Changes()+ manager.mu.RLock()+ attempt = manager.authorizations["oauth"]+ admitted := attempt != nil && attempt.view.Phase == "committing"+ manager.mu.RUnlock()+ if admitted {+ break+ }+ select {+ case <-changed:+ case <-ctx.Done():+ t.Fatal("real token exchange did not reach commit admission", ctx.Err())+ }+ }+ stopped := make(chan error, 1)+ go func() {+ var err error+ switch operation {+ case "cancel":+ err = manager.CancelAuthorizationAttempt(ctx, "oauth", view.ID)+ case "sign-out":+ _, err = manager.DisconnectAuthorization(ctx, "oauth")+ case "shutdown":+ err = manager.Close()+ }+ stopped <- err+ }()+ select {+ case <-attempt.ctx.Done():+ case <-ctx.Done():+ t.Fatal("owner did not withdraw authorization", ctx.Err())+ }+ select {+ case err := <-stopped:+ t.Fatalf("owner completed before admitted write drained: %v", err)+ default:+ }+ close(releaseBarrier)+ if err := <-barrierDone; err != nil {+ t.Fatal(err)+ }+ locked = false+ select {+ case err := <-stopped:+ if err != nil {+ t.Fatal("owner did not finish admitted commit and cleanup", err)+ }+ case <-ctx.Done():+ t.Fatal("cancel/commit/remount deadlock", ctx.Err())+ }+ select {+ case result := <-completed:+ if result.err != nil || result.view.State != "authorized" {+ t.Fatalf("admitted commit was reported as withdrawn: %+v, %v", result.view, result.err)+ }+ case <-ctx.Done():+ t.Fatal("callback did not settle", ctx.Err())+ }+ store := manager.oauthStore+ if operation == "shutdown" {+ var err error+ store, err = newOAuthGrantStore(filepath.Join(cwd, ".dsh", ".credentials.yaml"))+ if err != nil {+ t.Fatal(err)+ }+ }+ grant, found, err := store.get("oauth", manager.oauthConfigBinding("oauth", "", settings.Servers["oauth"]))+ if err != nil || found != (operation != "sign-out") || (found && grant.Token.AccessToken == "") {+ t.Fatalf("invalid post-commit credential lifecycle: found=%v, err=%v", found, err)+ }+ if operation == "cancel" && manager.Status().Servers[0].State != "connected" {+ t.Fatal("cancelled admitted commit was not activated synchronously")+ }+ if operation == "sign-out" && manager.Status().Servers[0].State != "waiting-authorization" {+ t.Fatal("sign-out did not remount without the committed grant")+ }+ })+ }+}++func TestOAuthCommittedGrantIsIndependentOfManagedConnectionFailure(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ settings := f.settings("test-client")+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ f.denyResource.Store(true)+ result, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view))+ if err != nil || result.State != "authorized" {+ t.Fatalf("MCP outage retracted successful credential commit: %+v, %v", result, err)+ }+ if _, found, err := manager.oauthStore.get("oauth", manager.oauthConfigBinding("oauth", "", settings.Servers["oauth"])); err != nil || !found {+ t.Fatal("MCP outage lost successful grant", err)+ }+ status := manager.Status().Servers[0]+ if status.State == "connected" || status.Authorization == nil || status.Authorization.State != "authorized" {+ t.Fatalf("credential and connection outcomes were conflated: %+v", status)+ }+}diff --git a/internal/mcpclient/oauth_identity_test.go b/internal/mcpclient/oauth_identity_test.gonew file mode 100644index 0000000..f2f98b5--- /dev/null+++ b/internal/mcpclient/oauth_identity_test.go@@ -0,0 +1,166 @@+package mcpclient++import (+ "context"+ "net/http"+ "net/url"+ "slices"+ "strings"+ "testing"+ "time"++ mcpconfig "go-bot/mcp"+)++type oauthChallengeTransport struct {+ resource, scope string+}++func (t oauthChallengeTransport) RoundTrip(request *http.Request) (*http.Response, error) {+ response, err := http.DefaultTransport.RoundTrip(request)+ if err == nil && request.URL.String() == t.resource && response.StatusCode == http.StatusUnauthorized && t.scope != "" {+ response.Header.Set("WWW-Authenticate", response.Header.Get("WWW-Authenticate")+`, scope="`+t.scope+`"`)+ }+ return response, err+}++func TestOAuthUsesConfiguredOrChallengeScopeWithoutInferringAdditionalAccess(t *testing.T) {+ empty, configured := "", "configured-only"+ for _, scenario := range []struct {+ name, challenge, expected string+ configured *string+ }{+ {"no-scope", "", "", nil},+ {"challenge", "challenge-only", "challenge-only", nil},+ {"explicit-empty", "challenge-only", "", &empty},+ {"configured", "challenge-only", "configured-only", &configured},+ } {+ t.Run(scenario.name, func(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir(), Connection: ConnectionOptions{HTTPClient: &http.Client{+ Transport: oauthChallengeTransport{resource: f.resource.URL + "/mcp", scope: scenario.challenge},+ }}})+ defer manager.Close()+ settings := f.settings("fixture")+ settings.Servers["oauth"].OAuth.Scope = scenario.configured+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ parsed, err := url.Parse(view.URL)+ if err != nil || parsed.Query().Get("scope") != scenario.expected {+ t.Fatal("scope inference differs from upstream", parsed.Query().Get("scope"), err)+ }+ })+ }+}++func TestOAuthClientKeyMatchesUpstreamJSONIdentity(t *testing.T) {+ manager := &Manager{}+ entry := &serverEntry{name: "original", owner: "plugin:handle", config: mcpconfig.Server{+ URL: "https://resource.example/mcp?x=1&y=2", OAuth: &mcpconfig.OAuth{CredentialKey: "mcp-client/mail"},+ }}+ // Generated by the upstream JSON.stringify tuple + SHA256 expression;+ // omission produces null, and URL '&' must not become an HTML escape.+ key := manager.oauthClientKey(entry, "https://issuer.example/", "http://127.0.0.1:9090/callback")+ if key != "mcp-client/mail-client-eff213c4fed6766933aeaad656408665f95f020b0f93543167e44a3f4eaa9275" {+ t.Fatal("client registration key differs from upstream", key)+ }+ entry.name, entry.owner = "renamed", "another-plugin:another-handle"+ entry.config.OAuth.ClientSecret = "rotated-secret"+ if got := manager.oauthClientKey(entry, "https://issuer.example/", "http://127.0.0.1:9090/callback"); got != key {+ t.Fatal("runtime ownership or secret rotation changed client identity")+ }+ empty := ""+ entry.config.OAuth.ClientID, entry.config.OAuth.Scope = "public", &empty+ if got := manager.oauthClientKey(entry, "https://issuer.example/", "http://127.0.0.1:9090/callback"); got != "mcp-client/mail-client-0ff30b886fa63a547940d1c6a5331308c5e78540a4ace5dbf9f906ed2422cc84" {+ t.Fatal("configured empty scope was treated as omitted", got)+ }+}++func TestOAuthGrantBindingUsesOnlyUpstreamConfigurationIdentity(t *testing.T) {+ manager := &Manager{}+ server := mcpconfig.Server{URL: "https://resource.example/mcp", OAuth: &mcpconfig.OAuth{CredentialKey: "mcp-client/mail"}}+ bound := manager.oauthConfigBinding("mail", "first:handle", server)+ budget := int64(500)+ server.OAuth.RequestTimeoutMS = &budget+ server.OAuth.ClientSecret = "new-client-secret"+ if got := manager.oauthConfigBinding("renamed", "other:handle", server); got != bound {+ t.Fatal("operational options invalidated a compatible grant")+ }+ for _, change := range []func(*mcpconfig.Server){+ func(s *mcpconfig.Server) { s.URL += "/other" },+ func(s *mcpconfig.Server) { s.OAuth.ClientID = "different" },+ func(s *mcpconfig.Server) { empty := ""; s.OAuth.Scope = &empty },+ } {+ copy := server+ oauth := *server.OAuth+ copy.OAuth = &oauth+ change(©)+ if got := manager.oauthConfigBinding("mail", "first:handle", copy); got == bound {+ t.Fatal("different endpoint, client or scope reused the grant")+ }+ }+}++func TestOAuthOriginalScopeAndBudgetsReachActualAuthorization(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ settings := f.settings("test-client")+ server := settings.Servers["oauth"]+ scope, requestMS, authorizationMS := "read custom", int64(700), int64(800)+ server.OAuth.Scope = &scope+ server.OAuth.RequestTimeoutMS = &requestMS+ server.OAuth.AuthorizationTimeoutMS = &authorizationMS+ settings.Servers["oauth"] = server+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ if client := manager.oauthHTTPClient(server.OAuth); client.Timeout != 700*time.Millisecond {+ t.Fatal("configured request budget ignored", client.Timeout)+ }+ if manager.oauthHTTPClient(nil).Timeout != 10*time.Second || oauthAuthorizationTimeout(nil) != 10*time.Minute {+ t.Fatal("OAuth defaults differ from upstream")+ }+ ctx, cancel := context.WithTimeout(t.Context(), 4*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ authorizationURL, err := url.Parse(view.URL)+ if err != nil {+ t.Fatal(err)+ }+ actualScopes, expectedScopes := strings.Fields(authorizationURL.Query().Get("scope")), strings.Fields(scope)+ // OAuth scopes form a set. The Go SDK's union uses map iteration order,+ // so wire ordering is not a permission difference.+ slices.Sort(actualScopes)+ slices.Sort(expectedScopes)+ if !slices.Equal(actualScopes, expectedScopes) {+ t.Fatal("original singular scope was not sent to the authorization server", err)+ }+ for ctx.Err() == nil {+ manager.mu.RLock()+ attempt := manager.authorizations["oauth"]+ manager.mu.RUnlock()+ select {+ case <-attempt.done:+ manager.mu.RLock()+ state := attempt.view.State+ manager.mu.RUnlock()+ if state != "expired" {+ t.Fatal("browser deadline did not expire the actual flow", state)+ }+ return+ case <-ctx.Done():+ t.Fatal("configured browser deadline was ignored", ctx.Err())+ }+ }+}diff --git a/internal/mcpclient/oauth_payload.go b/internal/mcpclient/oauth_payload.gonew file mode 100644index 0000000..262f319--- /dev/null+++ b/internal/mcpclient/oauth_payload.go@@ -0,0 +1,133 @@+package mcpclient++import (+ "encoding/json"+ "math"+ "net/url"+ "strconv"+ "time"++ "github.com/modelcontextprotocol/go-sdk/oauthex"+ "golang.org/x/oauth2"+)++// This is the upstream McpOAuthGrant payload, not a serialized oauth2.Config.+// Client authentication lives in the separately addressed client information.+type oauthGrantPayload struct {+ ID string `json:"id"`+ ServerURL string `json:"serverUrl"`+ Issuer string `json:"issuer"`+ ClientKey string `json:"clientKey"`+ ClientID string `json:"clientId"`+ ConfiguredClientID *string `json:"configuredClientId,omitempty"`+ ConfiguredScope *string `json:"configuredScope,omitempty"`+ Resource string `json:"resource,omitempty"`+ Metadata json.RawMessage `json:"metadata,omitempty"`+ Tokens oauthTokensPayload `json:"tokens"`+ ExpiresAt *int64 `json:"expiresAt,omitempty"`+}++type oauthTokensPayload struct {+ AccessToken string `json:"access_token"`+ TokenType string `json:"token_type"`+ RefreshToken string `json:"refresh_token,omitempty"`+ ExpiresIn *float64 `json:"expires_in,omitempty"`+ Scope *string `json:"scope,omitempty"`+ IDToken *string `json:"id_token,omitempty"`+ Issuer *string `json:"issuer,omitempty"`+}++func (g oauthGrant) MarshalJSON() ([]byte, error) {+ p := oauthGrantPayload{ID: g.ID, ServerURL: g.ServerURL, Issuer: g.Issuer, ClientKey: g.ClientKey, ClientID: g.Config.ClientID,+ ConfiguredClientID: g.ConfiguredClientID, ConfiguredScope: g.ConfiguredScope, Resource: g.Resource, Metadata: g.Metadata,+ Tokens: oauthTokensPayload{AccessToken: g.Token.AccessToken, TokenType: g.Token.TokenType, RefreshToken: g.Token.RefreshToken}}+ if g.ScopePresent || g.Scope != "" {+ p.Tokens.Scope = &g.Scope+ }+ p.Tokens.ExpiresIn = g.TokenExpiresIn+ if p.Tokens.ExpiresIn == nil {+ p.Tokens.ExpiresIn = oauthTokenExpiresIn(&g.Token)+ }+ if value, ok := g.Token.Extra("id_token").(string); ok {+ p.Tokens.IDToken = &value+ }+ if value, ok := g.Token.Extra("issuer").(string); ok {+ p.Tokens.Issuer = &value+ }+ if !g.Token.Expiry.IsZero() {+ expiry := g.Token.Expiry.UnixMilli()+ p.ExpiresAt = &expiry+ }+ return json.Marshal(p)+}++func (g *oauthGrant) UnmarshalJSON(data []byte) error {+ var p oauthGrantPayload+ if err := json.Unmarshal(data, &p); err != nil {+ return err+ }+ *g = oauthGrant{ID: p.ID, ServerURL: p.ServerURL, Issuer: p.Issuer, ClientKey: p.ClientKey, ConfiguredClientID: p.ConfiguredClientID, ConfiguredScope: p.ConfiguredScope,+ Resource: p.Resource, Metadata: p.Metadata, Config: oauth2.Config{ClientID: p.ClientID}, Token: oauth2.Token{AccessToken: p.Tokens.AccessToken, TokenType: p.Tokens.TokenType, RefreshToken: p.Tokens.RefreshToken}}+ g.Binding = oauthIdentityBinding(p.ServerURL, p.ConfiguredClientID, p.ConfiguredScope)+ if p.Metadata != nil {+ var metadata oauthex.AuthServerMeta+ if err := json.Unmarshal(p.Metadata, &metadata); err != nil {+ return err+ }+ g.Config.Endpoint = oauth2.Endpoint{AuthURL: metadata.AuthorizationEndpoint, TokenURL: metadata.TokenEndpoint}+ } else {+ issuer, err := url.Parse(p.Issuer)+ if err != nil {+ return err+ }+ g.Config.Endpoint = oauth2.Endpoint{AuthURL: issuer.ResolveReference(&url.URL{Path: "/authorize"}).String(), TokenURL: issuer.ResolveReference(&url.URL{Path: "/token"}).String()}+ }+ extra := map[string]any{}+ if p.Tokens.Scope != nil {+ g.Scope = *p.Tokens.Scope+ g.ScopePresent = true+ extra["scope"] = g.Scope+ }+ if p.Tokens.ExpiresIn != nil {+ g.TokenExpiresIn = p.Tokens.ExpiresIn+ g.Token.ExpiresIn = int64(*p.Tokens.ExpiresIn)+ extra["expires_in"] = *p.Tokens.ExpiresIn+ }+ if p.Tokens.IDToken != nil {+ extra["id_token"] = *p.Tokens.IDToken+ }+ if p.Tokens.Issuer != nil {+ extra["issuer"] = *p.Tokens.Issuer+ }+ g.Token = *g.Token.WithExtra(extra)+ if p.ExpiresAt != nil {+ g.Token.Expiry = time.UnixMilli(*p.ExpiresAt).UTC()+ }+ return nil+}++func oauthTokenExpiresIn(token *oauth2.Token) *float64 {+ var value float64+ if raw := token.Extra("expires_in"); raw != nil {+ var err error+ switch number := raw.(type) {+ case float64:+ value = number+ case json.Number:+ value, err = number.Float64()+ case string:+ value, err = strconv.ParseFloat(number, 64)+ default:+ value = float64(token.ExpiresIn)+ }+ if err != nil || math.IsNaN(value) || math.IsInf(value, 0) {+ return nil+ }+ return &value+ }+ if token.ExpiresIn == 0 {+ return nil+ }+ value = float64(token.ExpiresIn)+ return &value+}diff --git a/internal/mcpclient/oauth_payload_test.go b/internal/mcpclient/oauth_payload_test.gonew file mode 100644index 0000000..1394585--- /dev/null+++ b/internal/mcpclient/oauth_payload_test.go@@ -0,0 +1,216 @@+package mcpclient++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "go-bot/internal/credentials"+ mcpconfig "go-bot/mcp"+)++// This optional differential test uses the actual pinned upstream source and+// SDK to refresh Go-written records against a real local OAuth server. Ordinary+// Go tests need neither npm installation nor network access to a model service.+func TestOAuthRecordsInteroperateWithPinnedUpstream(t *testing.T) {+ module := os.Getenv("GO_BOT_UPSTREAM_MCP_OAUTH_MODULE")+ if module == "" {+ t.Skip("set GO_BOT_UPSTREAM_MCP_OAUTH_MODULE to the compiled pinned upstream oauth-credentials module")+ }+ for _, scenario := range []struct {+ name, clientID string+ confidential bool+ }{+ {"dynamic-public", "", false}, {"dynamic-confidential", "", true}, {"configured-public", "test-client", false},+ } {+ t.Run(scenario.name, func(t *testing.T) {+ f := oauthServiceFixture(t)+ f.dynamicConfidential.Store(scenario.confidential)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ settings := f.settings(scenario.clientID)+ const key = "mcp-client/oracle"+ settings.Servers["oauth"].OAuth.CredentialKey = key+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err != nil {+ t.Fatal(err)+ }+ rows, err := manager.oauthStore.credentials.ListRecords()+ if err != nil {+ t.Fatal(err)+ }+ records := map[string]*credentials.Record{}+ for _, row := range rows {+ records[row.Key], err = manager.oauthStore.credentials.ReadRecord(row.Key)+ if err != nil {+ t.Fatal(err)+ }+ }+ grant, err := manager.oauthStore.connectionGrant(key, manager.oauthConfigBinding("oauth", "", settings.Servers["oauth"]))+ if err != nil {+ t.Fatal(err)+ }+ input, _ := json.Marshal(map[string]any{"records": records, "key": key, "url": settings.Servers["oauth"].URL, "clientId": scenario.clientID, "accessToken": grant.Token.AccessToken})+ script, err := filepath.Abs("../../tests/upstream-plugins/mcp-oauth-oracle.mjs")+ if err != nil {+ t.Fatal(err)+ }+ command := exec.CommandContext(ctx, "node", script, module)+ command.Stdin = bytes.NewReader(input)+ var stderr bytes.Buffer+ command.Stderr = &stderr+ output, err := command.Output()+ if err != nil {+ t.Fatalf("pinned upstream record/refresh oracle: %v %s", err, stderr.String())+ }+ var result struct {+ Records map[string]*credentials.Record `json:"records"`+ Refreshed bool `json:"refreshed"`+ }+ if err := json.Unmarshal(output, &result); err != nil || !result.Refreshed || f.refreshes.Load() != 1 {+ t.Fatal("upstream oracle did not perform one actual refresh", err)+ }+ for name, record := range result.Records {+ if _, err := manager.oauthStore.credentials.ModifyRecord(ctx, name, func(*credentials.Record) (*credentials.Record, error) { return record, nil }); err != nil {+ t.Fatal(err)+ }+ }+ status, err := manager.Restart(ctx, "oauth")+ if err != nil || len(status.Servers) != 1 || status.Servers[0].State != "connected" {+ t.Fatalf("Go could not reconnect using the upstream-refreshed grant: %v", err)+ }+ })+ }+}++func TestOAuthGrantUsesUpstreamPayloadWithoutGoConfigOrDuplicatedClientSecret(t *testing.T) {+ grant := fixtureOAuthGrant()+ grant.ScopePresent = true // Explicit empty scope remains different from omission.+ record, err := oauthRecord("mcp-oauth-grant", grant)+ if err != nil {+ t.Fatal(err)+ }+ var value map[string]json.RawMessage+ if err := json.Unmarshal(record.Payload, &value); err != nil {+ t.Fatal(err)+ }+ for _, field := range []string{"version", "type", "id", "serverUrl", "issuer", "clientKey", "clientId", "metadata", "tokens", "expiresAt"} {+ if _, ok := value[field]; !ok {+ t.Fatalf("missing upstream field %s", field)+ }+ }+ for _, field := range []string{"binding", "config", "token", "scope"} {+ if _, ok := value[field]; ok {+ t.Fatalf("private Go representation leaked through %s", field)+ }+ }+ if strings.Contains(string(record.Payload), grant.Config.ClientSecret) {+ t.Fatal("client secret duplicated in grant")+ }+ var tokens map[string]json.RawMessage+ if err := json.Unmarshal(value["tokens"], &tokens); err != nil {+ t.Fatal(err)+ }+ if string(tokens["scope"]) != `""` {+ t.Fatal("explicit empty token scope was lost")+ }+ var decoded oauthGrant+ if err := decodeOAuthRecord(record, "mcp-oauth-grant", &decoded); err != nil || decoded.Binding != grant.Binding || !decoded.ScopePresent || !sameOAuthToken(decoded.Token, grant.Token) {+ t.Fatal("upstream record did not restore the bound token", err)+ }+}++func TestOAuthRefreshRejectsMissingOrReplacedClientInformation(t *testing.T) {+ for _, scenario := range []string{"deleted", "different-issuer", "different-client", "wrong-kind"} {+ t.Run(scenario, func(t *testing.T) {+ requests := 0+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests++; http.Error(w, "must not refresh", 400) }))+ defer remote.Close()+ store, err := newOAuthGrantStore(filepath.Join(t.TempDir(), credentials.Filename))+ if err != nil {+ t.Fatal(err)+ }+ defer store.credentials.Close()+ grant := fixtureOAuthGrant()+ grant.Config.Endpoint.TokenURL = remote.URL+ saveFixtureOAuthClient(t, store, &grant)+ if err := store.put(t.Context(), "mail", grant); err != nil {+ t.Fatal(err)+ }+ if scenario == "deleted" {+ if err := store.credentials.DeleteRecord(t.Context(), grant.ClientKey); err != nil {+ t.Fatal(err)+ }+ } else {+ _, err = store.credentials.ModifyRecord(t.Context(), grant.ClientKey, func(record *credentials.Record) (*credentials.Record, error) {+ if scenario == "wrong-kind" {+ return &credentials.Record{Kind: "api-key"}, nil+ }+ var registration oauthClientRegistration+ if err := decodeOAuthRecord(record, "mcp-oauth-client", ®istration); err != nil {+ return nil, err+ }+ if scenario == "different-issuer" {+ registration.Issuer = "https://other.example"+ } else {+ registration.Response.ClientID = "other-client"+ }+ return oauthRecord("mcp-oauth-client", registration)+ })+ if err != nil {+ t.Fatal(err)+ }+ }+ _, err = store.refresh(t.Context(), "mail", grant.Binding, grant.ID, grant.Token.AccessToken, true, remote.Client())+ var detail *Error+ if !errors.As(err, &detail) || detail.AuthorizationReason != "binding" || requests != 0 {+ t.Fatalf("refresh did not enforce client binding: requests=%d err=%v", requests, err)+ }+ loaded, found, err := store.get("mail", grant.Binding)+ if err != nil || !found || loaded.Token.AccessToken != grant.Token.AccessToken {+ t.Fatal("rejected refresh modified the grant", err)+ }+ })+ }+}++func TestOAuthCanReadUpstreamRecordsFromTheSharedProvider(t *testing.T) {+ store, err := newOAuthGrantStore(filepath.Join(t.TempDir(), credentials.Filename))+ if err != nil {+ t.Fatal(err)+ }+ defer store.credentials.Close()+ // Upstream oauthRecord(): optional metadata and expiry need not be present.+ payload := json.RawMessage(`{"version":1,"type":"mcp-oauth-grant","id":"e477b6dc-20c1-431d-9fca-4cb56932bf13","serverUrl":"https://resource.example/mcp","issuer":"https://issuer.example","clientKey":"mcp-client/shared-client","clientId":"shared-client","configuredScope":"","tokens":{"access_token":"foreign-access","token_type":"Bearer","scope":"read"}}`)+ _, err = store.credentials.ModifyRecord(t.Context(), "mcp-client/shared", func(*credentials.Record) (*credentials.Record, error) {+ return &credentials.Record{Kind: "grant", Payload: payload}, nil+ })+ if err != nil {+ t.Fatal(err)+ }+ empty := ""+ grant, err := store.connectionGrant("mcp-client/shared", oauthIdentityBinding("https://resource.example/mcp", nil, &empty))+ if err != nil || grant.Scope != "read" || !grant.Token.Expiry.IsZero() || grant.Config.ClientSecret != "" {+ t.Fatal("upstream grant could not be read", err)+ }+ if _, err := store.connectionGrant("mcp-client/shared", oauthIdentityBinding("https://resource.example/mcp", nil, nil)); err == nil {+ t.Fatal("configured empty scope crossed omitted scope binding")+ }+}diff --git a/internal/mcpclient/oauth_store.go b/internal/mcpclient/oauth_store.gonew file mode 100644index 0000000..4fb1949--- /dev/null+++ b/internal/mcpclient/oauth_store.go@@ -0,0 +1,358 @@+package mcpclient++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/url"+ "strings"+ "sync"+ "time"++ "github.com/google/uuid"+ "go-bot/internal/credentials"+ "golang.org/x/oauth2"+)++// MCP interprets its own opaque payload. The built-in Go credential service+// owns persistence and atomic mutations, exactly as ctx.credentials upstream.+type oauthGrant struct {+ ID, Binding, ServerURL, Issuer, ClientKey string+ ConfiguredClientID, ConfiguredScope *string+ Config oauth2.Config+ Token oauth2.Token+ Metadata json.RawMessage+ Resource, Scope string+ ScopePresent bool+ TokenExpiresIn *float64+}+type oauthGrantStore struct {+ mu sync.Mutex+ credentials *credentials.Store+}++func newOAuthGrantStore(path string) (*oauthGrantStore, error) {+ store, err := credentials.Open(path, credentials.Options{})+ if err != nil {+ return nil, err+ }+ return &oauthGrantStore{credentials: store}, nil+}+func oauthGrantKey(name string) string {+ if credentials.ValidKey(name) {+ return name+ }+ sum := sha256.Sum256([]byte(name))+ return "mcp/connection-" + hex.EncodeToString(sum[:])+}+func oauthClientRecordKey(key string) string {+ if credentials.ValidKey(key) {+ return key+ }+ sum := sha256.Sum256([]byte(key))+ return "mcp/client-" + hex.EncodeToString(sum[:])+}+func oauthRecord(kind string, value any) (*credentials.Record, error) {+ data, err := json.Marshal(value)+ if err != nil {+ return nil, err+ }+ var payload map[string]any+ if json.Unmarshal(data, &payload) != nil {+ return nil, errors.New("invalid MCP credential payload")+ }+ payload["version"], payload["type"] = 1, kind+ data, err = json.Marshal(payload)+ return &credentials.Record{Kind: "grant", Payload: data}, err+}+func decodeOAuthRecord(record *credentials.Record, kind string, output any) error {+ if record == nil {+ return nil+ }+ var tag struct {+ Version int `json:"version"`+ Type string `json:"type"`+ }+ if record.Kind != "grant" || json.Unmarshal(record.Payload, &tag) != nil || tag.Version != 1 || tag.Type != kind || json.Unmarshal(record.Payload, output) != nil {+ return fail("MCP_OAUTH_STORE_INVALID", "Stored MCP credential record has an invalid format")+ }+ return nil+}+func validStoredGrant(grant oauthGrant) error {+ if _, err := uuid.Parse(grant.ID); err != nil || grant.Token.AccessToken == "" || grant.Token.TokenType == "" || grant.Config.ClientID == "" || !validOAuthURL(grant.ServerURL) || !validOAuthURL(grant.Issuer) || !credentials.ValidKey(grant.ClientKey) || (grant.Resource != "" && !validOAuthURL(grant.Resource)) {+ return fail("MCP_OAUTH_STORE_INVALID", "Stored OAuth grant is incomplete")+ }+ if !validOAuthURL(grant.Config.Endpoint.TokenURL) || !validOAuthURL(grant.Config.Endpoint.AuthURL) {+ return fail("MCP_OAUTH_STORE_INVALID", "Stored OAuth metadata is incomplete")+ }+ return nil+}+func (s *oauthGrantStore) get(name, binding string) (oauthGrant, bool, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ var grant oauthGrant+ record, err := s.credentials.ReadRecord(oauthGrantKey(name))+ if err != nil || record == nil {+ return grant, false, err+ }+ if err = decodeOAuthRecord(record, "mcp-oauth-grant", &grant); err != nil {+ return grant, false, err+ }+ if grant.Binding != binding {+ return grant, false, nil+ }+ return grant, true, validStoredGrant(grant)+}+func (s *oauthGrantStore) put(ctx context.Context, name string, grant oauthGrant) error {+ if name == "" || grant.Binding == "" {+ return fail("MCP_OAUTH_STORE_INVALID", "Cannot persist an incomplete OAuth grant")+ }+ if err := validStoredGrant(grant); err != nil {+ return err+ }+ record, err := oauthRecord("mcp-oauth-grant", grant)+ if err != nil {+ return err+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ _, err = s.credentials.ModifyRecord(ctx, oauthGrantKey(name), func(*credentials.Record) (*credentials.Record, error) { return record, nil })+ return err+}+func (s *oauthGrantStore) connectionGrant(name, binding string) (oauthGrant, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ var grant oauthGrant+ record, err := s.credentials.ReadRecord(oauthGrantKey(name))+ if err != nil {+ return grant, err+ }+ if record == nil {+ return grant, authorizationFailure("missing", "Connect this MCP server with OAuth")+ }+ if err = decodeOAuthRecord(record, "mcp-oauth-grant", &grant); err != nil {+ return grant, authorizationFailure("binding", "Stored OAuth authorization is incompatible; reconnect this server")+ }+ if grant.Binding != binding {+ return grant, authorizationFailure("binding", "OAuth authorization no longer matches this MCP configuration")+ }+ if err := validStoredGrant(grant); err != nil {+ return grant, authorizationFailure("binding", "Stored OAuth authorization is incompatible; reconnect this server")+ }+ return grant, nil+}+func (s *oauthGrantStore) remove(ctx context.Context, name string) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.credentials.DeleteRecord(ctx, oauthGrantKey(name))+}+func sameOAuthToken(left, right oauth2.Token) bool {+ return left.AccessToken == right.AccessToken && left.RefreshToken == right.RefreshToken && left.TokenType == right.TokenType && left.Expiry.Equal(right.Expiry) && left.ExpiresIn == right.ExpiresIn+}++func oauthTokenExpired(token oauth2.Token) bool {+ // Upstream expiresAt is tested against the current time; oauth2.Valid's+ // implicit ten-second safety margin is not part of that contract.+ return token.AccessToken == "" || (!token.Expiry.IsZero() && !token.Expiry.After(time.Now()))+}++// Refresh under the shared provider's mutation queue, as upstream does. Two+// independently created transports bound to the same grant must reuse the+// first rotation rather than send the same refresh token twice.+func (s *oauthGrantStore) refresh(ctx context.Context, name, binding, id, access string, force bool, client *http.Client) (oauthGrant, error) {+ record, err := s.credentials.ModifyRecord(ctx, oauthGrantKey(name), func(record *credentials.Record) (*credentials.Record, error) {+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ var grant oauthGrant+ if record == nil {+ return nil, authorizationFailure("binding", "OAuth authorization changed; reconnect this server")+ }+ if err := decodeOAuthRecord(record, "mcp-oauth-grant", &grant); err != nil {+ return nil, authorizationFailure("binding", "Stored OAuth authorization is incompatible; reconnect this server")+ }+ if err := validStoredGrant(grant); err != nil {+ return nil, authorizationFailure("binding", "Stored OAuth authorization is incompatible; reconnect this server")+ }+ if grant.Binding != binding || grant.ID != id {+ return nil, authorizationFailure("binding", "OAuth authorization changed; reconnect this server")+ }+ if grant.Token.AccessToken != access || (!force && !oauthTokenExpired(grant.Token)) {+ return nil, nil+ }+ if grant.Token.RefreshToken == "" {+ return nil, authorizationFailure("expired", "OAuth token expired without a refresh token; reconnect this server")+ }+ // Client information belongs to its own credential record upstream. Do+ // not refresh using a secret copied into an old grant after sign-out,+ // replacement, deletion or a plugin changing the registered identity.+ registration, found, err := s.readClient(grant.ClientKey)+ if err != nil || !found || registration.Issuer != grant.Issuer || registration.Response.ClientID != grant.Config.ClientID {+ return nil, authorizationFailure("binding", "OAuth client registration changed; reconnect this server")+ }+ grant.Config.ClientSecret = registration.Response.ClientSecret+ switch registration.Response.TokenEndpointAuthMethod {+ case "none", "client_secret_post":+ grant.Config.Endpoint.AuthStyle = oauth2.AuthStyleInParams+ case "client_secret_basic":+ grant.Config.Endpoint.AuthStyle = oauth2.AuthStyleInHeader+ }+ refreshContext := context.WithValue(ctx, oauth2.HTTPClient, oauthRefreshClient(client, grant.Config.Endpoint.TokenURL, grant.Resource))+ previous := grant.Token+ // oauth2 normally only refreshes expired tokens. A resource server's+ // 401 is also grounds to refresh even before the advertised expiry.+ previous.Expiry = time.Now().Add(-time.Hour)+ next, err := grant.Config.TokenSource(refreshContext, &previous).Token()+ if err != nil {+ return nil, authorizationFailure("rejected", "OAuth token refresh failed; reconnect this server")+ }+ grant.Token = *next+ grant.TokenExpiresIn = oauthTokenExpiresIn(next)+ if scope, ok := next.Extra("scope").(string); ok {+ grant.Scope = scope+ grant.ScopePresent = true+ }+ return oauthRecord("mcp-oauth-grant", grant)+ })+ if err != nil {+ return oauthGrant{}, err+ }+ var grant oauthGrant+ if err = decodeOAuthRecord(record, "mcp-oauth-grant", &grant); err != nil {+ return grant, err+ }+ return grant, validStoredGrant(grant)+}++// oauth2.Config does not expose token-refresh parameters. Preserve the resource+// selected by the SDK's authorization request, as upstream refreshAuthorization+// does, without changing discovery, authentication or token response handling.+func oauthRefreshClient(client *http.Client, endpoint, resource string) *http.Client {+ if resource == "" {+ return client+ }+ if client == nil {+ client = http.DefaultClient+ }+ copy := *client+ base := copy.Transport+ if base == nil {+ base = http.DefaultTransport+ }+ copy.Transport = oauthResourceTransport{base: base, endpoint: endpoint, resource: resource}+ return ©+}++type oauthResourceTransport struct {+ base http.RoundTripper+ endpoint, resource string+}++func (t oauthResourceTransport) RoundTrip(request *http.Request) (*http.Response, error) {+ if request.Method != http.MethodPost || request.URL.String() != t.endpoint {+ return t.base.RoundTrip(request)+ }+ if request.Body != nil {+ defer request.Body.Close()+ }+ if request.GetBody == nil {+ return nil, errors.New("OAuth refresh request cannot be replayed")+ }+ body, err := request.GetBody()+ if err != nil {+ return nil, err+ }+ data, err := io.ReadAll(body)+ _ = body.Close()+ if err != nil {+ return nil, err+ }+ form, err := url.ParseQuery(string(data))+ if err != nil {+ return nil, err+ }+ if form.Get("grant_type") != "refresh_token" {+ return t.base.RoundTrip(request)+ }+ form.Set("resource", t.resource)+ encoded := form.Encode()+ clone := request.Clone(request.Context())+ clone.Body = io.NopCloser(strings.NewReader(encoded))+ clone.ContentLength = int64(len(encoded))+ clone.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(encoded)), nil }+ return t.base.RoundTrip(clone)+}++type persistentOAuthTokenSource struct {+ mu sync.Mutex+ ctx context.Context+ store *oauthGrantStore+ name string+ binding string+ id string+ client *http.Client+ failed error // Terminal for this connection; explicit reconnect creates a new source.+}++func (s *oauthGrantStore) tokenSource(ctx context.Context, name string, grant oauthGrant, client *http.Client) oauth2.TokenSource {+ if client == nil {+ client = &http.Client{Timeout: RequestTimeout}+ }+ return &persistentOAuthTokenSource{ctx: ctx, store: s, name: name, binding: grant.Binding, id: grant.ID,+ client: client}+}++func (s *persistentOAuthTokenSource) Token() (*oauth2.Token, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.failed != nil {+ return nil, s.failed+ }+ // Like oauth2.ReuseTokenSource, a still-valid cached token remains usable+ // for the transport's final authenticated DELETE after Host cancellation.+ // Refresh requests still carry the cancelled owner context and cannot start+ // fresh network work after shutdown.+ grant, err := s.store.connectionGrant(s.name, s.binding)+ if err == nil && grant.ID != s.id {+ err = authorizationFailure("binding", "OAuth authorization changed; reconnect this server")+ }+ if err != nil {+ s.failed = err+ return nil, s.failed+ }+ if oauthTokenExpired(grant.Token) {+ grant, err = s.store.refresh(s.ctx, s.name, s.binding, s.id, grant.Token.AccessToken, false, s.client)+ if err != nil {+ s.failed = err+ return nil, err+ }+ }+ token := grant.Token+ return &token, nil+}++func (s *persistentOAuthTokenSource) refreshRejected(ctx context.Context, access string) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.failed != nil {+ return s.failed+ }+ // Both the connection and the particular rejected request own this refresh.+ request, cancel := context.WithCancel(s.ctx)+ stop := context.AfterFunc(ctx, cancel)+ defer stop()+ defer cancel()+ if ctx.Err() != nil {+ cancel()+ }+ _, err := s.store.refresh(request, s.name, s.binding, s.id, access, true, s.client)+ if err != nil {+ s.failed = err+ return err+ }+ return nil+}diff --git a/internal/mcpclient/oauth_store_test.go b/internal/mcpclient/oauth_store_test.gonew file mode 100644index 0000000..58c296f--- /dev/null+++ b/internal/mcpclient/oauth_store_test.go@@ -0,0 +1,387 @@+package mcpclient++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/modelcontextprotocol/go-sdk/oauthex"+ "go-bot/internal/credentials"+ mcpconfig "go-bot/mcp"+ "golang.org/x/oauth2"+)++func TestMCPUsesSharedGoCredentialsAndLeavesOtherPluginRecordsIntact(t *testing.T) {+ f := oauthServiceFixture(t)+ path := filepath.Join(t.TempDir(), credentials.Filename)+ store, err := credentials.Open(path, credentials.Options{})+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()+ if _, err = store.ModifyRecord(t.Context(), "calendar/personal", func(*credentials.Record) (*credentials.Record, error) {+ return &credentials.Record{Kind: "api-key"}, nil+ }); err != nil {+ t.Fatal(err)+ }+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir(), Credentials: store})+ defer manager.Close()+ settings := f.settings("")+ server := settings.Servers["oauth"]+ server.OAuth.CredentialKey = "mail/personal"+ settings.Servers["oauth"] = server+ if _, err = manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ view, err := manager.Authorize(t.Context(), "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ if _, err = manager.CompleteAuthorization(t.Context(), visitOAuthAuthorization(t, view)); err != nil {+ t.Fatal(err)+ }+ entries, err := store.ListRecords()+ if err != nil || len(entries) != 3 {+ t.Fatalf("shared records: %+v %v", entries, err)+ }+ grant, err := store.ReadRecord("mail/personal")+ if err != nil || grant == nil || grant.Kind != "grant" {+ t.Fatal("MCP grant bypassed the shared service", err)+ }+ var authorized oauthGrant+ if err := decodeOAuthRecord(grant, "mcp-oauth-grant", &authorized); err != nil || authorized.Resource != f.resource.URL+"/mcp" || authorized.Scope != "read offline_access" {+ t.Fatal("SDK authorization lost the selected resource or returned scope", err)+ }+ for _, entry := range entries {+ if entry.Key != "calendar/personal" && entry.Key != "mail/personal" && !strings.HasPrefix(entry.Key, "mail/personal-client-") {+ t.Fatalf("client registration lost owning namespace: %s", entry.Key)+ }+ }+ if _, err = manager.DisconnectAuthorization(t.Context(), "oauth"); err != nil {+ t.Fatal(err)+ }+ if record, _ := store.ReadRecord("mail/personal"); record != nil {+ t.Fatal("sign-out retained grant")+ }+ entries, err = store.ListRecords()+ if err != nil || len(entries) != 2 {+ t.Fatalf("sign-out removed unrelated or retained-client records: %+v %v", entries, err)+ }+ if err = manager.Close(); err != nil {+ t.Fatal(err)+ }+ if _, err = store.ListRecords(); err != nil {+ t.Fatal("MCP closed a Host-owned credential service", err)+ }+}++func fixtureOAuthGrant() oauthGrant {+ grant := oauthGrant{ID: uuid.NewString(), ServerURL: "https://resource.example/mcp", Issuer: "https://auth.example", ClientKey: "mcp-client/fixture-client", Config: oauth2.Config{ClientID: "fixture-client", ClientSecret: "private-client-secret", Endpoint: oauth2.Endpoint{AuthURL: "https://auth.example/authorize", TokenURL: "https://auth.example/token"}}, Token: oauth2.Token{AccessToken: "private-access", RefreshToken: "private-refresh", TokenType: "Bearer", Expiry: time.Now().Add(time.Hour).UTC().Truncate(time.Millisecond)}}+ grant.Binding = oauthIdentityBinding(grant.ServerURL, nil, nil)+ grant.Metadata = json.RawMessage(`{"issuer":"https://auth.example","authorization_endpoint":"https://auth.example/authorize","token_endpoint":"https://auth.example/token","response_types_supported":["code"]}`)+ return grant+}++func saveFixtureOAuthClient(t *testing.T, store *oauthGrantStore, grant *oauthGrant) {+ t.Helper()+ grant.Metadata, _ = json.Marshal(map[string]any{"issuer": grant.Issuer, "authorization_endpoint": grant.Config.Endpoint.AuthURL, "token_endpoint": grant.Config.Endpoint.TokenURL, "response_types_supported": []string{"code"}})+ method := "client_secret_basic"+ if grant.Config.Endpoint.AuthStyle == oauth2.AuthStyleInParams {+ method = "client_secret_post"+ }+ if err := store.saveClient(t.Context(), grant.ClientKey, oauthClientRegistration{Issuer: grant.Issuer, Response: &oauthex.ClientRegistrationResponse{ClientID: grant.Config.ClientID, ClientSecret: grant.Config.ClientSecret, ClientRegistrationMetadata: oauthex.ClientRegistrationMetadata{TokenEndpointAuthMethod: method}}}); err != nil {+ t.Fatal(err)+ }+}++func TestOAuthGrantPersistsPrivatelyAcrossStoreReopenWithoutCrossingBindings(t *testing.T) {+ path := filepath.Join(t.TempDir(), ".dsh", "mcp", "credentials.json")+ store, err := newOAuthGrantStore(path)+ if err != nil {+ t.Fatal(err)+ }+ grant := fixtureOAuthGrant()+ if err := store.put(t.Context(), "mail", grant); err != nil {+ t.Fatal(err)+ }+ info, err := os.Stat(path)+ if err != nil || info.Mode().Perm() != 0600 {+ t.Fatalf("credential permissions: %v %v", info, err)+ }+ reopened, err := newOAuthGrantStore(path)+ if err != nil {+ t.Fatal(err)+ }+ loaded, found, err := reopened.get("mail", grant.Binding)+ if err != nil || !found || !sameOAuthToken(loaded.Token, grant.Token) || loaded.Config.ClientSecret != "" {+ t.Fatalf("grant did not survive restart: found=%v err=%v", found, err)+ }+ if _, found, err := reopened.get("mail", "another-resource-or-client"); err != nil || found {+ t.Fatal("grant crossed its configured binding", err)+ }+ if err := reopened.remove(t.Context(), "mail"); err != nil {+ t.Fatal(err)+ }+ afterDelete, err := newOAuthGrantStore(path)+ if err != nil {+ t.Fatal(err)+ }+ if _, found, err := afterDelete.get("mail", grant.Binding); err != nil || found {+ t.Fatal("deleted grant remained", err)+ }+}++func TestOAuthRefreshRotatesAndPersistsOnceForConcurrentRequests(t *testing.T) {+ var requests atomic.Int32+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests.Add(1)+ if r.Method != http.MethodPost || r.FormValue("grant_type") != "refresh_token" || r.FormValue("refresh_token") != "private-refresh" {+ http.Error(w, "bad refresh request", 400)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh", "token_type": "Bearer", "expires_in": 3600})+ }))+ defer remote.Close()+ store, _ := newOAuthGrantStore(filepath.Join(t.TempDir(), "credentials.json"))+ grant := fixtureOAuthGrant()+ grant.Token.Expiry = time.Now().Add(-time.Hour)+ grant.Config.Endpoint.TokenURL = remote.URL+ grant.Config.Endpoint.AuthStyle = oauth2.AuthStyleInParams+ saveFixtureOAuthClient(t, store, &grant)+ if err := store.put(t.Context(), "mail", grant); err != nil {+ t.Fatal(err)+ }+ var group sync.WaitGroup+ for range 12 {+ // Independent managed/probe transports share only the Go provider,+ // not one oauth2.ReuseTokenSource mutex.+ source := store.tokenSource(t.Context(), "mail", grant, remote.Client())+ group.Add(1)+ go func() {+ defer group.Done()+ token, err := source.Token()+ if err != nil || token.AccessToken != "rotated-access" {+ t.Errorf("refresh token=%v err=%v", token, err)+ }+ }()+ }+ group.Wait()+ if requests.Load() != 1 {+ t.Fatalf("refresh requests=%d; want one", requests.Load())+ }+ loaded, found, err := store.get("mail", grant.Binding)+ if err != nil || !found || loaded.Token.AccessToken != "rotated-access" || loaded.Token.RefreshToken != "rotated-refresh" {+ t.Fatalf("rotated grant was not persisted: found=%v err=%v", found, err)+ }+}++func TestOAuthConcurrentRejectedRequestsReuseTheSharedCommittedRotation(t *testing.T) {+ var requests atomic.Int32+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests.Add(1)+ if r.FormValue("refresh_token") != "private-refresh" {+ http.Error(w, "rotated refresh token was reused", 400)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"access_token": "resource-retry-access", "refresh_token": "resource-retry-refresh", "token_type": "Bearer", "expires_in": 3600})+ }))+ defer remote.Close()+ store, err := newOAuthGrantStore(filepath.Join(t.TempDir(), credentials.Filename))+ if err != nil {+ t.Fatal(err)+ }+ defer store.credentials.Close()+ grant := fixtureOAuthGrant()+ grant.Config.Endpoint.TokenURL = remote.URL+ grant.Config.Endpoint.AuthStyle = oauth2.AuthStyleInParams+ saveFixtureOAuthClient(t, store, &grant)+ if err := store.put(t.Context(), "mail", grant); err != nil {+ t.Fatal(err)+ }+ var group sync.WaitGroup+ for range 12 {+ source := store.tokenSource(t.Context(), "mail", grant, remote.Client())+ group.Go(func() {+ request, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, "http://127.0.0.1/mcp", nil)+ request.Header.Set("Authorization", "Bearer "+grant.Token.AccessToken)+ if err := (&storedOAuthHandler{source: source}).Authorize(t.Context(), request, &http.Response{StatusCode: http.StatusUnauthorized}); err != nil {+ t.Error("Shared revoked-token refresh failed", err)+ return+ }+ if token, err := source.Token(); err != nil || token.AccessToken != "resource-retry-access" {+ t.Error("Did not reuse the committed token", err)+ }+ })+ }+ group.Wait()+ if requests.Load() != 1 {+ t.Fatalf("Independent requests performed %d rotations; want one", requests.Load())+ }+}++func TestOAuthRefreshPreservesAuthorizedResourceAndScopeAcrossReopen(t *testing.T) {+ const resource = "https://mcp.example/reports?tenant=team"+ var requests atomic.Int32+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ sequence := requests.Add(1)+ if r.Method != http.MethodPost || r.FormValue("grant_type") != "refresh_token" || r.FormValue("resource") != resource || r.FormValue("client_id") != "fixture-client" || r.FormValue("client_secret") != "private-client-secret" {+ http.Error(w, "refresh lost resource or client authentication", 400)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ value := map[string]any{"access_token": fmt.Sprintf("access-%d", sequence), "token_type": "Bearer"}+ if sequence == 2 {+ value["scope"] = "read write"+ value["expires_in"] = 3600+ }+ _ = json.NewEncoder(w).Encode(value)+ }))+ defer remote.Close()+ path := filepath.Join(t.TempDir(), credentials.Filename)+ grant := fixtureOAuthGrant()+ grant.Resource, grant.Scope = resource, "read offline_access"+ grant.Config.Endpoint.TokenURL = remote.URL+ grant.Config.Endpoint.AuthStyle = oauth2.AuthStyleInParams+ store, err := newOAuthGrantStore(path)+ if err != nil {+ t.Fatal(err)+ }+ saveFixtureOAuthClient(t, store, &grant)+ if err := store.put(t.Context(), "mail", grant); err != nil {+ t.Fatal(err)+ }+ if err := store.credentials.Close(); err != nil {+ t.Fatal(err)+ }+ // Actual serialization/reopen is required: oauth2.Token drops its Extra+ // fields from JSON, so an in-memory token alone cannot preserve scope.+ store, err = newOAuthGrantStore(path)+ if err != nil {+ t.Fatal(err)+ }+ defer store.credentials.Close()+ for sequence, expectedScope := range []string{"read offline_access", "read write", "read write"} {+ grant, err = store.refresh(t.Context(), "mail", grant.Binding, grant.ID, grant.Token.AccessToken, true, remote.Client())+ if err != nil {+ t.Fatal(err)+ }+ if grant.Resource != resource || grant.Scope != expectedScope || grant.Token.RefreshToken != "private-refresh" {+ t.Fatalf("refresh %d lost resource, scope or retained refresh token", sequence+1)+ }+ if (sequence == 1) == grant.Token.Expiry.IsZero() {+ t.Fatalf("refresh %d did not replace the prior expiry", sequence+1)+ }+ }+ if requests.Load() != 3 {+ t.Fatalf("unexpected refresh attempts: %d", requests.Load())+ }+ loaded, found, err := store.get("mail", grant.Binding)+ if err != nil || !found || loaded.Scope != "read write" || loaded.Resource != resource {+ t.Fatal("refreshed resource and scope were not persisted", err)+ }+}++func TestLateOAuthSourceCannotResurrectOrOverwriteAnotherAuthorization(t *testing.T) {+ for _, operation := range []string{"sign-out", "new-authorization", "new-authorization-same-token", "binding-change"} {+ t.Run(operation, func(t *testing.T) {+ store, _ := newOAuthGrantStore(filepath.Join(t.TempDir(), "credentials.json"))+ grant := fixtureOAuthGrant()+ if err := store.put(t.Context(), "mail", grant); err != nil {+ t.Fatal(err)+ }+ source := store.tokenSource(t.Context(), "mail", grant, nil)+ if operation == "sign-out" {+ if err := store.remove(t.Context(), "mail"); err != nil {+ t.Fatal(err)+ }+ } else {+ current := grant+ current.ID = uuid.NewString()+ if operation != "new-authorization-same-token" {+ current.Token.AccessToken = "new-authorization-token"+ }+ if operation == "binding-change" {+ current.ServerURL += "/other"+ current.Binding = oauthIdentityBinding(current.ServerURL, nil, nil)+ }+ if err := store.put(t.Context(), "mail", current); err != nil {+ t.Fatal(err)+ }+ }+ _, err := source.Token()+ var failure *Error+ if !errors.As(err, &failure) || failure.Code != "MCP_AUTHORIZATION_REQUIRED" {+ t.Fatalf("stale source remained usable: %v", err)+ }+ binding := grant.Binding+ if operation == "binding-change" {+ binding = oauthIdentityBinding(grant.ServerURL+"/other", nil, nil)+ }+ loaded, found, err := store.get("mail", binding)+ if err != nil {+ t.Fatal(err)+ }+ if operation == "sign-out" {+ if found {+ t.Fatal("late source resurrected signed-out grant")+ }+ } else if !found || (operation != "new-authorization-same-token" && loaded.Token.AccessToken != "new-authorization-token") {+ t.Fatal("late source replaced the new authorization")+ }+ })+ }+}++func TestOAuthGrantConcurrentWritesAndCancelledSaveKeepCompleteFile(t *testing.T) {+ path := filepath.Join(t.TempDir(), "credentials.json")+ store, _ := newOAuthGrantStore(path)+ var group sync.WaitGroup+ for index := range 12 {+ group.Add(1)+ go func() {+ defer group.Done()+ if err := store.put(t.Context(), fmt.Sprint(index), fixtureOAuthGrant()); err != nil {+ t.Error(err)+ }+ }()+ }+ group.Wait()+ reopened, err := newOAuthGrantStore(path)+ if err != nil {+ t.Fatal(err)+ }+ entries, err := reopened.credentials.ListRecords()+ if err != nil || len(entries) != 12 {+ t.Fatalf("concurrent grant writes lost shared records: %v %v", entries, err)+ }+ for index := range 12 {+ if _, found, err := reopened.get(fmt.Sprint(index), fixtureOAuthGrant().Binding); err != nil || !found {+ t.Fatalf("grant %d was not durable: %v", index, err)+ }+ }+ ctx, cancel := context.WithCancel(t.Context())+ cancel()+ if err := store.put(ctx, "cancelled", fixtureOAuthGrant()); err == nil {+ t.Fatal("cancelled credential write succeeded")+ }+ if _, found, err := store.get("cancelled", fixtureOAuthGrant().Binding); err != nil || found {+ t.Fatal("cancelled write was published", err)+ }+ files, err := filepath.Glob(filepath.Join(filepath.Dir(path), ".credential-write-*"))+ if err != nil || len(files) != 0 {+ t.Fatal("temporary OAuth credential files remained", files, err)+ }+}diff --git a/internal/mcpclient/oauth_test.go b/internal/mcpclient/oauth_test.gonew file mode 100644index 0000000..64d948f--- /dev/null+++ b/internal/mcpclient/oauth_test.go@@ -0,0 +1,589 @@+package mcpclient++import (+ "context"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "net/url"+ "path/filepath"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ mcpconfig "go-bot/mcp"+)++type oauthTestService struct {+ resource, provider *httptest.Server+ server *sdk.Server+ mu sync.Mutex+ codes map[string]string+ tokens map[string]bool+ sequence int+ lastAccess, lastRefresh string+ refreshes atomic.Int32+ requests atomic.Int32+ registrations atomic.Int32+ denyRefresh atomic.Bool+ denyClient atomic.Bool+ dynamicConfidential atomic.Bool+ denyResource atomic.Bool+ omitIssuerAdvertisement atomic.Bool+}++func oauthServiceFixture(t *testing.T) *oauthTestService {+ t.Helper()+ f := &oauthTestService{codes: map[string]string{}, tokens: map[string]bool{}}+ f.provider = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ write := func(value any) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(value)+ }+ switch r.URL.Path {+ case "/.well-known/oauth-authorization-server":+ write(map[string]any{"issuer": f.provider.URL, "authorization_endpoint": f.provider.URL + "/authorize", "token_endpoint": f.provider.URL + "/token", "registration_endpoint": f.provider.URL + "/register", "response_types_supported": []string{"code"}, "grant_types_supported": []string{"authorization_code", "refresh_token"}, "token_endpoint_auth_methods_supported": []string{"none", "client_secret_post"}, "code_challenge_methods_supported": []string{"S256"}, "scopes_supported": []string{"read", "offline_access"}, "authorization_response_iss_parameter_supported": !f.omitIssuerAdvertisement.Load()})+ case "/register":+ f.registrations.Add(1)+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusCreated)+ registration := map[string]any{"client_id": "dynamic-client", "token_endpoint_auth_method": "none"}+ if f.dynamicConfidential.Load() {+ registration["token_endpoint_auth_method"] = "client_secret_post"+ registration["client_secret"] = "private-dynamic-client-secret"+ registration["client_secret_expires_at"] = 0+ }+ write(registration)+ case "/authorize":+ query := r.URL.Query()+ if query.Get("code_challenge") == "" || query.Get("code_challenge_method") != "S256" {+ http.Error(w, "PKCE required", 400)+ return+ }+ f.mu.Lock()+ f.sequence+++ code := fmt.Sprint("code-", f.sequence)+ f.codes[code] = query.Get("code_challenge")+ f.mu.Unlock()+ callback, err := url.Parse(query.Get("redirect_uri"))+ if err != nil {+ http.Error(w, "bad redirect", 400)+ return+ }+ values := callback.Query()+ values.Set("code", code)+ values.Set("state", query.Get("state"))+ values.Set("iss", f.provider.URL)+ callback.RawQuery = values.Encode()+ http.Redirect(w, r, callback.String(), http.StatusFound)+ case "/token":+ if f.denyClient.Load() {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusBadRequest)+ write(map[string]string{"error": "invalid_client", "error_description": "rejected private-dynamic-client-secret"})+ return+ }+ if err := r.ParseForm(); err != nil {+ http.Error(w, "bad token form", 400)+ return+ }+ if r.Form.Get("client_id") == "confidential-client" && r.Form.Get("client_secret") != "private-user-client-secret" {+ http.Error(w, "invalid confidential client", 400)+ return+ }+ if r.Form.Get("client_id") == "dynamic-client" && f.dynamicConfidential.Load() && r.Form.Get("client_secret") != "private-dynamic-client-secret" {+ http.Error(w, "dynamic registration auth method or secret was lost", 400)+ return+ }+ if r.Form.Get("grant_type") == "authorization_code" {+ f.mu.Lock()+ challenge, found := f.codes[r.Form.Get("code")]+ delete(f.codes, r.Form.Get("code"))+ f.mu.Unlock()+ digest := sha256.Sum256([]byte(r.Form.Get("code_verifier")))+ if !found || base64.RawURLEncoding.EncodeToString(digest[:]) != challenge || r.Form.Get("resource") != f.resource.URL+"/mcp" {+ http.Error(w, "bad code, verifier or resource", 400)+ return+ }+ } else if r.Form.Get("grant_type") == "refresh_token" {+ f.refreshes.Add(1)+ if r.Form.Get("resource") != f.resource.URL+"/mcp" {+ http.Error(w, "refresh lost its authorized resource", 400)+ return+ }+ if f.denyRefresh.Load() {+ w.WriteHeader(400)+ write(map[string]string{"error": "invalid_grant"})+ return+ }+ if !strings.HasPrefix(r.Form.Get("refresh_token"), "refresh-") {+ http.Error(w, "bad refresh", 400)+ return+ }+ } else {+ http.Error(w, "bad grant type", 400)+ return+ }+ f.mu.Lock()+ f.sequence+++ access := fmt.Sprint("access-", f.sequence)+ refresh := fmt.Sprint("refresh-", f.sequence)+ f.tokens[access] = true+ f.lastAccess, f.lastRefresh = access, refresh+ f.mu.Unlock()+ write(map[string]any{"access_token": access, "refresh_token": refresh, "expires_in": 3600, "token_type": "Bearer", "scope": "read offline_access"})+ default:+ http.NotFound(w, r)+ }+ }))+ server := testServer()+ f.server = server+ mcpHandler := sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil)+ f.resource = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/.well-known/oauth-protected-resource/mcp" {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"resource": f.resource.URL + "/mcp", "authorization_servers": []string{f.provider.URL}, "scopes_supported": []string{"read"}})+ return+ }+ f.requests.Add(1)+ f.mu.Lock()+ authorized := f.tokens[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]+ f.mu.Unlock()+ if !authorized {+ w.Header().Set("WWW-Authenticate", `Bearer resource_metadata="`+f.resource.URL+`/.well-known/oauth-protected-resource/mcp"`)+ http.Error(w, "authorization required", 401)+ return+ }+ if f.denyResource.Load() {+ http.Error(w, "MCP temporarily unavailable after authorization", http.StatusServiceUnavailable)+ return+ }+ mcpHandler.ServeHTTP(w, r)+ }))+ t.Cleanup(f.resource.Close)+ t.Cleanup(f.provider.Close)+ return f+}++func TestOAuthDynamicAndConfidentialClientsUseTheSameExplicitFlow(t *testing.T) {+ for _, client := range []string{"", "confidential-client"} {+ t.Run("client-"+client, func(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ settings := f.settings(client)+ if client != "" {+ server := settings.Servers["oauth"]+ server.OAuth.ClientSecretRef = "oauth/client-secret"+ settings.Servers["oauth"] = server+ settings.Credentials = map[string]string{"oauth/client-secret": "private-user-client-secret"}+ }+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ if status := manager.Status().Servers[0]; !status.OAuthEnabled || status.Authorization != nil {+ t.Fatalf("OAuth capability must be discoverable before starting a flow: %+v", status)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err != nil {+ t.Fatal(err)+ }+ if manager.Status().Servers[0].State != "connected" {+ t.Fatal("client did not connect")+ }+ })+ }+}++func TestOAuthRevokedLiveTokenRefreshesAndRejectedRefreshWaitsForExplicitAuthorization(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), f.settings("test-client")); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err != nil {+ t.Fatal(err)+ }+ scope := manager.NewScope()+ defer scope.Close()+ tool := findTool(t, scope, PublicToolName("oauth", "one"))+ if tool == nil {+ t.Fatal("missing authorized tool")+ }+ f.mu.Lock()+ f.tokens = map[string]bool{}+ f.mu.Unlock()+ if _, err := tool.Execute(ctx, json.RawMessage(`{}`)); err != nil {+ t.Fatal("Resource rejection did not refresh and retry", err)+ }+ if f.refreshes.Load() != 1 || manager.Status().Servers[0].State != "connected" {+ t.Fatal("Resource rejection did not recover with one refresh")+ }+ f.denyRefresh.Store(true)+ f.mu.Lock()+ f.tokens = map[string]bool{}+ f.mu.Unlock()+ if _, err := tool.Execute(ctx, json.RawMessage(`{}`)); err == nil {+ t.Fatal("Both revoked access and rejected refresh still executed a remote tool")+ }+ for {+ changes, _ := manager.Changes()+ if manager.Status().Servers[0].State == "waiting-authorization" {+ break+ }+ select {+ case <-changes:+ case <-ctx.Done():+ t.Fatal("revoked token did not enter waiting-authorization")+ }+ }+ manager.mu.RLock()+ entry := manager.entries["oauth"]+ attempts := len(manager.authorizations)+ manager.mu.RUnlock()+ select {+ case <-entry.done:+ case <-ctx.Done():+ t.Fatal("authorization failure continued reconnecting")+ }+ if attempts != 0 {+ t.Fatal("background tool failure implicitly opened an OAuth authorization")+ }+ if f.refreshes.Load() != 2 {+ t.Fatalf("Rejected refresh was repeated: requests=%d", f.refreshes.Load())+ }+}++func TestOAuthIssuerMismatchDoesNotPersistGrant(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), f.settings("test-client")); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ callback := visitOAuthAuthorization(t, view)+ callback.Issuer = "https://other-issuer.example"+ if result, err := manager.CompleteAuthorization(ctx, callback); err == nil {+ t.Fatalf("mismatched OAuth issuer was accepted: state=%s url=%t", result.State, result.URL != "")+ }+ if _, found, err := manager.oauthStore.get("oauth", manager.oauthConfigBinding("oauth", "", f.settings("test-client").Servers["oauth"])); err != nil || found {+ t.Fatal("issuer mismatch persisted a grant", err)+ }+}++func (f *oauthTestService) settings(client string) mcpconfig.Settings {+ return mcpconfig.Settings{Servers: map[string]mcpconfig.Server{"oauth": {Transport: "streamable-http", URL: f.resource.URL + "/mcp", OAuth: &mcpconfig.OAuth{ClientID: client}}}}+}++func visitOAuthAuthorization(t *testing.T, view mcpconfig.OAuthAuthorization) mcpconfig.OAuthCallback {+ t.Helper()+ if view.State != "pending" || view.URL == "" || view.ExpiresAt <= time.Now().UnixMilli() {+ t.Fatalf("not a real pending authorization: %+v", view)+ }+ client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Timeout: 3 * time.Second}+ response, err := client.Get(view.URL)+ if err != nil {+ t.Fatal(err)+ }+ defer response.Body.Close()+ if response.StatusCode != http.StatusFound {+ t.Fatalf("authorize status=%d", response.StatusCode)+ }+ location, err := response.Location()+ if err != nil {+ t.Fatal(err)+ }+ query := location.Query()+ return mcpconfig.OAuthCallback{State: query.Get("state"), Code: query.Get("code"), Issuer: query.Get("iss")}+}++func TestOAuthExplicitPKCECallbackConnectsAndRestoresWithRefresh(t *testing.T) {+ f := oauthServiceFixture(t)+ directory := t.TempDir()+ manager := NewManager(t.Context(), ManagerOptions{CWD: directory})+ defer manager.Close()+ settings := f.settings("test-client")+ if status, err := manager.Apply(t.Context(), settings); err != nil || status.Servers[0].State != "waiting-authorization" {+ t.Fatalf("initial=%+v err=%v", status, err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal("start OAuth", err)+ }+ callback := visitOAuthAuthorization(t, view)+ completed, err := manager.CompleteAuthorization(ctx, callback)+ if err != nil || completed.State != "authorized" {+ t.Fatalf("callback=%+v err=%v", completed, err)+ }+ if status := manager.Status(); status.Servers[0].State != "connected" || status.Servers[0].ToolCount != 2 {+ t.Fatalf("authorized connection=%+v", status)+ }+ if _, err := manager.CompleteAuthorization(ctx, callback); err == nil {+ t.Fatal("one-time OAuth callback was replayed")+ }+ if result, err := manager.Probe(ctx, "oauth"); err != nil || result.State != "connected" {+ t.Fatalf("authorized probe=%+v err=%v", result, err)+ }+ if err := manager.Close(); err != nil {+ t.Fatal(err)+ }+ store, _ := newOAuthGrantStore(filepath.Join(directory, ".dsh", ".credentials.yaml"))+ grant, found, err := store.get("oauth", manager.oauthConfigBinding("oauth", "", settings.Servers["oauth"]))+ if err != nil || !found {+ t.Fatal("OAuth grant was not persisted", err)+ }+ grant.Token.Expiry = time.Now().Add(-time.Hour)+ if err := store.put(ctx, "oauth", grant); err != nil {+ t.Fatal(err)+ }+ restored := NewManager(t.Context(), ManagerOptions{CWD: directory})+ defer restored.Close()+ if status, err := restored.Apply(ctx, settings); err != nil || status.Servers[0].State != "connected" {+ t.Fatalf("restart=%+v err=%v", status, err)+ }+ if f.refreshes.Load() != 1 {+ t.Fatalf("refreshes=%d; want one", f.refreshes.Load())+ }+ public, _ := json.Marshal(restored.Status())+ if strings.Contains(string(public), "access-") || strings.Contains(string(public), "refresh-") {+ t.Fatal("public status leaked a token")+ }+ if status, err := restored.DisconnectAuthorization(ctx, "oauth"); err != nil || status.Servers[0].State != "waiting-authorization" {+ t.Fatalf("disconnect=%+v err=%v", status, err)+ }+ afterSignOut, err := newOAuthGrantStore(filepath.Join(directory, ".dsh", ".credentials.yaml"))+ if err != nil {+ t.Fatal(err)+ }+ if _, found, err := afterSignOut.get("oauth", grant.Binding); err != nil || found {+ t.Fatal("sign-out retained the local OAuth grant", err)+ }+}++func TestOAuthCancellationAndResourceChangeNeverForwardOldGrant(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ settings := f.settings("test-client")+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)+ defer cancel()+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ stateURL, _ := url.Parse(view.URL)+ if _, err := manager.CancelAuthorization(ctx, "oauth"); err != nil {+ t.Fatal(err)+ }+ if _, err := manager.CompleteAuthorization(ctx, mcpconfig.OAuthCallback{State: stateURL.Query().Get("state"), Code: "late"}); err == nil {+ t.Fatal("cancelled flow accepted a callback")+ }+ view, err = manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err != nil {+ t.Fatal(err)+ }+ before := f.requests.Load()+ changed := settings.Clone()+ server := changed.Servers["oauth"]+ server.URL = f.resource.URL + "/other-resource"+ changed.Servers["oauth"] = server+ if status, err := manager.Apply(ctx, changed); err != nil || status.Servers[0].State != "waiting-authorization" {+ t.Fatalf("changed resource=%+v err=%v", status, err)+ }+ if f.requests.Load() != before+1 { // Closing the old initialized session sends its DELETE.+ t.Fatalf("unexpected requests to the changed resource: before=%d after=%d", before, f.requests.Load())+ }+}++func TestOAuthRejectedRefreshWaitsForAuthorizationWithoutRetryOrBrowserFlow(t *testing.T) {+ f := oauthServiceFixture(t)+ directory := t.TempDir()+ manager := NewManager(t.Context(), ManagerOptions{CWD: directory})+ defer manager.Close()+ settings := f.settings("test-client")+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ if _, err := manager.Apply(ctx, settings); err != nil {+ t.Fatal(err)+ }+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err != nil {+ t.Fatal(err)+ }+ if err := manager.Close(); err != nil {+ t.Fatal(err)+ }+ persisted, err := newOAuthGrantStore(filepath.Join(directory, ".dsh", ".credentials.yaml"))+ if err != nil {+ t.Fatal(err)+ }+ grant, found, err := persisted.get("oauth", manager.oauthConfigBinding("oauth", "", settings.Servers["oauth"]))+ if err != nil || !found {+ t.Fatal("missing original grant", err)+ }+ grant.Token.Expiry = time.Now().Add(-time.Hour)+ if err := persisted.put(ctx, "oauth", grant); err != nil {+ t.Fatal(err)+ }+ f.denyRefresh.Store(true)+ restored := NewManager(t.Context(), ManagerOptions{CWD: directory})+ defer restored.Close()+ status, err := restored.Apply(ctx, settings)+ if err != nil || status.Servers[0].State != "waiting-authorization" || status.Servers[0].Authorization != nil {+ t.Fatalf("refresh rejection status=%+v err=%v", status, err)+ }+ restored.mu.RLock()+ entry := restored.entries["oauth"]+ attempts := len(restored.authorizations)+ restored.mu.RUnlock()+ select {+ case <-entry.done:+ case <-ctx.Done():+ t.Fatal("rejected refresh continued reconnecting")+ }+ if attempts != 0 || f.refreshes.Load() != 1 {+ t.Fatalf("rejected refresh started another flow: attempts=%d refreshes=%d", attempts, f.refreshes.Load())+ }+}++func TestOAuthDisabledServerCanAuthorizeWithoutPublishingTools(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ settings := f.settings("test-client")+ server := settings.Servers["oauth"]+ enabled := false+ server.Enabled = &enabled+ settings.Servers["oauth"] = server+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ if _, err := manager.Apply(ctx, settings); err != nil {+ t.Fatal(err)+ }+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ result, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view))+ if err != nil || result.State != "authorized" {+ t.Fatalf("disabled authorization=%+v err=%v", result, err)+ }+ status := manager.Status().Servers[0]+ if status.State != "disabled" || status.ToolCount != 0 {+ t.Fatalf("authorization enabled a disabled server: %+v", status)+ }+ enabled = true+ if status, err := manager.Apply(ctx, settings); err != nil || status.Servers[0].State != "connected" {+ t.Fatalf("stored grant did not connect after enabling: %+v err=%v", status, err)+ }+}++func TestOAuthExpiredAttemptClearsURLAndRejectsLateCallback(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), f.settings("test-client")); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithDeadline(manager.ctx, time.Now().Add(-time.Second))+ defer cancel()+ manager.mu.Lock()+ entry := manager.entries["oauth"]+ attempt := &oauthAttempt{entry: entry, ctx: ctx, cancel: cancel, done: make(chan struct{}), ready: make(chan struct{}, 1), answer: make(chan oauthCallbackResult, 1), state: "expired-state", view: mcpconfig.OAuthAuthorization{Name: "oauth", State: "pending", URL: f.provider.URL + "/authorize", ExpiresAt: time.Now().Add(-time.Second).UnixMilli()}}+ manager.authorizations["oauth"] = attempt+ manager.mu.Unlock()+ manager.runAuthorization(attempt, "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if view := manager.Status().Servers[0].Authorization; view == nil || view.State != "expired" || view.URL != "" {+ t.Fatalf("expired flow was still actionable: %+v", view)+ }+ if _, err := manager.CompleteAuthorization(t.Context(), mcpconfig.OAuthCallback{State: "expired-state", Code: "late"}); err == nil {+ t.Fatal("expired state accepted a callback")+ }+}++func TestOAuthRefreshedTokensAreRedactedFromRemoteToolErrors(t *testing.T) {+ f := oauthServiceFixture(t)+ f.server.AddTool(&sdk.Tool{Name: "one", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ return &sdk.CallToolResult{IsError: true, Content: []sdk.Content{&sdk.TextContent{Text: "provider echoed " + f.lastAccess + " " + f.lastRefresh}}}, nil+ })+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ settings := f.settings("test-client")+ if _, err := manager.Apply(ctx, settings); err != nil {+ t.Fatal(err)+ }+ view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := manager.CompleteAuthorization(ctx, visitOAuthAuthorization(t, view)); err != nil {+ t.Fatal(err)+ }+ grant, found, err := manager.oauthStore.get("oauth", manager.oauthConfigBinding("oauth", "", settings.Servers["oauth"]))+ if err != nil || !found {+ t.Fatal("missing original grant", err)+ }+ grant.Token.Expiry = time.Now().Add(-time.Hour)+ if err := manager.oauthStore.put(ctx, "oauth", grant); err != nil {+ t.Fatal(err)+ }+ if status, err := manager.Restart(ctx, "oauth"); err != nil || status.Servers[0].State != "connected" {+ t.Fatalf("refreshed server=%+v err=%v", status, err)+ }+ f.mu.Lock()+ access, refresh := f.lastAccess, f.lastRefresh+ f.mu.Unlock()+ if access == grant.Token.AccessToken || f.refreshes.Load() != 1 {+ t.Fatal("fixture did not rotate the original tokens")+ }+ scope := manager.NewScope()+ defer scope.Close()+ tool := findTool(t, scope, PublicToolName("oauth", "one"))+ if tool == nil {+ t.Fatal("missing refreshed tool")+ }+ result, err := tool.(*Tool).ExecuteResult(ctx, json.RawMessage(`{}`))+ data, marshalErr := json.Marshal(result)+ if err != nil || marshalErr != nil || !result.IsError || !strings.Contains(string(data), "[redacted]") || strings.Contains(string(data), access) || strings.Contains(string(data), refresh) {+ t.Fatal("refreshed OAuth token escaped into the tool result or canonical metadata", err, marshalErr)+ }+}diff --git a/internal/mcpclient/probe.go b/internal/mcpclient/probe.gonew file mode 100644index 0000000..1e65298--- /dev/null+++ b/internal/mcpclient/probe.go@@ -0,0 +1,140 @@+package mcpclient++import (+ "context"+ "sync"+ "time"++ mcpconfig "go-bot/mcp"+)++type serverProbe struct {+ cancel context.CancelFunc+ done chan struct{}+}++type probeRun struct {+ call context.Context+ entry *serverEntry+ config mcpconfig.Server+ status mcpconfig.ServerStatus+ options ConnectionOptions+ finish func()+}++// beginProbe snapshots the real entry and joins its cleanup fence. Both+// client-facing projections use this same ownership and cancellation path.+func (m *Manager) beginProbe(ctx context.Context, name string, timeout time.Duration) (probeRun, error) {+ if !mcpconfig.ValidServerName(name) {+ return probeRun{}, fail("MCP_INVALID_CONFIG", "Invalid MCP server name")+ }+ m.mu.Lock()+ entry := m.entries[name]+ if entry == nil || entry.ctx.Err() != nil || m.closed {+ m.mu.Unlock()+ return probeRun{}, fail("MCP_NOT_FOUND", "MCP server is not available for probing")+ }+ if entry.cleanupFailure != nil {+ m.mu.Unlock()+ return probeRun{}, fail("MCP_CLEANUP_INCOMPLETE", "MCP probe cleanup failed; restart the Host before replacing this server")+ }+ config := (mcpconfig.Settings{Servers: map[string]mcpconfig.Server{name: entry.config}}).Clone().Servers[name]+ result := mcpconfig.ServerStatus{Name: name, Source: entry.status.Source, Owner: entry.status.Owner, Missing: append([]string(nil), entry.status.Missing...), OAuthEnabled: entry.config.OAuth != nil}+ options := m.options.Connection+ options.Secrets = append([]string(nil), options.Secrets...)+ for secret := range m.secrets {+ options.Secrets = append(options.Secrets, secret)+ }+ call, cancel := context.WithTimeout(ctx, timeout)+ stop := context.AfterFunc(entry.ctx, cancel)+ probe := &serverProbe{cancel: cancel, done: make(chan struct{})}+ if entry.probes == nil {+ entry.probes = make(map[*serverProbe]struct{})+ }+ entry.probes[probe] = struct{}{}+ m.mu.Unlock()+ var finishOnce sync.Once+ finish := func() {+ finishOnce.Do(func() {+ stop()+ cancel()+ m.mu.Lock()+ delete(entry.probes, probe)+ close(probe.done)+ m.mu.Unlock()+ })+ }+ return probeRun{call: call, entry: entry, config: config, status: result, options: options, finish: finish}, nil+}++// Probe is the bundled clients' status projection. The Cordis contract is+// ProbeDetailed; neither operation publishes persistent tools or logs in.+func (m *Manager) Probe(ctx context.Context, name string) (mcpconfig.ServerStatus, error) {+ run, err := m.beginProbe(ctx, name, RequestTimeout)+ if err != nil {+ return mcpconfig.ServerStatus{}, err+ }+ call, entry, config, result, options, finish := run.call, run.entry, run.config, run.status, run.options, run.finish+ deferredCleanup := false+ defer func() {+ if !deferredCleanup {+ finish()+ }+ }()+ if len(result.Missing) > 0 {+ result.State = "waiting-credentials"+ return result, nil+ }+ if config.OAuth != nil {+ var err error+ options, err = m.connectionOptions(entry)+ if authorizationRequired(err) {+ result.State = "waiting-authorization"+ return result, nil+ }+ if err != nil {+ result.State, result.Error = "failed", m.redact(err.Error())+ return result, nil+ }+ }+ options.connectCleanup = func(err error) {+ if err != nil {+ m.retainCleanup(entry, mcpconfig.CloseResult{CloseConfirmed: false, CleanupError: m.redact(err.Error())})+ }+ }+ connection, err := Connect(call, name, config, options)+ if err != nil {+ if authorizationRequired(err) {+ result.State = "waiting-authorization"+ return result, nil+ }+ result.State, result.Error = "failed", m.redact(err.Error())+ return result, nil+ }+ discovery, discoverErr := connection.Discover(call)+ closeErr := connection.Close()+ if closeErr != nil {+ closed := false+ select {+ case <-connection.Closed():+ closed = true+ default:+ }+ m.retainCleanup(entry, mcpconfig.CloseResult{CloseConfirmed: closed, CleanupError: m.redact(closeErr.Error())})+ // Keep this probe in the entry's cleanup fence until the transport is+ // actually closed. A replacement must not overlap an orphan process.+ deferredCleanup = true+ go func() { <-connection.Closed(); finish() }()+ result.State, result.Error = "stopping", m.redact(closeErr.Error())+ return result, closeErr+ }+ if discoverErr != nil {+ result.State, result.Error = "failed", m.redact(discoverErr.Error())+ return result, nil+ }+ result.State, result.ToolCount, result.Resources, result.ProtocolVersion = "connected", len(discovery.Tools), discovery.Resources, discovery.ProtocolVersion+ if discovery.ServerInfo != nil {+ result.ServerName = discovery.ServerInfo.Name+ }+ return result, nil+}diff --git a/internal/mcpclient/probe_detailed.go b/internal/mcpclient/probe_detailed.gonew file mode 100644index 0000000..ec209d4--- /dev/null+++ b/internal/mcpclient/probe_detailed.go@@ -0,0 +1,182 @@+package mcpclient++import (+ "context"+ "math"+ "strings"+ "time"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ mcpconfig "go-bot/mcp"+)++type probeSpec struct {+ timeout time.Duration+ maxPages, maxNames int64+}++func resolveProbeOptions(options mcpconfig.ProbeOptions) (probeSpec, error) {+ spec := probeSpec{timeout: 10 * time.Second, maxPages: 16, maxNames: 512}+ if options.TimeoutMS != nil {+ value := *options.TimeoutMS+ if math.IsNaN(value) || math.IsInf(value, 0) || value <= 0 {+ return spec, fail("MCP_INVALID_PROBE_OPTIONS", "timeoutMs must be a positive finite number")+ }+ if value >= float64(math.MaxInt64)/float64(time.Millisecond) {+ spec.timeout = time.Duration(math.MaxInt64)+ } else {+ spec.timeout = time.Duration(value * float64(time.Millisecond))+ }+ }+ for _, field := range []struct {+ name string+ input *int64+ target *int64+ }{{"maxPages", options.MaxPages, &spec.maxPages}, {"maxToolNames", options.MaxToolNames, &spec.maxNames}} {+ if field.input == nil {+ continue+ }+ if *field.input < 1 || *field.input > 9007199254740991 {+ return spec, fail("MCP_INVALID_PROBE_OPTIONS", field.name+" must be a positive safe integer")+ }+ *field.target = *field.input+ }+ return spec, nil+}++// ProbeDetailed implements the original plugin-facing probe contract. It+// lists raw advertised names, without publishing or compiling model tools.+// Expected connection/list/cancellation failures are values, not RPC errors.+func (m *Manager) ProbeDetailed(ctx context.Context, name string, options mcpconfig.ProbeOptions) (mcpconfig.ProbeResult, error) {+ spec, err := resolveProbeOptions(options)+ if err != nil {+ return mcpconfig.ProbeResult{}, err+ }+ started := time.Now()+ run, err := m.beginProbe(ctx, name, spec.timeout)+ if err != nil {+ return mcpconfig.ProbeResult{}, err+ }+ deferredCleanup := false+ defer func() {+ if !deferredCleanup {+ run.finish()+ }+ }()+ result := mcpconfig.ProbeResult{CloseResult: mcpconfig.CloseResult{CloseConfirmed: true}, Stage: "connect", ToolNames: []string{}}+ failure := func(message string) (mcpconfig.ProbeResult, error) {+ result.OK = false+ result.Message = m.redact(message)+ if ctx.Err() != nil || run.entry.ctx.Err() != nil {+ result.Message = "probe aborted"+ } else if run.call.Err() != nil {+ result.Message = "probe timed out"+ }+ result.DurationMS = time.Since(started).Milliseconds()+ return result, nil+ }+ if run.call.Err() != nil {+ return failure(run.call.Err().Error())+ }+ if len(run.status.Missing) > 0 {+ return failure("Missing credentials: " + strings.Join(run.status.Missing, ", "))+ }+ connectionOptions := run.options+ if run.config.OAuth != nil {+ connectionOptions, err = m.connectionOptions(run.entry)+ if err != nil {+ return failure(err.Error())+ }+ }+ // The whole probe budget owns negotiation; the live instance's startup+ // timeout does not shorten this independent operation.+ connectionOptions.StartupTimeout = spec.timeout+ connectionOptions.connectCleanup = func(cleanupErr error) {+ if cleanupErr != nil {+ result.CloseConfirmed = false+ result.CleanupError = m.redact(cleanupErr.Error())+ }+ }+ connection, err := Connect(run.call, name, run.config, connectionOptions)+ if err != nil {+ if result.CleanupError != "" {+ // Failed negotiation returned no connection handle whose closure can+ // later be confirmed. Retain the namespace instead of retrying it.+ m.retainCleanup(run.entry, result.CloseResult)+ }+ return failure(err.Error())+ }+ result.Stage = "list"+ info := connection.Session.InitializeResult()+ if info.ServerInfo != nil {+ result.ServerInfo = &mcpconfig.ProbeServerInfo{Name: info.ServerInfo.Name, Version: info.ServerInfo.Version}+ }+ var listErr error+ if info.Capabilities != nil && info.Capabilities.Tools != nil {+ cursor := ""+ for page := int64(0); page < spec.maxPages; page++ {+ response, err := connection.Session.ListTools(run.call, &sdk.ListToolsParams{Cursor: cursor})+ if err != nil {+ listErr = connection.requestError(run.call, err)+ break+ }+ for _, tool := range response.Tools {+ if int64(len(result.ToolNames)) >= spec.maxNames {+ result.Truncated = true+ break+ }+ if tool == nil {+ listErr = fail("MCP_INVALID_LIST", "MCP probe received a null tool")+ break+ }+ result.ToolNames = append(result.ToolNames, tool.Name)+ }+ if listErr != nil {+ break+ }+ cursor = response.NextCursor+ if cursor == "" || result.Truncated {+ break+ }+ if page == spec.maxPages-1 {+ result.Truncated = true+ }+ }+ }+ if listErr == nil && run.call.Err() != nil {+ listErr = run.call.Err()+ }+ if listErr != nil {+ result, _ = failure(listErr.Error())+ } else {+ result.OK = true+ result.DurationMS = time.Since(started).Milliseconds()+ }+ // Capture the outcome before closing: duration excludes cleanup and a+ // cleanup failure must not turn a successful listing into a list failure.+ closeErr := connection.Close()+ select {+ case <-connection.Closed():+ result.CloseConfirmed = true+ default:+ result.CloseConfirmed = false+ deferredCleanup = true+ go func() { <-connection.Closed(); run.finish() }()+ }+ if closeErr != nil {+ result.CleanupError = m.redact(closeErr.Error())+ m.retainCleanup(run.entry, result.CloseResult)+ }+ return result, nil+}++func (m *Manager) retainCleanup(entry *serverEntry, result mcpconfig.CloseResult) {+ m.mu.Lock()+ if m.entries[entry.name] == entry && entry.cleanupFailure == nil {+ copy := result+ entry.cleanupFailure = ©+ entry.status.State, entry.status.Error = "failed", result.CleanupError+ }+ m.mu.Unlock()+ m.changed()+}diff --git a/internal/mcpclient/probe_detailed_test.go b/internal/mcpclient/probe_detailed_test.gonew file mode 100644index 0000000..f98cff3--- /dev/null+++ b/internal/mcpclient/probe_detailed_test.go@@ -0,0 +1,237 @@+package mcpclient++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "reflect"+ "strings"+ "testing"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ mcpconfig "go-bot/mcp"+)++func TestDetailedProbeKeepsRawNamesIdentityCapsAndLiveGeneration(t *testing.T) {+ manager, _, _ := managedFixture(t, "eager")+ scope := manager.NewScope()+ defer scope.Close()+ before := manager.Status()+ tool := findTool(t, scope, PublicToolName("fixture", "one"))+ for _, limit := range []struct {+ pages, names int64+ expected []string+ truncated bool+ }{+ {16, 512, []string{"one", "two"}, false},+ {1, 512, []string{"one"}, true},+ {16, 1, []string{"one"}, true},+ {16, 2, []string{"one", "two"}, false},+ } {+ result, err := manager.ProbeDetailed(t.Context(), "fixture", mcpconfig.ProbeOptions{MaxPages: &limit.pages, MaxToolNames: &limit.names})+ if err != nil || !result.OK || !result.CloseConfirmed || result.CleanupError != "" || result.Truncated != limit.truncated || !reflect.DeepEqual(result.ToolNames, limit.expected) {+ t.Fatalf("probe limits %+v: %+v %v", limit, result, err)+ }+ if result.ServerInfo == nil || result.ServerInfo.Name != "remote-name-is-not-our-namespace" || result.ServerInfo.Version != "1.0.0" {+ t.Fatalf("lost raw server identity: %+v", result)+ }+ data, _ := json.Marshal(result)+ if bytes.Contains(data, []byte(`"stage"`)) || bytes.Contains(data, []byte(`"message"`)) {+ t.Fatalf("success contains failure fields: %s", data)+ }+ }+ if !reflect.DeepEqual(before, manager.Status()) || tool != findTool(t, scope, PublicToolName("fixture", "one")) {+ t.Fatal("one-shot probe changed the active generation")+ }+}++func TestDetailedProbeEmptySuccessAndWaitingCredentialsAreRealOutcomes(t *testing.T) {+ server := sdk.NewServer(&sdk.Implementation{Name: "empty", Version: "1"}, nil)+ remote := httptest.NewServer(sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil))+ defer remote.Close()+ manager := NewManager(t.Context(), ManagerOptions{})+ defer manager.Close()+ disabled := false+ if _, err := manager.Apply(t.Context(), mcpconfig.Settings{Servers: map[string]mcpconfig.Server{+ "empty": {Enabled: &disabled, Transport: "streamable-http", URL: remote.URL},+ "key": {Transport: "streamable-http", URL: remote.URL, Headers: map[string]string{"Authorization": "Bearer ${credential:missing}"}},+ "oauth": {Transport: "streamable-http", URL: remote.URL, OAuth: &mcpconfig.OAuth{ClientID: "example-client"}},+ }}); err != nil {+ t.Fatal(err)+ }+ result, err := manager.ProbeDetailed(t.Context(), "empty", mcpconfig.ProbeOptions{})+ if err != nil || !result.OK || len(result.ToolNames) != 0 || result.Truncated || !result.CloseConfirmed {+ t.Fatalf("empty: %+v %v", result, err)+ }+ data, _ := json.Marshal(result)+ if !bytes.Contains(data, []byte(`"toolNames":[]`)) || !bytes.Contains(data, []byte(`"truncated":false`)) {+ t.Fatalf("empty success wire shape: %s", data)+ }+ for _, name := range []string{"key", "oauth"} {+ result, err := manager.ProbeDetailed(t.Context(), name, mcpconfig.ProbeOptions{})+ if err != nil || result.OK || result.Stage != "connect" || result.Message == "" || !result.CloseConfirmed {+ t.Fatalf("waiting %s: %+v %v", name, result, err)+ }+ data, _ := json.Marshal(result)+ if bytes.Contains(data, []byte(`"toolNames"`)) || bytes.Contains(data, []byte(`"serverInfo"`)) {+ t.Fatalf("failure wire shape: %s", data)+ }+ }+}++func TestDetailedProbeSeparatesConnectListTimeoutAndCancellation(t *testing.T) {+ for _, behavior := range []string{"connect-error", "list-error", "timeout", "cancel-list"} {+ t.Run(behavior, func(t *testing.T) {+ server := testServer()+ handler := sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil)+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == http.MethodPost {+ data, _ := io.ReadAll(r.Body)+ r.Body = io.NopCloser(bytes.NewReader(data))+ var request struct {+ Method string `json:"method"`+ }+ _ = json.Unmarshal(data, &request)+ if behavior == "connect-error" {+ http.Error(w, "connection fixture rejected", 500)+ return+ }+ if behavior == "timeout" {+ <-r.Context().Done()+ return+ }+ if request.Method == "tools/list" {+ if behavior == "list-error" {+ http.Error(w, "listing fixture rejected", 500)+ return+ }+ if behavior == "cancel-list" {+ cancel()+ <-r.Context().Done()+ return+ }+ }+ }+ handler.ServeHTTP(w, r)+ }))+ defer remote.Close()+ manager := NewManager(t.Context(), ManagerOptions{})+ defer manager.Close()+ disabled := false+ if _, err := manager.Apply(t.Context(), mcpconfig.Settings{Servers: map[string]mcpconfig.Server{"test": {Enabled: &disabled, Transport: "streamable-http", URL: remote.URL}}}); err != nil {+ t.Fatal(err)+ }+ options := mcpconfig.ProbeOptions{}+ if behavior == "timeout" {+ ms := float64(60)+ options.TimeoutMS = &ms+ }+ result, err := manager.ProbeDetailed(ctx, "test", options)+ stage := "connect"+ if behavior == "list-error" || behavior == "cancel-list" {+ stage = "list"+ }+ if err != nil || result.OK || result.Stage != stage || result.Message == "" || !result.CloseConfirmed || result.CleanupError != "" {+ t.Fatalf("%s: %+v %v", behavior, result, err)+ }+ if behavior == "timeout" && result.Message != "probe timed out" {+ t.Fatalf("timeout: %+v", result)+ }+ if behavior == "cancel-list" && result.Message != "probe aborted" {+ t.Fatalf("cancel: %+v", result)+ }+ })+ }+}++type probeCloseErrorTransport struct{ base sdk.Transport }++func (t probeCloseErrorTransport) Connect(ctx context.Context) (sdk.Connection, error) {+ c, err := t.base.Connect(ctx)+ if err != nil {+ return nil, err+ }+ return probeCloseErrorConnection{c}, nil+}++type probeCloseErrorConnection struct{ sdk.Connection }++func (c probeCloseErrorConnection) Close() error {+ return errors.Join(c.Connection.Close(), errors.New("probe cleanup fixture failed"))+}++func TestDetailedProbeKeepsSuccessAndCleanupFailureSeparateAndBlocksReplacement(t *testing.T) {+ clientTransport, serverTransport := sdk.NewInMemoryTransports()+ server := testServer()+ session, err := server.Connect(t.Context(), serverTransport, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer session.Close()+ manager := NewManager(t.Context(), ManagerOptions{Connection: ConnectionOptions{Transport: probeCloseErrorTransport{clientTransport}}})+ defer manager.Close()+ disabled := false+ if _, err := manager.Apply(t.Context(), mcpconfig.Settings{Servers: map[string]mcpconfig.Server{"test": {Enabled: &disabled, Transport: "streamable-http", URL: "http://fixture.invalid/mcp"}}}); err != nil {+ t.Fatal(err)+ }+ result, err := manager.ProbeDetailed(t.Context(), "test", mcpconfig.ProbeOptions{})+ if err != nil || !result.OK || len(result.ToolNames) != 2 || !result.CloseConfirmed || !strings.Contains(result.CleanupError, "fixture failed") {+ t.Fatalf("cleanup overwrote probe outcome: %+v %v", result, err)+ }+ if _, err := manager.ProbeDetailed(t.Context(), "test", mcpconfig.ProbeOptions{}); err == nil {+ t.Fatal("cleanup failure allowed another probe")+ }+ if _, err := manager.Restart(t.Context(), "test"); err == nil {+ t.Fatal("cleanup failure allowed replacement")+ }+ if status := manager.Status(); len(status.Servers) != 1 || status.Servers[0].State != "failed" {+ t.Fatalf("cleanup diagnostic not retained: %+v", status)+ }+}++func TestDetailedProbeRejectsInvalidOptionsBeforeStartingWork(t *testing.T) {+ manager := NewManager(t.Context(), ManagerOptions{})+ defer manager.Close()+ zero := float64(0)+ negative := int64(-1)+ for _, options := range []mcpconfig.ProbeOptions{{TimeoutMS: &zero}, {MaxPages: &negative}, {MaxToolNames: &negative}} {+ _, err := manager.ProbeDetailed(t.Context(), "unknown", options)+ var failure *Error+ if !errors.As(err, &failure) || failure.Code != "MCP_INVALID_PROBE_OPTIONS" {+ t.Fatalf("invalid options reached server lookup: %v", err)+ }+ }+}++func TestDetailedProbeRedactsResolvedCredentialsInFailureValues(t *testing.T) {+ secret := "fixture-probe-secret-only"+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {+ if request.Header.Get("Authorization") != "Bearer "+secret {+ t.Error("probe did not receive its configured credential")+ }+ http.Error(w, "provider rejected "+secret, http.StatusInternalServerError)+ }))+ defer remote.Close()+ manager := NewManager(t.Context(), ManagerOptions{})+ defer manager.Close()+ disabled := false+ if _, err := manager.Apply(t.Context(), mcpconfig.Settings{Credentials: map[string]string{"probe/key": secret}, Servers: map[string]mcpconfig.Server{+ "private": {Enabled: &disabled, Transport: "streamable-http", URL: remote.URL, Headers: map[string]string{"Authorization": "Bearer ${credential:probe/key}"}},+ }}); err != nil {+ t.Fatal(err)+ }+ result, err := manager.ProbeDetailed(t.Context(), "private", mcpconfig.ProbeOptions{})+ if err != nil || result.OK || result.Message == "" {+ t.Fatalf("expected a failure value: %+v %v", result, err)+ }+ data, _ := json.Marshal(result)+ if bytes.Contains(data, []byte(secret)) {+ t.Fatalf("probe exposed resolved credentials: %s", data)+ }+}diff --git a/internal/mcpclient/probe_test.go b/internal/mcpclient/probe_test.gonew file mode 100644index 0000000..db1cf01--- /dev/null+++ b/internal/mcpclient/probe_test.go@@ -0,0 +1,142 @@+package mcpclient++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "reflect"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ mcpconfig "go-bot/mcp"+)++func TestProbeDoesNotPublishToolsOrReplaceManagedGeneration(t *testing.T) {+ manager, _, _ := managedFixture(t, "eager")+ scope := manager.NewScope()+ defer scope.Close()+ tool := findTool(t, scope, PublicToolName("fixture", "one"))+ before := manager.Status()+ result, err := manager.Probe(t.Context(), "fixture")+ if err != nil || result.State != "connected" || result.ToolCount != 2 || !result.Resources || result.ProtocolVersion == "" {+ t.Fatalf("probe=%+v err=%v", result, err)+ }+ if !reflect.DeepEqual(before, manager.Status()) || findTool(t, scope, PublicToolName("fixture", "one")) != tool {+ t.Fatal("probe mutated managed state or replaced an active handler")+ }+}++func TestDisabledEntryProbeClosesItsTemporarySessionAndPublishesNothing(t *testing.T) {+ server := testServer()+ remote := httptest.NewServer(sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil))+ defer remote.Close()+ manager := NewManager(t.Context(), ManagerOptions{})+ defer manager.Close()+ disabled := false+ if _, err := manager.Apply(t.Context(), mcpconfig.Settings{Servers: map[string]mcpconfig.Server{"disabled": {Enabled: &disabled, Transport: "streamable-http", URL: remote.URL}}}); err != nil {+ t.Fatal(err)+ }+ before := manager.Status()+ result, err := manager.Probe(t.Context(), "disabled")+ if err != nil || result.State != "connected" || result.ToolCount != 2 {+ t.Fatalf("probe=%+v err=%v", result, err)+ }+ scope := manager.NewScope()+ defer scope.Close()+ tools, err := scope.Tools(t.Context(), "")+ if err != nil || len(tools) != 0 || !reflect.DeepEqual(before, manager.Status()) {+ t.Fatal("disabled probe activated persistent tools or state", err)+ }+ deadline := time.Now().Add(2 * time.Second)+ for {+ count := 0+ for range server.Sessions() {+ count+++ }+ if count == 0 {+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("temporary MCP session was not closed")+ }+ time.Sleep(5 * time.Millisecond)+ }+}++func TestProbeWaitsForCredentialsWithoutRequestsOrImplicitOAuth(t *testing.T) {+ var calls atomic.Int32+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1); http.Error(w, "unexpected request", 500) }))+ defer remote.Close()+ manager := NewManager(t.Context(), ManagerOptions{})+ defer manager.Close()+ settings := mcpconfig.Settings{Servers: map[string]mcpconfig.Server{+ "key": {Transport: "streamable-http", URL: remote.URL, Headers: map[string]string{"Authorization": "Bearer ${credential:key}"}},+ "oauth": {Transport: "streamable-http", URL: remote.URL, OAuth: &mcpconfig.OAuth{ClientID: "client"}},+ }}+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ for name, want := range map[string]string{"key": "waiting-credentials", "oauth": "waiting-authorization"} {+ result, err := manager.Probe(t.Context(), name)+ if err != nil || result.State != want {+ t.Fatalf("%s probe=%+v err=%v", name, result, err)+ }+ }+ if calls.Load() != 0 {+ t.Fatal("a waiting probe attempted a connection or login")+ }+}++func TestRemovingServerCancelsProbeAndWaitsForTemporaryCleanup(t *testing.T) {+ server := testServer()+ handler := sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil)+ started := make(chan struct{}, 1)+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == http.MethodPost {+ data, _ := io.ReadAll(r.Body)+ r.Body = io.NopCloser(strings.NewReader(string(data)))+ var message struct {+ Method string `json:"method"`+ }+ _ = json.Unmarshal(data, &message)+ if message.Method == "tools/list" {+ started <- struct{}{}+ <-r.Context().Done()+ return+ }+ }+ handler.ServeHTTP(w, r)+ }))+ defer remote.Close()+ manager := NewManager(t.Context(), ManagerOptions{})+ defer manager.Close()+ disabled := false+ if _, err := manager.Apply(t.Context(), mcpconfig.Settings{Servers: map[string]mcpconfig.Server{"probe": {Enabled: &disabled, Transport: "streamable-http", URL: remote.URL}}}); err != nil {+ t.Fatal(err)+ }+ finished := make(chan error, 1)+ go func() { _, err := manager.Probe(t.Context(), "probe"); finished <- err }()+ select {+ case <-started:+ case <-time.After(3 * time.Second):+ t.Fatal("probe did not reach discovery")+ }+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ if _, err := manager.Apply(ctx, mcpconfig.Settings{}); err != nil {+ t.Fatal("removal did not drain the probe", err)+ }+ select {+ case <-finished:+ case <-ctx.Done():+ t.Fatal("probe did not settle after removal")+ }+ if len(manager.Status().Servers) != 0 {+ t.Fatal("removed server or temporary probe stayed registered")+ }+}diff --git a/internal/mcpclient/resources.go b/internal/mcpclient/resources.gonew file mode 100644index 0000000..798da79--- /dev/null+++ b/internal/mcpclient/resources.go@@ -0,0 +1,133 @@+package mcpclient++import (+ "context"+ "encoding/json"+ "fmt"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ "go-bot/harness/agent"+ "go-bot/harness/content"+ "go-bot/internal/modeldata"+ mcpconfig "go-bot/mcp"+)++func (m *Manager) resourceConnection(name string) (*Connection, error) {+ m.mu.RLock()+ defer m.mu.RUnlock()+ entry := m.entries[name]+ if entry == nil || !entry.config.IsEnabled() {+ return nil, fail("MCP_NOT_FOUND", "MCP server not configured: "+name)+ }+ if entry.status.State == "waiting-authorization" {+ return nil, fail("MCP_AUTHORIZATION_REQUIRED", "Authorize this MCP server in settings before using it")+ }+ if entry.status.State == "waiting-credentials" {+ return nil, fail("MCP_CREDENTIALS_REQUIRED", "Configure this MCP server's credentials before using it")+ }+ if entry.status.State != "connected" || entry.connection == nil {+ return nil, fail("MCP_SERVER_UNAVAILABLE", "MCP server is not connected: "+name)+ }+ return entry.connection, nil+}++type resourceTool struct {+ manager *Manager+ name string+}++func (t *resourceTool) Spec() agent.ToolSpec {+ parameters := json.RawMessage(`{"type":"object","properties":{"server":{"type":"string"}},"required":["server"],"additionalProperties":false}`)+ description := "List resources from an explicitly configured MCP server."+ if t.name == "list_mcp_resource_templates" {+ description = "List resource URI templates from an explicitly configured MCP server."+ }+ if t.name == "read_mcp_resource" {+ description = "Read a resource URI from an explicitly configured MCP server."+ parameters = json.RawMessage(`{"type":"object","properties":{"server":{"type":"string"},"uri":{"type":"string"}},"required":["server","uri"],"additionalProperties":false}`)+ }+ return agent.ToolSpec{Name: t.name, Description: description, Parameters: parameters, Timeout: RequestTimeout}+}+func (t *resourceTool) Validate(raw json.RawMessage) error {+ var input struct {+ Server string `json:"server"`+ URI string `json:"uri"`+ }+ if json.Unmarshal(raw, &input) != nil || !mcpconfig.ValidServerName(input.Server) || (t.name == "read_mcp_resource" && input.URI == "") {+ return fail("MCP_INVALID_ARGUMENTS", "Specify a configured MCP server and required resource URI")+ }+ return nil+}+func (t *resourceTool) Execute(ctx context.Context, raw json.RawMessage) (string, error) {+ result, err := t.ExecuteResult(ctx, raw)+ if err != nil {+ return "", err+ }+ data, _ := json.Marshal(result.ContentBlocks)+ return string(data), nil+}+func (t *resourceTool) ExecutePresented(ctx context.Context, raw json.RawMessage) (string, json.RawMessage, error) {+ result, err := t.ExecuteResult(ctx, raw)+ return result.Content, result.Meta, err+}+func (t *resourceTool) ExecuteRich(ctx context.Context, raw json.RawMessage) (string, []content.ContentBlock, json.RawMessage, error) {+ result, err := t.ExecuteResult(ctx, raw)+ return result.Content, result.ContentBlocks, result.Meta, err+}+func (t *resourceTool) ExecuteResult(ctx context.Context, raw json.RawMessage) (modeldata.ToolResult, error) {+ var empty modeldata.ToolResult+ if err := t.Validate(raw); err != nil {+ return empty, err+ }+ var input struct {+ Server string `json:"server"`+ URI string `json:"uri"`+ }+ _ = json.Unmarshal(raw, &input)+ connection, err := t.manager.resourceConnection(input.Server)+ if err != nil {+ return empty, err+ }+ result := &sdk.CallToolResult{}+ switch t.name {+ case "list_mcp_resources":+ resources, err := connection.Resources(ctx)+ if err != nil {+ return empty, err+ }+ result.StructuredContent = map[string]any{"resources": resources}+ case "list_mcp_resource_templates":+ templates, err := connection.ResourceTemplates(ctx)+ if err != nil {+ return empty, err+ }+ result.StructuredContent = map[string]any{"resourceTemplates": templates}+ case "read_mcp_resource":+ resource, err := connection.ReadResource(ctx, input.URI)+ if err != nil {+ return empty, err+ }+ for _, row := range resource.Contents {+ if row == nil {+ return empty, fail("MCP_INVALID_RESULT", "MCP resource contains an empty entry")+ }+ if len(row.Blob) > 0 && supportedImageType(row.MIMEType) {+ result.Content = append(result.Content, &sdk.TextContent{Text: fmt.Sprintf("MCP resource %s", row.URI)}, &sdk.ImageContent{Data: row.Blob, MIMEType: row.MIMEType})+ } else {+ result.Content = append(result.Content, &sdk.EmbeddedResource{Resource: row})+ }+ }+ default:+ return empty, fail("MCP_INVALID_ARGUMENTS", "Unknown MCP resource operation")+ }+ adapter := &Tool{connection: connection, definition: ToolDefinition{RawName: t.name}, options: ToolOptions{Images: t.manager.options.Images}}+ return adapter.materialize(ctx, result)+}++func supportedImageType(mime string) bool {+ switch mime {+ case "image/png", "image/jpeg", "image/webp", "image/gif":+ return true+ }+ return false+}diff --git a/internal/mcpclient/runtime_status.go b/internal/mcpclient/runtime_status.gonew file mode 100644index 0000000..af25bae--- /dev/null+++ b/internal/mcpclient/runtime_status.go@@ -0,0 +1,66 @@+package mcpclient++import (+ "strings"++ mcpconfig "go-bot/mcp"+)++func (c *Connection) authorizationFailure() error {+ if detail := c.authorizationError.Load(); detail != nil {+ return detail+ }+ return authorizationFailure("rejected", "Reconnect this MCP server with OAuth")+}++func transportClosed(connection *Connection) bool {+ if connection == nil {+ return false+ }+ select {+ case <-connection.Closed():+ return true+ default:+ return false+ }+}++func (m *Manager) closeGeneration(entry *serverEntry, connection *Connection) error {+ err := connection.Close()+ if err != nil {+ m.retainCleanup(entry, mcpconfig.CloseResult{CloseConfirmed: transportClosed(connection), CleanupError: m.redact(err.Error())})+ }+ return err+}++// Called under m.mu. The values are recorded by the actual supervisor, not+// inferred from Node timers or a public diagnostic's wording.+func (m *Manager) runtimeStatusLocked(entry *serverEntry) mcpconfig.ManagedServerStatus {+ if entry.cleanupFailure != nil {+ result := *entry.cleanupFailure+ return mcpconfig.ManagedServerStatus{State: "failed", Reason: "cleanup", Result: &result}+ }+ state := entry.status.State+ if entry.ctx.Err() != nil {+ confirmed := false+ select {+ case <-entry.done:+ confirmed = entry.connection == nil || transportClosed(entry.connection)+ default:+ }+ return mcpconfig.ManagedServerStatus{State: "closed", Result: &mcpconfig.CloseResult{CloseConfirmed: confirmed}}+ }+ status := mcpconfig.ManagedServerStatus{State: state, LastError: entry.status.Error, Attempt: entry.attempt, MaxAttempts: 10, NextRetryAtMS: entry.nextRetryAt, ConnectedAt: entry.connectedAt, ToolCount: entry.status.ToolCount}+ switch state {+ case "waiting-credentials":+ status.LastError = "Missing MCP credentials: " + strings.Join(entry.status.Missing, ", ")+ case "waiting-authorization":+ status.Reason = entry.authorizationReason+ if status.Reason == "" {+ status.Reason = "rejected"+ }+ case "failed":+ status.Reason = "gave-up"+ }+ return status+}diff --git a/internal/mcpclient/runtime_status_test.go b/internal/mcpclient/runtime_status_test.gonew file mode 100644index 0000000..82f6123--- /dev/null+++ b/internal/mcpclient/runtime_status_test.go@@ -0,0 +1,222 @@+package mcpclient++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "path/filepath"+ "sync/atomic"+ "testing"+ "time"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ mcpconfig "go-bot/mcp"+)++func waitRuntimeStatus(t *testing.T, manager *Manager, state string) mcpconfig.ManagedServerStatus {+ t.Helper()+ timer := time.NewTimer(5 * time.Second)+ defer timer.Stop()+ for {+ changed, _ := manager.Changes()+ for _, row := range manager.ListViews() {+ if row.Status.State == state {+ return row.Status+ }+ }+ select {+ case <-changed:+ case <-timer.C:+ t.Fatalf("did not reach %s: %+v", state, manager.ListViews())+ }+ }+}++func TestRuntimeStatusUsesRealConnectAndReconnectTimings(t *testing.T) {+ var unavailable atomic.Bool+ unavailable.Store(true)+ server := testServer()+ handler := sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil)+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if unavailable.Load() {+ http.Error(w, "temporary outage", 503)+ return+ }+ handler.ServeHTTP(w, r)+ }))+ defer remote.Close()+ manager := NewManager(t.Context(), ManagerOptions{})+ defer manager.Close()+ before := time.Now().UnixMilli()+ if _, err := manager.Apply(t.Context(), mcpconfig.Settings{Servers: map[string]mcpconfig.Server{"fixture": {Transport: "streamable-http", URL: remote.URL}}}); err == nil {+ t.Fatal("first failed attempt should report its failure")+ }+ retrying := waitRuntimeStatus(t, manager, "reconnecting")+ if retrying.Attempt < 1 || retrying.MaxAttempts != 10 || retrying.NextRetryAtMS < before+450 || retrying.LastError == "" {+ t.Fatalf("retry facts missing: %+v", retrying)+ }+ unavailable.Store(false)+ connected := waitRuntimeStatus(t, manager, "connected")+ if connected.ToolCount != 2 || connected.ConnectedAt < before || connected.ConnectedAt > time.Now().UnixMilli() {+ t.Fatalf("connect facts missing: %+v", connected)+ }+ server.AddTool(&sdk.Tool{Name: "third", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {+ return &sdk.CallToolResult{}, nil+ })+ timer := time.NewTimer(5 * time.Second)+ defer timer.Stop()+ for {+ changed, _ := manager.Changes()+ status := manager.ListViews()[0].Status+ if status.ToolCount == 3 {+ if status.ConnectedAt != connected.ConnectedAt {+ t.Fatal("catalog sync reset the connection timestamp")+ }+ break+ }+ select {+ case <-changed:+ case <-timer.C:+ t.Fatal("tools notification was not reflected")+ }+ }+ data, err := json.Marshal(manager.ListViews()[0])+ if err != nil {+ t.Fatal(err)+ }+ var row map[string]any+ if err := json.Unmarshal(data, &row); err != nil {+ t.Fatal(err)+ }+ status := row["status"].(map[string]any)+ if len(status) != 3 || status["connectedAt"] == nil || status["toolCount"] != float64(3) {+ t.Fatalf("status is not the connected union: %s", data)+ }+ if err := manager.Close(); err != nil {+ t.Fatal(err)+ }+ if status := manager.ListViews()[0].Status; status.State != "closed" || status.Result == nil || !status.Result.CloseConfirmed {+ t.Fatalf("closed manager advertises a new connection: %+v", status)+ }+}++func TestRuntimeStatusRetainsFailedGenerationCleanup(t *testing.T) {+ client, remote := sdk.NewInMemoryTransports()+ server := testServer()+ session, err := server.Connect(t.Context(), remote, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer session.Close()+ manager := NewManager(t.Context(), ManagerOptions{Connection: ConnectionOptions{Transport: probeCloseErrorTransport{base: client}}})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), mcpconfig.Settings{Servers: map[string]mcpconfig.Server{"fixture": {Transport: "stdio", Command: "not-spawned"}}}); err != nil {+ t.Fatal(err)+ }+ if _, err := manager.Restart(t.Context(), "fixture"); err == nil {+ t.Fatal("failed cleanup allowed a replacement")+ }+ status := manager.ListViews()[0].Status+ if status.State != "failed" || status.Reason != "cleanup" || status.Result == nil || !status.Result.CloseConfirmed || status.Result.CleanupError == "" {+ t.Fatalf("cleanup facts missing: %+v", status)+ }+ if _, err := manager.Restart(t.Context(), "fixture"); err == nil {+ t.Fatal("retained cleanup failure was forgotten")+ }+}++func TestRuntimeAuthorizationReasonsComeFromCredentialAndProviderFailures(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})+ defer manager.Close()+ settings := f.settings("test-client")+ if _, err := manager.Apply(t.Context(), settings); err != nil {+ t.Fatal(err)+ }+ if status := manager.ListViews()[0].Status; status.State != "waiting-authorization" || status.Reason != "missing" || status.LastError == "" {+ t.Fatalf("missing grant reason: %+v", status)+ }+ grant := fixtureOAuthGrant()+ grant.Binding = "wrong-binding"+ if err := manager.oauthStore.put(t.Context(), "oauth", grant); err != nil {+ t.Fatal(err)+ }+ if _, err := manager.Restart(t.Context(), "oauth"); err != nil {+ t.Fatal(err)+ }+ if status := manager.ListViews()[0].Status; status.Reason != "binding" {+ t.Fatalf("binding mismatch reason: %+v", status)+ }+ manager.mu.RLock()+ grant.Binding = manager.entries["oauth"].oauthBinding+ manager.mu.RUnlock()+ grant.ServerURL = settings.Servers["oauth"].URL+ configuredClientID := settings.Servers["oauth"].OAuth.ClientID+ grant.ConfiguredClientID = &configuredClientID+ grant.Token.Expiry = time.Now().Add(-time.Hour)+ grant.Token.RefreshToken = ""+ if err := manager.oauthStore.put(t.Context(), "oauth", grant); err != nil {+ t.Fatal(err)+ }+ if _, err := manager.Restart(t.Context(), "oauth"); err != nil {+ t.Fatal(err)+ }+ if status := manager.ListViews()[0].Status; status.Reason != "expired" {+ t.Fatalf("expired grant reason: %+v", status)+ }+ response := httptest.NewRecorder()+ response.Header().Set("WWW-Authenticate", `Bearer error="insufficient_scope"`)+ response.WriteHeader(http.StatusForbidden)+ err := (&storedOAuthHandler{}).Authorize(t.Context(), nil, response.Result())+ var detail *Error+ if !errors.As(err, &detail) || detail.AuthorizationReason != "scope" {+ t.Fatalf("provider scope reason lost: %v", err)+ }+}++func TestAuthorizationAttemptIdentityAndSelectedCancellation(t *testing.T) {+ f := oauthServiceFixture(t)+ manager := NewManager(t.Context(), ManagerOptions{OAuthCredentialsPath: filepath.Join(t.TempDir(), "credentials.json")})+ defer manager.Close()+ if _, err := manager.Apply(t.Context(), f.settings("test-client")); err != nil {+ t.Fatal(err)+ }+ redirect := "http://127.0.0.1:9090" + mcpconfig.OAuthCallbackPath + "alice"+ first, err := manager.Authorize(t.Context(), "oauth", redirect)+ if err != nil {+ t.Fatal(err)+ }+ if first.ID == "" || first.Phase != "waiting-browser" {+ t.Fatalf("attempt identity missing: %+v", first)+ }+ if err := manager.CancelAuthorizationAttempt(t.Context(), "oauth", "stale-id"); err != nil {+ t.Fatal(err)+ }+ if current := manager.ListViews()[0].Authorization; current == nil || current.ID != first.ID || current.Phase != "waiting-browser" || current.AuthorizationURL == "" {+ t.Fatalf("stale cancellation touched live attempt: %+v", current)+ }+ if err := manager.CancelAuthorizationAttempt(t.Context(), "oauth", first.ID); err != nil {+ t.Fatal(err)+ }+ if current := manager.ListViews()[0].Authorization; current == nil || current.ID != first.ID || current.Phase != "cancelled" || current.AuthorizationURL != "" {+ t.Fatalf("selected cancellation was not retained: %+v", current)+ }+ second, err := manager.Authorize(t.Context(), "oauth", redirect)+ if err != nil {+ t.Fatal(err)+ }+ if first.ID == second.ID {+ t.Fatal("replacement reused the attempt identity")+ }+ if err := manager.CancelAuthorizationAttempt(t.Context(), "oauth", first.ID); err != nil {+ t.Fatal(err)+ }+ if _, err := manager.CompleteAuthorization(t.Context(), visitOAuthAuthorization(t, second)); err != nil {+ t.Fatal(err)+ }+ if current := manager.ListViews()[0].Authorization; current == nil || current.ID != second.ID || current.Phase != "authorized" || current.AuthorizationURL != "" {+ t.Fatalf("completion lost attempt identity: %+v", current)+ }+}diff --git a/internal/mcpclient/scope.go b/internal/mcpclient/scope.gonew file mode 100644index 0000000..cceb34d--- /dev/null+++ b/internal/mcpclient/scope.go@@ -0,0 +1,249 @@+package mcpclient++import (+ "context"+ "encoding/json"+ "fmt"+ "sort"+ "strings"+ "sync"+ "unicode/utf16"++ "go-bot/harness/agent"+ "go-bot/harness/skills"+)++type serverView struct {+ name, loading, state string+ connection *Connection+ generation context.Context+ discovery Discovery+ tools []*Tool+}++func (m *Manager) views() []serverView {+ m.mu.RLock()+ defer m.mu.RUnlock()+ var result []serverView+ for _, entry := range m.entries {+ if !entry.config.IsEnabled() {+ continue+ }+ result = append(result, serverView{name: entry.name, loading: entry.config.Loading(), state: entry.status.State, connection: entry.connection, generation: entry.generation, discovery: entry.discovery, tools: append([]*Tool(nil), entry.tools...)})+ }+ sort.Slice(result, func(i, j int) bool { return result[i].name < result[j].name })+ return result+}++// Scope belongs to one live Agent instance. A fork or cold recovery creates a+// new Scope, not a journal-restored set of registrations. Loaded names survive+// connection generations only within this Scope while they remain offered.+type Scope struct {+ manager *Manager+ mu sync.Mutex+ loaded map[string]map[string]bool+ closed bool+}++func (m *Manager) NewScope() *Scope { return &Scope{manager: m, loaded: map[string]map[string]bool{}} }+func (s *Scope) Close() { s.mu.Lock(); s.closed = true; s.loaded = nil; s.mu.Unlock() }++func (s *Scope) Tools(_ context.Context, _ string) ([]agent.Tool, error) {+ views := s.manager.views()+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.closed {+ return nil, fail("MCP_SCOPE_CLOSED", "MCP Agent scope is closed")+ }+ var result []agent.Tool+ for _, view := range views {+ if view.loading == "eager" {+ for _, tool := range view.tools {+ result = append(result, tool)+ }+ continue+ }+ if view.generation == nil {+ continue+ }+ result = append(result, &loaderTool{scope: s, view: view})+ offered := map[string]bool{}+ for _, tool := range view.tools {+ raw := tool.definition.RawName+ if raw == "load_tools" {+ continue+ }+ offered[raw] = true+ if s.loaded[view.name][raw] {+ result = append(result, tool)+ }+ }+ for raw := range s.loaded[view.name] {+ if !offered[raw] {+ delete(s.loaded[view.name], raw)+ }+ }+ }+ if len(views) > 0 {+ for _, name := range []string{"list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"} {+ result = append(result, &resourceTool{manager: s.manager, name: name})+ }+ }+ return result, nil+}++func (s *Scope) Context(_ context.Context, _ string) ([]agent.RuntimeContextSection, error) {+ s.mu.Lock()+ closed := s.closed+ s.mu.Unlock()+ if closed {+ return nil, fail("MCP_SCOPE_CLOSED", "MCP Agent scope is closed")+ }+ views := s.manager.views()+ if len(views) == 0 {+ return nil, nil+ }+ var sections []agent.RuntimeContextSection+ names := make([]string, 0, len(views))+ for _, view := range views {+ names = append(names, view.name)+ }+ sections = append(sections, agent.RuntimeContextSection{Name: "mcp:servers", Text: "Configured MCP servers: " + strings.Join(names, ", ") + ". MCP resource tools require an explicit server name."})+ for _, view := range views {+ if view.discovery.Instructions != "" {+ sections = append(sections, agent.RuntimeContextSection{Name: "mcp:" + view.name + ":instructions", Text: "MCP server " + view.name + " instructions (literal text):\n" + view.discovery.Instructions})+ }+ if view.loading != "on-demand" || len(view.tools) == 0 {+ continue+ }+ var definitions []ToolDefinition+ for _, tool := range view.tools {+ if tool.definition.RawName != "load_tools" {+ definitions = append(definitions, tool.definition)+ }+ }+ sort.Slice(definitions, func(i, j int) bool { return jsLess(definitions[i].RawName, definitions[j].RawName) })+ if len(definitions) == 0 {+ continue+ }+ lines := []string{"### On-demand tools from MCP server " + view.name, "These tools are not in your tool list. Before calling one, load it with " + PublicToolName(view.name, "load_tools") + "."}+ var catalog []string+ for _, definition := range definitions {+ summary := descriptionSummary(definition.Description)+ line := "- " + definition.RawName+ if summary != "" {+ line += ": " + summary+ }+ catalog = append(catalog, line)+ }+ lines = append(lines, strings.Join(catalog, "\n"))+ sections = append(sections, agent.RuntimeContextSection{Name: "mcp:" + view.name + ":catalog", Text: strings.Join(lines, "\n\n")})+ }+ return sections, nil+}++func jsLess(a, b string) bool {+ x, y := utf16.Encode([]rune(a)), utf16.Encode([]rune(b))+ for i := 0; i < len(x) && i < len(y); i++ {+ if x[i] != y[i] {+ return x[i] < y[i]+ }+ }+ return len(x) < len(y)+}+func descriptionSummary(text string) string {+ text = strings.TrimFunc(text, skills.IsSpace)+ text = strings.SplitN(text, "\n", 2)[0]+ text = strings.Join(strings.FieldsFunc(text, skills.IsSpace), " ")+ if len(utf16.Encode([]rune(text))) <= 160 {+ return text+ }+ var runes []rune+ units := 0+ for _, r := range text {+ width := 1+ if r > 0xffff {+ width = 2+ }+ if units+width > 157 {+ break+ }+ units += width+ runes = append(runes, r)+ }+ return string(runes) + "..."+}++type loaderTool struct {+ scope *Scope+ view serverView+}++func (t *loaderTool) Spec() agent.ToolSpec {+ return agent.ToolSpec{Name: PublicToolName(t.view.name, "load_tools"), Description: fmt.Sprintf("Add tools from MCP server %s to your tool list. The system prompt lists them under \"On-demand tools from MCP server %s\".", t.view.name, t.view.name), Parameters: json.RawMessage(`{"type":"object","properties":{"tools":{"type":"array","items":{"type":"string"},"minItems":1}},"required":["tools"],"additionalProperties":false}`)}+}+func (t *loaderTool) Validate(raw json.RawMessage) error {+ var input struct {+ Tools []string `json:"tools"`+ }+ if json.Unmarshal(raw, &input) != nil || len(input.Tools) == 0 {+ return fail("MCP_INVALID_ARGUMENTS", "MCP loader requires at least one tool name")+ }+ return nil+}+func (t *loaderTool) Execute(ctx context.Context, raw json.RawMessage) (string, error) {+ if err := ctx.Err(); err != nil {+ return "", err+ }+ if err := t.Validate(raw); err != nil {+ return "", err+ }+ if t.view.generation == nil || t.view.generation.Err() != nil {+ return "", fail("MCP_SERVER_UNAVAILABLE", "MCP tool catalog is unavailable")+ }+ var input struct {+ Tools []string `json:"tools"`+ }+ _ = json.Unmarshal(raw, &input)+ offered := map[string]string{}+ for _, tool := range t.view.tools {+ if tool.definition.RawName != "load_tools" {+ offered[tool.definition.RawName] = tool.definition.PublicName+ }+ }+ for _, name := range input.Tools {+ if offered[name] == "" {+ return "", fail("MCP_UNKNOWN_TOOL", fmt.Sprintf("MCP server %s does not offer %q; use names from its on-demand tool list", t.view.name, name))+ }+ }+ t.scope.mu.Lock()+ defer t.scope.mu.Unlock()+ if t.scope.closed {+ return "", fail("MCP_SCOPE_CLOSED", "MCP Agent scope is closed")+ }+ if t.scope.loaded[t.view.name] == nil {+ t.scope.loaded[t.view.name] = map[string]bool{}+ }+ var loaded, present []string+ seen := map[string]bool{}+ for _, name := range input.Tools {+ if seen[name] {+ continue+ }+ seen[name] = true+ if t.scope.loaded[t.view.name][name] {+ present = append(present, offered[name])+ } else {+ loaded = append(loaded, offered[name])+ t.scope.loaded[t.view.name][name] = true+ }+ }+ var message []string+ if len(loaded) > 0 {+ message = append(message, "Loaded: "+strings.Join(loaded, ", ")+".")+ }+ if len(present) > 0 {+ message = append(message, "Already loaded: "+strings.Join(present, ", ")+".")+ }+ return strings.Join(message, "\n"), nil+}diff --git a/internal/mcpclient/tool.go b/internal/mcpclient/tool.gonew file mode 100644index 0000000..cc82d2b--- /dev/null+++ b/internal/mcpclient/tool.go@@ -0,0 +1,235 @@+package mcpclient++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/santhosh-tekuri/jsonschema/v6"+ "go-bot/harness/agent"+ "go-bot/harness/content"+ "go-bot/internal/modeldata"+)++type ImageWriter interface {+ SaveImage(context.Context, []byte, string, string, string) (content.ImageAttachment, error)+}++type ToolOptions struct {+ Images ImageWriter+ Lifetime context.Context+}++type Tool struct {+ connection *Connection+ definition ToolDefinition+ options ToolOptions+}++func NewTool(connection *Connection, definition ToolDefinition, options ToolOptions) *Tool {+ definition.InputSchema = append(json.RawMessage(nil), definition.InputSchema...)+ definition.OutputSchema = append(json.RawMessage(nil), definition.OutputSchema...)+ if options.Lifetime == nil {+ options.Lifetime = connection.ctx+ }+ return &Tool{connection: connection, definition: definition, options: options}+}++func (t *Tool) Spec() agent.ToolSpec {+ return agent.ToolSpec{Name: t.definition.PublicName, Description: t.definition.Description, Parameters: append(json.RawMessage(nil), t.definition.InputSchema...), Timeout: RequestTimeout}+}+func (t *Tool) Validate(raw json.RawMessage) error {+ if t.definition.input == nil {+ return fail("MCP_INVALID_SCHEMA", "MCP tool has no validated input schema")+ }+ value, err := jsonschema.UnmarshalJSON(strings.NewReader(string(raw)))+ if err != nil {+ return err+ }+ return t.definition.input.Validate(value)+}++func (t *Tool) Execute(ctx context.Context, args json.RawMessage) (string, error) {+ result, err := t.ExecuteResult(ctx, args)+ if err != nil {+ return "", err+ }+ var text []string+ for _, block := range result.ContentBlocks {+ if block.Type == "text" {+ text = append(text, block.Text)+ }+ }+ message := strings.Join(text, "\n")+ if result.IsError {+ return message, fail(result.Code, message)+ }+ return message, nil+}+func (t *Tool) ExecutePresented(ctx context.Context, args json.RawMessage) (string, json.RawMessage, error) {+ result, err := t.ExecuteResult(ctx, args)+ if err != nil {+ return "", nil, err+ }+ var text []string+ for _, block := range result.ContentBlocks {+ if block.Type == "text" {+ text = append(text, block.Text)+ }+ }+ if result.IsError {+ err = fail(result.Code, strings.Join(text, "\n"))+ }+ return strings.Join(text, "\n"), result.Meta, err+}+func (t *Tool) ExecuteRich(ctx context.Context, args json.RawMessage) (string, []content.ContentBlock, json.RawMessage, error) {+ result, err := t.ExecuteResult(ctx, args)+ if err != nil {+ return "", nil, nil, err+ }+ if result.IsError {+ err = fail(result.Code, "MCP server reported a tool error")+ }+ return "", result.ContentBlocks, result.Meta, err+}++// ExecuteResult retains MCP's isError outcome and the order of its text/image+// blocks. Images enter the existing content-addressed attachment store once;+// canonical metadata contains references, never a second copy of pixels.+func (t *Tool) ExecuteResult(ctx context.Context, args json.RawMessage) (modeldata.ToolResult, error) {+ var output modeldata.ToolResult+ if err := t.Validate(args); err != nil {+ return output, err+ }+ if t.options.Lifetime.Err() != nil {+ return output, fail("MCP_TOOL_UNAVAILABLE", "This MCP tool generation is no longer available")+ }+ ctx, cancel := context.WithCancel(ctx)+ stop := context.AfterFunc(t.options.Lifetime, cancel)+ defer stop()+ defer cancel()+ result, err := t.connection.Call(ctx, t.definition.RawName, args)+ if err != nil {+ return output, err+ }+ if result == nil {+ return output, fail("MCP_INVALID_RESULT", "MCP tool returned no result")+ }+ if !result.IsError && t.definition.output != nil {+ if result.StructuredContent == nil {+ return output, fail("MCP_INVALID_RESULT", "MCP tool declared output schema but returned no structured content")+ }+ data, err := json.Marshal(result.StructuredContent)+ if err != nil {+ return output, fail("MCP_INVALID_RESULT", "MCP structured content is not JSON")+ }+ value, err := jsonschema.UnmarshalJSON(strings.NewReader(string(data)))+ if err != nil || t.definition.output.Validate(value) != nil {+ return output, fail("MCP_INVALID_RESULT", "MCP structured content does not match its output schema")+ }+ }+ return t.materialize(ctx, result)+}++func (t *Tool) materialize(ctx context.Context, result *sdk.CallToolResult) (modeldata.ToolResult, error) {+ var output modeldata.ToolResult+ var err error+ canonical := map[string]any{"content": []any{}}+ protocol := []any{}+ totalText, totalImages := 0, 0+ addText := func(text string) error {+ if result.IsError {+ text = t.connection.redact(text)+ }+ totalText += len(text)+ if totalText > 256<<10 {+ return fail("MCP_RESULT_LIMIT", "MCP tool text exceeds 256 KiB")+ }+ if text != "" {+ output.ContentBlocks = append(output.ContentBlocks, content.ContentBlock{Type: "text", Text: text})+ protocol = append(protocol, map[string]any{"type": "text", "text": text})+ }+ return nil+ }+ for _, block := range result.Content {+ switch value := block.(type) {+ case *sdk.TextContent:+ if err = addText(value.Text); err != nil {+ return modeldata.ToolResult{}, err+ }+ case *sdk.ImageContent:+ if t.options.Images == nil {+ return output, fail("MCP_IMAGE_UNAVAILABLE", "MCP image attachment storage is unavailable")+ }+ totalImages += len(value.Data)+ if totalImages > 8<<20 {+ return output, fail("MCP_RESULT_LIMIT", "MCP tool images exceed 8 MiB")+ }+ switch value.MIMEType {+ case "image/png", "image/jpeg", "image/webp", "image/gif":+ default:+ return output, fail("MCP_INVALID_RESULT", "Unsupported MCP image media type")+ }+ ref, err := t.options.Images.SaveImage(ctx, value.Data, value.MIMEType, "", "")+ if err != nil {+ return output, fail("MCP_INVALID_RESULT", t.connection.redact(err.Error()))+ }+ output.ContentBlocks = append(output.ContentBlocks, content.ImageBlock(ref))+ protocol = append(protocol, map[string]any{"type": "image", "attachment": map[string]any{"attachmentId": ref.ID, "mediaType": ref.MIMEType, "bytes": ref.Bytes, "width": ref.Width, "height": ref.Height, "name": ref.Name}})+ case *sdk.ResourceLink:+ if err = addText(fmt.Sprintf("MCP resource %q: %s\n%s", value.Name, value.URI, value.Description)); err != nil {+ return output, err+ }+ case *sdk.EmbeddedResource:+ if value.Resource == nil {+ return output, fail("MCP_INVALID_RESULT", "MCP embedded resource is missing")+ }+ text := value.Resource.Text+ if len(value.Resource.Blob) > 0 {+ text = fmt.Sprintf("MCP resource %q contains %d bytes of %s; binary preview is not supported.", value.Resource.URI, len(value.Resource.Blob), value.Resource.MIMEType)+ }+ if err = addText(text); err != nil {+ return output, err+ }+ case *sdk.AudioContent:+ if err = addText(fmt.Sprintf("MCP audio result: %s, %d bytes; audio preview is not supported.", value.MIMEType, len(value.Data))); err != nil {+ return output, err+ }+ default:+ if err = addText("MCP returned a content type that this Host does not render."); err != nil {+ return output, err+ }+ }+ }+ if result.StructuredContent != nil && !result.IsError {+ canonical["structuredContent"] = result.StructuredContent+ if len(output.ContentBlocks) == 0 {+ data, err := json.Marshal(result.StructuredContent)+ if err != nil {+ return output, err+ }+ if err = addText(string(data)); err != nil {+ return output, err+ }+ }+ }+ canonical["content"] = protocol+ output.IsError = result.IsError+ if result.IsError {+ output.Code, output.ErrorName = "MCP_TOOL_ERROR", "McpToolError"+ }+ value, err := json.Marshal(canonical)+ if err != nil {+ return output, err+ }+ if len(value) > 512<<10 {+ return output, fail("MCP_RESULT_LIMIT", "MCP canonical result exceeds 512 KiB")+ }+ output.Meta, err = json.Marshal(map[string]any{"mcp": map[string]any{"server": t.connection.Name, "tool": t.definition.RawName}, "canonicalValue": json.RawMessage(value)})+ return output, err+}++var _ agent.ResultTool = (*Tool)(nil)+var _ agent.RichTool = (*Tool)(nil)diff --git a/internal/mcpclient/tool_test.go b/internal/mcpclient/tool_test.gonew file mode 100644index 0000000..bec34f5--- /dev/null+++ b/internal/mcpclient/tool_test.go@@ -0,0 +1,107 @@+package mcpclient++import (+ "bytes"+ "context"+ "encoding/base64"+ "encoding/json"+ "image"+ "image/color"+ "image/png"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ "go-bot/harness/attachments"+ mcpconfig "go-bot/mcp"+)++func TestMCPToolKeepsOrderedImageAttachmentsStructuredValuesAndServerFailures(t *testing.T) {+ var pixels bytes.Buffer+ canvas := image.NewRGBA(image.Rect(0, 0, 3, 3))+ canvas.Set(1, 1, color.RGBA{R: 255, A: 255})+ if err := png.Encode(&pixels, canvas); err != nil {+ t.Fatal(err)+ }+ server := sdk.NewServer(&sdk.Implementation{Name: "fixture", Version: "1"}, nil)+ var calls atomic.Int32+ server.AddTool(&sdk.Tool{Name: "render.report", InputSchema: map[string]any{"type": "object", "properties": map[string]any{"fail": map[string]any{"type": "boolean"}}, "additionalProperties": false}, OutputSchema: map[string]any{"type": "object", "properties": map[string]any{"ok": map[string]any{"type": "boolean"}}, "required": []string{"ok"}}}, func(_ context.Context, request *sdk.CallToolRequest) (*sdk.CallToolResult, error) {+ calls.Add(1)+ if request.Params.Name != "render.report" {+ t.Error("public name was sent on the wire")+ }+ var input struct {+ Fail bool `json:"fail"`+ }+ _ = json.Unmarshal(request.Params.Arguments, &input)+ text := "before"+ if input.Fail {+ text = "rejected fixture-secret"+ }+ return &sdk.CallToolResult{IsError: input.Fail, StructuredContent: map[string]any{"ok": true}, Content: []sdk.Content{&sdk.TextContent{Text: text}, &sdk.ImageContent{MIMEType: "image/png", Data: pixels.Bytes()}, &sdk.TextContent{Text: "after"}}}, nil+ })+ httpServer := httptest.NewServer(sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil))+ t.Cleanup(httpServer.Close)+ connection, err := Connect(t.Context(), "reports", mcpconfig.Server{Transport: "streamable-http", URL: httpServer.URL}, ConnectionOptions{Secrets: []string{"fixture-secret"}})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = connection.Close() })+ discovery, err := connection.Discover(t.Context())+ if err != nil || len(discovery.Tools) != 1 {+ t.Fatalf("discovery=%+v err=%v", discovery, err)+ }+ store := attachments.Store{API: attachments.LocalObjectAPI{Root: t.TempDir()}}+ lifetime, cancel := context.WithCancel(t.Context())+ defer cancel()+ tool := NewTool(connection, discovery.Tools[0], ToolOptions{Images: store, Lifetime: lifetime})+ result, err := tool.ExecuteResult(t.Context(), json.RawMessage(`{}`))+ if err != nil || result.IsError || len(result.ContentBlocks) != 3 || result.ContentBlocks[0].Text != "before" || result.ContentBlocks[1].Type != "image" || result.ContentBlocks[2].Text != "after" {+ t.Fatalf("result=%+v err=%v", result, err)+ }+ if !strings.Contains(string(result.Meta), `"structuredContent":{"ok":true}`) || strings.Contains(string(result.Meta), base64.StdEncoding.EncodeToString(pixels.Bytes())) {+ t.Fatal("canonical metadata lost structured output or duplicated image bytes")+ }+ ref := result.ContentBlocks[1]+ if ref.ImageRefID == "" || ref.Width != 3 || ref.Height != 3 {+ t.Fatalf("image attachment=%+v", ref)+ }+ failed, err := tool.ExecuteResult(t.Context(), json.RawMessage(`{"fail":true}`))+ if err != nil || !failed.IsError || failed.Code != "MCP_TOOL_ERROR" || len(failed.ContentBlocks) != 3 || strings.Contains(failed.ContentBlocks[0].Text, "fixture-secret") {+ t.Fatalf("failure=%+v err=%v", failed, err)+ }+ if _, err = tool.ExecuteResult(t.Context(), json.RawMessage(`{"fail":"not-a-boolean"}`)); err == nil {+ t.Fatal("invalid tool arguments were sent")+ }+ if calls.Load() != 2 {+ t.Fatalf("remote calls=%d", calls.Load())+ }+ cancel()+ if _, err = tool.ExecuteResult(t.Context(), json.RawMessage(`{}`)); err == nil {+ t.Fatal("withdrawn generation was still callable")+ }+}++func TestMCPToolValidatesDeclaredStructuredOutput(t *testing.T) {+ server := sdk.NewServer(&sdk.Implementation{Name: "fixture", Version: "1"}, nil)+ server.AddTool(&sdk.Tool{Name: "bad", InputSchema: map[string]any{"type": "object"}, OutputSchema: map[string]any{"type": "object", "required": []string{"required"}}}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {+ return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "looks fine"}}, StructuredContent: map[string]any{}}, nil+ })+ httpServer := httptest.NewServer(sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil))+ t.Cleanup(httpServer.Close)+ connection, err := Connect(t.Context(), "schemas", mcpconfig.Server{Transport: "streamable-http", URL: httpServer.URL}, ConnectionOptions{})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = connection.Close() })+ discovery, err := connection.Discover(t.Context())+ if err != nil {+ t.Fatal(err)+ }+ if _, err = NewTool(connection, discovery.Tools[0], ToolOptions{}).ExecuteResult(t.Context(), json.RawMessage(`{}`)); err == nil {+ t.Fatal("rendered text hid invalid structured output")+ }+}diff --git a/internal/modeldata/types.go b/internal/modeldata/types.goindex 05d981b..83e4d40 100644--- a/internal/modeldata/types.go+++ b/internal/modeldata/types.go@@ -27,7 +27,18 @@ type AssistantOutputBlock struct {Arguments string `json:"arguments,omitempty"`}+// ProviderReplay contains signed native blocks, separate from visible content.+// It is reusable only with the endpoint and model that produced it.+type ProviderReplay struct {+ EndpointURL string `json:"endpointUrl,omitempty"`+ Protocol string `json:"protocol"`+ EndpointID string `json:"endpointId"`+ ModelID string `json:"modelId"`+ Content []json.RawMessage `json:"content"`+}+type AssistantMessage struct {+ ProviderReplay *ProviderReplay `json:"providerReplay,omitempty"`Content string `json:"content"`MaxTokens bool `json:"maxTokens,omitempty"`RawOutput []content.ContentBlock `json:"rawOutput,omitempty"`@@ -54,13 +65,15 @@ type ModelUsage struct {}type ToolResult struct {- ID string `json:"id"`- Name string `json:"name"`- Content string `json:"content"`- ContentBlocks []content.ContentBlock `json:"contentBlocks,omitempty"`- IsError bool `json:"isError,omitempty"`- Code string `json:"code,omitempty"`- ErrorName string `json:"errorName,omitempty"`- Meta json.RawMessage `json:"meta,omitempty"`- ConcludeTurn bool `json:"concludeTurn,omitempty"`+ ID string `json:"id"`+ Name string `json:"name"`+ Content string `json:"content"`+ ContentBlocks []content.ContentBlock `json:"contentBlocks,omitempty"`+ IsError bool `json:"isError,omitempty"`+ Code string `json:"code,omitempty"`+ ErrorName string `json:"errorName,omitempty"`+ ErrorReason *string `json:"errorReason,omitempty"`+ Meta json.RawMessage `json:"meta,omitempty"`+ ConcludeTurn bool `json:"concludeTurn,omitempty"`+ AdditionalContexts []json.RawMessage `json:"-"`}diff --git a/internal/modelsettings/settings.go b/internal/modelsettings/settings.goindex b675ee6..5c95840 100644--- a/internal/modelsettings/settings.go+++ b/internal/modelsettings/settings.go@@ -17,11 +17,30 @@ type Selection struct {ModelID string `json:"modelId"`}+// Protocol belongs to an endpoint, independently of its model IDs.+const (+ Responses = "responses"+ AnthropicMessages = "anthropic_messages"+)++func NormalizeProtocol(value string) string {+ if value == "" {+ return Responses+ }+ return value+}++func ValidProtocol(value string) bool {+ value = NormalizeProtocol(value)+ return value == Responses || value == AnthropicMessages+}+type Endpoint struct {- Name string `json:"name"`- BaseURL string `json:"baseUrl"`- APIKey string `json:"apiKey"`- Models []string `json:"models"`+ Protocol string `json:"protocol"`+ Name string `json:"name"`+ BaseURL string `json:"baseUrl"`+ APIKey string `json:"apiKey"`+ Models []string `json:"models"`}type Catalog struct {@@ -42,7 +61,7 @@ func (c Catalog) Resolve(selection Selection) (Endpoint, error) {return Endpoint{}, ErrUnconfigured}endpoint, ok := c.Endpoints[selection.EndpointID]- if !ok || endpoint.BaseURL == "" || endpoint.APIKey == "" || !slices.Contains(endpoint.Models, selection.ModelID) {+ if !ok || !ValidProtocol(endpoint.Protocol) || endpoint.BaseURL == "" || endpoint.APIKey == "" || !slices.Contains(endpoint.Models, selection.ModelID) {return Endpoint{}, ErrUnavailable}return endpoint, nildiff --git a/internal/plugins/authorization_http.go b/internal/plugins/authorization_http.gonew file mode 100644index 0000000..79dab2f--- /dev/null+++ b/internal/plugins/authorization_http.go@@ -0,0 +1,168 @@+package plugins++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/url"+ "strings"++ "github.com/google/uuid"+ "go-bot/internal/authorization"+ "go-bot/plugin"+)++func (m *Manager) Authorization(ctx context.Context, method string, input any) (json.RawMessage, error) {+ switch method {+ case "list", "start", "get", "answer", "cancel", "cancelKey", "callback", "disconnect":+ default:+ return nil, failure("METHOD_NOT_FOUND", "Unknown authorization operation")+ }+ m.mu.RLock()+ runtime := m.runtime+ m.mu.RUnlock()+ if runtime == nil || !runtime.Alive() {+ return nil, failure("RUNTIME_UNAVAILABLE", "Plugin runtime is not running")+ }+ raw, err := json.Marshal(input)+ if err != nil {+ return nil, err+ }+ value, err := m.surface.Handle(ctx, method, raw)+ if err != nil {+ return nil, authorizationError(err)+ }+ result, err := json.Marshal(value)+ if err != nil {+ return nil, err+ }+ if method == "list" {+ return result, nil+ }+ // IDs, offered options and intentional browser URLs are protocol data,+ // not diagnostics. Opaque records can contain ordinary account names and+ // scope strings; replacing those across this response breaks the next+ // request. The Go surface never returns answers or credential records.+ var view map[string]json.RawMessage+ if err := json.Unmarshal(result, &view); err != nil {+ return nil, err+ }+ if raw, ok := view["error"]; ok {+ var message string+ if err := json.Unmarshal(raw, &message); err != nil {+ return nil, err+ }+ view["error"], _ = json.Marshal(m.redact(message))+ }+ return json.Marshal(view)+}++func (m *Manager) authorizationHTTP(w http.ResponseWriter, r *http.Request, respond func(int, any), decode func(any) error) {+ suffix := strings.TrimPrefix(r.URL.Path, plugin.InternalPath+"/authorization")+ method := ""+ var input any = struct{}{}+ status := http.StatusOK+ switch {+ case suffix == "" && r.Method == http.MethodGet:+ method = "list"+ case suffix == "" && r.Method == http.MethodPost:+ var start plugin.AuthorizationStart+ if err := decode(&start); err != nil {+ respond(400, map[string]string{"error": "invalid_authorization_request"})+ return+ }+ method, input, status = "start", start, http.StatusAccepted+ case suffix == "/disconnect" && r.Method == http.MethodPost:+ var key struct {+ Key string `json:"key"`+ }+ if err := decode(&key); err != nil {+ respond(400, map[string]string{"error": "invalid_authorization_request"})+ return+ }+ method, input = "disconnect", key+ case suffix == "/callback" && r.Method == http.MethodPost:+ var callback struct {+ Token string `json:"token"`+ Query map[string][]string `json:"query"`+ }+ if err := decode(&callback); err != nil {+ respond(400, map[string]string{"error": "invalid_authorization_callback"})+ return+ }+ method, input = "callback", callback+ case suffix == "" && r.Method == http.MethodDelete:+ var inputKey struct {+ Key string `json:"key"`+ }+ if err := decode(&inputKey); err != nil {+ respond(400, map[string]string{"error": "invalid_authorization_request"})+ return+ }+ method, input = "cancelKey", inputKey+ default:+ id, action, _ := strings.Cut(strings.TrimPrefix(suffix, "/"), "/")+ if _, err := uuid.Parse(id); err != nil {+ http.NotFound(w, r)+ return+ }+ switch {+ case action == "" && r.Method == http.MethodGet:+ method, input = "get", map[string]string{"id": id}+ case action == "" && r.Method == http.MethodDelete:+ method, input = "cancel", map[string]string{"id": id}+ case action == "answer" && r.Method == http.MethodPost:+ var answer plugin.AuthorizationAnswer+ if err := decode(&answer); err != nil {+ respond(400, map[string]string{"error": "invalid_authorization_answer"})+ return+ }+ method = "answer"+ input = struct {+ ID string `json:"id"`+ plugin.AuthorizationAnswer+ }{id, answer}+ default:+ http.NotFound(w, r)+ return+ }+ }+ ctx := r.Context()+ if base := r.Header.Get(plugin.AuthorizationCallbackHeader); base != "" {+ u, err := url.Parse(base)+ if err != nil || u.Path != plugin.AuthorizationCallbackPath+url.PathEscape(m.config.Runtime.UserID)+"/" {+ respond(400, map[string]string{"error": "invalid_authorization_callback"})+ return+ }+ ctx = authorization.WithCallbackBase(ctx, base)+ }+ result, err := m.Authorization(ctx, method, input)+ if err != nil {+ code := "authorization_failed"+ status = http.StatusUnprocessableEntity+ var detail *plugin.Error+ if errors.As(err, &detail) {+ code = detail.Code+ switch code {+ case "RUNTIME_UNAVAILABLE":+ status = http.StatusServiceUnavailable+ case "ALREADY_IN_FLIGHT", "AUTHORIZATION_BUSY":+ status = http.StatusConflict+ case "NO_FLOW", "AUTHORIZATION_NOT_FOUND", "PROMPT_NOT_FOUND":+ status = http.StatusNotFound+ }+ }+ respond(status, map[string]string{"error": code, "message": m.redact(err.Error())})+ return+ }+ respond(status, result)+}++func authorizationError(err error) error {+ var detail *authorization.Error+ if errors.As(err, &detail) {+ return &plugin.Error{Code: detail.Code, Message: detail.Message, Name: "AuthorizationError"}+ }+ return err+}diff --git a/internal/plugins/host_authorization.go b/internal/plugins/host_authorization.gonew file mode 100644index 0000000..ac6e7b8--- /dev/null+++ b/internal/plugins/host_authorization.go@@ -0,0 +1,129 @@+package plugins++import (+ "context"+ "encoding/json"+ "strings"++ "go-bot/internal/authorization"+ "go-bot/internal/credentials"+)++type hostAuthorizationDefinition struct {+ Key string `json:"key"`+ Title string `json:"title"`+ Methods []authorization.Method `json:"methods"`+}++func validateHostAuthorization(row *hostContribution) error {+ var definition hostAuthorizationDefinition+ if err := decodeHostJSON(row.Descriptor, &definition); err != nil {+ return err+ }+ if _, err := credentialAddress(row.Owner, definition.Key); err != nil {+ return err+ }+ if strings.TrimSpace(definition.Title) == "" || len(definition.Methods) == 0 {+ return failure("INVALID_ARGUMENT", "Authorization needs a title and methods")+ }+ for _, method := range row.Callbacks {+ if method == "run" {+ return nil+ }+ }+ return failure("INVALID_ARGUMENT", "Authorization run callback is required")+}++func (r *hostBridge) registerAuthorizationResource(row *hostContribution) (func(context.Context) error, error) {+ if r.config.Authorization == nil {+ return nil, failure("UNAVAILABLE", "Go authorization service is not configured")+ }+ var definition hostAuthorizationDefinition+ _ = json.Unmarshal(row.Descriptor, &definition)+ key, _ := credentialAddress(row.Owner, definition.Key)+ flow := authorization.Flow{Key: key, Label: definition.Title, Methods: definition.Methods, Run: func(session *authorization.Session) error {+ return r.callback(session.Context, row, "run", map[string]string{"id": session.ID, "method": session.Method}, nil, nil)+ }}+ for _, method := range row.Callbacks {+ switch method {+ case "inspect":+ flow.Inspect = func(ctx context.Context) (authorization.AccountState, error) {+ var state authorization.AccountState+ err := r.callback(ctx, row, "inspect", struct{}{}, nil, &state)+ return state, err+ }+ case "disconnect":+ flow.Disconnect = func(ctx context.Context) error { return r.callback(ctx, row, "disconnect", struct{}{}, nil, nil) }+ }+ }+ dispose, err := r.config.Authorization.Register(flow)+ if err != nil {+ return nil, err+ }+ return func(ctx context.Context) error {+ dispose()+ _, err := r.config.Authorization.CancelAndWait(ctx, key)+ return err+ }, nil+}++func (r *hostBridge) authorizationRequest(ctx context.Context, owner, method string, raw json.RawMessage, mutation string) (any, error) {+ service := r.config.Authorization+ if service == nil {+ return nil, failure("UNAVAILABLE", "Go authorization service is not configured")+ }+ var input struct {+ Key string `json:"key"`+ ID string `json:"id"`+ State string `json:"state"`+ Notice authorization.Notice `json:"notice"`+ Prompt authorization.Prompt `json:"prompt"`+ Record *credentials.Record `json:"record"`+ }+ if err := decodeHostJSON(raw, &input); err != nil {+ return nil, err+ }+ if method == "list" {+ result := []map[string]any{}+ for _, entry := range service.List() {+ if key, ok := strings.CutPrefix(entry.Key, owner+"/"); ok {+ phase := "idle"+ if entry.InFlight {+ phase = "running"+ }+ result = append(result, map[string]any{"key": key, "title": entry.Label, "methods": entry.Methods, "phase": phase})+ }+ }+ return result, nil+ }+ if method == "cancel" {+ key, err := credentialAddress(owner, input.Key)+ if err != nil {+ return nil, err+ }+ service.Cancel(key)+ return nil, nil+ }+ session := service.Session(input.ID)+ if session == nil || !strings.HasPrefix(session.Key, owner+"/") {+ return nil, failure("UNAVAILABLE", "Authorization attempt is no longer active")+ }+ switch method {+ case "notify":+ session.Notify(ctx, input.Notice)+ return nil, nil+ case "prompt":+ return session.Prompt(ctx, input.Prompt)+ case "callback":+ return session.Callback(ctx, input.State)+ case "waitCallback":+ return session.WaitCallback(ctx)+ case "commit":+ if mutation != "" {+ return nil, failure("CONFLICT", "A credential mutation cannot recursively commit an authorization")+ }+ return nil, session.Commit(input.Record)+ default:+ return nil, failure("NOT_FOUND", "Unknown authorization method")+ }+}diff --git a/internal/plugins/host_bridge.go b/internal/plugins/host_bridge.gonew file mode 100644index 0000000..9ba16c0--- /dev/null+++ b/internal/plugins/host_bridge.go@@ -0,0 +1,526 @@+package plugins++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "sort"+ "strings"+ "sync"+ "syscall"+ "time"++ "github.com/google/uuid"+ "go-bot/internal/credentials"+ "go-bot/plugin"+)++// hostBridge is the Go endpoint of the new ctx.host contract. It owns no+// Agent or Session: those remain in the existing Harness runtime.+type hostBridge struct {+ config RuntimeConfig+ peer *peer+ command *exec.Cmd+ directory string+ done chan struct{}+ closed chan struct{}+ closeOnce sync.Once+ applyMu sync.Mutex+ mu sync.RWMutex+ registrations map[string]*hostContribution+ sequence uint64+ invocations sync.Map+ notifications hostNotifications+ unsubscribers []func()+}++type hostPluginInstance = plugin.InstanceConfig++type hostContribution struct {+ ID string `json:"id"`+ Owner string `json:"owner"`+ Kind string `json:"kind"`+ CallbackID string `json:"callbackId"`+ Descriptor json.RawMessage `json:"descriptor"`+ Callbacks []string `json:"callbacks"`+ order uint64+ ctx context.Context+ cancel context.CancelFunc+ tool *hostTool+ resourceMu sync.Mutex+ cleanup func(context.Context) error+}++var bridgeInstanceName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,23}$`)++func startHostBridge(ctx context.Context, c RuntimeConfig) (*hostBridge, error) {+ if !filepath.IsAbs(c.Main) || !filepath.IsAbs(c.ProfileDir) {+ return nil, errors.New("Host Bridge needs absolute entry and package paths")+ }+ if c.Node == "" {+ c.Node = "node"+ }+ if err := os.MkdirAll(c.ProfileDir, 0700); err != nil {+ return nil, err+ }+ directory, err := os.MkdirTemp(c.SocketParent, "go-bot-bridge-")+ if err != nil {+ return nil, err+ }+ listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: filepath.Join(directory, "rpc.sock"), Net: "unix"})+ if err != nil {+ os.RemoveAll(directory)+ return nil, err+ }+ defer listener.Close()+ if err = os.Chmod(filepath.Join(directory, "rpc.sock"), 0600); err != nil {+ os.RemoveAll(directory)+ return nil, err+ }+ r := &hostBridge{config: c, directory: directory, done: make(chan struct{}), closed: make(chan struct{}),+ registrations: map[string]*hostContribution{}}+ r.command = exec.Command(c.Node, c.Main, filepath.Join(directory, "rpc.sock"))+ r.command.Dir = c.ProfileDir+ r.command.Env = runtimeEnvironment()+ for name, value := range map[string]string{"HOME": c.Home, "DSH_HOME": c.DSHHome} {+ if value != "" {+ r.command.Env = append(r.command.Env, name+"="+value)+ }+ }+ r.command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}+ r.command.Stdout, r.command.Stderr = io.Discard, io.Discard+ if err = r.command.Start(); err != nil {+ os.RemoveAll(directory)+ return nil, err+ }+ go func() { _ = r.command.Wait(); close(r.done) }()+ accepted := make(chan net.Conn, 1)+ go func() { conn, _ := listener.Accept(); accepted <- conn }()+ startup, cancel := context.WithTimeout(ctx, 15*time.Second)+ defer cancel()+ var conn net.Conn+ select {+ case conn = <-accepted:+ case <-r.done:+ err = errors.New("Host Bridge exited before connecting")+ case <-startup.Done():+ err = startup.Err()+ }+ if conn == nil {+ listener.Close()+ _ = syscall.Kill(-r.command.Process.Pid, syscall.SIGKILL)+ <-r.done+ select {+ case pending := <-accepted:+ if pending != nil {+ pending.Close()+ }+ default:+ }+ os.RemoveAll(directory)+ return nil, fmt.Errorf("start Host Bridge: %w", err)+ }+ r.peer = newPeer(conn, r.handle)+ var status []any+ if err = r.peer.call(startup, "runtime.inspect", nil, &status); err != nil {+ r.Close()+ return nil, err+ }+ r.startNotifications()+ go func() {+ select {+ case <-ctx.Done():+ case <-r.peer.closed:+ case <-r.done:+ case <-r.closed:+ return+ }+ _ = r.Close()+ }()+ return r, nil+}++func (r *hostBridge) handle(ctx context.Context, method string, raw json.RawMessage) (any, error) {+ switch method {+ case "bridge.initialize":+ var input struct {+ Protocol int `json:"protocol"`+ API string `json:"api"`+ }+ if json.Unmarshal(raw, &input) != nil || input.Protocol != 1 || input.API != "1" {+ return nil, failure("INCOMPATIBLE_PLUGIN", "Unsupported Host Bridge protocol")+ }+ return map[string]any{"protocol": 1, "api": "1", "directory": r.config.ProfileDir,+ "maxFrameBytes": maxFrame,+ "capabilities": []string{"info", "tools", "skills", "prompts", "credentials", "authorization", "mcp", "approvals", "questions"}}, nil+ case "contribution.register":+ var row hostContribution+ if err := json.Unmarshal(raw, &row); err != nil {+ return nil, err+ }+ if err := r.register(ctx, &row); err != nil {+ return nil, err+ }+ return map[string]string{"id": row.ID}, nil+ case "contribution.remove":+ var input struct {+ Owner string `json:"owner"`+ ID string `json:"registrationId"`+ }+ if err := json.Unmarshal(raw, &input); err != nil {+ return nil, err+ }+ return nil, r.remove(input.ID, input.Owner)+ case "host.invoke":+ return r.invokeHost(ctx, raw)+ case "runtime.log":+ var input struct {+ Level string `json:"level"`+ Message string `json:"message"`+ }+ if err := json.Unmarshal(raw, &input); err != nil {+ return nil, err+ }+ if r.config.Log != nil {+ if r.config.Credentials != nil {+ input.Message = r.config.Credentials.Redact(input.Message)+ }+ r.config.Log(input.Level, input.Message)+ }+ return nil, nil+ default:+ return nil, failure("NOT_FOUND", "Unknown Host Bridge method")+ }+}++func (r *hostBridge) register(ctx context.Context, row *hostContribution) error {+ if err := ctx.Err(); err != nil {+ return err+ }+ if !bridgeInstanceName.MatchString(row.Owner) || !identifier.MatchString(row.CallbackID) || !json.Valid(row.Descriptor) {+ return failure("INVALID_ARGUMENT", "Invalid plugin contribution")+ }+ var err error+ switch row.Kind {+ case "tool":+ row.tool, err = r.newTool(row)+ case "prompt":+ err = validateHostPrompt(row)+ case "skill", "skill-directory", "skill-provider":+ err = validateHostSkill(row)+ case "authorization":+ err = validateHostAuthorization(row)+ case "mcp":+ err = validateHostMCP(row)+ default:+ return failure("UNAVAILABLE", "This contribution kind has not been connected to Host Bridge")+ }+ if err != nil {+ return err+ }+ r.mu.Lock()+ for _, current := range r.registrations {+ if row.tool != nil && current.tool != nil && row.tool.Spec().Name == current.tool.Spec().Name {+ r.mu.Unlock()+ return failure("CONFLICT", "Plugin tool name is already registered")+ }+ }+ row.ID = uuid.NewString()+ r.sequence+++ row.order = r.sequence+ row.ctx, row.cancel = context.WithCancel(context.Background())+ r.registrations[row.ID] = row+ r.mu.Unlock()+ if row.Kind == "authorization" || row.Kind == "mcp" {+ var cleanup func(context.Context) error+ var err error+ if row.Kind == "authorization" {+ cleanup, err = r.registerAuthorizationResource(row)+ } else {+ cleanup, err = r.registerMCPResource(ctx, row)+ }+ if err != nil {+ _ = r.remove(row.ID, row.Owner)+ return err+ }+ row.resourceMu.Lock()+ row.cleanup = cleanup+ closed := row.ctx.Err() != nil+ row.resourceMu.Unlock()+ if closed {+ _ = cleanup(context.WithoutCancel(ctx))+ return failure("CANCELLED", "The contribution was removed while registering")+ }+ }+ if err := ctx.Err(); err != nil {+ _ = r.remove(row.ID, row.Owner)+ return err+ }+ r.contributionChanged(row)+ return nil+}++func (r *hostBridge) remove(id, owner string) error {+ r.mu.Lock()+ row := r.registrations[id]+ if row == nil {+ r.mu.Unlock()+ return nil+ }+ if row.Owner != owner {+ r.mu.Unlock()+ return failure("INVALID_ARGUMENT", "The contribution belongs to another plugin instance")+ }+ row.cancel()+ delete(r.registrations, id)+ r.mu.Unlock()+ r.contributionChanged(row)+ row.resourceMu.Lock()+ cleanup := row.cleanup+ row.resourceMu.Unlock()+ if cleanup != nil {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ return cleanup(ctx)+ }+ return nil+}++func (r *hostBridge) rows(kind string) []*hostContribution {+ r.mu.RLock()+ defer r.mu.RUnlock()+ var rows []*hostContribution+ for _, row := range r.registrations {+ if row.Kind == kind {+ rows = append(rows, row)+ }+ }+ sort.Slice(rows, func(i, j int) bool { return rows[i].order < rows[j].order })+ return rows+}++func (r *hostBridge) callback(ctx context.Context, row *hostContribution, method string, args any, call any, out any) error {+ found := false+ for _, name := range row.Callbacks {+ if name == method {+ found = true+ break+ }+ }+ if !found {+ return failure("NOT_FOUND", "Plugin callback is unavailable")+ }+ callCtx, cancel := context.WithCancel(ctx)+ defer cancel()+ stop := context.AfterFunc(row.ctx, cancel)+ defer stop()+ if row.ctx.Err() != nil {+ return failure("UNAVAILABLE", "Plugin registration has been disposed")+ }+ err := r.peer.callDrained(callCtx, "callback.invoke", map[string]any{"owner": row.Owner, "callbackId": row.CallbackID, "method": method, "args": args, "context": call}, out)+ if fatalDrain(err) {+ r.peer.close()+ }+ return err+}++func (r *hostBridge) Apply(ctx context.Context, instances []hostPluginInstance) ([]map[string]any, error) {+ r.applyMu.Lock()+ defer r.applyMu.Unlock()+ ids := map[string]bool{}+ for _, instance := range instances {+ if !bridgeInstanceName.MatchString(instance.ID) {+ return nil, failure("INVALID_ARGUMENT", "Invalid plugin instance id")+ }+ if ids[instance.ID] {+ return nil, failure("CONFLICT", "Duplicate plugin instance id")+ }+ ids[instance.ID] = true+ }+ var response struct {+ Instances []map[string]any `json:"instances"`+ }+ err := r.peer.call(ctx, "runtime.apply", map[string]any{"instances": instances}, &response)+ return response.Instances, err+}++func (r *hostBridge) Close() error {+ r.closeOnce.Do(func() {+ close(r.closed)+ for _, unsubscribe := range r.unsubscribers {+ unsubscribe()+ }+ if r.peer != nil {+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ _ = r.peer.call(ctx, "runtime.shutdown", nil, nil)+ cancel()+ r.peer.close()+ }+ if r.command != nil {+ _ = syscall.Kill(-r.command.Process.Pid, syscall.SIGTERM)+ select {+ case <-r.done:+ case <-time.After(3 * time.Second):+ _ = syscall.Kill(-r.command.Process.Pid, syscall.SIGKILL)+ <-r.done+ }+ }+ r.mu.Lock()+ remaining := make([]*hostContribution, 0, len(r.registrations))+ for _, row := range r.registrations {+ row.cancel()+ remaining = append(remaining, row)+ }+ r.registrations = map[string]*hostContribution{}+ r.mu.Unlock()+ for _, row := range remaining {+ row.resourceMu.Lock()+ cleanup := row.cleanup+ row.resourceMu.Unlock()+ if cleanup != nil {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ _ = cleanup(ctx)+ cancel()+ }+ }+ _ = os.RemoveAll(r.directory)+ })+ return nil+}++func (r *hostBridge) invokeHost(ctx context.Context, raw json.RawMessage) (any, error) {+ var input struct {+ Owner string `json:"owner"`+ Service string `json:"service"`+ Method string `json:"method"`+ Input json.RawMessage `json:"input"`+ Mutation string `json:"mutation"`+ Discovery bool `json:"discovery"`+ Invocation string `json:"invocation"`+ }+ if err := json.Unmarshal(raw, &input); err != nil {+ return nil, err+ }+ if !bridgeInstanceName.MatchString(input.Owner) {+ return nil, failure("INVALID_ARGUMENT", "Invalid plugin source")+ }+ if input.Service == "credentials" {+ return r.credential(ctx, input.Owner, input.Method, input.Input, input.Mutation)+ }+ if input.Service == "approvals" && input.Method == "request" {+ return r.approvalCall(ctx, input.Owner, input.Invocation, input.Input)+ }+ if input.Service == "questions" && input.Method == "ask" {+ return r.questionCall(ctx, input.Owner, input.Invocation, input.Input)+ }+ if input.Service == "authorization" {+ return r.authorizationRequest(ctx, input.Owner, input.Method, input.Input, input.Mutation)+ }+ if input.Service == "mcp" {+ return r.mcpRequest(ctx, input.Owner, input.Method, input.Input)+ }+ if input.Service == "skills" {+ if input.Method == "invalidate" {+ r.notify("host/skills-changed", "skill:"+input.Owner, map[string]string{"instanceId": input.Owner, "source": "invalidate"})+ }+ return r.skillRequest(ctx, input.Method, input.Input, input.Discovery)+ }+ if input.Service == "info" && input.Method == "get" {+ return map[string]string{"userId": r.config.UserID, "hostId": r.config.HostID, "dataRoot": r.config.Workspace, "apiVersion": "1", "instanceId": input.Owner}, nil+ }+ return nil, failure("UNAVAILABLE", "The requested Host service has not been connected")+}++func credentialAddress(owner, key string) (string, error) {+ if !bridgeInstanceName.MatchString(owner) || !bridgeInstanceName.MatchString(key) {+ return "", failure("INVALID_ARGUMENT", "Invalid plugin credential key")+ }+ return owner + "/" + key, nil+}++func (r *hostBridge) credential(ctx context.Context, owner, method string, raw json.RawMessage, mutation string) (any, error) {+ if r.config.Credentials == nil {+ return nil, failure("UNAVAILABLE", "Go credential service is not configured")+ }+ var input struct {+ Key string `json:"key"`+ Ref string `json:"ref"`+ Record *credentials.Record `json:"record"`+ Callback string `json:"callback"`+ }+ if err := json.Unmarshal(raw, &input); err != nil {+ return nil, err+ }+ if method == "resolve" {+ value, err := r.config.Credentials.Resolve(input.Ref)+ if value == nil {+ return nil, err+ }+ return value.Value, err+ }+ if method == "list" {+ rows, err := r.config.Credentials.ListRecords()+ if err != nil {+ return nil, err+ }+ result := []map[string]string{}+ for _, row := range rows {+ if key, ok := strings.CutPrefix(row.Key, owner+"/"); ok {+ result = append(result, map[string]string{"key": key, "kind": row.Kind})+ }+ }+ return result, nil+ }+ key, err := credentialAddress(owner, input.Key)+ if err != nil {+ return nil, err+ }+ if mutation != "" && (method == "put" || method == "update" || method == "remove") {+ return nil, failure("CONFLICT", "A credential mutation cannot recursively write the credential store")+ }+ switch method {+ case "get":+ return r.config.Credentials.ReadRecord(key)+ case "describe":+ return r.config.Credentials.DescribeRecord(key)+ case "remove":+ return nil, r.config.Credentials.DeleteRecord(ctx, key)+ case "put":+ if input.Record == nil {+ return nil, failure("INVALID_ARGUMENT", "A credential record is required")+ }+ _, err := r.config.Credentials.ModifyRecord(ctx, key, func(*credentials.Record) (*credentials.Record, error) { return input.Record, nil })+ return nil, err+ case "update":+ if !identifier.MatchString(input.Callback) {+ return nil, failure("INVALID_ARGUMENT", "A credential mutation callback is required")+ }+ return r.config.Credentials.ModifyRecord(ctx, key, func(current *credentials.Record) (*credentials.Record, error) {+ var next *credentials.Record+ err := r.peer.callDrained(ctx, "callback.invoke", map[string]any{"owner": owner, "callbackId": input.Callback, "method": "mutate", "args": current, "context": map[string]string{"mutation": uuid.NewString()}}, &next)+ return next, err+ })+ default:+ return nil, failure("NOT_FOUND", "Unknown credential method")+ }+}++func (r *hostBridge) Alive() bool {+ select {+ case <-r.closed:+ return false+ case <-r.done:+ return false+ case <-r.peer.closed:+ return false+ default:+ return true+ }+}diff --git a/internal/plugins/host_bridge_test.go b/internal/plugins/host_bridge_test.gonew file mode 100644index 0000000..b1fc005--- /dev/null+++ b/internal/plugins/host_bridge_test.go@@ -0,0 +1,305 @@+package plugins++import (+ "context"+ "encoding/json"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "go-bot/harness/agent"+ "go-bot/internal/authorization"+ "go-bot/internal/credentials"+ "go-bot/internal/modeldata"+)++func TestHostBridgeRealNodeDirectToolAndNativeCordisDisposal(t *testing.T) {+ c := testRuntimeConfig(t)++ c.Workspace = t.TempDir()+ store, err := credentials.Open(filepath.Join(t.TempDir(), "credentials.yaml"), credentials.Options{})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = store.Close() })+ c.Credentials = store+ c.Authorization = authorization.New(store)+ _, err = store.ModifyRecord(t.Context(), "work/mailbox", func(*credentials.Record) (*credentials.Record, error) {+ key := "example-secret"+ return &credentials.Record{Kind: "api-key", Key: &key}, nil+ })+ if err != nil {+ t.Fatal(err)+ }+ root := filepath.Join(c.ProfileDir, "node_modules", "example-mail")+ if err = os.MkdirAll(root, 0700); err != nil {+ t.Fatal(err)+ }+ for name, text := range map[string]string{+ "package.json": `{"name":"example-mail","version":"0.1.0","type":"module","exports":"./index.mjs","goBot":{"api":"1"}}`,+ "index.mjs": `export const name='mail';export const inject=['host'];export async function apply(ctx){await ctx.host.tools.register({name:'echo',description:'Echo credential presence',inputSchema:{type:'object'},async execute(args,call){const key=await ctx.host.credentials.get('mailbox');return{content:[{type:'text',text:call.sessionId+':'+(key.key?'configured':'missing')}]}}})}`,+ } {+ if err = os.WriteFile(filepath.Join(root, name), []byte(text), 0600); err != nil {+ t.Fatal(err)+ }+ }+ r, err := startHostBridge(t.Context(), c)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = r.Close() })+ status, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "work", Package: "example-mail", Enabled: true}})+ if err != nil || len(status) != 1 || status[0]["state"] != "ready" {+ t.Fatalf("load: %v %v", status, err)+ }+ tools, err := r.Tools(t.Context(), "session-one")+ if err != nil || len(tools) != 1 {+ t.Fatalf("tools: %v %v", tools, err)+ }+ if tools[0].Spec().Name != "work__echo" {+ t.Fatal(tools[0].Spec().Name)+ }+ result, err := tools[0].(interface {+ ExecuteResult(context.Context, json.RawMessage) (modeldata.ToolResult, error)+ }).ExecuteResult(t.Context(), json.RawMessage(`{}`))+ if err != nil || len(result.ContentBlocks) != 1 || result.ContentBlocks[0].Text != "session-one:configured" {+ t.Fatalf("tool: %+v %v", result, err)+ }+ if _, err = r.Apply(t.Context(), nil); err != nil {+ t.Fatal(err)+ }+ if tools, err = r.Tools(t.Context(), "session-one"); err != nil || len(tools) != 0 {+ t.Fatalf("native Cordis cleanup did not remove tools: %v %v", tools, err)+ }+ if record, readErr := store.ReadRecord("work/mailbox"); readErr != nil || record == nil {+ t.Fatalf("plugin unload removed a durable credential: %v", readErr)+ }+}++func bridgeFixture(t *testing.T, source string, configure ...func(*RuntimeConfig)) *hostBridge {+ t.Helper()+ c := testRuntimeConfig(t)++ c.Workspace = t.TempDir()+ store, err := credentials.Open(filepath.Join(t.TempDir(), "credentials.yaml"), credentials.Options{})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = store.Close() })+ c.Credentials = store+ c.Authorization = authorization.New(store)+ root := filepath.Join(c.ProfileDir, "node_modules", "fixture")+ if err = os.MkdirAll(root, 0700); err != nil {+ t.Fatal(err)+ }+ for name, data := range map[string]string{"package.json": `{"name":"fixture","version":"0.1.0","type":"module","exports":"./index.mjs","goBot":{"api":"1"}}`, "index.mjs": source} {+ if err = os.WriteFile(filepath.Join(root, name), []byte(data), 0600); err != nil {+ t.Fatal(err)+ }+ }+ for _, apply := range configure {+ apply(&c)+ }+ r, err := startHostBridge(t.Context(), c)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = r.Close() })+ return r+}++func TestHostBridgeCredentialUpdateIsAtomicAndRejectsReentrantWrites(t *testing.T) {+ r := bridgeFixture(t, `export const name='credentials';export const inject=['host'];export async function apply(ctx){await ctx.host.credentials.put('account',{kind:'grant',payload:{count:0}});await ctx.host.tools.register({name:'update',description:'Update credential',inputSchema:{type:'object'},async execute(){const saved=await ctx.host.credentials.update('account',async current=>{const observed=await ctx.host.credentials.get('account');if(observed.payload.count!==0)throw Error('unexpected snapshot');return{kind:'grant',payload:{count:current.payload.count+1}}});let failure='';try{await ctx.host.credentials.update('account',async current=>{await ctx.host.credentials.put('other',{kind:'api-key',key:'bad'});return current})}catch(error){failure=error.code}return{content:[{type:'text',text:saved.payload.count+':'+failure}]}}})}`)+ status, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "account", Package: "fixture", Enabled: true}})+ if err != nil || len(status) != 1 || status[0]["state"] != "ready" {+ t.Fatalf("apply: %v %v", status, err)+ }+ tools, err := r.Tools(t.Context(), "session")+ if err != nil || len(tools) != 1 {+ t.Fatalf("tools: %v %v", tools, err)+ }+ text, err := tools[0].Execute(t.Context(), json.RawMessage(`{}`))+ if err != nil || text != "1:CONFLICT" {+ t.Fatalf("credential callback: %q %v", text, err)+ }+ other, err := r.config.Credentials.ReadRecord("account/other")+ if err != nil || other != nil {+ t.Fatalf("nested write reached storage: %v %v", other, err)+ }+}++func TestHostBridgeAuthorizationUsesOnlyGoFlowAndCredentialServices(t *testing.T) {+ r := bridgeFixture(t, `export const name='login';export const inject=['host'];export async function apply(ctx){await ctx.host.authorization.register({key:'mailbox',title:'Mailbox',methods:[{id:'code',label:'Use code'}],async run(session){await session.notify({message:'Continue login'});const token=await session.prompt({kind:'secret',message:'Access code'});await session.commit({kind:'grant',payload:{access_token:token}})}})}`)+ status, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "login", Package: "fixture", Enabled: true}})+ if err != nil || len(status) != 1 || status[0]["state"] != "ready" {+ t.Fatalf("apply: %v %v", status, err)+ }+ notices := 0+ result, err := r.config.Authorization.Begin(t.Context(), "login/mailbox", "code", authorization.Interaction{+ Notify: func(context.Context, authorization.Notice) error { notices++; return nil },+ Prompt: func(context.Context, authorization.Prompt) (string, error) { return "test-access-token", nil },+ })+ if err != nil || result.Status != "authorized" || notices != 1 {+ t.Fatalf("authorization: %+v notices=%d %v", result, notices, err)+ }+ record, err := r.config.Credentials.ReadRecord("login/mailbox")+ if err != nil || record == nil || !strings.Contains(string(record.Payload), "test-access-token") {+ t.Fatalf("authorization did not commit to Go credentials: %+v %v", record, err)+ }+ if _, err = r.Apply(t.Context(), nil); err != nil {+ t.Fatal(err)+ }+ if len(r.config.Authorization.List()) != 0 {+ t.Fatal("Cordis disposal retained a Go authorization registration")+ }+}++func TestHostBridgeAuthorizationBrowserCallbackUsesPromiseRPC(t *testing.T) {+ r := bridgeFixture(t, `export const inject=['host'];export async function apply(ctx){await ctx.host.authorization.register({key:'account',title:'Browser account',methods:[{id:'oauth',label:'Connect in browser'}],async run(session){const callback=await session.callback({state:'expected-state'});await session.notify({message:'Open provider',url:callback.url});const query=await callback.wait();if(query.code?.[0]!=='fixture-code')throw Error('Provider response rejected');await session.commit({kind:'grant',payload:{access_token:'fixture-token'}})}})}`)+ if _, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "login", Package: "fixture", Enabled: true}}); err != nil {+ t.Fatal(err)+ }+ surface := authorization.NewSurface(t.Context(), r.config.Authorization, nil)+ t.Cleanup(surface.Close)+ ctx := authorization.WithCallbackBase(t.Context(), "https://controller.example/v1/plugins/authorization/callback/alice/")+ value, err := surface.Handle(ctx, "start", json.RawMessage(`{"key":"login/account"}`))+ if err != nil {+ t.Fatal(err)+ }+ view := value.(authorization.View)+ deadline := time.Now().Add(3 * time.Second)+ for len(view.Notices) == 0 && time.Now().Before(deadline) {+ value, err = surface.Handle(t.Context(), "get", json.RawMessage(`{"id":"`+view.ID+`"}`))+ if err != nil {+ t.Fatal(err)+ }+ view = value.(authorization.View)+ time.Sleep(time.Millisecond)+ }+ if len(view.Notices) != 1 {+ t.Fatalf("Node did not prepare callback: %+v", view)+ }+ u, err := url.Parse(view.Notices[0].URL)+ if err != nil {+ t.Fatal(err)+ }+ input, _ := json.Marshal(map[string]any{"token": u.Path[strings.LastIndex(u.Path, "/")+1:], "query": map[string][]string{"state": {"expected-state"}, "code": {"fixture-code"}}})+ if _, err = surface.Handle(t.Context(), "callback", input); err != nil {+ t.Fatal(err)+ }+ for time.Now().Before(deadline) {+ value, err = surface.Handle(t.Context(), "get", json.RawMessage(`{"id":"`+view.ID+`"}`))+ if err != nil {+ t.Fatal(err)+ }+ view = value.(authorization.View)+ if view.Status != "running" {+ break+ }+ time.Sleep(time.Millisecond)+ }+ if view.Status != "authorized" {+ t.Fatalf("Node callback failed: %+v", view)+ }+ record, err := r.config.Credentials.ReadRecord("login/account")+ if err != nil || record == nil || !strings.Contains(string(record.Payload), "fixture-token") {+ t.Fatal("no Go credential commit", record, err)+ }+}++func bridgeRunTool(t *testing.T, r *hostBridge, name string, approve func(context.Context, agent.ToolPolicyAsk) error) agent.ToolPipelineResult {+ t.Helper()+ tools, err := r.Tools(t.Context(), "session")+ if err != nil {+ t.Fatal(err)+ }+ var target agent.Tool+ for _, tool := range tools {+ if tool.Spec().Name == name {+ target = tool+ break+ }+ }+ if target == nil {+ t.Fatal("missing tool", name)+ }+ p, err := hostToolInvocation(t.Context(), agent.ToolExecution{SessionID: "session", CallID: "recorded-call", Name: name, CWD: r.config.Workspace, Arguments: json.RawMessage(`{}`)}, func(ctx context.Context) modeldata.ToolResult {+ value, err := target.(interface {+ ExecuteResult(context.Context, json.RawMessage) (modeldata.ToolResult, error)+ }).ExecuteResult(ctx, json.RawMessage(`{}`))+ if err != nil {+ return modeldata.ToolResult{IsError: true, Content: err.Error()}+ }+ return value+ }, approve)+ if err != nil {+ t.Fatal(err)+ }+ prepared := p.Prepare()+ outcome := prepared.Outcome+ if prepared.Dispatch {+ outcome = p.Dispatch()+ }+ return p.Complete(outcome)+}++func TestHostBridgeCredentialQueriesUseActualStoreAndInstanceAddresses(t *testing.T) {+ r := bridgeFixture(t, `export const inject=['host'];export async function apply(ctx){+ await ctx.host.credentials.put('account',{kind:'api-key',key:'fixture-key'});+ await ctx.host.tools.register({name:'inspect',description:'Inspect stored credentials',inputSchema:{type:'object'},async execute(){+ const info=await ctx.host.info(),description=await ctx.host.credentials.describe('account'),entries=await ctx.host.credentials.list();+ const ref=await ctx.host.credentials.resolve('SHARED_REF'),missing=await ctx.host.credentials.get('missing');+ const saved=await ctx.host.credentials.update('account',async()=>null);+ await ctx.host.credentials.remove('account');+ return {content:[{type:'text',text:JSON.stringify({info,description,entries,ref,missing,saved,after:await ctx.host.credentials.get('account')})}]};+ }});+}`, func(c *RuntimeConfig) {+ c.UserID, c.HostID = "fixture-user", "fixture-host"+ if err := c.Credentials.Set(t.Context(), "SHARED_REF", "fixture-shared-value"); err != nil {+ t.Fatal(err)+ }+ other := "other-instance-key"+ if _, err := c.Credentials.ModifyRecord(t.Context(), "other/account", func(*credentials.Record) (*credentials.Record, error) {+ return &credentials.Record{Kind: "api-key", Key: &other}, nil+ }); err != nil {+ t.Fatal(err)+ }+ })+ if _, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "mail", Package: "fixture", Enabled: true}}); err != nil {+ t.Fatal(err)+ }+ result := bridgeRunTool(t, r, "mail__inspect", nil)+ decoded, err := agent.DecodeToolPipelineResult(result)+ if err != nil {+ t.Fatal(err)+ }+ var view struct {+ Info struct{ UserID, HostID, DataRoot, APIVersion string }+ Description credentials.RecordInfo+ Entries []credentials.RecordEntry+ Ref string+ Missing, After *credentials.Record+ Saved *credentials.Record+ }+ if err = json.Unmarshal([]byte(decoded.Content), &view); err != nil {+ t.Fatal(err)+ }+ if view.Info.UserID != "fixture-user" || view.Info.HostID != "fixture-host" || view.Info.DataRoot != r.config.Workspace || view.Info.APIVersion != "1" {+ t.Fatalf("info: %+v", view.Info)+ }+ if !view.Description.Configured || !view.Description.Writable || view.Description.Kind != "api-key" || len(view.Entries) != 1 || view.Entries[0].Key != "account" {+ t.Fatalf("view: %+v", view)+ }+ if view.Ref != "fixture-shared-value" || view.Missing != nil || view.After != nil || view.Saved == nil || view.Saved.Key == nil || *view.Saved.Key != "fixture-key" {+ t.Fatalf("store result: %+v", view)+ }+ if strings.Contains(decoded.Content, "other-instance-key") {+ t.Fatal("foreign credential entered the plugin view")+ }+ if record, err := r.config.Credentials.ReadRecord("mail/account"); err != nil || record != nil {+ t.Fatal("remove did not update Go store", err)+ }+}diff --git a/internal/plugins/host_contract_test.go b/internal/plugins/host_contract_test.gonew file mode 100644index 0000000..819db59--- /dev/null+++ b/internal/plugins/host_contract_test.go@@ -0,0 +1,122 @@+package plugins++import (+ "encoding/json"+ "fmt"+ "strings"+ "testing"+ "time"++ "go-bot/internal/credentials"+)++func TestHostBridgeCredentialNotificationUsesPublicMetadata(t *testing.T) {+ r := bridgeFixture(t, `export const inject=['host'];export async function apply(ctx){const changes=[];ctx.on('host/credential-changed',event=>changes.push(event));await ctx.host.tools.register({name:'changes',description:'Read received changes',inputSchema:{type:'object'},async execute(){return{content:[{type:'text',text:JSON.stringify(changes)}]}}})}`)+ if _, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "mail", Package: "fixture", Enabled: true}}); err != nil {+ t.Fatal(err)+ }+ secret := "private-notification-token"+ if _, err := r.config.Credentials.ModifyRecord(t.Context(), "mail/mailbox", func(*credentials.Record) (*credentials.Record, error) {+ return &credentials.Record{Kind: "api-key", Key: &secret}, nil+ }); err != nil {+ t.Fatal(err)+ }+ tools, err := r.Tools(t.Context(), "session")+ if err != nil {+ t.Fatal(err)+ }+ deadline := time.NewTimer(3 * time.Second)+ defer deadline.Stop()+ tick := time.NewTicker(5 * time.Millisecond)+ defer tick.Stop()+ for {+ select {+ case <-deadline.C:+ t.Fatal("credential notification did not reach the Node listener")+ case <-tick.C:+ text, err := tools[0].Execute(t.Context(), json.RawMessage(`{}`))+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(text, secret) {+ t.Fatal("notification leaked the credential")+ }+ if text == "[]" {+ continue+ }+ var received []struct {+ InstanceID string `json:"instanceId"`+ Key string `json:"key"`+ Configured bool `json:"configured"`+ }+ if json.Unmarshal([]byte(text), &received) != nil || len(received) != 1 || received[0].InstanceID != "mail" || received[0].Key != "mailbox" || !received[0].Configured {+ t.Fatal(text)+ }+ return+ }+ }+}++func TestHostBridgeToolResultRejectsUnpublishedAssetAndFactFields(t *testing.T) {+ for _, body := range []string{+ `{content:[{type:'image',image:{id:'forged'}}]}`,+ `{content:[{type:'file',file:{path:'/root/harness/report.txt'}}]}`,+ `{content:[{type:'text',text:'ok'}],meta:{presentedFiles:['/root/harness/report.txt']}}`,+ } {+ t.Run(body, func(t *testing.T) {+ r := bridgeFixture(t, `export const inject=['host'];export async function apply(ctx){if(ctx.host.assets!==undefined||ctx.host.tools.registerGuard!==undefined)throw Error('removed API is present');await ctx.host.tools.register({name:'result',description:'Result contract',inputSchema:{type:'object'},async execute(){return `+body+`}})}`)+ status, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "mail", Package: "fixture", Enabled: true}})+ if err != nil || status[0]["state"] != "ready" {+ t.Fatalf("load=%v err=%v", status, err)+ }+ tools, err := r.Tools(t.Context(), "session")+ if err != nil {+ t.Fatal(err)+ }+ if _, err = tools[0].Execute(t.Context(), json.RawMessage(`{}`)); err == nil {+ t.Fatal("invalid result accepted")+ }+ })+ }+}++func TestHostStateNotificationsAreBoundedAndCoalesced(t *testing.T) {+ r := &hostBridge{closed: make(chan struct{}), notifications: hostNotifications{pending: map[string]hostNotification{}, wake: make(chan struct{}, 1)}}+ for index := 0; index < 70; index++ {+ key := fmt.Sprint(index)+ r.notify("host/credential-changed", key, map[string]int{"revision": index})+ }+ if len(r.notifications.pending) != 64 || len(r.notifications.order) != 64 || r.notifications.dropped != 6 {+ t.Fatal("notification producer was not bounded")+ }+ r.notify("host/credential-changed", "69", map[string]int{"revision": 999})+ if len(r.notifications.order) != 64 || r.notifications.pending["69"].data.(map[string]int)["revision"] != 999 {+ t.Fatal("notification was not coalesced")+ }+ close(r.closed)+ r.notify("host/skills-changed", "after-close", nil)+ if len(r.notifications.order) != 64 {+ t.Fatal("closed runtime accepted a notification")+ }+}++func TestHostBridgeHandshakeConfirmsVersionLimitsAndServices(t *testing.T) {+ r := &hostBridge{}+ for _, raw := range []string{`{"protocol":2,"api":"1"}`, `{"protocol":1,"api":"2"}`} {+ if _, err := r.handle(t.Context(), "bridge.initialize", json.RawMessage(raw)); err == nil {+ t.Fatal("accepted incompatible peer", raw)+ }+ }+ result, err := r.handle(t.Context(), "bridge.initialize", json.RawMessage(`{"protocol":1,"api":"1"}`))+ if err != nil {+ t.Fatal(err)+ }+ view := result.(map[string]any)+ if view["maxFrameBytes"] != maxFrame {+ t.Fatal(view)+ }+ services := view["capabilities"].([]string)+ if strings.Join(services, ",") != "info,tools,skills,prompts,credentials,authorization,mcp,approvals,questions" {+ t.Fatal(services)+ }+}diff --git a/internal/plugins/host_events.go b/internal/plugins/host_events.gonew file mode 100644index 0000000..5fcf2d4--- /dev/null+++ b/internal/plugins/host_events.go@@ -0,0 +1,157 @@+package plugins++import (+ "encoding/json"+ "fmt"+ "strings"+ "sync"++ "go-bot/internal/credentials"+)++// State notifications are bounded, coalesced observations. They never hold up+// a credential write, callback, tool result or Session commit.+type hostNotifications struct {+ mu sync.Mutex+ pending map[string]hostNotification+ order []string+ wake chan struct{}+ dropped uint64+}+type hostNotification struct {+ name string+ data any+}++func (r *hostBridge) notify(name, key string, data any) {+ n := &r.notifications+ n.mu.Lock()+ select {+ case <-r.closed:+ n.mu.Unlock()+ return+ default:+ }+ if _, exists := n.pending[key]; !exists {+ if len(n.order) == 64 {+ delete(n.pending, n.order[0])+ n.order = n.order[1:]+ n.dropped+++ }+ n.order = append(n.order, key)+ }+ n.pending[key] = hostNotification{name, data}+ n.mu.Unlock()+ select {+ case n.wake <- struct{}{}:+ default:+ }+}++func (r *hostBridge) startNotifications() {+ n := &r.notifications+ n.pending, n.wake = make(map[string]hostNotification), make(chan struct{}, 1)+ if r.config.Credentials != nil {+ r.unsubscribers = append(r.unsubscribers, r.config.Credentials.Subscribe(func(update credentials.Update) {+ for _, address := range update.Records {+ owner, key, valid := strings.Cut(address, "/")+ if !valid || !bridgeInstanceName.MatchString(owner) {+ continue+ }+ info, err := r.config.Credentials.DescribeRecord(address)+ if err == nil {+ r.notify("host/credential-changed", "credential:"+address, map[string]any{"instanceId": owner, "key": key, "configured": info.Configured})+ }+ }+ }))+ }+ if r.config.Authorization != nil {+ r.unsubscribers = append(r.unsubscribers, r.config.Authorization.Subscribe(func(address, phase string) {+ owner, key, valid := strings.Cut(address, "/")+ if valid && bridgeInstanceName.MatchString(owner) {+ r.notify("host/authorization-changed", "authorization:"+address, map[string]string{"instanceId": owner, "key": key, "phase": phase})+ }+ }))+ }+ go func() {+ for {+ select {+ case <-r.closed:+ return+ case <-n.wake:+ }+ for {+ n.mu.Lock()+ if len(n.order) == 0 {+ n.mu.Unlock()+ break+ }+ key := n.order[0]+ n.order = n.order[1:]+ event := n.pending[key]+ delete(n.pending, key)+ dropped := n.dropped+ n.dropped = 0+ n.mu.Unlock()+ if dropped > 0 && r.config.Log != nil {+ r.config.Log("warn", fmt.Sprintf("Host state notification queue dropped %d older entries; query current state to refresh", dropped))+ }+ data, err := json.Marshal(map[string]any{"name": event.name, "data": event.data})+ if err == nil {+ err = r.peer.send(frame{JSONRPC: "2.0", Method: "host.event", Params: data})+ }+ if err != nil {+ return+ }+ }+ }+ }()+ if r.config.MCP != nil {+ go func() {+ for {+ changed, done := r.config.MCP.Changes()+ select {+ case <-r.closed:+ return+ case <-done:+ return+ case <-changed:+ }+ for _, row := range r.rows("mcp") {+ var definition hostMCPDefinition+ _ = json.Unmarshal(row.Descriptor, &definition)+ for _, view := range r.mcpViews(row.Owner) {+ if view["name"] == definition.Name {+ payload := map[string]any{"instanceId": row.Owner, "name": definition.Name, "state": view["state"], "toolCount": view["toolCount"]}+ if message, ok := view["error"]; ok {+ payload["error"] = message+ }+ r.notify("host/mcp-changed", "mcp:"+row.ID, payload)+ }+ }+ }+ }+ }()+ }+}+func (r *hostBridge) contributionChanged(row *hostContribution) {+ if strings.HasPrefix(row.Kind, "skill") {+ r.notify("host/skills-changed", "skill:"+row.Owner, map[string]string{"instanceId": row.Owner, "source": row.Kind})+ }+ if row.Kind == "mcp" {+ var definition hostMCPDefinition+ _ = json.Unmarshal(row.Descriptor, &definition)+ payload := map[string]any{"instanceId": row.Owner, "name": definition.Name, "state": "removed", "toolCount": 0}+ if row.ctx.Err() == nil {+ for _, view := range r.mcpViews(row.Owner) {+ if view["name"] == definition.Name {+ payload["state"], payload["toolCount"] = view["state"], view["toolCount"]+ }+ }+ }+ r.notify("host/mcp-changed", "mcp:"+row.ID, payload)+ }+ if r.config.Changed != nil {+ r.config.Changed()+ }+}diff --git a/internal/plugins/host_interaction_test.go b/internal/plugins/host_interaction_test.gonew file mode 100644index 0000000..e838ac9--- /dev/null+++ b/internal/plugins/host_interaction_test.go@@ -0,0 +1,140 @@+package plugins++import (+ "context"+ "strings"+ "testing"+ "time"++ "go-bot/harness/agent"+ "go-bot/harness/interaction"+ sessionformat "go-bot/harness/session"+ "go-bot/internal/modeldata"+ "go-bot/plugin"+)++func TestHostBridgeToolBusinessApprovalUsesGoOutcome(t *testing.T) {+ r := bridgeFixture(t, `export const inject=['host'];export async function apply(ctx){await ctx.host.tools.register({name:'send',description:'Send with approval',inputSchema:{type:'object'},async execute(args,call){const decision=await ctx.host.approvals.request(call,{reason:'Send one message'});return{content:[{type:'text',text:decision==='allowed'?'sent':'skipped:'+decision}]}}})}`)+ if _, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "mail", Package: "fixture", Enabled: true}}); err != nil {+ t.Fatal(err)+ }+ for _, outcome := range []string{"allowed", "rejected", "cancelled", "unavailable"} {+ t.Run(outcome, func(t *testing.T) {+ approve := func(ctx context.Context, ask agent.ToolPolicyAsk) error {+ if _, deadline := ctx.Deadline(); deadline {+ t.Error("ordinary approval inherited a short RPC deadline")+ }+ if ask.Reason != "Send one message" {+ t.Error(ask)+ }+ if outcome != "allowed" {+ return &plugin.Error{Code: "APPROVAL_" + strings.ToUpper(outcome), Message: outcome}+ }+ return nil+ }+ result := bridgeRunTool(t, r, "mail__send", approve)+ decoded, err := agent.DecodeToolPipelineResult(result)+ if err != nil || result.IsError {+ t.Fatalf("result=%+v err=%v", result, err)+ }+ want := "sent"+ if outcome != "allowed" {+ want = "skipped:" + outcome+ }+ if decoded.Content != want {+ t.Fatalf("result=%+v", decoded)+ }+ })+ }+}++type bridgeJournal struct{}++func (bridgeJournal) Append(context.Context, []sessionformat.Event) error { return nil }+func (bridgeJournal) Close() error { return nil }++type bridgeModel func(context.Context, []agent.Message, []agent.ToolSpec) (modeldata.AssistantMessage, error)++func (f bridgeModel) Complete(ctx context.Context, m []agent.Message, t []agent.ToolSpec) (modeldata.AssistantMessage, error) {+ return f(ctx, m, t)+}++func TestHostBridgeQuestionWaitsAndAnswersWithinRealGoTurn(t *testing.T) {+ r := bridgeFixture(t, `export const inject=['host'];export async function apply(ctx){await ctx.host.tools.register({name:'choose',description:'Ask about delivery',inputSchema:{type:'object'},async execute(args,call){const result=await ctx.host.questions.ask(call,{questions:[{id:'delivery',question:'Choose delivery',options:[{label:'Email'},{label:'Download'}]}]});return{content:[{type:'text',text:JSON.stringify(result)}]}}})}`)+ if _, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "mail", Package: "fixture", Enabled: true}}); err != nil {+ t.Fatal(err)+ }+ live, err := sessionformat.NewLiveSession(sessionformat.Header{Type: "session", Version: 4, ID: "question-session", CreatedAt: 1, CWD: r.config.Workspace}, bridgeJournal{})+ if err != nil {+ t.Fatal(err)+ }+ defer live.Close()+ questions := interaction.NewNativeQuestions()+ questions.Enable()+ defer questions.Close()+ calls := 0+ model := bridgeModel(func(_ context.Context, messages []agent.Message, _ []agent.ToolSpec) (modeldata.AssistantMessage, error) {+ calls+++ if calls == 1 {+ return modeldata.AssistantMessage{ToolCalls: []modeldata.ToolRequest{{ID: "choose-call", Name: "mail__choose", Arguments: `{}`}}}, nil+ }+ found := false+ for _, message := range messages {+ if message.Role == "tool" && strings.Contains(message.Content, "Email") {+ found = true+ }+ }+ if !found {+ t.Error("the Go model context did not receive the question answer")+ }+ return modeldata.AssistantMessage{Content: "done"}, nil+ })+ loop, err := agent.NewNativeLoop(live, model, "test", "test", "core prompt", nil, 3, 3)+ if err != nil {+ t.Fatal(err)+ }+ loop.SetToolQuestions(questions)+ loop.SetToolSource(r.Tools)+ loop.SetToolInvocationSource(func(context.Context, string) (agent.ToolInvocationFactory, error) { return hostToolInvocation, nil })+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ if _, err = loop.AcceptText(ctx, "Ask a question"); err != nil {+ t.Fatal(err)+ }+ done := make(chan error, 1)+ go func() { _, _, err := loop.RunNext(ctx); done <- err }()+ tick := time.NewTicker(5 * time.Millisecond)+ defer tick.Stop()+ answered := false+ for !answered {+ select {+ case err := <-done:+ t.Fatalf("turn ended before the user answered: %v", err)+ case <-ctx.Done():+ t.Fatal("question was not published")+ case <-tick.C:+ pending := questions.Pending()+ if len(pending) == 0 {+ continue+ }+ if err := questions.Answer(ctx, pending[0].CallID, interaction.Answer{Answers: []interaction.AnswerItem{{ID: "delivery", Selected: []string{"Email"}}}}); err != nil {+ t.Fatal(err)+ }+ answered = true+ }+ }+ select {+ case err := <-done:+ if err != nil {+ t.Fatal(err)+ }+ case <-ctx.Done():+ t.Fatal("turn did not resume after the answer")+ }+ if calls != 2 || len(questions.Pending()) != 0 {+ t.Fatalf("calls=%d pending=%v", calls, questions.Pending())+ }+ if err := sessionformat.ValidateV4Relationships(live.DurableEvents()); err != nil {+ t.Fatal(err)+ }+}diff --git a/internal/plugins/host_invocations.go b/internal/plugins/host_invocations.gonew file mode 100644index 0000000..6ac0c57--- /dev/null+++ b/internal/plugins/host_invocations.go@@ -0,0 +1,96 @@+package plugins++import (+ "context"+ "encoding/json"+ "errors"+ "strings"++ "github.com/google/uuid"+ "go-bot/harness/agent"+ "go-bot/internal/modeldata"+)++type hostBodyKey struct{}+type hostBody struct {+ execution agent.ToolExecution+ approve func(context.Context, agent.ToolPolicyAsk) error+}+type hostLiveCall struct {+ owner string+ body hostBody+ ctx context.Context+}++func hostToolInvocation(ctx context.Context, execution agent.ToolExecution, dispatch func(context.Context) modeldata.ToolResult, approve func(context.Context, agent.ToolPolicyAsk) error) (*agent.ToolInvocation, error) {+ return agent.NewToolInvocation(ctx, execution, agent.ToolPipelineProcessors{}, func(callCtx context.Context) (agent.ToolPipelineResult, error) {+ callCtx = context.WithValue(callCtx, hostBodyKey{}, hostBody{execution: execution, approve: approve})+ return agent.EncodeToolPipelineResult(dispatch(callCtx))+ }, approve), nil+}++func (r *hostBridge) beginCall(ctx context.Context, tool *hostTool) (map[string]any, func()) {+ body, ok := ctx.Value(hostBodyKey{}).(hostBody)+ if !ok {+ body.execution = agent.ToolExecution{SessionID: tool.sessionID, CWD: tool.cwd, Name: tool.Spec().Name}+ body.execution.CallID, _ = agent.ToolCallIDFromContext(ctx)+ }+ token := uuid.NewString()+ r.invocations.Store(token, &hostLiveCall{owner: tool.row.Owner, body: body, ctx: ctx})+ return map[string]any{"id": body.execution.CallID, "sessionId": tool.sessionID, "cwd": tool.cwd, "workspace": tool.workspace, "invocation": token}, func() { r.invocations.Delete(token) }+}++func (r *hostBridge) approvalCall(ctx context.Context, owner, token string, input json.RawMessage) (any, error) {+ value, ok := r.invocations.Load(token)+ if !ok {+ return nil, failure("UNAVAILABLE", "The tool invocation is not active")+ }+ live := value.(*hostLiveCall)+ if live.owner != owner {+ return nil, failure("INVALID_ARGUMENT", "The invocation belongs to another plugin")+ }+ if live.ctx.Err() != nil {+ return "cancelled", nil+ }+ var request struct {+ Reason string `json:"reason"`+ Detail string `json:"detail,omitempty"`+ }+ if err := decodeHostJSON(input, &request); err != nil {+ return nil, err+ }+ if strings.TrimSpace(request.Reason) == "" {+ return nil, failure("INVALID_ARGUMENT", "An approval reason is required")+ }+ if live.body.approve == nil {+ return "unavailable", nil+ }+ callCtx, cancel := context.WithCancel(live.ctx)+ defer cancel()+ stop := context.AfterFunc(ctx, cancel)+ defer stop()+ reason := request.Reason+ if request.Detail != "" {+ reason += "\n" + request.Detail+ }+ err := live.body.approve(callCtx, agent.ToolPolicyAsk{Reason: reason})+ if err == nil {+ return "allowed", nil+ }+ var detail interface{ ToolErrorInfo() (string, string) }+ if errors.As(err, &detail) {+ _, code := detail.ToolErrorInfo()+ switch code {+ case "APPROVAL_REJECTED":+ return "rejected", nil+ case "APPROVAL_UNAVAILABLE":+ return "unavailable", nil+ case "APPROVAL_CANCELLED":+ return "cancelled", nil+ }+ }+ if callCtx.Err() != nil {+ return "cancelled", nil+ }+ return nil, err+}diff --git a/internal/plugins/host_mcp.go b/internal/plugins/host_mcp.gonew file mode 100644index 0000000..5e67aea--- /dev/null+++ b/internal/plugins/host_mcp.go@@ -0,0 +1,119 @@+package plugins++import (+ "context"+ "encoding/json"+ "path/filepath"+ "strings"++ mcpconfig "go-bot/mcp"+)++type hostMCPDefinition struct {+ Name string `json:"name"`+ Connection mcpconfig.Server `json:"connection"`+ ToolLoading string `json:"toolLoading,omitempty"`+}++func validateHostMCP(row *hostContribution) error {+ var definition hostMCPDefinition+ if err := decodeHostJSON(row.Descriptor, &definition); err != nil {+ return err+ }+ if !mcpconfig.ValidServerName(row.Owner + "__" + definition.Name) {+ return failure("INVALID_ARGUMENT", "The namespaced MCP name must fit within 32 characters")+ }+ if definition.Connection.Enabled != nil {+ return failure("INVALID_ARGUMENT", "MCP registration lifetime is managed by Cordis; enabled is not a connection field")+ }+ if definition.ToolLoading != "" {+ definition.Connection.ToolLoading = definition.ToolLoading+ }+ return definition.Connection.Validate()+}++func (r *hostBridge) registerMCPResource(ctx context.Context, row *hostContribution) (func(context.Context) error, error) {+ if r.config.MCP == nil {+ return nil, failure("UNAVAILABLE", "Go MCP Client is not configured")+ }+ var definition hostMCPDefinition+ _ = json.Unmarshal(row.Descriptor, &definition)+ if definition.ToolLoading != "" {+ definition.Connection.ToolLoading = definition.ToolLoading+ }+ name := row.Owner + "__" + definition.Name+ source := "bridge:" + filepath.Base(r.directory) + ":" + row.Owner+ if err := r.config.MCP.Register(ctx, name, source, definition.Connection); err != nil {+ return nil, err+ }+ return func(ctx context.Context) error { return r.config.MCP.Release(ctx, name, source) }, nil+}++func (r *hostBridge) mcpViews(owner string) []map[string]any {+ views := []map[string]any{}+ for _, view := range r.config.MCP.ListViews() {+ if name, ok := strings.CutPrefix(view.Name, owner+"__"); ok {+ item := map[string]any{"name": name, "state": view.Status.State, "toolCount": view.Status.ToolCount}+ if view.Authorization != nil {+ item["authorization"] = view.Authorization+ }+ if view.Status.LastError != "" {+ message := view.Status.LastError+ if r.config.Credentials != nil {+ message = r.config.Credentials.Redact(message)+ }+ item["error"] = message+ }+ views = append(views, item)+ }+ }+ return views+}++func (r *hostBridge) mcpRequest(ctx context.Context, owner, method string, raw json.RawMessage) (any, error) {+ if r.config.MCP == nil {+ return nil, failure("UNAVAILABLE", "Go MCP Client is not configured")+ }+ var input struct {+ Name string `json:"name"`+ AttemptID string `json:"attemptId,omitempty"`+ }+ if err := decodeHostJSON(raw, &input); err != nil {+ return nil, err+ }+ if method == "list" {+ return r.mcpViews(owner), nil+ }+ name := owner + "__" + input.Name+ if !mcpconfig.ValidServerName(name) {+ return nil, failure("INVALID_ARGUMENT", "Invalid MCP name")+ }+ view := func() any {+ for _, view := range r.mcpViews(owner) {+ if view["name"] == input.Name {+ return view+ }+ }+ return nil+ }+ if method == "inspect" {+ return view(), nil+ }+ if view() == nil {+ return nil, failure("NOT_FOUND", "MCP service was not registered by this plugin")+ }+ switch method {+ case "restart":+ _, err := r.config.MCP.Restart(ctx, name)+ return view(), err+ case "authorize":+ return r.config.MCP.StartAuthorization(ctx, name)+ case "cancelAuthorization":+ return nil, r.config.MCP.CancelAuthorizationAttempt(ctx, name, input.AttemptID)+ case "signOut":+ _, err := r.config.MCP.DisconnectAuthorization(ctx, name)+ return nil, err+ default:+ return nil, failure("NOT_FOUND", "Unknown MCP method")+ }+}diff --git a/internal/plugins/host_mcp_test.go b/internal/plugins/host_mcp_test.gonew file mode 100644index 0000000..399d003--- /dev/null+++ b/internal/plugins/host_mcp_test.go@@ -0,0 +1,75 @@+package plugins++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ sdk "github.com/modelcontextprotocol/go-sdk/mcp"+ "go-bot/harness/agent"+ "go-bot/internal/mcpclient"+)++func TestHostBridgeMCPUsesGoConnectionCredentialsAndDirectTool(t *testing.T) {+ server := sdk.NewServer(&sdk.Implementation{Name: "business", Version: "1"}, nil)+ server.AddTool(&sdk.Tool{Name: "ping", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {+ return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "pong from Go MCP"}}}, nil+ })+ handler := sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return server }, nil)+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "Bearer fixture-secret" {+ http.Error(w, "missing credential", http.StatusUnauthorized)+ return+ }+ handler.ServeHTTP(w, r)+ }))+ defer remote.Close()+ var manager *mcpclient.Manager+ r := bridgeFixture(t, `export const inject=['host'];export async function apply(ctx,config){await ctx.host.mcp.register({name:'docs',connection:{transport:'streamable-http',url:config.url,headers:{Authorization:'Bearer ${credential:MCP_API_KEY}'}}});await ctx.host.tools.register({name:'state',description:'Inspect MCP',inputSchema:{type:'object'},async execute(){return{content:[{type:'text',text:JSON.stringify(await ctx.host.mcp.inspect('docs'))}]}}})}`, func(c *RuntimeConfig) {+ if err := c.Credentials.Set(t.Context(), "MCP_API_KEY", "fixture-secret"); err != nil {+ t.Fatal(err)+ }+ manager = mcpclient.NewManager(t.Context(), mcpclient.ManagerOptions{Credentials: c.Credentials})+ t.Cleanup(func() { _ = manager.Close() })+ c.MCP = manager+ })+ config, _ := json.Marshal(map[string]string{"url": remote.URL})+ loaded, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "mail", Package: "fixture", Enabled: true, Config: config}})+ if err != nil || loaded[0]["state"] != "ready" {+ t.Fatalf("load=%v err=%v", loaded, err)+ }+ result := bridgeRunTool(t, r, "mail__state", nil)+ value, err := agent.DecodeToolPipelineResult(result)+ decoded := value.Content+ if err != nil || !strings.Contains(decoded, `"state":"connected"`) || strings.Contains(decoded, "fixture-secret") {+ t.Fatalf("view=%s err=%v", decoded, err)+ }+ scope := manager.NewScope()+ defer scope.Close()+ tools, err := scope.Tools(t.Context(), "session")+ if err != nil {+ t.Fatal(err)+ }+ found := false+ for _, tool := range tools {+ if strings.HasSuffix(tool.Spec().Name, "ping") {+ found = true+ out, err := tool.Execute(t.Context(), json.RawMessage(`{}`))+ if err != nil || out != "pong from Go MCP" {+ t.Fatal(out, err)+ }+ }+ }+ if !found {+ t.Fatal("Go MCP tool was not discovered")+ }+ if _, err = r.Apply(t.Context(), nil); err != nil {+ t.Fatal(err)+ }+ if len(manager.Status().Servers) != 0 {+ t.Fatal("Cordis disposal retained the Go MCP connection")+ }+}diff --git a/internal/plugins/host_prompt.go b/internal/plugins/host_prompt.gonew file mode 100644index 0000000..7a613c2--- /dev/null+++ b/internal/plugins/host_prompt.go@@ -0,0 +1,65 @@+package plugins++import (+ "context"+ "encoding/json"+ "sort"+ "strings"++ "go-bot/harness/agent"+)++type hostPromptDefinition struct {+ ID string `json:"id"`+ Location string `json:"location"`+ Text *string `json:"text,omitempty"`+ Order int `json:"order,omitempty"`+}++// AssemblePrompt appends only declared contributions. It never delegates core+// prompt assembly, tool selection, memory or compaction to the Node process.+func (r *hostBridge) AssemblePrompt(ctx context.Context, input agent.PromptAssemblyInput) (agent.PromptAssembly, error) {+ output := agent.PromptAssembly{SystemPrompt: input.SystemPrompt, Tools: input.Tools}+ rows := r.rows("prompt")+ definition := func(row *hostContribution) hostPromptDefinition {+ var d hostPromptDefinition+ _ = json.Unmarshal(row.Descriptor, &d)+ return d+ }+ sort.SliceStable(rows, func(i, j int) bool {+ a, b := definition(rows[i]), definition(rows[j])+ if a.Order != b.Order {+ return a.Order < b.Order+ }+ if rows[i].Owner != rows[j].Owner {+ return rows[i].Owner < rows[j].Owner+ }+ return a.ID < b.ID+ })+ size := 0+ for _, row := range rows {+ d := definition(row)+ text := ""+ if d.Text != nil {+ text = *d.Text+ } else {+ view := map[string]any{"sessionId": input.SessionID, "cwd": input.CWD, "workspace": input.CWD, "model": map[string]string{"provider": input.ModelSelection.Provider, "name": input.ModelSelection.Model}}+ if err := r.callback(ctx, row, "text", view, nil, &text); err != nil {+ return output, err+ }+ }+ size += len(text)+ if size > 256<<10 {+ return output, failure("INVALID_RESULT", "Plugin prompt contributions exceed 256 KiB")+ }+ if strings.TrimSpace(text) == "" {+ continue+ }+ if d.Location == "system" {+ output.SystemPrompt += "\n\n" + text+ } else {+ output.Contexts = append(output.Contexts, agent.RuntimeContextSection{Name: row.Owner + "/" + d.ID, Text: text})+ }+ }+ return output, ctx.Err()+}diff --git a/internal/plugins/host_questions.go b/internal/plugins/host_questions.gonew file mode 100644index 0000000..28f76cb--- /dev/null+++ b/internal/plugins/host_questions.go@@ -0,0 +1,49 @@+package plugins++import (+ "context"+ "encoding/json"++ "github.com/google/uuid"+ "go-bot/harness/agent"+ "go-bot/harness/interaction"+)++func (r *hostBridge) questionCall(ctx context.Context, owner, token string, raw json.RawMessage) (any, error) {+ value, ok := r.invocations.Load(token)+ if !ok {+ return nil, failure("UNAVAILABLE", "An active tool body is required to ask a question")+ }+ live := value.(*hostLiveCall)+ if live.owner != owner {+ return nil, failure("INVALID_ARGUMENT", "The invocation belongs to another plugin")+ }+ questions := agent.ToolQuestionsFromContext(live.ctx)+ if questions == nil {+ return nil, failure("UNAVAILABLE", "This invocation has no user question channel")+ }+ var input struct {+ Questions []interaction.Question `json:"questions"`+ }+ if err := decodeHostJSON(raw, &input); err != nil {+ return nil, err+ }+ if len(input.Questions) > 16 {+ return nil, failure("INVALID_ARGUMENT", "A question request supports at most 16 items")+ }+ if err := interaction.ValidateQuestions(input.Questions); err != nil {+ return nil, failure("INVALID_ARGUMENT", err.Error())+ }+ turn, step, ok := agent.ToolPositionFromContext(live.ctx)+ if !ok {+ return nil, failure("UNAVAILABLE", "The question requires a running Agent step")+ }+ callCtx, cancel := context.WithCancel(live.ctx)+ defer cancel()+ stop := context.AfterFunc(ctx, cancel)+ defer stop()+ // Multiple questions from one tool are separate foreground waits. The ID is+ // only an answer-channel key, never a replacement for the durable tool call.+ id := "plugin-question-" + uuid.NewString()+ return questions.Ask(callCtx, turn, step, id, input.Questions)+}diff --git a/internal/plugins/host_services_test.go b/internal/plugins/host_services_test.gonew file mode 100644index 0000000..3527264--- /dev/null+++ b/internal/plugins/host_services_test.go@@ -0,0 +1,123 @@+package plugins++import (+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "go-bot/harness/agent"+ "go-bot/harness/skills"+)++func TestHostBridgeSkillsUseGoDiscoveryAndProviderCallbacks(t *testing.T) {+ r := bridgeFixture(t, `export const name='skills';export const inject=['host'];export async function apply(ctx){+ await ctx.host.credentials.put('lookup',{kind:'grant',payload:{name:'remote-skill'}});+ await ctx.host.skills.register({name:'shared-skill',description:'Plugin version',content:'plugin body'});+ await ctx.host.skills.registerDirectory('skills');+ await ctx.host.skills.registerProvider({id:'remote',async list(context){+ const stored=await ctx.host.credentials.get('lookup');+ let blocked=false;try{await ctx.host.skills.list()}catch(error){blocked=error.code==='CONFLICT'}+ if(!blocked)throw Error('reentrant discovery was allowed');+ return{items:[{name:stored.payload.name,description:'Remote summary',key:{id:7}}],complete:true};+ },async get(key,context){if(key.id!==7)throw Error('locator changed');return{name:'remote-skill',description:'Remote summary',content:'loaded for '+context.cwd}}});+ await ctx.host.tools.register({name:'inspect',description:'Inspect Go Skill registry',inputSchema:{type:'object'},async execute(){+ await ctx.host.skills.invalidate();const listed=await ctx.host.skills.list();const loaded=await ctx.host.skills.get('remote-skill');+ return{content:[{type:'text',text:JSON.stringify({listed,loaded})}]};+ }});+}`, func(c *RuntimeConfig) {+ c.Skills = &skills.Registry{DSHHome: filepath.Join(c.Workspace, ".dsh")}+ files := map[string]string{+ filepath.Join(c.Skills.DSHHome, "skills", "shared-skill", "SKILL.md"): "---\nname: shared-skill\ndescription: User version\n---\nuser body",+ filepath.Join(c.ProfileDir, "node_modules", "fixture", "skills", "bundled-skill", "SKILL.md"): "---\nname: bundled-skill\ndescription: Package directory\n---\nbundled body",+ }+ for path, data := range files {+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(data), 0600); err != nil {+ t.Fatal(err)+ }+ }+ })+ r.config.Skills.Providers = r.Skills+ status, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "skills", Package: "fixture", Enabled: true}})+ if err != nil || status[0]["state"] != "ready" {+ t.Fatalf("load: %v %v", status, err)+ }+ lookup := skills.Lookup{CWD: r.config.Workspace, Workspace: r.config.Workspace}+ snapshot, err := r.config.Skills.Snapshot(t.Context(), lookup)+ if err != nil || !snapshot.Complete || len(snapshot.Entries) != 3 {+ t.Fatalf("snapshot: %+v %v", snapshot, err)+ }+ for _, name := range []string{"shared-skill", "bundled-skill", "remote-skill"} {+ candidate, found, err := r.config.Skills.Find(t.Context(), lookup, name)+ if err != nil || !found {+ t.Fatalf("find %s: %v %v", name, found, err)+ }+ loaded, found, err := candidate.Load(t.Context())+ if err != nil || !found {+ t.Fatalf("load %s: %v %v", name, found, err)+ }+ if name == "shared-skill" && loaded.Value.Content != "user body" {+ t.Fatalf("plugin shadowed user's skill: %+v", loaded)+ }+ if name == "remote-skill" && loaded.Value.Content != "loaded for "+lookup.CWD {+ t.Fatal(loaded)+ }+ }++ updated := "---\nname: bundled-skill\ndescription: Updated package directory\n---\nupdated directory body"+ if err := os.WriteFile(filepath.Join(r.config.ProfileDir, "node_modules", "fixture", "skills", "bundled-skill", "SKILL.md"), []byte(updated), 0600); err != nil {+ t.Fatal(err)+ }+ candidate, found, err := r.config.Skills.Find(t.Context(), lookup, "bundled-skill")+ if err != nil || !found {+ t.Fatal("updated directory not discovered", err)+ }+ loaded, found, err := candidate.Load(t.Context())+ if err != nil || !found || loaded.Value.Content != "updated directory body" {+ t.Fatalf("stale directory: %+v %v", loaded, err)+ }+ tools, err := r.Tools(t.Context(), "session")+ if err != nil {+ t.Fatal(err)+ }+ text, err := tools[0].Execute(t.Context(), json.RawMessage(`{}`))+ if err != nil || !strings.Contains(text, `"complete":true`) || !strings.Contains(text, "loaded for ") {+ t.Fatalf("nested Go discovery: %s %v", text, err)+ }+ if _, err = r.Apply(t.Context(), nil); err != nil {+ t.Fatal(err)+ }+ snapshot, err = r.config.Skills.Snapshot(t.Context(), lookup)+ if err != nil || len(snapshot.Entries) != 1 || snapshot.Entries[0].Name != "shared-skill" {+ t.Fatalf("unload: %+v %v", snapshot, err)+ }+}++func TestHostBridgePromptIsAppendedInGoAndReflectsCurrentInput(t *testing.T) {+ r := bridgeFixture(t, `export const name='prompt';export const inject=['host'];export async function apply(ctx){+ await ctx.host.prompts.register({id:'last',location:'system',order:9,text:'last'});+ await ctx.host.prompts.register({id:'dynamic',location:'context',text:async context=>'cwd='+context.cwd+';model='+context.model.name});+ await ctx.host.prompts.register({id:'first',location:'system',order:-1,text:'first'});+}`)+ status, err := r.Apply(t.Context(), []hostPluginInstance{{ID: "prompt", Package: "fixture", Enabled: true}})+ if err != nil || status[0]["state"] != "ready" {+ t.Fatalf("load: %v %v", status, err)+ }+ for _, model := range []string{"one", "two"} {+ out, err := r.AssemblePrompt(t.Context(), agent.PromptAssemblyInput{SessionID: "session", CWD: r.config.Workspace, SystemPrompt: "core memory + skills", Tools: []agent.ToolSpec{{Name: "shellexecute"}}, ModelSelection: agent.ModelRoute{Provider: "main", Model: model}})+ if err != nil || out.SystemPrompt != "core memory + skills\n\nfirst\n\nlast" || len(out.Tools) != 1 || len(out.Contexts) != 1 || out.Contexts[0].Text != "cwd="+r.config.Workspace+";model="+model {+ t.Fatalf("assembly: %+v %v", out, err)+ }+ }+ if _, err = r.Apply(t.Context(), nil); err != nil {+ t.Fatal(err)+ }+ out, err := r.AssemblePrompt(t.Context(), agent.PromptAssemblyInput{SystemPrompt: "core"})+ if err != nil || out.SystemPrompt != "core" || len(out.Contexts) != 0 {+ t.Fatalf("unload: %+v %v", out, err)+ }+}diff --git a/internal/plugins/host_skills.go b/internal/plugins/host_skills.gonew file mode 100644index 0000000..4868d1a--- /dev/null+++ b/internal/plugins/host_skills.go@@ -0,0 +1,295 @@+package plugins++import (+ "context"+ "encoding/json"+ "os"+ "path/filepath"+ "strings"++ "go-bot/harness/skills"+)++type hostSkillSummary struct {+ Name string `json:"name"`+ Description string `json:"description"`+ WhenToUse string `json:"whenToUse,omitempty"`+ ModelInvocable *bool `json:"modelInvocable,omitempty"`+ UserInvocable *bool `json:"userInvocable,omitempty"`+ ResourceBase *skills.ResourceBase `json:"resourceBase,omitempty"`+}+type hostSkillDefinition struct {+ hostSkillSummary+ Content string `json:"content"`+}+type hostSkillItem struct {+ hostSkillSummary+ Key json.RawMessage `json:"key"`+}++func (s hostSkillSummary) validate() error {+ if !skills.IsName(s.Name) || strings.TrimSpace(s.Description) == "" || len(s.Description) > 16000 {+ return failure("INVALID_ARGUMENT", "A Skill needs a valid name and description")+ }+ if base := s.ResourceBase; base != nil {+ switch base.Kind {+ case "directory":+ if !filepath.IsAbs(base.Path) {+ return failure("INVALID_ARGUMENT", "A Skill resource directory must be absolute")+ }+ case "url":+ if !strings.HasPrefix(base.URL, "https://") && !strings.HasPrefix(base.URL, "http://") {+ return failure("INVALID_ARGUMENT", "A Skill resource URL must use HTTP(S)")+ }+ default:+ return failure("INVALID_ARGUMENT", "Invalid Skill resource base")+ }+ }+ return nil+}+func (s hostSkillSummary) summary() skills.Summary {+ model, user := true, true+ if s.ModelInvocable != nil {+ model = *s.ModelInvocable+ }+ if s.UserInvocable != nil {+ user = *s.UserInvocable+ }+ return skills.Summary{Name: s.Name, Description: s.Description, WhenToUse: s.WhenToUse, ModelInvocable: model, UserInvocable: user}+}+func (s hostSkillDefinition) loaded(provider string) (skills.Loaded, error) {+ if err := s.hostSkillSummary.validate(); err != nil {+ return skills.Loaded{}, err+ }+ if strings.TrimSpace(s.Content) == "" || len(s.Content) > 256<<10 {+ return skills.Loaded{}, failure("INVALID_RESULT", "A Skill needs nonempty content within 256 KiB")+ }+ return skills.Loaded{Summary: s.summary(), Value: skills.Value{Name: s.Name, Provider: provider, Content: s.Content, ResourceBase: s.ResourceBase}}, nil+}+func validateHostSkill(row *hostContribution) error {+ switch row.Kind {+ case "skill":+ var d hostSkillDefinition+ if err := decodeHostJSON(row.Descriptor, &d); err != nil {+ return err+ }+ _, err := d.loaded(row.Owner)+ return err+ case "skill-directory":+ var d struct {+ Path string `json:"path"`+ }+ if err := decodeHostJSON(row.Descriptor, &d); err != nil {+ return err+ }+ info, err := os.Stat(d.Path)+ if err != nil {+ return err+ }+ if !filepath.IsAbs(d.Path) || !info.IsDir() {+ return failure("INVALID_ARGUMENT", "A Skill root must be an existing absolute directory")+ }+ return nil+ case "skill-provider":+ var d struct {+ ID string `json:"id"`+ }+ if err := decodeHostJSON(row.Descriptor, &d); err != nil {+ return err+ }+ if !identifier.MatchString(d.ID) {+ return failure("INVALID_ARGUMENT", "A Skill provider needs an id")+ }+ found := map[string]bool{}+ for _, name := range row.Callbacks {+ found[name] = true+ }+ if !found["list"] || !found["get"] {+ return failure("INVALID_ARGUMENT", "A Skill provider needs list and get callbacks")+ }+ return nil+ }+ return failure("NOT_FOUND", "Unknown Skill contribution")+}++// Skills supplies sources to the existing Go discovery merger. Filesystem+// user/project sources keep their original rank and win over bundled sources.+func (r *hostBridge) Skills(_ context.Context, _ skills.Lookup) ([]skills.Provider, error) {+ var result []skills.Provider+ for _, kind := range []string{"skill", "skill-directory", "skill-provider"} {+ for _, row := range r.rows(kind) {+ provider := skills.Provider{Name: row.Owner + ":" + row.ID}+ provider.List = func(ctx context.Context, lookup skills.Lookup) (skills.ProviderSnapshot, error) {+ if row.ctx.Err() != nil {+ return skills.ProviderSnapshot{}, failure("UNAVAILABLE", "Skill contribution was disposed")+ }+ snapshot := skills.ProviderSnapshot{Complete: true, Entries: []skills.ProviderEntry{}}+ add := func(d hostSkillSummary, key json.RawMessage) error {+ if err := d.validate(); err != nil {+ return err+ }+ if !json.Valid(key) {+ return failure("INVALID_RESULT", "Skill provider keys must be JSON values")+ }+ snapshot.Entries = append(snapshot.Entries, skills.ProviderEntry{Summary: d.summary(), Rank: 600 + float64(row.order), Data: key})+ return nil+ }+ switch row.Kind {+ case "skill":+ var d hostSkillDefinition+ _ = json.Unmarshal(row.Descriptor, &d)+ if err := add(d.hostSkillSummary, json.RawMessage(`null`)); err != nil {+ return snapshot, err+ }+ case "skill-directory":+ var d struct {+ Path string `json:"path"`+ }+ _ = json.Unmarshal(row.Descriptor, &d)+ disk := &skills.Registry{CustomDirs: []string{d.Path}}+ files, err := disk.Snapshot(ctx, skills.Lookup{})+ if err != nil {+ return snapshot, err+ }+ snapshot.Complete = files.Complete+ for _, candidate := range files.Entries {+ key, _ := json.Marshal(candidate.Name)+ snapshot.Entries = append(snapshot.Entries, skills.ProviderEntry{Summary: candidate.Summary, Rank: 600 + float64(row.order), Data: key})+ }+ case "skill-provider":+ var listed struct {+ Items []hostSkillItem `json:"items"`+ Complete bool `json:"complete"`+ }+ if err := r.callback(ctx, row, "list", map[string]string{"cwd": lookup.CWD}, map[string]bool{"discovery": true}, &listed); err != nil {+ return snapshot, err+ }+ if len(listed.Items) > 4096 {+ return snapshot, failure("INVALID_RESULT", "Skill provider returned too many entries")+ }+ snapshot.Complete = listed.Complete+ seen := map[string]bool{}+ for _, item := range listed.Items {+ if seen[item.Name] {+ return snapshot, failure("INVALID_RESULT", "Skill provider returned duplicate names")+ }+ seen[item.Name] = true+ if err := add(item.hostSkillSummary, item.Key); err != nil {+ return snapshot, err+ }+ }+ }+ return snapshot, nil+ }+ provider.Load = func(ctx context.Context, lookup skills.Lookup, entry skills.ProviderEntry) (skills.Loaded, error) {+ if row.ctx.Err() != nil {+ return skills.Loaded{}, failure("UNAVAILABLE", "Skill contribution was disposed")+ }+ switch row.Kind {+ case "skill":+ var d hostSkillDefinition+ _ = json.Unmarshal(row.Descriptor, &d)+ return d.loaded(provider.Name)+ case "skill-directory":+ var d struct {+ Path string `json:"path"`+ }+ _ = json.Unmarshal(row.Descriptor, &d)+ disk := &skills.Registry{CustomDirs: []string{d.Path}}+ candidate, found, err := disk.Find(ctx, skills.Lookup{}, entry.Name)+ if err != nil {+ return skills.Loaded{}, err+ }+ if !found {+ return skills.Loaded{}, os.ErrNotExist+ }+ value, found, err := candidate.Load(ctx)+ if err == nil && !found {+ err = os.ErrNotExist+ }+ return value, err+ default:+ var d *hostSkillDefinition+ if err := r.callback(ctx, row, "get", map[string]any{"key": entry.Data, "context": map[string]string{"cwd": lookup.CWD}}, map[string]bool{"discovery": true}, &d); err != nil {+ return skills.Loaded{}, err+ }+ if d == nil {+ return skills.Loaded{}, os.ErrNotExist+ }+ if d.Name != entry.Name {+ return skills.Loaded{}, failure("INVALID_RESULT", "Skill provider changed the selected identity")+ }+ return d.loaded(provider.Name)+ }+ }+ result = append(result, provider)+ }+ }+ return result, nil+}++func (r *hostBridge) skillRequest(ctx context.Context, method string, raw json.RawMessage, discovery bool) (any, error) {+ if discovery {+ return nil, failure("CONFLICT", "Skill discovery cannot recursively query the merged Skill registry")+ }+ if r.config.Skills == nil {+ return nil, failure("UNAVAILABLE", "Go Skill registry is not configured")+ }+ var input struct {+ CWD string `json:"cwd"`+ Name string `json:"name,omitempty"`+ }+ if err := decodeHostJSON(raw, &input); err != nil {+ return nil, err+ }+ lookup := skills.Lookup{CWD: input.CWD, Workspace: r.config.Workspace}+ if lookup.CWD == "" {+ lookup.CWD = lookup.Workspace+ }+ if !filepath.IsAbs(lookup.CWD) {+ return nil, failure("INVALID_ARGUMENT", "Skill lookup requires an absolute cwd")+ }+ switch method {+ case "invalidate":+ return nil, nil // No extra Bridge cache; Go revalidates every selected source.+ case "list":+ snapshot, err := r.config.Skills.Snapshot(ctx, lookup)+ if err != nil {+ return nil, err+ }+ items := []map[string]any{}+ for _, entry := range snapshot.Entries {+ items = append(items, hostSkillCatalog(entry.Catalog()))+ }+ return map[string]any{"items": items, "complete": snapshot.Complete}, nil+ case "get":+ candidate, found, err := r.config.Skills.Find(ctx, lookup, input.Name)+ if err != nil || !found {+ return nil, err+ }+ value, found, err := candidate.Load(ctx)+ if err != nil || !found {+ return nil, err+ }+ definition := candidate.Definition(value)+ result := hostSkillCatalog(definition.CatalogSkill)+ result["content"] = definition.Content+ return result, nil+ default:+ return nil, failure("NOT_FOUND", "Unknown Skill method")+ }+}++func hostSkillCatalog(value skills.CatalogSkill) map[string]any {+ result := map[string]any{"name": value.Name, "description": value.Description, "source": value.Source, "provider": value.Provider, "modelInvocable": value.Invocation.ModelInvocable, "userInvocable": value.Invocation.UserInvocable}+ if value.WhenToUse != "" {+ result["whenToUse"] = value.WhenToUse+ }+ if value.Path != "" {+ result["path"] = value.Path+ }+ if value.ResourceBase != nil {+ result["resourceBase"] = value.ResourceBase+ }+ return result+}diff --git a/internal/plugins/host_tools.go b/internal/plugins/host_tools.gonew file mode 100644index 0000000..3029616--- /dev/null+++ b/internal/plugins/host_tools.go@@ -0,0 +1,174 @@+package plugins++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "regexp"+ "strings"+ "time"++ "github.com/santhosh-tekuri/jsonschema/v6"+ "go-bot/harness/agent"+ "go-bot/harness/content"+ "go-bot/internal/modeldata"+)++var hostToolName = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)++func decodeHostJSON(raw json.RawMessage, out any) error {+ d := json.NewDecoder(bytes.NewReader(raw))+ d.DisallowUnknownFields()+ if err := d.Decode(out); err != nil {+ return failure("INVALID_ARGUMENT", err.Error())+ }+ if !errors.Is(d.Decode(new(any)), io.EOF) {+ return failure("INVALID_ARGUMENT", "Expected one JSON object")+ }+ return nil+}++type hostTool struct {+ runtime *hostBridge+ row *hostContribution+ definition struct {+ Name string `json:"name"`+ Description string `json:"description"`+ InputSchema json.RawMessage `json:"inputSchema"`+ Concurrency string `json:"concurrency,omitempty"`+ TimeoutMs int64 `json:"timeoutMs,omitempty"`+ }+ schema *jsonschema.Schema+ sessionID, cwd, workspace string+}++func (r *hostBridge) newTool(row *hostContribution) (*hostTool, error) {+ t := &hostTool{runtime: r, row: row}+ if err := decodeHostJSON(row.Descriptor, &t.definition); err != nil {+ return nil, err+ }+ d := t.definition+ if !hostToolName.MatchString(d.Name) || len(row.Owner+"__"+d.Name) > 64 || strings.TrimSpace(d.Description) == "" || len(d.Description) > 32000 || d.TimeoutMs < 0 || d.TimeoutMs > int64((24*time.Hour)/time.Millisecond) {+ return nil, failure("INVALID_ARGUMENT", "Invalid tool definition")+ }+ if d.Concurrency != "" && d.Concurrency != "exclusive" && d.Concurrency != "parallel" {+ return nil, failure("INVALID_ARGUMENT", "Invalid tool concurrency")+ }+ var schema map[string]any+ if json.Unmarshal(d.InputSchema, &schema) != nil || schema["type"] != "object" {+ return nil, failure("INVALID_ARGUMENT", "Tool inputSchema needs an object root")+ }+ compiled, err := compileSchema(d.InputSchema)+ if err != nil {+ return nil, err+ }+ t.schema = compiled+ found := false+ for _, callback := range row.Callbacks {+ if callback == "execute" {+ found = true+ }+ }+ if !found {+ return nil, failure("INVALID_ARGUMENT", "Tool execute callback is required")+ }+ return t, nil+}++func (t *hostTool) Spec() agent.ToolSpec {+ return agent.ToolSpec{Name: t.row.Owner + "__" + t.definition.Name, Description: t.definition.Description, Parameters: bytes.Clone(t.definition.InputSchema), ParallelSafe: t.definition.Concurrency == "parallel", Timeout: time.Duration(t.definition.TimeoutMs) * time.Millisecond}+}+func (t *hostTool) Validate(raw json.RawMessage) error { return validateSchema(t.schema, raw) }+func (t *hostTool) Execute(ctx context.Context, raw json.RawMessage) (string, error) {+ result, err := t.ExecuteResult(ctx, raw)+ var text []string+ for _, block := range result.ContentBlocks {+ if block.Type == "text" {+ text = append(text, block.Text)+ }+ }+ return strings.Join(text, "\n"), err+}++type hostResultBlock struct {+ Type string `json:"type"`+ Text string `json:"text,omitempty"`+}++func (t *hostTool) ExecuteResult(ctx context.Context, raw json.RawMessage) (modeldata.ToolResult, error) {+ if err := t.Validate(raw); err != nil {+ return modeldata.ToolResult{}, err+ }+ var output struct {+ Content []hostResultBlock `json:"content"`+ Data json.RawMessage `json:"data"`+ }+ call, finish := t.runtime.beginCall(ctx, t)+ defer finish()+ var encoded json.RawMessage+ if err := t.runtime.callback(ctx, t.row, "execute", raw, call, &encoded); err != nil {+ return modeldata.ToolResult{}, err+ }+ if err := decodeHostJSON(encoded, &output); err != nil {+ return modeldata.ToolResult{}, failure("INVALID_RESULT", "Invalid plugin tool result: "+err.Error())+ }+ if len(output.Content) == 0 || len(output.Content) > 256 {+ return modeldata.ToolResult{}, failure("INVALID_RESULT", "Tool content must contain between one and 256 blocks")+ }+ result := modeldata.ToolResult{}+ for _, block := range output.Content {+ switch block.Type {+ case "text":+ if block.Text == "" {+ return result, failure("INVALID_RESULT", "Tool text must not be empty")+ }+ result.ContentBlocks = append(result.ContentBlocks, content.ContentBlock{Type: "text", Text: block.Text})+ default:+ return result, failure("INVALID_RESULT", "Unsupported tool content block")+ }+ }+ if len(output.Data) == 0 {+ output.Data = json.RawMessage(`null`)+ }+ result.Meta, _ = json.Marshal(map[string]any{"canonicalValue": output.Data})+ return result, nil+}++func (r *hostBridge) Tools(ctx context.Context, sessionID string) ([]agent.Tool, error) {+ info, _ := agent.ToolSourceInfoFromContext(ctx)+ cwd := info.CWD+ if cwd == "" {+ cwd = r.config.Workspace+ }+ var result []agent.Tool+ for _, row := range r.rows("tool") {+ tool := *row.tool+ tool.sessionID = sessionID+ tool.cwd = cwd+ tool.workspace = cwd+ result = append(result, &tool)+ }+ return result, nil+}++func validateHostPrompt(row *hostContribution) error {+ var definition hostPromptDefinition+ if err := decodeHostJSON(row.Descriptor, &definition); err != nil {+ return err+ }+ if !identifier.MatchString(definition.ID) || (definition.Location != "system" && definition.Location != "context") {+ return failure("INVALID_ARGUMENT", "Invalid prompt contribution")+ }+ if definition.Text != nil {+ return nil+ }+ for _, method := range row.Callbacks {+ if method == "text" {+ return nil+ }+ }+ return fmt.Errorf("a prompt needs static text or a text callback")+}diff --git a/internal/plugins/http.go b/internal/plugins/http.gonew file mode 100644index 0000000..144a29d--- /dev/null+++ b/internal/plugins/http.go@@ -0,0 +1,113 @@+package plugins++import (+ "encoding/json"+ "errors"+ "go-bot/plugin"+ "io"+ "net/http"+ "strings"+)++func (m *Manager) Handler() http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ respond := func(code int, value any) {+ w.Header().Set("Content-Type", "application/json")+ w.Header().Set("Cache-Control", "no-store")+ w.WriteHeader(code)+ _ = json.NewEncoder(w).Encode(value)+ }+ decode := func(value any) error {+ d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))+ d.DisallowUnknownFields()+ if err := d.Decode(value); err != nil {+ return err+ }+ if !errors.Is(d.Decode(new(any)), io.EOF) {+ return errors.New("expected one JSON object")+ }+ return nil+ }+ fail := func(err error) {+ respond(http.StatusUnprocessableEntity, map[string]string{"error": "plugin_operation_failed", "message": m.redact(err.Error())})+ }+ suffix := strings.TrimPrefix(r.URL.Path, plugin.InternalPath)+ switch {+ case suffix == "/authorization" || strings.HasPrefix(suffix, "/authorization/"):+ m.authorizationHTTP(w, r, respond, decode)+ case r.Method == http.MethodGet && suffix == "":+ status, err := m.Status(r.Context())+ if err != nil {+ fail(err)+ return+ }+ respond(200, status)+ case r.Method == http.MethodPut && suffix == "/settings":+ var settings plugin.RuntimeSettings+ if err := decode(&settings); err != nil {+ respond(400, map[string]string{"error": "invalid_plugin_settings"})+ return+ }+ status, err := m.Apply(r.Context(), settings)+ if err != nil {+ fail(err)+ return+ }+ respond(200, status)+ case r.Method == http.MethodPost && suffix == "/packages/inspect":+ var input struct {+ Name string `json:"name"`+ Source plugin.Source `json:"source"`+ }+ if err := decode(&input); err != nil {+ respond(400, map[string]string{"error": "invalid_plugin_package"})+ return+ }+ info, err := m.InspectPackage(r.Context(), input.Name, input.Source)+ if err != nil {+ fail(err)+ return+ }+ respond(200, info)+ case r.Method == http.MethodPost && (suffix == "/packages/remove" || suffix == "/packages/reinstall"):+ var input struct {+ Name string `json:"name"`+ Settings plugin.RuntimeSettings `json:"settings"`+ }+ if err := decode(&input); err != nil {+ respond(400, map[string]string{"error": "invalid_plugin_package"})+ return+ }+ var status Status+ var err error+ if suffix == "/packages/remove" {+ status, err = m.Remove(r.Context(), input.Name, input.Settings)+ } else {+ status, err = m.Reinstall(r.Context(), input.Name, input.Settings)+ }+ if err != nil {+ fail(err)+ return+ }+ respond(200, status)+ case r.Method == http.MethodPost && suffix == "/runtime/restart":+ var input struct {+ Settings *plugin.RuntimeSettings `json:"settings,omitempty"`+ }+ if r.Body != nil && r.ContentLength != 0 {+ if err := decode(&input); err != nil {+ respond(400, map[string]string{"error": "invalid_plugin_settings"})+ return+ }+ }+ status, err := m.restart(r.Context(), input.Settings)+ if err != nil {+ fail(err)+ return+ }+ respond(200, status)+ default:+ http.NotFound(w, r)+ }+ })+}diff --git a/internal/plugins/install_concurrency_test.go b/internal/plugins/install_concurrency_test.gonew file mode 100644index 0000000..8d901c5--- /dev/null+++ b/internal/plugins/install_concurrency_test.go@@ -0,0 +1,98 @@+package plugins++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"+ "time"++ "go-bot/plugin"+)++func TestNewPackageInstallationKeepsExistingCordisToolsAvailable(t *testing.T) {+ c := testRuntimeConfig(t)+ c.Workspace = t.TempDir()+ directory := t.TempDir()+ root := filepath.Join(directory, "profile", "node_modules", "fixture")+ if err := os.MkdirAll(root, 0700); err != nil {+ t.Fatal(err)+ }+ for name, text := range map[string]string{+ "package.json": `{"name":"fixture","version":"0.1.0","type":"module","exports":"./index.mjs","goBot":{"api":"1"}}`,+ "index.mjs": `export const inject=['host'];export async function apply(ctx){await ctx.host.tools.register({name:'echo',description:'Existing working tool',inputSchema:{type:'object'},async execute(){return{content:[{type:'text',text:'ready'}]}}})}`,+ } {+ if err := os.WriteFile(filepath.Join(root, name), []byte(text), 0600); err != nil {+ t.Fatal(err)+ }+ }+ base := plugin.RuntimePackage{Source: plugin.Source{Type: "directory", Spec: root}, Version: "0.1.0"}+ data, _ := json.Marshal([]plugin.PackageInfo{{Name: "fixture", Version: "0.1.0", API: "1", Present: true, Source: base.Source}})+ state, started, release := filepath.Join(directory, "installed.json"), filepath.Join(directory, "started"), filepath.Join(directory, "release")+ if err := os.WriteFile(state, data, 0600); err != nil {+ t.Fatal(err)+ }+ paths, _ := json.Marshal([]string{state, started, release})+ main := filepath.Join(directory, "packages.mjs")+ script := `import {readFile,writeFile,access} from 'node:fs/promises';+const [state,started,release]=` + string(paths) + `;+let text='';for await(const chunk of process.stdin)text+=chunk;const req=JSON.parse(text);+let installed=JSON.parse(await readFile(state,'utf8')),result=installed;+if(req.method==='install'){+ await writeFile(started,'');+ while(true){try{await access(release);break}catch{await new Promise(resolve=>setTimeout(resolve,10))}}+ result={name:req.name,version:'0.1.0',api:'1',present:true,source:req.source};+ installed.push(result);await writeFile(state,JSON.stringify(installed));+}+process.stdout.write(JSON.stringify({result}));`+ if err := os.WriteFile(main, []byte(script), 0600); err != nil {+ t.Fatal(err)+ }+ m, err := NewManager(t.Context(), ManagerConfig{Directory: directory, Runtime: c, PackageMain: main})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = m.Close() })+ s := plugin.RuntimeSettings{Packages: map[string]plugin.RuntimePackage{"fixture": base}, Instances: []plugin.InstanceConfig{{ID: "fixture", Package: "fixture", Enabled: true}}}+ if _, err := m.Apply(t.Context(), s); err != nil {+ t.Fatal(err)+ }+ previous := m.runtime+ s.Packages["extra"] = plugin.RuntimePackage{Source: plugin.Source{Type: "directory", Spec: root}}+ s.Instances = append(s.Instances, plugin.InstanceConfig{ID: "extra", Package: "extra"})+ done := make(chan error, 1)+ go func() { _, err := m.Apply(t.Context(), s); done <- err }()+ defer func() { _ = os.WriteFile(release, nil, 0600) }()+ deadline := time.NewTimer(5 * time.Second)+ defer deadline.Stop()+ tick := time.NewTicker(10 * time.Millisecond)+ defer tick.Stop()+ for {+ if _, err := os.Stat(started); err == nil {+ break+ }+ select {+ case <-deadline.C:+ t.Fatal("package installation did not start")+ case <-tick.C:+ }+ }+ tools, err := m.Tools(t.Context(), "session")+ if err != nil || len(tools) != 1 || tools[0].Spec().Name != "fixture__echo" {+ t.Fatalf("existing tools unavailable during download: %v %v", tools, err)+ }+ if err := os.WriteFile(release, nil, 0600); err != nil {+ t.Fatal(err)+ }+ select {+ case err := <-done:+ if err != nil {+ t.Fatal(err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("package installation did not finish")+ }+ if previous != m.runtime || !previous.Alive() {+ t.Fatal("adding a disabled package restarted unrelated working plugins")+ }+}diff --git a/internal/plugins/manager.go b/internal/plugins/manager.gonew file mode 100644index 0000000..08ebe6c--- /dev/null+++ b/internal/plugins/manager.go@@ -0,0 +1,490 @@+package plugins++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "sort"+ "sync"+ "time"++ "go-bot/harness/agent"+ "go-bot/harness/skills"+ "go-bot/internal/authorization"+ "go-bot/internal/credentials"+ "go-bot/plugin"+)++type ManagerConfig struct {+ Directory string+ Runtime RuntimeConfig+ PackageMain string+ PNPM string+ Changed func()+}+type Status = plugin.Status++// Manager installs packages and applies desired configuration to native Cordis.+// It has no plugin-instance lifecycle state machine or Session ownership.+type Manager struct {+ ctx context.Context+ cancel context.CancelFunc+ config ManagerConfig+ gate chan struct{}+ mu sync.RWMutex+ runtime *hostBridge+ desired plugin.RuntimeSettings+ lastError string+ changes chan struct{}+ surface *authorization.Surface+ ownsCredentials bool+ closeOnce sync.Once+ closeError error+}++func NewManager(ctx context.Context, c ManagerConfig) (*Manager, error) {+ if !filepath.IsAbs(c.Directory) || !filepath.IsAbs(c.Runtime.Main) || !filepath.IsAbs(c.PackageMain) {+ return nil, errors.New("plugin manager paths must be absolute")+ }+ if err := os.MkdirAll(c.Directory, 0700); err != nil {+ return nil, err+ }+ ctx, cancel := context.WithCancel(ctx)+ m := &Manager{ctx: ctx, cancel: cancel, config: c, gate: make(chan struct{}, 1), changes: make(chan struct{}), desired: plugin.RuntimeSettings{}.Clone()}+ if m.config.Runtime.Credentials == nil {+ home := c.Runtime.DSHHome+ if home == "" {+ home = filepath.Dir(c.Directory)+ }+ store, err := credentials.Open(filepath.Join(home, credentials.Filename), credentials.Options{Watch: true})+ if err != nil {+ cancel()+ return nil, err+ }+ m.config.Runtime.Credentials = store+ m.ownsCredentials = true+ }+ if m.config.Runtime.Authorization == nil {+ m.config.Runtime.Authorization = authorization.New(m.config.Runtime.Credentials)+ }+ m.surface = authorization.NewSurface(ctx, m.config.Runtime.Authorization, m.changed)+ return m, nil+}+func (m *Manager) profile() string { return filepath.Join(m.config.Directory, "profile") }+func (m *Manager) packages() Packages {+ return Packages{Directory: m.profile(), Main: m.config.PackageMain, Node: m.config.Runtime.Node, PNPM: m.config.PNPM}+}+func (m *Manager) enter(ctx context.Context) (context.Context, func(), error) {+ select {+ case m.gate <- struct{}{}:+ case <-ctx.Done():+ return nil, nil, ctx.Err()+ case <-m.ctx.Done():+ return nil, nil, m.ctx.Err()+ }+ call, cancel := context.WithCancel(ctx)+ stop := context.AfterFunc(m.ctx, cancel)+ return call, func() { stop(); cancel(); <-m.gate }, nil+}+func (m *Manager) changed() {+ m.mu.Lock()+ close(m.changes)+ m.changes = make(chan struct{})+ m.mu.Unlock()+ if m.config.Changed != nil {+ m.config.Changed()+ }+}+func (m *Manager) Changes() (<-chan struct{}, <-chan struct{}) {+ m.mu.RLock()+ defer m.mu.RUnlock()+ return m.changes, m.ctx.Done()+}+func (m *Manager) redact(message string) string { return m.config.Runtime.Credentials.Redact(message) }+func (m *Manager) report(err error) {+ message := ""+ if err != nil {+ message = m.redact(err.Error())+ }+ m.mu.Lock()+ m.lastError = message+ m.mu.Unlock()+ m.changed()+}+func (m *Manager) packageCredentials(source plugin.Source) (map[string]string, error) {+ out := map[string]string{}+ if source.AuthRef == "" {+ return out, nil+ }+ value, err := m.config.Runtime.Credentials.Resolve(source.AuthRef)+ if err != nil {+ return nil, err+ }+ if value == nil {+ return nil, failure("CREDENTIAL_REQUIRED", "Missing installation credential: "+source.AuthRef)+ }+ out[source.AuthRef] = value.Value+ return out, nil+}+func (m *Manager) InspectPackage(ctx context.Context, name string, source plugin.Source) (plugin.PackageInfo, error) {+ ctx, leave, err := m.enter(ctx)+ if err != nil {+ return plugin.PackageInfo{}, err+ }+ defer leave()+ values, err := m.packageCredentials(source)+ if err != nil {+ return plugin.PackageInfo{}, err+ }+ return m.packages().Inspect(ctx, name, source, values)+}++func (m *Manager) stopRuntime() error {+ m.mu.Lock()+ runtime := m.runtime+ m.runtime = nil+ m.mu.Unlock()+ if runtime != nil {+ return runtime.Close()+ }+ return nil+}+func (m *Manager) Apply(ctx context.Context, settings plugin.RuntimeSettings) (Status, error) {+ if err := settings.Validate(); err != nil {+ return Status{}, err+ }+ ctx, leave, err := m.enter(ctx)+ if err != nil {+ return Status{}, err+ }+ defer leave()+ return m.apply(ctx, settings.Clone(), false, "")+}+func (m *Manager) apply(ctx context.Context, s plugin.RuntimeSettings, restart bool, reinstall string) (status Status, err error) {+ m.mu.Lock()+ m.desired = s.Clone()+ m.mu.Unlock()+ defer func() {+ m.report(err)+ read, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)+ defer cancel()+ status, _ = m.Status(read)+ }()+ if err = os.MkdirAll(m.profile(), 0700); err != nil {+ return+ }+ installed, err := m.packages().List(ctx)+ if err != nil {+ return status, err+ }+ actual := map[string]plugin.PackageInfo{}+ for _, pkg := range installed {+ actual[pkg.Name] = pkg+ }+ // Restore an installed selected release without silently upgrading it just+ // because the market now offers a newer release/source. The source snapshot+ // belongs to the package manager's installed manifest, not Redis user config.+ for name, wanted := range s.Packages {+ if name != reinstall && wanted.Version != "" && actual[name].Present && actual[name].Version == wanted.Version {+ wanted.Source = actual[name].Source+ s.Packages[name] = wanted+ }+ }+ names := make([]string, 0, len(s.Packages))+ for name := range s.Packages {+ names = append(names, name)+ }+ sort.Strings(names)+ missing := []string{}+ for _, name := range names {+ if name == reinstall || !actual[name].Present || actual[name].Source != s.Packages[name].Source || (s.Packages[name].Version != "" && actual[name].Version != s.Packages[name].Version) {+ missing = append(missing, name)+ }+ }+ reloadRuntime := restart+ for _, name := range missing {+ // Existing modules must be reloaded after replacement. A new package+ // must not take every working plugin offline during its installation.+ reloadRuntime = reloadRuntime || actual[name].Present+ var values map[string]string+ values, err = m.packageCredentials(s.Packages[name].Source)+ if err != nil {+ return+ }+ if expected := s.Packages[name].Version; expected != "" {+ var available plugin.PackageInfo+ available, err = m.packages().Inspect(ctx, name, s.Packages[name].Source, values)+ if err != nil {+ return+ }+ if available.Version != expected {+ return status, failure("SELECTED_RELEASE_UNAVAILABLE", name+": selected release is not present; update to the reviewed market release")+ }+ }+ if _, err = m.packages().Install(ctx, name, s.Packages[name].Source, values, s.Packages[name].Builds...); err != nil {+ return+ }+ }+ if reloadRuntime {+ if err = m.stopRuntime(); err != nil {+ return+ }+ }+ actualPackages, metadataErr := m.packages().List(ctx)+ if metadataErr != nil {+ return status, metadataErr+ }+ metadata := map[string]plugin.PackageInfo{}+ for _, info := range actualPackages {+ metadata[info.Name] = info+ }+ for _, row := range s.Instances {+ if !row.Enabled {+ continue+ }+ schema := metadata[row.Package].ConfigSchema+ if len(schema) == 0 {+ continue+ }+ compiled, schemaErr := compileSchema(schema)+ if schemaErr != nil {+ return status, schemaErr+ }+ config := row.Config+ if len(config) == 0 {+ config = json.RawMessage(`{}`)+ }+ if schemaErr = validateSchema(compiled, config); schemaErr != nil {+ return status, failure("INVALID_CONFIG", row.ID+": "+schemaErr.Error())+ }+ }+ enabled := false+ for _, row := range s.Instances {+ enabled = enabled || row.Enabled+ }+ if !enabled {+ err = m.stopRuntime()+ return+ }+ m.mu.RLock()+ runtime := m.runtime+ m.mu.RUnlock()+ if runtime != nil && !runtime.Alive() {+ if err = m.stopRuntime(); err != nil {+ return+ }+ runtime = nil+ }+ if runtime == nil {+ c := m.config.Runtime+ c.ProfileDir = m.profile()+ c.Changed = m.changed+ runtime, err = startHostBridge(m.ctx, c)+ if err != nil {+ return+ }+ m.mu.Lock()+ m.runtime = runtime+ m.mu.Unlock()+ }+ var instances []map[string]any+ instances, err = runtime.Apply(ctx, s.Instances)+ if err == nil {+ for _, row := range instances {+ if row["state"] == "failed" {+ err = errors.Join(err, failure("PLUGIN_LOAD_FAILED", m.redact(row["id"].(string)+": "+stringField(row, "error"))))+ }+ }+ }+ return+}+func stringField(row map[string]any, key string) string { value, _ := row[key].(string); return value }+func (m *Manager) Status(ctx context.Context) (Status, error) {+ m.mu.RLock()+ runtime, last, desired := m.runtime, m.lastError, m.desired.Clone()+ m.mu.RUnlock()+ status := Status{Runtime: "stopped", Packages: []plugin.PackageInfo{}, Instances: []plugin.Instance{}, Error: last}+ if runtime != nil {+ status.Runtime = "running"+ if !runtime.Alive() {+ status.Runtime = "failed"+ status.Error = "Plugin process is unavailable"+ } else {+ var rows []plugin.Instance+ if err := runtime.peer.call(ctx, "runtime.inspect", nil, &rows); err != nil {+ status.Runtime = "failed"+ status.Error = m.redact(err.Error())+ } else {+ status.Instances = rows+ for i := range rows {+ rows[i].Error = m.redact(rows[i].Error)+ }+ }+ }+ } else {+ for _, row := range desired.Instances {+ state := "disabled"+ if row.Enabled {+ state = "unavailable"+ }+ status.Instances = append(status.Instances, plugin.Instance{ID: row.ID, Package: row.Package, State: state})+ }+ }+ installed, err := m.packages().List(ctx)+ if err != nil {+ return status, err+ }+ status.Packages = installed+ found := map[string]bool{}+ for _, row := range installed {+ found[row.Name] = true+ }+ for name, pkg := range desired.Packages {+ if !found[name] {+ status.Packages = append(status.Packages, plugin.PackageInfo{Name: name, Source: pkg.Source})+ }+ }+ sort.Slice(status.Packages, func(i, j int) bool { return status.Packages[i].Name < status.Packages[j].Name })+ return status, nil+}+func (m *Manager) Restart(ctx context.Context) (Status, error) {+ return m.restart(ctx, nil)+}++func (m *Manager) restart(ctx context.Context, settings *plugin.RuntimeSettings) (Status, error) {+ if settings != nil {+ if err := settings.Validate(); err != nil {+ return Status{}, err+ }+ }+ ctx, leave, err := m.enter(ctx)+ if err != nil {+ return Status{}, err+ }+ defer leave()+ m.mu.RLock()+ s := m.desired.Clone()+ m.mu.RUnlock()+ if settings != nil {+ s = settings.Clone()+ }+ return m.apply(ctx, s, true, "")+}+func (m *Manager) Reinstall(ctx context.Context, name string, s plugin.RuntimeSettings) (Status, error) {+ if _, ok := s.Packages[name]; !ok {+ return Status{}, errors.New("package is not configured")+ }+ if err := s.Validate(); err != nil {+ return Status{}, err+ }+ ctx, leave, err := m.enter(ctx)+ if err != nil {+ return Status{}, err+ }+ defer leave()+ return m.apply(ctx, s.Clone(), false, name)+}+func (m *Manager) Remove(ctx context.Context, name string, s plugin.RuntimeSettings) (Status, error) {+ if !plugin.ValidPackageName(name) {+ return Status{}, errors.New("invalid package name")+ }+ if _, ok := s.Packages[name]; ok {+ return Status{}, errors.New("remove package from settings first")+ }+ if err := s.Validate(); err != nil {+ return Status{}, err+ }+ ctx, leave, err := m.enter(ctx)+ if err != nil {+ return Status{}, err+ }+ defer leave()+ // Apply native removal before deleting code. Other instances stay under Cordis.+ if _, err = m.apply(ctx, s.Clone(), false, ""); err != nil {+ return Status{}, err+ }+ if err = m.packages().Remove(ctx, name); err != nil {+ return Status{}, err+ }+ return m.Status(ctx)+}+func (m *Manager) executionRuntime() (*hostBridge, error) {+ m.mu.RLock()+ runtime := m.runtime+ configured := false+ for _, row := range m.desired.Instances {+ configured = configured || row.Enabled+ }+ m.mu.RUnlock()+ if !configured {+ return nil, nil+ }+ if runtime == nil || !runtime.Alive() {+ return nil, nil // No Node dependency for core execution; failed plugins are shown by Status.+ }+ return runtime, nil+}+func (m *Manager) Tools(ctx context.Context, id string) ([]agent.Tool, error) {+ r, err := m.executionRuntime()+ if err != nil || r == nil {+ return nil, err+ }+ return r.Tools(ctx, id)+}+func (m *Manager) Skills(ctx context.Context, lookup skills.Lookup) ([]skills.Provider, error) {+ r, err := m.executionRuntime()+ if err != nil || r == nil {+ return nil, err+ }+ return r.Skills(ctx, lookup)+}+func (m *Manager) AssemblePrompt(ctx context.Context, input agent.PromptAssemblyInput) (agent.PromptAssembly, error) {+ r, err := m.executionRuntime()+ if err != nil {+ return agent.PromptAssembly{}, err+ }+ if r == nil {+ return agent.PromptAssembly{SystemPrompt: input.SystemPrompt, Tools: input.Tools}, nil+ }+ return r.AssemblePrompt(ctx, input)+}+func (m *Manager) ToolInvocations(context.Context, string) (agent.ToolInvocationFactory, error) {+ // A Go-only adapter supplies active-call data. Node is contacted only from a+ // registered plugin's business callback, never for core stage preparation.+ return hostToolInvocation, nil+}++func (m *Manager) Close() error {+ m.closeOnce.Do(func() {+ m.cancel()+ m.gate <- struct{}{}+ defer func() { <-m.gate }()+ m.surface.Close()+ m.closeError = m.stopRuntime()+ if m.ownsCredentials {+ m.closeError = errors.Join(m.closeError, m.config.Runtime.Credentials.Close())+ }+ })+ return m.closeError+}+func writePrivate(path string, data []byte) error {+ file, err := os.CreateTemp(filepath.Dir(path), ".write-*")+ if err != nil {+ return err+ }+ defer os.Remove(file.Name())+ if _, err = file.Write(data); err != nil {+ file.Close()+ return err+ }+ if err = file.Sync(); err != nil {+ file.Close()+ return err+ }+ if err = file.Close(); err != nil {+ return err+ }+ return os.Rename(file.Name(), path)+}diff --git a/internal/plugins/packages.go b/internal/plugins/packages.gonew file mode 100644index 0000000..03ce630--- /dev/null+++ b/internal/plugins/packages.go@@ -0,0 +1,125 @@+package plugins++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "syscall"+ "time"++ "go-bot/plugin"+)++type Packages struct {+ Directory string+ Node string+ Main string+ PNPM string+}++type packageRequest struct {+ Method string `json:"method"`+ Directory string `json:"directory"`+ PNPM string `json:"pnpm,omitempty"`+ Name string `json:"name,omitempty"`+ Builds []string `json:"builds,omitempty"`+ Source plugin.Source `json:"source,omitempty"`+ Credentials map[string]string `json:"credentials,omitempty"`+}++type limitedOutput struct {+ data bytes.Buffer+ overflow bool+}++func (b *limitedOutput) Write(p []byte) (int, error) {+ if b.data.Len()+len(p) > maxFrame {+ b.overflow = true+ return len(p), nil+ }+ return b.data.Write(p)+}++// One bounded subprocess runs package operations without loading business+// modules. The enclosing Host manager serializes mutations and owns activation.+func (p Packages) call(ctx context.Context, request packageRequest, output any) error {+ if !filepath.IsAbs(p.Directory) || !filepath.IsAbs(p.Main) {+ return errors.New("package manager paths must be absolute")+ }+ if err := os.MkdirAll(p.Directory, 0700); err != nil {+ return err+ }+ request.Directory, request.PNPM = p.Directory, p.PNPM+ input, err := json.Marshal(request)+ if err != nil {+ return err+ }+ if len(input) > 4<<20 {+ return errors.New("package request exceeds 4 MiB")+ }+ node := p.Node+ if node == "" {+ node = "node"+ }+ ctx, cancel := context.WithTimeout(ctx, 15*time.Minute)+ defer cancel()+ command := exec.CommandContext(ctx, node, p.Main)+ command.Dir = p.Directory+ command.Env = runtimeEnvironment()+ command.Stdin = bytes.NewReader(input)+ command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}+ command.Cancel = func() error { return syscall.Kill(-command.Process.Pid, syscall.SIGKILL) }+ command.WaitDelay = 3 * time.Second+ var result limitedOutput+ command.Stdout = &result+ // stderr can contain third-party exception data. Only the structured and+ // redacted response on stdout is returned through the public management API.+ err = command.Run()+ if ctx.Err() != nil {+ return ctx.Err()+ }+ if result.overflow {+ return failure("PACKAGE_OUTPUT_LIMIT", "Package manager response exceeds 1 MiB")+ }+ var response struct {+ Result json.RawMessage `json:"result"`+ Error *plugin.Error `json:"error"`+ }+ if json.Unmarshal(result.data.Bytes(), &response) != nil {+ return failure("PACKAGE_RUNTIME_FAILED", "Package manager returned no valid structured response")+ }+ if response.Error != nil {+ return response.Error+ }+ if err != nil {+ return fmt.Errorf("package manager failed: %w", err)+ }+ if output != nil {+ return json.Unmarshal(response.Result, output)+ }+ return nil+}++func (p Packages) Inspect(ctx context.Context, name string, source plugin.Source, credentials map[string]string) (plugin.PackageInfo, error) {+ var result plugin.PackageInfo+ err := p.call(ctx, packageRequest{Method: "inspect", Name: name, Source: source, Credentials: credentials}, &result)+ return result, err+}+func (p Packages) Install(ctx context.Context, name string, source plugin.Source, credentials map[string]string, builds ...string) (plugin.PackageInfo, error) {+ var result plugin.PackageInfo+ err := p.call(ctx, packageRequest{Method: "install", Name: name, Source: source, Credentials: credentials, Builds: builds}, &result)+ return result, err+}+func (p Packages) List(ctx context.Context) ([]plugin.PackageInfo, error) {+ var result []plugin.PackageInfo+ err := p.call(ctx, packageRequest{Method: "list"}, &result)+ return result, err+}+func (p Packages) Remove(ctx context.Context, name string) error {+ return p.call(ctx, packageRequest{Method: "remove", Name: name}, nil)+}diff --git a/internal/plugins/rpc.go b/internal/plugins/rpc.gonew file mode 100644index 0000000..c484ce6--- /dev/null+++ b/internal/plugins/rpc.go@@ -0,0 +1,274 @@+package plugins++import (+ "bufio"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net"+ "strconv"+ "sync"+ "sync/atomic"+ "time"++ "go-bot/plugin"+)++const maxFrame = 1 << 20++var errDisconnected = &plugin.Error{Code: "RUNTIME_DISCONNECTED", Message: "Extension runtime disconnected; an in-flight operation may have an unknown outcome."}++type rpcError struct {+ Code int `json:"code"`+ Message string `json:"message"`+ Data struct {+ Code string `json:"code"`+ Name string `json:"name,omitempty"`+ Classified bool `json:"classified"`+ } `json:"data"`+}++type frame struct {+ JSONRPC string `json:"jsonrpc"`+ ID string `json:"id,omitempty"`+ Method string `json:"method,omitempty"`+ Params json.RawMessage `json:"params,omitempty"`+ Result json.RawMessage `json:"result,omitempty"`+ Error *rpcError `json:"error,omitempty"`+}++type rpcHandler func(context.Context, string, json.RawMessage) (any, error)++// Each incoming request runs independently: a plugin callback may await a Host+// call while that Host call is itself waiting for the Node runtime. Mutations+// serialize in their owner, never by holding this transport's mutex.+type peer struct {+ ctx context.Context+ cancel context.CancelFunc+ conn net.Conn+ handle rpcHandler+ writeMu sync.Mutex+ mu sync.Mutex+ pending map[string]chan frame+ active map[string]context.CancelFunc+ closed chan struct{}+ once sync.Once+ sequence atomic.Uint64+}++func newPeer(conn net.Conn, handle rpcHandler) *peer {+ ctx, cancel := context.WithCancel(context.Background())+ p := &peer{ctx: ctx, cancel: cancel, conn: conn, handle: handle, pending: map[string]chan frame{}, active: map[string]context.CancelFunc{}, closed: make(chan struct{})}+ go p.read()+ return p+}++func (p *peer) call(ctx context.Context, method string, input, output any) error {+ return p.callWithDrain(ctx, method, input, output, false)+}++// Tool stages and owned callbacks must settle after cancellation. Ordinary+// management calls may return promptly; a tool result cannot race ahead of+// cleanup still changing the execution world.+func (p *peer) callDrained(ctx context.Context, method string, input, output any) error {+ return p.callWithDrain(ctx, method, input, output, true)+}++func (p *peer) callWithDrain(ctx context.Context, method string, input, output any, drain bool) error {+ if err := ctx.Err(); err != nil {+ return err+ }+ params, err := json.Marshal(input)+ if err != nil {+ return err+ }+ id := "g" + strconv.FormatUint(p.sequence.Add(1), 10)+ result := make(chan frame, 1)+ p.mu.Lock()+ select {+ case <-p.closed:+ p.mu.Unlock()+ return errDisconnected+ default:+ }+ p.pending[id] = result+ p.mu.Unlock()+ defer func() { p.mu.Lock(); delete(p.pending, id); p.mu.Unlock() }()+ if err := p.send(frame{ID: id, Method: method, Params: params}); err != nil {+ return err+ }+ decode := func(message frame) error {+ if message.Error != nil {+ return &plugin.Error{Code: message.Error.Data.Code, Name: message.Error.Data.Name, Message: message.Error.Message, Unclassified: !message.Error.Data.Classified}+ }+ if output != nil {+ return json.Unmarshal(message.Result, output)+ }+ return nil+ }+ select {+ case message := <-result:+ return decode(message)+ case <-ctx.Done():+ params, _ := json.Marshal(map[string]string{"id": id})+ go func() { _ = p.send(frame{Method: "request.cancel", Params: params}) }()+ if !drain {+ return ctx.Err()+ }+ // The Node owner has a five-second disposal fence. Allow its failure+ // response to arrive before this transport closes the connection.+ timer := time.NewTimer(6 * time.Second)+ defer timer.Stop()+ select {+ case message := <-result:+ return decode(message)+ case <-p.closed:+ return errDisconnected+ case <-timer.C:+ p.close()+ return failure("PLUGIN_DRAIN_TIMEOUT", "Plugin callback did not settle after cancellation")+ }+ case <-p.closed:+ return errDisconnected+ }+}++func (p *peer) send(message frame) error {+ message.JSONRPC = "2.0"+ data, err := json.Marshal(message)+ if err != nil {+ return err+ }+ if len(data)+1 > maxFrame {+ return errors.New("extension RPC frame exceeds 1 MiB")+ }+ p.writeMu.Lock()+ defer p.writeMu.Unlock()+ _ = p.conn.SetWriteDeadline(time.Now().Add(30 * time.Second))+ data = append(data, '\n')+ for len(data) > 0 {+ n, err := p.conn.Write(data)+ if err != nil {+ p.close()+ return errDisconnected+ }+ data = data[n:]+ }+ return nil+}++func (p *peer) read() {+ defer p.close()+ scanner := bufio.NewScanner(p.conn)+ scanner.Buffer(make([]byte, 4096), maxFrame)+ for scanner.Scan() {+ var message frame+ if json.Unmarshal(scanner.Bytes(), &message) != nil || message.JSONRPC != "2.0" {+ return+ }+ if message.Method == "" {+ // A missing result is a malformed response, not a successful void.+ // Void is encoded as result:null; exactly one result/error is required.+ if message.ID == "" || (len(message.Result) > 0) == (message.Error != nil) {+ return+ }+ p.mu.Lock()+ waiting := p.pending[message.ID]+ p.mu.Unlock()+ if waiting != nil {+ select {+ case waiting <- message:+ default:+ }+ }+ continue+ }+ if message.Method == "request.cancel" {+ var params struct {+ ID string `json:"id"`+ }+ if json.Unmarshal(message.Params, ¶ms) == nil {+ p.mu.Lock()+ cancel := p.active[params.ID]+ p.mu.Unlock()+ if cancel != nil {+ cancel()+ }+ }+ continue+ }+ ctx, cancel := context.WithCancel(p.ctx)+ p.mu.Lock()+ if _, duplicate := p.active[message.ID]; duplicate && message.ID != "" {+ p.mu.Unlock()+ cancel()+ return+ }+ if message.ID != "" {+ p.active[message.ID] = cancel+ }+ p.mu.Unlock()+ go p.dispatch(ctx, cancel, message)+ }+}++func (p *peer) dispatch(ctx context.Context, cancel context.CancelFunc, message frame) {+ defer func() { cancel(); p.mu.Lock(); delete(p.active, message.ID); p.mu.Unlock() }()+ result, err := func() (result any, err error) {+ defer func() {+ if value := recover(); value != nil {+ err = fmt.Errorf("Host extension handler panicked: %v", value)+ }+ }()+ if p.handle == nil {+ return nil, &plugin.Error{Code: "METHOD_NOT_FOUND", Message: "Host RPC method is unavailable"}+ }+ return p.handle(ctx, message.Method, message.Params)+ }()+ if message.ID == "" {+ return+ }+ response := frame{ID: message.ID}+ if err == nil {+ response.Result, err = json.Marshal(result)+ }+ if err != nil {+ response.Error = &rpcError{Code: -32000, Message: err.Error()}+ response.Result = nil+ response.Error.Data.Code = "HOST_ERROR"+ var details *plugin.Error+ if errors.As(err, &details) {+ response.Error.Data.Code = details.Code+ response.Error.Data.Name = details.Name+ response.Error.Data.Classified = !details.Unclassified && details.Code != "EXTENSION_ERROR"+ }+ var typed interface{ ToolErrorInfo() (string, string) }+ if errors.As(err, &typed) {+ name, code := typed.ToolErrorInfo()+ if code != "" {+ response.Error.Data.Name = name+ response.Error.Data.Code = code+ response.Error.Data.Classified = true+ }+ }+ }+ if err := p.send(response); err != nil && !errors.Is(err, errDisconnected) {+ fallback := frame{ID: message.ID, Error: &rpcError{Code: -32000, Message: "Host response is not serializable within the RPC size limit"}}+ fallback.Error.Data.Code = "INVALID_RESULT"+ _ = p.send(fallback)+ }+}++func (p *peer) close() {+ p.once.Do(func() {+ close(p.closed)+ p.cancel()+ _ = p.conn.Close()+ p.mu.Lock()+ for _, cancel := range p.active {+ cancel()+ }+ p.mu.Unlock()+ })+}diff --git a/internal/plugins/rpc_test.go b/internal/plugins/rpc_test.gonew file mode 100644index 0000000..fe1af4d--- /dev/null+++ b/internal/plugins/rpc_test.go@@ -0,0 +1,155 @@+package plugins++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net"+ "strings"+ "testing"+ "time"++ "go-bot/internal/mcpclient"+ "go-bot/plugin"+)++func TestRPCOuterCapabilityErrorOwnsClassification(t *testing.T) {+ left, right := net.Pipe()+ host := newPeer(left, func(context.Context, string, json.RawMessage) (any, error) {+ return nil, &mcpclient.Error{Code: "MCP_CONNECTION_FAILED", Message: "outer capability failure", Cause: &plugin.Error{Name: "PluginError", Code: "EXTENSION_CLOSED", Message: "inner failure"}}+ })+ node := newPeer(right, nil)+ t.Cleanup(host.close)+ t.Cleanup(node.close)+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ err := node.call(ctx, "mcp", nil, nil)+ var details *plugin.Error+ if !errors.As(err, &details) || details.Name != "McpError" || details.Code != "MCP_CONNECTION_FAILED" || details.Message != "outer capability failure" || details.Unclassified {+ t.Fatalf("an inner cause replaced the outer capability identity: %v", err)+ }+}++func TestRPCWrappedPluginErrorRetainsIdentity(t *testing.T) {+ left, right := net.Pipe()+ host := newPeer(left, func(context.Context, string, json.RawMessage) (any, error) {+ return nil, fmt.Errorf("loading skill: %w", &plugin.Error{Name: "SkillError", Code: "SKILL_INVALID_DEFINITION", Message: "invalid definition"})+ })+ node := newPeer(right, nil)+ t.Cleanup(host.close)+ t.Cleanup(node.close)+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ err := node.call(ctx, "skill", nil, nil)+ var details *plugin.Error+ if !errors.As(err, &details) || details.Name != "SkillError" || details.Code != "SKILL_INVALID_DEFINITION" || details.Message != "loading skill: invalid definition" {+ t.Fatalf("wrapped plugin error changed across RPC: %v", err)+ }+}++func TestRPCNestedCallbackDoesNotDeadlock(t *testing.T) {+ left, right := net.Pipe()+ var host *peer+ host = newPeer(left, func(ctx context.Context, method string, raw json.RawMessage) (any, error) {+ if method != "outer" {+ return nil, errors.New("unexpected request")+ }+ var answer string+ if err := host.call(ctx, "inner", map[string]int{"n": 42}, &answer); err != nil {+ return nil, err+ }+ return "nested:" + answer, nil+ })+ node := newPeer(right, func(_ context.Context, method string, raw json.RawMessage) (any, error) {+ if method != "inner" {+ return nil, errors.New("unexpected callback")+ }+ return "42", nil+ })+ t.Cleanup(host.close)+ t.Cleanup(node.close)+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer cancel()+ var value string+ if err := node.call(ctx, "outer", nil, &value); err != nil || value != "nested:42" {+ t.Fatalf("callback: value=%q err=%v", value, err)+ }+}++func TestRPCCancellationAndOversizedResult(t *testing.T) {+ left, right := net.Pipe()+ started, settled := make(chan struct{}), make(chan struct{})+ host := newPeer(left, func(ctx context.Context, method string, _ json.RawMessage) (any, error) {+ if method == "oversized" {+ return strings.Repeat("x", maxFrame), nil+ }+ close(started)+ <-ctx.Done()+ close(settled)+ return nil, ctx.Err()+ })+ node := newPeer(right, nil)+ t.Cleanup(host.close)+ t.Cleanup(node.close)+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() { done <- node.call(ctx, "wait", nil, nil) }()+ select {+ case <-started:+ case <-time.After(3 * time.Second):+ t.Fatal("request never started")+ }+ cancel()+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("caller cancellation: %v", err)+ }+ select {+ case <-settled:+ case <-time.After(3 * time.Second):+ t.Fatal("remote call was not cancelled")+ }+ ctx, stop := context.WithTimeout(context.Background(), 3*time.Second)+ defer stop()+ var result any+ err := node.call(ctx, "oversized", nil, &result)+ var info *plugin.Error+ if !errors.As(err, &info) || info.Code != "INVALID_RESULT" {+ t.Fatalf("oversized response hung or was accepted: %v", err)+ }+}++func TestRPCDisconnectSettlesCallAndCancelsHandler(t *testing.T) {+ left, right := net.Pipe()+ started, settled := make(chan struct{}), make(chan struct{})+ host := newPeer(left, func(ctx context.Context, _ string, _ json.RawMessage) (any, error) {+ close(started)+ <-ctx.Done()+ close(settled)+ return nil, ctx.Err()+ })+ node := newPeer(right, nil)+ t.Cleanup(host.close)+ t.Cleanup(node.close)+ done := make(chan error, 1)+ go func() { done <- node.call(context.Background(), "effect", nil, nil) }()+ select {+ case <-started:+ case <-time.After(3 * time.Second):+ t.Fatal("request never started")+ }+ node.close()+ select {+ case err := <-done:+ if !errors.Is(err, errDisconnected) {+ t.Fatalf("disconnect: %v", err)+ }+ case <-time.After(3 * time.Second):+ t.Fatal("pending call leaked")+ }+ select {+ case <-settled:+ case <-time.After(3 * time.Second):+ t.Fatal("handler context leaked")+ }+}diff --git a/internal/plugins/runtime.go b/internal/plugins/runtime.gonew file mode 100644index 0000000..23f0f36--- /dev/null+++ b/internal/plugins/runtime.go@@ -0,0 +1,56 @@+package plugins++import (+ "context"+ "errors"+ "os"++ "go-bot/harness/skills"+ "go-bot/internal/authorization"+ "go-bot/internal/credentials"+ mcpconfig "go-bot/mcp"+ "go-bot/plugin"+)++type MCPManager interface {+ Register(context.Context, string, string, mcpconfig.Server) error+ Release(context.Context, string, string) error+ ListViews() []mcpconfig.ManagedServerView+ Changes() (<-chan struct{}, <-chan struct{})+ Restart(context.Context, string) (mcpconfig.Status, error)+ CancelAuthorizationAttempt(context.Context, string, string) error+ DisconnectAuthorization(context.Context, string) (mcpconfig.Status, error)+ StartAuthorization(context.Context, string) (mcpconfig.OAuthAttemptView, error)+}+type RuntimeConfig struct {+ UserID string+ HostID string+ Node string+ Main string+ ProfileDir string+ Home string+ DSHHome string+ SocketParent string+ ReservedTools []string+ Authorization *authorization.Service+ Credentials *credentials.Store+ MCP MCPManager+ Skills *skills.Registry+ Workspace string+ Log func(string, string)+ Changed func()+}++func runtimeEnvironment() []string {+ var out []string+ for _, name := range []string{"PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS"} {+ if value, ok := os.LookupEnv(name); ok {+ out = append(out, name+"="+value)+ }+ }+ return out+}+func fatalDrain(err error) bool {+ var detail *plugin.Error+ return errors.As(err, &detail) && detail.Code == "PLUGIN_DRAIN_TIMEOUT"+}diff --git a/internal/plugins/runtime_test.go b/internal/plugins/runtime_test.gonew file mode 100644index 0000000..0780694--- /dev/null+++ b/internal/plugins/runtime_test.go@@ -0,0 +1,32 @@+package plugins++import (+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+)++func testRuntimeConfig(t *testing.T) RuntimeConfig {+ t.Helper()+ node, err := exec.LookPath("node")+ if err != nil {+ t.Skip("Node is required for the Cordis integration test")+ }+ version, _ := exec.Command(node, "--version").Output()+ var major, minor int+ _, _ = fmt.Sscanf(string(version), "v%d.%d", &major, &minor)+ if major < 24 || major == 24 && minor < 9 {+ t.Skip("Cordis Loader requires Node >=24.9")+ }+ main, err := filepath.Abs("../../extensions/cordis/src/main.mjs")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(filepath.Dir(main), "../node_modules/@deepseek-ai/cordis/package.json")); err != nil {+ t.Skip("Run pnpm install in extensions/cordis to test the actual Node runtime")+ }+ home := t.TempDir()+ return RuntimeConfig{Node: node, Main: main, ProfileDir: t.TempDir(), Home: home, DSHHome: filepath.Join(home, ".dsh"), ReservedTools: []string{"shellexecute"}}+}diff --git a/internal/plugins/validation.go b/internal/plugins/validation.gonew file mode 100644index 0000000..7e70e36--- /dev/null+++ b/internal/plugins/validation.go@@ -0,0 +1,41 @@+package plugins++import (+ "bytes"+ "encoding/json"+ "fmt"+ "github.com/santhosh-tekuri/jsonschema/v6"+ "go-bot/plugin"+ "regexp"+)++var identifier = regexp.MustCompile(`^[a-zA-Z0-9_.-]{1,128}$`)++func failure(code, message string) error { return &plugin.Error{Code: code, Message: message} }++type denySchemaLoader struct{}++func (denySchemaLoader) Load(url string) (any, error) {+ return nil, fmt.Errorf("external schema references are not supported: %s", url)+}+func compileSchema(raw json.RawMessage) (*jsonschema.Schema, error) {+ value, err := jsonschema.UnmarshalJSON(bytes.NewReader(raw))+ if err != nil {+ return nil, err+ }+ c := jsonschema.NewCompiler()+ c.DefaultDraft(jsonschema.Draft2020)+ c.UseLoader(denySchemaLoader{})+ const url = "https://go-bot.invalid/plugin-schema.json"+ if err := c.AddResource(url, value); err != nil {+ return nil, err+ }+ return c.Compile(url)+}+func validateSchema(schema *jsonschema.Schema, raw json.RawMessage) error {+ value, err := jsonschema.UnmarshalJSON(bytes.NewReader(raw))+ if err != nil {+ return err+ }+ return schema.Validate(value)+}diff --git a/mcp/probe.go b/mcp/probe.gonew file mode 100644index 0000000..8668265--- /dev/null+++ b/mcp/probe.go@@ -0,0 +1,56 @@+package mcpconfig++import "encoding/json"++type ProbeOptions struct {+ TimeoutMS *float64 `json:"timeoutMs,omitempty"`+ MaxPages *int64 `json:"maxPages,omitempty"`+ MaxToolNames *int64 `json:"maxToolNames,omitempty"`+}++type CloseResult struct {+ CloseConfirmed bool `json:"closeConfirmed"`+ CleanupError string `json:"cleanupError,omitempty"`+}++type ProbeServerInfo struct {+ Name string `json:"name"`+ Version string `json:"version"`+}++// ProbeResult preserves the upstream connect/list union and independent+// cleanup result. It never reports Agent execution or persistent activation.+type ProbeResult struct {+ CloseResult+ OK bool `json:"ok"`+ DurationMS int64 `json:"durationMs"`+ ServerInfo *ProbeServerInfo `json:"serverInfo,omitempty"`+ ToolNames []string `json:"toolNames"`+ Truncated bool `json:"truncated"`+ Stage string `json:"stage,omitempty"`+ Message string `json:"message,omitempty"`+}++func (r ProbeResult) MarshalJSON() ([]byte, error) {+ if !r.OK {+ return json.Marshal(struct {+ CloseResult+ OK bool `json:"ok"`+ Stage string `json:"stage"`+ Message string `json:"message"`+ DurationMS int64 `json:"durationMs"`+ }{r.CloseResult, false, r.Stage, r.Message, r.DurationMS})+ }+ names := r.ToolNames+ if names == nil {+ names = []string{}+ }+ return json.Marshal(struct {+ CloseResult+ OK bool `json:"ok"`+ ServerInfo *ProbeServerInfo `json:"serverInfo,omitempty"`+ ToolNames []string `json:"toolNames"`+ Truncated bool `json:"truncated"`+ DurationMS int64 `json:"durationMs"`+ }{r.CloseResult, true, r.ServerInfo, names, r.Truncated, r.DurationMS})+}diff --git a/mcp/runtime_status.go b/mcp/runtime_status.gonew file mode 100644index 0000000..5174d9c--- /dev/null+++ b/mcp/runtime_status.go@@ -0,0 +1,95 @@+package mcpconfig++import (+ "encoding/json"+ "fmt"+)++// ManagedServerStatus is the plugin-facing upstream union. HTTP settings keep+// the separate ServerStatus projection used by this project's own clients.+type ManagedServerStatus struct {+ State string+ Reason string+ LastError string+ Result *CloseResult+ Attempt int+ MaxAttempts int+ ToolCount int+ ConnectedAt int64+ NextRetryAtMS int64+}++func (s ManagedServerStatus) MarshalJSON() ([]byte, error) {+ value := map[string]any{"state": s.State}+ switch s.State {+ case "disabled":+ case "closed":+ if s.Result == nil {+ return nil, fmt.Errorf("closed MCP status requires a cleanup result")+ }+ value["result"] = s.Result+ case "waiting-credentials":+ value["lastError"] = s.LastError+ case "waiting-authorization":+ value["reason"], value["lastError"] = s.Reason, s.LastError+ case "connecting":+ value["attempt"] = s.Attempt+ case "connected":+ value["toolCount"], value["connectedAt"] = s.ToolCount, s.ConnectedAt+ case "reconnecting":+ value["attempt"], value["maxAttempts"], value["nextRetryAtMs"], value["lastError"] = s.Attempt, s.MaxAttempts, s.NextRetryAtMS, s.LastError+ case "failed":+ value["reason"] = s.Reason+ if s.Reason == "cleanup" {+ if s.Result == nil {+ return nil, fmt.Errorf("failed MCP cleanup status requires a cleanup result")+ }+ value["result"] = s.Result+ } else if s.LastError != "" || s.Reason == "load" {+ value["lastError"] = s.LastError+ }+ default:+ return nil, fmt.Errorf("unknown MCP runtime state %q", s.State)+ }+ return json.Marshal(value)+}++func (s *ManagedServerStatus) UnmarshalJSON(data []byte) error {+ var value struct {+ State string `json:"state"`+ Reason string `json:"reason"`+ LastError string `json:"lastError"`+ Result *CloseResult `json:"result"`+ Attempt int `json:"attempt"`+ MaxAttempts int `json:"maxAttempts"`+ ToolCount int `json:"toolCount"`+ ConnectedAt int64 `json:"connectedAt"`+ NextRetryAtMS int64 `json:"nextRetryAtMs"`+ }+ if err := json.Unmarshal(data, &value); err != nil {+ return err+ }+ *s = ManagedServerStatus{State: value.State, Reason: value.Reason, LastError: value.LastError, Result: value.Result, Attempt: value.Attempt, MaxAttempts: value.MaxAttempts, ToolCount: value.ToolCount, ConnectedAt: value.ConnectedAt, NextRetryAtMS: value.NextRetryAtMS}+ return nil+}++type OAuthAttemptView struct {+ ID string `json:"id"`+ Phase string `json:"phase"`+ AuthorizationURL string `json:"authorizationUrl,omitempty"`+ LastError string `json:"lastError,omitempty"`+}++func (a OAuthAuthorization) AttemptView() *OAuthAttemptView {+ if a.ID == "" {+ return nil+ }+ view := &OAuthAttemptView{ID: a.ID, Phase: a.Phase}+ if a.Phase == "waiting-browser" {+ view.AuthorizationURL = a.URL+ }+ if a.Phase == "failed" {+ view.LastError = a.Error+ }+ return view+}diff --git a/mcp/settings.go b/mcp/settings.gonew file mode 100644index 0000000..e7312d9--- /dev/null+++ b/mcp/settings.go@@ -0,0 +1,353 @@+// Package mcpconfig defines the built-in MCP contracts used by Host plugins.+// Connections, OAuth grants and discovered tools belong to the Host.+package mcpconfig++import (+ "encoding/json"+ "errors"+ "fmt"+ "net/url"+ "path/filepath"+ "regexp"+ "sort"+ "strings"++ "go-bot/internal/credentials"+ "golang.org/x/net/http/httpguts"+)++const InternalPath = "/internal/host/mcp"+const RuntimePath = "/v1/host/mcp"+const OAuthCallbackPath = "/v1/mcp/oauth/callback/"++// OAuthCallbackHeader is private Controller-to-Host routing metadata. It must+// be replaced, never relayed from an external client's supplied value.+const OAuthCallbackHeader = "X-Go-Bot-OAuth-Callback"+const ControllerOriginHeader = "X-Go-Bot-Controller-Origin"++type OAuth struct {+ CredentialKey string `json:"credentialKey,omitempty"`+ ClientID string `json:"clientId,omitempty"`+ ClientSecretRef string `json:"clientSecretRef,omitempty"`+ Scopes []string `json:"scopes,omitempty"`+ Scope *string `json:"scope,omitempty"`+ RequestTimeoutMS *int64 `json:"requestTimeoutMs,omitempty"`+ AuthorizationTimeoutMS *int64 `json:"authorizationTimeoutMs,omitempty"`+ // ClientSecret is resolved Host-private input. It never crosses public+ // settings JSON or Redis; plugin RPC delivers it in a separate envelope.+ ClientSecret string `json:"-"`+}++// RequestedScope preserves the upstream distinction between omitted scope+// (use the server challenge) and an explicitly empty scope.+func (o OAuth) RequestedScope() *string {+ if o.Scope != nil {+ return o.Scope+ }+ if o.Scopes != nil {+ value := strings.Join(o.Scopes, " ")+ return &value+ }+ return nil+}++type Server struct {+ Enabled *bool `json:"enabled,omitempty"`+ Transport string `json:"transport"`+ Command string `json:"command,omitempty"`+ Args []string `json:"args,omitempty"`+ Env map[string]string `json:"env,omitempty"`+ CWD string `json:"cwd,omitempty"`+ URL string `json:"url,omitempty"`+ Headers map[string]string `json:"headers,omitempty"`+ ToolLoading string `json:"toolLoading,omitempty"`+ OAuth *OAuth `json:"oauth,omitempty"`+}++type Settings struct {+ Servers map[string]Server `json:"servers"`+ Credentials map[string]string `json:"credentials"`+}++var serverName = regexp.MustCompile(`^[A-Za-z0-9_-]{1,32}$`)+var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)+var credentialReference = regexp.MustCompile(`\$\{credential:([^}]+)\}`)++func ValidServerName(name string) bool { return serverName.MatchString(name) }+func (s Server) IsEnabled() bool { return s.Enabled == nil || *s.Enabled }+func (s Server) Loading() string {+ if s.ToolLoading == "" {+ return "eager"+ }+ return s.ToolLoading+}++func (s Server) Validate() error {+ if s.Loading() != "eager" && s.Loading() != "on-demand" {+ return errors.New("invalid MCP tool loading mode")+ }+ if len(s.Args) > 256 || len(s.Env) > 128 || len(s.Headers) > 64 {+ return errors.New("MCP server configuration exceeds supported limits")+ }+ switch s.Transport {+ case "stdio":+ if s.Command == "" || strings.TrimSpace(s.Command) != s.Command || len(s.Command) > 4096 || strings.ContainsAny(s.Command, "\x00\r\n") || strings.Contains(s.Command, "${credential:") {+ return errors.New("enter a literal MCP executable and separate arguments")+ }+ if s.URL != "" || len(s.Headers) > 0 || s.OAuth != nil {+ return errors.New("stdio cannot configure an HTTP URL, headers or OAuth")+ }+ if s.CWD != "" && (!filepath.IsAbs(s.CWD) || strings.ContainsAny(s.CWD, "\x00\r\n") || strings.Contains(s.CWD, "${credential:")) {+ return errors.New("MCP working directory must be an absolute literal Host path")+ }+ case "streamable-http":+ u, err := url.Parse(s.URL)+ if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.Fragment != "" || len(s.URL) > 4096 || strings.Contains(s.URL, "${credential:") {+ return errors.New("enter an HTTP(S) MCP URL; put credentials in headers")+ }+ if s.Command != "" || len(s.Args) > 0 || len(s.Env) > 0 || s.CWD != "" {+ return errors.New("HTTP MCP servers cannot configure a process")+ }+ default:+ return errors.New("MCP transport must be stdio or streamable-http")+ }+ for _, arg := range s.Args {+ if len(arg) > 16384 || strings.ContainsRune(arg, 0) {+ return errors.New("invalid MCP command argument")+ }+ }+ for key, value := range s.Env {+ if !envName.MatchString(key) || len(value) > 16384 || strings.ContainsRune(value, 0) {+ return errors.New("invalid MCP process environment")+ }+ }+ seen := map[string]bool{}+ for key, value := range s.Headers {+ lower := strings.ToLower(key)+ if !httpguts.ValidHeaderFieldName(key) || !httpguts.ValidHeaderFieldValue(value) || len(value) > 16384 || seen[lower] {+ return errors.New("invalid or duplicate MCP HTTP header")+ }+ seen[lower] = true+ if s.OAuth != nil && lower == "authorization" {+ return errors.New("choose OAuth or an Authorization header, not both")+ }+ }+ if s.OAuth != nil {+ for _, budget := range []*int64{s.OAuth.RequestTimeoutMS, s.OAuth.AuthorizationTimeoutMS} {+ if budget != nil && (*budget < 1 || *budget > 2147483647) {+ return errors.New("invalid MCP OAuth timeout")+ }+ }+ if s.OAuth.Scope != nil && (len(*s.OAuth.Scope) > 16384 || strings.ContainsAny(*s.OAuth.Scope, "\x00\r\n")) {+ return errors.New("invalid MCP OAuth scope")+ }+ if s.OAuth.CredentialKey != "" && !credentials.ValidKey(s.OAuth.CredentialKey) {+ return errors.New("invalid MCP OAuth credential key")+ }+ if len(s.OAuth.ClientSecret) > 16384 || strings.ContainsRune(s.OAuth.ClientSecret, 0) {+ return errors.New("invalid private MCP OAuth client secret")+ }+ if (s.OAuth.ClientSecretRef != "" || s.OAuth.ClientSecret != "") && s.OAuth.ClientID == "" {+ return errors.New("MCP OAuth clientId is required with a client secret")+ }+ if len(s.OAuth.ClientID) > 4096 || strings.ContainsAny(s.OAuth.ClientID, "\x00\r\n") || len(s.OAuth.ClientSecretRef) > 256 || strings.ContainsAny(s.OAuth.ClientSecretRef, "\x00\r\n") || len(s.OAuth.Scopes) > 64 {+ return errors.New("invalid MCP OAuth client configuration")+ }+ for _, scope := range s.OAuth.Scopes {+ if scope == "" || len(scope) > 256 || strings.ContainsAny(scope, "\x00\r\n\t ") {+ return errors.New("invalid MCP OAuth scope")+ }+ }+ }+ for _, value := range s.templateValues() {+ remaining := credentialReference.ReplaceAllString(value, "")+ if strings.Contains(remaining, "${credential:") {+ return errors.New("invalid MCP credential reference template")+ }+ for _, match := range credentialReference.FindAllStringSubmatch(value, -1) {+ if err := validCredential(match[1], ""); err != nil {+ return err+ }+ }+ }+ return nil+}++func (s Server) templateValues() []string {+ values := append([]string(nil), s.Args...)+ for _, value := range s.Env {+ values = append(values, value)+ }+ for _, value := range s.Headers {+ values = append(values, value)+ }+ return values+}++func sensitiveHeader(name string) bool {+ name = strings.ToLower(name)+ return name == "authorization" || name == "proxy-authorization" || name == "cookie" || name == "apikey" || strings.Contains(name, "api-key") || strings.HasSuffix(name, "-token") || strings.HasSuffix(name, "-secret")+}++// SecretValues also covers literal authentication headers accepted by the+// transport. Referenced values remain in the credential table; placeholders+// themselves are configuration, not secrets to hide from an editor.+func (s Server) SecretValues() []string {+ var values []string+ if s.OAuth != nil && s.OAuth.ClientSecret != "" {+ values = append(values, s.OAuth.ClientSecret)+ }+ for name, value := range s.Headers {+ if !sensitiveHeader(name) || value == "" || credentialReference.MatchString(value) {+ continue+ }+ values = append(values, value)+ fields := strings.Fields(value)+ if strings.EqualFold(name, "authorization") && len(fields) == 2 {+ values = append(values, fields[1])+ }+ }+ return values+}++func validCredential(ref, value string) error {+ if ref == "" || len(ref) > 256 || strings.ContainsAny(ref, "\x00\r\n") || len(value) > 16384 || strings.ContainsRune(value, 0) {+ return errors.New("invalid MCP credential reference or value")+ }+ return nil+}++func (s Settings) Validate() error {+ if len(s.Servers) > 64 || len(s.Credentials) > 256 {+ return errors.New("MCP settings exceed supported limits")+ }+ for name, server := range s.Servers {+ if !ValidServerName(name) {+ return errors.New("MCP server names use 1–32 letters, digits, underscores or hyphens")+ }+ if err := server.Validate(); err != nil {+ return fmt.Errorf("MCP server %s: %w", name, err)+ }+ }+ for ref, value := range s.Credentials {+ if err := validCredential(ref, value); err != nil {+ return err+ }+ }+ data, err := json.Marshal(s)+ if err != nil {+ return err+ }+ if len(data) > 768<<10 {+ return errors.New("MCP settings exceed 768 KiB")+ }+ return nil+}++func (s Settings) Clone() Settings {+ data, _ := json.Marshal(s)+ var copy Settings+ _ = json.Unmarshal(data, ©)+ for name, server := range s.Servers {+ if server.OAuth != nil {+ cloned := copy.Servers[name]+ if cloned.OAuth != nil {+ cloned.OAuth.ClientSecret = server.OAuth.ClientSecret+ copy.Servers[name] = cloned+ }+ }+ }+ return copy+}++// Resolve expands only explicit references. Unrelated account credentials do+// not enter the process environment, HTTP headers or a model request.+func (s Settings) Resolve(name string) (Server, []string, error) {+ server, ok := s.Servers[name]+ if !ok {+ return Server{}, nil, errors.New("MCP server not configured")+ }+ if err := server.Validate(); err != nil {+ return Server{}, nil, err+ }+ copy := Settings{Servers: map[string]Server{name: server}}.Clone().Servers[name]+ missing := map[string]bool{}+ expand := func(value string) string {+ return credentialReference.ReplaceAllStringFunc(value, func(token string) string {+ ref := credentialReference.FindStringSubmatch(token)[1]+ value := s.Credentials[ref]+ if value == "" {+ missing[ref] = true+ return token+ }+ return value+ })+ }+ for i, value := range copy.Args {+ copy.Args[i] = expand(value)+ }+ for key, value := range copy.Env {+ copy.Env[key] = expand(value)+ }+ for key, value := range copy.Headers {+ copy.Headers[key] = expand(value)+ }+ if copy.OAuth != nil && copy.OAuth.ClientSecretRef != "" && copy.OAuth.ClientSecret == "" {+ copy.OAuth.ClientSecret = s.Credentials[copy.OAuth.ClientSecretRef]+ if copy.OAuth.ClientSecret == "" {+ missing[copy.OAuth.ClientSecretRef] = true+ }+ }+ var refs []string+ for ref := range missing {+ refs = append(refs, ref)+ }+ sort.Strings(refs)+ if len(refs) == 0 {+ if err := copy.Validate(); err != nil {+ return Server{}, nil, errors.New("resolved MCP configuration is invalid")+ }+ }+ return copy, refs, nil+}++func (s Settings) PublicView() Settings {+ copy := s.Clone()+ if copy.Servers == nil {+ copy.Servers = map[string]Server{}+ }+ if copy.Credentials == nil {+ copy.Credentials = map[string]string{}+ }+ for name, server := range copy.Servers {+ if server.OAuth != nil {+ server.OAuth.ClientSecret = ""+ }+ for key, value := range server.Headers {+ if sensitiveHeader(key) && value != "" && !credentialReference.MatchString(value) {+ server.Headers[key] = "[redacted]"+ }+ }+ copy.Servers[name] = server+ }+ for ref, secret := range copy.Credentials {+ copy.Credentials[ref] = ""+ if secret == "" {+ continue+ }+ for name, server := range copy.Servers {+ for i, value := range server.Args {+ server.Args[i] = strings.ReplaceAll(value, secret, "[redacted]")+ }+ for key, value := range server.Env {+ server.Env[key] = strings.ReplaceAll(value, secret, "[redacted]")+ }+ for key, value := range server.Headers {+ server.Headers[key] = strings.ReplaceAll(value, secret, "[redacted]")+ }+ server.URL = strings.ReplaceAll(server.URL, secret, "[redacted]")+ copy.Servers[name] = server+ }+ }+ return copy+}diff --git a/mcp/settings_test.go b/mcp/settings_test.gonew file mode 100644index 0000000..131e988--- /dev/null+++ b/mcp/settings_test.go@@ -0,0 +1,129 @@+package mcpconfig++import (+ "encoding/json"+ "strings"+ "testing"+)++func TestOriginalOAuthBudgetsAndScopeValidateAndSurviveCloning(t *testing.T) {+ for _, value := range []string{+ `{"scope":"","requestTimeoutMs":1,"authorizationTimeoutMs":2147483647}`,+ `{"scope":"read offline_access"}`,+ `{}`,+ } {+ var oauth OAuth+ if err := json.Unmarshal([]byte(value), &oauth); err != nil {+ t.Fatal(err)+ }+ s := Settings{Servers: map[string]Server{"mail": {Transport: "streamable-http", URL: "https://example.com/mcp", OAuth: &oauth}}}+ if err := s.Validate(); err != nil {+ t.Fatal("upstream options rejected", err)+ }+ cloned := s.Clone().Servers["mail"].OAuth+ if (cloned.Scope == nil) != (oauth.Scope == nil) || (cloned.Scope != nil && *cloned.Scope != *oauth.Scope) {+ t.Fatal("explicit empty scope did not survive cloning")+ }+ }+ for _, value := range []string{+ `{"requestTimeoutMs":0}`, `{"authorizationTimeoutMs":0}`,+ `{"requestTimeoutMs":-1}`, `{"authorizationTimeoutMs":2147483648}`,+ } {+ var oauth OAuth+ _ = json.Unmarshal([]byte(value), &oauth)+ s := Server{Transport: "streamable-http", URL: "https://example.com/mcp", OAuth: &oauth}+ if err := s.Validate(); err == nil {+ t.Fatal("invalid explicit upstream budget accepted", value)+ }+ }+}++func TestMCPConfigChecksTransportCredentialAndOAuthBoundaries(t *testing.T) {+ for _, server := range []Server{+ {Transport: "stdio", Command: "python3", Args: []string{"server.py"}, Env: map[string]string{"KEY": "${credential:service/key}"}},+ {Transport: "streamable-http", URL: "https://example.com/mcp", Headers: map[string]string{"Authorization": "Bearer ${credential:service/key}"}},+ {Transport: "streamable-http", URL: "http://127.0.0.1:8000/mcp", OAuth: &OAuth{ClientID: "client"}},+ } {+ if err := server.Validate(); err != nil {+ t.Fatal(err)+ }+ }+ for _, server := range []Server{+ {Transport: "stdio", Command: "python3", URL: "https://example.com"},+ {Transport: "stdio", Command: "python3", CWD: "relative"},+ {Transport: "stdio", Command: "python3", Env: map[string]string{"BAD=KEY": "value"}},+ {Transport: "streamable-http", URL: "https://[email protected]/mcp"},+ {Transport: "streamable-http", URL: "https://example.com/mcp", Command: "python3"},+ {Transport: "streamable-http", URL: "https://example.com/mcp", Headers: map[string]string{"Authorization": "key", "authorization": "other"}},+ {Transport: "streamable-http", URL: "https://example.com/mcp", Headers: map[string]string{"Authorization": "Bearer key"}, OAuth: &OAuth{}},+ {Transport: "streamable-http", URL: "https://example.com/mcp", Headers: map[string]string{"X-Key": "${credential:unterminated"}},+ } {+ if err := server.Validate(); err == nil {+ t.Fatalf("invalid config accepted: %+v", server)+ }+ }+}++func TestMCPReferencesResolveOnlyExplicitFieldsAndPublicViewNeverReturnsValues(t *testing.T) {+ settings := Settings{Servers: map[string]Server{"knowledge": {Transport: "streamable-http", URL: "https://example.com/mcp", Headers: map[string]string{"Authorization": "Bearer ${credential:service/key}"}}}, Credentials: map[string]string{"service/key": "private-value", "unrelated": "do-not-forward"}}+ if err := settings.Validate(); err != nil {+ t.Fatal(err)+ }+ resolved, missing, err := settings.Resolve("knowledge")+ if err != nil || len(missing) != 0 || resolved.Headers["Authorization"] != "Bearer private-value" {+ t.Fatalf("resolved=%+v missing=%v err=%v", resolved, missing, err)+ }+ data, _ := json.Marshal(resolved)+ if strings.Contains(string(data), "do-not-forward") {+ t.Fatal("unreferenced credential was forwarded")+ }+ public, _ := json.Marshal(settings.PublicView())+ if strings.Contains(string(public), "private-value") || strings.Contains(string(public), "do-not-forward") {+ t.Fatal("public settings exposed a private value")+ }+ delete(settings.Credentials, "service/key")+ _, missing, err = settings.Resolve("knowledge")+ if err != nil || len(missing) != 1 || missing[0] != "service/key" {+ t.Fatalf("missing=%v err=%v", missing, err)+ }+ settings.Credentials["service/key"] = "bad\nheader"+ if _, _, err = settings.Resolve("knowledge"); err == nil {+ t.Fatal("credential expansion permitted an invalid HTTP header")+ }+}++func TestPublicMCPViewMasksLiteralAuthenticationHeadersButPreservesReferences(t *testing.T) {+ settings := Settings{Servers: map[string]Server{"headers": {Transport: "streamable-http", URL: "https://example.com/mcp", Headers: map[string]string{+ "Authorization": "Bearer literal-private-key", "X-API-Key": "another-private-key", "X-Service-Token": "${credential:service/token}", "X-Tenant": "research",+ }}}}+ public := settings.PublicView()+ data, _ := json.Marshal(public)+ if strings.Contains(string(data), "literal-private-key") || strings.Contains(string(data), "another-private-key") {+ t.Fatal("literal authentication header leaked")+ }+ if public.Servers["headers"].Headers["X-Service-Token"] != "${credential:service/token}" || public.Servers["headers"].Headers["X-Tenant"] != "research" {+ t.Fatal("non-secret configuration was hidden")+ }+ if settings.Servers["headers"].Headers["Authorization"] != "Bearer literal-private-key" {+ t.Fatal("public projection modified private input")+ }+}++func TestResolvedOAuthClientSecretRemainsPrivateAcrossClones(t *testing.T) {+ settings := Settings{Servers: map[string]Server{"oauth": {Transport: "streamable-http", URL: "https://example.com/mcp", OAuth: &OAuth{ClientID: "client", ClientSecretRef: "oauth/client"}}}, Credentials: map[string]string{"oauth/client": "private-oauth-secret"}}+ server, missing, err := settings.Resolve("oauth")+ if err != nil || len(missing) != 0 || server.OAuth.ClientSecret != "private-oauth-secret" {+ t.Fatal("client secret reference did not resolve", err)+ }+ private := Settings{Servers: map[string]Server{"oauth": server}}+ if private.Clone().Servers["oauth"].OAuth.ClientSecret != "private-oauth-secret" {+ t.Fatal("Host clone lost private OAuth input")+ }+ data, _ := json.Marshal(private)+ if strings.Contains(string(data), "private-oauth-secret") {+ t.Fatal("private OAuth input entered serializable settings")+ }+ if private.PublicView().Servers["oauth"].OAuth.ClientSecret != "" {+ t.Fatal("public projection retained a private client secret")+ }+}diff --git a/mcp/status.go b/mcp/status.gonew file mode 100644index 0000000..3585396--- /dev/null+++ b/mcp/status.go@@ -0,0 +1,56 @@+package mcpconfig++type ServerStatus struct {+ Name string `json:"name"`+ Source string `json:"source"`+ Owner string `json:"owner,omitempty"`+ State string `json:"state"`+ Error string `json:"error,omitempty"`+ Missing []string `json:"missing,omitempty"`+ ToolCount int `json:"toolCount"`+ Resources bool `json:"resources"`+ ProtocolVersion string `json:"protocolVersion,omitempty"`+ ServerName string `json:"serverName,omitempty"`+ OAuthEnabled bool `json:"oauthEnabled"`+ Authorization *OAuthAuthorization `json:"authorization,omitempty"`+}++type OAuthAuthorization struct {+ ID string `json:"id,omitempty"`+ Phase string `json:"phase,omitempty"`+ Name string `json:"name"`+ URL string `json:"url,omitempty"`+ ExpiresAt int64 `json:"expiresAt,omitempty"`+ State string `json:"state"`+ Error string `json:"error,omitempty"`+}++type OAuthCallback struct {+ State string `json:"state"`+ Code string `json:"code,omitempty"`+ Issuer string `json:"issuer,omitempty"`+ Error string `json:"error,omitempty"`+}++// Receipt acknowledges transport admission; it is not an authorization outcome.+type OAuthCallbackReceipt struct {+ State string `json:"state"`+}++type Status struct {+ Servers []ServerStatus `json:"servers"`+ Error string `json:"error,omitempty"`+}++// ManagedServerView is the plugin-facing list/watch shape. The connection is+// still owned by Go; Node receives only these public status values.+type ManagedServerView struct {+ Name string `json:"name"`+ Configured bool `json:"configured"`+ Status ManagedServerStatus `json:"status"`+ Authorization *OAuthAttemptView `json:"authorization,omitempty"`+}++type View struct {+ Status Status `json:"status"`+}diff --git a/mobile/App.tsx b/mobile/App.tsxindex 822506e..6fe932a 100644--- a/mobile/App.tsx+++ b/mobile/App.tsx@@ -1,6 +1,6 @@import { languages, LocaleProvider, useLocale } from './src/locale'import { useEffect, useRef, useState } from 'react'-import { Animated, Easing, Image, Keyboard, KeyboardAvoidingView, Platform, Pressable, ScrollView, StyleSheet, Text, View, useWindowDimensions } from 'react-native'+import { AppState, Animated, Easing, Image, Keyboard, KeyboardAvoidingView, Platform, Pressable, ScrollView, StyleSheet, Text, View, useWindowDimensions } from 'react-native'import { StatusBar } from 'expo-status-bar'import { File, Paths } from 'expo-file-system'import { SafeAreaProvider, useSafeAreaInsets } from 'react-native-safe-area-context'@@ -8,9 +8,10 @@ import { CalendarDays, Languages, Link2, MessageCircle, UserRound } from 'lucideimport { Controller, normalizeProfile, type Profile } from './src/api'import { Chat } from './src/Chat'import { LanguageSheet } from './src/LanguageSheet'-import { Me } from './src/Me'+import { Me, type Section } from './src/Me'import { Tasks } from './src/Tasks'import { TranscriptCache } from '../frontend/src/chat/transcriptCache'+import { HostConnection } from '../frontend/src/chat/hostConnection'import { accent, Ambient, Button, edge, Field, Hint, ink, logo, muted, Panel, s, useReducedMotion } from './src/ui'const profileFile = new File(Paths.document, 'controller-profile.json')@@ -51,7 +52,6 @@ const tabs = [{ label: '会话', Icon: MessageCircle },{ label: '我的', Icon: UserRound },]-type Section = 'models' | 'web-search' | 'image-generation'export default function App() {return <SafeAreaProvider><StatusBar style="dark" /><LocaleProvider><Main /></LocaleProvider></SafeAreaProvider>@@ -159,6 +159,17 @@ function Workspace({ api, exitAccount }: { api: Controller; exitAccount: () => vconst itemWidth = (barWidth - 12) / 3const duration = reduced ? 0 : 235+ useEffect(() => {+ const connection = new HostConnection(transcriptCache, (cursors, signal, opened, receive) =>+ api.hostStream(cursors, signal, opened, receive))+ if (AppState.currentState !== 'background') connection.start()+ const listener = AppState.addEventListener('change', state => {+ if (state === 'background') connection.stop()+ else if (state === 'active') connection.start()+ })+ return () => { listener.remove(); connection.stop() }+ }, [api, transcriptCache])+useEffect(() => {if (session !== undefined) {saveChat(api.profile.account, session)@@ -194,7 +205,7 @@ function Workspace({ api, exitAccount }: { api: Controller; exitAccount: () => vreturn <KeyboardAvoidingView style={styles.app} behavior={Platform.OS === 'ios' ? 'padding' : undefined}><Animated.View style={{ flex: 1, transform: [{ translateX: offset }] }}>- <View style={tab === 0 ? styles.app : styles.hidden}><Tasks api={api} active={tab === 0} openChat={id => { setSession(id); setExternalChat(old => old + 1); activate(1) }} /></View>+ <View style={tab === 0 ? styles.app : styles.hidden}><Tasks api={api} cache={transcriptCache} active={tab === 0} openChat={id => { setSession(id); setExternalChat(old => old + 1); activate(1) }} /></View><View style={tab === 1 ? styles.app : styles.hidden}><Chat key={externalChat} api={api} cache={transcriptCache} id={session ?? ''} active={tab === 1}resolving={session === undefined} lookupError={lookupError} retryLookup={() => setLookupAttempt(value => value + 1)}selectSession={setSession} onUnavailable={unavailable} openModelSettings={openModelSettings} /></View>diff --git a/mobile/README.md b/mobile/README.mdindex 2559a12..35794d5 100644--- a/mobile/README.md+++ b/mobile/README.md@@ -22,6 +22,10 @@ npm run android在 `android/` 运行 `./gradlew :app:assembleRelease -PreactNativeArchitectures=arm64-v8a` 可生成 ARM64 Release APK。发布时用 Android SDK 的 `zipalign -P 16` 对齐、再用 `apksigner` 签名,最后验证签名和对齐。发布密钥保存在仓库外。+`with-shared-source-inputs` 配置插件会把共用的 `frontend/src` 纳入 Android JavaScript 打包任务的输入,修改共享文案、会话投影或授权交互后,增量 Release 构建也会更新包。Metro 的 React 映射和 TypeScript 路径使用移动端自己的依赖,无需另外安装 Web 的 node_modules。++TypeScript 中的 React 路径只指向类型声明;`experiments.tsconfigPaths=false` 避免 Metro 把声明文件当成运行时代码。运行时通过 `metro.config.js` 解析实际 React。+在连接页填写 Controller 入口地址和账号名。可以连接已有账号,也可以在同一页面创建账号。新账号在「我的 → 模型」设置端点和默认模型后即可发送第一条消息。iOS 模拟器可直接填同机的 `http://127.0.0.1:8080`。## 手机连接diff --git a/mobile/app.json b/mobile/app.jsonindex 4e2371c..b304038 100644--- a/mobile/app.json+++ b/mobile/app.json@@ -4,6 +4,9 @@"slug": "go-bot-mobile","version": "0.0.1","userInterfaceStyle": "light",+ "experiments": {+ "tsconfigPaths": false+ },"platforms": ["ios","android"@@ -26,6 +29,7 @@]},"plugins": [+ "./plugins/with-shared-source-inputs",["expo-build-properties",{@@ -43,7 +47,10 @@"microphonePermission": false}],- ["react-native-share", {}],+ [+ "react-native-share",+ {}+ ],["expo-media-library",{@@ -51,7 +58,8 @@"granularPermissions": []}],- "expo-localization"+ "expo-localization",+ "expo-video"],"icon": "./assets/app-icon.png"}diff --git a/mobile/metro.config.js b/mobile/metro.config.jsindex 6740558..2a72bd7 100644--- a/mobile/metro.config.js+++ b/mobile/metro.config.js@@ -1,6 +1,9 @@const path = require('node:path')const { getDefaultConfig } = require('expo/metro-config')const config = getDefaultConfig(__dirname)-// The transcript projector is also used by the existing web client.+// Share transcript, locale and interaction sources with the existing Web client.config.watchFolders = [...config.watchFolders, path.resolve(__dirname, '../frontend/src')]+// Shared interaction hooks must use this app's React instance. Do not resolve+// a second Web React (or require Web node_modules) when bundling native code.+config.resolver.extraNodeModules = { ...config.resolver.extraNodeModules, react: path.resolve(__dirname, 'node_modules/react') }module.exports = configdiff --git a/mobile/package-lock.json b/mobile/package-lock.jsonindex 1af3e2a..7e6bf24 100644--- a/mobile/package-lock.json+++ b/mobile/package-lock.json@@ -20,6 +20,7 @@"expo-media-library": "~58.0.14","expo-sharing": "~58.0.23","expo-status-bar": "~58.0.5",+ "expo-video": "~58.0.14","js-sha256": "0.11.1","lucide-react-native": "^1.73.0","punycode": "2.3.1",@@ -3221,6 +3222,17 @@"react-native": "*"}},+ "node_modules/expo-video": {+ "version": "58.0.14",+ "resolved": "https://registry.npmjs.org/expo-video/-/expo-video-58.0.14.tgz",+ "integrity": "sha512-PYB85kvyvTN8E40TUOgHTI+nucp9O2aFYf4IULZUE71l0iW+YmXIAcp+ZwsLuMSYtdt5QRPqdpdvbyXWeEZLPw==",+ "license": "MIT",+ "peerDependencies": {+ "expo": "*",+ "react": "*",+ "react-native": "*"+ }+ },"node_modules/expo/node_modules/@expo/cli": {"version": "58.1.20","resolved": "https://registry.npmjs.org/@expo/cli/-/cli-58.1.20.tgz",diff --git a/mobile/package.json b/mobile/package.jsonindex 666da6d..11d0ba1 100644--- a/mobile/package.json+++ b/mobile/package.json@@ -22,6 +22,7 @@"expo-media-library": "~58.0.14","expo-sharing": "~58.0.23","expo-status-bar": "~58.0.5",+ "expo-video": "~58.0.14","js-sha256": "0.11.1","lucide-react-native": "^1.73.0","punycode": "2.3.1",diff --git a/mobile/plugins/with-shared-source-inputs.js b/mobile/plugins/with-shared-source-inputs.jsnew file mode 100644index 0000000..d083e29--- /dev/null+++ b/mobile/plugins/with-shared-source-inputs.js@@ -0,0 +1,19 @@+const { withAppBuildGradle } = require('expo/config-plugins')++// Metro watches the shared projector and interaction hooks, but Gradle's+// default bundle inputs stop at the mobile project root. Keep those external+// sources in the incremental-build fingerprint after every Expo prebuild.+const marker = '// Go Bot shared frontend bundle inputs'+module.exports = config => withAppBuildGradle(config, next => {+ if (!next.modResults.contents.includes(marker)) {+ next.modResults.contents += `+${marker}+tasks.matching { it.name.startsWith("createBundle") && it.name.endsWith("JsAndAssets") }.configureEach {+ inputs.dir(new File(projectRoot, "../frontend/src"))+ .withPropertyName("sharedFrontendSource")+ .withPathSensitivity(org.gradle.api.tasks.PathSensitivity.RELATIVE)+}+`+ }+ return next+})diff --git a/mobile/src/Chat.tsx b/mobile/src/Chat.tsxindex 6210777..a474e74 100644--- a/mobile/src/Chat.tsx+++ b/mobile/src/Chat.tsx@@ -1,12 +1,14 @@import { useLocale } from './locale'import { useEffect, useRef, useState, type ComponentRef } from 'react'import { ActivityIndicator, Alert, Animated, Easing, Image, Keyboard, Pressable, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native'-import { ArrowUp, ChevronDown, FileText, Folder, ImagePlus, Images, ListFilter, MessageCircle, MessageCircleQuestion, Plus, Shield, ShieldAlert, Square, X } from 'lucide-react-native'+import { ArrowUp, ChevronDown, FileText, ImagePlus, Images, ListFilter, MessageCircle, MessageCircleQuestion, Plus, Shield, ShieldAlert, Square, X } from 'lucide-react-native'import { attemptMessage, groupAssistantReplies, messageText, visibleQueue, type Message } from '../../frontend/src/chat/transcript'import type { TranscriptCache } from '../../frontend/src/chat/transcriptCache'import { ApiError, Controller, problem, type ModelSelection, type SessionRow } from './api'import { LibrarySheet, ModelSheet, QuestionSheet } from './ChatSheets'import { FileIcon } from './FileIcon'+import { ChatMenu } from './ChatMenu'+import { PluginSheet } from './extensions/PluginSheet'import { HostFilesSheet } from './HostFilesSheet'import { ImageViewer } from './ImageViewer'import { addAttachments, pickPhotos, readLibrary, type LibraryEntry } from './library'@@ -21,11 +23,14 @@ type Props = {resolving: boolean; lookupError: boolean; retryLookup: () => voidselectSession: (id: string) => void; onUnavailable: (id: string) => void; openModelSettings: () => void}-type Overlay = 'chats' | 'files' | 'model' | 'permission' | 'tools' | 'image' | 'file' | ''+type Overlay = 'plugins' | 'chats' | 'files' | 'model' | 'permission' | 'tools' | 'image' | 'file' | ''export function Chat({ api, cache, id, active, resolving, lookupError, retryLookup, selectSession, onUnavailable, openModelSettings }: Props) {const { t } = useLocale()const [rows, setRows] = useState<SessionRow[]>([])+ const [, updateSummaries] = useState(0)+ useEffect(() => cache.subscribe('@summaries', () => updateSummaries(value => value + 1)), [cache])+async function archiveChat(row: SessionRow, stopActivity = false) {try {await api.archive(row.sessionId, stopActivity)@@ -53,6 +58,15 @@ export function Chat({ api, cache, id, active, resolving, lookupError, retryLookconst [defaultModel, setDefaultModel] = useState('')const [permission, setPermission] = useState<{ id: string; mode: PermissionMode }>()const [overlay, show] = useState<Overlay>('')+ useEffect(() => {+ if (overlay !== 'chats') return+ let timer: ReturnType<typeof setTimeout> | undefined+ const unsubscribe = cache.subscribe('@sessions', () => {+ clearTimeout(timer)+ timer = setTimeout(() => void refreshChats(), 150)+ })+ return () => { unsubscribe(); clearTimeout(timer) }+ }, [cache, overlay, api])const [sending, setSending] = useState(false)const [creating, setCreating] = useState(false)const createInFlight = useRef(false)@@ -88,7 +102,7 @@ export function Chat({ api, cache, id, active, resolving, lookupError, retryLookasync function choose(model: ModelSelection) {if (!id) returnawait api.selectModel(id, model)- if (scopedId.current === id) setSelectedModel(model)+ if (scopedId.current === id) { setSelectedModel(model); if (cache.get(id)?.transcript.activeTurn != null) setNotice('将在下一轮使用此模型。') }}function switchChat(next?: string) {Keyboard.dismiss()@@ -146,14 +160,14 @@ export function Chat({ api, cache, id, active, resolving, lookupError, retryLook<ListFilter size={21} color={ink} strokeWidth={1.75} /></IconButton><View style={{ flex: 1 }} />- <IconButton label={t('文件系统')} onPress={() => { Keyboard.dismiss(); show('files') }}><Folder size={20} color={ink} strokeWidth={1.75} /></IconButton>+ <ChatMenu onFiles={() => show('files')} onPlugins={() => show('plugins')} /></View>{!id ? <View style={styles.emptyChat}><Image source={logo} accessibilityLabel="Go Bot" resizeMode="contain" style={styles.emptyLogo} />{resolving && !lookupError ? <ActivityIndicator color={accent} accessibilityLabel={t('正在读取会话…')} />: <Button label={t('创建新会话')} primary busy={creating} onPress={createChat}><Plus size={18} color="white" /></Button>}{resolving && lookupError && <Button label={t('重新加载')} onPress={retryLookup} />}- {!overlay && !!notice && <View style={styles.createError}><Hint error>{t(notice)}</Hint>+ {!overlay && !!notice && <View style={styles.createError}><Hint error={notice !== '将在下一轮使用此模型。'}>{t(notice)}</Hint>{notice.includes('默认模型') && <Button label={t('打开模型设置')} onPress={openModelSettings} />}</View>}</View> : <Conversation key={id} api={api} cache={cache} id={id} active={active && !overlay} onUnavailable={onUnavailable}@@ -193,7 +207,7 @@ export function Chat({ api, cache, id, active, resolving, lookupError, retryLook</IconButton></View></View>- {!!notice && <View><Hint error>{t(notice)}</Hint>{notice.includes('默认模型') && <Button label={t('打开模型设置')} onPress={openModelSettings} />}</View>}+ {!!notice && <View><Hint error={notice !== '将在下一轮使用此模型。'}>{t(notice)}</Hint>{notice.includes('默认模型') && <Button label={t('打开模型设置')} onPress={openModelSettings} />}</View>}</View>}/>}{overlay === 'permission' && permission?.id === id && <PermissionSheet mode={permission.mode} close={() => show('')}@@ -202,7 +216,10 @@ export function Chat({ api, cache, id, active, resolving, lookupError, retryLook<Button label={t('新会话')} primary disabled={sending} busy={creating} onPress={createChat}><Plus size={20} color="white" /></Button>{rows.map(row => <View key={row.sessionId} style={[s.row, { borderRadius: 13, backgroundColor: row.sessionId === id ? wash : glass, paddingLeft: 11 }]}><Pressable accessibilityRole="button" onPress={() => switchChat(row.sessionId)} disabled={sending || creating} style={[s.row, { flex: 1, minHeight: 44 }]}>- <MessageCircle size={17} color={accent} /><Text style={[s.body, { flex: 1 }]} numberOfLines={2}>{row.title || t('未命名会话')}</Text>+ <MessageCircle size={17} color={accent} /><View style={{ flex: 1, gap: 3 }}>+ <Text style={s.body} numberOfLines={2}>{row.title || t('未命名会话')}</Text>+ {cache.summary(row.sessionId)?.pending && <Text style={[s.caption, { color: '#936433' }]}>{t(cache.summary(row.sessionId)?.pending === 'approval' ? '待审批' : '待回答')}</Text>}+ </View></Pressable><IconButton label={t('归档会话')} disabled={sending} onPress={() => Alert.alert(t('归档此会话?'), t('会话将从列表隐藏。'), [{ text: t('返回'), style: 'cancel' }, { text: t('归档'), style: 'destructive', onPress: () => void archiveChat(row) },@@ -212,9 +229,10 @@ export function Chat({ api, cache, id, active, resolving, lookupError, retryLook{loadingRows && !rows.length && <Hint>{t('正在读取会话…')}</Hint>}{!loadingRows && !rows.length && !listError && <Hint>{t('还没有会话。')}</Hint>}<Hint error>{t(listError)}</Hint>- <Hint error>{t(notice)}</Hint>+ <Hint error={notice !== '将在下一轮使用此模型。'}>{t(notice)}</Hint>{notice.includes('默认模型') && <Button label={t('打开模型设置')} onPress={() => { show(''); openModelSettings() }} />}</SheetScroll></Sheet>}+ {overlay === 'plugins' && <PluginSheet api={api} cache={cache} close={() => show('')} />}{overlay === 'files' && <HostFilesSheet api={api} close={() => show('')} />}{overlay === 'model' && <ModelSheet api={api} choice={selectedModel} choose={choose} close={() => show('')} settingsOpen={openModelSettings} />}{overlay === 'tools' && <Sheet title={t('工具栏')} raised={122} onClose={() => show('')}>{afterClose => <SheetScroll>diff --git a/mobile/src/ChatMenu.tsx b/mobile/src/ChatMenu.tsxnew file mode 100644index 0000000..8241911--- /dev/null+++ b/mobile/src/ChatMenu.tsx@@ -0,0 +1,30 @@+import { useRef, useState, type ComponentRef } from 'react'+import { Keyboard, Modal, Platform, Pressable, StyleSheet, Text, useWindowDimensions, View } from 'react-native'+import { Ellipsis, Folder, Puzzle } from 'lucide-react-native'+import { useLocale } from './locale'+import { edge, IconButton, ink, s } from './ui'++export function ChatMenu({ onFiles, onPlugins }: { onFiles: () => void; onPlugins: () => void }) {+ const { t } = useLocale(), screen = useWindowDimensions(), anchor = useRef<ComponentRef<typeof View>>(null)+ const [position, setPosition] = useState<{ x: number; y: number }>()+ const pending = useRef<(() => void) | undefined>(undefined)+ const finish = () => { const action = pending.current; pending.current = undefined; action?.() }+ const choose = (action: () => void) => { pending.current = action; setPosition(undefined); if (Platform.OS !== 'ios') requestAnimationFrame(finish) }+ return <View ref={anchor} collapsable={false}>+ <IconButton label={t('Workspace menu')} accessibilityState={{ expanded: !!position }} onPress={() => { Keyboard.dismiss(); anchor.current?.measureInWindow((x, y, width, height) => setPosition({ x: Math.max(16, Math.min(x + width - 206, screen.width - 222)), y: Math.max(16, Math.min(y + height + 8, screen.height - 144)) })) }}><Ellipsis size={23} color={ink} strokeWidth={1.75} /></IconButton>+ <Modal visible={!!position} transparent animationType="none" onDismiss={finish} onRequestClose={() => setPosition(undefined)} supportedOrientations={['portrait', 'landscape']}>+ <Pressable accessibilityLabel={t('Close menu')} style={StyleSheet.absoluteFill} onPress={() => setPosition(undefined)} />+ {position && <View accessibilityViewIsModal style={[menu.surface, { top: position.y, left: position.x }]}>+ <Pressable accessibilityRole="button" onPress={() => choose(onFiles)} style={({ pressed }) => [menu.row, pressed && s.pressed]}><Folder size={20} color={ink} strokeWidth={1.7} /><Text style={menu.label}>{t('文件系统')}</Text></Pressable>+ <View style={menu.divider} />+ <Pressable accessibilityRole="button" onPress={() => choose(onPlugins)} style={({ pressed }) => [menu.row, pressed && s.pressed]}><Puzzle size={20} color={ink} strokeWidth={1.7} /><Text style={menu.label}>{t('Plugin market')}</Text></Pressable>+ </View>}+ </Modal>+ </View>+}+const menu = StyleSheet.create({+ surface: { position: 'absolute', width: 206, padding: 7, borderRadius: 19, borderWidth: 1, borderColor: edge, backgroundColor: '#fffdfdfa', boxShadow: '0 10px 36px rgba(33,42,66,0.13)' },+ row: { minHeight: 49, paddingHorizontal: 13, flexDirection: 'row', alignItems: 'center', gap: 13, borderRadius: 12 },+ label: { color: ink, fontSize: 15, fontWeight: '500' },+ divider: { height: StyleSheet.hairlineWidth, backgroundColor: edge, marginHorizontal: 12 },+})diff --git a/mobile/src/ChatSheets.tsx b/mobile/src/ChatSheets.tsxindex 8850de3..92bd4d8 100644--- a/mobile/src/ChatSheets.tsx+++ b/mobile/src/ChatSheets.tsx@@ -1,3 +1,4 @@+import { modelProtocol, protocolNames } from '../../frontend/src/settings/modelProtocol'import { useLocale } from './locale'import { useEffect, useState } from 'react'import { Alert, Image, Pressable, StyleSheet, Text, View } from 'react-native'@@ -22,7 +23,7 @@ export function ModelSheet({ api, choice, close, choose, settingsOpen }: {return <Sheet title={t('选择模型')} onClose={close}>{afterClose => <SheetScroll>{data && !Object.keys(data.endpoints).length && <Hint>{t('请先添加端点并设置默认模型。')}</Hint>}{Object.entries(data?.endpoints ?? {}).map(([endpointId, endpoint]) => <View key={endpointId} style={{ gap: 6 }}>- <Text style={s.caption}>{endpoint.name}</Text>+ <Text style={s.caption}>{endpoint.name} · {protocolNames[modelProtocol(endpoint.protocol)]}</Text>{endpoint.models.map(modelId => {const active = endpointId === selected.endpointId && modelId === selected.modelIdreturn <Pressable key={modelId} accessibilityRole="button" accessibilityState={{ selected: active }} disabled={busy} onPress={async () => {@@ -144,12 +145,12 @@ export function QuestionSheet({ pending, close, submit, cancel }: {catch (e) { setError(problem(e, '无法提交,请重试。')) }finally { setBusy(false) }}- return <Sheet title={t('助手需要你的确认')} onClose={close} raised={64}><SheetScroll>+ return <Sheet title={t(pending.questions.some(question => question.id === 'plan-review') ? '审阅方案' : '助手需要你的确认')} onClose={close} raised={64}><SheetScroll>{pending.questions.map(question => {const a = answers[question.id] ?? { id: question.id, selected: [] }return <View key={question.id} style={{ gap: 8 }}>{!!question.header && <Text style={s.caption}>{question.header}</Text>}- <Text style={[s.body, { fontWeight: '600' }]}>{question.question}</Text>+ <Text style={[s.body, { fontWeight: '600' }]}>{t(question.question)}</Text><Hint>{question.detail}</Hint>{question.options?.map(option => {const active = a.selected.includes(option.label)@@ -163,7 +164,7 @@ export function QuestionSheet({ pending, close, submit, cancel }: {{active && (question.multiSelect ? <Check size={12} color={accent} strokeWidth={2.4} />: <View style={{ width: 9, height: 9, borderRadius: 5, backgroundColor: accent }} />)}</View>- <View style={{ flex: 1 }}><Text style={{ color: ink, fontSize: 15 }}>{option.label}</Text><Hint>{option.description}</Hint></View>+ <View style={{ flex: 1 }}><Text style={{ color: ink, fontSize: 15 }}>{t(option.label)}</Text><Hint>{t(option.description ?? '')}</Hint></View></Pressable>})}<Field label={t(question.options?.length ? '其他答案' : '你的回答')} multiline style={{ minHeight: 54 }} value={a.custom ?? ''} onChangeText={custom =>diff --git a/mobile/src/Me.tsx b/mobile/src/Me.tsxindex 36daa40..5ab9075 100644--- a/mobile/src/Me.tsx+++ b/mobile/src/Me.tsx@@ -1,3 +1,5 @@+import { ProtocolDropdown } from './ProtocolDropdown'+import { changeProtocolURL, modelProtocol, modelRequestURL, protocolNames, protocolURLs, type ModelProtocol } from '../../frontend/src/settings/modelProtocol'import { languages, useLocale } from './locale'import { useEffect, useState } from 'react'import { ActivityIndicator, Alert, Image, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'@@ -8,7 +10,7 @@ import { LanguageSheet } from './LanguageSheet'import { accent, Button, Field, Hint, IconButton, edge, glass, ink, muted, Panel, s, Sheet, SheetScroll, wash } from './ui'const providerLabels = { 'web-search': '网页搜索', 'image-generation': '图片生成' }-type Section = 'models' | ProviderPage+export type Section = 'models' | ProviderPageexport function Me({ api, section, open, close, exitAccount }: {api: Controller; section: Section | null; open: (section: Section) => void; close: () => void; exitAccount: () => void@@ -20,6 +22,7 @@ export function Me({ api, section, open, close, exitAccount }: {const [languageOpen, setLanguageOpen] = useState(false)const [serverOpen, setServerOpen] = useState(false)const [stopping, setStopping] = useState(false)+ const [modelDirty, setModelDirty] = useState(false)const [error, setError] = useState('')async function changeAvatar(camera: boolean) {setError('')@@ -93,17 +96,22 @@ export function Me({ api, section, open, close, exitAccount }: {<Button label={t('从图库选择')} onPress={() => afterClose(() => changeAvatar(false))}><Images size={19} color={accent} /></Button><Button label={t('拍照')} onPress={() => afterClose(() => changeAvatar(true))}><Camera size={19} color={accent} /></Button></SheetScroll>}</Sheet>}- {section === 'models' && <Sheet title={t('模型')} onClose={close}><Models api={api} /></Sheet>}+ {section === 'models' && <Sheet title={t('模型')} onClose={() => { setModelDirty(false); close() }} beforeDismiss={proceed => {+ if (!modelDirty) { proceed(); return }+ Alert.alert(t('放弃未保存的修改?'), undefined, [{ text: t('取消'), style: 'cancel' }, { text: t('放弃修改'), style: 'destructive', onPress: proceed }])+ }}><Models api={api} onDirtyChange={setModelDirty} /></Sheet>}{section && section !== 'models' && <Sheet title={t(providerLabels[section])} onClose={close}><Providers key={section} api={api} page={section} /></Sheet>}+</>}-function Models({ api }: { api: Controller }) {+function Models({ api, onDirtyChange }: { api: Controller; onDirtyChange: (dirty: boolean) => void }) {const { t } = useLocale()const [settings, setSettings] = useState<ModelSettings>()const [editing, setEditing] = useState<string | null>(null)const [name, setName] = useState('')const [baseUrl, setURL] = useState('')+ const [protocol, setProtocol] = useState<ModelProtocol>('responses')const [models, setModels] = useState('')const [apiKey, setKey] = useState('')const [busy, setBusy] = useState(false)@@ -115,7 +123,8 @@ function Models({ api }: { api: Controller }) {const endpoint = settings?.endpoints[id]setEditing(id)setName(endpoint?.name ?? '')- setURL(endpoint?.baseUrl ?? '')+ setProtocol(modelProtocol(endpoint?.protocol))+ setURL(endpoint?.baseUrl ?? protocolURLs.responses)setModels(endpoint?.models.join('\n') ?? '')setKey('')setError('')@@ -128,24 +137,33 @@ function Models({ api }: { api: Controller }) {finally { setBusy(false) }}const list = models.split(/[\n,]/).map(model => model.trim()).filter(Boolean)+ useEffect(() => {+ const initial = editing === null ? undefined : settings?.endpoints[editing]+ onDirtyChange(editing !== null && (name !== (initial?.name ?? '') || baseUrl !== (initial?.baseUrl ?? protocolURLs.responses) || protocol !== modelProtocol(initial?.protocol) || apiKey !== '' || models !== (initial?.models.join('\n') ?? '')))+ }, [editing, settings, name, baseUrl, protocol, apiKey, models, onDirtyChange])+return <SheetScroll>- <Hint>{t('支持 OpenAI 兼容的 Responses 接口。默认端点列表中的第一个模型用于新会话。')}</Hint>+ <Hint>{t('支持 OpenAI Responses 和 Anthropic Messages 兼容接口。默认端点的第一个模型用于新会话。')}</Hint>{Object.entries(settings?.endpoints ?? {}).map(([id, endpoint]) => <Pressable key={id} accessibilityRole="button" onPress={() => edit(id)}><Panel style={{ backgroundColor: id === editing ? wash : glass }}><View style={s.row}><Text style={[s.body, { flex: 1, fontWeight: '600' }]}>{endpoint.name}</Text>{settings?.defaultEndpointId === id && <Text style={s.caption}>{t('默认')}</Text>}<ChevronRight size={16} color={muted} /></View>- <Hint>{endpoint.models.join(' · ')}</Hint>+ <Hint>{protocolNames[modelProtocol(endpoint.protocol)]} · {endpoint.models.join(' · ')}</Hint></Panel></Pressable>)}{editing === null ? <Button label={t('添加端点')} onPress={() => edit('')} /> : <><Field label={t('名称')} value={name} onChangeText={setName} />- <Field label={t('端点地址')} keyboardType="url" autoCorrect={false} placeholder="https://api.example.com/v1" value={baseUrl} onChangeText={setURL} />+ <ProtocolDropdown value={protocol} disabled={busy} onChange={next => { setURL(changeProtocolURL(baseUrl, protocol, next)); setProtocol(next) }} />+ <Hint>{t('按服务商提供的接口格式选择,与模型名称无关。')}</Hint>+ <Field label={t('端点地址')} keyboardType="url" autoCorrect={false} placeholder={protocolURLs[protocol]} value={baseUrl} onChangeText={setURL} />+ <Hint>{t('请求地址')}: {modelRequestURL(baseUrl, protocol)}</Hint><Field label="API key" autoCorrect={false} secureTextEntry value={apiKey} onChangeText={setKey}placeholder={settings?.endpoints[editing]?.hasApiKey ? t('已保存,留空保留当前密钥') : t('输入 API key')} /><Field label={t('模型名(每行一个)')} autoCorrect={false} multiline value={models} onChangeText={setModels} />- <Button primary label={t('保存端点')} busy={busy} disabled={!name.trim() || !baseUrl.trim() || !list.length}- onPress={() => update(() => api.saveEndpoint(editing || undefined, { name: name.trim(), baseUrl: baseUrl.trim(), models: list, ...(apiKey.trim() && { apiKey: apiKey.trim() }) }))} />+ <Button primary label={t('保存端点')} busy={busy} disabled={!name.trim() || !baseUrl.trim() || !list.length || (!apiKey.trim() && !settings?.endpoints[editing]?.hasApiKey)}+ onPress={() => update(() => api.saveEndpoint(editing || undefined, { protocol, name: name.trim(), baseUrl: baseUrl.trim(), models: list, ...(apiKey.trim() && { apiKey: apiKey.trim() }) }))} />+ <Button label={t('取消')} disabled={busy} onPress={() => setEditing(null)} />{!!editing && settings?.defaultEndpointId !== editing && <Button label={t('设为默认端点')} disabled={busy} onPress={() => update(() => api.setDefaultEndpoint(editing))} />}{!!editing && <Button label={t('删除端点')} dangerTone disabled={busy} onPress={() => Alert.alert(t('删除端点?'), name, [{ text: t('返回'), style: 'cancel' }, { text: t('删除'), style: 'destructive', onPress: () => update(() => api.removeEndpoint(editing)) }])} />}</>}diff --git a/mobile/src/ProtocolDropdown.tsx b/mobile/src/ProtocolDropdown.tsxnew file mode 100644index 0000000..a46196f--- /dev/null+++ b/mobile/src/ProtocolDropdown.tsx@@ -0,0 +1,36 @@+import { useRef, useState, type ComponentRef } from 'react'+import { Keyboard, Modal, Pressable, StyleSheet, Text, useWindowDimensions, View } from 'react-native'+import { Check, ChevronDown } from 'lucide-react-native'+import { type ModelProtocol, protocolNames } from '../../frontend/src/settings/modelProtocol'+import { useLocale } from './locale'+import { accent, edge, ink, muted, s } from './ui'++export function ProtocolDropdown({ value, onChange, disabled }: { value: ModelProtocol; onChange: (value: ModelProtocol) => void; disabled?: boolean }) {+ const { t } = useLocale()+ const anchor = useRef<ComponentRef<typeof View>>(null)+ const [position, setPosition] = useState<{ x: number; y: number; width: number }>()+ const screen = useWindowDimensions()+ function open() {+ Keyboard.dismiss()+ anchor.current?.measureInWindow((x, y, width, height) => setPosition({ x, y: Math.min(y + height + 6, screen.height - 155), width }))+ }+ return <View style={s.fieldWrap}>+ <Text style={s.caption}>{t('接口协议')}</Text>+ <View ref={anchor} collapsable={false}>+ <Pressable accessibilityRole="combobox" accessibilityLabel={t('接口协议')} accessibilityValue={{ text: protocolNames[value] }} accessibilityState={{ expanded: !!position, disabled }} disabled={disabled} onPress={open}+ style={[s.field, { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }]}>+ <Text style={s.body}>{protocolNames[value]}</Text><ChevronDown size={16} color={muted} />+ </Pressable>+ </View>+ <Modal visible={!!position} transparent animationType="fade" onRequestClose={() => setPosition(undefined)} supportedOrientations={['portrait', 'landscape']}>+ <Pressable accessibilityLabel={t('收起')} style={StyleSheet.absoluteFill} onPress={() => setPosition(undefined)} />+ {position && <View style={{ position: 'absolute', left: Math.max(12, Math.min(position.x, screen.width - position.width - 12)), top: position.y, width: position.width,+ padding: 6, backgroundColor: '#fffdfd', borderRadius: 14, borderWidth: 1, borderColor: edge, boxShadow: '0 8px 24px rgba(29,34,49,0.12)' }}>+ {(Object.keys(protocolNames) as ModelProtocol[]).map(protocol => <Pressable key={protocol} accessibilityRole="menuitem" accessibilityState={{ selected: protocol === value }}+ onPress={() => { onChange(protocol); setPosition(undefined) }} style={{ minHeight: 48, paddingHorizontal: 12, borderRadius: 9, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', backgroundColor: protocol === value ? '#f0edf8' : 'transparent' }}>+ <Text style={[s.body, { color: ink }]}>{protocolNames[protocol]}</Text>{protocol === value && <Check size={16} color={accent} />}+ </Pressable>)}+ </View>}+ </Modal>+ </View>+}diff --git a/mobile/src/Tasks.tsx b/mobile/src/Tasks.tsxindex e68ed5b..346aae5 100644--- a/mobile/src/Tasks.tsx+++ b/mobile/src/Tasks.tsx@@ -3,6 +3,7 @@ import { Alert, Pressable, RefreshControl, ScrollView, StyleSheet, Text, View }import { CalendarDays, ChartNoAxesColumnIncreasing, ChevronRight, Clock3, FileText, FolderOpen, MessageSquare, Plus, Send, type LucideIcon } from 'lucide-react-native'import { Controller, problem, type Schedule, type ScheduleState } from './api'import { useLocale, type Language } from './locale'+import type { TranscriptCache } from '../../frontend/src/chat/transcriptCache'import { ScheduleEditor, WeekdayLabels, scheduleError, targetLabels, timingLabels } from './ScheduleEditor'import { accent, Button, Hint, IconButton, ink, muted, Panel, s, SectionTitle, Sheet, SheetScroll, TintIcon } from './ui'@@ -63,7 +64,7 @@ function taskIcon(kind: Schedule['record']['kind']) {}}-export function Tasks({ api, active, openChat }: { api: Controller; active: boolean; openChat: (id: string) => void }) {+export function Tasks({ api, cache, active, openChat }: { api: Controller; cache: TranscriptCache; active: boolean; openChat: (id: string) => void }) {const { t, language } = useLocale()const [tasks, setTasks] = useState<Schedule[]>([])const [tab, setTab] = useState<TaskTab>('upcoming')@@ -92,29 +93,21 @@ export function Tasks({ api, active, openChat }: { api: Controller; active: booluseEffect(() => {if (!active) return- const controller = new AbortController()- let reconnect: ReturnType<typeof setTimeout> | undefinedlet coalesce: ReturnType<typeof setTimeout> | undefinedconst changed = () => {clearTimeout(coalesce)coalesce = setTimeout(() => void refresh(), 100)}- const listen = () => {- void api.scheduleChanges(controller.signal, changed).catch(() => {}).finally(() => {- if (!controller.signal.aborted) reconnect = setTimeout(() => { void refresh(); listen() }, 5000)- })- }+ const unsubscribe = cache.subscribe('@schedule', changed)void refresh()- listen()const timer = setInterval(() => setClock(Date.now()), 1000)return () => {++requestID.current- controller.abort()+ unsubscribe()clearInterval(timer)- clearTimeout(reconnect)clearTimeout(coalesce)}- }, [api, active])+ }, [api, active, cache])const selected = screen?.mode === 'detail' ? screen.id : ''const task = tasks.find(item => item.record.id === selected)diff --git a/mobile/src/api.ts b/mobile/src/api.tsindex cfbec96..1267755 100644--- a/mobile/src/api.ts+++ b/mobile/src/api.ts@@ -53,6 +53,9 @@ export function normalizeProfile(profile: Profile): Profile {export function problem(error: unknown, fallback = '操作未完成,请重试。') {if (error instanceof ApiError) {+ if (error.code === 'invalid_model_protocol') return '请选择支持的接口协议。'+ if (error.code === 'model_base_url_required') return '请填写基础地址,不包含 /messages、/responses 或 /chat/completions。'+ if (error.code === 'api_key_required_for_new_origin') return '新地址需要重新填写 API key。'if (error.code === 'model_default_required') return '请先在「我的 → 模型」设置默认模型。'if (error.code === 'model_unavailable' || error.code === 'model_unconfigured') return '请为当前会话选择可用模型。'if (error.code === 'settings_saved_host_apply_failed') return '设置已保存,但 Host 暂未应用。可重试或重新连接。'@@ -73,11 +76,12 @@ const scheduleURL = (id: string) => schedulePath + '/' + part(id)export class Controller {constructor(readonly profile: Profile) {}- get headers() { return { 'X-User-ID': this.profile.account } }+ get headers() { return { 'X-User-ID': this.profile.account, 'X-Go-Bot-Controller-Origin': new URL(this.profile.server).origin } }async response(path: string, init?: RequestInit, timeout?: number) {const headers = new Headers(init?.headers)headers.set('X-User-ID', this.profile.account)+ headers.set('X-Go-Bot-Controller-Origin', new URL(this.profile.server).origin)const deadline = timeout && !init?.signal ? new AbortController() : undefinedconst timer = deadline ? setTimeout(() => deadline.abort(), timeout) : undefinedconst response = await fetch(this.profile.server + path, {@@ -141,8 +145,8 @@ export class Controller {transcript(id: string, before: number | null, signal?: AbortSignal) {return this.request<TranscriptPage>(session(id) + '/transcript?limit=20' + (before === null ? '' : '&before=' + before), { signal })}- async stream(id: string, after: number | null, signal: AbortSignal, onOpen: () => void, onEvent: (type: string, data: unknown) => void) {- const response = await this.response(session(id) + '/stream?view=chat' + (after === null ? '' : '&after=' + after),+ async hostStream(cursors: Record<string, number | null>, signal: AbortSignal, onOpen: () => void, onEvent: (type: string, data: unknown) => void) {+ const response = await this.response('/v1/host/stream?cursors=' + part(JSON.stringify(cursors)),{ headers: { Accept: 'text/event-stream' }, signal })if (!response.body) throw new Error('服务器没有返回事件流。')const reader = response.body.getReader()@@ -214,23 +218,6 @@ export class Controller {}deleteEndedSchedules() { return this.request<{ deleted: number }>(schedulePath + '/ended', { method: 'DELETE' }) }runSchedule(id: string) { return this.request<Schedule>(scheduleURL(id) + '/run', { method: 'POST' }) }- async scheduleChanges(signal: AbortSignal, onChange: () => void) {- const response = await this.response(schedulePath + '/stream', { headers: { Accept: 'text/event-stream' }, signal })- if (!response.body) return- const reader = response.body.getReader()- const decoder = new TextDecoder()- const parser = createParser({ onEvent: event => { if (event.event === 'schedule/changed') onChange() } })- try {- for (;;) {- const { value, done } = await reader.read()- if (done) break- parser.feed(decoder.decode(value, { stream: true }))- }- } finally {- await reader.cancel().catch(() => {})- reader.releaseLock()- }- }fileURL(id: string, ref: FileRef, name?: string) {return this.profile.server + session(id) + (ref.source === 'presented'diff --git a/mobile/src/extensions/Authorizations.tsx b/mobile/src/extensions/Authorizations.tsxnew file mode 100644index 0000000..3eebf01--- /dev/null+++ b/mobile/src/extensions/Authorizations.tsx@@ -0,0 +1,98 @@+import { useEffect, useMemo, useState } from 'react'+import { ActivityIndicator, AppState, Linking, Pressable, StyleSheet, Text, View } from 'react-native'+import { Check, ExternalLink, KeyRound } from 'lucide-react-native'+import type { AuthorizationEntry, AuthorizationPrompt, MCPServer } from '../../../frontend/src/api/extensions'+import { authorizationLabel, authorizationURL, useAuthorization } from '../../../frontend/src/extensions/useAuthorization'+import { useLocale } from '../locale'+import { accent, Button, edge, Field, Hint, ink, muted, Panel, s } from '../ui'+import { authorizationAPI, mcpAuthorizationAPI } from './api'+import { useMCPAuthorization } from '../../../frontend/src/extensions/useMCPAuthorization'+import { connectionLabel, connectionTitle, mcpAuthorizationLabel, mcpAuthorizationRunning } from '../../../frontend/src/extensions/connections'+import { Choice } from './Choice'+import { Feedback, TextAction, Toolbar, type ScreenProps, x } from './shared'++export function usePluginAuthorizations({ api, cache }: Pick<ScreenProps, 'api' | 'cache'>, instanceIds: string[]) {+ const transport = useMemo(() => authorizationAPI(api), [api]), mcpAPI = useMemo(() => mcpAuthorizationAPI(api), [api])+ const state = useAuthorization(transport, cache), mcp = useMCPAuthorization(mcpAPI, cache, instanceIds)+ const entries = state.entries.filter(entry => instanceIds.some(id => entry.key.startsWith(id + '/')))+ const scope = instanceIds.join('\0')+ useEffect(() => { state.close(); mcp.close() }, [scope])+ const busy = state.busy || mcp.busy, reload = () => { state.reload(); mcp.reload() }+ useEffect(() => { const listener = AppState.addEventListener('change', value => { if (value === 'active') { state.reload(); mcp.reload() } }); return () => listener.remove() }, [state.reload, mcp.reload])+ return { state, mcp, entries, busy, reload }+}+export function Authorizations({ connections, onBusyChange, onBack }: Pick<ScreenProps, 'onBusyChange'> & { connections: ReturnType<typeof usePluginAuthorizations>; onBack: () => void }) {+ const { state, mcp, entries, busy, reload } = connections, { t } = useLocale(), attempt = state.attempt+ useEffect(() => { onBusyChange(busy); return () => onBusyChange(false) }, [busy, onBusyChange])+ return <>+ <Toolbar title={attempt ? attempt.label : mcp.selected ? connectionTitle(mcp.selected) : 'Accounts and authorization'} busy={busy} onBack={() => { if (attempt) state.close(); else if (mcp.attempt) mcp.close(); else onBack() }} onRefresh={reload} />+ {attempt ? <>+ <View style={a.status}><KeyRound size={19} color={muted} strokeWidth={1.6} /><Text style={s.meta}>{t(authorizationLabel[attempt.status])}</Text></View>+ {attempt.notices.map((notice, index) => <Panel key={index} style={a.panel}>+ <Text selectable style={a.message}>{t(notice.message)}</Text>+ {attempt.status === 'running' && notice.code && <Text selectable style={a.code}>{notice.code}</Text>}+ {attempt.status === 'running' && authorizationURL(notice.url) && <Pressable accessibilityRole="link" onPress={() => { void Linking.openURL(authorizationURL(notice.url)!).catch(() => {}) }} style={a.link}><Text style={a.linkText}>{t('Continue in browser')}</Text><ExternalLink size={15} color={accent} /></Pressable>}+ </Panel>)}+ {attempt.prompts.map(prompt => <Question key={prompt.id} prompt={prompt} busy={state.busy} onAnswer={(answer, decline) => { void state.answer(prompt.id, answer, decline) }} />)}+ {attempt.status === 'running' && !attempt.prompts.length && <View style={a.status}><ActivityIndicator color={accent} size="small" /><Text style={[s.meta, { flex: 1 }]}>{t('Waiting for authorization to finish…')}</Text></View>}+ {attempt.status === 'authorized' && <View style={a.status}><Check size={20} color="#397863" /><Text style={[s.body, { color: '#397863', flex: 1 }]}>{t('Authorization is ready.')}</Text></View>}+ <Hint error>{attempt.error ? t(attempt.error) : undefined}</Hint><Button label={t(attempt.status === 'running' ? 'Cancel authorization' : 'Done')} disabled={state.busy} onPress={() => { if (attempt.status === 'running') void state.cancel(); else state.close() }} />+ {attempt.status === 'running' && <Hint>{t('Closing this panel keeps the authorization running. You can return to it from this plugin.')}</Hint>}+ </> : mcp.attempt && mcp.selected ? <MCPDetails state={mcp} /> : <>+ <Hint>{t('Connect accounts using the authorization methods provided by your plugins.')}</Hint>+ {entries.map(entry => <Account key={entry.key} entry={entry} onDisconnect={() => { void state.disconnect(entry.key) }} busy={busy} onCancel={() => { void state.cancelKey(entry.key) }} onStart={method => { if (entry.inFlight && entry.attemptId) void state.open(entry.attemptId); else void state.start(entry.key, method) }} onView={() => { if (entry.attemptId) void state.open(entry.attemptId) }} />)}+ {mcp.servers.map(server => <MCPAccount key={server.name} server={server} busy={busy} onStart={() => { void mcp.open(server) }} onView={() => mcp.resume(server)} />)}+ {!entries.length && !mcp.servers.length && <Hint>{t('No account authorization methods are available.')}</Hint>}+ </>}+ <Feedback error={attempt ? state.error : mcp.attempt ? mcp.error : state.error || mcp.error} notice="" />+ </>+}+function Account({ entry, busy, onStart, onCancel, onView, onDisconnect }: { entry: AuthorizationEntry; busy: boolean; onStart: (method: string) => void; onCancel: () => void; onView: () => void; onDisconnect: () => void }) {+ const { t } = useLocale(), [method, setMethod] = useState(entry.methods[0]?.id ?? '')+ return <Panel style={a.panel}><View style={a.status}><KeyRound size={19} color={muted} strokeWidth={1.6} /><View style={x.identity}><Text style={x.heading}>{entry.label}</Text><Text style={s.meta}>{t(entry.inFlight ? 'Authorization in progress' : entry.configured ? 'Connected' : 'Not configured')}{entry.accountLabel ? ' · ' + entry.accountLabel : ''}</Text></View></View>+ {entry.methods.length > 1 && <Choice label="Authorization method" value={method} options={entry.methods.map(method => ({ value: method.id, label: t(method.label) }))} disabled={busy || entry.inFlight} onChange={setMethod} />}+ <TextAction label={entry.inFlight ? 'Continue authorization' : entry.configured ? 'Authorize again' : entry.methods.length === 1 ? entry.methods[0].label : 'Authorize'} disabled={busy} onPress={() => onStart(method)} />+ {entry.configured && entry.canDisconnect && !entry.inFlight && <TextAction label="Disconnect account" disabled={busy} onPress={onDisconnect} />}+ {entry.inFlight && <TextAction label="Cancel authorization" disabled={busy} onPress={onCancel} />}+ {!entry.inFlight && entry.attemptId && <TextAction label="View last result" disabled={busy} onPress={onView} />}+ </Panel>+}+function MCPAccount({ server, busy, onStart, onView }: { server: MCPServer; busy: boolean; onStart: () => void; onView: () => void }) {+ const { t } = useLocale(), active = mcpAuthorizationRunning(server.authorization)+ return <Panel style={a.panel}><View style={a.status}><KeyRound size={19} color={muted} strokeWidth={1.6} /><View style={x.identity}><Text style={x.heading}>{connectionTitle(server)}</Text><Text style={s.meta}>{t(connectionLabel(server))}</Text></View></View><TextAction label={active ? 'Continue authorization' : 'Connect in browser'} disabled={busy} onPress={onStart} />{!active && server.authorization?.id && <TextAction label="View last result" disabled={busy} onPress={onView} />}</Panel>+}+function MCPDetails({ state }: { state: ReturnType<typeof useMCPAuthorization> }) {+ const { t } = useLocale(), attempt = state.attempt!, server = state.selected!, active = mcpAuthorizationRunning(attempt), url = authorizationURL(attempt.url)+ return <><View style={a.status}><KeyRound size={19} color={muted} /><Text style={s.meta}>{t(mcpAuthorizationLabel(attempt))}</Text></View>+ {active && url && <Panel style={a.panel}><Text style={a.message}>{t('Authorize access on the service website, then return here.')}</Text><Pressable accessibilityRole="link" style={a.link} onPress={() => { void Linking.openURL(url).catch(() => {}) }}><Text style={a.linkText}>{t('Continue in browser')}</Text><ExternalLink size={15} color={accent} /></Pressable></Panel>}+ {active && <View style={a.status}><ActivityIndicator size="small" color={accent} /><Text style={[s.meta, { flex: 1 }]}>{t('Waiting for authorization to finish…')}</Text></View>}+ {attempt.phase === 'authorized' && <View style={a.status}><Check size={20} color="#397863" /><Text style={[s.body, { flex: 1 }]}>{t('Authorization is ready.')}</Text></View>}+ <Hint error>{attempt.error || server.error}</Hint><Button label={t(active ? 'Cancel authorization' : 'Done')} disabled={state.busy} onPress={() => { if (active) void state.cancel(); else state.close() }} />+ {active && <Hint>{t('Closing this panel keeps the authorization running. You can return to it from this plugin.')}</Hint>}+ </>+}+function Question({ prompt, busy, onAnswer }: { prompt: AuthorizationPrompt; busy: boolean; onAnswer: (answer?: string, decline?: boolean) => void }) {+ const { t } = useLocale(), [answer, setAnswer] = useState('')+ return <Panel style={a.panel}>+ {prompt.kind === 'select' ? <>+ <Text style={a.question}>{t(prompt.message)}</Text>+ {prompt.options.map(option => <Pressable key={option.id} accessibilityRole="radio" accessibilityState={{ checked: answer === option.id, disabled: busy }} disabled={busy} onPress={() => setAnswer(option.id)} style={({ pressed }) => [a.option, answer === option.id && a.selected, pressed && s.pressed]}>+ <View style={[a.radio, answer === option.id && { borderColor: accent }]}>{answer === option.id && <View style={a.dot} />}</View><View style={{ flex: 1, gap: 5 }}><Text style={s.body}>{t(option.label)}</Text>{option.description && <Text style={s.meta}>{t(option.description)}</Text>}</View>+ </Pressable>)}+ </> : <Field label={t(prompt.message)} value={answer} onChangeText={setAnswer} placeholder={prompt.placeholder} editable={!busy} secureTextEntry={prompt.kind === 'secret'} autoCapitalize="none" autoCorrect={false} maxLength={16384} />}+ <Button primary label={t('Continue')} busy={busy} disabled={prompt.kind === 'select' && !answer} onPress={() => { onAnswer(answer); setAnswer('') }} />+ <TextAction label="Not now" disabled={busy} onPress={() => onAnswer(undefined, true)} />+ </Panel>+}+const a = StyleSheet.create({+ panel: { paddingVertical: 22, gap: 17 },+ status: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 5 },+ message: { color: ink, fontSize: 15, lineHeight: 23 },+ code: { color: ink, fontFamily: 'monospace', fontSize: 19, letterSpacing: 1.2, borderWidth: 1, borderColor: edge, borderRadius: 12, padding: 14, backgroundColor: '#ffffffa6', alignSelf: 'flex-start' },+ link: { flexDirection: 'row', alignItems: 'center', gap: 8, minHeight: 44 }, linkText: { color: accent, fontSize: 14 },+ question: { color: ink, fontSize: 15, fontWeight: '500', lineHeight: 23 },+ option: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 15, paddingVertical: 17, borderRadius: 13, borderWidth: 1, borderColor: edge, backgroundColor: '#ffffffa0' },+ selected: { borderColor: '#b8b4d1', backgroundColor: '#f2f0fa' },+ radio: { width: 19, height: 19, borderWidth: 1, borderColor: '#bec3d0', borderRadius: 10, justifyContent: 'center', alignItems: 'center' },+ dot: { width: 9, height: 9, borderRadius: 5, backgroundColor: accent },+})diff --git a/mobile/src/extensions/Choice.tsx b/mobile/src/extensions/Choice.tsxnew file mode 100644index 0000000..2ae97cc--- /dev/null+++ b/mobile/src/extensions/Choice.tsx@@ -0,0 +1,25 @@+import { useRef, useState, type ComponentRef } from 'react'+import { Keyboard, Modal, Pressable, ScrollView, StyleSheet, Text, useWindowDimensions, View } from 'react-native'+import { Check, ChevronDown } from 'lucide-react-native'+import { useLocale } from '../locale'+import { accent, edge, ink, muted, s } from '../ui'++export function Choice<T extends string>({ label, value, options, onChange, disabled }: { label: string; value: T; options: readonly { value: T; label: string }[]; onChange: (value: T) => void; disabled?: boolean }) {+ const { t } = useLocale()+ const anchor = useRef<ComponentRef<typeof View>>(null), screen = useWindowDimensions()+ const [position, setPosition] = useState<{ x: number; y: number; width: number }>()+ const menuHeight = Math.min(screen.height * .55, options.length * 49 + 12)+ const selected = options.find(row => row.value === value)+ return <View style={s.fieldWrap}><Text style={s.caption}>{t(label)}</Text><View ref={anchor} collapsable={false}>+ <Pressable accessibilityRole="combobox" accessibilityLabel={t(label)} accessibilityValue={{ text: t(selected?.label ?? value) }} accessibilityState={{ expanded: !!position, disabled }} disabled={disabled} onPress={() => {+ Keyboard.dismiss(); anchor.current?.measureInWindow((x, y, width, height) => setPosition({ x, y: Math.max(12, Math.min(y + height + 6, screen.height - menuHeight - 26)), width }))+ }} style={[s.field, s.row, { justifyContent: 'space-between' }, disabled && s.disabled]}><Text numberOfLines={1} style={[s.body, { flex: 1 }]}>{t(selected?.label ?? value)}</Text><ChevronDown size={16} color={muted} /></Pressable>+ </View><Modal visible={!!position} transparent animationType="fade" onRequestClose={() => setPosition(undefined)} supportedOrientations={['portrait', 'landscape']}>+ <Pressable accessibilityLabel={t('收起')} style={StyleSheet.absoluteFill} onPress={() => setPosition(undefined)} />+ {position && <View accessibilityViewIsModal style={{ position: 'absolute', left: Math.max(12, Math.min(position.x, screen.width - position.width - 12)), top: position.y, width: Math.min(position.width, screen.width - 24), padding: 6, borderRadius: 15, borderWidth: 1, borderColor: edge, backgroundColor: '#fffdfd', boxShadow: '0 8px 24px rgba(29,34,49,0.12)' }}>+ <ScrollView style={{ maxHeight: menuHeight }} keyboardShouldPersistTaps="handled">{options.map(option => <Pressable key={option.value} accessibilityRole="menuitem" accessibilityState={{ selected: option.value === value }} onPress={() => { onChange(option.value); setPosition(undefined) }} style={({ pressed }) => [{ minHeight: 48, paddingHorizontal: 11, borderRadius: 9, flexDirection: 'row', gap: 8, alignItems: 'center', justifyContent: 'space-between', backgroundColor: option.value === value ? '#f0edf8' : 'transparent' }, pressed && s.pressed]}>+ <Text style={[s.meta, { color: ink, flexShrink: 1 }]}>{t(option.label)}</Text>{option.value === value && <Check size={16} color={accent} />}+ </Pressable>)}</ScrollView>+ </View>}+ </Modal></View>+}diff --git a/mobile/src/extensions/PluginIcon.tsx b/mobile/src/extensions/PluginIcon.tsxnew file mode 100644index 0000000..22c9c33--- /dev/null+++ b/mobile/src/extensions/PluginIcon.tsx@@ -0,0 +1,8 @@+import { Image, StyleSheet, View } from 'react-native'+import { Puzzle } from 'lucide-react-native'+import type { Controller } from '../api'+export function PluginIcon({ api, icon, large = false }: { api: Controller; icon?: string; large?: boolean }) {+ const size = large ? 64 : 48+ return <View accessible={false} style={[styles.mark,{width:size,height:size,borderRadius:large ? 18 : 14}]}>{icon ? <Image source={{uri:new URL(icon,api.profile.server).toString()}} style={{width:size,height:size}} /> : <Puzzle size={large ? 30 : 24} strokeWidth={1.65} color="#74809a" />}</View>+}+const styles = StyleSheet.create({mark:{alignItems:'center',justifyContent:'center',overflow:'hidden',backgroundColor:'#fff',borderWidth:1,borderColor:'#25334a12'}})diff --git a/mobile/src/extensions/PluginSheet.tsx b/mobile/src/extensions/PluginSheet.tsxnew file mode 100644index 0000000..43b9501--- /dev/null+++ b/mobile/src/extensions/PluginSheet.tsx@@ -0,0 +1,17 @@+import { useState } from 'react'+import { Alert } from 'react-native'+import type { TranscriptCache } from '../../../frontend/src/chat/transcriptCache'+import type { Controller } from '../api'+import { useLocale } from '../locale'+import { Sheet } from '../ui'+import { Plugins } from './Plugins'++export function PluginSheet({ api, cache, close }: { api: Controller; cache: TranscriptCache; close: () => void }) {+ const { t } = useLocale(), [dirty, setDirty] = useState(false)+ return <Sheet title={t('Plugin market')} onClose={close} beforeDismiss={proceed => {+ if (!dirty) { proceed(); return }+ Alert.alert(t('放弃未保存的修改?'), undefined, [{ text: t('取消'), style: 'cancel' }, { text: t('放弃修改'), style: 'destructive', onPress: proceed }])+ }}><Plugins api={api} cache={cache} onDirtyChange={setDirty} onBusyChange={ignoreBusy} /></Sheet>+}++function ignoreBusy(_busy: boolean) {}diff --git a/mobile/src/extensions/PluginTutorial.tsx b/mobile/src/extensions/PluginTutorial.tsxnew file mode 100644index 0000000..a8d4aad--- /dev/null+++ b/mobile/src/extensions/PluginTutorial.tsx@@ -0,0 +1,24 @@+import {useState} from 'react'+import {Image,Pressable,Text,View} from 'react-native'+import {PlayCircle} from 'lucide-react-native'+import {useVideoPlayer,VideoView} from 'expo-video'+import {useEvent} from 'expo'+import type {PluginTutorial as Tutorial} from '../../../frontend/src/api/extensions'+import {selectTutorial} from '../../../frontend/src/extensions/catalog'+import type {Controller} from '../api'+import {useLocale} from '../locale'+import {Hint,s} from '../ui'+export function PluginTutorial({api,tutorials}:{api:Controller;tutorials?:Tutorial[]}){+ const {language,t}=useLocale(),tutorial=selectTutorial(tutorials,language),[playing,setPlaying]=useState(false)+ if(!tutorial)return null+ const uri=new URL(tutorial.video,api.profile.server).href+ return <View style={{gap:12,marginVertical:10}}><Text style={[s.body,{fontWeight:'600'}]}>{t('Video guide')}</Text><Text style={s.hint}>{tutorial.title}</Text>+ {playing ? <Player key={uri} uri={uri} /> : <Pressable accessibilityRole="button" accessibilityLabel={t('Play video guide')} onPress={()=>setPlaying(true)} style={{aspectRatio:16/9,backgroundColor:'#e9edf3',borderRadius:18,overflow:'hidden',justifyContent:'center',alignItems:'center'}}>+ {tutorial.poster && <Image source={{uri:new URL(tutorial.poster,api.profile.server).href}} style={{position:'absolute',width:'100%',height:'100%'}} resizeMode="contain" />}<View style={{position:'absolute',inset:0,backgroundColor:'#15202f45'}} /><PlayCircle size={42} color="#fff" strokeWidth={1.5} /><Text style={[s.meta,{color:'#fff',marginTop:8}]}>{t('Play video guide')}</Text>+ </Pressable>}+ </View>+}+function Player({uri}:{uri:string}){+ const {t}=useLocale(),player=useVideoPlayer(uri,player=>player.play()),{status}=useEvent(player,'statusChange',{status:player.status})+ return <View style={{gap:10}}><VideoView player={player} surfaceType="textureView" nativeControls fullscreenOptions={{enable:true}} contentFit="contain" style={{width:'100%',aspectRatio:16/9,borderRadius:18,backgroundColor:'#182131'}} />{status==='error'&&<Hint error>{t('Could not load this video. Try again.')}</Hint>}</View>+}diff --git a/mobile/src/extensions/Plugins.tsx b/mobile/src/extensions/Plugins.tsxnew file mode 100644index 0000000..eead3fc--- /dev/null+++ b/mobile/src/extensions/Plugins.tsx@@ -0,0 +1,83 @@+import { useState } from 'react'+import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native'+import { ChevronRight, KeyRound, MoreHorizontal, Plus, Puzzle, RefreshCw, Trash2 } from 'lucide-react-native'+import { useLocale } from '../locale'+import { accent, Button, edge, Hint, IconButton, ink, muted, Panel, s, Sheet, SheetScroll } from '../ui'+import { installPackage, loadPlugins, removePackage, restartPlugins, setPluginEnabled, updatePackage } from './api'+import { confirmChange, Empty, Fact, Feedback, Fold, Loading, State, TextAction, Toggle, Toolbar, useManagement, x, type ScreenProps } from './shared'+import { Authorizations, usePluginAuthorizations } from './Authorizations'+import { localize } from '../../../frontend/src/extensions/catalog'+import Markdown from 'react-native-markdown-display'+import { Linking } from 'react-native'+import { PluginTutorial } from './PluginTutorial'+import { PluginIcon } from './PluginIcon'++export function Plugins(props: ScreenProps) {+ const { api } = props, { t, language } = useLocale(), m = useManagement(props, loadPlugins)+ const [tab, setTab] = useState<'market' | 'installed'>('market'), [selected, setSelected] = useState<string>(), [authorization, setAuthorization] = useState(false), [menu, setMenu] = useState<string>()+ const selectedBusy = !!selected && m.busy.endsWith(':' + selected)+ const busyName = m.view?.catalog.find(row => m.busy.endsWith(':' + row.package))?.name+ const view = m.view, info = view?.status.packages.find(pkg => pkg.name === selected), saved = selected ? view?.settings.packages[selected] : undefined+ const entry = view?.catalog.find(item => item.package === selected), actual = view?.status.instances.find(row => row.package === selected)+ const connections = usePluginAuthorizations(props, actual?.state === 'ready' && saved?.enabled ? [actual.id] : [])+ const names = Object.keys(view?.settings.packages ?? {}).sort(), title = entry ? entry.name : info?.title || selected || ''+ const install = async (name: string) => {+ const release = view?.catalog.find(row => row.package === name)+ if (release) await m.run('install:' + name, () => installPackage(api, release.pluginId), 'Plugin and dependencies installed. Enable it to use its capabilities.')+ }+ return <>+ <SheetScroll key={authorization ? 'authorization' : selected ?? tab}>+ {authorization ? <Authorizations connections={connections} onBusyChange={props.onBusyChange} onBack={() => setAuthorization(false)} />+ : selected && view ? <>+ <Toolbar title="Plugin details" onBack={() => { setSelected(undefined); setTab('market') }}>{saved && <IconButton label={t('More options')} disabled={!!m.busy} onPress={() => setMenu(selected)}><MoreHorizontal size={20} color={muted} /></IconButton>}</Toolbar>+ <View style={market.detailHead}><PluginIcon api={api} icon={entry?.icon} large /><View style={{flex:1,gap:8}}><Text style={market.detailTitle}>{title}</Text><Text style={s.hint}>{entry ? localize(entry.description, language).split('\n')[0] : info?.description}</Text></View></View>+ {entry && localize(entry.description,language).includes('\n') && <Panel style={{paddingVertical:16}}><Fold label="Connection setup"><Markdown style={{body:{fontSize:14,lineHeight:23,color:muted},link:{color:accent},paragraph:{marginTop:10,marginBottom:6}}} onLinkPress={url=>{if(/^https?:\/\//i.test(url))void Linking.openURL(url).catch(()=>{});return false}}>{localize(entry.description,language).split('\n').slice(1).join('\n').trim()}</Markdown></Fold></Panel>}+ {entry && <PluginTutorial api={api} tutorials={entry.tutorials} />}+ <Feedback error={m.error} notice={m.notice} />+ {m.busy && <View style={s.row}><ActivityIndicator size="small" color={accent} /><Text style={s.meta}>{busyName ? busyName + ' · ' : ''}{t(m.busy.startsWith('install:') ? 'Installing…' : 'Applying plugin changes…')}</Text></View>}+ {info?.availableVersion && entry && <Panel><View style={s.row}><View style={{flex:1,gap:6}}><Text style={s.caption}>{t('Update available')}</Text><Text style={s.meta}>{info.version} → {info.availableVersion}</Text></View><Button label={t('Update plugin')} busy={!!m.busy} onPress={() => { void m.run('install:' + selected, () => updatePackage(api, selected, entry.pluginId)) }} /></View></Panel>}+ {!saved ? <Button primary busy={selectedBusy} disabled={!!m.busy} label={t('Install plugin')} onPress={() => { void install(selected) }}><Plus size={18} color="#fff" /></Button> : <Panel style={{paddingVertical:20}}><View style={[s.row,{justifyContent:'space-between'}]}><Text style={s.meta}>{t('Plugin status')}</Text>{!selectedBusy && <State value={actual?.state ?? (saved.enabled ? 'unavailable' : 'disabled')} />}</View><Toggle label="Enable plugin" checked={saved.enabled} disabled={!!m.busy} onChange={enabled => { void m.run('settings:' + selected, () => setPluginEnabled(api, selected, enabled)) }} />{!selectedBusy && <Hint error>{actual?.error || view.status.error}</Hint>}</Panel>}+ {entry && <>+ <View style={{gap:15,paddingVertical:8}}><Fact label="Version" value={info?.present ? info.version : entry.version} /><Fact label="Maintainer" value={entry.maintainer} /><Fact label="License" value={entry.license} /></View>++ </>}+ {(connections.entries.length > 0 || connections.mcp.servers.length > 0) && <Button label={t('Accounts and authorization')} disabled={!!m.busy || view.status.runtime !== 'running'} onPress={() => setAuthorization(true)}><KeyRound size={18} color={accent} /></Button>}+ {(connections.entries.length > 0 || connections.mcp.servers.length > 0) && <Hint error>{t(connections.state.error || connections.mcp.error)}</Hint>}+ </> : <>+ <View style={s.row}><Text style={[s.hint,{flex:1}]}>{t('Extend your agent with plugins reviewed for this project.')}</Text><IconButton label={t('Refresh extensions')} onPress={m.reload}><RefreshCw size={18} color={muted} /></IconButton></View>+ <View style={market.tabs}>{(['market','installed'] as const).map(value => <Pressable key={value} accessibilityRole="tab" accessibilityState={{selected:tab === value}} onPress={() => setTab(value)} style={[market.tab,tab === value && market.selected]}><Text style={[market.label,tab === value && market.selectedLabel]}>{t(value === 'market' ? 'Plugin market' : 'Installed')}{value === 'installed' ? ` · ${names.length}` : ''}</Text></Pressable>)}</View>+ <Feedback error={m.error} notice={m.notice} />+ {m.busy && <View style={s.row}><ActivityIndicator size="small" color={accent} /><Text style={[s.hint,{flex:1}]}>{busyName ? busyName + ' · ' : ''}{t('Plugin changes continue while you use other features.')}</Text></View>}+ {!view && m.loading && <Loading />}+ {view && <>+ {!(tab === 'market' ? view.catalog.length : names.length) && <Empty title={tab === 'market' ? 'More capabilities are on the way' : 'No plugins installed'} text="Your built-in agent works without plugins. Add packages when you need more capabilities."><Puzzle size={30} color={muted} strokeWidth={1.4} /></Empty>}+ <View style={{gap:8}}>{(tab === 'market' ? view.catalog.map(entry => entry.package) : names).map(name => {+ const release = view.catalog.find(row => row.package === name), saved = view.settings.packages[name], state = view.status.instances.find(row => row.package === name)+ const label = release ? release.name : view.status.packages.find(pkg => pkg.name === name)?.title || name+ return <View key={name} style={market.tile}>+ <Pressable accessibilityRole="button" accessibilityLabel={label} onPress={() => setSelected(name)} style={({pressed}) => [market.tileMain,pressed && s.pressed]}><PluginIcon api={api} icon={release?.icon} /><View style={{flex:1,gap:7}}><Text style={market.title}>{label}</Text><Text numberOfLines={2} style={market.summary}>{release ? localize(release.description,language).split('\n')[0] : name}</Text>{view.status.packages.find(row => row.name === name)?.availableVersion && <Text style={market.update}>{t('Update available')}</Text>}{tab === 'installed' && <State value={state?.state ?? (saved?.enabled ? 'unavailable' : 'disabled')} />}</View></Pressable>+ {m.busy === 'install:' + name ? <ActivityIndicator style={{width:44}} color={accent} /> : <IconButton label={t(saved ? 'More options' : 'Install plugin') + ': ' + label} disabled={!!m.busy} onPress={() => { if (saved) setMenu(name); else void install(name) }}>{saved ? <MoreHorizontal size={20} color={muted} /> : <Plus size={22} color={muted} />}</IconButton>}+ </View>+ })}</View>+ {tab === 'installed' && <Fold label="Plugin runtime"><View style={s.row}><State value={view.status.runtime} /><TextAction label="Restart" disabled={!!m.busy} onPress={() => { void m.run('restart',() => restartPlugins(api)) }} /></View><Hint error>{view.status.error}</Hint></Fold>}+ </>}+ </>}+ </SheetScroll>+ {menu && <Sheet title={t('More options')} onClose={() => setMenu(undefined)} raised={18}><SheetScroll>+ {!selected && <TextAction label="Plugin details" onPress={() => { setSelected(menu);setMenu(undefined) }} />}+ <TextAction label="Reinstall plugin" onPress={() => { const name=menu, release=view?.catalog.find(row=>row.package===name);setMenu(undefined);if(release) void m.run('install:'+name,()=>updatePackage(api,name,release.pluginId)) }} />+ <TextAction label="Uninstall" destructive onPress={() => { const name=menu;setMenu(undefined);void confirmChange('Uninstall this package? Its credentials and workspace files will stay on disk.',t).then(async ok=>{if(ok && await m.run('remove:'+name,()=>removePackage(api,name)))setSelected(undefined)}) }} />+ </SheetScroll></Sheet>}+ </>+}+const market = StyleSheet.create({+ tabs:{flexDirection:'row',gap:8,paddingBottom:8},+ tab:{flex:1,alignItems:'center',justifyContent:'center',minHeight:44,paddingHorizontal:12,borderRadius:14,borderWidth:1,borderColor:'transparent'},+ selected:{backgroundColor:'#ffffffb8',borderColor:edge},label:{color:muted,fontSize:14,fontWeight:'500'},selectedLabel:{color:accent},+ tile:{flexDirection:'row',alignItems:'center',gap:4,borderRadius:17},+ tileMain:{flex:1,flexDirection:'row',alignItems:'center',gap:15,paddingVertical:20},+ title:{color:ink,fontSize:16,fontWeight:'600',letterSpacing:-.2},summary:{color:muted,fontSize:13,lineHeight:20},+ detailHead:{flexDirection:'row',alignItems:'flex-start',gap:18,paddingVertical:14},detailTitle:{fontSize:25,color:ink,fontWeight:'600',letterSpacing:-.6},+ update:{fontSize:11,color:'#5d70a0',fontWeight:'600'},+ section:{gap:16,paddingVertical:24,borderBottomWidth:1,borderBottomColor:'#27344c10'},heading:{color:ink,fontWeight:'600',fontSize:14},+})diff --git a/mobile/src/extensions/api.ts b/mobile/src/extensions/api.tsnew file mode 100644index 0000000..916acfd--- /dev/null+++ b/mobile/src/extensions/api.ts@@ -0,0 +1,34 @@+import type { Controller } from '../api'+import type { PluginView, AuthorizationAPI, AuthorizationEntry, AuthorizationAttempt, MCPAuthorizationAPI, MCPOAuthAttempt, MCPServer } from '../../../frontend/src/api/extensions'+export type { PackageInfo, PackageSource, PluginInstance, PluginSettings, PluginView, CatalogEntry, Localized } from '../../../frontend/src/api/extensions'+const pluginPath = '/v1/settings/plugins'+const part = encodeURIComponent+async function change<T>(api: Controller, path: string, method: string, value?: unknown): Promise<T> {+ const response = await api.response(path, { method, ...(value === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(value) }) }, 15 * 60_000)+ return response.status === 204 ? undefined as T : response.json() as Promise<T>+}+export const loadPlugins = (api: Controller, signal?: AbortSignal) => api.request<PluginView>(pluginPath, { signal })+export const installPackage = (api: Controller, pluginId: string) => change<PluginView>(api, pluginPath + '/packages', 'POST', { pluginId })+export const updatePackage = (api: Controller, name: string, pluginId: string) => change<PluginView>(api, pluginPath + '/packages/' + part(name) + '/update', 'POST', { pluginId })+export const removePackage = (api: Controller, name: string) => change<PluginView>(api, pluginPath + '/packages/' + part(name), 'DELETE')+export const setPluginEnabled = (api: Controller, name: string, enabled: boolean) => change<PluginView>(api, pluginPath + '/packages/' + part(name), 'PUT', { enabled })+export const restartPlugins = (api: Controller) => change<PluginView>(api, '/v1/host/plugins/runtime/restart', 'POST')++const authorization = '/v1/host/extensions/authorization'+export const authorizationAPI = (api: Controller): AuthorizationAPI => ({+ list: signal => api.request<AuthorizationEntry[]>(authorization, { signal }),+ get: (id, signal) => api.request<AuthorizationAttempt>(authorization + '/' + part(id), { signal }),+ start: (key, method) => change<AuthorizationAttempt>(api, authorization, 'POST', { key, method }),+ answer: (id, promptId, answer, decline) => change<AuthorizationAttempt>(api, authorization + '/' + part(id) + '/answer', 'POST', { promptId, answer, decline }),+ cancel: id => change<AuthorizationAttempt>(api, authorization + '/' + part(id), 'DELETE'),+ cancelKey: key => change(api, authorization, 'DELETE', { key }),+ disconnect: key => change(api, authorization + '/disconnect', 'POST', {key}),+})++const mcp = '/v1/host/mcp'+export const mcpAuthorizationAPI = (api: Controller): MCPAuthorizationAPI => ({+ list: signal => api.request<{ status: { servers: MCPServer[]; error?: string } }>(mcp, { signal }),+ start: name => change<MCPOAuthAttempt>(api, mcp + '/servers/' + part(name) + '/authorize', 'POST', { origin: new URL(api.profile.server).origin }),+ cancel: (name, attemptId) => change(api, mcp + '/servers/' + part(name) + '/authorization?id=' + part(attemptId), 'DELETE'),+ signOut: name => change(api, mcp + '/servers/' + part(name) + '/grant', 'DELETE'),+})diff --git a/mobile/src/extensions/shared.tsx b/mobile/src/extensions/shared.tsxnew file mode 100644index 0000000..ab2d19a--- /dev/null+++ b/mobile/src/extensions/shared.tsx@@ -0,0 +1,83 @@+import { useCallback, useEffect, useState, useSyncExternalStore, type ReactNode } from 'react'+import { AppState, Alert, Platform, Pressable, StyleSheet, Text, View } from 'react-native'+import { ArrowLeft, ChevronDown, RefreshCw } from 'lucide-react-native'+import { extensionOperations } from '../../../frontend/src/extensions/operations'+import type { TranscriptCache } from '../../../frontend/src/chat/transcriptCache'+import { ApiError, type Controller } from '../api'+import { useLocale } from '../locale'+import { accent, Button, danger, edge, Field, glass, Hint, IconButton, ink, muted, Panel, s } from '../ui'++export type ScreenProps = { api: Controller; cache: TranscriptCache; onDirtyChange: (value: boolean) => void; onBusyChange: (value: boolean) => void }+export function useManagement<T>({ api, cache }: ScreenProps, load: (api: Controller, signal?: AbortSignal) => Promise<T>) {+ const [view, setView] = useState<T>(), [loading, setLoading] = useState(true), [version, setVersion] = useState(0)+ const operations = extensionOperations(cache)+ const { busy, error, notice, revision } = useSyncExternalStore(operations.subscribe, operations.snapshot)+ const reload = useCallback(() => setVersion(value => value + 1), [])+ useEffect(() => cache.subscribe('@extensions', reload), [cache, reload])+ useEffect(() => { const listener = AppState.addEventListener('change', state => { if (state === 'active') reload() }); return () => listener.remove() }, [reload])+ useEffect(() => {+ const request = new AbortController()+ setLoading(true)+ void load(api, request.signal).then(next => { if (!request.signal.aborted) { setView(next); if (operations.snapshot().error === 'Could not load extensions. Try again.') operations.setError('') } }, () => { if (!request.signal.aborted) operations.setError('Could not load extensions. Try again.') }).finally(() => { if (!request.signal.aborted) setLoading(false) })+ return () => request.abort()+ }, [api, load, version, revision, operations])+ const run = (label: string, work: () => Promise<unknown>, success = 'Configuration saved. Review the runtime state below.') =>+ operations.run(label, work, error => error instanceof ApiError && error.code === 'settings_saved_host_apply_failed' ? 'Settings were saved, but the Host could not apply them. Refresh to check the actual state.'+ : error instanceof ApiError && error.code === 'host_not_running' ? 'Start your Host before managing extensions.'+ : error instanceof ApiError && error.code === 'oauth_requires_https_or_loopback_http' ? 'OAuth requires HTTPS or localhost HTTP. Open the Controller through one of these addresses.'+ : error instanceof ApiError && [400, 422].includes(error.status) && /\s/.test(error.code) ? error.code.slice(0, 1024)+ : 'Could not complete this operation. Refresh the actual state before trying again.', success)+ return { view, error, notice, busy, loading, reload, run }+}+export type Runner = ReturnType<typeof useManagement>['run']++const stateLabels: Record<string, string> = { installed: 'Installed', active: 'Active', running: 'Running', connected: 'Connected', ready: 'Ready', loading: 'Starting', applying: 'Starting', connecting: 'Connecting', pending: 'Pending', failed: 'Failed', unavailable: 'Unavailable', stopped: 'Stopped', disabled: 'Disabled', stopping: 'Stopping', 'waiting-credentials': 'Needs credentials', 'waiting-authorization': 'Authorization needed' }+export function State({ value }: { value: string }) {+ const { t } = useLocale()+ const color = ['active', 'connected', 'running', 'ready'].includes(value) ? '#3d7967' : value === 'failed' ? danger : muted+ return <View style={x.state}><View style={[x.dot, { backgroundColor: color }]} /><Text style={[x.stateLabel, { color }]}>{t(stateLabels[value] ?? value)}</Text></View>+}+export function Toolbar({ title, busy, onBack, onRefresh, children }: { title: string; busy?: boolean; onBack?: () => void; onRefresh?: () => void; children?: ReactNode }) {+ const { t } = useLocale()+ return <View style={[s.row, { gap: 8, marginBottom: 6 }]}>{onBack && <IconButton label={t('返回')} disabled={busy} onPress={onBack}><ArrowLeft size={19} color={muted} /></IconButton>}<Text accessibilityRole="header" style={[x.heading, { flex: 1 }]}>{t(title)}</Text>{onRefresh && <IconButton label={t('Refresh extensions')} disabled={busy} onPress={onRefresh}><RefreshCw size={18} color={muted} /></IconButton>}{children}</View>+}+export function TextAction({ label, onPress, disabled, destructive = false }: { label: string; onPress: () => void; disabled?: boolean; destructive?: boolean }) {+ const { t } = useLocale()+ return <Pressable accessibilityRole="button" disabled={disabled} onPress={onPress} style={({ pressed }) => [x.textAction, pressed && s.pressed, disabled && s.disabled]}><Text style={[x.actionText, destructive && { color: danger }]}>{t(label)}</Text></Pressable>+}+export function Feedback({ error, notice }: { error: string; notice: string }) { const { t } = useLocale(); return <><Hint error>{t(error)}</Hint><Hint>{t(notice)}</Hint></> }+export function Empty({ title, text, children }: { title: string; text: string; children: ReactNode }) {+ const { t } = useLocale()+ return <View style={x.empty}>{children}<Text style={x.heading}>{t(title)}</Text><Text style={[s.hint, { textAlign: 'center', maxWidth: 300 }]}>{t(text)}</Text></View>+}+export function Loading() { return <View accessibilityLabel="Loading" style={{ gap: 14 }}>{[0, 1, 2].map(i => <View key={i} style={{ height: 66, borderRadius: 17, backgroundColor: '#ebe9f1' }} />)}</View> }+export function Fact({ label, value }: { label: string; value: string | number }) { const { t } = useLocale(); return <View style={x.fact}><Text style={[s.caption, { width: 98 }]}>{t(label)}</Text><Text selectable style={[s.meta, { flex: 1, color: ink }]}>{value}</Text></View> }+export function JSONField({ label, value, onChange, editable = true }: { label: string; value: string; onChange: (text: string) => void; editable?: boolean }) {+ const { t } = useLocale()+ return <Field label={t(label)} value={value} onChangeText={onChange} editable={editable} multiline autoCorrect={false} spellCheck={false} style={{ fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace', fontSize: 13, lineHeight: 21, minHeight: 125 }} />+}+export function Toggle({ label, checked, onChange, disabled }: { label: string; checked: boolean; onChange: (value: boolean) => void; disabled?: boolean }) {+ const { t } = useLocale()+ return <Pressable accessibilityRole="switch" accessibilityState={{ checked, disabled }} accessibilityLabel={t(label)} disabled={disabled} onPress={() => onChange(!checked)} style={[s.row, { minHeight: 48, justifyContent: 'space-between', gap: 16 }, disabled && s.disabled]}><Text style={[s.meta, { flex: 1, color: ink }]}>{t(label)}</Text><View style={[x.toggle, checked && { backgroundColor: accent }]}><View style={[x.thumb, checked && { alignSelf: 'flex-end' }]} /></View></Pressable>+}+export function Fold({ label, children }: { label: string; children: ReactNode }) {+ const [open, setOpen] = useState(false); const { t } = useLocale()+ return <View><Pressable accessibilityRole="button" accessibilityState={{ expanded: open }} onPress={() => setOpen(!open)} style={[s.row, { minHeight: 50 }]}><Text style={[s.caption, { flex: 1 }]}>{t(label)}</Text><ChevronDown size={16} color={muted} style={open ? { transform: [{ rotate: '180deg' }] } : undefined} /></Pressable>{open && <View style={{ gap: 16, paddingVertical: 8 }}>{children}</View>}</View>+}+export function confirmChange(message: string, t: (key: string) => string): Promise<boolean> {+ return new Promise(resolve => Alert.alert(t('Confirm change'), t(message), [{ text: t('取消'), style: 'cancel', onPress: () => resolve(false) }, { text: t('Confirm'), style: 'destructive', onPress: () => resolve(true) }], { cancelable: true, onDismiss: () => resolve(false) }))+}+export function useDirty(dirty: boolean, onDirty: (value: boolean) => void) { useEffect(() => { onDirty(dirty); return () => onDirty(false) }, [dirty, onDirty]) }+export function objectJSON(value: string): Record<string, unknown> { const data: unknown = JSON.parse(value); if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Enter a JSON object.'); return data as Record<string, unknown> }+export function stringsJSON(value: string) { const data = objectJSON(value); if (Object.values(data).some(item => typeof item !== 'string')) throw new Error('Use string values for environment variables and headers.'); if (Object.values(data).some(item => String(item).includes('[redacted]'))) throw new Error('Replace redacted values with credential references before saving.'); return data as Record<string, string> }+++export const x = StyleSheet.create({+ heading: { color: ink, fontSize: 18, fontWeight: '600', letterSpacing: -.3 },+ state: { flexDirection: 'row', alignItems: 'center', gap: 6, flexShrink: 1 }, dot: { width: 5, height: 5, borderRadius: 3 }, stateLabel: { fontSize: 12, flexShrink: 1 },+ listRow: { flexDirection: 'row', alignItems: 'center', gap: 12, minHeight: 76, paddingVertical: 17 }, identity: { flex: 1, gap: 5, minWidth: 0 }, title: { color: ink, fontSize: 15, fontWeight: '600', lineHeight: 22 },+ fact: { flexDirection: 'row', alignItems: 'flex-start', gap: 12, paddingVertical: 5 }, textAction: { minHeight: 44, paddingHorizontal: 6, justifyContent: 'center' }, actionText: { color: accent, fontSize: 14, fontWeight: '500' },+ empty: { alignItems: 'center', gap: 14, paddingVertical: 42, paddingHorizontal: 8 }, actions: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', columnGap: 14, rowGap: 4 },+ toggle: { width: 43, height: 27, padding: 3, borderRadius: 16, backgroundColor: '#d9dce5' }, thumb: { width: 21, height: 21, borderRadius: 12, backgroundColor: '#fff' },+ list: { backgroundColor: glass, borderRadius: 22, paddingHorizontal: 16, borderWidth: 1, borderColor: edge },+})diff --git a/mobile/src/locale.tsx b/mobile/src/locale.tsxindex 0131430..ba0f958 100644--- a/mobile/src/locale.tsx+++ b/mobile/src/locale.tsx@@ -1,8 +1,13 @@import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'import { File, Paths } from 'expo-file-system'import { getLocales } from 'expo-localization'+import { extensionChinese } from '../../frontend/src/extensions/messages'++const extensionEnglish = Object.fromEntries(Object.entries(extensionChinese).map(([en, zh]) => [zh, en]))const english: Record<string, string> = {+ '审阅方案': 'Review the plan',+ '待审批': 'Approval needed', '待回答': 'Answer needed','当前会话权限': 'Chat permission', '全权限': 'Full access', '工作区可写': 'Workspace write', '只读': 'Read only','允许工具在 Host 可访问的范围内写入。': 'Allow writes anywhere the Host tools can access.','允许写入当前会话工作区。超出范围时需要审批。': 'Allow writes in this chat’s workspace. Ask before widening access.',@@ -57,6 +62,14 @@ const english: Record<string, string> = {'模型': 'Models', '无法读取模型设置。': 'Could not load model settings.','无法保存。请检查端点地址、密钥与模型名。': 'Could not save. Check the URL, API key, and model names.','支持 OpenAI 兼容的 Responses 接口。默认端点列表中的第一个模型用于新会话。': 'Supports OpenAI-compatible Responses endpoints. New chats use the first model on the default endpoint.',+ '放弃未保存的修改?': 'Discard unsaved changes?', '放弃修改': 'Discard changes',+ '请选择支持的接口协议。': 'Choose a supported API protocol.',+ '请填写基础地址,不包含 /messages、/responses 或 /chat/completions。': 'Enter a base URL without /messages, /responses, or /chat/completions.',+ '新地址需要重新填写 API key。': 'Enter an API key for the new address.',+ '接口协议': 'API protocol', '请求地址': 'Request URL',+ '按服务商提供的接口格式选择,与模型名称无关。': 'Choose the API format provided by your service, regardless of the model name.',+ '支持 OpenAI Responses 和 Anthropic Messages 兼容接口。默认端点的第一个模型用于新会话。': 'Supports OpenAI Responses and Anthropic Messages compatible endpoints. New chats use the first model on the default endpoint.',+ '将在下一轮使用此模型。': 'This model will be used from the next turn.','默认': 'Default', '添加端点': 'Add endpoint', '名称': 'Name', '端点地址': 'Endpoint URL','已保存,留空保留当前密钥': 'Saved. Leave blank to keep the current key.', '输入 API key': 'Enter an API key','模型名(每行一个)': 'Model names (one per line)', '保存端点': 'Save endpoint', '设为默认端点': 'Set as default',@@ -111,6 +124,11 @@ const english: Record<string, string> = {'助手未能完成回复。': 'The agent could not finish its reply.',}const notices: Record<string, string> = {+ 'Approve this plan and leave plan mode?': '确认方案后开始执行,或提出修改意见继续规划。',+ 'Approve': '按此方案执行', 'Keep planning': '继续完善方案',+ 'Leave plan mode; the plan is carried out from the next step.': '退出规划模式,从下一步开始执行方案。',+ 'Stay in plan mode; feedback goes back to the model.': '保持规划模式,将修改意见交给助手。',+'Scheduled task': '定时任务','Background task': '后台任务','The reply was interrupted.': '回复已中断。',@@ -119,7 +137,7 @@ const notices: Record<string, string> = {export type Language = 'zh-CN' | 'en'export const languages: readonly { id: Language; name: string }[] = [{ id: 'zh-CN', name: '简体中文' }, { id: 'en', name: 'English' }]const preference = new File(Paths.document, 'ui-language.txt')-const Locale = createContext({ language: 'zh-CN' as Language, changeLanguage: async (_language: Language) => {}, t: (key: string) => key })+const Locale = createContext({ language: 'zh-CN' as Language, changeLanguage: async (_language: Language) => {}, t: (key: string, _values?: Record<string, string | number>) => key })function deviceLanguage(): Language {return getLocales()[0]?.languageCode === 'zh' ? 'zh-CN' : 'en'@@ -138,9 +156,11 @@ export function LocaleProvider({ children }: { children: ReactNode }) {preference.write(next)setLanguage(next)}- const t = (key: string) => {+ const t = (key: string, values?: Record<string, string | number>) => {const dictionary = language === 'en' ? english : notices- return Object.hasOwn(dictionary, key) ? dictionary[key] : key+ const fallback = language === 'en' ? extensionEnglish : extensionChinese+ const text = Object.hasOwn(dictionary, key) ? dictionary[key] : fallback[key] ?? key+ return text.replace(/\{(\w+)\}/g, (match, name: string) => values?.[name] === undefined ? match : String(values[name]))}return <Locale.Provider value={{ language, changeLanguage, t }}>{ready && children}</Locale.Provider>}diff --git a/mobile/src/ui.tsx b/mobile/src/ui.tsxindex 1afef53..8728c2a 100644--- a/mobile/src/ui.tsx+++ b/mobile/src/ui.tsx@@ -1,6 +1,6 @@import { useLocale } from './locale'import { useEffect, useRef, useState, type ReactNode } from 'react'-import { AccessibilityInfo, ActivityIndicator, Animated, Easing, Image, KeyboardAvoidingView, Modal, Platform, Pressable, ScrollView, StyleSheet, Text, TextInput, useWindowDimensions, View, type StyleProp, type TextInputProps, type ViewStyle } from 'react-native'+import { AccessibilityInfo, ActivityIndicator, Animated, Easing, Image, KeyboardAvoidingView, Modal, Platform, Pressable, ScrollView, StyleSheet, Text, TextInput, useWindowDimensions, View, type AccessibilityState, type StyleProp, type TextInputProps, type ViewStyle } from 'react-native'import { useSafeAreaInsets } from 'react-native-safe-area-context'import { LinearGradient } from 'expo-linear-gradient'import Svg, { Defs, RadialGradient, Rect, Stop } from 'react-native-svg'@@ -60,8 +60,8 @@ export function useReducedMotion() {return reduced}-export function IconButton({ label, children, onPress, disabled, style }: { label: string; children: ReactNode; onPress: () => void; disabled?: boolean; style?: StyleProp<ViewStyle> }) {- return <Pressable accessibilityRole="button" accessibilityLabel={label} onPress={onPress} disabled={disabled}+export function IconButton({ label, children, onPress, disabled, style, accessibilityState }: { label: string; children: ReactNode; onPress: () => void; disabled?: boolean; style?: StyleProp<ViewStyle>; accessibilityState?: AccessibilityState }) {+ return <Pressable accessibilityRole="button" accessibilityLabel={label} accessibilityState={{ ...accessibilityState, disabled }} onPress={onPress} disabled={disabled}style={({ pressed }) => [s.icon, style, pressed && s.pressed, disabled && s.disabled]}>{children}</Pressable>}@@ -82,6 +82,7 @@ export function Field({ label, style, ...props }: TextInputProps & { label: stritype AfterClose = (action: () => void) => voidtype SheetProps = {+ beforeDismiss?: (proceed: () => void) => voidtitle: stringchildren: ReactNode | ((afterClose: AfterClose) => ReactNode)onClose: () => void@@ -92,7 +93,7 @@ type SheetProps = {surfaceColors?: readonly [string, string, string]}-export function Sheet({ title, children, onClose, drawer = false, raised = 0, headerAction, hideTitle = false, surfaceColors }: SheetProps) {+export function Sheet({ title, children, onClose, drawer = false, raised = 0, headerAction, hideTitle = false, surfaceColors, beforeDismiss }: SheetProps) {const { t } = useLocale()const inset = useSafeAreaInsets()const [visible, setVisible] = useState(true)@@ -127,20 +128,24 @@ export function Sheet({ title, children, onClose, drawer = false, raised = 0, heelse finish()})}+ function requestDismiss() {+ if (beforeDismiss) beforeDismiss(() => dismiss())+ else dismiss()+ }const transform = drawer? [{ translateX: motion.interpolate({ inputRange: [0, 1], outputRange: [-Math.min(width, 390), 0] }) }]: [{ translateY: motion.interpolate({ inputRange: [0, 1], outputRange: [raised ? 24 : height * 0.87, 0] }) }]- return <Modal visible={visible} transparent animationType="none" onRequestClose={() => dismiss()} onDismiss={finish} supportedOrientations={['portrait', 'landscape']}>+ return <Modal visible={visible} transparent animationType="none" onRequestClose={requestDismiss} onDismiss={finish} supportedOrientations={['portrait', 'landscape']}><KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={[s.overlay, drawer && s.left]}><Animated.View style={[StyleSheet.absoluteFill, s.backdrop, { opacity: motion }]}>- <Pressable accessibilityRole="button" accessibilityLabel={t('收起') + ' ' + title} style={StyleSheet.absoluteFill} onPress={() => dismiss()} />+ <Pressable accessibilityRole="button" accessibilityLabel={t('收起') + ' ' + title} style={StyleSheet.absoluteFill} onPress={requestDismiss} /></Animated.View><Animated.View accessibilityViewIsModal style={[s.sheet, drawer ? [s.drawer, { paddingTop: inset.top + 12, paddingBottom: inset.bottom + 12 }] : raised ? [s.raised, { marginBottom: Math.max(inset.bottom, 8) + raised }] : { paddingBottom: Math.max(16, inset.bottom), marginTop: inset.top + 18 }, { transform }, !!raised && { opacity: motion }]}><LinearGradient pointerEvents="none" colors={surfaceColors ?? ['#fffdfc', '#faf8fc', '#f3eef9']} locations={[0, 0.68, 1]}style={[StyleSheet.absoluteFill, s.sheetTint, drawer && s.drawerTint, !!raised && s.raisedTint]} />{!drawer && <View style={s.handle} />}- <View style={s.sheetHead}>{!hideTitle && <Text accessibilityRole="header" style={s.sheetTitle}>{title}</Text>}<View style={[s.row, hideTitle && { marginLeft: 'auto' }]}>{headerAction}<IconButton label={t('关闭')} onPress={() => dismiss()}><X color={muted} size={20} /></IconButton></View></View>+ <View style={s.sheetHead}>{!hideTitle && <Text accessibilityRole="header" style={s.sheetTitle}>{title}</Text>}<View style={[s.row, hideTitle && { marginLeft: 'auto' }]}>{headerAction}<IconButton label={t('关闭')} onPress={requestDismiss}><X color={muted} size={20} /></IconButton></View></View>{typeof children === 'function' ? children(dismiss) : children}</Animated.View></KeyboardAvoidingView>diff --git a/mobile/src/useTranscript.ts b/mobile/src/useTranscript.tsindex bb70949..d7c1c92 100644--- a/mobile/src/useTranscript.ts+++ b/mobile/src/useTranscript.ts@@ -1,7 +1,6 @@import { useEffect, useRef, useState } from 'react'-import { AppState } from 'react-native'import { emptyTranscript } from '../../frontend/src/chat/transcript'-import { cacheTranscript, prependTranscriptPage, updateCachedTranscript, type TranscriptCache } from '../../frontend/src/chat/transcriptCache'+import { prependTranscriptPage, type TranscriptCache } from '../../frontend/src/chat/transcriptCache'import { ApiError, Controller, problem } from './api'export function useTranscript(api: Controller, id: string, cache: TranscriptCache) {@@ -21,75 +20,35 @@ export function useTranscript(api: Controller, id: string, cache: TranscriptCachconst life = new AbortController()historySignal.current = life.signalsetOlder(false)- let stream: AbortController | undefined- let timer: ReturnType<typeof setTimeout> | undefined- let entry = cache.get(id)- let wait = 500- let running = false-- function again() {- if (life.signal.aborted || AppState.currentState === 'background') return- setConnecting(true)- timer = setTimeout(follow, wait)- wait = Math.min(wait * 2, 5000)- }-- async function follow() {- if (running || !entry || life.signal.aborted || AppState.currentState === 'background') return- const current = entry- clearTimeout(timer)- running = true- stream = new AbortController()- try {- await api.stream(id, current.cursor, stream.signal, () => {- if (life.signal.aborted) return- setConnecting(false)- wait = 500- }, (kind, data) => {- if (life.signal.aborted || stream?.signal.aborted || cache.get(id) !== current) return- setState(updateCachedTranscript(current, kind, data))- })- again()- } catch (e) {- if (life.signal.aborted) return- if (e instanceof ApiError && e.status === 404) {- cache.delete(id)- entry = undefined- setState(emptyTranscript())- setBefore(null)- setConnecting(false)- setUnavailable(true)- } else again()- } finally { running = false }- }-- const listener = AppState.addEventListener('change', status => {- if (status === 'background') { clearTimeout(timer); stream?.abort() }- if (status === 'active') void follow()- })setError('')+ setUnavailable(false)+ const update = () => {+ if (cache.isUnavailable(id)) { setUnavailable(true); return }+ const entry = cache.get(id)+ if (entry) { setState(entry.transcript); setBefore(entry.before) }+ }+ const unsubscribe = cache.subscribe(id, update)+ const connection = () => setConnecting(cache.connecting)+ const unsubscribeConnection = cache.subscribe('@connection', connection)+ connection()+ const entry = cache.get(id)if (entry) {cache.keep(id, entry)- void follow()+ update()+ setLoading(false)} else {+ cache.beginLoad(id)setLoading(true)api.transcript(id, null, life.signal).then(page => {- if (life.signal.aborted) return- entry = cacheTranscript(page)- cache.keep(id, entry)- setBefore(entry.before)- setState(entry.transcript)- void follow()+ if (!life.signal.aborted) cache.finishLoad(id, page)}).catch(e => {if (life.signal.aborted) return+ cache.cancelLoad(id)if (e instanceof ApiError && e.status === 404) setUnavailable(true)else setError(problem(e, '无法读取会话。'))- }).finally(() => {- if (!life.signal.aborted) setLoading(false)- })+ }).finally(() => { if (!life.signal.aborted) setLoading(false) })}-- return () => { life.abort(); stream?.abort(); clearTimeout(timer); listener.remove() }+ return () => { life.abort(); unsubscribe(); unsubscribeConnection(); cache.cancelLoad(id) }}, [api, cache, id, retry])async function loadOlder() {diff --git a/mobile/tsconfig.json b/mobile/tsconfig.jsonindex 4569917..1245e34 100644--- a/mobile/tsconfig.json+++ b/mobile/tsconfig.json@@ -1,4 +1,13 @@{"extends": "expo/tsconfig.base",- "compilerOptions": { "strict": true, "noEmit": true, "allowImportingTsExtensions": true }+ "compilerOptions": {+ "strict": true,+ "noEmit": true,+ "allowImportingTsExtensions": true,+ "paths": {+ "react": ["./node_modules/@types/react/index.d.ts"],+ "react/*": ["./node_modules/@types/react/*"],+ "eventsource-parser/stream": ["./node_modules/eventsource-parser/dist/stream"]+ }+ }}diff --git a/plugin/authorization.go b/plugin/authorization.gonew file mode 100644index 0000000..ca6d8e9--- /dev/null+++ b/plugin/authorization.go@@ -0,0 +1,16 @@+package plugin++const AuthorizationPath = "/v1/host/extensions/authorization"+const AuthorizationCallbackPath = "/v1/plugins/authorization/callback/"+const AuthorizationCallbackHeader = "X-Go-Bot-Authorization-Callback"++type AuthorizationStart struct {+ Key string `json:"key"`+ Method string `json:"method,omitempty"`+}++type AuthorizationAnswer struct {+ PromptID string `json:"promptId"`+ Answer *string `json:"answer,omitempty"`+ Decline bool `json:"decline,omitempty"`+}diff --git a/plugin/management.go b/plugin/management.gonew file mode 100644index 0000000..c473dc6--- /dev/null+++ b/plugin/management.go@@ -0,0 +1,18 @@+package plugin++const SettingsPath = "/v1/settings/plugins"+const InternalPath = "/internal/host/plugins"++type Status struct {+ Runtime string `json:"runtime"`+ Packages []PackageInfo `json:"packages"`+ Instances []Instance `json:"instances"`+ Warnings []string `json:"warnings,omitempty"`+ Error string `json:"error,omitempty"`+}++type View struct {+ Catalog []CatalogEntry `json:"catalog"`+ Settings Settings `json:"settings"`+ Status Status `json:"status"`+}diff --git a/plugin/settings.go b/plugin/settings.gonew file mode 100644index 0000000..a598217--- /dev/null+++ b/plugin/settings.go@@ -0,0 +1,122 @@+package plugin++import (+ "encoding/json"+ "errors"+ "path/filepath"+ "regexp"+ "strings"+)++var packageName = regexp.MustCompile(`^(?:@[a-z0-9._-]+/)?[a-z0-9][a-z0-9._-]*$`)+var exactVersion = regexp.MustCompile(`^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$`)+var instanceName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,23}$`)+var gitCommit = regexp.MustCompile(`^[a-fA-F0-9]{40}$`)++func ValidPackageName(name string) bool { return len(name) <= 214 && packageName.MatchString(name) }+func (s RuntimeSettings) Validate() error {+ if len(s.Packages) > 200 || len(s.Instances) > 200 {+ return errors.New("plugin settings exceed the supported limit")+ }+ for name, pkg := range s.Packages {+ if !ValidPackageName(name) {+ return errors.New("invalid package name")+ }+ if len(pkg.Builds) > 100 {+ return errors.New("too many plugin build permissions")+ }+ for _, build := range pkg.Builds {+ if build == name {+ continue+ }+ at := strings.LastIndex(build, "@")+ if at <= 0 || !ValidPackageName(build[:at]) || !exactVersion.MatchString(build[at+1:]) {+ return errors.New("plugin build permissions must name the package or exact dependency versions")+ }+ }++ source := pkg.Source+ if source.Spec == "" || len(source.Spec) > 4096 || strings.ContainsAny(source.Spec, "\x00\r\n") {+ return errors.New("invalid package source")+ }+ switch source.Type {+ case "registry":+ if !strings.HasPrefix(source.Spec, name+"@") || !exactVersion.MatchString(strings.TrimPrefix(source.Spec, name+"@")) {+ return errors.New("stored registry sources require exact versions")+ }+ case "bundled":+ if !instanceName.MatchString(source.Spec) {+ return errors.New("invalid bundled plugin")+ }+ case "directory":+ if !filepath.IsAbs(source.Spec) {+ return errors.New("development directories must be absolute Host paths")+ }+ case "tarball":+ case "git":+ _, ref, ok := strings.Cut(source.Spec, "#")+ commit, _, _ := strings.Cut(ref, "&path:/")+ if !ok || !gitCommit.MatchString(commit) {+ return errors.New("stored Git sources require a full commit")+ }+ default:+ return errors.New("unknown package source type")+ }+ }+ seen := map[string]bool{}+ for _, row := range s.Instances {+ if !instanceName.MatchString(row.ID) || seen[row.ID] {+ return errors.New("instance IDs use 1–24 lowercase letters, digits or hyphens, starting with a letter, and must be unique")+ }+ seen[row.ID] = true+ if _, found := s.Packages[row.Package]; !found {+ return errors.New("instance package is not configured")+ }+ if len(row.Config) > 0 {+ var value map[string]json.RawMessage+ if json.Unmarshal(row.Config, &value) != nil || value == nil {+ return errors.New("plugin instance config must be a JSON object")+ }+ }+ }+ data, err := json.Marshal(s)+ if err != nil {+ return err+ }+ if len(data) > 768<<10 {+ return errors.New("plugin settings exceed 768 KiB")+ }+ return nil+}+func (s RuntimeSettings) Clone() RuntimeSettings {+ data, _ := json.Marshal(s)+ var out RuntimeSettings+ _ = json.Unmarshal(data, &out)+ if out.Packages == nil {+ out.Packages = map[string]RuntimePackage{}+ }+ if out.Instances == nil {+ out.Instances = []InstanceConfig{}+ }+ return out+}++// Clone returns an independent, non-nil selection map.+func (s Settings) Clone() Settings {+ out := Settings{Packages: map[string]PackageSelection{}}+ for name, selection := range s.Packages {+ out.Packages[name] = selection+ }+ return out+}+func (s Settings) Validate() error {+ if len(s.Packages) > 200 {+ return errors.New("too many selected plugins")+ }+ for name, selection := range s.Packages {+ if !ValidPackageName(name) || !packageName.MatchString(selection.CatalogID) || !exactVersion.MatchString(selection.Version) {+ return errors.New("invalid plugin selection")+ }+ }+ return nil+}diff --git a/plugin/types.go b/plugin/types.gonew file mode 100644index 0000000..a3a9789--- /dev/null+++ b/plugin/types.go@@ -0,0 +1,103 @@+// Package plugin defines the serializable Host extension management contracts.+package plugin++import "encoding/json"++const Protocol = 1++type Source struct {+ Type string `json:"type"`+ Spec string `json:"spec"`+ Registry string `json:"registry,omitempty"`+ AuthRef string `json:"authRef,omitempty"`+ Username string `json:"username,omitempty"`+}+type RuntimePackage struct {+ Version string `json:"version,omitempty"`+ CatalogID string `json:"catalogId,omitempty"`+ Source Source `json:"source"`+ Builds []string `json:"builds,omitempty"`+}++// CatalogEntry is the public, reviewed description. Installation sources stay+// in the Controller's compiled catalog and are never accepted from clients.+type Localized struct {+ EN string `json:"en"`+ ZH string `json:"zh-CN"`+}+type Tutorial struct {+ Language string `json:"language"`+ Title string `json:"title"`+ Video string `json:"video"`+ Poster string `json:"poster,omitempty"`+}++type CatalogEntry struct {+ ID string `json:"pluginId"`+ Package string `json:"package"`+ Name string `json:"name"`+ Description Localized `json:"description"`+ Version string `json:"version"`+ Icon string `json:"icon"`+ Maintainer string `json:"maintainer"`+ License string `json:"license"`+ Tutorials []Tutorial `json:"tutorials,omitempty"`+}++// PackageSelection is the only per-plugin data persisted in the user's Redis hash.+type PackageSelection struct {+ CatalogID string `json:"catalogId"`+ Version string `json:"version"`+ Enabled bool `json:"enabled"`+}+type Settings struct {+ Packages map[string]PackageSelection `json:"packages"`+}+type PackageInput struct {+ Enabled bool `json:"enabled"`+}+type PackageInfo struct {+ Name string `json:"name"`+ Version string `json:"version"`+ Description string `json:"description"`+ License string `json:"license"`+ Source Source `json:"source"`+ API string `json:"api"`+ Title string `json:"title,omitempty"`+ ConfigSchema json.RawMessage `json:"configSchema,omitempty"`+ AvailableVersion string `json:"availableVersion,omitempty"`+ Present bool `json:"present"`+}+type InstanceConfig struct {+ ID string `json:"id"`+ Package string `json:"package"`+ Enabled bool `json:"enabled"`+ Config json.RawMessage `json:"config,omitempty"`+}+type RuntimeSettings struct {+ Packages map[string]RuntimePackage `json:"packages"`+ Instances []InstanceConfig `json:"instances"`+}+type Instance struct {+ ID string `json:"id"`+ Package string `json:"package"`+ State string `json:"state"`+ Error string `json:"error,omitempty"`+}+type Error struct {+ Code string `json:"code"`+ Name string `json:"name,omitempty"`+ Message string `json:"message"`+ Unclassified bool `json:"-"`+}++func (e *Error) Error() string { return e.Message }+func (e *Error) ToolErrorInfo() (string, string) {+ if e.Unclassified || e.Code == "EXTENSION_ERROR" {+ return "", ""+ }+ if e.Name != "" {+ return e.Name, e.Code+ }+ return "HostError", e.Code+}diff --git a/plugin/version.go b/plugin/version.gonew file mode 100644index 0000000..591aa47--- /dev/null+++ b/plugin/version.go@@ -0,0 +1,16 @@+package plugin++import (+ "golang.org/x/mod/semver"+ "strings"+)++// NewerVersion reports a valid, strictly newer reviewed release. Installation+// state is supplied by the Host; saved Redis intent is not proof of installation.+func NewerVersion(installed, available string) string {+ a, b := "v"+strings.TrimPrefix(installed, "v"), "v"+strings.TrimPrefix(available, "v")+ if !semver.IsValid(a) || !semver.IsValid(b) || semver.Compare(b, a) <= 0 {+ return ""+ }+ return available+}diff --git a/plugin/version_test.go b/plugin/version_test.gonew file mode 100644index 0000000..280ee54--- /dev/null+++ b/plugin/version_test.go@@ -0,0 +1,15 @@+package plugin++import "testing"++func TestNewerVersionUsesSemanticPrecedence(t *testing.T) {+ for _, tc := range []struct{ installed, available, want string }{+ {"0.9.0", "0.10.0", "0.10.0"}, {"0.10.0", "0.9.0", ""},+ {"1.0.0-rc.1", "1.0.0", "1.0.0"}, {"1.0.0", "1.0.0-rc.1", ""},+ {"1.0.0+one", "1.0.0+two", ""}, {"invalid", "1.0.0", ""},+ } {+ if got := NewerVersion(tc.installed, tc.available); got != tc.want {+ t.Errorf("%s -> %s: got %q, want %q", tc.installed, tc.available, got, tc.want)+ }+ }+}diff --git a/providers/model/mainmodel/model.go b/providers/model/mainmodel/model.goindex c31bd30..3cc802b 100644--- a/providers/model/mainmodel/model.go+++ b/providers/model/mainmodel/model.go@@ -55,7 +55,7 @@ func ParseConfig(raw string) (Config, error) {parsed, err := url.Parse(endpoint.BaseURL)if name == "" || strings.TrimSpace(name) != name || err != nil || parsed.Host == "" ||(parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" ||- (endpoint.Protocol != llm.Responses && endpoint.Protocol != llm.ChatCompletions) {+ (endpoint.Protocol != llm.Responses && endpoint.Protocol != llm.ChatCompletions && endpoint.Protocol != llm.AnthropicMessages) {return Config{}, fmt.Errorf("invalid Host model endpoint %q", name)}}@@ -139,5 +139,5 @@ func (m Model) adapter(ctx context.Context) (agent.LLMAdapter, context.Context,if err != nil {return agent.LLMAdapter{}, nil, err}- return agent.LLMAdapter{Transport: client, Protocol: endpoint.Protocol, Images: m.Images, ImageAccessPath: m.ImageAccessPath, ImageInputEnabled: true}, ctx, nil+ return agent.LLMAdapter{EndpointURL: strings.TrimRight(endpoint.BaseURL, "/"), Transport: client, Protocol: endpoint.Protocol, Images: m.Images, ImageAccessPath: m.ImageAccessPath, ImageInputEnabled: true}, ctx, nil}diff --git a/providers/web/brave/provider.go b/providers/web/brave/provider.gonew file mode 100644index 0000000..2a89e03--- /dev/null+++ b/providers/web/brave/provider.go@@ -0,0 +1,76 @@+package brave++import (+ "context"+ "errors"+ "net/http"+ "strings"+ "time"+ "unicode/utf8"++ "go-bot/internal/providersettings"+ "go-bot/providers/web/internal/standard"+ api "go-bot/thirdparty/brave"+ "go-bot/thirdparty/providerhttp"+ "go-bot/web"+)++const ID = "brave"+const name = "Brave Search"++type Provider struct {+ endpoint, key string+ http *http.Client+}++func New(options web.Options) (web.SearchProvider, error) {+ if options.APIKey == "" || !providersettings.ValidAPIKey(options.APIKey) {+ return nil, errors.New("invalid Brave Search API key")+ }+ endpoint := options.BaseURL+ if endpoint == "" {+ endpoint = api.Endpoint+ }+ return &Provider{endpoint, options.APIKey, providerhttp.New(30 * time.Second)}, nil+}++func (*Provider) Name() string { return ID }++func (p *Provider) Search(ctx context.Context, request web.SearchRequest) (web.SearchResult, error) {+ query := web.CollapseSpace(request.Query)+ if query == "" || utf8.RuneCountInString(query) > 600 || len(strings.Fields(query)) > 75 {+ return web.SearchResult{}, &web.Error{Code: "WEB_INVALID_QUERY", Message: "Brave Search requires 1–600 characters and at most 75 words per query. Shorten the query and try again."}+ }+ count := standard.Count(request)+ response, status, err := api.Search(ctx, p.http, p.endpoint, p.key, query, count)+ if err := standard.Failed(name, status, err); err != nil {+ return web.SearchResult{}, err+ }+ if response.Grounding == nil || response.Grounding.Results == nil {+ return web.SearchResult{}, standard.Invalid(name)+ }+ result := web.SearchResult{Sources: make([]web.SearchSource, 0, min(count, len(response.Grounding.Results)))}+ for _, row := range response.Grounding.Results {+ metadata := response.Sources[row.URL]+ title := row.Title+ if strings.TrimSpace(title) == "" {+ title = metadata.Title+ }+ published := ""+ // age[3] is the ISO timestamp; age[1] is the absolute calendar date.+ // Relative ages and last-fetch timestamps are not publication dates.+ if len(metadata.Age) > 3 {+ published = metadata.Age[3]+ }+ if published == "" && len(metadata.Age) > 1 {+ published = metadata.Age[1]+ }+ if source, ok := standard.Source(row.URL, title, metadata.Description, strings.Join(row.Snippets, "\n\n"), published); ok {+ result.Sources = append(result.Sources, source)+ if len(result.Sources) == count {+ break+ }+ }+ }+ return result, nil+}diff --git a/providers/web/international_test.go b/providers/web/international_test.gonew file mode 100644index 0000000..5c0eb2e--- /dev/null+++ b/providers/web/international_test.go@@ -0,0 +1,211 @@+package webproviders++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "go-bot/harness/tools"+ "go-bot/web"+)++const tavilyFixture = `{"results":[{"url":"javascript:invalid"},{"title":"Fixture","url":"https://example.com/report","content":"Relevant source text","published_date":"2026-11-18"},{"url":"https://example.com/overflow"}],"answer":"Do not forward generated answers","raw_content":"Do not forward raw HTML"}`+const braveFixture = `{"grounding":{"generic":[{"url":"javascript:invalid","snippets":[]},{"url":"https://example.com/report","snippets":["Relevant source text","Another passage"]},{"url":"https://example.com/overflow","snippets":[]}]},"sources":{"https://example.com/report":{"title":"Fixture","description":"Source description","age":["November 18, 2026","2026-11-18","today","2026-11-18T00:00:00Z"],"fetched_content_timestamp":1}}}`++func checkInternationalRequest(t *testing.T, id string, r *http.Request, count int) {+ t.Helper()+ var body map[string]any+ if r.Method != http.MethodPost || r.URL.Path != "/search" || r.URL.RawQuery != "" || r.Header.Get("Content-Type") != "application/json" || json.NewDecoder(r.Body).Decode(&body) != nil {+ t.Error("unexpected search wire request")+ return+ }+ if id == "tavily" {+ if r.Header.Get("Authorization") != "Bearer fixture-secret" || body["query"] != "fixture query" || body["max_results"] != float64(count) || body["search_depth"] != "basic" || body["topic"] != "general" || body["include_answer"] != false || body["include_raw_content"] != false || body["auto_parameters"] != false || body["include_published_date"] != true {+ t.Errorf("incorrect Tavily search defaults: %+v", body)+ }+ } else {+ if r.Header.Get("X-Subscription-Token") != "fixture-secret" || r.Header.Get("Authorization") != "" || body["q"] != "fixture query" || body["count"] != float64(count) || body["maximum_number_of_urls"] != float64(count) || body["maximum_number_of_tokens"] != float64(8192) || body["enable_source_metadata"] != true {+ t.Errorf("incorrect Brave LLM Context defaults: %+v", body)+ }+ }+ if strings.Contains(string(mustJSON(t, body)), "fixture-secret") {+ t.Error("key was put into the body")+ }+}++func mustJSON(t *testing.T, v any) []byte {+ t.Helper()+ data, err := json.Marshal(v)+ if err != nil {+ t.Fatal(err)+ }+ return data+}++func TestInternationalSearchRequestAndToolProjection(t *testing.T) {+ for _, tc := range []struct{ id, reply string }{{"tavily", tavilyFixture}, {"brave", braveFixture}} {+ t.Run(tc.id, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ checkInternationalRequest(t, tc.id, r, 1)+ io.WriteString(w, tc.reply)+ }))+ defer server.Close()+ provider, err := New(tc.id, web.Options{BaseURL: server.URL + "/search", APIKey: "fixture-secret"})+ if err != nil {+ t.Fatal(err)+ }+ result, err := provider.Search(t.Context(), web.SearchRequest{Query: " fixture\nquery ", MaxResults: 1})+ if err != nil || len(result.Sources) != 1 {+ t.Fatalf("result=%+v err=%v", result, err)+ }+ source := result.Sources[0]+ if source.Title == nil || *source.Title != "Fixture" || source.Summary == nil || !strings.HasPrefix(*source.Summary, "Relevant source text") || source.PublishedAt == nil || !strings.HasPrefix(*source.PublishedAt, "2026-11-18") || result.Content != nil {+ t.Fatalf("source normalization lost data: %+v", source)+ }+ })+ // The actual tool receives the same bounded, untrusted source projection+ // for either service, rather than a vendor-generated answer or raw HTML.+ t.Run(tc.id+"-tool", func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, tc.reply) }))+ defer server.Close()+ p, _ := New(tc.id, web.Options{BaseURL: server.URL, APIKey: "fixture-secret"})+ text, _, err := (tools.WebSearch{Searcher: p}).ExecutePresented(t.Context(), json.RawMessage(`{"queries":["fixture query"]}`))+ if err != nil || !strings.Contains(text, "https://example.com/report") || !strings.Contains(text, "Relevant source text") || !strings.Contains(text, "untrusted") || strings.Contains(text, "Do not forward") {+ t.Fatalf("unexpected tool projection: %s (%v)", text, err)+ }+ })+ }+}++func TestInternationalSearchLimitsErrorsAndEmptyResults(t *testing.T) {+ for _, id := range []string{"tavily", "brave"} {+ empty := `{"results":[]}`+ if id == "brave" {+ empty = `{"grounding":{"generic":[]},"sources":{}}`+ }+ cases := []struct {+ status int+ reply, code string+ }{+ {200, empty, ""}, {200, `{}`, "WEB_PROVIDER_FAILED"}, {200, `{"results":`, "WEB_PROVIDER_FAILED"},+ {401, `{"error":"fixture-secret"}`, "WEB_PROVIDER_AUTH"}, {403, `{"error":"fixture-secret"}`, "WEB_PROVIDER_AUTH"},+ {402, `{}`, "WEB_PROVIDER_QUOTA"}, {429, `{}`, "WEB_PROVIDER_RATE_LIMIT"}, {500, `{}`, "WEB_PROVIDER_FAILED"},+ }+ if id == "tavily" {+ cases = append(cases, struct {+ status int+ reply, code string+ }{432, `{}`, "WEB_PROVIDER_QUOTA"}, struct {+ status int+ reply, code string+ }{433, `{}`, "WEB_PROVIDER_QUOTA"}, struct {+ status int+ reply, code string+ }{434, `{}`, "WEB_PROVIDER_RATE_LIMIT"})+ }+ for _, tc := range cases {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ count := 50+ if id == "tavily" {+ count = 20+ }+ checkInternationalRequest(t, id, r, count)+ w.WriteHeader(tc.status)+ io.WriteString(w, tc.reply)+ }))+ p, err := New(id, web.Options{BaseURL: server.URL + "/search", APIKey: "fixture-secret"})+ if err != nil {+ server.Close()+ t.Fatal(err)+ }+ result, err := p.Search(t.Context(), web.SearchRequest{Query: "fixture query", MaxResults: 100})+ server.Close()+ if tc.code == "" {+ if err != nil || len(result.Sources) != 0 {+ t.Fatalf("%s: empty response=%+v err=%v", id, result, err)+ }+ continue+ }+ failure, ok := err.(*web.Error)+ if !ok || failure.Code != tc.code || strings.Contains(err.Error(), "fixture-secret") {+ t.Fatalf("%s HTTP %d: error=%v", id, tc.status, err)+ }+ }+ }+}++func TestInternationalSearchCancellationRedirectAndSizeLimit(t *testing.T) {+ for _, id := range []string{"tavily", "brave"} {+ t.Run(id, func(t *testing.T) {+ for _, key := range []string{"", " bad", "bad\nkey", strings.Repeat("x", 4097)} {+ if _, err := New(id, web.Options{APIKey: key}); err == nil {+ t.Fatal("invalid key accepted")+ }+ }+ var followed atomic.Int32+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { followed.Add(1) }))+ defer target.Close()+ redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect)+ }))+ defer redirect.Close()+ p, _ := New(id, web.Options{BaseURL: redirect.URL, APIKey: "fixture-secret"})+ if _, err := p.Search(t.Context(), web.SearchRequest{Query: "fixture"}); err == nil || followed.Load() != 0 {+ t.Fatal("credential redirect was followed")+ }+ large := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, strings.Repeat("x", (4<<20)+1)) }))+ defer large.Close()+ p, _ = New(id, web.Options{BaseURL: large.URL, APIKey: "fixture-secret"})+ if _, err := p.Search(t.Context(), web.SearchRequest{Query: "fixture"}); err == nil {+ t.Fatal("oversized response accepted")+ }+ started := make(chan struct{})+ slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ io.Copy(io.Discard, r.Body)+ close(started)+ select {+ case <-r.Context().Done():+ case <-time.After(3 * time.Second):+ }+ }))+ defer slow.Close()+ p, _ = New(id, web.Options{BaseURL: slow.URL, APIKey: "fixture-secret"})+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ result := make(chan error, 1)+ go func() { _, err := p.Search(ctx, web.SearchRequest{Query: "fixture"}); result <- err }()+ <-started+ cancel()+ select {+ case err := <-result:+ if failure, ok := err.(*web.Error); !ok || failure.Code != "WEB_ABORTED" {+ t.Fatalf("cancellation=%v", err)+ }+ case <-time.After(time.Second):+ t.Fatal("request did not cancel")+ }+ })+ }+}++func TestBraveRejectsOversizedQueriesBeforeSending(t *testing.T) {+ var calls atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1) }))+ defer server.Close()+ p, _ := New("brave", web.Options{BaseURL: server.URL, APIKey: "fixture-secret"})+ for _, query := range []string{" ", strings.Repeat("界", 601), strings.Repeat("word ", 76)} {+ _, err := p.Search(t.Context(), web.SearchRequest{Query: query})+ if failure, ok := err.(*web.Error); !ok || failure.Code != "WEB_INVALID_QUERY" {+ t.Fatalf("invalid query=%v", err)+ }+ }+ if calls.Load() != 0 {+ t.Fatal("invalid query reached upstream")+ }+}diff --git a/providers/web/registry.go b/providers/web/registry.goindex 0e5e3ad..4ea9c3b 100644--- a/providers/web/registry.go+++ b/providers/web/registry.go@@ -6,8 +6,10 @@ import ("sort""go-bot/internal/providersettings"+ "go-bot/providers/web/brave""go-bot/providers/web/deepseek""go-bot/providers/web/doubao"+ "go-bot/providers/web/tavily""go-bot/providers/web/zhipu""go-bot/web")@@ -18,9 +20,11 @@ type adapter struct {}var registry = map[string]adapter{+ brave.ID: {name: "Brave Search", newProvider: brave.New},deepseek.ID: {name: "DeepSeek", newProvider: deepseek.New},doubao.ID: {name: "Doubao Search", newProvider: doubao.New},zhipu.ID: {name: "Zhipu Search", newProvider: zhipu.New},+ tavily.ID: {name: "Tavily", newProvider: tavily.New},}const Default = deepseek.IDdiff --git a/providers/web/tavily/provider.go b/providers/web/tavily/provider.gonew file mode 100644index 0000000..3ef9666--- /dev/null+++ b/providers/web/tavily/provider.go@@ -0,0 +1,66 @@+package tavily++import (+ "context"+ "errors"+ "net/http"+ "time"++ "go-bot/internal/providersettings"+ "go-bot/providers/web/internal/standard"+ "go-bot/thirdparty/providerhttp"+ api "go-bot/thirdparty/tavily"+ "go-bot/web"+)++const ID = "tavily"+const name = "Tavily"++type Provider struct {+ endpoint, key string+ http *http.Client+}++func New(options web.Options) (web.SearchProvider, error) {+ if options.APIKey == "" || !providersettings.ValidAPIKey(options.APIKey) {+ return nil, errors.New("invalid Tavily API key")+ }+ endpoint := options.BaseURL+ if endpoint == "" {+ endpoint = api.Endpoint+ }+ return &Provider{endpoint, options.APIKey, providerhttp.New(30 * time.Second)}, nil+}++func (*Provider) Name() string { return ID }++func (p *Provider) Search(ctx context.Context, request web.SearchRequest) (web.SearchResult, error) {+ query := web.CollapseSpace(request.Query)+ if query == "" {+ return web.SearchResult{}, &web.Error{Code: "WEB_INVALID_QUERY", Message: "Tavily requires a non-empty search query."}+ }+ count := min(standard.Count(request), 20)+ response, status, err := api.Search(ctx, p.http, p.endpoint, p.key, query, count)+ if status == 432 || status == 433 {+ status = http.StatusPaymentRequired+ }+ if status == 434 {+ status = http.StatusTooManyRequests+ }+ if err := standard.Failed(name, status, err); err != nil {+ return web.SearchResult{}, err+ }+ if response.Results == nil {+ return web.SearchResult{}, standard.Invalid(name)+ }+ result := web.SearchResult{Sources: make([]web.SearchSource, 0, min(count, len(response.Results)))}+ for _, row := range response.Results {+ if source, ok := standard.Source(row.URL, row.Title, "", row.Content, row.Published); ok {+ result.Sources = append(result.Sources, source)+ if len(result.Sources) == count {+ break+ }+ }+ }+ return result, nil+}diff --git a/scripts/smoke-image.sh b/scripts/smoke-image.shindex a848cf7..4eedaaa 100755--- a/scripts/smoke-image.sh+++ b/scripts/smoke-image.sh@@ -7,24 +7,24 @@ docker run --rm --entrypoint /bin/sh "$image" -ec 'node --versionnpm --versionnpx --version+ node -e "require(\"pdf-lib\")"chromium --versionsoffice --version- officecli --versionpython -c "import pypdf,pdfplumber,reportlab,pymupdf,pypdfium2,pptx"- mkdir /tmp/office-smoke- officecli create /tmp/office-smoke/report.docx- officecli add /tmp/office-smoke/report.docx /body --type paragraph --prop "text=Go Bot smoke"- officecli get /tmp/office-smoke/report.docx /- officecli save /tmp/office-smoke/report.docx- soffice -env:UserInstallation=file:///tmp/lo-smoke --headless --convert-to pdf --outdir /tmp/office-smoke /tmp/office-smoke/report.docx- pdfinfo /tmp/office-smoke/report.pdf+ # Official CLIs are installed by plugin lifecycle scripts, not preinstalled.+ ! command -v officecli+ ! command -v agent-browser+ ! command -v xurl+ ! command -v gws+ test ! -e /usr/share/go-bot/skill-seed+ for plugin in agent-browser officecli x google-workspace; do+ test -s "/usr/share/go-bot/plugins/$plugin/package.json"+ test -s "/usr/share/go-bot/plugins/$plugin/scripts/install.mjs"+ test -s "/usr/share/go-bot/plugins/$plugin/UPSTREAM_LICENSE"+ test -s "/usr/share/go-bot/plugins/$plugin/assets/icon.png"+ done+ test -s /usr/share/go-bot/plugins/google-workspace/skills/gws-shared/SKILL.mdchromium --headless --no-sandbox --disable-dev-shm-usage --no-zygote --screenshot=/tmp/browser.png "data:text/html,<h1>Go Bot</h1>" >/dev/null 2>&1test -s /tmp/browser.png- agent-browser --version- agent-browser skills get core > /tmp/agent-browser-core.md- grep -q "agent-browser core" /tmp/agent-browser-core.md- export AGENT_BROWSER_SOCKET_DIR="$(mktemp -d /tmp/ghb-XXXXXXXX)"- trap "agent-browser close --all" EXIT- agent-browser open about:blank- echo "Image document/browser smoke: OK"+ echo "Base environment and packaged plugin smoke: OK"'diff --git a/scripts/update-officecli.py b/scripts/update-officecli.pydeleted file mode 100755index be2e630..0000000--- a/scripts/update-officecli.py+++ /dev/null@@ -1,46 +0,0 @@-#!/usr/bin/env python3-"""Update official OfficeCLI version/checksum locks; rebuild and smoke afterwards."""-import json-import pathlib-import re-import urllib.request--ROOT = pathlib.Path(__file__).resolve().parent.parent---def fetch(url):- request = urllib.request.Request(url, headers={"User-Agent": "Go-Bot-build"})- with urllib.request.urlopen(request, timeout=60) as response:- data = response.read(2_000_001)- if len(data) > 2_000_000:- raise RuntimeError("Official release metadata exceeded expected size")- return data---def main():- release = json.loads(fetch("https://api.github.com/repos/iOfficeAI/OfficeCLI/releases/latest"))- version = release["tag_name"]- if release.get("prerelease") or release.get("draft") or not re.fullmatch(r"v\d+\.\d+\.\d+", version):- raise RuntimeError("Expected a stable official release")- checksums = fetch(f"https://github.com/iOfficeAI/OfficeCLI/releases/download/{version}/SHA256SUMS").decode()- wanted = ("officecli-linux-arm64", "officecli-linux-x64")- found = {}- for line in checksums.splitlines():- match = re.fullmatch(r"([0-9a-fA-F]{64})\s+\*?(\S+)", line)- if match and match[2] in wanted:- found[match[2]] = match[1].lower()- if set(found) != set(wanted):- raise RuntimeError("Official SHA256SUMS is missing required Linux assets")- dockerfile = ROOT / "build/Dockerfile.host"- updated, count = re.subn(r"ARG OFFICECLI_VERSION=v\d+\.\d+\.\d+", f"ARG OFFICECLI_VERSION={version}", dockerfile.read_text())- if count != 1:- raise RuntimeError("Expected exactly one OfficeCLI build version")- # All metadata is validated before modifying tracked files.- (ROOT / "build/officecli.sha256").write_text("".join(f"{found[name]} {name}\n" for name in wanted))- (ROOT / "build/dependencies.lock.yaml").write_text(f"officecli:\n repository: iOfficeAI/OfficeCLI\n version: {version}\n checksums: build/officecli.sha256\n")- dockerfile.write_text(updated)- print(f"Locked official OfficeCLI {version}; review changes, rebuild and smoke before publishing.")---if __name__ == "__main__":- main()diff --git a/tests/integration/browser_use_docker_test.go b/tests/integration/browser_use_docker_test.goindex 385133e..d05d2f0 100644--- a/tests/integration/browser_use_docker_test.go+++ b/tests/integration/browser_use_docker_test.go@@ -24,7 +24,7 @@ func TestDockerBrowserSkillAndSessionIsolation(t *testing.T) {if image := os.Getenv("HARNESS_TEST_HOST_IMAGE"); image != "" {c.Runtime.Image = image}- ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute)+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Minute)defer cancel()mux := http.NewServeMux()mux.HandleFunc("/page", func(w http.ResponseWriter, r *http.Request) {@@ -67,7 +67,9 @@ func TestDockerBrowserSkillAndSessionIsolation(t *testing.T) {var userMessage stringoutputs := map[string]string{}for _, item := range body.Input {- if item.Role == "user" && len(item.Content) > 0 && !strings.HasPrefix(item.Content[0].Text, "Time sampled") {+ if item.Role == "user" && len(item.Content) > 0 &&+ !strings.HasPrefix(item.Content[0].Text, "Time sampled") &&+ !strings.HasPrefix(item.Content[0].Text, "Current runtime context.") {userMessage = item.Content[0].Text}if item.Type == "function_call_output" && len(item.Output) > 0 {@@ -222,6 +224,13 @@ printf "fresh browser session"request("DELETE", imageSettings+"?provider=seedream", "", 200).Body.Close()first, second := newSession(), newSession()+ // Sessions already exist before CLI installation. Installation must prepare+ // software while disabled; activation contributes the Skill without downloading.+ manager.Exec(t, ctx, "sh", "-ec", "! command -v agent-browser")+ request("POST", "/v1/settings/plugins/packages", `{"pluginId":"agent-browser"}`, 200).Body.Close()+ manager.Exec(t, ctx, "sh", "-ec", "agent-browser --version; test ! -e /root/harness/.dsh/plugins/profile/plugins.json")+ request("PUT", "/v1/settings/plugins/packages/%40go-bot%2Fplugin-agent-browser", `{"enabled":true}`, 200).Body.Close()+send(first, "Browser first", "")after := send(second, "Browser second", "")for name, signature := range map[string]string{"browser-report.png": "\x89PNG", "browser-report.txt": "browser download fixture"} {diff --git a/tests/integration/docker_test.go b/tests/integration/docker_test.goindex cbcfb28..a313542 100644--- a/tests/integration/docker_test.go+++ b/tests/integration/docker_test.go@@ -70,7 +70,7 @@ func TestDockerHostConversationRecoveryAndFiles(t *testing.T) {model.Start()defer model.Close()port := listener.Addr().(*net.TCPAddr).Port- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)defer cancel()c := dockerFixtureConfig()baseImage := c.Runtime.Image@@ -125,6 +125,14 @@ func TestDockerHostConversationRecoveryAndFiles(t *testing.T) {b, _ := io.ReadAll(res.Body)return res.StatusCode, b}+ for _, operation := range []struct{ method, path, body string }{+ {"POST", "/v1/settings/plugins/packages", `{"pluginId":"officecli"}`},+ {"PUT", "/v1/settings/plugins/packages/%40go-bot%2Fplugin-officecli", `{"enabled":true}`},+ } {+ if code, body := call(operation.method, operation.path, operation.body); code != 200 {+ t.Fatalf("prepare OfficeCLI plugin: %d %s", code, body)+ }+ }status, b := call("POST", "/v1/sessions", "")if status != 201 {t.Fatalf("create: %d %s", status, b)@@ -176,9 +184,9 @@ func TestDockerHostConversationRecoveryAndFiles(t *testing.T) {test "$HOME" = /root && test "$DSH_HOME" = /root/harness/.dshtest "$DSH_AGENTS_HOME" = /root/harness/.agents && test "$PWD" = /root/harnessfor bundle in officecli officecli-docx officecli-xlsx officecli-pptx officecli-academic-paper officecli-data-dashboard officecli-financial-model officecli-pitch-deck officecli-word-form morph-ppt morph-ppt-3d; do- test -s "$DSH_HOME/skills/$bundle/SKILL.md"+ test -s "$DSH_HOME/plugins/profile/node_modules/@go-bot/plugin-officecli/skills/$bundle/SKILL.md"done- test -s "$DSH_HOME/skills/morph-ppt/reference/styles/INDEX.md"+ test -s "$DSH_HOME/plugins/profile/node_modules/@go-bot/plugin-officecli/skills/morph-ppt/reference/styles/INDEX.md"`); e != nil {t.Fatalf("unexpected container skills or environment: %v", e)}@@ -210,7 +218,8 @@ func TestDockerHostConversationRecoveryAndFiles(t *testing.T) {_ = readWebTurn(t, otherStream.Body)otherStream.Body.Close()assertDockerSkills(t, manager.Journal(t, ctx, second.SessionID), false, true)- manager.Exec(t, ctx, "rm", "-r", ".dsh/skills/officecli-pitch-deck")+ writeSkill(".dsh/skills/deleted-user-skill/SKILL.md", "---\nname: deleted-user-skill\ndescription: Deleted user skill\n---\nremoved\n")+ manager.Exec(t, ctx, "rm", "-r", ".dsh/skills/deleted-user-skill")beforeStop, e := manager.Store.Get(ctx, manager.account)if e != nil || beforeStop.HostEndpoint != instance.Endpoint {t.Fatalf("running Host route was not saved: %v", e)@@ -247,7 +256,7 @@ func TestDockerHostConversationRecoveryAndFiles(t *testing.T) {t.Fatal(err)}}- manager.Exec(t, ctx, "sh", "-ec", `test ! -e .dsh/skills/officecli-pitch-deck/SKILL.md; test -f .agents/skills/manual/SKILL.md`)+ manager.Exec(t, ctx, "sh", "-ec", `test ! -e .dsh/skills/deleted-user-skill/SKILL.md; test -f .agents/skills/manual/SKILL.md`)oldImageID, e := docker.Run(ctx, nil, "container", "inspect", "--format", "{{.Image}}", instance.Ref.ID)if e != nil {@@ -306,7 +315,7 @@ func TestDockerHostConversationRecoveryAndFiles(t *testing.T) {if status != 200 || string(b) != "harness-output" {t.Fatal("workspace did not survive")}- manager.Exec(t, ctx, "sh", "-ec", `test ! -e .dsh/skills/officecli-pitch-deck/SKILL.md; test -f .agents/skills/manual/SKILL.md`)+ manager.Exec(t, ctx, "sh", "-ec", `test ! -e .dsh/skills/deleted-user-skill/SKILL.md; test -f .agents/skills/manual/SKILL.md`)if calls := modelCalls.Load(); calls < 5 {t.Fatalf("expected model calls for two new turns and a resumed turn, got %d", calls)}diff --git a/tests/integration/host_stream_docker_test.go b/tests/integration/host_stream_docker_test.gonew file mode 100644index 0000000..bfd7d9a--- /dev/null+++ b/tests/integration/host_stream_docker_test.go@@ -0,0 +1,195 @@+package integration++import (+ "bufio"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "testing"+ "time"++ "go-bot/harness/interaction"+ "go-bot/internal/config"+)++func TestDockerHostStreamMultiplexesNewSessionsAndApprovalReconnect(t *testing.T) {+ if os.Getenv("RUN_DOCKER_INTEGRATION") != "1" {+ t.Skip("requires the built Host image")+ }+ ctx, cancel := context.WithTimeout(t.Context(), 70*time.Second)+ defer cancel()+ model := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, _ := io.ReadAll(r.Body)+ output := []map[string]any{{"type": "message", "role": "assistant", "content": []map[string]string{{"type": "output_text", "text": "Completed"}}}}+ if !strings.Contains(string(body), "function_call_output") {+ if strings.Contains(string(body), "approval-fixture") {+ output = []map[string]any{webCall("approval-call", "shellexecute", `{"command":"printf approved-once","sandbox_permissions":"danger-full-access","justification":"Verify one-shot execution approval"}`)}+ } else {+ output = []map[string]any{webCall("question-call", "ask_user_question", `{"questions":[{"id":"choice","question":"Choose?","options":[{"label":"A"},{"label":"B"}]}],"timeout":1}`)}+ }+ }+ payload, _ := json.Marshal(map[string]any{"type": "response.completed", "response": map[string]any{"id": "reply", "status": "completed", "output": output}})+ w.Header().Set("Content-Type", "text/event-stream")+ fmt.Fprintf(w, "event: response.completed\ndata: %s\n\n", payload)+ }))+ listener, err := net.Listen("tcp", "0.0.0.0:0")+ if err != nil {+ t.Fatal(err)+ }+ model.Listener = listener+ model.Start()+ defer model.Close()+ c := dockerFixtureConfig()+ c.Model.Main = config.MainModel{APIKey: "fixture", BaseURL: fmt.Sprintf("http://host.docker.internal:%d", listener.Addr().(*net.TCPAddr).Port), Name: "fixture"}+ m := newFixtureManager(t, c)+ defer func() {+ cleanup, stop := context.WithTimeout(context.Background(), 15*time.Second)+ defer stop()+ if err := m.Delete(cleanup); err != nil {+ t.Error(err)+ }+ }()+ if err := m.Ensure(ctx); err != nil {+ t.Fatal(err)+ }+ server := httptest.NewServer(m.Handler())+ defer server.Close()+ call := func(method, path, body string, want int) []byte {+ t.Helper()+ req, _ := http.NewRequestWithContext(ctx, method, server.URL+path, strings.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ resp, err := server.Client().Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer resp.Body.Close()+ data, _ := io.ReadAll(resp.Body)+ if resp.StatusCode != want {+ t.Fatalf("%s %s: %d %s", method, path, resp.StatusCode, data)+ }+ return data+ }+ type event struct {+ SessionID string `json:"sessionId"`+ Type string `json:"type"`+ Data json.RawMessage `json:"data"`+ }+ connect := func() (<-chan event, func()) {+ t.Helper()+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/v1/host/stream", nil)+ resp, err := server.Client().Do(req)+ if err != nil {+ t.Fatal(err)+ }+ if resp.StatusCode != 200 {+ resp.Body.Close()+ t.Fatalf("Host stream status %d", resp.StatusCode)+ }+ messages := make(chan event, 256)+ go func() {+ defer close(messages)+ scanner := bufio.NewScanner(resp.Body)+ scanner.Buffer(make([]byte, 4096), 2<<20)+ for scanner.Scan() {+ if data, ok := strings.CutPrefix(scanner.Text(), "data: "); ok {+ var e event+ if json.Unmarshal([]byte(data), &e) == nil {+ select {+ case messages <- e:+ case <-ctx.Done():+ return+ }+ }+ }+ }+ }()+ return messages, func() { resp.Body.Close() }+ }+ wait := func(events <-chan event, id, kind string, match func(json.RawMessage) bool) event {+ t.Helper()+ for {+ select {+ case e, ok := <-events:+ if !ok {+ t.Fatal("stream ended before expected event")+ }+ if e.SessionID == id && e.Type == kind && (match == nil || match(e.Data)) {+ return e+ }+ case <-ctx.Done():+ t.Fatalf("waiting for %s %s: %v", id, kind, ctx.Err())+ }+ }+ }+ newSession := func() string {+ var result struct{ SessionID string }+ if err := json.Unmarshal(call("POST", "/v1/sessions", "", 201), &result); err != nil {+ t.Fatal(err)+ }+ return result.SessionID+ }+ pending := func(data json.RawMessage) bool {+ var v struct{ Questions []interaction.Pending }+ _ = json.Unmarshal(data, &v)+ return len(v.Questions) > 0+ }+ // No interactive Host client: a new approval must fail closed rather than+ // silently grant access or wait forever for a client that is not present.+ offline := newSession()+ offlinePath := "/v1/sessions/" + offline+ call("POST", offlinePath+"/permissions", `{"mode":"read-only"}`, 200)+ call("POST", offlinePath+"/messages", `{"content":"approval-fixture"}`, 202)+ for {+ data := call("GET", offlinePath+"/events?limit=200", "", 200)+ if strings.Contains(string(data), `"type":"turn/end"`) {+ break+ }+ select {+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ case <-time.After(30 * time.Millisecond):+ }+ }+ if journal := string(m.Journal(t, ctx, offline)); !strings.Contains(journal, `"outcome":"unavailable"`) {+ t.Fatal("offline approval did not report unavailable")+ }+ events, closeStream := connect()+ wait(events, "", "sessions.changed", nil)+ first := newSession()+ path := "/v1/sessions/" + first+ call("POST", path+"/permissions", `{"mode":"read-only"}`, 200)+ call("POST", path+"/messages", `{"content":"approval-fixture"}`, 202)+ e := wait(events, first, "questions.state", pending)+ var state struct{ Questions []interaction.Pending }+ _ = json.Unmarshal(e.Data, &state)+ if state.Questions[0].Approval == nil {+ t.Fatal("no approval payload")+ }+ approvalID := state.Questions[0].CallID+ closeStream()+ // The same pending identity must survive reconnect, with no Session stream.+ events, closeStream = connect()+ defer closeStream()+ e = wait(events, first, "questions.state", pending)+ _ = json.Unmarshal(e.Data, &state)+ if state.Questions[0].CallID != approvalID {+ t.Fatal("reconnect replaced the pending request")+ }+ call("POST", path+"/questions/"+approvalID+"/answer", `{"answers":[{"id":"approval","selected":["Allow once"]}]}`, 204)+ wait(events, first, "session", func(data json.RawMessage) bool { return strings.Contains(string(data), `"type":"turn/end"`) })+ second := newSession()+ call("POST", "/v1/sessions/"+second+"/messages", `{"content":"question-fixture"}`, 202)+ wait(events, second, "questions.state", pending)+ wait(events, second, "questions.state", func(data json.RawMessage) bool { return strings.Contains(string(data), `"state":"continued"`) })+ // Both Sessions used one stream; a newly activated Session was discovered.+ journal := string(m.Journal(t, ctx, first))+ if !strings.Contains(journal, "allowed-once") || !strings.Contains(journal, "approved-once") {+ t.Fatal("approved call did not execute")+ }+}diff --git a/tests/integration/model_settings_docker_test.go b/tests/integration/model_settings_docker_test.goindex 8a251e2..28fd6da 100644--- a/tests/integration/model_settings_docker_test.go+++ b/tests/integration/model_settings_docker_test.go@@ -37,7 +37,28 @@ func TestDockerModelSettingsSwitchBetweenTurns(t *testing.T) {t.Error(err)return}- calls <- modelCall{r.URL.Path, input.Model, r.Header.Get("Authorization")}+ auth := r.Header.Get("Authorization")+ if strings.HasSuffix(r.URL.Path, "/messages") {+ auth = r.Header.Get("x-api-key")+ }+ calls <- modelCall{r.URL.Path, input.Model, auth}+ if strings.HasSuffix(r.URL.Path, "/messages") {+ if r.Header.Get("anthropic-version") != "2023-06-01" {+ t.Error("missing Anthropic version")+ }+ w.Header().Set("Content-Type", "text/event-stream")+ for _, frame := range []string{+ `{"type":"message_start","message":{"id":"a","usage":{"input_tokens":10}}}`,+ `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,+ `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Done"}}`,+ `{"type":"content_block_stop","index":0}`,+ `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}`,+ `{"type":"message_stop"}`,+ } {+ fmt.Fprintf(w, "data: %s\n\n", frame)+ }+ return+ }output := []map[string]any{{"type": "message", "id": "reply", "role": "assistant", "content": []map[string]string{{"type": "output_text", "text": "Done"}}}}if input.Model == "first" && !strings.Contains(string(body), "function_call_output") {select {@@ -121,7 +142,11 @@ func TestDockerModelSettingsSwitchBetweenTurns(t *testing.T) {}add := func(path, key string, models []string) string {t.Helper()- body, _ := json.Marshal(modelsettings.Endpoint{Name: path, BaseURL: base + path, APIKey: key, Models: models})+ protocol := modelsettings.Responses+ if path == "/second" {+ protocol = modelsettings.AnthropicMessages+ }+ body, _ := json.Marshal(modelsettings.Endpoint{Protocol: protocol, Name: path, BaseURL: base + path, APIKey: key, Models: models})var endpoint struct{ EndpointID string }decode(call("POST", "/v1/settings/models/endpoints", string(body), 201), &endpoint)return endpoint.EndpointID@@ -183,7 +208,7 @@ func TestDockerModelSettingsSwitchBetweenTurns(t *testing.T) {stream = call("GET", fmt.Sprintf("%s/stream?after=%d", path, events[len(events)-1].Seq), "", 200)defer stream.Body.Close()call("POST", path+"/messages", `{"content":"Continue with the second model"}`, 202).Body.Close()- expect(modelCall{"/second/responses", "second", "Bearer second-fixture-key"})+ expect(modelCall{"/second/messages", "second", "second-fixture-key"})readWebTurn(t, stream.Body)stream.Body.Close()if readSelection(other) != first {diff --git a/tests/integration/plugin_store_docker_test.go b/tests/integration/plugin_store_docker_test.gonew file mode 100644index 0000000..fd3b79d--- /dev/null+++ b/tests/integration/plugin_store_docker_test.go@@ -0,0 +1,84 @@+package integration++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "strings"+ "testing"+ "time"++ "go-bot/internal/controller"+ "go-bot/plugin"+ dockerapi "go-bot/thirdparty/docker"+)++func TestDockerPluginSettingsStayInTheUserHash(t *testing.T) {+ if os.Getenv("RUN_DOCKER_INTEGRATION") != "1" {+ t.Skip("requires Docker and the Redis image")+ }+ ctx, cancel := context.WithTimeout(t.Context(), 45*time.Second)+ defer cancel()+ docker := dockerapi.Client{}+ output, err := docker.Run(ctx, nil, "run", "--rm", "-d", "-p", "127.0.0.1::6379", "redis:8-alpine")+ if err != nil {+ t.Fatal(err)+ }+ container := strings.TrimSpace(string(output))+ t.Cleanup(func() {+ cleanup, done := context.WithTimeout(context.Background(), 10*time.Second)+ defer done()+ _, _ = docker.Run(cleanup, nil, "rm", "-f", container)+ })+ output, err = docker.Run(ctx, nil, "port", container, "6379/tcp")+ if err != nil {+ t.Fatal(err)+ }+ address := strings.TrimSpace(string(output))+ var store *controller.RedisStore+ for store == nil {+ store, err = controller.OpenRedis(ctx, address)+ if err == nil {+ break+ }+ select {+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ case <-time.After(50 * time.Millisecond):+ }+ }+ defer store.Close()+ if err = store.Create(ctx, "plugin-fixture", controller.Account{DesiredState: "stopped"}); err != nil {+ t.Fatal(err)+ }+ settings := plugin.Settings{Packages: map[string]plugin.PackageSelection{"@go-bot/plugin-officecli": {CatalogID: "officecli", Version: "0.1.0", Enabled: true}}}++ if err = store.SavePluginSettings(ctx, "plugin-fixture", settings); err != nil {+ t.Fatal(err)+ }+ // Host lifecycle writes must not clobber the independent settings field.+ if err = store.Save(ctx, "plugin-fixture", controller.Account{DesiredState: "running", HostID: "runtime-fixture"}); err != nil {+ t.Fatal(err)+ }+ record, err := store.Get(ctx, "plugin-fixture")+ if err != nil || record.Plugins == nil || len(record.Plugins.Packages) != 1 || !record.Plugins.Packages["@go-bot/plugin-officecli"].Enabled {+ t.Fatalf("account plugin data did not survive lifecycle save: %v", err)+ }+ output, err = docker.Run(ctx, nil, "exec", container, "redis-cli", "--raw", "KEYS", "*")+ if err != nil || strings.TrimSpace(string(output)) != "user:plugin-fixture" {+ t.Fatalf("plugin settings created another Redis key: %q %v", output, err)+ }+ output, err = docker.Run(ctx, nil, "exec", container, "redis-cli", "--raw", "TYPE", "user:plugin-fixture")+ if err != nil || strings.TrimSpace(string(output)) != "hash" {+ t.Fatalf("account is not a Hash: %q %v", output, err)+ }+ output, err = docker.Run(ctx, nil, "exec", container, "redis-cli", "--raw", "HGET", "user:plugin-fixture", "plugins")+ var actual plugin.Settings+ if err != nil || json.Unmarshal(output, &actual) != nil || actual.Packages["@go-bot/plugin-officecli"].Version != "0.1.0" || strings.Contains(string(output), "instances") || strings.Contains(string(output), "source") {+ t.Fatal("saved plugin field is not the expected settings JSON")+ }+ if err = store.SavePluginSettings(ctx, "absent", settings); !errors.Is(err, controller.ErrAccountNotFound) {+ t.Fatalf("missing account write: %v", err)+ }+}diff --git a/tests/integration/web_chat_queue_docker_test.go b/tests/integration/web_chat_queue_docker_test.goindex 617f722..1daea72 100644--- a/tests/integration/web_chat_queue_docker_test.go+++ b/tests/integration/web_chat_queue_docker_test.go@@ -11,6 +11,7 @@ import ("net/http/httptest""net/url""os"+ "reflect""strings""sync/atomic""testing"@@ -235,8 +236,20 @@ func TestDockerWebChatQueueAndQuestions(t *testing.T) {if err := manager.Ensure(ctx); err != nil {t.Fatal(err)}- if cold := read("GET", sessionPath+"/transcript?limit=1", "", 200); cold != latest {- t.Fatalf("cold transcript differs: %s", cold)+ cold := read("GET", sessionPath+"/transcript?limit=1", "", 200)+ var warmPage, coldPage map[string]any+ if err := json.Unmarshal([]byte(latest), &warmPage); err != nil {+ t.Fatal(err)+ }+ if err := json.Unmarshal([]byte(cold), &coldPage); err != nil {+ t.Fatal(err)+ }+ // A loaded runtime includes its transient stream baseline; a cold session+ // has no live stream. Persisted events, cursors and interaction state match.+ delete(warmPage, "baseline")+ delete(coldPage, "baseline")+ if !reflect.DeepEqual(coldPage, warmPage) {+ t.Fatalf("cold transcript differs: warm=%s cold=%s", latest, cold)}if file := read("GET", deliveryPath, "", 200); file != "updated contents" {t.Fatalf("cold delivery is %q", file)diff --git a/tests/upstream-plugins/README.md b/tests/upstream-plugins/README.mdnew file mode 100644index 0000000..6020fcb--- /dev/null+++ b/tests/upstream-plugins/README.md@@ -0,0 +1,62 @@+# Upstream source oracles++These optional differential checks compare the Go built-in MCP OAuth and model+selection behavior with pinned upstream source modules. They do not establish+compatibility with arbitrary upstream Cordis/npm plugins.++Business plugins use the project's own asynchronous `ctx.host` SDK. See+[`extensions/sdk`](../../extensions/sdk/README.md) and+[`examples/plugins`](../../examples/plugins/README.md). The production runtime+uses native Cordis/Loader for lifecycle; Go owns the Agent, Session, tools,+approval, credentials and MCP. There are no plugin tool-stage middleware or+guard interfaces.++## MCP OAuth source interoperability++The pinned upstream source revision is+`ca33fd6843b205e279c7ccb6cb73a472c78f5760`. Its+`packages/mcp/mcp-client/src/oauth-credentials.ts` contains newer OAuth support+than the published `@deepseek-ai/[email protected]` npm artifact. Do not+substitute that older artifact when validating this contract.++With the unedited source module compiled to ESM and its original dependencies+installed, run this opt-in differential test (use an absolute module path):++```sh+GO_BOT_UPSTREAM_MCP_OAUTH_MODULE=/absolute/path/to/upstream-credentials.mjs \+ go test -count=1 -v ./internal/mcpclient \+ -run '^TestOAuthRecordsInteroperateWithPinnedUpstream$'+```++The test runs real local OAuth/MCP servers. Go performs authorization and writes+the shared credential records; the original upstream class reads those records+and refreshes through its SDK; Go then reconnects using the upstream-written+record. It covers dynamic public, dynamic confidential and configured public+clients, without calling a paid model or third-party account. The helper+`mcp-oauth-oracle.mjs` is test code, not a second production credential provider.++## Agent model-selection source oracle++At the same pinned source revision, compile the unedited+`packages/core/agent/src/model-selection.ts` to ESM with its original runtime+dependencies available. Regenerate the projection and AgentModel expectations:++```sh+node tests/upstream-plugins/model-selection-oracle.mjs \+ /absolute/path/to/upstream-model-selection.mjs \+ < harness/session/testdata/model-selection-cases.json \+ > /tmp/model-selection-upstream.json+diff -u harness/session/testdata/model-selection-upstream.json /tmp/model-selection-upstream.json+go test -count=1 ./harness/session -run 'TestModelSelectionMatches|TestConcurrentModelSelect'+```++The 19 actions cover live fallback, explicit selection, deduplication, pending+selection retirement, null selection, changed request routes and adapter-defaulted+effort. The ordinary Go test uses the checked-in source-generated expectations+and reopens an actual JSONL journal. The helper's minimal append recorder is+test-only; production continues using the existing Go Session.+++Core Agent/Session class compatibility, synchronous append and factory lifecycle+oracles are intentionally excluded. Corresponding behavior is tested inside Go;+the plugin boundary is tested through real tool/Skill/MCP/auth contributions.diff --git a/tests/upstream-plugins/mcp-oauth-oracle.mjs b/tests/upstream-plugins/mcp-oauth-oracle.mjsnew file mode 100644index 0000000..168d83a--- /dev/null+++ b/tests/upstream-plugins/mcp-oauth-oracle.mjs@@ -0,0 +1,33 @@+// Optional source-level oracle. The module argument must be compiled, unedited+// oauth-credentials.ts from the pinned DeepSeek Harness source revision.+// npm rc.4's MCP package predates this OAuth implementation; do not silently+// substitute that older published package and claim to have checked OAuth.+import {readFileSync} from 'node:fs'+import {pathToFileURL} from 'node:url'++const {McpOAuthCredentials} = await import(pathToFileURL(process.argv[2]).href)+const input = JSON.parse(readFileSync(0, 'utf8'))+const records = structuredClone(input.records)+const provider = {+ async readRecord(key) { return structuredClone(records[key]) },+ async modifyRecord(key, mutate) {+ const next = await mutate(structuredClone(records[key]))+ if (next !== undefined) records[key] = structuredClone(next)+ return structuredClone(records[key])+ },+}+const credentials = new McpOAuthCredentials({get: name => name === 'credentials' ? provider : undefined}, {+ credentialKey: input.key, ...input.clientId ? {clientId: input.clientId} : {},+ ...input.scope !== undefined ? {scope: input.scope} : {}, requestTimeoutMs: 5000, authorizationTimeoutMs: 10000,+})+const signal = AbortSignal.timeout(10000)+const bound = await credentials.read(input.url, signal)+if (bound.tokens.access_token !== input.accessToken) throw new Error('Upstream did not read the Go grant')+const client = await credentials.client(bound.clientKey, bound.issuer)+if (client?.client_id !== bound.clientId) throw new Error('Upstream did not read the Go client record')+records[input.key].payload.expiresAt = 0+const expired = await credentials.read(input.url, signal)+const transport = credentials.transport(expired, signal, globalThis.fetch)+const token = await transport.authProvider.token()+if (!token || token === input.accessToken) throw new Error('Actual upstream refresh did not rotate the token')+process.stdout.write(JSON.stringify({records, refreshed: true}))diff --git a/tests/upstream-plugins/model-selection-oracle.mjs b/tests/upstream-plugins/model-selection-oracle.mjsnew file mode 100644index 0000000..277612d--- /dev/null+++ b/tests/upstream-plugins/model-selection-oracle.mjs@@ -0,0 +1,27 @@+// Run the unedited pinned model-selection.ts module compiled to ESM. This is+// only a projection/API oracle; it never starts a Node Agent or Session owner.+import {readFileSync} from 'node:fs'+import {pathToFileURL} from 'node:url'++const {AgentModel,modelSelectionProjectionDefinition:projection}=await import(pathToFileURL(process.argv[2]).href)+const actions=JSON.parse(readFileSync(0,'utf8'))+let state=projection.init(),options={},seq=0,selectionEvents=0+const append=(type,data)=>{+ state=projection.apply(state,{type,data,seq:seq++,time:1})+ if(type==='model/selection')selectionEvents+++}+const model=new AgentModel(()=>state,{append},{+ get provider(){return options.provider},get model(){return options.model},get reasoningEffort(){return options.reasoningEffort},+})+append('turn/start',{turn:1})+append('step/start',{turn:1,step:1})+const snapshots=[]+for(const action of actions){+ if(action.kind==='options')options=action.value+ else if(action.kind==='select')model.select(action.value)+ else if(action.kind==='header')append('request/header',{header:action.value})+ else if(action.kind==='clear')append('model/selection',null)+ else if(action.kind!=='read')throw new Error('Unknown oracle action')+ snapshots.push({current:model.current()??null,state:structuredClone(state),seq,selectionEvents})+}+process.stdout.write(JSON.stringify(snapshots,null,2)+'\n')diff --git a/thirdparty/README.md b/thirdparty/README.mdindex 5ee2218..a42570d 100644--- a/thirdparty/README.md+++ b/thirdparty/README.md@@ -7,6 +7,8 @@ and APIs. It is not a dependency cache or a copy of vendor repositories.- docker: CLI access and controlled Host environment injection.- llm: compatible protocol encoding, streaming and transport errors.- deepseek: the dedicated Search API HTTP request/response layer.+- zhipu, doubao, tavily, brave: official search API request/response wrappers;+ Brave uses its LLM Context endpoint. Provider policy remains in providers/web.Actual libraries are resolved by go.mod/go.sum. Capability decisions, instancelifecycles, provider selection and Agent execution belong to their respectivediff --git a/thirdparty/brave/search.go b/thirdparty/brave/search.gonew file mode 100644index 0000000..1485439--- /dev/null+++ b/thirdparty/brave/search.go@@ -0,0 +1,44 @@+// Package brave contains the wire contract for Brave's LLM Context Search API.+package brave++import (+ "context"+ "net/http"++ "go-bot/thirdparty/providerhttp"+)++const Endpoint = "https://api.search.brave.com/res/v1/llm/context"++type Result struct {+ URL string `json:"url"`+ Title string `json:"title"`+ Snippets []string `json:"snippets"`+}++type Source struct {+ Title string `json:"title"`+ Description string `json:"description"`+ Age []string `json:"age"`+}++type Response struct {+ Grounding *struct {+ Results []Result `json:"generic"`+ } `json:"grounding"`+ Sources map[string]Source `json:"sources"`+}++func Search(ctx context.Context, client *http.Client, endpoint, key, query string, count int) (Response, int, error) {+ input := struct {+ Query string `json:"q"`+ Count int `json:"count"`+ URLs int `json:"maximum_number_of_urls"`+ Tokens int `json:"maximum_number_of_tokens"`+ TokensPerURL int `json:"maximum_number_of_tokens_per_url"`+ SourceMetadata bool `json:"enable_source_metadata"`+ }{query, count, count, 8192, 1024, true}+ var output Response+ status, err := providerhttp.Post(ctx, client, endpoint, "X-Subscription-Token", key, input, &output, 4<<20)+ return output, status, err+}diff --git a/thirdparty/llm/anthropic_test.go b/thirdparty/llm/anthropic_test.gonew file mode 100644index 0000000..9a34183--- /dev/null+++ b/thirdparty/llm/anthropic_test.go@@ -0,0 +1,185 @@+package llm++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"+)++func TestAnthropicRequestGroupsToolsAndKeepsImages(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/v1/messages" || r.Header.Get("x-api-key") != "secret" || r.Header.Get("Authorization") != "" || r.Header.Get("anthropic-version") != "2023-06-01" {+ t.Errorf("wrong Anthropic routing/auth: %s", r.URL.Path)+ }+ var body map[string]json.RawMessage+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatal(err)+ }+ if string(body["max_tokens"]) != "16384" || len(body["reasoning"]) != 0 || len(body["thinking"]) != 0 {+ t.Error("invalid default parameters")+ }+ var messages []struct {+ Role string `json:"role"`+ Content []map[string]json.RawMessage `json:"content"`+ }+ _ = json.Unmarshal(body["messages"], &messages)+ if len(messages) != 3 || messages[1].Role != "assistant" || len(messages[1].Content) != 3 || messages[2].Role != "user" || len(messages[2].Content) != 3 {+ t.Fatalf("incorrect grouping: %s", body["messages"])+ }+ if string(messages[2].Content[0]["tool_use_id"]) != `"call_a"` || string(messages[2].Content[1]["tool_use_id"]) != `"call_b"` || string(messages[2].Content[0]["is_error"]) != "true" {+ t.Fatal("tool results or steering were reordered incorrectly")+ }+ var parts []map[string]json.RawMessage+ _ = json.Unmarshal(messages[2].Content[0]["content"], &parts)+ if len(parts) != 2 || !strings.Contains(string(parts[1]["source"]), `"base64"`) {+ t.Fatal("tool image was detached")+ }+ _, _ = io.WriteString(w, `{"id":"msg_1","type":"message","stop_reason":"end_turn","content":[{"type":"text","text":"done"}],"usage":{"input_tokens":10,"cache_read_input_tokens":4,"cache_creation_input_tokens":3,"output_tokens":5}}`)+ }))+ defer server.Close()+ client, _ := NewClient(Endpoint{BaseURL: server.URL + "/v1", APIKey: "secret"}, "custom-model", server.Client())+ result, err := client.GenerateWithProtocol(t.Context(), AnthropicMessages, Request{Input: []Item{+ {Type: "message", Role: "system", Content: []ContentBlock{{Type: "text", Text: "system"}}},+ {Type: "message", Role: "user", Content: []ContentBlock{{Type: "text", Text: "run both"}}},+ {Type: "message", Role: "assistant", Content: []ContentBlock{{Type: "text", Text: "working"}}},+ {Type: "tool_call", CallID: "call_a", Name: "a", Arguments: `{}`}, {Type: "tool_call", CallID: "call_b", Name: "b", Arguments: `{}`},+ {Type: "tool_result", CallID: "call_a", IsError: true, Content: []ContentBlock{{Type: "text", Text: "image"}, {Type: "image", Source: &ImageSource{Type: "url", URL: "data:image/png;base64,aGVsbG8="}}}},+ {Type: "message", Role: "user", Content: []ContentBlock{{Type: "text", Text: "steering"}}},+ {Type: "tool_result", CallID: "call_b", Content: []ContentBlock{{Type: "text", Text: "ok"}}},+ }, Tools: []Tool{{Name: "a", Parameters: json.RawMessage(`{"type":"object"}`)}}, ReasoningEffort: "medium"})+ if err != nil || result.Output[0].Content[0].Text != "done" || result.Usage.InputTokens != 17 || result.Usage.TotalTokens != 22 || result.Usage.CacheCreationTokens != 3 {+ t.Fatalf("response: %+v %v", result, err)+ }+}++func anthropicFrame(kind string, fields string) string {+ if fields != "" {+ fields = "," + fields+ }+ return fmt.Sprintf("event: %s\ndata: {\"type\":%q%s}\n\n", kind, kind, fields)+}+func anthropicToolStream() string {+ return anthropicFrame("message_start", `"message":{"id":"m","usage":{"input_tokens":10,"cache_read_input_tokens":2}}`) ++ anthropicFrame("content_block_start", `"index":0,"content_block":{"type":"thinking","thinking":"","signature":""}`) ++ anthropicFrame("content_block_delta", `"index":0,"delta":{"type":"thinking_delta","thinking":"consider"}`) ++ anthropicFrame("content_block_delta", `"index":0,"delta":{"type":"signature_delta","signature":"signed"}`) ++ anthropicFrame("content_block_stop", `"index":0`) ++ anthropicFrame("content_block_start", `"index":1,"content_block":{"type":"text","text":""}`) ++ anthropicFrame("content_block_delta", `"index":1,"delta":{"type":"text_delta","text":"hello"}`) ++ anthropicFrame("content_block_stop", `"index":1`) ++ anthropicFrame("content_block_start", `"index":2,"content_block":{"type":"tool_use","id":"t1","name":"echo","input":{}}`) ++ anthropicFrame("content_block_delta", `"index":2,"delta":{"type":"input_json_delta","partial_json":"{\"value\":"}`) ++ anthropicFrame("content_block_delta", `"index":2,"delta":{"type":"input_json_delta","partial_json":"\"ok\"}"}`) ++ anthropicFrame("content_block_stop", `"index":2`) ++ anthropicFrame("message_delta", `"delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":5,"cache_creation_input_tokens":3}`) ++ anthropicFrame("message_stop", "")+}+func TestAnthropicStreamingAndNativeReplay(t *testing.T) {+ var events []StreamEvent+ response, err := consumeAnthropicStream(strings.NewReader(anthropicToolStream()), func(e StreamEvent) error { events = append(events, e); return nil }, nil)+ if err != nil || len(response.Output) != 3 || response.Output[2].Arguments != `{"value":"ok"}` || response.Usage.InputTokens != 15 || response.Usage.OutputTokens != 5 {+ t.Fatalf("stream response %+v, %v", response, err)+ }+ if !strings.Contains(string(response.NativeContent[0]), `"signature":"signed"`) || events[1].Type != "reasoning.delta" || events[len(events)-1].Type != "completed" {+ t.Fatal("lost signed thinking or live deltas")+ }+ raw, _ := json.Marshal(response.NativeContent)+ body, err := encodeAnthropic("m", Request{Input: []Item{{Type: "message", Role: "user", Content: []ContentBlock{{Type: "text", Text: "do it"}}}, {Type: "anthropic_message", Raw: raw}, {Type: "tool_result", CallID: "t1", Content: []ContentBlock{{Type: "text", Text: "done"}}}}}, true)+ if err != nil || !strings.Contains(string(body), `"signature":"signed"`) {+ t.Fatalf("native replay: %s %v", body, err)+ }+}+func TestAnthropicRejectsIncompleteOrFailedStreams(t *testing.T) {+ full := anthropicToolStream()+ cases := []string{strings.TrimSuffix(full, anthropicFrame("message_stop", "")), strings.TrimSuffix(full, "\n\n"), anthropicFrame("error", `"error":{"type":"overloaded_error","message":"busy"}`), anthropicFrame("content_block_delta", `"index":0,"delta":{"type":"text_delta","text":"bad"}`), strings.Replace(full, `\"ok\"}`, `oops`, 1)}+ for i, stream := range cases {+ completed := false+ _, err := consumeAnthropicStream(strings.NewReader(stream), func(e StreamEvent) error { completed = completed || e.Type == "completed"; return nil }, nil)+ if err == nil || completed {+ t.Errorf("case %d accepted corrupt stream: %v", i, err)+ }+ }+}+func TestAnthropicStopReasonsAndErrors(t *testing.T) {+ for _, reason := range []string{"max_tokens", "refusal", "pause_turn", "model_context_window_exceeded"} {+ response, err := decodeAnthropic([]byte(fmt.Sprintf(`{"id":"m","stop_reason":%q,"content":[{"type":"text","text":"partial"}],"usage":{}}`, reason)))+ if err == nil || response == nil || response.Status == "completed" {+ t.Fatalf("unsafe stop reason %s", reason)+ }+ }+ err := decodeAPIError(401, []byte(`{"error":{"type":"authentication_error","message":"invalid key"}}`))+ var apiErr *APIError+ if !errors.As(err, &apiErr) || apiErr.Code != "authentication_error" {+ t.Fatal(err)+ }+ _, err = encodeAnthropic("m", Request{Input: []Item{{Type: "tool_call", CallID: "orphan", Name: "echo", Arguments: `{}`}}}, false)+ if err == nil {+ t.Fatal("unpaired call accepted")+ }+ _, err = decodeAnthropic([]byte(`{"stop_reason":"end_turn","content":[],"usage":{"input_tokens":9223372036854775807,"output_tokens":1}}`))+ if err == nil {+ t.Fatal("overflowed usage accepted")+ }+}+func TestAnthropicStreamingCancellationAndLiveDelta(t *testing.T) {+ entered := make(chan struct{})+ delta := make(chan struct{}, 1)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "text/event-stream")+ _, _ = io.WriteString(w, anthropicFrame("message_start", `"message":{"id":"m","usage":{}}`)+anthropicFrame("content_block_start", `"index":0,"content_block":{"type":"text","text":""}`)+anthropicFrame("content_block_delta", `"index":0,"delta":{"type":"text_delta","text":"live"}`))+ w.(http.Flusher).Flush()+ close(entered)+ <-r.Context().Done()+ }))+ defer server.Close()+ client, _ := NewClient(Endpoint{BaseURL: server.URL, APIKey: "k"}, "m", server.Client())+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ done := make(chan error, 1)+ go func() {+ _, err := client.StreamWithProtocol(ctx, AnthropicMessages, Request{Input: []Item{{Type: "message", Role: "user", Content: []ContentBlock{{Type: "text", Text: "hello"}}}}}, func(e StreamEvent) error {+ if e.Type == "message.delta" {+ delta <- struct{}{}+ }+ return nil+ })+ done <- err+ }()+ <-entered+ select {+ case <-delta:+ case <-time.After(time.Second):+ t.Fatal("buffered live delta")+ }+ cancel()+ select {+ case err := <-done:+ if !errors.Is(err, context.Canceled) {+ t.Fatal(err)+ }+ case <-time.After(time.Second):+ t.Fatal("cancel did not close stream")+ }+}++func TestAnthropicDoesNotForwardSecretsOnRedirect(t *testing.T) {+ reached := false+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached = true; w.WriteHeader(200) }))+ defer target.Close()+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect)+ }))+ defer origin.Close()+ client, _ := NewClient(Endpoint{BaseURL: origin.URL, APIKey: "private-key"}, "model", origin.Client())+ _, err := client.GenerateWithProtocol(t.Context(), AnthropicMessages, Request{Input: []Item{{Type: "message", Role: "user", Content: []ContentBlock{{Type: "text", Text: "hello"}}}}})+ if err == nil || reached {+ t.Fatal("model credentials followed redirect")+ }+}diff --git a/thirdparty/llm/client.go b/thirdparty/llm/client.goindex 7e1ff84..ab345e9 100644--- a/thirdparty/llm/client.go+++ b/thirdparty/llm/client.go@@ -60,7 +60,9 @@ func NewClient(endpoint Endpoint, model string, httpClient *http.Client) (*Clienif httpClient == nil {httpClient = &http.Client{Timeout: 5 * time.Minute}}- return &Client{endpoint: Endpoint{BaseURL: base, APIKey: strings.TrimSpace(endpoint.APIKey)}, model: strings.TrimSpace(model), http: httpClient}, nil+ safeHTTP := *httpClient+ safeHTTP.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }+ return &Client{endpoint: Endpoint{BaseURL: base, APIKey: strings.TrimSpace(endpoint.APIKey)}, model: strings.TrimSpace(model), http: &safeHTTP}, nil}func (c *Client) Generate(ctx context.Context, request Request) (*Response, error) {@@ -84,7 +86,7 @@ func (c *Client) GenerateWithProtocol(ctx context.Context, protocol Protocol, re}()pulse = func() { timer.Reset(c.nonStreamingIdleTimeout) }}- res, err := c.post(requestCtx, path, body, false)+ res, err := c.post(requestCtx, protocol, path, body, false)if err != nil {return nil, idleRequestError(requestCtx, errRequestIdle, err)}@@ -107,6 +109,8 @@ func (c *Client) GenerateWithProtocol(ctx context.Context, protocol Protocol, rereturn nil, decodeAPIError(res.StatusCode, data)}switch protocol {+ case AnthropicMessages:+ return decodeAnthropic(data)case Responses:return decodeResponses(data)case ChatCompletions:@@ -136,13 +140,20 @@ func idleRequestError(ctx context.Context, idle, err error) error {return err}-func (c *Client) post(ctx context.Context, path string, body []byte, stream bool) (*http.Response, error) {+func (c *Client) post(ctx context.Context, protocol Protocol, path string, body []byte, stream bool) (*http.Response, error) {req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint.BaseURL+path, bytes.NewReader(body))if err != nil {return nil, err}if c.endpoint.APIKey != "" {- req.Header.Set("Authorization", "Bearer "+c.endpoint.APIKey)+ if protocol == AnthropicMessages {+ req.Header.Set("x-api-key", c.endpoint.APIKey)+ } else {+ req.Header.Set("Authorization", "Bearer "+c.endpoint.APIKey)+ }+ }+ if protocol == AnthropicMessages {+ req.Header.Set("anthropic-version", "2023-06-01")}req.Header.Set("Content-Type", "application/json")if stream {@@ -163,6 +174,9 @@ func (c *Client) requestBody(protocol Protocol, request Request, stream bool) (sreturn "", nil, fmt.Errorf("negative maximum output tokens")}switch protocol {+ case AnthropicMessages:+ body, err := encodeAnthropic(c.model, request, stream)+ return "/messages", body, errcase Responses:input, err := encodeResponsesInput(request.Input)if err != nil {@@ -214,10 +228,14 @@ func decodeAPIError(status int, data []byte) error {var payload struct {Error struct {Code string `json:"code"`+ Type string `json:"type"`Message string `json:"message"`} `json:"error"`}_ = json.Unmarshal(data, &payload)+ if payload.Error.Code == "" {+ payload.Error.Code = payload.Error.Type+ }message := payload.Error.Messageif message == "" {message = fmt.Sprintf("LLM API returned HTTP %d", status)diff --git a/thirdparty/llm/decode_anthropic.go b/thirdparty/llm/decode_anthropic.gonew file mode 100644index 0000000..9f74d12--- /dev/null+++ b/thirdparty/llm/decode_anthropic.go@@ -0,0 +1,101 @@+package llm++import (+ "encoding/json"+ "fmt"+ "math"+)++type anthropicUsage struct {+ Input int64 `json:"input_tokens"`+ Output int64 `json:"output_tokens"`+ Read int64 `json:"cache_read_input_tokens"`+ Write int64 `json:"cache_creation_input_tokens"`+}++func (u anthropicUsage) valid() bool {+ return u.Input >= 0 && u.Output >= 0 && u.Read >= 0 && u.Write >= 0 && u.Read <= math.MaxInt64-u.Write && u.Input <= math.MaxInt64-u.Read-u.Write && u.Output <= math.MaxInt64-u.Input-u.Read-u.Write+}++func (u anthropicUsage) usage() *Usage {+ input := u.Input + u.Read + u.Write+ return &Usage{InputTokens: input, OutputTokens: u.Output, TotalTokens: input + u.Output, CachedTokens: u.Read, CacheCreationTokens: u.Write}+}++func anthropicItem(raw json.RawMessage, partial bool) (Item, error) {+ var b struct {+ Type string `json:"type"`+ Text string `json:"text"`+ Thinking string `json:"thinking"`+ ID string `json:"id"`+ Name string `json:"name"`+ Input json.RawMessage `json:"input"`+ }+ if err := json.Unmarshal(raw, &b); err != nil {+ return Item{}, err+ }+ switch b.Type {+ case "text":+ return Item{Type: "message", Role: "assistant", Content: []ContentBlock{{Type: "text", Text: b.Text}}}, nil+ case "thinking":+ return Item{Type: "reasoning", Content: []ContentBlock{{Type: "text", Text: b.Thinking}}}, nil+ case "redacted_thinking":+ return Item{Type: "reasoning"}, nil+ case "tool_use":+ var object map[string]json.RawMessage+ if b.ID == "" || b.Name == "" || !partial && (json.Unmarshal(b.Input, &object) != nil || object == nil) {+ return Item{}, fmt.Errorf("invalid Anthropic tool use")+ }+ return Item{Type: "tool_call", CallID: b.ID, Name: b.Name, Arguments: string(b.Input)}, nil+ default:+ return Item{}, fmt.Errorf("unsupported Anthropic output block %q", b.Type)+ }+}+func anthropicFinish(result *Response, reason string) error {+ result.FinishReason = reason+ switch reason {+ case "end_turn", "stop_sequence", "tool_use":+ result.Status = "completed"+ return nil+ case "max_tokens":+ result.Status = "incomplete"+ result.FinishReason = "max_output_tokens"+ return fmt.Errorf("Anthropic response reached max_tokens")+ case "refusal":+ result.Status = "refusal"+ return &APIError{Code: "content_policy", Message: "Anthropic refused this request"}+ case "model_context_window_exceeded":+ result.Status = "incomplete"+ return &APIError{Code: "context_length_exceeded", Message: "Anthropic model context length exceeded"}+ default:+ result.Status = "incomplete"+ return fmt.Errorf("unsupported Anthropic stop reason %q", reason)+ }+}+func decodeAnthropic(data []byte) (*Response, error) {+ var wire struct {+ ID string `json:"id"`+ Type string `json:"type"`+ Content []json.RawMessage `json:"content"`+ StopReason string `json:"stop_reason"`+ Usage anthropicUsage `json:"usage"`+ }+ if err := json.Unmarshal(data, &wire); err != nil {+ return nil, fmt.Errorf("decode Anthropic message: %w", err)+ }+ if wire.Type == "error" {+ return nil, decodeAPIError(0, data)+ }+ if !wire.Usage.valid() {+ return nil, fmt.Errorf("invalid Anthropic token usage")+ }+ result := &Response{ID: wire.ID, Usage: wire.Usage.usage(), NativeContent: wire.Content}+ for _, raw := range wire.Content {+ item, err := anthropicItem(raw, wire.StopReason == "max_tokens")+ if err != nil {+ return result, err+ }+ result.Output = append(result.Output, item)+ }+ return result, anthropicFinish(result, wire.StopReason)+}diff --git a/thirdparty/llm/encode_anthropic.go b/thirdparty/llm/encode_anthropic.gonew file mode 100644index 0000000..06d754f--- /dev/null+++ b/thirdparty/llm/encode_anthropic.go@@ -0,0 +1,192 @@+package llm++import (+ "encoding/base64"+ "encoding/json"+ "fmt"+ "strings"+)++type anthropicMessage struct {+ Role string `json:"role"`+ Content []any `json:"content"`+}++// encodeAnthropic keeps tool results attached to their call, and groups parallel+// results before any queued user text in the following user message.+func encodeAnthropic(model string, request Request, stream bool) ([]byte, error) {+ var system []any+ messages := []anthropicMessage{}+ pending := map[string]bool{}+ add := func(role string, blocks []any, result bool) error {+ if len(blocks) == 0 {+ return nil+ }+ if role != "user" && role != "assistant" {+ return fmt.Errorf("unsupported Anthropic role %q", role)+ }+ if role == "assistant" && len(pending) > 0 && (len(messages) == 0 || messages[len(messages)-1].Role != "assistant") {+ return fmt.Errorf("Anthropic tool calls are missing results")+ }+ if len(messages) == 0 || messages[len(messages)-1].Role != role {+ messages = append(messages, anthropicMessage{Role: role, Content: []any{}})+ }+ last := &messages[len(messages)-1]+ if result {+ // Results must precede text, including steering admitted between tools.+ pos := 0+ for pos < len(last.Content) {+ b, ok := last.Content[pos].(map[string]any)+ if !ok || b["type"] != "tool_result" {+ break+ }+ pos+++ }+ next := append([]any{}, last.Content[:pos]...)+ next = append(next, blocks...)+ last.Content = append(next, last.Content[pos:]...)+ } else {+ last.Content = append(last.Content, blocks...)+ }+ return nil+ }+ for _, item := range request.Input {+ switch item.Type {+ case "message":+ parts, err := anthropicParts(item.Content)+ if err != nil {+ return nil, err+ }+ if item.Role == "system" || item.Role == "developer" {+ system = append(system, parts...)+ continue+ }+ if err := add(item.Role, parts, false); err != nil {+ return nil, err+ }+ case "reasoning":+ // Portable reasoning text has no Anthropic signature. Only native messages+ // from the same endpoint/model may replay verified thinking blocks.+ case "anthropic_message":+ if len(pending) > 0 {+ return nil, fmt.Errorf("Anthropic native message before pending tool results")+ }+ var blocks []json.RawMessage+ if err := json.Unmarshal(item.Raw, &blocks); err != nil {+ return nil, fmt.Errorf("invalid native Anthropic content: %w", err)+ }+ parts := make([]any, 0, len(blocks))+ nextPending := map[string]bool{}+ for _, raw := range blocks {+ var b struct {+ Type string `json:"type"`+ ID string `json:"id"`+ }+ if err := json.Unmarshal(raw, &b); err != nil {+ return nil, err+ }+ if b.Type == "tool_use" {+ if b.ID == "" || nextPending[b.ID] {+ return nil, fmt.Errorf("invalid native tool call ID")+ }+ nextPending[b.ID] = true+ }+ parts = append(parts, json.RawMessage(raw))+ }+ if err := add("assistant", parts, false); err != nil {+ return nil, err+ }+ pending = nextPending+ case "tool_call":+ var input map[string]json.RawMessage+ if item.CallID == "" || item.Name == "" || json.Unmarshal([]byte(item.Arguments), &input) != nil || input == nil {+ return nil, fmt.Errorf("invalid Anthropic tool call")+ }+ if pending[item.CallID] {+ return nil, fmt.Errorf("duplicate Anthropic tool call ID")+ }+ if err := add("assistant", []any{map[string]any{"type": "tool_use", "id": item.CallID, "name": item.Name, "input": input}}, false); err != nil {+ return nil, err+ }+ pending[item.CallID] = true+ case "tool_result":+ if !pending[item.CallID] {+ return nil, fmt.Errorf("Anthropic tool result has no pending call %q", item.CallID)+ }+ parts, err := anthropicParts(item.Content)+ if err != nil {+ return nil, err+ }+ if err := add("user", []any{map[string]any{"type": "tool_result", "tool_use_id": item.CallID, "content": parts, "is_error": item.IsError}}, true); err != nil {+ return nil, err+ }+ delete(pending, item.CallID)+ default:+ return nil, fmt.Errorf("unsupported Anthropic input item %q", item.Type)+ }+ }+ if len(pending) > 0 {+ return nil, fmt.Errorf("Anthropic tool calls are missing results")+ }+ maxTokens := request.MaxOutputTokens+ if maxTokens == 0 {+ maxTokens = 16 * 1024+ }+ payload := map[string]any{"model": model, "messages": messages, "max_tokens": maxTokens, "stream": stream}+ if len(system) > 0 {+ payload["system"] = system+ }+ if len(request.Tools) > 0 {+ tools := make([]any, 0, len(request.Tools))+ for _, tool := range request.Tools {+ tools = append(tools, map[string]any{"name": tool.Name, "description": tool.Description, "input_schema": toolParameters(tool)})+ }+ payload["tools"] = tools+ choice := defaultToolChoice(request.ToolChoice)+ if choice == "required" {+ choice = "any"+ }+ if choice != "auto" && choice != "any" && choice != "none" {+ return nil, fmt.Errorf("unsupported Anthropic tool choice %q", choice)+ }+ payload["tool_choice"] = map[string]string{"type": choice}+ }+ return json.Marshal(payload)+}++func anthropicParts(blocks []ContentBlock) ([]any, error) {+ parts := []any{}+ for _, b := range blocks {+ switch b.Type {+ case "text":+ if b.Text != "" {+ parts = append(parts, map[string]string{"type": "text", "text": b.Text})+ }+ case "image":+ if b.Source == nil || b.Source.Type != "url" || b.Source.URL == "" {+ return nil, fmt.Errorf("image must be resolved before Anthropic request")+ }+ source := map[string]string{"type": "url", "url": b.Source.URL}+ if strings.HasPrefix(b.Source.URL, "data:") {+ header, data, ok := strings.Cut(strings.TrimPrefix(b.Source.URL, "data:"), ",")+ mime, encoded := strings.CutSuffix(header, ";base64")+ if !ok || !encoded {+ return nil, fmt.Errorf("invalid Anthropic image data URL")+ }+ switch mime {+ case "image/jpeg", "image/png", "image/gif", "image/webp":+ default:+ return nil, fmt.Errorf("unsupported Anthropic image type %q", mime)+ }+ if _, err := base64.StdEncoding.DecodeString(data); err != nil {+ return nil, fmt.Errorf("invalid image base64: %w", err)+ }+ source = map[string]string{"type": "base64", "media_type": mime, "data": data}+ }+ parts = append(parts, map[string]any{"type": "image", "source": source})+ default:+ return nil, fmt.Errorf("unsupported Anthropic content %q", b.Type)+ }+ }+ return parts, nil+}diff --git a/thirdparty/llm/model_error.go b/thirdparty/llm/model_error.goindex bb95000..9f8e4b3 100644--- a/thirdparty/llm/model_error.go+++ b/thirdparty/llm/model_error.go@@ -183,9 +183,9 @@ func classifyModelError(endpoint, model string, status int, upstreamCode, messagcode = ModelErrorBillingOrQuotaExhaustedcase containsAny(text, "permission denied", "accessdenied", "access denied", "forbidden", "model.accessdenied"):code = ModelErrorPermissionDenied- case containsAny(text, "datainspectionfailed", "data_inspection_failed", "sensitive content", "inappropriate content", "content policy"):+ case containsAny(text, "datainspectionfailed", "data_inspection_failed", "sensitive content", "inappropriate content", "content policy", "content_policy", "refusal"):code = ModelErrorContentPolicyRejected- case containsAny(text, "context length", "context_length", "ai_context_limit_exceeded", "maximum context", "token length exceed", "too many tokens"):+ case containsAny(text, "context length", "context_length", "ai_context_limit_exceeded", "maximum context", "token length exceed", "too many tokens", "prompt is too long", "model_context_window_exceeded"):code = ModelErrorContextLimitExceededcase containsAny(text, "model not found", "model_not_found", "model does not exist", "model not exist", "endpoint not found"):code = ModelErrorModelNotFound@@ -215,7 +215,7 @@ func classifyModelError(endpoint, model string, status int, upstreamCode, messagcode = ModelErrorUpstreamInternalcase containsAny(text, "connection reset", "broken pipe", "connection refused", "no such host", "network is unreachable", "tls handshake", "connection error", "dial tcp"):code = ModelErrorUpstreamNetwork- case status == http.StatusBadRequest || containsAny(text, "invalid parameter", "invalid_parameter", "invalid request", "bad request"):+ case status == http.StatusBadRequest || containsAny(text, "invalid parameter", "invalid_parameter", "invalid request", "invalid_request", "bad request"):code = ModelErrorInvalidRequestcase status == http.StatusUnauthorized:code = ModelErrorAuthenticationFaileddiff --git a/thirdparty/llm/stream.go b/thirdparty/llm/stream.goindex 0a09fe7..7253d1b 100644--- a/thirdparty/llm/stream.go+++ b/thirdparty/llm/stream.go@@ -43,7 +43,7 @@ func (c *Client) StreamWithProtocol(ctx context.Context, protocol Protocol, requ}()pulse = func() { timer.Reset(c.nonStreamingIdleTimeout) }}- res, err := c.post(requestCtx, path, body, true)+ res, err := c.post(requestCtx, protocol, path, body, true)if err != nil {return nil, idleRequestError(requestCtx, errRequestIdle, err)}@@ -67,6 +67,8 @@ func (c *Client) StreamWithProtocol(ctx context.Context, protocol Protocol, requ}var result *Responseswitch protocol {+ case AnthropicMessages:+ result, err = consumeAnthropicStream(res.Body, sink, pulse)case Responses:result, err = consumeResponsesStream(res.Body, sink, pulse)case ChatCompletions:diff --git a/thirdparty/llm/stream_anthropic.go b/thirdparty/llm/stream_anthropic.gonew file mode 100644index 0000000..a1eab44--- /dev/null+++ b/thirdparty/llm/stream_anthropic.go@@ -0,0 +1,253 @@+package llm++import (+ "encoding/json"+ "fmt"+ "io"+)++type anthropicStreamBlock struct {+ raw map[string]any+ args string+ fragmented bool+ closed bool+}++func (b *anthropicStreamBlock) item() (Item, error) {+ if b.raw["type"] == "tool_use" && b.fragmented {+ return Item{Type: "tool_call", CallID: stringField(b.raw, "id"), Name: stringField(b.raw, "name"), Arguments: b.args}, nil+ }+ data, err := json.Marshal(b.raw)+ if err != nil {+ return Item{}, err+ }+ return anthropicItem(data, true)+}+func stringField(m map[string]any, key string) string { s, _ := m[key].(string); return s }++func consumeAnthropicStream(body io.Reader, sink StreamSink, activity func()) (*Response, error) {+ result := &Response{}+ blocks := []*anthropicStreamBlock{}+ var usage anthropicUsage+ var started, deltaReceived, finished bool+ var reason string+ err := readSSE(body, func(data []byte) (bool, error) {+ var event struct {+ Type string `json:"type"`+ Index int `json:"index"`+ Block map[string]any `json:"content_block"`+ Message struct {+ ID string `json:"id"`+ Usage json.RawMessage `json:"usage"`+ } `json:"message"`+ Delta struct {+ Type string `json:"type"`+ Text string `json:"text"`+ Thinking string `json:"thinking"`+ Signature string `json:"signature"`+ Partial string `json:"partial_json"`+ StopReason string `json:"stop_reason"`+ } `json:"delta"`+ Usage json.RawMessage `json:"usage"`+ }+ if err := json.Unmarshal(data, &event); err != nil {+ return false, fmt.Errorf("decode Anthropic stream: %w", err)+ }+ switch event.Type {+ case "ping":+ return false, nil+ case "error":+ return false, decodeAPIError(0, data)+ case "message_start":+ if started {+ return false, fmt.Errorf("duplicate Anthropic message_start")+ }+ started = true+ result.ID = event.Message.ID+ if err := mergeAnthropicUsage(&usage, event.Message.Usage); err != nil {+ return false, err+ }+ case "content_block_start":+ if !started || deltaReceived || event.Index != len(blocks) || event.Block == nil {+ return false, fmt.Errorf("invalid Anthropic block start")+ }+ block := &anthropicStreamBlock{raw: event.Block}+ blocks = append(blocks, block)+ item, err := block.item()+ if err != nil {+ return false, err+ }+ if err := sink(StreamEvent{Type: "anthropic.block.start", OutputIndex: event.Index, Item: &item}); err != nil {+ return false, err+ }+ case "content_block_delta":+ if event.Index < 0 || event.Index >= len(blocks) || blocks[event.Index].closed || deltaReceived {+ return false, fmt.Errorf("Anthropic delta outside open block")+ }+ block := blocks[event.Index]+ emitted := StreamEvent{OutputIndex: event.Index}+ switch event.Delta.Type {+ case "text_delta":+ if block.raw["type"] != "text" {+ return false, fmt.Errorf("Anthropic text delta changed block type")+ }+ block.raw["text"] = stringField(block.raw, "text") + event.Delta.Text+ emitted.Type = "message.delta"+ emitted.Delta = event.Delta.Text+ case "thinking_delta":+ if block.raw["type"] != "thinking" {+ return false, fmt.Errorf("Anthropic thinking delta changed block type")+ }+ block.raw["thinking"] = stringField(block.raw, "thinking") + event.Delta.Thinking+ emitted.Type = "reasoning.delta"+ emitted.Delta = event.Delta.Thinking+ case "signature_delta":+ if block.raw["type"] != "thinking" {+ return false, fmt.Errorf("Anthropic signature outside thinking")+ }+ block.raw["signature"] = stringField(block.raw, "signature") + event.Delta.Signature+ return false, nil+ case "input_json_delta":+ if block.raw["type"] != "tool_use" {+ return false, fmt.Errorf("Anthropic input delta outside tool")+ }+ block.fragmented = true+ block.args += event.Delta.Partial+ emitted.Type = "tool_call.arguments.delta"+ emitted.Delta = event.Delta.Partial+ default:+ return false, nil // Protocol permits new delta types.+ }+ item, err := block.item()+ if err != nil {+ return false, err+ }+ emitted.Item = &item+ return false, sink(emitted)+ case "content_block_stop":+ if event.Index < 0 || event.Index >= len(blocks) || blocks[event.Index].closed || deltaReceived {+ return false, fmt.Errorf("invalid Anthropic block stop")+ }+ block := blocks[event.Index]+ block.closed = true+ item, err := block.item()+ if err != nil {+ return false, err+ }+ return false, sink(StreamEvent{Type: "anthropic.block.stop", OutputIndex: event.Index, Item: &item})+ case "message_delta":+ if !started {+ return false, fmt.Errorf("Anthropic message delta before start")+ }+ for _, block := range blocks {+ if !block.closed {+ return false, fmt.Errorf("Anthropic message ended with open block")+ }+ }+ deltaReceived = true+ if event.Delta.StopReason != "" {+ reason = event.Delta.StopReason+ }+ if err := mergeAnthropicUsage(&usage, event.Usage); err != nil {+ return false, err+ }+ case "message_stop":+ if !started || !deltaReceived || reason == "" {+ return false, fmt.Errorf("Anthropic stop without final delta")+ }+ for _, block := range blocks {+ if !block.closed {+ return false, fmt.Errorf("Anthropic stop with open block")+ }+ item, err := block.item()+ if err != nil {+ return false, err+ }+ if block.raw["type"] == "tool_use" {+ var object map[string]json.RawMessage+ if json.Unmarshal([]byte(item.Arguments), &object) != nil || object == nil {+ if reason != "max_tokens" {+ return false, fmt.Errorf("invalid Anthropic tool arguments JSON")+ }+ } else {+ block.raw["input"] = object+ }+ }+ result.Output = append(result.Output, item)+ raw, err := json.Marshal(block.raw)+ if err != nil {+ return false, err+ }+ result.NativeContent = append(result.NativeContent, raw)+ }+ if !usage.valid() {+ return false, fmt.Errorf("invalid Anthropic token usage")+ }+ result.Usage = usage.usage()+ finishErr := anthropicFinish(result, reason)+ if finishErr != nil && reason != "max_tokens" {+ return false, finishErr+ }+ if err := sink(StreamEvent{Type: "completed", Response: result}); err != nil {+ return false, err+ }+ finished = true+ return true, finishErr+ default:+ return false, nil+ }+ return false, nil+ }, activity)+ if !finished && len(result.Output) == 0 {+ for _, b := range blocks {+ if item, e := b.item(); e == nil {+ result.Output = append(result.Output, item)+ }+ }+ }+ if started && usage.valid() {+ result.Usage = usage.usage()+ }+ if err != nil {+ return result, err+ }+ if !finished {+ return result, fmt.Errorf("Anthropic stream ended without message_stop: %w", io.ErrUnexpectedEOF)+ }+ return result, nil+}++func mergeAnthropicUsage(dst *anthropicUsage, raw json.RawMessage) error {+ if len(raw) == 0 {+ return nil+ }+ var fields map[string]int64+ // usage may include nested cache details; only decode known counters.+ var parts map[string]json.RawMessage+ if err := json.Unmarshal(raw, &parts); err != nil {+ return err+ }+ fields = map[string]int64{}+ for _, key := range []string{"input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"} {+ if value, ok := parts[key]; ok {+ var count int64+ if err := json.Unmarshal(value, &count); err != nil || count < 0 {+ return fmt.Errorf("invalid Anthropic usage %s", key)+ }+ fields[key] = count+ }+ }+ if v, ok := fields["input_tokens"]; ok {+ dst.Input = v+ }+ if v, ok := fields["output_tokens"]; ok {+ dst.Output = v+ }+ if v, ok := fields["cache_read_input_tokens"]; ok {+ dst.Read = v+ }+ if v, ok := fields["cache_creation_input_tokens"]; ok {+ dst.Write = v+ }+ return nil+}diff --git a/thirdparty/llm/types.go b/thirdparty/llm/types.goindex db71e0a..9cddff1 100644--- a/thirdparty/llm/types.go+++ b/thirdparty/llm/types.go@@ -1,5 +1,5 @@// Package llm provides endpoint-based clients for OpenAI-compatible language-// model APIs. It does not know about application sessions or local resources.+// model APIs and Anthropic Messages. It does not know about application sessions or local resources.package llmimport "encoding/json"@@ -7,8 +7,9 @@ import "encoding/json"type Protocol stringconst (- Responses Protocol = "responses"- ChatCompletions Protocol = "chat_completions"+ Responses Protocol = "responses"+ ChatCompletions Protocol = "chat_completions"+ AnthropicMessages Protocol = "anthropic_messages")type Endpoint struct {@@ -33,6 +34,7 @@ type ContentBlock struct {// Item is one ordered model input or output item. Optional upstream fields// remain optional here; an agent decides whether a tool call is executable.type Item struct {+ IsError bool `json:"isError,omitempty"`Type string `json:"type"`ID string `json:"id,omitempty"`Role string `json:"role,omitempty"`@@ -53,7 +55,8 @@ func (i Item) MarshalJSON() ([]byte, error) {Type string `json:"type"`CallID string `json:"callId,omitempty"`Content []ContentBlock `json:"content"`- }{i.Type, i.CallID, content})+ IsError bool `json:"isError,omitempty"`+ }{i.Type, i.CallID, content, i.IsError})}if i.Type != "message" && i.Type != "reasoning" && i.Type != "tool_call" && len(i.Raw) > 0 {return append([]byte(nil), i.Raw...), nil@@ -74,6 +77,7 @@ func (i *Item) UnmarshalJSON(data []byte) error {Type string `json:"type"`CallID string `json:"callId"`Content json.RawMessage `json:"content"`+ IsError bool `json:"isError"`}if err := json.Unmarshal(data, &value); err != nil {return err@@ -82,7 +86,7 @@ func (i *Item) UnmarshalJSON(data []byte) error {if err := json.Unmarshal(value.Content, &content); err != nil {return err}- *i = Item{Type: value.Type, CallID: value.CallID, Content: content, Raw: append(json.RawMessage(nil), data...)}+ *i = Item{IsError: value.IsError, Type: value.Type, CallID: value.CallID, Content: content, Raw: append(json.RawMessage(nil), data...)}return nil}if kind.Type != "message" && kind.Type != "reasoning" && kind.Type != "tool_call" {@@ -121,20 +125,23 @@ type Request struct {}type Usage struct {- InputTokens int64 `json:"inputTokens"`- OutputTokens int64 `json:"outputTokens"`- TotalTokens int64 `json:"totalTokens"`- CachedTokens int64 `json:"cachedTokens,omitempty"`+ InputTokens int64 `json:"inputTokens"`+ OutputTokens int64 `json:"outputTokens"`+ TotalTokens int64 `json:"totalTokens"`+ CachedTokens int64 `json:"cachedTokens,omitempty"`+ CacheCreationTokens int64 `json:"cacheCreationTokens,omitempty"`// A subset of OutputTokens, never added again to the request total.ReasoningTokens int64 `json:"reasoningTokens,omitempty"`}type Response struct {- ID string `json:"id,omitempty"`- Status string `json:"status,omitempty"`- FinishReason string `json:"finishReason,omitempty"`- Output []Item `json:"output"`- Usage *Usage `json:"usage,omitempty"`+ // NativeContent is provider replay data, never a public transcript block.+ NativeContent []json.RawMessage `json:"-"`+ ID string `json:"id,omitempty"`+ Status string `json:"status,omitempty"`+ FinishReason string `json:"finishReason,omitempty"`+ Output []Item `json:"output"`+ Usage *Usage `json:"usage,omitempty"`}type APIError struct {diff --git a/thirdparty/tavily/search.go b/thirdparty/tavily/search.gonew file mode 100644index 0000000..bc6401d--- /dev/null+++ b/thirdparty/tavily/search.go@@ -0,0 +1,38 @@+// Package tavily contains the wire contract for Tavily Search.+package tavily++import (+ "context"+ "net/http"++ "go-bot/thirdparty/providerhttp"+)++const Endpoint = "https://api.tavily.com/search"++type Result struct {+ Title string `json:"title"`+ URL string `json:"url"`+ Content string `json:"content"`+ Published string `json:"published_date"`+}++type Response struct {+ Results []Result `json:"results"`+}++func Search(ctx context.Context, client *http.Client, endpoint, key, query string, count int) (Response, int, error) {+ input := struct {+ Query string `json:"query"`+ Count int `json:"max_results"`+ Depth string `json:"search_depth"`+ Topic string `json:"topic"`+ Answer bool `json:"include_answer"`+ RawContent bool `json:"include_raw_content"`+ Published bool `json:"include_published_date"`+ AutoParameters bool `json:"auto_parameters"`+ }{Query: query, Count: count, Depth: "basic", Topic: "general", Published: true}+ var output Response+ status, err := providerhttp.Post(ctx, client, endpoint, "Authorization", "Bearer "+key, input, &output, 4<<20)+ return output, status, err+}