agentful 0.4.46 → 0.4.47

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.
@@ -1,639 +0,0 @@
1
- import { tool } from "@opencode-ai/plugin"
2
- import * as fs from "fs"
3
- import * as path from "path"
4
- import * as crypto from "crypto"
5
-
6
- /**
7
- * imagegen — generate a project-owned image asset via the LLM Gateway.
8
- *
9
- * The gateway (POST /v1/images/generations) owns provider/model resolution,
10
- * data-residency enforcement (air claim), key handling and usage tracking.
11
- * This tool only validates the output path, calls the gateway with the
12
- * session token, writes the bytes into the workspace and reports the
13
- * relative path. The workspace file is the source of truth — no base64 in
14
- * the tool output, no attachments (keeps WebSocket events and chat
15
- * persistence small).
16
- *
17
- * AI Act Art. 50 Abs. 2: the provider embeds the machine-readable marking
18
- * (FLUX on Azure: signed C2PA manifest + InvisMark watermark) and this tool
19
- * writes the bytes unchanged. Every image is entered in the provenance
20
- * ledger .agentful/asset-sources.json (shared with fetchimage) with
21
- * aiGenerated and whether the C2PA manifest was found in the bytes. The
22
- * alarm on a missing manifest lives in the gateway, which sees every image.
23
- *
24
- * Art. 50 Abs. 4 is the site owner's duty (a realistic AI image on a public
25
- * site needs a visible disclosure). Owner decision 2026-11-01: for images
26
- * that depict something that exists or could plausibly exist, the tool hands
27
- * the agent a ready label (EU "AI" icon + short text in the page language)
28
- * and asks it to tell the user; the user may have it removed, there is no
29
- * switch. The label is an overlay in the page, not burnt into the pixels:
30
- * re-encoding would break the provider's signed C2PA binding.
31
- */
32
-
33
- const GATEWAY_URL = (process.env.LLM_GATEWAY_URL || "").replace(/\/+$/, "")
34
- const SESSION_TOKEN = process.env.SESSION_TOKEN || ""
35
- const MAX_PER_SESSION = intEnv("IMAGEGEN_MAX_PER_SESSION", 3)
36
- const MAX_IMAGE_BYTES = intEnv("IMAGEGEN_MAX_BYTES", 8 * 1024 * 1024)
37
- const REQUEST_TIMEOUT_MS = intEnv("IMAGEGEN_TIMEOUT_MS", 120_000)
38
- const MAX_PROMPT_CHARS = 2_000
39
- const LEDGER_REL_PATH = path.join(".agentful", "asset-sources.json")
40
-
41
- const ALLOWED_EXTENSIONS: Record<string, string> = {
42
- ".png": "image/png",
43
- ".webp": "image/webp",
44
- ".jpg": "image/jpeg",
45
- ".jpeg": "image/jpeg",
46
- }
47
-
48
- const SIZE_BY_ASPECT: Record<string, string> = {
49
- "1:1": "1024x1024",
50
- "4:3": "1408x1056",
51
- "3:2": "1536x1024",
52
- "16:9": "1792x1024",
53
- "9:16": "1024x1792",
54
- "21:9": "2016x864",
55
- }
56
-
57
- function intEnv(name: string, fallback: number): number {
58
- const raw = Number(process.env[name])
59
- return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : fallback
60
- }
61
-
62
- function slugify(text: string): string {
63
- const slug = text
64
- .toLowerCase()
65
- .replace(/[^a-z0-9]+/g, "-")
66
- .replace(/^-+|-+$/g, "")
67
- .slice(0, 48)
68
- return slug || "image"
69
- }
70
-
71
- /**
72
- * Resolve and validate the output path. The model-supplied value is
73
- * untrusted input: reject anything that is absolute, traverses out of the
74
- * workspace, targets hidden/config/tooling paths or a non-image extension.
75
- * Symlink escapes are caught by realpath-checking the deepest existing
76
- * ancestor before any directory is created.
77
- */
78
- function resolveOutputPath(
79
- workspaceRoot: string,
80
- requested: string | undefined,
81
- defaultRelPath: string,
82
- extension: string
83
- ): { absPath: string; relPath: string } {
84
- const rel = (requested || defaultRelPath).trim()
85
-
86
- if (!rel) throw new Error("outputPath is empty")
87
- if (path.isAbsolute(rel)) {
88
- throw new Error(`outputPath must be relative to the project root: ${rel}`)
89
- }
90
-
91
- const normalized = path.normalize(rel)
92
- const segments = normalized.split(path.sep)
93
- if (segments.some((seg) => seg === "..")) {
94
- throw new Error(`outputPath must not traverse outside the project: ${rel}`)
95
- }
96
- if (segments.some((seg) => seg.startsWith("."))) {
97
- throw new Error(`outputPath must not target hidden or config paths: ${rel}`)
98
- }
99
- if (segments.includes("node_modules")) {
100
- throw new Error(`outputPath must not target node_modules: ${rel}`)
101
- }
102
-
103
- const ext = path.extname(normalized).toLowerCase()
104
- if (!(ext in ALLOWED_EXTENSIONS)) {
105
- throw new Error(
106
- `outputPath must end in ${Object.keys(ALLOWED_EXTENSIONS).join("/")}: ${rel}`
107
- )
108
- }
109
- if (ext !== extension && !(ext === ".jpeg" && extension === ".jpg")) {
110
- throw new Error(
111
- `outputPath extension ${ext} does not match requested format ${extension}`
112
- )
113
- }
114
-
115
- const rootResolved = fs.realpathSync(workspaceRoot)
116
- const absPath = path.resolve(rootResolved, normalized)
117
- if (!absPath.startsWith(rootResolved + path.sep)) {
118
- throw new Error(`outputPath resolves outside the project: ${rel}`)
119
- }
120
-
121
- // Symlink containment: realpath the deepest existing ancestor and require
122
- // it to still be inside the workspace before creating any directories.
123
- let ancestor = path.dirname(absPath)
124
- while (!fs.existsSync(ancestor)) ancestor = path.dirname(ancestor)
125
- const ancestorReal = fs.realpathSync(ancestor)
126
- if (
127
- ancestorReal !== rootResolved &&
128
- !ancestorReal.startsWith(rootResolved + path.sep)
129
- ) {
130
- throw new Error(`outputPath resolves outside the project: ${rel}`)
131
- }
132
-
133
- return { absPath, relPath: path.relative(rootResolved, absPath) }
134
- }
135
-
136
- /**
137
- * public/ and static/ are only served from the site root by bundlers
138
- * (Vite/Next/Astro/SvelteKit/Nuxt). A vanilla HTML project has no build
139
- * step — there public/ is just a folder and must be referenced by its real
140
- * relative path (prod finding 2026-07-10: /landscape.png 404'd in a vanilla
141
- * project because the hint assumed framework semantics).
142
- */
143
- function isBundlerProject(workspaceRoot: string): boolean {
144
- const markers = [
145
- "package.json",
146
- "vite.config.js", "vite.config.ts", "vite.config.mjs",
147
- "astro.config.mjs", "astro.config.ts",
148
- "next.config.js", "next.config.ts", "next.config.mjs",
149
- "svelte.config.js", "nuxt.config.ts",
150
- ]
151
- return markers.some((marker) => fs.existsSync(path.join(workspaceRoot, marker)))
152
- }
153
-
154
- function defaultAssetDir(workspaceRoot: string): string {
155
- if (isBundlerProject(workspaceRoot)) {
156
- if (fs.existsSync(path.join(workspaceRoot, "static"))) return "static/generated"
157
- return "public/generated"
158
- }
159
- return "assets/generated"
160
- }
161
-
162
- function sessionCountFile(sessionID: string): string {
163
- const safe = sessionID.replace(/[^a-zA-Z0-9_-]/g, "_")
164
- return path.join("/tmp", `imagegen-count-${safe}`)
165
- }
166
-
167
- function readSessionCount(sessionID: string): number {
168
- try {
169
- return parseInt(fs.readFileSync(sessionCountFile(sessionID), "utf8"), 10) || 0
170
- } catch {
171
- return 0
172
- }
173
- }
174
-
175
- function writeSessionCount(sessionID: string, count: number): void {
176
- try {
177
- fs.writeFileSync(sessionCountFile(sessionID), String(count))
178
- } catch {
179
- // Counter is best-effort; generation itself already succeeded.
180
- }
181
- }
182
-
183
- /**
184
- * Embedded C2PA manifest store, read from the container without decoding
185
- * or verifying the signature. PNG: `caBX` chunk. JPEG: APP11 segments with a
186
- * JUMBF box labelled `c2pa` (a large store spans several segments, so they
187
- * are read together). WebP: `C2PA` RIFF chunk. aiSourceType = the store
188
- * declares trainedAlgorithmicMedia (or the composite variant). Same rules as
189
- * detectContentCredentials() in llm-gateway-ts/src/images.ts. Not exported:
190
- * the engine registers every named export of a tool file as a tool.
191
- */
192
- function detectContentCredentials(bytes: Buffer): { c2pa: boolean; aiSourceType: boolean } {
193
- const parts: Buffer[] = []
194
- const png = bytes.length >= 8 && bytes.readUInt32BE(0) === 0x89504e47 && bytes.readUInt32BE(4) === 0x0d0a1a0a
195
- const jpeg = bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff
196
- const webp =
197
- bytes.length >= 12 && bytes.toString("latin1", 0, 4) === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP"
198
-
199
- if (png) {
200
- let i = 8
201
- while (i + 8 <= bytes.length) {
202
- const length = bytes.readUInt32BE(i)
203
- const kind = bytes.toString("latin1", i + 4, i + 8)
204
- if (kind === "caBX") parts.push(bytes.subarray(i + 8, i + 8 + length))
205
- if (kind === "IEND") break
206
- i += 12 + length
207
- }
208
- } else if (jpeg) {
209
- const app11: Buffer[] = []
210
- let i = 2
211
- while (i + 4 <= bytes.length && bytes[i] === 0xff) {
212
- const marker = bytes[i + 1]
213
- if (marker === 0xff) { i += 1; continue } // fill byte
214
- if (marker === 0xda || marker === 0xd9) break // start of scan / end of image
215
- if ((marker >= 0xd0 && marker <= 0xd7) || marker === 0x01) { i += 2; continue }
216
- const length = bytes.readUInt16BE(i + 2)
217
- if (marker === 0xeb) app11.push(bytes.subarray(i + 4, i + 2 + length))
218
- i += 2 + length
219
- }
220
- const joined = Buffer.concat(app11)
221
- if (joined.includes("jumb") && joined.includes("c2pa")) parts.push(joined)
222
- } else if (webp) {
223
- let i = 12
224
- while (i + 8 <= bytes.length) {
225
- const kind = bytes.toString("latin1", i, i + 4)
226
- const length = bytes.readUInt32LE(i + 4)
227
- if (kind === "C2PA") parts.push(bytes.subarray(i + 8, i + 8 + length))
228
- i += 8 + length + (length & 1)
229
- }
230
- }
231
-
232
- const store = Buffer.concat(parts)
233
- return {
234
- c2pa: store.length > 0,
235
- aiSourceType: store.toString("latin1").toLowerCase().includes("trainedalgorithmicmedia"),
236
- }
237
- }
238
-
239
- type Depicts = "real_world" | "fictional" | "abstract"
240
-
241
- type ImagegenLedgerEntry = {
242
- source: "imagegen"
243
- generatedAt: string
244
- bytes: number
245
- mime: string
246
- sha256: string
247
- aiGenerated: true
248
- c2pa: boolean
249
- aiSourceType: boolean
250
- depicts: Depicts
251
- labelSuggested: boolean
252
- provider?: string
253
- model?: string
254
- purpose?: string
255
- }
256
-
257
- // Icons and textures are not depictions of anything; everything else is
258
- // treated as possibly realistic unless the agent says otherwise.
259
- function defaultDepicts(purpose: string | undefined): Depicts {
260
- return purpose === "icon" || purpose === "texture" ? "abstract" : "real_world"
261
- }
262
-
263
- // Platform languages (frontend/src/i18n/locales). Plain words, no
264
- // abbreviation except "AI"/"KI" (EU icon guidance).
265
- const LABEL_TEXT: Record<string, string> = {
266
- de: "KI-generiert",
267
- en: "AI-generated",
268
- es: "Generado con IA",
269
- fr: "Généré par IA",
270
- it: "Generato con IA",
271
- pl: "Wygenerowane przez AI",
272
- ru: "Создано ИИ",
273
- uk: "Створено ШІ",
274
- }
275
-
276
- /** `lang` of the page shell, if the project declares one. */
277
- function detectPageLanguage(workspaceRoot: string): string | null {
278
- const candidates = ["index.html", "src/app.html", "public/index.html", "app/layout.tsx", "app/layout.jsx", "src/app/layout.tsx"]
279
- for (const rel of candidates) {
280
- try {
281
- const text = fs.readFileSync(path.join(workspaceRoot, rel), "utf8").slice(0, 20_000)
282
- const match = /<html[^>]*\slang=["'{]*([a-zA-Z]{2})/.exec(text)
283
- if (match) return match[1].toLowerCase()
284
- } catch {
285
- // not there
286
- }
287
- }
288
- return null
289
- }
290
-
291
- // EU basic icon "AI" (white variant: white disc, dark letters), from the
292
- // Commission's icon set (digital-strategy.ec.europa.eu, "EU Icons for
293
- // labelling AI-generated content"; free to use, no attribution). Reduced to
294
- // two paths with inline fills: the original carries an id and a <style>
295
- // block with generic class names that would leak into the user's page.
296
- const EU_AI_ICON_SVG =
297
- '<svg viewBox="89.28 100.72 365.5 365.5" width="16" height="16" aria-hidden="true" focusable="false">' +
298
- '<path fill="#fff" fill-rule="evenodd" d="M272.03,100.72c100.92,0,182.74,81.82,182.74,182.75s-81.82,182.74-182.74,182.74-182.75-81.82-182.75-182.74,81.82-182.75,182.75-182.75"/>' +
299
- '<path fill="#1d1d1b" d="M170.79,353.74c-1.08,0-2.05-.43-2.92-1.31-.88-.87-1.31-1.84-1.31-2.92,0-.67.07-1.27.2-1.81l47.34-129.32c.4-1.48,1.24-2.79,2.52-3.93,1.27-1.14,3.05-1.71,5.34-1.71h29.81c2.28,0,4.06.57,5.34,1.71,1.27,1.14,2.11,2.45,2.52,3.93l47.14,129.32c.27.54.4,1.14.4,1.81,0,1.08-.44,2.05-1.31,2.92s-1.91,1.31-3.12,1.31h-24.78c-2.01,0-3.52-.5-4.53-1.51-1.01-1.01-1.65-1.91-1.91-2.72l-7.86-20.55h-53.78l-7.65,20.55c-.27.81-.88,1.71-1.81,2.72-.94,1.01-2.55,1.51-4.83,1.51h-24.78ZM218.13,299.96h37.47l-18.93-53.18-18.53,53.18Z"/>' +
300
- '<path fill="#1d1d1b" d="M328.11,353.74c-1.48,0-2.69-.47-3.63-1.41-.94-.94-1.41-2.15-1.41-3.63v-130.93c0-1.48.47-2.68,1.41-3.63s2.15-1.41,3.63-1.41h26.99c1.48,0,2.68.47,3.63,1.41.94.94,1.41,2.15,1.41,3.63v130.93c0,1.48-.47,2.69-1.41,3.63-.94.94-2.15,1.41-3.63,1.41h-26.99Z"/>' +
301
- "</svg>"
302
-
303
- const LABEL_CSS =
304
- ":where(.ai-image){position:relative}\n" +
305
- ".ai-label{position:absolute;left:.5rem;bottom:.5rem;z-index:2;display:inline-flex;align-items:center;" +
306
- "gap:.35em;padding:.2em .6em .2em .25em;border-radius:999px;background:rgba(17,17,17,.72);color:#fff;" +
307
- "font:600 12px/1.2 system-ui,-apple-system,'Segoe UI',sans-serif;pointer-events:none}\n" +
308
- ".ai-label svg{width:1.3em;height:1.3em;flex:none}"
309
-
310
- function labelMarkup(text: string): string {
311
- return `<span class="ai-label" data-ai-label="generated">${EU_AI_ICON_SVG}<span>${text}</span></span>`
312
- }
313
-
314
- // The label is positioned against the "ai-image" element, so that element
315
- // holds only the image and the label. postgen_fixes.repair_ai_label_wrap
316
- // builds the same wrapper when the agent puts the class on a <figure> with a
317
- // caption (plan ki-label-platzierung-deterministisch § 4.3; a test keeps the
318
- // two equal).
319
- const AI_IMAGE_WRAPPER = '<span class="ai-image" style="display:block">'
320
-
321
- function labelBlock(text: string): string {
322
- return `${AI_IMAGE_WRAPPER}<img src="…" alt="…">${labelMarkup(text)}</span>`
323
- }
324
-
325
- function writeAtomic(absPath: string, text: string): void {
326
- fs.mkdirSync(path.dirname(absPath), { recursive: true })
327
- const temp = path.join(path.dirname(absPath), `.imagegen-${process.pid}-${crypto.randomBytes(6).toString("hex")}.tmp`)
328
- try {
329
- fs.writeFileSync(temp, text, { flag: "wx" })
330
- fs.renameSync(temp, absPath)
331
- } finally {
332
- fs.rmSync(temp, { force: true })
333
- }
334
- }
335
-
336
- /**
337
- * Same ledger and the same rules as recordProvenance() in fetchimage.ts:
338
- * only the tools write it (.agentful/ is denied to edit/write), a .agentful
339
- * that resolves outside the project is refused, an unreadable ledger is kept
340
- * as .bak and a fresh one started.
341
- */
342
- function recordProvenance(workspaceRoot: string, relPath: string, entry: ImagegenLedgerEntry): void {
343
- const rootResolved = fs.realpathSync(workspaceRoot)
344
- const ledgerPath = path.join(rootResolved, LEDGER_REL_PATH)
345
- const ledgerDir = path.dirname(ledgerPath)
346
- if (fs.existsSync(ledgerDir)) {
347
- const real = fs.realpathSync(ledgerDir)
348
- if (!real.startsWith(rootResolved + path.sep)) throw new Error(".agentful resolves outside the project")
349
- }
350
- let ledger: { version: number; assets: Record<string, unknown> } = { version: 1, assets: {} }
351
- if (fs.existsSync(ledgerPath)) {
352
- const raw = fs.readFileSync(ledgerPath, "utf8")
353
- try {
354
- const parsed = JSON.parse(raw)
355
- if (parsed && typeof parsed === "object" && parsed.assets && typeof parsed.assets === "object") ledger = parsed
356
- else throw new Error("unexpected shape")
357
- } catch {
358
- writeAtomic(`${ledgerPath}.bak`, raw)
359
- }
360
- }
361
- ledger.assets[relPath.split(path.sep).join("/")] = entry
362
- writeAtomic(ledgerPath, JSON.stringify(ledger, null, 2) + "\n")
363
- }
364
-
365
- export default tool({
366
- description:
367
- "Generate an image asset (hero, illustration, texture, product mockup) and save it into the project. " +
368
- "Returns the saved project path. Vanilla projects must resolve that path relative to the consuming " +
369
- "HTML/CSS/JS file; bundler public/static assets get a site-root URL. " +
370
- "Realistic scenes are fine (they get a visible AI label); never an identifiable real person, " +
371
- "third-party logos or brands, AI people presented as the user's actual team or customers, " +
372
- "or an AI image presented as the user's actual product, premises or work. " +
373
- "Real photos the user owns come first: use the ones in the project or ask the user for them.",
374
- args: {
375
- prompt: tool.schema
376
- .string()
377
- .describe("Detailed visual description of the image to generate"),
378
- outputPath: tool.schema
379
- .string()
380
- .optional()
381
- .describe(
382
- "Relative output path inside the project, e.g. public/generated/hero.webp. " +
383
- "Extension must match format. Defaults to a generated path."
384
- ),
385
- purpose: tool.schema
386
- .enum(["hero", "card", "background", "icon", "texture", "product", "illustration"])
387
- .optional()
388
- .describe("What the image is used for (influences default naming)"),
389
- aspectRatio: tool.schema
390
- .enum(["1:1", "4:3", "3:2", "16:9", "9:16", "21:9"])
391
- .optional()
392
- .describe("Aspect ratio of the image (default 3:2)"),
393
- format: tool.schema
394
- .enum(["png", "webp", "jpeg"])
395
- .optional()
396
- .describe("Output format (default webp; use png for transparency)"),
397
- transparent: tool.schema
398
- .boolean()
399
- .optional()
400
- .describe("Request a transparent background (png/webp only)"),
401
- depicts: tool.schema
402
- .enum(["real_world", "fictional", "abstract"])
403
- .optional()
404
- .describe(
405
- "What the image shows: real_world = people, places, products, food, rooms or events that exist " +
406
- "or could plausibly exist (gets a visible AI label); fictional = evidently unreal (fantasy, " +
407
- "cartoon, drawn illustration); abstract = patterns, gradients, icons, textures. " +
408
- "Default: abstract for icon/texture, otherwise real_world."
409
- ),
410
- labelLanguage: tool.schema
411
- .string()
412
- .optional()
413
- .describe("Language of the page as ISO 639-1 code (e.g. de, en) for the AI label text; default: the page's lang attribute"),
414
- },
415
- async execute(args, context) {
416
- if (!GATEWAY_URL || !SESSION_TOKEN) {
417
- throw new Error(
418
- "Image generation is not configured for this session (no gateway credentials). " +
419
- "Use CSS/SVG placeholders instead."
420
- )
421
- }
422
-
423
- const prompt = (args.prompt || "").trim()
424
- if (!prompt) throw new Error("prompt must not be empty")
425
- if (prompt.length > MAX_PROMPT_CHARS) {
426
- throw new Error(`prompt too long (${prompt.length} > ${MAX_PROMPT_CHARS} chars)`)
427
- }
428
-
429
- const used = readSessionCount(context.sessionID)
430
- if (used >= MAX_PER_SESSION) {
431
- throw new Error(
432
- `Image limit reached for this run (${MAX_PER_SESSION}). ` +
433
- "Reuse already generated assets or CSS/SVG placeholders."
434
- )
435
- }
436
-
437
- const format = args.format || "webp"
438
- if (args.transparent && format === "jpeg") {
439
- throw new Error("transparent backgrounds require png or webp format")
440
- }
441
- const extension = format === "jpeg" ? ".jpg" : `.${format}`
442
- const size = SIZE_BY_ASPECT[args.aspectRatio || "3:2"]
443
-
444
- const workspaceRoot = context.directory
445
- const hash = crypto.createHash("sha1").update(prompt).digest("hex").slice(0, 8)
446
- const baseName = slugify(args.purpose ? `${args.purpose}-${prompt}` : prompt)
447
- const defaultRelPath = path.join(
448
- defaultAssetDir(workspaceRoot),
449
- `${baseName}-${hash}${extension}`
450
- )
451
- const { absPath, relPath } = resolveOutputPath(
452
- workspaceRoot,
453
- args.outputPath,
454
- defaultRelPath,
455
- extension
456
- )
457
-
458
- const startedAt = Date.now()
459
- let response: Response
460
- try {
461
- response = await fetch(`${GATEWAY_URL}/v1/images/generations`, {
462
- method: "POST",
463
- headers: {
464
- "Content-Type": "application/json",
465
- Authorization: `Bearer ${SESSION_TOKEN}`,
466
- },
467
- body: JSON.stringify({
468
- model: process.env.IMAGE_MODEL || "auto",
469
- prompt,
470
- size,
471
- response_format: "b64_json",
472
- output_format: format,
473
- ...(args.transparent ? { background: "transparent" } : {}),
474
- }),
475
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
476
- })
477
- } catch (error) {
478
- throw new Error(`Image generation request failed: ${error}`)
479
- }
480
-
481
- if (!response.ok) {
482
- let message = `${response.status}`
483
- try {
484
- const body = (await response.json()) as {
485
- error?: { message?: string } | string
486
- }
487
- const err = body?.error
488
- message =
489
- typeof err === "string" ? err : err?.message || JSON.stringify(body).slice(0, 300)
490
- } catch {
491
- // keep status-only message
492
- }
493
- throw new Error(`Image generation failed: ${message}`)
494
- }
495
-
496
- const result = (await response.json()) as {
497
- data?: Array<{ b64_json?: string }>
498
- model?: string
499
- provider?: string
500
- mime?: string
501
- }
502
- const b64 = result.data?.[0]?.b64_json
503
- if (!b64) {
504
- throw new Error("Image generation returned no image data")
505
- }
506
-
507
- const bytes = Buffer.from(b64, "base64")
508
- if (bytes.length === 0) {
509
- throw new Error("Image generation returned empty image data")
510
- }
511
- if (bytes.length > MAX_IMAGE_BYTES) {
512
- throw new Error(
513
- `Generated image too large (${bytes.length} bytes > ${MAX_IMAGE_BYTES})`
514
- )
515
- }
516
-
517
- // Providers do not always honor the requested format (e.g. Gemini always
518
- // returns PNG). The gateway reports the actual mime; keep the file
519
- // extension truthful by swapping it within the image-extension allowlist.
520
- let finalAbsPath = absPath
521
- let finalRelPath = relPath
522
- let finalMime = ALLOWED_EXTENSIONS[extension]
523
- const reportedMime = result.mime
524
- if (reportedMime && reportedMime !== finalMime) {
525
- const actualExt = Object.keys(ALLOWED_EXTENSIONS).find(
526
- (candidate) => ALLOWED_EXTENSIONS[candidate] === reportedMime && candidate !== ".jpeg"
527
- )
528
- if (actualExt) {
529
- finalAbsPath = absPath.slice(0, -path.extname(absPath).length) + actualExt
530
- finalRelPath = relPath.slice(0, -path.extname(relPath).length) + actualExt
531
- finalMime = reportedMime
532
- }
533
- }
534
-
535
- fs.mkdirSync(path.dirname(finalAbsPath), { recursive: true })
536
- fs.writeFileSync(finalAbsPath, bytes)
537
- writeSessionCount(context.sessionID, used + 1)
538
-
539
- // Visible label (Art. 50 Abs. 4, owner decision 2026-11-01).
540
- const depicts: Depicts = args.depicts || defaultDepicts(args.purpose)
541
- const labelSuggested = depicts === "real_world"
542
- const requestedLanguage = (args.labelLanguage || "").trim().toLowerCase().slice(0, 2)
543
- const labelLanguage =
544
- (requestedLanguage in LABEL_TEXT ? requestedLanguage : null) ||
545
- (() => {
546
- const detected = detectPageLanguage(workspaceRoot)
547
- return detected && detected in LABEL_TEXT ? detected : "en"
548
- })()
549
-
550
- // Provenance (Art. 50 Abs. 2). The image is already written and paid
551
- // for, so a ledger problem must not fail the call; it shows up in the
552
- // metadata instead.
553
- const credentials = detectContentCredentials(bytes)
554
- let provenanceRecorded = true
555
- try {
556
- recordProvenance(workspaceRoot, finalRelPath, {
557
- source: "imagegen",
558
- generatedAt: new Date().toISOString(),
559
- bytes: bytes.length,
560
- mime: finalMime,
561
- sha256: crypto.createHash("sha256").update(bytes).digest("hex"),
562
- aiGenerated: true,
563
- c2pa: credentials.c2pa,
564
- aiSourceType: credentials.aiSourceType,
565
- depicts,
566
- labelSuggested,
567
- ...(result.provider ? { provider: result.provider } : {}),
568
- ...(result.model ? { model: result.model } : {}),
569
- ...(args.purpose ? { purpose: args.purpose } : {}),
570
- })
571
- } catch {
572
- provenanceRecorded = false
573
- }
574
-
575
- // Bundler projects serve public/ and static/ from the site root. Vanilla
576
- // projects are served as-is, so there is no single drop-in URL: CSS URLs
577
- // resolve from the stylesheet while HTML URLs resolve from the document.
578
- const isBundler = isBundlerProject(workspaceRoot)
579
- const publicUrl = isBundler
580
- ? finalRelPath.replace(/^(public|static)\//, "/").replace(/^(?!\/)/, "/")
581
- : null
582
- const durationMs = Date.now() - startedAt
583
- const remaining = MAX_PER_SESSION - used - 1
584
- const referenceGuidance = isBundler
585
- ? `Reference it as ${publicUrl} in the app.`
586
- :
587
- `This is a project-root path, not a drop-in URL. ` +
588
- `From a root HTML document use ./${finalRelPath}; from css/style.css use ../${finalRelPath}. ` +
589
- `For any other consuming file, compute the URL relative to that file.`
590
-
591
- const labelGuidance = labelSuggested
592
- ? "\n\nAI label (EU AI Act Art. 50(4): unless the site is purely private, AI images that could be " +
593
- "taken for real must be visibly disclosed): " +
594
- "wherever this image is shown as <img>, wrap exactly the image and this label, nothing else:\n" +
595
- `${labelBlock(LABEL_TEXT[labelLanguage])}\n` +
596
- "A caption, text or buttons go outside this wrapper (in a <figure>, the <figcaption> follows it); " +
597
- "inside it, the label would sit on that text instead of the image. " +
598
- 'For a CSS background image, or an <img> that fills its container (position:absolute or height:100%, ' +
599
- 'as in a cover hero), give the class "ai-image" to that container instead ' +
600
- "(keep that element's own position such as absolute) and place the label inside it.\n" +
601
- "Add this CSS once to the global stylesheet:\n" +
602
- `${LABEL_CSS}\n` +
603
- 'In JSX write className instead of class and style={{ display: "block" }}. The label text is in ' +
604
- `"${labelLanguage}"; if the page uses another language, translate only that text and keep the icon. ` +
605
- "Do not use it as a link preview (og:image, twitter:image): previews show it without the label. " +
606
- "In your reply, tell the user in one sentence that the image carries a visible AI label because " +
607
- "AI images that could be taken for real must be visibly disclosed unless the site is purely " +
608
- "private, and that you can remove it on request, " +
609
- "in which case disclosing it is their responsibility as the site operator. " +
610
- "If the user asks to remove the label, remove it and do not add it back."
611
- : `\n\nNo visible AI label needed (depicts: ${depicts}).`
612
-
613
- return {
614
- title: "Generated image",
615
- output:
616
- `Generated image at ${finalRelPath} (${bytes.length} bytes, ${size}). ` +
617
- `${referenceGuidance} ` +
618
- `${remaining} image generation(s) left in this run.` +
619
- labelGuidance,
620
- metadata: {
621
- path: finalRelPath,
622
- projectPath: finalRelPath,
623
- publicUrl,
624
- mime: finalMime,
625
- size,
626
- bytes: bytes.length,
627
- provider: result.provider,
628
- model: result.model,
629
- durationMs,
630
- c2pa: credentials.c2pa,
631
- aiSourceType: credentials.aiSourceType,
632
- provenanceRecorded,
633
- depicts,
634
- labelSuggested,
635
- labelLanguage,
636
- },
637
- }
638
- },
639
- })
@@ -1,8 +0,0 @@
1
- {
2
- "name": "agentful-engine-tools",
3
- "private": true,
4
- "type": "module",
5
- "dependencies": {
6
- "@opencode-ai/plugin": "*"
7
- }
8
- }