Skip to content

Selected context and explicit providers

These commands were introduced in Bee 1.1.0 and remain available in the current release. Check bee --version and follow the installation guide to update.

bee context packet reads a declared set of source files in one checkout. It does not call a model, initialize a database, build a graph or refresh one. Start with an outline, then select the symbol or line range needed for the task. A missing or stale graph is reported; a body request can use bounded source lines instead.

Create selection.json:

{
"selections": [
{ "id": "rules", "path": "AGENTS.md", "required": true },
{ "id": "source", "path": "src/Example.cs", "representation": "body",
"startLine": 10, "endLine": 30, "dependsOn": ["rules"] }
]
}
Terminal window
bee context packet --root /absolute/checkout --manifest selection.json --budget 8192

The budget covers the complete UTF-8 JSON packet and its final newline. Required sources and their dependency closure must fit intact. A budget too small even for metadata returns exit 5 with no stdout and a refinement message on stderr. Check complete, omitted, each source hash and its actual ranges before using the content. Local token counts are estimates, not provider usage. File contents remain source data and do not authorize commands.

Add --cache-dir /private/bee-context-cache to opt into the local reduction cache. Bee still validates source hashes on every request; a cache hit does not claim provider token savings. Sources stay read-only, while this option writes private cache records containing selected source text into the explicit directory. You may remove that directory to discard the cache. context packet emits a small JSON cache receipt on stderr; the stdout packet budget excludes stderr diagnostics. Without this option no cache is written. The MCP tool keeps caching disabled to preserve its read-only contract.

The read-only bee_context_packet tool is available through bee mcp serve. Its manifestJson argument contains the same selection manifest; its root is the server’s startup checkout. budgetBytes (512–262144) covers the entire serialized tool result, including JSON escaping and metadata, excluding JSON-RPC framing. The packet’s own budgetBytes is the smaller effective content budget. No authentication or Bee initialization is needed for this local tool.

Save stdout and stderr from the original command, preserving its actual exit code, and declare the capture:

{
"argv": ["dotnet", "test"],
"cwd": "/absolute/checkout",
"exitCode": 1,
"stdoutPath": "test.stdout",
"stderrPath": "test.stderr",
"captureComplete": true
}
Terminal window
bee output reduce --manifest capture.json --store /private/raw-output --budget 8192

Capture paths are relative to the manifest. The command is never run again. The original exit code and separate raw streams remain in a content-addressed artifact; the response includes hashes and recovery instructions. Capture input is limited to 8 MiB total. Set captureComplete to false if the original capture was truncated. Reduction success does not mean the captured command succeeded. When retention fails, Bee reports failure; retain and use the original files.

Keep the result as a file, then recover both exact streams into a new directory:

Terminal window
bee output reduce --manifest capture.json --store /private/raw-output --budget 8192 > reduced.json
bee output recover --packet reduced.json --out /private/recovered-run

recover verifies the artifact and both stream hashes before writing stdout.bin and stderr.bin; it refuses an existing destination. Its JSON receipt preserves the original exitCode, signal and captureComplete. The files can contain arbitrary bytes. A failed write may leave an incomplete destination directory; only a successful recovery receipt establishes delivery. Reduction prioritizes diagnostic blocks and reports omitted diagnostic lines. Use recovery when a diagnostic block does not fit. Neither successful reduction nor recovery turns a failed original command into a successful one.

Provider execution is an explicit operation and may incur usage or native tool activity. A profile fixes the protocol, model, authentication mode, working directory and, for native clients, executable and account home. No provider, model, authentication or API-spend fallback is performed.

{
"profiles": [
{
"id": "local-model", "provider": "ollama", "protocol": "OllamaChat",
"model": "your-installed-model", "authMode": "None",
"workingDirectory": "/absolute/checkout",
"endpoint": "http://localhost:11434"
}
],
"aliases": { "local": "local-model" }
}
Terminal window
bee providers inspect --profiles profiles.json --profile local
bee providers run --profiles profiles.json --profile local \
--context selection.json --prompt-file question.txt --budget 8192

Inspection checks profile shape only: runnable remains not_verified. It does not verify accepted native arguments, executable availability, authentication or model access. run prepares the local packet before invoking the chosen runtime once. Missing required context stops generation. The receipt contains source provenance, omissions and provider-reported usage separately from local estimates. Optional --session-out NEW_FILE stores private continuation state; resume with --session FILE under the identical profile binding. Session files contain conversation data and must remain private. Existing files are not overwritten. The profile’s maxInputBytes (default 1 MiB, maximum 16 MiB) also limits the complete serialized session file, including JSON escaping and its outer envelope, on both save and load. This is separate from the 256 KiB selection and profile manifest limit. A continuation that cannot be saved produces an explicit session error after the invocation; the actual model text, usage and call ID remain in the receipt and Bee does not retry the call. savedPath: null means no continuation file was successfully delivered. returnedWithSuccessfulTurn distinguishes a continuation accompanying a failed turn from a successful turn.

