@aglyn/plugins-ai 1.20.1 → 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 (37) 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 +8 -0
  6. package/src/lib/jobs/ai-job-import-step.js +29 -2
  7. package/src/lib/jobs/ai-job-import-step.js.map +1 -1
  8. package/src/lib/jobs/ai-site-import-document.d.ts +2 -0
  9. package/src/lib/jobs/ai-site-import-document.js +4 -0
  10. package/src/lib/jobs/ai-site-import-document.js.map +1 -1
  11. package/src/lib/jobs/ai-site-import-graphics.d.ts +47 -0
  12. package/src/lib/jobs/ai-site-import-graphics.js +151 -0
  13. package/src/lib/jobs/ai-site-import-graphics.js.map +1 -0
  14. package/src/lib/jobs/ai-site-import-honesty.d.ts +5 -0
  15. package/src/lib/jobs/ai-site-import-honesty.js +32 -1
  16. package/src/lib/jobs/ai-site-import-honesty.js.map +1 -1
  17. package/src/lib/jobs/ai-site-import-improve.d.ts +9 -1
  18. package/src/lib/jobs/ai-site-import-improve.js +26 -11
  19. package/src/lib/jobs/ai-site-import-improve.js.map +1 -1
  20. package/src/lib/jobs/ai-site-import-pictures.js +1 -1
  21. package/src/lib/jobs/ai-site-import-pictures.js.map +1 -1
  22. package/src/lib/model/ai-site-import-fidelity.d.ts +1 -0
  23. package/src/lib/model/ai-site-import-fidelity.js +4 -2
  24. package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
  25. package/src/lib/model/ai-site-import-graphic.d.ts +49 -0
  26. package/src/lib/model/ai-site-import-graphic.js +124 -0
  27. package/src/lib/model/ai-site-import-graphic.js.map +1 -0
  28. package/src/lib/model/ai-site-import-ledger.d.ts +8 -1
  29. package/src/lib/model/ai-site-import-ledger.js +7 -7
  30. package/src/lib/model/ai-site-import-ledger.js.map +1 -1
  31. package/src/lib/model/ai-site-import-marks.d.ts +24 -6
  32. package/src/lib/model/ai-site-import-marks.js +23 -6
  33. package/src/lib/model/ai-site-import-marks.js.map +1 -1
  34. package/src/lib/model/ai-site-import.d.ts +7 -0
  35. package/src/lib/model/ai-site-import.js.map +1 -1
  36. package/src/lib/server/ai-image-reads-route.js +30 -2
  37. 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.1",
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.1",
29
- "@aglyn/shared-data-enums": "1.20.1",
30
- "@aglyn/shared-data-mdi": "1.20.1",
31
- "@aglyn/shared-data-types": "1.20.1",
32
- "@aglyn/shared-ui-email-campaigns": "1.20.1",
33
- "@aglyn/shared-ui-jsx": "1.20.1",
34
- "@aglyn/shared-ui-snackstack": "1.20.1",
35
- "@aglyn/shared-ui-theme": "1.20.1",
36
- "@aglyn/shared-util-email": "1.20.1",
37
- "@aglyn/shared-util-errors": "1.20.1",
38
- "@aglyn/shared-util-http": "1.20.1",
39
- "@aglyn/shared-util-timestamp": "1.20.1",
40
- "@aglyn/shared-util-tools": "1.20.1",
41
- "@aglyn/tenant-data-admin": "1.20.1",
42
- "@aglyn/tenant-feature-instance": "1.20.1",
43
- "@aglyn/tenant-runtime": "1.20.1",
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,SAAS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CAAC;QAAWH;IAAO;IAClG,IAAI;QACF,MAAMZ,WAAW,MAAMC,MAAM,GAAGN,OAAO,KAAK,EAAExD,yBAAyB,CAAC,EAAEI,qBAAqB,EAAE;YAC/F2D,QAAQ;YACRC,SAAS;gBAAE,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;AA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O;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"}
@@ -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;
@@ -234,6 +237,11 @@ export declare function aiSiteImportSiteLines(state: AiSiteImportState): string[
234
237
  * so an earlier page's lines would otherwise be gone by the next page.
235
238
  */
236
239
  export declare function aiSiteImportWaveLines(state: AiSiteImportState, page: AiSiteImportPage): string[];
240
+ /**
241
+ * The draft id of the site's page that holds a form (AGL-4152): one whose read
242
+ * has a form with fields, or, its read emptied once it is in, a form it saved.
243
+ */
244
+ export declare function aiSiteImportFormPageId(state: Pick<AiSiteImportState, 'pages'>): string | null;
237
245
  /** The page brought in, as its page job carries it: its lines, its photos, and the pages its links may go to (AGL-4084). */
238
246
  export declare function aiSiteImportDocumentFor(state: AiSiteImportState, page: AiSiteImportPage): AiSiteImportDocument | null;
239
247
  /** One page's job: a page job's plan of one screen, its sections the old page's own, its words carried as they are. */
@@ -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,
@@ -769,6 +770,18 @@ const delivered = (items, slot)=>items.some((row)=>row.slot === slot && (row.sta
769
770
  }
770
771
  return out;
771
772
  }
773
+ /**
774
+ * The draft id of the site's page that holds a form (AGL-4152): one whose read
775
+ * has a form with fields, or, its read emptied once it is in, a form it saved.
776
+ */ export function aiSiteImportFormPageId(state) {
777
+ var _ref;
778
+ var _state_pages_find;
779
+ const holds = (page)=>{
780
+ var _page_read_forms, _page_read, _page_forms;
781
+ return !!((_page_read = page.read) == null ? void 0 : (_page_read_forms = _page_read.forms) == null ? void 0 : _page_read_forms.some((form)=>form.fields.length)) || !!((_page_forms = page.forms) == null ? void 0 : _page_forms.some((form)=>form.formId));
782
+ };
783
+ return (_ref = (_state_pages_find = state.pages.find((page)=>!page.refused && holds(page))) == null ? void 0 : _state_pages_find.draftId) != null ? _ref : null;
784
+ }
772
785
  /** The page brought in, as its page job carries it: its lines, its photos, and the pages its links may go to (AGL-4084). */ export function aiSiteImportDocumentFor(state, page) {
773
786
  var _page_build, _ref;
774
787
  var _page_read, _state_look, _state_plan_roles, _state_plan, _state_sitePhotos, _page_photos, _page_read1, _page_read_videos, _page_read2;
@@ -776,6 +789,7 @@ const delivered = (items, slot)=>items.some((row)=>row.slot === slot && (row.sta
776
789
  if (!(blocks == null ? void 0 : blocks.length)) return null;
777
790
  // How the page's wave finishes it, as stamped when the wave started (AGL-4152).
778
791
  const wave = state.waves.find((entry)=>entry.index === page.wave);
792
+ const formPage = aiSiteImportFormPageId(state);
779
793
  return _extends({
780
794
  build: (_page_build = page.build) != null ? _page_build : aiSiteImportBuildOf(page),
781
795
  finish: wave ? aiSiteImportWaveChoice(state, wave).finish : 'keep',
@@ -788,6 +802,8 @@ const delivered = (items, slot)=>items.some((row)=>row.slot === slot && (row.sta
788
802
  scope: aiSiteImportWaveLines(state, page)
789
803
  }, state.plan ? {
790
804
  plan: state.plan
805
+ } : {}, formPage ? {
806
+ formPage
791
807
  } : {}, ((_state_look = state.look) == null ? void 0 : _state_look.drawn) ? {
792
808
  theme: state.look.drawn
793
809
  } : {}, page.origin === 'proposed' ? {
@@ -1587,7 +1603,7 @@ export function createAiJobImportStep(deps = {}) {
1587
1603
  if (work.kind === 'images') {
1588
1604
  var _ref1, _ref2;
1589
1605
  var _work_page_read, _work_page_read1;
1590
- const photos = (signal == null ? void 0 : signal.aborted) ? {
1606
+ const brought = (signal == null ? void 0 : signal.aborted) ? {
1591
1607
  brought: 0,
1592
1608
  reused: 0,
1593
1609
  skipped: (_ref1 = (_work_page_read = work.page.read) == null ? void 0 : _work_page_read.images.length) != null ? _ref1 : 0,
@@ -1605,6 +1621,17 @@ export function createAiJobImportStep(deps = {}) {
1605
1621
  }, deps.fetchImage ? {
1606
1622
  fetch: deps.fetchImage
1607
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
+ });
1608
1635
  return unspent({
1609
1636
  item: {
1610
1637
  slot: work.page.slot,