🌐 中文文档
All notable changes to LegnaCode CLI will be documented in this file.
- 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