run also accepts --cache-dir DIR; its localCache.status receipt describes only local reduction reuse. A hit still invokes the chosen provider once and does not imply provider caching or lower provider usage. The run --budget limits its input context packet, not the model response or receipt.

Add --stream to print visible response text as the provider produces it. For scripts, add --json as well to receive one JSON event per line:

Terminal window
bee providers run --profiles profiles.json --profile openai-api \
--context selection.json --prompt-file question.txt --stream
bee providers run --profiles profiles.json --profile openai-api \
--context selection.json --prompt-file question.txt --stream --json

The JSON stream contains InvocationStarted, zero or more TextDelta events and InvocationFinished. Render each textDelta once. The final receipt contains status, usage and continuation metadata; its provider text is omitted to avoid rendering the same answer twice. Partial output is provisional: check the final receipt and process exit code before accepting the answer. A failed input check can finish without starting a provider invocation.

Without --stream, the existing single JSON receipt is unchanged. Streaming uses the selected profile’s timeout and output limits. Ctrl+C cancels local work; this does not guarantee that a remote provider stops generation or billing. Unsupported streaming protocols or native options return an explicit error; Bee does not split a completed response into simulated chunks. Use providers inspect to check the protocol’s advertised capability, then run it to verify your installed client and account.

Supported API streaming protocols are OpenAiResponses, OpenAiChatCompletions, AnthropicMessages, GeminiGenerateContent, GeminiInteractions and OllamaChat. Native streaming is implemented for ClaudeCode, GeminiCli and Codex. AntigravityCli and AntigravityInteractions currently return Unsupported for streaming.

Codex streaming uses the installed client’s app-server interface and requires NativeAccount authentication. It maps explicit --sandbox and -c/--config model_reasoning_effort=... settings; other native options that cannot be preserved by this transport are rejected before starting. It does not silently drop permissions or switch accounts/models. Normal non-streaming Codex calls continue to use exec.

API credentials use secretSource: {"kind":"environment","name":"VARIABLE"} or {"kind":"vault","name":"existing-secret"} together with authMode: "ApiKey". Values never belong in profiles or command arguments. Vault reads use the existing identity without initializing or rotating keys. API endpoints must use HTTPS, except explicit loopback endpoints. Native account profiles use authMode: "NativeAccount"; Codex, Claude Code and Gemini CLI require an explicit nativeHome. Account access, model entitlement and platform support require a successful run; an inspected profile is not acceptance evidence.

Aliases map names to these profiles. Shell aliases and functions are not evaluated. In particular, codex-external is a profile alias to the actual Codex binary plus its explicit native home, not an executable wrapper. Native client permission policies remain in force. The existing bee ask and bee init legacy configuration and gated ask --tools behavior remain available; the new provider workflow does not enable an additional model tool loop.

For an API profile, select a protocol that matches the service’s actual wire contract. This example references an existing environment credential:

{
"profiles": [{
"id": "openai-api", "provider": "openai", "protocol": "OpenAiResponses",
"model": "gpt-6", "authMode": "ApiKey",
"secretSource": { "kind": "environment", "name": "TOOL_OPENAI" },
"workingDirectory": "/absolute/checkout",
"endpoint": "https://api.openai.com/v1/",
"maxInputBytes": 1048576, "maxOutputBytes": 1048576,
"maxOutputTokens": 4096, "timeout": "00:05:00"
}]
}

Model access is account-specific. Other explicit API protocols are AnthropicMessages, GeminiInteractions, GeminiGenerateContent, AntigravityInteractions, OllamaChat and OpenAiChatCompletions. Managed AntigravityInteractions also requires managedAgent; that is an agent identity, while model is the actual requested model. API sessions use Microsoft Agent Framework. Streaming uses its streaming execution path for supported protocols. The framework tool loop remains unsupported; a lifecycle event alone is not a text delta.

A native Codex profile uses the actual executable and existing account home:

{
"profiles": [{
"id": "codex-account", "provider": "openai", "protocol": "Codex",
"model": "gpt-6", "authMode": "NativeAccount",
"workingDirectory": "/absolute/checkout",
"executable": "/absolute/path/to/codex",
"nativeHome": "/absolute/private/codex-home",
"arguments": ["--sandbox", "read-only", "--config", "model_reasoning_effort=\"xhigh\""]
}],
"aliases": { "codex-external": "codex-account" }
}

Native protocols are Codex, ClaudeCode, GeminiCli and AntigravityCli. The adapter owns model, authentication, output format and resume arguments; only a narrow verified set of additional flags is accepted. Do not put login, credential or model override arguments in arguments. Native trust and permission failures remain failures; Bee does not log in, change trust settings or switch to paid API authentication to get past them. Custom Antigravity CLI home selection is currently unsupported.

