Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Add --random to npm run create to start from a newly drawn character
shinshin86498a8312fb27
diff --git a/README.ja.md b/README.ja.mdindex 4bc0302..dd692d6 100644--- a/README.ja.md+++ b/README.ja.md@@ -67,6 +67,15 @@ Codex は OpenAI の画像生成で、閉じ目・口の形・表情の描き分Codex は `--approve-for-me` 付きで動くため、ポーズ確認用の Chromium など sandbox の外でツールを動かす許可は、あなたの代わりに自動レビューが判断します。オプションは `npm run create -- --help` で確認できます。+手元にイラストがなければ、`--random` を付けると Codex がアニメ調の女の子を新しく描き、そこからアバターを作ります。+見た目はランダムに決まります。`--prompt` で希望を伝えることも、`--seed` で同じランダムな組み合わせを再現することもできます。+描いた絵は `work/random/` に、選ばれた見た目は `projects/<name>/work/character.json` に残ります。++```sh+npm run create -- --random+npm run create -- --random --prompt "銀髪のショートヘア、制服"+```+### 2. プロジェクトを開いて確認するエディタを起動し(`npm run dev`)、「プロジェクトを開く」の一覧から作ったプロジェクトを選びます。「ポーズ確認」で顔の向きや傾き、目の開閉を確かめ、「口の動き」では「ゆったり」「キビキビ」などを選んで口パクを試します。「細かく調整する」で口の大きさや閉じ方を調整し、音声ファイルでも確認できます。diff --git a/README.md b/README.mdindex 970649c..d7d656b 100644--- a/README.md+++ b/README.md@@ -90,6 +90,16 @@ the image and masks to OpenAI, so the command asks first; add `--yes` to agree ipose review, are reviewed automatically instead of by you. `npm run create -- --help` lists theoptions.+Without an illustration, `--random` has Codex draw a new anime-style girl first and builds the+avatar from her. Her looks are chosen at random; `--prompt` describes what you want instead,+and `--seed` repeats the same random choices. The drawing is kept in `work/random/`, and the+choices in `projects/<name>/work/character.json`.++```sh+npm run create -- --random+npm run create -- --random --prompt "silver short hair, school uniform"+```+### 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 357c5e0..3d67cb8 100644--- a/README.zh.md+++ b/README.zh.md@@ -66,6 +66,15 @@ Codex 还会用 OpenAI 图像生成绘制闭眼、嘴型和表情;如果插画`projects/<name>/HANDOVER.md`。Codex 以 `--approve-for-me` 运行,因此在沙箱外运行工具(例如姿势检查用的Chromium)的请求由自动审核代替你决定。用 `npm run create -- --help` 查看全部选项。+没有插画时,加上 `--random` 会让 Codex 先画一个新的动漫风格女孩,再用她制作虚拟形象。外观随机决定;+可用 `--prompt` 描述你想要的样子,用 `--seed` 重现同样的随机组合。画好的图保存在 `work/random/`,+选定的外观保存在 `projects/<name>/work/character.json`。++```sh+npm run create -- --random+npm run create -- --random --prompt "银色短发,校服"+```+### 2. 打开项目并检查启动编辑器(`npm run dev`),选择**打开项目**,从列表中挑选你的项目。在预览里使用**姿态测试**转头、倾斜头部、闭眼。在**嘴型测试**里选择口型样式,输入假名文本试试效果。打开**高级设置**调整动作幅度、大小和闭合度,或预览本地音频文件。diff --git a/tests/create-avatar.test.ts b/tests/create-avatar.test.tsindex 7775c84..b963b0a 100644--- a/tests/create-avatar.test.ts+++ b/tests/create-avatar.test.ts@@ -1,28 +1,34 @@import { join } from 'node:path';import { fileURLToPath } from 'node:url';import { describe, expect, test } from 'vitest';-import { agentPrompt, create, parseArgs, projectName, SPRITES } from '../tools/create.mjs';+import { agentPrompt, characterPrompt, create, drawingProblems, parseArgs, pickLooks, projectName, LOOKS, SPRITES } 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, answer = true as boolean | null, interactive = true, sprites = SPRITES } = {}) {+type Drawing = { format: string; width: number; height: number; transparent: boolean } | null;+const drawing: Drawing = { format: 'PNG', width: 1024, height: 1536, transparent: true };++function harness({ files = [] as string[], statuses = {} as Record<string, number | null>, environment = ready, answer = true as boolean | null, interactive = true, sprites = SPRITES, drawn = drawing as Drawing } = {}) {const calls: { command: string; args: string[]; options?: { stdio?: unknown } }[] = [], logs: string[] = [], errors: string[] = [], questions: string[] = [];- const existing = new Set(files);+ const existing = new Set(files), saved: Record<string, string> = {};const run = async (command: string, args: string[], options?: { stdio?: unknown }) => {calls.push({ command, args, options });- const key = command === process.execPath ? 'vite' : `${command} ${args[0]}`;+ const prompt = args.at(-1)!;+ const key = command === process.execPath ? 'vite' : command === 'codex' && prompt.includes('draw this character') ? 'codex draw' : `${command} ${args[0]}`;+ if (key === 'codex draw' && !(key in statuses)) existing.add(join(root, prompt.match(/save her as a PNG at (\S+):/)![1]));if (key === 'codex exec' && !(key in statuses)) {- const name = args.at(-1)!.match(/in projects\/([^ ]+) by/)![1];+ const name = prompt.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 read = async (command: string, args: string[]) => command === 'codex' ? 'codex-cli 0.164.0' : args[0] === 'run' ? JSON.stringify(drawn) : '/cache/uv';+ const save = (path: string, data: string) => { saved[path] = data; };const ask = async (question: string) => { questions.push(question); return answer; };const readJson = () => ({ layers: Object.fromEntries(sprites.map(sprite => [sprite, [0, 0, 1, 1]])) });- const deps = { run, read, readJson, ask, interactive, 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, questions, deps };+ const deps = { run, read, readJson, save, randomSeed: () => 4821, today: () => new Date('2026-10-27T12:00:00Z'), ask, interactive, 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, questions, saved, deps };}describe('npm run create', () => {@@ -134,4 +140,72 @@ describe('npm run create', () => {expect(errors[0]).toContain('HANDOVER.md');expect(calls.some(call => call.command === process.execPath)).toBe(false);});++ test('--random draws a character first, checks it, then builds from it', async () => {+ const { calls, questions, saved, logs, deps } = harness();+ expect(await create(['--random', '--lang', 'en'], deps)).toBe(0);+ expect(questions).toHaveLength(1);+ expect(questions[0]).toContain('draw a new character with OpenAI image generation');+ const draw = calls[0];+ expect(draw.args.slice(0, 2)).toEqual(['exec', '--approve-for-me']);+ expect(draw.args.at(-1)).toContain('save her as a PNG at work/random/random-20261027-4821/source.png:');+ expect(calls[1].args).toEqual(['run', 'tools/new-project.py', join(root, 'work/random/random-20261027-4821/source.png'), 'random-20261027-4821']);+ expect(calls[2].args.at(-1)).toContain('in projects/random-20261027-4821 by');+ expect(calls[2].args.at(-1)).toContain('the person agreed to send');+ const character = JSON.parse(saved[join(root, 'projects/random-20261027-4821/work/character.json')]);+ expect(character).toMatchObject({ seed: 4821, looks: pickLooks(4821), prompt: null });+ expect(logs.some(line => line.includes('seed 4821'))).toBe(true);+ expect(calls.at(-1)!.args).toContain('/?project=random-20261027-4821');+ });++ test('--seed repeats the looks and --prompt takes priority over them', async () => {+ expect(pickLooks(42)).toEqual(pickLooks(42));+ const picks = new Set(Array.from({ length: 50 }, (_, seed) => JSON.stringify(pickLooks(seed))));+ expect(picks.size).toBeGreaterThan(40);+ for (const [key, value] of Object.entries(pickLooks(7))) expect(LOOKS[key as keyof typeof LOOKS]).toContain(value);+ const { calls, saved, deps } = harness();+ expect(await create(['--random', '--seed', '42', '--prompt', 'silver short hair, school uniform', '--name', 'mio', '--yes', '--lang', 'en'], deps)).toBe(0);+ expect(calls[0].args.at(-1)).toContain('The person asked for: silver short hair, school uniform.');+ expect(JSON.parse(saved[join(root, 'projects/mio/work/character.json')])).toMatchObject({ seed: 42, prompt: 'silver short hair, school uniform' });+ });++ test('the character request keeps the rig requirements', () => {+ const request = characterPrompt(pickLooks(1), undefined);+ for (const rule of ['anime-style girl', 'bust-up portrait', 'transparent background', 'mouth closed', 'both eyes open', 'no hands, glasses, hats', 'must not resemble any existing character']) {+ expect(request).toContain(rule);+ }+ });++ test('--random stops before building when the drawing fails or cannot be used', async () => {+ const failed = harness({ statuses: { 'codex draw': 1 } });+ expect(await create(['--random', '--yes', '--lang', 'en'], failed.deps)).toBe(1);+ expect(failed.errors[0]).toContain('could not draw the character');+ expect(failed.calls).toHaveLength(1);+ const opaque = harness({ drawn: { ...drawing, transparent: false } });+ expect(await create(['--random', '--yes', '--lang', 'en'], opaque.deps)).toBe(1);+ expect(opaque.errors[0]).toContain('no transparent background');+ expect(opaque.calls).toHaveLength(1);+ expect(drawingProblems(null)).toEqual(['not a readable image']);+ expect(drawingProblems({ format: 'JPEG', width: 600, height: 700, transparent: false })).toEqual(['not a PNG', 'no transparent background', 'only 700 px tall']);+ });++ test('--random refuses an image, --no-variants, a bad seed, a declined question and no terminal', async () => {+ const cases: [string[], string][] = [+ [['a.png', '--random'], 'either an image or --random'],+ [['--random', '--no-variants'], 'cannot be combined with --no-variants'],+ [['--random', '--seed', 'abc'], 'Invalid seed: abc'],+ ];+ for (const [args, message] of cases) {+ const { calls, errors, deps } = harness({ files: ['/work/a.png'] });+ expect(await create([...args, '--lang', 'en'], deps)).toBe(1);+ expect(errors[0]).toContain(message);+ expect(calls).toEqual([]);+ }+ const declined = harness({ answer: false });+ expect(await create(['--random', '--lang', 'en'], declined.deps)).toBe(1);+ expect(declined.calls).toEqual([]);+ const headless = harness({ interactive: false });+ expect(await create(['--random', '--lang', 'en'], headless.deps)).toBe(1);+ expect(headless.errors[0]).toContain('add --yes to agree');+ });});diff --git a/tools/create.mjs b/tools/create.mjsindex 5cc974e..bf9cd59 100644--- a/tools/create.mjs+++ b/tools/create.mjs@@ -1,9 +1,10 @@#!/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.+// With --random, Codex first draws a new character to start from.import { spawn } from 'node:child_process';-import { existsSync, readFileSync, realpathSync } from 'node:fs';-import { basename, extname, join, resolve } from 'node:path';+import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';+import { basename, dirname, extname, join, relative, resolve } from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';import { checkEnvironment, formatReport, language } from './doctor.mjs';@@ -16,15 +17,27 @@ export const SPRITES = [const text = {en: {- usage: 'Usage: npm run create -- <image.png> [--name <name>] [--yes | --no-variants] [--no-open]\n\n'+ usage: 'Usage: npm run create -- <image.png> [--name <name>] [--yes | --no-variants] [--no-open]\n'+ + ' npm run create -- --random [--prompt <text>] [--seed <number>] [--name <name>] [--yes] [--no-open]\n\n'+ 'Codex also draws closed eyes, mouth shapes and expressions with OpenAI image generation,\n'+ 'and closes an open mouth in the illustration first so the avatar rests with it closed.\n'+ 'The command asks first, because this sends the image and masks to OpenAI.\n\n'+ ' --name project name under projects/ (default: from the file name)\n'+ ' --yes, -y agree to the image generation without asking\n'+ ' --no-variants keep everything on this machine and skip the drawn variants\n'- + ' --no-open do not start the editor when the avatar is ready',- missingImage: 'Give the path of a PNG illustration.',+ + ' --no-open do not start the editor when the avatar is ready\n'+ + ' --random draw a new anime-style girl with OpenAI image generation and start from her\n'+ + ' --prompt with --random: what she should look like; the rest is chosen at random\n'+ + ' --seed with --random: repeat the same random choices',+ missingImage: 'Give the path of a PNG illustration, or --random to draw a new character.',+ imageAndRandom: 'Give either an image or --random, not both.',+ randomNeedsVariants: '--random draws the character with OpenAI image generation, so it cannot be combined with --no-variants.',+ badSeed: seed => `Invalid seed: ${seed}. Use a whole number.`,+ randomConsent: 'Codex will draw a new character with OpenAI image generation, then her closed eyes,\nmouth shapes and expressions. The pictures and masks are sent to OpenAI. Continue? [Y/n] ',+ needRandomConsent: '--random uses OpenAI image generation. Without a terminal to ask, add --yes to agree.',+ character: (seed, character) => `Drawing a new character (seed ${seed}): ${character}`,+ drawFailed: status => `Codex could not draw the character (exit code ${status}).`,+ badDrawing: (path, problems) => `The drawn character cannot be used (${problems.join('; ')}): ${path}`,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.`,@@ -42,15 +55,27 @@ const text = {opening: 'Starting the editor. Press Ctrl+C to stop it.',},ja: {- usage: '使い方: npm run create -- <image.png> [--name <name>] [--yes | --no-variants] [--no-open]\n\n'+ usage: '使い方: npm run create -- <image.png> [--name <name>] [--yes | --no-variants] [--no-open]\n'+ + ' npm run create -- --random [--prompt <text>] [--seed <number>] [--name <name>] [--yes] [--no-open]\n\n'+ 'Codex は OpenAI の画像生成で、閉じ目・口の形・表情の描き分けも作ります。\n'+ 'イラストの口が開いていれば、先に口を閉じた絵にしてから作ります。\n'+ '画像とマスクが OpenAI に送られるため、始める前に確認します。\n\n'+ ' --name projects/ に作るプロジェクト名(既定: ファイル名から作成)\n'+ ' --yes, -y 確認せずに画像生成に同意する\n'+ ' --no-variants すべてこのマシンの中で行い、描き分けは作らない\n'- + ' --no-open アバターができてもエディタを起動しない',- missingImage: 'PNG のイラストのパスを指定してください。',+ + ' --no-open アバターができてもエディタを起動しない\n'+ + ' --random OpenAI の画像生成でアニメ調の女の子を新しく描き、そこから作る\n'+ + ' --prompt --random のとき、見た目の希望。指定しない部分はランダムに決める\n'+ + ' --seed --random のとき、同じランダムな組み合わせを再現する',+ missingImage: 'PNG のイラストのパスを指定するか、新しく描くなら --random を付けてください。',+ imageAndRandom: '画像と --random は同時に指定できません。',+ randomNeedsVariants: '--random は OpenAI の画像生成でキャラクターを描くため、--no-variants とは併用できません。',+ badSeed: seed => `seed が使えません: ${seed}。整数を指定してください。`,+ randomConsent: 'Codex が OpenAI の画像生成で新しいキャラクターを描き、閉じ目・口の形・表情の描き分けも作ります。\n絵とマスクが OpenAI に送られます。続けますか? [Y/n] ',+ needRandomConsent: '--random は OpenAI の画像生成を使います。確認できる端末がないため、同意するなら --yes を付けてください。',+ character: (seed, character) => `新しいキャラクターを描いています(seed ${seed}): ${character}`,+ drawFailed: status => `Codex がキャラクターを描けませんでした(終了コード ${status})。`,+ badDrawing: (path, problems) => `描いたキャラクターが使えません(${problems.join('、')}): ${path}`,noImage: path => `画像が見つかりません: ${path}`,badName: name => `プロジェクト名が使えません: ${name}。英数字、ハイフン、アンダースコアを使ってください。`,exists: name => `projects/${name} は既にあります。別の --name を指定してください。`,@@ -70,7 +95,7 @@ const text = {};export function parseArgs(argv) {- const options = { image: undefined, name: undefined, variants: true, yes: false, open: true, help: false };+ const options = { image: undefined, name: undefined, variants: true, yes: false, open: true, help: false, random: false, prompt: undefined, seed: undefined };for (let index = 0; index < argv.length; index++) {const arg = argv[index];if (arg === '--help' || arg === '-h') options.help = true;@@ -79,6 +104,11 @@ export function parseArgs(argv) {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 === '--random') options.random = true;+ else if (arg === '--prompt') options.prompt = argv[++index];+ else if (arg.startsWith('--prompt=')) options.prompt = arg.slice(9);+ else if (arg === '--seed') options.seed = argv[++index];+ else if (arg.startsWith('--seed=')) options.seed = arg.slice(7);else if (arg === '--lang') index++;else if (!arg.startsWith('--')) options.image ??= arg;}@@ -95,6 +125,75 @@ export function projectName(image, taken = name => existsSync(join(root, 'projecreturn name;}+// --random: create.mjs picks the looks so characters differ from run to run (a model left to+// itself draws much the same face), and a seed repeats the picks. The framing is kept in one+// place so other framings can be added later.+const FRAMING = 'bust-up portrait: from the top of the head to the chest, facing the viewer';+export const LOOKS = {+ hair: ['black', 'dark brown', 'chestnut brown', 'honey blonde', 'platinum blonde', 'silver', 'pastel pink', 'sky blue', 'lavender', 'mint green', 'auburn red'],+ hairstyle: ['short bob', 'chin-length bob', 'shoulder-length straight hair', 'shoulder-length wavy hair', 'long straight hair tucked behind the shoulders', 'low twin tails', 'high ponytail', 'side ponytail', 'short layered cut'],+ eyes: ['brown', 'amber', 'green', 'blue', 'violet', 'grey', 'red', 'teal'],+ outfit: ['school blazer uniform with a ribbon', 'sailor uniform', 'oversized hoodie', 'white blouse with a cardigan', 'sporty track jacket', 'casual knit sweater', 'idol stage costume', 'maid outfit', 'summer sundress', 'yukata'],+ mood: ['gentle smile', 'calm, soft smile', 'cheerful closed-mouth smile', 'cool, composed look'],+ palette: ['pastel colours', 'warm colours', 'cool colours', 'vivid colours', 'soft muted colours'],+};++/** Deterministic picks from LOOKS (mulberry32). */+export function pickLooks(seed) {+ let state = seed >>> 0;+ const next = () => {+ state = (state + 0x6d2b79f5) >>> 0;+ let x = Math.imul(state ^ (state >>> 15), 1 | state);+ x ^= x + Math.imul(x ^ (x >>> 7), 61 | x);+ return ((x ^ (x >>> 14)) >>> 0) / 4294967296;+ };+ return Object.fromEntries(Object.entries(LOOKS).map(([key, values]) => [key, values[Math.floor(next() * values.length)]]));+}++export const describeLooks = looks => `${looks.hair} ${looks.hairstyle}, ${looks.eyes} eyes, ${looks.outfit}, ${looks.mood}, ${looks.palette}`;++/** What the illustration must look like for the rig, from the agent guide's image section. */+export function characterPrompt(looks, wish) {+ return [+ 'An original anime-style girl, drawn as a clean, high-quality character illustration.',+ `Framing: ${FRAMING}, head and shoulders and upper chest fully inside the picture.`,+ wish ? `The person asked for: ${wish}. Follow that; use these only where it says nothing: ${describeLooks(looks)}.` : `Looks: ${describeLooks(looks)}.`,+ 'Requirements for animating her:',+ '- transparent background (RGBA PNG), no scenery, no frame, no text;',+ '- face turned straight to the viewer, not three-quarter or profile;',+ '- mouth closed (a closed smile is fine); both eyes open and fully visible;',+ '- bangs and hair do not cover the eyes or eyebrows heavily;',+ '- no hands, glasses, hats, masks, large hair ornaments or objects near or over the face;',+ '- portrait orientation, at least 1024 px wide and 1536 px tall.',+ 'She must not resemble any existing character, franchise or real person.',+ ].join('\n');+}++/** The request for codex exec that only draws the character. */+export function drawPrompt(output, looks, wish) {+ return [+ `Use your built-in image generation to draw this character and save her as a PNG at ${output}:`,+ '',+ characterPrompt(looks, wish),+ '',+ 'Look at the result and check every requirement above. Generate again, up to 4 tries, if any of them fails; keep the best one.',+ `Check with a script that ${output} is a PNG with an alpha channel, that the background is transparent, and that it is at least 1536 px tall.`,+ `Only write inside ${dirname(output)}/. Your image generator also keeps its own copy elsewhere (for example ~/.codex/generated_images); that is expected and allowed. Do not stage or commit anything.`,+ 'This run is non-interactive. End with a short summary of the picture and any requirement it still misses.',+ ].join('\n');+}++// Reads the drawing with Pillow (uv is required anyway) and lists what makes it unusable.+const INSPECT = "import json,sys\nfrom PIL import Image\nim=Image.open(sys.argv[1])\na=im.convert('RGBA').getchannel('A').getextrema()\nprint(json.dumps({'format':im.format,'width':im.width,'height':im.height,'transparent':a[0]<255}))";+export function drawingProblems(info) {+ if (!info) return ['not a readable image'];+ const problems = [];+ if (info.format !== 'PNG') problems.push('not a PNG');+ if (!info.transparent) problems.push('no transparent background');+ if (info.height < 800) problems.push(`only ${info.height} px tall`);+ return problems;+}+// The rig takes the mouth in the illustration as the closed rest mouth; an open one stays open// while silent and in every expression. With the image generator allowed, close it first.const closeMouth = project => [@@ -155,21 +254,30 @@ const capture = (command, args) => new Promise(done => {export async function create(argv, deps = {}) {const { run = execute, read = capture, exists = existsSync, environment = checkEnvironment, log = console.log, error = console.error,- readJson = path => JSON.parse(readFileSync(path, 'utf8')), ask = confirm, interactive = Boolean(process.stdin.isTTY), cwd = process.env.INIT_CWD || process.cwd() } = deps;+ readJson = path => JSON.parse(readFileSync(path, 'utf8')), ask = confirm, interactive = Boolean(process.stdin.isTTY), cwd = process.env.INIT_CWD || process.cwd(),+ save = (path, data) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, data); },+ randomSeed = () => Math.floor(Math.random() * 100000), today = () => new Date() } = 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; }+ if (options.random && options.image) { error(t.imageAndRandom); return 1; }+ if (options.random && !options.variants) { error(t.randomNeedsVariants); return 1; }+ if (!options.image && !options.random) { error(`${t.missingImage}\n\n${t.usage}`); return 1; }+ const seed = options.random ? (options.seed === undefined ? randomSeed() : Number(options.seed)) : undefined;+ if (options.random && !Number.isSafeInteger(seed)) { error(t.badSeed(options.seed)); 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)));+ let image = options.image && resolve(cwd, options.image);+ if (image && !exists(image)) { error(t.noImage(options.image)); return 1; }+ const taken = value => exists(join(root, 'projects', value));+ const stamp = today().toISOString().slice(0, 10).replaceAll('-', '');+ const name = options.name ?? (options.random ? projectName(`random-${stamp}-${seed}`, taken) : projectName(options.image, taken));if (!validName(name)) { error(t.badName(name)); return 1; }if (exists(join(root, 'projects', name))) { error(t.exists(name)); return 1; }// Ask before anything slow: the answer decides whether the image may leave this machine.if (options.variants && !options.yes) {- if (!interactive) { error(t.needConsent); return 1; }- const answer = await ask(t.consent);+ if (!interactive) { error(options.random ? t.needRandomConsent : t.needConsent); return 1; }+ const answer = await ask(options.random ? t.randomConsent : t.consent);if (answer === null) return 130;+ if (!answer && options.random) return 1;if (!answer) { options.variants = false; log(t.noConsent); }}@@ -177,19 +285,36 @@ export async function create(argv, deps = {}) {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; }+ // 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.+ // Its stdin stays closed: codex exec would otherwise wait to append piped input to the prompt.+ const cache = await read('uv', ['cache', 'dir']);+ const codex = prompt => run('codex', ['exec', '--approve-for-me', '-C', root, ...(cache ? ['--add-dir', cache] : []), prompt], { stdio: ['ignore', 'inherit', 'inherit'] });++ let character;+ if (options.random) {+ const looks = pickLooks(seed);+ image = join(root, 'work', 'random', name, 'source.png');+ const output = relative(root, image).split('\\').join('/');+ character = { seed, looks, prompt: options.prompt ?? null, request: characterPrompt(looks, options.prompt) };+ log(t.character(seed, options.prompt ?? describeLooks(looks)));+ const drawn = await codex(drawPrompt(output, looks, options.prompt));+ if (drawn !== 0) { error(t.drawFailed(drawn)); return drawn ?? 1; }+ let info = null;+ if (exists(image)) try { info = JSON.parse(await read('uv', ['run', '--with', 'pillow', 'python', '-c', INSPECT, image]) ?? 'null'); } catch { /* reported below */ }+ const problems = drawingProblems(info);+ if (problems.length) { error(t.badDrawing(output, problems)); return 1; }+ }log(t.creating(name));const created = await run('uv', ['run', 'tools/new-project.py', image, name]);if (created !== 0) return created ?? 1;+ const project = join(root, 'projects', name);+ if (character) save(join(project, 'work', 'character.json'), `${JSON.stringify(character, null, 2)}\n`);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.- // Its stdin stays closed: codex exec would otherwise wait to append piped input to the prompt.- 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)], { stdio: ['ignore', 'inherit', 'inherit'] });+ const agent = await codex(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; }if (options.variants) {let layers = {};