@eum-agent/llm-capability-image 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +437 -179
  2. package/package.json +5 -5
  3. package/ui/ui.js +4676 -61
package/dist/index.js CHANGED
@@ -1,8 +1,60 @@
1
- import { constants, existsSync } from "node:fs";
1
+ import { existsSync } from "node:fs";
2
+ import { basename, dirname } from "node:path";
2
3
  import { fileURLToPath } from "node:url";
3
4
  import { z } from "zod";
4
5
  import { randomUUID } from "node:crypto";
5
- import { open, realpath, stat } from "node:fs/promises";
6
+ //#region src/artifact-origins.ts
7
+ const PATTERN = new RegExp(`^https://([a-z0-9][a-z0-9-]*)\\*((?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?){2,})$`);
8
+ const SHARD = /^[a-z0-9-]+$/;
9
+ function declarationOf(entry) {
10
+ const [, prefix, suffix] = PATTERN.exec(entry) ?? [];
11
+ if (prefix && suffix) return {
12
+ kind: "pattern",
13
+ prefix,
14
+ suffix
15
+ };
16
+ if (entry.includes("*")) return void 0;
17
+ let url;
18
+ try {
19
+ url = new URL(entry);
20
+ } catch {
21
+ return;
22
+ }
23
+ if (url.protocol !== "https:" || url.username || url.password || url.origin !== entry) return void 0;
24
+ return {
25
+ kind: "exact",
26
+ origin: entry,
27
+ host: url.hostname,
28
+ port: Number(url.port || 443)
29
+ };
30
+ }
31
+ function isArtifactOriginEntry(entry) {
32
+ return declarationOf(entry) !== void 0;
33
+ }
34
+ function artifactOriginMatches(entries, origin) {
35
+ return entries.some((entry) => {
36
+ const declaration = declarationOf(entry);
37
+ if (declaration?.kind === "exact") return declaration.origin === origin;
38
+ if (!declaration) return false;
39
+ const head = `https://${declaration.prefix}`;
40
+ if (!origin.startsWith(head) || !origin.endsWith(declaration.suffix)) return false;
41
+ return SHARD.test(origin.slice(head.length, origin.length - declaration.suffix.length));
42
+ });
43
+ }
44
+ function artifactOriginGrant(entry) {
45
+ const declaration = declarationOf(entry);
46
+ if (!declaration) return void 0;
47
+ return declaration.kind === "exact" ? {
48
+ host: declaration.host,
49
+ port: declaration.port,
50
+ exact: true
51
+ } : {
52
+ host: `${declaration.prefix}*${declaration.suffix}`,
53
+ port: 443,
54
+ exact: false
55
+ };
56
+ }
57
+ //#endregion
6
58
  //#region src/runtime/models/redact.ts
7
59
  function redactables(type, secrets) {
8
60
  const out = { ...secrets };
@@ -18,7 +70,6 @@ function redactables(type, secrets) {
18
70
  }
19
71
  return out;
20
72
  }
