diff --git a/docs/step-configuration.md b/docs/step-configuration.md index 15b457b49..8bace974f 100644 --- a/docs/step-configuration.md +++ b/docs/step-configuration.md @@ -1,6 +1,7 @@ # Step configuration files -Step creates the global `~/.stepcode/config.toml` when it first runs. +Step creates the global `~/.stepcode/config.toml` when it first runs, together +with `config.schema.json` and `models.schema.json` beside it. The project file `/.stepcode/config.toml` is optional: a missing file contributes no project settings and does not produce a startup warning. Reading or reloading settings does not create the project file or directory. @@ -19,6 +20,47 @@ and `auth.json` keep their own formats — they hold model definitions and credentials, not settings — and a stale Step endpoint recorded in `models.json` by an older release is still repaired in place at startup. +## Editor schema and configuration discovery + +`config.toml` and `models.json` each have a JSON Schema generated from the same +TypeBox definitions their loaders validate with, so a key exists in the schema +exactly when the runtime reads it. Nothing is published at a URL and nothing is +fetched: the schema travels with the build, which means an editor never +validates a file against a different version than the binary that wrote it. + +| Command | Result | +| --- | --- | +| `step config show` | The stored global and project documents, `models.json`, and every resolved path. Values are not merged or defaulted; credentials are redacted | +| `step config path --json` | The same paths, including both schema files | +| `step config schema [config\|models]` | The schema on stdout | +| `step config schema --out ` | The schema written to a file | +| `step config init` | Template, `#:schema ./config.schema.json`, and both schemas beside the file | + +The schemas are written beside the global `config.toml` only. A project file +does not receive a copy: the repository owns that directory, two ~80 KB files in +every checkout would show up in `git status`, and a relative directive there +would point at a file that is not present. Use `step config schema --out` when a +project needs one. + +The schemas are committed at `packages/coding-agent/schema/`. `pnpm run +generate:config-schema` writes them; `pnpm run check:config-schema`, which is +part of `pnpm run check`, renders them again and fails when the committed copy +differs. The theme schema is generated the same way into +`packages/coding-agent/src/theme/theme-schema.json`, which is why the built-in +themes reference it as `./theme-schema.json` instead of a repository URL. + +The global file this product creates starts with the editor directive. An +existing file keeps its own header, so adding one by hand is the only step +needed for a file written by an older release: + +```toml +#:schema ./config.schema.json +``` + +The schema describes what a file may contain; it does not replace read-time +validation. Step still reports a bad value once at load and then uses its +default, and it still ignores an unknown key rather than refusing to start. + ## Step Plan login and API-key fallback Browser sign-in checks the selected region's `/step_plan/v1/usage` endpoint diff --git a/package.json b/package.json index 2a6267ba0..f73ebdb62 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "build": "cd packages/tui && npm run build && cd ../telemetry && npm run build && cd ../providers && npm run build && cd ../agent-core && npm run build && cd ../config && npm run build && cd ../lark-adapter && npm run build && cd ../coding-agent && npm run build && cd ../../apps/cli && npm run build", "build:offline": "cd packages/tui && npm run build && cd ../telemetry && npm run build && cd ../providers && npm run build:offline && cd ../agent-core && npm run build && cd ../config && npm run build && cd ../lark-adapter && npm run build && cd ../coding-agent && npm run build && cd ../../apps/cli && npm run build", "build:binaries": "bash scripts/build-binaries.sh --product step --offline-model-data", - "check": "biome check --write --error-on-warnings . && pnpm run check:pinned-deps && pnpm run check:ts-imports && pnpm run check:layer-direction && pnpm run check:ui-layer && pnpm run check:workspace-registry && pnpm run check:tui-no-ai && pnpm run check:coding-agent-entry-freeze && pnpm run check:contracts-deps-empty && pnpm run check:derived-compat-only && pnpm run check:no-provider-dispatch && pnpm run check:session-event-transports && pnpm run check:metadata-not-in-dispatch && pnpm run check:no-secret-leak && pnpm run check:legacy-scope-prefix && pnpm run check:no-observability && pnpm run check:public-boundary && tsgo --noEmit && pnpm run check:browser-smoke", + "check": "biome check --write --error-on-warnings . && pnpm run check:pinned-deps && pnpm run check:ts-imports && pnpm run check:layer-direction && pnpm run check:ui-layer && pnpm run check:workspace-registry && pnpm run check:tui-no-ai && pnpm run check:coding-agent-entry-freeze && pnpm run check:contracts-deps-empty && pnpm run check:derived-compat-only && pnpm run check:no-provider-dispatch && pnpm run check:session-event-transports && pnpm run check:metadata-not-in-dispatch && pnpm run check:no-secret-leak && pnpm run check:legacy-scope-prefix && pnpm run check:no-observability && pnpm run check:public-boundary && pnpm run check:config-schema && tsgo --noEmit && pnpm run check:browser-smoke", "check:browser-smoke": "node scripts/check-browser-smoke.mjs", "check:pinned-deps": "node scripts/check-pinned-deps.mjs", "check:ts-imports": "node scripts/check-ts-relative-imports.mjs", @@ -34,9 +34,11 @@ "check:legacy-scope-prefix": "node scripts/check-legacy-scope-prefix.mjs", "check:no-observability": "node scripts/check-no-observability.mjs", "check:public-boundary": "node scripts/check-public-boundary.mjs", + "check:config-schema": "tsx --tsconfig tsconfig.json scripts/generate-config-schema.ts --check", "generate:models": "npm --prefix packages/providers run generate-models", "hydrate:model-data": "npm --prefix packages/providers run hydrate-model-data", "check:model-data": "npm --prefix packages/providers run check:model-data", + "generate:config-schema": "tsx --tsconfig tsconfig.json scripts/generate-config-schema.ts", "generate:model-catalog": "npm --prefix packages/providers run generate-model-catalog", "diff:model-catalog": "node scripts/diff-model-catalog.mjs", "profile:tui": "node scripts/profile-coding-agent-node.mjs --mode tui", diff --git a/packages/coding-agent/docs/compaction.md b/packages/coding-agent/docs/compaction.md index 46a0a7904..fb6b39299 100644 --- a/packages/coding-agent/docs/compaction.md +++ b/packages/coding-agent/docs/compaction.md @@ -56,7 +56,7 @@ contextTokens > min( ) ``` -`triggerRatio` defaults to `0.85` for every model (configurable globally or per model in `~/.stepcode/config.toml` or trusted `/.stepcode/config.toml`). Providers clamp each request's `max_tokens` to the remaining context minus a 4096-token safety margin, so the second term keeps room for the next response: on a small window 15% of the context is less than that margin plus the response reservation. The trigger never drops below half the window. With an 8K-or-larger output limit, a 32K window compacts at 20,480 tokens (62.5%), 64K at 53,248 (81.25%), and 131K or larger at 85%. On large windows the default leaves 15% of the window as headroom for the response and for estimation error, so a prompt the heuristic underestimates (images, unusual text) is less likely to exceed the provider limit before compaction runs. A response truncated by the clamp still goes through the overflow/length recovery below. `tokenLimit` can only make compaction trigger earlier. An explicitly configured `reserveTokens` keeps its old effect as an additional ceiling, `contextWindow - reserveTokens`. +`triggerRatio` defaults to `0.9` for every model (configurable globally or per model in `~/.stepcode/config.toml` or trusted `/.stepcode/config.toml`). Providers clamp each request's `max_tokens` to the remaining context minus a 4096-token safety margin, so the second term keeps room for the next response: on a small window 15% of the context is less than that margin plus the response reservation. The trigger never drops below half the window. With an 8K-or-larger output limit, a 32K window compacts at 20,480 tokens (62.5%) and a 64K window at 53,248 (81.25%), because the response headroom is the smaller term; a 128K-or-larger window compacts at 90%. On large windows the default leaves 10% of the window as headroom for the response and for estimation error, so a prompt the heuristic underestimates (images, unusual text) is less likely to exceed the provider limit before compaction runs. A response truncated by the clamp still goes through the overflow/length recovery below. `tokenLimit` can only make compaction trigger earlier. An explicitly configured `reserveTokens` keeps its old effect as an additional ceiling, `contextWindow - reserveTokens`. Step checks the threshold once immediately before every model request: before the first request of a prompt (counting the incoming prompt), before every follow-up request inside a tool loop (counting the new tool results and injected steering), and before the first request of a continuation. If the threshold is crossed, Step compacts inside the same agent run and resumes with the summary and retained messages. Steering queued while a follow-up request compacts is delivered to that same request. Input queued while the pre-run check compacts (or added by an `agent_start` listener) joins the first request and is measured again before it is sent; input typed while that first request's own check compacts is delivered with the next request. A final answer that crosses the threshold does not compact on its own; the next request compacts first. Context-overflow and truncated-length recovery still run after the failed response. If measuring or preparing maintenance throws unexpectedly, the request is sent unchanged and overflow recovery remains the fallback. @@ -438,7 +438,7 @@ Configure compaction in `~/.stepcode/config.toml` or trusted `/.ste ```toml [compaction] enabled = true -triggerRatio = 0.85 +triggerRatio = 0.9 keepRecentTokens = 20000 [compaction.modelTriggerRatios] @@ -448,7 +448,7 @@ keepRecentTokens = 20000 | Setting | Default | Description | |---------|---------|-------------| | `enabled` | `true` | Enable auto-compaction | -| `triggerRatio` | `0.85` | Fraction of the context window that triggers auto-compaction (0.5-0.95); small windows trigger earlier to keep response room | +| `triggerRatio` | `0.9` | Fraction of the context window that triggers auto-compaction (0.5-0.95); small windows trigger earlier to keep response room | | `modelTriggerRatios` | none | Per-model `triggerRatio`, keyed by `provider/model-id` | | `tokenLimit` | none | Absolute token ceiling; can only trigger earlier | | `triggerPolicy` | `"v2"` | `"legacy"` restores the previous threshold and checkpoints | diff --git a/packages/coding-agent/docs/context-management.md b/packages/coding-agent/docs/context-management.md index 1cc3f565f..b55b97db4 100644 --- a/packages/coding-agent/docs/context-management.md +++ b/packages/coding-agent/docs/context-management.md @@ -63,7 +63,7 @@ next request. This avoids an unused context-edit/summary call after a completed task, while explicit maintenance commands and error recovery keep their normal behavior. By default it uses the native compact trigger, `contextTokens > floor(contextWindow * compaction.triggerRatio)` with a default -ratio of 0.85, so a 131,072-token window triggers above 111,411 tokens. Smaller +ratio of 0.9, so a 131,072-token window triggers above 117,964 tokens. Smaller windows trigger earlier to keep room for the next response. See [Compaction](compaction.md#when-it-triggers) for the exact rule, per-model ratios, and the legacy policy. With at least 8,000 context tokens and enough editable old text, CLM gets the first diff --git a/packages/coding-agent/docs/custom-provider.md b/packages/coding-agent/docs/custom-provider.md index f92b507a5..da1f66f8e 100644 --- a/packages/coding-agent/docs/custom-provider.md +++ b/packages/coding-agent/docs/custom-provider.md @@ -381,7 +381,7 @@ interface OAuthLoginCallbacks { ### OAuthCredentials -Credentials are persisted in `~/.stepcode/agent/auth.json`: +Credentials are persisted in `~/.stepcode/auth.json`: ```typescript interface OAuthCredentials { diff --git a/packages/coding-agent/docs/models.md b/packages/coding-agent/docs/models.md index 42d42eeec..b9ed3a1bd 100644 --- a/packages/coding-agent/docs/models.md +++ b/packages/coding-agent/docs/models.md @@ -1,6 +1,22 @@ # Custom Models -Add custom providers and models (Ollama, vLLM, LM Studio, proxies) via `~/.stepcode/agent/models.json`. +Add custom providers and models (Ollama, vLLM, LM Studio, proxies) via +`~/.stepcode/models.json`. + +The file is validated as a whole when it loads. A structural problem — a model +without `id`, a field with the wrong type — is reported with the failing path and +**no** custom provider is registered until the file is fixed. A half-loaded +catalog would make a model silently disappear from `/model`, which is harder to +diagnose than an explicit error. + +An unknown field inside a provider or model is ignored rather than rejected, the +same way an unknown key in `config.toml` is: a newer Step may add a field, and an +older one should keep loading the file. The editor schema flags those fields, so a +typo is visible without starting a session; the runtime still ignores them. + +A schema for editor completions ships with Step: run `step config init` to write +`models.schema.json` beside the file and add `"$schema": "./models.schema.json"` +as the first key, or print it with `step config schema models`. ## Table of Contents diff --git a/packages/coding-agent/docs/providers.md b/packages/coding-agent/docs/providers.md index d110e861e..47521346a 100644 --- a/packages/coding-agent/docs/providers.md +++ b/packages/coding-agent/docs/providers.md @@ -22,7 +22,7 @@ Use `/login` in interactive mode, then select a provider: - xAI (Grok/X subscription) - OpenRouter (OAuth-minted API key billed from OpenRouter credits) -Use `/logout` to clear credentials. Tokens are stored in `~/.stepcode/agent/auth.json` and auto-refresh when expired. OpenRouter instead mints a user-controlled API key that does not expire automatically. +Use `/logout` to clear credentials. Tokens are stored in `~/.stepcode/auth.json` and auto-refresh when expired. OpenRouter instead mints a user-controlled API key that does not expire automatically. ### OpenAI Codex @@ -102,7 +102,7 @@ Reference for environment variables and `auth.json` keys: [`const envMap`](https #### Auth File -Store credentials in `~/.stepcode/agent/auth.json`: +Store credentials in `~/.stepcode/auth.json`: ```json { diff --git a/packages/coding-agent/docs/quickstart.md b/packages/coding-agent/docs/quickstart.md index 1bf9eed0f..9e0e3a1af 100644 --- a/packages/coding-agent/docs/quickstart.md +++ b/packages/coding-agent/docs/quickstart.md @@ -62,7 +62,7 @@ export ANTHROPIC_API_KEY=sk-ant-... step ``` -You can also run `/login` and select an API-key provider to store the key in `~/.stepcode/agent/auth.json`. +You can also run `/login` and select an API-key provider to store the key in `~/.stepcode/auth.json`. See [Providers](providers.md) for all supported providers, environment variables, and cloud-provider setup. diff --git a/packages/coding-agent/docs/sdk.md b/packages/coding-agent/docs/sdk.md index b81d01446..4d06c2ea3 100644 --- a/packages/coding-agent/docs/sdk.md +++ b/packages/coding-agent/docs/sdk.md @@ -528,7 +528,7 @@ Authentication resolution priority (handled by `ModelRuntime`): import { InMemoryCredentialStore } from "@step-harness/providers"; import { createAgentSession, ModelRuntime } from "@step-harness/coding-agent"; -// Default: uses ~/.stepcode/agent/auth.json and ~/.stepcode/agent/models.json +// Default: uses ~/.stepcode/auth.json and ~/.stepcode/models.json const modelRuntime = await ModelRuntime.create(); // Provider-owned auth methods and current status diff --git a/packages/coding-agent/docs/settings.md b/packages/coding-agent/docs/settings.md index 1431cacae..fb8ca6b2d 100644 --- a/packages/coding-agent/docs/settings.md +++ b/packages/coding-agent/docs/settings.md @@ -1,21 +1,40 @@ # Settings -Step uses JSON settings files with project settings overriding global settings. +Step keeps its settings in `config.toml`, with project settings overriding +global settings per key. | Location | Scope | |----------|-------| -| `~/.stepcode/agent/settings.json` | Global (all projects) | -| `.stepcode/settings.json` | Project (current directory) | +| `~/.stepcode/config.toml` | Global (all projects) | +| `.stepcode/config.toml` | Project (current directory, loaded when the project is trusted) | -Edit directly or use `/settings` for common options. To save startup model defaults interactively, use `/model` and press Enter on the desired model. To save the startup thinking level, use `/effort` and press Enter. +`models.json` and `auth.json` sit beside the global file and keep their own +formats: they hold model definitions and credentials, not settings. + +Edit directly or use `/settings` for common options. To save startup model +defaults interactively, use `/model` and press Enter on the desired model. To +save the startup thinking level, use `/effort` and press Enter. + +## Editor completions and validation + +Every key below is described by a JSON Schema that ships with Step: + +- `step config schema` prints the `config.toml` schema; `step config schema models` prints the `models.json` schema. +- `step config init` writes both schemas next to the global config file, whose first line points at it: `#:schema ./config.schema.json`. A project `.stepcode/config.toml` gets no copy, because the repository owns that directory. +- `step config path --json` reports the resolved locations, including the two schema paths. + +Nothing is downloaded: the schema always matches the binary that reads the +file, so a completion or a validation error reflects the running version. An +unknown key or an out-of-range value is what your editor flags; Step itself +reports a bad value once at startup and then uses its default. ## Project Trust -On interactive startup, step asks before trusting a project folder that contains project-local settings, resources, or project `.agents/skills` or `.claude/skills` and has no saved decision for the folder or a parent folder in `~/.stepcode/agent/trust.json`. Trusting a project allows step to load `.stepcode/settings.json` and `.stepcode` resources, install missing project packages, and execute project extensions. +On interactive startup, step asks before trusting a project folder that contains project-local settings, resources, or project `.agents/skills` or `.claude/skills` and has no saved decision for the folder or a parent folder in `~/.stepcode/agent/trust.json`. Trusting a project allows step to load `.stepcode/config.toml` and `.stepcode` resources, install missing project packages, and execute project extensions. Non-interactive modes (`-p`, `--mode json`, and `--mode rpc`) do not show a trust prompt. Without an applicable saved trust decision, they use `defaultProjectTrust` from global settings: `ask` (default) and `never` ignore those project resources, while `always` trusts them. Pass `--approve`/`-a` or `--no-approve`/`-na` to override project trust for one run. -If no extension or saved decision applies, `defaultProjectTrust` controls the fallback behavior. Set it to `"ask"`, `"always"`, or `"never"` in `~/.stepcode/agent/settings.json`, or change it with `/settings`. +If no extension or saved decision applies, `defaultProjectTrust` controls the fallback behavior. Set it to `"ask"`, `"always"`, or `"never"` in `~/.stepcode/config.toml`, or change it with `/settings`. `step config` and package commands use the same project trust flow, except `step update` never prompts. Pass `--approve` to trust project-local settings for one command or `--no-approve` to ignore them. @@ -30,22 +49,20 @@ Use `/trust` in interactive mode to save a project trust decision for future ses | `defaultProvider` | string | - | Startup provider (e.g., `"anthropic"`, `"openai"`; saved with Enter in `/model`, or edited manually) | | `defaultModel` | string | - | Startup model ID (saved with Enter in `/model`, or edited manually) | | `defaultThinkingLevel` | string | - | Startup thinking level (saved with Enter in `/effort`, or edited manually): `"off"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`, `"max"` | -| `modelThinkingLevels` | object | - | Per-model startup thinking levels keyed by `"provider/modelId"`; configure from `/settings` → Default thinking level per model or edit manually | +| `modelThinkingLevels` | table | - | Per-model startup thinking levels keyed by `"provider/modelId"`; configure from `/settings` → Default thinking level per model or edit manually | | `hideThinkingBlock` | boolean | `false` | Hide thinking blocks in output | | `showCacheMissNotices` | boolean | `false` | Show transcript notices for significant prompt-cache misses and compaction or branch-summary usage | -| `thinkingBudgets` | object | - | Custom token budgets per thinking level. Anthropic, Google, and Bedrock use these natively. OpenAI-compatible models use them when `compat.thinkingTokenBudgetField` (or `supportsThinkingTokenBudget`) is set. | +| `thinkingBudgets` | table | - | Custom token budgets per thinking level. Anthropic, Google, and Bedrock use these natively. OpenAI-compatible models use them when `compat.thinkingTokenBudgetField` (or `supportsThinkingTokenBudget`) is set. | +| `recentModels` | array | - | Recently selected models, newest first. Written by Step from `/model`; not something to edit. | #### thinkingBudgets -```json -{ - "thinkingBudgets": { - "minimal": 1024, - "low": 4096, - "medium": 10240, - "high": 32768 - } -} +```toml +[thinkingBudgets] +minimal = 1024 +low = 4096 +medium = 10240 +high = 32768 ``` ### UI & Display @@ -58,7 +75,7 @@ Use `/trust` in interactive mode to save a project trust decision for future ses | `defaultProjectTrust` | string | `"ask"` | Fallback project trust behavior: `"ask"`, `"always"`, or `"never"`. Global setting only | | `collapseChangelog` | boolean | `false` | Show condensed changelog after updates | | `enableAnalytics` | boolean | `false` | Opt-in analytics data sharing. | -| `trackingId` | string | - | Analytics tracking identifier, generated when `enableAnalytics` is turned on | +| `trackingId` | string | - | Analytics tracking identifier, generated when `enableAnalytics` is turned on. Written by Step; no need to set it. | | `doubleEscapeAction` | string | `"tree"` | Action for double-escape: `"tree"`, `"fork"`, or `"none"` | | `treeFilterMode` | string | `"default"` | Default filter for `/tree`: `"default"`, `"no-tools"`, `"user-only"`, `"labeled-only"`, `"all"` | | `editorPaddingX` | number | `0` | Horizontal padding for input editor (0-3) | @@ -69,13 +86,12 @@ Use `/trust` in interactive mode to save a project trust decision for future ses | `fullscreenExitOutput` | string | `"transcript"` | Fullscreen exit output: `"transcript"` prints the final transcript and resume hint, while `"resume-hint"` restores the previous screen and prints only the resume hint. Has no effect in regular TUI mode | | `fullscreenScrollbar` | string | `"auto"` | Fullscreen transcript scrollbar: `"auto"` shows it temporarily while scrolling, `"always"` reserves the rightmost column and keeps it visible, and `"hidden"` hides it. Has no effect in regular TUI mode | | `fullscreenCopyOnSelect` | boolean | `true` | Automatically copy selected text in fullscreen mode. When disabled, selections stay highlighted and `Ctrl+X` copies the active selection | +| `statusTips` | boolean | `true` | Show one short tip per turn under the working status row | For VS Code, include `--wait` so step resumes after the editor exits: -```json -{ - "externalEditor": "code --wait" -} +```toml +externalEditor = "code --wait" ``` ### Network @@ -83,11 +99,11 @@ For VS Code, include `--wait` so step resumes after the editor exits: | Setting | Type | Default | Description | |---------|------|---------|-------------| | `httpProxy` | string | - | HTTP proxy URL applied as `HTTP_PROXY` and `HTTPS_PROXY`. Global setting only. | +| `httpIdleTimeoutMs` | number | `300000` | HTTP header/body idle timeout in milliseconds, also used by providers with explicit stream idle timeouts. Set to `0` to disable. | +| `websocketConnectTimeoutMs` | number | `15000` | WebSocket connect/open handshake timeout in milliseconds for providers that support WebSocket transports. Set to `0` to disable. | -```json -{ - "httpProxy": "http://127.0.0.1:7890" -} +```toml +httpProxy = "http://127.0.0.1:7890" ``` ### Warnings @@ -96,12 +112,9 @@ For VS Code, include `--wait` so step resumes after the editor exits: |---------|------|---------|-------------| | `warnings.anthropicExtraUsage` | boolean | `true` | Show a warning when Anthropic subscription auth may use paid extra usage | -```json -{ - "warnings": { - "anthropicExtraUsage": false - } -} +```toml +[warnings] +anthropicExtraUsage = false ``` ### Compaction @@ -109,23 +122,20 @@ For VS Code, include `--wait` so step resumes after the editor exits: | Setting | Type | Default | Description | |---------|------|---------|-------------| | `compaction.enabled` | boolean | `true` | Enable auto-compaction | -| `compaction.triggerRatio` | number | `0.85` | Fraction of the context window that triggers auto-compaction (0.5-0.95); small windows trigger earlier to keep response room | -| `compaction.modelTriggerRatios` | object | `{}` | Per-model trigger ratios keyed by `provider/model-id` | +| `compaction.triggerRatio` | number | `0.9` | Fraction of the context window that triggers auto-compaction (0.5-0.95); small windows trigger earlier to keep response room | +| `compaction.modelTriggerRatios` | table | `{}` | Per-model trigger ratios keyed by `provider/model-id` | | `compaction.tokenLimit` | number | - | Absolute trigger ceiling; can only trigger earlier | | `compaction.triggerPolicy` | string | `"v2"` | `"legacy"` restores the previous `contextWindow - reserveTokens` trigger and checkpoints | | `compaction.reserveTokens` | number | `16384` | Legacy trigger headroom; under v2 an explicit value also caps the trigger at `contextWindow - reserveTokens` | | `compaction.keepRecentTokens` | number | `20000` | Recent tokens to keep (not summarized) | -| `compaction.contextProjection` | string | `"clm-v1"` | CLM working view; `off` selects native compaction, `lightweight-v1` selects deterministic projection | +| `compaction.contextProjection` | string | `"off"` | `off` selects native compaction, `lightweight-v1` selects deterministic projection, `clm-v1` opts into CLM | | `compaction.autoClm.enabled` | boolean | `true` | Attempt bounded CLM maintenance before native compaction | -```json -{ - "compaction": { - "enabled": true, - "triggerRatio": 0.85, - "keepRecentTokens": 20000 - } -} +```toml +[compaction] +enabled = true +triggerRatio = 0.9 +keepRecentTokens = 20000 ``` Compaction summaries use the provider's normal model/output and remaining-context @@ -157,6 +167,18 @@ Keep `retry.provider.maxRetries` at `0` unless provider-level retries are explic Temporary 429/concurrency errors retry the current model request, preserving completed tool calls. They honor `Retry-After` when available; otherwise delays grow from 1 second to at most 30 seconds with jitter. Cancellation interrupts the wait. Explicit billing/quota exhaustion is not retried. `retry.enabled: false` disables both session retry budgets. +```toml +[retry] +enabled = true +maxRetries = 3 +baseDelayMs = 2000 + +[retry.provider] +timeoutMs = 3600000 +maxRetries = 0 +maxRetryDelayMs = 60000 +``` + ### Workflow concurrency and failures The harness does not pattern-match requests such as `开10个子agent` / `launch 10 subagents`; the model decides whether they call for the `subagent` tool's parallel mode or a workflow, and whether the message is a request at all. The `subagent` tool accepts batches larger than its own window (`[subagent] max_concurrency`, default 8, at most `maxParallelTasks` = 1,000 by default) and queues the excess. Its children and workflow nodes take slots from the same process-wide admission window, whose capacity is the smallest ceiling among the runs currently attached: a batch and a workflow running together are bound by the more conservative of the two, and a 429 seen by either lowers it for both. @@ -175,21 +197,26 @@ Failed nodes are retained in the journal and final `failures` list even if the s A callback that catches an agent-node failure and rethrows a **new** error is counted twice, as one failed node and one callback failure, because the node-failure marker travels with the original error object. Rethrow the caught error itself to keep a single count. The shared admission window covers concurrent workflows. When the last one finishes, a window that was never throttled is discarded; a window that was lowered or is cooling down after a 429 is remembered for 60 seconds, so back-to-back workflows do not restart at the full ceiling straight after a 429. After that it starts fresh. -```json -{ - "retry": { - "enabled": true, - "maxRetries": 3, - "baseDelayMs": 2000, - "provider": { - "timeoutMs": 3600000, - "maxRetries": 0, - "maxRetryDelayMs": 60000 - } - } -} +### Subagent + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `subagent.background` | boolean | `true` | `false` runs `run_in_background` subagent calls in the foreground | +| `subagent.background_timeout_seconds` | integer | `3600` | Per-turn wall-clock limit of a background lane (60-7200). A call's own `timeout_seconds` takes precedence | +| `subagent.max_concurrency` | integer | `8` | Child processes a parallel batch runs at once, with no upper bound; the batch is still capped by `maxParallelTasks` | + +```toml +[subagent] +background = true +background_timeout_seconds = 3600 +max_concurrency = 8 ``` +The same three values are also accepted as `subagentBackground`, +`subagentBackgroundTimeoutSeconds` and `subagentMaxConcurrency` at the document +root, which is the shape the older StepCode JSON config used. Prefer the +`[subagent]` table. + ### Subagent models A `subagent` call may name the model its child runs on through an optional `model` parameter, written as `provider/modelId` or as a bare model id on the calling session's provider. `tasks` and `chain` entries take the same field. @@ -200,6 +227,97 @@ The catalog is not copied into the tool definition. It is large and changes with An explicit `model` is checked against the catalog before any child starts. A host with no catalog to consult skips that check and leaves the CLI as the authority. +### Permissions + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `permissionPreset` | string | `"ask"` | Initial approval tier: `"ask"`, `"approve-for-me"`, or `"full-access"`. Also accepted as `[approval] preset` | +| `approvalMode` | string | tier default | Low-level override: `"confirm"` or `"auto"`. Also accepted as `[approval] mode` | +| `nonInteractiveApproval` | string | `"deny"` | Fallback when no UI can answer: `"allow"` or `"deny"`. Also accepted as `[approval] nonInteractive` | +| `autoResume` | boolean | tier default | Resume after a bounded model error without asking again. Also accepted as `[approval] autoResume` | +| `fullAccessAcknowledged` | boolean | `false` | Recorded risk acknowledgment from the Full Access prompt. Written by Step | +| `permissionMode` | string | - | Older spelling of `permissionPreset`; migrated on load | +| `noninteractiveApproval` | string | - | Older spelling of `nonInteractiveApproval` | +| `autopilot` | boolean | - | Older spelling of `autoResume` | +| `tools.approval.preset` | string | - | Older spelling of `[approval] preset`; `[tools.approval]` accepts the same keys as `[approval]` | +| `feedback.enabled` | boolean | `true` | Older spelling of `feedbackEnabled` | + +```toml +[approval] +preset = "approve-for-me" +``` + +`[tools.approval]` is accepted as an older spelling of `[approval]`. See +[command permissions](../../../docs/command-permissions.md) for what each tier allows. + +### Feedback + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `feedbackEnabled` | boolean | `true` | Allow the feedback submission flow. `[feedback] enabled` is the older spelling | + +### Search + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `search.provider` | string | `"auto"` | Web search backend: `"auto"`, `"step"`, `"exa"`, `"firecrawl"`, `"parallel"`, `"tavily"`, `"tinyfish"`, or `"off"` | + +```toml +[search] +provider = "auto" +``` + +`STEPCODE_SEARCH_PROVIDER` takes precedence over this key. An unrecognized +value is treated as `auto` rather than disabling search. + +### Telemetry + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `telemetry.enabled` | boolean | build default | Send product telemetry. An explicit `false` is honored | +| `telemetry.spool` | boolean | - | Buffer events on disk when the endpoint is unreachable | +| `telemetry.endpoint` | string | build default | Endpoint override | + +```toml +[telemetry] +enabled = false +``` + +### MCP servers + +The `mcp_servers` table declares servers: each `[mcp_servers.]` entry is +one server. `step mcp add|remove|login` writes this table; the keys +(`command`, `args`, `url`, `env`, `enabled`, `enabled_tools`, and the rest) are +documented in [MCP catalogs](mcp-catalog.md). + +```toml +[mcp_servers.local-files] +command = "node" +args = ["server.js"] +``` + +The `mcp_import` table records which foreign MCP configs the first-launch +prompt already offered, so it does not ask again: + +```toml +[mcp_import] +reviewed = [] # one directory name per import source already offered +``` + +Step writes it. It is a record, not a setting. + +### Migrated keys + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `queueMode` | string | - | Older spelling of `steeringMode`; migrated on load | +| `websockets` | boolean | - | Older spelling of `transport`; migrated on load (`true` means `websocket`) | +| `retry.maxDelayMs` | number | - | Older spelling of `retry.provider.maxRetryDelayMs`; migrated on load | +| `skills` as a table | table | - | Older shape with `customDirectories` and `enableSkillCommands`; migrated to the array plus the boolean on load | + +Step rewrites these when it reads the file, so they keep working. Prefer the +current spelling. + ### Message Delivery | Setting | Type | Default | Description | @@ -207,8 +325,6 @@ An explicit `model` is checked against the catalog before any child starts. A ho | `steeringMode` | string | `"one-at-a-time"` | How steering messages are sent: `"all"` or `"one-at-a-time"` | | `followUpMode` | string | `"one-at-a-time"` | How follow-up messages are sent: `"all"` or `"one-at-a-time"` | | `transport` | string | `"auto"` | Preferred transport for providers that support multiple transports: `"sse"`, `"websocket"`, `"websocket-cached"`, or `"auto"` | -| `httpIdleTimeoutMs` | number | `300000` | HTTP header/body idle timeout in milliseconds, also used by providers with explicit stream idle timeouts. Set to `0` to disable. | -| `websocketConnectTimeoutMs` | number | `15000` | WebSocket connect/open handshake timeout in milliseconds for providers that support WebSocket transports. Set to `0` to disable. | ### Terminal & Images @@ -218,9 +334,9 @@ An explicit `model` is checked against the catalog before any child starts. A ho | `terminal.imageWidthCells` | number | `60` | Preferred inline image width in terminal cells | | `terminal.clearOnShrink` | boolean | `false` | Clear empty rows when content shrinks (can cause flicker) | | `terminal.showTerminalProgress` | boolean | auto | Show an OSC 9;4 busy indicator on the terminal tab while the agent works or compacts. Unset enables it in Otty and Ghostty only, outside tmux/screen; set `true` to force it in other terminals that support OSC 9;4, `false` to disable | -| `terminal.hyperlinks` | boolean or `"auto"` | `"auto"` | Override OSC 8 hyperlink support (advanced, JSON-only) | -| `terminal.images` | string or boolean | `"auto"` | Override image protocol support with `"kitty"`, `"iterm2"`, `false`, or `"auto"` (advanced, JSON-only) | -| `terminal.trueColor` | boolean or `"auto"` | `"auto"` | Override truecolor support (advanced, JSON-only) | +| `terminal.hyperlinks` | boolean or `"auto"` | `"auto"` | Override OSC 8 hyperlink support (advanced) | +| `terminal.images` | string or boolean | `"auto"` | Override image protocol support with `"kitty"`, `"iterm2"`, `false`, or `"auto"` (advanced) | +| `terminal.trueColor` | boolean or `"auto"` | `"auto"` | Override truecolor support (advanced) | | `images.autoResize` | boolean | `true` | Resize images to 2000x2000 max. Applies to `@file` attachments, `read`, and images returned by tools | | `images.blockImages` | boolean | `false` | Block all images from being sent to LLM | @@ -234,24 +350,15 @@ Changing terminal progress in `/settings` applies immediately. Disabling it clea | `shellCommandPrefix` | string | - | Prefix for every bash command (e.g., `"shopt -s expand_aliases"`) | | `npmCommand` | string[] | - | Command argv used for npm package lookup/install operations (e.g., `["mise", "exec", "node@20", "--", "npm"]`) | -Windows paths in JSON must use forward slashes or escaped backslashes: - -```json -{ - "shellPath": "C:/Program Files/Git/bin/bash.exe" -} -``` +TOML strings escape backslashes, so a Windows path is written with forward +slashes or doubled backslashes: -```json -{ - "shellPath": "C:\\Program Files\\Git\\bin\\bash.exe" -} +```toml +shellPath = "C:/Program Files/Git/bin/bash.exe" ``` -```json -{ - "npmCommand": ["mise", "exec", "node@20", "--", "npm"] -} +```toml +npmCommand = ["mise", "exec", "node@20", "--", "npm"] ``` `npmCommand` is used for all npm package-manager operations, including installs, uninstalls, and dependency installs inside git packages. User-scoped npm packages install under `~/.stepcode/agent/npm/`; project-scoped npm packages install under `.stepcode/npm/`. Use argv-style entries exactly as the process should be launched. When `npmCommand` is configured, git package dependency installs use plain `install` to avoid npm-specific flags in wrappers or alternate package managers. @@ -264,18 +371,14 @@ Windows paths in JSON must use forward slashes or escaped backslashes: `defaultTools` selects the built-in tools enabled at startup. Extension and SDK custom tools remain enabled. Available built-ins are `read`, `bash`, `powershell`, `edit`, `write`, `grep`, `find`, and `ls`: -```json -{ - "defaultTools": ["bash", "edit", "write"] -} +```toml +defaultTools = ["bash", "edit", "write"] ``` On Windows, select `powershell` instead of `bash`, or include both: -```json -{ - "defaultTools": ["read", "powershell", "edit", "write"] -} +```toml +defaultTools = ["read", "powershell", "edit", "write"] ``` An empty array starts with no built-in tools while preserving extension and SDK custom tools. `--tools` replaces this behavior with a strict allowlist for all tools, `--no-tools` disables all tools, and `--no-builtin-tools` disables the built-in defaults. `--exclude-tools` filters the resulting list. A project `defaultTools` array replaces the global array. @@ -286,11 +389,11 @@ An empty array starts with no built-in tools while preserving extension and SDK |---------|------|---------|-------------| | `sessionDir` | string | - | Directory where session files are stored. Accepts absolute or relative paths, plus `~`. | -```json -{ "sessionDir": ".stepcode/sessions" } +```toml +sessionDir = ".stepcode/sessions" ``` -When multiple sources specify a session directory, precedence is `--session-dir`, `STEP_CODING_AGENT_SESSION_DIR`, then `sessionDir` in settings.json. +When multiple sources specify a session directory, precedence is `--session-dir`, `STEP_CODING_AGENT_SESSION_DIR`, then `sessionDir` in `config.toml`. ### Model Cycling @@ -298,10 +401,8 @@ When multiple sources specify a session directory, precedence is `--session-dir` |---------|------|---------|-------------| | `enabledModels` | string[] | - | Model patterns for Ctrl+P cycling (same format as `--models` CLI flag) | -```json -{ - "enabledModels": ["claude-*", "gpt-4o", "gemini-2*"] -} +```toml +enabledModels = ["claude-*", "gpt-4o", "gemini-2*"] ``` ### Markdown @@ -315,7 +416,7 @@ When multiple sources specify a session directory, precedence is `--session-dir` These settings define where to load extensions, skills, prompts, and themes from. -Paths in `~/.stepcode/agent/settings.json` resolve relative to `~/.stepcode/agent`. Paths in `.stepcode/settings.json` resolve relative to `.stepcode`. Absolute paths and `~` are supported. +Paths in `~/.stepcode/config.toml` resolve relative to `~/.stepcode/agent`. Paths in `.stepcode/config.toml` resolve relative to `.stepcode`. Absolute paths and `~` are supported. | Setting | Type | Default | Description | |---------|------|---------|-------------| @@ -332,77 +433,74 @@ Arrays support glob patterns and exclusions. Use `!pattern` to exclude. Use `+pa String form loads all resources from a package: -```json -{ - "packages": ["step-skills", "@org/my-extension"] -} +```toml +packages = ["step-skills", "@org/my-extension"] ``` -Object form filters which resources to load: - -```json -{ - "packages": [ - { - "source": "step-skills", - "skills": ["brave-search", "transcribe"], - "extensions": [] - } - ] -} +Table form filters which resources to load: + +```toml +[[packages]] +source = "step-skills" +skills = ["brave-search", "transcribe"] +extensions = [] ``` See [packages.md](packages.md) for package management details. ## Example -```json -{ - "defaultProvider": "anthropic", - "defaultModel": "claude-sonnet-4-20250514", - "defaultThinkingLevel": "medium", - "modelThinkingLevels": { - "anthropic/claude-sonnet-4-20250514": "high" - }, - "theme": "dark", - "compaction": { - "enabled": true, - "triggerRatio": 0.85, - "keepRecentTokens": 20000 - }, - "retry": { - "enabled": true, - "maxRetries": 3 - }, - "enabledModels": ["claude-*", "gpt-4o"], - "warnings": { - "anthropicExtraUsage": true - }, - "packages": ["step-skills"] -} +```toml +defaultProvider = "anthropic" +defaultModel = "claude-sonnet-4-20250514" +defaultThinkingLevel = "medium" +theme = "dark" +enabledModels = ["claude-*", "gpt-4o"] +packages = ["step-skills"] + +[modelThinkingLevels] +"anthropic/claude-sonnet-4-20250514" = "high" + +[compaction] +enabled = true +triggerRatio = 0.9 +keepRecentTokens = 20000 + +[retry] +enabled = true +maxRetries = 3 + +[warnings] +anthropicExtraUsage = true ``` ## Project Overrides -Project settings (`.stepcode/settings.json`) override global settings. Nested objects are merged: - -```json -// ~/.stepcode/agent/settings.json (global) -{ - "theme": "dark", - "compaction": { "enabled": true, "triggerRatio": 0.85 } -} - -// .stepcode/settings.json (project) -{ - "compaction": { "triggerRatio": 0.8 } -} - -// Result -{ - "theme": "dark", - "compaction": { "enabled": true, "triggerRatio": 0.8 } -} +Project settings (`.stepcode/config.toml`) override global settings per key. +Tables are merged key by key, so a project only states what differs: + +```toml +# ~/.stepcode/config.toml (global) +theme = "dark" + +[compaction] +enabled = true +triggerRatio = 0.9 +``` + +```toml +# .stepcode/config.toml (project) +[compaction] +triggerRatio = 0.8 +``` + +```toml +# Result +theme = "dark" + +[compaction] +enabled = true +triggerRatio = 0.8 ``` ### Model-managed context diff --git a/packages/coding-agent/docs/step-integration.md b/packages/coding-agent/docs/step-integration.md index 15631be37..b36172e60 100644 --- a/packages/coding-agent/docs/step-integration.md +++ b/packages/coding-agent/docs/step-integration.md @@ -68,7 +68,7 @@ The built-in Step provider uses the `anthropic-messages` adapter, which appends accepts the older `.../v1` and `.../v1/messages` spellings; the provider normalizes them before registering the model so the version segment is never sent twice. Startup also repairs the same stale spellings in an existing -`.stepcode/agent/models.json`, including model-level overrides. If an older +`~/.stepcode/models.json`, including model-level overrides. If an older legacy Step projection recorded a built-in Step id as an OpenAI-compatible model, startup restores its `anthropic-messages` API and Step endpoint as well. Upgrading from an earlier Step build therefore does not require signing diff --git a/packages/coding-agent/docs/themes.md b/packages/coding-agent/docs/themes.md index 5416bae77..05e64c25a 100644 --- a/packages/coding-agent/docs/themes.md +++ b/packages/coding-agent/docs/themes.md @@ -89,7 +89,7 @@ vim ~/.stepcode/agent/themes/my-theme.json ```json { - "$schema": "https://github.com/stepfun-ai/step-harness/raw/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "$schema": "./theme-schema.json", "name": "my-theme", "vars": { "primary": "#00aaff", @@ -163,7 +163,7 @@ vim ~/.stepcode/agent/themes/my-theme.json ```json { - "$schema": "https://github.com/stepfun-ai/step-harness/raw/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "$schema": "./theme-schema.json", "name": "my-theme", "vars": { "blue": "#0066cc", @@ -182,7 +182,11 @@ vim ~/.stepcode/agent/themes/my-theme.json - `vars` is optional. Define reusable colors here, then reference them in `colors`. - `colors` must define all 51 required tokens. `thinkingMax`, `scrollbarThumb`, and the two search highlight tokens are optional and use the fallbacks listed below. -The `$schema` field enables editor auto-completion and validation. +The `$schema` field enables editor auto-completion and validation. Copy +`theme-schema.json` next to the theme file; the built-in themes ship with a copy +in the installation's `theme/` directory, so `./theme-schema.json` resolves +there too. Nothing is downloaded, so the schema matches the Step that loads the +theme. ## Color Tokens diff --git a/packages/coding-agent/schema/config.schema.json b/packages/coding-agent/schema/config.schema.json new file mode 100644 index 000000000..ec9aef5ae --- /dev/null +++ b/packages/coding-agent/schema/config.schema.json @@ -0,0 +1,1735 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "StepCode config.toml", + "type": "object", + "properties": { + "lastChangelogVersion": { + "type": "string", + "description": "Last changelog version shown after an update. Written by the product." + }, + "defaultProvider": { + "type": "string", + "description": "Startup provider; saved by pressing Enter in `/model`." + }, + "defaultModel": { + "type": "string", + "description": "Startup model id; saved by pressing Enter in `/model`." + }, + "recentModels": { + "type": "array", + "items": { + "type": "object", + "required": [ + "provider", + "id" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1 + }, + "id": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false, + "description": "A recently selected model." + }, + "description": "Recently selected models, newest first (global only)." + }, + "defaultThinkingLevel": { + "anyOf": [ + { + "type": "string", + "const": "off" + }, + { + "type": "string", + "const": "minimal" + }, + { + "type": "string", + "const": "low" + }, + { + "type": "string", + "const": "medium" + }, + { + "type": "string", + "const": "high" + }, + { + "type": "string", + "const": "xhigh" + }, + { + "type": "string", + "const": "max" + } + ], + "description": "Startup thinking level; saved by pressing Enter in `/effort`." + }, + "modelThinkingLevels": { + "type": "object", + "patternProperties": { + "^.*$": { + "anyOf": [ + { + "type": "string", + "const": "off" + }, + { + "type": "string", + "const": "minimal" + }, + { + "type": "string", + "const": "low" + }, + { + "type": "string", + "const": "medium" + }, + { + "type": "string", + "const": "high" + }, + { + "type": "string", + "const": "xhigh" + }, + { + "type": "string", + "const": "max" + } + ] + } + }, + "description": "Per-model startup thinking levels keyed by `provider/modelId`." + }, + "transport": { + "anyOf": [ + { + "type": "string", + "const": "sse" + }, + { + "type": "string", + "const": "websocket" + }, + { + "type": "string", + "const": "websocket-cached" + }, + { + "type": "string", + "const": "auto" + } + ], + "description": "Preferred transport for providers that support several: \"sse\", \"websocket\", \"websocket-cached\", or \"auto\" (default)." + }, + "steeringMode": { + "anyOf": [ + { + "type": "string", + "const": "all" + }, + { + "type": "string", + "const": "one-at-a-time" + } + ], + "description": "How a message typed while the model is working is delivered (default one-at-a-time)." + }, + "followUpMode": { + "anyOf": [ + { + "type": "string", + "const": "all" + }, + { + "type": "string", + "const": "one-at-a-time" + } + ], + "description": "How queued follow-up messages are delivered (default one-at-a-time)." + }, + "theme": { + "type": "string", + "description": "Theme name: \"dark\", \"light\", \"step-blue\" (default), \"step-violet\", \"step-violet-light\", or a custom theme." + }, + "compaction": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Enable automatic compaction (default true)." + }, + "reserveTokens": { + "type": "integer", + "minimum": 1, + "description": "Headroom kept free for the next response (default 16384). Under the v2 policy an explicit value only caps the trigger earlier; anything but a positive integer is ignored." + }, + "keepRecentTokens": { + "type": "number", + "minimum": 0, + "description": "Recent tokens kept verbatim by the summary (default 20000)." + }, + "triggerPolicy": { + "anyOf": [ + { + "type": "string", + "const": "v2" + }, + { + "type": "string", + "const": "legacy" + } + ], + "description": "`v2` (default) checks once before each request; `legacy` keeps the previous checkpoints." + }, + "triggerRatio": { + "type": "number", + "minimum": 0.5, + "maximum": 0.95, + "description": "Fraction of the context window that triggers compaction (default 0.9)." + }, + "modelTriggerRatios": { + "type": "object", + "patternProperties": { + "^.*$": { + "type": "number", + "minimum": 0.5, + "maximum": 0.95 + } + }, + "description": "Per-model trigger ratios keyed by `provider/id` (0.5-0.95). A value outside the range is dropped and the global ratio applies." + }, + "tokenLimit": { + "type": "integer", + "minimum": 1, + "description": "Absolute token ceiling; only makes compaction trigger earlier. Must be a positive integer, or it is ignored." + }, + "contextProjection": { + "anyOf": [ + { + "type": "string", + "const": "off" + }, + { + "type": "string", + "const": "lightweight-v1" + }, + { + "type": "string", + "const": "clm-v1" + } + ], + "description": "Context projection mode: `off` (default, native compaction), `lightweight-v1`, or `clm-v1`." + }, + "autoClm": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Enable CLM maintenance requests (default true)." + }, + "softThresholdRatio": { + "type": "number", + "minimum": 0.3, + "maximum": 0.85, + "description": "Trigger CLM earlier than the native threshold (0.3-0.85). Omit for the native threshold." + }, + "minContextTokens": { + "type": "integer", + "minimum": 1024, + "maximum": 1000000, + "description": "Smallest context that may trigger CLM (default 8000, 1024-1000000)." + }, + "cooldownTurns": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "description": "Turns between CLM requests (default 3, 1-100)." + }, + "maxRequests": { + "type": "integer", + "minimum": 1, + "maximum": 3, + "description": "CLM requests per turn (default 2, 1-3)." + }, + "timeoutMs": { + "type": "integer", + "minimum": 100, + "maximum": 300000, + "description": "CLM request timeout in milliseconds (default 90000, 100-300000)." + }, + "maxOutputTokens": { + "type": "integer", + "minimum": 512, + "maximum": 32768, + "description": "CLM summary output token limit (default 8192, 512-32768)." + }, + "minSavingsTokens": { + "type": "integer", + "minimum": 1, + "maximum": 1000000, + "description": "Smallest saving that justifies a CLM request (default 1024, 1-1000000)." + }, + "minSavingsRatio": { + "type": "number", + "minimum": 0.01, + "maximum": 0.5, + "description": "Smallest saving ratio that justifies a CLM request (0.01-0.5)." + }, + "coldMaxPrefillTokens": { + "type": "integer", + "minimum": 0, + "maximum": 100000000, + "description": "Largest uncached CLM prefill in tokens; 0 removes the bound (default 262144, 0-100000000)." + } + }, + "additionalProperties": false, + "description": "Host-scheduled maintenance inside `contextProjection = \"clm-v1\"`." + } + }, + "additionalProperties": false, + "description": "Automatic context compaction." + }, + "branchSummary": { + "type": "object", + "properties": { + "reserveTokens": { + "type": "number", + "minimum": 0, + "description": "Tokens reserved for the prompt and the summary (default 16384)." + }, + "skipPrompt": { + "type": "boolean", + "description": "Skip the \"Summarize branch?\" prompt and default to no summary (default false)." + } + }, + "additionalProperties": false, + "description": "Summaries written when navigating away from a branch." + }, + "retry": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Retry failed requests (default true)." + }, + "maxRetries": { + "type": "number", + "minimum": 0, + "description": "Transient retry attempts (default 3)." + }, + "rateLimitMaxRetries": { + "type": "integer", + "minimum": 0, + "maximum": 20, + "description": "Rate-limit retry attempts, tracked separately (default 3, 0-20)." + }, + "baseDelayMs": { + "type": "number", + "minimum": 0, + "description": "Exponential backoff base in milliseconds (default 2000)." + }, + "provider": { + "type": "object", + "properties": { + "timeoutMs": { + "type": "number", + "minimum": 0, + "description": "Provider request timeout in milliseconds." + }, + "maxRetries": { + "type": "number", + "minimum": 0, + "description": "Provider retry attempts." + }, + "maxRetryDelayMs": { + "type": "number", + "minimum": 0, + "description": "Longest server-requested delay before failing (default 60000)." + }, + "streamIdleTimeoutMs": { + "type": "number", + "minimum": 0, + "description": "Longest wait for the next provider event (default 300000); 0 disables it." + } + }, + "additionalProperties": false, + "description": "Transport-level retry and timeout limits." + }, + "maxDelayMs": { + "type": "number", + "minimum": 0, + "description": "Older spelling of `provider.maxRetryDelayMs`; migrated on load." + } + }, + "additionalProperties": false, + "description": "Retry and backoff behavior." + }, + "hideThinkingBlock": { + "type": "boolean", + "description": "Hide thinking blocks in output." + }, + "statusTips": { + "type": "boolean", + "description": "Show one tip per turn under the status row (default true)." + }, + "showCacheMissNotices": { + "type": "boolean", + "description": "Show prompt-cache miss and compaction cost notices (default false)." + }, + "externalEditor": { + "type": "string", + "description": "Command for Ctrl+G; takes precedence over `VISUAL` and `EDITOR`." + }, + "shellPath": { + "type": "string", + "description": "Shell used for tool commands; supports a leading `~`." + }, + "quietStartup": { + "type": "boolean", + "description": "Hide the startup header (default false)." + }, + "defaultProjectTrust": { + "anyOf": [ + { + "type": "string", + "const": "ask" + }, + { + "type": "string", + "const": "always" + }, + { + "type": "string", + "const": "never" + } + ], + "description": "Fallback project trust behavior for non-interactive runs (default \"ask\", global only)." + }, + "shellCommandPrefix": { + "type": "string", + "description": "Text prepended to every shell command, for example alias setup." + }, + "npmCommand": { + "type": "array", + "items": { + "type": "string" + }, + "description": "argv for package lookups, for example [\"mise\", \"exec\", \"npm\"]." + }, + "collapseChangelog": { + "type": "boolean", + "description": "Show condensed changelog entries (default false)." + }, + "enableAnalytics": { + "type": "boolean", + "description": "Opt-in analytics sharing (default false)." + }, + "trackingId": { + "type": "string", + "description": "Analytics identifier, generated when analytics is enabled." + }, + "packages": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "required": [ + "source" + ], + "properties": { + "source": { + "type": "string", + "minLength": 1, + "description": "npm or git package source." + }, + "autoload": { + "type": "boolean", + "description": "Start empty and only apply the explicit resource patterns below." + }, + "extensions": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Extension paths or patterns to load." + }, + "skills": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Skill paths or patterns to load." + }, + "prompts": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Prompt template paths or patterns to load." + }, + "themes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Theme paths or patterns to load." + } + }, + "additionalProperties": false, + "description": "A package source with resource filtering." + } + ] + }, + "description": "npm or git package sources." + }, + "extensions": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Local extension files or directories." + }, + "skills": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + }, + "description": "Local skill files or directories." + }, + { + "type": "object", + "properties": { + "enableSkillCommands": { + "type": "boolean", + "description": "Promoted to the top-level key on load." + }, + "customDirectories": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Becomes the `skills` array on load." + } + }, + "additionalProperties": false, + "description": "Older object form of `skills`; migrated on load." + } + ], + "description": "Local skill files or directories. The older `[skills]` table is migrated on load." + }, + "prompts": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Local prompt template files or directories." + }, + "themes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Local theme files or directories." + }, + "enableSkillCommands": { + "type": "boolean", + "description": "Register skills as `/skill:name` commands (default true)." + }, + "terminal": { + "type": "object", + "properties": { + "showImages": { + "type": "boolean", + "description": "Render inline images when the terminal supports them (default true)." + }, + "imageWidthCells": { + "type": "number", + "minimum": 1, + "description": "Preferred inline image width in terminal cells (default 60)." + }, + "clearOnShrink": { + "type": "boolean", + "description": "Clear empty rows when content shrinks (default false)." + }, + "showTerminalProgress": { + "type": "boolean", + "description": "Emit OSC 9;4 progress indicators (default: auto, on in Otty and Ghostty)." + }, + "hyperlinks": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "const": "auto" + } + ], + "description": "Emit OSC 8 hyperlinks: `\"auto\"` (default) decides per terminal." + }, + "images": { + "anyOf": [ + { + "type": "string", + "const": "kitty" + }, + { + "type": "string", + "const": "iterm2" + }, + { + "type": "string", + "const": "auto" + }, + { + "type": "boolean", + "const": false + } + ], + "description": "Inline image protocol: `\"kitty\"`, `\"iterm2\"`, `\"auto\"` (default), or `false`." + }, + "trueColor": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "const": "auto" + } + ], + "description": "Use 24-bit color: `\"auto\"` (default) decides per terminal." + } + }, + "additionalProperties": false, + "description": "Terminal capability overrides; detection is the default." + }, + "images": { + "type": "object", + "properties": { + "autoResize": { + "type": "boolean", + "description": "Resize images to at most 2000x2000 for model compatibility (default true). Applies to @file attachments, read, and tool-returned images." + }, + "blockImages": { + "type": "boolean", + "description": "Never send images to providers (default false)." + } + }, + "additionalProperties": false, + "description": "Image handling before a request is sent." + }, + "enabledModels": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Model patterns available to Ctrl+P cycling." + }, + "defaultTools": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Initial built-in tool selection." + }, + "doubleEscapeAction": { + "anyOf": [ + { + "type": "string", + "const": "fork" + }, + { + "type": "string", + "const": "tree" + }, + { + "type": "string", + "const": "none" + } + ], + "description": "Action for double-escape with an empty editor (default \"tree\")." + }, + "treeFilterMode": { + "anyOf": [ + { + "type": "string", + "const": "default" + }, + { + "type": "string", + "const": "no-tools" + }, + { + "type": "string", + "const": "user-only" + }, + { + "type": "string", + "const": "labeled-only" + }, + { + "type": "string", + "const": "all" + } + ], + "description": "Default filter when opening `/tree` (default \"default\")." + }, + "thinkingBudgets": { + "type": "object", + "properties": { + "minimal": { + "type": "number", + "minimum": 0, + "description": "Token budget for the `minimal` thinking level." + }, + "low": { + "type": "number", + "minimum": 0, + "description": "Token budget for the `low` thinking level." + }, + "medium": { + "type": "number", + "minimum": 0, + "description": "Token budget for the `medium` thinking level." + }, + "high": { + "type": "number", + "minimum": 0, + "description": "Token budget for the `high` thinking level." + } + }, + "additionalProperties": false, + "description": "Custom token budgets per thinking level." + }, + "editorPaddingX": { + "type": "number", + "minimum": 0, + "maximum": 3, + "description": "Horizontal padding for the input editor (default 0, 0-3). `/settings` clamps to this range." + }, + "outputPad": { + "anyOf": [ + { + "type": "number", + "const": 0 + }, + { + "type": "number", + "const": 1 + } + ], + "description": "Horizontal output padding (default 1)." + }, + "autocompleteMaxVisible": { + "type": "number", + "minimum": 3, + "maximum": 20, + "description": "Visible rows in the autocomplete dropdown (default 5, 3-20)." + }, + "showHardwareCursor": { + "type": "boolean", + "description": "Show the terminal cursor while still positioning it for IME." + }, + "markdown": { + "type": "object", + "properties": { + "codeBlockIndent": { + "type": "string", + "description": "Indent applied to rendered code blocks (default \" \")." + }, + "mermaid": { + "anyOf": [ + { + "type": "string", + "const": "off" + }, + { + "type": "string", + "const": "final" + }, + { + "type": "string", + "const": "streaming" + } + ], + "description": "Mermaid rendering: `\"off\"`, `\"final\"`, or `\"streaming\"` (default)." + } + }, + "additionalProperties": false, + "description": "Markdown rendering options." + }, + "warnings": { + "type": "object", + "properties": { + "anthropicExtraUsage": { + "type": "boolean", + "description": "Warn before an Anthropic request uses extra usage credits (default true)." + } + }, + "additionalProperties": false, + "description": "Startup and in-session warnings." + }, + "sessionDir": { + "type": "string", + "description": "Session storage directory." + }, + "httpProxy": { + "type": "string", + "description": "Proxy URL applied as `HTTP_PROXY` and `HTTPS_PROXY` for managed HTTP clients." + }, + "httpIdleTimeoutMs": { + "anyOf": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "string", + "const": "disabled" + }, + { + "type": "string", + "pattern": "^\\s*\\d+\\s*$" + } + ], + "description": "Milliseconds, a numeric string, or \"disabled\" for 0 (default 300000)." + }, + "websocketConnectTimeoutMs": { + "anyOf": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "string", + "const": "disabled" + }, + { + "type": "string", + "pattern": "^\\s*\\d+\\s*$" + } + ], + "description": "Milliseconds, a numeric string, or \"disabled\" for 0 (unset leaves it to the provider)." + }, + "tuiMode": { + "anyOf": [ + { + "type": "string", + "const": "regular" + }, + { + "type": "string", + "const": "fullscreen" + } + ], + "description": "Interactive renderer mode (default \"regular\")." + }, + "fullscreenExitOutput": { + "anyOf": [ + { + "type": "string", + "const": "transcript" + }, + { + "type": "string", + "const": "resume-hint" + } + ], + "description": "What fullscreen mode prints on exit (default \"transcript\")." + }, + "fullscreenScrollbar": { + "anyOf": [ + { + "type": "string", + "const": "hidden" + }, + { + "type": "string", + "const": "auto" + }, + { + "type": "string", + "const": "always" + } + ], + "description": "Fullscreen scrollbar visibility (default \"auto\")." + }, + "fullscreenCopyOnSelect": { + "type": "boolean", + "description": "Copy the selection when the mouse is released in fullscreen mode (default true)." + }, + "permissionPreset": { + "anyOf": [ + { + "type": "string", + "const": "ask" + }, + { + "type": "string", + "const": "approve-for-me" + }, + { + "type": "string", + "const": "full-access" + }, + { + "type": "string", + "const": "confirm" + }, + { + "type": "string", + "const": "approve" + }, + { + "type": "string", + "const": "approveforme" + }, + { + "type": "string", + "const": "bypass" + }, + { + "type": "string", + "const": "auto" + }, + { + "type": "string", + "const": "autopilot" + }, + { + "type": "string", + "const": "bypasspermissions" + }, + { + "type": "string", + "const": "fullaccess" + }, + { + "type": "string", + "const": "full" + }, + { + "type": "string", + "const": "yolo" + }, + { + "type": "string", + "const": "never-ask" + }, + { + "type": "string", + "const": "read-only" + }, + { + "type": "string", + "const": "readonly" + }, + { + "type": "string", + "const": "strict" + }, + { + "type": "string", + "const": "plan" + } + ], + "description": "Initial approval tier: `ask`, `approve-for-me` (default), or `full-access`. Legacy spellings are accepted and mapped: `confirm`/`auto`/`bypass`/`strict`/`plan`/`read-only` mean `ask`, `approve` means `approve-for-me`, `full`/`fullaccess`/`yolo`/`never-ask` mean `full-access`. Matching ignores case and surrounding spaces. Full Access also needs `fullAccessAcknowledged` from its one-time prompt." + }, + "permissionMode": { + "anyOf": [ + { + "type": "string", + "const": "ask" + }, + { + "type": "string", + "const": "approve-for-me" + }, + { + "type": "string", + "const": "full-access" + }, + { + "type": "string", + "const": "confirm" + }, + { + "type": "string", + "const": "approve" + }, + { + "type": "string", + "const": "approveforme" + }, + { + "type": "string", + "const": "bypass" + }, + { + "type": "string", + "const": "auto" + }, + { + "type": "string", + "const": "autopilot" + }, + { + "type": "string", + "const": "bypasspermissions" + }, + { + "type": "string", + "const": "fullaccess" + }, + { + "type": "string", + "const": "full" + }, + { + "type": "string", + "const": "yolo" + }, + { + "type": "string", + "const": "never-ask" + }, + { + "type": "string", + "const": "read-only" + }, + { + "type": "string", + "const": "readonly" + }, + { + "type": "string", + "const": "strict" + }, + { + "type": "string", + "const": "plan" + } + ], + "description": "Initial approval tier: `ask`, `approve-for-me` (default), or `full-access`. Legacy spellings are accepted and mapped: `confirm`/`auto`/`bypass`/`strict`/`plan`/`read-only` mean `ask`, `approve` means `approve-for-me`, `full`/`fullaccess`/`yolo`/`never-ask` mean `full-access`. Matching ignores case and surrounding spaces. Full Access also needs `fullAccessAcknowledged` from its one-time prompt." + }, + "approvalMode": { + "anyOf": [ + { + "type": "string", + "const": "confirm" + }, + { + "type": "string", + "const": "auto" + }, + { + "type": "string", + "const": "ask" + }, + { + "type": "string", + "const": "default" + }, + { + "type": "string", + "const": "acceptedits" + }, + { + "type": "string", + "const": "strict" + }, + { + "type": "string", + "const": "read-only" + }, + { + "type": "string", + "const": "readonly" + }, + { + "type": "string", + "const": "plan" + }, + { + "type": "string", + "const": "bypass" + }, + { + "type": "string", + "const": "bypasspermissions" + } + ], + "description": "Low-level override of the tier's default approval mode: `confirm` or `auto`. Legacy spellings `ask`/`default`/`acceptedits`/`strict`/`read-only`/`plan` mean `confirm`; `bypass`/`bypasspermissions` mean `auto`." + }, + "nonInteractiveApproval": { + "anyOf": [ + { + "type": "string", + "const": "allow" + }, + { + "type": "string", + "const": "deny" + } + ], + "description": "Approval fallback when no interactive UI can answer a confirmation: `allow` or `deny` (default). Matching ignores case." + }, + "noninteractiveApproval": { + "anyOf": [ + { + "type": "string", + "const": "allow" + }, + { + "type": "string", + "const": "deny" + } + ], + "description": "Accepted for older files; prefer `nonInteractiveApproval`." + }, + "autoResume": { + "type": "boolean", + "description": "Resume after a bounded model error without asking again." + }, + "autopilot": { + "type": "boolean", + "description": "Accepted for older files; prefer `autoResume`." + }, + "fullAccessAcknowledged": { + "type": "boolean", + "description": "Recorded Full Access risk acknowledgment." + }, + "feedbackEnabled": { + "type": "boolean", + "description": "Allow the feedback submission flow (default true)." + }, + "subagentBackground": { + "type": "boolean", + "description": "Flat form of `[subagent] background`." + }, + "subagentBackgroundTimeoutSeconds": { + "type": "integer", + "minimum": 60, + "maximum": 7200, + "description": "Flat form of `[subagent] background_timeout_seconds`." + }, + "subagentMaxConcurrency": { + "type": "integer", + "minimum": 1, + "description": "Flat form of `[subagent] max_concurrency`." + }, + "approval": { + "type": "object", + "properties": { + "preset": { + "anyOf": [ + { + "type": "string", + "const": "ask" + }, + { + "type": "string", + "const": "approve-for-me" + }, + { + "type": "string", + "const": "full-access" + }, + { + "type": "string", + "const": "confirm" + }, + { + "type": "string", + "const": "approve" + }, + { + "type": "string", + "const": "approveforme" + }, + { + "type": "string", + "const": "bypass" + }, + { + "type": "string", + "const": "auto" + }, + { + "type": "string", + "const": "autopilot" + }, + { + "type": "string", + "const": "bypasspermissions" + }, + { + "type": "string", + "const": "fullaccess" + }, + { + "type": "string", + "const": "full" + }, + { + "type": "string", + "const": "yolo" + }, + { + "type": "string", + "const": "never-ask" + }, + { + "type": "string", + "const": "read-only" + }, + { + "type": "string", + "const": "readonly" + }, + { + "type": "string", + "const": "strict" + }, + { + "type": "string", + "const": "plan" + } + ], + "description": "Initial approval tier: `ask`, `approve-for-me` (default), or `full-access`. Legacy spellings are accepted and mapped: `confirm`/`auto`/`bypass`/`strict`/`plan`/`read-only` mean `ask`, `approve` means `approve-for-me`, `full`/`fullaccess`/`yolo`/`never-ask` mean `full-access`. Matching ignores case and surrounding spaces. Full Access also needs `fullAccessAcknowledged` from its one-time prompt." + }, + "mode": { + "anyOf": [ + { + "type": "string", + "const": "confirm" + }, + { + "type": "string", + "const": "auto" + }, + { + "type": "string", + "const": "ask" + }, + { + "type": "string", + "const": "default" + }, + { + "type": "string", + "const": "acceptedits" + }, + { + "type": "string", + "const": "strict" + }, + { + "type": "string", + "const": "read-only" + }, + { + "type": "string", + "const": "readonly" + }, + { + "type": "string", + "const": "plan" + }, + { + "type": "string", + "const": "bypass" + }, + { + "type": "string", + "const": "bypasspermissions" + } + ], + "description": "Low-level override of the tier's default approval mode: `confirm` or `auto`. Legacy spellings `ask`/`default`/`acceptedits`/`strict`/`read-only`/`plan` mean `confirm`; `bypass`/`bypasspermissions` mean `auto`." + }, + "nonInteractive": { + "anyOf": [ + { + "type": "string", + "const": "allow" + }, + { + "type": "string", + "const": "deny" + } + ], + "description": "Approval fallback when no interactive UI can answer a confirmation: `allow` or `deny` (default). Matching ignores case." + }, + "noninteractive": { + "anyOf": [ + { + "type": "string", + "const": "allow" + }, + { + "type": "string", + "const": "deny" + } + ], + "description": "Accepted for older files; prefer `nonInteractive`." + }, + "autoResume": { + "type": "boolean", + "description": "Resume after a bounded model error without asking again." + }, + "autopilot": { + "type": "boolean", + "description": "Accepted for older files; prefer `autoResume`." + }, + "fullAccessAcknowledged": { + "type": "boolean", + "description": "Set by \"Yes, and do not ask again\" when Full Access is selected; cleared when the tier is not Full Access." + } + }, + "additionalProperties": false, + "description": "Approval tier overrides." + }, + "tools": { + "type": "object", + "properties": { + "approval": { + "type": "object", + "properties": { + "preset": { + "anyOf": [ + { + "type": "string", + "const": "ask" + }, + { + "type": "string", + "const": "approve-for-me" + }, + { + "type": "string", + "const": "full-access" + }, + { + "type": "string", + "const": "confirm" + }, + { + "type": "string", + "const": "approve" + }, + { + "type": "string", + "const": "approveforme" + }, + { + "type": "string", + "const": "bypass" + }, + { + "type": "string", + "const": "auto" + }, + { + "type": "string", + "const": "autopilot" + }, + { + "type": "string", + "const": "bypasspermissions" + }, + { + "type": "string", + "const": "fullaccess" + }, + { + "type": "string", + "const": "full" + }, + { + "type": "string", + "const": "yolo" + }, + { + "type": "string", + "const": "never-ask" + }, + { + "type": "string", + "const": "read-only" + }, + { + "type": "string", + "const": "readonly" + }, + { + "type": "string", + "const": "strict" + }, + { + "type": "string", + "const": "plan" + } + ], + "description": "Initial approval tier: `ask`, `approve-for-me` (default), or `full-access`. Legacy spellings are accepted and mapped: `confirm`/`auto`/`bypass`/`strict`/`plan`/`read-only` mean `ask`, `approve` means `approve-for-me`, `full`/`fullaccess`/`yolo`/`never-ask` mean `full-access`. Matching ignores case and surrounding spaces. Full Access also needs `fullAccessAcknowledged` from its one-time prompt." + }, + "mode": { + "anyOf": [ + { + "type": "string", + "const": "confirm" + }, + { + "type": "string", + "const": "auto" + }, + { + "type": "string", + "const": "ask" + }, + { + "type": "string", + "const": "default" + }, + { + "type": "string", + "const": "acceptedits" + }, + { + "type": "string", + "const": "strict" + }, + { + "type": "string", + "const": "read-only" + }, + { + "type": "string", + "const": "readonly" + }, + { + "type": "string", + "const": "plan" + }, + { + "type": "string", + "const": "bypass" + }, + { + "type": "string", + "const": "bypasspermissions" + } + ], + "description": "Low-level override of the tier's default approval mode: `confirm` or `auto`. Legacy spellings `ask`/`default`/`acceptedits`/`strict`/`read-only`/`plan` mean `confirm`; `bypass`/`bypasspermissions` mean `auto`." + }, + "nonInteractive": { + "anyOf": [ + { + "type": "string", + "const": "allow" + }, + { + "type": "string", + "const": "deny" + } + ], + "description": "Approval fallback when no interactive UI can answer a confirmation: `allow` or `deny` (default). Matching ignores case." + }, + "noninteractive": { + "anyOf": [ + { + "type": "string", + "const": "allow" + }, + { + "type": "string", + "const": "deny" + } + ], + "description": "Accepted for older files; prefer `nonInteractive`." + }, + "autoResume": { + "type": "boolean", + "description": "Resume after a bounded model error without asking again." + }, + "autopilot": { + "type": "boolean", + "description": "Accepted for older files; prefer `autoResume`." + }, + "fullAccessAcknowledged": { + "type": "boolean", + "description": "Set by \"Yes, and do not ask again\" when Full Access is selected; cleared when the tier is not Full Access." + } + }, + "additionalProperties": false, + "description": "Approval tier overrides." + } + }, + "additionalProperties": false, + "description": "Tool policy tables." + }, + "feedback": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Allow the feedback submission flow." + } + }, + "additionalProperties": false, + "description": "Feedback submission." + }, + "subagent": { + "type": "object", + "properties": { + "background": { + "type": "boolean", + "description": "Run `run_in_background` subagent calls in a background lane (default true)." + }, + "background_timeout_seconds": { + "type": "integer", + "minimum": 60, + "maximum": 7200, + "description": "Per-turn wall-clock limit of a background lane in seconds (default 3600, 60-7200). A call's own timeout takes precedence." + }, + "max_concurrency": { + "type": "integer", + "minimum": 1, + "description": "Child processes a parallel batch runs at once (default 8, no upper bound)." + } + }, + "additionalProperties": false, + "description": "Subagent concurrency and background lanes." + }, + "queueMode": { + "anyOf": [ + { + "type": "string", + "const": "all" + }, + { + "type": "string", + "const": "one-at-a-time" + } + ], + "description": "Older spelling of `steeringMode`; migrated on load." + }, + "websockets": { + "type": "boolean", + "description": "Older spelling of `transport`; migrated on load (true -> websocket)." + }, + "search": { + "type": "object", + "properties": { + "provider": { + "anyOf": [ + { + "type": "string", + "const": "auto" + }, + { + "type": "string", + "const": "off" + }, + { + "type": "string", + "const": "step" + }, + { + "type": "string", + "const": "exa" + }, + { + "type": "string", + "const": "firecrawl" + }, + { + "type": "string", + "const": "parallel" + }, + { + "type": "string", + "const": "tavily" + }, + { + "type": "string", + "const": "tinyfish" + } + ], + "description": "Web search backend. `auto` (default) walks the chain; a backend id pins one; `off` keeps the tool but refuses calls. The runtime treats an unrecognized value as `auto`, so a misspelling silently disables the pin instead of failing." + } + }, + "additionalProperties": false, + "description": "Web search backend selection." + }, + "telemetry": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Send product telemetry. An explicit `false` is honored over any default." + }, + "spool": { + "type": "boolean", + "description": "Buffer events on disk when the endpoint is unreachable." + }, + "endpoint": { + "type": "string", + "description": "Telemetry endpoint override." + } + }, + "additionalProperties": false, + "description": "Product telemetry." + }, + "mcp_servers": { + "type": "object", + "patternProperties": { + "^.*$": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "Executable for a stdio server; mutually exclusive with `url`." + }, + "args": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Arguments for `command`." + }, + "cwd": { + "type": "string", + "description": "Working directory for `command`." + }, + "url": { + "type": "string", + "description": "Endpoint for an HTTP or SSE server." + }, + "env": { + "type": "object", + "patternProperties": { + "^.*$": { + "type": "string" + } + }, + "description": "Extra environment for `command`." + }, + "bearer_token_env_var": { + "type": "string", + "description": "Environment variable holding a bearer token for `url`." + }, + "http_headers": { + "type": "object", + "patternProperties": { + "^.*$": { + "type": "string" + } + }, + "description": "Static headers sent with every HTTP request." + }, + "env_http_headers": { + "type": "object", + "patternProperties": { + "^.*$": { + "type": "string" + } + }, + "description": "Header names whose value is read from the named environment variable." + }, + "enabled": { + "type": "boolean", + "description": "Set `false` to keep the declaration but skip connecting." + }, + "tool_timeout_sec": { + "type": "number", + "minimum": 0, + "description": "Per-call timeout in seconds." + }, + "startup_timeout_sec": { + "type": "number", + "minimum": 0, + "description": "Connection timeout in seconds." + }, + "enabled_tools": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Publish only these tools." + }, + "disabled_tools": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Never publish these tools." + }, + "oauth": { + "type": "object", + "properties": { + "client_id": { + "type": "string", + "description": "Static OAuth client id." + }, + "client_secret": { + "type": "string", + "description": "Static OAuth client secret." + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Requested OAuth scopes." + }, + "callback_port": { + "type": "integer", + "minimum": 1, + "maximum": 65535, + "description": "Local callback port." + } + }, + "additionalProperties": false, + "description": "OAuth settings for an HTTP MCP server." + } + }, + "additionalProperties": false, + "description": "One MCP server declaration." + } + }, + "description": "MCP servers keyed by the name shown in `/mcp`." + }, + "mcp_import": { + "type": "object", + "properties": { + "reviewed": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Import sources already offered, by source id." + } + }, + "additionalProperties": false, + "description": "Record of MCP import sources already reviewed." + } + }, + "additionalProperties": false, + "description": "StepCode `config.toml`. The global file is `~/.stepcode/config.toml`; a trusted project may add `.stepcode/config.toml`, whose values win per key." +} diff --git a/packages/coding-agent/schema/models.schema.json b/packages/coding-agent/schema/models.schema.json new file mode 100644 index 000000000..eabc037da --- /dev/null +++ b/packages/coding-agent/schema/models.schema.json @@ -0,0 +1,2004 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "StepCode models.json", + "type": "object", + "required": [ + "providers" + ], + "properties": { + "$schema": { + "type": "string", + "description": "Editor reference for this file, for example \"./models.schema.json\" beside the file." + }, + "providers": { + "type": "object", + "patternProperties": { + "^.*$": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "description": "Display name for the provider." + }, + "baseUrl": { + "type": "string", + "minLength": 1, + "description": "Endpoint base URL, for example http://127.0.0.1:8000/v1." + }, + "apiKey": { + "type": "string", + "minLength": 1, + "description": "Credential or a reference to one: a literal key, `$ENV_VAR`, or `!command`. A keyless local server still needs a placeholder value to appear in `/model`." + }, + "api": { + "type": "string", + "minLength": 1, + "description": "Default request dialect: \"openai-completions\", \"openai-responses\", or \"anthropic-messages\"." + }, + "headers": { + "type": "object", + "patternProperties": { + "^.*$": { + "type": "string" + } + }, + "description": "Headers sent with every request to this provider." + }, + "compat": { + "anyOf": [ + { + "type": "object", + "properties": { + "supportsStore": { + "type": "boolean" + }, + "supportsDeveloperRole": { + "type": "boolean" + }, + "supportsReasoningEffort": { + "type": "boolean" + }, + "supportsUsageInStreaming": { + "type": "boolean" + }, + "supportsFinishReason": { + "type": "boolean" + }, + "maxTokensField": { + "anyOf": [ + { + "type": "string", + "const": "max_completion_tokens" + }, + { + "type": "string", + "const": "max_tokens" + } + ] + }, + "requiresToolResultName": { + "type": "boolean" + }, + "requiresAssistantAfterToolResult": { + "type": "boolean" + }, + "requiresThinkingAsText": { + "type": "boolean" + }, + "requiresReasoningContentOnAssistantMessages": { + "type": "boolean" + }, + "thinkingFormat": { + "anyOf": [ + { + "type": "string", + "const": "openai" + }, + { + "type": "string", + "const": "openrouter" + }, + { + "type": "string", + "const": "together" + }, + { + "type": "string", + "const": "baseten" + }, + { + "type": "string", + "const": "deepseek" + }, + { + "type": "string", + "const": "zai" + }, + { + "type": "string", + "const": "qwen" + }, + { + "type": "string", + "const": "chat-template" + }, + { + "type": "string", + "const": "qwen-chat-template" + }, + { + "type": "string", + "const": "string-thinking" + }, + { + "type": "string", + "const": "ant-ling" + } + ] + }, + "chatTemplateKwargs": { + "type": "object", + "patternProperties": { + "^.*$": { + "anyOf": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + { + "type": "object", + "required": [ + "$var" + ], + "properties": { + "$var": { + "anyOf": [ + { + "type": "string", + "const": "thinking.enabled" + }, + { + "type": "string", + "const": "thinking.effort" + } + ] + }, + "omitWhenOff": { + "type": "boolean" + } + }, + "additionalProperties": false + } + ] + } + } + }, + "chatTemplateArgs": { + "type": "object", + "patternProperties": { + "^.*$": { + "anyOf": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + { + "type": "object", + "required": [ + "$var" + ], + "properties": { + "$var": { + "anyOf": [ + { + "type": "string", + "const": "thinking.enabled" + }, + { + "type": "string", + "const": "thinking.effort" + } + ] + }, + "omitWhenOff": { + "type": "boolean" + } + }, + "additionalProperties": false + } + ] + } + } + }, + "cacheControlFormat": { + "type": "string", + "const": "anthropic" + }, + "openRouterRouting": { + "type": "object", + "properties": { + "allow_fallbacks": { + "type": "boolean" + }, + "require_parameters": { + "type": "boolean" + }, + "data_collection": { + "anyOf": [ + { + "type": "string", + "const": "deny" + }, + { + "type": "string", + "const": "allow" + } + ] + }, + "zdr": { + "type": "boolean" + }, + "enforce_distillable_text": { + "type": "boolean" + }, + "order": { + "type": "array", + "items": { + "type": "string" + } + }, + "only": { + "type": "array", + "items": { + "type": "string" + } + }, + "ignore": { + "type": "array", + "items": { + "type": "string" + } + }, + "quantizations": { + "type": "array", + "items": { + "type": "string" + } + }, + "sort": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "properties": { + "by": { + "type": "string" + }, + "partition": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + ] + }, + "max_price": { + "type": "object", + "properties": { + "prompt": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "completion": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "image": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "audio": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "request": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + } + }, + "additionalProperties": false + }, + "preferred_min_throughput": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "object", + "properties": { + "p50": { + "type": "number" + }, + "p75": { + "type": "number" + }, + "p90": { + "type": "number" + }, + "p99": { + "type": "number" + } + }, + "additionalProperties": false + } + ] + }, + "preferred_max_latency": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "object", + "properties": { + "p50": { + "type": "number" + }, + "p75": { + "type": "number" + }, + "p90": { + "type": "number" + }, + "p99": { + "type": "number" + } + }, + "additionalProperties": false + } + ] + } + }, + "additionalProperties": false + }, + "vercelGatewayRouting": { + "type": "object", + "properties": { + "only": { + "type": "array", + "items": { + "type": "string" + } + }, + "order": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "supportsOpenAIGrammarTools": { + "type": "boolean" + }, + "supportsStrictMode": { + "type": "boolean" + }, + "sendSessionAffinityHeaders": { + "type": "boolean" + }, + "deferredToolsMode": { + "type": "string", + "const": "kimi" + }, + "sessionAffinityFormat": { + "anyOf": [ + { + "type": "string", + "const": "openai" + }, + { + "type": "string", + "const": "openai-nosession" + }, + { + "type": "string", + "const": "openrouter" + } + ] + }, + "supportsLongCacheRetention": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "supportsDeveloperRole": { + "type": "boolean" + }, + "sessionAffinityFormat": { + "anyOf": [ + { + "type": "string", + "const": "openai" + }, + { + "type": "string", + "const": "openai-nosession" + }, + { + "type": "string", + "const": "openrouter" + } + ] + }, + "supportsLongCacheRetention": { + "type": "boolean" + }, + "supportsStrictMode": { + "type": "boolean" + }, + "supportsOpenAIGrammarTools": { + "type": "boolean" + }, + "supportsAdditionalTools": { + "type": "boolean" + }, + "supportsToolSearch": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "supportsEagerToolInputStreaming": { + "type": "boolean" + }, + "supportsLongCacheRetention": { + "type": "boolean" + }, + "sendSessionAffinityHeaders": { + "type": "boolean" + }, + "supportsCacheControlOnTools": { + "type": "boolean" + }, + "supportsTemperature": { + "type": "boolean" + }, + "forceAdaptiveThinking": { + "type": "boolean" + }, + "allowEmptySignature": { + "type": "boolean" + }, + "supportsStrictTools": { + "type": "boolean" + }, + "supportsToolReferences": { + "type": "boolean" + } + }, + "additionalProperties": false + } + ] + }, + "authHeader": { + "type": "boolean", + "description": "Send the credential as an Authorization header (default true for most dialects)." + }, + "models": { + "type": "array", + "items": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Model id as the endpoint expects it in the request body." + }, + "name": { + "type": "string", + "minLength": 1, + "description": "Display name in `/model`; defaults to `id`." + }, + "api": { + "type": "string", + "minLength": 1, + "description": "Request dialect for this model, overriding the provider: \"openai-completions\", \"openai-responses\", or \"anthropic-messages\"." + }, + "baseUrl": { + "type": "string", + "minLength": 1, + "description": "Endpoint for this model only; overrides the provider." + }, + "reasoning": { + "type": "boolean", + "description": "The model exposes a thinking/reasoning channel." + }, + "thinkingLevelMap": { + "type": "object", + "properties": { + "off": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "minimal": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "low": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "medium": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "high": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "xhigh": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "max": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "description": "Maps a Step thinking level onto the value this model expects. Omitted levels use the provider default.", + "additionalProperties": false + }, + "input": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "const": "text" + }, + { + "type": "string", + "const": "image" + } + ] + }, + "description": "Modalities this model accepts: \"text\" and/or \"image\". Defaults to text only." + }, + "cost": { + "type": "object", + "required": [ + "input", + "output", + "cacheRead", + "cacheWrite" + ], + "properties": { + "input": { + "type": "number", + "description": "USD per million input tokens." + }, + "output": { + "type": "number", + "description": "USD per million output tokens." + }, + "cacheRead": { + "type": "number", + "description": "USD per million cached input tokens read back." + }, + "cacheWrite": { + "type": "number", + "description": "USD per million tokens written to the prompt cache." + }, + "tiers": { + "type": "array", + "items": { + "type": "object", + "required": [ + "inputTokensAbove", + "input", + "output", + "cacheRead", + "cacheWrite" + ], + "properties": { + "inputTokensAbove": { + "type": "number", + "description": "Input token count above which this tier's rates apply." + }, + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "cacheRead": { + "type": "number" + }, + "cacheWrite": { + "type": "number" + } + }, + "description": "One pricing tier for long-context requests.", + "additionalProperties": false + }, + "description": "Long-context pricing; the base rates apply below the first tier." + } + }, + "description": "Cost per million tokens, used for usage and cache-miss reporting. Not used for billing.", + "additionalProperties": false + }, + "contextWindow": { + "type": "number", + "minimum": 1, + "description": "Context window in tokens (default 128000). Drives compaction." + }, + "maxTokens": { + "type": "number", + "minimum": 1, + "description": "Output token limit per request (default 16384)." + }, + "samplingParams": { + "type": "object", + "patternProperties": { + "^.*$": {} + }, + "description": "Extra request fields, for example temperature, top_p, or a vendor-specific flag." + }, + "headers": { + "type": "object", + "patternProperties": { + "^.*$": { + "type": "string" + } + }, + "description": "Headers added to requests for this model." + }, + "compat": { + "anyOf": [ + { + "type": "object", + "properties": { + "supportsStore": { + "type": "boolean" + }, + "supportsDeveloperRole": { + "type": "boolean" + }, + "supportsReasoningEffort": { + "type": "boolean" + }, + "supportsUsageInStreaming": { + "type": "boolean" + }, + "supportsFinishReason": { + "type": "boolean" + }, + "maxTokensField": { + "anyOf": [ + { + "type": "string", + "const": "max_completion_tokens" + }, + { + "type": "string", + "const": "max_tokens" + } + ] + }, + "requiresToolResultName": { + "type": "boolean" + }, + "requiresAssistantAfterToolResult": { + "type": "boolean" + }, + "requiresThinkingAsText": { + "type": "boolean" + }, + "requiresReasoningContentOnAssistantMessages": { + "type": "boolean" + }, + "thinkingFormat": { + "anyOf": [ + { + "type": "string", + "const": "openai" + }, + { + "type": "string", + "const": "openrouter" + }, + { + "type": "string", + "const": "together" + }, + { + "type": "string", + "const": "baseten" + }, + { + "type": "string", + "const": "deepseek" + }, + { + "type": "string", + "const": "zai" + }, + { + "type": "string", + "const": "qwen" + }, + { + "type": "string", + "const": "chat-template" + }, + { + "type": "string", + "const": "qwen-chat-template" + }, + { + "type": "string", + "const": "string-thinking" + }, + { + "type": "string", + "const": "ant-ling" + } + ] + }, + "chatTemplateKwargs": { + "type": "object", + "patternProperties": { + "^.*$": { + "anyOf": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + { + "type": "object", + "required": [ + "$var" + ], + "properties": { + "$var": { + "anyOf": [ + { + "type": "string", + "const": "thinking.enabled" + }, + { + "type": "string", + "const": "thinking.effort" + } + ] + }, + "omitWhenOff": { + "type": "boolean" + } + }, + "additionalProperties": false + } + ] + } + } + }, + "chatTemplateArgs": { + "type": "object", + "patternProperties": { + "^.*$": { + "anyOf": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + { + "type": "object", + "required": [ + "$var" + ], + "properties": { + "$var": { + "anyOf": [ + { + "type": "string", + "const": "thinking.enabled" + }, + { + "type": "string", + "const": "thinking.effort" + } + ] + }, + "omitWhenOff": { + "type": "boolean" + } + }, + "additionalProperties": false + } + ] + } + } + }, + "cacheControlFormat": { + "type": "string", + "const": "anthropic" + }, + "openRouterRouting": { + "type": "object", + "properties": { + "allow_fallbacks": { + "type": "boolean" + }, + "require_parameters": { + "type": "boolean" + }, + "data_collection": { + "anyOf": [ + { + "type": "string", + "const": "deny" + }, + { + "type": "string", + "const": "allow" + } + ] + }, + "zdr": { + "type": "boolean" + }, + "enforce_distillable_text": { + "type": "boolean" + }, + "order": { + "type": "array", + "items": { + "type": "string" + } + }, + "only": { + "type": "array", + "items": { + "type": "string" + } + }, + "ignore": { + "type": "array", + "items": { + "type": "string" + } + }, + "quantizations": { + "type": "array", + "items": { + "type": "string" + } + }, + "sort": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "properties": { + "by": { + "type": "string" + }, + "partition": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + ] + }, + "max_price": { + "type": "object", + "properties": { + "prompt": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "completion": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "image": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "audio": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "request": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + } + }, + "additionalProperties": false + }, + "preferred_min_throughput": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "object", + "properties": { + "p50": { + "type": "number" + }, + "p75": { + "type": "number" + }, + "p90": { + "type": "number" + }, + "p99": { + "type": "number" + } + }, + "additionalProperties": false + } + ] + }, + "preferred_max_latency": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "object", + "properties": { + "p50": { + "type": "number" + }, + "p75": { + "type": "number" + }, + "p90": { + "type": "number" + }, + "p99": { + "type": "number" + } + }, + "additionalProperties": false + } + ] + } + }, + "additionalProperties": false + }, + "vercelGatewayRouting": { + "type": "object", + "properties": { + "only": { + "type": "array", + "items": { + "type": "string" + } + }, + "order": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "supportsOpenAIGrammarTools": { + "type": "boolean" + }, + "supportsStrictMode": { + "type": "boolean" + }, + "sendSessionAffinityHeaders": { + "type": "boolean" + }, + "deferredToolsMode": { + "type": "string", + "const": "kimi" + }, + "sessionAffinityFormat": { + "anyOf": [ + { + "type": "string", + "const": "openai" + }, + { + "type": "string", + "const": "openai-nosession" + }, + { + "type": "string", + "const": "openrouter" + } + ] + }, + "supportsLongCacheRetention": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "supportsDeveloperRole": { + "type": "boolean" + }, + "sessionAffinityFormat": { + "anyOf": [ + { + "type": "string", + "const": "openai" + }, + { + "type": "string", + "const": "openai-nosession" + }, + { + "type": "string", + "const": "openrouter" + } + ] + }, + "supportsLongCacheRetention": { + "type": "boolean" + }, + "supportsStrictMode": { + "type": "boolean" + }, + "supportsOpenAIGrammarTools": { + "type": "boolean" + }, + "supportsAdditionalTools": { + "type": "boolean" + }, + "supportsToolSearch": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "supportsEagerToolInputStreaming": { + "type": "boolean" + }, + "supportsLongCacheRetention": { + "type": "boolean" + }, + "sendSessionAffinityHeaders": { + "type": "boolean" + }, + "supportsCacheControlOnTools": { + "type": "boolean" + }, + "supportsTemperature": { + "type": "boolean" + }, + "forceAdaptiveThinking": { + "type": "boolean" + }, + "allowEmptySignature": { + "type": "boolean" + }, + "supportsStrictTools": { + "type": "boolean" + }, + "supportsToolReferences": { + "type": "boolean" + } + }, + "additionalProperties": false + } + ] + } + }, + "description": "One model served by a provider.", + "additionalProperties": false + }, + "description": "Models this provider serves." + }, + "modelOverrides": { + "type": "object", + "patternProperties": { + "^.*$": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "description": "Display name overriding the built-in catalog." + }, + "reasoning": { + "type": "boolean", + "description": "Whether the model exposes a thinking channel." + }, + "thinkingLevelMap": { + "type": "object", + "properties": { + "off": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "minimal": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "low": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "medium": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "high": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "xhigh": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "max": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "description": "Maps a Step thinking level onto the value this model expects. Omitted levels use the provider default.", + "additionalProperties": false + }, + "input": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "const": "text" + }, + { + "type": "string", + "const": "image" + } + ] + }, + "description": "Modalities this model accepts: \"text\" and/or \"image\"." + }, + "cost": { + "type": "object", + "properties": { + "input": { + "type": "number", + "description": "USD per million input tokens." + }, + "output": { + "type": "number", + "description": "USD per million output tokens." + }, + "cacheRead": { + "type": "number", + "description": "USD per million cached input tokens read back." + }, + "cacheWrite": { + "type": "number", + "description": "USD per million tokens written to the cache." + }, + "tiers": { + "type": "array", + "items": { + "type": "object", + "required": [ + "inputTokensAbove", + "input", + "output", + "cacheRead", + "cacheWrite" + ], + "properties": { + "inputTokensAbove": { + "type": "number", + "description": "Input token count above which this tier's rates apply." + }, + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "cacheRead": { + "type": "number" + }, + "cacheWrite": { + "type": "number" + } + }, + "description": "One pricing tier for long-context requests.", + "additionalProperties": false + }, + "description": "Long-context pricing tiers." + } + }, + "description": "Overrides for a built-in model's cost. Omitted rates keep the catalog value.", + "additionalProperties": false + }, + "contextWindow": { + "type": "number", + "minimum": 1, + "description": "Context window in tokens." + }, + "maxTokens": { + "type": "number", + "minimum": 1, + "description": "Output token limit per request." + }, + "samplingParams": { + "type": "object", + "patternProperties": { + "^.*$": {} + }, + "description": "Extra request fields for this model." + }, + "headers": { + "type": "object", + "patternProperties": { + "^.*$": { + "type": "string" + } + }, + "description": "Headers added to requests for this model." + }, + "compat": { + "anyOf": [ + { + "type": "object", + "properties": { + "supportsStore": { + "type": "boolean" + }, + "supportsDeveloperRole": { + "type": "boolean" + }, + "supportsReasoningEffort": { + "type": "boolean" + }, + "supportsUsageInStreaming": { + "type": "boolean" + }, + "supportsFinishReason": { + "type": "boolean" + }, + "maxTokensField": { + "anyOf": [ + { + "type": "string", + "const": "max_completion_tokens" + }, + { + "type": "string", + "const": "max_tokens" + } + ] + }, + "requiresToolResultName": { + "type": "boolean" + }, + "requiresAssistantAfterToolResult": { + "type": "boolean" + }, + "requiresThinkingAsText": { + "type": "boolean" + }, + "requiresReasoningContentOnAssistantMessages": { + "type": "boolean" + }, + "thinkingFormat": { + "anyOf": [ + { + "type": "string", + "const": "openai" + }, + { + "type": "string", + "const": "openrouter" + }, + { + "type": "string", + "const": "together" + }, + { + "type": "string", + "const": "baseten" + }, + { + "type": "string", + "const": "deepseek" + }, + { + "type": "string", + "const": "zai" + }, + { + "type": "string", + "const": "qwen" + }, + { + "type": "string", + "const": "chat-template" + }, + { + "type": "string", + "const": "qwen-chat-template" + }, + { + "type": "string", + "const": "string-thinking" + }, + { + "type": "string", + "const": "ant-ling" + } + ] + }, + "chatTemplateKwargs": { + "type": "object", + "patternProperties": { + "^.*$": { + "anyOf": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + { + "type": "object", + "required": [ + "$var" + ], + "properties": { + "$var": { + "anyOf": [ + { + "type": "string", + "const": "thinking.enabled" + }, + { + "type": "string", + "const": "thinking.effort" + } + ] + }, + "omitWhenOff": { + "type": "boolean" + } + }, + "additionalProperties": false + } + ] + } + } + }, + "chatTemplateArgs": { + "type": "object", + "patternProperties": { + "^.*$": { + "anyOf": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + { + "type": "object", + "required": [ + "$var" + ], + "properties": { + "$var": { + "anyOf": [ + { + "type": "string", + "const": "thinking.enabled" + }, + { + "type": "string", + "const": "thinking.effort" + } + ] + }, + "omitWhenOff": { + "type": "boolean" + } + }, + "additionalProperties": false + } + ] + } + } + }, + "cacheControlFormat": { + "type": "string", + "const": "anthropic" + }, + "openRouterRouting": { + "type": "object", + "properties": { + "allow_fallbacks": { + "type": "boolean" + }, + "require_parameters": { + "type": "boolean" + }, + "data_collection": { + "anyOf": [ + { + "type": "string", + "const": "deny" + }, + { + "type": "string", + "const": "allow" + } + ] + }, + "zdr": { + "type": "boolean" + }, + "enforce_distillable_text": { + "type": "boolean" + }, + "order": { + "type": "array", + "items": { + "type": "string" + } + }, + "only": { + "type": "array", + "items": { + "type": "string" + } + }, + "ignore": { + "type": "array", + "items": { + "type": "string" + } + }, + "quantizations": { + "type": "array", + "items": { + "type": "string" + } + }, + "sort": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "properties": { + "by": { + "type": "string" + }, + "partition": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + ] + }, + "max_price": { + "type": "object", + "properties": { + "prompt": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "completion": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "image": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "audio": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + }, + "request": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + } + }, + "additionalProperties": false + }, + "preferred_min_throughput": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "object", + "properties": { + "p50": { + "type": "number" + }, + "p75": { + "type": "number" + }, + "p90": { + "type": "number" + }, + "p99": { + "type": "number" + } + }, + "additionalProperties": false + } + ] + }, + "preferred_max_latency": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "object", + "properties": { + "p50": { + "type": "number" + }, + "p75": { + "type": "number" + }, + "p90": { + "type": "number" + }, + "p99": { + "type": "number" + } + }, + "additionalProperties": false + } + ] + } + }, + "additionalProperties": false + }, + "vercelGatewayRouting": { + "type": "object", + "properties": { + "only": { + "type": "array", + "items": { + "type": "string" + } + }, + "order": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "supportsOpenAIGrammarTools": { + "type": "boolean" + }, + "supportsStrictMode": { + "type": "boolean" + }, + "sendSessionAffinityHeaders": { + "type": "boolean" + }, + "deferredToolsMode": { + "type": "string", + "const": "kimi" + }, + "sessionAffinityFormat": { + "anyOf": [ + { + "type": "string", + "const": "openai" + }, + { + "type": "string", + "const": "openai-nosession" + }, + { + "type": "string", + "const": "openrouter" + } + ] + }, + "supportsLongCacheRetention": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "supportsDeveloperRole": { + "type": "boolean" + }, + "sessionAffinityFormat": { + "anyOf": [ + { + "type": "string", + "const": "openai" + }, + { + "type": "string", + "const": "openai-nosession" + }, + { + "type": "string", + "const": "openrouter" + } + ] + }, + "supportsLongCacheRetention": { + "type": "boolean" + }, + "supportsStrictMode": { + "type": "boolean" + }, + "supportsOpenAIGrammarTools": { + "type": "boolean" + }, + "supportsAdditionalTools": { + "type": "boolean" + }, + "supportsToolSearch": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "supportsEagerToolInputStreaming": { + "type": "boolean" + }, + "supportsLongCacheRetention": { + "type": "boolean" + }, + "sendSessionAffinityHeaders": { + "type": "boolean" + }, + "supportsCacheControlOnTools": { + "type": "boolean" + }, + "supportsTemperature": { + "type": "boolean" + }, + "forceAdaptiveThinking": { + "type": "boolean" + }, + "allowEmptySignature": { + "type": "boolean" + }, + "supportsStrictTools": { + "type": "boolean" + }, + "supportsToolReferences": { + "type": "boolean" + } + }, + "additionalProperties": false + } + ] + } + }, + "description": "Edits applied to a built-in model, keyed by model id under `modelOverrides`.", + "additionalProperties": false + } + }, + "description": "Edits to built-in models, keyed by model id." + } + }, + "description": "One provider entry, keyed by the id used in `/model` and `--model provider/id`.", + "additionalProperties": false + } + }, + "description": "Providers keyed by provider id." + } + }, + "additionalProperties": false, + "description": "StepCode `models.json`: provider endpoints, credentials and model definitions. JSON with `//` comments is accepted. The global file is `~/.stepcode/models.json`." +} diff --git a/packages/coding-agent/src/cli/args.ts b/packages/coding-agent/src/cli/args.ts index 36ec6045e..e2367ede5 100644 --- a/packages/coding-agent/src/cli/args.ts +++ b/packages/coding-agent/src/cli/args.ts @@ -653,6 +653,16 @@ ${chalk.bold("Ultracode (multi-agent workflows):")} One turn: "ultracode: " (also "ultraloop: "). From the shell: ${APP_NAME} -p "ultracode: "` : ""; + const stepConfigurationText = IS_STEP_ENTRYPOINT + ? ` + +${chalk.bold("Configuration:")} + ~/.stepcode/config.toml Settings: models, compaction, permissions, search, MCP servers + ~/.stepcode/models.json Custom providers and models + .stepcode/config.toml Project overrides, loaded when the project is trusted + ${APP_NAME} config show Print the stored config.toml, models.json, and paths + ${APP_NAME} config schema Print the JSON Schema an editor completes against` + : ""; const extensionFlagsText = extensionFlags && extensionFlags.length > 0 ? `\n${chalk.bold("Extension CLI Flags:")}\n${extensionFlags @@ -675,9 +685,10 @@ ${chalk.bold("Commands:")} ${APP_NAME} update [source|self|${APP_NAME}] Update ${APP_NAME}, extensions, or model catalogs ${APP_NAME} list List installed extensions from settings ${APP_NAME} config [-l] Open TUI to enable/disable package resources (Tab switches scope) + ${APP_NAME} config Same command; the subcommands are listed by \`config --help\` ${APP_NAME} auth Print credentials or check provider readiness ${stepAuthCommandsText} - ${APP_NAME} --help Show help for install/remove/uninstall/update/list/config/auth${stepUltracodeHelpText} + ${APP_NAME} --help Show help for install/remove/uninstall/update/list/config/auth${stepConfigurationText}${stepUltracodeHelpText} ${chalk.bold("Options:")} --provider Provider name (default: ${defaultProvider}) diff --git a/packages/coding-agent/src/core/model-config.ts b/packages/coding-agent/src/core/model-config.ts index d0e0db396..f76b1ffac 100644 --- a/packages/coding-agent/src/core/model-config.ts +++ b/packages/coding-agent/src/core/model-config.ts @@ -53,15 +53,21 @@ const VercelGatewayRoutingSchema = Type.Object({ }); const ThinkingLevelMapValueSchema = Type.Union([Type.String(), Type.Null()]); -const ThinkingLevelMapSchema = Type.Object({ - off: Type.Optional(ThinkingLevelMapValueSchema), - minimal: Type.Optional(ThinkingLevelMapValueSchema), - low: Type.Optional(ThinkingLevelMapValueSchema), - medium: Type.Optional(ThinkingLevelMapValueSchema), - high: Type.Optional(ThinkingLevelMapValueSchema), - xhigh: Type.Optional(ThinkingLevelMapValueSchema), - max: Type.Optional(ThinkingLevelMapValueSchema), -}); +const ThinkingLevelMapSchema = Type.Object( + { + off: Type.Optional(ThinkingLevelMapValueSchema), + minimal: Type.Optional(ThinkingLevelMapValueSchema), + low: Type.Optional(ThinkingLevelMapValueSchema), + medium: Type.Optional(ThinkingLevelMapValueSchema), + high: Type.Optional(ThinkingLevelMapValueSchema), + xhigh: Type.Optional(ThinkingLevelMapValueSchema), + max: Type.Optional(ThinkingLevelMapValueSchema), + }, + { + description: + "Maps a Step thinking level onto the value this model expects. Omitted levels use the provider default.", + }, +); const ChatTemplateKwargScalarSchema = Type.Union([Type.String(), Type.Number(), Type.Boolean(), Type.Null()]); const ChatTemplateKwargVariableSchema = Type.Object({ @@ -147,66 +153,154 @@ const ModelCostRatesSchema = { cacheRead: Type.Number(), cacheWrite: Type.Number(), }; -const ModelCostTierSchema = Type.Object({ - inputTokensAbove: Type.Number(), - ...ModelCostRatesSchema, -}); -const ModelCostSchema = Type.Object({ - ...ModelCostRatesSchema, - tiers: Type.Optional(Type.Array(ModelCostTierSchema)), -}); +const ModelCostTierSchema = Type.Object( + { + inputTokensAbove: Type.Number({ description: "Input token count above which this tier's rates apply." }), + ...ModelCostRatesSchema, + }, + { description: "One pricing tier for long-context requests." }, +); +const ModelCostSchema = Type.Object( + { + input: Type.Number({ description: "USD per million input tokens." }), + output: Type.Number({ description: "USD per million output tokens." }), + cacheRead: Type.Number({ description: "USD per million cached input tokens read back." }), + cacheWrite: Type.Number({ description: "USD per million tokens written to the prompt cache." }), + tiers: Type.Optional( + Type.Array(ModelCostTierSchema, { + description: "Long-context pricing; the base rates apply below the first tier.", + }), + ), + }, + { description: "Cost per million tokens, used for usage and cache-miss reporting. Not used for billing." }, +); -const ModelDefinitionSchema = Type.Object({ - id: Type.String({ minLength: 1 }), - name: Type.Optional(Type.String({ minLength: 1 })), - api: Type.Optional(Type.String({ minLength: 1 })), - baseUrl: Type.Optional(Type.String({ minLength: 1 })), - reasoning: Type.Optional(Type.Boolean()), - thinkingLevelMap: Type.Optional(ThinkingLevelMapSchema), - input: Type.Optional(Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")]))), - cost: Type.Optional(ModelCostSchema), - contextWindow: Type.Optional(Type.Number()), - maxTokens: Type.Optional(Type.Number()), - samplingParams: Type.Optional(Type.Record(Type.String(), Type.Unknown())), - headers: Type.Optional(Type.Record(Type.String(), Type.String())), - compat: Type.Optional(ProviderCompatSchema), -}); +const ModelDefinitionSchema = Type.Object( + { + id: Type.String({ minLength: 1, description: "Model id as the endpoint expects it in the request body." }), + name: Type.Optional(Type.String({ minLength: 1, description: "Display name in `/model`; defaults to `id`." })), + api: Type.Optional( + Type.String({ + minLength: 1, + description: + 'Request dialect for this model, overriding the provider: "openai-completions", "openai-responses", or "anthropic-messages".', + }), + ), + baseUrl: Type.Optional( + Type.String({ minLength: 1, description: "Endpoint for this model only; overrides the provider." }), + ), + reasoning: Type.Optional(Type.Boolean({ description: "The model exposes a thinking/reasoning channel." })), + thinkingLevelMap: Type.Optional(ThinkingLevelMapSchema), + input: Type.Optional( + Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")]), { + description: 'Modalities this model accepts: "text" and/or "image". Defaults to text only.', + }), + ), + cost: Type.Optional(ModelCostSchema), + contextWindow: Type.Optional( + Type.Number({ minimum: 1, description: "Context window in tokens (default 128000). Drives compaction." }), + ), + maxTokens: Type.Optional( + Type.Number({ minimum: 1, description: "Output token limit per request (default 16384)." }), + ), + samplingParams: Type.Optional( + Type.Record(Type.String(), Type.Unknown(), { + description: "Extra request fields, for example temperature, top_p, or a vendor-specific flag.", + }), + ), + headers: Type.Optional( + Type.Record(Type.String(), Type.String(), { description: "Headers added to requests for this model." }), + ), + compat: Type.Optional(ProviderCompatSchema), + }, + { description: "One model served by a provider." }, +); -const ModelOverrideSchema = Type.Object({ - name: Type.Optional(Type.String({ minLength: 1 })), - reasoning: Type.Optional(Type.Boolean()), - thinkingLevelMap: Type.Optional(ThinkingLevelMapSchema), - input: Type.Optional(Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")]))), - cost: Type.Optional( - Type.Object({ - input: Type.Optional(Type.Number()), - output: Type.Optional(Type.Number()), - cacheRead: Type.Optional(Type.Number()), - cacheWrite: Type.Optional(Type.Number()), - tiers: Type.Optional(Type.Array(ModelCostTierSchema)), - }), - ), - contextWindow: Type.Optional(Type.Number()), - maxTokens: Type.Optional(Type.Number()), - samplingParams: Type.Optional(Type.Record(Type.String(), Type.Unknown())), - headers: Type.Optional(Type.Record(Type.String(), Type.String())), - compat: Type.Optional(ProviderCompatSchema), -}); +const ModelOverrideCostSchema = Type.Object( + { + input: Type.Optional(Type.Number({ description: "USD per million input tokens." })), + output: Type.Optional(Type.Number({ description: "USD per million output tokens." })), + cacheRead: Type.Optional(Type.Number({ description: "USD per million cached input tokens read back." })), + cacheWrite: Type.Optional(Type.Number({ description: "USD per million tokens written to the cache." })), + tiers: Type.Optional(Type.Array(ModelCostTierSchema, { description: "Long-context pricing tiers." })), + }, + { description: "Overrides for a built-in model's cost. Omitted rates keep the catalog value." }, +); -const ProviderConfigSchema = Type.Object({ - name: Type.Optional(Type.String({ minLength: 1 })), - baseUrl: Type.Optional(Type.String({ minLength: 1 })), - apiKey: Type.Optional(Type.String({ minLength: 1 })), - api: Type.Optional(Type.String({ minLength: 1 })), - headers: Type.Optional(Type.Record(Type.String(), Type.String())), - compat: Type.Optional(ProviderCompatSchema), - authHeader: Type.Optional(Type.Boolean()), - models: Type.Optional(Type.Array(ModelDefinitionSchema)), - modelOverrides: Type.Optional(Type.Record(Type.String(), ModelOverrideSchema)), -}); +const ModelOverrideSchema = Type.Object( + { + name: Type.Optional(Type.String({ minLength: 1, description: "Display name overriding the built-in catalog." })), + reasoning: Type.Optional(Type.Boolean({ description: "Whether the model exposes a thinking channel." })), + thinkingLevelMap: Type.Optional(ThinkingLevelMapSchema), + input: Type.Optional( + Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")]), { + description: 'Modalities this model accepts: "text" and/or "image".', + }), + ), + cost: Type.Optional(ModelOverrideCostSchema), + contextWindow: Type.Optional(Type.Number({ minimum: 1, description: "Context window in tokens." })), + maxTokens: Type.Optional(Type.Number({ minimum: 1, description: "Output token limit per request." })), + samplingParams: Type.Optional( + Type.Record(Type.String(), Type.Unknown(), { description: "Extra request fields for this model." }), + ), + headers: Type.Optional( + Type.Record(Type.String(), Type.String(), { description: "Headers added to requests for this model." }), + ), + compat: Type.Optional(ProviderCompatSchema), + }, + { description: "Edits applied to a built-in model, keyed by model id under `modelOverrides`." }, +); + +const ProviderConfigSchema = Type.Object( + { + name: Type.Optional(Type.String({ minLength: 1, description: "Display name for the provider." })), + baseUrl: Type.Optional( + Type.String({ minLength: 1, description: "Endpoint base URL, for example http://127.0.0.1:8000/v1." }), + ), + apiKey: Type.Optional( + Type.String({ + minLength: 1, + description: + "Credential or a reference to one: a literal key, `$ENV_VAR`, or `!command`. A keyless local server still needs a placeholder value to appear in `/model`.", + }), + ), + api: Type.Optional( + Type.String({ + minLength: 1, + description: 'Default request dialect: "openai-completions", "openai-responses", or "anthropic-messages".', + }), + ), + headers: Type.Optional( + Type.Record(Type.String(), Type.String(), { + description: "Headers sent with every request to this provider.", + }), + ), + compat: Type.Optional(ProviderCompatSchema), + authHeader: Type.Optional( + Type.Boolean({ + description: "Send the credential as an Authorization header (default true for most dialects).", + }), + ), + models: Type.Optional(Type.Array(ModelDefinitionSchema, { description: "Models this provider serves." })), + modelOverrides: Type.Optional( + Type.Record(Type.String(), ModelOverrideSchema, { + description: "Edits to built-in models, keyed by model id.", + }), + ), + }, + { description: "One provider entry, keyed by the id used in `/model` and `--model provider/id`." }, +); -const ModelsConfigSchema = Type.Object({ - providers: Type.Record(Type.String(), ProviderConfigSchema), +/** + * The validated `models.json` shape. Exported so the editor schema is rendered + * from the same object the loader compiles, instead of a copy that can drift. + * + * This is also what the loader compiles, so it stays permissive about unknown + * fields: a newer Step may add one and an older binary must still load the + * file. The editor schema adds the strictness; see `config-schema.ts`. + */ +export const ModelsConfigSchema = Type.Object({ + providers: Type.Record(Type.String(), ProviderConfigSchema, { description: "Providers keyed by provider id." }), }); const validateModelsConfig = Compile(ModelsConfigSchema); diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.ts index f32d7838f..849ed92c4 100644 --- a/packages/coding-agent/src/core/settings-manager.ts +++ b/packages/coding-agent/src/core/settings-manager.ts @@ -1,7 +1,6 @@ import type { ThinkingLevel } from "@step-harness/agent-core"; -import type { TuiMode as RendererTuiMode, ScrollViewScrollbar, TerminalCapabilities } from "@step-harness/pi-tui"; +import type { ScrollViewScrollbar, TerminalCapabilities } from "@step-harness/pi-tui"; import { supportsTerminalProgress } from "@step-harness/pi-tui"; -import type { Transport } from "@step-harness/providers"; import { DEFAULT_STREAM_IDLE_TIMEOUT_MS } from "@step-harness/providers"; import { randomUUID } from "crypto"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; @@ -12,167 +11,38 @@ import { normalizePath, resolvePath } from "../utils/paths.ts"; import { stripBom } from "../utils/text.ts"; import { type AutoClmSettings, resolveAutoClmSettings } from "./compaction/live-context/auto-options.ts"; import type { ContextProjectionMode } from "./compaction/projection.ts"; -import { - type CompactionTriggerPolicy, - type CompactionTriggerSettings, - resolveCompactionTriggerSettings, -} from "./compaction/trigger-policy.ts"; +import { type CompactionTriggerSettings, resolveCompactionTriggerSettings } from "./compaction/trigger-policy.ts"; import { DEFAULT_HTTP_IDLE_TIMEOUT_MS, parseHttpIdleTimeoutMs } from "./http-dispatcher.ts"; - -export interface CompactionSettings { - enabled?: boolean; // default: true - /** - * Trigger headroom for the legacy policy (`contextWindow - reserveTokens`). Under v2 an - * explicit value only caps the trigger earlier; the default does not affect it. It never - * sets the summary output limit, which the provider sizes from the model and context. - */ - reserveTokens?: number; // default: 16384 - keepRecentTokens?: number; // default: 20000 - /** `v2` (default): one pre-request check at `resolveCompactionThreshold()`. `legacy`: previous checkpoints and threshold. */ - triggerPolicy?: CompactionTriggerPolicy; - /** Fraction of the context window that triggers automatic compaction (0.5-0.95, default 0.9). */ - triggerRatio?: number; - /** Per-model trigger ratios keyed by `provider/id`. */ - modelTriggerRatios?: Record; - /** Absolute token ceiling that can only make automatic compaction trigger earlier. */ - tokenLimit?: number; - /** Projection mode: native compaction (`off`) by default; `clm-v1` opts into CLM. */ - contextProjection?: ContextProjectionMode; - /** Host-triggered maintenance inside clm-v1; native compaction remains the fallback. */ - autoClm?: Partial; -} - -export interface BranchSummarySettings { - reserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response) - skipPrompt?: boolean; // default: false - when true, skips "Summarize branch?" prompt and defaults to no summary -} - -export interface ProviderRetrySettings { - timeoutMs?: number; // SDK/provider request timeout in milliseconds - maxRetries?: number; // SDK/provider retry attempts - maxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing) - streamIdleTimeoutMs?: number; // default: 300000; longest wait for the next provider event, 0 disables -} - -export interface RetrySettings { - enabled?: boolean; // default: true - maxRetries?: number; // default: 3 - rateLimitMaxRetries?: number; // default: 3; independent of transient and schema retries - baseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s) - provider?: ProviderRetrySettings; -} - -export type TuiMode = RendererTuiMode; -export type FullscreenExitOutput = "transcript" | "resume-hint"; - -export interface TerminalSettings { - showImages?: boolean; // default: true (only relevant if terminal supports images) - imageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells) - clearOnShrink?: boolean; // default: false (clear empty rows when content shrinks) - showTerminalProgress?: boolean; // default: auto, on in Otty and Ghostty (OSC 9;4 terminal progress indicators) - hyperlinks?: boolean | "auto"; - images?: "kitty" | "iterm2" | "auto" | false; - trueColor?: boolean | "auto"; -} - -export interface ImageSettings { - autoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility) - blockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers -} - -export interface ThinkingBudgetsSettings { - minimal?: number; - low?: number; - medium?: number; - high?: number; -} - -export type MermaidRenderingMode = "off" | "final" | "streaming"; - -export interface MarkdownSettings { - codeBlockIndent?: string; // default: " " - mermaid?: MermaidRenderingMode; // default: "streaming" -} - -export interface WarningSettings { - anthropicExtraUsage?: boolean; // default: true -} - -export type DefaultProjectTrust = "ask" | "always" | "never"; - -export type TransportSetting = Transport; - -/** - * Package source for npm/git packages. - * - String form: load all resources from the package - * - Object form: filter which resources to load - * - autoload=false: start empty and only apply explicit resource patterns - */ -export type PackageSource = - | string - | { - source: string; - autoload?: boolean; - extensions?: string[]; - skills?: string[]; - prompts?: string[]; - themes?: string[]; - }; - -export interface Settings { - lastChangelogVersion?: string; - defaultProvider?: string; - defaultModel?: string; - recentModels?: { provider: string; id: string }[]; - defaultThinkingLevel?: ThinkingLevel; - modelThinkingLevels?: Record; // per-model default thinking level overrides keyed by "provider/modelId" - transport?: TransportSetting; // default: "auto" - steeringMode?: "all" | "one-at-a-time"; - followUpMode?: "all" | "one-at-a-time"; - theme?: string; - compaction?: CompactionSettings; - branchSummary?: BranchSummarySettings; - retry?: RetrySettings; - hideThinkingBlock?: boolean; - statusTips?: boolean; // default: true - one-line tip under the working status row, one per turn - showCacheMissNotices?: boolean; // default: false - show prompt-cache miss and compaction cost notices - externalEditor?: string; // Command for Ctrl+G external editor; takes precedence over VISUAL/EDITOR - shellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows); supports leading ~ expansion - quietStartup?: boolean; - defaultProjectTrust?: DefaultProjectTrust; // default: "ask"; global setting only - shellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., "shopt -s expand_aliases" for alias support) - npmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., ["mise", "exec", "node@20", "--", "npm"]) - collapseChangelog?: boolean; // Show condensed changelog after update - enableAnalytics?: boolean; // default: false - opt-in analytics data sharing - trackingId?: string; // analytics tracking identifier, generated when analytics is enabled - packages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering) - extensions?: string[]; // Array of local extension file paths or directories - skills?: string[]; // Array of local skill file paths or directories - prompts?: string[]; // Array of local prompt template paths or directories - themes?: string[]; // Array of local theme file paths or directories - enableSkillCommands?: boolean; // default: true - register skills as /skill:name commands - terminal?: TerminalSettings; - images?: ImageSettings; - enabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag) - defaultTools?: string[]; // Initial built-in tool selection - doubleEscapeAction?: "fork" | "tree" | "none"; // Action for double-escape with empty editor (default: "tree") - treeFilterMode?: "default" | "no-tools" | "user-only" | "labeled-only" | "all"; // Default filter when opening /tree - thinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels - editorPaddingX?: number; // Horizontal padding for input editor (default: 0) - outputPad?: 0 | 1; // Horizontal padding for chat message output (default: 1) - autocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5) - showHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME - markdown?: MarkdownSettings; - warnings?: WarningSettings; - sessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag) - httpProxy?: string; // Proxy URL applied as HTTP_PROXY and HTTPS_PROXY for Pi-managed HTTP clients - httpIdleTimeoutMs?: number; // HTTP header/body idle timeout in milliseconds; 0 disables it - websocketConnectTimeoutMs?: number; // WebSocket connect/open handshake timeout in milliseconds; 0 disables it - tuiMode?: TuiMode; // default: "regular" - fullscreenExitOutput?: FullscreenExitOutput; // default: "transcript"; no effect in regular TUI mode - fullscreenScrollbar?: ScrollViewScrollbar; // default: "auto"; no effect in regular TUI mode - fullscreenCopyOnSelect?: boolean; // default: true; no effect in regular TUI mode -} +import type { + DefaultProjectTrust, + FullscreenExitOutput, + MermaidRenderingMode, + PackageSource, + Settings, + ThinkingBudgetsSettings, + TransportSetting, + TuiMode, + WarningSettings, +} from "./settings-schema.ts"; + +export type { + BranchSummarySettings, + CompactionSettings, + DefaultProjectTrust, + FullscreenExitOutput, + ImageSettings, + MarkdownSettings, + MermaidRenderingMode, + PackageSource, + ProviderRetrySettings, + RetrySettings, + Settings, + TerminalSettings, + ThinkingBudgetsSettings, + TransportSetting, + TuiMode, + WarningSettings, +} from "./settings-schema.ts"; function isMergeableObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); diff --git a/packages/coding-agent/src/core/settings-schema.ts b/packages/coding-agent/src/core/settings-schema.ts new file mode 100644 index 000000000..1e63440a3 --- /dev/null +++ b/packages/coding-agent/src/core/settings-schema.ts @@ -0,0 +1,569 @@ +/** + * Authoritative definition of the settings stored in `config.toml`. + * + * Each settings table is declared once here as a TypeBox schema. The TypeScript + * types the settings manager uses are derived from those schemas with + * `Static<...>`, and the editor contract (`schema/config.schema.json`) is + * generated from the same objects, so the two cannot drift: a key that exists + * in one exists in the other. + * + * The schema describes what a configuration file may contain. It does not + * replace the read-time validation in the settings manager, which keeps its + * fallback behavior (report a bad value once, then use the default). + */ + +import type { ThinkingLevel } from "@step-harness/agent-core"; +import type { ScrollViewScrollbar } from "@step-harness/pi-tui"; +import type { Transport } from "@step-harness/providers"; +import { type Static, Type } from "typebox"; +import { type AutoClmSettings, DEFAULT_AUTO_CLM_SETTINGS } from "./compaction/live-context/auto-options.ts"; +import type { ContextProjectionMode } from "./compaction/projection.ts"; +import type { CompactionTriggerPolicy } from "./compaction/trigger-policy.ts"; +import { + DEFAULT_COMPACTION_TRIGGER_RATIO, + MAX_COMPACTION_TRIGGER_RATIO, + MIN_COMPACTION_TRIGGER_RATIO, +} from "./compaction/trigger-policy.ts"; + +const ThinkingLevelSchema = Type.Union([ + Type.Literal("off"), + Type.Literal("minimal"), + Type.Literal("low"), + Type.Literal("medium"), + Type.Literal("high"), + Type.Literal("xhigh"), + Type.Literal("max"), +]); + +/** + * A timeout the HTTP dispatcher accepts: milliseconds, `"disabled"`, or a + * numeric string. `parseHttpIdleTimeoutMs` treats all three as valid and + * normalizes them, so the schema must not reject the string forms. + */ +/** + * A timeout: milliseconds, `"disabled"` for 0, or a numeric string. + * + * `parseHttpIdleTimeoutMs` accepts all three and normalizes them, so the schema + * must not reject the string forms. + */ +function timeoutSetting(defaultDescription: string) { + return Type.Optional( + Type.Union([Type.Number({ minimum: 0 }), Type.Literal("disabled"), Type.String({ pattern: "^\\s*\\d+\\s*$" })], { + // Written out rather than imported: `http-dispatcher.ts` imports + // undici, and loading the HTTP stack to print one number would make + // `step config schema` pay for a dependency it never uses. + description: `Milliseconds, a numeric string, or "disabled" for 0 (${defaultDescription}).`, + }), + ); +} + +/** + * Bounds mirror `resolveAutoClmSettings`, which clamps every field. Expressing + * them here keeps the editor warning about a value the runtime would silently + * replace with its default. + */ +function bounded(value: number, min: number, max: number, description: string) { + return Type.Optional( + Type.Integer({ + minimum: min, + maximum: max, + description: `${description} (default ${value}, ${min}-${max}).`, + }), + ); +} + +const AutoClmSettingsSchema = Type.Object( + { + enabled: Type.Optional( + Type.Boolean({ + description: `Enable CLM maintenance requests (default ${DEFAULT_AUTO_CLM_SETTINGS.enabled}).`, + }), + ), + softThresholdRatio: Type.Optional( + Type.Number({ + minimum: 0.3, + maximum: 0.85, + description: "Trigger CLM earlier than the native threshold (0.3-0.85). Omit for the native threshold.", + }), + ), + minContextTokens: bounded( + DEFAULT_AUTO_CLM_SETTINGS.minContextTokens, + 1024, + 1_000_000, + "Smallest context that may trigger CLM", + ), + cooldownTurns: bounded(DEFAULT_AUTO_CLM_SETTINGS.cooldownTurns, 1, 100, "Turns between CLM requests"), + maxRequests: bounded(DEFAULT_AUTO_CLM_SETTINGS.maxRequests, 1, 3, "CLM requests per turn"), + timeoutMs: bounded(DEFAULT_AUTO_CLM_SETTINGS.timeoutMs, 100, 300_000, "CLM request timeout in milliseconds"), + maxOutputTokens: bounded( + DEFAULT_AUTO_CLM_SETTINGS.maxOutputTokens, + 512, + 32_768, + "CLM summary output token limit", + ), + minSavingsTokens: bounded( + DEFAULT_AUTO_CLM_SETTINGS.minSavingsTokens, + 1, + 1_000_000, + "Smallest saving that justifies a CLM request", + ), + minSavingsRatio: Type.Optional( + Type.Number({ + minimum: 0.01, + maximum: 0.5, + description: "Smallest saving ratio that justifies a CLM request (0.01-0.5).", + }), + ), + coldMaxPrefillTokens: bounded( + DEFAULT_AUTO_CLM_SETTINGS.coldMaxPrefillTokens, + 0, + 100_000_000, + "Largest uncached CLM prefill in tokens; 0 removes the bound", + ), + }, + { additionalProperties: false, description: 'Host-scheduled maintenance inside `contextProjection = "clm-v1"`.' }, +); + +const CompactionSettingsSchema = Type.Object( + { + enabled: Type.Optional(Type.Boolean({ description: "Enable automatic compaction (default true)." })), + reserveTokens: Type.Optional( + Type.Integer({ + minimum: 1, + description: + "Headroom kept free for the next response (default 16384). Under the v2 policy an explicit value only caps the trigger earlier; anything but a positive integer is ignored.", + }), + ), + keepRecentTokens: Type.Optional( + Type.Number({ minimum: 0, description: "Recent tokens kept verbatim by the summary (default 20000)." }), + ), + triggerPolicy: Type.Optional( + Type.Union([Type.Literal("v2"), Type.Literal("legacy")], { + description: "`v2` (default) checks once before each request; `legacy` keeps the previous checkpoints.", + }), + ), + triggerRatio: Type.Optional( + Type.Number({ + minimum: MIN_COMPACTION_TRIGGER_RATIO, + maximum: MAX_COMPACTION_TRIGGER_RATIO, + description: `Fraction of the context window that triggers compaction (default ${DEFAULT_COMPACTION_TRIGGER_RATIO}).`, + }), + ), + modelTriggerRatios: Type.Optional( + Type.Record( + Type.String(), + Type.Number({ minimum: MIN_COMPACTION_TRIGGER_RATIO, maximum: MAX_COMPACTION_TRIGGER_RATIO }), + { + description: `Per-model trigger ratios keyed by \`provider/id\` (${MIN_COMPACTION_TRIGGER_RATIO}-${MAX_COMPACTION_TRIGGER_RATIO}). A value outside the range is dropped and the global ratio applies.`, + }, + ), + ), + tokenLimit: Type.Optional( + Type.Integer({ + minimum: 1, + description: + "Absolute token ceiling; only makes compaction trigger earlier. Must be a positive integer, or it is ignored.", + }), + ), + contextProjection: Type.Optional( + Type.Union([Type.Literal("off"), Type.Literal("lightweight-v1"), Type.Literal("clm-v1")], { + description: "Context projection mode: `off` (default, native compaction), `lightweight-v1`, or `clm-v1`.", + }), + ), + autoClm: Type.Optional(AutoClmSettingsSchema), + }, + { additionalProperties: false, description: "Automatic context compaction." }, +); + +const BranchSummarySettingsSchema = Type.Object( + { + reserveTokens: Type.Optional( + Type.Number({ minimum: 0, description: "Tokens reserved for the prompt and the summary (default 16384)." }), + ), + skipPrompt: Type.Optional( + Type.Boolean({ + description: 'Skip the "Summarize branch?" prompt and default to no summary (default false).', + }), + ), + }, + { additionalProperties: false, description: "Summaries written when navigating away from a branch." }, +); + +const ProviderRetrySettingsSchema = Type.Object( + { + timeoutMs: Type.Optional(Type.Number({ minimum: 0, description: "Provider request timeout in milliseconds." })), + maxRetries: Type.Optional(Type.Number({ minimum: 0, description: "Provider retry attempts." })), + maxRetryDelayMs: Type.Optional( + Type.Number({ minimum: 0, description: "Longest server-requested delay before failing (default 60000)." }), + ), + streamIdleTimeoutMs: Type.Optional( + Type.Number({ + minimum: 0, + description: "Longest wait for the next provider event (default 300000); 0 disables it.", + }), + ), + }, + { additionalProperties: false, description: "Transport-level retry and timeout limits." }, +); + +export const RetrySettingsSchema = Type.Object( + { + enabled: Type.Optional(Type.Boolean({ description: "Retry failed requests (default true)." })), + maxRetries: Type.Optional(Type.Number({ minimum: 0, description: "Transient retry attempts (default 3)." })), + rateLimitMaxRetries: Type.Optional( + Type.Integer({ + minimum: 0, + maximum: 20, + description: "Rate-limit retry attempts, tracked separately (default 3, 0-20).", + }), + ), + baseDelayMs: Type.Optional( + Type.Number({ minimum: 0, description: "Exponential backoff base in milliseconds (default 2000)." }), + ), + provider: Type.Optional(ProviderRetrySettingsSchema), + }, + { additionalProperties: false, description: "Retry and backoff behavior." }, +); + +const TerminalSettingsSchema = Type.Object( + { + showImages: Type.Optional( + Type.Boolean({ description: "Render inline images when the terminal supports them (default true)." }), + ), + imageWidthCells: Type.Optional( + Type.Number({ minimum: 1, description: "Preferred inline image width in terminal cells (default 60)." }), + ), + clearOnShrink: Type.Optional( + Type.Boolean({ description: "Clear empty rows when content shrinks (default false)." }), + ), + showTerminalProgress: Type.Optional( + Type.Boolean({ description: "Emit OSC 9;4 progress indicators (default: auto, on in Otty and Ghostty)." }), + ), + hyperlinks: Type.Optional( + Type.Union([Type.Boolean(), Type.Literal("auto")], { + description: 'Emit OSC 8 hyperlinks: `"auto"` (default) decides per terminal.', + }), + ), + images: Type.Optional( + Type.Union([Type.Literal("kitty"), Type.Literal("iterm2"), Type.Literal("auto"), Type.Literal(false)], { + description: 'Inline image protocol: `"kitty"`, `"iterm2"`, `"auto"` (default), or `false`.', + }), + ), + trueColor: Type.Optional( + Type.Union([Type.Boolean(), Type.Literal("auto")], { + description: 'Use 24-bit color: `"auto"` (default) decides per terminal.', + }), + ), + }, + { additionalProperties: false, description: "Terminal capability overrides; detection is the default." }, +); + +const ImageSettingsSchema = Type.Object( + { + autoResize: Type.Optional( + Type.Boolean({ + description: + "Resize images to at most 2000x2000 for model compatibility (default true). Applies to @file attachments, read, and tool-returned images.", + }), + ), + blockImages: Type.Optional(Type.Boolean({ description: "Never send images to providers (default false)." })), + }, + { additionalProperties: false, description: "Image handling before a request is sent." }, +); + +const ThinkingBudgetsSettingsSchema = Type.Object( + { + minimal: Type.Optional( + Type.Number({ minimum: 0, description: "Token budget for the `minimal` thinking level." }), + ), + low: Type.Optional(Type.Number({ minimum: 0, description: "Token budget for the `low` thinking level." })), + medium: Type.Optional(Type.Number({ minimum: 0, description: "Token budget for the `medium` thinking level." })), + high: Type.Optional(Type.Number({ minimum: 0, description: "Token budget for the `high` thinking level." })), + }, + { additionalProperties: false, description: "Custom token budgets per thinking level." }, +); + +const MarkdownSettingsSchema = Type.Object( + { + codeBlockIndent: Type.Optional( + Type.String({ description: 'Indent applied to rendered code blocks (default " ").' }), + ), + mermaid: Type.Optional( + Type.Union([Type.Literal("off"), Type.Literal("final"), Type.Literal("streaming")], { + description: 'Mermaid rendering: `"off"`, `"final"`, or `"streaming"` (default).', + }), + ), + }, + { additionalProperties: false, description: "Markdown rendering options." }, +); + +const WarningSettingsSchema = Type.Object( + { + anthropicExtraUsage: Type.Optional( + Type.Boolean({ description: "Warn before an Anthropic request uses extra usage credits (default true)." }), + ), + }, + { additionalProperties: false, description: "Startup and in-session warnings." }, +); + +const PackageSourceSchema = Type.Union([ + Type.String(), + Type.Object( + { + source: Type.String({ minLength: 1, description: "npm or git package source." }), + autoload: Type.Optional( + Type.Boolean({ description: "Start empty and only apply the explicit resource patterns below." }), + ), + extensions: Type.Optional(Type.Array(Type.String(), { description: "Extension paths or patterns to load." })), + skills: Type.Optional(Type.Array(Type.String(), { description: "Skill paths or patterns to load." })), + prompts: Type.Optional( + Type.Array(Type.String(), { description: "Prompt template paths or patterns to load." }), + ), + themes: Type.Optional(Type.Array(Type.String(), { description: "Theme paths or patterns to load." })), + }, + { additionalProperties: false, description: "A package source with resource filtering." }, + ), +]); + +const RecentModelSchema = Type.Object( + { + provider: Type.String({ minLength: 1 }), + id: Type.String({ minLength: 1 }), + }, + { additionalProperties: false, description: "A recently selected model." }, +); + +/** + * The settings tables shared with the agent runtime. `config.toml` adds the + * product-owned keys on top of this; see `src/step/config-schema.ts`. + */ +export const SettingsSchema = Type.Object( + { + lastChangelogVersion: Type.Optional( + Type.String({ description: "Last changelog version shown after an update. Written by the product." }), + ), + defaultProvider: Type.Optional( + Type.String({ description: "Startup provider; saved by pressing Enter in `/model`." }), + ), + defaultModel: Type.Optional( + Type.String({ description: "Startup model id; saved by pressing Enter in `/model`." }), + ), + recentModels: Type.Optional( + Type.Array(RecentModelSchema, { description: "Recently selected models, newest first (global only)." }), + ), + defaultThinkingLevel: Type.Optional( + Type.Union( + [ + Type.Literal("off"), + Type.Literal("minimal"), + Type.Literal("low"), + Type.Literal("medium"), + Type.Literal("high"), + Type.Literal("xhigh"), + Type.Literal("max"), + ], + { description: "Startup thinking level; saved by pressing Enter in `/effort`." }, + ), + ), + modelThinkingLevels: Type.Optional( + Type.Record(Type.String(), ThinkingLevelSchema, { + description: "Per-model startup thinking levels keyed by `provider/modelId`.", + }), + ), + transport: Type.Optional( + Type.Union( + [Type.Literal("sse"), Type.Literal("websocket"), Type.Literal("websocket-cached"), Type.Literal("auto")], + { + description: + 'Preferred transport for providers that support several: "sse", "websocket", "websocket-cached", or "auto" (default).', + }, + ), + ), + steeringMode: Type.Optional( + Type.Union([Type.Literal("all"), Type.Literal("one-at-a-time")], { + description: "How a message typed while the model is working is delivered (default one-at-a-time).", + }), + ), + followUpMode: Type.Optional( + Type.Union([Type.Literal("all"), Type.Literal("one-at-a-time")], { + description: "How queued follow-up messages are delivered (default one-at-a-time).", + }), + ), + theme: Type.Optional( + Type.String({ + description: + 'Theme name: "dark", "light", "step-blue" (default), "step-violet", "step-violet-light", or a custom theme.', + }), + ), + compaction: Type.Optional(CompactionSettingsSchema), + branchSummary: Type.Optional(BranchSummarySettingsSchema), + retry: Type.Optional(RetrySettingsSchema), + hideThinkingBlock: Type.Optional(Type.Boolean({ description: "Hide thinking blocks in output." })), + statusTips: Type.Optional( + Type.Boolean({ description: "Show one tip per turn under the status row (default true)." }), + ), + showCacheMissNotices: Type.Optional( + Type.Boolean({ description: "Show prompt-cache miss and compaction cost notices (default false)." }), + ), + externalEditor: Type.Optional( + Type.String({ description: "Command for Ctrl+G; takes precedence over `VISUAL` and `EDITOR`." }), + ), + shellPath: Type.Optional(Type.String({ description: "Shell used for tool commands; supports a leading `~`." })), + quietStartup: Type.Optional(Type.Boolean({ description: "Hide the startup header (default false)." })), + defaultProjectTrust: Type.Optional( + Type.Union([Type.Literal("ask"), Type.Literal("always"), Type.Literal("never")], { + description: 'Fallback project trust behavior for non-interactive runs (default "ask", global only).', + }), + ), + shellCommandPrefix: Type.Optional( + Type.String({ description: "Text prepended to every shell command, for example alias setup." }), + ), + npmCommand: Type.Optional( + Type.Array(Type.String(), { description: 'argv for package lookups, for example ["mise", "exec", "npm"].' }), + ), + collapseChangelog: Type.Optional( + Type.Boolean({ description: "Show condensed changelog entries (default false)." }), + ), + enableAnalytics: Type.Optional(Type.Boolean({ description: "Opt-in analytics sharing (default false)." })), + trackingId: Type.Optional( + Type.String({ description: "Analytics identifier, generated when analytics is enabled." }), + ), + packages: Type.Optional(Type.Array(PackageSourceSchema, { description: "npm or git package sources." })), + extensions: Type.Optional(Type.Array(Type.String(), { description: "Local extension files or directories." })), + skills: Type.Optional(Type.Array(Type.String(), { description: "Local skill files or directories." })), + prompts: Type.Optional(Type.Array(Type.String(), { description: "Local prompt template files or directories." })), + themes: Type.Optional(Type.Array(Type.String(), { description: "Local theme files or directories." })), + enableSkillCommands: Type.Optional( + Type.Boolean({ description: "Register skills as `/skill:name` commands (default true)." }), + ), + terminal: Type.Optional(TerminalSettingsSchema), + images: Type.Optional(ImageSettingsSchema), + enabledModels: Type.Optional( + Type.Array(Type.String(), { description: "Model patterns available to Ctrl+P cycling." }), + ), + defaultTools: Type.Optional(Type.Array(Type.String(), { description: "Initial built-in tool selection." })), + doubleEscapeAction: Type.Optional( + Type.Union([Type.Literal("fork"), Type.Literal("tree"), Type.Literal("none")], { + description: 'Action for double-escape with an empty editor (default "tree").', + }), + ), + treeFilterMode: Type.Optional( + Type.Union( + [ + Type.Literal("default"), + Type.Literal("no-tools"), + Type.Literal("user-only"), + Type.Literal("labeled-only"), + Type.Literal("all"), + ], + { description: 'Default filter when opening `/tree` (default "default").' }, + ), + ), + thinkingBudgets: Type.Optional(ThinkingBudgetsSettingsSchema), + editorPaddingX: Type.Optional( + Type.Number({ + minimum: 0, + maximum: 3, + description: "Horizontal padding for the input editor (default 0, 0-3). `/settings` clamps to this range.", + }), + ), + outputPad: Type.Optional( + Type.Union([Type.Literal(0), Type.Literal(1)], { description: "Horizontal output padding (default 1)." }), + ), + autocompleteMaxVisible: Type.Optional( + Type.Number({ + minimum: 3, + maximum: 20, + description: "Visible rows in the autocomplete dropdown (default 5, 3-20).", + }), + ), + showHardwareCursor: Type.Optional( + Type.Boolean({ description: "Show the terminal cursor while still positioning it for IME." }), + ), + markdown: Type.Optional(MarkdownSettingsSchema), + warnings: Type.Optional(WarningSettingsSchema), + sessionDir: Type.Optional(Type.String({ description: "Session storage directory." })), + httpProxy: Type.Optional( + Type.String({ description: "Proxy URL applied as `HTTP_PROXY` and `HTTPS_PROXY` for managed HTTP clients." }), + ), + httpIdleTimeoutMs: timeoutSetting("default 300000"), + // No default: an unset value is passed to the provider, which uses its own. + websocketConnectTimeoutMs: timeoutSetting("unset leaves it to the provider"), + tuiMode: Type.Optional( + Type.Union([Type.Literal("regular"), Type.Literal("fullscreen")], { + description: 'Interactive renderer mode (default "regular").', + }), + ), + fullscreenExitOutput: Type.Optional( + Type.Union([Type.Literal("transcript"), Type.Literal("resume-hint")], { + description: 'What fullscreen mode prints on exit (default "transcript").', + }), + ), + fullscreenScrollbar: Type.Optional( + Type.Union([Type.Literal("hidden"), Type.Literal("auto"), Type.Literal("always")], { + description: 'Fullscreen scrollbar visibility (default "auto").', + }), + ), + fullscreenCopyOnSelect: Type.Optional( + Type.Boolean({ + description: "Copy the selection when the mouse is released in fullscreen mode (default true).", + }), + ), + }, + { additionalProperties: false, description: "Settings stored in `config.toml`." }, +); + +export type CompactionSettings = Static; +export type BranchSummarySettings = Static; +export type ProviderRetrySettings = Static; +export type RetrySettings = Static; +export type TerminalSettings = Static; +export type ImageSettings = Static; +export type ThinkingBudgetsSettings = Static; +export type MarkdownSettings = Static; +export type WarningSettings = Static; +export type AutoClmSettingsInput = Static; +export type PackageSource = Static; + +export type MermaidRenderingMode = NonNullable["mermaid"]>; +export type DefaultProjectTrust = NonNullable["defaultProjectTrust"]>; +export type TransportSetting = NonNullable["transport"]>; +export type TuiMode = NonNullable["tuiMode"]>; +export type FullscreenExitOutput = NonNullable["fullscreenExitOutput"]>; +export type Settings = Static; + +/** + * Compile-time equality between a schema-derived type and the type its + * consumers import. + * + * Both directions matter. A schema that gains a member the runtime does not + * accept lets a value through that the runtime then ignores; a schema that loses + * one rejects a value the runtime would honor. Either way the editor and the + * runtime disagree about the same file, so the build fails here rather than at + * the user. + */ +// `never` here would be the bug: `Expect` satisfies `T extends true`, so a +// diverged type would pass silently. `false` is the only value the constraint +// rejects. +type Exact = [A] extends [B] ? ([B] extends [A] ? true : false) : false; +type Expect = T; + +export interface SettingsSchemaContract { + transport: Expect>; + thinkingLevel: Expect["defaultThinkingLevel"]>, ThinkingLevel>>; + triggerPolicy: Expect< + Exact>["triggerPolicy"]>, CompactionTriggerPolicy> + >; + contextProjection: Expect< + Exact< + NonNullable>["contextProjection"]>, + ContextProjectionMode + > + >; + fullscreenScrollbar: Expect< + Exact>["fullscreenScrollbar"]>, ScrollViewScrollbar> + >; + // The schema's table is a `Partial<>` of the runtime type: every field is + // optional in a config file and required once resolved. + autoClm: Expect>>; +} diff --git a/packages/coding-agent/src/features/step.ts b/packages/coding-agent/src/features/step.ts index dac9a8624..e684f6c80 100644 --- a/packages/coding-agent/src/features/step.ts +++ b/packages/coding-agent/src/features/step.ts @@ -442,12 +442,11 @@ export function createStepExtension(options: StepExtensionOptions = {}): Extensi pi.on("before_provider_headers", (event, ctx) => { const model = ctx.model; if (!model) return; - // x-step-client marks every request. The session id additionally rides - // every request to a Step first-party host (api.stepfun.com / .ai) as - // x-session-id, keyed by the request URL host regardless of provider id. - // The remaining workspace/goal/provider attribution is policy-gated - // (allowlist + highSensitivityFields), so it never egresses to a - // third-party endpoint. + // x-step-client marks every request. The session/workspace/provider + // attribution follows only Step-owned providers (native step + product + // proxies), keyed by provider id, so it never egresses to a distinct + // third-party provider. Caveat: overriding STEP_BASE_URL under the + // "step" id points that provider at another host and attribution follows. applyStepTraceHeaders( event.headers, { diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.ts index 1a028d924..c28f9eb08 100644 --- a/packages/coding-agent/src/package-manager-cli.ts +++ b/packages/coding-agent/src/package-manager-cli.ts @@ -10,7 +10,7 @@ import { DefaultResourceLoader } from "./core/resource-loader.ts"; import { SettingsManager, type SettingsManagerCreateOptions } from "./core/settings-manager.ts"; import { hasTrustRequiringProjectResources, ProjectTrustStore } from "./core/trust-manager.ts"; import type { StartupUiHooks } from "./modes/interactive-contract.ts"; -import { STEP_CONFIG_SUBCOMMANDS } from "./step/command-compat.ts"; +import { STEP_CONFIG_SUBCOMMANDS } from "./step/config-subcommands.ts"; import { isStepStorageContext, resolveStepAgentDir } from "./step/environment.ts"; export type PackageCommand = "install" | "remove" | "update" | "list"; @@ -73,9 +73,16 @@ function printConfigCommandHelp(): void { console.log(`${chalk.bold("Usage:")} ${CONFIG_COMMAND_USAGE} -Open the resource configuration TUI to enable or disable package resources. -Without -l, starts in global settings (~/${CONFIG_DIR_NAME}/config.toml). -Press Tab in the TUI to switch between global and project-local modes. +Without a subcommand, opens the resource configuration TUI to enable or disable +package resources. Without -l, it starts in global settings +(~/${CONFIG_DIR_NAME}/config.toml); press Tab to switch between global and +project-local modes. + +Settings themselves (models, compaction, permissions, search, MCP servers) live +in the same config.toml. \`config show\` prints the stored global and project +documents with credentials redacted, \`config schema\` prints the JSON Schema an +editor completes and validates against, and \`config init\` writes a template +plus that schema beside the global file. Options: -l, --local Edit project overrides (${CONFIG_DIR_NAME}/config.toml) diff --git a/packages/coding-agent/src/step/command-compat.ts b/packages/coding-agent/src/step/command-compat.ts index b36883178..66feb48ca 100644 --- a/packages/coding-agent/src/step/command-compat.ts +++ b/packages/coding-agent/src/step/command-compat.ts @@ -8,12 +8,23 @@ * Pi's parser/local runtime low-risk. */ -import { existsSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { mkdir, readFile, writeFile } from "node:fs/promises"; -import { basename, extname, join, resolve } from "node:path"; +import { basename, dirname, extname, join, resolve } from "node:path"; +import { + CONFIG_SCHEMA_FILE_NAME, + MODELS_SCHEMA_FILE_NAME, + renderConfigSchema, + renderModelsSchema, +} from "./config-schema.ts"; +import { isStepConfigSubcommand, STEP_CONFIG_SUBCOMMANDS, stepConfigSubcommandNames } from "./config-subcommands.ts"; import { readStepConfig, resolveStepConfigPath, STEP_CONFIG_FILE_NAME } from "./config-toml.ts"; +import { STEP_DEFAULT_MODEL, STEP_DEFAULT_PROVIDER } from "./defaults.ts"; import { resolveStepAgentDir, resolveStepConfigDir, resolveStepConfigRoot } from "./environment.ts"; import { normalizeStepStableVersion } from "./local-update.ts"; +import { configSchemaDirective, writeSchemaFiles } from "./schema-files.ts"; + +const SCHEMA_FILE_NAMES = [CONFIG_SCHEMA_FILE_NAME, MODELS_SCHEMA_FILE_NAME]; export type StepTopLevelCommand = "config" | "exec" | "models" | "resume"; @@ -109,6 +120,40 @@ export function translateStepCommandArgs(argv: readonly string[]): StepCommandCo } } +/** + * Replace credential material with a placeholder. + * + * `config show` is the discovery entry, so its output is likely to be pasted + * into a transcript or an issue. Field names are what a reader needs; the + * values are not. MCP declarations carry credentials in three places: a name + * like `apiKey`, an `env` table, and `http_headers`, so the value of any entry + * whose key looks like a secret is replaced at every level. + */ +function redact(value: unknown, referencesOnly = false): unknown { + if (Array.isArray(value)) return value.map((entry) => redact(entry, referencesOnly)); + if (value === null || typeof value !== "object") return value; + return Object.fromEntries( + Object.entries(value as Record).map(([key, entry]) => { + // Inside `env_http_headers` every value is the name of a variable, not + // the value it holds, so the header name must not trigger redaction: + // otherwise a reader cannot tell which variable to export. + const child = referencesOnly || key === "env_http_headers"; + return [ + key, + !referencesOnly && looksSecret(key) && typeof entry === "string" ? "(redacted)" : redact(entry, child), + ]; + }), + ); +} + +/** Whether a key names credential material rather than a reference to it. */ +function looksSecret(key: string): boolean { + // `bearer_token_env_var` holds the name of an environment variable, which is + // not itself a secret, so it stays readable. + if (/^(?:[a-z0-9]+_)*?(?:token|secret|key)_(?:env_)?var$/i.test(key)) return false; + return /api_?key|token|secret|passw(?:or)?d|authorization|cookie|credential|private_?key/i.test(key); +} + /** Parse the intentionally small Step self-update surface. */ export function parseStepUpdateCommand(argv: readonly string[]): StepUpdateCommand | { error: string } | undefined { const command = argv[0]; @@ -125,11 +170,12 @@ export function parseStepUpdateCommand(argv: readonly string[]): StepUpdateComma /** Return whether argv selects a Step config inspection command. */ export function isStepConfigCommand(argv: readonly string[]): boolean { - return argv[0] === "config" && ["path", "show", "init"].includes(argv[1] ?? ""); + return argv[0] === "config" && isStepConfigSubcommand(argv[1]); } export interface StepConfigCommandIo { stdout?: Pick; + stderr?: Pick; cwd?: string; homeEnv?: Record; } @@ -143,17 +189,21 @@ export interface StepConfigCommandIo { */ export async function runStepConfigCommand(argv: readonly string[], io: StepConfigCommandIo = {}): Promise { const stdout = io.stdout ?? process.stdout; + const stderr = io.stderr ?? process.stderr; const cwd = resolve(io.cwd ?? process.cwd()); const env = io.homeEnv ?? process.env; const agentDir = resolveStepAgentDir(env); const configRoot = resolveStepConfigRoot(env); const configDirName = resolveStepConfigDir(env); const projectDir = join(cwd, configDirName); + const globalSettings = resolveStepConfigPath(env); const paths = { agentDir, - globalSettings: resolveStepConfigPath(env), + globalSettings, globalModels: join(configRoot, "models.json"), globalAuth: join(configRoot, "auth.json"), + globalConfigSchema: join(dirname(globalSettings), CONFIG_SCHEMA_FILE_NAME), + globalModelsSchema: join(dirname(globalSettings), MODELS_SCHEMA_FILE_NAME), projectDir, projectSettings: join(projectDir, STEP_CONFIG_FILE_NAME), }; @@ -188,6 +238,8 @@ export async function runStepConfigCommand(argv: readonly string[], io: StepConf globalSettingsPath: paths.globalSettings, globalModelsPath: paths.globalModels, globalAuthPath: paths.globalAuth, + globalConfigSchemaPath: paths.globalConfigSchema, + globalModelsSchemaPath: paths.globalModelsSchema, workspaceConfigDir: paths.projectDir, workspaceSettingsPath: paths.projectSettings, existingPaths: Object.values(paths).filter((value) => existsSync(value)), @@ -201,6 +253,8 @@ export async function runStepConfigCommand(argv: readonly string[], io: StepConf `global settings: ${paths.globalSettings}`, `global models: ${paths.globalModels}`, `global auth: ${paths.globalAuth}`, + `global config schema: ${paths.globalConfigSchema}`, + `global models schema: ${paths.globalModelsSchema}`, `workspace: ${paths.projectDir}`, `workspace settings: ${paths.projectSettings}`, `existing: ${payload.existingPaths.length > 0 ? payload.existingPaths.join(", ") : "(none)"}`, @@ -218,18 +272,92 @@ export async function runStepConfigCommand(argv: readonly string[], io: StepConf const explicitPath = readOption(argv, "--path"); const target = resolve(explicitPath ?? (scope === "workspace" ? paths.projectSettings : paths.globalSettings)); const force = argv.includes("--force"); - if (existsSync(target) && !force) { + // A launch creates an empty config file before the user asks for one, so + // `init` must fill that file rather than refuse. Any setting already in it + // still needs --force, because the template does not preserve content. + if (existsSync(target) && !force && !isEmptyConfigFile(target)) { throw new Error(`Config file already exists: ${target} (pass --force to overwrite)`); } await mkdir(join(target, ".."), { recursive: true, mode: 0o700 }); + // Every section is commented out except the two defaults `step` already + // resolves, so the file states the shape without pinning a policy the + // user has not chosen. The first line points the editor at the schema + // written beside the file. + // A workspace file gets no directive: the schema lives beside the global + // file, and a relative path cannot reach it from another directory. + const writesSchemas = scope === "user" && !explicitPath; const template = [ + ...(writesSchemas ? [configSchemaDirective()] : []), "# StepCode configuration", - 'defaultProvider = "step"', - 'defaultModel = "step-5-preview"', + `defaultProvider = "${STEP_DEFAULT_PROVIDER}"`, + `defaultModel = "${STEP_DEFAULT_MODEL}"`, + "", + "# Uncomment to change a default; the schema above completes and validates", + "# every key. `step config schema` prints the same schema.", + "#", + "# [compaction]", + "# triggerRatio = 0.9 # 0.5-0.95 of the context window", + "#", + "# [subagent]", + "# max_concurrency = 8", + "# background_timeout_seconds = 3600", + "#", + "# [approval]", + '# preset = "approve-for-me" # ask | approve-for-me | full-access', + "#", + "# [search]", + '# provider = "auto" # auto | step | exa | firecrawl | parallel | tavily | tinyfish | off', "", ].join("\n"); await writeFile(target, template, { encoding: "utf8", mode: 0o600 }); stdout.write(`Wrote Step config template: ${target}\n`); + if (writesSchemas) { + const schemas = writeSchemaFiles(dirname(target)); + const missing = SCHEMA_FILE_NAMES.filter((name) => !schemas.some((path) => path.endsWith(name))); + if (missing.length > 0) { + // The template's `#:schema` line points at these, so saying the write + // succeeded would leave an editor reporting a missing schema. + stderr.write( + `Could not write ${missing.join(", ")} beside ${target}; the editor directive will not resolve.\n`, + ); + } + if (schemas.length > 0) stdout.write(`Wrote config schemas: ${schemas.join(", ")}\n`); + } + return; + } + + if (subcommand === "schema") { + // `--out` may appear before or after the target, and its value must not be + // mistaken for the target: skip by position, not by comparing the strings, + // so `--out models` still means the config schema. + const rest = argv.slice(2); + const out = readOption(argv, "--out"); + const positionals: string[] = []; + for (let index = 0; index < rest.length; index += 1) { + const arg = rest[index]!; + if (arg === "--out") { + index += 1; + continue; + } + if (arg.startsWith("--out=")) continue; + if (arg.startsWith("-")) continue; + positionals.push(arg); + } + if (positionals.length > 1) { + throw new Error( + `Unexpected argument "${positionals[1]}" for step config schema. Usage: step config schema [config|models] [--out ]`, + ); + } + const target = resolveSchemaTarget(positionals[0]); + const content = target.render(); + if (!out) { + stdout.write(content); + return; + } + const destination = resolve(out); + await mkdir(dirname(destination), { recursive: true, mode: 0o700 }); + await writeFile(destination, content, { encoding: "utf8", mode: 0o644 }); + stdout.write(`Wrote ${target.fileName}: ${destination}\n`); return; } @@ -237,16 +365,17 @@ export async function runStepConfigCommand(argv: readonly string[], io: StepConf const json = argv.includes("--json"); const readJson = async (path: string): Promise => { try { - return JSON.parse(await readFile(path, "utf8")) as unknown; + return redact(JSON.parse(await readFile(path, "utf8")) as unknown); } catch { return undefined; } }; // Settings are TOML; a missing or malformed file reads as absent here - // because `show` is a diagnostic, not a validator. + // because `show` is a diagnostic, not a validator. MCP declarations hold + // credentials too, so the same redaction applies to both formats. const readToml = (path: string): unknown => { try { - return readStepConfig(path); + return redact(readStepConfig(path)); } catch { return undefined; } @@ -259,15 +388,14 @@ export async function runStepConfigCommand(argv: readonly string[], io: StepConf // Auth presence is useful for diagnostics; credential material is not. auth: { configured: existsSync(paths.globalAuth), path: paths.globalAuth }, }; - if (json) { - stdout.write(`${JSON.stringify(payload, null, 2)}\n`); - } else { - stdout.write(`${JSON.stringify(payload, null, 2)}\n`); - } + // `show` has one machine-readable output; `--json` is accepted because it + // is the obvious spelling, not because it changes anything. + void json; + stdout.write(`${JSON.stringify(payload, null, 2)}\n`); return; } - throw new Error(`Usage: step config ${"path|show|init"}`); + throw new Error(`Usage: step config ${stepConfigSubcommandNames()}`); } function translateExecArgs(args: readonly string[]): string[] { @@ -351,31 +479,68 @@ function readOption(argv: readonly string[], name: string): string | undefined { } /** Flags each `step config` subcommand accepts. Anything else is a user error. */ -const STEP_CONFIG_SUBCOMMAND_FLAGS: Record = { - path: ["--json"], - show: ["--json"], - init: ["--scope", "--path", "--force"], +const STEP_CONFIG_SUBCOMMAND_FLAGS: Record = Object.fromEntries( + STEP_CONFIG_SUBCOMMANDS.map((sub) => [sub.name, sub.flags]), +); + +const STEP_CONFIG_SCHEMA_TARGETS: Record string; readonly fileName: string }> = { + config: { render: renderConfigSchema, fileName: CONFIG_SCHEMA_FILE_NAME }, + models: { render: renderModelsSchema, fileName: MODELS_SCHEMA_FILE_NAME }, }; -/** `step config` subcommands with one-line summaries, surfaced by `config --help`. */ -export const STEP_CONFIG_SUBCOMMANDS: readonly { readonly name: string; readonly summary: string }[] = [ - { name: "path", summary: "Print the resolved Step config file paths." }, - { name: "show", summary: "Print the effective Step config (credentials omitted)." }, - { name: "init", summary: "Write a Step config template (--scope, --path, --force)." }, -]; +/** + * Whether a config file exists but holds nothing the template would replace. + * + * "No parsed keys" is not enough: a file with only comments holds the user's + * notes, and overwriting it loses them. Only the exact header a launch writes, + * with or without the editor directive, counts as empty. + */ +function isEmptyConfigFile(path: string): boolean { + let content: string; + try { + content = readFileSync(path, "utf8"); + } catch { + return false; + } + if (Object.keys(readStepConfig(path) as Record).length > 0) return false; + + const remaining = content + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0 && !line.startsWith("#:schema")) + .join("\n"); + // Exactly the header, nothing else. + return remaining === "# StepCode configuration"; +} + +/** `config|models`, defaulting to the settings file. */ +function resolveSchemaTarget(value: string | undefined): { render: () => string; fileName: string } { + const name = value ?? "config"; + const target = STEP_CONFIG_SCHEMA_TARGETS[name]; + if (!target) { + throw new Error(`Unknown schema "${name}". Use config or models.`); + } + return target; +} function stepConfigUsage(subcommand: string): string { switch (subcommand) { case "path": return "Usage: step config path [--json]\n Print the resolved Step config file paths."; case "show": - return "Usage: step config show [--json]\n Print the effective Step config (credentials omitted)."; + return "Usage: step config show [--json]\n Print the stored config.toml and models.json documents (values not merged, credentials redacted)."; case "init": return [ "Usage: step config init [--scope user|workspace] [--path ] [--force]", " Write a Step config template. Defaults to the user scope; --force overwrites an existing file.", ].join("\n"); + case "schema": + return [ + "Usage: step config schema [config|models] [--out ]", + " Print the editor JSON Schema for config.toml (default) or models.json.", + " --out writes the schema to a file instead of stdout.", + ].join("\n"); default: - return "Usage: step config path|show|init"; + return `Usage: step config ${STEP_CONFIG_SUBCOMMANDS.map((sub) => sub.name).join("|")}`; } } diff --git a/packages/coding-agent/src/step/config-schema.ts b/packages/coding-agent/src/step/config-schema.ts new file mode 100644 index 000000000..93dd284a4 --- /dev/null +++ b/packages/coding-agent/src/step/config-schema.ts @@ -0,0 +1,441 @@ +/** + * Editor-facing contract for the files StepCode reads from the config root: + * `config.toml` and `models.json`. + * + * Both schemas are derived from the same TypeBox definitions the runtime loads + * through, so a key cannot exist in one and not the other. They are generated + * into `schema/*.json` and shipped beside the binary; nothing is fetched from + * the network, so an editor always validates against the version of the binary + * that wrote the file. + * + * `additionalProperties: false` makes the schema stricter than the runtime on + * purpose: the loaders keep an unknown key and ignore it, while an editor flags + * it. That difference is the feature — a typo becomes visible where it is + * written, and a launch never fails because of it. + */ + +import { type Static, Type } from "typebox"; +import { ModelsConfigSchema } from "../core/model-config.ts"; +import { RetrySettingsSchema, SettingsSchema } from "../core/settings-schema.ts"; +import { ThemeJsonSchema } from "../theme/theme-schema.ts"; +import type { SearchChainMode } from "./search/types.ts"; +import { SEARCH_CHAIN_MODES } from "./search/types.ts"; +import { + SUBAGENT_BACKGROUND_TIMEOUT_DEFAULT_SECONDS, + SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS, + SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS, + SUBAGENT_MAX_CONCURRENCY_DEFAULT, +} from "./subagent-limits.ts"; + +const JSON_SCHEMA_DIALECT = "https://json-schema.org/draft/2020-12/schema"; + +const optionalDescription = (description: string) => Type.Optional(Type.String({ description })); + +const PermissionPresetSchema = Type.Union( + [ + Type.Literal("ask"), + Type.Literal("approve-for-me"), + Type.Literal("full-access"), + // Spellings `normalizeStepPermissionPresetId` maps onto the three tiers. + Type.Literal("confirm"), + Type.Literal("approve"), + Type.Literal("approveforme"), + Type.Literal("bypass"), + Type.Literal("auto"), + Type.Literal("autopilot"), + Type.Literal("bypasspermissions"), + Type.Literal("fullaccess"), + Type.Literal("full"), + Type.Literal("yolo"), + Type.Literal("never-ask"), + Type.Literal("read-only"), + Type.Literal("readonly"), + Type.Literal("strict"), + Type.Literal("plan"), + ], + { + description: + "Initial approval tier: `ask`, `approve-for-me` (default), or `full-access`. Legacy spellings are accepted and mapped: `confirm`/`auto`/`bypass`/`strict`/`plan`/`read-only` mean `ask`, `approve` means `approve-for-me`, `full`/`fullaccess`/`yolo`/`never-ask` mean `full-access`. Matching ignores case and surrounding spaces. Full Access also needs `fullAccessAcknowledged` from its one-time prompt.", + }, +); + +const ApprovalModeSchema = Type.Union( + [ + Type.Literal("confirm"), + Type.Literal("auto"), + // Spellings `normalizeStepPermissionMode` maps onto the two modes. + Type.Literal("ask"), + Type.Literal("default"), + Type.Literal("acceptedits"), + Type.Literal("strict"), + Type.Literal("read-only"), + Type.Literal("readonly"), + Type.Literal("plan"), + Type.Literal("bypass"), + Type.Literal("bypasspermissions"), + ], + { + description: + "Low-level override of the tier's default approval mode: `confirm` or `auto`. Legacy spellings `ask`/`default`/`acceptedits`/`strict`/`read-only`/`plan` mean `confirm`; `bypass`/`bypasspermissions` mean `auto`.", + }, +); + +const NonInteractiveApprovalSchema = Type.Union([Type.Literal("allow"), Type.Literal("deny")], { + description: + "Approval fallback when no interactive UI can answer a confirmation: `allow` or `deny` (default). Matching ignores case.", +}); + +/** + * The approval table is accepted at `[approval]`, `[tools.approval]`, and as + * flat keys. All spellings are documented so an editor accepts a file written + * by any of them, and the descriptions say which one to prefer. + */ +const ApprovalTableSchema = Type.Object( + { + preset: Type.Optional(PermissionPresetSchema), + mode: Type.Optional(ApprovalModeSchema), + nonInteractive: Type.Optional(NonInteractiveApprovalSchema), + noninteractive: Type.Optional( + Type.Union([Type.Literal("allow"), Type.Literal("deny")], { + description: "Accepted for older files; prefer `nonInteractive`.", + }), + ), + autoResume: Type.Optional( + Type.Boolean({ description: "Resume after a bounded model error without asking again." }), + ), + autopilot: Type.Optional(Type.Boolean({ description: "Accepted for older files; prefer `autoResume`." })), + fullAccessAcknowledged: Type.Optional( + Type.Boolean({ + description: + 'Set by "Yes, and do not ask again" when Full Access is selected; cleared when the tier is not Full Access.', + }), + ), + }, + { additionalProperties: false, description: "Approval tier overrides." }, +); + +const SubagentTableSchema = Type.Object( + { + background: Type.Optional( + Type.Boolean({ description: "Run `run_in_background` subagent calls in a background lane (default true)." }), + ), + background_timeout_seconds: Type.Optional( + Type.Integer({ + minimum: SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS, + maximum: SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS, + description: `Per-turn wall-clock limit of a background lane in seconds (default ${SUBAGENT_BACKGROUND_TIMEOUT_DEFAULT_SECONDS}, ${SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS}-${SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS}). A call's own timeout takes precedence.`, + }), + ), + max_concurrency: Type.Optional( + Type.Integer({ + minimum: 1, + description: `Child processes a parallel batch runs at once (default ${SUBAGENT_MAX_CONCURRENCY_DEFAULT}, no upper bound).`, + }), + ), + }, + { additionalProperties: false, description: "Subagent concurrency and background lanes." }, +); + +const SearchTableSchema = Type.Object( + { + provider: Type.Optional( + Type.Union( + SEARCH_CHAIN_MODES.map((mode) => Type.Literal(mode)), + { + description: + "Web search backend. `auto` (default) walks the chain; a backend id pins one; `off` keeps the tool but refuses calls. The runtime treats an unrecognized value as `auto`, so a misspelling silently disables the pin instead of failing.", + }, + ), + ), + }, + { additionalProperties: false, description: "Web search backend selection." }, +); + +/** + * The `retry` table with the one legacy key the loader rewrites. + * + * Derived from the runtime table so a new field there cannot be missed here. + */ +const LegacyRetryTableSchema = Type.Object( + { + ...RetrySettingsSchema.properties, + maxDelayMs: Type.Optional( + Type.Number({ + minimum: 0, + description: "Older spelling of `provider.maxRetryDelayMs`; migrated on load.", + }), + ), + }, + { additionalProperties: false, description: "Retry and backoff behavior." }, +); + +/** + * The older `[skills]` table, which `migrateSettings` turns into the array of + * the same name plus `enableSkillCommands`. + * + * Listed as an alternative shape so the editor and the loader agree about a file + * that still uses it. + */ +const LegacySkillsTableSchema = Type.Object( + { + enableSkillCommands: Type.Optional(Type.Boolean({ description: "Promoted to the top-level key on load." })), + customDirectories: Type.Optional( + Type.Array(Type.String(), { description: "Becomes the `skills` array on load." }), + ), + }, + { additionalProperties: false, description: "Older object form of `skills`; migrated on load." }, +); + +const TelemetryTableSchema = Type.Object( + { + enabled: Type.Optional( + Type.Boolean({ description: "Send product telemetry. An explicit `false` is honored over any default." }), + ), + spool: Type.Optional(Type.Boolean({ description: "Buffer events on disk when the endpoint is unreachable." })), + endpoint: Type.Optional(Type.String({ description: "Telemetry endpoint override." })), + }, + { additionalProperties: false, description: "Product telemetry." }, +); + +const McpOauthSchema = Type.Object( + { + client_id: Type.Optional(Type.String({ description: "Static OAuth client id." })), + client_secret: Type.Optional(Type.String({ description: "Static OAuth client secret." })), + scopes: Type.Optional(Type.Array(Type.String(), { description: "Requested OAuth scopes." })), + callback_port: Type.Optional(Type.Integer({ minimum: 1, maximum: 65_535, description: "Local callback port." })), + }, + { additionalProperties: false, description: "OAuth settings for an HTTP MCP server." }, +); + +const McpServerSchema = Type.Object( + { + command: Type.Optional( + Type.String({ description: "Executable for a stdio server; mutually exclusive with `url`." }), + ), + args: Type.Optional(Type.Array(Type.String(), { description: "Arguments for `command`." })), + cwd: Type.Optional(Type.String({ description: "Working directory for `command`." })), + url: Type.Optional(Type.String({ description: "Endpoint for an HTTP or SSE server." })), + env: Type.Optional( + Type.Record(Type.String(), Type.String(), { description: "Extra environment for `command`." }), + ), + bearer_token_env_var: Type.Optional( + Type.String({ description: "Environment variable holding a bearer token for `url`." }), + ), + http_headers: Type.Optional( + Type.Record(Type.String(), Type.String(), { description: "Static headers sent with every HTTP request." }), + ), + env_http_headers: Type.Optional( + Type.Record(Type.String(), Type.String(), { + description: "Header names whose value is read from the named environment variable.", + }), + ), + enabled: Type.Optional(Type.Boolean({ description: "Set `false` to keep the declaration but skip connecting." })), + tool_timeout_sec: Type.Optional(Type.Number({ minimum: 0, description: "Per-call timeout in seconds." })), + startup_timeout_sec: Type.Optional(Type.Number({ minimum: 0, description: "Connection timeout in seconds." })), + enabled_tools: Type.Optional(Type.Array(Type.String(), { description: "Publish only these tools." })), + disabled_tools: Type.Optional(Type.Array(Type.String(), { description: "Never publish these tools." })), + oauth: Type.Optional(McpOauthSchema), + }, + { additionalProperties: false, description: "One MCP server declaration." }, +); + +/** + * Keys the product writes at the document root. Kept flat because that is the + * shape the settings storage merges; the nested spellings above are aliases the + * loaders still honor. + */ +const StepProductProperties = { + permissionPreset: Type.Optional(PermissionPresetSchema), + permissionMode: Type.Optional(PermissionPresetSchema), + approvalMode: Type.Optional(ApprovalModeSchema), + nonInteractiveApproval: Type.Optional(NonInteractiveApprovalSchema), + noninteractiveApproval: Type.Optional( + Type.Union([Type.Literal("allow"), Type.Literal("deny")], { + description: "Accepted for older files; prefer `nonInteractiveApproval`.", + }), + ), + autoResume: Type.Optional(Type.Boolean({ description: "Resume after a bounded model error without asking again." })), + autopilot: Type.Optional(Type.Boolean({ description: "Accepted for older files; prefer `autoResume`." })), + fullAccessAcknowledged: Type.Optional(Type.Boolean({ description: "Recorded Full Access risk acknowledgment." })), + feedbackEnabled: Type.Optional(Type.Boolean({ description: "Allow the feedback submission flow (default true)." })), + subagentBackground: Type.Optional(Type.Boolean({ description: "Flat form of `[subagent] background`." })), + subagentBackgroundTimeoutSeconds: Type.Optional( + Type.Integer({ + minimum: SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS, + maximum: SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS, + description: "Flat form of `[subagent] background_timeout_seconds`.", + }), + ), + subagentMaxConcurrency: Type.Optional( + Type.Integer({ minimum: 1, description: "Flat form of `[subagent] max_concurrency`." }), + ), + approval: Type.Optional(ApprovalTableSchema), + tools: Type.Optional( + Type.Object( + { approval: Type.Optional(ApprovalTableSchema) }, + { additionalProperties: false, description: "Tool policy tables." }, + ), + ), + feedback: Type.Optional( + Type.Object( + { enabled: Type.Optional(Type.Boolean({ description: "Allow the feedback submission flow." })) }, + { additionalProperties: false, description: "Feedback submission." }, + ), + ), + subagent: Type.Optional(SubagentTableSchema), + skills: Type.Optional( + Type.Union( + [Type.Array(Type.String(), { description: "Local skill files or directories." }), LegacySkillsTableSchema], + { description: "Local skill files or directories. The older `[skills]` table is migrated on load." }, + ), + ), + // Rewritten by `SettingsManager.migrateSettings` before any read. Listed here + // so a file that still uses them is not flagged as invalid. + queueMode: Type.Optional( + Type.Union([Type.Literal("all"), Type.Literal("one-at-a-time")], { + description: "Older spelling of `steeringMode`; migrated on load.", + }), + ), + websockets: Type.Optional( + Type.Boolean({ description: "Older spelling of `transport`; migrated on load (true -> websocket)." }), + ), + retry: Type.Optional(LegacyRetryTableSchema), + search: Type.Optional(SearchTableSchema), + telemetry: Type.Optional(TelemetryTableSchema), + mcp_servers: Type.Optional( + Type.Record(Type.String(), McpServerSchema, { description: "MCP servers keyed by the name shown in `/mcp`." }), + ), + // Written by the first-launch MCP import prompt so it is offered only once. + // Listed for that reason: a file the product writes must validate against the + // schema it ships, or the editor reports a false error. + mcp_import: Type.Optional( + Type.Object( + { + reviewed: Type.Optional( + Type.Array(Type.String(), { description: "Import sources already offered, by source id." }), + ), + }, + { additionalProperties: false, description: "Record of MCP import sources already reviewed." }, + ), + ), +}; + +/** The whole `config.toml` document: runtime settings plus product-owned keys. */ +export const ConfigTomlSchema = Type.Object( + { ...SettingsSchema.properties, ...StepProductProperties }, + { + additionalProperties: false, + description: + "StepCode `config.toml`. The global file is `~/.stepcode/config.toml`; a trusted project may add `.stepcode/config.toml`, whose values win per key.", + }, +); + +/** The whole `models.json` document, including the editor reference field. */ +export const ModelsJsonSchema = Type.Object( + { + $schema: optionalDescription( + 'Editor reference for this file, for example "./models.schema.json" beside the file.', + ), + ...ModelsConfigSchema.properties, + }, + { + additionalProperties: false, + description: + "StepCode `models.json`: provider endpoints, credentials and model definitions. JSON with `//` comments is accepted. The global file is `~/.stepcode/models.json`.", + }, +); + +type SchemaNode = { + type?: string; + properties?: Record; + patternProperties?: Record; + additionalProperties?: boolean | SchemaNode; + items?: SchemaNode; + anyOf?: SchemaNode[]; + oneOf?: SchemaNode[]; + allOf?: SchemaNode[]; +}; + +/** + * The same document with every object closed to unknown keys. + * + * `ModelsConfigSchema` is the loader's validator, so it must keep accepting an + * unknown field: a newer Step may add one and an older binary still has to load + * the file. The editor has the opposite job — an unknown field in `models.json` + * is never read, so it should be flagged. Rendering a closed copy from the same + * tree keeps the two from drifting while letting them differ on purpose. + * + * A record (`patternProperties`) stays open: its keys are data, not field names. + */ +function closeObjects(node: SchemaNode): SchemaNode { + const closed: SchemaNode = { ...node }; + if (closed.properties) { + closed.properties = Object.fromEntries( + Object.entries(closed.properties).map(([key, child]) => [key, closeObjects(child)]), + ); + } + if (closed.patternProperties) { + closed.patternProperties = Object.fromEntries( + Object.entries(closed.patternProperties).map(([pattern, child]) => [pattern, closeObjects(child)]), + ); + } + if (closed.items) closed.items = closeObjects(closed.items); + for (const key of ["anyOf", "oneOf", "allOf"] as const) { + const members = closed[key]; + if (members) closed[key] = members.map(closeObjects); + } + if (typeof closed.additionalProperties === "object") { + closed.additionalProperties = closeObjects(closed.additionalProperties); + } + // Only an object that names its fields is a closed object; leaving a record + // open is what keeps `samplingParams` usable. + if (closed.type === "object" && closed.properties && closed.additionalProperties === undefined) { + closed.additionalProperties = false; + } + return closed; +} + +/** `models.json` as the editor should see it. */ +const StrictModelsJsonSchema = closeObjects(ModelsJsonSchema as unknown as SchemaNode) as object; + +export type ConfigTomlDocument = Static; +export type ModelsJsonDocument = Static; +export type StepProductKey = keyof typeof StepProductProperties; +export type SearchProviderId = SearchChainMode; + +/** Render one schema as the JSON document written to `schema/.schema.json`. */ +export function renderSchemaJson(schema: object, title: string): string { + return `${JSON.stringify({ $schema: JSON_SCHEMA_DIALECT, title, ...schema }, null, "\t")}\n`; +} + +export const CONFIG_SCHEMA_FILE_NAME = "config.schema.json"; +export const MODELS_SCHEMA_FILE_NAME = "models.schema.json"; +export const THEME_SCHEMA_FILE_NAME = "theme-schema.json"; + +export const CONFIG_SCHEMA_TITLE = "StepCode config.toml"; +export const MODELS_SCHEMA_TITLE = "StepCode models.json"; +export const THEME_SCHEMA_TITLE = "StepCode theme"; + +export function renderConfigSchema(): string { + return renderSchemaJson(ConfigTomlSchema, CONFIG_SCHEMA_TITLE); +} + +export function renderModelsSchema(): string { + return renderSchemaJson(ModelsJsonSchema, MODELS_SCHEMA_TITLE); +} + +/** The permissive tree, so a test can prove the strict copy differs only there. */ +export const PermissiveModelsJsonSchema = ModelsJsonSchema; + +/** The closed tree. */ +export const ClosedModelsJsonSchema = StrictModelsJsonSchema; + +/** `models.json` with unknown fields closed, for editors. */ +export function renderStrictModelsSchema(): string { + return renderSchemaJson(StrictModelsJsonSchema, MODELS_SCHEMA_TITLE); +} + +/** The theme file shape, rendered from the schema the loader compiles. */ +export function renderThemeSchema(): string { + return renderSchemaJson(ThemeJsonSchema, THEME_SCHEMA_TITLE); +} diff --git a/packages/coding-agent/src/step/config-subcommands.ts b/packages/coding-agent/src/step/config-subcommands.ts new file mode 100644 index 000000000..24a9436bf --- /dev/null +++ b/packages/coding-agent/src/step/config-subcommands.ts @@ -0,0 +1,49 @@ +/** + * The `step config` subcommand table. + * + * Kept in its own module with no imports. `package-manager-cli.ts` renders the + * `config --help` subcommand list from it, and that module is loaded by every + * invocation, so a dependency here would be paid by every command. `cli/args.ts` + * names the same subcommands in its inline help text. + */ + +export interface StepConfigSubcommand { + readonly name: string; + readonly summary: string; + /** Flags the subcommand accepts. Anything else is a user error. */ + readonly flags: readonly string[]; +} + +/** Every `step config` subcommand, in the order `--help` lists them. */ +export const STEP_CONFIG_SUBCOMMANDS: readonly StepConfigSubcommand[] = [ + { + name: "path", + summary: "Print the resolved Step config file paths.", + flags: ["--json"], + }, + { + name: "show", + summary: "Print the stored config.toml and models.json documents (credentials redacted).", + flags: ["--json"], + }, + { + name: "init", + summary: "Write a Step config template (--scope, --path, --force).", + flags: ["--scope", "--path", "--force"], + }, + { + name: "schema", + summary: "Print the editor JSON Schema for config.toml or models.json (--out ).", + flags: ["--out"], + }, +]; + +/** Whether `name` selects a subcommand, so a bare `step config` still opens the TUI. */ +export function isStepConfigSubcommand(name: string | undefined): boolean { + return STEP_CONFIG_SUBCOMMANDS.some((sub) => sub.name === name); +} + +/** The `path|show|init|…` form used in usage text. */ +export function stepConfigSubcommandNames(): string { + return STEP_CONFIG_SUBCOMMANDS.map((sub) => sub.name).join("|"); +} diff --git a/packages/coding-agent/src/step/config-toml.ts b/packages/coding-agent/src/step/config-toml.ts index d9d42e921..ea5ec1a24 100644 --- a/packages/coding-agent/src/step/config-toml.ts +++ b/packages/coding-agent/src/step/config-toml.ts @@ -1,8 +1,9 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { dirname, join, resolve } from "node:path"; import { parse as parseToml, stringify as stringifyToml } from "smol-toml"; import { acquireSettingsLockSync, type SettingsScope, type SettingsStorage } from "../core/settings-manager.ts"; import { resolveStepConfigDir, resolveStepConfigRoot } from "./environment.ts"; +import { configSchemaDirective, refreshSchemaFiles } from "./schema-files.ts"; export const STEP_CONFIG_FILE_NAME = "config.toml"; @@ -44,12 +45,48 @@ export function resolveStepConfigPath(env: NodeJS.ProcessEnv = process.env, cwd? return join(root, STEP_CONFIG_FILE_NAME); } -/** Create a config file once, without replacing an existing file. */ -export function ensureStepConfigFile(path: string): string { +/** + * The header a StepCode-created config file starts with. + * + * Only the global file gets the editor directive, because only the global + * directory receives a copy of the schema. A project file lives in a directory + * the repository owns, and dropping two ~80 KB schemas into every project would + * be noise in `git status`; its directive would also point at a file that is + * not there. + */ +function configFileHeader(withSchemaDirective: boolean): string { + return withSchemaDirective ? `${configSchemaDirective()}\n# StepCode configuration\n` : "# StepCode configuration\n"; +} + +/** + * Whether a path is the global `config.toml` (as opposed to a project one). + * + * The environment is a parameter rather than `process.env`: an embedded host + * and the tests inject `STEP_CODING_AGENT_DIR`, and comparing against the + * process environment would then classify the injected global file as a project + * one. + */ +export function isGlobalStepConfigPath(path: string, env: NodeJS.ProcessEnv = process.env): boolean { + return resolve(path) === resolve(resolveStepConfigPath(env)); +} + +/** + * Create a config file once, without replacing an existing file. + * + * The first line is the editor schema directive when the schema sits beside the + * file. `writeStepConfig` preserves the leading comment block, so the directive + * survives settings writes instead of disappearing the first time a setting is + * saved. + */ +export function ensureStepConfigFile(path: string, options: { withSchemaDirective?: boolean } = {}): string { if (!existsSync(path)) { mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); try { - writeFileSync(path, "# StepCode configuration\n", { encoding: "utf8", mode: 0o600, flag: "wx" }); + writeFileSync(path, configFileHeader(options.withSchemaDirective ?? false), { + encoding: "utf8", + mode: 0o600, + flag: "wx", + }); } catch (error) { if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST") throw error; } @@ -57,9 +94,16 @@ export function ensureStepConfigFile(path: string): string { return path; } -/** Create the global config once, without replacing an existing file. */ +/** + * Create the global config once, and keep the adjacent editor schemas current. + * + * Refreshing here covers every launch, so upgrading the binary updates the + * schema an editor validates against instead of leaving a stale copy behind. + */ export function ensureStepGlobalConfig(env: NodeJS.ProcessEnv = process.env): string { - return ensureStepConfigFile(resolveStepConfigPath(env)); + const path = ensureStepConfigFile(resolveStepConfigPath(env), { withSchemaDirective: true }); + refreshSchemaFiles(dirname(path)); + return path; } export function readStepConfig(path: string): StepConfigDocument { @@ -146,6 +190,20 @@ function readLeadingComments(path: string): string { return kept.length > 0 ? `${kept.join("\n")}\n` : ""; } +/** + * Add the editor directive to a header that does not have one. + * + * A file written by an older release keeps its settings and gains one comment + * line, so the schema that a launch now writes beside it is actually referenced. + * Only the global file goes through this; a project file has no schema to point + * at. + */ +function withSchemaDirective(header: string): string { + if (/^#:schema\s/m.test(header)) return header; + const directive = `${configSchemaDirective()}\n`; + return header.length > 0 ? `${directive}${header}` : `${directive}# StepCode configuration\n`; +} + /** * TOML cannot express null. Drop those keys deliberately here rather than * letting the serializer decide, so "cleared" and "absent" mean the same thing @@ -162,9 +220,29 @@ function stripNullValues(value: unknown): unknown { return result; } -/** Atomically write a TOML document. Callers must preserve unknown fields before calling. */ -export function writeStepConfig(path: string, document: StepConfigDocument): void { - const header = readLeadingComments(path); +/** + * Atomically write a TOML document. Callers must preserve unknown fields before + * calling. + * + * A file this call creates keeps the header an existing file would have: the + * global file keeps or gains the editor directive, a project file stays plain. + * An existing file keeps whatever header it has. + */ +export function writeStepConfig( + path: string, + document: StepConfigDocument, + options: { env?: NodeJS.ProcessEnv; editorDirective?: boolean } = {}, +): void { + const created = !existsSync(path); + // The caller writes either the global file or a project file and knows which; + // fall back to the path only when it does not say. + const wantsDirective = options.editorDirective ?? isGlobalStepConfigPath(path, options.env); + const existing = created ? undefined : readLeadingComments(path); + const header = created + ? configFileHeader(wantsDirective) + : wantsDirective + ? withSchemaDirective(existing ?? "") + : (existing ?? ""); mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); const body = stringifyToml(stripNullValues(document) as Record); const temporary = `${path}.${process.pid}.tmp`; @@ -185,7 +263,7 @@ export function updateGlobalStepConfig( const path = ensureStepGlobalConfig(env); const release = acquireSettingsLockSync(path); try { - writeStepConfig(path, update(readStepConfig(path))); + writeStepConfig(path, update(readStepConfig(path)), { env, editorDirective: true }); } finally { release(); } @@ -212,8 +290,10 @@ export interface StepTomlSettingsStoragePaths { export class StepTomlSettingsStorage implements SettingsStorage { private readonly globalPath: string; private readonly projectPath: string; + private readonly env: NodeJS.ProcessEnv; constructor(cwd: string, env: NodeJS.ProcessEnv = process.env, paths: StepTomlSettingsStoragePaths = {}) { + this.env = env; // The product decorator derives its paths from the injected agent and // config directories. Accept the same paths here, or the Pi settings and // the Step settings of one manager end up in two different files. @@ -245,7 +325,7 @@ export class StepTomlSettingsStorage implements SettingsStorage { } const mcp = (document ?? readStepConfig(path)).mcp_servers; const merged: StepConfigDocument = { ...settings, ...(mcp ? { mcp_servers: mcp } : {}) }; - writeStepConfig(path, merged); + writeStepConfig(path, merged, { env: this.env, editorDirective: scope === "global" }); } finally { release?.(); } diff --git a/packages/coding-agent/src/step/schema-files.ts b/packages/coding-agent/src/step/schema-files.ts new file mode 100644 index 000000000..663d11edb --- /dev/null +++ b/packages/coding-agent/src/step/schema-files.ts @@ -0,0 +1,89 @@ +/** + * Write and refresh the editor schemas for `config.toml` and `models.json`. + * + * The committed schemas live in `packages/coding-agent/schema/`. At runtime both + * files are rendered from the same TypeBox definitions the loaders use and + * written next to the configuration files, so a file can reference them by a + * relative path (`#:schema ./config.schema.json` in TOML, + * `"$schema": "./models.schema.json"` in JSON). + * + * Nothing is fetched over the network and no URL is published: an editor + * validates against the same build that wrote the file, and a schema change + * ships as a normal code change instead of a separately versioned contract. + */ + +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { + CONFIG_SCHEMA_FILE_NAME, + MODELS_SCHEMA_FILE_NAME, + renderConfigSchema, + renderStrictModelsSchema, +} from "./config-schema.ts"; + +export interface SchemaFile { + readonly fileName: string; + readonly content: string; +} + +/** The generated schemas in the order they are written. */ +export function schemaFiles(): readonly SchemaFile[] { + return [ + { fileName: CONFIG_SCHEMA_FILE_NAME, content: renderConfigSchema() }, + { fileName: MODELS_SCHEMA_FILE_NAME, content: renderStrictModelsSchema() }, + ]; +} + +/** + * Write both schemas into `root`, replacing a file only when its content + * changed so a no-op run leaves modification times alone. Returns the paths + * that were written or already current; a path missing from the result could + * not be written. + * + * A read-only or otherwise unwritable directory is not fatal: the schemas are + * an editor aid, and a failing launch would be a worse outcome than a missing + * hint. Callers that must report the failure use the returned value. + */ +export function writeSchemaFiles(root: string): string[] { + const written: string[] = []; + for (const file of schemaFiles()) { + const path = join(root, file.fileName); + if (existsSync(path)) { + let current: string | undefined; + try { + current = readFileSync(path, "utf8"); + } catch { + current = undefined; + } + if (current === file.content) { + written.push(path); + continue; + } + } + try { + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); + const temporary = `${path}.${process.pid}.tmp`; + writeFileSync(temporary, file.content, { encoding: "utf8", mode: 0o644 }); + renameSync(temporary, path); + } catch { + // Best effort; see the doc comment. + continue; + } + written.push(path); + } + return written; +} + +/** + * Keep the copies next to the configuration files current. Called when the + * config file is created and on every launch, so `step update` refreshes them + * without a separate step. + */ +export function refreshSchemaFiles(root: string): string[] { + return writeSchemaFiles(root); +} + +/** The TOML header directive that points an editor at the adjacent schema. */ +export function configSchemaDirective(): string { + return `#:schema ./${CONFIG_SCHEMA_FILE_NAME}`; +} diff --git a/packages/coding-agent/src/step/settings-manager.ts b/packages/coding-agent/src/step/settings-manager.ts index ae09cb1f5..5c3da07e8 100644 --- a/packages/coding-agent/src/step/settings-manager.ts +++ b/packages/coding-agent/src/step/settings-manager.ts @@ -22,6 +22,14 @@ import { type StepPermissionMode, type StepPermissionPresetId, } from "./permissions.ts"; +import { + invalidSubagentBackgroundTimeoutMessage, + invalidSubagentMaxConcurrencyMessage, + isValidSubagentBackgroundTimeout, + isValidSubagentMaxConcurrency, + SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS, + SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS, +} from "./subagent-limits.ts"; /** Product-owned settings persisted by the Step decorator. */ export interface StepSettings { @@ -51,29 +59,6 @@ export interface StepSettings { type JsonObject = Record; -/** Bounds and default for the per-turn wall-clock limit of a background subagent lane. */ -export const SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS = 60; -export const SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS = 7_200; -export const SUBAGENT_BACKGROUND_TIMEOUT_DEFAULT_SECONDS = 3_600; - -/** Whether `value` is an accepted `[subagent] background_timeout_seconds`: an integer within the bounds. */ -export function isValidSubagentBackgroundTimeout(value: unknown): value is number { - return ( - typeof value === "number" && - Number.isInteger(value) && - value >= SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS && - value <= SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS - ); -} - -/** Message for a configured timeout that is ignored because it is out of bounds or not an integer. */ -export function invalidSubagentBackgroundTimeoutMessage( - value: unknown, - keyPath = "[subagent] background_timeout_seconds", -): string { - return `${keyPath} must be an integer from ${SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS} to ${SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS}; ignoring ${JSON.stringify(value)} and using ${SUBAGENT_BACKGROUND_TIMEOUT_DEFAULT_SECONDS}`; -} - /** The raw configured timeout values, from the flat key and the `[subagent]` table. */ function rawSubagentTimeouts(value: JsonObject): unknown[] { return [value.subagentBackgroundTimeoutSeconds, asObject(value.subagent)?.background_timeout_seconds].filter( @@ -81,25 +66,6 @@ function rawSubagentTimeouts(value: JsonObject): unknown[] { ); } -/** Default number of child processes a parallel subagent batch runs at once. */ -export const SUBAGENT_MAX_CONCURRENCY_DEFAULT = 8; - -/** - * Whether `value` is an accepted `[subagent] max_concurrency`: a positive - * integer. There is deliberately no upper bound — raising the limit above the - * default is the point of the setting. - */ -export function isValidSubagentMaxConcurrency(value: unknown): value is number { - return typeof value === "number" && Number.isInteger(value) && value >= 1; -} - -/** Message for a configured concurrency that is ignored because it is not a positive integer. */ -export function invalidSubagentMaxConcurrencyMessage(value: unknown, keyPath = "[subagent] max_concurrency"): string { - // The effective fallback (option, then default) is resolved per call, so the - // load-time warning only states that the value is ignored. - return `${keyPath} must be a positive integer; ignoring ${JSON.stringify(value)}`; -} - /** The raw configured concurrency values, from the flat key and the `[subagent]` table. */ function rawSubagentConcurrencies(value: JsonObject): unknown[] { return [value.subagentMaxConcurrency, asObject(value.subagent)?.max_concurrency].filter( @@ -325,7 +291,19 @@ function savedPermissionSelection(value: JsonObject): { preset?: string; mode?: return { preset, mode }; } -const STEP_SETTING_ALIASES: Record = { +export { + invalidSubagentBackgroundTimeoutMessage, + invalidSubagentMaxConcurrencyMessage, + isValidSubagentBackgroundTimeout, + isValidSubagentMaxConcurrency, + SUBAGENT_BACKGROUND_TIMEOUT_DEFAULT_SECONDS, + SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS, + SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS, + SUBAGENT_MAX_CONCURRENCY_DEFAULT, +} from "./subagent-limits.ts"; + +/** Flat root-level spellings each product setting also answers to. */ +export const STEP_SETTING_ALIASES: Record = { permissionPreset: ["permissionMode"], approvalMode: [], nonInteractiveApproval: ["noninteractiveApproval"], @@ -337,7 +315,8 @@ const STEP_SETTING_ALIASES: Record = { subagentMaxConcurrency: [], }; -const STEP_SETTING_NESTED_ALIASES: Record = { +/** Nested table spellings each product setting also answers to. */ +export const STEP_SETTING_NESTED_ALIASES: Record = { permissionPreset: [ ["approval", "preset"], ["tools", "approval", "preset"], @@ -585,7 +564,8 @@ class StepSettingsStore { if (value === undefined) delete next[rawKey]; else next[rawKey] = clone(value); } - if (path.endsWith(".toml")) writeStepConfig(path, { ...readStepConfig(path), ...next }); + if (path.endsWith(".toml")) + writeStepConfig(path, { ...readStepConfig(path), ...next }, { editorDirective: scope === "global" }); else writeFileSync(path, `${JSON.stringify(next, null, 2)}\n`, { encoding: "utf8", mode: 0o600 }); if (scope === "global") this.global = next; else this.project = next; diff --git a/packages/coding-agent/src/step/subagent-limits.ts b/packages/coding-agent/src/step/subagent-limits.ts new file mode 100644 index 000000000..059e67d09 --- /dev/null +++ b/packages/coding-agent/src/step/subagent-limits.ts @@ -0,0 +1,47 @@ +/** + * Accepted ranges for the `[subagent]` settings. + * + * Kept apart from the settings manager so the editor schema and the runtime + * validators read the same numbers without importing the whole manager. + */ + +export const SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS = 60; +export const SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS = 7_200; +export const SUBAGENT_BACKGROUND_TIMEOUT_DEFAULT_SECONDS = 3_600; + +/** Whether `value` is an accepted `[subagent] background_timeout_seconds`: an integer within the bounds. */ +export function isValidSubagentBackgroundTimeout(value: unknown): value is number { + return ( + typeof value === "number" && + Number.isInteger(value) && + value >= SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS && + value <= SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS + ); +} + +/** Message for a configured timeout that is ignored because it is out of bounds or not an integer. */ +export function invalidSubagentBackgroundTimeoutMessage( + value: unknown, + keyPath = "[subagent] background_timeout_seconds", +): string { + return `${keyPath} must be an integer from ${SUBAGENT_BACKGROUND_TIMEOUT_MIN_SECONDS} to ${SUBAGENT_BACKGROUND_TIMEOUT_MAX_SECONDS}; ignoring ${JSON.stringify(value)} and using ${SUBAGENT_BACKGROUND_TIMEOUT_DEFAULT_SECONDS}`; +} + +/** Default number of child processes a parallel subagent batch runs at once. */ +export const SUBAGENT_MAX_CONCURRENCY_DEFAULT = 8; + +/** + * Whether `value` is an accepted `[subagent] max_concurrency`: a positive + * integer. There is deliberately no upper bound — raising the limit above the + * default is the point of the setting. + */ +export function isValidSubagentMaxConcurrency(value: unknown): value is number { + return typeof value === "number" && Number.isInteger(value) && value >= 1; +} + +/** Message for a configured concurrency that is ignored because it is not a positive integer. */ +export function invalidSubagentMaxConcurrencyMessage(value: unknown, keyPath = "[subagent] max_concurrency"): string { + // The effective fallback (option, then default) is resolved per call, so the + // load-time warning only states that the value is ignored. + return `${keyPath} must be a positive integer; ignoring ${JSON.stringify(value)}`; +} diff --git a/packages/coding-agent/src/step/trace-headers.ts b/packages/coding-agent/src/step/trace-headers.ts index 17fc8a8db..23468cd84 100644 --- a/packages/coding-agent/src/step/trace-headers.ts +++ b/packages/coding-agent/src/step/trace-headers.ts @@ -46,36 +46,16 @@ const TRACE_HEADER_ENV_NAMES = [ */ const STEP_TRACE_PRODUCT_PROVIDERS = new Set(["stepfunModelProxy", "neocodex"]); -/** - * Step's first-party hosts (domestic `.com` + oversea `.ai`). Requests there - * carry the session id as the vendor-neutral `x-session-id`: on our own model - * endpoint that is product attribution, not third-party egress. - */ -export const STEP_FIRST_PARTY_TRACE_HOSTS: readonly string[] = ["api.stepfun.com", "api.stepfun.ai"]; - -/** Whether a request URL targets a Step first-party host over https. */ -export function isStepFirstPartyTraceUrl(requestUrl: string | undefined): boolean { - if (!requestUrl) return false; - try { - const url = new URL(requestUrl); - return url.protocol === "https:" && STEP_FIRST_PARTY_TRACE_HOSTS.includes(url.hostname); - } catch { - return false; - } -} - /** * Add Step attribution headers in place. * - * `x-step-client` is sent on every request. Step's first-party hosts - * (`https://api.stepfun.com/...`, `https://api.stepfun.ai/...`) additionally - * receive the session id as `x-session-id`. Every other high-sensitivity field - * (workspace/goal/...) — and the session id on any other host — is sent only - * when the request URL matches `options.allowedBaseUrls` AND the field appears - * in `options.highSensitivityFields`; an omitted or empty field list sends none - * of them (fail closed), so the local cwd never egresses to a third-party model - * endpoint. The session id keeps that single name on every path. Values are - * size-bounded and header-safe via {@link encodeStepTraceHeaderValue}. + * `x-step-client` is sent on every request. The high-sensitivity fields + * (session/workspace/goal/...) are sent only when the request URL matches + * `options.allowedBaseUrls` AND the field appears in + * `options.highSensitivityFields`; an omitted or empty field list sends none of + * them (fail closed), so the local cwd and session id never egress to a + * third-party model endpoint. Values are size-bounded and header-safe via + * {@link encodeStepTraceHeaderValue}. */ export function applyStepTraceHeaders( headers: Record, @@ -84,12 +64,6 @@ export function applyStepTraceHeaders( ): void { setHeader(headers, "x-step-client", options.clientType ?? "cli"); - // Step's own hosts always receive the session id, independent of the host - // trace policy; any other host only gets it through the allowlist below. - if (isStepFirstPartyTraceUrl(options.requestUrl)) { - setHeader(headers, "x-session-id", trace.sessionId); - } - const traceAllowed = options.requestUrl === undefined || options.allowedBaseUrls === undefined || @@ -104,9 +78,7 @@ export function applyStepTraceHeaders( const setIfAllowed = (field: string, value: string | undefined): void => { if (allowed.has(field)) setHeader(headers, `x-step-${field}`, value); }; - // The session id keeps one name on every path; the other attributed fields - // stay under the x-step-* prefix. - if (allowed.has("session-id")) setHeader(headers, "x-session-id", trace.sessionId); + setIfAllowed("session-id", trace.sessionId); setIfAllowed("goal-id", trace.goalId); setIfAllowed("attempt-id", trace.attemptId); setIfAllowed("harness-id", trace.harnessId); diff --git a/packages/coding-agent/src/theme/dark.json b/packages/coding-agent/src/theme/dark.json index 3201b0043..0c185da82 100644 --- a/packages/coding-agent/src/theme/dark.json +++ b/packages/coding-agent/src/theme/dark.json @@ -1,5 +1,5 @@ { - "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "$schema": "./theme-schema.json", "name": "dark", "vars": { "cyan": "#00d7ff", diff --git a/packages/coding-agent/src/theme/light.json b/packages/coding-agent/src/theme/light.json index e7e94e48b..939046cb6 100644 --- a/packages/coding-agent/src/theme/light.json +++ b/packages/coding-agent/src/theme/light.json @@ -1,5 +1,5 @@ { - "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "$schema": "./theme-schema.json", "name": "light", "vars": { "teal": "#5a8080", diff --git a/packages/coding-agent/src/theme/sage.json b/packages/coding-agent/src/theme/sage.json index 2ea872541..2733c8ba7 100644 --- a/packages/coding-agent/src/theme/sage.json +++ b/packages/coding-agent/src/theme/sage.json @@ -1,5 +1,5 @@ { - "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "$schema": "./theme-schema.json", "name": "sage", "vars": { "brand": "#a3ab78", diff --git a/packages/coding-agent/src/theme/step-violet-light.json b/packages/coding-agent/src/theme/step-violet-light.json index 1cb2d4c16..5e6c6c6b6 100644 --- a/packages/coding-agent/src/theme/step-violet-light.json +++ b/packages/coding-agent/src/theme/step-violet-light.json @@ -1,5 +1,5 @@ { - "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "$schema": "./theme-schema.json", "name": "step-violet-light", "vars": { "brand": "#5b21b6", diff --git a/packages/coding-agent/src/theme/step-violet.json b/packages/coding-agent/src/theme/step-violet.json index 22ae91631..887f799d0 100644 --- a/packages/coding-agent/src/theme/step-violet.json +++ b/packages/coding-agent/src/theme/step-violet.json @@ -1,5 +1,5 @@ { - "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "$schema": "./theme-schema.json", "name": "step-violet", "vars": { "brand": "#ab9eff", diff --git a/packages/coding-agent/src/theme/theme-schema.json b/packages/coding-agent/src/theme/theme-schema.json index 357998eec..a57d5f177 100644 --- a/packages/coding-agent/src/theme/theme-schema.json +++ b/packages/coding-agent/src/theme/theme-schema.json @@ -1,40 +1,38 @@ { - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "Pi Coding Agent Theme", - "description": "Theme schema for Pi coding agent", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "StepCode theme", "type": "object", - "required": ["name", "colors"], + "required": [ + "name", + "colors" + ], "properties": { "$schema": { - "type": "string", - "description": "JSON schema reference" + "type": "string" }, "name": { "type": "string", - "pattern": "^[^/]+$", - "description": "Theme name. Must not contain '/' because it is reserved for automatic light/dark theme settings." + "minLength": 1 }, "vars": { "type": "object", - "description": "Reusable color variables", - "additionalProperties": { - "oneOf": [ - { - "type": "string", - "description": "Hex color (#RRGGBB), variable reference, or empty string for terminal default" - }, - { - "type": "integer", - "minimum": 0, - "maximum": 255, - "description": "256-color palette index (0-255)" - } - ] + "patternProperties": { + "^.*$": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] + } } }, "colors": { "type": "object", - "description": "Theme color definitions (thinkingMax, scrollbarThumb, and search highlight colors are optional and use compatible fallbacks)", "required": [ "accent", "border", @@ -59,7 +57,6 @@ "toolTitle", "toolOutput", "mdHeading", - "mdTableHeader", "mdLink", "mdLinkUrl", "mdCode", @@ -91,271 +88,731 @@ ], "properties": { "accent": { - "$ref": "#/$defs/colorValue", - "description": "Primary accent color (logo, selected items, cursor)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "border": { - "$ref": "#/$defs/colorValue", - "description": "Normal borders" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "borderAccent": { - "$ref": "#/$defs/colorValue", - "description": "Highlighted borders" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "borderMuted": { - "$ref": "#/$defs/colorValue", - "description": "Subtle borders" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "success": { - "$ref": "#/$defs/colorValue", - "description": "Success states" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "error": { - "$ref": "#/$defs/colorValue", - "description": "Error states" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "warning": { - "$ref": "#/$defs/colorValue", - "description": "Warning states" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "muted": { - "$ref": "#/$defs/colorValue", - "description": "Secondary/dimmed text" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "dim": { - "$ref": "#/$defs/colorValue", - "description": "Very dimmed text (more subtle than muted)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "text": { - "$ref": "#/$defs/colorValue", - "description": "Default text color (usually empty string)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "thinkingText": { - "$ref": "#/$defs/colorValue", - "description": "Thinking block text color" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "selectedBg": { - "$ref": "#/$defs/colorValue", - "description": "Selected item background" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "scrollbarThumb": { - "$ref": "#/$defs/colorValue", - "description": "Fullscreen scrollbar thumb background (falls back to selectedBg when omitted)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "searchMatchBg": { - "$ref": "#/$defs/colorValue", - "description": "Transcript search match background and current-match text (falls back to selectedBg when omitted)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "searchMatchText": { - "$ref": "#/$defs/colorValue", - "description": "Transcript search match text and current-match background (falls back to text when omitted)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "userMessageBg": { - "$ref": "#/$defs/colorValue", - "description": "User message background" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "userMessageText": { - "$ref": "#/$defs/colorValue", - "description": "User message text color" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "customMessageBg": { - "$ref": "#/$defs/colorValue", - "description": "Custom message background (hook-injected messages)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "codeInlineBg": { - "$ref": "#/$defs/colorValue", - "description": "Inline code chip background (optional; falls back to customMessageBg)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "customMessageText": { - "$ref": "#/$defs/colorValue", - "description": "Custom message text color" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "customMessageLabel": { - "$ref": "#/$defs/colorValue", - "description": "Custom message type label color" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "toolPendingBg": { - "$ref": "#/$defs/colorValue", - "description": "Tool execution box (pending state)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "toolSuccessBg": { - "$ref": "#/$defs/colorValue", - "description": "Tool execution box (success state)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "toolErrorBg": { - "$ref": "#/$defs/colorValue", - "description": "Tool execution box (error state)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "toolTitle": { - "$ref": "#/$defs/colorValue", - "description": "Tool execution box title color" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "toolOutput": { - "$ref": "#/$defs/colorValue", - "description": "Tool execution box output text color" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdHeading": { - "$ref": "#/$defs/colorValue", - "description": "Markdown heading text" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdTableHeader": { - "$ref": "#/$defs/colorValue", - "description": "Markdown table header text" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdLink": { - "$ref": "#/$defs/colorValue", - "description": "Markdown link text" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdLinkUrl": { - "$ref": "#/$defs/colorValue", - "description": "Markdown link URL" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdCode": { - "$ref": "#/$defs/colorValue", - "description": "Markdown inline code" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdCodeBlock": { - "$ref": "#/$defs/colorValue", - "description": "Markdown code block content" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdCodeBlockBorder": { - "$ref": "#/$defs/colorValue", - "description": "Markdown code block fences" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdQuote": { - "$ref": "#/$defs/colorValue", - "description": "Markdown blockquote text" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdQuoteBorder": { - "$ref": "#/$defs/colorValue", - "description": "Markdown blockquote border" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdHr": { - "$ref": "#/$defs/colorValue", - "description": "Markdown horizontal rule" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "mdListBullet": { - "$ref": "#/$defs/colorValue", - "description": "Markdown list bullets/numbers" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "toolDiffAdded": { - "$ref": "#/$defs/colorValue", - "description": "Added lines in tool diffs" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "toolDiffRemoved": { - "$ref": "#/$defs/colorValue", - "description": "Removed lines in tool diffs" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "toolDiffContext": { - "$ref": "#/$defs/colorValue", - "description": "Context lines in tool diffs" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "syntaxComment": { - "$ref": "#/$defs/colorValue", - "description": "Syntax highlighting: comments" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "syntaxKeyword": { - "$ref": "#/$defs/colorValue", - "description": "Syntax highlighting: keywords" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "syntaxFunction": { - "$ref": "#/$defs/colorValue", - "description": "Syntax highlighting: function names" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "syntaxVariable": { - "$ref": "#/$defs/colorValue", - "description": "Syntax highlighting: variable names" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "syntaxString": { - "$ref": "#/$defs/colorValue", - "description": "Syntax highlighting: string literals" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "syntaxNumber": { - "$ref": "#/$defs/colorValue", - "description": "Syntax highlighting: number literals" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "syntaxType": { - "$ref": "#/$defs/colorValue", - "description": "Syntax highlighting: type names" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "syntaxOperator": { - "$ref": "#/$defs/colorValue", - "description": "Syntax highlighting: operators" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "syntaxPunctuation": { - "$ref": "#/$defs/colorValue", - "description": "Syntax highlighting: punctuation" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "thinkingOff": { - "$ref": "#/$defs/colorValue", - "description": "Thinking level border: off" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "thinkingMinimal": { - "$ref": "#/$defs/colorValue", - "description": "Thinking level border: minimal" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "thinkingLow": { - "$ref": "#/$defs/colorValue", - "description": "Thinking level border: low" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "thinkingMedium": { - "$ref": "#/$defs/colorValue", - "description": "Thinking level border: medium" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "thinkingHigh": { - "$ref": "#/$defs/colorValue", - "description": "Thinking level border: high" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "thinkingXhigh": { - "$ref": "#/$defs/colorValue", - "description": "Thinking level border: xhigh" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "thinkingMax": { - "$ref": "#/$defs/colorValue", - "description": "Thinking level border: max (falls back to thinkingXhigh when omitted)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "bashMode": { - "$ref": "#/$defs/colorValue", - "description": "Editor border color in bash mode" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] } - }, - "additionalProperties": false + } }, "export": { "type": "object", - "description": "Optional colors for HTML export (defaults derived from userMessageBg if not specified)", "properties": { "pageBg": { - "$ref": "#/$defs/colorValue", - "description": "Page background color" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "cardBg": { - "$ref": "#/$defs/colorValue", - "description": "Card/container background color" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] }, "infoBg": { - "$ref": "#/$defs/colorValue", - "description": "Info sections background (system prompt, notices)" + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255 + } + ] } - }, - "additionalProperties": false - } - }, - "additionalProperties": false, - "$defs": { - "colorValue": { - "oneOf": [ - { - "type": "string", - "description": "Hex color (#RRGGBB), variable reference, or empty string for terminal default" - }, - { - "type": "integer", - "minimum": 0, - "maximum": 255, - "description": "256-color palette index (0-255)" - } - ] + } } } } diff --git a/packages/coding-agent/src/theme/theme-schema.ts b/packages/coding-agent/src/theme/theme-schema.ts new file mode 100644 index 000000000..a5ba5f024 --- /dev/null +++ b/packages/coding-agent/src/theme/theme-schema.ts @@ -0,0 +1,98 @@ +/** + * The on-disk theme shape. + * + * Separate from `theme.ts` so generating or printing the editor schema does not + * load the theme runtime (colors, highlighting, the file watcher). The schema + * depends on TypeBox only, and `theme.ts` validates with the same object. + */ + +import { type Static, Type } from "typebox"; + +export const ColorValueSchema = Type.Union([ + Type.String(), // hex "#ff0000", var ref "primary", or empty "" + Type.Integer({ minimum: 0, maximum: 255 }), // 256-color index +]); + +export type ColorValue = Static; + +/** The on-disk theme shape; the editor schema is generated from it. */ +export const ThemeJsonSchema = Type.Object({ + $schema: Type.Optional(Type.String()), + // The rule lives in `assertThemeNameIsValid`, whose message explains why; a + // pattern here would fire first and replace it with "must match pattern". + name: Type.String({ minLength: 1 }), + vars: Type.Optional(Type.Record(Type.String(), ColorValueSchema)), + colors: Type.Object({ + // Core UI (10 colors) + accent: ColorValueSchema, + border: ColorValueSchema, + borderAccent: ColorValueSchema, + borderMuted: ColorValueSchema, + success: ColorValueSchema, + error: ColorValueSchema, + warning: ColorValueSchema, + muted: ColorValueSchema, + dim: ColorValueSchema, + text: ColorValueSchema, + thinkingText: ColorValueSchema, + // Backgrounds & Content Text (11 required, 3 optional) + selectedBg: ColorValueSchema, + scrollbarThumb: Type.Optional(ColorValueSchema), + searchMatchBg: Type.Optional(ColorValueSchema), + searchMatchText: Type.Optional(ColorValueSchema), + userMessageBg: ColorValueSchema, + userMessageText: ColorValueSchema, + customMessageBg: ColorValueSchema, + codeInlineBg: Type.Optional(ColorValueSchema), + customMessageText: ColorValueSchema, + customMessageLabel: ColorValueSchema, + toolPendingBg: ColorValueSchema, + toolSuccessBg: ColorValueSchema, + toolErrorBg: ColorValueSchema, + toolTitle: ColorValueSchema, + toolOutput: ColorValueSchema, + // Markdown (11 colors) + mdHeading: ColorValueSchema, + mdTableHeader: Type.Optional(ColorValueSchema), + mdLink: ColorValueSchema, + mdLinkUrl: ColorValueSchema, + mdCode: ColorValueSchema, + mdCodeBlock: ColorValueSchema, + mdCodeBlockBorder: ColorValueSchema, + mdQuote: ColorValueSchema, + mdQuoteBorder: ColorValueSchema, + mdHr: ColorValueSchema, + mdListBullet: ColorValueSchema, + // Tool Diffs (3 colors) + toolDiffAdded: ColorValueSchema, + toolDiffRemoved: ColorValueSchema, + toolDiffContext: ColorValueSchema, + // Syntax Highlighting (9 colors) + syntaxComment: ColorValueSchema, + syntaxKeyword: ColorValueSchema, + syntaxFunction: ColorValueSchema, + syntaxVariable: ColorValueSchema, + syntaxString: ColorValueSchema, + syntaxNumber: ColorValueSchema, + syntaxType: ColorValueSchema, + syntaxOperator: ColorValueSchema, + syntaxPunctuation: ColorValueSchema, + // Thinking Level Borders (6 colors) + thinkingOff: ColorValueSchema, + thinkingMinimal: ColorValueSchema, + thinkingLow: ColorValueSchema, + thinkingMedium: ColorValueSchema, + thinkingHigh: ColorValueSchema, + thinkingXhigh: ColorValueSchema, + thinkingMax: Type.Optional(ColorValueSchema), + // Bash Mode (1 color) + bashMode: ColorValueSchema, + }), + export: Type.Optional( + Type.Object({ + pageBg: Type.Optional(ColorValueSchema), + cardBg: Type.Optional(ColorValueSchema), + infoBg: Type.Optional(ColorValueSchema), + }), + ), +}); diff --git a/packages/coding-agent/src/theme/theme.ts b/packages/coding-agent/src/theme/theme.ts index 24ec0510d..ca62a1be8 100644 --- a/packages/coding-agent/src/theme/theme.ts +++ b/packages/coding-agent/src/theme/theme.ts @@ -10,104 +10,19 @@ import { type SettingsListTheme, } from "@step-harness/pi-tui"; import chalk from "chalk"; -import { type Static, Type } from "typebox"; +import type { Static } from "typebox"; import { Compile } from "typebox/compile"; import { getCustomThemesDir, getThemesDir } from "../config.ts"; import type { SourceInfo } from "../core/source-info.ts"; import { closeWatcher, watchWithErrorHandler } from "../utils/fs-watch.ts"; import { highlight, highlightGrammarRevision, supportsLanguage } from "../utils/syntax-highlight.ts"; import { stripBom } from "../utils/text.ts"; +import { type ColorValue, ThemeJsonSchema } from "./theme-schema.ts"; // ============================================================================ // Types & Schema // ============================================================================ -const ColorValueSchema = Type.Union([ - Type.String(), // hex "#ff0000", var ref "primary", or empty "" - Type.Integer({ minimum: 0, maximum: 255 }), // 256-color index -]); - -type ColorValue = Static; - -const ThemeJsonSchema = Type.Object({ - $schema: Type.Optional(Type.String()), - name: Type.String(), - vars: Type.Optional(Type.Record(Type.String(), ColorValueSchema)), - colors: Type.Object({ - // Core UI (10 colors) - accent: ColorValueSchema, - border: ColorValueSchema, - borderAccent: ColorValueSchema, - borderMuted: ColorValueSchema, - success: ColorValueSchema, - error: ColorValueSchema, - warning: ColorValueSchema, - muted: ColorValueSchema, - dim: ColorValueSchema, - text: ColorValueSchema, - thinkingText: ColorValueSchema, - // Backgrounds & Content Text (11 required, 3 optional) - selectedBg: ColorValueSchema, - scrollbarThumb: Type.Optional(ColorValueSchema), - searchMatchBg: Type.Optional(ColorValueSchema), - searchMatchText: Type.Optional(ColorValueSchema), - userMessageBg: ColorValueSchema, - userMessageText: ColorValueSchema, - customMessageBg: ColorValueSchema, - codeInlineBg: Type.Optional(ColorValueSchema), - customMessageText: ColorValueSchema, - customMessageLabel: ColorValueSchema, - toolPendingBg: ColorValueSchema, - toolSuccessBg: ColorValueSchema, - toolErrorBg: ColorValueSchema, - toolTitle: ColorValueSchema, - toolOutput: ColorValueSchema, - // Markdown (11 colors) - mdHeading: ColorValueSchema, - mdTableHeader: Type.Optional(ColorValueSchema), - mdLink: ColorValueSchema, - mdLinkUrl: ColorValueSchema, - mdCode: ColorValueSchema, - mdCodeBlock: ColorValueSchema, - mdCodeBlockBorder: ColorValueSchema, - mdQuote: ColorValueSchema, - mdQuoteBorder: ColorValueSchema, - mdHr: ColorValueSchema, - mdListBullet: ColorValueSchema, - // Tool Diffs (3 colors) - toolDiffAdded: ColorValueSchema, - toolDiffRemoved: ColorValueSchema, - toolDiffContext: ColorValueSchema, - // Syntax Highlighting (9 colors) - syntaxComment: ColorValueSchema, - syntaxKeyword: ColorValueSchema, - syntaxFunction: ColorValueSchema, - syntaxVariable: ColorValueSchema, - syntaxString: ColorValueSchema, - syntaxNumber: ColorValueSchema, - syntaxType: ColorValueSchema, - syntaxOperator: ColorValueSchema, - syntaxPunctuation: ColorValueSchema, - // Thinking Level Borders (6 colors) - thinkingOff: ColorValueSchema, - thinkingMinimal: ColorValueSchema, - thinkingLow: ColorValueSchema, - thinkingMedium: ColorValueSchema, - thinkingHigh: ColorValueSchema, - thinkingXhigh: ColorValueSchema, - thinkingMax: Type.Optional(ColorValueSchema), - // Bash Mode (1 color) - bashMode: ColorValueSchema, - }), - export: Type.Optional( - Type.Object({ - pageBg: Type.Optional(ColorValueSchema), - cardBg: Type.Optional(ColorValueSchema), - infoBg: Type.Optional(ColorValueSchema), - }), - ), -}); - type ThemeJson = Static; const validateThemeJson = Compile(ThemeJsonSchema); @@ -575,6 +490,11 @@ function assertThemeNameIsValid(name: string): void { } function parseThemeJson(label: string, json: unknown): ThemeJson { + // Checked before the schema so the user sees why "/" is rejected, rather than + // a generic pattern mismatch. + if (json && typeof json === "object" && typeof (json as { name?: unknown }).name === "string") { + assertThemeNameIsValid((json as { name: string }).name); + } if (!validateThemeJson.Check(json)) { const errors = Array.from(validateThemeJson.Errors(json)); const missingColors = new Set(); diff --git a/packages/coding-agent/test/cli-startup-cost.test.ts b/packages/coding-agent/test/cli-startup-cost.test.ts new file mode 100644 index 000000000..2e5b97b34 --- /dev/null +++ b/packages/coding-agent/test/cli-startup-cost.test.ts @@ -0,0 +1,109 @@ +import { existsSync, readFileSync } from "node:fs"; +import { dirname, relative, resolve } from "node:path"; +import { describe, expect, test } from "vitest"; + +/** + * Guard what `cli/args.ts` pulls in at startup. + * + * Every invocation loads this module, including `--help`. A commit on this + * branch once imported the config schema from it for one line of help text, + * which took the process from ~25 to ~148 modules and added about half a second + * to every command. Nothing failed in review; the first symptom was an + * unrelated test's child process timing out. + * + * The import graph is read statically rather than measured, so the result does + * not depend on the machine. Type-only imports are skipped: they are erased at + * compile time and cost nothing at startup. + */ + +const packageRoot = resolve(import.meta.dirname, ".."); +const ENTRY = resolve(packageRoot, "src/cli/args.ts"); + +/** + * Modules the entry must never reach at runtime. Each one belongs to the config + * subsystem, whose own entry point is `step config`, not every command. + */ +const FORBIDDEN_MODULES = [ + "src/step/config-schema.ts", + "src/step/config-toml.ts", + "src/step/command-compat.ts", + "src/step/settings-manager.ts", + "src/step/schema-files.ts", + "src/step/subagent-limits.ts", + "src/core/model-config.ts", + "src/core/settings-manager.ts", + "src/theme/theme.ts", +]; + +/** Packages the entry must never reach at runtime. */ +const FORBIDDEN_PACKAGES = ["typebox", "smol-toml", "undici", "highlight.js"]; + +/** `main` sits at 8 files; the allowance is for an unrelated addition. */ +const MAX_FILES = 12; + +interface Graph { + readonly files: string[]; + readonly packages: string[]; +} + +/** Follow runtime imports from `entry`, ignoring type-only ones. */ +function runtimeImportGraph(entry: string): Graph { + const files = new Set(); + const packages = new Set(); + + const walk = (file: string): void => { + if (files.has(file)) return; + files.add(file); + + const source = readFileSync(file, "utf8"); + // `import type` / `export type` are erased at compile time. + const runtime = source.replace(/(?:^|\n)\s*(?:import|export)\s+type\s[^;]*?;/g, "\n"); + + // `import "./x.ts"` has no `from`, and `import()` is an expression; a graph + // that only follows `from` would miss both. + const specifiers = [ + ...runtime.matchAll(/(?:^|\n)\s*(?:import|export)[^;]*?from\s+["']([^"']+)["']/g), + ...runtime.matchAll(/(?:^|\n)\s*import\s+["']([^"']+)["']/g), + ...runtime.matchAll(/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g), + ].map((match) => match[1]!); + + for (const specifier of specifiers) { + if (!specifier.startsWith(".")) { + packages.add(specifier); + continue; + } + const base = resolve(dirname(file), specifier); + const resolved = [base, `${base}.ts`, `${base}/index.ts`].find( + (candidate) => candidate.endsWith(".ts") && existsSync(candidate), + ); + if (resolved) walk(resolved); + } + }; + + walk(entry); + return { files: [...files], packages: [...packages] }; +} + +describe("cli/args.ts startup import graph", () => { + const graph = runtimeImportGraph(ENTRY); + + test("does not reach the config subsystem", () => { + const paths = graph.files.map((file) => relative(packageRoot, file)); + const reached = FORBIDDEN_MODULES.filter((module) => paths.includes(module)); + expect(reached, "cli/args.ts must not import these at runtime").toEqual([]); + }); + + test("does not pull in a heavy package", () => { + const reached = FORBIDDEN_PACKAGES.filter((name) => + graph.packages.some((specifier) => specifier === name || specifier.startsWith(`${name}/`)), + ); + expect(reached, "cli/args.ts must not import these at runtime").toEqual([]); + }); + + test("stays within the file budget", () => { + const paths = graph.files.map((file) => relative(packageRoot, file)); + expect(paths.length, `cli/args.ts reaches ${paths.length} files:\n${paths.join("\n")}`).toBeLessThanOrEqual( + MAX_FILES, + ); + }); +}); diff --git a/packages/coding-agent/test/config-help-subcommands.test.ts b/packages/coding-agent/test/config-help-subcommands.test.ts index 69c2cc204..2cfd5ff35 100644 --- a/packages/coding-agent/test/config-help-subcommands.test.ts +++ b/packages/coding-agent/test/config-help-subcommands.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "vitest"; -import { STEP_CONFIG_SUBCOMMANDS } from "../src/step/command-compat.ts"; +import { STEP_CONFIG_SUBCOMMANDS } from "../src/step/config-subcommands.ts"; import { runCliBrandingProbe } from "./cli-branding-probe.ts"; describe("config --help subcommands", () => { @@ -27,7 +27,7 @@ describe("config --help subcommands", () => { expect(result.isStepEntrypoint).toBe(true); expect(result.configHandled).toBe(true); expect(result.configHelp).toContain(`${appName} config [-l]`); - expect(STEP_CONFIG_SUBCOMMANDS.map((sub) => sub.name)).toEqual(["path", "show", "init"]); + expect(STEP_CONFIG_SUBCOMMANDS.map((sub) => sub.name)).toEqual(["path", "show", "init", "schema"]); for (const { name } of STEP_CONFIG_SUBCOMMANDS) { expect(result.configHelp).toMatch(new RegExp(`^\\s+${name}\\s`, "m")); } diff --git a/packages/coding-agent/test/config-schema.test.ts b/packages/coding-agent/test/config-schema.test.ts new file mode 100644 index 000000000..793f8d145 --- /dev/null +++ b/packages/coding-agent/test/config-schema.test.ts @@ -0,0 +1,372 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { parse as parseToml } from "smol-toml"; +import { Compile } from "typebox/compile"; +import { describe, expect, test } from "vitest"; +import { + DEFAULT_COMPACTION_TRIGGER_RATIO, + MAX_COMPACTION_TRIGGER_RATIO, + MIN_COMPACTION_TRIGGER_RATIO, +} from "../src/core/compaction/trigger-policy.ts"; +import { DEFAULT_HTTP_IDLE_TIMEOUT_MS } from "../src/core/http-dispatcher.ts"; +import { + ClosedModelsJsonSchema, + ConfigTomlSchema, + MODELS_SCHEMA_FILE_NAME, + ModelsJsonSchema, + PermissiveModelsJsonSchema, + renderConfigSchema, + renderStrictModelsSchema, + renderThemeSchema, +} from "../src/step/config-schema.ts"; +import { STEP_SETTING_ALIASES, STEP_SETTING_NESTED_ALIASES, type StepSettings } from "../src/step/settings-manager.ts"; +import { ThemeJsonSchema } from "../src/theme/theme-schema.ts"; + +const compileConfig = Compile(ConfigTomlSchema); +const compileModels = Compile(ModelsJsonSchema); +const compileTheme = Compile(ThemeJsonSchema); + +type JsonSchema = { properties?: Record; type?: string }; +const configProperties = (ConfigTomlSchema as JsonSchema).properties ?? {}; + +function hasKey(schema: JsonSchema, path: readonly string[]): boolean { + let node: JsonSchema | undefined = schema; + for (const part of path) { + node = node?.properties?.[part]; + if (!node) return false; + } + return true; +} + +describe("config.toml schema", () => { + // The loaders accept a flat key and two nested spellings for the same + // product setting. The schema has to accept every one of them, or an editor + // rejects a file the product still reads. + test("accepts every alias the settings manager honors", () => { + const aliases: string[][] = []; + for (const key of Object.keys(STEP_SETTING_ALIASES) as (keyof StepSettings)[]) { + aliases.push([key]); + for (const alias of STEP_SETTING_ALIASES[key]) aliases.push([alias]); + for (const nested of STEP_SETTING_NESTED_ALIASES[key]) aliases.push([...nested]); + } + const missing = aliases.filter((path) => !hasKey(ConfigTomlSchema as JsonSchema, path)); + expect(missing).toEqual([]); + }); + + test("accepts a document that uses the documented tables", () => { + const document = parseToml(` +defaultProvider = "step" +defaultModel = "step-5-preview" +permissionPreset = "approve-for-me" + +[compaction] +triggerRatio = 0.9 + +[subagent] +background = true +background_timeout_seconds = 3600 +max_concurrency = 8 + +[search] +provider = "auto" + +[telemetry] +enabled = false + +[mcp_servers.local] +command = "node" +args = ["server.js"] +`); + expect(compileConfig.Check(document)).toBe(true); + }); + + test("rejects an unknown key instead of silently accepting a typo", () => { + expect(compileConfig.Check({ compactionn: {} })).toBe(false); + expect(compileConfig.Check({ compaction: { triggerRation: 0.9 } })).toBe(false); + }); + + test("rejects a value the settings manager would discard", () => { + expect(compileConfig.Check({ compaction: { triggerRatio: 5 } })).toBe(false); + expect(compileConfig.Check({ subagent: { background_timeout_seconds: 10 } })).toBe(false); + expect(compileConfig.Check({ search: { provider: "not-a-backend" } })).toBe(false); + }); + + test("documents every top-level settings key in the schema", () => { + // A key the runtime reads but the schema omits would make the editor + // report a valid configuration as invalid. + const documented = Object.keys(configProperties); + expect(documented).toContain("defaultProvider"); + expect(documented).toContain("compaction"); + expect(documented).toContain("mcp_servers"); + expect(new Set(documented).size).toBe(documented.length); + }); +}); + +describe("models.json schema", () => { + test("accepts a provider with models and editable metadata", () => { + const document = { + $schema: "./models.schema.json", + providers: { + local: { + name: "Local", + baseUrl: "http://127.0.0.1:8000/v1", + apiKey: "unused", + api: "openai-completions", + models: [{ id: "local-model", contextWindow: 128000, maxTokens: 8192 }], + }, + }, + }; + expect(compileModels.Check(document)).toBe(true); + }); + + test("still requires providers", () => { + expect(compileModels.Check({})).toBe(false); + }); +}); + +describe("committed schema files", () => { + test("match the definitions the runtime loads through", () => { + const dir = join(import.meta.dirname, "..", "schema"); + expect(readFileSync(join(dir, "config.schema.json"), "utf8")).toBe(renderConfigSchema()); + expect(readFileSync(join(dir, MODELS_SCHEMA_FILE_NAME), "utf8")).toBe(renderStrictModelsSchema()); + }); +}); + +describe("theme schema", () => { + const themeDir = join(import.meta.dirname, "..", "src", "theme"); + + test("is generated from the schema the theme loader compiles", () => { + expect(readFileSync(join(themeDir, "theme-schema.json"), "utf8")).toBe(renderThemeSchema()); + }); + + test("every built-in theme resolves its editor schema beside itself", () => { + const files = readdirSync(themeDir).filter((name) => name.endsWith(".json") && name !== "theme-schema.json"); + expect(files.length).toBeGreaterThan(3); + for (const name of files) { + const theme = JSON.parse(readFileSync(join(themeDir, name), "utf8")) as { $schema?: string; name: string }; + // A relative path cannot rot the way a repository URL does. + expect(theme.$schema, name).toBe("./theme-schema.json"); + } + }); + + test("every built-in theme satisfies the schema", () => { + const check = compileTheme; + const files = readdirSync(themeDir).filter((name) => name.endsWith(".json") && name !== "theme-schema.json"); + for (const name of files) { + const theme = JSON.parse(readFileSync(join(themeDir, name), "utf8")) as unknown; + expect( + check.Errors(theme).map((error) => `${error.instancePath} ${error.message}`), + name, + ).toEqual([]); + } + }); +}); + +describe("files the product writes", () => { + // A file Step writes itself must satisfy the schema it ships. A new + // product-owned key that nobody added to the schema would otherwise make an + // editor report a false error on a freshly written config. + test("a config.toml written by the product validates against the schema", async () => { + const { mkdtemp, rm } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { markStepMcpImportSourcesReviewed } = await import("../src/step/mcp-import-store.ts"); + const { updateGlobalMcpConfig } = await import("../src/step/config-toml.ts"); + const root = await mkdtemp(join(tmpdir(), "step-schema-write-")); + const env = { STEP_CODING_AGENT_DIR: join(root, "agent"), HOME: join(root, "home") }; + try { + updateGlobalMcpConfig(env, () => ({ local: { command: "node", args: ["server.js"] } })); + markStepMcpImportSourcesReviewed([".claude"], env); + + const written = parseToml(readFileSync(join(root, "config.toml"), "utf8")); + const errors = compileConfig.Check(written) ? [] : compileConfig.Errors(written); + expect(errors.map((error) => `${error.instancePath} ${error.message}`)).toEqual([]); + expect(written.mcp_import).toBeDefined(); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); +}); + +type JsonSchemaNode = { + readonly description?: string; + readonly minimum?: number; + readonly maximum?: number; + readonly properties?: Record; +}; + +/** One property node of the generated document, by dotted path. */ +function schemaNode(path: readonly string[]): JsonSchemaNode | undefined { + let node: JsonSchemaNode | undefined = ConfigTomlSchema as unknown as JsonSchemaNode; + for (const part of path) node = node?.properties?.[part]; + return node; +} + +describe("schema values follow the constants the runtime reads", () => { + // Regenerating the schema catches a changed key. This catches a changed + // number: the schema's default and bounds are copied by hand into a + // description, so nothing else would notice the constant moving. + function numericBounds(path: readonly string[]): { minimum?: number; maximum?: number } { + const node = schemaNode(path); + return { minimum: node?.minimum, maximum: node?.maximum }; + } + + test("compaction.triggerRatio bounds match MIN/MAX_COMPACTION_TRIGGER_RATIO", () => { + expect(numericBounds(["compaction", "triggerRatio"])).toEqual({ + minimum: MIN_COMPACTION_TRIGGER_RATIO, + maximum: MAX_COMPACTION_TRIGGER_RATIO, + }); + }); + + test("the documented default equals DEFAULT_COMPACTION_TRIGGER_RATIO", () => { + const description = schemaNode(["compaction", "triggerRatio"])?.description; + expect(description).toContain(`default ${DEFAULT_COMPACTION_TRIGGER_RATIO}`); + }); + + test("autoClm fields are integers, as resolveAutoClmSettings requires", () => { + const schema = ConfigTomlSchema as unknown as { + properties: { + compaction: { properties: { autoClm: { properties: Record } } }; + }; + }; + const fields = schema.properties.compaction.properties.autoClm.properties; + const nonInteger = Object.entries(fields) + // `enabled` is a boolean and the two ratios are fractions. + .filter( + ([name, node]) => + !["enabled", "softThresholdRatio", "minSavingsRatio"].includes(name) && node.type !== "integer", + ) + .map(([name]) => name); + expect(nonInteger).toEqual([]); + }); + + test("rateLimitMaxRetries matches the clamp in getRetrySettings", () => { + expect(numericBounds(["retry", "rateLimitMaxRetries"])).toEqual({ minimum: 0, maximum: 20 }); + }); + + // The description states the number instead of importing the constant, so the + // schema module stays free of the HTTP stack. This keeps the two in step. + test("httpIdleTimeoutMs documents DEFAULT_HTTP_IDLE_TIMEOUT_MS", () => { + expect(schemaNode(["httpIdleTimeoutMs"])?.description).toContain(String(DEFAULT_HTTP_IDLE_TIMEOUT_MS)); + }); + + test("editorPaddingX and autocompleteMaxVisible match the ranges their setters clamp to", () => { + // `setEditorPaddingX` clamps 0-3 and `setAutocompleteMaxVisible` 3-20; the + // getters do not, so the schema is the only guard on a hand-edited file. + expect(numericBounds(["editorPaddingX"])).toEqual({ minimum: 0, maximum: 3 }); + expect(numericBounds(["autocompleteMaxVisible"])).toEqual({ minimum: 3, maximum: 20 }); + }); +}); + +describe("mcp_servers entries", () => { + // `normalizeDeclaration` in mcp.ts reads exactly these fields. A field added + // there but not to the schema would make the editor reject a working entry, + // and the other way round would let a key through that is never read. + test("the schema covers every field the MCP loader reads", async () => { + const source = readFileSync(join(import.meta.dirname, "..", "src", "step", "mcp.ts"), "utf8"); + const normalized = source.slice( + source.indexOf("function normalizeDeclaration"), + source.indexOf("export async function connectStepMcpServer"), + ); + const readFields = [...normalized.matchAll(/declaration\.([a-z_]+) =/g)].map((match) => match[1]!); + expect(readFields.length).toBeGreaterThan(5); + + const mcpSchema = ( + ConfigTomlSchema as unknown as { + properties: { mcp_servers: { patternProperties: Record }> } }; + } + ).properties.mcp_servers; + const server = Object.values(mcpSchema.patternProperties)[0]!; + const missing = [...new Set(readFields)].filter((field) => !(field in server.properties)); + expect(missing).toEqual([]); + }); +}); + +describe("legacy keys are part of the schema", () => { + // `migrateSettings` rewrites these before any read, so a file that still uses + // them works. The schema has to list them or the editor flags a valid file. + test.each(["queueMode", "websockets"])("%s is in the schema", (key) => { + expect(schemaNode([key])).toBeDefined(); + }); + + test("retry.maxDelayMs is in the schema", () => { + expect(schemaNode(["retry", "maxDelayMs"])).toBeDefined(); + }); + + // `migrateSettings` rewrites this shape into an array plus a boolean, so a + // file that still uses it loads. Without it here the editor would call that + // file invalid. + test("the older [skills] table is accepted alongside the array", () => { + const skills = schemaNode(["skills"]) as unknown as { anyOf?: unknown[] } | undefined; + expect(skills?.anyOf?.length).toBe(2); + expect(compileConfig.Check({ skills: { customDirectories: ["/tmp/x"] } })).toBe(true); + expect(compileConfig.Check({ skills: ["/tmp/x"] })).toBe(true); + }); +}); + +describe("the models.json editor schema only adds strictness", () => { + // The strict copy exists so a misspelled provider field is visible. If it + // ever diverges from the loader's shape for another reason, the editor would + // describe a different file than the runtime reads. + type Node = Record; + + /** Every path where `additionalProperties: false` was added. */ + function addedClosures(permissive: unknown, closed: unknown, path: string[] = []): string[] { + if (typeof permissive !== "object" || permissive === null || typeof closed !== "object" || closed === null) { + return []; + } + const a = permissive as Node; + const b = closed as Node; + const found: string[] = []; + if (a.additionalProperties === undefined && b.additionalProperties === false) found.push(path.join(".") || "/"); + + const keys = new Set([...Object.keys(a), ...Object.keys(b)]); + for (const key of keys) { + if (key === "additionalProperties") continue; + found.push(...addedClosures(a[key], b[key], [...path, key])); + } + return found; + } + + /** The two trees with those flags removed, which must then be identical. */ + function withoutClosures(value: unknown): unknown { + if (Array.isArray(value)) return value.map(withoutClosures); + if (typeof value !== "object" || value === null) return value; + return Object.fromEntries( + Object.entries(value as Node) + .filter(([key, entry]) => !(key === "additionalProperties" && entry === false)) + .map(([key, entry]) => [key, withoutClosures(entry)]), + ); + } + + test("differs from the loader's shape only by additionalProperties: false", () => { + expect(withoutClosures(ClosedModelsJsonSchema)).toEqual(withoutClosures(PermissiveModelsJsonSchema)); + }); + + test("closes provider and model objects", () => { + const closed = addedClosures(PermissiveModelsJsonSchema, ClosedModelsJsonSchema); + expect(closed.some((path) => path.includes("providers"))).toBe(true); + }); + + test("leaves a declared record open", () => { + // `samplingParams` is `Record`; its keys are data, so a + // closed object there would reject every sampling parameter. + const schema = ClosedModelsJsonSchema as unknown as { + properties: { + providers: { + patternProperties: Record< + string, + { + properties: { + models: { items: { properties: Record } }; + }; + } + >; + }; + }; + }; + const provider = Object.values(schema.properties.providers.patternProperties)[0]!; + const model = provider.properties.models.items; + expect(model.properties.samplingParams?.additionalProperties).not.toBe(false); + expect(model.properties.headers?.additionalProperties).not.toBe(false); + }); +}); diff --git a/packages/coding-agent/test/docs-config.test.ts b/packages/coding-agent/test/docs-config.test.ts new file mode 100644 index 000000000..b1d6a48ce --- /dev/null +++ b/packages/coding-agent/test/docs-config.test.ts @@ -0,0 +1,184 @@ +import { readFileSync } from "node:fs"; +import { dirname, join, relative } from "node:path"; +import { parse as parseToml } from "smol-toml"; +import { Compile } from "typebox/compile"; +import { describe, expect, test } from "vitest"; +import { ConfigTomlSchema, ModelsJsonSchema } from "../src/step/config-schema.ts"; + +const packageRoot = join(import.meta.dirname, ".."); +const repoRoot = join(packageRoot, "..", ".."); +const compileConfig = Compile(ConfigTomlSchema); +const compileModels = Compile(ModelsJsonSchema); + +/** + * Documentation files whose TOML blocks are StepCode configuration. + * + * A block in one of these files is validated against the shipped schema, so a + * documented key or value that the runtime would reject fails here instead of + * being copied by a reader. Files that show another product's TOML are listed + * below and skipped; adding one is a deliberate edit, not a silent opt-out. + */ +const CONFIG_DOCS = [ + join(packageRoot, "docs", "settings.md"), + join(packageRoot, "docs", "compaction.md"), + join(packageRoot, "docs", "context-management.md"), + join(repoRoot, "docs", "step-configuration.md"), + join(repoRoot, "docs", "step-unified-config-and-mcp.md"), +]; + +/** TOML blocks in these files belong to another tool, not to StepCode. */ +const EXTERNAL_TOML_DOCS = [join(packageRoot, "docs", "terminal-setup.md")]; + +interface Block { + readonly file: string; + readonly line: number; + readonly body: string; +} + +function tomlBlocks(file: string): Block[] { + const text = readFileSync(file, "utf8"); + const blocks: Block[] = []; + const pattern = /```toml\n([\s\S]*?)```/g; + for (const match of text.matchAll(pattern)) { + const line = text.slice(0, match.index).split("\n").length; + blocks.push({ file: relative(repoRoot, file), line, body: match[1]! }); + } + return blocks; +} + +describe("documented configuration examples", () => { + const blocks = CONFIG_DOCS.flatMap(tomlBlocks); + + test("there are examples to validate", () => { + expect(blocks.length).toBeGreaterThan(5); + }); + + test.each(blocks)("$file:$line parses and matches the config schema", (block) => { + let document: unknown; + try { + document = parseToml(block.body); + } catch (error) { + throw new Error(`${block.file}:${block.line} is not valid TOML: ${(error as Error).message}`); + } + const errors = compileConfig.Check(document) ? [] : compileConfig.Errors(document); + expect( + errors.map((error) => `${error.instancePath || "/"} ${error.message}`), + `${block.file}:${block.line}`, + ).toEqual([]); + }); + + test("files showing another product's TOML stay excluded from this check", () => { + for (const file of EXTERNAL_TOML_DOCS) expect(tomlBlocks(file).length).toBeGreaterThan(0); + }); +}); + +describe("settings documentation covers the schema", () => { + /** + * Keys the product writes itself and a reader should not configure. They are + * still in the schema so a file containing one stays valid. + */ + const INTERNAL_KEYS = new Set(["lastChangelogVersion"]); + + const allTopLevelKeys = Object.keys((ConfigTomlSchema as { properties: Record }).properties); + const settingsDoc = readFileSync(join(packageRoot, "docs", "settings.md"), "utf8"); + + test("every configurable top-level key is documented", () => { + const undocumented = allTopLevelKeys.filter( + (key) => !INTERNAL_KEYS.has(key) && !settingsDoc.includes(`\`${key}`), + ); + expect(undocumented).toEqual([]); + }); + + test("every documented setting row exists in the schema", () => { + const rows = [...settingsDoc.matchAll(/^\| `([a-zA-Z0-9_.]+)`/gm)].map((match) => match[1]!); + expect(rows.length).toBeGreaterThan(60); + + const properties = (ConfigTomlSchema as { properties: Record }).properties; + const missing = [...new Set(rows)].filter((key) => { + let node: JsonSchema | undefined = { properties }; + for (const part of key.split(".")) { + node = node?.properties?.[part]; + if (!node) return true; + } + return false; + }); + expect(missing).toEqual([]); + }); + + test("the documented settings file is config.toml, not a JSON settings file", () => { + expect(settingsDoc).toContain("~/.stepcode/config.toml"); + expect(settingsDoc).not.toContain("agent/settings.json"); + }); +}); + +describe("models documentation", () => { + test("the models.json schema accepts a documented provider entry", () => { + const document = { + providers: { + local: { + name: "Local", + baseUrl: "http://127.0.0.1:8000/v1", + api: "openai-completions", + models: [{ id: "local-model", contextWindow: 128000 }], + }, + }, + }; + expect(compileModels.Check(document)).toBe(true); + }); + + test("the models doc points at the schema shipped beside the file", () => { + const text = readFileSync(join(packageRoot, "docs", "models.md"), "utf8"); + expect(text).toContain("models.schema.json"); + expect(dirname(join(packageRoot, "docs"))).toBe(packageRoot); + }); +}); + +interface JsonSchema { + properties?: Record; +} + +describe("documented defaults match the schema", () => { + /** + * Every numeric default is written twice: once in the schema description + * (which an editor shows) and once in the docs table. Regenerating the schema + * does not catch a hand-edited number, so this compares them. + */ + function schemaDescription(path: readonly string[]): string | undefined { + let node: JsonSchema | undefined = ConfigTomlSchema as unknown as JsonSchema; + for (const part of path) node = node?.properties?.[part]; + return (node as { description?: string } | undefined)?.description; + } + + const documentedDefaults: Array<{ key: readonly string[]; docDefault: string }> = [ + { key: ["compaction", "triggerRatio"], docDefault: "0.9" }, + { key: ["compaction", "keepRecentTokens"], docDefault: "20000" }, + { key: ["compaction", "reserveTokens"], docDefault: "16384" }, + { key: ["branchSummary", "reserveTokens"], docDefault: "16384" }, + { key: ["retry", "maxRetries"], docDefault: "3" }, + { key: ["retry", "baseDelayMs"], docDefault: "2000" }, + { key: ["editorPaddingX"], docDefault: "0" }, + { key: ["autocompleteMaxVisible"], docDefault: "5" }, + { key: ["terminal", "imageWidthCells"], docDefault: "60" }, + { key: ["subagent", "max_concurrency"], docDefault: "8" }, + { key: ["subagent", "background_timeout_seconds"], docDefault: "3600" }, + ]; + + test.each(documentedDefaults)("$key default appears in the schema description", ({ key, docDefault }) => { + expect(schemaDescription(key), key.join(".")).toContain(docDefault); + }); + + test("the settings table default column agrees with the schema description", () => { + const settingsDoc = readFileSync(join(packageRoot, "docs", "settings.md"), "utf8"); + const rows = [...settingsDoc.matchAll(/^\| `([a-zA-Z0-9_.]+)` \| [^|]+ \| ([^|]+) \|/gm)]; + const mismatched: string[] = []; + for (const [, key, rawDefault] of rows) { + const expected = documentedDefaults.find((entry) => entry.key.join(".") === key); + if (!expected) continue; + const documented = rawDefault!.trim().replace(/`/g, ""); + if (documented !== expected.docDefault) { + mismatched.push(`${key}: table says ${documented}, schema says ${expected.docDefault}`); + } + } + expect(mismatched).toEqual([]); + }); +}); diff --git a/packages/coding-agent/test/step-config-command.test.ts b/packages/coding-agent/test/step-config-command.test.ts index 357bd8ca7..f581d2b89 100644 --- a/packages/coding-agent/test/step-config-command.test.ts +++ b/packages/coding-agent/test/step-config-command.test.ts @@ -1,4 +1,4 @@ -import { existsSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -190,3 +190,219 @@ describe("runStepConfigCommand argument handling", () => { ).rejects.toThrow(/Option "--path" requires a value/); }); }); + +describe("runStepConfigCommand schema files", () => { + test("`config init` writes the editor directive and both schemas beside the file", async () => { + const { env, root, configPath } = await makeEnv(); + const io = capture(); + + await runStepConfigCommand(["config", "init"], { stdout: io.stdout, homeEnv: env }); + + const template = readFileSync(configPath, "utf8"); + expect(template.split("\n")[0]).toBe("#:schema ./config.schema.json"); + expect(existsSync(join(root, "config.schema.json"))).toBe(true); + expect(existsSync(join(root, "models.schema.json"))).toBe(true); + expect(io.text()).toContain("config.schema.json"); + }); + + // The schema lives beside the global file only. A project or explicitly + // placed file belongs to a directory StepCode does not own, and two ~80 KB + // files in every checkout would show up in `git status`. + test("`config init --path ` writes no schema beside that file", async () => { + const { env, root } = await makeEnv(); + const target = join(root, "elsewhere", "config.toml"); + + await runStepConfigCommand(["config", "init", "--path", target], { + stdout: capture().stdout, + homeEnv: env, + }); + + expect(existsSync(target)).toBe(true); + expect(existsSync(join(root, "elsewhere", "config.schema.json"))).toBe(false); + expect(readFileSync(target, "utf8").split("\n")[0]).toBe("# StepCode configuration"); + }); + + test("`config init --scope workspace` writes no schema into the project", async () => { + const { env, root } = await makeEnv(); + const io = capture(); + + await runStepConfigCommand(["config", "init", "--scope", "workspace"], { + stdout: io.stdout, + homeEnv: env, + cwd: root, + }); + + expect(existsSync(join(root, ".stepcode", "config.toml"))).toBe(true); + expect(existsSync(join(root, ".stepcode", "config.schema.json"))).toBe(false); + }); + + test("the written template is a valid document", async () => { + const { env, configPath } = await makeEnv(); + await runStepConfigCommand(["config", "init"], { stdout: capture().stdout, homeEnv: env }); + + // The template is the first thing a new user edits, so it must satisfy + // the schema shipped next to it. + const { Compile } = await import("typebox/compile"); + const { parse } = await import("smol-toml"); + const { ConfigTomlSchema } = await import("../src/step/config-schema.ts"); + expect(Compile(ConfigTomlSchema).Check(parse(readFileSync(configPath, "utf8")))).toBe(true); + }); + + test("`config schema` prints the settings schema as JSON", async () => { + const { env } = await makeEnv(); + const io = capture(); + + await runStepConfigCommand(["config", "schema"], { stdout: io.stdout, homeEnv: env }); + + const schema = JSON.parse(io.text()); + expect(schema.title).toContain("config.toml"); + expect(schema.properties.compaction).toBeDefined(); + }); + + test("`config schema models --out ` writes the models schema", async () => { + const { env, root } = await makeEnv(); + const target = join(root, "models.schema.json"); + + await runStepConfigCommand(["config", "schema", "models", "--out", target], { + stdout: capture().stdout, + homeEnv: env, + }); + + const schema = JSON.parse(readFileSync(target, "utf8")); + expect(schema.title).toContain("models.json"); + expect(schema.properties.providers).toBeDefined(); + }); + + test("`config schema` rejects an unknown target", async () => { + const { env } = await makeEnv(); + await expect( + runStepConfigCommand(["config", "schema", "bogus"], { stdout: capture().stdout, homeEnv: env }), + ).rejects.toThrow(/Unknown schema "bogus"/); + }); +}); + +describe("runStepConfigCommand on a file a launch already created", () => { + // A launch creates an empty config.toml before the user asks for a template. + // Refusing to fill it forced `--force`, which also overwrites real settings. + test("`config init` fills an empty file without --force", async () => { + const { env, configPath } = await makeEnv(); + const { mkdirSync, writeFileSync } = await import("node:fs"); + mkdirSync(join(configPath, ".."), { recursive: true }); + writeFileSync(configPath, "#:schema ./config.schema.json\n# StepCode configuration\n"); + + const io = capture(); + await runStepConfigCommand(["config", "init"], { stdout: io.stdout, homeEnv: env }); + + expect(io.text()).toContain("Wrote Step config template"); + expect(readFileSync(configPath, "utf8")).toContain("defaultModel"); + }); + + test("`config init` still refuses a file that holds a setting", async () => { + const { env, configPath } = await makeEnv(); + const { mkdirSync, writeFileSync } = await import("node:fs"); + mkdirSync(join(configPath, ".."), { recursive: true }); + writeFileSync(configPath, 'theme = "dark"\n'); + + await expect( + runStepConfigCommand(["config", "init"], { stdout: capture().stdout, homeEnv: env }), + ).rejects.toThrow(/already exists/); + expect(readFileSync(configPath, "utf8")).toBe('theme = "dark"\n'); + }); +}); + +describe("config show redaction", () => { + // `show` is the discovery entry, so its output lands in transcripts and + // issues. Field names are useful; key material is not. + test("redacts credentials in config.toml as well as models.json", async () => { + const { env, root, configPath } = await makeEnv(); + const { mkdirSync, writeFileSync } = await import("node:fs"); + mkdirSync(join(configPath, ".."), { recursive: true }); + writeFileSync( + configPath, + [ + "[mcp_servers.remote]", + 'url = "https://example.test"', + 'bearer_token_env_var = "MY_TOKEN_VAR"', + 'env = { GITHUB_TOKEN = "ENV_TOKEN_VALUE", PATH = "/usr/bin" }', + 'http_headers = { Authorization = "Bearer HEADER_SECRET" }', + "[mcp_servers.remote.oauth]", + 'client_secret = "TOML_SECRET"', + 'client_id = "public-id"', + "", + ].join("\n"), + ); + writeFileSync(join(root, "models.json"), JSON.stringify({ providers: { p: { apiKey: "SK_SECRET" } } })); + const io = capture(); + + await runStepConfigCommand(["config", "show"], { stdout: io.stdout, homeEnv: env }); + const text = io.text(); + + for (const secret of ["ENV_TOKEN_VALUE", "HEADER_SECRET", "TOML_SECRET", "SK_SECRET"]) { + expect(text).not.toContain(secret); + } + // A non-secret value and a reference by name stay readable. + expect(text).toContain("/usr/bin"); + expect(text).toContain("MY_TOKEN_VAR"); + expect(text).toContain("public-id"); + }); +}); + +describe("config schema --out", () => { + // `--out` and the target are both bare words; skipping the option value by + // position keeps `--out models` from selecting the models schema. + test("writes the config schema when --out is named models", async () => { + const { env, root } = await makeEnv(); + const target = join(root, "models"); + + await runStepConfigCommand(["config", "schema", "--out", target], { + stdout: capture().stdout, + homeEnv: env, + }); + + expect(JSON.parse(readFileSync(target, "utf8")).title).toContain("config.toml"); + }); + + test("writes the models schema when the target and --out share a name", async () => { + const { env, root } = await makeEnv(); + const target = join(root, "config"); + + await runStepConfigCommand(["config", "schema", "models", "--out", target], { + stdout: capture().stdout, + homeEnv: env, + }); + + expect(JSON.parse(readFileSync(target, "utf8")).title).toContain("models.json"); + }); + + test("rejects an extra positional argument", async () => { + const { env } = await makeEnv(); + await expect( + runStepConfigCommand(["config", "schema", "models", "extra"], { + stdout: capture().stdout, + homeEnv: env, + }), + ).rejects.toThrow(/Unexpected argument "extra"/); + }); +}); + +describe("a launch never rewrites the config file", () => { + // The schema copies are refreshed on every launch; the config file is only + // written when the user changes a setting. Adding the editor directive is + // part of a write that was going to happen, not a write of its own. + test("refreshing schema copies leaves an existing config byte-identical", async () => { + const { env, root, configPath } = await makeEnv(); + const { mkdirSync, statSync, writeFileSync } = await import("node:fs"); + mkdirSync(join(configPath, ".."), { recursive: true }); + const content = '# StepCode configuration\ntheme = "dark"\n'; + writeFileSync(configPath, content); + const before = statSync(configPath).mtimeMs; + + // `ensureStepGlobalConfig` is what a launch calls. + const { ensureStepGlobalConfig } = await import("../src/step/config-toml.ts"); + ensureStepGlobalConfig(env); + + expect(readFileSync(configPath, "utf8")).toBe(content); + expect(statSync(configPath).mtimeMs).toBe(before); + expect(existsSync(join(root, "config.schema.json"))).toBe(true); + }); +}); diff --git a/packages/coding-agent/test/step-extension.test.ts b/packages/coding-agent/test/step-extension.test.ts index 050628513..b2d983392 100644 --- a/packages/coding-agent/test/step-extension.test.ts +++ b/packages/coding-agent/test/step-extension.test.ts @@ -845,9 +845,9 @@ describe("Step extension", () => { sessionManager: { getSessionId: () => "session-1" }, } as unknown as Pick); // The native Step endpoint is a direct model API, not the cloud-trace - // collector: workspace identifiers stay off it, while the session id rides - // along as first-party attribution under its single vendor-neutral name. - expect(headers).toEqual({ "x-step-client": "cli", "x-session-id": "session-1" }); + // collector. Keep session/workspace identifiers off custom or direct + // provider requests; only the low-sensitivity client marker is universal. + expect(headers).toEqual({ "x-step-client": "cli" }); const originalOrigin = process.env.STEPCODE_CLOUD_TRACE_ORIGIN; process.env.STEPCODE_CLOUD_TRACE_ORIGIN = "https://trace.example.test/v1"; @@ -864,7 +864,7 @@ describe("Step extension", () => { } as unknown as Pick); expect(otherHeaders).toMatchObject({ "x-step-client": "cli", - "x-session-id": "session-2", + "x-step-session-id": "session-2", "x-step-workspace-id": "/workspace", "x-step-provider-id": "stepfunModelProxy", "x-step-model": "step-proxy", diff --git a/packages/coding-agent/test/step-settings-manager.test.ts b/packages/coding-agent/test/step-settings-manager.test.ts index 7c3fd5e2d..40f8124ca 100644 --- a/packages/coding-agent/test/step-settings-manager.test.ts +++ b/packages/coding-agent/test/step-settings-manager.test.ts @@ -506,7 +506,12 @@ describe("Step settings manager decorator", () => { }); const written = readFileSync(path, "utf8"); - expect(written.startsWith("# StepCode configuration\n# hand written note\n")).toBe(true); + // A file written by an older release has no editor directive; the first + // write adds one so the schema now shipped beside it is actually used, and + // every existing comment survives in order. + expect(written.startsWith("#:schema ./config.schema.json\n# StepCode configuration\n# hand written note\n")).toBe( + true, + ); expect(readStepConfig(path)).toEqual({ defaultModel: "next", mcp_servers: { demo: { command: "demo" } } }); }); diff --git a/packages/coding-agent/test/step-trace-headers.test.ts b/packages/coding-agent/test/step-trace-headers.test.ts index 39484679d..7710b4f7f 100644 --- a/packages/coding-agent/test/step-trace-headers.test.ts +++ b/packages/coding-agent/test/step-trace-headers.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest"; import { applyStepTraceHeaders, encodeStepTraceHeaderValue, - isStepFirstPartyTraceUrl, isStepTraceRequestAllowed, matchesStepTraceBaseUrl, resolveStepTraceAllowlist, @@ -90,54 +89,6 @@ describe("Step trace headers", () => { expect(headers).toEqual({ "x-step-client": "cli" }); }); - it("sends the session id as x-session-id on Step's first-party hosts", () => { - for (const requestUrl of [ - "https://api.stepfun.com/step_plan/v1/chat/completions", - "https://api.stepfun.com/v1/messages", - "https://api.stepfun.ai/v1/responses", - ]) { - const headers: Record = {}; - // No allowlist and no field policy: the first-party host still gets the - // session id, and nothing else, under the vendor-neutral name. - applyStepTraceHeaders(headers, trace, { requestUrl, allowedBaseUrls: [] }); - expect(headers).toEqual({ "x-step-client": "cli", "x-session-id": "session-1" }); - } - }); - - it("keeps the session id off every other host", () => { - const headers: Record = {}; - applyStepTraceHeaders(headers, trace, { - requestUrl: "https://api.stepfun.com.example/v1", - allowedBaseUrls: [], - }); - expect(headers).toEqual({ "x-step-client": "cli" }); - }); - - it("omits x-session-id on a first-party host when the session id is absent", () => { - const headers: Record = {}; - applyStepTraceHeaders(headers, {}, { requestUrl: "https://api.stepfun.com/step_plan/v1", allowedBaseUrls: [] }); - expect(headers).toEqual({ "x-step-client": "cli" }); - }); - - it("recognizes only https first-party hosts", () => { - expect(isStepFirstPartyTraceUrl("https://api.stepfun.com/step_plan/v1")).toBe(true); - expect(isStepFirstPartyTraceUrl("https://API.Stepfun.Com/v1")).toBe(true); - expect(isStepFirstPartyTraceUrl("https://api.stepfun.ai/v1")).toBe(true); - expect(isStepFirstPartyTraceUrl("http://api.stepfun.com/v1")).toBe(false); - expect(isStepFirstPartyTraceUrl("https://api.stepfun.com.evil/v1")).toBe(false); - expect(isStepFirstPartyTraceUrl(undefined)).toBe(false); - }); - - it("does not duplicate the session id when the first-party host is also allowlisted", () => { - const headers: Record = {}; - applyStepTraceHeaders(headers, trace, { - requestUrl: "https://api.stepfun.com/step_plan/v1", - allowedBaseUrls: ["https://api.stepfun.com/step_plan/v1"], - highSensitivityFields: ["session-id"], - }); - expect(headers).toEqual({ "x-step-client": "cli", "x-session-id": "session-1" }); - }); - it("matches only a complete URL prefix", () => { const allowed = ["https://collector.example/v1/"]; expect(matchesStepTraceBaseUrl("https://collector.example/v1/messages", allowed)).toBe(true); diff --git a/scripts/generate-config-schema.ts b/scripts/generate-config-schema.ts new file mode 100644 index 000000000..feae69dbc --- /dev/null +++ b/scripts/generate-config-schema.ts @@ -0,0 +1,64 @@ +#!/usr/bin/env tsx +/** + * Write the editor schemas that ship with the binary. + * + * The schemas are generated from the TypeBox definitions the runtime loads + * through, so they are committed instead of hand-maintained. `--check` verifies + * the committed files without writing, and is run by `pnpm check`, so a change + * to a settings key cannot land with a stale schema. + */ + +import { readFileSync, writeFileSync } from "node:fs"; +import { dirname, join, relative } from "node:path"; +import { fileURLToPath } from "node:url"; +import { + renderConfigSchema, + renderStrictModelsSchema, + renderThemeSchema, +} from "../packages/coding-agent/src/step/config-schema.ts"; + +const repoRoot = join(dirname(fileURLToPath(import.meta.url)), ".."); +const schemaDir = join(repoRoot, "packages/coding-agent/schema"); + +const files = [ + { path: join(schemaDir, "config.schema.json"), content: renderConfigSchema() }, + { path: join(schemaDir, "models.schema.json"), content: renderStrictModelsSchema() }, + // Shipped beside the built-in themes, which reference it as ./theme-schema.json. + { path: join(repoRoot, "packages/coding-agent/src/theme/theme-schema.json"), content: renderThemeSchema() }, +]; + +const check = process.argv.includes("--check"); +let failed = false; + +for (const file of files) { + let current: string | undefined; + try { + current = readFileSync(file.path, "utf8"); + } catch { + current = undefined; + } + const label = relative(repoRoot, file.path); + + if (check) { + if (current === file.content) { + console.log(`ok ${label}`); + continue; + } + failed = true; + console.error( + current === undefined + ? `missing ${label}` + : `stale ${label}: regenerate with \`pnpm run generate:config-schema\``, + ); + continue; + } + + if (current === file.content) { + console.log(`unchanged ${label}`); + continue; + } + writeFileSync(file.path, file.content, "utf8"); + console.log(`wrote ${label}`); +} + +if (failed) process.exit(1);