emitter-mcp 1.0.1

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.
Files changed (3) hide show
  1. package/README.md +81 -0
  2. package/dist/server.js +2071 -0
  3. package/package.json +29 -0
package/dist/server.js ADDED
@@ -0,0 +1,2071 @@
1
+ #!/usr/bin/env node
2
+
3
+ // server.ts
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+
7
+ // core.ts
8
+ import { spawn } from "node:child_process";
9
+ import { readFile as readFile2, stat } from "node:fs/promises";
10
+ import { homedir as homedir2 } from "node:os";
11
+ import { basename, join as join3 } from "node:path";
12
+ import sharp2 from "sharp";
13
+
14
+ // config.ts
15
+ import { readFileSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { isAbsolute, join, resolve } from "node:path";
18
+
19
+ // ../lib/models.ts
20
+ var IMAGE_SIZES = [
21
+ { value: "square", label: "Square", short: "1:1", aspect: "1 / 1" },
22
+ { value: "square_hd", label: "Square HD", short: "1:1 HD", aspect: "1 / 1" },
23
+ { value: "landscape_16_9", label: "Landscape 16:9", short: "16:9", aspect: "16 / 9" },
24
+ { value: "landscape_4_3", label: "Landscape 4:3", short: "4:3", aspect: "4 / 3" },
25
+ { value: "portrait_4_3", label: "Portrait 3:4", short: "3:4", aspect: "3 / 4" },
26
+ { value: "portrait_16_9", label: "Portrait 9:16", short: "9:16", aspect: "9 / 16" }
27
+ ];
28
+ var HD_MODEL_ID = "openai/gpt-image-2.5/sunburst/text-to-image";
29
+ var QUALITIES = ["auto", "low", "medium", "high", "xhigh", "max"];
30
+ var GPT_IMAGE_2_5_QUALITY = QUALITIES;
31
+ var MODELS = [
32
+ {
33
+ id: "openai/gpt-image-2.5/sunburst/text-to-image",
34
+ label: "GPT Image 2.5 Sunburst",
35
+ short: "Image 2.5 Sunburst",
36
+ edit: { id: "openai/gpt-image-2.5/sunburst/edit", max: 16, mask: true },
37
+ seed: false,
38
+ quality: GPT_IMAGE_2_5_QUALITY,
39
+ background: true,
40
+ safety: "checker"
41
+ },
42
+ {
43
+ id: "openai/gpt-image-2.5/flare/text-to-image",
44
+ label: "GPT Image 2.5 Flare",
45
+ short: "Image 2.5 Flare",
46
+ edit: { id: "openai/gpt-image-2.5/flare/edit", max: 16, mask: true },
47
+ seed: false,
48
+ quality: GPT_IMAGE_2_5_QUALITY,
49
+ background: true,
50
+ safety: "checker"
51
+ },
52
+ {
53
+ id: "openai/gpt-image-2",
54
+ label: "GPT Image 2",
55
+ short: "Image 2",
56
+ edit: { id: "openai/gpt-image-2/edit", max: 16, mask: true },
57
+ seed: false,
58
+ quality: ["auto", "low", "medium", "high"],
59
+ background: true,
60
+ safety: "checker"
61
+ },
62
+ {
63
+ id: "xai/grok-imagine-image/v2.0/text-to-image",
64
+ label: "Grok Imagine 2.0",
65
+ edit: { id: "xai/grok-imagine-image/v2.0/edit", max: 3 },
66
+ sizing: "aspect_ratio",
67
+ seed: false,
68
+ quality: ["low", "medium"],
69
+ resolution: ["1k", "2k", "2k"],
70
+ safety: "checker"
71
+ },
72
+ {
73
+ id: "xai/grok-imagine-image",
74
+ label: "Grok Imagine",
75
+ edit: { id: "xai/grok-imagine-image/edit", max: 3 },
76
+ sizing: "aspect_ratio",
77
+ seed: false,
78
+ resolution: ["1k", "2k", "2k"],
79
+ safety: "checker"
80
+ },
81
+ {
82
+ id: "google/nano-banana-2.5",
83
+ label: "Nano Banana 2.5",
84
+ edit: { id: "google/nano-banana-2.5/edit", max: 14 },
85
+ sizing: "aspect_ratio",
86
+ resolution: ["1K", "2K", "4K"],
87
+ safety: { default: 4, min: 1, max: 6, string: true },
88
+ thinking: true
89
+ },
90
+ {
91
+ id: "google/nano-banana-2.1",
92
+ label: "Nano Banana 2.1",
93
+ edit: { id: "google/nano-banana-2.1/edit", max: 14 },
94
+ sizing: "aspect_ratio",
95
+ resolution: ["1K", "2K", "4K"],
96
+ safety: { default: 4, min: 1, max: 6, string: true },
97
+ thinking: true
98
+ },
99
+ {
100
+ id: "blackforestlabs/flux-3/text-to-image",
101
+ label: "FLUX 3",
102
+ edit: { id: "blackforestlabs/flux-3/edit-image", max: 10 },
103
+ sizing: "aspect_ratio",
104
+ resolution: ["1k", "2k", "4k"],
105
+ seed: false,
106
+ numImages: false,
107
+ safety: { default: 2, min: 0, max: 4 },
108
+ enhancePrompt: "enable_prompt_expansion"
109
+ }
110
+ ];
111
+ var DEFAULT_MODEL_ID = MODELS[0].id;
112
+ var getModel = (endpoint) => MODELS.find((m) => m.id === endpoint || m.edit?.id === endpoint) ?? { id: endpoint, label: endpoint, custom: true };
113
+ var MAX_REF_CAP = Math.max(...MODELS.map((m) => m.edit?.max ?? 0));
114
+
115
+ // ../lib/direct-core.ts
116
+ var DIRECT_KEY_HEADER = "x-direct-key";
117
+ var DIRECT_RESOURCE_HEADER = "x-direct-resource";
118
+ var DIRECT_DEPLOYMENT_HEADER = "x-direct-deployment";
119
+ var DIRECT_ENDPOINTS = [HD_MODEL_ID, getModel(HD_MODEL_ID).edit?.id].filter((id) => Boolean(id));
120
+
121
+ // config.ts
122
+ class ConfigError extends Error {
123
+ }
124
+ var DEFAULT_URL = "https://emitter.sh";
125
+ var DIRECT_KEYS = [
126
+ { name: "EMITTER_DIRECT_KEY", fallback: "ANTHROPIC_FOUNDRY_API_KEY", field: "key" },
127
+ { name: "EMITTER_DIRECT_RESOURCE", fallback: "ANTHROPIC_FOUNDRY_RESOURCE", field: "resource" },
128
+ { name: "EMITTER_DIRECT_DEPLOYMENT", fallback: "FOUNDRY_IMAGE_DEPLOYMENT", field: "deployment" }
129
+ ];
130
+ var expand = (path) => {
131
+ const p = path.trim();
132
+ if (p === "~")
133
+ return homedir();
134
+ if (p.startsWith("~/"))
135
+ return join(homedir(), p.slice(2));
136
+ return isAbsolute(p) ? p : resolve(p);
137
+ };
138
+ var parseEnvFile = (text) => {
139
+ const out = {};
140
+ for (const raw of text.split(/\r?\n/)) {
141
+ let line = raw.trim();
142
+ if (!line || line.startsWith("#"))
143
+ continue;
144
+ if (line.startsWith("export "))
145
+ line = line.slice(7).trim();
146
+ const at = line.indexOf("=");
147
+ if (at < 1)
148
+ continue;
149
+ const key = line.slice(0, at).trim();
150
+ let value = line.slice(at + 1).trim();
151
+ const quote = value[0];
152
+ if (value.length >= 2 && (quote === '"' || quote === "'") && value.endsWith(quote))
153
+ value = value.slice(1, -1);
154
+ out[key] = value;
155
+ }
156
+ return out;
157
+ };
158
+ var readEnvFile = (path) => {
159
+ if (!path)
160
+ return {};
161
+ try {
162
+ return parseEnvFile(readFileSync(path, "utf8"));
163
+ } catch {
164
+ return {};
165
+ }
166
+ };
167
+ var readConfig = (env = process.env) => {
168
+ const named = env.EMITTER_ENV_FILE?.trim() ? expand(env.EMITTER_ENV_FILE) : undefined;
169
+ const fromNamed = readEnvFile(named);
170
+ const home = expand(env.EMITTER_HOME?.trim() || fromNamed.EMITTER_HOME || "~/.emitter");
171
+ const homeFile = join(home, "env");
172
+ const fromHome = readEnvFile(homeFile);
173
+ const fromFiles = (key) => fromNamed[key]?.trim() || fromHome[key]?.trim() || undefined;
174
+ const get = (key) => env[key]?.trim() || fromFiles(key);
175
+ const values = DIRECT_KEYS.map((k) => ({ ...k, value: get(k.name) ?? fromFiles(k.fallback) }));
176
+ const present = values.filter((v) => v.value);
177
+ if (present.length && present.length < values.length) {
178
+ const missing = values.filter((v) => !v.value).map((v) => v.name);
179
+ throw new ConfigError(`Direct rendering is half configured: ${missing.join(", ")} ${missing.length > 1 ? "are" : "is"} missing. Set all three of ${DIRECT_KEYS.map((k) => k.name).join(", ")} in ${named ?? homeFile}, or none.`);
180
+ }
181
+ const direct = present.length ? Object.fromEntries(values.map((v) => [v.field, v.value])) : undefined;
182
+ return {
183
+ home,
184
+ url: (get("EMITTER_URL") ?? DEFAULT_URL).replace(/\/+$/, ""),
185
+ token: get("EMITTER_TOKEN"),
186
+ ...direct && { direct },
187
+ directOnly: !/^(false|0|no|off)$/i.test(get("EMITTER_DIRECT_ONLY") ?? ""),
188
+ images: expand(get("EMITTER_IMAGES") ?? "~/Downloads/emitter"),
189
+ envFile: named ?? homeFile
190
+ };
191
+ };
192
+ var headersOf = (config, direct = true) => ({
193
+ ...config.token && { authorization: `Bearer ${config.token}` },
194
+ ...direct && config.direct && {
195
+ [DIRECT_KEY_HEADER]: config.direct.key,
196
+ [DIRECT_RESOURCE_HEADER]: config.direct.resource,
197
+ [DIRECT_DEPLOYMENT_HEADER]: config.direct.deployment
198
+ }
199
+ });
200
+ var secretsOf = (config) => [config.token, config.direct?.key].filter((s) => Boolean(s && s.length >= 6));
201
+ var scrub = (text, secrets) => secrets.reduce((out, secret) => out.split(secret).join("[redacted]"), text);
202
+ var norm = (s) => s.trim().toLowerCase().replace(/\s+/g, " ");
203
+ var DIRECT_MODEL_NAMES = new Set([...DIRECT_ENDPOINTS, getModel(HD_MODEL_ID).label, getModel(HD_MODEL_ID).short ?? "", "gpt", "gpt image", "gpt-image", "openai", "sunburst", "gpt image 2.5", "gpt-image-2.5"].filter(Boolean).map(norm));
204
+ var DIRECT_MODEL_LABEL = getModel(HD_MODEL_ID).label;
205
+ var isDirectModel = (name) => DIRECT_MODEL_NAMES.has(norm(name));
206
+
207
+ // api.ts
208
+ class ApiError extends Error {
209
+ status;
210
+ errorCode;
211
+ body;
212
+ constructor(message, status, errorCode, body) {
213
+ super(message);
214
+ this.status = status;
215
+ this.errorCode = errorCode;
216
+ this.body = body;
217
+ }
218
+ }
219
+ var isObject = (x) => !!x && typeof x === "object" && !Array.isArray(x);
220
+ var reasonOf = (err) => {
221
+ if (err instanceof Error)
222
+ return err.name === "AbortError" || err.name === "TimeoutError" ? "the request timed out" : err.message;
223
+ return String(err);
224
+ };
225
+ async function apiCall(fetcher, config, method, path, options = {}) {
226
+ const headers = headersOf(config, options.direct !== false);
227
+ let body;
228
+ if (options.raw) {
229
+ headers["content-type"] = options.contentType ?? "application/octet-stream";
230
+ body = options.raw;
231
+ } else if (options.body !== undefined) {
232
+ headers["content-type"] = "application/json";
233
+ body = JSON.stringify(options.body);
234
+ }
235
+ let res;
236
+ try {
237
+ res = await fetcher(config.url + path, { method, headers, body, signal: AbortSignal.timeout(options.timeoutMs ?? 60000) });
238
+ } catch (err) {
239
+ throw new ApiError(`Could not reach ${config.url}: ${reasonOf(err)}`, 0, "unreachable");
240
+ }
241
+ const text = await res.text().catch(() => "");
242
+ let parsed;
243
+ try {
244
+ parsed = text ? JSON.parse(text) : null;
245
+ } catch {
246
+ parsed = undefined;
247
+ }
248
+ if (res.ok) {
249
+ if (parsed === undefined)
250
+ throw new ApiError(`${method} ${path} answered ${res.status} with a body that is not JSON`, res.status, "upstream_error");
251
+ return parsed;
252
+ }
253
+ const answer = isObject(parsed) ? parsed : undefined;
254
+ const message = typeof answer?.error === "string" ? answer.error : text.trim().slice(0, 300) || `${method} ${path} answered ${res.status}`;
255
+ throw new ApiError(message, res.status, typeof answer?.errorCode === "string" ? answer.errorCode : undefined, parsed);
256
+ }
257
+
258
+ // images.ts
259
+ import { mkdir as mkdir2 } from "node:fs/promises";
260
+ import { dirname } from "node:path";
261
+ import sharp from "sharp";
262
+
263
+ // store.ts
264
+ import { createHash, randomBytes } from "node:crypto";
265
+ import { appendFile, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
266
+ import { join as join2 } from "node:path";
267
+ var sanitizeName = (raw) => raw.toLowerCase().replace(/[^a-z0-9]+/g, "-").split("-").filter(Boolean).slice(0, 2).join("-");
268
+ var HANDLE = /^([a-z0-9]+(?:-[a-z0-9]+)?)-v(\d+)(?:-([a-z]))?$/;
269
+ var parseHandle = (text) => {
270
+ const m = HANDLE.exec(text.trim());
271
+ if (!m)
272
+ return;
273
+ return { run: `${m[1]}-v${m[2]}`, name: m[1], version: Number(m[2]), ...m[3] && { letter: m[3] } };
274
+ };
275
+ var letterOf = (slot) => String.fromCharCode(97 + slot);
276
+ async function writeAtomic(path, data) {
277
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
278
+ await writeFile(tmp, data);
279
+ await rename(tmp, path);
280
+ }
281
+ var readJson = async (path, fallback) => {
282
+ try {
283
+ return JSON.parse(await readFile(path, "utf8"));
284
+ } catch {
285
+ return fallback;
286
+ }
287
+ };
288
+ var queues = new Map;
289
+ var locked = (key, work) => {
290
+ const next = (queues.get(key) ?? Promise.resolve()).then(work, work);
291
+ queues.set(key, next.catch(() => {
292
+ return;
293
+ }));
294
+ return next;
295
+ };
296
+ var distance = (a, b) => {
297
+ let row = Array.from({ length: b.length + 1 }, (_, j) => j);
298
+ for (let i = 1;i <= a.length; i++) {
299
+ const next = [i];
300
+ for (let j = 1;j <= b.length; j++)
301
+ next.push(Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)));
302
+ row = next;
303
+ }
304
+ return row[b.length];
305
+ };
306
+
307
+ class Store {
308
+ home;
309
+ constructor(home) {
310
+ this.home = home;
311
+ }
312
+ runsDir = () => join2(this.home, "runs");
313
+ runPath = (run) => join2(this.runsDir(), `${run}.json`);
314
+ refsPath = () => join2(this.home, "refs.json");
315
+ memoryPath = () => join2(this.home, "memory.json");
316
+ ledgerPath = () => join2(this.home, "ledger.jsonl");
317
+ cachePath = (key) => join2(this.home, "cache", `${key.replace(/[^a-z0-9.-]+/gi, "_")}.json`);
318
+ async runHandles() {
319
+ const names = await readdir(this.runsDir()).catch(() => []);
320
+ return names.filter((n) => n.endsWith(".json")).map((n) => n.slice(0, -5));
321
+ }
322
+ readRun = (run) => readJson(this.runPath(run), undefined);
323
+ async writeRun(record) {
324
+ await mkdir(this.runsDir(), { recursive: true });
325
+ await writeAtomic(this.runPath(record.run), JSON.stringify(record, null, 1));
326
+ }
327
+ deleteRun = (run) => rm(this.runPath(run), { force: true });
328
+ async listRuns() {
329
+ const records = await Promise.all((await this.runHandles()).map((run) => this.readRun(run)));
330
+ return records.filter((r) => Boolean(r)).sort((a, b) => a.startedAt - b.startedAt || a.name.localeCompare(b.name) || a.version - b.version);
331
+ }
332
+ async reserveRun(name, record) {
333
+ await mkdir(this.runsDir(), { recursive: true });
334
+ const versions = [];
335
+ for (const handle of await this.runHandles()) {
336
+ const parsed = parseHandle(handle);
337
+ if (parsed?.name === name)
338
+ versions.push(parsed.version);
339
+ }
340
+ for (const file of await readdir(record.dir).catch(() => [])) {
341
+ const parsed = parseHandle(file.replace(/\.[a-z0-9]+$/i, ""));
342
+ if (parsed?.name === name && parsed.letter)
343
+ versions.push(parsed.version);
344
+ }
345
+ for (let version = Math.max(0, ...versions) + 1;; version++) {
346
+ const full = { ...record, run: `${name}-v${version}`, name, version };
347
+ try {
348
+ await writeFile(this.runPath(full.run), JSON.stringify(full, null, 1), { flag: "wx" });
349
+ return full;
350
+ } catch (err) {
351
+ if (err.code !== "EEXIST")
352
+ throw err;
353
+ }
354
+ }
355
+ }
356
+ async nearest(text) {
357
+ const handles = await this.runHandles();
358
+ const asked = parseHandle(text);
359
+ if (asked?.letter && handles.includes(asked.run)) {
360
+ const record = await this.readRun(asked.run);
361
+ if (record?.images.length)
362
+ return record.images.map((i) => i.id);
363
+ return [asked.run];
364
+ }
365
+ const name = asked?.name ?? sanitizeName(text);
366
+ const scored = handles.map((handle) => {
367
+ const parsed = parseHandle(handle);
368
+ const same = parsed?.name === name;
369
+ return { handle, same, version: parsed?.version ?? 0, d: distance(asked?.run ?? text.toLowerCase(), handle) };
370
+ });
371
+ scored.sort((a, b) => Number(b.same) - Number(a.same) || (a.same ? b.version - a.version : a.d - b.d));
372
+ return scored.slice(0, 5).map((s) => s.handle);
373
+ }
374
+ readRefs = async () => {
375
+ const file = await readJson(this.refsPath(), {});
376
+ return { byHash: file.byHash ?? {}, byPath: file.byPath ?? {} };
377
+ };
378
+ async findRef(scope, at) {
379
+ const refs = await this.readRefs();
380
+ const hash = at.hash ?? (at.pathKey ? refs.byPath[at.pathKey]?.hash : undefined);
381
+ return hash ? refs.byHash[`${scope}:${hash}`] : undefined;
382
+ }
383
+ saveRef = (scope, hash, record, pathKey) => locked(this.refsPath(), async () => {
384
+ await mkdir(this.home, { recursive: true });
385
+ const refs = await this.readRefs();
386
+ refs.byHash[`${scope}:${hash}`] = record;
387
+ if (pathKey)
388
+ refs.byPath[pathKey] = { hash };
389
+ await writeAtomic(this.refsPath(), JSON.stringify(refs, null, 1));
390
+ });
391
+ notePath = (pathKey, hash) => locked(this.refsPath(), async () => {
392
+ const refs = await this.readRefs();
393
+ if (refs.byPath[pathKey]?.hash === hash)
394
+ return;
395
+ refs.byPath[pathKey] = { hash };
396
+ await mkdir(this.home, { recursive: true });
397
+ await writeAtomic(this.refsPath(), JSON.stringify(refs, null, 1));
398
+ });
399
+ async readMemory() {
400
+ const list = await readJson(this.memoryPath(), []);
401
+ return Array.isArray(list) ? list : [];
402
+ }
403
+ writeMemory = (list) => locked(this.memoryPath(), async () => {
404
+ await mkdir(this.home, { recursive: true });
405
+ await writeAtomic(this.memoryPath(), JSON.stringify(list, null, 1));
406
+ });
407
+ async readLedger() {
408
+ const text = await readFile(this.ledgerPath(), "utf8").catch(() => "");
409
+ const lines = [];
410
+ for (const line of text.split(`
411
+ `)) {
412
+ if (!line.trim())
413
+ continue;
414
+ try {
415
+ lines.push(JSON.parse(line));
416
+ } catch {}
417
+ }
418
+ return lines;
419
+ }
420
+ recordRun = (line) => locked(this.ledgerPath(), async () => {
421
+ await mkdir(this.home, { recursive: true });
422
+ const lines = await this.readLedger();
423
+ if (!lines.some((l) => l.run === line.run))
424
+ return appendFile(this.ledgerPath(), `${JSON.stringify(line)}
425
+ `);
426
+ await writeAtomic(this.ledgerPath(), lines.map((l) => `${JSON.stringify(l.run === line.run ? line : l)}
427
+ `).join(""));
428
+ });
429
+ setKept = (run, kept) => locked(this.ledgerPath(), async () => {
430
+ const lines = await this.readLedger();
431
+ if (!lines.some((l) => l.run === run))
432
+ return;
433
+ await writeAtomic(this.ledgerPath(), lines.map((l) => `${JSON.stringify(l.run === run ? { ...l, kept } : l)}
434
+ `).join(""));
435
+ });
436
+ async ledgerTotals() {
437
+ const lines = await this.readLedger();
438
+ const images = lines.reduce((n, l) => n + (l.images || 0), 0);
439
+ const kept = lines.reduce((n, l) => n + (l.kept?.length ?? 0), 0);
440
+ return { runs: lines.length, images, kept, rendersPerKept: kept ? Math.round(images / kept * 10) / 10 : null };
441
+ }
442
+ async cached(key, ttlMs, now = Date.now()) {
443
+ const entry = await readJson(this.cachePath(key), undefined);
444
+ return entry && now - entry.at < ttlMs ? entry.data : undefined;
445
+ }
446
+ async cache(key, data, now = Date.now()) {
447
+ await mkdir(join2(this.home, "cache"), { recursive: true });
448
+ await writeAtomic(this.cachePath(key), JSON.stringify({ at: now, data }));
449
+ }
450
+ dropCache = (key) => rm(this.cachePath(key), { force: true });
451
+ }
452
+ var scopeOf = (origin) => createHash("sha256").update(origin).digest("hex").slice(0, 10);
453
+ var hashBytes = (bytes) => createHash("sha256").update(bytes).digest("hex");
454
+
455
+ // images.ts
456
+ var INLINE_BUDGET = 350000;
457
+ var SINGLE_EDGE = 1024;
458
+ var LOOK_EDGE = 1568;
459
+ var GROUND = { r: 230, g: 230, b: 230 };
460
+ var pause = (ms) => new Promise((done) => setTimeout(done, ms));
461
+ async function fetchBytes(fetcher, url, { tries = 5, baseMs = 1000, sleep = pause } = {}) {
462
+ let last;
463
+ for (let i = 0;i < tries; i++) {
464
+ try {
465
+ const res = await fetcher(url, { headers: { "user-agent": "emitter-mcp" }, signal: AbortSignal.timeout(120000) });
466
+ if (!res.ok)
467
+ throw new Error(`${res.status} from ${new URL(url).host}`);
468
+ return Buffer.from(await res.arrayBuffer());
469
+ } catch (err) {
470
+ last = err;
471
+ if (i < tries - 1)
472
+ await sleep(baseMs * 2 ** i);
473
+ }
474
+ }
475
+ throw new Error(`download failed after ${tries} tries: ${last instanceof Error ? last.message : String(last)}`);
476
+ }
477
+ async function download(fetcher, url, dest, retry) {
478
+ const bytes = await fetchBytes(fetcher, url, retry);
479
+ await mkdir2(dirname(dest), { recursive: true });
480
+ await writeAtomic(dest, bytes);
481
+ return bytes;
482
+ }
483
+ var extOf = (url, format) => {
484
+ const tail = /\.([a-z0-9]+)$/i.exec(url.split(/[?#]/)[0])?.[1]?.toLowerCase();
485
+ const ext = tail && ["png", "jpg", "jpeg", "webp"].includes(tail) ? tail : (format ?? "jpeg").toLowerCase();
486
+ return ext === "jpeg" ? "jpg" : ext;
487
+ };
488
+ var MIME = { png: "image/png", jpeg: "image/jpeg", jpg: "image/jpeg", webp: "image/webp", gif: "image/gif", avif: "image/avif", heif: "image/heic", tiff: "image/tiff" };
489
+ async function mimeOf(bytes) {
490
+ const { format } = await sharp(bytes).metadata();
491
+ const mime = format && MIME[format];
492
+ if (!mime)
493
+ throw new Error("not an image this client can read");
494
+ return mime;
495
+ }
496
+ async function sizeOf(bytes) {
497
+ const { width = 0, height = 0 } = await sharp(bytes).metadata();
498
+ return { width, height };
499
+ }
500
+ async function inlineOf(input, maxEdge = SINGLE_EDGE, budget = INLINE_BUDGET) {
501
+ let edge = maxEdge;
502
+ for (;; ) {
503
+ for (const quality of [80, 68, 55]) {
504
+ const { data, info } = await sharp(input).rotate().resize({ width: edge, height: edge, fit: "inside", withoutEnlargement: true }).flatten({ background: GROUND }).jpeg({ quality, mozjpeg: true }).toBuffer({ resolveWithObject: true });
505
+ if (data.byteLength <= budget || edge <= 256)
506
+ return { data: data.toString("base64"), mimeType: "image/jpeg", width: info.width, height: info.height, bytes: data.byteLength };
507
+ }
508
+ edge = Math.round(edge * 0.8);
509
+ }
510
+ }
511
+ var columnsFor = (n) => n <= 3 ? n : n === 4 ? 2 : n <= 9 ? 3 : n <= 16 ? 4 : n <= 25 ? 5 : 6;
512
+ var escapeXml = (s) => s.replace(/[<>&"']/g, (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&apos;" })[c] ?? c);
513
+ var badge = (label, maxWidth) => {
514
+ const size = 15;
515
+ const text = label.length * size * 0.6 + 14 > maxWidth ? `${label.slice(0, Math.max(3, Math.floor((maxWidth - 14) / (size * 0.6)) - 1))}…` : label;
516
+ const width = Math.min(maxWidth, Math.ceil(text.length * size * 0.6 + 14));
517
+ const height = size + 10;
518
+ return Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><rect width="${width}" height="${height}" rx="5" fill="#111" fill-opacity="0.82"/><text x="7" y="${size + 3}" font-family="Menlo, Consolas, monospace" font-size="${size}" fill="#fff">${escapeXml(text)}</text></svg>`);
519
+ };
520
+ async function sheetOf(cells, maxEdge = LOOK_EDGE, columns = columnsFor(cells.length)) {
521
+ if (!cells.length)
522
+ throw new Error("a sheet needs at least one image");
523
+ const gap = 8;
524
+ const rows = Math.ceil(cells.length / columns);
525
+ const first = await sizeOf(cells[0].input);
526
+ const aspect = Math.min(1.6, Math.max(0.5, first.width && first.height ? first.height / first.width : 1));
527
+ let cellW = Math.min(640, Math.floor((maxEdge - gap * (columns + 1)) / columns));
528
+ const tall = (w) => rows * Math.round(w * aspect) + gap * (rows + 1);
529
+ if (tall(cellW) > maxEdge)
530
+ cellW = Math.floor((maxEdge - gap * (rows + 1)) / rows / aspect);
531
+ const cellH = Math.round(cellW * aspect);
532
+ const pictures = await Promise.all(cells.map(async (cell, i) => {
533
+ const input = await sharp(cell.input).rotate().resize({ width: cellW, height: cellH, fit: "contain", background: GROUND }).flatten({ background: GROUND }).png().toBuffer();
534
+ return { input, left: gap + i % columns * (cellW + gap), top: gap + Math.floor(i / columns) * (cellH + gap) };
535
+ }));
536
+ const badges = cells.map((cell, i) => ({ input: badge(cell.label, cellW - 8), left: pictures[i].left + 4, top: pictures[i].top + 4 }));
537
+ return sharp({ create: { width: columns * cellW + gap * (columns + 1), height: rows * cellH + gap * (rows + 1), channels: 3, background: { r: 250, g: 250, b: 250 } } }).composite([...pictures, ...badges]).png().toBuffer();
538
+ }
539
+ async function dataUrlOf(bytes) {
540
+ return `data:${await mimeOf(bytes)};base64,${bytes.toString("base64")}`;
541
+ }
542
+
543
+ // core.ts
544
+ class ToolError extends Error {
545
+ errorCode;
546
+ fix;
547
+ constructor(message, errorCode, fix) {
548
+ super(message);
549
+ this.errorCode = errorCode;
550
+ this.fix = fix;
551
+ }
552
+ }
553
+ var textResult = (value, images = []) => ({
554
+ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }, ...images.map((i) => ({ type: "image", data: i.data, mimeType: i.mimeType }))]
555
+ });
556
+ var openInBackground = (targets) => new Promise((done) => {
557
+ if (process.platform !== "darwin" || !targets.length)
558
+ return done(false);
559
+ const child = spawn("open", ["-g", ...targets], { stdio: "ignore" });
560
+ child.on("error", () => done(false));
561
+ child.on("exit", (code) => done(code === 0));
562
+ });
563
+ var defaultDeps = () => ({
564
+ env: process.env,
565
+ fetch: (input, init) => fetch(input, init),
566
+ open: openInBackground,
567
+ sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
568
+ now: () => Date.now(),
569
+ retryMs: 1000,
570
+ log: (line) => process.stderr.write(`[emitter-mcp] ${line}
571
+ `)
572
+ });
573
+ var contextOf = (deps) => {
574
+ const config = readConfig(deps.env);
575
+ return {
576
+ ...deps,
577
+ config,
578
+ store: new Store(config.home),
579
+ secrets: secretsOf(config),
580
+ scope: scopeOf(`${config.url}
581
+ ${config.token ?? ""}`),
582
+ api: (method, path, options) => apiCall(deps.fetch, config, method, path, options)
583
+ };
584
+ };
585
+ var errorResult = (err, config) => {
586
+ const secrets = config ? secretsOf(config) : [];
587
+ let out;
588
+ if (err instanceof ApiError && err.status === 401) {
589
+ const where = config?.envFile ?? "~/.emitter/env";
590
+ out = {
591
+ error: err.message,
592
+ errorCode: err.errorCode ?? "unauthorized",
593
+ fix: `Ask the user to copy a fresh token from Emitter's Agent panel into ${where} as EMITTER_TOKEN=<token>; it is read on the next call, no restart needed. Never ask them to paste it in chat.`
594
+ };
595
+ } else if (err instanceof ApiError)
596
+ out = { error: err.message, errorCode: err.errorCode ?? (err.status ? `http_${err.status}` : "unreachable") };
597
+ else if (err instanceof ToolError)
598
+ out = { error: err.message, ...err.errorCode && { errorCode: err.errorCode }, ...err.fix && { fix: err.fix } };
599
+ else if (err instanceof ConfigError)
600
+ out = { error: err.message, errorCode: "config" };
601
+ else
602
+ out = { error: err instanceof Error ? err.message : String(err), errorCode: "client_error" };
603
+ return { isError: true, content: [{ type: "text", text: scrub(JSON.stringify(out), secrets) }] };
604
+ };
605
+ var DOC_TTL_MS = 10 * 60000;
606
+ async function briefOf(ctx) {
607
+ const key = `brief-${scopeOf(ctx.config.url)}`;
608
+ const cached = await ctx.store.cached(key, DOC_TTL_MS, ctx.now());
609
+ if (cached)
610
+ return cached;
611
+ const brief = await ctx.api("GET", "/api/agent?brief=1", { direct: false });
612
+ if (!isObject(brief))
613
+ throw new ToolError(`${ctx.config.url}/api/agent?brief=1 did not answer the brief`, "upstream_error");
614
+ await ctx.store.cache(key, brief, ctx.now());
615
+ return brief;
616
+ }
617
+ async function fullDocOf(ctx) {
618
+ const key = `doc-${scopeOf(ctx.config.url)}`;
619
+ const cached = await ctx.store.cached(key, DOC_TTL_MS, ctx.now());
620
+ if (cached)
621
+ return cached;
622
+ const doc = await ctx.api("GET", "/api/agent", { direct: false });
623
+ if (!isObject(doc))
624
+ throw new ToolError(`${ctx.config.url}/api/agent did not answer the reference`, "upstream_error");
625
+ await ctx.store.cache(key, doc, ctx.now());
626
+ return doc;
627
+ }
628
+ var modeOf = (brief) => {
629
+ const line = typeof brief.mode === "string" ? brief.mode.trim().toLowerCase() : isObject(brief.mode) && typeof brief.mode.current === "string" ? brief.mode.current : "";
630
+ return line.startsWith("local") ? "local" : line.startsWith("stateless") ? "stateless" : undefined;
631
+ };
632
+ var tasteOf = (entries) => (Array.isArray(entries) ? entries : []).filter((e) => isObject(e) && e.key === "taste" && typeof e.value === "string" && (typeof e.confidence !== "number" || e.confidence >= 0.5)).map((e) => e.value);
633
+ async function serverMemory(ctx, fresh = false) {
634
+ const key = `memory-${ctx.scope}`;
635
+ if (!fresh) {
636
+ const cached = await ctx.store.cached(key, DOC_TTL_MS, ctx.now());
637
+ if (cached)
638
+ return cached;
639
+ }
640
+ let fact;
641
+ try {
642
+ const listed = await ctx.api("GET", "/api/agent/memory?key=taste", { direct: false });
643
+ fact = { kept: true, taste: tasteOf(isObject(listed) ? listed.entries : undefined) };
644
+ } catch (err) {
645
+ if (!(err instanceof ApiError) || err.status === 401)
646
+ throw err;
647
+ if (err.status === 404)
648
+ fact = { kept: false };
649
+ else
650
+ fact = { kept: modeOf(await briefOf(ctx)) === "local" };
651
+ }
652
+ await ctx.store.cache(key, fact, ctx.now());
653
+ return fact;
654
+ }
655
+ var noteServerMemory = (ctx, kept) => ctx.store.cache(`memory-${ctx.scope}`, { kept }, ctx.now());
656
+ async function standingTaste(ctx, fact) {
657
+ return fact.kept ? fact.taste ?? [] : tasteOf(await ctx.store.readMemory());
658
+ }
659
+ var FAL_HOSTS = /(^|\.)(fal\.media|fal\.ai|fal\.run)$/i;
660
+ var isFalUrl = (url) => {
661
+ try {
662
+ const { protocol, hostname } = new URL(url);
663
+ return protocol === "https:" && FAL_HOSTS.test(hostname);
664
+ } catch {
665
+ return false;
666
+ }
667
+ };
668
+ var isUrl = (s) => /^https?:\/\//i.test(s);
669
+ var isPath = (s) => s.startsWith("/") || s.startsWith("~/");
670
+ var expandPath = (s) => s.startsWith("~/") ? join3(homedir2(), s.slice(2)) : s;
671
+ var MAX_INLINE_BYTES = 1e6;
672
+ var MAX_UPLOAD_BYTES = 4200000;
673
+ var unknownHandle = async (ctx, text, field) => {
674
+ const near = await ctx.store.nearest(text);
675
+ return new ToolError(`${field}: "${text.length > 80 ? `${text.slice(0, 80)}…` : text}" is not a run or image this client knows, an absolute file path, or an https url.${near.length ? ` Nearest: ${near.join(", ")}.` : " There are no runs yet."}`, "unknown_handle");
676
+ };
677
+ async function named(ctx, text, field) {
678
+ const value = text.trim();
679
+ if (value.startsWith("ref_") || value.startsWith("data:"))
680
+ return { kind: "raw", value };
681
+ if (isUrl(value))
682
+ return { kind: "url", url: value };
683
+ if (isPath(value)) {
684
+ const path = expandPath(value);
685
+ if (!await stat(path).then((s) => s.isFile(), () => false))
686
+ throw new ToolError(`${field}: there is no file at ${path}`, "not_found");
687
+ return { kind: "file", path };
688
+ }
689
+ const handle = parseHandle(value);
690
+ const record = handle && await ctx.store.readRun(handle.run);
691
+ if (!handle || !record)
692
+ throw await unknownHandle(ctx, value, field);
693
+ if (!handle.letter) {
694
+ if (!record.images.length)
695
+ throw new ToolError(`${field}: ${record.run} has no finished images${record.status === "queued" || record.status === "running" ? "; it is still rendering, call job first" : ""}`, "not_ready");
696
+ return { kind: "images", record, images: record.images, whole: true };
697
+ }
698
+ const image = record.images.find((i) => i.id === value);
699
+ if (!image)
700
+ throw await unknownHandle(ctx, value, field);
701
+ return { kind: "images", record, images: [image], whole: false };
702
+ }
703
+ async function runOf(ctx, text, field = "run") {
704
+ const handle = parseHandle(text.trim());
705
+ const record = handle && await ctx.store.readRun(handle.run);
706
+ if (!record)
707
+ throw await unknownHandle(ctx, text, field);
708
+ return record;
709
+ }
710
+ var pathKeyOf = async (path) => {
711
+ const s = await stat(path);
712
+ return `${path}|${s.size}|${Math.round(s.mtimeMs)}`;
713
+ };
714
+ var fitUpload = async (bytes) => {
715
+ if (bytes.byteLength <= MAX_UPLOAD_BYTES)
716
+ return { bytes, type: await mimeOf(bytes) };
717
+ const shrunk = await sharp2(bytes).rotate().resize({ width: 2048, height: 2048, fit: "inside", withoutEnlargement: true }).flatten({ background: "#ffffff" }).jpeg({ quality: 90 }).toBuffer();
718
+ return { bytes: shrunk, type: "image/jpeg" };
719
+ };
720
+ async function uploadReference(ctx, source, field) {
721
+ const pathKey = "path" in source ? await pathKeyOf(source.path) : `url|${source.url}`;
722
+ const known = await ctx.store.findRef(ctx.scope, { pathKey });
723
+ if (known)
724
+ return known.id;
725
+ const bytes = "path" in source ? await readFile2(source.path) : await fetchBytes(ctx.fetch, source.url, { baseMs: ctx.retryMs, sleep: ctx.sleep });
726
+ const hash = hashBytes(bytes);
727
+ const same = await ctx.store.findRef(ctx.scope, { hash });
728
+ if (same) {
729
+ await ctx.store.notePath(pathKey, hash);
730
+ return same.id;
731
+ }
732
+ const name = "path" in source ? basename(source.path) : decodeURIComponent(new URL(source.url).pathname.split("/").pop() || "reference");
733
+ let fitted;
734
+ try {
735
+ fitted = await fitUpload(bytes);
736
+ } catch {
737
+ throw new ToolError(`${field}: ${name} is not an image this client can read`, "bad_request");
738
+ }
739
+ const answer = await ctx.api("POST", `/api/agent/references?name=${encodeURIComponent(name)}`, { raw: fitted.bytes, contentType: fitted.type });
740
+ const ref = isObject(answer) && Array.isArray(answer.references) && isObject(answer.references[0]) ? answer.references[0] : undefined;
741
+ if (!ref || typeof ref.id !== "string")
742
+ throw new ToolError(`${field}: the upload of ${name} answered no reference id`, "upstream_error");
743
+ await ctx.store.saveRef(ctx.scope, hash, { id: ref.id, name, ...typeof ref.url === "string" && { url: ref.url }, ...typeof ref.width === "number" && { width: ref.width }, ...typeof ref.height === "number" && { height: ref.height } }, pathKey);
744
+ return ref.id;
745
+ }
746
+ async function referencesOf(ctx, text, field) {
747
+ const it = await named(ctx, text, field);
748
+ if (it.kind === "raw")
749
+ return [it.value];
750
+ if (it.kind === "images")
751
+ return it.images.map((i) => i.url);
752
+ if (it.kind === "url")
753
+ return isFalUrl(it.url) ? [it.url] : [await uploadReference(ctx, { url: it.url }, field)];
754
+ return [await uploadReference(ctx, { path: it.path }, field)];
755
+ }
756
+ async function exactImageOf(ctx, text, field) {
757
+ const it = await named(ctx, text, field);
758
+ if (it.kind === "raw")
759
+ return it.value;
760
+ if (it.kind === "images") {
761
+ if (it.images.length > 1)
762
+ throw new ToolError(`${field} takes one image and ${it.record.run} has ${it.images.length}: name one of ${it.images.map((i) => i.id).join(", ")}`, "bad_request");
763
+ return it.images[0].url;
764
+ }
765
+ if (it.kind === "url" && isFalUrl(it.url))
766
+ return it.url;
767
+ const bytes = it.kind === "url" ? await fetchBytes(ctx.fetch, it.url, { baseMs: ctx.retryMs, sleep: ctx.sleep }) : await readFile2(it.path);
768
+ const name = it.kind === "url" ? it.url : basename(it.path);
769
+ if (bytes.byteLength > MAX_INLINE_BYTES) {
770
+ throw new ToolError(`${field}: ${name} is ${(bytes.byteLength / 1e6).toFixed(1)} MB, over the ${MAX_INLINE_BYTES / 1e6} MB an image may be when sent inline. This image is read at full size with its alpha, so it cannot go through the reference upload, which shrinks and flattens it.`, "payload_too_large", "Use a smaller file (under 1 MB), or name a run image by its handle.");
771
+ }
772
+ try {
773
+ return await dataUrlOf(bytes);
774
+ } catch {
775
+ throw new ToolError(`${field}: ${name} is not an image this client can read`, "bad_request");
776
+ }
777
+ }
778
+ async function oneReferenceOf(ctx, text, field) {
779
+ const all = await referencesOf(ctx, text, field);
780
+ if (all.length !== 1)
781
+ throw new ToolError(`${field} takes one image, and "${text}" names ${all.length}: add the image's letter`, "bad_request");
782
+ return all[0];
783
+ }
784
+ var each = async (list, field, work) => {
785
+ if (!Array.isArray(list))
786
+ return;
787
+ for (const [i, item] of list.entries())
788
+ if (isObject(item))
789
+ await work(item, `${field}[${i}]`);
790
+ };
791
+ async function resolveImages(ctx, body) {
792
+ const out = { ...body };
793
+ if (Array.isArray(body.references)) {
794
+ const references = [];
795
+ for (const [i, ref] of body.references.entries()) {
796
+ if (typeof ref === "string")
797
+ references.push(...await referencesOf(ctx, ref, `references[${i}]`));
798
+ else
799
+ references.push(ref);
800
+ }
801
+ out.references = references;
802
+ }
803
+ if (isObject(body.edit)) {
804
+ const edit = { ...body.edit };
805
+ if (typeof edit.image === "string")
806
+ edit.image = await exactImageOf(ctx, edit.image, "edit.image");
807
+ if (typeof edit.mask === "string")
808
+ edit.mask = await exactImageOf(ctx, edit.mask, "edit.mask");
809
+ out.edit = edit;
810
+ }
811
+ if (Array.isArray(body.overlays)) {
812
+ const overlays = body.overlays.map((o) => isObject(o) ? { ...o } : o);
813
+ await each(overlays, "overlays", async (o, field) => {
814
+ if (typeof o.ref === "string")
815
+ o.ref = await exactImageOf(ctx, o.ref, `${field}.ref`);
816
+ });
817
+ out.overlays = overlays;
818
+ }
819
+ if (Array.isArray(body.colorize)) {
820
+ const colorize = body.colorize.map((c) => isObject(c) ? { ...c } : c);
821
+ await each(colorize, "colorize", async (c, field) => {
822
+ if (typeof c.mask === "string")
823
+ c.mask = await exactImageOf(ctx, c.mask, `${field}.mask`);
824
+ });
825
+ out.colorize = colorize;
826
+ }
827
+ if (isObject(body.require) && typeof body.require.logo === "string")
828
+ out.require = { ...body.require, logo: await oneReferenceOf(ctx, body.require.logo, "require.logo") };
829
+ return out;
830
+ }
831
+ async function picturesOf(ctx, text, field) {
832
+ const it = await named(ctx, text, field);
833
+ if (it.kind === "raw")
834
+ throw new ToolError(`${field}: name an image by its handle, a file path, or a url`, "bad_request");
835
+ if (it.kind === "images")
836
+ return it.images.map((image) => ({ label: image.id, file: image.file, url: image.url, image, record: it.record }));
837
+ if (it.kind === "file")
838
+ return [{ label: basename(it.path), file: it.path }];
839
+ return [{ label: decodeURIComponent(new URL(it.url).pathname.split("/").pop() || it.url), url: it.url }];
840
+ }
841
+ async function bytesOf(ctx, picture) {
842
+ if (picture.file) {
843
+ const bytes = await readFile2(picture.file).catch(() => {
844
+ return;
845
+ });
846
+ if (bytes)
847
+ return bytes;
848
+ }
849
+ if (picture.url)
850
+ return fetchBytes(ctx.fetch, picture.url, { baseMs: ctx.retryMs, sleep: ctx.sleep });
851
+ throw new ToolError(`${picture.label}: the file is gone and there is no url to fetch it from`, "not_found");
852
+ }
853
+
854
+ // tools.ts
855
+ import { stat as stat2 } from "node:fs/promises";
856
+ import { gzipSync } from "node:zlib";
857
+ import { z } from "zod";
858
+
859
+ // ../lib/share-id.ts
860
+ var sharedId = (payload) => {
861
+ let h1 = 3735928559;
862
+ let h2 = 1103547991;
863
+ for (let i = 0;i < payload.length; i++) {
864
+ const ch = payload.charCodeAt(i);
865
+ h1 = Math.imul(h1 ^ ch, 2654435761);
866
+ h2 = Math.imul(h2 ^ ch, 1597334677);
867
+ }
868
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
869
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
870
+ return `shared-${(4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)}`;
871
+ };
872
+
873
+ // guide.ts
874
+ var TOPIC_BUDGET = 24000;
875
+ var CLIENT_TOPIC = "client";
876
+ var clientGuide = (ctx) => [
877
+ "This client keeps what a render needs on this machine, so you pass short names and get short answers with the picture inline.",
878
+ `- Handles: a run is <name>-v<N>. You give name (one or two lowercase words, like "sword" or "badge front"); the client picks N. Its images are <run>-a, <run>-b, … in slot order, saved as ${ctx.config.images}/<run>-<letter>.<ext>.`,
879
+ "- Wherever an image is wanted (references, edit.image, overlays[].ref, require.logo, look, feedback, show) pass an image handle (sword-v2-a), a run handle (all its images), an absolute file path, or an https url. A file is uploaded once and remembered.",
880
+ "- You never send or see state, job handles, ref_ ids, auth, or the memory list. Where the server text below mentions them, the client does that part.",
881
+ `- A new direction: generate with from: "<run>", which keeps that run's settings and references. A small change: generate with edit: { image: "<image handle>", region: "<the part>" } and count 1.`,
882
+ "- Tools: guide (this page, or guide { topic } for one section of the reference), generate (one run; dryRun: true first when a call matters, it is free), batch (up to 16 runs in one call), job (keep waiting on a run that is still rendering, or cancel it), look (images inline, without reading files), feedback (said: the user's words; kept: the images they kept), context (recent runs, keeps, renders per kept image, the standing taste), show (open results in Emitter for the user), call (any other route of the API).",
883
+ "- flags on an image list only what the server measured as wrong: clipped edges, a halo, no alpha on a cutout. No flags means nothing was measured wrong, not that the picture is right: look at it.",
884
+ "- Memory and the ledger are kept for you. Write toward taste when a result carries it. Read context before rendering more: renders per kept image is the figure to keep low.",
885
+ ...ctx.config.direct ? [
886
+ `- This machine renders directly: leave model out (${DIRECT_MODEL_LABEL}). Pass fal: true only when the user asks for a render on fal. A direct render holds the call until it is done, and nothing is matted for it, so use cutout: true (the model's own alpha) rather than /cut; dimensions: "2048x2048" gives more pixels than a size preset.`
887
+ ] : []
888
+ ].join(`
889
+ `);
890
+ var sizeOf2 = (value) => typeof value === "string" ? value.length : (JSON.stringify(value) ?? "").length;
891
+ var short = (n) => n >= 1000 ? `${(n / 1000).toFixed(n >= 1e4 ? 0 : 1)}k` : String(n);
892
+ var scalar = (v) => v === null || typeof v !== "object";
893
+ var inlineRow = (item) => {
894
+ const entries = Object.entries(item);
895
+ if (!entries.every(([, v]) => scalar(v) || Array.isArray(v) && v.every(scalar)))
896
+ return;
897
+ return entries.filter(([, v]) => !(Array.isArray(v) && !v.length)).map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(", ") : String(v)}`).join("; ");
898
+ };
899
+ var render = (value, indent = "") => {
900
+ if (typeof value === "string")
901
+ return `${indent}${value}`;
902
+ if (value === null || typeof value !== "object")
903
+ return `${indent}${String(value)}`;
904
+ if (Array.isArray(value))
905
+ return value.map((item) => isObject(item) || Array.isArray(item) ? `${indent}- ${isObject(item) && inlineRow(item) || JSON.stringify(item)}` : `${indent}- ${String(item)}`).join(`
906
+ `);
907
+ return Object.entries(value).map(([key, v]) => v !== null && typeof v === "object" ? `${indent}${key}:
908
+ ${render(v, `${indent} `)}` : `${indent}${key}: ${String(v)}`).join(`
909
+ `);
910
+ };
911
+ var BRIEF_DROPS = ["name", "brief", "full", "auth", "ledger", "jobs", "cancel", "answer", "errors", "ui", "topics"];
912
+ var BODY_DROPS = ["state", "job", "sessionId", "save", "name", "key", "webhook", "direct", "label", "stream", "async", "memory", "contact", "dryRun"];
913
+ var FLOW_DROPS = [/^POST \/api\/agent\/references/, /^POST \/api\/agent\/jobs/, /^POST \/api\/agent\/cancel/, /^GET \/api\/agent\/context/, /^done → contact\.url/, /^memory /, /^continuous /];
914
+ var trimmedBrief = (brief) => {
915
+ const out = {};
916
+ for (const [key, value] of Object.entries(brief)) {
917
+ if (BRIEF_DROPS.includes(key))
918
+ continue;
919
+ if (key === "flow" && Array.isArray(value))
920
+ out.flow = value.filter((line) => typeof line !== "string" || !FLOW_DROPS.some((drop) => drop.test(line)));
921
+ else if (key === "body" && isObject(value))
922
+ out.body = Object.fromEntries(Object.entries(value).filter(([k]) => !BODY_DROPS.includes(k)));
923
+ else
924
+ out[key] = value;
925
+ }
926
+ return out;
927
+ };
928
+ var topicAware = (brief) => isObject(brief.topics) || Array.isArray(brief.topics);
929
+ var listedTopics = (topics) => {
930
+ if (Array.isArray(topics))
931
+ return topics.filter((t) => typeof t === "string").map((name) => ({ name }));
932
+ if (!isObject(topics))
933
+ return [];
934
+ return Object.entries(topics).map(([name, line]) => {
935
+ if (!Array.isArray(line))
936
+ return { name };
937
+ const [chars, covers, parts] = line;
938
+ return {
939
+ name,
940
+ ...typeof chars === "number" && { chars },
941
+ ...typeof covers === "string" && { covers },
942
+ ...isObject(parts) && { parts: Object.fromEntries(Object.entries(parts).filter((p) => typeof p[1] === "number")) }
943
+ };
944
+ });
945
+ };
946
+ var topicsOfDoc = (doc) => Object.entries(doc).map(([name, section]) => {
947
+ const chars = sizeOf2(section);
948
+ const parted = isObject(section) && (name === "endpoints" || chars > 12000);
949
+ return { name, chars, ...parted && { parts: Object.fromEntries(Object.entries(section).map(([part, value]) => [part, sizeOf2(value)])) } };
950
+ });
951
+ var topicText = (topics) => [
952
+ `- ${CLIENT_TOPIC}: handles and the tools, as above`,
953
+ ...topics.map(({ name, chars, covers, parts }) => {
954
+ const head = `- ${name}${covers ? `: ${covers}` : ""}${chars !== undefined ? ` (${short(chars)})` : ""}`;
955
+ return parts ? `${head}; parts: ${Object.entries(parts).map(([part, size]) => `${name}.${part} ${short(size)}`).join(", ")}` : head;
956
+ })
957
+ ].join(`
958
+ `);
959
+ var sectionOf = (doc, name) => {
960
+ const segments = name.split(".");
961
+ let node = doc;
962
+ let reached = "";
963
+ for (let i = 0;i < segments.length; ) {
964
+ if (!isObject(node))
965
+ throw new ToolError(`Unknown topic "${name}": "${reached}" has no named parts, so ask for it whole`, "bad_request");
966
+ let key;
967
+ for (let n = 1;i + n <= segments.length && key === undefined; n++) {
968
+ const candidate = segments.slice(i, i + n).join(".");
969
+ if (Object.hasOwn(node, candidate))
970
+ key = candidate;
971
+ }
972
+ if (key === undefined) {
973
+ const names = Object.keys(node).join(", ");
974
+ throw new ToolError(reached ? `Unknown topic "${name}": "${reached}" has no "${segments.slice(i).join(".")}". Under ${reached}: ${names}` : `Unknown topic "${name}". Topics: ${CLIENT_TOPIC}, ${names}. A dotted name reaches into one (endpoints.generate)`, "bad_request");
975
+ }
976
+ node = node[key];
977
+ reached = reached ? `${reached}.${key}` : key;
978
+ i += key.split(".").length;
979
+ }
980
+ return node;
981
+ };
982
+ var sectionText = (name, section) => {
983
+ const chars = sizeOf2(section);
984
+ if (chars <= TOPIC_BUDGET)
985
+ return `# ${name}
986
+ ${render(section)}`;
987
+ if (isObject(section)) {
988
+ return `# ${name}
989
+ ${short(chars)} characters, too long to read whole. Ask for a part:
990
+ ${Object.entries(section).map(([part, value]) => `- ${name}.${part} (${short(sizeOf2(value))})`).join(`
991
+ `)}`;
992
+ }
993
+ return `# ${name}
994
+ ${render(section).slice(0, TOPIC_BUDGET)}
995
+ … cut at ${short(TOPIC_BUDGET)} of ${short(chars)} characters`;
996
+ };
997
+ async function guide(ctx, args) {
998
+ const brief = await briefOf(ctx);
999
+ const asked = (args.topic ?? "").split(",").map((t) => t.trim()).filter(Boolean);
1000
+ if (!asked.length) {
1001
+ const topics = topicAware(brief) ? listedTopics(brief.topics) : topicsOfDoc(await fullDocOf(ctx));
1002
+ return textResult([
1003
+ "# Emitter",
1004
+ clientGuide(ctx),
1005
+ "",
1006
+ `# From the server (${ctx.config.url})`,
1007
+ render(trimmedBrief(brief)),
1008
+ "",
1009
+ '# Topics: guide { topic: "<name>" }, several separated by commas; a dotted name reaches into one',
1010
+ topicText(topics)
1011
+ ].join(`
1012
+ `));
1013
+ }
1014
+ const fromServer = asked.filter((t) => t !== CLIENT_TOPIC);
1015
+ const sections = new Map;
1016
+ if (fromServer.length && topicAware(brief)) {
1017
+ const answer = await ctx.api("GET", `/api/agent?topic=${fromServer.map(encodeURIComponent).join(",")}`, { direct: false });
1018
+ if (!isObject(answer))
1019
+ throw new ToolError("the server answered no topics", "upstream_error");
1020
+ for (const name of fromServer)
1021
+ sections.set(name, answer[name]);
1022
+ } else if (fromServer.length) {
1023
+ const doc = await fullDocOf(ctx);
1024
+ for (const name of fromServer)
1025
+ sections.set(name, sectionOf(doc, name));
1026
+ }
1027
+ return textResult(asked.map((name) => name === CLIENT_TOPIC ? `# ${CLIENT_TOPIC}
1028
+ ${clientGuide(ctx)}` : sectionText(name, sections.get(name))).join(`
1029
+
1030
+ `));
1031
+ }
1032
+
1033
+ // runs.ts
1034
+ import { readFile as readFile3 } from "node:fs/promises";
1035
+ import { homedir as homedir3 } from "node:os";
1036
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join4 } from "node:path";
1037
+ var BODY_KEYS = ["prompt", "references", "model", "size", "dimensions", "quality", "count", "format", "cutout", "style", "keep", "avoid", "edit", "require", "project"];
1038
+ var CLIENT_OWNED = {
1039
+ state: "continue a run with from",
1040
+ job: "continue a run with from",
1041
+ sessionId: "continue a run with from",
1042
+ save: "images are always written to disk; dir picks where",
1043
+ name: "name is the run name, at the top level",
1044
+ key: "a resend never renders twice as it is",
1045
+ webhook: "the client polls for you",
1046
+ direct: "pass fal: true to render on fal",
1047
+ dryRun: "pass dryRun at the top level",
1048
+ label: "the run handle is the label"
1049
+ };
1050
+ var DEFAULT_WAIT = 120;
1051
+ var MAX_WAIT = 280;
1052
+ var POLL_HOLD = 25;
1053
+ var RENDER_TIMEOUT_MS = 330000;
1054
+ var CONTROL_KEYS = ["name", "from", "options", "dryRun", "fal", "wait", "dir", "jobs", "sheet"];
1055
+ var bodyOf = (args, field) => {
1056
+ const options = args.options ?? {};
1057
+ if (!isObject(options))
1058
+ throw new ToolError(`${field}options must be an object of API keys`, "bad_request");
1059
+ for (const key of Object.keys(options))
1060
+ if (key in CLIENT_OWNED)
1061
+ throw new ToolError(`${field}options.${key} is set by this client: ${CLIENT_OWNED[key]}`, "bad_request");
1062
+ const body = {};
1063
+ for (const [key, value] of Object.entries(args)) {
1064
+ if (CONTROL_KEYS.includes(key) || BODY_KEYS.includes(key) || value === undefined)
1065
+ continue;
1066
+ if (key in CLIENT_OWNED)
1067
+ throw new ToolError(`${field}${key} is set by this client: ${CLIENT_OWNED[key]}`, "bad_request");
1068
+ body[key] = value;
1069
+ }
1070
+ Object.assign(body, options);
1071
+ for (const key of BODY_KEYS)
1072
+ if (args[key] !== undefined)
1073
+ body[key] = args[key];
1074
+ return body;
1075
+ };
1076
+ var waitOf = (wait) => {
1077
+ if (wait === undefined || wait === null)
1078
+ return DEFAULT_WAIT;
1079
+ if (typeof wait !== "number" || !Number.isFinite(wait) || wait < 0)
1080
+ throw new ToolError(`wait is seconds, 0 to ${MAX_WAIT}`, "bad_request");
1081
+ return Math.min(MAX_WAIT, wait);
1082
+ };
1083
+ var dirOf = (ctx, dir) => {
1084
+ if (!dir)
1085
+ return ctx.config.images;
1086
+ const path = dir.startsWith("~/") ? join4(homedir3(), dir.slice(2)) : dir;
1087
+ if (!isAbsolute2(path))
1088
+ throw new ToolError("dir must be an absolute path", "bad_request");
1089
+ return path;
1090
+ };
1091
+ var strings = (list) => Array.isArray(list) ? list.filter((x) => typeof x === "string") : [];
1092
+ var modelsOf = (body, state) => {
1093
+ const named2 = [
1094
+ ...typeof body.model === "string" ? [body.model] : [],
1095
+ ...strings(body.models),
1096
+ ...Array.isArray(body.slots) ? body.slots.flatMap((s) => isObject(s) && typeof s.model === "string" ? [s.model] : []) : []
1097
+ ];
1098
+ if (named2.length || !state)
1099
+ return named2;
1100
+ const config = isObject(state.config) ? state.config : {};
1101
+ const base = config.modelId === "custom" ? config.customEndpoint : config.modelId;
1102
+ const slots = Array.isArray(state.overrides) ? state.overrides.flatMap((o) => isObject(o) && typeof o.endpoint === "string" && o.endpoint ? [o.endpoint] : []) : [];
1103
+ return [...typeof base === "string" && base ? [base] : [], ...slots];
1104
+ };
1105
+ var routeOf = (ctx, models, fal) => {
1106
+ if (!ctx.config.direct || fal)
1107
+ return "fal";
1108
+ const others = [...new Set(models.filter((m) => !isDirectModel(m)))];
1109
+ if (!others.length)
1110
+ return "direct";
1111
+ if (ctx.config.directOnly) {
1112
+ throw new ToolError(`This machine is set to render directly, and ${others.join(", ")} would render on fal instead. Only ${DIRECT_MODEL_LABEL} renders directly.`, "direct_only", `Use ${DIRECT_MODEL_LABEL} (or leave model out), or pass fal: true, only when the user asks for a render on fal.`);
1113
+ }
1114
+ return "fal";
1115
+ };
1116
+ var routed = (body, route, fal) => ({
1117
+ ...body,
1118
+ ...route === "direct" && { direct: true, async: false },
1119
+ ...route === "fal" && fal && { direct: false }
1120
+ });
1121
+ var withMemory = async (ctx, body) => {
1122
+ if (body.memory !== undefined || (await serverMemory(ctx)).kept)
1123
+ return body;
1124
+ const list = await ctx.store.readMemory();
1125
+ return list.length ? { ...body, memory: list } : body;
1126
+ };
1127
+ var shorten = (value) => {
1128
+ if (typeof value === "string")
1129
+ return value.startsWith("data:") ? `${value.slice(0, value.indexOf(",") > 0 ? Math.min(value.indexOf(","), 40) : 20)},<${value.length} characters>` : value;
1130
+ if (Array.isArray(value))
1131
+ return value.map(shorten);
1132
+ if (isObject(value))
1133
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, shorten(v)]));
1134
+ return value;
1135
+ };
1136
+ var kept = (body) => {
1137
+ const { memory: _memory, state: _state, key: _key, jobs: _jobs, ...rest } = body;
1138
+ return shorten(rest);
1139
+ };
1140
+ var statusOf = (answer) => typeof answer.status === "string" ? answer.status : "done";
1141
+ var slotsOf = (answer) => isObject(answer.run) && Array.isArray(answer.run.slots) ? answer.run.slots.filter(isObject) : [];
1142
+ var flagsOf = (slot) => {
1143
+ const flags = [];
1144
+ const checks = isObject(slot.checks) ? slot.checks : undefined;
1145
+ const settings = isObject(slot.settings) ? slot.settings : {};
1146
+ if (checks) {
1147
+ const alpha = isObject(checks.alpha) ? checks.alpha : {};
1148
+ if (settings.cutout === true && alpha.present === false)
1149
+ flags.push("no alpha");
1150
+ const clipped = strings(checks.clipped);
1151
+ if (clipped.length)
1152
+ flags.push(`clipped ${clipped.join("/")}`);
1153
+ if (typeof checks.halo === "number" && checks.halo > 0.5)
1154
+ flags.push(`halo ${Math.round(checks.halo * 100)}%`);
1155
+ }
1156
+ if (slot.cutoutError)
1157
+ flags.push("cutout failed");
1158
+ if (slot.finishError)
1159
+ flags.push("finish failed");
1160
+ if (slot.postError)
1161
+ flags.push("post step failed");
1162
+ if (isObject(slot.colorMatch) && slot.colorMatch.warning)
1163
+ flags.push("color clipped");
1164
+ const verdict = isObject(slot.accept) ? slot.accept.verdict : undefined;
1165
+ if (verdict === "fail" || verdict === "unsure")
1166
+ flags.push(`require ${verdict}`);
1167
+ return flags;
1168
+ };
1169
+ var round = (n, places = 1) => Math.round(n * 10 ** places) / 10 ** places;
1170
+ var brief = (text, max = 220) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
1171
+ var warningsOf = (list, max = 5) => {
1172
+ const all = strings(list);
1173
+ if (!all.length)
1174
+ return;
1175
+ return [...all.slice(0, max).map((w) => brief(w)), ...all.length > max ? [`and ${all.length - max} more`] : []];
1176
+ };
1177
+ var SAID_ELSEWHERE = [/^slot \d+: the cutout has no transparent pixels/, /^slot \d+: visible pixels touch the /, /^slot \d+: \d+% of the cutout's edge is near white/, /^Rendered directly/];
1178
+ var absorb = async (ctx, record, answer) => {
1179
+ record.status = statusOf(answer) === "running" ? "running" : "queued";
1180
+ if (typeof answer.job === "string")
1181
+ record.job = answer.job;
1182
+ if (isObject(answer.state))
1183
+ record.state = answer.state;
1184
+ if (isObject(answer.run) && typeof answer.run.id === "string")
1185
+ record.serverRun = answer.run.id;
1186
+ if (isObject(answer.session) && typeof answer.session.id === "string")
1187
+ record.sessionId = answer.session.id;
1188
+ await ctx.store.writeRun(record);
1189
+ };
1190
+ async function finish(ctx, record, answer) {
1191
+ const before = new Map(record.images.map((i) => [i.id, i]));
1192
+ const bytes = new Map;
1193
+ const failed = [];
1194
+ const warnings = strings(answer.warnings).filter((w) => !SAID_ELSEWHERE.some((said) => said.test(w)));
1195
+ let tokens = 0;
1196
+ const images = await Promise.all(slotsOf(answer).map(async (slot, i) => {
1197
+ const index = typeof slot.index === "number" ? slot.index : i;
1198
+ const letter = letterOf(index);
1199
+ const image = isObject(slot.image) ? slot.image : undefined;
1200
+ if (!image || typeof image.url !== "string") {
1201
+ failed.push({ slot: letter, error: brief(typeof slot.error === "string" ? slot.error : `no image (${String(slot.status ?? "unknown")})`) });
1202
+ return;
1203
+ }
1204
+ if (isObject(slot.tokens) && typeof slot.tokens.total === "number")
1205
+ tokens += slot.tokens.total;
1206
+ const id = `${record.run}-${letter}`;
1207
+ const settings = isObject(slot.settings) ? slot.settings : {};
1208
+ const checks = isObject(slot.checks) ? slot.checks : {};
1209
+ const file = join4(record.dir, `${id}.${extOf(image.url, typeof settings.format === "string" ? settings.format : undefined)}`);
1210
+ let written;
1211
+ try {
1212
+ bytes.set(id, await download(ctx.fetch, image.url, file, { baseMs: ctx.retryMs, sleep: ctx.sleep }));
1213
+ written = file;
1214
+ } catch (err) {
1215
+ warnings.push(`${id}: ${err instanceof Error ? err.message : String(err)}; the image is still at its url, and look fetches it again`);
1216
+ }
1217
+ const width = typeof image.width === "number" ? image.width : typeof checks.width === "number" ? checks.width : undefined;
1218
+ const height = typeof image.height === "number" ? image.height : typeof checks.height === "number" ? checks.height : undefined;
1219
+ const flags = flagsOf(slot);
1220
+ if (record.route === "direct" && slot.provider === "fal")
1221
+ flags.push("rendered on fal");
1222
+ return {
1223
+ id,
1224
+ slot: index,
1225
+ label: typeof slot.label === "string" ? slot.label : String(index + 1),
1226
+ ...typeof slot.model === "string" && { model: slot.model },
1227
+ url: image.url,
1228
+ ...written && { file: written },
1229
+ ...width && { width },
1230
+ ...height && { height },
1231
+ ...before.get(id)?.kept && { kept: true },
1232
+ ...flags.length && { flags }
1233
+ };
1234
+ }));
1235
+ record.images = images.filter((i) => Boolean(i));
1236
+ record.status = record.images.length ? "done" : "failed";
1237
+ delete record.job;
1238
+ if (failed.length)
1239
+ record.failed = failed;
1240
+ else
1241
+ delete record.failed;
1242
+ if (isObject(answer.state))
1243
+ record.state = answer.state;
1244
+ if (isObject(answer.run) && typeof answer.run.id === "string")
1245
+ record.serverRun = answer.run.id;
1246
+ if (isObject(answer.session) && typeof answer.session.id === "string")
1247
+ record.sessionId = answer.session.id;
1248
+ const cost = isObject(answer.cost) && typeof answer.cost.total === "number" ? answer.cost.total : undefined;
1249
+ if (cost !== undefined)
1250
+ record.cost = round(cost, 4);
1251
+ if (tokens)
1252
+ record.tokens = tokens;
1253
+ if (warnings.length)
1254
+ record.warnings = warnings;
1255
+ if (isObject(answer.contact) && typeof answer.contact.url === "string")
1256
+ record.contact = answer.contact.url;
1257
+ record.seconds = round((ctx.now() - record.startedAt) / 1000);
1258
+ await ctx.store.writeRun(record);
1259
+ await ctx.store.recordRun({
1260
+ at: new Date(ctx.now()).toISOString(),
1261
+ run: record.run,
1262
+ ...record.project && { project: record.project },
1263
+ model: [...new Set(record.images.map((i) => i.model).filter(Boolean))].join(", "),
1264
+ images: record.images.length,
1265
+ files: record.images.flatMap((i) => i.file ? [i.file] : []),
1266
+ urls: record.images.map((i) => i.url),
1267
+ ...record.cost !== undefined && { cost: record.cost },
1268
+ kept: record.images.filter((i) => i.kept).map((i) => i.id)
1269
+ });
1270
+ const filled = isObject(answer.memory) && isObject(answer.memory.filled) ? answer.memory.filled : undefined;
1271
+ return { record, bytes, ...typeof filled?.taste === "string" && { taste: filled.taste } };
1272
+ }
1273
+ var isGone = (err) => err instanceof ApiError && (err.status === 0 || err.status >= 500);
1274
+ var FAILED_FAST_MS = 5000;
1275
+ async function submit(ctx, path, body, route, key) {
1276
+ const started = ctx.now();
1277
+ for (let attempt = 0;; attempt++) {
1278
+ const sent = ctx.now();
1279
+ try {
1280
+ const answer = await ctx.api("POST", path, { body: { ...body, key }, direct: route === "direct", timeoutMs: RENDER_TIMEOUT_MS });
1281
+ if (!isObject(answer))
1282
+ throw new ToolError(`${path} answered no run`, "upstream_error");
1283
+ return answer;
1284
+ } catch (err) {
1285
+ if (!(err instanceof ApiError))
1286
+ throw err;
1287
+ if (err.status === 0 && attempt < 2 && ctx.now() - sent < FAILED_FAST_MS)
1288
+ await ctx.sleep(2000 * (attempt + 1));
1289
+ else if (err.status === 409 && attempt > 0 && ctx.now() - started < RENDER_TIMEOUT_MS)
1290
+ await ctx.sleep(5000);
1291
+ else if (err.status === 0 && ctx.now() - sent >= FAILED_FAST_MS) {
1292
+ throw new ToolError(`${err.message}. The connection was lost ${Math.round((ctx.now() - sent) / 1000)}s into the call, so the render may have gone through without its answer reaching this machine; nothing was recorded for it.`, "unreachable", "Check the server before rendering again, so the same image is not paid for twice.");
1293
+ } else
1294
+ throw err;
1295
+ }
1296
+ }
1297
+ }
1298
+ async function poll(ctx, body, route, hold) {
1299
+ for (let attempt = 0;; attempt++) {
1300
+ try {
1301
+ const answer = await ctx.api("POST", "/api/agent/jobs", { body: { ...body, wait: hold }, direct: route === "direct", timeoutMs: (hold + 40) * 1000 });
1302
+ if (!isObject(answer))
1303
+ throw new ToolError("the poll answered nothing", "upstream_error");
1304
+ return answer;
1305
+ } catch (err) {
1306
+ if (!isGone(err) || attempt >= 2)
1307
+ throw err;
1308
+ await ctx.sleep(2000 * (attempt + 1));
1309
+ }
1310
+ }
1311
+ }
1312
+ var holdFor = (ctx, deadline) => Math.max(0, Math.min(POLL_HOLD, Math.ceil((deadline - ctx.now()) / 1000)));
1313
+ async function follow(ctx, record, first, deadline) {
1314
+ let answer = first;
1315
+ for (;; ) {
1316
+ if (statusOf(answer) === "done")
1317
+ return finish(ctx, record, answer);
1318
+ await absorb(ctx, record, answer);
1319
+ if (!record.job)
1320
+ throw new ToolError(`${record.run}: the server answered "${statusOf(answer)}" without a job to poll`, "upstream_error");
1321
+ if (ctx.now() >= deadline)
1322
+ return;
1323
+ answer = await poll(ctx, { job: record.job }, record.route, holdFor(ctx, deadline));
1324
+ }
1325
+ }
1326
+ async function followMany(ctx, records, deadline, done) {
1327
+ let pending = records.filter((r) => r.job && (r.status === "queued" || r.status === "running"));
1328
+ while (pending.length && ctx.now() < deadline) {
1329
+ const answer = await poll(ctx, { jobs: pending.map((r) => r.job), contact: false }, pending[0].route, holdFor(ctx, deadline));
1330
+ const entries = Array.isArray(answer.jobs) ? answer.jobs.filter(isObject) : [];
1331
+ const still = [];
1332
+ for (const [i, record] of pending.entries()) {
1333
+ const entry = entries.find((e) => e.index === i) ?? entries[i];
1334
+ const one = entry && isObject(entry.answer) ? entry.answer : undefined;
1335
+ if (one && statusOf(one) === "done")
1336
+ done.set(record.run, await finish(ctx, record, one));
1337
+ else if (one) {
1338
+ await absorb(ctx, record, one);
1339
+ still.push(record);
1340
+ } else if (entry && entry.status === "error" && !(typeof entry.httpStatus === "number" && entry.httpStatus >= 500)) {
1341
+ record.status = "failed";
1342
+ record.failed = [{ slot: "-", error: brief(typeof entry.error === "string" ? entry.error : "the job failed") }];
1343
+ delete record.job;
1344
+ await ctx.store.writeRun(record);
1345
+ } else
1346
+ still.push(record);
1347
+ }
1348
+ pending = still;
1349
+ }
1350
+ }
1351
+ var readIf = (file) => readFile3(file).catch(() => {
1352
+ return;
1353
+ });
1354
+ var sizeText = (image) => image.width && image.height ? `${image.width}x${image.height}` : undefined;
1355
+ var imageLine = (image, file = "path") => ({
1356
+ id: image.id,
1357
+ ...image.file && { file: file === "path" ? image.file : basename2(image.file) },
1358
+ ...sizeText(image) && { size: sizeText(image) },
1359
+ ...image.model && { model: image.model },
1360
+ ...image.kept && { kept: true },
1361
+ ...image.flags?.length && { flags: image.flags }
1362
+ });
1363
+ async function pictureOf(ctx, finished) {
1364
+ const { record, bytes } = finished;
1365
+ const loaded = record.images.filter((i) => bytes.has(i.id));
1366
+ try {
1367
+ if (!loaded.length)
1368
+ return {};
1369
+ if (record.images.length === 1)
1370
+ return { inline: await inlineOf(bytes.get(loaded[0].id), SINGLE_EDGE) };
1371
+ if (record.contact) {
1372
+ try {
1373
+ const sheet2 = await fetchBytes(ctx.fetch, record.contact, { tries: 2, baseMs: ctx.retryMs, sleep: ctx.sleep });
1374
+ const first = record.images[0];
1375
+ const last = record.images[record.images.length - 1];
1376
+ return { inline: await inlineOf(sheet2, LOOK_EDGE), note: `cells numbered ${first.label} to ${last.label} are ${letterOf(first.slot)} to ${letterOf(last.slot)}` };
1377
+ } catch {}
1378
+ }
1379
+ const sheet = await sheetOf(loaded.map((i) => ({ input: bytes.get(i.id), label: letterOf(i.slot) })));
1380
+ return { inline: await inlineOf(sheet, LOOK_EDGE), note: "cells are lettered as the image handles end" };
1381
+ } catch (err) {
1382
+ return { note: `no picture: ${err instanceof Error ? err.message : String(err)}` };
1383
+ }
1384
+ }
1385
+ async function finishedResult(ctx, finished, extra = {}) {
1386
+ const { record } = finished;
1387
+ const picture = await pictureOf(ctx, finished);
1388
+ return textResult({
1389
+ run: record.run,
1390
+ status: record.status,
1391
+ images: record.images.map((i) => imageLine(i)),
1392
+ ...record.failed?.length && { failed: record.failed },
1393
+ ...record.cost !== undefined && { cost: record.cost },
1394
+ ...record.tokens && { tokens: record.tokens },
1395
+ ...record.seconds !== undefined && { seconds: record.seconds },
1396
+ ...warningsOf(record.warnings) && { warnings: warningsOf(record.warnings) },
1397
+ ...finished.taste && { taste: brief(finished.taste, 400) },
1398
+ ...picture.note && { [picture.inline ? "sheet" : "picture"]: picture.note },
1399
+ ...extra
1400
+ }, picture.inline ? [picture.inline] : []);
1401
+ }
1402
+ var runningResult = (ctx, record) => textResult({ run: record.run, status: "running", seconds: round((ctx.now() - record.startedAt) / 1000), next: `still rendering: call job with run "${record.run}" to keep waiting` });
1403
+ var estimateOf = (estimate) => {
1404
+ if (!isObject(estimate))
1405
+ return;
1406
+ const cost = isObject(estimate.cost) ? estimate.cost : {};
1407
+ const seconds = isObject(estimate.seconds) ? estimate.seconds : {};
1408
+ return {
1409
+ ...typeof cost.total === "number" && { cost: cost.total },
1410
+ ...typeof cost.upTo === "number" && { upTo: cost.upTo },
1411
+ ...strings(cost.unpriced).length && { unpriced: strings(cost.unpriced).map((u) => brief(u, 120)) },
1412
+ ...typeof seconds.low === "number" && typeof seconds.high === "number" && { seconds: `${seconds.low}-${seconds.high}` }
1413
+ };
1414
+ };
1415
+ var problemsOf = (list) => (Array.isArray(list) ? list.filter(isObject) : []).map((p) => ({ ...typeof p.field === "string" && { field: p.field }, error: brief(String(p.error ?? ""), 400), ...typeof p.errorCode === "string" && { errorCode: p.errorCode } }));
1416
+ var dryLine = (answer) => {
1417
+ const providers = [...new Set((Array.isArray(answer.slots) ? answer.slots.filter(isObject) : []).map((s) => s.provider).filter((p) => typeof p === "string"))];
1418
+ return {
1419
+ ok: answer.ok === true,
1420
+ ...problemsOf(answer.problems).length && { problems: problemsOf(answer.problems) },
1421
+ ...warningsOf(answer.warnings, 8) && { warnings: warningsOf(answer.warnings, 8) },
1422
+ ...Array.isArray(answer.slots) && { images: answer.slots.length },
1423
+ ...providers.length && { renders: providers.join(", ") },
1424
+ ...estimateOf(answer.estimate) && { estimate: estimateOf(answer.estimate) }
1425
+ };
1426
+ };
1427
+ async function prepare(ctx, args, field, inherited) {
1428
+ const name = sanitizeName(typeof args.name === "string" ? args.name : "");
1429
+ if (!name)
1430
+ throw new ToolError(`${field}name must have a letter or digit: one or two lowercase words, e.g. "sword" or "badge front"`, "bad_request");
1431
+ if (typeof args.prompt !== "string" || !args.prompt.trim())
1432
+ throw new ToolError(`${field}prompt is empty`, "bad_request");
1433
+ const from = args.from ? await runOf(ctx, args.from, `${field}from`) : inherited;
1434
+ if (from && !from.state)
1435
+ throw new ToolError(`${field}from: ${from.run} has no result to continue from yet${from.job ? "; call job on it first" : ""}`, "not_ready");
1436
+ const body = await resolveImages(ctx, bodyOf(args, field));
1437
+ return { name, body, ...from && { from } };
1438
+ }
1439
+ var fresh = (ctx, route, dir, body, extra = {}) => ({
1440
+ createdAt: new Date(ctx.now()).toISOString(),
1441
+ origin: ctx.config.url,
1442
+ route,
1443
+ ...typeof body.project === "string" && { project: body.project },
1444
+ dir,
1445
+ body: kept(body),
1446
+ status: "submitting",
1447
+ images: [],
1448
+ startedAt: ctx.now(),
1449
+ ...extra
1450
+ });
1451
+ var single = (body, continued) => !continued && (body.count === undefined || body.count === 1) && !body.slots && !body.models && body.contact === undefined;
1452
+ async function generate(ctx, args) {
1453
+ const prepared = await prepare(ctx, args, "");
1454
+ const route = routeOf(ctx, modelsOf(prepared.body, prepared.from?.state), args.fal);
1455
+ const wait = waitOf(args.wait);
1456
+ const dir = dirOf(ctx, args.dir);
1457
+ let body = await withMemory(ctx, routed(prepared.body, route, args.fal));
1458
+ if (prepared.from)
1459
+ body = { ...body, state: prepared.from.state };
1460
+ if (args.dryRun) {
1461
+ const answer2 = await ctx.api("POST", "/api/agent/generate", { body: { ...body, dryRun: true }, direct: route === "direct" });
1462
+ return textResult({ dryRun: true, ...dryLine(isObject(answer2) ? answer2 : {}) });
1463
+ }
1464
+ if (single(body, Boolean(prepared.from)))
1465
+ body = { ...body, contact: false };
1466
+ const record = await ctx.store.reserveRun(prepared.name, fresh(ctx, route, dir, body));
1467
+ let answer;
1468
+ try {
1469
+ answer = await submit(ctx, "/api/agent/generate", body, route, `mcp/${record.run}/${record.startedAt.toString(36)}`);
1470
+ } catch (err) {
1471
+ await ctx.store.deleteRun(record.run);
1472
+ throw err;
1473
+ }
1474
+ const finished = await follow(ctx, record, answer, ctx.now() + wait * 1000);
1475
+ return finished ? finishedResult(ctx, finished) : runningResult(ctx, record);
1476
+ }
1477
+ var MAX_BATCH_JOBS = 16;
1478
+ var MAX_SHEET_CELLS = 36;
1479
+ var lineOf = (record) => ({
1480
+ run: record.run,
1481
+ status: record.status === "queued" ? "running" : record.status,
1482
+ ...record.images.length && { images: record.images.map((i) => imageLine(i, "name")) },
1483
+ ...record.failed?.length && { failed: record.failed }
1484
+ });
1485
+ var batchText = (head, lines, tail) => {
1486
+ const open = JSON.stringify(head).slice(0, -1);
1487
+ const close = JSON.stringify(tail).slice(1);
1488
+ return `${open}${open.length > 1 ? "," : ""}"jobs":[
1489
+ ${lines.map((l) => JSON.stringify(l)).join(`,
1490
+ `)}
1491
+ ]${close.length > 1 ? "," : ""}${close}`;
1492
+ };
1493
+ async function batchSheet(ctx, records, done) {
1494
+ const all = records.flatMap((r) => r.images.map((image) => ({ image, bytes: done.get(r.run)?.bytes.get(image.id) })));
1495
+ const shown = all.length > MAX_SHEET_CELLS ? all.filter(({ image }) => image.slot === 0) : all;
1496
+ const cells = [];
1497
+ for (const { image, bytes } of shown.slice(0, MAX_SHEET_CELLS)) {
1498
+ const input = bytes ?? (image.file ? await readIf(image.file) : undefined);
1499
+ if (input)
1500
+ cells.push({ input, label: image.id });
1501
+ }
1502
+ if (!cells.length)
1503
+ return;
1504
+ try {
1505
+ return await inlineOf(cells.length === 1 ? cells[0].input : await sheetOf(cells), LOOK_EDGE);
1506
+ } catch {
1507
+ return;
1508
+ }
1509
+ }
1510
+ var batchResult = async (ctx, started, lines, records, done, sheet, extra = {}) => {
1511
+ const running = records.filter((r) => r.status === "queued" || r.status === "running");
1512
+ const cost = records.reduce((sum, r) => sum + (r.cost ?? 0), 0);
1513
+ const warnings = warningsOf(records.flatMap((r) => (r.warnings ?? []).map((w) => `${r.run}: ${w}`)), 6);
1514
+ const taste = [...done.values()].find((f) => f.taste)?.taste;
1515
+ const inline = sheet ? await batchSheet(ctx, records, done) : undefined;
1516
+ const dirs = [...new Set(records.map((r) => r.dir))];
1517
+ const text = batchText({ status: running.length ? "running" : "done", seconds: round((ctx.now() - started) / 1000), ...dirs.length === 1 && { dir: dirs[0] } }, lines, {
1518
+ ...cost > 0 && { cost: round(cost, 4) },
1519
+ ...warnings && { warnings },
1520
+ ...taste && { taste: brief(taste, 400) },
1521
+ ...running.length && { next: `still rendering: call job with run "${running[0].run}" to keep waiting on ${running.length === 1 ? "it" : `all ${running.length}`}` },
1522
+ ...extra
1523
+ });
1524
+ return textResult(text, inline ? [inline] : []);
1525
+ };
1526
+ async function batch(ctx, args) {
1527
+ const { jobs, sheet, wait: waitArg, fal, dryRun, dir: dirArg, from: fromArg, ...shared } = args;
1528
+ if (!Array.isArray(jobs) || !jobs.length)
1529
+ throw new ToolError("jobs must be a list of { name, prompt, … }", "bad_request");
1530
+ if (jobs.length > MAX_BATCH_JOBS)
1531
+ throw new ToolError(`a batch takes at most ${MAX_BATCH_JOBS} jobs; this one has ${jobs.length}`, "bad_request");
1532
+ const wait = waitOf(waitArg);
1533
+ const dir = dirOf(ctx, dirArg);
1534
+ const inherited = fromArg ? await runOf(ctx, fromArg, "from") : undefined;
1535
+ const defaults = await resolveImages(ctx, bodyOf(shared, ""));
1536
+ const prepared = [];
1537
+ for (const [i, job] of jobs.entries())
1538
+ prepared.push(await prepare(ctx, job, `jobs[${i}].`, inherited));
1539
+ const routes = prepared.map((p) => routeOf(ctx, modelsOf({ ...defaults, ...p.body }, p.from?.state), fal));
1540
+ if (new Set(routes).size > 1) {
1541
+ throw new ToolError("This batch mixes jobs that render directly with jobs that render on fal, and one call goes one way.", "bad_request", "Send the direct jobs and the fal jobs as two batch calls.");
1542
+ }
1543
+ const route = routes[0];
1544
+ const top = await withMemory(ctx, routed({ ...defaults, contact: false }, route, fal));
1545
+ const jobBody = (p, label) => ({ ...p.body, ...p.from && { state: p.from.state }, ...label && { label } });
1546
+ if (dryRun) {
1547
+ const answer2 = await ctx.api("POST", "/api/agent/batch", { body: { ...top, jobs: prepared.map((p) => jobBody(p)), dryRun: true }, direct: route === "direct" });
1548
+ const entries2 = isObject(answer2) && Array.isArray(answer2.jobs) ? answer2.jobs.filter(isObject) : [];
1549
+ const lines2 = prepared.map((p, i) => ({ name: p.name, ...dryLine(entries2.find((e) => e.index === i) ?? entries2[i] ?? {}) }));
1550
+ const whole = isObject(answer2) ? answer2 : {};
1551
+ return textResult(batchText({ dryRun: true, ok: whole.ok === true }, lines2, { ...warningsOf(whole.warnings) && { warnings: warningsOf(whole.warnings) } }));
1552
+ }
1553
+ const started = ctx.now();
1554
+ const id = `b${started.toString(36)}`;
1555
+ const records = [];
1556
+ for (const p of prepared)
1557
+ records.push(await ctx.store.reserveRun(p.name, fresh(ctx, route, dir, { ...defaults, ...p.body }, { batch: id })));
1558
+ let answer;
1559
+ try {
1560
+ answer = await submit(ctx, "/api/agent/batch", { ...top, jobs: prepared.map((p, i) => jobBody(p, records[i].run)) }, route, `mcp/${id}`);
1561
+ } catch (err) {
1562
+ await Promise.all(records.map((r) => ctx.store.deleteRun(r.run)));
1563
+ throw err;
1564
+ }
1565
+ const entries = isObject(answer.batch) && Array.isArray(answer.batch.jobs) ? answer.batch.jobs.filter(isObject) : [];
1566
+ const done = new Map;
1567
+ const lines = [];
1568
+ const standing = [];
1569
+ for (const [i, record] of records.entries()) {
1570
+ const entry = entries.find((e) => e.index === i) ?? entries[i];
1571
+ const one = entry && isObject(entry.answer) ? entry.answer : undefined;
1572
+ if (!one) {
1573
+ await ctx.store.deleteRun(record.run);
1574
+ lines.push({ name: prepared[i].name, status: "error", error: brief(typeof entry?.error === "string" ? entry.error : "the batch answered nothing for this job", 400), ...typeof entry?.errorCode === "string" && { errorCode: entry.errorCode } });
1575
+ continue;
1576
+ }
1577
+ standing.push(record);
1578
+ lines.push(undefined);
1579
+ if (statusOf(one) === "done")
1580
+ done.set(record.run, await finish(ctx, record, one));
1581
+ else
1582
+ await absorb(ctx, record, one);
1583
+ }
1584
+ await followMany(ctx, standing, started + wait * 1000, done);
1585
+ let next = 0;
1586
+ const filled = lines.map((line) => line ?? lineOf(standing[next++]));
1587
+ return batchResult(ctx, started, filled, standing, done, sheet !== false);
1588
+ }
1589
+ var recalled = async (ctx, record) => {
1590
+ const bytes = new Map;
1591
+ for (const image of record.images) {
1592
+ const data = image.file ? await readIf(image.file) : undefined;
1593
+ if (data)
1594
+ bytes.set(image.id, data);
1595
+ }
1596
+ return { record, bytes };
1597
+ };
1598
+ async function job(ctx, args) {
1599
+ const record = await runOf(ctx, args.run);
1600
+ const deadline = ctx.now() + waitOf(args.wait) * 1000;
1601
+ const pendingNow = (r) => Boolean(r.job) && (r.status === "queued" || r.status === "running");
1602
+ if (args.cancel) {
1603
+ if (!pendingNow(record))
1604
+ return textResult({ run: record.run, status: record.status, cancel: "nothing to cancel: the run is not rendering" });
1605
+ const answer = await ctx.api("POST", "/api/agent/cancel", { body: { job: record.job }, direct: record.route === "direct" });
1606
+ if (!isObject(answer))
1607
+ throw new ToolError("the cancel answered nothing", "upstream_error");
1608
+ const outcomes = (Array.isArray(answer.cancel) ? answer.cancel.filter(isObject) : []).map((c) => {
1609
+ const number = typeof c.slot === "number" ? c.slot : Number.parseInt(String(c.label ?? ""), 10);
1610
+ return { image: number >= 1 ? letterOf(number - 1) : String(c.label ?? ""), outcome: String(c.outcome ?? "unknown") };
1611
+ });
1612
+ if (statusOf(answer) !== "done") {
1613
+ await absorb(ctx, record, answer);
1614
+ return textResult({ run: record.run, status: "running", cancel: outcomes, next: `some images were already rendering and will finish: call job with run "${record.run}"` });
1615
+ }
1616
+ const finished2 = await finish(ctx, record, answer);
1617
+ if (!finished2.record.images.length) {
1618
+ finished2.record.status = "cancelled";
1619
+ await ctx.store.writeRun(finished2.record);
1620
+ }
1621
+ return finishedResult(ctx, finished2, { cancel: outcomes });
1622
+ }
1623
+ if (record.status === "submitting")
1624
+ throw new ToolError(`${record.run} was never answered by the server: the call that started it is still open, or it was interrupted`, "not_ready", "Wait for that call, or generate again under the same name.");
1625
+ const siblings = record.batch ? (await ctx.store.listRuns()).filter((r) => r.batch === record.batch) : [record];
1626
+ if (siblings.length > 1) {
1627
+ const done = new Map;
1628
+ await followMany(ctx, siblings, deadline, done);
1629
+ for (const r of siblings)
1630
+ if (!done.has(r.run) && r.images.length)
1631
+ done.set(r.run, await recalled(ctx, r));
1632
+ return batchResult(ctx, Math.min(...siblings.map((r) => r.startedAt)), siblings.map(lineOf), siblings, done, true);
1633
+ }
1634
+ if (!pendingNow(record))
1635
+ return finishedResult(ctx, await recalled(ctx, record));
1636
+ const finished = await follow(ctx, record, await poll(ctx, { job: record.job }, record.route, holdFor(ctx, deadline)), deadline);
1637
+ return finished ? finishedResult(ctx, finished) : runningResult(ctx, record);
1638
+ }
1639
+
1640
+ // tools.ts
1641
+ var INSTRUCTIONS = "Emitter is the user's image generator. Make and edit images with these tools rather than calling an image API or Emitter's HTTP API by hand: this server keeps references, run state, memory and the ledger on this machine, and returns pictures inline. Call guide once before the first generate. Refer to runs and images by the short handles the tools return. When the user reacts to a result, call feedback with their words and what they kept. Call show when the user should look at results.";
1642
+ var MAX_LOOK = 36;
1643
+ var LOOK_SEPARATE = 4;
1644
+ async function look(ctx, args) {
1645
+ if (!Array.isArray(args.images) || !args.images.length)
1646
+ throw new ToolError("images must name at least one image: a handle, a run, a file path, or a url", "bad_request");
1647
+ const pictures = [];
1648
+ for (const [i, text] of args.images.entries())
1649
+ pictures.push(...await picturesOf(ctx, text, `images[${i}]`));
1650
+ if (pictures.length > MAX_LOOK)
1651
+ throw new ToolError(`look takes at most ${MAX_LOOK} images at once; these are ${pictures.length}`, "bad_request");
1652
+ const loaded = await Promise.all(pictures.map(async (picture) => ({ picture, bytes: await bytesOf(ctx, picture) })));
1653
+ const lines = await Promise.all(loaded.map(async ({ picture, bytes }) => {
1654
+ const image = picture.image;
1655
+ const size = image?.width && image.height ? { width: image.width, height: image.height } : await sizeOf(bytes).catch(() => {
1656
+ return;
1657
+ });
1658
+ return {
1659
+ id: picture.label,
1660
+ ...size && { size: `${size.width}x${size.height}` },
1661
+ ...image?.kept && { kept: true },
1662
+ ...image?.flags?.length && { flags: image.flags }
1663
+ };
1664
+ }));
1665
+ const asSheet = args.sheet === true || loaded.length > LOOK_SEPARATE;
1666
+ const inline = asSheet ? [await inlineOf(await sheetOf(loaded.map(({ picture, bytes }) => ({ input: bytes, label: picture.label }))), LOOK_EDGE)] : await Promise.all(loaded.map(({ bytes }) => inlineOf(bytes, LOOK_EDGE)));
1667
+ return textResult({ images: lines, ...asSheet && { sheet: "one sheet, each cell labelled" } }, inline);
1668
+ }
1669
+ var brief2 = (text, max = 160) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
1670
+ var runImages = async (ctx, list, field) => {
1671
+ const out = [];
1672
+ for (const [i, text] of (list ?? []).entries()) {
1673
+ const it = await named(ctx, text, `${field}[${i}]`);
1674
+ if (it.kind !== "images")
1675
+ throw new ToolError(`${field}[${i}]: name an image by its handle, like sword-v2-a`, "bad_request");
1676
+ for (const image of it.images)
1677
+ out.push({ record: it.record, id: image.id });
1678
+ }
1679
+ return out;
1680
+ };
1681
+ var touchedOf = (list) => (Array.isArray(list) ? list.filter(isObject) : []).slice(0, 12).map((e) => ({
1682
+ key: e.key,
1683
+ value: typeof e.value === "string" ? brief2(e.value) : e.value,
1684
+ ...typeof e.confidence === "number" && { confidence: Math.round(e.confidence * 100) / 100 },
1685
+ ...Array.isArray(e.topic) && e.topic.length && { topic: e.topic.slice(0, 4) },
1686
+ ...typeof e.project === "string" && { project: e.project }
1687
+ }));
1688
+ async function feedback(ctx, args) {
1689
+ const said = typeof args.said === "string" ? args.said.trim() : "";
1690
+ const keeps = await runImages(ctx, args.kept, "kept");
1691
+ const drops = await runImages(ctx, args.unkept, "unkept");
1692
+ if (!said && !keeps.length && !drops.length)
1693
+ throw new ToolError("feedback needs the user's words (said), the images they kept (kept), or images to take the kept mark off (unkept)", "bad_request");
1694
+ const changed = new Map;
1695
+ const mark = async (entries, kept2) => {
1696
+ for (const { record, id } of entries) {
1697
+ const current = changed.get(record.run) ?? await ctx.store.readRun(record.run) ?? record;
1698
+ current.images = current.images.map((image) => image.id === id ? { ...image, ...kept2 ? { kept: true } : { kept: undefined } } : image);
1699
+ changed.set(record.run, current);
1700
+ }
1701
+ };
1702
+ await mark(keeps, true);
1703
+ await mark(drops, false);
1704
+ for (const record of changed.values()) {
1705
+ await ctx.store.writeRun(record);
1706
+ await ctx.store.setKept(record.run, record.images.filter((i) => i.kept).map((i) => i.id));
1707
+ }
1708
+ let target;
1709
+ let touched;
1710
+ let warnings;
1711
+ if (said) {
1712
+ const marked = [...new Set([...keeps, ...drops].map((e) => e.record.run))];
1713
+ if (args.run)
1714
+ target = await runOf(ctx, args.run);
1715
+ else if (marked.length === 1)
1716
+ target = changed.get(marked[0]);
1717
+ else
1718
+ target = (await ctx.store.listRuns()).filter((r) => r.state && r.status === "done").pop();
1719
+ if (!target)
1720
+ throw new ToolError("said is about a run, and there is no finished run yet: name one with run", "bad_request");
1721
+ if (!target.state)
1722
+ throw new ToolError(`${target.run} has no result yet for the words to be about${target.job ? "; call job on it first" : ""}`, "not_ready");
1723
+ const run = target.run;
1724
+ const picked = keeps.filter((e) => e.record.run === run).flatMap((e) => target.images.filter((i) => i.id === e.id).map((i) => Number(i.label) || i.slot + 1));
1725
+ const body = { said, state: target.state, ...picked.length && { pick: [...new Set(picked)] }, ...target.project && { project: target.project } };
1726
+ const send = async (own2) => ctx.api("POST", "/api/agent/memory/feedback", { body: own2 ? { ...body, memory: await ctx.store.readMemory() } : body, timeoutMs: 120000 });
1727
+ let own = !(await serverMemory(ctx)).kept;
1728
+ let answer;
1729
+ try {
1730
+ answer = await send(own);
1731
+ } catch (err) {
1732
+ if (own || !(err instanceof ApiError) || err.status !== 404)
1733
+ throw err;
1734
+ own = true;
1735
+ await noteServerMemory(ctx, false);
1736
+ answer = await send(true);
1737
+ }
1738
+ const result = isObject(answer) ? answer : {};
1739
+ if (own && Array.isArray(result.memory))
1740
+ await ctx.store.writeMemory(result.memory.filter(isObject));
1741
+ touched = touchedOf(result.touched);
1742
+ if (Array.isArray(result.warnings) && result.warnings.length)
1743
+ warnings = result.warnings.filter((w) => typeof w === "string").slice(0, 4).map((w) => brief2(w, 220));
1744
+ }
1745
+ const totals = await ctx.store.ledgerTotals();
1746
+ return textResult({
1747
+ ...target && { run: target.run },
1748
+ ...keeps.length && { kept: [...new Set(keeps.map((e) => e.id))] },
1749
+ ...drops.length && { unkept: [...new Set(drops.map((e) => e.id))] },
1750
+ ...touched && { touched },
1751
+ ...warnings && { warnings },
1752
+ ledger: totals
1753
+ });
1754
+ }
1755
+ var RECENT_RUNS = 8;
1756
+ var mergeUiKeeps = async (ctx, records, kept2) => {
1757
+ const marked = [];
1758
+ for (const record of records) {
1759
+ let dirty = false;
1760
+ record.images = record.images.map((image) => {
1761
+ if (image.kept)
1762
+ return image;
1763
+ const hit = kept2.some((k) => {
1764
+ const url = isObject(k.image) ? k.image.url : undefined;
1765
+ if (typeof url === "string" && url === image.url)
1766
+ return true;
1767
+ const sameRun = typeof k.runId !== "string" || record.serverRun === undefined || k.runId === record.serverRun;
1768
+ return record.sessionId !== undefined && k.sessionId === record.sessionId && k.slot === image.slot && sameRun;
1769
+ });
1770
+ if (!hit)
1771
+ return image;
1772
+ dirty = true;
1773
+ marked.push(image.id);
1774
+ return { ...image, kept: true };
1775
+ });
1776
+ if (!dirty)
1777
+ continue;
1778
+ await ctx.store.writeRun(record);
1779
+ await ctx.store.setKept(record.run, record.images.filter((i) => i.kept).map((i) => i.id));
1780
+ }
1781
+ return marked;
1782
+ };
1783
+ var agoText = (ms) => ms < 90000 ? `${Math.round(ms / 1000)}s ago` : ms < 5400000 ? `${Math.round(ms / 60000)}m ago` : ms < 172800000 ? `${Math.round(ms / 3600000)}h ago` : `${Math.round(ms / 86400000)}d ago`;
1784
+ async function context(ctx) {
1785
+ let auth;
1786
+ let memory;
1787
+ try {
1788
+ memory = await serverMemory(ctx, true);
1789
+ auth = ctx.config.token ? "ok" : "ok, no token needed";
1790
+ } catch (err) {
1791
+ if (!(err instanceof ApiError))
1792
+ throw err;
1793
+ auth = err.status === 401 ? `failed: ${brief2(err.message, 200)}. Ask the user to copy a fresh token from Emitter's Agent panel into ${ctx.config.envFile} as EMITTER_TOKEN.` : `unknown: ${brief2(err.message, 200)}`;
1794
+ }
1795
+ const reachable = !auth.startsWith("unknown");
1796
+ const up = reachable || await ctx.api("GET", "/api/agent/ping", { direct: false, timeoutMs: 1e4 }).then(() => true, () => false);
1797
+ if (!up)
1798
+ auth = `unreachable: ${ctx.config.url} did not answer`;
1799
+ const about = up ? await briefOf(ctx).catch(() => {
1800
+ return;
1801
+ }) : undefined;
1802
+ const mode = about ? modeOf(about) : undefined;
1803
+ let records = await ctx.store.listRuns();
1804
+ let ui;
1805
+ if (mode === "local" && reachable) {
1806
+ try {
1807
+ const answer = await ctx.api("GET", "/api/agent/context?limit=50", { direct: false });
1808
+ if (isObject(answer)) {
1809
+ const marked = await mergeUiKeeps(ctx, records, Array.isArray(answer.kept) ? answer.kept.filter(isObject) : []);
1810
+ if (marked.length)
1811
+ records = await ctx.store.listRuns();
1812
+ const open = isObject(answer.open) && typeof answer.open.sessionId === "string" ? answer.open : undefined;
1813
+ const openRun = open && [...records].reverse().find((r) => r.sessionId === open.sessionId || r.shownAs === open.sessionId);
1814
+ ui = {
1815
+ ...open && { open: openRun ? openRun.run : "a session none of these runs made (new, or made in the app)", ...typeof open.ago === "number" && { seen: agoText(open.ago) } },
1816
+ ...marked.length && { keptInUi: marked },
1817
+ ...isObject(answer.totals) && { totals: answer.totals }
1818
+ };
1819
+ }
1820
+ } catch (err) {
1821
+ if (!(err instanceof ApiError) || err.status !== 404)
1822
+ ui = { error: brief2(err instanceof Error ? err.message : String(err), 200) };
1823
+ }
1824
+ }
1825
+ const totals = await ctx.store.ledgerTotals();
1826
+ const taste = memory ? await standingTaste(ctx, memory) : [];
1827
+ const own = memory && !memory.kept ? (await ctx.store.readMemory()).length : undefined;
1828
+ return textResult({
1829
+ server: ctx.config.url,
1830
+ auth,
1831
+ ...mode && { mode },
1832
+ renders: ctx.config.direct ? "directly" : "on fal",
1833
+ ...memory && { memory: memory.kept ? "kept by the server" : `kept on this machine (${own} entries)` },
1834
+ ledger: totals,
1835
+ recent: records.slice(-RECENT_RUNS).reverse().map((r) => ({
1836
+ run: r.run,
1837
+ ...r.status !== "done" && { status: r.status === "queued" ? "running" : r.status },
1838
+ images: r.images.map((i) => i.id.slice(r.run.length + 1)).join(" "),
1839
+ ...r.images.some((i) => i.kept) && { kept: r.images.filter((i) => i.kept).map((i) => i.id.slice(r.run.length + 1)).join(" ") }
1840
+ })),
1841
+ ...taste.length && { taste: taste.map((t) => brief2(t, 300)) },
1842
+ ...ui && Object.keys(ui).length && { ui },
1843
+ images: ctx.config.images
1844
+ });
1845
+ }
1846
+ var runLink = (origin, record) => {
1847
+ const state = structuredClone(record.state ?? {});
1848
+ const newest = isObject(state.newest) ? state.newest : undefined;
1849
+ if (newest && Array.isArray(newest.slots))
1850
+ newest.slots = newest.slots.map((slot) => isObject(slot) ? Object.fromEntries(Object.entries(slot).filter(([key]) => key !== "checks")) : slot);
1851
+ const payload = gzipSync(Buffer.from(JSON.stringify({ v: 1, state, name: record.run }), "utf8")).toString("base64url");
1852
+ return `${origin}/#run=${payload}`;
1853
+ };
1854
+ var shownAsOf = (link) => sharedId(link.slice(link.indexOf("#run=") + 5));
1855
+ async function show(ctx, args) {
1856
+ let record;
1857
+ let pictures = [];
1858
+ if (args.run)
1859
+ record = await runOf(ctx, args.run);
1860
+ else if (Array.isArray(args.images) && args.images.length) {
1861
+ for (const [i, text] of args.images.entries())
1862
+ pictures.push(...await picturesOf(ctx, text, `images[${i}]`));
1863
+ const runs = new Set(pictures.map((p) => p.record?.run));
1864
+ if (runs.size === 1 && pictures[0].record)
1865
+ record = pictures[0].record;
1866
+ } else
1867
+ throw new ToolError("show takes a run, or images to open", "bad_request");
1868
+ if (record && !pictures.length)
1869
+ pictures = record.images.map((image) => ({ label: image.id, file: image.file, url: image.url, image, record }));
1870
+ const about = await briefOf(ctx).catch(() => {
1871
+ return;
1872
+ });
1873
+ let url;
1874
+ if (record && record.images.length && about && about.ui !== undefined) {
1875
+ if (record.sessionId && record.origin === ctx.config.url)
1876
+ url = `${ctx.config.url}/?session=${encodeURIComponent(record.sessionId)}`;
1877
+ else if (record.state) {
1878
+ url = runLink(ctx.config.url, record);
1879
+ const shownAs = shownAsOf(url);
1880
+ if (record.shownAs !== shownAs)
1881
+ await ctx.store.writeRun({ ...record, shownAs });
1882
+ }
1883
+ }
1884
+ const files = [];
1885
+ if (!url) {
1886
+ for (const picture of pictures) {
1887
+ if (picture.file && await stat2(picture.file).then(() => true, () => false))
1888
+ files.push(picture.file);
1889
+ else if (picture.url)
1890
+ files.push(picture.url);
1891
+ }
1892
+ if (!files.length)
1893
+ throw new ToolError(`${record ? record.run : "these images"}: nothing to show yet${record?.job ? "; the run is still rendering, call job first" : ""}`, "not_ready");
1894
+ }
1895
+ const opened = args.open === false ? false : await ctx.open(url ? [url] : files);
1896
+ return textResult({ ...record && { run: record.run }, ...url ? { url } : { files }, opened });
1897
+ }
1898
+ var CALL_BUDGET = 8000;
1899
+ var METHODS = ["GET", "POST", "PATCH", "DELETE"];
1900
+ var EXACT_KEYS = ["image", "mask", "ref"];
1901
+ var IMAGE_FILE = /\.(png|jpe?g|webp|gif|heic|avif)$/i;
1902
+ var resolveDeep = async (ctx, value, field, key) => {
1903
+ if (typeof value === "string") {
1904
+ const handle = parseHandle(value);
1905
+ if (handle && await ctx.store.readRun(handle.run)) {
1906
+ const urls = await referencesOf(ctx, value, field);
1907
+ return urls.length === 1 ? urls[0] : urls;
1908
+ }
1909
+ if ((value.startsWith("/") || value.startsWith("~/")) && IMAGE_FILE.test(value))
1910
+ return key && EXACT_KEYS.includes(key) ? exactImageOf(ctx, value, field) : (await referencesOf(ctx, value, field))[0];
1911
+ return value;
1912
+ }
1913
+ if (Array.isArray(value)) {
1914
+ const out = [];
1915
+ for (const [i, item] of value.entries()) {
1916
+ const resolved = await resolveDeep(ctx, item, `${field}[${i}]`, key);
1917
+ if (typeof item === "string" && Array.isArray(resolved))
1918
+ out.push(...resolved);
1919
+ else
1920
+ out.push(resolved);
1921
+ }
1922
+ return out;
1923
+ }
1924
+ if (isObject(value)) {
1925
+ const out = {};
1926
+ for (const [k, v] of Object.entries(value))
1927
+ out[k] = await resolveDeep(ctx, v, field ? `${field}.${k}` : k, k);
1928
+ return out;
1929
+ }
1930
+ return value;
1931
+ };
1932
+ async function call(ctx, args) {
1933
+ const method = (args.method ?? (args.body === undefined ? "GET" : "POST")).toUpperCase();
1934
+ if (!METHODS.includes(method))
1935
+ throw new ToolError(`method must be one of ${METHODS.join(", ")}`, "bad_request");
1936
+ let target;
1937
+ try {
1938
+ target = new URL(String(args.path), ctx.config.url);
1939
+ } catch {
1940
+ throw new ToolError("path must be a path of the agent API, like /api/agent/check", "bad_request");
1941
+ }
1942
+ if (target.origin !== new URL(ctx.config.url).origin || !(target.pathname === "/api/agent" || target.pathname.startsWith("/api/agent/"))) {
1943
+ throw new ToolError(`call only reaches Emitter's agent API: the path must start with /api/agent/, and "${brief2(String(args.path), 80)}" does not`, "bad_request");
1944
+ }
1945
+ let body = args.body === undefined || method === "GET" ? undefined : await resolveDeep(ctx, args.body, "");
1946
+ const own = method === "POST" && isObject(body) && body.memory === undefined && /^\/api\/agent\/memory(\/feedback)?$/.test(target.pathname) && (body.brief !== undefined || target.pathname.endsWith("/feedback")) && !(await serverMemory(ctx)).kept;
1947
+ if (own && isObject(body))
1948
+ body = { ...body, memory: await ctx.store.readMemory() };
1949
+ let answer = await ctx.api(method, `${target.pathname}${target.search}`, { ...body !== undefined && { body }, timeoutMs: 330000 });
1950
+ if (own && isObject(answer) && Array.isArray(answer.memory)) {
1951
+ if (target.pathname.endsWith("/feedback"))
1952
+ await ctx.store.writeMemory(answer.memory.filter(isObject));
1953
+ answer = { ...answer, memory: `${answer.memory.length} entries, kept on this machine` };
1954
+ }
1955
+ const text = JSON.stringify(answer);
1956
+ if (text.length <= CALL_BUDGET)
1957
+ return textResult(text);
1958
+ return textResult(`${text.slice(0, CALL_BUDGET)}
1959
+ … cut at ${CALL_BUDGET} of ${text.length} characters; ask for less (a narrower path or query) to see the rest`);
1960
+ }
1961
+ var imageName = "an image handle (sword-v2-a), a run handle, an absolute file path, or an https url";
1962
+ var renderShape = {
1963
+ from: z.string().optional().describe("A run handle to continue from: its settings and references carry over, and prompt replaces its prompt. For a new direction on the same setup."),
1964
+ references: z.array(z.string()).optional().describe(`Images the model should see: each ${imageName}. A run handle adds all its images. Call each "the attached <name>" in the prompt.`),
1965
+ model: z.string().optional().describe("Model id, label, or alias (gpt, flux, grok, banana). Left out: the default, or what memory suggests."),
1966
+ size: z.enum(IMAGE_SIZES.map((s) => s.value)).optional().describe("Aspect preset."),
1967
+ dimensions: z.string().optional().describe('Exact pixels as "<width>x<height>", on the models that take them; stands in for size.'),
1968
+ quality: z.enum(QUALITIES).optional(),
1969
+ count: z.number().int().min(1).max(8).optional().describe("How many images, 1 to 8. Use 2 to 4 when the brief is open and the user will pick by eye, 1 for a precise brief or an edit."),
1970
+ format: z.enum(["jpeg", "png"]).optional(),
1971
+ cutout: z.boolean().optional().describe("The subject cut out with its shadow, as a transparent PNG."),
1972
+ style: z.union([z.string(), z.record(z.string(), z.unknown()), z.array(z.union([z.string(), z.record(z.string(), z.unknown())]))]).optional().describe("A style name, an inline style { prefix?, keep?, avoid?, scene?, …options }, or a list of either layered in order."),
1973
+ keep: z.string().optional().describe("Text every prompt of the run must keep."),
1974
+ avoid: z.string().optional().describe("Text every prompt of the run must avoid."),
1975
+ edit: z.looseObject({
1976
+ image: z.string().describe(`The image to edit: ${imageName}.`),
1977
+ region: z.string().optional().describe('The part to change, in a few words ("the chest print"); found on the image by the server.'),
1978
+ box: z.array(z.number()).length(4).optional().describe("The part as [x, y, width, height], fractions of the frame."),
1979
+ mask: z.string().optional().describe("A PNG transparent where the edit may land."),
1980
+ grow: z.number().optional().describe("Pixels to widen the region by, for room around the part.")
1981
+ }).optional().describe("A masked local edit, for a small change: the prompt states the change, and everything outside the region keeps the original pixels. Give region, box, or mask."),
1982
+ require: z.looseObject({
1983
+ text: z.union([z.string(), z.array(z.string())]).optional().describe("Strings that must appear exactly."),
1984
+ logo: z.string().optional().describe(`A logo that must appear: ${imageName}.`),
1985
+ colors: z.union([z.string(), z.array(z.string())]).optional().describe("Colors that must be clearly visible."),
1986
+ nothingExtra: z.boolean().optional().describe("No other text, logos, or watermarks."),
1987
+ retries: z.number().int().min(0).max(3).optional()
1988
+ }).optional().describe("An acceptance checklist each image is judged against; a failing image is rendered again."),
1989
+ project: z.string().optional().describe("A short project name; its memory applies whatever the wording."),
1990
+ options: z.record(z.string(), z.unknown()).optional().describe('Any other key the API takes (hd, fit, background, overlays, text, colorize, scene, slots, models, seed, …), merged into the body as written; such a key may also sit beside prompt. guide { topic: "options" } lists them. An unknown key is an error that names it.')
1991
+ };
1992
+ var generateShape = {
1993
+ name: z.string().describe('One or two lowercase words for the subject ("sword", "badge front"). The run becomes <name>-v<N>.'),
1994
+ prompt: z.string().describe("The finished prompt, sent to the model as written; guide says how to write one. Settings are the keys beside it, never words in the prompt."),
1995
+ ...renderShape,
1996
+ dryRun: z.boolean().optional().describe("true renders nothing and answers the problems, warnings, and the cost and time estimate. Free, and uses no version number."),
1997
+ fal: z.boolean().optional().describe("Only on a machine set to render directly: true sends this call to fal instead. Pass it only when the user asks for a render on fal."),
1998
+ wait: z.number().min(0).max(MAX_WAIT).optional().describe(`Seconds to wait for the images, default ${DEFAULT_WAIT}. Past it the run answers status "running"; call job to keep waiting. A direct render holds until it is done.`),
1999
+ dir: z.string().optional().describe("An absolute directory to write the images to, in place of the default.")
2000
+ };
2001
+ var batchShape = {
2002
+ jobs: z.array(z.looseObject({ name: z.string().describe("The run name, as for generate."), prompt: z.string().describe("The finished prompt.") })).min(1).max(MAX_BATCH_JOBS).describe(`Up to ${MAX_BATCH_JOBS} jobs, each its own run: name, prompt, and any other key generate takes (from, references, model, count, edit, …).`),
2003
+ sheet: z.boolean().optional().describe("false leaves the inline sheet out. Default true: every finished image on one sheet, each cell labelled with its handle."),
2004
+ dryRun: z.boolean().optional().describe("true renders nothing and answers each job's problems, warnings, and estimate."),
2005
+ fal: generateShape.fal,
2006
+ wait: generateShape.wait,
2007
+ dir: generateShape.dir
2008
+ };
2009
+ var tool = (name, description, shape, run, loose = false) => ({
2010
+ name,
2011
+ description,
2012
+ schema: loose ? z.looseObject(shape) : z.object(shape),
2013
+ run
2014
+ });
2015
+ var TOOLS = [
2016
+ tool("guide", "How to use Emitter: how to write a prompt, the models and options, and how handles and these tools work. Call it once before the first generate of a session. With topic, one section of the full reference instead (several separated by commas, a dotted name like endpoints.generate.body.edit reaches into one); the page lists the topics. Returns text.", { topic: z.string().optional().describe("A topic name from the guide page, or several separated by commas. Left out: the one-page guide.") }, guide),
2017
+ tool("generate", `Render one run of images from a finished prompt, or edit an existing image (edit), or continue an earlier run in a new direction (from). Waits for the images, writes them to disk, and returns the run handle, each image's handle, file, size and flags, the cost, and the picture inline (one image, or a sheet of several). If it returns status "running", call job with the run handle.`, generateShape, generate, true),
2018
+ tool("batch", "Render several different briefs in one call: up to 16 jobs, each its own run with its own name and prompt. Any key generate takes (model, references, cutout, style, project, …) may sit beside jobs as a default under every job, or inside a job for that job alone. Use it instead of several generate calls; for variations of one brief use generate with count. Returns one line per job (its run handle and images, or its error while the others stand) and one sheet inline with every image labelled by its handle.", batchShape, batch, true),
2019
+ tool("job", 'Keep waiting on a run that generate or batch returned as "running", and finish it the same way: images on disk, the result, and the picture inline. Naming one run of a batch waits on all of that batch. With cancel: true, stop the run instead (what was already rendering still finishes). On a finished run it returns the result again.', {
2020
+ run: z.string().describe("The run handle, like sword-v2."),
2021
+ cancel: z.boolean().optional().describe("true stops what is still queued."),
2022
+ wait: z.number().min(0).max(MAX_WAIT).optional().describe(`Seconds to wait, default ${DEFAULT_WAIT}.`)
2023
+ }, job),
2024
+ tool("look", "See images inline without downloading or reading files: run images by handle, whole runs, files on disk, or urls. Up to 4 come back as separate images, more (or sheet: true) as one labelled sheet. Use it to compare earlier results or to look closer at one image of a sheet. Returns each image's size and its flags (clipped edges, a halo, no alpha on a cutout) with the pictures.", {
2025
+ images: z.array(z.string()).min(1).describe(`Each ${imageName}. A run handle shows all its images.`),
2026
+ sheet: z.boolean().optional().describe("true puts them on one labelled sheet even when there are 4 or fewer.")
2027
+ }, look),
2028
+ tool("feedback", "Record how the user reacted to a result. said is their words verbatim, which the server turns into memory for later runs (their taste, what to keep and avoid); kept is the images they kept, which the ledger counts, and unkept takes that mark off. Either part alone is fine. Call it every time the user reacts or picks. Returns the memory entries touched and the ledger totals, with renders per kept image.", {
2029
+ run: z.string().optional().describe("The run the words are about. Left out: the run of the kept images, else the newest finished run."),
2030
+ said: z.string().optional().describe("The user's words, verbatim."),
2031
+ kept: z.array(z.string()).optional().describe("Handles of the images the user kept."),
2032
+ unkept: z.array(z.string()).optional().describe("Handles of images to take the kept mark off.")
2033
+ }, feedback),
2034
+ tool("context", "Where things stand, before rendering more or when picking work back up: the server and whether auth works, where renders go, the ledger totals with renders per kept image, the last few runs with their image handles and keeps, the standing taste from memory, and, on a local server, what the user kept in Emitter itself and which run they have open. Returns compact JSON.", {}, (ctx) => context(ctx)),
2035
+ tool("show", "Put results in front of the user: opens a run in Emitter's own UI in the background, or the image files when the server has no such link. Call it when the user should look at or pick from results. Returns the url or the file paths, and whether they were opened.", {
2036
+ run: z.string().optional().describe("The run handle to show."),
2037
+ images: z.array(z.string()).optional().describe(`In place of run: each ${imageName}.`),
2038
+ open: z.boolean().optional().describe("false returns the link or paths without opening anything.")
2039
+ }, show),
2040
+ tool("call", 'Any other route of the Emitter agent API, with auth added and image handles inside the body turned into what the API takes: /api/agent/check (judge an existing image), /api/agent/sheet, /api/agent/sequence, /api/agent/memory, /api/agent/styles and the rest; guide { topic: "endpoints" } lists them. Use the other tools for rendering, polling, and feedback. Returns the JSON answer, cut short with a note when it is long.', {
2041
+ method: z.enum(["GET", "POST", "PATCH", "DELETE"]).optional().describe("Default GET, or POST when there is a body."),
2042
+ path: z.string().describe("A path under /api/agent/, with its query if any."),
2043
+ body: z.record(z.string(), z.unknown()).optional().describe("The JSON body. Image handles and image file paths in it are resolved.")
2044
+ }, call)
2045
+ ];
2046
+ async function runTool(deps, name, args) {
2047
+ const found = TOOLS.find((t) => t.name === name);
2048
+ if (!found)
2049
+ return errorResult(new ToolError(`There is no tool "${name}"`, "bad_request"));
2050
+ let ctx;
2051
+ try {
2052
+ ctx = contextOf(deps);
2053
+ } catch (err) {
2054
+ return errorResult(err);
2055
+ }
2056
+ try {
2057
+ const result = await found.run(ctx, args ?? {});
2058
+ return { ...result, content: result.content.map((c) => c.type === "text" ? { ...c, text: scrub(c.text, ctx.secrets) } : c) };
2059
+ } catch (err) {
2060
+ deps.log(`${name} failed: ${scrub(err instanceof Error ? err.message : String(err), ctx.secrets)}`);
2061
+ return errorResult(err, ctx.config);
2062
+ }
2063
+ }
2064
+
2065
+ // server.ts
2066
+ var deps = defaultDeps();
2067
+ var server = new McpServer({ name: "emitter", version: "1.0.0" }, { instructions: INSTRUCTIONS });
2068
+ for (const tool2 of TOOLS) {
2069
+ server.registerTool(tool2.name, { description: tool2.description, inputSchema: tool2.schema }, async (args) => runTool(deps, tool2.name, args));
2070
+ }
2071
+ await server.connect(new StdioServerTransport);