# SOPHIA Configuration Analysis

> **Date:** 2026-03-15  
> **Source:** Deep review of sophiaclaw-clean v0.1.9  
> **Focus:** Configuration system, agent capabilities, self-awareness, v0.1.9 features, integration points

---

## Executive Summary

SophiaClaw is a sophisticated AI agent platform with extensive customization capabilities. This analysis reveals a highly modular architecture supporting multiple LLM providers, rich tool ecosystems, governance frameworks, and emerging self-awareness features. The v0.1.9 release introduces significant enhancements including a background tasks sidebar (replacing the orchestrator), governance features, and improved UI/agent integration.

---

## 1. Configuration System Deep Dive

### 1.1 Configuration Architecture

**Config Files & Locations:**

```
~/.sophiaclaw/sophiaclaw.json          # Main user config
~/.sophiaclaw/agents/<id>/config.json  # Per-agent config
~/.sophiaclaw/credentials/             # API keys & secrets
~/.sophiaclaw/sessions/                # Session storage
~/.sophiaclaw/sophia/config.yaml       # Sophia governance config
```

**Config Loading Hierarchy (highest priority first):**

1. Runtime environment variables
2. Command-line flags
3. Session-specific overrides
4. Agent-specific config
5. User config (`~/.sophiaclaw/sophiaclaw.json`)
6. Default values from `src/config/defaults.ts`

### 1.2 Core Configuration Types

**SophiaClawConfig** (`src/config/types.sophiaclaw.ts`):

```typescript
type SophiaClawConfig = {
  meta?: { lastTouchedVersion?: string; lastTouchedAt?: string };
  auth?: AuthConfig; // API key profiles
  agents?: AgentsConfig; // Agent definitions
  models?: ModelsConfig; // Provider/model configuration
  tools?: ToolsConfig; // Tool policies & settings
  channels?: ChannelsConfig; // Messaging channels
  gateway?: GatewayConfig; // Gateway settings
  memory?: MemoryConfig; // Memory/RAG configuration
  skills?: SkillsConfig; // Skill management
  plugins?: PluginsConfig; // Plugin system
  cron?: CronConfig; // Scheduled tasks
  hooks?: HooksConfig; // Lifecycle hooks
  approvals?: ApprovalsConfig; // Approval gates
  session?: SessionConfig; // Session defaults
  logging?: LoggingConfig; // Logging configuration
  diagnostics?: DiagnosticsConfig; // Health/telemetry
  browser?: BrowserConfig; // Browser automation
  canvasHost?: CanvasHostConfig; // Canvas/A2UI settings
  ui?: {
    // UI customization
    seamColor?: string;
    assistant?: { name?: string; avatar?: string };
  };
  // ... and more
};
```

### 1.3 Agent Configuration

**Agent Defaults** (`src/config/types.agent-defaults.ts`):

| Setting                 | Type                                                           | Description                     |
| ----------------------- | -------------------------------------------------------------- | ------------------------------- |
| `model`                 | `AgentModelListConfig`                                         | Primary + fallback models       |
| `models`                | `Record<string, AgentModelEntryConfig>`                        | Full model catalog with aliases |
| `thinkingDefault`       | `"off" \| "minimal" \| "low" \| "medium" \| "high" \| "xhigh"` | Default reasoning level         |
| `verboseDefault`        | `"off" \| "on" \| "full"`                                      | Default verbosity               |
| `elevatedDefault`       | `"off" \| "on" \| "ask" \| "full"`                             | Default elevated permissions    |
| `blockStreamingDefault` | `"off" \| "on"`                                                | Streaming block replies         |
| `humanDelay`            | `HumanDelayConfig`                                             | Typing simulation               |
| `timeoutSeconds`        | `number`                                                       | Request timeout                 |
| `contextTokens`         | `number`                                                       | Context window size             |
| `maxConcurrent`         | `number`                                                       | Max parallel runs               |
| `contextPruning`        | `AgentContextPruningConfig`                                    | Auto-compaction settings        |
| `compaction`            | `AgentCompactionConfig`                                        | Summarization mode              |
| `memorySearch`          | `MemorySearchConfig`                                           | Vector memory settings          |
| `heartbeat`             | `HeartbeatConfig`                                              | Periodic check-in config        |
| `subagents`             | `SubagentDefaultsConfig`                                       | Sub-agent spawning rules        |
| `sandbox`               | `AgentSandboxConfig`                                           | Containerization settings       |

