InkdownInkdown
Start writing

Claude-Code

62 files·4 subfolders

Shared Workspace

Claude-Code
codex

09-services-overview

Shared from "Claude-Code" on Inkdown

Services Overview

The business logic layer — everything that isn't UI, tools, or the query loop.


Analytics & Telemetry

Analytics Service (services/analytics/)

Tracks usage events and feature flags:

TypeScript
// Log an event
logEvent('tengu_started', { /* metadata */ })

// Events are queued until sinks are attached
// initSinks() drains the queue to:
// 1. Statsig (product analytics)
// 2. Internal logging (ant-only)
// 3. Local telemetry
0000_start_here_index_and_recommended_reading_order.md
0100_project_overview_tech_stack_runtime_modes_and_folder_map.md
0200_startup_flow_entry_points_and_cold_start_sequence.md
0300_codebase_modules_layers_state_models_and_schemas.md
0400_system_architecture_and_design_rationale.md
0500_interactive_repl_request_flow_end_to_end.md
0600_headless_sdk_and_print_mode_request_flow_end_to_end.md
0700_mcp_integration_connection_and_tool_call_flow.md
0800_external_services_sdks_storage_and_local_dependencies.md
0900_environment_variables_settings_feature_flags_and_failure_modes.md
1000_non_obvious_patterns_gotchas_and_debugging_traps.md
1100_full_codebase_file_inventory_grouped_by_directory.md
kimi
00-overview.md
01-entrypoints.md
02-state-management.md
03-query-system.md
04-tools-system.md
05-tasks-system.md
06-ui-components.md
07-bridge-remote.md
08-services.md
09-skills-plugins.md
10-commands.md
11-testing-architecture.md
12-permission-system.md
13-build-system.md
14-ink-internals.md
15-git-internals.md
16-context-compaction.md
17-vim-mode.md
18-mailbox-notifications.md
19-session-persistence.md
20-hooks-system.md
21-error-recovery.md
README.md
qwen
00-overview.md
01-entry-points.md
02-query-engine.md
03-tools-and-tasks.md
04-commands-and-skills.md
05-state-management.md
06-ink-rendering.md
07-bridge-remote.md
08-mcp-services.md
09-services-overview.md
10-multi-agent.md
11-system-prompt-constants.md
12-tool-interface.md
13-memory-system.md
14-buddy-companion.md
15-keybindings.md
16-stop-hooks.md
17-vim-mode.md
18-upstreamproxy.md
19-cost-tracking-history.md
20-contexts-styles-onboarding.md
21-hooks.md
22-screens.md
tweets-explain
claude-code-memory-analysis.md
compact
memory-system
agentic-architecture
GrowthBook (services/analytics/growthbook.ts)

Feature flag and A/B testing platform:

TypeScript
// Get feature value (cached, may be stale)
getFeatureValue_CACHED_MAY_BE_STALE('tengu_otk_slot_v1', false)

// Feature gate (compile-time elimination)
if (feature('COORDINATOR_MODE')) { ... }

// Refresh after auth change
refreshGrowthBookAfterAuthChange()
OpenTelemetry

Full OTel integration:

TypeScript
// Meter (metrics)
const meter = getMeter()
const sessionCounter = meter.createCounter('sessions')

// Tracer (distributed tracing)
const tracer = getTracerProvider()

// Event Logger (structured events)
const eventLogger = getEventLogger()

Attributed counters track:

  • Sessions
  • Lines of code changed
  • PRs created
  • Commits made
  • Cost
  • Tokens
  • Active time

Compact Services (services/compact/)

Auto-Compact

Summarizes old messages when context approaches the limit:

TypeScript
// Triggered in query.ts before API call
const compactionResult = await autocompact(
  messagesForQuery,
  toolUseContext,
  { systemPrompt, userContext, systemContext, ... },
  querySource,
  tracking,
  snipTokensFreed
)

Process:

  1. Check if context exceeds threshold
  2. If yes, send old messages to compact model (Haiku)
  3. Replace old messages with summary
  4. Track compaction usage for analytics
Micro-Compact

Removes redundant tool_use/tool_result pairs:

TypeScript
const microcompactResult = await microcompact(
  messagesForQuery,
  toolUseContext,
  querySource
)
Reactive Compact

Triggered reactively when the API returns 413 (prompt too long):

TypeScript
const compacted = await tryReactiveCompact({
  hasAttempted: hasAttemptedReactiveCompact,
  querySource,
  aborted,
  messages,
  cacheSafeParams: { ... }
})
Snip Compact

Removes the oldest messages:

TypeScript
const snipResult = snipCompactIfNeeded(messagesForQuery)
// Returns: { messages, tokensFreed, boundaryMessage? }

Context Collapse (services/contextCollapse/)

A more aggressive context reduction strategy:

  • Archives old conversation segments
  • Stores summaries in a persistent collapse store
  • projectView() replays the commit log on every entry
  • Summaries persist across turns (unlike compaction)
TypeScript
// Initialize
initContextCollapse()

// Apply collapses if needed
const result = await applyCollapsesIfNeeded(messages, toolUseContext, querySource)

// Recover from overflow by draining staged collapses
const drained = recoverFromOverflow(messages, querySource)

Session Memory (services/SessionMemory/)

Extracts and stores memories from conversations:

TypeScript
// Initialize
initSessionMemory()

// Hook: triggered on conversation changes
registerMemoryExtractionHook()

// Memories stored in .claude/ directory

Team Memory Sync (services/teamMemorySync/)

Syncs memory across team members:

TypeScript
// Start watcher
startTeamMemoryWatcher()

