@clarity-js/agent 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,346 @@
1
+ // @clarity-js/agent — the second wave of asset connectors, each written against its service's published API (the
2
+ // docs URL is on each one). Same shape as adapters.js: generate(req, ctx) → { files: [{ url | bytes, ext }], usd?, meta? }.
3
+
4
+ import { spawn } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { randomUUID } from 'node:crypto';
9
+ import { client, waitFor, b64, form, extOf, ConnectorError } from './http.js';
10
+ import { sizeOf, unknown, fixed, findFiles } from './adapters.js';
11
+
12
+ const ratioOf = (aspect, pairs) => pairs[aspect] ?? Object.values(pairs)[0];
13
+ const fail = (name, id, what, body) => { throw new ConnectorError(`${name}: ${what}.`, { connector: id, body }); };
14
+
15
+ // ── Runway: Gen-4.5 video, Gen-4 images, sound effects and music ─────────────────────────────
16
+ const runway = {
17
+ id: 'runway', name: 'Runway (Gen-4.5 video, images, sound, music)', kinds: ['video', 'image', 'sfx', 'music'], keyEnv: 'RUNWAYML_API_SECRET', docs: 'https://docs.dev.runwayml.com',
18
+ models: { video: 'gen4.5', image: 'gen4_image_turbo', sfx: 'eleven_text_to_sound_v2', music: 'eleven_music_v2_5' }, version: '2024-11-06',
19
+ estimate: (req) => req.kind === 'video' ? fixed(+(0.12 * Math.min(10, Math.max(2, Math.round(req.seconds ?? 5)))).toFixed(2), 'Gen-4.5: $0.12 a second') : req.kind === 'image' ? fixed(0.02, 'gen4_image_turbo: $0.02 an image') : unknown('Runway bills sound and music in credits'),
20
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
21
+ const base = config.baseUrl ?? 'https://api.dev.runwayml.com/v1', api = client({ name: 'Runway', headers: { authorization: `Bearer ${key}`, 'x-runway-version': config.version ?? this.version }, fetchImpl, signal });
22
+ const model = req.model ?? config.models?.[req.kind] ?? this.models[req.kind];
23
+ const body = req.kind === 'video' ? { model, promptText: req.prompt, ratio: req.aspect === '9:16' ? '720:1280' : '1280:720', duration: Math.min(10, Math.max(2, Math.round(req.seconds ?? 5))) }
24
+ : req.kind === 'image' ? { model, promptText: req.prompt, ratio: ratioOf(req.aspect, { '16:9': '1920:1080', '9:16': '1080:1920', '1:1': '1024:1024', '4:3': '1440:1080', '3:4': '1080:1440' }) }
25
+ : { model, promptText: req.prompt, ...(req.seconds ? { duration: req.kind === 'sfx' ? Math.min(30, Math.max(0.5, req.seconds)) : req.seconds } : {}) };
26
+ const path_ = { video: 'text_to_video', image: 'text_to_image', sfx: 'sound_effect', music: 'text_to_music' }[req.kind];
27
+ const sent = await api.post(`${base}/${path_}`, { ...body, ...(req.options ?? {}) });
28
+ if (!sent?.id) fail('Runway', 'runway', 'no task came back', sent);
29
+ const task = await waitFor(async () => { const t = await api.get(`${base}/tasks/${encodeURIComponent(sent.id)}`); if (t.status === 'SUCCEEDED') return t; if (['FAILED', 'CANCELLED'].includes(t.status)) fail('Runway', 'runway', `the task ${t.status.toLowerCase()}${t.failure ? `: ${t.failure}` : ''}`, t); return undefined; }, { every: 3000, signal, onProgress });
30
+ const ext = { video: 'mp4', image: 'png', sfx: 'mp3', music: 'mp3' }[req.kind];
31
+ return { files: (task.output ?? []).map((url) => ({ url, ext: extOf(url, ext) })), meta: { task: sent.id, model } };
32
+ },
33
+ };
34
+
35
+ // ── Luma: Ray video, Photon images ───────────────────────────────────────────────────────────
36
+ const luma = {
37
+ id: 'luma', name: 'Luma (Ray video, Photon images)', kinds: ['video', 'image'], keyEnv: 'LUMAAI_API_KEY', docs: 'https://docs.lumalabs.ai', models: { video: 'ray-2', image: 'photon-1' },
38
+ estimate: () => unknown('Luma bills each generation by model, length and resolution'),
39
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
40
+ const base = config.baseUrl ?? 'https://api.lumalabs.ai/dream-machine/v1', api = client({ name: 'Luma', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
41
+ const model = req.model ?? config.models?.[req.kind] ?? this.models[req.kind];
42
+ const aspect = ['1:1', '16:9', '9:16', '4:3', '3:4', '21:9', '9:21'].includes(req.aspect) ? req.aspect : '16:9';
43
+ const sent = await api.post(`${base}/generations/${req.kind === 'video' ? 'video' : 'image'}`, { model, prompt: req.prompt, aspect_ratio: aspect, ...(req.kind === 'video' ? { duration: (req.seconds ?? 5) > 6 ? '9s' : '5s' } : {}), ...(req.options ?? {}) });
44
+ if (!sent?.id) fail('Luma', 'luma', 'no generation came back', sent);
45
+ const g = await waitFor(async () => { const r = await api.get(`${base}/generations/${encodeURIComponent(sent.id)}`); if (r.state === 'completed') return r; if (r.state === 'failed') fail('Luma', 'luma', `the generation failed${r.failure_reason ? `: ${r.failure_reason}` : ''}`, r); return undefined; }, { every: 3000, signal, onProgress });
46
+ const url = req.kind === 'video' ? g.assets?.video : g.assets?.image;
47
+ if (!url) fail('Luma', 'luma', 'the generation finished with no file', g);
48
+ return { files: [{ url, ext: extOf(url, req.kind === 'video' ? 'mp4' : 'jpg') }], meta: { generation: sent.id, model } };
49
+ },
50
+ };
51
+
52
+ // ── Leonardo.ai ──────────────────────────────────────────────────────────────────────────────
53
+ const leonardo = {
54
+ id: 'leonardo', name: 'Leonardo.ai (images)', kinds: ['image', 'sprite', 'texture'], keyEnv: 'LEONARDO_API_KEY', docs: 'https://docs.leonardo.ai', models: { image: '6bef9f1b-29cb-40c7-b9df-32b51c1f67d3' },
55
+ estimate: () => unknown('Leonardo bills in API credits by size, model and features'),
56
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
57
+ const base = config.baseUrl ?? 'https://cloud.leonardo.ai/api/rest/v1', api = client({ name: 'Leonardo', headers: { authorization: `Bearer ${key}`, accept: 'application/json' }, fetchImpl, signal });
58
+ const [w, h] = sizeOf(req.aspect).map((n) => Math.round(n / 2 / 8) * 8); // 768x512 and the like: Leonardo's sizes go in steps of 8
59
+ const sent = await api.post(`${base}/generations`, { prompt: req.prompt, modelId: req.model ?? config.model ?? this.models.image, width: w, height: h, num_images: 1, ...(req.negative ? { negative_prompt: req.negative } : {}), ...(req.options ?? {}) });
60
+ const id = sent?.sdGenerationJob?.generationId;
61
+ if (!id) fail('Leonardo', 'leonardo', 'no generation came back', sent);
62
+ const g = await waitFor(async () => { const r = (await api.get(`${base}/generations/${encodeURIComponent(id)}`))?.generations_by_pk; if (r?.status === 'COMPLETE') return r; if (r?.status === 'FAILED') fail('Leonardo', 'leonardo', 'the generation failed', r); return undefined; }, { every: 2500, signal, onProgress });
63
+ return { files: (g.generated_images ?? []).map((i) => ({ url: i.url, ext: extOf(i.url, 'jpg') })), meta: { generation: id } };
64
+ },
65
+ };
66
+
67
+ // ── Runware: hundreds of models, one call ────────────────────────────────────────────────────
68
+ const runware = {
69
+ id: 'runware', name: 'Runware (images, video by model id)', kinds: ['image', 'sprite', 'texture', 'video'], keyEnv: 'RUNWARE_API_KEY', docs: 'https://runware.ai/docs', models: { image: 'runware:101@1' },
70
+ estimate: () => unknown('Runware bills each model at its own rate; the answer says what it cost'),
71
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
72
+ const base = config.baseUrl ?? 'https://api.runware.ai/v1', api = client({ name: 'Runware', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
73
+ const model = req.model ?? config.models?.[req.kind] ?? this.models[req.kind];
74
+ if (!model) fail('Runware', 'runware', `say which ${req.kind} model (model: "provider:id@version", from runware.ai/models)`);
75
+ const taskUUID = randomUUID(), [w, h] = sizeOf(req.aspect).map((n) => Math.round(n / 64) * 64);
76
+ const task = req.kind === 'video' ? { taskType: 'videoInference', taskUUID, positivePrompt: req.prompt, model, deliveryMethod: 'async', ...(req.seconds ? { duration: req.seconds } : {}) }
77
+ : { taskType: 'imageInference', taskUUID, positivePrompt: req.prompt, model, width: w, height: h, numberResults: 1, outputType: 'URL', includeCost: true, ...(req.negative ? { negativePrompt: req.negative } : {}) };
78
+ const first = await api.post(base, [{ ...task, ...(req.options ?? {}) }]);
79
+ if (first?.errors?.length) fail('Runware', 'runware', first.errors[0].message ?? 'the task was refused', first);
80
+ const done = (r) => (r?.data ?? []).find((d) => d.taskUUID === taskUUID && (d.imageURL || d.videoURL || d.status === 'success'));
81
+ let row = done(first);
82
+ if (!row) row = await waitFor(async () => { const r = await api.post(base, [{ taskType: 'getResponse', taskUUID }]); if (r?.errors?.length) fail('Runware', 'runware', r.errors[0].message ?? 'the task failed', r); return done(r); }, { every: 3000, signal, onProgress });
83
+ const url = row.imageURL ?? row.videoURL;
84
+ return { files: [{ url, ext: extOf(url, req.kind === 'video' ? 'mp4' : 'jpg') }], usd: typeof row.cost === 'number' ? row.cost : null, meta: { task: taskUUID, model } };
85
+ },
86
+ };
87
+
88
+ // ── WaveSpeedAI: a model id, its inputs, the result ──────────────────────────────────────────
89
+ const wavespeed = {
90
+ id: 'wavespeed', name: 'WaveSpeedAI (any model by id)', kinds: ['image', 'sprite', 'texture', 'video', 'voice', 'sfx', 'music', 'model3d'], keyEnv: 'WAVESPEED_API_KEY', docs: 'https://wavespeed.ai/docs', models: { image: 'wavespeed-ai/z-image/turbo' },
91
+ estimate: () => unknown('each WaveSpeed model page lists its price'),
92
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
93
+ const base = config.baseUrl ?? 'https://api.wavespeed.ai/api/v3', api = client({ name: 'WaveSpeed', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
94
+ const model = req.model ?? config.models?.[req.kind] ?? this.models[req.kind];
95
+ if (!model) fail('WaveSpeed', 'wavespeed', `say which ${req.kind} model (model: "owner/model/variant", from wavespeed.ai/models)`);
96
+ // a submitted job may be billed even if the answer is lost: never resend it, only ask for its result again
97
+ const sent = await api.post(`${base}/${String(model).replace(/^\//, '')}`, { prompt: req.prompt, ...(req.kind === 'image' || req.kind === 'sprite' || req.kind === 'texture' ? { size: sizeOf(req.aspect).join('*') } : {}), ...(req.seconds ? { duration: req.seconds } : {}), ...(req.refs?.[0] ? { image: req.refs[0] } : {}), ...(req.options ?? {}) });
98
+ const id = sent?.data?.id ?? sent?.id;
99
+ if (!id) fail('WaveSpeed', 'wavespeed', 'no prediction came back', sent);
100
+ const r = await waitFor(async () => { const q = (await api.get(`${base}/predictions/${encodeURIComponent(id)}/result`))?.data ?? {}; if (q.status === 'completed') return q; if (q.status === 'failed') fail('WaveSpeed', 'wavespeed', `the prediction failed${q.error ? `: ${q.error}` : ''}`, q); return undefined; }, { every: 2000, signal, onProgress });
101
+ const urls = (r.outputs ?? []).filter((u) => typeof u === 'string');
102
+ if (!urls.length) fail('WaveSpeed', 'wavespeed', 'the prediction finished with no file', r);
103
+ return { files: urls.map((u) => ({ url: u, ext: extOf(u, req.kind === 'video' ? 'mp4' : 'png') })), meta: { prediction: id, model } };
104
+ },
105
+ };
106
+
107
+ // ── PixVerse: video ──────────────────────────────────────────────────────────────────────────
108
+ const pixverse = {
109
+ id: 'pixverse', name: 'PixVerse (video)', kinds: ['video'], keyEnv: 'PIXVERSE_API_KEY', docs: 'https://docs.platform.pixverse.ai', models: { video: 'v6' },
110
+ estimate: () => unknown('PixVerse bills in credits by model, length and quality'),
111
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
112
+ const base = config.baseUrl ?? 'https://app-api.pixverse.ai/openapi/v2', trace = randomUUID();
113
+ const api = client({ name: 'PixVerse', headers: { 'API-KEY': key, 'Ai-trace-id': trace }, fetchImpl, signal });
114
+ const ok = (r) => { if (r?.ErrCode !== 0) fail('PixVerse', 'pixverse', `${r?.ErrCode ?? '?'} ${r?.ErrMsg ?? 'refused'} (trace ${trace})`, r); return r.Resp; };
115
+ const sent = ok(await api.post(`${base}/video/text/generate`, { model: req.model ?? this.models.video, prompt: req.prompt, duration: Math.round(req.seconds ?? 5), quality: '720p', aspect_ratio: ['16:9', '9:16', '4:3', '3:4', '1:1'].includes(req.aspect) ? req.aspect : '16:9', ...(req.options ?? {}) }));
116
+ const r = await waitFor(async () => { const q = ok(await api.get(`${base}/video/result/${encodeURIComponent(sent.video_id)}`)); if (q.status === 1 && q.url) return q; if (q.status === 7) fail('PixVerse', 'pixverse', 'the prompt did not pass moderation', q); if (q.status === 8) fail('PixVerse', 'pixverse', `the video failed (trace ${trace})`, q); return undefined; }, { every: 4000, signal, onProgress });
117
+ return { files: [{ url: r.url, ext: 'mp4' }], meta: { video: sent.video_id } };
118
+ },
119
+ };
120
+
121
+ // ── Atlas Cloud: image and video models from many companies, one key ─────────────────────────
122
+ const atlas = {
123
+ id: 'atlas', name: 'Atlas Cloud (image and video by model id)', kinds: ['image', 'sprite', 'texture', 'video'], keyEnv: 'ATLASCLOUD_API_KEY', docs: 'https://www.atlascloud.ai/docs', models: { video: 'bytedance/seedance-2.0/text-to-video' },
124
+ estimate: () => unknown('each Atlas Cloud model lists its price in its llms.txt'),
125
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
126
+ const base = config.baseUrl ?? 'https://api.atlascloud.ai/api/v1/model', api = client({ name: 'Atlas Cloud', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
127
+ const model = req.model ?? config.models?.[req.kind] ?? this.models[req.kind];
128
+ if (!model) fail('Atlas Cloud', 'atlas', `say which ${req.kind} model (model: "provider/model/task", from atlascloud.ai/models)`);
129
+ const sent = await api.post(`${base}/${req.kind === 'video' ? 'generateVideo' : 'generateImage'}`, { model, prompt: req.prompt, ...(req.aspect ? { aspect_ratio: req.aspect } : {}), ...(req.seconds ? { duration: req.seconds } : {}), ...(req.options ?? {}) });
130
+ const id = sent?.data?.id ?? sent?.data?.prediction_id;
131
+ if (!id) fail('Atlas Cloud', 'atlas', 'no prediction came back', sent);
132
+ const r = await waitFor(async () => { const q = (await api.get(`${base}/prediction/${encodeURIComponent(id)}`))?.data ?? {}; if (['completed', 'succeeded'].includes(q.status)) return q; if (q.status === 'failed') fail('Atlas Cloud', 'atlas', `the prediction failed${q.error ? `: ${q.error}` : ''}`, q); return undefined; }, { every: 3000, signal, onProgress });
133
+ const urls = (r.outputs ?? []).filter((u) => typeof u === 'string');
134
+ if (!urls.length) fail('Atlas Cloud', 'atlas', 'the prediction finished with no file', r);
135
+ return { files: urls.map((u) => ({ url: u, ext: extOf(u, req.kind === 'video' ? 'mp4' : 'png') })), meta: { prediction: id, model } };
136
+ },
137
+ };
138
+
139
+ // ── Ideogram: images with good lettering ─────────────────────────────────────────────────────
140
+ const ideogram = {
141
+ id: 'ideogram', name: 'Ideogram (images, lettering)', kinds: ['image', 'texture'], keyEnv: 'IDEOGRAM_API_KEY', docs: 'https://developer.ideogram.ai/v2/api-reference/images/generate/auto', models: { image: 'auto' },
142
+ estimate: () => unknown('Ideogram bills each model and speed at its own rate'),
143
+ async generate(req, { key, fetchImpl, signal, config = {} }) {
144
+ const base = config.baseUrl ?? 'https://api.ideogram.ai/v2/image/generate', api = client({ name: 'Ideogram', headers: { 'Api-Key': key }, fetchImpl, signal });
145
+ const r = await api.post(`${base}/${req.model ?? config.model ?? this.models.image}`, form({ prompt: req.prompt, negative_prompt: req.negative, aspect_ratio: req.aspect ? req.aspect.replace(':', 'x') : undefined, ...(req.options ?? {}) }));
146
+ const imgs = (r?.data ?? []).filter((d) => d.url);
147
+ if (!imgs.length) fail('Ideogram', 'ideogram', r?.data?.length ? 'the image did not pass the safety check' : 'no image came back', r);
148
+ return { files: imgs.map((d) => ({ url: d.url, ext: extOf(d.url, 'png') })) }; // the links expire: the generator downloads them at once
149
+ },
150
+ };
151
+
152
+ // ── Krea: Flux, Krea's own and other image models ────────────────────────────────────────────
153
+ const krea = {
154
+ id: 'krea', name: 'Krea (images)', kinds: ['image', 'texture', 'sprite'], keyEnv: 'KREA_API_TOKEN', docs: 'https://www.krea.ai/docs/developers', models: { image: 'bfl/flux-1-dev' },
155
+ estimate: () => unknown('Krea bills each model in compute units'),
156
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
157
+ const base = config.baseUrl ?? 'https://api.krea.ai', api = client({ name: 'Krea', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
158
+ const [width, height] = req.aspect === '16:9' ? [1024, 576] : req.aspect === '9:16' ? [576, 1024] : [1024, 1024];
159
+ const job = await api.post(`${base}/generate/image/${req.model ?? config.model ?? this.models.image}`, { prompt: req.prompt, width, height, ...(req.options ?? {}) });
160
+ if (!job?.job_id) fail('Krea', 'krea', 'no job came back', job);
161
+ const r = await waitFor(async () => { const j = await api.get(`${base}/jobs/${encodeURIComponent(job.job_id)}`); if (j.status === 'completed') return j; if (['failed', 'cancelled'].includes(j.status)) fail('Krea', 'krea', `the job ${j.status}`, j); return undefined; }, { every: 2000, signal, onProgress });
162
+ return { files: (r.result?.urls ?? []).map((u) => ({ url: u, ext: extOf(u, 'png') })), meta: { job: job.job_id } };
163
+ },
164
+ };
165
+
166
+ // ── Adobe Firefly ────────────────────────────────────────────────────────────────────────────
167
+ // the key is the Developer Console project's "client id:client secret"; a token is fetched for each run
168
+ const firefly = {
169
+ id: 'firefly', name: 'Adobe Firefly (images)', kinds: ['image', 'texture'], keyEnv: 'FIREFLY_CREDENTIALS', docs: 'https://developer.adobe.com/firefly-services/docs/firefly-api/', keyHint: 'client id:client secret',
170
+ estimate: () => unknown('Firefly is billed by your Adobe Firefly Services agreement'),
171
+ async generate(req, { key, fetchImpl = globalThis.fetch, signal, config = {} }) {
172
+ const [id, secret] = String(key).split(':');
173
+ if (!secret) fail('Firefly', 'firefly', 'the key is "client id:client secret" from the Adobe Developer Console project');
174
+ const tokenRes = await fetchImpl(config.tokenUrl ?? 'https://ims-na1.adobelogin.com/ims/token/v3', { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'client_credentials', client_id: id, client_secret: secret, scope: 'openid,AdobeID,session,additional_info,read_organizations,firefly_api,ff_apis' }).toString(), signal });
175
+ const token = (await tokenRes.json().catch(() => ({})))?.access_token;
176
+ if (!token) fail('Firefly', 'firefly', `no token (${tokenRes.status}): check the client id and secret`);
177
+ const api = client({ name: 'Firefly', headers: { 'x-api-key': id, authorization: `Bearer ${token}` }, fetchImpl, signal });
178
+ const [width, height] = req.aspect === '16:9' ? [2304, 1792] : req.aspect === '9:16' ? [1792, 2304] : [2048, 2048];
179
+ const r = await api.post(config.baseUrl ?? 'https://firefly-api.adobe.io/v2/images/generate', { prompt: req.prompt, n: 1, size: { width, height }, ...(req.negative ? { negativePrompt: req.negative } : {}), ...(req.options ?? {}) });
180
+ const urls = (r?.outputs ?? []).map((o) => o.image?.presignedUrl).filter(Boolean);
181
+ if (!urls.length) fail('Firefly', 'firefly', 'no image came back', r);
182
+ return { files: urls.map((u) => ({ url: u, ext: extOf(u, 'jpg') })) };
183
+ },
184
+ };
185
+
186
+ // ── Stable Diffusion WebUI (Forge, A1111) and Draw Things: on this computer ──────────────────
187
+ function sdWebui(id, name, port, docs) {
188
+ return {
189
+ id, name, kinds: ['image', 'sprite', 'texture'], local: true, docs,
190
+ estimate: () => fixed(0, 'runs on this computer'),
191
+ async generate(req, { fetchImpl, signal, config = {} }) {
192
+ const base = config.baseUrl ?? `http://127.0.0.1:${port}`, api = client({ name, fetchImpl, signal });
193
+ const [width, height] = sizeOf(req.aspect).map((n) => Math.round(n * 0.75 / 64) * 64);
194
+ const r = await api.post(`${base}/sdapi/v1/txt2img`, { prompt: req.prompt, negative_prompt: req.negative ?? '', width, height, steps: config.steps ?? 25, ...(req.model ? { override_settings: { sd_model_checkpoint: req.model } } : {}), ...(req.options ?? {}) });
195
+ if (!r?.images?.length) fail(name, id, 'no image came back', r);
196
+ return { files: r.images.map((d) => ({ bytes: b64(String(d).replace(/^data:[^,]+,/, '')), ext: 'png' })) };
197
+ },
198
+ };
199
+ }
200
+ const forge = sdWebui('forge', 'Stable Diffusion WebUI Forge / A1111 (this computer, --api)', 7860, 'https://github.com/lllyasviel/stable-diffusion-webui-forge');
201
+ const drawthings = sdWebui('drawthings', 'Draw Things (this Mac, HTTP API server on)', 7860, 'https://drawthings.ai');
202
+
203
+ // ── Vidu: video ──────────────────────────────────────────────────────────────────────────────
204
+ const vidu = {
205
+ id: 'vidu', name: 'Vidu (video)', kinds: ['video'], keyEnv: 'VIDU_API_KEY', docs: 'https://platform.vidu.com/docs', models: { video: 'viduq2' },
206
+ estimate: () => unknown('Vidu bills in credits by model, length and resolution'),
207
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
208
+ const base = config.baseUrl ?? 'https://api.vidu.com/ent/v2', api = client({ name: 'Vidu', headers: { authorization: `Token ${key}` }, fetchImpl, signal });
209
+ const sent = await api.post(`${base}/text2video`, { model: req.model ?? this.models.video, prompt: req.prompt, duration: Math.round(req.seconds ?? 5), aspect_ratio: ['16:9', '9:16', '1:1'].includes(req.aspect) ? req.aspect : '16:9', ...(req.options ?? {}) });
210
+ if (!sent?.task_id) fail('Vidu', 'vidu', 'no task came back', sent);
211
+ const r = await waitFor(async () => { const q = await api.get(`${base}/tasks/${encodeURIComponent(sent.task_id)}/creations`); if (q.state === 'success') return q; if (q.state === 'failed') fail('Vidu', 'vidu', `the task failed${q.err_code ? `: ${q.err_code}` : ''}`, q); return undefined; }, { every: 4000, signal, onProgress });
212
+ const urls = (r.creations ?? []).map((c) => c.url).filter(Boolean);
213
+ if (!urls.length) fail('Vidu', 'vidu', 'the task finished with no file', r);
214
+ return { files: urls.map((u) => ({ url: u, ext: 'mp4' })), meta: { task: sent.task_id } };
215
+ },
216
+ };
217
+
218
+ // ── 3D AI Studio: Hunyuan 3D and other 3D models ─────────────────────────────────────────────
219
+ const studio3d = {
220
+ id: '3daistudio', name: '3D AI Studio (Hunyuan 3D and more)', kinds: ['model3d'], keyEnv: 'THREEDAI_API_KEY', docs: 'https://www.3daistudio.com/Platform/API/Documentation', models: { model3d: '3.1' },
221
+ estimate: () => unknown('3D AI Studio bills in credits per model'),
222
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
223
+ const base = config.baseUrl ?? 'https://api.3daistudio.com/v1', api = client({ name: '3D AI Studio', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
224
+ const sent = await api.post(`${base}/3d-models/tencent/generate/pro/`, { model: req.model ?? this.models.model3d, prompt: req.prompt, enable_pbr: true, ...(req.options ?? {}) });
225
+ if (!sent?.task_id) fail('3D AI Studio', '3daistudio', 'no task came back', sent);
226
+ const r = await waitFor(async () => { const q = await api.get(`${base}/generation-request/${encodeURIComponent(sent.task_id)}/status/`); if (q.status === 'FINISHED') return q; if (['FAILED', 'ERROR', 'CANCELLED'].includes(q.status) || q.failure_reason) fail('3D AI Studio', '3daistudio', `the task failed${q.failure_reason ? `: ${q.failure_reason}` : ''}`, q); return undefined; }, { every: 5000, signal, onProgress });
227
+ const model = (r.results ?? []).find((x) => x.asset_type === '3D_MODEL') ?? r.results?.[0];
228
+ if (!model?.asset) fail('3D AI Studio', '3daistudio', 'the task finished with no model', r);
229
+ return { files: [{ url: model.asset, ext: extOf(model.asset, 'glb') }], meta: { task: sent.task_id } };
230
+ },
231
+ };
232
+
233
+ // ── voices: Inworld, Groq (Orpheus); music: Beatoven; Piper on this computer ─────────────────
234
+ const inworld = {
235
+ id: 'inworld', name: 'Inworld TTS (voices)', kinds: ['voice'], keyEnv: 'INWORLD_API_KEY', docs: 'https://docs.inworld.ai/api-reference/ttsAPI/texttospeech/synthesize-speech', models: { voice: 'inworld-tts-2' }, voice: 'Ashley', keyHint: 'the Base64 credential from Inworld Portal',
236
+ estimate: () => unknown('Inworld bills speech by characters'),
237
+ async generate(req, { key, fetchImpl, signal, config = {} }) {
238
+ const api = client({ name: 'Inworld', headers: { authorization: `Basic ${key}` }, fetchImpl, signal });
239
+ const r = await api.post(config.baseUrl ?? 'https://api.inworld.ai/tts/v1/voice', { text: req.prompt, voiceId: req.voice ?? config.voice ?? this.voice, modelId: req.model ?? this.models.voice, audioConfig: { audioEncoding: 'MP3' }, ...(req.options ?? {}) });
240
+ if (!r?.audioContent) fail('Inworld', 'inworld', 'no audio came back', r);
241
+ return { files: [{ bytes: b64(r.audioContent), ext: 'mp3' }], meta: { characters: r.usage?.processedCharactersCount ?? null } };
242
+ },
243
+ };
244
+ const groqTts = {
245
+ id: 'groq', name: 'Groq (Orpheus voices)', kinds: ['voice'], keyEnv: 'GROQ_API_KEY', docs: 'https://console.groq.com/docs/text-to-speech', models: { voice: 'canopylabs/orpheus-v1-english' }, voice: 'austin',
246
+ estimate: () => unknown('Groq bills speech by characters'),
247
+ async generate(req, { key, fetchImpl, signal, config = {} }) {
248
+ const api = client({ name: 'Groq', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
249
+ const r = await api.post(config.baseUrl ?? 'https://api.groq.com/openai/v1/audio/speech', { model: req.model ?? this.models.voice, voice: req.voice ?? config.voice ?? this.voice, input: req.prompt, response_format: 'wav', ...(req.options ?? {}) });
250
+ if (!r?.bytes) fail('Groq', 'groq', 'no audio came back', r);
251
+ return { files: [{ bytes: r.bytes, ext: 'wav' }] };
252
+ },
253
+ };
254
+ const beatoven = {
255
+ id: 'beatoven', name: 'Beatoven.ai (music, royalty-free)', kinds: ['music'], keyEnv: 'BEATOVEN_API_KEY', docs: 'https://github.com/Beatoven/public-api/blob/main/docs/api-spec.md',
256
+ estimate: () => unknown('Beatoven bills per track'),
257
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
258
+ const base = config.baseUrl ?? 'https://public-api.beatoven.ai/api/v1', api = client({ name: 'Beatoven', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
259
+ const sent = await api.post(`${base}/tracks/compose`, { prompt: { text: req.prompt + (req.seconds ? ` (${req.seconds} seconds)` : '') }, format: 'mp3', looping: !!req.options?.loop, ...(req.options ?? {}) });
260
+ if (!sent?.task_id) fail('Beatoven', 'beatoven', 'no task came back', sent);
261
+ const r = await waitFor(async () => { const q = await api.get(`${base}/tasks/${encodeURIComponent(sent.task_id)}`); if (q.status === 'composed') return q; if (q.status === 'failed') fail('Beatoven', 'beatoven', 'the track failed', q); return undefined; }, { every: 5000, signal, onProgress });
262
+ const url = r.meta?.track_url;
263
+ if (!url) fail('Beatoven', 'beatoven', 'the track finished with no file', r);
264
+ return { files: [{ url, ext: extOf(url, 'mp3') }], meta: { task: sent.task_id, stems: r.meta?.stems_url ?? null } };
265
+ },
266
+ };
267
+ const piper = {
268
+ id: 'piper', name: 'Piper (voices on this computer)', kinds: ['voice'], local: true, needs: ['voice'], docs: 'https://github.com/OHF-Voice/piper1-gpl',
269
+ estimate: () => fixed(0, 'runs on this computer'),
270
+ async generate(req, { signal, config = {} }) {
271
+ const voice = req.voice ?? config.voice;
272
+ if (!voice) fail('Piper', 'piper', 'say which voice model (a .onnx file): "connectors": { "piper": { "voice": "~/voices/en_US-lessac-medium.onnx" } }');
273
+ const out = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'piper-')), 'line.wav');
274
+ await new Promise((resolve, reject) => {
275
+ const p = spawn(config.command ?? 'piper', ['--model', voice.replace(/^~(?=\/)/, os.homedir()), '--output_file', out], { signal, stdio: ['pipe', 'ignore', 'pipe'] });
276
+ let err = ''; p.stderr.on('data', (d) => { err += d; });
277
+ p.on('error', (e) => reject(new ConnectorError(e.code === 'ENOENT' ? 'Piper is not installed (pip install piper-tts).' : e.message, { connector: 'piper' })));
278
+ p.on('close', (code) => (code === 0 ? resolve() : reject(new ConnectorError(`Piper stopped (${code}): ${err.slice(-300)}`, { connector: 'piper' }))));
279
+ p.stdin.end(req.prompt);
280
+ });
281
+ const bytes = new Uint8Array(fs.readFileSync(out));
282
+ fs.rmSync(path.dirname(out), { recursive: true, force: true });
283
+ return { files: [{ bytes, ext: 'wav' }] };
284
+ },
285
+ };
286
+
287
+ // ── Scenario: game art, with your own trained styles ─────────────────────────────────────────
288
+ const scenario = {
289
+ id: 'scenario', name: 'Scenario (game art, your own styles)', kinds: ['image', 'sprite', 'texture'], keyEnv: 'SCENARIO_API_KEY', docs: 'https://docs.scenario.com', models: { image: 'model_bfl-flux-2-dev' }, keyHint: 'API key:API secret',
290
+ estimate: () => unknown('Scenario bills in compute units per model'),
291
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
292
+ if (!String(key).includes(':')) fail('Scenario', 'scenario', 'the key is "API key:API secret"');
293
+ const base = config.baseUrl ?? 'https://api.cloud.scenario.com/v1', api = client({ name: 'Scenario', headers: { authorization: `Basic ${Buffer.from(key).toString('base64')}` }, fetchImpl, signal });
294
+ const [width, height] = req.aspect === '16:9' ? [1344, 768] : req.aspect === '9:16' ? [768, 1344] : [1024, 1024];
295
+ const sent = await api.post(`${base}/generate/custom/${encodeURIComponent(req.model ?? config.model ?? this.models.image)}`, { prompt: req.prompt, width, height, ...(req.options ?? {}) });
296
+ const jobId = sent?.job?.jobId;
297
+ if (!jobId) fail('Scenario', 'scenario', 'no job came back', sent);
298
+ const job = await waitFor(async () => { const j = (await api.get(`${base}/jobs/${encodeURIComponent(jobId)}`))?.job; if (j?.status === 'success') return j; if (['failure', 'canceled'].includes(j?.status)) fail('Scenario', 'scenario', `the job ended: ${j.status}`, j); return undefined; }, { every: 2500, signal, onProgress });
299
+ const files = [];
300
+ for (const a of job.metadata?.assetIds ?? []) { const url = (await api.get(`${base}/assets/${encodeURIComponent(a)}`))?.asset?.url; if (url) files.push({ url, ext: extOf(url, 'png') }); }
301
+ if (!files.length) fail('Scenario', 'scenario', 'the job finished with no asset', job);
302
+ return { files, meta: { job: jobId } };
303
+ },
304
+ };
305
+
306
+ // ── Ludo.ai: game assets of every kind ───────────────────────────────────────────────────────
307
+ const ludo = {
308
+ id: 'ludo', name: 'Ludo.ai (sprites, icons, backgrounds, sound, music, voices)', kinds: ['image', 'sprite', 'texture', 'vector', 'sfx', 'music', 'voice'], keyEnv: 'LUDO_API_KEY', docs: 'https://api.ludo.ai/api-documentation',
309
+ estimate: () => unknown('Ludo bills in credits; the job says what it charged'),
310
+ async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
311
+ const base = config.baseUrl ?? 'https://api.ludo.ai/api', api = client({ name: 'Ludo', headers: { authorization: `ApiKey ${key}` }, fetchImpl, signal });
312
+ const aspect = { '1:1': 'ar_1_1', '4:3': 'ar_4_3', '16:9': 'ar_16_9', '3:4': 'ar_3_4', '9:16': 'ar_9_16' }[req.aspect] ?? 'default';
313
+ const [route, body, ext] = req.kind === 'sfx' ? ['/audio/sound-effect', { description: req.prompt, ...(req.seconds ? { duration: req.seconds } : {}) }, 'mp3']
314
+ : req.kind === 'music' ? ['/audio/music', { description: req.prompt, ...(req.seconds ? { duration: req.seconds } : {}) }, 'mp3']
315
+ : req.kind === 'voice' ? ['/audio/voice', { text: req.prompt, ...(req.voice ? { voice_description: req.voice } : {}) }, 'mp3']
316
+ : ['/assets/image', { prompt: req.prompt, image_type: req.options?.image_type ?? { sprite: 'sprite', texture: 'texture', vector: 'icon', image: 'asset' }[req.kind], aspect_ratio: aspect, n: 1 }, 'png'];
317
+ const { image_type: _t, ...rest } = req.options ?? {};
318
+ let r = await api.post(`${base}${route}`, { ...body, ...rest });
319
+ if (r?.id && r?.status) { // 202: a job to wait for
320
+ const id = r.id;
321
+ r = await waitFor(async () => { const j = await api.get(`${base}/assets/jobs/${encodeURIComponent(id)}?wait=30`); if (j.status === 'succeeded') return j.result; if (['failed', 'canceled'].includes(j.status)) fail('Ludo', 'ludo', `the job ${j.status}${j.error?.message ? `: ${j.error.message}` : ''}`, j); return undefined; }, { every: 1000, signal, onProgress });
322
+ }
323
+ const urls = [...new Set(findFiles(r).map((f) => f.url ?? f).filter((u) => typeof u === 'string' && /^https?:/.test(u)))].filter((u) => !/normal/.test(u));
324
+ if (!urls.length) fail('Ludo', 'ludo', 'no file came back', r);
325
+ return { files: urls.slice(0, 4).map((u) => ({ url: u, ext: extOf(u, ext) })) };
326
+ },
327
+ };
328
+
329
+ // ── Figma: frames and icons from a design file, as SVG or PNG ────────────────────────────────
330
+ // the "prompt" is a Figma link with a node (…/design/<file>/…?node-id=1-2), or "<file key> <node id>"
331
+ const figma = {
332
+ id: 'figma', name: 'Figma (export frames and icons)', kinds: ['vector', 'image'], keyEnv: 'FIGMA_TOKEN', docs: 'https://www.figma.com/developers/api#get-images-endpoint',
333
+ estimate: () => fixed(0, 'exports from your own Figma file'),
334
+ async generate(req, { key, fetchImpl, signal, config = {} }) {
335
+ const m = /figma\.com\/(?:design|file|proto)\/([A-Za-z0-9]+)[^?]*\?(?:.*&)?node-id=([0-9]+[-:][0-9]+)/.exec(req.prompt) ?? /^([A-Za-z0-9]{10,})\s+([0-9]+[-:][0-9]+)$/.exec(req.prompt.trim());
336
+ if (!m) fail('Figma', 'figma', 'give a Figma link with a node-id (right-click a frame → Copy link)');
337
+ const [, file, node] = m, id = node.replace('-', ':'), format = req.kind === 'vector' ? 'svg' : 'png';
338
+ const api = client({ name: 'Figma', headers: { 'X-Figma-Token': key }, fetchImpl, signal });
339
+ const r = await api.get(`${config.baseUrl ?? 'https://api.figma.com/v1'}/images/${file}?ids=${encodeURIComponent(id)}&format=${format}${format === 'png' ? '&scale=2' : ''}`);
340
+ const url = r?.images?.[id];
341
+ if (!url) fail('Figma', 'figma', r?.err ? String(r.err) : 'that node did not export (is it a frame or a component?)', r);
342
+ return { files: [{ url, ext: format }], meta: { file, node: id } };
343
+ },
344
+ };
345
+
346
+ export const MORE_ADAPTERS = [runway, luma, leonardo, runware, wavespeed, pixverse, atlas, ideogram, krea, firefly, forge, drawthings, vidu, studio3d, inworld, groqTts, beatoven, piper, scenario, ludo, figma];
package/src/diff.js ADDED
@@ -0,0 +1,59 @@
1
+ // @clarity-js/agent — what changed in a file, line by line, as a unified diff. No dependency: the longest run of
2
+ // lines the two have in common is found by the textbook table, after the lines they share at both ends are set
3
+ // aside (an edit to a long file is usually a few lines in the middle).
4
+
5
+ const split = (text) => {
6
+ if (text == null || text === '') return [];
7
+ const lines = String(text).split('\n');
8
+ if (lines[lines.length - 1] === '') lines.pop(); else lines.push('\');
9
+ return lines;
10
+ };
11
+ const isBinary = (text) => typeof text === 'string' && text.includes('\u0000');
12
+
13
+ /**
14
+ * The difference between two texts (null: the file is not there).
15
+ * @param options path (for the header) · context (3 lines round a change) · most (400: lines of diff kept)
16
+ * → { text, added, removed, hunks, binary }
17
+ */
18
+ export function lineDiff(before, after, { path = 'file', context = 3, most = 400 } = {}) {
19
+ if (isBinary(before) || isBinary(after)) return { text: `Binary file ${path} ${before == null ? 'made' : after == null ? 'removed' : 'changed'}`, added: 0, removed: 0, hunks: 0, binary: true };
20
+ const a = split(before), b = split(after);
21
+ let head = 0; while (head < a.length && head < b.length && a[head] === b[head]) head++;
22
+ let tail = 0; while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail++;
23
+ const A = a.slice(head, a.length - tail), B = b.slice(head, b.length - tail), ops = []; // ops: [' ' | '-' | '+', line]
24
+ if (A.length * B.length > 6e6 || A.length > 65000 || B.length > 65000) { for (const l of A) ops.push(['-', l]); for (const l of B) ops.push(['+', l]); }
25
+ else {
26
+ const w = B.length + 1, t = new Uint16Array((A.length + 1) * w);
27
+ for (let i = A.length - 1; i >= 0; i--) for (let j = B.length - 1; j >= 0; j--) t[i * w + j] = A[i] === B[j] ? t[(i + 1) * w + j + 1] + 1 : Math.max(t[(i + 1) * w + j], t[i * w + j + 1]);
28
+ let i = 0, j = 0;
29
+ while (i < A.length && j < B.length) {
30
+ if (A[i] === B[j]) { ops.push([' ', A[i]]); i++; j++; }
31
+ else if (t[(i + 1) * w + j] >= t[i * w + j + 1]) ops.push(['-', A[i++]]);
32
+ else ops.push(['+', B[j++]]);
33
+ }
34
+ while (i < A.length) ops.push(['-', A[i++]]);
35
+ while (j < B.length) ops.push(['+', B[j++]]);
36
+ }
37
+ const added = ops.filter((o) => o[0] === '+').length, removed = ops.filter((o) => o[0] === '-').length;
38
+ if (!added && !removed) return { text: '', added: 0, removed: 0, hunks: 0, binary: false };
39
+ // the whole file as one run of ops (the shared ends as context), cut into hunks with `context` lines round each change
40
+ const all = [...a.slice(0, head).map((l) => [' ', l]), ...ops, ...a.slice(a.length - tail).map((l) => [' ', l])];
41
+ const out = [`--- ${before == null ? '/dev/null' : 'a/' + path}`, `+++ ${after == null ? '/dev/null' : 'b/' + path}`];
42
+ let hunks = 0, k = 0, la = 1, lb = 1; // la, lb: the line numbers the next op has in each file
43
+ while (k < all.length) {
44
+ if (all[k][0] === ' ') { k++; la++; lb++; continue; }
45
+ // a hunk: from `context` lines before this change to `context` lines after the last change that is within 2 × context of the one before
46
+ let start = Math.max(0, k - context), end = k, quiet = 0;
47
+ for (let m = k; m < all.length; m++) { if (all[m][0] === ' ') { if (++quiet > context * 2) break; } else { quiet = 0; end = m; } }
48
+ end = Math.min(all.length - 1, end + context);
49
+ const sa = la - (k - start), sb = lb - (k - start), part = all.slice(start, end + 1);
50
+ const na = part.filter((o) => o[0] !== '+').length, nb = part.filter((o) => o[0] !== '-').length;
51
+ out.push(`@@ -${na ? sa : sa - 1}${na === 1 ? '' : ',' + na} +${nb ? sb : sb - 1}${nb === 1 ? '' : ',' + nb} @@`);
52
+ for (const [s, l] of part) out.push(l.startsWith('\\ No newline') ? l : s + l);
53
+ hunks++;
54
+ for (let m = k; m <= end; m++) { if (all[m][0] !== '+') la++; if (all[m][0] !== '-') lb++; }
55
+ k = end + 1;
56
+ }
57
+ const text = out.length > most ? out.slice(0, most).join('\n') + `\n… ${out.length - most} more lines` : out.join('\n');
58
+ return { text, added, removed, hunks, binary: false };
59
+ }
package/src/dream.js ADDED
@@ -0,0 +1,156 @@
1
+ // @clarity-js/agent — Dream Engine: a sentence becomes a design the agent can build. For an app, a site or a game:
2
+ //
3
+ // 1 listen what kind of thing it is, what it is like, what it must have
4
+ // 2 ask at most three questions whose answers change the result ("you decide" is an answer)
5
+ // 3 originate three original concepts: what is taken from a reference is its kind and its mechanics, never its
6
+ // names, characters, art or music
7
+ // 4 design the chosen one in full: screens, data, roles and API for an app; pages and content for a site;
8
+ // the loop, controls, levels and progression for a game; the first minutes; the store text
9
+ // 5 style one style guide for everything that is made, with the base of every prompt
10
+ // 6 assets each asset with its kind, size, prompt and the connector that can make it
11
+ //
12
+ // It writes dream.md, style.json and assets.yaml. The model is the user's own (providers.js).
13
+
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { inside } from './tools.js';
17
+
18
+ export const MODES = ['app', 'site', 'game'];
19
+
20
+ /** Without a model: app, site or game, from the words. */
21
+ export function guessMode(idea) {
22
+ const s = String(idea).toLowerCase();
23
+ if (/\b(game|oyun|level|seviye|player|oyuncu|shoot|platformer|puzzle|bulmaca|rpg|arcade|boss|racing|yarış)/.test(s)) return 'game';
24
+ if (/\b(site|website|landing|portfolio|portfolyo|blog|homepage|ana sayfa|tanıtım sayfası)/.test(s)) return 'site';
25
+ return 'app';
26
+ }
27
+
28
+ /** The first JSON object in a model's answer (fenced or not). */
29
+ export function readJSON(text) {
30
+ const s = String(text ?? '');
31
+ const fenced = /```(?:json)?\s*\n([\s\S]*?)```/.exec(s);
32
+ for (const cand of [fenced?.[1], s]) {
33
+ if (!cand) continue;
34
+ const i = cand.indexOf('{'); if (i < 0) continue;
35
+ let depth = 0, inStr = false, esc = false;
36
+ for (let j = i; j < cand.length; j++) {
37
+ const ch = cand[j];
38
+ if (inStr) { if (esc) esc = false; else if (ch === '\\') esc = true; else if (ch === '"') inStr = false; continue; }
39
+ if (ch === '"') inStr = true; else if (ch === '{') depth++; else if (ch === '}' && --depth === 0) { try { return JSON.parse(cand.slice(i, j + 1)); } catch { break; } }
40
+ }
41
+ }
42
+ throw new Error('The model did not answer with JSON.');
43
+ }
44
+
45
+ const RULES = `Rules: everything you propose is original. When the idea names an existing game, app, film or brand, take only its kind and its mechanics; never its names, characters, logos, art, music or text. No real brands in names or content. Write for the people who will use it, in plain words. Answer with one JSON object and nothing else.`;
46
+
47
+ async function ask(provider, model, system, prompt, { signal, schemaHint, maxTokens = 6000 } = {}) {
48
+ const messages = [{ role: 'user', content: `${prompt}\n\nThe JSON has this shape:\n${schemaHint}` }];
49
+ const usage = { input: 0, output: 0 };
50
+ for (let attempt = 0; attempt < 2; attempt++) {
51
+ const r = await provider.chat({ model, system, messages, maxTokens, signal, json: true, temperature: 0.8 });
52
+ usage.input += r.usage?.input ?? 0; usage.output += r.usage?.output ?? 0;
53
+ try { return { data: readJSON(r.text), usage }; } catch (e) {
54
+ messages.push({ role: 'assistant', content: r.text }, { role: 'user', content: `That was not one JSON object (${e.message}). Answer again with only the JSON.` });
55
+ }
56
+ }
57
+ throw new Error('Dream Engine: the model did not give a design it could read, twice. Try another model.');
58
+ }
59
+
60
+ const SYSTEM = `You are Dream Engine, the design partner inside Clarity Agent. You turn a one-sentence idea into a design that can be built with Clarity.js (a front-end language for web apps, sites and games, with a game engine) and a back end. You think like a senior product designer and, for games, like a game designer. ${RULES}`;
61
+
62
+ const DESIGN_SHAPES = {
63
+ app: `{"title": "", "pitch": "one sentence", "audience": "", "roles": [{"name": "", "can": ""}], "screens": [{"name": "", "purpose": "", "parts": ["…"]}], "data": [{"entity": "", "fields": [{"name": "", "type": "string|number|boolean|date|ref:<Entity>|list"}]}], "flows": [{"name": "", "steps": ["…"]}], "api": [{"method": "GET|POST|PUT|DELETE", "path": "/api/…", "purpose": "", "auth": "public|user|admin"}], "integrations": ["payments, email …, only if needed"], "firstMinutes": ["what a new user does in the first minutes"], "storeText": "the text for the app's page"}`,
64
+ site: `{"title": "", "pitch": "", "audience": "", "pages": [{"path": "/", "purpose": "", "sections": ["…"]}], "tone": "", "seo": {"title": "", "description": "", "keywords": ["…"]}, "forms": [{"name": "", "fields": ["…"]}], "firstMinutes": ["what a visitor does first"], "storeText": "a short description for sharing"}`,
65
+ game: `{"title": "", "pitch": "", "audience": "", "genre": "", "loop": "the core loop in one or two sentences", "controls": ["…"], "levels": [{"name": "", "idea": ""}], "obstacles": ["enemies, hazards …"], "progression": "", "difficulty": "how it rises", "session": "how long a session is", "firstMinutes": ["the first ten minutes, step by step"], "storeText": "the store page text"}`,
66
+ };
67
+ const STYLE_SHAPE = `{"look": "the visual language in a sentence", "palette": [{"name": "", "hex": "#rrggbb"}], "type": {"heading": "a font family", "body": "a font family"}, "light": "", "lines": "", "mood": "", "promptBase": "the words every image prompt starts with, so everything looks alike", "negative": "what no image may have", "sound": "for games and media: the sound and music in a sentence"}`;
68
+ const ASSET_SHAPE = `{"assets": [{"name": "kebab-case", "kind": "image|sprite|texture|vector|video|model3d|voice|sfx|music", "use": "where it is used", "aspect": "1:1|16:9|9:16|4:3|3:4", "seconds": 0, "prompt": "the prompt, after the style's promptBase"}]}`;
69
+
70
+ /**
71
+ * Dream: idea → { mode, analysis, answers, concepts, chosen, design, style, assets, files, usage }.
72
+ * provider, model the user's model
73
+ * mode 'app' | 'site' | 'game' (the model reads it from the idea when not given)
74
+ * answer(questions) → { id: answer }; without it every question is "you decide"
75
+ * choose(concepts) → the index of the chosen one; without it the first
76
+ * root, write where to write dream.md, style.json, assets.yaml (and whether to)
77
+ * quote(asset) → usd|null the price of each asset (the connectors'), for the total
78
+ * on(step) 'listen' | 'ask' | 'originate' | 'design' | 'style' | 'assets' | 'write', as each starts
79
+ */
80
+ export async function dream({ idea, provider, model, mode, answer, choose, root = process.cwd(), dir = '.', write = true, quote, signal, on = () => {} }) {
81
+ if (!String(idea ?? '').trim()) throw new Error('Say the idea: one sentence.');
82
+ const usage = { input: 0, output: 0 }, add = (u) => { usage.input += u?.input ?? 0; usage.output += u?.output ?? 0; };
83
+ on('listen');
84
+ const a = await ask(provider, model, SYSTEM, `The idea: "${idea}"${mode ? `\nIt is a ${mode}.` : ''}\n\nWork out what it is. Then the questions whose answers would change the design most: at most three, each with three or four short options. Leave out any question the idea already answers.`, { signal, schemaHint: `{"mode": "app|site|game", "title": "a working title", "summary": "", "references": ["what it is like, if the idea says"], "musts": ["what it must have"], "questions": [{"id": "q1", "question": "", "options": ["…"]}]}` });
85
+ add(a.usage);
86
+ const analysis = a.data, kind = MODES.includes(mode) ? mode : MODES.includes(analysis.mode) ? analysis.mode : guessMode(idea);
87
+ const questions = (analysis.questions ?? []).slice(0, 3);
88
+ on('ask');
89
+ const answers = questions.length && answer ? (await answer(questions)) ?? {} : {};
90
+ const said = questions.map((q) => `- ${q.question} → ${answers[q.id] ?? 'you decide'}`).join('\n');
91
+ on('originate');
92
+ const c = await ask(provider, model, SYSTEM, `The idea: "${idea}" (a ${kind}).\nWhat we know: ${analysis.summary ?? ''}\nMust have: ${(analysis.musts ?? []).join('; ') || '—'}\nAnswers:\n${said || '- none'}\n\nPropose three different, original concepts for it. Each has a name, a hook (why someone would choose it), a look, and its core (${kind === 'game' ? 'the core loop' : kind === 'site' ? 'what the visitor gets' : 'the main flow'}).`, { signal, schemaHint: `{"concepts": [{"name": "", "hook": "", "look": "", "core": "", "why": "what makes it different"}]}` });
93
+ add(c.usage);
94
+ const concepts = (c.data.concepts ?? []).slice(0, 3);
95
+ if (!concepts.length) throw new Error('Dream Engine: no concepts came back.');
96
+ const pick = Math.max(0, Math.min(concepts.length - 1, (choose ? await choose(concepts) : 0) ?? 0)), chosen = concepts[pick];
97
+ on('design');
98
+ const d = await ask(provider, model, SYSTEM, `Design this ${kind} in full, ready to build.\nThe idea: "${idea}"\nThe concept: ${JSON.stringify(chosen)}\nAnswers:\n${said || '- none'}\n${kind === 'app' ? 'Keep the first version small: the screens, data and API a first release needs.' : kind === 'game' ? 'Keep the first version small: three to six levels, one mechanic done well.' : 'Keep it to the pages a first version needs.'}`, { signal, schemaHint: DESIGN_SHAPES[kind], maxTokens: 8000 });
99
+ add(d.usage);
100
+ on('style');
101
+ const s = await ask(provider, model, SYSTEM, `The style guide for "${d.data.title ?? chosen.name}" (${kind}), so every picture, model and sound made for it looks and sounds as one. The concept's look: ${chosen.look}.`, { signal, schemaHint: STYLE_SHAPE });
102
+ add(s.usage);
103
+ on('assets');
104
+ const as = await ask(provider, model, SYSTEM, `The assets "${d.data.title ?? chosen.name}" needs for its first version (${kind}). The design: ${JSON.stringify(d.data).slice(0, 6000)}\nThe style: ${JSON.stringify(s.data)}\n${kind === 'game' ? 'Characters, enemies, tiles, backgrounds, UI, effects, music and sound effects; sprite sheets as one asset each.' : 'A logo and icons (kind vector, as SVG), illustrations, hero images, and any sound; no stock photos of real people.'} Keep it to what the first version needs.`, { signal, schemaHint: ASSET_SHAPE });
105
+ add(as.usage);
106
+ const assets = (as.data.assets ?? []).map((x) => ({ ...x, prompt: x.prompt ?? '', status: 'todo' }));
107
+ for (const x of assets) { try { x.usd = quote ? await quote(x) : null; } catch { x.usd = null; } }
108
+ const result = { mode: kind, idea, analysis, answers, concepts, chosen, design: d.data, style: s.data, assets, usage, files: [] };
109
+ if (write) {
110
+ on('write');
111
+ const out = inside(root, dir);
112
+ fs.mkdirSync(out, { recursive: true });
113
+ fs.writeFileSync(path.join(out, 'dream.md'), dreamMarkdown(result));
114
+ fs.writeFileSync(path.join(out, 'style.json'), JSON.stringify(s.data, null, 2) + '\n');
115
+ fs.writeFileSync(path.join(out, 'assets.yaml'), assetsYaml(assets));
116
+ result.files = ['dream.md', 'style.json', 'assets.yaml'].map((f) => path.relative(fs.realpathSync(root), path.join(out, f)).split(path.sep).join('/'));
117
+ }
118
+ return result;
119
+ }
120
+
121
+ // ── the files ────────────────────────────────────────────────────────────────────────────────
122
+ const list = (xs, f = (x) => x) => (xs ?? []).map((x) => `- ${f(x)}`).join('\n');
123
+ export function dreamMarkdown({ mode, idea, concepts, chosen, design: d, style: s, assets, answers, analysis }) {
124
+ const total = assets.reduce((t, x) => t + (x.usd ?? 0), 0), unpriced = assets.filter((x) => x.usd == null).length;
125
+ const parts = [
126
+ `# ${d.title ?? chosen.name}`, '', `> ${d.pitch ?? chosen.hook}`, '', `A ${mode} from the idea: "${idea}"`, '',
127
+ '## The concept', '', `**${chosen.name}** — ${chosen.hook}`, '', `Look: ${chosen.look}`, '', `Core: ${chosen.core}`, '',
128
+ ...(concepts.length > 1 ? ['The other concepts:', '', list(concepts.filter((x) => x !== chosen), (x) => `**${x.name}**: ${x.hook}`), ''] : []),
129
+ ...((analysis.questions ?? []).length ? ['Answers:', '', list(analysis.questions, (q) => `${q.question} — ${answers[q.id] ?? 'you decide'}`), ''] : []),
130
+ ];
131
+ if (mode === 'app') parts.push('## Who uses it', '', d.audience ?? '', '', list(d.roles, (r) => `**${r.name}**: ${r.can}`), '', '## Screens', '', list(d.screens, (x) => `**${x.name}** — ${x.purpose}${x.parts?.length ? ` (${x.parts.join(', ')})` : ''}`), '', '## Data', '', list(d.data, (e) => `**${e.entity}**: ${(e.fields ?? []).map((f) => `${f.name} (${f.type})`).join(', ')}`), '', '## Flows', '', ...(d.flows ?? []).flatMap((f) => [`**${f.name}**`, '', ...(f.steps ?? []).map((st, i) => `${i + 1}. ${st}`), '']), '## API', '', '| Method | Path | What | Who |', '| --- | --- | --- | --- |', ...(d.api ?? []).map((x) => `| ${x.method} | \`${x.path}\` | ${x.purpose} | ${x.auth} |`), '', ...(d.integrations?.length ? ['## Integrations', '', list(d.integrations), ''] : []));
132
+ if (mode === 'site') parts.push('## Pages', '', list(d.pages, (p) => `\`${p.path}\` — ${p.purpose}${p.sections?.length ? `: ${p.sections.join(', ')}` : ''}`), '', `Tone: ${d.tone ?? ''}`, '', '## Search', '', `Title: ${d.seo?.title ?? ''}`, '', `Description: ${d.seo?.description ?? ''}`, '', ...(d.forms?.length ? ['## Forms', '', list(d.forms, (f) => `**${f.name}**: ${(f.fields ?? []).join(', ')}`), ''] : []));
133
+ if (mode === 'game') parts.push('## The game', '', `Genre: ${d.genre ?? ''}`, '', `Loop: ${d.loop ?? ''}`, '', `Session: ${d.session ?? ''}`, '', '## Controls', '', list(d.controls), '', '## Levels', '', ...(d.levels ?? []).map((l, i) => `${i + 1}. **${l.name}** — ${l.idea}`), '', '## Obstacles', '', list(d.obstacles), '', '## Progression and difficulty', '', d.progression ?? '', '', d.difficulty ?? '', '');
134
+ parts.push('## The first minutes', '', ...(d.firstMinutes ?? []).map((x, i) => `${i + 1}. ${x}`), '', '## Style', '', s.look ?? '', '', list(s.palette, (p) => `${p.name}: \`${p.hex}\``), '', `Type: ${s.type?.heading ?? ''} for headings, ${s.type?.body ?? ''} for text.`, '', ...(s.sound ? [`Sound: ${s.sound}`, ''] : []), `Every image prompt begins: "${s.promptBase ?? ''}"`, '', '## Assets', '', `${assets.length} assets (assets.yaml)${assets.length ? `; priced ones about $${total.toFixed(2)}${unpriced ? `, ${unpriced} priced by the service when made` : ''}` : ''}.`, '', list(assets, (x) => `${x.name} (${x.kind}) — ${x.use ?? ''}`), '', ...(d.storeText ? ['## Store text', '', d.storeText, ''] : []));
135
+ return parts.join('\n').replace(/\n{3,}/g, '\n\n');
136
+ }
137
+
138
+ const y = (v) => (v == null ? '' : typeof v === 'number' || typeof v === 'boolean' ? String(v) : /^[\w ./:,()'-]*$/.test(String(v)) && !/^(true|false|null|yes|no|\d.*)$/i.test(String(v)) && String(v).trim() === String(v) ? String(v) : JSON.stringify(String(v)));
139
+ /** assets.yaml: one entry per asset; its status goes from todo to made as the agent makes it. */
140
+ export function assetsYaml(assets) {
141
+ return `# Assets for this project: made with \`clarity gen\` or by the agent, then marked made.\nassets:\n` + assets.map((a) => ' - ' + Object.entries(a).filter(([, v]) => v != null && v !== '' && !(typeof v === 'number' && v === 0 && false)).map(([k, v], i) => `${i ? ' ' : ''}${k}: ${y(v)}`).join('\n')).join('\n') + '\n';
142
+ }
143
+ /** Read assets.yaml back (the subset assetsYaml writes). */
144
+ export function readAssetsYaml(text) {
145
+ const out = []; let cur = null;
146
+ for (const line of String(text).split('\n')) {
147
+ const m = /^\s*(-\s+)?([\w]+):\s*(.*)$/.exec(line);
148
+ if (!m || m[2] === 'assets') continue;
149
+ if (m[1]) { cur = {}; out.push(cur); }
150
+ if (!cur) continue;
151
+ let v = m[3].trim();
152
+ if (v.startsWith('"')) { try { v = JSON.parse(v); } catch { /* keep */ } } else if (/^-?\d+(\.\d+)?$/.test(v)) v = Number(v); else if (v === 'true' || v === 'false') v = v === 'true';
153
+ cur[m[2]] = v;
154
+ }
155
+ return out;
156
+ }