Claude Code’s default account storage has a distinct native keychain namespace. For its existing default account, explicitly select nativeHomeMode: "Default" with the actual current user’s <home>/.claude path as nativeHome:

{
"profiles": [{
"id": "claude-default-account", "provider": "anthropic", "protocol": "ClaudeCode",
"model": "your-entitled-model", "authMode": "NativeAccount",
"workingDirectory": "/absolute/checkout",
"executable": "/absolute/path/to/claude",
"nativeHome": "/absolute/your-home/.claude", "nativeHomeMode": "Default",
"arguments": ["--permission-mode", "plan", "--tools", ""]
}]
}

Bee verifies that explicit path against the current user’s default before unsetting the two Claude config-directory overrides in the child process. nativeHomeMode: "Explicit" remains the default and selects the override namespace, even if its path text equals the usual default. Bee never switches between these modes after an authentication failure. Default is currently supported only for Claude Code native-account profiles. Existing profiles without this field retain their profile binding.

Workers are explicit model calls with separate usage receipts. Their summaries are lossy; source hashes and ranges establish provenance, not semantic accuracy. No helper cost or failed call is excluded from a total-consumption comparison.

Terminal window
bee worker summarize --profiles profiles.json --profile local \
--context selection.json --prompt-file summary-request.txt \
--context-budget 8192 --budget 6000

--context-budget limits the selected input packet; --budget limits the whole worker JSON response including newline. Check context.complete, selectionComplete, omitted source lines/items and summaryOmittedBytes. Local token estimates exclude the worker instruction, framing, output and provider billing. A native summary additionally requires --allow-native-authority; its native client’s existing tools and write permissions remain active. It is not a Bee-enforced read-only sandbox. Managed-agent summaries (AntigravityInteractions) are currently rejected before invocation because their tool authority is not verified; the native authority flag does not enable them.

Generate a candidate with a tool-free API profile. Record the current target’s SHA-256 first, then pass that literal lowercase hash as TARGET_SHA:

Terminal window
shasum -a 256 src/Example.cs
bee worker generate --profiles profiles.json --profile local \
--context selection.json --prompt-file generation-request.txt \
--store /private/worker-artifacts --target src/Example.cs \
--expected-sha256 TARGET_SHA --budget 16384 --diff-budget 4096

The instruction file describes the desired replacement. The model must return one JSON object containing only a string content; Bee validates it, stores a private candidate and returns its manifest/hash plus a bounded diff excerpt. The target is unchanged. Inspect artifact.candidatePath and the complete candidate before applying it; the returned diff is not an executable patch. Native and managed-agent candidate generation are unsupported because their tool/write authority cannot currently be restricted by this operation.

Copy artifact.id and artifact.candidateSha256 from the receipt, then apply explicitly using the same original target hash:

Terminal window
bee worker apply --store /private/worker-artifacts --root /absolute/checkout \
--target src/Example.cs --expected-sha256 TARGET_SHA \
--artifact ARTIFACT_ID --candidate-sha256 CANDIDATE_SHA

For a new file, use --expected-sha256 absent during both generate and apply. Parent directories must already exist. Apply checks source/target/candidate hashes and refuses changed input. Snapshot checks plus atomic replacement are not a filesystem compare-and-swap. No model is called during apply. Candidate files are capped at 256 KiB; the CLI instruction file at 64 KiB; the diff at 16 KiB. Worker stdout budgets are capped at 1 MiB. If an after-call receipt cannot fit stdout, stderr explicitly retains the call and artifact reference outside that stdout budget; do not interpret empty stdout as zero model usage. Existing non-private artifact stores are refused on Unix; Windows store ACL privacy has not been independently established.

Terminal window
bee context claude-hook-config --root /absolute/checkout

This prints an opt-in Claude Code settings fragment; it does not install or edit any settings. Add it to the intended project settings only after inspecting it. The hook rejects an unbounded Read of a source-code file at least 32 KiB and directs the model to explicit context selection. It checks metadata only. It does not read or inject source text before native tool permissions are checked. Explicit offset/limit reads, documents and instruction files continue through the host’s normal permission flow. A routing failure leaves that flow intact. The command has a two-second deadline; the printed host timeout is also two seconds. The hook never invokes a provider or builds a graph.

Host Available path Current boundary
Claude Code Opt-in PreToolUse routing plus CLI/MCP packets Routing asks for a subsequent tool call; it does not automatically execute that call. Snippet generation currently targets POSIX shells.
Codex Explicit CLI/MCP packets Bee does not claim a general post-tool output replacement hook.
Hermes Explicit CLI/MCP packets Existing retained-context behavior is separate; no new global interception is installed.

Routing follows the Claude hook contract. The Codex hook contract permits observation and blocking, but does not establish Bee-wide result replacement. Native host configuration and a direct invocation test are separate from live model-driven host acceptance.