**Agent Definition** (`src/config/types.agents.ts`):

```typescript
type AgentConfig = {
  id: string; // Unique identifier
  default?: boolean; // Is default agent?
  name?: string; // Display name
  workspace?: string; // Working directory
  agentDir?: string; // Agent storage
  model?: AgentModelConfig; // Model selection
  skills?: string[]; // Allowed skills
  memorySearch?: MemorySearchConfig;
  humanDelay?: HumanDelayConfig;
  heartbeat?: HeartbeatConfig;
  identity?: IdentityConfig; // Personality/avatar
  groupChat?: GroupChatConfig; // Group behavior
  subagents?: SubagentConfig; // Spawning permissions
  sandbox?: AgentSandboxConfig; // Container config
  tools?: AgentToolsConfig; // Tool policies
};
```

### 1.4 Model Configuration

**Provider/Model Schema** (`src/config/types.models.ts`):

```typescript
type ModelsConfig = {
  providers?: Record<string, ProviderConfig>;
};

type ProviderConfig = {
  api?: "anthropic-messages" | "openai" | "ollama" | ...;
  baseUrl?: string;
  auth?: { profile?: string; apiKey?: string };
  models: ModelDefinitionConfig[];
};

type ModelDefinitionConfig = {
  id: string;                    // Model identifier
  name?: string;                 // Display name
  contextWindow?: number;        // Max context tokens
  maxTokens?: number;            // Max output tokens
  input?: ("text" | "image")[];  // Capabilities
  reasoning?: boolean;           // Supports reasoning
  cost?: {
    input: number;               // $ per 1M tokens
    output: number;
    cacheRead?: number;
    cacheWrite?: number;
  };
};
```

**Built-in Model Aliases** (`src/config/defaults.ts`):

```javascript
{
  opus: "anthropic/claude-opus-4-6",
  sonnet: "anthropic/claude-sonnet-4-6",
  gpt: "openai/gpt-5.2",
  "gpt-mini": "openai/gpt-5-mini",
  gemini: "google/gemini-3-pro-preview",
  "gemini-flash": "google/gemini-3-flash-preview",
}
```

### 1.5 Tools Configuration

**Tools Policy System** (`src/config/types.tools.ts`):

```typescript
type ToolsConfig = {
  profile?: ToolProfileId; // "minimal" | "coding" | "messaging" | "full"
  allow?: string[]; // Explicit allowlist
  alsoAllow?: string[]; // Additive allowlist
  deny?: string[]; // Blocked tools
  byProvider?: Record<string, ToolPolicyConfig>;

  // Tool-specific configs
  web?: {
    search?: WebSearchConfig;
    fetch?: WebFetchConfig;
  };
  media?: MediaToolsConfig;
  message?: MessageToolConfig;
  agentToAgent?: AgentToAgentConfig;
  sessions?: SessionsToolConfig;

  // Security & execution
  elevated?: ElevatedConfig;
  exec?: ExecToolConfig;
  fs?: FsToolsConfig;
  loopDetection?: ToolLoopDetectionConfig;
  subagents?: SubagentToolConfig;
  sandbox?: SandboxToolConfig;
};
```

**Exec Tool Security Levels** (`src/config/types.tools.ts`):

```typescript
type ExecToolConfig = {
  host?: "sandbox" | "gateway" | "node"; // Execution target
  security?: "deny" | "allowlist" | "full"; // Permission level
  ask?: "off" | "on-miss" | "always"; // Approval mode
  node?: string; // Default node binding
  safeBins?: string[]; // Pre-approved binaries
  backgroundMs?: number; // Auto-background threshold
  timeoutSec?: number; // Kill timeout
  notifyOnExit?: boolean; // Alert on completion
};
```

### 1.6 Environment Variable Integration

**Environment Substitution** (`src/config/env-substitution.ts`):

- Syntax: `${VAR_NAME}` or `${VAR_NAME:-default}`
- Supports: `$HOME`, `$USER`, custom env vars
- Scope: Any string value in config

**Shell Env Import** (`src/config/types.sophiaclaw.ts`):

