@dudko.dev/agent-web 0.0.50 → 0.0.52

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 (39) hide show
  1. package/README.md +49 -4
  2. package/dist/agent-web.js +173 -165
  3. package/dist/agent-web.js.map +1 -1
  4. package/dist/{chunk-3V27UZT6.js → chunk-DOWC4CFZ.js} +257 -3
  5. package/dist/chunk-DOWC4CFZ.js.map +1 -0
  6. package/dist/{chunk-IT77BVAD.js → chunk-HXUR2SG5.js} +2 -2
  7. package/dist/{chunk-JTZEUPIG.js → chunk-NUL6QEAX.js} +49 -49
  8. package/dist/chunk-NUL6QEAX.js.map +1 -0
  9. package/dist/{chunk-6XHCPSZE.js → chunk-QWOKTI62.js} +58 -6
  10. package/dist/chunk-QWOKTI62.js.map +1 -0
  11. package/dist/chunk-R5VCITT3.js +192 -0
  12. package/dist/chunk-R5VCITT3.js.map +1 -0
  13. package/dist/{chunk-7Y5UC6L7.js → chunk-SVGIGIRR.js} +3 -3
  14. package/dist/fit-reference-worker.cjs +158 -0
  15. package/dist/fit-reference-worker.cjs.map +1 -0
  16. package/dist/fit-reference-worker.d.cts +1 -0
  17. package/dist/fit-reference-worker.d.ts +1 -0
  18. package/dist/fit-reference-worker.js +16 -0
  19. package/dist/fit-reference-worker.js.map +1 -0
  20. package/dist/index.cjs +1366 -366
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +130 -72
  23. package/dist/index.d.ts +130 -72
  24. package/dist/index.js +589 -89
  25. package/dist/index.js.map +1 -1
  26. package/dist/mcp.js +2 -2
  27. package/dist/media-fit-worker-Do1qzteo.d.cts +159 -0
  28. package/dist/media-fit-worker-Do1qzteo.d.ts +159 -0
  29. package/dist/{sandbox-IGTCMOOX.js → sandbox-QNEDQZTA.js} +3 -3
  30. package/dist/secrets.js +3 -3
  31. package/dist/{webllm-BEL5A4OF.js → webllm-EZSJGU6P.js} +2 -2
  32. package/package.json +14 -2
  33. package/dist/chunk-3V27UZT6.js.map +0 -1
  34. package/dist/chunk-6XHCPSZE.js.map +0 -1
  35. package/dist/chunk-JTZEUPIG.js.map +0 -1
  36. /package/dist/{chunk-IT77BVAD.js.map → chunk-HXUR2SG5.js.map} +0 -0
  37. /package/dist/{chunk-7Y5UC6L7.js.map → chunk-SVGIGIRR.js.map} +0 -0
  38. /package/dist/{sandbox-IGTCMOOX.js.map → sandbox-QNEDQZTA.js.map} +0 -0
  39. /package/dist/{webllm-BEL5A4OF.js.map → webllm-EZSJGU6P.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools/media-fit.ts"],"sourcesContent":["// `media.fitReference` for the browser: a reference picture over the bounds made small enough to\n// send, with the browser's own codecs - `createImageBitmap` decodes and scales, an\n// `OffscreenCanvas` encodes. Web APIs only (no DOM, no `node:*`): it works in a page and in a\n// Web Worker. On a page's thread the encode is a long task (about 200 ms for a 4096 px JPEG), so a\n// host runs it in a worker: `fitReferenceInWorker(() => new Worker(...))` with the\n// `@dudko.dev/agent-web/fit-reference-worker` entry, which serves `fitReferenceImage` by itself.\n//\n// Types only from the shared file: the worker entry stays a few kilobytes.\nimport type {\n IFittedReference,\n IFitReferenceOptions,\n IReferenceBounds,\n IReferencePicture,\n MediaFitReference,\n} from './media-shared.js'\n\n/** JPEG qualities tried at each size, best first. */\nconst QUALITIES = [0.85, 0.72, 0.6]\n/** How much smaller each next size is (on each side), and how many sizes are tried. */\nconst STEP = 0.75\nconst SIZES = 6\n\nconst positive = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n > 0\n\n/** Width and height scaled by `scale`, rounded DOWN (never over the bound), at least 1. */\nconst scaled = (width: number, height: number, scale: number) => ({\n width: Math.max(1, Math.floor(width * scale)),\n height: Math.max(1, Math.floor(height * scale)),\n})\n\nconst isPortrait = (w: number, h: number) => w < h\n\n/**\n * The picture decoded and scaled so that its longer side is at most `maxSide`, as the browser\n * shows it (EXIF orientation applied).\n *\n * Only the SHORTER side is asked for (`resizeWidth` or `resizeHeight`): the browser keeps the\n * aspect, so the picture is never stretched. The header's width and height are the stored ones; a\n * phone's portrait photo is stored landscape with an orientation tag, and the browser turns it -\n * then the side asked for was the longer one of the turned picture and the result is smaller than\n * it could be (never larger), so it is decoded once more with the side it really has.\n *\n * A browser that ignores the resize options hands back the picture at its full size: it is then\n * scaled when it is drawn (`drawImage`, smoothing 'high') - the same result, with the full-size\n * bitmap held in memory meanwhile.\n */\nconst decodeScaled = async (\n blob: Blob,\n width: number,\n height: number,\n maxSide: number,\n): Promise<ImageBitmap> => {\n const scale = Math.min(1, maxSide / Math.max(width, height))\n const target = scaled(width, height, scale)\n const decode = (portrait: boolean, w: number, h: number) =>\n createImageBitmap(\n blob,\n portrait\n ? { resizeWidth: w, resizeQuality: 'high' }\n : { resizeHeight: h, resizeQuality: 'high' },\n )\n const first = await decode(isPortrait(width, height), target.width, target.height)\n const turned =\n width !== height &&\n isPortrait(first.width, first.height) !== isPortrait(width, height) &&\n Math.max(first.width, first.height) < Math.max(target.width, target.height)\n if (!turned) return first\n first.close()\n // The browser turned it: the stored height is its width now.\n const again = scaled(height, width, scale)\n return decode(isPortrait(height, width), again.width, again.height)\n}\n\n/** What fits in `maxSide`, from the bitmap as it is (in case the resize options were ignored). */\nconst fitSide = (bitmap: ImageBitmap, maxSide: number) =>\n scaled(bitmap.width, bitmap.height, Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height)))\n\nconst draw = (bitmap: ImageBitmap, width: number, height: number, opaque: boolean) => {\n const canvas = new OffscreenCanvas(width, height)\n const ctx = canvas.getContext('2d')\n if (!ctx) throw new Error('fitReferenceImage: no 2D canvas')\n if (opaque) {\n // JPEG has no transparency: what was transparent becomes white, not black.\n ctx.fillStyle = '#fff'\n ctx.fillRect(0, 0, width, height)\n }\n ctx.imageSmoothingEnabled = true\n ctx.imageSmoothingQuality = 'high'\n ctx.drawImage(bitmap, 0, 0, width, height)\n return canvas\n}\n\nconst bytesOf = async (blob: Blob): Promise<Uint8Array> => new Uint8Array(await blob.arrayBuffer())\n\n/**\n * `media.fitReference` with the browser's codecs. The longer side is brought to at most\n * `maxSide`; a PNG stays a PNG when it then fits in `maxBytes` (a screenshot keeps sharp text),\n * anything else - and a PNG that does not fit - becomes a JPEG (on white where it was\n * transparent), at falling quality and then falling size until it fits. undefined when this\n * browser cannot do it (no `createImageBitmap` / `OffscreenCanvas`), cannot decode the picture, or\n * nothing it tried fits: the agent then refuses the picture. Stops when `options.signal` aborts.\n *\n * Decoding (`createImageBitmap` of a Blob) happens off the calling thread in Chromium and Safari;\n * the encode (`convertToBlob`) does not on a page's thread - run this in a worker\n * (`fitReferenceInWorker`) on a page that must keep answering.\n */\nexport const fitReferenceImage: MediaFitReference = async (\n picture: IReferencePicture,\n bounds: IReferenceBounds,\n options?: IFitReferenceOptions,\n): Promise<IFittedReference | undefined> => {\n if (typeof createImageBitmap !== 'function' || typeof OffscreenCanvas === 'undefined') {\n return undefined\n }\n const { maxSide, maxBytes } = bounds ?? ({} as IReferenceBounds)\n if (!positive(maxSide) || !positive(maxBytes)) return undefined\n if (\n !(picture?.bytes instanceof Uint8Array) ||\n !positive(picture.width) ||\n !positive(picture.height)\n )\n return undefined\n const signal = options?.signal\n signal?.throwIfAborted()\n let bitmap: ImageBitmap\n try {\n bitmap = await decodeScaled(\n new Blob([picture.bytes as Uint8Array<ArrayBuffer>], { type: picture.mediaType }),\n picture.width,\n picture.height,\n maxSide,\n )\n } catch {\n signal?.throwIfAborted()\n return undefined // a picture this browser cannot decode\n }\n try {\n let size = fitSide(bitmap, maxSide)\n if (picture.mediaType === 'image/png') {\n signal?.throwIfAborted()\n const png = await draw(bitmap, size.width, size.height, false).convertToBlob({\n type: 'image/png',\n })\n if (png.size <= maxBytes) return { bytes: await bytesOf(png), mediaType: 'image/png' }\n }\n for (let step = 0; step < SIZES; step++) {\n const canvas = draw(bitmap, size.width, size.height, true)\n for (const quality of QUALITIES) {\n signal?.throwIfAborted()\n const jpeg = await canvas.convertToBlob({ type: 'image/jpeg', quality })\n if (jpeg.size <= maxBytes) return { bytes: await bytesOf(jpeg), mediaType: jpeg.type }\n }\n size = scaled(size.width, size.height, STEP)\n }\n return undefined\n } finally {\n bitmap.close()\n }\n}\n\n// ── in a Web Worker ──────────────────────────────────────────────────────────\n\n/** What the page posts to the worker, and what the worker answers. */\ninterface FitRequest {\n type: 'fit-reference'\n picture: IReferencePicture\n bounds: IReferenceBounds\n}\ntype FitAnswer =\n | { type: 'fit-reference'; ok: true; bytes?: Uint8Array; mediaType?: string }\n | { type: 'fit-reference'; ok: false; error: string }\n\n/** The slice of a Worker this needs (a `Worker`, or anything shaped like one in a test). */\nexport interface FitReferenceWorker {\n postMessage(message: unknown, transfer: Transferable[]): void\n addEventListener(type: 'message' | 'error' | 'messageerror', listener: (ev: any) => void): void\n terminate(): void\n}\n\n/** Bytes that own their whole buffer can be handed over as they are; a view is copied first. */\nconst ownBytes = (bytes: Uint8Array): Uint8Array =>\n bytes.byteOffset === 0 &&\n bytes.byteLength === bytes.buffer.byteLength &&\n !(typeof SharedArrayBuffer !== 'undefined' && bytes.buffer instanceof SharedArrayBuffer)\n ? bytes\n : bytes.slice()\n\n/**\n * `media.fitReference` that runs in a Web Worker: one worker per picture, from `createWorker`,\n * terminated when it has answered - or at once when the call's signal aborts (the agent's time\n * bound, a stopped run), so a stuck decode is stopped, not just left behind. The picture's bytes\n * are transferred to the worker, not copied. The worker is the `fit-reference-worker` entry (or a\n * script that calls `serveFitReferenceWorker`):\n *\n * ```ts\n * // Vite\n * import FitWorker from '@dudko.dev/agent-web/fit-reference-worker?worker'\n * media: { imageModel, fitReference: fitReferenceInWorker(() => new FitWorker()) }\n * // bundlers that follow `new URL(..., import.meta.url)`\n * fitReferenceInWorker(\n * () =>\n * new Worker(new URL('@dudko.dev/agent-web/fit-reference-worker', import.meta.url), {\n * type: 'module',\n * }),\n * )\n * ```\n */\nexport const fitReferenceInWorker =\n (createWorker: () => FitReferenceWorker): MediaFitReference =>\n (picture, bounds, options) =>\n new Promise<IFittedReference | undefined>((resolve, reject) => {\n const signal = options?.signal\n if (signal?.aborted) {\n reject(signal.reason ?? new Error('aborted'))\n return\n }\n let worker: FitReferenceWorker\n try {\n worker = createWorker()\n } catch (err) {\n reject(err)\n return\n }\n let settled = false\n const finish = (fn: () => void) => {\n if (settled) return\n settled = true\n signal?.removeEventListener('abort', onAbort)\n worker.terminate()\n fn()\n }\n const onAbort = () => finish(() => reject(signal?.reason ?? new Error('aborted')))\n signal?.addEventListener('abort', onAbort, { once: true })\n worker.addEventListener('message', (ev: MessageEvent) => {\n const a = ev.data as FitAnswer | undefined\n if (!a || a.type !== 'fit-reference') return\n if (!a.ok) {\n finish(() => reject(new Error(`fitReferenceInWorker: ${String(a.error).slice(0, 200)}`)))\n return\n }\n finish(() =>\n resolve(\n a.bytes instanceof Uint8Array\n ? {\n bytes: a.bytes,\n ...(typeof a.mediaType === 'string' ? { mediaType: a.mediaType } : {}),\n }\n : undefined,\n ),\n )\n })\n worker.addEventListener('error', (ev: ErrorEvent) =>\n finish(() =>\n reject(new Error(`fitReferenceInWorker: the worker failed (${ev?.message ?? 'error'})`)),\n ),\n )\n worker.addEventListener('messageerror', () =>\n finish(() => reject(new Error('fitReferenceInWorker: the answer could not be read'))),\n )\n const bytes = ownBytes(picture.bytes)\n const request: FitRequest = {\n type: 'fit-reference',\n picture: {\n bytes,\n mediaType: picture.mediaType,\n width: picture.width,\n height: picture.height,\n path: picture.path,\n },\n bounds: { maxSide: bounds.maxSide, maxBytes: bounds.maxBytes },\n }\n try {\n worker.postMessage(request, [bytes.buffer])\n } catch (err) {\n finish(() => reject(err))\n }\n })\n\n/** The slice of a worker scope this needs. */\nexport interface FitReferenceWorkerScope {\n postMessage(message: unknown, transfer?: Transferable[]): void\n addEventListener(type: 'message', listener: (ev: MessageEvent) => void): void\n}\n\nexport interface ServeFitReferenceOptions {\n /** The message endpoint (default: the worker global scope). */\n scope?: FitReferenceWorkerScope\n /** What fits a picture (default: `fitReferenceImage`). */\n fit?: MediaFitReference\n}\n\n/**\n * The worker side of `fitReferenceInWorker`: answers each request with `fit` (default\n * `fitReferenceImage`), the result's bytes transferred back. The `fit-reference-worker` entry\n * calls it when it is loaded.\n */\nexport const serveFitReferenceWorker = (opts: ServeFitReferenceOptions = {}): void => {\n const scope = opts.scope ?? (globalThis as unknown as FitReferenceWorkerScope)\n const fit = opts.fit ?? fitReferenceImage\n scope.addEventListener('message', (ev: MessageEvent) => {\n const req = ev.data as FitRequest | undefined\n if (!req || req.type !== 'fit-reference') return\n const answer = (a: FitAnswer, transfer: Transferable[] = []) => scope.postMessage(a, transfer)\n // The page terminates the worker at its time bound: this signal never fires on its own.\n const signal = new AbortController().signal\n Promise.resolve()\n .then(() => fit(req.picture, req.bounds, { signal }))\n .then(\n (out) => {\n if (!out || !(out.bytes instanceof Uint8Array)) {\n answer({ type: 'fit-reference', ok: true })\n return\n }\n const bytes = ownBytes(out.bytes)\n answer(\n {\n type: 'fit-reference',\n ok: true,\n bytes,\n ...(typeof out.mediaType === 'string' ? { mediaType: out.mediaType } : {}),\n },\n [bytes.buffer],\n )\n },\n (err) =>\n answer({\n type: 'fit-reference',\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n }),\n )\n })\n}\n"],"mappings":";AAiBA,IAAM,YAAY,CAAC,MAAM,MAAM,GAAG;AAElC,IAAM,OAAO;AACb,IAAM,QAAQ;AAEd,IAAM,WAAW,CAAC,MAA4B,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,IAAI;AAGjG,IAAM,SAAS,CAAC,OAAe,QAAgB,WAAmB;AAAA,EAChE,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,KAAK,CAAC;AAAA,EAC5C,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,KAAK,CAAC;AAChD;AAEA,IAAM,aAAa,CAAC,GAAW,MAAc,IAAI;AAgBjD,IAAM,eAAe,OACnB,MACA,OACA,QACA,YACyB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IAAI,SAAS,IAAI,QAAQ,EAAE,OAAO,CAAC,CAAC,EACnD;AAAA,MACC,CAAC,QAAQ;AACP,YAAI,CAAC,OAAO,EAAE,IAAI,iBAAiB,aAAa;AAC9C,iBAAO,EAAE,MAAM,iBAAiB,IAAI,KAAK,CAAC;AAC1C;AAAA,QACF;AACA,cAAM,QAAQ,SAAS,IAAI,KAAK;AAChC;AAAA,UACE;AAAA,YACE,MAAM;AAAA,YACN,IAAI;AAAA,YACJ;AAAA,YACA,GAAI,OAAO,IAAI,cAAc,WAAW,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;AAAA,UAC1E;AAAA,UACA,CAAC,MAAM,MAAM;AAAA,QACf;AAAA,MACF;AAAA,MACA,CAAC,QACC,OAAO;AAAA,QACL,MAAM;AAAA,QACN,IAAI;AAAA,QACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACxD,CAAC;AAAA,IACL;AAAA,EACJ,CAAC;AACH;","names":[]}
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  IndexedDBVault
3
- } from "./chunk-IT77BVAD.js";
3
+ } from "./chunk-HXUR2SG5.js";
4
4
  import {
5
5
  currentTab,
6
6
  postStorageChangeFrom
7
- } from "./chunk-JTZEUPIG.js";
7
+ } from "./chunk-NUL6QEAX.js";
8
8
 
