# Xigua Agent Configuration Reference

This reference describes the persisted JSON configuration loaded from `~/.xigua-agent/config.json`.
Use `XIGUA_RUNTIME_HOME_DIR` to move the runtime home; the effective file is `${XIGUA_RUNTIME_HOME_DIR}/config.json`.

The loader is `packages/core/src/config/loadAppConfig.ts`; type definitions are in `packages/core/src/types.ts`.
The loader fills missing values from defaults and normalizes invalid or legacy values. Unknown fields should be preserved by editors, but they may not be used by the current version.

## Minimal Safe Baseline

This is an example only. It contains no real credentials.

```json
{
  "providers": {
    "default": "default",
    "items": [
      {
        "name": "default",
        "type": "openai",
        "enabled": true,
        "apiKeyEnv": "OPENAI_API_KEY",
        "defaultModel": "gpt-4.1-mini",
        "models": [
          {
            "id": "gpt-4.1-mini",
            "enabled": true,
            "supportsTools": true,
            "supportsImages": false
          }
        ]
      }
    ]
  },
  "permissions": {
    "mode": "ask",
    "allowRules": [],
    "denyRules": []
  },
  "compatibility": {
    "loadClaudePaths": false
  }
}
```

Do not replace an existing configuration with this example. Edit only the requested field.

## Top-Level Domains

| Path | Purpose | Default / important behavior |
|---|---|---|
| `providers` | Main model providers, models, image fallback, and failover | Default provider is `default`; default model is `gpt-4.1-mini` |
| `webSearch` | Web search provider registry | Built-in default is DuckDuckGo |
| `modelRouting` | Enables model-routing behavior | `enabled: false` |
| `gateway` | WebSocket/API gateway listener | Disabled by default, `127.0.0.1:19477` |
| `bridgePlugins` | Optional bridge plugin registry | `soul-bridge-plugin` disabled by default |
| `web` | Web console listener and gateway connection | Enabled by default, `127.0.0.1:19337` |
| `tasks` | Subagent/task concurrency and budgets | Uses task manager defaults |
| `cron` | Scheduler, persistence, missed runs, and jitter | Enabled; one concurrent run |
| `busyMessages` | Behavior when a session is already processing | Queue-oriented defaults |
| `permissions` | Tool permission mode and rules | `ask`, with empty allow/deny lists |
| `behavior` | Default behavior mode and lite mode | `chat` |
| `ui` | TUI display preferences | Timestamps off; system messages on |
| `compatibility` | Claude path compatibility loading | `loadClaudePaths: true` by default |
| `skills` | Per-skill enable overrides | Empty override map |
| `mcpServers` | MCP server definitions | Empty list |
| `onboarding` | Onboarding check timestamps and hash | Runtime-maintained state; normally do not hand-edit |

## providers

### Registry

- `providers.default` (`string`): provider name used for normal model resolution. It must match an entry in `providers.items`; normalization falls back to the first provider if it does not.
- `providers.imageModel` (`object|null`): optional image-understanding fallback with `provider` and `model` strings. It is used when the active model cannot understand images.
- `providers.fallbackModels` (`array`): ordered `{ provider, model }` candidates for failover. Empty or malformed entries are discarded during normalization.
- `providers.items` (`array`): provider definitions.

### Provider

- `name` (`string`): stable provider identifier referenced by `default`, `imageModel`, and fallback entries.
- `type` (`"openai" | "openai-compatible" | "codex"`): adapter type.
- `enabled` (`boolean`): whether the provider can be selected.
- `apiKey` (`string`, sensitive): inline credential. Avoid this field; use `apiKeyEnv`.
- `apiKeyEnv` (`string`): environment variable containing the credential.
- `baseURL` (`string`): API base URL for OpenAI-compatible providers.
- `headers` (`object`): additional HTTP headers. Treat values as sensitive unless known otherwise.
- `codexAuth` (`object`): Codex authentication paths and refresh behavior.
  - `authFile`: optional auth file path.
  - `configFile`: optional config file path.
  - `refreshSkewSeconds`: refresh lead time in seconds.
- `defaultModel` (`string`): model id selected when this provider is active.
- `models` (`array`): model capabilities and limits.
- `dsmlToolCalls` (`boolean`): provider-level compatibility switch for DSML tool-call formatting.

### Model

