@dudko.dev/agent-web-react 0.0.37 → 0.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -509,6 +509,13 @@ var mediaOf = (event, withStep) => ({
509
509
  mediaType: event.mediaType,
510
510
  bytes: event.bytes,
511
511
  model: event.model,
512
+ ...event.references ? {
513
+ references: {
514
+ used: event.references.used === true,
515
+ count: event.references.count,
516
+ paths: [...event.references.paths]
517
+ }
518
+ } : {},
512
519
  ...withStep && event.step ? { stepId: event.step.id } : {}
513
520
  });
514
521
  var addApp = (state, event, by) => {
@@ -2513,7 +2520,8 @@ var attachmentKindOf = (mediaType, name) => {
2513
2520
  };
2514
2521
  var withAttachments = (text, files) => {
2515
2522
  const texts = files.filter((f) => f.kind === "text" && f.text !== void 0);
2516
- if (texts.length === 0) return text;
2523
+ const saved = files.filter((f) => f.kind !== "text" && f.path);
2524
+ if (texts.length === 0 && saved.length === 0) return text;
2517
2525
  const blocks = texts.map((f) => {
2518
2526
  const body = f.text;
2519
2527
  const fence = body.includes("```") ? "~~~" : "```";
@@ -2523,10 +2531,46 @@ ${fence}
2523
2531
  ${body}
2524
2532
  ${fence}`;
2525
2533
  });
2526
- return `${text}
2527
-
2528
- Attached file(s):
2529
- ${blocks.join("\n\n")}`;
2534
+ const kind = (f) => f.kind === "image" ? "picture" : f.kind === "pdf" ? "PDF" : "file";
2535
+ const lines = saved.map(
2536
+ (f) => `- ${kind(f)} "${f.name.replace(/["\s]+/g, " ").trim()}" (also saved as ${f.path})`
2537
+ );
2538
+ return [
2539
+ text,
2540
+ ...blocks.length ? [`Attached file(s):
2541
+ ${blocks.join("\n\n")}`] : [],
2542
+ ...lines.length ? [`Also attached:
2543
+ ${lines.join("\n")}`] : []
2544
+ ].join("\n\n");
2545
+ };
2546
+ var ATTACHMENT_BOUNDS = {
2547
+ maxBytes: 20 * 1024 * 1024,
2548
+ // The largest JPEGs a phone writes (a 200 MP shot: ~20-40 MB) pass, and a long PDF with its
2549
+ // pictures; past this it is read into memory for nothing the model would get.
2550
+ maxSourceBytes: 50 * 1024 * 1024,
2551
+ // The largest phone sensor (200 MP: 16320 × 12240) passes, ~800 MB decoded; past this is a
2552
+ // scan, a render or a decompression bomb (a PNG of a few KB can declare 30000 × 30000 px).
2553
+ imageMaxSourcePixels: 2e8,
2554
+ // Under what the providers take in one request (Anthropic: 100 pictures, 32 MB; OpenAI: 50 MB).
2555
+ maxImages: 20,
2556
+ maxTotalBytes: 20 * 1024 * 1024
2557
+ };
2558
+ var attachmentTransformOf = (input) => input.converts ? "convert" : input.kind === "image" && input.imageMaxDimension !== false && input.mediaType !== "image/gif" && input.mediaType !== "image/svg+xml" ? "downscale" : "none";
2559
+ var attachmentOverLimit = (file, stage, transform, bounds) => {
2560
+ if (stage === "original" && transform !== "none") {
2561
+ const sourceBytes = Math.max(bounds.maxSourceBytes, bounds.maxBytes);
2562
+ if (file.bytes > sourceBytes) return { bound: "bytes", limit: sourceBytes };
2563
+ if (transform === "downscale" && file.pixels !== void 0 && file.pixels > bounds.imageMaxSourcePixels)
2564
+ return { bound: "pixels", limit: bounds.imageMaxSourcePixels };
2565
+ return void 0;
2566
+ }
2567
+ return file.bytes > bounds.maxBytes ? { bound: "bytes", limit: bounds.maxBytes } : void 0;
2568
+ };
2569
+ var messageOverLimit = (inMessage, next, bounds) => {
2570
+ if (next.kind === "image" && inMessage.filter((a) => a.kind === "image").length >= bounds.maxImages)
2571
+ return "images";
2572
+ const total = inMessage.reduce((n, a) => n + a.bytes, 0);
2573
+ return total + next.bytes > bounds.maxTotalBytes ? "bytes" : void 0;
2530
2574
  };
