Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Add npm run create to build an avatar from an image with Codex
shinshin86f8599571a0c3
diff --git a/README.ja.md b/README.ja.mdindex ad01f5a..35de9b9 100644--- a/README.ja.md+++ b/README.ja.md@@ -52,6 +52,20 @@ npm run dev| Claude Code | Claude Opus 5.5 || Codex | GPT-6.1 Sol |+#### Codex でコマンド1つで作る++[Codex CLI](https://github.com/openai/codex) をインストールしてサインインしていれば、次のコマンド1つで+プロジェクトの作成、Codex によるエージェントガイドの実行(途中の質問なし)、完成したアバターをエディタで開くところまで進みます。++```sh+npm run create -- /path/to/your-image.png+```++通常は数十分かかります。Codex のメモは `projects/<name>/HANDOVER.md` に書き出されます。+Codex は `--approve-for-me` 付きで動くため、ポーズ確認用の Chromium など sandbox の外でツールを動かす許可は、+あなたの代わりに自動レビューが判断します。`--variants` を付けると閉じ目と口の形も描かせます。+このとき画像とマスクが Codex の画像生成に送られます。オプションは `npm run create -- --help` で確認できます。+### 2. プロジェクトを開いて確認するエディタを起動し(`npm run dev`)、「プロジェクトを開く」の一覧から作ったプロジェクトを選びます。「ポーズ確認」で顔の向きや傾き、目の開閉を確かめ、「口の動き」では「ゆったり」「キビキビ」などを選んで口パクを試します。「細かく調整する」で口の大きさや閉じ方を調整し、音声ファイルでも確認できます。diff --git a/README.md b/README.mdindex 3cd23cd..f0cc54d 100644--- a/README.md+++ b/README.md@@ -72,6 +72,22 @@ Recommended setups:| Claude Code | Claude Opus 5.5 || Codex | GPT-6.1 Sol |+#### One command with Codex++With the [Codex CLI](https://github.com/openai/codex) installed and signed in, one command+creates the project, has Codex follow the agent guide without questions and opens the editor+on the result:++```sh+npm run create -- /path/to/your-image.png+```++It usually takes tens of minutes. Codex writes its notes to `projects/<name>/HANDOVER.md`.+It runs with `--approve-for-me`, so its requests to run tools outside its sandbox, such as+Chromium for the pose review, are reviewed automatically instead of by you. Add `--variants`+to have it draw closed eyes and mouth shapes as well; this sends the image and masks to its+image generator. `npm run create -- --help` lists the options.+### 2. Open the project and check itStart the editor (`npm run dev`), choose **Open project** and pick your project from the list.diff --git a/README.zh.md b/README.zh.mdindex 96bd0d2..fa30ead 100644--- a/README.zh.md+++ b/README.zh.md@@ -52,6 +52,20 @@ npm run dev| Claude Code | Claude Opus 5.5 || Codex | GPT-6.1 Sol |+#### 用 Codex 一条命令完成++安装并登录 [Codex CLI](https://github.com/openai/codex) 后,一条命令即可创建项目、让 Codex+按照助手指南完成全部步骤(中途不提问),并在编辑器中打开结果:++```sh+npm run create -- /path/to/your-image.png+```++通常需要几十分钟。Codex 的说明写在 `projects/<name>/HANDOVER.md`。Codex 以 `--approve-for-me`+运行,因此在沙箱外运行工具(例如姿势检查用的 Chromium)的请求由自动审核代替你决定。加上+`--variants` 还会绘制闭眼和嘴型,此时图像和遮罩会发送到 Codex 的图像生成器。用+`npm run create -- --help` 查看全部选项。+### 2. 打开项目并检查启动编辑器(`npm run dev`),选择**打开项目**,从列表中挑选你的项目。在预览里使用**姿态测试**转头、倾斜头部、闭眼。在**嘴型测试**里选择口型样式,输入假名文本试试效果。打开**高级设置**调整动作幅度、大小和闭合度,或预览本地音频文件。diff --git a/e2e/projects-lipsync.spec.ts b/e2e/projects-lipsync.spec.tsindex 32b60a0..5d492cd 100644--- a/e2e/projects-lipsync.spec.ts+++ b/e2e/projects-lipsync.spec.ts@@ -155,6 +155,16 @@ test('recent projects persist in order, auto-reopen, remove missing entries, andawait expect(menu.getByText('No recent projects.', { exact: true })).toBeVisible();});+test('a ?project= address opens that project instead of the recent one and is then removed', async ({ page }) => {+ await open(page, 'sample-miko-qipao');+ await page.goto(`/?project=${name}`);+ await expect(page.getByTestId('project-location')).toContainText(name);+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');+ expect(new URL(page.url()).search).toBe('');+ await page.goto('/?project=missing-ui-test');+ await expect(page.getByTestId('project-location')).toContainText(name);+});+test('picker projects without a persistent handle show Browse again in recent history', async ({ page }) => {await page.goto('/'); await dismissGuide(page);await page.getByLabel('Open project folder files', { exact: true }).setInputFiles(directory);diff --git a/package.json b/package.jsonindex 8b4623b..32c46fb 100644--- a/package.json+++ b/package.json@@ -25,7 +25,8 @@"pack-avatar": "node --experimental-strip-types tools/pack-avatar.mjs","render-poses": "node --experimental-strip-types tools/render-poses.mjs","quality": "node --experimental-strip-types tools/quality.mjs",- "doctor": "node tools/doctor.mjs"+ "doctor": "node tools/doctor.mjs",+ "create": "node tools/create.mjs"},"dependencies": {"@mediapipe/tasks-vision": "0.10.21",diff --git a/src/editor/App.tsx b/src/editor/App.tsxindex 290cb5d..b2e0be7 100644--- a/src/editor/App.tsx+++ b/src/editor/App.tsx@@ -86,6 +86,14 @@ function Workspace() {const missing = list ? entries.filter(entry => entry.kind === 'server' && !list.some(project => project.name === entry.serverName)) : [];const available = entries.filter(entry => !missing.includes(entry));if (missing.length) { setRecent(available); saveRecent(available); setNotice({ key: 'missingRecent', path: missing.map(entry => entry.name).join(', ') }); }+ // `npm run create` opens the editor at ?project=<name>; that project wins over the recent one.+ const params = new URLSearchParams(location.search), requested = params.get('project');+ if (requested !== null) {+ params.delete('project');+ window.history.replaceState(null, '', `${location.pathname}${params.size ? `?${params}` : ''}${location.hash}`);+ const project = list?.find(item => item.name === requested && item.relativePath.startsWith('projects/'));+ if (project && !project.error && !projectOpened.current) { projectOpened.current = true; await openLocal(project); return; }+ }if (readPreference(REOPEN_KEY) === '0' || !available.length || projectOpened.current) return;const latest = available[0];if (latest.kind === 'server') {diff --git a/tests/create-avatar.test.ts b/tests/create-avatar.test.tsnew file mode 100644index 0000000..ab5c445--- /dev/null+++ b/tests/create-avatar.test.ts@@ -0,0 +1,79 @@+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, expect, test } from 'vitest';+import { agentPrompt, create, parseArgs, projectName } from '../tools/create.mjs';++const root = fileURLToPath(new URL('..', import.meta.url));+const ready = async () => ['node', 'packages', 'uv', 'python', 'chromium'].map(id => ({ id, status: 'ok', message: id }));++function harness({ files = [] as string[], statuses = {} as Record<string, number | null>, environment = ready } = {}) {+ const calls: { command: string; args: string[] }[] = [], logs: string[] = [], errors: string[] = [];+ const existing = new Set(files);+ const run = async (command: string, args: string[]) => {+ calls.push({ command, args });+ const key = command === process.execPath ? 'vite' : `${command} ${args[0]}`;+ if (key === 'codex exec' && !(key in statuses)) {+ const name = args.at(-1)!.match(/in projects\/([^ ]+) by/)![1];+ existing.add(join(root, 'projects', name, 'rig.json')).add(join(root, 'projects', name, 'built', 'base.png'));+ }+ return key in statuses ? statuses[key] : 0;+ };+ const read = async (command: string) => command === 'codex' ? 'codex-cli 0.164.0' : '/cache/uv';+ const deps = { run, read, exists: (path: string) => existing.has(path), environment, log: (m: string) => logs.push(m), error: (m: string) => errors.push(m), cwd: '/work' };+ return { calls, logs, errors, deps };+}++describe('npm run create', () => {+ test('parses the image, name and flags', () => {+ expect(parseArgs(['a.png', '--name', 'mio', '--variants', '--no-open', '--lang', 'ja'])).toMatchObject({ image: 'a.png', name: 'mio', variants: true, open: false });+ expect(parseArgs(['--name=mio', 'b.png'])).toMatchObject({ image: 'b.png', name: 'mio', variants: false, open: true });+ });++ test('derives a project name from the file name and skips taken names', () => {+ expect(projectName('/x/My New Avatar (v2).png', () => false)).toBe('my-new-avatar-v2');+ expect(projectName('/x/少女.png', () => false)).toBe('avatar');+ expect(projectName('mio.png', name => name === 'mio' || name === 'mio-2')).toBe('mio-3');+ });++ test('answers every question of the guide and sends the image only with --variants', () => {+ const plain = agentPrompt('mio', { variants: false });+ expect(plain).toContain('docs/agent-guide.md');+ expect(plain).toContain('projects/mio/HANDOVER.md');+ expect(plain).toContain('Step 6: skip it');+ expect(plain).toContain('do not stage or commit');+ expect(agentPrompt('mio', { variants: true })).toContain('the person agreed to send source.png and the masks');+ });++ test('creates the project, runs Codex and opens the editor on it', async () => {+ const { calls, deps } = harness({ files: ['/work/mio.png'] });+ expect(await create(['mio.png', '--lang', 'en'], deps)).toBe(0);+ expect(calls.map(call => `${call.command === process.execPath ? 'vite' : call.command} ${call.args[0]}`)).toEqual(['uv run', 'codex exec', 'vite ' + join(root, 'node_modules/vite/bin/vite.js')]);+ expect(calls[0].args).toEqual(['run', 'tools/new-project.py', '/work/mio.png', 'mio']);+ expect(calls[1].args.slice(0, 6)).toEqual(['exec', '--approve-for-me', '-C', root, '--add-dir', '/cache/uv']);+ expect(calls[2].args).toContain('/?project=mio');+ });++ test('stops before creating anything when a tool is missing', async () => {+ const environment = async () => [{ id: 'chromium', status: 'warn', message: 'Playwright Chromium was not found.' }];+ const { calls, errors, deps } = harness({ files: ['/work/mio.png'], environment });+ expect(await create(['mio.png', '--lang', 'en'], deps)).toBe(1);+ expect(calls).toEqual([]);+ expect(errors.join('\n')).toContain('Playwright Chromium was not found.');+ });++ test('refuses an existing project and does not open the editor when Codex fails', async () => {+ const taken = harness({ files: ['/work/mio.png', join(root, 'projects', 'mio')] });+ expect(await create(['mio.png', '--name', 'mio', '--lang', 'en'], taken.deps)).toBe(1);+ expect(taken.errors[0]).toContain('projects/mio already exists');+ const failed = harness({ files: ['/work/mio.png'], statuses: { 'codex exec': 2 } });+ expect(await create(['mio.png', '--lang', 'en'], failed.deps)).toBe(2);+ expect(failed.calls.some(call => call.command === process.execPath)).toBe(false);+ });++ test('does not open the editor when Codex leaves no built avatar', async () => {+ const { calls, errors, deps } = harness({ files: ['/work/mio.png'], statuses: { 'codex exec': 0 } });+ expect(await create(['mio.png', '--lang', 'en'], deps)).toBe(1);+ expect(errors[0]).toContain('HANDOVER.md');+ expect(calls.some(call => call.command === process.execPath)).toBe(false);+ });+});diff --git a/tools/create.mjs b/tools/create.mjsnew file mode 100644index 0000000..af105b3--- /dev/null+++ b/tools/create.mjs@@ -0,0 +1,154 @@+#!/usr/bin/env node+// One command from an illustration to an open editor: creates projects/<name>, has Codex+// follow docs/agent-guide.md without questions, then starts the editor on that project.+import { spawn } from 'node:child_process';+import { existsSync, realpathSync } from 'node:fs';+import { basename, extname, join, resolve } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { checkEnvironment, formatReport, language } from './doctor.mjs';++const root = fileURLToPath(new URL('..', import.meta.url));++const text = {+ en: {+ usage: 'Usage: npm run create -- <image.png> [--name <name>] [--variants] [--no-open]\n\n'+ + ' --name project name under projects/ (default: from the file name)\n'+ + ' --variants let Codex send source.png and masks to its image generator for drawn\n'+ + ' closed eyes and mouth shapes (Step 6 of the agent guide)\n'+ + ' --no-open do not start the editor when the avatar is ready',+ missingImage: 'Give the path of a PNG illustration.',+ noImage: path => `Image not found: ${path}`,+ badName: name => `Invalid project name: ${name}. Use letters, digits, hyphens or underscores.`,+ exists: name => `projects/${name} already exists. Choose another --name.`,+ environment: 'Fix the tools marked above, then run this command again.',+ noCodex: 'Codex CLI was not found. Install it and sign in: https://github.com/openai/codex',+ creating: name => `Creating projects/${name} …`,+ agent: 'Codex is building the avatar. This usually takes tens of minutes.',+ agentFailed: status => `Codex stopped with exit code ${status}. Its notes, if any, are in the project folder.`,+ incomplete: name => `Codex finished but projects/${name} has no built avatar. Read projects/${name}/HANDOVER.md for the reason.`,+ ready: name => `The avatar is ready: projects/${name}. Hand-over notes: projects/${name}/HANDOVER.md`,+ opening: 'Starting the editor. Press Ctrl+C to stop it.',+ },+ ja: {+ usage: '使い方: npm run create -- <image.png> [--name <name>] [--variants] [--no-open]\n\n'+ + ' --name projects/ に作るプロジェクト名(既定: ファイル名から作成)\n'+ + ' --variants 閉じ目と口の形の描き分けのため、source.png とマスクを Codex の画像生成に\n'+ + ' 送ることを許可する(エージェントガイドの Step 6)\n'+ + ' --no-open アバターができてもエディタを起動しない',+ missingImage: 'PNG のイラストのパスを指定してください。',+ noImage: path => `画像が見つかりません: ${path}`,+ badName: name => `プロジェクト名が使えません: ${name}。英数字、ハイフン、アンダースコアを使ってください。`,+ exists: name => `projects/${name} は既にあります。別の --name を指定してください。`,+ environment: '上の警告やエラーのツールを用意してから、もう一度実行してください。',+ noCodex: 'Codex CLI が見つかりません。インストールしてサインインしてください: https://github.com/openai/codex',+ creating: name => `projects/${name} を作成しています…`,+ agent: 'Codex がアバターを作っています。通常は数十分かかります。',+ agentFailed: status => `Codex が終了コード ${status} で止まりました。メモがあればプロジェクトフォルダにあります。`,+ incomplete: name => `Codex は終了しましたが、projects/${name} にアバターができていません。理由は projects/${name}/HANDOVER.md を確認してください。`,+ ready: name => `アバターができました: projects/${name}。引き継ぎメモ: projects/${name}/HANDOVER.md`,+ opening: 'エディタを起動します。止めるときは Ctrl+C を押してください。',+ },+};++export function parseArgs(argv) {+ const options = { image: undefined, name: undefined, variants: false, open: true, help: false };+ for (let index = 0; index < argv.length; index++) {+ const arg = argv[index];+ if (arg === '--help' || arg === '-h') options.help = true;+ else if (arg === '--variants') options.variants = true;+ else if (arg === '--no-open') options.open = false;+ else if (arg === '--name') options.name = argv[++index];+ else if (arg.startsWith('--name=')) options.name = arg.slice(7);+ else if (arg === '--lang') index++;+ else if (!arg.startsWith('--')) options.image ??= arg;+ }+ return options;+}++export const validName = name => /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name ?? '');++/** A project name from the file name, with a number added while that name is taken. */+export function projectName(image, taken = name => existsSync(join(root, 'projects', name))) {+ const stem = basename(image, extname(image)).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48).replace(/-+$/, '') || 'avatar';+ let name = stem;+ for (let index = 2; taken(name); index++) name = `${stem}-${index}`;+ return name;+}++/** The request Codex runs non-interactively: every question in the guide is answered here. */+export function agentPrompt(name, { variants }) {+ const project = `projects/${name}`;+ return [+ `Create a mesh avatar in ${project} by following docs/agent-guide.md from "Before you start" through Step 7.`,+ `Step 1 is already done: ${project}/source.png and ${project}/rig.draft.json exist. Do not run new-project.py again.`,+ '',+ 'This run is non-interactive. Nobody can answer questions, so decide as follows:',+ '- Model: state which model you are running as in the hand-over notes and continue.',+ `- Vision check: run it with ${project}/work/vision-check as the folder. If the score fails, stop and explain it in the hand-over notes.`,+ '- Image warnings (pose, covered face, missing transparency): record them in the hand-over notes and continue.',+ variants+ ? '- Step 6: the person agreed to send source.png and the masks to your built-in image generator. Generate the required variants (closed, half and smiling eyes; mouths あ, half あ, い, お), not the optional expression ones, then run build-sprites and review the poses again.'+ : '- Step 6: skip it. The person did not agree to send the image to an image generator.',+ `- Step 7: write the hand-over notes to ${project}/HANDOVER.md instead of telling the person. The editor is opened for them, so leave out how to open it.`,+ '',+ `Only create or change files inside ${project}/. Do not change other files in the repository, and do not stage or commit anything.`,+ 'End with a short summary of the result and the parts to check first.',+ ].join('\n');+}++const execute = (command, args, options = {}) => new Promise(done => {+ const child = spawn(command, args, { cwd: root, stdio: 'inherit', windowsHide: true, ...options });+ child.on('error', () => done(null));+ child.on('exit', status => done(status));+});++const capture = (command, args) => new Promise(done => {+ const child = spawn(command, args, { cwd: root, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });+ let output = '';+ child.stdout.on('data', chunk => { output += chunk; });+ child.on('error', () => done(null));+ child.on('exit', status => done(status === 0 ? output.trim() : null));+});++export async function create(argv, deps = {}) {+ const { run = execute, read = capture, exists = existsSync, environment = checkEnvironment, log = console.log, error = console.error,+ cwd = process.env.INIT_CWD || process.cwd() } = deps;+ const lang = language(argv), t = text[lang], options = parseArgs(argv);+ if (options.help) { log(t.usage); return 0; }+ if (!options.image) { error(`${t.missingImage}\n\n${t.usage}`); return 1; }+ // npm run starts in the repository root; INIT_CWD is where the person typed the command.+ const image = resolve(cwd, options.image);+ if (!exists(image)) { error(t.noImage(options.image)); return 1; }+ const name = options.name ?? projectName(options.image, value => exists(join(root, 'projects', value)));+ if (!validName(name)) { error(t.badName(name)); return 1; }+ if (exists(join(root, 'projects', name))) { error(t.exists(name)); return 1; }++ // Every step of the guide needs uv, Python and Chromium, so a warning blocks here.+ const results = await environment(lang);+ if (results.some(result => result.status !== 'ok')) { error(formatReport(results, lang)); error(t.environment); return 1; }+ if (!await read('codex', ['--version'])) { error(t.noCodex); return 1; }++ log(t.creating(name));+ const created = await run('uv', ['run', 'tools/new-project.py', image, name]);+ if (created !== 0) return created ?? 1;++ log(t.agent);+ // Codex works in its sandbox and asks for more only to run Chromium and similar tools;+ // --approve-for-me has those requests reviewed automatically instead of by a person.+ const cache = await read('uv', ['cache', 'dir']);+ const agent = await run('codex', ['exec', '--approve-for-me', '-C', root, ...(cache ? ['--add-dir', cache] : []), agentPrompt(name, options)]);+ if (agent !== 0) { error(t.agentFailed(agent)); return agent ?? 1; }+ const project = join(root, 'projects', name);+ if (!exists(join(project, 'rig.json')) || !exists(join(project, 'built', 'base.png'))) { error(t.incomplete(name)); return 1; }+ log(t.ready(name));+ if (!options.open) return 0;++ log(t.opening);+ const vite = join(root, 'node_modules', 'vite', 'bin', 'vite.js');+ return await run(process.execPath, [vite, '--host', '127.0.0.1', '--open', `/?project=${encodeURIComponent(name)}`]) ?? 1;+}++// npm run starts this file through a link, so compare real paths.+if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {+ process.exitCode = await create(process.argv.slice(2));+}