```json
{
  "env": {
    "shellEnv": {
      "enabled": true,
      "timeoutMs": 15000
    },
    "vars": {
      "CUSTOM_API_KEY": "sk-..."
    }
  }
}
```

---

## 2. Agent Capabilities Analysis

### 2.1 Available Tools

**Core Tools** (`src/agents/tools/`):

| Tool               | File                       | Description                      |
| ------------------ | -------------------------- | -------------------------------- |
| `read`             | `pi-tools.read.ts`         | Read files with workspace guards |
| `write`            | `pi-tools.ts`              | Create/overwrite files           |
| `edit`             | `pi-tools.ts`              | Surgical text replacement        |
| `apply_patch`      | `pi-tools.ts`              | Multi-file patches (OpenAI)      |
| `grep`             | `pi-tools.ts`              | Content search                   |
| `find`             | `pi-tools.ts`              | File discovery                   |
| `ls`               | `pi-tools.ts`              | Directory listing                |
| `exec`             | `bash-tools.exec.ts`       | Shell execution with PTY         |
| `process`          | `bash-tools.process.ts`    | Background process mgmt          |
| `web_search`       | `web-search.ts`            | Brave/Perplexity/Grok search     |
| `web_fetch`        | `web-fetch.ts`             | URL content extraction           |
| `browser`          | `browser-tool.ts`          | Browser automation               |
| `canvas`           | `canvas-tool.ts`           | A2UI canvas control              |
| `nodes`            | `nodes-tool.ts`            | Paired device control            |
| `cron`             | `cron-tool.ts`             | Job scheduling                   |
| `message`          | `message-tool.ts`          | Cross-channel messaging          |
| `gateway`          | `gateway-tool.ts`          | Gateway control                  |
| `agents_list`      | `agents-list-tool.ts`      | List available agents            |
| `sessions_list`    | `sessions-list-tool.ts`    | Session enumeration              |
| `sessions_history` | `sessions-history-tool.ts` | Fetch session logs               |
| `sessions_send`    | `sessions-send-tool.ts`    | A2A messaging                    |
| `sessions_spawn`   | `sessions-spawn-tool.ts`   | Sub-agent creation               |
| `subagents`        | `subagents-tool.ts`        | Sub-agent orchestration          |
| `session_status`   | `session-status-tool.ts`   | Status display                   |
| `image`            | `image-tool.ts`            | Vision analysis                  |
| `memory_search`    | `memory-tool.ts`           | Vector memory retrieval          |
| `memory_get`       | `memory-tool.ts`           | Direct memory access             |
| `tts`              | `tts-tool.ts`              | Text-to-speech                   |

### 2.2 Tool Profiles

**Predefined Profiles** (`src/config/types.tools.ts`):

| Profile     | Included Tools                                                     |
| ----------- | ------------------------------------------------------------------ |
| `minimal`   | `read`, `write`, `edit`, `exec`                                    |
| `coding`    | All file ops + `web_search`, `web_fetch`, `browser`, `apply_patch` |
| `messaging` | `message`, `sessions_send`, `sessions_spawn` + basic file ops      |
| `full`      | All available tools                                                |

### 2.3 Permissions Model

**Permission Hierarchy** (most restrictive wins):

1. **Global `tools.deny`** - Universally blocked
2. **Global `tools.allow`** - Explicitly allowed (if set)
3. **Profile allowlist** - Base set from profile
4. **Agent `tools.deny`** - Agent-specific blocks
5. **Agent `tools.allow`** - Agent-specific additions
6. **Runtime overrides** - Session-level changes

**Elevated Mode** (`src/config/types.tools.ts`):

```typescript
type ElevatedConfig = {
  enabled?: boolean;
  allowFrom?: AgentElevatedAllowFromConfig; // Per-provider allowlists
};
```

**Sender-Based Policy** (`src/config/types.tools.ts`):

```typescript
type GroupToolPolicyBySenderConfig = {
  "id:<senderId>"?: GroupToolPolicyConfig;
  "e164:<phone>"?: GroupToolPolicyConfig;
  "username:<handle>"?: GroupToolPolicyConfig;
  "name:<display>"?: GroupToolPolicyConfig;
  "*"?: GroupToolPolicyConfig; // Wildcard
};
```

