Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(create-agent): scaffold a rigged 3D agent from one npm create command
nirholas692ff512d33c
diff --git a/docs/create-agent.md b/docs/create-agent.mdnew file mode 100644index 000000000..d8f17bde9--- /dev/null+++ b/docs/create-agent.md@@ -0,0 +1,126 @@+# create-agent: one command, one 3D character++```bash+npm create @three-ws/agent "a friendly cartoon astronaut in a glossy white suit"+```++That command generates a textured 3D figure, rigs it with a humanoid skeleton, downloads it, and writes a folder with a working demo page and the embed snippet for your own site. No account, no API key, no signup: it runs on the three.ws free lane and the platform's provider keys cover the cost.++It is the terminal-native version of [three.ws/create](https://three.ws/create), for people who would rather stay in a shell, and for scripts and CI that need a character without a browser.++---++## The 60-second version++```bash+$ npm create @three-ws/agent "a knight in worn steel armor"++three.ws building "a knight in worn steel armor"+ a rigged humanoid, free lane, no account needed++· sent to the three.ws forge+· generating the figure (15s)+· generating the figure, then the skeleton (60s)+✓ model ready+· downloading the model++Knight In Worn is ready in 88s++ folder a-knight-in-worn/+ index.html+ agent.json+ README.md+ agent.glb (3.1 MB)+ viewer https://three.ws/viewer?src=…+```++```bash+$ npx serve a-knight-in-worn+```++The demo page renders the character with `<agent-3d>`; `agent.glb` is yours to drop into Blender, Unity, Godot, or any glTF tool.++---++## What lands on disk++| File | What it is |+| --- | --- |+| `agent.glb` | The model with its skeleton. Poseable and animatable, because three.ws retargets its pre-baked clip library onto any humanoid rig it can canonicalize. |+| `index.html` | A demo page that works on a double click. It points at the **hosted** model URL on purpose: a page opened over `file://` cannot fetch a neighbouring `.glb` without a server, and a demo that shows nothing is worse than no demo. |+| `agent.json` | Prompt, hosted URLs, backend, generation time, and a `madeWith` marker, so a script can pick the result up. |+| `README.md` | The embed snippet and the next steps, written for whoever opens the folder later. |++---++## Options++| Option | Meaning |+| --- | --- |+| `--photo <url>` | Build the character from a public https reference image instead of a description |+| `--out <dir>` | Where to write the project (default: a slug of the description) |+| `--name <name>` | Display name (default: derived from the description) |+| `--object` | An object or prop (mesh only) instead of a rigged character |+| `--no-download` | Keep the hosted model URL, skip writing `agent.glb` |+| `--json` | Print the result as JSON and nothing else, for scripting |+| `--origin <url>` | API origin (default `https://three.ws`) |++### Writing a prompt that rigs well++Describe **one full-body humanoid in a neutral standing pose**. Lead with the subject, then materials and colours; the free lane conditions on roughly the first 77 characters, so front-load what matters.++Good: `a friendly cartoon astronaut in a glossy white suit, orange visor`+Less good: `an epic scene where an astronaut floats above a ringed planet`++A clearly non-humanoid subject (furniture, a vehicle, a quadruped) should use `--object`. Auto-rigging assumes a humanoid.++---++## Under the hood++The CLI is a thin client over one public endpoint:++```bash+curl -s -X POST https://three.ws/api/mcp-studio \+ -H 'content-type: application/json' \+ -d '{+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {+ "name": "forge_avatar",+ "arguments": { "prompt": "a friendly cartoon astronaut in a glossy white suit" }+ }+ }'+```++`forge_avatar` is generate-then-rig bundled; `--object` calls `forge_free` instead. Both are open, keyless JSON-RPC tools on the same endpoint the three.ws MCP server exposes, so anything that can speak HTTP can do what this CLI does. The MCP surface is documented in [mcp.md](mcp.md).++The job blocks server-side until the model exists, which is why the CLI reports **real elapsed seconds** rather than a progress bar it would have to invent. Every call carries a 10-minute deadline; on a timeout the job may still finish, and finished models land at [three.ws/creations](https://three.ws/creations).++---++## Programmatic use++```js+import { createAgent } from '@three-ws/create-agent';++const made = await createAgent({+ prompt: 'a friendly cartoon astronaut',+ out: './astro',+ onProgress: ({ message }) => console.log(message),+});+```++`createAgent`, `callForge`, `downloadModel` and the scaffold builders are all exported, and each takes `{ fetchImpl, signal, origin }`, so the pipeline runs against a local three.ws or a test double. Errors are one class, `ForgeError`, carrying a `code`: `timeout`, `unreachable`, `no_model`, `rpc_error`, `http_<status>`.++Full reference: [packages/create-agent/README.md](https://github.com/nirholas/three.ws/blob/main/packages/create-agent/README.md).++---++## Then what++- **Put it on your site.** The printed snippet is the whole integration; attribute reference in [web-component.md](web-component.md).+- **Give it a brain and a voice.** [three.ws/create](https://three.ws/create) takes the same model and adds a personality, memory, and speech.+- **Show what it is doing.** [Glance](glance.md) puts the agent's live status on a home screen, in a README, or in Slack.+- **Let other agents hire it.** [three.ws/marketplace](https://three.ws/marketplace).diff --git a/packages/create-agent/README.md b/packages/create-agent/README.mdnew file mode 100644index 000000000..47d67a6dc--- /dev/null+++ b/packages/create-agent/README.md@@ -0,0 +1,109 @@+# @three-ws/create-agent++**One command from a sentence to a rigged 3D character you can put on your site.**++```bash+npm create @three-ws/agent "a friendly cartoon astronaut in a glossy white suit"+```++```+three.ws building "a friendly cartoon astronaut in a glossy white suit"+ a rigged humanoid, free lane, no account needed++· sent to the three.ws forge+· generating the figure (15s)+· generating the figure, then the skeleton (60s)+✓ model ready+· downloading the model++Friendly Cartoon Astronaut is ready in 94s++ folder a-friendly-cartoon-astronaut/+ index.html+ agent.json+ README.md+ agent.glb (3.4 MB)+ viewer https://three.ws/viewer?src=…++ Paste this anywhere:++ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>++ <agent-3d body="https://three.ws/cdn/…/rigged.glb"+ name="Friendly Cartoon Astronaut"+ style="width:100%;max-width:420px;height:520px"></agent-3d>++ Open the demo: npx serve a-friendly-cartoon-astronaut+```++No account. No API key. No signup. The generation runs on the three.ws free lane, and the platform's own provider keys cover it.++## What you get++| File | What it is |+| --- | --- |+| `agent.glb` | The model, with a humanoid skeleton, so it can be posed and animated. Opens in Blender, Unity, Godot, or any glTF tool. |+| `index.html` | A working demo page. Double click it. |+| `agent.json` | The record: prompt, hosted URLs, backend, timing. |+| `README.md` | How to embed it and where to go next. |++## Options++```bash+npm create @three-ws/agent "a knight in worn steel armor" --out ./knight+npm create @three-ws/agent --photo https://example.com/me.jpg --name "Me"+npm create @three-ws/agent "a small ceramic frog figurine" --object+```++| Option | Meaning |+| --- | --- |+| `--photo <url>` | Build from a public https reference image instead of a description |+| `--out <dir>` | Where to write the project (default: a slug of the description) |+| `--name <name>` | Display name (default: derived from the description) |+| `--object` | An object or prop (mesh only, free lane) instead of a rigged character |+| `--no-download` | Keep the hosted model URL, skip writing `agent.glb` |+| `--json` | Print the result as JSON and nothing else |+| `--origin <url>` | API origin (default `https://three.ws`) |++Describe **one full-body humanoid in a neutral standing pose** for the best rig. Lead with the subject, then materials and colours: the free lane conditions on roughly the first 77 characters, so front-load what matters.++## Programmatic use++```js+import { createAgent } from '@three-ws/create-agent';++const made = await createAgent({+ prompt: 'a friendly cartoon astronaut',+ out: './astro',+ onProgress: ({ message }) => console.log(message),+});++made.result.glbUrl; // hosted, durable+made.result.rigged; // true+made.dir; // absolute path to the project+```++| Export | What it does |+| --- | --- |+| `createAgent(opts)` | The whole pipeline: generate, scaffold, download |+| `callForge({ tool, args, ... })` | One forge call (`forge_avatar` or `forge_free`) |+| `downloadModel(url)` | Fetch the model bytes with a deadline |+| `projectFiles(...)`, `demoPage(...)`, `embedSnippet(...)` | The scaffold, as pure functions |+| `ForgeError` | Carries `code`: `timeout`, `unreachable`, `no_model`, `rpc_error`, `http_<status>` |++Everything takes `{ fetchImpl, signal, origin }`, so it runs against a local three.ws, a proxy, or a test double.++## How long it takes++A rigged character is generation plus rigging, usually one to three minutes; rigging is the slow half. An `--object` is faster. Every call carries an explicit deadline (10 minutes) and reports real elapsed time, never an invented progress bar. If the deadline hits, the job may still finish: finished models land at <https://three.ws/creations>.++## Related++- The full pipeline in a browser: <https://three.ws/create>+- `<agent-3d>` attribute reference: <https://three.ws/docs/web-component>+- Your agent's live status on a home screen or in a README: [@three-ws/agent-glance](../agent-glance)+- Docs: <https://three.ws/docs/create-agent>++## License++Apache-2.0diff --git a/packages/create-agent/bin/create-agent.js b/packages/create-agent/bin/create-agent.jsnew file mode 100755index 000000000..8b5f67af4--- /dev/null+++ b/packages/create-agent/bin/create-agent.js@@ -0,0 +1,98 @@+#!/usr/bin/env node+/**+ * npm create @three-ws/agent "a friendly cartoon astronaut"+ *+ * From a sentence to a rigged 3D character with a working demo page, in one+ * command, with no account and no API key.+ */++import { relative } from 'node:path';++import { createAgent, embedSnippet, ForgeError } from '../src/index.js';+import { parseArgs, USAGE } from '../src/args.js';+++const color = process.stdout.isTTY && !process.env.NO_COLOR;+const c = (code, text) => (color ? `\u001b[${code}m${text}\u001b[0m` : String(text));+++function progress(json) {+ let lastPhase = '';+ return ({ phase, message }) => {+ if (json) return;+ // One line per real event. No spinner, no invented percentage: the only+ // honest signal a blocking generation gives is elapsed time.+ if (phase === 'submitted') process.stdout.write(`${c('90', '·')} ${message}\n`);+ else if (phase === 'working') process.stdout.write(`${c('90', '·')} ${message}\n`);+ else if (phase === 'download') process.stdout.write(`${c('90', '·')} ${message}\n`);+ else if (phase === 'done' && lastPhase !== 'done') process.stdout.write(`${c('32', '✓')} ${message}\n`);+ lastPhase = phase;+ };+}++async function main() {+ const opts = parseArgs(process.argv.slice(2));++ if (opts.unknown) {+ console.error(`create-agent: unknown option ${opts.unknown}\n\n${USAGE}`);+ process.exit(1);+ }+ if (opts.help || (!opts.prompt && !opts.imageUrl)) {+ console.log(USAGE);+ process.exit(opts.help ? 0 : 1);+ }++ if (!opts.json) {+ const what = opts.imageUrl ? `the character in ${opts.imageUrl}` : `"${opts.prompt}"`;+ console.log(`\n${c('1', 'three.ws')} ${c('90', 'building')} ${what}`);+ console.log(+ c('90', opts.rig ? ' a rigged humanoid, free lane, no account needed' : ' an object, free lane, no account needed'),+ );+ console.log('');+ }++ const started = Date.now();+ const made = await createAgent({ ...opts, onProgress: progress(opts.json) });+ const seconds = Math.round((Date.now() - started) / 1000);++ if (opts.json) {+ console.log(JSON.stringify({ ...made, seconds }, null, 2));+ return;+ }++ const dir = relative(process.cwd(), made.dir) || '.';+ console.log('');+ console.log(`${c('1', made.name)} ${c('90', `is ready in ${seconds}s`)}`);+ console.log('');+ console.log(` ${c('90', 'folder ')} ${dir}/`);+ for (const file of made.files) {+ const size = file === 'agent.glb' && made.bytes ? c('90', ` (${(made.bytes / 1e6).toFixed(1)} MB)`) : '';+ console.log(` ${c('90', ' ')} ${file}${size}`);+ }+ console.log(` ${c('90', 'viewer ')} ${made.result.viewerUrl}`);+ if (made.result.studioUrl) console.log(` ${c('90', 'studio ')} ${made.result.studioUrl}`);+ console.log('');+ console.log(c('90', ' Paste this anywhere:'));+ console.log('');+ console.log(+ embedSnippet({ name: made.name, glbUrl: made.result.glbUrl, instructions: null })+ .split('\n')+ .map((l) => ` ${l}`)+ .join('\n'),+ );+ console.log('');+ console.log(c('90', ` Open the demo: npx serve ${dir}`));+ console.log('');+}++main().catch((err) => {+ if (err instanceof ForgeError) {+ console.error(`\ncreate-agent: ${err.message}`);+ if (err.code === 'timeout') {+ console.error('Nothing was lost: the forge keeps finished models at https://three.ws/creations');+ }+ process.exit(1);+ }+ console.error(`\ncreate-agent: ${err?.message || err}`);+ process.exit(1);+});diff --git a/packages/create-agent/package.json b/packages/create-agent/package.jsonnew file mode 100644index 000000000..c52431bba--- /dev/null+++ b/packages/create-agent/package.json@@ -0,0 +1,45 @@+{+ "name": "@three-ws/create-agent",+ "version": "0.1.0",+ "description": "One command from a sentence to a rigged, animated 3D agent you can embed anywhere. npm create @three-ws/agent \"a friendly cartoon astronaut\"",+ "keywords": [+ "three.ws",+ "3d",+ "avatar",+ "agent",+ "text-to-3d",+ "glb",+ "gltf",+ "rigging",+ "web-component",+ "scaffold",+ "create"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "Apache-2.0",+ "homepage": "https://three.ws/create",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/create-agent"+ },+ "type": "module",+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "bin": {+ "create-agent": "./bin/create-agent.js"+ },+ "files": [+ "src",+ "bin",+ "README.md"+ ],+ "engines": {+ "node": ">=18"+ },+ "publishConfig": {+ "access": "public"+ }+}diff --git a/packages/create-agent/src/args.js b/packages/create-agent/src/args.jsnew file mode 100644index 000000000..613b0e9ad--- /dev/null+++ b/packages/create-agent/src/args.js@@ -0,0 +1,45 @@+/**+ * Command line surface for `npm create @three-ws/agent`.+ *+ * Split out of the executable so the parser can be tested directly: importing+ * the bin would run the whole generation.+ */++export const USAGE = `npm create @three-ws/agent "<what to make>" [options]++ "<what to make>" describe a single full-body character+ --photo <url> build from a public https reference image instead+ --out <dir> where to write the project (default: a slug of the prompt)+ --name <name> display name (default: derived from the description)+ --object make an object or prop instead of a rigged character+ --no-download skip writing agent.glb locally (keep the hosted URL only)+ --json print the result as JSON and nothing else+ --origin <url> API origin (default https://three.ws)+ -h, --help this message++Examples+ npm create @three-ws/agent "a friendly cartoon astronaut in a glossy white suit"+ npm create @three-ws/agent "a knight in worn steel armor" --out ./knight+ npm create @three-ws/agent --photo https://example.com/me.jpg --name "Me"+ npm create @three-ws/agent "a small ceramic frog figurine" --object+`;++export function parseArgs(argv) {+ const opts = { rig: true, download: true };+ const words = [];+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--photo' || arg === '--image') opts.imageUrl = argv[++i];+ else if (arg === '--out' || arg === '-o') opts.out = argv[++i];+ else if (arg === '--name') opts.name = argv[++i];+ else if (arg === '--object' || arg === '--prop') opts.rig = false;+ else if (arg === '--no-download') opts.download = false;+ else if (arg === '--json') opts.json = true;+ else if (arg === '--origin') opts.origin = argv[++i];+ else if (arg === '-h' || arg === '--help') opts.help = true;+ else if (arg.startsWith('-')) opts.unknown = arg;+ else words.push(arg);+ }+ if (words.length) opts.prompt = words.join(' ');+ return opts;+}diff --git a/packages/create-agent/src/forge.js b/packages/create-agent/src/forge.jsnew file mode 100644index 000000000..26ccf99f4--- /dev/null+++ b/packages/create-agent/src/forge.js@@ -0,0 +1,178 @@+/**+ * The three.ws forge, over the public JSON-RPC endpoint.+ *+ * `https://three.ws/api/mcp-studio` is open: no key, no account, no signup. The+ * platform's own provider keys cover the cost, which is what makes+ * `npm create @three-ws/agent "a knight"` work on a machine that has never+ * heard of three.ws.+ *+ * Two tools are used here:+ * forge_avatar a humanoid character, generated and then rigged (a skeleton,+ * so it can be posed and animated)+ * forge_free any other object or prop, mesh only, on the free lane+ *+ * Both are long jobs: the call blocks server-side until the model exists. That+ * is why every request carries an explicit deadline and the caller gets real+ * elapsed-time progress rather than a fake bar.+ */++export const FORGE_ORIGIN = 'https://three.ws';+const RPC_PATH = '/api/mcp-studio';++// Generation genuinely takes minutes on the high tier. The deadline is long,+// but it exists: a hung socket must fail with an explanation, not sit forever.+export const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;+const HEARTBEAT_MS = 15_000;++export class ForgeError extends Error {+ constructor(message, { code = 'forge_failed', cause } = {}) {+ super(message);+ this.name = 'ForgeError';+ this.code = code;+ if (cause) this.cause = cause;+ }+}++/**+ * Normalize whatever the tool returned into one shape.+ * Exported because it is the part worth testing without a network.+ */+export function readForgeResult(body, { kind }) {+ if (body?.error) {+ throw new ForgeError(body.error.message || 'the forge refused the request', {+ code: 'rpc_error',+ });+ }+ const result = body?.result;+ const structured = result?.structuredContent || result;+ const glbUrl = structured?.glbUrl || structured?.riggedGlbUrl || structured?.modelUrl;+ if (!glbUrl) {+ throw new ForgeError('the forge answered without a model URL', { code: 'no_model' });+ }+ return {+ kind: structured.kind || kind,+ glbUrl,+ meshUrl: structured.meshUrl || null,+ viewerUrl: structured.viewerUrl || `${FORGE_ORIGIN}/viewer?src=${encodeURIComponent(glbUrl)}`,+ studioUrl: structured.studioUrl || structured.poseUrl || null,+ rigged: Boolean(structured.rigged ?? kind === 'avatar'),+ backend: structured.backend || null,+ durationMs: Number(structured.durationMs) || null,+ };+}++/**+ * Call one forge tool and wait for the model.+ *+ * @param {object} opts+ * @param {'forge_avatar'|'forge_free'} opts.tool+ * @param {object} opts.args tool arguments+ * @param {(event:{phase:string, elapsedMs:number, message:string}) => void} [opts.onProgress]+ * @param {string} [opts.origin]+ * @param {number} [opts.timeoutMs]+ * @param {typeof fetch} [opts.fetchImpl]+ * @param {AbortSignal} [opts.signal]+ */+export async function callForge({+ tool,+ args,+ onProgress = () => {},+ origin = FORGE_ORIGIN,+ timeoutMs = DEFAULT_TIMEOUT_MS,+ fetchImpl,+ signal,+}) {+ const doFetch = fetchImpl || globalThis.fetch;+ if (typeof doFetch !== 'function') throw new ForgeError('no fetch implementation available');++ const startedAt = Date.now();+ const controller = new AbortController();+ const onAbort = () => controller.abort(signal?.reason);+ signal?.addEventListener('abort', onAbort, { once: true });+ const deadline = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);++ // The job runs server-side inside one request, so there is no poll to report.+ // A heartbeat with real elapsed seconds is the honest alternative to a+ // progress bar that is making its numbers up.+ const heartbeat = setInterval(() => {+ onProgress({+ phase: 'working',+ elapsedMs: Date.now() - startedAt,+ message: describeWait(Date.now() - startedAt, tool),+ });+ }, HEARTBEAT_MS);++ onProgress({ phase: 'submitted', elapsedMs: 0, message: 'sent to the three.ws forge' });++ try {+ const res = await doFetch(new URL(RPC_PATH, origin), {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: tool, arguments: args },+ }),+ signal: controller.signal,+ });+ if (!res.ok) {+ throw new ForgeError(`three.ws answered ${res.status}`, { code: `http_${res.status}` });+ }+ const result = readForgeResult(await res.json(), {+ kind: tool === 'forge_avatar' ? 'avatar' : 'model',+ });+ onProgress({+ phase: 'done',+ elapsedMs: Date.now() - startedAt,+ message: 'model ready',+ });+ return result;+ } catch (err) {+ if (err instanceof ForgeError) throw err;+ if (controller.signal.aborted) {+ throw new ForgeError(+ `the forge did not answer within ${Math.round(timeoutMs / 1000)}s. The job may still finish: check https://three.ws/creations`,+ { code: 'timeout', cause: err },+ );+ }+ throw new ForgeError(`could not reach three.ws: ${err?.message || err}`, {+ code: 'unreachable',+ cause: err,+ });+ } finally {+ clearInterval(heartbeat);+ clearTimeout(deadline);+ signal?.removeEventListener('abort', onAbort);+ }+}++function describeWait(elapsedMs, tool) {+ const s = Math.round(elapsedMs / 1000);+ if (tool === 'forge_avatar') {+ if (s < 45) return `generating the figure (${s}s)`;+ if (s < 120) return `generating the figure, then the skeleton (${s}s)`;+ return `still working (${s}s). Rigging is the slow half`;+ }+ return `generating geometry and texture (${s}s)`;+}++/**+ * Download the model bytes. Returns the buffer and its size; the caller decides+ * where to put it.+ */+export async function downloadModel(url, { fetchImpl, timeoutMs = 120_000 } = {}) {+ const doFetch = fetchImpl || globalThis.fetch;+ const res = await doFetch(url, { signal: AbortSignal.timeout(timeoutMs) }).catch((err) => {+ throw new ForgeError(`could not download the model: ${err?.message || err}`, {+ code: 'download_failed',+ cause: err,+ });+ });+ if (!res.ok) {+ throw new ForgeError(`the model URL answered ${res.status}`, { code: `http_${res.status}` });+ }+ const bytes = Buffer.from(await res.arrayBuffer());+ if (!bytes.length) throw new ForgeError('the model URL returned an empty file', { code: 'empty' });+ return bytes;+}diff --git a/packages/create-agent/src/index.js b/packages/create-agent/src/index.jsnew file mode 100644index 000000000..fb7414710--- /dev/null+++ b/packages/create-agent/src/index.js@@ -0,0 +1,99 @@+/**+ * @three-ws/create-agent+ *+ * One command from a sentence to a rigged 3D agent:+ *+ * npm create @three-ws/agent "a friendly cartoon astronaut"+ *+ * The programmatic entry point is `createAgent()`, so the same pipeline can run+ * inside a build script, a bot, or another CLI.+ */++import { mkdir, writeFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';++import { callForge, downloadModel, ForgeError, FORGE_ORIGIN } from './forge.js';+import { projectFiles, slugify, titleFrom, embedSnippet } from './scaffold.js';++export { ForgeError, FORGE_ORIGIN, embedSnippet, slugify, titleFrom };+export { callForge, downloadModel } from './forge.js';+export { projectFiles, demoPage, agentRecord, readme, LOADER_URL } from './scaffold.js';++/**+ * Generate an agent and write a runnable project.+ *+ * @param {object} opts+ * @param {string} [opts.prompt] what to make ("a friendly cartoon astronaut")+ * @param {string} [opts.imageUrl] an https reference image, instead of a prompt+ * @param {string} [opts.out] target directory (default: a slug of the prompt)+ * @param {string} [opts.name] display name (default: derived from the prompt)+ * @param {boolean} [opts.rig] rig the result as a humanoid (default true)+ * @param {boolean} [opts.download] write agent.glb locally (default true)+ * @param {(e:{phase:string,message:string,elapsedMs:number}) => void} [opts.onProgress]+ * @param {string} [opts.origin]+ * @param {typeof fetch} [opts.fetchImpl]+ * @param {AbortSignal} [opts.signal]+ * @returns {Promise<{dir:string, files:string[], result:object, name:string, bytes:number}>}+ */+export async function createAgent({+ prompt,+ imageUrl,+ out,+ name,+ rig = true,+ download = true,+ onProgress = () => {},+ origin = FORGE_ORIGIN,+ fetchImpl,+ signal,+} = {}) {+ if (!prompt && !imageUrl) {+ throw new ForgeError('describe what to make, or pass a reference image url', {+ code: 'no_input',+ });+ }+ if (prompt && String(prompt).trim().length < 3) {+ throw new ForgeError('the description needs at least 3 characters', { code: 'short_prompt' });+ }+ if (imageUrl && !/^https:\/\//i.test(imageUrl)) {+ throw new ForgeError('a reference image must be a public https url', { code: 'bad_image' });+ }++ const displayName = name || titleFrom(prompt || 'agent');+ const dir = resolve(out || slugify(prompt || 'agent'));++ const result = await callForge({+ tool: rig ? 'forge_avatar' : 'forge_free',+ args: rig+ ? imageUrl+ ? { image_url: imageUrl }+ : { prompt }+ : { prompt, tier: 'draft' },+ onProgress,+ origin,+ fetchImpl,+ signal,+ });++ await mkdir(dir, { recursive: true });+ const files = projectFiles({ name: displayName, prompt, imageUrl, result, dir });+ for (const [file, contents] of Object.entries(files)) {+ await writeFile(join(dir, file), contents, 'utf8');+ }++ let bytes = 0;+ if (download) {+ onProgress({ phase: 'download', elapsedMs: 0, message: 'downloading the model' });+ const buffer = await downloadModel(result.glbUrl, { fetchImpl });+ await writeFile(join(dir, 'agent.glb'), buffer);+ bytes = buffer.length;+ }++ return {+ dir,+ files: Object.keys(files).concat(download ? ['agent.glb'] : []),+ result,+ name: displayName,+ bytes,+ };+}diff --git a/packages/create-agent/src/scaffold.js b/packages/create-agent/src/scaffold.jsnew file mode 100644index 000000000..0a7a3ee72--- /dev/null+++ b/packages/create-agent/src/scaffold.js@@ -0,0 +1,199 @@+/**+ * What lands on disk after a generation.+ *+ * Pure string builders, so the shape of a generated project is testable without+ * a network, a filesystem, or a real model. The rule for every file here: it+ * must work when the person opens it, with no build step and no server.+ */++export const LOADER_URL = 'https://three.ws/agent-3d/latest/agent-3d.js';++/** A filesystem-safe directory name derived from what the person asked for. */+export function slugify(text, fallback = 'agent') {+ const slug = String(text || '')+ .toLowerCase()+ .normalize('NFKD')+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .split('-')+ .filter(Boolean)+ .slice(0, 4)+ .join('-');+ return slug || fallback;+}++/** A display name from a prompt: "a friendly cartoon astronaut" -> "Friendly Cartoon Astronaut". */+export function titleFrom(text, fallback = 'Agent') {+ const words = String(text || '')+ .replace(/^(a|an|the)\s+/i, '')+ .split(/\s+/)+ .filter(Boolean)+ .slice(0, 4);+ if (!words.length) return fallback;+ return words.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');+}++export function escapeHtml(value) {+ return String(value ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++/**+ * The embed snippet. This is the thing people paste into their own site, so it+ * is also the thing the CLI prints.+ */+export function embedSnippet({ name, glbUrl, instructions }) {+ const attrs = [+ `body="${escapeHtml(glbUrl)}"`,+ `name="${escapeHtml(name)}"`,+ instructions ? `instructions="${escapeHtml(instructions)}"` : null,+ 'style="width:100%;max-width:420px;height:520px"',+ ].filter(Boolean);+ return [+ `<script type="module" src="${LOADER_URL}"></script>`,+ '',+ `<agent-3d ${attrs.join('\n ')}></agent-3d>`,+ ].join('\n');+}++/**+ * The demo page. It points at the hosted model URL rather than the local file+ * on purpose: a page opened straight off the disk (file://) cannot fetch a+ * neighbouring .glb without a server, and a demo that shows nothing on a double+ * click is worse than no demo. The local copy is there for hosting.+ */+export function demoPage({ name, prompt, glbUrl, viewerUrl, rigged }) {+ return `<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>${escapeHtml(name)}</title>+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <script type="module" src="${LOADER_URL}"></script>+ <style>+ :root { color-scheme: light dark; }+ body {+ margin: 0; min-height: 100vh; display: grid; place-items: center; gap: 24px;+ padding: 40px 20px; box-sizing: border-box;+ font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ background: #0b0b16; color: #f6f7fb;+ }+ @media (prefers-color-scheme: light) { body { background: #fff; color: #0b0b18; } }+ main { display: grid; gap: 18px; justify-items: center; text-align: center; max-width: 560px; }+ h1 { margin: 0; font-size: 26px; letter-spacing: -0.02em; }+ p { margin: 0; opacity: 0.7; font-size: 14px; line-height: 1.6; }+ agent-3d { width: 100%; max-width: 420px; height: 520px; border-radius: 20px; overflow: hidden; }+ code { font-size: 12.5px; opacity: 0.8; }+ a { color: inherit; }+ </style>+ </head>+ <body>+ <main>+ <h1>${escapeHtml(name)}</h1>+ <p>${escapeHtml(prompt)}</p>+ <agent-3d+ body="${escapeHtml(glbUrl)}"+ name="${escapeHtml(name)}"+ style="width:100%;max-width:420px;height:520px"+ ></agent-3d>+ <p>+ ${rigged ? 'Rigged: this figure has a humanoid skeleton, so it can be posed and animated.' : 'Mesh only: no skeleton on this one.'}+ Open it in the <a href="${escapeHtml(viewerUrl)}">three.ws viewer</a>, or drop+ <code>agent.glb</code> into Blender, Unity, or any glTF tool.+ </p>+ </main>+ </body>+</html>+`;+}++/** The record of what was made. Machine-readable, so a script can pick it up. */+export function agentRecord({ name, prompt, imageUrl, result, createdAt = new Date() }) {+ return `${JSON.stringify(+ {+ name,+ prompt: prompt || null,+ imageUrl: imageUrl || null,+ kind: result.kind,+ rigged: result.rigged,+ glbUrl: result.glbUrl,+ viewerUrl: result.viewerUrl,+ studioUrl: result.studioUrl,+ backend: result.backend,+ generationMs: result.durationMs,+ createdAt: createdAt.toISOString(),+ madeWith: '@three-ws/create-agent',+ },+ null,+ '\t',+ )}\n`;+}++export function readme({ name, prompt, result, dir }) {+ return `# ${name}++Made with one command:++\`\`\`bash+npm create @three-ws/agent "${prompt}"+\`\`\`++## What is in here++| File | What it is |+| --- | --- |+| \`agent.glb\` | The 3D model${result.rigged ? ', with a humanoid skeleton (poseable and animatable)' : ''}. Open it in Blender, Unity, Godot, or any glTF tool. |+| \`index.html\` | A working demo page. Open it in a browser. |+| \`agent.json\` | The record: the prompt, the hosted URLs, and how it was made. |++## Put it on your site++\`\`\`html+${embedSnippet({ name, glbUrl: result.glbUrl, instructions: null })}+\`\`\`++That is the whole integration. The element loads the model, renders it with+three.js, and needs no build step and no API key. Full attribute reference:+<https://three.ws/docs/web-component>.++## Host the model yourself++\`\`\`html+<agent-3d body="/agent.glb" name="${name}"></agent-3d>+\`\`\`++\`agent.glb\` in this folder is yours. Serve it from your own origin and point+\`body\` at it; nothing here calls back to three.ws except the loader script.+Serving the folder locally (\`npx serve ${dir}\`) is enough to try it.++## Links++- Viewer: ${result.viewerUrl}+${result.studioUrl ? `- Pose studio: ${result.studioUrl}\n` : ''}- Hosted model: ${result.glbUrl}+- Docs: <https://three.ws/docs/create-agent>++## Next++- Give it a voice and a personality: <https://three.ws/create>+- Put its live status on your home screen or in a README: <https://three.ws/glance>+- Publish it so other agents can hire it: <https://three.ws/marketplace>+`;+}++/** Every file a generated project contains, as { path: contents }. */+export function projectFiles({ name, prompt, imageUrl, result, dir }) {+ return {+ 'index.html': demoPage({+ name,+ prompt: prompt || 'Generated from a reference image.',+ glbUrl: result.glbUrl,+ viewerUrl: result.viewerUrl,+ rigged: result.rigged,+ }),+ 'agent.json': agentRecord({ name, prompt, imageUrl, result }),+ 'README.md': readme({ name, prompt: prompt || 'a character from a photo', result, dir }),+ };+}diff --git a/tests/create-agent.test.js b/tests/create-agent.test.jsnew file mode 100644index 000000000..dfc8662af--- /dev/null+++ b/tests/create-agent.test.js@@ -0,0 +1,292 @@+// @three-ws/create-agent: the one-command path from a sentence to a rigged 3D+// character.+//+// The network half is exercised through an injected fetch (the real free lane+// takes minutes and costs GPU time); the file half runs against a real temp+// directory, because "it wrote a project you can open" is the whole promise.++import { describe, it, expect, vi } from 'vitest';+import { mkdtemp, readFile, readdir } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { parseArgs } from '../packages/create-agent/src/args.js';+import { readForgeResult, callForge, ForgeError } from '../packages/create-agent/src/forge.js';+import {+ slugify,+ titleFrom,+ embedSnippet,+ demoPage,+ projectFiles,+ LOADER_URL,+} from '../packages/create-agent/src/scaffold.js';+import { createAgent } from '../packages/create-agent/src/index.js';++const RESULT = {+ kind: 'avatar',+ glbUrl: 'https://three.ws/cdn/creations/abc/rigged.glb',+ viewerUrl: 'https://three.ws/viewer?src=abc',+ studioUrl: 'https://three.ws/studio/abc',+ rigged: true,+ backend: 'hunyuan3d',+ durationMs: 84_000,+};++function rpcOk(structured = RESULT) {+ return {+ ok: true,+ status: 200,+ json: async () => ({ jsonrpc: '2.0', id: 1, result: { structuredContent: structured } }),+ };+}++describe('parseArgs', () => {+ it('takes the description as bare words, so quoting is optional', () => {+ expect(parseArgs(['a', 'friendly', 'astronaut']).prompt).toBe('a friendly astronaut');+ });++ it('defaults to a rigged humanoid with a local model file', () => {+ const opts = parseArgs(['a knight']);+ expect(opts.rig).toBe(true);+ expect(opts.download).toBe(true);+ });++ it('reads every documented flag', () => {+ const opts = parseArgs([+ 'a knight',+ '--out',+ './k',+ '--name',+ 'Sir',+ '--object',+ '--no-download',+ '--json',+ '--origin',+ 'http://localhost:3000',+ ]);+ expect(opts).toMatchObject({+ prompt: 'a knight',+ out: './k',+ name: 'Sir',+ rig: false,+ download: false,+ json: true,+ origin: 'http://localhost:3000',+ });+ });++ it('flags an unknown option rather than silently ignoring it', () => {+ expect(parseArgs(['a knight', '--turbo']).unknown).toBe('--turbo');+ });++ it('accepts a reference image instead of a description', () => {+ expect(parseArgs(['--photo', 'https://example.com/me.jpg']).imageUrl).toBe(+ 'https://example.com/me.jpg',+ );+ });+});++describe('readForgeResult', () => {+ it('normalizes the tool payload into one shape', () => {+ const body = { result: { structuredContent: RESULT } };+ expect(readForgeResult(body, { kind: 'avatar' })).toMatchObject({+ glbUrl: RESULT.glbUrl,+ rigged: true,+ backend: 'hunyuan3d',+ });+ });++ it('accepts riggedGlbUrl, which the avatar lane returns instead', () => {+ const body = { result: { riggedGlbUrl: 'https://three.ws/x.glb' } };+ expect(readForgeResult(body, { kind: 'avatar' }).glbUrl).toBe('https://three.ws/x.glb');+ });++ it('synthesizes a viewer link when the tool did not send one', () => {+ const body = { result: { glbUrl: 'https://three.ws/x.glb' } };+ expect(readForgeResult(body, { kind: 'model' }).viewerUrl).toBe(+ 'https://three.ws/viewer?src=https%3A%2F%2Fthree.ws%2Fx.glb',+ );+ });++ it('surfaces a JSON-RPC error as a readable failure', () => {+ expect(() => readForgeResult({ error: { message: 'prompt rejected' } }, { kind: 'avatar' })).toThrow(+ /prompt rejected/,+ );+ });++ it('refuses a response with no model rather than scaffolding an empty project', () => {+ expect(() => readForgeResult({ result: {} }, { kind: 'avatar' })).toThrow(/without a model URL/);+ });+});++describe('callForge', () => {+ it('calls the public JSON-RPC endpoint with the tool and arguments', async () => {+ const fetchImpl = vi.fn(async () => rpcOk());+ await callForge({ tool: 'forge_avatar', args: { prompt: 'a knight' }, fetchImpl });+ const [url, init] = fetchImpl.mock.calls[0];+ expect(String(url)).toBe('https://three.ws/api/mcp-studio');+ expect(JSON.parse(init.body)).toMatchObject({+ method: 'tools/call',+ params: { name: 'forge_avatar', arguments: { prompt: 'a knight' } },+ });+ expect(init.signal).toBeDefined();+ });++ it('reports the phases a caller can actually show', async () => {+ const seen = [];+ await callForge({+ tool: 'forge_avatar',+ args: { prompt: 'a knight' },+ fetchImpl: async () => rpcOk(),+ onProgress: (e) => seen.push(e.phase),+ });+ expect(seen).toEqual(['submitted', 'done']);+ });++ it('turns an HTTP failure into a ForgeError carrying the status', async () => {+ const fetchImpl = async () => ({ ok: false, status: 503, json: async () => ({}) });+ await expect(callForge({ tool: 'forge_free', args: {}, fetchImpl })).rejects.toMatchObject({+ name: 'ForgeError',+ code: 'http_503',+ });+ });++ it('explains an unreachable host instead of leaking a socket error', async () => {+ const fetchImpl = async () => {+ throw new Error('ENOTFOUND');+ };+ await expect(callForge({ tool: 'forge_free', args: {}, fetchImpl })).rejects.toThrow(+ /could not reach three\.ws/,+ );+ });+});++describe('scaffold', () => {+ it('derives a short directory name and a display name from the prompt', () => {+ expect(slugify('a friendly cartoon astronaut in a glossy white suit')).toBe(+ 'a-friendly-cartoon-astronaut',+ );+ expect(titleFrom('a friendly cartoon astronaut')).toBe('Friendly Cartoon Astronaut');+ expect(slugify('!!!')).toBe('agent');+ expect(titleFrom('')).toBe('Agent');+ });++ it('emits an embed snippet that is the whole integration', () => {+ const snippet = embedSnippet({ name: 'Astro', glbUrl: 'https://three.ws/a.glb' });+ expect(snippet).toContain(LOADER_URL);+ expect(snippet).toContain('body="https://three.ws/a.glb"');+ expect(snippet).toContain('name="Astro"');+ });++ it('escapes a prompt that would otherwise break the generated page', () => {+ const page = demoPage({+ name: '<img onerror=alert(1)>',+ prompt: 'a "quoted" & dangerous <script>',+ glbUrl: 'https://three.ws/a.glb',+ viewerUrl: 'https://three.ws/viewer',+ rigged: true,+ });+ expect(page).not.toContain('<script>a');+ expect(page).toContain('<img onerror=alert(1)>');+ expect(page).toContain('&');+ });++ it('points the demo page at the hosted model so a double click still works', () => {+ const page = demoPage({+ name: 'Astro',+ prompt: 'astronaut',+ glbUrl: 'https://three.ws/a.glb',+ viewerUrl: 'https://three.ws/viewer',+ rigged: true,+ });+ expect(page).toContain('body="https://three.ws/a.glb"');+ expect(page).not.toContain('body="agent.glb"');+ });++ it('writes three files, and says in the README which is which', () => {+ const files = projectFiles({ name: 'Astro', prompt: 'astronaut', result: RESULT, dir: 'astro' });+ expect(Object.keys(files).sort()).toEqual(['README.md', 'agent.json', 'index.html']);+ expect(JSON.parse(files['agent.json'])).toMatchObject({+ name: 'Astro',+ prompt: 'astronaut',+ glbUrl: RESULT.glbUrl,+ rigged: true,+ madeWith: '@three-ws/create-agent',+ });+ expect(files['README.md']).toContain('agent.glb');+ });+});++describe('createAgent', () => {+ it('refuses to call the forge with nothing to make', async () => {+ await expect(createAgent({})).rejects.toThrow(/describe what to make/);+ await expect(createAgent({ prompt: 'ab' })).rejects.toThrow(/at least 3 characters/);+ await expect(createAgent({ imageUrl: 'http://example.com/x.jpg' })).rejects.toThrow(+ /public https url/,+ );+ });++ it('writes a runnable project, model included', async () => {+ const out = join(await mkdtemp(join(tmpdir(), 'create-agent-')), 'astro');+ const glb = Buffer.from('glTF binary bytes');+ const fetchImpl = vi.fn(async (url) =>+ String(url).endsWith('.glb')+ ? { ok: true, status: 200, arrayBuffer: async () => glb }+ : rpcOk(),+ );++ const made = await createAgent({ prompt: 'a friendly astronaut', out, fetchImpl });++ expect(made.name).toBe('Friendly Astronaut');+ expect(made.bytes).toBe(glb.length);+ expect((await readdir(out)).sort()).toEqual(['README.md', 'agent.glb', 'agent.json', 'index.html']);+ expect(await readFile(join(out, 'agent.glb'))).toEqual(glb);+ expect(await readFile(join(out, 'index.html'), 'utf8')).toContain(RESULT.glbUrl);+ });++ it('skips the download when asked, and still writes the project', async () => {+ const out = join(await mkdtemp(join(tmpdir(), 'create-agent-')), 'astro');+ const fetchImpl = vi.fn(async () => rpcOk());+ const made = await createAgent({ prompt: 'a knight', out, download: false, fetchImpl });+ expect(made.bytes).toBe(0);+ expect(await readdir(out)).not.toContain('agent.glb');+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ });++ it('routes an object to the free mesh lane instead of the rigging lane', async () => {+ const out = join(await mkdtemp(join(tmpdir(), 'create-agent-')), 'frog');+ const fetchImpl = vi.fn(async () => rpcOk({ ...RESULT, kind: 'model', rigged: false }));+ await createAgent({ prompt: 'a ceramic frog', out, rig: false, download: false, fetchImpl });+ expect(JSON.parse(fetchImpl.mock.calls[0][1].body).params).toMatchObject({+ name: 'forge_free',+ arguments: { prompt: 'a ceramic frog', tier: 'draft' },+ });+ });++ it('sends a reference image as image_url on the avatar lane', async () => {+ const out = join(await mkdtemp(join(tmpdir(), 'create-agent-')), 'me');+ const fetchImpl = vi.fn(async () => rpcOk());+ await createAgent({+ imageUrl: 'https://example.com/me.jpg',+ out,+ download: false,+ fetchImpl,+ });+ expect(JSON.parse(fetchImpl.mock.calls[0][1].body).params.arguments).toEqual({+ image_url: 'https://example.com/me.jpg',+ });+ });++ it('propagates a forge failure instead of leaving half a project', async () => {+ const out = join(await mkdtemp(join(tmpdir(), 'create-agent-')), 'nope');+ const fetchImpl = async () => ({+ ok: true,+ status: 200,+ json: async () => ({ error: { message: 'safety filter' } }),+ });+ await expect(createAgent({ prompt: 'a knight', out, fetchImpl })).rejects.toBeInstanceOf(+ ForgeError,+ );+ await expect(readdir(out)).rejects.toThrow();+ });+});