Imported from zhushipeng666/keil-c51-ai-mcu-platform (
AGENTS.md). Install upstream withnpx skills add zhushipeng666/keil-c51-ai-mcu-platform. Copyright stays with the author.
Project: keil_c51_build
Project Background
This project is a Keil C51 command-line build and flash automation tool with a small Node.js web dashboard. It wraps Keil uVision UV4.exe for 8051/C51 projects, streams build output to a browser UI, and includes Pester tests for the PowerShell build logic.
The current checked-in demo project is minimal: demo/project.uvproj defines one Keil 8051 target and demo/main.c writes 0x00 to port P1 forever.
There is also a draft design spec for upgrading this tool into an AI-driven MCU development platform for STC/AT89 8051-compatible chips.
Tech Stack
- Language: PowerShell, JavaScript, C, Windows batch
- Runtime: Windows PowerShell 5.1+, Node.js, Keil C51/uVision
- Compiler/build tool: Keil
UV4.exe - Test framework: Pester for PowerShell tests
- Web server: Node.js built-in
httpmodule, Server-Sent Events for streaming logs - Firmware target: Keil 8051 / C51
.uvprojprojects
Common Commands
- Start dashboard:
start.cmdornode server.js - Build default project:
build.cmdorpowershell -ExecutionPolicy Bypass -File .\build.ps1 - Build a specific project:
powershell -ExecutionPolicy Bypass -File .\build.ps1 -Project "E:\my51\led.uvproj" - Build a target with clean:
powershell -ExecutionPolicy Bypass -File .\build.ps1 -Target "Target 1" -Clean - Flash via Keil:
flash.cmdorpowershell -ExecutionPolicy Bypass -File .\flash.ps1 - Stream build output for the web UI:
powershell -ExecutionPolicy Bypass -File .\stream_build.ps1 - Run tests:
Invoke-Pester tests\
Project Architecture
Directory Structure
keil_c51_build/
build.ps1 Main UV4.exe build/flash wrapper with retry and exit-code mapping
stream_build.ps1 Web-oriented build wrapper that prints stream-friendly markers
flash.ps1 Thin wrapper around build.ps1 -Flash
build.cmd Windows launcher for build.ps1
flash.cmd Windows launcher for flash.ps1
start.cmd Windows launcher for node server.js
config.psd1 Default paths and retry settings
server.js Node HTTP server and embedded browser dashboard
demo/
project.uvproj Minimal Keil 8051 project file
main.c Minimal C51 firmware sample
docs/superpowers/specs/
2026-05-12-stc-ai-mcu-platform-design.md
tests/
build_functions.tests.ps1
config.tests.ps1
stream_build.tests.ps1
Entry Points
- CLI build entry:
build.ps1 - CLI flash entry:
flash.ps1 - Dashboard/server entry:
server.js - Browser UI: embedded HTML string at the bottom of
server.js - Configuration source:
config.psd1 - Default Keil project:
demo/project.uvproj
Current Server API
GET /api/stream: SSE log streamPOST /api/build: runsstream_build.ps1in build modePOST /api/flash: runsstream_build.ps1 -FlashPOST /api/cancel: terminates the running child processGET /api/config: returns parsedconfig.psd1valuesPOST /api/config: updatesUV4Path,ProjectPath, orProjectFileinconfig.psd1
Code Style & Conventions
- Keep scripts Windows-first; this project assumes PowerShell,
.cmd, and Windows paths. build.ps1uses coloredWrite-Hostoutput for interactive CLI use.stream_build.ps1uses plainWrite-Outputmarkers (ERROR:,EXIT_CODE:,RESULT:) for server parsing and SSE display.server.jsintentionally has no npm dependency file and uses Node built-in modules only.- Tests duplicate small pieces of script logic to avoid requiring Keil
UV4.exeduring test execution.
Key Decisions & Notes
config.psd1currently points toD:\Keil5_C51\UV4\UV4.exeand default projectE:\keil_c51_build\demo\project.uvproj.- Keil exit code
0means success,1means warnings,2+indicates errors/fatal conditions. build.ps1detects Flex license contention from the generated log and retries usingLicenseRetryMaxandLicenseRetryWait.server.jsallows only one running build/flash process at a time through therunningProcessguard.- The AI MCU platform design in
docs/superpowers/specs/2026-05-12-stc-ai-mcu-platform-design.mdis a draft/future plan, not the current implementation. - User approved the complete platformization route: stabilize current Keil build tooling, modularize the server, add device detection, add STC burning, add AI generation, add AI repair, and finally add a one-click AI pipeline. AI should have relatively broad project-level write permissions with snapshots and system-directory protections.
User Requirements
- Understand the project located at
E:\keil_c51_buildand summarize what it does. - Provide a complete optimization plan and implementation framework for the Keil C51 AI MCU platform, with AI present in each major part and fewer AI restrictions than a strict sandbox.
Session Log
2026-05-12 Design Approval Summary
- User approved the complete optimization direction for transforming the tool into an AI-assisted Keil C51/STC MCU workbench.
- Wrote the formal design spec to
docs/superpowers/specs/2026-05-12-keil-c51-ai-platform-optimization-design.md. - Captured the AI permission decision: default toward broad project-level AI write access, backed by snapshots, diff summaries, and system-directory protections.
2026-05-12 Session Summary
- Scanned the project root, scripts, demo Keil project, tests, Node server, and AI MCU design spec.
- Identified the current project as a Keil C51 build/flash automation tool with a Node-based SSE dashboard.
- Created this
AGENTS.mdbecause the project had no existing persistent project memory file.
2026-05-13 Session Summary — Phase 1 Complete
- Implemented Phase 1 of the AI MCU platform design: modularize and stabilize.
- Created
package.jsonwithnpm start,npm testscripts. - Created
lib/config.js— reads, validates, and updatesconfig.psd1with all new fields. - Created
lib/sse.js— SSE client management and broadcasting. - Created
lib/process-runner.js— process spawning, streaming, and Windows process-tree kill viataskkill /T /F. - Created
lib/build-runner.js— Keil C51 build task creation, output parsing, hex path resolution. - Updated
config.psd1with new fields: OutputDir, LogDir, SnapshotDir, DefaultChip, DefaultPort, BurnTool, PythonPath, OpenCodePath, AiMode, AiAllowProjectWrite, AiAllowToolEdit, AiMaxRepairRounds. - Refactored
server.jsto use modularlib/imports, added/api/envand/api/devicesendpoints, improved cancel with process-tree kill, serves static files frompublic/. - Separated frontend into
public/index.html,public/app.js,public/style.css(dark theme, device panel, env check, chip selector). - Created
hwdetect.ps1— WMI-based USB-TTL adapter scanner (CH340, CP210x, PL2303, FT232, etc.). - Created
tests/server.test.jswith 14 Node tests for config, build-runner, process-runner, sse. - All tests pass: 41/41 Pester + 14/14 Node.
- Created directories:
lib/,public/,logs/,snapshots/,scripts/,tools/. - Next: Phase 2 — STC burning via
burn.py,/api/chip/detect,/api/burn, and UI integration.
2026-05-13 Session Summary — Phase 2 Complete
- Created
tools/burn.py— stcgal Python wrapper with detect, flash, info, list-chips subcommands, JSON output. - Added
POST /api/chip/detect— runstools/burn.py detect --portand returns chip info (model, protocol, flash size). - Added
POST /api/burn— streams stcgal flash output to SSE, returns exit code and status. - Added
GET /api/chip/list-chips— returns supported chip models and names. - Added burn panel to UI: port selector (auto-populated from device scan), chip type picker, detect button, STC burn button.
- Created
scripts/burn.ps1— CLI PowerShell helper for burn.py. - Created
tests/burn.test.js— 4 Node tests for burn.py script existence, list-chips, detect, flash (graceful failure without hardware). - All tests pass: 41/41 Pester + 18/18 Node.
- Next: Phase 3 — AI code generation (
agent/).
2026-05-13 Session Summary — Phase 3 Complete
- Created
agent/generate.js— AI code generation core module with prompt building, snapshot/diff safety, and opencode invocation. - Created
agent/templates/default.candagent/templates/stc89c52rc.c— chip-specific C51 code templates. - Added
POST /api/ai/generate— accepts{prompt, chip}, snapshots project, calls opencode, computes diff, streams to SSE. - Respects
AiModeconfig:strictblocks generation,project/openallows it. - Added AI generation panel to UI: textarea prompt input, chip selector, generate button.
- Created
tests/agent.test.js— 7 Node tests for template loading, chip info, prompt building, snapshot, diff. - All tests pass: 41/41 Pester + 25/25 Node.
- Next: Phase 4 — AI build repair (
agent/repair.js).
2026-05-13 Session Summary — Phase 4 + 5 Complete
- Installed stcgal 1.10 + pyserial 3.5 (STC burn now fully functional).
- Fixed
demo/project.uvprojto Keil-compatible format (SchemaVersion 1.1, MCS-51, correct Groups/TargetOption). - Fixed
demo/main.cUTF-8 BOM issue (C51 compiler rejects BOM). - Fixed
build.ps1encoding (UTF-8 BOM for PowerShell 5.1). - Fixed opencode invocation:
exec()with absolute path, positional args, ANSI escape stripping. - Created
agent/repair.js— AI-powered build error repair with retry loop (up to N rounds). - Created
agent/task-pipeline.js— end-to-end pipeline: build → AI repair → rebuild → flash. - Added
POST /api/pipeline— one-click AI pipeline endpoint. - Added "一键流水线" button to UI.
- All tests pass: 41/41 Pester + 25/25 Node.
- Platform is fully operational: compile, flash, STC burn, AI generate, AI repair, pipeline.
2026-05-13 Session Summary — AI Invocation Root-Cause Fix
- Root cause for AI generation crashes/hangs: Windows cannot
spawn()npm.cmdshims directly (EINVAL), passing the full AI prompt as one command-line argument is fragile for long multiline prompts, andopencode run --filetreats following positionals as more file paths. - Fixed AI invocation by resolving
opencode.cmdto the Node launcher script (node_modules/opencode-ai/bin/opencode) and running it withspawn('node', args). - Fixed long prompt handling by writing the full generation/repair task to a task file and invoking
opencode run <short instruction> --dangerously-skip-permissions --file <task-file>. - Added regression tests for
.cmdshim resolution, permission flag ordering, file-based AI task prompts, and the requiredmessage before --fileargument order. - Replaced STC burn's brittle
commandOverridepath with directrunPython(tools/burn.py, args)execution. - Later root cause for UI hanging at "AI 生成代码中": opencode successfully modified source, then tried to run UV4/build verification itself; that Keil command hung, so the AI child process never exited.
- Fixed AI prompts to explicitly forbid shell/build/flash/hardware commands; generation and repair now only modify source files, while platform build/pipeline buttons handle verification.
- Added
--pureto opencode invocation to isolate it from global plugins/session state. - Fixed final AI hang cause:
spawnProcess()opened a stdin pipe for opencode and did not close it; opencode could wait silently for stdin EOF.runOpenCode()now setscloseStdin: true. - Added process inactivity watchdog; silent child processes are killed after timeout, and AI generation warns after 60 seconds with no output instead of hanging forever.
- Corrected Keil flash semantics: UV4
-fexit code 0 only means the Keil Flash command completed, not that hardware was connected or MCU flash was verified. UI now labels it "Keil Flash 命令" and logs a warning recommending STC serial burn for STC chips. - Improved
start.cmdto open the browser after a short delay usingStart-Process. - Removed unused server/agent imports after the AI invocation refactor.
- Verification: Node tests pass 36/36, Pester tests pass 41/41, direct
runOpenCode()emits output, modifiesdemo/main.c, and exits 0; actual Keil build succeeds.
2026-05-14 Session Summary — Project Cleanup
- Added
README.mdwith quick start, commands, project layout, config notes, and flash semantics. - Added
.gitignorefor logs, AI snapshots, Keil generated outputs, user session files, local env files, and editor/OS noise. - Added
scripts/clean.ps1, a safe cleanup helper that defaults to dry-run and only removes candidates when-Applyis passed. - Added
tests/clean.test.jsto verify the cleanup script exists and dry-run mode does not delete generated output candidates. - No existing logs, snapshots, HEX files, or Keil outputs were deleted during cleanup.
- Verification: Node tests pass 38/38, Pester tests pass 41/41, actual Keil build succeeds.