Compare commits

..
Author SHA1 Message Date
codewhale-agent[bot] 624ef93f17 chore(catalog): refresh the Models.dev offline seed
Generated by .github/workflows/catalog-refresh.yml from models.dev. No LLM wrote these rows.
2026-11-10 22:14:08 +00:00
781 changed files with 11807 additions and 58318 deletions

No files matched your search

-6
View File
@@ -65,12 +65,6 @@ crates/engine/extension-host/dist/** text eol=lf
crates/engine/tests/fixtures/extension_host/** text eol=lf
crates/engine/extension-host/src/dsh/dsh-message-compat.js text eol=lf
# DeepSeek Harness creator pins are compared byte for byte against recorded
# SHA-256 values (UPSTREAM.json) and embedded with include_bytes!(); a CRLF
# Windows checkout must not rewrite any of them.
crates/skills/assets/dsh-creator/** text eol=lf
crates/engine/extension-host/src/dsh/upstream/creator/** text eol=lf
# Rustfmt writes LF; keep Rust sources stable across Windows/Linux/macOS.
*.rs text eol=lf
+1 -6
View File
@@ -14,8 +14,7 @@ name: Main landing gate
# This job is deliberately narrow. It runs `scripts/preflight.sh --check`,
# which is the checked-in local preflight for exactly the class of breakage that
# reaches `main` unnoticed: rustfmt, the CHANGELOG slice, README locale stamps,
# the dead-code and blocking-calls budgets, generated-asset drift (including
# the website's generated facts, agent docs and feature registry), and the
# the dead-code and blocking-calls budgets, generated-asset drift, and the
# feature receipts. Measured at 45 s on a warm Linux runner.
#
# Since 2026-11-08 (founder) the `full-ci` job also dispatches `ci.yml` on every
@@ -51,10 +50,6 @@ jobs:
toolchain: stable
components: rustfmt
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 22
- name: Preflight
env:
BEFORE_SHA: ${{ github.event.before }}
-4
View File
@@ -612,7 +612,6 @@ jobs:
set -euo pipefail
node web/scripts/sync-latest-release.mjs
node web/scripts/derive-facts.mjs
node web/scripts/derive-release-docs.mjs
- name: Prove the record passes the web fact gates
env:
GITHUB_TOKEN: ${{ github.token }}
@@ -621,7 +620,6 @@ jobs:
node web/scripts/sync-latest-release.mjs --check
node web/scripts/check-cloud-facts.mjs
node web/scripts/check-facts.mjs
node web/scripts/check-release-docs.mjs
- name: Propose the record to the default branch
env:
TAG: ${{ needs.resolve.outputs.tag }}
@@ -635,8 +633,6 @@ jobs:
docs/cloud-facts/stable.json
web/lib/facts.generated.ts
web/data/agent-docs.generated.json
web/data/agent-docs.release.json
web/data/agent-docs.release-index.json
web/data/features.generated.json
)
if git diff --quiet -- "${paths[@]}"; then
-319
View File
@@ -1,319 +0,0 @@
name: Web maintainer
on:
schedule:
- cron: '43 6 * * *'
workflow_dispatch:
inputs:
lane:
description: Which lane to run
required: true
default: all
type: choice
options:
- all
- derived
- copy-freshness
- link-health
- docs-drift
permissions: {}
concurrency:
group: web-maintainer
cancel-in-progress: false
env:
WEB_MAINTAINER_CLI_VERSION: v0.10.2
jobs:
plan:
name: Plan
if: github.repository == 'codewhale-hq/Codewhale' && github.ref == 'refs/heads/main' && vars.WEB_MAINTAINER_ENABLED == 'true'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions: {}
outputs:
lanes: ${{ steps.plan.outputs.lanes }}
derived: ${{ steps.plan.outputs.derived }}
steps:
- id: plan
env:
INPUT_LANE: ${{ inputs.lane || 'all' }}
run: |
derived=false
lanes='[]'
case "$INPUT_LANE" in
all) derived=true; lanes='["copy-freshness","link-health","docs-drift"]' ;;
derived) derived=true ;;
copy-freshness|link-health|docs-drift) lanes="[\"${INPUT_LANE}\"]" ;;
*) echo "::error::unknown lane"; exit 1 ;;
esac
echo "derived=${derived}" >> "$GITHUB_OUTPUT"
echo "lanes=${lanes}" >> "$GITHUB_OUTPUT"
echo "Web maintainer plan: derived=${derived} lanes=${lanes}" >> "$GITHUB_STEP_SUMMARY"
derived:
name: Derived files
needs: plan
if: needs.plan.result == 'success' && needs.plan.outputs.derived == 'true' && vars.WEB_MAINTAINER_ENABLED == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
ref: main
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 22
- name: Install web dependencies
working-directory: web
run: npm ci --no-audit --no-fund
- name: Regenerate derived files
working-directory: web
env:
GH_TOKEN: ${{ github.token }}
run: |
node scripts/sync-latest-release.mjs
node scripts/derive-facts.mjs
node scripts/derive-changelog.mjs
node scripts/derive-install.mjs
node scripts/render-terminal-capture.mjs
- name: Check what changed
id: drift
run: |
mkdir -p "$RUNNER_TEMP/out"
if [ -n "$(git ls-files --others --exclude-standard)" ]; then
echo "::error::regeneration produced untracked files"
git ls-files --others --exclude-standard
exit 1
fi
git diff --name-status | node web/maintainer/check-allowlist.mjs web/maintainer/derived.txt derived
if [ -n "$(git diff --summary)" ]; then
echo "::error::regeneration created, deleted or changed modes"
exit 1
fi
git diff --binary > "$RUNNER_TEMP/out/change.patch"
if [ -s "$RUNNER_TEMP/out/change.patch" ]; then
echo "drift=true" >> "$GITHUB_OUTPUT"
git diff --stat >> "$GITHUB_STEP_SUMMARY"
else
echo "drift=false" >> "$GITHUB_OUTPUT"
echo "Derived files are current." >> "$GITHUB_STEP_SUMMARY"
fi
- name: Run the web checks on the regenerated tree
if: steps.drift.outputs.drift == 'true'
working-directory: web
run: |
npm run check
npx vitest run
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
if: steps.drift.outputs.drift == 'true'
with:
name: web-maintainer-derived
path: ${{ runner.temp }}/out/change.patch
retention-days: 3
if-no-files-found: error
lane:
name: Lane ${{ matrix.lane }}
needs: plan
if: needs.plan.result == 'success' && needs.plan.outputs.lanes != '[]' && vars.WEB_MAINTAINER_ENABLED == 'true'
runs-on: ubuntu-latest
timeout-minutes: 45
permissions:
contents: read
strategy:
fail-fast: false
max-parallel: 3
matrix:
lane: ${{ fromJSON(needs.plan.outputs.lanes) }}
env:
LANE: ${{ matrix.lane }}
steps:
- name: Require the DeepSeek key
env:
KEY: ${{ secrets.WEB_MAINTAINER_DEEPSEEK_API_KEY }}
run: |
if [ -z "$KEY" ]; then
echo "::error::WEB_MAINTAINER_DEEPSEEK_API_KEY is not set. Create a dedicated DeepSeek key with a provider-side monthly cap and add it as that repository secret, or unset WEB_MAINTAINER_ENABLED. See web/maintainer/README.md."
exit 1
fi
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
ref: main
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 22
- name: Prove the command sandbox works or stop
run: |
sudo apt-get install -y --no-install-recommends bubblewrap util-linux >/dev/null
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 >/dev/null || true
probe="$GITHUB_WORKSPACE/.sandbox-probe"
rm -f "$probe" /usr/local/sandbox-probe
if ! timeout 10 bash -c 'exec 3<>/dev/tcp/api.deepseek.com/443'; then
echo "::error::the runner cannot reach api.deepseek.com, so the network denial cannot be proven."
exit 1
fi
if ! /usr/bin/bwrap --unshare-all --ro-bind / / --dev /dev --proc /proc --tmpfs /tmp \
--bind "$GITHUB_WORKSPACE" "$GITHUB_WORKSPACE" --chdir "$GITHUB_WORKSPACE" -- \
bash -c 'touch .sandbox-probe && ! touch /usr/local/sandbox-probe 2>/dev/null && ! timeout 10 bash -c "exec 3<>/dev/tcp/api.deepseek.com/443" 2>/dev/null'; then
echo "::error::bubblewrap did not confine a child on this runner (writes outside the workspace or outbound network were not denied). Refusing to give a model a shell."
exit 1
fi
if [ ! -e "$probe" ] || [ -e /usr/local/sandbox-probe ]; then
echo "::error::sandbox probe left unexpected state. Refusing to give a model a shell."
exit 1
fi
rm -f "$probe"
echo "Sandbox probe passed: workspace-only writes, no outbound network." >> "$GITHUB_STEP_SUMMARY"
- name: Stage trusted tooling and the pinned CLI
run: |
mkdir -p "$RUNNER_TEMP/trusted" "$RUNNER_TEMP/home"
cp web/maintainer/allowlist.txt web/maintainer/check-allowlist.mjs "$RUNNER_TEMP/trusted/"
cp "web/maintainer/lanes/${LANE}.md" "$RUNNER_TEMP/trusted/prompt.md"
CODEWHALE_VERSION="$WEB_MAINTAINER_CLI_VERSION" CODEWHALE_INSTALL_DIR="$RUNNER_TEMP/bin" sh web/public/install.sh
"$RUNNER_TEMP/bin/codewhale" --version
- name: Probe outbound links
if: matrix.lane == 'link-health'
run: node web/maintainer/link-report.mjs "$GITHUB_WORKSPACE/.git/maintainer-input/link-report.json"
- name: Record the git state the model must not change
run: |
git config --local --list | sort > "$RUNNER_TEMP/git-config.before"
find .git/hooks -type f ! -name '*.sample' > "$RUNNER_TEMP/hooks.before"
test ! -s "$RUNNER_TEMP/hooks.before"
- name: Run the lane on DeepSeek
timeout-minutes: 25
env:
WEB_MAINTAINER_DEEPSEEK_API_KEY: ${{ secrets.WEB_MAINTAINER_DEEPSEEK_API_KEY }}
run: |
env -i \
PATH="$PATH" \
HOME="$RUNNER_TEMP/home" \
CODEWHALE_HOME="$RUNNER_TEMP/home/.codewhale" \
CODEWHALE_SECRET_BACKEND=file \
CODEWHALE_MEMORY=false \
CODEWHALE_TELEMETRY=false \
DEEPSEEK_API_KEY="$WEB_MAINTAINER_DEEPSEEK_API_KEY" \
"$RUNNER_TEMP/bin/codewhale" \
--no-project-config \
--skip-onboarding \
--workspace "$GITHUB_WORKSPACE" \
exec \
--provider deepseek \
--model deepseek-flash \
--reasoning-effort low \
--auto \
--sandbox workspace-write \
--max-turns 40 \
--output-format stream-json \
-- "$(cat "$RUNNER_TEMP/trusted/prompt.md")" \
> "$RUNNER_TEMP/exec.jsonl"
echo "Model run finished: $(wc -l < "$RUNNER_TEMP/exec.jsonl") stream events." >> "$GITHUB_STEP_SUMMARY"
- name: Enforce the path allowlist
id: scope
run: |
if git status --porcelain --untracked-files=all --ignored | grep -qv '^ M '; then
echo "::error::the lane left untracked, ignored, staged or non-edit entries"
git status --porcelain --untracked-files=all --ignored | grep -v '^ M '
exit 1
fi
git config --local --list | sort | diff - "$RUNNER_TEMP/git-config.before" || { echo "::error::the lane changed .git/config"; exit 1; }
find .git/hooks -type f ! -name '*.sample' | diff - "$RUNNER_TEMP/hooks.before" || { echo "::error::the lane added git hooks"; exit 1; }
git diff --name-status | node "$RUNNER_TEMP/trusted/check-allowlist.mjs" "$RUNNER_TEMP/trusted/allowlist.txt" "$LANE"
if [ -n "$(git diff --summary)" ]; then
echo "::error::the lane created, deleted or changed modes"
exit 1
fi
mkdir -p "$RUNNER_TEMP/out"
git diff --binary > "$RUNNER_TEMP/out/change.patch"
if [ ! -s "$RUNNER_TEMP/out/change.patch" ]; then
echo "changed=false" >> "$GITHUB_OUTPUT"
echo "Lane ${LANE}: no change proposed." >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
if [ "$(wc -c < "$RUNNER_TEMP/out/change.patch")" -gt 262144 ]; then
echo "::error::patch exceeds 256 KiB"
exit 1
fi
echo "changed=true" >> "$GITHUB_OUTPUT"
{ echo "Lane ${LANE} proposes:"; echo '```text'; git diff --stat; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
- name: Fresh checkout for verification
if: steps.scope.outputs.changed == 'true'
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
ref: main
path: verify
persist-credentials: false
- name: Run the web checks on the proposal in a clean tree without secrets
if: steps.scope.outputs.changed == 'true'
env:
PATCH: ${{ runner.temp }}/out/change.patch
run: |
cd verify
git apply --index --whitespace=nowarn "$PATCH"
cd web
npm ci --no-audit --no-fund
npm run check
npx vitest run
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
if: steps.scope.outputs.changed == 'true'
with:
name: web-maintainer-${{ matrix.lane }}
path: ${{ runner.temp }}/out/change.patch
retention-days: 3
if-no-files-found: error
publish:
name: Open pull requests
needs: [plan, derived, lane]
if: always() && needs.plan.result == 'success' && vars.WEB_MAINTAINER_ENABLED == 'true'
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
continue-on-error: true
with:
pattern: web-maintainer-*
path: ${{ runner.temp }}/patches
- name: Look for proposed patches
id: patches
run: |
if [ -n "$(find "$RUNNER_TEMP/patches" -name change.patch -size +0c 2>/dev/null)" ]; then
echo "found=true" >> "$GITHUB_OUTPUT"
else
echo "found=false" >> "$GITHUB_OUTPUT"
echo "No lane proposed a change; no pull request opened." >> "$GITHUB_STEP_SUMMARY"
fi
- if: steps.patches.outputs.found == 'true'
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3
id: app-token
with:
app-id: ${{ vars.CODEWHALE_APP_ID }}
private-key: ${{ secrets.CODEWHALE_APP_PRIVATE_KEY }}
permission-contents: write
permission-pull-requests: write
- if: steps.patches.outputs.found == 'true'
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
ref: main
fetch-depth: 0
token: ${{ steps.app-token.outputs.token }}
persist-credentials: false
- name: Open or update one pull request per lane
if: steps.patches.outputs.found == 'true'
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
APP_ID: ${{ vars.CODEWHALE_APP_ID }}
ARTIFACTS_DIR: ${{ runner.temp }}/patches
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
mkdir -p "$RUNNER_TEMP/trusted"
cp web/maintainer/allowlist.txt web/maintainer/derived.txt web/maintainer/check-allowlist.mjs web/maintainer/publish-prs.sh "$RUNNER_TEMP/trusted/"
TRUSTED_DIR="$RUNNER_TEMP/trusted" bash "$RUNNER_TEMP/trusted/publish-prs.sh"
+19 -85
View File
@@ -7,104 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
- **Website Plugins page:** The website's Plugins page now describes what the released version does, and a labelled section says what 0.10.3 adds: one Plugins place, Standard and Creator mode, and the Permissions control.
- **Plugin docs and plugin-creator:** Docs now say everything you add is a plugin. The bundled plugin-creator skill no longer tells an agent never to trust or enable a plugin (in Full Access it may, for one it wrote and installed from its project), points code and screen plugins at cordis-plugin-development, and an untouched copy from 0.10.2 now upgrades. The Chinese extension and Runtime API docs now say editor ACP sessions get plugin tools and configured MCP servers.
- **Model thinking:** New installs show model thinking by default: it streams live in the transcript and collapses under a "Thought for …" header when the answer starts. Existing installs keep their saved setting; turn it on under Model reasoning in chat in /config.
- **Footer clock:** The footer clock and phase now say "thinking", matching the transcript.
- **Paused stream:** A paused stream now shows the thinking it has already received instead of waiting for the next token.
- **Sign-in notice:** The "Account not loaded" notice now appears once per sign-in in the footer, and Esc dismisses it; it no longer lands in the transcript.
- **Usage reporting:** Installers now run their closing diagnostic with usage reporting and update checks off and print how to turn usage reporting off. `codewhale doctor` now says a saved opt-out comes from the config file, not the environment, and help and English notices call the feature "usage reporting".
- **Long tool names:** Tools whose encoded name is longer than the route's limit are now left out with a visible warning instead of failing every request with a 400. The limit is 64 characters on OpenAI and on other OpenAI-compatible providers that document no larger limit, and 128 on Anthropic-style routes, DeepSeek, Ollama, Ollama Cloud, vLLM, SGLang and custom routes. Forcing such a tool gives an error that names the tool and the limit, and a session that already called one on a route with a documented limit (Anthropic, OpenAI, Codex, DeepSeek) is refused with a message saying to switch route or start a new session. A forced tool_choice in any chat form now names the encoded tool, and a tool whose real name looks like an encoded escape can no longer be mistaken for another tool.
- **Start after a hard kill:** The Engine now also starts after a hard kill when its home was spelled through a symbolic link (for example under /tmp on macOS) or, on macOS and Windows, in a different letter case: a dead owner's record for the deleted data directory is discarded instead of refusing every start.
- **Context window labels:** the model picker and fleet capability badges now show `1.5M` and `2.1M` for 1,500,000- and 2,100,000-token windows instead of `1.50M` and `2.10M`. Thanks [@Aboysky](https://github.com/Aboysky) (PR 7295).
- **REPL output limit:** REPL output is now cut to its byte limit, so Chinese, Japanese, Korean or emoji output no longer comes back up to three times longer than the limit, and the cut never splits a character. Thanks [@Aboysky](https://github.com/Aboysky) (PR 7296).
- **Git status with renamed files:** the Git and Changes views no longer fail with "git status failed" or show a phantom row when a file is renamed on the worktree side (for example a moved file marked with `git add -N`), including when the original name starts with non-ASCII text such as Chinese. Thanks [@luochen211](https://github.com/luochen211) (PR 7310).
- **Skill install and import:** `/skill install` now works out an archive's wrapper directory from every entry instead of the first one, so a GitHub repository laid out as `<name>/SKILL.md` installs instead of failing with "missing SKILL.md in archive", a repository-root `SKILL.md` is chosen ahead of a nested `skills/<name>/SKILL.md`, and a flat tarball that lists `scripts/run.sh` before `SKILL.md` no longer installs without its `SKILL.md`. Importing an external skill that contains dotfiles such as `.DS_Store`, `.gitignore` or `.config/` no longer fails with "imported content digest mismatch"; the dotfiles are copied, and the source's own `.trusted` and `.installed-from` are still left behind. Thanks [@luochen211](https://github.com/luochen211) (PR 7311).
- **Workflow authoring:** a declarative Workflow or structured `workflow` plan whose goal or prompt mentions words such as "async", "import" or "open(" is no longer rejected as an unsupported construct. Fleet TOML values written as 'single-quoted' strings, or with escapes such as `\"`, are now read without their quotes. Workflow scripts can no longer reach the internal `__workflow_slot_dropped` binding, which had let a script mark a clean run as Degraded. Thanks [@luochen211](https://github.com/luochen211) (PR 7312).
- **Tool output escape stripping:** tool output no longer shows a stray character after a character-set escape such as the `ESC ( B` that `tput sgr0` prints, and a stray `ESC [` no longer hides the Chinese, Japanese or Korean text after it. Coloured tool output now keeps only well-formed colour sequences. Thanks [@luochen211](https://github.com/luochen211) (PR 7313).
- **Patches with short hunk headers:** `apply_patch` now reads every line of a hunk when the `@@` header counts are too small. Lines past twice the header counts used to be dropped without an error, so a long hunk, or a new file written under `@@ -0,0 +1 @@`, could lose its later lines. A header with an enormous count no longer crashes the parser, and stray text after such a hunk now fails as a context mismatch. Thanks [@luochen211](https://github.com/luochen211) (PR 7287).
- **Script tools with `env -S` shebangs:** a script tool whose first line is `#!/usr/bin/env -S python3 -u` now starts `python3 -u` instead of failing to launch a program named `-S`. Other `env` options, the attached `-Sprogram` form and `env -S` quoting are still not interpreted. Thanks [@luochen211](https://github.com/luochen211) (PR 7288).
- **Timeline summaries:** a thread or task timeline summary that already fits its length limit is now shown in full, instead of having its last characters replaced by `...`. Thanks [@luochen211](https://github.com/luochen211) (PR 7289).
- **RLM context names:** `rlm_open` without a `name` now keeps non-ASCII letters and digits from the file name, so `docs/报告.txt` and `docs/总结.txt` open as `报告_txt` and `总结_txt` instead of both becoming `txt` and the second open failing with "already exists". Names derived from ASCII file names are unchanged. Thanks [@luochen211](https://github.com/luochen211) (PR 7290).
- **Web fetch and `web.run` entities:** text a page escaped on purpose now stays escaped. A page that writes `&amp;lt;br&amp;gt;` to show a literal `&lt;br&gt;` now reads as `&lt;br&gt;` in fetched text, `web.run` lines, page titles and meta descriptions; before, it was decoded twice into `<br>`. Both tools now use the search scraper's single-pass decoder, so numeric references such as `&#8212;` and names such as `&mdash;` are decoded there too. Thanks [@luochen211](https://github.com/luochen211) (PR 7291).
- **Simplified Chinese punctuation and /status:** in the zh-Hans interface, the `/router` setup and test screens, label prompts and usage lines now use full-width punctuation (`:;,()`) instead of ASCII marks next to Chinese text, and `/status` values start in one column under Chinese labels instead of starting at a different column for each label. Thanks [@luochen211](https://github.com/luochen211) (PR 7314).
- **Git tool on older git:** the Git tool's `review_scope` action no longer passes `--no-lazy-fetch`, which git older than 2.44 rejects, so it failed on every call there. It sets `GIT_NO_LAZY_FETCH=1` instead, which keeps the same protection on newer git and is ignored by older git.
- **Plugins from a shell:** `codewhale plugins trust <name>` prints the same capability review as `/plugin trust` with its bundle review token and, in a terminal, asks once. `--review-token <token> --yes` trusts without a prompt while that token still matches the installed content and capabilities; the token ties trust to the exact content, does not show that anyone read the review, and is not the host-service review token. A `--yes` trust is recorded as the command line and grants no host service. Every command the agent runs (shell, persistent terminal, verifier and test runs, the Python kernel, MCP servers it starts) now carries `CODEWHALE_AGENT_PROJECT` with the session's project, while hooks and configured MCP servers do not; with it, a trust or enable is recorded as the agent's, for that project only, even when a prompt is answered through a terminal, and the agent may trust only a plugin it installed from a folder inside the project. `plugins enable`, `disable` and `revoke` work the same way, each with `--json`, and `plugins status` shows who approved. The agent's shell commands that run them go through the session's approval like any other shell command, so a Full Access agent can trust and enable a plugin it wrote; the mark is a label the agent could remove in Full Access. (CW-7891)
- **Sandbox:** a managed configuration can set `tool_launcher` (Linux) to run every sandboxed tool command as another user, in front of bubblewrap; commands then run inside the sandbox or not at all, masks are computed for that user, `/tmp` is private per command, and `GET /v1/runtime/info` reports `sandbox.kind` and `sandbox.tool_launcher`. Without the key nothing changes. A managed configuration named by `CODEWHALE_MANAGED_CONFIG_PATH` or `managed_config_path` is applied on every load, and one that is missing or cannot be read stops the load instead of loading with no managed layer; a blank `CODEWHALE_MANAGED_CONFIG_PATH` is now ignored instead of switching the managed layer off, and a config file's `managed_config_path` can no longer point away from an existing file at the default managed path. Fleet local workers inherit the managed-config variable, and `codewhale serve --mcp` does not expose shell tools when the managed configuration it loads sets `tool_launcher`. A configuration whose provider is declared only by a plugin fails to load under a managed configuration, with an error that says to declare the provider table or pick a built-in provider.
- **Receipts:** a terminal session's receipt (`/receipts`, `codewhale receipts`) now shows the provider's token counts and the same cost report `/cost` prints, saying "unknown" and why when the route's price is not known, never a guess. A Runtime thread's receipt shows token counts only; its cost line follows in a later release. `codewhale metrics` now counts usage saved in terminal sessions instead of reporting none. Sessions saved by 0.10.2 carry only a combined token total.
- **ACP server on the official SDK:** The ACP server (`codewhale serve --acp`) now runs on the official Agent Client Protocol SDK. Its messages follow the official v1 types, and it no longer advertises the non-standard `modelSelection` capability or session `models` field. Session list entries carry `createdAt` and `messageCount` under `_meta.codewhale`, terminal sign-in methods are advertised only to clients that enabled terminal authentication, a notification is never answered, a permission request always carries text, and session list and configuration requests are served while a turn runs, response ids are echoed unchanged for every client (the Zed-only string rewrite is gone), and `initialize` without `protocolVersion` is refused with `-32602`.
- **External agents over ACP:** Codewhale now drives external agents through the official Agent Client Protocol SDK. Request ids on the wire are strings, and an agent's error is treated as a sign-in problem only when it carries the protocol's auth-required code.
- **Creator skills:** Codewhale now ships DeepSeek Harness's four plugin-authoring skills (`cordis-plugin-development`, `editing-cordis-compositions`, `cordis-composition-reference`, `agent-experience`) bundled, unmodified, with their reference and template files and DeepSeek's MIT notice beside each. They stay hidden from the model until Creator mode. A bundled skill can now carry files; `load_skill` prints its base directory and a short Codewhale host-notes block, and a file you edited is never overwritten on upgrade.
- **Conversation modes (Engine):** `GET /v1/modes` lists two built-in modes, `standard` (default) and `creator`, each with `id`, `name`, `description`, `source` and `available` (plus `reason` when not; Creator is listed unavailable, "not ready in this build", until it loads its own tools, and then also when no Node.js or Bun plugin runtime is found). A thread's mode is `agent_preset`, set on `POST /v1/threads` or by `PATCH /v1/threads/{id}` until the thread has a turn, saved on the thread record and the terminal session file and shown in `GET /v1/threads/summary`; records without it load as `standard`. An unknown or unavailable id, a change after the first turn, or a mode together with another vendor's agent is refused with `error.code` `unknown_mode`, `mode_unavailable`, `mode_locked` or `mode_not_supported_with_executor`. Source only: Creator loads nothing extra yet and no menu uses it.
- **Website home page:** the page is reorganized around what a visitor does: a dated OrcaRouter offer strip with a visible referral tag, one proof strip (release, stars, contributors), a models section with the newest first-party models, one capabilities section that includes Computer Use, an "Everything is a plugin" teaser and a community panel whose live GitHub numbers fill in from the browser and hide when unavailable. Unused home copy was removed from all 18 site languages.
- **Website home page, rebuilt around one first screen:** the headline stays "The model can be anyone's. The agent should be yours.", centred, with one plain sentence under it that says what Codewhale is (an open-source coding agent for your terminal, written in Rust, working with any model and able to split a task across several agents), the install command, and one wide picture of a real terminal session that runs off the bottom of the first screen. A row of facts under the picture takes its counts of provider routes and models from the published release, and the facts row lists many agents on one task only while the release has it. The route of where the product is going moves lower and smaller, and the home page names no other coding agents. This replaces the earlier reorganization of the home page, so the community panel whose GitHub numbers filled in from the browser is no longer on it, and the dated OrcaRouter offer strip, English only, with its referral disclosure, stays below the first screen until it ends; the models and contribute pages keep their own content. The new text in the 17 non-English languages is machine-drafted and is labelled as such in the footer; the Arabic page now reads the opening sentence right to left.
- **Website models and plugins:** /models leads with recently added models, three ways to connect (DeepSeek, first-party providers, any OpenAI-compatible endpoint) and a catalog grouped by maker; Ollama and OpenRouter are listed but no longer featured. /plugins leads with "Everything is a plugin" (credited to DeepSeek Harness) and shows MCP connectors from the connection catalog.
- **Model catalog:** Claude Fable 5.2 (`claude-fable-5-2`) and Gemini 4 Carbon (`gemini-4-carbon`) are in the bundled catalog, and a daily catalog-refresh workflow proposes new first-party models from models.dev as a pull request. The workflow has not run in GitHub Actions yet.
- **Gemini 4 output limit:** Gemini 4 Carbon and Gemini 4 Argon now allow 65,536 output tokens per reply, up from 32,768, matching Google's published limit.
- **Anthropic xhigh effort:** Choosing xhigh effort on an Anthropic model that documents it, such as Claude Fable 5.2 or Claude Opus 4.8, now sends xhigh instead of max, so the model uses and bills the level you picked.
- **Public model list:** The public model list gains GPT-6.1 Terra, Kimi K3.1 Pro (and its high-speed variant), MiniMax M3.1 Flash and Mistral Large 4, each marked unreviewed.
- **Model Studio Token Plan:** Token Plan users can now pick `qwen4-max-preview` on both the OpenAI and Anthropic dialects. It was added from the model table Alibaba publishes on its Token Plan pricing page and has not been exercised against the live endpoint. Alibaba publishes no context window, output limit, tool calling or thinking control for it, so Codewhale records image input only and sends it no thinking switch on either dialect. The Coding Plan does not list it.
- **Website brand and app pages:** the header, footer and favicon use the black-and-white Codewhale mark, keeping the colored whale for character moments. New /app and /docs/account pages say plainly that the desktop app is a development build, the browser app is not open yet, and how sign-in works where it exists. The terminal demo was recaptured from the 0.10.3 source.
- **DSH plugin client review:** the DSH importer now reviews a plugin's client (`dsh.client`) files: the review lists every file the client loads with its SHA-256 and which modules the host must provide, and says exactly why a client stays disabled (for example an npm package that is not in the bundle, or a module loaded by a computed specifier). Plugin UI is still not shown; that needs the Engine client bootstrap.
- **`codewhale exec` prompt input:** `codewhale exec "prompt"` no longer hangs when stdin is an open pipe that sends nothing (it continues after 2 s and says so, and a slow producer can be included by piping the prompt as well), and a flag typed after the prompt in full-width or typographic-dash form is rejected like `--auto` instead of being sent to the model as text. Tested on Unix only; no Windows, hosted CI or real-provider run.
- **Website docs:** documentation pages no longer stack a second "Codewhale documentation" header under the site navigation; the line saying which release the docs describe now sits under the breadcrumb.
- **Website languages:** the Roadmap and Contribute pages now show their titles, introductions and actions in all 18 site languages instead of English outside English and Chinese. The translations have had no native review yet.
- **Responses dialect profiles:** Codex, DeepSeek and Concentrate Responses behavior now comes from one checked dialect table instead of per-provider code, a custom `wire = "responses"` provider can set `responses_profile = "standard"` (the default when omitted), and preview shows the profile each Responses request used. A Responses client whose route cannot be resolved now fails when it is created rather than at its first request ([#7261](https://github.com/codewhale-hq/Codewhale/pull/7261)). Thanks [@SamhandsomeLee](https://github.com/SamhandsomeLee).
- **Read-only builtins over the Runtime API:** `POST /v1/threads/{id}/commands/builtin` runs `/system`, `/tokens` or `/cost` against a thread and returns the same answer the terminal prints, including the effective system prompt the engine sends. Any other command name answers 404, a thread whose engine is not loaded or has no live context estimate answers 409, and the route never starts an engine or writes settings ([#7277](https://github.com/codewhale-hq/Codewhale/pull/7277)). Verified by the app-server route tests and terminal-host tests; no editor client uses it yet. Thanks [@gaord](https://github.com/gaord).
- **Automations:** a run missed while Codewhale was closed now waits on reopen for Run now or Skip instead of catching up silently; each automation can choose "If missed: ask" (default), "run once" or "skip". Tested in the engine only; no HTTP route tests, no desktop client yet, and a Mac asleep longer than the grace window counts as closed.
- **Website maintainer:** a scheduled `web-maintainer` workflow proposes website upkeep as pull requests only: regenerated facts, and three DeepSeek lanes (stale version mentions, moved links, docs drift) that may edit only allowlisted copy files and must pass `npm run check` and the web tests. It is off until the repository variable `WEB_MAINTAINER_ENABLED` is set and a capped `WEB_MAINTAINER_DEEPSEEK_API_KEY` secret exists, and it has never run. The Worker's triage, PR-review, stale, duplicate and curate (Today's Dispatch drafting) cron tasks are removed; the digest stays.
- **Website measurement:** the first-party ingest now accepts a closed website funnel schema while preserving existing runtime and browser batches. Reader confirmations remain self-reports, new website data stays first-party, and no deployment or live conversion gain is established by the source change.
- **Website facts:** the website now reads the installed version, asset list and repository numbers from the published release and a dated snapshot instead of the source tree, shows nothing rather than 0 when a live number cannot be read, stamps its facts revision and date together, no longer calls the desktop app native, says when the release was read, and drops the price from its structured data. This is a source change and is not deployed yet.
- **Website surface status:** the status of the terminal, browser, desktop, cloud and accounts surfaces now comes from typed states with copy in every locale, the desktop download appears only for a signed, notarized release with a checksum, the cloud-invitation and plan switches are committed values that default to off, the partner strip expires at render time, and repository numbers show when they were read. This is a source change and is not deployed yet.
- **Website capabilities:** the website now lists a capability as available only when the published release has it, labels features that exist only in source as not yet released, keeps held features (cloud computers beyond invite-only, other vendors' agents over ACP, and plans) hidden behind committed switches that default to off, and prints provider route, catalog model and tool counts as they are at the published release tag instead of on main. This is not deployed yet.
- **Installer uninstall lines:** the installers now print the uninstall command, the update-mode sentence and the shell-profile marker sentence only when the Codewhale they just installed reports an `uninstall` command, and older releases such as a pinned v0.10.2 get the manual removal steps instead of a command that would be sent to the model as a prompt. (CW-8029) The installers reach people through the website, so this is not deployed yet.
- **Installer PATH ending:** when `codewhale` is not on PATH, the installers' last lines are now the copy-paste `export PATH=...; hash -r` command and `codewhale --version`, and when it is on PATH the last line is `Next: codewhale --version`; the Computer Use notice moves above them and shows on macOS only. (CW-8030) The installers reach people through the website, so this is not deployed yet.
- **Installer PATH setup:** when the install directory is not on PATH, the macOS and Linux installers now add Codewhale's marked three-line PATH block to your shell profile, print exactly which file and lines they added and the command that removes them, and skip this with `--no-modify-path` or `CODEWHALE_NO_MODIFY_PATH=1`; the Windows archive installer adds the directory to your user PATH the same way and skips it with `-NoModifyPath`. Release archives carry this from 0.10.3 on, and the Windows installer has not been run yet. (CW-8036) The website serves install.sh, so this reaches people only when the website is next deployed.
- **Website and docs:** installation now leads to a version check and a verifiable first task, article search finds text and commands with section links, and GitHub star links show the fetched count. The hero reuses the generated drone whale, and control/tool references distinguish the unpublished source candidate from v0.10.2; these website changes still await deployment.
- **External agent options:** `GET /v1/agents/external/{id}/options?cwd=` returns the models, modes and options an external agent itself offers for a folder, and which Codewhale actions it will not carry. A saved agent model the agent no longer offers is refused with a stable `choice_not_offered` code instead of being ignored, per-turn settings an agent cannot honor are refused as `unsupported_control`, and each agent turn records the context window and tokens the agent reported, with cost shown as unknown (CW-7879). Probing starts a real agent session in the folder, which the agent may keep in its own history. Mode and config choices are listed but cannot yet be chosen through thread creation. Verified on Linux by unit and local HTTP tests against a fixture agent; no real installed agent, macOS, Windows or hosted CI run.
- **External agent interrupts:** Interrupting a turn while an external agent waits for approval now answers the agent's permission request as cancelled. (CW-7958)
- **External agent quota:** The Runtime API route `GET /v1/agents/external/quota` reports each external agent's quota as unknown with a reason (flag off, consent missing, not implemented). The new `agents.quota.<agent>` and `agents.quota.<agent>.consent` settings, saved through `POST /v1/config`, record the opt-in and consent (at most 32 agent entries). No agent credential is read. (CW-7993)
### Changed
- **Docs for agents match the release:** `/llms-full.txt` and `/docs-markdown/*` now serve the documents as they were at the published release tag, from a committed snapshot that is checked against the published release.
- **Extension host (experimental): trusted plugins ask for review once more.** With `extension_host` turned on, plugins you already trusted are shown for review again after this update, because the capability table they were reviewed against gained the `remote` service. No plugin can use that service yet: none is granted it.
- **Website text for agents:** llms.txt now gives agents the install steps for the released version, the current release and the state of each part of Codewhale, from the same content as the pages. `/docs-markdown/install.md` serves those install steps as a page, and the main-branch documents beside it now say which release they can run ahead of.
- **Website design:** codewhale.net now uses the desktop app's 5.3 light and dark colour roles and Geist / Geist Mono, replacing the warm-paper palette and Shannon Sans; the vendored design copy is synced to 5.3.0 and the whale-road ocean bands are unchanged.
- ACP: editors can start, list, load, prompt and cancel Codewhale sessions and approve or reject tool permissions through the Runtime; prompts with image or audio blocks and relative session directories are now refused instead of ignored, and edit and read tools report the right kind. Sessions an editor drives now run the plugin tools (TypeScript and DSH, when the extension host is on) and the MCP servers configured in Codewhale; their calls show as ACP tool calls and ask through the session's permission setting, and `initialize` reports the state under `agentCapabilities._meta.codewhale`. MCP servers an editor passes in `mcpServers` and configured shell hooks still do not run in ACP sessions. A real-editor journey is not yet proved.
- Extension host: the `sessions` and `systemPrompt` services now come from a reviewed DSH adapter instead of inline shims, and `sessions.flush` refuses an empty checkpoint ticket. Session reads and events and the `agent/pre-step` hook are still not available to plugins. (CW-7959)
- Extension host: DSH service adapters now have one ticketed `dsh/broker` request to the core, each ticket is bound to the plugin, the service and the session, and every service (workspace, llm, network, settings, catalog, terminal and remote) refuses with a typed `not_available` until its broker lands. Nothing new is offered to plugins yet. (CW-8012)
- **Plugin host services and who approved:** a plugin can now be granted a Codewhale host service, and only by a review that shows it. The review names each service and the plugins it is shared with, and every review records who approved it: you, the agent (in Full Access, in Auto-Review, or from a shell command carrying the agent's mark), or the command line with `--yes`; who turned the plugin on is recorded too. Plugins share one process, so a service works only while every loaded plugin of the same kind holds the same grant. A plugin the agent approved is active only in its own project and its code does not run beside the plugins you reviewed until you review it. No service is offered yet, and a plugin reviewed before this release holds no grant until it is reviewed again. Once a plugin has been reviewed or turned on in this release, Codewhale 0.10.2 and earlier cannot read the plugin state file and turn every plugin off when run on the same home folder. (CW-8012)
- Fleet member starts are now durable: replaying an operation key after a timeout or restart returns the original worker, and GET /v1/threads/{id}/members/operations/{key} reports the outcome. A member start now answers with `state` `accepted` (200) or `unknown` (202) instead of `started` or `queued`. Verified by local HTTP tests on Linux; a real Engine restart is simulated, not exercised. (CW-7964)
- Plugin activation now says when a requested service belongs to the Codewhale core and is not exposed to plugins yet. No plugin, provider or installed-app run exercised it; checked by the extension-host tests only.
- Codex App Server v2 contract record (paused, not part of 0.10.3): the selected Codex v2 contract is frozen as a generated manifest in the protocol crate, with typed Rust and TypeScript shapes checked against the pinned Codex schema. It changes no wire behavior and adds no dispatch, so nothing is reachable through it yet.
- **Website copy:** The site's headline is now "The model can be anyone's. The agent should be yours.", with its subhead, belief and labelled product map in every language.
- **Website routes:** Pages that repeated each other now redirect to the one page that does the job, the header and footer list only pages that exist under their current names, the sitemap drops redirected and catalogue pages, and machine-drafted translations say so.
- **Website privacy:** The website no longer counts anything when your browser sends Global Privacy Control or Do Not Track, and the privacy page says exactly what is counted and how it is keyed.
- Plugin UI: the Runtime API now serves reviewed DSH client closures on six seats (customize.plugins.detail, conversation.composer.dock, conversation.chat.node, workpane.panel, sidebar.section, command.row) with coded refusals, drops a plugin's UI grants the moment it is disabled, revoked or uninstalled, and adds a plugin route bridge that refuses until a plugin web server exists. No real DSH package has been served end to end yet, and a client that imports `@deepseek-ai/dsh-client-*` modules is still refused. (CW-7956)
### Fixed
- **Starting after a hard kill:** the Engine now starts when its process was killed and its data directory was then deleted. A socket owner record whose process is dead and whose data directory, the one this start selected, no longer exists is discarded instead of failing every start with "Failed to resolve ... tasks/runtime". A home reached through a symbolic link, such as one under macOS /tmp, is not covered yet.
- The install guide's note for a first message that gets no answer now describes v0.10.2: connect a model with `/provider`, and restart if messages stay saved for later after you connect. It described v0.10.0's key screen. The Chinese guide carries the same correction.
- Project activity on the site now comes from a server-side snapshot with a freshness record, the browser no longer calls GitHub, and count sentences use the right plural form in every language.
- The install page now gives the exact steps for the released version on every platform, including what the installer adds to PATH, how to turn off usage counting, and how to remove it, and the install command no longer gets cut off on phones.
- After choosing "explore offline" on first run, connecting a provider or Custom endpoint with /provider now takes effect immediately; messages are no longer held as "Saved for later" until restart, and a message held while offline returns to the composer.
- The pet browser view opens with a one-time code instead of the long-lived owner token, so the token no longer appears in the URL or the launcher command line. The code lasts 30 seconds and works once; the owner token itself is still stored in the cookie and connection file and is not rotated. Not run in a real browser.
- On Windows with Caps Lock on, Ctrl+E moves to the end of the line again instead of opening the file tree; the file tree now needs an explicit Shift (Ctrl+Shift+E or Cmd+Shift+E), so a terminal that reports an uppercase E with Ctrl but no Shift flag can no longer toggle it. The Caps Lock key event is simulated from the input library source; no native Windows run.
- External agents installed through npm on Windows (`claude.cmd`, `codex.cmd`, ...) are now found instead of the unrunnable shell shim, `GET /v1/agents/external` says whether an agent answered with an unsupported protocol rather than reporting every failure as no answer, and a hung `--version` or handshake probe no longer leaves the agent's child processes running. Verified on macOS and Linux; the Windows code has never been compiled or run, and no agent row is qualified by this change.
- The Runtime API's `POST /v1/git/push` now pushes exactly one branch at one commit (`<commit>:refs/heads/<branch>`, no follow-tags or submodule recursion), so `push.default`, `remote.<name>.push` and `push.followTags` can no longer publish other branches or tags. Clients can bind a push to a named branch and expected HEAD with `branch` + `expect.head` (advertised as `named_push` in `GET /v1/git`); a stale branch or HEAD answers `409 git_state_changed` and pushes nothing. A bare push from a detached HEAD or an unborn branch is now refused, and the desktop app has not yet adopted the named form. Verified on macOS by unit tests against a local bare remote; no real network remote, Linux, Windows or hosted CI run.
- Cancelling or timing out a read-only Git tool (git_status, git_diff, git_commit_plan, git_log, git_show, git_blame, git_merge_tree) now stops the git process and anything it started, instead of leaving it running in the background. Verified on macOS by unit tests; Linux, Windows and hosted CI are not yet run, and the filter-override probe is still not contained.
- TUI: the launch resume confirmation no longer treats Meta+Enter, Meta+Y or Hyper+Enter as "resume"; only a plain Enter/Y or Shift+Y answers it. Verified by the focused unit tests only; not tried in a terminal that sends Meta or Hyper.
- TUI: mentioning a huge directory or a far-away line range (`@file:N-M`) now stops after a bounded scan and says the result is partial instead of claiming end of file. Verified by the focused `file_mention` unit tests; no real 64 MiB file was tried.
- Runtime `patch-undo` now restores a turn's own file changes in the default (Ask) posture without trust mode or Full Access; later edits and changes the turn did not make are still refused with nothing changed, and the `restore_requires_trust` error code is gone ([#6970](https://github.com/codewhale-hq/Codewhale/issues/6970)). Verified by app-server and TUI unit tests on Linux; no Windows `/undo` or process-restart run.
- **Website terminal frames:** The site can render terminal frames captured from the released version, and chooses each frame's caption from where it was captured.
- **Website docs truth:** Documentation pages now describe the released version first and show what exists only in source in a labelled section that switches on when a release carries it.
- **Website Arabic pages:** On Arabic pages, English text that has no translation yet keeps its own direction and language, so punctuation, commands and dates no longer appear reversed.
- A DSH plugin whose package includes a `.gitignore` at its root now installs instead of being refused as a hidden file; nested `.gitignore` files, other hidden files, credential files and links are still refused. (CW-8023)
- `install.bat` in the Windows release archive now passes its arguments to `install.ps1`, so `install.bat -NoModifyPath` declines the user PATH edit like the PowerShell installer does, and the install guide says so. It has not been run on Windows. The batch file reaches people in the next release archive, and the guide sentence when the website is next deployed, because the site serves the guide but not `install.bat`. (CW-8046)
## [0.10.3] - 2026-11-08
@@ -113,12 +37,11 @@ until the matching tag, packages, checksums, and release assets exist.
### Work in progress and known limits
This source candidate is not the final 0.10.3 tag. There is no
`0.10.3-beta.2`: the next release is the full 0.10.3, and its final tag waits
for the full scope list. Codex App Server v2 is paused and is not part of
0.10.3; the legacy JSON-RPC dialect is not retired in this release. The coarse
Engine split and DSH all-33 compatibility stay in 0.10.3, and none of this
work is declared complete here. Items moved to 0.10.4 by name are marked below.
This source candidate is not the final 0.10.3 tag. The 2026-11-08 scope
decision keeps App Server v2, the coarse Engine split and DSH all-33
compatibility in 0.10.3; the final tag waits for that full list. The near-term
`0.10.3-beta.2` is a GitHub prerelease for the Boat image and desktop, not this
tag. Items moved to 0.10.4 by name are marked below.
- **Terminal lifetime (0.10.3 work item):** deleting a conversation now ends the
terminal sessions and background jobs owned by that Runtime thread. The
@@ -661,14 +584,14 @@ work is declared complete here. Items moved to 0.10.4 by name are marked below.
- **Listing installed agent CLIs no longer blocks the runtime.** `GET /v1/agents/external` looks for each binary with `tokio::fs` instead of synchronous file calls on a runtime worker.
- **A failed custom-provider switch leaves the provider you were on.** When saving a custom provider succeeds but switching to it fails (its identity cannot be resolved, or the engine refuses the route), the next request keeps going to the provider the footer shows instead of the half-configured one.
- **A zero page size over stdio still advances.** `thread/loaded/list` on the App Server's stdio transport treats a requested limit of `0` as `1`, so a client that sends `0` reaches the next page. `GET /v1/threads` is unchanged.
- **Anthropic and Messages-compatible routes accept any tool name.** Tool names that Anthropic's pattern rejects, such as `web.run` from a loaded tool group, are encoded on the wire and decoded in replies, as the chat and responses routes already did, including when such a tool is forced through an object-form `tool_choice`. Before, one such name made every request fail with "tools.N.custom.name: String should match pattern", which stopped sub-agents that had loaded it ([#7252](https://github.com/codewhale-hq/Codewhale/issues/7252)). Thanks [@ychu824](https://github.com/ychu824) for the report.
- **Anthropic and Messages-compatible routes accept any tool name.** Tool names that Anthropic's pattern rejects, such as `web.run` from a loaded tool group, are encoded on the wire and decoded in replies, as the chat and responses routes already did. Before, one such name made every request fail with "tools.N.custom.name: String should match pattern", which stopped sub-agents that had loaded it.
- **A large sub-agent fan-out no longer exhausts the usage journal.** The per-session limit of live usage receipts rises from 64 to 256, above the workflow ceiling of 128, so a full fan-out keeps its cost receipts instead of running with cost unknown.
- **A turn that stalls before it starts is now bounded.** The stall watchdog covers the setup before the first model request, so a wedged start is logged, cancelled after 180 seconds with a stated reason, and leaves a stall record instead of waiting silently. A warning names the case where all four blocking-work slots are held. Refs #6184.
- **One unreadable saved session no longer empties the recent-sessions list.** The launch card and ACP `session/list` show the readable sessions and log the failure. Refs #7095.
- **Windows uninstall removes the receipt and update leftovers.** The installer's uninstaller also deletes `.codewhale-install.sha256` and `codewhale.old-*`/`codew.old-*` left by a self-update, so `bin` can be removed. Refs #7091.
- **Windows `/undo` matches recorded file paths regardless of case.** A write recorded under a different drive-letter or directory case, or a `\\?\` prefix, is no longer dropped from the restore plan. Refs #6970.
- **Windows: Fleet and metrics read live files again.** Replaying a Fleet ledger and reading audit or receipt records no longer fail with a sharing violation while their writer is still open; the same regular-file, link and identity checks apply. Plugin enablement now says which snapshot check refused (stage root, content identity or final check) instead of one generic message. Generated protocol and SDK exports keep LF line endings in Windows checkouts.
- **Sessions in one folder no longer leave each other's sub-agents read-only or private:** a second session works beside another one, stale or suspended included, the older sub-agent store upgrades right away, and a store that cannot be opened is retried on the next sub-agent change instead of needing a restart. While another Codewhale session, a suspended one included, is open in a folder the desktop app or `serve` was asked to work in (other than the folder it started in), that Runtime still refuses sub-agents that would edit the folder directly; isolated worktrees are unaffected. A sub-agent store that cannot be opened shows its refusal once instead of repeating cleanup warnings on every sidebar refresh. Restart any session started with Codewhale 0.10.2 or older: once the folder upgrades it can no longer save sub-agent state (Refs #7232).
- **A held coordination lock no longer makes a new session read-only.** When another session owns the delegated-agent store, the new session starts on private state and says so, instead of refusing every sub-agent with “Failed to clean up sub-agents”.
- **A dev server can outlive the turn in an interactive session.** `persist:true` now works in the TUI and desktop when the thread has Full Access; restricted postures and Fleet/sub-agents still refuse it.
- **`codewhale exec --add-dir <path>`** (repeatable) and `addDirs` on `POST /v1/threads` let the file tools read and write a sibling directory, a second checkout or a shared scratch root without turning on Full Access.
- **Unsettled usage is persisted in production, not only in tests.** The interactive sink now records a legacy usage receipt when a provider response has no settlement, so children and turns stop reporting settlement failure.
@@ -705,6 +628,12 @@ work is declared complete here. Items moved to 0.10.4 by name are marked below.
composer. Real Pinyin input on macOS and Windows is not yet confirmed.
Thanks [@cmdcorp6534](https://github.com/cmdcorp6534) for the report
(Refs #2323).
- **Sub-agents beside an older session:** while a Codewhale 0.10.2 session
still uses a folder's older delegated-agent store, a 0.10.3 session in the
same folder keeps working sub-agents with private state that is not saved,
instead of refusing every sub-agent action. The older session's files are
left untouched, and the store upgrades when a session starts after the older
one exits (Refs #7232).
- **Fleet members:** a replayed member start now matches only within its own
session, so two sessions that reuse an operation key no longer receive each
other's agent.
@@ -733,6 +662,12 @@ work is declared complete here. Items moved to 0.10.4 by name are marked below.
bare self-package exports resolve inside the selected package directory.
Invalid or incompatible ranges and paths outside the reviewed package still
refuse. Real published-plugin activation remains unqualified.
- **Coordination lock diagnostics (#7232):** stale lock-file contents no longer
identify an owner PID. A refused legacy admission keeps its reason in Work
and shows one notice per cause instead of repeating cleanup warnings on
every sidebar refresh. Legacy migration still requires the actual holder to
exit and the refused owning Runtime to restart; locks and retained state
remain protected.
- **A local proxy that stops mid-session no longer strands the session (#7231):** the model, catalog, search, vision, finance, MCP-registry, profile and remote-control clients watch a loopback proxy port and go direct while it refuses connections, then resume proxying when it returns. Only a definite refusal from every resolved address changes the route; remote proxies, `NO_PROXY` matches, credentials and the existing precedence are unchanged. Set `CODEWHALE_LOCAL_PROXY_FALLBACK=0` to keep the old build-time snapshot.
- **Proxy diagnostic privacy ([#7233](https://github.com/codewhale-hq/codewhale/issues/7233)):** malformed MCP proxy warnings omit configured values; local-proxy log labels mask userinfo and omit URL paths, queries and fragments. Routing is unchanged. All 23 existing proxy tests passed on macOS; runtime log capture and other platforms remain unqualified. Thanks [@SparkofSpike](https://github.com/SparkofSpike) for the report.
- **Fork, undo and retry work after a workspace drift notice (#7234):** the history-boundary walks now treat a whole `<context_update>` envelope as engine-owned, so a session that received one can be cut at every saved turn. A person quoting a notice or a truncated envelope still counts as their own prompt.
@@ -1121,7 +1056,6 @@ work is declared complete here. Items moved to 0.10.4 by name are marked below.
- **[@Statter](https://github.com/Statter)** — reported black-on-black text on terminals that do not report their background ([#7043](https://github.com/codewhale-hq/Codewhale/issues/7043)).
- **[@eugenicum](https://github.com/eugenicum)** — asked for a visible Full Access flag for `serve --acp` ([#6992](https://github.com/codewhale-hq/Codewhale/issues/6992)).
- **[@luestr](https://github.com/luestr)** — reported file and conversation rollback diverging ([#6970](https://github.com/codewhale-hq/Codewhale/issues/6970)), the Linux multiline send key ([#7093](https://github.com/codewhale-hq/Codewhale/issues/7093)) and session export guidance ([#6996](https://github.com/codewhale-hq/Codewhale/issues/6996)).
- **[@ychu824](https://github.com/ychu824)** — reported every Anthropic request failing with a 400 once `tool_search` added a tool whose name contains a dot, such as `web.run` ([#7252](https://github.com/codewhale-hq/Codewhale/issues/7252)).
## [0.10.2] - 2026-10-22
Generated
+25 -170
View File
@@ -19,48 +19,6 @@ dependencies = [
"cpufeatures 0.2.17",
]
[[package]]
name = "agent-client-protocol"
version = "5.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32339d83e679c8092ec69d2f18e84448f4acf09b46a753e48f3e9265f920acb1"
dependencies = [
"agent-client-protocol-derive",
"agent-client-protocol-schema",
"anyhow",
"futures",
"futures-concurrency",
"rustc-hash",
"serde",
"serde_json",
"tracing",
"uuid",
]
[[package]]
name = "agent-client-protocol-derive"
version = "5.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05a39fd0d81daab854d25144e82e31006b87c554818beb695f0edb576e9c54c4"
dependencies = [
"quote",
"syn 3.0.9",
]
[[package]]
name = "agent-client-protocol-schema"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fd595be39fc4f9c8170872e5d10d81b44cb6dca44bcc66daba0d34412d4237d"
dependencies = [
"anyhow",
"derive_more",
"serde",
"serde_json",
"serde_with",
"strum",
]
[[package]]
name = "ahash"
version = "0.8.12"
@@ -643,15 +601,6 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "bs58"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
dependencies = [
"tinyvec",
]
[[package]]
name = "bstr"
version = "1.13.0"
@@ -933,8 +882,6 @@ dependencies = [
name = "codewhale-app-server"
version = "0.10.3"
dependencies = [
"agent-client-protocol",
"agent-client-protocol-schema",
"anyhow",
"async-stream",
"async-trait",
@@ -1019,7 +966,7 @@ version = "0.10.3"
dependencies = [
"chrono",
"jsonschema",
"schemars 1.2.2",
"schemars",
"serde",
"serde_json",
]
@@ -1123,7 +1070,7 @@ dependencies = [
"libc",
"ring",
"rust_decimal",
"schemars 1.2.2",
"schemars",
"semver",
"serde",
"serde_json",
@@ -1176,8 +1123,6 @@ dependencies = [
name = "codewhale-engine"
version = "0.10.3"
dependencies = [
"agent-client-protocol",
"agent-client-protocol-schema",
"anyhow",
"arboard",
"async-stream",
@@ -1249,7 +1194,7 @@ dependencies = [
"rmcp",
"rusqlite",
"rustls",
"schemars 1.2.2",
"schemars",
"serde",
"serde_json",
"sha2 0.11.1",
@@ -1509,7 +1454,6 @@ dependencies = [
"codewhale-protocol",
"codewhale-sanitize",
"serde_json",
"unicode-width",
]
[[package]]
@@ -1886,7 +1830,7 @@ dependencies = [
"rquickjs",
"rusqlite",
"rustls",
"schemars 1.2.2",
"schemars",
"semver",
"serde",
"serde_json",
@@ -2000,7 +1944,7 @@ version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
dependencies = [
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -2445,9 +2389,6 @@ name = "deranged"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
dependencies = [
"serde_core",
]
[[package]]
name = "derive_more"
@@ -2527,7 +2468,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -2668,7 +2609,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -2771,7 +2712,7 @@ checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78"
dependencies = [
"cfg-if",
"rustix",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -2918,19 +2859,6 @@ dependencies = [
"futures-sink",
]
[[package]]
name = "futures-concurrency"
version = "7.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6"
dependencies = [
"fixedbitset 0.5.7",
"futures-core",
"futures-lite",
"pin-project",
"smallvec",
]
[[package]]
name = "futures-core"
version = "0.3.34"
@@ -3795,7 +3723,7 @@ dependencies = [
"futures-core",
"futures-sink",
"http",
"indexmap 2.14.0",
"indexmap",
"slab",
"tokio",
"tokio-util",
@@ -3822,12 +3750,6 @@ dependencies = [
"byteorder",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -4234,17 +4156,6 @@ dependencies = [
"quick-error",
]
[[package]]
name = "indexmap"
version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
dependencies = [
"autocfg",
"hashbrown 0.12.3",
"serde",
]
[[package]]
name = "indexmap"
version = "2.14.0"
@@ -4994,7 +4905,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -5435,7 +5346,7 @@ checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
dependencies = [
"fixedbitset 0.5.7",
"hashbrown 0.15.5",
"indexmap 2.14.0",
"indexmap",
]
[[package]]
@@ -6167,13 +6078,13 @@ dependencies = [
"async-trait",
"chrono",
"futures",
"indexmap 2.14.0",
"indexmap",
"libc",
"oauth2",
"pastey",
"pin-project-lite",
"reqwest",
"schemars 1.2.2",
"schemars",
"serde",
"serde_json",
"sha2 0.11.1",
@@ -6215,7 +6126,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a2ea9adb03b669c933482ff740b683cd36be7cef23891657a8ccb850401d286"
dependencies = [
"convert_case 0.12.0",
"indexmap 2.14.0",
"indexmap",
"proc-macro-crate",
"proc-macro2",
"quote",
@@ -6340,15 +6251,15 @@ dependencies = [
[[package]]
name = "rustix"
version = "1.1.6"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags 2.13.1",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -6404,7 +6315,7 @@ dependencies = [
"security-framework 3.7.0",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -6473,18 +6384,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "schemars"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"
dependencies = [
"dyn-clone",
"ref-cast",
"serde",
"serde_json",
]
[[package]]
name = "schemars"
version = "1.2.2"
@@ -6654,7 +6553,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"foldhash 0.2.0",
"indexmap 2.14.0",
"indexmap",
"itoa",
"memchr",
"serde",
@@ -6714,39 +6613,6 @@ dependencies = [
"serde",
]
[[package]]
name = "serde_with"
version = "3.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f"
dependencies = [
"base64 0.23.1",
"bs58",
"chrono",
"hex",
"indexmap 1.9.3",
"indexmap 2.14.0",
"jiff",
"schemars 0.9.0",
"schemars 1.2.2",
"serde_core",
"serde_json",
"serde_with_macros",
"time",
]
[[package]]
name = "serde_with_macros"
version = "3.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "serial2"
version = "0.2.38"
@@ -7214,7 +7080,7 @@ dependencies = [
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -7246,7 +7112,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874"
dependencies = [
"rustix",
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -7399,7 +7265,6 @@ dependencies = [
"powerfmt",
"serde_core",
"time-core",
"time-macros",
]
[[package]]
@@ -7408,16 +7273,6 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
[[package]]
name = "time-macros"
version = "0.2.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
dependencies = [
"num-conv",
"time-core",
]
[[package]]
name = "tiny_http"
version = "0.12.0"
@@ -7559,7 +7414,7 @@ version = "1.1.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
dependencies = [
"indexmap 2.14.0",
"indexmap",
"serde_core",
"serde_spanned 1.1.1",
"toml_datetime 1.1.1+spec-1.1.0",
@@ -7592,7 +7447,7 @@ version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
"indexmap 2.14.0",
"indexmap",
"serde",
"serde_spanned 0.6.9",
"toml_datetime 0.6.11",
@@ -7606,7 +7461,7 @@ version = "0.25.15+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"
dependencies = [
"indexmap 2.14.0",
"indexmap",
"toml_datetime 1.1.1+spec-1.1.0",
"toml_parser",
"toml_writer",
@@ -8365,7 +8220,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
-2
View File
@@ -73,8 +73,6 @@ repository = "https://github.com/codewhale-hq/CodeWhale"
warnings = "deny"
[workspace.dependencies]
agent-client-protocol = { version = "=5.2.0", default-features = false }
agent-client-protocol-schema = { version = "=1.17.0", default-features = false }
anyhow = "1.0.100"
async-trait = "0.1.89"
axum = { version = "0.8.5", features = ["json", "ws"] }
-38
View File
@@ -164,44 +164,6 @@ The host bundle's own copy of these notices is `dist/LICENSES.txt`, generated
from the bundler's metafile; Codewhale writes it beside the bundle it
materialises (`~/.codewhale/extension-host/<sha256>/LICENSES.txt`).
## DeepSeek Harness Creator files (`dsh-agent-preset` skills, `dsh-plugin-manager`, `dsh-tool-cordis`, `dsh-sandbox`) — MIT
Codewhale ships, unmodified, the four authoring skills of
`@deepseek-ai/dsh-agent-preset` 0.2.2-rc.1
(`crates/skills/assets/dsh-creator/`), and keeps byte-for-byte copies of
`@deepseek-ai/dsh-plugin-manager` 0.2.2-rc.1 `lib/types/tools.js` and
`@deepseek-ai/dsh-tool-cordis` 0.2.2-rc.1 `lib/index.js`
(`crates/engine/extension-host/src/dsh/upstream/creator/`).
`@deepseek-ai/dsh-sandbox` 0.2.2-rc.1 is named for the approval excerpt that
slice will add. Each package is published under the licence text below, and
each pin's `UPSTREAM.json` records the SHA-256 of every file.
Upstream: <https://github.com/deepseek-ai/deepseek-harness>
```
MIT License
Copyright (c) 2026 DeepSeek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## Model Context Protocol SDK and bundled dependencies
The pinned builtin MCP bundle (`crates/engine/extension-host/dist/builtin/mcp.mjs`)
+2 -3
View File
@@ -924,7 +924,7 @@ base_url = "https://api.deepseek.com/beta"
# (https://bailian.console.aliyun.com/)
#
# Token Plan Personal and Team share the same AP-Southeast (Singapore) endpoint.
# Available text/coding models: qwen3.8-max, qwen4-max-preview, qwen3.7-plus,
# Available text/coding models: qwen3.8-max, qwen3.8-max-preview, qwen3.7-plus,
# qwen3.7-max, qwen3.6-flash, deepseek-v4-pro, deepseek-v4-flash-0731, glm-5.2
#
# Provider aliases: modelstudio-token-plan, modelstudio_token_plan,
@@ -944,8 +944,7 @@ base_url = "https://api.deepseek.com/beta"
# (https://bailian.console.aliyun.com/)
#
# Coding Plan uses a separate international endpoint (coding-intl.dashscope).
# Same model ids as the Token Plan except qwen4-max-preview, which is
# Token Plan only.
# Same model catalog as the Token Plan.
#
# Provider aliases: modelstudio-coding-plan, modelstudio_coding_plan,
# alibaba-coding-plan, dashscope-coding-plan
@@ -391,11 +391,6 @@
"type": "boolean",
"default": false
},
"thread_fleet_member_durable_operations_v1": {
"type": "boolean",
"description": "Member starts are durable per `(store, thread, operation_key)`;\n`GET /v1/threads/{id}/members/operations/{operation_key}` reads them.",
"default": false
},
"fleet_run_start": {
"type": "boolean",
"default": false
@@ -487,7 +482,6 @@
"worker_runtime",
"fleet_run_create",
"thread_fleet_members",
"thread_fleet_member_durable_operations_v1",
"fleet_run_start",
"fleet_event_replay",
"fleet_event_stream",
@@ -86,7 +86,6 @@ export type RuntimeCapabilities = {
worker_runtime: boolean
fleet_run_create: boolean
thread_fleet_members: boolean
thread_fleet_member_durable_operations_v1: boolean
fleet_run_start: boolean
fleet_event_replay: boolean
fleet_event_stream: boolean
@@ -173,10 +173,6 @@ pub struct RuntimeCapabilities {
pub fleet_run_create: bool,
#[serde(default)]
pub thread_fleet_members: bool,
/// Member starts are durable per `(store, thread, operation_key)`;
/// `GET /v1/threads/{id}/members/operations/{operation_key}` reads them.
#[serde(default)]
pub thread_fleet_member_durable_operations_v1: bool,
#[serde(default)]
pub fleet_run_start: bool,
#[serde(default)]
@@ -554,7 +550,6 @@ mod tests {
worker_runtime: false,
fleet_run_create: true,
thread_fleet_members: true,
thread_fleet_member_durable_operations_v1: true,
fleet_run_start: true,
fleet_event_replay: true,
fleet_event_stream: true,
-2
View File
@@ -26,7 +26,6 @@ default = []
test-support = ["codewhale-engine/test-support"]
[dependencies]
agent-client-protocol.workspace = true
codewhale-account-cli = { path = "../account-cli", version = "0.10.3" }
codewhale-app-server-protocol = { path = "../app-server-protocol", version = "0.10.3" }
anyhow.workspace = true
@@ -95,7 +94,6 @@ urlencoding = "2.1"
webbrowser = "1.0"
[dev-dependencies]
agent-client-protocol-schema.workspace = true
rusqlite.workspace = true
tempfile.workspace = true
tower = "0.5"
File diff suppressed because it is too large. Load diff
@@ -1,441 +0,0 @@
use super::*;
use agent_client_protocol::v1::{ConnectionTo, Responder};
use agent_client_protocol::{Agent, Client, Lines, UntypedMessage};
use codewhale_util::bounded_lines::{BoundedLines, FrameRefusal, MAX_FRAME_BYTES};
use futures_util::{Sink, Stream};
use std::io;
use std::sync::{MutexGuard, PoisonError};
use tokio::sync::{Notify, mpsc};
const PROMPT_BUSY: &str = "a session/prompt turn is already in progress";
const OUTGOING_QUEUE_FRAMES: usize = 256;
const OVERSIZE_RESPONSE: &str =
"ACP response exceeds the 8 MiB transport limit; inspect canonical state without replay";
type Cx = ConnectionTo<Client>;
pub(super) struct Shared {
server: tokio::sync::Mutex<AcpServer>,
prompt: std::sync::Mutex<Option<mpsc::UnboundedSender<Inbound>>>,
idle: Notify,
ending: Notify,
failure: std::sync::Mutex<Option<anyhow::Error>>,
}
struct PromptGuard(Arc<Shared>);
impl Drop for PromptGuard {
fn drop(&mut self) {
self.0.release();
}
}
impl PromptGuard {
fn finish(self, responder: Responder<Value>, result: std::result::Result<Value, SdkError>) {
let mut slot = self.0.slot();
let _ = responder.respond_with_result(result);
*slot = None;
drop(slot);
self.0.idle.notify_waiters();
}
}
impl Shared {
pub(super) fn new(server: AcpServer) -> Self {
Self {
server: tokio::sync::Mutex::new(server),
prompt: std::sync::Mutex::new(None),
idle: Notify::new(),
ending: Notify::new(),
failure: std::sync::Mutex::new(None),
}
}
pub(super) fn fail(&self, error: anyhow::Error) {
self.failure
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get_or_insert(error);
self.tell_prompt(Inbound::Eof);
self.ending.notify_one();
}
pub(super) fn take_failure(&self) -> Option<anyhow::Error> {
self.failure
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
}
#[cfg(test)]
pub(super) fn into_server(self) -> AcpServer {
self.server.into_inner()
}
fn slot(&self) -> MutexGuard<'_, Option<mpsc::UnboundedSender<Inbound>>> {
self.prompt.lock().unwrap_or_else(PoisonError::into_inner)
}
fn prompt_active(&self) -> bool {
self.slot().is_some()
}
fn tell_prompt(&self, message: Inbound) {
if let Some(inbox) = self.slot().as_ref() {
let _ = inbox.send(message);
}
}
fn release(&self) {
*self.slot() = None;
self.idle.notify_waiters();
}
async fn wait_idle(&self) {
loop {
let notified = self.idle.notified();
if !self.prompt_active() {
return;
}
notified.await;
}
}
fn cancel(&self, params: &Value) {
if let Some(session) = params.get("sessionId").and_then(Value::as_str) {
self.tell_prompt(Inbound::Cancel {
session: session.to_string(),
});
}
}
async fn request(
self: &Arc<Self>,
method: String,
params: Value,
responder: Responder<Value>,
cx: Cx,
) {
match method.as_str() {
"session/cancel" => {
self.cancel(&params);
let _ = responder.respond(Value::Null);
}
"session/prompt" => self.start_prompt(params, responder, cx).await,
_ if self.prompt_active() => self.during_prompt(&cx, method, params, responder),
"shutdown" => {
let _ = responder.respond(Value::Null);
self.ending.notify_one();
}
"session/load" => self.load(params, responder, cx).await,
_ => {
let result = self
.server
.lock()
.await
.handle_request(&method, params)
.await;
let _ = responder.respond_with_result(result);
}
}
}
fn during_prompt(
self: &Arc<Self>,
cx: &Cx,
method: String,
params: Value,
responder: Responder<Value>,
) {
let served = matches!(
method.as_str(),
"session/list"
| "session/set_config_option"
| "session/set_mode"
| "session/set_model"
| "session/listProviders"
| "session/currentModel"
| "session/selectModel"
);
if !served {
let error = if matches!(
method.as_str(),
"initialize" | "session/new" | "session/load" | "shutdown"
) {
SdkError::new(-32603, PROMPT_BUSY)
} else {
SdkError::method_not_found().data(Value::String(method))
};
let _ = responder.respond_with_error(error);
return;
}
let shared = Arc::clone(self);
let _ = cx.spawn(async move {
let result = shared
.server
.lock()
.await
.handle_request(&method, params)
.await;
let _ = responder.respond_with_result(result);
Ok(())
});
}
async fn load(&self, params: Value, responder: Responder<Value>, cx: Cx) {
let mut server = self.server.lock().await;
let result = async {
let loaded = server.load_session(params).await.map_err(SdkError::from)?;
if let Some(session) = loaded.get("sessionId").and_then(Value::as_str) {
let updates = server
.history_updates(session)
.await
.map_err(|error| SdkError::new(-32603, error.to_string()))?;
for update in updates {
cx.send_notification(acp::SessionNotification::new(
session.to_string(),
update,
))?;
}
}
Ok::<_, SdkError>(loaded)
}
.await;
drop(server);
let _ = responder.respond_with_result(result);
}
async fn start_prompt(self: &Arc<Self>, params: Value, responder: Responder<Value>, cx: Cx) {
if self.prompt_active() {
let _ = responder.respond_with_error(SdkError::new(-32603, PROMPT_BUSY));
return;
}
let admitted = {
let server = self.server.lock().await;
server.validate_prompt(&params).map(|(session, prompt)| {
let thread = server.sessions[&session].thread_id.clone();
(session, thread, prompt, server.prompt_run())
})
};
let (session, thread, prompt, run) = match admitted {
Ok(admitted) => admitted,
Err(error) => {
let _ = responder.respond_with_error(error.into());
return;
}
};
let (answers, mut inbox) = mpsc::unbounded_channel();
*self.slot() = Some(answers.clone());
let guard = PromptGuard(Arc::clone(self));
let task_cx = cx.clone();
let _ = cx.spawn(async move {
let result = {
let mut emit = |outgoing: Outgoing| -> Result<()> {
match outgoing {
Outgoing::Update(notification) => task_cx
.send_notification(notification)
.map_err(|error| anyhow!("ACP update was not sent: {}", error.message)),
Outgoing::Permission { key, request } => {
let answers = answers.clone();
task_cx
.send_request(request)
.on_receiving_result(async move |reply| {
let gone = matches!(
&reply,
Err(error)
if agent_client_protocol::is_incoming_transport_closed(error)
|| agent_client_protocol::is_connection_terminated(error)
);
if !gone {
let _ = answers.send(Inbound::Permission {
key,
allow: permission_allowed(&reply),
});
}
Ok(())
})
.map_err(|error| {
anyhow!("ACP permission request was not sent: {}", error.message)
})
}
}
};
run.drive_prompt(&session, &thread, prompt, &mut emit, &mut inbox)
.await
};
let result = match result {
Ok(stop) => to_wire(&acp::PromptResponse::new(stop)).map_err(SdkError::from),
Err(error) => Err(SdkError::new(
-32603,
codewhale_engine::client::redact_model_bound_text(&error.to_string(), &[]),
)),
};
guard.finish(responder, result);
Ok(())
});
}
}
fn permission_allowed(
reply: &std::result::Result<acp::RequestPermissionResponse, SdkError>,
) -> bool {
matches!(
reply,
Ok(response) if matches!(
&response.outcome,
acp::RequestPermissionOutcome::Selected(selected)
if &*selected.option_id.0 == "allow-once"
)
)
}
fn closes_input(line: &str) -> bool {
line.len() <= 256
&& line.contains("daemon/input_closed")
&& serde_json::from_str::<Value>(line)
.is_ok_and(|message| crate::is_control_input_closed(&message))
}
fn incoming_lines(
input: Box<dyn AsyncBufRead + Send + Unpin>,
shared: Arc<Shared>,
) -> impl Stream<Item = io::Result<String>> + Send + 'static {
futures_util::stream::unfold(
(BoundedLines::new(input), shared),
|(mut lines, shared)| async move {
loop {
match lines.next_line().await {
Ok(Some(line)) if line.trim().is_empty() => continue,
Ok(Some(line)) if closes_input(&line) => return None,
Ok(Some(line)) => return Some((Ok(line), (lines, shared))),
Ok(None) => return None,
Err(error) if crate::stdio::is_frame_refusal(&error) => {
return Some((Ok(error.to_string()), (lines, shared)));
}
Err(error) => {
shared.fail(anyhow!("ACP input failed: {error}"));
return None;
}
}
}
},
)
}
pub(super) fn bound_outgoing(line: String) -> io::Result<String> {
if line.len() <= MAX_FRAME_BYTES {
return Ok(line);
}
let refused = || io::Error::new(io::ErrorKind::InvalidData, FrameRefusal::TooLarge);
let Ok(Value::Object(frame)) = serde_json::from_str::<Value>(&line) else {
return Err(refused());
};
if frame.contains_key("method") || !frame.contains_key("id") {
return Err(refused());
}
let failure = |id: Value| {
json!({"jsonrpc":"2.0","id":id,"error":{"code":-32603,"message":OVERSIZE_RESPONSE}})
.to_string()
};
let replaced = failure(frame["id"].clone());
Ok(if replaced.len() <= MAX_FRAME_BYTES {
replaced
} else {
failure(Value::Null)
})
}
pub(super) fn outgoing_lines(
frames: mpsc::Sender<String>,
shared: Arc<Shared>,
) -> impl Sink<String, Error = io::Error> + Send + 'static {
futures_util::sink::unfold(
(frames, shared),
|(frames, shared), line: String| async move {
let line = match bound_outgoing(line) {
Ok(line) => line,
Err(error) => {
shared.fail(anyhow!("ACP output refused: {error}"));
return Ok((frames, shared));
}
};
frames
.send(line)
.await
.map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "ACP output closed"))?;
Ok::<_, io::Error>((frames, shared))
},
)
}
pub(super) async fn serve_connection<'a>(
server: AcpServer,
input: Box<dyn AsyncBufRead + Send + Unpin>,
mut output: Box<dyn AsyncWrite + Send + Unpin + 'a>,
) -> Result<Arc<Shared>> {
let shared = Arc::new(Shared::new(server));
let (frames, mut queued) = mpsc::channel::<String>(OUTGOING_QUEUE_FRAMES);
let transport = Lines::new(
outgoing_lines(frames, Arc::clone(&shared)),
incoming_lines(input, Arc::clone(&shared)),
);
let requests = Arc::clone(&shared);
let notifications = Arc::clone(&shared);
let finishing = Arc::clone(&shared);
let connection = Agent
.v1()
.on_receive_request(
async move |request: UntypedMessage, responder, cx| {
let (method, params) = request.into_parts();
requests.request(method, params, responder, cx).await;
Ok(())
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_notification(
async move |notification: UntypedMessage, _cx| {
let (method, params) = notification.into_parts();
if method == "session/cancel" {
notifications.cancel(&params);
}
Ok(())
},
agent_client_protocol::on_receive_notification!(),
)
.connect_with(transport, async move |cx| {
tokio::select! {
() = cx.incoming_closed() => {}
() = finishing.ending.notified() => {}
}
finishing.tell_prompt(Inbound::Eof);
finishing.wait_idle().await;
Ok(())
});
let connection = async {
match connection.await {
Err(error) if agent_client_protocol::is_incoming_transport_closed(&error) => Ok(()),
other => other.map_err(|error| anyhow!("ACP connection failed: {}", error.message)),
}
};
let failing = Arc::clone(&shared);
let pump = async {
let mut broken = false;
while let Some(frame) = queued.recv().await {
if broken {
continue;
}
if let Err(error) =
crate::stdio::write_control_line(&mut output, frame.as_bytes()).await
{
broken = true;
failing.fail(error);
}
}
};
let (ended, ()) = tokio::join!(connection, pump);
drop(failing);
if let Some(error) = shared.take_failure() {
return Err(error);
}
ended?;
Ok(shared)
}
+194 -147
View File
@@ -5,17 +5,12 @@ use codewhale_engine::runtime_threads::{
manager::ExternalApprovalDecision, manager::StartTurnRequest,
};
use std::time::Duration;
use tokio::sync::mpsc::UnboundedReceiver;
struct Permission {
thread_id: String,
turn_id: String,
approval_id: String,
execution_id: String,
}
pub(super) struct PromptRun {
pub(super) runtime: Arc<RuntimeThreadManager>,
pub(super) sessions_dir: PathBuf,
}
struct Projection<'a> {
session: &'a str,
thread: &'a str,
@@ -47,20 +42,21 @@ impl Drop for TurnClaim {
}
}
}
fn update(session: &str, update: acp::SessionUpdate) -> Outgoing {
Outgoing::Update(acp::SessionNotification::new(session.to_string(), update))
}
impl PromptRun {
pub(super) async fn drive_prompt(
&self,
session_id: &str,
thread_id: &str,
prompt: String,
emit: Emit<'_>,
inbox: &mut UnboundedReceiver<Inbound>,
) -> Result<acp::StopReason> {
let session_id = session_id.to_string();
let thread_id = thread_id.to_string();
impl AcpServer {
pub(super) async fn drive_prompt<R: AsyncBufRead + Unpin, W: AsyncWrite + Unpin>(
&mut self,
params: Value,
reader: &mut crate::stdio::BoundedLines<R>,
writer: &mut W,
) -> Result<&'static str> {
let (session_id, prompt) = self
.validate_prompt(&params)
.map_err(|error| anyhow!(error.message))?;
let binding = self
.sessions
.get(&session_id)
.ok_or_else(|| anyhow!("unknown sessionId"))?;
let thread_id = binding.thread_id.clone();
// Subscribe before snapshot/admission; replay deduplicates by seq.
let mut receiver = self.runtime.subscribe_events();
let cursor = self.runtime.get_thread_detail(&thread_id).await?.latest_seq;
@@ -90,7 +86,7 @@ impl PromptRun {
permissions: HashMap::new(),
};
let terminal = match self
.project_turn(&mut projection, &mut receiver, inbox, emit)
.project_turn(&mut projection, &mut receiver, reader, writer)
.await
{
Ok(terminal) => terminal,
@@ -148,6 +144,9 @@ impl PromptRun {
}
};
claim.armed = false;
if let Some(binding) = self.sessions.get_mut(&session_id) {
binding.cursor = projection.cursor;
}
self.save_checkpoint(&thread_id, &session_id).await?;
if terminal
.model_request_diagnostics
@@ -155,13 +154,11 @@ impl PromptRun {
.and_then(|facts| facts.stop_reason)
== Some(RuntimeTurnStopReason::StepBudgetExhausted)
{
return Ok(acp::StopReason::MaxTurnRequests);
return Ok("max_turn_requests");
}
match terminal.status {
RuntimeTurnStatus::Completed => Ok(acp::StopReason::EndTurn),
RuntimeTurnStatus::Interrupted | RuntimeTurnStatus::Canceled => {
Ok(acp::StopReason::Cancelled)
}
RuntimeTurnStatus::Completed => Ok("end_turn"),
RuntimeTurnStatus::Interrupted | RuntimeTurnStatus::Canceled => Ok("cancelled"),
_ => Err(anyhow!(
"{}",
terminal.error.unwrap_or_else(
@@ -212,12 +209,12 @@ impl PromptRun {
})?;
Ok(())
}
async fn project_turn(
async fn project_turn<R: AsyncBufRead + Unpin, W: AsyncWrite + Unpin>(
&self,
projection: &mut Projection<'_>,
receiver: &mut tokio::sync::broadcast::Receiver<RuntimeEventRecord>,
inbox: &mut UnboundedReceiver<Inbound>,
emit: Emit<'_>,
reader: &mut crate::stdio::BoundedLines<R>,
writer: &mut W,
) -> Result<TurnRecord> {
let session = projection.session;
let thread = projection.thread;
@@ -235,26 +232,45 @@ impl PromptRun {
}
tokio::select! {
() = async { match cancel_deadline { Some(deadline) => tokio::time::sleep_until(deadline).await, None => std::future::pending().await } } => return Err(anyhow!("Core cancellation remains nonterminal; ACP cannot report a fabricated cancelled receipt")),
message = inbox.recv(), if !eof => {
match message {
Some(Inbound::Cancel { session: cancelled_session }) => {
if cancelled_session == session {
cancelled = true; projection.permissions.clear(); self.interrupt_claimed_turn(thread, turn).await?;
cancel_deadline.get_or_insert(tokio::time::Instant::now() + Duration::from_secs(30));
}
line = reader.next_line(), if !eof => {
let line = match line {
Ok(line) => line,
Err(error) if crate::stdio::is_frame_refusal(&error) => {
write_jsonrpc_error(writer, None, -32700, error.to_string()).await?;
continue;
}
Some(Inbound::Permission { key, allow }) => {
if !cancelled && let Some(permission) = projection.permissions.remove(&key) { self.answer_permission(&permission, allow).await?; }
}
Some(Inbound::Eof) | None => {
eof = true; cancelled = true; projection.permissions.clear(); self.interrupt_claimed_turn(thread, turn).await?;
Err(error) => return Err(error.into()),
};
let Some(line) = line else {
eof = true; cancelled = true; projection.permissions.clear(); self.interrupt_claimed_turn(thread, turn).await?;
cancel_deadline = Some(tokio::time::Instant::now() + Duration::from_secs(30)); continue;
};
if line.trim().is_empty() { continue; }
let message: Value = match serde_json::from_str(&line) {
Ok(message) => message,
Err(error) => { write_jsonrpc_error(writer, None, -32700, format!("invalid json: {error}")).await?; continue; }
};
if crate::is_control_input_closed(&message) {
eof=true; cancelled=true; projection.permissions.clear();self.interrupt_claimed_turn(thread,turn).await?;
cancel_deadline.get_or_insert(tokio::time::Instant::now()+Duration::from_secs(30));continue;
}
let response_id = message.get("id").cloned().map(|id| self.response_id_policy.response_id(id));
if message.get("jsonrpc").and_then(Value::as_str) != Some("2.0") { write_jsonrpc_error(writer, response_id, -32600, "jsonrpc version must be 2.0").await?; continue; }
if is_jsonrpc_response(&message) {
if !cancelled && let Some(id) = message.get("id").and_then(Value::as_str) && let Some(permission) = projection.permissions.remove(id) { self.answer_permission(&permission, &message).await?; }
continue;
}
if message.get("method").and_then(Value::as_str) == Some("session/cancel") {
if message.pointer("/params/sessionId").and_then(Value::as_str) == Some(session) {
cancelled = true; projection.permissions.clear(); self.interrupt_claimed_turn(thread, turn).await?;
cancel_deadline.get_or_insert(tokio::time::Instant::now() + Duration::from_secs(30));
}
}
if let Some(id) = response_id { write_jsonrpc_result(writer, id, json!(null)).await?; }
} else if let Some(id) = response_id { write_jsonrpc_error(writer, Some(id), -32603, "a session/prompt turn is already in progress").await?; }
}
record = async { replay_batch.pop_front().expect("nonempty bounded replay batch") }, if !replay_batch.is_empty() => {
projection.emit = !cancelled && !eof;
if let Some(done) = self.project_event(projection, &record, &mut *emit).await? { return Ok(done); }
if let Some(done) = self.project_event(projection, &record, writer).await? { return Ok(done); }
}
batch = async { replay.as_mut().expect("active replay").batches.recv().await }, if replay.is_some() && replay_batch.is_empty() => {
match batch {
@@ -264,7 +280,7 @@ impl PromptRun {
}
event = receiver.recv(), if replay.is_none() && replay_batch.is_empty() => {
match event {
Ok(record) => { projection.emit = !cancelled && !eof; if let Some(done) = self.project_event(projection, &record, &mut *emit).await? { return Ok(done); } },
Ok(record) => { projection.emit = !cancelled && !eof; if let Some(done) = self.project_event(projection, &record, writer).await? { return Ok(done); } },
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
let captured = self.runtime.replay_events(thread, Some(projection.cursor), None).await?;
if captured.base_seq > projection.cursor { return Err(anyhow!("ACP replay no longer covers the cursor; projection is incomplete")); }
@@ -276,7 +292,7 @@ impl PromptRun {
}
}
}
async fn answer_permission(&self, permission: &Permission, allow: bool) -> Result<()> {
async fn answer_permission(&self, permission: &Permission, response: &Value) -> Result<()> {
let detail = self
.runtime
.get_thread_detail(&permission.thread_id)
@@ -288,6 +304,15 @@ impl PromptRun {
}) {
return Ok(());
}
let allow = response.get("error").is_none()
&& response
.pointer("/result/outcome/outcome")
.and_then(Value::as_str)
== Some("selected")
&& response
.pointer("/result/outcome/optionId")
.and_then(Value::as_str)
== Some("allow-once");
self.runtime
.deliver_approval_from(
&permission.approval_id,
@@ -302,11 +327,11 @@ impl PromptRun {
.await?;
Ok(())
}
async fn project_event(
async fn project_event<W: AsyncWrite + Unpin>(
&self,
projection: &mut Projection<'_>,
record: &RuntimeEventRecord,
out: Emit<'_>,
writer: &mut W,
) -> Result<Option<TurnRecord>> {
let session = projection.session;
let thread = projection.thread;
@@ -328,7 +353,7 @@ impl PromptRun {
if emit && p.get("kind").and_then(Value::as_str) == Some("agent_message") =>
{
if let Some(text) = p.get("delta").and_then(Value::as_str) {
out(update(session, agent_text(text.to_string())))?;
write_session_update(writer, session, text.to_string()).await?;
}
}
"item.started" => {
@@ -348,10 +373,7 @@ impl PromptRun {
input: tool.get("input").cloned().unwrap_or(Value::Null),
};
if emit {
out(update(
session,
acp::SessionUpdate::ToolCall(tool_call_start(&call)),
))?;
write_tool_call_start(writer, session, &call).await?;
}
calls.insert(id, call);
}
@@ -364,15 +386,7 @@ impl PromptRun {
let call = calls
.get(id)
.ok_or_else(|| anyhow!("Dispatch projection lacks its admitted start"))?;
out(update(
session,
acp::SessionUpdate::ToolCallUpdate(tool_call_update(
call,
acp::ToolCallStatus::InProgress,
None,
&[],
)),
))?;
write_tool_call_update(writer, session, call, "in_progress", None).await?;
}
"item.completed" | "item.failed" | "item.interrupted" if emit => {
if let Some(item) = p.get("item")
@@ -389,19 +403,19 @@ impl PromptRun {
.unwrap_or_default();
let status = if item.get("status").and_then(Value::as_str) == Some("completed")
{
acp::ToolCallStatus::Completed
"completed"
} else {
acp::ToolCallStatus::Failed
"failed"
};
out(update(
write_tool_call_update_with_blocks(
writer,
session,
acp::SessionUpdate::ToolCallUpdate(tool_call_update(
&call,
status,
item.get("detail").and_then(Value::as_str),
&blocks,
)),
))?;
&call,
status,
item.get("detail").and_then(Value::as_str),
&blocks,
)
.await?;
}
}
"approval.required" if emit => {
@@ -422,41 +436,11 @@ impl PromptRun {
let call = calls
.get(execution)
.ok_or_else(|| anyhow!("Approval projection lacks admitted tool start"))?;
let id = uuid::Uuid::new_v4().to_string();
let title = tool_call_title(call);
let text = p
.get("description")
.and_then(Value::as_str)
.filter(|text| !text.trim().is_empty())
.map_or_else(|| title.clone(), str::to_string);
let request = acp::RequestPermissionRequest::new(
session.to_string(),
acp::ToolCallUpdate::new(
execution.to_string(),
acp::ToolCallUpdateFields::new()
.title(title)
.kind(tool_call_kind(call))
.status(acp::ToolCallStatus::Pending)
.raw_input((!call.input.is_null()).then(|| call.input.clone()))
.content(vec![acp::ToolCallContent::from(text)]),
),
vec![
acp::PermissionOption::new(
"allow-once",
"Allow once",
acp::PermissionOptionKind::AllowOnce,
),
acp::PermissionOption::new(
"reject-once",
"Reject",
acp::PermissionOptionKind::RejectOnce,
),
],
let id = format!(
"codewhale-permission-{}",
NEXT_ACP_PERMISSION_REQUEST_ID.fetch_add(1, Ordering::Relaxed)
);
out(Outgoing::Permission {
key: id.clone(),
request,
})?;
write_json_line(writer, json!({"jsonrpc":"2.0","id":id,"method":"session/request_permission","params":{"sessionId":session,"toolCall":{"toolCallId":execution,"title":tool_call_title(call),"kind":tool_call_kind(call),"status":"pending","rawInput":call.input,"content":[{"type":"content","content":{"type":"text","text":p.get("description")}}]},"options":[{"optionId":"allow-once","name":"Allow once","kind":"allow_once"},{"optionId":"reject-once","name":"Reject","kind":"reject_once"}]}})).await?;
permissions.insert(
id,
Permission {
@@ -505,22 +489,6 @@ impl PromptRun {
mod tests {
use super::super::tests::{Rig, fixture_config};
use super::*;
fn frame(outgoing: Outgoing) -> Value {
match outgoing {
Outgoing::Update(notification) => {
json!({"jsonrpc":"2.0","method":"session/update","params":serde_json::to_value(notification).unwrap()})
}
Outgoing::Permission { key, request } => {
json!({"jsonrpc":"2.0","id":key,"method":"session/request_permission","params":serde_json::to_value(request).unwrap()})
}
}
}
fn recording(out: &mut Vec<Value>) -> impl FnMut(Outgoing) -> Result<()> + Send + '_ {
move |outgoing| {
out.push(frame(outgoing));
Ok(())
}
}
fn event(seq: u64, thread: &str, turn: &str, name: &str, payload: Value) -> RuntimeEventRecord {
serde_json::from_value(json!({"seq":seq,"timestamp":chrono::Utc::now(),"thread_id":thread,"turn_id":turn,"event":name,"payload":payload})).unwrap()
}
@@ -638,15 +606,14 @@ mod tests {
calls: HashMap::new(),
permissions: HashMap::new(),
};
let mut output: Vec<Value> = Vec::new();
let mut output = Vec::new();
// Project the actual Runtime records, not synthetic ACP frames.
for record in rig.server.runtime.events_since(&thread, None)? {
rig.server
.prompt_run()
.project_event(&mut projection, &record, &mut recording(&mut output))
.project_event(&mut projection, &record, &mut output)
.await?;
}
let wire = output;
let wire = super::super::tests::parse_lines(output);
let requests: Vec<_> = wire
.iter()
.filter(|frame| frame["method"] == "session/request_permission")
@@ -668,8 +635,12 @@ mod tests {
)
.ok_or_else(|| anyhow!("ACP permission was not retained"))?;
rig.server
.prompt_run()
.answer_permission(&permission, true)
.answer_permission(
&permission,
&json!({
"result":{"outcome":{"outcome":"selected","optionId":"allow-once"}}
}),
)
.await?;
assert_eq!(
tokio::time::timeout(Duration::from_secs(10), engine.recv_approval_event())
@@ -787,7 +758,7 @@ mod tests {
})
.await??;
let mut terminal = None;
let mut settled_output: Vec<Value> = Vec::new();
let mut settled_output = Vec::new();
for record in rig
.server
.runtime
@@ -795,12 +766,7 @@ mod tests {
{
if let Some(completed) = rig
.server
.prompt_run()
.project_event(
&mut projection,
&record,
&mut recording(&mut settled_output),
)
.project_event(&mut projection, &record, &mut settled_output)
.await?
{
terminal = Some(completed);
@@ -815,7 +781,7 @@ mod tests {
assert!(projection.permissions.is_empty());
assert!(projection.calls.is_empty());
assert!(
!settled_output
!super::super::tests::parse_lines(settled_output)
.iter()
.any(|frame| frame["method"] == "session/request_permission")
);
@@ -838,7 +804,7 @@ mod tests {
calls: HashMap::new(),
permissions: HashMap::new(),
};
let mut output: Vec<Value> = Vec::new();
let mut output = Vec::new();
let start = event(
1,
&thread,
@@ -847,13 +813,11 @@ mod tests {
json!({"tool":{"id":"core-call","name":"read","input":{"path":"x"}}}),
);
rig.server
.prompt_run()
.project_event(&mut p, &start, &mut recording(&mut output))
.project_event(&mut p, &start, &mut output)
.await?;
let before = output.len();
rig.server
.prompt_run()
.project_event(&mut p, &start, &mut recording(&mut output))
.project_event(&mut p, &start, &mut output)
.await?;
assert_eq!(output.len(), before);
let dispatch = event(
@@ -865,8 +829,7 @@ mod tests {
);
assert!(
rig.server
.prompt_run()
.project_event(&mut p, &dispatch, &mut recording(&mut output))
.project_event(&mut p, &dispatch, &mut output)
.await
.is_err()
);
@@ -887,7 +850,7 @@ mod tests {
calls: HashMap::new(),
permissions: HashMap::new(),
};
let mut output: Vec<Value> = Vec::new();
let mut output = Vec::new();
for record in [
event(
1,
@@ -919,8 +882,7 @@ mod tests {
),
] {
rig.server
.prompt_run()
.project_event(&mut p, &record, &mut recording(&mut output))
.project_event(&mut p, &record, &mut output)
.await?;
}
assert!(output.is_empty());
@@ -942,7 +904,7 @@ mod tests {
calls: HashMap::new(),
permissions: HashMap::new(),
};
let mut output: Vec<Value> = Vec::new();
let mut output = Vec::new();
let failure = event(
1,
&thread,
@@ -952,8 +914,7 @@ mod tests {
);
let error = rig
.server
.prompt_run()
.project_event(&mut p, &failure, &mut recording(&mut output))
.project_event(&mut p, &failure, &mut output)
.await
.unwrap_err();
assert!(error.to_string().contains("no terminal receipt"));
@@ -961,4 +922,90 @@ mod tests {
rig.close().await;
Ok(())
}
struct FailedAnswerWriter(Vec<u8>);
impl AsyncWrite for FailedAnswerWriter {
fn poll_write(
mut self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
bytes: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
if String::from_utf8_lossy(bytes).contains("agent_message_chunk") {
return std::task::Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"fixture client disappeared after tool effect",
)));
}
self.0.extend_from_slice(bytes);
std::task::Poll::Ready(Ok(bytes.len()))
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
}
#[tokio::test(flavor = "current_thread")]
async fn failed_transport_after_completed_write_retains_actual_core_terminal_and_checkpoint()
-> Result<()> {
use codewhale_engine::llm_client::mock::canned;
let mut config = fixture_config();
config.yolo = Some(true);
let mut rig = Rig::new(
config,
vec![
canned::tool_call_turn(
"write",
"write",
r#"{"path":"writer-failure.txt","content":"completed"}"#,
),
canned::simple_text_turn("final answer"),
],
)?;
let id = rig.new_session().await;
let (client, input) = tokio::io::duplex(1024);
let mut reader = crate::stdio::BoundedLines::new(BufReader::new(input));
let mut writer = FailedAnswerWriter(Vec::new());
let error = tokio::time::timeout(
Duration::from_secs(20),
rig.server.drive_prompt(
json!({"sessionId":id,"prompt":"write then answer"}),
&mut reader,
&mut writer,
),
)
.await?
.unwrap_err();
drop(client);
assert!(error.to_string().contains("partial receipts retained"));
assert_eq!(
std::fs::read_to_string(rig.workspace.join("writer-failure.txt"))?,
"completed"
);
let store = codewhale_engine::session_manager::SessionManager::new(
rig.server.sessions_dir.clone(),
)?;
let saved = store.load_session(&id)?;
assert!(
saved
.messages
.iter()
.flat_map(|m| &m.content)
.any(|b| matches!(b, codewhale_models::ContentBlock::ToolResult { .. }))
);
let thread = &rig.server.sessions[&id].thread_id;
let detail = rig.server.runtime.get_thread_detail(thread).await?;
assert!(!matches!(
detail.turns.last().unwrap().status,
RuntimeTurnStatus::Queued | RuntimeTurnStatus::InProgress
));
rig.close().await;
Ok(())
}
}
+2 -67
View File
@@ -41,34 +41,6 @@ mod platform {
tokio::io::WriteHalf<Connection>,
>;
fn resolved_store_form(path: PathBuf) -> Option<PathBuf> {
let checked = codewhale_engine::runtime_threads::checked_runtime_store_root(path).ok()?;
let mut tail = Vec::new();
let mut probe = checked.as_path();
loop {
match probe.canonicalize() {
Ok(real) => {
return Some(tail.iter().rev().fold(real, |acc, part| acc.join(part)));
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
tail.push(probe.file_name()?.to_owned());
probe = probe.parent()?;
}
Err(_) => return None,
}
}
}
fn resolved_store_form_of(path: &std::path::Path) -> PathBuf {
resolved_store_form(path.to_path_buf()).unwrap_or_else(|| path.to_path_buf())
}
fn same_store_path(left: &std::path::Path, right: &std::path::Path) -> bool {
left == right
|| (cfg!(any(target_os = "macos", windows))
&& left.to_string_lossy().to_lowercase() == right.to_string_lossy().to_lowercase())
}
fn same_socket_selection(left: &std::path::Path, right: &std::path::Path) -> bool {
if left == right {
return true;
@@ -255,34 +227,6 @@ mod platform {
);
Ok(())
}
fn discard_if_store_gone_blocking(&self, selected_store: PathBuf) -> Result<bool> {
let gone = resolved_store_form(selected_store).is_some_and(|selected| {
same_store_path(&selected, &resolved_store_form_of(&self.receipt().data_dir))
&& matches!(
selected.symlink_metadata(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound
)
});
if !gone || !matches!(self.revalidate_receipt(), Ok(true)) {
return Ok(false);
}
anyhow::ensure!(
self.publication.parent.retire_private_receipt(
&self.publication.receipt_name,
&self.publication.file
)?,
PublicationChangedBeforeAttach
);
Ok(true)
}
async fn discard_if_store_gone(
self: &Arc<Self>,
selected_store: &std::path::Path,
) -> Result<bool> {
let held = self.clone();
let selected_store = selected_store.to_path_buf();
owner_work(move || held.discard_if_store_gone_blocking(selected_store)).await
}
/// Caller retains the real Runtime lease; this checks evidence only.
pub(crate) fn revalidate_receipt(&self) -> Result<bool> {
if !self.publication.receipt_is_current()? {
@@ -401,9 +345,8 @@ mod platform {
pub async fn probe_owner_for_host_startup(
config_path: Option<PathBuf>,
selected: Option<PathBuf>,
selected_store: &std::path::Path,
) -> Result<HostOwnerProbe> {
match probe_frontend(
probe_frontend(
config_path,
selected,
crate::daemon_socket::AttachFrontend::Control,
@@ -412,15 +355,7 @@ mod platform {
None,
None,
)
.await?
{
HostOwnerProbe::Unavailable(publication)
if publication.discard_if_store_gone(selected_store).await? =>
{
Ok(HostOwnerProbe::Absent)
}
probe => Ok(probe),
}
.await
}
pub async fn connect(
-4
View File
@@ -1349,7 +1349,6 @@ mod platform {
let config = root.join("config.toml");
std::fs::write(&config, "")?;
let parent = PrivateDirectory::admit(path.parent().unwrap())?;
std::fs::create_dir_all(root.join("runtime"))?;
let stale = std::os::unix::net::UnixListener::bind(&path)?;
let identity = parent.socket_identity("daemon.sock")?.unwrap();
parent.protect_socket("daemon.sock", identity)?;
@@ -1384,7 +1383,6 @@ mod platform {
crate::daemon_client::probe_owner_for_host_startup(
Some(config.clone()),
Some(path.clone()),
&owner.data_dir,
)
.await?
else {
@@ -1394,7 +1392,6 @@ mod platform {
let observed_hook = observed.clone();
let selected = path.clone();
let selected_config = config.clone();
let selected_store = owner.data_dir.clone();
let stale_capture = captured.clone();
BEFORE_OWNER_REBIND.with(|slot| {
*slot.borrow_mut() = Some(Box::new(move |endpoint| {
@@ -1415,7 +1412,6 @@ mod platform {
crate::daemon_client::probe_owner_for_host_startup(
Some(selected_config),
Some(endpoint),
&selected_store,
)
.await
.unwrap(),
-1
View File
@@ -668,7 +668,6 @@ pub async fn run_exec_agent(
execution_config.subagent_heartbeat_timeout_secs_for_provider(&effective_identity),
),
prefer_bwrap: execution_config.prefers_bwrap(),
tool_launcher: execution_config.tool_launcher.clone(),
bwrap_extensions: codewhale_sandbox::BwrapMountExtensions {
read_only_roots: execution_config.bwrap_ro_roots.clone(),
device_roots: execution_config.bwrap_dev_roots.clone(),
+1 -37
View File
@@ -76,18 +76,6 @@ impl McpServerSettings {
}
}
fn refuse_shell_tools(&mut self) -> Vec<String> {
let (refused, kept): (Vec<String>, Vec<String>) = std::mem::take(&mut self.expose_tools)
.into_iter()
.partition(|name| {
build_exposed_tools(std::slice::from_ref(name))
.iter()
.any(|tool| tool.internal == "exec_shell")
});
self.expose_tools = kept;
refused
}
fn from_toml(contents: &str) -> Result<Self> {
let config: McpServerConfigFile = toml::from_str(contents)?;
Ok(Self {
@@ -110,21 +98,12 @@ pub async fn run_mcp_server(
workspace: PathBuf,
skills_dir: PathBuf,
skills_config: std::sync::Arc<codewhale_runtime::config::SkillsConfig>,
tool_launcher_configured: bool,
) -> Result<()> {
// Settings load is a synchronous config read; keep it off the async
// worker per the blocking-call convention.
let mut settings = tokio::task::spawn_blocking(McpServerSettings::load)
let settings = tokio::task::spawn_blocking(McpServerSettings::load)
.await
.context("MCP server settings task failed")??;
if tool_launcher_configured {
for name in settings.refuse_shell_tools() {
eprintln!(
"codewhale mcp server: not exposing '{name}': the managed configuration sets \
tool_launcher, and this server does not run commands through it."
);
}
}
let server = McpServer::new(workspace, settings, skills_dir, skills_config)?;
// stdout carries the protocol; the notice goes to stderr so an operator
// whose config lists write tools sees why they are missing.
@@ -927,21 +906,6 @@ mod tests {
);
}
#[test]
fn a_tool_launcher_refuses_shell_tools_even_when_the_operator_allows_them() {
let mut settings = McpServerSettings::from_toml(
"[server]\nexpose_tools = [\"file_read\", \"shell\", \"exec_shell\", \"Bash\"]\nrequire_approval = false\n",
)
.expect("parse config");
assert_eq!(settings.refuse_shell_tools(), vec!["shell", "exec_shell"]);
let server = test_server(PathBuf::from("."), settings);
let names: Vec<&str> = server.tools.iter().map(|tool| tool.name.as_ref()).collect();
assert_eq!(names, vec!["file_read"]);
for internal in ["exec_shell", "Bash", "bash"] {
assert!(server.registry.get(internal).is_none(), "{internal}");
}
}
#[test]
fn existing_config_without_require_approval_withholds_and_names_write_tools() {
let settings = McpServerSettings::from_toml(
+29 -102
View File
@@ -114,11 +114,9 @@ mod account;
mod auth;
mod automations;
mod avatars;
mod builtin_commands;
mod computer_display;
mod context;
mod diagnostics;
mod external_agent_options;
mod external_agents;
mod git;
mod jobs;
@@ -1323,7 +1321,6 @@ struct ThreadSummary {
preview: String,
model: String,
mode: String,
agent_preset: String,
workspace: PathBuf,
branch: Option<String>,
head: Option<String>,
@@ -1579,41 +1576,10 @@ struct RuntimeInfoResponse {
job_operation_store_id: Option<String>,
account: RuntimeAccountInfo,
experimental: RuntimeExperimentalCapabilities,
sandbox: RuntimeSandboxInfo,
// Backward-compatible alias kept for existing clients.
version: &'static str,
}
#[derive(Debug, Serialize)]
struct RuntimeSandboxInfo {
kind: String,
tool_launcher: bool,
}
async fn runtime_sandbox_info(state: &RuntimeApiState) -> RuntimeSandboxInfo {
let (prefer_bwrap, tool_launcher, denied_read_paths) = {
let cfg = state.config.read();
(
cfg.prefers_bwrap(),
cfg.tool_launcher.clone(),
codewhale_sandbox::read_guard::ReadDenylist::from_config(&cfg).subtree_paths(),
)
};
let launcher_configured = tool_launcher.is_some();
let kind = tokio::task::spawn_blocking(move || {
let mut manager = codewhale_sandbox::SandboxManager::with_bwrap_preference(prefer_bwrap);
manager.set_tool_launcher(tool_launcher);
manager.set_denied_read_subpaths(denied_read_paths);
manager.configured_sandbox().unwrap_or_default().to_string()
})
.await
.unwrap_or_else(|_| codewhale_sandbox::SandboxType::None.to_string());
RuntimeSandboxInfo {
kind,
tool_launcher: launcher_configured,
}
}
fn default_runtime_capabilities() -> RuntimeCapabilities {
RuntimeCapabilities {
client_token_intents: true,
@@ -1653,7 +1619,6 @@ fn default_runtime_capabilities() -> RuntimeCapabilities {
worker_runtime: true,
fleet_run_create: true,
thread_fleet_members: true,
thread_fleet_member_durable_operations_v1: true,
fleet_run_start: true,
fleet_event_replay: true,
fleet_event_stream: true,
@@ -2067,7 +2032,7 @@ async fn admit_runtime_host(
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let probe = match crate::daemon_client::probe_owner_for_host_startup(
config_path.clone(), selected_socket.clone(), &selected_store,
config_path.clone(), selected_socket.clone(),
).await {
Err(error) if error.is::<PublicationChangedBeforeAttach>() => {
tokio::time::sleep(Duration::from_millis(25)).await;
@@ -3163,12 +3128,7 @@ pub fn build_router(state: RuntimeApiState) -> Router {
.route("/v1/threads/{id}/context", get(context::get_thread_context))
.route(
"/v1/threads/{id}/members",
post(members::start_thread_member)
.layer(DefaultBodyLimit::max(members::MAX_MEMBER_REQUEST_BYTES)),
)
.route(
"/v1/threads/{id}/members/operations/{operation_key}",
get(members::get_member_operation),
post(members::start_thread_member),
)
.route("/v1/threads/{id}/plan", get(plans::get_thread_plan))
.route("/v1/threads/{id}/todo", get(plans::get_thread_todo))
@@ -3315,13 +3275,8 @@ pub fn build_router(state: RuntimeApiState) -> Router {
.route("/v1/tasks/{id}", get(get_task))
.route("/v1/tasks/{id}/cancel", post(cancel_task))
.route("/v1/skills", get(list_skills))
.route("/v1/modes", get(list_modes))
.route("/v1/commands", get(list_commands))
.route("/v1/threads/{id}/commands", post(run_thread_command))
.route(
"/v1/threads/{id}/commands/builtin",
post(builtin_commands::run_builtin_command),
)
.route(
"/v1/threads/{id}/commands/{operation_key}",
get(get_thread_command).delete(cancel_thread_command),
@@ -3413,10 +3368,6 @@ pub fn build_router(state: RuntimeApiState) -> Router {
"/v1/apps/plugins/{selector}/ui/{*path}",
get(plugins::get_plugin_ui_asset),
)
.route(
"/v1/apps/plugins/{selector}/routes/{*path}",
any(plugins::plugin_route_bridge),
)
.route(
"/v1/apps/plugins/{selector}/update",
post(plugins::update_plugin_api),
@@ -3511,14 +3462,6 @@ pub fn build_router(state: RuntimeApiState) -> Router {
"/v1/agents/external",
get(external_agents::list_external_agents),
)
.route(
"/v1/agents/external/quota",
get(external_agents::get_external_agent_quota),
)
.route(
"/v1/agents/external/{id}/options",
get(external_agent_options::get_external_agent_options),
)
.route("/v1/providers", get(list_providers))
.route("/v1/providers/{id}/models", get(list_provider_models))
.route(
@@ -3937,7 +3880,7 @@ async fn create_thread(
)
.await
.map_err(|e| {
if let Some(refusal) = external_agent_refusal(&e).or_else(|| mode_refusal(&e)) {
if let Some(refusal) = external_agent_refusal(&e) {
refusal
} else if e
.is::<codewhale_engine::runtime_threads::manager::RuntimeThreadCreateConflict>()
@@ -4186,10 +4129,6 @@ async fn list_threads_summary(
preview,
model: thread.model,
mode: thread.mode,
agent_preset: codewhale_engine::conversation_modes::effective_id(
thread.agent_preset.as_deref(),
)
.to_string(),
branch: workspace_git.and_then(|git| git.branch.clone()),
head: workspace_git.and_then(|git| git.head.clone()),
dirty: workspace_git.is_some_and(|git| git.dirty),
@@ -6254,17 +6193,6 @@ async fn list_hooks(
}))
}
async fn list_modes(
State(state): State<RuntimeApiState>,
) -> Json<codewhale_engine::conversation_modes::ConversationModeTable> {
Json(
codewhale_engine::conversation_modes::current_table(
state.runtime_threads.extension_host_options(),
)
.await,
)
}
async fn list_skills(
State(state): State<RuntimeApiState>,
) -> Result<Json<SkillsResponse>, ApiError> {
@@ -7131,7 +7059,6 @@ async fn runtime_info(
capabilities.fleet_run_create = !session_only;
capabilities.fleet_run_start = !session_only;
capabilities.fleet_local_target = !session_only;
let sandbox = runtime_sandbox_info(&state).await;
Json(RuntimeInfoResponse {
service: "codewhale-runtime-api",
runtime_api_version: RUNTIME_API_VERSION,
@@ -7146,7 +7073,6 @@ async fn runtime_info(
.then(|| state.runtime_threads.job_operation_store_id().to_string()),
account,
experimental: RuntimeExperimentalCapabilities::default(),
sandbox,
version,
})
}
@@ -9285,13 +9211,14 @@ async fn preview_patch_undo_thread_turn(
.iter()
.map(|turn| turn.turn_id.clone())
.collect();
let trusted = thread.trust_mode || thread.auto_approve;
#[cfg(any(test, feature = "test-support"))]
let env_ticket = codewhale_engine::test_support::env_scope_ticket();
let (result, paths) = tokio::task::spawn_blocking(move || {
let _reservation = _reservation;
#[cfg(any(test, feature = "test-support"))]
let _membership = codewhale_engine::test_support::join_env_scope(env_ticket);
patch_undo_workspace_files_impl(&thread.workspace, &dropped_turns, true, None)
patch_undo_workspace_files_impl(&thread.workspace, &dropped_turns, trusted, true, None)
})
.await
.map_err(|error| ApiError::internal(format!("Patch undo preview failed: {error}")))??;
@@ -9328,6 +9255,10 @@ async fn patch_undo_thread_turn(
// Validate the selected turn/history before touching any file, so an invalid
// undo request cannot leave a half-applied workspace.
let prepared = prepare_patch_undo(&state, &id, &req).await?;
// File rollback is a workspace mutation, so it needs the trust the
// TUI's `/undo` requires. Read from the thread's own record: the
// client does not get to assert it.
let trusted = thread.trust_mode || thread.auto_approve;
let workspace = thread.workspace.clone();
// The restore points come from the dropped turns' own records, not
// from the thread's saved-session binding or a scan of the shared
@@ -9339,7 +9270,7 @@ async fn patch_undo_thread_turn(
let patch_result = tokio::task::spawn_blocking(move || {
#[cfg(any(test, feature = "test-support"))]
let _membership = codewhale_engine::test_support::join_env_scope(env_ticket);
patch_undo_workspace_files_impl(&workspace, &dropped_turns, false, req.expected_paths.as_deref()).map(|(result, _)| result)
patch_undo_workspace_files_impl(&workspace, &dropped_turns, trusted, false, req.expected_paths.as_deref()).map(|(result, _)| result)
})
.await
.map_err(|e| ApiError::internal(format!("Patch undo task failed: {e}")))??;
@@ -9382,6 +9313,7 @@ const PATCH_UNDO_NO_RESTORE_POINT: &str = "restore_point_unavailable";
const PATCH_UNDO_RESTORE_POINT_PRUNED: &str = "restore_point_pruned";
const PATCH_UNDO_PATH_NOT_SNAPSHOTTED: &str = "path_not_snapshotted";
const PATCH_UNDO_WORKSPACE_CHANGED: &str = "workspace_changed_since_turn";
const PATCH_UNDO_UNTRUSTED: &str = "restore_requires_trust";
const PATCH_UNDO_WORKSPACE_UNAVAILABLE: &str = "workspace_unavailable";
/// One pre-turn → post-turn window of a dropped turn, resolved to the trees
@@ -9613,23 +9545,21 @@ fn no_restore_point(turn_id: &str, why: &str) -> ApiError {
/// point, or a path changed since the turn is a `409` with a stable
/// `error.code`, never a `201` that forks while the files stay changed.
///
/// # Posture
///
/// No trust mode or Full Access is required. Undo reverses only what the
/// dropped turns' own tool calls wrote, and only while every such path still
/// holds exactly the bytes the turn left; the same ownership and later-edit
/// proofs refuse anything else, so the default posture cannot lose work the
/// turn did not make.
/// `trusted` mirrors the gate the TUI's `patch_undo()` applies
/// (`yolo || trust_mode`), evaluated once a real change is known.
pub fn patch_undo_workspace_files(
workspace: &FsPath,
dropped_turns: &[codewhale_engine::runtime_threads::manager::DroppedTurnSnapshots],
trusted: bool,
) -> Result<PatchUndoResult, ApiError> {
patch_undo_workspace_files_impl(workspace, dropped_turns, false, None).map(|(result, _)| result)
patch_undo_workspace_files_impl(workspace, dropped_turns, trusted, false, None)
.map(|(result, _)| result)
}
fn patch_undo_workspace_files_impl(
workspace: &FsPath,
dropped_turns: &[codewhale_engine::runtime_threads::manager::DroppedTurnSnapshots],
trusted: bool,
preview: bool,
expected_paths: Option<&[String]>,
) -> Result<(PatchUndoResult, Vec<String>), ApiError> {
@@ -9886,6 +9816,17 @@ fn patch_undo_workspace_files_impl(
));
}
// Restoring is a workspace mutation. Gate it exactly where the TUI gates
// it — after a real, owned change is known — so the two surfaces cannot
// drift into "one refuses, the other half-undoes".
if !trusted {
return Err(ApiError::conflict(
"Refusing to undo workspace files outside trusted mode. \
Turn on /trust or switch this thread to Full Access, then undo again.",
)
.with_code(PATCH_UNDO_UNTRUSTED));
}
let paths: Vec<String> = to_restore
.iter()
.map(|(path, _, _)| path.display().to_string())
@@ -14846,20 +14787,6 @@ fn map_automation_err(err: anyhow::Error) -> ApiError {
}
}
fn mode_refusal(err: &anyhow::Error) -> Option<ApiError> {
use codewhale_engine::conversation_modes::ModeRefusal;
let error = err.downcast_ref::<ModeRefusal>()?;
Some(ApiError {
status: match error.code {
ModeRefusal::MODE_UNAVAILABLE => StatusCode::FAILED_DEPENDENCY,
ModeRefusal::MODE_LOCKED => StatusCode::CONFLICT,
_ => StatusCode::BAD_REQUEST,
},
message: error.message.clone(),
code: Some(error.code),
})
}
fn external_agent_refusal(err: &anyhow::Error) -> Option<ApiError> {
use codewhale_engine::fleet::agents::ExecutorUnavailable;
let error = err.downcast_ref::<ExecutorUnavailable>()?;
@@ -14875,7 +14802,7 @@ fn external_agent_refusal(err: &anyhow::Error) -> Option<ApiError> {
}
fn map_thread_err(err: anyhow::Error) -> ApiError {
if let Some(refusal) = external_agent_refusal(&err).or_else(|| mode_refusal(&err)) {
if let Some(refusal) = external_agent_refusal(&err) {
return refusal;
}
if let Some(error) = err.downcast_ref::<codewhale_engine::runtime_threads::manager::RuntimeTurnOperationLookupError>() {
@@ -1,255 +0,0 @@
//! `POST /v1/threads/{id}/commands/builtin` — execute a terminal built-in
//! command against a thread, remotely.
//!
//! The thread's state is assembled into the engine's
//! [`BuiltinCommandHostSnapshot`] (contract projections included) and handed
//! to the installed command catalog, whose terminal-host implementation maps
//! it into the facet envelope and runs the portable handlers. Which commands
//! this serves is the host's decision (`builtin_execution::SERVED`); a name
//! outside that set answers 404 the same way an unknown name does, so the
//! remote surface can never widen without the host widening it first.
//!
//! Phase 1 notes: executions are not receipt-tracked (the phase-1 set is
//! read-only — every served handler is pure over the snapshot), and the
//! `text_only` flag reports commands that also asked the terminal host for an
//! action, which a remote client cannot perform.
use axum::Json;
use axum::extract::{Path, State};
use codewhale_command_contract::facets::{
DebugCostProjection, DebugRouteCost, DebugSystemPrompt, DebugTokenProjection,
};
use codewhale_command_contract::types::{CommandCurrency, CommandMode};
use codewhale_engine::command_catalog::{self, BuiltinCommandHostSnapshot};
use codewhale_models::SystemPrompt;
use serde::Deserialize;
use super::{ApiError, RuntimeApiState};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct BuiltinCommandApiRequest {
/// The command name (canonical or alias), with or without the slash.
pub name: String,
/// The argument tail after the command word, if any.
#[serde(default)]
pub args: Option<String>,
}
#[derive(serde::Serialize)]
pub(super) struct BuiltinCommandApiResponse {
pub name: String,
pub text: String,
pub is_error: bool,
/// `false` when the command also asked the terminal host for an action
/// the remote client cannot perform.
pub text_only: bool,
}
pub(super) async fn run_builtin_command(
State(state): State<RuntimeApiState>,
Path(thread_id): Path<String>,
Json(request): Json<BuiltinCommandApiRequest>,
) -> Result<Json<BuiltinCommandApiResponse>, ApiError> {
let catalog = command_catalog::installed()
.ok_or_else(|| ApiError::internal("command catalog is not installed"))?;
// Refuse a name outside the host's remote surface before reading any
// thread state: an unknown command and a known-but-unserved one get the
// same answer, and neither can be distinguished by what the read says
// about the daemon's idle threads.
if !catalog.serves_builtin(&request.name) {
return Err(not_served(&request.name));
}
let thread = state
.runtime_threads
.get_thread(&thread_id)
.await
.map_err(super::map_thread_err)?;
let snapshot = assemble_snapshot(&state, &thread_id, &thread).await?;
match catalog.execute_builtin(&request.name, request.args.as_deref(), &snapshot) {
Some(execution) => Ok(Json(BuiltinCommandApiResponse {
name: execution.name,
text: execution.text,
is_error: execution.is_error,
text_only: execution.text_only,
})),
// The host refused the name: the same answer an unknown command gets.
None => Err(not_served(&request.name)),
}
}
fn not_served(name: &str) -> ApiError {
const MAX_ECHOED_NAME_CHARS: usize = 64;
let shown: String = name.chars().take(MAX_ECHOED_NAME_CHARS).collect();
let ellipsis = if shown.len() < name.len() { "..." } else { "" };
ApiError::not_found(format!(
"no remotely executable builtin command '{shown}{ellipsis}'"
))
}
/// Assemble the host snapshot for one thread from the record, the live
/// engine's context budget, the usage aggregate, and the canonical session
/// document. Every projection field is filled from measured data or left at
/// its honest absence encoding; nothing is estimated into place.
async fn assemble_snapshot(
state: &RuntimeApiState,
thread_id: &str,
thread: &codewhale_engine::runtime_threads::ThreadRecord,
) -> Result<BuiltinCommandHostSnapshot, ApiError> {
// The live engine carries the context budget; an idle daemon thread has
// no honest context estimate, so the served diagnostics refuse rather
// than print zeros.
let engine = state
.runtime_threads
.loaded_engine(thread_id)
.await
.ok_or_else(|| {
ApiError::conflict("this thread's engine is not loaded; send a message first")
})?;
let budget = engine
.get_context_budget()
.await
.map_err(super::map_thread_err)?
.ok_or_else(|| {
ApiError::conflict("this thread has no live context estimate yet; send a message first")
})?;
let usage = state
.runtime_threads
.aggregate_usage_for_thread(thread_id)
.await
.map_err(super::map_thread_err)?;
let parent = &usage.parent;
let children = &usage.routed_children;
let combined = usage.combined();
// The daemon tracks no UI chat history (that is the client's layer), so
// the chat count is a true zero; the model transcript and the effective
// system prompt come from the live engine session.
let session = engine
.get_session_snapshot()
.await
.map_err(|err| ApiError::internal(format!("engine session snapshot unavailable: {err}")))?;
let api_message_count = session.messages.len();
let chat_message_count = 0;
// Currency follows the same rule the TUI's cost display applies, so the
// same config answers the same way on both surfaces: a Simplified-Chinese
// UI reading the default "usd" shows CNY, and every other spelling goes
// through the canonical parser (which accepts rmb and yuan) rather than a
// bare string compare. The CNY column is the provider-published subtotal
// only; a USD-picked currency keeps the authoritative USD numbers.
#[cfg(test)]
let env_ticket = codewhale_runtime::test_support::env_scope_ticket();
let settings = tokio::task::spawn_blocking(move || {
#[cfg(test)]
let _membership = codewhale_runtime::test_support::join_env_scope(env_ticket);
codewhale_runtime::settings::Settings::load_read_only()
})
.await
.map_err(|err| ApiError::internal(format!("settings task failed: {err}")))?
.map_err(|err| ApiError::internal(format!("settings unavailable: {err}")))?;
let locale = codewhale_localization::resolve_locale(&settings.locale);
let currency = match (settings.cost_currency.as_str(), locale.tag()) {
("usd", "zh-Hans") => CommandCurrency::Cny,
_ => match codewhale_config::pricing::CostCurrency::from_setting(&settings.cost_currency) {
Some(codewhale_config::pricing::CostCurrency::Cny) => CommandCurrency::Cny,
_ => CommandCurrency::Usd,
},
};
let currency_amount =
|totals: &codewhale_engine::runtime_threads::manager::UsageTotals| match currency {
CommandCurrency::Cny => totals.cost_cny,
CommandCurrency::Usd => totals.cost_usd,
};
let parent_amount = currency_amount(parent);
let children_amount = currency_amount(children);
let total_amount = currency_amount(&combined);
let (priced_turns, unpriced_turns, unpriced_reasons) = match currency {
CommandCurrency::Cny => (
combined.cny_priced_turns,
combined.cny_unpriced_turns,
&combined.cny_unpriced_reasons,
),
CommandCurrency::Usd => (
combined.priced_turns,
combined.unpriced_turns,
&combined.unpriced_reasons,
),
};
let mode = CommandMode::parse(&session.mode).unwrap_or(CommandMode::Agent);
let mode_label = codewhale_config::AppMode::from_setting(&session.mode)
.label()
.to_string();
let system_prompt = match session.system_prompt {
None => DebugSystemPrompt::None,
Some(SystemPrompt::Text(text)) => DebugSystemPrompt::Text(text),
Some(SystemPrompt::Blocks(blocks)) => {
DebugSystemPrompt::Blocks(blocks.into_iter().map(|block| block.text).collect())
}
};
let cost = DebugCostProjection {
currency,
// The combined subtotal is the authoritative total, and it is by
// construction the parent and children amounts added up; the
// terminal's #244 reconciliation floor only exists because its
// display total and its recomputed components can drift apart. The
// remote aggregate cannot drift from itself, so there is no floor to
// report and none is invented.
total: total_amount,
parent_turns: parent_amount,
subagents: children_amount,
display_floor: 0.0,
priced_turns: priced_turns.clamp(0, u32::MAX as u64) as u32,
unpriced_turns: unpriced_turns.clamp(0, u32::MAX as u64) as u32,
legacy_coverage_unknown: !combined.cost_complete,
// Pricing-provenance bookkeeping (user-declared estimates, live
// defects, route receipts) is terminal-session state the daemon
// does not track; the honest encoding is "none recorded".
user_declared_estimates: false,
// Per-route attribution needs per-turn provider identities, which
// the remote snapshot does not assemble yet; the coverage counts
// above stay authoritative. With no route rows, no turn is itemized:
// claiming otherwise would make the renderer state a breakdown it
// cannot show.
itemized_turns: 0,
route_amounts: Vec::<DebugRouteCost>::new(),
turn_history_capacity: 0,
unpriced_reason_labels: unpriced_reasons.iter().cloned().collect(),
unpriced_classes: combined.unpriced_classes.iter().cloned().collect(),
pricing_provenances: Vec::new(),
live_pricing_defects: Vec::new(),
unusable_pricing_defects: Vec::new(),
route_receipts: Vec::new(),
};
Ok(BuiltinCommandHostSnapshot {
mode,
mode_label,
locale,
model: thread.model.clone(),
system_prompt,
tokens: DebugTokenProjection {
active_context_used: (budget.input_tokens as usize).min(budget.window_tokens as usize),
context_window: budget.window_tokens.clamp(0, u32::MAX as u64) as u32,
// The context budget carries no per-turn telemetry, so the
// last-turn columns take their honest absence encoding rather
// than a stale or fabricated value.
last_input: None,
last_output: None,
cache_hit: None,
cache_miss: None,
total_tokens: combined.input_tokens.saturating_add(combined.output_tokens),
cache_write_tokens: combined.cache_write_tokens,
api_message_count,
chat_message_count,
model: thread.model.clone(),
cost,
},
})
}
@@ -1,72 +0,0 @@
use std::path::PathBuf;
use axum::Json;
use axum::extract::{Path, Query, State};
use serde::Deserialize;
use codewhale_engine::fleet::acp::AgentOptions;
use codewhale_engine::fleet::agents::ExecutorUnavailable;
use super::{ApiError, RuntimeApiState, external_agent_refusal};
const MAX_AGENT_ID_BYTES: usize = 64;
const MAX_CWD_BYTES: usize = 4096;
#[derive(Debug, Deserialize)]
pub(super) struct OptionsQuery {
cwd: Option<PathBuf>,
}
fn valid_agent_id(id: &str) -> bool {
!id.is_empty()
&& id.len() <= MAX_AGENT_ID_BYTES
&& id
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_'))
}
pub(super) async fn get_external_agent_options(
State(state): State<RuntimeApiState>,
Path(id): Path<String>,
Query(query): Query<OptionsQuery>,
) -> Result<Json<AgentOptions>, ApiError> {
if !valid_agent_id(&id) {
return Err(ApiError::bad_request(
"the agent id must name an agent from GET /v1/agents/external",
));
}
let cwd = query
.cwd
.ok_or_else(|| ApiError::bad_request("cwd is required"))?;
let text = cwd.to_string_lossy();
if text.len() > MAX_CWD_BYTES || text.chars().any(char::is_control) || !cwd.is_absolute() {
return Err(ApiError::bad_request(
"cwd must be an absolute directory path",
));
}
let probe = cwd.clone();
let is_dir = tokio::task::spawn_blocking(move || probe.is_dir())
.await
.map_err(|_| ApiError::internal("cwd check failed"))?;
if !is_dir {
return Err(ApiError::not_found(
"cwd is not a directory on this computer",
));
}
match state
.runtime_threads
.external_agent_options(&id, &cwd)
.await
{
Ok(options) => Ok(Json(options)),
Err(error) => {
let mut refusal = external_agent_refusal(&error);
if let Some(refusal) = refusal.as_mut()
&& refusal.code == Some(ExecutorUnavailable::UNKNOWN_AGENT)
{
refusal.status = axum::http::StatusCode::NOT_FOUND;
}
Err(refusal.unwrap_or_else(|| ApiError::internal(error.to_string())))
}
}
}
@@ -14,11 +14,10 @@ const PROBE_REAP_TIMEOUT: Duration = Duration::from_secs(2);
const SILENT_HANDSHAKE: &str = "It did not answer the Agent Client Protocol handshake.";
use codewhale_engine::fleet::agents::{
AGENTS, AgentQuota, ExecutorUnavailable, ExternalAgent, QuotaGate, QuotaSource, QuotaUnknown,
below_minimum, cli_version, foreign_command, local_signin_quota, not_installed, resolve,
AGENTS, ExecutorUnavailable, ExternalAgent, below_minimum, cli_version, foreign_command,
not_installed, resolve,
};
use codewhale_runtime::process_tree::ProcessTree;
use codewhale_runtime::settings::{AgentSettings, Settings};
#[derive(Debug)]
enum Handshake {
@@ -275,75 +274,6 @@ pub(super) async fn list_external_agents() -> Json<Value> {
Json(json!({ "agents": found }))
}
fn quota_json(quota: &AgentQuota) -> Value {
match quota {
AgentQuota::Known { source, windows } => json!({
"status": "known",
"source": source.as_str(),
"windows": windows
.iter()
.map(|window| json!({
"name": window.name,
"used_percent": window.used_percent,
"resets_at": window.resets_at,
}))
.collect::<Vec<_>>(),
}),
AgentQuota::Unknown(reason) => json!({
"status": "unknown",
"reason": reason.as_str(),
}),
}
}
async fn agent_quota_report(agents: &AgentSettings) -> Value {
let mut entries = Vec::with_capacity(AGENTS.len());
for agent in AGENTS {
let choice = agents.quota(agent.id);
let gate = QuotaGate {
enabled: choice.enabled,
consented: choice.consented_at.is_some(),
};
let quota = local_signin_quota(agent, gate).await;
entries.push(json!({
"id": agent.id,
"name": agent.name,
"quota": quota_json(&quota),
}));
}
for id in agents
.quota
.keys()
.filter(|id| !AGENTS.iter().any(|agent| agent.id == id.as_str()))
{
entries.push(json!({
"id": id,
"name": null,
"quota": quota_json(&AgentQuota::Unknown(QuotaUnknown::UnknownAgent)),
}));
}
json!({
"default_source": QuotaSource::AgentReported.as_str(),
"agents": entries,
})
}
pub(super) async fn get_external_agent_quota() -> Json<Value> {
#[cfg(any(test, feature = "test-support"))]
let env_ticket = codewhale_engine::test_support::env_scope_ticket();
let agents = tokio::task::spawn_blocking(move || {
#[cfg(any(test, feature = "test-support"))]
let _membership = codewhale_engine::test_support::join_env_scope(env_ticket);
Settings::load_read_only()
})
.await
.ok()
.and_then(Result::ok)
.map(|settings| settings.agents)
.unwrap_or_default();
Json(agent_quota_report(&agents).await)
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
+2 -20
View File
@@ -515,11 +515,9 @@ fn parse_porcelain(porcelain: &str) -> Vec<GitFileEntry> {
}
let index = record.as_bytes()[0] as char;
let worktree = record.as_bytes()[1] as char;
let Some(path) = record.get(3..).map(str::to_string) else {
continue;
};
let path = record[3..].to_string();
let mut old_path = None;
if matches!(index, 'R' | 'C') || matches!(worktree, 'R' | 'C') {
if matches!(index, 'R' | 'C') {
old_path = records.next().map(str::to_string);
}
entries.push(GitFileEntry {
@@ -2911,22 +2909,6 @@ mod tests {
);
}
#[test]
fn worktree_rename_consumes_its_original_path_record() {
let rows = parse_porcelain(" R new.md\0ab说明.md\0 M a.txt\0");
let rows: Vec<_> = rows
.iter()
.map(|row| (row.path.as_str(), row.status, row.old_path.as_deref()))
.collect();
assert_eq!(
rows,
[
("new.md", "renamed", Some("ab说明.md")),
("a.txt", "modified", None),
]
);
}
pub(super) fn repo() -> tempfile::TempDir {
let tmp = tempfile::tempdir().expect("tempdir");
let dir = tmp.path();
+43 -373
View File
@@ -3,20 +3,12 @@ use std::time::Duration;
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use serde::{Deserialize, Serialize};
use serde::Deserialize;
use serde_json::{Value, json};
use codewhale_engine::runtime_threads::job_operations::{
JobOperationTransaction, MEMBER_ABANDONED, MEMBER_ACCEPTED, MEMBER_RESERVED, MEMBER_UNKNOWN,
MemberOperation, MemberOperationRecord, member_request_fingerprint, new_member_agent_id,
valid_member_key,
};
use codewhale_engine::tools::subagent::AgentWorkerRecord;
use super::jobs::operation_error;
use super::{ApiError, RuntimeApiState, map_thread_err};
const MEMBER_START_WAIT: Duration = Duration::from_secs(20);
pub(super) const MAX_MEMBER_REQUEST_BYTES: usize = 2 * 1024 * 1024;
const MAX_MEMBER_PROMPT_CHARS: usize = 256_000;
#[derive(Debug, Deserialize)]
@@ -27,148 +19,28 @@ pub(super) struct StartMemberRequest {
display_name: String,
prompt: String,
fleet: codewhale_engine::fleet::store::FleetFile,
#[serde(default)]
expected_store_id: Option<String>,
#[serde(default)]
request_fingerprint: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct MemberReceipt {
thread_id: String,
member_id: String,
operation_key: String,
request_fingerprint: String,
runtime_store_id: String,
agent_id: String,
state: String,
fn opaque(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 128
&& value.as_bytes()[0].is_ascii_alphanumeric()
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"._:-".contains(&byte))
}
impl MemberReceipt {
fn new(record: &MemberOperationRecord, state: &str) -> Self {
Self {
thread_id: record.operation.thread_id.clone(),
member_id: record.operation.member_id.clone(),
operation_key: record.operation.operation_key.clone(),
request_fingerprint: record.request_fingerprint.clone(),
runtime_store_id: record.operation.store_id.clone(),
agent_id: record.operation.agent_id.clone(),
state: state.to_string(),
}
}
fn status(&self) -> StatusCode {
if self.state == MEMBER_ACCEPTED {
StatusCode::OK
} else {
StatusCode::ACCEPTED
}
}
}
fn worker_proves(operation: &MemberOperation, worker: Option<&AgentWorkerRecord>) -> bool {
worker.is_some_and(|worker| {
worker.owner_session_id == operation.thread_id
&& worker.spec.worker_id == operation.agent_id
&& worker
.spec
.child_route
.as_ref()
.and_then(|route| route.requested_profile.as_deref())
== Some(operation.member_id.as_str())
})
}
fn project(
transaction: &JobOperationTransaction<'_>,
record: &mut MemberOperationRecord,
worker: Option<&AgentWorkerRecord>,
generation: &str,
) -> anyhow::Result<String> {
let proven = worker_proves(&record.operation, worker);
match record.operation.state.as_str() {
MEMBER_ACCEPTED if proven => Ok(MEMBER_ACCEPTED.to_string()),
MEMBER_ACCEPTED => Ok(MEMBER_UNKNOWN.to_string()),
MEMBER_RESERVED if proven => {
settle(transaction, record, MEMBER_ACCEPTED)?;
Ok(MEMBER_ACCEPTED.to_string())
}
MEMBER_RESERVED if record.owner_generation != generation => {
settle(transaction, record, MEMBER_ABANDONED)?;
Ok(MEMBER_ABANDONED.to_string())
}
MEMBER_RESERVED => Ok(MEMBER_UNKNOWN.to_string()),
state => Ok(state.to_string()),
}
}
fn settle(
transaction: &JobOperationTransaction<'_>,
record: &mut MemberOperationRecord,
state: &str,
) -> anyhow::Result<()> {
record.operation.state = state.to_string();
record.operation.updated_at_ms = chrono::Utc::now()
.timestamp_millis()
.max(record.operation.created_at_ms);
transaction.save_member(record)
}
async fn member_worker(
state: &RuntimeApiState,
thread_id: &str,
agent_id: &str,
) -> Option<AgentWorkerRecord> {
state
.sub_agent_manager
.read()
.await
.get_worker_record_for_session(thread_id, agent_id)
}
async fn settle_outcome(
state: RuntimeApiState,
operation: &MemberOperation,
outcome: Option<Result<String, String>>,
) -> Result<(), ApiError> {
let worker = match &outcome {
Some(Ok(agent_id)) => member_worker(&state, &operation.thread_id, agent_id).await,
_ => None,
};
let id = operation.id.clone();
let store = state.runtime_threads.job_operation_store();
tokio::task::spawn_blocking(move || {
store.with_job_operations(|transaction| {
let Some(mut record) = transaction.get_member(&id)? else {
return Ok(());
};
if record.operation.state != MEMBER_RESERVED {
return Ok(());
}
match outcome {
Some(Ok(agent_id))
if agent_id == record.operation.agent_id
&& worker_proves(&record.operation, worker.as_ref()) =>
{
settle(transaction, &mut record, MEMBER_ACCEPTED)
}
Some(Err(_)) => transaction.remove_member(&id),
_ => Ok(()),
}
})
})
.await
.map_err(|_| ApiError::internal("member operation settlement failed"))?
.map_err(operation_error)
}
fn validate(request: &StartMemberRequest) -> Result<(String, String), ApiError> {
if !valid_member_key(&request.operation_key) || !valid_member_key(&request.member_id) {
pub(super) async fn start_thread_member(
State(state): State<RuntimeApiState>,
Path(thread_id): Path<String>,
Json(request): Json<StartMemberRequest>,
) -> Result<(StatusCode, Json<Value>), ApiError> {
let display_name = request.display_name.trim();
if !opaque(&request.operation_key) || !opaque(&request.member_id) {
return Err(ApiError::bad_request(
"operation_key and member_id must be 1-128 URL-safe characters",
));
}
let display_name = request.display_name.trim();
if display_name.is_empty()
|| display_name.chars().count() > 80
|| display_name.chars().any(char::is_control)
@@ -183,249 +55,47 @@ fn validate(request: &StartMemberRequest) -> Result<(String, String), ApiError>
"prompt must contain 1-256000 characters",
));
}
Ok((display_name.to_string(), prompt.to_string()))
}
pub(super) async fn start_thread_member(
State(state): State<RuntimeApiState>,
Path(thread_id): Path<String>,
Json(request): Json<StartMemberRequest>,
) -> Result<(StatusCode, Json<MemberReceipt>), ApiError> {
let (display_name, prompt) = validate(&request)?;
let store_id = state.runtime_threads.job_operation_store_id().to_string();
if request
.expected_store_id
.as_deref()
.is_some_and(|expected| expected != store_id)
{
return Err(ApiError::conflict("member operation store changed")
.with_code("member_operation_store_changed"));
}
let fingerprint = member_request_fingerprint(
&thread_id,
&request.member_id,
&display_name,
&prompt,
&request.fleet,
)
.map_err(|_| ApiError::internal("member request fingerprint failed"))?;
if request
.request_fingerprint
.as_deref()
.is_some_and(|claimed| claimed != fingerprint)
{
return Err(
ApiError::bad_request("request_fingerprint does not match this request")
.with_code("member_request_fingerprint_mismatch"),
);
}
state
let engine = state
.runtime_threads
.get_thread(&thread_id)
.get_engine(&thread_id)
.await
.map_err(map_thread_err)?;
let generation = state
.runtime_threads
.job_operation_generation()
.map_err(operation_error)?;
let store = state.runtime_threads.job_operation_store();
let key = request.operation_key.clone();
let lookup_thread = thread_id.clone();
let existing = {
let store = store.clone();
tokio::task::spawn_blocking(move || {
store.with_job_operations(|transaction| {
let id = transaction.member_operation_id(&lookup_thread, &key)?;
transaction.get_member(&id)
})
})
.await
.map_err(|_| ApiError::internal("member operation lookup failed"))?
.map_err(operation_error)?
};
if let Some(existing) = existing {
if existing.request_fingerprint != fingerprint {
return Err(
ApiError::conflict("member operation key belongs to a different request")
.with_code("member_operation_mismatch"),
);
}
let receipt = replay(&state, existing, generation).await?;
if receipt.state == MEMBER_ABANDONED {
return Err(ApiError::conflict(
"member operation was abandoned before it started; use a new operation_key",
)
.with_code("member_operation_abandoned"));
}
return Ok((receipt.status(), Json(receipt)));
}
let reserve_thread = thread_id.clone();
let reserve_key = request.operation_key.clone();
let reserve_member = request.member_id.clone();
let reserve_fingerprint = fingerprint.clone();
let reserve_generation = generation.clone();
let reserved = {
let store = store.clone();
tokio::task::spawn_blocking(move || {
store.with_job_operations(|transaction| {
let id = transaction.member_operation_id(&reserve_thread, &reserve_key)?;
if let Some(existing) = transaction.get_member(&id)? {
return Ok(Err(existing));
}
let now = chrono::Utc::now().timestamp_millis();
let record = MemberOperationRecord {
schema_version: 1,
operation: MemberOperation {
id,
store_id,
thread_id: reserve_thread,
member_id: reserve_member,
operation_key: reserve_key,
agent_id: new_member_agent_id(),
state: MEMBER_RESERVED.to_string(),
created_at_ms: now,
updated_at_ms: now,
},
request_fingerprint: reserve_fingerprint,
owner_generation: reserve_generation,
};
transaction.save_member(&record)?;
Ok(Ok(record))
})
})
.await
.map_err(|_| ApiError::internal("member operation reservation failed"))?
.map_err(operation_error)?
};
let record = match reserved {
Ok(record) => record,
Err(existing) => {
if existing.request_fingerprint != fingerprint {
return Err(ApiError::conflict(
"member operation key belongs to a different request",
)
.with_code("member_operation_mismatch"));
}
let receipt = replay(&state, existing, generation).await?;
return Ok((receipt.status(), Json(receipt)));
}
};
let engine = match state.runtime_threads.get_engine(&thread_id).await {
Ok(engine) => engine,
Err(error) => {
settle_outcome(state.clone(), &record.operation, Some(Err(String::new()))).await?;
return Err(map_thread_err(error));
}
};
let (tx, mut rx) = tokio::sync::oneshot::channel();
if let Err(error) = engine
let (tx, rx) = tokio::sync::oneshot::channel();
engine
.send(codewhale_engine::core::ops::Op::StartFleetMember {
start: Box::new(codewhale_engine::tools::subagent::FleetMemberStart {
operation_key: request.operation_key.clone(),
fleet: request.fleet,
member_id: request.member_id.clone(),
display_name,
prompt,
reserved_agent_id: Some(record.operation.agent_id.clone()),
display_name: display_name.to_string(),
prompt: prompt.to_string(),
}),
tx: std::sync::Arc::new(std::sync::Mutex::new(Some(tx))),
})
.await
{
settle_outcome(state.clone(), &record.operation, Some(Err(String::new()))).await?;
return Err(ApiError::internal(format!(
"Failed to reach the thread's engine: {error}"
)));
}
match tokio::time::timeout(MEMBER_START_WAIT, &mut rx).await {
Ok(Ok(Ok(agent_id))) => {
let settled = settle_outcome(state.clone(), &record.operation, Some(Ok(agent_id)))
.await
.is_ok();
let receipt = if settled {
replay(&state, record.clone(), generation)
.await
.unwrap_or_else(|_| MemberReceipt::new(&record, MEMBER_UNKNOWN))
} else {
MemberReceipt::new(&record, MEMBER_UNKNOWN)
};
Ok((receipt.status(), Json(receipt)))
}
Ok(Ok(Err(message))) => {
settle_outcome(state.clone(), &record.operation, Some(Err(message.clone()))).await?;
Err(ApiError::conflict(message))
}
.map_err(|err| ApiError::internal(format!("Failed to reach the thread's engine: {err}")))?;
match tokio::time::timeout(MEMBER_START_WAIT, rx).await {
Ok(Ok(Ok(agent_id))) => Ok((
StatusCode::OK,
Json(json!({
"thread_id": thread_id,
"member_id": request.member_id,
"agent_id": agent_id,
"state": "started",
})),
)),
Ok(Ok(Err(message))) => Err(ApiError::conflict(message)),
Ok(Err(_)) => Err(ApiError::internal(
"The engine closed before starting the member",
)),
Err(_) => {
let operation = record.operation.clone();
let background = state.clone();
tokio::spawn(async move {
let outcome = rx.await.ok();
if let Err(error) = settle_outcome(background, &operation, outcome).await {
tracing::warn!(error = %error.message, "member operation settlement failed");
}
});
let receipt = MemberReceipt::new(&record, MEMBER_UNKNOWN);
Ok((receipt.status(), Json(receipt)))
}
Err(_) => Ok((
StatusCode::ACCEPTED,
Json(json!({
"thread_id": thread_id,
"member_id": request.member_id,
"operation_key": request.operation_key,
"state": "queued",
})),
)),
}
}
async fn replay(
state: &RuntimeApiState,
record: MemberOperationRecord,
generation: String,
) -> Result<MemberReceipt, ApiError> {
let worker = member_worker(
state,
&record.operation.thread_id,
&record.operation.agent_id,
)
.await;
let store = state.runtime_threads.job_operation_store();
let id = record.operation.id.clone();
tokio::task::spawn_blocking(move || {
store.with_job_operations(|transaction| {
let mut record = transaction.get_member(&id)?.unwrap_or(record);
let state = project(transaction, &mut record, worker.as_ref(), &generation)?;
Ok(MemberReceipt::new(&record, &state))
})
})
.await
.map_err(|_| ApiError::internal("member operation lookup failed"))?
.map_err(operation_error)
}
pub(super) async fn get_member_operation(
State(state): State<RuntimeApiState>,
Path((thread_id, key)): Path<(String, String)>,
) -> Result<Json<MemberReceipt>, ApiError> {
if !valid_member_key(&key) {
return Err(ApiError::bad_request("invalid member operation key"));
}
state
.runtime_threads
.get_thread(&thread_id)
.await
.map_err(map_thread_err)?;
let generation = state
.runtime_threads
.job_operation_generation()
.map_err(operation_error)?;
let store = state.runtime_threads.job_operation_store();
let record = tokio::task::spawn_blocking(move || {
store.with_job_operations(|transaction| {
let id = transaction.member_operation_id(&thread_id, &key)?;
transaction.get_member(&id)
})
})
.await
.map_err(|_| ApiError::internal("member operation lookup failed"))?
.map_err(operation_error)?
.ok_or_else(|| ApiError::not_found("member operation not found"))?;
Ok(Json(replay(&state, record, generation).await?))
}
+42 -602
View File
@@ -29,7 +29,6 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use codewhale_plugins::host_services::{PersonVia, PluginApprover, ReviewApproval};
use codewhale_plugins::marketplace::document::{
CatalogInstallResolution, load_catalog_document, resolve_candidate_install,
};
@@ -43,102 +42,6 @@ use super::{ApiError, RuntimeApiState};
const PLUGIN_UI_MAX_BYTES: u64 = 8 * 1024 * 1024;
const PLUGIN_UI_SLOT: &str = "customize.plugins.detail";
const PLUGIN_UI_SEATS: [&str; 6] = [
PLUGIN_UI_SLOT,
"conversation.composer.dock",
"conversation.chat.node",
"workpane.panel",
"sidebar.section",
"command.row",
];
const DSH_BOOTSTRAP_ENTRY: &str = "__codewhale_dsh_bootstrap.js";
const DSH_FRAME_MODULES: [&str; 4] = [
"react",
"react-dom",
"react-dom/client",
"react/jsx-runtime",
];
const DSH_ROUTE_METHODS: [&str; 5] = ["GET", "POST", "PUT", "PATCH", "DELETE"];
enum DshSeat {
Seat(&'static str),
Unsupported(&'static str),
}
const DSH_SEAT_TABLE: [(&str, DshSeat); 30] = [
("plugins.bundle.config", DshSeat::Seat(PLUGIN_UI_SLOT)),
("plugins.row.config", DshSeat::Seat(PLUGIN_UI_SLOT)),
("plugins.tab", DshSeat::Seat(PLUGIN_UI_SLOT)),
("plugins.detail.section", DshSeat::Seat(PLUGIN_UI_SLOT)),
("settings.section", DshSeat::Seat(PLUGIN_UI_SLOT)),
("settings.plugin.item", DshSeat::Seat(PLUGIN_UI_SLOT)),
("settings.general.item", DshSeat::Seat(PLUGIN_UI_SLOT)),
("settings.plugins.tab", DshSeat::Seat(PLUGIN_UI_SLOT)),
(
"conversation.chat.node",
DshSeat::Seat("conversation.chat.node"),
),
(
"conversation.chat.turnTail",
DshSeat::Seat("conversation.chat.node"),
),
(
"conversation.chat.assistant-actions",
DshSeat::Seat("conversation.chat.node"),
),
(
"conversation.chat.text-interaction",
DshSeat::Seat("conversation.chat.node"),
),
(
"conversation.user.text.node",
DshSeat::Seat("conversation.chat.node"),
),
(
"tool.call.toolview",
DshSeat::Seat("conversation.chat.node"),
),
("conversation.view", DshSeat::Seat("conversation.chat.node")),
(
"conversation.input.dock",
DshSeat::Seat("conversation.composer.dock"),
),
(
"conversation.input.overlay",
DshSeat::Seat("conversation.composer.dock"),
),
(
"conversation.input.right",
DshSeat::Seat("conversation.composer.dock"),
),
(
"conversation.composer.dock",
DshSeat::Seat("conversation.composer.dock"),
),
("sidebar.right.pane.tab", DshSeat::Seat("workpane.panel")),
("main.conversation", DshSeat::Seat("workpane.panel")),
("main.page-menu", DshSeat::Seat("workpane.panel")),
("sidebar.panellist", DshSeat::Seat("sidebar.section")),
("sidebar.workspaces", DshSeat::Seat("sidebar.section")),
("sidebar.footer.action", DshSeat::Seat("sidebar.section")),
(
"sidebar.session.row.leading",
DshSeat::Seat("sidebar.section"),
),
(
"sidebar.workspaces.session.row.action",
DshSeat::Seat("sidebar.section"),
),
(
"conversation.session.header.actions",
DshSeat::Unsupported("no ADE seat yet"),
),
(
"conversation.session.header.utilities",
DshSeat::Unsupported("no ADE seat yet"),
),
("contextMenu.icon", DshSeat::Unsupported("no ADE seat yet")),
];
// ---------------------------------------------------------------------------
// Response shapes
@@ -273,20 +176,9 @@ pub(super) struct PluginActionResponse {
pub(super) note: Option<&'static str>,
}
#[derive(Debug, Serialize)]
pub(super) struct PluginUiBridge {
pub(super) kind: &'static str,
pub(super) dsh_version: String,
pub(super) compatibility_digest: String,
}
#[derive(Debug, Serialize)]
pub(super) struct PluginUiSlotResponse {
pub(super) slot: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) dsh_slot: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) bridge: Option<PluginUiBridge>,
pub(super) base: String,
pub(super) entry: String,
pub(super) revision: String,
@@ -317,7 +209,6 @@ pub(super) struct InstallPluginRequest {
#[derive(Debug, Deserialize)]
pub(super) struct PluginUiQuery {
pub(super) slot: Option<String>,
pub(super) dsh_slot: Option<String>,
}
#[derive(Debug, Deserialize)]
@@ -628,18 +519,6 @@ struct PluginUiGrant {
ui_prefix: PathBuf,
file_hashes: Arc<BTreeMap<PathBuf, String>>,
expires: std::time::Instant,
dsh: Option<Arc<DshServed>>,
}
struct DshClosure {
package: String,
entry: String,
files: BTreeMap<String, String>,
host_provided: Vec<String>,
}
struct DshServed {
closure: DshClosure,
}
#[derive(Default)]
@@ -669,12 +548,6 @@ impl PluginUiGrants {
}
}
fn revoke_selector(&self, selector: &str) {
self.entries
.lock()
.retain(|_, value| value.selector != selector);
}
fn get(&self, revision: &str) -> Option<PluginUiGrant> {
let mut entries = self.entries.lock();
let now = std::time::Instant::now();
@@ -688,8 +561,7 @@ fn ui_file_refusal(plugin: &LoadedPlugin, display: &str, error: UiFileError) ->
UiFileError::Missing => ApiError::not_found(format!(
"plugin '{}' has no staged file '{display}'",
plugin.name()
))
.with_code("plugin_ui_file_not_reviewed"),
)),
UiFileError::TooLarge => ApiError::payload_too_large(format!(
"plugin '{}' file '{display}' exceeds the 8 MiB plugin UI limit",
plugin.name()
@@ -784,15 +656,6 @@ fn admit_ui_grant(state: &RuntimeApiState, grant: &PluginUiGrant) -> Result<(),
Ok(())
}
fn valid_dsh_slot_key(key: &str) -> bool {
let mut chars = key.chars();
key.len() <= 128
&& chars
.next()
.is_some_and(|first| first.is_ascii_alphanumeric())
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}
fn ui_stale_revision() -> ApiError {
ApiError {
status: StatusCode::PRECONDITION_FAILED,
@@ -801,300 +664,10 @@ fn ui_stale_revision() -> ApiError {
}
}
struct PreparedPluginUi {
entry: String,
dsh_slot: Option<String>,
bridge: Option<PluginUiBridge>,
grant: PluginUiGrant,
}
fn seat_not_admitted(plugin: &LoadedPlugin, seat: &str, dsh_slot: Option<&str>) -> ApiError {
let key = dsh_slot
.map(|key| format!(" key '{key}'"))
.unwrap_or_default();
ApiError::not_found(format!(
"plugin '{}' has no admitted client for seat '{seat}'{key}",
plugin.name()
))
.with_code("plugin_ui_seat_not_admitted")
}
fn ui_unsupported(message: impl Into<String>) -> ApiError {
ApiError::bad_request(message).with_code("plugin_ui_unsupported")
}
fn sha256_hex(bytes: &[u8]) -> String {
Sha256::digest(bytes)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
fn dsh_client_closure(conversion: &Value) -> Option<DshClosure> {
let closure = conversion
.get("client_closures")?
.as_array()?
.iter()
.find(|closure| closure.get("root").and_then(Value::as_str) == Some(""))?;
let files = closure
.get("files")?
.as_object()?
.iter()
.map(|(path, hash)| Some((path.clone(), hash.as_str()?.to_string())))
.collect::<Option<BTreeMap<_, _>>>()?;
let entry = closure.get("entry")?.as_str()?.to_string();
if !files.contains_key(&entry) {
return None;
}
Some(DshClosure {
package: closure
.get("package")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
entry,
files,
host_provided: closure
.get("host_provided")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(|item| item.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default(),
})
}
fn verify_dsh_closure(
grant: &PluginUiGrant,
closure: &DshClosure,
) -> Result<Vec<(String, Vec<u8>)>, UiFileError> {
let mut verified = Vec::with_capacity(closure.files.len());
for (path, expected) in &closure.files {
let relative = ui_relative_path(path)
.map_err(|reason| UiFileError::Invalid(format!("closure file '{path}': {reason}")))?;
let bytes = verified_ui_file(grant, &relative)?;
if sha256_hex(&bytes) != *expected {
return Err(UiFileError::Invalid(format!(
"closure file '{path}' no longer matches its reviewed hash"
)));
}
verified.push((path.clone(), bytes));
}
Ok(verified)
}
fn has_esm_syntax(text: &str) -> bool {
text.contains("import.meta")
|| text.lines().any(|line| {
let line = line.trim_start();
[
"import ", "import{", "import\"", "import'", "export ", "export{", "export*",
]
.iter()
.any(|prefix| line.starts_with(prefix))
})
}
fn dsh_closure_unsupported(closure: &DshClosure, verified: &[(String, Vec<u8>)]) -> Option<String> {
let missing: Vec<&str> = closure
.host_provided
.iter()
.map(String::as_str)
.filter(|module| !DSH_FRAME_MODULES.contains(module))
.take(5)
.collect();
if !missing.is_empty() {
return Some(format!(
"this DSH client requires modules the plugin frame does not provide yet: {}",
missing.join(", ")
));
}
for (path, bytes) in verified {
let Ok(text) = std::str::from_utf8(bytes) else {
return Some(format!("closure file '{path}' is not UTF-8 text"));
};
if path.ends_with(".json") {
if serde_json::from_str::<Value>(text).is_err() {
return Some(format!("closure file '{path}' is not valid JSON"));
}
} else if has_esm_syntax(text) {
return Some(format!(
"closure file '{path}' uses ES module syntax; only CommonJS closures are served"
));
}
}
None
}
fn quoted_in(text: &str, key: &str) -> bool {
['"', '\'', '`']
.iter()
.any(|quote| text.contains(&format!("{quote}{key}{quote}")))
}
fn declared_dsh_keys(verified: &[(String, Vec<u8>)]) -> Vec<&'static (&'static str, DshSeat)> {
let texts: Vec<String> = verified
.iter()
.map(|(_, bytes)| String::from_utf8_lossy(bytes).into_owned())
.collect();
DSH_SEAT_TABLE
.iter()
.filter(|(key, _)| texts.iter().any(|text| quoted_in(text, key)))
.collect()
}
fn admit_dsh_seat(
plugin: &LoadedPlugin,
seat: &str,
requested: Option<&str>,
declared: &[&'static (&'static str, DshSeat)],
) -> Result<String, ApiError> {
if let Some(key) = requested {
let Some((_, mapped)) = declared.iter().find(|(name, _)| *name == key) else {
return Err(seat_not_admitted(plugin, seat, requested));
};
return match mapped {
DshSeat::Unsupported(reason) => Err(ApiError {
status: StatusCode::UNPROCESSABLE_ENTITY,
message: format!(
"plugin '{}' declares '{key}', which has no Codewhale seat: {reason}",
plugin.name()
),
code: Some("plugin_ui_seat_unsupported"),
}),
DshSeat::Seat(mapped_seat) if *mapped_seat == seat => Ok(key.to_string()),
DshSeat::Seat(_) => Err(seat_not_admitted(plugin, seat, requested)),
};
}
let mut on_seat = declared.iter().filter_map(|(name, mapped)| match mapped {
DshSeat::Seat(mapped_seat) if *mapped_seat == seat => Some(*name),
_ => None,
});
match (on_seat.next(), on_seat.next()) {
(None, _) => Err(seat_not_admitted(plugin, seat, None)),
(Some(key), None) => Ok(key.to_string()),
(Some(_), Some(_)) => Err(ApiError::bad_request(format!(
"plugin '{}' admits more than one client key on seat '{seat}'; pass dsh_slot",
plugin.name()
))
.with_code("plugin_ui_dsh_slot_required")),
}
}
fn dsh_bridge() -> Result<PluginUiBridge, ApiError> {
let receipt: Value = serde_json::from_slice(codewhale_plugins::activation::DSH_COMPATIBILITY)
.map_err(|_| {
ApiError::internal("the pinned DSH compatibility receipt is unreadable")
})?;
let version = receipt
.get("target_dsh_version")
.and_then(Value::as_str)
.ok_or_else(|| ApiError::internal("the pinned DSH compatibility receipt has no version"))?;
Ok(PluginUiBridge {
kind: "dsh-client",
dsh_version: version.to_string(),
compatibility_digest: sha256_hex(codewhale_plugins::activation::DSH_COMPATIBILITY),
})
}
const DSH_BOOTSTRAP_HEAD: &str = r#""use strict";
(function () {
var files = {
"#;
const DSH_BOOTSTRAP_TAIL: &str = r#" var cache = {};
var probes = ["", ".js", ".mjs", ".cjs", ".json", "/index.js", "/index.mjs", "/index.cjs"];
var hostRequire = null;
function normalize(path) {
var out = [];
path.split("/").forEach(function (part) {
if (part === "" || part === ".") return;
if (part === "..") out.pop();
else out.push(part);
});
return out.join("/");
}
function resolve(from, id) {
var base = normalize(from.slice(0, from.lastIndexOf("/")) + "/" + id);
for (var i = 0; i < probes.length; i++) {
if (Object.prototype.hasOwnProperty.call(files, base + probes[i])) return base + probes[i];
}
return null;
}
function load(path) {
if (Object.prototype.hasOwnProperty.call(cache, path)) return cache[path].exports;
var module = { exports: {} };
cache[path] = module;
files[path].call(module.exports, module, module.exports, makeRequire(path));
return module.exports;
}
function makeRequire(from) {
return function (id) {
if (id.charAt(0) === ".") {
var resolved = resolve(from, id);
if (resolved === null) throw new Error("the plugin client requires a file outside its reviewed closure: " + id);
return load(resolved);
}
return hostRequire(id);
};
}
window.__ModuleLoader__.load({
id: PLUGIN_ID,
factory: function (require) {
hostRequire = require;
return load(ENTRY);
}
});
})();
"#;
fn dsh_bootstrap(
selector: &str,
closure: &DshClosure,
verified: &[(String, Vec<u8>)],
) -> Result<Vec<u8>, UiFileError> {
let quote = |text: &str| {
serde_json::to_string(text).map_err(|error| UiFileError::Internal(error.to_string()))
};
let mut out = String::from(DSH_BOOTSTRAP_HEAD);
for (path, bytes) in verified {
let text = std::str::from_utf8(bytes)
.map_err(|_| UiFileError::Invalid(format!("closure file '{path}' is not UTF-8")))?;
out.push_str(" ");
out.push_str(&quote(path)?);
out.push_str(": function (module, exports, require) {\n");
if path.ends_with(".json") {
out.push_str("module.exports = ");
out.push_str(text);
out.push(';');
} else {
out.push_str(text);
}
out.push_str("\n},\n");
}
out.push_str(" };\n");
out.push_str(&format!(
" var PLUGIN_ID = {};\n var ENTRY = {};\n",
quote(if closure.package.is_empty() {
selector
} else {
&closure.package
})?,
quote(&closure.entry)?
));
out.push_str(DSH_BOOTSTRAP_TAIL);
Ok(out.into_bytes())
}
fn prepare_plugin_ui(
state: &RuntimeApiState,
selector: &str,
seat: &str,
dsh_slot: Option<&str>,
) -> Result<PreparedPluginUi, ApiError> {
) -> Result<(String, PluginUiGrant), ApiError> {
let registry = registry_for_state(state);
let plugin = registry
.get(selector)
@@ -1145,7 +718,6 @@ fn prepare_plugin_ui(
ui_prefix: PathBuf::new(),
file_hashes: Arc::new(validated.file_hashes),
expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
dsh: None,
};
let mut found = None;
for candidate in ["package.json", "source/package.json"] {
@@ -1173,7 +745,6 @@ fn prepare_plugin_ui(
return Err(ApiError::not_found(format!("plugin '{}' declares no dsh.client UI in {}; add dsh.client and exports[\"./client\"] to expose client assets", plugin.name(), ui_relative_display(&manifest_path))).with_code("plugin_ui_not_declared"));
}
let conversion_path = FsPath::new("CONVERSION.json");
let mut closure = None;
if grant.file_hashes.contains_key(conversion_path) {
let bytes = verified_ui_file(&grant, conversion_path)
.map_err(|error| ui_file_refusal(&plugin, "CONVERSION.json", error))?;
@@ -1188,39 +759,16 @@ fn prepare_plugin_ui(
.and_then(Value::as_str)
== Some("dsh")
{
closure = Some(dsh_client_closure(&conversion).ok_or_else(|| {
ui_unsupported(
"this DSH client UI was not converted and is not supported by Codewhale yet",
)
})?);
return Err(ApiError::bad_request(
"this DSH client UI was not converted and is not supported by Codewhale yet",
)
.with_code("plugin_ui_unsupported"));
}
}
grant.ui_prefix = manifest_path
.parent()
.unwrap_or(FsPath::new(""))
.to_path_buf();
if let Some(closure) = closure {
let verified = verify_dsh_closure(&grant, &closure)
.map_err(|error| ui_file_refusal(&plugin, "client closure", error))?;
if let Some(reason) = dsh_closure_unsupported(&closure, &verified) {
return Err(ui_unsupported(format!(
"plugin '{}': {reason}",
plugin.name()
)));
}
let key = admit_dsh_seat(&plugin, seat, dsh_slot, &declared_dsh_keys(&verified))?;
grant.dsh = Some(Arc::new(DshServed { closure }));
admit_ui_grant(state, &grant)?;
return Ok(PreparedPluginUi {
entry: DSH_BOOTSTRAP_ENTRY.to_string(),
dsh_slot: Some(key),
bridge: Some(dsh_bridge()?),
grant,
});
}
if seat != PLUGIN_UI_SLOT || dsh_slot.is_some() {
return Err(seat_not_admitted(&plugin, seat, dsh_slot));
}
let raw = ui_client_entry(&manifest).unwrap_or_else(|| "client.js".into());
let relative = ui_relative_path(&raw).map_err(|reason| {
ApiError::bad_request(format!(
@@ -1231,12 +779,7 @@ fn prepare_plugin_ui(
verified_ui_file(&grant, &grant.ui_prefix.join(&relative))
.map_err(|error| ui_file_refusal(&plugin, &ui_relative_display(&relative), error))?;
admit_ui_grant(state, &grant)?;
Ok(PreparedPluginUi {
entry: ui_relative_display(&relative),
dsh_slot: None,
bridge: None,
grant,
})
Ok((ui_relative_display(&relative), grant))
}
fn plugin_ui_base(
@@ -1366,8 +909,6 @@ async fn run_plugin_mutation(
PluginMutationOutcome::Uninstalled => "uninstalled",
};
state.plugin_ui_grants.revoke_selector(&receipt.name);
// Mutations can change merged plugin MCP servers. Advance the existing
// shared generation so each captured workspace pool reloads on next use.
state
@@ -1433,16 +974,8 @@ async fn run_registry_mutation(
let mut registry = (*registry).clone();
let result = match mutation {
RegistryMutation::Trust { .. } => registry.trust_reviewed(
selector,
ReviewApproval {
approved_by: PluginApprover::person(PersonVia::App),
host_services: None,
},
),
RegistryMutation::Enable => {
registry.enable_by(selector, PluginApprover::person(PersonVia::App))
}
RegistryMutation::Trust { .. } => registry.trust(selector),
RegistryMutation::Enable => registry.enable(selector),
RegistryMutation::Restage => registry.restage(selector),
RegistryMutation::Disable => registry.disable(selector),
RegistryMutation::Revoke => registry.revoke_trust(selector),
@@ -1451,8 +984,6 @@ async fn run_registry_mutation(
ApiError::conflict(format!("{action} failed for '{selector}': {error}"))
})?;
state.plugin_ui_grants.revoke_selector(selector);
state
.workspace_scopes
.mcp_generation
@@ -1734,58 +1265,43 @@ pub(super) async fn get_plugin_ui(
));
}
let slot = query.slot.ok_or_else(|| {
ApiError::bad_request(format!(
"the 'slot' query parameter is required; seats: {}",
PLUGIN_UI_SEATS.join(", ")
))
.with_code("plugin_ui_seat_unknown")
})?;
if !PLUGIN_UI_SEATS.contains(&slot.as_str()) {
return Err(ApiError::bad_request(format!(
"slot '{slot}' is not a plugin UI seat; seats: {}",
PLUGIN_UI_SEATS.join(", ")
))
.with_code("plugin_ui_seat_unknown"));
}
if let Some(key) = &query.dsh_slot
&& !valid_dsh_slot_key(key)
{
return Err(ApiError::bad_request(
"dsh_slot must be 1 to 128 characters of letters, digits, '.', '_' or '-', starting with a letter or digit",
ApiError::bad_request(
"the 'slot' query parameter is required; supported slot: 'customize.plugins.detail'",
)
.with_code("plugin_ui_dsh_slot_invalid"));
})?;
if slot.as_str() != PLUGIN_UI_SLOT {
return Err(ApiError::bad_request(format!(
"slot '{slot}' is not supported; supported slot: 'customize.plugins.detail'"
)));
}
let state_for_prepare = state.clone();
let selector_for_prepare = selector.clone();
let seat = slot.clone();
let requested_key = query.dsh_slot.clone();
let prepared = tokio::task::spawn_blocking(move || {
prepare_plugin_ui(
&state_for_prepare,
&selector_for_prepare,
&seat,
requested_key.as_deref(),
)
let (entry, grant) = tokio::task::spawn_blocking(move || {
prepare_plugin_ui(&state_for_prepare, &selector_for_prepare)
})
.await
.map_err(|_| ApiError::internal("plugin UI preparation failed"))??;
let base = plugin_ui_base(&state, &selector, &headers, &uri)?;
let revision = state.plugin_ui_grants.insert(prepared.grant);
let revision = state.plugin_ui_grants.insert(grant);
Ok(Json(PluginUiSlotResponse {
slot,
dsh_slot: prepared.dsh_slot,
bridge: prepared.bridge,
base,
entry: prepared.entry,
entry,
revision,
}))
}
fn grant_for_request(
state: &RuntimeApiState,
selector: &str,
headers: &HeaderMap,
) -> Result<(PluginUiGrant, String), ApiError> {
pub(super) async fn get_plugin_ui_asset(
State(state): State<RuntimeApiState>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
Path((selector, path)): Path<(String, String)>,
headers: HeaderMap,
) -> Result<Response, ApiError> {
if !peer.ip().is_loopback() {
return Err(ApiError::forbidden(
"plugin UI assets are available only from loopback",
));
}
let mut values = headers.get_all(header::IF_MATCH).iter();
let first = values.next().ok_or_else(|| ApiError {
status: StatusCode::PRECONDITION_REQUIRED,
@@ -1803,101 +1319,25 @@ fn grant_for_request(
if grant.selector != selector || grant.authority.workspace != state.workspace {
return Err(ui_stale_revision());
}
Ok((grant, revision))
}
pub(super) async fn plugin_route_bridge(
State(state): State<RuntimeApiState>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
Path((selector, path)): Path<(String, String)>,
method: axum::http::Method,
headers: HeaderMap,
) -> Result<Response, ApiError> {
if !peer.ip().is_loopback() {
return Err(ApiError::forbidden(
"plugin routes are available only from loopback",
));
}
let (grant, revision) = grant_for_request(&state, &selector, &headers)?;
let state_for_route = state.clone();
tokio::task::spawn_blocking(move || {
codewhale_plugins::registry::verify_plugin_authority(&grant.authority)
.map_err(|_| ui_stale_revision())?;
admit_ui_grant(&state_for_route, &grant)?;
if state_for_route.plugin_ui_grants.get(&revision).is_none() {
return Err(ui_stale_revision());
}
if grant.dsh.is_none() {
return Err(ApiError::forbidden(
"this plugin UI grant has no DSH client and no plugin routes",
)
.with_code("plugin_route_not_admitted"));
}
Ok(())
})
.await
.map_err(|_| ApiError::internal("plugin route check failed"))??;
ui_relative_path(&path).map_err(|reason| {
ApiError::bad_request(format!("plugin route path '{path}' is invalid: {reason}"))
})?;
if !DSH_ROUTE_METHODS.contains(&method.as_str()) {
return Err(ApiError {
status: StatusCode::METHOD_NOT_ALLOWED,
message: format!("plugin routes do not accept {method}"),
code: None,
});
}
Err(ApiError::not_implemented(
"this Engine has no plugin web server to forward the route to yet",
)
.with_code("plugin_route_not_served"))
}
pub(super) async fn get_plugin_ui_asset(
State(state): State<RuntimeApiState>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
Path((selector, path)): Path<(String, String)>,
headers: HeaderMap,
) -> Result<Response, ApiError> {
if !peer.ip().is_loopback() {
return Err(ApiError::forbidden(
"plugin UI assets are available only from loopback",
));
}
let (grant, revision) = grant_for_request(&state, &selector, &headers)?;
let relative = ui_relative_path(&path).map_err(|reason| {
ApiError::bad_request(format!("plugin UI path '{path}' is invalid: {reason}"))
})?;
let content_type = ui_content_type(&relative);
if grant.dsh.is_some() && relative != FsPath::new(DSH_BOOTSTRAP_ENTRY) {
return Err(
ApiError::not_found("plugin UI file is not in the reviewed client closure")
.with_code("plugin_ui_file_not_reviewed"),
);
}
let state_for_asset = state.clone();
let bytes = tokio::task::spawn_blocking(move || {
codewhale_plugins::registry::verify_plugin_authority(&grant.authority)
.map_err(|_| ui_stale_revision())?;
let bytes = if let Some(dsh) = &grant.dsh {
let verified =
verify_dsh_closure(&grant, &dsh.closure).map_err(|_| ui_stale_revision())?;
dsh_bootstrap(&grant.selector, &dsh.closure, &verified)
.map_err(|_| ui_stale_revision())?
} else {
verified_ui_file(&grant, &grant.ui_prefix.join(&relative)).map_err(
|error| match error {
UiFileError::Missing => {
ApiError::not_found("plugin UI file is not in the reviewed bundle")
.with_code("plugin_ui_file_not_reviewed")
}
UiFileError::TooLarge => {
ApiError::payload_too_large("plugin UI file exceeds the 8 MiB limit")
}
_ => ui_stale_revision(),
},
)?
};
let bytes = verified_ui_file(&grant, &grant.ui_prefix.join(&relative)).map_err(
|error| match error {
UiFileError::Missing => {
ApiError::not_found("plugin UI file is not in the reviewed bundle")
}
UiFileError::TooLarge => {
ApiError::payload_too_large("plugin UI file exceeds the 8 MiB limit")
}
_ => ui_stale_revision(),
},
)?;
admit_ui_grant(&state_for_asset, &grant)?;
if state_for_asset.plugin_ui_grants.get(&revision).is_none() {
return Err(ui_stale_revision());
+108 -56
View File
@@ -18,17 +18,9 @@ use uuid::Uuid;
mod command_catalog;
#[cfg(unix)]
mod control_socket_selection;
mod conversation_modes;
#[cfg(unix)]
mod external_agent_options;
#[cfg(unix)]
mod external_agent_quota;
mod headless_catalog;
#[cfg(any(unix, windows))]
mod member_operations;
#[cfg(unix)]
mod owner_bootstrap;
mod plugin_ui;
mod profile_constitution;
#[cfg(any(unix, windows))]
mod runtime_store_convergence;
@@ -424,7 +416,6 @@ fn saved_session_with_blocks(blocks: Vec<codewhale_models::ContentBlock>) -> Sav
composer_color: None,
last_auto_route: None,
turn_outcomes: Vec::new(),
agent_preset: None,
}
}
@@ -565,7 +556,6 @@ fn messages_from_thread_detail_batches_tool_results() {
last_read: None,
executor: None,
environment: None,
agent_preset: None,
};
let turn = TurnRecord {
source_usage_origin_turn_id: None,
@@ -798,7 +788,6 @@ fn legacy_exact_thread_export_normalizes_provider_kind_and_id() {
last_read: None,
executor: None,
environment: None,
agent_preset: None,
},
turns: Vec::new(),
items: Vec::new(),
@@ -8203,13 +8192,18 @@ fn patch_undo_helper_restores_only_the_dropped_turns_changes() -> Result<()> {
);
let snapshot_count = repo.list(usize::MAX)?.len();
let (preview, paths) =
patch_undo_workspace_files_impl(&workspace, std::slice::from_ref(&turn), true, None)
patch_undo_workspace_files_impl(&workspace, std::slice::from_ref(&turn), true, true, None)
.expect("a trusted preview should succeed");
assert!(!preview.files_restored);
assert_eq!(paths, vec!["a.txt", "made/new.txt"]);
let refused =
patch_undo_workspace_files_impl(&workspace, std::slice::from_ref(&turn), false, Some(&[]))
.expect_err("an unreviewed file plan must refuse before restoring");
let refused = patch_undo_workspace_files_impl(
&workspace,
std::slice::from_ref(&turn),
true,
false,
Some(&[]),
)
.expect_err("an unreviewed file plan must refuse before restoring");
assert_eq!(refused.status, StatusCode::CONFLICT);
assert_eq!(refused.code, Some("undo_selection_changed"));
@@ -8218,7 +8212,7 @@ fn patch_undo_helper_restores_only_the_dropped_turns_changes() -> Result<()> {
assert_eq!(fs::read_to_string(&other)?, "later work");
assert_eq!(repo.list(usize::MAX)?.len(), snapshot_count);
let restored = patch_undo_workspace_files(&workspace, std::slice::from_ref(&turn))
let restored = patch_undo_workspace_files(&workspace, std::slice::from_ref(&turn), true)
.expect("a trusted rollback should succeed");
assert!(restored.files_restored, "{:?}", restored.summary);
assert_eq!(fs::read_to_string(&a)?, "before", "both writes are undone");
@@ -8238,7 +8232,7 @@ fn patch_undo_helper_restores_only_the_dropped_turns_changes() -> Result<()> {
);
// Undoing again finds the files already at their pre-turn state.
let again = patch_undo_workspace_files(&workspace, std::slice::from_ref(&turn))
let again = patch_undo_workspace_files(&workspace, std::slice::from_ref(&turn), true)
.expect("already restored is provably nothing to do");
assert!(!again.files_restored);
Ok(())
@@ -8272,7 +8266,7 @@ fn patch_undo_helper_refuses_to_overwrite_later_edits() -> Result<()> {
true,
shell_turn_receipts(&repo, &pre, &post, "thr_a"),
);
let err = patch_undo_workspace_files(&workspace, &[turn])
let err = patch_undo_workspace_files(&workspace, &[turn], true)
.expect_err("a later edit must not be overwritten");
assert_eq!(err.status, StatusCode::CONFLICT);
assert_eq!(err.code, Some(PATCH_UNDO_WORKSPACE_CHANGED));
@@ -8328,7 +8322,7 @@ fn patch_undo_helper_fails_honestly_without_an_owned_restore_point() -> Result<(
),
];
for (turn, code) in cases {
let err = patch_undo_workspace_files(&workspace, std::slice::from_ref(&turn))
let err = patch_undo_workspace_files(&workspace, std::slice::from_ref(&turn), true)
.expect_err(&turn.turn_id);
assert_eq!(err.status, StatusCode::CONFLICT, "{}", turn.turn_id);
assert_eq!(err.code, Some(code), "{}: {}", turn.turn_id, err.message);
@@ -8336,16 +8330,20 @@ fn patch_undo_helper_fails_honestly_without_an_owned_restore_point() -> Result<(
assert_eq!(fs::read_to_string(&a)?, "after");
}
let chat_only =
patch_undo_workspace_files(&workspace, &[dropped_turn("chat", false, Vec::new())])
.expect("a turn that ran no tools changed no files");
let chat_only = patch_undo_workspace_files(
&workspace,
&[dropped_turn("chat", false, Vec::new())],
false,
)
.expect("a turn that ran no tools changed no files");
assert!(!chat_only.files_restored);
// A prune that drops the restore point's tree fails closed too.
let receipts = shell_turn_receipts(&repo, &pre, &post, "thr_a");
repo.prune_older_than(Duration::ZERO)?;
let err = patch_undo_workspace_files(&workspace, &[dropped_turn("pruned", true, receipts)])
.expect_err("a pruned restore point cannot be restored");
let err =
patch_undo_workspace_files(&workspace, &[dropped_turn("pruned", true, receipts)], true)
.expect_err("a pruned restore point cannot be restored");
assert_eq!(err.code, Some(PATCH_UNDO_RESTORE_POINT_PRUNED));
assert_eq!(fs::read_to_string(&a)?, "after");
Ok(())
@@ -8389,6 +8387,7 @@ fn patch_undo_helper_survives_a_prune_that_rewrites_commit_ids() -> Result<()> {
true,
shell_turn_receipts(&repo, &pre, &post, "thr_a"),
)],
true,
)
.expect("the tree still resolves the restore point");
assert!(restored.files_restored);
@@ -8482,6 +8481,7 @@ fn patch_undo_helper_attributes_changes_to_the_turns_own_tool_spans() -> Result<
let err = patch_undo_workspace_files(
&workspace,
&[dropped_turn("turn_1", true, receipts(gap_writer))],
true,
)
.expect_err("another writer's change must not be reverted");
assert_eq!(err.status, StatusCode::CONFLICT);
@@ -8508,9 +8508,12 @@ fn patch_undo_helper_attributes_changes_to_the_turns_own_tool_spans() -> Result<
None,
Some(changed_between(&repo, &post_tool, &clean_post)),
);
let restored =
patch_undo_workspace_files(&workspace, &[dropped_turn("turn_1", true, clean.clone())])
.expect("the turn's own write restores");
let restored = patch_undo_workspace_files(
&workspace,
&[dropped_turn("turn_1", true, clean.clone())],
true,
)
.expect("the turn's own write restores");
assert!(restored.files_restored, "{:?}", restored.summary);
assert_eq!(fs::read_to_string(&own)?, "before");
@@ -8518,8 +8521,9 @@ fn patch_undo_helper_attributes_changes_to_the_turns_own_tool_spans() -> Result<
fs::write(&own, "turn")?;
let mut shell = clean.clone();
shell[1].write_paths = None;
let restored = patch_undo_workspace_files(&workspace, &[dropped_turn("turn_1", true, shell)])
.expect("an undeclared span owns its changes");
let restored =
patch_undo_workspace_files(&workspace, &[dropped_turn("turn_1", true, shell)], true)
.expect("an undeclared span owns its changes");
assert!(restored.files_restored);
assert_eq!(fs::read_to_string(&own)?, "before");
@@ -8527,8 +8531,9 @@ fn patch_undo_helper_attributes_changes_to_the_turns_own_tool_spans() -> Result<
fs::write(&own, "turn")?;
let mut unknown = clean;
unknown[2].changed_paths = None;
let err = patch_undo_workspace_files(&workspace, &[dropped_turn("turn_1", true, unknown)])
.expect_err("an unaccounted span fails closed");
let err =
patch_undo_workspace_files(&workspace, &[dropped_turn("turn_1", true, unknown)], true)
.expect_err("an unaccounted span fails closed");
assert_eq!(
err.code,
Some(PATCH_UNDO_NO_RESTORE_POINT),
@@ -8589,6 +8594,7 @@ fn patch_undo_helper_refuses_declared_writes_snapshots_cannot_hold() -> Result<(
let err = patch_undo_workspace_files(
&workspace,
&[dropped_turn("turn_1", true, receipts(&[declared]))],
true,
)
.expect_err(declared);
assert_eq!(err.status, StatusCode::CONFLICT, "{declared}");
@@ -8603,24 +8609,24 @@ fn patch_undo_helper_refuses_declared_writes_snapshots_cannot_hold() -> Result<(
// The same declared write from a call recorded as failed wrote nothing.
let mut failed = dropped_turn("turn_1", true, receipts(&[".env.local"]));
failed.unrun_tool_calls.insert("call-1".to_string());
let result =
patch_undo_workspace_files(&workspace, &[failed]).expect("a failed call wrote nothing");
let result = patch_undo_workspace_files(&workspace, &[failed], true)
.expect("a failed call wrote nothing");
assert!(!result.files_restored);
// Declared through the turn's items rather than a receipt.
let mut from_items = dropped_turn("turn_1", true, receipts(&[]));
from_items.declared_writes.push(".env.local".to_string());
let err = patch_undo_workspace_files(&workspace, &[from_items])
let err = patch_undo_workspace_files(&workspace, &[from_items], true)
.expect_err("an item-declared ignored write refuses too");
assert_eq!(err.code, Some(PATCH_UNDO_PATH_NOT_SNAPSHOTTED));
Ok(())
}
/// Default posture (no trust mode, no Full Access): the Runtime does not
/// gate on trust at all, because the ownership and later-edit proofs already
/// decide what may be reverted. A later edit in the same workspace still
/// refuses and leaves every byte alone.
/// The gate the TUI's `/undo` applies, stated as a contract: an untrusted
/// thread may not roll files back. When there *is* something to roll back the
/// whole undo aborts — nothing is changed, and the caller must not fork the
/// conversation either.
#[test]
fn patch_undo_helper_restores_in_the_default_posture_and_still_refuses_later_edits() -> Result<()> {
fn patch_undo_helper_refuses_an_untrusted_rollback_and_touches_nothing() -> Result<()> {
if git_missing() {
return Ok(());
}
@@ -8645,20 +8651,69 @@ fn patch_undo_helper_restores_in_the_default_posture_and_still_refuses_later_edi
shell_turn_receipts(&repo, &pre, &post, "thr_a"),
);
fs::write(&file, "edited later by the person")?;
let refused = patch_undo_workspace_files(&workspace, std::slice::from_ref(&turn))
.expect_err("a later edit must not be overwritten");
assert_eq!(refused.code, Some(PATCH_UNDO_WORKSPACE_CHANGED));
assert_eq!(fs::read_to_string(&file)?, "edited later by the person");
let err = patch_undo_workspace_files(&workspace, std::slice::from_ref(&turn), false)
.expect_err("an untrusted rollback must be refused");
assert_eq!(err.status, StatusCode::CONFLICT);
assert_eq!(err.code, Some(PATCH_UNDO_UNTRUSTED));
assert!(
err.message.contains("outside trusted mode"),
"got: {}",
err.message
);
assert_eq!(
fs::read_to_string(&file)?,
"after",
"a refusal must leave the workspace exactly as it was"
);
fs::write(&file, "after")?;
let restored = patch_undo_workspace_files(&workspace, &[turn])
.expect("the turn's own change restores without trust");
// The identical call once trusted performs the rollback.
let restored = patch_undo_workspace_files(&workspace, &[turn], true)
.expect("a trusted rollback should succeed");
assert!(restored.files_restored, "{:?}", restored.summary);
assert_eq!(fs::read_to_string(&file)?, "before");
Ok(())
}
/// ...but with provably nothing to roll back, an untrusted undo is still
/// allowed: the conversation half needs no trust, and skipping it would make
/// Undo useless in Ask / Auto-Review for no safety gain.
#[test]
fn patch_undo_helper_allows_an_untrusted_undo_with_nothing_to_roll_back() -> Result<()> {
if git_missing() {
return Ok(());
}
let _lock = lock_test_env();
let root = tempfile::tempdir()?;
let home = root.path().join("home");
fs::create_dir_all(&home)?;
let _home = EnvVarGuard::set("HOME", &home);
let workspace = root.path().join("workspace");
fs::create_dir_all(&workspace)?;
let repo = codewhale_snapshot::SnapshotRepo::open_or_init(&workspace)?;
let file = workspace.join("a.txt");
fs::write(&file, "only-state")?;
let pre = repo.take_snapshot("pre-turn:1", Some("thr_a"))?;
// The turn ran a tool but changed nothing.
let post = repo.take_snapshot("post-turn:1", Some("thr_a"))?;
let result = patch_undo_workspace_files(
&workspace,
&[dropped_turn(
"turn_1",
true,
shell_turn_receipts(&repo, &pre, &post, "thr_a"),
)],
false,
)
.expect("nothing to roll back is not a refusal");
assert!(!result.files_restored);
assert!(result.summary.is_some());
assert_eq!(fs::read_to_string(&file)?, "only-state");
Ok(())
}
fn sha256_of(path: &FsPath) -> String {
format!(
"sha256:{}",
@@ -11087,8 +11142,6 @@ async fn runtime_info_reports_bind_state() -> Result<()> {
assert!(info["account"].get("refresh_token").is_none());
assert!(info["account"].get("email").is_none());
assert!(info["experimental"].is_object());
assert!(info["sandbox"]["kind"].is_string());
assert_eq!(info["sandbox"]["tool_launcher"], false);
handle.abort();
Ok(())
@@ -26453,9 +26506,8 @@ mod thread_snapshot_ownership {
/// An undo that cannot restore files fails honestly: snapshots disabled,
/// a legacy seeded turn with tool calls and no receipts, a restore point
/// pruned from the store. Each is a 409 with a code, no fork, and
/// unchanged files. A default-posture thread (no trust, no Full Access)
/// with an intact restore point is not among them: it restores.
/// pruned from the store, and an untrusted thread. Each is a 409 with a
/// code, no fork, and unchanged files.
#[tokio::test]
async fn undo_that_cannot_restore_files_is_refused() -> Result<()> {
let _env = lock_test_env();
@@ -26538,7 +26590,7 @@ mod thread_snapshot_ownership {
assert_eq!(fx.thread_count().await?, before + 1);
drop(fx);
// Snapshots on again: a pruned restore point, then a default-posture thread.
// Snapshots on again: a pruned restore point and an untrusted thread.
let root = test_root("honest-on");
let _home = EnvVarGuard::set("CODEWHALE_HOME", root.join("home"));
let Some(fx) = fixture(&root, TestServerOverrides::default()).await? else {
@@ -26560,9 +26612,9 @@ mod thread_snapshot_ownership {
.await?
.error_for_status()?;
let before = fx.thread_count().await?;
fx.undo_restoring(&untrusted, 0).await?;
assert_eq!(fx.read("u.txt"), None);
assert_eq!(fx.thread_count().await?, before + 1);
refused(&fx, untrusted, "restore_requires_trust").await?;
assert_eq!(fx.read("u.txt").as_deref(), Some("u"));
assert_eq!(fx.thread_count().await?, before);
let _ = &fx.root;
Ok(())
}
@@ -828,149 +828,3 @@ async fn turn_detail(
.and_then(|turns| turns.iter().find(|turn| turn["id"] == turn_id))
.map_or_else(|| "turn absent".to_string(), Value::to_string))
}
// ── Remote built-in execution ──
/// A catalog that serves exactly one built-in remotely, so the route's name
/// gate and snapshot hand-off can be observed without the terminal host.
struct RemoteBuiltinCatalog;
impl CommandCatalog for RemoteBuiltinCatalog {
fn answers_to(&self, name: &str) -> bool {
name == "system"
}
fn builtins(&self) -> Vec<BuiltinCommand> {
vec![builtin("system", vec!["xitong".to_string()])]
}
fn user_commands(&self, _workspace: &Path) -> Vec<UserCommand> {
Vec::new()
}
fn serves_builtin(&self, name: &str) -> bool {
matches!(name.trim_start_matches('/'), "system" | "xitong")
}
fn execute_builtin(
&self,
name: &str,
_args: Option<&str>,
host: &codewhale_engine::command_catalog::BuiltinCommandHostSnapshot,
) -> Option<codewhale_engine::command_catalog::BuiltinCommandExecution> {
if !self.serves_builtin(name) {
return None;
}
Some(codewhale_engine::command_catalog::BuiltinCommandExecution {
name: "system".to_string(),
text: format!(
"{}|{}|{}",
host.mode_label,
host.model,
match &host.system_prompt {
codewhale_command_contract::facets::DebugSystemPrompt::None => 0,
codewhale_command_contract::facets::DebugSystemPrompt::Text(text) => text.len(),
codewhale_command_contract::facets::DebugSystemPrompt::Blocks(blocks) =>
blocks.iter().map(String::len).sum(),
}
),
is_error: false,
text_only: true,
})
}
}
/// B5: `POST /v1/threads/{id}/commands/builtin` executes only the names the
/// installed host serves, and answers everything else like an unknown name.
#[tokio::test]
async fn post_thread_builtin_command_serves_only_the_host_allowlist() -> Result<()> {
let _env = lock_test_env();
let temp = tempfile::tempdir()?;
let token = "builtin-route-fixture-token";
let root = temp.path().join("builtin-commands-route");
let sessions_dir = root.join("sessions");
let workspace = root.join("workspace");
fs::create_dir_all(&workspace)?;
let _catalog =
codewhale_engine::command_catalog::CatalogGuard::install(Arc::new(RemoteBuiltinCatalog));
let Some((addr, runtime_threads, handle)) = spawn_test_server_with_root_token_mobile_workspace(
root,
sessions_dir,
Some(token.to_string()),
false,
workspace,
)
.await?
else {
return Ok(());
};
let client = codewhale_release::tls::reqwest_client();
let thread = runtime_threads
.create_thread(CreateThreadRequest::default())
.await?;
let url = format!("http://{addr}/v1/threads/{}/commands/builtin", thread.id);
let unauthorized = client
.post(&url)
.json(&json!({ "name": "system" }))
.send()
.await?;
assert_eq!(unauthorized.status(), StatusCode::UNAUTHORIZED);
let cold = client
.post(&url)
.bearer_auth(token)
.json(&json!({ "name": "system" }))
.send()
.await?;
assert_eq!(cold.status(), StatusCode::CONFLICT, "cold engine");
runtime_threads.get_engine(&thread.id).await?;
// Not on the host's remote surface: the same answer an unknown name gets.
for name in ["balance", "cache", "not-a-command"] {
let response = client
.post(&url)
.bearer_auth(token)
.json(&json!({ "name": name }))
.send()
.await?;
assert_eq!(response.status(), StatusCode::NOT_FOUND, "{name}");
}
// A served name (alias spelling included) reaches the host with the
// thread's own state, and its text comes back unchanged.
for name in ["system", "/system", "xitong"] {
let body: Value = client
.post(&url)
.bearer_auth(token)
.json(&json!({ "name": name, "args": "ignored" }))
.send()
.await?
.error_for_status()?
.json()
.await?;
assert_eq!(body["name"], "system");
assert_eq!(body["is_error"], false);
assert_eq!(body["text_only"], true);
// One snapshot field per segment, so a route that assembled the
// wrong thread's state cannot pass.
let text = body["text"].as_str().context("builtin text")?;
let fields: Vec<&str> = text.split('|').collect();
assert_eq!(fields.len(), 3, "{text}");
assert!(!fields[0].is_empty(), "mode label: {text}");
assert_eq!(fields[1], thread.model, "model: {text}");
let prompt_len: usize = fields[2].parse().context("system prompt length")?;
assert!(prompt_len > 0, "effective system prompt reported: {text}");
}
// The thread id is still the address: a missing thread stays 404.
let missing = client
.post(format!(
"http://{addr}/v1/threads/thr_missing/commands/builtin"
))
.bearer_auth(token)
.json(&json!({ "name": "system" }))
.send()
.await?;
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
handle.abort();
Ok(())
}
@@ -1,82 +0,0 @@
use super::*;
use codewhale_engine::conversation_modes::CreatorAvailabilityGuard;
#[tokio::test]
async fn modes_route_lists_the_table_and_threads_carry_and_refuse_modes() -> Result<()> {
let _unavailable = CreatorAvailabilityGuard::unforced();
let Some((addr, _threads, handle)) = spawn_test_server().await? else {
return Ok(());
};
let client = codewhale_release::tls::reqwest_client();
let base = format!("http://{addr}");
let table: Value = client
.get(format!("{base}/v1/modes"))
.send()
.await?
.error_for_status()?
.json()
.await?;
assert_eq!(table["default"], "standard");
assert_eq!(table["modes"][0]["id"], "standard");
assert_eq!(table["modes"][0]["source"], "builtin");
assert_eq!(table["modes"][0]["available"], true);
assert!(table["modes"][0].get("reason").is_none());
assert_eq!(table["modes"][1]["id"], "creator");
assert_eq!(table["modes"][1]["available"], false);
assert_eq!(
table["modes"][1]["reason"],
codewhale_engine::conversation_modes::CREATOR_NOT_READY_REASON
);
let unavailable = client
.post(format!("{base}/v1/threads"))
.json(&json!({"agent_preset": "creator"}))
.send()
.await?;
assert_eq!(unavailable.status(), reqwest::StatusCode::FAILED_DEPENDENCY);
let body: Value = unavailable.json().await?;
assert_eq!(body["error"]["code"], "mode_unavailable");
let unknown = client
.post(format!("{base}/v1/threads"))
.json(&json!({"agent_preset": "minimal"}))
.send()
.await?;
assert_eq!(unknown.status(), reqwest::StatusCode::BAD_REQUEST);
let body: Value = unknown.json().await?;
assert_eq!(body["error"]["code"], "unknown_mode");
let created: Value = client
.post(format!("{base}/v1/threads"))
.json(&json!({"agent_preset": "standard"}))
.send()
.await?
.error_for_status()?
.json()
.await?;
let id = created["id"].as_str().expect("thread id").to_string();
let summary: Value = client
.get(format!("{base}/v1/threads/summary"))
.send()
.await?
.error_for_status()?
.json()
.await?;
let row = summary
.as_array()
.and_then(|rows| rows.iter().find(|row| row["id"] == id.as_str()))
.expect("summary row");
assert_eq!(row["agent_preset"], "standard");
let patched = client
.patch(format!("{base}/v1/threads/{id}"))
.json(&json!({"agent_preset": "creator"}))
.send()
.await?;
assert_eq!(patched.status(), reqwest::StatusCode::FAILED_DEPENDENCY);
handle.abort();
let _ = handle.await;
Ok(())
}
@@ -1,184 +0,0 @@
use super::*;
use reqwest::StatusCode as HttpStatus;
fn options_fixture() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../engine/tests/fixtures/acp-options-agent.mjs")
.canonicalize()
.expect("the options fixture agent")
}
fn with_query(base: &str, pairs: &[(&str, &str)]) -> reqwest::Url {
let mut url = reqwest::Url::parse(base).expect("a url");
for (key, value) in pairs {
url.query_pairs_mut().append_pair(key, value);
}
url
}
fn received(workspace: &Path) -> Vec<Value> {
fs::read_to_string(workspace.join("options-received.jsonl"))
.unwrap_or_default()
.lines()
.filter_map(|line| serde_json::from_str(line).ok())
.collect()
}
async fn wait_for_usage_total(
manager: &SharedRuntimeThreadManager,
thread_id: &str,
) -> Result<RuntimeEventRecord> {
for _ in 0..600 {
let events = manager.events_since_async(thread_id, None).await?;
if let Some(event) = events.into_iter().find(|event| {
event.event == "turn.agent_usage" && event.payload["kind"] == "turn_total"
}) {
return Ok(event);
}
sleep(Duration::from_millis(50)).await;
}
bail!("the agent's usage was never recorded")
}
#[tokio::test]
async fn the_options_route_offers_the_agents_choices_and_a_chosen_one_reaches_it() -> Result<()> {
let _env = lock_test_env();
let _fixture = EnvVarGuard::set("CODEWHALE_ACP_FIXTURE_AGENT", options_fixture());
let Some((addr, manager, handle)) = spawn_test_server().await? else {
return Ok(());
};
let client = codewhale_release::tls::reqwest_client();
let workspace = tempfile::tempdir()?;
let cwd = workspace.path().canonicalize()?;
let url = format!("http://{addr}/v1/agents/external/fixture/options");
let offered: Value = client
.get(with_query(&url, &[("cwd", cwd.to_str().unwrap())]))
.send()
.await?
.error_for_status()?
.json()
.await?;
assert_eq!(offered["agent"]["id"], "fixture");
let controls = offered["controls"].as_array().unwrap();
let model = controls.iter().find(|c| c["id"] == "model").unwrap();
let values: Vec<&str> = model["choices"]
.as_array()
.unwrap()
.iter()
.map(|c| c["value"].as_str().unwrap())
.collect();
assert!(values.len() >= 2, "{values:?}");
assert!(controls.iter().any(|c| c["id"] == "mode"));
assert!(
controls.iter().any(|c| c["id"] == "config:verbose"
&& c["unavailable"]["code"] == "control_type_unsupported")
);
assert!(
offered["actions"]
.as_array()
.unwrap()
.iter()
.any(|a| a["action"] == "steering" && a["supported"] == false)
);
let leaked = fs::read_to_string(cwd.join("options-env.json"))?;
assert!(!leaked.contains("CODEWHALE_ACP_FIXTURE_AGENT"));
for (query, status, code) in [
(vec![], HttpStatus::BAD_REQUEST, None),
(vec![("cwd", "relative/dir")], HttpStatus::BAD_REQUEST, None),
(
vec![("cwd", "/definitely/not/here")],
HttpStatus::NOT_FOUND,
None,
),
] {
let response = client.get(with_query(&url, &query)).send().await?;
assert_eq!(response.status(), status, "{query:?}");
let body: Value = response.json().await?;
assert_eq!(body["error"]["code"].as_str(), code, "{body}");
}
let unknown = client
.get(with_query(
&format!("http://{addr}/v1/agents/external/nope/options"),
&[("cwd", cwd.to_str().unwrap())],
))
.send()
.await?;
assert_eq!(unknown.status(), HttpStatus::NOT_FOUND);
let body: Value = unknown.json().await?;
assert_eq!(body["error"]["code"], "unknown_agent");
let bad_id = client
.get(with_query(
&format!("http://{addr}/v1/agents/external/..%2Fsh/options"),
&[("cwd", cwd.to_str().unwrap())],
))
.send()
.await?;
assert!(bad_id.status().is_client_error());
let chosen = values[1];
let created: Value = client
.post(format!("http://{addr}/v1/threads"))
.json(&json!({
"workspace": cwd,
"permission_posture": "ask",
"executor": {"kind": "acp", "agent_id": "fixture", "config": {"model": chosen}}
}))
.send()
.await?
.error_for_status()?
.json()
.await?;
let thread_id = created["id"].as_str().unwrap().to_string();
let refused = client
.post(format!("http://{addr}/v1/threads/{thread_id}/turns"))
.json(&json!({"prompt": "x", "model": "other"}))
.send()
.await?;
assert_eq!(refused.status(), HttpStatus::FAILED_DEPENDENCY);
let body: Value = refused.json().await?;
assert_eq!(body["error"]["code"], "unsupported_control");
client
.post(format!("http://{addr}/v1/threads/{thread_id}/turns"))
.json(&json!({"prompt": "hello"}))
.send()
.await?
.error_for_status()?;
let total = wait_for_usage_total(&manager, &thread_id).await?;
assert_eq!(total.payload["source"], "agent reported");
assert_eq!(total.payload["cost"], "unknown");
assert_eq!(total.payload["tokens"]["total_tokens"], 150);
let log = received(&cwd);
let prompt = log
.iter()
.find(|e| e["method"] == "session/prompt")
.unwrap();
assert_eq!(prompt["state"]["model"], chosen);
let stale = client
.post(format!("http://{addr}/v1/threads"))
.json(&json!({
"workspace": cwd,
"executor": {"kind": "acp", "agent_id": "fixture", "config": {"model": "model-z"}}
}))
.send()
.await?
.error_for_status()?
.json::<Value>()
.await?;
let stale_id = stale["id"].as_str().unwrap();
let response = client
.post(format!("http://{addr}/v1/threads/{stale_id}/turns"))
.json(&json!({"prompt": "x"}))
.send()
.await?;
assert_eq!(response.status(), HttpStatus::FAILED_DEPENDENCY);
let body: Value = response.json().await?;
assert_eq!(body["error"]["code"], "choice_not_offered");
handle.abort();
Ok(())
}
@@ -1,202 +0,0 @@
use super::*;
use reqwest::StatusCode as HttpStatus;
use std::collections::BTreeMap;
const FIXTURE_TOKEN: &str = "cw-fixture-token-7993-do-not-echo";
fn reasons(body: &Value) -> BTreeMap<String, String> {
body["agents"]
.as_array()
.expect("agents array")
.iter()
.map(|entry| {
assert!(
entry["quota"].get("source").is_none(),
"no source without a reader: {entry}"
);
assert_eq!(entry["quota"]["status"], "unknown", "{entry}");
(
entry["id"].as_str().expect("id").to_string(),
entry["quota"]["reason"]
.as_str()
.expect("reason")
.to_string(),
)
})
.collect()
}
fn snapshot(paths: &[PathBuf]) -> Vec<(Vec<u8>, std::time::SystemTime)> {
paths
.iter()
.map(|path| {
(
fs::read(path).expect("fixture credential"),
fs::metadata(path)
.and_then(|meta| meta.modified())
.expect("mtime"),
)
})
.collect()
}
#[tokio::test]
async fn agent_quota_reads_nothing_until_flag_and_consent_and_never_echoes_a_token() -> Result<()> {
let _env = lock_test_env();
let root = tempfile::tempdir()?;
let home = root.path().join("home");
let mut credentials = Vec::new();
for (dir, file) in [
(".claude", ".credentials.json"),
(".codex", "auth.json"),
(".gemini", "oauth_creds.json"),
(".kimi", "credentials.json"),
(".grok", "auth.json"),
] {
let dir = home.join(dir);
fs::create_dir_all(&dir)?;
let path = dir.join(file);
fs::write(
&path,
format!(r#"{{"access_token":"{FIXTURE_TOKEN}","refresh_token":"{FIXTURE_TOKEN}"}}"#),
)?;
credentials.push(path);
}
let before = snapshot(&credentials);
let config_file = root.path().join("config").join("config.toml");
fs::create_dir_all(config_file.parent().unwrap())?;
fs::write(
&config_file,
"provider = \"deepseek\"\napi_key = \"runtime-api-test-key\"\nbase_url = \"http://127.0.0.1:1/v1\"\n",
)?;
let _home = EnvVarGuard::set("HOME", &home);
let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &config_file);
let Some((addr, _runtime_threads, handle)) =
spawn_test_server_with_config_path(config_file.clone()).await?
else {
return Ok(());
};
let client = codewhale_release::tls::reqwest_client();
let mut seen = String::new();
let read = || {
let client = client.clone();
let url = format!("http://{addr}/v1/agents/external/quota");
async move {
let text = client
.get(url)
.send()
.await?
.error_for_status()?
.text()
.await?;
Ok::<String, anyhow::Error>(text)
}
};
let set = |key: &'static str, value: &'static str| {
let client = client.clone();
let url = format!("http://{addr}/v1/config");
async move {
let response = client
.post(url)
.json(&json!({"key": key, "value": value, "persist": true}))
.send()
.await?;
let status = response.status();
Ok::<(HttpStatus, String), anyhow::Error>((status, response.text().await?))
}
};
let text = read().await?;
seen.push_str(&text);
let body: Value = serde_json::from_str(&text)?;
assert_eq!(body["default_source"], "agent_reported");
let initial = reasons(&body);
assert_eq!(initial.len(), codewhale_engine::fleet::agents::AGENTS.len());
assert!(
initial.values().all(|reason| reason == "flag_off"),
"{initial:?}"
);
for (key, value) in [
("agents.quota.claude", "on"),
("agents.quota.codex.consent", "granted"),
] {
let (status, text) = set(key, value).await?;
seen.push_str(&text);
assert_eq!(status, HttpStatus::OK, "{key}: {text}");
}
let text = read().await?;
seen.push_str(&text);
let gated = reasons(&serde_json::from_str(&text)?);
assert_eq!(gated["claude"], "consent_missing");
assert_eq!(gated["codex"], "flag_off");
assert_eq!(gated["grok"], "flag_off");
for (key, value) in [
("agents.quota.claude.consent", "granted"),
("agents.quota.codex", "true"),
] {
let (status, text) = set(key, value).await?;
seen.push_str(&text);
assert_eq!(status, HttpStatus::OK, "{key}: {text}");
}
let saved = codewhale_runtime::settings::Settings::load_persisted()?;
assert!(saved.agents.quota("claude").enabled);
assert!(saved.agents.quota("claude").consented_at.is_some());
let text = read().await?;
seen.push_str(&text);
let consented = reasons(&serde_json::from_str(&text)?);
assert_eq!(consented["claude"], "not_implemented");
assert_eq!(consented["codex"], "not_implemented");
assert_eq!(consented["opencode"], "flag_off");
for (key, value) in [
("agents.quota.claude.consent", "revoked"),
("agents.quota.codex", "off"),
] {
let (status, text) = set(key, value).await?;
seen.push_str(&text);
assert_eq!(status, HttpStatus::OK, "{key}: {text}");
}
let text = read().await?;
seen.push_str(&text);
let revoked = reasons(&serde_json::from_str(&text)?);
assert_eq!(revoked["claude"], "consent_missing");
assert_eq!(revoked["codex"], "flag_off");
for (key, value) in [
("agents.quota.claude.consent", FIXTURE_TOKEN),
("agents.quota.Claude/../x", "on"),
("agents.quota.claude", FIXTURE_TOKEN),
] {
let (status, text) = set(key, value).await?;
assert_eq!(status, HttpStatus::BAD_REQUEST, "{key}: {text}");
seen.push_str(&text);
}
let (status, text) = set("agents.quota.not-an-agent", "on").await?;
seen.push_str(&text);
assert_eq!(status, HttpStatus::OK, "{text}");
let text = read().await?;
seen.push_str(&text);
assert_eq!(
reasons(&serde_json::from_str(&text)?)["not-an-agent"],
"unknown_agent"
);
let settings_file = fs::read_to_string(config_file.with_file_name("settings.toml"))?;
assert!(
settings_file.contains("[agents.quota.claude]"),
"{settings_file}"
);
assert!(!settings_file.contains(FIXTURE_TOKEN));
assert!(
!seen.contains(FIXTURE_TOKEN),
"a response echoed the fixture token"
);
assert_eq!(snapshot(&credentials), before, "a credential file changed");
handle.abort();
Ok(())
}
@@ -1,285 +0,0 @@
use super::*;
use codewhale_engine::llm_client::mock::MockLlmClient;
use codewhale_engine::runtime_threads::job_operations::{
MEMBER_RESERVED, MemberOperation, MemberOperationRecord,
};
struct AbortOnDrop(tokio::task::AbortHandle);
impl Drop for AbortOnDrop {
fn drop(&mut self) {
self.0.abort();
}
}
fn fleet() -> Value {
json!({
"schema": "fleet",
"schema_revision": 2,
"name": "Review team",
"members": [
{ "id": "reviewer", "role": "reviewer", "provider": "deepseek", "model": "deepseek-v4-pro" }
]
})
}
fn start_body(key: &str, prompt: &str) -> Value {
json!({
"operation_key": key,
"member_id": "reviewer",
"display_name": "Reviewer",
"prompt": prompt,
"fleet": fleet(),
})
}
fn reserve(
threads: &SharedRuntimeThreadManager,
thread_id: &str,
key: &str,
generation: &str,
) -> Result<()> {
threads
.job_operation_store()
.with_job_operations(|transaction| {
let now = chrono::Utc::now().timestamp_millis();
transaction.save_member(&MemberOperationRecord {
schema_version: 1,
operation: MemberOperation {
id: transaction.member_operation_id(thread_id, key)?,
store_id: threads.job_operation_store_id().to_string(),
thread_id: thread_id.to_string(),
member_id: "reviewer".to_string(),
operation_key: key.to_string(),
agent_id: "agent_reservedfixture".to_string(),
state: MEMBER_RESERVED.to_string(),
created_at_ms: now,
updated_at_ms: now,
},
request_fingerprint: "a".repeat(64),
owner_generation: generation.to_string(),
})
})
}
#[tokio::test]
async fn member_starts_are_durable_replayable_and_refuse_foreign_or_mismatched_replay() -> Result<()>
{
let _env = lock_test_env();
let temporary = tempfile::tempdir()?;
let root = temporary.path().canonicalize()?;
let _home = EnvVarGuard::set("CODEWHALE_HOME", root.join("home"));
let workspace = root.join("workspace");
fs::create_dir_all(&workspace)?;
let config = Config::default().with_legacy_root(
Some("member-fixture-key".into()),
Some("http://127.0.0.1:1/v1".into()),
);
let (addr, threads, server) = spawn_test_server_with_root_token_mobile_workspace_and_overrides(
root.clone(),
root.join("sessions"),
None,
false,
workspace.clone(),
TestServerOverrides {
config: Some(config),
..TestServerOverrides::default()
},
)
.await?
.context("the member fixture needs a loopback listener")?;
let _server = AbortOnDrop(server.abort_handle());
threads.set_test_model_client(Arc::new(MockLlmClient::new(Vec::new())));
let client = codewhale_release::tls::reqwest_client();
let url = |path: &str| format!("http://{addr}{path}");
let create_thread = || async {
let created: Value = client
.post(url("/v1/threads"))
.json(&json!({ "model": "deepseek-v4-pro", "mode": "agent", "workspace": workspace }))
.send()
.await?
.error_for_status()?
.json()
.await?;
anyhow::Ok(created["id"].as_str().context("thread id")?.to_string())
};
let thread = create_thread().await?;
let other = create_thread().await?;
let info: Value = client
.get(url("/v1/runtime/info"))
.send()
.await?
.json()
.await?;
assert_eq!(
info["capabilities"]["thread_fleet_member_durable_operations_v1"],
true
);
let store_id = threads.job_operation_store_id().to_string();
let members = url(&format!("/v1/threads/{thread}/members"));
let first = client
.post(&members)
.json(&start_body("team-start-1", "Review the diff"))
.send()
.await?;
let status = first.status();
let receipt: Value = first.json().await?;
assert_eq!(status, StatusCode::OK, "{receipt}");
assert_eq!(receipt["state"], "accepted");
assert_eq!(receipt["runtime_store_id"], store_id.as_str());
assert_eq!(receipt["operation_key"], "team-start-1");
let agent_id = receipt["agent_id"]
.as_str()
.context("agent id")?
.to_string();
let runs = member_runs(&client, addr, &thread).await?;
assert_eq!(runs.len(), 1, "{runs:?}");
assert_eq!(
runs[0]["spec"]["worker_id"],
agent_id.as_str(),
"the receipt names the worker it started"
);
let replayed: Value = client
.post(&members)
.json(&start_body("team-start-1", "Review the diff"))
.send()
.await?
.error_for_status()?
.json()
.await?;
assert_eq!(
replayed, receipt,
"exact replay returns the original receipt"
);
let read: Value = client
.get(url(&format!(
"/v1/threads/{thread}/members/operations/team-start-1"
)))
.send()
.await?
.error_for_status()?
.json()
.await?;
assert_eq!(read, receipt);
let mismatched = client
.post(&members)
.json(&start_body("team-start-1", "Review something else"))
.send()
.await?;
assert_eq!(mismatched.status(), StatusCode::CONFLICT);
let body: Value = mismatched.json().await?;
assert_eq!(body["error"]["code"], "member_operation_mismatch");
let foreign = client
.get(url(&format!(
"/v1/threads/{other}/members/operations/team-start-1"
)))
.send()
.await?;
assert_eq!(
foreign.status(),
StatusCode::NOT_FOUND,
"a key never crosses threads"
);
let mut ghost = start_body("team-ghost", "Review the diff");
ghost["member_id"] = json!("ghost");
let refused = client.post(&members).json(&ghost).send().await?;
assert_eq!(refused.status(), StatusCode::CONFLICT);
let withdrawn = client
.get(url(&format!(
"/v1/threads/{thread}/members/operations/team-ghost"
)))
.send()
.await?;
assert_eq!(
withdrawn.status(),
StatusCode::NOT_FOUND,
"a start the Engine refused withdraws its reservation"
);
let mut stale = start_body("team-start-2", "Review the diff");
stale["expected_store_id"] = json!("another-store");
let stale = client.post(&members).json(&stale).send().await?;
assert_eq!(stale.status(), StatusCode::CONFLICT);
let body: Value = stale.json().await?;
assert_eq!(body["error"]["code"], "member_operation_store_changed");
let mut forged = start_body("team-start-3", "Review the diff");
forged["request_fingerprint"] = json!("b".repeat(64));
let forged = client.post(&members).json(&forged).send().await?;
assert_eq!(forged.status(), StatusCode::BAD_REQUEST);
let generation = threads.job_operation_generation()?;
reserve(&threads, &other, "in-flight", &generation)?;
let deleted = threads.delete_thread(&other).await;
assert!(
deleted
.as_ref()
.is_err_and(|error| error.to_string().contains("pending member operation")),
"a thread with a start in flight is not deleted: {deleted:?}"
);
reserve(
&threads,
&other,
"before-restart",
&Uuid::new_v4().to_string(),
)?;
let abandoned: Value = client
.get(url(&format!(
"/v1/threads/{other}/members/operations/before-restart"
)))
.send()
.await?
.error_for_status()?
.json()
.await?;
assert_eq!(
abandoned["state"], "abandoned",
"a reservation an earlier Engine never started is settled, not left unknown"
);
let cancelled = client
.post(url(&format!("/v1/agent-runs/{agent_id}/cancel")))
.send()
.await?;
assert!(cancelled.status().is_success(), "{}", cancelled.status());
let after_cancel: Value = client
.post(&members)
.json(&start_body("team-start-1", "Review the diff"))
.send()
.await?
.error_for_status()?
.json()
.await?;
assert_eq!(
after_cancel["agent_id"], agent_id,
"owner cancellation never makes a replay start a second worker"
);
assert_eq!(member_runs(&client, addr, &thread).await?.len(), 1);
Ok(())
}
async fn member_runs(
client: &reqwest::Client,
addr: SocketAddr,
thread: &str,
) -> Result<Vec<Value>> {
let listed: Value = client
.get(format!("http://{addr}/v1/agent-runs"))
.send()
.await?
.error_for_status()?
.json()
.await?;
Ok(listed["runs"]
.as_array()
.context("runs")?
.iter()
.filter(|run| run["owner_session_id"] == thread)
.cloned()
.collect())
}
@@ -1,537 +0,0 @@
use super::*;
const SEATS: [&str; 6] = [
"customize.plugins.detail",
"conversation.composer.dock",
"conversation.chat.node",
"workpane.panel",
"sidebar.section",
"command.row",
];
const CONSUMER_BRIDGE_KEYS: [&str; 7] = [
"kind",
"dsh_version",
"cordis_version",
"compatibility_digest",
"declared_range",
"matched_version",
"admission",
];
const CONSUMER_REFUSALS: [(u16, &str); 6] = [
(404, "plugin_ui_not_declared"),
(404, "plugin_ui_seat_not_admitted"),
(400, "plugin_ui_unsupported"),
(422, "plugin_ui_seat_unsupported"),
(400, "plugin_ui_seat_unknown"),
(404, "plugin_ui_file_not_reviewed"),
];
const DSH_CLIENT: &str = "const react = require(\"react\");\n\
const util = require(\"./util\");\n\
const keys = [\"sidebar.right.pane.tab\", \"settings.section\", \"conversation.session.header.utilities\"];\n\
exports.apply = function apply(ctx) { return [react, util.v, keys, ctx]; };\n";
fn write_dsh_package(dir: &Path, name: &str, client: &str) -> Result<PathBuf> {
let package = dir.join(name);
fs::create_dir_all(package.join("lib"))?;
fs::write(
package.join("package.json"),
serde_json::json!({
"name": format!("@demo/{name}"),
"version": "1.0.0",
"exports": { "./client": { "default": "./lib/client.js" } },
"dsh": {
"bundle": { "patch": "./cordis.patch.yml" },
"client": { "platform": "web" }
}
})
.to_string(),
)?;
fs::write(
package.join("cordis.patch.yml"),
"- insert:\n - id: skills\n name: \"@deepseek-ai/dsh-skill-filesystem\"\n config:\n customSkillDirs:\n - ./skills\n",
)?;
fs::create_dir_all(package.join("skills/greet"))?;
fs::write(
package.join("skills/greet/SKILL.md"),
"---\nname: greet\ndescription: Greets a person\n---\nSay hi.\n",
)?;
fs::write(package.join("lib/client.js"), client)?;
fs::write(package.join("lib/util.js"), "exports.v = 1;\n")?;
Ok(package)
}
fn write_native_ui_bundle(dir: &Path, name: &str) -> Result<PathBuf> {
let bundle = write_plugin_source_bundle(dir, name)?;
fs::write(
bundle.join("package.json"),
serde_json::json!({
"name": name,
"version": "1.0.0",
"exports": { "./client": "./client.js" },
"dsh": { "client": { "platform": "web" } }
})
.to_string(),
)?;
fs::write(bundle.join("client.js"), "window.__native = true;\n")?;
Ok(bundle)
}
async fn install_active(
client: &reqwest::Client,
base: &str,
source: String,
) -> Result<serde_json::Value> {
let install: serde_json::Value = client
.post(format!("{base}/install"))
.json(&serde_json::json!({ "source": source }))
.send()
.await?
.error_for_status()?
.json()
.await?;
let name = install["name"]
.as_str()
.expect("installed name")
.to_string();
let detail: serde_json::Value = client
.get(format!("{base}/{name}"))
.send()
.await?
.error_for_status()?
.json()
.await?;
let token = detail["review"]["token"].as_str().unwrap().to_string();
client
.post(format!("{base}/{name}/trust"))
.json(&serde_json::json!({ "token": token }))
.send()
.await?
.error_for_status()?;
let enabled: serde_json::Value = client
.post(format!("{base}/{name}/enable"))
.send()
.await?
.error_for_status()?
.json()
.await?;
assert_eq!(enabled["state"], "active", "{enabled}");
Ok(serde_json::json!({ "name": name, "path": detail["path"] }))
}
async fn ui(
client: &reqwest::Client,
base: &str,
name: &str,
query: &str,
) -> Result<(u16, serde_json::Value)> {
let response = client
.get(format!("{base}/{name}/ui?{query}"))
.send()
.await?;
let status = response.status().as_u16();
Ok((status, response.json().await?))
}
async fn mutate(client: &reqwest::Client, url: String) -> Result<(StatusCode, String)> {
let response = client.post(url).send().await?;
Ok((response.status(), response.text().await?))
}
fn refusal(status: u16, body: &serde_json::Value) -> (u16, String) {
(
status,
body["error"]["code"].as_str().unwrap_or("").to_string(),
)
}
fn assert_consumer_contract(name: &str, minted: &serde_json::Value, seat: &str, key: &str) {
assert_eq!(minted["slot"], seat);
assert_eq!(minted["dsh_slot"], key);
assert!(SEATS.contains(&minted["slot"].as_str().unwrap()));
let key = minted["dsh_slot"].as_str().unwrap();
assert!(key.len() <= 128 && key.chars().next().unwrap().is_ascii_alphanumeric());
assert!(
key.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
);
let bridge = minted["bridge"].as_object().expect("bridge object");
assert_eq!(bridge["kind"], "dsh-client");
for (field, value) in bridge {
assert!(CONSUMER_BRIDGE_KEYS.contains(&field.as_str()), "{field}");
assert!(
value
.as_str()
.is_some_and(|v| !v.is_empty() && v.len() <= 128)
);
}
assert!(bridge.contains_key("dsh_version"));
let base = minted["base"].as_str().unwrap();
assert!(base.starts_with("http://127.0.0.1:"));
assert!(base.ends_with(&format!(
"/v1/apps/plugins/{}/ui/",
urlencoding::encode(name)
)));
let entry = minted["entry"].as_str().unwrap();
assert!(!entry.is_empty() && entry.len() <= 512 && !entry.contains(".."));
assert!(
minted["revision"]
.as_str()
.is_some_and(|r| r.starts_with('"'))
);
}
fn bootstrap_loads_in_node(source: &str) -> Option<String> {
let dir = tempfile::tempdir().ok()?;
let script = dir.path().join("run.js");
let harness = format!(
"var captured;\nvar window = {{ __ModuleLoader__: {{ load: function (r) {{ captured = r; }} }} }};\n{source}\nvar mod = captured.factory(function (id) {{ return {{ id: id }}; }});\nprocess.stdout.write(JSON.stringify({{ id: captured.id, apply: typeof mod.apply, out: mod.apply('ctx') }}));\n"
);
fs::write(&script, harness).ok()?;
let output = std::process::Command::new("node")
.arg(&script)
.output()
.ok()?;
assert!(
output.status.success(),
"the served bootstrap failed under node: {}",
String::from_utf8_lossy(&output.stderr)
);
Some(String::from_utf8_lossy(&output.stdout).into_owned())
}
#[tokio::test]
async fn plugin_ui_dsh_client_serves_admitted_seats_and_denies_and_revokes() -> Result<()> {
let tmp = tempfile::tempdir()?;
let root = tmp.path().join("runtime");
let workspace = tmp.path().join("ws");
fs::create_dir_all(&root)?;
let package = write_dsh_package(tmp.path(), "panel", DSH_CLIENT)?;
let Some((addr, handle)) = spawn_plugin_api_server(root, workspace).await? else {
return Ok(());
};
let client = codewhale_release::tls::reqwest_client();
let base = format!("http://{addr}/v1/apps/plugins");
let installed = install_active(&client, &base, format!("dsh:{}", package.display())).await?;
let name = installed["name"].as_str().unwrap().to_string();
let (status, panel) = ui(&client, &base, &name, "slot=workpane.panel").await?;
assert_eq!(status, 200, "{panel}");
assert_consumer_contract(&name, &panel, "workpane.panel", "sidebar.right.pane.tab");
assert_eq!(panel["entry"], "__codewhale_dsh_bootstrap.js");
let (status, detail) = ui(&client, &base, &name, "slot=customize.plugins.detail").await?;
assert_eq!(status, 200, "{detail}");
assert_consumer_contract(
&name,
&detail,
"customize.plugins.detail",
"settings.section",
);
let (status, explicit) = ui(
&client,
&base,
&name,
"slot=workpane.panel&dsh_slot=sidebar.right.pane.tab",
)
.await?;
assert_eq!(status, 200, "{explicit}");
for (query, expected) in [
("slot=sidebar.section", (404, "plugin_ui_seat_not_admitted")),
("slot=command.row", (404, "plugin_ui_seat_not_admitted")),
(
"slot=workpane.panel&dsh_slot=main.page-menu",
(404, "plugin_ui_seat_not_admitted"),
),
(
"slot=workpane.panel&dsh_slot=settings.section",
(404, "plugin_ui_seat_not_admitted"),
),
(
"slot=workpane.panel&dsh_slot=conversation.session.header.utilities",
(422, "plugin_ui_seat_unsupported"),
),
("slot=chat.node", (400, "plugin_ui_seat_unknown")),
("dsh_slot=settings.section", (400, "plugin_ui_seat_unknown")),
(
"slot=workpane.panel&dsh_slot=..%2Fx",
(400, "plugin_ui_dsh_slot_invalid"),
),
] {
let (status, body) = ui(&client, &base, &name, query).await?;
let (status, code) = refusal(status, &body);
assert_eq!((status, code.as_str()), expected, "{query}: {body}");
assert!(
CONSUMER_REFUSALS.contains(&(status, code.as_str()))
|| code == "plugin_ui_dsh_slot_invalid",
"{query}"
);
}
let revision = panel["revision"].as_str().unwrap().to_string();
let asset_url = format!(
"{}{}",
panel["base"].as_str().unwrap(),
panel["entry"].as_str().unwrap()
);
let served = client
.get(&asset_url)
.header("If-Match", &revision)
.send()
.await?;
assert_eq!(served.status(), StatusCode::OK);
assert!(
served
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("text/javascript"))
);
let bootstrap = served.text().await?;
assert!(bootstrap.contains("\"source/lib/util.js\""));
assert!(!bootstrap.contains("Bearer"));
match bootstrap_loads_in_node(&bootstrap) {
Some(out) => {
let out: serde_json::Value = serde_json::from_str(&out)?;
assert_eq!(out["apply"], "function");
assert_eq!(out["out"][0]["id"], "react");
assert_eq!(out["out"][1], 1);
}
None => eprintln!("node is unavailable; the bootstrap execution check was skipped"),
}
let asset_base = panel["base"].as_str().unwrap().to_string();
let missing = client.get(&asset_url).send().await?;
assert_eq!(missing.status(), StatusCode::PRECONDITION_REQUIRED);
let wrong = client
.get(&asset_url)
.header("If-Match", "\"not-a-revision\"")
.send()
.await?;
assert_eq!(wrong.status(), StatusCode::PRECONDITION_FAILED);
for outside in [
"package.json",
"source/package.json",
"source/lib/index.cjs",
"source/lib/util.js",
] {
let response = client
.get(format!("{asset_base}{outside}"))
.header("If-Match", &revision)
.send()
.await?;
assert_eq!(response.status(), StatusCode::NOT_FOUND, "{outside}");
let body: serde_json::Value = response.json().await?;
assert_eq!(body["error"]["code"], "plugin_ui_file_not_reviewed");
}
let traversal = client
.get(format!("{asset_base}%2e%2e/%2e%2e/etc/passwd"))
.header("If-Match", &revision)
.send()
.await?;
assert!(traversal.status().is_client_error());
let route = format!("{base}/{name}/routes/api/state");
let routed = client
.post(&route)
.header("If-Match", &revision)
.send()
.await?;
assert_eq!(routed.status(), StatusCode::NOT_IMPLEMENTED);
let body: serde_json::Value = routed.json().await?;
assert_eq!(body["error"]["code"], "plugin_route_not_served");
assert_eq!(
client.post(&route).send().await?.status(),
StatusCode::PRECONDITION_REQUIRED
);
assert_eq!(
client
.post(&route)
.header("If-Match", "\"not-a-revision\"")
.send()
.await?
.status(),
StatusCode::PRECONDITION_FAILED
);
assert_eq!(
client
.post(format!("{base}/other/routes/api/state"))
.header("If-Match", &revision)
.send()
.await?
.status(),
StatusCode::PRECONDITION_FAILED
);
assert!(
client
.post(format!("{base}/{name}/routes/%2e%2e/x"))
.header("If-Match", &revision)
.send()
.await?
.status()
.is_client_error()
);
let (status, body) = mutate(&client, format!("{base}/{name}/disable")).await?;
assert_eq!(status, StatusCode::OK, "{body}");
for url in [&asset_url, &route] {
let response = client.get(url).header("If-Match", &revision).send().await?;
assert_eq!(response.status(), StatusCode::PRECONDITION_FAILED, "{url}");
}
let (status, body) = mutate(&client, format!("{base}/{name}/enable")).await?;
assert_eq!(status, StatusCode::OK, "{body}");
let stale = client
.get(&asset_url)
.header("If-Match", &revision)
.send()
.await?;
assert_eq!(stale.status(), StatusCode::PRECONDITION_FAILED);
let (status, again) = ui(&client, &base, &name, "slot=workpane.panel").await?;
assert_eq!(status, 200, "{again}");
let again_revision = again["revision"].as_str().unwrap().to_string();
assert_ne!(again_revision, revision);
let staged = PathBuf::from(installed["path"].as_str().unwrap()).join("source/lib/util.js");
let live = client
.get(&asset_url)
.header("If-Match", &again_revision)
.send()
.await?;
assert_eq!(live.status(), StatusCode::OK);
fs::write(&staged, "exports.v = 2;\n")?;
let tampered = client
.get(&asset_url)
.header("If-Match", &again_revision)
.send()
.await?;
assert_eq!(tampered.status(), StatusCode::PRECONDITION_FAILED);
handle.abort();
Ok(())
}
#[tokio::test]
async fn plugin_ui_dsh_client_with_unprovided_modules_or_ambient_dependencies_is_unsupported()
-> Result<()> {
let tmp = tempfile::tempdir()?;
let root = tmp.path().join("runtime");
let workspace = tmp.path().join("ws");
fs::create_dir_all(&root)?;
let host_module = write_dsh_package(
tmp.path(),
"hostmod",
"require(\"@deepseek-ai/dsh-client-ui-primitives\");\nconst k = \"sidebar.right.pane.tab\";\n",
)?;
let esm = write_dsh_package(
tmp.path(),
"esm",
"const k = \"sidebar.right.pane.tab\";\nexport const apply = () => k;\n",
)?;
let ambient = write_dsh_package(
tmp.path(),
"ambient",
"require(\"left-pad\");\nconst k = \"sidebar.right.pane.tab\";\n",
)?;
let Some((addr, handle)) = spawn_plugin_api_server(root, workspace).await? else {
return Ok(());
};
let client = codewhale_release::tls::reqwest_client();
let base = format!("http://{addr}/v1/apps/plugins");
for package in [host_module, esm, ambient] {
let installed =
install_active(&client, &base, format!("dsh:{}", package.display())).await?;
let name = installed["name"].as_str().unwrap();
let (status, body) = ui(&client, &base, name, "slot=workpane.panel").await?;
assert_eq!(
refusal(status, &body),
(400, "plugin_ui_unsupported".to_string()),
"{name}: {body}"
);
}
handle.abort();
Ok(())
}
#[tokio::test]
async fn plugin_ui_native_client_serves_only_the_detail_seat_and_is_revoked() -> Result<()> {
let tmp = tempfile::tempdir()?;
let root = tmp.path().join("runtime");
let workspace = tmp.path().join("ws");
fs::create_dir_all(&root)?;
let bundle = write_native_ui_bundle(tmp.path(), "nativeui")?;
let Some((addr, handle)) = spawn_plugin_api_server(root.clone(), workspace.clone()).await?
else {
return Ok(());
};
let client = codewhale_release::tls::reqwest_client();
let base = format!("http://{addr}/v1/apps/plugins");
let installed = install_active(&client, &base, format!("path:{}", bundle.display())).await?;
let name = installed["name"].as_str().unwrap().to_string();
let recorded =
isolated_plugin_discovery(&root, &workspace).inspect_registry_for_workspace(&workspace);
let by_app = codewhale_plugins::host_services::PluginApprover::person(
codewhale_plugins::host_services::PersonVia::App,
);
let plugin = recorded.get(&name).unwrap();
assert_eq!(plugin.approved_by.as_ref(), Some(&by_app));
assert_eq!(plugin.enabled_by.as_ref(), Some(&by_app));
let (status, minted) = ui(&client, &base, &name, "slot=customize.plugins.detail").await?;
assert_eq!(status, 200, "{minted}");
assert!(minted.get("dsh_slot").is_none() && minted.get("bridge").is_none());
assert_eq!(minted["entry"], "client.js");
for query in [
"slot=workpane.panel",
"slot=sidebar.section",
"slot=customize.plugins.detail&dsh_slot=settings.section",
] {
let (status, body) = ui(&client, &base, &name, query).await?;
assert_eq!(
refusal(status, &body),
(404, "plugin_ui_seat_not_admitted".to_string()),
"{query}"
);
}
let revision = minted["revision"].as_str().unwrap().to_string();
let asset = format!("{}client.js", minted["base"].as_str().unwrap());
let served = client
.get(&asset)
.header("If-Match", &revision)
.send()
.await?;
assert_eq!(served.status(), StatusCode::OK);
let unlisted = client
.get(format!("{}nothing.js", minted["base"].as_str().unwrap()))
.header("If-Match", &revision)
.send()
.await?;
assert_eq!(unlisted.status(), StatusCode::NOT_FOUND);
let body: serde_json::Value = unlisted.json().await?;
assert_eq!(body["error"]["code"], "plugin_ui_file_not_reviewed");
let routed = client
.post(format!("{base}/{name}/routes/x"))
.header("If-Match", &revision)
.send()
.await?;
assert_eq!(routed.status(), StatusCode::FORBIDDEN);
let body: serde_json::Value = routed.json().await?;
assert_eq!(body["error"]["code"], "plugin_route_not_admitted");
let (status, body) = mutate(&client, format!("{base}/{name}/revoke")).await?;
assert_eq!(status, StatusCode::OK, "{body}");
let after = client
.get(&asset)
.header("If-Match", &revision)
.send()
.await?;
assert_eq!(after.status(), StatusCode::PRECONDITION_FAILED);
handle.abort();
Ok(())
}
@@ -635,7 +635,7 @@ async fn snapshot_in_owner(
snapshot_in_runtime(&state.runtime_threads, &state.sessions_dir, id).await
}
pub(super) async fn snapshot_in_runtime(
async fn snapshot_in_runtime(
runtime: &Arc<RuntimeThreadManager>,
sessions_dir: &Path,
id: String,
@@ -559,7 +559,6 @@ impl RuntimeChatRelayHost {
parent_thread_id: None,
executor: None,
environment: None,
agent_preset: None,
operation_key: None,
model: Some(command.model.clone()),
model_provider: Some(command.model_provider.clone()),
@@ -722,7 +721,6 @@ impl RuntimeChatRelayHost {
parent_thread_id: None,
executor: None,
environment: None,
agent_preset: None,
dynamic_tools: Vec::new(),
environments: Vec::new(),
})
+101 -4
View File
@@ -18,14 +18,111 @@ use serde::Deserialize;
use serde_json::{Value, json};
use std::collections::VecDeque;
use std::time::Duration;
use tokio::io::AsyncWriteExt as _;
use tokio::io::{AsyncBufRead, AsyncWrite};
use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _};
use tokio_util::sync::CancellationToken;
pub use codewhale_util::bounded_lines::{BoundedLines, FrameRefusal, is_frame_refusal};
#[derive(Debug, thiserror::Error)]
pub enum FrameRefusal {
#[error("control frame exceeds the 8 MiB transport limit")]
TooLarge,
#[error("control frame is not UTF-8")]
InvalidUtf8,
}
const _: () =
assert!(codewhale_util::bounded_lines::MAX_FRAME_BYTES == MAX_RUNTIME_IMAGE_BODY_BYTES);
pub fn is_frame_refusal(error: &std::io::Error) -> bool {
error
.get_ref()
.is_some_and(|source| source.is::<FrameRefusal>())
}
/// Cancellation-safe, allocation-bounded newline framing shared by every
/// local control transport. Consumed partial bytes remain owned by the reader.
pub struct BoundedLines<R> {
reader: R,
pub(crate) pending: Vec<u8>,
discarding: bool,
}
impl<R: AsyncBufRead + Unpin> BoundedLines<R> {
pub fn new(reader: R) -> Self {
Self {
reader,
pending: Vec::new(),
discarding: false,
}
}
pub fn into_inner(self) -> R {
self.reader
}
pub async fn next_line(&mut self) -> std::io::Result<Option<String>> {
loop {
let available = self.reader.fill_buf().await?;
if available.is_empty() {
self.discarding = false;
if self.pending.is_empty() {
return Ok(None);
}
if self.pending.len() > MAX_RUNTIME_IMAGE_BODY_BYTES {
self.pending.clear();
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
FrameRefusal::TooLarge,
));
}
let bytes = std::mem::take(&mut self.pending);
return String::from_utf8(bytes).map(Some).map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidData, FrameRefusal::InvalidUtf8)
});
}
let available = &available[..available.len().min(8192)];
let newline = available.iter().position(|&byte| byte == b'\n');
let count = newline.unwrap_or(available.len());
if self.discarding {
self.reader.consume(count + usize::from(newline.is_some()));
if newline.is_some() {
self.discarding = false;
} else {
tokio::task::yield_now().await;
}
continue;
}
if count > (MAX_RUNTIME_IMAGE_BODY_BYTES + 1).saturating_sub(self.pending.len()) {
self.pending.clear();
self.reader.consume(count + usize::from(newline.is_some()));
self.discarding = newline.is_none();
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
FrameRefusal::TooLarge,
));
}
// Do not let Vec's geometric growth double an almost-full frame.
self.pending.reserve_exact(count);
self.pending.extend_from_slice(&available[..count]);
self.reader.consume(count + usize::from(newline.is_some()));
if self.pending.len() > MAX_RUNTIME_IMAGE_BODY_BYTES
&& self.pending.last() != Some(&b'\r')
{
self.pending.clear();
self.discarding = newline.is_none();
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
FrameRefusal::TooLarge,
));
}
if newline.is_some() {
if self.pending.last() == Some(&b'\r') {
self.pending.pop();
}
let bytes = std::mem::take(&mut self.pending);
return String::from_utf8(bytes).map(Some).map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidData, FrameRefusal::InvalidUtf8)
});
}
}
}
}
/// The stdio JSON-RPC loop, generic over its transport so it can be driven by
/// a duplex pipe in tests rather than the process's real stdin/stdout.
+31
View File
@@ -31,6 +31,37 @@ async fn control_framing_accepts_exact_limit_crlf_and_preserves_next_frame() {
assert!(reader.next_line().await.unwrap().is_none());
}
#[tokio::test]
async fn control_framing_refuses_oversize_before_retaining_extra_bytes() {
let input = vec![b'x'; MAX_RUNTIME_IMAGE_BODY_BYTES + 4096];
let mut reader = BoundedLines::new(BufReader::with_capacity(8192, input.as_slice()));
assert_eq!(
reader.next_line().await.unwrap_err().kind(),
std::io::ErrorKind::InvalidData
);
assert!(reader.pending.len() <= MAX_RUNTIME_IMAGE_BODY_BYTES + 1);
assert!(reader.pending.capacity() <= MAX_RUNTIME_IMAGE_BODY_BYTES + 1);
}
#[tokio::test]
async fn control_framing_keeps_consumed_prefix_when_read_future_is_cancelled() {
let (mut input, output) = tokio::io::duplex(64);
input.write_all(b"partial").await.unwrap();
let mut reader = BoundedLines::new(BufReader::new(output));
std::future::poll_fn(|cx| {
let mut read = std::pin::pin!(reader.next_line());
assert!(std::future::Future::poll(read.as_mut(), cx).is_pending());
std::task::Poll::Ready(())
})
.await;
assert_eq!(reader.pending, b"partial");
input.write_all(b"-continued\n").await.unwrap();
assert_eq!(
reader.next_line().await.unwrap().as_deref(),
Some("partial-continued")
);
}
#[tokio::test]
async fn control_framing_rejects_non_utf8_and_keeps_eof_line_contract() {
let mut invalid = BoundedLines::new(BufReader::new(&b"\xff\n"[..]));
-306
View File
@@ -1,306 +0,0 @@
mod acp_support;
#[path = "../../engine/tests/support/acp_conformance.rs"]
mod conformance;
use acp_support::{Client, fixture_config, text_of, updates};
use agent_client_protocol_schema::ProtocolVersion;
use agent_client_protocol_schema::v1 as acp;
use anyhow::{Result, anyhow};
use codewhale_app_server::acp_server::capture_frontend;
use codewhale_engine::llm_client::mock::{MockLlmClient, canned};
use codewhale_engine::runtime_threads::manager::{
RuntimeThreadManager, RuntimeThreadManagerConfig,
};
use conformance::{Allowed, Conformance, Side};
use serde::Serialize;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncWriteExt, BufReader};
const KNOWN: &[Allowed] = &[Allowed {
side: Side::Agent,
frame: "session/load response",
problem: "field `.sessionId` is not in the official type",
reason: "session/load keeps the session/new body with its root sessionId through the 0.10.3 tag; official LoadSessionResponse has no sessionId",
}];
fn wire<T: Serialize>(value: T) -> Value {
serde_json::to_value(value).expect("official type serializes")
}
async fn prompt_to_end(
client: &mut Client,
params: Value,
answer: Value,
) -> Result<(Value, Vec<Value>)> {
client.next_id += 1;
let id = client.next_id;
client
.send(json!({"jsonrpc":"2.0","id":id,"method":"session/prompt","params":params}))
.await?;
let mut frames = Vec::new();
loop {
let frame = client.recv().await?;
if frame["id"] == json!(id) && frame.get("method").is_none() {
return Ok((frame, frames));
}
if frame["method"] == "session/request_permission" {
client
.send(json!({"jsonrpc":"2.0","id":frame["id"],"result":answer}))
.await?;
}
frames.push(frame);
}
}
#[test]
fn every_frame_the_acp_server_writes_is_an_official_v1_shape() -> Result<()> {
std::thread::Builder::new()
.stack_size(64 << 20)
.spawn(|| {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(async {
tokio::time::timeout(Duration::from_secs(120), journey())
.await
.map_err(|_| anyhow!("conformance journey exceeded 120s"))?
})
})?
.join()
.map_err(|_| anyhow!("conformance journey thread panicked"))?
}
async fn journey() -> Result<()> {
let dir = tempfile::tempdir()?;
let _home = codewhale_engine::test_support::SealedHome::at(dir.path());
let workspace = dir.path().join("workspace");
std::fs::create_dir(&workspace)?;
let runtime_dir = dir.path().join("runtime");
let config = fixture_config();
let plugins = Arc::new(codewhale_plugins::PluginRegistry::empty(&workspace));
let manager = Arc::new(RuntimeThreadManager::open_host(
config.clone(),
workspace.clone(),
RuntimeThreadManagerConfig {
mcp_auth_context: Default::default(),
data_dir: runtime_dir.clone(),
task_data_dir: runtime_dir,
sessions_dir: None,
max_active_threads: 4,
},
plugins,
codewhale_engine::core::engine::EngineHostProfile::Acp,
None,
None,
)?);
let provider = Arc::new(MockLlmClient::new(vec![
canned::tool_call_turn(
"plan-call",
"todo_write",
r#"{"todos":[{"content":"write the file","status":"in_progress"}]}"#,
),
canned::tool_call_turn(
"write-call",
"write",
r#"{"path":"allowed.txt","content":"approved"}"#,
),
canned::simple_text_turn("settled after approval"),
canned::tool_call_turn(
"cancel-call",
"write",
r#"{"path":"cancelled.txt","content":"never"}"#,
),
canned::simple_text_turn("unused"),
]));
manager.set_test_model_client(provider.clone());
let sessions_dir = codewhale_engine::session_manager::default_sessions_dir()?;
let frontend = capture_frontend(
config,
"fixture-model".into(),
workspace.clone(),
Arc::clone(&manager),
sessions_dir,
None,
None,
)?;
let mut observed = Conformance::checking(&[Side::Agent]);
let (mut client, agent_read, agent_write) = Client::connect(true);
let first_connection =
frontend.serve(Box::new(BufReader::new(agent_read)), Box::new(agent_write));
let first_script = async {
let result = async {
let (initialized, _) = client
.request(
"initialize",
wire(
acp::InitializeRequest::new(ProtocolVersion::V1)
.client_capabilities(
acp::ClientCapabilities::new()
.fs(acp::FileSystemCapabilities::new())
.terminal(false),
)
.client_info(acp::Implementation::new("conformance", "1.0.0")),
),
)
.await?;
assert_eq!(initialized["result"]["protocolVersion"], 1);
client
.send(json!({"jsonrpc":"2.0","method":"$/cancel_request","params":wire(acp::CancelRequestNotification::new(999_i64))}))
.await?;
let (unknown, _) = client.request("session/not_a_method", json!({})).await?;
assert_eq!(unknown["error"]["code"], -32601);
let (invalid, _) = client
.request("session/set_mode", json!({"modeId":"agent"}))
.await?;
assert_eq!(invalid["error"]["code"], -32602);
let (relative, _) = client
.request("session/new", wire(acp::NewSessionRequest::new("relative/dir")))
.await?;
assert_eq!(relative["error"]["code"], -32602);
let (created, _) = client
.request("session/new", wire(acp::NewSessionRequest::new(&workspace)))
.await?;
let session = created["result"]["sessionId"]
.as_str()
.ok_or_else(|| anyhow!("session/new returned no sessionId"))?
.to_string();
let (mode, _) = client
.request(
"session/set_mode",
wire(acp::SetSessionModeRequest::new(session.clone(), "agent")),
)
.await?;
assert!(mode.get("result").is_some(), "{mode}");
let (option, _) = client
.request(
"session/set_config_option",
wire(acp::SetSessionConfigOptionRequest::new(
session.clone(),
"model",
"fixture-model",
)),
)
.await?;
assert!(option.get("result").is_some(), "{option}");
let (image, _) = client
.request(
"session/prompt",
wire(acp::PromptRequest::new(
session.clone(),
vec![acp::ContentBlock::Image(acp::ImageContent::new(
"AAAA",
"image/png",
))],
)),
)
.await?;
assert_eq!(image["error"]["code"], -32602);
let allow = wire(acp::RequestPermissionResponse::new(
acp::RequestPermissionOutcome::Selected(acp::SelectedPermissionOutcome::new(
"allow-once",
)),
));
let (done, frames) = prompt_to_end(
&mut client,
wire(acp::PromptRequest::new(
session.clone(),
vec![acp::ContentBlock::Text(acp::TextContent::new(
"plan, then write under Ask",
))],
)),
allow,
)
.await?;
assert_eq!(done["result"]["stopReason"], "end_turn");
assert!(!updates(&frames, "tool_call").is_empty());
assert_eq!(text_of(&frames, "agent_message_chunk"), "settled after approval");
client.next_id += 1;
let cancel_id = client.next_id;
client
.send(json!({"jsonrpc":"2.0","id":cancel_id,"method":"session/prompt","params":wire(acp::PromptRequest::new(
session.clone(),
vec![acp::ContentBlock::Text(acp::TextContent::new("write then cancel"))],
))}))
.await?;
let (permission, _) = client.until_permission().await?;
client
.send(json!({"jsonrpc":"2.0","method":"session/cancel","params":wire(acp::CancelNotification::new(session.clone()))}))
.await?;
client
.send(json!({"jsonrpc":"2.0","id":permission["id"],"result":wire(acp::RequestPermissionResponse::new(acp::RequestPermissionOutcome::Cancelled))}))
.await?;
let (cancelled, _) = client.until_response(cancel_id).await?;
assert_eq!(cancelled["result"]["stopReason"], "cancelled");
let (listed, _) = client
.request(
"session/list",
wire(acp::ListSessionsRequest::new().cwd(workspace.clone())),
)
.await?;
assert!(listed["result"]["sessions"].is_array());
Ok::<_, anyhow::Error>(session)
}
.await;
let _ = client.write.shutdown().await;
result
};
let (served, session) = tokio::join!(first_connection, first_script);
served?;
let session = session?;
for (sent, frame) in client.log.take().unwrap_or_default() {
observed.observe(if sent { Side::Client } else { Side::Agent }, &frame);
}
let (mut client, agent_read, agent_write) = Client::connect(true);
let second_connection =
frontend.serve(Box::new(BufReader::new(agent_read)), Box::new(agent_write));
let second_script = async {
let result = async {
client
.request(
"initialize",
wire(acp::InitializeRequest::new(ProtocolVersion::V1)),
)
.await?;
let (missing, _) = client
.request(
"session/load",
wire(acp::LoadSessionRequest::new("no-such-session", &workspace)),
)
.await?;
assert_eq!(missing["error"]["code"], -32602);
let (loaded, replay) = client
.request(
"session/load",
wire(acp::LoadSessionRequest::new(session.clone(), &workspace)),
)
.await?;
assert!(loaded.get("result").is_some(), "{loaded}");
assert!(text_of(&replay, "user_message_chunk").contains("plan, then write under Ask"));
assert!(!updates(&replay, "tool_call_update").is_empty());
Ok::<_, anyhow::Error>(())
}
.await;
let _ = client.write.shutdown().await;
result
};
let (served, script) = tokio::join!(second_connection, second_script);
served?;
script?;
for (sent, frame) in client.log.take().unwrap_or_default() {
observed.observe(if sent { Side::Client } else { Side::Agent }, &frame);
}
manager.shutdown_and_wait().await?;
assert!(
observed.frames() > 20,
"only {} frames observed",
observed.frames()
);
observed.assert_only(KNOWN);
Ok(())
}
-499
View File
@@ -1,499 +0,0 @@
mod acp_support;
use acp_support::{Client, fixture_config, text_of, updates};
use anyhow::{Result, anyhow};
use codewhale_app_server::acp_server::capture_frontend;
use codewhale_engine::llm_client::mock::{MockLlmClient, canned};
use codewhale_engine::runtime_threads::RuntimeTurnStatus;
use codewhale_engine::runtime_threads::manager::{
RuntimeThreadManager, RuntimeThreadManagerConfig,
};
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncWriteExt, BufReader};
#[test]
fn editor_drives_a_session_through_permission_cancel_and_load() -> Result<()> {
std::thread::Builder::new()
.stack_size(64 << 20)
.spawn(|| {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(async {
tokio::time::timeout(Duration::from_secs(120), journey())
.await
.map_err(|_| anyhow!("journey exceeded 120s"))?
})
})?
.join()
.map_err(|_| anyhow!("journey thread panicked"))?
}
async fn journey() -> Result<()> {
let dir = tempfile::tempdir()?;
let _home = codewhale_engine::test_support::SealedHome::at(dir.path());
let workspace = dir.path().join("workspace");
std::fs::create_dir(&workspace)?;
let runtime_dir = dir.path().join("runtime");
let config = fixture_config();
let plugins = Arc::new(codewhale_plugins::PluginRegistry::empty(&workspace));
let manager = Arc::new(RuntimeThreadManager::open_host(
config.clone(),
workspace.clone(),
RuntimeThreadManagerConfig {
mcp_auth_context: Default::default(),
data_dir: runtime_dir.clone(),
task_data_dir: runtime_dir,
sessions_dir: None,
max_active_threads: 4,
},
plugins,
codewhale_engine::core::engine::EngineHostProfile::Acp,
None,
None,
)?);
let provider = Arc::new(MockLlmClient::new(vec![
canned::tool_call_turn(
"provider-id-not-authority",
"write",
r#"{"path":"allowed.txt","content":"approved"}"#,
),
canned::simple_text_turn("settled after approval"),
canned::tool_call_turn(
"provider-id-two",
"write",
r#"{"path":"cancelled.txt","content":"never"}"#,
),
canned::simple_text_turn("resumed in the real session"),
]));
manager.set_test_model_client(provider.clone());
let sessions_dir = codewhale_engine::session_manager::default_sessions_dir()?;
let frontend = capture_frontend(
config,
"fixture-model".into(),
workspace.clone(),
Arc::clone(&manager),
sessions_dir,
None,
None,
)?;
let (mut client, agent_read, agent_write) = Client::connect(false);
let first_connection =
frontend.serve(Box::new(BufReader::new(agent_read)), Box::new(agent_write));
let first_script = async {
let result = async {
let (initialized, _) = client
.request(
"initialize",
json!({"protocolVersion":1,"clientCapabilities":{"terminal":false}}),
)
.await?;
let capabilities = &initialized["result"]["agentCapabilities"];
assert_eq!(initialized["result"]["protocolVersion"], 1);
assert_eq!(capabilities["loadSession"], true);
assert_eq!(capabilities["promptCapabilities"]["image"], false);
assert_eq!(capabilities["promptCapabilities"]["audio"], false);
assert_eq!(capabilities["mcpCapabilities"]["http"], false);
assert_eq!(capabilities["mcpCapabilities"]["sse"], false);
assert!(capabilities["sessionCapabilities"]["list"].is_object());
assert!(capabilities["sessionCapabilities"].get("resume").is_none());
let (relative, _) = client
.request("session/new", json!({"cwd":"relative/dir"}))
.await?;
assert_eq!(relative["error"]["code"], -32602);
let (mcp, _) = client
.request(
"session/new",
json!({"cwd":workspace,"mcpServers":[{"name":"x","command":"x","args":[],"env":[]}]}),
)
.await?;
assert_eq!(mcp["error"]["code"], -32602);
let (resume, _) = client
.request("session/resume", json!({"sessionId":"x","cwd":workspace}))
.await?;
assert_eq!(resume["error"]["code"], -32601);
let (created, _) = client
.request("session/new", json!({"cwd":workspace}))
.await?;
let session = created["result"]["sessionId"]
.as_str()
.ok_or_else(|| anyhow!("session/new returned no sessionId"))?
.to_string();
let (image, _) = client
.request(
"session/prompt",
json!({"sessionId":session,"prompt":[
{"type":"text","text":"look"},
{"type":"image","data":"AAAA","mimeType":"image/png"}
]}),
)
.await?;
assert_eq!(image["error"]["code"], -32602);
assert_eq!(
provider.call_count(),
0,
"a refused prompt never reaches the provider"
);
client.next_id += 1;
let prompt_id = client.next_id;
client
.send(
json!({"jsonrpc":"2.0","id":prompt_id,"method":"session/prompt","params":{
"sessionId":session,"prompt":[{"type":"text","text":"write under Ask"}]}}),
)
.await?;
let (permission, before) = client.until_permission().await?;
assert_eq!(permission["params"]["sessionId"], session.as_str());
assert_eq!(permission["params"]["toolCall"]["kind"], "edit");
let kinds: Vec<_> = permission["params"]["options"]
.as_array()
.unwrap()
.iter()
.map(|option| option["kind"].as_str().unwrap().to_string())
.collect();
assert_eq!(kinds, ["allow_once", "reject_once"]);
assert!(
!updates(&before, "tool_call").is_empty(),
"the tool call is announced before approval is requested"
);
assert!(
updates(&before, "tool_call_update")
.iter()
.all(|frame| frame.pointer("/params/update/status") != Some(&json!("in_progress"))),
"nothing dispatches before the person decides"
);
assert!(!workspace.join("allowed.txt").exists());
client
.send(json!({"jsonrpc":"2.0","id":permission["id"],
"result":{"outcome":{"outcome":"selected","optionId":"allow-once"}}}))
.await?;
let (done, after) = client.until_response(prompt_id).await?;
assert_eq!(done["result"]["stopReason"], "end_turn");
assert_eq!(
std::fs::read_to_string(workspace.join("allowed.txt"))?,
"approved"
);
assert!(
updates(&after, "tool_call_update")
.iter()
.any(|frame| frame.pointer("/params/update/status") == Some(&json!("completed")))
);
assert_eq!(
text_of(&after, "agent_message_chunk"),
"settled after approval"
);
client.next_id += 1;
let cancel_id = client.next_id;
client
.send(
json!({"jsonrpc":"2.0","id":cancel_id,"method":"session/prompt","params":{
"sessionId":session,"prompt":"write then cancel"}}),
)
.await?;
let (second, _) = client.until_permission().await?;
client
.send(json!({"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":session}}))
.await?;
client
.send(json!({"jsonrpc":"2.0","id":second["id"],
"result":{"outcome":{"outcome":"cancelled"}}}))
.await?;
let (cancelled, _) = client.until_response(cancel_id).await?;
assert_eq!(cancelled["result"]["stopReason"], "cancelled");
assert!(!workspace.join("cancelled.txt").exists());
let (listed, _) = client
.request("session/list", json!({"cwd":workspace}))
.await?;
assert!(
listed["result"]["sessions"]
.as_array()
.unwrap()
.iter()
.any(|entry| entry["sessionId"] == session.as_str())
);
client.request("shutdown", json!({})).await?;
Ok::<_, anyhow::Error>(session)
}
.await;
if result.is_err() {
let _ = client.write.shutdown().await;
}
result
};
let (served, session) = tokio::join!(first_connection, first_script);
served?;
let session = session?;
let thread = manager
.list_threads(Default::default(), None)
.await?
.into_iter()
.next()
.ok_or_else(|| anyhow!("no runtime thread was created"))?;
let detail = manager.get_thread_detail(&thread.id).await?;
assert!(
detail.pending_approvals.is_empty(),
"cancel settles the approval"
);
assert_eq!(detail.turns.len(), 2);
assert_eq!(detail.turns[0].status, RuntimeTurnStatus::Completed);
assert_eq!(detail.turns[1].status, RuntimeTurnStatus::Interrupted);
let (mut client, agent_read, agent_write) = Client::connect(false);
let second_connection =
frontend.serve(Box::new(BufReader::new(agent_read)), Box::new(agent_write));
let second_script = async {
client
.request(
"initialize",
json!({"protocolVersion":1,"clientCapabilities":{}}),
)
.await?;
let (missing, _) = client
.request(
"session/load",
json!({"sessionId":"no-such-session","cwd":workspace,"mcpServers":[]}),
)
.await?;
assert_eq!(missing["error"]["code"], -32602);
let (loaded, replay) = client
.request(
"session/load",
json!({"sessionId":session,"cwd":workspace,"mcpServers":[]}),
)
.await?;
assert_eq!(loaded["result"]["sessionId"], session.as_str());
assert!(text_of(&replay, "user_message_chunk").contains("write under Ask"));
assert!(text_of(&replay, "agent_message_chunk").contains("settled after approval"));
assert!(!updates(&replay, "tool_call").is_empty());
let (resumed, frames) = client
.request(
"session/prompt",
json!({"sessionId":session,"prompt":"continue"}),
)
.await?;
assert_eq!(resumed["result"]["stopReason"], "end_turn");
assert_eq!(
text_of(&frames, "agent_message_chunk"),
"resumed in the real session"
);
client.request("shutdown", json!({})).await?;
Ok::<_, anyhow::Error>(())
};
let (served, script) = tokio::join!(second_connection, second_script);
served?;
script?;
let requests = provider.captured_requests();
let last = serde_json::to_string(requests.last().ok_or_else(|| anyhow!("no model request"))?)?;
assert!(
last.contains("write under Ask") && last.contains("settled after approval"),
"the loaded session continues from its real history"
);
manager.shutdown_and_wait().await?;
Ok(())
}
const MCP_FIXTURE: &str = r#"import readline from 'node:readline';
readline.createInterface({input:process.stdin}).on('line', line => {
const r = JSON.parse(line); if (r.id === undefined) return;
let result = {};
if (r.method === 'initialize') result = {protocolVersion:'2024-11-05',capabilities:{tools:{}},serverInfo:{name:'fixture',version:'1'}};
if (r.method === 'tools/list') result = {tools:[{name:'echo',description:'Echo text',inputSchema:{type:'object',properties:{text:{type:'string'}},required:['text']}}]};
if (r.method === 'tools/call') result = {content:[{type:'text',text:'mcp-echo:' + r.params.arguments.text}]};
process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:r.id,result}) + '\n');
});
"#;
#[test]
fn plugin_and_mcp_tools_run_as_acp_tool_calls_through_the_permission_dial() -> Result<()> {
std::thread::Builder::new()
.stack_size(64 << 20)
.spawn(|| {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(async {
tokio::time::timeout(Duration::from_secs(120), extension_journey())
.await
.map_err(|_| anyhow!("extension journey exceeded 120s"))?
})
})?
.join()
.map_err(|_| anyhow!("extension journey thread panicked"))?
}
async fn extension_journey() -> Result<()> {
use codewhale_engine::extension_host::test_support::{FixturePlugins, node_for_tests};
let Some(node) = node_for_tests("plugin_and_mcp_tools_run_as_acp_tool_calls") else {
return Ok(());
};
let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(true);
let fixture = FixturePlugins::new(&["plugin-context"]).await;
let host = fixture.manager(node.clone());
let _host = codewhale_engine::extension_host::TestManagerGuard::install(Arc::clone(&host));
let dir = tempfile::tempdir()?;
let _home = codewhale_engine::test_support::SealedHome::at(dir.path());
let workspace = fixture.workspace().to_path_buf();
let server = dir.path().join("fixture-mcp.mjs");
std::fs::write(&server, MCP_FIXTURE)?;
let mcp_config = dir.path().join("mcp.json");
std::fs::write(
&mcp_config,
serde_json::to_vec(&json!({"servers":{"fixture":{"command":node,"args":[server]}}}))?,
)?;
let runtime_dir = dir.path().join("runtime");
let mut config = fixture_config();
config.set_feature("mcp", true).unwrap();
config.set_feature("extension_host", true).unwrap();
config.mcp_config_path = Some(mcp_config.to_string_lossy().into_owned());
let manager = Arc::new(RuntimeThreadManager::open_host(
config.clone(),
workspace.clone(),
RuntimeThreadManagerConfig {
mcp_auth_context: Default::default(),
data_dir: runtime_dir.clone(),
task_data_dir: runtime_dir,
sessions_dir: None,
max_active_threads: 4,
},
fixture.registry(),
codewhale_engine::core::engine::EngineHostProfile::Acp,
None,
None,
)?);
let provider = Arc::new(MockLlmClient::new(vec![
canned::tool_call_turn("plugin-call", "ctx_probe", "{}"),
canned::tool_call_turn("mcp-call", "mcp_fixture_echo", r#"{"text":"from-acp"}"#),
canned::simple_text_turn("both extension tools ran"),
]));
manager.set_test_model_client(provider.clone());
let frontend = capture_frontend(
config,
"fixture-model".into(),
workspace.clone(),
Arc::clone(&manager),
codewhale_engine::session_manager::default_sessions_dir()?,
None,
None,
)?;
let (mut client, agent_read, agent_write) = Client::connect(false);
let connection = frontend.serve(Box::new(BufReader::new(agent_read)), Box::new(agent_write));
let script = async {
let result = async {
let (initialized, _) = client
.request(
"initialize",
json!({"protocolVersion":1,"clientCapabilities":{}}),
)
.await?;
let meta = &initialized["result"]["agentCapabilities"]["_meta"]["codewhale"];
assert_eq!(meta["plugins"], true);
assert_eq!(meta["configuredMcpServers"], true);
assert_eq!(meta["clientMcpServers"], false);
let (created, _) = client
.request("session/new", json!({"cwd":workspace}))
.await?;
let session = created["result"]["sessionId"]
.as_str()
.ok_or_else(|| anyhow!("session/new returned no sessionId"))?
.to_string();
client.next_id += 1;
let prompt_id = client.next_id;
client
.send(json!({"jsonrpc":"2.0","id":prompt_id,"method":"session/prompt","params":{
"sessionId":session,"prompt":[{"type":"text","text":"use both extension tools"}]}}))
.await?;
let mut asked = Vec::new();
let mut frames = Vec::new();
let done = loop {
let frame = client.recv().await?;
if frame["method"] == "session/request_permission" {
asked.push(
frame["params"]["toolCall"]["title"]
.as_str()
.unwrap_or_default()
.to_string(),
);
client
.send(json!({"jsonrpc":"2.0","id":frame["id"],
"result":{"outcome":{"outcome":"selected","optionId":"allow-once"}}}))
.await?;
} else if frame["id"] == json!(prompt_id) && frame.get("method").is_none() {
break frame;
} else {
frames.push(frame);
}
};
assert_eq!(done["result"]["stopReason"], "end_turn");
assert!(
asked.iter().any(|title| title.starts_with("ctx_probe")),
"the plugin tool asks through the permission dial: {asked:?} {frames:#?}"
);
assert!(
asked
.iter()
.any(|title| title.starts_with("mcp_fixture_echo")),
"the MCP tool asks through the permission dial: {asked:?}"
);
let announced: Vec<_> = updates(&frames, "tool_call")
.iter()
.filter_map(|frame| frame.pointer("/params/update/title")?.as_str())
.map(str::to_string)
.collect();
assert!(announced.iter().any(|title| title == "ctx_probe"), "{announced:?}");
assert!(
announced.iter().any(|title| title == "mcp_fixture_echo"),
"{announced:?}"
);
let completed = updates(&frames, "tool_call_update")
.iter()
.filter(|frame| {
frame.pointer("/params/update/status") == Some(&json!("completed"))
})
.count();
assert_eq!(completed, 2, "both extension calls complete: {frames:#?}");
let rendered = serde_json::to_string(&frames)?;
assert!(rendered.contains("mcp-echo:from-acp"), "{rendered}");
let probed = updates(&frames, "tool_call_update")
.iter()
.filter_map(|frame| frame.pointer("/params/update/content/0/content/text"))
.filter_map(Value::as_str)
.filter_map(|text| serde_json::from_str::<Value>(&text[text.find('{')?..]).ok())
.find_map(|result| Some(PathBuf::from(result.get("workspace")?.as_str()?)))
.ok_or_else(|| anyhow!("the plugin result did not reach the editor: {rendered}"))?;
assert_eq!(probed.canonicalize()?, workspace.canonicalize()?);
assert_eq!(
text_of(&frames, "agent_message_chunk"),
"both extension tools ran"
);
client.request("shutdown", json!({})).await?;
Ok::<_, anyhow::Error>(())
}
.await;
if result.is_err() {
let _ = client.write.shutdown().await;
}
result
};
let (served, scripted) = tokio::join!(connection, script);
served?;
scripted?;
let first = serde_json::to_string(
provider
.captured_requests()
.first()
.ok_or_else(|| anyhow!("no model request"))?,
)?;
assert!(
first.contains("ctx_probe") && first.contains("mcp_fixture_echo"),
"the first model request carries both extension tools"
);
manager.shutdown_and_wait().await?;
host.shutdown().await;
Ok(())
}
-120
View File
@@ -1,120 +0,0 @@
use anyhow::{Result, anyhow};
use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig, SnapshotsConfig};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream, ReadHalf, WriteHalf};
pub const STEP: Duration = Duration::from_secs(30);
pub fn fixture_config() -> Config {
let mut config = Config::default();
config.provider = Some("acp-fixture".into());
config.providers = Some(ProvidersConfig {
custom: HashMap::from([(
"acp-fixture".into(),
ProviderConfig {
kind: Some("openai-compatible".into()),
base_url: Some("http://127.0.0.1:18181/v1".into()),
model: Some("fixture-model".into()),
api_key: Some("local-test-key".into()),
..Default::default()
},
)]),
..Default::default()
});
config.snapshots = Some(SnapshotsConfig {
enabled: false,
..Default::default()
});
config.set_feature("mcp", false).unwrap();
config.set_feature("subagents", false).unwrap();
config
}
pub struct Client {
pub lines: tokio::io::Lines<BufReader<ReadHalf<DuplexStream>>>,
pub write: WriteHalf<DuplexStream>,
pub next_id: u64,
pub log: Option<Vec<(bool, Value)>>,
}
impl Client {
pub fn connect(record: bool) -> (Self, ReadHalf<DuplexStream>, WriteHalf<DuplexStream>) {
let (client, agent) = tokio::io::duplex(1 << 20);
let (agent_read, agent_write) = tokio::io::split(agent);
let (client_read, client_write) = tokio::io::split(client);
(
Client {
lines: BufReader::new(client_read).lines(),
write: client_write,
next_id: 0,
log: record.then(Vec::new),
},
agent_read,
agent_write,
)
}
pub async fn send(&mut self, message: Value) -> Result<()> {
let mut line = serde_json::to_vec(&message)?;
line.push(b'\n');
self.write.write_all(&line).await?;
self.write.flush().await?;
if let Some(log) = &mut self.log {
log.push((true, message));
}
Ok(())
}
pub async fn recv(&mut self) -> Result<Value> {
let line = tokio::time::timeout(STEP, self.lines.next_line())
.await
.map_err(|_| anyhow!("agent produced no frame within {STEP:?}"))??
.ok_or_else(|| anyhow!("agent closed the transport"))?;
let frame: Value = serde_json::from_str(&line)?;
if let Some(log) = &mut self.log {
log.push((false, frame.clone()));
}
Ok(frame)
}
pub async fn request(&mut self, method: &str, params: Value) -> Result<(Value, Vec<Value>)> {
self.next_id += 1;
let id = self.next_id;
self.send(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}))
.await?;
self.until_response(id).await
}
pub async fn until_permission(&mut self) -> Result<(Value, Vec<Value>)> {
let mut frames = Vec::new();
loop {
let frame = self.recv().await?;
if frame["method"] == "session/request_permission" {
return Ok((frame, frames));
}
frames.push(frame);
}
}
pub async fn until_response(&mut self, id: u64) -> Result<(Value, Vec<Value>)> {
let mut frames = Vec::new();
loop {
let frame = self.recv().await?;
if frame["id"] == json!(id) && frame.get("method").is_none() {
return Ok((frame, frames));
}
frames.push(frame);
}
}
}
pub fn updates<'a>(frames: &'a [Value], kind: &str) -> Vec<&'a Value> {
frames
.iter()
.filter(|frame| frame.pointer("/params/update/sessionUpdate") == Some(&json!(kind)))
.collect()
}
pub fn text_of(frames: &[Value], kind: &str) -> String {
updates(frames, kind)
.iter()
.filter_map(|frame| frame.pointer("/params/update/content/text")?.as_str())
.collect()
}
+2 -97
View File
@@ -139,7 +139,6 @@ impl BootstrapPublicationFixture {
if reused {
process_start.push_str("-different-generation");
}
std::fs::create_dir_all(harness.root.join("runtime")).unwrap();
let owner = codewhale_protocol::RuntimeOwnerReceipt {
version: 1,
data_dir: harness.root.join("runtime"),
@@ -169,7 +168,6 @@ impl BootstrapPublicationFixture {
match codewhale_app_server::daemon_client::probe_owner_for_host_startup(
self.owner.config_path.clone(),
Some(self.owner.socket_path.clone()),
&self.owner.data_dir,
)
.await
.unwrap()
@@ -252,105 +250,12 @@ async fn owner_bootstrap_unavailable_is_host_only_and_read_only() {
fixture.parent.socket_identity("daemon.sock").unwrap(),
identity
);
assert_eq!(
std::fs::read_dir(&fixture.owner.data_dir).unwrap().count(),
0,
assert!(
!fixture.owner.data_dir.exists(),
"standalone control must not open or mint a store"
);
}
#[tokio::test]
async fn dead_owner_whose_store_was_deleted_is_discarded_and_startup_proceeds() {
let fixture = BootstrapPublicationFixture::new("boot-gone", true, false).await;
std::fs::remove_dir(&fixture.owner.data_dir).unwrap();
assert!(matches!(
codewhale_app_server::daemon_client::probe_owner_for_host_startup(
fixture.owner.config_path.clone(),
Some(fixture.owner.socket_path.clone()),
&fixture.harness.root.join("another-store"),
)
.await
.unwrap(),
codewhale_app_server::daemon_client::HostOwnerProbe::Unavailable(_)
));
fixture.assert_publication(&fixture.bytes);
let probe = codewhale_app_server::daemon_client::probe_owner_for_host_startup(
fixture.owner.config_path.clone(),
Some(fixture.owner.socket_path.clone()),
&fixture.owner.data_dir,
)
.await
.unwrap();
assert!(matches!(
probe,
codewhale_app_server::daemon_client::HostOwnerProbe::Absent
));
assert!(
fixture
.parent
.read_private_receipt("daemon.sock.owner.json", 16384)
.unwrap()
.is_none()
);
assert!(!fixture.owner.data_dir.exists());
fixture.bind_replacement(None).await.unwrap();
}
async fn assert_gone_store_spelled_as_is_discarded(
label: &str,
spell: impl FnOnce(&Path) -> PathBuf,
) {
let fixture = BootstrapPublicationFixture::new(label, true, false).await;
std::fs::remove_dir(&fixture.owner.data_dir).unwrap();
let spelled = spell(&fixture.harness.root);
assert_ne!(spelled, fixture.owner.data_dir);
assert!(matches!(
codewhale_app_server::daemon_client::probe_owner_for_host_startup(
fixture.owner.config_path.clone(),
Some(fixture.owner.socket_path.clone()),
&spelled,
)
.await
.unwrap(),
codewhale_app_server::daemon_client::HostOwnerProbe::Absent
));
assert!(
fixture
.parent
.read_private_receipt("daemon.sock.owner.json", 16384)
.unwrap()
.is_none()
);
}
#[tokio::test]
async fn dead_owner_is_discarded_when_the_selected_store_is_spelled_through_a_symlink() {
assert_gone_store_spelled_as_is_discarded("boot-gone-link", |root| {
std::os::unix::fs::symlink(root, root.join("alias")).unwrap();
root.join("alias").join("runtime")
})
.await;
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn dead_owner_is_discarded_when_the_selected_store_is_spelled_in_another_letter_case() {
assert_gone_store_spelled_as_is_discarded("boot-gone-case", |root| {
let upper = PathBuf::from(root.to_string_lossy().to_uppercase());
assert!(upper.exists(), "this test needs a case-insensitive volume");
upper.join("RUNTIME")
})
.await;
}
#[tokio::test]
async fn live_owner_with_a_missing_store_is_never_discarded() {
let fixture = BootstrapPublicationFixture::new("boot-gone-live", false, false).await;
std::fs::remove_dir(&fixture.owner.data_dir).unwrap();
fixture.capture().await;
fixture.assert_publication(&fixture.bytes);
}
#[tokio::test]
async fn owner_bootstrap_live_process_and_reused_pid_refuse_retirement() {
for reused in [false, true] {
+12 -39
View File
@@ -117,7 +117,7 @@ struct Cli {
#[arg(
long,
value_name = "BOOL",
help = "Control usage reporting (default on; Codewhale + PostHog; \
help = "Control aggregate usage counting (default on; Codewhale + PostHog; \
durable off: config set telemetry false; CODEWHALE_TELEMETRY=0 always wins)"
)]
telemetry: Option<bool>,
@@ -234,10 +234,10 @@ enum Commands {
#[command(about = "Install a plugin bundle without trusting or enabling it")]
Install(TuiPassthroughArgs),
#[command(
about = "Inspect, review, trust, enable, disable or revoke plugin bundles",
about = "Inspect or restage reviewed plugin bundles",
alias = "plugin",
override_usage = "codewhale plugins <COMMAND>",
after_help = "Commands:\n status [NAME] [--json] Inspect plugin status and diagnostics\n list [NAME] [--json] Alias of status\n restage <NAME> [--json] Restore an eligible reviewed plugin snapshot\n trust <NAME> [--json] Show the capability review; in a terminal, then ask\n trust <NAME> --review-token T [--yes] [--json] Trust exactly the content the bundle review token names\n enable <NAME> [--json] Enable a trusted plugin\n disable <NAME> [--json] Disable a plugin, keeping its trust\n revoke <NAME> [--json] Revoke trust\n\nThe bundle review token ties trust to exact content; it does not show that anyone read the review,\nand it is not the host-service review token. A --yes trust is recorded as the command line. When\nCODEWHALE_AGENT_PROJECT marks the process, as it does every command the agent runs, trust and enable\nare the agent's, for that project only; that mark is a label the agent could remove in Full Access."
after_help = "Commands:\n status [NAME] [--json] Inspect plugin status and diagnostics\n list [NAME] [--json] Alias of status\n restage <NAME> [--json] Restore an eligible reviewed plugin snapshot"
)]
Plugins(TuiPassthroughArgs),
/// Bootstrap MCP config and/or skills directories.
@@ -265,16 +265,17 @@ Common forwarded flags:
--output-format <FORMAT> Output format: text or stream-json
--hooks Opt in to configured hooks (tool_call_before, shell_env)
Plain `codewhale exec` runs the agent with the normal tool surface under the
configured sandbox and approval posture. Use `--no-tools` for one answer with
no tools. `--auto` selects automatic approvals and Full Access by default. A
reply cut off at the provider's output limit is continued in the same turn, at
most 8 model steps unless `--max-turns` says otherwise.
Plain `codewhale exec` is a one-shot model response: one Engine turn with the
same system prompt as every other run, and no tools. Use `--auto` for
non-interactive agent-with-tools execution. Tools are offered only with
`--auto`, `--yolo`, `--allowed-tools`, or when resuming a session; limits such
as `--max-turns`, `--disallowed-tools` or `--sandbox`, and the output format,
never add tools. A reply cut off at the provider's output limit is continued
in the same turn, at most 8 model steps unless `--max-turns` says otherwise.
--auto defaults to Full Access: no shell sandbox and trust mode on. Use --sandbox workspace-write to keep the shell sandbox and file-tool workspace restrictions; stricter configured policies also apply. A denied sandbox retry requires --allow-sandbox-elevation or --sandbox danger-full-access.
Any --sandbox other than danger-full-access (or an equivalent sandbox_mode in config) disables trust mode.
Runs that offer tools, stream-json runs, and resumed sessions are saved for codewhale sessions, exec --continue, and codewhale receipts <id>. Answer-only (--no-tools) text/--json runs are not saved unless compaction needs recovery.
Runs that offer tools, stream-json runs, and resumed sessions are saved for codewhale sessions, exec --continue, and codewhale receipts <id>. Plain answer-only text/--json runs are not saved unless compaction needs recovery.
Put flags before the prompt. Put -- before a prompt starting with - or containing literal exec flags.
Piped stdin is the prompt when no prompt argument is given, or is appended to it; with a prompt argument, stdin that sends nothing for 2 seconds is ignored with a note on stderr.
")]
Exec(TuiPassthroughArgs),
/// Manage durable Agent fleet runs.
@@ -1957,7 +1958,7 @@ enum ConfigCommand {
Unset {
key: String,
},
/// Review usage reporting by Codewhale and PostHog (default on).
/// Review aggregate usage counting by Codewhale and PostHog (default on).
Telemetry {
/// Optional compatibility form: enable future sessions under this policy version.
#[arg(long, value_name = "VERSION")]
@@ -6792,10 +6793,6 @@ fn apply_tui_env(cli: &Cli, resolved_runtime: &ResolvedRuntimeOptions, passthrou
codewhale_config::TELEMETRY_FLOOR_ENV,
if floor { "1" } else { "0" },
);
set_tui_env(
codewhale_config::TELEMETRY_SOURCE_ENV,
resolved_runtime.telemetry_source.as_str(),
);
if let Some(endpoint) = resolved_runtime.telemetry_endpoint.as_ref() {
set_tui_env("CODEWHALE_TELEMETRY_ENDPOINT", endpoint);
}
@@ -7230,30 +7227,6 @@ mod tests {
);
}
#[test]
fn dispatcher_hands_the_telemetry_source_to_the_tui() {
let _lock = env_lock();
let _guards = [
ScopedEnvVar::remove("CODEWHALE_TELEMETRY"),
ScopedEnvVar::remove("DEEPSEEK_TELEMETRY"),
ScopedEnvVar::remove(codewhale_config::TELEMETRY_FLOOR_ENV),
ScopedEnvVar::remove(codewhale_config::TELEMETRY_SOURCE_ENV),
];
let cli = parse_ok(&["codewhale"]);
let mut runtime = resolved_runtime_for_test(ProviderKind::NvidiaNim, ProviderSource::Cli);
runtime.telemetry = false;
runtime.telemetry_source = codewhale_config::TelemetrySource::Config;
apply_tui_env(&cli, &runtime, &[]);
assert_eq!(std::env::var("CODEWHALE_TELEMETRY").as_deref(), Ok("false"));
assert!(std::env::var(codewhale_config::TELEMETRY_FLOOR_ENV).is_ok());
assert_eq!(
std::env::var(codewhale_config::TELEMETRY_SOURCE_ENV).as_deref(),
Ok("config")
);
}
#[test]
fn clap_command_definition_is_consistent() {
Cli::command().debug_assert();
+2 -129
View File
@@ -425,74 +425,6 @@ pub struct RuntimeRequestStats {
pub provider_reported_output_tokens: u64,
}
#[derive(Debug, Default, serde::Serialize)]
pub struct SessionUsageStats {
pub sessions: u64,
pub usage_receipts: u64,
pub usage_receipts_incomplete: u64,
pub provider_reported_input_tokens: u64,
pub provider_reported_output_tokens: u64,
pub sessions_with_total_tokens_only: u64,
pub total_tokens_only: u64,
}
fn record_session_usage(v: &Value, rollup: &mut Rollup) {
let Some(sources) = v
.pointer("/metadata/cost/accounted_usage_sources")
.and_then(Value::as_object)
else {
let total = v
.pointer("/metadata/total_tokens")
.and_then(Value::as_u64)
.unwrap_or(0);
if total > 0 {
let stats = &mut rollup.session_usage;
stats.sessions_with_total_tokens_only =
stats.sessions_with_total_tokens_only.saturating_add(1);
stats.total_tokens_only = stats.total_tokens_only.saturating_add(total);
}
return;
};
let stats = &mut rollup.session_usage;
let mut counted = false;
for contribution in sources.values() {
let record = contribution.get("record");
let reported = match record
.and_then(|record| record.pointer("/settlement/coverage"))
.and_then(Value::as_str)
{
Some(coverage) => matches!(coverage, "reported" | "incomplete"),
None => record
.and_then(|record| record.pointer("/usage/usage"))
.is_some_and(|usage| {
usage.get("input_tokens").and_then(Value::as_u64) != Some(0)
|| usage.get("output_tokens").and_then(Value::as_u64) != Some(0)
}),
};
if !reported {
continue;
}
let tokens = |name: &str| {
record
.and_then(|record| record.pointer(&format!("/usage/usage/{name}")))
.and_then(Value::as_u64)
};
let (Some(input), Some(output)) = (tokens("input_tokens"), tokens("output_tokens")) else {
stats.usage_receipts_incomplete = stats.usage_receipts_incomplete.saturating_add(1);
continue;
};
stats.usage_receipts = stats.usage_receipts.saturating_add(1);
stats.provider_reported_input_tokens =
stats.provider_reported_input_tokens.saturating_add(input);
stats.provider_reported_output_tokens =
stats.provider_reported_output_tokens.saturating_add(output);
counted = true;
}
if counted {
stats.sessions = stats.sessions.saturating_add(1);
}
}
/// Top-level rollup.
#[derive(Debug, Default, serde::Serialize)]
pub struct Rollup {
@@ -513,7 +445,6 @@ pub struct Rollup {
pub capacity: CapacityStats,
pub credentials: CredentialStats,
pub runtime_requests: RuntimeRequestStats,
pub session_usage: SessionUsageStats,
/// Total lines read across all sources.
pub total_lines: u64,
/// Lines successfully parsed.
@@ -1005,8 +936,6 @@ fn read_session_file(path: &Path, since: Option<DateTime<Utc>>, rollup: &mut Rol
rollup.touch_ts(&ts);
}
record_session_usage(&v, rollup);
// Walk messages looking for tool_use calls with associated results.
let messages = match v.get("messages").and_then(|m| m.as_array()) {
Some(m) => m,
@@ -1711,44 +1640,15 @@ fn print_human(rollup: &Rollup, since: Option<DateTime<Utc>>) {
);
}
if runtime.provider_usage_receipts == 0 {
println!(
"Provider usage receipts (Runtime events): (none recorded; this is not zero usage)"
);
println!("Provider usage receipts: (none recorded; this is not zero usage)");
} else {
println!(
"Provider usage receipts (Runtime events): {} records, {} input tokens, {} output tokens",
"Provider usage receipts: {} records, {} input tokens, {} output tokens",
fmt_num(runtime.provider_usage_receipts),
fmt_num(runtime.provider_reported_input_tokens),
fmt_num(runtime.provider_reported_output_tokens),
);
}
let session_usage = &rollup.session_usage;
if session_usage.usage_receipts == 0 {
println!(
"Provider usage receipts (saved terminal sessions): (none recorded; this is not zero usage)"
);
} else {
println!(
"Provider usage receipts (saved terminal sessions): {} records in {} sessions, {} input tokens, {} output tokens",
fmt_num(session_usage.usage_receipts),
fmt_num(session_usage.sessions),
fmt_num(session_usage.provider_reported_input_tokens),
fmt_num(session_usage.provider_reported_output_tokens),
);
}
if session_usage.sessions_with_total_tokens_only > 0 {
println!(
"Saved sessions with a combined token total only: {} sessions, {} tokens (no per-call usage receipts saved)",
fmt_num(session_usage.sessions_with_total_tokens_only),
fmt_num(session_usage.total_tokens_only),
);
}
if session_usage.usage_receipts_incomplete > 0 {
println!(
"Saved-session usage coverage: {} usage receipts incomplete, not counted as zero",
fmt_num(session_usage.usage_receipts_incomplete),
);
}
if runtime.diagnostics_unavailable_turn_receipts > 0
|| runtime.diagnostics_incomplete_turn_receipts > 0
|| runtime.terminal_receipts_without_identity > 0
@@ -2341,33 +2241,6 @@ mod tests {
assert_eq!(runtime.model_requests_started, 2, "status is not a request");
}
#[test]
fn saved_terminal_session_usage_is_counted_apart_from_runtime_events() {
let session = serde_json::json!({
"metadata": { "cost": { "accounted_usage_sources": {
"a": { "record": { "settlement": { "coverage": "reported" }, "usage": { "usage": { "input_tokens": 40, "output_tokens": 6 } } } },
"b": { "record": { "settlement": { "coverage": "missing" }, "usage": { "usage": { "input_tokens": 0, "output_tokens": 0 } } } },
"c": { "record": { "settlement": { "coverage": "incomplete" }, "usage": { "usage": { "input_tokens": 3 } } } }
} } }
});
let mut rollup = Rollup::default();
record_session_usage(&session, &mut rollup);
let usage = &rollup.session_usage;
assert_eq!(usage.usage_receipts, 1);
assert_eq!(usage.usage_receipts_incomplete, 1);
assert_eq!(usage.sessions, 1);
assert_eq!(usage.provider_reported_input_tokens, 40);
assert_eq!(usage.provider_reported_output_tokens, 6);
record_session_usage(&serde_json::json!({ "metadata": {} }), &mut rollup);
assert_eq!(rollup.session_usage.sessions, 1);
record_session_usage(
&serde_json::json!({ "metadata": { "total_tokens": 900 } }),
&mut rollup,
);
assert_eq!(rollup.session_usage.sessions_with_total_tokens_only, 1);
assert_eq!(rollup.session_usage.total_tokens_only, 900);
}
#[test]
fn runtime_usage_receipts_deduplicate_by_runtime_event_identity() {
let usage = runtime_event(
@@ -39,8 +39,6 @@ pub struct Receipt {
/// own record; empty when no turn recorded one.
pub postures: Vec<&'static str>,
pub totals: ReceiptTotals,
#[serde(skip_serializing_if = "Option::is_none")]
pub usage: Option<ReceiptUsage>,
pub actions: Vec<ReceiptAction>,
/// Actions left off the list because it hit [`MAX_RECEIPT_ACTIONS`].
pub omitted_actions: usize,
@@ -49,50 +47,6 @@ pub struct Receipt {
pub claim_ceiling: [&'static str; 3],
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ReceiptUsage {
#[serde(skip_serializing_if = "Option::is_none")]
pub tokens: Option<ReceiptTokens>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cost: Option<ReceiptCost>,
}
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct ReceiptTokens {
#[serde(skip_serializing_if = "Option::is_none")]
pub input: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub output: Option<u64>,
pub total: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub cache_read: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cache_write: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub calls: Option<usize>,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ReceiptCost {
pub state: ReceiptCostState,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<f64>,
pub currency: &'static str,
pub priced_turns: u32,
pub unpriced_turns: u32,
pub report: String,
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ReceiptCostState {
Priced,
Partial,
Unknown,
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SourceKind {
@@ -263,7 +263,6 @@ fn empty_receipt() -> Receipt {
turn: None,
postures: vec![],
totals: ReceiptTotals::default(),
usage: None,
actions: vec![],
omitted_actions: 0,
not_recorded: vec![],
+12 -17
View File
@@ -217,21 +217,7 @@ pub fn cost(contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult {
};
let projection = diagnostics.cost_projection();
let details = arg.is_some_and(|arg| arg.trim().eq_ignore_ascii_case("details"));
if cost_is_subscription_only(&projection) && !details {
return CommandResult::message(format!(
"Session Cost:\n ─────────────────────────────\n {SUBSCRIPTION_ONLY_COST_NOTE}\n\n Run /cost details for the route receipts."
));
}
match cost_report(&projection, presentation) {
Ok(report) => CommandResult::message(report),
Err(error) => CommandResult::error(error),
}
}
pub const SUBSCRIPTION_ONLY_COST_NOTE: &str = "These routes use subscription billing. Codewhale does not know the amount charged by your provider.";
pub fn cost_is_subscription_only(projection: &DebugCostProjection) -> bool {
projection.total == 0.0
let plan_only = projection.total == 0.0
&& projection.priced_turns == 0
&& projection.unpriced_turns == 0
&& !projection.legacy_coverage_unknown
@@ -241,10 +227,19 @@ pub fn cost_is_subscription_only(projection: &DebugCostProjection) -> bool {
receipt
.split_whitespace()
.any(|field| field == "billing_mode=subscription")
})
});
if plan_only && !details {
return CommandResult::message(
"Session Cost:\n ─────────────────────────────\n These routes use subscription billing. Codewhale does not know the amount charged by your provider.\n\n Run /cost details for the route receipts.".to_string(),
);
}
match cost_report(&projection, presentation) {
Ok(report) => CommandResult::message(report),
Err(error) => CommandResult::error(error),
}
}
pub fn cost_report(
fn cost_report(
cost: &DebugCostProjection,
presentation: &dyn CommandPresentationContext,
) -> Result<String, String> {
@@ -414,53 +414,6 @@ pub fn action_line(action: &ReceiptAction) -> String {
one_line(&line)
}
fn tokens_line(tokens: &ReceiptTokens) -> String {
let mut line = match (tokens.input, tokens.output) {
(Some(input), Some(output)) => {
format!("Tokens: {input} in · {output} out · {} total", tokens.total)
}
_ => format!("Tokens: {} total", tokens.total),
};
if let Some(calls) = tokens.calls {
line.push_str(&format!(
" · {}",
plural(calls, "provider call", "provider calls")
));
}
let detail: Vec<String> = [
("cache read", tokens.cache_read),
("cache write", tokens.cache_write),
("reasoning", tokens.reasoning),
]
.into_iter()
.filter_map(|(label, value)| value.map(|value| format!("{value} {label}")))
.collect();
if !detail.is_empty() {
line.push_str(&format!(" ({})", detail.join(", ")));
}
line
}
fn usage_block(usage: &ReceiptUsage) -> String {
let mut out = String::new();
if let Some(tokens) = &usage.tokens {
out.push_str(&one_line(&tokens_line(tokens)));
out.push('\n');
}
if let Some(cost) = &usage.cost {
out.push_str("Cost, as /cost reports it:\n");
for line in cost
.report
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
{
out.push_str(&format!(" {}\n", one_line(line)));
}
}
out
}
/// The readable receipt: header, totals, one line per action, then what the
/// record does not hold. Valid Markdown and plain enough for a terminal.
#[must_use]
@@ -504,10 +457,6 @@ pub fn render_markdown(receipt: &Receipt) -> String {
out.push_str("\n\n");
out.push_str(&one_line(&totals_line(receipt)));
out.push_str("\n\n");
if let Some(usage) = &receipt.usage {
out.push_str(&usage_block(usage));
out.push('\n');
}
let width = receipt.actions.len().to_string().len();
for action in &receipt.actions {
out.push_str(&format!(
+49 -70
View File
@@ -354,18 +354,6 @@
"cache_read_per_m": 0.145
},
"reason": "Fireworks hosts DeepSeek V4 Pro at its own published rates, as in the reviewed table in crates/engine/src/pricing.rs; Models.dev lists a flat 1.2/1.2 rate with a 0.6 cache-read rate for this deployment."
},
{
"provider": "google",
"id": "gemini-4-argon",
"max_output": 65536,
"reason": "Google publishes 65,536 output tokens by default for synchronous requests (https://aistudio.google.com/docs/models/gemini-4-argon, read 2026-11-10); Models.dev lists 32768."
},
{
"provider": "google",
"id": "gemini-4-carbon",
"max_output": 65536,
"reason": "Google publishes 65,536 output tokens by default for synchronous requests (https://aistudio.google.com/docs/models/gemini-4-carbon, read 2026-11-10); Models.dev lists 32768."
}
],
"reviewed": {
@@ -407,7 +395,7 @@
"reasoning"
],
"reasoning": true,
"source": "official vendor model docs, verified 2026-11-10; see source_receipts",
"source": "https://models.dev/catalog.json anthropic/claude-fable-5-2, retrieved 2026-11-10",
"family": "Anthropic"
},
"claude-opus-5-5": {
@@ -1188,9 +1176,6 @@
"context_window": 1000000,
"max_output": 131072
},
"qwen4-max-preview": {
"source": "Token Plan Supported Models table, https://qwencloud.com/pricing/token-plan, verified 2026-11-11: id qwen4-max-preview (New), capabilities Text Generation, Reasoning Model, Visual Understanding; see source_receipts"
},
"step-3.5-flash": {
"context_window": 256000,
"modalities": [
@@ -1644,16 +1629,14 @@
"family": "Google"
},
"gemini-4-argon": {
"source": "official vendor model docs, verified 2026-11-10; see source_receipts",
"source": "official vendor model docs, verified 2026-10-17; see source_receipts",
"context_window": 1048576,
"max_output": 65536,
"reasoning": true,
"family": "Google"
},
"gemini-4-carbon": {
"source": "official vendor model docs, verified 2026-11-10; see source_receipts",
"source": "https://models.dev/catalog.json google/gemini-4-carbon, retrieved 2026-11-10",
"context_window": 1048576,
"max_output": 65536,
"max_output": 32768,
"reasoning": true,
"family": "Google"
},
@@ -1891,38 +1874,53 @@
"source": "preserved public presentation facts, not route availability"
},
"mistral-large-4": {
"source": "models.dev mistral/mistral-large-4, discovered 2026-11-11; unreviewed",
"source": "models.dev mistral/mistral-large-4, discovered 2026-11-10; unreviewed",
"context_window": 1048576,
"max_output": 262144,
"reasoning": true,
"family": "Mistral"
},
"mistral-large-4-0-8": {
"source": "models.dev mistral/mistral-large-4-0-8, discovered 2026-11-10; unreviewed",
"context_window": 1048576,
"max_output": 262144,
"reasoning": true,
"family": "Mistral"
},
"minimax-m3.1-flash": {
"source": "models.dev minimax/MiniMax-M3.1-Flash, discovered 2026-11-11; unreviewed",
"source": "models.dev minimax/MiniMax-M3.1-Flash, discovered 2026-11-10; unreviewed",
"context_window": 1000000,
"max_output": 524288,
"reasoning": true,
"family": "Minimax"
"family": "MiniMax"
},
"kimi-k3.1-pro": {
"source": "models.dev moonshotai/kimi-k3.1-pro, discovered 2026-11-11; unreviewed",
"source": "models.dev moonshotai/kimi-k3.1-pro, discovered 2026-11-10; unreviewed",
"context_window": 1048576,
"max_output": 1048576,
"reasoning": true,
"family": "Moonshot"
"family": "Moonshot/Kimi"
},
"kimi-k3.1-pro-highspeed": {
"source": "models.dev moonshotai/kimi-k3.1-pro-highspeed, discovered 2026-11-11; unreviewed",
"source": "models.dev moonshotai/kimi-k3.1-pro-highspeed, discovered 2026-11-10; unreviewed",
"context_window": 1048576,
"max_output": 1048576,
"reasoning": true,
"family": "Moonshot"
"family": "Moonshot/Kimi"
},
"gpt-6.1-terra": {
"source": "models.dev openai/gpt-6.1-terra, discovered 2026-11-11; unreviewed",
"source": "models.dev openai/gpt-6.1-terra, discovered 2026-11-10; unreviewed",
"context_window": 1050000,
"max_output": 128000,
"reasoning": true,
"family": "OpenAi"
"family": "OpenAI"
},
"muse-ember-1.0": {
"source": "models.dev meta/muse-ember-1.0, discovered 2026-11-10; unreviewed",
"context_window": 1048576,
"max_output": 524288,
"reasoning": true,
"family": "Meta"
}
},
"official_deepseek_aliases": {
@@ -4180,12 +4178,6 @@
"added_at": "2026-08-02",
"aliases": []
},
{
"id": "qwen4-max-preview",
"label": "Qwen",
"added_at": "2026-11-10",
"aliases": []
},
{
"id": "kimi-for-coding-highspeed",
"label": "Moonshot/Kimi",
@@ -4582,11 +4574,19 @@
{
"id": "mistral-large-4",
"label": "Mistral",
"added_at": "2026-11-05",
"added_at": "2026-10-06",
"aliases": [
"mistral-large-4"
]
},
{
"id": "mistral-large-4-0-8",
"label": "Mistral",
"added_at": "2026-10-06",
"aliases": [
"mistral-large-4-0-8"
]
},
{
"id": "MiniMax-M3.1-Flash",
"label": "MiniMax",
@@ -4618,6 +4618,14 @@
"aliases": [
"gpt-6.1-terra"
]
},
{
"id": "muse-ember-1.0",
"label": "Meta",
"added_at": "2026-11-09",
"aliases": [
"muse-ember-1.0"
]
}
],
"constants": {
@@ -4773,12 +4781,7 @@
"https://developers.openai.com/api/docs/models/gpt-6-sol": "verified 2026-10-17: $2 in / $0.20 cached / $10 out / $2.50 cache write; gpt-6.1-sol $2 / $0.10 / $10 / $2.50 and gpt-6-luna $0.10 / $0.01 / $0.50 per the changelog",
"https://developers.openai.com/api/docs/deprecations": "verified 2026-10-17: gpt-5.3-codex and gpt-5.1 move to gpt-6-sol and gpt-5.4-nano to gpt-6-luna, all shutting down 2027-04-01; the catalog has no lifecycle field, so the rows stay until shutdown",
"https://ai.google.dev/gemini-api/docs/changelog": "verified 2026-10-17: gemini-4-argon GA 2026-10-13, gemini-3.8-flash GA 2026-09-02; gemini-3.7-flash (auto-routed to gemini-3.8-flash) and gemini-3.5-flash (auto-routed to gemini-3.6-flash) deprecated 2026-10-08 and kept only as selector aliases",
"https://ai.google.dev/gemini-api/docs/models": "verified 2026-10-17: gemini-4-argon and gemini-3.8-flash are stable; argon's 1M context is stated; the output ceiling is recorded from its own model page (see the aistudio.google.com receipts, verified 2026-11-10)",
"https://aistudio.google.com/docs/models/gemini-4-carbon": "verified 2026-11-10: model code gemini-4-carbon, 1,048,576 context, 65,536 output by default (up to 1,048,576 with long decode), thinking levels low, medium and high, function calling, structured outputs, implicit caching only; thought signatures are not mentioned",
"https://aistudio.google.com/docs/models/gemini-4-argon": "verified 2026-11-10: model code gemini-4-argon, 1,048,576 context, 65,536 output by default (up to 1,048,576 with long decode), thinking levels low, medium and high",
"https://aistudio.google.com/docs/pricing": "verified 2026-11-10: gemini-4-carbon is $2 in / $10 out / $0.10 cached through 2026-11-30 and $4 / $20 / $0.20 from 2026-12-01; the catalog carries one undated price, so the row shows the current rate",
"https://platform.claude.com/docs/en/models/fable-5-2/overview": "verified 2026-11-10: claude-fable-5-2, 1M context, 128K output, adaptive thinking always on, $8 in / $40 out, text and image input",
"https://platform.claude.com/docs/en/build-with-claude/effort": "verified 2026-11-10: xhigh is its own effort level on Fable 5.2, Mythos 5.2, Fable 5.1, Fable 5, Opus 5.5, Opus 5, Opus 4.8, Opus 4.7, Sonnet 5.5, Sonnet 5 and Haiku 5.5; not every model that supports max supports xhigh",
"https://ai.google.dev/gemini-api/docs/models": "verified 2026-10-17: gemini-4-argon and gemini-3.8-flash are stable; argon's 1M context is stated but no output ceiling is, so none is recorded",
"https://docs.z.ai/guides/vlm/glm-5.3-flash": "verified 2026-10-17: model code glm-5.3-flash, 1M context, 128K output, thinking.type only supports enabled",
"https://dev.meta.ai/docs/models.md": "verified 2026-10-17: muse-spark-1.3 is recommended for new work, muse-spark-1.2 is the previous version, muse-spark-1.3-contributor has no max effort, muse-wonder-1.0 is a preview; all 1,048,576 context",
"https://dev.meta.ai/docs/pricing-rate-limits": "verified 2026-10-17: Muse Spark 1.3 and 1.2 $1.25 in / $0.15 cached / $4.25 out, contributor $0.10 / $0.002 / $0.20; Muse Wonder 1.0 $4 / $0.20 / $20; no long-context premium",
@@ -4788,8 +4791,7 @@
"https://api.deepinfra.com/models/list": "verified 2026-10-20: deepseek-ai/DeepSeek-V4.1-Flash-1017, deepseek-ai/DeepSeek-V4.1-Flash, deepseek-ai/DeepSeek-V4-Pro-0813 and deepseek-ai/DeepSeek-V4-Flash-0731 are listed and not deprecated, each with max_tokens 1048576 and the tools tag; both V4.1 Flash ids are tagged multimodal and reasoning, V4-Flash-0731 reasoning; V4-Pro-0813 carries can-disable-reasoning beside a non-reasoning tag, while its model page documents low, high and max reasoning effort and the Models.dev deepseek/deepseek-v4-pro-0813 row marks reasoning, so reasoning is recorded; the V4-Pro and V4-Flash previews are still listed; no separate output limit is published, so none is recorded",
"https://modelscope.cn/api/v1/models/deepseek-ai/DeepSeek-V4-Pro-0813": "verified 2026-10-20: the ModelScope card describes DeepSeek-V4-Pro-0813 as the official release of DeepSeek-V4-Pro on the preview model structure, whose card lists a 1M context length; no separate ModelScope API-Inference context limit is published there",
"https://modelscope.cn/api/v1/models/deepseek-ai/DeepSeek-V4.1-Flash": "verified 2026-10-20: the ModelScope card states contexts of up to one million tokens and a recommended 1M context_window; no separate ModelScope API-Inference context limit is published there",
"https://platform.claude.com/docs/en/models/haiku-4-5/overview": "verified 2026-10-22: claude-haiku-4-5 supports manual extended thinking and image input, with 200K context and 64K output; no adaptive-thinking or default-effort support inferred",
"https://qwencloud.com/pricing/token-plan": "verified 2026-11-11: the Supported Models table lists qwen4-max-preview marked New with Text Generation, Reasoning Model and Visual Understanding, so image input is recorded; the page gives no context window, maximum output, tool calling or thinking control, so none is recorded and Codewhale sends no thinking switch"
"https://platform.claude.com/docs/en/models/haiku-4-5/overview": "verified 2026-10-22: claude-haiku-4-5 supports manual extended thinking and image input, with 200K context and 64K output; no adaptive-thinking or default-effort support inferred"
},
"transports": [
{
@@ -5062,17 +5064,6 @@
"default_for_provider": false,
"source": "preserved reviewed exact transport snapshot; see source_receipts"
},
{
"provider": "modelstudio-token-plan",
"id": "qwen4-max-preview",
"endpoint_key": "chat",
"default_for_provider": false,
"source": "Token Plan Supported Models table, verified 2026-11-11; see source_receipts",
"limits": {},
"capabilities": {
"image_input": "supported"
}
},
{
"provider": "opencode-go",
"id": "qwen3.8-flash",
@@ -6891,22 +6882,10 @@
"@MODELSTUDIO_TEXT_MODELS"
],
"modelstudio-coding-plan": [
"qwen3.8-max",
"qwen3.7-plus",
"qwen3.7-max",
"qwen3.6-flash",
"deepseek-v4-pro",
"deepseek-v4-flash-0731",
"glm-5.2"
"@MODELSTUDIO_TEXT_MODELS"
],
"modelstudio-coding-plan-anthropic": [
"qwen3.8-max",
"qwen3.7-plus",
"qwen3.7-max",
"qwen3.6-flash",
"deepseek-v4-pro",
"deepseek-v4-flash-0731",
"glm-5.2"
"@MODELSTUDIO_TEXT_MODELS"
],
"mistral": [
"$DEFAULT_MISTRAL_MODEL",
+119 -63
View File
@@ -9,8 +9,8 @@
"default_rows": "Each provider's `default: true` wire id equals that provider's built-in DEFAULT_*_MODEL so RouteResolver::new() and the descriptor stay in agreement when offline.",
"pending_release_metadata": "GLM-5.3 is live on the Z.ai Coding Plan (docs.z.ai/devpack/overview and docs.z.ai/devpack/latest-model, recorded 2026-08-13) and is the default direct Z.ai model (DEFAULT_ZAI_MODEL); explicit GLM-5.2 selections keep their own id. First-party wire id is GLM-5.3; OpenRouter mirror is z-ai/glm-5.3. Capability/limit/dialect values still inherit from GLM-5.2 until Z.ai publishes distinct 5.3 numbers. Pricing stays absent: Coding Plan publishes credit multipliers, not a USD PAYG row we can stand behind. Z.ai may auto-route GLM-5.2/GLM-5.1 requests to GLM-5.3 on their side; Codewhale still sends the selected picker id. Do not send a [1m] suffix. Scope stays first-party Z.ai plus the OpenRouter mirror; add third-party gateway rows only against that gateway's own published roster.",
"generated_by": "python3 scripts/catalog_models_dev.py seed render from scripts/catalog/models_dev_seed.toml and scripts/catalog/models_dev_seed.lock.json. Do not edit this file by hand; see docs/CATALOG_REFRESH.md.",
"upstream": "https://models.dev/catalog.json fetched 2026-11-10T21:14:00Z sha256 019e248c87ca384d63f16bfd2fde60f8e26b2c6fa1126927a1dac25fe88c9740",
"coverage": "23 providers, 136 provider model rows, 4 canonical model entries."
"upstream": "https://models.dev/catalog.json fetched 2026-11-10T22:14:03Z sha256 2d85d334089340e30ae6d3c6bbbcd8c7591e27b954e8089494348bb59d1bd7af",
"coverage": "23 providers, 137 provider model rows, 4 canonical model entries."
},
"models": {
"deepseek/deepseek-v4-pro-0813": {
@@ -3348,6 +3348,71 @@
"output": 20,
"cache_read": 0.2
}
},
"muse-ember-1.0": {
"id": "muse-ember-1.0",
"canonical_model_id": "meta/muse-ember-1.0",
"name": "Muse Ember",
"description": "Muse Ember is Meta's smallest and most efficient reasoning model, built for the work agents repeat all day: tool calls, coding subtasks, routing, extraction, and long-document parsing. It pairs with Muse Wonder or Muse Spark, which plan while Muse Ember handles the volume.",
"family": "muse",
"release_date": "2026-11-09",
"last_updated": "2026-11-09",
"attachment": true,
"reasoning": true,
"reasoning_options": [
{
"type": "effort",
"values": [
"minimal",
"low",
"medium",
"high",
"xhigh",
"max"
]
}
],
"tool_call": true,
"structured_output": true,
"temperature": true,
"open_weights": false,
"modalities": {
"input": [
"text",
"image",
"video",
"pdf",
"audio"
],
"output": [
"text"
]
},
"limit": {
"context": 1048576,
"output": 524288
},
"cost": {
"input": 0.1,
"output": 0.5,
"cache_read": 0.004,
"tiers": [
{
"input": 0.3,
"output": 1.5,
"cache_read": 0.012,
"tier": {
"type": "context",
"size": 200000
}
}
],
"context_over_200k": {
"input": 0.3,
"output": 1.5,
"cache_read": 0.012
}
}
}
}
},
@@ -5112,9 +5177,9 @@
"output": 384000
},
"cost": {
"input": 0.95526,
"output": 1.91052,
"cache_read": 0.079605
"input": 0.894012,
"output": 1.788024,
"cache_read": 0.074501
}
},
"deepseek/deepseek-v4-flash": {
@@ -8019,7 +8084,7 @@
"reasoning"
],
"reasoning": true,
"source": "official vendor model docs, verified 2026-11-10; see source_receipts",
"source": "https://models.dev/catalog.json anthropic/claude-fable-5-2, retrieved 2026-11-10",
"family": "Anthropic"
},
"claude-opus-5-5": {
@@ -8800,9 +8865,6 @@
"context_window": 1000000,
"max_output": 131072
},
"qwen4-max-preview": {
"source": "Token Plan Supported Models table, https://qwencloud.com/pricing/token-plan, verified 2026-11-11: id qwen4-max-preview (New), capabilities Text Generation, Reasoning Model, Visual Understanding; see source_receipts"
},
"step-3.5-flash": {
"context_window": 256000,
"modalities": [
@@ -9256,16 +9318,14 @@
"family": "Google"
},
"gemini-4-argon": {
"source": "official vendor model docs, verified 2026-11-10; see source_receipts",
"source": "official vendor model docs, verified 2026-10-17; see source_receipts",
"context_window": 1048576,
"max_output": 65536,
"reasoning": true,
"family": "Google"
},
"gemini-4-carbon": {
"source": "official vendor model docs, verified 2026-11-10; see source_receipts",
"source": "https://models.dev/catalog.json google/gemini-4-carbon, retrieved 2026-11-10",
"context_window": 1048576,
"max_output": 65536,
"max_output": 32768,
"reasoning": true,
"family": "Google"
},
@@ -9503,38 +9563,53 @@
"source": "preserved public presentation facts, not route availability"
},
"mistral-large-4": {
"source": "models.dev mistral/mistral-large-4, discovered 2026-11-11; unreviewed",
"source": "models.dev mistral/mistral-large-4, discovered 2026-11-10; unreviewed",
"context_window": 1048576,
"max_output": 262144,
"reasoning": true,
"family": "Mistral"
},
"mistral-large-4-0-8": {
"source": "models.dev mistral/mistral-large-4-0-8, discovered 2026-11-10; unreviewed",
"context_window": 1048576,
"max_output": 262144,
"reasoning": true,
"family": "Mistral"
},
"minimax-m3.1-flash": {
"source": "models.dev minimax/MiniMax-M3.1-Flash, discovered 2026-11-11; unreviewed",
"source": "models.dev minimax/MiniMax-M3.1-Flash, discovered 2026-11-10; unreviewed",
"context_window": 1000000,
"max_output": 524288,
"reasoning": true,
"family": "Minimax"
"family": "MiniMax"
},
"kimi-k3.1-pro": {
"source": "models.dev moonshotai/kimi-k3.1-pro, discovered 2026-11-11; unreviewed",
"source": "models.dev moonshotai/kimi-k3.1-pro, discovered 2026-11-10; unreviewed",
"context_window": 1048576,
"max_output": 1048576,
"reasoning": true,
"family": "Moonshot"
"family": "Moonshot/Kimi"
},
"kimi-k3.1-pro-highspeed": {
"source": "models.dev moonshotai/kimi-k3.1-pro-highspeed, discovered 2026-11-11; unreviewed",
"source": "models.dev moonshotai/kimi-k3.1-pro-highspeed, discovered 2026-11-10; unreviewed",
"context_window": 1048576,
"max_output": 1048576,
"reasoning": true,
"family": "Moonshot"
"family": "Moonshot/Kimi"
},
"gpt-6.1-terra": {
"source": "models.dev openai/gpt-6.1-terra, discovered 2026-11-11; unreviewed",
"source": "models.dev openai/gpt-6.1-terra, discovered 2026-11-10; unreviewed",
"context_window": 1050000,
"max_output": 128000,
"reasoning": true,
"family": "OpenAi"
"family": "OpenAI"
},
"muse-ember-1.0": {
"source": "models.dev meta/muse-ember-1.0, discovered 2026-11-10; unreviewed",
"context_window": 1048576,
"max_output": 524288,
"reasoning": true,
"family": "Meta"
}
},
"official_deepseek_aliases": {
@@ -11792,12 +11867,6 @@
"added_at": "2026-08-02",
"aliases": []
},
{
"id": "qwen4-max-preview",
"label": "Qwen",
"added_at": "2026-11-10",
"aliases": []
},
{
"id": "kimi-for-coding-highspeed",
"label": "Moonshot/Kimi",
@@ -12194,11 +12263,19 @@
{
"id": "mistral-large-4",
"label": "Mistral",
"added_at": "2026-11-05",
"added_at": "2026-10-06",
"aliases": [
"mistral-large-4"
]
},
{
"id": "mistral-large-4-0-8",
"label": "Mistral",
"added_at": "2026-10-06",
"aliases": [
"mistral-large-4-0-8"
]
},
{
"id": "MiniMax-M3.1-Flash",
"label": "MiniMax",
@@ -12230,6 +12307,14 @@
"aliases": [
"gpt-6.1-terra"
]
},
{
"id": "muse-ember-1.0",
"label": "Meta",
"added_at": "2026-11-09",
"aliases": [
"muse-ember-1.0"
]
}
],
"constants": {
@@ -12385,12 +12470,7 @@
"https://developers.openai.com/api/docs/models/gpt-6-sol": "verified 2026-10-17: $2 in / $0.20 cached / $10 out / $2.50 cache write; gpt-6.1-sol $2 / $0.10 / $10 / $2.50 and gpt-6-luna $0.10 / $0.01 / $0.50 per the changelog",
"https://developers.openai.com/api/docs/deprecations": "verified 2026-10-17: gpt-5.3-codex and gpt-5.1 move to gpt-6-sol and gpt-5.4-nano to gpt-6-luna, all shutting down 2027-04-01; the catalog has no lifecycle field, so the rows stay until shutdown",
"https://ai.google.dev/gemini-api/docs/changelog": "verified 2026-10-17: gemini-4-argon GA 2026-10-13, gemini-3.8-flash GA 2026-09-02; gemini-3.7-flash (auto-routed to gemini-3.8-flash) and gemini-3.5-flash (auto-routed to gemini-3.6-flash) deprecated 2026-10-08 and kept only as selector aliases",
"https://ai.google.dev/gemini-api/docs/models": "verified 2026-10-17: gemini-4-argon and gemini-3.8-flash are stable; argon's 1M context is stated; the output ceiling is recorded from its own model page (see the aistudio.google.com receipts, verified 2026-11-10)",
"https://aistudio.google.com/docs/models/gemini-4-carbon": "verified 2026-11-10: model code gemini-4-carbon, 1,048,576 context, 65,536 output by default (up to 1,048,576 with long decode), thinking levels low, medium and high, function calling, structured outputs, implicit caching only; thought signatures are not mentioned",
"https://aistudio.google.com/docs/models/gemini-4-argon": "verified 2026-11-10: model code gemini-4-argon, 1,048,576 context, 65,536 output by default (up to 1,048,576 with long decode), thinking levels low, medium and high",
"https://aistudio.google.com/docs/pricing": "verified 2026-11-10: gemini-4-carbon is $2 in / $10 out / $0.10 cached through 2026-11-30 and $4 / $20 / $0.20 from 2026-12-01; the catalog carries one undated price, so the row shows the current rate",
"https://platform.claude.com/docs/en/models/fable-5-2/overview": "verified 2026-11-10: claude-fable-5-2, 1M context, 128K output, adaptive thinking always on, $8 in / $40 out, text and image input",
"https://platform.claude.com/docs/en/build-with-claude/effort": "verified 2026-11-10: xhigh is its own effort level on Fable 5.2, Mythos 5.2, Fable 5.1, Fable 5, Opus 5.5, Opus 5, Opus 4.8, Opus 4.7, Sonnet 5.5, Sonnet 5 and Haiku 5.5; not every model that supports max supports xhigh",
"https://ai.google.dev/gemini-api/docs/models": "verified 2026-10-17: gemini-4-argon and gemini-3.8-flash are stable; argon's 1M context is stated but no output ceiling is, so none is recorded",
"https://docs.z.ai/guides/vlm/glm-5.3-flash": "verified 2026-10-17: model code glm-5.3-flash, 1M context, 128K output, thinking.type only supports enabled",
"https://dev.meta.ai/docs/models.md": "verified 2026-10-17: muse-spark-1.3 is recommended for new work, muse-spark-1.2 is the previous version, muse-spark-1.3-contributor has no max effort, muse-wonder-1.0 is a preview; all 1,048,576 context",
"https://dev.meta.ai/docs/pricing-rate-limits": "verified 2026-10-17: Muse Spark 1.3 and 1.2 $1.25 in / $0.15 cached / $4.25 out, contributor $0.10 / $0.002 / $0.20; Muse Wonder 1.0 $4 / $0.20 / $20; no long-context premium",
@@ -12400,8 +12480,7 @@
"https://api.deepinfra.com/models/list": "verified 2026-10-20: deepseek-ai/DeepSeek-V4.1-Flash-1017, deepseek-ai/DeepSeek-V4.1-Flash, deepseek-ai/DeepSeek-V4-Pro-0813 and deepseek-ai/DeepSeek-V4-Flash-0731 are listed and not deprecated, each with max_tokens 1048576 and the tools tag; both V4.1 Flash ids are tagged multimodal and reasoning, V4-Flash-0731 reasoning; V4-Pro-0813 carries can-disable-reasoning beside a non-reasoning tag, while its model page documents low, high and max reasoning effort and the Models.dev deepseek/deepseek-v4-pro-0813 row marks reasoning, so reasoning is recorded; the V4-Pro and V4-Flash previews are still listed; no separate output limit is published, so none is recorded",
"https://modelscope.cn/api/v1/models/deepseek-ai/DeepSeek-V4-Pro-0813": "verified 2026-10-20: the ModelScope card describes DeepSeek-V4-Pro-0813 as the official release of DeepSeek-V4-Pro on the preview model structure, whose card lists a 1M context length; no separate ModelScope API-Inference context limit is published there",
"https://modelscope.cn/api/v1/models/deepseek-ai/DeepSeek-V4.1-Flash": "verified 2026-10-20: the ModelScope card states contexts of up to one million tokens and a recommended 1M context_window; no separate ModelScope API-Inference context limit is published there",
"https://platform.claude.com/docs/en/models/haiku-4-5/overview": "verified 2026-10-22: claude-haiku-4-5 supports manual extended thinking and image input, with 200K context and 64K output; no adaptive-thinking or default-effort support inferred",
"https://qwencloud.com/pricing/token-plan": "verified 2026-11-11: the Supported Models table lists qwen4-max-preview marked New with Text Generation, Reasoning Model and Visual Understanding, so image input is recorded; the page gives no context window, maximum output, tool calling or thinking control, so none is recorded and Codewhale sends no thinking switch"
"https://platform.claude.com/docs/en/models/haiku-4-5/overview": "verified 2026-10-22: claude-haiku-4-5 supports manual extended thinking and image input, with 200K context and 64K output; no adaptive-thinking or default-effort support inferred"
},
"transports": [
{
@@ -12674,17 +12753,6 @@
"default_for_provider": false,
"source": "preserved reviewed exact transport snapshot; see source_receipts"
},
{
"provider": "modelstudio-token-plan",
"id": "qwen4-max-preview",
"endpoint_key": "chat",
"default_for_provider": false,
"source": "Token Plan Supported Models table, verified 2026-11-11; see source_receipts",
"limits": {},
"capabilities": {
"image_input": "supported"
}
},
{
"provider": "opencode-go",
"id": "qwen3.8-flash",
@@ -14503,22 +14571,10 @@
"@MODELSTUDIO_TEXT_MODELS"
],
"modelstudio-coding-plan": [
"qwen3.8-max",
"qwen3.7-plus",
"qwen3.7-max",
"qwen3.6-flash",
"deepseek-v4-pro",
"deepseek-v4-flash-0731",
"glm-5.2"
"@MODELSTUDIO_TEXT_MODELS"
],
"modelstudio-coding-plan-anthropic": [
"qwen3.8-max",
"qwen3.7-plus",
"qwen3.7-max",
"qwen3.6-flash",
"deepseek-v4-pro",
"deepseek-v4-flash-0731",
"glm-5.2"
"@MODELSTUDIO_TEXT_MODELS"
],
"mistral": [
"$DEFAULT_MISTRAL_MODEL",
+1 -1
View File
@@ -614,7 +614,7 @@ mod tests {
let reviewed = bundled_reviewed();
reviewed.validate().expect("committed data");
assert_eq!(reviewed.selections.len(), 188);
assert_eq!(reviewed.transports.len(), 123);
assert_eq!(reviewed.transports.len(), 122);
let go = reviewed_transport("opencode-go", "gpt-5.6-luna").unwrap();
assert_eq!(go.endpoint_key, "responses");
assert_eq!(
+1 -8
View File
@@ -605,7 +605,7 @@ pub const SETTINGS_SCHEMA: &[SettingDef] = &[
def(
"show_thinking",
SettingKind::Bool(SHOW_THINKING),
"true",
"false",
ui(
TAB_APPEARANCE,
"display",
@@ -1520,7 +1520,6 @@ pub const SETTINGS_SCHEMA: &[SettingDef] = &[
// Trust posture with a `/set` entry point but no row; surfaced where
// sandboxing acts, not as a settings sentence.
def("sandbox_mode", SettingKind::String, "", None),
def("agents", SettingKind::String, "", None),
// Route memory written by the pickers: per-provider defaults, enabled
// chooser sets, and pinned routes. Structured values no row could edit.
def("provider_models", SettingKind::String, "", None),
@@ -1546,12 +1545,6 @@ pub const SETTINGS_SCHEMA: &[SettingDef] = &[
"false",
None,
),
def(
"account_preferences_notice_shown",
SettingKind::String,
"",
None,
),
// Round 3 work-bar placement migration ran once (`top` → `bottom`).
def(
"work_surface_bottom_migrated",
-28
View File
@@ -33,8 +33,6 @@ pub const LEGACY_CLI_API_KEY_SOURCE_ENV: &str = "DEEPSEEK_API_KEY_SOURCE";
/// [`CLI_API_KEY_SOURCE_ENV`]. Set to `1`/`0` on every delegated run.
pub const TELEMETRY_FLOOR_ENV: &str = "CODEWHALE_TELEMETRY_FLOOR";
pub const TELEMETRY_SOURCE_ENV: &str = "CODEWHALE_TELEMETRY_SOURCE";
/// Whether an environment-level kill switch forces telemetry off here.
///
/// A floor is *not* the same as "telemetry resolved to false": off is the
@@ -94,32 +92,6 @@ impl TelemetrySource {
Self::Default => "default",
}
}
#[must_use]
pub fn from_label(label: &str) -> Option<Self> {
match label {
"cli" => Some(Self::Cli),
"env" => Some(Self::Env),
"config" => Some(Self::Config),
"default" => Some(Self::Default),
_ => None,
}
}
}
#[must_use]
pub fn dispatched_telemetry_source() -> Option<TelemetrySource> {
parse_bool(&std::env::var(TELEMETRY_FLOOR_ENV).ok()?).ok()?;
TelemetrySource::from_label(&std::env::var(TELEMETRY_SOURCE_ENV).ok()?)
}
#[must_use]
pub fn dispatched_telemetry_consent(file_telemetry: Option<bool>) -> (bool, TelemetrySource) {
let (on, source) = resolved_telemetry_consent(file_telemetry);
match (source, dispatched_telemetry_source()) {
(TelemetrySource::Env, Some(declared)) => (on, declared),
_ => (on, source),
}
}
/// Read the telemetry environment override, reporting an unreadable value
-66
View File
@@ -8763,7 +8763,6 @@ struct TelemetryEnvGuard {
codewhale: Option<OsString>,
deepseek: Option<OsString>,
floor: Option<OsString>,
source: Option<OsString>,
codewhale_endpoint: Option<OsString>,
deepseek_endpoint: Option<OsString>,
_lock: std::sync::MutexGuard<'static, ()>,
@@ -8776,7 +8775,6 @@ impl TelemetryEnvGuard {
codewhale: env::var_os("CODEWHALE_TELEMETRY"),
deepseek: env::var_os("DEEPSEEK_TELEMETRY"),
floor: env::var_os(TELEMETRY_FLOOR_ENV),
source: env::var_os(TELEMETRY_SOURCE_ENV),
// The endpoint variables are cleared too. Resolution now has a
// shipped default, so an ambient endpoint in the developer's or
// CI's environment is the difference between pinning the default
@@ -8790,7 +8788,6 @@ impl TelemetryEnvGuard {
env::remove_var("CODEWHALE_TELEMETRY");
env::remove_var("DEEPSEEK_TELEMETRY");
env::remove_var(TELEMETRY_FLOOR_ENV);
env::remove_var(TELEMETRY_SOURCE_ENV);
env::remove_var("CODEWHALE_TELEMETRY_ENDPOINT");
env::remove_var("DEEPSEEK_TELEMETRY_ENDPOINT");
}
@@ -8811,13 +8808,6 @@ impl TelemetryEnvGuard {
}
}
fn set_source(&self, value: &str) {
// Safety: test-only environment mutation guarded by the module mutex.
unsafe {
env::set_var(TELEMETRY_SOURCE_ENV, value);
}
}
fn set_floor(&self, value: &str) {
// Safety: test-only environment mutation guarded by the module mutex.
unsafe {
@@ -8831,7 +8821,6 @@ impl TelemetryEnvGuard {
env::remove_var("CODEWHALE_TELEMETRY");
env::remove_var("DEEPSEEK_TELEMETRY");
env::remove_var(TELEMETRY_FLOOR_ENV);
env::remove_var(TELEMETRY_SOURCE_ENV);
}
}
}
@@ -8852,10 +8841,6 @@ impl Drop for TelemetryEnvGuard {
Some(value) => env::set_var(TELEMETRY_FLOOR_ENV, value),
None => env::remove_var(TELEMETRY_FLOOR_ENV),
}
match self.source.take() {
Some(value) => env::set_var(TELEMETRY_SOURCE_ENV, value),
None => env::remove_var(TELEMETRY_SOURCE_ENV),
}
match self.codewhale_endpoint.take() {
Some(value) => env::set_var("CODEWHALE_TELEMETRY_ENDPOINT", value),
None => env::remove_var("CODEWHALE_TELEMETRY_ENDPOINT"),
@@ -9010,57 +8995,6 @@ fn telemetry_consent_names_its_source() {
assert_eq!(source, TelemetrySource::Env);
}
#[test]
fn dispatched_consent_names_the_dispatchers_source_not_its_hand_off() {
let guard = TelemetryEnvGuard::take();
guard.set("false");
guard.set_floor("0");
guard.set_source("config");
let (on, source) = dispatched_telemetry_consent(Some(false));
assert!(!on);
assert_eq!(source, TelemetrySource::Config);
guard.set("false");
guard.set_floor("1");
guard.set_source("env");
let (on, source) = dispatched_telemetry_consent(Some(false));
assert!(!on);
assert_eq!(source, TelemetrySource::Env);
guard.set("true");
guard.set_floor("0");
guard.set_source("default");
let (on, source) = dispatched_telemetry_consent(None);
assert!(on);
assert_eq!(source, TelemetrySource::Default);
guard.set("false");
guard.set_floor("1");
guard.set_source("cli");
let (on, source) = dispatched_telemetry_consent(None);
assert!(!on);
assert_eq!(source, TelemetrySource::Cli);
guard.clear();
guard.set("0");
guard.set_source("config");
let (on, source) = dispatched_telemetry_consent(Some(false));
assert!(!on);
assert_eq!(
source,
TelemetrySource::Env,
"a source with no dispatcher floor statement is not believed"
);
guard.clear();
guard.set("0");
guard.set_floor("1");
guard.set_source("nonsense");
let (_, source) = dispatched_telemetry_consent(None);
assert_eq!(source, TelemetrySource::Env);
}
#[test]
fn resolved_runtime_options_mints_a_route_candidate() {
let resolved = ConfigToml::default().resolve_runtime_options(&CliRuntimeOverrides::default());
-2
View File
@@ -73,7 +73,6 @@ path = "src/lib.rs"
doctest = false
[dependencies]
agent-client-protocol.workspace = true
http = "1.5"
codewhale-app-server-protocol = { path = "../app-server-protocol", version = "0.10.3" }
codewhale-sanitize = { path = "../sanitize", version = "0.10.3" }
@@ -180,7 +179,6 @@ wiremock = { version = "0.6", optional = true }
codewhale-build-support = { path = "../build-support", version = "0.10.3" }
[dev-dependencies]
agent-client-protocol-schema.workspace = true
tokio = { workspace = true, features = ["test-util"] }
codewhale-app-server-protocol = { path = "../app-server-protocol", version = "0.10.3", features = ["schema"] }
codewhale-skills = { path = "../skills", version = "0.10.3", features = ["test-support"] }
+44 -355
View File
@@ -727,7 +727,7 @@ var init_lib2 = __esm({
} else throw new TypeError("Invalid effect");
}, runner.getOuterStack);
}
effect(execute, label2 = "anonymous") {
effect(execute, label = "anonymous") {
this.assertActive();
if (this.state === 5) throw new CordisError("INACTIVE_EFFECT");
const disposables = [];
@@ -745,7 +745,7 @@ var init_lib2 = __esm({
return disposalTask = task2;
};
const meta = {
label: label2,
label,
children: []
};
const runner = {
@@ -1167,7 +1167,7 @@ var init_lib2 = __esm({
};
return dispatch();
}
register(label2, name, callback, options) {
register(label, name, callback, options) {
const method = options.prepend ? "unshift" : "push";
return this.ctx.fiber.effect(() => {
(this._hooks[name] ??= [])[method]({
@@ -1176,7 +1176,7 @@ var init_lib2 = __esm({
...options
});
return () => this.unregister(name, callback);
}, label2);
}, label);
}
unregister(name, callback) {
const hooks = this._hooks[name];
@@ -1205,8 +1205,8 @@ var init_lib2 = __esm({
listener = this.ctx.reflect.bind(listener);
const result = this.bail(this.ctx, "internal/listener", name, listener, options);
if (result) return result;
const label2 = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
return this.register(label2, name, listener, options);
const label = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
return this.register(label, name, listener, options);
}
/**
* Register an event listener that disposes itself after the first call.
@@ -1951,9 +1951,9 @@ var init_lib2 = __esm({
* @param label — scope label to join; defaults to a fresh unique symbol.
* @returns a child context whose `name` service resolves in the new scope.
*/
isolate(name, label2) {
isolate(name, label) {
const shadow = Object.create(this[symbols.isolate]);
shadow[name] = label2 ?? Symbol(name);
shadow[name] = label ?? Symbol(name);
return this.extend({ [symbols.isolate]: shadow });
}
intercept(name, config) {
@@ -2650,14 +2650,14 @@ function isolate(ctx) {
const delims = /* @__PURE__ */ Object.create(null);
function access2(entry, name, create = false) {
let realm;
const label2 = entry.options.isolate?.[name];
if (!label2) return;
if (label2 === true) {
const label = entry.options.isolate?.[name];
if (!label) return;
if (label === true) {
realm = entry.realm ??= new LocalRealm(entry);
} else if (create) {
realm = realms[label2] ??= new GlobalRealm(label2);
realm = realms[label] ??= new GlobalRealm(label);
} else {
realm = realms[label2];
realm = realms[label];
}
return realm?.access(name, create);
}
@@ -2714,10 +2714,10 @@ function isolate(ctx) {
}
});
ctx.on("loader/partial-dispose", (entry, legacy, active) => {
for (const [name, label2] of Object.entries(legacy.isolate ?? {})) {
if (label2 === true) continue;
if (active && entry.options.isolate?.[name] === label2) continue;
const realm = realms[label2];
for (const [name, label] of Object.entries(legacy.isolate ?? {})) {
if (label === true) continue;
if (active && entry.options.isolate?.[name] === label) continue;
const realm = realms[label];
if (!realm) continue;
for (const entry2 of ctx.loader.entries()) {
if (entry2.options.isolate?.[name] === realm.label) return;
@@ -2761,9 +2761,9 @@ var init_isolate = __esm({
}
};
GlobalRealm = class extends Realm {
constructor(label2) {
constructor(label) {
super();
this.label = label2;
this.label = label;
}
label;
get suffix() {
@@ -5452,14 +5452,14 @@ function requireDumper() {
let hasFoldableLine = false;
const shouldTrackWidth = lineWidth !== -1;
let previousLineBreak = -1;
let plain3 = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
let plain2 = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
if (singleLineOnly || forceQuotes) {
for (i2 = 0; i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
char = codePointAt(string, i2);
if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain3 = plain3 && isPlainSafe(char, prevChar, inblock);
plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
prevChar = char;
}
} else {
@@ -5475,13 +5475,13 @@ function requireDumper() {
} else if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain3 = plain3 && isPlainSafe(char, prevChar, inblock);
plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
prevChar = char;
}
hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
}
if (!hasLineBreak && !hasFoldableLine) {
if (plain3 && !forceQuotes && !testAmbiguousType(string)) {
if (plain2 && !forceQuotes && !testAmbiguousType(string)) {
return STYLE_PLAIN;
}
return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
@@ -7370,9 +7370,9 @@ var init_acorn = __esm({
keywordRelationalOperator = /^in(stanceof)?$/;
nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
TokenType = function TokenType2(label2, conf) {
TokenType = function TokenType2(label, conf) {
if (conf === void 0) conf = {};
this.label = label2;
this.label = label;
this.keyword = conf.keyword;
this.beforeExpr = !!conf.beforeExpr;
this.startsExpr = !!conf.startsExpr;
@@ -8421,8 +8421,8 @@ var init_acorn = __esm({
};
pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
for (var i$1 = 0, list2 = this.labels; i$1 < list2.length; i$1 += 1) {
var label2 = list2[i$1];
if (label2.name === maybeName) {
var label = list2[i$1];
if (label.name === maybeName) {
this.raise(expr.start, "Label '" + maybeName + "' is already declared");
}
}
@@ -12795,8 +12795,7 @@ var init_compatibility = __esm({
"prompt",
"avatars",
"mcp",
"shellHooks",
"remote"
"shellHooks"
]
},
refused_services: [
@@ -13554,23 +13553,11 @@ var init_composition = __esm({
});
// src/protocol.generated.ts
var MAGIC_ASCII, ErrorCode;
var MAGIC_ASCII;
var init_protocol_generated = __esm({
"src/protocol.generated.ts"() {
"use strict";
MAGIC_ASCII = "CWX1";
ErrorCode = {
ParseError: -32700,
InvalidRequest: -32600,
MethodNotFound: -32601,
InvalidParams: -32602,
Internal: -32603,
ExecutionFailed: -32e3,
NotAvailable: -32001,
Refused: -32002,
Denied: -32003,
Cancelled: -32800
};
}
});
@@ -13586,88 +13573,10 @@ var init_protocol = __esm({
});
// src/rpc.ts
var RpcError;
var init_rpc = __esm({
"src/rpc.ts"() {
"use strict";
init_protocol();
RpcError = class extends Error {
constructor(code, message, data2) {
super(message);
this.code = code;
this.data = data2;
this.name = "RpcError";
}
code;
data;
toWire() {
return this.data === void 0 ? { code: this.code, message: this.message } : { code: this.code, message: this.message, data: this.data };
}
};
}
});
// src/dsh/session-prompt.ts
function checkpointCall(host, ctx, session) {
const invocation = host.liveInvocation(ctx);
const ticket = invocation?.ticket;
return invocation !== void 0 && typeof ticket === "string" && ticket.length > 0 && session !== void 0 && session === invocation.session ? invocation : void 0;
}
var CHILD_ONLY, sessionsAdapter, systemPromptAdapter;
var init_session_prompt = __esm({
"src/dsh/session-prompt.ts"() {
"use strict";
init_lib2();
init_protocol();
init_rpc();
CHILD_ONLY = "system prompt sections are only available on a child agent's agent/created context";
sessionsAdapter = {
service: "sessions",
define(host) {
class SessionsService extends Service {
constructor(ctx) {
super(ctx, "sessions");
}
async flush(session) {
const ctx = this.ctx;
const call = checkpointCall(host, ctx, session);
if (call === void 0) throw new RpcError(ErrorCode.NotAvailable, "sessions.flush requires this live tool invocation’s session");
const owner = call.owner;
const live = () => checkpointCall(host, ctx, session) === call && !call.signal.aborted;
const run = async () => {
if (!live()) throw new RpcError(ErrorCode.NotAvailable, "session checkpoint invocation ended");
const result2 = await host.rpc.request("session/checkpoint", { owner: owner.ref, ticket: call.ticket }, call.signal);
if (!live()) throw new RpcError(ErrorCode.NotAvailable, "session checkpoint invocation ended");
if (typeof result2 !== "boolean") throw new RpcError(ErrorCode.Internal, "invalid session checkpoint receipt");
return result2;
};
const result = call.pending.then(run);
call.pending = result.then(() => void 0, () => void 0);
return result;
}
}
Object.freeze(SessionsService.prototype);
return SessionsService;
}
};
systemPromptAdapter = {
service: "systemPrompt",
define() {
class SystemPromptService extends Service {
constructor(ctx) {
super(ctx, "systemPrompt");
}
section() {
throw new RpcError(ErrorCode.NotAvailable, CHILD_ONLY);
}
getSectionOrder() {
throw new RpcError(ErrorCode.NotAvailable, CHILD_ONLY);
}
}
Object.freeze(SystemPromptService.prototype);
return SystemPromptService;
}
};
}
});
@@ -14299,12 +14208,11 @@ var init_lib3 = __esm({
});
// src/dsh/dsh-message-compat.js
var PERSONA_PREFIX_SECTION, HarnessError, UserQuestionError;
var HarnessError, UserQuestionError;
var init_dsh_message_compat = __esm({
"src/dsh/dsh-message-compat.js"() {
"use strict";
init_lib3();
PERSONA_PREFIX_SECTION = "deployment:persona-prefix";
HarnessError = class extends Error {
code;
constructor(message, code, options) {
@@ -14324,223 +14232,6 @@ var init_dsh_message_compat = __esm({
}
});
// src/dsh/agents.ts
function plain(value, allowed, what) {
if (value === null || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new RpcError(ErrorCode.InvalidParams, `expected a plain ${what} object`);
const result = /* @__PURE__ */ Object.create(null);
for (const key of Reflect.ownKeys(value)) {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (typeof key !== "string" || !allowed.includes(key) || !("value" in descriptor)) throw new RpcError(ErrorCode.NotAvailable, `unsupported ${what} property ${String(key)}`);
if (descriptor.value !== void 0) result[key] = descriptor.value;
}
return result;
}
function defineSubagents(host) {
class SubagentsShim extends Service {
constructor(ctx) {
super(ctx, "subagents");
}
getProvider(name) {
return name === "spawn" ? SPAWN_PROVIDER : void 0;
}
async startActivation(request) {
const owner = host.ownerOf(this.ctx);
const input = plain(request, ["provider", "label", "childId", "request", "signal", "delivery"], "activation");
if (input.provider !== "spawn") throw new RpcError(ErrorCode.NotAvailable, "only the spawn provider is available");
const spawn = plain(input.request, ["parent", "prompt", "agentOptions"], "spawn request");
const options = spawn.agentOptions === void 0 ? {} : plain(spawn.agentOptions, ["model"], "agentOptions");
if (options.model !== void 0 && typeof options.model !== "string") throw new RpcError(ErrorCode.InvalidParams, "agentOptions.model must be a string");
const delivery = input.delivery === void 0 ? "parent" : input.delivery;
if (delivery !== "caller" && delivery !== "parent") throw new RpcError(ErrorCode.InvalidParams, "delivery must be caller or parent");
const childId = input.childId;
if (typeof childId !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(childId)) throw new RpcError(ErrorCode.InvalidParams, "childId must be 1-128 letters, digits, or _.:-");
if (!Array.isArray(spawn.prompt) || spawn.prompt.length === 0) throw new RpcError(ErrorCode.InvalidParams, "prompt must be a non-empty content array");
const prompt = spawn.prompt.map((block) => {
const item = plain(block, ["type", "text"], "prompt block");
if (item.type !== "text" || typeof item.text !== "string") throw new RpcError(ErrorCode.NotAvailable, "only text prompt blocks are supported");
return item.text;
}).join("");
if (input.signal !== void 0 && !(input.signal instanceof AbortSignal)) throw new RpcError(ErrorCode.InvalidParams, "signal must be an AbortSignal");
const invocation = host.liveInvocation(this.ctx);
if (!invocation || invocation.agent === void 0 || spawn.parent !== invocation.agent) {
throw new RpcError(ErrorCode.NotAvailable, "startActivation requires the exact live calling agent as parent");
}
if (invocation.owner !== owner) throw new RpcError(ErrorCode.NotAvailable, "subagents service owner is no longer current");
if (invocation.delegated || invocation.subagentTicket === void 0) throw new RpcError(ErrorCode.NotAvailable, "child agents are only available to a root tool invocation");
const signal = input.signal === void 0 ? invocation.signal : AbortSignal.any([invocation.signal, input.signal]);
signal.throwIfAborted();
let persona;
const denied = /* @__PURE__ */ new Set();
let open = true;
const sealed = () => {
if (!open) throw new RpcError(ErrorCode.NotAvailable, "the child creation window has closed");
};
const child = Object.freeze({
id: childId,
ctx: Object.freeze({
systemPrompt: Object.freeze({
getSectionOrder(name) {
sealed();
if (name !== "DEPLOYMENT_PERSONA_PREFIX") throw new RpcError(ErrorCode.NotAvailable, "only the deployment persona slot is available");
return PERSONA_ORDER;
},
section(section) {
sealed();
const value = plain(section, ["name", "order", "text"], "system prompt section");
if (value.name !== PERSONA_PREFIX_SECTION || value.order !== PERSONA_ORDER || typeof value.text !== "string") {
throw new RpcError(ErrorCode.NotAvailable, "only the child deployment persona section is supported");
}
if (persona !== void 0) throw new RpcError(ErrorCode.InvalidParams, "the child persona is already set");
if (Buffer.byteLength(value.text) > 32 * 1024) throw new RpcError(ErrorCode.InvalidParams, "child persona exceeds 32768 bytes");
persona = value.text;
return () => void 0;
}
}),
tools: Object.freeze({
restrict(filter) {
sealed();
const value = plain(filter, ["deny"], "tool filter");
if (!Array.isArray(value.deny) || value.deny.some((name) => typeof name !== "string" || name === "")) throw new RpcError(ErrorCode.InvalidParams, "deny must be a list of tool names");
for (const name of value.deny) denied.add(name);
return () => void 0;
}
})
})
});
const listeners = (this.ctx.root?.events?._hooks?.["agent/created"] ?? []).filter((hook) => !hook.global && hook.ctx !== void 0 && host.ownerOf(hook.ctx) === owner).map((hook) => hook.callback);
try {
await Promise.all(listeners.map(async (callback) => callback({ agent: child })));
} finally {
open = false;
}
signal.throwIfAborted();
const call = invocation;
const rpc = (method, params, abort) => host.rpc.request(method, { owner: call.owner.ref, ticket: call.subagentTicket, child_id: childId, ...params }, abort);
const started = await rpc("subagent/start", {
prompt,
...options.model === void 0 ? {} : { model: options.model },
...persona === void 0 ? {} : { persona },
denied_tools: [...denied],
delivery
}, signal);
if (started === null || typeof started !== "object" || started.child_id !== childId || typeof started.message_id !== "string") {
throw new RpcError(ErrorCode.Internal, "invalid child activation receipt");
}
let result;
let disposed;
return Object.freeze({
childId,
messageId: started.message_id,
get result() {
result ??= rpc("subagent/result", {}, call.signal).then((value) => {
if (value === null || typeof value !== "object" || typeof value.stop_reason !== "string" || !Array.isArray(value.output)) {
throw new RpcError(ErrorCode.Internal, "invalid child result receipt");
}
return Object.freeze({
stopReason: value.stop_reason,
output: Object.freeze(value.output.map((block) => Object.freeze({ type: "text", text: String(block.text) }))),
...value.omitted_blocks > 0 ? { diagnostic: `${value.omitted_blocks} non-text output block(s) are not supported` } : {}
});
});
return result;
},
dispose() {
disposed ??= rpc("subagent/dispose", {}, call.signal).then(() => void 0);
return disposed;
}
});
}
}
Object.freeze(SubagentsShim.prototype);
return SubagentsShim;
}
function defineAgents() {
class AgentsShim extends Service {
constructor(ctx) {
super(ctx, "agents");
}
}
Object.freeze(AgentsShim.prototype);
return AgentsShim;
}
var SPAWN_PROVIDER, PERSONA_ORDER, DSH_AGENT_ADAPTERS;
var init_agents = __esm({
"src/dsh/agents.ts"() {
"use strict";
init_lib2();
init_protocol();
init_rpc();
init_dsh_message_compat();
SPAWN_PROVIDER = Object.freeze({
name: "spawn",
inheritsParentContext: false,
capabilities: Object.freeze({ persona: true, toolFilter: true, agentOptions: true })
});
PERSONA_ORDER = 0;
DSH_AGENT_ADAPTERS = Object.freeze([
{ service: "subagents", define: defineSubagents },
{ service: "agents", define: defineAgents }
]);
}
});
// src/dsh/remote.ts
function label(value) {
if (value === void 0) return void 0;
if (typeof value !== "string") throw new RpcError(ErrorCode.InvalidParams, "remote.pair label must be a string");
return value;
}
function grant(value) {
if (typeof value !== "string" || value.length === 0 || value.length > 128) throw new RpcError(ErrorCode.InvalidParams, "remote.revoke needs the grant id remote.pair returned");
return value;
}
var remoteAdapter;
var init_remote = __esm({
"src/dsh/remote.ts"() {
"use strict";
init_lib2();
init_protocol();
init_rpc();
remoteAdapter = {
service: "remote",
define(host) {
class RemoteService extends Service {
constructor(ctx) {
super(ctx, "remote");
}
status() {
return host.broker(this.ctx, "remote", "status", {});
}
pair(options) {
const value = label(options?.label);
return host.broker(this.ctx, "remote", "pair", value === void 0 ? {} : { label: value });
}
clients() {
return host.broker(this.ctx, "remote", "clients", {});
}
revoke(id) {
return host.broker(this.ctx, "remote", "revoke", { grant: grant(id) });
}
}
Object.freeze(RemoteService.prototype);
return RemoteService;
}
};
}
});
// src/dsh/adapters.ts
var DSH_ADAPTERS;
var init_adapters = __esm({
"src/dsh/adapters.ts"() {
"use strict";
init_session_prompt();
init_agents();
init_remote();
DSH_ADAPTERS = [sessionsAdapter, systemPromptAdapter, ...DSH_AGENT_ADAPTERS, remoteAdapter];
}
});
// src/dsh/dsh-tools-compat.js
var init_dsh_tools_compat = __esm({
"src/dsh/dsh-tools-compat.js"() {
@@ -14622,12 +14313,11 @@ var init_commands = __esm({
// src/root.ts
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
var REFUSED_SERVICES, PROVIDED_SERVICES, CORDIS_SERVICES, ownerStorage;
var REFUSED_SERVICES, PROVIDED_SERVICES, ownerStorage;
var init_root = __esm({
"src/root.ts"() {
"use strict";
init_composition();
init_adapters();
init_protocol();
init_rpc();
init_dsh_message_compat();
@@ -14649,7 +14339,6 @@ var init_root = __esm({
init_commands();
REFUSED_SERVICES = new Set(compatibility_default.refused_services);
PROVIDED_SERVICES = new Set(Object.values(compatibility_default.provided_services).flat());
CORDIS_SERVICES = new Set(compatibility_default.provided_services.cordis);
ownerStorage = new AsyncLocalStorage2();
}
});
@@ -14766,16 +14455,16 @@ function entryListProblem(rows, at2 = "") {
return at2 === "" ? "the composition must be a top-level list of plugin rows" : `group ${at2} must hold a list of plugin rows`;
}
for (const [index, row] of rows.entries()) {
const label2 = at2 === "" ? `row ${String(index + 1)}` : `${at2} row ${String(index + 1)}`;
const label = at2 === "" ? `row ${String(index + 1)}` : `${at2} row ${String(index + 1)}`;
if (typeof row !== "object" || row === null || Array.isArray(row)) {
return `${label2} is not a plugin row (expected a map with a "name")`;
return `${label} is not a plugin row (expected a map with a "name")`;
}
const { name, group, config } = row;
if (typeof name !== "string" || name === "") {
return `${label2} names no plugin (a "name" string is required)`;
return `${label} names no plugin (a "name" string is required)`;
}
if (group === true) {
const nested = entryListProblem(config, label2);
const nested = entryListProblem(config, label);
if (nested !== void 0) return nested;
}
}
@@ -14798,8 +14487,8 @@ async function unresolvableRows(rows, presetBase, harnessBase, resolves, io, at2
continue;
}
if (await rowResolves(classifyRowSpecifier(row.name), presetBase, harnessBase, resolves, io)) continue;
const label2 = typeof row.id === "string" && row.id !== "" ? `row "${row.id}"` : positional;
found.push({ label: label2, name: row.name });
const label = typeof row.id === "string" && row.id !== "" ? `row "${row.id}"` : positional;
found.push({ label, name: row.name });
}
return found;
}
@@ -14970,7 +14659,7 @@ var init_composition_inventory = __esm({
import { createHash as createHash3 } from "node:crypto";
import { resolve as resolve5, relative as relative3, dirname as dirname4, sep as sep3 } from "node:path";
import { fileURLToPath as fileURLToPath5, pathToFileURL as pathToFileURL5 } from "node:url";
function plain2(path) {
function plain(path) {
return typeof path === "string" && path.length > 0 && path.length <= 4096 && !/[\\:\u0000-\u001f\u007f]/u.test(path) && !path.startsWith("/") && path.split("/").every((p) => p !== "" && p !== "." && p !== "..");
}
function fail(message) {
@@ -15010,7 +14699,7 @@ function containedPackageModule(name, documents, files) {
entry = value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).some((k) => k.startsWith(".")) ? target(value[subpath]) : subpath === "." ? target(value) : void 0;
} else if (subpath === ".") entry = typeof data2.main === "string" ? data2.main : "./index.js";
else entry = subpath;
if (typeof entry !== "string" || !entry.startsWith("./") || !plain2(entry.slice(2))) return;
if (typeof entry !== "string" || !entry.startsWith("./") || !plain(entry.slice(2))) return;
const path = `${packageRoot}/${entry.slice(2)}`;
if (!/\.(mjs|js|mts)$/.test(path) || !SHA.test(files[path] ?? "")) return;
return { name, path, sha256: files[path] };
@@ -15023,20 +14712,20 @@ async function reviewAgentPresets(input) {
const baseUrl = pathToFileURL5(`${base}${sep3}`).href;
function key(path) {
const inside = relative3(base, path).split(sep3).join("/");
if (!plain2(inside)) fail("path escapes the admitted source root");
if (!plain(inside)) fail("path escapes the admitted source root");
return inside;
}
const documents = /* @__PURE__ */ new Map();
let bytes = 0;
for (const doc of input.documents) {
if (!plain2(doc.path) || !SHA.test(doc.sha256) || files[doc.path] !== doc.sha256 || hash(doc.source) !== doc.sha256 || documents.has(doc.path)) fail("document changed or is outside the source receipt");
if (!plain(doc.path) || !SHA.test(doc.sha256) || files[doc.path] !== doc.sha256 || hash(doc.source) !== doc.sha256 || documents.has(doc.path)) fail("document changed or is outside the source receipt");
bytes += Buffer.byteLength(doc.source);
if (Buffer.byteLength(doc.source) > 1024 * 1024 || bytes > 4 * 1024 * 1024) fail("documents exceed their bound");
documents.set(doc.path, doc.source);
}
const directories = new Set(input.directories);
for (const path of directories) if (!plain2(path)) fail("invalid source directory");
for (const path of Object.keys(files)) if (!plain2(path) || !SHA.test(files[path])) fail("invalid source file receipt");
for (const path of directories) if (!plain(path)) fail("invalid source directory");
for (const path of Object.keys(files)) if (!plain(path) || !SHA.test(files[path])) fail("invalid source file receipt");
const invalid = /* @__PURE__ */ new Set();
const parsed = /* @__PURE__ */ new Map();
const io = {
@@ -15101,7 +14790,7 @@ async function reviewAgentPresets(input) {
}
if (config.roots !== void 0 && !Array.isArray(config.roots)) fail("roots must be a literal list");
for (const root of config.roots ?? []) {
if (!root || Object.keys(root).some((k) => !["path", "trust"].includes(k)) || !plain2(root.path) || !["system", "user"].includes(root.trust)) fail("configured roots must stay inside the admitted package");
if (!root || Object.keys(root).some((k) => !["path", "trust"].includes(k)) || !plain(root.path) || !["system", "user"].includes(root.trust)) fail("configured roots must stay inside the admitted package");
if (!directories.has(root.path)) fail("configured preset root was not admitted");
roots.push({ path: resolve5(base, root.path), trust: root.trust });
}
+231 -374
View File
@@ -921,7 +921,7 @@ var init_lib2 = __esm({
} else throw new TypeError("Invalid effect");
}, runner.getOuterStack);
}
effect(execute, label2 = "anonymous") {
effect(execute, label = "anonymous") {
this.assertActive();
if (this.state === 5) throw new CordisError("INACTIVE_EFFECT");
const disposables = [];
@@ -939,7 +939,7 @@ var init_lib2 = __esm({
return disposalTask = task2;
};
const meta = {
label: label2,
label,
children: []
};
const runner = {
@@ -1361,7 +1361,7 @@ var init_lib2 = __esm({
};
return dispatch();
}
register(label2, name, callback, options) {
register(label, name, callback, options) {
const method = options.prepend ? "unshift" : "push";
return this.ctx.fiber.effect(() => {
(this._hooks[name] ??= [])[method]({
@@ -1370,7 +1370,7 @@ var init_lib2 = __esm({
...options
});
return () => this.unregister(name, callback);
}, label2);
}, label);
}
unregister(name, callback) {
const hooks = this._hooks[name];
@@ -1399,8 +1399,8 @@ var init_lib2 = __esm({
listener = this.ctx.reflect.bind(listener);
const result = this.bail(this.ctx, "internal/listener", name, listener, options);
if (result) return result;
const label2 = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
return this.register(label2, name, listener, options);
const label = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
return this.register(label, name, listener, options);
}
/**
* Register an event listener that disposes itself after the first call.
@@ -2145,9 +2145,9 @@ var init_lib2 = __esm({
* @param label — scope label to join; defaults to a fresh unique symbol.
* @returns a child context whose `name` service resolves in the new scope.
*/
isolate(name, label2) {
isolate(name, label) {
const shadow = Object.create(this[symbols.isolate]);
shadow[name] = label2 ?? Symbol(name);
shadow[name] = label ?? Symbol(name);
return this.extend({ [symbols.isolate]: shadow });
}
intercept(name, config) {
@@ -4543,14 +4543,14 @@ function isolate(ctx) {
const delims = /* @__PURE__ */ Object.create(null);
function access2(entry, name, create = false) {
let realm;
const label2 = entry.options.isolate?.[name];
if (!label2) return;
if (label2 === true) {
const label = entry.options.isolate?.[name];
if (!label) return;
if (label === true) {
realm = entry.realm ??= new LocalRealm(entry);
} else if (create) {
realm = realms[label2] ??= new GlobalRealm(label2);
realm = realms[label] ??= new GlobalRealm(label);
} else {
realm = realms[label2];
realm = realms[label];
}
return realm?.access(name, create);
}
@@ -4607,10 +4607,10 @@ function isolate(ctx) {
}
});
ctx.on("loader/partial-dispose", (entry, legacy, active) => {
for (const [name, label2] of Object.entries(legacy.isolate ?? {})) {
if (label2 === true) continue;
if (active && entry.options.isolate?.[name] === label2) continue;
const realm = realms[label2];
for (const [name, label] of Object.entries(legacy.isolate ?? {})) {
if (label === true) continue;
if (active && entry.options.isolate?.[name] === label) continue;
const realm = realms[label];
if (!realm) continue;
for (const entry2 of ctx.loader.entries()) {
if (entry2.options.isolate?.[name] === realm.label) return;
@@ -4655,9 +4655,9 @@ var init_isolate = __esm({
}
};
GlobalRealm = class extends Realm {
constructor(label2) {
constructor(label) {
super();
this.label = label2;
this.label = label;
}
label;
get suffix() {
@@ -7371,14 +7371,14 @@ function requireDumper() {
let hasFoldableLine = false;
const shouldTrackWidth = lineWidth !== -1;
let previousLineBreak = -1;
let plain2 = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
let plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
if (singleLineOnly || forceQuotes) {
for (i2 = 0; i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
char = codePointAt(string, i2);
if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
plain = plain && isPlainSafe(char, prevChar, inblock);
prevChar = char;
}
} else {
@@ -7394,13 +7394,13 @@ function requireDumper() {
} else if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
plain = plain && isPlainSafe(char, prevChar, inblock);
prevChar = char;
}
hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
}
if (!hasLineBreak && !hasFoldableLine) {
if (plain2 && !forceQuotes && !testAmbiguousType(string)) {
if (plain && !forceQuotes && !testAmbiguousType(string)) {
return STYLE_PLAIN;
}
return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
@@ -9683,9 +9683,9 @@ var init_acorn = __esm({
keywordRelationalOperator = /^in(stanceof)?$/;
nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
TokenType = function TokenType2(label2, conf) {
TokenType = function TokenType2(label, conf) {
if (conf === void 0) conf = {};
this.label = label2;
this.label = label;
this.keyword = conf.keyword;
this.beforeExpr = !!conf.beforeExpr;
this.startsExpr = !!conf.startsExpr;
@@ -10734,8 +10734,8 @@ var init_acorn = __esm({
};
pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
for (var i$1 = 0, list2 = this.labels; i$1 < list2.length; i$1 += 1) {
var label2 = list2[i$1];
if (label2.name === maybeName) {
var label = list2[i$1];
if (label.name === maybeName) {
this.raise(expr.start, "Label '" + maybeName + "' is already declared");
}
}
@@ -15147,8 +15147,7 @@ var init_compatibility = __esm({
"prompt",
"avatars",
"mcp",
"shellHooks",
"remote"
"shellHooks"
]
},
refused_services: [
@@ -15900,7 +15899,6 @@ var init_protocol_generated = __esm({
{ name: "subagent/start", direction: "host_to_core", request: true, params: "SubagentStartParams", tiers: ["plugin", "builtin"] },
{ name: "subagent/result", direction: "host_to_core", request: true, params: "SubagentHandleParams", tiers: ["plugin", "builtin"] },
{ name: "subagent/dispose", direction: "host_to_core", request: true, params: "SubagentHandleParams", tiers: ["plugin", "builtin"] },
{ name: "dsh/broker", direction: "host_to_core", request: true, params: "DshBrokerParams", tiers: ["plugin", "builtin"] },
{ name: "proc/launch", direction: "host_to_core", request: true, params: "ProcLaunchParams", tiers: ["builtin"] },
{ name: "proc/read", direction: "host_to_core", request: true, params: "ProcSessionParams", tiers: ["builtin"] },
{ name: "proc/write", direction: "host_to_core", request: true, params: "ProcWriteParams", tiers: ["builtin"] },
@@ -15941,16 +15939,6 @@ var init_protocol_generated = __esm({
required: { owner: { ref: "OwnerRef" } },
optional: { entry: { ref: "EntryRef" } }
},
DshBrokerParams: {
strict: true,
required: { owner: { ref: "OwnerRef" }, ticket: "string", service: "string", method: "string", input: "json" },
optional: {}
},
DshBrokerTicketWire: {
strict: true,
required: { service: "string", ticket: "string" },
optional: {}
},
EmptyParams: {
strict: true,
required: {},
@@ -16114,7 +16102,7 @@ var init_protocol_generated = __esm({
ToolCallParams: {
strict: false,
required: { handle: "uint", call_id: "string", input: "json", deadline_ms: "uint" },
optional: { workspace: "string", ticket: "string", checkpoint_ticket: "string", question_ticket: "string", subagent_ticket: "string", broker_tickets: { items: { ref: "DshBrokerTicketWire" } }, caller_tools: { items: "string" }, session_id: "string", agent_id: "string", origin_turn_id: "string" }
optional: { workspace: "string", ticket: "string", checkpoint_ticket: "string", question_ticket: "string", subagent_ticket: "string", caller_tools: { items: "string" }, session_id: "string", agent_id: "string", origin_turn_id: "string" }
},
UnregisterParams: {
strict: true,
@@ -16437,291 +16425,6 @@ var init_rpc = __esm({
}
});
// src/dsh/session-prompt.ts
function checkpointCall(host2, ctx, session) {
const invocation = host2.liveInvocation(ctx);
const ticket = invocation?.ticket;
return invocation !== void 0 && typeof ticket === "string" && ticket.length > 0 && session !== void 0 && session === invocation.session ? invocation : void 0;
}
var CHILD_ONLY, sessionsAdapter, systemPromptAdapter;
var init_session_prompt = __esm({
"src/dsh/session-prompt.ts"() {
"use strict";
init_define_BUILTIN_MODULE_DIGESTS();
init_lib2();
init_protocol();
init_rpc();
CHILD_ONLY = "system prompt sections are only available on a child agent's agent/created context";
sessionsAdapter = {
service: "sessions",
define(host2) {
class SessionsService extends Service {
constructor(ctx) {
super(ctx, "sessions");
}
async flush(session) {
const ctx = this.ctx;
const call = checkpointCall(host2, ctx, session);
if (call === void 0) throw new RpcError(ErrorCode.NotAvailable, "sessions.flush requires this live tool invocation’s session");
const owner = call.owner;
const live = () => checkpointCall(host2, ctx, session) === call && !call.signal.aborted;
const run = async () => {
if (!live()) throw new RpcError(ErrorCode.NotAvailable, "session checkpoint invocation ended");
const result2 = await host2.rpc.request("session/checkpoint", { owner: owner.ref, ticket: call.ticket }, call.signal);
if (!live()) throw new RpcError(ErrorCode.NotAvailable, "session checkpoint invocation ended");
if (typeof result2 !== "boolean") throw new RpcError(ErrorCode.Internal, "invalid session checkpoint receipt");
return result2;
};
const result = call.pending.then(run);
call.pending = result.then(() => void 0, () => void 0);
return result;
}
}
Object.freeze(SessionsService.prototype);
return SessionsService;
}
};
systemPromptAdapter = {
service: "systemPrompt",
define() {
class SystemPromptService extends Service {
constructor(ctx) {
super(ctx, "systemPrompt");
}
section() {
throw new RpcError(ErrorCode.NotAvailable, CHILD_ONLY);
}
getSectionOrder() {
throw new RpcError(ErrorCode.NotAvailable, CHILD_ONLY);
}
}
Object.freeze(SystemPromptService.prototype);
return SystemPromptService;
}
};
}
});
// src/dsh/agents.ts
function plain(value, allowed, what) {
if (value === null || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new RpcError(ErrorCode.InvalidParams, `expected a plain ${what} object`);
const result = /* @__PURE__ */ Object.create(null);
for (const key of Reflect.ownKeys(value)) {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (typeof key !== "string" || !allowed.includes(key) || !("value" in descriptor)) throw new RpcError(ErrorCode.NotAvailable, `unsupported ${what} property ${String(key)}`);
if (descriptor.value !== void 0) result[key] = descriptor.value;
}
return result;
}
function defineSubagents(host2) {
class SubagentsShim extends Service {
constructor(ctx) {
super(ctx, "subagents");
}
getProvider(name) {
return name === "spawn" ? SPAWN_PROVIDER : void 0;
}
async startActivation(request) {
const owner = host2.ownerOf(this.ctx);
const input = plain(request, ["provider", "label", "childId", "request", "signal", "delivery"], "activation");
if (input.provider !== "spawn") throw new RpcError(ErrorCode.NotAvailable, "only the spawn provider is available");
const spawn = plain(input.request, ["parent", "prompt", "agentOptions"], "spawn request");
const options = spawn.agentOptions === void 0 ? {} : plain(spawn.agentOptions, ["model"], "agentOptions");
if (options.model !== void 0 && typeof options.model !== "string") throw new RpcError(ErrorCode.InvalidParams, "agentOptions.model must be a string");
const delivery = input.delivery === void 0 ? "parent" : input.delivery;
if (delivery !== "caller" && delivery !== "parent") throw new RpcError(ErrorCode.InvalidParams, "delivery must be caller or parent");
const childId = input.childId;
if (typeof childId !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(childId)) throw new RpcError(ErrorCode.InvalidParams, "childId must be 1-128 letters, digits, or _.:-");
if (!Array.isArray(spawn.prompt) || spawn.prompt.length === 0) throw new RpcError(ErrorCode.InvalidParams, "prompt must be a non-empty content array");
const prompt = spawn.prompt.map((block) => {
const item = plain(block, ["type", "text"], "prompt block");
if (item.type !== "text" || typeof item.text !== "string") throw new RpcError(ErrorCode.NotAvailable, "only text prompt blocks are supported");
return item.text;
}).join("");
if (input.signal !== void 0 && !(input.signal instanceof AbortSignal)) throw new RpcError(ErrorCode.InvalidParams, "signal must be an AbortSignal");
const invocation = host2.liveInvocation(this.ctx);
if (!invocation || invocation.agent === void 0 || spawn.parent !== invocation.agent) {
throw new RpcError(ErrorCode.NotAvailable, "startActivation requires the exact live calling agent as parent");
}
if (invocation.owner !== owner) throw new RpcError(ErrorCode.NotAvailable, "subagents service owner is no longer current");
if (invocation.delegated || invocation.subagentTicket === void 0) throw new RpcError(ErrorCode.NotAvailable, "child agents are only available to a root tool invocation");
const signal = input.signal === void 0 ? invocation.signal : AbortSignal.any([invocation.signal, input.signal]);
signal.throwIfAborted();
let persona;
const denied2 = /* @__PURE__ */ new Set();
let open2 = true;
const sealed = () => {
if (!open2) throw new RpcError(ErrorCode.NotAvailable, "the child creation window has closed");
};
const child = Object.freeze({
id: childId,
ctx: Object.freeze({
systemPrompt: Object.freeze({
getSectionOrder(name) {
sealed();
if (name !== "DEPLOYMENT_PERSONA_PREFIX") throw new RpcError(ErrorCode.NotAvailable, "only the deployment persona slot is available");
return PERSONA_ORDER;
},
section(section) {
sealed();
const value = plain(section, ["name", "order", "text"], "system prompt section");
if (value.name !== PERSONA_PREFIX_SECTION || value.order !== PERSONA_ORDER || typeof value.text !== "string") {
throw new RpcError(ErrorCode.NotAvailable, "only the child deployment persona section is supported");
}
if (persona !== void 0) throw new RpcError(ErrorCode.InvalidParams, "the child persona is already set");
if (Buffer.byteLength(value.text) > 32 * 1024) throw new RpcError(ErrorCode.InvalidParams, "child persona exceeds 32768 bytes");
persona = value.text;
return () => void 0;
}
}),
tools: Object.freeze({
restrict(filter) {
sealed();
const value = plain(filter, ["deny"], "tool filter");
if (!Array.isArray(value.deny) || value.deny.some((name) => typeof name !== "string" || name === "")) throw new RpcError(ErrorCode.InvalidParams, "deny must be a list of tool names");
for (const name of value.deny) denied2.add(name);
return () => void 0;
}
})
})
});
const listeners = (this.ctx.root?.events?._hooks?.["agent/created"] ?? []).filter((hook) => !hook.global && hook.ctx !== void 0 && host2.ownerOf(hook.ctx) === owner).map((hook) => hook.callback);
try {
await Promise.all(listeners.map(async (callback) => callback({ agent: child })));
} finally {
open2 = false;
}
signal.throwIfAborted();
const call = invocation;
const rpc2 = (method, params, abort) => host2.rpc.request(method, { owner: call.owner.ref, ticket: call.subagentTicket, child_id: childId, ...params }, abort);
const started = await rpc2("subagent/start", {
prompt,
...options.model === void 0 ? {} : { model: options.model },
...persona === void 0 ? {} : { persona },
denied_tools: [...denied2],
delivery
}, signal);
if (started === null || typeof started !== "object" || started.child_id !== childId || typeof started.message_id !== "string") {
throw new RpcError(ErrorCode.Internal, "invalid child activation receipt");
}
let result;
let disposed;
return Object.freeze({
childId,
messageId: started.message_id,
get result() {
result ??= rpc2("subagent/result", {}, call.signal).then((value) => {
if (value === null || typeof value !== "object" || typeof value.stop_reason !== "string" || !Array.isArray(value.output)) {
throw new RpcError(ErrorCode.Internal, "invalid child result receipt");
}
return Object.freeze({
stopReason: value.stop_reason,
output: Object.freeze(value.output.map((block) => Object.freeze({ type: "text", text: String(block.text) }))),
...value.omitted_blocks > 0 ? { diagnostic: `${value.omitted_blocks} non-text output block(s) are not supported` } : {}
});
});
return result;
},
dispose() {
disposed ??= rpc2("subagent/dispose", {}, call.signal).then(() => void 0);
return disposed;
}
});
}
}
Object.freeze(SubagentsShim.prototype);
return SubagentsShim;
}
function defineAgents() {
class AgentsShim extends Service {
constructor(ctx) {
super(ctx, "agents");
}
}
Object.freeze(AgentsShim.prototype);
return AgentsShim;
}
var SPAWN_PROVIDER, PERSONA_ORDER, DSH_AGENT_ADAPTERS;
var init_agents = __esm({
"src/dsh/agents.ts"() {
"use strict";
init_define_BUILTIN_MODULE_DIGESTS();
init_lib2();
init_protocol();
init_rpc();
init_dsh_message_compat();
SPAWN_PROVIDER = Object.freeze({
name: "spawn",
inheritsParentContext: false,
capabilities: Object.freeze({ persona: true, toolFilter: true, agentOptions: true })
});
PERSONA_ORDER = 0;
DSH_AGENT_ADAPTERS = Object.freeze([
{ service: "subagents", define: defineSubagents },
{ service: "agents", define: defineAgents }
]);
}
});
// src/dsh/remote.ts
function label(value) {
if (value === void 0) return void 0;
if (typeof value !== "string") throw new RpcError(ErrorCode.InvalidParams, "remote.pair label must be a string");
return value;
}
function grant(value) {
if (typeof value !== "string" || value.length === 0 || value.length > 128) throw new RpcError(ErrorCode.InvalidParams, "remote.revoke needs the grant id remote.pair returned");
return value;
}
var remoteAdapter;
var init_remote = __esm({
"src/dsh/remote.ts"() {
"use strict";
init_define_BUILTIN_MODULE_DIGESTS();
init_lib2();
init_protocol();
init_rpc();
remoteAdapter = {
service: "remote",
define(host2) {
class RemoteService extends Service {
constructor(ctx) {
super(ctx, "remote");
}
status() {
return host2.broker(this.ctx, "remote", "status", {});
}
pair(options) {
const value = label(options?.label);
return host2.broker(this.ctx, "remote", "pair", value === void 0 ? {} : { label: value });
}
clients() {
return host2.broker(this.ctx, "remote", "clients", {});
}
revoke(id) {
return host2.broker(this.ctx, "remote", "revoke", { grant: grant(id) });
}
}
Object.freeze(RemoteService.prototype);
return RemoteService;
}
};
}
});
// src/dsh/adapters.ts
var DSH_ADAPTERS;
var init_adapters = __esm({
"src/dsh/adapters.ts"() {
"use strict";
init_define_BUILTIN_MODULE_DIGESTS();
init_session_prompt();
init_agents();
init_remote();
DSH_ADAPTERS = [sessionsAdapter, systemPromptAdapter, ...DSH_AGENT_ADAPTERS, remoteAdapter];
}
});
// src/shims/core.ts
function failureFor(error) {
if (error instanceof CoreCallError) return error;
@@ -17497,10 +17200,10 @@ function describeError2(error) {
if (error instanceof Error) return `${error.name}: ${error.message}`;
return String(error);
}
function withDeadline(promise, ms, label2) {
function withDeadline(promise, ms, label) {
let timer;
const deadline = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`${label2} exceeded ${ms} ms`)), ms);
timer = setTimeout(() => reject(new Error(`${label} exceeded ${ms} ms`)), ms);
timer.unref();
});
return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
@@ -17597,13 +17300,12 @@ function pendingFibers(fiber) {
}
return out;
}
var OWNER, REFUSED_SERVICES, PROVIDED_SERVICES, CORDIS_SERVICES, ACTIVATE_DEADLINE_MS, DISPOSE_DEADLINE_MS, ownerStorage, HostRoot;
var OWNER, REFUSED_SERVICES, PROVIDED_SERVICES, ACTIVATE_DEADLINE_MS, DISPOSE_DEADLINE_MS, ownerStorage, HostRoot;
var init_root = __esm({
"src/root.ts"() {
"use strict";
init_define_BUILTIN_MODULE_DIGESTS();
init_composition();
init_adapters();
init_lib2();
init_protocol();
init_rpc();
@@ -17627,12 +17329,11 @@ var init_root = __esm({
OWNER = /* @__PURE__ */ Symbol.for("codewhale.extension-host.owner");
REFUSED_SERVICES = new Set(compatibility_default.refused_services);
PROVIDED_SERVICES = new Set(Object.values(compatibility_default.provided_services).flat());
CORDIS_SERVICES = new Set(compatibility_default.provided_services.cordis);
ACTIVATE_DEADLINE_MS = 5e3;
DISPOSE_DEADLINE_MS = 2e3;
ownerStorage = new AsyncLocalStorage2();
HostRoot = class {
constructor(rpc2, tier, adapters = DSH_ADAPTERS) {
constructor(rpc2, tier) {
this.rpc = rpc2;
this.tier = tier;
const root = new Context();
@@ -17770,6 +17471,28 @@ var init_root = __esm({
return this.api().delete(key);
}
}
class SessionsShim extends Service {
constructor(ctx) {
super(ctx, "sessions");
}
async flush(session) {
const invocation = host2.toolInvocations.getStore();
const owner = this.ctx[OWNER];
const live = () => invocation && invocation.active && !invocation.signal.aborted && invocation.owner === owner && owner?.state === "active" && !owner.disposing && invocation.ticket !== void 0 && session === invocation.session && session !== void 0;
if (!live()) throw new RpcError(ErrorCode.NotAvailable, "sessions.flush requires this live tool invocation’s session");
const call = invocation;
const run = async () => {
if (!live()) throw new RpcError(ErrorCode.NotAvailable, "session checkpoint invocation ended");
const result2 = await host2.rpc.request("session/checkpoint", { owner: call.owner.ref, ticket: call.ticket }, call.signal);
if (!live()) throw new RpcError(ErrorCode.NotAvailable, "session checkpoint invocation ended");
if (typeof result2 !== "boolean") throw new RpcError(ErrorCode.Internal, "invalid session checkpoint receipt");
return result2;
};
const result = call.pending.then(run);
call.pending = result.then(() => void 0, () => void 0);
return result;
}
}
class UserQuestionsShim extends Service {
constructor(ctx) {
super(ctx, "userQuestions");
@@ -17888,49 +17611,185 @@ var init_root = __esm({
return Promise.race([result, cancelled]).finally(() => signal.removeEventListener("abort", cancel));
}
}
Object.freeze(UserQuestionsShim.prototype);
Object.freeze(StorageShim.prototype);
const adapterHost = {
tier,
rpc: rpc2,
ownerOf: (ctx) => ctx[OWNER],
liveInvocation: (ctx) => {
const SPAWN_PROVIDER = Object.freeze({
name: "spawn",
inheritsParentContext: false,
capabilities: Object.freeze({ persona: true, toolFilter: true, agentOptions: true })
});
const PERSONA_ORDER = 0;
class SubagentsShim extends Service {
constructor(ctx) {
super(ctx, "subagents");
}
getProvider(name) {
return name === "spawn" ? SPAWN_PROVIDER : void 0;
}
async startActivation(request) {
const invocation = host2.toolInvocations.getStore();
const owner = ctx[OWNER];
return invocation && invocation.active && !invocation.signal.aborted && owner !== void 0 && invocation.owner === owner && owner.state === "active" && !owner.disposing ? invocation : void 0;
},
log: (level, message, owner) => host2.log(level, message, owner),
broker: async (ctx, service, method, input) => {
const invocation = adapterHost.liveInvocation(ctx);
const ticket = invocation?.brokerTickets.get(service);
if (invocation === void 0 || ticket === void 0) throw new RpcError(ErrorCode.NotAvailable, `the ${String(service).slice(0, 64)} broker is only available to a live tool invocation the core gave a ticket for it`);
return rpc2.request("dsh/broker", { owner: invocation.owner.ref, ticket, service, method, input }, invocation.signal);
const owner = this.ctx[OWNER];
const plain = (value, allowed, what) => {
if (value === null || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new RpcError(ErrorCode.InvalidParams, `expected a plain ${what} object`);
const result2 = /* @__PURE__ */ Object.create(null);
for (const key of Reflect.ownKeys(value)) {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (typeof key !== "string" || !allowed.includes(key) || !("value" in descriptor)) throw new RpcError(ErrorCode.NotAvailable, `unsupported ${what} property ${String(key)}`);
if (descriptor.value !== void 0) result2[key] = descriptor.value;
}
return result2;
};
const input = plain(request, ["provider", "label", "childId", "request", "signal", "delivery"], "activation");
if (input.provider !== "spawn") throw new RpcError(ErrorCode.NotAvailable, "only the spawn provider is available");
const spawn = plain(input.request, ["parent", "prompt", "agentOptions"], "spawn request");
const options = spawn.agentOptions === void 0 ? {} : plain(spawn.agentOptions, ["model"], "agentOptions");
if (options.model !== void 0 && typeof options.model !== "string") throw new RpcError(ErrorCode.InvalidParams, "agentOptions.model must be a string");
const delivery = input.delivery === void 0 ? "parent" : input.delivery;
if (delivery !== "caller" && delivery !== "parent") throw new RpcError(ErrorCode.InvalidParams, "delivery must be caller or parent");
const childId = input.childId;
if (typeof childId !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(childId)) throw new RpcError(ErrorCode.InvalidParams, "childId must be 1-128 letters, digits, or _.:-");
if (!Array.isArray(spawn.prompt) || spawn.prompt.length === 0) throw new RpcError(ErrorCode.InvalidParams, "prompt must be a non-empty content array");
const prompt = spawn.prompt.map((block) => {
const item = plain(block, ["type", "text"], "prompt block");
if (item.type !== "text" || typeof item.text !== "string") throw new RpcError(ErrorCode.NotAvailable, "only text prompt blocks are supported");
return item.text;
}).join("");
if (input.signal !== void 0 && !(input.signal instanceof AbortSignal)) throw new RpcError(ErrorCode.InvalidParams, "signal must be an AbortSignal");
if (!invocation || !invocation.active || invocation.signal.aborted || invocation.agent === void 0 || spawn.parent !== invocation.agent) {
throw new RpcError(ErrorCode.NotAvailable, "startActivation requires the exact live calling agent as parent");
}
if (invocation.owner !== owner || owner?.state !== "active" || owner.disposing) throw new RpcError(ErrorCode.NotAvailable, "subagents service owner is no longer current");
if (invocation.delegated || invocation.subagentTicket === void 0) throw new RpcError(ErrorCode.NotAvailable, "child agents are only available to a root tool invocation");
const signal = input.signal === void 0 ? invocation.signal : AbortSignal.any([invocation.signal, input.signal]);
signal.throwIfAborted();
let persona;
const denied2 = /* @__PURE__ */ new Set();
let open2 = true;
const sealed = () => {
if (!open2) throw new RpcError(ErrorCode.NotAvailable, "the child creation window has closed");
};
const child = Object.freeze({
id: childId,
ctx: Object.freeze({
systemPrompt: Object.freeze({
getSectionOrder(name) {
sealed();
if (name !== "DEPLOYMENT_PERSONA_PREFIX") throw new RpcError(ErrorCode.NotAvailable, "only the deployment persona slot is available");
return PERSONA_ORDER;
},
section(section) {
sealed();
const value = plain(section, ["name", "order", "text"], "system prompt section");
if (value.name !== PERSONA_PREFIX_SECTION || value.order !== PERSONA_ORDER || typeof value.text !== "string") {
throw new RpcError(ErrorCode.NotAvailable, "only the child deployment persona section is supported");
}
if (persona !== void 0) throw new RpcError(ErrorCode.InvalidParams, "the child persona is already set");
if (Buffer.byteLength(value.text) > 32 * 1024) throw new RpcError(ErrorCode.InvalidParams, "child persona exceeds 32768 bytes");
persona = value.text;
return () => void 0;
}
}),
tools: Object.freeze({
restrict(filter) {
sealed();
const value = plain(filter, ["deny"], "tool filter");
if (!Array.isArray(value.deny) || value.deny.some((name) => typeof name !== "string" || name === "")) throw new RpcError(ErrorCode.InvalidParams, "deny must be a list of tool names");
for (const name of value.deny) denied2.add(name);
return () => void 0;
}
})
})
});
const listeners = (host2.root.events?._hooks?.["agent/created"] ?? []).filter((hook) => !hook.global && hook.ctx?.[OWNER] === owner).map((hook) => hook.callback);
try {
await Promise.all(listeners.map(async (callback) => callback({ agent: child })));
} finally {
open2 = false;
}
signal.throwIfAborted();
const call = invocation;
const rpc3 = (method, params, abort) => host2.rpc.request(method, { owner: call.owner.ref, ticket: call.subagentTicket, child_id: childId, ...params }, abort);
const started = await rpc3("subagent/start", {
prompt,
...options.model === void 0 ? {} : { model: options.model },
...persona === void 0 ? {} : { persona },
denied_tools: [...denied2],
delivery
}, signal);
if (started === null || typeof started !== "object" || started.child_id !== childId || typeof started.message_id !== "string") {
throw new RpcError(ErrorCode.Internal, "invalid child activation receipt");
}
let result;
let disposed;
return Object.freeze({
childId,
messageId: started.message_id,
get result() {
result ??= rpc3("subagent/result", {}, call.signal).then((value) => {
if (value === null || typeof value !== "object" || typeof value.stop_reason !== "string" || !Array.isArray(value.output)) {
throw new RpcError(ErrorCode.Internal, "invalid child result receipt");
}
return Object.freeze({
stopReason: value.stop_reason,
output: Object.freeze(value.output.map((block) => Object.freeze({ type: "text", text: String(block.text) }))),
...value.omitted_blocks > 0 ? { diagnostic: `${value.omitted_blocks} non-text output block(s) are not supported` } : {}
});
});
return result;
},
dispose() {
disposed ??= rpc3("subagent/dispose", {}, call.signal).then(() => void 0);
return disposed;
}
});
}
};
const shims = /* @__PURE__ */ new Map([
["tools", ToolsShim],
["commands", CommandsShim],
["prompt", PromptShim],
["storage", StorageShim],
["userQuestions", UserQuestionsShim],
["skills", SkillsShim],
["avatars", AvatarsShim],
["mcp", McpShim],
["shellHooks", ShellHooksShim]
]);
for (const adapter of adapters) {
if (shims.has(adapter.service)) throw new Error(`DSH adapter for \`${adapter.service}\` duplicates a service the host root already provides`);
shims.set(adapter.service, adapter.define(adapterHost));
}
const mismatched = [
...[...shims.keys()].filter((name) => !PROVIDED_SERVICES.has(name)).map((name) => `${name} is installed but not declared in compatibility.json`),
...[...PROVIDED_SERVICES].filter((name) => !CORDIS_SERVICES.has(name) && !shims.has(name)).map((name) => `${name} is declared in compatibility.json but has no installed service`)
];
if (mismatched.length > 0) throw new Error(`DSH provided services disagree with the installed services: ${mismatched.join("; ")}`);
for (const [name, shim] of shims) {
shimClasses.set(name, shim);
root.plugin(shim);
class AgentsShim extends Service {
constructor(ctx) {
super(ctx, "agents");
}
}
class SystemPromptShim extends Service {
constructor(ctx) {
super(ctx, "systemPrompt");
}
section() {
throw new RpcError(ErrorCode.NotAvailable, "system prompt sections are only available on a child agent's agent/created context");
}
getSectionOrder() {
throw new RpcError(ErrorCode.NotAvailable, "system prompt sections are only available on a child agent's agent/created context");
}
}
Object.freeze(SubagentsShim.prototype);
Object.freeze(AgentsShim.prototype);
Object.freeze(SystemPromptShim.prototype);
Object.freeze(UserQuestionsShim.prototype);
Object.freeze(SessionsShim.prototype);
Object.freeze(StorageShim.prototype);
shimClasses.set("tools", ToolsShim);
shimClasses.set("commands", CommandsShim);
shimClasses.set("prompt", PromptShim);
shimClasses.set("storage", StorageShim);
shimClasses.set("sessions", SessionsShim);
shimClasses.set("userQuestions", UserQuestionsShim);
shimClasses.set("subagents", SubagentsShim);
shimClasses.set("agents", AgentsShim);
shimClasses.set("systemPrompt", SystemPromptShim);
shimClasses.set("skills", SkillsShim);
shimClasses.set("avatars", AvatarsShim);
shimClasses.set("mcp", McpShim);
shimClasses.set("shellHooks", ShellHooksShim);
root.plugin(ToolsShim);
root.plugin(CommandsShim);
root.plugin(PromptShim);
root.plugin(StorageShim);
root.plugin(SessionsShim);
root.plugin(UserQuestionsShim);
root.plugin(SubagentsShim);
root.plugin(AgentsShim);
root.plugin(SystemPromptShim);
root.plugin(SkillsShim);
root.plugin(AvatarsShim);
root.plugin(McpShim);
root.plugin(ShellHooksShim);
shimClasses.set("loader", ReviewedLoader);
installCompositionLoader(root);
}
@@ -18051,8 +17910,7 @@ var init_root = __esm({
const plugin = pickPlugin(module);
const missing = Object.keys(Inject.resolve(plugin.inject)).filter((name) => !PROVIDED_SERVICES.has(name));
if (missing.length > 0) {
const owned = missing.filter((name) => REFUSED_SERVICES.has(name));
throw new Error(`requires ${missing.map((name) => `\`${name}\``).join(", ")}, not provided by the Codewhale extension host in this phase` + (owned.length > 0 ? `; ${owned.map((name) => `\`${name}\``).join(", ")} belong${owned.length === 1 ? "s" : ""} to the Codewhale core and no reviewed bridge exposes ${owned.length === 1 ? "it" : "them"} yet` : ""));
throw new Error(`requires ${missing.map((name) => `\`${name}\``).join(", ")}, not provided by the Codewhale extension host in this phase`);
}
const ownerCtx = this.root.extend({ [OWNER]: owner });
const fiber = ownerStorage.run(owner, () => ownerCtx.plugin(plugin, params.config ?? {}));
@@ -18201,7 +18059,6 @@ var init_root = __esm({
agent,
questionTicket: identity?.question_ticket,
subagentTicket: identity?.subagent_ticket,
brokerTickets: new Map((identity?.broker_tickets ?? []).map(({ service, ticket: ticket2 }) => [service, ticket2])),
callerTools: Object.freeze([...identity?.caller_tools ?? []]),
delegated: identity?.agent_id !== void 0,
ticket: identity?.checkpoint_ticket,
+44 -355
View File
@@ -755,7 +755,7 @@ var init_lib2 = __esm({
} else throw new TypeError("Invalid effect");
}, runner.getOuterStack);
}
effect(execute, label2 = "anonymous") {
effect(execute, label = "anonymous") {
this.assertActive();
if (this.state === 5) throw new CordisError("INACTIVE_EFFECT");
const disposables = [];
@@ -773,7 +773,7 @@ var init_lib2 = __esm({
return disposalTask = task2;
};
const meta = {
label: label2,
label,
children: []
};
const runner = {
@@ -1195,7 +1195,7 @@ var init_lib2 = __esm({
};
return dispatch();
}
register(label2, name, callback, options) {
register(label, name, callback, options) {
const method = options.prepend ? "unshift" : "push";
return this.ctx.fiber.effect(() => {
(this._hooks[name] ??= [])[method]({
@@ -1204,7 +1204,7 @@ var init_lib2 = __esm({
...options
});
return () => this.unregister(name, callback);
}, label2);
}, label);
}
unregister(name, callback) {
const hooks = this._hooks[name];
@@ -1233,8 +1233,8 @@ var init_lib2 = __esm({
listener = this.ctx.reflect.bind(listener);
const result = this.bail(this.ctx, "internal/listener", name, listener, options);
if (result) return result;
const label2 = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
return this.register(label2, name, listener, options);
const label = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
return this.register(label, name, listener, options);
}
/**
* Register an event listener that disposes itself after the first call.
@@ -1979,9 +1979,9 @@ var init_lib2 = __esm({
* @param label — scope label to join; defaults to a fresh unique symbol.
* @returns a child context whose `name` service resolves in the new scope.
*/
isolate(name, label2) {
isolate(name, label) {
const shadow = Object.create(this[symbols.isolate]);
shadow[name] = label2 ?? Symbol(name);
shadow[name] = label ?? Symbol(name);
return this.extend({ [symbols.isolate]: shadow });
}
intercept(name, config) {
@@ -2621,14 +2621,14 @@ function isolate(ctx) {
const delims = /* @__PURE__ */ Object.create(null);
function access2(entry, name, create = false) {
let realm;
const label2 = entry.options.isolate?.[name];
if (!label2) return;
if (label2 === true) {
const label = entry.options.isolate?.[name];
if (!label) return;
if (label === true) {
realm = entry.realm ??= new LocalRealm(entry);
} else if (create) {
realm = realms[label2] ??= new GlobalRealm(label2);
realm = realms[label] ??= new GlobalRealm(label);
} else {
realm = realms[label2];
realm = realms[label];
}
return realm?.access(name, create);
}
@@ -2685,10 +2685,10 @@ function isolate(ctx) {
}
});
ctx.on("loader/partial-dispose", (entry, legacy, active) => {
for (const [name, label2] of Object.entries(legacy.isolate ?? {})) {
if (label2 === true) continue;
if (active && entry.options.isolate?.[name] === label2) continue;
const realm = realms[label2];
for (const [name, label] of Object.entries(legacy.isolate ?? {})) {
if (label === true) continue;
if (active && entry.options.isolate?.[name] === label) continue;
const realm = realms[label];
if (!realm) continue;
for (const entry2 of ctx.loader.entries()) {
if (entry2.options.isolate?.[name] === realm.label) return;
@@ -2732,9 +2732,9 @@ var init_isolate = __esm({
}
};
GlobalRealm = class extends Realm {
constructor(label2) {
constructor(label) {
super();
this.label = label2;
this.label = label;
}
label;
get suffix() {
@@ -5423,14 +5423,14 @@ function requireDumper() {
let hasFoldableLine = false;
const shouldTrackWidth = lineWidth !== -1;
let previousLineBreak = -1;
let plain3 = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
let plain2 = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
if (singleLineOnly || forceQuotes) {
for (i2 = 0; i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
char = codePointAt(string, i2);
if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain3 = plain3 && isPlainSafe(char, prevChar, inblock);
plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
prevChar = char;
}
} else {
@@ -5446,13 +5446,13 @@ function requireDumper() {
} else if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain3 = plain3 && isPlainSafe(char, prevChar, inblock);
plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
prevChar = char;
}
hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
}
if (!hasLineBreak && !hasFoldableLine) {
if (plain3 && !forceQuotes && !testAmbiguousType(string)) {
if (plain2 && !forceQuotes && !testAmbiguousType(string)) {
return STYLE_PLAIN;
}
return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
@@ -7348,9 +7348,9 @@ var init_acorn = __esm({
keywordRelationalOperator = /^in(stanceof)?$/;
nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
TokenType = function TokenType2(label2, conf) {
TokenType = function TokenType2(label, conf) {
if (conf === void 0) conf = {};
this.label = label2;
this.label = label;
this.keyword = conf.keyword;
this.beforeExpr = !!conf.beforeExpr;
this.startsExpr = !!conf.startsExpr;
@@ -8399,8 +8399,8 @@ var init_acorn = __esm({
};
pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
for (var i$1 = 0, list2 = this.labels; i$1 < list2.length; i$1 += 1) {
var label2 = list2[i$1];
if (label2.name === maybeName) {
var label = list2[i$1];
if (label.name === maybeName) {
this.raise(expr.start, "Label '" + maybeName + "' is already declared");
}
}
@@ -12773,8 +12773,7 @@ var init_compatibility = __esm({
"prompt",
"avatars",
"mcp",
"shellHooks",
"remote"
"shellHooks"
]
},
refused_services: [
@@ -13230,23 +13229,11 @@ var init_prompt = __esm({
});
// src/protocol.generated.ts
var MAGIC_ASCII, ErrorCode;
var MAGIC_ASCII;
var init_protocol_generated = __esm({
"src/protocol.generated.ts"() {
"use strict";
MAGIC_ASCII = "CWX1";
ErrorCode = {
ParseError: -32700,
InvalidRequest: -32600,
MethodNotFound: -32601,
InvalidParams: -32602,
Internal: -32603,
ExecutionFailed: -32e3,
NotAvailable: -32001,
Refused: -32002,
Denied: -32003,
Cancelled: -32800
};
}
});
@@ -13262,88 +13249,10 @@ var init_protocol = __esm({
});
// src/rpc.ts
var RpcError;
var init_rpc = __esm({
"src/rpc.ts"() {
"use strict";
init_protocol();
RpcError = class extends Error {
constructor(code, message, data2) {
super(message);
this.code = code;
this.data = data2;
this.name = "RpcError";
}
code;
data;
toWire() {
return this.data === void 0 ? { code: this.code, message: this.message } : { code: this.code, message: this.message, data: this.data };
}
};
}
});
// src/dsh/session-prompt.ts
function checkpointCall(host, ctx, session) {
const invocation = host.liveInvocation(ctx);
const ticket = invocation?.ticket;
return invocation !== void 0 && typeof ticket === "string" && ticket.length > 0 && session !== void 0 && session === invocation.session ? invocation : void 0;
}
var CHILD_ONLY, sessionsAdapter, systemPromptAdapter;
var init_session_prompt = __esm({
"src/dsh/session-prompt.ts"() {
"use strict";
init_lib2();
init_protocol();
init_rpc();
CHILD_ONLY = "system prompt sections are only available on a child agent's agent/created context";
sessionsAdapter = {
service: "sessions",
define(host) {
class SessionsService extends Service {
constructor(ctx) {
super(ctx, "sessions");
}
async flush(session) {
const ctx = this.ctx;
const call = checkpointCall(host, ctx, session);
if (call === void 0) throw new RpcError(ErrorCode.NotAvailable, "sessions.flush requires this live tool invocation’s session");
const owner = call.owner;
const live = () => checkpointCall(host, ctx, session) === call && !call.signal.aborted;
const run = async () => {
if (!live()) throw new RpcError(ErrorCode.NotAvailable, "session checkpoint invocation ended");
const result2 = await host.rpc.request("session/checkpoint", { owner: owner.ref, ticket: call.ticket }, call.signal);
if (!live()) throw new RpcError(ErrorCode.NotAvailable, "session checkpoint invocation ended");
if (typeof result2 !== "boolean") throw new RpcError(ErrorCode.Internal, "invalid session checkpoint receipt");
return result2;
};
const result = call.pending.then(run);
call.pending = result.then(() => void 0, () => void 0);
return result;
}
}
Object.freeze(SessionsService.prototype);
return SessionsService;
}
};
systemPromptAdapter = {
service: "systemPrompt",
define() {
class SystemPromptService extends Service {
constructor(ctx) {
super(ctx, "systemPrompt");
}
section() {
throw new RpcError(ErrorCode.NotAvailable, CHILD_ONLY);
}
getSectionOrder() {
throw new RpcError(ErrorCode.NotAvailable, CHILD_ONLY);
}
}
Object.freeze(SystemPromptService.prototype);
return SystemPromptService;
}
};
}
});
@@ -13975,12 +13884,11 @@ var init_lib3 = __esm({
});
// src/dsh/dsh-message-compat.js
var PERSONA_PREFIX_SECTION, HarnessError, UserQuestionError;
var HarnessError, UserQuestionError;
var init_dsh_message_compat = __esm({
"src/dsh/dsh-message-compat.js"() {
"use strict";
init_lib3();
PERSONA_PREFIX_SECTION = "deployment:persona-prefix";
HarnessError = class extends Error {
code;
constructor(message, code, options) {
@@ -14000,223 +13908,6 @@ var init_dsh_message_compat = __esm({
}
});
// src/dsh/agents.ts
function plain(value, allowed, what) {
if (value === null || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new RpcError(ErrorCode.InvalidParams, `expected a plain ${what} object`);
const result = /* @__PURE__ */ Object.create(null);
for (const key of Reflect.ownKeys(value)) {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (typeof key !== "string" || !allowed.includes(key) || !("value" in descriptor)) throw new RpcError(ErrorCode.NotAvailable, `unsupported ${what} property ${String(key)}`);
if (descriptor.value !== void 0) result[key] = descriptor.value;
}
return result;
}
function defineSubagents(host) {
class SubagentsShim extends Service {
constructor(ctx) {
super(ctx, "subagents");
}
getProvider(name) {
return name === "spawn" ? SPAWN_PROVIDER : void 0;
}
async startActivation(request) {
const owner = host.ownerOf(this.ctx);
const input = plain(request, ["provider", "label", "childId", "request", "signal", "delivery"], "activation");
if (input.provider !== "spawn") throw new RpcError(ErrorCode.NotAvailable, "only the spawn provider is available");
const spawn = plain(input.request, ["parent", "prompt", "agentOptions"], "spawn request");
const options = spawn.agentOptions === void 0 ? {} : plain(spawn.agentOptions, ["model"], "agentOptions");
if (options.model !== void 0 && typeof options.model !== "string") throw new RpcError(ErrorCode.InvalidParams, "agentOptions.model must be a string");
const delivery = input.delivery === void 0 ? "parent" : input.delivery;
if (delivery !== "caller" && delivery !== "parent") throw new RpcError(ErrorCode.InvalidParams, "delivery must be caller or parent");
const childId = input.childId;
if (typeof childId !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(childId)) throw new RpcError(ErrorCode.InvalidParams, "childId must be 1-128 letters, digits, or _.:-");
if (!Array.isArray(spawn.prompt) || spawn.prompt.length === 0) throw new RpcError(ErrorCode.InvalidParams, "prompt must be a non-empty content array");
const prompt = spawn.prompt.map((block) => {
const item = plain(block, ["type", "text"], "prompt block");
if (item.type !== "text" || typeof item.text !== "string") throw new RpcError(ErrorCode.NotAvailable, "only text prompt blocks are supported");
return item.text;
}).join("");
if (input.signal !== void 0 && !(input.signal instanceof AbortSignal)) throw new RpcError(ErrorCode.InvalidParams, "signal must be an AbortSignal");
const invocation = host.liveInvocation(this.ctx);
if (!invocation || invocation.agent === void 0 || spawn.parent !== invocation.agent) {
throw new RpcError(ErrorCode.NotAvailable, "startActivation requires the exact live calling agent as parent");
}
if (invocation.owner !== owner) throw new RpcError(ErrorCode.NotAvailable, "subagents service owner is no longer current");
if (invocation.delegated || invocation.subagentTicket === void 0) throw new RpcError(ErrorCode.NotAvailable, "child agents are only available to a root tool invocation");
const signal = input.signal === void 0 ? invocation.signal : AbortSignal.any([invocation.signal, input.signal]);
signal.throwIfAborted();
let persona;
const denied = /* @__PURE__ */ new Set();
let open = true;
const sealed = () => {
if (!open) throw new RpcError(ErrorCode.NotAvailable, "the child creation window has closed");
};
const child = Object.freeze({
id: childId,
ctx: Object.freeze({
systemPrompt: Object.freeze({
getSectionOrder(name) {
sealed();
if (name !== "DEPLOYMENT_PERSONA_PREFIX") throw new RpcError(ErrorCode.NotAvailable, "only the deployment persona slot is available");
return PERSONA_ORDER;
},
section(section) {
sealed();
const value = plain(section, ["name", "order", "text"], "system prompt section");
if (value.name !== PERSONA_PREFIX_SECTION || value.order !== PERSONA_ORDER || typeof value.text !== "string") {
throw new RpcError(ErrorCode.NotAvailable, "only the child deployment persona section is supported");
}
if (persona !== void 0) throw new RpcError(ErrorCode.InvalidParams, "the child persona is already set");
if (Buffer.byteLength(value.text) > 32 * 1024) throw new RpcError(ErrorCode.InvalidParams, "child persona exceeds 32768 bytes");
persona = value.text;
return () => void 0;
}
}),
tools: Object.freeze({
restrict(filter) {
sealed();
const value = plain(filter, ["deny"], "tool filter");
if (!Array.isArray(value.deny) || value.deny.some((name) => typeof name !== "string" || name === "")) throw new RpcError(ErrorCode.InvalidParams, "deny must be a list of tool names");
for (const name of value.deny) denied.add(name);
return () => void 0;
}
})
})
});
const listeners = (this.ctx.root?.events?._hooks?.["agent/created"] ?? []).filter((hook) => !hook.global && hook.ctx !== void 0 && host.ownerOf(hook.ctx) === owner).map((hook) => hook.callback);
try {
await Promise.all(listeners.map(async (callback) => callback({ agent: child })));
} finally {
open = false;
}
signal.throwIfAborted();
const call = invocation;
const rpc = (method, params, abort) => host.rpc.request(method, { owner: call.owner.ref, ticket: call.subagentTicket, child_id: childId, ...params }, abort);
const started = await rpc("subagent/start", {
prompt,
...options.model === void 0 ? {} : { model: options.model },
...persona === void 0 ? {} : { persona },
denied_tools: [...denied],
delivery
}, signal);
if (started === null || typeof started !== "object" || started.child_id !== childId || typeof started.message_id !== "string") {
throw new RpcError(ErrorCode.Internal, "invalid child activation receipt");
}
let result;
let disposed;
return Object.freeze({
childId,
messageId: started.message_id,
get result() {
result ??= rpc("subagent/result", {}, call.signal).then((value) => {
if (value === null || typeof value !== "object" || typeof value.stop_reason !== "string" || !Array.isArray(value.output)) {
throw new RpcError(ErrorCode.Internal, "invalid child result receipt");
}
return Object.freeze({
stopReason: value.stop_reason,
output: Object.freeze(value.output.map((block) => Object.freeze({ type: "text", text: String(block.text) }))),
...value.omitted_blocks > 0 ? { diagnostic: `${value.omitted_blocks} non-text output block(s) are not supported` } : {}
});
});
return result;
},
dispose() {
disposed ??= rpc("subagent/dispose", {}, call.signal).then(() => void 0);
return disposed;
}
});
}
}
Object.freeze(SubagentsShim.prototype);
return SubagentsShim;
}
function defineAgents() {
class AgentsShim extends Service {
constructor(ctx) {
super(ctx, "agents");
}
}
Object.freeze(AgentsShim.prototype);
return AgentsShim;
}
var SPAWN_PROVIDER, PERSONA_ORDER, DSH_AGENT_ADAPTERS;
var init_agents = __esm({
"src/dsh/agents.ts"() {
"use strict";
init_lib2();
init_protocol();
init_rpc();
init_dsh_message_compat();
SPAWN_PROVIDER = Object.freeze({
name: "spawn",
inheritsParentContext: false,
capabilities: Object.freeze({ persona: true, toolFilter: true, agentOptions: true })
});
PERSONA_ORDER = 0;
DSH_AGENT_ADAPTERS = Object.freeze([
{ service: "subagents", define: defineSubagents },
{ service: "agents", define: defineAgents }
]);
}
});
// src/dsh/remote.ts
function label(value) {
if (value === void 0) return void 0;
if (typeof value !== "string") throw new RpcError(ErrorCode.InvalidParams, "remote.pair label must be a string");
return value;
}
function grant(value) {
if (typeof value !== "string" || value.length === 0 || value.length > 128) throw new RpcError(ErrorCode.InvalidParams, "remote.revoke needs the grant id remote.pair returned");
return value;
}
var remoteAdapter;
var init_remote = __esm({
"src/dsh/remote.ts"() {
"use strict";
init_lib2();
init_protocol();
init_rpc();
remoteAdapter = {
service: "remote",
define(host) {
class RemoteService extends Service {
constructor(ctx) {
super(ctx, "remote");
}
status() {
return host.broker(this.ctx, "remote", "status", {});
}
pair(options) {
const value = label(options?.label);
return host.broker(this.ctx, "remote", "pair", value === void 0 ? {} : { label: value });
}
clients() {
return host.broker(this.ctx, "remote", "clients", {});
}
revoke(id) {
return host.broker(this.ctx, "remote", "revoke", { grant: grant(id) });
}
}
Object.freeze(RemoteService.prototype);
return RemoteService;
}
};
}
});
// src/dsh/adapters.ts
var DSH_ADAPTERS;
var init_adapters = __esm({
"src/dsh/adapters.ts"() {
"use strict";
init_session_prompt();
init_agents();
init_remote();
DSH_ADAPTERS = [sessionsAdapter, systemPromptAdapter, ...DSH_AGENT_ADAPTERS, remoteAdapter];
}
});
// src/dsh/dsh-tools-compat.js
var init_dsh_tools_compat = __esm({
"src/dsh/dsh-tools-compat.js"() {
@@ -14298,12 +13989,11 @@ var init_commands = __esm({
// src/root.ts
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
var REFUSED_SERVICES, PROVIDED_SERVICES, CORDIS_SERVICES, ownerStorage;
var REFUSED_SERVICES, PROVIDED_SERVICES, ownerStorage;
var init_root = __esm({
"src/root.ts"() {
"use strict";
init_composition();
init_adapters();
init_protocol();
init_rpc();
init_dsh_message_compat();
@@ -14325,7 +14015,6 @@ var init_root = __esm({
init_commands();
REFUSED_SERVICES = new Set(compatibility_default.refused_services);
PROVIDED_SERVICES = new Set(Object.values(compatibility_default.provided_services).flat());
CORDIS_SERVICES = new Set(compatibility_default.provided_services.cordis);
ownerStorage = new AsyncLocalStorage2();
}
});
@@ -14442,16 +14131,16 @@ function entryListProblem(rows, at2 = "") {
return at2 === "" ? "the composition must be a top-level list of plugin rows" : `group ${at2} must hold a list of plugin rows`;
}
for (const [index, row] of rows.entries()) {
const label2 = at2 === "" ? `row ${String(index + 1)}` : `${at2} row ${String(index + 1)}`;
const label = at2 === "" ? `row ${String(index + 1)}` : `${at2} row ${String(index + 1)}`;
if (typeof row !== "object" || row === null || Array.isArray(row)) {
return `${label2} is not a plugin row (expected a map with a "name")`;
return `${label} is not a plugin row (expected a map with a "name")`;
}
const { name, group, config } = row;
if (typeof name !== "string" || name === "") {
return `${label2} names no plugin (a "name" string is required)`;
return `${label} names no plugin (a "name" string is required)`;
}
if (group === true) {
const nested = entryListProblem(config, label2);
const nested = entryListProblem(config, label);
if (nested !== void 0) return nested;
}
}
@@ -14474,8 +14163,8 @@ async function unresolvableRows(rows, presetBase, harnessBase, resolves, io, at2
continue;
}
if (await rowResolves(classifyRowSpecifier(row.name), presetBase, harnessBase, resolves, io)) continue;
const label2 = typeof row.id === "string" && row.id !== "" ? `row "${row.id}"` : positional;
found.push({ label: label2, name: row.name });
const label = typeof row.id === "string" && row.id !== "" ? `row "${row.id}"` : positional;
found.push({ label, name: row.name });
}
return found;
}
@@ -14646,7 +14335,7 @@ var init_composition_inventory = __esm({
import { createHash as createHash2 } from "node:crypto";
import { resolve as resolve4, relative as relative2, dirname as dirname4, sep as sep2 } from "node:path";
import { fileURLToPath as fileURLToPath4, pathToFileURL as pathToFileURL5 } from "node:url";
function plain2(path) {
function plain(path) {
return typeof path === "string" && path.length > 0 && path.length <= 4096 && !/[\\:\u0000-\u001f\u007f]/u.test(path) && !path.startsWith("/") && path.split("/").every((p) => p !== "" && p !== "." && p !== "..");
}
function fail(message) {
@@ -14686,7 +14375,7 @@ function containedPackageModule(name, documents, files) {
entry = value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).some((k) => k.startsWith(".")) ? target(value[subpath]) : subpath === "." ? target(value) : void 0;
} else if (subpath === ".") entry = typeof data2.main === "string" ? data2.main : "./index.js";
else entry = subpath;
if (typeof entry !== "string" || !entry.startsWith("./") || !plain2(entry.slice(2))) return;
if (typeof entry !== "string" || !entry.startsWith("./") || !plain(entry.slice(2))) return;
const path = `${packageRoot}/${entry.slice(2)}`;
if (!/\.(mjs|js|mts)$/.test(path) || !SHA.test(files[path] ?? "")) return;
return { name, path, sha256: files[path] };
@@ -14699,20 +14388,20 @@ async function reviewAgentPresets(input) {
const baseUrl = pathToFileURL5(`${base}${sep2}`).href;
function key(path) {
const inside = relative2(base, path).split(sep2).join("/");
if (!plain2(inside)) fail("path escapes the admitted source root");
if (!plain(inside)) fail("path escapes the admitted source root");
return inside;
}
const documents = /* @__PURE__ */ new Map();
let bytes = 0;
for (const doc of input.documents) {
if (!plain2(doc.path) || !SHA.test(doc.sha256) || files[doc.path] !== doc.sha256 || hash(doc.source) !== doc.sha256 || documents.has(doc.path)) fail("document changed or is outside the source receipt");
if (!plain(doc.path) || !SHA.test(doc.sha256) || files[doc.path] !== doc.sha256 || hash(doc.source) !== doc.sha256 || documents.has(doc.path)) fail("document changed or is outside the source receipt");
bytes += Buffer.byteLength(doc.source);
if (Buffer.byteLength(doc.source) > 1024 * 1024 || bytes > 4 * 1024 * 1024) fail("documents exceed their bound");
documents.set(doc.path, doc.source);
}
const directories = new Set(input.directories);
for (const path of directories) if (!plain2(path)) fail("invalid source directory");
for (const path of Object.keys(files)) if (!plain2(path) || !SHA.test(files[path])) fail("invalid source file receipt");
for (const path of directories) if (!plain(path)) fail("invalid source directory");
for (const path of Object.keys(files)) if (!plain(path) || !SHA.test(files[path])) fail("invalid source file receipt");
const invalid = /* @__PURE__ */ new Set();
const parsed = /* @__PURE__ */ new Map();
const io = {
@@ -14777,7 +14466,7 @@ async function reviewAgentPresets(input) {
}
if (config.roots !== void 0 && !Array.isArray(config.roots)) fail("roots must be a literal list");
for (const root of config.roots ?? []) {
if (!root || Object.keys(root).some((k) => !["path", "trust"].includes(k)) || !plain2(root.path) || !["system", "user"].includes(root.trust)) fail("configured roots must stay inside the admitted package");
if (!root || Object.keys(root).some((k) => !["path", "trust"].includes(k)) || !plain(root.path) || !["system", "user"].includes(root.trust)) fail("configured roots must stay inside the admitted package");
if (!directories.has(root.path)) fail("configured preset root was not admitted");
roots.push({ path: resolve4(base, root.path), trust: root.trust });
}
+1 -14
View File
@@ -18,7 +18,6 @@ var ErrorCode = {
Denied: -32003,
Cancelled: -32800
};
var DSH_SERVICES = ["workspace", "llm", "network", "settings", "catalog", "terminal", "remote"];
var METHODS = [
{ name: "host/initialize", direction: "core_to_host", request: true, params: "InitializeParams", tiers: ["plugin", "builtin"] },
{ name: "host/ping", direction: "core_to_host", request: true, params: "EmptyParams", tiers: ["plugin", "builtin"] },
@@ -43,7 +42,6 @@ var METHODS = [
{ name: "subagent/start", direction: "host_to_core", request: true, params: "SubagentStartParams", tiers: ["plugin", "builtin"] },
{ name: "subagent/result", direction: "host_to_core", request: true, params: "SubagentHandleParams", tiers: ["plugin", "builtin"] },
{ name: "subagent/dispose", direction: "host_to_core", request: true, params: "SubagentHandleParams", tiers: ["plugin", "builtin"] },
{ name: "dsh/broker", direction: "host_to_core", request: true, params: "DshBrokerParams", tiers: ["plugin", "builtin"] },
{ name: "proc/launch", direction: "host_to_core", request: true, params: "ProcLaunchParams", tiers: ["builtin"] },
{ name: "proc/read", direction: "host_to_core", request: true, params: "ProcSessionParams", tiers: ["builtin"] },
{ name: "proc/write", direction: "host_to_core", request: true, params: "ProcWriteParams", tiers: ["builtin"] },
@@ -84,16 +82,6 @@ var SHAPES = {
required: { owner: { ref: "OwnerRef" } },
optional: { entry: { ref: "EntryRef" } }
},
DshBrokerParams: {
strict: true,
required: { owner: { ref: "OwnerRef" }, ticket: "string", service: "string", method: "string", input: "json" },
optional: {}
},
DshBrokerTicketWire: {
strict: true,
required: { service: "string", ticket: "string" },
optional: {}
},
EmptyParams: {
strict: true,
required: {},
@@ -257,7 +245,7 @@ var SHAPES = {
ToolCallParams: {
strict: false,
required: { handle: "uint", call_id: "string", input: "json", deadline_ms: "uint" },
optional: { workspace: "string", ticket: "string", checkpoint_ticket: "string", question_ticket: "string", subagent_ticket: "string", broker_tickets: { items: { ref: "DshBrokerTicketWire" } }, caller_tools: { items: "string" }, session_id: "string", agent_id: "string", origin_turn_id: "string" }
optional: { workspace: "string", ticket: "string", checkpoint_ticket: "string", question_ticket: "string", subagent_ticket: "string", caller_tools: { items: "string" }, session_id: "string", agent_id: "string", origin_turn_id: "string" }
},
UnregisterParams: {
strict: true,
@@ -427,7 +415,6 @@ function validateMessage(value, direction, tier, methods = METHODS) {
return value;
}
export {
DSH_SERVICES,
ErrorCode,
FrameDecoder,
FrameError,
+1 -12
View File
@@ -39,7 +39,6 @@ var METHODS = [
{ name: "subagent/start", direction: "host_to_core", request: true, params: "SubagentStartParams", tiers: ["plugin", "builtin"] },
{ name: "subagent/result", direction: "host_to_core", request: true, params: "SubagentHandleParams", tiers: ["plugin", "builtin"] },
{ name: "subagent/dispose", direction: "host_to_core", request: true, params: "SubagentHandleParams", tiers: ["plugin", "builtin"] },
{ name: "dsh/broker", direction: "host_to_core", request: true, params: "DshBrokerParams", tiers: ["plugin", "builtin"] },
{ name: "proc/launch", direction: "host_to_core", request: true, params: "ProcLaunchParams", tiers: ["builtin"] },
{ name: "proc/read", direction: "host_to_core", request: true, params: "ProcSessionParams", tiers: ["builtin"] },
{ name: "proc/write", direction: "host_to_core", request: true, params: "ProcWriteParams", tiers: ["builtin"] },
@@ -80,16 +79,6 @@ var SHAPES = {
required: { owner: { ref: "OwnerRef" } },
optional: { entry: { ref: "EntryRef" } }
},
DshBrokerParams: {
strict: true,
required: { owner: { ref: "OwnerRef" }, ticket: "string", service: "string", method: "string", input: "json" },
optional: {}
},
DshBrokerTicketWire: {
strict: true,
required: { service: "string", ticket: "string" },
optional: {}
},
EmptyParams: {
strict: true,
required: {},
@@ -253,7 +242,7 @@ var SHAPES = {
ToolCallParams: {
strict: false,
required: { handle: "uint", call_id: "string", input: "json", deadline_ms: "uint" },
optional: { workspace: "string", ticket: "string", checkpoint_ticket: "string", question_ticket: "string", subagent_ticket: "string", broker_tickets: { items: { ref: "DshBrokerTicketWire" } }, caller_tools: { items: "string" }, session_id: "string", agent_id: "string", origin_turn_id: "string" }
optional: { workspace: "string", ticket: "string", checkpoint_ticket: "string", question_ticket: "string", subagent_ticket: "string", caller_tools: { items: "string" }, session_id: "string", agent_id: "string", origin_turn_id: "string" }
},
UnregisterParams: {
strict: true,
@@ -1,432 +0,0 @@
import { readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const root = join(here, '..')
const SOURCES = {
compatibility: join(root, 'src/dsh/compatibility.json'),
hostRoot: join(root, 'src/root.ts'),
shellHooks: join(root, 'src/dsh/shell-hooks.ts'),
seatTable: join(root, '../../app-server/src/runtime_api/plugins.rs'),
catalog: join(root, 'src/dsh/inspect-catalog.json'),
}
const read = (path) => readFileSync(path, 'utf8').replace(/\r\n/g, '\n')
const SERVICES = {
tools: {
summary: 'The tool registry: a plugin adds model-callable tools. The Engine owns calling, approval and results.',
availability: 'always',
methods: [
{ name: 'register', signature: 'register(definition: ToolDefinition): () => void', summary: 'Register one tool built with defineTool from @deepseek-ai/dsh-tools. The definition must stay inside the supported JSON Schema subset (type, oneOf, properties, required, additionalProperties, items, enum, const). A second argument is refused. Returns an idempotent disposer.' },
{ name: 'get', signature: 'get(name: string, agent: Agent): { name: string } | undefined', summary: 'Whether the calling agent has a tool by this name. Answers only inside a live tool call, for that call\'s own agent.' },
],
},
commands: {
summary: 'Slash commands a person types. A handler runs only when the person types the command.',
availability: 'always',
methods: [
{ name: 'register', signature: 'register(definition: { name: string, description: string, argumentHint?: string, handler(call: { args: string, signal: AbortSignal }): CommandResult }): () => void', summary: 'Register one slash command. Names start with a lower case letter, then lower case letters, digits, _ and -, at most 64 characters; at most 64 commands per plugin. A name that clashes with a built-in command gets the alias plugin-<plugin-slug>-<command>, and is refused if that alias is invalid or also taken. A name another plugin already registered is refused, so pick a plugin-specific name. Returns an idempotent disposer.' },
],
},
storage: {
summary: 'Owner-local JSON persistence under the data folder the Engine assigned. It holds no session history and no secrets.',
availability: 'always',
methods: [
{ name: 'get', signature: 'get(key: string): Promise<Json | undefined>', summary: 'Read one stored value.' },
{ name: 'set', signature: 'set(key: string, value: Json): Promise<void>', summary: 'Store one JSON value, within the bounded key, value and owner limits.' },
{ name: 'delete', signature: 'delete(key: string): Promise<void>', summary: 'Remove one stored value.' },
],
},
skills: {
summary: 'Skill roots: reviewed folders of skills added to the Engine\'s skill catalog.',
availability: 'always',
methods: [
{ name: 'registerRoot', signature: 'registerRoot(definition: { path: string }): () => void', summary: 'Add a bundle-relative folder of SKILL.md packages. At most 8 roots per plugin. Absolute paths, links, empty components, . and .. are refused.' },
],
},
sessions: {
summary: 'The session of the calling tool invocation.',
availability: 'tool-invocation',
methods: [
{ name: 'flush', signature: 'flush(session: Session): Promise<boolean>', summary: 'Ask the Engine to persist the committed prefix of the exact session of this tool call. Nothing else on sessions is available.' },
],
},
userQuestions: {
summary: 'Questions put to the person through the Engine\'s own question card.',
availability: 'tool-invocation',
methods: [
{ name: 'ask', signature: 'ask(request: { agent: Agent, questions: Question[], signal?: AbortSignal }): Promise<Answers>', summary: 'Ask the person typed questions during a live root tool call. Timed or continued questions (wait) are not supported.' },
],
},
subagents: {
summary: 'One independent child agent a root tool call may start.',
availability: 'tool-invocation',
methods: [
{ name: 'getProvider', signature: 'getProvider(id: \'spawn\'): Provider', summary: 'Describe the one provider: a fresh child with no inherited conversation.' },
{ name: 'startActivation', signature: 'startActivation(options: { provider: \'spawn\', childId: string, request: { parent: Agent, prompt: TextBlock[], agentOptions?: { model?: string } }, signal?: AbortSignal, delivery?: \'caller\' | \'parent\' }): Promise<{ childId: string, messageId: string, result: Promise<ChildResult>, dispose(): Promise<void> }>', summary: 'Start the child through the Engine\'s approval gate. Resolves to the activation handle { childId, messageId, result, dispose }. Prompts are text only; only the model option is accepted. Needs the live calling agent as parent and is not available inside a child.' },
{ name: 'result', signature: 'activation.result: Promise<{ stopReason: string, output: { type: \'text\', text: string }[], diagnostic?: string }>', summary: 'A getter, not a method: read the property, do not call it. Resolves when the child finishes, with its stop reason and its text output blocks; diagnostic notes dropped non-text blocks.' },
{ name: 'dispose', signature: 'activation.dispose(): Promise<void>', summary: 'Stop that exact child and its own descendants.' },
],
},
agents: {
summary: 'Reserved. The host offers no methods on agents.',
availability: 'none',
methods: [],
},
systemPrompt: {
summary: 'The child agent\'s persona slot, reachable only inside an agent/created listener.',
availability: 'child-agent-hook',
methods: [
{ name: 'section', signature: 'agent.ctx.systemPrompt.section({ name: \'deployment:persona-prefix\', order: agent.ctx.systemPrompt.getSectionOrder(\'DEPLOYMENT_PERSONA_PREFIX\'), text: string }): () => void', summary: 'Set the child\'s persona text, at most 32 KiB, once. name must be the string deployment:persona-prefix (the PERSONA_PREFIX_SECTION value) and order must be what getSectionOrder(\'DEPLOYMENT_PERSONA_PREFIX\') returns, which is 0. Anything else is refused. Called anywhere else it fails. The Engine\'s own system prompt cannot be replaced.' },
],
},
logger: {
summary: 'Cordis logging. Every line becomes a host log notification attributed to the plugin.',
availability: 'always',
cordis: true,
methods: [
{ name: 'logger', signature: 'ctx.logger(name?: string): Logger', summary: 'A named logger with debug, info, warn and error. The host reports error and warn as such and everything else as info.' },
],
},
events: {
summary: 'Cordis event dispatch. Query the host Event provider for the events this host fires.',
availability: 'always',
cordis: true,
methods: [
{ name: 'on', signature: 'ctx.on(name: string, listener: Function, options?: boolean | { prepend?: boolean, global?: boolean }): () => boolean', summary: 'Listen to an event. The host refuses five lifecycle events and limits the options of two (see the Event provider).' },
{ name: 'once', signature: 'ctx.once(name: string, listener: Function, options?: boolean | { prepend?: boolean, global?: boolean }): () => boolean', summary: 'Listen to an event once.' },
{ name: 'emit', signature: 'ctx.emit(name: string, ...args: any[]): void', summary: 'Dispatch an event to its listeners.' },
],
},
reflect: {
summary: 'Cordis service reflection. A plugin may provide its own services but not the Engine\'s.',
availability: 'always',
cordis: true,
methods: [
{ name: 'provide', signature: 'ctx.reflect.provide(name: string, value?: any): () => void', summary: 'Provide a service under a name. Names in refusedServices are refused: the Engine owns them.' },
{ name: 'get', signature: 'ctx.reflect.get(name: string, strict?: boolean): any', summary: 'Read a provided service.' },
],
},
registry: {
summary: 'Cordis plugin registry.',
availability: 'always',
cordis: true,
methods: [
{ name: 'get', signature: 'ctx.registry.get(plugin: Plugin): Runtime | undefined', summary: 'Look up the runtime record of a plugin.' },
{ name: 'resolve', signature: 'ctx.registry.resolve(plugin: Plugin): Function | undefined', summary: 'Resolve a plugin shape to its callback.' },
],
},
prompt: {
summary: 'Attributed sections of the Engine\'s runtime prompt. A plugin cannot replace the system prompt.',
availability: 'always',
methods: [
{ name: 'registerSection', signature: 'registerSection(definition: { id: string, text: string, interpolate?: \'model-cwd\' }): () => void', summary: 'Contribute a plain-text section of at most 4 KiB; at most 128 sections per plugin. The id is lower case letters, digits, _ and -, starts with a letter, at most 64 characters. With interpolate set, only {{model}} and {{cwd}} are expanded.' },
],
},
avatars: {
summary: 'Avatar packs for the terminal.',
availability: 'always',
methods: [
{ name: 'registerPack', signature: 'registerPack(definition: { path: string }): () => void', summary: 'Register a reviewed bundle-relative avatar pack: a path ending in .json, at most 4 packs per plugin.' },
],
},
mcp: {
summary: 'Proposals of MCP servers. The Engine owns connection, credentials and tool calls.',
availability: 'native-review',
methods: [
{ name: 'registerServer', signature: 'registerServer(definition: { serverName: string, server: Record<string, unknown> }): () => void', summary: 'Propose one server. serverName is a letter or digit followed by up to 31 letters, digits, _ or -. headers and env must stay empty and the url may carry no credentials, query or fragment. At most 64 servers per plugin; at most 64 KiB per definition.' },
],
},
shellHooks: {
summary: 'Claude Code and Codex style command hooks, run by the Engine.',
availability: 'native-review',
methods: [
{ name: 'register', signature: 'register(definition: { dialect: \'claude-code\' | \'codex\', point: string, matcher?: string, hook: { event: string, command: string, timeout_secs: number, background: false, continue_on_error: false, name: string } }): () => void', summary: 'Register one command hook for a reviewed native plugin. Forced continuation, observer steering, non-command and asynchronous hooks are not supported.' },
],
},
remote: {
summary: 'Remote pairing, served by the Engine.',
availability: 'review-grant',
methods: [
{ name: 'status', signature: 'status(): Promise<Status>', summary: 'Whether remote access is on.' },
{ name: 'pair', signature: 'pair(options?: { label?: string }): Promise<Pairing>', summary: 'Start a pairing.' },
{ name: 'clients', signature: 'clients(): Promise<Client[]>', summary: 'List paired clients.' },
{ name: 'revoke', signature: 'revoke(id: string): Promise<void>', summary: 'Revoke one grant by the id pair returned.' },
],
},
}
const AVAILABILITY = {
always: 'Available to every plugin that injects it.',
'tool-invocation': 'Answers only inside a live tool call of the plugin.',
'child-agent-hook': 'Answers only inside an agent/created listener, on the child agent.',
'native-review': 'Available to a reviewed native plugin.',
'review-grant': 'Served by the Engine only when the plugin\'s review granted it.',
none: 'No methods.',
}
const EVENTS_SUPPORTED = [
{
name: 'tools/pre-execute',
status: 'supported',
mode: 'ordered listeners, native hooks first, then plugin listeners in registration order',
signature: 'ctx.on(\'tools/pre-execute\', async (exec: { name: string, callId: string, arguments: object, signal: AbortSignal, workspace: string, mode: string, model: string }, next: () => Promise<Abstention>) => Verdict | undefined)',
summary: 'Programmable tool admission for a reviewed native plugin. The frozen call view has no session, agent, tool or approval handle. Return { kind: \'deny\', reason }, { kind: \'ask\', reason? }, { kind: \'revise\', input }, { kind: \'annotate\', text } or { kind: \'abstain\' }; undefined abstains. A malformed answer, error or timeout fails the call closed. The listener batch has a five second deadline.',
options: 'prepend and global are refused.',
},
{
name: 'agent/created',
status: 'supported',
mode: 'listeners of the owning plugin only',
signature: 'ctx.on(\'agent/created\', async ({ agent }: { agent: { id: string, ctx: { systemPrompt: { getSectionOrder(name), section(section) }, tools: { restrict(filter: { deny: string[] }) } } } }) => void)',
summary: 'Fires for a child agent that this plugin\'s own subagents.startActivation creates, before the child starts. The listener may set the child\'s persona and deny tools to it; the window closes when the listeners return.',
options: 'global is refused.',
},
]
const REFUSED_EVENT_REASON = 'Not projected by this host: no core projection exists, so a listener would never fire.'
const ROW_PACKAGES = {
'@deepseek-ai/dsh-mcp-client': {
summary: 'An MCP server row. The Engine proposes the server and owns the connection.',
schema: {
type: 'object',
additionalProperties: false,
required: ['transport', 'serverName'],
properties: {
transport: { type: 'string', enum: ['stdio', 'streamable-http', 'sse'] },
serverName: { type: 'string', pattern: '^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$' },
command: { type: 'string', description: 'stdio only: the program to run.' },
args: { type: 'array', items: { type: 'string' }, description: 'stdio only.' },
env: { type: 'object', maxProperties: 0, description: 'Must be empty or absent: credentials stay with the Engine.' },
cwd: { type: 'string', description: 'stdio only: a bundle-relative directory, no .. components.' },
url: { type: 'string', description: 'streamable-http and sse: the endpoint, with no credentials, query or fragment.' },
headers: { type: 'object', maxProperties: 0, description: 'Must be empty or absent: credentials stay with the Engine.' },
toolCallTimeoutMs: { type: 'integer', minimum: 1000, maximum: 86400000, multipleOf: 1000 },
failOnStartupError: { type: 'boolean', const: false, description: 'Only false: the Engine connects lazily and reports failures through /mcp.' },
},
},
limits: ['stdio rows name a command; streamable-http and sse rows name a url.', 'Reconnect and instruction bounds belong to the Engine and are not configurable here.'],
example: { transport: 'stdio', serverName: 'docs', command: 'node', args: ['server.js'], cwd: '.' },
},
'@deepseek-ai/dsh-skill-filesystem': {
summary: 'A skill folder row, limited to reviewed roots inside the bundle.',
schema: {
type: 'object',
additionalProperties: false,
required: ['includeDefaultRoots', 'watch', 'customSkillDirs'],
properties: {
providerName: { type: 'string', maxLength: 64 },
includeDefaultRoots: { type: 'boolean', const: false, description: 'Must be false: ambient roots are not read.' },
watch: { type: 'boolean', const: false, description: 'Must be false: there is no file watcher.' },
customSkillDirs: { type: 'array', minItems: 1, maxItems: 8, items: { type: 'string' }, description: 'Bundle-relative skill roots, no duplicates.' },
},
},
limits: ['Both includeDefaultRoots and watch must be written out as false.'],
example: { includeDefaultRoots: false, watch: false, customSkillDirs: ['skills'] },
},
'@deepseek-ai/dsh-hooks-claude-code': {
summary: 'Claude Code style command hooks read from a reviewed file in the bundle.',
schema: {
type: 'object',
additionalProperties: true,
required: ['configPath'],
properties: {
configPath: { type: 'string', description: 'A regular file inside the bundle, at most 1 MiB, unchanged since review.' },
pluginRoot: { type: 'string', description: 'Absent, ".", or this reviewed bundle root.' },
defaultTimeoutMs: { type: 'integer', minimum: 1000, maximum: 86400000, multipleOf: 1000, description: 'Whole seconds, used when a hook sets none; default 600000.' },
},
},
limits: ['projectDir is refused: each process uses the current workspace.', 'Only command hooks run; non-command and asynchronous hooks fail the row.', 'At most 128 commands per row.'],
example: { configPath: 'hooks/hooks.json' },
},
'@deepseek-ai/dsh-hooks-codex': {
summary: 'Codex style command hooks read from a reviewed file in the bundle.',
schema: {
type: 'object',
additionalProperties: true,
required: ['configPath'],
properties: {
configPath: { type: 'string', description: 'A regular file inside the bundle, at most 1 MiB, unchanged since review.' },
pluginRoot: { type: 'string', description: 'Absent, ".", or this reviewed bundle root.' },
defaultTimeoutMs: { type: 'integer', minimum: 1000, maximum: 86400000, multipleOf: 1000, description: 'Whole seconds, used when a hook sets none; default 600000.' },
},
},
limits: ['projectDir is refused: each process uses the current workspace.', 'Only command hooks run; non-command and asynchronous hooks fail the row.', 'At most 128 commands per row.'],
example: { configPath: 'hooks/hooks.json' },
},
'@deepseek-ai/dsh-persona': {
summary: 'Text added before and after the Engine\'s own prompt for this plugin\'s entry.',
schema: {
type: 'object',
additionalProperties: false,
required: ['prefix'],
properties: {
prefix: { type: 'string', description: 'At most 4096 UTF-8 bytes, no control characters. Only {{model}} and {{cwd}} are expanded.' },
suffix: { type: 'string', description: 'Same limits as prefix.' },
complete: { type: 'boolean', const: false, description: 'Replacing the whole prompt belongs to the Engine.' },
includeRuntimeContext: { type: 'boolean', const: true, description: 'Suppressing the runtime context belongs to the Engine.' },
},
},
limits: ['Needs an exact Engine-selected entry scope.'],
example: { prefix: 'Answer in short sentences.' },
},
}
const THEME = {
tokens: [],
colorSchemes: ['light', 'dark'],
scheme: 'The frame sets data-theme and color-scheme on its document to the app\'s current scheme and follows changes.',
api: [
{ name: 'ctx.theme.getTheme', signature: 'getTheme(): { active: { colorScheme: \'light\' | \'dark\' } }', summary: 'The scheme in use now.' },
{ name: 'ctx.theme.overrideTokens', signature: 'overrideTokens(source: string, tokens: Record<string, { light: string, dark: string }>): () => void', summary: 'Set custom properties on the frame\'s document for each scheme. source is at most 256 characters; each name starts with -- and is at most 128 characters; each value is at most 512 characters. Returns a disposer.' },
],
notes: [
'The frame defines no named design tokens of its own. There are no --dsw-* tokens to read: a plugin that wants tokens defines them with overrideTokens and uses them in its own styles.',
'The frame\'s background is transparent and its margin is zero, so the plugin sits on the app\'s own surface.',
],
}
const SEAT_NOTES = {
'customize.plugins.detail': { drawn: true, where: 'The plugin\'s own page under Customize, Plugins.' },
'conversation.composer.dock': { drawn: false, where: 'Under the composer. The desktop app does not place it yet.' },
'conversation.chat.node': { drawn: false, where: 'Inside the conversation. The desktop app does not place it yet.' },
'workpane.panel': { drawn: false, where: 'The work pane. The desktop app does not place it yet.' },
'sidebar.section': { drawn: false, where: 'The sidebar. The desktop app does not place it yet.' },
'command.row': { drawn: false, where: 'The command list. The desktop app does not place it yet.' },
}
function between(text, open, close, what) {
const start = text.indexOf(open)
if (start < 0) throw new Error(`${what}: cannot find ${open}`)
const end = text.indexOf(close, start + open.length)
if (end < 0) throw new Error(`${what}: cannot find the end of ${open}`)
return text.slice(start + open.length, end)
}
export function parseSeatTable(source) {
const text = source.replace(/\r\n/g, '\n')
const constants = Object.fromEntries([...text.matchAll(/const ([A-Z_]+): &str = "([^"]+)";/g)].map((m) => [m[1], m[2]]))
const resolve = (literal, name) => literal !== undefined ? literal : constants[name]
const seatBlock = between(text, 'const PLUGIN_UI_SEATS: [&str; ', '];', 'seat list')
const declaredSeats = Number(seatBlock.slice(0, seatBlock.indexOf(']')))
const seatBody = seatBlock.slice(seatBlock.indexOf('= [') + 3)
const seats = [...seatBody.matchAll(/"([^"]+)"|([A-Z_]+)/g)].map((m) => resolve(m[1], m[2]))
if (seats.length !== declaredSeats || seats.some((seat) => seat === undefined)) throw new Error('the seat list does not match its declared length')
const tableBlock = between(text, 'const DSH_SEAT_TABLE: [(&str, DshSeat); ', '];\n', 'slot table')
const declaredSlots = Number(tableBlock.slice(0, tableBlock.indexOf(']')))
const tableBody = tableBlock.slice(tableBlock.indexOf('= [') + 3)
const slots = [...tableBody.matchAll(/\(\s*"([^"]+)",\s*DshSeat::(Seat|Unsupported)\(\s*(?:"([^"]*)"|([A-Z_]+))\s*\)\s*,?\s*\)/g)].map((m) => {
const value = resolve(m[3], m[4])
return m[2] === 'Seat' ? { slot: m[1], seat: value, supported: true } : { slot: m[1], seat: null, supported: false, reason: value }
})
if (slots.length !== declaredSlots) throw new Error(`the slot table declares ${declaredSlots} rows and ${slots.length} were read`)
for (const slot of slots) if (slot.supported && !seats.includes(slot.seat)) throw new Error(`slot ${slot.slot} maps to ${slot.seat}, which is not a seat`)
return { seats, slots }
}
export function parseRefusedEvents(source) {
const text = source.replace(/\r\n/g, '\n')
const body = between(text, 'const unsupportedDshLifecycle = new Set([', '])', 'refused events')
return [...body.matchAll(/'([^']+)'/g)].map((m) => m[1])
}
export function parseHookEvents(source) {
const text = source.replace(/\r\n/g, '\n')
const body = between(text, 'const EVENTS:Record<string,string>={', '}', 'hook events')
return [...body.matchAll(/([A-Za-z]+):'([a-z_]+)'/g)].map((m) => ({ event: m[1], point: m[2] }))
}
export function buildCatalog(paths = SOURCES) {
const compatibility = JSON.parse(read(paths.compatibility))
const provided = Object.entries(compatibility.provided_services).flatMap(([group, names]) => names.map((name) => ({ group, name })))
const known = new Set(Object.keys(SERVICES))
const missing = provided.filter(({ name }) => !known.has(name)).map(({ name }) => name)
if (missing.length) throw new Error(`compatibility.json provides services with no entry in the method table: ${missing.join(', ')}`)
const extra = [...known].filter((name) => !provided.some((entry) => entry.name === name))
if (extra.length) throw new Error(`the method table names services the host does not provide: ${extra.join(', ')}`)
const services = provided.map(({ group, name }) => {
const entry = SERVICES[name]
return {
key: name,
group,
summary: entry.summary,
availability: entry.availability,
availabilityText: AVAILABILITY[entry.availability],
methods: entry.methods,
}
})
const refusedEvents = parseRefusedEvents(read(paths.hostRoot))
const hookEvents = parseHookEvents(read(paths.shellHooks))
const events = [
...EVENTS_SUPPORTED,
...refusedEvents.map((name) => ({ name, status: 'refused', summary: REFUSED_EVENT_REASON })),
]
const rowPackages = Object.keys(compatibility.row_bridges)
const unknownRows = rowPackages.filter((name) => !ROW_PACKAGES[name])
const staleRows = Object.keys(ROW_PACKAGES).filter((name) => !rowPackages.includes(name))
if (unknownRows.length || staleRows.length) throw new Error(`row packages differ from compatibility.json: missing ${unknownRows.join(', ')}; stale ${staleRows.join(', ')}`)
const rows = rowPackages.map((name) => ({
id: `row:${name}`,
name,
bridge: compatibility.row_bridges[name],
summary: ROW_PACKAGES[name].summary,
limits: ROW_PACKAGES[name].limits,
example: ROW_PACKAGES[name].example,
...(name.includes('hooks-') ? { hookEvents } : {}),
schema: { $schema: 'https://json-schema.org/draft/2020-12/schema', title: name, ...ROW_PACKAGES[name].schema },
}))
const table = parseSeatTable(read(paths.seatTable))
const unknownSeatNotes = table.seats.filter((seat) => !SEAT_NOTES[seat])
const staleSeatNotes = Object.keys(SEAT_NOTES).filter((seat) => !table.seats.includes(seat))
if (unknownSeatNotes.length || staleSeatNotes.length) throw new Error(`seat notes differ from the Engine seat list: missing ${unknownSeatNotes.join(', ')}; stale ${staleSeatNotes.join(', ')}`)
const seats = table.seats.map((seat) => ({ seat, drawn: SEAT_NOTES[seat].drawn, where: SEAT_NOTES[seat].where }))
return {
version: 1,
targetDshVersion: compatibility.target_dsh_version,
host: {
services,
refusedServices: compatibility.refused_services,
events,
cordisInternalEvents: 'Cordis fires its own internal/* lifecycle events. They are not part of this host\'s supported contract and are not listed.',
config: rows,
},
client: {
seats,
slots: table.slots,
theme: THEME,
},
}
}
export function renderCatalog(catalog) {
return `${JSON.stringify(catalog, null, 2)}\n`
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const text = renderCatalog(buildCatalog())
if (process.argv.includes('--check')) {
const current = existsOrEmpty(SOURCES.catalog)
if (current !== text) {
process.stderr.write('inspect-catalog.json is out of date: run node scripts/gen-inspect-catalog.mjs\n')
process.exit(1)
}
} else {
writeFileSync(SOURCES.catalog, text)
}
}
function existsOrEmpty(path) {
try {
return read(path)
} catch {
return ''
}
}
@@ -1,24 +0,0 @@
import type { Service } from '@deepseek-ai/cordis'
import type { DshService } from '../protocol.generated.ts'
import type { OwnerRecord, ToolInvocation } from '../root.ts'
import type { RpcPeer } from '../rpc.ts'
import type { HostTier } from '../tier.ts'
import { sessionsAdapter, systemPromptAdapter } from './session-prompt.ts'
import { DSH_AGENT_ADAPTERS } from './agents.ts'
import { remoteAdapter } from './remote.ts'
export interface AdapterHost {
readonly tier: HostTier
readonly rpc: RpcPeer
ownerOf(ctx: unknown): OwnerRecord | undefined
liveInvocation(ctx: unknown): ToolInvocation | undefined
broker(ctx: unknown, service: DshService, method: string, input: unknown): Promise<unknown>
log(level: 'info' | 'warn' | 'error', message: string, owner?: OwnerRecord): void
}
export interface DshAdapter {
readonly service: string
define(host: AdapterHost): new (ctx: any) => Service
}
export const DSH_ADAPTERS: readonly DshAdapter[] = [sessionsAdapter, systemPromptAdapter, ...DSH_AGENT_ADAPTERS, remoteAdapter]
@@ -1,154 +0,0 @@
import { Service } from '@deepseek-ai/cordis'
import { ErrorCode } from '../protocol.ts'
import { RpcError } from '../rpc.ts'
import { PERSONA_PREFIX_SECTION } from './dsh-message-compat.js'
import type { AdapterHost, DshAdapter } from './adapters.ts'
const SPAWN_PROVIDER = Object.freeze({
name: 'spawn',
inheritsParentContext: false,
capabilities: Object.freeze({ persona: true, toolFilter: true, agentOptions: true }),
})
const PERSONA_ORDER = 0
function plain(value: unknown, allowed: string[], what: string): Record<string, unknown> {
if (value === null || typeof value !== 'object' || Array.isArray(value)
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new RpcError(ErrorCode.InvalidParams, `expected a plain ${what} object`)
const result: Record<string, unknown> = Object.create(null)
for (const key of Reflect.ownKeys(value)) {
const descriptor = Object.getOwnPropertyDescriptor(value, key)!
if (typeof key !== 'string' || !allowed.includes(key) || !('value' in descriptor)) throw new RpcError(ErrorCode.NotAvailable, `unsupported ${what} property ${String(key)}`)
if (descriptor.value !== undefined) result[key] = descriptor.value
}
return result
}
function defineSubagents(host: AdapterHost): new (ctx: any) => Service {
class SubagentsShim extends Service {
constructor(ctx: any) { super(ctx, 'subagents') }
getProvider(name: unknown) { return name === 'spawn' ? SPAWN_PROVIDER : undefined }
async startActivation(request: any) {
const owner = host.ownerOf(this.ctx)
const input = plain(request, ['provider', 'label', 'childId', 'request', 'signal', 'delivery'], 'activation')
if (input.provider !== 'spawn') throw new RpcError(ErrorCode.NotAvailable, 'only the spawn provider is available')
const spawn = plain(input.request, ['parent', 'prompt', 'agentOptions'], 'spawn request')
const options = spawn.agentOptions === undefined ? {} : plain(spawn.agentOptions, ['model'], 'agentOptions')
if (options.model !== undefined && typeof options.model !== 'string') throw new RpcError(ErrorCode.InvalidParams, 'agentOptions.model must be a string')
const delivery = input.delivery === undefined ? 'parent' : input.delivery
if (delivery !== 'caller' && delivery !== 'parent') throw new RpcError(ErrorCode.InvalidParams, 'delivery must be caller or parent')
const childId = input.childId
if (typeof childId !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/.test(childId)) throw new RpcError(ErrorCode.InvalidParams, 'childId must be 1-128 letters, digits, or _.:-')
if (!Array.isArray(spawn.prompt) || spawn.prompt.length === 0) throw new RpcError(ErrorCode.InvalidParams, 'prompt must be a non-empty content array')
const prompt = spawn.prompt.map((block: unknown) => {
const item = plain(block, ['type', 'text'], 'prompt block')
if (item.type !== 'text' || typeof item.text !== 'string') throw new RpcError(ErrorCode.NotAvailable, 'only text prompt blocks are supported')
return item.text
}).join('')
if (input.signal !== undefined && !(input.signal instanceof AbortSignal)) throw new RpcError(ErrorCode.InvalidParams, 'signal must be an AbortSignal')
const invocation = host.liveInvocation(this.ctx)
if (!invocation || invocation.agent === undefined || spawn.parent !== invocation.agent) {
throw new RpcError(ErrorCode.NotAvailable, 'startActivation requires the exact live calling agent as parent')
}
if (invocation.owner !== owner) throw new RpcError(ErrorCode.NotAvailable, 'subagents service owner is no longer current')
if (invocation.delegated || invocation.subagentTicket === undefined) throw new RpcError(ErrorCode.NotAvailable, 'child agents are only available to a root tool invocation')
const signal = input.signal === undefined ? invocation.signal : AbortSignal.any([invocation.signal, input.signal as AbortSignal])
signal.throwIfAborted()
let persona: string | undefined
const denied = new Set<string>()
let open = true
const sealed = () => { if (!open) throw new RpcError(ErrorCode.NotAvailable, 'the child creation window has closed') }
const child = Object.freeze({
id: childId,
ctx: Object.freeze({
systemPrompt: Object.freeze({
getSectionOrder(name: unknown) {
sealed()
if (name !== 'DEPLOYMENT_PERSONA_PREFIX') throw new RpcError(ErrorCode.NotAvailable, 'only the deployment persona slot is available')
return PERSONA_ORDER
},
section(section: unknown) {
sealed()
const value = plain(section, ['name', 'order', 'text'], 'system prompt section')
if (value.name !== PERSONA_PREFIX_SECTION || value.order !== PERSONA_ORDER || typeof value.text !== 'string') {
throw new RpcError(ErrorCode.NotAvailable, 'only the child deployment persona section is supported')
}
if (persona !== undefined) throw new RpcError(ErrorCode.InvalidParams, 'the child persona is already set')
if (Buffer.byteLength(value.text) > 32 * 1024) throw new RpcError(ErrorCode.InvalidParams, 'child persona exceeds 32768 bytes')
persona = value.text
return () => undefined
},
}),
tools: Object.freeze({
restrict(filter: unknown) {
sealed()
const value = plain(filter, ['deny'], 'tool filter')
if (!Array.isArray(value.deny) || value.deny.some(name => typeof name !== 'string' || name === '')) throw new RpcError(ErrorCode.InvalidParams, 'deny must be a list of tool names')
for (const name of value.deny as string[]) denied.add(name)
return () => undefined
},
}),
}),
})
const listeners = (((this.ctx as any).root?.events?._hooks?.['agent/created']) ?? [])
.filter((hook: any) => !hook.global && hook.ctx !== undefined && host.ownerOf(hook.ctx) === owner)
.map((hook: any) => hook.callback)
try {
await Promise.all(listeners.map(async (callback: Function) => callback({ agent: child })))
} finally {
open = false
}
signal.throwIfAborted()
const call = invocation
const rpc = (method: string, params: Record<string, unknown>, abort: AbortSignal) =>
host.rpc.request<any>(method, { owner: call.owner.ref, ticket: call.subagentTicket, child_id: childId, ...params }, abort)
const started = await rpc('subagent/start', {
prompt,
...(options.model === undefined ? {} : { model: options.model }),
...(persona === undefined ? {} : { persona }),
denied_tools: [...denied],
delivery,
}, signal)
if (started === null || typeof started !== 'object' || started.child_id !== childId || typeof started.message_id !== 'string') {
throw new RpcError(ErrorCode.Internal, 'invalid child activation receipt')
}
let result: Promise<unknown> | undefined
let disposed: Promise<void> | undefined
return Object.freeze({
childId,
messageId: started.message_id,
get result() {
result ??= rpc('subagent/result', {}, call.signal).then((value: any) => {
if (value === null || typeof value !== 'object' || typeof value.stop_reason !== 'string' || !Array.isArray(value.output)) {
throw new RpcError(ErrorCode.Internal, 'invalid child result receipt')
}
return Object.freeze({
stopReason: value.stop_reason,
output: Object.freeze(value.output.map((block: any) => Object.freeze({ type: 'text', text: String(block.text) }))),
...(value.omitted_blocks > 0 ? { diagnostic: `${value.omitted_blocks} non-text output block(s) are not supported` } : {}),
})
})
return result
},
dispose() {
disposed ??= rpc('subagent/dispose', {}, call.signal).then(() => undefined)
return disposed
},
})
}
}
Object.freeze(SubagentsShim.prototype)
return SubagentsShim
}
function defineAgents(): new (ctx: any) => Service {
class AgentsShim extends Service {
constructor(ctx: any) { super(ctx, 'agents') }
}
Object.freeze(AgentsShim.prototype)
return AgentsShim
}
export const DSH_AGENT_ADAPTERS: readonly DshAdapter[] = Object.freeze([
{ service: 'subagents', define: defineSubagents },
{ service: 'agents', define: defineAgents },
])
@@ -23,8 +23,7 @@
"prompt",
"avatars",
"mcp",
"shellHooks",
"remote"
"shellHooks"
]
},
"refused_services": [
@@ -1,918 +0,0 @@
{
"version": 1,
"targetDshVersion": "0.2.2-rc.1",
"host": {
"services": [
{
"key": "tools",
"group": "dsh",
"summary": "The tool registry: a plugin adds model-callable tools. The Engine owns calling, approval and results.",
"availability": "always",
"availabilityText": "Available to every plugin that injects it.",
"methods": [
{
"name": "register",
"signature": "register(definition: ToolDefinition): () => void",
"summary": "Register one tool built with defineTool from @deepseek-ai/dsh-tools. The definition must stay inside the supported JSON Schema subset (type, oneOf, properties, required, additionalProperties, items, enum, const). A second argument is refused. Returns an idempotent disposer."
},
{
"name": "get",
"signature": "get(name: string, agent: Agent): { name: string } | undefined",
"summary": "Whether the calling agent has a tool by this name. Answers only inside a live tool call, for that call's own agent."
}
]
},
{
"key": "commands",
"group": "dsh",
"summary": "Slash commands a person types. A handler runs only when the person types the command.",
"availability": "always",
"availabilityText": "Available to every plugin that injects it.",
"methods": [
{
"name": "register",
"signature": "register(definition: { name: string, description: string, argumentHint?: string, handler(call: { args: string, signal: AbortSignal }): CommandResult }): () => void",
"summary": "Register one slash command. Names start with a lower case letter, then lower case letters, digits, _ and -, at most 64 characters; at most 64 commands per plugin. A name that clashes with a built-in command gets the alias plugin-<plugin-slug>-<command>, and is refused if that alias is invalid or also taken. A name another plugin already registered is refused, so pick a plugin-specific name. Returns an idempotent disposer."
}
]
},
{
"key": "storage",
"group": "dsh",
"summary": "Owner-local JSON persistence under the data folder the Engine assigned. It holds no session history and no secrets.",
"availability": "always",
"availabilityText": "Available to every plugin that injects it.",
"methods": [
{
"name": "get",
"signature": "get(key: string): Promise<Json | undefined>",
"summary": "Read one stored value."
},
{
"name": "set",
"signature": "set(key: string, value: Json): Promise<void>",
"summary": "Store one JSON value, within the bounded key, value and owner limits."
},
{
"name": "delete",
"signature": "delete(key: string): Promise<void>",
"summary": "Remove one stored value."
}
]
},
{
"key": "skills",
"group": "dsh",
"summary": "Skill roots: reviewed folders of skills added to the Engine's skill catalog.",
"availability": "always",
"availabilityText": "Available to every plugin that injects it.",
"methods": [
{
"name": "registerRoot",
"signature": "registerRoot(definition: { path: string }): () => void",
"summary": "Add a bundle-relative folder of SKILL.md packages. At most 8 roots per plugin. Absolute paths, links, empty components, . and .. are refused."
}
]
},
{
"key": "sessions",
"group": "dsh",
"summary": "The session of the calling tool invocation.",
"availability": "tool-invocation",
"availabilityText": "Answers only inside a live tool call of the plugin.",
"methods": [
{
"name": "flush",
"signature": "flush(session: Session): Promise<boolean>",
"summary": "Ask the Engine to persist the committed prefix of the exact session of this tool call. Nothing else on sessions is available."
}
]
},
{
"key": "userQuestions",
"group": "dsh",
"summary": "Questions put to the person through the Engine's own question card.",
"availability": "tool-invocation",
"availabilityText": "Answers only inside a live tool call of the plugin.",
"methods": [
{
"name": "ask",
"signature": "ask(request: { agent: Agent, questions: Question[], signal?: AbortSignal }): Promise<Answers>",
"summary": "Ask the person typed questions during a live root tool call. Timed or continued questions (wait) are not supported."
}
]
},
{
"key": "subagents",
"group": "dsh",
"summary": "One independent child agent a root tool call may start.",
"availability": "tool-invocation",
"availabilityText": "Answers only inside a live tool call of the plugin.",
"methods": [
{
"name": "getProvider",
"signature": "getProvider(id: 'spawn'): Provider",
"summary": "Describe the one provider: a fresh child with no inherited conversation."
},
{
"name": "startActivation",
"signature": "startActivation(options: { provider: 'spawn', childId: string, request: { parent: Agent, prompt: TextBlock[], agentOptions?: { model?: string } }, signal?: AbortSignal, delivery?: 'caller' | 'parent' }): Promise<{ childId: string, messageId: string, result: Promise<ChildResult>, dispose(): Promise<void> }>",
"summary": "Start the child through the Engine's approval gate. Resolves to the activation handle { childId, messageId, result, dispose }. Prompts are text only; only the model option is accepted. Needs the live calling agent as parent and is not available inside a child."
},
{
"name": "result",
"signature": "activation.result: Promise<{ stopReason: string, output: { type: 'text', text: string }[], diagnostic?: string }>",
"summary": "A getter, not a method: read the property, do not call it. Resolves when the child finishes, with its stop reason and its text output blocks; diagnostic notes dropped non-text blocks."
},
{
"name": "dispose",
"signature": "activation.dispose(): Promise<void>",
"summary": "Stop that exact child and its own descendants."
}
]
},
{
"key": "agents",
"group": "dsh",
"summary": "Reserved. The host offers no methods on agents.",
"availability": "none",
"availabilityText": "No methods.",
"methods": []
},
{
"key": "systemPrompt",
"group": "dsh",
"summary": "The child agent's persona slot, reachable only inside an agent/created listener.",
"availability": "child-agent-hook",
"availabilityText": "Answers only inside an agent/created listener, on the child agent.",
"methods": [
{
"name": "section",
"signature": "agent.ctx.systemPrompt.section({ name: 'deployment:persona-prefix', order: agent.ctx.systemPrompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX'), text: string }): () => void",
"summary": "Set the child's persona text, at most 32 KiB, once. name must be the string deployment:persona-prefix (the PERSONA_PREFIX_SECTION value) and order must be what getSectionOrder('DEPLOYMENT_PERSONA_PREFIX') returns, which is 0. Anything else is refused. Called anywhere else it fails. The Engine's own system prompt cannot be replaced."
}
]
},
{
"key": "logger",
"group": "cordis",
"summary": "Cordis logging. Every line becomes a host log notification attributed to the plugin.",
"availability": "always",
"availabilityText": "Available to every plugin that injects it.",
"methods": [
{
"name": "logger",
"signature": "ctx.logger(name?: string): Logger",
"summary": "A named logger with debug, info, warn and error. The host reports error and warn as such and everything else as info."
}
]
},
{
"key": "events",
"group": "cordis",
"summary": "Cordis event dispatch. Query the host Event provider for the events this host fires.",
"availability": "always",
"availabilityText": "Available to every plugin that injects it.",
"methods": [
{
"name": "on",
"signature": "ctx.on(name: string, listener: Function, options?: boolean | { prepend?: boolean, global?: boolean }): () => boolean",
"summary": "Listen to an event. The host refuses five lifecycle events and limits the options of two (see the Event provider)."
},
{
"name": "once",
"signature": "ctx.once(name: string, listener: Function, options?: boolean | { prepend?: boolean, global?: boolean }): () => boolean",
"summary": "Listen to an event once."
},
{
"name": "emit",
"signature": "ctx.emit(name: string, ...args: any[]): void",
"summary": "Dispatch an event to its listeners."
}
]
},
{
"key": "reflect",
"group": "cordis",
"summary": "Cordis service reflection. A plugin may provide its own services but not the Engine's.",
"availability": "always",
"availabilityText": "Available to every plugin that injects it.",
"methods": [
{
"name": "provide",
"signature": "ctx.reflect.provide(name: string, value?: any): () => void",
"summary": "Provide a service under a name. Names in refusedServices are refused: the Engine owns them."
},
{
"name": "get",
"signature": "ctx.reflect.get(name: string, strict?: boolean): any",
"summary": "Read a provided service."
}
]
},
{
"key": "registry",
"group": "cordis",
"summary": "Cordis plugin registry.",
"availability": "always",
"availabilityText": "Available to every plugin that injects it.",
"methods": [
{
"name": "get",
"signature": "ctx.registry.get(plugin: Plugin): Runtime | undefined",
"summary": "Look up the runtime record of a plugin."
},
{
"name": "resolve",
"signature": "ctx.registry.resolve(plugin: Plugin): Function | undefined",
"summary": "Resolve a plugin shape to its callback."
}
]
},
{
"key": "prompt",
"group": "codewhale",
"summary": "Attributed sections of the Engine's runtime prompt. A plugin cannot replace the system prompt.",
"availability": "always",
"availabilityText": "Available to every plugin that injects it.",
"methods": [
{
"name": "registerSection",
"signature": "registerSection(definition: { id: string, text: string, interpolate?: 'model-cwd' }): () => void",
"summary": "Contribute a plain-text section of at most 4 KiB; at most 128 sections per plugin. The id is lower case letters, digits, _ and -, starts with a letter, at most 64 characters. With interpolate set, only {{model}} and {{cwd}} are expanded."
}
]
},
{
"key": "avatars",
"group": "codewhale",
"summary": "Avatar packs for the terminal.",
"availability": "always",
"availabilityText": "Available to every plugin that injects it.",
"methods": [
{
"name": "registerPack",
"signature": "registerPack(definition: { path: string }): () => void",
"summary": "Register a reviewed bundle-relative avatar pack: a path ending in .json, at most 4 packs per plugin."
}
]
},
{
"key": "mcp",
"group": "codewhale",
"summary": "Proposals of MCP servers. The Engine owns connection, credentials and tool calls.",
"availability": "native-review",
"availabilityText": "Available to a reviewed native plugin.",
"methods": [
{
"name": "registerServer",
"signature": "registerServer(definition: { serverName: string, server: Record<string, unknown> }): () => void",
"summary": "Propose one server. serverName is a letter or digit followed by up to 31 letters, digits, _ or -. headers and env must stay empty and the url may carry no credentials, query or fragment. At most 64 servers per plugin; at most 64 KiB per definition."
}
]
},
{
"key": "shellHooks",
"group": "codewhale",
"summary": "Claude Code and Codex style command hooks, run by the Engine.",
"availability": "native-review",
"availabilityText": "Available to a reviewed native plugin.",
"methods": [
{
"name": "register",
"signature": "register(definition: { dialect: 'claude-code' | 'codex', point: string, matcher?: string, hook: { event: string, command: string, timeout_secs: number, background: false, continue_on_error: false, name: string } }): () => void",
"summary": "Register one command hook for a reviewed native plugin. Forced continuation, observer steering, non-command and asynchronous hooks are not supported."
}
]
},
{
"key": "remote",
"group": "codewhale",
"summary": "Remote pairing, served by the Engine.",
"availability": "review-grant",
"availabilityText": "Served by the Engine only when the plugin's review granted it.",
"methods": [
{
"name": "status",
"signature": "status(): Promise<Status>",
"summary": "Whether remote access is on."
},
{
"name": "pair",
"signature": "pair(options?: { label?: string }): Promise<Pairing>",
"summary": "Start a pairing."
},
{
"name": "clients",
"signature": "clients(): Promise<Client[]>",
"summary": "List paired clients."
},
{
"name": "revoke",
"signature": "revoke(id: string): Promise<void>",
"summary": "Revoke one grant by the id pair returned."
}
]
}
],
"refusedServices": [
"shellHooks",
"loader",
"approval",
"agents",
"subagents",
"sessions",
"llm",
"sandboxPolicy",
"credentials",
"fs",
"subprocess",
"systemPrompt",
"runtimeLoop",
"tools",
"commands",
"prompt",
"storage",
"skills",
"avatars",
"mcp",
"logger",
"userQuestions"
],
"events": [
{
"name": "tools/pre-execute",
"status": "supported",
"mode": "ordered listeners, native hooks first, then plugin listeners in registration order",
"signature": "ctx.on('tools/pre-execute', async (exec: { name: string, callId: string, arguments: object, signal: AbortSignal, workspace: string, mode: string, model: string }, next: () => Promise<Abstention>) => Verdict | undefined)",
"summary": "Programmable tool admission for a reviewed native plugin. The frozen call view has no session, agent, tool or approval handle. Return { kind: 'deny', reason }, { kind: 'ask', reason? }, { kind: 'revise', input }, { kind: 'annotate', text } or { kind: 'abstain' }; undefined abstains. A malformed answer, error or timeout fails the call closed. The listener batch has a five second deadline.",
"options": "prepend and global are refused."
},
{
"name": "agent/created",
"status": "supported",
"mode": "listeners of the owning plugin only",
"signature": "ctx.on('agent/created', async ({ agent }: { agent: { id: string, ctx: { systemPrompt: { getSectionOrder(name), section(section) }, tools: { restrict(filter: { deny: string[] }) } } } }) => void)",
"summary": "Fires for a child agent that this plugin's own subagents.startActivation creates, before the child starts. The listener may set the child's persona and deny tools to it; the window closes when the listeners return.",
"options": "global is refused."
},
{
"name": "agent/pre-step",
"status": "refused",
"summary": "Not projected by this host: no core projection exists, so a listener would never fire."
},
{
"name": "agent/turn-stopping",
"status": "refused",
"summary": "Not projected by this host: no core projection exists, so a listener would never fire."
},
{
"name": "tools/post-execute",
"status": "refused",
"summary": "Not projected by this host: no core projection exists, so a listener would never fire."
},
{
"name": "subagent/start",
"status": "refused",
"summary": "Not projected by this host: no core projection exists, so a listener would never fire."
},
{
"name": "subagent/end",
"status": "refused",
"summary": "Not projected by this host: no core projection exists, so a listener would never fire."
}
],
"cordisInternalEvents": "Cordis fires its own internal/* lifecycle events. They are not part of this host's supported contract and are not listed.",
"config": [
{
"id": "row:@deepseek-ai/dsh-mcp-client",
"name": "@deepseek-ai/dsh-mcp-client",
"bridge": "mcp",
"summary": "An MCP server row. The Engine proposes the server and owns the connection.",
"limits": [
"stdio rows name a command; streamable-http and sse rows name a url.",
"Reconnect and instruction bounds belong to the Engine and are not configurable here."
],
"example": {
"transport": "stdio",
"serverName": "docs",
"command": "node",
"args": [
"server.js"
],
"cwd": "."
},
"schema": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "@deepseek-ai/dsh-mcp-client",
"type": "object",
"additionalProperties": false,
"required": [
"transport",
"serverName"
],
"properties": {
"transport": {
"type": "string",
"enum": [
"stdio",
"streamable-http",
"sse"
]
},
"serverName": {
"type": "string",
"pattern": "^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$"
},
"command": {
"type": "string",
"description": "stdio only: the program to run."
},
"args": {
"type": "array",
"items": {
"type": "string"
},
"description": "stdio only."
},
"env": {
"type": "object",
"maxProperties": 0,
"description": "Must be empty or absent: credentials stay with the Engine."
},
"cwd": {
"type": "string",
"description": "stdio only: a bundle-relative directory, no .. components."
},
"url": {
"type": "string",
"description": "streamable-http and sse: the endpoint, with no credentials, query or fragment."
},
"headers": {
"type": "object",
"maxProperties": 0,
"description": "Must be empty or absent: credentials stay with the Engine."
},
"toolCallTimeoutMs": {
"type": "integer",
"minimum": 1000,
"maximum": 86400000,
"multipleOf": 1000
},
"failOnStartupError": {
"type": "boolean",
"const": false,
"description": "Only false: the Engine connects lazily and reports failures through /mcp."
}
}
}
},
{
"id": "row:@deepseek-ai/dsh-skill-filesystem",
"name": "@deepseek-ai/dsh-skill-filesystem",
"bridge": "skills",
"summary": "A skill folder row, limited to reviewed roots inside the bundle.",
"limits": [
"Both includeDefaultRoots and watch must be written out as false."
],
"example": {
"includeDefaultRoots": false,
"watch": false,
"customSkillDirs": [
"skills"
]
},
"schema": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "@deepseek-ai/dsh-skill-filesystem",
"type": "object",
"additionalProperties": false,
"required": [
"includeDefaultRoots",
"watch",
"customSkillDirs"
],
"properties": {
"providerName": {
"type": "string",
"maxLength": 64
},
"includeDefaultRoots": {
"type": "boolean",
"const": false,
"description": "Must be false: ambient roots are not read."
},
"watch": {
"type": "boolean",
"const": false,
"description": "Must be false: there is no file watcher."
},
"customSkillDirs": {
"type": "array",
"minItems": 1,
"maxItems": 8,
"items": {
"type": "string"
},
"description": "Bundle-relative skill roots, no duplicates."
}
}
}
},
{
"id": "row:@deepseek-ai/dsh-hooks-claude-code",
"name": "@deepseek-ai/dsh-hooks-claude-code",
"bridge": "hooks-claude-code",
"summary": "Claude Code style command hooks read from a reviewed file in the bundle.",
"limits": [
"projectDir is refused: each process uses the current workspace.",
"Only command hooks run; non-command and asynchronous hooks fail the row.",
"At most 128 commands per row."
],
"example": {
"configPath": "hooks/hooks.json"
},
"hookEvents": [
{
"event": "SessionStart",
"point": "session_start"
},
{
"event": "UserPromptSubmit",
"point": "message_submit"
},
{
"event": "PreToolUse",
"point": "tool_call_before"
},
{
"event": "PostToolUse",
"point": "tool_call_after"
},
{
"event": "Stop",
"point": "turn_end"
},
{
"event": "SubagentStart",
"point": "subagent_spawn"
},
{
"event": "SubagentStop",
"point": "subagent_complete"
}
],
"schema": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "@deepseek-ai/dsh-hooks-claude-code",
"type": "object",
"additionalProperties": true,
"required": [
"configPath"
],
"properties": {
"configPath": {
"type": "string",
"description": "A regular file inside the bundle, at most 1 MiB, unchanged since review."
},
"pluginRoot": {
"type": "string",
"description": "Absent, \".\", or this reviewed bundle root."
},
"defaultTimeoutMs": {
"type": "integer",
"minimum": 1000,
"maximum": 86400000,
"multipleOf": 1000,
"description": "Whole seconds, used when a hook sets none; default 600000."
}
}
}
},
{
"id": "row:@deepseek-ai/dsh-hooks-codex",
"name": "@deepseek-ai/dsh-hooks-codex",
"bridge": "hooks-codex",
"summary": "Codex style command hooks read from a reviewed file in the bundle.",
"limits": [
"projectDir is refused: each process uses the current workspace.",
"Only command hooks run; non-command and asynchronous hooks fail the row.",
"At most 128 commands per row."
],
"example": {
"configPath": "hooks/hooks.json"
},
"hookEvents": [
{
"event": "SessionStart",
"point": "session_start"
},
{
"event": "UserPromptSubmit",
"point": "message_submit"
},
{
"event": "PreToolUse",
"point": "tool_call_before"
},
{
"event": "PostToolUse",
"point": "tool_call_after"
},
{
"event": "Stop",
"point": "turn_end"
},
{
"event": "SubagentStart",
"point": "subagent_spawn"
},
{
"event": "SubagentStop",
"point": "subagent_complete"
}
],
"schema": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "@deepseek-ai/dsh-hooks-codex",
"type": "object",
"additionalProperties": true,
"required": [
"configPath"
],
"properties": {
"configPath": {
"type": "string",
"description": "A regular file inside the bundle, at most 1 MiB, unchanged since review."
},
"pluginRoot": {
"type": "string",
"description": "Absent, \".\", or this reviewed bundle root."
},
"defaultTimeoutMs": {
"type": "integer",
"minimum": 1000,
"maximum": 86400000,
"multipleOf": 1000,
"description": "Whole seconds, used when a hook sets none; default 600000."
}
}
}
},
{
"id": "row:@deepseek-ai/dsh-persona",
"name": "@deepseek-ai/dsh-persona",
"bridge": "persona",
"summary": "Text added before and after the Engine's own prompt for this plugin's entry.",
"limits": [
"Needs an exact Engine-selected entry scope."
],
"example": {
"prefix": "Answer in short sentences."
},
"schema": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "@deepseek-ai/dsh-persona",
"type": "object",
"additionalProperties": false,
"required": [
"prefix"
],
"properties": {
"prefix": {
"type": "string",
"description": "At most 4096 UTF-8 bytes, no control characters. Only {{model}} and {{cwd}} are expanded."
},
"suffix": {
"type": "string",
"description": "Same limits as prefix."
},
"complete": {
"type": "boolean",
"const": false,
"description": "Replacing the whole prompt belongs to the Engine."
},
"includeRuntimeContext": {
"type": "boolean",
"const": true,
"description": "Suppressing the runtime context belongs to the Engine."
}
}
}
}
]
},
"client": {
"seats": [
{
"seat": "customize.plugins.detail",
"drawn": true,
"where": "The plugin's own page under Customize, Plugins."
},
{
"seat": "conversation.composer.dock",
"drawn": false,
"where": "Under the composer. The desktop app does not place it yet."
},
{
"seat": "conversation.chat.node",
"drawn": false,
"where": "Inside the conversation. The desktop app does not place it yet."
},
{
"seat": "workpane.panel",
"drawn": false,
"where": "The work pane. The desktop app does not place it yet."
},
{
"seat": "sidebar.section",
"drawn": false,
"where": "The sidebar. The desktop app does not place it yet."
},
{
"seat": "command.row",
"drawn": false,
"where": "The command list. The desktop app does not place it yet."
}
],
"slots": [
{
"slot": "plugins.bundle.config",
"seat": "customize.plugins.detail",
"supported": true
},
{
"slot": "plugins.row.config",
"seat": "customize.plugins.detail",
"supported": true
},
{
"slot": "plugins.tab",
"seat": "customize.plugins.detail",
"supported": true
},
{
"slot": "plugins.detail.section",
"seat": "customize.plugins.detail",
"supported": true
},
{
"slot": "settings.section",
"seat": "customize.plugins.detail",
"supported": true
},
{
"slot": "settings.plugin.item",
"seat": "customize.plugins.detail",
"supported": true
},
{
"slot": "settings.general.item",
"seat": "customize.plugins.detail",
"supported": true
},
{
"slot": "settings.plugins.tab",
"seat": "customize.plugins.detail",
"supported": true
},
{
"slot": "conversation.chat.node",
"seat": "conversation.chat.node",
"supported": true
},
{
"slot": "conversation.chat.turnTail",
"seat": "conversation.chat.node",
"supported": true
},
{
"slot": "conversation.chat.assistant-actions",
"seat": "conversation.chat.node",
"supported": true
},
{
"slot": "conversation.chat.text-interaction",
"seat": "conversation.chat.node",
"supported": true
},
{
"slot": "conversation.user.text.node",
"seat": "conversation.chat.node",
"supported": true
},
{
"slot": "tool.call.toolview",
"seat": "conversation.chat.node",
"supported": true
},
{
"slot": "conversation.view",
"seat": "conversation.chat.node",
"supported": true
},
{
"slot": "conversation.input.dock",
"seat": "conversation.composer.dock",
"supported": true
},
{
"slot": "conversation.input.overlay",
"seat": "conversation.composer.dock",
"supported": true
},
{
"slot": "conversation.input.right",
"seat": "conversation.composer.dock",
"supported": true
},
{
"slot": "conversation.composer.dock",
"seat": "conversation.composer.dock",
"supported": true
},
{
"slot": "sidebar.right.pane.tab",
"seat": "workpane.panel",
"supported": true
},
{
"slot": "main.conversation",
"seat": "workpane.panel",
"supported": true
},
{
"slot": "main.page-menu",
"seat": "workpane.panel",
"supported": true
},
{
"slot": "sidebar.panellist",
"seat": "sidebar.section",
"supported": true
},
{
"slot": "sidebar.workspaces",
"seat": "sidebar.section",
"supported": true
},
{
"slot": "sidebar.footer.action",
"seat": "sidebar.section",
"supported": true
},
{
"slot": "sidebar.session.row.leading",
"seat": "sidebar.section",
"supported": true
},
{
"slot": "sidebar.workspaces.session.row.action",
"seat": "sidebar.section",
"supported": true
},
{
"slot": "conversation.session.header.actions",
"seat": null,
"supported": false,
"reason": "no ADE seat yet"
},
{
"slot": "conversation.session.header.utilities",
"seat": null,
"supported": false,
"reason": "no ADE seat yet"
},
{
"slot": "contextMenu.icon",
"seat": null,
"supported": false,
"reason": "no ADE seat yet"
}
],
"theme": {
"tokens": [],
"colorSchemes": [
"light",
"dark"
],
"scheme": "The frame sets data-theme and color-scheme on its document to the app's current scheme and follows changes.",
"api": [
{
"name": "ctx.theme.getTheme",
"signature": "getTheme(): { active: { colorScheme: 'light' | 'dark' } }",
"summary": "The scheme in use now."
},
{
"name": "ctx.theme.overrideTokens",
"signature": "overrideTokens(source: string, tokens: Record<string, { light: string, dark: string }>): () => void",
"summary": "Set custom properties on the frame's document for each scheme. source is at most 256 characters; each name starts with -- and is at most 128 characters; each value is at most 512 characters. Returns a disposer."
}
],
"notes": [
"The frame defines no named design tokens of its own. There are no --dsw-* tokens to read: a plugin that wants tokens defines them with overrideTokens and uses them in its own styles.",
"The frame's background is transparent and its margin is zero, so the plugin sits on the app's own surface."
]
}
}
}
@@ -1,245 +0,0 @@
import { isJson } from '../json.ts'
import { assertSupportedJsonSchema, validateJsonSchemaValue } from './dsh-tools-compat.js'
import catalogData from './inspect-catalog.json' with { type: 'json' }
export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
export type InspectPlatform = 'host' | 'client'
export interface InspectMethod {
name: string
description: string
inputSchema: JsonValue
outputSchema: JsonValue
}
export interface InspectProviderView {
platform: InspectPlatform
id: string
description: string
methods: InspectMethod[]
}
export interface InstalledRow {
id: string
name: string
state: string
}
export interface ClientState {
connected: boolean
drawnSeats?: readonly string[]
}
export interface InspectSources {
tools?: (agent: unknown, signal: AbortSignal) => Promise<readonly JsonValue[]> | readonly JsonValue[]
installed?: (signal: AbortSignal) => Promise<readonly InstalledRow[]> | readonly InstalledRow[]
client?: () => ClientState
}
export interface CordisInspect {
list(): InspectProviderView[]
query(platform: string, provider: string, method: string, input: JsonValue | undefined, agent?: unknown, signal?: AbortSignal): Promise<JsonValue>
}
interface Provider {
platform: InspectPlatform
id: string
description: string
methods: InspectMethod[]
run(method: string, input: Record<string, JsonValue>, agent: unknown, signal: AbortSignal): Promise<any> | any
}
const catalog = catalogData as any
const EMPTY_INPUT: JsonValue = { type: 'object', properties: {}, additionalProperties: false }
const ANY_OUTPUT: JsonValue = { description: 'JSON data owned by this inspect provider.' }
const NO_CLIENT = 'No client is connected. Plugin screens are drawn by the desktop app; in a terminal nothing is drawn, so every slot reports drawn: false.'
const exactInput = (field: string, description: string): JsonValue => ({
type: 'object',
properties: { [field]: { type: 'string', description } },
additionalProperties: false,
})
const method = (name: string, description: string, inputSchema: JsonValue = EMPTY_INPUT, outputSchema: JsonValue = ANY_OUTPUT): InspectMethod =>
({ name, description, inputSchema, outputSchema })
const copy = <T>(value: T): T => JSON.parse(JSON.stringify(value))
function serviceView(service: any): JsonValue {
return {
key: service.key,
group: service.group,
summary: service.summary,
availability: service.availability,
availabilityText: service.availabilityText,
methods: service.methods,
}
}
function serviceProvider(): Provider {
return {
platform: 'host', id: 'Service',
description: 'The services this host gives plugins, with their methods, and the services a plugin may not provide. A name that is not listed does not exist here.',
methods: [method('listService', 'Without input: the directory of services with one-line summaries and method signatures. With service: that service\'s exact contract, with availability. These are services a plugin injects, not DSH\'s full catalogue.',
exactInput('service', 'Exact service key. Omit it for the directory.'))],
run(_name, input) {
const key = input.service
if (key === undefined) {
return {
services: catalog.host.services.map((s: any) => ({ key: s.key, group: s.group, summary: s.summary, availability: s.availability, signatures: s.methods.map((m: any) => m.signature) })),
refusedServices: catalog.host.refusedServices,
note: 'refusedServices are names a plugin may not provide: the Engine owns them. Service methods named by the host Event and Config providers are separate.',
targetDshVersion: catalog.targetDshVersion,
}
}
const found = catalog.host.services.find((s: any) => s.key === key)
if (!found) throw new Error(`Host service "${String(key)}" is not provided by this host. Call without service for the directory.`)
return { service: serviceView(found), targetDshVersion: catalog.targetDshVersion }
},
}
}
function eventProvider(): Provider {
return {
platform: 'host', id: 'Event',
description: 'The events a plugin may listen to in this host, and the ones the host refuses.',
methods: [method('listEvents', 'Without input: the directory of events with status supported or refused. With event: its exact contract.',
exactInput('event', 'Exact event name. Omit it for the directory.'))],
run(_name, input) {
const key = input.event
if (key === undefined) {
return {
events: catalog.host.events.map((e: any) => ({ name: e.name, status: e.status, summary: e.summary })),
note: catalog.host.cordisInternalEvents,
}
}
const found = catalog.host.events.find((e: any) => e.name === key)
if (!found) throw new Error(`Host event "${String(key)}" is not known to this host. Call without event for the directory.`)
return { event: found }
},
}
}
const CONFIG_INPUT: JsonValue = {
type: 'object',
properties: {
entry: { type: 'string', description: 'Exact entry id from the directory; returns that entry\'s Config schema.' },
name: { type: 'string', description: 'Exact package or plugin name; limits the directory to it.' },
offset: { type: 'integer', description: 'Zero-based directory offset; defaults to 0.' },
limit: { type: 'integer', description: 'Directory page size, from 1 to 100; defaults to 25.' },
},
additionalProperties: false,
}
function configProvider(sources: InspectSources): Provider {
return {
platform: 'host', id: 'Config',
description: 'Config a composition row may carry: the packages a row may name, each with the config it accepts, and the plugins installed on this host with their state.',
methods: [method('listConfigs', 'Without entry: a page of the directory (row packages first, then installed plugins) with total and nextOffset. With entry: one row package\'s exact JSON Schema, limits and a valid example. Installed plugins are listed with their state; their own config is not described here.', CONFIG_INPUT)],
async run(_name, input, _agent, signal) {
const rows: any[] = catalog.host.config.map((r: any) => ({ id: r.id, name: r.name, kind: 'row-package', status: 'schema', bridge: r.bridge, summary: r.summary }))
const installed = sources.installed ? await sources.installed(signal) : []
for (const row of installed) rows.push({ id: `plugin:${row.id}`, name: row.name, kind: 'installed-plugin', status: row.state })
if (input.entry !== undefined) {
const pkg = catalog.host.config.find((r: any) => r.id === input.entry)
if (pkg) return { entry: pkg.id, name: pkg.name, kind: 'row-package', bridge: pkg.bridge, summary: pkg.summary, limits: pkg.limits, example: pkg.example, ...pkg.hookEvents ? { hookEvents: pkg.hookEvents } : {}, schema: pkg.schema }
const live = rows.find((r) => r.id === input.entry)
if (live) return { entry: live.id, name: live.name, kind: live.kind, status: live.status, schema: null, note: 'An installed plugin\'s own Config is not described by this host.' }
throw new Error(`Host Config entry "${String(input.entry)}" is not listed. Call without entry for the directory.`)
}
const filtered = input.name === undefined ? rows : rows.filter((r) => r.name === input.name)
const offset = typeof input.offset === 'number' ? input.offset : 0
const limit = typeof input.limit === 'number' ? input.limit : 25
if (offset < 0 || limit < 1 || limit > 100) throw new Error('Host Config directory needs offset >= 0 and 1 <= limit <= 100')
const page = filtered.slice(offset, offset + limit)
const next = offset + page.length
return { entries: page, total: filtered.length, ...next < filtered.length ? { nextOffset: next } : {} }
},
}
}
function toolProvider(sources: InspectSources): Provider | undefined {
const source = sources.tools
if (!source) return undefined
return {
platform: 'host', id: 'Tool',
description: 'Tools visible to the requesting agent.',
methods: [method('listTools', 'Return every tool schema currently callable by this agent.')],
async run(_name, _input, agent, signal) {
return { tools: [...await source(agent, signal)] }
},
}
}
const SUBTREE_INPUT = exactInput('root', 'Exact slot name to select. Omit it for every slot.')
function slotsProvider(sources: InspectSources): Provider {
return {
platform: 'client', id: 'Slots',
description: 'The DSH slot names this host accepts, the seat each maps to, and whether the connected client draws that seat.',
methods: [method('listSubTree', 'Return every slot with its seat and drawn state; with root, also that slot selected. Slots are static names here, not a live tree, and their props are not described by this host: a plugin registers on a slot, the Engine serves it on the mapped seat, and the client draws only the seats it places.', SUBTREE_INPUT)],
run(_name, input) {
const state = sources.client?.() ?? { connected: false }
const drawn = new Set(state.connected ? state.drawnSeats ?? catalog.client.seats.filter((s: any) => s.drawn).map((s: any) => s.seat) : [])
const slots = catalog.client.slots.map((s: any) => ({
type: 'slot', name: s.slot, seat: s.seat, supported: s.supported,
drawn: s.supported && drawn.has(s.seat),
...s.reason ? { reason: s.reason } : {},
}))
const seats = catalog.client.seats.map((s: any) => ({ seat: s.seat, drawn: drawn.has(s.seat), where: s.where }))
const out: Record<string, JsonValue> = {
client: state.connected ? { connected: true } : { connected: false, message: NO_CLIENT },
seats, trees: slots, referencedTypes: [],
}
if (input.root !== undefined) {
const selected = slots.find((s: any) => s.name === input.root)
out.requestedRoot = { name: input.root, available: selected !== undefined }
if (selected) out.selected = selected
}
return out
},
}
}
function themeProvider(): Provider {
return {
platform: 'client', id: 'Theme',
description: 'What the plugin frame provides for theming.',
methods: [method('listTokens', 'Return the named tokens the frame provides (none), the colour schemes, and the theme calls a plugin has.')],
run() {
return { tokens: catalog.client.theme.tokens, colorSchemes: catalog.client.theme.colorSchemes, scheme: catalog.client.theme.scheme, api: catalog.client.theme.api, notes: catalog.client.theme.notes, referencedTypes: [] }
},
}
}
export function createCordisInspect(sources: InspectSources = {}): CordisInspect {
const providers: Provider[] = [serviceProvider(), eventProvider(), configProvider(sources), toolProvider(sources), slotsProvider(sources), themeProvider()]
.filter((p): p is Provider => p !== undefined)
for (const provider of providers) {
if (provider.id.trim() === '' || provider.description.trim() === '') throw new Error('Cordis inspect provider needs an id and a description')
for (const m of provider.methods) {
assertSupportedJsonSchema(m.inputSchema)
assertSupportedJsonSchema(m.outputSchema)
}
}
const label = (platform: InspectPlatform) => platform === 'host' ? 'Host' : 'Client'
return {
list() {
return providers.map((p) => ({ platform: p.platform, id: p.id, description: p.description, methods: copy(p.methods) }))
},
async query(platform, providerId, methodName, input, agent, signal = new AbortController().signal) {
if (platform !== 'host' && platform !== 'client') throw new Error(`Cordis inspect platform must be "host" or "client", not "${String(platform)}"`)
const provider = providers.find((p) => p.platform === platform && p.id === providerId)
if (!provider) throw new Error(`${label(platform)} Cordis inspect provider "${providerId}" is not registered`)
const found = provider.methods.find((m) => m.name === methodName)
if (!found) throw new Error(`Cordis inspect provider "${provider.id}" has no method "${methodName}"`)
const violations = validateJsonSchemaValue(found.inputSchema, input ?? {}, 'input') as string[]
if (violations.length > 0) throw new Error(`${label(platform)} Cordis inspect ${provider.id}.${found.name} rejected input: ${violations.join('; ')}`)
signal.throwIfAborted()
const data = await provider.run(methodName, (input ?? {}) as Record<string, JsonValue>, agent, signal)
signal.throwIfAborted()
if (!isJson(data)) throw new Error(`${label(platform)} Cordis inspect ${provider.id}.${found.name} returned a non-JSON value`)
return copy(data)
},
}
}
@@ -1,92 +0,0 @@
import { Service } from '@deepseek-ai/cordis'
import { ErrorCode } from '../protocol.ts'
import { RpcError } from '../rpc.ts'
import type { AdapterHost, DshAdapter } from './adapters.ts'
export const CREDENTIAL_HANDLE_PREFIX = 'codewhale-credential:'
interface BrokeredResponse {
status: number
url: string
redirected: boolean
headers: [string, string][]
body_base64: string
}
function credentialRef(ref: unknown): string {
if (typeof ref !== 'string' || ref.length === 0) throw new RpcError(ErrorCode.InvalidParams, 'a credential ref is a non-empty string')
return ref
}
function brokered(value: unknown): BrokeredResponse {
const response = value as Partial<BrokeredResponse> | null
if (response === null || typeof response !== 'object' || typeof response.status !== 'number' || typeof response.url !== 'string'
|| typeof response.body_base64 !== 'string' || !Array.isArray(response.headers)) {
throw new RpcError(ErrorCode.Internal, 'invalid network broker response')
}
return response as BrokeredResponse
}
async function requestBody(body: unknown): Promise<string | undefined> {
if (body === undefined || body === null) return undefined
if (typeof body === 'string') return Buffer.from(body, 'utf8').toString('base64')
if (body instanceof ArrayBuffer) return Buffer.from(body).toString('base64')
if (ArrayBuffer.isView(body)) return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('base64')
if (body instanceof URLSearchParams) return Buffer.from(body.toString(), 'utf8').toString('base64')
if (body instanceof Blob) return Buffer.from(await body.arrayBuffer()).toString('base64')
throw new RpcError(ErrorCode.InvalidParams, 'the network broker sends string, binary, URLSearchParams or Blob bodies')
}
export async function brokeredFetch(host: AdapterHost, ctx: unknown, input: string | URL | Request, init: RequestInit = {}): Promise<Response> {
const request = input instanceof Request ? input : undefined
const url = request?.url ?? String(input)
const headers = new Headers(request?.headers)
new Headers(init.headers).forEach((value, name) => headers.set(name, value))
const body = init.body !== undefined ? init.body : request !== undefined && request.body !== null ? await request.arrayBuffer() : undefined
const result = brokered(await host.broker(ctx, 'network', 'fetch', {
url,
method: init.method ?? request?.method ?? 'GET',
headers: [...headers.entries()],
body_base64: await requestBody(body),
}))
const bytes = Buffer.from(result.body_base64, 'base64')
const nullBody = [101, 204, 205, 304].includes(result.status)
const response = new Response(nullBody ? null : bytes, { status: result.status, headers: result.headers })
Object.defineProperty(response, 'url', { value: result.url })
Object.defineProperty(response, 'redirected', { value: result.redirected === true })
return response
}
export const credentialsAdapter: DshAdapter = {
service: 'credentials',
define(host) {
class CredentialsService extends Service {
constructor(ctx: any) { super(ctx, 'credentials') }
async resolve(ref: unknown): Promise<{ value: string } | undefined> {
const result = await host.broker(this.ctx, 'network', 'credentials.resolve', { ref: credentialRef(ref) }) as { value?: unknown } | null
const value = result?.value
if (value === null || value === undefined) return undefined
if (typeof value !== 'string' || !value.startsWith(CREDENTIAL_HANDLE_PREFIX)) throw new RpcError(ErrorCode.Internal, 'invalid credential handle')
return { value }
}
async describe(ref: unknown): Promise<{ ref: string, set: boolean }> {
const result = await host.broker(this.ctx, 'network', 'credentials.describe', { ref: credentialRef(ref) }) as { ref?: unknown, set?: unknown } | null
if (result === null || typeof result !== 'object' || typeof result.set !== 'boolean') throw new RpcError(ErrorCode.Internal, 'invalid credential description')
return { ref: credentialRef(ref), set: result.set }
}
async set(ref: unknown, value: unknown): Promise<void> {
if (typeof value !== 'string' || value.length === 0) throw new RpcError(ErrorCode.InvalidParams, 'a credential value is a non-empty string')
await host.broker(this.ctx, 'network', 'credentials.set', { ref: credentialRef(ref), value })
}
fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {
return brokeredFetch(host, this.ctx, input, init)
}
}
Object.freeze(CredentialsService.prototype)
return CredentialsService
},
}
@@ -1,33 +0,0 @@
import { Service } from '@deepseek-ai/cordis'
import { ErrorCode } from '../protocol.ts'
import { RpcError } from '../rpc.ts'
import type { DshAdapter } from './adapters.ts'
function label(value: unknown): string | undefined {
if (value === undefined) return undefined
if (typeof value !== 'string') throw new RpcError(ErrorCode.InvalidParams, 'remote.pair label must be a string')
return value
}
function grant(value: unknown): string {
if (typeof value !== 'string' || value.length === 0 || value.length > 128) throw new RpcError(ErrorCode.InvalidParams, 'remote.revoke needs the grant id remote.pair returned')
return value
}
export const remoteAdapter: DshAdapter = {
service: 'remote',
define(host) {
class RemoteService extends Service {
constructor(ctx: any) { super(ctx, 'remote') }
status() { return host.broker(this.ctx, 'remote', 'status', {}) }
pair(options?: { label?: unknown }) {
const value = label(options?.label)
return host.broker(this.ctx, 'remote', 'pair', value === undefined ? {} : { label: value })
}
clients() { return host.broker(this.ctx, 'remote', 'clients', {}) }
revoke(id: unknown) { return host.broker(this.ctx, 'remote', 'revoke', { grant: grant(id) }) }
}
Object.freeze(RemoteService.prototype)
return RemoteService
},
}
@@ -1,58 +0,0 @@
import { Service } from '@deepseek-ai/cordis'
import { ErrorCode } from '../protocol.ts'
import { RpcError } from '../rpc.ts'
import type { OwnerRecord, ToolInvocation } from '../root.ts'
import type { AdapterHost, DshAdapter } from './adapters.ts'
const CHILD_ONLY = "system prompt sections are only available on a child agent's agent/created context"
function checkpointCall(host: AdapterHost, ctx: unknown, session: unknown): ToolInvocation | undefined {
const invocation = host.liveInvocation(ctx)
const ticket = invocation?.ticket
return invocation !== undefined && typeof ticket === 'string' && ticket.length > 0
&& session !== undefined && session === invocation.session
? invocation
: undefined
}
export const sessionsAdapter: DshAdapter = {
service: 'sessions',
define(host) {
class SessionsService extends Service {
constructor(ctx: any) { super(ctx, 'sessions') }
async flush(session: unknown): Promise<boolean> {
const ctx = this.ctx
const call = checkpointCall(host, ctx, session)
if (call === undefined) throw new RpcError(ErrorCode.NotAvailable, 'sessions.flush requires this live tool invocation’s session')
const owner: OwnerRecord = call.owner
const live = () => checkpointCall(host, ctx, session) === call && !call.signal.aborted
const run = async () => {
if (!live()) throw new RpcError(ErrorCode.NotAvailable, 'session checkpoint invocation ended')
const result = await host.rpc.request<unknown>('session/checkpoint', { owner: owner.ref, ticket: call.ticket }, call.signal)
if (!live()) throw new RpcError(ErrorCode.NotAvailable, 'session checkpoint invocation ended')
if (typeof result !== 'boolean') throw new RpcError(ErrorCode.Internal, 'invalid session checkpoint receipt')
return result
}
const result = call.pending.then(run)
call.pending = result.then(() => undefined, () => undefined)
return result
}
}
Object.freeze(SessionsService.prototype)
return SessionsService
},
}
export const systemPromptAdapter: DshAdapter = {
service: 'systemPrompt',
define() {
class SystemPromptService extends Service {
constructor(ctx: any) { super(ctx, 'systemPrompt') }
section() { throw new RpcError(ErrorCode.NotAvailable, CHILD_ONLY) }
getSectionOrder() { throw new RpcError(ErrorCode.NotAvailable, CHILD_ONLY) }
}
Object.freeze(SystemPromptService.prototype)
return SystemPromptService
},
}
@@ -1,64 +0,0 @@
import { Service } from '@deepseek-ai/cordis'
import { ErrorCode } from '../protocol.ts'
import { RpcError } from '../rpc.ts'
import type { DshAdapter } from './adapters.ts'
const SESSION = /^[A-Za-z0-9._-]{1,64}$/
function invalid(message: string): never {
throw new RpcError(ErrorCode.InvalidParams, message)
}
function session(value: unknown): string {
if (typeof value !== 'string' || !SESSION.test(value)) invalid('a terminal name is 1 to 64 letters, digits, `_`, `-` or `.`')
return value as string
}
function text(value: unknown, what: string): string {
if (typeof value !== 'string' || value.length === 0) invalid(`${what} is a non-empty string`)
return value as string
}
function bounded(value: unknown, what: string, min: number, max: number): number | undefined {
if (value === undefined) return undefined
if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) invalid(`${what} is an integer between ${min} and ${max}`)
return value as number
}
function compact(input: Record<string, unknown>): Record<string, unknown> {
return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined))
}
export const terminalAdapter: DshAdapter = {
service: 'terminal',
define(host) {
class TerminalService extends Service {
constructor(ctx: any) { super(ctx, 'terminal') }
list() { return host.broker(this.ctx, 'terminal', 'list', {}) }
run(command: unknown, options?: { session?: unknown, timeoutSecs?: unknown }) {
return host.broker(this.ctx, 'terminal', 'run', compact({
command: text(command, 'a command'),
session: options?.session === undefined ? undefined : session(options.session),
timeout_secs: bounded(options?.timeoutSecs, 'timeoutSecs', 1, 600),
}))
}
send(name: unknown, input: unknown, options?: { waitMs?: unknown }) {
return host.broker(this.ctx, 'terminal', 'send', compact({
session: session(name),
text: text(input, 'terminal input'),
wait_ms: bounded(options?.waitMs, 'waitMs', 0, 60_000),
}))
}
wait(name: unknown, options?: { timeoutSecs?: unknown }) {
return host.broker(this.ctx, 'terminal', 'wait', compact({
session: session(name),
timeout_secs: bounded(options?.timeoutSecs, 'timeoutSecs', 1, 600),
}))
}
cancel(name: unknown) { return host.broker(this.ctx, 'terminal', 'cancel', { session: session(name) }) }
reset(name: unknown) { return host.broker(this.ctx, 'terminal', 'reset', { session: session(name) }) }
}
Object.freeze(TerminalService.prototype)
return TerminalService
},
}
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 DeepSeek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -1,17 +0,0 @@
# DeepSeek Harness creator files, pinned
Byte-for-byte copies of the files DeepSeek Harness 0.2.2-rc.1 uses for its
Creator mode, kept so Codewhale hosts the same tool and skill text rather than
a rewrite. `UPSTREAM.json` records the package, version, upstream path and
SHA-256 of every file; `test/creator-pin.test.mjs` fails when a file drifts.
- `plugin-manager/tools.js`: `@deepseek-ai/dsh-plugin-manager` `lib/types/tools.js`
- `tool-cordis/index.js`: `@deepseek-ai/dsh-tool-cordis` `lib/index.js`
- `sandbox/escalation.js`: not yet pinned (see `UPSTREAM.json`, `pending`)
The four authoring skills of `@deepseek-ai/dsh-agent-preset` are pinned beside
the skills crate at `crates/skills/assets/dsh-creator/`.
The files are MIT licensed by DeepSeek; `LICENSE` is the licence text shipped
in each of the four packages. Nothing here is edited: change the pin by
replacing the file and its recorded hash together, at a new DSH version.
@@ -1,39 +0,0 @@
{
"repository": "https://github.com/deepseek-ai/deepseek-harness",
"version": "0.2.2-rc.1",
"license": "MIT",
"license_sha256": "ebb4f09972aee8608be255debaf78451a68e95c290f55c240dec2ecfa16ea6be",
"source": "npm packages as shipped in DeepSeek Harness desktop 0.2.2-rc.1",
"packages": [
"@deepseek-ai/dsh-agent-preset",
"@deepseek-ai/dsh-plugin-manager",
"@deepseek-ai/dsh-tool-cordis",
"@deepseek-ai/dsh-sandbox"
],
"files": [
{
"path": "plugin-manager/tools.js",
"package": "@deepseek-ai/dsh-plugin-manager",
"upstream_path": "lib/types/tools.js",
"sha256": "18d9f06f20a821bd205b6d88f87f440659730ef9431fb92351a50d86779da3ca",
"bytes": 12583,
"verbatim": true
},
{
"path": "tool-cordis/index.js",
"package": "@deepseek-ai/dsh-tool-cordis",
"upstream_path": "lib/index.js",
"sha256": "ce0cd4d8983532c920cab7713dc51874f6d710c2c46c4a095167bfa980becdb0",
"bytes": 3687,
"verbatim": true
}
],
"pending": [
{
"path": "sandbox/escalation.js",
"package": "@deepseek-ai/dsh-sandbox",
"reason": "excerpt of approveEscalation and its mode table; needs the published tarball, not yet fetched"
}
],
"skills_pin": "crates/skills/assets/dsh-creator/UPSTREAM.json"
}
@@ -1,154 +0,0 @@
/** Agent-facing current-profile management using the same service as Web controls. */
import { assertNever } from '@deepseek-ai/dsh-util-values';
import { approveEscalation } from '@deepseek-ai/dsh-sandbox';
import { defineTool } from '@deepseek-ai/dsh-tools';
import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot';
/** What the model does next for each refusal the manager reports. */
const ERROR_STEPS = {
'management-required': 'This entry belongs to plugin management itself and cannot be changed.',
'unaddressable': 'This entry has no unique profile patch target; tell the user to edit the profile patch file directly.',
'unknown-plugin': 'Call list_plugins and retry with an exact entryId.',
'invalid-spec': 'Retry with an npm package name, a git URL, a tarball URL, or an absolute local directory.',
'already-installed': 'The package is already installed; to install another version, call remove_bundle first, then install_bundle again.',
'ambiguous-install': 'The dependency change named no single package; call list_bundles to see what was installed.',
'not-bundle': 'The package declares no dsh.bundle and cannot be managed as a plugin; install a DSH plugin bundle instead.',
'not-removable': 'Call list_bundles; only bundles marked removable can be removed.',
'stop-profile': 'This profile runs without HMR; tell the user to stop DSH and run `dsh plugin --profile <profile> remove <bundle>`.',
'bundle-in-use': 'Call list_plugins, disable the entries from other layers that still use this bundle, then retry.',
'stale-approval': 'Call install_bundle again without approvedBuilds to read the current pendingBuilds.',
'incompatible-version': 'Install a version compatible with the running DSH. A version exemption needs the user\'s explicit acceptance of crash and data-loss risk.',
'unsupported-platform': 'This bundle cannot run on the current Host platform; ask the user to use a supported Host.',
'operation-error': 'Report the diagnostic to the user; retry only after its cause is addressed.',
};
/** What the model does next for each package-manager failure. */
const FAILURE_STEPS = {
'pnpm-missing': 'pnpm is not available to DSH; tell the user to install pnpm.',
'timeout': 'Retry, or retry with another registry.',
'not-found': 'Check the package name and version with the user, then retry.',
'no-matching-version': 'Retry with a published version.',
'network': 'Retry later or pass another registry.',
'disk-full': 'Tell the user to free disk space, then retry.',
'permission': 'Tell the user DSH cannot write the profile directory; retry after they fix its permissions.',
'build-blocked': 'Ask the user whether to allow the install scripts of the packages in pendingBuilds; if they approve, retry with approvedBuilds.',
};
/** Why a change waits for a restart, as the model tells the user. */
const RESTART_STEPS = {
'no-hmr': 'this profile applies changes only at startup',
'package-moved': 'an installed package now resolves to another directory, or the change replaces a package the DSH installation provides; remove a package before installing it from another location',
'host-module': 'the change reaches modules DSH itself loaded',
'unmanaged-plugin': 'the change reaches a plugin running outside the plugin list',
'module-comparison': 'DSH could not compare loaded plugins with their files',
};
/**
* The model-facing result of a change: the manager's result plus the next step its outcome calls for.
* @param result The manager's result.
* @returns The result with `nextStep` when it is not plainly applied.
*/
function withNextStep(result) {
switch (result.application) {
case 'applied':
return result;
case 'cancelled':
return { ...result, nextStep: 'The installation was cancelled and its files restored; nothing changed.' };
case 'overridden':
return { ...result, nextStep: 'Saved, but a higher-priority layer such as the agent preset overrides it; tell the user it is not in effect.' };
case 'restart-required': {
const reason = result.restartReason === undefined ? '' : `: ${RESTART_STEPS[result.restartReason]}`;
return { ...result, nextStep: `Tell the user to restart DSH to apply this change${reason}.` };
}
case 'failed': {
const code = result.error?.code ?? 'operation-error';
// A refusal code is more specific than the package manager's failure kind.
const kind = code === 'operation-error' ? result.packageResult?.kind : undefined;
return { ...result, nextStep: (kind === undefined ? undefined : FAILURE_STEPS[kind]) ?? ERROR_STEPS[code] };
}
/* v8 ignore next -- ChangeResult.application is a closed union */
default: return assertNever(result.application);
}
}
/** Required services for the management tool. */
export const inject = ['tools', 'pluginManager', 'sandboxPolicy'];
/** Register one management tool for discovery and the four persistent actions.
* @param ctx Agent-scoped tool registration context.
*/
export function apply(ctx) {
ctx.tools.register(defineTool({
name: 'plugin_manager',
description: 'List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.',
parameters: {
action: { type: 'string', required: true, enum: ['list_plugins', 'list_bundles', 'set_plugin', 'set_bundle', 'install_bundle', 'remove_bundle', 'list_version_exemptions', 'set_version_exemption'], description: 'Management operation.' },
target: { type: 'string', description: 'Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle.' },
enabled: { type: 'boolean', description: 'Required for set operations; defaults to true for installation. For set_version_exemption, true grants and false revokes.' },
runtimeVersion: { type: 'string', description: 'For set_version_exemption: exact DSH version from list_version_exemptions. Target must be the manifest package-name@version, not an alias or version range.' },
acceptRisk: { type: 'boolean', description: 'For granting an exemption: true only after warning the user about possible crashes and data loss and receiving explicit permission for this exact plugin/runtime pair. General installation permission is not enough.' },
approvedBuilds: { type: 'array', items: { type: 'string' }, description: 'For install_bundle: pass names from pendingBuilds only after the user explicitly approves running their install scripts in the conversation. This grants persistent permission for this profile.' },
registry: { type: 'string', description: 'For install_bundle: the npm registry URL asked first, when the user names one; otherwise the configured registry is asked, and its configured fallbacks while a registry is unreachable.' },
offset: { type: 'number', description: 'Zero-based list offset; defaults to 0.' },
limit: { type: 'number', description: 'List page size, from 1 to 100; defaults to 25.' },
},
output: {
schema: { type: 'string' },
render: (_args, value) => [{ type: 'text', text: value }],
},
async execute(args, exec) {
const policy = ctx.sandboxPolicy.resolve(exec.agent === undefined ? {} : { session: exec.agent.session });
await approveEscalation({
requestedMode: 'danger-full-access', effectiveMode: policy.mode, subject: 'plugin management operation',
justification: `plugin_manager ${JSON.stringify(args)}. Profile changes persist across sessions; installed Host code runs outside the workspace sandbox.`,
}, { approver: ctx.get('approval'), agent: exec.agent, callId: exec.callId,
toolName: 'plugin_manager', signal: exec.signal });
exec.signal.throwIfAborted();
const manager = ctx.pluginManager;
switch (args.action) {
case 'list_version_exemptions':
return JSON.stringify({ runtimeVersion: getDshRuntimeVersion(), ...manager.listVersionExemptions() });
case 'set_version_exemption':
if (args.target === undefined || args.runtimeVersion === undefined || args.enabled === undefined) {
throw new Error('target package-name@version, runtimeVersion, and enabled are required');
}
return JSON.stringify(withNextStep(await manager.setVersionExemption(args.target, args.runtimeVersion, args.enabled, args.acceptRisk)));
case 'list_plugins':
case 'list_bundles': {
const offset = args.offset ?? 0;
const limit = args.limit ?? 25;
if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100) {
throw new Error('offset must be a non-negative integer and limit must be an integer from 1 to 100');
}
const rows = args.action === 'list_plugins' ? await manager.listPlugins() : await manager.listBundles();
const entries = rows.slice(offset, offset + limit).map(({ meta: _meta, ...row }) => 'rows' in row
// GUI listing and update eligibility do not change the tool's management operations.
? (({ updatable: _updatable, listedByDefault: _listedByDefault, ...bundle }) => ({
...bundle, rows: bundle.rows.map(({ meta: _rowMeta, ...declared }) => declared),
}))(row)
: row);
return JSON.stringify({ entries, total: rows.length,
nextOffset: offset + entries.length < rows.length ? offset + entries.length : null });
}
case 'set_plugin':
case 'set_bundle': {
if (args.target === undefined || args.enabled === undefined)
throw new Error('target and enabled are required');
return JSON.stringify(withNextStep(await (args.action === 'set_plugin'
? manager.setPluginEnabled(args.target, args.enabled)
: manager.setBundleEnabled(args.target, args.enabled))));
}
case 'install_bundle':
if (args.target === undefined)
throw new Error('target package spec is required');
return JSON.stringify(withNextStep(await manager.installBundle(args.target, {
...args.enabled === undefined ? {} : { enabled: args.enabled },
...args.approvedBuilds === undefined ? {} : { approvedBuilds: args.approvedBuilds },
...args.registry === undefined ? {} : { registry: args.registry },
})));
case 'remove_bundle':
if (args.target === undefined)
throw new Error('target bundle name is required');
return JSON.stringify(withNextStep(await manager.removeBundle(args.target)));
/* v8 ignore next -- tool JSON validation rejects actions outside the declared enum */
default: return assertNever(args.action);
}
},
presentCall: args => ({ card: 'generic', title: 'Manage profile plugins', kind: args.action.startsWith('list_') ? 'read' : 'other', rawInput: args }),
}));
}
//# sourceMappingURL=tools.js.map
@@ -1,100 +0,0 @@
import { defineTool } from "@deepseek-ai/dsh-tools";
//#region lib/types/present.js
/**
* Render provider-directory inspection.
* @returns replay-safe generic call presentation.
*/
function presentInspectListCall() {
return {
card: "generic",
kind: "read",
title: "List Cordis Inspect Providers"
};
}
/**
* Render one provider query.
* @param args - target platform, provider, and method.
* @returns replay-safe generic call presentation.
*/
function presentInspectQueryCall(args) {
return {
card: "generic",
kind: "read",
title: `Query Cordis ${args.platform} ${args.provider}.${args.method}`
};
}
//#endregion
//#region lib/types/index.js
const name = "tool-cordis";
const inject = ["tools", "cordisInspect"];
function requireAgent(exec) {
if (exec.agent === void 0) throw new Error("Cordis inspection requires an Agent-backed session");
return exec.agent;
}
/** Register read-only runtime inspection tools over the Host providers that
* `@deepseek-ai/dsh-tool-cordis/host` registers once per process.
* @param ctx Agent-scoped registration context.
*/
function apply(ctx) {
ctx.tools.register(defineTool({
name: "cordis_inspect_list",
description: "List every Cordis Inspect Provider currently known to the Host, including local Host Providers and the latest manifests synchronized from the Client. Each entry includes its platform, purpose, read-only methods, and input/output schemas. Call this Tool before writing or configuring a plugin, then select the provider and method for cordis_inspect_query from its result. Do not guess names or treat an Inspect method as a business Service that Plugin code can call.",
parameters: {},
output: {
schema: { type: "json" },
render: (_args, value) => [{
type: "text",
text: JSON.stringify(value, null, 2)
}]
},
execute(_args, _exec) {
return Promise.resolve({ providers: ctx.cordisInspect.list() });
},
presentCall: presentInspectListCall
}));
ctx.tools.register(defineTool({
name: "cordis_inspect_query",
description: "Run a read-only query declared by an Inspect Provider. platform, provider, and method must come from cordis_inspect_list, and input must satisfy that method's schema. Use this Tool before writing plugin code to read exact Service methods, Event modes, plugin Config schemas, Tool schemas, theme tokens, or live Slot trees and props. Host queries run locally. A Client query waits for the first valid page response within the configured timeout; otherwise it reports a Client failure or asks you to reconnect and retry. This Tool cannot invoke business Service methods or modify the runtime.",
parameters: {
platform: {
type: "string",
required: true,
enum: ["host", "client"],
description: "Runtime platform that owns the Provider."
},
provider: {
type: "string",
required: true,
description: "Exact Provider ID returned by cordis_inspect_list."
},
method: {
type: "string",
required: true,
description: "Exact method name declared by the Provider manifest."
},
input: {
type: "json",
description: "Optional query input; it must satisfy the method input schema."
}
},
output: {
schema: { type: "json" },
render: (_args, value) => [{
type: "text",
text: JSON.stringify(value, null, 2)
}]
},
async execute(args, exec) {
const data = await ctx.cordisInspect.query(args.platform, args.provider, args.method, args.input, requireAgent(exec), exec.signal);
return {
platform: args.platform,
provider: args.provider,
method: args.method,
data
};
},
presentCall: presentInspectQueryCall
}));
}
//#endregion
export { apply, inject, name };
@@ -1,70 +0,0 @@
import { Service } from '@deepseek-ai/cordis'
import { ErrorCode } from '../protocol.ts'
import { RpcError } from '../rpc.ts'
import type { DshAdapter } from './adapters.ts'
const MAX_PATH = 512
const MAX_WRITE = 1024 * 1024
const MAX_ARGV = 9
const MAX_ARG = 1024
function invalid(message: string): never {
throw new RpcError(ErrorCode.InvalidParams, message)
}
function path(value: unknown): string {
if (typeof value !== 'string' || value.length === 0 || value.length > MAX_PATH || value.trim() !== value || /[\x00-\x1f\x7f]/.test(value)) {
invalid(`a path is 1 to ${MAX_PATH} characters on one line with no surrounding spaces`)
}
return value as string
}
function bounded(value: unknown, what: string, min: number, max: number): number | undefined {
if (value === undefined) return undefined
if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) invalid(`${what} is an integer between ${min} and ${max}`)
return value as number
}
function argv(value: unknown): string[] {
if (!Array.isArray(value) || value.length === 0 || value.length > MAX_ARGV || value.some(arg => typeof arg !== 'string' || arg.length > MAX_ARG || /[\x00-\x1f\x7f]/.test(arg))) {
invalid(`argv is 1 to ${MAX_ARGV} strings of at most ${MAX_ARG} characters`)
}
return [...value as string[]]
}
function compact(input: Record<string, unknown>): Record<string, unknown> {
return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined))
}
export const workspaceAdapter: DshAdapter = {
service: 'workspace',
define(host) {
class WorkspaceService extends Service {
constructor(ctx: any) { super(ctx, 'workspace') }
read(file: unknown, options?: { startLine?: unknown, maxLines?: unknown }) {
return host.broker(this.ctx, 'workspace', 'read', compact({
path: path(file),
start_line: bounded(options?.startLine, 'startLine', 1, Number.MAX_SAFE_INTEGER),
max_lines: bounded(options?.maxLines, 'maxLines', 1, 10_000),
}))
}
list(dir?: unknown) {
return host.broker(this.ctx, 'workspace', 'list', compact({ path: dir === undefined ? undefined : path(dir) }))
}
write(file: unknown, content: unknown, options?: { expectedHash?: unknown }) {
if (typeof content !== 'string' || Buffer.byteLength(content) > MAX_WRITE) invalid(`content is a string of at most ${MAX_WRITE} bytes`)
const hash = options?.expectedHash
if (hash !== undefined && (typeof hash !== 'string' || hash.length === 0 || hash.length > 128)) invalid('expectedHash is 1 to 128 characters')
return host.broker(this.ctx, 'workspace', 'write', compact({ path: path(file), content, expected_hash: hash }))
}
exec(command: unknown, options?: { cwd?: unknown }) {
return host.broker(this.ctx, 'workspace', 'exec', compact({
argv: argv(command),
cwd: options?.cwd === undefined ? undefined : path(options.cwd),
}))
}
}
Object.freeze(WorkspaceService.prototype)
return WorkspaceService
},
}
@@ -25,9 +25,6 @@ export const ErrorCode = {
export type Direction = 'core_to_host' | 'host_to_core'
export const DSH_SERVICES = ['workspace', 'llm', 'network', 'settings', 'catalog', 'terminal', 'remote'] as const
export type DshService = typeof DSH_SERVICES[number]
/** Every method either side may send, and the trust tiers it is allowed on; nothing else is admitted. */
export const METHODS = [
{ name: 'host/initialize', direction: 'core_to_host', request: true, params: 'InitializeParams', tiers: ['plugin', 'builtin'] },
@@ -53,7 +50,6 @@ export const METHODS = [
{ name: 'subagent/start', direction: 'host_to_core', request: true, params: 'SubagentStartParams', tiers: ['plugin', 'builtin'] },
{ name: 'subagent/result', direction: 'host_to_core', request: true, params: 'SubagentHandleParams', tiers: ['plugin', 'builtin'] },
{ name: 'subagent/dispose', direction: 'host_to_core', request: true, params: 'SubagentHandleParams', tiers: ['plugin', 'builtin'] },
{ name: 'dsh/broker', direction: 'host_to_core', request: true, params: 'DshBrokerParams', tiers: ['plugin', 'builtin'] },
{ name: 'proc/launch', direction: 'host_to_core', request: true, params: 'ProcLaunchParams', tiers: ['builtin'] },
{ name: 'proc/read', direction: 'host_to_core', request: true, params: 'ProcSessionParams', tiers: ['builtin'] },
{ name: 'proc/write', direction: 'host_to_core', request: true, params: 'ProcWriteParams', tiers: ['builtin'] },
@@ -115,16 +111,6 @@ export const SHAPES: { readonly [name: string]: Shape } = {
required: { owner: { ref: 'OwnerRef' } },
optional: { entry: { ref: 'EntryRef' } },
},
DshBrokerParams: {
strict: true,
required: { owner: { ref: 'OwnerRef' }, ticket: 'string', service: 'string', method: 'string', input: 'json' },
optional: {},
},
DshBrokerTicketWire: {
strict: true,
required: { service: 'string', ticket: 'string' },
optional: {},
},
EmptyParams: {
strict: true,
required: {},
@@ -288,7 +274,7 @@ export const SHAPES: { readonly [name: string]: Shape } = {
ToolCallParams: {
strict: false,
required: { handle: 'uint', call_id: 'string', input: 'json', deadline_ms: 'uint' },
optional: { workspace: 'string', ticket: 'string', checkpoint_ticket: 'string', question_ticket: 'string', subagent_ticket: 'string', broker_tickets: { items: { ref: 'DshBrokerTicketWire' } }, caller_tools: { items: 'string' }, session_id: 'string', agent_id: 'string', origin_turn_id: 'string' },
optional: { workspace: 'string', ticket: 'string', checkpoint_ticket: 'string', question_ticket: 'string', subagent_ticket: 'string', caller_tools: { items: 'string' }, session_id: 'string', agent_id: 'string', origin_turn_id: 'string' },
},
UnregisterParams: {
strict: true,
@@ -369,19 +355,6 @@ export interface DeactivateResult {
leaked: string[]
}
export interface DshBrokerParams {
owner: OwnerRef
ticket: string
service: string
method: string
input: Json
}
export interface DshBrokerTicketWire {
service: string
ticket: string
}
export interface EmptyParams {}
export interface EntryRef {
@@ -619,7 +592,6 @@ export interface ToolCallParams {
checkpoint_ticket?: string
question_ticket?: string
subagent_ticket?: string
broker_tickets?: DshBrokerTicketWire[]
caller_tools?: string[]
session_id?: string
agent_id?: string
+190 -53
View File
@@ -1,5 +1,4 @@
import { ReviewedLoader, installCompositionLoader } from './dsh/composition.ts'
import { DSH_ADAPTERS, type AdapterHost, type DshAdapter } from './dsh/adapters.ts'
/**
* The Cordis root that plugin fibers run under.
*
@@ -32,7 +31,7 @@ import {
type ToolResultWire,
} from './protocol.ts'
import { RpcError, type RpcPeer } from './rpc.ts'
import { UserQuestionError } from './dsh/dsh-message-compat.js'
import { UserQuestionError, PERSONA_PREFIX_SECTION } from './dsh/dsh-message-compat.js'
import { explainImportError } from './dsh/resolve-hooks.ts'
import compatibility from './dsh/compatibility.json' with { type: 'json' }
import { assertSupportedJsonSchema, validateJsonSchemaValue, ToolOutputError } from './dsh/dsh-tools-compat.js'
@@ -69,7 +68,6 @@ export const REFUSED_SERVICES = new Set(compatibility.refused_services)
/** Services the root provides; `inject` of anything else fails activation. */
const PROVIDED_SERVICES = new Set(Object.values(compatibility.provided_services).flat())
const CORDIS_SERVICES = new Set(compatibility.provided_services.cordis)
const ACTIVATE_DEADLINE_MS = 5_000
const DISPOSE_DEADLINE_MS = 2_000
@@ -136,13 +134,12 @@ function withDeadline<T>(promise: Promise<T>, ms: number, label: string): Promis
return Promise.race([promise, deadline]).finally(() => clearTimeout(timer))
}
export interface ToolInvocation {
interface ToolInvocation {
owner: OwnerRecord
session: object | undefined
agent: object | undefined
questionTicket: string | undefined
subagentTicket: string | undefined
brokerTickets: ReadonlyMap<string, string>
callerTools: readonly string[]
delegated: boolean
ticket: string | undefined
@@ -168,7 +165,6 @@ export class HostRoot {
private readonly rpc: RpcPeer,
/** The trust tier this process serves; it activates only owners of that tier. */
readonly tier: HostTier,
adapters: readonly DshAdapter[] = DSH_ADAPTERS,
) {
const root: any = new Context()
this.root = root
@@ -303,6 +299,28 @@ export class HostRoot {
set(key: string, value: Json) { return this.api().set(key, value) }
delete(key: string) { return this.api().delete(key) }
}
class SessionsShim extends Service {
constructor(ctx: any) { super(ctx, 'sessions') }
async flush(session: unknown): Promise<boolean> {
const invocation = host.toolInvocations.getStore()
const owner: OwnerRecord | undefined = (this.ctx as any)[OWNER]
const live = () => invocation && invocation.active && !invocation.signal.aborted
&& invocation.owner === owner && owner?.state === 'active' && !owner.disposing
&& invocation.ticket !== undefined && session === invocation.session && session !== undefined
if (!live()) throw new RpcError(ErrorCode.NotAvailable, 'sessions.flush requires this live tool invocation’s session')
const call = invocation!
const run = async () => {
if (!live()) throw new RpcError(ErrorCode.NotAvailable, 'session checkpoint invocation ended')
const result = await host.rpc.request<unknown>('session/checkpoint', { owner: call.owner.ref, ticket: call.ticket }, call.signal)
if (!live()) throw new RpcError(ErrorCode.NotAvailable, 'session checkpoint invocation ended')
if (typeof result !== 'boolean') throw new RpcError(ErrorCode.Internal, 'invalid session checkpoint receipt')
return result
}
const result = call.pending.then(run)
call.pending = result.then(() => undefined, () => undefined)
return result
}
}
class UserQuestionsShim extends Service {
constructor(ctx: any) { super(ctx, 'userQuestions') }
async ask(request: { agent?: unknown; questions: unknown; signal?: AbortSignal; wait?: unknown }) {
@@ -417,52 +435,175 @@ export class HostRoot {
return Promise.race([result, cancelled]).finally(() => signal.removeEventListener('abort', cancel))
}
}
Object.freeze(UserQuestionsShim.prototype)
Object.freeze(StorageShim.prototype)
const adapterHost: AdapterHost = {
tier,
rpc,
ownerOf: (ctx) => (ctx as { [OWNER]?: OwnerRecord })[OWNER],
liveInvocation: (ctx) => {
const SPAWN_PROVIDER = Object.freeze({
name: 'spawn',
inheritsParentContext: false,
capabilities: Object.freeze({ persona: true, toolFilter: true, agentOptions: true }),
})
const PERSONA_ORDER = 0
class SubagentsShim extends Service {
constructor(ctx: any) { super(ctx, 'subagents') }
getProvider(name: unknown) { return name === 'spawn' ? SPAWN_PROVIDER : undefined }
async startActivation(request: any) {
const invocation = host.toolInvocations.getStore()
const owner: OwnerRecord | undefined = (ctx as { [OWNER]?: OwnerRecord })[OWNER]
return invocation && invocation.active && !invocation.signal.aborted && owner !== undefined
&& invocation.owner === owner && owner.state === 'active' && !owner.disposing
? invocation
: undefined
},
log: (level, message, owner) => host.log(level, message, owner),
broker: async (ctx, service, method, input) => {
const invocation = adapterHost.liveInvocation(ctx)
const ticket = invocation?.brokerTickets.get(service)
if (invocation === undefined || ticket === undefined) throw new RpcError(ErrorCode.NotAvailable, `the ${String(service).slice(0, 64)} broker is only available to a live tool invocation the core gave a ticket for it`)
return rpc.request<unknown>('dsh/broker', { owner: invocation.owner.ref, ticket, service, method, input }, invocation.signal)
},
const owner: OwnerRecord | undefined = (this.ctx as any)[OWNER]
const plain = (value: unknown, allowed: string[], what: string): Record<string, unknown> => {
if (value === null || typeof value !== 'object' || Array.isArray(value)
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new RpcError(ErrorCode.InvalidParams, `expected a plain ${what} object`)
const result: Record<string, unknown> = Object.create(null)
for (const key of Reflect.ownKeys(value)) {
const descriptor = Object.getOwnPropertyDescriptor(value, key)!
if (typeof key !== 'string' || !allowed.includes(key) || !('value' in descriptor)) throw new RpcError(ErrorCode.NotAvailable, `unsupported ${what} property ${String(key)}`)
if (descriptor.value !== undefined) result[key] = descriptor.value
}
return result
}
const input = plain(request, ['provider', 'label', 'childId', 'request', 'signal', 'delivery'], 'activation')
if (input.provider !== 'spawn') throw new RpcError(ErrorCode.NotAvailable, 'only the spawn provider is available')
const spawn = plain(input.request, ['parent', 'prompt', 'agentOptions'], 'spawn request')
const options = spawn.agentOptions === undefined ? {} : plain(spawn.agentOptions, ['model'], 'agentOptions')
if (options.model !== undefined && typeof options.model !== 'string') throw new RpcError(ErrorCode.InvalidParams, 'agentOptions.model must be a string')
const delivery = input.delivery === undefined ? 'parent' : input.delivery
if (delivery !== 'caller' && delivery !== 'parent') throw new RpcError(ErrorCode.InvalidParams, 'delivery must be caller or parent')
const childId = input.childId
if (typeof childId !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/.test(childId)) throw new RpcError(ErrorCode.InvalidParams, 'childId must be 1-128 letters, digits, or _.:-')
if (!Array.isArray(spawn.prompt) || spawn.prompt.length === 0) throw new RpcError(ErrorCode.InvalidParams, 'prompt must be a non-empty content array')
const prompt = spawn.prompt.map((block: unknown) => {
const item = plain(block, ['type', 'text'], 'prompt block')
if (item.type !== 'text' || typeof item.text !== 'string') throw new RpcError(ErrorCode.NotAvailable, 'only text prompt blocks are supported')
return item.text
}).join('')
if (input.signal !== undefined && !(input.signal instanceof AbortSignal)) throw new RpcError(ErrorCode.InvalidParams, 'signal must be an AbortSignal')
if (!invocation || !invocation.active || invocation.signal.aborted || invocation.agent === undefined || spawn.parent !== invocation.agent) {
throw new RpcError(ErrorCode.NotAvailable, 'startActivation requires the exact live calling agent as parent')
}
if (invocation.owner !== owner || owner?.state !== 'active' || owner.disposing) throw new RpcError(ErrorCode.NotAvailable, 'subagents service owner is no longer current')
if (invocation.delegated || invocation.subagentTicket === undefined) throw new RpcError(ErrorCode.NotAvailable, 'child agents are only available to a root tool invocation')
const signal = input.signal === undefined ? invocation.signal : AbortSignal.any([invocation.signal, input.signal as AbortSignal])
signal.throwIfAborted()
let persona: string | undefined
const denied = new Set<string>()
let open = true
const sealed = () => { if (!open) throw new RpcError(ErrorCode.NotAvailable, 'the child creation window has closed') }
const child = Object.freeze({
id: childId,
ctx: Object.freeze({
systemPrompt: Object.freeze({
getSectionOrder(name: unknown) {
sealed()
if (name !== 'DEPLOYMENT_PERSONA_PREFIX') throw new RpcError(ErrorCode.NotAvailable, 'only the deployment persona slot is available')
return PERSONA_ORDER
},
section(section: unknown) {
sealed()
const value = plain(section, ['name', 'order', 'text'], 'system prompt section')
if (value.name !== PERSONA_PREFIX_SECTION || value.order !== PERSONA_ORDER || typeof value.text !== 'string') {
throw new RpcError(ErrorCode.NotAvailable, 'only the child deployment persona section is supported')
}
if (persona !== undefined) throw new RpcError(ErrorCode.InvalidParams, 'the child persona is already set')
if (Buffer.byteLength(value.text) > 32 * 1024) throw new RpcError(ErrorCode.InvalidParams, 'child persona exceeds 32768 bytes')
persona = value.text
return () => undefined
},
}),
tools: Object.freeze({
restrict(filter: unknown) {
sealed()
const value = plain(filter, ['deny'], 'tool filter')
if (!Array.isArray(value.deny) || value.deny.some(name => typeof name !== 'string' || name === '')) throw new RpcError(ErrorCode.InvalidParams, 'deny must be a list of tool names')
for (const name of value.deny as string[]) denied.add(name)
return () => undefined
},
}),
}),
})
const listeners = ((host.root as any).events?._hooks?.['agent/created'] ?? [])
.filter((hook: any) => !hook.global && hook.ctx?.[OWNER] === owner)
.map((hook: any) => hook.callback)
try {
await Promise.all(listeners.map(async (callback: Function) => callback({ agent: child })))
} finally {
open = false
}
signal.throwIfAborted()
const call = invocation
const rpc = (method: string, params: Record<string, unknown>, abort: AbortSignal) =>
host.rpc.request<any>(method, { owner: call.owner.ref, ticket: call.subagentTicket, child_id: childId, ...params }, abort)
const started = await rpc('subagent/start', {
prompt,
...(options.model === undefined ? {} : { model: options.model }),
...(persona === undefined ? {} : { persona }),
denied_tools: [...denied],
delivery,
}, signal)
if (started === null || typeof started !== 'object' || started.child_id !== childId || typeof started.message_id !== 'string') {
throw new RpcError(ErrorCode.Internal, 'invalid child activation receipt')
}
let result: Promise<unknown> | undefined
let disposed: Promise<void> | undefined
return Object.freeze({
childId,
messageId: started.message_id,
get result() {
result ??= rpc('subagent/result', {}, call.signal).then((value: any) => {
if (value === null || typeof value !== 'object' || typeof value.stop_reason !== 'string' || !Array.isArray(value.output)) {
throw new RpcError(ErrorCode.Internal, 'invalid child result receipt')
}
return Object.freeze({
stopReason: value.stop_reason,
output: Object.freeze(value.output.map((block: any) => Object.freeze({ type: 'text', text: String(block.text) }))),
...(value.omitted_blocks > 0 ? { diagnostic: `${value.omitted_blocks} non-text output block(s) are not supported` } : {}),
})
})
return result
},
dispose() {
disposed ??= rpc('subagent/dispose', {}, call.signal).then(() => undefined)
return disposed
},
})
}
}
const shims = new Map<string, new (ctx: any) => Service>([
['tools', ToolsShim],
['commands', CommandsShim],
['prompt', PromptShim],
['storage', StorageShim],
['userQuestions', UserQuestionsShim],
['skills', SkillsShim],
['avatars', AvatarsShim],
['mcp', McpShim],
['shellHooks', ShellHooksShim],
])
for (const adapter of adapters) {
if (shims.has(adapter.service)) throw new Error(`DSH adapter for \`${adapter.service}\` duplicates a service the host root already provides`)
shims.set(adapter.service, adapter.define(adapterHost))
class AgentsShim extends Service {
constructor(ctx: any) { super(ctx, 'agents') }
}
const mismatched = [
...[...shims.keys()].filter((name) => !PROVIDED_SERVICES.has(name)).map((name) => `${name} is installed but not declared in compatibility.json`),
...[...PROVIDED_SERVICES].filter((name) => !CORDIS_SERVICES.has(name) && !shims.has(name)).map((name) => `${name} is declared in compatibility.json but has no installed service`),
]
if (mismatched.length > 0) throw new Error(`DSH provided services disagree with the installed services: ${mismatched.join('; ')}`)
for (const [name, shim] of shims) {
shimClasses.set(name, shim)
root.plugin(shim)
class SystemPromptShim extends Service {
constructor(ctx: any) { super(ctx, 'systemPrompt') }
section() { throw new RpcError(ErrorCode.NotAvailable, "system prompt sections are only available on a child agent's agent/created context") }
getSectionOrder() { throw new RpcError(ErrorCode.NotAvailable, "system prompt sections are only available on a child agent's agent/created context") }
}
Object.freeze(SubagentsShim.prototype)
Object.freeze(AgentsShim.prototype)
Object.freeze(SystemPromptShim.prototype)
Object.freeze(UserQuestionsShim.prototype)
Object.freeze(SessionsShim.prototype)
Object.freeze(StorageShim.prototype)
shimClasses.set('tools', ToolsShim)
shimClasses.set('commands', CommandsShim)
shimClasses.set('prompt', PromptShim)
shimClasses.set('storage', StorageShim)
shimClasses.set('sessions', SessionsShim)
shimClasses.set('userQuestions', UserQuestionsShim)
shimClasses.set('subagents', SubagentsShim)
shimClasses.set('agents', AgentsShim)
shimClasses.set('systemPrompt', SystemPromptShim)
shimClasses.set('skills', SkillsShim)
shimClasses.set('avatars', AvatarsShim)
shimClasses.set('mcp',McpShim)
shimClasses.set('shellHooks',ShellHooksShim)
root.plugin(ToolsShim)
root.plugin(CommandsShim)
root.plugin(PromptShim)
root.plugin(StorageShim)
root.plugin(SessionsShim)
root.plugin(UserQuestionsShim)
root.plugin(SubagentsShim)
root.plugin(AgentsShim)
root.plugin(SystemPromptShim)
root.plugin(SkillsShim)
root.plugin(AvatarsShim)
root.plugin(McpShim)
root.plugin(ShellHooksShim)
shimClasses.set('loader', ReviewedLoader)
installCompositionLoader(root)
}
@@ -573,9 +714,7 @@ export class HostRoot {
const plugin = pickPlugin(module)
const missing = Object.keys(Inject.resolve(plugin.inject)).filter((name) => !PROVIDED_SERVICES.has(name))
if (missing.length > 0) {
const owned = missing.filter((name) => REFUSED_SERVICES.has(name))
throw new Error(`requires ${missing.map((name) => `\`${name}\``).join(', ')}, not provided by the Codewhale extension host in this phase`
+ (owned.length > 0 ? `; ${owned.map((name) => `\`${name}\``).join(', ')} belong${owned.length === 1 ? 's' : ''} to the Codewhale core and no reviewed bridge exposes ${owned.length === 1 ? 'it' : 'them'} yet` : ''))
throw new Error(`requires ${missing.map((name) => `\`${name}\``).join(', ')}, not provided by the Codewhale extension host in this phase`)
}
const ownerCtx = this.root.extend({ [OWNER]: owner })
const fiber = ownerStorage.run(owner, () => ownerCtx.plugin(plugin, params.config ?? {}))
@@ -734,7 +873,6 @@ export class HostRoot {
agent,
questionTicket: identity?.question_ticket,
subagentTicket: identity?.subagent_ticket,
brokerTickets: new Map((identity?.broker_tickets ?? []).map(({ service, ticket }) => [service, ticket])),
callerTools: Object.freeze([...(identity?.caller_tools ?? [])]),
delegated: identity?.agent_id !== undefined,
ticket: identity?.checkpoint_ticket,
@@ -805,7 +943,6 @@ export class HostRoot {
interface InvocationIdentityWire {
question_ticket?: string
subagent_ticket?: string
broker_tickets?: { service: string, ticket: string }[]
caller_tools?: string[]
checkpoint_ticket?: string
session_id?: string
@@ -1,71 +0,0 @@
import { test, before } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { build } from 'esbuild'
const here = dirname(fileURLToPath(import.meta.url))
const rpc = { request: async () => ({}), notify: () => {}, tier: 'plugin' }
let HostRoot
let Service
let DSH_ADAPTERS
before(async () => {
const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-adapters-'))
const outfile = join(dir, 'root.mjs')
await build({
entryPoints: [join(here, '../src/root.ts')],
outfile,
bundle: true,
platform: 'node',
format: 'esm',
packages: 'external',
absWorkingDir: join(here, '..'),
logLevel: 'silent',
})
const adapters = join(dir, 'adapters.mjs')
await build({
entryPoints: [join(here, '../src/dsh/adapters.ts')],
outfile: adapters,
bundle: true,
platform: 'node',
format: 'esm',
packages: 'external',
absWorkingDir: join(here, '..'),
logLevel: 'silent',
})
;({ HostRoot } = await import(pathToFileURL(outfile).href))
;({ DSH_ADAPTERS } = await import(pathToFileURL(adapters).href))
;({ Service } = await import('@deepseek-ai/cordis'))
process.on('exit', () => rmSync(dir, { recursive: true, force: true }))
})
const adapterFor = (service) => ({ service, define: () => class extends Service { constructor(ctx) { super(ctx, service) } } })
test('the shipped adapter table holds the reviewed adapters, and the root still builds', () => {
assert.deepEqual(DSH_ADAPTERS.map((adapter) => adapter.service), ['sessions', 'systemPrompt', 'subagents', 'agents', 'remote'])
assert.ok(new HostRoot(rpc, 'plugin'))
assert.ok(new HostRoot(rpc, 'builtin'))
})
test('an adapter for a service compatibility.json does not declare is refused at construction', () => {
assert.throws(() => new HostRoot(rpc, 'plugin', [...DSH_ADAPTERS, adapterFor('llm')]), /llm is installed but not declared in compatibility\.json/)
})
test('an adapter may not replace a service the root already provides', () => {
assert.throws(() => new HostRoot(rpc, 'plugin', [adapterFor('storage')]), /duplicates a service the host root already provides/)
assert.throws(() => new HostRoot(rpc, 'plugin', [...DSH_ADAPTERS, adapterFor('sessions')]), /duplicates a service/)
})
test('the adapter broker refuses locally, without sending, when no live invocation holds a ticket for the service', async () => {
const sent = []
const peer = { ...rpc, request: async (method, params) => { sent.push([method, params]); return {} } }
let host
const capture = { service: 'llm', define: (adapterHost) => { host = adapterHost; return adapterFor('llm').define() } }
assert.throws(() => new HostRoot(peer, 'plugin', [capture]), /not declared in compatibility\.json/)
for (const service of ['workspace', 'llm', 'vault']) {
await assert.rejects(host.broker({}, service, 'read', {}), (error) => error.code === -32001 && /broker is only available to a live tool invocation/.test(error.message))
}
assert.deepEqual(sent, [])
})
@@ -1,72 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { activate, startHost } from './harness.mjs'
import { ErrorCode } from '../dist/protocol.mjs'
const PLUGIN = `
export const inject = ['tools', 'subagents', 'agents']
export function apply(ctx) {
ctx.on('agent/created', ({ agent }) => {
agent.ctx.systemPrompt.section({ name: 'deployment:persona-prefix', order: agent.ctx.systemPrompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX'), text: 'Reviewer persona' })
agent.ctx.tools.restrict({ deny: ['exec_shell'] })
})
ctx.tools.register({ name: 'team_start', description: 'Start one child agent.', parameters: { type: 'object' },
async execute(input, exec) {
try {
const parent = input.forged ? { id: exec.agent?.id } : exec.agent
const handle = await ctx.subagents.startActivation({
provider: 'spawn', childId: input.childId ?? 'reviewer-1', delivery: 'caller',
request: { parent, prompt: [{ type: 'text', text: 'Review the diff' }] },
})
const result = await handle.result
await handle.dispose()
return { messageId: handle.messageId, stopReason: result.stopReason, text: result.output.map(block => block.text).join('') }
} catch (error) {
return { refused: error.code ?? String(error) }
}
},
})
}
`
test('the agents adapters serve subagents and agents through the reviewed adapter table', async (t) => {
const host = await startHost({
subagent: (params, _id, method) => method === 'subagent/start'
? { child_id: params.child_id, message_id: 'message-1' }
: method === 'subagent/result'
? { stop_reason: 'end_turn', output: [{ type: 'text', text: 'looks good' }], omitted_blocks: 0 }
: {},
})
t.after(() => host.stop())
const dir = mkdtempSync(join(tmpdir(), 'cw-agents-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
const entry = join(dir, 'index.mjs')
writeFileSync(entry, PLUGIN)
const { ref, result } = await activate(host, 'agent-team', entry)
assert.deepEqual(result, { status: 'ok', tools: ['team_start'], commands: [] })
const handle = host.registry.find(row => row.op === 'register' && row.spec.name === 'team_start').handle
const call = (input, identity) => host.call('tool/call', { handle, call_id: 'team', input, deadline_ms: 5000, ...identity })
const root = { session_id: 'session-root', workspace: '/workspace/team', subagent_ticket: 'subagent-ticket-1' }
assert.deepEqual((await call({}, root)).structured, { messageId: 'message-1', stopReason: 'end_turn', text: 'looks good' })
assert.deepEqual(host.subagents.map(row => row.method), ['subagent/start', 'subagent/result', 'subagent/dispose'])
const [start] = host.subagents
assert.deepEqual(start.owner, ref)
assert.equal(start.ticket, 'subagent-ticket-1')
assert.equal(start.child_id, 'reviewer-1')
assert.equal(start.prompt, 'Review the diff')
assert.equal(start.persona, 'Reviewer persona')
assert.deepEqual(start.denied_tools, ['exec_shell'])
assert.equal(start.delivery, 'caller')
assert.ok(host.subagents.every(row => row.ticket === 'subagent-ticket-1' && row.child_id === 'reviewer-1'))
const before = host.subagents.length
assert.deepEqual((await call({}, { ...root, agent_id: 'agent-child' })).structured, { refused: ErrorCode.NotAvailable }, 'a delegated caller cannot nest child agents')
assert.deepEqual((await call({}, { session_id: 'session-root', workspace: '/workspace/team' })).structured, { refused: ErrorCode.NotAvailable }, 'no subagent ticket, no child')
assert.deepEqual((await call({ forged: true }, root)).structured, { refused: ErrorCode.NotAvailable }, 'a forged parent is not the live caller')
assert.deepEqual((await call({ childId: 'bad id' }, root)).structured, { refused: ErrorCode.InvalidParams })
assert.equal(host.subagents.length, before, 'refused activations never reach the core')
})
@@ -1,48 +0,0 @@
import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { dirname, join, relative, sep } from 'node:path'
import { test } from 'node:test'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const pin = join(here, '..', 'src', 'dsh', 'upstream', 'creator')
const manifest = JSON.parse(readFileSync(join(pin, 'UPSTREAM.json'), 'utf8'))
const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex')
function walk(dir) {
return readdirSync(dir).flatMap((name) => {
const path = join(dir, name)
return statSync(path).isDirectory() ? walk(path) : [path]
})
}
test('every pinned creator file equals its recorded hash and is verbatim', () => {
assert.equal(manifest.version, '0.2.2-rc.1')
assert.ok(manifest.files.length >= 2)
for (const entry of manifest.files) {
assert.equal(entry.verbatim, true, entry.path)
const bytes = readFileSync(join(pin, entry.path))
assert.equal(bytes.length, entry.bytes, `${entry.path} size`)
assert.equal(sha256(bytes), entry.sha256, `${entry.path} hash`)
assert.ok(!bytes.includes(13), `${entry.path} must keep LF line endings`)
}
})
test('the pin directory holds exactly the files the manifest lists', () => {
const listed = new Set([...manifest.files.map((entry) => entry.path), 'UPSTREAM.json', 'LICENSE', 'README.md'])
const present = walk(pin).map((path) => relative(pin, path).split(sep).join('/'))
assert.deepEqual(present.sort(), [...listed].sort())
})
test('the licence is the MIT text the four packages ship', () => {
const license = readFileSync(join(pin, 'LICENSE'))
assert.equal(sha256(license), manifest.license_sha256)
assert.match(license.toString('utf8'), /^MIT License\n\nCopyright \(c\) 2026 DeepSeek\n/)
assert.deepEqual(manifest.packages.sort(), [
'@deepseek-ai/dsh-agent-preset',
'@deepseek-ai/dsh-plugin-manager',
'@deepseek-ai/dsh-sandbox',
'@deepseek-ai/dsh-tool-cordis',
])
})
+5 -10
View File
@@ -51,7 +51,7 @@ export const LIMITS = { max_frame: 32 * 1024 * 1024, max_inflight: 256, dispose_
* cancelled is not answered. Requests are recorded in `coreCalls`, the host's
* `$/cancel` ids in `cancels`.
*/
export async function startHost({ admit, env, ownGroup = false, tier = 'plugin', coreCall, checkpoint, userQuestions, subagent, compiledHost, cwd } = {}) {
export async function startHost({ admit, env, ownGroup = false, tier = 'plugin', coreCall, checkpoint, userQuestions, compiledHost, cwd } = {}) {
const started = performance.now()
// `ownGroup` spawns the host as a process-group leader and tells it so, as
// the Rust core does on Unix.
@@ -73,7 +73,6 @@ export async function startHost({ admit, env, ownGroup = false, tier = 'plugin',
coreCalls: [],
checkpoints: [],
questions: [],
subagents: [],
cancels: [],
registry: [],
hello: null,
@@ -147,15 +146,11 @@ export async function startHost({ admit, env, ownGroup = false, tier = 'plugin',
break
case 'session/checkpoint':
case 'user-questions/ask':
case 'subagent/start':
case 'subagent/result':
case 'subagent/dispose':
case 'core/call': {
const childRequest = message.method.startsWith('subagent/')
const handler = message.method === 'session/checkpoint' ? checkpoint : message.method === 'user-questions/ask' ? userQuestions : childRequest ? subagent : coreCall
const records = message.method === 'session/checkpoint' ? host.checkpoints : message.method === 'user-questions/ask' ? host.questions : childRequest ? host.subagents : host.coreCalls
records.push({ id: message.id, ...(childRequest ? { method: message.method } : {}), ...message.params })
const answer = handler ? handler(message.params, message.id, message.method) : { error: { code: -32002, message: 'no handler for ' + message.method } }
const handler = message.method === 'session/checkpoint' ? checkpoint : message.method === 'user-questions/ask' ? userQuestions : coreCall
const records = message.method === 'session/checkpoint' ? host.checkpoints : message.method === 'user-questions/ask' ? host.questions : host.coreCalls
records.push({ id: message.id, ...message.params })
const answer = handler ? handler(message.params, message.id) : { error: { code: -32002, message: 'no handler for ' + message.method } }
const id = message.id
Promise.resolve(answer).then((value) => {
if (host.cancels.includes(id) || child.exitCode !== null || stopping) return
@@ -174,7 +174,6 @@ test('injecting a service the host does not provide fails with its name', async
const { result } = await activate(host, 'needs-secrets', plugin.entry)
assert.equal(result.status, 'failed')
assert.match(result.diagnostic, /requires `secrets`/)
assert.doesNotMatch(result.diagnostic, /belongs? to the Codewhale core/)
const provided = tempPlugin("export const inject = ['shellHooks', 'sessions', 'userQuestions']; export function apply(ctx) { if (!ctx.shellHooks || typeof ctx.sessions.flush !== 'function' || typeof ctx.userQuestions.ask !== 'function') throw new Error('missing provided service') }\n")
t.after(() => provided.cleanup())
const available = await activate(host, 'needs-shell-hooks', provided.entry)
@@ -188,7 +187,6 @@ export function apply() { createUserMessage({ content: [], source: { kind: 'fixt
const refused = (await activate(host, `pure-needs-${service}`, pure.entry)).result
assert.equal(refused.status, 'failed')
assert.ok(refused.diagnostic.includes('requires `' + service + '`'), refused.diagnostic)
assert.match(refused.diagnostic, /`llm` belongs to the Codewhale core and no reviewed bridge exposes it yet/)
}
})
@@ -1,213 +0,0 @@
import assert from 'node:assert/strict'
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { build } from 'esbuild'
import { dirname, join } from 'node:path'
import { after, test } from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { buildCatalog, parseSeatTable, renderCatalog } from '../scripts/gen-inspect-catalog.mjs'
import { createCordisInspect } from '../src/dsh/inspect.ts'
const here = dirname(fileURLToPath(import.meta.url))
const src = (path) => join(here, '..', 'src', path)
const text = (path) => readFileSync(path, 'utf8').replace(/\r\n/g, '\n')
const compatibility = JSON.parse(text(src('dsh/compatibility.json')))
const catalog = JSON.parse(text(src('dsh/inspect-catalog.json')))
const seatSource = text(join(here, '..', '..', '..', 'app-server', 'src', 'runtime_api', 'plugins.rs'))
const rootSource = text(src('root.ts'))
const inspect = createCordisInspect()
const ask = (platform, provider, method, input) => inspect.query(platform, provider, method, input)
test('the committed catalog is what the generator writes now', () => {
assert.equal(text(src('dsh/inspect-catalog.json')), renderCatalog(buildCatalog()))
})
test('list names the providers DSH calls and leaves out Tool until a source exists', async () => {
const ids = inspect.list().map((p) => `${p.platform}.${p.id}.${p.methods.map((m) => m.name).join(',')}`)
assert.deepEqual(ids, ['host.Service.listService', 'host.Event.listEvents', 'host.Config.listConfigs', 'client.Slots.listSubTree', 'client.Theme.listTokens'])
const withTools = createCordisInspect({ tools: () => [{ name: 'read_file' }] })
assert.ok(withTools.list().some((p) => p.id === 'Tool'))
assert.deepEqual(await withTools.query('host', 'Tool', 'listTools', undefined, {}), { tools: [{ name: 'read_file' }] })
})
test('errors use DSH registry wording', async () => {
await assert.rejects(ask('host', 'Nope', 'x'), /Host Cordis inspect provider "Nope" is not registered/)
await assert.rejects(ask('client', 'Nope', 'x'), /Client Cordis inspect provider "Nope" is not registered/)
await assert.rejects(ask('host', 'Service', 'nope'), /Cordis inspect provider "Service" has no method "nope"/)
await assert.rejects(ask('host', 'Service', 'listService', { service: 3 }), /Host Cordis inspect Service.listService rejected input/)
await assert.rejects(ask('host', 'Tool', 'listTools'), /not registered/)
await assert.rejects(ask('page', 'Service', 'listService'), /platform must be/)
})
test('every service the catalog names is provided, and no provided service is missing', () => {
const provided = Object.values(compatibility.provided_services).flat().sort()
assert.deepEqual(catalog.host.services.map((s) => s.key).sort(), provided)
assert.deepEqual(catalog.host.refusedServices, compatibility.refused_services)
})
test('methods match the compatibility tables where it has them', () => {
const tables = { sessions: 'session_methods', userQuestions: 'user_question_methods', subagents: 'subagent_methods', agents: 'agents_methods', systemPrompt: 'system_prompt_methods' }
for (const [service, table] of Object.entries(tables)) {
const named = catalog.host.services.find((s) => s.key === service).methods.map((m) => m.name).sort()
assert.deepEqual(named, Object.keys(compatibility[table]).sort(), service)
}
})
const classBody = (source, name) => {
const start = source.indexOf(`class ${name} extends Service`)
assert.ok(start >= 0, `class ${name}`)
const rest = source.slice(start + 1)
const next = rest.search(/\n\s*(export )?(class |function )/)
return next < 0 ? rest : rest.slice(0, next)
}
const defines = (body, name) => new RegExp(`^\\s*(async\\s+)?${name}\\s*\\(`, 'm').test(body)
test('every curated method is defined on the class that serves it', () => {
const served = {
tools: ['root.ts', 'ToolsShim'], commands: ['shims/commands.ts', 'CommandsShim'], storage: ['root.ts', 'StorageShim'],
skills: ['shims/skills.ts', 'SkillsShim'], prompt: ['shims/prompt.ts', 'PromptShim'], avatars: ['shims/avatars.ts', 'AvatarsShim'],
mcp: ['shims/mcp.ts', 'McpShim'], shellHooks: ['shims/shell-hooks.ts', 'ShellHooks'], remote: ['dsh/remote.ts', 'RemoteService'],
sessions: ['dsh/session-prompt.ts', 'SessionsService'], userQuestions: ['root.ts', 'UserQuestionsShim'],
subagents: ['dsh/agents.ts', 'SubagentsShim'], systemPrompt: ['dsh/session-prompt.ts', 'SystemPromptService'],
}
const cordis = { events: ['events', ['on', 'once', 'emit']], reflect: ['reflect', ['provide', 'get']], registry: ['registry', ['get', 'resolve']] }
const agentsSource = text(src('dsh/agents.ts'))
for (const service of catalog.host.services) {
if (service.key === 'logger' || service.key === 'agents') continue
if (cordis[service.key]) {
const [file, names] = cordis[service.key]
const body = text(join(here, '..', 'node_modules', '@deepseek-ai', 'cordis', 'lib', 'types', `${file}.d.ts`))
assert.deepEqual(service.methods.map((m) => m.name).sort(), [...names].sort(), service.key)
for (const name of names) assert.ok(defines(body, name), `${service.key}.${name}`)
continue
}
const [file, cls] = served[service.key]
const body = classBody(text(src(file)), cls)
for (const m of service.methods) {
if (service.key === 'subagents' && m.name === 'result') assert.match(agentsSource, /^\s*get result\(\)/m, 'subagents.result is a getter')
else if (service.key === 'subagents' && m.name === 'dispose') assert.match(agentsSource, /^\s*dispose\(\)/m, 'subagents.dispose')
else assert.ok(defines(body, m.name), `${service.key}.${m.name}`)
}
}
assert.match(agentsSource, /^\s*section\(section: unknown\)/m)
assert.match(agentsSource, /^\s*getSectionOrder\(name: unknown\)/m)
})
test('the catalog states the contracts the host actually enforces', () => {
const agentsSource = text(src('dsh/agents.ts'))
const personaName = text(src('dsh/dsh-message-compat.js')).match(/PERSONA_PREFIX_SECTION = "([^"]+)"/)[1]
const section = catalog.host.services.find((s) => s.key === 'systemPrompt').methods[0]
assert.ok(section.signature.includes(`name: '${personaName}'`))
assert.ok(section.signature.includes("getSectionOrder('DEPLOYMENT_PERSONA_PREFIX')"))
assert.match(agentsSource, /PERSONA_ORDER = 0/)
const subagents = catalog.host.services.find((s) => s.key === 'subagents').methods
const result = subagents.find((m) => m.name === 'result')
assert.match(result.signature, /^activation\.result: Promise<\{ stopReason: string, output: \{ type: 'text', text: string \}\[\]/)
assert.ok(!result.signature.includes('result()'))
assert.match(subagents.find((m) => m.name === 'startActivation').signature, /Promise<\{ childId: string, messageId: string, result: Promise</)
})
test('an output that is not JSON is refused as DSH refuses it', async () => {
const bad = createCordisInspect({ tools: () => [{ name: 'x', extra: undefined }] })
await assert.rejects(bad.query('host', 'Tool', 'listTools', undefined, {}), /returned a non-JSON value/)
})
test('every slot and its seat equal the Engine seat table', () => {
const block = seatSource.slice(seatSource.indexOf('const DSH_SEAT_TABLE'), seatSource.indexOf('];', seatSource.indexOf('const DSH_SEAT_TABLE')))
const names = [...block.matchAll(/\(\s*"([^"]+)",\s*DshSeat::/g)].map((m) => m[1])
assert.equal(names.length, 30)
assert.deepEqual(catalog.client.slots.map((s) => s.slot), names)
const unsupported = [...block.matchAll(/\(\s*"([^"]+)",\s*DshSeat::Unsupported/g)].map((m) => m[1])
assert.deepEqual(catalog.client.slots.filter((s) => !s.supported).map((s) => s.slot), unsupported)
const seats = [...seatSource.slice(seatSource.indexOf('const PLUGIN_UI_SEATS'), seatSource.indexOf('];', seatSource.indexOf('const PLUGIN_UI_SEATS'))).matchAll(/"([^"]+)"/g)].map((m) => m[1])
for (const slot of catalog.client.slots.filter((s) => s.supported)) assert.ok(slot.seat === 'customize.plugins.detail' || seats.includes(slot.seat), slot.slot)
assert.equal(catalog.client.seats.length, 6)
assert.deepEqual(parseSeatTable(seatSource.replace(/\n/g, '\r\n')), parseSeatTable(seatSource))
})
test('the refused events equal the list in root.ts', () => {
const body = rootSource.slice(rootSource.indexOf('unsupportedDshLifecycle = new Set(['), rootSource.indexOf('])', rootSource.indexOf('unsupportedDshLifecycle = new Set([')))
const refused = [...body.matchAll(/'([^']+)'/g)].map((m) => m[1])
assert.equal(refused.length, 5)
assert.deepEqual(catalog.host.events.filter((e) => e.status === 'refused').map((e) => e.name), refused)
for (const name of catalog.host.events.filter((e) => e.status === 'supported').map((e) => e.name)) assert.ok(rootSource.includes(`'${name}'`) || text(src('dsh/agents.ts')).includes(`'${name}'`), name)
})
test('the Service provider answers a directory, one contract, and refuses a name the host lacks', async () => {
const directory = await ask('host', 'Service', 'listService')
assert.equal(directory.services.length, 18)
assert.ok(!directory.services.some((s) => s.key === 'fs' || s.key === 'llm'))
const one = await ask('host', 'Service', 'listService', { service: 'prompt' })
assert.equal(one.service.methods[0].name, 'registerSection')
await assert.rejects(ask('host', 'Service', 'listService', { service: 'llm' }), /not provided by this host/)
})
test('the Event provider separates supported from refused', async () => {
const { events } = await ask('host', 'Event', 'listEvents')
assert.deepEqual(events.map((e) => e.status), ['supported', 'supported', 'refused', 'refused', 'refused', 'refused', 'refused'])
assert.equal((await ask('host', 'Event', 'listEvents', { event: 'tools/pre-execute' })).event.name, 'tools/pre-execute')
await assert.rejects(ask('host', 'Event', 'listEvents', { event: 'subagent/start-x' }), /not known/)
})
test('the Config provider lists exactly the row packages, pages, and shows installed rows', async () => {
const page = await ask('host', 'Config', 'listConfigs')
assert.deepEqual(page.entries.map((e) => e.name).sort(), Object.keys(compatibility.row_bridges).sort())
assert.equal(page.total, 5)
const paged = await ask('host', 'Config', 'listConfigs', { limit: 2 })
assert.equal(paged.entries.length, 2)
assert.equal(paged.nextOffset, 2)
const schema = await ask('host', 'Config', 'listConfigs', { entry: 'row:@deepseek-ai/dsh-persona' })
assert.deepEqual(schema.schema.required, ['prefix'])
await assert.rejects(ask('host', 'Config', 'listConfigs', { limit: 500 }), /limit/)
await assert.rejects(ask('host', 'Config', 'listConfigs', { entry: 'row:nope' }), /not listed/)
const live = createCordisInspect({ installed: () => [{ id: 'abc', name: 'hello', state: 'active' }] })
const after = await live.query('host', 'Config', 'listConfigs', { name: 'hello' })
assert.deepEqual(after.entries, [{ id: 'plugin:abc', name: 'hello', kind: 'installed-plugin', status: 'active' }])
})
test('each row example passes the bridge that reads it', async () => {
const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-inspect-'))
after(() => rmSync(dir, { recursive: true, force: true }))
const bridges = join(dir, 'bridges.mjs')
await build({
stdin: { contents: "export { normalizePersonaConfig } from './src/dsh/persona.ts'\nexport { reviewedMcpModule } from './src/dsh/mcp.ts'\nexport { reviewedSkillModule } from './src/dsh/skill-filesystem.ts'", resolveDir: join(here, '..'), loader: 'ts' },
outfile: bridges, bundle: true, platform: 'node', format: 'esm', packages: 'external', absWorkingDir: join(here, '..'), logLevel: 'silent',
})
const { normalizePersonaConfig, reviewedMcpModule, reviewedSkillModule } = await import(pathToFileURL(bridges).href)
const example = (name) => catalog.host.config.find((r) => r.name === name).example
assert.doesNotThrow(() => normalizePersonaConfig(example('@deepseek-ai/dsh-persona')))
assert.throws(() => normalizePersonaConfig({ prefix: 'x', complete: true }))
const servers = []
reviewedMcpModule().apply({ mcp: { registerServer: (d) => servers.push(d) } }, example('@deepseek-ai/dsh-mcp-client'))
assert.equal(servers[0].serverName, 'docs')
const roots = []
reviewedSkillModule().apply({ skills: { registerRoot: (d) => roots.push(d) } }, example('@deepseek-ai/dsh-skill-filesystem'))
assert.equal(roots.length, 1)
})
test('Slots says no client is connected in a terminal and marks no slot drawn', async () => {
const out = await ask('client', 'Slots', 'listSubTree')
assert.equal(out.client.connected, false)
assert.match(out.client.message, /No client is connected/)
assert.equal(out.trees.length, 30)
assert.ok(out.trees.every((s) => s.drawn === false))
assert.deepEqual((await ask('client', 'Slots', 'listSubTree', { root: 'conversation.composer.dock' })).selected.seat, 'conversation.composer.dock')
assert.equal((await ask('client', 'Slots', 'listSubTree', { root: 'nope' })).requestedRoot.available, false)
})
test('Slots marks only the drawn seats when a client is connected', async () => {
const connected = createCordisInspect({ client: () => ({ connected: true }) })
const out = await connected.query('client', 'Slots', 'listSubTree')
const drawn = out.trees.filter((s) => s.drawn).map((s) => s.name)
assert.deepEqual(drawn, ['plugins.bundle.config', 'plugins.row.config', 'plugins.tab', 'plugins.detail.section', 'settings.section', 'settings.plugin.item', 'settings.general.item', 'settings.plugins.tab'])
const all = createCordisInspect({ client: () => ({ connected: true, drawnSeats: ['conversation.composer.dock'] }) })
const composer = (await all.query('client', 'Slots', 'listSubTree')).trees.filter((s) => s.drawn).map((s) => s.name)
assert.ok(composer.includes('conversation.input.dock') && !composer.includes('plugins.tab'))
assert.ok((await ask('client', 'Slots', 'listSubTree')).trees.filter((s) => !s.supported).every((s) => s.seat === null && s.reason))
})
test('Theme reports that the frame defines no named tokens', async () => {
const out = await ask('client', 'Theme', 'listTokens')
assert.deepEqual(out.tokens, [])
assert.deepEqual(out.colorSchemes, ['light', 'dark'])
assert.ok(out.api.some((a) => a.name === 'ctx.theme.overrideTokens'))
})
@@ -1,88 +0,0 @@
import { test, before } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { build } from 'esbuild'
const here = dirname(fileURLToPath(import.meta.url))
let credentialsAdapter
let brokeredFetch
before(async () => {
const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-network-'))
const outfile = join(dir, 'network.mjs')
await build({ entryPoints: [join(here, '../src/dsh/network.ts')], outfile, bundle: true, platform: 'node', format: 'esm', packages: 'external', absWorkingDir: join(here, '..'), logLevel: 'silent' })
;({ credentialsAdapter, brokeredFetch } = await import(pathToFileURL(outfile).href))
process.on('exit', () => rmSync(dir, { recursive: true, force: true }))
})
function brokerHost(answers) {
const calls = []
return {
calls,
host: {
tier: 'plugin',
broker: async (ctx, service, method, input) => {
calls.push({ service, method, input })
const answer = answers[method]
if (answer instanceof Error) throw answer
return typeof answer === 'function' ? answer(input) : answer
},
},
}
}
test('credentials resolve to an opaque handle and go only to the network broker', async () => {
const { host, calls } = brokerHost({
'credentials.resolve': { ref: 'KEY', value: 'codewhale-credential:KEY' },
'credentials.describe': { ref: 'KEY', set: true },
'credentials.set': { ref: 'KEY', set: true },
})
const Credentials = credentialsAdapter.define(host)
const service = Object.create(Credentials.prototype)
service.ctx = {}
assert.deepEqual(await service.resolve('KEY'), { value: 'codewhale-credential:KEY' })
assert.deepEqual(await service.describe('KEY'), { ref: 'KEY', set: true })
await service.set('KEY', 'sk-secret')
assert.deepEqual(calls.map((c) => [c.service, c.method]), [
['network', 'credentials.resolve'], ['network', 'credentials.describe'], ['network', 'credentials.set'],
])
await assert.rejects(service.resolve(''), /non-empty/)
})
test('a resolve answer that is not a handle is refused rather than passed on', async () => {
const { host } = brokerHost({ 'credentials.resolve': { value: 'sk-raw' } })
const service = Object.create(credentialsAdapter.define(host).prototype)
service.ctx = {}
await assert.rejects(service.resolve('KEY'), /invalid credential handle/)
const unset = Object.create(credentialsAdapter.define(brokerHost({ 'credentials.resolve': { value: null } }).host).prototype)
unset.ctx = {}
assert.equal(await unset.resolve('KEY'), undefined)
})
test('brokeredFetch sends a typed fetch and rebuilds a Response from the broker answer', async () => {
const { host, calls } = brokerHost({
fetch: {
status: 201, url: 'https://api.example.com/v1/x', redirected: true,
headers: [['content-type', 'application/json']],
body_base64: Buffer.from('{"ok":true}').toString('base64'),
},
})
const response = await brokeredFetch(host, {}, 'https://api.example.com/v1/x', {
method: 'POST', headers: { authorization: 'Bearer codewhale-credential:KEY' }, body: 'hi',
})
assert.equal(response.status, 201)
assert.equal(response.url, 'https://api.example.com/v1/x')
assert.equal(response.redirected, true)
assert.deepEqual(await response.json(), { ok: true })
assert.equal(calls[0].service, 'network')
assert.equal(calls[0].method, 'fetch')
assert.deepEqual(calls[0].input.headers, [['authorization', 'Bearer codewhale-credential:KEY']])
assert.equal(Buffer.from(calls[0].input.body_base64, 'base64').toString(), 'hi')
})
test('a broker refusal reaches the plugin as the refusal', async () => {
const { host } = brokerHost({ fetch: new Error('egress refused: `evil.example` is not one of this plugin\'s reviewed network hosts') })
await assert.rejects(brokeredFetch(host, {}, 'https://evil.example/'), /egress refused/)
})
@@ -1,68 +0,0 @@
import { test, before } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { build } from 'esbuild'
const here = dirname(fileURLToPath(import.meta.url))
let remoteAdapter
let Context
let ErrorCode
before(async () => {
const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-remote-'))
const bundle = async (entry, name) => {
const outfile = join(dir, name)
await build({ entryPoints: [join(here, entry)], outfile, bundle: true, platform: 'node', format: 'esm', packages: 'external', absWorkingDir: join(here, '..'), logLevel: 'silent' })
return import(pathToFileURL(outfile).href)
}
;({ remoteAdapter } = await bundle('../src/dsh/remote.ts', 'remote.mjs'))
;({ ErrorCode } = await bundle('../src/protocol.ts', 'protocol.mjs'))
;({ Context } = await import('@deepseek-ai/cordis'))
process.on('exit', () => rmSync(dir, { recursive: true, force: true }))
})
const settle = () => new Promise((resolve) => setTimeout(resolve, 0))
async function harness() {
const calls = []
const host = {
tier: 'plugin',
rpc: { request: async () => { throw new Error('remote never calls the core directly') }, notify() {} },
ownerOf: () => undefined,
liveInvocation: () => undefined,
broker: async (ctx, service, method, input) => { calls.push([service, method, input]); return { ok: method } },
log() {},
}
const ctx = new Context()
ctx.plugin(remoteAdapter.define(host))
await settle()
return { ctx, calls }
}
test('remote sends every method through the remote broker with a typed payload and nothing else', async () => {
const { ctx, calls } = await harness()
assert.deepEqual(await ctx.remote.status(), { ok: 'status' })
await ctx.remote.pair()
await ctx.remote.pair({ label: 'phone' })
await ctx.remote.clients()
await ctx.remote.revoke('cwrg_1')
assert.deepEqual(calls, [
['remote', 'status', {}],
['remote', 'pair', {}],
['remote', 'pair', { label: 'phone' }],
['remote', 'clients', {}],
['remote', 'revoke', { grant: 'cwrg_1' }],
])
})
test('remote refuses malformed arguments locally, before any broker call', async () => {
const { ctx, calls } = await harness()
assert.throws(() => ctx.remote.pair({ label: 3 }), (error) => error.code === ErrorCode.InvalidParams)
for (const id of [undefined, '', 7, 'x'.repeat(129)]) {
assert.throws(() => ctx.remote.revoke(id), (error) => error.code === ErrorCode.InvalidParams)
}
assert.equal(typeof ctx.remote.listen, 'undefined')
assert.deepEqual(calls, [])
})
@@ -1,85 +0,0 @@
import { test, before } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { build } from 'esbuild'
const here = dirname(fileURLToPath(import.meta.url))
let sessionsAdapter
let systemPromptAdapter
let Context
let ErrorCode
before(async () => {
const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-session-prompt-'))
const bundle = async (entry, name) => {
const outfile = join(dir, name)
await build({ entryPoints: [join(here, entry)], outfile, bundle: true, platform: 'node', format: 'esm', packages: 'external', absWorkingDir: join(here, '..'), logLevel: 'silent' })
return import(pathToFileURL(outfile).href)
}
;({ sessionsAdapter, systemPromptAdapter } = await bundle('../src/dsh/session-prompt.ts', 'session-prompt.mjs'))
;({ ErrorCode } = await bundle('../src/protocol.ts', 'protocol.mjs'))
;({ Context } = await import('@deepseek-ai/cordis'))
process.on('exit', () => rmSync(dir, { recursive: true, force: true }))
})
const settle = () => new Promise((resolve) => setTimeout(resolve, 0))
function flushHarness(invocation, requests) {
const session = {}
const host = {
tier: 'plugin',
rpc: { request: async (method, params) => { requests.push({ method, params }); return true }, notify() {} },
ownerOf: () => invocation?.owner,
liveInvocation: () => invocation,
log() {},
}
const ctx = new Context()
ctx.plugin(sessionsAdapter.define(host))
return { ctx, session }
}
const live = (extra = {}) => {
const session = {}
return { owner: { ref: { plugin_id: 'p' } }, session, ticket: 'ticket', signal: new AbortController().signal, pending: Promise.resolve(), ...extra }
}
test('sessions.flush refuses a live invocation that carries no checkpoint ticket', async () => {
const requests = []
const invocation = live({ ticket: undefined })
const { ctx } = flushHarness(invocation, requests)
await settle()
await assert.rejects(ctx.sessions.flush(invocation.session), (error) => error.code === ErrorCode.NotAvailable)
assert.equal(requests.length, 0)
})
test('sessions.flush refuses a session other than the invocation session and sends nothing', async () => {
const requests = []
const invocation = live()
const { ctx } = flushHarness(invocation, requests)
await settle()
await assert.rejects(ctx.sessions.flush({}), (error) => error.code === ErrorCode.NotAvailable)
await assert.rejects(ctx.sessions.flush(undefined), (error) => error.code === ErrorCode.NotAvailable)
assert.equal(requests.length, 0)
})
test('sessions.flush sends the exact owner and ticket, and a stale invocation is refused before the receipt returns', async () => {
const requests = []
const invocation = live()
let current = invocation
const host = { tier: 'plugin', rpc: { request: async (method, params) => { requests.push({ method, params }); current = undefined; return true }, notify() {} }, ownerOf: () => invocation.owner, liveInvocation: () => current, log() {} }
const ctx = new Context()
ctx.plugin(sessionsAdapter.define(host))
await settle()
await assert.rejects(ctx.sessions.flush(invocation.session), (error) => error.code === ErrorCode.NotAvailable)
assert.deepEqual(requests, [{ method: 'session/checkpoint', params: { owner: invocation.owner.ref, ticket: 'ticket' } }])
})
test('systemPrompt stays child-only: the root context refuses sections', async () => {
const ctx = new Context()
ctx.plugin(systemPromptAdapter.define({}))
await settle()
assert.throws(() => ctx.systemPrompt.section({ name: 'x', text: 'y' }), (error) => error.code === ErrorCode.NotAvailable)
assert.throws(() => ctx.systemPrompt.getSectionOrder('X'), (error) => error.code === ErrorCode.NotAvailable)
})
@@ -1,85 +0,0 @@
import { test, before } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { build } from 'esbuild'
const here = dirname(fileURLToPath(import.meta.url))
let terminalAdapter
let Context
let ErrorCode
before(async () => {
const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-terminal-'))
const bundle = async (entry, name) => {
const outfile = join(dir, name)
await build({ entryPoints: [join(here, entry)], outfile, bundle: true, platform: 'node', format: 'esm', packages: 'external', absWorkingDir: join(here, '..'), logLevel: 'silent' })
return import(pathToFileURL(outfile).href)
}
;({ terminalAdapter } = await bundle('../src/dsh/terminal.ts', 'terminal.mjs'))
;({ ErrorCode } = await bundle('../src/protocol.ts', 'protocol.mjs'))
;({ Context } = await import('@deepseek-ai/cordis'))
process.on('exit', () => rmSync(dir, { recursive: true, force: true }))
})
const settle = () => new Promise((resolve) => setTimeout(resolve, 0))
async function harness() {
const calls = []
const host = {
tier: 'plugin',
rpc: { request: async () => { throw new Error('terminal never calls the core directly') }, notify() {} },
ownerOf: () => undefined,
liveInvocation: () => undefined,
broker: async (ctx, service, method, input) => { calls.push([service, method, input]); return { ok: method } },
log() {},
}
const ctx = new Context()
ctx.plugin(terminalAdapter.define(host))
await settle()
return { ctx, calls }
}
test('terminal sends every method through the terminal broker with a typed payload and nothing else', async () => {
const { ctx, calls } = await harness()
assert.deepEqual(await ctx.terminal.list(), { ok: 'list' })
await ctx.terminal.run('make')
await ctx.terminal.run('make', { session: 'build', timeoutSecs: 30, cwd: '/', sandbox_permissions: 'danger' })
await ctx.terminal.send('build', 'y\n', { waitMs: 0 })
await ctx.terminal.wait('build')
await ctx.terminal.wait('build', { timeoutSecs: 600 })
await ctx.terminal.cancel('build')
await ctx.terminal.reset('build')
assert.deepEqual(calls, [
['terminal', 'list', {}],
['terminal', 'run', { command: 'make' }],
['terminal', 'run', { command: 'make', session: 'build', timeout_secs: 30 }],
['terminal', 'send', { session: 'build', text: 'y\n', wait_ms: 0 }],
['terminal', 'wait', { session: 'build' }],
['terminal', 'wait', { session: 'build', timeout_secs: 600 }],
['terminal', 'cancel', { session: 'build' }],
['terminal', 'reset', { session: 'build' }],
])
})
test('terminal refuses malformed arguments locally, before any broker call', async () => {
const { ctx, calls } = await harness()
const refused = (act) => assert.throws(act, (error) => error.code === ErrorCode.InvalidParams)
for (const command of [undefined, '', 7, ['ls']]) refused(() => ctx.terminal.run(command))
for (const name of [undefined, '', 7, '../term-1', 'dsh:b:x', 'a b', 'n'.repeat(65)]) {
refused(() => ctx.terminal.run('true', { session: name === undefined ? null : name }))
refused(() => ctx.terminal.send(name, 'x'))
refused(() => ctx.terminal.wait(name))
refused(() => ctx.terminal.cancel(name))
refused(() => ctx.terminal.reset(name))
}
refused(() => ctx.terminal.send('build', ''))
for (const secs of [0, 601, 1.5, '30']) {
refused(() => ctx.terminal.run('true', { timeoutSecs: secs }))
refused(() => ctx.terminal.wait('build', { timeoutSecs: secs }))
}
refused(() => ctx.terminal.send('build', 'x', { waitMs: 60_001 }))
for (const absent of ['spawn', 'kill', 'resize', 'read', 'exec']) assert.equal(typeof ctx.terminal[absent], 'undefined')
assert.deepEqual(calls, [])
})
@@ -1,80 +0,0 @@
import { test, before } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { build } from 'esbuild'
const here = dirname(fileURLToPath(import.meta.url))
let workspaceAdapter
let Context
let ErrorCode
before(async () => {
const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-workspace-'))
const bundle = async (entry, name) => {
const outfile = join(dir, name)
await build({ entryPoints: [join(here, entry)], outfile, bundle: true, platform: 'node', format: 'esm', packages: 'external', absWorkingDir: join(here, '..'), logLevel: 'silent' })
return import(pathToFileURL(outfile).href)
}
;({ workspaceAdapter } = await bundle('../src/dsh/workspace.ts', 'workspace.mjs'))
;({ ErrorCode } = await bundle('../src/protocol.ts', 'protocol.mjs'))
;({ Context } = await import('@deepseek-ai/cordis'))
process.on('exit', () => rmSync(dir, { recursive: true, force: true }))
})
const settle = () => new Promise((resolve) => setTimeout(resolve, 0))
async function harness() {
const calls = []
const host = {
tier: 'plugin',
rpc: { request: async () => { throw new Error('workspace never calls the core directly') }, notify() {} },
ownerOf: () => undefined,
liveInvocation: () => undefined,
broker: async (ctx, service, method, input) => { calls.push([service, method, input]); return { ok: method } },
log() {},
}
const ctx = new Context()
ctx.plugin(workspaceAdapter.define(host))
await settle()
return { ctx, calls }
}
test('workspace sends every method through the workspace broker with a typed payload and nothing else', async () => {
const { ctx, calls } = await harness()
assert.deepEqual(await ctx.workspace.read('src/a.ts'), { ok: 'read' })
await ctx.workspace.read('src/a.ts', { startLine: 3, maxLines: 10, follow: true })
await ctx.workspace.list()
await ctx.workspace.list('src')
await ctx.workspace.write('src/b.ts', 'x', { expectedHash: 'h', mode: 0o777 })
await ctx.workspace.write('src/c.ts', '')
await ctx.workspace.exec(['git', 'rev-parse', '--show-toplevel'], { cwd: '/w', env: { GIT_DIR: '/' }, shell: true })
assert.deepEqual(calls, [
['workspace', 'read', { path: 'src/a.ts' }],
['workspace', 'read', { path: 'src/a.ts', start_line: 3, max_lines: 10 }],
['workspace', 'list', {}],
['workspace', 'list', { path: 'src' }],
['workspace', 'write', { path: 'src/b.ts', content: 'x', expected_hash: 'h' }],
['workspace', 'write', { path: 'src/c.ts', content: '' }],
['workspace', 'exec', { argv: ['git', 'rev-parse', '--show-toplevel'], cwd: '/w' }],
])
})
test('workspace refuses malformed arguments locally, before any broker call', async () => {
const { ctx, calls } = await harness()
const refused = (act) => assert.throws(act, (error) => error.code === ErrorCode.InvalidParams)
for (const bad of [undefined, '', 7, ' a', 'a\nb', 'p'.repeat(513), ['a']]) {
refused(() => ctx.workspace.read(bad))
refused(() => ctx.workspace.write(bad, 'x'))
if (bad !== undefined) refused(() => ctx.workspace.list(bad))
}
for (const lines of [0, 10_001, 1.5, '3']) refused(() => ctx.workspace.read('a', { maxLines: lines }))
refused(() => ctx.workspace.read('a', { startLine: 0 }))
for (const content of [undefined, 7, 'c'.repeat(1024 * 1024 + 1)]) refused(() => ctx.workspace.write('a', content))
refused(() => ctx.workspace.write('a', 'x', { expectedHash: '' }))
for (const command of [undefined, 'git status', [], [7], ['git', 'a\u0000b'], new Array(10).fill('git')]) refused(() => ctx.workspace.exec(command))
refused(() => ctx.workspace.exec(['git'], { cwd: '' }))
for (const absent of ['delete', 'rename', 'spawn', 'shell', 'watch', 'readSync']) assert.equal(typeof ctx.workspace[absent], 'undefined')
assert.deepEqual(calls, [])
})
+3 -240
View File
@@ -44,9 +44,8 @@ use super::CodewhaleClient;
use super::prepared::WireDialect;
use super::role_placement::{RolePlacement, role_placement};
use super::wire::{
ToolNameWire, check_history_tool_names, documented_tool_name_limit, extract_sse_data_value,
from_api_tool_name, next_sse_line, over_limit_tool_name_message, push_sse_event_data,
to_api_tool_name, tool_name_exceeds_limit, tool_name_limit,
extract_sse_data_value, from_api_tool_name, next_sse_line, push_sse_event_data,
to_api_tool_name,
};
/// Maximum `cache_control` breakpoints Anthropic accepts per request.
@@ -104,11 +103,6 @@ impl CodewhaleClient {
repair_dangling_tool_uses(&mut messages);
body["messages"] = Value::Array(messages);
let tool_name_limit = tool_name_limit(self.api_provider, ToolNameWire::AnthropicMessages);
check_history_tool_names(
request,
documented_tool_name_limit(self.api_provider, ToolNameWire::AnthropicMessages),
)?;
let mut omitted_tool_names = Vec::new();
let mut omitted_logical_names = Vec::new();
if let Some(tools) = request.tools.as_ref()
@@ -119,11 +113,6 @@ impl CodewhaleClient {
};
let mut wire_tools = Vec::new();
for tool in tools {
if tool_name_exceeds_limit(&tool.name, tool_name_limit) {
omitted_logical_names.push(tool.name.clone());
omitted_tool_names.push(to_api_tool_name(&tool.name));
continue;
}
match project_tool_schema(route_projection, &tool.input_schema, tool.strict) {
ToolSchemaProjection::Exact {
parameters,
@@ -166,9 +155,6 @@ impl CodewhaleClient {
if let Some(name) = forced_tool_name(tool_choice)
&& omitted_logical_names.iter().any(|omitted| omitted == name)
{
if tool_name_exceeds_limit(name, tool_name_limit) {
anyhow::bail!(over_limit_tool_name_message(name, tool_name_limit));
}
anyhow::bail!(
"cannot force an omitted tool because its input schema is incompatible with this route"
);
@@ -234,22 +220,9 @@ impl CodewhaleClient {
Some(level) if thinking_capable && supports_adaptive => {
body["thinking"] = json!({ "type": "adaptive" });
if !is_minimax {
let row_lists_xhigh = self
.route_facts
.as_ref()
.filter(|facts| facts.wire_model_id == request.model)
.is_some_and(|facts| {
facts.reasoning_options.iter().any(|option| {
option.get("type").and_then(Value::as_str) == Some("effort")
&& option.get("values").and_then(Value::as_array).is_some_and(
|values| values.iter().any(|v| v.as_str() == Some("xhigh")),
)
})
});
let mapped = match level {
"low" | "minimal" => "low",
"medium" | "mid" => "medium",
"xhigh" if row_lists_xhigh => "xhigh",
"max" | "xhigh" | "highest" => "max",
_ => "high",
};
@@ -824,18 +797,7 @@ fn anthropic_tool_choice(tool_choice: &Value, model: &str) -> Value {
Some("none") => json!({ "type": "none" }),
Some("any" | "required") => json!({ "type": "any" }),
Some(name) => json!({ "type": "tool", "name": to_api_tool_name(name) }),
None => match forced_tool_name(tool_choice) {
Some(name) => {
let mut choice = tool_choice.clone();
choice["type"] = json!("tool");
choice["name"] = json!(to_api_tool_name(name));
if let Some(object) = choice.as_object_mut() {
object.remove("function");
}
choice
}
None => tool_choice.clone(),
},
None => tool_choice.clone(),
}
}
@@ -1319,75 +1281,6 @@ mod tests {
}
}
#[test]
fn over_long_encoded_tool_names_are_withheld_at_128() {
let client = anthropic_test_client(None);
let tool = |name: &str| Tool {
tool_type: None,
name: name.to_string(),
description: "d".to_string(),
input_schema: json!({"type": "object", "additionalProperties": false}),
allowed_callers: None,
defer_loading: None,
input_examples: None,
strict: None,
cache_control: None,
};
let mid = "mcp__tracker__projects.v2.issues.list-by-assignee";
let long = format!(
"mcp__tracker__{}.v2.issues.list-by-assignee",
"a".repeat(70)
);
assert!(to_api_tool_name(mid).len() > 64 && to_api_tool_name(mid).len() <= 128);
assert!(to_api_tool_name(&long).len() > 128);
let mut request = request_with("claude-sonnet-4-6", None, None, None);
request.tools = Some(vec![tool("read_file"), tool(mid), tool(&long)]);
let (body, omitted) = client
.build_anthropic_wire_body(&request, true)
.expect("body builds");
let sent: Vec<&str> = body["tools"]
.as_array()
.expect("tools")
.iter()
.filter_map(|t| t["name"].as_str())
.collect();
assert_eq!(sent, vec!["read_file".to_string(), to_api_tool_name(mid)]);
assert_eq!(omitted, vec![to_api_tool_name(&long)]);
request.tool_choice = Some(json!({"type": "tool", "name": long}));
let error = client
.build_anthropic_wire_body(&request, true)
.expect_err("forcing a withheld tool is refused");
assert!(error.to_string().contains("at most 128"), "{error}");
}
#[test]
fn a_100_character_encoded_name_is_offered_on_an_anthropic_wire_route_without_a_documented_limit()
{
let tool = |name: &str| Tool {
tool_type: None,
name: name.to_string(),
description: "d".to_string(),
input_schema: json!({"type": "object", "additionalProperties": false}),
allowed_callers: None,
defer_loading: None,
input_examples: None,
strict: None,
cache_control: None,
};
let name = "a".repeat(100);
assert_eq!(to_api_tool_name(&name).len(), 100);
let client = minimax_test_client();
let mut request = request_with("MiniMax-M2", None, None, None);
request.tools = Some(vec![tool(&name)]);
let (body, omitted) = client
.build_anthropic_wire_body(&request, true)
.expect("body builds");
assert_eq!(body["tools"][0]["name"], name);
assert!(omitted.is_empty());
}
fn request_with(
model: &str,
reasoning_effort: Option<&str>,
@@ -1596,94 +1489,6 @@ mod tests {
CodewhaleClient::new(&config).expect("Model Studio Messages client constructs")
}
#[test]
fn dotted_tool_names_stay_inside_the_anthropic_pattern_and_decode_back() {
let client = test_client();
let mut request = request_with("claude-sonnet-4-6", None, None, None);
let tool = |name: &str| Tool {
tool_type: None,
name: name.to_string(),
description: "d".to_string(),
input_schema: json!({"type": "object", "additionalProperties": false}),
allowed_callers: None,
defer_loading: None,
input_examples: None,
strict: None,
cache_control: None,
};
request.tools = Some(vec![tool("read_file"), tool("web.run")]);
request.tool_choice = Some(json!({"type": "tool", "name": "web.run"}));
request.messages.push(Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolUse {
execution_id: None,
id: "toolu_w".to_string(),
name: "web.run".to_string(),
input: json!({}),
caller: None,
thought_signature: None,
}],
});
let body = client.build_anthropic_body(&request, true);
let valid = |name: &str| {
(1..=128).contains(&name.len())
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
};
let mut sent = Vec::new();
for tool in body["tools"].as_array().expect("tools") {
sent.push(tool["name"].as_str().expect("tool name").to_string());
}
sent.push(
body.pointer("/tool_choice/name")
.and_then(Value::as_str)
.expect("forced tool name")
.to_string(),
);
for message in body["messages"].as_array().expect("messages") {
for block in message["content"].as_array().into_iter().flatten() {
if block["type"] == "tool_use" {
sent.push(block["name"].as_str().expect("tool_use name").to_string());
}
}
}
assert!(sent.iter().all(|name| valid(name)), "{sent:?}");
assert!(sent.iter().any(|name| name != "read_file"), "{sent:?}");
let wire = to_api_tool_name("web.run");
let message = decode_anthropic_message(json!({
"id": "m", "type": "message", "role": "assistant",
"model": "claude-sonnet-4-6", "stop_reason": "tool_use",
"content": [{"type": "tool_use", "id": "toolu_w", "name": wire, "input": {}}],
"usage": {"input_tokens": 1, "output_tokens": 1},
}))
.unwrap();
let ContentBlock::ToolUse { name, .. } = &message.content[0] else {
panic!("expected tool_use")
};
assert_eq!(name, "web.run");
let event = convert_anthropic_sse_data(
&json!({
"type": "content_block_start", "index": 0,
"content_block": {"type": "tool_use", "id": "toolu_w", "name": wire, "input": {}},
})
.to_string(),
)
.unwrap()
.unwrap();
let StreamEvent::ContentBlockStart {
content_block: codewhale_models::ContentBlockStart::ToolUse { name, .. },
..
} = event
else {
panic!("expected tool_use start")
};
assert_eq!(name, "web.run");
}
#[test]
fn body_keeps_native_cache_control_on_system_and_tools() {
let client = test_client();
@@ -1754,36 +1559,6 @@ mod tests {
Some("max")
);
let offering = |model: &str| {
client
.catalog_facts_for_model(model)
.unwrap_or_else(|| panic!("bundled catalog carries {model}"))
};
let mut xhigh_client = test_client();
xhigh_client.route_facts = Some(offering("claude-opus-4-8"));
let body = xhigh_client.build_anthropic_body(
&request_with("claude-opus-4-8", Some("xhigh"), None, None),
true,
);
assert_eq!(
body.pointer("/output_config/effort")
.and_then(Value::as_str),
Some("xhigh"),
"a row that lists xhigh is sent xhigh: {body}"
);
let mut no_xhigh_client = test_client();
no_xhigh_client.route_facts = Some(offering("claude-sonnet-4-6"));
let body = no_xhigh_client.build_anthropic_body(
&request_with("claude-sonnet-4-6", Some("xhigh"), None, None),
true,
);
assert_eq!(
body.pointer("/output_config/effort")
.and_then(Value::as_str),
Some("max"),
"a row without xhigh keeps the max mapping: {body}"
);
let body = client.build_anthropic_body(
&request_with("claude-sonnet-4-6", Some("off"), None, None),
true,
@@ -2025,18 +1800,6 @@ mod tests {
Some("disabled"),
"{body}"
);
let mut preview_client = modelstudio_test_client(
"https://token-plan.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
);
preview_client.route_facts = preview_client.catalog_facts_for_model("qwen4-max-preview");
for effort in [None, Some("high"), Some("max"), Some("off")] {
let mut request = request_with("qwen4-max-preview", effort, None, None);
request.max_tokens = 64_000;
let body = preview_client.build_anthropic_body(&request, true);
assert!(body.get("thinking").is_none(), "{effort:?}: {body}");
assert!(body.get("output_config").is_none(), "{effort:?}: {body}");
}
}
#[test]
+5 -252
View File
@@ -41,10 +41,8 @@ use super::reasoning_effort::apply_reasoning_effort;
use super::role_placement::{RolePlacement, role_placement};
use super::wire::{
ERROR_BODY_MAX_BYTES, SSE_BACKPRESSURE_HIGH_WATERMARK, SSE_BACKPRESSURE_SLEEP_MS,
SSE_MAX_LINES_PER_CHUNK, ToolNameWire, acquire_stream_buffer, bounded_error_text,
check_history_tool_names, documented_tool_name_limit, from_api_tool_name,
over_limit_tool_name_message, parse_usage, release_stream_buffer, system_to_instructions,
to_api_tool_name, tool_name_exceeds_limit, tool_name_limit,
SSE_MAX_LINES_PER_CHUNK, acquire_stream_buffer, bounded_error_text, from_api_tool_name,
parse_usage, release_stream_buffer, system_to_instructions, to_api_tool_name,
};
use super::wire::{extract_sse_data_value, flush_sse_line, push_sse_event_data, take_sse_line};
use codewhale_config::route::RouteLimits;
@@ -1210,20 +1208,11 @@ pub fn build_chat_wire_body_with_window(
body["top_p"] = json!(top_p);
}
let mut omitted_tool_names = Vec::new();
let tool_name_limit = tool_name_limit(provider, ToolNameWire::OpenAiCompatible);
check_history_tool_names(
request,
documented_tool_name_limit(provider, ToolNameWire::OpenAiCompatible),
)?;
if let Some(tools) = request.tools.as_ref() {
let route_projection =
chat_route_tool_projection(provider, base_url, strict_tools_disabled);
let mut chat_tools = Vec::new();
for tool in tools {
if tool_name_exceeds_limit(&tool.name, tool_name_limit) {
omitted_tool_names.push(to_api_tool_name(&tool.name));
continue;
}
match project_tool_schema(route_projection, &tool.input_schema, tool.strict) {
ToolSchemaProjection::Exact {
parameters,
@@ -1258,9 +1247,6 @@ pub fn build_chat_wire_body_with_window(
.iter()
.any(|omitted| omitted == name || *omitted == to_api_tool_name(name))
{
if tool_name_exceeds_limit(name, tool_name_limit) {
bail!(over_limit_tool_name_message(name, tool_name_limit));
}
bail!(
"cannot force an omitted tool because its input schema is incompatible with this route"
);
@@ -3269,25 +3255,11 @@ fn deepseek_base_url_supports_strict_tools(base_url: &str) -> bool {
fn map_tool_choice_for_chat(choice: &Value) -> Option<Value> {
if let Some(choice_str) = choice.as_str() {
return Some(match forced_tool_name(choice) {
Some(name) => json!({
"type": "function",
"function": { "name": to_api_tool_name(name) }
}),
None => json!(choice_str),
});
return Some(json!(choice_str));
}
let Some(choice_type) = choice.get("type").and_then(Value::as_str) else {
return Some(choice.clone());
};
if choice_type == "function"
&& let Some(name) = forced_tool_name(choice)
{
return Some(json!({
"type": "function",
"function": { "name": to_api_tool_name(name) }
}));
}
match choice_type {
"auto" | "none" => Some(json!(choice_type)),
@@ -5471,7 +5443,6 @@ mod alias_thinking_detection_tests {
"foo-reasoner",
"new-model-reasoning",
"acme-reasoner-v2",
"qwen4-max-preview",
] {
assert!(
!should_replay_reasoning_content_for_provider_on_route(
@@ -6692,13 +6663,9 @@ mod image_block_wire_tests {
//! most of them at once. The shape is fixed by OpenAI's spec: a `user`
//! message whose `content` is an array of parts, with the image as
//! `{"type":"image_url","image_url":{"url":…}}`.
use super::{
ChatWireBody, ProviderKind, build_chat_messages, build_chat_wire_body,
map_tool_choice_for_chat, to_api_tool_name,
};
use super::{ProviderKind, build_chat_messages, build_chat_wire_body};
use codewhale_models::Role;
use codewhale_models::{ContentBlock, ImageUrlContent, Message, MessageRequest, Tool};
use serde_json::{Value, json};
use codewhale_models::{ContentBlock, ImageUrlContent, Message, MessageRequest};
const DATA_URL: &str = "data:image/png;base64,QUJD";
@@ -7005,220 +6972,6 @@ mod image_block_wire_tests {
}
}
fn named_tool(name: &str) -> Tool {
Tool {
tool_type: None,
name: name.to_string(),
description: "d".to_string(),
input_schema: json!({"type": "object", "additionalProperties": false}),
allowed_callers: None,
defer_loading: None,
input_examples: None,
strict: None,
cache_control: None,
}
}
#[test]
fn function_object_tool_choice_encodes_the_tool_name() {
let encoded = to_api_tool_name("web.run");
assert_eq!(encoded, "web-x00002E-run");
let expected = json!({"type": "function", "function": {"name": encoded}});
for choice in [
json!({"type": "function", "function": {"name": "web.run"}}),
json!({"type": "function", "name": "web.run"}),
json!({"type": "tool", "name": "web.run"}),
json!("web.run"),
] {
assert_eq!(
map_tool_choice_for_chat(&choice),
Some(expected.clone()),
"{choice}"
);
}
assert_eq!(
map_tool_choice_for_chat(&json!("required")),
Some(json!("required"))
);
let mut request = request_with_image();
request.tools = Some(vec![named_tool("read_file"), named_tool("web.run")]);
request.tool_choice = Some(json!({"type": "function", "function": {"name": "web.run"}}));
let body = build_chat_wire_body(
&request,
ProviderKind::Openai,
"https://api.openai.com/v1",
false,
None,
)
.expect("wire body");
assert_eq!(body.body["tool_choice"], expected);
let declared: Vec<&str> = body.body["tools"]
.as_array()
.expect("tools")
.iter()
.filter_map(|tool| tool.pointer("/function/name").and_then(Value::as_str))
.collect();
assert!(declared.contains(&"web-x00002E-run"));
}
#[test]
fn over_long_encoded_tool_names_are_withheld_by_provider_limit() {
let mid = "mcp__tracker__projects.v2.issues.list-by-assignee";
let long = format!(
"mcp__tracker__{}.v2.issues.list-by-assignee",
"a".repeat(70)
);
let mid_len = to_api_tool_name(mid).len();
assert!(mid_len > 64 && mid_len <= 128, "{mid_len}");
assert!(to_api_tool_name(&long).len() > 128);
let build = |provider, base_url: &str, choice: Option<Value>| {
let mut request = request_with_image();
request.tools = Some(vec![
named_tool("read_file"),
named_tool(mid),
named_tool(&long),
]);
request.tool_choice = choice;
build_chat_wire_body(&request, provider, base_url, false, None)
};
let declared = |body: &ChatWireBody| -> Vec<String> {
body.body["tools"]
.as_array()
.expect("tools")
.iter()
.filter_map(|tool| tool.pointer("/function/name").and_then(Value::as_str))
.map(str::to_string)
.collect()
};
let openai = build(ProviderKind::Openai, "https://api.openai.com/v1", None).expect("body");
assert_eq!(declared(&openai), vec!["read_file".to_string()]);
assert_eq!(
openai.omitted_tool_names,
vec![to_api_tool_name(mid), to_api_tool_name(&long)]
);
let deepseek =
build(ProviderKind::Deepseek, "https://api.deepseek.com", None).expect("body");
assert_eq!(
declared(&deepseek),
vec!["read_file".to_string(), to_api_tool_name(mid)]
);
assert_eq!(deepseek.omitted_tool_names, vec![to_api_tool_name(&long)]);
let forced = json!({"type": "function", "function": {"name": mid}});
let error = build(
ProviderKind::Openai,
"https://api.openai.com/v1",
Some(forced),
)
.err()
.expect("forcing a withheld tool is refused");
let message = error.to_string();
assert!(
message.contains(&format!("{mid_len} characters")),
"{message}"
);
assert!(message.contains("at most 64"), "{message}");
}
#[test]
fn over_long_tool_name_in_history_is_refused_with_the_limit() {
let long = "mcp__tracker__projects.v2.issues.list-by-assignee";
let mut request = request_with_image();
request.messages.push(Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolUse {
execution_id: None,
id: "call_1".to_string(),
name: long.to_string(),
input: json!({}),
caller: None,
thought_signature: None,
}],
});
let error = build_chat_wire_body(
&request,
ProviderKind::Openai,
"https://api.openai.com/v1",
false,
None,
)
.err()
.expect("history name over the limit is refused");
let message = error.to_string();
assert!(
message.contains("at most 64") && message.contains(long),
"{message}"
);
build_chat_wire_body(
&request,
ProviderKind::Deepseek,
"https://api.deepseek.com",
false,
None,
)
.expect("the same history fits a 128-character route");
}
#[test]
fn history_name_of_65_to_128_characters_is_sent_unchanged_on_undocumented_routes() {
let long = "mcp__tracker__projects.v2.issues.list-by-assignee";
assert!(to_api_tool_name(long).len() > 64);
let mut request = request_with_image();
request.messages.push(Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolUse {
execution_id: None,
id: "call_1".to_string(),
name: long.to_string(),
input: json!({}),
caller: None,
thought_signature: None,
}],
});
for (provider, base_url) in [
(ProviderKind::Ollama, "http://localhost:11434/v1"),
(ProviderKind::Custom, "http://localhost:8000/v1"),
(ProviderKind::Minimax, "https://api.minimax.io/v1"),
] {
build_chat_wire_body(&request, provider, base_url, false, None)
.unwrap_or_else(|error| panic!("{provider:?}: {error}"));
}
let error = build_chat_wire_body(
&request,
ProviderKind::Openai,
"https://api.openai.com/v1",
false,
None,
)
.err()
.expect("documented 64-character route refuses the history name");
assert!(
error.to_string().contains("earlier in this session"),
"{error}"
);
}
#[test]
fn a_100_character_encoded_name_is_withheld_on_a_chat_wire_route() {
let name = "a".repeat(100);
let mut request = request_with_image();
request.tools = Some(vec![named_tool("read_file"), named_tool(&name)]);
let body = build_chat_wire_body(
&request,
ProviderKind::Minimax,
"https://api.minimax.io/v1",
false,
None,
)
.expect("wire body");
assert_eq!(body.omitted_tool_names, vec![name]);
assert_eq!(body.body["tools"].as_array().expect("tools").len(), 1);
}
fn request_with_image() -> MessageRequest {
MessageRequest {
model: "gpt-4o".to_string(),
+2 -22
View File
@@ -35,10 +35,8 @@ use super::chat::REASONING_REPLAY_PLACEHOLDER;
use super::prepared::WireDialect;
use super::role_placement::{RolePlacement, role_placement};
use super::wire::{
ERROR_BODY_MAX_BYTES, TOOL_NAME_LIMIT_64, ToolNameWire, bounded_error_text,
check_history_tool_names, documented_tool_name_limit, from_api_tool_name,
over_limit_tool_name_message, system_to_instructions, to_api_tool_name,
tool_name_exceeds_limit, tool_name_limit,
ERROR_BODY_MAX_BYTES, bounded_error_text, from_api_tool_name, system_to_instructions,
to_api_tool_name,
};
use super::wire::{extract_sse_data_value, next_sse_line, push_sse_event_data};
use crate::llm_client::LlmError;
@@ -137,7 +135,6 @@ pub(super) fn build_responses_wire_body(
.filter(|text| !text.trim().is_empty())
.unwrap_or_else(|| "You are a helpful assistant.".to_string());
let provider_kind = ProviderKind::parse(context.provider_id);
let mut input = convert_messages_to_responses_input(request, profile, context);
if profile.request.instructions == InstructionsPlacement::LeadingSystemInput {
input.insert(
@@ -153,26 +150,12 @@ pub(super) fn build_responses_wire_body(
}
body["input"] = json!(input);
let tool_name_limit = provider_kind.map_or(TOOL_NAME_LIMIT_64, |provider| {
tool_name_limit(provider, ToolNameWire::OpenAiCompatible)
});
check_history_tool_names(
request,
provider_kind.and_then(|provider| {
documented_tool_name_limit(provider, ToolNameWire::OpenAiCompatible)
}),
)?;
let mut omitted_tool_names = Vec::new();
let mut omitted_logical_names = Vec::new();
// Convert tools to Responses function tools.
if let Some(tools) = request.tools.as_ref() {
let mut responses_tools = Vec::new();
for tool in tools {
if tool_name_exceeds_limit(&tool.name, tool_name_limit) {
omitted_logical_names.push(tool.name.clone());
omitted_tool_names.push(to_api_tool_name(&tool.name));
continue;
}
match project_tool_schema(
RouteToolProjection::RelaxedNonStrict,
&tool.input_schema,
@@ -202,9 +185,6 @@ pub(super) fn build_responses_wire_body(
if let Some(name) = request.tool_choice.as_ref().and_then(forced_tool_name)
&& omitted_logical_names.iter().any(|omitted| omitted == name)
{
if tool_name_exceeds_limit(name, tool_name_limit) {
anyhow::bail!(over_limit_tool_name_message(name, tool_name_limit));
}
anyhow::bail!(
"cannot force an omitted tool because its input schema is incompatible with this route"
);
@@ -755,43 +755,6 @@ async fn responses_stream_inserts_boundary_between_reasoning_summary_parts() {
assert_eq!(thinking, "partA\n\npartB");
}
#[test]
fn over_long_encoded_tool_names_are_withheld_from_responses_at_64() {
let tool = |name: &str| Tool {
tool_type: None,
name: name.to_string(),
description: "d".to_string(),
input_schema: json!({"type": "object", "additionalProperties": false}),
allowed_callers: None,
defer_loading: None,
input_examples: None,
strict: None,
cache_control: None,
};
let long = "mcp__tracker__projects.v2.issues.list-by-assignee";
assert!(to_api_tool_name(long).len() > 64);
let mut request = minimal_responses_request();
request.tools = Some(vec![tool("read_file"), tool(long)]);
let (body, omitted) = build_responses_wire_body(
&request,
profile_for_provider(ProviderKind::Openai),
ResponsesReplayContext {
provider_id: ProviderKind::Openai.as_str(),
wire_model_id: request.model.as_str(),
reasoning_api_id: None,
},
)
.expect("body builds");
let sent: Vec<&str> = body["tools"]
.as_array()
.expect("tools")
.iter()
.filter_map(|t| t["name"].as_str())
.collect();
assert_eq!(sent, vec!["read_file"]);
assert_eq!(omitted, vec![to_api_tool_name(long)]);
}
#[test]
fn codex_reasoning_effort_uses_responses_labels() {
assert_eq!(codex_responses_reasoning_effort("max"), Some("max"));
+3 -4
View File
@@ -1449,10 +1449,9 @@ fn tool_name_scenario() {
}
// from tool_name_decode_bare_hex_no_trailing_dash
{
let exact = "foo_x00002Ebar";
assert_eq!(from_api_tool_name(exact), exact);
let mangled = "foo_.x00002Ebar";
assert_eq!(from_api_tool_name(mangled), "foo_..bar");
let mangled = "foo_x00002Ebar";
let decoded = from_api_tool_name(mangled);
assert_eq!(decoded, "foo_.bar");
}
// from tool_name_bare_hex_preserves_alnum
{
+7 -175
View File
@@ -6,8 +6,7 @@
use anyhow::Result;
use serde_json::Value;
use codewhale_config::ProviderKind;
use codewhale_models::{ContentBlock, MessageRequest, ServerToolUsage, SystemPrompt, Usage};
use codewhale_models::{ServerToolUsage, SystemPrompt, Usage};
use std::sync::{Mutex as StdMutex, OnceLock};
pub fn saturating_u32(value: u64) -> u32 {
@@ -316,7 +315,7 @@ pub fn to_api_tool_name(name: &str) -> String {
out
}
fn decode_delimited_tool_name(name: &str) -> String {
pub fn from_api_tool_name(name: &str) -> String {
let mut out = String::new();
let mut iter = name.chars().peekable();
while let Some(ch) = iter.next() {
@@ -358,87 +357,12 @@ fn decode_delimited_tool_name(name: &str) -> String {
}
out.push('-');
}
out
}
pub fn from_api_tool_name(name: &str) -> String {
let exact = decode_delimited_tool_name(name);
if to_api_tool_name(&exact) == name {
return exact;
}
decode_bare_hex_escapes(&exact)
}
pub const TOOL_NAME_LIMIT_64: usize = 64;
pub const TOOL_NAME_LIMIT_128: usize = 128;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolNameWire {
AnthropicMessages,
OpenAiCompatible,
}
pub fn documented_tool_name_limit(provider: ProviderKind, wire: ToolNameWire) -> Option<usize> {
match (provider, wire) {
(ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic, _) => Some(TOOL_NAME_LIMIT_128),
(ProviderKind::Anthropic, ToolNameWire::AnthropicMessages) => Some(TOOL_NAME_LIMIT_128),
(ProviderKind::Openai | ProviderKind::OpenaiCodex, ToolNameWire::OpenAiCompatible) => {
Some(TOOL_NAME_LIMIT_64)
}
_ => None,
}
}
pub fn tool_name_limit(provider: ProviderKind, wire: ToolNameWire) -> usize {
if let Some(limit) = documented_tool_name_limit(provider, wire) {
return limit;
}
match (provider, wire) {
(_, ToolNameWire::AnthropicMessages) => TOOL_NAME_LIMIT_128,
(
ProviderKind::Ollama
| ProviderKind::OllamaCloud
| ProviderKind::Vllm
| ProviderKind::Sglang
| ProviderKind::Custom,
_,
) => TOOL_NAME_LIMIT_128,
(_, ToolNameWire::OpenAiCompatible) => TOOL_NAME_LIMIT_64,
}
}
pub fn check_history_tool_names(request: &MessageRequest, documented: Option<usize>) -> Result<()> {
let Some(limit) = documented else {
return Ok(());
};
for message in &request.messages {
for block in &message.content {
if let ContentBlock::ToolUse { name, .. } = block
&& tool_name_exceeds_limit(name, limit)
{
anyhow::bail!(over_limit_history_tool_name_message(name, limit));
}
}
}
Ok(())
}
pub fn tool_name_exceeds_limit(name: &str, limit: usize) -> bool {
to_api_tool_name(name).len() > limit
}
pub fn over_limit_tool_name_message(name: &str, limit: usize) -> String {
format!(
"tool name `{name}` encodes to {} characters but this provider accepts at most {limit}; rename the tool (shorter name, fewer dots, hyphens or other special characters) or remove it",
to_api_tool_name(name).len()
)
}
pub fn over_limit_history_tool_name_message(name: &str, limit: usize) -> String {
format!(
"tool `{name}` was called earlier in this session and its encoded name is {} characters, but this provider accepts at most {limit}; switch to a route with a larger limit or start a new session",
to_api_tool_name(name).len()
)
// Second pass: decode bare hex escapes (e.g. `x00002E`) that the model
// may produce when it mangles the `-x00002E-` delimiter form. Only
// decode when the resulting character is one that `to_api_tool_name`
// would have encoded (not alphanumeric, not `_`, not `-`).
decode_bare_hex_escapes(&out)
}
pub const SSE_BACKPRESSURE_HIGH_WATERMARK: usize = 1024 * 1024; // 1 MB
@@ -541,98 +465,6 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn tool_name_encoding_is_collision_free_for_hostile_names() {
let names = [
"web.run",
"web-x00002E-run",
"web--x00002E--run",
"webx00002Erun",
"web_x00002Erun",
"web_.run",
"a-b",
"a--b",
"a_b",
"a.b",
"ax00002Eb",
"a-x00002E-b",
"mcp__srv__tool.name",
"mcp__srv__tool-x00002E-name",
];
let mut seen = std::collections::HashMap::new();
for name in names {
let encoded = to_api_tool_name(name);
assert!(
encoded
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
"{encoded}"
);
if let Some(previous) = seen.insert(encoded.clone(), name) {
panic!("{previous} and {name} both encode to {encoded}");
}
assert_eq!(from_api_tool_name(&encoded), name, "round trip of {name}");
}
}
#[test]
fn tool_name_limit_follows_the_wire_unless_the_provider_documents_one() {
use ToolNameWire::{AnthropicMessages, OpenAiCompatible};
assert_eq!(
tool_name_limit(ProviderKind::Anthropic, AnthropicMessages),
128
);
assert_eq!(
tool_name_limit(ProviderKind::MinimaxAnthropic, AnthropicMessages),
128
);
assert_eq!(
tool_name_limit(
ProviderKind::ModelstudioTokenPlanAnthropic,
AnthropicMessages
),
128
);
assert_eq!(
tool_name_limit(ProviderKind::Deepseek, OpenAiCompatible),
128
);
assert_eq!(
tool_name_limit(ProviderKind::DeepseekAnthropic, AnthropicMessages),
128
);
assert_eq!(tool_name_limit(ProviderKind::Openai, OpenAiCompatible), 64);
assert_eq!(tool_name_limit(ProviderKind::Minimax, OpenAiCompatible), 64);
assert_eq!(tool_name_limit(ProviderKind::Ollama, OpenAiCompatible), 128);
assert_eq!(
documented_tool_name_limit(ProviderKind::Ollama, OpenAiCompatible),
None
);
assert_eq!(
documented_tool_name_limit(ProviderKind::Custom, OpenAiCompatible),
None
);
}
#[test]
fn tool_name_limit_counts_the_encoded_form() {
let dotted = "mcp__tracker__projects.v2.issues.list-by-assignee";
assert!(dotted.len() <= 64);
assert!(tool_name_exceeds_limit(dotted, TOOL_NAME_LIMIT_64));
assert!(!tool_name_exceeds_limit(dotted, TOOL_NAME_LIMIT_128));
let plain = "a".repeat(64);
assert!(!tool_name_exceeds_limit(&plain, TOOL_NAME_LIMIT_64));
assert!(tool_name_exceeds_limit(
&format!("{plain}a"),
TOOL_NAME_LIMIT_64
));
let message = over_limit_tool_name_message(dotted, TOOL_NAME_LIMIT_64);
assert!(
message.contains("at most 64") && message.contains(dotted),
"{message}"
);
}
#[test]
fn sse_line_limit_rejects_oversized_pending_complete_and_final_lines() {
let mut decoder = SseLineDecoder::new();
-54
View File
@@ -41,60 +41,6 @@ pub trait CommandCatalog: Send + Sync {
fn answers_to(&self, name: &str) -> bool;
fn builtins(&self) -> Vec<BuiltinCommand>;
fn user_commands(&self, workspace: &Path) -> Vec<UserCommand>;
/// Whether this host executes `name` remotely at all. Checked before any
/// thread state is assembled, so a name outside the remote surface is
/// refused exactly like a name no host knows. `false` is the default: a
/// host opts in one command at a time, and widening this must widen
/// [`Self::execute_builtin`] too.
fn serves_builtin(&self, name: &str) -> bool {
let _ = name;
false
}
/// Execute one built-in command against a host snapshot. `None` means
/// this host does not implement remote execution, or does not answer to
/// the name; `Some` carries the command's own answer.
fn execute_builtin(
&self,
name: &str,
args: Option<&str>,
host: &BuiltinCommandHostSnapshot,
) -> Option<BuiltinCommandExecution> {
let _ = (name, args, host);
None
}
}
/// The thread state a remote built-in execution reads.
///
/// Engine-side so the app-server can assemble it from thread state and the
/// terminal host can interpret it without either depending on the other. The
/// projections are the command contract's own data-only types: the host maps
/// them into the facet envelope, and the capability mask each portable
/// handler declares decides which commands this snapshot can honestly serve.
pub struct BuiltinCommandHostSnapshot {
pub mode: codewhale_command_contract::types::CommandMode,
/// The host's own label for `mode` ("WORK", "PLAN"), the same string the
/// terminal footer shows.
pub mode_label: String,
pub locale: codewhale_localization::Locale,
pub model: String,
pub system_prompt: codewhale_command_contract::facets::DebugSystemPrompt,
/// Published usage telemetry and the host's cost breakdown for the
/// thread — the complete data source the portable `/tokens` and `/cost`
/// renderers consume.
pub tokens: codewhale_command_contract::facets::DebugTokenProjection,
}
/// One remote built-in execution's outcome.
pub struct BuiltinCommandExecution {
pub name: String,
pub text: String,
pub is_error: bool,
/// `false` when the command also asked the terminal host for an action —
/// the text is still what the command answered, but no API client can
/// perform that action (a balance fetch, a snapshot restore) on the
/// host's behalf.
pub text_only: bool,
}
static CATALOG: OnceLock<Arc<dyn CommandCatalog>> = OnceLock::new();
-234
View File
@@ -1,234 +0,0 @@
use std::sync::Mutex;
use std::time::{Duration, Instant};
use serde::Serialize;
use crate::extension_host::ExtensionHostOptions;
pub const STANDARD: &str = "standard";
pub const CREATOR: &str = "creator";
pub const SOURCE_BUILTIN: &str = "builtin";
pub const CREATOR_LOADS_ITS_OWN_TOOLS: bool = false;
pub const CREATOR_NOT_READY_REASON: &str = "Creator mode is not ready in this build.";
const AVAILABILITY_TTL: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{message}")]
pub struct ModeRefusal {
pub code: &'static str,
pub message: String,
}
impl ModeRefusal {
pub const UNKNOWN_MODE: &'static str = "unknown_mode";
pub const MODE_UNAVAILABLE: &'static str = "mode_unavailable";
pub const MODE_LOCKED: &'static str = "mode_locked";
pub const MODE_NOT_SUPPORTED_WITH_EXECUTOR: &'static str = "mode_not_supported_with_executor";
pub fn new(code: &'static str, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
pub fn locked() -> Self {
Self::new(
Self::MODE_LOCKED,
"The conversation mode is fixed once the conversation has its first turn; start a new conversation to use another mode.",
)
}
pub fn with_executor() -> Self {
Self::new(
Self::MODE_NOT_SUPPORTED_WITH_EXECUTOR,
"A session with another agent uses that agent's own tools and instructions; conversation modes are unavailable.",
)
}
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ConversationMode {
pub id: String,
pub name: String,
pub description: String,
pub source: &'static str,
pub available: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ConversationModeTable {
pub default: &'static str,
pub modes: Vec<ConversationMode>,
}
#[must_use]
pub fn effective_id(stored: Option<&str>) -> &str {
stored.unwrap_or(STANDARD)
}
#[must_use]
pub fn stored_form(id: &str) -> Option<String> {
(id != STANDARD).then(|| id.to_string())
}
#[must_use]
pub fn table(creator_unavailable: Option<String>) -> ConversationModeTable {
ConversationModeTable {
default: STANDARD,
modes: vec![
ConversationMode {
id: STANDARD.to_string(),
name: "Standard".to_string(),
description: "The everyday Codewhale agent with its normal tools and skills."
.to_string(),
source: SOURCE_BUILTIN,
available: true,
reason: None,
},
ConversationMode {
id: CREATOR.to_string(),
name: "Creator".to_string(),
description:
"Build, inspect and test Codewhale plugins in this conversation, with the plugin authoring tools and guides loaded."
.to_string(),
source: SOURCE_BUILTIN,
available: creator_unavailable.is_none(),
reason: creator_unavailable,
},
],
}
}
type Cached = Option<(Instant, Option<String>)>;
static CREATOR_PROBE: Mutex<Cached> = Mutex::new(None);
#[cfg(any(test, feature = "test-support"))]
static CREATOR_PROBE_OVERRIDE: Mutex<Option<Option<String>>> = Mutex::new(None);
#[cfg(any(test, feature = "test-support"))]
static CREATOR_PROBE_LOCK: Mutex<()> = Mutex::new(());
#[cfg(any(test, feature = "test-support"))]
pub struct CreatorAvailabilityGuard {
_serial: std::sync::MutexGuard<'static, ()>,
}
#[cfg(any(test, feature = "test-support"))]
impl CreatorAvailabilityGuard {
pub fn set(unavailable_reason: Option<&str>) -> Self {
Self::hold(Some(unavailable_reason.map(str::to_string)))
}
pub fn unforced() -> Self {
Self::hold(None)
}
fn hold(forced: Option<Option<String>>) -> Self {
let serial = CREATOR_PROBE_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
*CREATOR_PROBE_OVERRIDE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = forced;
Self { _serial: serial }
}
}
#[cfg(any(test, feature = "test-support"))]
impl Drop for CreatorAvailabilityGuard {
fn drop(&mut self) {
*CREATOR_PROBE_OVERRIDE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = None;
}
}
fn probe_host_runtime(options: &ExtensionHostOptions) -> Option<String> {
let resolution = codewhale_dependencies::resolve_extension_host_runtime(
options.runtime,
options.node_override.as_deref(),
options.bun_override.as_deref(),
crate::extension_host::bundle_sha256(),
);
if resolution.selected.is_some() {
None
} else {
Some(format!(
"Creator mode needs a plugin runtime (Node.js or Bun), and none was found. {}",
resolution.failure()
))
}
}
async fn creator_unavailable_reason(options: ExtensionHostOptions) -> Option<String> {
#[cfg(any(test, feature = "test-support"))]
if let Some(forced) = CREATOR_PROBE_OVERRIDE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
{
return forced;
}
if !CREATOR_LOADS_ITS_OWN_TOOLS {
return Some(CREATOR_NOT_READY_REASON.to_string());
}
if let Some((at, reason)) = CREATOR_PROBE.lock().expect("probe cache").clone()
&& at.elapsed() < AVAILABILITY_TTL
{
return reason;
}
let reason = tokio::task::spawn_blocking(move || probe_host_runtime(&options))
.await
.unwrap_or_else(|_| Some("Creator mode could not check for a plugin runtime.".to_string()));
*CREATOR_PROBE.lock().expect("probe cache") = Some((Instant::now(), reason.clone()));
reason
}
pub async fn current_table(options: ExtensionHostOptions) -> ConversationModeTable {
table(creator_unavailable_reason(options).await)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModeSelection {
pub id: String,
pub unavailable: Option<String>,
}
impl ModeSelection {
pub fn require_available(&self) -> Result<(), ModeRefusal> {
match &self.unavailable {
Some(reason) => Err(ModeRefusal::new(
ModeRefusal::MODE_UNAVAILABLE,
reason.clone(),
)),
None => Ok(()),
}
}
}
pub async fn select(id: &str, options: ExtensionHostOptions) -> Result<ModeSelection, ModeRefusal> {
let table = current_table(options).await;
match table.modes.into_iter().find(|mode| mode.id == id) {
Some(mode) => Ok(ModeSelection {
id: mode.id,
unavailable: if mode.available {
None
} else {
Some(
mode.reason
.unwrap_or_else(|| "This mode is unavailable.".to_string()),
)
},
}),
None => Err(ModeRefusal::new(
ModeRefusal::UNKNOWN_MODE,
format!("`{id}` is not a conversation mode; GET /v1/modes lists them."),
)),
}
}
-32
View File
@@ -863,38 +863,6 @@ mod tests {
TurnAuthority::from_effective_fields(mode, true, false, auto_approve, approval_mode)
}
#[test]
fn a_managed_network_grant_survives_the_ask_posture_and_shares_the_network() {
let workspace = Path::new("/srv/workspace");
for approval_mode in [ApprovalMode::Suggest, ApprovalMode::Bypass] {
let policy = sandbox_policy_for_turn(
AppMode::Agent,
approval_mode,
Some("workspace-write"),
workspace,
SandboxNetworkAccess::from_config(Some(true)),
);
assert!(
matches!(
policy,
SandboxPolicy::WorkspaceWrite {
network_access: true,
..
}
),
"{approval_mode:?}: {policy:?}"
);
}
let unset = sandbox_policy_for_turn(
AppMode::Agent,
ApprovalMode::Suggest,
Some("workspace-write"),
workspace,
SandboxNetworkAccess::from_config(None),
);
assert!(!unset.has_network_access(), "{unset:?}");
}
#[test]
fn write_carve_out_posture_is_exactly_accept_edits() {
assert!(write_carve_out_posture(
@@ -2758,42 +2758,6 @@ mod tests {
assert!(decision.reason.contains("publish-like"));
}
#[test]
fn plugin_trust_and_enable_from_a_shell_follow_the_session_approval() {
let policy = AutoReviewPolicy::default();
for command in [
"codewhale plugins trust demo --review-token a.b --yes",
"codewhale plugins enable demo",
"codewhale plugins trust demo",
] {
for mode in [
ApprovalMode::Suggest,
ApprovalMode::AcceptEdits,
ApprovalMode::Auto,
] {
let mut ctx = ctx_for(
"exec_shell",
json!({ "command": command }),
RunOrigin::Interactive,
mode,
);
ctx.session_runtime_risk = None;
let decision = policy.evaluate(&ctx);
assert_eq!(decision.action, AutoReviewAction::AskUser, "{command}");
assert!(!decision.built_in_safety_gate, "{command}");
assert!(!decision.reason.contains("plugin"), "{command}");
}
let full_access = policy.evaluate(&ctx_for(
"exec_shell",
json!({ "command": command }),
RunOrigin::Interactive,
ApprovalMode::Bypass,
));
assert!(!full_access.built_in_safety_gate, "{command}");
assert_ne!(full_access.action, AutoReviewAction::Block, "{command}");
}
}
#[test]
fn background_test_shell_is_not_held_by_safety_floor() {
// #3883: an ordinary build/test command flagged background must not
+3 -9
View File
@@ -314,8 +314,8 @@ pub struct EngineConfig {
pub session_id: Option<String>,
/// Optional host-owned root for delegated-agent runtime state.
///
/// When unset, the worker ledger and complete transcript artifacts
/// retain their historical location under
/// When unset, the worker ledger, complete transcript artifacts and
/// coordination lock retain their historical location under
/// `workspace/.codewhale/state`. Embedders may set a session-scoped root
/// to separate that control-plane state from the execution workspace.
/// Child cwd and file authority still derive from `workspace`; hosts using
@@ -566,7 +566,6 @@ pub struct EngineConfig {
/// When true and `/usr/bin/bwrap` is executable on Linux, route exec_shell
/// through bubblewrap (#2184).
pub prefer_bwrap: bool,
pub tool_launcher: Option<Vec<String>>,
/// User-configured bwrap mount extensions (#5410): extra read-only roots
/// and writable device nodes such as `/dev/null`.
pub bwrap_extensions: codewhale_sandbox::BwrapMountExtensions,
@@ -701,7 +700,6 @@ impl Default for EngineConfig {
goal_max_steps: None,
// Mirrors `Config::prefers_bwrap`: on unless explicitly opted out.
prefer_bwrap: true,
tool_launcher: None,
bwrap_extensions: codewhale_sandbox::BwrapMountExtensions::default(),
// Fail-closed (F7): `Engine::new` unconditionally installs this
// list process-wide via `read_guard::set_active`, so a default
@@ -2543,14 +2541,12 @@ impl Engine {
match shell_manager.lock() {
Ok(mut manager) => {
manager.set_prefer_bwrap(config.prefer_bwrap);
manager.set_tool_launcher(config.tool_launcher.clone());
manager.set_bwrap_extensions(config.bwrap_extensions.clone());
manager.set_denied_read_subpaths(config.read_denylist.subtree_paths());
}
Err(poisoned) => {
let mut manager = poisoned.into_inner();
manager.set_prefer_bwrap(config.prefer_bwrap);
manager.set_tool_launcher(config.tool_launcher.clone());
manager.set_bwrap_extensions(config.bwrap_extensions.clone());
manager.set_denied_read_subpaths(config.read_denylist.subtree_paths());
}
@@ -6246,9 +6242,7 @@ impl Engine {
};
}
if self.is_acp_turn() {
return self
.acp_turn_tool_build(input_policy, &route, allowed_tools, mcp_access)
.await;
return self.acp_tool_build(input_policy, &route, allowed_tools);
}
if self.rlm_host.is_some() {
return self.rlm_tool_build(input_policy, &route);
Loaded 100 of 781 files, more files were not shown because too many files have changed in this diff. Show more