- `id` (`string`): exact provider model id sent to the API.
- `enabled` (`boolean`): whether this model is selectable.
- `displayName` (`string`): UI label; does not change the API id.
- `contextWindow` (`number`): advertised input context capacity.
- `maxOutputTokens` (`number`): advertised output limit.
- `supportsTools` (`boolean`): whether tool calls are supported.
- `supportsImages` (`boolean`): whether the model accepts image input. Required for a configured `providers.imageModel`.
- `reasoning` (`boolean`): whether reasoning controls are applicable.
- `supportedThinkingLevels` (`array`): values from `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`.
- `defaultLevel` (`string|null`): this model's default thinking level. Use `null` or omit it to use the model capability fallback.
- `maxBudgetTokens` (`number|null`): this model's optional thinking-budget ceiling for dialects that support separate thinking budgets.
- `dsmlToolCalls` (`boolean`): model-level DSML tool-call compatibility override.
- `pricing` (`object`): optional custom pricing in USD per million tokens.
  - `promptUsdPerMillionTokens` (`number`)
  - `completionUsdPerMillionTokens` (`number`)

Example without a credential:

```json
{
  "providers": {
    "default": "cas",
    "imageModel": {
      "provider": "cas",
      "model": "gpt-5.6-luna"
    },
    "items": [
      {
        "name": "cas",
        "type": "openai-compatible",
        "enabled": true,
        "apiKeyEnv": "CAS_API_KEY",
        "baseURL": "https://example.invalid/v1",
        "defaultModel": "gpt-5.6-luna",
        "models": [
          {
            "id": "gpt-5.6-luna",
            "enabled": true,
            "supportsTools": true,
            "supportsImages": true,
            "reasoning": true,
            "supportedThinkingLevels": ["off", "low", "medium", "high"],
            "defaultLevel": "medium",
            "maxBudgetTokens": 16384
          }
        ]
      }
    ]
  }
}
```

Risks: a wrong provider/model reference causes resolution failure; an enabled model without valid credentials fails at runtime; inline keys can leak through backups, logs, or reports.

## webSearch

- `default` (`string`): selected search provider name.
- `items` (`array`): provider definitions.
  - `name`: stable provider name.
  - `kind`: implementation kind, such as `duckduckgo`.
  - `enabled`: whether it is selectable.
  - `apiKey` / `apiKeyEnv`: optional provider credential; prefer the environment form.
  - `baseURL`: optional endpoint override.
  - `headers`: optional request headers.
  - `defaultMaxResults`: default result count.

Risk: changing endpoint or headers can send queries to an unintended service.

## modelRouting and thinking

- `modelRouting.enabled` (`boolean`): enables model-routing logic. It does not itself change provider credentials.
- Thinking policy belongs to the selected `providers.items[].models[]` entry: use its `supportedThinkingLevels`, `defaultLevel`, and `maxBudgetTokens` fields described above.
- `ui.showReasoning` (`boolean`): show reasoning content where supported; it affects presentation only, not the level sent to the model.

Risk: high per-model defaults and budgets increase latency and cost; unsupported levels are normalized toward the model's supported set.

## gateway and web

### gateway

- `enabled`: start the gateway listener.
- `host`: bind address. `0.0.0.0` exposes it on all interfaces.
- `port`: TCP port.
- `authToken`: inline gateway token; avoid it.
- `authTokenEnv`: environment variable containing the gateway token.

### web

- `enabled`: start the web console.
- `host`: web bind address.
- `port`: web console port.
- `gatewayUrl`: WebSocket URL used by the console.
- `gatewayAuthToken`: inline token; avoid it.
- `gatewayAuthTokenEnv`: environment variable containing the token.

Security: binding gateway or web to `0.0.0.0` without authentication exposes control surfaces to the network.

## bridgePlugins

- `entries` (`object`): map from plugin name to entry.
- Each entry has `enabled`, `module`, and `options`.
- `module` is the runtime module path.
- `options` is plugin-specific and may contain URLs, user ids, protocol versions, retry settings, and token environment variable names.

Keep bridge plugins disabled unless needed. Validate module paths and use token environment variables rather than token values.

## tasks

- `maxConcurrentTasks` (`positive integer`): maximum concurrent task executions.
- `timeoutMs` (`positive integer`): task timeout.
- `maxTurns` (`positive integer`): maximum turns per task.

Higher limits consume more provider quota and local resources. Normalization replaces non-positive values with defaults.

## cron

- `enabled`: enable scheduling.
- `storePath`: optional custom cron store path.
- `maxConcurrentRuns` (`positive integer`): concurrent scheduled runs.
- `defaultTimezone`: optional timezone used by schedules.
- `minEveryMs` (`positive integer`): minimum interval for recurring schedules; default is `60000`.
- `runLog.maxBytes`: maximum run-log size; default is `2000000`.
- `runLog.keepLines`: retained run-log lines; default is `2000`.
- `missedPolicy`: `skip`, `ask`, or `run` when a run is missed.
- `jitter.enabled`: add scheduling jitter.
- `jitter.maxMs`: maximum jitter in milliseconds; must be non-negative.

Risk: `run` can execute stale work after downtime; broad concurrency or short intervals can cause provider cost spikes.

