@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.
- package/README.md +285 -2
- package/index.d.ts +155 -0
- package/package.json +132 -4
- package/src/app.js +139 -0
- package/src/budget.js +34 -0
- package/src/chat.js +288 -0
- package/src/checkpoints.js +126 -0
- package/src/ci.js +121 -0
- package/src/clarity.js +16 -0
- package/src/cli.js +340 -0
- package/src/connectors/adapters.js +371 -0
- package/src/connectors/http.js +46 -0
- package/src/connectors/index.js +103 -0
- package/src/connectors/more.js +346 -0
- package/src/diff.js +59 -0
- package/src/dream.js +156 -0
- package/src/headless.js +61 -0
- package/src/index.js +120 -0
- package/src/integrations.js +196 -0
- package/src/keys.js +48 -0
- package/src/loop.js +80 -0
- package/src/mcp-client.js +101 -0
- package/src/providers.js +200 -0
- package/src/schedule.js +113 -0
- package/src/session.js +126 -0
- package/src/ship.js +127 -0
- package/src/tools.js +139 -0
- package/ui/Panel.clarity +191 -0
- package/ui/main.js +28 -0
- package/ui/panel.css +93 -0
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// @clarity-js/agent — the services that make assets, each as an adapter:
|
|
2
|
+
//
|
|
3
|
+
// { id, name, kinds, keyEnv, local?, docs, models: { kind: default }, estimate(req) → { usd, note },
|
|
4
|
+
// generate(req, { key, fetchImpl, signal, onProgress, config }) → { files: [{ bytes | url, ext }], usd?, meta } }
|
|
5
|
+
//
|
|
6
|
+
// req: { kind, prompt, negative?, aspect?, seconds?, voice?, model?, refs?, options? }. kind is one of KINDS in
|
|
7
|
+
// index.js (image, sprite, texture, vector, video, model3d, voice, sfx, music). The endpoints follow each
|
|
8
|
+
// service's own reference (linked in `docs`); a model that changes is a setting, not a code change.
|
|
9
|
+
|
|
10
|
+
import { client, waitFor, b64, hex, form, extOf, ConnectorError } from './http.js';
|
|
11
|
+
import { MORE_ADAPTERS } from './more.js'; // more connectors; they use the helpers below only inside their functions
|
|
12
|
+
|
|
13
|
+
export const ASPECT_SIZE = { '1:1': '1024x1024', '16:9': '1536x1024', '3:2': '1536x1024', '4:3': '1536x1024', '9:16': '1024x1536', '2:3': '1024x1536', '3:4': '1024x1536' };
|
|
14
|
+
export const sizeOf = (aspect, fallback = '1024x1024') => (ASPECT_SIZE[aspect] ?? fallback).split('x').map(Number);
|
|
15
|
+
export const unknown = (note = 'the price is not known in advance; the service charges its own rate') => ({ usd: null, note });
|
|
16
|
+
export const fixed = (usd, note) => ({ usd, note });
|
|
17
|
+
|
|
18
|
+
// every { url } (or url-like string) in a result, with the type it says it is
|
|
19
|
+
export function findFiles(o, out = [], key = '') {
|
|
20
|
+
if (!o) return out;
|
|
21
|
+
if (typeof o === 'string') { if (/^https?:\/\//.test(o)) out.push({ url: o, key }); return out; }
|
|
22
|
+
if (Array.isArray(o)) { o.forEach((v) => findFiles(v, out, key)); return out; }
|
|
23
|
+
if (typeof o === 'object') {
|
|
24
|
+
if (typeof o.url === 'string' && /^https?:\/\//.test(o.url)) { out.push({ url: o.url, key, type: o.content_type ?? o.contentType ?? null, name: o.file_name ?? null }); return out; }
|
|
25
|
+
for (const [k, v] of Object.entries(o)) if (!/^(logs|metrics|input|urls)$/.test(k)) findFiles(v, out, k);
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// ── OpenAI images ────────────────────────────────────────────────────────────────────────────
|
|
31
|
+
const openaiImages = {
|
|
32
|
+
id: 'openai', name: 'OpenAI images', kinds: ['image', 'sprite', 'texture'], keyEnv: 'OPENAI_API_KEY', docs: 'https://platform.openai.com/docs/api-reference/images', models: { image: 'gpt-image-1' },
|
|
33
|
+
estimate: () => unknown('OpenAI bills images by size and quality'),
|
|
34
|
+
async generate(req, { key, fetchImpl, signal, config = {} }) {
|
|
35
|
+
const api = client({ name: 'OpenAI images', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
|
|
36
|
+
const r = await api.post(`${config.baseUrl ?? 'https://api.openai.com/v1'}/images/generations`, { model: req.model ?? this.models.image, prompt: req.prompt, size: ASPECT_SIZE[req.aspect] ?? '1024x1024', n: 1, ...(req.options ?? {}) });
|
|
37
|
+
const d = r?.data?.[0] ?? {};
|
|
38
|
+
return { files: [d.b64_json ? { bytes: b64(d.b64_json), ext: 'png' } : { url: d.url, ext: 'png' }], meta: { revised: d.revised_prompt ?? null } };
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// ── Google Gemini: images, video (Omni) and speech, with the same key as its models ─────────────
|
|
43
|
+
// video and speech go through the Interactions API: the output is a step of type model_output whose content holds
|
|
44
|
+
// the file (base64 in `data`, or a `uri` to fetch with the key)
|
|
45
|
+
async function geminiInteraction(api, base, body, want, key) {
|
|
46
|
+
const r = await api.post(`${base}/interactions`, body);
|
|
47
|
+
const items = (r?.steps ?? []).filter((s) => s.type === 'model_output').flatMap((s) => s.content ?? []);
|
|
48
|
+
const item = items.find((c) => c.type === want && (c.data || c.uri));
|
|
49
|
+
if (!item) throw new ConnectorError(`Gemini: no ${want} came back (the prompt may have been refused).`, { connector: 'gemini', body: r });
|
|
50
|
+
if (item.data) return { bytes: b64(item.data), mime: item.mime_type ?? '' };
|
|
51
|
+
const id = /files\/([^/:?]+)/.exec(item.uri)?.[1];
|
|
52
|
+
return { bytes: await api.bytes(id ? `${base}/files/${id}:download?alt=media` : item.uri, { 'x-goog-api-key': key }), mime: item.mime_type ?? '' };
|
|
53
|
+
}
|
|
54
|
+
const geminiImages = {
|
|
55
|
+
id: 'gemini', name: 'Google Gemini (images, Omni video, speech, Lyria music)', kinds: ['image', 'sprite', 'texture', 'video', 'voice', 'music'], keyEnv: 'GEMINI_API_KEY', docs: 'https://ai.google.dev/gemini-api/docs', models: { image: 'gemini-2.5-flash-image', video: 'gemini-omni-1.2-flash', voice: 'gemini-3.8-flash-tts', music: 'lyria-3-clip-preview' }, voice: 'Kore',
|
|
56
|
+
estimate: (req) => unknown(req.kind === 'video' ? 'Google bills Omni video by length and resolution' : req.kind === 'voice' ? 'Google bills speech by tokens' : req.kind === 'music' ? 'Google bills Lyria per clip or song' : 'Google bills image output by tokens'),
|
|
57
|
+
async generate(req, { key, fetchImpl, signal, config = {} }) {
|
|
58
|
+
const base = config.baseUrl ?? 'https://generativelanguage.googleapis.com/v1beta', api = client({ name: 'Gemini', headers: { 'x-goog-api-key': key }, fetchImpl, signal });
|
|
59
|
+
const model = req.model ?? config.models?.[req.kind] ?? this.models[req.kind] ?? this.models.image;
|
|
60
|
+
if (req.kind === 'video') {
|
|
61
|
+
const seconds = Math.min(15, Math.max(3, Math.round(req.seconds ?? 8)));
|
|
62
|
+
const v = await geminiInteraction(api, base, { model, input: req.prompt, response_format: { type: 'video', aspect_ratio: req.aspect === '9:16' ? '9:16' : '16:9', duration: `${seconds}s`, ...(req.options ?? {}) } }, 'video', key);
|
|
63
|
+
return { files: [{ bytes: v.bytes, ext: 'mp4' }], meta: { model, seconds } };
|
|
64
|
+
}
|
|
65
|
+
if (req.kind === 'music') {
|
|
66
|
+
// Lyria 3 Clip makes 30 seconds; Lyria 3.5 (model: 'lyria-3.5') takes its length from the prompt
|
|
67
|
+
const m = await geminiInteraction(api, base, { model, input: req.prompt + (req.seconds && model !== 'lyria-3-clip-preview' ? ` (${req.seconds} seconds long)` : ''), ...(req.options ?? {}) }, 'audio', key);
|
|
68
|
+
return { files: [{ bytes: m.bytes, ext: /wav/.test(m.mime) ? 'wav' : 'mp3' }], meta: { model } };
|
|
69
|
+
}
|
|
70
|
+
if (req.kind === 'voice') {
|
|
71
|
+
const a = await geminiInteraction(api, base, { model, input: [{ type: 'user_input', content: [{ type: 'text', text: req.prompt }] }], response_format: { type: 'audio' }, generation_config: { speech_config: [{ voice: req.voice ?? config.voice ?? this.voice }] }, ...(req.options ?? {}) }, 'audio', key);
|
|
72
|
+
return { files: [{ bytes: a.bytes, ext: /mpeg|mp3/.test(a.mime) ? 'mp3' : 'wav' }], meta: { model } };
|
|
73
|
+
}
|
|
74
|
+
const r = await api.post(`${base}/models/${encodeURIComponent(model)}:generateContent`, { contents: [{ parts: [{ text: req.prompt + (req.aspect ? ` (aspect ratio ${req.aspect})` : '') }] }], generationConfig: { responseModalities: ['IMAGE'] } });
|
|
75
|
+
const part = (r?.candidates?.[0]?.content?.parts ?? []).find((p) => p.inlineData?.data);
|
|
76
|
+
if (!part) throw new ConnectorError('Gemini: no image came back (the prompt may have been refused).', { connector: 'gemini', body: r });
|
|
77
|
+
return { files: [{ bytes: b64(part.inlineData.data), ext: /jpe?g/.test(part.inlineData.mimeType ?? '') ? 'jpg' : 'png' }], meta: { model } };
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// ── MiniMax: images and video ────────────────────────────────────────────────────────────────
|
|
82
|
+
const minimaxOk = (r, name = 'MiniMax') => { const c = r?.base_resp?.status_code; if (c && c !== 0) throw new ConnectorError(`${name}: ${c} ${r.base_resp.status_msg ?? ''}`.trim(), { connector: 'minimax', body: r }); return r; };
|
|
83
|
+
const minimax = {
|
|
84
|
+
id: 'minimax', name: 'MiniMax (images, Hailuo video, speech)', kinds: ['image', 'video', 'voice'], keyEnv: 'MINIMAX_API_KEY', docs: 'https://platform.minimax.io/docs/api-reference/video-generation-t2v', models: { image: 'image-01', video: 'MiniMax-Hailuo-2.3', voice: 'speech-2.8-hd' }, voice: 'English_expressive_narrator',
|
|
85
|
+
estimate: (req) => unknown(req.kind === 'video' ? 'MiniMax bills video by length and resolution' : req.kind === 'voice' ? 'MiniMax bills speech by characters' : 'MiniMax bills per image'),
|
|
86
|
+
async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
|
|
87
|
+
const base = config.baseUrl ?? 'https://api.minimax.io', api = client({ name: 'MiniMax', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
|
|
88
|
+
if (req.kind === 'voice') {
|
|
89
|
+
// t2a_v2: the audio comes back as hex in data.audio
|
|
90
|
+
const r = minimaxOk(await api.post(`${base}/v1/t2a_v2`, { model: req.model ?? this.models.voice, text: req.prompt, stream: false, voice_setting: { voice_id: req.voice ?? config.voice ?? this.voice }, audio_setting: { format: 'mp3' }, output_format: 'hex', ...(req.options ?? {}) }));
|
|
91
|
+
if (!r?.data?.audio) throw new ConnectorError('MiniMax: no audio came back.', { connector: 'minimax', body: r });
|
|
92
|
+
return { files: [{ bytes: hex(r.data.audio), ext: 'mp3' }], meta: { trace: r.trace_id ?? null } };
|
|
93
|
+
}
|
|
94
|
+
if (req.kind !== 'video') {
|
|
95
|
+
const r = minimaxOk(await api.post(`${base}/v1/image_generation`, { model: req.model ?? this.models.image, prompt: req.prompt, aspect_ratio: req.aspect ?? '1:1', response_format: 'base64', n: 1, ...(req.options ?? {}) }));
|
|
96
|
+
const img = r?.data?.image_base64?.[0];
|
|
97
|
+
if (!img) throw new ConnectorError('MiniMax: no image came back.', { connector: 'minimax', body: r });
|
|
98
|
+
return { files: [{ bytes: b64(img), ext: 'jpg' }], meta: { id: r.id } };
|
|
99
|
+
}
|
|
100
|
+
const started = minimaxOk(await api.post(`${base}/v1/video_generation`, { model: req.model ?? this.models.video, prompt: req.prompt, duration: req.seconds && req.seconds > 6 ? 10 : 6, ...(req.options ?? {}) }));
|
|
101
|
+
const fileId = await waitFor(async () => { const q = minimaxOk(await api.get(`${base}/v1/query/video_generation?task_id=${encodeURIComponent(started.task_id)}`)); if (q.status === 'Success') return q.file_id; if (q.status === 'Fail') throw new ConnectorError('MiniMax: the video failed.', { connector: 'minimax', body: q }); return undefined; }, { every: 8000, signal, onProgress });
|
|
102
|
+
const f = minimaxOk(await api.get(`${base}/v1/files/retrieve?file_id=${encodeURIComponent(fileId)}`));
|
|
103
|
+
return { files: [{ url: f?.file?.download_url, ext: 'mp4' }], meta: { task: started.task_id, file: fileId } };
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// ── ElevenLabs: voice, sound effects, music ──────────────────────────────────────────────────
|
|
108
|
+
const elevenlabs = {
|
|
109
|
+
id: 'elevenlabs', name: 'ElevenLabs (voice, sound effects, music)', kinds: ['voice', 'sfx', 'music'], keyEnv: 'ELEVENLABS_API_KEY', docs: 'https://elevenlabs.io/docs/api-reference', models: { voice: 'eleven_multilingual_v2', sfx: 'eleven_text_to_sound_v2', music: 'music_v2' }, voice: 'JBFqnCBsd6RMkjVDRZzb',
|
|
110
|
+
estimate: (req) => unknown(req.kind === 'voice' ? 'ElevenLabs bills speech by characters' : 'ElevenLabs bills by length'),
|
|
111
|
+
async generate(req, { key, fetchImpl, signal, config = {} }) {
|
|
112
|
+
const base = config.baseUrl ?? 'https://api.elevenlabs.io', api = client({ name: 'ElevenLabs', headers: { 'xi-api-key': key, accept: 'audio/mpeg' }, fetchImpl, signal }), fmt = 'output_format=mp3_44100_128';
|
|
113
|
+
let r;
|
|
114
|
+
if (req.kind === 'voice') r = await api.post(`${base}/v1/text-to-speech/${encodeURIComponent(req.voice ?? config.voice ?? this.voice)}?${fmt}`, { text: req.prompt, model_id: req.model ?? this.models.voice, ...(req.options ?? {}) });
|
|
115
|
+
else if (req.kind === 'sfx') r = await api.post(`${base}/v1/sound-generation?${fmt}`, { text: req.prompt, model_id: req.model ?? this.models.sfx, ...(req.seconds ? { duration_seconds: Math.min(30, Math.max(0.5, req.seconds)) } : {}), ...(req.options ?? {}) });
|
|
116
|
+
else r = await api.post(`${base}/v1/music?${fmt}`, { prompt: req.prompt, model_id: req.model ?? this.models.music, ...(req.seconds ? { music_length_ms: Math.min(600000, Math.max(3000, Math.round(req.seconds * 1000))) } : {}), ...(req.options ?? {}) });
|
|
117
|
+
if (!r?.bytes) throw new ConnectorError('ElevenLabs: no audio came back.', { connector: 'elevenlabs', body: r });
|
|
118
|
+
return { files: [{ bytes: r.bytes, ext: 'mp3' }] };
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
// ── Tripo: 3D models ─────────────────────────────────────────────────────────────────────────
|
|
123
|
+
const tripo = {
|
|
124
|
+
id: 'tripo', name: 'Tripo (3D models)', kinds: ['model3d'], keyEnv: 'TRIPO_API_KEY', docs: 'https://developers.tripo3d.ai/en/docs', models: { model3d: 'v3.1-20260211' },
|
|
125
|
+
estimate: () => unknown('Tripo bills in credits; the task reports what it cost'),
|
|
126
|
+
async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
|
|
127
|
+
const base = config.baseUrl ?? 'https://openapi.tripo3d.ai/v3', api = client({ name: 'Tripo', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
|
|
128
|
+
const made = await api.post(`${base}/generation/text-to-model`, { prompt: req.prompt, model: req.model ?? this.models.model3d, texture: true, pbr: true, texture_quality: 'standard', ...(req.negative ? { negative_prompt: req.negative } : {}), ...(req.options ?? {}) });
|
|
129
|
+
const id = made?.data?.task_id ?? made?.task_id;
|
|
130
|
+
if (!id) throw new ConnectorError('Tripo: no task came back.', { connector: 'tripo', body: made });
|
|
131
|
+
const task = await waitFor(async () => { const q = await api.get(`${base}/tasks/${encodeURIComponent(id)}`); const t = q?.data ?? q; if (t.status === 'success') return t; if (['failed', 'cancelled', 'banned', 'expired'].includes(t.status)) throw new ConnectorError(`Tripo: the task ${t.status}${t.error_message ? `: ${t.error_message}` : ''}.`, { connector: 'tripo', body: t }); return undefined; }, { every: 5000, signal, onProgress });
|
|
132
|
+
return { files: [{ url: task.output.model_url, ext: extOf(task.output.model_url, 'glb') }, ...(task.output.rendered_image_url ? [{ url: task.output.rendered_image_url, ext: extOf(task.output.rendered_image_url, 'webp'), preview: true }] : [])], usd: task.currency === 'USD' ? task.cost_amount ?? null : null, meta: { task: id, credits: task.credits_consumed ?? null } };
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// ── Meshy: 3D models (a preview, then its textures) ──────────────────────────────────────────
|
|
137
|
+
const meshy = {
|
|
138
|
+
id: 'meshy', name: 'Meshy (3D models)', kinds: ['model3d'], keyEnv: 'MESHY_API_KEY', docs: 'https://docs.meshy.ai/en/api/text-to-3d', models: { model3d: 'latest' },
|
|
139
|
+
estimate: () => unknown('Meshy bills in credits; the task reports what it used'),
|
|
140
|
+
async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
|
|
141
|
+
const base = config.baseUrl ?? 'https://api.meshy.ai', api = client({ name: 'Meshy', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
|
|
142
|
+
const done = (id) => waitFor(async () => { const t = await api.get(`${base}/openapi/v2/text-to-3d/${encodeURIComponent(id)}`); if (t.status === 'SUCCEEDED') return t; if (t.status === 'FAILED' || t.status === 'CANCELED') throw new ConnectorError(`Meshy: the task ${t.status.toLowerCase()}${t.task_error?.message ? `: ${t.task_error.message}` : ''}.`, { connector: 'meshy', body: t }); return undefined; }, { every: 5000, signal, onProgress });
|
|
143
|
+
const preview = await api.post(`${base}/openapi/v2/text-to-3d`, { mode: 'preview', prompt: req.prompt, ai_model: req.model ?? this.models.model3d, ...(req.options?.topology ? { topology: req.options.topology } : {}) });
|
|
144
|
+
let task = await done(preview.result), credits = task.consumed_credits ?? 0;
|
|
145
|
+
if (req.options?.texture !== false) {
|
|
146
|
+
const refine = await api.post(`${base}/openapi/v2/text-to-3d`, { mode: 'refine', preview_task_id: preview.result, enable_pbr: true });
|
|
147
|
+
task = await done(refine.result); credits += task.consumed_credits ?? 0;
|
|
148
|
+
}
|
|
149
|
+
return { files: [{ url: task.model_urls?.glb, ext: 'glb' }, ...(task.thumbnail_url ? [{ url: task.thumbnail_url, ext: extOf(task.thumbnail_url, 'png'), preview: true }] : [])], meta: { task: task.id, credits } };
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
// ── Higgsfield: many image and video models behind one key ───────────────────────────────────
|
|
154
|
+
const higgsfield = {
|
|
155
|
+
id: 'higgsfield', name: 'Higgsfield (image and video models)', kinds: ['image', 'video'], keyEnv: 'HIGGSFIELD_API_KEY', keyHint: 'the key id and its secret, as id:secret', docs: 'https://docs.higgsfield.ai', models: { image: 'higgsfield-ai/soul/v2/standard', video: null },
|
|
156
|
+
estimate: () => unknown('Higgsfield bills each model at its own rate'),
|
|
157
|
+
async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
|
|
158
|
+
const model = req.model ?? config.models?.[req.kind] ?? this.models[req.kind];
|
|
159
|
+
if (!model) throw new ConnectorError(`Higgsfield: say which ${req.kind} model to use (its path in the catalogue, as model: "…"), or set it once with clarity keys config higgsfield.models.${req.kind}.`, { connector: 'higgsfield' });
|
|
160
|
+
const base = config.baseUrl ?? 'https://api.higgsfield.ai', api = client({ name: 'Higgsfield', headers: { authorization: `Key ${key}` }, fetchImpl, signal });
|
|
161
|
+
const sent = await api.post(`${base}/${String(model).replace(/^\//, '')}`, { prompt: req.prompt, ...(req.aspect ? { aspect_ratio: req.aspect } : {}), ...(req.seconds ? { duration: req.seconds } : {}), ...(req.refs?.length ? { image_urls: req.refs } : {}), ...(req.options ?? {}) });
|
|
162
|
+
const url = sent.status_url ?? `${base}/requests/${sent.request_id}/status`;
|
|
163
|
+
const done = await waitFor(async () => { const s = await api.get(url); if (s.status === 'completed') return s; if (['failed', 'nsfw', 'canceled'].includes(s.status)) throw new ConnectorError(`Higgsfield: ${s.status === 'nsfw' ? 'refused by its content filter' : s.status}${s.error ? `: ${s.error}` : ''}.`, { connector: 'higgsfield', body: s }); return undefined; }, { every: 4000, signal, onProgress });
|
|
164
|
+
const urls = [...(done.images ?? []).map((i) => i.url), done.video?.url, done.audio?.url, ...(done.audios ?? []).map((a) => a.url)].filter(Boolean);
|
|
165
|
+
return { files: urls.map((u) => ({ url: u, ext: extOf(u, req.kind === 'video' ? 'mp4' : 'png') })), meta: { request: sent.request_id, model } };
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
// ── fal: a queue in front of hundreds of models (FLUX, Rodin, Kling, Wan …) ─────────────────
|
|
170
|
+
const fal = {
|
|
171
|
+
id: 'fal', name: 'fal (FLUX, Rodin, Kling, Wan and more)', kinds: ['image', 'video', 'model3d', 'sfx', 'music', 'voice', 'sprite', 'texture'], keyEnv: 'FAL_KEY', docs: 'https://fal.ai/docs/model-endpoints/queue', models: { image: 'fal-ai/flux/schnell', model3d: 'fal-ai/hyper3d/rodin', sprite: 'fal-ai/flux/schnell', texture: 'fal-ai/flux/schnell' },
|
|
172
|
+
estimate: (req) => ((req.model ?? fal.models[req.kind]) === 'fal-ai/hyper3d/rodin' ? fixed(0.4, 'Rodin on fal: about $0.40 a model') : unknown('fal bills each model at its own rate')),
|
|
173
|
+
async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
|
|
174
|
+
const model = req.model ?? config.models?.[req.kind] ?? this.models[req.kind];
|
|
175
|
+
if (!model) throw new ConnectorError(`fal: say which ${req.kind} model to use (its id on fal, as model: "…").`, { connector: 'fal' });
|
|
176
|
+
const base = config.baseUrl ?? 'https://queue.fal.run', api = client({ name: 'fal', headers: { authorization: `Key ${key}` }, fetchImpl, signal });
|
|
177
|
+
const input = model.includes('rodin') ? { prompt: req.prompt, geometry_file_format: 'glb', ...(req.refs?.length ? { input_image_urls: req.refs } : {}) } : { prompt: req.prompt, ...(req.aspect ? { aspect_ratio: req.aspect } : {}), ...(req.seconds ? { duration: req.seconds } : {}), ...(req.refs?.[0] ? { image_url: req.refs[0] } : {}) };
|
|
178
|
+
const sent = await api.post(`${base}/${model}`, { ...input, ...(req.options ?? {}) });
|
|
179
|
+
await waitFor(async () => { const s = await api.get(sent.status_url); if (s.status === 'COMPLETED') return s; if (s.error) throw new ConnectorError(`fal: ${s.error}`, { connector: 'fal', body: s }); return undefined; }, { every: 3000, signal, onProgress });
|
|
180
|
+
const result = await api.get(sent.response_url);
|
|
181
|
+
const files = findFiles(result).map((f) => ({ url: f.url, ext: extOf(f.name ?? f.url, req.kind === 'model3d' ? 'glb' : req.kind === 'video' ? 'mp4' : 'png') }));
|
|
182
|
+
if (!files.length) throw new ConnectorError('fal: the result held no file.', { connector: 'fal', body: result });
|
|
183
|
+
return { files, usd: model.includes('rodin') ? 0.4 : null, meta: { request: sent.request_id, model } };
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// ── Replicate: models by owner/name ──────────────────────────────────────────────────────────
|
|
188
|
+
const replicate = {
|
|
189
|
+
id: 'replicate', name: 'Replicate (open models by name)', kinds: ['image', 'video', 'model3d', 'music', 'voice', 'sfx', 'sprite', 'texture'], keyEnv: 'REPLICATE_API_TOKEN', docs: 'https://replicate.com/docs/reference/http', models: { image: 'black-forest-labs/flux-schnell', sprite: 'black-forest-labs/flux-schnell', texture: 'black-forest-labs/flux-schnell' },
|
|
190
|
+
estimate: () => unknown('Replicate bills each model by time or by output'),
|
|
191
|
+
async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
|
|
192
|
+
const model = req.model ?? config.models?.[req.kind] ?? this.models[req.kind];
|
|
193
|
+
if (!model) throw new ConnectorError(`Replicate: say which ${req.kind} model to use (owner/name).`, { connector: 'replicate' });
|
|
194
|
+
const base = config.baseUrl ?? 'https://api.replicate.com/v1', api = client({ name: 'Replicate', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
|
|
195
|
+
let p = await api.post(`${base}/models/${model}/predictions`, { input: { prompt: req.prompt, ...(req.aspect ? { aspect_ratio: req.aspect } : {}), ...(req.options ?? {}) } }, { prefer: 'wait=60' });
|
|
196
|
+
if (p.status !== 'succeeded') p = await waitFor(async () => { const q = await api.get(p.urls?.get ?? `${base}/predictions/${p.id}`); if (q.status === 'succeeded') return q; if (q.status === 'failed' || q.status === 'canceled') throw new ConnectorError(`Replicate: ${q.status}${q.error ? `: ${q.error}` : ''}.`, { connector: 'replicate', body: q }); return undefined; }, { every: 2500, signal, onProgress });
|
|
197
|
+
const files = findFiles(p.output).map((f) => ({ url: f.url, ext: extOf(f.url, 'png') }));
|
|
198
|
+
if (!files.length) throw new ConnectorError('Replicate: the prediction held no file.', { connector: 'replicate', body: p });
|
|
199
|
+
return { files, meta: { prediction: p.id, model } };
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// ── Black Forest Labs: FLUX.2 ────────────────────────────────────────────────────────────────
|
|
204
|
+
const bfl = {
|
|
205
|
+
id: 'bfl', name: 'Black Forest Labs (FLUX.2)', kinds: ['image', 'sprite', 'texture'], keyEnv: 'BFL_API_KEY', docs: 'https://docs.bfl.ai', models: { image: 'flux-2-pro-preview' },
|
|
206
|
+
estimate: () => unknown('BFL bills each FLUX.2 model per image (by megapixels)'),
|
|
207
|
+
async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
|
|
208
|
+
const base = config.baseUrl ?? 'https://api.bfl.ai/v1', api = client({ name: 'BFL', headers: { 'x-key': key, accept: 'application/json' }, fetchImpl, signal });
|
|
209
|
+
const model = req.model ?? config.model ?? this.models.image, [width, height] = sizeOf(req.aspect);
|
|
210
|
+
const sent = await api.post(`${base}/${model}`, { prompt: req.prompt, width, height, ...(req.options ?? {}) });
|
|
211
|
+
if (!sent?.polling_url) throw new ConnectorError('BFL: no task came back.', { connector: 'bfl', body: sent });
|
|
212
|
+
// the result is a signed link that lasts ten minutes: the generator fetches it straight away
|
|
213
|
+
const done = await waitFor(async () => { const q = await api.get(sent.polling_url); if (q.status === 'Ready') return q; if (['Error', 'Failed', 'Content Moderated', 'Request Moderated'].includes(q.status)) throw new ConnectorError(`BFL: ${q.status}.`, { connector: 'bfl', body: q }); return undefined; }, { every: 1500, signal, onProgress });
|
|
214
|
+
return { files: [{ url: done.result.sample, ext: extOf(done.result.sample, 'jpg') }], usd: typeof done.cost === 'number' ? done.cost : null, meta: { id: sent.id, model } };
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
// ── Recraft: images and SVG vectors (icons, logos, illustrations) ────────────────────────────
|
|
219
|
+
const recraft = {
|
|
220
|
+
id: 'recraft', name: 'Recraft (images, SVG vectors)', kinds: ['vector', 'image', 'texture'], keyEnv: 'RECRAFT_API_TOKEN', docs: 'https://www.recraft.ai/docs', models: { vector: 'recraftv4_1_vector' },
|
|
221
|
+
estimate: () => unknown('Recraft bills in credits per image'),
|
|
222
|
+
async generate(req, { key, fetchImpl, signal, config = {} }) {
|
|
223
|
+
const base = config.baseUrl ?? 'https://external.api.recraft.ai/v1', api = client({ name: 'Recraft', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
|
|
224
|
+
const model = req.model ?? config.models?.[req.kind] ?? this.models[req.kind]; // no model: Recraft's default
|
|
225
|
+
const r = await api.post(`${base}/images/generations`, { prompt: req.prompt, ...(model ? { model } : {}), ...(req.options ?? {}) });
|
|
226
|
+
const url = r?.data?.[0]?.url;
|
|
227
|
+
if (!url) throw new ConnectorError('Recraft: no image came back.', { connector: 'recraft', body: r });
|
|
228
|
+
return { files: [{ url, ext: req.kind === 'vector' ? 'svg' : extOf(url, 'webp') }], meta: { image: r.data[0].image_id ?? null, credits: r.credits ?? null } };
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
// ── PixelLab: pixel art (sprites, tiles) ─────────────────────────────────────────────────────
|
|
233
|
+
const pixellab = {
|
|
234
|
+
id: 'pixellab', name: 'PixelLab (pixel art)', kinds: ['sprite', 'texture', 'image'], keyEnv: 'PIXELLAB_API_KEY', keyEnvAlt: ['PIXELLAB_API_TOKEN', 'PIXELLAB_SECRET'], docs: 'https://api.pixellab.ai/v2/llms.txt', models: { sprite: 'create-image-pixflux' },
|
|
235
|
+
estimate: () => unknown('PixelLab bills per image; the answer says what it cost'),
|
|
236
|
+
async generate(req, { key, fetchImpl, signal, config = {} }) {
|
|
237
|
+
const base = config.baseUrl ?? 'https://api.pixellab.ai/v2', api = client({ name: 'PixelLab', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal });
|
|
238
|
+
const side = Number(req.options?.size ?? config.size ?? (req.kind === 'texture' ? 64 : 128)), [w, h] = req.aspect === '16:9' ? [side, Math.round(side * 9 / 16)] : req.aspect === '9:16' ? [Math.round(side * 9 / 16), side] : [side, side];
|
|
239
|
+
const { size: _size, ...rest } = req.options ?? {};
|
|
240
|
+
const r = await api.post(`${base}/${req.model ?? this.models.sprite}`, { description: req.prompt, image_size: { width: w, height: h }, no_background: req.kind === 'sprite', ...rest });
|
|
241
|
+
const data = r?.image?.base64;
|
|
242
|
+
if (!data) throw new ConnectorError('PixelLab: no image came back.', { connector: 'pixellab', body: r });
|
|
243
|
+
return { files: [{ bytes: b64(String(data).replace(/^data:[^,]+,/, '')), ext: 'png' }], usd: r.usage?.type === 'usd' ? r.usage.usd ?? null : null, meta: { size: [w, h] } };
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
// ── Retro Diffusion: pixel art, animations, tilesets ─────────────────────────────────────────
|
|
248
|
+
const retrodiffusion = {
|
|
249
|
+
id: 'retrodiffusion', name: 'Retro Diffusion (pixel art)', kinds: ['sprite', 'texture', 'image'], keyEnv: 'RETRODIFFUSION_API_KEY', docs: 'https://github.com/Retro-Diffusion/api-examples', models: { sprite: 'rd_core__default', texture: 'rd_core__default', image: 'rd_pro__default' },
|
|
250
|
+
estimate: (req) => ({ rd_lite: fixed(0.05, 'RD Lite: about $0.05 an image'), rd_core: fixed(0.1, 'RD Core: about $0.10 an image'), rd_pro: fixed(0.18, 'RD Pro: about $0.18 an image') })[String(req.model ?? retrodiffusion.models[req.kind]).split('__')[0]] ?? unknown('Retro Diffusion bills each style at its own rate'),
|
|
251
|
+
async generate(req, { key, fetchImpl, signal, onProgress, config = {} }) {
|
|
252
|
+
const base = config.baseUrl ?? 'https://api.retrodiffusion.ai/v2', api = client({ name: 'Retro Diffusion', headers: { 'x-rd-token': key }, fetchImpl, signal });
|
|
253
|
+
const side = Number(req.options?.size ?? config.size ?? 128), { size: _size, ...rest } = req.options ?? {};
|
|
254
|
+
const sent = await api.post(`${base}/inferences`, { prompt: req.prompt, prompt_style: req.model ?? config.models?.[req.kind] ?? this.models[req.kind], width: side, height: side, num_images: 1, remove_bg: req.kind === 'sprite', ...rest });
|
|
255
|
+
const id = sent?.task_id ?? sent?.id;
|
|
256
|
+
const task = sent?.result?.base64_images ? sent : await waitFor(async () => { const t = await api.get(`${base}/inferences/tasks/${encodeURIComponent(id)}`); if (t.status === 'succeeded') return t; if (['failed', 'error', 'cancelled'].includes(t.status)) throw new ConnectorError(`Retro Diffusion: the task ${t.status}${t.error ? `: ${t.error}` : ''}.`, { connector: 'retrodiffusion', body: t }); return undefined; }, { every: 2000, signal, onProgress });
|
|
257
|
+
const imgs = task.result?.base64_images ?? [];
|
|
258
|
+
if (!imgs.length) throw new ConnectorError('Retro Diffusion: no image came back.', { connector: 'retrodiffusion', body: task });
|
|
259
|
+
return { files: imgs.map((d) => { const bytes = b64(d); return { bytes, ext: bytes[0] === 0x47 ? 'gif' : 'png' }; }), usd: task.balance_cost ?? task.result?.balance_cost ?? null, meta: { task: id, model: task.model ?? null } };
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
// ── Stability AI: Stable Image ───────────────────────────────────────────────────────────────
|
|
264
|
+
const stability = {
|
|
265
|
+
id: 'stability', name: 'Stability AI (Stable Image, Stable Fast 3D)', kinds: ['image', 'texture', 'sprite', 'model3d'], keyEnv: 'STABILITY_API_KEY', docs: 'https://docs.stability.ai/api-reference', models: { image: 'core' },
|
|
266
|
+
estimate: (req) => req.kind === 'model3d' ? unknown('Stability bills Stable Fast 3D in credits (plus the picture when none is given)') : ({ core: fixed(0.03, 'Stable Image Core: $0.03 an image'), ultra: fixed(0.08, 'Stable Image Ultra: $0.08 an image') })[req.model ?? 'core'] ?? unknown('Stability bills in credits per image'),
|
|
267
|
+
async generate(req, { key, fetchImpl, signal, config = {} }) {
|
|
268
|
+
const base = config.baseUrl ?? 'https://api.stability.ai/v2beta', api = client({ name: 'Stability', headers: { authorization: `Bearer ${key}`, accept: 'image/*' }, fetchImpl, signal });
|
|
269
|
+
if (req.kind === 'model3d') {
|
|
270
|
+
// Stable Fast 3D turns one picture into a glb: the reference image, or one made first with Stable Image Core
|
|
271
|
+
let image = null;
|
|
272
|
+
if (req.refs?.[0]) image = new Blob([await client({ name: 'Stability', fetchImpl, signal }).bytes(req.refs[0])]);
|
|
273
|
+
else { const pic = await api.post(`${base}/stable-image/generate/core`, form({ prompt: `${req.prompt}, a single object centred on a plain white background`, output_format: 'png' })); image = new Blob([pic.bytes], { type: 'image/png' }); }
|
|
274
|
+
const glb = await client({ name: 'Stability', headers: { authorization: `Bearer ${key}` }, fetchImpl, signal }).post(`${base}/3d/stable-fast-3d`, form({ image, ...(req.options ?? {}) }));
|
|
275
|
+
if (!glb?.bytes) throw new ConnectorError('Stability: no model came back.', { connector: 'stability', body: glb });
|
|
276
|
+
return { files: [{ bytes: glb.bytes, ext: 'glb' }], meta: { model: 'stable-fast-3d' } };
|
|
277
|
+
}
|
|
278
|
+
const model = req.model ?? config.model ?? this.models.image;
|
|
279
|
+
const r = await api.post(`${base}/stable-image/generate/${model}`, form({ prompt: req.prompt, aspect_ratio: req.aspect, negative_prompt: req.negative, output_format: 'png', ...(req.options ?? {}) }));
|
|
280
|
+
if (!r?.bytes) throw new ConnectorError('Stability: no image came back.', { connector: 'stability', body: r });
|
|
281
|
+
return { files: [{ bytes: r.bytes, ext: /jpe?g/.test(r.type) ? 'jpg' : /webp/.test(r.type) ? 'webp' : 'png' }], meta: { model } };
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
// ── Cartesia: voices ─────────────────────────────────────────────────────────────────────────
|
|
286
|
+
const cartesia = {
|
|
287
|
+
id: 'cartesia', name: 'Cartesia (voices)', kinds: ['voice'], keyEnv: 'CARTESIA_API_KEY', docs: 'https://docs.cartesia.ai/api-reference/tts/bytes', models: { voice: 'sonic-3.6' }, voice: 'db6b0ed5-d5d3-463d-ae85-518a07d3c2b4', version: '2026-08-14',
|
|
288
|
+
estimate: () => unknown('Cartesia bills speech by characters (credits)'),
|
|
289
|
+
async generate(req, { key, fetchImpl, signal, config = {} }) {
|
|
290
|
+
const base = config.baseUrl ?? 'https://api.cartesia.ai', api = client({ name: 'Cartesia', headers: { authorization: `Bearer ${key}`, 'cartesia-version': config.version ?? this.version }, fetchImpl, signal });
|
|
291
|
+
const r = await api.post(`${base}/tts/bytes`, { model_id: req.model ?? this.models.voice, transcript: req.prompt, voice: { id: req.voice ?? config.voice ?? this.voice }, output_format: { container: 'mp3', sample_rate: 44100, bit_rate: 128000 }, ...(req.options ?? {}) });
|
|
292
|
+
if (!r?.bytes) throw new ConnectorError('Cartesia: no audio came back.', { connector: 'cartesia', body: r });
|
|
293
|
+
return { files: [{ bytes: r.bytes, ext: 'mp3' }] };
|
|
294
|
+
},
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
// ── ComfyUI on this computer ─────────────────────────────────────────────────────────────────
|
|
298
|
+
// a plain text-to-image graph in ComfyUI's API format; a workflow of one's own (exported with "Save (API)") can
|
|
299
|
+
// be given instead, with {{prompt}} and {{negative}} where the words go
|
|
300
|
+
export function comfyGraph({ prompt, negative = 'blurry, low quality, watermark, text', checkpoint, width = 1024, height = 1024, steps = 25, seed = Math.floor(Math.random() * 2 ** 31) }) {
|
|
301
|
+
return {
|
|
302
|
+
3: { class_type: 'KSampler', inputs: { seed, steps, cfg: 6.5, sampler_name: 'euler', scheduler: 'normal', denoise: 1, model: ['4', 0], positive: ['6', 0], negative: ['7', 0], latent_image: ['5', 0] } },
|
|
303
|
+
4: { class_type: 'CheckpointLoaderSimple', inputs: { ckpt_name: checkpoint } },
|
|
304
|
+
5: { class_type: 'EmptyLatentImage', inputs: { width, height, batch_size: 1 } },
|
|
305
|
+
6: { class_type: 'CLIPTextEncode', inputs: { text: prompt, clip: ['4', 1] } },
|
|
306
|
+
7: { class_type: 'CLIPTextEncode', inputs: { text: negative, clip: ['4', 1] } },
|
|
307
|
+
8: { class_type: 'VAEDecode', inputs: { samples: ['3', 0], vae: ['4', 2] } },
|
|
308
|
+
9: { class_type: 'SaveImage', inputs: { filename_prefix: 'clarity', images: ['8', 0] } },
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
export const fill = (graph, words) => JSON.parse(JSON.stringify(graph).replace(/\{\{(prompt|negative)\}\}/g, (_, k) => JSON.stringify(words[k] ?? '').slice(1, -1)));
|
|
312
|
+
const comfyui = {
|
|
313
|
+
id: 'comfyui', name: 'ComfyUI (this computer)', kinds: ['image', 'sprite', 'texture', 'video'], local: true, docs: 'https://docs.comfy.org', models: {},
|
|
314
|
+
estimate: () => fixed(0, 'runs on this computer: free'),
|
|
315
|
+
async generate(req, { fetchImpl, signal, onProgress, config = {} }) {
|
|
316
|
+
const base = config.baseUrl ?? 'http://127.0.0.1:8188', api = client({ name: 'ComfyUI', fetchImpl, signal });
|
|
317
|
+
const dims = (ASPECT_SIZE[req.aspect] ?? '1024x1024').split('x').map(Number);
|
|
318
|
+
let graph;
|
|
319
|
+
if (config.workflow) graph = fill(typeof config.workflow === 'string' ? JSON.parse(config.workflow) : config.workflow, { prompt: req.prompt, negative: req.negative });
|
|
320
|
+
else {
|
|
321
|
+
let checkpoint = req.model ?? config.checkpoint;
|
|
322
|
+
if (!checkpoint) { const info = await api.get(`${base}/object_info/CheckpointLoaderSimple`); checkpoint = info?.CheckpointLoaderSimple?.input?.required?.ckpt_name?.[0]?.[0]; }
|
|
323
|
+
if (!checkpoint) throw new ConnectorError('ComfyUI: it has no checkpoint to draw with. Put one in its models/checkpoints folder, or give a workflow of your own.', { connector: 'comfyui' });
|
|
324
|
+
graph = comfyGraph({ prompt: req.prompt, negative: req.negative, checkpoint, width: dims[0], height: dims[1] });
|
|
325
|
+
}
|
|
326
|
+
const sent = await api.post(`${base}/prompt`, { prompt: graph, client_id: 'clarity-agent' });
|
|
327
|
+
if (sent?.node_errors && Object.keys(sent.node_errors).length) throw new ConnectorError(`ComfyUI: the workflow has errors: ${JSON.stringify(sent.node_errors).slice(0, 300)}`, { connector: 'comfyui', body: sent });
|
|
328
|
+
const outputs = await waitFor(async () => { const h = await api.get(`${base}/history/${sent.prompt_id}`); const e = h?.[sent.prompt_id]; if (e?.status?.status_str === 'error') throw new ConnectorError('ComfyUI: the workflow failed.', { connector: 'comfyui', body: e.status }); return e?.outputs && Object.keys(e.outputs).length ? e.outputs : undefined; }, { every: 1500, signal, onProgress });
|
|
329
|
+
const files = [];
|
|
330
|
+
for (const out of Object.values(outputs)) for (const f of [...(out.images ?? []), ...(out.gifs ?? []), ...(out.videos ?? [])]) {
|
|
331
|
+
const q = new URLSearchParams({ filename: f.filename, subfolder: f.subfolder ?? '', type: f.type ?? 'output' });
|
|
332
|
+
files.push({ bytes: await api.bytes(`${base}/view?${q}`), ext: extOf(f.filename, 'png') });
|
|
333
|
+
}
|
|
334
|
+
return { files, usd: 0, meta: { prompt: sent.prompt_id } };
|
|
335
|
+
},
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
// ── Comfy Cloud: the same workflows on Comfy's GPUs ──────────────────────────────────────────
|
|
340
|
+
// a job is sent like ComfyUI's, watched at /api/jobs/{id}; /api/view answers with a redirect to a signed link,
|
|
341
|
+
// which is fetched without the key (the key must not go to the storage host)
|
|
342
|
+
const comfyCloud = {
|
|
343
|
+
id: 'comfy-cloud', name: 'Comfy Cloud (ComfyUI workflows, hosted)', kinds: ['image', 'sprite', 'texture', 'video'], keyEnv: 'COMFY_CLOUD_API_KEY', docs: 'https://docs.comfy.org/development/cloud/api-reference', models: {},
|
|
344
|
+
estimate: () => unknown('Comfy Cloud bills GPU time from the subscription\'s credits'),
|
|
345
|
+
async generate(req, { key, fetchImpl = globalThis.fetch, signal, onProgress, config = {} }) {
|
|
346
|
+
const base = config.baseUrl ?? 'https://cloud.comfy.org', api = client({ name: 'Comfy Cloud', headers: { 'x-api-key': key }, fetchImpl, signal });
|
|
347
|
+
const [width, height] = sizeOf(req.aspect);
|
|
348
|
+
let graph;
|
|
349
|
+
if (config.workflow) graph = fill(typeof config.workflow === 'string' ? JSON.parse(config.workflow) : config.workflow, { prompt: req.prompt, negative: req.negative });
|
|
350
|
+
else {
|
|
351
|
+
let checkpoint = req.model ?? config.checkpoint;
|
|
352
|
+
if (!checkpoint) { const info = await api.get(`${base}/api/object_info`); checkpoint = info?.CheckpointLoaderSimple?.input?.required?.ckpt_name?.[0]?.[0]; }
|
|
353
|
+
if (!checkpoint) throw new ConnectorError('Comfy Cloud: no checkpoint found. Give one (model: "…") or a workflow of your own.', { connector: 'comfy-cloud' });
|
|
354
|
+
graph = comfyGraph({ prompt: req.prompt, negative: req.negative, checkpoint, width, height });
|
|
355
|
+
}
|
|
356
|
+
const sent = await api.post(`${base}/api/prompt`, { prompt: graph, ...(config.partnerKey ? { extra_data: { api_key_comfy_org: config.partnerKey } } : {}) });
|
|
357
|
+
if (sent?.error || !sent?.prompt_id) throw new ConnectorError(`Comfy Cloud: the workflow was not accepted${sent?.error ? `: ${JSON.stringify(sent.error).slice(0, 300)}` : ''}.`, { connector: 'comfy-cloud', body: sent });
|
|
358
|
+
const job = await waitFor(async () => { const j = await api.get(`${base}/api/jobs/${encodeURIComponent(sent.prompt_id)}`); if (j.status === 'completed') return j; if (['failed', 'cancelled', 'error'].includes(j.status)) throw new ConnectorError(`Comfy Cloud: the job ${j.status}${j.execution_error?.exception_message ? `: ${j.execution_error.exception_message}` : ''}.`, { connector: 'comfy-cloud', body: j }); return undefined; }, { every: 2500, signal, onProgress });
|
|
359
|
+
const files = [];
|
|
360
|
+
for (const out of Object.values(job.outputs ?? {})) for (const f of [...(out.images ?? []), ...(out.video ?? []), ...(out.videos ?? []), ...(out.gifs ?? [])]) {
|
|
361
|
+
const q = new URLSearchParams({ filename: f.filename, subfolder: f.subfolder ?? '', type: f.type ?? 'output' });
|
|
362
|
+
const res = await fetchImpl(`${base}/api/view?${q}`, { headers: { 'x-api-key': key }, redirect: 'manual', signal });
|
|
363
|
+
const to = res.headers.get?.('location');
|
|
364
|
+
files.push(to ? { url: new URL(to, base).href, ext: extOf(f.filename, 'png') } : { bytes: new Uint8Array(await res.arrayBuffer()), ext: extOf(f.filename, 'png') });
|
|
365
|
+
}
|
|
366
|
+
if (!files.length) throw new ConnectorError('Comfy Cloud: the job finished with no file.', { connector: 'comfy-cloud', body: job });
|
|
367
|
+
return { files, meta: { job: sent.prompt_id } };
|
|
368
|
+
},
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
export const ADAPTERS = [comfyui, comfyCloud, higgsfield, minimax, elevenlabs, cartesia, tripo, meshy, bfl, recraft, pixellab, retrodiffusion, stability, fal, replicate, openaiImages, geminiImages, ...MORE_ADAPTERS];
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// @clarity-js/agent — what every connector needs: JSON over HTTP with a key, waiting for a job to finish, and
|
|
2
|
+
// fetching the file it made. Errors say which service and what it answered.
|
|
3
|
+
|
|
4
|
+
export class ConnectorError extends Error {
|
|
5
|
+
constructor(message, { status, connector, body } = {}) { super(message); this.name = 'ConnectorError'; this.status = status; this.connector = connector; this.body = body; }
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function client({ name, headers = {}, fetchImpl = globalThis.fetch, signal }) {
|
|
9
|
+
const call = async (method, url, body, extra = {}) => {
|
|
10
|
+
let res;
|
|
11
|
+
// JSON, raw bytes, or a form (multipart: fetch writes its own content-type with the boundary)
|
|
12
|
+
const raw = body instanceof Uint8Array || (typeof FormData !== 'undefined' && body instanceof FormData);
|
|
13
|
+
try { res = await fetchImpl(url, { method, headers: { ...(body !== undefined && !raw ? { 'content-type': 'application/json' } : {}), ...headers, ...extra }, body: body === undefined ? undefined : raw ? body : JSON.stringify(body), signal }); }
|
|
14
|
+
catch (e) { throw new ConnectorError(`${name}: ${e?.cause?.code === 'ECONNREFUSED' ? `nothing is listening at ${new URL(url).origin} (is it running?)` : e.message}`, { connector: name }); }
|
|
15
|
+
const type = res.headers.get?.('content-type') ?? '';
|
|
16
|
+
if (!res.ok) {
|
|
17
|
+
const text = await res.text().catch(() => ''); let j = null; try { j = JSON.parse(text); } catch { /* text */ }
|
|
18
|
+
const why = j?.error?.message ?? j?.detail?.message ?? (typeof j?.detail === 'string' ? j.detail : null) ?? j?.message ?? j?.base_resp?.status_msg ?? text.slice(0, 300);
|
|
19
|
+
throw new ConnectorError(`${name}: ${res.status} ${why}`, { status: res.status, connector: name, body: j ?? text });
|
|
20
|
+
}
|
|
21
|
+
if (/json/.test(type)) return res.json();
|
|
22
|
+
if (/^(audio|image|video|model|application\/octet-stream)/.test(type)) return { bytes: new Uint8Array(await res.arrayBuffer()), type };
|
|
23
|
+
const text = await res.text(); try { return JSON.parse(text); } catch { return text; }
|
|
24
|
+
};
|
|
25
|
+
return { get: (u, h) => call('GET', u, undefined, h), post: (u, b, h) => call('POST', u, b, h), bytes: async (u, h) => { const r = await call('GET', u, undefined, h); return r?.bytes ?? new TextEncoder().encode(typeof r === 'string' ? r : JSON.stringify(r)); } };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Ask `check` until it returns something (not undefined), every `every` ms, at most `timeout` ms. */
|
|
29
|
+
export async function waitFor(check, { every = 3000, timeout = 15 * 60000, signal, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), onProgress } = {}) {
|
|
30
|
+
const t0 = Date.now();
|
|
31
|
+
if (process.env.CLARITY_AGENT_POLL_MS) every = Number(process.env.CLARITY_AGENT_POLL_MS); // tests wait less
|
|
32
|
+
for (let i = 0; ; i++) {
|
|
33
|
+
if (signal?.aborted) throw new Error('Stopped.');
|
|
34
|
+
const r = await check(i);
|
|
35
|
+
if (r !== undefined) return r;
|
|
36
|
+
if (Date.now() - t0 > timeout) throw new Error(`still not ready after ${Math.round(timeout / 60000)} minutes`);
|
|
37
|
+
onProgress?.(i);
|
|
38
|
+
await sleep(every);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const b64 = (s) => Uint8Array.from(Buffer.from(s, 'base64'));
|
|
43
|
+
export const hex = (s) => Uint8Array.from(Buffer.from(s, 'hex'));
|
|
44
|
+
/** A form for the services that take multipart/form-data: { a: 1, b: undefined } → FormData with a only. */
|
|
45
|
+
export const form = (fields) => { const f = new FormData(); for (const [k, v] of Object.entries(fields)) if (v !== undefined && v !== null) f.append(k, v instanceof Blob ? v : typeof v === 'object' ? JSON.stringify(v) : String(v)); return f; };
|
|
46
|
+
export const extOf = (url, fallback) => { const m = /\.([a-z0-9]{2,5})(?:\?|#|$)/i.exec(String(url ?? '')); return (m?.[1] ?? fallback).toLowerCase(); };
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// @clarity-js/agent — connectors: one way to ask any service for an asset. The agent says what it wants (an
|
|
2
|
+
// image, a sprite, an SVG vector (icons, logos), a 3D model, a video, a voice line, a sound effect, music); the connector is picked (the one
|
|
3
|
+
// named, or the first with a key for that kind, local ones first); its price is shown and the limits checked
|
|
4
|
+
// before anything is spent; the files are saved into the project and written down with what made them.
|
|
5
|
+
//
|
|
6
|
+
// const gen = generator({ root, keys, ledger })
|
|
7
|
+
// await gen.make({ kind: 'model3d', prompt: 'a paper lantern', via: 'tripo' }) // → { files: ['assets/model3d/a-paper-lantern.glb'], usd, connector }
|
|
8
|
+
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import { ADAPTERS } from './adapters.js';
|
|
13
|
+
import { client } from './http.js';
|
|
14
|
+
import { inside } from '../tools.js';
|
|
15
|
+
import { usd as money } from '../budget.js';
|
|
16
|
+
|
|
17
|
+
export const KINDS = ['image', 'sprite', 'texture', 'vector', 'video', 'model3d', 'voice', 'sfx', 'music'];
|
|
18
|
+
const slug = (s) => String(s).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || 'asset';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The generator. keys: a key store (keys.js); ledger: budget.js; config: { connectorId: { baseUrl, model, … } };
|
|
22
|
+
* adapters: the connectors (ADAPTERS, and any of one's own).
|
|
23
|
+
*/
|
|
24
|
+
export function generator({ root = process.cwd(), keys, ledger, config = {}, adapters = ADAPTERS, fetchImpl = globalThis.fetch, onProgress } = {}) {
|
|
25
|
+
const byId = new Map(adapters.map((a) => [a.id, a]));
|
|
26
|
+
// a local connector is ready unless it needs a setting first (Piper: which voice)
|
|
27
|
+
const keyOf = (a) => (a.local ? (!a.needs || a.needs.every((k) => config[a.id]?.[k]) ? 'local' : null) : keys?.get(a.id) ?? null);
|
|
28
|
+
const cacheFile = path.join(root, '.clarity', 'assets-cache.json');
|
|
29
|
+
const readCache = () => { try { return JSON.parse(fs.readFileSync(cacheFile, 'utf8')); } catch { return {}; } };
|
|
30
|
+
return {
|
|
31
|
+
adapters,
|
|
32
|
+
/** Which connectors can make this kind, and whether each has its key. */
|
|
33
|
+
available(kind) { return adapters.filter((a) => !kind || a.kinds.includes(kind)).map((a) => ({ id: a.id, name: a.name, kinds: a.kinds, local: !!a.local, ready: !!keyOf(a) })); },
|
|
34
|
+
/** The connector for a request: the one named, or the first ready one (local first). */
|
|
35
|
+
pick({ kind, via }) {
|
|
36
|
+
if (via) { const a = byId.get(via); if (!a) throw new Error(`No connector "${via}". Connectors: ${[...byId.keys()].join(', ')}.`); if (!a.kinds.includes(kind)) throw new Error(`${a.name} does not make ${kind} (it makes ${a.kinds.join(', ')}).`); return a; }
|
|
37
|
+
const ready = adapters.filter((a) => a.kinds.includes(kind) && keyOf(a) && (!a.local || config[a.id]?.enabled !== false));
|
|
38
|
+
const pick = ready.find((a) => a.local && config[a.id]?.enabled) ?? ready.find((a) => !a.local) ?? ready[0];
|
|
39
|
+
if (!pick) throw new Error(`No connector with a key makes ${kind}. Add one: clarity keys set <${adapters.filter((a) => a.kinds.includes(kind) && !a.local).map((a) => a.id).join('|')}>.`);
|
|
40
|
+
return pick;
|
|
41
|
+
},
|
|
42
|
+
/** The price before: { connector, usd, note, refuse? } */
|
|
43
|
+
quote(req) {
|
|
44
|
+
const a = this.pick(req), e = a.estimate(req, config[a.id] ?? {});
|
|
45
|
+
const over = ledger && e.usd != null ? ledger.check(a.id, e.usd) : null;
|
|
46
|
+
return { connector: a.id, name: a.name, usd: e.usd, note: e.note, ...(over ? { refuse: `Not made: ${a.name} would cost about ${money(e.usd)}, which passes ${over}. Raise the limit (clarity keys limits) or choose a cheaper way.` } : {}) };
|
|
47
|
+
},
|
|
48
|
+
/** Make it: → { files, usd, connector, cached, license } */
|
|
49
|
+
async make(req, { signal, touch } = {}) {
|
|
50
|
+
if (!KINDS.includes(req.kind)) throw new Error(`What kind of asset? One of ${KINDS.join(', ')}.`);
|
|
51
|
+
if (!String(req.prompt ?? '').trim()) throw new Error('Say what to make: a prompt.');
|
|
52
|
+
const a = this.pick(req), cfg = config[a.id] ?? {};
|
|
53
|
+
const hash = crypto.createHash('sha256').update(JSON.stringify([a.id, req.kind, req.prompt, req.negative, req.aspect, req.seconds, req.voice, req.model, req.options ?? null])).digest('hex').slice(0, 16);
|
|
54
|
+
const cache = readCache();
|
|
55
|
+
if (cache[hash] && cache[hash].files.every((f) => fs.existsSync(path.join(root, f)))) return { ...cache[hash], cached: true };
|
|
56
|
+
const r = await a.generate(req, { key: keyOf(a), fetchImpl, signal, onProgress, config: cfg });
|
|
57
|
+
const dir = inside(root, req.out ? path.dirname(req.out) : path.join('assets', req.kind));
|
|
58
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
59
|
+
const name = req.out ? path.basename(req.out).replace(/\.[^.]+$/, '') : slug(req.name ?? req.prompt);
|
|
60
|
+
const files = [];
|
|
61
|
+
const get = client({ name: a.name, fetchImpl, signal });
|
|
62
|
+
for (const [i, f] of r.files.entries()) {
|
|
63
|
+
const bytes = f.bytes ?? (f.url ? await get.bytes(f.url) : null);
|
|
64
|
+
if (!bytes) continue;
|
|
65
|
+
let file = path.join(dir, `${name}${f.preview ? '.preview' : ''}${i && !f.preview ? `-${i + 1}` : ''}.${f.ext ?? 'bin'}`);
|
|
66
|
+
if (!req.out && fs.existsSync(file) && !cache[hash]) file = file.replace(/(\.[^.]+)$/, `-${hash.slice(0, 4)}$1`);
|
|
67
|
+
touch?.(file);
|
|
68
|
+
fs.writeFileSync(file, bytes);
|
|
69
|
+
files.push(path.relative(fs.realpathSync(root), file).split(path.sep).join('/')); // assets/image/a.png on Windows too: it goes into code
|
|
70
|
+
}
|
|
71
|
+
const spent = r.usd ?? this.quote(req).usd ?? null;
|
|
72
|
+
if (ledger) ledger.record({ connector: a.id, kind: req.kind, usd: spent ?? 0, priced: spent != null, prompt: String(req.prompt).slice(0, 200), files });
|
|
73
|
+
const out = { files, usd: spent, connector: a.id, name: a.name, license: `Made with ${a.name}; its terms of use decide how the output may be used (${a.docs}).`, meta: r.meta ?? {}, at: new Date().toISOString() };
|
|
74
|
+
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
|
|
75
|
+
fs.writeFileSync(cacheFile, JSON.stringify({ ...readCache(), [hash]: out }, null, 2));
|
|
76
|
+
return { ...out, cached: false };
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const obj = (properties, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
|
|
82
|
+
/** generate_asset, for the agent: priced and checked first, then asked (money is always asked). */
|
|
83
|
+
export function assetTool(gen) {
|
|
84
|
+
return {
|
|
85
|
+
name: 'generate_asset', risk: 'spend',
|
|
86
|
+
description: `Make an asset with a connected service and save it into the project: an image (a hero picture, a product shot, an illustration), a sprite, a texture, an SVG vector (an icon, a logo), a video, a 3D model (glb), a voice line, a sound effect or music. It is priced first and the user is asked. Connectors: ${gen.adapters.map((a) => `${a.id} (${a.kinds.join(', ')})`).join('; ')}. Without via, the first one with a key is used. Follow the project's style.json in the prompt when there is one.`,
|
|
87
|
+
inputSchema: obj({
|
|
88
|
+
kind: { type: 'string', enum: KINDS }, prompt: { type: 'string', description: 'What it is, how it looks or sounds.' },
|
|
89
|
+
via: { type: 'string', description: 'The connector (its id).' }, model: { type: 'string', description: 'A model of that connector, when not its default.' },
|
|
90
|
+
out: { type: 'string', description: 'Where to save it, from the project\'s root (assets/<kind>/<name>.<ext>).' }, name: { type: 'string', description: 'A short file name.' },
|
|
91
|
+
aspect: { type: 'string', description: 'For pictures and video: 1:1, 16:9, 9:16, 4:3, 3:4.' }, seconds: { type: 'number', description: 'For video, sound and music: how long.' },
|
|
92
|
+
voice: { type: 'string', description: 'For a voice line: the voice id.' }, negative: { type: 'string', description: 'What it must not have.' },
|
|
93
|
+
}, ['kind', 'prompt']),
|
|
94
|
+
summary: (a) => `make ${a.kind} "${String(a.prompt).slice(0, 80)}"${a.via ? ` with ${a.via}` : ''}`,
|
|
95
|
+
quote: (args) => gen.quote(args),
|
|
96
|
+
async run(args, { signal, touch }) {
|
|
97
|
+
const r = await gen.make(args, { signal, touch });
|
|
98
|
+
return { text: `${r.cached ? 'Already made (from the cache)' : `Made with ${r.name}`}: ${r.files.join(', ')}${r.usd != null ? ` (${money(r.usd)})` : ''}. ${r.license}`, data: r };
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export { ADAPTERS };
|