### 2.4 Sub-Agent System

**Spawn Configuration** (`src/config/types.agent-defaults.ts`):

```typescript
type SubagentDefaultsConfig = {
  maxConcurrent?: number; // Default: 1
  maxSpawnDepth?: number; // Default: 1 (no nesting)
  maxChildrenPerAgent?: number; // Default: 5
  archiveAfterMinutes?: number; // Default: 60
  model?: AgentModelConfig; // Sub-agent model
  thinking?: string; // Default thinking level
  announceTimeoutMs?: number; // Gateway timeout
};
```

**Registry Features** (`src/agents/subagent-registry.ts`):

- Persistent state across gateway restarts
- Lifecycle event hooks
- Completion announcements
- Kill/steer capabilities
- Depth tracking to prevent loops
- Outcome tracking (complete/error/killed)

---

## 3. Self-Awareness Features

### 3.1 Runtime Context Injection

**System Prompt Runtime Line** (`src/agents/system-prompt.ts`):

```
Runtime: agent=main | host=Shawn's Mac Mini | os=Darwin 25.3.0 (arm64) |
node=v24.13.1 | model=kimi-coding/k2p5 | default_model=kimi-coding/k2p5 |
shell=zsh | channel=webchat | capabilities=none | thinking=low
```

**Injected Parameters**:

- `agent`: Agent ID
- `host`: Machine hostname
- `os`: Operating system
- `arch`: CPU architecture
- `node`: Node.js version
- `model`: Current LLM
- `default_model`: Fallback LLM
- `shell`: Default shell
- `channel`: Current channel (telegram, discord, etc.)
- `capabilities`: Enabled features
- `thinking`: Current reasoning level

### 3.2 Session Metadata

**Session Context** (`src/agents/pi-embedded-runner/types.ts`):

```typescript
type EmbeddedPiAgentMeta = {
  sessionId: string;
  provider: string;
  model: string;
  compactionCount?: number;
  promptTokens?: number;
  usage?: {
    input?: number;
    output?: number;
    cacheRead?: number;
    cacheWrite?: number;
    total?: number;
  };
  lastCallUsage?: { ... };  // Per-call metrics
};
```

### 3.3 Context Window Management

**Context Tokens Lookup** (`src/agents/context.ts`):

- Discovers context windows from model registry
- Applies configured overrides
- Best-effort caching for performance
- Fail-safe: prefers smaller windows on conflict

### 3.4 Tool Self-Reporting

**Tool Display Metadata** (`src/agents/tool-display.ts`):

- Human-readable tool descriptions
- Category grouping
- Usage examples
- Dynamic schema documentation

### 3.5 Session Introspection

**Available via `session_status` tool**:

- Current usage statistics
- Active time elapsed
- Reasoning/Verbose/Elevated status
- Model override info

---

## 4. New v0.1.9 Capabilities

### 4.1 Background Tasks Sidebar

**Purpose:** Replace the complex orchestrator system with a simpler subagent-based approach.

**Implementation** (`docs/phase2/08-background-tasks-sidebar.md`):

**Removed:**

- `src/orchestrator/router.ts` - Intent classification
- Orchestrator config section
- LLM-based routing logic

**Added:**

- Hybrid sidebar UI (`ui/src/ui/controllers/tasks.ts`)
- Tabbed interface: Tool Output | Tasks
- Auto-open on subagent spawn
- Live status tracking
- View/Kill/Dismiss actions

**UI State Management**:

```typescript
type TasksState = {
  client: GatewayBrowserClient | null;
  connected: boolean;
  taskSessions: SessionsListResult | null;
  taskSessionsPrevCount: number;
  sidebarTab: "tool" | "tasks";
  sidebarOpen: boolean;
  tab: string;
};
```

### 4.2 Governance Framework

**Governance Controller** (`ui/src/ui/controllers/governance.ts`):

```typescript
type GovernanceSettings = {
  enabled: boolean;
  securityLevel: "relaxed" | "standard" | "strict";
  autoApproveLowRisk: boolean;
  requireApprovalFor: string[];
  denyList: string[];
  rules: GovernanceRule[];
  skillPermissions: GovernanceSkillPermission[];
  terminalPermissions: GovernanceTerminalPermission;
};

type GovernanceRule = {
  id: string;
  name: string;
  description: string;
  pattern: string;
  enforcement: "allow" | "require_approval" | "deny";
  scope: "global" | "agent" | "session";
  createdAt: string;
  updatedAt: string;
};
```

