@aglyn/plugins-ai 1.20.2 → 1.20.3

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 (33) hide show
  1. package/package.json +17 -17
  2. package/src/lib/jobs/ai-image-reads.d.ts +22 -5
  3. package/src/lib/jobs/ai-image-reads.js +1 -0
  4. package/src/lib/jobs/ai-image-reads.js.map +1 -1
  5. package/src/lib/jobs/ai-job-import-step.d.ts +3 -0
  6. package/src/lib/jobs/ai-job-import-step.js +14 -2
  7. package/src/lib/jobs/ai-job-import-step.js.map +1 -1
  8. package/src/lib/jobs/ai-site-import-document.js +2 -0
  9. package/src/lib/jobs/ai-site-import-document.js.map +1 -1
  10. package/src/lib/jobs/ai-site-import-graphics.d.ts +47 -0
  11. package/src/lib/jobs/ai-site-import-graphics.js +151 -0
  12. package/src/lib/jobs/ai-site-import-graphics.js.map +1 -0
  13. package/src/lib/jobs/ai-site-import-improve.d.ts +2 -1
  14. package/src/lib/jobs/ai-site-import-improve.js +7 -11
  15. package/src/lib/jobs/ai-site-import-improve.js.map +1 -1
  16. package/src/lib/jobs/ai-site-import-pictures.js +1 -1
  17. package/src/lib/jobs/ai-site-import-pictures.js.map +1 -1
  18. package/src/lib/model/ai-site-import-fidelity.d.ts +1 -0
  19. package/src/lib/model/ai-site-import-fidelity.js +4 -2
  20. package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
  21. package/src/lib/model/ai-site-import-graphic.d.ts +49 -0
  22. package/src/lib/model/ai-site-import-graphic.js +124 -0
  23. package/src/lib/model/ai-site-import-graphic.js.map +1 -0
  24. package/src/lib/model/ai-site-import-ledger.d.ts +8 -1
  25. package/src/lib/model/ai-site-import-ledger.js +7 -7
  26. package/src/lib/model/ai-site-import-ledger.js.map +1 -1
  27. package/src/lib/model/ai-site-import-marks.d.ts +24 -6
  28. package/src/lib/model/ai-site-import-marks.js +23 -6
  29. package/src/lib/model/ai-site-import-marks.js.map +1 -1
  30. package/src/lib/model/ai-site-import.d.ts +7 -0
  31. package/src/lib/model/ai-site-import.js.map +1 -1
  32. package/src/lib/server/ai-image-reads-route.js +30 -2
  33. package/src/lib/server/ai-image-reads-route.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-ai",
3
- "version": "1.20.2",
3
+ "version": "1.20.3",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,22 +25,22 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.20.2",
29
- "@aglyn/shared-data-enums": "1.20.2",
30
- "@aglyn/shared-data-mdi": "1.20.2",
31
- "@aglyn/shared-data-types": "1.20.2",
32
- "@aglyn/shared-ui-email-campaigns": "1.20.2",
33
- "@aglyn/shared-ui-jsx": "1.20.2",
34
- "@aglyn/shared-ui-snackstack": "1.20.2",
35
- "@aglyn/shared-ui-theme": "1.20.2",
36
- "@aglyn/shared-util-email": "1.20.2",
37
- "@aglyn/shared-util-errors": "1.20.2",
38
- "@aglyn/shared-util-http": "1.20.2",
39
- "@aglyn/shared-util-timestamp": "1.20.2",
40
- "@aglyn/shared-util-tools": "1.20.2",
41
- "@aglyn/tenant-data-admin": "1.20.2",
42
- "@aglyn/tenant-feature-instance": "1.20.2",
43
- "@aglyn/tenant-runtime": "1.20.2",
28
+ "@aglyn/aglyn": "1.20.3",
29
+ "@aglyn/shared-data-enums": "1.20.3",
30
+ "@aglyn/shared-data-mdi": "1.20.3",
31
+ "@aglyn/shared-data-types": "1.20.3",
32
+ "@aglyn/shared-ui-email-campaigns": "1.20.3",
33
+ "@aglyn/shared-ui-jsx": "1.20.3",
34
+ "@aglyn/shared-ui-snackstack": "1.20.3",
35
+ "@aglyn/shared-ui-theme": "1.20.3",
36
+ "@aglyn/shared-util-email": "1.20.3",
37
+ "@aglyn/shared-util-errors": "1.20.3",
38
+ "@aglyn/shared-util-http": "1.20.3",
39
+ "@aglyn/shared-util-timestamp": "1.20.3",
40
+ "@aglyn/shared-util-tools": "1.20.3",
41
+ "@aglyn/tenant-data-admin": "1.20.3",
42
+ "@aglyn/tenant-feature-instance": "1.20.3",
43
+ "@aglyn/tenant-runtime": "1.20.3",
44
44
  "@swc/helpers": "0.5.23"
45
45
  },