21
- /** Adds every opaque token string to the call's redaction set, including rotated tokens. */
22
73
  function trackLogin(handle, values) {
23
74
  let count = 0;
24
75
  function record(value) {
@@ -42,7 +93,6 @@ function trackLogin(handle, values) {
42
93
  }
43
94
  //#endregion
44
95
  //#region src/runtime/models/binding-port.ts
45
- /** Keeps construction, generation and deferred asset errors inside the same redaction lifetime. */
46
96
  function createImageBindingPort(adapter, call) {
47
97
  const values = { ...call.secrets };
48
98
  for (const [key, value] of Object.entries(call.secrets)) try {
@@ -102,7 +152,6 @@ function createImageBindingPort(adapter, call) {
102
152
  }
103
153
  //#endregion
104
154
  //#region src/capability.ts
105
- /** Validates the Image adapter shape without touching credentials or network. */
106
155
  function assertImageAdapter(adapter) {
107
156
  const value = adapter;
108
157
  if (!value || typeof value.models !== "function" || typeof value.createPort !== "function") throw new Error("unsupported-binding: invalid Image adapter");
@@ -124,10 +173,7 @@ const descriptors = z.array(z.strictObject({
124
173
  "audio",
125
174
  "video"
126
175
  ])).nonempty().refine(unique),
127
- artifactOrigins: z.array(z.string().url().refine((value) => {
128
- const url = new URL(value);
129
- return url.protocol === "https:" && !url.username && !url.password && url.origin === value;
130
- })).refine(unique).optional(),
176
+ artifactOrigins: z.array(z.string().refine(isArtifactOriginEntry)).refine(unique).optional(),
131
177
  operations: z.array(z.strictObject({
132
178
  id: z.string().trim().min(1),
133
179
  inputKinds: z.array(z.string().min(1)).refine(unique),
@@ -136,7 +182,6 @@ const descriptors = z.array(z.strictObject({
136
182
  paramsSchema: z.custom((value) => value instanceof z.ZodType)
137
183
  }).refine((value) => value.minInputs <= value.maxInputs)).nonempty().refine((values) => unique(values.map((value) => value.id)))
138
184
  })).refine((values) => unique(values.map((value) => value.id)));
139
- /** Validates descriptors at their capability boundary, including strict lossless operation schemas. */
140
185
  function generationModelsOf(protocol, context) {
141
186
  const adapter = protocol.adapters.image;
142
187
  if (!adapter) return [];
@@ -183,7 +228,6 @@ function imageModelFor(input) {
183
228
  operations
184
229
  } : void 0;
185
230
  }
186
- /** Registered Image ability; ordinary parameter edits affect only the next submission. */
187
231
  const imageCapability = {
188
232
  id: "image",
189
233
  tools: ["model_image_generate"],
@@ -220,7 +264,7 @@ const imageCapability = {
220
264
  descriptor: { operations: model?.operations.map((operation) => ({
221
265
  id: operation.id,
222
266
  inputKinds: [...operation.inputKinds],
223
- parameterSchema: operation.paramsSchema.toJSONSchema({ io: "input" })
267
+ parameterSchema: structuredClone(operation.paramsSchema.toJSONSchema({ io: "input" }))
224
268
  })) ?? [] }
225
269
  };
226
270
  },
@@ -238,7 +282,6 @@ const imageCapability = {
238
282
  };
239
283
  //#endregion
240
284
  //#region src/guidance.ts
241
- /** Image generation guidance withdraws with the owning tool. */
242
285
  const GUIDANCE = {
243
286
  title: "Images",
244
287
  entries: [{
@@ -247,46 +290,211 @@ const GUIDANCE = {
247
290
  }]
248
291
  };
249
292
  //#endregion
250
- //#region src/output-schema.ts
251
- /** Validates complete owner business results and bounded recoverable delivery failures. */
252
- /** Adds the standard failure envelope and bounded text refusals to an owner's result schema. */
253
- function toolOutputSchema(body, input, name) {
254
- return z.union([
255
- body,
256
- z.strictObject({
257
- ok: z.literal(false),
258
- error: z.strictObject({
259
- code: z.string().min(1).max(128),
260
- message: z.string().refine((value) => [...value].length <= 256).meta({ maxLength: 256 }),
261
- retryable: z.boolean(),
262
- field: z.string().max(256).optional(),
263
- maximum: z.number().finite().optional()
264
- }),
265
- next: z.strictObject({
266
- tool: z.literal(name),
267
- arguments: input
268
- }).nullable(),
269
- execution: z.strictObject({ state: z.enum([
270
- "not-started",
271
- "committed",
272
- "unknown"
273
- ]) }).optional()
274
- }),
275
- z.string().max(1024)
276
- ]);
293
+ //#region src/body-document.ts
294
+ const LocalBodyRefSchema = z.strictObject({
295
+ bodyId: z.uuid(),
296
+ codec: z.enum([
297
+ "utf8-text",
298
+ "json",
299
+ "opaque"
300
+ ]),
301
+ formatVersion: z.literal(1),
302
+ byteLength: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
303
+ sha256: z.string().regex(/^[a-f0-9]{64}$/)
304
+ });
305
+ async function captureTextBody(text, ctx) {
306
+ ctx.signal.throwIfAborted();
307
+ const writer = await ctx.openBody("utf8-text", ctx.signal);
308
+ const encoder = new TextEncoder();
309
+ let offset = 0;
310
+ let index = 0;
311
+ try {
312
+ while (index < text.length) {
313
+ ctx.signal.throwIfAborted();
314
+ const chunk = /* @__PURE__ */ new Uint8Array(65536);
315
+ let end = Math.min(text.length, index + 32768);
316
+ if (end < text.length && /[\uD800-\uDBFF]/u.test(text[end - 1])) end--;
317
+ const { read, written } = encoder.encodeInto(text.slice(index, end), chunk);
318
+ if (!read) throw new Error("text_encoding_failed");
319
+ await writer.write(offset, chunk.subarray(0, written), ctx.signal);
320
+ offset += written;
321
+ index += read;
322
+ }
323
+ return (await writer.seal(ctx.signal)).body;
324
+ } catch (error) {
325
+ await writer.abort();
326
+ throw error;
327
+ }
328
+ }
329
+ function createTextDocuments(render) {
330
+ const documents = /* @__PURE__ */ new WeakMap();
331
+ const prepare = (value, ctx) => {
332
+ const key = typeof value === "object" && value !== null ? value : void 0;
333
+ const prior = key ? documents.get(key) : void 0;
334
+ if (prior) return prior;
335
+ const work = (async () => {
336
+ const input = render(value);
337
+ const literals = input.nodes.filter((node) => node.kind === "literal");
338
+ const lengths = literals.map((node) => new TextEncoder().encode(node.text).byteLength);
339
+ if (literals.length === input.nodes.length && (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384 || input.nodes.length > 256)) {
340
+ const body = await captureTextBody(literals.map((node) => node.text).join(""), ctx);
341
+ return {
342
+ formatVersion: 1,
343
+ rendererVersion: 1,
344
+ nodes: [{
345
+ id: "text",
346
+ kind: "text-range",
347
+ body,
348
+ startByte: 0,
349
+ endByte: body.byteLength
350
+ }]
351
+ };
352
+ }
353
+ if (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384) {
354
+ const nodes = [];
355
+ const all = lengths.reduce((sum, length) => sum + length, 0) > 16384;
356
+ for (const node of input.nodes) {
357
+ if (node.kind !== "literal" || !all && new TextEncoder().encode(node.text).byteLength <= 4096) {
358
+ nodes.push(node);
359
+ continue;
360
+ }
361
+ const body = await captureTextBody(node.text, ctx);
362
+ nodes.push({
363
+ id: node.id,
364
+ kind: "text-range",
365
+ body,
366
+ startByte: 0,
367
+ endByte: body.byteLength
368
+ });
369
+ }
370
+ return {
371
+ ...input,
372
+ nodes
373
+ };
374
+ }
375
+ return input;
376
+ })();
377
+ if (key) documents.set(key, work);
378
+ return work;
379
+ };
380
+ return {
381
+ prepare,
382
+ formatModel: prepare
383
+ };
277
384
  }
278
385
  //#endregion
279
- //#region src/image-generation.ts
280
- const target = z.strictObject({
281
- providerId: z.string().min(1).max(512).describe("Exact configured provider connection ID from model_list."),
282
- model: z.string().min(1).max(256).describe("Exact configured image model ID from model_list.")
386
+ //#region src/tool-data.ts
387
+ const variant = z.strictObject({
388
+ id: z.string().regex(/^[a-f0-9]{64}$/),
389
+ mediaType: z.string().min(1),
390
+ size: z.number().int().positive(),
391
+ width: z.number().int().positive().optional(),
392
+ height: z.number().int().positive().optional()
393
+ });
394
+ const file = variant.extend({
395
+ name: z.string().min(1).max(200),
396
+ forModel: variant.optional()
283
397
  });
398
+ const ImageToolDataSchema = z.discriminatedUnion("ok", [z.strictObject({
399
+ ok: z.literal(true),
400
+ committed: z.literal(true),
401
+ target: z.strictObject({
402
+ providerId: z.string(),
403
+ model: z.string()
404
+ }),
405
+ text: LocalBodyRefSchema.optional(),
406
+ textError: z.literal("source_capture_failed").optional(),
407
+ fileIds: z.array(z.string().regex(/^[a-f0-9]{64}$/)).min(1).max(8),
408
+ files: z.array(file).min(1).max(8)
409
+ }).refine((data) => data.text !== void 0 !== (data.textError !== void 0)), z.strictObject({
410
+ ok: z.literal(false),
411
+ code: z.string().min(1).max(128),
412
+ message: z.string().max(1024),
413
+ resultState: z.enum([
414
+ "not-submitted",
415
+ "unknown",
416
+ "not-delivered"
417
+ ])
418
+ })]);
419
+ //#endregion
420
+ //#region src/tool-document.ts
421
+ function imageDocument(data) {
422
+ if (!data.ok) return {
423
+ formatVersion: 1,
424
+ rendererVersion: 1,
425
+ nodes: [{
426
+ id: "failure",
427
+ kind: "literal",
428
+ text: data.message
429
+ }]
430
+ };
431
+ return {
432
+ formatVersion: 1,
433
+ rendererVersion: 1,
434
+ nodes: [
435
+ {
436
+ id: "target",
437
+ kind: "literal",
438
+ text: `Image model ${data.target.providerId}/${data.target.model}: ${data.files.length} generated image(s).\n`
439
+ },
440
+ ...data.text ? [{
441
+ id: "text",
442
+ kind: "text-range",
443
+ body: data.text,
444
+ startByte: 0,
445
+ endByte: data.text.byteLength
446
+ }] : [{
447
+ id: "text-unavailable",
448
+ kind: "literal",
449
+ text: "The image was generated and saved, but its accompanying text could not be captured.\n"
450
+ }],
451
+ ...data.files.map((file, index) => ({
452
+ id: `image-${index}`,
453
+ kind: "media-ref",
454
+ file
455
+ }))
456
+ ]
457
+ };
458
+ }
459
+ function imageResult(data) {
460
+ return {
461
+ data,
462
+ execution: { state: data.ok ? "committed" : data.resultState === "not-submitted" ? "not-started" : "unknown" },
463
+ isError: !data.ok,
464
+ ...!data.ok ? { error: {
465
+ code: data.code,
466
+ retryable: false
467
+ } } : {},
468
+ presentation: {
469
+ type: "image-generated",
470
+ schemaVersion: 1,
471
+ state: data.ok ? data.textError ? "partial" : "ready" : "error",
472
+ summary: data.ok ? `${data.files.length} image(s) generated` : data.message.slice(0, 512),
473
+ fields: data.ok ? {
474
+ providerId: data.target.providerId,
475
+ model: data.target.model,
476
+ count: data.files.length,
477
+ committed: true
478
+ } : {
479
+ code: data.code,
480
+ resultState: data.resultState
481
+ },
482
+ actions: [],
483
+ bodyRefs: data.ok && data.text ? [data.text] : []
484
+ }
485
+ };
486
+ }
487
+ //#endregion
488
+ //#region src/image-generation.ts
284
489
  const common = {
285
- target: target.optional().describe("Exact configured target; otherwise use the global image default."),
286
- prompt: z.string().refine((value) => value.trim().length > 0 && [...value.trim()].length <= 32e3, { message: "The prompt must contain 1–32000 Unicode characters after trimming." }).meta({
490
+ target: z.strictObject({
491
+ providerId: z.string().min(1).max(512).describe("Exact configured provider connection ID from model_list."),
492
+ model: z.string().min(1).max(256).describe("Exact configured image model ID from model_list.")
493
+ }).optional().describe("Exact configured target; otherwise use the global image default."),
494
+ prompt: z.string().refine((value) => value.trim().length > 0 && [...value.trim()].length <= 32e3, { message: "The prompt must contain 1\u201332000 Unicode characters after trimming." }).meta({
287
495
  minLength: 1,
288
496
  maxLength: 32e3
289
- }).describe("Image instructions; 1–32000 Unicode characters after trimming."),
497
+ }).describe("Image instructions; 1\u201332000 Unicode characters after trimming."),
290
498
  params: z.record(z.string(), z.unknown()).default({}).describe("Parameters must match the selected model operation schema; omit to use that model default.")
291
499
  };
292
500
  const reference = z.union([z.strictObject({ fileId: z.string().regex(/^[0-9a-f]{64}$/).describe("Stored image file ID from this session.") }), z.strictObject({ path: z.string().min(1).max(4096).describe("Local image path to authorize before submission.") })]);
@@ -298,9 +506,8 @@ const edit = {
298
506
  ...common,
299
507
  operation: z.literal("edit").describe("Edit existing images selected by one reference mechanism.")
300
508
  };
301
- const explicit = { reference_images: z.array(reference).min(1).max(14).describe("1–14 ordered references, subject to the selected model limit; mutually exclusive with recent count.") };
302
- const recent = { num_last_images_to_include: z.number().int().min(1).max(14).describe("1–14 most recent distinct session images; mutually exclusive with explicit references.") };
303
- /** Strict create/edit shapes, with paired explicit targets and mutually exclusive reference selectors. */
509
+ const explicit = { reference_images: z.array(reference).min(1).max(14).describe("1\u201314 ordered references, subject to the selected model limit; mutually exclusive with recent count.") };
510
+ const recent = { num_last_images_to_include: z.number().int().min(1).max(14).describe("1\u201314 most recent distinct session images; mutually exclusive with explicit references.") };
304
511
  const IMAGE_INPUT_SCHEMA = z.union([
305
512
  z.strictObject(create),
306
513
  z.strictObject({
@@ -312,11 +519,13 @@ const IMAGE_INPUT_SCHEMA = z.union([
312
519
  ...recent
313
520
  })
314
521
  ]);
315
- function refusal(content) {
316
- return {
317
- isError: true,
318
- content: content.slice(0, 1024)
319
- };
522
+ function refusal(message) {
523
+ return imageResult({
524
+ ok: false,
525
+ code: "invalid-input",
526
+ message: message.slice(0, 1024),
527
+ resultState: "not-submitted"
528
+ });
320
529
  }
321
530
  const FAILURE_TEXT = {
322
531
  unsupported: "This connection does not support the requested image operation.",
@@ -342,24 +551,28 @@ const STATE_TEXT = {
342
551
  unknown: "The server result is unknown; another attempt creates a new request.",
343
552
  "not-delivered": "No image was delivered."
344
553
  };
345
- /** Displays only host-normalized detail; unexpected exceptions never expose their messages. */
346
554
  function failureOf(error, cancelled) {
347
555
  const failure = error;
348
- if (failure?.name !== "GenerationFailure" || typeof failure.code !== "string" || !Object.hasOwn(FAILURE_TEXT, failure.code)) return {
349
- isError: true,
350
- content: cancelled ? "Image generation was cancelled. No image was delivered." : "Image generation failed. No image was delivered."
351
- };
556
+ if (failure?.name !== "GenerationFailure" || typeof failure.code !== "string" || !Object.hasOwn(FAILURE_TEXT, failure.code)) return imageResult({
557
+ ok: false,
558
+ code: cancelled ? "cancelled" : "provider",
559
+ resultState: "unknown",
560
+ message: cancelled ? "Image generation was cancelled. No image was delivered." : "Image generation failed. No image was delivered."
561
+ });
352
562
  const state = failure.resultState ?? "not-delivered";
353
563
  const prefix = `${FAILURE_TEXT[failure.code]} ${STATE_TEXT[state] ?? STATE_TEXT["not-delivered"]}`;
354
564
  const retryAt = failure.retryAt;
355
565
  const retry = typeof retryAt === "number" && Number.isFinite(retryAt) && retryAt > 0 && retryAt <= 864e13 ? ` Retry after ${new Date(retryAt).toISOString()} UTC.` : "";
356
- return {
357
- isError: true,
358
- content: (prefix + (typeof failure.message === "string" ? ` ${failure.message}` : "")).slice(0, 511 - retry.length) + retry + " Do not automatically retry."
359
- };
566
+ const detail = typeof failure.message === "string" ? ` ${failure.message}` : "";
567
+ return imageResult({
568
+ ok: false,
569
+ code: failure.code,
570
+ resultState: state,
571
+ message: (prefix + detail).slice(0, 511 - retry.length) + retry + " Do not automatically retry."
572
+ });
360
573
  }
361
- /** Creates the shared image tool with explicit, default, then unique-candidate routing. */
362
574
  function imageGenerationTool(deps) {
575
+ const documents = createTextDocuments(imageDocument);
363
576
  const candidates = (operation) => deps.generation.connections().flatMap((connection) => connection.models.filter((model) => model.outputKinds.includes("image")).flatMap((model) => model.operations.filter((one) => one.id === operation).map((descriptor) => ({
364
577
  ref: {
365
578
  providerId: connection.providerId,
@@ -373,13 +586,8 @@ function imageGenerationTool(deps) {
373
586
  deliveryKind: "preview",
374
587
  description: "Generate or edit an image using a configured image model. Inspect model_list for operation parameter schemas. Supply target to override the global image default. Never automatically retry a failed submission.",
375
588
  inputSchema: IMAGE_INPUT_SCHEMA,
376
- outputSchema: toolOutputSchema(z.strictObject({
377
- ok: z.literal(true),
378
- committed: z.literal(true),
379
- text: z.string(),
380
- target,
381
- fileIds: z.array(z.string().regex(/^[0-9a-f]{64}$/)).min(1).max(8)
382
- }), IMAGE_INPUT_SCHEMA, "model_image_generate"),
589
+ outputSchema: ImageToolDataSchema,
590
+ formatModel: documents.formatModel,
383
591
  available(view) {
384
592
  return view.model !== null && deps.generation.connections().some((connection) => connection.models.some((model) => model.outputKinds.includes("image") && model.operations.some((operation) => operation.id === "create" || operation.id === "edit")));
385
593
  },
@@ -425,14 +633,23 @@ function imageGenerationTool(deps) {
425
633
  params: params.data,
426
634
  ...prepared === void 0 ? {} : { inputs: prepared }
427
635
  });
636
+ const text = result.text ?? "Image generated.";
637
+ let source;
638
+ try {
639
+ if ([...text].length > 16e3) throw new Error("invalid_image_text");
640
+ source = { text: await captureTextBody(text, ctx) };
641
+ } catch {
642
+ source = { textError: "source_capture_failed" };
643
+ }
428
644
  return {
429
- content: JSON.stringify({
645
+ ...imageResult(ImageToolDataSchema.parse({
430
646
  ok: true,
431
647
  committed: true,
432
648
  target: selected.ref,
433
- text: result.text?.trim() || "Image generated.",
434
- fileIds: result.files.map((file) => file.id)
435
- }),
649
+ ...source,
650
+ fileIds: result.files.map((file) => file.id),
651
+ files: [...result.files]
652
+ })),
436
653
  files: result.files.map((file) => ({
437
654
  fileId: file.id,
438
655
  name: file.name
@@ -446,14 +663,11 @@ function imageGenerationTool(deps) {
446
663
  }
447
664
  //#endregion
448
665
  //#region src/adapters.ts
449
- /** Returns the capability-owned image adapter. */
450
666
  function imageAdapter(protocol) {
451
667
  return protocol?.adapters.image;
452
668
  }
453
669
  //#endregion
454
670
  //#region src/runtime/models/generation.ts
455
- /** Host admission, validation, cancellation and atomic delivery for generation tools. */
456
- /** A stable failure whose text never contains raw provider headers or bodies. */
457
671
  var GenerationFailure = class extends Error {
458
672
  name = "GenerationFailure";
459
673
  code;
@@ -490,7 +704,6 @@ const FAILURE_CODES = /* @__PURE__ */ new Set([
490
704
  function fail(code, message) {
491
705
  throw new GenerationFailure(code, message);
492
706
  }
493
- /** Races uncooperative promises while still observing their eventual rejection. */
494
707
  function untilAbort(promise, signal) {
495
708
  if (signal.aborted) {
496
709
  promise.catch(() => {});
@@ -502,7 +715,6 @@ function untilAbort(promise, signal) {
502
715
  promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
503
716
  });
504
717
  }
505
- /** Builds independently bound services sharing the installation's admission budget. */
506
718
  function createGenerationHost(deps) {
507
719
  const prepared = /* @__PURE__ */ new WeakMap();
508
720
  const active = /* @__PURE__ */ new Set();
@@ -548,7 +760,7 @@ function createGenerationHost(deps) {
548
760
  const operation = model.operations.find((one) => one.id === input.operation);
549
761
  if (!operation || !model.outputKinds.includes(input.outputKind)) fail("unsupported", "the generation operation is unsupported");
550
762
  const prompt = input.prompt.trim();
551
- if (!prompt || [...prompt].length > 32e3) fail("invalid-params", "the generation prompt must contain 1–32000 characters");
763
+ if (!prompt || [...prompt].length > 32e3) fail("invalid-params", "the generation prompt must contain 1\u201332000 characters");
552
764
  const params = operation.paramsSchema.safeParse(input.params);
553
765
  if (!params.success) fail("invalid-params", `the generation parameters are invalid (${params.error.issues.slice(0, 4).map((issue) => `${issue.path.map(String).join(".") || "params"}: ${issue.code}`).join("; ")})`);
554
766
  const selection = input.inputs === void 0 ? void 0 : prepared.get(input.inputs);
@@ -607,6 +819,7 @@ function createGenerationHost(deps) {
607
819
  config: target.config,
608
820
  configuredModels: target.configuredModels,
609
821
  secrets: credential.secrets,
822
+ ...target.headers ? { headers: target.headers } : {},
610
823
  ...login ? { login } : {}
611
824
  });
612
825
  kept = {
@@ -630,6 +843,7 @@ function createGenerationHost(deps) {
630
843
  firstTimer.unref();
631
844
  const first = AbortSignal.any([signal, firstDeadline.signal]);
632
845
  const result = await untilAbort((async () => port.generate({
846
+ accounting: deps.beginUsage?.(ctx),
633
847
  identity: { callId: randomUUID() },
634
848
  artifacts: deps.artifacts(ctx, origins),
635
849
  operation: input.operation,
@@ -748,8 +962,8 @@ function createGenerationHost(deps) {
748
962
  }
749
963
  //#endregion
750
964
  //#region src/runtime/models/generation-inputs.ts
751
- /** Ordered, host-authorized image references for generation tool submissions. */
752
965
  const FILE_ORIGINAL_LIMIT = 20971520;
966
+ const READ_CHUNK = 1048576;
753
967
  const IMAGE_MEDIA_TYPES = [
754
968
  "image/png",
755
969
  "image/jpeg",
@@ -757,7 +971,6 @@ const IMAGE_MEDIA_TYPES = [
757
971
  "image/webp"
758
972
  ];
759
973
  const selectorsSchema = z.union([z.object({ recent: z.number().int().min(1).max(16) }).strict(), z.array(z.union([z.object({ fileId: z.string().regex(/^[0-9a-f]{64}$/) }).strict(), z.object({ path: z.string().min(1) }).strict()])).max(16)]);
760
- /** Prepares authorized bytes only after every selected path has passed the fence. */
761
974
  function createGenerationInputReader(deps) {
762
975
  return async (ctx, selectors) => {
763
976
  ctx.signal.throwIfAborted();
@@ -767,7 +980,8 @@ function createGenerationInputReader(deps) {
767
980
  message: "invalid generation input selectors"
768
981
  };
769
982
  selectors = parsed.data;
770
- const history = deps.history(ctx);
983
+ const history = await deps.history(ctx);
984
+ ctx.signal.throwIfAborted();
771
985
  const ordered = [];
772
986
  for (const message of history) for (const part of message.content) {
773
987
  if (part.type === "file") ordered.push(part.file);
@@ -786,7 +1000,6 @@ function createGenerationInputReader(deps) {
786
1000
  };
787
1001
  selection = recent.map((one) => ({ fileId: one.file.id }));
788
1002
  } else selection = selectors;
789
- const paths = /* @__PURE__ */ new Map();
790
1003
  for (const item of selection) if ("fileId" in item) {
791
1004
  const selected = latest.get(item.fileId);
792
1005
  if (!selected) return {
@@ -802,82 +1015,53 @@ function createGenerationInputReader(deps) {
802
1015
  index,
803
1016
  path: item.path
804
1017
  }] : []);
1018
+ const paths = /* @__PURE__ */ new Map();
805
1019
  if (requested.length > 0) {
806
- const verdict = deps.scope.allowsBatch(ctx, requested.map((item) => item.path), "read");
807
- if (!verdict.allowed) {
808
- if (verdict.reason === "ask" && "awaitHuman" in verdict.ask) return {
809
- kind: "ask",
810
- result: verdict.ask
811
- };
812
- return {
813
- kind: "refused",
814
- message: "message" in verdict ? verdict.message : "content" in verdict.ask ? verdict.ask.content : "reading the selected image paths was refused"
815
- };
816
- }
1020
+ const batch = await deps.scope.allowsMany(ctx, requested.map((item) => ({
1021
+ path: item.path,
1022
+ access: "read"
1023
+ })));
1024
+ ctx.signal.throwIfAborted();
1025
+ if (batch.ask && "awaitHuman" in batch.ask) return {
1026
+ kind: "ask",
1027
+ result: batch.ask
1028
+ };
817
1029
  for (const [offset, item] of requested.entries()) {
818
- const path = verdict.paths[offset];
819
- if (path === void 0) return {
1030
+ const verdict = batch.verdicts[offset];
1031
+ if (!verdict) return {
820
1032
  kind: "refused",
821
1033
  message: "the image path was not authorized"
822
1034
  };
823
- paths.set(item.index, path);
1035
+ if (!verdict.allowed) {
1036
+ if (verdict.reason === "ask" && "awaitHuman" in verdict.ask) return {
1037
+ kind: "ask",
1038
+ result: verdict.ask
1039
+ };
1040
+ return {
1041
+ kind: "refused",
1042
+ message: "message" in verdict ? verdict.message : "reading the selected image paths was refused"
1043
+ };
1044
+ }
1045
+ paths.set(item.index, verdict);
824
1046
  }
825
1047
  }
826
- function pathsCurrent() {
827
- const verdict = deps.scope.allowsBatch(ctx, requested.map((item) => item.path), "read");
828
- return verdict.allowed && requested.every((item, offset) => verdict.paths[offset] === paths.get(item.index));
829
- }
830
1048
  const files = [];
831
1049
  try {
832
1050
  for (const [index, item] of selection.entries()) {
833
1051
  ctx.signal.throwIfAborted();
834
1052
  let bytes;
835
1053
  if ("path" in item) {
836
- const path = paths.get(index);
837
- if (path === void 0) return {
1054
+ const verdict = paths.get(index);
1055
+ if (verdict === void 0) return {
838
1056
  kind: "refused",
839
1057
  message: "the image path was not authorized"
840
1058
  };
841
- const descriptor = await (deps.open ?? open)(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
842
- try {
843
- ctx.signal.throwIfAborted();
844
- const before = await descriptor.stat();
845
- if (!before.isFile() || before.size > FILE_ORIGINAL_LIMIT) return {
846
- kind: "refused",
847
- message: "the image exceeds the input size limit"
848
- };
849
- if (!pathsCurrent() || await realpath(path) !== path || !sameFile(before, await stat(path))) return {
850
- kind: "refused",
851
- message: "the image path changed before it was read"
852
- };
853
- const parts = [];
854
- let size = 0;
855
- for (;;) {
856
- ctx.signal.throwIfAborted();
857
- const chunk = Buffer.alloc(Math.min(65536, FILE_ORIGINAL_LIMIT - size + 1));
858
- const result = await descriptor.read(chunk, 0, chunk.length, size);
859
- ctx.signal.throwIfAborted();
860
- if (result.bytesRead === 0) break;
861
- size += result.bytesRead;
862
- if (size > FILE_ORIGINAL_LIMIT) return {
863
- kind: "refused",
864
- message: "the image exceeds the input size limit"
865
- };
866
- parts.push(chunk.subarray(0, result.bytesRead));
867
- }
868
- const after = await descriptor.stat();
869
- if (!sameFile(before, after) || size !== after.size) return {
870
- kind: "refused",
871
- message: "the image changed while it was read"
872
- };
873
- if (!pathsCurrent() || await realpath(path) !== path || !sameFile(after, await stat(path))) return {
874
- kind: "refused",
875
- message: "the image path changed while it was read"
876
- };
877
- bytes = Buffer.concat(parts, size);
878
- } finally {
879
- await descriptor.close();
880
- }
1059
+ const read = await readAuthorized(deps.clientFiles, verdict, ctx.signal);
1060
+ if (!Buffer.isBuffer(read)) return {
1061
+ kind: "refused",
1062
+ message: read.refused
1063
+ };
1064
+ bytes = read;
881
1065
  } else bytes = await deps.files.read(ctx.address.workspaceId, item.fileId);
882
1066
  if (!bytes || bytes.length > FILE_ORIGINAL_LIMIT) return {
883
1067
  kind: "refused",
@@ -906,12 +1090,49 @@ function createGenerationInputReader(deps) {
906
1090
  }
907
1091
  };
908
1092
  }
909
- function sameFile(before, after) {
910
- return before.ino === after.ino && before.dev === after.dev && before.size === after.size && before.mtimeMs === after.mtimeMs && before.ctimeMs === after.ctimeMs;
1093
+ async function readAuthorized(clientFiles, verdict, signal) {
1094
+ const parentPath = dirname(verdict.path);
1095
+ const parent = await clientFiles.anchor(parentPath, {
1096
+ sealedDirectories: verdict.sealedDirectories,
1097
+ signal
1098
+ });
1099
+ try {
1100
+ signal.throwIfAborted();
1101
+ if (parent.path !== parentPath) return { refused: "the image path changed before it was read" };
1102
+ const reader = await parent.openRead([basename(verdict.path)]);
1103
+ try {
1104
+ const before = await reader.stat();
1105
+ const identity = verdict.identity;
1106
+ if (identity) {
1107
+ const observed = identity.path === verdict.path ? before : identity.path === parentPath ? await parent.stat() : void 0;
1108
+ if (!observed || observed.device !== identity.identity.device || observed.inode !== identity.identity.fileId) return { refused: "the image path changed before it was read" };
1109
+ }
1110
+ const size = BigInt(before.size);
1111
+ if (before.kind !== "file" || size < 0n || size > BigInt(FILE_ORIGINAL_LIMIT)) return { refused: "the image exceeds the input size limit" };
1112
+ const total = Number(size);
1113
+ const chunks = [];
1114
+ let position = 0;
1115
+ while (position < total) {
1116
+ signal.throwIfAborted();
1117
+ const chunk = await reader.read(position, Math.min(READ_CHUNK, total - position));
1118
+ if (!chunk.length || chunk.length > total - position) return { refused: "the image changed while it was read" };
1119
+ chunks.push(chunk);
1120
+ position += chunk.length;
1121
+ }
1122
+ if ((await reader.read(position, 1)).length || !sameObservation(before, await reader.stat())) return { refused: "the image changed while it was read" };
1123
+ return Buffer.concat(chunks, position);
1124
+ } finally {
1125
+ await reader.close();
1126
+ }
1127
+ } finally {
1128
+ await parent.close();
1129
+ }
1130
+ }
1131
+ function sameObservation(before, after) {
1132
+ return before.device === after.device && before.inode === after.inode && before.kind === after.kind && before.size === after.size && before.modifiedNs === after.modifiedNs && before.changedNs === after.changedNs;
911
1133
  }
912
1134
  //#endregion
913
1135
  //#region src/runtime/models/generation-services.ts
914
- /** Composes resource authorization with capability-owned image execution and atomic publication. */
915
1136
  function createGenerationServices(input) {
916
1137
  const { ctx, manager, host } = input;
917
1138
  const deps = {
@@ -926,6 +1147,18 @@ function createGenerationServices(input) {
926
1147
  return host.contexts.session(id);
927
1148
  }
928
1149
  const identities = /* @__PURE__ */ new Map();
1150
+ const lifecycle = ctx.services.find?.("session-lifecycle");
1151
+ const callers = /* @__PURE__ */ new WeakMap();
1152
+ function sessionLease(request) {
1153
+ const call = callers.get(request.artifacts);
1154
+ if (!lifecycle || !call) return void 0;
1155
+ try {
1156
+ return lifecycle.enter(call.sessionId);
1157
+ } catch (error) {
1158
+ if (error instanceof Error && error.message.startsWith("not-found")) return void 0;
1159
+ throw error;
1160
+ }
1161
+ }
929
1162
  function target(ref) {
930
1163
  const row = manager.store.findConnection(ref.providerId);
931
1164
  if (!row) return void 0;
@@ -939,16 +1172,18 @@ function createGenerationServices(input) {
939
1172
  ...binding.execution ? { execution: binding.execution } : {}
940
1173
  }));
941
1174
  const fingerprint = JSON.stringify([
942
- row.revision,
943
- selected.revision,
944
- configuredModels,
1175
+ row.applicabilityRevision,
1176
+ row.enabled,
1177
+ selected.applicabilityRevision,
1178
+ configuredModels.find((model) => model.id === ref.model) ?? null,
945
1179
  provider.registrationEpoch,
946
1180
  protocol.registrationEpoch,
947
1181
  capability.registrationEpoch
948
1182
  ]);
949
- const prior = identities.get(ref.providerId);
1183
+ const identityKey = JSON.stringify([ref.providerId, ref.model]);
1184
+ const prior = identities.get(identityKey);
950
1185
  const revision = prior?.fingerprint === fingerprint ? prior.revision : (prior?.revision ?? 0) + 1;
951
- identities.set(ref.providerId, {
1186
+ identities.set(identityKey, {
952
1187
  fingerprint,
953
1188
  revision
954
1189
  });
@@ -960,14 +1195,21 @@ function createGenerationServices(input) {
960
1195
  image: {
961
1196
  ...original,
962
1197
  createPort: () => ({ async generate(request, signal) {
1198
+ const session = sessionLease(request);
963
1199
  const lease = await manager.acquire({
964
1200
  ...ref,
965
1201
  capabilityId: "image"
966
- }, signal);
1202
+ }, {
1203
+ signal,
1204
+ invocation: request.accounting,
1205
+ ...session ? { session } : {}
1206
+ });
967
1207
  try {
968
1208
  return await (await lease.runtime.createPort()).generate(request, lease.signal);
969
1209
  } finally {
970
- await lease.release();
1210
+ await lease.release().catch((error) => {
1211
+ if (!lease.signal.aborted) throw error;
1212
+ });
971
1213
  }
972
1214
  } })
973
1215
  }
@@ -991,6 +1233,7 @@ function createGenerationServices(input) {
991
1233
  endpointId: row.endpointId,
992
1234
  protocolId: protocol.type.type
993
1235
  },
1236
+ ...row.headers.length ? { headers: Object.fromEntries(row.headers.map((one) => [one.name, one.value])) } : {},
994
1237
  configuredModels,
995
1238
  connectionRevision: revision
996
1239
  };
@@ -1023,6 +1266,10 @@ function createGenerationServices(input) {
1023
1266
  }
1024
1267
  const approved = /* @__PURE__ */ new WeakMap();
1025
1268
  const generation = createGenerationHost({
1269
+ beginUsage: (call) => input.accounting?.begin({
1270
+ purpose: "image-generation",
1271
+ toolContext: call
1272
+ }),
1026
1273
  files: host.files,
1027
1274
  descriptors: generationModelsOf,
1028
1275
  authenticate: (owner, call) => host.contexts.authenticate(owner, call),
@@ -1059,7 +1306,8 @@ function createGenerationServices(input) {
1059
1306
  sessionRevision: (id) => session(id)?.historyGeneration ?? -1,
1060
1307
  prepare: createGenerationInputReader({
1061
1308
  files: host.files,
1062
- scope: host.security,
1309
+ scope: input.fence,
1310
+ clientFiles: input.clientFiles,
1063
1311
  probeImage: host.media.probeImage,
1064
1312
  history: (call) => host.contexts.history(call)
1065
1313
  }),
@@ -1067,21 +1315,24 @@ function createGenerationServices(input) {
1067
1315
  ctx.signal.throwIfAborted();
1068
1316
  const needs = [];
1069
1317
  for (const origin of origins) {
1070
- const url = new URL(origin);
1071
- if (url.protocol !== "https:" || url.origin !== origin || url.username || url.password) return {
1318
+ const grant = artifactOriginGrant(origin);
1319
+ if (!grant) return {
1072
1320
  kind: "refused",
1073
- message: "artifact origins must be exact HTTPS origins"
1321
+ message: "artifact origins must be valid HTTPS declarations"
1074
1322
  };
1075
- const verdict = await deps.security.judgeAddress(origin);
1076
- ctx.signal.throwIfAborted();
1077
- if (verdict.kind !== "allowed") return {
1078
- kind: "refused",
1079
- message: "the artifact origin address was refused or unresolved"
1080
- };
1081
- const port = Number(url.port || 443);
1082
- if (!deps.security.holdsHost(verdict.host, port, "connect")) needs.push({
1083
- host: verdict.host,
1084
- port
1323
+ let host = grant.host;
1324
+ if (grant.exact) {
1325
+ const verdict = await deps.security.judgeAddress(origin);
1326
+ ctx.signal.throwIfAborted();
1327
+ if (verdict.kind !== "allowed") return {
1328
+ kind: "refused",
1329
+ message: "the artifact origin address was refused or unresolved"
1330
+ };
1331
+ host = verdict.host;
1332
+ }
1333
+ if (!deps.security.holdsHost(host, grant.port, "connect")) needs.push({
1334
+ host,
1335
+ port: grant.port
1085
1336
  });
1086
1337
  }
1087
1338
  ctx.signal.throwIfAborted();
@@ -1126,12 +1377,12 @@ function createGenerationServices(input) {
1126
1377
  return { kind: "ready" };
1127
1378
  },
1128
1379
  artifacts(ctx, origins) {
1129
- return { async fetch(url, signal) {
1380
+ const reader = { async fetch(url, signal) {
1130
1381
  let currentUrl = url;
1131
1382
  for (let hop = 0; hop <= 5; hop++) {
1132
1383
  signal.throwIfAborted();
1133
1384
  const parsed = new URL(currentUrl);
1134
- if (!origins.includes(parsed.origin) || !approved.get(ctx)?.has(parsed.origin) || parsed.username || parsed.password) throw new GenerationFailure("forbidden", "the artifact URL has an unauthorized origin", "not-delivered");
1385
+ if (!artifactOriginMatches(origins, parsed.origin) || !artifactOriginMatches([...approved.get(ctx) ?? []], parsed.origin) || parsed.username || parsed.password) throw new GenerationFailure("forbidden", "the artifact URL has an unauthorized origin", "not-delivered");
1135
1386
  const address = await deps.security.judgeAddress(currentUrl);
1136
1387
  if (address.kind !== "allowed") throw new GenerationFailure("forbidden", "the artifact address was refused or unresolved", "not-delivered");
1137
1388
  signal.throwIfAborted();
@@ -1164,6 +1415,8 @@ function createGenerationServices(input) {
1164
1415
  }
1165
1416
  throw new GenerationFailure("network", "the artifact download failed", "not-delivered");
1166
1417
  } };
1418
+ callers.set(reader, ctx);
1419
+ return reader;
1167
1420
  }
1168
1421
  });
1169
1422
  const dispose = manager.onChanged(() => generation.invalidate());
@@ -1211,7 +1464,6 @@ function createGenerationServices(input) {
1211
1464
  }
1212
1465
  };
1213
1466
  }
1214
- /** Keeps a downloaded body in the same cancellation lifetime as its generation call. */
1215
1467
  function artifactResponse(response, signal) {
1216
1468
  const iterator = response.body?.[Symbol.asyncIterator]();
1217
1469
  let finished = false;
@@ -1266,18 +1518,18 @@ function artifactResponse(response, signal) {
1266
1518
  }
1267
1519
  //#endregion
1268
1520
  //#region src/index.ts
1269
- /** Image generation and editing capability, independent from the selected Chat provider. */
1270
- /** Tools owned by the Image capability. */
1271
1521
  const TOOL_NAMES = ["model_image_generate"];
1272
- /** Image tool settings withdraw the tool and its guidance together. */
1273
1522
  const ImageToolConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).default({ disabled: [] });
1274
1523
  const plugin = {
1275
1524
  name: "@eum-agent/llm-capability-image",
1276
1525
  requires: [
1277
1526
  "model-management",
1278
1527
  "agent-capability-host",
1279
- "approval"
1528
+ "approval",
1529
+ "fence",
1530
+ "client-files"
1280
1531
  ],
1532
+ optionalServices: ["usage-accounting", "session-lifecycle"],
1281
1533
  provides: ["generation-runtime"],
1282
1534
  configSchema: ImageToolConfig,
1283
1535
  apply(ctx, config) {
@@ -1287,10 +1539,13 @@ const plugin = {
1287
1539
  });
1288
1540
  const manager = ctx.services.get("model-management");
1289
1541
  const generation = createGenerationServices({
1542
+ accounting: ctx.services.find("usage-accounting"),
1290
1543
  ctx,
1291
1544
  manager,
1292
1545
  host: ctx.services.get("agent-capability-host"),
1293
- approval: ctx.services.get("approval")
1546
+ approval: ctx.services.get("approval"),
1547
+ fence: ctx.services.get("fence"),
1548
+ clientFiles: ctx.services.get("client-files")
1294
1549
  });
1295
1550
  ctx.services.provide("generation-runtime", {
1296
1551
  bind: generation.bind,
@@ -1316,7 +1571,10 @@ const plugin = {
1316
1571
  }));
1317
1572
  ctx.tools.guide(GUIDANCE);
1318
1573
  const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
1319
- if (existsSync(ui)) ctx.client.registerUi({ module: ui });
1574
+ if (existsSync(ui)) ctx.client.registerPackageFiles({
1575
+ root: dirname(ui),
1576
+ entry: "ui.js"
1577
+ });
1320
1578
  }
1321
1579
  };
1322
1580
  //#endregion