**Features:**

- Rule-based policy enforcement
- Skill-level permissions
- Terminal command allowlists/blocklists
- Approval gates for sensitive operations

### 4.3 Sophia Governance Config

**Config Location:** `.sophia/config.yaml`

```yaml
sophia:
  version: 1.0.0
  initialized: 2026-03-09T17:26:56.940Z
project:
  name: sophiaclaw
  tech_stack:
    language: typescript
    framework: express
    database: sqlite
    package_manager: pnpm
    test_runner: vitest
agents:
  detected:
    - name: claude-code
      config_file: CLAUDE.md
      status: active
    - name: opencode
      config_file: AGENTS.md
      status: active
user:
  experience_level: beginner
  governance_level: community
session:
  auto_detect: true
  stale_timeout_minutes: 30
  claim_mode: warn
policies:
  enabled:
    - security
    - quality
  strictness: strict
teaching:
  enabled: true
  show_explanations: true
  first_time_hints: true
health:
  auto_score: true
  score_on_commit: false
```

**Features:**

- Agent-specific rules
- Quality gates (no console.log, no 'any' type)
- Session management commands
- Memory system for patterns/corrections

---

## 5. Integration Points

### 5.1 UI-Gateway Integration

**Control UI** (`src/gateway/control-ui.ts`):

- Serves web-based configuration interface
- Avatar resolution system
- Security headers (CSP, framing, etc.)
- Static asset serving with SPA fallback

**Bootstrap Config** (`src/gateway/control-ui-contract.ts`):

```typescript
type ControlUiBootstrapConfig = {
  gatewayBaseUrl: string;
  agentId?: string;
  sessionKey?: string;
  assistant?: {
    name?: string;
    avatarUrl?: string | null;
  };
  flags?: {
    enableAgentSelect?: boolean;
    enableSessions?: boolean;
    enableMemory?: boolean;
    enableSkills?: boolean;
  };
};
```

### 5.2 Gateway-Agent Integration

**Agent Events** (`src/infra/agent-events.ts`):

- Event bus for agent lifecycle
- Message streaming
- Tool result propagation
- Session state changes

**Gateway Call** (`src/gateway/call.ts`):

- HTTP API for external control
- Channel management
- Status queries
- Configuration reloads

### 5.3 Channel Integration

**Supported Channels** (built-in + extensions):

- Telegram (`src/telegram/`)
- Discord (`src/discord/`)
- Slack (`src/slack/`)
- Signal (`src/signal/`)
- iMessage (`src/imessage/`)
- WhatsApp Web (`src/web/`)
- Web UI (built-in)
- MSTeams (extension)
- Matrix (extension)
- Zalo (extension)
- Voice Call (extension)

**Channel Capabilities** (`src/config/channel-capabilities.ts`):

```typescript
type ChannelCapabilities = {
  inlineButtons?: "dm" | "group" | "all" | "allowlist";
  replyTag?: boolean;
  typingIndicator?: boolean;
  mediaUpload?: boolean;
  mediaDownload?: boolean;
  voice?: boolean;
};
```

### 5.4 Plugin System

**Plugin SDK** (`src/plugin-sdk/`):

```typescript
// Tool registration
registerTool(name: string, handler: ToolHandler): void;

// Channel registration
registerChannel(config: ChannelConfig): void;

// Hook registration
onHook(event: string, handler: HookHandler): void;
```

**Plugin Loading** (`src/plugins/`):

- npm package resolution
- Local directory loading
- Hot-reload support
- Dependency injection

### 5.5 Memory System

**Vector Memory** (`src/config/types.tools.ts`):

```typescript
type MemorySearchConfig = {
  enabled?: boolean;
  sources?: Array<"memory" | "sessions">;
  provider?: "openai" | "gemini" | "local" | "voyage" | "mistral";
  model?: string;
  local?: { modelPath?: string; modelCacheDir?: string };
  query?: {
    maxResults?: number;
    minScore?: number;
    hybrid?: { enabled?: boolean; vectorWeight?: number; textWeight?: number };
  };
};
```