## busyMessages

This domain controls messages arriving while a session is busy.

- `enabled`: enable busy-message handling.
- `defaultMode`: `queue`, `collect`, `steer`, `btw`, or `reject`.
- `surfaceDefaults`: default mode for `tui`, `web`, `gateway`, and `cron`.
- `queue.maxItems`: queue capacity.
- `queue.maxCharsPerItem`: per-message character cap.
- `queue.overflow`: `reject` or `drop-oldest`.
- `queue.autoDrain`: automatically process queued messages; currently expected to be `true`.
- `collect.debounceMs`: collection debounce window.
- `collect.maxItems`: maximum collected messages.
- `collect.maxChars`: collected character cap.
- `collect.overflow`: `reject`, `queue`, or `drop-oldest`.
- `steer.fallback`: `queue`, `collect`, or `reject` if steering cannot apply.
- `steer.requireExpectedTurnId`: require an expected turn identity.
- `btw.enabled`: currently expected to be `false` in the normalized policy.

Risk: large limits increase memory and prompt size; `steer` can alter an in-flight interaction and should be used deliberately.

## permissions

- `mode`: `ask`, `auto`, `bypass`, or `full-access`.
- `allowRules`: tool/path rules explicitly allowed.
- `denyRules`: tool/path rules explicitly denied.

`full-access` and `bypass` reduce safety boundaries. Use the narrowest mode suitable for the task. A legacy `plan` value is migrated to behavior `plan` with permission mode `auto`.

## behavior

- `defaultMode`: `chat`, `lite`, or `plan`.
- `modes.lite.description`: UI/system description.
- `modes.lite.tools.enabled`: explicitly enabled tools.
- `modes.lite.tools.defaultDisabled`: tools disabled by default.
- `modes.lite.tools.blocked`: tools that cannot be enabled.
- `modes.lite.tools.allowMcp`, `allowWeb`, `allowAgent`, `allowSkills`: capability gates.
- `modes.lite.skills.enabled`: enable skills in lite mode.
- `modes.lite.skills.allowlist`: optional skill slug allowlist; `null` means no list restriction.
- `modes.lite.skills.autoTrigger`: allow automatic skill triggering.
- `modes.lite.skills.lazyLoad`: defer skill loading.
- `modes.lite.memory.recentMessages`: recent-message count.
- `includeSessionSummary`, `includeSessionMemory`, `includeDurableMemory`: memory inclusion switches.
- `relevantMemoryLimit`: relevant-memory result limit.
- `persistence.persistDeltas`: persist incremental deltas.
- `persistence.persistFinalOnly`: persist final output only.

Risk: enabling tools, agents, skills, MCP, or web in lite mode expands its authority and may defeat the intended low-latency/safety profile.

## ui, compatibility, and skills

### ui

- `showTimestamps`: show message timestamps.
- `showSystemMessages`: show system messages in the UI.

### compatibility

- `loadClaudePaths`: load Claude-compatible agents and skills from Claude paths. Default is `true`; set `false` to exclude them.

Disabling this can prevent incompatible or malformed Claude files from breaking startup, but removes those resources from discovery.

### skills

- `entries.<slug>.enabled`: per-skill enable override.
- Use the exact skill slug, not its display name.

## mcpServers

`mcpServers` is an array of MCP server definitions. The exact connection fields are server-type-specific; inspect `McpServerConfig` in `packages/core/src/types.ts` and the MCP integration code before editing. Treat command, URL, headers, and environment values as executable or sensitive configuration.

## onboarding

- `lastSuccessfulCheckAt`: last successful onboarding check timestamp.
- `lastFailedCheckAt`: last failed check timestamp.
- `lastSkippedAt`: last skipped check timestamp.
- `skipSilenceHours`: quiet period after skipping.
- `lastConfigHash`: internal config fingerprint.

These are runtime-maintained bookkeeping fields. Do not edit them for ordinary provider or behavior changes.

## Edit and Verification Examples

Set Claude compatibility loading off:

```json
"compatibility": {
  "loadClaudePaths": false
}
```

Set an image fallback:

```json
"providers": {
  "imageModel": {
    "provider": "cas",
    "model": "gpt-5.6-luna"
  }
}
```

After editing:

```bash
node -e "const c=require(process.env.USERPROFILE+'/.xigua-agent/config.json'); console.log(c.providers?.imageModel)"
```

On Windows PowerShell, use `$env:USERPROFILE`; when `XIGUA_RUNTIME_HOME_DIR` is set, inspect that directory instead. Restart xigua unless the relevant source path explicitly supports live reload.

## Maintenance Note

This reference is versioned with the source. When adding a config field, update both `packages/core/src/types.ts`/defaults and this document. Do not add real API keys, tokens, passwords, or private endpoints to examples.
