diff --git a/.github/actions/official-sdk/action.yml b/.github/actions/official-sdk/action.yml new file mode 100644 index 000000000..772351542 --- /dev/null +++ b/.github/actions/official-sdk/action.yml @@ -0,0 +1,17 @@ +name: Pinned official client +description: Install the official Python SDK that contracts/agents-api/upstream.json pins. +runs: + using: composite + steps: + - uses: actions/setup-python@v6 + with: + python-version: '3.12' + - name: Install pinned official client + shell: bash + run: | + python - <<'PY' + import json, subprocess, sys + pin = json.load(open('contracts/agents-api/upstream.json')) + subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', 'services/core/tests/requirements.txt', + 'openai @ git+https://github.com/openai/openai-python@' + pin['commit']], check=True) + PY diff --git a/.github/workflows/api-acceptance.yml b/.github/workflows/api-acceptance.yml index 1db726e16..9510546b2 100644 --- a/.github/workflows/api-acceptance.yml +++ b/.github/workflows/api-acceptance.yml @@ -45,17 +45,7 @@ jobs: OAC_DEV_CORE_BUILD_DIR="$RUNNER_TEMP/oac-core-build" make build-core "$RUNNER_TEMP/oac-core-build/oac-core-device" --help "$RUNNER_TEMP/oac-core-build/oac-core-environment-key" --help - - uses: actions/setup-python@v6 - with: - python-version: '3.12' - - name: Install pinned official client - run: | - python - <<'PY' - import json, subprocess, sys - pin = json.load(open('contracts/agents-api/upstream.json')) - subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', 'services/core/tests/requirements.txt', - 'openai @ git+https://github.com/openai/openai-python@' + pin['commit']], check=True) - PY + - uses: ./.github/actions/official-sdk - name: Verify official-client HTTP compatibility env: OAC_TEST_DATABASE_URL: postgres://oac:oac_test_only@127.0.0.1:${{ job.services.postgres.ports['5432'] }}/oac_ci_tests?sslmode=disable @@ -64,7 +54,6 @@ jobs: run: | python services/core/tests/official_schema_test.py python services/core/tests/official_client.py - go test ./services/core/tests/integration -run '^(TestFunctionStateOfficialClientReadsAndLiveEvents|TestSavedReferenceRetryOfficialClient|TestAgentUpdateOfficialClient|TestAgentDeletionOfficialClient|TestSessionAgentFilterOfficialClient|TestSessionDeletionOfficialClient|TestEnvironmentInitialFailureOfficialClient|TestSelfHostedInitialCreationOfficialClient|TestSelfHostedCancellationOfficialClient)$' -count=1 - uses: ./.github/actions/e2b-provider if: inputs.container - name: Verify the distribution's Core image diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 9ee59a3ab..3e975dac2 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -138,8 +138,12 @@ jobs: - name: Build standalone Core and test services and clients if: matrix.part == 'core' run: make build-core check-core-packages + - uses: ./.github/actions/official-sdk + if: matrix.part == 'integration' - name: Test Core integration shard ${{ matrix.shard }} if: matrix.part == 'integration' + env: + OAC_TEST_OFFICIAL_SDK_PYTHON: python run: make check-core-integration OAC_CORE_INTEGRATION_SHARD=${{ matrix.shard }} distribution: diff --git a/AGENTS.md b/AGENTS.md index 0075923ac..e0d6c29d6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,7 +87,26 @@ OpenAgentCore has had no public release. Replace superseded interfaces, executio - For each new task, create a new Git worktree. Name its directory after that change's commit subject, in kebab-case, beside the checkout. Run `git pull --ff-only` on the base branch, and create the feature branch in that worktree before development. - After every push to a pull request, wait 60 seconds, then run `gh pr checks` and confirm CI passes. Fix any failure before reporting the work as done. - When documents conflict, apply the latest explicit user decision and update the affected current guidance; recorded evidence does not override it. -- Review the complete diff with a fresh independent subagent that receives only the requirements, acceptance criteria, boundaries, repository path and comparison baseline, with no implementation summary, self-assessment or earlier findings. Explain these criteria to the user. Do not use `codex exec` as a substitute reviewer. [CONTRIBUTING.md](CONTRIBUTING.md#review) states the review contract. -- [CONTRIBUTING.md](CONTRIBUTING.md): documentation ownership, repository boundary, workflow, independent review, required checks and naming. +- Review every change through the [independent review gate](#independent-review-gate). +- [CONTRIBUTING.md](CONTRIBUTING.md): documentation ownership, repository boundary, workflow, the review contract, required checks and naming. - [Develop OpenAgentCore](docs/development.md): setup, the repository map, focused checks and [each extension boundary](docs/development.md#choose-an-extension-boundary). - [API namespaces and credentials](docs/api/index.md): each route's caller and credential. + +## Independent review gate + +Apply this gate to every change, including documentation, before declaring the work complete: documents under `docs/` and `contracts/` include protocol and contract sources. + +1. Freeze a review range the reviewer can reproduce, and do not commit or edit while a reviewer is running: normally `main...HEAD` for committed work, or, for uncommitted work, the working tree against its merge base with `main`, with new files marked by `git add -N`. Make sure every in-scope modification is visible in that range. +2. Choose reviewers for an implementation's first round by risk. By default, start one fresh, independent subagent with no inherited conversation context. Start two such reviewers when the change touches a protocol's code or document (a row of the table under [Protocols at every boundary](#protocols-at-every-boundary)), database schema or migrations, authentication, credentials or isolation, or a shared lifecycle, admission, cancellation or reuse flow. Every reviewer inspects that round's complete range. Do not use `codex exec` as a substitute reviewer. +3. Give each reviewer detailed but neutral context: the user's goal, intended behavior, acceptance criteria, task boundaries, relevant constraints, the repository path, repository layout, architectural boundaries, authoritative contracts or documentation, the exact review range, relevant read-only validation commands, and the dimensions to inspect (correctness, regressions, data integrity, concurrency, security, performance, compatibility, UI state, i18n, and tests). Before the review starts, tell the user the requirements, criteria and boundaries given to the reviewer. +4. Do not tell reviewers the implementation approach, what changes or fixes were made, the chosen design rationale, a self-assessment, known concerns, prior review findings, or another reviewer's conclusions. Reviewers must independently infer how the code attempts to meet the stated requirements. +5. Reviewers are read-only. Require prioritized findings with severity (blocker, high, medium or low; data integrity is a category at any severity), confidence, an exact file and line, a concrete failure scenario, reasoning, and a recommended direction. Require an explicit "no findings" result when applicable. Style-only comments are not findings unless they create a maintenance or correctness risk. +6. The primary agent must independently validate every finding against the source and tests. Do not apply reviewer suggestions mechanically. A problem the change causes or worsens is in scope wherever it appears. A validated pre-existing or unrelated problem that cannot be fixed within the task boundaries is recorded and reported to the user instead of fixed, and does not block completion. When an in-scope finding is deliberately left unfixed, such as to keep upstream-compatible behavior, record the decision and its reason and list it in the final report. Later reviewers receive deliberate decisions as intended behavior, and known out-of-boundary problems as task boundaries, among the constraints in step 3. Leaving an in-scope finding unfixed never satisfies step 10: an unfixed validated blocker, high-severity or data-integrity finding still blocks completion. +7. Fix confirmed in-scope issues, confirm each fixed failure scenario with a test or a reproduction, and run proportionate regression tests. After fixing a blocker, high-severity or data-integrity finding, or after any other material fix, review the changes made since the reviewed range with one new blind reviewer, started and briefed as in steps 2 to 5; when uncommitted new changes cannot be separated, review the whole working-tree range again. +8. Track findings by underlying invariant or failure scenario, not wording. Run at most three review rounds for one implementation, and end the gate in one of two ways: + - If the third round's validated in-scope findings are all medium or low and none concerns data integrity, finish without another round: fix the small, localized findings, confirm each with a test or a reproduction, and list the rest in the final report. + - If the third round reports a validated in-scope blocker, high-severity or data-integrity finding, or earlier if review and repair begin cycling, patches contradict earlier patches, or the same invariant repeatedly fails, stop patching and reassess the design: ownership, component boundaries, state model, data flow, contracts, and test strategy. A corrected design that fits within the task boundaries, which come from the user, goes through this gate once as a new implementation. If the design holds, or the task boundaries themselves look wrong, stop and report to the user. +9. If the design-level correction reaches either condition of the second case, stop and report the unresolved condition, review history, conflicting constraints, and viable options. Never start a second correction or broaden the task. +10. Completion requires no validated in-scope blocker, high-severity or data-integrity finding, all relevant checks passing, and a final primary-agent audit of the complete diff. + +The reviewer count is a review-quality gate, not a requirement to split the implementation into multiple pull requests; a protocol change is still reviewed on its own. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6901af58d..dcdef3d8c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing to OpenAgentCore -This guide owns how to work in the repository: documentation ownership, the repository boundary, workflow and review, required checks and naming. Every other subject has one canonical owner, listed below. +This guide owns how to work in the repository: documentation ownership, the repository boundary, workflow and review, required checks and naming. ## Documentation ownership @@ -10,6 +10,7 @@ Every subject has one owner. Most owners are the page whose title names the subj | --- | --- | | Design principles, public API fidelity, settings and data ownership, documentation rules | [AGENTS.md](AGENTS.md) | | Protocol code and documents at each component boundary | [Protocol map](AGENTS.md#protocols-at-every-boundary) | +| Agent review gate | [Independent review gate](AGENTS.md#independent-review-gate) | | Generated files (OpenAPI documents, Harness catalog reference, architecture diagram) | The source and generator named in [Contract and schema rules](#contract-and-schema-rules) and [Branding](#branding); never edit the output by hand | | Core service setup, tests and generation | [Core service guide](services/core/README.md) | | Core implementation constraints beyond the public contracts | [Implementation constraints](services/core/IMPLEMENTATION.md) | @@ -17,35 +18,31 @@ Every subject has one owner. Most owners are the page whose title names the subj | Codex, Claude and MiniMax Runtime adapters and images | [Codex](services/core/deploy/codex/README.md), [Claude](services/core/deploy/claude/README.md), [MiniMax](services/core/deploy/mcode/README.md) | | Claude private SDK bridge | [Claude SDK adapter](packages/claude-sdk-adapter/README.md) | | E2B template construction | [E2B template builder](services/core/deploy/e2b/README.md) | +| OpenSandbox Runtime image and adapter | [OpenSandbox adapter guide](services/core/deploy/opensandbox/README.md) | | E2B and microsandbox Provider helper implementation | [E2B helper](services/core/tools/e2b-provider/README.md), [microsandbox helper](services/core/tools/microsandbox-provider/README.md) | | Distribution builds, Runtime image builds, CI and publication | [Build and release OpenAgentCore](docs/maintainers.md) | | Website: landing page, bilingual documentation maintenance, documentation site build and GitHub Pages publication | [Website guide](website/README.md) | -| Installer lifecycle, locking, generated state, managed HTTPS and downloads | [Deployment](deploy/README.md) and [Node installer](deploy/node/README.md) | +| Installer lifecycle, locking, generated state and downloads | [Deployment](deploy/README.md) and [Node installer](deploy/node/README.md) | | Web page behavior and visual rules | [Web product](apps/web/PRODUCT.md), [Web design](apps/web/DESIGN.md) | -| Application example behavior and local operation | [Application example](example/parsar/README.md) | +| Application example behavior and local operation | [Parsar](example/parsar/README.md), [RL evaluation](example/rl-eval/README.md) | ## Repository boundary -This repository contains the Core API and database, Runtime daemon, Harness and Sandbox Provider adapters, shared protocol packages, Web administrator console and their build and test tools. Product applications stay outside that service boundary. Keep the external Parsar product's `server/`, `apps/parsar/`, CLI, plugins and deployment stack in its own repository; do not automatically sync or delete its Core copy. Go imports resolve through this repository's module. +This repository contains the Core API and database, Runtime daemon, Harness and Sandbox Provider adapters, shared protocol packages, Web administrator console and their build and test tools. Product applications stay outside that service boundary. -### Product and execution service separation - -Core builds, deploys and runs independently of product services, frontends and databases. Applications follow the [public API boundary](AGENTS.md#public-api) and, when they share a PostgreSQL server with Core, use separate databases, credentials and migrations. - -- Parsar owns users, workspaces, business authorization, Agent/Team definitions, capabilities, product conversations, IM/sharing, approval decisions and billing. It uses Core for execution. -- A product conversation may reference several execution Sessions. Core owns native engine session identities; an execution Session has its own lifetime, separate from a daemon connection, process or sandbox. -- Build application orchestration on the public Session and event contract in the [Agents API guide](docs/api/public-agent-api.md). Product cursor replay must be an explicit product extension. Business Team orchestration belongs to the application; Core's pinned `multi_agent` and Subagent resources remain part of the public contract. +Core builds, deploys and runs independently of product services, frontends and databases; applications follow the [public API boundary](AGENTS.md#public-api). ### Optional application example -`example/parsar/` is an optional Agent workbench in this repository. Its [README](example/parsar/README.md) owns its product behavior. +`example/parsar/` is an optional conversation workspace in this repository. Its [README](example/parsar/README.md) owns its product behavior. -- It calls only public `/v1` APIs. Its Project key stays server-side; it never holds a Core key or issues machine credentials. Self-hosted connection displays the public Session installation command unchanged; Core owns bootstrap authorization and machine credential issuance. +- It calls only public `/v1` APIs. Its Project key stays server-side; it never holds a Core key or issues machine credentials. The example uses only Core-managed hosted environments; its environment templates prepare packages, initialization commands, variables and initial files through the public Session contract. - It may keep a small product-owned SQLite database (Node's built-in module, Node 22.13+), outside the checkout and isolated by Core origin and Project key fingerprint. Provider keys never reach the browser. -- Core owns Skills and all execution and history state. The example stores only Session references and pending creation requests with stable idempotency keys. - Product resources use `/app/` and never become Core API or database conventions. - It is excluded from Core distributions and cannot become a service dependency. +`example/rl-eval/` is an optional script that runs batch rollouts for RL and evaluation. Its [README](example/rl-eval/README.md) owns its behavior. It calls only public `/v1` APIs, holds only a Project key, uses only Core-managed hosted environments and writes results only to a local JSONL file. + ## Workflow and review ### Before you start @@ -56,7 +53,6 @@ If requirements are unresolved, object ownership is unclear, or a design would n ### Implementation conventions -- Apply the [simplicity and performance principles](AGENTS.md#simplicity-and-performance) when adding structure or optimizing execution. - Keep one formatter, parser, validator and error mapper per job, and one error mapper per API surface. - Share frontend formatting and labels in `apps/web/src/lib/`. - Use `internal/obs/log` for logs. Keep credentials out of source and logs. Harness profiles must not copy Runtime tool environment values; see the [environment contract](contracts/agents-api/environments.md#explicit-local-tool-environment). @@ -66,7 +62,7 @@ If requirements are unresolved, object ownership is unclear, or a design would n ### Review -Every change gets an independent review of the complete diff against its requirements, acceptance criteria and boundaries. The reviewer receives no implementation summary or earlier findings. Fix substantiated in-scope findings, validate and review again; if the cycle repeats, reassess design and scope instead of adding changes, and report an unresolved blocker instead of broadening the task. +Every change gets an independent review of the complete diff against its requirements, acceptance criteria and boundaries. The reviewer receives no implementation summary or earlier findings. Fix substantiated in-scope findings, validate and review again; if the cycle repeats, reassess design and scope instead of adding changes, and report an unresolved blocker instead of broadening the task. Agents follow the [review gate](AGENTS.md#independent-review-gate) instead, which sets who reviews, what reviewers receive, how many rounds run and when to stop and report. ## Required checks @@ -89,7 +85,7 @@ The role needs `CREATE DATABASE`: tests of database-wide state, such as the exec ### Contract and schema rules -- Each `internal/harnessconfig//declaration.go` is the single authored declaration of one Harness, read by Core admission and the Runtime. `make generate-harness-catalog` generates the Go registrations, client identifiers/names and the reference, and projects the model-provider protocol names of `internal/modelprovider/config.go` to the client; `make openapi` derives the matching enums. `make check-harness-catalog` verifies freshness in the full gate. Native restrictions stay in the declaration; Runtime availability stays separate and discovery only narrows the declaration. +- [Declare the Harness](contracts/agents-api/harness-onboarding.md#declare-the-harness) owns what `make generate-harness-catalog` generates from each declaration and what `make check-harness-catalog` checks. The same generator also projects the model-provider protocol names of `internal/modelprovider/config.go` to the client. - `make openapi` regenerates the public Go types, the Agent request shapes, the route inventory and all three OpenAPI documents; run it after changing the pinned public schema, Go bindings, Core extensions or handler annotations, and commit the generated diffs. `make check-openapi` checks freshness and the generator, and also runs through `make check-go`. - `scripts/generate-public-api.py` reads the checked-in, checksum-verified official source without network access. It selects Agents, Vaults, Files and Skills and follows their schema references, preserving union types, nullability, required fields and constraints. The request shapes in `services/core/internal/api/official_shapes.gen.go` project `CreateAgentParams`, `UpdateAgentParams` and `SessionAgentConfigParam`; Core checks request bodies against them before it reads an Agent configuration. Core's extension types in `contracts/agents-api/v1/` stay authored in Go and are added to the public schema during generation. - The standard fields are generated into `v1/official.gen.go`. `go-bindings.json` lists the types Core consumes and overrides only the Go representation or field order that existing storage or custom JSON encoding requires; shared shapes use one Go type. Selected discriminated unions also generate JSON serializers that keep required nullable fields for each variant. Go input projections exclude `packages.system` to preserve its explicit rejection. Other union serializers, Core's local limits, execution admission and state transitions remain implementation code. @@ -102,7 +98,7 @@ The role needs `CREATE DATABASE`: tests of database-wide state, such as the exec Use official SDKs and upstream types or schemas. Validate raw HTTP payloads and observable workflows alongside SDK behavior. API changes preserve the pinned contracts, [OpenAI compatibility](contracts/agents-api/index.md), official-client tests and Core's independent build. Verify the official-client workflow before application integration. An OpenAI endpoint is a test target only when the required capabilities and credentials are available. -Controlled fixtures and synthetic model responses qualify deterministic behavior. Live acceptance calls a real model API through Core, the daemon and the Harness adapter. Direct native probes establish feasibility only. Keep provider credentials in private test configuration, outside source, logs and task records. +Controlled fixtures and synthetic model responses qualify deterministic behavior. Live acceptance calls a real model API through Core, the daemon and the Harness adapter. Direct native probes establish feasibility only. For wire details the pinned SDK does not specify, probe resources you own and retain the request evidence. In the [OpenAI compatibility](contracts/agents-api/index.md), keep observed behavior distinct from guarantees, accepted profiles distinct from complete coverage, and provider connectivity distinct from deployment qualification. @@ -112,7 +108,7 @@ Native adapter changes require their build/check targets and live provider accep ## OpenAgentCore Runtime names -| Surface | Current name | +| Surface | Name | | --- | --- | | Runtime binary | `oac-daemon` | | Filesystem and initialization helpers | `oac-*` | @@ -125,4 +121,4 @@ Provider bootstrap, Runtime images and Harness adapters must agree on these name ## Branding -Use OpenAgentCore for public project branding. The canonical mark is `docs/assets/openagentcore-logo.svg`; Web uses its outline with cropped transparent margins, theme-aware favicon colors and dark-surface inversion. The README wordmark is `docs/assets/openagentcore-wordmark-light.svg` with a dark variant, and `docs/assets/og-image.png` is the social preview. The architecture diagram that README and the website show, `docs/assets/architecture.svg` and `architecture-dark.svg`, is generated by `scripts/generate-architecture-diagram.py`; change the script and run it again. The `example/parsar/` workbench keeps its own name, logo and favicon. Preserve external repository URLs and data identifiers when changing display copy. +Use OpenAgentCore for public project branding. The canonical mark is `docs/assets/openagentcore-logo.svg`; Web uses its outline with cropped transparent margins, theme-aware favicon colors and dark-surface inversion. The README banner is `docs/assets/openagentcore-banner.webp`, and `docs/assets/og-image.png` is the social preview. The architecture diagram that README and the website show, `docs/assets/architecture.svg` and `architecture-dark.svg`, is generated by `scripts/generate-architecture-diagram.py`; change the script and run it again. The `example/parsar/` example keeps its own name, logo and favicon. diff --git a/Makefile b/Makefile index 3efed26be..bd809e0eb 100644 --- a/Makefile +++ b/Makefile @@ -55,7 +55,7 @@ check-go: check-openapi check-runtime-contract: go test ./internal/agentdaemon/proto/... ./services/core/internal/runtimegateway ./apps/daemon/internal/transport ./apps/daemon/internal/dispatch ./apps/daemon/internal/wireconformance -count=1 go test ./services/core/internal/execution -run '^TestRuntimeProtocol' -count=1 - go test ./apps/daemon/internal/agent/... -run '^(TestSharedTextLifecycle|TestPublicHarnessContractDeclarations|TestRegistryRejectsEveryOmittedCapabilityBeforeReplacement|TestUnsupportedExtensionsHaveNoNativeEffects)$$' -count=1 + go test ./apps/daemon/internal/agent/... -run '^(TestSharedTextLifecycle|TestPublicHarnessContractDeclarations|TestRegistryRejectsEveryOmittedCapabilityBeforeReplacement)$$' -count=1 build-daemon: @set -e; output="$${OAC_DEV_HOME:-$$HOME/.oac}/build/daemon"; \ @@ -142,6 +142,7 @@ check-example: example-deps pnpm --filter @oac/parsar-example test pnpm --filter @oac/parsar-example build pnpm --filter @oac/parsar-example test:e2e + PYTHONDONTWRITEBYTECODE=1 python3 example/rl-eval/rl_eval_test.py check-mcode-harness: node --test packages/mcode-harness/*.test.mjs @@ -202,6 +203,7 @@ check-sandbox-provider-contract: .PHONY: check-docs check-ci check-docs: PYTHONDONTWRITEBYTECODE=1 python3 scripts/core-distribution-manifest.test.py BundledDocsTests + PYTHONDONTWRITEBYTECODE=1 python3 scripts/benchmark.test.py check-ci: PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts -p 'ci_*test.py' diff --git a/README.md b/README.md index 8601923f3..673cd7179 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,6 @@
- - - OpenAgentCore - +![OpenAgentCore — One core. Many agents.](docs/assets/openagentcore-banner.webp) The OpenAI Agents API, open source and self-hosted. Run Codex, Claude Code or MiniMax Code on your own machines with your own models, through the official OpenAI SDK. @@ -15,13 +12,13 @@ The OpenAI Agents API, open source and self-hosted. Run Codex, Claude Code or Mi
+![Deployment overview](docs/assets/console-overview-en.webp) + - **Same API as OpenAI.** Set `OPENAI_BASE_URL` and the [official OpenAI SDK](https://developers.openai.com/api/docs/libraries), or plain HTTP, works unchanged. - **Your agent, your model.** Each Session runs Codex, Claude Code or MiniMax Code natively, as it runs on your machine, with the model provider you configure. See [Harness capabilities](https://openagentcore.dev/contracts/agents-api/harness-capabilities). -- **Compute that sleeps, workspaces that stay.** On microsandbox, which keeps every workspace on independent storage, idle sandboxes release compute and resume on a compatible node with their files intact. E2B pauses idle sandboxes in place. Docker and your own Linux, macOS or Windows machine also run Sessions. See [Sandbox Provider protocol](https://openagentcore.dev/docs/sandbox-provider). +- **Compute that sleeps, workspaces that stay.** On microsandbox, which keeps every workspace on independent storage, idle sandboxes release compute and resume on a compatible node with their files intact. E2B pauses idle sandboxes in place. Your own Linux, macOS or Windows machine also runs Sessions. See [Sandbox Provider protocol](https://openagentcore.dev/docs/sandbox-provider). - **Replaceable parts.** Sandbox Providers, workspace filesystems, Harnesses and model providers plug in through [defined protocols](AGENTS.md#protocols-at-every-boundary). -![Deployment overview](docs/assets/console-overview-en.webp) - ## Quickstart Install Core, Web and PostgreSQL on Linux or macOS with [Docker](https://openagentcore.dev/docs/getting-started/install#prerequisites): @@ -36,7 +33,7 @@ On Windows, in PowerShell: irm https://github.com/MiniMax-AI/OpenAgentCore/releases/latest/download/install.ps1 | iex ``` -In Web, sign in with the Core key the installer prints, configure the public address, set a default model, issue a Project API key and add sandbox capacity (a node or E2B). [Install Core and Web](https://openagentcore.dev/docs/getting-started/install) covers each step. +In Web, sign in with the Core key the installer prints, configure the public address, set a default model, issue a Project API key and add sandbox capacity (a node, E2B or OpenSandbox). [Install Core and Web](https://openagentcore.dev/docs/getting-started/install) covers each step. Then call it with the OpenAI SDK, with `OPENAI_BASE_URL` set to your API base URL (`https://core.example/v1`) and `OPENAI_API_KEY` to the Project API key: diff --git a/README.zh-CN.md b/README.zh-CN.md index a92ff4679..474cf7a50 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,9 +1,6 @@
- - - OpenAgentCore - +![OpenAgentCore — One core. Many agents.](docs/assets/openagentcore-banner.webp) 开源、可自部署的 OpenAI Agents API。用官方 OpenAI SDK,在你自己的机器上用你自己的模型运行 Codex、Claude Code 或 MiniMax Code。 @@ -15,13 +12,13 @@
+![部署概览](docs/assets/console-overview-zh.webp) + - **与 OpenAI 相同的 API。** 设置 `OPENAI_BASE_URL` 后,[官方 OpenAI SDK](https://developers.openai.com/api/docs/libraries)或直接的 HTTP 调用无需改动即可使用。 - **你的 Agent,你的模型。** 每个 Session 原生运行 Codex、Claude Code 或 MiniMax Code,使用你配置的模型提供商,与在本机运行一致。详见 [Harness 能力](https://openagentcore.dev/zh/contracts/agents-api/harness-capabilities)。 -- **计算会休眠,工作区会保留。** 在 microsandbox 上(每个工作区都保存在独立存储中),空闲沙箱释放计算资源,并在兼容节点上带着文件恢复。E2B 会就地暂停空闲沙箱。Docker 以及你自己的 Linux、macOS 或 Windows 机器同样可以运行 Session。详见[沙箱提供商协议](https://openagentcore.dev/zh/docs/sandbox-provider)。 +- **计算会休眠,工作区会保留。** 在 microsandbox 上(每个工作区都保存在独立存储中),空闲沙箱释放计算资源,并在兼容节点上带着文件恢复。E2B 会就地暂停空闲沙箱。你自己的 Linux、macOS 或 Windows 机器同样可以运行 Session。详见[沙箱提供商协议](https://openagentcore.dev/zh/docs/sandbox-provider)。 - **部件可替换。** 沙箱提供商、工作区文件系统、Harness 和模型提供商都通过[既定协议](AGENTS.md#protocols-at-every-boundary)接入。 -![部署概览](docs/assets/console-overview-zh.webp) - ## 快速开始 在 Linux 或 macOS 上,按[前置条件](https://openagentcore.dev/zh/docs/getting-started/install#prerequisites)准备好 Docker 后,安装 Core、Web 和 PostgreSQL: @@ -36,7 +33,7 @@ curl -fsSL https://openagentcore.dev/install.sh | bash irm https://github.com/MiniMax-AI/OpenAgentCore/releases/latest/download/install.ps1 | iex ``` -在 Web 中,用安装程序输出的 Core 密钥登录,配置公共地址,设置默认模型,签发项目 API 密钥,并添加沙箱容量(节点或 E2B)。每一步见[安装 Core 和 Web](https://openagentcore.dev/zh/docs/getting-started/install)。 +在 Web 中,用安装程序输出的 Core 密钥登录,配置公共地址,设置默认模型,签发项目 API 密钥,并添加沙箱容量(节点、E2B 或 OpenSandbox)。每一步见[安装 Core 和 Web](https://openagentcore.dev/zh/docs/getting-started/install)。 然后用 OpenAI SDK 调用,将 `OPENAI_BASE_URL` 设为你的 API 基础地址(`https://core.example/v1`),`OPENAI_API_KEY` 设为项目 API 密钥: diff --git a/apps/daemon/internal/agent/claudesdk/cancellation.go b/apps/daemon/internal/agent/claudesdk/cancellation.go index e3070a246..2162ba7ea 100644 --- a/apps/daemon/internal/agent/claudesdk/cancellation.go +++ b/apps/daemon/internal/agent/claudesdk/cancellation.go @@ -3,6 +3,7 @@ package claudesdk import ( "context" "errors" + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" diff --git a/apps/daemon/internal/agent/claudesdk/cancellation_test.go b/apps/daemon/internal/agent/claudesdk/cancellation_test.go index 8d1bf3503..8f3392b86 100644 --- a/apps/daemon/internal/agent/claudesdk/cancellation_test.go +++ b/apps/daemon/internal/agent/claudesdk/cancellation_test.go @@ -47,7 +47,7 @@ func TestCancellationWaitsForDrainAndPublishesOutcome(t *testing.T) { if err := running.(*session).SteerWithReceipt(ctx, proto.PromptSteerPayload{InputID: "later", Input: proto.TextInput("later")}, func() {}); !errors.Is(err, agent.ErrSteeringInactive) { t.Fatal("cancelled execution accepted steering", err) } - if err := os.WriteFile(filepath.Join(config.StateDir, "release"), nil, 0o600); err != nil { + if err := os.WriteFile(filepath.Join(testState(config), "release"), nil, 0o600); err != nil { t.Fatal(err) } if err := running.Cancel(ctx); err != nil { @@ -133,7 +133,7 @@ func TestCancellationDrainsIntoReadyConsumer(t *testing.T) { if event := <-out; event.Type != proto.TypeDelta { t.Fatal("missing native readiness barrier") } - if err := os.WriteFile(filepath.Join(config.StateDir, "release"), nil, 0o600); err != nil { + if err := os.WriteFile(filepath.Join(testState(config), "release"), nil, 0o600); err != nil { t.Fatal(err) } if err := running.Cancel(ctx); err != nil { @@ -159,11 +159,11 @@ func TestCancellationDrainsIntoReadyConsumer(t *testing.T) { } func cancellationConfig(root, mode string) Config { - return Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=cancellation-" + mode, "GORACE=atexit_sleep_ms=0"}} + return Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=cancellation-" + mode, "GORACE=atexit_sleep_ms=0"}} } func cancellationRequest() proto.PromptRequestPayload { - return proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", AgentOptions: map[string]any{"model": "fake-model", "system_prompt": "instructions"}} + return proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", Turn: proto.TurnSettings{Model: "fake-model"}, AgentOptions: map[string]any{"system_prompt": "instructions"}} } func runCancellationHelper(request startRequest, mode string, scanner *bufio.Scanner, emit func(bridgeEvent)) { diff --git a/apps/daemon/internal/agent/claudesdk/commands_session_test.go b/apps/daemon/internal/agent/claudesdk/commands_session_test.go index b19a7584e..efe9fb2ba 100644 --- a/apps/daemon/internal/agent/claudesdk/commands_session_test.go +++ b/apps/daemon/internal/agent/claudesdk/commands_session_test.go @@ -21,7 +21,7 @@ func TestWorkspaceCommandsRequirePackagedFeature(t *testing.T) { if _, err := NewExecutorFactory(config)(t.Context(), preparationRequest()); err == nil || !strings.Contains(err.Error(), "workspace preparation is unavailable") { t.Fatal("old bridge accepted command observations", err) } - if _, err := os.Stat(filepath.Join(config.StateDir, "launched")); !os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(testState(config), "launched")); !os.IsNotExist(err) { t.Fatal("old bridge started execution before rejection") } } @@ -33,11 +33,11 @@ func TestWorkspaceCommandFramesKeepStartIdentityAndObservedOutput(t *testing.T) t.Fatal(err) } defer resource.Close(context.Background()) - if _, err := os.Stat(filepath.Join(config.StateDir, "start.json")); !os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(testState(config), "start.json")); !os.IsNotExist(err) { t.Fatal("preparation submitted a command") } out := make(chan proto.Envelope, 16) - s, err := resource.StartTurn(t.Context(), "actual-command-run", proto.TextInput("hello"), out) + s, err := resource.StartTurn(t.Context(), "actual-command-run", proto.TurnSettings{}, proto.TextInput("hello"), out) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/claudesdk/declaration.go b/apps/daemon/internal/agent/claudesdk/declaration.go index c6d497577..ec60ad383 100644 --- a/apps/daemon/internal/agent/claudesdk/declaration.go +++ b/apps/daemon/internal/agent/claudesdk/declaration.go @@ -9,7 +9,6 @@ import ( "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/localworkspace" - "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/paths" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" declaration "github.com/MiniMax-AI/OpenAgentCore/internal/harnessconfig/claudesdk" ) @@ -38,9 +37,6 @@ func discoverWithCheck(parent context.Context, options agent.DiscoveryOptions, d if !filepath.IsAbs(entrypoint) { return fail(fmt.Errorf("%s must be absolute", claudeSDKEntrypointEnv)) } - if err := paths.ValidateProfile(options.Profile); err != nil { - return fail(err) - } if !filepath.IsAbs(options.RuntimeRoot) || filepath.Clean(options.RuntimeRoot) != options.RuntimeRoot { return fail(fmt.Errorf("Claude SDK requires an explicit Runtime root")) } @@ -59,13 +55,13 @@ func discoverWithCheck(parent context.Context, options agent.DiscoveryOptions, d if !filepath.IsAbs(options.StateRoot) || filepath.Clean(options.StateRoot) != options.StateRoot { return fail(fmt.Errorf("Claude SDK requires an explicit state root")) } - config = Config{Node: node, Entrypoint: entrypoint, StateDir: filepath.Join(options.StateRoot, "daemon", options.Profile, "runtime", "claude-sdk")} + config = Config{Node: node, Entrypoint: entrypoint, StateRoot: options.StateRoot, RuntimeRoot: options.RuntimeRoot} if binding := localworkspace.Current(); binding != nil { config.Node, err = filepath.EvalSymlinks(node) if err != nil { return fail(err) } - config, err = ConfigureLocal(config, options.StateRoot, options.RuntimeRoot, binding.Workspace()) + config, err = ConfigureLocal(config, binding.Workspace()) if err != nil { return fail(err) } @@ -74,7 +70,7 @@ func discoverWithCheck(parent context.Context, options agent.DiscoveryOptions, d if err != nil { return fail(err) } - local := config.Workspace != nil + local := config.Workspace != "" if local && !info.SupportsLocalRuntime() { return fail(fmt.Errorf("Claude SDK bundle does not support the local Runtime contract")) } diff --git a/apps/daemon/internal/agent/claudesdk/declaration_test.go b/apps/daemon/internal/agent/claudesdk/declaration_test.go index 1e6510eaa..716bc6efb 100644 --- a/apps/daemon/internal/agent/claudesdk/declaration_test.go +++ b/apps/daemon/internal/agent/claudesdk/declaration_test.go @@ -26,7 +26,7 @@ func TestClaudeSDKInvalidPathsFailBeforeProbe(t *testing.T) { } else { root = "relative-home" } - out := discoverWithCheck(t.Context(), agent.DiscoveryOptions{RuntimeRoot: root, StateRoot: t.TempDir(), Profile: "default", Stdout: &strings.Builder{}, Stderr: &strings.Builder{}}, Declaration.Info(), func(context.Context, Config) (RuntimeInfo, error) { + out := discoverWithCheck(t.Context(), agent.DiscoveryOptions{RuntimeRoot: root, StateRoot: t.TempDir(), Stdout: &strings.Builder{}, Stderr: &strings.Builder{}}, Declaration.Info(), func(context.Context, Config) (RuntimeInfo, error) { t.Fatal("invalid paths reached runtime probe") return RuntimeInfo{}, nil }) @@ -47,7 +47,7 @@ func TestClaudeSDKFeatureDiscovery(t *testing.T) { } t.Setenv(claudeSDKNodeEnv, node) for _, features := range [][]string{nil, {"mcp_http_tools"}, {"mcp_http_bearer_auth"}, {"mcp_http_tools", "mcp_http_bearer_auth"}, {"mcp_http_required"}, {"mcp_http_tools", "mcp_http_required"}, {"subagent_resources"}, {"structured_output"}} { - out := discoverWithCheck(t.Context(), agent.DiscoveryOptions{RuntimeRoot: root, StateRoot: t.TempDir(), Profile: "default", Stdout: &strings.Builder{}, Stderr: &strings.Builder{}}, Declaration.Info(), func(context.Context, Config) (RuntimeInfo, error) { + out := discoverWithCheck(t.Context(), agent.DiscoveryOptions{RuntimeRoot: root, StateRoot: t.TempDir(), Stdout: &strings.Builder{}, Stderr: &strings.Builder{}}, Declaration.Info(), func(context.Context, Config) (RuntimeInfo, error) { info := RuntimeInfo{SDK: declaration.Declaration.Native.Version, Native: "native", Features: features} return info, nil }) @@ -75,7 +75,7 @@ func TestDiscoveryOnlyNarrowsDeclaration(t *testing.T) { } t.Setenv(claudeSDKNodeEnv, node) features := []string{"message_images", "function_result_images", "tool_search", "structured_output", "subagent_resources", "mcp_http_tools", "mcp_http_bearer_auth", "mcp_http_required"} - out := discoverWithCheck(t.Context(), agent.DiscoveryOptions{RuntimeRoot: root, StateRoot: t.TempDir(), Profile: "default", Stdout: io.Discard, Stderr: io.Discard}, Declaration.Info(), func(context.Context, Config) (RuntimeInfo, error) { + out := discoverWithCheck(t.Context(), agent.DiscoveryOptions{RuntimeRoot: root, StateRoot: t.TempDir(), Stdout: io.Discard, Stderr: io.Discard}, Declaration.Info(), func(context.Context, Config) (RuntimeInfo, error) { return RuntimeInfo{SDK: declaration.Declaration.Native.Version, Native: "native", Features: features}, nil }) if out == nil || !out.Info.Available { @@ -93,7 +93,7 @@ func TestRuntimeDiscoveryConfigurationAndRegistration(t *testing.T) { } t.Setenv(claudeSDKNodeEnv, node) entrypoint := filepath.Join(root, "bundle", "main.js") - options := agent.DiscoveryOptions{RuntimeRoot: root, StateRoot: t.TempDir(), Profile: "test", Stdout: io.Discard, Stderr: io.Discard} + options := agent.DiscoveryOptions{RuntimeRoot: root, StateRoot: t.TempDir(), Stdout: io.Discard, Stderr: io.Discard} for _, configured := range []bool{false, true} { for _, ready := range []bool{false, true} { t.Setenv(claudeSDKEntrypointEnv, "") @@ -103,7 +103,7 @@ func TestRuntimeDiscoveryConfigurationAndRegistration(t *testing.T) { calls := 0 runtime := discoverWithCheck(t.Context(), options, Declaration.Info(), func(_ context.Context, c Config) (RuntimeInfo, error) { calls++ - if c.Node != node || c.Entrypoint != entrypoint || c.StateDir != filepath.Join(options.StateRoot, "daemon", "test", "runtime", "claude-sdk") || c.Env != nil { + if c.Node != node || c.Entrypoint != entrypoint || c.StateRoot != options.StateRoot || c.RuntimeRoot != options.RuntimeRoot || c.Env != nil { t.Fatalf("configuration: %+v", c) } if !ready { diff --git a/apps/daemon/internal/agent/claudesdk/error_classification_test.go b/apps/daemon/internal/agent/claudesdk/error_classification_test.go index 6ebc1eab2..f34bfc1d7 100644 --- a/apps/daemon/internal/agent/claudesdk/error_classification_test.go +++ b/apps/daemon/internal/agent/claudesdk/error_classification_test.go @@ -20,8 +20,8 @@ func TestClassifiedBridgeFailurePreservesTerminalEvidence(t *testing.T) { t.Run(mode, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=classified-" + mode, "GORACE=atexit_sleep_ms=0"}} - req := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", AgentOptions: map[string]any{"model": "fake-model", "system_prompt": "instructions"}} + config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=classified-" + mode, "GORACE=atexit_sleep_ms=0"}} + req := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", Turn: proto.TurnSettings{Model: "fake-model"}, AgentOptions: map[string]any{"system_prompt": "instructions"}} ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() out := make(chan proto.Envelope, 16) diff --git a/apps/daemon/internal/agent/claudesdk/execution_controls_test.go b/apps/daemon/internal/agent/claudesdk/execution_controls_test.go index ffd8c8230..09bd55db3 100644 --- a/apps/daemon/internal/agent/claudesdk/execution_controls_test.go +++ b/apps/daemon/internal/agent/claudesdk/execution_controls_test.go @@ -16,8 +16,8 @@ import ( func TestExecutionControlsPreserveNativeDefaultsAndInstructions(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state")} - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("Original input."), AgentSessionID: "native-session", AgentOptions: map[string]any{"model": "native-model", "system_prompt": "Keep these exact instructions.\nDo not replace them."}} + config := Config{Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state")} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("Original input."), AgentSessionID: "native-session", Turn: proto.TurnSettings{Model: "native-model"}, AgentOptions: map[string]any{"system_prompt": "Keep these exact instructions.\nDo not replace them."}} ordinary, _, err := prepareConfiguration(config, request) if err != nil { t.Fatal(err) @@ -48,8 +48,8 @@ func TestLiveWebSearchReachesTheBridgeOnEveryPlacement(t *testing.T) { live := &proto.ExecutionControls{WebSearch: &proto.WebSearchControl{Mode: "live", ContextSize: "medium"}, TextVerbosity: "medium"} root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - none, _, err := prepareConfiguration(Config{Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state")}, proto.PromptRequestPayload{ - RunID: "run", Input: proto.TextInput("Search."), ExecutionControls: live, AgentOptions: map[string]any{"model": "native-model"}}) + none, _, err := prepareConfiguration(Config{Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state")}, proto.PromptRequestPayload{AgentStateKey: testStateKey, + RunID: "run", Input: proto.TextInput("Search."), ExecutionControls: live, Turn: proto.TurnSettings{Model: "native-model"}, AgentOptions: map[string]any{}}) if err != nil || none.WebSearch != "live" { t.Fatal("live search on environment none did not reach the bridge", err) } @@ -63,28 +63,26 @@ func TestLiveWebSearchReachesTheBridgeOnEveryPlacement(t *testing.T) { func TestExecutionControlsRejectUnsupportedProfilesBeforeLaunch(t *testing.T) { enabled := true - cases := map[string]proto.ExecutionControls{ - "cached-search": {WebSearch: &proto.WebSearchControl{Mode: "cached", ContextSize: "medium"}}, - "enabled-ptc": {ProgrammaticToolCalling: &enabled}, - "low-verbosity": {TextVerbosity: "low"}, - "high-verbosity": {TextVerbosity: "high"}, - "unknown-verbosity": {TextVerbosity: "invalid"}, - "no-effort": {ReasoningEffort: "none"}, - "minimal-effort": {ReasoningEffort: "minimal"}, - "summary": {ReasoningSummary: "concise"}, - "service-tier": {ServiceTier: "priority"}, - } - for name, controls := range cases { + model := proto.TurnSettings{Model: "native-model"} + cases := map[string]proto.PromptRequestPayload{ + "cached-search": {Turn: model, ExecutionControls: &proto.ExecutionControls{WebSearch: &proto.WebSearchControl{Mode: "cached", ContextSize: "medium"}}}, + "enabled-ptc": {Turn: model, ExecutionControls: &proto.ExecutionControls{ProgrammaticToolCalling: &enabled}}, + "low-verbosity": {Turn: model, ExecutionControls: &proto.ExecutionControls{TextVerbosity: "low"}}, + "high-verbosity": {Turn: model, ExecutionControls: &proto.ExecutionControls{TextVerbosity: "high"}}, + "unknown-verbosity": {Turn: model, ExecutionControls: &proto.ExecutionControls{TextVerbosity: "invalid"}}, + "summary": {Turn: model, ExecutionControls: &proto.ExecutionControls{ReasoningSummary: "concise"}}, + } + for name, request := range cases { t.Run(name, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: "must-not-run", Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state")} - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("Original input."), ExecutionControls: &controls, AgentOptions: map[string]any{"model": "native-model"}} + config := Config{Node: "must-not-run", Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state")} + request.RunID, request.Input, request.AgentStateKey = "run", proto.TextInput("Original input."), testStateKey _, err := startSingleTurn(t.Context(), config, request, make(chan proto.Envelope, 1)) if err == nil || !strings.Contains(err.Error(), "not supported by this Harness") { t.Fatal("unsupported controls did not fail at admission", err) } - if _, err := os.Stat(config.StateDir); !os.IsNotExist(err) { + if _, err := os.Stat(testState(config)); !os.IsNotExist(err) { t.Fatal("unsupported controls reached native setup", err) } }) @@ -94,9 +92,9 @@ func TestExecutionControlsRejectUnsupportedProfilesBeforeLaunch(t *testing.T) { func TestReasoningEffortReachesNativeOptions(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state")} + config := Config{Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state")} for _, effort := range []string{"low", "medium", "high", "xhigh", "max"} { - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), ExecutionControls: &proto.ExecutionControls{TextVerbosity: "medium", ReasoningEffort: effort}, AgentOptions: map[string]any{"model": "native-model", "harness_config": map[string]any{"thinking": map[string]any{"type": "adaptive"}}}} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), ExecutionControls: &proto.ExecutionControls{TextVerbosity: "medium"}, Turn: proto.TurnSettings{Model: "native-model", ReasoningEffort: effort}, AgentOptions: map[string]any{"harness_config": map[string]any{"thinking": map[string]any{"type": "adaptive"}}}} start, _, err := prepareConfiguration(config, request) if err != nil { t.Fatal(effort, err) @@ -110,14 +108,14 @@ func TestReasoningEffortReachesNativeOptions(t *testing.T) { func TestMCPWithoutEnvironmentNoneRejectedBeforeSetup(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: "must-not-run", Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state")} + config := Config{Node: "must-not-run", Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state")} servers := []proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "remote", ServerURL: "https://example.test/mcp"}} - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("Input"), MCPHTTPServers: &servers} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("Input"), MCPHTTPServers: &servers} _, err := startSingleTurn(t.Context(), config, request, make(chan proto.Envelope, 1)) if err == nil || !strings.Contains(err.Error(), "service-origin MCP requires a service execution host") { t.Fatal("MCP reached an unsupported environment", err) } - if _, err := os.Stat(config.StateDir); !os.IsNotExist(err) { + if _, err := os.Stat(testState(config)); !os.IsNotExist(err) { t.Fatal("MCP reached native setup", err) } } @@ -125,9 +123,9 @@ func TestMCPWithoutEnvironmentNoneRejectedBeforeSetup(t *testing.T) { func TestStructuredOutputConfigurationReachesNativeUnchanged(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state")} + config := Config{Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state")} schema := json.RawMessage(`{"type":"object","properties":{"n":{"const":9007199254740992}}}`) - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("Original input."), DisableSubagents: true, AgentOptions: map[string]any{"model": "model", "system_prompt": "Original instructions."}, ExecutionControls: &proto.ExecutionControls{TextVerbosity: "medium", OutputFormat: &proto.OutputFormat{Type: "json_schema", Schema: schema}}} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("Original input."), DisableSubagents: true, Turn: proto.TurnSettings{Model: "model"}, AgentOptions: map[string]any{"system_prompt": "Original instructions."}, ExecutionControls: &proto.ExecutionControls{TextVerbosity: "medium", OutputFormat: &proto.OutputFormat{Type: "json_schema", Schema: schema}}} start, _, err := prepareConfiguration(config, request) if err != nil { t.Fatal(err) @@ -150,8 +148,8 @@ func TestStructuredOutputConfigurationReachesNativeUnchanged(t *testing.T) { func TestToolDiscoveryPreservesFrozenFunctionsBesideOtherProfiles(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state")} - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("Original input."), DisableSubagents: true, ToolSearch: true, AgentOptions: map[string]any{"model": "model"}, FunctionTools: []proto.FunctionTool{ + config := Config{Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state")} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("Original input."), DisableSubagents: true, ToolSearch: true, Turn: proto.TurnSettings{Model: "model"}, AgentOptions: map[string]any{}, FunctionTools: []proto.FunctionTool{ {Name: "lookup", Description: "Lookup", Parameters: json.RawMessage(`{"type":"object","properties":{"ticket":{"const":"original"}}}`), DeferLoading: true}, {Name: "clock", Description: "Clock", Parameters: json.RawMessage(`{"type":"object"}`)}, }} @@ -173,8 +171,8 @@ func TestToolDiscoveryPreservesFrozenFunctionsBesideOtherProfiles(t *testing.T) func TestReasoningSummaryReachesTheBridgeOnlyWhenRequested(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state")} - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("Input."), AgentOptions: map[string]any{"model": "native-model"}} + config := Config{Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state")} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("Input."), Turn: proto.TurnSettings{Model: "native-model"}, AgentOptions: map[string]any{}} for _, summary := range []string{"", "auto"} { request.ExecutionControls = &proto.ExecutionControls{TextVerbosity: "medium", ReasoningSummary: summary} start, _, err := prepareConfiguration(config, request) diff --git a/apps/daemon/internal/agent/claudesdk/executor.go b/apps/daemon/internal/agent/claudesdk/executor.go index 4fc143057..9d9526a04 100644 --- a/apps/daemon/internal/agent/claudesdk/executor.go +++ b/apps/daemon/internal/agent/claudesdk/executor.go @@ -28,10 +28,6 @@ type executor struct { func NewExecutorFactory(config Config) agent.ExecutorFactory { config.Env = slices.Clone(config.Env) - if config.Workspace != nil { - workspace := *config.Workspace - config.Workspace = &workspace - } checked := &runtimeCheckCache{} return func(ctx context.Context, req proto.PromptRequestPayload) (agent.Executor, error) { if ctx == nil { @@ -135,7 +131,7 @@ func (e *executor) read() { break } if !ready { - if event.Type != "executor_ready" || event.Protocol != 3 || event.TurnID != "" { + if event.Type != "executor_ready" || event.Protocol != 4 || event.TurnID != "" { if event.Type == "error" { readyFailure = bridgeFailure(event.Code) } @@ -179,7 +175,7 @@ func (e *executor) read() { close(e.done) } -func (e *executor) StartTurn(ctx context.Context, run string, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { +func (e *executor) StartTurn(ctx context.Context, run string, turn proto.TurnSettings, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { if ctx == nil { ctx = context.Background() } @@ -199,7 +195,11 @@ func (e *executor) StartTurn(ctx context.Context, run string, input proto.Messag go s.runTurn(start, out) // Once the write is attempted, a lost receipt has an unknown input outcome. stopWrite := context.AfterFunc(ctx, s.invalidate) - err := e.write(turnStartFrame{"turn_start", run, input}) + settings := turnSettings{Model: turn.Model, Review: turn.Review} + if turn.ReasoningEffort != "" { + settings.Effort = &turn.ReasoningEffort + } + err := e.write(turnStartFrame{"turn_start", run, input, settings}) stopWrite() if err != nil { s.invalidate() diff --git a/apps/daemon/internal/agent/claudesdk/executor_fixture_test.go b/apps/daemon/internal/agent/claudesdk/executor_fixture_test.go index e6ad19996..48723ebd4 100644 --- a/apps/daemon/internal/agent/claudesdk/executor_fixture_test.go +++ b/apps/daemon/internal/agent/claudesdk/executor_fixture_test.go @@ -21,7 +21,7 @@ func startSingleTurn(ctx context.Context, config Config, req proto.PromptRequest if err != nil { return nil, err } - turn, err := resource.StartTurn(ctx, run, input, out) + turn, err := resource.StartTurn(ctx, run, proto.TurnSettings{}, input, out) if turn == nil { _ = resource.Close(context.Background()) return nil, err @@ -31,7 +31,7 @@ func startSingleTurn(ctx context.Context, config Config, req proto.PromptRequest } func helperTurn(scanner *bufio.Scanner, request *startRequest) (func(bridgeEvent), func()) { - _ = json.NewEncoder(os.Stdout).Encode(bridgeEvent{Type: "executor_ready", Protocol: 3}) + _ = json.NewEncoder(os.Stdout).Encode(bridgeEvent{Type: "executor_ready", Protocol: 4}) if !scanner.Scan() { os.Exit(4) } diff --git a/apps/daemon/internal/agent/claudesdk/executor_test.go b/apps/daemon/internal/agent/claudesdk/executor_test.go index 964f2be19..128591741 100644 --- a/apps/daemon/internal/agent/claudesdk/executor_test.go +++ b/apps/daemon/internal/agent/claudesdk/executor_test.go @@ -26,7 +26,7 @@ func persistentConfig(t *testing.T, mode string) (Config, proto.PromptRequestPay if err := os.WriteFile(entry, []byte("version-one"), 0600); err != nil { t.Fatal(err) } - return Config{Node: os.Args[0], Entrypoint: entry, StateDir: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_EXECUTOR_HELPER=1", "SDK_EXECUTOR_DIR=" + root, "SDK_EXECUTOR_MODE=" + mode, "GORACE=atexit_sleep_ms=0"}}, proto.PromptRequestPayload{DisableExecutionEnvironment: true, AgentOptions: map[string]any{"model": "fixture"}} + return Config{Node: os.Args[0], Entrypoint: entry, StateRoot: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_EXECUTOR_HELPER=1", "SDK_EXECUTOR_DIR=" + root, "SDK_EXECUTOR_MODE=" + mode, "GORACE=atexit_sleep_ms=0"}}, proto.PromptRequestPayload{AgentStateKey: testStateKey, DisableExecutionEnvironment: true, Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{}} } func runPersistentExecutorHelper() { @@ -51,7 +51,7 @@ func runPersistentExecutorHelper() { } _ = os.WriteFile(filepath.Join(root, "prepared"), []byte(strconv.Itoa(os.Getpid())), 0600) encode := func(event bridgeEvent) { _ = json.NewEncoder(os.Stdout).Encode(event) } - encode(bridgeEvent{Type: "executor_ready", Protocol: 3}) + encode(bridgeEvent{Type: "executor_ready", Protocol: 4}) if os.Getenv("SDK_EXECUTOR_MODE") == "block" { time.Sleep(time.Hour) return @@ -135,7 +135,7 @@ func runPersistentExecutorHelper() { func consumeExecutorTurn(t *testing.T, owner agent.Executor, id, input string) (agent.Turn, <-chan proto.Envelope) { t.Helper() out := make(chan proto.Envelope, 16) - turn, err := owner.StartTurn(t.Context(), id, proto.TextInput(input), out) + turn, err := owner.StartTurn(t.Context(), id, proto.TurnSettings{}, proto.TextInput(input), out) if err != nil || turn == nil { t.Fatalf("StartTurn: %v", err) } @@ -215,7 +215,7 @@ func TestExecutorLateTurnEventInvalidatesWithoutRetargeting(t *testing.T) { t.Fatal("unknown native outcome marked settled") } next := make(chan proto.Envelope, 1) - if turn, err := owner.StartTurn(t.Context(), "third", proto.TextInput("hello"), next); turn != nil || err == nil { + if turn, err := owner.StartTurn(t.Context(), "third", proto.TurnSettings{}, proto.TextInput("hello"), next); turn != nil || err == nil { t.Fatal("invalid executor accepted input") } } @@ -262,7 +262,7 @@ func TestExecutorSeparatesPreInputRejectionFromUnknownWrite(t *testing.T) { rejected := make(chan proto.Envelope, 1) cancelled, stop := context.WithCancel(t.Context()) stop() - if turn, err := owner.StartTurn(cancelled, "not-written", proto.TextInput("hello"), rejected); turn != nil || err == nil { + if turn, err := owner.StartTurn(cancelled, "not-written", proto.TurnSettings{}, proto.TextInput("hello"), rejected); turn != nil || err == nil { t.Fatal("cancelled admission reached native input") } select { @@ -275,7 +275,7 @@ func TestExecutorSeparatesPreInputRejectionFromUnknownWrite(t *testing.T) { t.Fatal(err) } out := make(chan proto.Envelope, 8) - turn, err := owner.StartTurn(t.Context(), "unknown-write", proto.TextInput("hello"), out) + turn, err := owner.StartTurn(t.Context(), "unknown-write", proto.TurnSettings{}, proto.TextInput("hello"), out) if turn == nil || err == nil { t.Fatalf("attempted write must preserve unknown Turn ownership: %T %v", turn, err) } diff --git a/apps/daemon/internal/agent/claudesdk/executor_turn.go b/apps/daemon/internal/agent/claudesdk/executor_turn.go index 418de6b14..c0505daa1 100644 --- a/apps/daemon/internal/agent/claudesdk/executor_turn.go +++ b/apps/daemon/internal/agent/claudesdk/executor_turn.go @@ -3,10 +3,11 @@ package claudesdk import ( "encoding/json" "fmt" - "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" - "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" "strings" "time" + + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" + "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" ) func (s *session) runTurn(start startRequest, out chan<- proto.Envelope) { diff --git a/apps/daemon/internal/agent/claudesdk/functions_test.go b/apps/daemon/internal/agent/claudesdk/functions_test.go index 5f99ec7bb..15f203ea5 100644 --- a/apps/daemon/internal/agent/claudesdk/functions_test.go +++ b/apps/daemon/internal/agent/claudesdk/functions_test.go @@ -21,8 +21,8 @@ func TestFunctionFactoryNativeReceipts(t *testing.T) { t.Run(mode, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=" + mode, "GORACE=atexit_sleep_ms=0"}} - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", AgentOptions: map[string]any{"model": "fake-model", "system_prompt": "instructions"}, FunctionTools: []proto.FunctionTool{{Name: "lookup", Description: "Lookup.", Parameters: json.RawMessage(`{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"}}}}`)}}} + config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=" + mode, "GORACE=atexit_sleep_ms=0"}} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", Turn: proto.TurnSettings{Model: "fake-model"}, AgentOptions: map[string]any{"system_prompt": "instructions"}, FunctionTools: []proto.FunctionTool{{Name: "lookup", Description: "Lookup.", Parameters: json.RawMessage(`{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string"}}}}`)}}} ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() out := make(chan proto.Envelope, 16) diff --git a/apps/daemon/internal/agent/claudesdk/harness_config_test.go b/apps/daemon/internal/agent/claudesdk/harness_config_test.go index ae4dc36e1..217ad31f8 100644 --- a/apps/daemon/internal/agent/claudesdk/harness_config_test.go +++ b/apps/daemon/internal/agent/claudesdk/harness_config_test.go @@ -2,18 +2,19 @@ package claudesdk import ( "encoding/json" - "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" - "github.com/MiniMax-AI/OpenAgentCore/internal/harnessconfig" "path/filepath" "testing" + + "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" + "github.com/MiniMax-AI/OpenAgentCore/internal/harnessconfig" ) func TestHarnessConfigReachesBridgeAndOwnsSnapshot(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Entrypoint: filepath.Join(root, "main.js"), StateDir: filepath.Join(root, "state")} + config := Config{Entrypoint: filepath.Join(root, "main.js"), StateRoot: filepath.Join(root, "state")} native := map[string]any{"thinking": map[string]any{"type": "enabled", "budgetTokens": 1024}} - req := proto.PromptRequestPayload{AgentOptions: map[string]any{"model": "fixture", "harness_config": native}, ExecutionControls: &proto.ExecutionControls{TextVerbosity: "medium", ReasoningEffort: "high"}} + req := proto.PromptRequestPayload{AgentStateKey: testStateKey, Turn: proto.TurnSettings{Model: "fixture", ReasoningEffort: "high"}, AgentOptions: map[string]any{"harness_config": native}, ExecutionControls: &proto.ExecutionControls{TextVerbosity: "medium"}} start, _, err := prepareConfiguration(config, req) if err != nil { t.Fatal(err) diff --git a/apps/daemon/internal/agent/claudesdk/installation.go b/apps/daemon/internal/agent/claudesdk/installation.go index c4b5fa196..83ebf0c21 100644 --- a/apps/daemon/internal/agent/claudesdk/installation.go +++ b/apps/daemon/internal/agent/claudesdk/installation.go @@ -3,10 +3,11 @@ package claudesdk import ( "context" "fmt" - "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" - declaration "github.com/MiniMax-AI/OpenAgentCore/internal/harnessconfig/claudesdk" "path/filepath" "runtime" + + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" + declaration "github.com/MiniMax-AI/OpenAgentCore/internal/harnessconfig/claudesdk" ) func Installation() agent.Installation { diff --git a/apps/daemon/internal/agent/claudesdk/local.go b/apps/daemon/internal/agent/claudesdk/local.go index d6a465cda..9e32aa6e3 100644 --- a/apps/daemon/internal/agent/claudesdk/local.go +++ b/apps/daemon/internal/agent/claudesdk/local.go @@ -3,27 +3,16 @@ package claudesdk import ( "fmt" "os" - "path/filepath" "strings" ) -// ConfigureLocal selects the qualified, dedicated Runtime layout. The shared -// localworkspace binding still authorizes every request against its Session. -func ConfigureLocal(config Config, stateRoot, root, workspace string) (Config, error) { - if !filepath.IsAbs(stateRoot) || filepath.Clean(stateRoot) != stateRoot { - return Config{}, fmt.Errorf("claudesdk: state root must be a clean absolute directory") - } - config.StateDir = filepath.Join(stateRoot, "runtime", "claude-sdk", "history") - config.Workspace = &WorkspaceConfig{ - Directory: workspace, - HomeDir: filepath.Join(root, "runtime", "claude-sdk", "home"), - ScratchDir: filepath.Join(root, "runtime", "claude-sdk", "scratch"), - } - for _, dir := range []string{config.StateDir, config.Workspace.HomeDir, config.Workspace.ScratchDir} { - if err := os.MkdirAll(dir, 0700); err != nil { - return Config{}, err - } +// ConfigureLocal binds the dedicated workspace and keeps only the workspace +// environment names of the process environment. +func ConfigureLocal(config Config, workspace string) (Config, error) { + if !canonicalWorkspaceDir(workspace) { + return Config{}, fmt.Errorf("claudesdk: invalid trusted workspace configuration") } + config.Workspace = workspace config.Env = nil for _, entry := range os.Environ() { name, _, _ := strings.Cut(entry, "=") @@ -31,6 +20,5 @@ func ConfigureLocal(config Config, stateRoot, root, workspace string) (Config, e config.Env = append(config.Env, entry) } } - _, _, err := workspaceEnvironment(config) - return config, err + return config, nil } diff --git a/apps/daemon/internal/agent/claudesdk/local_test.go b/apps/daemon/internal/agent/claudesdk/local_test.go index 09ff0d219..ef94c0097 100644 --- a/apps/daemon/internal/agent/claudesdk/local_test.go +++ b/apps/daemon/internal/agent/claudesdk/local_test.go @@ -2,7 +2,6 @@ package claudesdk import ( "encoding/json" - "path/filepath" "slices" "strings" "testing" @@ -13,7 +12,7 @@ import ( func TestLocalWorkspaceBindingAndRequiredHistory(t *testing.T) { config := workspaceFixture(t) req := workspaceRequest() - req.LocalEnvironment = &proto.LocalEnvironment{ID: "environment", WorkspaceRoot: config.Workspace.Directory} + req.LocalEnvironment = &proto.LocalEnvironment{ID: "environment", WorkspaceRoot: config.Workspace} req.RequireExistingNativeSession = true start, _, err := prepareConfiguration(config, req) if err != nil || !start.RequireHistory { @@ -47,25 +46,3 @@ func TestWorkspaceProviderCredentialsReplaceAmbientSelection(t *testing.T) { } } } - -func TestLocalHistorySurvivesChangingInstanceRoot(t *testing.T) { - config := workspaceFixture(t) - retained, instance := t.TempDir(), t.TempDir() - first, err := ConfigureLocal(config, retained, instance, config.Workspace.Directory) - if err != nil { - t.Fatal(err) - } - second, err := ConfigureLocal(config, retained, t.TempDir(), config.Workspace.Directory) - if err != nil { - t.Fatal(err) - } - if first.StateDir != second.StateDir || first.StateDir != filepath.Join(retained, "runtime", "claude-sdk", "history") { - t.Fatal("history moved with compute") - } - if first.Workspace.HomeDir == second.Workspace.HomeDir || first.Workspace.ScratchDir == second.Workspace.ScratchDir { - t.Fatal("instance HOME or scratch retained across compute") - } - if _, err := ConfigureLocal(config, "relative", instance, config.Workspace.Directory); err == nil { - t.Fatal("invalid state root accepted") - } -} diff --git a/apps/daemon/internal/agent/claudesdk/mcp_bearer_test.go b/apps/daemon/internal/agent/claudesdk/mcp_bearer_test.go index 6fd5830cd..f428d6585 100644 --- a/apps/daemon/internal/agent/claudesdk/mcp_bearer_test.go +++ b/apps/daemon/internal/agent/claudesdk/mcp_bearer_test.go @@ -14,7 +14,7 @@ import ( func TestMCPBearerUsesFreshOwnedEnvironmentReferences(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Entrypoint: filepath.Join(root, "main.js"), StateDir: filepath.Join(root, "state")} + config := Config{Entrypoint: filepath.Join(root, "main.js"), StateRoot: filepath.Join(root, "state")} tokens := []string{"first.synthetic+/==", "second-synthetic_token~"} tools := []string{"echo.v1"} servers := []proto.MCPHTTPServer{ @@ -22,7 +22,7 @@ func TestMCPBearerUsesFreshOwnedEnvironmentReferences(t *testing.T) { {ConnectionOrigin: "service", ServerLabel: "second", ServerURL: "https://second.example/mcp", BearerToken: &tokens[1]}, {ConnectionOrigin: "service", ServerLabel: "anonymous", ServerURL: "http://anonymous.example/mcp"}, } - req := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, MCPHTTPServers: &servers, AgentOptions: map[string]any{"model": "fixture"}} + req := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, MCPHTTPServers: &servers, Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{}} seen := map[string]bool{} for range 2 { start, env, err := prepareConfiguration(config, req) @@ -64,9 +64,9 @@ func TestMCPBearerRejectsInvalidCredentialBeforeStateCreation(t *testing.T) { for _, token := range []string{"", "=", " space", "space ", "has space", "line\r\ninjection", "nul\x00byte", "opaque中文", "middle=padding", "punctuation:invalid"} { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Entrypoint: filepath.Join(root, "main.js"), StateDir: filepath.Join(root, "state")} + config := Config{Entrypoint: filepath.Join(root, "main.js"), StateRoot: filepath.Join(root, "state")} servers := []proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "fixture", ServerURL: "https://example.invalid/mcp", BearerToken: &token}} - req := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, MCPHTTPServers: &servers, AgentOptions: map[string]any{"model": "fixture"}} + req := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, MCPHTTPServers: &servers, Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{}} if _, _, err := prepareConfiguration(config, req); err == nil || err.Error() != "claudesdk: unsupported HTTPS MCP bearer credential" { t.Fatal("invalid bearer accepted or unsafe error returned") } diff --git a/apps/daemon/internal/agent/claudesdk/mcp_environment_test.go b/apps/daemon/internal/agent/claudesdk/mcp_environment_test.go index d614578ea..cb67554ed 100644 --- a/apps/daemon/internal/agent/claudesdk/mcp_environment_test.go +++ b/apps/daemon/internal/agent/claudesdk/mcp_environment_test.go @@ -15,7 +15,7 @@ func TestEnvironmentMCPUsesInstalledLauncherAndSelectedCredential(t *testing.T) req := workspaceRequest() token := "selected-user-token" t.Setenv("MCP_TOKEN", "unselected-native-token") - req.LocalEnvironment = &proto.LocalEnvironment{CapabilityRoot: "/private/runtime/capabilities", WorkspaceRoot: config.Workspace.Directory, MCP: []proto.EnvironmentMCP{ + req.LocalEnvironment = &proto.LocalEnvironment{CapabilityRoot: "/private/runtime/capabilities", WorkspaceRoot: config.Workspace, MCP: []proto.EnvironmentMCP{ {InstallationRoot: "/private/runtime/capabilities", PackageRoot: "plugins/local", Server: proto.PluginMCPServer{Name: "local", Type: "stdio", Command: "untrusted-package-command", Args: []string{"package-argument"}, EnvVars: []string{"MCP_TOKEN"}}}, {InstallationRoot: "/private/runtime/capabilities", PackageRoot: "plugins/remote", Server: proto.PluginMCPServer{Name: "remote", Type: "http", URL: "https://example.invalid/mcp", BearerTokenEnvVar: "MCP_TOKEN"}, BearerToken: &token}, }} @@ -94,7 +94,7 @@ func TestEnvironmentMCPObservationsUseInstalledDeclarations(t *testing.T) { func TestPublicMCPStdioStartsInTheWorkspaceDirectory(t *testing.T) { servers := []proto.MCPHTTPServer{{ConnectionOrigin: "environment", ServerLabel: "local", Stdio: &proto.MCPStdio{Command: "run", Cwd: "/workspace", EnvVars: []string{"TOKEN"}}}} - req := proto.PromptRequestPayload{LocalEnvironment: &proto.LocalEnvironment{WorkspaceDirectory: "/workspace", WorkspaceRoot: "/environment/workspace"}, MCPHTTPServers: &servers} + req := proto.PromptRequestPayload{AgentStateKey: testStateKey, LocalEnvironment: &proto.LocalEnvironment{WorkspaceDirectory: "/workspace", WorkspaceRoot: "/environment/workspace"}, MCPHTTPServers: &servers} projected, _, err := prepareRuntimeMCP(req) raw, _ := json.Marshal(projected) if err != nil || string(raw) != `[{"server_label":"local","allowed_tools":null,"command":"run","args":[],"declared":true}]` { diff --git a/apps/daemon/internal/agent/claudesdk/mcp_test.go b/apps/daemon/internal/agent/claudesdk/mcp_test.go index 25ba5ab6b..9a5d90be6 100644 --- a/apps/daemon/internal/agent/claudesdk/mcp_test.go +++ b/apps/daemon/internal/agent/claudesdk/mcp_test.go @@ -14,9 +14,9 @@ func TestHTTPMCPDeclaration(t *testing.T) { t.Run(mode, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Entrypoint: filepath.Join(root, "main.js"), StateDir: filepath.Join(root, "state")} + config := Config{Entrypoint: filepath.Join(root, "main.js"), StateRoot: filepath.Join(root, "state")} servers := []proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "fixture", ServerURL: "https://example.invalid/mcp"}} - req := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, MCPHTTPServers: &servers, AgentOptions: map[string]any{"model": "fixture"}} + req := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, MCPHTTPServers: &servers, Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{}} tools := []string{"echo"} switch mode { case "selected": diff --git a/apps/daemon/internal/agent/claudesdk/messages_test.go b/apps/daemon/internal/agent/claudesdk/messages_test.go index 7a6c0ffa1..e185a96dc 100644 --- a/apps/daemon/internal/agent/claudesdk/messages_test.go +++ b/apps/daemon/internal/agent/claudesdk/messages_test.go @@ -19,8 +19,8 @@ func TestMessageObservations(t *testing.T) { t.Run(mode, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=" + mode, "GORACE=atexit_sleep_ms=0"}} - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", AgentOptions: map[string]any{"model": "fake-model", "system_prompt": "instructions"}} + config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=" + mode, "GORACE=atexit_sleep_ms=0"}} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", Turn: proto.TurnSettings{Model: "fake-model"}, AgentOptions: map[string]any{"system_prompt": "instructions"}} ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() out := make(chan proto.Envelope, 16) diff --git a/apps/daemon/internal/agent/claudesdk/options.go b/apps/daemon/internal/agent/claudesdk/options.go index d82cfd9d1..85750665c 100644 --- a/apps/daemon/internal/agent/claudesdk/options.go +++ b/apps/daemon/internal/agent/claudesdk/options.go @@ -6,6 +6,7 @@ import ( "path/filepath" "strings" + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" harnessconfiguration "github.com/MiniMax-AI/OpenAgentCore/internal/harnessconfig/claudesdk" ) @@ -13,9 +14,12 @@ import ( type Config struct { Node string Entrypoint string - StateDir string - Env []string - Workspace *WorkspaceConfig + // StateRoot and RuntimeRoot hold each Session's native state, derived from its state key. + StateRoot string + RuntimeRoot string + Env []string + // Workspace is the trusted workspace directory; empty means environment:none. + Workspace string } type subagentOptions struct { @@ -45,18 +49,15 @@ func prepareConfiguration(config Config, req proto.PromptRequestPayload) (startR fail := func(reason string) (startRequest, []string, error) { return startRequest{}, nil, fmt.Errorf("claudesdk: %s", reason) } - modelConfiguration, err := harnessconfiguration.Declaration.Configuration.Prepare(req.AgentOptions) + modelConfiguration, err := harnessconfiguration.Declaration.Configuration.Prepare(req.Turn.Model, req.AgentOptions) if err != nil { return startRequest{}, nil, err } if err := harnessconfiguration.Declaration.ValidateExecutionControls(req.ExecutionControls); err != nil { return fail(err.Error()) } - effort := "" - if req.ExecutionControls != nil { - effort = req.ExecutionControls.ReasoningEffort - } - start.NativeModelOptions = compileNativeModelOptions(modelConfiguration.HarnessConfig, effort) + start.Model = req.Turn.Model + start.NativeModelOptions = compileNativeModelOptions(modelConfiguration.HarnessConfig, req.Turn.ReasoningEffort) if err := req.ValidateToolSearch(true); err != nil { return startRequest{}, nil, err } @@ -113,12 +114,9 @@ func prepareConfiguration(config Config, req proto.PromptRequestPayload) (startR } value, ok := raw.(string) if !ok { - return fail("model and system_prompt options must be strings") + return fail("system_prompt option must be a string") } - switch name { - case "model": - start.Model = value - case "system_prompt": + if name == "system_prompt" { start.SystemPrompt = value } } @@ -129,29 +127,31 @@ func prepareConfiguration(config Config, req proto.PromptRequestPayload) (startR return fail("SDK entrypoint must be absolute") } config.Env = withProvider(config.Env, provider) - if config.Workspace != nil { - profile, env, err := prepareWorkspace(config, req) + state, err := agent.StateDir(config.StateRoot, harnessconfiguration.Declaration.Kind, req.AgentStateKey) + if err != nil { + return fail(err.Error()) + } + if config.Workspace != "" { + profile, env, err := prepareWorkspace(config, req, state) if err != nil { return startRequest{}, nil, err } start.Workspace = profile - start.Cwd = config.Workspace.Directory + start.Cwd = config.Workspace return start, env, nil } if req.LocalEnvironment != nil || req.RequireExistingNativeSession { return fail("local execution and history recovery require a dedicated workspace") } - if !filepath.IsAbs(config.StateDir) || filepath.Clean(config.StateDir) != config.StateDir || filepath.Dir(config.StateDir) == config.StateDir { - return fail("SDK state must be an explicit private absolute directory") - } - start.Cwd = filepath.Join(config.StateDir, "work") - for _, dir := range []string{config.StateDir, filepath.Join(config.StateDir, "tmp"), start.Cwd} { + start.Cwd = filepath.Join(state, "work") + configDir, home, tmp := filepath.Join(state, "config"), filepath.Join(state, "home"), filepath.Join(state, "tmp") + for _, dir := range []string{start.Cwd, configDir, home, tmp} { if err := os.MkdirAll(dir, 0o700); err != nil { return startRequest{}, nil, err } } env := withProvider(append(append([]string{}, os.Environ()...), config.Env...), provider) - env = append(env, "CLAUDE_CONFIG_DIR="+config.StateDir, "TMPDIR="+filepath.Join(config.StateDir, "tmp")) + env = append(env, "CLAUDE_CONFIG_DIR="+configDir, "HOME="+home, "TMPDIR="+tmp) projectedMCP, mcpEnv, err := prepareRuntimeMCP(req) if err != nil { return startRequest{}, nil, err diff --git a/apps/daemon/internal/agent/claudesdk/options_test.go b/apps/daemon/internal/agent/claudesdk/options_test.go index c3dc1305d..74fc3f86b 100644 --- a/apps/daemon/internal/agent/claudesdk/options_test.go +++ b/apps/daemon/internal/agent/claudesdk/options_test.go @@ -14,18 +14,17 @@ func TestNullableSystemPrompt(t *testing.T) { want string reject bool }{ - {"omitted", map[string]any{"model": "test-model"}, "", false}, - {"null", map[string]any{"model": "test-model", "system_prompt": nil}, "", false}, - {"empty", map[string]any{"model": "test-model", "system_prompt": ""}, "", false}, - {"text", map[string]any{"model": "test-model", "system_prompt": "instructions"}, "instructions", false}, - {"null-model", map[string]any{"model": nil}, "", true}, - {"null-unknown", map[string]any{"model": "test-model", "unsupported": nil}, "", true}, + {"omitted", map[string]any{}, "", false}, + {"null", map[string]any{"system_prompt": nil}, "", false}, + {"empty", map[string]any{"system_prompt": ""}, "", false}, + {"text", map[string]any{"system_prompt": "instructions"}, "instructions", false}, + {"null-unknown", map[string]any{"unsupported": nil}, "", true}, } { t.Run(tc.name, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Entrypoint: filepath.Join(root, "main.js"), StateDir: filepath.Join(root, "state")} - start, _, err := prepareConfiguration(config, proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), AgentOptions: tc.options}) + config := Config{Entrypoint: filepath.Join(root, "main.js"), StateRoot: filepath.Join(root, "state")} + start, _, err := prepareConfiguration(config, proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), Turn: proto.TurnSettings{Model: "test-model"}, AgentOptions: tc.options}) if (err != nil) != tc.reject || (!tc.reject && start.SystemPrompt != tc.want) { t.Fatalf("system prompt %q, error %v", start.SystemPrompt, err) } diff --git a/apps/daemon/internal/agent/claudesdk/preparation_fixture_test.go b/apps/daemon/internal/agent/claudesdk/preparation_fixture_test.go index 58805600b..7234139ba 100644 --- a/apps/daemon/internal/agent/claudesdk/preparation_fixture_test.go +++ b/apps/daemon/internal/agent/claudesdk/preparation_fixture_test.go @@ -84,14 +84,14 @@ func runPreparationHelper() { time.Sleep(time.Millisecond) } } - emit(bridgeEvent{Type: "executor_ready", Protocol: 3}) + emit(bridgeEvent{Type: "executor_ready", Protocol: 4}) if !scanner.Scan() { return } raw = append([]byte{}, scanner.Bytes()...) _ = os.WriteFile(filepath.Join(state, "start.json"), raw, 0o600) fields = nil - if json.Unmarshal(raw, &fields) != nil || len(fields) != 3 || string(fields["type"]) != `"turn_start"` || string(fields["input"]) != `[{"content":[{"type":"input_text","text":"hello"}]}]` { + if json.Unmarshal(raw, &fields) != nil || len(fields) != 4 || string(fields["type"]) != `"turn_start"` || string(fields["input"]) != `[{"content":[{"type":"input_text","text":"hello"}]}]` { os.Exit(4) } var turnID string diff --git a/apps/daemon/internal/agent/claudesdk/preparation_test.go b/apps/daemon/internal/agent/claudesdk/preparation_test.go index 27a4436ad..6b681a568 100644 --- a/apps/daemon/internal/agent/claudesdk/preparation_test.go +++ b/apps/daemon/internal/agent/claudesdk/preparation_test.go @@ -31,7 +31,7 @@ func TestPreparationWaitsForReceiptAndRetainsConfiguration(t *testing.T) { } result <- e }() - raw := waitPreparationFile(t, filepath.Join(config.StateDir, "prepare.json")) + raw := waitPreparationFile(t, filepath.Join(testState(config), "prepare.json")) select { case <-result: t.Fatal("preparation returned before its native receipt") @@ -39,7 +39,7 @@ func TestPreparationWaitsForReceiptAndRetainsConfiguration(t *testing.T) { t.Fatal(err) default: } - if err := os.WriteFile(filepath.Join(config.StateDir, "ready"), nil, 0o600); err != nil { + if err := os.WriteFile(filepath.Join(testState(config), "ready"), nil, 0o600); err != nil { t.Fatal(err) } var resource agent.Executor @@ -53,7 +53,7 @@ func TestPreparationWaitsForReceiptAndRetainsConfiguration(t *testing.T) { e := resource.(*executor) defer e.Close(context.Background()) pid := e.base.process.Cmd.Process.Pid - if _, err := os.Stat(filepath.Join(config.StateDir, "start.json")); !os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(testState(config), "start.json")); !os.IsNotExist(err) { t.Fatal("preparation submitted input") } var frozen startRequest @@ -64,16 +64,20 @@ func TestPreparationWaitsForReceiptAndRetainsConfiguration(t *testing.T) { t.Fatal("configuration-only request was not retained") } config.Env[0] = "ANTHROPIC_AUTH_TOKEN=changed" - config.Workspace.Directory = "/changed" - req.AgentOptions["model"] = "changed" + config.Workspace = "/changed" + req.Turn.Model = "changed" req.AgentSessionID = "changed" out := make(chan proto.Envelope, 16) operation, stopOperation := context.WithCancel(ctx) - turn, err := e.StartTurn(operation, "actual-run", proto.TextInput("hello"), out) + turn, err := e.StartTurn(operation, "actual-run", proto.TurnSettings{Model: "turn-model", Review: "auto_review"}, proto.TextInput("hello"), out) stopOperation() if err != nil { t.Fatal(err) } + var sent struct{ Settings json.RawMessage } + if json.Unmarshal(waitPreparationFile(t, filepath.Join(testState(config), "start.json")), &sent) != nil || string(sent.Settings) != `{"model":"turn-model","effort":null,"review":"auto_review"}` { + t.Fatalf("turn_start settings = %s", sent.Settings) + } if turn.(*session).owner != e || turn.(*session).process.Cmd.Process.Pid != pid { t.Fatal("StartTurn replaced the prepared native process") } @@ -91,7 +95,7 @@ func TestPreparationWaitsForReceiptAndRetainsConfiguration(t *testing.T) { if done.Content != "completed" || done.Metadata[proto.DoneMetaAgentSessionID] != "native-session" || done.Usage.Raw["claude_sdk_result"] == nil { t.Fatal("prepared execution lost ordinary output or frozen resume", done) } - if _, err := os.Stat(filepath.Join(config.StateDir, "released")); err != nil { + if _, err := os.Stat(filepath.Join(testState(config), "released")); err != nil { t.Fatal("completion preceded process release", err) } } @@ -122,7 +126,7 @@ func TestPreparationRejectsInputAndUnavailableProfilesBeforeLaunch(t *testing.T) if _, err := NewExecutorFactory(config)(t.Context(), req); err == nil { t.Fatal("invalid preparation was accepted") } - if _, err := os.Stat(filepath.Join(config.StateDir, "launched")); !os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(testState(config), "launched")); !os.IsNotExist(err) { t.Fatal("rejection launched native preparation") } }) @@ -161,7 +165,7 @@ func TestPreparationFailureAndUnusedRelease(t *testing.T) { prompt = "hello" cancel() } - _, startErr := e.StartTurn(operation, "run", proto.TextInput(prompt), make(chan proto.Envelope, 8)) + _, startErr := e.StartTurn(operation, "run", proto.TurnSettings{}, proto.TextInput(prompt), make(chan proto.Envelope, 8)) cancel() if startErr == nil { t.Fatal("invalid or cancelled StartTurn succeeded") @@ -176,7 +180,7 @@ func TestPreparationFailureAndUnusedRelease(t *testing.T) { case <-time.After(5 * time.Second): t.Fatal("unused process was not settled") } - if _, err := e.StartTurn(t.Context(), "late", proto.TextInput("hello"), make(chan proto.Envelope, 8)); err == nil { + if _, err := e.StartTurn(t.Context(), "late", proto.TurnSettings{}, proto.TextInput("hello"), make(chan proto.Envelope, 8)); err == nil { t.Fatal("released Executor was reusable") } }) diff --git a/apps/daemon/internal/agent/claudesdk/readiness.go b/apps/daemon/internal/agent/claudesdk/readiness.go index a9f7f8fbf..b1b328aa7 100644 --- a/apps/daemon/internal/agent/claudesdk/readiness.go +++ b/apps/daemon/internal/agent/claudesdk/readiness.go @@ -103,12 +103,18 @@ func CheckRuntime(ctx context.Context, config Config) (RuntimeInfo, error) { binary = "node" } env := append(append([]string{}, os.Environ()...), config.Env...) - if config.Workspace != nil { + if config.Workspace != "" { var err error - _, env, err = workspaceEnvironment(config) + if env, _, err = trustedEnvironment(config); err != nil { + return RuntimeInfo{}, err + } + // The check belongs to no Session, so it writes only to a home it discards. + home, err := os.MkdirTemp("", "claude-runtime-check-") if err != nil { return RuntimeInfo{}, err } + defer os.RemoveAll(home) + env = append(env, "HOME="+home, "TMPDIR="+home, "CLAUDE_CONFIG_DIR="+home) } process, err := clirunner.Start(clirunner.StartOptions{ Parent: ctx, Binary: binary, diff --git a/apps/daemon/internal/agent/claudesdk/readiness_test.go b/apps/daemon/internal/agent/claudesdk/readiness_test.go index 466d6e38e..93c106b0a 100644 --- a/apps/daemon/internal/agent/claudesdk/readiness_test.go +++ b/apps/daemon/internal/agent/claudesdk/readiness_test.go @@ -20,11 +20,11 @@ const readyReport = `{"type":"runtime_ready","protocol":3,"node":"22.22.2","sdk" func TestRequiredMCPNeedsQualifiedRuntime(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "main.js"), StateDir: filepath.Join(root, "state"), Env: []string{ + config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "main.js"), StateRoot: filepath.Join(root, "state"), Env: []string{ "GO_CLAUDE_READINESS_HELPER=1", "READINESS_MODE=ready-http-mcp", "GORACE=atexit_sleep_ms=0", }} - req := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, - AgentOptions: map[string]any{"model": "fixture"}, MCPHTTPServers: &[]proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "fixture", ServerURL: "https://example.invalid/mcp", Required: true}}} + req := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, + Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{}, MCPHTTPServers: &[]proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "fixture", ServerURL: "https://example.invalid/mcp", Required: true}}} if _, err := startSingleTurn(t.Context(), config, req, make(chan proto.Envelope, 1)); err == nil || err.Error() != "claudesdk: packaged runtime does not support required HTTP MCP" { t.Fatalf("unqualified runtime executed required MCP: %v", err) } @@ -33,7 +33,7 @@ func TestRequiredMCPNeedsQualifiedRuntime(t *testing.T) { func TestHTTPMCPRejectsOldPackagedRuntime(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "main.js"), StateDir: filepath.Join(root, "state"), Env: []string{ + config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "main.js"), StateRoot: filepath.Join(root, "state"), Env: []string{ "GO_CLAUDE_READINESS_HELPER=1", "READINESS_MODE=ready", "GORACE=atexit_sleep_ms=0", }} info, err := CheckRuntime(t.Context(), config) @@ -44,8 +44,8 @@ func TestHTTPMCPRejectsOldPackagedRuntime(t *testing.T) { if !info.SupportsHTTPMCP() { t.Fatal("runtime feature not recognized") } - req := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, - AgentOptions: map[string]any{"model": "fixture"}, MCPHTTPServers: &[]proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "fixture", ServerURL: "https://example.invalid/mcp"}}} + req := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, + Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{}, MCPHTTPServers: &[]proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "fixture", ServerURL: "https://example.invalid/mcp"}}} if _, err := startSingleTurn(t.Context(), config, req, make(chan proto.Envelope, 1)); err == nil || !strings.Contains(err.Error(), "packaged runtime does not support HTTP MCP") { t.Fatalf("old runtime was not rejected before execution: %v", err) } @@ -77,12 +77,12 @@ func TestRuntimeReadiness(t *testing.T) { func TestMCPBearerRejectsAnonymousOnlyRuntimeWithoutProbeSecrets(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "main.js"), StateDir: filepath.Join(root, "state"), Env: []string{ + config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "main.js"), StateRoot: filepath.Join(root, "state"), Env: []string{ "GO_CLAUDE_READINESS_HELPER=1", "READINESS_MODE=ready-http-mcp", "GORACE=atexit_sleep_ms=0", }} token := "private-fixture-token" - req := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, - AgentOptions: map[string]any{"model": "fixture"}, MCPHTTPServers: &[]proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "fixture", ServerURL: "https://example.invalid/mcp", BearerToken: &token}}} + req := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), DisableExecutionEnvironment: true, + Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{}, MCPHTTPServers: &[]proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "fixture", ServerURL: "https://example.invalid/mcp", BearerToken: &token}}} if _, err := startSingleTurn(t.Context(), config, req, make(chan proto.Envelope, 1)); err == nil || err.Error() != "claudesdk: packaged runtime does not support authenticated HTTP MCP" { t.Fatalf("old runtime executed authenticated request or readiness received its secret: %v", err) } diff --git a/apps/daemon/internal/agent/claudesdk/restrictions_test.go b/apps/daemon/internal/agent/claudesdk/restrictions_test.go index 494e32727..aad7b7e25 100644 --- a/apps/daemon/internal/agent/claudesdk/restrictions_test.go +++ b/apps/daemon/internal/agent/claudesdk/restrictions_test.go @@ -24,8 +24,8 @@ func TestTextFactoryAcceptsRestrictiveCapabilities(t *testing.T) { t.Run(test.name, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=success", "GORACE=atexit_sleep_ms=0"}} - request := proto.PromptRequestPayload{RunID: "restricted-run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", DisableExecutionEnvironment: test.environment, DisableSubagents: test.subagents, ExecutionControls: test.controls, AgentOptions: map[string]any{"model": "fake-model", "system_prompt": "instructions"}} + config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=success", "GORACE=atexit_sleep_ms=0"}} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "restricted-run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", DisableExecutionEnvironment: test.environment, DisableSubagents: test.subagents, ExecutionControls: test.controls, Turn: proto.TurnSettings{Model: "fake-model"}, AgentOptions: map[string]any{"system_prompt": "instructions"}} ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() out := make(chan proto.Envelope, 16) diff --git a/apps/daemon/internal/agent/claudesdk/session.go b/apps/daemon/internal/agent/claudesdk/session.go index d0bea805c..4fb87ba72 100644 --- a/apps/daemon/internal/agent/claudesdk/session.go +++ b/apps/daemon/internal/agent/claudesdk/session.go @@ -37,6 +37,15 @@ type turnStartFrame struct { Type string `json:"type"` TurnID string `json:"turn_id"` Input proto.MessageInput `json:"input"` + // Settings are the Turn's model, effort and review; the bridge applies what differs from the last Turn. + Settings turnSettings `json:"settings"` +} + +// turnSettings carries a null Effort to return to the model's default effort. +type turnSettings struct { + Model string `json:"model"` + Effort *string `json:"effort"` + Review string `json:"review"` } type turnCancelFrame struct { diff --git a/apps/daemon/internal/agent/claudesdk/session_test.go b/apps/daemon/internal/agent/claudesdk/session_test.go index e885c51a8..d402ebbc0 100644 --- a/apps/daemon/internal/agent/claudesdk/session_test.go +++ b/apps/daemon/internal/agent/claudesdk/session_test.go @@ -21,8 +21,8 @@ func TestTextFactoryCompletionAndFailures(t *testing.T) { t.Run(mode, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=" + mode, "GORACE=atexit_sleep_ms=0"}} - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", AgentOptions: map[string]any{"model": "fake-model", "system_prompt": "instructions"}} + config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=" + mode, "GORACE=atexit_sleep_ms=0"}} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", Turn: proto.TurnSettings{Model: "fake-model"}, AgentOptions: map[string]any{"system_prompt": "instructions"}} ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() out := make(chan proto.Envelope, 16) @@ -55,7 +55,7 @@ func TestTextFactoryCompletionAndFailures(t *testing.T) { if payload.Content != "final" || payload.Metadata[proto.DoneMetaAgentSessionID] != "native-session" || deltas != "partial" { t.Fatalf("bad completion: %+v, deltas %q", payload, deltas) } - if _, err := os.Stat(filepath.Join(config.StateDir, "released")); err != nil { + if _, err := os.Stat(filepath.Join(testState(config), "released")); err != nil { t.Fatal("Done preceded process release") } } else if payload.Metadata[proto.DoneMetaAgentSessionID] != nil { @@ -75,15 +75,15 @@ func TestTextFactoryRejectsUnsupportedInput(t *testing.T) { t.Run(kind, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: "must-not-run", Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state")} - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), AgentOptions: map[string]any{"model": "fake"}} + config := Config{Node: "must-not-run", Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state")} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), Turn: proto.TurnSettings{Model: "fake"}, AgentOptions: map[string]any{}} switch kind { case "execution-controls": request.ExecutionControls = &proto.ExecutionControls{TextVerbosity: "low"} case "tool": request.FunctionTools = []proto.FunctionTool{{}} case "outside": - config.StateDir = "relative-state" + config.StateRoot = "relative-state" } _, err := startSingleTurn(context.Background(), config, request, make(chan proto.Envelope, 1)) if err == nil || !strings.HasPrefix(err.Error(), "claudesdk:") { diff --git a/apps/daemon/internal/agent/claudesdk/steering_test.go b/apps/daemon/internal/agent/claudesdk/steering_test.go index 2313476b6..216daebd2 100644 --- a/apps/daemon/internal/agent/claudesdk/steering_test.go +++ b/apps/daemon/internal/agent/claudesdk/steering_test.go @@ -23,11 +23,11 @@ func TestSteeringReceiptsAndLifecycle(t *testing.T) { t.Run(mode, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=steering-" + mode, "GORACE=atexit_sleep_ms=0"}} + config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=steering-" + mode, "GORACE=atexit_sleep_ms=0"}} if mode == "phased" { config.Env[1] = "SDK_HELPER_MODE=steering-timeout" } - request := proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native", AgentOptions: map[string]any{"model": "fake-model", "system_prompt": "instructions"}} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), AgentSessionID: "native", Turn: proto.TurnSettings{Model: "fake-model"}, AgentOptions: map[string]any{"system_prompt": "instructions"}} ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() out := make(chan proto.Envelope, 16) diff --git a/apps/daemon/internal/agent/claudesdk/tool_environment_test.go b/apps/daemon/internal/agent/claudesdk/tool_environment_test.go index 873bc281f..26a1cb0f6 100644 --- a/apps/daemon/internal/agent/claudesdk/tool_environment_test.go +++ b/apps/daemon/internal/agent/claudesdk/tool_environment_test.go @@ -16,8 +16,8 @@ func TestSelfHostedToolEnvironment(t *testing.T) { } t.Setenv("OAC_RUNTIME_TOOL_ENV_FILE", file) req := workspaceRequest() - req.LocalEnvironment = &proto.LocalEnvironment{WorkspaceRoot: config.Workspace.Directory} - profile, _, err := prepareWorkspace(config, req) + req.LocalEnvironment = &proto.LocalEnvironment{WorkspaceRoot: config.Workspace} + profile, _, err := prepareWorkspace(config, req, testState(config)) if err != nil { t.Fatal(err) } @@ -27,7 +27,7 @@ func TestSelfHostedToolEnvironment(t *testing.T) { if err := os.WriteFile(file, []byte(`[]`), 0600); err != nil { t.Fatal(err) } - if _, _, err := prepareWorkspace(config, req); err == nil { + if _, _, err := prepareWorkspace(config, req, testState(config)); err == nil { t.Fatal("invalid explicit tool configuration was ignored") } } diff --git a/apps/daemon/internal/agent/claudesdk/usage_test.go b/apps/daemon/internal/agent/claudesdk/usage_test.go index d3c49bf3c..09b0d7f6c 100644 --- a/apps/daemon/internal/agent/claudesdk/usage_test.go +++ b/apps/daemon/internal/agent/claudesdk/usage_test.go @@ -22,8 +22,8 @@ func TestUsageTransportPreservesSnapshotOnFailureAndDone(t *testing.T) { t.Run(mode, func(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) - config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateDir: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=usage-" + mode, "GORACE=atexit_sleep_ms=0"}} - request := proto.PromptRequestPayload{RunID: "usage-run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", AgentOptions: map[string]any{"model": "fake-model", "system_prompt": "instructions"}} + config := Config{Node: os.Args[0], Entrypoint: filepath.Join(root, "worker"), StateRoot: filepath.Join(root, "state"), Env: []string{"GO_CLAUDE_SDK_HELPER=1", "SDK_HELPER_MODE=usage-" + mode, "GORACE=atexit_sleep_ms=0"}} + request := proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "usage-run", Input: proto.TextInput("hello"), AgentSessionID: "native-session", Turn: proto.TurnSettings{Model: "fake-model"}, AgentOptions: map[string]any{"system_prompt": "instructions"}} ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() out := make(chan proto.Envelope, 16) diff --git a/apps/daemon/internal/agent/claudesdk/workspace.go b/apps/daemon/internal/agent/claudesdk/workspace.go index e76457cc4..9f2c6ac1d 100644 --- a/apps/daemon/internal/agent/claudesdk/workspace.go +++ b/apps/daemon/internal/agent/claudesdk/workspace.go @@ -7,20 +7,12 @@ import ( "slices" "strings" + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/localworkspace" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" + harnessconfiguration "github.com/MiniMax-AI/OpenAgentCore/internal/harnessconfig/claudesdk" ) -// WorkspaceConfig binds one trusted private placement. It does not create an -// isolation boundary or authorize a public Environment. The operator must place -// the entire factory inside the qualified outer mount/process boundary first. -// State directories must already exist. -type WorkspaceConfig struct { - Directory string - HomeDir string - ScratchDir string -} - type workspaceProfile struct { ToolEnv map[string]string `json:"tool_env,omitempty"` CapabilityRoot string `json:"capability_root,omitempty"` @@ -32,17 +24,29 @@ type workspaceProfile struct { EnvNames []string `json:"env_names"` } -func prepareWorkspace(config Config, req proto.PromptRequestPayload) (*workspaceProfile, []string, error) { +func prepareWorkspace(config Config, req proto.PromptRequestPayload, state string) (*workspaceProfile, []string, error) { if req.DisableExecutionEnvironment { return nil, nil, fmt.Errorf("claudesdk: workspace profile does not support the requested execution combination") } - if req.LocalEnvironment != nil && req.LocalEnvironment.WorkspaceRoot != config.Workspace.Directory { + if req.LocalEnvironment != nil && req.LocalEnvironment.WorkspaceRoot != config.Workspace { return nil, nil, fmt.Errorf("claudesdk: workspace root conflicts with the trusted workspace binding") } - profile, env, err := workspaceEnvironment(config) + // Retained history lives with the Environment filesystem; HOME and scratch stay on the Runtime's own disk. + runtime, err := agent.StateDir(config.RuntimeRoot, harnessconfiguration.Declaration.Kind, req.AgentStateKey) if err != nil { return nil, nil, err } + env, names, err := trustedEnvironment(config) + if err != nil { + return nil, nil, err + } + profile := &workspaceProfile{Home: filepath.Join(runtime, "home"), State: filepath.Join(state, "config"), Scratch: filepath.Join(runtime, "scratch"), EnvNames: names} + env = append(env, "HOME="+profile.Home, "TMPDIR="+profile.Scratch, "CLAUDE_CONFIG_DIR="+profile.State) + for _, dir := range []string{profile.State, profile.Home, profile.Scratch} { + if err = os.MkdirAll(dir, 0o700); err != nil { + return nil, nil, err + } + } if req.LocalEnvironment != nil { profile.ToolEnv, err = localworkspace.ReadOptionalToolEnvironment() if err != nil { @@ -62,27 +66,20 @@ func prepareWorkspace(config Config, req proto.PromptRequestPayload) (*workspace return profile, append(env, credentials...), nil } -// Harness state paths and selected model credentials overlay the user environment. -func workspaceEnvironment(config Config) (*workspaceProfile, []string, error) { - fail := func() (*workspaceProfile, []string, error) { +// trustedEnvironment validates the trusted binding and returns the user environment without Harness state paths or credentials. +func trustedEnvironment(config Config) ([]string, []string, error) { + fail := func() ([]string, []string, error) { return nil, nil, fmt.Errorf("claudesdk: invalid trusted workspace configuration") } - w := config.Workspace - if w == nil { - return fail() - } for _, path := range []string{config.Node, config.Entrypoint, filepath.Join(filepath.Dir(config.Entrypoint), "runtime_check.js")} { info, err := os.Stat(path) if !filepath.IsAbs(path) || err != nil || !info.Mode().IsRegular() { return fail() } } - for _, path := range []string{w.Directory, config.StateDir, w.HomeDir, w.ScratchDir} { - if !canonicalWorkspaceDir(path) { - return fail() - } + if !canonicalWorkspaceDir(config.Workspace) { + return fail() } - profile := &workspaceProfile{Home: w.HomeDir, State: config.StateDir, Scratch: w.ScratchDir, EnvNames: []string{}} env := []string{} for _, entry := range os.Environ() { name, _, _ := strings.Cut(entry, "=") @@ -90,7 +87,7 @@ func workspaceEnvironment(config Config) (*workspaceProfile, []string, error) { env = append(env, entry) } } - env = append(env, "HOME="+w.HomeDir, "TMPDIR="+w.ScratchDir, "CLAUDE_CONFIG_DIR="+config.StateDir) + names := []string{} seen := map[string]bool{} for _, entry := range config.Env { name, _, ok := strings.Cut(entry, "=") @@ -98,10 +95,10 @@ func workspaceEnvironment(config Config) (*workspaceProfile, []string, error) { return fail() } seen[name] = true - profile.EnvNames = append(profile.EnvNames, name) + names = append(names, name) env = append(env, entry) } - return profile, env, nil + return env, names, nil } func workspaceEnvName(name string) bool { diff --git a/apps/daemon/internal/agent/claudesdk/workspace_launch_test.go b/apps/daemon/internal/agent/claudesdk/workspace_launch_test.go index 861312450..612d3cf64 100644 --- a/apps/daemon/internal/agent/claudesdk/workspace_launch_test.go +++ b/apps/daemon/internal/agent/claudesdk/workspace_launch_test.go @@ -27,7 +27,7 @@ case "$1" in printf '%s\n' '{"type":"runtime_ready","protocol":3,"node":"fixture","sdk":"fixture","mcp":"fixture","native":"fixture","features":["workspace_tools","workspace_prepare","workspace_command_observations"]}' ;; *) IFS= read -r request - printf '%s\n' '{"type":"executor_ready","protocol":3}' + printf '%s\n' '{"type":"executor_ready","protocol":4}' IFS= read -r request printf '%s\n' '{"type":"result","turn_id":"run","session_id":"native","text":"completed"}' printf '%s\n' '{"type":"turn_settled","turn_id":"run","confirmed":true,"reusable":true,"reason":""}' ;; @@ -60,14 +60,14 @@ esac } // Feature checking must reject an older bridge without starting execution. script = strings.ReplaceAll(script, `"features":["workspace_tools","workspace_prepare","workspace_command_observations"]`, `"features":[]`) - script = strings.ReplaceAll(script, "IFS= read -r request", "touch '"+filepath.Join(config.StateDir, "unexpected-start")+"'") + script = strings.ReplaceAll(script, "IFS= read -r request", "touch '"+filepath.Join(testState(config), "unexpected-start")+"'") if err := os.WriteFile(config.Node, []byte(script), 0o700); err != nil { t.Fatal(err) } if _, err := startSingleTurn(t.Context(), config, workspaceRequest(), out); err == nil { t.Fatal("old packaged bridge accepted workspace execution") } - if _, err := os.Stat(filepath.Join(config.StateDir, "unexpected-start")); !os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(testState(config), "unexpected-start")); !os.IsNotExist(err) { t.Fatal("old packaged bridge started execution") } } diff --git a/apps/daemon/internal/agent/claudesdk/workspace_structured_test.go b/apps/daemon/internal/agent/claudesdk/workspace_structured_test.go index 4b77d59ee..8a2815e34 100644 --- a/apps/daemon/internal/agent/claudesdk/workspace_structured_test.go +++ b/apps/daemon/internal/agent/claudesdk/workspace_structured_test.go @@ -25,7 +25,7 @@ func TestWorkspaceStructuredPreparationQualificationAndFrozenSchema(t *testing.T if err == nil || !strings.Contains(err.Error(), "workspace structured output") { t.Fatal("unqualified bundle admitted", err) } - if _, err := os.Stat(filepath.Join(config.StateDir, "launched")); !os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(testState(config), "launched")); !os.IsNotExist(err) { t.Fatal("unqualified request reached native launch", err) } return @@ -36,14 +36,14 @@ func TestWorkspaceStructuredPreparationQualificationAndFrozenSchema(t *testing.T defer e.Close(context.Background()) req.ExecutionControls.OutputFormat.Schema[0] = ' ' var frozen startRequest - if err := json.Unmarshal(waitPreparationFile(t, filepath.Join(config.StateDir, "prepare.json")), &frozen); err != nil { + if err := json.Unmarshal(waitPreparationFile(t, filepath.Join(testState(config), "prepare.json")), &frozen); err != nil { t.Fatal(err) } if frozen.OutputFormat == nil || string(frozen.OutputFormat.Schema) != schema { t.Fatal("prepared native schema changed with caller memory") } out := make(chan proto.Envelope, 16) - if _, err := e.StartTurn(t.Context(), "run", proto.TextInput("hello"), out); err != nil { + if _, err := e.StartTurn(t.Context(), "run", proto.TurnSettings{}, proto.TextInput("hello"), out); err != nil { t.Fatal(err) } for event := range out { @@ -52,7 +52,7 @@ func TestWorkspaceStructuredPreparationQualificationAndFrozenSchema(t *testing.T } } var started map[string]json.RawMessage - if err := json.Unmarshal(waitPreparationFile(t, filepath.Join(config.StateDir, "start.json")), &started); err != nil || len(started) != 3 || started["output_format"] != nil { + if err := json.Unmarshal(waitPreparationFile(t, filepath.Join(testState(config), "start.json")), &started); err != nil || len(started) != 4 || started["output_format"] != nil { t.Fatal("Start replaced the prepared configuration", err) } }) diff --git a/apps/daemon/internal/agent/claudesdk/workspace_test.go b/apps/daemon/internal/agent/claudesdk/workspace_test.go index de2eac9a1..ccf4f3b9e 100644 --- a/apps/daemon/internal/agent/claudesdk/workspace_test.go +++ b/apps/daemon/internal/agent/claudesdk/workspace_test.go @@ -4,10 +4,13 @@ import ( "encoding/json" "os" "path/filepath" + "slices" "strings" "testing" + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" + harnessconfiguration "github.com/MiniMax-AI/OpenAgentCore/internal/harnessconfig/claudesdk" ) func workspaceFixture(t *testing.T) Config { @@ -17,15 +20,14 @@ func workspaceFixture(t *testing.T) Config { t.Fatal(err) } t.Setenv("OAC_RUNTIME_HOME", root) - for _, name := range []string{"workspace", "home", "state", "scratch", "secrets", "bin", "runtime/dist", "runtime/node_modules"} { + for _, name := range []string{"workspace", "state", "runtime-home", "secrets", "bin", "runtime/dist", "runtime/node_modules"} { if err := os.MkdirAll(filepath.Join(root, name), 0o700); err != nil { t.Fatal(err) } } - config := Config{Node: filepath.Join(root, "bin", "node"), Entrypoint: filepath.Join(root, "runtime", "dist", "main.js"), StateDir: filepath.Join(root, "state"), - Env: []string{"ANTHROPIC_AUTH_TOKEN=selected-provider-fixture", "ANTHROPIC_BASE_URL=https://example.invalid"}, - Workspace: &WorkspaceConfig{Directory: filepath.Join(root, "workspace"), HomeDir: filepath.Join(root, "home"), - ScratchDir: filepath.Join(root, "scratch")}} + config := Config{Node: filepath.Join(root, "bin", "node"), Entrypoint: filepath.Join(root, "runtime", "dist", "main.js"), StateRoot: filepath.Join(root, "state"), + Env: []string{"ANTHROPIC_AUTH_TOKEN=selected-provider-fixture", "ANTHROPIC_BASE_URL=https://example.invalid"}, + RuntimeRoot: filepath.Join(root, "runtime-home"), Workspace: filepath.Join(root, "workspace")} for _, name := range []string{config.Node, config.Entrypoint, filepath.Join(filepath.Dir(config.Entrypoint), "runtime_check.js")} { if err := os.WriteFile(name, nil, 0o700); err != nil { t.Fatal(err) @@ -35,8 +37,8 @@ func workspaceFixture(t *testing.T) Config { } func workspaceRequest() proto.PromptRequestPayload { - return proto.PromptRequestPayload{RunID: "run", Input: proto.TextInput("hello"), DisableSubagents: true, - AgentOptions: map[string]any{"model": "fixture"}} + return proto.PromptRequestPayload{AgentStateKey: testStateKey, RunID: "run", Input: proto.TextInput("hello"), DisableSubagents: true, + Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{}} } func TestWorkspaceTrustedBindingAndEnvironment(t *testing.T) { @@ -47,7 +49,7 @@ func TestWorkspaceTrustedBindingAndEnvironment(t *testing.T) { if err != nil { t.Fatal(err) } - if start.Cwd != config.Workspace.Directory || start.Workspace == nil || start.MCPHTTPServers != nil { + if start.Cwd != config.Workspace || start.Workspace == nil || start.MCPHTTPServers != nil { t.Fatal("trusted binding was not retained") } raw, _ := json.Marshal(start) @@ -65,16 +67,46 @@ func TestWorkspaceTrustedBindingAndEnvironment(t *testing.T) { if _, ok := values["ANTHROPIC_API_KEY"]; ok { t.Fatal("inherited unselected provider credential") } - if values["HOME"] != config.Workspace.HomeDir || values["CLAUDE_CONFIG_DIR"] != config.StateDir || - values["TMPDIR"] != config.Workspace.ScratchDir || values["ANTHROPIC_AUTH_TOKEN"] != "selected-provider-fixture" { + if values["CLAUDE_CONFIG_DIR"] != testState(config) || values["ANTHROPIC_AUTH_TOKEN"] != "selected-provider-fixture" { t.Fatal("explicit runtime environment was not preserved") } - entries, err := os.ReadDir(config.StateDir) + entries, err := os.ReadDir(testState(config)) if err != nil || len(entries) != 0 { t.Fatal("preparation created history or nested scratch") } } +func TestSessionsKeepNativeStateInOwnDirectories(t *testing.T) { + config := workspaceFixture(t) + req := workspaceRequest() + seen := map[string]string{} + for _, key := range []string{"session-a", "session-b"} { + req.AgentStateKey = key + _, env, err := prepareConfiguration(config, req) + if err != nil { + t.Fatal(err) + } + state, _ := agent.StateDir(config.StateRoot, harnessconfiguration.Declaration.Kind, key) + runtime, _ := agent.StateDir(config.RuntimeRoot, harnessconfiguration.Declaration.Kind, key) + for name, want := range map[string]string{"CLAUDE_CONFIG_DIR": filepath.Join(state, "config"), "HOME": filepath.Join(runtime, "home"), "TMPDIR": filepath.Join(runtime, "scratch")} { + if !slices.Contains(env, name+"="+want) { + t.Fatalf("%s for %s is not %s", name, key, want) + } + if prior, ok := seen[want]; ok { + t.Fatalf("%s and %s share %s", prior, key, want) + } + seen[want] = key + } + } + // Without a workspace, every native path, HOME included, is under the key too. + config.Workspace = "" + _, env, err := prepareConfiguration(config, req) + state, _ := agent.StateDir(config.StateRoot, harnessconfiguration.Declaration.Kind, req.AgentStateKey) + if err != nil || !slices.Contains(env, "HOME="+filepath.Join(state, "home")) || !slices.Contains(env, "CLAUDE_CONFIG_DIR="+filepath.Join(state, "config")) { + t.Fatal("environment none keeps native state outside the key", err) + } +} + func TestWorkspaceRejectsConflictsBeforeSideEffects(t *testing.T) { for _, name := range []string{"none", "workspace-root", "mcp", "relative", "missing", "ambient-setting", "duplicate-env", "bad-env"} { t.Run(name, func(t *testing.T) { @@ -84,26 +116,13 @@ func TestWorkspaceRejectsConflictsBeforeSideEffects(t *testing.T) { case "none": req.DisableExecutionEnvironment = true case "workspace-root": - req.LocalEnvironment = &proto.LocalEnvironment{ID: "environment", WorkspaceRoot: config.Workspace.ScratchDir} + req.LocalEnvironment = &proto.LocalEnvironment{ID: "environment", WorkspaceRoot: filepath.Join(config.RuntimeRoot, "scratch")} case "mcp": req.MCPHTTPServers = &[]proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "remote", ServerURL: "https://example.test/mcp"}} case "relative": - config.Workspace.Directory = "relative" + config.Workspace = "relative" case "missing": - config.Workspace.Directory = filepath.Join(config.Workspace.Directory, "missing") - case "overlap": - config.Workspace.ScratchDir = config.StateDir - case "symlink": - alias := filepath.Join(filepath.Dir(config.StateDir), "alias") - if err := os.Symlink(config.Workspace.Directory, alias); err != nil { - t.Fatal(err) - } - config.Workspace.Directory = alias - case "rule-pattern": - config.Workspace.Directory += "*" - if err := os.Mkdir(config.Workspace.Directory, 0o700); err != nil { - t.Fatal(err) - } + config.Workspace = filepath.Join(config.Workspace, "missing") case "ambient-setting": config.Env = append(config.Env, "NODE_OPTIONS=--require=untrusted") case "duplicate-env": @@ -115,8 +134,7 @@ func TestWorkspaceRejectsConflictsBeforeSideEffects(t *testing.T) { if _, _, err := prepareConfiguration(config, req); err == nil { t.Fatal("invalid binding or request accepted") } - entries, err := os.ReadDir(config.StateDir) - if err != nil || len(entries) != 0 { + if _, err := os.Stat(testState(config)); !os.IsNotExist(err) { t.Fatal("rejection created execution state") } }) @@ -139,7 +157,7 @@ func TestWorkspaceRetainsDeclaredFunctions(t *testing.T) { func TestPublicMCPUsesWorkspaceProjectionWithoutCredentialCopy(t *testing.T) { config := workspaceFixture(t) req := workspaceRequest() - req.LocalEnvironment = &proto.LocalEnvironment{WorkspaceRoot: config.Workspace.Directory} + req.LocalEnvironment = &proto.LocalEnvironment{WorkspaceRoot: config.Workspace} token := "vault-selected-canary" tools := []string{"prove"} req.MCPHTTPServers = &[]proto.MCPHTTPServer{{ConnectionOrigin: "environment", ServerLabel: "remote", ServerURL: "https://example.test/mcp", AllowedTools: &tools, Required: true, BearerToken: &token}} @@ -171,3 +189,14 @@ func TestPublicMCPUsesWorkspaceProjectionWithoutCredentialCopy(t *testing.T) { t.Fatal(err) } } + +const testStateKey = "session" + +// testState is the native state directory the fixtures' Session writes to. +func testState(config Config) string { + dir, err := agent.StateDir(config.StateRoot, harnessconfiguration.Declaration.Kind, testStateKey) + if err != nil { + panic(err) + } + return filepath.Join(dir, "config") +} diff --git a/apps/daemon/internal/agent/codex/boundary_independent_qa_test.go b/apps/daemon/internal/agent/codex/boundary_independent_qa_test.go index 4600e547b..253a91741 100644 --- a/apps/daemon/internal/agent/codex/boundary_independent_qa_test.go +++ b/apps/daemon/internal/agent/codex/boundary_independent_qa_test.go @@ -43,7 +43,7 @@ func TestQANativeBoundaryActualLifecycle(t *testing.T) { rejectedCtx, reject := context.WithCancel(ctx) reject() out := make(chan proto.Envelope, 20) - if turn, err := e.StartTurn(rejectedCtx, "rejected", proto.TextInput("answer"), out); turn != nil || err == nil { + if turn, err := e.StartTurn(rejectedCtx, "rejected", proto.TurnSettings{}, proto.TextInput("answer"), out); turn != nil || err == nil { t.Fatal("rejection changed") } if len(qaBoundaryRows(t, logs.String())) != 0 { @@ -53,7 +53,7 @@ func TestQANativeBoundaryActualLifecycle(t *testing.T) { if mode == "cancel" { input = "hold" } - turn, startErr := e.StartTurn(ctx, "qa-run", proto.TextInput(input), out) + turn, startErr := e.StartTurn(ctx, "qa-run", proto.TurnSettings{}, proto.TextInput(input), out) if turn == nil { t.Fatal("missing owner", startErr) } diff --git a/apps/daemon/internal/agent/codex/completion_evidence_test.go b/apps/daemon/internal/agent/codex/completion_evidence_test.go index 3ff12bd38..b1a7f9bfc 100644 --- a/apps/daemon/internal/agent/codex/completion_evidence_test.go +++ b/apps/daemon/internal/agent/codex/completion_evidence_test.go @@ -33,7 +33,7 @@ func TestNativeCompletionEvidence(t *testing.T) { for _, visible := range []bool{true, false} { t.Run(tc.name+map[bool]string{true: " visible", false: " hidden"}[visible], func(t *testing.T) { var logs bytes.Buffer - cfg := defaultSessionConfig(testStateRoot(t)) + cfg := defaultSessionConfig(testStateRoot(t), t.TempDir()) cfg.logger = slog.New(slog.NewJSONHandler(&logs, nil)) out := make(chan proto.Envelope, 64) s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: cfg} diff --git a/apps/daemon/internal/agent/codex/declaration.go b/apps/daemon/internal/agent/codex/declaration.go index ff96549d3..c580a1f24 100644 --- a/apps/daemon/internal/agent/codex/declaration.go +++ b/apps/daemon/internal/agent/codex/declaration.go @@ -33,7 +33,7 @@ func discoverWithCheck(parent context.Context, options agent.DiscoveryOptions, i for _, capability := range []*proto.CapabilitySupport{&caps.LocalEnvironment, &caps.WorkspaceReadPreparation, &caps.WorkspaceOutputExport, &caps.RetainedNativeHistory} { agent.Narrow(capability, local) } - runtime.Executor = NewExecutorFactory(options.StateRoot) + runtime.Executor = NewExecutorFactory(options.StateRoot, options.RuntimeRoot) fmt.Fprintf(options.Stdout, "Codex preflight ok (%s)\n", version) return runtime } diff --git a/apps/daemon/internal/agent/codex/environment_transport_test.go b/apps/daemon/internal/agent/codex/environment_transport_test.go index 36ed0e9e3..4dc578c14 100644 --- a/apps/daemon/internal/agent/codex/environment_transport_test.go +++ b/apps/daemon/internal/agent/codex/environment_transport_test.go @@ -19,7 +19,7 @@ func TestReadOnlyPreparationRejectedBeforeNativeSetup(t *testing.T) { if len(preparationFrames(t, root)) != 0 { t.Fatal("read-only request started native child") } - if _, err := os.Stat(filepath.Join(root, "daemon", "agent-sessions")); !os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(root, "runtime", "codex")); !os.IsNotExist(err) { t.Fatal("read-only request created native state", err) } } @@ -41,7 +41,7 @@ func TestNativeTransportEnvironmentRejectedBeforeState(t *testing.T) { if len(preparationFrames(t, root)) != 0 { t.Fatal("transport override started native process") } - if _, err := os.Stat(filepath.Join(root, "daemon", "agent-sessions")); !os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(root, "runtime", "codex")); !os.IsNotExist(err) { t.Fatal("transport override created state", err) } }) diff --git a/apps/daemon/internal/agent/codex/error_classification_test.go b/apps/daemon/internal/agent/codex/error_classification_test.go index f9ccf642d..eb547b124 100644 --- a/apps/daemon/internal/agent/codex/error_classification_test.go +++ b/apps/daemon/internal/agent/codex/error_classification_test.go @@ -50,7 +50,7 @@ func TestClassificationOnlyFromRootTerminalError(t *testing.T) { for _, mode := range []string{"failed", "recovered", "notification-only"} { t.Run(mode, func(t *testing.T) { out := make(chan proto.Envelope, 16) - s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t)), rpc: NewJSONRPCClient(JSONRPCConfig{})} + s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), rpc: NewJSONRPCClient(JSONRPCConfig{})} s.registerHandlers() s.setThreadID("root") scopeNotification(t, s, "turn/started", `{"threadId":"root","turn":{"id":"turn"}}`) @@ -135,7 +135,7 @@ func TestProviderRejectionClassifiedOnce(t *testing.T) { } } out := make(chan proto.Envelope, 16) - s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t)), rpc: NewJSONRPCClient(JSONRPCConfig{})} + s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), rpc: NewJSONRPCClient(JSONRPCConfig{})} s.registerHandlers() s.setThreadID("root") turnError, _ := json.Marshal(TurnError{Message: body, CodexErrorInfo: json.RawMessage(`"other"`)}) diff --git a/apps/daemon/internal/agent/codex/execution_controls_test.go b/apps/daemon/internal/agent/codex/execution_controls_test.go index 12d072865..8bfd0e6ac 100644 --- a/apps/daemon/internal/agent/codex/execution_controls_test.go +++ b/apps/daemon/internal/agent/codex/execution_controls_test.go @@ -2,6 +2,7 @@ package codex import ( "reflect" + "slices" "testing" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" @@ -28,11 +29,10 @@ func TestExecutionControlsMapToNativeSettings(t *testing.T) { {"tools.web_search.location.city", `"Paris"`}, {"tools.web_search.location.timezone", `"Europe/Paris"`}}}, {"empty domain list stays distinct from null", &proto.ExecutionControls{WebSearch: &proto.WebSearchControl{Mode: "disabled", ContextSize: "low", AllowedDomains: []string{}}}, [][2]string{{"web_search", `"disabled"`}, {"tools.web_search.context_size", `"low"`}, {"tools.web_search.allowed_domains", `[]`}}}, - {"reasoning and tier", &proto.ExecutionControls{ReasoningEffort: "max", ReasoningSummary: "concise", ServiceTier: "priority"}, - [][2]string{{"model_reasoning_effort", `"max"`}, {"model_reasoning_summary", `"concise"`}, {"service_tier", `"priority"`}}}, + {"reasoning summary", &proto.ExecutionControls{ReasoningSummary: "concise"}, [][2]string{{"model_reasoning_summary", `"concise"`}}}, } { t.Run(tc.name, func(t *testing.T) { - plan, err := BuildSessionPlan(testStateRoot(t), "state", map[string]any{"model": "test-model"}, tc.controls) + plan, err := BuildSessionPlan(testStateRoot(t), "state", map[string]any{}, proto.TurnSettings{}, tc.controls) if err != nil { t.Fatal(err) } @@ -55,11 +55,23 @@ func TestExecutionControlsRejectUndeclaredValues(t *testing.T) { t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) for _, controls := range []proto.ExecutionControls{ {WebSearch: &proto.WebSearchControl{Mode: "indexed", ContextSize: "medium"}}, - {TextVerbosity: "invalid"}, {ReasoningEffort: "ultra"}, {ReasoningSummary: "none"}, {ServiceTier: "scale"}, + {TextVerbosity: "invalid"}, {ReasoningSummary: "none"}, } { - if plan, err := BuildSessionPlan(testStateRoot(t), "state", nil, &controls); err == nil { + if plan, err := BuildSessionPlan(testStateRoot(t), "state", nil, proto.TurnSettings{}, &controls); err == nil { plan.Cleanup() t.Fatal("undeclared controls accepted", controls) } } } + +func TestTurnSettingsReachNativeConfig(t *testing.T) { + t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) + plan, err := BuildSessionPlan(testStateRoot(t), "state", nil, proto.TurnSettings{Model: "m", ReasoningEffort: "max", ServiceTier: "priority"}, nil) + if err != nil { + t.Fatal(err) + } + plan.Cleanup() + if plan.Model != "m" || !slices.Contains(plan.ExtraConfig, [2]string{"model_reasoning_effort", `"max"`}) || !slices.Contains(plan.ExtraConfig, [2]string{"service_tier", `"priority"`}) { + t.Fatalf("turn settings not applied: %v", plan.ExtraConfig) + } +} diff --git a/apps/daemon/internal/agent/codex/executor.go b/apps/daemon/internal/agent/codex/executor.go index 0b2ca1a6a..26406677f 100644 --- a/apps/daemon/internal/agent/codex/executor.go +++ b/apps/daemon/internal/agent/codex/executor.go @@ -21,8 +21,8 @@ type Executor struct { closeMu sync.Mutex } -func PrepareExecutor(ctx context.Context, stateRoot string, req proto.PromptRequestPayload) (agent.Executor, error) { - return newExecutor(ctx, req, defaultSessionConfig(stateRoot)) +func PrepareExecutor(ctx context.Context, stateRoot, runtimeRoot string, req proto.PromptRequestPayload) (agent.Executor, error) { + return newExecutor(ctx, req, defaultSessionConfig(stateRoot, runtimeRoot)) } func newExecutor(ctx context.Context, req proto.PromptRequestPayload, cfg sessionConfig) (*Executor, error) { @@ -40,7 +40,7 @@ func newExecutor(ctx context.Context, req proto.PromptRequestPayload, cfg sessio return &Executor{prepared: p}, nil } -func (e *Executor) StartTurn(ctx context.Context, runID string, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { +func (e *Executor) StartTurn(ctx context.Context, runID string, turn proto.TurnSettings, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { entered := time.Now() if out == nil || strings.TrimSpace(runID) == "" || input.Validate() != nil { return nil, errors.New("codex: start requires a run identity, input and output") @@ -97,7 +97,7 @@ func (e *Executor) StartTurn(ctx context.Context, runID string, input proto.Mess req := proto.PromptRequestPayload{RunID: runID, Input: input, AgentSessionID: e.prepared.resumeID, RequireExistingNativeSession: e.prepared.requireExistingNativeSession} // Ownership precedes any native submission. Even an uncertain start returns the // exact Turn so its caller can await settlement without replaying the input. - err := s.startNative(ctx, e.prepared.plan, req) + err := s.startNative(ctx, e.prepared.plan, turn, req) if err != nil { s.emitTerminal("codex: native start failed", true) s.finishAfterTerminal() @@ -173,8 +173,8 @@ func (e *Executor) Close(ctx context.Context) error { var _ agent.Executor = (*Executor)(nil) -func NewExecutorFactory(stateRoot string) agent.ExecutorFactory { +func NewExecutorFactory(stateRoot, runtimeRoot string) agent.ExecutorFactory { return func(ctx context.Context, req proto.PromptRequestPayload) (agent.Executor, error) { - return PrepareExecutor(ctx, stateRoot, req) + return PrepareExecutor(ctx, stateRoot, runtimeRoot, req) } } diff --git a/apps/daemon/internal/agent/codex/executor_test.go b/apps/daemon/internal/agent/codex/executor_test.go index 1f1696d6e..aa1f7da80 100644 --- a/apps/daemon/internal/agent/codex/executor_test.go +++ b/apps/daemon/internal/agent/codex/executor_test.go @@ -84,7 +84,7 @@ func TestExecutorNormalTurnsKeepProcessAndThread(t *testing.T) { var previous agent.Turn for _, id := range []string{"one", "two"} { out := make(chan proto.Envelope, 20) - turn, err := e.StartTurn(t.Context(), id, proto.TextInput("answer"), out) + turn, err := e.StartTurn(t.Context(), id, proto.TurnSettings{}, proto.TextInput("answer"), out) if err != nil { t.Fatal(err) } @@ -126,11 +126,11 @@ func TestExecutorFreezesPreparedConfiguration(t *testing.T) { assertPreparationOnly(t, root) cwd := e.prepared.plan.Cwd // Caller-owned data cannot revise the prepared native configuration. - req.AgentOptions["model"] = "different-model" + req.Turn.Model = "different-model" req.AgentSessionID = "different-thread" copy(req.FunctionTools[0].Parameters, strings.ReplaceAll(string(req.FunctionTools[0].Parameters), "integer", "boolean")) out := make(chan proto.Envelope, 20) - turn, err := e.StartTurn(t.Context(), "actual-run", proto.TextInput("actual prompt"), out) + turn, err := e.StartTurn(t.Context(), "actual-run", proto.TurnSettings{}, proto.TextInput("actual prompt"), out) if err != nil { t.Fatal(err) } @@ -189,7 +189,7 @@ func TestExecutorUnavailableOwnerStartsNoTurn(t *testing.T) { t.Fatal(err) } out := make(chan proto.Envelope, 1) - if turn, err := e.StartTurn(t.Context(), "late-run", proto.TextInput("must not start"), out); turn != nil || err == nil { + if turn, err := e.StartTurn(t.Context(), "late-run", proto.TurnSettings{}, proto.TextInput("must not start"), out); turn != nil || err == nil { t.Fatal("unavailable executor started a Turn", err) } if len(out) != 0 { @@ -203,11 +203,11 @@ func TestExecutorUnavailableOwnerStartsNoTurn(t *testing.T) { func TestExecutorCancellationSettlesThenReuses(t *testing.T) { e, root := executorFixture(t, "complete") out := make(chan proto.Envelope, 20) - first, err := e.StartTurn(t.Context(), "cancel", proto.TextInput("hold"), out) + first, err := e.StartTurn(t.Context(), "cancel", proto.TurnSettings{}, proto.TextInput("hold"), out) if err != nil { t.Fatal(err) } - if _, err := e.StartTurn(t.Context(), "overlap", proto.TextInput("answer"), make(chan proto.Envelope, 20)); err == nil { + if _, err := e.StartTurn(t.Context(), "overlap", proto.TurnSettings{}, proto.TextInput("answer"), make(chan proto.Envelope, 20)); err == nil { t.Fatal("overlapping turn admitted") } ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) @@ -219,7 +219,7 @@ func TestExecutorCancellationSettlesThenReuses(t *testing.T) { t.Fatal("cancelled healthy executor unavailable") } secondOut := make(chan proto.Envelope, 20) - second, err := e.StartTurn(t.Context(), "next", proto.TextInput("hold"), secondOut) + second, err := e.StartTurn(t.Context(), "next", proto.TurnSettings{}, proto.TextInput("hold"), secondOut) if err != nil { t.Fatal(err) } @@ -250,7 +250,7 @@ func TestExecutorStartErrorsRetainExactOwnership(t *testing.T) { out := make(chan proto.Envelope, 20) ctx, cancel := context.WithCancel(t.Context()) cancel() - turn, err := e.StartTurn(ctx, "before", proto.TextInput("answer"), out) + turn, err := e.StartTurn(ctx, "before", proto.TurnSettings{}, proto.TextInput("answer"), out) if turn != nil || !errors.Is(err, context.Canceled) { t.Fatal(turn, err) } @@ -259,7 +259,7 @@ func TestExecutorStartErrorsRetainExactOwnership(t *testing.T) { t.Fatal("pre-admission output was retained or closed") default: } - turn, err = e.StartTurn(t.Context(), "after", proto.TextInput("answer"), out) + turn, err = e.StartTurn(t.Context(), "after", proto.TurnSettings{}, proto.TextInput("answer"), out) if turn == nil || err == nil { t.Fatal("uncertain submission lost owner", err) } @@ -313,7 +313,7 @@ func TestExecutorCloseRetainsPlanUntilReaped(t *testing.T) { func TestExecutorCloseSeparatesTurnFailureFromResourceCleanup(t *testing.T) { e, root := executorFixture(t, "interrupt-error") out := make(chan proto.Envelope, 20) - turn, err := e.StartTurn(t.Context(), "cancel-failure", proto.TextInput("hold"), out) + turn, err := e.StartTurn(t.Context(), "cancel-failure", proto.TurnSettings{}, proto.TextInput("hold"), out) if err != nil { t.Fatal(err) } @@ -339,7 +339,7 @@ func TestExecutorCloseSeparatesTurnFailureFromResourceCleanup(t *testing.T) { func TestExecutorCloseTerminatesAfterMissingCancellationTerminal(t *testing.T) { e, root := executorFixture(t, "interrupt-no-terminal") out := make(chan proto.Envelope, 20) - turn, err := e.StartTurn(t.Context(), "missing-terminal", proto.TextInput("hold"), out) + turn, err := e.StartTurn(t.Context(), "missing-terminal", proto.TurnSettings{}, proto.TextInput("hold"), out) if err != nil { t.Fatal(err) } @@ -372,3 +372,40 @@ func TestExecutorCloseTerminatesAfterMissingCancellationTerminal(t *testing.T) { t.Fatal("original cancellation waiter was abandoned") } } + +func TestTurnStartCarriesTheTurnSettings(t *testing.T) { + e, root := executorFixture(t, "complete") + turns := []proto.TurnSettings{ + {Model: "one", ReasoningEffort: "high", ServiceTier: "priority"}, + {Model: "two", Review: "auto_review"}, + } + for i, settings := range turns { + out := make(chan proto.Envelope, 20) + turn, err := e.StartTurn(t.Context(), "run", settings, proto.TextInput("answer"), out) + if err != nil { + t.Fatal(err) + } + awaitExecutorTurn(t, turn, out) + var sent []string + for _, frame := range preparationFrames(t, root) { + if frame.Method == "turn/start" { + var p struct { + Model, Effort, ApprovalPolicy, ApprovalsReviewer string + ServiceTier *string + } + if err := json.Unmarshal(frame.Params, &p); err != nil { + t.Fatal(err) + } + tier := "null" + if p.ServiceTier != nil { + tier = *p.ServiceTier + } + sent = append(sent, strings.Join([]string{p.Model, p.Effort, tier, p.ApprovalPolicy, p.ApprovalsReviewer}, " ")) + } + } + want := []string{"one high priority never user", "two null on-request auto_review"} + if len(sent) != i+1 || sent[i] != want[i] { + t.Fatalf("turn/start %d = %q, want %q", i, sent, want[i]) + } + } +} diff --git a/apps/daemon/internal/agent/codex/functions_test.go b/apps/daemon/internal/agent/codex/functions_test.go index 6019a1680..07eb4f540 100644 --- a/apps/daemon/internal/agent/codex/functions_test.go +++ b/apps/daemon/internal/agent/codex/functions_test.go @@ -211,3 +211,21 @@ func TestEndedChildTurnWithdrawsItsPendingCall(t *testing.T) { default: } } + +func TestApprovalEscalationsAreDeniedWithMethodNotFound(t *testing.T) { + tc, srv, cleanup := NewTestClient() + defer cleanup() + newFunctionTestSession(tc.JSONRPCClient) + if err := SendServerRequest(srv, "approval", "item/commandExecution/requestApproval", map[string]any{"threadId": "thread"}); err != nil { + t.Fatal(err) + } + var reply struct { + ID string `json:"id"` + Error struct { + Code int `json:"code"` + } `json:"error"` + } + if err := json.NewDecoder(srv.FromClient).Decode(&reply); err != nil || reply.ID != "approval" || reply.Error.Code != -32601 { + t.Fatal(reply, err) + } +} diff --git a/apps/daemon/internal/agent/codex/harness_config_test.go b/apps/daemon/internal/agent/codex/harness_config_test.go index 7b9150ccc..df345f9f9 100644 --- a/apps/daemon/internal/agent/codex/harness_config_test.go +++ b/apps/daemon/internal/agent/codex/harness_config_test.go @@ -15,9 +15,8 @@ import ( func TestReasoningEffortAppliedWithoutChangingProvider(t *testing.T) { t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) plan, err := BuildSessionPlan(testStateRoot(t), "native-config", map[string]any{ - "model": "fixture", "model_provider": map[string]any{"base_url": "https://provider.invalid/v1", "protocol": "responses", "api_key": "test-key"}, - }, &proto.ExecutionControls{ReasoningEffort: "max"}) + }, proto.TurnSettings{Model: "fixture", ReasoningEffort: "max"}, nil) if err != nil { t.Fatal(err) } @@ -28,14 +27,14 @@ func TestReasoningEffortAppliedWithoutChangingProvider(t *testing.T) { } func TestReasoningEffortHasNoHarnessConfigHome(t *testing.T) { - _, err := BuildSessionPlan(testStateRoot(t), "", map[string]any{"harness_config": map[string]any{"model_reasoning_effort": "high"}}, nil) + _, err := BuildSessionPlan(testStateRoot(t), "", map[string]any{"harness_config": map[string]any{"model_reasoning_effort": "high"}}, proto.TurnSettings{}, nil) if err != harnessconfig.ErrHarnessConfig { t.Fatalf("duplicate effort home accepted: %v", err) } } func TestHarnessConfigConflictFailsBeforePreparation(t *testing.T) { - _, err := BuildSessionPlan(testStateRoot(t), "", map[string]any{"harness_config": map[string]any{"model_provider": "bypass"}}, nil) + _, err := BuildSessionPlan(testStateRoot(t), "", map[string]any{"harness_config": map[string]any{"model_provider": "bypass"}}, proto.TurnSettings{}, nil) if err != harnessconfig.ErrHarnessConfig { t.Fatalf("configuration must fail before filesystem preparation: %v", err) } @@ -47,8 +46,8 @@ func TestNativeTurnsCarryNoCollaborationMode(t *testing.T) { req, cfg, root := preparationFixture(t) t.Setenv("OAC_TEST_EXECUTOR_MODE", "complete") req.AgentSessionID = resumeID - controls := &proto.ExecutionControls{TextVerbosity: "medium", ReasoningEffort: "high"} - req.ExecutionControls = controls + req.ExecutionControls = &proto.ExecutionControls{TextVerbosity: "medium"} + req.Turn.ReasoningEffort = "high" ownerCtx, cancelOwner := context.WithCancel(context.Background()) t.Cleanup(cancelOwner) e, err := newExecutor(ownerCtx, req, cfg) @@ -62,10 +61,9 @@ func TestNativeTurnsCarryNoCollaborationMode(t *testing.T) { t.Error(err) } }) - controls.ReasoningEffort = "low" for _, id := range []string{"one", "two"} { out := make(chan proto.Envelope, 20) - turn, err := e.StartTurn(t.Context(), id, proto.TextInput("answer"), out) + turn, err := e.StartTurn(t.Context(), id, proto.TurnSettings{}, proto.TextInput("answer"), out) if err != nil { t.Fatal(err) } @@ -117,7 +115,7 @@ func TestOutputSchemaReachesEveryNativeTurn(t *testing.T) { }) for _, id := range []string{"one", "two"} { out := make(chan proto.Envelope, 20) - turn, err := e.StartTurn(t.Context(), id, proto.TextInput("answer"), out) + turn, err := e.StartTurn(t.Context(), id, proto.TurnSettings{}, proto.TextInput("answer"), out) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/codex/mcp_config_test.go b/apps/daemon/internal/agent/codex/mcp_config_test.go index c55ca481a..a545c3d2f 100644 --- a/apps/daemon/internal/agent/codex/mcp_config_test.go +++ b/apps/daemon/internal/agent/codex/mcp_config_test.go @@ -73,11 +73,11 @@ func TestWriteCodexMCPConfig_EmitsStreamableHTTPURL(t *testing.T) { // TestWriteCodexMCPConfig_FreshHomeDropsStaleEntries documents the // "fresh entries only" guarantee: callers allocate a brand-new -// CODEX_HOME per prompt (BuildSessionPlan does this via allocCodexHome +// CODEX_HOME per prompt (BuildSessionPlan does this via sessionDir // + plan.Cleanup), so the previous run's mcp_servers can't leak. // // writeCodexMCPConfig itself is APPEND semantics now — the truncation -// guarantee lives in allocCodexHome's RemoveAll, not in the writer. +// guarantee lives in sessionDir's RemoveAll, not in the writer. // Test that workflow explicitly so a future refactor that breaks the // fresh-home contract fails here. func TestWriteCodexMCPConfig_FreshHomeDropsStaleEntries(t *testing.T) { diff --git a/apps/daemon/internal/agent/codex/mcp_http_bearer_test.go b/apps/daemon/internal/agent/codex/mcp_http_bearer_test.go index c7dcaf0b5..da0627df2 100644 --- a/apps/daemon/internal/agent/codex/mcp_http_bearer_test.go +++ b/apps/daemon/internal/agent/codex/mcp_http_bearer_test.go @@ -22,7 +22,7 @@ func TestMCPHTTPBearerPlanSeparatesServersAndProcesses(t *testing.T) { req := proto.PromptRequestPayload{AgentStateKey: "retained-mcp", DisableExecutionEnvironment: true, MCPHTTPServers: &servers} seen := map[string]bool{} for range 2 { - plan, _, err := prepareSessionPlan(t.Context(), req, defaultSessionConfig(testStateRoot(t))) + plan, _, err := prepareSessionPlan(t.Context(), req, defaultSessionConfig(testStateRoot(t), t.TempDir())) if err != nil { t.Fatal(err) } @@ -58,7 +58,7 @@ func TestMCPHTTPBearerRejectsInvalidTokensWithoutPersistence(t *testing.T) { for _, token := range []string{"", "=", " has-space", "has-space ", "has space", "line\r\ninjection", "nul\x00byte", "opaque中文", "middle=padding", "punctuation:invalid"} { servers := []proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "tools", ServerURL: "https://tools.example/mcp", BearerToken: &token}} req := proto.PromptRequestPayload{AgentStateKey: "invalid-bearer", DisableExecutionEnvironment: true, MCPHTTPServers: &servers} - if _, _, err := prepareSessionPlan(t.Context(), req, defaultSessionConfig(testStateRoot(t))); err == nil || err.Error() != "invalid HTTPS MCP bearer credential" { + if _, _, err := prepareSessionPlan(t.Context(), req, defaultSessionConfig(testStateRoot(t), t.TempDir())); err == nil || err.Error() != "invalid HTTPS MCP bearer credential" { t.Fatal("invalid bearer value accepted or unsafe error returned") } } diff --git a/apps/daemon/internal/agent/codex/mcp_http_preflight_test.go b/apps/daemon/internal/agent/codex/mcp_http_preflight_test.go index 297725749..285a2c080 100644 --- a/apps/daemon/internal/agent/codex/mcp_http_preflight_test.go +++ b/apps/daemon/internal/agent/codex/mcp_http_preflight_test.go @@ -130,7 +130,7 @@ func TestPublicMCPHTTPPreparationChecksBeforeNewAndResumedThread(t *testing.T) { for _, mode := range []string{"new", "resume", "extra server", "reject url", "reject bearer reference"} { t.Run(mode, func(t *testing.T) { req, cfg, root := preparationFixture(t) - req.AgentOptions = map[string]any{"model": "fixture-model"} + req.Turn.Model = "fixture-model" servers := []proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "docs", ServerURL: "https://docs.example/mcp"}} if mode == "reject bearer reference" { token := "synthetic-private-bearer" @@ -174,12 +174,12 @@ func TestPublicMCPHTTPPreparationChecksBeforeNewAndResumedThread(t *testing.T) { t.Fatal(err) } assertPreparationOnly(t, root) - home, err := allocCodexHome(testStateRoot(t), req.AgentStateKey) + home, err := sessionDir(testStateRoot(t), req.AgentStateKey) if err != nil { t.Fatal(err) } out := make(chan proto.Envelope, 20) - turn, err := e.StartTurn(t.Context(), "actual-run", proto.TextInput("actual prompt"), out) + turn, err := e.StartTurn(t.Context(), "actual-run", proto.TurnSettings{}, proto.TextInput("actual prompt"), out) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/codex/mcp_http_test.go b/apps/daemon/internal/agent/codex/mcp_http_test.go index 75610d9fa..585953866 100644 --- a/apps/daemon/internal/agent/codex/mcp_http_test.go +++ b/apps/daemon/internal/agent/codex/mcp_http_test.go @@ -21,7 +21,7 @@ func TestPublicMCPHTTPPlanOwnsConfigurationAndPreservesHistory(t *testing.T) { {ConnectionOrigin: "service", ServerLabel: "blocked", ServerURL: "http://127.0.0.1:12345/mcp", AllowedTools: &denyAll}, } req := proto.PromptRequestPayload{AgentStateKey: "public-mcp", DisableExecutionEnvironment: true, MCPHTTPServers: &servers} - plan, _, err := prepareSessionPlan(t.Context(), req, defaultSessionConfig(testStateRoot(t))) + plan, _, err := prepareSessionPlan(t.Context(), req, defaultSessionConfig(testStateRoot(t), t.TempDir())) if err != nil { t.Fatal(err) } @@ -31,7 +31,7 @@ func TestPublicMCPHTTPPlanOwnsConfigurationAndPreservesHistory(t *testing.T) { !slices.Contains(plan.ExtraConfig, [2]string{"shell_environment_policy.exclude", `["OAC_RUNTIME_MCP_*"]`}) { t.Fatal("native profile kept only credential isolation") } - home, err := allocCodexHome(testStateRoot(t), req.AgentStateKey) + home, err := sessionDir(testStateRoot(t), req.AgentStateKey) if err != nil { t.Fatal(err) } @@ -56,7 +56,7 @@ func TestPublicMCPHTTPPlanOwnsConfigurationAndPreservesHistory(t *testing.T) { t.Fatal(err) } servers = []proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "replacement", ServerURL: "https://new.example/mcp"}} - second, _, err := prepareSessionPlan(t.Context(), req, defaultSessionConfig(testStateRoot(t))) + second, _, err := prepareSessionPlan(t.Context(), req, defaultSessionConfig(testStateRoot(t), t.TempDir())) if err != nil { t.Fatal(err) } @@ -91,7 +91,7 @@ func TestPublicMCPHTTPRejectsInvalidProfileAndStoredCredentials(t *testing.T) { } } t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) - home, err := allocCodexHome(testStateRoot(t), "credentials") + home, err := sessionDir(testStateRoot(t), "credentials") if err != nil { t.Fatal(err) } @@ -101,7 +101,7 @@ func TestPublicMCPHTTPRejectsInvalidProfileAndStoredCredentials(t *testing.T) { t.Fatal(err) } req := proto.PromptRequestPayload{AgentStateKey: "credentials", DisableExecutionEnvironment: true, MCPHTTPServers: &valid} - if _, _, err := prepareSessionPlan(t.Context(), req, defaultSessionConfig(testStateRoot(t))); err == nil { + if _, _, err := prepareSessionPlan(t.Context(), req, defaultSessionConfig(testStateRoot(t), t.TempDir())); err == nil { t.Fatal("existing MCP credentials accepted") } if after, err := os.ReadFile(path); err != nil || !reflect.DeepEqual(after, stored) { diff --git a/apps/daemon/internal/agent/codex/mcp_required_test.go b/apps/daemon/internal/agent/codex/mcp_required_test.go index 4dc500470..9f5b7f90d 100644 --- a/apps/daemon/internal/agent/codex/mcp_required_test.go +++ b/apps/daemon/internal/agent/codex/mcp_required_test.go @@ -17,7 +17,7 @@ func TestRequiredMCPWaitsForNativeThreadAndNeverRestartsFailedResume(t *testing. for _, mode := range []string{"new ready", "new failed", "resume ready", "resume failed"} { t.Run(mode, func(t *testing.T) { req, cfg, root := preparationFixture(t) - req.AgentOptions = map[string]any{"model": "fixture-model"} + req.Turn.Model = "fixture-model" servers := []proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "docs", ServerURL: "https://docs.example/mcp", Required: true}} req.MCPHTTPServers = &servers method := "thread/start" @@ -45,7 +45,7 @@ func TestRequiredMCPWaitsForNativeThreadAndNeverRestartsFailedResume(t *testing. } result := make(chan started, 1) go func() { - turn, err := e.StartTurn(t.Context(), "required-run", proto.TextInput("actual prompt"), out) + turn, err := e.StartTurn(t.Context(), "required-run", proto.TurnSettings{}, proto.TextInput("actual prompt"), out) result <- started{turn, err} }() waitPreparationMethod(t, root, method) diff --git a/apps/daemon/internal/agent/codex/model_headers_native_test.go b/apps/daemon/internal/agent/codex/model_headers_native_test.go index 8d45c6e5d..b41059455 100644 --- a/apps/daemon/internal/agent/codex/model_headers_native_test.go +++ b/apps/daemon/internal/agent/codex/model_headers_native_test.go @@ -53,10 +53,10 @@ func TestNativeModelHeadersEveryTurn(t *testing.T) { for _, name := range []string{"CODEX_EXEC_SERVER_URL", "CODEX_EXEC_SERVER_NOISE_REGISTRY_URL", "CODEX_EXEC_SERVER_NOISE_ENVIRONMENT_ID", "CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN"} { t.Setenv(name, "") } - cfg := defaultSessionConfig(testStateRoot(t)) + cfg := defaultSessionConfig(testStateRoot(t), t.TempDir()) cfg.codexBinary = binary cfg.logger = slog.New(slog.DiscardHandler) - req := proto.PromptRequestPayload{AgentKind: "codex", AgentStateKey: "header-native", DisableExecutionEnvironment: true, DisableSubagents: true, FunctionTools: []proto.FunctionTool{{Name: "lookup", Description: "Fixture", Parameters: json.RawMessage(`{"type":"object","properties":{}}`)}}, AgentOptions: map[string]any{"model": "gpt-5.5", "model_provider": map[string]any{"protocol": "responses", "base_url": server.URL + "/v1", "api_key": "fixture", "headers": map[string]string{"X-Sandbase-Benefit": "daily-free", "X-Literal": "${unchanged}:value"}}}} + req := proto.PromptRequestPayload{AgentKind: "codex", AgentStateKey: "header-native", DisableExecutionEnvironment: true, DisableSubagents: true, FunctionTools: []proto.FunctionTool{{Name: "lookup", Description: "Fixture", Parameters: json.RawMessage(`{"type":"object","properties":{}}`)}}, Turn: proto.TurnSettings{Model: "gpt-5.5"}, AgentOptions: map[string]any{"model_provider": map[string]any{"protocol": "responses", "base_url": server.URL + "/v1", "api_key": "fixture", "headers": map[string]string{"X-Sandbase-Benefit": "daily-free", "X-Literal": "${unchanged}:value"}}}} ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second) defer cancel() e, err := newExecutor(ctx, req, cfg) @@ -66,7 +66,7 @@ func TestNativeModelHeadersEveryTurn(t *testing.T) { defer func() { _ = e.Close(context.Background()) }() for i := 0; i < 3; i++ { output := make(chan proto.Envelope, 256) - turn, err := e.StartTurn(ctx, fmt.Sprintf("turn-%d", i), proto.TextInput("Reply HEADER-OK."), output) + turn, err := e.StartTurn(ctx, fmt.Sprintf("turn-%d", i), req.Turn, proto.TextInput("Reply HEADER-OK."), output) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/codex/model_route_test.go b/apps/daemon/internal/agent/codex/model_route_test.go index 74ad45684..92aebb079 100644 --- a/apps/daemon/internal/agent/codex/model_route_test.go +++ b/apps/daemon/internal/agent/codex/model_route_test.go @@ -1,6 +1,7 @@ package codex import ( + "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" "reflect" "slices" "strings" @@ -12,7 +13,7 @@ func TestPlanRejectsNonNativeFrozenProvider(t *testing.T) { for _, protocol := range []string{"anthropic", "chat_completions"} { t.Run(protocol, func(t *testing.T) { provider := map[string]any{"protocol": protocol, "base_url": "https://model.invalid/v1", "api_key": "private-sentinel"} - plan, err := BuildSessionPlan(testStateRoot(t), "frozen-state", map[string]any{"model": "frozen-model", "model_provider": provider}, nil) + plan, err := BuildSessionPlan(testStateRoot(t), "frozen-state", map[string]any{"model_provider": provider}, proto.TurnSettings{Model: "frozen-model"}, nil) if plan.Cleanup != nil { plan.Cleanup() } @@ -31,7 +32,7 @@ func TestPlanRejectsIncompleteExplicitProvider(t *testing.T) { {"model": "chosen", "model_provider": nil}, {"model_provider": map[string]any{"protocol": "responses", "base_url": "https://model.example/v1", "api_key": "fixture"}}, } { - if _, err := BuildSessionPlan(testStateRoot(t), "state", options, nil); err == nil { + if _, err := BuildSessionPlan(testStateRoot(t), "state", options, proto.TurnSettings{}, nil); err == nil { t.Fatal("explicit provider fell back to native defaults") } } @@ -40,13 +41,13 @@ func TestPlanRejectsIncompleteExplicitProvider(t *testing.T) { func TestPlanMapsTheContextWindowNatively(t *testing.T) { t.Setenv("HOME", t.TempDir()) provider := map[string]any{"protocol": "responses", "base_url": "https://model.example/v1", "api_key": "fixture", "context_window": 64000} - plan, err := BuildSessionPlan(testStateRoot(t), "limits", map[string]any{"model": "m", "model_provider": provider}, nil) + plan, err := BuildSessionPlan(testStateRoot(t), "limits", map[string]any{"model_provider": provider}, proto.TurnSettings{Model: "m"}, nil) if err != nil || !slices.Contains(plan.ExtraConfig, [2]string{"model_context_window", "64000"}) { t.Fatalf("context window not native: %v %v", plan.ExtraConfig, err) } plan.Cleanup() provider["max_output_tokens"] = 4096 - if _, err := BuildSessionPlan(testStateRoot(t), "limits", map[string]any{"model": "m", "model_provider": provider}, nil); err == nil { + if _, err := BuildSessionPlan(testStateRoot(t), "limits", map[string]any{"model_provider": provider}, proto.TurnSettings{Model: "m"}, nil); err == nil { t.Fatal("max_output_tokens without a native home accepted") } } diff --git a/apps/daemon/internal/agent/codex/native_boundary_test.go b/apps/daemon/internal/agent/codex/native_boundary_test.go index eae6229d2..b08b235dc 100644 --- a/apps/daemon/internal/agent/codex/native_boundary_test.go +++ b/apps/daemon/internal/agent/codex/native_boundary_test.go @@ -169,7 +169,7 @@ func TestNativeBoundaryActualThreadResolution(t *testing.T) { } calls <- append(methods, method) }() - err := s.startNative(context.Background(), SessionPlan{Model: "fixture"}, req) + err := s.startNative(context.Background(), SessionPlan{Model: "fixture"}, proto.TurnSettings{Model: "fixture"}, req) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/codex/native_state_identity_test.go b/apps/daemon/internal/agent/codex/native_state_identity_test.go index ff434d5aa..8e6721908 100644 --- a/apps/daemon/internal/agent/codex/native_state_identity_test.go +++ b/apps/daemon/internal/agent/codex/native_state_identity_test.go @@ -54,11 +54,11 @@ func TestNativeStateIdentitySurvivesExecutorRestart(t *testing.T) { t.Setenv(name, "") } root := testStateRoot(t) - cfg := defaultSessionConfig(root) + cfg := defaultSessionConfig(root, t.TempDir()) cfg.codexBinary = binary cfg.logger = slog.New(slog.DiscardHandler) id := "e4dd7710-9dab-449d-b6ec-ab0f74d05c2a" - req := proto.PromptRequestPayload{AgentKind: "codex", AgentStateKey: "agents-api-" + id, DisableExecutionEnvironment: true, DisableSubagents: true, AgentOptions: map[string]any{"model": "gpt-5.5", "model_provider": map[string]any{"protocol": "responses", "base_url": server.URL + "/v1", "api_key": "fixture"}}} + req := proto.PromptRequestPayload{AgentKind: "codex", AgentStateKey: "agents-api-" + id, DisableExecutionEnvironment: true, DisableSubagents: true, Turn: proto.TurnSettings{Model: "gpt-5.5"}, AgentOptions: map[string]any{"model_provider": map[string]any{"protocol": "responses", "base_url": server.URL + "/v1", "api_key": "fixture"}}} ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second) defer cancel() for i := 0; i < 2; i++ { @@ -71,7 +71,7 @@ func TestNativeStateIdentitySurvivesExecutorRestart(t *testing.T) { if i == 1 { prompt = "Return the previous code." } - turn, err := e.StartTurn(ctx, fmt.Sprintf("ops-%d", i), proto.TextInput(prompt), output) + turn, err := e.StartTurn(ctx, fmt.Sprintf("ops-%d", i), req.Turn, proto.TextInput(prompt), output) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/codex/options.go b/apps/daemon/internal/agent/codex/options.go index c3096e13f..40eb7c824 100644 --- a/apps/daemon/internal/agent/codex/options.go +++ b/apps/daemon/internal/agent/codex/options.go @@ -9,6 +9,7 @@ import ( "sort" "strings" + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" harnessconfiguration "github.com/MiniMax-AI/OpenAgentCore/internal/harnessconfig/codex" ) @@ -67,22 +68,22 @@ type SessionPlan struct { } // BuildSessionPlan derives a SessionPlan from the request's agent_options and -// execution controls. It reads these agent_options keys: +// turn settings and execution controls. It reads these agent_options keys: // -// model string codex model slug, e.g. "gpt-5.5" // system_prompt string forwarded as developerInstructions // model_provider object frozen upstream protocol, endpoint, credential and token limits // harness_config object native parameters accepted by harnessconfig/codex // // Execution controls map one to one to native settings; see applyExecutionControls. // The codex binary itself is resolved via PATH only. -func BuildSessionPlan(stateRoot, agentStateKey string, opts map[string]any, controls *proto.ExecutionControls) (SessionPlan, error) { +func BuildSessionPlan(stateRoot, agentStateKey string, opts map[string]any, turn proto.TurnSettings, controls *proto.ExecutionControls) (SessionPlan, error) { plan := SessionPlan{ // Harnesses run unattended: Codex never offers its ask-the-user tool, - // and an unreachable model host fails the Turn after the provider's - // bounded retries instead of waiting for the network forever. + // an unreachable model host fails the Turn after the provider's + // bounded retries instead of waiting for the network forever, and no + // goal starts native turns of its own after the Turn ends. ExtraConfig: [][2]string{{"tools.experimental_request_user_input.enabled", "false"}}, - DisableFeatures: []string{"unbounded_connection_retries"}, + DisableFeatures: []string{"unbounded_connection_retries", "goals"}, Cleanup: func() {}, } @@ -90,7 +91,7 @@ func BuildSessionPlan(stateRoot, agentStateKey string, opts map[string]any, cont return plan, err } - if value, present := opts["model_provider"]; present && (value == nil || stringOpt(opts, "model") == "") { + if value, present := opts["model_provider"]; present && (value == nil || turn.Model == "") { return plan, errors.New("codex: model and complete model_provider are required") } @@ -98,10 +99,10 @@ func BuildSessionPlan(stateRoot, agentStateKey string, opts map[string]any, cont return plan, err } - plan.Model = stringOpt(opts, "model") + plan.Model = turn.Model plan.SystemPrompt = stringOpt(opts, "system_prompt") - codexHome, err := allocCodexHome(stateRoot, agentStateKey) + codexHome, err := sessionDir(stateRoot, agentStateKey) if err != nil { return plan, err } @@ -140,7 +141,7 @@ func BuildSessionPlan(stateRoot, agentStateKey string, opts map[string]any, cont } plan.Env = env - applyExecutionControls(&plan, controls) + applyExecutionControls(&plan, turn, controls) if plan.ModelProvider != "" { // Pin model_provider at the CLI layer so codex skips its builtin // "openai" provider — without this the [model_providers.oac] @@ -170,12 +171,18 @@ func excludeFromShellEnvironment(plan *SessionPlan, pattern string) { // applyExecutionControls maps each official value to its native setting. An // absent control sends nothing, so Codex keeps its native default; Codex itself // ignores a value the selected model does not support. -func applyExecutionControls(plan *SessionPlan, controls *proto.ExecutionControls) { +func applyExecutionControls(plan *SessionPlan, turn proto.TurnSettings, controls *proto.ExecutionControls) { set := func(key, value string) { plan.ExtraConfig = append(plan.ExtraConfig, [2]string{key, value}) } if controls == nil || controls.ReasoningSummary == "" { // The official default is no reasoning summary, while Codex defaults to a model-dependent one. set("model_reasoning_summary", strconv("none")) } + if turn.ReasoningEffort != "" { + set("model_reasoning_effort", strconv(turn.ReasoningEffort)) + } + if turn.ServiceTier != "" { + set("service_tier", strconv(turn.ServiceTier)) + } if controls == nil { return } @@ -203,16 +210,10 @@ func applyExecutionControls(plan *SessionPlan, controls *proto.ExecutionControls if format := controls.OutputFormat; format != nil { plan.OutputSchema = format.Schema } - if controls.ReasoningEffort != "" { - set("model_reasoning_effort", strconv(controls.ReasoningEffort)) - } if controls.ReasoningSummary != "" { plan.ReasoningSummary = true set("model_reasoning_summary", strconv(controls.ReasoningSummary)) } - if controls.ServiceTier != "" { - set("service_tier", strconv(controls.ServiceTier)) - } if controls.TextVerbosity != "" { set("model_verbosity", strconv(controls.TextVerbosity)) } @@ -222,27 +223,14 @@ func applyExecutionControls(plan *SessionPlan, controls *proto.ExecutionControls // helpers // --------------------------------------------------------------------------- -func allocCodexHome(root, agentStateKey string) (string, error) { - if strings.TrimSpace(agentStateKey) == "" { - return "", fmt.Errorf("codex: agentStateKey required for CODEX_HOME allocation") - } - if !filepath.IsAbs(root) || filepath.Clean(root) != root { - return "", fmt.Errorf("codex: state root must be a clean absolute directory") - } - parts := strings.Split(agentStateKey, "/") - safeParts := make([]string, 0, len(parts)) - for _, part := range parts { - if safe := safePathPartCodex(part); safe != "" && safe != "." && safe != ".." { - safeParts = append(safeParts, safe) - } - } - if len(safeParts) == 0 { - return "", fmt.Errorf("codex: invalid agentStateKey %q", agentStateKey) +// sessionDir creates the Session's native state directory under root. +func sessionDir(root, agentStateKey string) (string, error) { + dir, err := agent.CodexHistoryDir(root, agentStateKey) + if err != nil { + return "", err } - dirParts := append([]string{root, "daemon", "agent-sessions"}, safeParts...) - dir := filepath.Join(dirParts...) if err := os.MkdirAll(dir, 0o700); err != nil { - return "", fmt.Errorf("codex: create CODEX_HOME %s: %w", dir, err) + return "", fmt.Errorf("codex: create Session directory %s: %w", dir, err) } return dir, nil } @@ -294,22 +282,6 @@ func stringOpt(opts map[string]any, key string) string { return strings.TrimSpace(s) } -func safePathPartCodex(runID string) string { - var b strings.Builder - for _, r := range runID { - if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' { - b.WriteRune(r) - } else { - b.WriteByte('_') - } - } - out := b.String() - if out == "" { - return "run" - } - return out -} - // strconv quotes a value as a TOML string. Done by reusing the JSON // encoder for escape rules — TOML strings accept the same standard // escape set so this is wire-safe. diff --git a/apps/daemon/internal/agent/codex/options_test.go b/apps/daemon/internal/agent/codex/options_test.go index a63c5db19..cf2b9311d 100644 --- a/apps/daemon/internal/agent/codex/options_test.go +++ b/apps/daemon/internal/agent/codex/options_test.go @@ -8,7 +8,7 @@ import ( ) func TestBuildSessionPlan_DefaultsToBypass(t *testing.T) { - plan, err := BuildSessionPlan(testStateRoot(t), "conv-1/agent-1/codex", nil, nil) + plan, err := BuildSessionPlan(testStateRoot(t), "conv-1/agent-1/codex", nil, proto.TurnSettings{}, nil) if err != nil { t.Fatalf("BuildSessionPlan: %v", err) } @@ -22,7 +22,7 @@ func TestBuildSessionPlan_DefaultsToBypass(t *testing.T) { } func TestBuildSessionPlan_AllocsCodexHomeAndEnv(t *testing.T) { - plan, err := BuildSessionPlan(testStateRoot(t), "conv-1/agent-1/codex", nil, nil) + plan, err := BuildSessionPlan(testStateRoot(t), "conv-1/agent-1/codex", nil, proto.TurnSettings{}, nil) if err != nil { t.Fatalf("BuildSessionPlan: %v", err) } @@ -43,11 +43,11 @@ func TestBuildSessionPlan_AllocsCodexHomeAndEnv(t *testing.T) { func TestBuildSessionPlan_StableCodexHomeByStateKey(t *testing.T) { stateKey := "conv-stable/agent-stable/codex" - planA, err := BuildSessionPlan(testStateRoot(t), stateKey, nil, nil) + planA, err := BuildSessionPlan(testStateRoot(t), stateKey, nil, proto.TurnSettings{}, nil) if err != nil { t.Fatalf("BuildSessionPlan A: %v", err) } - planB, err := BuildSessionPlan(testStateRoot(t), stateKey, nil, nil) + planB, err := BuildSessionPlan(testStateRoot(t), stateKey, nil, proto.TurnSettings{}, nil) if err != nil { t.Fatalf("BuildSessionPlan B: %v", err) } diff --git a/apps/daemon/internal/agent/codex/permission_profile_test.go b/apps/daemon/internal/agent/codex/permission_profile_test.go index 722bda5bd..5d12325dd 100644 --- a/apps/daemon/internal/agent/codex/permission_profile_test.go +++ b/apps/daemon/internal/agent/codex/permission_profile_test.go @@ -12,7 +12,7 @@ func TestRuntimeUsesHostPermissions(t *testing.T) { t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) { req := proto.PromptRequestPayload{AgentStateKey: "session", DisableSubagents: true, LocalEnvironment: &proto.LocalEnvironment{WorkspaceRoot: t.TempDir()}} - plan, _, err := prepareSessionPlan(t.Context(), req, sessionConfig{stateRoot: testStateRoot(t)}) + plan, _, err := prepareSessionPlan(t.Context(), req, sessionConfig{stateRoot: testStateRoot(t), runtimeRoot: t.TempDir()}) if err != nil { t.Fatal(err) } @@ -32,12 +32,13 @@ func TestSelfHostedToolEnvironmentCannotRedirectNativeHistory(t *testing.T) { root := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", root) config := filepath.Join(root, "tool-env.json") - if err := os.WriteFile(config, []byte(`{"CODEX_HOME":"wrong","HOME":"wrong","USERPROFILE":"wrong","USER_VALUE":"ready"}`), 0600); err != nil { + if err := os.WriteFile(config, []byte(`{"CODEX_HOME":"wrong","CODEX_SQLITE_HOME":"wrong","HOME":"wrong","USERPROFILE":"wrong","USER_VALUE":"ready"}`), 0600); err != nil { t.Fatal(err) } t.Setenv("OAC_RUNTIME_TOOL_ENV_FILE", config) req := proto.PromptRequestPayload{AgentStateKey: "session", DisableSubagents: true, LocalEnvironment: &proto.LocalEnvironment{}} - plan, _, err := prepareSessionPlan(t.Context(), req, sessionConfig{stateRoot: testStateRoot(t)}) + runtimeRoot := t.TempDir() + plan, _, err := prepareSessionPlan(t.Context(), req, sessionConfig{stateRoot: testStateRoot(t), runtimeRoot: runtimeRoot}) if err != nil { t.Fatal(err) } @@ -47,7 +48,8 @@ func TestSelfHostedToolEnvironmentCannotRedirectNativeHistory(t *testing.T) { key, value, _ := strings.Cut(entry, "=") values[key] = value } - if values["CODEX_HOME"] == "" || values["CODEX_HOME"] == "wrong" || values["HOME"] == "wrong" || values["USERPROFILE"] == "wrong" || values["USER_VALUE"] != "ready" { + if values["CODEX_HOME"] == "" || values["CODEX_HOME"] == "wrong" || values["HOME"] == "wrong" || values["USERPROFILE"] == "wrong" || values["USER_VALUE"] != "ready" || + values["CODEX_SQLITE_HOME"] != filepath.Join(runtimeRoot, "runtime", "codex", "state", "session") { t.Fatal("initialization changed native state identity") } } diff --git a/apps/daemon/internal/agent/codex/preparation_helpers_test.go b/apps/daemon/internal/agent/codex/preparation_helpers_test.go index 780febc73..308e39177 100644 --- a/apps/daemon/internal/agent/codex/preparation_helpers_test.go +++ b/apps/daemon/internal/agent/codex/preparation_helpers_test.go @@ -37,11 +37,11 @@ func preparationFixture(t *testing.T) (proto.PromptRequestPayload, sessionConfig if err := os.WriteFile(binary, []byte(body), 0o700); err != nil { t.Fatal(err) } - cfg := defaultSessionConfig(testStateRoot(t)) + cfg := defaultSessionConfig(testStateRoot(t), t.TempDir()) cfg.codexBinary = binary req := proto.PromptRequestPayload{ AgentKind: "codex", AgentStateKey: "prepared-session", - AgentOptions: map[string]any{"model": "fixture-model"}, + Turn: proto.TurnSettings{Model: "fixture-model"}, AgentOptions: map[string]any{}, ExecutionControls: &proto.ExecutionControls{TextVerbosity: "medium"}, DisableExecutionEnvironment: true, FunctionTools: []proto.FunctionTool{{Name: "lookup", Parameters: json.RawMessage(`{"type":"object","properties":{"value":{"type":"integer"}}}`)}}, diff --git a/apps/daemon/internal/agent/codex/preparation_router_test.go b/apps/daemon/internal/agent/codex/preparation_router_test.go index b75c8b23c..94eb1ffb3 100644 --- a/apps/daemon/internal/agent/codex/preparation_router_test.go +++ b/apps/daemon/internal/agent/codex/preparation_router_test.go @@ -39,7 +39,7 @@ func TestPreparationRouterRetainsActualNativeChild(t *testing.T) { if err := os.MkdirAll(workspace, 0700); err != nil { t.Fatal(err) } - binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, workspace, filepath.Join(t.TempDir(), "capabilities")) + binding, err := localworkspace.NewWithCapabilityDirectory(environment, workspace, filepath.Join(t.TempDir(), "capabilities")) if err != nil { t.Fatal(err) } @@ -47,7 +47,7 @@ func TestPreparationRouterRetainsActualNativeChild(t *testing.T) { req.DisableExecutionEnvironment = false req.LocalEnvironment = &proto.LocalEnvironment{ID: environment, WorkspaceDirectory: "/workspace", CapabilitySources: &proto.CapabilitySources{}} registry := agent.NewRegistry() - registry.RegisterKind(proto.SupportedAgentKind{Kind: "codex", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported, FunctionTools: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + registry.RegisterKind(proto.SupportedAgentKind{Kind: "codex", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported, FunctionTools: proto.CapabilitySupported})}, harnessconfig.Declaration{}) prepared := make(chan *Prepared, 1) registry.RegisterExecutor("codex", func(ctx context.Context, req proto.PromptRequestPayload) (agent.Executor, error) { e, err := newExecutor(ctx, req, cfg) diff --git a/apps/daemon/internal/agent/codex/protocol.go b/apps/daemon/internal/agent/codex/protocol.go index baa591ffd..d98344e14 100644 --- a/apps/daemon/internal/agent/codex/protocol.go +++ b/apps/daemon/internal/agent/codex/protocol.go @@ -162,6 +162,14 @@ type TurnStartParams struct { Input []UserInput `json:"input"` // OutputSchema constrains this Turn's final assistant message natively. OutputSchema json.RawMessage `json:"outputSchema,omitempty"` + // The settings below apply to this and later Turns. Every Turn sends them, + // because a cold thread/resume restores the persisted values. + Model string `json:"model,omitempty"` + Effort string `json:"effort,omitempty"` + ServiceTier any `json:"serviceTier"` // a tier, or null for auto + ApprovalPolicy string `json:"approvalPolicy"` + // ApprovalsReviewer is "user" or "auto_review". + ApprovalsReviewer string `json:"approvalsReviewer"` } type TurnInterruptParams struct { diff --git a/apps/daemon/internal/agent/codex/provider_config_test.go b/apps/daemon/internal/agent/codex/provider_config_test.go index 03ae2512a..b12e5903a 100644 --- a/apps/daemon/internal/agent/codex/provider_config_test.go +++ b/apps/daemon/internal/agent/codex/provider_config_test.go @@ -1,6 +1,8 @@ package codex import ( + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" + "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" "os" "path/filepath" "slices" @@ -148,12 +150,11 @@ func TestNormaliseProviderConfig_Nil(t *testing.T) { func TestBuildSessionPlan_PinsModelProviderWhenProviderSet(t *testing.T) { plan, err := BuildSessionPlan(testStateRoot(t), "conv-1/agent-1/codex", map[string]any{ - "model": "fixture-model", "model_provider": map[string]any{"protocol": "responses", "base_url": "https://x/v1", "api_key": "sk-x", }, - }, nil) + }, proto.TurnSettings{Model: "fixture-model"}, nil) if err != nil { t.Fatalf("BuildSessionPlan: %v", err) } @@ -185,7 +186,7 @@ func TestBuildSessionPlan_PinsModelProviderWhenProviderSet(t *testing.T) { } func TestBuildSessionPlan_NoProviderLeavesBuiltinDefault(t *testing.T) { - plan, err := BuildSessionPlan(testStateRoot(t), "conv-1/agent-1/codex", nil, nil) + plan, err := BuildSessionPlan(testStateRoot(t), "conv-1/agent-1/codex", nil, proto.TurnSettings{}, nil) if err != nil { t.Fatalf("BuildSessionPlan: %v", err) } @@ -212,7 +213,7 @@ func mustReadFile(t *testing.T, path string) string { // Codex's default unbounded connection retries keep a Turn whose model host // is unreachable in progress forever. func TestModelConnectionRetriesStayBounded(t *testing.T) { - plan, err := BuildSessionPlan(t.TempDir(), "bounded", map[string]any{}, nil) + plan, err := BuildSessionPlan(t.TempDir(), "bounded", map[string]any{}, proto.TurnSettings{}, nil) if err != nil { t.Fatal(err) } @@ -221,10 +222,22 @@ func TestModelConnectionRetriesStayBounded(t *testing.T) { } } +// An active Codex goal starts native turns on its own whenever its thread is +// idle, which would run work after the Turn ends. +func TestGoalsStayDisabled(t *testing.T) { + plan, err := BuildSessionPlan(t.TempDir(), "goals", map[string]any{}, proto.TurnSettings{}, nil) + if err != nil { + t.Fatal(err) + } + if !slices.Contains(plan.DisableFeatures, "goals") { + t.Fatal("goals stay enabled") + } +} + func TestProviderCredentialOnlyInNativeLoopEnvironment(t *testing.T) { root := t.TempDir() const token = "synthetic-private-provider-token" - plan, err := BuildSessionPlan(root, "stable-session", map[string]any{"model": "fixture-model", "model_provider": map[string]any{"protocol": "responses", "base_url": "https://model.example/v1", "api_key": token}}, nil) + plan, err := BuildSessionPlan(root, "stable-session", map[string]any{"model_provider": map[string]any{"protocol": "responses", "base_url": "https://model.example/v1", "api_key": token}}, proto.TurnSettings{Model: "fixture-model"}, nil) if err != nil { t.Fatal(err) } @@ -255,10 +268,26 @@ func TestProviderCredentialOnlyInNativeLoopEnvironment(t *testing.T) { } } +func TestSessionsKeepNativeStateInOwnDirectories(t *testing.T) { + state := testStateRoot(t) + homes := map[string]bool{} + for _, key := range []string{"session-a", "session-b"} { + plan, err := BuildSessionPlan(state, key, nil, proto.TurnSettings{}, nil) + if err != nil { + t.Fatal(err) + } + want, _ := agent.CodexHistoryDir(state, key) + if got := nativeHomeFromPlan(plan); got != want || homes[got] { + t.Fatalf("CODEX_HOME for %s = %s, want its own %s", key, got, want) + } + homes[want] = true + } +} + func TestExplicitStateRootSurvivesRuntimeReplacement(t *testing.T) { state := t.TempDir() t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) - first, err := allocCodexHome(state, "stable-session") + first, err := sessionDir(state, "stable-session") if err != nil { t.Fatal(err) } @@ -267,7 +296,7 @@ func TestExplicitStateRootSurvivesRuntimeReplacement(t *testing.T) { t.Fatal(err) } t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) - second, err := allocCodexHome(state, "stable-session") + second, err := sessionDir(state, "stable-session") if err != nil || second != first { t.Fatal("instance identity changed native history", err) } @@ -278,16 +307,16 @@ func TestExplicitStateRootSurvivesRuntimeReplacement(t *testing.T) { if err = os.WriteFile(unavailable, nil, 0600); err != nil { t.Fatal(err) } - if _, err = allocCodexHome(unavailable, "stable-session"); err == nil { + if _, err = sessionDir(unavailable, "stable-session"); err == nil { t.Fatal("unavailable explicit root fell back") } } func TestProviderHeadersRebuiltForEveryTurn(t *testing.T) { root := t.TempDir() - opts := map[string]any{"model": "fixture", "model_provider": map[string]any{"protocol": "responses", "base_url": "https://example.test/v1", "api_key": "fixture", "headers": map[string]string{"X-Activity": "private-header-canary"}}} + opts := map[string]any{"model_provider": map[string]any{"protocol": "responses", "base_url": "https://example.test/v1", "api_key": "fixture", "headers": map[string]string{"X-Activity": "private-header-canary"}}} for range 3 { - plan, err := BuildSessionPlan(root, "persistent", opts, nil) + plan, err := BuildSessionPlan(root, "persistent", opts, proto.TurnSettings{Model: "fixture"}, nil) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/codex/recovery_test.go b/apps/daemon/internal/agent/codex/recovery_test.go index 82ced82cf..22655073c 100644 --- a/apps/daemon/internal/agent/codex/recovery_test.go +++ b/apps/daemon/internal/agent/codex/recovery_test.go @@ -147,7 +147,7 @@ func TestPreparedRecoveryCannotStartWithoutExistingHistory(t *testing.T) { t.Run(environment, func(t *testing.T) { req, cfg, root := preparationFixture(t) req.RequireExistingNativeSession = true - cwd, err := allocCodexHome(testStateRoot(t), req.AgentStateKey) + cwd, err := sessionDir(testStateRoot(t), req.AgentStateKey) if err != nil { t.Fatal(err) } @@ -168,7 +168,7 @@ func TestPreparedRecoveryCannotStartWithoutExistingHistory(t *testing.T) { } assertPreparationOnly(t, root) out := make(chan proto.Envelope, 16) - turn, err := e.StartTurn(t.Context(), "recovery-run", proto.TextInput("continue"), out) + turn, err := e.StartTurn(t.Context(), "recovery-run", proto.TurnSettings{}, proto.TextInput("continue"), out) if err == nil { t.Fatal("missing history started a Turn") } diff --git a/apps/daemon/internal/agent/codex/rpc_close_test.go b/apps/daemon/internal/agent/codex/rpc_close_test.go index 7d4c2c29b..6eb6c841e 100644 --- a/apps/daemon/internal/agent/codex/rpc_close_test.go +++ b/apps/daemon/internal/agent/codex/rpc_close_test.go @@ -80,7 +80,7 @@ func TestJSONRPCClientCloseCanRetryUnreapedChild(t *testing.T) { closeConcurrently(true) ownerCtx, cancelOwner := context.WithCancel(t.Context()) s := &Session{rpc: client, cancelCtx: ownerCtx, cancelFn: cancelOwner, - cfg: defaultSessionConfig(testStateRoot(t)), bufs: NewItemBuffers()} + cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), bufs: NewItemBuffers()} ctx, cancelWait := context.WithTimeout(t.Context(), 20*time.Millisecond) defer cancelWait() if err := s.Cancel(ctx); !errors.Is(err, context.DeadlineExceeded) { diff --git a/apps/daemon/internal/agent/codex/session.go b/apps/daemon/internal/agent/codex/session.go index 43788f4a9..55efd4e46 100644 --- a/apps/daemon/internal/agent/codex/session.go +++ b/apps/daemon/internal/agent/codex/session.go @@ -24,14 +24,16 @@ const terminalSendTimeout = 2 * time.Second // defaultSessionConfig. type sessionConfig struct { stateRoot string + runtimeRoot string codexBinary string logger *slog.Logger killTimeout time.Duration } -func defaultSessionConfig(stateRoot string) sessionConfig { +func defaultSessionConfig(stateRoot, runtimeRoot string) sessionConfig { return sessionConfig{ stateRoot: stateRoot, + runtimeRoot: runtimeRoot, codexBinary: defaultBinary(), logger: obslog.Bg(), killTimeout: rpcKillTimeout, @@ -133,9 +135,9 @@ func (s *Session) registerHandlers() { rpc.OnNotification("thread/tokenUsage/updated", s.onUsageUpdated) rpc.OnNotification("error", s.onErrorNotif) - // Harnesses run unattended. Approval policy never and the session plan keep - // native asks from being raised; any other server request gets the - // client's method-not-found reply. + // Harnesses run unattended. Approval policy never raises no native ask, and + // under auto_review the reviewer answers. Any server request that still + // reaches the client gets method-not-found, which Codex turns into a denial. s.onServerRequest("item/tool/call", s.handleFunctionCall) } diff --git a/apps/daemon/internal/agent/codex/session_cancel_test.go b/apps/daemon/internal/agent/codex/session_cancel_test.go index e4307ae1e..5bcc706e4 100644 --- a/apps/daemon/internal/agent/codex/session_cancel_test.go +++ b/apps/daemon/internal/agent/codex/session_cancel_test.go @@ -116,7 +116,7 @@ func cancellationTestSession(t *testing.T) (*Session, *TestClient, ServerSide) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) s := &Session{rpc: client.JSONRPCClient, cancelCtx: ctx, cancelFn: cancel, - cfg: defaultSessionConfig(testStateRoot(t)), out: make(chan proto.Envelope, 8), bufs: NewItemBuffers()} + cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), out: make(chan proto.Envelope, 8), bufs: NewItemBuffers()} return s, client, server } diff --git a/apps/daemon/internal/agent/codex/session_cancel_write_test.go b/apps/daemon/internal/agent/codex/session_cancel_write_test.go index e9adb4970..11c547aca 100644 --- a/apps/daemon/internal/agent/codex/session_cancel_write_test.go +++ b/apps/daemon/internal/agent/codex/session_cancel_write_test.go @@ -146,7 +146,7 @@ func TestCancelReleasesBlockedNativeProcess(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() s := &Session{rpc: client, cancelCtx: ctx, cancelFn: cancel, - cfg: defaultSessionConfig(testStateRoot(t)), bufs: NewItemBuffers()} + cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), bufs: NewItemBuffers()} s.setThreadID("native-thread") s.onTurnStarted(json.RawMessage(`{"threadId":"native-thread","turn":{"id":"native-turn"}}`)) cancelDone := make(chan struct{}) diff --git a/apps/daemon/internal/agent/codex/session_command_output_test.go b/apps/daemon/internal/agent/codex/session_command_output_test.go index f14b3eab3..8f3c42421 100644 --- a/apps/daemon/internal/agent/codex/session_command_output_test.go +++ b/apps/daemon/internal/agent/codex/session_command_output_test.go @@ -10,7 +10,7 @@ import ( func TestCommandOutputRequiresRootTurn(t *testing.T) { out := make(chan proto.Envelope, 10) - s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t)), rpc: NewJSONRPCClient(JSONRPCConfig{})} + s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), rpc: NewJSONRPCClient(JSONRPCConfig{})} s.registerHandlers() s.setThreadID("root") s.beginRootTurn("root", "turn") diff --git a/apps/daemon/internal/agent/codex/session_items_test.go b/apps/daemon/internal/agent/codex/session_items_test.go index 95ce60d56..0c29fff53 100644 --- a/apps/daemon/internal/agent/codex/session_items_test.go +++ b/apps/daemon/internal/agent/codex/session_items_test.go @@ -71,7 +71,7 @@ func TestDispatchStartedItem_UnknownSilent(t *testing.T) { func TestReasoningIsReportedOnlyWhenRequested(t *testing.T) { for _, requested := range []bool{true, false} { out := make(chan proto.Envelope, 16) - s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t)), + s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), rpc: NewJSONRPCClient(JSONRPCConfig{}), bufs: NewItemBuffers(), reasoningSummary: requested} s.registerHandlers() s.setThreadID("root") diff --git a/apps/daemon/internal/agent/codex/session_messages_test.go b/apps/daemon/internal/agent/codex/session_messages_test.go index eacc37199..2b908a5d3 100644 --- a/apps/daemon/internal/agent/codex/session_messages_test.go +++ b/apps/daemon/internal/agent/codex/session_messages_test.go @@ -10,7 +10,7 @@ import ( func TestMessageObservationKeepsNativeBoundaries(t *testing.T) { out := make(chan proto.Envelope, 16) - s := &Session{runID: "run", out: out, cancelCtx: context.Background(), bufs: NewItemBuffers(), cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{runID: "run", out: out, cancelCtx: context.Background(), bufs: NewItemBuffers(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.setThreadID("thread") s.onTurnStarted(json.RawMessage(`{"threadId":"thread","turn":{"id":"turn"}}`)) s.onItemStarted(json.RawMessage(`{"threadId":"thread","turnId":"turn","item":{"type":"agentMessage","id":"a","phase":"commentary"}}`)) diff --git a/apps/daemon/internal/agent/codex/session_notifications_rpc_test.go b/apps/daemon/internal/agent/codex/session_notifications_rpc_test.go index c14d7cd98..bc6b4da2a 100644 --- a/apps/daemon/internal/agent/codex/session_notifications_rpc_test.go +++ b/apps/daemon/internal/agent/codex/session_notifications_rpc_test.go @@ -19,7 +19,7 @@ func TestRootRPCNotificationOrdering(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() out := make(chan proto.Envelope, 16) - s := &Session{runID: "run", out: out, rpc: client.JSONRPCClient, cancelCtx: ctx, bufs: NewItemBuffers(), cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{runID: "run", out: out, rpc: client.JSONRPCClient, cancelCtx: ctx, bufs: NewItemBuffers(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.registerHandlers() barrier := make(chan struct{}, 1) client.OnNotification("test/barrier", func(json.RawMessage) { barrier <- struct{}{} }) @@ -132,7 +132,7 @@ func TestThreadRPCResponseRequiresRootIdentity(t *testing.T) { defer cleanup() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() - s := &Session{rpc: client.JSONRPCClient, cancelCtx: ctx, cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{rpc: client.JSONRPCClient, cancelCtx: ctx, cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.registerHandlers() result := make(chan error, 1) go func() { result <- s.resumeThread("root", SessionPlan{}) }() diff --git a/apps/daemon/internal/agent/codex/session_notifications_test.go b/apps/daemon/internal/agent/codex/session_notifications_test.go index 3e33d7885..e8bf661b2 100644 --- a/apps/daemon/internal/agent/codex/session_notifications_test.go +++ b/apps/daemon/internal/agent/codex/session_notifications_test.go @@ -12,7 +12,7 @@ func TestRootNotificationIsolation(t *testing.T) { for _, childStarted := range []bool{false, true} { t.Run(map[bool]string{false: "child without thread started", true: "child thread started"}[childStarted], func(t *testing.T) { out := make(chan proto.Envelope, 64) - s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t)), + s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), rpc: NewJSONRPCClient(JSONRPCConfig{}), bufs: NewItemBuffers(), reasoningSummary: true} s.registerHandlers() s.setThreadID("root") @@ -96,7 +96,7 @@ func TestRootNotificationIsolation(t *testing.T) { } func TestNotificationsCannotEstablishRootIdentity(t *testing.T) { - s := &Session{cfg: defaultSessionConfig(testStateRoot(t)), rpc: NewJSONRPCClient(JSONRPCConfig{}), bufs: NewItemBuffers()} + s := &Session{cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), rpc: NewJSONRPCClient(JSONRPCConfig{}), bufs: NewItemBuffers()} s.registerHandlers() scopeNotification(t, s, "thread/started", `{"thread":{"id":"unrelated"}}`) scopeNotification(t, s, "turn/started", `{"threadId":"unrelated","turn":{"id":"unrelated-turn"}}`) @@ -116,7 +116,7 @@ func TestRootNativeErrorNotification(t *testing.T) { for _, location := range []string{"error notification", "completion"} { t.Run(name+"/"+location, func(t *testing.T) { out := make(chan proto.Envelope, 4) - s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t)), rpc: NewJSONRPCClient(JSONRPCConfig{})} + s := &Session{runID: "run", out: out, cancelCtx: context.Background(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), rpc: NewJSONRPCClient(JSONRPCConfig{})} s.registerHandlers() s.setThreadID("root") scopeNotification(t, s, "turn/started", `{"threadId":"root","turn":{"id":"turn"}}`) diff --git a/apps/daemon/internal/agent/codex/session_plan.go b/apps/daemon/internal/agent/codex/session_plan.go index fe240ec20..0136ec9eb 100644 --- a/apps/daemon/internal/agent/codex/session_plan.go +++ b/apps/daemon/internal/agent/codex/session_plan.go @@ -3,8 +3,10 @@ package codex import ( "context" "fmt" + "os" "strings" + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/localworkspace" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" ) @@ -20,10 +22,22 @@ func prepareSessionPlan(ctx context.Context, req proto.PromptRequestPayload, cfg if err != nil { return SessionPlan{}, nil, err } - plan, err := BuildSessionPlan(cfg.stateRoot, req.AgentStateKey, req.AgentOptions, req.ExecutionControls) + plan, err := BuildSessionPlan(cfg.stateRoot, req.AgentStateKey, req.AgentOptions, req.Turn, req.ExecutionControls) if err != nil { return SessionPlan{}, nil, fmt.Errorf("codex: build session plan: %w", err) } + // Codex's SQLite databases stay on the compute's own disk, where they open faster than + // on shared state storage. A replacement compute rebuilds them from the history in + // CODEX_HOME; goals, whose state lives only there, are disabled. + sqliteHome, err := agent.StateDir(cfg.runtimeRoot, "codex", req.AgentStateKey) + if err == nil { + err = os.MkdirAll(sqliteHome, 0700) + } + if err != nil { + plan.Cleanup() + return SessionPlan{}, nil, err + } + plan.Env = append(plan.Env, "CODEX_SQLITE_HOME="+sqliteHome) if err := configureSubagentObservations(&plan, req); err != nil { plan.Cleanup() return SessionPlan{}, nil, err @@ -47,7 +61,7 @@ func prepareSessionPlan(ctx context.Context, req proto.PromptRequestPayload, cfg return SessionPlan{}, nil, err } for key, value := range values { - if strings.EqualFold(key, "CODEX_HOME") || strings.EqualFold(key, "HOME") || strings.EqualFold(key, "USERPROFILE") { + if strings.EqualFold(key, "CODEX_HOME") || strings.EqualFold(key, "CODEX_SQLITE_HOME") || strings.EqualFold(key, "HOME") || strings.EqualFold(key, "USERPROFILE") { continue } plan.Env = append(plan.Env, key+"="+value) diff --git a/apps/daemon/internal/agent/codex/session_policy_test.go b/apps/daemon/internal/agent/codex/session_policy_test.go index f534f4cf4..697dd9df2 100644 --- a/apps/daemon/internal/agent/codex/session_policy_test.go +++ b/apps/daemon/internal/agent/codex/session_policy_test.go @@ -16,7 +16,7 @@ func TestThreadRequestsApplyDeploymentPolicy(t *testing.T) { for _, method := range []string{"thread/start", "thread/resume"} { t.Run(method, func(t *testing.T) { t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) - plan, _, err := prepareSessionPlan(context.Background(), proto.PromptRequestPayload{AgentStateKey: "conv/agent/codex", DisableSubagents: true, DisableExecutionEnvironment: true}, sessionConfig{stateRoot: testStateRoot(t)}) + plan, _, err := prepareSessionPlan(context.Background(), proto.PromptRequestPayload{AgentStateKey: "conv/agent/codex", DisableSubagents: true, DisableExecutionEnvironment: true}, sessionConfig{stateRoot: testStateRoot(t), runtimeRoot: t.TempDir()}) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/codex/session_run.go b/apps/daemon/internal/agent/codex/session_run.go index 48e3002ff..4779dae84 100644 --- a/apps/daemon/internal/agent/codex/session_run.go +++ b/apps/daemon/internal/agent/codex/session_run.go @@ -8,7 +8,7 @@ import ( "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" ) -func (s *Session) startNative(ctx context.Context, plan SessionPlan, req proto.PromptRequestPayload) error { +func (s *Session) startNative(ctx context.Context, plan SessionPlan, turn proto.TurnSettings, req proto.PromptRequestPayload) error { threadStarted := time.Now() mode := "reuse" if s.currentThreadID() == "" { @@ -28,9 +28,21 @@ func (s *Session) startNative(ctx context.Context, plan SessionPlan, req proto.P return err } turnParams := TurnStartParams{ - ThreadID: s.currentThreadID(), - Input: input, - OutputSchema: plan.OutputSchema, + ThreadID: s.currentThreadID(), + Input: input, + OutputSchema: plan.OutputSchema, + Model: turn.Model, + Effort: turn.ReasoningEffort, + ApprovalPolicy: approvalPolicyNever, ApprovalsReviewer: approvalsReviewerUser, + } + if turn.ServiceTier != "" { + turnParams.ServiceTier = turn.ServiceTier + } + if turn.Review == "auto_review" { + turnParams.ApprovalPolicy, turnParams.ApprovalsReviewer = approvalPolicyOnRequest, turn.Review + } + if turn.Model != "" { + s.resolvedModel = turn.Model } turnCtx, turnCancel := context.WithTimeout(ctx, 10*time.Second) _, ackErr := s.rpc.requestWithResult(withNativeBoundary(turnCtx, s.boundary), "turn/start", turnParams, s.bindTurnResult) diff --git a/apps/daemon/internal/agent/codex/session_steering_lifecycle_test.go b/apps/daemon/internal/agent/codex/session_steering_lifecycle_test.go index 8cbaa7863..17502bf53 100644 --- a/apps/daemon/internal/agent/codex/session_steering_lifecycle_test.go +++ b/apps/daemon/internal/agent/codex/session_steering_lifecycle_test.go @@ -112,7 +112,7 @@ func TestBlockedSteeringWriteEndsRunWithTerminalFrames(t *testing.T) { ready <- nil }() // Executor.StartTurn starts and settles each Turn through these two steps. - go s.settleExecutorTurn(s.startNative(ctx, SessionPlan{Model: "synthetic"}, proto.PromptRequestPayload{Input: proto.TextInput("first")})) + go s.settleExecutorTurn(s.startNative(ctx, SessionPlan{Model: "synthetic"}, proto.TurnSettings{Model: "synthetic"}, proto.PromptRequestPayload{Input: proto.TextInput("first")})) if err := <-ready; err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/codex/session_thread.go b/apps/daemon/internal/agent/codex/session_thread.go index 65b59fce9..70d03e4cd 100644 --- a/apps/daemon/internal/agent/codex/session_thread.go +++ b/apps/daemon/internal/agent/codex/session_thread.go @@ -5,10 +5,13 @@ import ( "fmt" ) -// Harnesses run unattended with the launching user's permissions: Codex never -// raises a native approval request and applies no inner sandbox. +// Harnesses run unattended with the launching user's permissions and no inner +// sandbox. Codex asks for approval only under review auto_review, which sends +// each request to its native reviewer. const ( approvalPolicyNever = "never" + approvalPolicyOnRequest = "on-request" + approvalsReviewerUser = "user" sandboxDangerFullAccess = "danger-full-access" ) diff --git a/apps/daemon/internal/agent/codex/session_tools_test.go b/apps/daemon/internal/agent/codex/session_tools_test.go index 1080b2230..ae740f1f9 100644 --- a/apps/daemon/internal/agent/codex/session_tools_test.go +++ b/apps/daemon/internal/agent/codex/session_tools_test.go @@ -35,7 +35,7 @@ func TestToolObservations(t *testing.T) { } t.Run(source.ID, func(t *testing.T) { out := make(chan proto.Envelope, 4) - s := &Session{runID: "run", out: out, cancelCtx: context.Background(), bufs: NewItemBuffers(), cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{runID: "run", out: out, cancelCtx: context.Background(), bufs: NewItemBuffers(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.setThreadID("private-thread") s.onTurnStarted(json.RawMessage(`{"threadId":"private-thread","turn":{"id":"private-turn"}}`)) raw := json.RawMessage(`{"threadId":"private-thread","turnId":"private-turn","item":` + item + `}`) @@ -87,7 +87,7 @@ func TestCompletedCommandNULReachesWireAsText(t *testing.T) { } defer conn.Close() out := make(chan proto.Envelope, 1) - session := &Session{runID: "run", out: out, cancelCtx: ctx, cfg: defaultSessionConfig(testStateRoot(t))} + session := &Session{runID: "run", out: out, cancelCtx: ctx, cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} env, err := proto.NewEnvelope(proto.TypeToolCall, "run", proto.ToolCallPayload{ID: "cmd", Name: "Bash", Stage: "after"}) if err != nil { t.Fatal(err) diff --git a/apps/daemon/internal/agent/codex/session_usage_live_test.go b/apps/daemon/internal/agent/codex/session_usage_live_test.go index ba9fe754f..55ab89a61 100644 --- a/apps/daemon/internal/agent/codex/session_usage_live_test.go +++ b/apps/daemon/internal/agent/codex/session_usage_live_test.go @@ -15,7 +15,7 @@ const activeUsageNotification = `{"method":"thread/tokenUsage/updated","params": func TestUsagePublishedBeforeCompletion(t *testing.T) { out := make(chan proto.Envelope, 8) - s := &Session{runID: "run", out: out, cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{runID: "run", out: out, cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.setThreadID("thread") s.onUsageUpdated(json.RawMessage(`{"threadId":"thread","turnId":"old","tokenUsage":{"total":{"inputTokens":10,"cachedInputTokens":1,"outputTokens":3,"reasoningOutputTokens":1,"totalTokens":13}}}`)) if len(s.out) != 0 { @@ -159,7 +159,7 @@ func TestLiveUsageRequiresConsistentCompleteBreakdown(t *testing.T) { } { t.Run(name, func(t *testing.T) { out := make(chan proto.Envelope, 1) - s := &Session{out: out, cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{out: out, cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.setThreadID("thread") s.onTurnStarted(json.RawMessage(`{"threadId":"thread","turn":{"id":"turn"}}`)) s.onUsageUpdated(json.RawMessage(`{"threadId":"thread","turnId":"turn","tokenUsage":{"total":` + counters + `}}`)) @@ -177,7 +177,7 @@ func TestLiveUsageRequiresConsistentCompleteBreakdown(t *testing.T) { func TestLiveUsageRejectsInconsistentResumeDelta(t *testing.T) { out := make(chan proto.Envelope, 2) - s := &Session{out: out, cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{out: out, cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.setThreadID("thread") s.onUsageUpdated(json.RawMessage(`{"threadId":"thread","turnId":"old","tokenUsage":{"total":{"inputTokens":100,"cachedInputTokens":90,"outputTokens":50,"reasoningOutputTokens":10,"totalTokens":150}}}`)) s.onTurnStarted(json.RawMessage(`{"threadId":"thread","turn":{"id":"turn"}}`)) diff --git a/apps/daemon/internal/agent/codex/session_usage_test.go b/apps/daemon/internal/agent/codex/session_usage_test.go index 7c5e17ada..473a02ab1 100644 --- a/apps/daemon/internal/agent/codex/session_usage_test.go +++ b/apps/daemon/internal/agent/codex/session_usage_test.go @@ -62,7 +62,7 @@ func TestNativeTokenUsageAcrossRuns(t *testing.T) { } func TestNativeTokenUsageFreshThreadAndIgnoredPayloads(t *testing.T) { - s := &Session{out: make(chan proto.Envelope, 8), cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{out: make(chan proto.Envelope, 8), cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.setThreadID("thread") s.onTurnStarted(json.RawMessage(`{"threadId":"thread","turn":{"id":"current"}}`)) s.onUsageUpdated(json.RawMessage(`{"threadId":"thread","turnId":"current","tokenUsage":{"total":{"inputTokens":321,"outputTokens":45}}}`)) @@ -81,7 +81,7 @@ func TestNativeTokenUsageFreshThreadAndIgnoredPayloads(t *testing.T) { } func TestLegacyTurnUsagePayload(t *testing.T) { - s := &Session{out: make(chan proto.Envelope, 8), cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{out: make(chan proto.Envelope, 8), cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.setThreadID("thread") s.onTurnStarted(json.RawMessage(`{"threadId":"thread","turn":{"id":"current"}}`)) s.onUsageUpdated(json.RawMessage(`{"threadId":"thread","usage":{"inputTokens":123,"outputTokens":12}}`)) @@ -95,7 +95,7 @@ func TestLegacyTurnUsagePayload(t *testing.T) { } func TestCompleteTokenBreakdownAndCancellation(t *testing.T) { - s := &Session{out: make(chan proto.Envelope, 8), cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{out: make(chan proto.Envelope, 8), cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.setThreadID("thread") s.onUsageUpdated(json.RawMessage(`{"threadId":"thread","turnId":"old","tokenUsage":{"total":{"inputTokens":100,"cachedInputTokens":20,"outputTokens":50,"reasoningOutputTokens":10,"totalTokens":150}}}`)) s.onTurnStarted(json.RawMessage(`{"threadId":"thread","turn":{"id":"new"}}`)) @@ -164,7 +164,7 @@ func TestUnadvancedThreadTotalIsNotTurnUsage(t *testing.T) { } { t.Run(name, func(t *testing.T) { out := make(chan proto.Envelope, 8) - s := &Session{runID: "run", out: out, cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t))} + s := &Session{runID: "run", out: out, cancelCtx: t.Context(), cfg: defaultSessionConfig(testStateRoot(t), t.TempDir())} s.setThreadID("thread") total := `{"inputTokens":0,"cachedInputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":0}` if replay != "" { diff --git a/apps/daemon/internal/agent/codex/subagent_observations_test.go b/apps/daemon/internal/agent/codex/subagent_observations_test.go index 14589a919..0175d8f29 100644 --- a/apps/daemon/internal/agent/codex/subagent_observations_test.go +++ b/apps/daemon/internal/agent/codex/subagent_observations_test.go @@ -74,7 +74,7 @@ func observationSession(t *testing.T, status string) (*Session, *subagentFixture t.Fatal(err) } f.persist(t) - s := &Session{runID: "run", nativeHome: f.home, rpc: client.JSONRPCClient, out: out, cancelCtx: ctx, cancelFn: cancel, cfg: defaultSessionConfig(testStateRoot(t)), bufs: NewItemBuffers()} + s := &Session{runID: "run", nativeHome: f.home, rpc: client.JSONRPCClient, out: out, cancelCtx: ctx, cancelFn: cancel, cfg: defaultSessionConfig(testStateRoot(t), t.TempDir()), bufs: NewItemBuffers()} s.setThreadID("root") s.beginRootTurn("root", "root-turn") s.startSubagentObservations() diff --git a/apps/daemon/internal/agent/codex/terminal_cleanup_test.go b/apps/daemon/internal/agent/codex/terminal_cleanup_test.go index c0a208c6b..9a1374e25 100644 --- a/apps/daemon/internal/agent/codex/terminal_cleanup_test.go +++ b/apps/daemon/internal/agent/codex/terminal_cleanup_test.go @@ -24,7 +24,7 @@ func TestExecutorCancellationRequiresNativeTerminalCleanup(t *testing.T) { allow() } out := make(chan proto.Envelope, 20) - turn, err := e.StartTurn(t.Context(), "cancel", proto.TextInput("hold"), out) + turn, err := e.StartTurn(t.Context(), "cancel", proto.TurnSettings{}, proto.TextInput("hold"), out) if err != nil { t.Fatal(err) } @@ -60,7 +60,7 @@ func TestExecutorCancellationRequiresNativeTerminalCleanup(t *testing.T) { } if confirmed { nextOut := make(chan proto.Envelope, 20) - next, err := e.StartTurn(ctx, "next", proto.TextInput("answer"), nextOut) + next, err := e.StartTurn(ctx, "next", proto.TurnSettings{}, proto.TextInput("answer"), nextOut) if err != nil || !awaitExecutorTurn(t, next, nextOut).Reusable { t.Fatal("confirmed cleanup prevented reuse", err) } @@ -83,7 +83,7 @@ func TestExecutorCancellationRequiresNativeTerminalCleanup(t *testing.T) { func TestExecutorCloseCleansNativeTerminalsAfterNormalCompletion(t *testing.T) { e, root := executorFixture(t, "terminal-cleanup") out := make(chan proto.Envelope, 20) - turn, err := e.StartTurn(t.Context(), "normal", proto.TextInput("answer"), out) + turn, err := e.StartTurn(t.Context(), "normal", proto.TurnSettings{}, proto.TextInput("answer"), out) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/configuration_test.go b/apps/daemon/internal/agent/configuration_test.go index 2d36d96da..f6824a99b 100644 --- a/apps/daemon/internal/agent/configuration_test.go +++ b/apps/daemon/internal/agent/configuration_test.go @@ -17,25 +17,25 @@ func TestEveryRegistryEntryPreparesTheBoundModelConfiguration(t *testing.T) { configuration := harnessconfig.Configuration{Providers: []harnessconfig.Provider{{Protocol: "responses"}}} calls := 0 expected := errors.New("native entry reached") - registry.RegisterKind(proto.SupportedAgentKind{Kind: "fixture", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, configuration) + registry.RegisterKind(proto.SupportedAgentKind{Kind: "fixture", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Declaration{Configuration: configuration}) registry.RegisterExecutor("fixture", func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { calls++ return nil, expected }) configuration.Providers[0].Protocol = "anthropic" - executor, _ := registry.ResolveExecutor("fixture") - for _, options := range []map[string]any{ - {"model": nil}, - {"model": "fixture", "model_provider": map[string]any{"protocol": "anthropic", "base_url": "https://provider.example", "api_key": "private-sentinel"}}, - {"model_provider": map[string]any{"protocol": "responses", "base_url": "https://provider.example", "api_key": "private-sentinel"}}, - {"harness_config": map[string]any{"unknown": "private-sentinel"}}, + executor, _, _ := registry.ResolveExecutor("fixture") + for _, request := range []proto.PromptRequestPayload{ + {Turn: proto.TurnSettings{Model: " "}}, + {Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{"model_provider": map[string]any{"protocol": "anthropic", "base_url": "https://provider.example", "api_key": "private-sentinel"}}}, + {AgentOptions: map[string]any{"model_provider": map[string]any{"protocol": "responses", "base_url": "https://provider.example", "api_key": "private-sentinel"}}}, + {AgentOptions: map[string]any{"harness_config": map[string]any{"unknown": "private-sentinel"}}}, } { - _, err := executor(t.Context(), proto.PromptRequestPayload{AgentOptions: options}) + _, err := executor(t.Context(), request) if err == nil || errors.Is(err, expected) || calls != 0 || strings.Contains(err.Error(), "private-sentinel") { t.Fatal("invalid configuration reached native entry or leaked values") } } - if _, err := executor(t.Context(), proto.PromptRequestPayload{AgentOptions: map[string]any{"model": "fixture", "model_provider": map[string]any{"protocol": "responses", "base_url": "https://provider.example", "api_key": "private-sentinel"}}}); !errors.Is(err, expected) || calls != 1 { + if _, err := executor(t.Context(), proto.PromptRequestPayload{Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{"model_provider": map[string]any{"protocol": "responses", "base_url": "https://provider.example", "api_key": "private-sentinel"}}}); !errors.Is(err, expected) || calls != 1 { t.Fatal("bound declaration was lost or mutated", err) } } @@ -46,5 +46,5 @@ func TestRegistryRejectsInvalidConfigurationDeclaration(t *testing.T) { t.Fatal("invalid configuration registered") } }() - agent.NewRegistry().RegisterKind(proto.SupportedAgentKind{Kind: "fixture", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Configuration{Providers: []harnessconfig.Provider{{Protocol: "unknown"}}}) + agent.NewRegistry().RegisterKind(proto.SupportedAgentKind{Kind: "fixture", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Declaration{Configuration: harnessconfig.Configuration{Providers: []harnessconfig.Provider{{Protocol: "unknown"}}}}) } diff --git a/apps/daemon/internal/agent/contracttest/text.go b/apps/daemon/internal/agent/contracttest/text.go index 90e513753..9c2f95d4b 100644 --- a/apps/daemon/internal/agent/contracttest/text.go +++ b/apps/daemon/internal/agent/contracttest/text.go @@ -111,7 +111,7 @@ func start(t *testing.T, ctx context.Context, f TextFixture, id string, input pr } } }() - turn, err := f.Executor.StartTurn(ctx, id, input, out) + turn, err := f.Executor.StartTurn(ctx, id, proto.TurnSettings{}, input, out) if turn == nil { close(out) } diff --git a/apps/daemon/internal/agent/harness.go b/apps/daemon/internal/agent/harness.go index 25b5ff61e..4e1d98d45 100644 --- a/apps/daemon/internal/agent/harness.go +++ b/apps/daemon/internal/agent/harness.go @@ -78,7 +78,6 @@ func Narrow(capability *proto.CapabilitySupport, provided bool) { // DiscoveryOptions provides process context without naming an implementation. type DiscoveryOptions struct { - Profile string // StateRoot holds private history retained with the Environment filesystem. StateRoot string // RuntimeRoot holds instance-private configuration and process files. @@ -105,7 +104,7 @@ func (r *Registry) Register(declaration Declaration, runtime Runtime) { if widened := Widened(declaration.Capabilities, advertised); len(widened) > 0 { panic("agent.Registry.Register: discovery widened " + strings.Join(widened, ", ")) } - r.RegisterKind(runtime.Info, declaration.Configuration) + r.RegisterKind(runtime.Info, declaration.Declaration) if runtime.Executor != nil { r.RegisterExecutor(runtime.Info.Kind, runtime.Executor) } @@ -135,7 +134,7 @@ type Executor interface { // A nil Turn guarantees no input was submitted or output retained and leaves // out with the caller. A non-nil Turn owns out, including on error; input // may have been submitted and must never be replayed automatically. - StartTurn(context.Context, string, proto.MessageInput, chan<- proto.Envelope) (Turn, error) + StartTurn(ctx context.Context, runID string, turn proto.TurnSettings, input proto.MessageInput, out chan<- proto.Envelope) (Turn, error) // Success confirms all native work and owned output streams have stopped. // It does not establish an otherwise unknown Turn result. An error retains // resource ownership; another caller may await or retry Close. @@ -225,21 +224,21 @@ type Installation struct { // RegisterKind installs the heartbeat descriptor and model configuration for an // agent_kind. Callers may set Available=false when an adapter exists but its // underlying CLI is not usable. -func (r *Registry) RegisterKind(info proto.SupportedAgentKind, configuration harnessconfig.Configuration) { +func (r *Registry) RegisterKind(info proto.SupportedAgentKind, declaration harnessconfig.Declaration) { kind := info.Kind if kind == "" { panic("agent.Registry.Register: empty kind") } - if err := configuration.ValidateDeclaration(); err != nil { + if err := declaration.Configuration.ValidateDeclaration(); err != nil { panic(err) } if err := info.ValidateDeclaration(); err != nil { panic(err) } - configuration = configuration.Clone() + declaration.Configuration = declaration.Configuration.Clone() r.mu.Lock() defer r.mu.Unlock() - r.configurations[kind] = configuration + r.declarations[kind] = declaration delete(r.executors, kind) info.Capabilities.Preparation = proto.CapabilityUnsupported r.kinds[kind] = info @@ -254,12 +253,12 @@ func (r *Registry) RegisterExecutor(kind string, factory ExecutorFactory) { if !exists || factory == nil { panic("agent.Registry.RegisterExecutor: registered kind and factory required") } - configuration, declared := r.configurations[kind] + declaration, declared := r.declarations[kind] if !declared { panic("agent.Registry.RegisterExecutor: configuration required") } r.executors[kind] = func(ctx context.Context, req proto.PromptRequestPayload) (Executor, error) { - if _, err := configuration.Prepare(req.AgentOptions); err != nil { + if _, err := declaration.Configuration.Prepare(req.Turn.Model, req.AgentOptions); err != nil { return nil, err } return factory(ctx, req) diff --git a/apps/daemon/internal/agent/mcode/environment_mcp_test.go b/apps/daemon/internal/agent/mcode/environment_mcp_test.go index eb26734af..e4c7f941f 100644 --- a/apps/daemon/internal/agent/mcode/environment_mcp_test.go +++ b/apps/daemon/internal/agent/mcode/environment_mcp_test.go @@ -117,7 +117,7 @@ func TestEnvironmentMCPCancelSettlesPendingObservationBeforeDone(t *testing.T) { ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) defer cancel() out := make(chan proto.Envelope, 16) - session, err := resource.StartTurn(ctx, "run", proto.TextInput("invoke and wait"), out) + session, err := resource.StartTurn(ctx, "run", proto.TurnSettings{}, proto.TextInput("invoke and wait"), out) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/mcode/executor.go b/apps/daemon/internal/agent/mcode/executor.go index 9853f9d5a..879f3e497 100644 --- a/apps/daemon/internal/agent/mcode/executor.go +++ b/apps/daemon/internal/agent/mcode/executor.go @@ -105,7 +105,7 @@ func newExecutor(ctx context.Context, req proto.PromptRequestPayload, opts launc return e, nil } -func (e *executor) StartTurn(ctx context.Context, runID string, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { +func (e *executor) StartTurn(ctx context.Context, runID string, _ proto.TurnSettings, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { if ctx == nil { ctx = context.Background() } diff --git a/apps/daemon/internal/agent/mcode/executor_backpressure_test.go b/apps/daemon/internal/agent/mcode/executor_backpressure_test.go index 00bddf925..da395e1ee 100644 --- a/apps/daemon/internal/agent/mcode/executor_backpressure_test.go +++ b/apps/daemon/internal/agent/mcode/executor_backpressure_test.go @@ -14,7 +14,7 @@ func TestExecutorBlockedPromptWriteCanBeCancelledOrClosed(t *testing.T) { t.Run(operation, func(t *testing.T) { e, _ := executorFixture(t, "executor-backpressure", true) out := make(chan proto.Envelope, 32) - turn, err := e.StartTurn(t.Context(), "blocked", proto.TextInput(strings.Repeat("x", 4*1024*1024)), out) + turn, err := e.StartTurn(t.Context(), "blocked", proto.TurnSettings{}, proto.TextInput(strings.Repeat("x", 4*1024*1024)), out) if err != nil { t.Fatal(err) } @@ -66,7 +66,7 @@ func TestExecutorBlockedPromptWriteCanBeCancelledOrClosed(t *testing.T) { func TestExecutorUnknownSteeringOutcomeCannotBecomeAppliedCancellation(t *testing.T) { e, _ := executorFixture(t, "executor-steer-unknown", true) out := make(chan proto.Envelope, 32) - turn, err := e.StartTurn(t.Context(), "unknown-input", proto.TextInput("wait"), out) + turn, err := e.StartTurn(t.Context(), "unknown-input", proto.TurnSettings{}, proto.TextInput("wait"), out) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/mcode/executor_native_test.go b/apps/daemon/internal/agent/mcode/executor_native_test.go index 7f5b6afc5..6089e7a2d 100644 --- a/apps/daemon/internal/agent/mcode/executor_native_test.go +++ b/apps/daemon/internal/agent/mcode/executor_native_test.go @@ -60,7 +60,7 @@ func TestNativeMCodeExecutorReuse(t *testing.T) { run := func(id, prompt string) agent.Turn { t.Helper() out := make(chan proto.Envelope, 256) - turn, startErr := e.StartTurn(ctx, id, proto.TextInput(prompt), out) + turn, startErr := e.StartTurn(ctx, id, proto.TurnSettings{}, proto.TextInput(prompt), out) if startErr != nil || turn == nil { t.Fatal("native Turn admission failed") } @@ -96,7 +96,7 @@ func TestNativeMCodeExecutorReuse(t *testing.T) { first := run("first", "Remember the exact marker ORCHID-72-BLUE for this conversation. Reply with only that marker.") run("second", "What exact marker did I ask you to remember? Reply with only that marker.") out := make(chan proto.Envelope, 256) - interrupted, err := e.StartTurn(ctx, "cancelled", proto.TextInput("Produce 2000 numbered lines now. Each line must contain a different sentence about rain. Start immediately at line 1 and continue without stopping or summarizing."), out) + interrupted, err := e.StartTurn(ctx, "cancelled", proto.TurnSettings{}, proto.TextInput("Produce 2000 numbered lines now. Each line must contain a different sentence about rain. Start immediately at line 1 and continue without stopping or summarizing."), out) if err != nil || interrupted == nil { t.Fatal("cancellation Turn admission failed") } @@ -141,7 +141,7 @@ func TestNativeMCodeExecutorReuse(t *testing.T) { if !settlement.Reusable { t.Log("Native cancellation cannot establish reusable settlement; successor must use recovery") successor := make(chan proto.Envelope, 1) - next, nextErr := e.StartTurn(ctx, "unsafe-successor", proto.TextInput("must not execute"), successor) + next, nextErr := e.StartTurn(ctx, "unsafe-successor", proto.TurnSettings{}, proto.TextInput("must not execute"), successor) if next != nil || nextErr == nil { t.Fatal("unsettled native owner accepted a successor") } diff --git a/apps/daemon/internal/agent/mcode/executor_test.go b/apps/daemon/internal/agent/mcode/executor_test.go index c304d5bf4..8ccad2a51 100644 --- a/apps/daemon/internal/agent/mcode/executor_test.go +++ b/apps/daemon/internal/agent/mcode/executor_test.go @@ -70,7 +70,7 @@ func executorFixture(t *testing.T, scenario string, workspace bool) (*executor, func runExecutorFixtureTurn(t *testing.T, e *executor, id, text string) (*Session, []proto.Envelope) { t.Helper() out := make(chan proto.Envelope, 256) - turn, err := e.StartTurn(t.Context(), id, proto.TextInput(text), out) + turn, err := e.StartTurn(t.Context(), id, proto.TurnSettings{}, proto.TextInput(text), out) if err != nil { t.Fatal(err) } @@ -154,7 +154,7 @@ func TestExecutorCancellationRetiresOwnerAndLateCancelCannotRetarget(t *testing. t.Setenv("OAC_RUNTIME_MCODE_COMPANION", dir) } out := make(chan proto.Envelope, 32) - second, err := e.StartTurn(t.Context(), "second", proto.TextInput("wait"), out) + second, err := e.StartTurn(t.Context(), "second", proto.TurnSettings{}, proto.TextInput("wait"), out) if err != nil { t.Fatal(err) } @@ -193,7 +193,7 @@ func TestExecutorCancellationRetiresOwnerAndLateCancelCannotRetarget(t *testing. for range out { } thirdOut := make(chan proto.Envelope, 1) - third, err := e.StartTurn(t.Context(), "third", proto.TextInput("three"), thirdOut) + third, err := e.StartTurn(t.Context(), "third", proto.TurnSettings{}, proto.TextInput("three"), thirdOut) if third != nil || err == nil { t.Fatal("unproven native owner admitted a successor") } @@ -218,7 +218,7 @@ func TestExecutorStartFailureOwnership(t *testing.T) { {"attachment", "does not support image input", proto.MessageInput{{Content: []proto.InputContent{{Type: "input_image", ImageURL: &image}}}}}, } { out := make(chan proto.Envelope, 1) - turn, err := e.StartTurn(t.Context(), invalid.id, invalid.input, out) + turn, err := e.StartTurn(t.Context(), invalid.id, proto.TurnSettings{}, invalid.input, out) if err == nil || turn != nil || !strings.Contains(err.Error(), invalid.reason) { t.Fatal("invalid Start acquired output", err) } @@ -233,7 +233,7 @@ func TestExecutorStartFailureOwnership(t *testing.T) { t.Run("before input", func(t *testing.T) { e, record := executorFixture(t, "executor-preexit", true) out := make(chan proto.Envelope, 1) - turn, err := e.StartTurn(t.Context(), "run", proto.TextInput("input"), out) + turn, err := e.StartTurn(t.Context(), "run", proto.TurnSettings{}, proto.TextInput("input"), out) if err == nil || turn != nil { t.Fatal("failed readiness retained caller output") } @@ -246,7 +246,7 @@ func TestExecutorStartFailureOwnership(t *testing.T) { t.Run("after submission", func(t *testing.T) { e, record := executorFixture(t, "executor-exit", true) out := make(chan proto.Envelope, 32) - turn, err := e.StartTurn(t.Context(), "run", proto.TextInput("input"), out) + turn, err := e.StartTurn(t.Context(), "run", proto.TurnSettings{}, proto.TextInput("input"), out) if err != nil || turn == nil { t.Fatal("submitted Turn lost ownership", err) } @@ -263,7 +263,7 @@ func TestExecutorStartFailureOwnership(t *testing.T) { t.Fatal("uncertain input was replayed") } rejected := make(chan proto.Envelope) - again, err := e.StartTurn(t.Context(), "again", proto.TextInput("again"), rejected) + again, err := e.StartTurn(t.Context(), "again", proto.TurnSettings{}, proto.TextInput("again"), rejected) if again != nil || err == nil { t.Fatal("invalid owner accepted another Turn") } diff --git a/apps/daemon/internal/agent/mcode/functions_native_test.go b/apps/daemon/internal/agent/mcode/functions_native_test.go index aa8cbaafb..087236915 100644 --- a/apps/daemon/internal/agent/mcode/functions_native_test.go +++ b/apps/daemon/internal/agent/mcode/functions_native_test.go @@ -35,7 +35,7 @@ func TestNativeMCodePublicFunction(t *testing.T) { t.Fatal("native Executor preparation failed") } out := make(chan proto.Envelope, 256) - turn, err := e.StartTurn(ctx, "turn", proto.TextInput("Call the lookup_code function to get the access code, then reply with only the code."), out) + turn, err := e.StartTurn(ctx, "turn", proto.TurnSettings{}, proto.TextInput("Call the lookup_code function to get the access code, then reply with only the code."), out) if err != nil { t.Fatal("native Turn admission failed") } diff --git a/apps/daemon/internal/agent/mcode/model_provider_test.go b/apps/daemon/internal/agent/mcode/model_provider_test.go index c6dfb0cf4..c3c214370 100644 --- a/apps/daemon/internal/agent/mcode/model_provider_test.go +++ b/apps/daemon/internal/agent/mcode/model_provider_test.go @@ -16,7 +16,7 @@ func TestOptionsModelProviderProtocols(t *testing.T) { req := testRequest(t) req.AgentOptions["model_provider"].(map[string]any)["protocol"] = tc.protocol req.AgentOptions["model_provider"].(map[string]any)["headers"] = map[string]string{"X-Activity": "private-header"} - req.AgentOptions["model"] = "chosen-model" + req.Turn.Model = "chosen-model" opts, err := prepareOptions(testStateRoot(t), req, nil) if err != nil { t.Fatal(err) @@ -121,7 +121,7 @@ func TestOptionsAllowLoopbackProviderFixture(t *testing.T) { func TestOptionsWriteNativeThinkingEffort(t *testing.T) { req := testRequest(t) - req.ExecutionControls.ReasoningEffort = "high" + req.Turn.ReasoningEffort = "high" opts, err := prepareOptions(testStateRoot(t), req, nil) if err != nil { t.Fatal(err) diff --git a/apps/daemon/internal/agent/mcode/native_effort_mcp_test.go b/apps/daemon/internal/agent/mcode/native_effort_mcp_test.go index 60cfa4c94..91c497aeb 100644 --- a/apps/daemon/internal/agent/mcode/native_effort_mcp_test.go +++ b/apps/daemon/internal/agent/mcode/native_effort_mcp_test.go @@ -94,7 +94,7 @@ func TestNativeMCodeEffortMCPAndPlainText(t *testing.T) { })) defer mcp.Close() - req.ExecutionControls.ReasoningEffort = "high" + req.Turn.ReasoningEffort = "high" req.MCPHTTPServers = &[]proto.MCPHTTPServer{{ConnectionOrigin: "service", ServerLabel: "fixture", ServerURL: mcp.URL + "/mcp"}} value, err := NewExecutorFactory(testStateRoot(t), nil)(ctx, req) if err != nil { @@ -107,7 +107,7 @@ func TestNativeMCodeEffortMCPAndPlainText(t *testing.T) { _ = e.Close(cleanup) }() out := make(chan proto.Envelope, 256) - turn, err := e.StartTurn(ctx, "turn", proto.TextInput("Use the MCP tool to get the access code, then reply with only the code."), out) + turn, err := e.StartTurn(ctx, "turn", proto.TurnSettings{}, proto.TextInput("Use the MCP tool to get the access code, then reply with only the code."), out) if err != nil { t.Fatal("native Turn admission failed") } diff --git a/apps/daemon/internal/agent/mcode/options.go b/apps/daemon/internal/agent/mcode/options.go index 8fb9e5fce..362987bb0 100644 --- a/apps/daemon/internal/agent/mcode/options.go +++ b/apps/daemon/internal/agent/mcode/options.go @@ -55,15 +55,11 @@ func prepareOptions(runtimeRoot string, req proto.PromptRequestPayload, workspac return result, err } config := map[string]any{} - effort := "" - if req.ExecutionControls != nil { - effort = req.ExecutionControls.ReasoningEffort - } - result.Model = optionString(opts, "model") + result.Model = req.Turn.Model if result.Model == "" { return result, fmt.Errorf("mcode: model is required") } - provider, err := modelProviderConfig(opts["model_provider"], result.Model, effort) + provider, err := modelProviderConfig(opts["model_provider"], result.Model, req.Turn.ReasoningEffort) if err != nil { return result, err } diff --git a/apps/daemon/internal/agent/mcode/options_test.go b/apps/daemon/internal/agent/mcode/options_test.go index 027b5a961..acc270a04 100644 --- a/apps/daemon/internal/agent/mcode/options_test.go +++ b/apps/daemon/internal/agent/mcode/options_test.go @@ -67,7 +67,7 @@ func TestOptionsRejectDroppedContext(t *testing.T) { name string edit func(*proto.PromptRequestPayload) }{ - {"missing model", func(r *proto.PromptRequestPayload) { delete(r.AgentOptions, "model") }}, + {"missing model", func(r *proto.PromptRequestPayload) { r.Turn.Model = "" }}, {"missing provider", func(r *proto.PromptRequestPayload) { delete(r.AgentOptions, "model_provider") }}, } for _, tt := range tests { diff --git a/apps/daemon/internal/agent/mcode/session.go b/apps/daemon/internal/agent/mcode/session.go index 826214f7d..bf4d3f838 100644 --- a/apps/daemon/internal/agent/mcode/session.go +++ b/apps/daemon/internal/agent/mcode/session.go @@ -112,7 +112,7 @@ func (s *Session) prepareNative() error { s.mu.Unlock() // A model with effort options is advertised only with its "thinking" variant. variant := "" - if s.req.ExecutionControls != nil && s.req.ExecutionControls.ReasoningEffort != "" { + if s.req.Turn.ReasoningEffort != "" { variant = "thinking" } model, err := advertisedModel(session.ConfigOptions, s.opts.Model, variant) @@ -130,7 +130,7 @@ func (s *Session) prepareNative() error { } if variant != "" { // A selected variant takes no model default, so the Session's effort is set explicitly. - return s.call("session/set_config_option", map[string]any{"sessionId": session.SessionID, "configId": "thinkingEffort", "value": s.req.ExecutionControls.ReasoningEffort}, nil, false) + return s.call("session/set_config_option", map[string]any{"sessionId": session.SessionID, "configId": "thinkingEffort", "value": s.req.Turn.ReasoningEffort}, nil, false) } return nil } diff --git a/apps/daemon/internal/agent/mcode/session_test.go b/apps/daemon/internal/agent/mcode/session_test.go index c080aa50c..15e1ab44e 100644 --- a/apps/daemon/internal/agent/mcode/session_test.go +++ b/apps/daemon/internal/agent/mcode/session_test.go @@ -18,8 +18,8 @@ import ( func testRequest(t *testing.T) proto.PromptRequestPayload { t.Helper() t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) - return proto.PromptRequestPayload{RunID: "run-1", AgentStateKey: "conversation-1/agent-1/mcode", Input: proto.TextInput("Hello"), AgentOptions: map[string]any{ - "model": "fixture", "model_provider": map[string]any{"protocol": "anthropic", "base_url": "https://provider.example/v1", "api_key": "fixture-key", "context_window": 64000, "max_output_tokens": 4096}, "system_prompt": "Current instructions", + return proto.PromptRequestPayload{RunID: "run-1", AgentStateKey: "conversation-1/agent-1/mcode", Input: proto.TextInput("Hello"), Turn: proto.TurnSettings{Model: "fixture"}, AgentOptions: map[string]any{ + "model_provider": map[string]any{"protocol": "anthropic", "base_url": "https://provider.example/v1", "api_key": "fixture-key", "context_window": 64000, "max_output_tokens": 4096}, "system_prompt": "Current instructions", }, DisableExecutionEnvironment: true, DisableSubagents: true, ExecutionControls: &proto.ExecutionControls{TextVerbosity: "medium"}} } @@ -71,7 +71,7 @@ func startTurn(t *testing.T, ctx context.Context, req proto.PromptRequestPayload if err != nil { return nil, err } - turn, err := e.StartTurn(ctx, req.RunID, req.Input, out) + turn, err := e.StartTurn(ctx, req.RunID, proto.TurnSettings{}, req.Input, out) if err != nil { return nil, err } diff --git a/apps/daemon/internal/agent/mcode/subagents_test.go b/apps/daemon/internal/agent/mcode/subagents_test.go index e82e4f3b9..121385b36 100644 --- a/apps/daemon/internal/agent/mcode/subagents_test.go +++ b/apps/daemon/internal/agent/mcode/subagents_test.go @@ -90,7 +90,11 @@ func TestSubagentSettlementIncludesActiveRootTurn(t *testing.T) { if err := os.WriteFile(filepath.Join(dir, "snapshot.json"), raw, 0600); err != nil { t.Fatal(err) } - ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) + deadline := 3 * time.Second + if status == "accepted" { + deadline = 100 * time.Millisecond + } + ctx, cancel := context.WithTimeout(t.Context(), deadline) defer cancel() s := &Session{ctx: ctx, sessionID: "root", opts: launchOptions{DataDir: dir}, frames: make(chan rpcFrame)} err := s.settleSubagents() diff --git a/apps/daemon/internal/agent/mcode/tool_environment_test.go b/apps/daemon/internal/agent/mcode/tool_environment_test.go index ad8a50b2c..7bd51aeb1 100644 --- a/apps/daemon/internal/agent/mcode/tool_environment_test.go +++ b/apps/daemon/internal/agent/mcode/tool_environment_test.go @@ -44,7 +44,7 @@ func TestWorkspaceCredentialsRemainInRuntimeSnapshotAcrossReconnect(t *testing.T req.AgentSessionID = "native-1" write(source, `{"MCP_TEST_TOKEN":"changed","TOOL_SECRET":"changed"}`) } - binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, config.Directory, capabilityDirectory) + binding, err := localworkspace.NewWithCapabilityDirectory(environment, config.Directory, capabilityDirectory) if err != nil { t.Fatal(err) } @@ -97,7 +97,7 @@ func TestWorkspaceCredentialsRemainInRuntimeSnapshotAcrossReconnect(t *testing.T if err := os.Remove(filepath.Join(initialization, "tool-env.json")); err != nil { t.Fatal(err) } - binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, config.Directory, capabilityDirectory) + binding, err := localworkspace.NewWithCapabilityDirectory(environment, config.Directory, capabilityDirectory) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/mcode/workspace_native_test.go b/apps/daemon/internal/agent/mcode/workspace_native_test.go index d9639eed1..95df6530d 100644 --- a/apps/daemon/internal/agent/mcode/workspace_native_test.go +++ b/apps/daemon/internal/agent/mcode/workspace_native_test.go @@ -75,7 +75,7 @@ func TestNativeMCodeWorkspaceTools(t *testing.T) { } }() out := make(chan proto.Envelope, 1024) - turn, err := e.StartTurn(ctx, "turn", proto.TextInput(prompt), out) + turn, err := e.StartTurn(ctx, "turn", proto.TurnSettings{}, proto.TextInput(prompt), out) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/agent/registry.go b/apps/daemon/internal/agent/registry.go index c6998e918..bc3240297 100644 --- a/apps/daemon/internal/agent/registry.go +++ b/apps/daemon/internal/agent/registry.go @@ -12,17 +12,17 @@ import ( // Registry keeps the daemon-advertised capability descriptor and execution // factories for each agent_kind. Safe for concurrent use. type Registry struct { - mu sync.RWMutex - executors map[string]ExecutorFactory - kinds map[string]proto.SupportedAgentKind - configurations map[string]harnessconfig.Configuration + mu sync.RWMutex + executors map[string]ExecutorFactory + kinds map[string]proto.SupportedAgentKind + declarations map[string]harnessconfig.Declaration } func NewRegistry() *Registry { return &Registry{ - executors: make(map[string]ExecutorFactory), - kinds: make(map[string]proto.SupportedAgentKind), - configurations: make(map[string]harnessconfig.Configuration), + executors: make(map[string]ExecutorFactory), + kinds: make(map[string]proto.SupportedAgentKind), + declarations: make(map[string]harnessconfig.Declaration), } } @@ -47,12 +47,14 @@ func (r *Registry) SupportedAgentKinds() []proto.SupportedAgentKind { return out } -func (r *Registry) ResolveExecutor(kind string) (ExecutorFactory, error) { +// ResolveExecutor returns the factory of a kind and the declaration it was +// registered with. +func (r *Registry) ResolveExecutor(kind string) (ExecutorFactory, harnessconfig.Declaration, error) { r.mu.RLock() defer r.mu.RUnlock() factory := r.executors[kind] if factory == nil { - return nil, fmt.Errorf("agent: executor unavailable for %q", kind) + return nil, harnessconfig.Declaration{}, fmt.Errorf("agent: executor unavailable for %q", kind) } - return factory, nil + return factory, r.declarations[kind], nil } diff --git a/apps/daemon/internal/agent/registry_test.go b/apps/daemon/internal/agent/registry_test.go index 04ffc9420..2d51b33f8 100644 --- a/apps/daemon/internal/agent/registry_test.go +++ b/apps/daemon/internal/agent/registry_test.go @@ -15,8 +15,8 @@ import ( func TestRegistryRegisterOverwritesDescriptor(t *testing.T) { reg := agent.NewRegistry() - reg.RegisterKind(proto.SupportedAgentKind{Kind: "k", Available: true, Version: "v1", Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Configuration{}) - reg.RegisterKind(proto.SupportedAgentKind{Kind: "k", Available: true, Version: "v2", Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Configuration{}) + reg.RegisterKind(proto.SupportedAgentKind{Kind: "k", Available: true, Version: "v1", Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Declaration{}) + reg.RegisterKind(proto.SupportedAgentKind{Kind: "k", Available: true, Version: "v2", Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Declaration{}) got := reg.SupportedAgentKinds() if len(got) != 1 || got[0].Version != "v2" { @@ -30,7 +30,7 @@ func TestRegistryRegisterPanicsOnEmptyKind(t *testing.T) { t.Fatal("Register(\"\", ...) did not panic") } }() - agent.NewRegistry().RegisterKind(proto.SupportedAgentKind{Kind: "", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Configuration{}) + agent.NewRegistry().RegisterKind(proto.SupportedAgentKind{Kind: "", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Declaration{}) } func TestRegistryRegisterRejectsFactoriesForUnavailableRuntime(t *testing.T) { @@ -75,7 +75,7 @@ func TestRegistrySupportedAgentKindsReportsDescriptors(t *testing.T) { Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{ Streaming: proto.CapabilitySupported, }), - }, harnessconfig.Configuration{}) + }, harnessconfig.Declaration{}) reg.RegisterKind(proto.SupportedAgentKind{ Kind: "fake_alpha", Available: true, @@ -85,7 +85,7 @@ func TestRegistrySupportedAgentKindsReportsDescriptors(t *testing.T) { Usage: proto.CapabilitySupported, Resume: proto.CapabilitySupported, }), - }, harnessconfig.Configuration{}) + }, harnessconfig.Declaration{}) got := reg.SupportedAgentKinds() if len(got) != 2 { @@ -104,21 +104,21 @@ func TestRegistrySupportedAgentKindsReportsDescriptors(t *testing.T) { func TestRegistryExecutorRequiresExplicitRegistration(t *testing.T) { registry := agent.NewRegistry() - registry.RegisterKind(proto.SupportedAgentKind{Kind: "native", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Configuration{}) - if _, err := registry.ResolveExecutor("native"); err == nil { + registry.RegisterKind(proto.SupportedAgentKind{Kind: "native", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Declaration{}) + if _, _, err := registry.ResolveExecutor("native"); err == nil { t.Fatal("kind registration implied reusable execution") } expected := errors.New("executor factory") registry.RegisterExecutor("native", func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { return nil, expected }) - factory, err := registry.ResolveExecutor("native") + factory, _, err := registry.ResolveExecutor("native") if err != nil { t.Fatal(err) } if _, err := factory(t.Context(), proto.PromptRequestPayload{}); !errors.Is(err, expected) { t.Fatal(err) } - registry.RegisterKind(proto.SupportedAgentKind{Kind: "native", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Configuration{}) - if _, err := registry.ResolveExecutor("native"); err == nil { + registry.RegisterKind(proto.SupportedAgentKind{Kind: "native", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{})}, harnessconfig.Declaration{}) + if _, _, err := registry.ResolveExecutor("native"); err == nil { t.Fatal("replacing a kind retained its old executor capability") } } @@ -129,7 +129,7 @@ func TestRegistryRejectsEveryOmittedCapabilityBeforeReplacement(t *testing.T) { t.Run(reflect.TypeOf(valid).Field(i).Name, func(t *testing.T) { registry := agent.NewRegistry() original := proto.SupportedAgentKind{Kind: "fixture", Available: true, Capabilities: valid} - registry.RegisterKind(original, harnessconfig.Configuration{}) + registry.RegisterKind(original, harnessconfig.Declaration{}) registry.RegisterExecutor("fixture", func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { return nil, nil }) original.Capabilities.Preparation = proto.CapabilitySupported missing := valid @@ -140,9 +140,9 @@ func TestRegistryRejectsEveryOmittedCapabilityBeforeReplacement(t *testing.T) { t.Error("incomplete declaration registered") } }() - registry.RegisterKind(proto.SupportedAgentKind{Kind: "fixture", Available: false, Capabilities: missing}, harnessconfig.Configuration{}) + registry.RegisterKind(proto.SupportedAgentKind{Kind: "fixture", Available: false, Capabilities: missing}, harnessconfig.Declaration{}) }() - if _, err := registry.ResolveExecutor("fixture"); err != nil || !reflect.DeepEqual(registry.SupportedAgentKinds(), []proto.SupportedAgentKind{original}) { + if _, _, err := registry.ResolveExecutor("fixture"); err != nil || !reflect.DeepEqual(registry.SupportedAgentKinds(), []proto.SupportedAgentKind{original}) { t.Fatal("failed declaration changed registry") } }) diff --git a/apps/daemon/internal/agent/runtime_paths.go b/apps/daemon/internal/agent/runtime_paths.go index ce61e9a89..56f270e43 100644 --- a/apps/daemon/internal/agent/runtime_paths.go +++ b/apps/daemon/internal/agent/runtime_paths.go @@ -2,6 +2,7 @@ package agent import ( "fmt" + "os" "path/filepath" "strings" ) @@ -9,18 +10,29 @@ import ( // StateDir returns an adapter-owned state directory scoped to one agent // state. It never derives runtime state from the subprocess cwd. func StateDir(root, agentKind, agentStateKey string) (string, error) { - if !filepath.IsAbs(root) || filepath.Clean(root) != root { - return "", fmt.Errorf("agent: state root must be a clean absolute directory") - } kind := safeRuntimePathPart(agentKind) if kind == "" { return "", fmt.Errorf("agent: invalid agent kind %q", agentKind) } + return sessionPath(root, filepath.Join("runtime", kind, "state"), agentStateKey) +} + +// CodexHistoryDir preserves the absolute paths recorded in native rollouts and indexes. +func CodexHistoryDir(root, agentStateKey string) (string, error) { + return sessionPath(root, codexHistoryDirectory, agentStateKey) +} + +const codexHistoryDirectory = "daemon/agent-sessions" + +func sessionPath(root, directory, agentStateKey string) (string, error) { + if !filepath.IsAbs(root) || filepath.Clean(root) != root { + return "", fmt.Errorf("agent: state root must be a clean absolute directory") + } parts := safeRuntimePathParts(agentStateKey) if len(parts) == 0 { return "", fmt.Errorf("agent: invalid agent state key %q", agentStateKey) } - return filepath.Join(append([]string{root, "runtime", kind, "state"}, parts...)...), nil + return filepath.Join(append([]string{root, directory}, parts...)...), nil } func safeRuntimePathParts(value string) []string { @@ -49,3 +61,50 @@ func safeRuntimePathPart(value string) string { } return value } + +// RemoveSessionState deletes the state directory of every key but keepKey under +// both roots, for every agent kind. It lists directories instead of tracking +// Sessions, so it also covers state left by earlier processes and checkpoints. +func RemoveSessionState(stateRoot, runtimeRoot, keepKey string) error { + keep := safeRuntimePathParts(keepKey) + if len(keep) != 1 { + return fmt.Errorf("agent: invalid agent state key %q", keepKey) + } + for _, root := range []string{stateRoot, runtimeRoot} { + if !filepath.IsAbs(root) || filepath.Clean(root) != root { + return fmt.Errorf("agent: state root must be a clean absolute directory") + } + kinds, err := os.ReadDir(filepath.Join(root, "runtime")) + if err != nil && !os.IsNotExist(err) { + return err + } + for _, kind := range kinds { + if !kind.IsDir() { + continue + } + states := filepath.Join(root, "runtime", kind.Name(), "state") + if err := removeOtherStateKeys(states, keep[0]); err != nil { + return err + } + } + if err := removeOtherStateKeys(filepath.Join(root, codexHistoryDirectory), keep[0]); err != nil { + return err + } + } + return nil +} + +func removeOtherStateKeys(states, keep string) error { + entries, err := os.ReadDir(states) + if err != nil && !os.IsNotExist(err) { + return err + } + for _, entry := range entries { + if entry.Name() != keep { + if err := os.RemoveAll(filepath.Join(states, entry.Name())); err != nil { + return err + } + } + } + return nil +} diff --git a/apps/daemon/internal/agent/runtime_paths_test.go b/apps/daemon/internal/agent/runtime_paths_test.go index 7abd9ebd8..75fe05338 100644 --- a/apps/daemon/internal/agent/runtime_paths_test.go +++ b/apps/daemon/internal/agent/runtime_paths_test.go @@ -1,6 +1,7 @@ package agent import ( + "os" "path/filepath" "testing" ) @@ -31,3 +32,76 @@ func TestStateDirRequiresAgentState(t *testing.T) { t.Fatalf("sanitized state = %q, %v; want %q", got, err, want) } } + +func TestRemoveSessionStateKeepsCurrentBetaCodexHistory(t *testing.T) { + stateRoot, runtimeRoot := t.TempDir(), t.TempDir() + const keep = "agents-api-11111111-1111-4111-8111-111111111111" + const other = "agents-api-22222222-2222-4222-8222-222222222222" + for _, root := range []string{stateRoot, runtimeRoot} { + for _, key := range []string{keep, other} { + dir := filepath.Join(root, "daemon", "agent-sessions", key) + got, err := CodexHistoryDir(root, key) + if err != nil || got != dir { + t.Fatalf("Codex history directory = %q, %v; want %q", got, err, dir) + } + if err := os.MkdirAll(dir, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "history"), []byte(key), 0600); err != nil { + t.Fatal(err) + } + } + } + if err := RemoveSessionState(stateRoot, runtimeRoot, keep); err != nil { + t.Fatal(err) + } + for _, root := range []string{stateRoot, runtimeRoot} { + base := filepath.Join(root, "daemon", "agent-sessions") + body, err := os.ReadFile(filepath.Join(base, keep, "history")) + if err != nil || string(body) != keep { + t.Fatalf("current history lost: %v", err) + } + if _, err := os.Stat(filepath.Join(base, other)); !os.IsNotExist(err) { + t.Fatalf("other session history remains: %v", err) + } + } +} + +func TestRemoveSessionStateKeepsOnlyTheNamedKey(t *testing.T) { + stateRoot, runtimeRoot := t.TempDir(), t.TempDir() + var kept, removed []string + for _, root := range []string{stateRoot, runtimeRoot} { + for _, kind := range []string{"codex", "claude-sdk"} { + keep, err := StateDir(root, kind, "keep") + if err != nil { + t.Fatal(err) + } + other, _ := StateDir(root, kind, "other") + for _, dir := range []string{keep, other} { + if err := os.MkdirAll(filepath.Join(dir, "history"), 0o700); err != nil { + t.Fatal(err) + } + } + kept, removed = append(kept, keep), append(removed, other) + } + } + if err := os.WriteFile(filepath.Join(stateRoot, "runtime", ".DS_Store"), nil, 0o600); err != nil { + t.Fatal(err) + } + if err := RemoveSessionState(stateRoot, runtimeRoot, "keep"); err != nil { + t.Fatal(err) + } + for _, dir := range kept { + if _, err := os.Stat(dir); err != nil { + t.Fatalf("kept state removed: %v", err) + } + } + for _, dir := range removed { + if _, err := os.Stat(dir); !os.IsNotExist(err) { + t.Fatalf("other state kept: %s", dir) + } + } + if err := RemoveSessionState(t.TempDir(), t.TempDir(), "keep"); err != nil { + t.Fatalf("empty roots: %v", err) + } +} diff --git a/apps/daemon/internal/cli/agent_discovery.go b/apps/daemon/internal/cli/agent_discovery.go index 06c88d697..9f2072267 100644 --- a/apps/daemon/internal/cli/agent_discovery.go +++ b/apps/daemon/internal/cli/agent_discovery.go @@ -45,7 +45,7 @@ func discoverAgentCLIs(parent context.Context, rc *runContext, profile string, d running.Go(func() { p := &probes[i] started := time.Now() - p.runtime = declaration.Discover(parent, agent.DiscoveryOptions{Profile: profile, StateRoot: stateRoot, RuntimeRoot: runtimeRoot, Stdout: &p.stdout, Stderr: &p.stderr}, declaration.Info()) + p.runtime = declaration.Discover(parent, agent.DiscoveryOptions{StateRoot: stateRoot, RuntimeRoot: runtimeRoot, Stdout: &p.stdout, Stderr: &p.stderr}, declaration.Info()) obslog.Ctx(parent).Info("runtime startup stage", "stage", "harness_discovery", "harness_kind", declaration.Kind, "duration_ms", float64(time.Since(started))/float64(time.Millisecond), "available", p.runtime != nil && p.runtime.Info.Available) }) } diff --git a/apps/daemon/internal/cli/connect_bootstrap.go b/apps/daemon/internal/cli/connect_bootstrap.go index 196a4e7e7..22a9a97de 100644 --- a/apps/daemon/internal/cli/connect_bootstrap.go +++ b/apps/daemon/internal/cli/connect_bootstrap.go @@ -19,9 +19,11 @@ func bootstrapProfile(path string, rc *runContext) (*auth.Profile, bool, error) if err != nil { return nil, false, err } - if err = localworkspace.Bind(input.EnvironmentID, input.SessionID, input.Workspace, localworkspace.CapabilityDirectory); err != nil { + if err = localworkspace.Bind(input.EnvironmentID, input.Workspace, localworkspace.CapabilityDirectory); err != nil { return nil, false, errors.New("connect: Runtime workspace binding unavailable") } - rc.installedKinds = map[string]bool{input.Harness: true} + if input.Harness != "" { + rc.installedKinds = map[string]bool{input.Harness: true} + } return &auth.Profile{ServerURL: input.CoreURL, RuntimeID: input.DeviceID, RunnerCredential: input.Credential}, input.SuspendControl, nil } diff --git a/apps/daemon/internal/cli/connect_bootstrap_test.go b/apps/daemon/internal/cli/connect_bootstrap_test.go index c8155ed2e..e4ad9ef8a 100644 --- a/apps/daemon/internal/cli/connect_bootstrap_test.go +++ b/apps/daemon/internal/cli/connect_bootstrap_test.go @@ -34,7 +34,7 @@ func TestBootstrapConnectionDoesNotReadOrOverwritePrivateProfile(t *testing.T) { t.Fatal(err) } input := runtimebootstrap.Connection{Version: runtimebootstrap.Version, Harness: "codex", CoreURL: "https://core.example/api/v1", DeviceID: "da912024-1543-4242-a2c1-5f4f7ebbc6c7", Credential: "bootstrap-secret", - EnvironmentID: uuid.NewString(), SessionID: uuid.NewString(), Workspace: t.TempDir()} + EnvironmentID: uuid.NewString(), Workspace: t.TempDir()} raw, err := input.Marshal() if err != nil { t.Fatal(err) diff --git a/apps/daemon/internal/cli/connect_cleanup_test.go b/apps/daemon/internal/cli/connect_cleanup_test.go index e5122a48c..b3cf6c493 100644 --- a/apps/daemon/internal/cli/connect_cleanup_test.go +++ b/apps/daemon/internal/cli/connect_cleanup_test.go @@ -76,7 +76,7 @@ type cleanupExecutor struct { confirm chan struct{} } -func (e *cleanupExecutor) StartTurn(_ context.Context, _ string, _ proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { +func (e *cleanupExecutor) StartTurn(_ context.Context, _ string, _ proto.TurnSettings, _ proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { if e.started == nil { return nil, errors.New("unexpected Turn") } @@ -150,7 +150,7 @@ func testDisconnectedPumpCleanup(t *testing.T, suspend, silent bool) { owner.cancelled = make(chan struct{}) } registry := agent.NewRegistry() - registry.RegisterKind(proto.SupportedAgentKind{Kind: "cleanup", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{EnvironmentNone: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + registry.RegisterKind(proto.SupportedAgentKind{Kind: "cleanup", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{EnvironmentNone: proto.CapabilitySupported})}, harnessconfig.Declaration{}) var factories atomic.Int32 registry.RegisterExecutor("cleanup", func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { factories.Add(1) diff --git a/apps/daemon/internal/cli/connect_environment_binding.go b/apps/daemon/internal/cli/connect_environment_binding.go index a9371407f..a533754dc 100644 --- a/apps/daemon/internal/cli/connect_environment_binding.go +++ b/apps/daemon/internal/cli/connect_environment_binding.go @@ -62,7 +62,7 @@ func bindEnvironmentRuntime(remote string, bound machineapi.Enrollment, workspac if bound.WorkspaceDirectory != runtimebootstrap.PublicWorkspace && bound.WorkspaceDirectory != workspace { return errors.New("connect: enrollment does not match the Runtime workspace") } - if err := localworkspace.Bind(bound.EnvironmentID, bound.SessionID, workspace, capabilityDirectory); err != nil { + if err := localworkspace.Bind(bound.EnvironmentID, workspace, capabilityDirectory); err != nil { return errors.New("connect: local Runtime layout unavailable") } return saveEnvironmentBinding(root, environmentBinding{RemoteURL: remote, Enrollment: bound, LocalWorkspace: workspace, CapabilityDirectory: capabilityDirectory}) diff --git a/apps/daemon/internal/cli/connect_environment_binding_test.go b/apps/daemon/internal/cli/connect_environment_binding_test.go index df7b7b4cd..87f37e15e 100644 --- a/apps/daemon/internal/cli/connect_environment_binding_test.go +++ b/apps/daemon/internal/cli/connect_environment_binding_test.go @@ -26,7 +26,7 @@ func environmentRuntimeFixture(t *testing.T) (root, workspace, credential string } t.Setenv("OAC_RUNTIME_HOME", root) t.Cleanup(localworkspace.Unbind) - return root, workspace, credential, machineapi.Enrollment{DeviceID: uuid.NewString(), SessionID: uuid.NewString(), EnvironmentID: uuid.NewString(), WorkspaceDirectory: "/workspace"} + return root, workspace, credential, machineapi.Enrollment{DeviceID: uuid.NewString(), EnvironmentID: uuid.NewString(), WorkspaceDirectory: "/workspace"} } func TestBindEnvironmentRuntimeUsesCanonicalOperatorWorkspace(t *testing.T) { @@ -48,7 +48,7 @@ func TestBindEnvironmentRuntimeUsesCanonicalOperatorWorkspace(t *testing.T) { t.Fatal("workspace identity changed", receipt) } if err := bindEnvironmentRuntime(receipt.RemoteURL, bound, workspace, localworkspace.CapabilityDirectory); err != nil { - t.Fatal("same binding refused", err) + t.Fatal("same Environment refused on rebind", err) } replacement := filepath.Join(filepath.Dir(workspace), "replacement") if err := os.Mkdir(replacement, 0700); err != nil { diff --git a/apps/daemon/internal/cli/connect_environment_test.go b/apps/daemon/internal/cli/connect_environment_test.go index fe704a709..d4a19c9c3 100644 --- a/apps/daemon/internal/cli/connect_environment_test.go +++ b/apps/daemon/internal/cli/connect_environment_test.go @@ -33,7 +33,7 @@ func TestEnvironmentConnectionURL(t *testing.T) { func TestEnvironmentEnrollmentAndBootstrap(t *testing.T) { environment := uuid.NewString() - want := machineapi.Enrollment{DeviceID: uuid.NewString(), SessionID: uuid.NewString(), EnvironmentID: environment, WorkspaceDirectory: "/workspace"} + want := machineapi.Enrollment{DeviceID: uuid.NewString(), EnvironmentID: environment, WorkspaceDirectory: "/workspace"} var remote string var enrolls, bootstraps int server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -156,11 +156,11 @@ func TestEnvironmentBindingPreservesIdentityAndHistory(t *testing.T) { if err := os.Chmod(root, 0700); err != nil { t.Fatal(err) } - want := environmentBinding{"wss://core/api/v1/agent-daemon/ws", machineapi.Enrollment{DeviceID: uuid.NewString(), SessionID: uuid.NewString(), EnvironmentID: uuid.NewString(), WorkspaceDirectory: "/workspace"}, "/environment/workspace", "/environment/initialization/capabilities"} + want := environmentBinding{"wss://core/api/v1/agent-daemon/ws", machineapi.Enrollment{DeviceID: uuid.NewString(), EnvironmentID: uuid.NewString(), WorkspaceDirectory: "/workspace"}, "/environment/workspace", "/environment/initialization/capabilities"} if err := saveEnvironmentBinding(root, want); err != nil { t.Fatal(err) } - history := filepath.Join(root, "daemon", "agent-sessions", "retained") + history := filepath.Join(root, "runtime", "codex", "state", "retained") if err := os.MkdirAll(filepath.Dir(history), 0700); err != nil { t.Fatal(err) } @@ -170,7 +170,7 @@ func TestEnvironmentBindingPreservesIdentityAndHistory(t *testing.T) { if err := saveEnvironmentBinding(root, want); err != nil { t.Fatal(err) } - for _, mutate := range []func(*environmentBinding){func(b *environmentBinding) { b.Enrollment.SessionID = uuid.NewString() }, func(b *environmentBinding) { b.Enrollment.EnvironmentID = uuid.NewString() }, func(b *environmentBinding) { b.Enrollment.DeviceID = uuid.NewString() }, func(b *environmentBinding) { b.RemoteURL = "wss://other/api/v1/agent-daemon/ws" }} { + for _, mutate := range []func(*environmentBinding){func(b *environmentBinding) { b.Enrollment.EnvironmentID = uuid.NewString() }, func(b *environmentBinding) { b.Enrollment.DeviceID = uuid.NewString() }, func(b *environmentBinding) { b.RemoteURL = "wss://other/api/v1/agent-daemon/ws" }} { changed := want mutate(&changed) if err := saveEnvironmentBinding(root, changed); err == nil { @@ -193,7 +193,7 @@ func TestEnvironmentBindingAllowsOperatorFilePermissions(t *testing.T) { if err := os.Chmod(root, 0700); err != nil { t.Fatal(err) } - want := environmentBinding{"wss://core/api/v1/agent-daemon/ws", machineapi.Enrollment{DeviceID: uuid.NewString(), SessionID: uuid.NewString(), EnvironmentID: uuid.NewString(), WorkspaceDirectory: "/workspace"}, "/environment/workspace", "/environment/initialization/capabilities"} + want := environmentBinding{"wss://core/api/v1/agent-daemon/ws", machineapi.Enrollment{DeviceID: uuid.NewString(), EnvironmentID: uuid.NewString(), WorkspaceDirectory: "/workspace"}, "/environment/workspace", "/environment/initialization/capabilities"} if err := os.WriteFile(filepath.Join(root, "installed-bundle"), []byte("bundle"), 0600); err != nil { t.Fatal(err) } @@ -215,7 +215,7 @@ func TestEnvironmentTargetCheckedBeforeCredentialTransmission(t *testing.T) { t.Fatal(err) } t.Setenv("OAC_RUNTIME_HOME", root) - want := environmentBinding{"wss://core/api/v1/agent-daemon/ws", machineapi.Enrollment{DeviceID: uuid.NewString(), SessionID: uuid.NewString(), EnvironmentID: uuid.NewString(), WorkspaceDirectory: "/workspace"}, "/environment/workspace", "/environment/initialization/capabilities"} + want := environmentBinding{"wss://core/api/v1/agent-daemon/ws", machineapi.Enrollment{DeviceID: uuid.NewString(), EnvironmentID: uuid.NewString(), WorkspaceDirectory: "/workspace"}, "/environment/workspace", "/environment/initialization/capabilities"} if err := saveEnvironmentBinding(root, want); err != nil { t.Fatal(err) } @@ -232,8 +232,8 @@ func TestEnvironmentTargetCheckedBeforeCredentialTransmission(t *testing.T) { func TestEnvironmentEnrollmentRejectsWrongIdentityAndWorkspace(t *testing.T) { environment := uuid.NewString() - good := machineapi.Enrollment{DeviceID: uuid.NewString(), SessionID: uuid.NewString(), EnvironmentID: environment, WorkspaceDirectory: "/workspace"} - for _, mutate := range []func(*machineapi.Enrollment){func(b *machineapi.Enrollment) { b.EnvironmentID = uuid.NewString() }, func(b *machineapi.Enrollment) { b.DeviceID = "" }, func(b *machineapi.Enrollment) { b.SessionID = "invalid" }, func(b *machineapi.Enrollment) { b.WorkspaceDirectory = "relative" }} { + good := machineapi.Enrollment{DeviceID: uuid.NewString(), EnvironmentID: environment, WorkspaceDirectory: "/workspace"} + for _, mutate := range []func(*machineapi.Enrollment){func(b *machineapi.Enrollment) { b.EnvironmentID = uuid.NewString() }, func(b *machineapi.Enrollment) { b.DeviceID = "" }, func(b *machineapi.Enrollment) { b.WorkspaceDirectory = "relative" }} { bad := good mutate(&bad) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(bad) })) @@ -247,7 +247,7 @@ func TestEnvironmentEnrollmentRejectsWrongIdentityAndWorkspace(t *testing.T) { func TestEnvironmentEnrollmentAcceptsPhysicalWorkspaceSelection(t *testing.T) { environment := uuid.NewString() - want := machineapi.Enrollment{DeviceID: uuid.NewString(), SessionID: uuid.NewString(), EnvironmentID: environment, WorkspaceDirectory: "/srv/runtime/workspace"} + want := machineapi.Enrollment{DeviceID: uuid.NewString(), EnvironmentID: environment, WorkspaceDirectory: "/srv/runtime/workspace"} server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(want) })) defer server.Close() actual, err := enrollEnvironment(t.Context(), environmentClient(), server.URL, environment, "secret") diff --git a/apps/daemon/internal/cli/connect_heartbeat_test.go b/apps/daemon/internal/cli/connect_heartbeat_test.go index cc29ac3d4..16a598f0f 100644 --- a/apps/daemon/internal/cli/connect_heartbeat_test.go +++ b/apps/daemon/internal/cli/connect_heartbeat_test.go @@ -14,8 +14,8 @@ func TestHeartbeatNeverAdvertisesUndeclaredExport(t *testing.T) { exporting := local exporting.WorkspaceOutputExport = proto.CapabilitySupported registry := agent.NewRegistry() - registry.RegisterKind(proto.SupportedAgentKind{Kind: "declared", Available: true, Capabilities: prototest.Capabilities(exporting)}, harnessconfig.Configuration{}) - registry.RegisterKind(proto.SupportedAgentKind{Kind: "undeclared", Available: true, Capabilities: prototest.Capabilities(local)}, harnessconfig.Configuration{}) + registry.RegisterKind(proto.SupportedAgentKind{Kind: "declared", Available: true, Capabilities: prototest.Capabilities(exporting)}, harnessconfig.Declaration{}) + registry.RegisterKind(proto.SupportedAgentKind{Kind: "undeclared", Available: true, Capabilities: prototest.Capabilities(local)}, harnessconfig.Declaration{}) for _, canExport := range []bool{false, true} { for _, kind := range advertisedKinds(registry, canExport) { if got, want := kind.Capabilities.WorkspaceOutputExport.IsSupported(), canExport && kind.Kind == "declared"; got != want { diff --git a/apps/daemon/internal/cli/connect_suspend_test.go b/apps/daemon/internal/cli/connect_suspend_test.go index 0222ad112..9577da460 100644 --- a/apps/daemon/internal/cli/connect_suspend_test.go +++ b/apps/daemon/internal/cli/connect_suspend_test.go @@ -342,7 +342,7 @@ func TestQuiesceRetainsExecutorAcrossReconnectAndShutdownConfirmsCleanup(t *test environment, session := uuid.NewString(), uuid.NewString() t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) t.Setenv("OAC_RUNTIME_STATE_DIRECTORY", t.TempDir()) - if err := localworkspace.Bind(environment, session, t.TempDir(), t.TempDir()); err != nil { + if err := localworkspace.Bind(environment, t.TempDir(), t.TempDir()); err != nil { t.Fatal(err) } t.Cleanup(localworkspace.Unbind) @@ -368,7 +368,7 @@ func TestQuiesceRetainsExecutorAcrossReconnectAndShutdownConfirmsCleanup(t *test } }() registry := agent.NewRegistry() - registry.RegisterKind(proto.SupportedAgentKind{Kind: "cleanup", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + registry.RegisterKind(proto.SupportedAgentKind{Kind: "cleanup", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported})}, harnessconfig.Declaration{}) registry.RegisterExecutor("cleanup", func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { return native, nil }) control := &suspendControl{path: filepath.Join(t.TempDir(), "control.json"), identity: suspendIdentity{EnvironmentID: environment}, signal: make(chan os.Signal, 1)} finished := make(chan error, 1) diff --git a/apps/daemon/internal/cli/native_start_interrupt_unix_test.go b/apps/daemon/internal/cli/native_start_interrupt_unix_test.go index 24f2812b9..600270ac6 100644 --- a/apps/daemon/internal/cli/native_start_interrupt_unix_test.go +++ b/apps/daemon/internal/cli/native_start_interrupt_unix_test.go @@ -43,7 +43,6 @@ func TestNativeStartInterruptCancelsEnrollment(t *testing.T) { } _ = json.NewEncoder(w).Encode(machineapi.Enrollment{ DeviceID: "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa", - SessionID: "bbbbbbbb-1111-4111-8111-bbbbbbbbbbbb", EnvironmentID: config.Environment, WorkspaceDirectory: config.Workspace, }) diff --git a/apps/daemon/internal/cli/suspend_control_linux_test.go b/apps/daemon/internal/cli/suspend_control_linux_test.go index 53d890936..02c8d2d25 100644 --- a/apps/daemon/internal/cli/suspend_control_linux_test.go +++ b/apps/daemon/internal/cli/suspend_control_linux_test.go @@ -22,7 +22,7 @@ func TestResumeControlRejectsStaleIdentityAndDiscardsPreParkSignals(t *testing.T } path := filepath.Join(dir, "control.json") environment := uuid.NewString() - if err := localworkspace.Bind(environment, uuid.NewString(), t.TempDir(), t.TempDir()); err != nil { + if err := localworkspace.Bind(environment, t.TempDir(), t.TempDir()); err != nil { t.Fatal(err) } t.Cleanup(localworkspace.Unbind) diff --git a/apps/daemon/internal/dispatch/executor.go b/apps/daemon/internal/dispatch/executor.go index e8617f5d7..48a1c3abf 100644 --- a/apps/daemon/internal/dispatch/executor.go +++ b/apps/daemon/internal/dispatch/executor.go @@ -23,6 +23,7 @@ type executorState struct { nativeID string ctx context.Context cancel context.CancelFunc + turn proto.TurnSettings admission *preparationState run *sessionState preparing bool @@ -34,8 +35,10 @@ type executorState struct { idleLease uint64 } +// executorFingerprint covers the configuration a retained Executor fixes. The +// Turn settings are not part of it: ValidateSessionUpdate decides their change. func executorFingerprint(req proto.PromptRequestPayload) ([32]byte, error) { - req.RunID, req.Input = "", nil + req.RunID, req.Input, req.Turn = "", nil, proto.TurnSettings{} req.AgentSessionID = "" req.RequireExistingNativeSession = false data, err := json.Marshal(req) @@ -51,7 +54,7 @@ func (r *Router) handleExecutorPrepare(ctx context.Context, env proto.Envelope, if !available { return r.rejectPreparation(env, "resource_unavailable") } - factory, err := r.registry.ResolveExecutor(req.AgentKind) + factory, declaration, err := r.registry.ResolveExecutor(req.AgentKind) if err != nil || !caps.Preparation.IsSupported() { return r.rejectPreparation(env, "unsupported_preparation") } @@ -62,6 +65,9 @@ func (r *Router) handleExecutorPrepare(ctx context.Context, env proto.Envelope, if validateExecutionEnvironment(req, caps) != nil || len(req.FunctionTools) > 0 && !caps.FunctionTools.IsSupported() { return r.rejectPreparation(env, "unsupported_configuration") } + if declaration.ValidateTurnSettings(req.Turn) != nil { + return r.rejectPreparation(env, "unsupported_configuration") + } fingerprint, err := executorFingerprint(req) if err != nil { return r.rejectPreparation(env, "invalid_configuration") @@ -95,8 +101,18 @@ func (r *Router) handleExecutorPrepare(ctx context.Context, env proto.Envelope, return r.rejectPreparation(env, "preparation_capacity") } active := 0 + // A Runtime bound to an Environment serves one Session at a time; the new + // executor closes the other Sessions' idle executors before it prepares. + var others []*executorState for _, candidate := range r.executors { - if candidate.sessionID != input.SessionID && candidate.stateKey == req.AgentStateKey { + switch { + case candidate.sessionID == input.SessionID: + case r.localWorkspace != nil && (candidate.preparing || candidate.admission != nil || candidate.run != nil): + r.mu.Unlock() + return r.rejectPreparation(env, "resource_unavailable") + case r.localWorkspace != nil: + others = append(others, candidate) + case candidate.stateKey == req.AgentStateKey: r.mu.Unlock() return r.rejectPreparation(env, "session_binding_conflict") } @@ -115,7 +131,7 @@ func (r *Router) handleExecutorPrepare(ctx context.Context, env proto.Envelope, if owner != nil { code := "" switch { - case owner.environmentID != req.EnvironmentID() || owner.fingerprint != fingerprint: + case owner.environmentID != req.EnvironmentID() || owner.fingerprint != fingerprint || declaration.ValidateSessionUpdate(owner.turn, req.Turn) != nil: code = "configuration_conflict" case owner.invalid: code = "executor_cleanup_unconfirmed" @@ -134,18 +150,19 @@ func (r *Router) handleExecutorPrepare(ctx context.Context, env proto.Envelope, owner.timer.Stop() } owner.idleLease++ + owner.turn = req.Turn } else { if len(r.executors) >= executorIdleCapacity+preparationCapacity { r.mu.Unlock() return r.rejectPreparation(env, "executor_capacity") } ownerCtx, cancel := context.WithCancel(context.WithoutCancel(ctx)) - owner = &executorState{capabilities: caps, id: uuid.NewString(), sessionID: input.SessionID, environmentID: req.EnvironmentID(), stateKey: req.AgentStateKey, fingerprint: fingerprint, ctx: ownerCtx, cancel: cancel, preparing: true, nativeID: req.AgentSessionID} + owner = &executorState{capabilities: caps, id: uuid.NewString(), sessionID: input.SessionID, environmentID: req.EnvironmentID(), stateKey: req.AgentStateKey, fingerprint: fingerprint, turn: req.Turn, ctx: ownerCtx, cancel: cancel, preparing: true, nativeID: req.AgentSessionID} r.executors[input.SessionID] = owner r.log.Info("executor owner_created", "executor_id", owner.id, "session_id", owner.sessionID) } operation, cancel := context.WithCancel(context.WithoutCancel(ctx)) - p := &preparationState{capabilities: owner.capabilities, requestID: env.ID, trace: env.Trace, fingerprint: requestFingerprint, ctx: operation, cancel: cancel, environmentID: req.EnvironmentID(), executor: owner, owns: true, busy: !reused, deadline: time.Now().Add(r.preparationTimeout)} + p := &preparationState{capabilities: owner.capabilities, requestID: env.ID, trace: env.Trace, fingerprint: requestFingerprint, turn: req.Turn, ctx: operation, cancel: cancel, environmentID: req.EnvironmentID(), executor: owner, owns: true, busy: !reused, deadline: time.Now().Add(r.preparationTimeout)} state := "preparing" if reused { state = "ready" @@ -162,12 +179,15 @@ func (r *Router) handleExecutorPrepare(ctx context.Context, env proto.Envelope, if reused { r.publishPreparation(p, status) } else { - go r.prepareExecutor(p, req, factory) + go r.prepareExecutor(p, req, factory, others) } return nil } -func (r *Router) prepareExecutor(p *preparationState, req proto.PromptRequestPayload, factory agent.ExecutorFactory) { +// prepareExecutor confirms the close of the other Sessions' executors and +// removes their native state, which also covers state left by expired +// executors and earlier processes, before it prepares the new executor. +func (r *Router) prepareExecutor(p *preparationState, req proto.PromptRequestPayload, factory agent.ExecutorFactory, others []*executorState) { defer r.shutdownWG.Done() owner := p.executor started := time.Now() @@ -177,21 +197,27 @@ func (r *Router) prepareExecutor(p *preparationState, req proto.PromptRequestPay if !r.sendPreparation(p.requestID, p.trace, initial) { r.abandonExecutorAdmission(p, "failed", "status_delivery_failed", false) } - var native agent.Executor - var err error - if owner.ctx.Err() == nil { + err := owner.ctx.Err() + for _, other := range others { + if err == nil { + err = r.closeExecutor(other) + } + } + if err == nil { + err = r.localWorkspace.RemoveOtherSessionState(req.AgentStateKey) + } + if err == nil { workspaceStarted := time.Now() req, err = r.localWorkspace.Prepare(owner.ctx, req) r.log.InfoContext(owner.ctx, "executor preparation stage", "stage", "workspace", "executor_id", owner.id, "session_id", owner.sessionID, "duration_ms", float64(time.Since(workspaceStarted))/float64(time.Millisecond), "success", err == nil) - if err == nil && owner.ctx.Err() == nil { - native, err = factory(owner.ctx, req) - } - } else { - err = owner.ctx.Err() + } + var native agent.Executor + if err == nil && owner.ctx.Err() == nil { + native, err = factory(owner.ctx, req) } r.mu.Lock() owner.native, owner.preparing = native, false - r.log.Info("executor native_prepare", "executor_id", owner.id, "session_id", owner.sessionID, "duration_ms", time.Since(started).Milliseconds(), "success", err == nil && native != nil) + r.log.Info("executor native_prepare", "executor_id", owner.id, "session_id", owner.sessionID, "duration_ms", time.Since(started).Milliseconds(), "success", err == nil && native != nil, "err", err) ready := native != nil && err == nil && !owner.invalid && !r.closed && r.suspension == nil && p.status.State == "preparing" && p.ctx.Err() == nil p.busy = false if ready { diff --git a/apps/daemon/internal/dispatch/executor_cancel_receipt_test.go b/apps/daemon/internal/dispatch/executor_cancel_receipt_test.go index e5b6cddaf..8de91f2df 100644 --- a/apps/daemon/internal/dispatch/executor_cancel_receipt_test.go +++ b/apps/daemon/internal/dispatch/executor_cancel_receipt_test.go @@ -47,7 +47,7 @@ type receiptCancelExecutor struct { closeOnce sync.Once } -func (e *receiptCancelExecutor) StartTurn(_ context.Context, id string, _ proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { +func (e *receiptCancelExecutor) StartTurn(_ context.Context, id string, _ proto.TurnSettings, _ proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { turn := &receiptCancelTurn{id: id, out: out, owner: e, written: make(chan struct{}), cancelled: make(chan struct{}), closed: make(chan struct{}), settled: make(chan struct{}), awaiting: make(chan struct{})} e.current = turn e.turn <- turn @@ -128,7 +128,7 @@ func TestExecutorCancellationReachesNativeBeforeDurableReceiptJoin(t *testing.T) sender := &receiptCancelSender{recSender: &recSender{}, entered: make(chan struct{}), release: make(chan struct{})} owner := &receiptCancelExecutor{turn: make(chan *receiptCancelTurn, 2), cancelFails: mode == "cancel_failure" || mode == "close_failure_retry", closeFailsFirst: mode == "close_failure_retry", closeEntered: make(chan struct{}), closeRelease: make(chan struct{})} reg := agent.NewRegistry() - reg.RegisterKind(proto.SupportedAgentKind{Kind: "reusable", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{EnvironmentNone: proto.CapabilitySupported, DurableInputReceipts: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + reg.RegisterKind(proto.SupportedAgentKind{Kind: "reusable", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{EnvironmentNone: proto.CapabilitySupported, DurableInputReceipts: proto.CapabilitySupported})}, harnessconfig.Declaration{}) reg.RegisterExecutor("reusable", func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { return owner, nil }) r, err := dispatch.New(dispatch.Config{Registry: reg, Sender: sender, IdleTimeout: time.Hour}) if err != nil { diff --git a/apps/daemon/internal/dispatch/executor_handoff_test.go b/apps/daemon/internal/dispatch/executor_handoff_test.go index 23720d271..efa86b03f 100644 --- a/apps/daemon/internal/dispatch/executor_handoff_test.go +++ b/apps/daemon/internal/dispatch/executor_handoff_test.go @@ -46,7 +46,7 @@ type terminalHandoffExecutor struct { } func (e *terminalHandoffExecutor) Close(context.Context) error { e.closes.Add(1); return nil } -func (e *terminalHandoffExecutor) StartTurn(_ context.Context, id string, _ proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { +func (e *terminalHandoffExecutor) StartTurn(_ context.Context, id string, _ proto.TurnSettings, _ proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { turn := &terminalHandoffTurn{id: id, out: out, settled: make(chan struct{})} e.turns <- turn return turn, nil @@ -93,7 +93,7 @@ func TestPreparedDonePublishesAfterExecutorHandoff(t *testing.T) { } owner := &terminalHandoffExecutor{turns: make(chan *terminalHandoffTurn, 3)} registry := agent.NewRegistry() - registry.RegisterKind(proto.SupportedAgentKind{Kind: "handoff", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{EnvironmentNone: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + registry.RegisterKind(proto.SupportedAgentKind{Kind: "handoff", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{EnvironmentNone: proto.CapabilitySupported})}, harnessconfig.Declaration{}) var creates atomic.Int32 registry.RegisterExecutor("handoff", func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { creates.Add(1) diff --git a/apps/daemon/internal/dispatch/executor_switch_test.go b/apps/daemon/internal/dispatch/executor_switch_test.go new file mode 100644 index 000000000..d1dd9ffa9 --- /dev/null +++ b/apps/daemon/internal/dispatch/executor_switch_test.go @@ -0,0 +1,51 @@ +package dispatch_test + +import ( + "context" + "os" + "testing" + "time" + + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" + "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" + "github.com/google/uuid" +) + +func TestBoundRuntimeSwitchesSessionOnlyWhenOtherSessionIsIdle(t *testing.T) { + var made []*controlledPreparation + sender := &recSender{} + r := preparationRouter(t, sender, time.Minute, func(context.Context, proto.PromptRequestPayload) (preparedFixture, error) { + p := &controlledPreparation{closed: make(chan struct{})} + made = append(made, p) + return p, nil + }) + root := os.Getenv("OAC_RUNTIME_HOME") + first, next := preparationRequest(), preparationRequest() + next.SessionID = uuid.NewString() + next.Configuration.AgentStateKey = proto.SessionStateKey(next.SessionID) + ready := executorAdmission(t, r, sender, "first", first) + var dirs [2]string + for i, id := range []string{first.Configuration.AgentStateKey, next.Configuration.AgentStateKey} { + dir, err := agent.StateDir(root, "codex", id) + if err != nil || os.MkdirAll(dir, 0o700) != nil { + t.Fatal(err) + } + dirs[i] = dir + } + _ = r.Handle(t.Context(), mustEnv(t, proto.TypeExecutionPrepare, "busy", next)) + if got := waitPreparationStatus(t, sender, "busy", "rejected", ""); got.ErrorCode != "resource_unavailable" || len(made) != 1 { + t.Fatalf("admitted Session was displaced: %+v", got) + } + if err := r.Handle(t.Context(), mustEnv(t, proto.TypeExecutionRelease, "first", proto.ExecutionReleasePayload{Handle: ready.Handle})); err != nil { + t.Fatal(err) + } + waitPreparationStatus(t, sender, "first", "released", "") + executorAdmission(t, r, sender, "switch", next) + waitPreparationClosed(t, made[0]) + if _, err := os.Stat(dirs[0]); !os.IsNotExist(err) { + t.Fatal("old Session state kept") + } + if _, err := os.Stat(dirs[1]); err != nil { + t.Fatal("new Session state removed") + } +} diff --git a/apps/daemon/internal/dispatch/executor_test.go b/apps/daemon/internal/dispatch/executor_test.go index 9058f6c40..78acb0b81 100644 --- a/apps/daemon/internal/dispatch/executor_test.go +++ b/apps/daemon/internal/dispatch/executor_test.go @@ -23,6 +23,7 @@ type reusableExecutor struct { mu sync.Mutex closeErr error startErr error + turn proto.TurnSettings } func (e *reusableExecutor) Close(context.Context) error { @@ -31,11 +32,12 @@ func (e *reusableExecutor) Close(context.Context) error { defer e.mu.Unlock() return e.closeErr } -func (e *reusableExecutor) StartTurn(_ context.Context, id string, _ proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { +func (e *reusableExecutor) StartTurn(_ context.Context, id string, turn proto.TurnSettings, _ proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { if e.startErr != nil { return nil, e.startErr } t := &reusableTurn{id: id, out: out, settled: make(chan struct{})} + e.turn = turn e.starts <- t return t, nil } @@ -84,7 +86,7 @@ func executorRequest() proto.ExecutionPreparePayload { // registerExecutorKind registers info for prepared execution only. func registerExecutorKind(reg *agent.Registry, info proto.SupportedAgentKind, factory agent.ExecutorFactory) { - reg.RegisterKind(info, harnessconfig.Configuration{}) + reg.RegisterKind(info, harnessconfig.Declaration{Execution: harnessconfig.ExecutionOptions{ReasoningEfforts: []string{"low", "high"}}, SessionUpdates: harnessconfig.SessionUpdates{ReasoningEffort: proto.CapabilitySupported}}) reg.RegisterExecutor(info.Kind, factory) } func executorRouter(t *testing.T, owner *reusableExecutor, idle time.Duration) (*dispatch.Router, *recSender, *atomic.Int32) { @@ -157,6 +159,32 @@ func TestExecutorRetainsOwnerAcrossIndependentTurns(t *testing.T) { t.Fatal("executor closed between Turns") } } +func TestExecutorAcceptsDeclaredTurnChangesAndStartsWithThem(t *testing.T) { + owner := &reusableExecutor{starts: make(chan *reusableTurn, 2)} + r, s, calls := executorRouter(t, owner, time.Minute) + first := executorAdmission(t, r, s, "first", executorRequest()) + startExecutorTurn(t, r, s, "first", "one", first) + (<-owner.starts).finish() + waitFor(t, func() bool { return r.ActiveRuns() == 0 }, "first Turn settled") + req := executorRequest() + req.Configuration.AgentSessionID = "native-session" + req.Configuration.Turn.ReasoningEffort = "high" + second := executorAdmission(t, r, s, "second", req) + startExecutorTurn(t, r, s, "second", "two", second) + (<-owner.starts).finish() + waitFor(t, func() bool { return r.ActiveRuns() == 0 }, "second Turn settled") + req.Configuration.Turn.ReasoningEffort = "" + if err := r.Handle(t.Context(), mustEnv(t, proto.TypeExecutionPrepare, "reset", req)); err == nil { + t.Fatal("accepted an undeclared reset of effort") + } + req.Configuration.Turn.ReasoningEffort = "max" + if err := r.Handle(t.Context(), mustEnv(t, proto.TypeExecutionPrepare, "undeclared", req)); err == nil { + t.Fatal("accepted an undeclared effort") + } + if !second.Reused || calls.Load() != 1 || owner.turn.ReasoningEffort != "high" { + t.Fatalf("reused=%t calls=%d turn=%+v", second.Reused, calls.Load(), owner.turn) + } +} func TestExecutorCancelSettlesTurnWithoutClosingOwner(t *testing.T) { owner := &reusableExecutor{starts: make(chan *reusableTurn, 1)} r, s, _ := executorRouter(t, owner, time.Minute) @@ -182,7 +210,7 @@ func TestExecutorRejectsConfigurationAndNativeIdentityChanges(t *testing.T) { for _, kind := range []string{"configuration", "native"} { req := executorRequest() if kind == "configuration" { - req.Configuration.AgentOptions = map[string]any{"model": "changed"} + req.Configuration.Turn.Model = "changed" } else { req.Configuration.AgentSessionID = "other-native" } @@ -232,7 +260,7 @@ func TestExecutorPreInputFailureConfirmsCloseBeforeRetrySignal(t *testing.T) { func poolRouter(t *testing.T, factory agent.ExecutorFactory) (*dispatch.Router, *recSender) { t.Helper() registry := agent.NewRegistry() - registry.RegisterKind(proto.SupportedAgentKind{Kind: "reusable", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{EnvironmentNone: proto.CapabilitySupported, DurableInputReceipts: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + registry.RegisterKind(proto.SupportedAgentKind{Kind: "reusable", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{EnvironmentNone: proto.CapabilitySupported, DurableInputReceipts: proto.CapabilitySupported})}, harnessconfig.Declaration{}) registry.RegisterExecutor("reusable", factory) sender := &recSender{} router, err := dispatch.New(dispatch.Config{Registry: registry, Sender: sender, IdleTimeout: time.Minute}) @@ -304,6 +332,16 @@ func TestExecutorRejectsSessionStateScopeMismatch(t *testing.T) { } } +func TestUnboundRuntimeKeepsSessionsSideBySide(t *testing.T) { + owner := &reusableExecutor{} + r, s, calls := executorRouter(t, owner, time.Minute) + executorAdmission(t, r, s, "first", executorRequest()) + executorAdmission(t, r, s, "second", noEnvironmentPreparation("next", proto.PromptRequestPayload{AgentKind: "reusable"})) + if owner.closes.Load() != 0 || calls.Load() != 2 { + t.Fatalf("unbound Runtime closes=%d prepares=%d, want 0 and 2", owner.closes.Load(), calls.Load()) + } +} + func TestExecutorRejectsUnsupportedConfigurationBeforeFactory(t *testing.T) { for name, change := range map[string]func(*proto.PromptRequestPayload){ "no environment": func(r *proto.PromptRequestPayload) { r.DisableExecutionEnvironment = false }, @@ -380,7 +418,7 @@ func TestExecutorResumesSameOwnerAndNextTurnAfterSuspension(t *testing.T) { req := preparationRequest() req.Configuration.AgentSessionID = "native-session" conflict := req - conflict.Configuration.AgentOptions = map[string]any{"model": "changed"} + conflict.Configuration.Turn.Model = "changed" if err := r.Handle(t.Context(), mustEnv(t, proto.TypeExecutionPrepare, "conflict", conflict)); err == nil { t.Fatal("suspension relaxed the fixed configuration") } diff --git a/apps/daemon/internal/dispatch/functions_native_test.go b/apps/daemon/internal/dispatch/functions_native_test.go index b022d94dd..fe6629d6a 100644 --- a/apps/daemon/internal/dispatch/functions_native_test.go +++ b/apps/daemon/internal/dispatch/functions_native_test.go @@ -18,7 +18,7 @@ import ( "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent/codex" "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/dispatch" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" - "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto/prototest" + codexconfig "github.com/MiniMax-AI/OpenAgentCore/internal/harnessconfig/codex" ) type nativeFunctionSender chan proto.Envelope @@ -108,7 +108,8 @@ func TestNativeFunctionBridge(t *testing.T) { })) defer model.Close() reg := agent.NewRegistry() - registerExecutorKind(reg, proto.SupportedAgentKind{Kind: "codex", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{FunctionTools: proto.CapabilitySupported, EnvironmentNone: proto.CapabilitySupported})}, codex.NewExecutorFactory(t.TempDir())) + reg.RegisterKind(proto.SupportedAgentKind{Kind: "codex", Available: true, Capabilities: codexconfig.Declaration.Capabilities}, codexconfig.Declaration) + reg.RegisterExecutor("codex", codex.NewExecutorFactory(t.TempDir(), t.TempDir())) sender := make(nativeFunctionSender, 256) ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second) defer cancel() @@ -162,7 +163,7 @@ func TestNativeFunctionBridge(t *testing.T) { run := fmt.Sprintf("run-%d", index) request := noEnvironmentPreparation("native-functions", proto.PromptRequestPayload{AgentKind: "codex", AgentSessionID: nativeID, FunctionTools: []proto.FunctionTool{{Name: "lookup_ticket", Description: "Read a synthetic ticket", Parameters: json.RawMessage(`{"type":"object","properties":{"ticket":{"type":"string"}},"required":["ticket"],"additionalProperties":false}`)}}, - AgentOptions: map[string]any{"model": "gpt-5.5", "model_provider": map[string]any{"protocol": "responses", "base_url": model.URL + "/v1", "api_key": "synthetic-local-token"}}}) + Turn: proto.TurnSettings{Model: "gpt-5.5"}, AgentOptions: map[string]any{"model_provider": map[string]any{"protocol": "responses", "base_url": model.URL + "/v1", "api_key": "synthetic-local-token"}}}) prepare, _ := proto.NewEnvelope(proto.TypeExecutionPrepare, run, request) if err := router.Handle(ctx, prepare); err != nil { t.Fatal(err) diff --git a/apps/daemon/internal/dispatch/local_directory_test.go b/apps/daemon/internal/dispatch/local_directory_test.go index 766c0244d..c4f3c8f4e 100644 --- a/apps/daemon/internal/dispatch/local_directory_test.go +++ b/apps/daemon/internal/dispatch/local_directory_test.go @@ -23,13 +23,13 @@ func TestLocalDirectoryPreparationNeedsNoHarnessAndRejectsOtherOwners(t *testing workspace := t.TempDir() environment, session := uuid.NewString(), uuid.NewString() - binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, workspace, t.TempDir()) + binding, err := localworkspace.NewWithCapabilityDirectory(environment, workspace, t.TempDir()) if err != nil { t.Fatal(err) } var harnessCalls atomic.Int32 reg := agent.NewRegistry() - reg.RegisterKind(proto.SupportedAgentKind{Kind: "native", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported, WorkspaceReadPreparation: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + reg.RegisterKind(proto.SupportedAgentKind{Kind: "native", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported, WorkspaceReadPreparation: proto.CapabilitySupported})}, harnessconfig.Declaration{}) reg.RegisterExecutor("native", func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { harnessCalls.Add(1) return nil, errors.New("must not prepare a harness") @@ -66,11 +66,6 @@ func TestLocalDirectoryPreparationNeedsNoHarnessAndRejectsOtherOwners(t *testing if err := r.Handle(t.Context(), mustEnv(t, proto.TypeExecutionStart, "idle", proto.ExecutionStartPayload{Handle: ready.Handle, ExecutorID: ready.ExecutorID, RunID: "forbidden", Input: proto.TextInput("work")})); err == nil { t.Fatal("read preparation admitted execution") } - bad := request - bad.AgentStateKey = uuid.NewString() - if err := r.Handle(t.Context(), mustEnv(t, proto.TypeExecutionPrepare, "wrong-session", proto.ExecutionPreparePayload{Configuration: bad})); err == nil { - t.Fatal("wrong Session accepted") - } _ = r.Handle(t.Context(), mustEnv(t, proto.TypeExecutionRelease, "idle", proto.ExecutionReleasePayload{Handle: ready.Handle})) waitPreparationStatus(t, sender, "idle", "released", "") if harnessCalls.Load() != 0 || r.ActiveRuns() != 0 { @@ -103,12 +98,12 @@ func TestLocalDirectoryKeepsNotDirectorySeparateFromFailures(t *testing.T) { t.Fatal(err) } environment, session := uuid.NewString(), uuid.NewString() - binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, workspace, t.TempDir()) + binding, err := localworkspace.NewWithCapabilityDirectory(environment, workspace, t.TempDir()) if err != nil { t.Fatal(err) } reg := agent.NewRegistry() - reg.RegisterKind(proto.SupportedAgentKind{Kind: "native", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported, WorkspaceReadPreparation: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + reg.RegisterKind(proto.SupportedAgentKind{Kind: "native", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported, WorkspaceReadPreparation: proto.CapabilitySupported})}, harnessconfig.Declaration{}) reg.RegisterExecutor("native", func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { return nil, errors.New("must not prepare a harness") }) diff --git a/apps/daemon/internal/dispatch/mcp_http_test.go b/apps/daemon/internal/dispatch/mcp_http_test.go index ff6805d3e..a806e7bf8 100644 --- a/apps/daemon/internal/dispatch/mcp_http_test.go +++ b/apps/daemon/internal/dispatch/mcp_http_test.go @@ -111,7 +111,7 @@ func TestLocalMCPOriginAndCapabilityAdmission(t *testing.T) { req.Configuration.MCPHTTPServers = nil } entered := make(chan struct{}, 1) - h.reg.RegisterKind(proto.SupportedAgentKind{Kind: "prepared", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported, MCPHTTPTools: proto.CapabilityFromBool(mode != "environment missing capability"), MCPHTTPBearerAuth: proto.CapabilitySupported, MCPHTTPRequired: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + h.reg.RegisterKind(proto.SupportedAgentKind{Kind: "prepared", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported, MCPHTTPTools: proto.CapabilityFromBool(mode != "environment missing capability"), MCPHTTPBearerAuth: proto.CapabilitySupported, MCPHTTPRequired: proto.CapabilitySupported})}, harnessconfig.Declaration{}) h.reg.RegisterExecutor("prepared", func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { entered <- struct{}{} return nil, errors.New("controlled stop") diff --git a/apps/daemon/internal/dispatch/native_file_results_test.go b/apps/daemon/internal/dispatch/native_file_results_test.go index fda03adbb..dd0eb6f63 100644 --- a/apps/daemon/internal/dispatch/native_file_results_test.go +++ b/apps/daemon/internal/dispatch/native_file_results_test.go @@ -38,7 +38,7 @@ func TestLocalUploadUnknownRetainsOwner(t *testing.T) { t.Fatal(got) } r.workspaceWrite = &workspaceUpload{envelope: proto.Envelope{ID: uuid.NewString()}, finished: true, uncertain: true} - request := proto.WorkspaceWritePayload{Step: "begin", EnvironmentID: uuid.NewString(), SessionID: uuid.NewString(), Path: "file", SizeBytes: 0, SHA256: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"} + request := proto.WorkspaceWritePayload{Step: "begin", EnvironmentID: uuid.NewString(), Path: "file", SizeBytes: 0, SHA256: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"} env, _ := proto.NewEnvelope(proto.TypeWorkspaceWrite, uuid.NewString(), request) if err = r.Handle(t.Context(), env); err != nil { t.Fatal(err) diff --git a/apps/daemon/internal/dispatch/preparation.go b/apps/daemon/internal/dispatch/preparation.go index 36dea9749..bbaaa1f53 100644 --- a/apps/daemon/internal/dispatch/preparation.go +++ b/apps/daemon/internal/dispatch/preparation.go @@ -25,6 +25,7 @@ type preparationState struct { requestID string trace string fingerprint [32]byte + turn proto.TurnSettings startFingerprint [32]byte status proto.PreparationStatusPayload deadline time.Time diff --git a/apps/daemon/internal/dispatch/preparation_executor_fixture_test.go b/apps/daemon/internal/dispatch/preparation_executor_fixture_test.go index c3e8c9ebf..1aa47ea4b 100644 --- a/apps/daemon/internal/dispatch/preparation_executor_fixture_test.go +++ b/apps/daemon/internal/dispatch/preparation_executor_fixture_test.go @@ -57,7 +57,7 @@ func (e *preparationExecutor) Close(ctx context.Context) error { return err } -func (e *preparationExecutor) StartTurn(ctx context.Context, id string, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { +func (e *preparationExecutor) StartTurn(ctx context.Context, id string, _ proto.TurnSettings, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { upstream := make(chan proto.Envelope, 64) terminal := make(chan struct{}) var once sync.Once diff --git a/apps/daemon/internal/dispatch/preparation_start.go b/apps/daemon/internal/dispatch/preparation_start.go index 6c786871f..c13159fcb 100644 --- a/apps/daemon/internal/dispatch/preparation_start.go +++ b/apps/daemon/internal/dispatch/preparation_start.go @@ -96,7 +96,7 @@ func (r *Router) startPreparedExecution(p *preparationState, state *sessionState if blocked { startErr = context.Canceled } else { - turn, startErr = handoff.target.StartTurn(agent.WithBoundaryInput(p.ctx, received, p.requestID), input.RunID, input.Input, state.out) + turn, startErr = handoff.target.StartTurn(agent.WithBoundaryInput(p.ctx, received, p.requestID), input.RunID, p.turn, input.Input, state.out) } r.mu.Lock() handoff.turn = turn diff --git a/apps/daemon/internal/dispatch/preparation_test.go b/apps/daemon/internal/dispatch/preparation_test.go index 8a74242a1..d534c888d 100644 --- a/apps/daemon/internal/dispatch/preparation_test.go +++ b/apps/daemon/internal/dispatch/preparation_test.go @@ -83,7 +83,7 @@ func preparationWorkspace(t *testing.T) *localworkspace.Binding { } t.Setenv("OAC_RUNTIME_HOME", runtimeHome) preparationDirectories.workspace, preparationDirectories.capabilities = t.TempDir(), t.TempDir() - binding, err := localworkspace.NewWithCapabilityDirectory(preparationEnvironmentID, preparationSessionID, preparationDirectories.workspace, preparationDirectories.capabilities) + binding, err := localworkspace.NewWithCapabilityDirectory(preparationEnvironmentID, preparationDirectories.workspace, preparationDirectories.capabilities) if err != nil { t.Fatal(err) } @@ -111,7 +111,7 @@ func preparationRequest() proto.ExecutionPreparePayload { func preparationRouter(t *testing.T, sender dispatch.Sender, timeout time.Duration, factory preparationFactory) *dispatch.Router { t.Helper() reg := agent.NewRegistry() - reg.RegisterKind(proto.SupportedAgentKind{Kind: "prepared", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported, WorkspaceReadPreparation: proto.CapabilitySupported, FunctionTools: proto.CapabilitySupported, DurableInputReceipts: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + reg.RegisterKind(proto.SupportedAgentKind{Kind: "prepared", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{LocalEnvironment: proto.CapabilitySupported, WorkspaceReadPreparation: proto.CapabilitySupported, FunctionTools: proto.CapabilitySupported, DurableInputReceipts: proto.CapabilitySupported})}, harnessconfig.Declaration{}) reg.RegisterExecutor("prepared", preparationExecutorFixture(factory)) r, err := dispatch.New(dispatch.Config{Registry: reg, Sender: sender, PreparationTimeout: timeout, LocalWorkspace: preparationWorkspace(t)}) if err != nil { diff --git a/apps/daemon/internal/dispatch/runtime_preparation.go b/apps/daemon/internal/dispatch/runtime_preparation.go index 926ddc5f9..e57861ad9 100644 --- a/apps/daemon/internal/dispatch/runtime_preparation.go +++ b/apps/daemon/internal/dispatch/runtime_preparation.go @@ -60,7 +60,7 @@ func (r *Router) handleRuntimePrepare(ctx context.Context, env proto.Envelope) e } return r.sendRuntimePrepareResult(ctx, env.ID, rejectedRuntimePreparation("runtime_preparation_capacity")) } - if r.localWorkspace == nil || !r.localWorkspace.Matches(request.EnvironmentID, request.SessionID) || r.runtimePreparationResourcesBusyLocked() { + if r.localWorkspace == nil || !r.localWorkspace.Matches(request.EnvironmentID) || r.runtimePreparationResourcesBusyLocked() { r.mu.Unlock() return r.sendRuntimePrepareResult(ctx, env.ID, rejectedRuntimePreparation("resource_unavailable")) } @@ -151,7 +151,9 @@ func (r *Router) runRuntimePreparationTransfer(ctx context.Context, u *runtimePr r.mu.Unlock() result := rejectedRuntimePreparation("invalid_request") if admitted { + started := time.Now() result = runtimePreparationResult(apply(ctx, u.request, data), u.request.SizeBytes) + result.DurationMS = time.Since(started).Milliseconds() } // Release the potentially large body before waiting on transport delivery. data = nil diff --git a/apps/daemon/internal/dispatch/runtime_preparation_test.go b/apps/daemon/internal/dispatch/runtime_preparation_test.go index cdd948ae6..f9b5a48d9 100644 --- a/apps/daemon/internal/dispatch/runtime_preparation_test.go +++ b/apps/daemon/internal/dispatch/runtime_preparation_test.go @@ -30,10 +30,10 @@ func (s *capabilitiesTestSender) Send(ctx context.Context, env proto.Envelope) e } } -func capabilitiesTestRouter(t *testing.T) (*Router, *capabilitiesTestSender, string, string) { +func capabilitiesTestRouter(t *testing.T) (*Router, *capabilitiesTestSender, string) { t.Helper() - environment, session := uuid.NewString(), uuid.NewString() - binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, t.TempDir(), t.TempDir()) + environment := uuid.NewString() + binding, err := localworkspace.NewWithCapabilityDirectory(environment, t.TempDir(), t.TempDir()) if err != nil { t.Fatal(err) } @@ -42,7 +42,7 @@ func capabilitiesTestRouter(t *testing.T) (*Router, *capabilitiesTestSender, str if err != nil { t.Fatal(err) } - return router, sender, environment, session + return router, sender, environment } func capabilityEnvelope(t *testing.T, id string, request proto.RuntimePreparePayload) proto.Envelope { @@ -54,10 +54,10 @@ func capabilityEnvelope(t *testing.T, id string, request proto.RuntimePreparePay return env } -func capabilityBegin(environment, session string, body []byte) proto.RuntimePreparePayload { +func capabilityBegin(environment string, body []byte) proto.RuntimePreparePayload { digest := sha256.Sum256(body) return proto.RuntimePreparePayload{ - BudgetMS: 300000, Step: "begin", Action: "skill", EnvironmentID: environment, SessionID: session, + BudgetMS: 300000, Step: "begin", Action: "skill", EnvironmentID: environment, Skill: &proto.SkillMetadata{Type: "inline", Name: "proof", Description: "A proof."}, SizeBytes: len(body), SHA256: hex.EncodeToString(digest[:]), } @@ -90,10 +90,10 @@ func shutdownCapabilitiesRouter(t *testing.T, router *Router) { func TestRuntimePreparationTransferValidatesCompleteBodyBeforeMutation(t *testing.T) { for _, mode := range []string{"offset", "digest", "short", "oversized-chunk"} { t.Run(mode, func(t *testing.T) { - r, sender, environment, session := capabilitiesTestRouter(t) + r, sender, environment := capabilitiesTestRouter(t) defer shutdownCapabilitiesRouter(t, r) body := bytes.Repeat([]byte("a"), proto.RuntimePrepareChunkBytes+1) - request := capabilityBegin(environment, session, body) + request := capabilityBegin(environment, body) if mode == "digest" { request.SHA256 = stringsOfZeroDigest() } @@ -143,15 +143,13 @@ func TestRuntimePreparationTransferValidatesCompleteBodyBeforeMutation(t *testin func stringsOfZeroDigest() string { return hex.EncodeToString(make([]byte, sha256.Size)) } func TestRuntimePreparationBeginRequiresExactBindingAndBounds(t *testing.T) { - r, sender, environment, session := capabilitiesTestRouter(t) + r, sender, environment := capabilitiesTestRouter(t) defer shutdownCapabilitiesRouter(t, r) - for _, mode := range []string{"environment", "session", "size", "nil-binding"} { - request := capabilityBegin(environment, session, []byte("abc")) + for _, mode := range []string{"environment", "size", "nil-binding"} { + request := capabilityBegin(environment, []byte("abc")) switch mode { case "environment": request.EnvironmentID = uuid.NewString() - case "session": - request.SessionID = uuid.NewString() case "size": request.SizeBytes = proto.RuntimePrepareMaxBytes + 1 case "nil-binding": @@ -171,7 +169,7 @@ func TestRuntimePreparationBeginRequiresExactBindingAndBounds(t *testing.T) { func TestRuntimePreparationPreparationExcludesOwnedResources(t *testing.T) { for _, mode := range []string{"write", "export", "read", "run", "executor", "preparation"} { t.Run(mode, func(t *testing.T) { - r, sender, environment, session := capabilitiesTestRouter(t) + r, sender, environment := capabilitiesTestRouter(t) switch mode { case "write": r.workspaceWrite = &workspaceUpload{} @@ -182,12 +180,12 @@ func TestRuntimePreparationPreparationExcludesOwnedResources(t *testing.T) { case "run": r.sessions["run"] = &sessionState{} case "executor": - r.executors[session] = &executorState{} + r.executors["session"] = &executorState{} case "preparation": r.preparations["p"] = &preparationState{owns: true} } id := uuid.NewString() - if err := r.Handle(t.Context(), capabilityEnvelope(t, id, capabilityBegin(environment, session, []byte("abc")))); err != nil { + if err := r.Handle(t.Context(), capabilityEnvelope(t, id, capabilityBegin(environment, []byte("abc")))); err != nil { t.Fatal(err) } if got := capabilitiesReceipt(t, sender, id, "rejected"); got.ErrorCode != "resource_unavailable" { @@ -208,9 +206,9 @@ func TestRuntimePreparationPreparationExcludesOwnedResources(t *testing.T) { } func TestRuntimePreparationUploadBlocksWorkspaceWriteAndSuspension(t *testing.T) { - r, sender, environment, session := capabilitiesTestRouter(t) + r, sender, environment := capabilitiesTestRouter(t) id := uuid.NewString() - if err := r.Handle(t.Context(), capabilityEnvelope(t, id, capabilityBegin(environment, session, []byte("abc")))); err != nil { + if err := r.Handle(t.Context(), capabilityEnvelope(t, id, capabilityBegin(environment, []byte("abc")))); err != nil { t.Fatal(err) } capabilitiesReceipt(t, sender, id, "ready") @@ -218,7 +216,7 @@ func TestRuntimePreparationUploadBlocksWorkspaceWriteAndSuspension(t *testing.T) t.Fatal(err) } digest := sha256.Sum256([]byte("abc")) - write, err := proto.NewEnvelope(proto.TypeWorkspaceWrite, uuid.NewString(), proto.WorkspaceWritePayload{Step: "begin", EnvironmentID: environment, SessionID: session, Path: "proof", SizeBytes: 3, SHA256: hex.EncodeToString(digest[:])}) + write, err := proto.NewEnvelope(proto.TypeWorkspaceWrite, uuid.NewString(), proto.WorkspaceWritePayload{Step: "begin", EnvironmentID: environment, Path: "proof", SizeBytes: 3, SHA256: hex.EncodeToString(digest[:])}) if err != nil { t.Fatal(err) } @@ -244,11 +242,11 @@ func TestRuntimePreparationUploadBlocksWorkspaceWriteAndSuspension(t *testing.T) } func TestRuntimePreparationCancellationKeepsOwnershipUntilApplyStops(t *testing.T) { - r, sender, environment, session := capabilitiesTestRouter(t) + r, sender, environment := capabilitiesTestRouter(t) sender.frames = make(chan proto.Envelope) ctx, cancel := context.WithCancel(context.Background()) id := uuid.NewString() - request := proto.RuntimePreparePayload{BudgetMS: 300000, Step: "begin", Action: "finalize", EnvironmentID: environment, SessionID: session, Sources: &proto.CapabilitySources{}} + request := proto.RuntimePreparePayload{BudgetMS: 300000, Step: "begin", Action: "finalize", EnvironmentID: environment, Sources: &proto.CapabilitySources{}} owner := &runtimePreparationTransfer{envelope: capabilityEnvelope(t, id, request), request: request, ready: make(chan struct{}), cancel: cancel, finished: true, apply: true} close(owner.ready) r.runtimePreparation = owner @@ -337,10 +335,10 @@ func TestRuntimePreparationResultCategoriesAndUnknownOwnership(t *testing.T) { t.Fatalf("unsafe result: %+v", got) } } - r, sender, environment, session := capabilitiesTestRouter(t) + r, sender, environment := capabilitiesTestRouter(t) ctx, cancel := context.WithCancel(context.Background()) id := uuid.NewString() - request := capabilityBegin(environment, session, []byte("abc")) + request := capabilityBegin(environment, []byte("abc")) owner := &runtimePreparationTransfer{envelope: capabilityEnvelope(t, id, request), request: request, data: []byte("abc"), ready: make(chan struct{}), cancel: cancel, finished: true, apply: true} close(owner.ready) r.runtimePreparation = owner @@ -368,9 +366,9 @@ func TestRuntimePreparationResultCategoriesAndUnknownOwnership(t *testing.T) { func TestRuntimePreparationStagingDeadlineRejectsWithoutApplying(t *testing.T) { synctest.Test(t, func(t *testing.T) { - r, sender, environment, session := capabilitiesTestRouter(t) + r, sender, environment := capabilitiesTestRouter(t) id := uuid.NewString() - request := capabilityBegin(environment, session, []byte("abc")) + request := capabilityBegin(environment, []byte("abc")) if err := r.Handle(t.Context(), capabilityEnvelope(t, id, request)); err != nil { t.Fatal(err) } @@ -390,10 +388,10 @@ func TestRuntimePreparationStagingDeadlineRejectsWithoutApplying(t *testing.T) { func TestRuntimePreparationApplyOutlivesStagingAndHonorsBudget(t *testing.T) { synctest.Test(t, func(t *testing.T) { - r, sender, environment, session := capabilitiesTestRouter(t) + r, sender, environment := capabilitiesTestRouter(t) ctx, cancel := context.WithTimeout(t.Context(), 5*time.Minute) id := uuid.NewString() - request := capabilityBegin(environment, session, []byte("abc")) + request := capabilityBegin(environment, []byte("abc")) owner := &runtimePreparationTransfer{envelope: capabilityEnvelope(t, id, request), request: request, ready: make(chan struct{}), cancel: cancel, finished: true, apply: true, transferDeadline: time.Now().Add(2 * time.Minute)} close(owner.ready) r.runtimePreparation = owner @@ -427,9 +425,9 @@ func TestRuntimePreparationApplyOutlivesStagingAndHonorsBudget(t *testing.T) { func TestRuntimePreparationHonorsBeginBudgetDuringStaging(t *testing.T) { synctest.Test(t, func(t *testing.T) { - r, sender, environment, session := capabilitiesTestRouter(t) + r, sender, environment := capabilitiesTestRouter(t) id := uuid.NewString() - request := capabilityBegin(environment, session, []byte("abc")) + request := capabilityBegin(environment, []byte("abc")) request.BudgetMS = 10 if err := r.Handle(t.Context(), capabilityEnvelope(t, id, request)); err != nil { t.Fatal(err) @@ -441,3 +439,25 @@ func TestRuntimePreparationHonorsBeginBudgetDuringStaging(t *testing.T) { shutdownCapabilitiesRouter(t, r) }) } + +func TestRuntimePreparationReportsApplyDuration(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + r, sender, environment := capabilitiesTestRouter(t) + _, cancel := context.WithCancel(t.Context()) + id := uuid.NewString() + request := proto.RuntimePreparePayload{BudgetMS: 300000, Step: "begin", Action: "finalize", EnvironmentID: environment, Sources: &proto.CapabilitySources{}} + owner := &runtimePreparationTransfer{envelope: capabilityEnvelope(t, id, request), request: request, ready: make(chan struct{}), cancel: cancel, finished: true, apply: true} + close(owner.ready) + r.runtimePreparation = owner + r.shutdownWG.Add(1) + go r.runRuntimePreparationTransfer(t.Context(), owner, func(context.Context, proto.RuntimePreparePayload, []byte) error { + time.Sleep(1500 * time.Millisecond) + return nil + }) + synctest.Wait() + got := capabilitiesReceipt(t, sender, id, "completed") + if got.DurationMS != 1500 || !proto.ValidRuntimePrepareResult(got, "completed", 0, 0) { + t.Fatalf("apply duration not reported: %+v", got) + } + }) +} diff --git a/apps/daemon/internal/dispatch/suspend_test.go b/apps/daemon/internal/dispatch/suspend_test.go index 36562c3e2..5aba63398 100644 --- a/apps/daemon/internal/dispatch/suspend_test.go +++ b/apps/daemon/internal/dispatch/suspend_test.go @@ -20,7 +20,7 @@ type suspendedExecutor struct { close func(context.Context) error } -func (e *suspendedExecutor) StartTurn(context.Context, string, proto.MessageInput, chan<- proto.Envelope) (agent.Turn, error) { +func (e *suspendedExecutor) StartTurn(context.Context, string, proto.TurnSettings, proto.MessageInput, chan<- proto.Envelope) (agent.Turn, error) { return nil, errors.New("suspended executor must not start a Turn") } diff --git a/apps/daemon/internal/dispatch/workspace_export_test.go b/apps/daemon/internal/dispatch/workspace_export_test.go index 0da4f5d19..714aa73cb 100644 --- a/apps/daemon/internal/dispatch/workspace_export_test.go +++ b/apps/daemon/internal/dispatch/workspace_export_test.go @@ -50,8 +50,8 @@ func exporterRouter(t *testing.T, program string) (*Router, exportSender, proto. } f.Close() } - environment, session := uuid.NewString(), uuid.NewString() - binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, workspace, t.TempDir()) + environment := uuid.NewString() + binding, err := localworkspace.NewWithCapabilityDirectory(environment, workspace, t.TempDir()) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/dispatch/workspace_write.go b/apps/daemon/internal/dispatch/workspace_write.go index 50ef6c5ff..e40491869 100644 --- a/apps/daemon/internal/dispatch/workspace_write.go +++ b/apps/daemon/internal/dispatch/workspace_write.go @@ -58,7 +58,7 @@ func (r *Router) handleWorkspaceWrite(ctx context.Context, env proto.Envelope) e } return r.sendWorkspaceWrite(ctx, env.ID, rejectedWorkspaceWrite("write_capacity")) } - if !r.localWorkspace.AcceptsFileWrite(request.EnvironmentID, request.SessionID) || len(r.sessions) != 0 || len(r.workspaceReads) != 0 { + if !r.localWorkspace.AcceptsFileWrite(request.EnvironmentID) || len(r.sessions) != 0 || len(r.workspaceReads) != 0 { r.mu.Unlock() return r.sendWorkspaceWrite(ctx, env.ID, rejectedWorkspaceWrite("resource_unavailable")) } diff --git a/apps/daemon/internal/dispatch/workspace_write_test.go b/apps/daemon/internal/dispatch/workspace_write_test.go index 7ecab2792..7b87d6b94 100644 --- a/apps/daemon/internal/dispatch/workspace_write_test.go +++ b/apps/daemon/internal/dispatch/workspace_write_test.go @@ -19,8 +19,8 @@ import ( func localWriterRouter(t *testing.T) (*dispatch.Router, *recSender, proto.WorkspaceWritePayload, string) { t.Helper() workspace := t.TempDir() - environment, session := uuid.NewString(), uuid.NewString() - binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, workspace, t.TempDir()) + environment := uuid.NewString() + binding, err := localworkspace.NewWithCapabilityDirectory(environment, workspace, t.TempDir()) if err != nil { t.Fatal(err) } @@ -35,7 +35,7 @@ func localWriterRouter(t *testing.T) (*dispatch.Router, *recSender, proto.Worksp _ = r.Shutdown(ctx) }) digest := sha256.Sum256([]byte("abc")) - return r, sender, proto.WorkspaceWritePayload{Step: "begin", EnvironmentID: environment, SessionID: session, Path: "file", SizeBytes: 3, SHA256: hex.EncodeToString(digest[:])}, workspace + return r, sender, proto.WorkspaceWritePayload{Step: "begin", EnvironmentID: environment, Path: "file", SizeBytes: 3, SHA256: hex.EncodeToString(digest[:])}, workspace } func waitWorkspaceWrite(t *testing.T, sender *recSender, id, outcome string) proto.WorkspaceWriteResultPayload { @@ -62,19 +62,13 @@ func waitWorkspaceWrite(t *testing.T, sender *recSender, id, outcome string) pro func TestLocalUploadRequiresExactScopeAndCompleteBody(t *testing.T) { r, sender, request, workspace := localWriterRouter(t) - for _, field := range []string{"environment", "session"} { - bad := request - if field == "environment" { - bad.EnvironmentID = uuid.NewString() - } else { - bad.SessionID = uuid.NewString() - } - id := uuid.NewString() - if err := r.Handle(t.Context(), mustEnv(t, proto.TypeWorkspaceWrite, id, bad)); err != nil { - t.Fatal(err) - } - waitWorkspaceWrite(t, sender, id, "rejected") + bad := request + bad.EnvironmentID = uuid.NewString() + badID := uuid.NewString() + if err := r.Handle(t.Context(), mustEnv(t, proto.TypeWorkspaceWrite, badID, bad)); err != nil { + t.Fatal(err) } + waitWorkspaceWrite(t, sender, badID, "rejected") id := uuid.NewString() if err := r.Handle(t.Context(), mustEnv(t, proto.TypeWorkspaceWrite, id, request)); err != nil { t.Fatal(err) diff --git a/apps/daemon/internal/localworkspace/binding.go b/apps/daemon/internal/localworkspace/binding.go index d94f26576..a3160a6db 100644 --- a/apps/daemon/internal/localworkspace/binding.go +++ b/apps/daemon/internal/localworkspace/binding.go @@ -2,8 +2,10 @@ package localworkspace import ( "errors" + "strings" "sync" + "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/agent" "github.com/MiniMax-AI/OpenAgentCore/apps/daemon/internal/paths" "github.com/MiniMax-AI/OpenAgentCore/internal/agentcapabilities" @@ -15,33 +17,37 @@ import ( // Binding freezes operator-owned identity and paths for one Runtime lifetime. type Binding struct { environment string - stateKey string workspace string writer *fileWriter capabilityMu sync.Mutex capabilityRoot string stateRoot string + runtimeRoot string } // NewWithCapabilityDirectory freezes paths selected by the Runtime operator. -func NewWithCapabilityDirectory(environment, session, workspace, directory string) (*Binding, error) { +func NewWithCapabilityDirectory(environment, workspace, directory string) (*Binding, error) { stateRoot, err := paths.StateDirectory() if err != nil { return nil, err } - b, err := newNativeBinding(environment, session, workspace, directory) + b, err := newNativeBinding(environment, workspace, directory) if err != nil { return nil, err } - b.stateRoot = stateRoot + runtimeRoot, err := paths.Root() + if err != nil { + return nil, err + } + b.stateRoot, b.runtimeRoot = stateRoot, runtimeRoot return b, nil } var current *Binding // Bind freezes the Runtime's Environment binding for this process. It runs once, before any Harness discovery. -func Bind(environment, session, workspace, capabilityDirectory string) error { - b, err := NewWithCapabilityDirectory(environment, session, workspace, capabilityDirectory) +func Bind(environment, workspace, capabilityDirectory string) error { + b, err := NewWithCapabilityDirectory(environment, workspace, capabilityDirectory) if err != nil { return err } @@ -66,7 +72,8 @@ func (b *Binding) Configure(r proto.PromptRequestPayload) (proto.PromptRequestPa if b == nil && r.LocalEnvironment == nil { return r, nil } - if b == nil || r.LocalEnvironment == nil || r.LocalEnvironment.ID != b.environment || r.AgentStateKey != b.stateKey || + sessionID, hasPrefix := strings.CutPrefix(r.AgentStateKey, proto.SessionStateKey("")) + if b == nil || r.LocalEnvironment == nil || r.LocalEnvironment.ID != b.environment || !hasPrefix || !canonicalID(sessionID) || r.DisableExecutionEnvironment { return r, errors.New("request does not match the dedicated local Environment") } @@ -90,6 +97,14 @@ func (b *Binding) Configure(r proto.PromptRequestPayload) (proto.PromptRequestPa return r, nil } -func (b *Binding) Matches(environment, session string) bool { - return b != nil && b.environment == environment && b.stateKey == proto.SessionStateKey(session) +func (b *Binding) Matches(environment string) bool { + return b != nil && b.environment == environment +} + +// RemoveOtherSessionState deletes every Session's native state but keepKey's. +func (b *Binding) RemoveOtherSessionState(keepKey string) error { + if b == nil { + return nil + } + return agent.RemoveSessionState(b.stateRoot, b.runtimeRoot, keepKey) } diff --git a/apps/daemon/internal/localworkspace/binding_test.go b/apps/daemon/internal/localworkspace/binding_test.go index 31bfea2fc..fe86860ea 100644 --- a/apps/daemon/internal/localworkspace/binding_test.go +++ b/apps/daemon/internal/localworkspace/binding_test.go @@ -20,7 +20,7 @@ func testBinding(t *testing.T) (*Binding, proto.PromptRequestPayload) { t.Setenv("OAC_RUNTIME_HOME", private) root := t.TempDir() environment, session := uuid.NewString(), uuid.NewString() - b, err := NewWithCapabilityDirectory(environment, session, root, t.TempDir()) + b, err := NewWithCapabilityDirectory(environment, root, t.TempDir()) if err != nil { t.Fatal(err) } @@ -38,8 +38,8 @@ func TestBindingRejectsScopeOverrides(t *testing.T) { "other Environment": func(r *proto.PromptRequestPayload) { r.LocalEnvironment = &proto.LocalEnvironment{ID: uuid.NewString()} }, - "other Session": func(r *proto.PromptRequestPayload) { r.AgentStateKey = uuid.NewString() }, - "none": func(r *proto.PromptRequestPayload) { r.DisableExecutionEnvironment = true }, + "non-canonical Session": func(r *proto.PromptRequestPayload) { r.AgentStateKey = "x y" }, + "none": func(r *proto.PromptRequestPayload) { r.DisableExecutionEnvironment = true }, } { t.Run(name, func(t *testing.T) { r := valid @@ -57,6 +57,20 @@ func TestBindingRejectsScopeOverrides(t *testing.T) { } } +func TestBindingServesSessionsInSequence(t *testing.T) { + b, req := testBinding(t) + for _, key := range []string{req.AgentStateKey, proto.SessionStateKey(uuid.NewString())} { + req.AgentStateKey = key + configured, err := b.Configure(req) + if err != nil { + t.Fatalf("Session %s: %v", key, err) + } + if _, err = b.Prepare(t.Context(), configured); err != nil { + t.Fatalf("Session %s: %v", key, err) + } + } +} + func TestDirectoryValidatesRelativePaths(t *testing.T) { b, _ := testBinding(t) got, err := b.ListWorkspaceDirectory(t.Context(), "", 2) @@ -96,11 +110,11 @@ func TestBindingPrepareRejectsOtherWorkspaceRoot(t *testing.T) { func TestCapabilityLayoutUsesOperatorDirectories(t *testing.T) { b, _ := testBinding(t) for _, directory := range []string{filepath.Join(b.workspace, "capabilities"), filepath.Join(os.Getenv("OAC_RUNTIME_HOME"), "capabilities")} { - if _, err := NewWithCapabilityDirectory(b.environment, b.capabilityIdentity().SessionID, b.workspace, directory); err != nil { + if _, err := NewWithCapabilityDirectory(b.environment, b.workspace, directory); err != nil { t.Fatal(err) } } - if _, err := NewWithCapabilityDirectory(b.environment, b.capabilityIdentity().SessionID, b.workspace, "relative"); err == nil { + if _, err := NewWithCapabilityDirectory(b.environment, b.workspace, "relative"); err == nil { t.Fatal("relative installation path accepted") } } diff --git a/apps/daemon/internal/localworkspace/capabilities.go b/apps/daemon/internal/localworkspace/capabilities.go index fc1558c7f..567dcd981 100644 --- a/apps/daemon/internal/localworkspace/capabilities.go +++ b/apps/daemon/internal/localworkspace/capabilities.go @@ -20,7 +20,7 @@ func (b *Binding) Prepare(ctx context.Context, r proto.PromptRequestPayload) (pr return r, nil } if b == nil || r.LocalEnvironment == nil || r.LocalEnvironment.CapabilitySources == nil || - r.LocalEnvironment.ID != b.environment || r.AgentStateKey != b.stateKey || r.LocalEnvironment.WorkspaceRoot != b.workspace { + r.LocalEnvironment.ID != b.environment || r.LocalEnvironment.WorkspaceRoot != b.workspace { return r, agentcapabilities.ErrInvalid } b.capabilityMu.Lock() @@ -86,7 +86,7 @@ func (b *Binding) Prepare(ctx context.Context, r proto.PromptRequestPayload) (pr // ApplyRuntimePreparation settles every filesystem operation before returning. A // cancelled caller never leaves an unowned installation goroutine behind. func (b *Binding) ApplyRuntimePreparation(ctx context.Context, input proto.RuntimePreparePayload, data []byte) error { - if b == nil || !b.Matches(input.EnvironmentID, input.SessionID) || !proto.ValidRuntimePrepareRequest(input) || input.Step != "begin" { + if b == nil || !b.Matches(input.EnvironmentID) || !proto.ValidRuntimePrepareRequest(input) || input.Step != "begin" { return agentcapabilities.ErrInvalid } b.capabilityMu.Lock() @@ -151,7 +151,7 @@ func (b *Binding) loadCapabilitySnapshot(root *os.Root, input proto.CapabilitySo } manifest, err := agentcapabilities.Load(root) if err == nil && !completed && manifest.Identity != identity { - // A preparation restored from an identical earlier Session carries that Session's identity. + // A preparation restored from an identical earlier Environment carries that Environment's identity. err = agentcapabilities.Rebind(root, &manifest, input, identity) } if err != nil || agentcapabilities.ValidateSelection(manifest, input, identity) != nil { @@ -161,7 +161,7 @@ func (b *Binding) loadCapabilitySnapshot(root *os.Root, input proto.CapabilitySo } func (b *Binding) capabilityIdentity() agentcapabilities.Identity { - return agentcapabilities.Identity{EnvironmentID: b.environment, SessionID: strings.TrimPrefix(b.stateKey, proto.SessionStateKey(""))} + return agentcapabilities.Identity{EnvironmentID: b.environment} } // The current Linux Runtime layout is shared by user-owned and managed hosts. diff --git a/apps/daemon/internal/localworkspace/capability_preparation_test.go b/apps/daemon/internal/localworkspace/capability_preparation_test.go index 06cd5f368..6d5b59bca 100644 --- a/apps/daemon/internal/localworkspace/capability_preparation_test.go +++ b/apps/daemon/internal/localworkspace/capability_preparation_test.go @@ -9,7 +9,6 @@ import ( "github.com/MiniMax-AI/OpenAgentCore/internal/agentcapabilities" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" - "github.com/google/uuid" ) func writeSourceSkill(t *testing.T, directory, text string) { @@ -40,7 +39,7 @@ func TestPreparationFreezesLocalContentsAcrossReconnect(t *testing.T) { t.Fatalf("first preparation: %v", err) } writeSourceSkill(t, source, "second") - reconnect, err := NewWithCapabilityDirectory(b.environment, b.capabilityIdentity().SessionID, b.workspace, b.capabilityRoot) + reconnect, err := NewWithCapabilityDirectory(b.environment, b.workspace, b.capabilityRoot) if err != nil { t.Fatal(err) } @@ -66,8 +65,7 @@ func TestPreparationFreezesLocalContentsAcrossReconnect(t *testing.T) { if err != nil || string(fresh[len(fresh)-6:]) != "second" { t.Fatal("new Session did not capture new source", err) } - // Reusing a snapshot under another selection cannot start native work, even - // for another Session. + // Reusing a snapshot under another selection cannot start native work. local := *configured.LocalEnvironment local.CapabilitySources = &proto.CapabilitySources{} changed := configured @@ -75,11 +73,6 @@ func TestPreparationFreezesLocalContentsAcrossReconnect(t *testing.T) { if _, err = b.Prepare(t.Context(), changed); err == nil { t.Fatal("changed selection accepted") } - reconnect.stateKey = uuid.NewString() - changed.AgentStateKey = reconnect.stateKey - if _, err = reconnect.Prepare(t.Context(), changed); err == nil { - t.Fatal("foreign snapshot accepted") - } } func TestPreparationUsesOperatorSourcesAndLeavesFailuresInert(t *testing.T) { @@ -204,7 +197,7 @@ func TestPreparationFreezesToolOnlyEnvironmentAcrossReconnect(t *testing.T) { if err := os.WriteFile(source, []byte(`{"LOCAL_ONLY":"changed"}`), 0600); err != nil { t.Fatal(err) } - reconnect, err := NewWithCapabilityDirectory(b.environment, b.capabilityIdentity().SessionID, b.workspace, b.capabilityRoot) + reconnect, err := NewWithCapabilityDirectory(b.environment, b.workspace, b.capabilityRoot) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/localworkspace/capability_rebind_test.go b/apps/daemon/internal/localworkspace/capability_rebind_test.go index a0a10ebfd..df0795ba9 100644 --- a/apps/daemon/internal/localworkspace/capability_rebind_test.go +++ b/apps/daemon/internal/localworkspace/capability_rebind_test.go @@ -23,7 +23,7 @@ func TestFinalizeRebindsIdenticalRestoredInstallation(t *testing.T) { t.Fatal(err) } // The next Session's directory holds the files restored from the first. - next, err := NewWithCapabilityDirectory(uuid.NewString(), uuid.NewString(), first.workspace, first.capabilityRoot) + next, err := NewWithCapabilityDirectory(uuid.NewString(), first.workspace, first.capabilityRoot) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/localworkspace/native_binding.go b/apps/daemon/internal/localworkspace/native_binding.go index 85e10a7c0..9f62e7cb0 100644 --- a/apps/daemon/internal/localworkspace/native_binding.go +++ b/apps/daemon/internal/localworkspace/native_binding.go @@ -5,17 +5,13 @@ import ( "os" "path/filepath" - "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" "github.com/MiniMax-AI/OpenAgentCore/internal/runtimefs" "github.com/google/uuid" ) -func newNativeBinding(environment, session, workspace, capabilities string) (*Binding, error) { - for _, value := range []string{environment, session} { - id, err := uuid.Parse(value) - if err != nil || id == uuid.Nil || id.String() != value { - return nil, errors.New("local workspace requires canonical resource identities") - } +func newNativeBinding(environment, workspace, capabilities string) (*Binding, error) { + if !canonicalID(environment) { + return nil, errors.New("local workspace requires a canonical Environment identity") } for _, path := range []string{workspace, capabilities} { if runtimefs.ValidateLocalPath(path) != nil || filepath.Dir(path) == path { @@ -26,7 +22,12 @@ func newNativeBinding(environment, session, workspace, capabilities string) (*Bi if err != nil || !info.IsDir() { return nil, errors.New("local workspace root must be an existing directory") } - return &Binding{environment: environment, stateKey: proto.SessionStateKey(session), workspace: workspace, capabilityRoot: capabilities, writer: &fileWriter{}}, nil + return &Binding{environment: environment, workspace: workspace, capabilityRoot: capabilities, writer: &fileWriter{}}, nil +} + +func canonicalID(value string) bool { + id, err := uuid.Parse(value) + return err == nil && id != uuid.Nil && id.String() == value } // ReadToolEnvironment reads explicit initialization values for this installation. diff --git a/apps/daemon/internal/localworkspace/runtime_initialization_test.go b/apps/daemon/internal/localworkspace/runtime_initialization_test.go index 4e4aeb2bf..3b6472e46 100644 --- a/apps/daemon/internal/localworkspace/runtime_initialization_test.go +++ b/apps/daemon/internal/localworkspace/runtime_initialization_test.go @@ -347,7 +347,7 @@ func TestRuntimePreparationRejectsFilesAfterFinalization(t *testing.T) { t.Fatal(err) } digest := sha256.Sum256(nil) - input := proto.RuntimePreparePayload{BudgetMS: 300000, Step: "begin", EnvironmentID: b.environment, SessionID: b.capabilityIdentity().SessionID, + input := proto.RuntimePreparePayload{BudgetMS: 300000, Step: "begin", EnvironmentID: b.environment, Action: "file", File: &proto.RuntimeInitialFile{Path: "/workspace/file"}, SHA256: hex.EncodeToString(digest[:])} if err = b.ApplyRuntimePreparation(t.Context(), input, nil); !errors.Is(err, agentcapabilities.ErrInvalid) { t.Fatal("finalized Runtime accepted file", err) diff --git a/apps/daemon/internal/localworkspace/snapshot_marker.go b/apps/daemon/internal/localworkspace/snapshot_marker.go index 48ea5e49e..f3e2a813a 100644 --- a/apps/daemon/internal/localworkspace/snapshot_marker.go +++ b/apps/daemon/internal/localworkspace/snapshot_marker.go @@ -23,11 +23,8 @@ type snapshotMarker struct { func (b *Binding) openSnapshotMarker() (*snapshotMarker, error) { identity := b.capabilityIdentity() - for _, id := range []string{identity.EnvironmentID, identity.SessionID} { - parsed, err := uuid.Parse(id) - if err != nil || parsed == uuid.Nil || parsed.String() != id { - return nil, agentcapabilities.ErrInvalid - } + if parsed, err := uuid.Parse(identity.EnvironmentID); err != nil || parsed == uuid.Nil || parsed.String() != identity.EnvironmentID { + return nil, agentcapabilities.ErrInvalid } private := b.stateRoot if agentcapabilities.ValidateLocalDirectories([]string{private}) != nil { @@ -65,7 +62,7 @@ func (b *Binding) openSnapshotMarker() (*snapshotMarker, error) { current.Close() return nil, agentcapabilities.ErrInvalid } - marker := &snapshotMarker{directory: current, unlock: unlock, name: identity.EnvironmentID + "-" + identity.SessionID + ".json", root: b.capabilityRoot} + marker := &snapshotMarker{directory: current, unlock: unlock, name: identity.EnvironmentID + ".json", root: b.capabilityRoot} completed, err := marker.read() if err != nil { marker.close() diff --git a/apps/daemon/internal/localworkspace/snapshot_marker_test.go b/apps/daemon/internal/localworkspace/snapshot_marker_test.go index 5126ade53..2748be6dc 100644 --- a/apps/daemon/internal/localworkspace/snapshot_marker_test.go +++ b/apps/daemon/internal/localworkspace/snapshot_marker_test.go @@ -27,7 +27,7 @@ func markerBinding(t *testing.T) (*Binding, proto.PromptRequestPayload) { } func markerPath(b *Binding) string { identity := b.capabilityIdentity() - return filepath.Join(b.stateRoot, "daemon", "capability-installations", identity.EnvironmentID+"-"+identity.SessionID+".json") + return filepath.Join(b.stateRoot, "daemon", "capability-installations", identity.EnvironmentID+".json") } func TestSnapshotMarkerRoundTrip(t *testing.T) { b, _ := markerBinding(t) @@ -185,7 +185,7 @@ func TestSnapshotMarkerRefusesDamagedState(t *testing.T) { func TestCapabilityFinalizeRecordsCompletionAndRejectsLaterImports(t *testing.T) { b, _ := markerBinding(t) identity := b.capabilityIdentity() - finalize := proto.RuntimePreparePayload{BudgetMS: 300000, Step: "begin", EnvironmentID: identity.EnvironmentID, SessionID: identity.SessionID, Action: "finalize", Sources: &proto.CapabilitySources{}} + finalize := proto.RuntimePreparePayload{BudgetMS: 300000, Step: "begin", EnvironmentID: identity.EnvironmentID, Action: "finalize", Sources: &proto.CapabilitySources{}} if err := b.ApplyRuntimePreparation(t.Context(), finalize, nil); err != nil { t.Fatal(err) } @@ -196,7 +196,7 @@ func TestCapabilityFinalizeRecordsCompletionAndRejectsLaterImports(t *testing.T) if err := os.RemoveAll(b.capabilityRoot); err != nil { t.Fatal(err) } - skill := proto.RuntimePreparePayload{BudgetMS: 300000, Step: "begin", EnvironmentID: identity.EnvironmentID, SessionID: identity.SessionID, Action: "skill", Skill: &proto.SkillMetadata{Type: "inline", Name: "example", Description: "Example"}, SizeBytes: 1, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"} + skill := proto.RuntimePreparePayload{BudgetMS: 300000, Step: "begin", EnvironmentID: identity.EnvironmentID, Action: "skill", Skill: &proto.SkillMetadata{Type: "inline", Name: "example", Description: "Example"}, SizeBytes: 1, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"} if err := b.ApplyRuntimePreparation(t.Context(), skill, []byte("x")); err == nil { t.Fatal("completed identity accepted import") } @@ -237,7 +237,7 @@ func TestCapabilityMarkerSurvivesComputeReplacement(t *testing.T) { marker.close() t.Setenv("OAC_RUNTIME_HOME", t.TempDir()) identity := b.capabilityIdentity() - replacement, err := NewWithCapabilityDirectory(identity.EnvironmentID, identity.SessionID, b.workspace, b.capabilityRoot) + replacement, err := NewWithCapabilityDirectory(identity.EnvironmentID, b.workspace, b.capabilityRoot) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/internal/localworkspace/write.go b/apps/daemon/internal/localworkspace/write.go index 22094814f..3b54d3f7d 100644 --- a/apps/daemon/internal/localworkspace/write.go +++ b/apps/daemon/internal/localworkspace/write.go @@ -12,8 +12,8 @@ import ( // This private transfer bound is distinct from the public inline-file limit. const WriteMaxBytes = proto.WorkspaceWriteMaxBytes -func (b *Binding) AcceptsFileWrite(environment, session string) bool { - return b != nil && b.writer != nil && b.environment == environment && b.stateKey == proto.SessionStateKey(session) +func (b *Binding) AcceptsFileWrite(environment string) bool { + return b != nil && b.writer != nil && b.environment == environment } // WriteWorkspaceFile starts only after the caller supplies the complete bounded diff --git a/apps/daemon/internal/transport/ws_test.go b/apps/daemon/internal/transport/ws_test.go index a81b6cccc..6ad199f9b 100644 --- a/apps/daemon/internal/transport/ws_test.go +++ b/apps/daemon/internal/transport/ws_test.go @@ -28,7 +28,6 @@ type fakeGateway struct { dialURL string dialAuth string frames []proto.Envelope - wantAuth bool legacy bool connCh chan *websocket.Conn diff --git a/apps/daemon/internal/wireconformance/wire_test.go b/apps/daemon/internal/wireconformance/wire_test.go index 937f2db6d..c5acd2704 100644 --- a/apps/daemon/internal/wireconformance/wire_test.go +++ b/apps/daemon/internal/wireconformance/wire_test.go @@ -157,7 +157,7 @@ func connectRuntime(t *testing.T, peer *corePeer, setupErr error) *runtimeSide { peer.accept(t) rt := &runtimeSide{conn: conn, executor: &controlledExecutor{turn: make(chan *controlledTurn, 1)}, stopped: make(chan struct{})} kinds := agent.NewRegistry() - kinds.RegisterKind(proto.SupportedAgentKind{Kind: prototest.HarnessKind, Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{EnvironmentNone: proto.CapabilitySupported})}, harnessconfig.Configuration{}) + kinds.RegisterKind(proto.SupportedAgentKind{Kind: prototest.HarnessKind, Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{EnvironmentNone: proto.CapabilitySupported})}, harnessconfig.Declaration{Execution: harnessconfig.ExecutionOptions{ReasoningEfforts: []string{prototest.Turn.ReasoningEffort}, Reviews: []string{prototest.Turn.Review}}}) kinds.RegisterExecutor(prototest.HarnessKind, func(context.Context, proto.PromptRequestPayload) (agent.Executor, error) { return rt.executor, setupErr }) @@ -323,7 +323,10 @@ type controlledExecutor struct { } func (e *controlledExecutor) Close(context.Context) error { e.closes.Add(1); return nil } -func (e *controlledExecutor) StartTurn(_ context.Context, id string, _ proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { +func (e *controlledExecutor) StartTurn(_ context.Context, id string, settings proto.TurnSettings, _ proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { + if settings != prototest.Turn { + return nil, errors.New("Turn settings did not reach StartTurn") + } e.starts.Add(1) turn := &controlledTurn{id: id, out: out, cancelling: make(chan struct{}), allowCancel: make(chan struct{}), settled: make(chan struct{})} e.turn <- turn diff --git a/apps/daemon/internal/workspaceobs/export_test.go b/apps/daemon/internal/workspaceobs/export_test.go index b72e09caa..1bba67af3 100644 --- a/apps/daemon/internal/workspaceobs/export_test.go +++ b/apps/daemon/internal/workspaceobs/export_test.go @@ -18,7 +18,7 @@ import ( func TestWriterActualProducerBackpressureAndActiveEnvelope(t *testing.T) { for _, active := range []bool{false, true} { t.Run(map[bool]string{false: "slow_reader", true: "active_work"}[active], func(t *testing.T) { - binding, err := localworkspace.NewWithCapabilityDirectory(uuid.NewString(), uuid.NewString(), t.TempDir(), t.TempDir()) + binding, err := localworkspace.NewWithCapabilityDirectory(uuid.NewString(), t.TempDir(), t.TempDir()) if err != nil { t.Fatal(err) } diff --git a/apps/daemon/testdata/onboarding/main.go b/apps/daemon/testdata/onboarding/main.go index 59bc3e2ea..5414e0189 100644 --- a/apps/daemon/testdata/onboarding/main.go +++ b/apps/daemon/testdata/onboarding/main.go @@ -63,7 +63,7 @@ type executor struct { closed bool } -func (e *executor) StartTurn(ctx context.Context, run string, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { +func (e *executor) StartTurn(ctx context.Context, run string, _ proto.TurnSettings, input proto.MessageInput, out chan<- proto.Envelope) (agent.Turn, error) { if ctx.Err() != nil || run == "" || out == nil { return nil, errors.New("invalid fixture Start") } @@ -165,7 +165,7 @@ func run() error { h := &harness{history: map[string]string{}} registry.RegisterKind(proto.SupportedAgentKind{Kind: "fixture_harness", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{ Streaming: proto.CapabilitySupported, DurableTurns: proto.CapabilitySupported, DurableInputReceipts: proto.CapabilitySupported, ExecutionControls: proto.CapabilitySupported, ToolObservations: proto.CapabilitySupported, SubagentControl: proto.CapabilitySupported, EnvironmentNone: proto.CapabilitySupported, - })}, harnessconfig.Configuration{}) + })}, harnessconfig.Declaration{}) registry.RegisterExecutor("fixture_harness", h.prepare) sink := &sender{encoder: json.NewEncoder(os.Stdout)} router, err := dispatch.New(dispatch.Config{Registry: registry, Sender: sink, Log: slog.New(slog.NewTextHandler(io.Discard, nil))}) diff --git a/apps/web/.impeccable/design.json b/apps/web/.impeccable/design.json deleted file mode 100644 index ed5f742b6..000000000 --- a/apps/web/.impeccable/design.json +++ /dev/null @@ -1,787 +0,0 @@ -{ - "schemaVersion": 2, - "generatedAt": "2026-09-30T07:33:58.959421+00:00", - "title": "Design System: OpenAgentCore Console", - "extensions": { - "colorMeta": { - "ink": { - "role": "neutral", - "displayName": "Ledger Ink", - "canonical": "oklch(0.247 0.006 258.361)", - "cssVar": "--ink", - "dark": "oklch(0.964 0.002 247.839)", - "tonalRamp": [ - "oklch(0.15 0.006 258.361)", - "oklch(0.27 0.006 258.361)", - "oklch(0.39 0.006 258.361)", - "oklch(0.51 0.006 258.361)", - "oklch(0.63 0.006 258.361)", - "oklch(0.75 0.006 258.361)", - "oklch(0.87 0.006 258.361)", - "oklch(0.95 0.006 258.361)" - ] - }, - "ink-muted": { - "role": "neutral", - "displayName": "Graphite", - "canonical": "oklch(0.506 0.01 264.477)", - "cssVar": "--ink-2", - "dark": "oklch(0.731 0.008 260.731)", - "tonalRamp": [ - "oklch(0.15 0.01 264.477)", - "oklch(0.27 0.01 264.477)", - "oklch(0.39 0.01 264.477)", - "oklch(0.51 0.01 264.477)", - "oklch(0.63 0.01 264.477)", - "oklch(0.75 0.01 264.477)", - "oklch(0.87 0.01 264.477)", - "oklch(0.95 0.01 264.477)" - ] - }, - "ink-subtle": { - "role": "neutral", - "displayName": "Pencil", - "canonical": "oklch(0.695 0.009 264.505)", - "cssVar": "--ink-3", - "dark": "oklch(0.541 0.01 264.484)", - "tonalRamp": [ - "oklch(0.15 0.009 264.505)", - "oklch(0.27 0.009 264.505)", - "oklch(0.39 0.009 264.505)", - "oklch(0.51 0.009 264.505)", - "oklch(0.63 0.009 264.505)", - "oklch(0.75 0.009 264.505)", - "oklch(0.87 0.009 264.505)", - "oklch(0.95 0.009 264.505)" - ] - }, - "sidebar-ink": { - "role": "neutral", - "displayName": "Sidebar Ink", - "canonical": "oklch(0.506 0.01 264.477)", - "cssVar": "--ink-2", - "dark": "oklch(0.731 0.008 260.731)", - "tonalRamp": [ - "oklch(0.15 0.01 264.477)", - "oklch(0.27 0.01 264.477)", - "oklch(0.39 0.01 264.477)", - "oklch(0.51 0.01 264.477)", - "oklch(0.63 0.01 264.477)", - "oklch(0.75 0.01 264.477)", - "oklch(0.87 0.01 264.477)", - "oklch(0.95 0.01 264.477)" - ] - }, - "surface": { - "role": "neutral", - "displayName": "Paper", - "canonical": "oklch(1 0 0)", - "cssVar": "--surface", - "dark": "oklch(0.26 0.006 271.191)", - "tonalRamp": [ - "oklch(0.15 0 0)", - "oklch(0.27 0 0)", - "oklch(0.39 0 0)", - "oklch(0.51 0 0)", - "oklch(0.63 0 0)", - "oklch(0.75 0 0)", - "oklch(0.87 0 0)", - "oklch(0.95 0 0)" - ] - }, - "surface-subtle": { - "role": "neutral", - "displayName": "Margin Gray", - "canonical": "oklch(0.979 0.002 247.839)", - "cssVar": "--inset", - "dark": "oklch(0.243 0.004 264.492)", - "tonalRamp": [ - "oklch(0.15 0.002 247.839)", - "oklch(0.27 0.002 247.839)", - "oklch(0.39 0.002 247.839)", - "oklch(0.51 0.002 247.839)", - "oklch(0.63 0.002 247.839)", - "oklch(0.75 0.002 247.839)", - "oklch(0.87 0.002 247.839)", - "oklch(0.95 0.002 247.839)" - ] - }, - "surface-muted": { - "role": "neutral", - "displayName": "Well Gray", - "canonical": "oklch(0.961 0.001 286.375)", - "cssVar": "--field", - "dark": "oklch(0.293 0.006 271.223)", - "tonalRamp": [ - "oklch(0.15 0.001 286.375)", - "oklch(0.27 0.001 286.375)", - "oklch(0.39 0.001 286.375)", - "oklch(0.51 0.001 286.375)", - "oklch(0.63 0.001 286.375)", - "oklch(0.75 0.001 286.375)", - "oklch(0.87 0.001 286.375)", - "oklch(0.95 0.001 286.375)" - ] - }, - "canvas": { - "role": "neutral", - "displayName": "Canvas", - "canonical": "oklch(0.961 0.002 247.84)", - "cssVar": "--canvas", - "dark": "oklch(0.231 0.004 264.487)", - "tonalRamp": [ - "oklch(0.15 0.002 247.84)", - "oklch(0.27 0.002 247.84)", - "oklch(0.39 0.002 247.84)", - "oklch(0.51 0.002 247.84)", - "oklch(0.63 0.002 247.84)", - "oklch(0.75 0.002 247.84)", - "oklch(0.87 0.002 247.84)", - "oklch(0.95 0.002 247.84)" - ] - }, - "frame-line": { - "role": "neutral", - "displayName": "Card Edge", - "canonical": "color-mix(in oklch, oklch(0.247 0.006 258.361) 11%, transparent)", - "cssVar": "--frame-line", - "dark": "oklch(1 0 0 / 10%)", - "tonalRamp": [] - }, - "line": { - "role": "neutral", - "displayName": "Hairline", - "canonical": "oklch(0.946 0.003 264.542)", - "cssVar": "--line", - "dark": "oklch(0.308 0.006 258.354)", - "tonalRamp": [ - "oklch(0.15 0.003 264.542)", - "oklch(0.27 0.003 264.542)", - "oklch(0.39 0.003 264.542)", - "oklch(0.51 0.003 264.542)", - "oklch(0.63 0.003 264.542)", - "oklch(0.75 0.003 264.542)", - "oklch(0.87 0.003 264.542)", - "oklch(0.95 0.003 264.542)" - ] - }, - "line-muted": { - "role": "neutral", - "displayName": "Faint Rule", - "canonical": "oklch(0.966 0.002 264.542)", - "cssVar": "--line-soft", - "dark": "oklch(0.278 0.006 258.354)", - "tonalRamp": [ - "oklch(0.15 0.002 264.542)", - "oklch(0.27 0.002 264.542)", - "oklch(0.39 0.002 264.542)", - "oklch(0.51 0.002 264.542)", - "oklch(0.63 0.002 264.542)", - "oklch(0.75 0.002 264.542)", - "oklch(0.87 0.002 264.542)", - "oklch(0.95 0.002 264.542)" - ] - }, - "line-strong": { - "role": "neutral", - "displayName": "Firm Rule", - "canonical": "oklch(0.912 0.005 258.326)", - "cssVar": "--line-strong", - "dark": "oklch(0.356 0.007 264.474)", - "tonalRamp": [ - "oklch(0.15 0.005 258.326)", - "oklch(0.27 0.005 258.326)", - "oklch(0.39 0.005 258.326)", - "oklch(0.51 0.005 258.326)", - "oklch(0.63 0.005 258.326)", - "oklch(0.75 0.005 258.326)", - "oklch(0.87 0.005 258.326)", - "oklch(0.95 0.005 258.326)" - ] - }, - "hover": { - "role": "neutral", - "displayName": "Hover", - "canonical": "oklch(0.97 0.002 247.839)", - "cssVar": "--hover", - "dark": "oklch(0.289 0.006 271.22)", - "tonalRamp": [ - "oklch(0.15 0.002 247.839)", - "oklch(0.27 0.002 247.839)", - "oklch(0.39 0.002 247.839)", - "oklch(0.51 0.002 247.839)", - "oklch(0.63 0.002 247.839)", - "oklch(0.75 0.002 247.839)", - "oklch(0.87 0.002 247.839)", - "oklch(0.95 0.002 247.839)" - ] - }, - "pressed": { - "role": "neutral", - "displayName": "Pressed", - "canonical": "oklch(0.933 0.003 247.86)", - "cssVar": "--hover-2", - "dark": "oklch(0.318 0.007 274.747)", - "tonalRamp": [ - "oklch(0.15 0.003 247.86)", - "oklch(0.27 0.003 247.86)", - "oklch(0.39 0.003 247.86)", - "oklch(0.51 0.003 247.86)", - "oklch(0.63 0.003 247.86)", - "oklch(0.75 0.003 247.86)", - "oklch(0.87 0.003 247.86)", - "oklch(0.95 0.003 247.86)" - ] - }, - "tile": { - "role": "neutral", - "displayName": "Tile", - "canonical": "oklch(0.933 0.003 247.86)", - "cssVar": "--hover-2", - "dark": "oklch(0.318 0.007 274.747)", - "tonalRamp": [ - "oklch(0.15 0.003 247.86)", - "oklch(0.27 0.003 247.86)", - "oklch(0.39 0.003 247.86)", - "oklch(0.51 0.003 247.86)", - "oklch(0.63 0.003 247.86)", - "oklch(0.75 0.003 247.86)", - "oklch(0.87 0.003 247.86)", - "oklch(0.95 0.003 247.86)" - ] - }, - "accent": { - "role": "primary", - "displayName": "OpenAgentCore Indigo", - "canonical": "oklch(0.52 0.165 277)", - "cssVar": "--accent", - "dark": "oklch(0.72 0.12 277)", - "tonalRamp": [ - "oklch(0.15 0.165 277)", - "oklch(0.27 0.165 277)", - "oklch(0.39 0.165 277)", - "oklch(0.51 0.165 277)", - "oklch(0.63 0.165 277)", - "oklch(0.75 0.165 277)", - "oklch(0.87 0.165 277)", - "oklch(0.95 0.165 277)" - ] - }, - "accent-emphasis": { - "role": "primary", - "displayName": "Pressed Indigo", - "canonical": "oklch(0.47 0.16 277)", - "cssVar": "--accent-ink", - "dark": "oklch(0.8 0.1 277)", - "tonalRamp": [ - "oklch(0.15 0.16 277)", - "oklch(0.27 0.16 277)", - "oklch(0.39 0.16 277)", - "oklch(0.51 0.16 277)", - "oklch(0.63 0.16 277)", - "oklch(0.75 0.16 277)", - "oklch(0.87 0.16 277)", - "oklch(0.95 0.16 277)" - ] - }, - "accent-fg": { - "role": "primary", - "displayName": "On Indigo", - "canonical": "#ffffff", - "cssVar": "--accent-fg", - "dark": "oklch(0.2 0.03 277)", - "tonalRamp": [] - }, - "data": { - "role": "data", - "displayName": "Data", - "canonical": "oklch(0.56 0.14 277)", - "cssVar": "--data", - "dark": "oklch(0.68 0.13 277)", - "tonalRamp": [ - "oklch(0.15 0.14 277)", - "oklch(0.27 0.14 277)", - "oklch(0.39 0.14 277)", - "oklch(0.51 0.14 277)", - "oklch(0.63 0.14 277)", - "oklch(0.75 0.14 277)", - "oklch(0.87 0.14 277)", - "oklch(0.95 0.14 277)" - ] - }, - "success": { - "role": "signal", - "displayName": "Healthy Green", - "canonical": "oklch(0.6 0.12 158)", - "cssVar": "--green", - "dark": "oklch(0.72 0.12 158)", - "tonalRamp": [ - "oklch(0.15 0.12 158)", - "oklch(0.27 0.12 158)", - "oklch(0.39 0.12 158)", - "oklch(0.51 0.12 158)", - "oklch(0.63 0.12 158)", - "oklch(0.75 0.12 158)", - "oklch(0.87 0.12 158)", - "oklch(0.95 0.12 158)" - ] - }, - "warning": { - "role": "signal", - "displayName": "Caution Amber", - "canonical": "oklch(0.68 0.135 62)", - "cssVar": "--orange", - "dark": "oklch(0.76 0.12 65)", - "tonalRamp": [ - "oklch(0.15 0.135 62)", - "oklch(0.27 0.135 62)", - "oklch(0.39 0.135 62)", - "oklch(0.51 0.135 62)", - "oklch(0.63 0.135 62)", - "oklch(0.75 0.135 62)", - "oklch(0.87 0.135 62)", - "oklch(0.95 0.135 62)" - ] - }, - "danger": { - "role": "signal", - "displayName": "Fault Red", - "canonical": "oklch(0.585 0.17 25)", - "cssVar": "--red", - "dark": "oklch(0.68 0.15 25)", - "tonalRamp": [ - "oklch(0.15 0.17 25)", - "oklch(0.27 0.17 25)", - "oklch(0.39 0.17 25)", - "oklch(0.51 0.17 25)", - "oklch(0.63 0.17 25)", - "oklch(0.75 0.17 25)", - "oklch(0.87 0.17 25)", - "oklch(0.95 0.17 25)" - ] - }, - "status-queued": { - "role": "signal", - "displayName": "Queued Gray", - "canonical": "oklch(0.695 0.009 264.505)", - "cssVar": "--ink-3", - "dark": "oklch(0.541 0.01 264.484)", - "tonalRamp": [ - "oklch(0.15 0.009 264.505)", - "oklch(0.27 0.009 264.505)", - "oklch(0.39 0.009 264.505)", - "oklch(0.51 0.009 264.505)", - "oklch(0.63 0.009 264.505)", - "oklch(0.75 0.009 264.505)", - "oklch(0.87 0.009 264.505)", - "oklch(0.95 0.009 264.505)" - ] - }, - "series-1": { - "role": "data", - "displayName": "Indigo", - "canonical": "oklch(0.56 0.14 277)", - "cssVar": "--series-1", - "dark": "oklch(0.68 0.13 277)", - "tonalRamp": [ - "oklch(0.15 0.14 277)", - "oklch(0.27 0.14 277)", - "oklch(0.39 0.14 277)", - "oklch(0.51 0.14 277)", - "oklch(0.63 0.14 277)", - "oklch(0.75 0.14 277)", - "oklch(0.87 0.14 277)", - "oklch(0.95 0.14 277)" - ] - }, - "series-2": { - "role": "data", - "displayName": "Teal", - "canonical": "oklch(0.7 0.09 195)", - "cssVar": "--series-2", - "dark": "oklch(0.74 0.09 195)", - "tonalRamp": [ - "oklch(0.15 0.09 195)", - "oklch(0.27 0.09 195)", - "oklch(0.39 0.09 195)", - "oklch(0.51 0.09 195)", - "oklch(0.63 0.09 195)", - "oklch(0.75 0.09 195)", - "oklch(0.87 0.09 195)", - "oklch(0.95 0.09 195)" - ] - }, - "series-3": { - "role": "data", - "displayName": "Ochre", - "canonical": "oklch(0.78 0.11 80)", - "cssVar": "--series-3", - "dark": "oklch(0.8 0.1 80)", - "tonalRamp": [ - "oklch(0.15 0.11 80)", - "oklch(0.27 0.11 80)", - "oklch(0.39 0.11 80)", - "oklch(0.51 0.11 80)", - "oklch(0.63 0.11 80)", - "oklch(0.75 0.11 80)", - "oklch(0.87 0.11 80)", - "oklch(0.95 0.11 80)" - ] - }, - "series-4": { - "role": "data", - "displayName": "Coral", - "canonical": "oklch(0.66 0.12 20)", - "cssVar": "--series-4", - "dark": "oklch(0.72 0.11 20)", - "tonalRamp": [ - "oklch(0.15 0.12 20)", - "oklch(0.27 0.12 20)", - "oklch(0.39 0.12 20)", - "oklch(0.51 0.12 20)", - "oklch(0.63 0.12 20)", - "oklch(0.75 0.12 20)", - "oklch(0.87 0.12 20)", - "oklch(0.95 0.12 20)" - ] - }, - "series-5": { - "role": "data", - "displayName": "Slate", - "canonical": "oklch(0.62 0.06 250)", - "cssVar": "--series-5", - "dark": "oklch(0.7 0.06 250)", - "tonalRamp": [ - "oklch(0.15 0.06 250)", - "oklch(0.27 0.06 250)", - "oklch(0.39 0.06 250)", - "oklch(0.51 0.06 250)", - "oklch(0.63 0.06 250)", - "oklch(0.75 0.06 250)", - "oklch(0.87 0.06 250)", - "oklch(0.95 0.06 250)" - ] - }, - "series-6": { - "role": "data", - "displayName": "Sage", - "canonical": "oklch(0.72 0.08 145)", - "cssVar": "--series-6", - "dark": "oklch(0.76 0.08 145)", - "tonalRamp": [ - "oklch(0.15 0.08 145)", - "oklch(0.27 0.08 145)", - "oklch(0.39 0.08 145)", - "oklch(0.51 0.08 145)", - "oklch(0.63 0.08 145)", - "oklch(0.75 0.08 145)", - "oklch(0.87 0.08 145)", - "oklch(0.95 0.08 145)" - ] - }, - "series-other": { - "role": "data", - "displayName": "Series Other", - "canonical": "oklch(0.82 0.008 264)", - "cssVar": "--series-other", - "dark": "oklch(0.45 0.01 264)", - "tonalRamp": [ - "oklch(0.15 0.008 264)", - "oklch(0.27 0.008 264)", - "oklch(0.39 0.008 264)", - "oklch(0.51 0.008 264)", - "oklch(0.63 0.008 264)", - "oklch(0.75 0.008 264)", - "oklch(0.87 0.008 264)", - "oklch(0.95 0.008 264)" - ] - }, - "meter-fill": { - "role": "data", - "displayName": "Meter Fill", - "canonical": "color-mix(in srgb, oklch(0.247 0.006 258.361) 62%, transparent)", - "cssVar": "--meter-fill", - "dark": "color-mix(in srgb, oklch(0.964 0.002 247.839) 62%, transparent)", - "tonalRamp": [] - } - }, - "typographyMeta": { - "metric": { - "displayName": "Metric", - "purpose": "The four Overview tiles; tabular numerals." - }, - "display": { - "displayName": "KPI Figure", - "purpose": "KPI strip values; tabular numerals, one step above body text." - }, - "headline": { - "displayName": "Page Title", - "purpose": "One per page in the page header." - }, - "title": { - "displayName": "Section Title", - "purpose": "Section and card headings; dialog titles step up to 15px." - }, - "body": { - "displayName": "Body", - "purpose": "Table cells, controls, fields, dialog text; document base is 14px/20px." - }, - "label": { - "displayName": "Label", - "purpose": "KPI labels, column headers, text actions, segmented options, the list count." - }, - "mono": { - "displayName": "Mono", - "purpose": "IDs in name cells (Graphite) and other code in tables (Pencil)." - } - }, - "shadows": [ - { - "name": "panel-shadow", - "value": "0 0 0 1px var(--line), 0 1px 2px oklch(0 0 0 / 3%), 0 8px 24px -12px oklch(0 0 0 / 8%)", - "dark": "0 0 0 1px oklch(1 0 0 / 8%), 0 8px 28px -12px oklch(0 0 0 / 50%)", - "purpose": "The white page panel on the canvas." - }, - { - "name": "shadow-card", - "value": "0 0 0 1px var(--frame-line)", - "dark": "0 0 0 1px oklch(1 0 0 / 10%)", - "purpose": "Cards, KPI strips, table frames, chart grids and empty states: a ring only, no drop shadow." - }, - { - "name": "shadow-btn", - "value": "0 0 0 1px var(--line-strong), var(--shadow-xs)", - "dark": "0 0 0 1px oklch(1 0 0 / 0.1), 0 1px 2px oklch(0 0 0 / 0.3)", - "purpose": "Outline buttons, the active segment, and search fields and selects in toolbars." - }, - { - "name": "shadow-hairline", - "value": "0 0 0 1px var(--line)", - "dark": "0 0 0 1px var(--line)", - "purpose": "The ring of inputs and selects inside cards and dialogs, and of count and value pills." - }, - { - "name": "shadow-overlay", - "value": "0 0 0 1px var(--line), var(--shadow-lg)", - "dark": "0 0 0 1px oklch(1 0 0 / 0.15), 0 8px 28px oklch(0 0 0 / 0.34)", - "purpose": "Anchored popovers, menus, dialogs, help tips and chart tooltips." - } - ], - "motion": [ - { - "name": "ease-out-strong", - "value": "cubic-bezier(0.23, 1, 0.32, 1)", - "purpose": "Colour, background and press transitions of buttons, navigation items and segments (150ms); press scales buttons to 0.96." - }, - { - "name": "ease-spring", - "value": "cubic-bezier(0.34, 1.56, 0.64, 1)", - "purpose": "Dialog entry: pop-in from 96% scale in 200ms." - }, - { - "name": "ease-settle", - "value": "cubic-bezier(0.22, 1, 0.36, 1)", - "purpose": "Dialog exit (150ms) and overlay fades." - }, - { - "name": "layout-glide", - "value": "spring, 320ms, no bounce (Motion shared layout)", - "purpose": "The navigation chip and segmented thumbs glide to a new choice." - }, - { - "name": "popover-in", - "value": "opacity 0 to 1, scale 98% to 100%", - "purpose": "Anchored popovers." - }, - { - "name": "page-in", - "value": "opacity 0 to 1, 160ms", - "purpose": "Page change; no choreography." - }, - { - "name": "skeleton-sweep", - "value": "900ms linear, repeating", - "purpose": "First-read skeleton bars; stops under reduced motion." - }, - { - "name": "fleet-link-flow", - "value": "4s linear, repeating", - "purpose": "The moving dash on a live topology link; none on offline links, a stale topology or under reduced motion." - } - ], - "breakpoints": [ - { - "name": "sidebar-rail", - "value": "640px" - }, - { - "name": "min-desktop", - "value": "960px" - }, - { - "name": "stack-charts", - "value": "1180px" - } - ] - }, - "components": [ - { - "name": "Primary Button", - "kind": "button", - "refersTo": "button-primary", - "description": "The one filled button in a header or a non-destructive dialog; ink, not indigo.", - "html": "", - "css": ".ds-btn { display:inline-flex; height:30px; align-items:center; gap:6px; padding:0 13px; font:500 13px/1 \"Inter Variable\", -apple-system, BlinkMacSystemFont, \"PingFang SC\", \"Segoe UI\", \"Microsoft YaHei\", \"Noto Sans SC\", sans-serif; border:0; border-radius:8px; cursor:pointer; transition: transform 150ms cubic-bezier(0.23,1,0.32,1), background-color 150ms cubic-bezier(0.23,1,0.32,1), opacity 150ms cubic-bezier(0.23,1,0.32,1); } .ds-btn-primary { color: var(--canvas); background: var(--ink); box-shadow: inset 0 1px 0 rgb(255 255 255 / 14%), var(--shadow-xs); } .ds-btn-primary:hover { opacity: 0.88; } .ds-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } .ds-btn:active { transform: scale(0.96); }" - }, - { - "name": "Outline Button", - "kind": "button", - "refersTo": "button-outline", - "description": "Every action in a card or section header; Paper with the Firm Rule ring.", - "html": "", - "css": ".ds-btn-outline { display:inline-flex; height:30px; align-items:center; gap:6px; padding:0 13px; font:500 13px/1 \"Inter Variable\", -apple-system, BlinkMacSystemFont, \"PingFang SC\", \"Segoe UI\", \"Microsoft YaHei\", \"Noto Sans SC\", sans-serif; border:0; border-radius:8px; cursor:pointer; transition: transform 150ms cubic-bezier(0.23,1,0.32,1), background-color 150ms cubic-bezier(0.23,1,0.32,1), opacity 150ms cubic-bezier(0.23,1,0.32,1); color: var(--ink); background: var(--surface); box-shadow: var(--shadow-btn); } .ds-btn-outline:hover { background: var(--inset); } .ds-btn-outline:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } .ds-btn-outline:active { transform: scale(0.96); }" - }, - { - "name": "Text Field", - "kind": "input", - "refersTo": "input-field", - "description": "30px filled field with a Hairline ring inside cards and dialogs; focus turns it Paper with an indigo ring.", - "html": "", - "css": ".ds-input { width:240px; height:30px; padding:0 10px; color: var(--ink); font:400 13px/18px \"Inter Variable\", -apple-system, BlinkMacSystemFont, \"PingFang SC\", \"Segoe UI\", \"Microsoft YaHei\", \"Noto Sans SC\", sans-serif; background: var(--field); border:0; border-radius:8px; box-shadow: var(--shadow-hairline); } .ds-input::placeholder { color: var(--ink-3); } .ds-input:hover { background: var(--hover-2); } .ds-input:focus { outline:none; background: var(--surface); box-shadow: 0 0 0 1px var(--accent), 0 0 0 4px var(--accent-tint); }" - }, - { - "name": "Segmented Range Control", - "kind": "chip", - "refersTo": "segmented-option", - "description": "The single style for ranges, order and status filters; the chosen option sits on a Paper thumb.", - "html": "
", - "css": ".ds-seg { display:inline-flex; gap:2px; padding:2px; background: var(--hover-2); border-radius:8px; } .ds-seg button { height:26px; padding:0 11px; color: var(--ink-2); font:500 12.5px/1 \"Inter Variable\", -apple-system, BlinkMacSystemFont, \"PingFang SC\", \"Segoe UI\", \"Microsoft YaHei\", \"Noto Sans SC\", sans-serif; background: transparent; border:0; border-radius:6px; cursor:pointer; } .ds-seg button:hover { color: var(--ink); } .ds-seg button[aria-checked=\"true\"] { color: var(--ink); background: var(--surface); box-shadow: var(--shadow-btn); }" - }, - { - "name": "Sidebar Navigation", - "kind": "nav", - "refersTo": "nav-item", - "description": "Grouped items on the canvas; the active item is a white chip ringed like the page panel.", - "html": "", - "css": ".ds-nav { width:216px; padding:10px 8px; background: var(--canvas); font-family: \"Inter Variable\", -apple-system, BlinkMacSystemFont, \"PingFang SC\", \"Segoe UI\", \"Microsoft YaHei\", \"Noto Sans SC\", sans-serif; } .ds-nav-label { margin:0; padding:14px 8px 6px; color: var(--ink-3); font-size:12px; font-weight:500; } .ds-nav button { display:flex; width:100%; height:32px; align-items:center; gap:8px; margin:0 0 1px; padding:0 8px; color: var(--ink-2); font-size:14px; font-weight:500; background: transparent; border:0; border-radius:8px; cursor:pointer; } .ds-nav button:hover { color: var(--ink); background: var(--hover-2); } .ds-nav button.active { color: var(--ink); background: var(--surface); box-shadow: 0 0 0 1px var(--frame-line), 0 1px 2px oklch(0 0 0 / 4%); }" - }, - { - "name": "KPI Strip", - "kind": "card", - "refersTo": "kpi-cell", - "description": "One card of equal cells divided by inset rules; figures at 20px/500, units small beside them.", - "html": "
Service
Degraded
Sandbox slots
12 / 16
Reported tokens
4.16M
P95 duration
—
", - "css": ".ds-kpis { display:grid; grid-template-columns: repeat(4, minmax(0,1fr)); margin:0; overflow:hidden; background: var(--surface); border-radius:12px; box-shadow: var(--shadow-card); font-family: \"Inter Variable\", -apple-system, BlinkMacSystemFont, \"PingFang SC\", \"Segoe UI\", \"Microsoft YaHei\", \"Noto Sans SC\", sans-serif; } .ds-kpi { display:grid; gap:4px; padding:14px 16px 16px; box-shadow: inset -1px 0 var(--grid-line), inset 0 -1px var(--grid-line); } .ds-kpi dt { color: var(--ink-2); font-size:12.5px; font-weight:500; } .ds-kpi dd { display:flex; align-items:center; gap:8px; margin:0; color: var(--ink); font-size:20px; font-weight:500; line-height:26px; letter-spacing:-0.015em; font-variant-numeric: tabular-nums; } .ds-tone { width:8px; height:8px; border-radius:50%; } .ds-tone.warn { background: var(--orange); }" - }, - { - "name": "Status Dot", - "kind": "custom", - "refersTo": "status-dot", - "description": "A 6px dot plus a plain 13px label; never colour alone, never a pill.", - "html": "Running Needs action Failed Idle", - "css": ".ds-status { display:inline-flex; align-items:center; gap:6px; margin-right:12px; color: var(--ink); font:400 13px/18px \"Inter Variable\", -apple-system, BlinkMacSystemFont, \"PingFang SC\", \"Segoe UI\", \"Microsoft YaHei\", \"Noto Sans SC\", sans-serif; } .ds-status i { width:6px; height:6px; border-radius:50%; background: var(--ink-3); } .ds-status.ok i { background: var(--green); } .ds-status.warn i { background: var(--orange); } .ds-status.danger i { background: var(--red); }" - }, - { - "name": "Meter", - "kind": "custom", - "refersTo": "meter", - "description": "A 5px Well Gray rail with a neutral ink fill that turns amber at 90% and red at 100% of its limit.", - "html": "
Active sandboxes12 / 16
node-0211 / 12
", - "css": ".ds-meter-row { display:grid; grid-template-columns: 120px 1fr auto; align-items:center; gap:12px; margin:6px 0; color: var(--ink-2); font:400 12.5px/18px \"Inter Variable\", -apple-system, BlinkMacSystemFont, \"PingFang SC\", \"Segoe UI\", \"Microsoft YaHei\", \"Noto Sans SC\", sans-serif; } .ds-meter-row b { color: var(--ink); font-weight:500; font-variant-numeric: tabular-nums; } .ds-meter { position:relative; display:block; height:5px; overflow:hidden; background: var(--field); border-radius:999px; box-shadow: inset 0 0 0 1px var(--grid-line); } .ds-meter > span { position:absolute; inset:0 auto 0 0; background: var(--meter-fill); border-radius:999px; } .ds-meter.warn > span { background: var(--orange); }" - }, - { - "name": "Data Table", - "kind": "custom", - "refersTo": "table-row", - "description": "A card with a 36px Paper header over a Hairline, 44px rows divided by Faint Rules, right-aligned tabular numerics.", - "html": "
AgentRequestsError rate
Contract checker571.8%
Code reviewer20—
", - "css": ".ds-table { overflow:auto; background: var(--surface); border-radius:12px; box-shadow: var(--shadow-card); font-family: \"Inter Variable\", -apple-system, BlinkMacSystemFont, \"PingFang SC\", \"Segoe UI\", \"Microsoft YaHei\", \"Noto Sans SC\", sans-serif; } .ds-table table { width:100%; border-collapse:collapse; font-size:13px; line-height:18px; } .ds-table th { height:36px; padding:0 12px; color: var(--ink-2); font-size:12.5px; font-weight:500; text-align:left; background: var(--surface); border-bottom:1px solid var(--line); } .ds-table td { height:44px; padding:6px 12px; color: var(--ink); border-bottom:1px solid var(--grid-line); } .ds-table tr:hover td { background: var(--hover); } .ds-table .n { text-align:right; font-variant-numeric: tabular-nums; }" - } - ], - "narrative": { - "northStar": "The Operator's Ledger", - "overview": "The console is a management tool, not a developer showroom. Every screen reads like a ledger page laid on a desk: a quiet canvas, one white page panel, one header, then white cards holding the evidence (figures, charts, tables). Structure comes from the card edge, 1px internal rules and whitespace; there are no cards inside cards. Colour is spent on problems and on the data itself, almost never on decoration. The indigo accent means \"you selected this\" or \"this is a link\"; its data shade (`--data`) means \"this is the single measured quantity\". Primary actions are filled with ink.\n\nDensity is deliberately high and calm: 13px body, 44px table rows, 30px controls, tabular figures in every column. The system is bilingual (zh-CN and English) and ships light and dark themes on the same token names; dark swaps values, never structure. It honours reduced motion and treats keyboard focus as a first-class state (2px indigo outline).\n\nThe data contract is part of the look. Core reports only what it observes, so the interface shows absence honestly: an em dash, a gap in a line, the word \"Unavailable\" or \"Unknown\". Explanations stay one click away behind a circled question mark, so the page stays a ledger rather than a leaflet.", - "keyCharacteristics": [ - "Each page sits in one white panel with 14px corners on a cool gray canvas, which also holds the sidebar. Inside the panel, cards are drawn by a hairline ring, and the page header is white with a hairline rule under it.", - "One indigo voice for selection, focus, links and single-series data (`--data`); the primary button is ink.", - "Meters are neutral ink; green, amber and red appear only when something is wrong or a state needs reporting.", - "A six-slot categorical palette for multi-series data, bound to the entity, not its rank.", - "One list grammar on every resource page: project filter, search, count, name with compact ID, creator, row actions.", - "Tabular numerals everywhere a number can line up.", - "Status is always a dot plus a plain-language label.", - "Explanations live behind \"?\" help tips; errors, warnings and safety notices stay visible. No small print: an empty state's explanation is a help tip beside its title, a field's rules a help tip beside its label, and filler lines are cut." - ], - "rules": [ - { - "name": "The Colour Only for Problems Rule", - "body": "A healthy state is drawn in ink. Meters fill in neutral ink and turn amber or red only past their thresholds; tone dots appear only on figures that report a state.", - "section": "colors" - }, - { - "name": "The One Voice Rule", - "body": "Indigo is for selection, focus, links and the single `--data` series. Multi-series charts draw from `--series-1..6` and `--series-other`, never from the accent.", - "section": "colors" - }, - { - "name": "The Entity Owns Its Colour Rule", - "body": "A categorical colour follows the entity (model, tool), never its rank. An entity keeps its slot while visible; only slots of entities that left the view are reused. Anything beyond six series collapses into Series Other.", - "section": "colors" - }, - { - "name": "The Columns Line Up Rule", - "body": "Every figure that can share a column uses tabular numerals: KPI and tile values, numeric table cells (right-aligned), legend totals, axis ticks, tooltip values, counts.", - "section": "typography" - }, - { - "name": "The Honest Figure Rule", - "body": "Missing data renders as \"—\", a gap in the line, \"Unavailable\" or \"Unknown\"; never as 0. Compact numbers keep two decimals only when the integer part is a single digit (\"1.04M\"), otherwise one (\"415.7万\"); values under 10,000 print whole. Durations read \"850 ms / 12.4 s / 4m 12s / 3h 5m\".", - "section": "typography" - }, - { - "name": "The Plain Vocabulary Rule", - "body": "zh-CN copy and the zh docs use one term per concept: 项目 (project), 沙箱 (sandbox), 提供商 (provider: 沙箱提供商 for the sandbox provider, 模型提供商 for the model provider, and the MCP provider behind a Credential), 凭据 (any other credential), 执行器 (executor), 主机 (host), 模板 (template), 密钥 (key: Core 密钥, 项目 API 密钥), 创建者 (creator), 已上报 (reported), 活跃 (active). API terms stay in English (Agent, Session, Turn, Item, Runtime, Environment, Harness, Skill, Vault, Credential), and usage counts are \"token\". Time ranges read \"1 小时 / 6 小时 / 24 小时 / 7 天\" (English \"1h / 6h / 24h / 7d\"), always in the one segmented control style.", - "section": "typography" - }, - { - "name": "The Liveness Only Rule", - "body": "The moving dash on a topology link shows that a connection is live, never traffic or work. An offline link is dashed and still, a stale topology shows no movement, and reduced motion stops the animation.", - "section": "layout" - }, - { - "name": "The One Page Grammar Rule", - "body": "Every page uses PageHeader, PageBody and Section from `components/console-ui.tsx`, and every resource list uses the list grammar from `components/list-ui.tsx`. No page invents its own header height, gutter, section rhythm or toolbar.", - "section": "layout" - }, - { - "name": "The One Card Rule", - "body": "Figures, charts and tables sit in one card divided by 1px internal rules. A card never contains another bordered, shadowed container; an empty list is itself one card.", - "section": "elevation" - } - ], - "dos": [ - "**Do** put every explanation of a figure, column, section or page behind a circled \"?\" help tip; report errors in a dialog or a toast; keep warnings and safety notices (deletion consequences, a key shown once) visible.", - "**Do** start every project-scoped toolbar with the project filter, then search, with the count on the right.", - "**Do** end every resource table with the Creator column and then the row actions.", - "**Do** confirm every deletion in ConfirmDialog.", - "**Do** keep meters in neutral ink and let amber and red mean a threshold was crossed.", - "**Do** reserve OpenAgentCore Indigo for selection, focus, links and the single `--data` series.", - "**Do** place figures, charts and tables in one card divided by 1px internal rules.", - "**Do** render missing data as \"—\", a chart gap, \"Unavailable\" or \"Unknown\".", - "**Do** show status as a 6px dot plus a plain label.", - "**Do** use tabular numerals for every aligned figure and right-align numeric columns.", - "**Do** build every page from PageHeader, PageBody and Section." - ], - "donts": [ - "**Don't** add lines of small explanatory print under headings, KPIs, fields or charts.", - "**Don't** colour healthy meters, bars or states; colour is for problems and data.", - "**Don't** colour multi-series data with the indigo accent.", - "**Don't** nest cards inside cards or draw a dashed empty state.", - "**Don't** render an unreported value as 0 or draw a missing interval as a zero line.", - "**Don't** use coloured status pills or colour-only status.", - "**Don't** reassign a categorical colour by rank when data re-sorts.", - "**Don't** show full IDs in list columns; show the compact ID with its copy button.", - "**Don't** add uppercase letter-spaced micro-labels or eyebrow lines above headings; a section is named by its title alone.", - "**Don't** mix synonyms in zh-CN copy (for example alternating 沙盒 with 沙箱, or API 密钥 with API key)." - ] - } -} diff --git a/apps/web/.impeccable/surfaces/src-app-tsx.md b/apps/web/.impeccable/surfaces/src-app-tsx.md deleted file mode 100644 index a3b0b0337..000000000 --- a/apps/web/.impeccable/surfaces/src-app-tsx.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -version: 1 -slug: "src-app-tsx" -primary_target: "src/App.tsx" -related_targets: ["src/ConsoleApp.tsx"] ---- - -# Administrator console (operate) - -Scope: the signed-in console shell and every page behind it, including Getting started on the Overview and the optional console tour. Visitor mode: Operate. Audience: the administrator of one OpenAgentCore deployment. Task: judge health, capacity, usage and failures; inspect and delete project assets; manage projects, keys, nodes and each Harness's default model. Constraints: Web API only (`/core/v1`); missing data stays visibly missing; no small print, explanations live in help tips; API terms stay English in Chinese copy; zh-CN and English, light and dark. - -Information architecture: Monitor (Overview, Core metrics, Agent metrics, Sandbox metrics, Session log) · Resources (Agents, Environment templates, Skills, Files, Vaults) · Platform (Projects and keys, Nodes, System). - -## Direction contract - -THESIS: One calm instrument panel for a whole deployment; every screen speaks one component language so the administrator reads state, not layout. Refuses the assembled dashboard of mismatched widgets and loading spinners. OWN-WORLD: Beautiful UI's foundation: cool near-white canvas, white cards drawn by a hairline ring, neutral ink ramp, 8px-radius buttons (ink primary; only status badges are pills), Inter with CJK system fallback, tabular numerals, semantic tints as condiment; Parsar indigo as the only accent, for selection, links and data. STORY: The administrator lands on health, sees what needs attention, drills into a project, Session or node, and acts (delete, issue, revoke) without waiting on a spinner. FIRST VIEWPORT: Page header with title, filters and refresh on one line; KPI strip; the page's primary card (chart grid, table or topology); nothing above the fold is a loader. FORM: User-pinned world (Beautiful UI + Parsar indigo, 2026-09-24); concept roll skipped because a user-pinned direction beats the roll. FINISH: unreviewed and undocumented is unfinished; this build ends with the finish review, the verdict, DESIGN.md, and every shipping raster carrying its provenance diff --git a/apps/web/DESIGN.md b/apps/web/DESIGN.md index d35739d74..c36085fda 100644 --- a/apps/web/DESIGN.md +++ b/apps/web/DESIGN.md @@ -277,7 +277,7 @@ A restrained neutral ledger with one indigo voice, three signal colours and a se **Character:** One quiet sans in several weights, sized for dense reading; hierarchy comes from weight and a tight scale, not from a second typeface. Mono appears only for machine identifiers, key prefixes, models and commands. ### Hierarchy -- **Metric** (600, 24px, 32px, -0.015em, tabular): the four Overview tiles. +- **Metric** (600, 28px, 36px, -0.025em, tabular): the four Overview tiles. - **Display** (500, 20px, 26px, -0.015em, tabular): KPI strip figures. Figures stand out by weight and position, one step above body text. - **Headline** (600, 20px, 28px, -0.015em): the page title in the page header; one per page. Detail pages put the back button before it. - **Title** (600, 14px, 20px, -0.01em): section and card headings. Dialog titles are 600 at 15px; empty-state titles 500 at 13.5px. @@ -359,24 +359,23 @@ Every resource list, the Session log and the project list share one grammar: - Sections follow: usage figures in a KPI strip, then tables in cards. - A Session's **History** header holds an outline "Jump to the failed Turn" (with the count when several failed) before the view switch while any Turn failed; it shows the conversation (the Turn table when there are no Items), scrolls the page body to the next failed Turn and focuses it. - An active project's page ends its keys with a **How to call** section (see Dialogs) before its write operations. -- A self-hosted Session's **Executor credentials** section ends with **Connect a host**: a Linux/macOS or PowerShell selector, the one copyable command Core generated for that platform, and a link to the native installation guide. The console shows Core's command as it is and never builds one. The command installs the daemon and its Harnesses, starts it and checks its connection; its authorization expires after 30 minutes. Requirements and reconnection details belong in the title help. Reconnection after credential rotation requires `stop`, replacement of the configured credential file, then `start`; disconnection does not imply process exit. Connection status comes only from Core. When Core has no command, a note replaces it; an archived project shows a note instead. +- A self-hosted Session's **Executor credentials** section ends with **Connect a host**: a Linux/macOS or PowerShell selector, the one copyable command Core generated for that platform, and a link to the native installation guide. The console shows Core's command as it is and never builds one. Requirements and reconnection details belong in the title help. Connection status comes only from Core. When Core has no command, a note replaces it; an archived project shows a note instead. ### Dialogs Dialogs are 448px Paper cards (960px when wide) with 8px corners, a 52px header and a 56px Margin Gray footer separated by Hairlines, and the overlay shadow. They cannot be closed while a request runs. - **ConfirmDialog**: the one grammar for destructive actions. The body states what will be deleted and its consequences; the footer holds Cancel (outline) and the confirm button (danger), whose label changes while busy. Core's reason for a rejection, or an uncertain-outcome warning, appears in red inside the dialog. The Skill page's delete dialogs follow the same grammar; deleting a whole Skill also requires typing its name. Archiving a project says in bold that it can't be undone, then how many active keys it revokes (the project read's count, or more when its loaded key list shows more) and that assets and accepted work stay; with active keys it too requires typing the project's name, shown in mono with its inner spaces kept (surrounding spaces are forgiven, Unicode compared in NFC). While the project list is read again Archive waits; if that read failed, a red line says the count may be out of date and Archive stays disabled. - **Key dialogs**: name fields carry their rules in a help tip and their problem in red underneath. The issued key appears in a read-only field with a copy button, under a notice that it is shown once; only "I've saved this key" dismisses it. Closing the dialog moves the key into a pending notice card on the page. - **Executor credential dialog** (640px): the shown-once notice, then a prompt to save the JSON privately before Done. Download credential file is primary; Copy credential is secondary. Installation commands are not repeated here. Done forgets the credential; closing preserves it in the pending card. The native installer reads the unchanged JSON file: its absolute path is entered during interactive installation or passed with `--credential-file`; tokens never enter command arguments. -- **Add node**: the Limits choice first (Recommended, which leaves the limits for Core to derive from the host once it enrolls, or Custom with the two numbers), then the one-time command in a Terminal block (expiry countdown and Copy command in its header), the three progress steps, and, once the installer's minute passes, an amber card with the reason and a copyable system-service log command. Below, the Host requirements Hairline disclosure is open until this browser has shown it once. Installation requires root or sudo, creates the `oac-node` system service, and serves one Core per host because nodes share the service account. The docker group's root-equivalent access is stated once, in **Use Docker instead of microsandbox?**. Do not expose an ordinary-user installation command or user-service prerequisites. The command downloads from the installation's public URL, never the browser's address, so it works as shown on any host. Until the installation is read, a line says it is being checked; a failed read, a public URL other machines can't use (loopback or not HTTPS), or a console without the provider's node files replaces the limits with one line saying why (the failed read with Try again), and the footer offers nothing to generate. Once the node is ready, while Getting started is open, one line under the green status names the next step (set a default model provider, or finish Getting started) with a text action to Settings → Models and credentials or the Overview. +- **Add node**: the Limits choice first (Recommended, which leaves the limits for Core to derive from the host once it enrolls, or Custom with the two numbers), then the one-time command in a Terminal block (expiry countdown and Copy command in its header), the three progress steps, and, once the installer's minute passes, an amber card with the reason and a copyable system-service log command. Below, the Host requirements Hairline disclosure is open until this browser has shown it once. Do not expose an ordinary-user installation command or user-service prerequisites. The command downloads from the installation's public URL, never the browser's address, so it works as shown on any host. Until the installation is read, a line says it is being checked; a failed read, a public URL other machines can't use (loopback or not HTTPS), or a console without the provider's node files replaces the limits with one line saying why (the failed read with Try again), and the footer offers nothing to generate. Once the node is ready, while Getting started is open, one line under the green status names the next step (set a default model provider, or finish Getting started) with a text action to Settings → Models and credentials or the Overview. - **Clean up the host**: after a node is removed, a dialog gives the host's uninstall command in the same Terminal block, a Graphite line that it deletes no sandboxes, volumes or images; the uninstaller prints what it keeps. The command requires root or sudo; there is no user-service alternative. A node enrolled with an earlier Core address adds an "Old Core address gone?" disclosure with the `--force` form. The command, too, downloads from the public URL, which the dialog reads again if it is not at hand: until then one line says it is being checked, a failed read says so with Try again, and a public URL other machines can't use (loopback, or none) gets a line saying the service stays on the host and no command can be given. Done dismisses it and focus returns to the page heading. -- **Use Docker?**: choosing a backend that declares cautions in sandbox setup, Docker today, titles the dialog "Use {backend}?" and lists each caution as a plain list item: for Docker, that containers share the host kernel and that the node's account joins the docker group, which is root-equivalent on the host. The footer holds Use Docker (outline) and Back (primary), which takes focus; Back, closing or Escape leaves the choice unmade. -- **Edit node**: the name, then the Limits choice, Recommended showing the node's `recommended_capacity` while Core has one, or Custom with the numbers. The Nodes list and a node's Capacity show "Active / limit" for Docker and microsandbox alike, so a saved limit shows where it was set. +- **Edit node**: the name, then the Limits choice, Recommended showing the node's `recommended_capacity` while Core has one, or Custom with the numbers. The Nodes list and a node's Capacity show "Active / limit", so a saved limit shows where it was set. - **How to call**: wherever a new key is shown, a card under it gives three copyable samples, each a Margin Gray block with a Hairline and its label and copy button in a header row: a Shell block exporting `OPENAI_BASE_URL` (the installation's API base URL) and `OPENAI_API_KEY` (the new key) together, then curl and Python (with the pinned SDK), each listing the project's Agents and creating a Session with a first message (`environment`, an inline `agent` with `model: ""`, and `input`). A copy the clipboard refuses selects the sample and says so in red underneath. One Graphite line says to put a model the model provider serves in place of ``, and that running an Agent needs a model provider: in each request, saved on the Agent, or the deployment default. An active project's page shows the same samples as a section without any key: the Shell block exports a quoted placeholder, and a Graphite line above the samples says to use a key issued for this project, shown only once at issuance. When the public address is loopback, a note above the samples says the API is reachable only on the Core machine; without a public address only a note to set one shows. Before the installation is read, a skeleton holds the first sample's place. ### Navigation Sidebar groups Monitor, Resources and Platform with 12px Pencil group labels; items are 36px rows with an 18px outline icon and primary text. Hover takes the Pressed gray; the active item has a neutral background and an indigo edge. Compact icon-rail rows are 40px tall. The Platform group sits below a hairline. A secondary page (one Session) highlights its parent. The footer holds Show Getting started, then sign-out and the language/theme menu. A detail page's back arrow returns to the page it was opened from (a Skill opened from a template goes back to the template); opened directly, it goes to its list. The arrow is labelled plainly "Back". ### KPI strip and metric tiles -A KPI strip is one card of equal cells separated by inset rules. Each cell: a 12.5px Graphite label with an optional help tip, then the figure at 20px/500 with any unit or limit small beside it, optionally led by an 8px tone dot. Overview uses four separate metric tiles instead: a 13px label with a help tip, the same 20px figure (the service status as a dot and a word), and one 12.5px line of context. Figures ellipsize rather than wrap. Live figures on monitor pages roll their digits to a new value on refresh (NumberFlow) instead of swapping. +A KPI strip is one card of equal cells separated by inset rules. Each cell: a 12.5px Graphite label with an optional help tip, then the figure at 20px/500 with any unit or limit small beside it, optionally led by an 8px tone dot. Overview uses four separate metric tiles instead: a 13px label with a help tip, the Metric figure (the service status as a dot and a word), and one 12.5px line of context. Figures ellipsize rather than wrap. Live figures on monitor pages roll their digits to a new value on refresh (NumberFlow) instead of swapping. ### Help tip An 18px circular button holding a 13px circled "?" in Pencil; hover or open takes Ledger Ink on the Pressed gray. It opens on hover, focus or click (click pins it), closes on Escape, scroll or resize, and renders a dark 12px tooltip (8px corners, overlay shadow, max 288px wide) in a portal. The text also exists in a visually hidden element for assistive technology. @@ -398,53 +397,34 @@ On Overview and Session log, failed reads that leave a section unavailable repla A failed action whose outcome needs a decision (a sandbox change with no answer, a timeout or a 5xx) opens an error dialog with the reason and the next step as its primary button. Failed refreshes and project reads also raise an error toast; other failed actions, Core's clear refusal of a sandbox change among them, are reported there with the reason. A refusal leaves the page usable as it was. Errors inside a dialog or a form stay beside what they concern. Coverage notes (Margin Gray, Hairline ring, 8px corners, 12.5px Graphite) state bounded aggregation. Standing warnings that need action use an amber-tinted line at the top of the page body. On Nodes, this names nodes still bound to an old Core address; each of those nodes' status reads Old address (amber dot) with "Remove and add again" under it in 12px Graphite. Partial-data chips are amber-tinted pills with a help tip. Safety notices (a key shown once, a destructive consequence) stay visible in body text. -A local-only installation has the same amber notice on Overview, Nodes and Settings: other machines cannot connect, followed by Review the public address, which leads to Settings → Service and deployment. Add node is disabled with its reason beside the action, and Getting started leaves its first step to do with the address fix visible. A pending or failed installation read cannot complete that step; a failed read shows Unknown and Retry. - ### Onboarding -Signing in and the console tour share one frame: a dark stage on the left (always dark, whatever the theme) and the task panel on the right, which follows the theme. The stage is the product's one authored moment: a flickering indigo dot grid under slow light rays (Magic UI's flickering grid and light rays), Core as the OpenAgentCore mark on a tile with a travelling border beam, and two orbits of Agents, Sessions, Skills, Vaults, files, templates and machines around it; the OpenAgentCore mark is itself nodes on a ring. Brand copy sits bottom-left in solid ink; it is a paragraph, not a heading, because the panel's title names the task. Signing in asks for one thing, the deployment's Core key, in a single password field; a copyable Docker Compose command to read the key stays visible beneath it, with a reminder to substitute a custom installation directory. The key’s authority stays in a help tip. A refused key, too many attempts or an unavailable console is an error beside the field. Signing in opens the console on the Overview. The optional tour has three chapters — Monitor, Resources, Platform — whose stage shows a real dark screenshot of those pages, tilted towards the panel; it takes the place of the console until its last button, Skip or Escape, and then returns the focus to the control that opened it. Entering the console or the tour, and leaving the tour, happen inside a View Transition: the old page dissolves forward and the new one is revealed in a circle growing from the pressed button. With reduced motion the orbits hold their places, the grid is a still frame and no transition runs. +Signing in and the console tour share one frame: a dark stage on the left (always dark, whatever the theme) and the task panel on the right, which follows the theme. The stage is the product's one authored moment: a flickering indigo dot grid under slow light rays (Magic UI's flickering grid and light rays), Core as the OpenAgentCore mark on a tile with a travelling border beam, and two orbits of Agents, Sessions, Skills, Vaults, files, templates and machines around it; the OpenAgentCore mark is itself nodes on a ring. Brand copy sits bottom-left in solid ink; it is a paragraph, not a heading, because the panel's title names the task. Signing in asks for one thing, the deployment's Core key, in a single password field. The key’s authority stays in a help tip. A refused key, too many attempts or an unavailable console is an error beside the field. Signing in opens the console on the Overview. The optional tour has three chapters — Monitor, Resources, Platform — whose stage shows a real dark screenshot of those pages, tilted towards the panel; it takes the place of the console until its last button, Skip or Escape, and then returns the focus to the control that opened it. Entering the console or the tour, and leaving the tour, happen inside a View Transition: the old page dissolves forward and the new one is revealed in a circle growing from the pressed button. With reduced motion the orbits hold their places, the grid is a still frame and no transition runs. ### Getting started The first card on the Overview while any step is to do: a card header ("Getting started", "n of 4 done", a help tip, then a ghost Take the tour button and an icon button that hides it) over four rows split by Faint Rules. Each row has a 22px numbered ring (a check on the tile wash when done), a 13px/600 title over one 12.5px Graphite line, a status dot (Done in green, To do in Pencil, Checking pending, Unknown for a failed read) and one outline action while the step is to do: Set up sandboxes, Add node, Open Nodes or Open sandbox backend; Open Settings; Create project (which continues to the new project's first key) or Issue key; See how to call (the newest active project, preferring one with an active key), or Projects and keys without an active project. Add node, Create project and Issue key open their page with the dialog already open; Open Settings brings the Models and credentials tab to the top of the page body and focuses the default Harness's Set or Replace; See how to call opens the project and, once its keys, usage and address are read, brings its How to call heading to the top of the page body, focused. Only the page body scrolls; the page header stays. Every step done turns it into one line, "You're set", with Take the tour and Dismiss; it stays, through the tour, until dismissed, and the checklist does not come back on its own. The choice is kept per installation in the browser, also while the deployment cannot be read; Show Getting started, a quiet row above the sidebar's account controls, opens it again at any time. ### Sandbox setup -Setting up hosted sandboxes is a set of pages inside Settings → Sandbox and scheduling, one decision each: where sandboxes run (own machines or E2B), then the backend, or for E2B the Connect E2B page (service, API key, template build and endpoint), then the size of each sandbox (three presets; E2B skips it, since each sandbox takes the template build's size), then a review. Choices are large cards that advance on a click; short indigo dashes show the progress; pages slide and blur across. The backend page compares microsandbox and Docker behind a help tip; microsandbox comes first, preselected (a saved backend stays selected), with a neutral Recommended pill beside its title. Docker takes a confirmation (see Dialogs) once per visit to setup; a saved Docker deployment has already made it. The review states where sandboxes run, the size, each declared connection value (an empty optional one reads Provider default) and the Core address, read-only: it is config.json's `public_url`, and the console never asks for it. A loopback address carries an amber line under it: only the Core machine reaches it. When Core rejects the configuration for it (E2B with a loopback `public_url`), a red-tinted block under the review states the reason and adds Managed in Settings, which leads to Settings → Service and deployment. A save attempt clears the transient E2B key. Initial setup then asks for it again, with a link to that step; an update may leave it blank to keep the committed key. Advanced settings, one link away on the review page of a backend that declares a default size, hold the exact CPU, memory and disk values; E2B has none, so the review offers no link. A change keeps the saved size while the backend stays the same (a saved size outside the presets is offered as Current). Same-backend editing starts at size or the E2B connection with the provider fixed. With the saved key kept, the template build stays an editable text field of the saved value; entering a key loads the build list again. It is an online configuration update, including when older sandboxes remain: existing node identities and resource ownership are retained. Changing the backend or E2B team requires reset and then a new setup. E2B updates can omit the key to retain it; every explicitly entered key takes the verified replacement path and advances the target generation on success, including the same value. Rejections remain inline with a safe reason and a deliberate way back to reset; never infer teams from a key, auto-reset or auto-resubmit. Optional explanations sit behind help tips; errors and safety consequences remain visible. - -### Sandbox lifecycle - -For deployments with a suspension policy, the Nodes list adds Suspended and Retained / limit columns and a node's Capacity strip adds Suspended, Retained / limit and Snapshots; one-line help tips say what each limit counts. Overview adds the suspended total of all registered nodes under its sandbox slots. The idle threshold is edited in Settings → Sandbox and scheduling, where snapshot retention is read-only. Read failures preserve known counts with a visible unconfirmed notice, and absent evidence stays a dash. Allocation rows show elapsed time in the recorded compute phase without estimating expiry. Sandbox metrics shows one Status column, Core's lifecycle record; when an active sandbox has no sample, the reason reads in its CPU and Memory cells, never as a second status. Supporting persistence and resume conditions belong in help tips. - -### Configuration generations -A single rollout row opens a details dialog for Core's target generation, previous-generation sandboxes and rollout counts. Poll rapidly only while Core reports preparing, or while the independent reset is active. Settled is preparation state, not proof that all nodes are ready or all older Sessions have ended. Retained old resources alone must not keep rapid polling alive. Render failed, update-required and unknown target states distinctly. Keep offline/live-provider status separate from a node's durable serving-generation pin; the pin alone never means the node is online or ready. Node detail shows the serving generation and target preparation; allocation detail shows the owned configuration generation. Do not calculate rollout completion from these rows or promise immediate placement on the target. - -A generation-only update within the same installation/backend lifecycle retains compatible previous node/allocation evidence while refreshing. Failed or pending reads visibly qualify those observations; never replace them with fabricated zeros. Reset, backend and installation lifecycle changes discard incompatible data. The shared deployment query and write ownership below govern navigation, late reads, explicit retries and login isolation. +Setting up hosted sandboxes is a set of pages inside Settings → Sandbox and scheduling, one decision each: where sandboxes run (own machines or E2B), then the backend, or for E2B the Connect E2B page (service, API key, template build and endpoint), then the size of each sandbox (three presets; E2B skips it, since each sandbox takes the template build's size), then a review. Choices are large cards that advance on a click; short indigo dashes show the progress; pages slide and blur across. The backend page offers microsandbox, preselected (a saved backend stays selected), with a neutral Recommended pill beside its title. The review states where sandboxes run, the size, each declared connection value (an empty optional one reads Provider default) and the Core address, read-only: the console never asks for it. A loopback address carries an amber line under it: only the Core machine reaches it. When Core rejects the configuration for it (E2B with a loopback `public_url`), a red-tinted block under the review states the reason and adds Managed in Settings, which leads to Settings → Service and deployment. A save attempt clears the transient E2B key. Initial setup then asks for it again, with a link to that step; an update may leave it blank to keep the committed key. Advanced settings, one link away on the review page of a backend that declares a default size, hold the exact CPU, memory and disk values; E2B has none, so the review offers no link. A change keeps the saved size while the backend stays the same (a saved size outside the presets is offered as Current). Same-backend editing starts at size or the E2B connection with the provider fixed. With the saved key kept, the template build stays an editable text field of the saved value; entering a key loads the build list again. It is an online configuration update, including when older sandboxes remain: existing node identities and resource ownership are retained. Changing the backend or E2B team requires reset and then a new setup. E2B updates can omit the key to retain it; every explicitly entered key takes the verified replacement path and advances the target generation on success, including the same value. Rejections remain inline with a safe reason and a deliberate way back to reset; never infer teams from a key, auto-reset or auto-resubmit. Optional explanations sit behind help tips; errors and safety consequences remain visible. ### Sandbox reset -Sandbox configuration offers an explicit reset ([semantics](../../contracts/agents-api/sandbox-deployment.md#reset)) through its panels and confirmation dialogs. The confirmation keeps to one concise consequence paragraph, two mode choices, the auto deadline and footer actions. Put cleanup sequencing and preservation details in help tips. Auto clear is selected first, with a one-hour deadline editable from 5 minutes to 24 hours; Force clear and escalation require destructive confirmation. State directly that hosted work is archived, remaining active work may be cancelled, archived Sessions cannot resume and unpersisted workspace contents may be lost. Further consequences live behind the reset impact help tip. +Sandbox configuration offers an explicit reset ([semantics](../../contracts/agents-api/sandbox-deployment.md#reset)) through its panels and confirmation dialogs. The confirmation keeps to one concise consequence paragraph, two mode choices, the auto deadline and footer actions. Put cleanup sequencing and preservation details in help tips. State directly that hosted work is archived, remaining active work may be cancelled, archived Sessions cannot resume and unpersisted workspace contents may be lost. Further consequences live behind the reset impact help tip. -A persistent progress panel uses Core's busy, idle and cleanup counts, deadline and named offline-node blockers. Bring blocked nodes online for confirmed cleanup; never offer a browser-side force-release shortcut. Poll the deployment every five seconds only while its reset is non-null. A passed deadline does not establish force or completion; only a Core response does. Completion opens the setup flow, with a new explicit save using the generation read from Core, including zero on a fresh install. Reset and online configuration rollout have independent authoritative progress; neither automatically replays configuration. +A persistent progress panel uses Core's busy, idle and cleanup counts, deadline and named offline-node blockers. Bring blocked nodes online for confirmed cleanup; never offer a browser-side force-release shortcut. Poll the deployment every five seconds only while its reset is non-null. Read deployment progress independently of node details. Partial failures retain successful facts with a visible stale/unavailable notice. An uncertain write opens the recovery dialog and requires a new authoritative read before another mutation; refresh reads state and never resubmits the write. The connection's QueryClient owns both the authoritative deployment and pending or uncertain writes across route transitions. Leaving Sandbox configuration cannot cancel or forget a submitted reset, and a cached node snapshot cannot replace a newer reset or completion learned on Overview. Returning to Nodes or Sandbox configuration reads the shared deployment immediately and refreshes node evidence separately. Only a successful authoritative read begun after the write settles can release the mutation block; an earlier or still-pending read cannot. Submitting consumes the reset confirmation even if its outcome is uncertain; recovery uses the separate read-and-review dialog. Observation retries preserve applicable non-secret configuration drafts. A changed installation, owner epoch, backend, mode or generation discards the prior draft and confirmation. Logout clears this connection-scoped state. ### Settings page -Settings is the single platform configuration entry, with one tab per [group](../../docs/configuration.md#runtime-settings-web). Each tab has a stable address; links from Nodes and metrics open the owning tab, and the Sandbox and scheduling header links back to Nodes. Forms save independently through their resource APIs, never through one cross-resource Save all action. +Settings is the single platform configuration entry, with one tab per [group](../../docs/configuration.md#runtime-settings-web). Each tab has a stable address; links from Nodes and metrics open the owning tab, and the Sandbox and scheduling header links back to Nodes. The hierarchy is page, tab, section, row. The page header loses its rule to an underline tab row: 40px text tabs in Graphite 13px/500, the current one Ink with a 2px Ink underline. Below 640px the tabs wrap onto a second row rather than scroll out of sight. The body is a left-aligned column at most 880px wide with 32px between sections. A section is the shared Section heading (14px/600, help tip, section-wide outline actions on the right) over one card of label/value rows (`settings.css`): a 200px Graphite label column with its help tip and an Ink value column, 8px by 16px padding, 32px minimum line height, Faint Rules between rows; below 640px the label sits above the value. An action that changes one value sits at the end of its row (Edit tenant capacity; Save beside the idle-seconds field, whose error appears beneath it). Read-only status is a row too (Configuration rollout, Snapshot retention); tables sit in one framed card. Settings never repeats the KPI strips of Nodes or the metrics pages. The irreversible operation closes the page in its own section: a red-ringed card with one Ink line stating the consequence and a red-text outline button. -Sandbox and scheduling contains sandbox setup or Deployment provider (Provider, Each sandbox, the E2B connection rows and the rollout row, with Change resources in the section header), then Automatic suspension (the deployment-wide idle policy and read-only snapshot retention, shown only when the deployment declares suspension), then Reset. While a reset runs, its progress section leads the page with Force reset now and Cancel reset in its header. Nodes owns the nodes themselves: status, per-node limits, allocations, host figures and charts, Add node (with its enrollment form), Edit node and removal. Resource changes never imply rewriting existing allocations. Lower limits do not imply forced termination or snapshot deletion. +Sandbox and scheduling contains sandbox setup or Deployment provider (Provider, Each sandbox, the E2B connection rows and the rollout row, with Change resources in the section header), then the idle setting, always shown: Automatic suspension with checkpoint support (Idle before suspension (seconds) and read-only snapshot retention) or Idle timeout without it (Idle before expiry (seconds)), then Reset. While a reset runs, its progress section leads the page with Force reset now and Cancel reset in its header. -Workspace storage shows the selected configuration's adapter and tenant capacity (in bytes units, or No tenant capacity limit) under Storage configuration, with Select new configuration in the section header and Edit tenant capacity on the capacity row. The configuration ID and parameters JSON sit in a closed Configuration details disclosure at the end of the card. Select new configuration accepts an adapter identifier, configuration ID, parameters JSON object and optional write-only credential JSON object. Edit tenant capacity keeps the current configuration identity. Explain adapter preparation and existing-workspace behavior behind help tips, with a link to the owning configuration document; keep required form labels and validation visible. Never prefill credentials or persist their drafts across navigation. A failed read is not an unconfigured filesystem, and an uncertain write is not a safe automatic retry. +Workspace storage shows the selected configuration's adapter and tenant capacity (in bytes units, or No tenant capacity limit) under Storage configuration, with Select new configuration in the section header and Edit tenant capacity on the capacity row. The configuration ID and parameters JSON sit in a closed Configuration details disclosure at the end of the card. Explain adapter preparation and existing-workspace behavior behind help tips, with a link to the owning configuration document; keep required form labels and validation visible. Models and credentials stacks one default-model card per Harness. Its header carries the Harness name, its [readiness](../../docs/configuration.md#runtime-settings-web) (Ready in green; Model provider not set in amber, with Set as the primary button; Disabled in neutral, with a View startup settings text action), a Default pill, a help tip and the Set, Replace and Clear actions; rows hold model ID, provider protocol, base URL, key presence, token limits when set and update time, and a foot holds Usage details. Set and Replace open one form dialog. The adapter declaration supplies supported protocols and native JSON support without harness-specific branches. Native settings use an optional JSON object editor with formatting and inline syntax errors. Changing model identity clears native JSON; replacing only the required write-only API key does not. Keys are never prefilled and are forgotten when the form closes. Core rejections remain visible in the form; Clear uses ConfirmDialog. Usage details opens Core's observations separately. -Service and deployment shows installation addresses, an Installation details disclosure, closed by default, with the installation ID and source commit, Domain and HTTPS actions, and the startup settings Core loaded. Process settings remain read-only here; their source stays the installation configuration. Each row's label is the setting's environment variable in code style (OAC_LOG_LEVEL), as Core reports it, wrapping after an underscore so a phone keeps all three columns; values show as is, with arrays joined, On or Off for booleans and None for an empty list. How to change a setting in the section header links to the configuration guide. Sensitive settings show only Configured or Not set. Default uses a neutral pill. - -### One place for each task -Each configuration has exactly one editor in Settings; other pages link to it. Resource operations such as Project keys, Session executor credentials and node removal stay on their resource pages. Keep the configuration page flat: resource editors are dialogs and rollout is one status row with a details action. Explanations go in help tips, not small-print helper paragraphs. Errors, uncertain outcomes and current usage exceeding a new limit remain visible without duplicating the workflow. - -### Diagnostic observations -Failure reasons belong beside the failed Session or Turn status. On the Session page the Status fact stays short, and the reason and its next step read as one block under the facts, at reading width. Their first read uses a skeleton; an unavailable reason names that state and puts the read retry beside its help tip. Technical classifications are translated through one catalogue, not shown as raw error codes. Trace Timing labels Core receipt times separately from tool-reported duration; explanations of batched delivery, clock differences and historical gaps live in help tips. - -The self-hosted connection panel names Core's observed state, the bound key and last heartbeat. The bound-key action uses the rotation confirmation and the one-time credential flow. Stale observations cannot complete Run on host. +Service and deployment shows installation addresses, an Installation details disclosure, closed by default, with the installation ID and source commit, and the startup settings Core loaded. Each row's label is the setting's environment variable in code style (OAC_LOG_LEVEL), as Core reports it, wrapping after an underscore so a phone keeps all three columns; values show as is, with arrays joined, On or Off for booleans and None for an empty list. How to change a setting in the section header links to the configuration guide. Sensitive settings show only Configured or Not set. Default uses a neutral pill. ### Loading and motion The console has no spinners and no "Loading…" lines. Reads are cached (TanStack Query) and prefetched on navigation hover, so revisits show data at once and refreshes keep the last data on screen. Only a first read shows a skeleton in the final layout's cards: table rows, a headline strip with chart panels, or a facts card with a table, with a sweep that repeats every 900ms and stops under reduced motion. Work in progress is the Agent's shimmering "Working…" line in the conversation and the breathing pending dot. @@ -480,8 +460,6 @@ Motion reports state and never makes anyone wait: the navigation chip and segmen ## Navigation icons and first use -Use Lucide throughout. Navigation icons are 18px with a 1.75px stroke; shared tool icons use the same stroke at their existing compact sizes. Default navigation icons use secondary ink, selected icons use primary ink. The selected row has a neutral background and a narrow indigo marker. - -Getting started emphasizes the first confirmed incomplete step with the primary button while leaving every step independently available. Only authoritative, successful zero-Session reads replace the activity chart with first-use guidance. Missing and failed reads retain their uncertainty and recovery controls. +Use Lucide throughout. Navigation icons are 18px with a 1.75px stroke; shared tool icons use the same stroke at their existing compact sizes. Default navigation icons use secondary ink, selected icons use primary ink. -Configuration controls show concise labels, values and actions. Validation and request failures remain visible beside the affected action or field. +Getting started emphasizes the first confirmed incomplete step with the primary button while leaving every step independently available. Only authoritative, successful zero-Session reads replace the activity chart with first-use guidance. diff --git a/apps/web/PRODUCT.md b/apps/web/PRODUCT.md index 7c79d41b1..0bec6426b 100644 --- a/apps/web/PRODUCT.md +++ b/apps/web/PRODUCT.md @@ -22,32 +22,29 @@ The console runs beside the administrator's own Core, with execution, files and ## Operating Context -- Paired console (`services/web`): the administrator signs in with the deployment's [Core key](../../docs/getting-started/operations.md#core-key). Sign-in shows the copyable `~/.oac/core/oac core-key --show` command that reads the key on the Core host, with a reminder to substitute a custom installation directory. The browser sends the key only to sign in and keeps only the session cookie; the console server holds the Core key and forwards the Web API (`/core/v1/**`, including sandbox administration under `/core/v1/sandbox/**`). The console never calls `/v1`. -- The Core key is not an Agents API identity and cannot call `/v1`. An administrator who wants to call the Agents API issues a project API key like any other caller. -- `/console/config` reports the node installer (`node_installer`, `node_installer_sha256`), offered only with a 64-hex digest. Native self-hosted installation does not depend on this endpoint. It also lists the providers it has node files for (`node_artifacts`); without the deployment's provider, Add node says so and issues no command. Signing in grants administration, sandbox administration included. +- Paired console (`services/web`): the administrator signs in with the deployment's [Core key](../../docs/getting-started/operations.md#core-key). Sign-in shows the copyable `~/.oac/core/oac core-key --show` command that reads the key on the Core host, with a reminder to substitute a custom installation directory. The console never calls `/v1`. - Chinese and English UI; light and dark themes; reduced motion honored. ## Information Architecture - **Monitor**: Overview (service status, running Sessions, sandbox slots, the Needs attention count for the last 24 hours, 24-hour Session activity, a compact inventory of Core and up to four nodes, prioritizing offline and degraded nodes when the list is full, where Core opens Core metrics, a node opens its page on Nodes and E2B opens Sandbox metrics, the Needs attention table, whose rows name each Session, its project, its one-line reason and last activity and open it, with older ones left to the Session log, usage by project), Core metrics (whether Core can run Turns: execution slots, the Turn queue, its p95 wait and interrupted Turns, connected daemons, database latency, the Core process's CPU and memory, and background jobs; Go heap, goroutines and the database pool sit in a collapsed Diagnostics area), Agent metrics (requests, errors, duration, tokens, models, tools, Agents and API keys for 1 h / 6 h / 24 h / 7 d), Sandbox metrics (hosted Runtimes across projects over time, active against total; a sandbox opens in a dialog with its figures and CPU and memory charts; an E2B deployment adds what Core holds in E2B's cloud), Request log (recent public or administration HTTP requests, status, duration, safe error code and correlation IDs; bounded to the serving Core instance, with manual refresh and no body capture), Session log (every Session, read-only, with a failed Session's reason under its status, opening one Session's history, which jumps to its failed Turns; a self-hosted Session's page also has its environment's executor credentials). Session facts and Agent metrics link to an Agent's page only when that saved resource exists; inline snapshots and snapshots of deleted Agents remain readable without a broken resource link. Agent metrics' failed Turns open the Agent's Sessions in the Session log. - **Resources**: Agents, Environment templates, Skills, Files, Vaults. Each list shows one project or all projects, with a Project column when all are shown and a Creator column naming the creating key. Detail pages show the resource's facts and offer Delete. An empty list says, in one sentence, that applications create these resources through the Agents API, and links to that resource's section of the API guide; Agent metrics does the same for Sessions. -- **Platform**: Projects and keys (projects, their assets and usage, named keys, write history), Nodes (the node list, each node's capacity and limits, host figures and charts, allocations, Add node, Edit node and individual removal operations), and Settings, the single entry for platform configuration. Sandbox and scheduling owns setup, resource edits, rollout, reset and the idle policy, and links to Nodes for nodes and their capacity. Add node on Nodes offers Recommended or Custom limits before issuing its one-time command; installers use Core's public URL and require supported node artifacts. Edit node changes a node's name and limits; removal stays on the node page and offers the host's uninstall command. Models and credentials owns each Harness's default model and shows its [readiness](../../docs/configuration.md#runtime-settings-web), with Set as the primary action when the model provider is not set and a link to the startup settings when it is disabled. Getting started uses the same readiness. Service and deployment owns installation facts (the public and API base URLs, with the installation ID and source commit behind Installation details), Domain and HTTPS actions and read-only startup settings, each named by its environment variable, with a link to the configuration guide's section on changing them. +- **Platform**: Projects and keys (projects, their assets and usage, named keys, write history), Nodes (the node list, each node's capacity and limits, host figures and charts, allocations, Add node, Edit node and individual removal operations), and Settings, the single entry for platform configuration. Sandbox and scheduling owns setup, resource edits, rollout, reset and the idle policy, and links to Nodes for nodes and their capacity. Add node on Nodes offers Recommended or Custom limits before issuing its one-time command; installers use Core's public URL and require supported node artifacts. Edit node changes a node's name and limits; removal stays on the node page and offers the host's uninstall command. Models and credentials owns each Harness's default model and shows its [readiness](../../docs/configuration.md#runtime-settings-web), with Set as the primary action when the model provider is not set and a link to the startup settings when it is disabled. Getting started uses the same readiness. Service and deployment owns installation facts (the public and API base URLs, with the installation ID and source commit behind Installation details) and read-only startup settings, each named by its environment variable, with a link to the configuration guide's section on changing them. - A node whose provider is not ready names the reason as one Provider-neutral readiness class (provider unavailable, host unsupported, provider files or Runtime image missing, a host too small) and its fix in the help tip beside its status, wherever that status shows. - A node enrolled with an earlier Core address gets no new sandboxes, so on the Nodes list and its page its status is Old address, with "Remove and add again", never Available. - **Sandbox reset** is an explicit administrator operation in Settings → Sandbox and scheduling. Auto clear is the default, with a one-hour deadline (5 minutes–24 hours); Force clear requires destructive confirmation. Its semantics are defined in [Reset](../../contracts/agents-api/sandbox-deployment.md#reset); Web shows only Core's progress and completion, and a new configuration is a separate deliberate save. - **Online sandbox configuration** changes the same backend's resources or E2B template without retiring existing nodes or changing existing Sessions' resource ownership. New placement follows Core's qualified capacity; saving a target does not promise immediate placement on it. Configuration rollout shows Core's target preparation and retained previous-generation sandbox count. A settled rollout can still have failed or unknown nodes and old resources. An offline node stays offline even when it has a recorded serving generation. Node and allocation detail distinguish the serving pin, target preparation and each resource's configuration generation. - **E2B credential replacement** uses the same configuration form. Setup requires a key; leaving it blank during an update keeps the saved key. An explicit key, even the same value, is verified as a replacement and advances the target generation after successful verification. Another backend or E2B team requires a deliberate reset. A rejected or uncertain replacement never clears the committed configuration or replays the write. - **E2B deployments** have no machines: Nodes offers a link to Settings → Sandbox and scheduling. Overview and Sandbox metrics show the sandboxes Core holds in E2B's cloud (running, starting or changing, and the size of each) instead of node capacity, with no Add node action; a sandbox's dialog adds its disk use. -- **Automatic suspension** appears when the deployment declares a suspension policy. Nodes shows each node's suspended count and retained limit, the most sandboxes it keeps running and suspended together, with Edit node for its limits; Overview adds the suspended total of all registered nodes under its sandbox slots. Settings → Sandbox and scheduling owns **Automatic suspension**: deployment-wide idle seconds are editable there; snapshot retention remains read-only. These are Core records, not measured CPU or memory savings. Node allocations show the recorded compute phase and elapsed phase time, never an inferred snapshot-expiry countdown. Sandbox metrics' Hosted Runtimes has one Status column: Core's lifecycle record of each sandbox (Active, Suspended, Changing state, Waiting for allocation or Stopped), which Core derives from the allocation's recorded phase. The Session page's Runtime state reads the same way. When an active sandbox has no sample, its CPU and Memory cells name why. Independent workspace persistence is explained only when the deployment declares it. Nodes refreshes its inventory every 30 seconds while visible; reset and active preparation retain their faster polling. +- With checkpoint support, Nodes shows each node's suspended count and retained limit, the most sandboxes it keeps running and suspended together, with Edit node for its limits; Overview adds the suspended total of all registered nodes under its sandbox slots. Settings → Sandbox and scheduling always shows the idle setting: **Automatic suspension** with checkpoint support (deployment-wide idle seconds are editable; snapshot retention remains read-only) and **Idle timeout** without it (idle seconds only). These are Core records, not measured CPU or memory savings. Node allocations show the recorded compute phase and elapsed phase time, never an inferred snapshot-expiry countdown. Sandbox metrics' Hosted Runtimes has one Status column: Core's lifecycle record of each sandbox (Active, Suspended, Changing state, Waiting for allocation or Stopped), which Core derives from the allocation's recorded phase. The Session page's Runtime state reads the same way. When an active sandbox has no sample, its CPU and Memory cells name why. Independent workspace persistence is explained only when the deployment declares it. Nodes refreshes its inventory every 30 seconds while visible; reset and active preparation retain their faster polling. - **Getting started**: signing in opens the console on the Overview; nothing is forced first. While a step is to do, a Getting started checklist on the Overview shows four steps, in any order, each with its state and one action: sandboxes ready (a saved deployment and a node online and ready, or a saved E2B deployment), a default model provider on the default Harness (on any enabled Harness when none is default), a project with an active key, and a first Session, whose action opens the call samples of the newest active project, preferring one with an active key. Completion comes from reads the console already makes. It can be hidden; Show Getting started in the sidebar opens it again, and it ends with a brief "You're set". While it is open, Add node ends with the next step once its node is ready: the default model provider while that is to do, otherwise back to the checklist. The optional three-chapter tour of the console (Monitor, Resources, Platform) opens from it, on the sign-in stage. -- Terminology: API terms stay in English in the Chinese UI and docs (Agent, Session, Turn, Item, Runtime, Environment, Skill, Vault, Credential, Harness); providers are 提供商 (沙箱提供商, 模型提供商). The sign-in credential is the Core key ("Core 密钥"); keys issued in a project for applications are project API keys ("项目 API 密钥"). Empty lists read "No … yet" ("还没有…"). Sandbox provider readiness is "Provider not ready / 沙箱提供商未就绪"; revoked credentials and keys use "Revoked / 已撤销". A default model provider is a service address and write-only key; the application's Agent `model` chooses the provider-supported model name. A sandbox is Core-managed compute; Runtime names Core's execution observations, and Environment is the Session's API execution environment. These are distinct counts and resources, not synonyms. +- Terminology: Empty lists read "No … yet" ("还没有…"). Sandbox provider readiness is "Provider not ready / 沙箱提供商未就绪"; revoked credentials and keys use "Revoked / 已撤销". A default model provider is a service address and write-only key; the application's Agent `model` chooses the provider-supported model name. A sandbox is Core-managed compute; Runtime names Core's execution observations, and Environment is the Session's API execution environment. These are distinct counts and resources, not synonyms. ## Capabilities and Constraints - **Projects and keys.** A project owns an isolated set of assets shared by all of its named API keys; projects do not see each other's assets. Issuing or revoking a key never touches assets. The list shows active projects by default; the Archived filter, with its count, shows the rest. Archiving a project revokes every key and keeps its assets viewable and deletable; it can't be undone, so its confirmation says so, counts the active keys it revokes and, when there are any, asks for the project's name. Key plaintext is shown once, at issuance, and never stored by the console. Beside it, and without the key on an active project's page, the console tells developers to set `OPENAI_BASE_URL` (the installation's API base URL) and `OPENAI_API_KEY` (a key of the project), with curl and Python samples that list Agents and create a Session. -- **One home for each setting.** Settings owns each platform configuration editor. Overview, Nodes, metrics and onboarding navigate to its relevant group rather than duplicating forms. Each resource saves through its API independently; there is no cross-resource save. Process settings remain file-owned and read-only in Web. Projects, API keys and Session executor credentials remain on their resource pages. Capacity is node-owned, idle policy is deployment-wide, and sandbox specifications are independent of node limits. Resource editing uses a dialog; rollout counts and generations appear in its details dialog. Settings shows configuration and the status that qualifies it, not capacity figures. Each fact has one page: Nodes owns the node list, per-node capacity and host figures; Overview summarizes capacity and links to Nodes; Sandbox metrics owns Runtime time series and activity; Core metrics owns the Core process. Reset sits apart at the end of Sandbox and scheduling, and leads it while a reset runs. +- **One home for each setting.** Overview, Nodes, metrics and onboarding navigate to the relevant group in [Settings](../../docs/configuration.md#runtime-settings-web) rather than duplicating forms. Capacity is node-owned, idle policy is deployment-wide, and sandbox specifications are independent of node limits. Resource editing uses a dialog; rollout counts and generations appear in its details dialog. Settings shows configuration and the status that qualifies it, not capacity figures. Each fact has one page: Nodes owns the node list, per-node capacity and host figures; Overview summarizes capacity and links to Nodes; Sandbox metrics owns Runtime time series and activity; Core metrics owns the Core process. Reset sits apart at the end of Sandbox and scheduling, and leads it while a reset runs. - **Workspace storage.** Settings → Workspace storage owns selecting an immutable configuration and editing tenant capacity through the storage API. It shows the adapter and tenant capacity; the configuration ID and adapter parameters stay under Configuration details. Adapter parameters and optional write-only credentials are JSON objects validated by Core, with no vendor-specific Web fields or capability discovery by name. Selecting a new configuration does not migrate existing workspaces; changing tenant capacity does not resize them. Credentials are never prefilled, stored in browser persistence or included in error output. Uncertain writes require an authoritative read before another save. -- **Web API only.** Every read and write goes through `/core/v1/**`. The console holds no API key and sends nothing to `/v1`. - **No asset writes except delete.** Assets are created and changed only by a project's keys through the Agents API. The console does not create or edit Agents or Templates, upload Skills or Files, create or replace Credentials, start Sessions, send input or cancel work. Deletion follows the public deletion rules; a busy Session is not deletable and the console never cancels work to make it so. - **Secrets stay write-only.** Credential tokens, Template environment variables and setup commands are never returned, to the administrator included. An Agent's saved model provider shows its protocol, base URL, limits and whether a key is configured, never the key. - **Creators.** Core records the key behind every write. The console shows the creating key of each asset and a project's write history; an asset without a record shows as Unknown. @@ -57,8 +54,8 @@ The console runs beside the administrator's own Core, with execution, files and - **Failure diagnostics.** Failed Session and Turn rows read Core diagnostics and translate its classified reason. On the Session page the Status fact shows the status alone, and the reason and its next step, where the reason has one, read as one block under the facts, such as checking the model shown on the Session page and the Session's model provider; lists show the reason alone, with the next step in its tooltip. A next step must hold for every Session kind and deployment: a self-hosted Session never uses the default model provider, and an E2B deployment has no nodes. Provider observations in Settings show the reason alone. Core never returns the Harness's or provider's own message, so an unclassified failure says so. The console never infers a cause from raw logs. Unavailable or mismatched diagnostics offer an explicit read retry; refreshing does not replay execution. Trace Timing keeps each Item's Core receipt interval separate from public Turn times and native tool duration. Historical missing timestamps stay unknown, negative clock intervals stay missing, and bounded response truncation remains visible. - **Executor credentials.** Core issues executor credentials; the console does so with the deployment's Core key. A Session page whose environment is self-hosted has an Executor credentials section: issue a credential (shown once as one line of JSON, to copy or download, never stored), rotate it (the old one stops working immediately) or revoke it (the executor disconnects; installed Runtime state and workspace contents are not deleted). The file lets one executor connect for that environment only; it cannot call the Agents API. - **Default provider observations.** Each configured Harness offers Usage details for Core's last successful use and any newer classified provider error. Missing records remain unknown; an error at or before the last success is no longer actionable. These are best-effort observations, not readiness checks. Failed refreshes qualify retained records, and replacing the provider starts a new observation history. -- **Host connection.** Core's connection observation and credential metadata share one five-second read while visible. Never connected, connected, disconnected, bound credential revoked, and unknown are distinct; a recent heartbeat alone never proves connectivity. Only a fresh connected read marks Host connected. Stale or failed reads withhold completion. Recovery rotates the bound key, stops the installed daemon, replaces the host credential file and starts the daemon again. -- **Connect a host.** The Linux/macOS and PowerShell commands come from Core's installation read for the Session's environment; the console shows them as they are, with a link to the native installation guide, and never builds one itself. A command downloads the matching installer, installs the chosen Harnesses, starts the daemon and checks its connection. Its authorization expires after 30 minutes; the console reads a fresh one every 20 minutes, and says the command is unavailable when Core has none. No model readiness is implied. Rotating a credential requires stopping the installed daemon, replacing the configured file and starting that same daemon again. A disconnected daemon may still be running; `start` alone does not replace it. +- **Host connection.** Core's connection observation and credential metadata share one five-second read while visible. Never connected, connected, disconnected, bound credential revoked, and unknown are distinct; a recent heartbeat alone never proves connectivity. Only a fresh connected read marks Host connected. Stale or failed reads withhold completion. +- **Connect a host.** The Linux/macOS and PowerShell commands come from Core's installation read for the Session's environment; the console shows them as they are, with a link to the native installation guide, and never builds one itself. A command downloads the matching installer, installs the chosen Harnesses, starts the daemon and checks its connection. Its authorization expires after 30 minutes; the console reads a fresh one every 20 minutes, and says the command is unavailable when Core has none. No model readiness is implied. - **Typed errors.** Every failure the console shows, read or write, follows one rule. Known Core codes use shared bilingual copy and safe typed details. Exact Core field paths attach definite refusals to the relevant input. Other codes show Core's own message in English and name the code in Chinese, since Core's messages are English; a failure without a code names its HTTP status, and one that never reached Core says so. Uncertain write outcomes stay form-level and are never retried automatically. - **Read failures.** A read is tried again once after a 5xx answer or a failed connection, never after a 4xx answer. Overview and Session log distinguish unavailable reads from successful empty results. Failed reads have a visible retry; a first read that fails never mentions earlier data; retained or partial data says it may be incomplete or out of date, and Session filter totals stay missing while any required read has failed. Only successful empty reads show zero. - **Local-only address.** Overview, Nodes and Settings warn when Core reports `local_only` and lead to Settings → Service and deployment to review the public address. Add node is unavailable with a reason; Getting started keeps the first step to do until the public address is fixed. An unread installation address cannot complete that step, and a failed read offers Retry. diff --git a/apps/web/e2e/console.ts b/apps/web/e2e/console.ts index 14381899f..03d2e3fdd 100644 --- a/apps/web/e2e/console.ts +++ b/apps/web/e2e/console.ts @@ -14,9 +14,9 @@ export const FIXTURE_CORE_KEY = "fixture-core-key-3f9a2c71"; * (loopback: only the Core machine reaches the API, and E2B is rejected) or "stale" (public, * with a node enrolled with an earlier address), and `installers: "none"` a console without its node installation payload, so it serves neither * the node nor the self-hosted installer. `nodeArtifacts` lists the providers the console has - * node files for, both by default; as in the console, microsandbox needs Docker's files too. + * node files for, microsandbox by default. */ -export interface FixtureOptions { fresh?: boolean; sandbox?: "configured" | "none" | "e2b"; nodes?: "none"; installation?: "public" | "local" | "stale"; installers?: "none"; nodeArtifacts?: ("docker" | "microsandbox")[] } +export interface FixtureOptions { fresh?: boolean; sandbox?: "configured" | "none" | "e2b"; nodes?: "none"; installation?: "public" | "local" | "stale"; installers?: "none"; nodeArtifacts?: "microsandbox"[] } /** Fresh fixture state: signed out ("login") or already signed in ("authenticated"). */ export async function resetFixture(request: APIRequestContext, auth: "login" | "authenticated" = "authenticated", options: FixtureOptions = {}) { diff --git a/apps/web/e2e/data/resources.mjs b/apps/web/e2e/data/resources.mjs index a542ef781..694ff1fd3 100644 --- a/apps/web/e2e/data/resources.mjs +++ b/apps/web/e2e/data/resources.mjs @@ -42,7 +42,7 @@ export function buildResources(now) { ].map((template, index) => ({ id: uuid(), object: "agent.environment.template", name: template.name, created_at: now - 86400 * (4 + index * 5), updated_at: now - 86400 * (1 + index * 2), - capability_directories: index === 0 ? ["/workspace/capabilities"] : [], network: template.network, packages: template.packages, + capability_directories: index === 0 ? ["/workspace/capabilities"] : [], network: template.network, desktop: { enabled: false }, packages: template.packages, files: template.files, plugins: [], skills: template.skills, })); @@ -56,7 +56,7 @@ export function buildResources(now) { const created = vault.created_at + 3600 * (index + 1); return { id: uuid(), vault_id: vault.id, name, object: "vault.credential", auth: { type: "static_bearer", mcp_server_url: `https://mcp.example.com/${name.toLowerCase().replace(/\s+/g, "-")}` }, - created_at: created, updated_at: created + (index % 2 ? 86400 : 0) }; + metadata: {}, created_at: created, updated_at: created + (index % 2 ? 86400 : 0) }; }).reverse()])); return { diff --git a/apps/web/e2e/data/routes.mjs b/apps/web/e2e/data/routes.mjs index adddd9dea..4315e4bb8 100644 --- a/apps/web/e2e/data/routes.mjs +++ b/apps/web/e2e/data/routes.mjs @@ -72,7 +72,7 @@ export function buildDemo(now = Math.floor(Date.now() / 1000), publicUrl = "http const { object: _o, metadata: _m, created_at: _c, updated_at: _u, ...snapshot } = agent; sessions.push({ id, object: "agent.session", agent: snapshot, - environment: envType === "none" ? { type: "none" } : envType === "self_hosted" ? { type: "self_hosted", id: uuid(), remote_url: daemonUrl(publicUrl), workspace_directory: "/srv/work", capability_directories: [] } : { type: "openai_hosted", id: uuid(), capability_directories: [], network: { access: "disabled", allowed_domains: [] }, packages: { npm: [], python: [], system: [] }, files: [], plugins: [], skills: [] }, + environment: envType === "none" ? { type: "none" } : envType === "self_hosted" ? { type: "self_hosted", id: uuid(), remote_url: daemonUrl(publicUrl), workspace_directory: "/srv/work", capability_directories: [] } : { type: "openai_hosted", id: uuid(), container_size: null, desktop: { enabled: false }, capability_directories: [], network: { access: "disabled", allowed_domains: [] }, packages: { npm: [], python: [], system: [] }, files: [], plugins: [], skills: [] }, status, error: status === "failed" ? pick(["Sandbox allocation failed: node unavailable.", "Model provider returned 429 Too Many Requests.", "Tool call timed out after 300 s."]) : null, metadata: {}, required_actions: status === "requires_action" ? [{ type: "function_call", call_id: uuid(), turn_id: sessionTurns.at(-1)?.id ?? uuid(), name: "approve_refund", arguments: {} }] : [], vault_ids: [], usage: status === "in_progress" ? null : sessionTurns.length ? { input_tokens: input, output_tokens: output, total_tokens: input + output, input_tokens_details: { cached_tokens: cached }, output_tokens_details: { reasoning_tokens: reasoning } } : null, @@ -83,9 +83,9 @@ export function buildDemo(now = Math.floor(Date.now() / 1000), publicUrl = "http }); sessions.sort((a, b) => b.created_at - a.created_at); const nodes = [ - { rollout: { state: "ready", ready_generation: 1 }, id: "node-local", name: "core-01", provider: "docker", online: true, provider_ready: true, cpu_count: 16, available_memory_bytes: 38 * 2 ** 30, available_disk_bytes: 410 * 2 ** 30, running: 5, snapshots: 2, last_seen_at: new Date((now - 8) * 1000).toISOString(), max_active: 8, max_retained: 16, recommended_capacity: { max_active: 6, max_retained: 6 }, active: 5, reserved: 1, retained: 2, cleanup_pending: 0, created_at: new Date((now - 86400 * 30) * 1000).toISOString() }, - { rollout: { state: "failed", ready_generation: null, diagnostic: "host_unsupported" }, id: "node-gpu", name: "gpu-worker-02", provider: "docker", online: true, provider_ready: false, cpu_count: 32, available_memory_bytes: 12 * 2 ** 30, available_disk_bytes: 96 * 2 ** 30, running: 7, snapshots: 5, last_seen_at: new Date((now - 12) * 1000).toISOString(), max_active: 8, max_retained: 16, recommended_capacity: null, active: 7, reserved: 0, retained: 5, cleanup_pending: 1, created_at: new Date((now - 86400 * 12) * 1000).toISOString() }, - { rollout: { state: "unknown", ready_generation: 1 }, id: "node-edge", name: "edge-03", provider: "docker", online: false, provider_ready: false, cpu_count: 8, available_memory_bytes: null, available_disk_bytes: null, running: 0, snapshots: 0, last_seen_at: new Date((now - 5400) * 1000).toISOString(), max_active: 4, max_retained: 8, recommended_capacity: null, active: 0, reserved: 0, retained: 0, cleanup_pending: 0, created_at: new Date((now - 86400 * 3) * 1000).toISOString() }, + { rollout: { state: "ready", ready_generation: 1 }, id: "node-local", name: "core-01", provider: "microsandbox", online: true, provider_ready: true, cpu_count: 16, available_memory_bytes: 38 * 2 ** 30, available_disk_bytes: 410 * 2 ** 30, running: 5, snapshots: 2, last_seen_at: new Date((now - 8) * 1000).toISOString(), max_active: 8, max_retained: 16, recommended_capacity: { max_active: 6, max_retained: 6 }, active: 5, reserved: 1, retained: 2, cleanup_pending: 0, created_at: new Date((now - 86400 * 30) * 1000).toISOString() }, + { rollout: { state: "failed", ready_generation: null, diagnostic: "host_unsupported" }, id: "node-gpu", name: "gpu-worker-02", provider: "microsandbox", online: true, provider_ready: false, cpu_count: 32, available_memory_bytes: 12 * 2 ** 30, available_disk_bytes: 96 * 2 ** 30, running: 7, snapshots: 5, last_seen_at: new Date((now - 12) * 1000).toISOString(), max_active: 8, max_retained: 16, recommended_capacity: null, active: 7, reserved: 0, retained: 5, cleanup_pending: 1, created_at: new Date((now - 86400 * 12) * 1000).toISOString() }, + { rollout: { state: "unknown", ready_generation: 1 }, id: "node-edge", name: "edge-03", provider: "microsandbox", online: false, provider_ready: false, cpu_count: 8, available_memory_bytes: null, available_disk_bytes: null, running: 0, snapshots: 0, last_seen_at: new Date((now - 5400) * 1000).toISOString(), max_active: 4, max_retained: 8, recommended_capacity: null, active: 0, reserved: 0, retained: 0, cleanup_pending: 0, created_at: new Date((now - 86400 * 3) * 1000).toISOString() }, ]; const hosted = sessions.filter((session) => session.environment.type === "openai_hosted"); const allocations = hosted.map((session, index) => { @@ -104,7 +104,7 @@ export function buildDemo(now = Math.floor(Date.now() / 1000), publicUrl = "http if (session.environment.type === "self_hosted") return { ...base, environment_id: session.environment.id, mode: "self_hosted", provider_type: null, instance: { kind: "self_hosted_connection", allocation_id: null, device_id: null, connection_generation: null }, lifecycle_state: null, status: "unsupported", reason: "runtime_mode_not_observable", allocation_created_at: null, observed_at: null, started_at: null, memory: null }; const allocation = allocations.find((entry) => entry.session_id === session.id); const sleeping = allocation.compute_phase === "suspended"; - return { ...base, environment_id: session.environment.id, mode: "openai_hosted", provider_type: "docker", instance: { kind: "managed_allocation", allocation_id: allocation.id, device_id: null, connection_generation: null }, lifecycle_state: sleeping ? "sleeping" : "active", status: "observed", reason: null, allocation_created_at: session.created_at, observed_at: now - 2, started_at: session.created_at, memory: sleeping ? null : { usage_bytes: Math.floor((0.4 + rand() * 1.4) * 2 ** 30), limit_bytes: 2 * 2 ** 30 } }; + return { ...base, environment_id: session.environment.id, mode: "openai_hosted", provider_type: "microsandbox", instance: { kind: "managed_allocation", allocation_id: allocation.id, device_id: null, connection_generation: null }, lifecycle_state: sleeping ? "sleeping" : "active", status: "observed", reason: null, allocation_created_at: session.created_at, observed_at: now - 2, started_at: session.created_at, memory: sleeping ? null : { usage_bytes: Math.floor((0.4 + rand() * 1.4) * 2 ** 30), limit_bytes: 2 * 2 ** 30 } }; }); // Added after everything else is generated, so the seeded data above does not change. agents.push(...providerAgentDefinitions.map((definition, index) => ({ diff --git a/apps/web/e2e/fixture-console.mjs b/apps/web/e2e/fixture-console.mjs index a6c92d720..286e84715 100644 --- a/apps/web/e2e/fixture-console.mjs +++ b/apps/web/e2e/fixture-console.mjs @@ -82,21 +82,21 @@ function nodeRollout(previous = 0) { } function unconfiguredDeployment(generation = 0, ownerEpoch = 3) { - return { installation_id: INSTALLATION_ID, provider: "", credential_configured: false, core_url: publicUrl(), reset: null, rollout: noNodeRollout(), owner_epoch: ownerEpoch, generation, mode: "", resources: { allocations: 0, running: 0, pending: 0 }, suspension: null }; + return { installation_id: INSTALLATION_ID, provider: "", credential_configured: false, core_url: publicUrl(), reset: null, rollout: noNodeRollout(), owner_epoch: ownerEpoch, generation, mode: "", resources: { allocations: 0, running: 0, pending: 0 }, idle_seconds: 300, suspension: null }; } function configuredDeployment() { - return { installation_id: INSTALLATION_ID, provider: "docker", credential_configured: false, configuration: {}, metadata: {}, core_url: publicUrl(), reset: null, rollout: nodeRollout(), owner_epoch: 3, generation: 1, mode: "nodes", resources: { allocations: 0, running: 0, pending: 0 }, specification: { resources: { cpus: 2, memory_mib: 4096 } }, specification_digest: "fixture", suspension: null }; + return { installation_id: INSTALLATION_ID, provider: "microsandbox", credential_configured: false, configuration: {}, metadata: {}, core_url: publicUrl(), reset: null, rollout: nodeRollout(), owner_epoch: 3, generation: 1, mode: "nodes", resources: { allocations: 0, running: 0, pending: 0 }, specification: { resources: { cpus: 2, memory_mib: 4096 }, network: { public: true, domains: [] } }, specification_digest: "fixture", idle_seconds: 300, suspension: { retention_seconds: 86400 } }; } /** The E2B template build as Core read it when the selection was saved. */ const templateBuild = { status: "ready", resources: { cpus: 2, memory_mib: 2048, root_disk_mib: 10240 } }; // E2B runs sandboxes in its cloud: no nodes, only what Core holds there. function e2bDeployment() { - return { ...configuredDeployment(), provider: "e2b", mode: "direct", rollout: noNodeRollout(), resources: { allocations: 3, running: 3, pending: 1 }, specification: { resources: { cpus: 2, memory_mib: 2048 } }, configuration: { template: "oac-runtime:0f1e2d3c-4b5a-6978-8a9b-0c1d2e3f4a5b", api_url: "https://api.e2b.app", domain: "e2b.app" } , credential_configured: true, metadata: { template_build: templateBuild } }; + return { ...configuredDeployment(), provider: "e2b", mode: "direct", rollout: noNodeRollout(), suspension: null, resources: { allocations: 3, running: 3, pending: 1 }, specification: { resources: { cpus: 2, memory_mib: 2048 }, network: { public: true, domains: [] } }, configuration: { template: "oac-runtime:0f1e2d3c-4b5a-6978-8a9b-0c1d2e3f4a5b", api_url: "https://api.e2b.app", domain: "e2b.app" } , credential_configured: true, metadata: { template_build: templateBuild } }; } -function reset(mode = "login", fresh = false, sandbox = "configured", nodes = "demo", address = "public", installers = true, artifacts = "docker,microsandbox") { +function reset(mode = "login", fresh = false, sandbox = "configured", nodes = "demo", address = "public", installers = true, artifacts = "microsandbox") { // Self-hosted Sessions get their remote_url from public_url, as in Core. const screenshots = process.env.OAC_WEB_SCREENSHOT_DEMO === "1"; const now = Math.floor(Date.now() / 1000); @@ -253,6 +253,7 @@ async function adminWrite(request, response, path) { const index = collection.findIndex((entry) => entry.id === resourceId && a.owner.get(`${kind.slice(0, -1)}:${entry.id}`) === project.id); if (index < 0) return error(response, 404, "No such resource."); collection.splice(index, 1); + if (kind === "sessions") for (const allocation of state.allocations) if (allocation.session_id === resourceId) allocation.session_id = null; return send(response, 200, { id: resourceId, object: kind === "agents" ? "agent.deleted" : "agent.session.deleted", deleted: true }); } return error(response, 404, "Not found."); @@ -293,7 +294,7 @@ function adminRead(response, path, url) { if (m[2] === "diagnostics") { const failedTurn = (state.turns.get(session.id) ?? []).findLast((turn) => turn.status === "failed"); return send(response, 200, { object: "core.session_diagnostics", session_id: session.id, status: session.status, - failure: session.status === "failed" ? { source: failedTurn ? "turn" : "environment_input", ...(failedTurn ? { turn_id: failedTurn.id } : {}), code: "internal_error", params: {}, failed_at: null } : null }); + failure: session.status === "failed" ? { source: failedTurn ? "turn" : "environment_input", ...(failedTurn ? { turn_id: failedTurn.id } : {}), code: "internal_error", params: {}, failed_at: null } : null, initialization_steps: [] }); } const diagnostics = m[2].match(/^turns\/([^/]+)\/diagnostics$/); if (diagnostics) { @@ -381,9 +382,9 @@ async function sandboxRoute(request, response, path, url) { } if (path === "/deployment" && request.method === "PATCH") { const input = await body(request); - if (!state.deployment.suspension || state.deployment.reset) return error(response, 409, "Suspension policy is unavailable.", "sandbox_deployment_conflict"); + if (!state.deployment.provider || state.deployment.reset) return error(response, 409, "Idle policy is unavailable.", "sandbox_deployment_conflict"); if (!Number.isInteger(input.idle_seconds) || input.idle_seconds < 30 || input.idle_seconds > 86400) return error(response, 400, "Invalid idle seconds.", "invalid_request_error"); - state.deployment.suspension.idle_seconds = input.idle_seconds; + state.deployment.idle_seconds = input.idle_seconds; return send(response, 200, state.deployment); } if (path === "/deployment" && (request.method === "POST" || request.method === "PUT")) { @@ -410,7 +411,7 @@ async function sandboxRoute(request, response, path, url) { // As Core: E2B may omit resources and adopt its template build's CPU and memory; only microsandbox suspends. const resources = input.resources ?? { cpus: templateBuild.resources.cpus, memory_mib: templateBuild.resources.memory_mib }; const previous = state.deployment; - const specification = { resources }; + const specification = { resources, network: input.network ?? (initialize ? { public: true, domains: [] } : previous.specification.network) }; const explicitKey = e2b && Object.hasOwn(input, "credential"); const sameSelection = !initialize && JSON.stringify(specification) === JSON.stringify(previous.specification) && (!e2b || input.configuration.template === previous.configuration?.template); // Omission can be a no-op; every explicit key, including identical bytes, @@ -427,7 +428,7 @@ async function sandboxRoute(request, response, path, url) { rollout: e2b ? { ...noNodeRollout(), previous_generation_sandboxes: held.allocations + held.pending } : nodeRollout(held.allocations + held.pending), specification, ...(e2b ? { configuration: { template: input.configuration?.template ?? "", api_url: input.configuration?.api_url ?? state.deployment.configuration?.api_url ?? "https://api.e2b.app", domain: input.configuration?.domain ?? state.deployment.configuration?.domain ?? "e2b.app" } , credential_configured: true, metadata: { template_build: templateBuild } } : { configuration: {}, metadata: {}, credential_configured: false }), - suspension: input.provider === "microsandbox" ? { idle_seconds: 300, retention_seconds: 86400 } : null, + idle_seconds: previous.idle_seconds, suspension: input.provider === "microsandbox" ? { retention_seconds: 86400 } : null, }; return send(response, 200, state.deployment); } @@ -521,7 +522,7 @@ async function executorCredentialRoute(request, response, projectId, environment */ function registeredNode(nodeId) { const { enrollment_id = null, ...limits } = state.enrollment ?? { max_active: 1, max_retained: 1 }; - return { rollout: { state: "unknown", ready_generation: null }, id: nodeId, name: nodeId, provider: state.deployment?.provider ?? "docker", core_url: publicUrl(), enrollment_id, online: false, provider_ready: false, cpu_count: null, available_memory_bytes: null, available_disk_bytes: null, running: 0, snapshots: 0, last_seen_at: null, recommended_capacity: null, ...limits, active: 0, reserved: 0, retained: 0, cleanup_pending: 0, created_at: new Date().toISOString() }; + return { rollout: { state: "unknown", ready_generation: null }, id: nodeId, name: nodeId, provider: state.deployment?.provider ?? "microsandbox", core_url: publicUrl(), enrollment_id, online: false, provider_ready: false, cpu_count: null, available_memory_bytes: null, available_disk_bytes: null, running: 0, snapshots: 0, last_seen_at: null, recommended_capacity: null, ...limits, active: 0, reserved: 0, retained: 0, cleanup_pending: 0, created_at: new Date().toISOString() }; } const HARNESS_PROVIDER = /^\/harnesses\/([^/]+)\/model-configuration$/; diff --git a/apps/web/e2e/nodes.spec.ts b/apps/web/e2e/nodes.spec.ts index bb0889aa6..9e5685126 100644 --- a/apps/web/e2e/nodes.spec.ts +++ b/apps/web/e2e/nodes.spec.ts @@ -26,10 +26,10 @@ test("adds a node: host requirements, a root/sudo command, a countdown, the same await expect(add.getByLabel("One-time enrollment command without sudo", { exact: true })).toHaveCount(0); await add.getByRole("radio", { name: "Custom" }).click(); await add.getByLabel("Sandboxes at once").fill("3"); + await add.getByLabel("Retained sandboxes").fill("3"); const tokenRequest = () => page.waitForRequest((sent) => sent.method() === "POST" && sent.url().endsWith("/core/v1/sandbox/enrollment-tokens")); const issued = tokenRequest(); await add.getByRole("button", { name: "Generate command" }).click(); - // Docker never suspends, so it retains exactly the sandboxes it runs. expect((await issued).postDataJSON()).toEqual({ max_active: 3, max_retained: 3 }); const field = add.getByLabel("One-time enrollment command", { exact: true }); await expect(field).toHaveValue(/enroll_fixture_/); @@ -42,7 +42,7 @@ test("adds a node: host requirements, a root/sudo command, a countdown, the same await expect(add.getByText("If the command is interrupted or the download stalls, run it again: unfinished downloads restart, and verified files are reused.")).toBeVisible(); await expect(add.getByRole("timer")).toHaveText(/^Expires in (1:00:00|59:\d\d)$/); const progress = add.getByRole("status", { name: "Registration progress" }); - await expect(progress).toHaveText(/Waiting for registration.*Connect.*Docker check/); + await expect(progress).toHaveText(/Waiting for registration.*Connect.*microsandbox check/); // Closing keeps the command for the next opening. Meanwhile another command's node, with the // same limits, registers: it reports another enrollment ID, so it is not this command's node. @@ -53,7 +53,7 @@ test("adds a node: host requirements, a root/sudo command, a countdown, the same await page.getByRole("button", { name: "Add node" }).click(); await expect(field).toHaveValue(first); await expect(page.getByRole("table", { name: "Sandbox nodes" })).toContainText("edge-05"); - await expect(progress).toHaveText(/Waiting for registration.*Connect.*Docker check/); + await expect(progress).toHaveText(/Waiting for registration.*Connect.*microsandbox check/); // Once expired, a new command is issued only on request, for the same limits. await page.clock.fastForward("01:00:30"); @@ -79,7 +79,7 @@ test("adds a node: host requirements, a root/sudo command, a countdown, the same watch.expiredWatch.observe(document.body, { childList: true, subtree: true, characterData: true }); }); await page.getByRole("button", { name: "Add node" }).click(); - await expect(progress).toHaveText(/Registered · edge-04.*Waiting to connect.*Docker check/); + await expect(progress).toHaveText(/Registered · edge-04.*Waiting to connect.*microsandbox check/); expect(await page.evaluate(() => { const watch = window as unknown as { expiredShown: boolean; expiredWatch: MutationObserver }; watch.expiredWatch.disconnect(); @@ -95,7 +95,7 @@ test("adds a node: host requirements, a root/sudo command, a countdown, the same // Connected but not ready, it keeps waiting for its provider; once ready, the node is connected. await setNode(request, { id: "node-new", online: true }); await expect(problem).toContainText("Sandbox provider unavailable"); - await expect(progress).toContainText("Waiting for Docker"); + await expect(progress).toContainText("Waiting for microsandbox"); await setNode(request, { id: "node-new", provider_ready: true }); await expect(progress).toHaveText("edge-04 · Connected"); await add.getByRole("button", { name: "Done" }).click(); @@ -145,7 +145,7 @@ test("issues no command before the installation is read, for a loopback public U await openConsole(page, request, "nodes", { nodeArtifacts: [] }); await page.getByRole("button", { name: "Refresh sandbox state" }).click(); await page.getByRole("button", { name: "Add node" }).click(); - await expect(add.getByRole("status")).toHaveText("This console has no node files for Docker. Install Core from the offline bundle, or add the release artifacts and rerun ./install.sh."); + await expect(add.getByRole("status")).toHaveText("This console has no node files for microsandbox. Install Core from the offline bundle, or add the release artifacts and rerun ./install.sh."); await expect(add.getByRole("button", { name: "Generate command" })).toHaveCount(0); expect(await writes(request)).toEqual([]); // Rerunning ./install.sh adds them: reopening reads the console again, without a reload. @@ -187,7 +187,6 @@ test("marks a node on an old Core address in its row, beside each node's limit", await expect(row).toContainText("Old address"); await expect(row).toContainText("Remove and add again"); await expect(row).not.toContainText("Available"); - // Docker nodes show their limit too. await expect(row).toContainText("5 / 8"); }); @@ -224,34 +223,6 @@ test("sets up own-machine sandboxes page by page", async ({ page, request }) => await page.getByRole("button", { name: "Settings", exact: true }).click(); }); -test("preselects microsandbox and asks once before switching to Docker", async ({ page, request }) => { - await openConsole(page, request, "settings?id=sandbox", { sandbox: "none" }); - await page.getByRole("button", { name: "Own machines" }).click(); - const microsandbox = page.getByRole("button", { name: "microsandbox Recommended" }); - const docker = page.getByRole("button", { name: "Docker", exact: true }); - const confirm = page.getByRole("dialog", { name: "Use Docker?" }); - const sizeStep = page.getByRole("heading", { name: "How big is each sandbox?" }); - await expect(microsandbox).toHaveAttribute("aria-pressed", "true"); - - // Keeping microsandbox is the default action; it leaves microsandbox selected. - await docker.click(); - const keep = confirm.getByRole("button", { name: "Back" }); - await expect(keep).toBeFocused(); - await keep.click(); - await expect(confirm).toBeHidden(); - await expect(microsandbox).toHaveAttribute("aria-pressed", "true"); - - // Confirmed, Docker is selected and the wizard does not ask again. - await docker.click(); - await confirm.getByRole("button", { name: "Use Docker" }).click(); - await expect(sizeStep).toBeVisible(); - await page.getByRole("button", { name: "Back", exact: true }).click(); - await expect(docker).toHaveAttribute("aria-pressed", "true"); - await docker.click(); - await expect(sizeStep).toBeVisible(); - await expect(confirm).toHaveCount(0); -}); - test("saves E2B without opening Add node, as it has no machines", async ({ page, request }) => { let submitted: Record | null = null; page.on("request", (sent) => { @@ -313,10 +284,10 @@ test("shows the retained E2B build while a replacement key is checked", async ({ }); test("edits only the saved backend, preserving a custom size", async ({ page, request }) => { - const current = { resources: { cpus: 7, memory_mib: 8192 } }; - let deployment = { configuration: {}, metadata: {}, credential_configured: false, installation_id: "94be54a1-138c-4f30-bc87-b13686272dbe", provider: "docker", core_url: "https://core.example", reset: null, rollout: { state: "settled", previous_generation_sandboxes: 0, nodes: { ready: 0, preparing: 0, failed: 0, unknown: 0 } }, + const current = { resources: { cpus: 7, memory_mib: 8192, root_disk_mib: 10240 }, network: { public: true, domains: [] }, workspace: { attachment: "host_directory", user_xattr: true, capacity_quota: false } }; + let deployment = { configuration: {}, metadata: {}, credential_configured: false, installation_id: "94be54a1-138c-4f30-bc87-b13686272dbe", provider: "microsandbox", core_url: "https://core.example", reset: null, rollout: { state: "settled", previous_generation_sandboxes: 0, nodes: { ready: 0, preparing: 0, failed: 0, unknown: 0 } }, owner_epoch: 1, generation: 1, mode: "nodes", resources: { allocations: 0, running: 0, pending: 0 }, specification: current, specification_digest: "e".repeat(64), - suspension: null }; + idle_seconds: 300, suspension: null }; let submitted: Record | null = null; await page.route("**/core/v1/sandbox/deployment", async (route) => { if (route.request().method() === "PUT") { @@ -332,7 +303,7 @@ test("edits only the saved backend, preserving a custom size", async ({ page, re await expect(page.getByRole("button", { name: "E2B", exact: true })).toHaveCount(0); await page.getByRole("button", { name: /^Current/ }).click(); await page.getByRole("button", { name: "Save configuration" }).click(); - await expect.poll(() => submitted).toMatchObject({ provider: "docker", expected_generation: 1, resources: current.resources }); + await expect.poll(() => submitted).toMatchObject({ provider: "microsandbox", expected_generation: 1, resources: current.resources }); expect(submitted).not.toHaveProperty("core_url"); }); @@ -367,7 +338,7 @@ test("renames a node and sets how many sandboxes run on it at once", async ({ pa await page.getByRole("row").filter({ hasText: "core-01" }).getByRole("button", { name: "Edit node" }).click(); const edit = page.getByRole("dialog", { name: "Edit node" }); await edit.getByLabel("Name").fill("core-01-large"); - await expect(edit).toContainText("Recommended: 6 at once."); + await expect(edit).toContainText("Recommended: 6 at once, 6 retained."); await edit.getByRole("button", { name: "Use recommended" }).click(); await expect(edit.getByLabel("Sandboxes at once")).toHaveValue("6"); await edit.getByRole("button", { name: "Save" }).click(); diff --git a/apps/web/e2e/projects.spec.ts b/apps/web/e2e/projects.spec.ts index 1d26b0078..a0d6b29c4 100644 --- a/apps/web/e2e/projects.spec.ts +++ b/apps/web/e2e/projects.spec.ts @@ -22,7 +22,7 @@ test("creates a project, shows a new key once, revokes it and archives the proje await expect(call.getByLabel("Shell", { exact: true })).toHaveText(`export OPENAI_BASE_URL=https://core.example.com/v1\nexport OPENAI_API_KEY=${key}`); await expect(call.getByLabel("curl", { exact: true })).toContainText('curl "$OPENAI_BASE_URL/agents"'); await expect(call.getByLabel("curl", { exact: true })).toContainText('curl "$OPENAI_BASE_URL/agents/sessions"'); - await expect(call.getByLabel("Python", { exact: true })).toContainText("pip install openai==3.13.0"); + await expect(call.getByLabel("Python", { exact: true })).toContainText("pip install openai==3.45.0"); await issued.getByRole("button", { name: "I've saved this key" }).click(); await expect(page.getByRole("table", { name: "Keys of Acceptance" })).toContainText("ci"); await expect(page.getByLabel("New key ci")).toHaveCount(0); diff --git a/apps/web/e2e/public-url.spec.ts b/apps/web/e2e/public-url.spec.ts index b7a7ddd2a..2acb6af30 100644 --- a/apps/web/e2e/public-url.spec.ts +++ b/apps/web/e2e/public-url.spec.ts @@ -28,10 +28,10 @@ test("explains an E2B rejection in the wizard, with a link to domain setup", asy await selectFixtureE2BBuild(page); await page.getByRole("button", { name: "Next" }).click(); const address = page.getByRole("definition").filter({ hasText: "http://127.0.0.1:8091" }); - await expect(address).toContainText("Set a public address before connecting; E2B sandboxes need an HTTPS one."); + await expect(address).toContainText("Set a public address before connecting; E2B sandboxes reach Core through it."); await page.getByRole("button", { name: "Save configuration" }).click(); const rejection = page.locator(".wizard-rejection"); - await expect(rejection).toContainText("This sandbox provider needs a public HTTPS address."); + await expect(rejection).toContainText("This sandbox provider needs a public address."); await expect(rejection.getByRole("button", { name: "Managed in Settings" })).toBeVisible(); // Nothing was saved and nothing is uncertain: no dialog, and the wizard stays on its review. await expect(page.getByRole("dialog")).toHaveCount(0); diff --git a/apps/web/e2e/sandbox-generation.spec.ts b/apps/web/e2e/sandbox-generation.spec.ts index a94ac1432..11a9115ef 100644 --- a/apps/web/e2e/sandbox-generation.spec.ts +++ b/apps/web/e2e/sandbox-generation.spec.ts @@ -64,7 +64,7 @@ test("online configuration retains existing resources and stops rapid polling wh await page.getByRole("button", { name: /^Large/ }).click(); const saved = await saveConfiguration(page); expect(saved.response.ok()).toBe(true); - expect(saved.input).toMatchObject({ provider: "docker", expected_generation: 1 }); + expect(saved.input).toMatchObject({ provider: "microsandbox", expected_generation: 1 }); const current = await saved.response.json() as SandboxDeployment; expect(current.generation).toBe(2); expect(current.resources.allocations).toBe(before.allocations.length); @@ -141,7 +141,7 @@ test("unknown target preparation preserves live old-generation service while an test("a generation-only change preserves mixed allocation ownership through failed inventory reads", async ({ page, request }) => { await openConsole(page, request, "settings?id=sandbox"); await expect(rollout(page)).toBeVisible(); - let expected: { session: string; generation: string }[] = []; + let expected: { session: string | null; generation: string }[] = []; await page.route("**/core/v1/sandbox/nodes/node-local/allocations", async (route) => { const response = await route.fetch(); const body = await response.json() as { data: SandboxAllocation[] }; @@ -158,7 +158,7 @@ test("a generation-only change preserves mixed allocation ownership through fail await expect(table.getByRole("columnheader", { name: "Configuration generation", exact: true })).toBeVisible(); await expect.poll(() => [...new Set(expected.map((entry) => entry.generation))].sort()).toEqual(["1", "2"]); const ownership = () => table.locator("tbody tr").evaluateAll((rows) => rows.map((row) => ({ - session: row.querySelector("th code")?.getAttribute("title"), + session: row.querySelector("th code")?.getAttribute("title") ?? null, generation: row.querySelector("td")?.textContent, }))); await expect.poll(ownership).toEqual(expected); @@ -240,7 +240,7 @@ test("uncertain configuration refresh preserves a draft until its generation cha const edit = page.getByRole("dialog", { name: "Change resources", exact: true }); await edit.getByRole("button", { name: /^Large/ }).click(); const wizard = edit.getByRole("region", { name: "Change the sandbox configuration", exact: true }); - const draftSize = await fact(wizard, "Each sandbox").innerText(); + const draftSize = (await fact(wizard, "Each sandbox").textContent()) ?? ""; expect(draftSize).not.toBe(committedSize); await failNext(request, { method: "PUT", path: deploymentPath, status: 503, message: "Configuration outcome is unconfirmed." }); const result = await saveConfiguration(page); diff --git a/apps/web/e2e/sandbox-lifecycle.spec.ts b/apps/web/e2e/sandbox-lifecycle.spec.ts index ffb53a7e7..cc0ca0579 100644 --- a/apps/web/e2e/sandbox-lifecycle.spec.ts +++ b/apps/web/e2e/sandbox-lifecycle.spec.ts @@ -7,7 +7,7 @@ test("shows each node's retained limit and elapsed phase time without inventing await page.route("**/core/v1/sandbox/deployment", async (route) => { const response = await route.fetch(); const deployment = await response.json(); - await route.fulfill({ response, json: { ...deployment, provider: "microsandbox", suspension: { idle_seconds: 300, retention_seconds: 86400 }, specification: { ...deployment.specification, resources: { ...deployment.specification.resources, root_disk_mib: 8192 } } } }); + await route.fulfill({ response, json: { ...deployment, provider: "microsandbox", suspension: { retention_seconds: 86400 }, specification: { ...deployment.specification, resources: { ...deployment.specification.resources, root_disk_mib: 8192 } } } }); }); await page.route("**/core/v1/sandbox/nodes", async (route) => { const response = await route.fetch(); @@ -37,19 +37,13 @@ test("shows each node's retained limit and elapsed phase time without inventing await page.screenshot({ path: testInfo.outputPath("sandbox-metrics-zh.png"), fullPage: true }); }); -test("hides the retained limit when the provider declares no suspension support", async ({ page, request }) => { - await openConsole(page, request, "nodes"); - await expect(page.getByRole("table", { name: "Sandbox nodes" })).toBeVisible(); - await expect(page.getByRole("columnheader", { name: "Retained / limit" })).toHaveCount(0); -}); - test("edits deployment idle time without changing generation", async ({ page, request }) => { // Settings shows the deployment only; Nodes reads the node inventory. const nodeReads: string[] = []; page.on("request", (sent) => { if (new URL(sent.url()).pathname.startsWith("/core/v1/sandbox/nodes")) nodeReads.push(sent.url()); }); await openConsole(page, request, "settings?id=sandbox"); - const deployment = await setDeployment(request, { suspension: { idle_seconds: 300, retention_seconds: 86400 } }); + const deployment = await setDeployment(request, { idle_seconds: 300, suspension: { retention_seconds: 86400 } }); await setDeployment(request, { provider: "microsandbox", specification: { ...deployment.specification!, resources: { ...deployment.specification!.resources, root_disk_mib: 8192 } } }); await page.getByRole("button", { name: "Refresh sandbox state" }).click(); const area = page.getByRole("region", { name: "Automatic suspension" }); @@ -63,10 +57,34 @@ test("edits deployment idle time without changing generation", async ({ page, re await area.getByRole("button", { name: "Save", exact: true }).click(); const saved = await (await response).json(); expect(saved.generation).toBe(deployment.generation); - expect(saved.suspension).toEqual({ idle_seconds: 60, retention_seconds: 86400 }); + expect(saved.idle_seconds).toBe(60); + expect(saved.suspension).toEqual({ retention_seconds: 86400 }); await expect(idle).toHaveValue("60"); await page.reload(); await expect(idle).toHaveValue("60"); expect((await writes(request)).filter((write) => write === "PATCH /core/v1/sandbox/deployment")).toHaveLength(1); expect(nodeReads).toEqual([]); }); + +test("edits the sandbox network cap for new sandboxes", async ({ page, request }) => { + await openConsole(page, request, "settings?id=sandbox"); + const area = page.getByRole("region", { name: "Network" }); + const domains = area.getByLabel("Extra allowed domains"); + await expect(area.getByRole("switch", { name: "Allow public internet" })).toBeChecked(); + await domains.fill("Git.example.com\n*.com"); + await expect(area.getByText("*.com is not a valid host name.")).toBeVisible(); + await expect(area.getByRole("button", { name: "Save", exact: true })).toBeDisabled(); + await domains.fill("gitlab.example.com\n*.corp.example"); + await area.getByRole("switch", { name: "Allow public internet" }).uncheck(); + const response = page.waitForResponse((response) => response.request().method() === "PUT" && response.url().endsWith("/sandbox/deployment")); + await area.getByRole("button", { name: "Save", exact: true }).click(); + expect((await response).request().postDataJSON().network).toEqual({ public: false, domains: ["gitlab.example.com", "*.corp.example"] }); + await expect(page.getByText("New sandboxes will run with this policy")).toBeVisible(); +}); + +test("greys out private domains where the provider cannot reach a private network", async ({ page, request }) => { + await openConsole(page, request, "settings?id=sandbox", { sandbox: "e2b" }); + const area = page.getByRole("region", { name: "Network" }); + await expect(area.getByLabel("Extra allowed domains")).toBeDisabled(); + await expect(area.getByRole("switch", { name: "Allow public internet" })).toBeEnabled(); +}); diff --git a/apps/web/e2e/system.spec.ts b/apps/web/e2e/system.spec.ts index cf4277fac..bf8b30f15 100644 --- a/apps/web/e2e/system.spec.ts +++ b/apps/web/e2e/system.spec.ts @@ -30,7 +30,7 @@ test("sets, replaces and clears a harness's default model configuration, and kee await set.getByLabel("Default model ID").fill("fixture-model"); await expect(set).toContainText("Used for new Sessions when the application does not specify a model."); // Every rejected URL stays local; Enter cannot bypass validation or write a secret. - for (const url of ["http://model.example/v1", "ftp://model.example", "https://user:password@model.example/v1", "https://@model.example/v1", "https:model.example/v1", "https://model.example/v1?token=x", "https://model.example/v1#fragment", "https://model.example/v1?", "https://model.example/v1#", "not a URL"]) { + for (const url of ["ftp://model.example", "https://user:password@model.example/v1", "https://@model.example/v1", "https:model.example/v1", "https://model.example/v1?token=x", "https://model.example/v1#fragment", "https://model.example/v1?", "https://model.example/v1#", "not a URL"]) { await set.getByLabel("Base URL").fill(url); await expect(set.getByLabel("Base URL")).toHaveAttribute("aria-invalid", "true"); await expect(set.getByRole("button", { name: "Save", exact: true })).toBeDisabled(); diff --git a/apps/web/e2e/unified-settings.spec.ts b/apps/web/e2e/unified-settings.spec.ts index 549e8495e..d1c1cf434 100644 --- a/apps/web/e2e/unified-settings.spec.ts +++ b/apps/web/e2e/unified-settings.spec.ts @@ -151,3 +151,15 @@ test("a phone scrolls wide tables inside their frames and keeps every Settings t await expect(page.getByRole("table", { name: "Startup settings" }).getByRole("columnheader", { name: "Restarts", exact: true })).toBeInViewport({ ratio: 1 }); expect(await pageScrollsSideways()).toBe(false); }); + +test("skip to content moves focus to the page and keeps its route", async ({ page, request }) => { + await openConsole(page, request, "settings?id=storage"); + const current = page.getByRole("navigation").getByRole("button", { name: "Workspace storage", exact: true }); + await expect(current).toHaveAttribute("aria-current", "page"); + await page.keyboard.press("Tab"); + await expect(page.getByRole("link", { name: "Skip to main content" })).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(page.locator("#main-content")).toBeFocused(); + await expect(current).toHaveAttribute("aria-current", "page"); + expect(new URL(page.url()).hash).toBe("#settings?id=storage"); +}); diff --git a/apps/web/src/ConsoleApp.tsx b/apps/web/src/ConsoleApp.tsx index 8e55c738e..e661d0103 100644 --- a/apps/web/src/ConsoleApp.tsx +++ b/apps/web/src/ConsoleApp.tsx @@ -120,7 +120,11 @@ function ConsoleShell() {
- {t("skipToContent")} + {/* The router owns the URL fragment, so the link moves focus instead of navigating. */} + { + event.preventDefault(); + document.getElementById("main-content")?.focus(); + }}>{t("skipToContent")} navigate(view)} onIntent={prefetch} onGettingStarted={() => navigate("overview", {}, "getting-started")} />
diff --git a/apps/web/src/features/api-keys/HowToCall.tsx b/apps/web/src/features/api-keys/HowToCall.tsx index 8c49e2bca..3cae7d8e4 100644 --- a/apps/web/src/features/api-keys/HowToCall.tsx +++ b/apps/web/src/features/api-keys/HowToCall.tsx @@ -9,7 +9,7 @@ import { useCopy } from "./IssuedKey"; import "./how-to-call.css"; /** The official SDK release Core is pinned to (contracts/agents-api/upstream.json). */ -const SDK_PIN = "openai==3.13.0"; +const SDK_PIN = "openai==3.45.0"; /** Stands for the model name in the Session example; the note under the samples says what to put there. */ export const MODEL_PLACEHOLDER = ""; diff --git a/apps/web/src/features/dashboard/runtime-history.test.ts b/apps/web/src/features/dashboard/runtime-history.test.ts index df9454bd4..fc22ec350 100644 --- a/apps/web/src/features/dashboard/runtime-history.test.ts +++ b/apps/web/src/features/dashboard/runtime-history.test.ts @@ -73,7 +73,7 @@ function history(overrides: Partial = {}): RuntimeHistory { environment_id: environmentID, allocation_id: allocationID, started_at: { seconds: 10, nanoseconds: 500_000_000 }, - provider_type: "docker", + provider_type: "microsandbox", points: [{ start: 100, end: 130, first_observed_at: 110, last_observed_at: 110, observation_count: 1, observed_count: 1, unavailable_count: 0, diff --git a/apps/web/src/features/fleet/SandboxResetNotice.test.tsx b/apps/web/src/features/fleet/SandboxResetNotice.test.tsx index 79341708d..07ca93c21 100644 --- a/apps/web/src/features/fleet/SandboxResetNotice.test.tsx +++ b/apps/web/src/features/fleet/SandboxResetNotice.test.tsx @@ -6,7 +6,7 @@ import { SandboxResetNotice } from "./SandboxResetNotice"; const reset: SandboxReset = { clear: "auto", requested_at: "2026-09-27T10:00:00Z", deadline_at: "2026-09-27T11:00:00Z", forced_at: null, remaining: { busy: 1, idle: 0, cleanup: 2, on_offline_nodes: 1, offline_nodes: [{ node_id: "n1", name: "Node 1", resources: 1 }] } }; -const deployment = (reset: SandboxReset | null): SandboxDeployment => ({ credential_configured: false, configuration: {}, metadata: {}, rollout: { state: "settled", previous_generation_sandboxes: 0, nodes: { ready: 1, preparing: 0, failed: 0, unknown: 0 } }, installation_id: "i", provider: "docker", core_url: "http://core", reset, owner_epoch: 1, generation: 1, mode: "nodes", resources: { allocations: 3, running: 3, pending: 0 }, suspension: null }); +const deployment = (reset: SandboxReset | null): SandboxDeployment => ({ credential_configured: false, configuration: {}, metadata: {}, rollout: { state: "settled", previous_generation_sandboxes: 0, nodes: { ready: 1, preparing: 0, failed: 0, unknown: 0 } }, installation_id: "i", provider: "microsandbox", core_url: "http://core", reset, owner_epoch: 1, generation: 1, mode: "nodes", resources: { allocations: 3, running: 3, pending: 0 }, idle_seconds: 300, suspension: null }); const render = (value: SandboxDeployment | undefined, failed = false) => renderToStaticMarkup( {}} />); describe("reset notices on read-only surfaces", () => { diff --git a/apps/web/src/features/fleet/fleet-queries.test.ts b/apps/web/src/features/fleet/fleet-queries.test.ts index aabdcc5c4..b480eb72b 100644 --- a/apps/web/src/features/fleet/fleet-queries.test.ts +++ b/apps/web/src/features/fleet/fleet-queries.test.ts @@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { sandboxAdmin, sandboxDeploymentQuery, sandboxScope } from "../sandbox/sandbox-queries"; import { fleetQuery } from "./fleet-queries"; -const deployment: SandboxDeployment = { credential_configured: false, configuration: {}, metadata: {}, rollout: { state: "settled", previous_generation_sandboxes: 0, nodes: { ready: 1, preparing: 0, failed: 0, unknown: 0 } }, installation_id: "i", provider: "docker", core_url: "http://core", owner_epoch: 1, generation: 1, mode: "nodes", resources: { allocations: 1, running: 1, pending: 0 }, suspension: null, +const deployment: SandboxDeployment = { credential_configured: false, configuration: {}, metadata: {}, rollout: { state: "settled", previous_generation_sandboxes: 0, nodes: { ready: 1, preparing: 0, failed: 0, unknown: 0 } }, installation_id: "i", provider: "microsandbox", core_url: "http://core", owner_epoch: 1, generation: 1, mode: "nodes", resources: { allocations: 1, running: 1, pending: 0 }, idle_seconds: 300, suspension: null, reset: { clear: "auto", requested_at: "2026-09-27T10:00:00Z", deadline_at: "2026-09-27T11:00:00Z", forced_at: null, remaining: { busy: 1, idle: 0, cleanup: 0, on_offline_nodes: 0, offline_nodes: [] } } }; afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); }); diff --git a/apps/web/src/features/fleet/use-sandbox-fleet.test.tsx b/apps/web/src/features/fleet/use-sandbox-fleet.test.tsx index 49a8ba840..b47344438 100644 --- a/apps/web/src/features/fleet/use-sandbox-fleet.test.tsx +++ b/apps/web/src/features/fleet/use-sandbox-fleet.test.tsx @@ -10,7 +10,7 @@ import { fleetQuery, type FleetSnapshot } from "./fleet-queries"; import { FleetReadNotice } from "./FleetReadNotice"; import { fleetSnapshot, useSandboxFleet } from "./use-sandbox-fleet"; -const configured: SandboxDeployment = { credential_configured: false, configuration: {}, metadata: {}, rollout: { state: "settled", previous_generation_sandboxes: 0, nodes: { ready: 1, preparing: 0, failed: 0, unknown: 0 } }, installation_id: "i", provider: "docker", core_url: "http://core", reset: null, owner_epoch: 1, generation: 1, mode: "nodes", resources: { allocations: 1, running: 1, pending: 0 }, suspension: null }; +const configured: SandboxDeployment = { credential_configured: false, configuration: {}, metadata: {}, rollout: { state: "settled", previous_generation_sandboxes: 0, nodes: { ready: 1, preparing: 0, failed: 0, unknown: 0 } }, installation_id: "i", provider: "microsandbox", core_url: "http://core", reset: null, owner_epoch: 1, generation: 1, mode: "nodes", resources: { allocations: 1, running: 1, pending: 0 }, idle_seconds: 300, suspension: null }; function Probe() { const { state, deployment } = useSandboxFleet(); diff --git a/apps/web/src/features/overview/getting-started.test.ts b/apps/web/src/features/overview/getting-started.test.ts index aaffd5da0..f5ebe2a1b 100644 --- a/apps/web/src/features/overview/getting-started.test.ts +++ b/apps/web/src/features/overview/getting-started.test.ts @@ -6,8 +6,8 @@ import { checklistStorageKey, checklistView, gettingStartedSteps, nextStepAfterN import { node, project } from "./test-fixtures"; const deployment = (overrides: Partial = {}): SandboxDeployment => ({ credential_configured: false, configuration: {}, metadata: {}, - rollout: { state: "settled", previous_generation_sandboxes: 0, nodes: { ready: 1, preparing: 0, failed: 0, unknown: 0 } }, installation_id: "i", provider: "docker", core_url: "http://core", reset: null, owner_epoch: 1, generation: 1, mode: "nodes", - resources: { allocations: 0, running: 0, pending: 0 }, suspension: null, ...overrides, + rollout: { state: "settled", previous_generation_sandboxes: 0, nodes: { ready: 1, preparing: 0, failed: 0, unknown: 0 } }, installation_id: "i", provider: "microsandbox", core_url: "http://core", reset: null, owner_epoch: 1, generation: 1, mode: "nodes", + resources: { allocations: 0, running: 0, pending: 0 }, idle_seconds: 300, suspension: null, ...overrides, }); const fleet = (value: SandboxDeployment, nodes = [node("n1")]): FleetState => ({ status: "ready", snapshot: { deployment: value, nodes, allocations: [], loadedAt: 0 }, targetGeneration: value.generation, refreshing: false, error: null }); const sandboxes = (state: FleetState) => gettingStartedSteps({ sandboxReset: false, fleet: state, localOnly: false, projects: [], sessions: 0, harnesses: [] }).sandboxes; @@ -27,7 +27,7 @@ describe("Getting started steps", () => { }); it("does not report ready during reset or an unreadable deployment, even with ready nodes", () => { - for (const backend of ["docker", "e2b"] as const) { + for (const backend of ["microsandbox", "e2b"] as const) { const input = { fleet: fleet(deployment({ provider: backend })), localOnly: false, projects: [project("p")], sessions: 1, harnesses: [harness("codex", { default: true, model_configuration: { ...provider, harness: "codex" } })] }; for (const sandboxReset of [true, "failed", undefined] as const) { @@ -53,7 +53,7 @@ describe("Getting started steps", () => { } }); it("keeps local-only installations to do even with a ready node or cloud deployment", () => { - for (const provider of ["docker", "e2b"] as const) { + for (const provider of ["microsandbox", "e2b"] as const) { const steps = gettingStartedSteps({ sandboxReset: false, fleet: fleet(deployment({ provider, mode: provider === "e2b" ? "direct" : "nodes" })), projects: [], sessions: 1, harnesses: [], localOnly: true }); expect(steps.sandboxes).toMatchObject({ state: "todo", action: "nodes", cloud: provider === "e2b" }); } diff --git a/apps/web/src/features/overview/test-fixtures.ts b/apps/web/src/features/overview/test-fixtures.ts index 98229483c..bc46a793b 100644 --- a/apps/web/src/features/overview/test-fixtures.ts +++ b/apps/web/src/features/overview/test-fixtures.ts @@ -35,7 +35,7 @@ export function session(id: string, overrides: Partial = {}): Agen export function node(id: string, overrides: Partial = {}): SandboxNode { return { - id, name: id, provider: "docker", online: true, provider_ready: true, + id, name: id, provider: "microsandbox", online: true, provider_ready: true, rollout: { state: overrides.online === false ? "unknown" : "ready", ready_generation: 1 }, cpu_count: 8, available_memory_bytes: 1024, available_disk_bytes: 2048, running: 1, snapshots: 0, last_seen_at: "2026-09-24T00:00:00Z", @@ -48,7 +48,7 @@ export function node(id: string, overrides: Partial = {}): SandboxN export function hostedObservation(sessionId: string, projectId: string, overrides: Partial = {}): OwnedRuntimeObservation { return { id: sessionId, object: "agent.runtime_observation", session_id: sessionId, resolved_at: 1_000, - environment_id: `env_${sessionId}`, mode: "openai_hosted", provider_type: "docker", + environment_id: `env_${sessionId}`, mode: "openai_hosted", provider_type: "microsandbox", instance: { kind: "managed_allocation", allocation_id: `alloc_${sessionId}`, device_id: null, connection_generation: null }, lifecycle_state: "active", status: "observed", reason: null, allocation_created_at: 100, observed_at: 1_000, started_at: 400, memory: { usage_bytes: 100, limit_bytes: 400 }, diff --git a/apps/web/src/features/sandbox/NetworkSettings.test.tsx b/apps/web/src/features/sandbox/NetworkSettings.test.tsx new file mode 100644 index 000000000..c71e392b8 --- /dev/null +++ b/apps/web/src/features/sandbox/NetworkSettings.test.tsx @@ -0,0 +1,30 @@ +import type { SandboxDeployment } from "@oac/agents-client"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { NetworkForm } from "./NetworkSettings"; +import { domainIssues, parseDomains } from "./network-policy"; + +const deployment = (provider: "microsandbox" | "e2b") => ({ provider, specification: { resources: { cpus: 2, memory_mib: 4096 }, network: { public: true, domains: ["gitlab.example.com"] } } }) as SandboxDeployment; + +describe("network policy", () => { + it("validates domains with the generated rule", () => { + expect(domainIssues(parseDomains("gitlab.example.com\n\n a.b-c.example \nGit.Example.com\n*.corp.example"))).toEqual([]); + expect(domainIssues(["a.*.example.com", "*.com", "-x.com", "a.com", "a.com", "a".repeat(254)]).map((issue) => issue.problem)).toEqual(["invalid", "invalid", "invalid", "duplicate", "too_long"]); + expect(domainIssues(Array.from({ length: 101 }, (_, index) => `h${index}.example.com`))).toEqual([{ problem: "too_many" }]); + }); + + it("enables both controls where the provider supports them", () => { + const html = renderToStaticMarkup( true} />); + expect(html).toContain("Allow public internet"); + expect(html).toContain("gitlab.example.com"); + expect(html).not.toMatch(/]*disabled/); + expect(html).not.toMatch(/]*disabled/); + }); + + it("disables the domain list where the provider cannot reach a private network", () => { + const html = renderToStaticMarkup( true} />); + expect(html).toMatch(/]*disabled/); + expect(html).not.toMatch(/]*disabled/); + expect(html).toContain("cannot reach your private network"); + }); +}); diff --git a/apps/web/src/features/sandbox/NetworkSettings.tsx b/apps/web/src/features/sandbox/NetworkSettings.tsx new file mode 100644 index 000000000..91a31e0cc --- /dev/null +++ b/apps/web/src/features/sandbox/NetworkSettings.tsx @@ -0,0 +1,66 @@ +import { useState } from "react"; +import type { SandboxDeployment, SandboxSpecification } from "@oac/agents-client"; +import { useTranslation } from "react-i18next"; +import { HelpTip, Section } from "../../components/console-ui"; +import { useToast } from "../../components/Toast"; +import { sandboxProviderLabel } from "../../lib/sandbox-labels"; +import { domainIssues, maxDomains, networkSupport, parseDomains, type DomainIssue } from "./network-policy"; + +type Network = SandboxSpecification["network"]; + +/** Settings edits the deployment's network cap; it applies to new sandboxes only. */ +export function NetworkSettings({ deployment, disabled, onSave }: { deployment: SandboxDeployment; disabled: boolean; onSave: (network: Network) => Promise }) { + const { t } = useTranslation("sandbox"); + const toast = useToast(); + async function save(network: Network) { + const saved = await onSave(network); + if (saved) toast.show(t("New sandboxes will run with this policy")); + return saved; + } + return ; +} + +export function NetworkForm({ deployment, disabled, onSave }: { deployment: SandboxDeployment; disabled: boolean; onSave: (network: Network) => Promise }) { + const { t, i18n } = useTranslation("sandbox"); + const locale = i18n.resolvedLanguage?.startsWith("zh") ? "zh-CN" : "en"; + const current = deployment.specification?.network; + const [publicAccess, setPublicAccess] = useState(null); + const [text, setText] = useState(null); + if (!current || !deployment.provider) return null; + const support = networkSupport(deployment.provider); + const provider = sandboxProviderLabel(deployment.provider, locale); + const allowPublic = publicAccess ?? current.public; + const domains = text === null ? current.domains : parseDomains(text); + const issues = domainIssues(domains); + const changed = allowPublic !== current.public || domains.join("\n") !== current.domains.join("\n"); + const message = (issue: DomainIssue) => { + switch (issue.problem) { + case "too_many": return t("Add at most {{count}} domains.", { count: maxDomains }); + case "duplicate": return t("{{domain}} is listed twice.", { domain: issue.domain }); + case "too_long": return t("{{domain}} is too long.", { domain: issue.domain }); + default: return t("{{domain}} is not a valid host name.", { domain: issue.domain }); + } + }; + return
0}>{t("Save")}}> +
{ + event.preventDefault(); + if (disabled || !changed || issues.length > 0) return; + if (await onSave({ public: allowPublic, domains })) { setPublicAccess(null); setText(null); } + }}> +
+
{support.restrict ? t("When off, sandboxes reach only the domains listed below.") : t("{{provider}} cannot restrict outbound traffic, so sandboxes always reach the public internet.", { provider })}
+
+ setPublicAccess(event.target.checked)} /> +
+
+
+
{support.private_domains ? t("One host name per line, such as gitlab.example.com, up to {{count}}. Sandboxes can reach these names, including names on your private network. *.example.com allows its subdomains, not example.com itself.", { count: maxDomains }) : t("{{provider}} sandboxes run in the provider's cloud and cannot reach your private network.", { provider })}
+
+