**PageIndex** (RAG for large docs):

- Token threshold: 4000
- Max tree depth: 6
- Structure extraction: gemini-1.5-flash
- Summary generation: gemini-1.5-flash

### 5.6 Skills System

**Skill Structure** (`src/agents/skills/`):

```
skills/
├── SKILL.md           # Documentation
├── config.json        # Metadata
├── install.sh         # Setup script
└── ...
```

**Workspace Skills**:

- Auto-discovered from `./.sophiaclaw/skills/`
- Version controlled with project
- Override bundled skills

---

## 6. Security Architecture

### 6.1 Secrets Management

**Storage**:

- `~/.sophiaclaw/credentials/` (600 permissions)
- Environment variables
- 1Password integration (for maintainers)

**Redaction** (`src/config/redact-snapshot.ts`):

- Automatic secret detection
- Config snapshot redaction
- Log sanitization

### 6.2 Approval Gates

**Exec Approval** (`src/gateway/exec-approval.ts`):

- Destructive operation confirmation
- Configurable thresholds
- Multi-level approval chains

### 6.3 Sandbox System

**Container Modes**:

- `docker`: Full containerization
- `podman`: Rootless containers
- `none`: Host execution (restricted)

**Workspace Mounting**:

- Read-only or read-write
- Path validation
- Escape prevention

---

## 7. Configuration Best Practices

### 7.1 Agent-Specific Overrides

```json
{
  "agents": {
    "list": [
      {
        "id": "sophia",
        "name": "SOPHIA",
        "model": {
          "primary": "kimi-coding/k2p5"
        },
        "tools": {
          "profile": "full",
          "alsoAllow": ["custom_tool"]
        },
        "memorySearch": {
          "enabled": true,
          "sources": ["memory", "sessions"]
        },
        "heartbeat": {
          "every": "30m",
          "target": "last"
        }
      }
    ]
  }
}
```

### 7.2 Multi-Model Failover

```json
{
  "agents": {
    "defaults": {
      "model": {
        "primary": "anthropic/claude-sonnet-4-6",
        "fallbacks": ["openai/gpt-5.2", "google/gemini-3-pro-preview"]
      }
    }
  }
}
```

### 7.3 Tool Policy by Provider

```json
{
  "tools": {
    "byProvider": {
      "anthropic": {
        "allow": ["read", "write", "edit", "browser"]
      },
      "openai": {
        "allow": ["read", "write", "apply_patch"]
      }
    }
  }
}
```

### 7.4 Channel-Specific Behavior

```json
{
  "channels": {
    "telegram": {
      "dmPolicy": "owner",
      "groupPolicy": "mention"
    },
    "discord": {
      "dmPolicy": "owner",
      "guildPolicy": "mention"
    }
  }
}
```

---

## 8. Summary Matrix

| Feature         | Config Path                               | Default                       | Notes                          |
| --------------- | ----------------------------------------- | ----------------------------- | ------------------------------ |
| Default Model   | `agents.defaults.model.primary`           | `anthropic/claude-sonnet-4-6` | Override per-agent             |
| Tool Profile    | `tools.profile`                           | `full`                        | `minimal`/`coding`/`messaging` |
| Exec Security   | `tools.exec.security`                     | `deny`                        | Use `allowlist` for safety     |
| Sub-agent Depth | `agents.defaults.subagents.maxSpawnDepth` | `1`                           | Increase for nested tasks      |
| Heartbeat       | `agents.defaults.heartbeat.every`         | `30m`                         | Set `none` to disable          |
| Context Pruning | `agents.defaults.contextPruning.mode`     | `cache-ttl`                   | `off` to disable               |
| Compaction      | `agents.defaults.compaction.mode`         | `safeguard`                   | Preserves context              |
| Memory Search   | `tools.memorySearch.enabled`              | `true`                        | Requires embedding provider    |
| Sandbox         | `agents.defaults.sandbox.mode`            | `none`                        | `docker` for isolation         |
| Block Streaming | `agents.defaults.blockStreamingDefault`   | `off`                         | `on` for real-time             |

---

_This analysis is current as of sophiaclaw-clean v0.1.9 (2026-03-15)_
