From 5bfc4148014ebf951397dfeeccafd61b23d8d01f Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 21:17:42 +0900 Subject: [PATCH] feat(editor,editormcp): add built-in agent runner with cx.Secrets, task routing, limit queueing, and failover (#1030) --- ...11-26-editor-builtin-agent-models-usage.md | 69 + .../editor-builtin-agent-models-usage-1030.md | 4 + docs/en/editor.md | 6 +- docs/zh/editor.md | 6 +- packages/game/editor/agent.go | 263 +-- packages/game/editor/agent_builtin.go | 1420 +++++++++++++++++ packages/game/editor/agent_builtin_test.go | 442 +++++ packages/game/editor/agent_settings.go | 131 +- packages/game/editor/agent_ui.go | 403 ++++- .../agent_builtin_screenshot_test.go | 155 ++ .../editor/editormcp/builtin_agent_test.go | 319 ++++ packages/game/editor/editormcp/server.go | 59 + packages/game/editor/locales/en.yaml | 1 + packages/game/editor/locales/zh.yaml | 1 + packages/game/editor/settings.go | 5 + packages/game/editor/state.go | 13 + 16 files changed, 3138 insertions(+), 159 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-26-editor-builtin-agent-models-usage.md create mode 100644 changelog.d/editor-builtin-agent-models-usage-1030.md create mode 100644 packages/game/editor/agent_builtin.go create mode 100644 packages/game/editor/agent_builtin_test.go create mode 100644 packages/game/editor/editorcmd/agent_builtin_screenshot_test.go create mode 100644 packages/game/editor/editormcp/builtin_agent_test.go diff --git a/.agents/notes/implemented/feature/2026-11-26-editor-builtin-agent-models-usage.md b/.agents/notes/implemented/feature/2026-11-26-editor-builtin-agent-models-usage.md new file mode 100644 index 00000000..72307fa7 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-26-editor-builtin-agent-models-usage.md @@ -0,0 +1,69 @@ +# Agent Note: Built-in agent runner with `cx.Secrets`, task routing, limit queueing, and model-error failover + +Status: implemented + +## Problem + +Issue #1030 layers the live built-in agent runner on top of the [Agent Settings pages](../../implemented/feature/2026-11-26-editor-settings-agent-pages.md) (#1028), [connecting external agents](../../implemented/architecture/2026-11-26-editor-agent-connect.md) (#1009), and the [You-only boundary](../../implemented/feature/2026-11-26-editor-you-only-and-proposed-deletions.md) (#1015). Authors need to run requests directly through their own API key without an external MCP CLI, route each **WHO DOES WHAT** task kind to either a connected local MCP agent or a built-in Anthropic model, queue overflow prompts when the person-only weekly request limit is reached, and recover cleanly from transient HTTP `529` / `429` / `5xx` errors by retrying with backoff or failing over to another connected agent. + +Four cross-module contracts needed to be reconciled cleanly with #1028's settings schema and MCP server enforcement: + +1. **Unified secret storage (`cx.Secrets` + `Editor.Keychain`)**: #1030 requires reading/writing API keys via NSGo's `cx.Secrets` (backed by the OS keychain in apps and `nsgotest.Secrets` in tests), while #1028 also supports explicit `Editor.Keychain` injection in tests. Both must share `You only` enforcement (`ErrAgentSettingsYouOnly`) and never write keys to `editor.yaml`, project files, or logs. +2. **Inverted MCP tool bridge enforcing #1028 policies**: `packages/game/editor` cannot import `packages/game/editor/editormcp`, yet every built-in agent tool call must pass through `editormcp.Server`'s enabled-tool filter, permission rules, `WithAgentActor` isolation, and symlink-aware outbound privacy checks. +3. **Hardened HTTP transport and non-deadlocking backoff**: the built-in runner must validate endpoint URLs (refusing plaintext `http://` to remote hosts, embedded userinfo, and cross-host/downgrade redirects), bound response bodies and tool outputs, redact secrets from all error paths, and never deadlock if the UI scope is disposed while waiting on a retry card update. +4. **Single source of truth for WHO DOES WHAT and weekly limits**: task routing and weekly usage counts must reuse #1028's `settingsMu`-guarded `EditorSettings.Agent` (`routes`, `weeklyRequestLimit`, `usage`) rather than duplicating state or forking `editor-settings.v1.json`. + +## Decision + +### 1. Unified API key lookup (`core.Secrets` with `Editor.Keychain` compatibility) + +- `agent_builtin.go` defines `AgentAPIKeySecretAccount = "agent.anthropic.api_key"` and `AgentSecretStore` matching NSGo's `core.Secrets` interface (`Get`/`Set`/`Delete`), plus `MemorySecretStore` (whose `String()`/`GoString()` redact values). +- `agent_settings.go`'s `StoreAgentAPIKey`, `DeleteAgentAPIKey`, `AgentAPIKey`, `HasAgentAPIKey`, and `RefreshAgentAPIKeyStatus` resolve secret storage in deterministic precedence: `Editor.AgentSecretStore` (if explicitly set) -> `Editor.Keychain` (if explicitly set, keeping #1028 tests intact) -> `cx.Secrets()` when a `core.Scope` is attached -> `activeKeychain()` fallback. +- Key presence is cached under `e.settingsMu` and invalidated when a new `core.Scope` attaches (`AttachScope`) or settings reload (`ApplySettings`, which now also refuses `AgentActorActive()` with `ErrAgentSettingsYouOnly`). + +### 2. Inverted MCP tool bridge (`editor.AgentToolExecutor`) with full policy enforcement + +- `packages/game/editor` declares `AgentToolExecutor` (`ListTools` / `CallTool`) and `Editor.AgentTools`. +- `editormcp.New` wires `serverToolExecutor` onto `ed.AgentTools` (and clears it on `Server.Close()`). `ListTools` filters out any tool disabled in **Settings › Tools** (such as default-off `game_delete_file`) so disabled tools are never advertised to the remote model. `CallTool` delegates to `Server.call(...)`, inheriting tool-disabled checks, permission rules (#1010), symlink-aware pre/post privacy checks (#1028), `WithAgentActor` isolation (#1015), and save-failure warnings without creating a synthetic external MCP session. +- `builtInAgentRunner.executeToolWithPrivacy` adds defense-in-depth live checks against `Editor.IsMCPToolEnabled` and `Editor.AgentPrivacy()` (including `ClassifyProjectFilePrivacy` on `scene_read` and stripping PNGs when `ViewportImages` is off). + +### 3. Reusing #1028's WHO DOES WHAT routes and weekly usage limits + +- `AgentTaskKind` uses the exact canonical keys from `AgentTaskRoutesDefs()` (`scene_edits`, `playtest_analysis`, `problems_fixes`, `ask_in_place`, `art_and_sound`). `ResolveAgentModelRoute` maps the persisted route label (`Claude Code · default`, `Anthropic API · default`, `Anthropic API · fast`, `Not connected`) to `AgentModelRoute`. +- `SwitchAgentTurnToAlternative` (refused for agent actors with `ErrAgentSettingsYouOnly`) cancels the active backoff run, persists the new label via `SetAgentTaskRoute` so **Settings › Models and connections** stays in sync, and re-runs on the alternative connected agent without double-charging `WeeklyRequests`. +- Reaching `WeeklyRequestLimit()` transitions status to `AgentStatusLimitReached` (`Limit reached · resets 00:00` + **Usage** link) and appends subsequent prompts to a bounded queue (`maxQueuedAgentRequests = 64`) until `CheckAgentUsageReset()` crosses Monday `00:00` or the person raises the limit and clicks **Send**. + +### 4. Hardened built-in Anthropic Messages API loop + +- `validateAndResolveBuiltInEndpoint` permits only `https://` (or loopback `http://127.0.0.1` / `::1` / `localhost` for local tests), refuses embedded URL credentials, and default `http.Client` installs `builtInCheckRedirect` refusing cross-host or HTTPS-to-HTTP redirects. +- Response reads are capped via `io.LimitReader(resp.Body, builtInMaxResponseBytes+1)` (8 MiB), failing immediately as non-retryable on oversize or invalid JSON; tool results and error messages are bounded and passed through `redactSecret`. +- Transient errors (`429`, `5xx`, `529` overloaded) retry on `AgentModelRetryDelays = [4s, 8s, 16s, 32s]`. `postModelError` updates `AgentTurn.ModelError` and schedules the backoff timer atomically on the editor goroutine while selecting on `ctx.Done()` so scope disposal never deadlocks. `AttachScope(nil)` and `resetAgentForProject()` cancel active runs and retry timers cleanly. + +## Alternatives considered + +### Duplicate Settings pages and `AgentSettings` fields from pre-#1028 drafts + +Keeping a separate `AgentSettings` layout (`weeklyLimit` vs `weeklyRequestLimit`, `scene_edit` vs `scene_edits`) would have fractured `editor-settings.v1.json` and duplicated #1028's Settings UI. Rejected in favor of layering directly onto #1028's schema, `settingsMu` locking, and Settings pages. + +### Use an in-memory MCP client session for the built-in agent + +Connecting the built-in agent over `mcp.NewInMemoryTransports` would register it in `Server.sessions` / `Editor.AgentClients()` and conflate the built-in API connection with local MCP clients (Claude Code / Codex) in the Connect dialog, status chip, and failover picker. Rejected in favor of the `AgentToolExecutor` bridge directly over `Server.Tools()` (filtered by `isToolEnabled`) and `Server.call(...)`. + +### Auto-send queued requests immediately when the limit rises + +Automatically firing queued prompts as soon as the limit increases or resets could start unexpected model spend. Rejected to match `docs/design/editor/AgentStates.dc.html`, which keeps queued prompts visible until the person explicitly presses **Send** or removes them. + +## Consequences + +- **Benefits**: + - Zero duplication with #1028's Agent Settings pages, privacy enforcement, or `editor-settings.v1.json` schema. + - Built-in agent runs end-to-end with `cx.Secrets()` and real `editormcp` tools under the exact same security, permission, and privacy rules as external agents. + - Endpoint validation, redirect guards, bounded reads, secret redaction, and `ctx`-aware UI posting prevent secret leakage, memory exhaustion, and goroutine leaks. +- **Costs and known limits**: + - The built-in HTTP runner currently targets the Anthropic Messages API wire format; additional providers can plug behind `builtInAgentRunner` later without changing Settings or UI contracts. + +## Testing + +- `packages/game/editor/agent_builtin_test.go`: tests weekly limit queueing, `ErrAgentSettingsYouOnly` refusals across every mutator and `AgentAPIKey`, `529` backoff schedule (`4s, 8s, 16s`), **Retry now**, **Use Claude Code** failover without double-charging usage, insecure endpoint refusal, secret redaction on 400 error bodies, and oversized response rejection. +- `packages/game/editor/editormcp/builtin_agent_test.go`: tests end-to-end built-in agent execution with `nsgotest.Secrets` and real `editormcp.Server` (`scene_edit`, single-step Undo, zero key leakage across project and settings files) plus enforcement of default-off `game_delete_file` and `GoSource=false` privacy. +- `packages/game/editor/editorcmd/agent_builtin_screenshot_test.go`: real macOS `nsgotest` screenshots (`-target macos`) of Connect API key step, 529 Model error card (Dark & Light), and Limit reached + queue (Dark & Light). diff --git a/changelog.d/editor-builtin-agent-models-usage-1030.md b/changelog.d/editor-builtin-agent-models-usage-1030.md new file mode 100644 index 00000000..343411b5 --- /dev/null +++ b/changelog.d/editor-builtin-agent-models-usage-1030.md @@ -0,0 +1,4 @@ +### Added + +- `game/editor`, `game/editor/editormcp`: add the built-in agent runner (`SubmitAgentTaskPrompt`, `Editor.AgentTools`, `Editor.BuiltInAgentEndpoint`) that runs requests against the Anthropic Messages API using the editor's MCP tools (enforcing Settings › Tools toggles, permissions, You-only boundaries, and outbound privacy) with API keys kept in NSGo's `core.Secrets` / system keychain and never written to project files, `editor.yaml`, or logs (#1030). +- `game/editor`: connect WHO DOES WHAT task routing (`scene_edits`, `playtest_analysis`, `problems_fixes`, `ask_in_place`, `art_and_sound`), person-only weekly request limit queueing (`Limit reached · resets 00:00` + Usage link and manual queue dispatch), and transient model-error retry backoff (`4 s, 8 s, 16 s, 32 s`) with **Retry now** and switching that task kind to another connected agent (#1030). diff --git a/docs/en/editor.md b/docs/en/editor.md index 0d46db57..3d13901d 100644 --- a/docs/en/editor.md +++ b/docs/en/editor.md @@ -955,11 +955,13 @@ With `Editor.Library` set to a pack library (`library.Open`), as `nsgo game edit All per-computer agent controls, project-level `game.yaml` settings, and editor preferences share one unified **Settings** workspace (`SettingsView`, opened with `OpenSettingsPage(page)`, inspected with `SettingsOpen()` / `SettingsPage()`, and closed with `CloseSettings()` / `Escape`) laid out from `docs/design/editor/Settings.dc.html` and `Spec.dc.html` using `SpecPalette` tokens in both Dark and Light appearances. The left sidebar groups **`AGENT`** (**Models and connections**, **Tools**, **Usage and privacy** — all per-computer and **You only**), **`PROJECT · game.yaml`** (**Project**, **Input map**, **Audio buses**, **Export**), and **`EDITOR · THIS COMPUTER`** (**General**, **Shortcuts**); each row displays its label, help text, value control, and agent-policy badge (**Agent may change** or **You only**), and every interactive control across all pages uses real focusable `ui.Button` / `ui.*` widgets reachable via `Tab` with visible focus rings. -### Agent pages: Models and connections, Tools, and Usage and privacy (#1028) +### Agent pages: Models and connections, Tools, and Usage and privacy (#1028, #1030) Stored per computer in `EditorSettings` (`editor.yaml` under `agent`, never inside the project) with every mutator refused when invoked by an agent (`ErrAgentSettingsYouOnly`): -- **Models and connections (`SettingsPageModels`)**: shows connected local MCP agents (such as Claude Code), the built-in API connection (`Anthropic API`, whose key is stored exclusively in the host OS keychain under `AgentKeychainServiceName` via `StoreAgentAPIKey`, `HasAgentAPIKey`, `DeleteAgentAPIKey`, and `AgentAPIKey` — never written to `editor.yaml` or any project file), **+ Connect another agent or model** (opening `ConnectAgentDialogView`), and **WHO DOES WHAT** task routing (`AgentTaskRoute` / `SetAgentTaskRoute`). The sidebar meta reports the active connection count (`AgentActiveConnectionCount`, e.g. `2 on`). +- **Models and connections (`SettingsPageModels`)**: shows connected local MCP agents (such as Claude Code), the built-in API connection (`Anthropic API`, whose key is stored exclusively in NSGo's `core.Secrets` under `AgentAPIKeySecretAccount` / the host OS keychain under `AgentKeychainServiceName` via `StoreAgentAPIKey`, `HasAgentAPIKey`, `DeleteAgentAPIKey`, and `AgentAPIKey` — never written to `editor.yaml`, project files, or logs), **+ Connect another agent or model** (opening `ConnectAgentDialogView`), and **WHO DOES WHAT** task routing (`AgentTaskRoute` / `SetAgentTaskRoute` / `ResolveAgentModelRoute`). The sidebar meta reports the active connection count (`AgentActiveConnectionCount`, e.g. `2 on`). +- **Built-in agent runner (`SubmitAgentTaskPrompt`, `Editor.AgentTools`, `Editor.BuiltInAgentEndpoint`)**: routes each task kind (`AgentTaskSceneEdit`, `AgentTaskPlaytest`, `AgentTaskProblems`, `AgentTaskAskInPlace`, `AgentTaskArtSound`) to either a connected local MCP agent or the built-in Anthropic Messages API runner (`DefaultBuiltInModel` / `DefaultBuiltInFastModel`), validating that custom endpoints use `https://` (or loopback `http://` for local tests) and never forward `x-api-key` across redirect hosts. `editormcp.New` wires `Editor.AgentTools` automatically so built-in tool calls execute through the same `editormcp.Server` tool toggles, permission rules, `WithAgentActor` You-only guard, and symlink-aware outbound privacy enforcement as external MCP clients. +- **Weekly limit queueing & model error failover (`AgentStatusLimitReached`, `AgentQueuedRequests`, `AgentModelErrorState`)**: reaching the person-only weekly request limit (`WeeklyRequestLimit` / `SetWeeklyRequestLimit`) transitions the Agent header chip to `Limit reached · resets 00:00` with a **Usage** link and queues subsequent requests (`SendQueuedAgentRequest`, `RemoveQueuedAgentRequest`) until `CheckAgentUsageReset` crosses the weekly reset or the person raises the limit. Transient model errors (`429`, `5xx`, `529` overloaded) retry on `AgentModelRetryDelays` (`4 s, 8 s, 16 s, 32 s`), rendering the model error card with **Retry now** (`RetryAgentTurn`) and **Use ``** (`SwitchAgentTurnToAlternative`) to update WHO DOES WHAT and run the request on another connected agent without double-counting usage. - **Tools (`SettingsPageTools`)**: lists every tool registered on the editor's MCP server (`RegisteredMCPTools`) with its monospace name, description, and an accessible `role="switch"` toggle (`IsMCPToolEnabled` / `SetMCPToolEnabled`), showing `"enabled / total"` in the sidebar (`EnabledMCPToolCount`). `game_delete_file` is off by default; turning any tool off removes it from the MCP server's client tool list (`tools/list_changed`) and returns a readable refusal if called. Below the editor's tools, **OTHER MCP SERVERS THE AGENT MAY USE** starts with **Running game · nsgo dev** (`nsgo-game` / `go tool nsgo mcp`) and provides **+ Add a server** (`AddAgentMCPServer`, `SetAgentMCPServerEnabled`, `RemoveAgentMCPServer`), syncing enabled servers into the open project's `.mcp.json` and `.codex/config.toml` (`editormcp.InstallWithServers`). - **Usage and privacy (`SettingsPageUsage`)**: displays **This week** requests against a user-configured weekly limit (`WeeklyRequestLimit` / `SetWeeklyRequestLimit` / `RecordAgentRequest`), **Kept** share of reviewed agent changes (`RecordAgentReviewOutcome`), and local **Playtests** run count (`RecordPlaytestRun`), followed by the four **WHAT MAY LEAVE THIS COMPUTER** switches (`AgentPrivacy` / `SetAgentPrivacy`): **Scene and data files** (on), **Viewport images** (on), **Go source code** (off), and **Art and audio files** (off). The editor's MCP server refuses, with the reason, any tool call or resource read whose result would carry switched-off content for every connected agent. diff --git a/docs/zh/editor.md b/docs/zh/editor.md index 89323724..8b487531 100644 --- a/docs/zh/editor.md +++ b/docs/zh/editor.md @@ -955,11 +955,13 @@ func main() { 所有每台电脑的智能体控制、项目级 `game.yaml` 配置与编辑器偏好均汇集在统一的**设置**视图(`SettingsView`,通过 `OpenSettingsPage(page)` 打开、`SettingsOpen()` / `SettingsPage()` 查询、`CloseSettings()` 或 `Escape` 关闭)中,界面布局严格遵循 `docs/design/editor/Settings.dc.html` 与 `Spec.dc.html`,并在深色与浅色外观下统一使用 `SpecPalette` 令牌。左侧导航将 **`AGENT`**(**Models and connections**、**Tools**、**Usage and privacy**,全部保存在此计算机且为**仅限用户**)、**`PROJECT · game.yaml`**(**Project**、**Input map**、**Audio buses**、**Export**)与 **`EDITOR · THIS COMPUTER`**(**General**、**Shortcuts**)分组展示;每一行包含标签、说明文本、值控件与智能体权限徽章(**Agent may change** 或 **You only**);全部页面上的交互控件均使用真实可聚焦的 `ui.Button` / `ui.*` 组件,支持 `Tab` 键逐项到达并显示焦点环。 -### 智能体设置页:模型与连接、工具、用量与隐私(#1028) +### 智能体设置页:模型与连接、工具、用量与隐私(#1028、#1030) 全部保存在每台电脑的 `EditorSettings`(`editor.yaml` 的 `agent` 小节,从不写入项目目录),且所有修改方法都会拒绝来自智能体的调用(`ErrAgentSettingsYouOnly`): -- **模型与连接(`SettingsPageModels`)**:展示已连接的本机 MCP 智能体(如 Claude Code)、内置 API 连接(`Anthropic API`,密钥通过 `StoreAgentAPIKey`、`HasAgentAPIKey`、`DeleteAgentAPIKey` 和 `AgentAPIKey` 仅保存在系统钥匙串 `AgentKeychainServiceName` 中,绝不写入 `editor.yaml` 或任何项目文件)、打开 `ConnectAgentDialogView` 的 **+ 连接其他智能体或模型** 按钮,以及 **任务分工**(`AgentTaskRoute` / `SetAgentTaskRoute`)。导航栏徽章实时显示已连接数量(`AgentActiveConnectionCount`,如 `2 个已连接`)。 +- **模型与连接(`SettingsPageModels`)**:展示已连接的本机 MCP 智能体(如 Claude Code)、内置 API 连接(`Anthropic API`,密钥通过 `StoreAgentAPIKey`、`HasAgentAPIKey`、`DeleteAgentAPIKey` 和 `AgentAPIKey` 仅保存在 NSGo 的 `core.Secrets`(`AgentAPIKeySecretAccount`)或系统钥匙串(`AgentKeychainServiceName`)中,绝不写入 `editor.yaml`、任何项目文件或日志)、打开 `ConnectAgentDialogView` 的 **+ 连接其他智能体或模型** 按钮,以及 **任务分工**(`AgentTaskRoute` / `SetAgentTaskRoute` / `ResolveAgentModelRoute`)。导航栏徽章实时显示已连接数量(`AgentActiveConnectionCount`,如 `2 个已连接`)。 +- **内置智能体执行器(`SubmitAgentTaskPrompt`、`Editor.AgentTools`、`Editor.BuiltInAgentEndpoint`)**:根据 **任务分工** 将五类任务(`AgentTaskSceneEdit`、`AgentTaskPlaytest`、`AgentTaskProblems`、`AgentTaskAskInPlace`、`AgentTaskArtSound`)路由到已连接的本地 MCP 智能体或内置 Anthropic Messages API 执行器(`DefaultBuiltInModel` / `DefaultBuiltInFastModel`),仅允许 `https://`(或本地测试用的回环 `http://`)端点,且拒绝跨主机或 HTTPS 降级重定向以防泄露 `x-api-key`。`editormcp.New` 会自动绑定 `Editor.AgentTools`,使内置智能体调用的工具与外部 MCP 客户端一样经过完整的工具开关、权限规则、`WithAgentActor` 仅限用户保护以及解析符号链接的外发隐私校验。 +- **每周限额排队与模型错误切换(`AgentStatusLimitReached`、`AgentQueuedRequests`、`AgentModelErrorState`)**:达到仅限用户可调整的每周请求上限(`WeeklyRequestLimit` / `SetWeeklyRequestLimit`)后,智能体面板顶栏切换为 `Limit reached · resets 00:00` 与 **Usage** 链接,新提交的请求会进入队列等待(`SendQueuedAgentRequest`、`RemoveQueuedAgentRequest`),直至 `CheckAgentUsageReset` 跨过每周重置时刻或用户调高限额。遇到瞬时模型错误(`429`、`5xx`、`529` 过载)时,按 `AgentModelRetryDelays`(`4 s、8 s、16 s、32 s`)指数退避重试,并展示包含 **Retry now**(`RetryAgentTurn`)与 **Use `<已连接智能体>`**(`SwitchAgentTurnToAlternative`)的错误卡片,一键将该类任务切换到另一已连接智能体继续执行且不重复扣减每周请求数。 - **工具(`SettingsPageTools`)**:列出编辑器 MCP 服务器注册的全部工具(`RegisteredMCPTools`),每项显示等宽工具名、说明与带 `role="switch"` 的开关(`IsMCPToolEnabled` / `SetMCPToolEnabled`),导航栏显示 `"已开启 / 总数"`(`EnabledMCPToolCount`)。`game_delete_file` 默认关闭;关闭任一工具会立即将其从已连接客户端的工具列表中移除(发送 `tools/list_changed`),若智能体仍调用该工具则会收到可读的拒绝原因。下方 **智能体可使用的其他 MCP 服务器** 默认包含 **Running game · nsgo dev**(`nsgo-game` / `go tool nsgo mcp`)并提供 **+ 添加服务器**(`AddAgentMCPServer`、`SetAgentMCPServerEnabled`、`RemoveAgentMCPServer`),已启用的服务器会自动同步到项目的 `.mcp.json` 与 `.codex/config.toml`(`editormcp.InstallWithServers`)。 - **用量与隐私(`SettingsPageUsage`)**:展示 **本周请求** 与用户设定的每周限额进度条(`WeeklyRequestLimit` / `SetWeeklyRequestLimit` / `RecordAgentRequest`)、审查后 **保留率**(`RecordAgentReviewOutcome`)以及本地 **试玩次数**(`RecordPlaytestRun`),下方提供四项 **允许离开此计算机的内容** 开关(`AgentPrivacy` / `SetAgentPrivacy`):**场景与数据文件**(开)、**视口画面**(开)、**Go 源代码**(关)与 **美术与音频文件**(关)。只要某类内容处于关闭状态,编辑器的 MCP 服务器就会对所有智能体拒绝返回此类内容的工具调用或资源读取,并在错误中说明原因。 diff --git a/packages/game/editor/agent.go b/packages/game/editor/agent.go index 4d2d1edc..c6f6b32e 100644 --- a/packages/game/editor/agent.go +++ b/packages/game/editor/agent.go @@ -35,7 +35,7 @@ const ( AgentModeUnconfigured AgentMode = "" // AgentModeLocal connects to an external MCP agent running on this computer (Claude Code, Codex, or any MCP client). AgentModeLocal AgentMode = "local" - // AgentModeAPIKey selects the built-in model path using an API key (implemented in its own issue). + // AgentModeAPIKey selects the built-in model path using an API key stored in NSGo's core.Secrets / system keychain. AgentModeAPIKey AgentMode = "apikey" // AgentModeNone disables agent features and keeps the Agent panel closed. AgentModeNone AgentMode = "none" @@ -47,7 +47,7 @@ type AgentStatus string const ( // AgentStatusNotConnected indicates no agent has connected yet. AgentStatusNotConnected AgentStatus = "not_connected" - // AgentStatusConnected indicates an MCP client is attached and idle. + // AgentStatusConnected indicates an MCP client or built-in API key agent is attached and idle. AgentStatusConnected AgentStatus = "connected" // AgentStatusWorking indicates the agent is actively executing a request. AgentStatusWorking AgentStatus = "working" @@ -57,6 +57,8 @@ const ( AgentStatusReconnecting AgentStatus = "reconnecting" // AgentStatusDisconnected indicates all reconnect retries failed. AgentStatusDisconnected AgentStatus = "disconnected" + // AgentStatusLimitReached indicates the weekly request limit set on Usage and privacy has been reached and requests queue until reset or until the person raises it. + AgentStatusLimitReached AgentStatus = "limit_reached" ) // ConnectStep identifies a specific step inside the Connect an agent dialog so Troubleshoot reopens directly at the step that failed. @@ -250,31 +252,35 @@ type AgentTurnContext struct { // AgentTurn is one user request (in-place ⌘L, Agent panel composer, terminal-initiated MCP turn, or background automation run) // and its attached context, streamed steps, and reply. type AgentTurn struct { - ID string `json:"id"` - Prompt string `json:"prompt"` - Source string `json:"source,omitempty"` // "in_place", "panel", "external", or "automation" - SkipPlan bool `json:"skipPlan,omitempty"` // true for small in-place ⌘L edits per Plan.dc.html - Status string `json:"status,omitempty"` // "pending", "running", "done", "stopped" - External bool `json:"external,omitempty"` // true for turns started by a terminal MCP client rather than the composer - AgentName string `json:"agentName,omitempty"` - Steps []AgentStep `json:"steps,omitempty"` - Summary string `json:"summary,omitempty"` - Reply string `json:"reply,omitempty"` - Error string `json:"error,omitempty"` - Stopped bool `json:"stopped,omitempty"` - Done bool `json:"done,omitempty"` - InputTokens int `json:"inputTokens,omitempty"` - OutputTokens int `json:"outputTokens,omitempty"` - CreatedAt time.Time `json:"createdAt"` - StartedAt time.Time `json:"startedAt"` - FinishedAt time.Time `json:"finishedAt"` - Context AgentTurnContext `json:"context"` - Automation bool `json:"automation,omitempty"` // true for turns started by an automation trigger - AutomationID string `json:"automationId,omitempty"` // rule ID from automations.yaml when Automation is true - AutomationName string `json:"automationName,omitempty"` // WHEN summary of the triggering automation rule - TriggerSummary string `json:"triggerSummary,omitempty"` // concrete trigger description, e.g. "File changed · scenes/level_01.scene.yaml" - CheckpointID string `json:"checkpointId,omitempty"` // checkpoint captured before the automation started - ReviewState AgentReviewState `json:"reviewState,omitempty"` // lifecycle state for Ready to review / Kept / Dismissed / Failed + ID string `json:"id"` + Prompt string `json:"prompt"` + Source string `json:"source,omitempty"` // "in_place", "panel", "external", or "automation" + SkipPlan bool `json:"skipPlan,omitempty"` // true for small in-place ⌘L edits per Plan.dc.html + Status string `json:"status,omitempty"` // "pending", "running", "done", "stopped" + External bool `json:"external,omitempty"` // true for turns started by a terminal MCP client rather than the composer + AgentName string `json:"agentName,omitempty"` + Task AgentTaskKind `json:"task,omitempty"` + Route AgentModelRoute `json:"route,omitempty"` + Model string `json:"model,omitempty"` + Steps []AgentStep `json:"steps,omitempty"` + Summary string `json:"summary,omitempty"` + Reply string `json:"reply,omitempty"` + Error string `json:"error,omitempty"` + ModelError *AgentModelErrorState `json:"modelError,omitempty"` + Stopped bool `json:"stopped,omitempty"` + Done bool `json:"done,omitempty"` + InputTokens int `json:"inputTokens,omitempty"` + OutputTokens int `json:"outputTokens,omitempty"` + CreatedAt time.Time `json:"createdAt"` + StartedAt time.Time `json:"startedAt"` + FinishedAt time.Time `json:"finishedAt"` + Context AgentTurnContext `json:"context"` + Automation bool `json:"automation,omitempty"` // true for turns started by an automation trigger + AutomationID string `json:"automationId,omitempty"` // rule ID from automations.yaml when Automation is true + AutomationName string `json:"automationName,omitempty"` // WHEN summary of the triggering automation rule + TriggerSummary string `json:"triggerSummary,omitempty"` // concrete trigger description, e.g. "File changed · scenes/level_01.scene.yaml" + CheckpointID string `json:"checkpointId,omitempty"` // checkpoint captured before the automation started + ReviewState AgentReviewState `json:"reviewState,omitempty"` // lifecycle state for Ready to review / Kept / Dismissed / Failed } // AgentOpenRequest represents a pending permission prompt or question waiting on the user. @@ -295,6 +301,9 @@ type AgentRequest struct { SelectedID string AgentKind ExternalAgentKind Permissions AgentPermissions + Task AgentTaskKind + Route AgentModelRoute + Model string AutomationID string AutomationName string TriggerKind AutomationTriggerKind @@ -306,12 +315,13 @@ type AgentRequest struct { type AgentEventKind string const ( - AgentEventSession AgentEventKind = "session" - AgentEventStep AgentEventKind = "step" - AgentEventMessage AgentEventKind = "message" - AgentEventUsage AgentEventKind = "usage" - AgentEventDone AgentEventKind = "done" - AgentEventError AgentEventKind = "error" + AgentEventSession AgentEventKind = "session" + AgentEventStep AgentEventKind = "step" + AgentEventMessage AgentEventKind = "message" + AgentEventUsage AgentEventKind = "usage" + AgentEventDone AgentEventKind = "done" + AgentEventError AgentEventKind = "error" + AgentEventModelRecovered AgentEventKind = "model_recovered" ) // AgentEvent is one incremental update streamed by an AgentRunner. @@ -388,6 +398,10 @@ type agentState struct { activeRunCancel context.CancelFunc activeRunID uint64 activeTurnID string + activeRetryNow chan struct{} + activeRetryCancel func() + queued []AgentQueuedRequest + queueSeq int openRequest *AgentOpenRequest focusRequestSeq uint64 focusRequestCalled int @@ -504,17 +518,22 @@ func (e *Editor) stopAgentTimers() { e.agent.connectCopiedStop() e.agent.connectCopiedStop = nil } + if e.agent.activeRetryCancel != nil { + e.agent.activeRetryCancel() + e.agent.activeRetryCancel = nil + } if e.agent.activeRunCancel != nil { e.agent.activeRunCancel() e.agent.activeRunCancel = nil } e.stopAutomationRunsAndScheduler() + e.agent.activeRetryNow = nil e.agent.activeTurnID = "" e.agent.connectAPIKey = "" } // resetAgentForProject stops active agent runs/timers and clears per-project agent conversation, -// client sessions, open requests, composer draft, and draft API key when switching projects or demos. +// client sessions, open requests, queued requests, composer draft, and draft API key when switching projects or demos. func (e *Editor) resetAgentForProject() { if e == nil { return @@ -537,11 +556,20 @@ func (e *Editor) resetAgentForProject() { e.agent.connectAPIKey = "" e.agent.sessionID = "" e.agent.turns = nil + e.agent.queued = nil e.agent.composerText = "" e.agent.workingStep = 0 e.agent.workingTotal = 0 e.agent.openRequest = nil - e.agent.status = AgentStatusNotConnected + if e.agent.mode == AgentModeAPIKey && e.HasAgentAPIKey(DefaultAgentAPIKeyAccount) { + if e.AgentWeeklyLimitReached() { + e.agent.status = AgentStatusLimitReached + } else { + e.agent.status = AgentStatusConnected + } + } else { + e.agent.status = AgentStatusNotConnected + } e.updateAgentAnnouncement() } @@ -627,8 +655,14 @@ func (e *Editor) AgentPrimaryClient() (AgentClientInfo, bool) { return AgentClientInfo{}, false } -// AgentStatusTooltip returns the hover text for the Connected status chip, naming the agent and transport (for example "Claude Code over stdio"). +// AgentStatusTooltip returns the hover text for the Connected status chip, naming the agent and transport (for example "Claude Code over stdio" or "Anthropic API (built in)"). func (e *Editor) AgentStatusTooltip() string { + if len(e.agent.clients) > 0 { + return e.agent.clients[0].HoverLabel() + } + if e != nil && (e.agent.mode == AgentModeAPIKey || e.HasAgentAPIKey(DefaultAgentAPIKeyAccount)) { + return e.BuiltInAgentProvider() + " (built in · key in system keychain)" + } if c, ok := e.AgentPrimaryClient(); ok { return c.HoverLabel() } @@ -695,7 +729,11 @@ func (e *Editor) AgentLiveAnnouncement() string { func (e *Editor) updateAgentAnnouncement() { switch e.agent.status { case AgentStatusConnected: - e.agent.liveAnnouncement = fmt.Sprintf("Connected via MCP: %s", e.AgentStatusTooltip()) + if len(e.agent.clients) == 0 && (e.agent.mode == AgentModeAPIKey || e.HasAgentAPIKey(DefaultAgentAPIKeyAccount)) { + e.agent.liveAnnouncement = fmt.Sprintf("Connected via %s", e.BuiltInAgentProvider()) + } else { + e.agent.liveAnnouncement = fmt.Sprintf("Connected via MCP: %s", e.AgentStatusTooltip()) + } case AgentStatusWorking: if e.agent.workingTotal > 0 { e.agent.liveAnnouncement = fmt.Sprintf("Agent working, step %d of %d", max(1, e.agent.workingStep), e.agent.workingTotal) @@ -713,6 +751,8 @@ func (e *Editor) updateAgentAnnouncement() { e.agent.liveAnnouncement = fmt.Sprintf("Agent reconnecting, try %d of %d", attempt, total) case AgentStatusDisconnected: e.agent.liveAnnouncement = "Agent disconnected" + case AgentStatusLimitReached: + e.agent.liveAnnouncement = fmt.Sprintf("Weekly agent limit reached, resets at %s", e.AgentUsageResetLabel()) default: e.agent.liveAnnouncement = "No agent connected" } @@ -784,6 +824,15 @@ func (e *Editor) OpenConnectDialog() { e.notify() } +// OpenConnectDialogForMode opens the Connect an agent dialog pre-selected on mode (for example AgentModeAPIKey). +func (e *Editor) OpenConnectDialogForMode(mode AgentMode) { + if e == nil { + return + } + e.OpenConnectDialog() + e.SetConnectChoice(mode) +} + // OpenConnectDialogAt opens the Connect an agent dialog focused directly on step (used by Troubleshoot so it lands on the step that failed, not the start). func (e *Editor) OpenConnectDialogAt(step ConnectStep) { if e == nil { @@ -922,13 +971,17 @@ func (e *Editor) CompleteConnectDialog() { switch choice { case AgentModeNone: - e.cancelAgentReconnect() + e.stopAgentTimers() + e.agent.queued = nil e.agent.rightTab = RightTabInspector e.agent.status = AgentStatusNotConnected e.updateAgentAnnouncement() case AgentModeLocal: e.agent.rightTab = RightTabAgent - if len(e.agent.clients) > 0 && e.agent.status == AgentStatusNotConnected { + if e.AgentWeeklyLimitReached() { + e.agent.status = AgentStatusLimitReached + e.updateAgentAnnouncement() + } else if len(e.agent.clients) > 0 && e.agent.status == AgentStatusNotConnected { e.agent.status = AgentStatusConnected e.updateAgentAnnouncement() } @@ -939,6 +992,14 @@ func (e *Editor) CompleteConnectDialog() { e.Status = err.Error() } } + if e.HasAgentAPIKey(DefaultAgentAPIKeyAccount) { + if e.AgentWeeklyLimitReached() { + e.agent.status = AgentStatusLimitReached + } else if e.agent.status == AgentStatusNotConnected || e.agent.status == AgentStatusDisconnected { + e.agent.status = AgentStatusConnected + } + e.updateAgentAnnouncement() + } } e.notify() } @@ -1528,96 +1589,9 @@ func (e *Editor) RecordExternalAgentToolCall(clientName, toolName, summary strin e.notify() } -// SubmitAgentPrompt submits prompt (or the current composer text when prompt is empty) to the connected agent runner and streams its steps into the Agent panel. +// SubmitAgentPrompt submits prompt (or the current composer text when prompt is empty) to the agent routed for Scene and data edits and streams its steps into the Agent panel. func (e *Editor) SubmitAgentPrompt(prompt string) error { - if e == nil { - return errors.New("editor: nil editor") - } - if e.playing { - return ErrPlaying - } - if e.agent.mode == AgentModeNone { - return errors.New("editor: agent is disabled") - } - text := strings.TrimSpace(prompt) - if text == "" { - text = strings.TrimSpace(e.agent.composerText) - } - if text == "" { - return nil - } - if e.agent.activeRunCancel != nil { - return errors.New("editor: an agent request is already running") - } - runner := e.AgentRunner - if runner == nil { - if len(e.agent.clients) == 0 && e.agent.mode != AgentModeLocal { - e.OpenConnectDialog() - return errors.New("editor: no agent connected") - } - runner = defaultCLIAgentRunner() - } - - e.agent.composerText = "" - e.agent.turnSeq++ - e.agent.turnChangeSeq++ - turnID := fmt.Sprintf("turn-%d", e.agent.turnSeq) - clientName := "" - agentKind := ExternalAgentAuto - if c, ok := e.AgentPrimaryClient(); ok { - clientName = c.DisplayName - agentKind = DetectExternalAgentKind(c.Name) - } - now := e.nowTime() - e.agent.turns = append(e.agent.turns, AgentTurn{ - ID: turnID, - Prompt: text, - Source: "panel", - Status: "running", - AgentName: clientName, - CreatedAt: now, - StartedAt: now, - }) - - e.agent.activeRunID++ - runID := e.agent.activeRunID - e.agent.activeTurnID = turnID - ctx, cancel := context.WithCancel(context.Background()) - e.agent.activeRunCancel = cancel - e.agent.status = AgentStatusWorking - e.agent.workingStep = 1 - e.agent.workingTotal = 0 - e.RecordAgentRequest(1) - e.updateAgentAnnouncement() - e.upsertTurnNotificationTask(AgentTask{ - ID: turnID, - Title: text, - State: TaskRunning, - ScenePath: e.ScenePath, - }, e.FilePath, time.Time{}) - - req := AgentRequest{ - ThreadID: e.agent.threadID, - SessionID: e.agent.sessionID, - Prompt: text, - ProjectRoot: e.agentProjectRoot(), - ScenePath: e.ScenePath, - SelectedID: e.SelectedID, - AgentKind: agentKind, - Permissions: e.agent.permissions, - } - - go func() { - err := runner.Run(ctx, req, func(ev AgentEvent) { - e.postOrRun(func() { - e.applyAgentEventForRun(runID, turnID, ev) - }) - }) - e.postOrRun(func() { - e.finishAgentRun(runID, turnID, err, ctx.Err() != nil) - }) - }() - return nil + return e.SubmitAgentTaskPrompt(AgentTaskSceneEdit, prompt) } // StopAgentRun cancels the currently running composer request, keeping completed steps visible. @@ -1625,6 +1599,11 @@ func (e *Editor) StopAgentRun() { if e == nil || e.agent.activeRunCancel == nil { return } + if e.agent.activeRetryCancel != nil { + e.agent.activeRetryCancel() + e.agent.activeRetryCancel = nil + } + e.agent.activeRetryNow = nil cancel := e.agent.activeRunCancel stoppedTurnID := e.agent.activeTurnID e.agent.activeRunCancel = nil @@ -1638,8 +1617,13 @@ func (e *Editor) StopAgentRun() { if n := len(e.agent.turns); n > 0 && !e.agent.turns[n-1].Done { e.agent.turns[n-1].Stopped = true e.agent.turns[n-1].Done = true + e.agent.turns[n-1].Status = "stopped" e.agent.turns[n-1].FinishedAt = e.nowTime() + if e.agent.turns[n-1].ModelError != nil { + e.agent.turns[n-1].ModelError.Retrying = false + } } + e.agent.turnChangeSeq++ e.restoreIdleAgentStatus() if stoppedTurnID != "" { e.removeTurnNotificationTask(stoppedTurnID) @@ -1740,11 +1724,14 @@ func (e *Editor) applyAgentEventForRun(runID uint64, turnID string, ev AgentEven if ev.Err != "" { turn.Error = ev.Err } + case AgentEventModelRecovered: + turn.ModelError = nil case AgentEventDone: if ev.Text != "" && turn.Summary == "" { turn.Summary = ev.Text turn.Reply = ev.Text } + turn.ModelError = nil turn.Done = true turn.Status = "done" turn.FinishedAt = e.nowTime() @@ -1758,6 +1745,11 @@ func (e *Editor) finishAgentRun(runID uint64, turnID string, err error, canceled if e.agent.activeRunID != runID { return } + if e.agent.activeRetryCancel != nil { + e.agent.activeRetryCancel() + e.agent.activeRetryCancel = nil + } + e.agent.activeRetryNow = nil if e.agent.activeRunCancel != nil { e.agent.activeRunCancel() e.agent.activeRunCancel = nil @@ -1772,11 +1764,17 @@ func (e *Editor) finishAgentRun(runID uint64, turnID string, err error, canceled if canceled { turn.Stopped = true turn.Status = "stopped" + if turn.ModelError != nil { + turn.ModelError.Retrying = false + } } else { turn.Status = "done" if err != nil && turn.Error == "" { turn.Error = err.Error() } + if turn.ModelError != nil { + turn.ModelError.Retrying = false + } } for i := range turn.Steps { if turn.Steps[i].Status == AgentStepRunning { @@ -1830,11 +1828,16 @@ func (e *Editor) finishAgentRun(runID uint64, turnID string, err error, canceled func (e *Editor) restoreIdleAgentStatus() { e.agent.workingStep = 0 e.agent.workingTotal = 0 + if e.agent.mode != AgentModeNone && e.AgentWeeklyLimitReached() { + e.agent.status = AgentStatusLimitReached + e.updateAgentAnnouncement() + return + } if e.agent.openRequest != nil { e.agent.status = AgentStatusWaitingForYou - } else if len(e.agent.clients) > 0 { + } else if len(e.agent.clients) > 0 || (e.agent.mode == AgentModeAPIKey && e.HasAgentAPIKey(DefaultAgentAPIKeyAccount)) { e.agent.status = AgentStatusConnected - } else if e.agent.status == AgentStatusWorking { + } else if e.agent.status == AgentStatusWorking || e.agent.status == AgentStatusLimitReached { if e.agent.hadClient { e.agent.status = AgentStatusDisconnected } else { diff --git a/packages/game/editor/agent_builtin.go b/packages/game/editor/agent_builtin.go new file mode 100644 index 00000000..797bc430 --- /dev/null +++ b/packages/game/editor/agent_builtin.go @@ -0,0 +1,1420 @@ +package editor + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/netip" + "net/url" + "slices" + "strings" + "sync" + "time" + "unicode/utf8" +) + +const ( + // AgentAPIKeySecretAccount is the account name under NSGo's core.Secrets where the built-in agent's API key is stored. + // It is never written to project files, EditorSettings YAML, or logs. + AgentAPIKeySecretAccount = "agent.anthropic.api_key" + + // DefaultBuiltInAgentEndpoint is the default Anthropic Messages API endpoint used by the built-in agent. + DefaultBuiltInAgentEndpoint = "https://api.anthropic.com/v1/messages" + + // DefaultBuiltInModel is the default model used for "Anthropic API · default". + DefaultBuiltInModel = "claude-sonnet-4-6" + + // DefaultBuiltInFastModel is the default model used for "Anthropic API · fast". + DefaultBuiltInFastModel = "claude-haiku-4-5" + + builtInMaxToolIterations = 24 + builtInMaxResponseBytes = 8 << 20 + builtInMaxToolResultChars = 256 * 1024 + builtInMaxToolImageBytes = 8 << 20 + maxQueuedAgentRequests = 64 + maxModelErrorMessageRunes = 240 + anthropicAPIVersion = "2023-06-01" +) + +var ( + // ErrAgentLimitReached is returned when a request cannot run immediately because the weekly request limit has been reached. + ErrAgentLimitReached = errors.New("editor: weekly agent request limit reached") + + // ErrAgentAPIKeyMissing is returned when the built-in agent has no API key stored in NSGo secrets or the system keychain. + ErrAgentAPIKeyMissing = errors.New("editor: built-in agent API key is not configured in system keychain") + + // ErrBuiltInEndpointInsecure is returned when BuiltInAgentEndpoint is not an https:// URL (or loopback http:// URL for local testing). + ErrBuiltInEndpointInsecure = errors.New("editor: built-in agent endpoint must use https:// (or loopback http://)") + + // errBuiltInNonRetryable marks client/protocol errors (oversized body, invalid JSON) that must not be retried. + errBuiltInNonRetryable = errors.New("non-retryable model error") +) + +// AgentModelRetryDelays is the exponential backoff schedule used when a model endpoint returns a retryable error (429, 5xx, 529 overloaded): +// try 1 = 4 s, try 2 = 8 s, try 3 = 16 s, try 4 = 32 s (matching docs/design/editor/AgentStates.dc.html: "Retrying in 8 s · try 2 of 4"). +var AgentModelRetryDelays = []time.Duration{ + 4 * time.Second, + 8 * time.Second, + 16 * time.Second, + 32 * time.Second, +} + +// AgentSecretStore matches NSGo's core.Secrets interface (Get/Set/Delete by account) so the editor uses cx.Secrets() directly in apps and nsgotest, or a test store when headless. +type AgentSecretStore interface { + Get(account string) (string, bool, error) + Set(account, value string) error + Delete(account string) error +} + +// MemorySecretStore is an in-memory AgentSecretStore for headless tests without a core.Scope. +type MemorySecretStore struct { + mu sync.RWMutex + values map[string]string +} + +// NewMemorySecretStore returns an initialized MemorySecretStore optionally seeded with values. +func NewMemorySecretStore(initial map[string]string) *MemorySecretStore { + m := &MemorySecretStore{values: make(map[string]string, len(initial))} + for k, v := range initial { + m.values[k] = v + } + return m +} + +// Get returns the secret stored under account. +func (m *MemorySecretStore) Get(account string) (string, bool, error) { + if m == nil { + return "", false, errors.New("editor: secret store unavailable") + } + m.mu.RLock() + v, ok := m.values[account] + m.mu.RUnlock() + return v, ok, nil +} + +// Set stores value under account. +func (m *MemorySecretStore) Set(account, value string) error { + if m == nil { + return errors.New("editor: secret store unavailable") + } + m.mu.Lock() + if m.values == nil { + m.values = make(map[string]string) + } + m.values[account] = value + m.mu.Unlock() + return nil +} + +// Delete removes account from the store. +func (m *MemorySecretStore) Delete(account string) error { + if m == nil { + return errors.New("editor: secret store unavailable") + } + m.mu.Lock() + delete(m.values, account) + m.mu.Unlock() + return nil +} + +// String redacts stored secret values so they can never leak into logs or test output. +func (m *MemorySecretStore) String() string { + if m == nil { + return "MemorySecretStore(nil)" + } + m.mu.RLock() + n := len(m.values) + m.mu.RUnlock() + return fmt.Sprintf("MemorySecretStore{count:%d, values:[REDACTED]}", n) +} + +// GoString redacts stored secret values. +func (m *MemorySecretStore) GoString() string { return m.String() } + +// AgentToolSpec describes one editor MCP tool offered to the built-in agent model. +type AgentToolSpec struct { + Name string `json:"name"` + Title string `json:"title,omitempty"` + Description string `json:"description"` + InputSchema json.RawMessage `json:"input_schema"` +} + +// AgentToolCallResult holds the text, optional PNG, and error flag returned by executing one editor MCP tool. +type AgentToolCallResult struct { + Text string + PNG []byte + IsError bool +} + +// AgentToolExecutor lists and invokes the editor's MCP tools for the built-in agent. +// editormcp.Server wires itself onto Editor.AgentTools automatically in editormcp.New. +type AgentToolExecutor interface { + ListTools(ctx context.Context) ([]AgentToolSpec, error) + CallTool(ctx context.Context, name string, args json.RawMessage) (AgentToolCallResult, error) +} + +// AgentTaskKind identifies one row of the WHO DOES WHAT routing table on Settings › Models and connections. +// Its string values match AgentTaskRoutesDefs keys persisted in EditorSettings (editor.yaml). +type AgentTaskKind string + +const ( + // AgentTaskSceneEdit routes general scene and data edit requests. + AgentTaskSceneEdit AgentTaskKind = "scene_edits" + // AgentTaskPlaytest routes playtest replay and heatmap analysis requests. + AgentTaskPlaytest AgentTaskKind = "playtest_analysis" + // AgentTaskProblems routes Problems panel explanation and fix proposals. + AgentTaskProblems AgentTaskKind = "problems_fixes" + // AgentTaskAskInPlace routes quick in-place (⌘L) requests. + AgentTaskAskInPlace AgentTaskKind = "ask_in_place" + // AgentTaskArtSound routes sprite, texture, and sound generation requests. + AgentTaskArtSound AgentTaskKind = "art_and_sound" +) + +// AllAgentTaskKinds lists the WHO DOES WHAT rows in the canonical order of docs/design/editor/Settings.dc.html. +var AllAgentTaskKinds = []AgentTaskKind{ + AgentTaskSceneEdit, + AgentTaskPlaytest, + AgentTaskProblems, + AgentTaskAskInPlace, + AgentTaskArtSound, +} + +// Valid reports whether k is a recognized WHO DOES WHAT task kind. +func (k AgentTaskKind) Valid() bool { + switch k { + case AgentTaskSceneEdit, AgentTaskPlaytest, AgentTaskProblems, AgentTaskAskInPlace, AgentTaskArtSound: + return true + default: + return false + } +} + +// Label returns the human-readable task title shown in model error cards and errors. +func (k AgentTaskKind) Label() string { + switch k { + case AgentTaskSceneEdit: + return "Scene and data edits" + case AgentTaskPlaytest: + return "Playtest analysis" + case AgentTaskProblems: + return "Problems and fixes" + case AgentTaskAskInPlace: + return "Ask in place (⌘L)" + case AgentTaskArtSound: + return "Art and sound" + default: + return "Scene and data edits" + } +} + +// AgentModelRoute classifies which execution backend handles a WHO DOES WHAT route label. +type AgentModelRoute string + +const ( + // AgentRouteLocal routes work to the connected local MCP agent (for example Claude Code or Codex). + AgentRouteLocal AgentModelRoute = "local" + // AgentRouteBuiltInDefault routes work to the built-in Anthropic API default model. + AgentRouteBuiltInDefault AgentModelRoute = "builtin_default" + // AgentRouteBuiltInFast routes work to the built-in Anthropic API fast model. + AgentRouteBuiltInFast AgentModelRoute = "builtin_fast" + // AgentRouteNone leaves a task kind unassigned (for example Art and sound when no generator server is connected). + AgentRouteNone AgentModelRoute = "none" +) + +// Valid reports whether r is a recognized task route. +func (r AgentModelRoute) Valid() bool { + switch r { + case AgentRouteLocal, AgentRouteBuiltInDefault, AgentRouteBuiltInFast, AgentRouteNone: + return true + default: + return false + } +} + +// IsBuiltIn reports whether r uses the built-in API key runner rather than a local MCP CLI agent. +func (r AgentModelRoute) IsBuiltIn() bool { + return r == AgentRouteBuiltInDefault || r == AgentRouteBuiltInFast +} + +// AgentQueuedRequest is a prompt queued while the weekly request limit is reached (waiting for user send after reset or limit raise). +type AgentQueuedRequest struct { + ID string + Task AgentTaskKind + Prompt string + QueuedAt time.Time +} + +// AgentModelErrorState describes a live model API error card (such as HTTP 529 overloaded) with retry progress and an optional switch to another connected agent. +type AgentModelErrorState struct { + Provider string + StatusCode int + Headline string + Message string + RetryDelay time.Duration + RetryAttempt int + RetryTotal int + Retrying bool + Task AgentTaskKind + AlternativeAgent string + AlternativeRoute AgentModelRoute +} + +// Body formats the model error card body text matching docs/design/editor/AgentStates.dc.html, +// for example "Retrying in 8 s · try 2 of 4. Playtest analysis can switch to Claude Code for now." +func (m AgentModelErrorState) Body() string { + var parts []string + if m.Retrying && m.RetryTotal > 0 { + secs := int(m.RetryDelay.Round(time.Second) / time.Second) + if secs < 1 { + secs = 1 + } + parts = append(parts, fmt.Sprintf("Retrying in %d s · try %d of %d.", secs, m.RetryAttempt, m.RetryTotal)) + } else if m.RetryTotal > 0 { + parts = append(parts, fmt.Sprintf("Failed after %d of %d tries.", m.RetryAttempt, m.RetryTotal)) + } else if strings.TrimSpace(m.Message) != "" { + parts = append(parts, strings.TrimSpace(m.Message)) + } + if m.AlternativeAgent != "" && m.AlternativeRoute != "" && m.AlternativeRoute != AgentRouteNone { + taskLabel := m.Task.Label() + if taskLabel == "" { + taskLabel = "This work" + } + parts = append(parts, fmt.Sprintf("%s can switch to %s for now.", taskLabel, m.AlternativeAgent)) + } + return strings.Join(parts, " ") +} + +// ResolveAgentModelRoute resolves the configured WHO DOES WHAT route label for task into an execution route. +func (e *Editor) ResolveAgentModelRoute(task AgentTaskKind) AgentModelRoute { + if !task.Valid() { + task = AgentTaskSceneEdit + } + label := strings.TrimSpace(e.AgentTaskRoute(string(task))) + if label == "" || strings.EqualFold(label, "Not connected") { + return AgentRouteNone + } + provider := DefaultBuiltInProviderName + if e != nil { + provider = e.BuiltInAgentProvider() + } + lower := strings.ToLower(label) + provLower := strings.ToLower(provider) + isBuiltInPrefix := strings.HasPrefix(lower, provLower) || strings.HasPrefix(lower, strings.ToLower(DefaultBuiltInProviderName)) + if isBuiltInPrefix { + if strings.Contains(lower, "fast") { + return AgentRouteBuiltInFast + } + return AgentRouteBuiltInDefault + } + return AgentRouteLocal +} + +func (e *Editor) agentRouteDisplayLabel(route AgentModelRoute) string { + provider := DefaultBuiltInProviderName + if e != nil { + provider = e.BuiltInAgentProvider() + } + switch route { + case AgentRouteLocal: + name := "Claude Code" + if c, ok := e.AgentPrimaryClient(); ok && strings.TrimSpace(c.DisplayName) != "" { + name = c.DisplayName + } + return name + " · default" + case AgentRouteBuiltInDefault: + return provider + " · default" + case AgentRouteBuiltInFast: + return provider + " · fast" + default: + return "Not connected" + } +} + +// AgentBuiltInModelForRoute returns the Anthropic model ID for route. +func (e *Editor) AgentBuiltInModelForRoute(route AgentModelRoute) string { + if route == AgentRouteBuiltInFast { + return DefaultBuiltInFastModel + } + return DefaultBuiltInModel +} + +func nextWeeklyReset(now time.Time) time.Time { + // Next Monday 00:00 in now's location (aligned with weekStartISO in agent_settings.go). + y, m, d := now.Date() + loc := now.Location() + midnight := time.Date(y, m, d, 0, 0, 0, 0, loc) + daysUntilMonday := (int(time.Monday) - int(now.Weekday()) + 7) % 7 + if daysUntilMonday == 0 { + daysUntilMonday = 7 + } + return midnight.AddDate(0, 0, daysUntilMonday) +} + +// AgentUsageResetAt returns the next weekly usage reset boundary (Monday 00:00 in the editor's clock location). +func (e *Editor) AgentUsageResetAt() time.Time { + if e == nil { + return nextWeeklyReset(time.Now()) + } + return nextWeeklyReset(e.nowTime()) +} + +// AgentUsageResetLabel returns the formatted reset time shown in the Limit reached chip (for example "00:00"). +func (e *Editor) AgentUsageResetLabel() string { + return e.AgentUsageResetAt().Format("15:04") +} + +// AgentWeeklyLimitReached reports whether a finite weekly request limit is set and has been reached for the current week. +func (e *Editor) AgentWeeklyLimitReached() bool { + if e == nil { + return false + } + limit := e.WeeklyRequestLimit() + if limit <= 0 { + return false + } + return e.AgentUsage().WeeklyRequests >= limit +} + +func (e *Editor) refreshAgentLimitStatus() { + if e == nil || e.agent.mode == AgentModeNone { + return + } + if e.AgentWeeklyLimitReached() { + if e.agent.activeRunCancel == nil { + e.agent.status = AgentStatusLimitReached + e.updateAgentAnnouncement() + } + return + } + if e.agent.status == AgentStatusLimitReached { + e.restoreIdleAgentStatus() + } +} + +// CheckAgentUsageReset checks whether the weekly reset boundary has passed and clears Limit reached if so. +func (e *Editor) CheckAgentUsageReset() { + if e == nil { + return + } + prevReached := e.agent.status == AgentStatusLimitReached + e.refreshAgentLimitStatus() + if prevReached != (e.agent.status == AgentStatusLimitReached) { + e.notify() + } +} + +// AgentQueuedRequests returns a copy of requests waiting in the Agent panel queue. +func (e *Editor) AgentQueuedRequests() []AgentQueuedRequest { + if e == nil || len(e.agent.queued) == 0 { + return nil + } + return slices.Clone(e.agent.queued) +} + +// RemoveQueuedAgentRequest removes one queued request by ID. +func (e *Editor) RemoveQueuedAgentRequest(id string) bool { + if e == nil { + return false + } + for i, q := range e.agent.queued { + if q.ID == id { + e.agent.queued = append(e.agent.queued[:i], e.agent.queued[i+1:]...) + e.notify() + return true + } + } + return false +} + +// SendQueuedAgentRequest dispatches one queued request once the weekly limit has reset or been raised. +// While the weekly limit is still reached, it returns ErrAgentLimitReached and leaves the item queued. +func (e *Editor) SendQueuedAgentRequest(id string) error { + if e == nil { + return errors.New("editor: nil editor") + } + e.refreshAgentLimitStatus() + if e.AgentWeeklyLimitReached() { + return ErrAgentLimitReached + } + idx := -1 + for i, q := range e.agent.queued { + if q.ID == id { + idx = i + break + } + } + if idx < 0 { + return fmt.Errorf("editor: queued request %q not found", id) + } + q := e.agent.queued[idx] + e.agent.queued = append(e.agent.queued[:idx], e.agent.queued[idx+1:]...) + if err := e.SubmitAgentTaskPrompt(q.Task, q.Prompt); err != nil { + // Restore on failure so the user does not lose their queued prompt. + e.agent.queued = slices.Insert(e.agent.queued, idx, q) + e.notify() + return err + } + return nil +} + +// resolveRouteAndRunner picks the effective route, runner, display agent name, and model ID for task. +func (e *Editor) resolveRouteAndRunner(task AgentTaskKind) (route AgentModelRoute, runner AgentRunner, agentName, model string, err error) { + route = e.ResolveAgentModelRoute(task) + hasLocal := len(e.agent.clients) > 0 || e.AgentRunner != nil + hasBuiltIn := e.HasAgentAPIKey(DefaultAgentAPIKeyAccount) + + // If the user explicitly configured API key mode and no external MCP agent is connected, + // route tasks that default to local seamlessly through the built-in API key agent. + if route == AgentRouteLocal && !hasLocal && (e.agent.mode == AgentModeAPIKey || hasBuiltIn) { + route = AgentRouteBuiltInDefault + } + if route == AgentRouteNone { + if e.agent.mode == AgentModeAPIKey && hasBuiltIn { + route = AgentRouteBuiltInDefault + } else if hasLocal { + route = AgentRouteLocal + } else { + return AgentRouteNone, nil, "", "", errors.New("editor: no agent or generator is connected for " + task.Label()) + } + } + + if route.IsBuiltIn() { + model = e.AgentBuiltInModelForRoute(route) + builtInRunner, buildErr := e.newBuiltInAgentRunner() + if buildErr != nil { + return route, nil, "", "", buildErr + } + return route, builtInRunner, e.BuiltInAgentProvider(), model, nil + } + + // Local MCP / external CLI runner. + runner = e.AgentRunner + if runner == nil { + if len(e.agent.clients) == 0 && e.agent.mode != AgentModeLocal { + e.OpenConnectDialog() + return route, nil, "", "", errors.New("editor: no agent connected") + } + runner = defaultCLIAgentRunner() + } + if c, ok := e.AgentPrimaryClient(); ok { + agentName = c.DisplayName + } + return route, runner, agentName, "", nil +} + +// alternativeAgentForRoute returns another connected agent that can take over if the active route fails (e.g. HTTP 529). +func (e *Editor) alternativeAgentForRoute(failedRoute AgentModelRoute) (displayName string, altRoute AgentModelRoute) { + if e == nil { + return "", AgentRouteNone + } + if failedRoute.IsBuiltIn() { + if c, ok := e.AgentPrimaryClient(); ok && len(e.agent.clients) > 0 { + return c.DisplayName, AgentRouteLocal + } + if e.AgentRunner != nil { + if c, ok := e.AgentPrimaryClient(); ok && c.DisplayName != "" { + return c.DisplayName, AgentRouteLocal + } + return "Claude Code", AgentRouteLocal + } + return "", AgentRouteNone + } + if e.HasAgentAPIKey(DefaultAgentAPIKeyAccount) { + return e.BuiltInAgentProvider(), AgentRouteBuiltInDefault + } + return "", AgentRouteNone +} + +// SubmitAgentTaskPrompt submits prompt for task, routing according to WHO DOES WHAT. +// When the weekly request limit is reached, the prompt is queued instead of executed and status shows Limit reached. +func (e *Editor) SubmitAgentTaskPrompt(task AgentTaskKind, prompt string) error { + return e.submitAgentTaskPromptInternal(task, prompt, false) +} + +func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string, skipUsageIncrement bool) error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.playing { + return ErrPlaying + } + if e.agent.mode == AgentModeNone { + return errors.New("editor: agent is disabled") + } + if !task.Valid() { + task = AgentTaskSceneEdit + } + text := strings.TrimSpace(prompt) + if text == "" { + text = strings.TrimSpace(e.agent.composerText) + } + if text == "" { + return nil + } + if e.agent.activeRunCancel != nil { + return errors.New("editor: an agent request is already running") + } + + // Enforce the weekly limit before starting any request; reaching it queues the request instead of running it. + if !skipUsageIncrement && e.AgentWeeklyLimitReached() { + if len(e.agent.queued) >= maxQueuedAgentRequests { + return fmt.Errorf("editor: request queue is full (%d queued requests)", maxQueuedAgentRequests) + } + e.agent.composerText = "" + e.agent.queueSeq++ + e.agent.queued = append(e.agent.queued, AgentQueuedRequest{ + ID: fmt.Sprintf("queued-%d", e.agent.queueSeq), + Task: task, + Prompt: text, + QueuedAt: e.nowTime(), + }) + e.agent.status = AgentStatusLimitReached + e.updateAgentAnnouncement() + e.notify() + return nil + } + + route, runner, clientName, model, err := e.resolveRouteAndRunner(task) + if err != nil { + return err + } + + e.agent.composerText = "" + e.agent.turnSeq++ + e.agent.turnChangeSeq++ + turnID := fmt.Sprintf("turn-%d", e.agent.turnSeq) + agentKind := ExternalAgentAuto + if !route.IsBuiltIn() { + if c, ok := e.AgentPrimaryClient(); ok { + agentKind = DetectExternalAgentKind(c.Name) + } + } + now := e.nowTime() + e.agent.turns = append(e.agent.turns, AgentTurn{ + ID: turnID, + Prompt: text, + Source: "panel", + Status: "running", + AgentName: clientName, + Task: task, + Route: route, + Model: model, + CreatedAt: now, + StartedAt: now, + }) + + e.agent.activeRunID++ + runID := e.agent.activeRunID + ctx, cancel := context.WithCancel(context.Background()) + e.agent.activeRunCancel = cancel + e.agent.activeTurnID = turnID + e.agent.activeRetryNow = make(chan struct{}, 1) + if e.agent.activeRetryCancel != nil { + e.agent.activeRetryCancel() + e.agent.activeRetryCancel = nil + } + e.agent.status = AgentStatusWorking + e.agent.workingStep = 1 + e.agent.workingTotal = 0 + if !skipUsageIncrement { + e.RecordAgentRequest(1) + } + e.updateAgentAnnouncement() + e.upsertTurnNotificationTask(AgentTask{ + ID: turnID, + Title: text, + State: TaskRunning, + ScenePath: e.ScenePath, + }, e.FilePath, time.Time{}) + + req := AgentRequest{ + ThreadID: e.agent.threadID, + SessionID: e.agent.sessionID, + Prompt: text, + ProjectRoot: e.agentProjectRoot(), + ScenePath: e.ScenePath, + SelectedID: e.SelectedID, + AgentKind: agentKind, + Permissions: e.agent.permissions, + Task: task, + Route: route, + Model: model, + } + + if builtIn, ok := runner.(*builtInAgentRunner); ok { + builtIn.runID = runID + builtIn.turnID = turnID + builtIn.retryNow = e.agent.activeRetryNow + } + + go func() { + runErr := runner.Run(ctx, req, func(ev AgentEvent) { + e.postOrRun(func() { + e.applyAgentEventForRun(runID, turnID, ev) + }) + }) + e.postOrRun(func() { + e.finishAgentRun(runID, turnID, runErr, ctx.Err() != nil) + }) + }() + return nil +} + +// RetryAgentTurn immediately retries a turn waiting in model-error backoff (or re-runs a failed turn). +func (e *Editor) RetryAgentTurn(turnID string) error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.agent.activeRunCancel != nil && e.agent.activeTurnID == turnID && e.agent.activeRetryNow != nil { + if e.agent.activeRetryCancel != nil { + e.agent.activeRetryCancel() + e.agent.activeRetryCancel = nil + } + select { + case e.agent.activeRetryNow <- struct{}{}: + default: + } + return nil + } + turn := e.findAgentTurn(turnID) + if turn == nil { + return fmt.Errorf("editor: agent turn %q not found", turnID) + } + if e.agent.activeRunCancel != nil { + return errors.New("editor: another agent request is already running") + } + return e.submitAgentTaskPromptInternal(turn.Task, turn.Prompt, true) +} + +// SwitchAgentTurnToAlternative switches the task kind of a turn experiencing a model error to another connected agent +// (updating WHO DOES WHAT in EditorSettings) and immediately runs the request on that agent. +// Refused with ErrAgentSettingsYouOnly if invoked by an agent. +func (e *Editor) SwitchAgentTurnToAlternative(turnID string) error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.AgentActorActive() { + return ErrAgentSettingsYouOnly + } + turn := e.findAgentTurn(turnID) + if turn == nil { + return fmt.Errorf("editor: agent turn %q not found", turnID) + } + if turn.ModelError == nil || turn.ModelError.AlternativeRoute == "" || turn.ModelError.AlternativeRoute == AgentRouteNone { + return errors.New("editor: no alternative connected agent available") + } + task := turn.Task + if !task.Valid() { + task = AgentTaskSceneEdit + } + prompt := turn.Prompt + altRoute := turn.ModelError.AlternativeRoute + altName := turn.ModelError.AlternativeAgent + altLabel := e.agentRouteDisplayLabel(altRoute) + + // Cancel the retrying/failed built-in run cleanly before switching. + if e.agent.activeRunCancel != nil { + cancel := e.agent.activeRunCancel + e.agent.activeRunCancel = nil + if e.agent.activeRetryCancel != nil { + e.agent.activeRetryCancel() + e.agent.activeRetryCancel = nil + } + e.agent.activeRetryNow = nil + e.agent.activeTurnID = "" + e.agent.activeRunID++ + cancel() + } + e.removeTurnNotificationTask(turnID) + turn.Done = true + turn.Status = "done" + turn.FinishedAt = e.nowTime() + e.agent.turnChangeSeq++ + if turn.ModelError != nil { + turn.ModelError.Retrying = false + } + if turn.Summary == "" { + turn.Summary = fmt.Sprintf("Switched %s to %s.", task.Label(), altName) + } + + if err := e.SetAgentTaskRoute(string(task), altLabel); err != nil { + return err + } + return e.submitAgentTaskPromptInternal(task, prompt, true) +} + +// --- Built-in Anthropic Messages API runner --- + +type builtInAgentRunner struct { + ed *Editor + provider string + tools AgentToolExecutor + endpoint string + client *http.Client + readKey func() (string, error) + runID uint64 + turnID string + retryNow chan struct{} +} + +func (e *Editor) newBuiltInAgentRunner() (*builtInAgentRunner, error) { + rawEndpoint := strings.TrimSpace(e.BuiltInAgentEndpoint) + if rawEndpoint == "" { + rawEndpoint = DefaultBuiltInAgentEndpoint + } + endpoint, err := validateAndResolveBuiltInEndpoint(rawEndpoint) + if err != nil { + return nil, err + } + client := e.BuiltInHTTPClient + if client == nil { + client = &http.Client{ + Timeout: 60 * time.Second, + CheckRedirect: builtInCheckRedirect, + } + } + // Capture the active secret source on the editor goroutine so the runner goroutine never touches core.Scope directly. + var readKey func() (string, error) + if store := e.agentSecretsStore(); store != nil { + readKey = func() (string, error) { + val, ok, gerr := store.Get(AgentAPIKeySecretAccount) + if gerr != nil { + return "", gerr + } + if !ok || strings.TrimSpace(val) == "" { + return "", ErrAgentAPIKeyMissing + } + return strings.TrimSpace(val), nil + } + } else { + kc := e.activeKeychain() + readKey = func() (string, error) { + val, gerr := kc.Get(AgentKeychainServiceName, DefaultAgentAPIKeyAccount) + if gerr != nil { + if errors.Is(gerr, ErrCredentialNotFound) { + return "", ErrAgentAPIKeyMissing + } + return "", gerr + } + if strings.TrimSpace(val) == "" { + return "", ErrAgentAPIKeyMissing + } + return strings.TrimSpace(val), nil + } + } + return &builtInAgentRunner{ + ed: e, + provider: e.BuiltInAgentProvider(), + tools: e.AgentTools, + endpoint: endpoint, + client: client, + readKey: readKey, + }, nil +} + +func isLoopbackHost(host string) bool { + h := strings.ToLower(strings.TrimSpace(host)) + if h == "localhost" { + return true + } + addr, err := netip.ParseAddr(h) + return err == nil && addr.IsLoopback() +} + +func validateAndResolveBuiltInEndpoint(raw string) (string, error) { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || u == nil { + return "", fmt.Errorf("%w: invalid URL", ErrBuiltInEndpointInsecure) + } + if u.User != nil { + return "", fmt.Errorf("%w: URL must not include embedded credentials", ErrBuiltInEndpointInsecure) + } + host := u.Hostname() + if host == "" { + return "", fmt.Errorf("%w: missing host", ErrBuiltInEndpointInsecure) + } + switch strings.ToLower(u.Scheme) { + case "https": + // Allowed for any host. + case "http": + if !isLoopbackHost(host) { + return "", fmt.Errorf("%w: refusing plaintext http:// to non-loopback host %q", ErrBuiltInEndpointInsecure, host) + } + default: + return "", fmt.Errorf("%w: unsupported scheme %q", ErrBuiltInEndpointInsecure, u.Scheme) + } + if u.Path == "" || u.Path == "/" { + u.Path = "/v1/messages" + } + return u.String(), nil +} + +func builtInCheckRedirect(req *http.Request, via []*http.Request) error { + if len(via) == 0 { + return nil + } + if len(via) >= 3 { + return errors.New("editor: too many redirects from model endpoint") + } + orig := via[0].URL + next := req.URL + if orig == nil || next == nil { + return ErrBuiltInEndpointInsecure + } + // Never forward x-api-key across hosts or downgrade https -> http. + if !strings.EqualFold(orig.Hostname(), next.Hostname()) || orig.Port() != next.Port() { + return errors.New("editor: refusing cross-host redirect from model endpoint") + } + if strings.EqualFold(orig.Scheme, "https") && !strings.EqualFold(next.Scheme, "https") { + return errors.New("editor: refusing https-to-http downgrade redirect from model endpoint") + } + return nil +} + +type anthropicRequest struct { + Model string `json:"model"` + MaxTokens int `json:"max_tokens"` + System string `json:"system,omitempty"` + Tools []anthropicToolDef `json:"tools,omitempty"` + Messages []anthropicMessage `json:"messages"` +} + +type anthropicToolDef struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + InputSchema json.RawMessage `json:"input_schema"` +} + +type anthropicMessage struct { + Role string `json:"role"` + Content any `json:"content"` +} + +type anthropicContentBlock struct { + Type string `json:"type"` + Text string `json:"text,omitempty"` + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Input json.RawMessage `json:"input,omitempty"` +} + +type anthropicResponse struct { + ID string `json:"id"` + Model string `json:"model"` + StopReason string `json:"stop_reason"` + Content []anthropicContentBlock `json:"content"` + Usage struct { + InputTokens int `json:"input_tokens"` + OutputTokens int `json:"output_tokens"` + } `json:"usage"` +} + +type anthropicErrorEnvelope struct { + Error struct { + Type string `json:"type"` + Message string `json:"message"` + } `json:"error"` +} + +type modelHTTPError struct { + Provider string + StatusCode int + ErrType string + Message string + Retryable bool +} + +func (e *modelHTTPError) Error() string { + provider := e.Provider + if provider == "" { + provider = DefaultBuiltInProviderName + } + return formatModelErrorHeadline(provider, e.StatusCode, e.ErrType, e.Message) +} + +func isRetryableModelStatus(code int) bool { + switch code { + case http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout, 529: + return true + default: + return false + } +} + +func truncateRunes(s string, maxRunes int) string { + if maxRunes <= 0 || utf8.RuneCountInString(s) <= maxRunes { + return s + } + runes := []rune(s) + return string(runes[:maxRunes]) + "…" +} + +func formatModelErrorHeadline(provider string, statusCode int, errType, msg string) string { + if provider == "" { + provider = DefaultBuiltInProviderName + } + if statusCode == 529 || strings.Contains(strings.ToLower(errType), "overloaded") { + return fmt.Sprintf("%s is overloaded (%d)", provider, statusCode) + } + if statusCode == http.StatusTooManyRequests { + return fmt.Sprintf("%s rate limit reached (429)", provider) + } + if statusCode == http.StatusUnauthorized { + return fmt.Sprintf("%s rejected the API key (401)", provider) + } + if statusCode >= 500 { + return fmt.Sprintf("%s temporary error (%d)", provider, statusCode) + } + if statusCode > 0 { + if trimmed := truncateRunes(strings.TrimSpace(msg), maxModelErrorMessageRunes); trimmed != "" { + return fmt.Sprintf("%s error (%d): %s", provider, statusCode, trimmed) + } + return fmt.Sprintf("%s error (%d)", provider, statusCode) + } + if trimmed := truncateRunes(strings.TrimSpace(msg), maxModelErrorMessageRunes); trimmed != "" { + return fmt.Sprintf("%s request failed: %s", provider, trimmed) + } + return fmt.Sprintf("%s request failed", provider) +} + +func redactSecret(s, secret string) string { + if secret == "" || s == "" { + return s + } + return strings.ReplaceAll(s, secret, "[REDACTED]") +} + +func (r *builtInAgentRunner) Run(ctx context.Context, req AgentRequest, emit func(AgentEvent)) error { + if r.readKey == nil { + r.markAPIKeyFailure("No API key found in the system keychain.") + return ErrAgentAPIKeyMissing + } + apiKey, err := r.readKey() + if err != nil { + r.markAPIKeyFailure("No API key found in the system keychain.") + if errors.Is(err, ErrAgentAPIKeyMissing) { + return ErrAgentAPIKeyMissing + } + return fmt.Errorf("editor: read built-in API key from secrets: %w", err) + } + apiKey = strings.TrimSpace(apiKey) + if apiKey == "" { + r.markAPIKeyFailure("No API key found in the system keychain.") + return ErrAgentAPIKeyMissing + } + + var toolDefs []anthropicToolDef + if r.tools != nil { + specs, listErr := r.tools.ListTools(ctx) + if listErr != nil { + return fmt.Errorf("built-in agent: list editor MCP tools: %w", listErr) + } + toolDefs = make([]anthropicToolDef, 0, len(specs)) + for _, spec := range specs { + schema := spec.InputSchema + if len(schema) == 0 { + schema = json.RawMessage(`{"type":"object"}`) + } + toolDefs = append(toolDefs, anthropicToolDef{ + Name: spec.Name, + Description: spec.Description, + InputSchema: schema, + }) + } + } + + model := strings.TrimSpace(req.Model) + if model == "" { + model = DefaultBuiltInModel + } + + systemPrompt := buildBuiltInSystemPrompt(req) + messages := []anthropicMessage{ + {Role: "user", Content: req.Prompt}, + } + + for iter := 0; iter < builtInMaxToolIterations; iter++ { + if ctx.Err() != nil { + return ctx.Err() + } + resp, err := r.callModelWithRetries(ctx, apiKey, req, anthropicRequest{ + Model: model, + MaxTokens: 4096, + System: systemPrompt, + Tools: toolDefs, + Messages: messages, + }, emit) + if err != nil { + return errors.New(redactSecret(err.Error(), apiKey)) + } + + if resp.Usage.InputTokens > 0 || resp.Usage.OutputTokens > 0 { + emit(AgentEvent{ + Kind: AgentEventUsage, + InputTokens: resp.Usage.InputTokens, + OutputTokens: resp.Usage.OutputTokens, + }) + } + + var toolUses []anthropicContentBlock + for _, block := range resp.Content { + switch block.Type { + case "text": + if strings.TrimSpace(block.Text) != "" { + emit(AgentEvent{Kind: AgentEventMessage, Text: redactSecret(block.Text, apiKey)}) + } + case "tool_use": + toolUses = append(toolUses, block) + } + } + + if len(toolUses) == 0 { + emit(AgentEvent{Kind: AgentEventDone}) + return nil + } + + // Record assistant turn containing the tool calls. + messages = append(messages, anthropicMessage{ + Role: "assistant", + Content: resp.Content, + }) + + toolResults := make([]map[string]any, 0, len(toolUses)) + for _, tu := range toolUses { + if ctx.Err() != nil { + return ctx.Err() + } + stepID := tu.ID + if stepID == "" { + stepID = fmt.Sprintf("tool-%d-%s", iter+1, tu.Name) + } + emit(AgentEvent{ + Kind: AgentEventStep, + StepID: stepID, + StepTitle: formatAgentToolStep(tu.Name), + ToolName: tu.Name, + StepStatus: AgentStepRunning, + }) + + res := r.executeToolWithPrivacy(ctx, tu.Name, tu.Input) + stepStatus := AgentStepDone + if res.IsError { + stepStatus = AgentStepFailed + } + emit(AgentEvent{ + Kind: AgentEventStep, + StepID: stepID, + StepTitle: formatAgentToolStep(tu.Name), + ToolName: tu.Name, + StepStatus: stepStatus, + }) + + resultText := truncateRunes(redactSecret(res.Text, apiKey), builtInMaxToolResultChars) + resultEntry := map[string]any{ + "type": "tool_result", + "tool_use_id": tu.ID, + "is_error": res.IsError, + } + if len(res.PNG) > 0 && len(res.PNG) <= builtInMaxToolImageBytes { + blocks := []map[string]any{} + if resultText != "" { + blocks = append(blocks, map[string]any{"type": "text", "text": resultText}) + } + blocks = append(blocks, map[string]any{ + "type": "image", + "source": map[string]any{ + "type": "base64", + "media_type": "image/png", + "data": base64.StdEncoding.EncodeToString(res.PNG), + }, + }) + resultEntry["content"] = blocks + } else { + if len(res.PNG) > builtInMaxToolImageBytes { + if resultText != "" { + resultText += "\n" + } + resultText += "[image omitted: exceeds maximum size]" + } + resultEntry["content"] = resultText + } + toolResults = append(toolResults, resultEntry) + } + + messages = append(messages, anthropicMessage{ + Role: "user", + Content: toolResults, + }) + } + + return errors.New("built-in agent exceeded maximum tool iterations") +} + +func (r *builtInAgentRunner) markAPIKeyFailure(cause string) { + if r.ed == nil { + return + } + r.ed.postOrRun(func() { + r.ed.agent.failedStep = ConnectStepAPIKey + r.ed.agent.failedCause = cause + r.ed.settingsMu.Lock() + r.ed.agent.builtInKeyChecked = true + r.ed.agent.builtInKeyPresent = false + r.ed.settingsMu.Unlock() + }) +} + +func (r *builtInAgentRunner) executeToolWithPrivacy(ctx context.Context, name string, args json.RawMessage) AgentToolCallResult { + if r.tools == nil { + return AgentToolCallResult{Text: "editor MCP tools are not connected", IsError: true} + } + // Defense-in-depth enforcement of Settings › Tools and Settings › Usage and privacy + // in addition to editormcp.Server's symlink-aware privacy and permission checks. + if r.ed != nil && !r.ed.IsMCPToolEnabled(name) { + return AgentToolCallResult{ + Text: fmt.Sprintf("tool %s is turned off in Settings › Tools; ask the person to enable it", name), + IsError: true, + } + } + privacy := DefaultAgentPrivacyPolicy() + if r.ed != nil { + privacy = r.ed.AgentPrivacy() + } + if name == "viewport_image" && !privacy.ViewportImages { + return AgentToolCallResult{ + Text: PrivacyRefusalError(PrivacyViewportImages, name).Error(), + IsError: true, + } + } + if name == "scene_read" { + var readArgs struct { + File string `json:"file"` + } + if json.Unmarshal(args, &readArgs) == nil { + kind := PrivacySceneAndData + if strings.TrimSpace(readArgs.File) != "" { + kind = ClassifyProjectFilePrivacy(readArgs.File) + } + if !privacy.Allows(kind) { + return AgentToolCallResult{ + Text: PrivacyRefusalError(kind, readArgs.File).Error(), + IsError: true, + } + } + } + } + res, err := r.tools.CallTool(ctx, name, args) + if err != nil { + return AgentToolCallResult{Text: err.Error(), IsError: true} + } + if len(res.PNG) > 0 && !privacy.ViewportImages { + res.PNG = nil + } + return res +} + +func (r *builtInAgentRunner) callModelWithRetries(ctx context.Context, apiKey string, req AgentRequest, payload anthropicRequest, emit func(AgentEvent)) (*anthropicResponse, error) { + delays := AgentModelRetryDelays + maxRetries := len(delays) + hadRetryError := false + provider := r.provider + if provider == "" { + provider = DefaultBuiltInProviderName + } + + for attempt := 0; ; attempt++ { + if ctx.Err() != nil { + return nil, ctx.Err() + } + resp, err := r.doModelRequest(ctx, apiKey, payload) + if err == nil { + if hadRetryError { + emit(AgentEvent{Kind: AgentEventModelRecovered}) + } + return resp, nil + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + + var httpErr *modelHTTPError + retryable := false + statusCode := 0 + errType := "" + msg := redactSecret(err.Error(), apiKey) + if errors.As(err, &httpErr) { + retryable = httpErr.Retryable + statusCode = httpErr.StatusCode + errType = httpErr.ErrType + msg = redactSecret(httpErr.Message, apiKey) + } else if !errors.Is(err, ErrBuiltInEndpointInsecure) && !errors.Is(err, errBuiltInNonRetryable) { + // Transient transport / network errors are retryable. + retryable = true + } + + headline := formatModelErrorHeadline(provider, statusCode, errType, msg) + if statusCode == http.StatusUnauthorized { + r.markAPIKeyFailure(headline) + } + + if !retryable || attempt >= maxRetries { + r.postModelError(ctx, AgentModelErrorState{ + Provider: provider, + StatusCode: statusCode, + Headline: headline, + Message: truncateRunes(msg, maxModelErrorMessageRunes), + RetryAttempt: attempt, + RetryTotal: maxRetries, + Retrying: false, + Task: req.Task, + }, 0, nil) + return nil, errors.New(headline) + } + + // Drain any stale Retry now signal received before this error card is published. + if r.retryNow != nil { + select { + case <-r.retryNow: + default: + } + } + + hadRetryError = true + delay := delays[attempt] + timerCh := make(chan struct{}, 1) + r.postModelError(ctx, AgentModelErrorState{ + Provider: provider, + StatusCode: statusCode, + Headline: headline, + Message: truncateRunes(msg, maxModelErrorMessageRunes), + RetryDelay: delay, + RetryAttempt: attempt + 1, + RetryTotal: maxRetries, + Retrying: true, + Task: req.Task, + }, delay, timerCh) + + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-r.retryNow: + case <-timerCh: + } + } +} + +// postModelError updates the turn's ModelError state AND schedules its retry timer atomically on the editor goroutine, +// preventing any timing race between observing the error card and firing AgentScheduleAfter in tests while honoring ctx cancellation. +func (r *builtInAgentRunner) postModelError(ctx context.Context, state AgentModelErrorState, delay time.Duration, timerCh chan struct{}) { + if r.ed == nil { + return + } + done := make(chan struct{}) + r.ed.postOrRun(func() { + defer close(done) + if r.ed.agent.activeRunID != r.runID { + return + } + turn := r.ed.findAgentTurn(r.turnID) + if turn == nil || turn.Done { + return + } + altName, altRoute := r.ed.alternativeAgentForRoute(turn.Route) + state.AlternativeAgent = altName + state.AlternativeRoute = altRoute + cp := state + turn.ModelError = &cp + r.ed.agent.turnChangeSeq++ + + if r.ed.agent.activeRetryCancel != nil { + r.ed.agent.activeRetryCancel() + r.ed.agent.activeRetryCancel = nil + } + if state.Retrying && timerCh != nil { + runID := r.runID + r.ed.agent.activeRetryCancel = r.ed.scheduleAgentAfter(delay, func() { + if r.ed.agent.activeRunID != runID { + return + } + r.ed.agent.activeRetryCancel = nil + select { + case timerCh <- struct{}{}: + default: + } + }) + } + r.ed.updateAgentAnnouncement() + r.ed.notify() + }) + select { + case <-done: + case <-ctx.Done(): + } +} + +func (r *builtInAgentRunner) doModelRequest(ctx context.Context, apiKey string, payload anthropicRequest) (*anthropicResponse, error) { + body, err := json.Marshal(payload) + if err != nil { + return nil, fmt.Errorf("encode model request: %w", err) + } + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, r.endpoint, bytes.NewReader(body)) + if err != nil { + return nil, fmt.Errorf("build model request: %w", err) + } + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("x-api-key", apiKey) + httpReq.Header.Set("anthropic-version", anthropicAPIVersion) + + resp, err := r.client.Do(httpReq) + if err != nil { + return nil, errors.New(redactSecret(err.Error(), apiKey)) + } + defer func() { _ = resp.Body.Close() }() + + respBytes, err := io.ReadAll(io.LimitReader(resp.Body, builtInMaxResponseBytes+1)) + if err != nil { + return nil, fmt.Errorf("read model response: %w", err) + } + if len(respBytes) > builtInMaxResponseBytes { + return nil, fmt.Errorf("%w: model response exceeded maximum size (%d bytes)", errBuiltInNonRetryable, builtInMaxResponseBytes) + } + + if resp.StatusCode >= 400 { + var env anthropicErrorEnvelope + _ = json.Unmarshal(respBytes, &env) + msg := strings.TrimSpace(env.Error.Message) + if msg == "" { + msg = strings.TrimSpace(string(respBytes)) + } + return nil, &modelHTTPError{ + Provider: r.provider, + StatusCode: resp.StatusCode, + ErrType: env.Error.Type, + Message: truncateRunes(redactSecret(msg, apiKey), maxModelErrorMessageRunes), + Retryable: isRetryableModelStatus(resp.StatusCode), + } + } + + var decoded anthropicResponse + if err := json.Unmarshal(respBytes, &decoded); err != nil { + return nil, fmt.Errorf("%w: decode model response: %v", errBuiltInNonRetryable, err) + } + return &decoded, nil +} + +func buildBuiltInSystemPrompt(req AgentRequest) string { + var b strings.Builder + b.WriteString("You are the NSGo Game Editor's built-in agent. Use the editor's MCP tools to read and edit the open game project cleanly as undoable editor commands.") + if req.ScenePath != "" { + fmt.Fprintf(&b, "\nOpen scene: %s", req.ScenePath) + } + if req.SelectedID != "" { + fmt.Fprintf(&b, "\nSelected object: %s", req.SelectedID) + } + return b.String() +} diff --git a/packages/game/editor/agent_builtin_test.go b/packages/game/editor/agent_builtin_test.go new file mode 100644 index 00000000..f05de0f1 --- /dev/null +++ b/packages/game/editor/agent_builtin_test.go @@ -0,0 +1,442 @@ +package editor_test + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +// #1030 Acceptance 2: Reaching the weekly limit queues the next request and shows "Limit reached · resets 00:00"; +// any attempt by the agent to raise the limit (or mutate You-only settings / read the API key) is refused with ErrAgentSettingsYouOnly. +func TestAgentWeeklyLimitQueuesAndRefusesAgentRaise(t *testing.T) { + var apiHits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + apiHits.Add(1) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": "msg_limit_test", + "model": editor.DefaultBuiltInModel, + "stop_reason": "end_turn", + "content": []map[string]any{ + {"type": "text", "text": "Done."}, + }, + "usage": map[string]int{"input_tokens": 20, "output_tokens": 5}, + }) + })) + defer srv.Close() + + settingsPath := filepath.Join(t.TempDir(), "editor.yaml") + now := time.Date(2026, 11, 26, 14, 10, 0, 0, time.UTC) + + ed := newTestEditor(t) + ed.Now = func() time.Time { return now } + ed.SettingsPath = settingsPath + ed.BuiltInAgentEndpoint = srv.URL + ed.BuiltInHTTPClient = srv.Client() + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), nsgotest.Secrets(map[string]string{ + editor.AgentAPIKeySecretAccount: "sk-ant-limit-test-secret", + })) + + // Configure Built-in API key mode and open Usage and privacy in Settings. + ed.OpenConnectDialogAt(editor.ConnectStepAPIKey) + app.Settle() + app.Press("id:connect-done") + app.Settle() + + ed.OpenSettingsPage(editor.SettingsPageUsage) + app.Settle() + if !app.Exists("id:settings-usage-page") { + t.Fatal("Usage and privacy page did not render") + } + + // Person sets weekly limit to 2 requests via UI. + app.Clear("id:settings-usage-limit-input") + app.Type("id:settings-usage-limit-input", "2") + app.Press("id:settings-usage-limit-apply") + app.Settle() + if ed.WeeklyRequestLimit() != 2 { + t.Fatalf("weekly limit = %d, want 2", ed.WeeklyRequestLimit()) + } + ed.CloseSettings() + app.Settle() + + // Run 2 requests -> both hit the endpoint and succeed. + for i := range 2 { + if err := ed.SubmitAgentPrompt("Place coin"); err != nil { + t.Fatalf("request %d: %v", i+1, err) + } + app.WaitUntil(5*time.Second, func() bool { return !ed.AgentWorking() }) + app.Settle() + } + if apiHits.Load() != 2 { + t.Fatalf("apiHits = %d, want 2", apiHits.Load()) + } + if ed.AgentStatus() != editor.AgentStatusLimitReached { + t.Fatalf("status after reaching limit = %q, want %q", ed.AgentStatus(), editor.AgentStatusLimitReached) + } + if got := agentViewText(t, app, "id:agent-status-text"); got != "Limit reached · resets 00:00" { + t.Fatalf("status chip = %q, want Limit reached · resets 00:00", got) + } + if !app.Exists("id:agent-status-usage") { + t.Fatal("missing Usage link beside Limit reached chip") + } + + // Submitting a 3rd request queues it without hitting the model endpoint. + if err := ed.SubmitAgentPrompt("Make the coins spin slowly"); err != nil { + t.Fatalf("queued submit returned error: %v", err) + } + app.Settle() + if apiHits.Load() != 2 { + t.Fatalf("queued request should not have called endpoint: apiHits=%d", apiHits.Load()) + } + queued := ed.AgentQueuedRequests() + if len(queued) != 1 || queued[0].Prompt != "Make the coins spin slowly" { + t.Fatalf("queued = %+v, want 1 prompt", queued) + } + if !app.Exists("id:agent-queued-section") || !strings.Contains(agentViewText(t, app, "id:agent-queued-heading"), "QUEUED · 1") { + t.Fatal("Agent panel missing QUEUED · 1 section") + } + + // Sending a queued request while still at limit must fail with ErrAgentLimitReached. + if err := ed.SendQueuedAgentRequest(queued[0].ID); !errors.Is(err, editor.ErrAgentLimitReached) { + t.Fatalf("SendQueuedAgentRequest at limit = %v, want ErrAgentLimitReached", err) + } + + // Any attempt by an agent to raise the weekly limit, alter You-only settings, or read the API key MUST be refused. + if err := ed.WithAgentActor(func() error { + return ed.SetWeeklyRequestLimit(999) + }); !errors.Is(err, editor.ErrAgentSettingsYouOnly) { + t.Fatalf("agent SetWeeklyRequestLimit = %v, want ErrAgentSettingsYouOnly", err) + } + if err := ed.WithAgentActor(func() error { + s := ed.Settings() + higher := 999 + if s.Agent == nil { + s.Agent = &editor.AgentSettings{} + } + s.Agent.WeeklyRequestLimit = &higher + return ed.ApplySettings(s) + }); !errors.Is(err, editor.ErrAgentSettingsYouOnly) { + t.Fatalf("agent ApplySettings = %v, want ErrAgentSettingsYouOnly", err) + } + if err := ed.WithAgentActor(func() error { + return ed.SetAgentTaskRoute(string(editor.AgentTaskPlaytest), "Claude Code · default") + }); !errors.Is(err, editor.ErrAgentSettingsYouOnly) { + t.Fatalf("agent SetAgentTaskRoute = %v, want ErrAgentSettingsYouOnly", err) + } + if err := ed.WithAgentActor(func() error { + return ed.SetAgentPrivacy(editor.PrivacyGoSource, true) + }); !errors.Is(err, editor.ErrAgentSettingsYouOnly) { + t.Fatalf("agent SetAgentPrivacy = %v, want ErrAgentSettingsYouOnly", err) + } + if err := ed.WithAgentActor(func() error { + return ed.StoreAgentAPIKey(editor.DefaultAgentAPIKeyAccount, "sk-agent-injected") + }); !errors.Is(err, editor.ErrAgentSettingsYouOnly) { + t.Fatalf("agent StoreAgentAPIKey = %v, want ErrAgentSettingsYouOnly", err) + } + if err := ed.WithAgentActor(func() error { + _, err := ed.AgentAPIKey(editor.DefaultAgentAPIKeyAccount) + return err + }); !errors.Is(err, editor.ErrAgentSettingsYouOnly) { + t.Fatalf("agent AgentAPIKey = %v, want ErrAgentSettingsYouOnly", err) + } + if ed.WeeklyRequestLimit() != 2 { + t.Fatalf("agent mutated weekly limit to %d, want 2", ed.WeeklyRequestLimit()) + } + + // Clicking the Usage link in the header opens Usage and privacy so the person can raise the limit. + app.Press("id:agent-status-usage") + app.Settle() + if !ed.SettingsOpen() || ed.SettingsPage() != editor.SettingsPageUsage { + t.Fatalf("Usage link opened page=%q open=%v, want usage/true", ed.SettingsPage(), ed.SettingsOpen()) + } + app.Clear("id:settings-usage-limit-input") + app.Type("id:settings-usage-limit-input", "10") + app.Press("id:settings-usage-limit-apply") + app.Settle() + ed.CloseSettings() + app.Settle() + + if ed.WeeklyRequestLimit() != 10 || ed.AgentStatus() != editor.AgentStatusConnected { + t.Fatalf("after person raises limit: limit=%d status=%q", ed.WeeklyRequestLimit(), ed.AgentStatus()) + } + + // Person sends the queued request from the queue list. + app.Press("id:agent-queued-send-0") + app.WaitUntil(5*time.Second, func() bool { return !ed.AgentWorking() && apiHits.Load() == 3 }) + app.Settle() + if len(ed.AgentQueuedRequests()) != 0 { + t.Fatalf("queue not drained after sending: %+v", ed.AgentQueuedRequests()) + } + + // Verify automatic reset when clock crosses weekly reset boundary (Monday 00:00). + if err := ed.SetWeeklyRequestLimit(3); err != nil { + t.Fatal(err) + } + if !ed.AgentWeeklyLimitReached() { + t.Fatal("expected limit reached at 3/3") + } + now = ed.AgentUsageResetAt().Add(time.Minute) + ed.CheckAgentUsageReset() + if ed.AgentWeeklyLimitReached() || ed.AgentUsage().WeeklyRequests != 0 { + t.Fatalf("usage did not reset after ResetAt: %+v", ed.AgentUsage()) + } + + // Verify secret key never leaked into editor.yaml. + rawSettings, err := os.ReadFile(settingsPath) + if err != nil { + t.Fatalf("read persisted editor.yaml: %v", err) + } + if strings.Contains(string(rawSettings), "sk-ant-limit-test-secret") { + t.Fatal("API key leaked into editor.yaml") + } +} + +// #1030 Acceptance 3: A fake endpoint returning 529 shows the model error card with its retry count +// ("Anthropic API is overloaded (529)", "Retrying in 4 s · try 1 of 4", then "Retrying in 8 s · try 2 of 4"), +// supports Retry now, and switching the work to another connected agent updates WHO DOES WHAT and runs the request there. +func TestBuiltInAgent529RetryBackoffAndSwitchToConnectedAgent(t *testing.T) { + var apiHits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + apiHits.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(529) + _ = json.NewEncoder(w).Encode(map[string]any{ + "type": "error", + "error": map[string]string{ + "type": "overloaded_error", + "message": "Overloaded", + }, + }) + })) + defer srv.Close() + + sched := &fakeRetryScheduler{} + var claudeMu sync.Mutex + var claudeReqs []editor.AgentRequest + + ed := newTestEditor(t) + ed.AgentScheduleAfter = sched.schedule + ed.BuiltInAgentEndpoint = srv.URL + ed.BuiltInHTTPClient = srv.Client() + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + claudeMu.Lock() + claudeReqs = append(claudeReqs, req) + claudeMu.Unlock() + emit(editor.AgentEvent{ + Kind: editor.AgentEventStep, + StepID: "claude-step-1", + StepTitle: "Analyzed playtest replay via Claude Code", + StepStatus: editor.AgentStepDone, + }) + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Claude Code finished the playtest report."}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone}) + return nil + }) + ed.SetRightRailTab(editor.RightTabAgent) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), nsgotest.Secrets(map[string]string{ + editor.AgentAPIKeySecretAccount: "sk-ant-529-test-secret", + })) + + // Connect Claude Code as an external MCP client alongside the built-in Anthropic API. + ed.NotifyAgentMCPConnected(editor.AgentClientInfo{ + ID: "claude-1", + Name: "claude-code", + Transport: "stdio", + }) + app.Settle() + + // Playtest analysis defaults to Anthropic API · fast in WHO DOES WHAT. + if got := ed.ResolveAgentModelRoute(editor.AgentTaskPlaytest); got != editor.AgentRouteBuiltInFast { + t.Fatalf("default playtest route = %q, want %q", got, editor.AgentRouteBuiltInFast) + } + + if err := ed.SubmitAgentTaskPrompt(editor.AgentTaskPlaytest, "Analyze floor 3 deaths"); err != nil { + t.Fatalf("SubmitAgentTaskPrompt: %v", err) + } + + // Try 1 fails with 529 -> card shows "Anthropic API is overloaded (529)" and "Retrying in 4 s · try 1 of 4". + app.WaitUntil(5*time.Second, func() bool { + turns := ed.AgentTurns() + return len(turns) == 1 && turns[0].ModelError != nil && turns[0].ModelError.RetryAttempt == 1 + }) + app.Settle() + + if title := agentViewText(t, app, "id:agent-turn-model-error-title-0"); title != "Anthropic API is overloaded (529)" { + t.Fatalf("model error title = %q, want Anthropic API is overloaded (529)", title) + } + if body := agentViewText(t, app, "id:agent-turn-model-error-body-0"); !strings.Contains(body, "Retrying in 4 s · try 1 of 4") || !strings.Contains(body, "Claude Code") { + t.Fatalf("model error body (try 1) = %q", body) + } + if !app.Exists("id:agent-turn-retry-0") || !app.Exists("id:agent-turn-switch-0") { + t.Fatal("model error card missing Retry now or Use Claude Code button") + } + + // Fire backoff timer -> try 2 fails with 529 -> "Retrying in 8 s · try 2 of 4". + sched.fireLast() + app.WaitUntil(5*time.Second, func() bool { + turns := ed.AgentTurns() + return len(turns) == 1 && turns[0].ModelError != nil && turns[0].ModelError.RetryAttempt == 2 + }) + app.Settle() + if body := agentViewText(t, app, "id:agent-turn-model-error-body-0"); !strings.Contains(body, "Retrying in 8 s · try 2 of 4") { + t.Fatalf("model error body (try 2) = %q, want Retrying in 8 s · try 2 of 4", body) + } + + // Clicking "Retry now" immediately performs try 3 -> "Retrying in 16 s · try 3 of 4". + app.Press("id:agent-turn-retry-0") + app.WaitUntil(5*time.Second, func() bool { + turns := ed.AgentTurns() + return len(turns) == 1 && turns[0].ModelError != nil && turns[0].ModelError.RetryAttempt == 3 + }) + app.Settle() + wantDelays := []time.Duration{4 * time.Second, 8 * time.Second, 16 * time.Second} + if !slices.Equal(sched.delays(), wantDelays) { + t.Fatalf("model retry delays = %v, want %v", sched.delays(), wantDelays) + } + + // An agent actor cannot invoke SwitchAgentTurnToAlternative (You only). + if err := ed.WithAgentActor(func() error { + return ed.SwitchAgentTurnToAlternative(ed.AgentTurns()[0].ID) + }); !errors.Is(err, editor.ErrAgentSettingsYouOnly) { + t.Fatalf("agent SwitchAgentTurnToAlternative = %v, want ErrAgentSettingsYouOnly", err) + } + + usageBeforeSwitch := ed.AgentUsage().WeeklyRequests + + // Clicking "Use Claude Code" switches Playtest analysis to Claude Code and runs the request there without double-charging usage. + app.Press("id:agent-turn-switch-0") + app.WaitUntil(5*time.Second, func() bool { + claudeMu.Lock() + n := len(claudeReqs) + claudeMu.Unlock() + return n == 1 && !ed.AgentWorking() + }) + app.Settle() + + if got := ed.ResolveAgentModelRoute(editor.AgentTaskPlaytest); got != editor.AgentRouteLocal { + t.Fatalf("playtest route after switch = %q, want %q", got, editor.AgentRouteLocal) + } + if got := ed.AgentTaskRoute(string(editor.AgentTaskPlaytest)); got != "Claude Code · default" { + t.Fatalf("persisted playtest route label = %q, want Claude Code · default", got) + } + if got := ed.AgentUsage().WeeklyRequests; got != usageBeforeSwitch { + t.Fatalf("switching agent double-charged weekly requests: got %d, want %d", got, usageBeforeSwitch) + } + claudeMu.Lock() + gotReq := claudeReqs[0] + claudeMu.Unlock() + if gotReq.Prompt != "Analyze floor 3 deaths" || gotReq.Task != editor.AgentTaskPlaytest { + t.Fatalf("Claude Code received req = %+v", gotReq) + } + turns := ed.AgentTurns() + if len(turns) != 2 || !turns[1].Done || !strings.Contains(turns[1].Summary, "Claude Code finished the playtest report.") { + t.Fatalf("switched turn = %+v", turns) + } + if apiHits.Load() < 3 { + t.Fatalf("expected at least 3 529 attempts before switching, got %d", apiHits.Load()) + } +} + +// Verifies endpoint URL validation (no plaintext http:// to remote hosts, no embedded credentials), +// secret redaction on error responses, and response size cap without pointless retries. +func TestBuiltInAgentHardeningEndpointRedactionAndLimits(t *testing.T) { + const secret = "sk-ant-super-secret-redaction-check-999" + + // 1. Refuse insecure non-loopback http://, file://, and embedded-userinfo endpoints before sending key. + for _, badURL := range []string{ + "http://api.anthropic.com/v1/messages", + "file:///etc/passwd", + "https://user:pass@api.anthropic.com/v1/messages", + } { + ed := newTestEditor(t) + ed.AgentSecretStore = editor.NewMemorySecretStore(map[string]string{ + editor.AgentAPIKeySecretAccount: secret, + }) + ed.BuiltInAgentEndpoint = badURL + if err := ed.SubmitAgentTaskPrompt(editor.AgentTaskPlaytest, "test"); !errors.Is(err, editor.ErrBuiltInEndpointInsecure) { + t.Fatalf("endpoint %q: got err=%v, want ErrBuiltInEndpointInsecure", badURL, err) + } + } + + // 2. Redact API key if an upstream error echoes it, and reject oversized responses without retrying. + var oversizedHits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/echo-secret" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(map[string]any{ + "error": map[string]string{ + "type": "invalid_request_error", + "message": "bad header value " + r.Header.Get("x-api-key"), + }, + }) + return + } + oversizedHits.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(strings.Repeat("a", (8<<20)+1024))) + })) + defer srv.Close() + + ed := newTestEditor(t) + ed.AgentSecretStore = editor.NewMemorySecretStore(map[string]string{ + editor.AgentAPIKeySecretAccount: secret, + }) + ed.BuiltInAgentEndpoint = srv.URL + "/echo-secret" + ed.BuiltInHTTPClient = srv.Client() + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 800)) + + if err := ed.SubmitAgentTaskPrompt(editor.AgentTaskPlaytest, "Trigger 400"); err != nil { + t.Fatalf("submit 400: %v", err) + } + app.WaitUntil(5*time.Second, func() bool { return !ed.AgentWorking() && len(ed.AgentTurns()) == 1 && ed.AgentTurns()[0].Done }) + turn := ed.AgentTurns()[0] + if strings.Contains(turn.Error, secret) || (turn.ModelError != nil && (strings.Contains(turn.ModelError.Headline, secret) || strings.Contains(turn.ModelError.Message, secret))) { + t.Fatalf("API key leaked into turn error state: err=%q modelErr=%+v", turn.Error, turn.ModelError) + } + if !strings.Contains(turn.Error, "[REDACTED]") { + t.Fatalf("expected [REDACTED] in error, got %q", turn.Error) + } + + // Oversized response fails cleanly in 1 attempt without burning 4 retries. + ed.BuiltInAgentEndpoint = srv.URL + "/oversized" + if err := ed.SubmitAgentTaskPrompt(editor.AgentTaskPlaytest, "Trigger oversized"); err != nil { + t.Fatalf("submit oversized: %v", err) + } + app.WaitUntil(5*time.Second, func() bool { return !ed.AgentWorking() && len(ed.AgentTurns()) == 2 && ed.AgentTurns()[1].Done }) + if got := oversizedHits.Load(); got != 1 { + t.Fatalf("oversized response retried %d times, want 1 attempt only", got) + } + if !strings.Contains(ed.AgentTurns()[1].Error, "maximum size") { + t.Fatalf("unexpected oversized error: %q", ed.AgentTurns()[1].Error) + } + + // MemorySecretStore.String() must redact values. + if s := ed.AgentSecretStore.(*editor.MemorySecretStore).String(); strings.Contains(s, secret) || !strings.Contains(s, "[REDACTED]") { + t.Fatalf("MemorySecretStore.String leaked or did not redact: %q", s) + } +} diff --git a/packages/game/editor/agent_settings.go b/packages/game/editor/agent_settings.go index df53cac9..223f60cd 100644 --- a/packages/game/editor/agent_settings.go +++ b/packages/game/editor/agent_settings.go @@ -573,7 +573,7 @@ func (e *Editor) persistEditorSettings() error { return SaveEditorSettings(e.SettingsPath, &s) } -// --- Models & connections + system keychain API key --- +// --- Models & connections + system keychain / core.Secrets API key --- func agentAPIKeyAccount(account string) string { acc := strings.TrimSpace(account) @@ -583,7 +583,64 @@ func agentAPIKeyAccount(account string) string { return acc } -// StoreAgentAPIKey saves the built-in model API key exclusively in the system keychain +func agentSecretStoreAccount(account string) string { + acc := agentAPIKeyAccount(account) + if acc == DefaultAgentAPIKeyAccount { + return AgentAPIKeySecretAccount + } + return "agent." + acc + ".api_key" +} + +// agentSecretsStore returns the active NSGo core.Secrets handle (or explicit AgentSecretStore override) +// when no explicit Editor.Keychain override is configured. +func (e *Editor) agentSecretsStore() AgentSecretStore { + if e == nil { + return nil + } + if e.AgentSecretStore != nil { + return e.AgentSecretStore + } + if e.Keychain != nil { + return nil + } + if cx := e.agent.getScope(); cx != nil && !cx.Disposed() { + return cx.Secrets() + } + return nil +} + +func (e *Editor) writeAgentSecret(account, value string) error { + if store := e.agentSecretsStore(); store != nil { + return store.Set(agentSecretStoreAccount(account), value) + } + return e.activeKeychain().Set(AgentKeychainServiceName, agentAPIKeyAccount(account), value) +} + +func (e *Editor) readAgentSecret(account string) (string, error) { + if store := e.agentSecretsStore(); store != nil { + val, ok, err := store.Get(agentSecretStoreAccount(account)) + if err != nil { + return "", err + } + if !ok || strings.TrimSpace(val) == "" { + return "", ErrCredentialNotFound + } + return val, nil + } + return e.activeKeychain().Get(AgentKeychainServiceName, agentAPIKeyAccount(account)) +} + +func (e *Editor) deleteAgentSecret(account string) error { + if store := e.agentSecretsStore(); store != nil { + return store.Delete(agentSecretStoreAccount(account)) + } + if err := e.activeKeychain().Delete(AgentKeychainServiceName, agentAPIKeyAccount(account)); err != nil && !errors.Is(err, ErrCredentialNotFound) { + return err + } + return nil +} + +// StoreAgentAPIKey saves the built-in model API key exclusively in NSGo's core.Secrets / system keychain // (never in editor.yaml or any project file). Refused when invoked by an agent. func (e *Editor) StoreAgentAPIKey(account, apiKey string) error { if e == nil { @@ -597,17 +654,27 @@ func (e *Editor) StoreAgentAPIKey(account, apiKey string) error { return errors.New("editor: API key must not be empty") } acc := agentAPIKeyAccount(account) - if err := e.activeKeychain().Set(AgentKeychainServiceName, acc, apiKey); err != nil { + if err := e.writeAgentSecret(acc, apiKey); err != nil { return err } e.settingsMu.Lock() - e.agent.builtInKeyChecked = true - e.agent.builtInKeyPresent = true + if acc == DefaultAgentAPIKeyAccount { + e.agent.builtInKeyChecked = true + e.agent.builtInKeyPresent = true + } a := e.ensureAgentSettings() if strings.TrimSpace(a.BuiltInProvider) == "" { a.BuiltInProvider = DefaultBuiltInProviderName } e.settingsMu.Unlock() + if acc == DefaultAgentAPIKeyAccount && e.agent.mode == AgentModeAPIKey && (e.agent.status == AgentStatusNotConnected || e.agent.status == AgentStatusDisconnected) { + if e.AgentWeeklyLimitReached() { + e.agent.status = AgentStatusLimitReached + } else { + e.agent.status = AgentStatusConnected + } + e.updateAgentAnnouncement() + } if err := e.persistEditorSettings(); err != nil { e.notify() return err @@ -617,7 +684,7 @@ func (e *Editor) StoreAgentAPIKey(account, apiKey string) error { return nil } -// DeleteAgentAPIKey removes the built-in model API key from the system keychain. +// DeleteAgentAPIKey removes the built-in model API key from NSGo's core.Secrets / system keychain. // Refused when invoked by an agent. func (e *Editor) DeleteAgentAPIKey(account string) error { if e == nil { @@ -627,17 +694,23 @@ func (e *Editor) DeleteAgentAPIKey(account string) error { return ErrAgentSettingsYouOnly } acc := agentAPIKeyAccount(account) - if err := e.activeKeychain().Delete(AgentKeychainServiceName, acc); err != nil && !errors.Is(err, ErrCredentialNotFound) { + if err := e.deleteAgentSecret(acc); err != nil { return err } e.settingsMu.Lock() - e.agent.builtInKeyChecked = true - e.agent.builtInKeyPresent = false - if e.settings.Agent != nil { - e.settings.Agent.BuiltInProvider = "" - e.settings.Agent = cloneAgentSettings(e.settings.Agent) + if acc == DefaultAgentAPIKeyAccount { + e.agent.builtInKeyChecked = true + e.agent.builtInKeyPresent = false + if e.settings.Agent != nil { + e.settings.Agent.BuiltInProvider = "" + e.settings.Agent = cloneAgentSettings(e.settings.Agent) + } } e.settingsMu.Unlock() + if acc == DefaultAgentAPIKeyAccount && e.agent.mode == AgentModeAPIKey && len(e.agent.clients) == 0 { + e.agent.status = AgentStatusNotConnected + e.updateAgentAnnouncement() + } if err := e.persistEditorSettings(); err != nil { e.notify() return err @@ -647,7 +720,7 @@ func (e *Editor) DeleteAgentAPIKey(account string) error { return nil } -// AgentAPIKey retrieves the built-in model API key from the system keychain. +// AgentAPIKey retrieves the built-in model API key from NSGo's core.Secrets / system keychain. // Refused when invoked by an agent actor so secrets can never leak through MCP tools. func (e *Editor) AgentAPIKey(account string) (string, error) { if e == nil { @@ -656,15 +729,15 @@ func (e *Editor) AgentAPIKey(account string) (string, error) { if e.AgentActorActive() { return "", ErrAgentSettingsYouOnly } - return e.activeKeychain().Get(AgentKeychainServiceName, agentAPIKeyAccount(account)) + return e.readAgentSecret(account) } -// RefreshAgentAPIKeyStatus queries the system keychain for the built-in API key and caches whether one is present. +// RefreshAgentAPIKeyStatus queries NSGo's core.Secrets / system keychain for the built-in API key and caches whether one is present. func (e *Editor) RefreshAgentAPIKeyStatus() bool { if e == nil { return false } - val, err := e.activeKeychain().Get(AgentKeychainServiceName, DefaultAgentAPIKeyAccount) + val, err := e.readAgentSecret(DefaultAgentAPIKeyAccount) present := err == nil && strings.TrimSpace(val) != "" e.settingsMu.Lock() e.agent.builtInKeyChecked = true @@ -673,18 +746,18 @@ func (e *Editor) RefreshAgentAPIKeyStatus() bool { return present } -// HasAgentAPIKey reports whether a built-in API key is currently stored in the system keychain. +// HasAgentAPIKey reports whether a built-in API key is currently stored in NSGo's core.Secrets / system keychain. func (e *Editor) HasAgentAPIKey(account string) bool { if e == nil { return false } acc := agentAPIKeyAccount(account) if acc != DefaultAgentAPIKeyAccount { - val, err := e.activeKeychain().Get(AgentKeychainServiceName, acc) + val, err := e.readAgentSecret(acc) return err == nil && strings.TrimSpace(val) != "" } - if e.Keychain != nil { - val, err := e.Keychain.Get(AgentKeychainServiceName, acc) + if e.AgentSecretStore != nil || e.Keychain != nil { + val, err := e.readAgentSecret(acc) present := err == nil && strings.TrimSpace(val) != "" e.settingsMu.Lock() e.agent.builtInKeyChecked = true @@ -692,6 +765,22 @@ func (e *Editor) HasAgentAPIKey(account string) bool { e.settingsMu.Unlock() return present } + if store := e.agentSecretsStore(); store != nil { + e.settingsMu.RLock() + checked := e.agent.builtInKeyChecked + present := e.agent.builtInKeyPresent + e.settingsMu.RUnlock() + if checked { + return present + } + val, ok, err := store.Get(AgentAPIKeySecretAccount) + present = err == nil && ok && strings.TrimSpace(val) != "" + e.settingsMu.Lock() + e.agent.builtInKeyChecked = true + e.agent.builtInKeyPresent = present + e.settingsMu.Unlock() + return present + } e.settingsMu.RLock() needCheck := !e.agent.builtInKeyChecked && e.settings.Agent != nil && strings.TrimSpace(e.settings.Agent.BuiltInProvider) != "" present := e.agent.builtInKeyPresent @@ -1183,6 +1272,7 @@ func (e *Editor) SetWeeklyRequestLimit(limit int) error { v := limit a.WeeklyRequestLimit = &v e.settingsMu.Unlock() + e.refreshAgentLimitStatus() if err := e.persistEditorSettings(); err != nil { e.notify() return err @@ -1208,6 +1298,7 @@ func (e *Editor) RecordAgentRequest(count int) { } a.Usage.WeeklyRequests += count e.settingsMu.Unlock() + e.refreshAgentLimitStatus() _ = e.persistEditorSettings() e.notify() } diff --git a/packages/game/editor/agent_ui.go b/packages/game/editor/agent_ui.go index d0399a3f..52cbcf1e 100644 --- a/packages/game/editor/agent_ui.go +++ b/packages/game/editor/agent_ui.go @@ -257,6 +257,8 @@ func compactAgentChip(ed *Editor, rev *core.Signal[uint64], p SpecPalette) core. col = p.Warning.Fg case AgentStatusDisconnected: col = p.Removed.Fg + case AgentStatusLimitReached: + col = p.Removed.Fg case AgentStatusReconnecting: col = p.TextFaint } @@ -273,6 +275,9 @@ func compactAgentChip(ed *Editor, rev *core.Signal[uint64], p SpecPalette) core. _ = rev.Get() switch ed.AgentStatus() { case AgentStatusConnected: + if len(ed.AgentClients()) == 0 && (ed.AgentMode() == AgentModeAPIKey || ed.HasAgentAPIKey(DefaultAgentAPIKeyAccount)) { + return "API" + } return "MCP" case AgentStatusWorking: return ed.T("agent.status.workingShort") @@ -282,6 +287,8 @@ func compactAgentChip(ed *Editor, rev *core.Signal[uint64], p SpecPalette) core. return ed.T("agent.status.reconnectingShort") case AgentStatusDisconnected: return ed.T("agent.status.disconnected") + case AgentStatusLimitReached: + return ed.T("agent.status.limitShort") default: return ed.T("agent.connectShort") } @@ -369,6 +376,9 @@ func AgentStatusChipView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c Role: core.RoleButton, LabelFunc: func() string { _ = rev.Get() + if len(ed.AgentClients()) == 0 && (ed.AgentMode() == AgentModeAPIKey || ed.HasAgentAPIKey(DefaultAgentAPIKeyAccount)) { + return fmt.Sprintf("Connected · API (%s)", ed.AgentStatusTooltip()) + } return fmt.Sprintf("Connected · MCP (%s)", ed.AgentStatusTooltip()) }, Style: core.Style{ @@ -397,8 +407,14 @@ func AgentStatusChipView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c }, }, core.Text{ - TestID: "agent-status-text", - Content: "Connected · MCP", + TestID: "agent-status-text", + ContentFunc: func() string { + _ = rev.Get() + if len(ed.AgentClients()) == 0 && (ed.AgentMode() == AgentModeAPIKey || ed.HasAgentAPIKey(DefaultAgentAPIKeyAccount)) { + return "Connected · API" + } + return "Connected · MCP" + }, Style: core.Style{ FontSize: 11.5, Color: p.TextMuted, @@ -667,6 +683,74 @@ func AgentStatusChipView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c }, } + case AgentStatusLimitReached: + return core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 6, + }, + Children: []core.Node{ + core.View{ + TestID: "agent-status-chip", + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Height: core.Pt(24), + Padding: core.Symmetric(0, 10), + Gap: 6, + CornerRadius: 12, + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Gauge(), + Style: core.Style{ + Width: core.Pt(13), + Height: core.Pt(13), + Color: p.Removed.Fg, + FlexShrink: 0, + }, + }, + core.Text{ + TestID: "agent-status-text", + ContentFunc: func() string { + _ = rev.Get() + return fmt.Sprintf("Limit reached · resets %s", ed.AgentUsageResetLabel()) + }, + Style: core.Style{ + FontSize: 11.5, + Color: p.TextSecondary, + }, + }, + }, + }, + ui.Button{ + TestID: "agent-status-usage", + Text: "Usage", + Label: "Open Usage and privacy settings", + Variant: ui.ButtonGhost, + Size: ui.SizeSmall, + Color: func() core.Color { return p.Panel }, + TextStyle: core.Style{ + FontSize: 11.5, + FontWeight: 500, + Color: p.Accent.Fg, + }, + Style: core.Style{ + Height: core.Pt(24), + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.OpenSettingsPage(SettingsPageUsage) + }, + }, + }, + } + default: return core.View{ TestID: "agent-status-chip", @@ -759,12 +843,18 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N threadKey := core.NewMemo(cx, func() string { _ = rev.Get() var b strings.Builder - fmt.Fprintf(&b, "%s|%s|%d|%d|%s|%d|", ed.ResolvedLanguage(), ed.AgentStatus(), len(ed.agent.turns), ed.AgentTurnSeq(), ed.review.outcome, ed.review.uiRev) + fmt.Fprintf(&b, "%s|%s|%d|%d|%s|%d|%d|", ed.ResolvedLanguage(), ed.AgentStatus(), len(ed.agent.turns), ed.AgentTurnSeq(), ed.review.outcome, ed.review.uiRev, len(ed.agent.queued)) for _, t := range ed.agent.turns { fmt.Fprintf(&b, "%s:%s:%d:%v:%v:%v:%s:%s:%d:%d:%d|", t.ID, t.Status, len(t.Steps), t.Done, t.Stopped, t.SkipPlan, t.ReviewState, t.CheckpointID, len(t.Summary), len(t.Reply), len(t.Error)) for _, st := range t.Steps { fmt.Fprintf(&b, "%s=%s;", st.ID, st.Status) } + if t.ModelError != nil { + fmt.Fprintf(&b, "me=%d:%d:%d:%v:%s:%s;", t.ModelError.StatusCode, t.ModelError.RetryAttempt, t.ModelError.RetryTotal, t.ModelError.Retrying, t.ModelError.Headline, t.ModelError.AlternativeAgent) + } + } + for _, q := range ed.agent.queued { + fmt.Fprintf(&b, "q=%s;", q.ID) } if ed.agent.openRequest != nil { fmt.Fprintf(&b, "req:%s", ed.agent.openRequest.ID) @@ -788,6 +878,8 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N openReq := ed.AgentOpenRequest() hasReviewCard := ed.HasAgentPanelCard() dtPending := ed.DataTableReviewPending() + queued := ed.AgentQueuedRequests() + limitReached := ed.AgentWeeklyLimitReached() var items []core.Node if ready := ed.ReadyToReviewTurns(); len(ready) > 0 { @@ -825,7 +917,13 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N }, }) } - if len(turns) == 0 && openReq == nil && !hasReviewCard && !dtPending { + if limitReached { + items = append(items, agentLimitReachedCard(ed, p)) + if len(queued) > 0 { + items = append(items, agentQueuedRequestsView(ed, queued, limitReached, p)) + } + } + if len(turns) == 0 && openReq == nil && !hasReviewCard && !dtPending && len(queued) == 0 && !limitReached { items = append(items, agentEmptyStateCard(ed, p)) } for ti, turn := range turns { @@ -840,6 +938,9 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N if openReq != nil { items = append(items, agentOpenRequestCard(ed, openReq, openReqRef, p)) } + if !limitReached && len(queued) > 0 { + items = append(items, agentQueuedRequestsView(ed, queued, limitReached, p)) + } return core.View{ TestID: "agent-thread-list", Style: core.Style{ @@ -1140,7 +1241,9 @@ func agentTurnView(ed *Editor, turnIdx int, turn AgentTurn, p SpecPalette) core. }) } - if turn.Error != "" { + if turn.ModelError != nil { + children = append(children, agentModelErrorCard(ed, turnIdx, turn.ID, turn.ModelError, p)) + } else if turn.Error != "" { children = append(children, core.View{ TestID: fmt.Sprintf("agent-turn-error-%d", turnIdx), Style: core.Style{ @@ -1343,6 +1446,260 @@ func automationReviewBadgeStyle(ed *Editor, state AgentReviewState, p SpecPalett return ed.T("agent.automationState.ready"), p.Accent.Fg, p.Accent.Fill, p.Accent.Edge } } + +func agentModelErrorCard(ed *Editor, turnIdx int, turnID string, me *AgentModelErrorState, p SpecPalette) core.Node { + actions := []core.Node{ + ui.Button{ + TestID: fmt.Sprintf("agent-turn-retry-%d", turnIdx), + Text: "Retry now", + Label: "Retry now", + Variant: ui.ButtonGhost, + Size: ui.SizeSmall, + Color: func() core.Color { return p.Raised }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 500, + Color: p.TextSecondary, + }, + Style: core.Style{ + Height: core.Pt(30), + Padding: core.Symmetric(0, 12), + CornerRadius: 8, + BorderWidth: 1, + BorderColor: p.LineRaised, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.report(ed.RetryAgentTurn(turnID)) + }, + }, + } + if me.AlternativeAgent != "" && me.AlternativeRoute != "" && me.AlternativeRoute != AgentRouteNone { + switchLabel := "Use " + me.AlternativeAgent + actions = append(actions, ui.Button{ + TestID: fmt.Sprintf("agent-turn-switch-%d", turnIdx), + Text: switchLabel, + Label: switchLabel, + Variant: ui.ButtonGhost, + Size: ui.SizeSmall, + Color: func() core.Color { return p.Removed.Fill }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 500, + Color: p.TextMuted, + }, + Style: core.Style{ + Height: core.Pt(30), + Padding: core.Symmetric(0, 12), + CornerRadius: 8, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.report(ed.SwitchAgentTurnToAlternative(turnID)) + }, + }) + } + return core.View{ + TestID: fmt.Sprintf("agent-turn-model-error-%d", turnIdx), + Role: core.RoleAlert, + Label: me.Headline, + Style: core.Style{ + CornerRadius: 12, + Background: p.Removed.Fill, + BorderWidth: 1, + BorderColor: p.Removed.Edge, + Padding: core.All(12), + Gap: 8, + }, + Children: []core.Node{ + core.Text{ + TestID: fmt.Sprintf("agent-turn-model-error-title-%d", turnIdx), + Content: me.Headline, + Style: core.Style{ + FontSize: 12.5, + FontWeight: 600, + Color: p.Removed.Fg, + }, + }, + core.Text{ + TestID: fmt.Sprintf("agent-turn-model-error-body-%d", turnIdx), + Content: me.Body(), + Style: core.Style{ + FontSize: 12.5, + Color: p.TextSecondary, + }, + }, + core.View{ + Style: core.Style{ + Direction: core.Row, + Wrap: core.Wrap, + Gap: 8, + }, + Children: actions, + }, + }, + } +} + +func agentLimitReachedCard(ed *Editor, p SpecPalette) core.Node { + u := ed.AgentUsage() + limit := ed.WeeklyRequestLimit() + return core.View{ + TestID: "agent-limit-card", + Role: core.RoleRegion, + Label: "Weekly limit reached", + Style: core.Style{ + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Padding: core.All(12), + Gap: 8, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Gauge(), + Style: core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + Color: p.Removed.Fg, + FlexShrink: 0, + }, + }, + core.Text{ + Content: fmt.Sprintf("Limit reached · resets %s", ed.AgentUsageResetLabel()), + Style: core.Style{ + FontSize: 13, + FontWeight: 600, + Color: p.TextPrimary, + }, + }, + }, + }, + core.Text{ + Content: fmt.Sprintf("This week's limit (%d of %d requests) is used. Requests wait in the queue until the reset or until you raise the limit; only you can.", u.WeeklyRequests, limit), + Style: core.Style{ + FontSize: 12.5, + Color: p.TextSecondary, + }, + }, + core.View{ + Style: core.Style{ + Direction: core.Row, + Gap: 8, + }, + Children: []core.Node{ + settingsSpecButton(p, "agent-limit-open-usage", "Usage and privacy", "Open Usage and privacy settings", false, nil, func() { + ed.OpenSettingsPage(SettingsPageUsage) + }), + }, + }, + }, + } +} + +func agentQueuedRequestsView(ed *Editor, queued []AgentQueuedRequest, limitReached bool, p SpecPalette) core.Node { + rows := make([]core.Node, 0, len(queued)+2) + rows = append(rows, core.Text{ + TestID: "agent-queued-heading", + Content: fmt.Sprintf("QUEUED · %d", len(queued)), + Style: core.Style{ + FontSize: 11, + FontWeight: 600, + LetterSpacing: 0.7, + Color: p.TextFaint, + }, + }) + for i, q := range queued { + item := q + idx := i + rowChildren := []core.Node{ + core.View{ + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + MinWidth: core.Pt(0), + Gap: 2, + }, + Children: []core.Node{ + core.Text{ + TestID: fmt.Sprintf("agent-queued-text-%d", idx), + Content: item.Prompt, + Style: core.Style{ + FontSize: 12.5, + Color: p.TextSecondary, + }, + }, + core.Text{ + Content: fmt.Sprintf("queued %s", item.QueuedAt.Format("15:04")), + Style: core.Style{ + FontSize: 11.5, + Color: p.TextFaint, + }, + }, + }, + }, + } + if !limitReached { + rowChildren = append(rowChildren, settingsSpecButton(p, fmt.Sprintf("agent-queued-send-%d", idx), "Send", "Send queued request", true, nil, func() { + ed.report(ed.SendQueuedAgentRequest(item.ID)) + })) + } + rowChildren = append(rowChildren, ui.Button{ + TestID: fmt.Sprintf("agent-queued-remove-%d", idx), + Label: fmt.Sprintf("Remove %q from queue", item.Prompt), + Variant: ui.ButtonGhost, + Size: ui.SizeSmall, + Color: func() core.Color { return p.Raised }, + Style: core.Style{ + Width: core.Pt(28), + Height: core.Pt(28), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.RemoveQueuedAgentRequest(item.ID) + }, + Icon: lucide.X, + }) + rows = append(rows, core.View{ + TestID: fmt.Sprintf("agent-queued-item-%d", idx), + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Edges{Top: 8, Right: 8, Bottom: 8, Left: 12}, + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: rowChildren, + }) + } + rows = append(rows, core.Text{ + Content: "When the limit resets or you raise it, each queued request waits for you to send it.", + Style: core.Style{ + FontSize: 12, + Color: p.TextFaint, + }, + }) + return core.View{ + TestID: "agent-queued-section", + Style: core.Style{ + Gap: 8, + }, + Children: rows, + } +} + func agentStepRow(turnIdx, stepIdx int, step AgentStep, p SpecPalette) core.Node { var badge core.Node textCol := p.TextMuted @@ -1994,6 +2351,9 @@ func ConnectAgentDialogView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64] if cause := ed.AgentFailedCause(); cause != "" { return cause } + if ed.ConnectDialogStep() == ConnectStepAPIKey { + return "The built-in API key could not be verified. Check your key in the system keychain or paste a new key." + } return "The MCP connection stopped answering. Confirm the project configuration and reconnect your agent." }, Style: core.Style{ @@ -2242,6 +2602,39 @@ func ConnectAgentDialogView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64] Color: p.TextFaint, }, }, + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.HasAgentAPIKey(DefaultAgentAPIKeyAccount) + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + TestID: "connect-key-saved-status", + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(7), + Height: core.Pt(7), + CornerRadius: 4, + Background: p.Added.Fg, + }, + }, + core.Text{ + Content: "Key stored in system keychain · leave blank to keep current key", + Style: core.Style{ + FontSize: 12, + Color: p.Added.Fg, + }, + }, + }, + } + }, + }, }, } }, diff --git a/packages/game/editor/editorcmd/agent_builtin_screenshot_test.go b/packages/game/editor/editorcmd/agent_builtin_screenshot_test.go new file mode 100644 index 00000000..b47d854d --- /dev/null +++ b/packages/game/editor/editorcmd/agent_builtin_screenshot_test.go @@ -0,0 +1,155 @@ +package editorcmd_test + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +// TestBuiltInAgentModelsAndUsageMacOSScreenshots renders Settings › Models and connections, +// Settings › Usage and privacy, Connect dialog API key step, Agent panel 529 Model error card, +// and Agent panel Limit reached + Queue on real macOS (`-target macos`) in Dark and Light themes +// for visual inspection beside docs/design/editor/Settings.dc.html, AgentStates.dc.html, and Connect.dc.html. +func TestBuiltInAgentModelsAndUsageMacOSScreenshots(t *testing.T) { + dir := t.TempDir() + sceneDir := filepath.Join(dir, "scenes") + if err := os.MkdirAll(sceneDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(sceneDir, "level_01.scene.yaml"), []byte("version: 1\nname: Level 01\nlayers:\n - name: world\n space: world\n order: 0\n"), 0o644); err != nil { + t.Fatal(err) + } + pf := &project.File{ + Version: project.CurrentVersion, + Name: "Dungeon Run", + ID: "dev.nsgo.dungeonrun", + AppVersion: "0.4.2", + Window: project.Window{Width: 640, Height: 360}, + Autoload: &project.Autoload{ + Scenes: []project.Entry{{Name: "level_01", Path: "scenes/level_01.scene.yaml"}}, + MainScene: "level_01", + }, + } + data, err := project.Encode(pf) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, project.FileName), data, 0o644); err != nil { + t.Fatal(err) + } + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(529) + _ = json.NewEncoder(w).Encode(map[string]any{ + "type": "error", + "error": map[string]string{ + "type": "overloaded_error", + "message": "Overloaded", + }, + }) + })) + defer srv.Close() + + var schedMu sync.Mutex + var scheduled []func() + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + now := time.Date(2026, 11, 26, 14, 12, 0, 0, time.UTC) + ed.Now = func() time.Time { return now } + _ = ed.SetLanguage(editor.LanguageEnglish) + _ = ed.SetAppearance(editor.AppearanceDark) + ed.BuiltInAgentEndpoint = srv.URL + ed.BuiltInHTTPClient = srv.Client() + ed.AgentScheduleAfter = func(_ time.Duration, fn func()) func() { + schedMu.Lock() + scheduled = append(scheduled, fn) + schedMu.Unlock() + return func() {} + } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), nsgotest.Secrets(map[string]string{ + editor.AgentAPIKeySecretAccount: "sk-ant-screenshot-key", + })) + + app.Post(func() { + ed.NotifyAgentMCPConnected(editor.AgentClientInfo{ + ID: "claude-1", + Name: "claude-code", + Transport: "stdio", + }) + ed.RecordAgentReviewOutcome(true, 6) + ed.RecordAgentReviewOutcome(false, 1) + ed.RecordPlaytestRun(380) + }) + app.Settle() + + // 1. Connect dialog › Built in, with your API key + app.Post(func() { ed.OpenConnectDialogForMode(editor.AgentModeAPIKey) }) + app.Settle() + app.Screenshot("connect-apikey-dark") + app.Post(func() { ed.CloseConnectDialog() }) + app.Settle() + + // 2. Agent panel › 529 Model error card (try 2 of 4 · Retrying in 8 s) in Dark & Light + app.Post(func() { + ed.SetRightRailTab(editor.RightTabAgent) + _ = ed.SubmitAgentTaskPrompt(editor.AgentTaskPlaytest, "Analyze floor 3 deaths") + }) + app.WaitUntil(5*time.Second, func() bool { + turns := ed.AgentTurns() + return len(turns) == 1 && turns[0].ModelError != nil && turns[0].ModelError.RetryAttempt == 1 + }) + app.Post(func() { + schedMu.Lock() + var fn func() + if len(scheduled) > 0 { + fn = scheduled[len(scheduled)-1] + } + schedMu.Unlock() + if fn != nil { + fn() + } + }) + app.WaitUntil(5*time.Second, func() bool { + turns := ed.AgentTurns() + return len(turns) == 1 && turns[0].ModelError != nil && turns[0].ModelError.RetryAttempt == 2 + }) + app.Settle() + app.Screenshot("agent-529-error-dark") + app.Post(func() { _ = ed.SetAppearance(editor.AppearanceLight) }) + app.Settle() + app.Screenshot("agent-529-error-light") + app.Post(func() { _ = ed.SetAppearance(editor.AppearanceDark) }) + app.Settle() + + // 3. Agent panel › Limit reached + Queued requests in Dark & Light + app.Post(func() { + ed.StopAgentRun() + _ = ed.SetWeeklyRequestLimit(1) + _ = ed.SubmitAgentPrompt("Make the coins spin slowly") + _ = ed.SubmitAgentPrompt("Add a lever beside the door") + }) + app.Settle() + app.Screenshot("agent-limit-reached-dark") + app.Post(func() { _ = ed.SetAppearance(editor.AppearanceLight) }) + app.Settle() + app.Screenshot("agent-limit-reached-light") +} diff --git a/packages/game/editor/editormcp/builtin_agent_test.go b/packages/game/editor/editormcp/builtin_agent_test.go new file mode 100644 index 00000000..e6e1125c --- /dev/null +++ b/packages/game/editor/editormcp/builtin_agent_test.go @@ -0,0 +1,319 @@ +package editormcp_test + +import ( + "encoding/json" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/editor/editormcp" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +// #1030 Acceptance 1: A fake model endpoint runs a request end to end through the built-in agent +// with the editor's real MCP tools; the API key is read from nsgotest secrets and appears in no file under the project. +func TestBuiltInAgentEndToEndWithNSGoTestSecretsAndMCPTools(t *testing.T) { + const secretKey = "sk-ant-nsgotest-secret-do-not-write-to-disk" + + f := openFixture(t) + settingsPath := filepath.Join(t.TempDir(), "user-config", "editor.yaml") + f.ed.SettingsPath = settingsPath + + var mu sync.Mutex + var gotAPIKeys []string + var sawSceneEditTool bool + var sawDeleteFileTool bool + var sawToolResult bool + var calls int + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload struct { + Model string `json:"model"` + Tools []struct { + Name string `json:"name"` + } `json:"tools"` + Messages []struct { + Role string `json:"role"` + Content json.RawMessage `json:"content"` + } `json:"messages"` + } + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + mu.Lock() + calls++ + callNum := calls + gotAPIKeys = append(gotAPIKeys, r.Header.Get("x-api-key")) + for _, tool := range payload.Tools { + if tool.Name == editormcp.ToolSceneEdit { + sawSceneEditTool = true + } + if tool.Name == editor.ToolNameGameDeleteFile { + sawDeleteFileTool = true + } + } + if callNum == 2 && strings.Contains(string(payload.Messages[len(payload.Messages)-1].Content), "tool_result") { + sawToolResult = true + } + mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + if callNum == 1 { + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": "msg_1", + "model": payload.Model, + "stop_reason": "tool_use", + "content": []map[string]any{ + { + "type": "tool_use", + "id": "toolu_1", + "name": editormcp.ToolSceneEdit, + "input": map[string]any{ + "edits": []map[string]any{ + { + "op": "add", + "layer": "actors", + "object": map[string]any{ + "id": "slime_builtin", + "name": "Built-in Slime", + "x": 180, + "y": 120, + }, + }, + }, + }, + }, + }, + "usage": map[string]int{"input_tokens": 120, "output_tokens": 45}, + }) + return + } + + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": "msg_2", + "model": payload.Model, + "stop_reason": "end_turn", + "content": []map[string]any{ + {"type": "text", "text": "Placed slime_builtin at (180, 120)."}, + }, + "usage": map[string]int{"input_tokens": 180, "output_tokens": 25}, + }) + })) + defer srv.Close() + + f.ed.BuiltInAgentEndpoint = srv.URL + f.ed.BuiltInHTTPClient = srv.Client() + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, f.ed) + }, nsgotest.Size(1440, 900), nsgotest.Secrets(map[string]string{ + editor.AgentAPIKeySecretAccount: secretKey, + })) + + s := editormcp.New(f.ed, editormcp.Options{Run: app.Post}) + t.Cleanup(func() { _ = s.Close() }) + + // Select "Built in, with your API key" in Connect dialog (key is already in nsgotest secrets). + f.ed.OpenConnectDialog() + app.Settle() + app.Press("id:connect-choice-key") + app.Settle() + if !app.Exists("id:connect-key-saved-status") { + t.Fatal("Connect dialog did not detect API key stored in nsgotest secrets") + } + app.Press("id:connect-done") + app.Settle() + + if f.ed.AgentMode() != editor.AgentModeAPIKey { + t.Fatalf("AgentMode = %q, want apikey", f.ed.AgentMode()) + } + if f.ed.AgentStatus() != editor.AgentStatusConnected { + t.Fatalf("AgentStatus = %q, want connected", f.ed.AgentStatus()) + } + + beforeHist := f.ed.History.Index() + + // Submit prompt through the composer -> runs built-in agent -> executes real editormcp scene_edit -> finishes. + if err := f.ed.SubmitAgentPrompt("Add a slime at 180, 120"); err != nil { + t.Fatalf("SubmitAgentPrompt: %v", err) + } + app.WaitUntil(5*time.Second, func() bool { + return !f.ed.AgentWorking() && len(f.ed.AgentTurns()) == 1 && f.ed.AgentTurns()[0].Done + }) + app.Settle() + + mu.Lock() + if len(gotAPIKeys) != 2 || gotAPIKeys[0] != secretKey || gotAPIKeys[1] != secretKey { + t.Fatalf("endpoint x-api-key headers = %d entries (matched=%v)", len(gotAPIKeys), len(gotAPIKeys) == 2 && gotAPIKeys[0] == secretKey) + } + if !sawSceneEditTool || !sawToolResult { + t.Fatalf("sawSceneEditTool=%v sawToolResult=%v", sawSceneEditTool, sawToolResult) + } + if sawDeleteFileTool { + t.Fatal("disabled default-off tool game_delete_file was advertised to built-in agent") + } + mu.Unlock() + + obj, _, _ := f.ed.FindObject("slime_builtin") + if obj == nil || obj.Name != "Built-in Slime" || obj.X != 180 || obj.Y != 120 { + t.Fatalf("slime_builtin not placed by built-in agent: %+v", obj) + } + if f.ed.History.Index() != beforeHist+1 { + t.Fatalf("expected 1 undo step, history index=%d (was %d)", f.ed.History.Index(), beforeHist) + } + + turns := f.ed.AgentTurns() + if len(turns) != 1 || turns[0].Summary != "Placed slime_builtin at (180, 120)." || len(turns[0].Steps) != 1 || turns[0].Steps[0].Status != editor.AgentStepDone { + t.Fatalf("unexpected turn state: %+v", turns) + } + if turns[0].InputTokens != 300 || turns[0].OutputTokens != 70 { + t.Fatalf("usage tokens = %d/%d, want 300/70", turns[0].InputTokens, turns[0].OutputTokens) + } + + // Save scene + project + editor settings, then verify secretKey appears in NO file under the project or user settings. + if err := f.ed.Save(); err != nil { + t.Fatalf("Save: %v", err) + } + if err := f.ed.SaveSettings(); err != nil { + t.Fatalf("SaveSettings: %v", err) + } + + projectDir := filepath.Dir(f.ed.ProjectPath) + if err := filepath.WalkDir(projectDir, func(p string, d fs.DirEntry, walkErr error) error { + if walkErr != nil || d.IsDir() { + return walkErr + } + b, readErr := os.ReadFile(p) + if readErr != nil { + return readErr + } + if strings.Contains(string(b), secretKey) { + t.Errorf("API key found in project file %s", p) + } + return nil + }); err != nil { + t.Fatal(err) + } + if b, err := os.ReadFile(settingsPath); err == nil && strings.Contains(string(b), secretKey) { + t.Errorf("API key found in editor settings file %s", settingsPath) + } + + // Undo removes the built-in agent's edit in one step. + if !f.ed.Undo() { + t.Fatal("Undo failed") + } + if obj, _, _ := f.ed.FindObject("slime_builtin"); obj != nil { + t.Fatalf("Undo did not remove slime_builtin: %+v", obj) + } +} + +// Verifies the built-in agent's MCP tool bridge enforces Settings › Tools toggles and Settings › Usage and privacy switches +// (default-off game_delete_file and GoSource=false). +func TestBuiltInAgentRespectsDisabledToolsAndPrivacy(t *testing.T) { + f := openFixture(t) + projectDir := filepath.Dir(f.ed.ProjectPath) + if err := os.WriteFile(filepath.Join(projectDir, "main.go"), []byte("package main\nconst secretLogic = 42\n"), 0o644); err != nil { + t.Fatal(err) + } + + var mu sync.Mutex + var calls int + var toolResults []string + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload struct { + Model string `json:"model"` + Messages []struct { + Role string `json:"role"` + Content json.RawMessage `json:"content"` + } `json:"messages"` + } + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + mu.Lock() + calls++ + callNum := calls + if callNum == 2 && len(payload.Messages) > 0 { + toolResults = append(toolResults, string(payload.Messages[len(payload.Messages)-1].Content)) + } + mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + if callNum == 1 { + // Model attempts to read main.go (GoSource=false) AND invoke disabled game_delete_file. + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": "msg_priv_1", + "model": payload.Model, + "stop_reason": "tool_use", + "content": []map[string]any{ + { + "type": "tool_use", + "id": "toolu_go", + "name": editormcp.ToolSceneRead, + "input": map[string]any{"file": "main.go"}, + }, + { + "type": "tool_use", + "id": "toolu_del", + "name": editor.ToolNameGameDeleteFile, + "input": map[string]any{"file": "scenes/level.scene.yaml"}, + }, + }, + }) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": "msg_priv_2", + "model": payload.Model, + "stop_reason": "end_turn", + "content": []map[string]any{ + {"type": "text", "text": "Both calls were refused as expected."}, + }, + }) + })) + defer srv.Close() + + f.ed.BuiltInAgentEndpoint = srv.URL + f.ed.BuiltInHTTPClient = srv.Client() + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, f.ed) + }, nsgotest.Size(1280, 800), nsgotest.Secrets(map[string]string{ + editor.AgentAPIKeySecretAccount: "sk-ant-privacy-check", + })) + + s := editormcp.New(f.ed, editormcp.Options{Run: app.Post}) + t.Cleanup(func() { _ = s.Close() }) + + if err := f.ed.SubmitAgentTaskPrompt(editor.AgentTaskPlaytest, "Inspect main.go and delete scene"); err != nil { + t.Fatalf("SubmitAgentTaskPrompt: %v", err) + } + app.WaitUntil(5*time.Second, func() bool { + return !f.ed.AgentWorking() && len(f.ed.AgentTurns()) == 1 && f.ed.AgentTurns()[0].Done + }) + + mu.Lock() + defer mu.Unlock() + if len(toolResults) != 1 { + t.Fatalf("expected 1 tool_result turn, got %d", len(toolResults)) + } + got := toolResults[0] + if strings.Contains(got, "secretLogic") { + t.Fatalf("Go source content leaked to remote model despite GoSource=false: %s", got) + } + if !strings.Contains(got, "Go source code") || !strings.Contains(got, "turned off") { + t.Fatalf("expected privacy and disabled-tool refusals in tool results, got: %s", got) + } +} diff --git a/packages/game/editor/editormcp/server.go b/packages/game/editor/editormcp/server.go index bda20d60..d46cb888 100644 --- a/packages/game/editor/editormcp/server.go +++ b/packages/game/editor/editormcp/server.go @@ -276,12 +276,68 @@ func New(ed *editor.Editor, opts Options) *Server { return err } } + if ed.AgentTools == nil { + ed.AgentTools = &serverToolExecutor{s: s} + } s.syncTools(true) s.wg.Add(1) go s.sendNotices() return s } +type serverToolExecutor struct { + s *Server +} + +func (e *serverToolExecutor) ListTools(_ context.Context) ([]editor.AgentToolSpec, error) { + if e == nil || e.s == nil || e.s.isClosed() { + return nil, errors.New("editormcp: the editor's server is closed") + } + tools := e.s.Tools() + out := make([]editor.AgentToolSpec, 0, len(tools)) + for _, t := range tools { + if !e.s.isToolEnabled(t.Name) { + continue + } + out = append(out, editor.AgentToolSpec{ + Name: t.Name, + Title: t.Title, + Description: t.Description, + InputSchema: slices.Clone(t.InputSchema), + }) + } + return out, nil +} + +func (e *serverToolExecutor) CallTool(ctx context.Context, name string, args json.RawMessage) (editor.AgentToolCallResult, error) { + if e == nil || e.s == nil || e.s.isClosed() { + return editor.AgentToolCallResult{}, errors.New("editormcp: the editor's server is closed") + } + e.s.mu.Lock() + t, ok := e.s.tools[name] + e.s.mu.Unlock() + if !ok { + return editor.AgentToolCallResult{ + Text: fmt.Sprintf("unknown editor MCP tool %q", name), + IsError: true, + }, nil + } + res, err := e.s.call(ctx, t, args, false) + if err != nil { + return editor.AgentToolCallResult{ + Text: err.Error(), + IsError: true, + }, nil + } + if res == nil { + return editor.AgentToolCallResult{}, nil + } + return editor.AgentToolCallResult{ + Text: res.Text, + PNG: slices.Clone(res.PNG), + }, nil +} + // AddTool adds t to the server, which tells connected clients the tool list changed. It refuses a tool without a name or a handler, with an invalid input schema, or with a name already on the server. func (s *Server) AddTool(t Tool) error { if err := s.registerTool(t); err != nil { @@ -774,6 +830,9 @@ func (s *Server) Close() error { s.ed.SetTaskHoldReleaseHook(nil) s.ed.CancelAgentReconnect() s.ed.AgentReconnectProbe = nil + if exec, ok := s.ed.AgentTools.(*serverToolExecutor); ok && exec.s == s { + s.ed.AgentTools = nil + } } return nil } diff --git a/packages/game/editor/locales/en.yaml b/packages/game/editor/locales/en.yaml index 306a086a..a57cc7f8 100644 --- a/packages/game/editor/locales/en.yaml +++ b/packages/game/editor/locales/en.yaml @@ -43,6 +43,7 @@ strings: agent.playDot.hoverFormat: '{summary} · stop Play to open' agent.revert: Revert agent.status.disconnected: Disconnected + agent.status.limitShort: Limit agent.status.reconnectingShort: Reconnecting agent.status.waitingShort: Waiting agent.status.workingShort: Working diff --git a/packages/game/editor/locales/zh.yaml b/packages/game/editor/locales/zh.yaml index a11b9023..7b49f9cf 100644 --- a/packages/game/editor/locales/zh.yaml +++ b/packages/game/editor/locales/zh.yaml @@ -43,6 +43,7 @@ strings: agent.playDot.hoverFormat: '{summary} · 停止播放以打开' agent.revert: 还原 agent.status.disconnected: 已断开 + agent.status.limitShort: 已达上限 agent.status.reconnectingShort: 重连中 agent.status.waitingShort: 等待你 agent.status.workingShort: 处理中 diff --git a/packages/game/editor/settings.go b/packages/game/editor/settings.go index cb0b4303..caad839f 100644 --- a/packages/game/editor/settings.go +++ b/packages/game/editor/settings.go @@ -824,10 +824,14 @@ func (e *Editor) SetAppearance(appearance Appearance) error { } // ApplySettings validates and applies s to the editor without writing to disk. +// Refused when invoked on behalf of an agent because EditorSettings includes You-only agent limits and privacy switches. func (e *Editor) ApplySettings(s EditorSettings) error { if e == nil { return nil } + if e.AgentActorActive() { + return ErrAgentSettingsYouOnly + } if err := ValidateEditorSettings(&s); err != nil { return err } @@ -884,6 +888,7 @@ func (e *Editor) ApplySettings(s EditorSettings) error { e.agent.builtInKeyChecked = false e.settingsMu.Unlock() e.applyViewStateSnap(s.Snap) + e.refreshAgentLimitStatus() e.syncOverlaysFromSettings() if s.AutoSaveEnabled() { e.scheduleAutoSaveIfNeeded() diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index d8e3318a..c707183b 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -8,6 +8,7 @@ import ( "io" "io/fs" "math" + "net/http" "os" "path" "path/filepath" @@ -535,6 +536,14 @@ type Editor struct { AgentRunner AgentRunner // AutomationDrafter optionally turns plain words from "+ New automation, in words" into a candidate AutomationRule; when nil, a built-in English/Chinese drafter is used. AutomationDrafter func(ctx context.Context, words string) (AutomationRule, error) + // AgentTools lists and executes the editor's MCP tools for the built-in agent; editormcp.New wires this automatically. + AgentTools AgentToolExecutor + // AgentSecretStore optionally overrides secret storage for the built-in agent's API key; when nil and Keychain is nil, cx.Secrets() is used whenever a core.Scope is attached (backed by the OS keychain in production and nsgotest.Secrets in tests) so keys never touch project files. + AgentSecretStore AgentSecretStore + // BuiltInAgentEndpoint optionally overrides the HTTP endpoint used by the built-in agent (defaults to DefaultBuiltInAgentEndpoint). Only https:// URLs or loopback http:// URLs are permitted. + BuiltInAgentEndpoint string + // BuiltInHTTPClient optionally overrides the *http.Client used by the built-in agent. + BuiltInHTTPClient *http.Client // AgentReconnectProbe checks whether an MCP agent session is reachable during a reconnect attempt; wired automatically by editormcp.Server and replaceable in tests. AgentReconnectProbe func(ctx context.Context) (AgentClientInfo, error) // AgentScheduleAfter schedules fn to run after d and returns a cancel function; when nil, time.AfterFunc posting onto the editor's UI scope is used. Tests replace this to verify the 1, 2, 4, 8, 16 s reconnect backoff without real sleeps. @@ -1086,6 +1095,9 @@ func (e *Editor) AttachScope(cx *core.Scope) { e.firstRun.setScope(cx) e.remote.setScope(cx) e.agent.setScope(cx) + e.settingsMu.Lock() + e.agent.builtInKeyChecked = false + e.settingsMu.Unlock() e.buildRelease.setScope(cx) e.tasks.setScope(cx) e.setDiskWatcherScope(cx) @@ -1098,6 +1110,7 @@ func (e *Editor) AttachScope(cx *core.Scope) { e.syncAgentPulseLoop() cx.SetAppearance(e.Appearance().CoreAppearance()) } else { + e.stopAgentTimers() e.stopAllTaskRunners() e.stopParticlePreviewLoop() e.stopSceneEmitterLoop()