46
46
  "peerDependencies": {
@@ -21,15 +21,32 @@ export declare const AI_IMAGE_READS_PATH = "ai/image-reads";
21
21
  export declare const AI_IMAGE_READS_SIGNATURE = "x-aglyn-images-signature";
22
22
  /** How far a signed request's moment may be from the function's clock. */
23
23
  export declare const AI_IMAGE_READS_WINDOW_MS: number;
24
- /** The reads the function makes; `logo-raster` turns a site import's SVG logo into a PNG (AGL-4084). */
25
- export type AiImageReadsOp = 'product-photo' | 'logo-colors' | 'logo-raster';
24
+ /**
25
+ * The reads the function makes; `logo-raster` turns a site import's SVG logo
26
+ * into a PNG (AGL-4084); `picture-graphics` says which of a site import's
27
+ * pictures are graphics by their pixels (AGL-4152).
28
+ */
29
+ export type AiImageReadsOp = 'product-photo' | 'logo-colors' | 'logo-raster' | 'picture-graphics';
26
30
  /** One request's body: the asset by its media reference, and whose read it is. */
27
31
  export interface AiImageReadsRequest {
28
- op: AiImageReadsOp;
32
+ op: Exclude<AiImageReadsOp, 'logo-raster' | 'picture-graphics'>;
29
33
  ref: string;
30
34
  hostId: string;
31
35
  orgId: string;
32
36
  }
37
+ /** The most pictures one `picture-graphics` request names. */
38
+ export declare const AI_PICTURE_GRAPHICS_MAX_REFS = 40;
39
+ /**
40
+ * Which of a site import's pictures are graphics (AGL-4152): each by its
41
+ * media reference, located again by the function under the same rule; the
42
+ * answer is `{graphics}`, a flag or `null` for each, in order.
43
+ */
44
+ export interface AiPictureGraphicsRequest {
45
+ op: 'picture-graphics';
46
+ refs: readonly string[];
47
+ hostId: string;
48
+ orgId: string;
49
+ }
33
50
  /** Test seam. */
34
51
  export declare function setAiImageReadsSecretForTests(secret: (() => string) | null): void;
35
52
  /** The header value for a body signed now. Throws on a deploy with no signing secret. */
@@ -51,12 +68,12 @@ export declare function aiImageReadsOrigin(): string | null;
51
68
  * reference, which the function locates again. `null` for a location no
52
69
  * reference can name, which is never read.
53
70
  */
54
- export declare function aiImageReadsRequest(op: AiImageReadsOp, location: AiMediaAssetLocation, hostId: string, orgId: string): AiImageReadsRequest | null;
71
+ export declare function aiImageReadsRequest(op: AiImageReadsRequest['op'], location: AiMediaAssetLocation, hostId: string, orgId: string): AiImageReadsRequest | null;
55
72
  /**
56
73
  * Asks the images function for one read, signed, waiting no longer than the
57
74
  * step's own bound for it (`signal`). Throws on anything but an answer.
58
75
  */
59
- export declare function requestAiImageReads<T>(origin: string, payload: AiImageReadsRequest, signal: AbortSignal): Promise<T>;
76
+ export declare function requestAiImageReads<T>(origin: string, payload: AiImageReadsRequest | AiPictureGraphicsRequest, signal: AbortSignal): Promise<T>;
60
77
  /** The largest SVG turned into a picture. */
61
78
  export declare const AI_LOGO_RASTER_MAX_BYTES: number;
62
79
  /** The tallest picture an SVG logo is drawn at. */
@@ -53,6 +53,7 @@ import { tokenSigningSecret } from "@aglyn/tenant-data-admin/server/media-signin
53
53
  *=========================================*/ /** The images route's registered path, served under `/api/plugin-images/`. */ export const AI_IMAGE_READS_PATH = 'ai/image-reads';
54
54
  /** The request header that carries the signature: `t=<ms>,v1=<hex>`. */ export const AI_IMAGE_READS_SIGNATURE = 'x-aglyn-images-signature';
55
55
  /** How far a signed request's moment may be from the function's clock. */ export const AI_IMAGE_READS_WINDOW_MS = 5 * 60 * 1000;
56
+ /** The most pictures one `picture-graphics` request names. */ export const AI_PICTURE_GRAPHICS_MAX_REFS = 40;
56
57
  let secretOverride = null;
57
58
  /** Test seam. */ export function setAiImageReadsSecretForTests(secret) {
58
59
  secretOverride = secret;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-image-reads.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHash, createHmac, timingSafeEqual } from 'node:crypto'\nimport { PLUGIN_IMAGES_API_PREFIX } from '@aglyn/aglyn/app-utils/api-plugins'\nimport { formatMediaRef } from '@aglyn/aglyn/app-utils/media-ref'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { tokenSigningSecret } from '@aglyn/tenant-data-admin/server/media-signing'\nimport type { AiMediaAssetLocation } from './ai-media-asset'\n\n/*==========================================\n * A JOB'S IMAGE READS HAVE THEIR OWN FUNCTION (AGL-4048).\n *\n * Two job steps decode a picture from a site's media library with `sharp`:\n * the products step makes the JPEG of a product's first photo that the\n * model is shown (`ai-product-image.ts`), and the theme step reduces the\n * site logo to its dominant colors (`ai-theme-brand-inputs.ts`). `sharp`\n * takes libvips, a 17 MB native library that on Vercel only the console's\n * plugins' image function ships: neither the plugin dispatcher, where a door\n * runs a job's first step, nor the AI jobs beat, which runs every step after\n * it, carries it. So the read is a route of its own, registered to draw\n * images (`images: true`) and served at `/api/plugin-images/ai/image-reads`\n * (`server/ai-image-reads-route.ts`), and on Vercel a step asks it:\n *\n * product-photo {ref, hostId, orgId} `{read}`: the photo as the step\n * sends it, or why it was not read\n * logo-colors {ref, hostId, orgId} `{colors}`: the logo's dominant\n * colors, or null\n *\n * The function locates the asset again from the reference, the site and\n * the org, under the same rule the step used, and reads it the way the media\n * CDN would serve it, so it reads nothing the step could not have read\n * itself. Each request is signed with the platform's signing secret over the\n * moment and the body, as the card reader start-up screen's are, under this\n * route's own name, so a signature for one route is none for another. Off\n * Vercel one process holds every route, and libvips with it, so the read\n * runs where it is asked for, as before.\n *\n * Any failure is the read's own: the photo is unreadable and the copy is\n * written from the product's words, or the logo's colors are left out with\n * the note that says so.\n *=========================================*/\n\n/** The images route's registered path, served under `/api/plugin-images/`. */\nexport const AI_IMAGE_READS_PATH = 'ai/image-reads'\n\n/** The request header that carries the signature: `t=<ms>,v1=<hex>`. */\nexport const AI_IMAGE_READS_SIGNATURE = 'x-aglyn-images-signature'\n\n/** How far a signed request's moment may be from the function's clock. */\nexport const AI_IMAGE_READS_WINDOW_MS = 5 * 60 * 1000\n\n/** The reads the function makes; `logo-raster` turns a site import's SVG logo into a PNG (AGL-4084). */\nexport type AiImageReadsOp = 'product-photo' | 'logo-colors' | 'logo-raster'\n\n/** One request's body: the asset by its media reference, and whose read it is. */\nexport interface AiImageReadsRequest {\n op: AiImageReadsOp\n ref: string\n hostId: string\n orgId: string\n}\n\nlet secretOverride: (() => string) | null = null\n\n/** Test seam. */\nexport function setAiImageReadsSecretForTests(secret: (() => string) | null): void {\n secretOverride = secret\n}\n\nfunction signature(at: number, body: string): string {\n const digest = createHash('sha256').update(body).digest('hex')\n return createHmac('sha256', (secretOverride ?? tokenSigningSecret)())\n .update(`ai-image-reads:${at}.${digest}`)\n .digest('hex')\n}\n\n/** The header value for a body signed now. Throws on a deploy with no signing secret. */\nexport function signAiImageReadsRequest(body: string, nowMs: number = Date.now()): string {\n return `t=${nowMs},v1=${signature(nowMs, body)}`\n}\n\n/**\n * Whether a request's signature is ours, over this body, and recent. False\n * for anything else, a deploy with no signing secret included (fail closed).\n */\nexport function verifyAiImageReadsRequest(\n header: string | null | undefined,\n body: string,\n nowMs: number = Date.now(),\n): boolean {\n const parts = Object.fromEntries(\n String(header ?? '')\n .split(',')\n .map((part) => part.trim().split('=') as [string, string])\n .filter((pair) => pair.length === 2),\n )\n const at = Number(parts['t'])\n const given = String(parts['v1'] ?? '')\n if (!Number.isFinite(at) || !/^[a-f0-9]{64}$/.test(given)) return false\n if (Math.abs(nowMs - at) > AI_IMAGE_READS_WINDOW_MS) return false\n let expected: string\n try {\n expected = signature(at, body)\n } catch {\n return false\n }\n return timingSafeEqual(Buffer.from(given), Buffer.from(expected))\n}\n\n/**\n * Where to ask for an image read, or `null` to make it in this process. On\n * Vercel only the images function ships libvips, so every other function\n * asks it, at the console's own address; anywhere else this process can\n * decode.\n */\nexport function aiImageReadsOrigin(): string | null {\n if (process.env['VERCEL'] !== '1') return null\n return platformConsoleOrigin()\n}\n\n/**\n * The request for a located asset's read: the asset named by its media\n * reference, which the function locates again. `null` for a location no\n * reference can name, which is never read.\n */\nexport function aiImageReadsRequest(\n op: AiImageReadsOp,\n location: AiMediaAssetLocation,\n hostId: string,\n orgId: string,\n): AiImageReadsRequest | null {\n const ref = formatMediaRef(location.scopeSegment, location.mediaId)\n return ref ? { op, ref, hostId, orgId } : null\n}\n\n/**\n * The headers that get our own request past our own edge, when configured:\n * the same pair the render monitor sends (AGL-3571).\n */\nfunction edgeBypassHeaders(): Record<string, string> {\n const probe = String(process.env['AGLYN_PROBE_TOKEN'] ?? '').trim()\n const bypass = String(\n process.env['AGLYN_VERCEL_BYPASS'] || process.env['VERCEL_AUTOMATION_BYPASS_SECRET'] || '',\n ).trim()\n return {\n ...(probe ? { 'x-aglyn-probe': probe } : {}),\n ...(bypass ? { 'x-vercel-protection-bypass': bypass } : {}),\n }\n}\n\n/**\n * Asks the images function for one read, signed, waiting no longer than the\n * step's own bound for it (`signal`). Throws on anything but an answer.\n */\nexport async function requestAiImageReads<T>(\n origin: string,\n payload: AiImageReadsRequest,\n signal: AbortSignal,\n): Promise<T> {\n const body = JSON.stringify(payload)\n const response = await fetch(`${origin}/api/${PLUGIN_IMAGES_API_PREFIX}/${AI_IMAGE_READS_PATH}`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n [AI_IMAGE_READS_SIGNATURE]: signAiImageReadsRequest(body),\n ...edgeBypassHeaders(),\n },\n body,\n signal,\n })\n if (!response.ok) throw new Error(`the AI image reads function answered ${response.status}`)\n return (await response.json()) as T\n}\n\n/*------------------------------------------\n * A site import's SVG logo, as a picture (AGL-4084)\n *-----------------------------------------*/\n\n/** The largest SVG turned into a picture. */\nexport const AI_LOGO_RASTER_MAX_BYTES = 512 * 1024\n\n/** The tallest picture an SVG logo is drawn at. */\nexport const AI_LOGO_RASTER_MAX_HEIGHT = 512\n\n/** The request for an SVG logo drawn as a PNG: the drawing itself, never an address, and the height. */\nexport interface AiLogoRasterRequest {\n op: 'logo-raster'\n svg: string\n height: number\n}\n\ninterface SharpSvg {\n (input: Buffer, options?: { limitInputPixels?: number; density?: number }): {\n resize(options: { height: number; withoutEnlargement?: boolean }): { png(): { toBuffer(): Promise<Buffer> } }\n }\n}\n\n/**\n * An SVG logo drawn as a PNG of the height asked, in this process (AGL-4084).\n * `sharp`'s SVG reader loads nothing the drawing links to, so only its own\n * shapes are drawn. `null` for what is not a drawing, or is too large.\n */\nexport async function rasterizeAiLogoSvg(svg: Uint8Array, height: number): Promise<Uint8Array | null> {\n if (!svg.byteLength || svg.byteLength > AI_LOGO_RASTER_MAX_BYTES) return null\n const text = Buffer.from(svg).toString('utf8')\n if (!/<svg[\\s>]/i.test(text)) return null\n const { loadAiMediaSharp } = await import('./ai-media-asset')\n const sharp = (await loadAiMediaSharp()) as SharpSvg\n const size = Math.max(16, Math.min(AI_LOGO_RASTER_MAX_HEIGHT, Math.round(height)))\n const png = await sharp(Buffer.from(svg), { limitInputPixels: 64_000_000, density: 300 }).resize({ height: size }).png().toBuffer()\n return new Uint8Array(png)\n}\n\n/** An SVG logo drawn as a PNG by the images function (AGL-4084); `null` on anything but a picture. */\nexport async function requestAiLogoRaster(origin: string, svg: Uint8Array, height: number): Promise<Uint8Array | null> {\n if (!svg.byteLength || svg.byteLength > AI_LOGO_RASTER_MAX_BYTES) return null\n const body = JSON.stringify({ op: 'logo-raster', svg: Buffer.from(svg).toString('base64'), height } satisfies AiLogoRasterRequest)\n try {\n const response = await fetch(`${origin}/api/${PLUGIN_IMAGES_API_PREFIX}/${AI_IMAGE_READS_PATH}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', [AI_IMAGE_READS_SIGNATURE]: signAiImageReadsRequest(body), ...edgeBypassHeaders() },\n body,\n signal: AbortSignal.timeout(15_000),\n })\n if (!response.ok) return null\n const answer = (await response.json()) as { png?: unknown }\n return typeof answer.png === 'string' && answer.png ? new Uint8Array(Buffer.from(answer.png, 'base64')) : null\n } catch {\n return null\n }\n}\n"],"names":["createHash","createHmac","timingSafeEqual","PLUGIN_IMAGES_API_PREFIX","formatMediaRef","platformConsoleOrigin","tokenSigningSecret","AI_IMAGE_READS_PATH","AI_IMAGE_READS_SIGNATURE","AI_IMAGE_READS_WINDOW_MS","secretOverride","setAiImageReadsSecretForTests","secret","signature","at","body","digest","update","signAiImageReadsRequest","nowMs","Date","now","verifyAiImageReadsRequest","header","parts","Object","fromEntries","String","split","map","part","trim","filter","pair","length","Number","given","isFinite","test","Math","abs","expected","Buffer","from","aiImageReadsOrigin","process","env","aiImageReadsRequest","op","location","hostId","orgId","ref","scopeSegment","mediaId","edgeBypassHeaders","probe","bypass","requestAiImageReads","origin","payload","signal","JSON","stringify","response","fetch","method","headers","ok","Error","status","json","AI_LOGO_RASTER_MAX_BYTES","AI_LOGO_RASTER_MAX_HEIGHT","rasterizeAiLogoSvg","svg","height","byteLength","text","toString","loadAiMediaSharp","sharp","size","max","min","round","png","limitInputPixels","density","resize","toBuffer","Uint8Array","requestAiLogoRaster","AbortSignal","timeout","answer"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,UAAU,EAAEC,eAAe,QAAQ,cAAa;AACrE,SAASC,wBAAwB,QAAQ,qCAAoC;AAC7E,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,kBAAkB,QAAQ,gDAA+C;AAGlF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA+B2C,GAE3C,4EA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,gBAAgB;gBAAoB,CAAC3D,yBAAyB,EAAEU,wBAAwBH;eAAUwC;YAC7GxC;YACA8C,QAAQgC,YAAYC,OAAO,CAAC;QAC9B;QACA,IAAI,CAAC9B,SAASI,EAAE,EAAE,OAAO;QACzB,MAAM2B,SAAU,MAAM/B,SAASO,IAAI;QACnC,OAAO,OAAOwB,OAAOT,GAAG,KAAK,YAAYS,OAAOT,GAAG,GAAG,IAAIK,WAAWjD,OAAOC,IAAI,CAACoD,OAAOT,GAAG,EAAE,aAAa;IAC5G,EAAE,eAAM;QACN,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-image-reads.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHash, createHmac, timingSafeEqual } from 'node:crypto'\nimport { PLUGIN_IMAGES_API_PREFIX } from '@aglyn/aglyn/app-utils/api-plugins'\nimport { formatMediaRef } from '@aglyn/aglyn/app-utils/media-ref'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { tokenSigningSecret } from '@aglyn/tenant-data-admin/server/media-signing'\nimport type { AiMediaAssetLocation } from './ai-media-asset'\n\n/*==========================================\n * A JOB'S IMAGE READS HAVE THEIR OWN FUNCTION (AGL-4048).\n *\n * Two job steps decode a picture from a site's media library with `sharp`:\n * the products step makes the JPEG of a product's first photo that the\n * model is shown (`ai-product-image.ts`), and the theme step reduces the\n * site logo to its dominant colors (`ai-theme-brand-inputs.ts`). `sharp`\n * takes libvips, a 17 MB native library that on Vercel only the console's\n * plugins' image function ships: neither the plugin dispatcher, where a door\n * runs a job's first step, nor the AI jobs beat, which runs every step after\n * it, carries it. So the read is a route of its own, registered to draw\n * images (`images: true`) and served at `/api/plugin-images/ai/image-reads`\n * (`server/ai-image-reads-route.ts`), and on Vercel a step asks it:\n *\n * product-photo {ref, hostId, orgId} `{read}`: the photo as the step\n * sends it, or why it was not read\n * logo-colors {ref, hostId, orgId} `{colors}`: the logo's dominant\n * colors, or null\n *\n * The function locates the asset again from the reference, the site and\n * the org, under the same rule the step used, and reads it the way the media\n * CDN would serve it, so it reads nothing the step could not have read\n * itself. Each request is signed with the platform's signing secret over the\n * moment and the body, as the card reader start-up screen's are, under this\n * route's own name, so a signature for one route is none for another. Off\n * Vercel one process holds every route, and libvips with it, so the read\n * runs where it is asked for, as before.\n *\n * Any failure is the read's own: the photo is unreadable and the copy is\n * written from the product's words, or the logo's colors are left out with\n * the note that says so.\n *=========================================*/\n\n/** The images route's registered path, served under `/api/plugin-images/`. */\nexport const AI_IMAGE_READS_PATH = 'ai/image-reads'\n\n/** The request header that carries the signature: `t=<ms>,v1=<hex>`. */\nexport const AI_IMAGE_READS_SIGNATURE = 'x-aglyn-images-signature'\n\n/** How far a signed request's moment may be from the function's clock. */\nexport const AI_IMAGE_READS_WINDOW_MS = 5 * 60 * 1000\n\n/**\n * The reads the function makes; `logo-raster` turns a site import's SVG logo\n * into a PNG (AGL-4084); `picture-graphics` says which of a site import's\n * pictures are graphics by their pixels (AGL-4152).\n */\nexport type AiImageReadsOp = 'product-photo' | 'logo-colors' | 'logo-raster' | 'picture-graphics'\n\n/** One request's body: the asset by its media reference, and whose read it is. */\nexport interface AiImageReadsRequest {\n op: Exclude<AiImageReadsOp, 'logo-raster' | 'picture-graphics'>\n ref: string\n hostId: string\n orgId: string\n}\n\n/** The most pictures one `picture-graphics` request names. */\nexport const AI_PICTURE_GRAPHICS_MAX_REFS = 40\n\n/**\n * Which of a site import's pictures are graphics (AGL-4152): each by its\n * media reference, located again by the function under the same rule; the\n * answer is `{graphics}`, a flag or `null` for each, in order.\n */\nexport interface AiPictureGraphicsRequest {\n op: 'picture-graphics'\n refs: readonly string[]\n hostId: string\n orgId: string\n}\n\nlet secretOverride: (() => string) | null = null\n\n/** Test seam. */\nexport function setAiImageReadsSecretForTests(secret: (() => string) | null): void {\n secretOverride = secret\n}\n\nfunction signature(at: number, body: string): string {\n const digest = createHash('sha256').update(body).digest('hex')\n return createHmac('sha256', (secretOverride ?? tokenSigningSecret)())\n .update(`ai-image-reads:${at}.${digest}`)\n .digest('hex')\n}\n\n/** The header value for a body signed now. Throws on a deploy with no signing secret. */\nexport function signAiImageReadsRequest(body: string, nowMs: number = Date.now()): string {\n return `t=${nowMs},v1=${signature(nowMs, body)}`\n}\n\n/**\n * Whether a request's signature is ours, over this body, and recent. False\n * for anything else, a deploy with no signing secret included (fail closed).\n */\nexport function verifyAiImageReadsRequest(\n header: string | null | undefined,\n body: string,\n nowMs: number = Date.now(),\n): boolean {\n const parts = Object.fromEntries(\n String(header ?? '')\n .split(',')\n .map((part) => part.trim().split('=') as [string, string])\n .filter((pair) => pair.length === 2),\n )\n const at = Number(parts['t'])\n const given = String(parts['v1'] ?? '')\n if (!Number.isFinite(at) || !/^[a-f0-9]{64}$/.test(given)) return false\n if (Math.abs(nowMs - at) > AI_IMAGE_READS_WINDOW_MS) return false\n let expected: string\n try {\n expected = signature(at, body)\n } catch {\n return false\n }\n return timingSafeEqual(Buffer.from(given), Buffer.from(expected))\n}\n\n/**\n * Where to ask for an image read, or `null` to make it in this process. On\n * Vercel only the images function ships libvips, so every other function\n * asks it, at the console's own address; anywhere else this process can\n * decode.\n */\nexport function aiImageReadsOrigin(): string | null {\n if (process.env['VERCEL'] !== '1') return null\n return platformConsoleOrigin()\n}\n\n/**\n * The request for a located asset's read: the asset named by its media\n * reference, which the function locates again. `null` for a location no\n * reference can name, which is never read.\n */\nexport function aiImageReadsRequest(\n op: AiImageReadsRequest['op'],\n location: AiMediaAssetLocation,\n hostId: string,\n orgId: string,\n): AiImageReadsRequest | null {\n const ref = formatMediaRef(location.scopeSegment, location.mediaId)\n return ref ? { op, ref, hostId, orgId } : null\n}\n\n/**\n * The headers that get our own request past our own edge, when configured:\n * the same pair the render monitor sends (AGL-3571).\n */\nfunction edgeBypassHeaders(): Record<string, string> {\n const probe = String(process.env['AGLYN_PROBE_TOKEN'] ?? '').trim()\n const bypass = String(\n process.env['AGLYN_VERCEL_BYPASS'] || process.env['VERCEL_AUTOMATION_BYPASS_SECRET'] || '',\n ).trim()\n return {\n ...(probe ? { 'x-aglyn-probe': probe } : {}),\n ...(bypass ? { 'x-vercel-protection-bypass': bypass } : {}),\n }\n}\n\n/**\n * Asks the images function for one read, signed, waiting no longer than the\n * step's own bound for it (`signal`). Throws on anything but an answer.\n */\nexport async function requestAiImageReads<T>(\n origin: string,\n payload: AiImageReadsRequest | AiPictureGraphicsRequest,\n signal: AbortSignal,\n): Promise<T> {\n const body = JSON.stringify(payload)\n const response = await fetch(`${origin}/api/${PLUGIN_IMAGES_API_PREFIX}/${AI_IMAGE_READS_PATH}`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n [AI_IMAGE_READS_SIGNATURE]: signAiImageReadsRequest(body),\n ...edgeBypassHeaders(),\n },\n body,\n signal,\n })\n if (!response.ok) throw new Error(`the AI image reads function answered ${response.status}`)\n return (await response.json()) as T\n}\n\n/*------------------------------------------\n * A site import's SVG logo, as a picture (AGL-4084)\n *-----------------------------------------*/\n\n/** The largest SVG turned into a picture. */\nexport const AI_LOGO_RASTER_MAX_BYTES = 512 * 1024\n\n/** The tallest picture an SVG logo is drawn at. */\nexport const AI_LOGO_RASTER_MAX_HEIGHT = 512\n\n/** The request for an SVG logo drawn as a PNG: the drawing itself, never an address, and the height. */\nexport interface AiLogoRasterRequest {\n op: 'logo-raster'\n svg: string\n height: number\n}\n\ninterface SharpSvg {\n (input: Buffer, options?: { limitInputPixels?: number; density?: number }): {\n resize(options: { height: number; withoutEnlargement?: boolean }): { png(): { toBuffer(): Promise<Buffer> } }\n }\n}\n\n/**\n * An SVG logo drawn as a PNG of the height asked, in this process (AGL-4084).\n * `sharp`'s SVG reader loads nothing the drawing links to, so only its own\n * shapes are drawn. `null` for what is not a drawing, or is too large.\n */\nexport async function rasterizeAiLogoSvg(svg: Uint8Array, height: number): Promise<Uint8Array | null> {\n if (!svg.byteLength || svg.byteLength > AI_LOGO_RASTER_MAX_BYTES) return null\n const text = Buffer.from(svg).toString('utf8')\n if (!/<svg[\\s>]/i.test(text)) return null\n const { loadAiMediaSharp } = await import('./ai-media-asset')\n const sharp = (await loadAiMediaSharp()) as SharpSvg\n const size = Math.max(16, Math.min(AI_LOGO_RASTER_MAX_HEIGHT, Math.round(height)))\n const png = await sharp(Buffer.from(svg), { limitInputPixels: 64_000_000, density: 300 }).resize({ height: size }).png().toBuffer()\n return new Uint8Array(png)\n}\n\n/** An SVG logo drawn as a PNG by the images function (AGL-4084); `null` on anything but a picture. */\nexport async function requestAiLogoRaster(origin: string, svg: Uint8Array, height: number): Promise<Uint8Array | null> {\n if (!svg.byteLength || svg.byteLength > AI_LOGO_RASTER_MAX_BYTES) return null\n const body = JSON.stringify({ op: 'logo-raster', svg: Buffer.from(svg).toString('base64'), height } satisfies AiLogoRasterRequest)\n try {\n const response = await fetch(`${origin}/api/${PLUGIN_IMAGES_API_PREFIX}/${AI_IMAGE_READS_PATH}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', [AI_IMAGE_READS_SIGNATURE]: signAiImageReadsRequest(body), ...edgeBypassHeaders() },\n body,\n signal: AbortSignal.timeout(15_000),\n })\n if (!response.ok) return null\n const answer = (await response.json()) as { png?: unknown }\n return typeof answer.png === 'string' && answer.png ? new Uint8Array(Buffer.from(answer.png, 'base64')) : null\n } catch {\n return null\n }\n}\n"],"names":["createHash","createHmac","timingSafeEqual","PLUGIN_IMAGES_API_PREFIX","formatMediaRef","platformConsoleOrigin","tokenSigningSecret","AI_IMAGE_READS_PATH","AI_IMAGE_READS_SIGNATURE","AI_IMAGE_READS_WINDOW_MS","AI_PICTURE_GRAPHICS_MAX_REFS","secretOverride","setAiImageReadsSecretForTests","secret","signature","at","body","digest","update","signAiImageReadsRequest","nowMs","Date","now","verifyAiImageReadsRequest","header","parts","Object","fromEntries","String","split","map","part","trim","filter","pair","length","Number","given","isFinite","test","Math","abs","expected","Buffer","from","aiImageReadsOrigin","process","env","aiImageReadsRequest","op","location","hostId","orgId","ref","scopeSegment","mediaId","edgeBypassHeaders","probe","bypass","requestAiImageReads","origin","payload","signal","JSON","stringify","response","fetch","method","headers","ok","Error","status","json","AI_LOGO_RASTER_MAX_BYTES","AI_LOGO_RASTER_MAX_HEIGHT","rasterizeAiLogoSvg","svg","height","byteLength","text","toString","loadAiMediaSharp","sharp","size","max","min","round","png","limitInputPixels","density","resize","toBuffer","Uint8Array","requestAiLogoRaster","AbortSignal","timeout","answer"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,UAAU,EAAEC,eAAe,QAAQ,cAAa;AACrE,SAASC,wBAAwB,QAAQ,qCAAoC;AAC7E,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,kBAAkB,QAAQ,gDAA+C;AAGlF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA+B2C,GAE3C,4EAA4E,GAC5E,OAAO,MAAMC,sBAAsB,iBAAgB;AAEnD,sEAAsE,GACtE,OAAO,MAAMC,2BAA2B,2BAA0B;AAElE,wEAAwE,GACxE,OAAO,MAAMC,2BAA2B,IAAI,KAAK,KAAI;AAiBrD,4DAA4D,GAC5D,OAAO,MAAMC,+BAA+B,GAAE;AAc9C,IAAIC,iBAAwC;AAE5C,eAAe,GACf,OAAO,SAASC,8BAA8BC,MAA6B;IACzEF,iBAAiBE;AACnB;AAEA,SAASC,UAAUC,EAAU,EAAEC,IAAY;IACzC,MAAMC,SAASjB,WAAW,UAAUk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AE,aAAa;IAC5G,EAAE,eAAM;QACN,OAAO;IACT;AACF"}
@@ -19,6 +19,7 @@ import type { AiJob, AiJobItemLedger, AiJobReview } from '../model/ai-jobs.types
19
19
  import { type AiSiteImportBuild, type AiSiteImportHome, type AiSiteImportLeftOutReason, type AiSiteImportPage, type AiSiteImportPageRead, type AiSiteImportPlan, type AiSiteImportState, type AiSiteImportWave, type SiteImportLookFacts, type SiteImportNavEntry } from '../model/ai-site-import';
20
20
  import { crawlSiteForImport, type SiteImportCrawlSeams, type SiteImportInventory } from '../site-import/site-import-crawl';
21
21
  import { type SiteImportPhotosDeps } from '../site-import/site-import-images';
22
+ import { type AiSiteImportPictureGraphics } from './ai-site-import-graphics';
22
23
  import { type AiLayoutFrameSource, type AiLayoutFrameSourceGround, type AiLayoutFrameSourceRole, type AiLayoutFrameSourceTo } from '../layout-language/ai-layout-frame-source';
23
24
  import { type AiSiteImportDocument } from './ai-site-import-document';
24
25
  import { type AiSiteImportFormsDeps } from './ai-site-import-forms';
@@ -110,6 +111,8 @@ export interface AiSiteImportStepDeps {
110
111
  videoPostersFlagOn?: (orgId: string) => Promise<boolean>;
111
112
  ingest?: () => PluginMediaIngest | null;
112
113
  fetchImage?: SiteImportPhotosDeps['fetch'];
114
+ /** Which of a page's photos are graphics by their pixels (AGL-4152); absent, read where `sharp` is shipped. */
115
+ pictureGraphics?: AiSiteImportPictureGraphics;
113
116
  readRoom?: typeof readAiScreenRoom;
114
117
  readSiteName?: (firestore: FirebaseFirestore.Firestore, hostId: string) => Promise<string>;
115
118
  pageWritten?: typeof aiSitePageWritten;
@@ -67,6 +67,7 @@ import { aiModelForStep } from "../providers/routing.js";
67
67
  import { SITE_IMPORT_GENERATIVE_RELEASE_FLAG, SITE_IMPORT_RELEASE_FLAG, SITE_IMPORT_VIDEO_POSTERS_RELEASE_FLAG } from "../site-import/site-import-flag.js";
68
68
  import { crawlSiteForImport, siteImportOrigins } from "../site-import/site-import-crawl.js";
69
69
  import { bringInSiteImportPhotos } from "../site-import/site-import-images.js";
70
+ import { AI_SITE_IMPORT_GRAPHICS_MS, aiSiteImportPhotoGraphics } from "./ai-site-import-graphics.js";
70
71
  import { siteImportHeaderBrand, siteImportLabel, siteImportLeftOutReason, siteImportListedPage, siteImportPageRead, siteImportPageWords, siteImportSiteFacts, siteImportSiteName } from "../site-import/site-import-page.js";
71
72
  import { aiSiteKindFor } from "../model/ai-site-kinds.js";
72
73
  import { AI_LAYOUT_SITE_BRAND_INPUT, AI_LAYOUT_SITE_FACTS_INPUT, AI_LAYOUT_SITE_FRAME_INPUT } from "./ai-job-layout-language.js";
@@ -103,7 +104,7 @@ const DAY_MS = 24 * 60 * 60 * 1000;
103
104
  /** The least time each pass that asks no model needs. */ export const AI_SITE_IMPORT_PASS_MINIMUM_MS = {
104
105
  read: AI_SITE_IMPORT_READ_MS + OWN_READS_MS + AI_JOB_STEP_OVERHEAD_MS,
105
106
  wave: AI_SITE_IMPORT_WAVE_READ_MS + OWN_READS_MS + AI_JOB_STEP_OVERHEAD_MS,
106
- photos: AI_SITE_IMPORT_PHOTOS_MS + OWN_READS_MS + AI_JOB_STEP_OVERHEAD_MS
107
+ photos: AI_SITE_IMPORT_PHOTOS_MS + AI_SITE_IMPORT_GRAPHICS_MS + OWN_READS_MS + AI_JOB_STEP_OVERHEAD_MS
107
108
  };
108
109
  /**
109
110
  * The passes one import may take: a read, then for every page its photos,
@@ -1602,7 +1603,7 @@ export function createAiJobImportStep(deps = {}) {
1602
1603
  if (work.kind === 'images') {
1603
1604
  var _ref1, _ref2;
1604
1605
  var _work_page_read, _work_page_read1;
1605
- const photos = (signal == null ? void 0 : signal.aborted) ? {
1606
+ const brought = (signal == null ? void 0 : signal.aborted) ? {
1606
1607
  brought: 0,
1607
1608
  reused: 0,
1608
1609
  skipped: (_ref1 = (_work_page_read = work.page.read) == null ? void 0 : _work_page_read.images.length) != null ? _ref1 : 0,
@@ -1620,6 +1621,17 @@ export function createAiJobImportStep(deps = {}) {
1620
1621
  }, deps.fetchImage ? {
1621
1622
  fetch: deps.fetchImage
1622
1623
  } : {}));
1624
+ // Which of them are graphics by their pixels, read once now so a redesign reads a flag (AGL-4152).
1625
+ const assets = await aiSiteImportPhotoGraphics(brought.assets, _extends({
1626
+ firestore,
1627
+ hostId,
1628
+ orgId: job.orgId
1629
+ }, signal ? {
1630
+ signal
1631
+ } : {}), deps.pictureGraphics);
1632
+ const photos = _extends({}, brought, {
1633
+ assets
1634
+ });
1623
1635
  return unspent({
1624
1636
  item: {
1625
1637
  slot: work.page.slot,