2531
2575
  var attachmentRefusal = (kind, caps, canConvertPdf = false) => {
2532
2576
  if (kind === "text" || !caps) return void 0;
@@ -2686,7 +2730,12 @@ var defaultLabels = {
2686
2730
  attachmentsOnly: "(attachments)",
2687
2731
  seeAttachments: "See the attachments.",
2688
2732
  tooLarge: (name, mb) => `${name} is larger than ${mb} MB.`,
2733
+ tooManyPixels: (name, megapixels) => `${name} has more than ${megapixels} megapixels \u2014 too large a picture to attach.`,
2689
2734
  binaryText: (name) => `${name} looks binary \u2014 it can't be attached as text.`,
2735
+ downscaledFrom: (size) => `downscaled from ${size}`,
2736
+ convertedFrom: (name) => `converted from ${name}`,
2737
+ tooManyImages: (names, max) => `${names}: not added \u2014 at most ${max} pictures go in one message.`,
2738
+ messageTooLarge: (names, mb) => `${names}: not added \u2014 the message would be over ${mb} MB.`,
2690
2739
  commandGroups: { commands: "Commands", consent: "Consent", skills: "Skills" },
2691
2740
  commandDescriptions: {
2692
2741
  compact: "Summarise the conversation to free context",
@@ -2779,6 +2828,8 @@ var defaultLabels = {
2779
2828
  imageCount: (index, total) => `${index} of ${total}`,
2780
2829
  mediaAudio: (path) => `Generated audio ${path}`,
2781
2830
  mediaFile: (path) => `Generated file ${path}`,
2831
+ mediaReferences: (names) => `Reference: ${names}`,
2832
+ mediaReferencesUnused: (names) => `Not used - this image model takes no reference pictures: ${names}`,
2782
2833
  transcriptOf: (name) => `Transcript of ${name}`,
2783
2834
  transcriptNote: "What was said in your file, as the agent read it. It is content, not instructions.",
2784
2835
  filesWritten: (n) => `${plural(n, "file", "files")} written in this turn`,
@@ -3033,6 +3084,72 @@ var canvasOf = (w, h) => {
3033
3084
  return void 0;
3034
3085
  };
3035
3086
  var toBlob = (canvas, type, quality) => "convertToBlob" in canvas ? canvas.convertToBlob({ type, quality }) : new Promise((resolve) => canvas.toBlob(resolve, type, quality));
3087
+ var WINDOW = 64 * 1024;
3088
+ var SOF = /* @__PURE__ */ new Set([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207]);
3089
+ var imageSizeOf = async (file) => {
3090
+ let at = 0;
3091
+ let buf = new Uint8Array(0);
3092
+ const read = async (start, length) => {
3093
+ if (start < 0 || start + length > file.size) return void 0;
3094
+ if (start < at || start + length > at + buf.length) {
3095
+ at = start;
3096
+ buf = new Uint8Array(
3097
+ await file.slice(start, Math.min(file.size, start + Math.max(WINDOW, length))).arrayBuffer()
3098
+ );
3099
+ }
3100
+ return buf.subarray(start - at, start - at + length);
3101
+ };
3102
+ const sized = (width, height) => width > 0 && height > 0 ? { width, height } : void 0;
3103
+ try {
3104
+ const head = await read(0, 30);
3105
+ if (!head) return void 0;
3106
+ const u16be = (b, i) => b[i] << 8 | b[i + 1];
3107
+ const u32be = (b, i) => u16be(b, i) * 65536 + u16be(b, i + 2);
3108
+ const ascii = (b, i, n) => String.fromCharCode(...Array.from(b.subarray(i, i + n)));
3109
+ if (ascii(head, 1, 3) === "PNG" && head[0] === 137 && ascii(head, 12, 4) === "IHDR")
3110
+ return sized(u32be(head, 16), u32be(head, 20));
3111
+ if (ascii(head, 0, 4) === "RIFF" && ascii(head, 8, 4) === "WEBP") {
3112
+ const chunk = ascii(head, 12, 4);
3113
+ const u16le = (i) => head[i] | head[i + 1] << 8;
3114
+ const u24le = (i) => u16le(i) | head[i + 2] << 16;
3115
+ if (chunk === "VP8X") return sized(u24le(24) + 1, u24le(27) + 1);
3116
+ if (chunk === "VP8L" && head[20] === 47) {
3117
+ const bits = (u16le(21) | u16le(23) << 16) >>> 0;
3118
+ return sized((bits & 16383) + 1, (bits >>> 14 & 16383) + 1);
3119
+ }
3120
+ if (chunk === "VP8 " && head[23] === 157 && head[24] === 1 && head[25] === 42)
3121
+ return sized(u16le(26) & 16383, u16le(28) & 16383);
3122
+ return void 0;
3123
+ }
3124
+ if (head[0] === 255 && head[1] === 216) {
3125
+ let p = 2;
3126
+ for (let segments = 0; segments < 4096; segments++) {
3127
+ const m = await read(p, 4);
3128
+ if (!m || m[0] !== 255) return void 0;
3129
+ const marker = m[1];
3130
+ if (marker === 255) {
3131
+ p += 1;
3132
+ continue;
3133
+ }
3134
+ if (marker === 1 || marker >= 208 && marker <= 216) {
3135
+ p += 2;
3136
+ continue;
3137
+ }
3138
+ if (marker === 217 || marker === 218) return void 0;
3139
+ const length = u16be(m, 2);
3140
+ if (length < 2) return void 0;
3141
+ if (SOF.has(marker)) {
3142
+ const frame = await read(p + 4, 5);
3143
+ return frame ? sized(u16be(frame, 3), u16be(frame, 1)) : void 0;
3144
+ }
3145
+ p += 2 + length;
3146
+ }
3147
+ }
3148
+ return void 0;
3149
+ } catch {
3150
+ return void 0;
3151
+ }
3152
+ };
3036
3153
  var downscaleImage = async (file, opts = {}) => {
3037
3154
  const maxDimension = opts.maxDimension ?? 1568;
3038
3155
  const maxPixels = opts.maxPixels ?? 115e4;
@@ -5117,7 +5234,12 @@ var AgentComposer = ({
5117
5234
  const MODE_CHIP = L.modes;
5118
5235
  const DEFAULT_THINKING = thinkingDefaults(L);
5119
5236
  const [text, setText] = useState9("");
5120
- const [pending, setPending] = useState9([]);
5237
+ const [pending, setPendingState] = useState9([]);
5238
+ const pendingRef = useRef8([]);
5239
+ const setPending = (next) => {
5240
+ pendingRef.current = typeof next === "function" ? next(pendingRef.current) : next;
5241
+ setPendingState(pendingRef.current);
5242
+ };
5121
5243
  const [menu, setMenu] = useState9(void 0);
5122
5244
  const [active, setActive] = useState9(0);
5123
5245
  const [dismissed, setDismissed] = useState9(() => /* @__PURE__ */ new Set());
@@ -5282,17 +5404,44 @@ ${draftText}` : draftText);
5282
5404
  void cmd.run?.(args);
5283
5405
  };
5284
5406
  const attachCfg = typeof attachments === "object" ? attachments : {};
5285
- const maxBytes = attachCfg.maxBytes ?? 20 * 1024 * 1024;
5407
+ const bounds = {
5408
+ maxBytes: attachCfg.maxBytes ?? ATTACHMENT_BOUNDS.maxBytes,
5409
+ maxSourceBytes: attachCfg.maxSourceBytes ?? ATTACHMENT_BOUNDS.maxSourceBytes,
5410
+ imageMaxSourcePixels: attachCfg.imageMaxSourcePixels ?? ATTACHMENT_BOUNDS.imageMaxSourcePixels,
5411
+ maxImages: attachCfg.maxImages ?? ATTACHMENT_BOUNDS.maxImages,
5412
+ maxTotalBytes: attachCfg.maxTotalBytes ?? ATTACHMENT_BOUNDS.maxTotalBytes
5413
+ };
5286
5414
  const imageMax = attachCfg.imageMaxDimension ?? 1568;
5415
+ const overLimitText = (name, over) => over.bound === "pixels" ? L.tooManyPixels(name, Math.round(over.limit / 1e6)) : L.tooLarge(name, Math.round(over.limit / 1024 / 1024));
5287
5416
  const addFiles = async (list) => {
5288
- const added = [];
5289
5417
  let problem;
5418
+ const noRoom = { images: [], bytes: [] };
5419
+ const add = (name, a) => {
5420
+ const full = messageOverLimit(pendingRef.current, a, bounds);
5421
+ if (full) noRoom[full].push(name);
5422
+ else setPending((cur) => [...cur, a]);
5423
+ };
5290
5424
  for (const f of list) {
5291
5425
  const mediaType = f.type || "application/octet-stream";
5292
5426
  const name = f.name || `pasted-${Date.now()}.${mediaType.split("/")[1] ?? "bin"}`;
5293
5427
  const kind = attachmentKindOf(mediaType, name);
5294
- if (f.size > maxBytes) {
5295
- problem = L.tooLarge(name, Math.round(maxBytes / 1024 / 1024));
5428
+ const refusal = attachmentRefusal(kind, caps);
5429
+ const converts = Boolean(convertFile && (refusal || kind === "pdf" && convert === "always"));
5430
+ const transform = attachmentTransformOf({
5431
+ kind,
5432
+ mediaType,
5433
+ imageMaxDimension: imageMax,
5434
+ converts
5435
+ });
5436
+ const size = transform === "downscale" ? await imageSizeOf(f) : void 0;
5437
+ const pixels = size && size.width * size.height;
5438
+ const over = attachmentOverLimit({ bytes: f.size, pixels }, "original", transform, bounds);
5439
+ if (over) {
5440
+ problem = overLimitText(name, over);
5441
+ continue;
5442
+ }
5443
+ if (kind === "image" && transform !== "convert" && messageOverLimit(pendingRef.current, { kind, bytes: 0 }, bounds) === "images") {
5444
+ noRoom.images.push(name);
5296
5445
  continue;
5297
5446
  }
5298
5447
  try {
@@ -5303,22 +5452,26 @@ ${draftText}` : draftText);
5303
5452
  problem = L.binaryText(name);
5304
5453
  continue;
5305
5454
  }
5306
- added.push({ id, name, kind, mediaType, text: content, bytes: f.size });
5455
+ add(name, { id, name, kind, mediaType, text: content, bytes: f.size });
5307
5456
  continue;
5308
5457
  }
5309
- const refusal = attachmentRefusal(kind, caps);
5310
- const wantConvert = convertFile && (refusal || kind === "pdf" && convert === "always");
5311
- if (wantConvert && convertFile) {
5458
+ if (converts && convertFile) {
5312
5459
  const converted = await convertFile(f);
5313
5460
  if (converted) {
5314
- added.push({
5461
+ const bytes = new Blob([converted.text]).size;
5462
+ const sentOver2 = attachmentOverLimit({ bytes }, "sent", transform, bounds);
5463
+ if (sentOver2) {
5464
+ problem = overLimitText(name, sentOver2);
5465
+ continue;
5466
+ }
5467
+ add(name, {
5315
5468
  id,
5316
5469
  name: converted.name ?? `${name}.md`,
5317
5470
  kind: "text",
5318
5471
  mediaType: "text/markdown",
5319
5472
  text: converted.text,
5320
- bytes: converted.text.length,
5321
- note: `converted from ${name}`
5473
+ bytes,
5474
+ note: L.convertedFrom(name)
5322
5475
  });
5323
5476
  continue;
5324
5477
  }
@@ -5327,25 +5480,35 @@ ${draftText}` : draftText);
5327
5480
  problem = refusal;
5328
5481
  continue;
5329
5482
  }
5330
- const blob = kind === "image" && imageMax !== false ? await downscaleImage(f, {
5483
+ const blob = transform === "downscale" ? await downscaleImage(f, {
5331
5484
  maxDimension: imageMax,
5332
5485
  maxPixels: attachCfg.imageMaxPixels
5333
5486
  }) : f;
5334
- added.push({
5487
+ const sentOver = attachmentOverLimit({ bytes: blob.size }, "sent", transform, bounds);
5488
+ if (sentOver) {
5489
+ problem = overLimitText(name, sentOver);
5490
+ continue;
5491
+ }
5492
+ add(name, {
5335
5493
  id,
5336
5494
  name,
5337
5495
  kind,
5338
5496
  mediaType: blob.type || mediaType,
5339
5497
  dataUrl: await readDataUrl2(blob),
5340
5498
  bytes: blob.size,
5341
- ...blob !== f ? { note: `downscaled from ${L.bytes(f.size)}` } : {}
5499
+ ...blob !== f ? { note: L.downscaledFrom(L.bytes(f.size)) } : {}
5342
5500
  });
5343
5501
  } catch (err) {
5344
5502
  problem = `${name}: ${err instanceof Error ? err.message : String(err)}`;
5345
5503
  }
5346
5504
  }
5347
- setAttachError(problem);
5348
- if (added.length) setPending((cur) => [...cur, ...added]);
5505
+ const names = (list2) => list2.length > 3 ? `${list2.slice(0, 3).join(", ")}, \u2026` : list2.join(", ");
5506
+ const said = [
5507
+ problem,
5508
+ noRoom.images.length ? L.tooManyImages(names(noRoom.images), bounds.maxImages) : "",
5509
+ noRoom.bytes.length ? L.messageTooLarge(names(noRoom.bytes), Math.round(bounds.maxTotalBytes / 1024 / 1024)) : ""
5510
+ ];
5511
+ setAttachError(said.filter(Boolean).join(" ") || void 0);
5349
5512
  if (fileRef.current) fileRef.current.value = "";
5350
5513
  };
5351
5514
  const onPaste = (e) => {
@@ -5614,7 +5777,10 @@ ${draftText}` : draftText);
5614
5777
  if (renderAttachment) return /* @__PURE__ */ jsx5("span", { children: renderAttachment(a, remove) }, a.id);
5615
5778
  return /* @__PURE__ */ jsxs3("span", { className: "awr-chip awr-file", title: a.note ?? a.mediaType, children: [
5616
5779
  a.kind === "image" && a.dataUrl ? /* @__PURE__ */ jsx5("img", { className: "awr-file__thumb", src: a.dataUrl, alt: a.name }) : /* @__PURE__ */ jsx5(FileIcon, { size: 14 }),
5617
- /* @__PURE__ */ jsx5("span", { className: "awr-file__name", children: a.name }),
5780
+ a.note ? /* @__PURE__ */ jsxs3("span", { className: "awr-file__text", children: [
5781
+ /* @__PURE__ */ jsx5("span", { className: "awr-file__name", children: a.name }),
5782
+ /* @__PURE__ */ jsx5("span", { className: "awr-file__note", children: a.note })
5783
+ ] }) : /* @__PURE__ */ jsx5("span", { className: "awr-file__name", children: a.name }),
5618
5784
  /* @__PURE__ */ jsx5(
5619
5785
  "button",
5620
5786
  {
@@ -6824,13 +6990,14 @@ var useFileUrl = (files, path, mediaType) => {
6824
6990
  }, [files, path, mediaType]);
6825
6991
  return url;
6826
6992
  };
6993
+ var baseName = (path) => path.split(/[\\/]/).filter(Boolean).pop() ?? path;
6827
6994
  var GeneratedMedia = ({ media, files, labels }) => {
6828
6995
  const L = useLabels(labels);
6829
6996
  const family = mediaFamilyOf(media.mediaType);
6830
6997
  const type = family ? media.mediaType.toLowerCase().split(";")[0].trim() : void 0;
6831
6998
  const url = useFileUrl(files, media.path, type);
6832
6999
  if (url && family === "image") {
6833
- return /* @__PURE__ */ jsx11(
7000
+ const thumb = /* @__PURE__ */ jsx11(
6834
7001
  ImageThumb,
6835
7002
  {
6836
7003
  className: "awr-media awr-media--image",
@@ -6842,6 +7009,20 @@ var GeneratedMedia = ({ media, files, labels }) => {
6842
7009
  labels
6843
7010
  }
6844
7011
  );
7012
+ const refs = media.references;
7013
+ if (!refs || refs.paths.length === 0) return thumb;
7014
+ const names = refs.paths.map(baseName).join(", ");
7015
+ return /* @__PURE__ */ jsxs9("span", { className: "awr-media-refs", children: [
7016
+ thumb,
7017
+ /* @__PURE__ */ jsx11(
7018
+ "span",
7019
+ {
7020
+ className: `awr-media__refs${refs.used ? "" : " awr-media__refs--unused"}`,
7021
+ title: refs.paths.join("\n"),
7022
+ children: refs.used ? L.mediaReferences(names) : L.mediaReferencesUnused(names)
7023
+ }
7024
+ )
7025
+ ] });
6845
7026
  }
6846
7027
  if (url && family === "audio") {
6847
7028
  return /* @__PURE__ */ jsx11("span", { className: "awr-media awr-media--audio", title: media.path, children: /* @__PURE__ */ jsx11(
@@ -9121,6 +9302,7 @@ export {
9121
9302
  APP_MAX_HEIGHT,
9122
9303
  APP_MIN_HEIGHT,
9123
9304
  ASK_USER_TOOL_NAME,
9305
+ ATTACHMENT_BOUNDS,
9124
9306
  AgentChat,
9125
9307
  AgentComposer,
9126
9308
  AgentLabelsProvider,
@@ -9215,7 +9397,9 @@ export {
9215
9397
  askUserOutputKept,
9216
9398
  askUserWith,
9217
9399
  attachmentKindOf,
9400
+ attachmentOverLimit,
9218
9401
  attachmentRefusal,
9402
+ attachmentTransformOf,
9219
9403
  buildMcpAppDocument,
9220
9404
  buildMcpAppSandboxShell,
9221
9405
  buildSandboxedDocument,
@@ -9250,6 +9434,7 @@ export {
9250
9434
  formatElapsed,
9251
9435
  grantedAppCsp,
9252
9436
  imageExtensionOf,
9437
+ imageSizeOf,
9253
9438
  isMcpAppSandboxMessage,
9254
9439
  isWebGPUAvailable2 as isWebGPUAvailable,
9255
9440
  lessonsOf,
@@ -9267,6 +9452,7 @@ export {
9267
9452
  menuSections,
9268
9453
  mergeChatRecord,
9269
9454
  mergeLabels,
9455
+ messageOverLimit,
9270
9456
  newChatId,
9271
9457
  noticesOf,
9272
9458
  onStorageChange,