🌐 中文文档
All notable changes to LegnaCode CLI will be documented in this file.
- OpenAI Responses API Bridge — New
apiFormat: "responses"setting enables Codex-compatible providers (/v1/responseswire format). Full streaming + non-streaming support with Anthropic event translation. - Admin Config Hot-Reload — Saving an active profile via inline editor now syncs to
settings.json, triggering CLI hot-reload without profile switch. - Admin UI Auto-Refresh — Profile list refreshes automatically after save, showing updated endpoint/model info immediately.
- getGlobalSettings Dead Code — All 3 call sites (
claude.ts,adapters/index.ts,gates.ts) referenced a non-existent function. Fixed to usegetInitialSettings()from settings.ts. This makeskiroGatewaytoggle actually work.
- Kiro Gateway Client-Side History Optimization — New
kiroGatewaysetting enables client-side history compression aligned with Gateway's converter.py (thinking/tool_result truncation, schema normalization). - Admin Profile Inline Editing — Each profile card has an "编辑" button for inline settings editing. Profile-specific API:
GET/PUT /api/:scope/profiles/:filename. - Admin Preset Templates — 7 provider presets (DeepSeek, Kimi, GLM, Qwen, MiniMax, MiMo, Anthropic).
- ANTHROPIC_MODEL Settings Field — Highest-priority model override in admin settings panel.
- Model Allowlist Removed —
isModelAllowed()always returns true. Third-party providers use arbitrary model names that would never pass a Claude-centric allowlist. - count_tokens API Disabled — Both
countMessagesTokensWithAPIandcountTokensViaHaikuFallbackreturn null unconditionally. The/v1/messages/count_tokensendpoint is not supported by third-party providers and causes 403 errors. - Bash Sandbox Removed — Disabled native sandbox addon, Seatbelt fallback, and sandbox-adapter native path.
- Migration Auto-Fill ANTHROPIC_MODEL — Auto-fills from OPUS value when migrating Claude Code configs.
- Admin Preset Profile Templates — "从预设创建" button with 7 provider templates. Creates file and auto-switches.
- ANTHROPIC_MODEL Settings Field — Highest-priority model override in admin settings panel.
- Backend profiles/create API —
POST /api/:scope/profiles/create { filename, content }.
- Bash Exit Code 65 — Complete Fix — Disabled all sandbox wrapping paths: native Rust addon (
sandboxAddon = null), Seatbelt fallback (wrapCommandreturnsnone), andsandbox-adapter.tsnative path. The(deny default)Seatbelt profile was blocking all commands includingls,echo,pwd. Command safety handled at TS permission layer. - Migration Auto-Fill ANTHROPIC_MODEL — Auto-fills from OPUS value when migrating Claude Code configs.
- compile-all.ts Auto-Copy Addons — Copies
.nodeaddons from bothsrc/native/andnative/*/.
- Admin Preset Profile Templates — "从预设创建" button in profiles panel with 7 provider templates (DeepSeek, Kimi, GLM, Qwen, MiniMax, MiMo, Anthropic). Each preset pre-fills
env.ANTHROPIC_AUTH_TOKEN,ANTHROPIC_BASE_URL,ANTHROPIC_MODEL,ANTHROPIC_DEFAULT_HAIKU/SONNET/OPUS_MODEL. Creates file and auto-switches to it. - ANTHROPIC_MODEL Settings Field — Admin settings panel now exposes
env.ANTHROPIC_MODEL("指定模型 — 覆盖所有层级"), the highest-priority model override. Separate from themodelalias field (sonnet/opus/haiku). - Backend profiles/create API —
POST /api/:scope/profiles/create { filename, content }creates a new settings file with preset content.
- Migration Auto-Fill ANTHROPIC_MODEL — When migrating from Claude Code configs that have
ANTHROPIC_DEFAULT_OPUS_MODELbut noANTHROPIC_MODEL, the migration now auto-fillsANTHROPIC_MODELfrom the OPUS value. Without this, the CLI defaults toclaude-opus-4-6which fails on third-party providers.
- macOS Seatbelt Sandbox Rewrite — Replaced
(deny default)with(allow default)strategy. The sandbox now only denies writes to critical system paths (/System,/usr,/bin,/sbin) and user-configuredprotected_paths. Normal shell commands work without friction — no more exit code 65. - Shell.ts Sandbox Return Path — Restored the return statement for successful sandbox execution that was accidentally removed in v1.9.3, which caused commands to fall through and re-execute unsandboxed.
- OpenAI-Compatible API Routing — New
apiFormatsetting ('anthropic' | 'openai' | auto) enables routing requests through OpenAI Chat Completions API instead of Anthropic Messages API. Per-adapterapiFormat: 'auto'auto-detects from base URL:/anthropicsuffix → Anthropic SDK, otherwise → OpenAI fetch bridge. All 6 CN adapters default to auto. - OpenAI Streaming Bridge — New
openaiStreamBridge.tstranslates OpenAI SSE stream into Anthropic event format. Handlesdelta.content,delta.tool_calls,delta.reasoning_content(DeepSeek/Kimi/MiMo),delta.reasoning_details(MiniMax). Downstream code (tool execution, session storage) sees identical events — zero changes needed. - Admin Profile Clone — New "复制" button on each profile card in admin WebUI. Inline form with auto-prefixed
settings-and.jsonsuffix. Backend:POST /api/:scope/profiles/clone. - Admin API Route Selector — Settings panel now shows "API 路由模式" dropdown: Auto (URL-based), Anthropic, or OpenAI.
- Deep Adapter Alignment — All 7 adapters (DeepSeek, MiniMax, Qwen, GLM, Kimi, MiMo, OpenAICompat) updated per official API docs:
- DeepSeek: dual endpoints, model list (v4-flash/v4-pro),
output_config.effortpreserved,reasoning_contentpassback - MiniMax: dual endpoints (China/Global + Token Plan),
reasoning_detailsarray format,stripUnsupportedContentBlocks - Qwen/DashScope: Beijing/Singapore/Coding Plan URLs,
coding.dashscope.aliyuncs.comhost, qwen3.6-* prefix - GLM/ZhipuAI: OpenAI + Anthropic + Coding Plan URLs,
sensitive/network_error/model_context_window_exceededfinish reasons,cached_tokenssupport - Kimi/Moonshot: kimi-k2.6 (thinking, immutable temp/top_p),
moonshot-v1-*prefix, Preserved Thinking (thinking.keep: "all") - MiMo/Xiaomi: mimo-v2.5-pro/v2.5 models, Token Plan host,
repetition_truncationfinish reason
- DeepSeek: dual endpoints, model list (v4-flash/v4-pro),
- OpenAI SDK Type Alignment — Reviewed OpenAI SDK v6.34.0 types:
Delta.ToolCall.indexrequired,Delta.contentnullable,function_calldeprecated finish reason,stream_options.include_usage,Delta.refusalhandling. - Shared Adapter Utilities —
stripUnsupportedContentBlocksfilters image/document/server_tool_use/redacted_thinking.forceAutoToolChoicestripsdisable_parallel_tool_use.stripUnsupportedFieldspreservesoutput_config.effort. - API Key Resolution — OpenAI bridge now uses
getAnthropicApiKey()unified auth path (settings.json → env → keychain) instead of rawprocess.env.
- Bash Exit Code 65 — macOS Seatbelt sandbox returns exit code 65 due to overly restrictive profile.
Shell.tsnow detects this and falls through to unsandboxed spawn path. - Admin Settings Profile —
GET/PUT /api/:scope/settingsnow reads/writes the active profile file (viagetActiveProfile()) instead of hardcodedsettings.json. - Design Prompt False Positives — Narrowed Chinese keyword detection for design prompt injection. Replaced broad single-character words (界面, 组件, 页面) with compound terms (前端开发, UI组件, 页面设计).
- Computer Use Auto-Enable — Removed
DEFAULT_DISABLED_BUILTINwhitelist that required manual opt-in viaenabledMcpServers. - reasoning_content Passback — DeepSeek/Kimi OpenAI endpoints require
reasoning_contentfrom thinking mode to be passed back.convertAnthropicToOpenAInow extracts thinking blocks and sets them on assistant messages.
- Computer Use Python Bridge — Replaced native Swift/Rust modules (
@ant/computer-use-swift+@ant/computer-use-input) with pure Python subprocess bridge (runtime/mac_helper.py+runtime/win_helper.py). Zero NAPI dependencies. Supports 28 commands: screenshot, mouse, keyboard, app management, clipboard, permission detection. Cross-platform: macOS and Windows. - Auto Python Environment Setup — First Computer Use invocation automatically detects system Python 3.12+, creates a venv at
~/.legna/computer-use-venv/, installs platform-specific dependencies. Search order:LEGNA_PYTHON_BINenv →python3.14..python3.12→python3/python→ Windowspylauncher. Requirements hash invalidation triggers reinstall on dependency changes. - Platform-Specific Dependencies — Split
requirements.txtintorequirements-macos.txt(pyobjc),requirements-windows.txt(pywin32/psutil/screeninfo/pyperclip),requirements-common.txt(mss/Pillow/pyautogui).
- Feature Gate Removal — Removed all GrowthBook remote feature flags and Max/Pro subscription checks for Computer Use. Now controlled by local
settings.json(computerUse.enabled, defaulttrue). Available to all users. - Executor Simplification —
executor.tsrewritten from ~800 lines to ~200 lines. No CFRunLoop drain, no NAPI, no animated mouse movement — pure subprocess I/O.
- Portable Sessions — Migrated session JSONL files use
"cwd":"."relative paths instead of absolute paths. Projects can be moved, copied, or synced via git — resume works from any location. Runtime resolves"."to current working directory at 5 points insessionStorage.ts,crossProjectResume.ts, andlistSessionsImpl.ts. - WebUI Project Browser — New "项目总览" tab with card layout showing all projects from
~/.claude/and~/.legna/. Displays session count, last active time, migration status, source (Claude/Legna/Both). Missing paths highlighted in red. - WebUI Memory Editor — Three-column layout: project list → file tree with expand/collapse for subdirectories → Markdown editor. Banner: "记忆是 AI 的建议性笔记,随项目演进自动更新,内容仅供参考".
- WebUI Force-Directed Graph — Interactive project relationship visualization with physics simulation (repulsion + attraction + center gravity + damping). Draggable nodes. Node size = session count, color = recency, edges = same-day activity with weight labels.
- Full Project Migration — Migrates sessions (JSONL + subagents/ + tool-results/), memory, skills/, agents/, rules/, CLAUDE.md → LEGNA.md, settings.json, .mcp.json. Path rewriting handles Windows backslash, spaces, special characters, JSON-escaped paths.
- Multi-Source Migration — Scans
~/.claude/projects/,~/.legna/projects/with correct path resolution from JSONLcwdfield (no more-to/misparse for paths likeclaude-code-main). - Profile Pointer Switching — Config profile switching uses
.active-profilepointer file instead of physically renaming files. Original filenames preserved permanently.
- Migration Panel Redesign — Two-tab layout: "项目迁移" (project-level with checkboxes, source badges, status tags) and "配置同步" (field-level with icons, collapsible JSON preview).
- MCP Config Migration — Global
~/.claude/.mcp.jsonand project-level.claude/.mcp.jsonincluded in migration. - Co-Authored-By Attribution — Changed from
noreply@anthropic.comto@LegnaOScontributor identity.
- Tool Prompt Compression — Compressed tool descriptions for BashTool (
21K→12K chars), AgentTool (16K→13K chars), TodoWriteTool (9.5K→2K chars), and EnterPlanModeTool (7.7K→2K chars). Reduces first-request token cost by ~8,000-10,000 tokens.
- Model Adapter cache_control Fix — Added
normalizeToolsKeepCache()variant insrc/utils/model/adapters/shared.tsthat preservescache_controlon tool definitions. Kimi, MiniMax, and MiMo adapters now use it, fixing tool-level prompt caching that was silently stripped bynormalizeTools(). MiMo adapter also drops unnecessarystripCacheControl()since its API supports server-side auto caching.
- Session Transcript Null Guard — Added defensive null/type checks to
isLoggableMessage,collectReplIds, andtransformMessagesForExternalTranscriptinsrc/utils/sessionStorage.ts. Preventsm4 is not an Object (evaluating '"isVirtual" in m4')crash when the messages array contains undefined/null elements during React effect processing inuseLogMessages.
- GitHub Actions Release Workflow — 4-stage CI pipeline: prepare (bump + webui) → native (Rust addons on 4 platform runners) → compile (7 Bun cross-compile targets) → publish (npm). Trigger via
v*tag push or manualworkflow_dispatch. - Cross-Platform Rust Native Addons — CI builds
sandbox,file-search,apply-patchNAPI addons for darwin-arm64, darwin-x64, linux-x64, linux-arm64 using native runners. - compile.ts --target flag — Support cross-compilation target override for CI usage.
- OML Agent Type Mismatch — Fixed
agentfield in OML skill definitions passing an object{ type, model }instead of a string. Caused all 19 OML agent skills to silently fallback togeneral-purposein fork mode.
- Message Pipeline Null Guards — Added defensive null checks to 11 functions in
src/utils/messages.ts(normalizeMessages,isNotEmptyMessage,isSyntheticMessage,isToolUseRequestMessage,isToolUseResultMessage,isHookAttachmentMessage,isSystemLocalCommandMessage,isThinkingMessage,getAssistantMessageText,getUserMessageText,reorderMessagesInUI). Preventsundefined is not an object (evaluating 'message.type')runtime crash when message arrays contain undefined elements. - Mode Command Disabled — Removed
/modeslash command registration to fix Bun compiled binary startup hang caused by JIT compilation stall.
- Rust Native Addons (darwin-arm64) — Compiled and bundled
sandbox,file-search,apply-patchNAPI addons. Fixed missingregex-litedependency in file-search crate andResulttype mismatch in apply-patch crate.
Codex Full Fusion Release — 5-phase integration of OpenAI Codex CLI capabilities into LegnaCode.
- Process Hardening — Disable core dumps, detect ptrace attachment, sanitize dangerous env vars (
LD_PRELOAD,DYLD_INSERT_LIBRARIES,NODE_OPTIONSinjection). - Static Exec Policy Engine — TOML-based command execution rules (
prefix/glob/regexmatching). Built-in defaults block destructive commands (rm -rf /,mkfs), prompt for package installs, allow read-only operations. Evaluated before LLM classifier —forbidden→ instant deny,allow→ instant pass,prompt→ existing approval flow. - Secret Detector — Regex pattern library for AWS keys, GitHub tokens, JWTs, Slack tokens, private keys, generic API keys. Auto-redaction in memory pipeline (
[REDACTED:type]). - Rollback — Full implementation with timeline scanning,
--dry-runpreview,--safebackup branch creation. - Guardian Sub-Agent — Dedicated tool call risk assessment with 6-category taxonomy (data_exfiltration, credential_probing, security_weakening, destructive_action, privilege_escalation, supply_chain). Rule-based pre-classification (30+ patterns), compact transcript builder (<2000 tokens), fail-closed design.
- Shell Escalation Protocol — Three-tier execution:
sandbox(restricted),escalate(user confirm),deny(refuse). Platform-aware wrapping: macOS Seatbelt, Linux bubblewrap, fallbackunshare --net. - Network Policy Agent — Domain-level access control with
full/limited/blockedmodes, wildcard patterns, denylist priority, JSONL audit log.
- Rust Native NAPI Addon —
cosine_similarity(SIMD f32),tfidf_vectorize(Rayon parallel),content_hash(SHA-256 streaming),estimate_tokens(branchless CJK-aware). ~10-50x speedup with automatic TS fallback. - Kernel-Level Sandbox — Seatbelt via
sandbox_init()(macOS), seccomp-bpf viaprctl(Linux). No external dependency (sandbox-exec/bwrap). - Two-Pass Wake-Up — Greedy L1 fill + L0 backfill for maximum depth and coverage within token budget.
- Keyword-Density L1 — Sentence ranking by
(keyword_ratio × √keyword_count)replaces naive first-3-sentences. - Token ROI Ranking — Memories ranked by recall-to-cost ratio; compact frequently-recalled memories outrank verbose one-shot memories.
- Collaboration Mode System — Templated
.mdmodes with YAML frontmatter. Built-in:default,plan,execute,pair. Three-tier loading (built-in → user → project). Runtime switching via programmatic API (note:/modeslash command disabled in compiled binary due to Bun JIT limitation). - JS REPL Bridge — Public
legnacodeobject in REPL scope:tool(),readFile(),exec(),glob(),grep(),emitImage(). - App-Server JSON-RPC — Full JSON-RPC 2.0 with 7 method groups (
thread/*,turn/*,fs/*,config/*,mcpServer/*,model/*,skills/*). Streaming notifications. stdio + WebSocket transports. - Agent Config Migration —
/migratedetects Codex, Cursor, Copilot, Windsurf, Aider, Continue. Imports config, MCP servers, rules. - Codex Plugin Compatibility — Adapter for
codex-plugin.jsonmanifests. Marketplace registry fetcher with cache. Installation + auth policy engines. Integrated into plugin loader (CWD auto-scan) and marketplace browser. - Codex Skills Compatibility — Auto-discovery of
~/.codex/skills/. Frontmatter normalizer (triggers→when_to_use,tools→allowed-tools,invoke→argument-hint). - Codex Config Interoperability — Bidirectional
~/.codex/config.tomlmapping. Auto-import as lowest-priority settings base. - TypeScript SDK (
@legna/legnacode-sdk) —LegnaCodeclient,Threadclass, stdio/WebSocket transports, structured output.Codexalias. - Python SDK (
legnacode-sdk) — Async client, Thread, JSON-RPC transport, dataclass types.Codexalias. - TTS Voice Output — Native backend (macOS
say, Linuxespeak). Streaming queue. Graceful degradation. - WebRTC Voice Transport — Bidirectional audio via WebRTC. Signalling, ICE exchange, peer connection. Stub fallback.
- Rust Native NAPI Addon — Core hot-path operations rewritten in Rust via
napi-rs.cosine_similarity(SIMD-accelerated f32 dot product),tfidf_vectorize(parallel TF-IDF with Rayon),content_hash(SHA-256 with streaming), andestimate_tokens(branchless CJK-aware counting). TypeScript bindings with automatic fallback to pure-TS implementations when the native module is unavailable. ~10-50x speedup on vector operations.
- Kernel-Level Sandbox Integration — Rust-native sandbox profiles replace shell-exec wrappers. macOS: Seatbelt profile compiled in-process via
sandbox_init()(nosandbox-execchild process). Linux: directprctlseccomp-bpf syscall filter (nobwrap/unsharedependency). Platform capability detection with graceful degradation.SandboxNativeclass withapplySeatbelt()/applySeccomp()/detect()API.
- Two-Pass Wake-Up Filling —
LayeredStack.wakeUp()now uses a two-pass strategy: Pass 1 greedily fills with L1 summaries (richer context), Pass 2 backfills remaining budget with L0 summaries from skipped drawers. Maximizes both depth and coverage within the same token budget. - Keyword-Density L1 Generation —
generateL1()replaced naive "first 3 sentences" with keyword-density scoring. Sentences ranked by(keyword_ratio × √keyword_count), first sentence always anchored for context, top-density sentences greedily packed into 400 chars, re-sorted by original position for coherent reading. - Token ROI Ranking —
topByImportance()andsearch()now factor in token ROI: memories with high recall-to-cost ratio are boosted. A compact memory recalled frequently outranks a verbose memory recalled once. Content-hash index added for faster dedup lookups.
- Collaboration Mode System — Templated collaboration modes with YAML frontmatter
.mdfiles. Three-tier loading: built-in (src/services/collaborationModes/templates/), user-level (~/.legnacode/modes/), project-level (.legnacode/modes/). Later tiers override earlier by mode ID. Modes control system prompt injection, tool restrictions (allow/deny lists), and behavior flags (readOnly,autoExecute,stepByStep,requirePlan). Ships with four built-in modes:default,plan,execute,pair. New/modeslash command for listing and switching modes at runtime. - JS REPL Bridge — Public
legnacodeobject injected into the JavaScript REPL global scope. Providestool()for calling any LegnaCode tool by name,readFile(),exec(),glob(),grep()shortcuts, andemitImage()for rendering base64/Buffer/file-path images. Enables scripting LegnaCode capabilities from within REPL sessions. - App-Server JSON-RPC Layer — Full JSON-RPC 2.0 infrastructure for IDE integration. Router with method registration and dispatch. Seven method groups:
thread/*(session lifecycle, fork, rollback, compact),turn/*(message send, steer, interrupt),fs/*(read/write/metadata),config/*(read/write/batch),mcpServer/*(status, resource, tool call),model/list,skills/list+collaborationMode/list. Streaming notifier pushesitem/*,turn/*,agentMessage/deltanotifications. Two transports: stdio (JSONL) and WebSocket (with heartbeat keepalive). Standalone entrypoint vialegnacode app-server --transport stdio|websocket. - External Agent Config Migration — Detect and import configurations from other AI coding tools. Detectors for Codex, Cursor, GitHub Copilot, Windsurf, Aider, and Continue. Importers for Codex (TOML/JSON config → model + MCP servers), Cursor (settings.json → MCP servers +
.cursorrules→LEGNACODE.md), and Copilot (copilot-instructions.md→LEGNACODE.md). Integrated into/migrate --agentsflag and available standalone. Supports--dry-runpreview and--forceoverwrite.
- Guardian Sub-Agent — Dedicated approval agent for tool call risk assessment. Six-category risk taxonomy (data_exfiltration, credential_probing, security_weakening, destructive_action, privilege_escalation, supply_chain). Rule-based fast pre-classification with 30+ signal patterns. Compact transcript builder compresses conversation history to <2000 tokens for context. Fail-closed design: timeout/error/malformed response → deny. Structured JSON assessment output. Configurable via
guardiansettings field. - Shell Escalation Protocol — Three-tier per-command execution decision:
sandbox(restricted environment),escalate(user confirmation required),deny(refuse). Platform-aware sandbox wrapping: macOS Seatbelt (sandbox-exec), Linux bubblewrap (bwrap), Linux fallback (unshare --net). Integrates execPolicy + Guardian pre-classification for decision making. Detects commands needing external write access or network. - Network Policy Agent — Domain-level network access control for all outbound requests. Three modes:
full(unrestricted),limited(GET/HEAD/OPTIONS only),blocked(deny all). Wildcard domain patterns (*.example.com). Denylist takes precedence over allowlist. JSONL audit logging to~/.legnacode/logs/network-audit.jsonl. Configurable via~/.legnacode/network-policy.toml.
- Process Hardening — Startup module inspired by Codex's
process-hardening. Strips dangerous environment variables (LD_PRELOAD,DYLD_INSERT_LIBRARIES,ELECTRON_RUN_AS_NODE), sanitizesNODE_OPTIONS(removes--require/--loaderinjection flags), disables core dumps on Linux, and detects ptrace attachment. - Static Execution Policy Engine — Rule-based command evaluation before shell execution. Supports prefix, glob, regex, and host_executable matchers. Ships with built-in defaults (forbids
rm -rf /, pipe-to-shell, fork bombs; prompts for package installs andsudo; allows read-only git/file ops). User-configurable via.legnacode/exec-policy.toml(project) or~/.legnacode/exec-policy.toml(global). Codex-compatible function-call syntax supported. - Secret Detection & Redaction — Pattern-based detector for 25+ secret types (AWS keys, GitHub PATs, Stripe keys, OpenAI/Anthropic API keys, JWTs, private keys, database URLs, etc.). Integrated into the auto-memory write pipeline — secrets are replaced with
[REDACTED:type]before persisting to.legna/memory/.
- Rollback CLI — Full implementation of the rollback command. Lists checkpoint history, resolves targets by index or message-ID prefix, supports
--dry-run(preview changes),--safe(creates git backup branch before restoring), and--list(show all rollback points). Built on the existing fileHistory snapshot infrastructure.
- Git-style
/forkcommand — Unified conversation forking with sub-commands:/fork— Fork from current position (replaces/branch)/fork @N— Fork from the Nth user message, truncating subsequent history/fork list— Display branch tree with ASCII art, marking current branch/fork switch <id|name>— Switch between conversation branches/fork <name>— Fork with a custom name/branchis now an alias for/fork
- WebUI SSE timeout — Bun.serve
idleTimeoutraised to 255s (max); SSE streaming no longer drops after 10s. - WebUI controller double-close crash — Guard
sendEventandcontroller.close()against repeated invocation after client disconnect.
Republish of 1.5.3 with all platform binaries in sync.
- Hermes Self-Evolution Loop — Automatic learning closed loop: repeated tool patterns (3x) auto-generate SKILL.md via side-channel LLM; behavior corrections auto-write to
.legna/memory/; no user confirmation needed. Background Review Agent extracts experience insights after each session. - Qwen Model Adapter — Dedicated adapter for Qwen full series (qwen-plus, qwen-max, qwen-turbo, qwen-coder-plus, qwq-plus, qwen3-235b). Supports
thinking_budgetmapping, DashScope server-side web search (enable_search),reasoning_contentstreaming, andcontent_filterstop reason. - WebUI Chat Viewer — New "聊天记录" panel in admin WebUI. Browse session history with full message rendering, collapsible thinking blocks, tool call visualization (input/output/error), and auto-scroll. Backend
/api/:scope/sessions/:id/messagesendpoint reads JSONL session files. - WebUI Live Chat —
legna adminWebUI now supports live chat via SSE streaming. Send messages, see streaming responses with thinking/tool-use visualization. Note: each message starts a new independent session (no multi-turn conversation); intended for quick API connectivity testing, not as a full chat client. - Skill Auto-Create —
SkillPatternDetector.record()was already wired but results were never surfaced. Now auto-creates skills from detected patterns and notifies user after the fact. - Skill Improvement Path B —
skillImprovementno longer gated to active skill execution. General conversation learning detects workflow preferences, behavior corrections, and coding style preferences every 10 user messages. - Nudge System — Counter-driven session learning summary. Reports what was automatically learned (skills created, corrections captured, insights recorded) instead of suggesting the user go learn.
- onPreCompress Enhanced — Working state extraction added alongside existing exchange pair extraction. Captures current task, key decisions, file paths, and error patterns before context compression. High-priority drawer written to DrawerStore.
- Skill Version Backup —
applySkillImprovementnow backs up current SKILL.md to.versions/before overwriting. Changelog with last 20 versions maintained automatically. /skillifyUnlocked — RemovedUSER_TYPE === 'ant'gate. All users can now capture session workflows as reusable skills.
- WebUI inline script crash — Fixed
Unexpected token '<'error caused by unescaped</sequences in inlined JavaScript. JS and CSS are now served as separate files (/__admin__/app.js,/__admin__/app.css) instead of being inlined into<script>tags.
- Async CodeGraph —
build()andwalkDir()converted from sync to async, yielding the event loop every 50 files. AddedmaxDepth=10depth limit andvisitedInodessymlink loop protection.save()now uses asyncwriteFile. - undoTracker size guard — Added 1MB file size limit; files exceeding it skip undo snapshot recording (prevents OOM).
readFileSync→ asyncreadFile. - Async error file pre-injection —
extractErrorFilesconverted fromexistsSync+readFileSyncto asyncaccess+readFile. - stripCode dedup —
magicKeywords.tsreducedstripCode()from 3-4 calls to 1, passing the result to all downstream functions. - FileMemoryProvider TTL cache —
searchSolutionsand fallback file search now use 60s TTL cache, avoiding repeated disk reads on every prefetch. - OML_SESSION_GUIDANCE cache —
attachments.tsdynamic import cached at module level after first load. - frustrationHint patterns hoisted — Regex array moved from function body to module-level constant.
- Compacting status messages localized — "Compacting context…" → "凝练上下文…", "Compacting conversation" → "精炼对话中" for Chinese users.
- Turn completion verbs localized — New
getTurnCompletionVerbs()function; Chinese users see "烹制了 5s" instead of "Baked for 5s".
- Deleted dead code
src/commands/undo.ts(was never registered in command list). - Fixed dead conditional in
extractImports.
- Proactive skill invocation — Wired
OML_SESSION_GUIDANCE(the "1% rule") into theskill_listingattachment. The AI now proactively considers available skills before every response, instead of only responding to explicit/slashcommands. - Frontend/design auto-guidelines — New
designPrompt.tsdetects frontend intent (UI, prototype, design exploration) from user input and transparently injects layered design guidelines (oklch colors, responsive layout, animation best practices, design exploration methodology). Zero user action required. - Enhanced designer agent —
/oml:designernow carries a full design methodology prompt (oklch palettes, mobile-first, ARIA accessibility, 3+ variation exploration) instead of a one-line description.
- Skills were never proactively used —
OML_SESSION_GUIDANCEwas defined insuperpowers.tsbut never imported or injected anywhere. Now wired into the skill listing attachment.
- Fix REPL startup deadlock — The
/undocommand was registered via staticimportincommands.ts, creating a circular dependency (commands.ts→undo.ts→commands.ts) that caused Bun's module loader to deadlock. The REPL would hang with no output on launch. Fixed by removing the static import entirely. The/undofeature remains available viasrc/services/undoTracker.ts(wired into Edit/Write tools) but is no longer registered as a slash command to avoid the circular dependency.
- AtomCode intelligence fusion — Pangu CJK spacing, negative feedback detection, tool call loop detection, error file pre-injection, first-read full file
- OpenAI-compatible bridge adapter — Anthropic ↔ OpenAI format translation for DeepSeek/Qwen/GLM/Ollama/vLLM/LM Studio
- Code Graph — Regex-based symbol index + file dependency graph (TS/JS/Python/Go/Rust)
- Parallel File Edit — One sub-agent per file with sibling skeletons
- Workflow Engine — Structured markdown step execution with checks and dependencies
- Cross-session knowledge — Auto-writes
.legna/knowledge.mdon session end - Baseline builds — No-AVX binaries for older x64 CPUs (darwin-x64-baseline, linux-x64-baseline)
- Baseline (no-AVX) builds — New platform packages for older x64 CPUs without AVX instruction set support:
@legna-lnc/legnacode-darwin-x64-baseline— macOS Intel (pre-2011 or Hackintosh without AVX)@legna-lnc/legnacode-linux-x64-baseline— Linux x64 servers/VMs without AVX- Fixes
warn: CPU lacks AVX support, strange crashes may occurerror - Install:
npm i -g @legna-lnc/legnacode-darwin-x64-baseline(use directly, not via main package)
-
AtomCode intelligence fusion (Layer A) — Lightweight agent intelligence, zero new dependencies:
- Pangu CJK spacing — Auto-inserts spaces between CJK and ASCII in Markdown rendering
- Negative feedback detection — Detects frustration ("still broken"/"错了"/"まだ壊れ"), injects strategy-shift hint (EN/ZH/JA)
- Tool call loop detection — Same (tool, args) 3+ times → blocks. Resets per user message
- Error file pre-injection — Bash fail → extracts file paths from stderr, auto-reads first 30 lines
- First-read full file — First encounter ignores offset/limit, forces full read
-
OpenAI-compatible bridge adapter (Layer B1) — Full Anthropic ↔ OpenAI format translation:
- Message format:
tool_use↔tool_calls,tool_result↔role: "tool" - Tool schema:
input_schema↔function.parameters - JSON repair for weak models (markdown fences, trailing commas, unbalanced brackets)
- Supports: OpenAI, DeepSeek, Qwen, GLM, SiliconFlow, Ollama, vLLM, LM Studio
- Activate:
OPENAI_COMPAT_BASE_URL+OPENAI_COMPAT_API_KEYenv vars
- Message format:
-
Code Graph (Layer B2) — Regex-based symbol index + file dependency graph:
- Languages: TypeScript/TSX, JavaScript, Python, Go, Rust
- Incremental mtime updates, persisted to
<cwd>/.legna/.palace/graph.json - Wired: auto-builds on session start, injects file summaries into prefetch context
-
Parallel File Edit (Layer B3) — "One sub-agent per file" execution model:
- Target file full text + sibling skeletons + interface contracts
- Wired: integrated into
/dispatchskill prompt with parallel edit instructions
-
Workflow Engine (Layer B4) — Structured step execution:
- Markdown
## Step N:format with checks, failure handling, dependencies - Wired: WorkflowTool now parses steps, shows status, substitutes args
- Markdown
-
/undo command — Reverts the last file edit (Edit or Write tool):
- Tracks original content before each edit, max 20 entries per session
- New file creation → undo deletes the file
-
Cross-session knowledge persistence — Auto-writes
<cwd>/.legna/knowledge.md:- Extracts key decisions/actions from last 10 assistant messages on session end
- Appends timestamped entries, caps at 50KB
-
Enhanced compiler error detection — Extended error file pre-injection:
- Now matches compiler-style paths (
file.ts:42,file.py(10)) in addition to standard paths
- Now matches compiler-style paths (
- claude-mem memory intelligence fusion — Ported 5 lightweight techniques from claude-mem's persistent memory system into DrawerStore, zero new dependencies:
- Content-hash deduplication —
sha256(wing + room + content)with 30-second window prevents duplicate observations during rapid compaction cycles - Token economics tracking — Each drawer records
discoveryTokens(cost to create) andreadTokens(accumulated recall cost) for memory ROI analysis - Relevance feedback —
relevanceCountincremented on each search hit; frequently recalled memories get up to +100% importance boost viaimportance * (1 + 0.1 * min(count, 10)) - 90-day time decay —
max(0.3, 1.0 - age_days / 90)applied to both search similarity and importance ranking. Old memories fade but never fully disappear - Privacy tag filtering —
<private>...</private>content stripped to[REDACTED]before memory extraction. Zero config, just wrap sensitive text in tags
- Content-hash deduplication —
- Modified
src/memdir/vectorStore/types.ts— Drawer gainsdiscoveryTokens,readTokens,relevanceCount,contentHashfields - Modified
src/memdir/vectorStore/drawerStore.ts— Schema migration (4 new columns), content-hash dedup in upsert, relevance feedback in search, time decay in search + topByImportance - Modified
src/memdir/vectorStore/exchangeExtractor.ts—stripPrivate()applied before pair extraction
- OML skill crash fix — All 40 OML skills (16 superpowers + 5 orchestrators + 19 agents) returned
stringinstead ofContentBlockParam[]fromgetPromptForCommand, causingresult.filter is not a functioncrash on/ultrawork,/ralph,/autopilot, etc. Now wrapped asPromise<[{ type: 'text', text }]>. - Statusline writes to wrong config dir —
statuslineSetupagent hardcoded~/.claude/settings.jsonand~/.claude/statusline-command.sh. Fixed to~/.legna/.
- Plans moved to project-local — Default plan directory changed from
~/.legna/plans/to<cwd>/.legna/plans/. Plans now live alongside the project they belong to. - Auto-memory moved to project-local — Default auto-memory path changed from
~/.legna/projects/<slug>/memory/to<cwd>/.legna/memory/. First startup auto-migrates files from the legacy global path (non-destructive, never overwrites). - Compound engineering seamless fusion — Knowledge compounding from compound-engineering-plugin, injected into 3 existing automation points with zero new commands:
onPreCompress: high-value exchange pairs auto-written todocs/solutions/(opt-in viamkdir docs/solutions)prefetch: auto-searchesdocs/solutions/for past learnings when user asks related questionsmagicKeywords: deep scope detection (refactor/migrate/architecture) appends a lightweight compound hint
- Legacy path comments cleaned — Updated stale
~/.claude/projects/references in memdir, extractMemories, settings types
- OpenViking content tiering fusion — Ported L0/L1/L2 three-tier content grading from OpenViking's context database:
- Content Tiering — Each drawer auto-generates L0 (one-sentence summary, ~25 words) and L1 (core overview, ~200 words) at upsert time. L2 is the full verbatim content.
- Budget-aware wake-up —
wakeUp()now accepts a token budget (default 800) and greedily fills it with L1 content, degrading to L0 when budget is tight. - Budget-capped recall — New
recallWithBudget()method: L2→L1→L0 degradation strategy ensures recall never exceeds character budget. - CJK-aware token estimation —
estimateTokens()handles mixed CJK/Latin text. - SQLite schema migration — Existing DrawerStore databases auto-migrate with
ALTER TABLE ADD COLUMN. - Fixed recallByTopic() — Now passes actual query for vector ranking instead of empty string.
- Status messages moved to spinner line — autocompact / output truncated / interrupted status messages no longer insert system messages into the conversation; they now display temporarily on the spinner animation line, flashing briefly without polluting context
- ToolUseContext adds setSpinnerMessage — generic spinner text callback allowing the query loop to update spinner status at any time
- LegnaCode vs Claude Code comparison doc — added COMPARISON.md with 60+ item-by-item comparison across 9 categories
- mempalace memory architecture integration — ported mempalace core memory system, pure TypeScript implementation, zero external dependencies:
- DrawerStore — SQLite-persisted vector memory storage + WAL audit log, deterministic drawer ID (sha256 idempotent upsert)
- TF-IDF vectorizer — pure TS implementation (Porter stemming + cosine similarity), <10K drawer search <5ms
- 4-layer memory stack — L0 identity (~100 tokens) + L1 top drawers (~500-800 tokens) loaded every turn, L2/L3 recalled on demand. Per-turn tokens reduced from ~8K to ~800 (~88% savings)
- Temporal knowledge graph — SQLite entity-relation storage, supports triples with validity periods and point-in-time queries
- Room auto-classification — 6 categories (facts/decisions/events/discoveries/preferences/advice) with keyword scoring
- Exchange pair extractor — Q+A paired chunking + 5-category tag scoring (decisions/preferences/milestones/problems/emotional)
- Auto-migration — automatically migrates existing .legna/memory/*.md files to DrawerStore on first startup
- PreCompact memory save — automatically extracts high-value exchange pairs to DrawerStore before compaction, preventing memory loss
- Added
src/memdir/vectorStore/— complete vector memory system (8 files)types.ts— Drawer, SearchResult, MetadataFilter typestfidfVectorizer.ts— TF-IDF + Porter stemming + cosine similaritydrawerStore.ts— SQLite persistence + WAL + vector searchroomDetector.ts— content auto-classificationlayeredStack.ts— 4-layer memory stackknowledgeGraph.ts— temporal knowledge graphexchangeExtractor.ts— exchange pair extraction + tag scoringmigration.ts— .md → DrawerStore auto-migration
- Upgraded
src/memdir/providers/FileMemoryProvider.ts— DrawerStore + LayeredStack backend - Wired
src/services/compact/autoCompact.ts— calls onPreCompress before compaction
- verbose enabled by default — users now see full tool execution progress and status information by default
- Token/Timer instant display — removed 30-second delay, token count and elapsed time shown from second 1
- Autocompact status visible — displays "Compacting conversation context..." system message during conversation compaction
- Interrupt reason visible — shows abort reason on interruption (streaming and tool_execution phases)
- Output truncated retry prompt — displays retry progress during max output tokens recovery
- Tool execution logging — StreamingToolExecutor outputs current tool name and queue depth
- Microcompact/Snip logging — added debug logging for compaction operations
- ForkedAgent startup logging — outputs label and ID when child agent starts
- Apple Terminal notification logic fix — bell is now sent only when bell is not disabled (logic was previously inverted)
- MiniMax deep native integration — when using MiniMax models with
MINIMAX_API_KEYconfigured, automatically registers 6 native multimodal tools:MiniMaxImageGenerate— image generation (POST /v1/image_generation)MiniMaxVideoGenerate— video generation + async polling (POST /v1/video_generation)MiniMaxSpeechSynthesize— text-to-speech (POST /v1/t2a_v2)MiniMaxMusicGenerate— music generation (POST /v1/music_generation)MiniMaxVisionDescribe— image understanding VLM (POST /v1/coding_plan/vlm)MiniMaxWebSearch— web search (POST /v1/web_search)
- MiniMax auth command —
/auth-minimaxcommand to configure API key, persisted to~/.legna/minimax-credentials.json - MiniMax tool schema export —
schemaExport.tssupports exporting Anthropic-compatible tool schemas - MiniMax multimodal skill pack — 5 built-in skills (image/video/speech/music/pipeline) guiding AI to orchestrate multimodal workflows
- Smart model routing — heuristic routing to fast/default/strong model tiers based on prompt complexity
- Autonomous skill detection — detects repetitive tool call patterns and prompts users to save as reusable skills
- Context compression enhancements:
- Tool output pre-pruning — large tool_result blocks auto-trimmed before compact (head + tail preserved)
- Budget pressure injection — injects hints into tool results when context usage exceeds 80%, guiding the model to wrap up
- RPC subprocess tool execution — Unix Domain Socket RPC server + stub generator + code execution runner; AI-generated scripts can call back LegnaCode tools (Bash/Read/Write/Edit/Glob/Grep/WebFetch) via RPC, compressing multi-step operations into a single inference
- Memory Provider plugin system — abstract base class + registry + default FileMemoryProvider; supports one external provider running in parallel with built-in memory, full lifecycle (initialize/prefetch/syncTurn/shutdown) + optional hooks (onTurnStart/onSessionEnd/onPreCompress/onDelegation)
- Cross-session memory search —
/recallcommand searches historical session JSONL files with keyword matching + relevance ranking - Worker thread pool — large file operations / batch searches can be offloaded to worker threads, avoiding main thread blocking
- Added
src/tools/MiniMaxTools/— complete MiniMax multimodal tool directory (client, endpoints, 6 buildTool tools, conditional registration, schema export) - Added
src/services/rpc/— RPC subprocess tool execution (rpcServer.ts, stubGenerator.ts, codeExecutionRunner.ts) - Added
src/memdir/providers/— Memory Provider plugin system (MemoryProvider.ts abstract base class, FileMemoryProvider.ts default implementation, registry.ts registry) - Added
src/services/modelRouter.ts— task complexity estimation + model tier routing - Added
src/services/skillAutoCreate.ts— tool call pattern detector, integrated into toolExecution.ts - Added
src/services/compact/toolOutputPruner.ts— tool output pre-pruning, integrated into autoCompact.ts - Added
src/services/compact/budgetPressure.ts— context budget pressure injection, integrated into query.ts - Added
src/services/sessionSearch.ts— cross-session search engine - Added
src/commands/recall/—/recallcommand - Added
src/commands/auth/—/auth-minimaxcommand - Added
src/skills/builtin-minimax/— 5 MiniMax multimodal skill files - Added
src/utils/workerPool.ts— worker thread pool
- Resume session detection —
legna resumefailed to discover sessions written to<project>/.legna/sessions/since v1.3.0.getStatOnlyLogsForWorktrees()only scanned the global~/.legna/projects/; it now also scans the project-local sessions directory, consistent withfetchLogs()behavior - Interrupted diagnostics logging — added abort reason + call stack logging at
onCancel()andquery.tsinterrupt points; traceable under--verbosemode
- Priority-now interrupt visibility — when a queued command interrupts the current task, the command summary is logged to debug log instead of silently aborting
- Background task status visibility — footer pill shows real-time activity summary for a single background agent (latest tool + token stats); task completion notification includes progress statistics
src/utils/sessionStorage.ts—getStatOnlyLogsForWorktrees()Path A/B both include.legna/sessions/scanningsrc/query.ts— abort reason logging added at bothcreateUserInterruptionMessagecall sitessrc/screens/REPL.tsx—onCancel()call stack logging, priority-now useEffect logs command summarysrc/tasks/pillLabel.ts— single agent task displaysgetActivitySummary()real-time activitysrc/tasks/LocalMainSessionTask.ts—completeMainSessionTaskcaptures progress, notification includes statistics
- Windows Edit tool path separator false positive — fixed #7935: on Windows, after reading a file with forward slashes (
D:/path), Edit/MultiEdit tools reported "File has been unexpectedly modified" error. Root cause:path.normalize()does not always convert/to\in certain runtimes (Bun compiled binary + Git Bash/MINGW environment), causing FileStateCache key mismatchFileStateCacheaddednormalizeKey()— explicitly replaces/with the native separator (Windows:\) afterpath.normalize(), ensuringD:/fooandD:\fooalways hit the same cache entryexpandPath()addedensureNativeSeparators()— all returned paths force backslashes on Windows as a defensive fix
src/utils/fileStateCache.ts—normalizeKey()replaces barenormalize(), importssepsrc/utils/path.ts—ensureNativeSeparators()wraps allnormalize()/resolve()/join()return values
- SessionStart hook error — OML's SessionStart hook used
type: 'prompt', but the SessionStart phase has notoolUseContext(LLM call context), causing a guaranteed crash. Removed SessionStart hook; skill guidance is now exposed through skill descriptions - Windows alt-screen rendering flicker — in alt-screen mode,
fullResetSequence_CAUSES_FLICKERwas still triggered (viewport changes, scrollback detection, etc.), causing full-screen clear + redraw flicker. AddedaltScreenFullRedraw()method; in alt-screen mode, uses simpleCSI 2J + CSI H(erase screen + cursor home) instead ofclearTerminal's Windows legacy path - Windows drainStdin — previously skipped stdin draining entirely on Windows; residual mouse events caused input field corruption. Changed to flush buffered input events by toggling raw mode
src/ink/log-update.ts— 5fullResetSequence_CAUSES_FLICKERcall sites now checkaltScreen, addedaltScreenFullRedraw()methodsrc/ink/ink.tsx— WindowsdrainStdinalternative (toggle raw mode)src/plugins/bundled/oml/definition.ts— removed SessionStart hook, OML upgraded to 1.2.0
- OML Superpowers engineering discipline — integrated obra/superpowers core skills, enforcing strict software engineering workflows for AI
/verify— completion verification discipline: cannot claim completion without fresh evidence/tdd— TDD enforcement: RED-GREEN-REFACTOR, write tests before code/debug— 4-stage systematic debugging, question architecture after 3 failures/brainstorm— Socratic design: hard gate, no implementation allowed until design is approved/write-plan— break design into 2-5 minute tasks, zero placeholders/sdd— sub-agent driven development: implement → spec review → quality review, 3 stages/exec-plan— load plan file and execute tasks sequentially/dispatch— parallel sub-agent dispatch/code-review— dispatch reviewer sub-agent/worktree— Git worktree isolated development/finish-branch— branch wrap-up (merge/PR/keep/discard)
- SessionStart skill guidance — automatically injects OML skill guidance prompt at session start ("1% rule")
- OML plugin version upgraded to 1.1.0, 35 built-in skills total
src/plugins/bundled/oml/superpowers.ts— 11 engineering discipline skills + SessionStart guidancesrc/plugins/bundled/oml/definition.ts— appended superpowers skills + SessionStart hook
- OML (Oh-My-LegnaCode) smart orchestration layer — built-in oh-my-claudecode core functionality, works out of the box
- 5 orchestration skills:
/ultrawork(parallel execution),/ralph(persistent loop),/autopilot(fully autonomous),/ralplan(plan then execute),/plan-oml(structured planning) - 19 specialized agent skills:
/oml:explore,/oml:planner,/oml:architect,/oml:executor,/oml:verifier, etc. - Magic Keywords auto-detection: when prompt contains keywords like ultrawork/ralph/autopilot/ultrathink, orchestration directives are auto-injected (supports CJK and Vietnamese)
- Can be enabled/disabled via
/pluginUI (oml@builtin, enabled by default) OML_BUILTINfeature flag controls compile-time DCE
- 5 orchestration skills:
- Windows Terminal Fullscreen — automatically enables alt-screen mode in
WT_SESSIONenvironment, completely eliminating the cursor-up viewport yank bug (microsoft/terminal#14774). Covers WSL-in-Windows-Terminal.CLAUDE_CODE_NO_FLICKER=0to opt-out
src/plugins/bundled/oml/— OML plugin module (definition, skills, agents, magicKeywords)src/plugins/bundled/index.ts— registered OML builtin pluginsrc/utils/processUserInput/processUserInput.ts— magic keyword detection integration pointsrc/utils/fullscreen.ts— Windows Terminal fullscreen condition
- Disabled HISTORY_SNIP —
bunfig.tomlfeature flag set to false, compile-time DCE removes all snip-related code (SnipTool, snipCompact, snipProjection, force-snip command, attachments nudge). Auto-compact is unaffected; context management reverts to the original mechanism
- Windows Terminal streaming text — no longer disables streaming text display for all Windows; now only disabled under legacy conhost. Windows Terminal (detected via
WT_SESSIONenvironment variable) restores normal streaming rendering
- Snip-aware context window — 1M models are no longer prematurely snipped;
KEEP_RECENTchanged from hardcoded 10 to dynamic calculation (1M: 200, 500K: 100, 200K: 10) - Snip nudge frequency — 1M model nudge threshold raised from 20 to 100 messages
- branch command branding —
/branchresume prompt changed fromclaude -rtolegna -r - admin version fallback — displays correct version number when running from source
src/services/compact/snipCompact.ts— addedgetSnipThresholds(model)dynamic threshold function;snipCompactIfNeededandshouldNudgeForSnipsgained model parametersrc/query.ts/src/QueryEngine.ts/src/commands/force-snip-impl.ts— pass model parameter
- Project-local storage — sessions, skills, memory, rules, and settings all moved down to
<project>/.legna/directory- New sessions written to
<project>/.legna/sessions/<uuid>.jsonl, traveling with the project - Project-level skills/rules/settings/agent-memory/workflows unified under
.legna/ .legna/automatically added to.gitignore
- New sessions written to
- Global data migration — automatically migrates from
~/.claude/to~/.legna/on first startup (one-way)- Migrates settings.json, credentials, rules, skills, agents, plugins, keybindings, etc.
- Does not overwrite existing files; writes
.migration-donemarker on completion LEGNA_NO_CONFIG_SYNC=1to disable
legna migratecommand — manual data migration--globalmigrates global data only--sessionsmigrates current project sessions to local only--allmigrates everything (default)--dry-runpreview mode
- Three-level fallback reads — automatically searches
.legna/→.claude/→~/.legna/→~/.claude/when reading, zero-breakage backward compatibility
src/utils/legnaPathResolver.ts— unified path resolution (PROJECT_FOLDER/LEGACY_FOLDER/resolveProjectPath)src/utils/ensureLegnaGitignored.ts— auto-gitignore utilitysrc/utils/envUtils.ts— refactored global migration logic, removed old syncClaudeConfigToLegnasrc/utils/sessionStoragePortable.ts— added getLocalSessionsDir/getLegacyProjectsDir, refactored resolveSessionFilePathsrc/utils/sessionStorage.ts— session write path switched to project-localsrc/utils/listSessionsImpl.ts— multi-source scan and merge (local + global + legacy)src/commands/migrate/— CLI migration command
- Model Adapter Layer — unified third-party model compatibility framework, auto-detects model/endpoint and applies corresponding transforms
- MiMo (Xiaomi) adapter — api.xiaomimimo.com/anthropic, supports mimo-v2-pro/omni/flash (1M ctx)
- simplifyThinking + forceAutoToolChoice + normalizeTools + stripBetas + injectTopP(0.95) + stripCacheControl
- Handles content_filter / repetition_truncation stop_reason
- GLM (ZhipuAI) adapter — open.bigmodel.cn/api/anthropic, supports glm-5.1/5/5-turbo/4.7/4.6/4.5, etc.
- Full standard transform suite, server-side auto-caching (strip cache_control)
- DeepSeek adapter — api.deepseek.com/anthropic, supports deepseek-chat/coder/reasoner
- stripReasoningContent to avoid 400 errors, reasoner models auto-strip temperature/top_p
- Kimi (Moonshot) adapter — api.moonshot.ai/anthropic, supports kimi-k2/k2.5/k2-turbo, etc.
- Preserves cache_control (Kimi supports prompt caching discount), stripReasoningContent
- MiniMax adapter — api.minimaxi.com/anthropic (China) + api.minimax.io/anthropic (international)
- Supports MiniMax-M2.7/M2.5/M2.1/M2 full series (204K ctx), case-insensitive matching
- Deep compatibility: preserves metadata, tool_choice, cache_control, top_p (other adapters need strip/force)
- Only needs simplifyThinking + normalizeTools + stripBetas + stripUnsupportedFieldsKeepMetadata
src/utils/model/adapters/index.ts— adapter registry + match/transform dispatchsrc/utils/model/adapters/shared.ts— 12 shared transform functions (including new stripUnsupportedFieldsKeepMetadata)src/utils/model/adapters/{mimo,glm,deepseek,kimi,minimax}.ts— 5 provider adapterssrc/services/api/claude.ts— paramsFromContext() calls applyModelAdapter() at the end
- Sessions grouped by project — WebUI session history panel groups sessions by project path
- resume command with cd — copied resume command auto-includes
cdto project directory (Windows usescd /d) - Migration supports session history — config migration panel adds "also migrate session history" option, copies
projects/directory - Windows native compilation — Windows binary now compiled natively on Windows
- Migration panel field names corrected to match actual settings.json fields
- Windows compile script fix —
scripts/compile.tscorrectly handles.exesuffix on Windows, fixing the issue where compiled output file could not be found - Windows native binary recompiled and published — recompiled native
legna.exeusing Windows-native Bun, replacing the previous cross-compiled version
- postinstall auto-installs platform package — added
npm/postinstall.cjs; duringnpm install, automatically detects and installs the corresponding platform binary package from the official registry, completely solving the issue where optionalDependencies fails on Windows/mirror registries - Force official registry — postinstall uses
--registry https://registry.npmjs.orgto avoid 404 errors from unsynchronized mirrors (e.g., Taobao) - bin wrapper simplified — removed runtime auto-install logic, now guaranteed by postinstall
- Windows npm global install missing platform package — bin wrapper now auto-executes
npm install -gfor the corresponding platform package when it detects the package is not installed, no longer requiring manual user action - bin wrapper path lookup optimization — fixed scope directory path joining under global node_modules flat layout
- Completely fixed Windows external module error — cleared the compile external list; all stub modules (
@ant/*,@anthropic-ai/*, native napi) are now bundled into the binary, no longer depending on runtime external modules
- Windows external module error — removed
@anthropic-ai/sandbox-runtime,@anthropic-ai/mcpb,@anthropic-ai/claude-agent-sdk,audio-capture-napi,color-diff-napi,modifiers-napifrom the compile external list, letting stub code bundle directly into the binary; Windows no longer reportsCannot find module - bin wrapper multi-path lookup —
npm/bin/legna.cjsadded global node_modules flat path and nested path fallback, improving cross-platform npm global install compatibility - Version number automation — added
scripts/bump.tsfor one-click sync of version numbers across package.json, bunfig.toml, webui/package.json, and optionalDependencies - Release process automation — rewrote
scripts/publish.tsfor one-click bump → build webui → compile all → publish npm
- WebUI admin panel —
legna adminlaunches a browser-based admin panel (HTTP server + React SPA, default port 3456), visual management of both~/.claude/and~/.legna/config directories - Config editing — edit API endpoint, API key, model mapping (Opus/Sonnet/Haiku), timeout, permission mode, language, and all other settings.json fields in the browser
- Config file switching — lists settings*.json files, shows baseUrl/model, one-click swap to activate
- Session history browsing — parses all session JSONL files under the projects directory, displays project path, slug, time, prompt count, and copy resume command
- Config migration — Claude ↔ LegnaCode bidirectional migration, supports full or selective field migration (env/model/permissions, etc.), preview diff before migration
- npm cross-platform publishing — bin wrapper (.cjs), compile-all cross-platform compilation (darwin/linux/win32), publish script
- OAuth disabled —
isAnthropicAuthEnabled()returns false, removed OAuth login flow
- bin wrapper changed to
.cjsto fix ESMrequireerror optionalDependenciesplatform package versions aligned- Terminal restored on admin server exit with screen clear
- WebUI frontend inlined into binary, no longer depends on external
webui/dist/ - All package versions unified to 1.1.5
- Backend:
src/server/admin.ts— Bun.serve REST API, SPA inlined as string constant - Frontend:
webui/— React 18 + Vite + Tailwind SPA, tab-based scope switching - Inlining:
scripts/inline-webui.ts→src/server/admin-ui-html.ts - CLI:
src/entrypoints/cli.tsx—adminfast-path, zero extra module loading
- i18n multilingual completion — completed ~100 missing hardcoded English strings across 9 files, covering Spinner, teammate tree, pill labels, keyboard shortcut hints, Tips, and all other UI areas
- Built-in styled status bar — no external script configuration needed; displays directory, Git branch/sync status, model name (smart parsing to friendly name), colored context progress bar, and time by default; cross-platform compatible with Win/Mac/Linux
- Config auto-migration — automatically syncs
~/.claude/settings.jsonto~/.legna/settings.jsonon startup; prints warning without overwriting when both sides differ;LEGNA_NO_CONFIG_SYNC=1to disable
~/.legna/is now the preferred config directory,~/.claude/serves as compatibility fallback- Status bar model name auto-parsing:
Claude-Opus-4-6-Agentic[1m]→Opus 4.6 KeyboardShortcutHintcomponent "to" connector word internationalized (Chinese displays "→")
| File | Changes |
|---|---|
src/utils/i18n/zh.ts |
+50 translation entries |
src/components/Spinner.tsx |
7 i18n points |
src/components/PromptInput/PromptInputFooterLeftSide.tsx |
4 i18n points |
src/components/design-system/KeyboardShortcutHint.tsx |
"to" internationalized |
src/components/Spinner/teammateSelectHint.ts |
i18n |
src/components/Spinner/TeammateSpinnerTree.tsx |
6 i18n points |
src/components/Spinner/TeammateSpinnerLine.tsx |
7 i18n points |
src/tasks/pillLabel.ts |
all pill labels i18n |
src/services/tips/tipRegistry.ts |
25 tips i18n |
src/utils/builtinStatusLine.ts |
added: built-in status bar renderer |
src/components/StatusLine.tsx |
integrated built-in status bar |
src/utils/envUtils.ts |
config auto-migration logic |
- MONITOR_TOOL — MCP server health monitoring tool, supports start/stop/status operations, background periodic ping to detect connection status
- WORKFLOW_SCRIPTS — workflow automation system, reads
.claude/workflows/*.mdto execute multi-step workflows,/workflowscommand lists available workflows - HISTORY_SNIP — session history trimming, model can proactively call SnipTool to remove old messages and free context,
/force-snipfor forced trimming, UI retains full history while model view is filtered
- Added
src/tools/MonitorTool/MonitorTool.ts— MCP monitoring tool (buildTool construction) - Added
src/tasks/MonitorMcpTask/MonitorMcpTask.ts— monitoring background task lifecycle management - Added
src/components/permissions/MonitorPermissionRequest/— monitoring permission UI - Added
src/components/tasks/MonitorMcpDetailDialog.tsx— monitoring task detail dialog - Added
src/tools/WorkflowTool/WorkflowTool.ts— workflow execution tool - Added
src/tools/WorkflowTool/createWorkflowCommand.ts— workflow command scanning and registration - Added
src/tools/WorkflowTool/bundled/index.ts— built-in workflow registration entry - Added
src/tools/WorkflowTool/WorkflowPermissionRequest.tsx— workflow permission UI - Added
src/commands/workflows/—/workflowsslash command - Added
src/tasks/LocalWorkflowTask/LocalWorkflowTask.ts— workflow background task (kill/skip/retry) - Added
src/components/tasks/WorkflowDetailDialog.tsx— workflow detail dialog - Added
src/services/compact/snipCompact.ts— trim trigger logic (rewrote stub) - Added
src/services/compact/snipProjection.ts— model view message filtering - Added
src/tools/SnipTool/SnipTool.ts— model-callable trimming tool - Added
src/tools/SnipTool/prompt.ts— SnipTool constants and prompt - Added
src/commands/force-snip.ts—/force-snipslash command - Added
src/components/messages/SnipBoundaryMessage.tsx— trim boundary UI component - 3 feature flags flipped: MONITOR_TOOL, WORKFLOW_SCRIPTS, HISTORY_SNIP
- Cumulative 47/87 feature flags enabled
- TERMINAL_PANEL —
Alt+Jtoggles built-in terminal panel (tmux persistent), TerminalCapture tool can read terminal content - WEB_BROWSER_TOOL — built-in web browsing tool, fetches web page content and extracts text
- TEMPLATES — structured workflow template system,
legna new/list/replyCLI commands, job status tracking - BG_SESSIONS — background session management,
legna ps/logs/attach/kill/--bg, tmux persistence + PID file discovery
- Added
src/tools/TerminalCaptureTool/— tmux capture-pane tool (2 files) - Added
src/tools/WebBrowserTool/WebBrowserTool.ts— fetch + HTML text extraction - Added
src/jobs/classifier.ts— workflow turn classifier - Added
src/cli/handlers/templateJobs.ts— template CLI handler - Added
src/cli/bg.ts— background session CLI (5 handlers) - Added
src/utils/taskSummary.ts— periodic activity summary - Added
src/utils/udsClient.ts— active session enumeration - Cumulative 44/87 feature flags enabled
- CACHED_MICROCOMPACT — cache-aware tool result compression, deletes old tool_result via API cache_edits directive without breaking prompt cache
- AGENT_TRIGGERS —
/loopcron scheduling command + CronCreate/Delete/List tools, local scheduled task engine - TREE_SITTER_BASH — pure TypeScript bash AST parser (~4300 lines), used for command safety analysis
- TREE_SITTER_BASH_SHADOW — tree-sitter vs legacy parser shadow comparison mode
- MCP_SKILLS — auto-discovers and registers skill commands from MCP server
skill://resources - REACTIVE_COMPACT — auto-triggers context compression on 413/overload errors
- REVIEW_ARTIFACT —
/reviewcode review skill + ReviewArtifact tool
- Rewrote
src/services/compact/cachedMicrocompact.ts(from stub to 150+ line full implementation) - Added
src/services/compact/cachedMCConfig.ts— synchronous config module - Added
CACHE_EDITING_BETA_HEADERtosrc/constants/betas.ts - Added
src/skills/mcpSkills.ts,src/services/compact/reactiveCompact.ts - Added
src/tools/ReviewArtifactTool/,src/skills/bundled/hunter.ts - Cumulative 40/87 feature flags enabled
- AGENT_TRIGGERS —
/loopcron scheduling command, CronCreate/Delete/List tools, local scheduled task engine - TREE_SITTER_BASH — pure TypeScript bash AST parser, used for command safety analysis
- TREE_SITTER_BASH_SHADOW — tree-sitter vs legacy parser shadow comparison mode
- MCP_SKILLS — auto-discovers and registers skill commands from MCP server
skill://resources - REACTIVE_COMPACT — auto-triggers context compression on 413/overload errors
- REVIEW_ARTIFACT —
/reviewcode review skill + ReviewArtifact tool + permission UI
- Added
src/skills/mcpSkills.ts— MCP skill discovery module - Added
src/services/compact/reactiveCompact.ts— reactive compression strategy - Added
src/tools/ReviewArtifactTool/— code review tool - Added
src/components/permissions/ReviewArtifactPermissionRequest/— review permission UI - Added
src/skills/bundled/hunter.ts— /review skill registration - Cumulative 39/87 feature flags enabled
- ULTRAPLAN —
/ultraplanstructured multi-step planning command - VERIFICATION_AGENT — auto-spawns verification Agent after batch task completion
- AUTO_THEME — auto-switches dark/light theme by querying terminal background color via OSC 11
- AGENT_MEMORY_SNAPSHOT — Agent memory snapshots
- FILE_PERSISTENCE — file persistence tracking
- POWERSHELL_AUTO_MODE — PowerShell auto mode
- HARD_FAIL — strict error mode
- SLOW_OPERATION_LOGGING — slow operation logging
- UNATTENDED_RETRY — unattended retry
- ALLOW_TEST_VERSIONS — allow test versions
- Added
src/utils/systemThemeWatcher.ts— OSC 11 terminal theme detection and real-time monitoring - Cumulative 33/87 feature flags enabled
- COMMIT_ATTRIBUTION — tracks Claude's contribution ratio per commit, PR description auto-appends attribution trailer
- AWAY_SUMMARY — displays summary of what happened while user was away
- COMPACTION_REMINDERS — efficiency reminders during context compaction
- HOOK_PROMPTS — allows hooks to request user input
- BASH_CLASSIFIER — shell command safety classifier
- EXTRACT_MEMORIES — auto-extracts persistent memories from conversations
- SHOT_STATS — session statistics panel
- PROMPT_CACHE_BREAK_DETECTION — detects prompt cache invalidation
- ULTRATHINK — deep thinking mode
- MCP_RICH_OUTPUT — MCP tool rich text output
- CONNECTOR_TEXT — connector text enhancement
- NATIVE_CLIPBOARD_IMAGE — native clipboard image support
- NEW_INIT — improved project initialization flow
- DUMP_SYSTEM_PROMPT — debug system prompt export
- BREAK_CACHE_COMMAND —
/break-cachecommand - BUILTIN_EXPLORE_PLAN_AGENTS — built-in Explore/Plan Agents
- Added
src/utils/attributionHooks.ts,attributionTrailer.ts,postCommitAttribution.ts— three attribution modules
- QUICK_SEARCH —
Ctrl+Pquick file open in fullscreen mode,Ctrl+Shift+Fglobal symbol/content search - MESSAGE_ACTIONS — copy, edit, retry and other actions on messages in fullscreen mode
- FORK_SUBAGENT —
/fork <directive>session fork, child Agent inherits full conversation context and executes tasks in parallel - HISTORY_PICKER —
Ctrl+Ropens history search dialog, replacing the previous inline search
- Added
src/commands/fork/command module andUserForkBoilerplateMessageUI component
- BUDDY virtual pet companion —
/buddy hatchhatches an exclusive coding pet, 18 species, 5 rarities, random attributes/buddy hatchhatch ·/buddy petpet ·/buddy statsstats ·/buddy releaserelease- Pet comments in cute language based on conversation context, supports multilingual auto-switching
- Re-hatching after release gives a different pet (generation counter)
- TOKEN_BUDGET — use
+500koruse 2M tokensin prompts to set token budget, auto-tracks usage - STREAMLINED_OUTPUT — environment variable
CLAUDE_CODE_STREAMLINED_OUTPUT=trueenables streamlined output
- Build system feature flags fix —
scripts/build.tsnow correctly readsbunfig.toml's[bundle.features]and passes them to theBun.build()API; previously allfeature()calls defaulted tofalse
- Added
scripts/compile.tsreplacing barebun build --compile, ensuring compiled binary correctly applies feature flags - Added
src/buddy/companionObserver.tscontext-aware pet reaction system - Added
src/commands/buddy/complete command module
- Initial release: LegnaCode CLI v1.0.0
- Built on the Claude Code CLI open-source edition
- Brand adaptation and customization