En/01 Telemetry And Privacy
Telemetry & Privacy Analysis
Based on publicly available online references and community discussions on Claude Code v2.1.88.
Overview
Claude Code implements a two-tier analytics pipeline that collects extensive environment and usage metadata. While there is no evidence of keylogging or user code exfiltration, the breadth of collection and inability to fully opt out raises legitimate privacy concerns.
Data Pipeline Architecture
First-Party Logging (1P)
- Endpoint: https://api.anthropic.com/api/event_logging/batch
- Protocol: OpenTelemetry with Protocol Buffers
- Batch size: Up to 200 events per batch, flushed every 10 seconds
- Retry: Quadratic backoff, up to 8 attempts, disk-persisted for durability
- Storage: Failed events saved to ~/.claude/telemetry/
Source: src/services/analytics/firstPartyEventLoggingExporter.ts
Third-Party Logging (Datadog)
- Endpoint: https://http-intake.logs.us5.datadoghq.com/api/v2/logs
- Scope: Limited to 64 pre-approved event types
- Token: pubbbf48e6d78dae54bceaa4acf463299bf
Source: src/services/analytics/datadog.ts
What Is Collected
Environment Fingerprint
Every event carries this metadata (src/services/analytics/metadata.ts:417-452):
- platform, platformRaw, arch, nodeVersion
- terminal type
- installed package managers and runtimes
- CI/CD detection, GitHub Actions metadata
- WSL version, Linux distro, kernel version
- VCS (version control system) type
- Claude Code version and build time
- deployment environmentProcess Metrics (metadata.ts:457-467)
- uptime, rss, heapTotal, heapUsed
- CPU usage and percentage
- memory arrays and external allocationsUser Tracking (metadata.ts:472-496)
- model in use
- session ID, user ID, device ID
- account UUID, organization UUID
- subscription tier (max, pro, enterprise, team)
- repository remote URL hash (SHA256, first 16 chars)
- agent type, team name, parent session IDTool Input Logging
Tool inputs are truncated by default:
- Strings: truncated at 512 chars, displayed as 128 + ellipsis
- JSON: limited to 4,096 chars
- Arrays: max 20 items
- Nested objects: max 2 levels deepSource: metadata.ts:236-241
However, when OTEL_LOG_TOOL_DETAILS=1 is set, full tool inputs are logged.
Source: metadata.ts:86-88
File Extension Tracking
Bash commands involving rm, mv, cp, touch, mkdir, chmod, chown, cat, head, tail, sort, stat, diff, wc, grep, rg, sed have their file arguments' extensions extracted and logged.
Source: metadata.ts:340-412
The Opt-Out Problem
The first-party logging pipeline cannot be disabled for direct Anthropic API users.
// src/services/analytics/firstPartyEventLogger.ts:141-144
export function is1PEventLoggingEnabled(): boolean {
return !isAnalyticsDisabled()
}isAnalyticsDisabled() returns true only for:
- Test environments
- Third-party cloud providers (Bedrock, Vertex)
- Global telemetry opt-out (not exposed in settings UI)
There is no user-facing setting to disable first-party event logging.
GrowthBook A/B Testing
Users are assigned to experiment groups via GrowthBook without explicit consent. The system sends user attributes including:
- id, sessionId, deviceID
- platform, organizationUUID, subscriptionTypeSource: src/services/analytics/growthbook.ts
Key Takeaways
1. Volume: Hundreds of events per session are collected
2. No opt-out: First-party logging cannot be disabled by direct API users
3. Persistence: Failed events are saved to disk and retried aggressively
4. Third-party sharing: Data flows to Datadog
5. Tool detail backdoor: OTEL_LOG_TOOL_DETAILS=1 enables full input logging
6. Repository fingerprinting: Repo URLs are hashed and sent for server-side correlation
---
En/02 Hidden Features And Codenames
Hidden Features & Model Codenames
Based on publicly available online references and community discussions on Claude Code v2.1.88.
Model Codename System
Anthropic uses animal names as internal model codenames. These are aggressively protected from leaking into external builds.
Known Codenames
| Codename | Role | Evidence |
|----------|------|----------|
| Tengu (天狗) | Product/telemetry prefix, possibly a model | Used as tengu_* prefix for all 250+ analytics events and feature flags |
| Capybara | Sonnet-series model, currently at v8 | capybara-v2-fast[1m], prompt patches for v8 behavior issues |
| Fennec (耳廓狐) | Predecessor to Opus 4.6 | Migration: fennec-latest → opus |
| Numbat (袋食蚁兽) | Next model launch | Comment: "Remove this section when we launch numbat" |
Codename Protection
The undercover mode explicitly lists protected codenames:
// src/utils/undercover.ts:48-49
NEVER include in commit messages or PR descriptions:
- Internal model codenames (animal names like Capybara, Tengu, etc.)
- Unreleased model version numbers (e.g., opus-4-7, sonnet-4-8)The build system uses scripts/excluded-strings.txt to scan for leaked codenames. Buddy system species are encoded via String.fromCharCode() to avoid triggering the canary:
// src/buddy/types.ts:10-13
// One species name collides with a model-codename canary in excluded-strings.txt.
// The check greps build output (not source), so runtime-constructing the value keeps
// the literal out of the bundle while the check stays armed for the actual codename.That colliding species is capybara — both a pet species and a model codename.
Capybara Behavior Issues (v8)
The architecture reveals specific behavioral problems with Capybara v8:
1. Stop sequence false trigger (~10% rate when <functions> at prompt tail)
- Source: src/utils/messages.ts:2141
2. Empty tool_result causes zero output
- Source: src/utils/toolResultStorage.ts:281
3. Over-commenting — requires dedicated anti-comment prompt patches
- Source: src/constants/prompts.ts:204
4. High false-claims rate: v8 has 29-30% FC rate vs v4's 16.7%
- Source: src/constants/prompts.ts:237
5. Insufficient verification — requires "thoroughness counterweight"
- Source: src/constants/prompts.ts:210
Feature Flag Naming Convention
All feature flags use the tengu_ prefix with random word pairs to obscure their purpose:
| Flag | Purpose |
|------|---------|
| tengu_onyx_plover | Auto Dream (background memory consolidation) |
| tengu_coral_fern | memdir feature |
| tengu_moth_copse | Another memdir switch |
| tengu_herring_clock | Team memory |
| tengu_passport_quail | Path feature |
| tengu_slate_thimble | Another memdir switch |
| tengu_sedge_lantern | Away Summary |
| tengu_frond_boric | Analytics kill switch |
| tengu_amber_quartz_disabled | Voice mode kill switch |
| tengu_amber_flint | Agent teams |
| tengu_hive_evidence | Verification agent |
The random word pattern (adjective/material + nature/object) prevents external observers from inferring feature purpose from flag names alone.
Internal vs External User Difference
Anthropic employees (USER_TYPE === 'ant') receive significantly better treatment:
Prompt Differences (src/constants/prompts.ts)
| Dimension | External Users | Internal (ant) |
|-----------|---------------|----------------|
| Output style | "Be extra concise" | "Err on the side of more explanation" |
| False-claims mitigation | None | Dedicated Capybara v8 patches |
| Numeric length anchors | None | "≤25 words between tools, ≤100 words final" |
| Verification agent | None | Required for non-trivial changes |
| Comment guidance | Generic | Dedicated anti-over-commenting prompt |
| Proactive correction | None | "If user has misconception, say so" |
Tool Access
Internal users have access to tools not available externally:
- REPLTool — REPL mode
- SuggestBackgroundPRTool — background PR suggestions
- TungstenTool — performance monitoring panel
- VerifyPlanExecutionTool — plan verification
- Agent nesting (agents spawning agents)
Hidden Commands
| Command | Status | Description |
|---------|--------|-------------|
| /btw | Active | Ask side questions without interrupting |
| /stickers | Active | Order Claude Code stickers (opens browser) |
| /thinkback | Active | 2025 Year in Review |
| /effort | Active | Set model effort level |
| /good-claude | Stub | Hidden placeholder |
| /bughunter | Stub | Hidden placeholder |
---
En/03 Undercover Mode
Undercover Mode Analysis
Based on publicly available online references and community discussions on Claude Code v2.1.88.
What Is Undercover Mode?
Undercover mode is a safety system for official employees contributing to external/open-source repositories. When active, it hides internal-specific AI model information and attribution, instructing the system to present its contributions as if written by a human developer. This is primarily to prevent the leakage of internal secrets and unreleased model names into the open-source community.
Source: src/utils/undercover.ts
Activation Logic
// src/utils/undercover.ts:28-37
export function isUndercover(): boolean {
if (process.env.USER_TYPE === 'ant') {
if (isEnvTruthy(process.env.CLAUDE_CODE_UNDERCOVER)) return true
// Auto: active unless positively confirmed internal repo
return getRepoClassCached() !== 'internal'
}
return false
}Key properties:
- Internal only: Only active for official employees (USER_TYPE === 'ant')
- Default ON: Active in all repos except those on the internal allowlist
- No force-off: "There is NO force-OFF. This guards against model codename leaks"
- External builds: Dead-code-eliminated by the bundler; never executes
The Prompt Given to the Model
// src/utils/undercover.ts:39-69
export function getUndercoverInstructions(): string {
return ## UNDERCOVER MODE — CRITICALYou are operating UNDERCOVER in a PUBLIC/OPEN-SOURCE repository. Your commit
messages, PR titles, and PR bodies MUST NOT contain ANY Anthropic-internal
information. Do not blow your cover.
NEVER include in commit messages or PR descriptions:
- Internal model codenames (animal names like Capybara, Tengu, etc.)
- Unreleased model version numbers (e.g., opus-4-7, sonnet-4-8)
- Internal repo or project names (e.g., claude-cli-internal, anthropics/…)
- Internal tooling, Slack channels, or short links (e.g., go/cc, #claude-code-…)
- The phrase "Claude Code" or any mention that you are an AI
- Any hint of what model or version you are
- Co-Authored-By lines or any other attribution
Write commit messages as a human developer would — describe only what the code
change does.
GOOD:
- "Fix race condition in file watcher initialization"
- "Add support for custom key bindings"
BAD (never write these):
- "Fix bug found while testing with Claude Capybara"
- "1-shotted by claude-opus-4-6"
- "Generated with Claude Code"
- "Co-Authored-By: Claude Opus 4.6 <…>"
}Attribution System
The attribution system (src/utils/attribution.ts, src/utils/commitAttribution.ts) complements undercover mode:
// src/utils/attribution.ts:70-72
// @[MODEL LAUNCH]: Update the hardcoded fallback model name below
// (guards against codename leaks).
// For external repos, fall back to "Claude Opus 4.6" for unrecognized models.// src/utils/model/model.ts:386-392
function maskModelCodename(baseName: string): string {
// e.g. capybara-v2-fast → cap*-v2-fast
const [codename = '', ...rest] = baseName.split('-')
const masked = codename.slice(0, 3) + '*'.repeat(Math.max(0, codename.length - 3))
return [masked, ...rest].join('-')
}Implications
For Open Source
When official employees use Claude Code to contribute to open-source projects:
1. Code is written by AI but commits appear human-authored
2. No "Co-Authored-By: Claude" attribution
3. No "Generated with Claude Code" markers
4. Project maintainers and community cannot identify AI-generated contributions
5. This potentially violates open-source transparency norms regarding AI contributions
For Official Protection
The primary stated purpose is preventing accidental leaks of:
- Internal model codenames (competitive intelligence)
- Unreleased version numbers (market timing)
- Internal infrastructure details (security)
Ethical Considerations
The phrase "Do not blow your cover" frames the AI as an undercover agent. The intentional concealment of AI authorship in public code contributions raises questions about:
- Transparency in open-source communities
- Compliance with project contribution guidelines
- The line between trade secret protection and deception
---
En/04 Remote Control And Killswitches
Remote Control & Killswitches
Based on publicly available online references and community discussions on Claude Code v2.1.88.
Overview
Claude Code implements remote management mechanisms that allow officials (and enterprise administrators) to manage and update specific client behaviors via remote configuration to ensure system security and enterprise compliance.
1. Remote Managed Settings
Architecture
Every eligible session fetches settings from:
GET /api/claude_code/settingsSource: src/services/remoteManagedSettings/index.ts:105-107
Polling Behavior
// src/services/remoteManagedSettings/index.ts:52-54
const SETTINGS_TIMEOUT_MS = 10000
const DEFAULT_MAX_RETRIES = 5
const POLLING_INTERVAL_MS = 60 60 1000 // 1 hourSettings are polled every hour, with up to 5 retries on failure.
Eligibility
- Console users (API key): All eligible
- OAuth users: Only Enterprise/C4E and Team subscribers
Accept-or-Die Dialog
When remote settings contain "dangerous" changes, a blocking dialog is shown:
// src/services/remoteManagedSettings/securityCheck.tsx:67-73
export function handleSecurityCheckResult(result: SecurityCheckResult): boolean {
if (result === 'rejected') {
gracefulShutdownSync(1) // Exit with code 1
return false
}
return true
}Users who reject remote settings have the application forcefully terminated. The only options are: accept the remote settings, or Claude Code exits.
Graceful Degradation
If the remote server is unreachable, cached settings from disk are used:
// src/services/remoteManagedSettings/index.ts:433-436
if (cachedSettings) {
logForDebugging('Remote settings: Using stale cache after fetch failure')
setSessionCache(cachedSettings)
return cachedSettings
}Once remote settings have been applied, they persist even when the server is down.
2. Feature Flag Killswitches
Multiple features can be remotely disabled via GrowthBook feature flags:
Bypass Permissions Killswitch
// src/utils/permissions/bypassPermissionsKillswitch.ts
// Checks a Statsig gate to disable bypass permissionsCan disable permission bypass capabilities without user consent.
Auto Mode Circuit Breaker
// src/utils/permissions/autoModeState.ts
// autoModeCircuitBroken state prevents re-entry to auto modeAuto mode can be remotely disabled.
Fast Mode Killswitch
// src/utils/fastMode.ts
// Fetches from /api/claude_code_penguin_mode
// Can permanently disable fast mode for a userAnalytics Sink Killswitch
// src/services/analytics/sinkKillswitch.ts:4
const SINK_KILLSWITCH_CONFIG_NAME = 'tengu_frond_boric'Can remotely stop all analytics output.
Agent Teams Killswitch
// src/utils/agentSwarmsEnabled.ts
// Requires both env var AND GrowthBook gate 'tengu_amber_flint'Voice Mode Killswitch
// src/voice/voiceModeEnabled.ts:21
// 'tengu_amber_quartz_disabled' — emergency off for voice mode3. Model Override System
To conduct canary testing or respond to unexpected online situations, the system supports dynamically switching the model versions for specific groups, such as internal employees:
// src/utils/model/antModels.ts:32-33
// @[MODEL LAUNCH]: Update tengu_ant_model_override with new ant-only models
// @[MODEL LAUNCH]: Add the codename to scripts/excluded-strings.txtThe tengu_ant_model_override GrowthBook flag can:
- Set a default model
- Set default effort level
- Append to the system prompt
- Define custom model aliases
4. Penguin Mode
Fast mode status is fetched from a dedicated endpoint:
// src/utils/fastMode.ts
// GET /api/claude_code_penguin_mode
// If API indicates disabled, permanently disabled for userMultiple feature flags control fast mode availability:
- tengu_penguins_off
- tengu_marble_sandcastle
Summary
| Mechanism | Scope | User Consent |
|-----------|-------|-------------|
| Remote managed settings | Enterprise/Team | Accept or exit |
| GrowthBook feature flags | All users | None |
| Killswitches | All users | None |
| Model override | Internal (ant) | None |
| Fast mode control | All users | None |
The remote control infrastructure is extensive. Enterprise administrators can enforce policies that users cannot override, and the system can remotely change behavior for any user through feature flags to address critical issues.
---
En/05 Future Roadmap
Future Roadmap — What the Architecture Reveals
Based on publicly available online references and community discussions on Claude Code v2.1.88.
1. Next Model: Numbat
The most concrete evidence of the next model launch:
// src/constants/prompts.ts:402
// @[MODEL LAUNCH]: Remove this section when we launch numbat.Numbat (袋食蚁兽) is the codename for an upcoming model. The comment indicates the output efficiency section will be revised when Numbat launches, suggesting it may have better native output control.
Future Version Numbers
// src/utils/undercover.ts:49
- Unreleased model version numbers (e.g., opus-4-7, sonnet-4-8)Opus 4.7 and Sonnet 4.8 are in development.
Codename Evolution Chain
Fennec (耳廓狐) → Opus 4.6 → [Numbat?]
Capybara (水豚) → Sonnet v8 → [?]
Tengu (天狗) → telemetry/product prefixThe Fennec-to-Opus migration is documented:
// src/migrations/migrateFennecToOpus.ts:7-11
// fennec-latest → opus
// fennec-latest[1m] → opus[1m]
// fennec-fast-latest → opus[1m] + fast modeMODEL LAUNCH Checklist
The codebase contains 20+ @[MODEL LAUNCH] markers listing everything to update:
- Default model names (FRONTIER_MODEL_NAME)
- Model family IDs
- Knowledge cutoff dates
- Pricing tables
- Context window configurations
- Thinking mode support flags
- Display name mappings
- Migration scripts
2. KAIROS — Autonomous Agent Mode
The largest unreleased feature, KAIROS transforms Claude Code from a reactive assistant into a proactive autonomous agent.
System Prompt (excerpts)
// src/constants/prompts.ts:860-913You are running autonomously.
You will receive <tick> prompts that keep you alive between turns.
If you have nothing useful to do, call SleepTool.
Bias toward action — read files, make changes, commit without asking.
Terminal focus
- Unfocused: The user is away. Lean heavily into autonomous action.
- Focused: The user is watching. Be more collaborative.Associated Tools
| Tool | Feature Flag | Purpose |
|------|-------------|---------|
| SleepTool | KAIROS / PROACTIVE | Control pacing between autonomous actions |
| SendUserFileTool | KAIROS | Proactively send files to users |
| PushNotificationTool | KAIROS / KAIROS_PUSH_NOTIFICATION | Push notifications to user devices |
| SubscribePRTool | KAIROS_GITHUB_WEBHOOKS | Subscribe to GitHub PR webhook events |
| BriefTool | KAIROS_BRIEF | Proactive status updates |
Behavior
- Operates on <tick> heartbeat prompts
- Adjusts autonomy based on terminal focus state
- Can commit, push, and make decisions independently
- Sends proactive notifications and status updates
- Monitors GitHub PRs for changes
3. Voice Mode
Push-to-talk voice input is fully implemented but gated behind VOICE_MODE feature flag.
// src/voice/voiceModeEnabled.ts
// Connects to Anthropic's voice_stream WebSocket endpoint
// Uses conversation_engine backed models for speech-to-text
// Hold-to-talk: hold keybinding to record, release to submit- OAuth-only (no API key / Bedrock / Vertex support)
- Uses mTLS for WebSocket connections
- Killswitch: tengu_amber_quartz_disabled
4. Unreleased Tools
Tools found in source but not yet enabled for external users:
| Tool | Feature Flag | Description |
|------|-------------|-------------|
| WebBrowserTool | WEB_BROWSER_TOOL | Built-in browser automation (codename: bagel) |
| TerminalCaptureTool | TERMINAL_PANEL | Terminal panel capture and monitoring |
| WorkflowTool | WORKFLOW_SCRIPTS | Execute predefined workflow scripts |
| MonitorTool | MONITOR_TOOL | System/process monitoring |
| SnipTool | HISTORY_SNIP | Conversation history snipping/truncation |
| ListPeersTool | UDS_INBOX | Unix domain socket peer discovery |
| RemoteTriggerTool | AGENT_TRIGGERS_REMOTE | Remote agent triggering |
| TungstenTool | ant-only | Internal performance monitoring panel |
| VerifyPlanExecutionTool | VERIFY_PLAN env | Plan execution verification |
| OverflowTestTool | OVERFLOW_TEST_TOOL | Context overflow testing |
| SubscribePRTool | KAIROS_GITHUB_WEBHOOKS | GitHub PR webhook subscriptions |
5. Coordinator Mode
Multi-agent coordination system:
// src/coordinator/coordinatorMode.ts
// Feature flag: COORDINATOR_MODEEnables coordinated task execution across multiple agents with shared state and messaging.
6. Buddy System (Virtual Pets)
The complete pet companion system is implemented but not yet launched:
- 18 species: duck, goose, blob, cat, dragon, octopus, owl, penguin, turtle, snail, ghost, axolotl, capybara, cactus, robot, rabbit, mushroom, chonk
- 5 rarity tiers: Common (60%), Uncommon (25%), Rare (10%), Epic (4%), Legendary (1%)
- 7 hats: crown, tophat, propeller, halo, wizard, beanie, tinyduck
- 5 stats: DEBUGGING, PATIENCE, CHAOS, WISDOM, SNARK
- 1% shiny chance: Sparkle variant of any species
- Deterministic generation: Based on hash of user ID
Source: src/buddy/
7. Dream Task
Background memory consolidation subagent:
// src/tasks/DreamTask/
// Auto-dreaming feature that works in the background
// Controlled by 'tengu_onyx_plover' feature flagEnables the AI to autonomously process and consolidate memories during idle time.
Summary: The Three Directions
1. New Models: Numbat (next), Opus 4.7, Sonnet 4.8 in development
2. Autonomous Agent: KAIROS mode — unattended operation, proactive actions, push notifications
3. Multi-modal: Voice input ready, browser tool waiting, workflow automation coming
Claude Code is evolving from a coding assistant into an always-on autonomous development agent.
---
README
Claude Code Architecture Study
Introduction: This project is a learning and research repository focused on CLI Agent architecture. All materials are compiled entirely from publicly available online references and discussions, with a particular focus on public information regarding the highly popular CLI Agent claude-code. Our intention is to help developers better understand and utilize Agent technologies. We will continue to share more insights and practical discussions on Agent architecture in the future. Thank you for your support!Disclaimer: All content in this repository is provided strictly for technical research, study, and educational exchange among enthusiasts. Commercial use is strictly prohibited. No individual, organization, or entity may use this content for commercial purposes, profit-making activities, illegal activities, or any other unauthorized scenarios. If any content infringes upon your legal rights, intellectual property, or other interests, please contact us and we will verify and remove it immediately.
Language: English | 中文 | 한국어 | 日本語
---
Table of Contents
- Deep Analysis Reports (docs/) — Telemetry, codenames, undercover mode, remote control, future roadmap
- Directory Reference — Code structure tree
- Architecture Overview — Entry → Query Engine → Tools/Services/State
- Tool System & Permissions — 40+ tools, permission flow, sub-agents
- The 12 Progressive Harness Mechanisms — How Claude Code layers production features on the agent loop
---
Deep Analysis Reports (docs/)
Deep analysis reports compiled from publicly available online references and community discussions on Claude Code v2.1.88. Quadrilingual (EN/JA/KO/ZH).
/ Detailed source-code truncated for AI context efficiency. /Click any filename above to jump to the full report.
| # | Topic | Key Findings |
|---|-------|-------------|
| 01 | Telemetry & Privacy | Two analytics sinks (1P, Datadog). Environment fingerprint, process metrics, repo hash on every event. No UI-exposed opt-out for 1st-party logging. OTEL_LOG_TOOL_DETAILS=1 enables full tool input capture. |
| 02 | Hidden Features & Codenames | Animal codenames (Capybara v8, Tengu, Fennec→Opus 4.6, Numbat next). Feature flags use random word pairs (tengu_frond_boric) to obscure purpose. Internal users get better prompts, verification agents, and effort anchors. Hidden commands: /btw, /stickers. |
| 03 | Undercover Mode | Official employees auto-enter undercover mode in public repos. Model instructed: "Do not blow your cover" — strip all AI attribution, write commits "as a human developer would." No force-OFF exists. Raises transparency questions for open-source communities. |
| 04 | Remote Control | Hourly polling of /api/claude_code/settings. Dangerous changes show blocking dialog — reject = app exits. 6+ killswitches (bypass permissions, fast mode, voice mode, analytics sink). GrowthBook flags can change any user's behavior without consent. |
| 05 | Future Roadmap | Numbat codename confirmed. Opus 4.7 / Sonnet 4.8 in development. KAIROS = fully autonomous agent mode with <tick> heartbeats, push notifications, PR subscriptions. Voice mode (push-to-talk) ready but gated. 17 unreleased tools found. |
---
Copyright & Disclaimer
This repository is provided strictly for technical research and educational purposes.
Commercial use is strictly prohibited.If you are the copyright owner and believe this repository content infringes your rights,
please contact the repository owner for immediate removal.
---
Stats
| Item | Count |
|------|-------|
| Files (.ts/.tsx) | ~1,884 |
| Lines | ~512,664 |
| Largest single file | query.ts (~785KB) |
| Built-in tools | ~40+ |
| Slash commands | ~80+ |
| Dependencies (node_modules) | ~192 packages |
| Runtime | Bun (compiled to Node.js >= 18 bundle) |
---
The Agent Pattern
THE CORE LOOP
============= User --> messages[] --> Claude API --> response
|
stop_reason == "tool_use"?
/ \
yes no
| |
execute tools return text
append tool_result
loop back -----------------> messages[]
That is the minimal agent loop. Claude Code wraps this loop
with a production-grade harness: permissions, streaming,
concurrency, compaction, sub-agents, persistence, and MCP.
---
Directory Reference
/ Detailed source-code truncated for AI context efficiency. /---
Architecture Overview
/ Detailed source-code truncated for AI context efficiency. /---
Data Flow: A Single Query Lifecycle
USER INPUT (prompt / slash command)
│
▼
processUserInput() ← parse /commands, build UserMessage
│
▼
fetchSystemPromptParts() ← tools → prompt sections, CLAUDE.md memory
│
▼
recordTranscript() ← persist user message to disk (JSONL)
│
▼
┌─→ normalizeMessagesForAPI() ← strip UI-only fields, compact if needed
│ │
│ ▼
│ Claude API (streaming) ← POST /v1/messages with tools + system prompt
│ │
│ ▼
│ stream events ← message_start → content_block_delta → message_stop
│ │
│ ├─ text block ──────────────→ yield to consumer (SDK / REPL)
│ │
│ └─ tool_use block?
│ │
│ ▼
│ StreamingToolExecutor ← partition: concurrent-safe vs serial
│ │
│ ▼
│ canUseTool() ← permission check (hooks + rules + UI prompt)
│ │
│ ├─ DENY ────────────────→ append tool_result(error), continue loop
│ │
│ └─ ALLOW
│ │
│ ▼
│ tool.call() ← execute the tool (Bash, Read, Edit, etc.)
│ │
│ ▼
│ append tool_result ← push to messages[], recordTranscript()
│ │
└─────────┘ ← loop back to API call
│
▼ (stop_reason != "tool_use")
yield result message ← final text, usage, cost, session_id---
Tool System Architecture
/ Detailed source-code truncated for AI context efficiency. /Complete Tool Inventory
/ Detailed source-code truncated for AI context efficiency. /---
Permission System
/ Detailed source-code truncated for AI context efficiency. /---
Sub-Agent & Multi-Agent Architecture
MAIN AGENT
==========
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌──────────────┐ ┌──────────┐ ┌──────────────┐
│ FORK AGENT │ │ REMOTE │ │ IN-PROCESS │
│ │ │ AGENT │ │ TEAMMATE │
│ Fork process │ │ Bridge │ │ Same process │
│ Shared cache │ │ session │ │ Async context│
│ Fresh msgs[] │ │ Isolated │ │ Shared state │
└──────────────┘ └──────────┘ └──────────────┘ SPAWN MODES:
├─ default → in-process, shared conversation
├─ fork → child process, fresh messages[], shared file cache
├─ worktree → isolated git worktree + fork
└─ remote → bridge to Claude Code Remote / container
COMMUNICATION:
├─ SendMessageTool → agent-to-agent messages
├─ TaskCreate/Update → shared task board
└─ TeamCreate/Delete → team lifecycle management
SWARM MODE (feature-gated):
┌─────────────────────────────────────────────┐
│ Lead Agent │
│ ├── Teammate A ──> claims Task 1 │
│ ├── Teammate B ──> claims Task 2 │
│ └── Teammate C ──> claims Task 3 │
│ │
│ Shared: task board, message inbox │
│ Isolated: messages[], file cache, cwd │
└─────────────────────────────────────────────┘
---
Context Management (Compact System)
/ Detailed source-code truncated for AI context efficiency. /---
MCP (Model Context Protocol) Integration
/ Detailed source-code truncated for AI context efficiency. /---
Bridge Layer (Claude Desktop / Remote)
Claude Desktop / Web / Cowork Claude Code CLI
══════════════════════════ ═════════════════ ┌───────────────────┐ ┌──────────────────┐
│ Bridge Client │ ←─ HTTP ──→ │ bridgeMain.ts │
│ (Desktop App) │ │ │
└───────────────────┘ │ Session Manager │
│ ├── spawn CLI │
PROTOCOL: │ ├── poll status │
├─ JWT authentication │ ├── relay msgs │
├─ Work secret exchange │ └── capacityWake │
├─ Session lifecycle │ │
│ ├── create │ Backoff: │
│ ├── run │ ├─ conn: 2s→2m │
│ └─ stop │ └─ gen: 500ms→30s│
└─ Token refresh scheduler └──────────────────┘
---
Session Persistence
SESSION STORAGE
══════════════ ~/.claude/projects/<hash>/sessions/
└── <session-id>.jsonl ← append-only log
├── {"type":"user",...}
├── {"type":"assistant",...}
├── {"type":"progress",...}
└── {"type":"system","subtype":"compact_boundary",...}
RESUME FLOW:
getLastSessionLog() ──> parse JSONL ──> rebuild messages[]
│
├── --continue → last session in cwd
├── --resume <id> → specific session
└── --fork-session → new ID, copy history
PERSISTENCE STRATEGY:
├─ User messages → await write (blocking, for crash recovery)
├─ Assistant msgs → fire-and-forget (order-preserving queue)
├─ Progress → inline write (dedup on next query)
└─ Flush → on result yield / cowork eager flush
---
Feature Flag System
DEAD CODE ELIMINATION (Bun compile-time)
══════════════════════════════════════════ feature('FLAG_NAME') ──→ true → included in bundle
──→ false → stripped from bundle
FLAGS (observed in source):
├─ COORDINATOR_MODE → multi-agent coordinator
├─ HISTORY_SNIP → aggressive history trimming
├─ CONTEXT_COLLAPSE → context restructuring
├─ DAEMON → background daemon workers
├─ AGENT_TRIGGERS → cron/remote triggers
├─ AGENT_TRIGGERS_REMOTE → remote trigger support
├─ MONITOR_TOOL → MCP monitoring tool
├─ WEB_BROWSER_TOOL → browser automation
├─ VOICE_MODE → voice input/output
├─ TEMPLATES → job classifier
├─ EXPERIMENTAL_SKILL_SEARCH → skill discovery
├─ KAIROS → push notifications, file sends
├─ PROACTIVE → sleep tool, proactive behavior
├─ OVERFLOW_TEST_TOOL → testing tool
├─ TERMINAL_PANEL → terminal capture
├─ WORKFLOW_SCRIPTS → workflow tool
├─ CHICAGO_MCP → computer use MCP
├─ DUMP_SYSTEM_PROMPT → prompt extraction (ant-only)
├─ UDS_INBOX → peer discovery
├─ ABLATION_BASELINE → experiment ablation
└─ UPGRADE_NOTICE → upgrade notifications
RUNTIME GATES:
├─ process.env.USER_TYPE === 'ant' → internal features
└─ GrowthBook feature flags → A/B experiments at runtime
---
State Management
/ Detailed source-code truncated for AI context efficiency. /---
The 12 Progressive Harness Mechanisms
This architecture demonstrates 12 layered mechanisms that a production AI agent harness needs beyond the basic loop. Each builds on the previous:
/ Detailed source-code truncated for AI context efficiency. /---
Key Design Patterns
| Pattern | Where | Purpose |
|---------|-------|---------|
| AsyncGenerator streaming | QueryEngine, query() | Full-chain streaming from API to consumer |
| Builder + Factory | buildTool() | Safe defaults for tool definitions |
| Branded Types | SystemPrompt, asSystemPrompt() | Prevent string/array confusion |
| Feature Flags + DCE | feature() from bun:bundle | Compile-time dead code elimination |
| Discriminated Unions | Message types | Type-safe message handling |
| Observer + State Machine | StreamingToolExecutor | Tool execution lifecycle tracking |
| Snapshot State | FileHistoryState | Undo/redo for file operations |
| Ring Buffer | Error log | Bounded memory for long sessions |
| Fire-and-Forget Write | recordTranscript() | Non-blocking persistence with ordering |
| Lazy Schema | lazySchema() | Defer Zod schema evaluation for performance |
| Context Isolation | AsyncLocalStorage | Per-agent context in shared process |
---
License
This repository content is for technical research and education only. All intellectual property rights belong to the original company. If there is any infringement, please contact us for removal.
---