openpencil/apps/cli/src/index.ts
Kayshen Xu 52efa884e6 V0.7.1 (#102)
* fix(desktop,web): rebuild Electron dev sync + bitmap dragging fix on v0.7.1 (#99)

Re-applies b046a0d from the closed PR #97 now that the base is v0.7.1.
Original conflict against v0.7.0 came from the release branch churn —
the cherry-pick onto v0.7.1 applies cleanly.

Keeps dev-startup, sync-noise, and bitmap-dragging fixes; drops the
loopback proxy helper scripts upstream rejected in PR #92. Readiness
probe now does direct socket checks inside the existing dev entrypoint;
sync hardening stays focused on request diagnostics, backpressure, and
drag-time clip-rect correctness.

Original commit: b046a0d
Supersedes: #97 (closed, head branch deleted)

Co-authored-by: Rais <vdcoolzi@gmail.com>

* fix(canvas): use ImageFill.url in skia-interaction test

The image-backed rectangle fixture in the skia-interaction test used
`{ type: 'image', src: '…' }`, but `ImageFill` in pen-types declares
the field as `url`. `npx tsc --noEmit` flagged it as TS2352 on the
`as PenNode` cast. One-word rename.

The squash-merge of #99 captured an earlier snapshot that did not
include this fix, so re-apply directly on v0.7.1.

* feat(cli): add `op install` / `op uninstall` for openpencil-skill

Bundle skill files at build time (scripts/bundle-skill.ts → skill-bundle.json)
so users without GitHub access can install directly. Falls back to git clone
when the bundle is empty.

Supports auto-detection of: Claude Code, Codex, Cursor, Gemini CLI, OpenCode.
CI workflows updated to checkout openpencil-skill before cli:compile.

* fix(panels): allow reparenting nodes into rectangle in layer panel

CONTAINER_TYPES was missing 'rectangle', preventing drag-drop into
rectangles even though the data model (ContainerProps) and store
(moveNode) both support it.

* fix(agent,ai): tool_exec reset + insert_node with after + move_node + CRUD tools

- fix(agent): reset StreamingToolExecutor between turns — prevents stale
  tool_use IDs that caused 400 errors on multi-turn tool calls (MiniMax etc.)
- feat(ai): add insert_node "after" parameter — auto-resolves sibling's
  parent and position for intuitive node insertion
- feat(ai): add move_node and insert_node to CRUD tool set
- feat(ai): add Chinese keywords (增加/添加/插入) to design intent detection
- fix(ai): insert_node uses addNode directly for existing parents instead
  of streaming pipeline, fixing parent resolution

* feat(ai): route CRUD intents to lightweight prompt and tool set

CRUD operations (read/update/delete) now get a focused system prompt
without design generation instructions, and use getCrudToolDefs()
(which includes insert_node and move_node) instead of the full design set.

* fix(agent,mcp): submodule update + MCP tool improvements

- Update agent-native submodule (tool_exec reset, HTTP error diagnostics)
- Improve MCP tool descriptions and parameter schemas
- Enhance agent.ts error handling

* feat(ai): add PenNode examples to CRUD prompt for complete node generation

The CRUD system prompt now includes button and text node examples
showing the full structure (fills, children, icons, layout) so models
generate complete nodes instead of empty frames.

* Update agent-native submodule to commit f9633a8, ensuring compatibility with recent changes and improvements in the agent's functionality.

* fix(ci,agent): generate skill-bundle before type check + fix moveNode arg

- Add `bun run cli:bundle-skill` step in CI before `tsc --noEmit` so
  skill-bundle.json exists when type-checking the CLI
- Fix moveNode index parameter: default to -1 when undefined

* fix(ci): add pen-engine and pen-react to npm publish workflow

Insert pen-engine and pen-react in topological order between
pen-renderer and pen-mcp so they are published before pen-sdk.

* docs: add MIT LICENSE and README to all packages

- Add MIT LICENSE to pen-ai-skills, pen-core, pen-engine, pen-figma,
  pen-mcp, pen-react, pen-renderer, pen-sdk, pen-types
- Add README.md to pen-engine, pen-react, pen-mcp, pen-ai-skills

* docs: comprehensive package metadata, README, CLAUDE.md, and LICENSE

- Add author, license, repository, bugs, homepage to all package.json
- Homepage points to each package's own directory on GitHub
- Rewrite README for pen-engine, pen-react, pen-mcp, pen-ai-skills
  with full API docs, usage examples, and feature tables
- Add CLAUDE.md to pen-types, pen-core, pen-engine, pen-figma,
  pen-mcp, pen-react, pen-renderer, pen-sdk
- Add MIT LICENSE to all packages
- Update root CLAUDE.md with index of all sub-CLAUDE.md files
- Fix git URL from nicepkg → ZSeven-W

* docs: package metadata, README, LICENSE, and CLAUDE.md for all packages

- Add author, license, repository, bugs, homepage to all package.json
- Homepage points to each package's own directory on GitHub
- Rewrite README for pen-engine, pen-react, pen-mcp, pen-ai-skills
  with full API docs, usage examples, and feature tables
- Add MIT LICENSE to all packages missing it
- Add CLAUDE.md to pen-types
- Update root CLAUDE.md with index of all sub-CLAUDE.md files
- Fix git URL from nicepkg to ZSeven-W

* docs: rewrite README for pen-core, pen-figma, pen-renderer, pen-sdk

Comprehensive READMEs with full API reference, usage examples,
feature tables, and architecture overview for each package.

* feat(acp): acpAgents store — persist, hydrate, CRUD actions

* feat(acp): pen-acp package + agent settings types + store

- pen-acp/types.ts: AcpAgentConfig, AcpAgentInfo, AcpConnectResult, AcpConnectionState
- pen-acp/client.ts: connectAcpAgent (local stdio + remote WebSocket), disconnectAcpAgent
- pen-acp/event-adapter.ts: acpUpdateToSSE (ACP session/update → SSE events)
- agent-settings.ts: AcpAgentConfig type, widen ModelGroup/GroupedModel.provider
- agent-settings-store.ts: acpAgents persist/hydrate/CRUD + acpConnectionStatus

* fix(acp): remove unused type imports in client.ts

* feat(acp): ACP agent settings UI — form, cards, connect/disconnect

* feat(acp): add AcpAgentSection to Agents settings tab

* refactor(agent): AgentSession as discriminated union (native | acp)

* feat(acp): connection manager — connect, disconnect, cleanup

* feat(acp): connect/disconnect API route

* feat(acp): ACP branch in agent result handler

* fix(agent): use NativeAgentSession type for runDelegateMember

* feat(acp): ACP prompt SSE stream in agent endpoint

* feat(acp): ACP agents in model list + request routing

* i18n(acp): add ACP agent translation keys for all 15 locales

* fix(i18n): translate ACP keys for all 15 locales + fix missing key references

- zh.ts/zh-tw.ts: proper Chinese translations (Agent not translated)
- All other locales: translated from English placeholders
- Fix acp.add → acp.addAgent, acp.disconnected → acp.notConnected

* chore: bump agent-native submodule — surface upstream HTTP errors

* feat(acp,build,codegen): comprehensive fixes for ACP integration + prod build

ACP agent integration:
- Rewrite system prompt to enforce layered design pipeline (get_design_prompt
  → design_skeleton → design_content → design_refine) for higher quality output
- Use correct PenNode field names: content for text, iconFontName for icons
- Strict JSON rules to prevent empty-key / trailing-comma / smart-quote errors
- Prefer icon_font over path icons (standalone MCP has no hooks registered)
- Auto-start MCP server before ACP session (lazy bootstrap)
- Auto-reconnect ACP on stale connection (dev server restart scenario)
- Auto-approve tool permission requests (trust model: user configured agent)
- Use type: 'http' + headers: [] for MCP server config (SDK schema requirement)
- Persist ACP connections via globalThis so they survive Vite HMR

Build / packaging:
- Place agent-native under server/node_modules for Nitro to resolve at runtime
- Copy agent_napi.node to napi/ as extraResource
- Kill detached MCP server on Electron quit (before-quit + dev SIGINT handlers)
- Capture drag-dropped filesystem path via webUtils.getPathForFile so recent
  files entries are clickable after reopening

Codegen:
- Compact JSON (no indent) + strip noise fields (id, parentId, default rotation
  /opacity/visible, layout-managed x/y) to reduce request body size by 60-70%
  so proxies don't reject with 403 'Request not allowed'

MCP batch_design robustness:
- splitOperations tracks bracket/quote balance → multi-line JSON now works
- Auto-normalize fill/stroke shorthand forms
- Collect per-line errors instead of aborting whole batch
- Repair empty keys, trailing commas, smart quotes in JSON
- Bindless I(...) form supported (auto-generates binding)

UI:
- ModelDropdown / ChatInput handle ACP model icons (Plug)
- Reset streaming state + abort controller on ACP error path
- Strip h3 JSON error wrapper so chat shows clean error messages
- ACP agent settings form + cards + connect/disconnect

* fix(types): resolve TS errors in CI typecheck

- acp-connection-manager.ts: correct relative import path (utils/ → src/types)
- ai-chat-handlers.ts: cast currentProvider to AIProviderType at design-generator callsites
- ai-chat-panel.tsx: explicitly type groups as ModelGroup[] so 'acp' string fits the widened union
- acp-agent-settings.tsx: cast window through unknown for Record lookup
- electron.d.ts: add getPathForFile to ElectronAPI declaration
- builtin-provider-presets.ts: drop now-redundant config.preset !== 'custom' check (handled by early return)
- pen-acp/client.ts: cast Writable/Readable.toWeb to typed Streams; coerce nullish agentInfo fields to undefined

---------

Co-authored-by: Rais <vdcoolzi@gmail.com>
2026-04-13 21:30:23 +08:00

456 lines
13 KiB
JavaScript

#!/usr/bin/env node
import pkg from '../package.json';
import { setPretty, output, outputError } from './output';
// --- Arg parsing ---
interface ParsedArgs {
command: string;
positionals: string[];
flags: Record<string, string | boolean>;
}
function parseArgs(argv: string[]): ParsedArgs {
const args = argv.slice(2);
const positionals: string[] = [];
const flags: Record<string, string | boolean> = {};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg.startsWith('--')) {
const key = arg.slice(2);
const next = args[i + 1];
if (next && !next.startsWith('--')) {
flags[key] = next;
i++;
} else {
flags[key] = true;
}
} else {
positionals.push(arg);
}
}
return {
command: positionals[0] ?? '',
positionals: positionals.slice(1),
flags,
};
}
// --- Help ---
const HELP = `OpenPencil CLI v${pkg.version}
Usage: op <command> [options]
App:
op start [--desktop|--web] Launch OpenPencil
op stop Stop running instance
op status Check if running
Document:
op open [file.op] Open file or connect to live canvas
op save <file.op> Save current document to file
op get [--type X] [--name Y] [--id Z] [--depth N]
op selection Get current canvas selection
Nodes:
op insert <json> [--parent P] [--index N] [--post-process]
op update <id> <json> [--post-process]
op delete <id>
op move <id> --parent <P> [--index N]
op copy <id> [--parent P]
op replace <id> <json> [--post-process]
Design:
op design <dsl|@file|->
op design:skeleton <json|@file|->
op design:content <section-id> <json|@file|->
op design:refine --root-id <id>
Read Nodes:
op read-nodes [ids] [--depth N] [--vars] [--page P] [--file F]
ids: comma-separated node IDs (omit to read all)
Codegen Pipeline:
op codegen:plan <plan-json|@file|->
op codegen:submit <planId> <chunk-result|@file|->
op codegen:assemble <planId> [--framework react]
op codegen:clean <planId>
Variables & Themes:
op vars Get variables
op vars:set <json> Set variables
op themes Get themes
op themes:set <json> Set themes
op theme:save <file.optheme> Save theme preset
op theme:load <file.optheme> Load theme preset
op theme:list [dir] List theme presets
Pages:
op page list
op page add [--name N]
op page remove <id>
op page rename <id> <name>
op page reorder <id> <index>
op page duplicate <id>
Import:
op import:svg <file.svg> Import SVG file
op import:figma <file.fig> Import Figma file
Skill:
op install [--target T] Install openpencil-skill for AI agents
op uninstall [--target T] Uninstall openpencil-skill
Targets: claude, codex, cursor, gemini, opencode (auto-detected if omitted)
Layout:
op layout [--parent P] [--depth N]
op find-space [--direction right|bottom|left|top]
Arguments that accept JSON or DSL can be passed as:
<value> Inline string
@filepath Read from file (e.g. @design.txt)
- Read from stdin (e.g. cat design.txt | op design -)
Global Flags:
--file <path> Target .op file (default: live canvas)
--page <id> Target page ID
--pretty Human-readable JSON output
--help Show this help
--version Show version
`;
// --- Main ---
async function main(): Promise<void> {
const { command, positionals, flags } = parseArgs(process.argv);
if (flags.pretty) setPretty(true);
if (flags.help || command === 'help') {
process.stdout.write(HELP);
return;
}
if (flags.version || command === 'version') {
output({ version: pkg.version });
return;
}
if (!command) {
process.stdout.write(HELP);
return;
}
const globalFlags = {
file: flags.file as string | undefined,
page: flags.page as string | undefined,
};
switch (command) {
// --- App ---
case 'start': {
const { cmdStart } = await import('./commands/app');
await cmdStart({ desktop: !!flags.desktop, web: !!flags.web });
break;
}
case 'stop': {
const { cmdStop } = await import('./commands/app');
await cmdStop();
break;
}
case 'status': {
const { cmdStatus } = await import('./commands/app');
await cmdStatus();
break;
}
// --- Document ---
case 'open': {
const { cmdOpen } = await import('./commands/document');
await cmdOpen(positionals, globalFlags);
break;
}
case 'save': {
const { cmdSave } = await import('./commands/document');
await cmdSave(positionals, globalFlags);
break;
}
case 'get': {
const { cmdGet } = await import('./commands/document');
await cmdGet(positionals, {
...globalFlags,
type: flags.type as string | undefined,
name: flags.name as string | undefined,
id: flags.id as string | undefined,
depth: flags.depth as string | undefined,
parent: flags.parent as string | undefined,
});
break;
}
case 'selection': {
const { cmdSelection } = await import('./commands/document');
await cmdSelection({ ...globalFlags, depth: flags.depth as string | undefined });
break;
}
// --- Nodes ---
case 'insert': {
const { cmdInsert } = await import('./commands/nodes');
await cmdInsert(positionals, {
...globalFlags,
parent: flags.parent as string | undefined,
index: flags.index as string | undefined,
postProcess: !!flags['post-process'],
});
break;
}
case 'update': {
const { cmdUpdate } = await import('./commands/nodes');
await cmdUpdate(positionals, {
...globalFlags,
postProcess: !!flags['post-process'],
});
break;
}
case 'delete': {
const { cmdDelete } = await import('./commands/nodes');
await cmdDelete(positionals, globalFlags);
break;
}
case 'move': {
const { cmdMove } = await import('./commands/nodes');
await cmdMove(positionals, {
...globalFlags,
parent: flags.parent as string | undefined,
index: flags.index as string | undefined,
});
break;
}
case 'copy': {
const { cmdCopy } = await import('./commands/nodes');
await cmdCopy(positionals, {
...globalFlags,
parent: flags.parent as string | undefined,
});
break;
}
case 'replace': {
const { cmdReplace } = await import('./commands/nodes');
await cmdReplace(positionals, {
...globalFlags,
postProcess: !!flags['post-process'],
});
break;
}
// --- Design ---
case 'design': {
const { cmdDesign } = await import('./commands/design');
await cmdDesign(positionals, {
...globalFlags,
postProcess: flags['post-process'] !== false ? true : undefined,
canvasWidth: flags['canvas-width'] as string | undefined,
});
break;
}
case 'design:skeleton': {
const { cmdDesignSkeleton } = await import('./commands/design');
await cmdDesignSkeleton(positionals, globalFlags);
break;
}
case 'design:content': {
const { cmdDesignContent } = await import('./commands/design');
await cmdDesignContent(positionals, {
...globalFlags,
canvasWidth: flags['canvas-width'] as string | undefined,
});
break;
}
case 'design:refine': {
const { cmdDesignRefine } = await import('./commands/design');
await cmdDesignRefine(positionals, {
...globalFlags,
rootId: flags['root-id'] as string | undefined,
canvasWidth: flags['canvas-width'] as string | undefined,
});
break;
}
// --- Read Nodes ---
case 'read-nodes': {
const { cmdReadNodes } = await import('./commands/read-nodes');
await cmdReadNodes(positionals, {
file: globalFlags.file,
page: globalFlags.page,
depth: flags.depth as string | undefined,
vars: !!flags.vars,
});
break;
}
// --- Codegen Pipeline ---
case 'codegen:plan': {
const { cmdCodegenPlan } = await import('./commands/codegen');
await cmdCodegenPlan(positionals, globalFlags);
break;
}
case 'codegen:submit': {
const { cmdCodegenSubmit } = await import('./commands/codegen');
await cmdCodegenSubmit(positionals, globalFlags);
break;
}
case 'codegen:assemble': {
const { cmdCodegenAssemble } = await import('./commands/codegen');
await cmdCodegenAssemble(positionals, {
...globalFlags,
framework: flags.framework as string | undefined,
});
break;
}
case 'codegen:clean': {
const { cmdCodegenClean } = await import('./commands/codegen');
await cmdCodegenClean(positionals, globalFlags);
break;
}
// --- Variables & Themes ---
case 'vars': {
const { cmdVars } = await import('./commands/variables');
await cmdVars(globalFlags);
break;
}
case 'vars:set': {
const { cmdVarsSet } = await import('./commands/variables');
await cmdVarsSet(positionals, { ...globalFlags, replace: !!flags.replace });
break;
}
case 'themes': {
const { cmdThemes } = await import('./commands/variables');
await cmdThemes(globalFlags);
break;
}
case 'themes:set': {
const { cmdThemesSet } = await import('./commands/variables');
await cmdThemesSet(positionals, { ...globalFlags, replace: !!flags.replace });
break;
}
case 'theme:save': {
const { cmdThemeSave } = await import('./commands/variables');
await cmdThemeSave(positionals, globalFlags);
break;
}
case 'theme:load': {
const { cmdThemeLoad } = await import('./commands/variables');
await cmdThemeLoad(positionals, globalFlags);
break;
}
case 'theme:list': {
const { cmdThemeList } = await import('./commands/variables');
await cmdThemeList(positionals);
break;
}
// --- Pages ---
case 'page': {
const subCmd = positionals[0];
const subArgs = positionals.slice(1);
switch (subCmd) {
case 'list': {
const { cmdPageList } = await import('./commands/pages');
await cmdPageList(globalFlags);
break;
}
case 'add': {
const { cmdPageAdd } = await import('./commands/pages');
await cmdPageAdd(subArgs, { ...globalFlags, name: flags.name as string | undefined });
break;
}
case 'remove': {
const { cmdPageRemove } = await import('./commands/pages');
await cmdPageRemove(subArgs, globalFlags);
break;
}
case 'rename': {
const { cmdPageRename } = await import('./commands/pages');
await cmdPageRename(subArgs, globalFlags);
break;
}
case 'reorder': {
const { cmdPageReorder } = await import('./commands/pages');
await cmdPageReorder(subArgs, globalFlags);
break;
}
case 'duplicate': {
const { cmdPageDuplicate } = await import('./commands/pages');
await cmdPageDuplicate(subArgs, globalFlags);
break;
}
default:
outputError(
`Unknown page subcommand: "${subCmd}". Use: list, add, remove, rename, reorder, duplicate`,
);
}
break;
}
// --- Import ---
case 'import:svg': {
const { cmdImportSvg } = await import('./commands/import');
await cmdImportSvg(positionals, {
...globalFlags,
parent: flags.parent as string | undefined,
});
break;
}
case 'import:figma': {
const { cmdImportFigma } = await import('./commands/import');
await cmdImportFigma(positionals, {
...globalFlags,
out: flags.out as string | undefined,
});
break;
}
// --- Skill install ---
case 'install': {
const { cmdInstall } = await import('./commands/install');
cmdInstall({ target: flags.target as string | undefined });
break;
}
case 'uninstall': {
const { cmdUninstall } = await import('./commands/install');
cmdUninstall({ target: flags.target as string | undefined });
break;
}
// --- Layout ---
case 'layout': {
const { cmdLayout } = await import('./commands/layout');
await cmdLayout({
...globalFlags,
parent: flags.parent as string | undefined,
depth: flags.depth as string | undefined,
});
break;
}
case 'find-space': {
const { cmdFindSpace } = await import('./commands/layout');
await cmdFindSpace({
...globalFlags,
direction: flags.direction as string | undefined,
width: flags.width as string | undefined,
height: flags.height as string | undefined,
});
break;
}
default:
outputError(`Unknown command: "${command}". Run "op --help" for usage.`);
}
}
main().catch((err) => {
outputError(err instanceof Error ? err.message : String(err));
});