@f5-sales-demo/xcsh 21.8.0 → 21.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@f5-sales-demo/xcsh",
4
- "version": "21.8.0",
4
+ "version": "21.9.0",
5
5
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
6
6
  "homepage": "https://github.com/f5-sales-demo/xcsh",
7
7
  "author": "Can Boluk",
@@ -61,13 +61,13 @@
61
61
  },
62
62
  "dependencies": {
63
63
  "@agentclientprotocol/sdk": "1.3.0",
64
- "@f5-sales-demo/pi-agent-core": "21.8.0",
65
- "@f5-sales-demo/pi-ai": "21.8.0",
66
- "@f5-sales-demo/pi-natives": "21.8.0",
67
- "@f5-sales-demo/pi-resource-management": "21.8.0",
68
- "@f5-sales-demo/pi-tui": "21.8.0",
69
- "@f5-sales-demo/pi-utils": "21.8.0",
70
- "@f5-sales-demo/xcsh-stats": "21.8.0",
64
+ "@f5-sales-demo/pi-agent-core": "21.9.0",
65
+ "@f5-sales-demo/pi-ai": "21.9.0",
66
+ "@f5-sales-demo/pi-natives": "21.9.0",
67
+ "@f5-sales-demo/pi-resource-management": "21.9.0",
68
+ "@f5-sales-demo/pi-tui": "21.9.0",
69
+ "@f5-sales-demo/pi-utils": "21.9.0",
70
+ "@f5-sales-demo/xcsh-stats": "21.9.0",
71
71
  "@mozilla/readability": "^0.6",
72
72
  "@sinclair/typebox": "^0.34",
73
73
  "@xterm/headless": "^6.0",
@@ -17,17 +17,17 @@ export interface BuildInfo {
17
17
  }
18
18
 
19
19
  export const BUILD_INFO: BuildInfo = {
20
- "version": "21.8.0",
21
- "commit": "1fbf4e99094587555f6270619aa5e24a8da8f340",
22
- "shortCommit": "1fbf4e9",
20
+ "version": "21.9.0",
21
+ "commit": "7ee899e33f372b2cc147d2f38903e2e77b1cd7b2",
22
+ "shortCommit": "7ee899e",
23
23
  "branch": "main",
24
- "tag": "v21.8.0",
25
- "commitDate": "2026-09-03T01:24:51+00:00",
26
- "buildDate": "2026-09-03T01:59:18.972Z",
24
+ "tag": "v21.9.0",
25
+ "commitDate": "2026-09-03T04:22:53+00:00",
26
+ "buildDate": "2026-09-03T04:50:52.144Z",
27
27
  "dirty": true,
28
28
  "prNumber": "",
29
29
  "repoUrl": "https://github.com/f5-sales-demo/xcsh",
30
30
  "repoSlug": "f5-sales-demo/xcsh",
31
- "commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/1fbf4e99094587555f6270619aa5e24a8da8f340",
32
- "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.8.0"
31
+ "commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/7ee899e33f372b2cc147d2f38903e2e77b1cd7b2",
32
+ "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.9.0"
33
33
  };
@@ -144,7 +144,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
144
144
  "en/natives/porting-to-natives.md": "---\ntitle: Porting to pi-natives (Node-API) — Field notes\ndescription: Field notes for migrating Node.js child_process and shell code to the Rust N-API native layer.\nsidebar:\n order: 9\n label: Porting to pi-natives\n---\n\nThis guide describes how to migrate performance-critical execution paths to Rust in `crates/pi-natives` and expose them through TypeScript bindings in `@f5-sales-demo/pi-natives`.\n\n## When to port to native modules\n\nPort execution paths to Rust when:\n\n- Execution paths execute within high-frequency rendering loops or large batch data pipelines.\n- JavaScript memory allocations dominate execution time (excessive string allocations, regex backtracking, large array transformations).\n- The operation is CPU-bound or performs blocking I/O that can run on libuv worker threads (`task::blocking`).\n- The operation orchestrates asynchronous I/O that benefits from the Tokio runtime (`task::future`).\n\nAvoid porting operations that require access to JavaScript runtime state or dynamic module imports. Native exports must remain pure, data-in/data-out functions.\n\n## Native export architecture\n\n### Rust implementation layer (`crates/pi-natives/`)\n\n1. Implement core functionality in `crates/pi-natives/src/<MODULE>.rs`.\n2. Register the module in `crates/pi-natives/src/lib.rs`.\n3. Annotate functions with `#[napi]`. Rust `snake_case` function names convert to JavaScript `camelCase` identifiers automatically.\n4. Use `task::blocking` for CPU-bound computation and `task::future` for asynchronous operations. Pass `CancelToken` instances when supporting timeouts or `AbortSignal`.\n\n### TypeScript binding layer (`packages/natives/`)\n\n1. Define interface augmentations in `packages/natives/src/<MODULE>/types.ts` extending `NativeBindings` via declaration merging.\n2. Import `<MODULE>/types.ts` in `packages/natives/src/native.ts` to activate type definitions.\n3. Add validation entries in `validateNative` within `packages/natives/src/native.ts` to enforce required exports at startup.\n4. Implement ergonomic wrappers in `packages/natives/src/<MODULE>/index.ts` and re-export them from `packages/natives/src/index.ts`.\n\n## Step-by-step porting workflow\n\n1. **Implement Rust logic**: Create functions with owned types (`String`, `Vec<String>`, `Uint8Array`) and wrap long loops with `ct.heartbeat()?`.\n2. **Expose TypeScript bindings**: Add types in `<MODULE>/types.ts` and export wrapper functions.\n3. **Register native validation**: Add `checkFn(\"exportName\")` to `validateNative` in `packages/natives/src/native.ts`.\n4. **Create performance benchmarks**: Benchmark JavaScript and Rust implementations side-by-side using `Bun.nanoseconds()`.\n5. **Compile native binaries**: Run `bun --cwd=packages/natives run build`.\n6. **Validate performance**: Verify that the native path outperforms JavaScript before switching production call sites.\n\n## Troubleshooting common issues\n\n### Stale native binaries\n\nThe runtime loader prioritizes platform-tagged binaries (`pi_natives.<PLATFORM>-<ARCH>.node`). If exports fail to update:\n\n```bash\nrm packages/natives/native/pi_natives.*.node\nbun --cwd=packages/natives run build\n```\n\nIf testing against pre-compiled binaries, remove the extraction cache:\n\n```bash\nrm -rf ~/.xcsh/natives/\n```\n\n### Missing export validation errors\n\nIf `validateNative` raises an error indicating missing exports:\n\n- Verify that the Rust export name matches the expected JavaScript camelCase name.\n- Verify that the binary was rebuilt after adding the `#[napi]` attribute.\n- Never disable or weaken `validateNative` checks.\n",
145
145
  "en/office-test-ownership.md": "# Office add-in test ownership\n\nThis document defines the canonical test ownership and execution responsibilities for the `office-pane` package and Office add-in task pane integration tests.\n\n## Test suites and domain ownership\n\n| Test suite / harness | Location | Canonical owner | Execution tier | Description |\n| --- | --- | --- | --- | --- |\n| **Office Task Pane UI Unit Tests** | `packages/office-pane/src/**/*.test.ts` | Frontend / UI Core Team | Local and PR CI | Core Office.js state management and task pane rendering |\n| **Office Host Integration Harness** | `packages/office-pane/test/integration/` | Ecosystem Integrations Team | PR CI Matrix | Simulated Office.js API host binding and event handling |\n| **Acceptance End-to-End Suite** | `packages/office-pane/test/e2e/` | QA and Release Engineering | Nightly Release CI | Headless browser execution against Word and Excel task pane mocks |\n\n## Maintenance responsibilities\n\n- **Frontend / UI Core Team**: Responsible for unit test coverage on UI components in `office-pane`.\n- **Ecosystem Integrations Team**: Responsible for host mock fidelity and API contract alignment.\n- **Release Engineering**: Responsible for end-to-end environment stability and CI matrix runtimes.\n",
146
146
  "en/providers/models.md": "---\ntitle: Model and Provider Configuration\ndescription: Model registry and provider configuration via models.yml with routing, fallback, and pricing.\nsidebar:\n order: 1\n label: Models & providers\n---\n\nThis document describes how xcsh loads model registries, applies configuration overrides, resolves API credentials, and manages model selection at runtime.\n\n## Core implementation architecture\n\nModel configuration and runtime resolution are implemented across the following modules:\n\n- `src/config/model-registry.ts`: Loads built-in and custom models, manages provider overrides, discovers local models, and integrates authentication.\n- `src/config/model-resolver.ts`: Parses model patterns, handles canonical coalescing, and selects default, small, and reasoning models.\n- `src/config/settings-schema.ts`: Defines settings schemas for `modelRoles` and transport options.\n- `src/session/auth-storage.ts`: Resolves API keys and OAuth tokens across configuration sources.\n- `packages/ai/src/models.ts` and `packages/ai/src/types.ts`: Defines built-in models and compatibility contracts.\n\n## Configuration file path\n\nDefault configuration path:\n\n- `~/.xcsh/agent/models.yml`\n\n> [!NOTE]\n> If `models.yml` is missing and a legacy `models.json` file exists in the configuration directory, xcsh automatically migrates the settings to `models.yml`.\n\n## Schema structure\n\n```yaml\nconfigVersion: 1\nproviders:\n <PROVIDER_ID>:\n baseUrl: https://api.example.com/v1\n apiKey: MY_API_KEY_ENV_VAR\n api: openai-completions\n headers:\n X-Custom-Header: value\n auth: apiKey\n discovery:\n type: ollama\n modelOverrides:\n <MODEL_ID>:\n name: Custom Model Display Name\n models:\n - id: custom-model-id\n name: Custom Model Name\n api: openai-completions\n contextWindow: 128000\n maxTokens: 16384\n cost:\n input: 0\n output: 0\n cacheRead: 0\n cacheWrite: 0\nequivalence:\n overrides:\n <PROVIDER_ID>/<MODEL_ID>: <CANONICAL_MODEL_ID>\n exclude:\n - <PROVIDER_ID>/<MODEL_ID>\n```\n\n### Supported API protocol types\n\n- `openai-completions`\n- `openai-responses`\n- `openai-codex-responses`\n- `azure-openai-responses`\n- `anthropic-messages`\n- `google-generative-ai`\n- `google-vertex`\n\n## Validation rules\n\n### Custom provider definitions (`models` defined)\n\nThe following fields are required:\n\n- `baseUrl`: Base endpoint URL.\n- `apiKey`: Required unless `auth: none` is explicitly configured.\n- `api`: Protocol type specified at the provider or model level.\n\n### Override-only providers (`models` omitted)\n\nMust specify at least one of:\n\n- `baseUrl`\n- `modelOverrides`\n- `discovery`\n\n## Merge and override hierarchy\n\nWhen initializing or refreshing the model registry, xcsh applies configuration in the following order:\n\n1. **Built-in catalog**: Loads default providers and models from `@f5-sales-demo/pi-ai`.\n2. **Custom configuration**: Parses `~/.xcsh/agent/models.yml`.\n3. **Provider overrides**: Applies custom `baseUrl` and default `headers` to built-in models.\n4. **Model overrides**: Merges custom settings from `modelOverrides`.\n5. **Custom models**: Appends or replaces model definitions matching existing `provider/id` pairs.\n6. **Runtime discovery**: Queries active local endpoints (such as Ollama or LM Studio) and registers discovered models.\n\n## Canonical model equivalence and coalescing\n\nxcsh groups equivalent model checkpoints from different providers under canonical upstream identifiers (for example, `claude-sonnet-4`, `gpt-5.3-codex`):\n\n- **Overrides**: Maps specific provider identifiers to standard canonical names via `equivalence.overrides`.\n- **Exclusions**: Removes specific variants from automatic grouping via `equivalence.exclude`.\n- **Resolution priority**: Selects concrete providers based on credential availability and `modelProviderOrder` precedence.\n\n## Runtime model discovery\n\nxcsh detects local inference runtimes automatically:\n\n- **Ollama**: Probes `http://127.0.0.1:11434/api/tags` (or `OLLAMA_BASE_URL`).\n- **LM Studio**: Probes `http://127.0.0.1:1234/v1/models` (or `LM_STUDIO_BASE_URL`).\n- **llama.cpp**: Probes `http://127.0.0.1:8080/v1/models` (or `LLAMA_CPP_BASE_URL`).\n\n## Credential resolution hierarchy\n\nWhen resolving API keys for a provider, xcsh evaluates sources in the following priority order:\n\n1. CLI flag `--api-key`\n2. Stored API keys in `agent.db`\n3. Stored OAuth tokens in `agent.db`\n4. Standard environment variables (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`)\n5. Provider `apiKey` field in `models.yml` (evaluated first as an environment variable name, then as a literal token)\n\n## Corporate Google Cloud Vertex AI login\n\n`/login` lists **Google Cloud Vertex AI (Corporate)** first. This route opens the authorized standalone Google enterprise browser flow, validates the selected Google Cloud project and Gemini 3.7 Flash access in `global`, then selects `google-vertex/gemini-3.7-flash:high`. It does not require `gcloud` or an Application Default Credentials file.\n\nThe short-lived credential is stored only in the isolated `google-vertex` namespace. The confirmed project and `global` location are stored as non-secret xcsh provider preferences and injected into every Vertex request. The route never falls back to ambient ADC, a Gemini API key, consumer Gemini login, or Antigravity OAuth.\n\nHeadless terminals display a browser URL and accept the resulting localhost callback URL. Billing, API enablement, IAM, quota, and model-access errors are reported before model state is changed.\n\n**Google Antigravity Enterprise (Advanced OAuth)** remains a separate route. It uses its own entitlement-discovery OAuth flow and does not assert that its discovered model is Vertex Gemini 3.7. Consumer and free-tier Google routes remain optional, but are never selected automatically.\n\n## Model roles and selection\n\nxcsh supports logical role aliases configured via `settings.modelRoles`:\n\n- `default`: Primary interaction model.\n- `smol`: Fast, lightweight model for metadata tasks and short tool evaluations.\n- `slow`: High-reasoning model for complex multi-step planning and analysis.\n- `plan`: Model assigned to interactive planning modes.\n- `commit`: Model assigned to git commit generation.\n\nEach role definition can include thinking intensity suffixes (for example, `pi/smol:minimal`, `claude-sonnet-4:high`).\n\n## Context promotion and fallback\n\nWhen a model context window overflows during a conversation turn (`context_length_exceeded`), xcsh automatically promotes the session to a larger-context sibling model before initiating context compaction:\n\n1. Evaluates explicit `contextPromotionTarget` configurations.\n2. Identifies the smallest available model with a larger context window on the same provider.\n3. Switches the session model temporarily and retries the turn.\n",
147
- "en/providers/openai-api-access.md": "---\ntitle: OpenAI access\ndescription: Choose ChatGPT subscription or usage-based OpenAI Platform access in xcsh.\nsidebar:\n order: 4\n label: OpenAI access\n---\n\nxcsh supports two distinct access methods for OpenAI services, depending on whether you authenticate with a ChatGPT subscription or an OpenAI Platform API key.\n\n## 1. ChatGPT subscription (OAuth)\n\nTo use your ChatGPT Plus or Pro subscription, run `/login openai-codex` or select **ChatGPT Plus/Pro (Codex Subscription)** in the `/login` interactive picker. xcsh stores the OAuth credentials securely in `agent.db` and discovers advertised subscription models.\n\n### Headless and SSH remote login\n\nWhen running inside an SSH session or headless terminal, xcsh automatically initiates device-code authentication:\n\n1. xcsh displays `https://auth.openai.com/codex/device` and a one-time verification code.\n2. Open the URL in any web browser and log in with your ChatGPT account credentials.\n3. Enter the one-time verification code.\n4. The remote xcsh process detects authorization automatically and completes authentication.\n\n> [!NOTE]\n> Device-code authentication requires enabling the beta feature in ChatGPT under **Settings → Security**, or via workspace administrator settings under **Workspace settings → Permissions & roles**.\n\n### Local desktop browser callback\n\nOn local workstations with graphical desktop environments, the same `/login openai-codex` command opens your default browser and receives tokens through a local loopback listener on port 1455 (`http://localhost:1455/auth/callback`).\n\nIf device authorization is unavailable in an SSH or headless session, the same login flow offers browser/manual redirect authentication. Open the displayed URL locally, then paste the redirect URL into `/login <redirect URL>` on the remote host.\n\n## 2. OpenAI Platform API (usage-based billing)\n\nTo use pay-as-you-go OpenAI Platform access, configure the `OPENAI_API_KEY` environment variable or provide it in `models.yml`:\n\n```bash\nexport OPENAI_API_KEY=\"<OPENAI_API_KEY>\"\nxcsh\n```\n\nAfter starting xcsh, select an OpenAI model using `/model`.\n",
147
+ "en/providers/openai-api-access.md": "---\ntitle: OpenAI access\ndescription: Choose ChatGPT subscription or usage-based OpenAI Platform access in xcsh.\nsidebar:\n order: 4\n label: OpenAI access\n---\n\nxcsh supports two distinct access methods for OpenAI services, depending on whether you authenticate with a ChatGPT subscription or an OpenAI Platform API key.\n\n## 1. ChatGPT subscription (OAuth)\n\nTo use your ChatGPT Plus or Pro subscription, run `/login openai-codex` or select **ChatGPT Plus/Pro (Codex Subscription)** in the `/login` interactive picker. xcsh stores the OAuth credentials securely in `agent.db` and discovers advertised subscription models.\n\nWhen fresh authenticated discovery advertises all three GPT-5.6 tiers, login applies this role profile atomically:\n\n| Role | Model and effort | Intended use |\n| --- | --- | --- |\n| `smol` | `openai-codex/gpt-5.6-luna:low` | Lightweight and metadata work |\n| `default` | `openai-codex/gpt-5.6-terra:medium` | Balanced everyday work |\n| `slow` | `openai-codex/gpt-5.6-sol:high` | Thorough analysis |\n| `plan` | `openai-codex/gpt-5.6-sol:high` | Architectural planning |\n\nThe active post-login model is Terra at medium effort. This follows\n[OpenAI model guidance](https://developers.openai.com/api/docs/guides/latest-model):\nLuna is the efficient high-volume tier, Terra balances intelligence and cost, and Sol is the\nflagship for complex professional work. OpenAI recommends medium as a balanced starting point,\nlow for latency-sensitive work, and higher efforts only where they produce a measured quality gain.\n\nAutomatic routing remains off after login. If you enable it, the existing pool routes Luna/low → Terra/medium → Sol/high and uses Sol/xhigh only for rejected work or the highest-complexity requests. `max` remains available as a manual quality-first effort rather than a static role default.\n\nIf Luna, Terra, or Sol is absent—or authenticated discovery is stale—the profile and active model are left unchanged.\n\n### Headless and SSH remote login\n\nWhen running inside an SSH session or headless terminal, xcsh automatically initiates device-code authentication:\n\n1. xcsh displays `https://auth.openai.com/codex/device` and a one-time verification code.\n2. Open the URL in any web browser and log in with your ChatGPT account credentials.\n3. Enter the one-time verification code.\n4. The remote xcsh process detects authorization automatically and completes authentication.\n\n> [!NOTE]\n> Device-code authentication requires enabling the beta feature in ChatGPT under **Settings → Security**, or via workspace administrator settings under **Workspace settings → Permissions & roles**.\n\n### Local desktop browser callback\n\nOn local workstations with graphical desktop environments, the same `/login openai-codex` command opens your default browser and receives tokens through a local loopback listener on port 1455 (`http://localhost:1455/auth/callback`).\n\nIf device authorization is unavailable in an SSH or headless session, the same login flow offers browser/manual redirect authentication. Open the displayed URL locally, then paste the redirect URL into `/login <redirect URL>` on the remote host.\n\n## 2. OpenAI Platform API (usage-based billing)\n\nTo use pay-as-you-go OpenAI Platform access, configure the `OPENAI_API_KEY` environment variable or provide it in `models.yml`:\n\n```bash\nexport OPENAI_API_KEY=\"<OPENAI_API_KEY>\"\nxcsh\n```\n\nAfter starting xcsh, select an OpenAI model using `/model`.\n",
148
148
  "en/providers/provider-streaming-internals.md": "---\ntitle: Provider Streaming Internals\ndescription: Provider streaming implementation with SSE parsing, token counting, and backpressure handling.\nsidebar:\n order: 2\n label: Streaming internals\n---\n\nThis document describes how token and tool call streams from diverse LLM providers are normalized in `@f5-sales-demo/pi-ai` and propagated through `@f5-sales-demo/pi-agent-core` to `coding-agent` session events.\n\n## End-to-end streaming architecture\n\n1. **Stream dispatch**: `streamSimple()` in `packages/ai/src/stream.ts` maps provider-agnostic request options and dispatches them to the selected provider driver.\n2. **Provider normalization**: Provider stream drivers (`anthropic.ts`, `openai-responses.ts`, `google.ts`) translate vendor-specific Server-Sent Events (SSE) into a unified `AssistantMessageEvent` stream.\n3. **Event throttling**: `AssistantMessageEventStream` (`packages/ai/src/utils/event-stream.ts`) buffers and coalesces rapid delta events (~50ms cadence) to smooth UI rendering.\n4. **Agent loop consumption**: `agentLoop` (`packages/agent/src/agent-loop.ts`) processes events, updates in-flight message state, and emits `message_update` events.\n5. **Session event integration**: `AgentSession` (`packages/coding-agent/src/session/agent-session.ts`) handles user aborts, automated retries, context compaction, and tool call execution guards.\n\n## Unified stream contract (`AssistantMessageEvent`)\n\nAll provider drivers emit events conforming to the `AssistantMessageEvent` union:\n\n- `start`: Initiates stream processing.\n- Content block lifecycle triplets:\n - Text: `text_start` → `text_delta`* → `text_end`\n - Thinking / reasoning: `thinking_start` → `thinking_delta`* → `thinking_end`\n - Tool invocation: `toolcall_start` → `toolcall_delta`* → `toolcall_end`\n- Terminal events:\n - `done`: Emits termination reasons (`stop`, `length`, `toolUse`).\n - `error`: Emits failure reasons (`aborted`, `error`).\n\n## Provider-specific normalization logic\n\n### Anthropic (`anthropic-messages`)\n\n- Maps `message_start` to token usage metadata.\n- Maps `content_block_start` and `content_block_delta` to unified text, thinking, and tool invocation blocks.\n- Accumulates streamed JSON fragments in `partialJson` and reparses arguments incrementally via `parseStreamingJson()`.\n\n### OpenAI Responses (`openai-responses`)\n\n- Maps `response.output_item.added` to text or reasoning blocks.\n- Maps `response.reasoning_summary_text.delta` to `thinking_delta`.\n- Translates `response.function_call_arguments.delta` into `toolcall_delta`.\n- Normalizes tool call identifiers into `<CALL_ID>|<ITEM_ID>`.\n\n### Google Generative AI (`google-generative-ai`)\n\n- Parses `candidate.content.parts`, distinguishing thinking blocks via `isThinkingPart()`.\n- Emits synthetic `toolcall_delta` containing serialized JSON strings for structured tool call events.\n\n## Tool call JSON accumulation and error recovery\n\nIncremental tool arguments are parsed via `parseStreamingJson()` (`packages/ai/src/utils/json-parse.ts`):\n\n1. Attempts standard `JSON.parse`.\n2. Falls back to partial JSON parsing to evaluate incomplete streamed fragments.\n3. If partial parsing fails, returns `{}` temporarily until subsequent deltas provide valid JSON structures.\n4. Performs a final parse pass on `toolcall_end`.\n\n## Cancellation and lifecycle boundaries\n\n- **Provider HTTP request**: `options.signal` aborts the active HTTP transport connection.\n- **Agent loop**: Evaluates `signal.aborted` prior to processing each streamed event.\n- **Session abortion**: Calling `AgentSession.abort()` propagates cancellations to active tool subprocesses.\n- **Tool execution interrupts**: Tool runners listen to `AbortSignal.any([agentSignal, steeringAbortSignal])`, allowing users to interrupt long-running tools without discarding prior turns.\n\n## Related implementation files\n\n- `packages/ai/src/stream.ts`: Provider stream dispatcher and option normalizer.\n- `packages/ai/src/utils/event-stream.ts`: Stream queueing and delta event throttling.\n- `packages/ai/src/utils/json-parse.ts`: Incremental streaming JSON parser.\n- `packages/ai/src/providers/anthropic.ts`: Anthropic SSE event transformer.\n- `packages/ai/src/providers/openai-responses.ts`: OpenAI Responses event transformer.\n- `packages/ai/src/providers/google.ts`: Google Gemini event transformer.\n- `packages/agent/src/agent-loop.ts`: Agent event processing loop.\n- `packages/coding-agent/src/session/agent-session.ts`: Session lifecycle, retry policies, and persistence.\n",
149
149
  "en/providers/python-repl.md": "---\ntitle: Python Tool and IPython Runtime\ndescription: Python REPL tool runtime with IPython kernel management, execution, and output capture.\nsidebar:\n order: 3\n label: Python & IPython\n---\n\nThis document describes the Python execution architecture in `packages/coding-agent`, covering tool parameters, Jupyter Kernel Gateway lifecycles, environment isolation, execution semantics, and troubleshooting procedures.\n\n## Architecture overview\n\nPython execution is managed across several core modules:\n\n- `src/tools/python.ts`: Tool interface definition and interactive cell renderers.\n- `src/ipy/executor.ts`: Session-level kernel orchestration and execution scheduling.\n- `src/ipy/kernel.ts`: Kernel lifecycle management and WebSocket communication protocol.\n- `src/ipy/gateway-coordinator.ts`: Shared local Jupyter Kernel Gateway process coordinator.\n- `src/ipy/runtime.ts`: Python environment discovery, virtualenv resolution, and environment variable filtering.\n\n## Tool parameter schema\n\n```typescript\ninterface PythonToolParams {\n cells: Array<{\n code: string;\n title?: string;\n }>;\n timeout?: number; // Execution timeout in seconds (1–600, default: 30)\n cwd?: string; // Working directory for execution\n reset?: boolean; // Reset kernel state prior to executing first cell\n}\n```\n\nThe tool executes with `concurrency: \"exclusive\"`, ensuring sequential execution per session.\n\n## Gateway lifecycle management\n\n### Gateway operational modes\n\n1. **Local shared gateway (default)**:\n - Coordinates a single shared process under `~/.xcsh/agent/python-gateway/`.\n - Synchronizes access via `gateway.lock` and tracks state in `gateway.json`.\n - Starts `python -m kernel_gateway` bound to an ephemeral port on `127.0.0.1`.\n2. **External gateway**:\n - Configured via `PI_PYTHON_GATEWAY_URL`.\n - Authenticates requests with `PI_PYTHON_GATEWAY_TOKEN` when required.\n - Bypasses local process management.\n\n### Kernel lifecycle\n\n1. **Creation**: Allocates a new kernel session via `POST /api/kernels`.\n2. **Connection**: Establishes a WebSocket channel (`/api/kernels/:id/channels`).\n3. **Initialization**: Configures `cwd`, applies sanitized environment variables, and executes runtime preludes.\n4. **Module loading**: Imports custom modules from `~/.xcsh/agent/modules/*.py` and project-specific `<CWD>/.xcsh/modules/*.py`.\n5. **Termination**: Issues `DELETE /api/kernels/:id` and closes WebSocket connections upon session cleanup.\n\n## Environment isolation and security\n\nBefore launching Python runtimes, xcsh filters environment variables:\n\n- **Retained variables**: Core system variables (`PATH`, `HOME`, `VIRTUAL_ENV`, `PYTHONPATH`) and whitelisted prefixes (`LC_*`, `XDG_*`, `PI_*`).\n- **Sanitized variables**: Strips sensitive LLM API keys (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`) to prevent accidental leaks.\n\n### Python environment resolution order\n\n1. Active virtual environment (`VIRTUAL_ENV` or `<CWD>/.venv`)\n2. Managed xcsh virtual environment (`~/.xcsh/python-env`)\n3. System `python3` or `python` on `PATH`\n\n## Output capture and MIME rendering\n\nThe runtime captures structured output across multiple MIME types:\n\n- `text/markdown`: Rendered directly in interactive output panes.\n- `text/plain`: Standard console output and tracebacks.\n- `application/json`: Formatted JSON inspector trees.\n- `image/png`: Inline image payloads.\n- `application/x-xcsh-status`: Structured progress and execution status events.\n\n## Troubleshooting\n\n### Python tool unavailable\n\n- Verify that `jupyter_kernel_gateway` and `ipykernel` are installed in the resolved Python environment:\n\n ```bash\n python -m pip install jupyter_kernel_gateway ipykernel\n ```\n\n- Verify that `python.toolMode` or `PI_PY` is not set to `bash-only`.\n\n### Execution timeouts or hangs\n\n- Python does not support interactive standard input (`input()`). Avoid invoking interactive prompts.\n- To handle long-running workloads, increase the `timeout` parameter (up to 600 seconds).\n",
150
150
  "en/runtime-tools/bash-tool-runtime.md": "---\ntitle: Bash Tool Runtime\ndescription: Bash tool runtime with shell process management, sandboxing, timeout, and output streaming.\nsidebar:\n order: 1\n label: Bash tool\n---\n\nThis document describes the execution pipeline of the `bash` tool in `packages/coding-agent`, covering command normalization, interception rules, process sandboxing, output truncation, and UI rendering across execution modes.\n\n## Execution entry points\n\nxcsh provides two distinct shell execution interfaces:\n\n1. **Agent tool interface (`bash`)**: Invoked by LLMs during conversation turns. Supports command normalization, security interception, PTY emulation, and structured output formatting.\n - Entry point: `BashTool.execute()`\n2. **User shell execution (`!cmd`)**: Direct shell execution triggered by user input in the TUI or RPC mode.\n - Entry point: `AgentSession.executeBash()`\n\nBoth execution paths utilize the underlying `executeBash()` engine in `src/exec/bash-executor.ts` for non-interactive execution.\n\n## Execution pipeline\n\n### 1. Command normalization and argument parsing\n\nWhen a tool call occurs, `BashTool.execute()` normalizes command strings via `normalizeBashCommand()`:\n\n- Extracts trailing pipe limits (`| head -n N`, `| tail -n N`) into structured pagination parameters.\n- Trims outer whitespace while preserving internal arguments and heredocs.\n- Merges extracted limits with explicit `head` or `tail` parameters (explicit arguments take precedence).\n\n### 2. Command interception and rule enforcement\n\nIf `bashInterceptor.enabled` is active, the tool checks the command against configured regex rules before spawning processes:\n\n- **Rule evaluation**: Blocks commands when patterns match (e.g., using `cat` or `grep` when specialized tools exist) and the suggested alternative tool is present in active context (`ctx.toolNames`).\n- **Rejection behavior**: Raises a `ToolError` containing the blocking reason and guidance toward preferred tools (`view_file`, `grep_search`, `list_dir`, `replace_file_content`).\n\n### 3. Working directory validation and timeouts\n\n- Resolves working directories relative to session root (`resolveToCwd`).\n- Validates that directory paths exist and are accessible directories prior to execution.\n- Clamps timeout durations to the range of 1 to 3600 seconds (default: 30 seconds).\n\n### 4. Interactive PTY vs. non-interactive execution\n\nxcsh chooses PTY execution (`runInteractiveBashPty`) when all of the following conditions are met:\n\n- `bash.virtualTerminal` is configured to `on`.\n- `PI_NO_PTY` is not set to `1`.\n- The session has an active graphical/TUI terminal context (`ctx.hasUI === true`).\n\nIn headless, print, or RPC modes, xcsh always uses non-interactive execution.\n\n## Output streaming, truncation, and artifact spill\n\nOutput is processed through `OutputSink` in `src/session/streaming-output.ts`:\n\n- **Memory buffer**: Maintains a UTF-8-safe tail buffer (default: 50 KB).\n- **Artifact spillover**: When output exceeds the buffer threshold, xcsh writes the full stream to disk in artifact storage (`artifact://<ID>`).\n- **Truncation notice**: Injects truncation summaries into tool results, including total byte/line counts and artifact links for full-output retrieval.\n\n## Filesystem sandboxing and containment\n\nxcsh enforces filesystem containment boundaries using platform-native security primitives:\n\n| Platform | Kernel version | Security backend | Boundary enforcement |\n| -------- | -------------- | ---------------- | -------------------- |\n| macOS | Any | `seatbelt` | OS-enforced kernel sandbox |\n| Linux (modern) | Kernel ≥ 6.1 (Debian 12, Ubuntu 24.04, Fedora) | `landlock` (ABI ≥ 2) | OS-enforced kernel sandbox |\n| Linux (legacy) | Kernel < 6.1 (RHEL 9, Ubuntu 22.04 GA) | `scanner-only` | Command-text static analysis |\n\n> [!IMPORTANT]\n> On legacy Linux kernels with Landlock ABI 1 (kernel < 6.1), xcsh operates in `scanner-only` mode because ABI 1 lacks `LANDLOCK_ACCESS_FS_REFER` (which prevents `git` and `mv` operations). For full OS-enforced isolation, deploy on Linux kernels 6.1 or newer.\n\n## Related implementation files\n\n- `src/tools/bash.ts`: Tool definition, normalization, and rendering logic.\n- `src/tools/bash-normalize.ts`: Command string normalization and line limit extraction.\n- `src/tools/bash-interceptor.ts`: Pattern matching rules for command redirection.\n- `src/exec/bash-executor.ts`: Process execution engine and shell session reuse.\n- `src/tools/bash-interactive.ts`: Virtual PTY runtime and terminal input handling.\n- `src/session/streaming-output.ts`: `OutputSink` buffer management and artifact spillover.\n",
@@ -51,10 +51,10 @@ export const GOOGLE_VERTEX_LOGIN_MODEL_CHOICE: LoginModelChoice = {
51
51
  };
52
52
 
53
53
  export const OPENAI_CODEX_LOGIN_MODEL_CHOICE: LoginModelChoice = {
54
- label: "GPT-5.6",
54
+ label: "GPT-5.6 Terra",
55
55
  description: "OpenAI Codex subscription model with medium reasoning",
56
56
  provider: "openai-codex",
57
- modelId: "gpt-5.6-sol",
57
+ modelId: "gpt-5.6-terra",
58
58
  thinkingLevel: ThinkingLevel.Medium,
59
59
  };
60
60
 
@@ -88,11 +88,14 @@ interface BaseModelApplicableSession {
88
88
  }
89
89
 
90
90
  interface ModelApplicableSession extends BaseModelApplicableSession {
91
+ model?: Model;
92
+ thinkingLevel?: ThinkingLevel;
91
93
  modelRegistry: {
92
94
  getAll(): Model[];
93
95
  getProviderDiscoveryState?(provider: string): { status: string; stale: boolean } | undefined;
94
96
  };
95
97
  settings?: Pick<Settings, "getModelRoles" | "get" | "set">;
98
+ setModelTemporary?(model: Model, thinkingLevel?: ThinkingLevel): Promise<void>;
96
99
  }
97
100
 
98
101
  /**
@@ -155,6 +158,8 @@ export async function applyOAuthLoginModel(
155
158
  ),
156
159
  )
157
160
  : {};
161
+ const previousModel = session.model;
162
+ const previousThinkingLevel = session.thinkingLevel;
158
163
  if (settings) {
159
164
  const available = session.modelRegistry.getAll().map(model => `${model.provider}/${model.id}`);
160
165
  const profile = applySubscriptionProfileRoles(
@@ -177,10 +182,27 @@ export async function applyOAuthLoginModel(
177
182
  }
178
183
  return applied ? choice : undefined;
179
184
  } catch (error) {
185
+ const rollbackErrors: unknown[] = [];
180
186
  if (settings) {
181
- settings.set("modelRoles", previousRoles);
182
- settings.set("routing.mode", previousRoutingMode);
183
- settings.set("routing.profile", previousProfile);
187
+ try {
188
+ settings.set("modelRoles", previousRoles);
189
+ settings.set("routing.mode", previousRoutingMode);
190
+ settings.set("routing.profile", previousProfile);
191
+ } catch (rollbackError) {
192
+ rollbackErrors.push(rollbackError);
193
+ }
194
+ }
195
+ try {
196
+ if (previousModel && session.setModelTemporary) {
197
+ await session.setModelTemporary(previousModel, previousThinkingLevel);
198
+ } else if (previousThinkingLevel !== undefined) {
199
+ session.setThinkingLevel(previousThinkingLevel);
200
+ }
201
+ } catch (rollbackError) {
202
+ rollbackErrors.push(rollbackError);
203
+ }
204
+ if (rollbackErrors.length > 0) {
205
+ throw new AggregateError([error, ...rollbackErrors], "OAuth login model rollback was incomplete");
184
206
  }
185
207
  throw error;
186
208
  }
@@ -39,7 +39,7 @@ export const SUBSCRIPTION_ROUTING_PROFILES: Readonly<Record<SubscriptionProfileI
39
39
  provider: "openai-codex",
40
40
  roles: {
41
41
  smol: "openai-codex/gpt-5.6-luna:low",
42
- default: "openai-codex/gpt-5.6-sol:medium",
42
+ default: "openai-codex/gpt-5.6-terra:medium",
43
43
  slow: "openai-codex/gpt-5.6-sol:high",
44
44
  plan: "openai-codex/gpt-5.6-sol:high",
45
45
  },
@@ -16,7 +16,7 @@ import { SearchProvider } from "./base";
16
16
 
17
17
  const CODEX_BASE_URL = "https://chatgpt.com/backend-api";
18
18
  const CODEX_RESPONSES_PATH = "/codex/responses";
19
- const DEFAULT_MODEL = "gpt-5-codex-mini";
19
+ const DEFAULT_MODEL = "gpt-5.6-terra";
20
20
  const JWT_CLAIM_PATH = "https://api.openai.com/auth";
21
21
  const DEFAULT_INSTRUCTIONS =
22
22
  "You are a helpful assistant with web search capabilities. Search the web to answer the user's question accurately and cite your sources.";