# lingyu-code **Repository Path**: 203014/lingyu-code ## Basic Information - **Project Name**: lingyu-code - **Description**: 桌面 AI 编码助手。Electron + Vue 3 + Rust,本地运行,工具可审计。 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2026-05-07 - **Last Updated**: 2026-05-26 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # LingYu Code AI 编码助手。Rust 核心引擎,1:1 复刻 Claude Code v2.1.88 后端(排除 UI 和 LLM 供应商层)。支持 DeepSeek/Claude/GPT/Qwen 多模型。 --- ## 一、技术栈 | 层 | 技术 | 说明 | |------|------|------| | 核心引擎 | Rust (code-core) | agent、plan、task、tool、model、event、query_loop | | 服务层 | Rust (code-server) | JSON-RPC (63 API)、session、event bus、cron、background | | LLM 客户端 | reqwest 0.12 (stream + rustls-tls) | OpenAI 兼容 API,支持 DeepSeek/Claude/GPT/Qwen | | LSP | lsp-types 0.97 | typed 协议,JSON-RPC 帧,8 模块 facade | | 异步 | Tokio 1 (rt-multi-thread) | 多线程调度,Semaphore 并发控制 | | 序列化 | serde + serde_json | 全层统一 | | 日志 | tracing 0.1 + tracing-subscriber 0.3 | 结构化 span/event | | 构建 | Cargo workspace | code-core + code-server 双 crate | --- ## 二、系统分层架构 ``` ┌─────────────────────────────────────────────────────────────────┐ │ CLI / Frontend │ │ code-server --print │ --interactive │ --dump-system-prompt │ │ /help /version /init /model /cost /stats /review ... (85 命令) │ └────────────────────────────┬────────────────────────────────────┘ │ JSON-RPC / Stdio ┌────────────────────────────┴────────────────────────────────────┐ │ crates/code-server (服务层) │ │ 160 源文件 · 29 模块 │ │ │ │ ┌─────────────┐ ┌───────────┐ ┌──────────┐ ┌───────────────┐ │ │ │ API Layer │ │ Session │ │ Event │ │ Cron/Worker │ │ │ │ 63 methods │ │ Store │ │ Bus │ │ Background │ │ │ │ JSON-RPC │ │ JSONL │ │ Broadcast│ │ Task Registry │ │ │ │ agent.start │ │ Compact │ │ 4096 cap │ │ Schedule │ │ │ └──────┬──────┘ └─────┬─────┘ └────┬─────┘ └───────┬───────┘ │ │ │ │ │ │ │ │ ┌──────┴──────────────┴────────────┴────────────────┴───────┐ │ │ │ Services: lsp sandbox notifier auto_dream magic_docs │ │ │ │ settings_sync team_runtime worktree_runtime oauth │ │ │ │ bridge plugin remote teleport migration bootstrap │ │ │ └──────────────────────────────────────────────────────────┘ │ └────────────────────────────┬────────────────────────────────────┘ │ ┌────────────────────────────┴────────────────────────────────────┐ │ crates/code-core (核心引擎) │ │ 230 源文件 · 30 模块 · 213 测试 │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌────────────────────┐ │ │ │ Agent │ │ Plan │ │ Task │ │ QueryLoop │ │ │ │ 11 文件 │ │ Generator│ │ Spec │ │ 10步主循环 │ │ │ │ Fork │ │ Executor │ │ Contract │ │ 7 恢复路径 │ │ │ │ Swarm │ │ Stage │ │ Risk │ │ 17 步消息规范化 │ │ │ │ Team │ │ Approval │ │ Approval │ │ 53 个事件类型 │ │ │ │ Repair │ │ Hash │ │ Gate │ │ Token 预算 │ │ │ │ Circuit │ │ │ │ │ │ Compact 三策略 │ │ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ └─────────┬──────────┘ │ │ │ │ │ │ │ │ ┌────┴────────────┴────────────┴──────────────────┴──────────┐ │ │ │ Tool System (60 文件, 81 工具) │ │ │ │ ┌────────┐ ┌────────┐ ┌──────────┐ ┌───────────────────┐ │ │ │ │ │ File │ │ Shell │ │ LSP(8模块)│ │ MCP(5模块) │ │ │ │ │ │ 6 tools│ │ 7模块 │ │ Client │ │ Registry Channel │ │ │ │ │ │ Read │ │ Security│ │ Protocol │ │ Config InProcess │ │ │ │ │ │ Write │ │ AST │ │ Manager │ │ Pool SSE/Stdio │ │ │ │ │ │ Edit │ │ Win │ │ Hover Def │ │ │ │ │ │ │ └────────┘ └────────┘ └──────────┘ └───────────────────┘ │ │ │ │ ┌────────┐ ┌────────┐ ┌──────────┐ ┌───────────────────┐ │ │ │ │ │ Git │ │ Web │ │ Agent │ │ Task/Cron │ │ │ │ │ │ 5 tools│ │ Fetch │ │ Subagent │ │ Create List Update│ │ │ │ │ │ Diff │ │ Search │ │ Team │ │ Stop Output │ │ │ │ │ │ Status │ │ HTML→txt│ │ Builtin │ │ Schedule │ │ │ │ │ └────────┘ └────────┘ └──────────┘ └───────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ ┌──────────────────────────────────────────────────────────────┐ │ │ │ Model Client │ Context Mgr │ Compact │ Permission │ │ │ │ Stream Parse │ Token Est │ 940行 │ Classifier Engine │ │ │ │ Retry(10重试) │ Collapse │ 3策略 │ Rule Match(MCP感知) │ │ │ │ Error(20变体) │ Compaction │ Boundary │ Smart Approval │ │ │ │ ANSI Strip │ Window Calc │ Attachments│ Denial Track │ │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌──────────────────────────────────────────────────────────────┐ │ │ │ Hooks(6模块) │ Skill(4模块) │ Audit(4) │ Verification(4) │ │ │ │ Prompt(17) │ Memory(4) │ Telemetry│ Voice(Whisper) │ │ │ │ LSP(8 facade)│ Utils(9) │ Cost(2) │ Constants(13) │ │ │ └──────────────────────────────────────────────────────────────┘ │ └──────────────────────────────────────────────────────────────────┘ ``` --- ## 三、Agent 编排引擎 ### 3.1 状态机 (16 阶段) ``` GoalIntake → ClarifyingGoal → ProposingContract → WaitingContractApproval │ ┌────────────────────────────────────┘ ▼ Planning → WaitingPlanApproval → Executing │ ┌───────────────────────────────┘ ▼ Observing ←→ Repairing │ ▼ Verifying → PreparingDelivery → Completed 任意阶段 ──→ Failed / Cancelled / TakenOver ``` **16 个阶段,20 条合法转移路径。** `validate_transition(from, to)` 编译期验证。终端阶段(Completed、Failed、Cancelled、TakenOver)不可再转移。 ### 3.2 QueryLoop 主循环 (query_loop.rs, 2043 行) ``` loop { Step 1: lightweight_precompact (snip → microcompact) + boundary 注入 Step 1.5: context collapse projection (feature-gated) Step 2: auto-compact (SessionMemory → LlmSummary → HardPrune) + compact_boundary 事件 + compact.completed 事件 Step 3: context block check (token estimation > 95%) Step 4: LLM model call (streaming + usage tracking) + mid-stream fallback (tombstone 事件) Step 5: post-sampling hooks (PostTool event after model response) Step 6: tool execution (partition → parallel read-only / serial write) + tool started → delta → completed 事件 + schema validation before execution + permission denied hooks Step 7: tool results → conversation messages Step 8: terminal check (complete / error / max_turns / budget exceeded) Step 9: API error short-circuit (跳过 stop hooks 防死循环) Step 10: stop hooks + teammate hooks → 4 分支分类 Step 11: continue / 7 恢复路径: collapse_drain → reactive_compact → max_output_escalate → max_output_recovery → stop_hook_blocking → token_budget_continuation → next_turn } ``` ### 3.3 关键子系统 | 系统 | 位置 | 说明 | |------|------|------| | RepairLoop | `agent/repair.rs` | 验证失败后最多 2 次修复尝试 | | CircuitBreaker | `agent/circuit_breaker.rs` | 熔断状态:Closed→Open→HalfOpen | | PlanGenerator | `compat.rs` | 从 TaskSpec 确定性生成 3 阶段 ExecutionPlan | | PlanExecutor | `compat.rs` | stage 允许/阻止工具 + 通配符 + 完成状态检查 | | SmartApproval | `compat.rs` | bash/powershell 命令分类 + 读写判断 + 风险评级 | | ContextManager | `context/manager.rs` | Token 估算 + 90%/80%/70% 三级阈值 | | Collapse | `context/collapse.rs` | 按 API round 分组,从头丢弃至 token 预算内 | | AuditBundle | `audit/bundle.rs` | EvidenceRef 链 + 可重建 | | CostTracker | `cost/tracker.rs` | AtomicF64 原子累加,模型感知定价 | --- ## 四、消息规范化管道 (17 步) 模型调用前,消息经过完整的 17 步规范化管道(匹配 TS normalizeMessagesForAPI): ``` 1. Strip virtual/progress messages 2. Strip media error blocks (image/PDF retry prevention) 3. Filter whitespace-only assistant messages 4. Normalize tool inputs (strip plan/caller/internal fields) 5. Handle tool references (strip blocks) 6. Normalize attachments (split multi-attachment users) 7. Merge consecutive user messages 8. Merge consecutive assistant messages 9. Filter trailing thinking from last assistant 10. Filter orphaned thinking-only messages 11. Ensure non-empty assistant content 12. Merge system reminder siblings 13. Sanitize error tool result content 14. Validate images for API size limits 15. Append message ID tags for history snip 16. Repair tool_use/tool_result pairing (orphan detection + dedup + synthetic insertion) 17. Final merge pass ``` --- ## 五、事件系统 ### 5.1 CodexRunEvent (53 变体) 事件通过 `CoreEventSink` (broadcast channel) 发出,分为 12 个域: | 域 | 事件 | 说明 | |------|------|------| | **Goal Intake** | GoalIntakeStarted, GoalIntakeClassified, GoalContractProposed/Approved/Rejected, TaskContractWaitingApproval/Ready, TaskSpecCreated/Updated, TaskScopeChanged, GoalClarificationAnswered/Resolved | 目标澄清和合同审批流程 | | **Planning** | PlanCreated, PlanUpdated, PlanRejected, PlanApprovalRequested, PlanApproved | 执行计划生命周期 | | **Run Phase** | RunPhaseStarted/Blocked/Failed/Completed/Recovered | 阶段状态机 | | **Turn** | TurnStarted, TurnStatus, TurnCompleted, TurnFailed, UserMessage | 对话轮次 | | **Model Call** | ModelCallStarted, ModelCallCompleted, ModelCallFailed, ContextUsage, LlmSegmentDelta, LlmSegmentCompleted | LLM 调用流 | | **Tool** | ToolGroupStarted, ToolItemStarted, ToolItemDelta, ToolItemCompleted, ToolGroupCompleted | 工具执行 | | **Verification** | VerificationStarted, VerificationCheckStarted/Completed/Failed, VerificationCompleted/Failed | 验证流程 | | **Audit** | AuditBundleStarted, AuditEvidenceAdded, AuditBundleCompleted, AuditBundleExported | 审计追踪 | | **Intervention** | InterventionRequested/Submitted/Applied/Rejected, InterventionTakeoverStarted/Completed | 人工干预 | | **Memory** | MemoryPatchApplied | 记忆更新 | | **Subagent** | SubagentStarted/Completed/Failed, WorktreeCreated/Cleaned, AgentMessageSent/Received | 子代理 | | **Team** | TeamStarted, TeamWorkerStarted/Completed, TeamCompleted | 团队协作 | ### 5.2 SdkMessage (8 变体) `CodexRunEvent` → `records_to_sdk_messages()` → `SdkMessage` 流: | 消息类型 | 关键字段 | UI 渲染 | |----------|---------|---------| | User | message(ContentBlock[]), is_synthetic, is_replay, attachments | 用户气泡 | | Assistant | message(ContentBlock[]), error | 助手气泡 + 工具块 | | StreamEvent | event(message_start/delta/stop) | 逐字流式渲染 | | ToolUseSummary | summary, preceding_tool_use_ids | 工具执行摘要 | | Tombstone | message, uuid | 内容移除/编辑标记 | | StreamRequestStart | uuid | 流式请求开始 | | Result | subtype, duration, cost, usage, errors | 轮次结果卡片 | | System | subtype(compact_boundary/api_retry), data | 系统通知 | --- ## 六、JSON-RPC API (63 方法) | 分类 | 方法 | 数量 | |------|------|------| | **Agent** | agent.start, agent.startSubagent, agent.stop, agent.contextUsage | 4 | | **Runtime** | runtime.health, run.state, run.resume, run.cancel, run.takeover | 5 | | **Task** | task.create/update/approve/reject/get/answerClarification/versions/contract | 9 | | **Plan** | plan.get/update/approve/reject/versions/replace/startExecution | 8 | | **Verification** | verification.run, verification.report, verification.confirmManualEvidence | 3 | | **Intervention** | intervention.submit, intervention.list | 2 | | **Audit** | audit.get/export/exportJson/exportMarkdown/rebuild | 5 | | **Memory** | memory.query/patch/clear/injectPreview | 4 | | **Background** | backgroundTask.create/list/get/output/stop | 5 | | **Cron** | cron.schedule/list/delete/update | 4 | | **Session** | session.create/list/resume/events/messages/archive/rename/delete/compact/rewind/export | 11 | | **Permission** | permission.resolve | 1 | | **AppState** | appState.get, appState.update | 2 | --- ## 七、Core 层模块清单 ### code-core/src/ (30 模块, 230 源文件, 213 测试) | 模块 | 文件 | 职责 | |------|------|------| | `agent/` | 11 | 子代理规范、隔离、swarm、team、fork、repair、circuit_breaker、builtin | | `audit/` | 4 | AuditBuilder、AuditBundle、EvidenceKind、DeliverySummary | | `bridge/` | 6 | 桥接配置、容量唤醒、入站消息/附件、协议 | | `command/` | 3 | Command trait、registry、types、CommandCategory | | `compact/` | 1 (940行) | Snip、microcompact、auto-compact (3策略)、PTL 重试、边界附件构建、post-compact cleanup | | `compat.rs` | 1 (962行) | IntelligenceConfig、ExecutionPlan、PlanGenerator、PlanExecutor、SmartApprovalClassifier、RunStateMachine、GoalClarification、BudgetSnapshot | | `constants/` | 13 | apiLimits、toolLimits、product、errorIds、common、betas、files、keys、messages、prompts、system、xml | | `context/` | 6 | ContextManager、collapse、compaction、replay、tokens (模型感知计数) | | `coordinator/` | 2 | 协调器模式、CoordinatorMode | | `cost/` | 2 | CostTracker (AtomicF64)、ModelUsage、SessionCost、estimate_cost (模型感知定价) | | `engine.rs` | 1 | DefaultCodexCoreEngine、start_run/stop_run、CoreRunMode (AgentLoop/QueryLoop) | | `error.rs` | 1 | CodeCoreError (20 变体)、Result | | `event.rs` | 1 | CodexRunEvent (53 变体)、LlmUsage、CostEstimate、ProviderProfile、SandboxMode、ApprovalPolicy | | `feature.rs` | 1 | FeatureFlags、is_feature_enabled | | `hooks/` | 6 | HookEvent (12 事件)、HookRunner、HookExecutor (Shell/HTTP/Prompt/Agent)、HookConfigManager、notifications、tool_permission | | `intervention/` | 3 | HumanIntervention、InterventionRecord、InterventionResult | | `lsp/` | 8 | diagnostics、definition、references、hover、call_hierarchy、client、manager、feedback | | `mcp/` | 5 | McpRegistry、channel permissions、in_process transport、config、types | | `memdir/` | 2 | 内存目录管理 | | `memory/` | 4 | RuntimeMemory、MemoryPatch、dream、injection、session | | `model/` | 12 | ChatMessage、ModelClient、stream parser (OpenAiStreamState)、retry (10重试+指数退避)、pricing、messages (17步规范化)、error (20变体)、providers、rate_limit、usage、cache、pdf | | `oauth/` | 2 | OAuthConfig、OAuthTokens、OAuthProfile | | `permission/` | 7 | ApprovalDelegate、ClassifierEngine、SmartApprovalClassifier、PermissionRule、mode、update | | `plugin.rs` | 1 (528行) | PluginManifest、PluginInstaller、validate_manifest、PluginType、PluginSource | | `prompt/` | 17 | SystemPromptBuilder、PromptContext、sections (13 段:identity/rules/doing_tasks/code_style/actions_care/using_tools/tone_style/output_efficiency/memory_context/env_info/session_guidance/mcp_instructions/skill_reminders)、cache | | `protocol.rs` | 1 | JSON-RPC、stable_hash、VersionedSchema | | `proxy/` | 3 | ProxyConfig、TCP relay、protobuf chunk 编解码 | | `query_loop.rs` | 1 (2043行) | 主循环、QueryParams、TaskBudget、TerminalReason、7 恢复路径、QueryState | | `remote/` | 2 | RemoteSession、RemoteSessionStatus | | `schemas/` | 2 | Hook schema 验证 (Bash/Prompt/Http/Agent) | | `sdk_types.rs` | 1 | CronTask、SessionInfo、SdkMessage、RemoteControlHandle | | `settings/` | 5 | SettingsJson、SettingsManager、change_detector、constants、validation | | `skill/` | 4 | SkillRegistry (条件激活索引)、SkillDefinition、executor、builtin (17 技能)、watcher | | `task/` | 5 | TaskSpec、TaskComplexity、TaskRisk、ApprovalGate、DeliveryExpectation | | `telemetry.rs` | 1 | TelemetryEvent (20+ 变体)、TelemetrySender (批量)、global_sender、session tracking | | `terminal/` | 9 | 终端渲染:cell、diff、layout、node、style_pool、screen、ansi、frame | | `tool/` | 60 | Tool trait、descriptor、orchestrator、registry (81 注册)、streaming_executor、shell (7模块)、file (read/write/edit/multi_edit)、git、web、lsp (7文件)、mcp、agent、task、team、cron、notebook、plan_mode、browser、skill、todo、search | | `utils/` | 9 | env (tty/CI/container检测)、process (tree-kill/shell_escape)、path (glob/tilde/gitignore)、debug (PerfTimer/metrics)、git、signal、backend、complete | | `verification/` | 4 | VerificationStrategy、VerificationRunner (真实评估)、VerificationReport | | `voice.rs` | 1 | VoiceProvider、WhisperLocalProvider (model download + SHA-256)、VoiceManager、VoicePostProcessor (CJK 标点) | ### code-server/src/ (29 模块, 160 源文件) | 模块 | 文件 | 职责 | |------|------|------| | `analytics/` | 3 | 分析管道、logger | | `api/` | 15 | JSON-RPC handler:agent、session、task、plan、audit、cron、memory、background、permission、methods、run、verification、app_state、intervention | | `app_state/` | 4 | 应用状态管理、startup、side_effects | | `background/` | 1 | 后台任务注册表 | | `bootstrap/` | 4 | init (27 阶段:toolchain→env→shell→git→config→hooks→migration→watcher→collapse→prefetch→repo→attribution→bypass→OAuth→remote→policy→preconnect→shutdown→telemetry→plugin→MCP→scratchpad→beacon)、state、env | | `bridge/` | 14 | ReplBridge (入站/出站队列)、session_runner、daemon (指数退避)、JWT、messaging、capacity_wake、flush_gate、config、client | | `cli/` | 10 | args (50+ flag, 9 子命令)、main_loop、handlers (agents/auth/auto_mode/mcp/plugins/util) | | `command/` | 8 | 85 命令 (13 FnCommand + 6 PromptCommand + 55 SimpleCommand + 6 复杂 + ~5 独立) | | `coordinator/` | 2 | 协调器模式 | | `cron/` | 2 | CronWorker (1s tick)、CronStore (持久化 + due_jobs) | | `event/` | 5 | SdkMessage adapter、CodexRunEventRecord、notification、bus (broadcast 4096) | | `history/` | 2 | HistoryStore (JSONL + pending buffer + 去重 + 文件锁) | | `keybindings/` | 3 | 32 默认绑定、parser | | `mcp/` | 5 | McpConnectionManager (指数退避重连)、transport (stdio/sse/http/ws/sdk)、channels、complete | | `memdir/` | 2 | 内存目录扫描 | | `migration/` | 2 | MigrationRunner (11 迁移、结构化 JSON 操作) | | `oauth/` | 4 | OAuthClient (PKCE + profile + manual flow)、crypto、server (AuthCodeListener) | | `permission/` | 4 | ServerApprovalDelegate、denial_tracking、remembered_rules | | `plugin/` | 4 | PluginInstaller (git clone + manifest 验证)、manager、marketplace | | `proxy/` | 2 | 代理客户端 | | `remote/` | 3 | RemoteSessionManager (重连 5次+退避、cancel、keepalive) | | `secure_storage/` | 2 | 安全存储 (加密回退) | | `services/` | 28 | desktop_notifier、lsp_service、sandbox_service (命令包装+违规记录)、magic_docs、auto_dream、extract_memories、prompt_suggestion、session_memory_service、suggestions、diagnostic_tracking、internal_logging、policy_limits、remote_managed_settings、sandbox、team_memory_sync、tips、token_estimation、tool_use_summary、vcr、powershell_utils、rate_limit_messages、onboarding、memory_utils、task_utils、todo_utils、agent_summary、background | | `session/` | 4 | InMemorySessionStore、storage (JSONL + 旧版目录树兼容)、lifecycle、concurrency | | `settings/` | 5 | loader (5 源:user/project/local/flag/policy)、manager、MDM、managed_path | | `settings_sync/` | 2 | SettingsSync (HTTP push/pull + 序列跟踪) | | `teleport/` | 3 | TeleportClient (tsh 调用)、environment | | `transport/` | 8 | WebSocket、SSE、stdio、JSON-RPC、codec、hybrid、in_memory | | `worktree_runtime.rs` | 1 (685行) | WorktableManager (池管理:创建/获取/释放/丢弃/预热/空闲清理/补丁) | | `team_runtime.rs` | 1 (460行) | TeamRuntime (创建/持久化/清理)、TaskInfo | --- ## 八、工具系统 (81 工具, 60 文件) ### 8.1 工具分区和执行 ``` PendingToolCall[] → partition_tool_calls() ├─ 输入感知并发安全检测 (is_concurrency_safe_with_args) │ ├─ Bash: 检查命令前缀 (ls/cat/grep/echo/git log → 安全) │ ├─ File: 写工具 → 不安全 │ └─ 其他: 名称匹配 ├─ 并发批次: tokio::spawn + Semaphore(10) + mpsc channel (完成顺序产出) │ └─ Bash 错误级联: sibling_abort 取消兄弟工具 └─ 串行批次: 逐个 await ├─ enforce_task_scope → validate_input → dangerous_check → permission → execute └─ 权限拒绝: emit_permission_denied (TS executePermissionDeniedHooks) ``` ### 8.2 工具清单 | 分类 | 工具 | 数量 | |------|------|------| | **文件** | read_file, write_file, edit_file, multi_edit, delete_file, notebook_edit | 6 | | **Shell** | bash, powershell | 2 | | **搜索** | grep, glob, list_files, tool_search | 4 | | **Git** | git_status, git_diff, git_log, git_commit, git_push | 5 | | **Web** | web_fetch, web_search | 2 | | **LSP** | lsp, lsp_diagnostics, lsp_format, lsp_symbols, lsp_definition, lsp_references, lsp_hover, lsp_call_hierarchy, lsp_implementation, lsp_config | 10 | | **MCP** | mcp_call, mcp_list_resources, mcp_read_resource, mcp_auth | 4 | | **Agent** | agent, team_create, team_delete, send_message, workflow | 5 | | **Task** | task_create, task_list, task_get, task_update, task_stop, task_output | 6 | | **Plan** | enter_plan_mode, exit_plan_mode | 2 | | **Cron** | cron_schedule, cron_list, cron_delete, cron_update | 4 | | **Browser** | browser | 1 | | **Skill** | skill, ask_user_question, brief, todo_write, sleep | 5 | | **Config** | config, model_config, update_memory | 3 | | **其他** | repl, remote_trigger, synthetic_output, tungsten, delegate (22 工具) | 22 | --- ## 九、数据流总览 ``` 用户输入 → agent.start (JSON-RPC) ↓ AppServer → CoreRunRequest ↓ DefaultCodexCoreEngine::start_run ↓ query_params_from_core_request → QueryParams ↓ query_with_sink → CoreEventSink (broadcast channel) ↓ ┌──────────────── Event Stream ─────────────────┐ │ GoalIntake → TaskSpec → Plan → Turn 循环 │ │ ModelCallStarted │ │ LlmSegmentDelta (Text/Thinking) │ │ ModelCallCompleted │ │ PostTool hooks │ │ ToolGroupStarted │ │ ToolItemStarted → Delta → Completed │ │ ToolGroupCompleted │ │ TurnCompleted │ │ VerificationStarted → Check → Completed │ │ AuditBundleCompleted │ └──────────────────────────────────────────────┘ ↓ records_to_sdk_messages() → SdkMessage 流 → 前端渲染 ↓ session/storage.rs → JSONL 持久化 ↓ cost/tracker.rs → 成本累计 ``` --- ## 十、配置和部署 ### 10.1 环境变量 | 变量 | 用途 | 默认值 | |------|------|--------| | `DEEPSEEK_API_KEY` | DeepSeek API 密钥 | — | | `ANTHROPIC_API_KEY` | Anthropic API 密钥 (fallback) | — | | `OPENAI_API_KEY` | OpenAI API 密钥 (fallback) | — | | `DEEPSEEK_BASE_URL` | DeepSeek API 地址 | `https://api.deepseek.com/v1` | | `ANTHROPIC_BASE_URL` | Anthropic API 地址 | — | | `DEEPSEEK_MODEL` | 默认模型 | `deepseek-chat` | ### 10.2 构建命令 ```powershell # 开发构建 cargo check -p code-core -p code-server # 测试 cargo test -p code-core cargo test -p code-server cargo test --workspace # 发布构建 cargo build --release -p code-server # 运行 ./target/release/code-server.exe --help ./target/release/code-server.exe --print "你的提示词" ``` ### 10.3 项目结构 ``` lingyu-code/ ├── crates/ │ ├── code-core/ # 核心引擎 (230 源文件) │ │ ├── src/ │ │ │ ├── agent/ # 代理系统 (11) │ │ │ ├── compact/ # 压缩 (1, 940行) │ │ │ ├── context/ # 上下文 (6) │ │ │ ├── hooks/ # 钩子 (6) │ │ │ ├── lsp/ # LSP (8) │ │ │ ├── mcp/ # MCP (5) │ │ │ ├── model/ # 模型客户端 (12) │ │ │ ├── permission/# 权限 (7) │ │ │ ├── prompt/ # 提示词 (17) │ │ │ ├── skill/ # 技能 (4) │ │ │ ├── tool/ # 工具系统 (60) │ │ │ ├── utils/ # 工具函数 (9) │ │ │ └── ... # 其他 (16) │ │ └── tests/ # 28 测试文件 │ └── code-server/ # 服务层 (160 源文件) │ ├── src/ │ │ ├── api/ # JSON-RPC API (15) │ │ ├── bridge/ # 桥接 (14) │ │ ├── cli/ # CLI (10) │ │ ├── command/ # 命令系统 (8) │ │ ├── services/ # 服务 (28) │ │ ├── session/ # 会话 (4) │ │ ├── transport/ # 传输 (8) │ │ └── ... # 其他 (17) │ └── tests/ # 21 测试文件 ├── docs/ # 文档 │ ├── lingyu-1to1-restoration.md # 1:1 复刻文档 │ └── lingyu-frontend-ui-design.md # 前端 UI 设计 ├── Cargo.toml # Workspace 配置 └── README.md # 本文档 ```