// Syncs .claude/ memories to shared storage

Settings Sync (services/settingsSync/)

Uploads local settings to the cloud:

TypeScript
// Background upload
uploadUserSettingsInBackground()

// Only for interactive sessions
if (getIsInteractive()) { ... }

LSP Service (services/lsp/)

Language Server Protocol integration:

TypeScript
// Initialize manager
initializeLspServerManager()

// Recommendation shown once per session
hasShownLspRecommendationThisSession()

Prompt Suggestion (services/PromptSuggestion/)

Suggests prompts to the user:

TypeScript
// Check if enabled
shouldEnablePromptSuggestion()

// Shows suggestions in the UI

Tips (services/tips/)

Contextual tips shown to users:

TypeScript
// Get relevant tips
getRelevantTips()

// Prefetched at startup

Rate Limit Management

Claude AI Limits (services/claudeAiLimits.ts)

Tracks and displays rate limit status:

TypeScript
// Check quota
checkQuotaStatus()

// Hook for limit changes
registerClaudeAiLimitsHook()
Rate Limit Messages (services/rateLimitMessages.ts)

User-friendly messages for rate limits:

TypeScript
// Generate message based on limit type
getRateLimitMessage(limitType)
Rate Limit Mocking (services/rateLimitMocking.ts)

For testing:

TypeScript
// Mock rate limits
mockRateLimits(config)

Auto Dream (services/autoDream/)

Background processing feature:

TypeScript
// Auto-dream: process conversations in background
// Consolidation lock prevents concurrent dreams

Prevent Sleep (services/preventSleep.ts)

Keeps the system awake during long operations:

TypeScript
// Prevent system sleep
preventSleep()

// Allow sleep again
allowSleep()

Notifier (services/notifier.ts)

Notification system:

TypeScript
// Send notification
notify(message, options)

// Notifications shown in the UI

VCR (Playback/Recording) (services/vcr.ts)

Records and replays API interactions for testing:

TypeScript
// Record mode
recordVcr()

// Playback mode
playbackVcr()

Voice Services

Voice (services/voice.ts)

Voice input support:

TypeScript
// Voice processing
processVoiceInput()
Voice Keyterms (services/voiceKeyterms.ts)

Domain-specific keyterms for voice:

TypeScript
// Get keyterms for project
getVoiceKeyterms(projectRoot)
Voice Stream STT (services/voiceStreamSTT.ts)

Streaming speech-to-text:

TypeScript
// Stream audio to STT service
streamToSTT(audioStream)

Magic Docs (services/MagicDocs/)

Auto-generates documentation:

TypeScript
// Generate docs for codebase
generateMagicDocs()

Diagnostic Tracking (services/diagnosticTracking.ts)

Collects diagnostic information:

TypeScript
// Track diagnostics
trackDiagnostic(name, value)

Internal Logging (services/internalLogging.ts)

Internal logging for debugging:

TypeScript
// Log permission context
logPermissionContextForAnts()

Away Summary (services/awaySummary.ts)

Summarizes what happened while the user was away:

TypeScript
// Generate away summary
generateAwaySummary()

Extract Memories (services/extractMemories/)

Memory extraction from conversations:

TypeScript
// Extract memories from messages
extractMemories(messages)

Remote Managed Settings (services/remoteManagedSettings/)

Enterprise-managed settings:

TypeScript
// Load remote settings
loadRemoteManagedSettings()

// Refresh on changes
refreshRemoteManagedSettings()

// Security checks
securityCheck()

Policy Limits (services/policyLimits/)

Enterprise policy enforcement:

TypeScript
// Load policy limits
loadPolicyLimits()

// Check if action is allowed
isPolicyAllowed(action)

// Refresh limits
refreshPolicyLimits()

OAuth (services/oauth/)

OAuth authentication:

TypeScript
// OAuth flow
startOAuthFlow()

// Refresh token
refreshOAuthToken()

Plugins (services/plugins/)

Plugin management:

TypeScript
// Plugin operations
installPlugin(name)
uninstallPlugin(name)
updatePlugin(name)
listPlugins()

// Plugin state in AppState
plugins: {
  enabled: Set<string>
  disabled: Set<string>
  errors: PluginError[]
  installationStatus: Map<string, InstallationStatus>
  needsRefresh: boolean
}

Key Files Reference

DirectoryPurpose
services/analytics/Telemetry, GrowthBook, OTel
services/api/Anthropic API client
services/compact/Context compaction
services/contextCollapse/Context collapse
services/mcp/MCP servers
services/tools/Tool orchestration
services/SessionMemory/Session memory
services/teamMemorySync/Team memory sync
services/settingsSync/Settings sync
services/lsp/LSP integration
services/plugins/Plugin management
services/policyLimits/Enterprise policies
services/oauth/OAuth authentication
services/remoteManagedSettings/Remote settings
services/autoDream/Auto dream
services/PromptSuggestion/Prompt suggestions
services/tips/Tips
services/voice.tsVoice input
services/vcr.tsVCR recording/playback
services/notifier.tsNotifications
services/rateLimitMessages.tsRate limit messages
services/awaySummary.tsAway summary
services/diagnosticTracking.tsDiagnostics
services/internalLogging.tsInternal logging
services/MagicDocs/Auto documentation
services/extractMemories/Memory extraction
services/toolUseSummary/Tool use summaries
services/tokenEstimation.tsToken estimation
services/claudeAiLimits.tsClaude AI limits
services/preventSleep.tsPrevent system sleep
services/mockRateLimits.tsRate limit mocking
services/voiceKeyterms.tsVoice keyterms
services/voiceStreamSTT.tsVoice STT