9
9
  // src/secrets/store.ts
10
10
  var VaultCredentialStore = class {
@@ -49,4 +49,4 @@ export {
49
49
  VaultCredentialStore,
50
50
  MemoryCredentialStore
51
51
  };
52
- //# sourceMappingURL=chunk-7Y5UC6L7.js.map
52
+ //# sourceMappingURL=chunk-SVGIGIRR.js.map
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/tools/media-fit-worker.ts
21
+ var media_fit_worker_exports = {};
22
+ __export(media_fit_worker_exports, {
23
+ fitReferenceImage: () => fitReferenceImage,
24
+ serveFitReferenceWorker: () => serveFitReferenceWorker
25
+ });
26
+ module.exports = __toCommonJS(media_fit_worker_exports);
27
+
28
+ // src/tools/media-fit.ts
29
+ var QUALITIES = [0.85, 0.72, 0.6];
30
+ var STEP = 0.75;
31
+ var SIZES = 6;
32
+ var positive = (n) => typeof n === "number" && Number.isFinite(n) && n > 0;
33
+ var scaled = (width, height, scale) => ({
34
+ width: Math.max(1, Math.floor(width * scale)),
35
+ height: Math.max(1, Math.floor(height * scale))
36
+ });
37
+ var isPortrait = (w, h) => w < h;
38
+ var decodeScaled = async (blob, width, height, maxSide) => {
39
+ const scale = Math.min(1, maxSide / Math.max(width, height));
40
+ const target = scaled(width, height, scale);
41
+ const decode = (portrait, w, h) => createImageBitmap(
42
+ blob,
43
+ portrait ? { resizeWidth: w, resizeQuality: "high" } : { resizeHeight: h, resizeQuality: "high" }
44
+ );
45
+ const first = await decode(isPortrait(width, height), target.width, target.height);
46
+ const turned = width !== height && isPortrait(first.width, first.height) !== isPortrait(width, height) && Math.max(first.width, first.height) < Math.max(target.width, target.height);
47
+ if (!turned) return first;
48
+ first.close();
49
+ const again = scaled(height, width, scale);
50
+ return decode(isPortrait(height, width), again.width, again.height);
51
+ };
52
+ var fitSide = (bitmap, maxSide) => scaled(bitmap.width, bitmap.height, Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height)));
53
+ var draw = (bitmap, width, height, opaque) => {
54
+ const canvas = new OffscreenCanvas(width, height);
55
+ const ctx = canvas.getContext("2d");
56
+ if (!ctx) throw new Error("fitReferenceImage: no 2D canvas");
57
+ if (opaque) {
58
+ ctx.fillStyle = "#fff";
59
+ ctx.fillRect(0, 0, width, height);
60
+ }
61
+ ctx.imageSmoothingEnabled = true;
62
+ ctx.imageSmoothingQuality = "high";
63
+ ctx.drawImage(bitmap, 0, 0, width, height);
64
+ return canvas;
65
+ };
66
+ var bytesOf = async (blob) => new Uint8Array(await blob.arrayBuffer());
67
+ var fitReferenceImage = async (picture, bounds, options) => {
68
+ if (typeof createImageBitmap !== "function" || typeof OffscreenCanvas === "undefined") {
69
+ return void 0;
70
+ }
71
+ const { maxSide, maxBytes } = bounds ?? {};
72
+ if (!positive(maxSide) || !positive(maxBytes)) return void 0;
73
+ if (!(picture?.bytes instanceof Uint8Array) || !positive(picture.width) || !positive(picture.height))
74
+ return void 0;
75
+ const signal = options?.signal;
76
+ signal?.throwIfAborted();
77
+ let bitmap;
78
+ try {
79
+ bitmap = await decodeScaled(
80
+ new Blob([picture.bytes], { type: picture.mediaType }),
81
+ picture.width,
82
+ picture.height,
83
+ maxSide
84
+ );
85
+ } catch {
86
+ signal?.throwIfAborted();
87
+ return void 0;
88
+ }
89
+ try {
90
+ let size = fitSide(bitmap, maxSide);
91
+ if (picture.mediaType === "image/png") {
92
+ signal?.throwIfAborted();
93
+ const png = await draw(bitmap, size.width, size.height, false).convertToBlob({
94
+ type: "image/png"
95
+ });
96
+ if (png.size <= maxBytes) return { bytes: await bytesOf(png), mediaType: "image/png" };
97
+ }
98
+ for (let step = 0; step < SIZES; step++) {
99
+ const canvas = draw(bitmap, size.width, size.height, true);
100
+ for (const quality of QUALITIES) {
101
+ signal?.throwIfAborted();
102
+ const jpeg = await canvas.convertToBlob({ type: "image/jpeg", quality });
103
+ if (jpeg.size <= maxBytes) return { bytes: await bytesOf(jpeg), mediaType: jpeg.type };
104
+ }
105
+ size = scaled(size.width, size.height, STEP);
106
+ }
107
+ return void 0;
108
+ } finally {
109
+ bitmap.close();
110
+ }
111
+ };
112
+ var ownBytes = (bytes) => bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength && !(typeof SharedArrayBuffer !== "undefined" && bytes.buffer instanceof SharedArrayBuffer) ? bytes : bytes.slice();
113
+ var serveFitReferenceWorker = (opts = {}) => {
114
+ const scope = opts.scope ?? globalThis;
115
+ const fit = opts.fit ?? fitReferenceImage;
116
+ scope.addEventListener("message", (ev) => {
117
+ const req = ev.data;
118
+ if (!req || req.type !== "fit-reference") return;
119
+ const answer = (a, transfer = []) => scope.postMessage(a, transfer);
120
+ const signal = new AbortController().signal;
121
+ Promise.resolve().then(() => fit(req.picture, req.bounds, { signal })).then(
122
+ (out) => {
123
+ if (!out || !(out.bytes instanceof Uint8Array)) {
124
+ answer({ type: "fit-reference", ok: true });
125
+ return;
126
+ }
127
+ const bytes = ownBytes(out.bytes);
128
+ answer(
129
+ {
130
+ type: "fit-reference",
131
+ ok: true,
132
+ bytes,
133
+ ...typeof out.mediaType === "string" ? { mediaType: out.mediaType } : {}
134
+ },
135
+ [bytes.buffer]
136
+ );
137
+ },
138
+ (err) => answer({
139
+ type: "fit-reference",
140
+ ok: false,
141
+ error: err instanceof Error ? err.message : String(err)
142
+ })
143
+ );
144
+ });
145
+ };
146
+
147
+ // src/tools/media-fit-worker.ts
148
+ var inWorker = () => {
149
+ const g = globalThis;
150
+ return typeof g.WorkerGlobalScope !== "undefined" && typeof g.document === "undefined";
151
+ };
152
+ if (inWorker()) serveFitReferenceWorker();
153
+ // Annotate the CommonJS export names for ESM import in node:
154
+ 0 && (module.exports = {
155
+ fitReferenceImage,
156
+ serveFitReferenceWorker
157
+ });
158
+ //# sourceMappingURL=fit-reference-worker.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools/media-fit-worker.ts","../src/tools/media-fit.ts"],"sourcesContent":["import { serveFitReferenceWorker } from './media-fit.js'\n\n/**\n * The Web Worker side of `fitReferenceInWorker`: the entry\n * `@dudko.dev/agent-web/fit-reference-worker`. Loaded as a worker it serves `fitReferenceImage`\n * by itself - a reference picture over the bounds decoded, scaled and encoded off the page's\n * thread:\n *\n * ```ts\n * // Vite\n * import FitWorker from '@dudko.dev/agent-web/fit-reference-worker?worker'\n * createAgent({ media: { imageModel, fitReference: fitReferenceInWorker(() => new FitWorker()) } })\n * ```\n *\n * One worker fits one picture and is terminated by the page when it has answered, or at the\n * agent's time bound. Web APIs only (`createImageBitmap`, `OffscreenCanvas`); nothing else is\n * imported, so the worker's chunk is a few kilobytes.\n */\nexport { serveFitReferenceWorker, fitReferenceImage } from './media-fit.js'\n\n// Served only inside a worker (not when a page, or a test, imports the module).\nconst inWorker = (): boolean => {\n const g = globalThis as { WorkerGlobalScope?: unknown; document?: unknown }\n return typeof g.WorkerGlobalScope !== 'undefined' && typeof g.document === 'undefined'\n}\n\nif (inWorker()) serveFitReferenceWorker()\n","// `media.fitReference` for the browser: a reference picture over the bounds made small enough to\n// send, with the browser's own codecs - `createImageBitmap` decodes and scales, an\n// `OffscreenCanvas` encodes. Web APIs only (no DOM, no `node:*`): it works in a page and in a\n// Web Worker. On a page's thread the encode is a long task (about 200 ms for a 4096 px JPEG), so a\n// host runs it in a worker: `fitReferenceInWorker(() => new Worker(...))` with the\n// `@dudko.dev/agent-web/fit-reference-worker` entry, which serves `fitReferenceImage` by itself.\n//\n// Types only from the shared file: the worker entry stays a few kilobytes.\nimport type {\n IFittedReference,\n IFitReferenceOptions,\n IReferenceBounds,\n IReferencePicture,\n MediaFitReference,\n} from './media-shared.js'\n\n/** JPEG qualities tried at each size, best first. */\nconst QUALITIES = [0.85, 0.72, 0.6]\n/** How much smaller each next size is (on each side), and how many sizes are tried. */\nconst STEP = 0.75\nconst SIZES = 6\n\nconst positive = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n > 0\n\n/** Width and height scaled by `scale`, rounded DOWN (never over the bound), at least 1. */\nconst scaled = (width: number, height: number, scale: number) => ({\n width: Math.max(1, Math.floor(width * scale)),\n height: Math.max(1, Math.floor(height * scale)),\n})\n\nconst isPortrait = (w: number, h: number) => w < h\n\n/**\n * The picture decoded and scaled so that its longer side is at most `maxSide`, as the browser\n * shows it (EXIF orientation applied).\n *\n * Only the SHORTER side is asked for (`resizeWidth` or `resizeHeight`): the browser keeps the\n * aspect, so the picture is never stretched. The header's width and height are the stored ones; a\n * phone's portrait photo is stored landscape with an orientation tag, and the browser turns it -\n * then the side asked for was the longer one of the turned picture and the result is smaller than\n * it could be (never larger), so it is decoded once more with the side it really has.\n *\n * A browser that ignores the resize options hands back the picture at its full size: it is then\n * scaled when it is drawn (`drawImage`, smoothing 'high') - the same result, with the full-size\n * bitmap held in memory meanwhile.\n */\nconst decodeScaled = async (\n blob: Blob,\n width: number,\n height: number,\n maxSide: number,\n): Promise<ImageBitmap> => {\n const scale = Math.min(1, maxSide / Math.max(width, height))\n const target = scaled(width, height, scale)\n const decode = (portrait: boolean, w: number, h: number) =>\n createImageBitmap(\n blob,\n portrait\n ? { resizeWidth: w, resizeQuality: 'high' }\n : { resizeHeight: h, resizeQuality: 'high' },\n )\n const first = await decode(isPortrait(width, height), target.width, target.height)\n const turned =\n width !== height &&\n isPortrait(first.width, first.height) !== isPortrait(width, height) &&\n Math.max(first.width, first.height) < Math.max(target.width, target.height)\n if (!turned) return first\n first.close()\n // The browser turned it: the stored height is its width now.\n const again = scaled(height, width, scale)\n return decode(isPortrait(height, width), again.width, again.height)\n}\n\n/** What fits in `maxSide`, from the bitmap as it is (in case the resize options were ignored). */\nconst fitSide = (bitmap: ImageBitmap, maxSide: number) =>\n scaled(bitmap.width, bitmap.height, Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height)))\n\nconst draw = (bitmap: ImageBitmap, width: number, height: number, opaque: boolean) => {\n const canvas = new OffscreenCanvas(width, height)\n const ctx = canvas.getContext('2d')\n if (!ctx) throw new Error('fitReferenceImage: no 2D canvas')\n if (opaque) {\n // JPEG has no transparency: what was transparent becomes white, not black.\n ctx.fillStyle = '#fff'\n ctx.fillRect(0, 0, width, height)\n }\n ctx.imageSmoothingEnabled = true\n ctx.imageSmoothingQuality = 'high'\n ctx.drawImage(bitmap, 0, 0, width, height)\n return canvas\n}\n\nconst bytesOf = async (blob: Blob): Promise<Uint8Array> => new Uint8Array(await blob.arrayBuffer())\n\n/**\n * `media.fitReference` with the browser's codecs. The longer side is brought to at most\n * `maxSide`; a PNG stays a PNG when it then fits in `maxBytes` (a screenshot keeps sharp text),\n * anything else - and a PNG that does not fit - becomes a JPEG (on white where it was\n * transparent), at falling quality and then falling size until it fits. undefined when this\n * browser cannot do it (no `createImageBitmap` / `OffscreenCanvas`), cannot decode the picture, or\n * nothing it tried fits: the agent then refuses the picture. Stops when `options.signal` aborts.\n *\n * Decoding (`createImageBitmap` of a Blob) happens off the calling thread in Chromium and Safari;\n * the encode (`convertToBlob`) does not on a page's thread - run this in a worker\n * (`fitReferenceInWorker`) on a page that must keep answering.\n */\nexport const fitReferenceImage: MediaFitReference = async (\n picture: IReferencePicture,\n bounds: IReferenceBounds,\n options?: IFitReferenceOptions,\n): Promise<IFittedReference | undefined> => {\n if (typeof createImageBitmap !== 'function' || typeof OffscreenCanvas === 'undefined') {\n return undefined\n }\n const { maxSide, maxBytes } = bounds ?? ({} as IReferenceBounds)\n if (!positive(maxSide) || !positive(maxBytes)) return undefined\n if (\n !(picture?.bytes instanceof Uint8Array) ||\n !positive(picture.width) ||\n !positive(picture.height)\n )\n return undefined\n const signal = options?.signal\n signal?.throwIfAborted()\n let bitmap: ImageBitmap\n try {\n bitmap = await decodeScaled(\n new Blob([picture.bytes as Uint8Array<ArrayBuffer>], { type: picture.mediaType }),\n picture.width,\n picture.height,\n maxSide,\n )\n } catch {\n signal?.throwIfAborted()\n return undefined // a picture this browser cannot decode\n }\n try {\n let size = fitSide(bitmap, maxSide)\n if (picture.mediaType === 'image/png') {\n signal?.throwIfAborted()\n const png = await draw(bitmap, size.width, size.height, false).convertToBlob({\n type: 'image/png',\n })\n if (png.size <= maxBytes) return { bytes: await bytesOf(png), mediaType: 'image/png' }\n }\n for (let step = 0; step < SIZES; step++) {\n const canvas = draw(bitmap, size.width, size.height, true)\n for (const quality of QUALITIES) {\n signal?.throwIfAborted()\n const jpeg = await canvas.convertToBlob({ type: 'image/jpeg', quality })\n if (jpeg.size <= maxBytes) return { bytes: await bytesOf(jpeg), mediaType: jpeg.type }\n }\n size = scaled(size.width, size.height, STEP)\n }\n return undefined\n } finally {\n bitmap.close()\n }\n}\n\n// ── in a Web Worker ──────────────────────────────────────────────────────────\n\n/** What the page posts to the worker, and what the worker answers. */\ninterface FitRequest {\n type: 'fit-reference'\n picture: IReferencePicture\n bounds: IReferenceBounds\n}\ntype FitAnswer =\n | { type: 'fit-reference'; ok: true; bytes?: Uint8Array; mediaType?: string }\n | { type: 'fit-reference'; ok: false; error: string }\n\n/** The slice of a Worker this needs (a `Worker`, or anything shaped like one in a test). */\nexport interface FitReferenceWorker {\n postMessage(message: unknown, transfer: Transferable[]): void\n addEventListener(type: 'message' | 'error' | 'messageerror', listener: (ev: any) => void): void\n terminate(): void\n}\n\n/** Bytes that own their whole buffer can be handed over as they are; a view is copied first. */\nconst ownBytes = (bytes: Uint8Array): Uint8Array =>\n bytes.byteOffset === 0 &&\n bytes.byteLength === bytes.buffer.byteLength &&\n !(typeof SharedArrayBuffer !== 'undefined' && bytes.buffer instanceof SharedArrayBuffer)\n ? bytes\n : bytes.slice()\n\n/**\n * `media.fitReference` that runs in a Web Worker: one worker per picture, from `createWorker`,\n * terminated when it has answered - or at once when the call's signal aborts (the agent's time\n * bound, a stopped run), so a stuck decode is stopped, not just left behind. The picture's bytes\n * are transferred to the worker, not copied. The worker is the `fit-reference-worker` entry (or a\n * script that calls `serveFitReferenceWorker`):\n *\n * ```ts\n * // Vite\n * import FitWorker from '@dudko.dev/agent-web/fit-reference-worker?worker'\n * media: { imageModel, fitReference: fitReferenceInWorker(() => new FitWorker()) }\n * // bundlers that follow `new URL(..., import.meta.url)`\n * fitReferenceInWorker(\n * () =>\n * new Worker(new URL('@dudko.dev/agent-web/fit-reference-worker', import.meta.url), {\n * type: 'module',\n * }),\n * )\n * ```\n */\nexport const fitReferenceInWorker =\n (createWorker: () => FitReferenceWorker): MediaFitReference =>\n (picture, bounds, options) =>\n new Promise<IFittedReference | undefined>((resolve, reject) => {\n const signal = options?.signal\n if (signal?.aborted) {\n reject(signal.reason ?? new Error('aborted'))\n return\n }\n let worker: FitReferenceWorker\n try {\n worker = createWorker()\n } catch (err) {\n reject(err)\n return\n }\n let settled = false\n const finish = (fn: () => void) => {\n if (settled) return\n settled = true\n signal?.removeEventListener('abort', onAbort)\n worker.terminate()\n fn()\n }\n const onAbort = () => finish(() => reject(signal?.reason ?? new Error('aborted')))\n signal?.addEventListener('abort', onAbort, { once: true })\n worker.addEventListener('message', (ev: MessageEvent) => {\n const a = ev.data as FitAnswer | undefined\n if (!a || a.type !== 'fit-reference') return\n if (!a.ok) {\n finish(() => reject(new Error(`fitReferenceInWorker: ${String(a.error).slice(0, 200)}`)))\n return\n }\n finish(() =>\n resolve(\n a.bytes instanceof Uint8Array\n ? {\n bytes: a.bytes,\n ...(typeof a.mediaType === 'string' ? { mediaType: a.mediaType } : {}),\n }\n : undefined,\n ),\n )\n })\n worker.addEventListener('error', (ev: ErrorEvent) =>\n finish(() =>\n reject(new Error(`fitReferenceInWorker: the worker failed (${ev?.message ?? 'error'})`)),\n ),\n )\n worker.addEventListener('messageerror', () =>\n finish(() => reject(new Error('fitReferenceInWorker: the answer could not be read'))),\n )\n const bytes = ownBytes(picture.bytes)\n const request: FitRequest = {\n type: 'fit-reference',\n picture: {\n bytes,\n mediaType: picture.mediaType,\n width: picture.width,\n height: picture.height,\n path: picture.path,\n },\n bounds: { maxSide: bounds.maxSide, maxBytes: bounds.maxBytes },\n }\n try {\n worker.postMessage(request, [bytes.buffer])\n } catch (err) {\n finish(() => reject(err))\n }\n })\n\n/** The slice of a worker scope this needs. */\nexport interface FitReferenceWorkerScope {\n postMessage(message: unknown, transfer?: Transferable[]): void\n addEventListener(type: 'message', listener: (ev: MessageEvent) => void): void\n}\n\nexport interface ServeFitReferenceOptions {\n /** The message endpoint (default: the worker global scope). */\n scope?: FitReferenceWorkerScope\n /** What fits a picture (default: `fitReferenceImage`). */\n fit?: MediaFitReference\n}\n\n/**\n * The worker side of `fitReferenceInWorker`: answers each request with `fit` (default\n * `fitReferenceImage`), the result's bytes transferred back. The `fit-reference-worker` entry\n * calls it when it is loaded.\n */\nexport const serveFitReferenceWorker = (opts: ServeFitReferenceOptions = {}): void => {\n const scope = opts.scope ?? (globalThis as unknown as FitReferenceWorkerScope)\n const fit = opts.fit ?? fitReferenceImage\n scope.addEventListener('message', (ev: MessageEvent) => {\n const req = ev.data as FitRequest | undefined\n if (!req || req.type !== 'fit-reference') return\n const answer = (a: FitAnswer, transfer: Transferable[] = []) => scope.postMessage(a, transfer)\n // The page terminates the worker at its time bound: this signal never fires on its own.\n const signal = new AbortController().signal\n Promise.resolve()\n .then(() => fit(req.picture, req.bounds, { signal }))\n .then(\n (out) => {\n if (!out || !(out.bytes instanceof Uint8Array)) {\n answer({ type: 'fit-reference', ok: true })\n return\n }\n const bytes = ownBytes(out.bytes)\n answer(\n {\n type: 'fit-reference',\n ok: true,\n bytes,\n ...(typeof out.mediaType === 'string' ? { mediaType: out.mediaType } : {}),\n },\n [bytes.buffer],\n )\n },\n (err) =>\n answer({\n type: 'fit-reference',\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n }),\n )\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBA,IAAM,YAAY,CAAC,MAAM,MAAM,GAAG;AAElC,IAAM,OAAO;AACb,IAAM,QAAQ;AAEd,IAAM,WAAW,CAAC,MAA4B,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,K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,KAAK;AAChC;AAAA,UACE;AAAA,YACE,MAAM;AAAA,YACN,IAAI;AAAA,YACJ;AAAA,YACA,GAAI,OAAO,IAAI,cAAc,WAAW,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;AAAA,UAC1E;AAAA,UACA,CAAC,MAAM,MAAM;AAAA,QACf;AAAA,MACF;AAAA,MACA,CAAC,QACC,OAAO;AAAA,QACL,MAAM;AAAA,QACN,IAAI;AAAA,QACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACxD,CAAC;AAAA,IACL;AAAA,EACJ,CAAC;AACH;;;ADvTA,IAAM,WAAW,MAAe;AAC9B,QAAM,IAAI;AACV,SAAO,OAAO,EAAE,sBAAsB,eAAe,OAAO,EAAE,aAAa;AAC7E;AAEA,IAAI,SAAS,EAAG,yBAAwB;","names":[]}
@@ -0,0 +1 @@
1
+ export { O as fitReferenceImage, U as serveFitReferenceWorker } from './media-fit-worker-Do1qzteo.cjs';
@@ -0,0 +1 @@
1
+ export { O as fitReferenceImage, U as serveFitReferenceWorker } from './media-fit-worker-Do1qzteo.js';
@@ -0,0 +1,16 @@
1
+ import {
2
+ fitReferenceImage,
3
+ serveFitReferenceWorker
4
+ } from "./chunk-R5VCITT3.js";
5
+
6
+ // src/tools/media-fit-worker.ts
7
+ var inWorker = () => {
8
+ const g = globalThis;
9
+ return typeof g.WorkerGlobalScope !== "undefined" && typeof g.document === "undefined";
10
+ };
11
+ if (inWorker()) serveFitReferenceWorker();
12
+ export {
13
+ fitReferenceImage,
14
+ serveFitReferenceWorker
15
+ };
16
+ //# sourceMappingURL=fit-reference-worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools/media-fit-worker.ts"],"sourcesContent":["import { serveFitReferenceWorker } from './media-fit.js'\n\n/**\n * The Web Worker side of `fitReferenceInWorker`: the entry\n * `@dudko.dev/agent-web/fit-reference-worker`. Loaded as a worker it serves `fitReferenceImage`\n * by itself - a reference picture over the bounds decoded, scaled and encoded off the page's\n * thread:\n *\n * ```ts\n * // Vite\n * import FitWorker from '@dudko.dev/agent-web/fit-reference-worker?worker'\n * createAgent({ media: { imageModel, fitReference: fitReferenceInWorker(() => new FitWorker()) } })\n * ```\n *\n * One worker fits one picture and is terminated by the page when it has answered, or at the\n * agent's time bound. Web APIs only (`createImageBitmap`, `OffscreenCanvas`); nothing else is\n * imported, so the worker's chunk is a few kilobytes.\n */\nexport { serveFitReferenceWorker, fitReferenceImage } from './media-fit.js'\n\n// Served only inside a worker (not when a page, or a test, imports the module).\nconst inWorker = (): boolean => {\n const g = globalThis as { WorkerGlobalScope?: unknown; document?: unknown }\n return typeof g.WorkerGlobalScope !== 'undefined' && typeof g.document === 'undefined'\n}\n\nif (inWorker()) serveFitReferenceWorker()\n"],"mappings":";;;;;;AAqBA,IAAM,WAAW,MAAe;AAC9B,QAAM,IAAI;AACV,SAAO,OAAO,EAAE,sBAAsB,eAAe,OAAO,EAAE,aAAa;AAC7E;AAEA,IAAI,SAAS,EAAG,yBAAwB;","names":[]}