@f5-sales-demo/xcsh 21.11.3 → 21.11.5
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.11.
|
|
4
|
+
"version": "21.11.5",
|
|
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.11.
|
|
65
|
-
"@f5-sales-demo/pi-ai": "21.11.
|
|
66
|
-
"@f5-sales-demo/pi-natives": "21.11.
|
|
67
|
-
"@f5-sales-demo/pi-resource-management": "21.11.
|
|
68
|
-
"@f5-sales-demo/pi-tui": "21.11.
|
|
69
|
-
"@f5-sales-demo/pi-utils": "21.11.
|
|
70
|
-
"@f5-sales-demo/xcsh-stats": "21.11.
|
|
64
|
+
"@f5-sales-demo/pi-agent-core": "21.11.5",
|
|
65
|
+
"@f5-sales-demo/pi-ai": "21.11.5",
|
|
66
|
+
"@f5-sales-demo/pi-natives": "21.11.5",
|
|
67
|
+
"@f5-sales-demo/pi-resource-management": "21.11.5",
|
|
68
|
+
"@f5-sales-demo/pi-tui": "21.11.5",
|
|
69
|
+
"@f5-sales-demo/pi-utils": "21.11.5",
|
|
70
|
+
"@f5-sales-demo/xcsh-stats": "21.11.5",
|
|
71
71
|
"@mozilla/readability": "^0.6",
|
|
72
72
|
"@sinclair/typebox": "^0.34",
|
|
73
73
|
"@xterm/headless": "^6.0",
|
package/src/commands/manager.ts
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
*/
|
|
20
20
|
import * as fs from "node:fs";
|
|
21
21
|
import { homedir } from "node:os";
|
|
22
|
-
import { dirname, join } from "node:path";
|
|
22
|
+
import { basename, dirname, join } from "node:path";
|
|
23
23
|
import { Command } from "@f5-sales-demo/pi-utils/cli";
|
|
24
24
|
// Lean subpath (not the package barrel, which pulls the winston logger graph and
|
|
25
25
|
// slows the manager's cold start — keep the daemon's module graph minimal).
|
|
@@ -192,9 +192,18 @@ function bridgeHello(port: number, timeoutMs = 400): Promise<Record<string, unkn
|
|
|
192
192
|
* `bun src/cli.ts <mode>` — re-exec a genuinely working subcommand. Shared by
|
|
193
193
|
* the manager (worker re-exec) and the chrome-host (manager re-exec).
|
|
194
194
|
*/
|
|
195
|
-
export function reexecArgv(
|
|
196
|
-
|
|
197
|
-
|
|
195
|
+
export function reexecArgv(
|
|
196
|
+
mode: "worker" | "manager",
|
|
197
|
+
argv: string[] = process.argv,
|
|
198
|
+
execPath: string = process.execPath,
|
|
199
|
+
): string[] {
|
|
200
|
+
const script = argv[1];
|
|
201
|
+
const executable = basename(execPath).toLowerCase();
|
|
202
|
+
if (
|
|
203
|
+
executable.startsWith("bun") &&
|
|
204
|
+
script &&
|
|
205
|
+
(script.endsWith(".ts") || script.endsWith(".js") || script.endsWith(".mjs"))
|
|
206
|
+
) {
|
|
198
207
|
return [script, mode];
|
|
199
208
|
}
|
|
200
209
|
return [mode];
|
|
@@ -17,17 +17,17 @@ export interface BuildInfo {
|
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
export const BUILD_INFO: BuildInfo = {
|
|
20
|
-
"version": "21.11.
|
|
21
|
-
"commit": "
|
|
22
|
-
"shortCommit": "
|
|
20
|
+
"version": "21.11.5",
|
|
21
|
+
"commit": "95c019fa60c8a8242482b18c45844ec73784ee11",
|
|
22
|
+
"shortCommit": "95c019f",
|
|
23
23
|
"branch": "main",
|
|
24
|
-
"tag": "v21.11.
|
|
25
|
-
"commitDate": "2026-09-
|
|
26
|
-
"buildDate": "2026-09-
|
|
24
|
+
"tag": "v21.11.5",
|
|
25
|
+
"commitDate": "2026-09-04T19:55:37+00:00",
|
|
26
|
+
"buildDate": "2026-09-04T20:34:45.692Z",
|
|
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/
|
|
32
|
-
"releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.11.
|
|
31
|
+
"commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/95c019fa60c8a8242482b18c45844ec73784ee11",
|
|
32
|
+
"releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.11.5"
|
|
33
33
|
};
|
|
@@ -146,7 +146,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
|
|
|
146
146
|
"en/providers/anthropic-access.md": "---\ntitle: Anthropic access\ndescription: Choose Claude subscription OAuth or usage-based Anthropic API access in xcsh.\nsidebar:\n order: 4\n label: Anthropic access\n---\n\nxcsh supports two separate Anthropic credential paths. A Claude App Pro or Max subscription uses OAuth; an\nAnthropic Console account uses usage-based API billing and an API key. Signing in to one does not grant access to\nthe other.\n\n## Claude subscription\n\nRun `/login anthropic` or select **Anthropic (Claude Pro/Max)** from the login picker. xcsh opens a loopback OAuth\nroute automatically and also displays a hosted authorization link that can be copied for SSH or headless use. The\nhosted page returns `code#state`; paste that complete value into xcsh. Both routes use PKCE and require the exact\nstate generated for that login attempt.\n\nAfter authentication, xcsh fetches the account's current model inventory. It applies the Claude subscription\nprofile only when fresh discovery advertises all three requested tiers:\n\n| Role | Model and thinking | Purpose |\n| --- | --- | --- |\n| `smol` | Claude Haiku 4.5 at `low` | Lightweight work |\n| `default` | Claude Sonnet 5 at `medium` | Everyday work |\n| `slow` | Claude Opus 5 at `high` | Thorough work |\n| `plan` | Claude Opus 5 at `high` | Planning |\n\nAutomatic routing follows Haiku → Sonnet → Opus. The highest-complexity escalation uses Opus at `xhigh`. xcsh\nstores the exact selector advertised for each tier, including the dated Haiku 4.5 API ID when the canonical alias\nis not advertised.\n\nIf any required tier is missing or the inventory is stale, the login remains valid but xcsh leaves the active\nmodel, thinking level, roles, routing mode, and profile unchanged. Use `/model` to inspect and select the models\nthe account currently advertises.\n\n## Anthropic API key\n\nFor usage-based Anthropic Console access, set `ANTHROPIC_API_KEY`. API requests are billed by Anthropic Console and\ndo not consume a Claude App subscription allowance. API-key authentication does not use `/login anthropic` and\ndoes not automatically apply the Claude subscription profile.\n",
|
|
147
147
|
"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\n## Manual Model Inventory Refresh\n\nIn the interactive model selector (`/model` or `Ctrl+M`), press `r` or run `/model --refresh` to trigger a manual inventory refresh. This forces a live probe of local endpoints (Ollama, LM Studio) and remote provider discovery caches without restarting the xcsh daemon.\n\n## LaTeX and Mathematical Formatting\n\nxcsh natively renders LaTeX math blocks and inline formulas (`$...$` and `$$...$$`) across the interactive TUI, markdown exports, and webviews with real-time Unicode glyph and KaTeX fallback formatting.\n",
|
|
148
148
|
"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",
|
|
149
|
-
"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.\
|
|
149
|
+
"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- When a supported Anthropic model is explicitly forced to call one named tool, that tool opts into strict generation\n only if its tool definition has `strict: true`, strict-schema adaptation succeeds, and the adapted schema stays within\n Anthropic's documented complexity limits. Other tools in the same request remain non-strict. Automatic tool\n selection, legacy or unknown models, and incompatible schemas retain the normal non-strict request shape.\n- OAuth requests apply the Claude tool-name prefix consistently to both the forced `tool_choice` and the matching strict tool definition.\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.\n\nThat tolerant parser is limited to in-progress previews. At Anthropic `content_block_stop`, a tool call that received\nJSON deltas is committed with exact `JSON.parse`; malformed completed JSON becomes a provider error and no\n`toolcall_end` is emitted. If Anthropic supplied complete inline input at `content_block_start` and sent no deltas,\nthe inline input is retained. Server-tool progress parsing remains best-effort because it is display-only and is not\ndispatched as a client tool call.\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",
|
|
150
150
|
"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",
|
|
151
151
|
"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",
|
|
152
152
|
"en/runtime-tools/context-command.md": "---\ntitle: \"F5 XC Contexts\"\ndescription: Connect xcsh to F5 Distributed Cloud tenants -- create, switch, and manage authentication contexts.\nsidebar:\n order: 1\n label: F5 XC Contexts\n---\n\nxcsh connects to F5 Distributed Cloud (F5 XC) tenants through **contexts** — named credential profiles binding a tenant endpoint URL, API token, and active namespace. Context management mimics `kubectl` and `kubectx` workflows: create contexts, switch between them by name, and use `-` to alternate between recent contexts.\n\n## Getting started\n\n### 1. Create a context\n\nObtain your tenant endpoint URL, an API certificate/token, and your target namespace from the F5 XC Console, then run:\n\n```bash\n/context create production https://<XC_TENANT>.console.ves.volterra.io <XC_API_TOKEN>\n```\n\nAlternatively, launch the guided setup wizard:\n\n```bash\n/context wizard\n```\n\n### 2. Activate a context\n\nActivate a context by specifying its name:\n\n```bash\n/context production\n```\n\n```text\n╭─ production ─────────────────────────────────────────────────╮\n│ XCSH_TENANT <XC_TENANT> │\n│ XCSH_API_URL https://<XC_TENANT>.console.ves.volterra.io │\n│ XCSH_API_TOKEN ...oken │\n│ Status Connected (312ms) │\n├─ Environment ────────────────────────────────────────────────┤\n│ XCSH_NAMESPACE default │\n╰──────────────────────────────────────────────────────────────╯\n```\n\nOnce activated, xcsh injects tenant credentials into the active session environment. The agent uses these credentials for F5 XC REST and Terraform operations.\n\n### 3. Switch between contexts\n\nSwitch to another context directly by name:\n\n```bash\n/context staging\n```\n\nAlternate back to the previous context:\n\n```bash\n/context -\n```\n\n### 4. List available contexts\n\n```bash\n/context\n```\n\nThe output indicates the active context with an asterisk (`*`):\n\n```text\n production https://<XC_TENANT>.console.ves.volterra.io\n* staging https://<XC_TENANT_STAGING>.console.ves.volterra.io\n```\n\n## Command reference\n\n### General management\n\n| Command | Description |\n| --- | --- |\n| `/context` | Lists all configured contexts. |\n| `/context <NAME>` | Activates the specified context. |\n| `/context -` | Switches to the previously active context. |\n| `/context show` | Displays active context configuration with masked tokens. |\n| `/context status` | Validates and reports API connectivity status. |\n\n### Context lifecycle operations\n\n| Command | Description |\n| --- | --- |\n| `/context create <NAME> <URL> <TOKEN> [NAMESPACE]` | Creates a new tenant context. |\n| `/context delete <NAME> --confirm` | Removes a context profile. |\n| `/context rename <OLD_NAME> <NEW_NAME>` | Renames an existing context. |\n| `/context validate <NAME>` | Tests credential validity without activating. |\n| `/context export [NAME] [--include-token]` | Exports context definitions to JSON. |\n| `/context import <PATH_OR_JSON> [--overwrite]` | Imports context configurations from JSON files or strings. |\n| `/context wizard` | Starts interactive step-by-step context configuration. |\n\n## Namespace management\n\nUpdate the active namespace within the current context:\n\n```bash\n/context namespace system\n```\n\nAuto-completion queries active namespaces from the connected tenant.\n\n## Custom context environment variables\n\nContexts can define custom environment variables that xcsh injects upon activation:\n\n```bash\n/context set CUSTOM_HEADER=x-demo-trace\n/context set LOG_LEVEL=debug\n/context env list\n/context unset LOG_LEVEL\n```\n\n## Environment variable precedence\n\nIf `XCSH_API_URL` and `XCSH_API_TOKEN` are set in the host shell prior to launching xcsh, environment variables override context configurations. When running under environment overrides, `/context` displays credentials marked with `(via env vars)`.\n",
|