@aglyn/plugins-ai 1.0.0-beta.250 → 1.0.0-beta.252
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +17 -17
- package/src/lib/components/ai-brief-dialog.component.js +15 -1
- package/src/lib/components/ai-brief-dialog.component.js.map +1 -1
- package/src/lib/components/ai-job-links.js +1 -1
- package/src/lib/components/ai-job-links.js.map +1 -1
- package/src/lib/components/ai-job-plan.component.js +20 -2
- package/src/lib/components/ai-job-plan.component.js.map +1 -1
- package/src/lib/components/ai-jobs-store.d.ts +11 -0
- package/src/lib/components/ai-jobs-store.js +22 -0
- package/src/lib/components/ai-jobs-store.js.map +1 -1
- package/src/lib/jobs/ai-job-crm-step.js +7 -4
- package/src/lib/jobs/ai-job-crm-step.js.map +1 -1
- package/src/lib/jobs/ai-job-drafts.d.ts +24 -0
- package/src/lib/jobs/ai-job-drafts.js +46 -0
- package/src/lib/jobs/ai-job-drafts.js.map +1 -1
- package/src/lib/jobs/ai-job-experiment-step.js +6 -1
- package/src/lib/jobs/ai-job-experiment-step.js.map +1 -1
- package/src/lib/jobs/ai-job-form-reuse.d.ts +78 -0
- package/src/lib/jobs/ai-job-form-reuse.js +136 -0
- package/src/lib/jobs/ai-job-form-reuse.js.map +1 -0
- package/src/lib/jobs/ai-job-form-step.d.ts +17 -0
- package/src/lib/jobs/ai-job-form-step.js +63 -11
- package/src/lib/jobs/ai-job-form-step.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-step.js +6 -1
- package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
- package/src/lib/jobs/ai-job-plan-step.d.ts +19 -0
- package/src/lib/jobs/ai-job-plan-step.js +39 -1
- package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
- package/src/lib/jobs/ai-job-seo-step.js +5 -3
- package/src/lib/jobs/ai-job-seo-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-content.d.ts +7 -5
- package/src/lib/jobs/ai-job-site-content.js +7 -5
- package/src/lib/jobs/ai-job-site-content.js.map +1 -1
- package/src/lib/jobs/ai-job-text-step.js +6 -3
- package/src/lib/jobs/ai-job-text-step.js.map +1 -1
- package/src/lib/jobs/ai-layout-stock-photos.d.ts +11 -7
- package/src/lib/jobs/ai-layout-stock-photos.js +25 -10
- package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
- package/src/lib/jobs/ai-stock-business-nouns.d.ts +62 -0
- package/src/lib/jobs/ai-stock-business-nouns.js +264 -0
- package/src/lib/jobs/ai-stock-business-nouns.js.map +1 -0
- package/src/lib/model/ai-build-plan.d.ts +7 -3
- package/src/lib/model/ai-build-plan.js +11 -1
- package/src/lib/model/ai-build-plan.js.map +1 -1
- package/src/lib/model/ai-credit-estimate.d.ts +32 -18
- package/src/lib/model/ai-credit-estimate.js +36 -18
- package/src/lib/model/ai-credit-estimate.js.map +1 -1
- package/src/lib/model/ai-job-activity.d.ts +30 -0
- package/src/lib/model/ai-job-activity.js +35 -0
- package/src/lib/model/ai-job-activity.js.map +1 -1
- package/src/lib/model/ai-media-credits.d.ts +5 -3
- package/src/lib/model/ai-media-credits.js +7 -5
- package/src/lib/model/ai-media-credits.js.map +1 -1
- package/src/lib/model/ai-site-job.js +6 -3
- package/src/lib/model/ai-site-job.js.map +1 -1
- package/src/lib/model/ai-site-store-pages.d.ts +5 -0
- package/src/lib/model/ai-site-store-pages.js +2 -0
- package/src/lib/model/ai-site-store-pages.js.map +1 -1
- package/src/lib/plugin-config.js +2 -2
- package/src/lib/plugin-config.js.map +1 -1
- package/src/lib/providers/anthropic-crm-wording-superseded.d.ts +29 -0
- package/src/lib/providers/anthropic-crm-wording-superseded.js +31 -0
- package/src/lib/providers/anthropic-crm-wording-superseded.js.map +1 -0
- package/src/lib/providers/catalog.d.ts +24 -17
- package/src/lib/providers/catalog.js +63 -30
- package/src/lib/providers/catalog.js.map +1 -1
- package/src/lib/providers/model-choice.d.ts +1 -1
- package/src/lib/providers/model-choice.js +39 -30
- package/src/lib/providers/model-choice.js.map +1 -1
- package/src/lib/providers/routing.d.ts +20 -1
- package/src/lib/providers/routing.js +47 -8
- package/src/lib/providers/routing.js.map +1 -1
- package/src/lib/runtime/ai-dev-env.d.ts +37 -1
- package/src/lib/runtime/ai-dev-env.js +59 -6
- package/src/lib/runtime/ai-dev-env.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.js +3 -1
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-doctrine.js +8 -4
- package/src/lib/runtime/ai-doctrine.js.map +1 -1
- package/src/lib/runtime/ai-eval-live.d.ts +8 -0
- package/src/lib/runtime/ai-eval-live.js +34 -8
- package/src/lib/runtime/ai-eval-live.js.map +1 -1
- package/src/lib/runtime/ai-palette.generated.js +4 -0
- package/src/lib/runtime/ai-palette.generated.js.map +1 -1
- package/src/lib/runtime/ai-runtime.js +17 -2
- package/src/lib/runtime/ai-runtime.js.map +1 -1
- package/src/lib/runtime/seo-fields.js +4 -3
- package/src/lib/runtime/seo-fields.js.map +1 -1
- package/src/lib/server/ai-assist.js +3 -2
- package/src/lib/server/ai-assist.js.map +1 -1
- package/src/lib/server/ai-media-svg.js +4 -0
- package/src/lib/server/ai-media-svg.js.map +1 -1
- package/src/lib/usage/ai-allotment-alerts.js +2 -5
- package/src/lib/usage/ai-allotment-alerts.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-site-content.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 { resolveMediaSrc } from '@aglyn/aglyn/app-utils/media-ref'\nimport { hostRoleCanWrite } from '@aglyn/aglyn/app-utils/organizations'\nimport { pluginResourceDraftWriter } from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport {\n publishContentEntries,\n writeContentCollection,\n writeContentEntryDraft,\n} from '@aglyn/tenant-data-admin/server/content-entry-drafts'\nimport { aiCatalogPrice, aiProductsProposalOf } from '../model/ai-products'\nimport type { AiJob, AiJobOutput } from '../model/ai-jobs.types'\nimport { aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { AI_SITE_BLOG_NAME, AI_SITE_BLOG_SLUGS, aiSiteWords } from '../model/ai-site-job'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { aiModelForStep } from '../providers/routing'\nimport {\n AI_BLOG_POST_MAX_TOKENS,\n AI_BLOG_POST_STEP,\n generateAiBlogPost,\n} from '../runtime/ai-blog-post-generation'\nimport {\n aiLayoutStarterPhotos,\n type AiLayoutPicturePhoto,\n type AiLayoutPictureSlot,\n} from '../layout-language/ai-layout-pictures'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport { aiLayoutStockPhotoSource, aiStockPhotoWordsOf } from './ai-layout-stock-photos'\nimport {\n aiLayoutListingId,\n aiLayoutListingPlacements,\n type AiLayoutListing,\n type AiLayoutListingScreen,\n} from '../layout-language/ai-layout-listings'\nimport { aiJobAdmissionFor, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiGenerationSpent, aiUnspentOutcome } from './ai-job-generation'\nimport type { AiJobStepContext, AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\n\n/**\n * A GUIDED START'S FIRST POSTS AND FIRST PRODUCTS (AGL-3676).\n *\n * A site of the kind \"Blog & writing\" or \"Online store\" got the right look\n * and pages, and nothing real in them: the writing page's cards and the\n * shop's grid named posts and products nobody had written. On a paid plan,\n * the scaffold now builds one more part for those two kinds, before the\n * pages, each its own row with its own timer and credits:\n *\n * - WRITING YOUR FIRST POSTS: a content collection \"Blog\" — the platform's\n * own blog, served at `/{slug}` with an entry page per post — and\n * `AI_SITE_POSTS` posts in it, one generation a pass. Each is written as a\n * draft through the same rules the console's routes hold\n * (`content-entry-drafts.ts`), bylined with the business's name the person\n * gave, and given a cover: a stock photo of its own title where the\n * deployment has a library, else a starter (AGL-3676), which the blog's\n * cards show. They go live with the\n * site: the guided start's publish publishes them with its pages\n * (`aiPublishSitePosts`), as a person's Publish would.\n * - ADDING YOUR FIRST PRODUCTS: the `products` step's catalog, asked for\n * `AI_SITE_PRODUCTS` products, each written through the commerce plugin's\n * `product` draft writer, at the price the catalog suggests for what it\n * is (Zach, 2026-10-12: a bar of soap is not priced like a gift set),\n * which code keeps in range (`aiCatalogPrice`); a product with no price\n * in range takes the writer's default price (his 2026-10-08 \"default a\n * price\", AGL-3676). Every price is the owner's to change, and the job's\n * row says so. Since the\n * 2026-10-08 Ember & Wick start, whose store showed no product at all,\n * each is LISTED at once (`comingSoon`: written `active`). Each gets a\n * photo in its slot, a stock photo of its own words where the deployment\n * has a library, else a starter, for the owner to replace with their\n * own.\n *\n * The pages built after them are told their titles or names, and the\n * sections that show them list the real records (`aiSiteListings`,\n * `ai-layout-listings.ts`): the shop's Product grid, the blog's posts.\n *\n * ── Not on the Free taste ────────────────────────────────────────────────\n *\n * A guided start's Free site, built on an empty site with its layout and\n * form, leaves 18 credits once its eight sections and its retried page's\n * room are held (`aiFreeSiteSectionsWithin`, AGL-3660), under the 23 one post\n * costs at its worst; and a Free plan includes neither\n * the `commerce` feature nor a product (`productsPerHost` is 0).\n * `ai-job-free-site.spec.ts` shows the arithmetic. Free sites keep the pages\n * their kind already describes; the owner adds posts and products after.\n */\n\n/** How many first posts a paid blog gets. */\nexport const AI_SITE_POSTS = 3\n\n/** How many first products a paid store gets: asked for, and the most written. */\nexport const AI_SITE_PRODUCTS = { min: 3, max: 6 } as const\n\n/** What a products row says when none of what we made could be written: our failure, refunded. */\nexport const AI_SITE_PRODUCTS_NOT_WRITTEN_COPY = 'Your first products could not be added this time.'\n\n/** What each part's row reads. */\nexport const AI_SITE_POSTS_LABEL = 'Writing your first posts'\nexport const AI_SITE_PRODUCTS_LABEL = 'Adding your first products'\n\n/** The blog the posts go in, and the addresses it may answer at (`model/ai-site-job.ts`). */\nexport { AI_SITE_BLOG_NAME, AI_SITE_BLOG_SLUGS } from '../model/ai-site-job'\n\n/** The input a site unit's own job carries what the part needs in. */\nexport const AI_SITE_CONTENT_INPUT = 'siteContent'\n\n/** Which part a site of these answers gets; `null` for the Free taste and every other kind. */\nexport function aiSiteContentPart(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n freeTaste: boolean,\n): 'posts' | 'products' | null {\n if (freeTaste) return null\n const kind = aiSiteKindOfInputs(inputs)?.id\n if (kind === 'blog') return 'posts'\n if (kind === 'store') return 'products'\n return null\n}\n\n/**\n * ASSUMED: what one post pass reads and writes beside its generation: the\n * host, the collection's slug claim and the entry's transaction.\n */\nexport const AI_SITE_POST_WRITES_MS = 1_500\n\n/** One post's pass: its generation and re-ask at the `copy.blog` ceiling, and its writes. */\nexport const AI_SITE_POST_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS[AI_BLOG_POST_STEP],\n maxTokens: AI_BLOG_POST_MAX_TOKENS,\n lookups: 0,\n ownReadsMs: AI_SITE_POST_WRITES_MS,\n})\n\n/** What a posts unit's job is told: the posts already written and the addresses the blog must not take. */\nexport interface AiSitePostsInput {\n written: Array<{ id: string; title: string }>\n total: number\n /** Addresses the site's own pages answer at, which the blog must not shadow. */\n avoidSlugs: string[]\n /** Who the posts are by: the business's name as given, else empty. */\n byline: string\n}\n\n/** What a products unit's job is told. */\nexport interface AiSiteProductsInput {\n min: number\n max: number\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\nfunction postsInputOf(job: Pick<AiJob, 'inputs'>): AiSitePostsInput {\n const raw = (job.inputs?.[AI_SITE_CONTENT_INPUT] ?? {}) as Partial<AiSitePostsInput>\n return {\n written: Array.isArray(raw.written) ? raw.written.filter((one) => one && typeof one.id === 'string') : [],\n total: typeof raw.total === 'number' && raw.total > 0 ? Math.floor(raw.total) : AI_SITE_POSTS,\n avoidSlugs: Array.isArray(raw.avoidSlugs) ? raw.avoidSlugs.map(str).filter(Boolean) : [],\n byline: str(raw.byline),\n }\n}\n\n/** The id of the `index`th post, of the blog its unit writes under `unitJobId`. */\nexport function aiSitePostId(unitJobId: string, index: number): string {\n return `${unitJobId}-${index}`\n}\n\n/** The id of the `index`th product a products unit writes. */\nexport function aiSiteProductId(unitJobId: string, index: number): string {\n return `${unitJobId}-${index}`\n}\n\n/** A site's subdomain and name, as its outputs and its posts' byline read them. */\nasync function readSite(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<{ subdomain: string | null; name: string } | null> {\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return null\n const seo = (host.get('seo') ?? {}) as Record<string, unknown>\n const subdomain = str(host.get('subdomain')) || null\n return { subdomain, name: str(host.get('displayName')) || str(seo['title']) }\n}\n\nconst limitReview = (message: string) => ({ reason: 'limit' as const, message, findings: [] })\n\nexport interface AiSitePostsRunnerDeps {\n generate?: typeof generateAiBlogPost\n writeCollection?: typeof writeContentCollection\n writeEntry?: typeof writeContentEntryDraft\n /** Where each post's cover comes from; the stock library, else the starters, otherwise. */\n cover?: typeof aiSitePostCover\n}\n\n/** A post's cover's shape: the blog's cards' (`COLLECTION_LIST_COVER_RATIO`, the posts listing's). */\nconst AI_SITE_POST_COVER_ASPECT = 3 / 2\n\n/**\n * A post's cover (AGL-3676): a stock photo of the post's own title, copied\n * into the site's library, where the deployment has a stock library; else the\n * starter photo a post was always given, turned by the job so blogs differ.\n * The blog's cards and the post's page show it, for the owner to replace.\n * Never throws: a post whose search fails takes its starter.\n */\nexport async function aiSitePostCover(input: {\n job: Pick<AiJob, '$id' | 'hostId' | 'createdBy' | 'inputs' | 'brief' | 'plan'>\n title: string\n index: number\n total: number\n signal?: AbortSignal\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}): Promise<string | null> {\n const { job, index } = input\n if (job.hostId && input.title.trim()) {\n try {\n const source = (input.stockPhotos ?? aiLayoutStockPhotoSource)({\n hostId: job.hostId,\n uid: job.createdBy,\n seed: `${job.$id}:posts:${index}`,\n business: aiSiteWords(job.inputs).about || job.brief,\n ...aiStockPhotoWordsOf(job),\n sectionNames: ['Blog'],\n jobId: aiOriginJobId(job),\n ...(input.signal ? { signal: input.signal } : {}),\n })\n const [found] = source\n ? await source([\n {\n imageId: `cover${index}`,\n frameId: null,\n iconId: null,\n alt: input.title,\n aspect: AI_SITE_POST_COVER_ASPECT,\n sectionIndex: 0,\n role: 'gallery' as const,\n },\n ])\n : []\n if (found?.src) return found.src\n } catch (error) {\n console.warn('ai site posts: the stock photo failed; the starter covers it', { error: String(error) })\n }\n }\n const starters = aiLayoutStarterPhotos(\n Array.from({ length: Math.max(input.total, index + 1) }, (_, slot) => ({\n imageId: `cover${slot}`,\n frameId: null,\n iconId: null,\n alt: '',\n aspect: 16 / 9,\n sectionIndex: slot + 1,\n role: 'gallery' as const,\n })),\n job.$id,\n )\n return starters[index]?.src ?? null\n}\n\n/**\n * The posts unit's runner, on the job the scaffold derived for it: one post a\n * pass, continuing while posts remain. Its first pass makes the blog; every\n * pass finds it again under the unit's own id, and a post under its own id,\n * so a pass repeated after its write reports the post it already wrote.\n */\nexport function createAiSitePostsRunner(deps: AiSitePostsRunnerDeps = {}): AiJobStepRunner {\n const generate = deps.generate ?? generateAiBlogPost\n const writeCollection = deps.writeCollection ?? writeContentCollection\n const writeEntry = deps.writeEntry ?? writeContentEntryDraft\n const coverFor = deps.cover ?? aiSitePostCover\n return async (context): Promise<AiJobStepOutcome> => {\n const { job, firestore, signal } = context\n const model = context.modelFor?.(AI_BLOG_POST_STEP) ?? aiModelForStep(AI_BLOG_POST_STEP)\n if (!job.hostId) return { ...aiUnspentOutcome(model), failure: 'Open the site before writing its posts.' }\n const input = postsInputOf(job)\n const index = input.written.length\n if (index >= input.total) return aiUnspentOutcome(model)\n const site = await readSite(firestore, job.hostId)\n if (!site) return { ...aiUnspentOutcome(model), failure: 'This site no longer exists.' }\n const avoid = new Set(input.avoidSlugs.map((slug) => slug.toLowerCase()))\n const blog = await writeCollection(firestore, {\n hostId: job.hostId,\n uid: job.createdBy,\n id: job.$id,\n displayName: AI_SITE_BLOG_NAME,\n slugs: AI_SITE_BLOG_SLUGS.filter((slug) => !avoid.has(slug)),\n now: context.now,\n })\n if (blog.ok === false) return aiUnspentOutcome(model, { review: limitReview(blog.error) })\n\n const generation = await generate({\n brief: job.brief,\n merchantWords: job.brief,\n earlierTitles: input.written.map((post) => post.title),\n index: index + 1,\n total: input.total,\n model,\n maxTokens: AI_SITE_POST_BUDGET.maxTokens(model),\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(generation)\n if (generation.status === 'refused') return { ...spent, refused: true }\n if (generation.status === 'needs_input') return { ...spent, failure: generation.message }\n const post = generation.value\n // A stock photo of its title as its cover, else a starter (AGL-3676).\n const cover = await coverFor({\n job,\n title: post.title,\n index,\n total: input.total,\n ...(signal ? { signal } : {}),\n }).catch(() => null)\n const byline = input.byline || site.name\n const written = await writeEntry(firestore, {\n hostId: job.hostId,\n collectionId: blog.id,\n uid: job.createdBy,\n id: aiSitePostId(job.$id, index),\n content: {\n title: post.title,\n excerpt: post.excerpt,\n body: post.body,\n seoDescription: post.seoDescription,\n ...(cover ? { coverImage: cover, coverImageAlt: post.title } : {}),\n ...(byline ? { authorName: byline } : {}),\n },\n now: context.now,\n })\n if (written.ok === false) return { ...spent, review: limitReview(written.error) }\n const output: AiJobOutput = {\n resource: 'entry',\n id: written.id,\n hostId: job.hostId,\n hostSubdomain: site.subdomain,\n label: written.title,\n note: `A post in ${blog.displayName}, at /${blog.slug}/${written.slug}. It goes live with the site.`,\n proposal: { collectionId: blog.id, collectionSlug: blog.slug, slug: written.slug },\n }\n return { ...spent, outputs: [output], ...(index + 1 < input.total ? { continue: true } : {}) }\n }\n}\n\nexport const runAiSitePostsUnit = createAiSitePostsRunner()\n\nexport interface AiSiteProductsRunnerDeps {\n /** The catalog's runner: the `products` step's. */\n catalog: AiJobStepRunner\n writerFor?: typeof pluginResourceDraftWriter\n /** Where each product's photo comes from; the stock library, else the starters, otherwise. */\n photos?: typeof aiSiteProductPhotos\n}\n\n/**\n * A photo for each product (AGL-3676), in order: a stock photo of the\n * product's own words, copied into the site's library, where the deployment\n * has a stock library; else a starter photo, as a page's empty picture takes\n * one. It fills the photo slot every product card and product page has, for\n * the owner to replace with their own; the product's note says so. Never\n * throws: a product with no photo is still written.\n */\nexport async function aiSiteProductPhotos(input: {\n job: Pick<AiJob, '$id' | 'hostId' | 'createdBy' | 'inputs' | 'brief' | 'plan'>\n names: readonly string[]\n /** What each product's photo should show, as its catalog proposed it, by position (AGL-3676). */\n shows?: readonly string[]\n signal?: AbortSignal\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}): Promise<Array<string | null>> {\n if (!input.names.length || !input.job.hostId) return input.names.map(() => null)\n const slots: AiLayoutPictureSlot[] = input.names.map((name, index) => ({\n imageId: `product${index}`,\n frameId: null,\n iconId: null,\n alt: name,\n // The product card's own shape (`cardStyle: 'photo'`).\n aspect: 4 / 5,\n sectionIndex: 0,\n role: 'gallery' as const,\n // Searched for by its own name, then what its photo shows, with the shop's\n // category, and held to that category (AGL-3676).\n product: { subjects: [name, input.shows?.[index] ?? ''].filter((words) => words.trim()) },\n }))\n const seed = `${input.job.$id}:products`\n let found: ReadonlyArray<AiLayoutPicturePhoto | null> = []\n try {\n const source = (input.stockPhotos ?? aiLayoutStockPhotoSource)({\n hostId: input.job.hostId,\n uid: input.job.createdBy,\n seed,\n business: aiSiteWords(input.job.inputs).about || input.job.brief,\n ...aiStockPhotoWordsOf(input.job),\n sectionNames: ['Products'],\n jobId: aiOriginJobId(input.job),\n // Each product may try its name, its photo's subject, its category, a\n // gift's wrapper and the craft's broad searches (AGL-3660).\n searches: slots.length * 6,\n ...(input.signal ? { signal: input.signal } : {}),\n })\n if (source) found = await source(slots)\n } catch (error) {\n console.warn('ai site products: the stock photos failed; starter photos fill them', { error: String(error) })\n }\n const starters = aiLayoutStarterPhotos(slots, seed)\n const hostId = input.job.hostId\n // Every product has a photo (AGL-3676): a starter where no stock photo\n // named its category, never an empty tile.\n return slots.map(\n (_slot, index) =>\n aiSiteProductPhotoSrc(found[index]?.src, hostId) ?? aiSiteProductPhotoSrc(starters[index]?.src, hostId),\n )\n}\n\n/**\n * A photo as a product stores it: the form the console's picker writes when\n * an owner picks one from the library (`console-media-picker-provider`), the\n * asset's CDN path `/api/media/cdn/{scope}/{mediaId}`, or a starter's own\n * site path. A page's picture slot holds the library's `media:` reference\n * (`mediaNodeSrc`), which is what the stock source hands back, and the\n * product's rules take only an https address or a path on the site: the\n * candle store's guided start of 2026-10-09 (job FYNasg1h0S) wrote no\n * product at all because every photo was a `media:` reference. The path\n * names the asset, not its bytes, so a replace in the library still reaches\n * the product. Anything else is no photo, never a value the product refuses.\n */\nexport function aiSiteProductPhotoSrc(src: string | null | undefined, hostId: string): string | null {\n if (!src) return null\n const path = resolveMediaSrc(src, { hostId })\n if (!path || path.length > 2_000 || /[\\s\"'<>]/.test(path)) return null\n return path.startsWith('/') || path.startsWith('https://') ? path : null\n}\n\n/**\n * A proposed product's real choices (AGL-3676): each option with two or more\n * distinct values. An option of one value is no choice for a shopper to make\n * — the beta.237 Willow Wick gift set's \"Scent\" select offered nothing — so\n * it is left out, and its one value stays in the product's own words.\n */\nexport function aiSiteProductChoices(\n options: ReadonlyArray<{ name: string; values: readonly string[] }> | null | undefined,\n): Array<{ name: string; values: string[] }> {\n return (options ?? []).flatMap((option) => {\n const seen = new Set<string>()\n const values = option.values\n .map((value) => value.trim())\n .filter((value) => value && !seen.has(value.toLowerCase()) && !!seen.add(value.toLowerCase()))\n return option.name.trim() && values.length >= 2 ? [{ name: option.name.trim(), values }] : []\n })\n}\n\n/** The sentence the products unit's brief ends with, which the catalog's rules read as how many. */\nexport function aiSiteProductsBriefLine(input: AiSiteProductsInput = AI_SITE_PRODUCTS): string {\n return `Propose between ${input.min} and ${input.max} products: the store's first ones.`\n}\n\n/**\n * The products unit's runner: the `products` step's catalog for the store's\n * brief, then each proposed product, up to the most a site starts with,\n * written by the plugin that keeps products at its suggested price (else the\n * store's default), listed. A\n * product past the plan's allowance stops the writing there, and the row\n * says how many were added; none at all is the allowance's review. A photo\n * the product's rules refuse is dropped and the product written without it;\n * a product they refuse outright is skipped, and none written for that\n * reason is our failure, refunded, never the person's review (AGL-3676).\n */\nexport function createAiSiteProductsRunner(deps: AiSiteProductsRunnerDeps): AiJobStepRunner {\n const writerFor = deps.writerFor ?? pluginResourceDraftWriter\n return async (context): Promise<AiJobStepOutcome> => {\n const { job } = context\n const keeper = writerFor('product')\n const model = context.modelFor?.('job.products') ?? aiModelForStep('job.products')\n if (!keeper || !job.hostId) return { ...aiUnspentOutcome(model), failure: 'Products are not available on this site.' }\n const outcome = await deps.catalog({\n ...context,\n job: { ...job, kind: 'products', inputs: { ...job.inputs, target: 'catalog' } },\n })\n if (outcome.refused || outcome.failure || outcome.review) return outcome\n const catalog = outcome.outputs.map((output) => ({ output, proposal: aiProductsProposalOf(output) })).find(\n (entry) => entry.proposal?.kind === 'catalog',\n )\n if (!catalog || catalog.proposal?.kind !== 'catalog') return { ...outcome, outputs: [] }\n const proposed = catalog.proposal.products.slice(0, AI_SITE_PRODUCTS.max)\n const photos = await (deps.photos ?? aiSiteProductPhotos)({\n job,\n names: proposed.map((product) => product.name),\n shows: proposed.map((product) => product.photo ?? ''),\n ...(context.signal ? { signal: context.signal } : {}),\n }).catch(() => proposed.map(() => null))\n const outputs: AiJobOutput[] = []\n let stopped: string | null = null\n /** The product's rules refusing what we made: ours, never the workspace's (AGL-3676). */\n let rejected: string | null = null\n for (const [index, product] of proposed.entries()) {\n const content: Record<string, unknown> = {\n name: product.name,\n type: product.type,\n // Listed at once, so no \"[gift card terms]\" gap reaches a shopper:\n // a sentence that leaves a fact for the owner is left out.\n description: aiSiteProductDescriptionWithoutGaps(product.description),\n tags: product.tags,\n // A choice is two values or more (AGL-3676): a \"Scent\" of one value\n // drew a select with nothing to pick on the live Willow Wick page.\n options: aiSiteProductChoices(product.options),\n seoTitle: product.seoTitle,\n seoDescription: product.seoDescription,\n comingSoon: true,\n // The catalog's suggested price for what the product is (Zach,\n // 2026-10-12), held to range once more here: none, or one out of\n // range, is left unstated and the writer gives the store's default.\n ...aiSiteProductPriceContent(product.price),\n }\n // A photo we picked that the product's rules refuse is dropped, never\n // the product: its slot stays empty for the owner's own.\n const photo = photos[index] ?? null\n const withPhoto = photo ? { ...content, mediaUrls: [photo] } : content\n const photoRefused =\n photo !== null &&\n keeper.writer.check(withPhoto, { hostId: job.hostId }).ok === false &&\n keeper.writer.check(content, { hostId: job.hostId }).ok\n if (photoRefused) {\n console.warn('ai site products: the product refused its photo; written without it', {\n orgId: job.orgId,\n jobId: job.$id,\n photo,\n })\n }\n const written = await keeper.writer.write({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n id: aiSiteProductId(job.$id, index),\n name: product.name,\n // Its suggested price, else the store's default, for the owner to\n // change (AGL-3676). Listed at once. Its photo slot holds a stock or\n // starter photo for the owner to replace.\n content: photoRefused ? content : withPhoto,\n })\n if (written.ok === false) {\n // A 400 is the product's rules refusing content we made: that one\n // product is skipped and the rest are still written. Anything else\n // (the allowance, the role, the site) stops the writing there.\n if (written.status === 400) {\n console.error('ai site products: the product writer refused a product we made', {\n orgId: job.orgId,\n jobId: job.$id,\n index,\n error: written.error,\n })\n rejected = written.error\n continue\n }\n stopped = written.error\n break\n }\n outputs.push({\n resource: 'product',\n id: written.id,\n hostId: job.hostId,\n hostSubdomain: catalog.output.hostSubdomain ?? null,\n label: written.name,\n note: AI_SITE_PRODUCT_NOTE,\n })\n }\n if (!outputs.length) {\n // Nothing written because the product's rules refused what we made:\n // the failure is ours, so the item's credits are refunded\n // (`aiUnitFailure` → `ours: true`). Only the workspace's allowance,\n // role or site is the person's to review.\n if (!stopped && rejected) return { ...outcome, outputs: [], failure: AI_SITE_PRODUCTS_NOT_WRITTEN_COPY }\n return { ...outcome, outputs: [], review: limitReview(stopped ?? 'No product could be added.') }\n }\n // The allowance that stopped the rest is said where the last one added is.\n const last = outputs[outputs.length - 1]\n if (stopped) {\n last.note = `${last.note} ${outputs.length} of ${proposed.length} added: ${stopped}.`\n } else if (outputs.length < proposed.length) {\n last.note = `${last.note} ${outputs.length} of ${proposed.length} added.`\n }\n return { ...outcome, outputs }\n }\n}\n\n/**\n * Whether a part may be built for this member on this site, asked before its\n * first pass so a refusal spends nothing; `null` admits. Products ask what a\n * `products` job asks (the plan's commerce feature, Commerce on and released\n * for the site) and the writer's own refusal (role, allowance); posts ask\n * that the member may write the site's content.\n */\nexport async function aiSiteContentRefusal(\n part: 'posts' | 'products',\n context: Pick<AiJobStepContext, 'firestore' | 'org' | 'now'> & { job: Pick<AiJob, 'orgId' | 'hostId' | 'createdBy' | 'inputs'> },\n deps: { writerFor?: typeof pluginResourceDraftWriter; admissionFor?: typeof aiJobAdmissionFor } = {},\n): Promise<string | null> {\n const { job, firestore } = context\n if (!job.hostId) return 'Open the site first.'\n if (part === 'posts') {\n const host = await firestore.collection('hosts').doc(job.hostId).get()\n return hostRoleCanWrite((host.get('memberRoles') ?? {})[job.createdBy]) ? null : 'Editing requires the editor role'\n }\n const admission = (deps.admissionFor ?? aiJobAdmissionFor)('products')\n const refused: AiJobAdmissionRefusal | null = admission\n ? await admission({\n firestore,\n orgId: job.orgId,\n hostId: job.hostId,\n inputs: { target: 'catalog' },\n org: context.org ?? null,\n uid: job.createdBy,\n })\n : { status: 403, error: 'Products are not available on this site.' }\n if (refused) return refused.error\n const keeper = (deps.writerFor ?? pluginResourceDraftWriter)('product')\n if (!keeper) return 'Products are not available on this site.'\n const room = await keeper.writer.refusal({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n })\n return room?.error ?? null\n}\n\n/** The guided start's posts, published with its pages (AGL-3676). */\nexport interface AiSitePostsPublish {\n published: number\n kept: number\n /** The blog's own addresses, for the publish's cache drop. */\n paths: string[]\n}\n\n/**\n * Publishes the posts a guided start wrote, as the entry editor's Publish\n * does, once its pages are live. Never throws: a post that stays a draft is\n * the owner's to publish from Content.\n */\nexport async function aiPublishSitePosts(\n firestore: FirebaseFirestore.Firestore,\n input: { job: Pick<AiJob, '$id' | 'orgId' | 'hostId' | 'createdBy'>; outputs: readonly AiJobOutput[]; now: Date },\n publish: typeof publishContentEntries = publishContentEntries,\n): Promise<AiSitePostsPublish | null> {\n const posts = input.outputs.filter((output) => output.resource === 'entry')\n const collectionId = str(posts[0]?.proposal?.['collectionId'])\n const collectionSlug = str(posts[0]?.proposal?.['collectionSlug'])\n if (!input.job.hostId || !posts.length || !collectionId) return null\n try {\n const result = await publish(firestore, {\n hostId: input.job.hostId,\n collectionId,\n uid: input.job.createdBy,\n ids: posts.map((post) => post.id),\n now: input.now,\n })\n if ('ok' in result) {\n console.warn('ai site posts not published', { jobId: input.job.$id, error: result.error })\n return { published: 0, kept: posts.length, paths: [] }\n }\n const slugs = posts\n .filter((post) => result.published.includes(post.id))\n .map((post) => str(post.proposal?.['slug']))\n .filter(Boolean)\n return {\n published: result.published.length,\n kept: result.kept.length,\n paths: collectionSlug ? [`/${collectionSlug}`, ...slugs.map((slug) => `/${collectionSlug}/${slug}`)] : [],\n }\n } catch (error) {\n console.error('ai site posts publish threw', { orgId: input.job.orgId, jobId: input.job.$id, error })\n return null\n }\n}\n\n/**\n * The site's listings a layout or a page unit is handed (AGL-3676,\n * `ai-layout-listings.ts`): the store's catalog once its products are written,\n * the blog once its posts are, each with the sections of the plan's pages\n * that list it. A layout is built before either, so it is told the store will\n * sell (`sells`, its ledger still owing the products part), which puts the\n * cart in its header.\n */\nexport function aiSiteListings(input: {\n outputs: readonly AiJobOutput[]\n screens: readonly AiLayoutListingScreen[]\n /** The ledger owes a store's first products: a layout built before them carries the cart. */\n sells?: boolean\n /**\n * The site is a store (`siteKind: 'store'`, AGL-3676): its Shop page and\n * its home list the catalog whatever its first products came to — the\n * live Hearth & Wick start's products step failed, and its Shop page was\n * six cards naming kinds of candle. An empty catalog says so in the grid.\n */\n store?: boolean\n /**\n * The site is a music site (`siteKind: 'music'`, AGL-3716): its Music page,\n * or its home, places an empty Music player for the artist's own tracks.\n * Nothing is sourced: the owner uploads the recordings.\n */\n music?: boolean\n}): AiLayoutListing[] {\n const listings: AiLayoutListing[] = []\n const products = input.outputs.filter((output) => output.resource === 'product' && !output.proposal)\n if (products.length || input.sells || input.store) {\n const contact = aiSiteContactPath(input.screens)\n listings.push({\n id: aiLayoutListingId('products'),\n kind: 'products',\n name: 'the shop',\n records: products.map((product) => product.label),\n ...(contact ? { emptyAction: { label: 'Get in touch', href: contact } } : {}),\n // A store whose first products were skipped or failed lists its\n // (empty) catalog, but its header carries no cart until it sells.\n ...(products.length || input.sells ? {} : { cart: false }),\n placements: aiLayoutListingPlacements('products', input.screens),\n })\n // A store that sells shows its customers' reviews and takes newsletter\n // sign-ups where its pages name them (AGL-3676): both commerce elements,\n // so only where the store's commerce runs, never on a store that cannot\n // sell yet.\n if (products.length || input.sells) {\n for (const kind of ['reviews', 'signup'] as const) {\n const placements = aiLayoutListingPlacements(kind, input.screens)\n if (placements.length) listings.push({ id: aiLayoutListingId(kind), kind, name: kind === 'reviews' ? 'the store' : 'the newsletter', records: [], placements })\n }\n }\n }\n const posts = input.outputs.filter((output) => output.resource === 'entry')\n const slug = str(posts[0]?.proposal?.['collectionSlug'])\n if (posts.length && slug) {\n listings.push({\n id: aiLayoutListingId('posts'),\n kind: 'posts',\n name: 'the blog',\n records: posts.map((post) => post.label),\n href: `/${slug}`,\n collectionSlug: slug,\n placements: aiLayoutListingPlacements('posts', input.screens),\n })\n }\n if (input.music) {\n const placements = aiLayoutListingPlacements('tracks', input.screens)\n if (placements.length) {\n listings.push({ id: aiLayoutListingId('tracks'), kind: 'tracks', name: 'the music', records: [], placements })\n }\n }\n return listings\n}\n\n/** The page a visitor gets in touch on, by its path: one whose address or name says contact, else the one placing a form. */\nfunction aiSiteContactPath(screens: readonly AiLayoutListingScreen[]): string | null {\n const path = (slug: string) => `/${slug.trim().replace(/^\\/+|\\/+$/g, '')}`\n const isPath = (slug: string) => /^\\/[a-z0-9-]+(?:\\/[a-z0-9-]+)*$/.test(path(slug))\n const named = screens.find((screen) => isPath(screen.slug) && /\\b(contact|get in touch|enquir|inquir)/i.test(`${screen.slug} ${screen.title}`))\n if (named) return path(named.slug)\n const form = screens.find((screen) => isPath(screen.slug) && screen.sections.some((section) => (section.uses ?? []).some((use) => /form/i.test(use))))\n return form ? path(form.slug) : null\n}\n\n/**\n * A proposed product's description with each sentence that leaves a gap for\n * the owner (\"Delivery details: [how and when the card is sent].\") taken\n * out (AGL-3676): a start's products are listed as soon as they are written,\n * and a live run's gift card showed its gaps on the product page. A line\n * break is kept; nothing else is changed.\n */\nexport function aiSiteProductDescriptionWithoutGaps(description: string): string {\n return description\n .split('\\n')\n .map((line) =>\n line\n .split(/(?<=[.!?])\\s+/)\n .filter((sentence) => !/\\[[^\\]]+\\]/.test(sentence))\n .join(' '),\n )\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n}\n\n/** What each product a start wrote says on the job's page (AGL-3676). */\nexport const AI_SITE_PRODUCT_NOTE =\n 'On your store at a suggested price. Change its price — and add your own photo — in Products.'\n\n/** The note a store's products row carries once they are written (AGL-3676): the step left before it sells. */\nexport const AI_SITE_PRODUCTS_PRICE_NOTE =\n 'Your products are on your store at suggested prices. Review and change them in Products.'\n\n/**\n * The price a start writes a product with (Zach, 2026-10-12): the catalog's\n * suggestion as `aiCatalogPrice` keeps it, stated as the writer reads one\n * (`priceUsd`); nothing when there is none in range, so the writer gives the\n * store's default price. Never `priceUsd: null`, which would leave the\n * product unpriced on purpose.\n */\nexport function aiSiteProductPriceContent(price: unknown): { priceUsd?: number } {\n const kept = aiCatalogPrice(price)\n return kept === null ? {} : { priceUsd: kept }\n}\n\n/** What a page of a blog or a store is told about the posts or products built before it. */\nexport function aiSiteContentBriefLines(outputs: readonly AiJobOutput[]): string[] {\n const posts = outputs.filter((output) => output.resource === 'entry')\n const products = outputs.filter((output) => output.resource === 'product' && !output.proposal)\n const lines: string[] = []\n if (posts.length) {\n const slug = str(posts[0].proposal?.['collectionSlug'])\n lines.push(\n `This site's blog${slug ? ` at /${slug}` : ''} has these posts: ${posts.map((post) => `“${post.label}”`).join(', ')}.`,\n 'Where a page features writing, feature these posts by their titles; never name a post that is not in this list.',\n )\n }\n if (products.length) {\n lines.push(\n `This store's products are: ${products.map((product) => `“${product.label}”`).join(', ')}.`,\n 'Where a page features products, feature these by their names; never name another product, and never state a price.',\n // The collection tiles a storefront home shows (AGL-3676): its own range, grouped.\n 'Where a page shows the shop by collection, group these products into two to four collections by what they are (a kind, a use or an occasion), one item each, named for the group and never for one product.',\n )\n }\n return lines\n}\n"],"names":["resolveMediaSrc","hostRoleCanWrite","pluginResourceDraftWriter","publishContentEntries","writeContentCollection","writeContentEntryDraft","aiCatalogPrice","aiProductsProposalOf","aiSiteKindOfInputs","AI_SITE_BLOG_NAME","AI_SITE_BLOG_SLUGS","aiSiteWords","AI_STEP_TIERS","aiModelForStep","AI_BLOG_POST_MAX_TOKENS","AI_BLOG_POST_STEP","generateAiBlogPost","aiLayoutStarterPhotos","aiOriginJobId","aiLayoutStockPhotoSource","aiStockPhotoWordsOf","aiLayoutListingId","aiLayoutListingPlacements","aiJobAdmissionFor","aiJobStepBudget","aiGenerationSpent","aiUnspentOutcome","AI_SITE_POSTS","AI_SITE_PRODUCTS","min","max","AI_SITE_PRODUCTS_NOT_WRITTEN_COPY","AI_SITE_POSTS_LABEL","AI_SITE_PRODUCTS_LABEL","AI_SITE_CONTENT_INPUT","aiSiteContentPart","inputs","freeTaste","kind","id","AI_SITE_POST_WRITES_MS","AI_SITE_POST_BUDGET","tier","maxTokens","lookups","ownReadsMs","str","value","trim","postsInputOf","job","raw","written","Array","isArray","filter","one","total","Math","floor","avoidSlugs","map","Boolean","byline","aiSitePostId","unitJobId","index","aiSiteProductId","readSite","firestore","hostId","host","collection","doc","get","exists","seo","subdomain","name","limitReview","message","reason","findings","AI_SITE_POST_COVER_ASPECT","aiSitePostCover","input","starters","title","source","stockPhotos","uid","createdBy","seed","$id","business","about","brief","sectionNames","jobId","signal","found","imageId","frameId","iconId","alt","aspect","sectionIndex","role","src","error","console","warn","String","from","length","_","slot","createAiSitePostsRunner","deps","generate","writeCollection","writeEntry","coverFor","cover","context","model","modelFor","failure","site","avoid","Set","slug","toLowerCase","blog","displayName","slugs","has","now","ok","review","generation","merchantWords","earlierTitles","post","spent","status","refused","catch","collectionId","content","excerpt","body","seoDescription","coverImage","coverImageAlt","authorName","output","resource","hostSubdomain","label","note","proposal","collectionSlug","outputs","continue","runAiSitePostsUnit","aiSiteProductPhotos","names","slots","product","subjects","shows","words","searches","_slot","aiSiteProductPhotoSrc","path","test","startsWith","aiSiteProductChoices","options","flatMap","option","seen","values","add","aiSiteProductsBriefLine","createAiSiteProductsRunner","writerFor","catalog","keeper","outcome","target","find","entry","proposed","products","slice","photos","photo","stopped","rejected","entries","type","description","aiSiteProductDescriptionWithoutGaps","tags","seoTitle","comingSoon","aiSiteProductPriceContent","price","withPhoto","mediaUrls","photoRefused","writer","check","orgId","write","org","push","AI_SITE_PRODUCT_NOTE","last","aiSiteContentRefusal","part","admission","admissionFor","room","refusal","aiPublishSitePosts","publish","posts","result","ids","published","kept","paths","includes","aiSiteListings","listings","sells","store","contact","aiSiteContactPath","screens","records","emptyAction","href","cart","placements","music","replace","isPath","named","screen","form","sections","some","section","uses","use","split","line","sentence","join","AI_SITE_P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,CAAC,EAAEA,QAAQV,KAAK,CAAC,CAAC,CAAC,EAAEwG,IAAI,CAAC,MAAM,CAAC,CAAC,EAC3F,sHACA,mFAAmF;QACnF;IAEJ;IACA,OAAOI;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-site-content.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 { resolveMediaSrc } from '@aglyn/aglyn/app-utils/media-ref'\nimport { hostRoleCanWrite } from '@aglyn/aglyn/app-utils/organizations'\nimport { pluginResourceDraftWriter } from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport {\n publishContentEntries,\n writeContentCollection,\n writeContentEntryDraft,\n} from '@aglyn/tenant-data-admin/server/content-entry-drafts'\nimport { aiCatalogPrice, aiProductsProposalOf } from '../model/ai-products'\nimport type { AiJob, AiJobOutput } from '../model/ai-jobs.types'\nimport { aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { AI_SITE_BLOG_NAME, AI_SITE_BLOG_SLUGS, aiSiteWords } from '../model/ai-site-job'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { aiModelForStep } from '../providers/routing'\nimport {\n AI_BLOG_POST_MAX_TOKENS,\n AI_BLOG_POST_STEP,\n generateAiBlogPost,\n} from '../runtime/ai-blog-post-generation'\nimport {\n aiLayoutStarterPhotos,\n type AiLayoutPicturePhoto,\n type AiLayoutPictureSlot,\n} from '../layout-language/ai-layout-pictures'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport { aiLayoutStockPhotoSource, aiStockPhotoWordsOf } from './ai-layout-stock-photos'\nimport {\n aiLayoutListingId,\n aiLayoutListingPlacements,\n type AiLayoutListing,\n type AiLayoutListingScreen,\n} from '../layout-language/ai-layout-listings'\nimport { aiJobAdmissionFor, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiGenerationSpent, aiUnspentOutcome } from './ai-job-generation'\nimport type { AiJobStepContext, AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\n\n/**\n * A GUIDED START'S FIRST POSTS AND FIRST PRODUCTS (AGL-3676).\n *\n * A site of the kind \"Blog & writing\" or \"Online store\" got the right look\n * and pages, and nothing real in them: the writing page's cards and the\n * shop's grid named posts and products nobody had written. On a paid plan,\n * the scaffold now builds one more part for those two kinds, before the\n * pages, each its own row with its own timer and credits:\n *\n * - WRITING YOUR FIRST POSTS: a content collection \"Blog\" — the platform's\n * own blog, served at `/{slug}` with an entry page per post — and\n * `AI_SITE_POSTS` posts in it, one generation a pass. Each is written as a\n * draft through the same rules the console's routes hold\n * (`content-entry-drafts.ts`), bylined with the business's name the person\n * gave, and given a cover: a stock photo of its own title where the\n * deployment has a library, else a starter (AGL-3676), which the blog's\n * cards show. They go live with the\n * site: the guided start's publish publishes them with its pages\n * (`aiPublishSitePosts`), as a person's Publish would.\n * - ADDING YOUR FIRST PRODUCTS: the `products` step's catalog, asked for\n * `AI_SITE_PRODUCTS` products, each written through the commerce plugin's\n * `product` draft writer, at the price the catalog suggests for what it\n * is (Zach, 2026-10-12: a bar of soap is not priced like a gift set),\n * which code keeps in range (`aiCatalogPrice`); a product with no price\n * in range takes the writer's default price (his 2026-10-08 \"default a\n * price\", AGL-3676). Every price is the owner's to change, and the job's\n * row says so. Since the\n * 2026-10-08 Ember & Wick start, whose store showed no product at all,\n * each is LISTED at once (`comingSoon`: written `active`). Each gets a\n * photo in its slot, a stock photo of its own words where the deployment\n * has a library, else a starter, for the owner to replace with their\n * own.\n *\n * The pages built after them are told their titles or names, and the\n * sections that show them list the real records (`aiSiteListings`,\n * `ai-layout-listings.ts`): the shop's Product grid, the blog's posts.\n *\n * ── Not on the Free taste ────────────────────────────────────────────────\n *\n * A guided start's Free site writes no first posts and no products. Built on\n * an empty site with its layout and form, it leaves 57 credits once its eight\n * sections and its retried page's room are held (`aiFreeSiteSectionsWithin`,\n * AGL-3660), which since AGL-3781 would hold the 4 one post costs at its worst\n * on the fast tier; but a Free site has no content part of its own, and a Free\n * plan includes neither the `commerce` feature nor a product\n * (`productsPerHost` is 0).\n * `ai-job-free-site.spec.ts` shows the arithmetic. Free sites keep the pages\n * their kind already describes; the owner adds posts and products after.\n */\n\n/** How many first posts a paid blog gets. */\nexport const AI_SITE_POSTS = 3\n\n/** How many first products a paid store gets: asked for, and the most written. */\nexport const AI_SITE_PRODUCTS = { min: 3, max: 6 } as const\n\n/** What a products row says when none of what we made could be written: our failure, refunded. */\nexport const AI_SITE_PRODUCTS_NOT_WRITTEN_COPY = 'Your first products could not be added this time.'\n\n/** What each part's row reads. */\nexport const AI_SITE_POSTS_LABEL = 'Writing your first posts'\nexport const AI_SITE_PRODUCTS_LABEL = 'Adding your first products'\n\n/** The blog the posts go in, and the addresses it may answer at (`model/ai-site-job.ts`). */\nexport { AI_SITE_BLOG_NAME, AI_SITE_BLOG_SLUGS } from '../model/ai-site-job'\n\n/** The input a site unit's own job carries what the part needs in. */\nexport const AI_SITE_CONTENT_INPUT = 'siteContent'\n\n/** Which part a site of these answers gets; `null` for the Free taste and every other kind. */\nexport function aiSiteContentPart(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n freeTaste: boolean,\n): 'posts' | 'products' | null {\n if (freeTaste) return null\n const kind = aiSiteKindOfInputs(inputs)?.id\n if (kind === 'blog') return 'posts'\n if (kind === 'store') return 'products'\n return null\n}\n\n/**\n * ASSUMED: what one post pass reads and writes beside its generation: the\n * host, the collection's slug claim and the entry's transaction.\n */\nexport const AI_SITE_POST_WRITES_MS = 1_500\n\n/** One post's pass: its generation and re-ask at the `copy.blog` ceiling, and its writes. */\nexport const AI_SITE_POST_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS[AI_BLOG_POST_STEP],\n maxTokens: AI_BLOG_POST_MAX_TOKENS,\n lookups: 0,\n ownReadsMs: AI_SITE_POST_WRITES_MS,\n})\n\n/** What a posts unit's job is told: the posts already written and the addresses the blog must not take. */\nexport interface AiSitePostsInput {\n written: Array<{ id: string; title: string }>\n total: number\n /** Addresses the site's own pages answer at, which the blog must not shadow. */\n avoidSlugs: string[]\n /** Who the posts are by: the business's name as given, else empty. */\n byline: string\n}\n\n/** What a products unit's job is told. */\nexport interface AiSiteProductsInput {\n min: number\n max: number\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\nfunction postsInputOf(job: Pick<AiJob, 'inputs'>): AiSitePostsInput {\n const raw = (job.inputs?.[AI_SITE_CONTENT_INPUT] ?? {}) as Partial<AiSitePostsInput>\n return {\n written: Array.isArray(raw.written) ? raw.written.filter((one) => one && typeof one.id === 'string') : [],\n total: typeof raw.total === 'number' && raw.total > 0 ? Math.floor(raw.total) : AI_SITE_POSTS,\n avoidSlugs: Array.isArray(raw.avoidSlugs) ? raw.avoidSlugs.map(str).filter(Boolean) : [],\n byline: str(raw.byline),\n }\n}\n\n/** The id of the `index`th post, of the blog its unit writes under `unitJobId`. */\nexport function aiSitePostId(unitJobId: string, index: number): string {\n return `${unitJobId}-${index}`\n}\n\n/** The id of the `index`th product a products unit writes. */\nexport function aiSiteProductId(unitJobId: string, index: number): string {\n return `${unitJobId}-${index}`\n}\n\n/** A site's subdomain and name, as its outputs and its posts' byline read them. */\nasync function readSite(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<{ subdomain: string | null; name: string } | null> {\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return null\n const seo = (host.get('seo') ?? {}) as Record<string, unknown>\n const subdomain = str(host.get('subdomain')) || null\n return { subdomain, name: str(host.get('displayName')) || str(seo['title']) }\n}\n\nconst limitReview = (message: string) => ({ reason: 'limit' as const, message, findings: [] })\n\nexport interface AiSitePostsRunnerDeps {\n generate?: typeof generateAiBlogPost\n writeCollection?: typeof writeContentCollection\n writeEntry?: typeof writeContentEntryDraft\n /** Where each post's cover comes from; the stock library, else the starters, otherwise. */\n cover?: typeof aiSitePostCover\n}\n\n/** A post's cover's shape: the blog's cards' (`COLLECTION_LIST_COVER_RATIO`, the posts listing's). */\nconst AI_SITE_POST_COVER_ASPECT = 3 / 2\n\n/**\n * A post's cover (AGL-3676): a stock photo of the post's own title, copied\n * into the site's library, where the deployment has a stock library; else the\n * starter photo a post was always given, turned by the job so blogs differ.\n * The blog's cards and the post's page show it, for the owner to replace.\n * Never throws: a post whose search fails takes its starter.\n */\nexport async function aiSitePostCover(input: {\n job: Pick<AiJob, '$id' | 'hostId' | 'createdBy' | 'inputs' | 'brief' | 'plan'>\n title: string\n index: number\n total: number\n signal?: AbortSignal\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}): Promise<string | null> {\n const { job, index } = input\n if (job.hostId && input.title.trim()) {\n try {\n const source = (input.stockPhotos ?? aiLayoutStockPhotoSource)({\n hostId: job.hostId,\n uid: job.createdBy,\n seed: `${job.$id}:posts:${index}`,\n business: aiSiteWords(job.inputs).about || job.brief,\n ...aiStockPhotoWordsOf(job),\n sectionNames: ['Blog'],\n jobId: aiOriginJobId(job),\n ...(input.signal ? { signal: input.signal } : {}),\n })\n const [found] = source\n ? await source([\n {\n imageId: `cover${index}`,\n frameId: null,\n iconId: null,\n alt: input.title,\n aspect: AI_SITE_POST_COVER_ASPECT,\n sectionIndex: 0,\n role: 'gallery' as const,\n },\n ])\n : []\n if (found?.src) return found.src\n } catch (error) {\n console.warn('ai site posts: the stock photo failed; the starter covers it', { error: String(error) })\n }\n }\n const starters = aiLayoutStarterPhotos(\n Array.from({ length: Math.max(input.total, index + 1) }, (_, slot) => ({\n imageId: `cover${slot}`,\n frameId: null,\n iconId: null,\n alt: '',\n aspect: 16 / 9,\n sectionIndex: slot + 1,\n role: 'gallery' as const,\n })),\n job.$id,\n )\n return starters[index]?.src ?? null\n}\n\n/**\n * The posts unit's runner, on the job the scaffold derived for it: one post a\n * pass, continuing while posts remain. Its first pass makes the blog; every\n * pass finds it again under the unit's own id, and a post under its own id,\n * so a pass repeated after its write reports the post it already wrote.\n */\nexport function createAiSitePostsRunner(deps: AiSitePostsRunnerDeps = {}): AiJobStepRunner {\n const generate = deps.generate ?? generateAiBlogPost\n const writeCollection = deps.writeCollection ?? writeContentCollection\n const writeEntry = deps.writeEntry ?? writeContentEntryDraft\n const coverFor = deps.cover ?? aiSitePostCover\n return async (context): Promise<AiJobStepOutcome> => {\n const { job, firestore, signal } = context\n const model = context.modelFor?.(AI_BLOG_POST_STEP) ?? aiModelForStep(AI_BLOG_POST_STEP)\n if (!job.hostId) return { ...aiUnspentOutcome(model), failure: 'Open the site before writing its posts.' }\n const input = postsInputOf(job)\n const index = input.written.length\n if (index >= input.total) return aiUnspentOutcome(model)\n const site = await readSite(firestore, job.hostId)\n if (!site) return { ...aiUnspentOutcome(model), failure: 'This site no longer exists.' }\n const avoid = new Set(input.avoidSlugs.map((slug) => slug.toLowerCase()))\n const blog = await writeCollection(firestore, {\n hostId: job.hostId,\n uid: job.createdBy,\n id: job.$id,\n displayName: AI_SITE_BLOG_NAME,\n slugs: AI_SITE_BLOG_SLUGS.filter((slug) => !avoid.has(slug)),\n now: context.now,\n })\n if (blog.ok === false) return aiUnspentOutcome(model, { review: limitReview(blog.error) })\n\n const generation = await generate({\n brief: job.brief,\n merchantWords: job.brief,\n earlierTitles: input.written.map((post) => post.title),\n index: index + 1,\n total: input.total,\n model,\n maxTokens: AI_SITE_POST_BUDGET.maxTokens(model),\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(generation)\n if (generation.status === 'refused') return { ...spent, refused: true }\n if (generation.status === 'needs_input') return { ...spent, failure: generation.message }\n const post = generation.value\n // A stock photo of its title as its cover, else a starter (AGL-3676).\n const cover = await coverFor({\n job,\n title: post.title,\n index,\n total: input.total,\n ...(signal ? { signal } : {}),\n }).catch(() => null)\n const byline = input.byline || site.name\n const written = await writeEntry(firestore, {\n hostId: job.hostId,\n collectionId: blog.id,\n uid: job.createdBy,\n id: aiSitePostId(job.$id, index),\n content: {\n title: post.title,\n excerpt: post.excerpt,\n body: post.body,\n seoDescription: post.seoDescription,\n ...(cover ? { coverImage: cover, coverImageAlt: post.title } : {}),\n ...(byline ? { authorName: byline } : {}),\n },\n now: context.now,\n })\n if (written.ok === false) return { ...spent, review: limitReview(written.error) }\n const output: AiJobOutput = {\n resource: 'entry',\n id: written.id,\n hostId: job.hostId,\n hostSubdomain: site.subdomain,\n label: written.title,\n note: `A post in ${blog.displayName}, at /${blog.slug}/${written.slug}. It goes live with the site.`,\n proposal: { collectionId: blog.id, collectionSlug: blog.slug, slug: written.slug },\n }\n return { ...spent, outputs: [output], ...(index + 1 < input.total ? { continue: true } : {}) }\n }\n}\n\nexport const runAiSitePostsUnit = createAiSitePostsRunner()\n\nexport interface AiSiteProductsRunnerDeps {\n /** The catalog's runner: the `products` step's. */\n catalog: AiJobStepRunner\n writerFor?: typeof pluginResourceDraftWriter\n /** Where each product's photo comes from; the stock library, else the starters, otherwise. */\n photos?: typeof aiSiteProductPhotos\n}\n\n/**\n * A photo for each product (AGL-3676), in order: a stock photo of the\n * product's own words, copied into the site's library, where the deployment\n * has a stock library; else a starter photo, as a page's empty picture takes\n * one. It fills the photo slot every product card and product page has, for\n * the owner to replace with their own; the product's note says so. Never\n * throws: a product with no photo is still written.\n */\nexport async function aiSiteProductPhotos(input: {\n job: Pick<AiJob, '$id' | 'hostId' | 'createdBy' | 'inputs' | 'brief' | 'plan'>\n names: readonly string[]\n /** What each product's photo should show, as its catalog proposed it, by position (AGL-3676). */\n shows?: readonly string[]\n signal?: AbortSignal\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}): Promise<Array<string | null>> {\n if (!input.names.length || !input.job.hostId) return input.names.map(() => null)\n const slots: AiLayoutPictureSlot[] = input.names.map((name, index) => ({\n imageId: `product${index}`,\n frameId: null,\n iconId: null,\n alt: name,\n // The product card's own shape (`cardStyle: 'photo'`).\n aspect: 4 / 5,\n sectionIndex: 0,\n role: 'gallery' as const,\n // Searched for by its own name, then what its photo shows, with the shop's\n // category, and held to that category (AGL-3676).\n product: { subjects: [name, input.shows?.[index] ?? ''].filter((words) => words.trim()) },\n }))\n const seed = `${input.job.$id}:products`\n let found: ReadonlyArray<AiLayoutPicturePhoto | null> = []\n try {\n const source = (input.stockPhotos ?? aiLayoutStockPhotoSource)({\n hostId: input.job.hostId,\n uid: input.job.createdBy,\n seed,\n business: aiSiteWords(input.job.inputs).about || input.job.brief,\n ...aiStockPhotoWordsOf(input.job),\n sectionNames: ['Products'],\n jobId: aiOriginJobId(input.job),\n // Each product may try its name, its photo's subject, its category, a\n // gift's wrapper and the craft's broad searches (AGL-3660).\n searches: slots.length * 6,\n ...(input.signal ? { signal: input.signal } : {}),\n })\n if (source) found = await source(slots)\n } catch (error) {\n console.warn('ai site products: the stock photos failed; starter photos fill them', { error: String(error) })\n }\n const starters = aiLayoutStarterPhotos(slots, seed)\n const hostId = input.job.hostId\n // Every product has a photo (AGL-3676): a starter where no stock photo\n // named its category, never an empty tile.\n return slots.map(\n (_slot, index) =>\n aiSiteProductPhotoSrc(found[index]?.src, hostId) ?? aiSiteProductPhotoSrc(starters[index]?.src, hostId),\n )\n}\n\n/**\n * A photo as a product stores it: the form the console's picker writes when\n * an owner picks one from the library (`console-media-picker-provider`), the\n * asset's CDN path `/api/media/cdn/{scope}/{mediaId}`, or a starter's own\n * site path. A page's picture slot holds the library's `media:` reference\n * (`mediaNodeSrc`), which is what the stock source hands back, and the\n * product's rules take only an https address or a path on the site: the\n * candle store's guided start of 2026-10-09 (job FYNasg1h0S) wrote no\n * product at all because every photo was a `media:` reference. The path\n * names the asset, not its bytes, so a replace in the library still reaches\n * the product. Anything else is no photo, never a value the product refuses.\n */\nexport function aiSiteProductPhotoSrc(src: string | null | undefined, hostId: string): string | null {\n if (!src) return null\n const path = resolveMediaSrc(src, { hostId })\n if (!path || path.length > 2_000 || /[\\s\"'<>]/.test(path)) return null\n return path.startsWith('/') || path.startsWith('https://') ? path : null\n}\n\n/**\n * A proposed product's real choices (AGL-3676): each option with two or more\n * distinct values. An option of one value is no choice for a shopper to make\n * — the beta.237 Willow Wick gift set's \"Scent\" select offered nothing — so\n * it is left out, and its one value stays in the product's own words.\n */\nexport function aiSiteProductChoices(\n options: ReadonlyArray<{ name: string; values: readonly string[] }> | null | undefined,\n): Array<{ name: string; values: string[] }> {\n return (options ?? []).flatMap((option) => {\n const seen = new Set<string>()\n const values = option.values\n .map((value) => value.trim())\n .filter((value) => value && !seen.has(value.toLowerCase()) && !!seen.add(value.toLowerCase()))\n return option.name.trim() && values.length >= 2 ? [{ name: option.name.trim(), values }] : []\n })\n}\n\n/** The sentence the products unit's brief ends with, which the catalog's rules read as how many. */\nexport function aiSiteProductsBriefLine(input: AiSiteProductsInput = AI_SITE_PRODUCTS): string {\n return `Propose between ${input.min} and ${input.max} products: the store's first ones.`\n}\n\n/**\n * The products unit's runner: the `products` step's catalog for the store's\n * brief, then each proposed product, up to the most a site starts with,\n * written by the plugin that keeps products at its suggested price (else the\n * store's default), listed. A\n * product past the plan's allowance stops the writing there, and the row\n * says how many were added; none at all is the allowance's review. A photo\n * the product's rules refuse is dropped and the product written without it;\n * a product they refuse outright is skipped, and none written for that\n * reason is our failure, refunded, never the person's review (AGL-3676).\n */\nexport function createAiSiteProductsRunner(deps: AiSiteProductsRunnerDeps): AiJobStepRunner {\n const writerFor = deps.writerFor ?? pluginResourceDraftWriter\n return async (context): Promise<AiJobStepOutcome> => {\n const { job } = context\n const keeper = writerFor('product')\n const model = context.modelFor?.('job.products') ?? aiModelForStep('job.products')\n if (!keeper || !job.hostId) return { ...aiUnspentOutcome(model), failure: 'Products are not available on this site.' }\n const outcome = await deps.catalog({\n ...context,\n job: { ...job, kind: 'products', inputs: { ...job.inputs, target: 'catalog' } },\n })\n if (outcome.refused || outcome.failure || outcome.review) return outcome\n const catalog = outcome.outputs.map((output) => ({ output, proposal: aiProductsProposalOf(output) })).find(\n (entry) => entry.proposal?.kind === 'catalog',\n )\n if (!catalog || catalog.proposal?.kind !== 'catalog') return { ...outcome, outputs: [] }\n const proposed = catalog.proposal.products.slice(0, AI_SITE_PRODUCTS.max)\n const photos = await (deps.photos ?? aiSiteProductPhotos)({\n job,\n names: proposed.map((product) => product.name),\n shows: proposed.map((product) => product.photo ?? ''),\n ...(context.signal ? { signal: context.signal } : {}),\n }).catch(() => proposed.map(() => null))\n const outputs: AiJobOutput[] = []\n let stopped: string | null = null\n /** The product's rules refusing what we made: ours, never the workspace's (AGL-3676). */\n let rejected: string | null = null\n for (const [index, product] of proposed.entries()) {\n const content: Record<string, unknown> = {\n name: product.name,\n type: product.type,\n // Listed at once, so no \"[gift card terms]\" gap reaches a shopper:\n // a sentence that leaves a fact for the owner is left out.\n description: aiSiteProductDescriptionWithoutGaps(product.description),\n tags: product.tags,\n // A choice is two values or more (AGL-3676): a \"Scent\" of one value\n // drew a select with nothing to pick on the live Willow Wick page.\n options: aiSiteProductChoices(product.options),\n seoTitle: product.seoTitle,\n seoDescription: product.seoDescription,\n comingSoon: true,\n // The catalog's suggested price for what the product is (Zach,\n // 2026-10-12), held to range once more here: none, or one out of\n // range, is left unstated and the writer gives the store's default.\n ...aiSiteProductPriceContent(product.price),\n }\n // A photo we picked that the product's rules refuse is dropped, never\n // the product: its slot stays empty for the owner's own.\n const photo = photos[index] ?? null\n const withPhoto = photo ? { ...content, mediaUrls: [photo] } : content\n const photoRefused =\n photo !== null &&\n keeper.writer.check(withPhoto, { hostId: job.hostId }).ok === false &&\n keeper.writer.check(content, { hostId: job.hostId }).ok\n if (photoRefused) {\n console.warn('ai site products: the product refused its photo; written without it', {\n orgId: job.orgId,\n jobId: job.$id,\n photo,\n })\n }\n const written = await keeper.writer.write({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n id: aiSiteProductId(job.$id, index),\n name: product.name,\n // Its suggested price, else the store's default, for the owner to\n // change (AGL-3676). Listed at once. Its photo slot holds a stock or\n // starter photo for the owner to replace.\n content: photoRefused ? content : withPhoto,\n })\n if (written.ok === false) {\n // A 400 is the product's rules refusing content we made: that one\n // product is skipped and the rest are still written. Anything else\n // (the allowance, the role, the site) stops the writing there.\n if (written.status === 400) {\n console.error('ai site products: the product writer refused a product we made', {\n orgId: job.orgId,\n jobId: job.$id,\n index,\n error: written.error,\n })\n rejected = written.error\n continue\n }\n stopped = written.error\n break\n }\n outputs.push({\n resource: 'product',\n id: written.id,\n hostId: job.hostId,\n hostSubdomain: catalog.output.hostSubdomain ?? null,\n label: written.name,\n note: AI_SITE_PRODUCT_NOTE,\n })\n }\n if (!outputs.length) {\n // Nothing written because the product's rules refused what we made:\n // the failure is ours, so the item's credits are refunded\n // (`aiUnitFailure` → `ours: true`). Only the workspace's allowance,\n // role or site is the person's to review.\n if (!stopped && rejected) return { ...outcome, outputs: [], failure: AI_SITE_PRODUCTS_NOT_WRITTEN_COPY }\n return { ...outcome, outputs: [], review: limitReview(stopped ?? 'No product could be added.') }\n }\n // The allowance that stopped the rest is said where the last one added is.\n const last = outputs[outputs.length - 1]\n if (stopped) {\n last.note = `${last.note} ${outputs.length} of ${proposed.length} added: ${stopped}.`\n } else if (outputs.length < proposed.length) {\n last.note = `${last.note} ${outputs.length} of ${proposed.length} added.`\n }\n return { ...outcome, outputs }\n }\n}\n\n/**\n * Whether a part may be built for this member on this site, asked before its\n * first pass so a refusal spends nothing; `null` admits. Products ask what a\n * `products` job asks (the plan's commerce feature, Commerce on and released\n * for the site) and the writer's own refusal (role, allowance); posts ask\n * that the member may write the site's content.\n */\nexport async function aiSiteContentRefusal(\n part: 'posts' | 'products',\n context: Pick<AiJobStepContext, 'firestore' | 'org' | 'now'> & { job: Pick<AiJob, 'orgId' | 'hostId' | 'createdBy' | 'inputs'> },\n deps: { writerFor?: typeof pluginResourceDraftWriter; admissionFor?: typeof aiJobAdmissionFor } = {},\n): Promise<string | null> {\n const { job, firestore } = context\n if (!job.hostId) return 'Open the site first.'\n if (part === 'posts') {\n const host = await firestore.collection('hosts').doc(job.hostId).get()\n return hostRoleCanWrite((host.get('memberRoles') ?? {})[job.createdBy]) ? null : 'Editing requires the editor role'\n }\n const admission = (deps.admissionFor ?? aiJobAdmissionFor)('products')\n const refused: AiJobAdmissionRefusal | null = admission\n ? await admission({\n firestore,\n orgId: job.orgId,\n hostId: job.hostId,\n inputs: { target: 'catalog' },\n org: context.org ?? null,\n uid: job.createdBy,\n })\n : { status: 403, error: 'Products are not available on this site.' }\n if (refused) return refused.error\n const keeper = (deps.writerFor ?? pluginResourceDraftWriter)('product')\n if (!keeper) return 'Products are not available on this site.'\n const room = await keeper.writer.refusal({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n })\n return room?.error ?? null\n}\n\n/** The guided start's posts, published with its pages (AGL-3676). */\nexport interface AiSitePostsPublish {\n published: number\n kept: number\n /** The blog's own addresses, for the publish's cache drop. */\n paths: string[]\n}\n\n/**\n * Publishes the posts a guided start wrote, as the entry editor's Publish\n * does, once its pages are live. Never throws: a post that stays a draft is\n * the owner's to publish from Content.\n */\nexport async function aiPublishSitePosts(\n firestore: FirebaseFirestore.Firestore,\n input: { job: Pick<AiJob, '$id' | 'orgId' | 'hostId' | 'createdBy'>; outputs: readonly AiJobOutput[]; now: Date },\n publish: typeof publishContentEntries = publishContentEntries,\n): Promise<AiSitePostsPublish | null> {\n const posts = input.outputs.filter((output) => output.resource === 'entry')\n const collectionId = str(posts[0]?.proposal?.['collectionId'])\n const collectionSlug = str(posts[0]?.proposal?.['collectionSlug'])\n if (!input.job.hostId || !posts.length || !collectionId) return null\n try {\n const result = await publish(firestore, {\n hostId: input.job.hostId,\n collectionId,\n uid: input.job.createdBy,\n ids: posts.map((post) => post.id),\n now: input.now,\n })\n if ('ok' in result) {\n console.warn('ai site posts not published', { jobId: input.job.$id, error: result.error })\n return { published: 0, kept: posts.length, paths: [] }\n }\n const slugs = posts\n .filter((post) => result.published.includes(post.id))\n .map((post) => str(post.proposal?.['slug']))\n .filter(Boolean)\n return {\n published: result.published.length,\n kept: result.kept.length,\n paths: collectionSlug ? [`/${collectionSlug}`, ...slugs.map((slug) => `/${collectionSlug}/${slug}`)] : [],\n }\n } catch (error) {\n console.error('ai site posts publish threw', { orgId: input.job.orgId, jobId: input.job.$id, error })\n return null\n }\n}\n\n/**\n * The site's listings a layout or a page unit is handed (AGL-3676,\n * `ai-layout-listings.ts`): the store's catalog once its products are written,\n * the blog once its posts are, each with the sections of the plan's pages\n * that list it. A layout is built before either, so it is told the store will\n * sell (`sells`, its ledger still owing the products part), which puts the\n * cart in its header.\n */\nexport function aiSiteListings(input: {\n outputs: readonly AiJobOutput[]\n screens: readonly AiLayoutListingScreen[]\n /** The ledger owes a store's first products: a layout built before them carries the cart. */\n sells?: boolean\n /**\n * The site is a store (`siteKind: 'store'`, AGL-3676): its Shop page and\n * its home list the catalog whatever its first products came to — the\n * live Hearth & Wick start's products step failed, and its Shop page was\n * six cards naming kinds of candle. An empty catalog says so in the grid.\n */\n store?: boolean\n /**\n * The site is a music site (`siteKind: 'music'`, AGL-3716): its Music page,\n * or its home, places an empty Music player for the artist's own tracks.\n * Nothing is sourced: the owner uploads the recordings.\n */\n music?: boolean\n}): AiLayoutListing[] {\n const listings: AiLayoutListing[] = []\n const products = input.outputs.filter((output) => output.resource === 'product' && !output.proposal)\n if (products.length || input.sells || input.store) {\n const contact = aiSiteContactPath(input.screens)\n listings.push({\n id: aiLayoutListingId('products'),\n kind: 'products',\n name: 'the shop',\n records: products.map((product) => product.label),\n ...(contact ? { emptyAction: { label: 'Get in touch', href: contact } } : {}),\n // A store whose first products were skipped or failed lists its\n // (empty) catalog, but its header carries no cart until it sells.\n ...(products.length || input.sells ? {} : { cart: false }),\n placements: aiLayoutListingPlacements('products', input.screens),\n })\n // A store that sells shows its customers' reviews and takes newsletter\n // sign-ups where its pages name them (AGL-3676): both commerce elements,\n // so only where the store's commerce runs, never on a store that cannot\n // sell yet.\n if (products.length || input.sells) {\n for (const kind of ['reviews', 'signup'] as const) {\n const placements = aiLayoutListingPlacements(kind, input.screens)\n if (placements.length) listings.push({ id: aiLayoutListingId(kind), kind, name: kind === 'reviews' ? 'the store' : 'the newsletter', records: [], placements })\n }\n }\n }\n const posts = input.outputs.filter((output) => output.resource === 'entry')\n const slug = str(posts[0]?.proposal?.['collectionSlug'])\n if (posts.length && slug) {\n listings.push({\n id: aiLayoutListingId('posts'),\n kind: 'posts',\n name: 'the blog',\n records: posts.map((post) => post.label),\n href: `/${slug}`,\n collectionSlug: slug,\n placements: aiLayoutListingPlacements('posts', input.screens),\n })\n }\n if (input.music) {\n const placements = aiLayoutListingPlacements('tracks', input.screens)\n if (placements.length) {\n listings.push({ id: aiLayoutListingId('tracks'), kind: 'tracks', name: 'the music', records: [], placements })\n }\n }\n return listings\n}\n\n/** The page a visitor gets in touch on, by its path: one whose address or name says contact, else the one placing a form. */\nfunction aiSiteContactPath(screens: readonly AiLayoutListingScreen[]): string | null {\n const path = (slug: string) => `/${slug.trim().replace(/^\\/+|\\/+$/g, '')}`\n const isPath = (slug: string) => /^\\/[a-z0-9-]+(?:\\/[a-z0-9-]+)*$/.test(path(slug))\n const named = screens.find((screen) => isPath(screen.slug) && /\\b(contact|get in touch|enquir|inquir)/i.test(`${screen.slug} ${screen.title}`))\n if (named) return path(named.slug)\n const form = screens.find((screen) => isPath(screen.slug) && screen.sections.some((section) => (section.uses ?? []).some((use) => /form/i.test(use))))\n return form ? path(form.slug) : null\n}\n\n/**\n * A proposed product's description with each sentence that leaves a gap for\n * the owner (\"Delivery details: [how and when the card is sent].\") taken\n * out (AGL-3676): a start's products are listed as soon as they are written,\n * and a live run's gift card showed its gaps on the product page. A line\n * break is kept; nothing else is changed.\n */\nexport function aiSiteProductDescriptionWithoutGaps(description: string): string {\n return description\n .split('\\n')\n .map((line) =>\n line\n .split(/(?<=[.!?])\\s+/)\n .filter((sentence) => !/\\[[^\\]]+\\]/.test(sentence))\n .join(' '),\n )\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n}\n\n/** What each product a start wrote says on the job's page (AGL-3676). */\nexport const AI_SITE_PRODUCT_NOTE =\n 'On your store at a suggested price. Change its price — and add your own photo — in Products.'\n\n/** The note a store's products row carries once they are written (AGL-3676): the step left before it sells. */\nexport const AI_SITE_PRODUCTS_PRICE_NOTE =\n 'Your products are on your store at suggested prices. Review and change them in Products.'\n\n/**\n * The price a start writes a product with (Zach, 2026-10-12): the catalog's\n * suggestion as `aiCatalogPrice` keeps it, stated as the writer reads one\n * (`priceUsd`); nothing when there is none in range, so the writer gives the\n * store's default price. Never `priceUsd: null`, which would leave the\n * product unpriced on purpose.\n */\nexport function aiSiteProductPriceContent(price: unknown): { priceUsd?: number } {\n const kept = aiCatalogPrice(price)\n return kept === null ? {} : { priceUsd: kept }\n}\n\n/** What a page of a blog or a store is told about the posts or products built before it. */\nexport function aiSiteContentBriefLines(outputs: readonly AiJobOutput[]): string[] {\n const posts = outputs.filter((output) => output.resource === 'entry')\n const products = outputs.filter((output) => output.resource === 'product' && !output.proposal)\n const lines: string[] = []\n if (posts.length) {\n const slug = str(posts[0].proposal?.['collectionSlug'])\n lines.push(\n `This site's blog${slug ? ` at /${slug}` : ''} has these posts: ${posts.map((post) => `“${post.label}”`).join(', ')}.`,\n 'Where a page features writing, feature these posts by their titles; never name a post that is not in this list.',\n )\n }\n if (products.length) {\n lines.push(\n `This store's products are: ${products.map((product) => `“${product.label}”`).join(', ')}.`,\n 'Where a page features products, feature these by their names; never name another product, and never state a price.',\n // The collection tiles a storefront home shows (AGL-3676): its own range, grouped.\n 'Where a page shows the shop by collection, group these products into two to four collections by what they are (a kind, a use or an occasion), one item each, named for the group and never for one product.',\n )\n }\n return lines\n}\n"],"names":["resolveMediaSrc","hostRoleCanWrite","pluginResourceDraftWriter","publishContentEntries","writeContentCollection","writeContentEntryDraft","aiCatalogPrice","aiProductsProposalOf","aiSiteKindOfInputs","AI_SITE_BLOG_NAME","AI_SITE_BLOG_SLUGS","aiSiteWords","AI_STEP_TIERS","aiModelForStep","AI_BLOG_POST_MAX_TOKENS","AI_BLOG_POST_STEP","generateAiBlogPost","aiLayoutStarterPhotos","aiOriginJobId","aiLayoutStockPhotoSource","aiStockPhotoWordsOf","aiLayoutListingId","aiLayoutListingPlacements","aiJobAdmissionFor","aiJobStepBudget","aiGenerationSpent","aiUnspentOutcome","AI_SITE_POSTS","AI_SITE_PRODUCTS","min","max","AI_SITE_PRODUCTS_NOT_WRITTEN_COPY","AI_SITE_POSTS_LABEL","AI_SITE_PRODUCTS_LABEL","AI_SITE_CONTENT_INPUT","aiSiteContentPart","inputs","freeTaste","kind","id","AI_SITE_POST_WRITES_MS","AI_SITE_POST_BUDGET","tier","maxTokens","lookups","ownReadsMs","str","value","trim","postsInputOf","job","raw","written","Array","isArray","filter","one","total","Math","floor","avoidSlugs","map","Boolean","byline","aiSitePostId","unitJobId","index","aiSiteProductId","readSite","firestore","hostId","host","collection","doc","get","exists","seo","subdomain","name","limitReview","message","reason","findings","AI_SITE_POST_COVER_ASPECT","aiSitePostCover","input","starters","title","source","stockPhotos","uid","createdBy","seed","$id","business","about","brief","sectionNames","jobId","signal","found","imageId","frameId","iconId","alt","aspect","sectionIndex","role","src","error","console","warn","String","from","length","_","slot","createAiSitePostsRunner","deps","generate","writeCollection","writeEntry","coverFor","cover","context","model","modelFor","failure","site","avoid","Set","slug","toLowerCase","blog","displayName","slugs","has","now","ok","review","generation","merchantWords","earlierTitles","post","spent","status","refused","catch","collectionId","content","excerpt","body","seoDescription","coverImage","coverImageAlt","authorName","output","resource","hostSubdomain","label","note","proposal","collectionSlug","outputs","continue","runAiSitePostsUnit","aiSiteProductPhotos","names","slots","product","subjects","shows","words","searches","_slot","aiSiteProductPhotoSrc","path","test","startsWith","aiSiteProductChoices","options","flatMap","option","seen","values","add","aiSiteProductsBriefLine","createAiSiteProductsRunner","writerFor","catalog","keeper","outcome","target","find","entry","proposed","products","slice","photos","photo","stopped","rejected","entries","type","description","aiSiteProductDescriptionWithoutGaps","tags","seoTitle","comingSoon","aiSiteProductPriceContent","price","withPhoto","mediaUrls","photoRefused","writer","check","orgId","write","org","push","AI_SITE_PRODUCT_NOTE","last","aiSiteContentRefusal","part","admission","admissionFor","room","refusal","aiPublishSitePosts","publish","posts","result","ids","published","kept","paths","includes","aiSiteListings","listings","sells","store","contact","aiSiteContactPath","screens","records","emptyAction","href","cart","placements","music","replace","isPath","named","screen","form","sections","some","section","uses","use","split","line","sentence","join","AI_SITE_PRODUCTS_PRICE_NOTE","priceUsd","aiSiteContentBriefLines","lines"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,eAAe,QAAQ,mCAAkC;AAClE,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,yBAAyB,QAAQ,qDAAoD;AAC9F,SACEC,qBAAqB,EACrBC,sBAAsB,EACtBC,sBAAsB,QACjB,uDAAsD;AAC7D,SAASC,cAAc,EAAEC,oBAAoB,QAAQ,0BAAsB;AAE3E,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,iBAAiB,EAAEC,kBAAkB,EAAEC,WAAW,QAAQ,0BAAsB;AACzF,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SACEC,uBAAuB,EACvBC,iBAAiB,EACjBC,kBAAkB,QACb,wCAAoC;AAC3C,SACEC,qBAAqB,QAGhB,2CAAuC;AAC9C,SAASC,aAAa,QAAQ,wBAAoB;AAClD,SAASC,wBAAwB,EAAEC,mBAAmB,QAAQ,8BAA0B;AACxF,S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OAAOK,QAAQ;IAC7F,MAAM0G,QAAkB,EAAE;IAC1B,IAAIrC,MAAMpH,MAAM,EAAE;YACCoH;QAAjB,MAAMnG,OAAOrF,KAAIwL,mBAAAA,KAAK,CAAC,EAAE,CAACrE,QAAQ,qBAAjBqE,gBAAmB,CAAC,iBAAiB;QACtDqC,MAAMhD,IAAI,CACR,CAAC,gBAAgB,EAAExF,OAAO,CAAC,KAAK,EAAEA,MAAM,GAAG,GAAG,kBAAkB,EAAEmG,MAAMzK,GAAG,CAAC,CAACkF,OAAS,CAAC,CAAC,EAAEA,KAAKgB,KAAK,CAAC,CAAC,CAAC,EAAEwG,IAAI,CAAC,MAAM,CAAC,CAAC,EACtH;IAEJ;IACA,IAAInE,SAASlF,MAAM,EAAE;QACnByJ,MAAMhD,IAAI,CACR,CAAC,2BAA2B,EAAEvB,SAASvI,GAAG,CAAC,CAAC4G,UAAY,CAAC,CAAC,EAAEA,QAAQV,KAAK,CAAC,CAAC,CAAC,EAAEwG,IAAI,CAAC,MAAM,CAAC,CAAC,EAC3F,sHACA,mFAAmF;QACnF;IAEJ;IACA,OAAOI;AACT"}
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
17
|
import { AI_STEP_TIERS } from "../providers/catalog.js";
|
|
18
18
|
import { AI_ROUTING_TABLE, aiModelForStep } from "../providers/routing.js";
|
|
19
|
+
import { aiDevEffortFor } from "../runtime/ai-dev-env.js";
|
|
19
20
|
import { runAiRequest } from "../runtime/ai-runtime.js";
|
|
20
21
|
import { aiJobStepBudget } from "./ai-job-budget.js";
|
|
21
22
|
import { aiOverlayCopyRequested } from "../model/ai-overlay-copy.js";
|
|
@@ -74,7 +75,7 @@ import { runAiOverlayCopy } from "./ai-job-overlay-copy.js";
|
|
|
74
75
|
return lines.join('\n');
|
|
75
76
|
}
|
|
76
77
|
export const runAiJobTextStep = async ({ job, signal, modelFor })=>{
|
|
77
|
-
var _ref, _job_hostId;
|
|
78
|
+
var _ref, _aiDevEffortFor, _job_hostId;
|
|
78
79
|
const model = (_ref = modelFor == null ? void 0 : modelFor('job.text')) != null ? _ref : aiJobTextModel();
|
|
79
80
|
// Overlay copy (AGL-3603): the same one request, answered as fields.
|
|
80
81
|
if (aiOverlayCopyRequested(job.inputs)) {
|
|
@@ -86,6 +87,8 @@ export const runAiJobTextStep = async ({ job, signal, modelFor })=>{
|
|
|
86
87
|
signal
|
|
87
88
|
} : {}));
|
|
88
89
|
}
|
|
90
|
+
// A development run's effort A/B arm (AGL-3781), else the row's.
|
|
91
|
+
const effort = (_aiDevEffortFor = aiDevEffortFor('job.text')) != null ? _aiDevEffortFor : AI_ROUTING_TABLE['job.text'].effort;
|
|
89
92
|
const result = await runAiRequest(_extends({
|
|
90
93
|
model,
|
|
91
94
|
system: AI_JOB_TEXT_SYSTEM,
|
|
@@ -100,8 +103,8 @@ export const runAiJobTextStep = async ({ job, signal, modelFor })=>{
|
|
|
100
103
|
maxTokens: AI_JOB_TEXT_STEP_BUDGET.maxTokens(model)
|
|
101
104
|
}, AI_ROUTING_TABLE['job.text'].thinking ? {
|
|
102
105
|
thinking: AI_ROUTING_TABLE['job.text'].thinking
|
|
103
|
-
} : {},
|
|
104
|
-
effort
|
|
106
|
+
} : {}, effort ? {
|
|
107
|
+
effort
|
|
105
108
|
} : {}, {
|
|
106
109
|
stream: false
|
|
107
110
|
}, signal ? {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-text-step.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 type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type {\n AiJob,\n AiJobOutput,\n AiJobPlan,\n AiJobReview,\n AiJobItemFailure,\n AiJobItemLedger,\n AiJobItemStatus,\n AiJobSitePublish,\n} from '../model/ai-jobs.types'\nimport { AI_STEP_TIERS, type AiStepKind } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport { runAiRequest, type AiEffort, type AiSystemBlock } from '../runtime/ai-runtime'\nimport type { AssistTokenUsage } from '../usage/assist-usage'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiOverlayCopyRequested } from '../model/ai-overlay-copy'\nimport { runAiOverlayCopy } from './ai-job-overlay-copy'\n\n/**\n * The `text` step (AGL-2904): a brief in, a short piece of copy out.\n *\n * The one step kind this issue ships for real, so the state machine — the\n * lease, the reservation, the record, the beat — is exercised end to end by\n * something that spends tokens, rather than by a stub that could pass with\n * the meter unplugged. Every other kind refuses until its own issue lands.\n *\n * The balanced tier with adaptive thinking: a brief is open-ended in a way the copy\n * assistant's element mode is not, and the cost is one call per job. The\n * static system block is cached; the brief rides in the user turn, so no\n * per-org byte sits inside the cached prefix (AGL-2352, enforced by the\n * runtime before the request leaves).\n */\n\n/** The model the text step runs on: the routing table's answer for `job.text`. */\nexport function aiJobTextModel(): string {\n return aiModelForStep('job.text')\n}\n\n/** The text step's answer ceiling, from the routing table. */\nexport const AI_JOB_TEXT_MAX_TOKENS = AI_ROUTING_TABLE['job.text'].maxTokens\n\n/**\n * The text step's time (AGL-3035): ONE request — no re-ask, and no site\n * inventory to look anything up in — at the routing table's ceiling on the\n * tier `job.text` is served from, with the step's reads and writes. That fits\n * an inline door's budget, so a door runs a text job where it is asked for,\n * and the least time is the helper's worst case rather than a figure anyone\n * chose; a slower tier asks less so its worst case still fits.\n */\nexport const AI_JOB_TEXT_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.text'],\n maxTokens: AI_JOB_TEXT_MAX_TOKENS,\n attempts: 1,\n lookups: 0,\n})\n\n/** The least time one text step needs before it starts. */\nexport const AI_JOB_TEXT_STEP_MINIMUM_MS = AI_JOB_TEXT_STEP_BUDGET.minimumMs\n\n/** How much of a brief is sent. Past this a brief is a document, not a brief. */\nexport const AI_JOB_BRIEF_MAX_CHARS = 4_000\n\n/**\n * What a step hands back to the machine. The machine meters `usage` at\n * `model`'s rates, records the step and appends the outputs; a step never\n * touches the job document or the meter itself.\n */\nexport interface AiJobStepOutcome {\n outputs: AiJobOutput[]\n /**\n * The step made progress and has more of the same work to do (AGL-2910):\n * a site audit works through its pages a batch at a time. The machine\n * records this pass — its spend and its outputs — and hands the SAME step\n * back to run again, so every pass is one reservation and one provider\n * exchange, and the job document says how far it got.\n */\n continue?: boolean\n usage: AssistTokenUsage\n estCostUsd: number\n model: string\n stopReason: string | null\n /**\n * The thinking effort the request asked for, recorded on the step\n * (AGL-2937); absent or `null` when the request named none.\n */\n effort?: AiEffort | null\n /** The model declined the brief (`stop_reason: 'refusal'`). Tokens were spent. */\n refused?: boolean\n /**\n * The model answered and nothing usable came of it — no structured answer\n * even after the step's own re-ask, say (AGL-2938). Tokens were spent, so\n * the machine meters the step before it fails the job with this sentence,\n * which is customer-safe and the only thing a customer reads.\n */\n failure?: string\n /** The plan the plan step proposed, which the machine keeps on the job (AGL-2935). */\n plan?: AiJobPlan\n /**\n * The step stopped for a person (AGL-2935). The machine records what it\n * spent and parks the job `needs_review`: a `plan` review completes the\n * step, so confirming runs the next one; a `doctrine` review hands the\n * step back, so trying again runs the same one.\n */\n review?: AiJobReview\n /**\n * The answer was refused by the platform's own checks, not the model's\n * (AGL-3594): the machine meters the step as any other and then gives the\n * job's credits back to the meters it was charged to (`refundJobCredits`),\n * a bounded number of times a day.\n */\n uncredited?: boolean\n /**\n * The `failure` is the workspace's own limit, not a fault of ours: the\n * month's Free AI credits are spent (a 429 from the kind's admission, asked\n * when the plan is kept). The machine fails the job and gives the step's\n * credits back exactly as for our failure, but announces it as NOT ours, so\n * no staff alert is raised for a customer reaching their allowance.\n */\n customerLimit?: boolean\n /**\n * What a guided site start put live on its last pass (AGL-3596), kept on\n * the job by the machine in the write that records the pass: a step never\n * writes the job document itself.\n */\n sitePublish?: AiJobSitePublish\n /**\n * A `build` pass's unit and what it came to (AGL-3616), which the machine\n * writes to the job's item ledger in the transaction that records the\n * pass's spend. An item's failure is never the step's: it is a row, and\n * the build goes on.\n */\n item?: AiJobItemOutcome\n /** A `build`'s ledger to start from, written by the machine in the same transaction (AGL-3616). */\n items?: AiJobItemLedger[]\n}\n\n/** What one `build` pass came to for the unit it ran (AGL-3616). */\nexport interface AiJobItemOutcome {\n slot: string\n /** `running` while the unit asks for another pass of its own. */\n status: AiJobItemStatus\n failure?: AiJobItemFailure | null\n /** Customer-safe: what the person should know about the item. */\n note?: string | null\n degradedBy?: string[]\n /** The ids of the outputs this pass produced for the item. */\n outputs?: string[]\n}\n\nexport interface AiJobStepContext {\n job: AiJob\n stepIndex: number\n now: Date\n /** Aborts the provider call when the runner's budget ends. */\n signal?: AbortSignal\n /**\n * The Admin SDK handle the machine runs on, for a step that reads what it\n * builds from — a site's theme, say — or writes a draft. A step never\n * writes the job document, the meter or the lease through it.\n */\n firestore: FirebaseFirestore.Firestore\n /** The org document the machine read for the step's reservation. */\n org?: Partial<AglynOrgBilling> | null\n /**\n * The model a step of this kind runs on for THIS job (AGL-2942): the\n * creator's pick where the plan and the allotment allowlists allow it,\n * the routing table otherwise. Absent, a runner asks the table itself.\n */\n modelFor?: (kind: AiStepKind) => string | undefined\n}\n\nexport type AiJobStepRunner = (\n context: AiJobStepContext,\n) => Promise<AiJobStepOutcome>\n\n/**\n * The static block, byte-identical on every request so it caches. The\n * customer's brief and the org's inputs never enter it.\n */\nexport const AI_JOB_TEXT_SYSTEM: AiSystemBlock[] = [\n {\n text:\n 'You write short, publishable copy for a website builder. You are ' +\n 'given a brief from the person who owns the site. Answer with the ' +\n 'copy only: no preamble, no headings unless the brief asks for them, ' +\n 'no closing remarks, no markdown fences. Keep to the length the brief ' +\n 'implies; when it implies none, write under 150 words. Write in the ' +\n 'language of the brief. Never invent facts, prices, names or claims ' +\n 'the brief did not give you; where a detail is missing, leave a ' +\n 'clearly marked placeholder in square brackets.',\n cacheBreakpoint: true,\n },\n]\n\n/** The brief as the user turn, with the kind-specific inputs stated plainly. */\nexport function aiJobTextPrompt(job: Pick<AiJob, 'brief' | 'inputs'>): string {\n const brief = job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)\n const tone = typeof job.inputs?.['tone'] === 'string' ? job.inputs['tone'] : ''\n const audience =\n typeof job.inputs?.['audience'] === 'string' ? job.inputs['audience'] : ''\n const lines = [`Brief: ${brief}`]\n if (tone) lines.push(`Tone: ${tone}`)\n if (audience) lines.push(`Audience: ${audience}`)\n return lines.join('\\n')\n}\n\nexport const runAiJobTextStep: AiJobStepRunner = async ({ job, signal, modelFor }) => {\n const model = modelFor?.('job.text') ?? aiJobTextModel()\n // Overlay copy (AGL-3603): the same one request, answered as fields.\n if (aiOverlayCopyRequested(job.inputs)) {\n return runAiOverlayCopy({\n job,\n model,\n maxTokens: AI_JOB_TEXT_STEP_BUDGET.maxTokens(model),\n ...(signal ? { signal } : {}),\n })\n }\n const result = await runAiRequest({\n model,\n system: AI_JOB_TEXT_SYSTEM,\n messages: [{ role: 'user', content: aiJobTextPrompt(job) }],\n // The routing ceiling, lowered on a tier too slow to answer it inside the\n // least time the step registered.\n maxTokens: AI_JOB_TEXT_STEP_BUDGET.maxTokens(model),\n ...(AI_ROUTING_TABLE['job.text'].thinking ? { thinking: AI_ROUTING_TABLE['job.text'].thinking } : {}),\n ...(AI_ROUTING_TABLE['job.text'].effort ? { effort: AI_ROUTING_TABLE['job.text'].effort } : {}),\n stream: false,\n ...(signal ? { signal } : {}),\n })\n if (result.kind === 'refusal') {\n return {\n outputs: [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model,\n stopReason: result.stopReason,\n refused: true,\n }\n }\n const text = result.text.trim()\n return {\n outputs: text\n ? [\n {\n resource: 'text',\n // A text output has no document of its own; the id names the\n // step within the job so a later step can address it.\n id: 'draft',\n hostId: job.hostId ?? null,\n label: 'Draft copy',\n text,\n },\n ]\n : [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model,\n stopReason: result.stopReason,\n }\n}\n"],"names":["AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","runAiRequest","aiJobStepBudget","aiOverlayCopyRequested","runAiOverlayCopy","aiJobTextModel","AI_JOB_TEXT_MAX_TOKENS","maxTokens","AI_JOB_TEXT_STEP_BUDGET","tier","attempts","lookups","AI_JOB_TEXT_STEP_MINIMUM_MS","minimumMs","AI_JOB_BRIEF_MAX_CHARS","AI_JOB_TEXT_SYSTEM","text","cacheBreakpoint","aiJobTextPrompt","job","brief","slice","tone","inputs","audience","lines","push","join","runAiJobTextStep","signal","modelFor","model","result","system","messages","role","content","thinking","effort","stream","kind","outputs","usage","estCostUsd","stopReason","refused","trim","resource","id","hostId","label"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAaD,SAASA,aAAa,QAAyB,0BAAsB;AACrE,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SAASC,YAAY,QAA2C,2BAAuB;AAEvF,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SAASC,sBAAsB,QAAQ,8BAA0B;AACjE,SAASC,gBAAgB,QAAQ,2BAAuB;AAExD;;;;;;;;;;;;;CAaC,GAED,gFAAgF,GAChF,OAAO,SAASC;IACd,OAAOL,eAAe;AACxB;AAEA,4DAA4D,GAC5D,OAAO,MAAMM,yBAAyBP,gBAAgB,CAAC,WAAW,CAACQ,SAAS,CAAA;AAE5E;;;;;;;CAOC,GACD,OAAO,MAAMC,0BAA0BN,gBAAgB;IACrDO,MAAMX,aAAa,CAAC,WAAW;IAC/BS,WAAWD;IACXI,U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RmB,UAAU;YAAC;gBAAEC,MAAM;gBAAQC,SAASlB,gBAAgBC;YAAK;SAAE;QAC3D,0EAA0E;QAC1E,kCAAkC;QAClCZ,WAAWC,wBAAwBD,SAAS,CAACwB;OACzChC,gBAAgB,CAAC,WAAW,CAACsC,QAAQ,GAAG;QAAEA,UAAUtC,gBAAgB,CAAC,WAAW,CAACsC,QAAQ;IAAC,IAAI,CAAC,GAC/FtC,gBAAgB,CAAC,WAAW,CAACuC,MAAM,GAAG;QAAEA,QAAQvC,gBAAgB,CAAC,WAAW,CAACuC,MAAM;IAAC,IAAI,CAAC;QAC7FC,QAAQ;OACJV,SAAS;QAAEA;IAAO,IAAI,CAAC;IAE7B,IAAIG,OAAOQ,IAAI,KAAK,WAAW;QAC7B,OAAO;YACLC,SAAS,EAAE;YACXC,OAAOV,OAAOU,KAAK;YACnBC,YAAYX,OAAOW,UAAU;YAC7BZ;YACAa,YAAYZ,OAAOY,UAAU;YAC7BC,SAAS;QACX;IACF;IACA,MAAM7B,OAAOgB,OAAOhB,IAAI,CAAC8B,IAAI;IAC7B,OAAO;QACLL,SAASzB,OACL;YACE;gBACE+B,UAAU;gBACV,6DAA6D;gBAC7D,sDAAsD;gBACtDC,IAAI;gBACJC,MAAM,GAAE9B,cAAAA,IAAI8B,MAAM,YAAV9B,cAAc;gBACtB+B,OAAO;gBACPlC;YACF;SACD,GACD,EAAE;QACN0B,OAAOV,OAAOU,KAAK;QACnBC,YAAYX,OAAOW,UAAU;QAC7BZ;QACAa,YAAYZ,OAAOY,UAAU;IAC/B;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-text-step.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 type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type {\n AiJob,\n AiJobOutput,\n AiJobPlan,\n AiJobReview,\n AiJobItemFailure,\n AiJobItemLedger,\n AiJobItemStatus,\n AiJobSitePublish,\n} from '../model/ai-jobs.types'\nimport { AI_STEP_TIERS, type AiStepKind } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport { aiDevEffortFor } from '../runtime/ai-dev-env'\nimport { runAiRequest, type AiEffort, type AiSystemBlock } from '../runtime/ai-runtime'\nimport type { AssistTokenUsage } from '../usage/assist-usage'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiOverlayCopyRequested } from '../model/ai-overlay-copy'\nimport { runAiOverlayCopy } from './ai-job-overlay-copy'\n\n/**\n * The `text` step (AGL-2904): a brief in, a short piece of copy out.\n *\n * The one step kind this issue ships for real, so the state machine — the\n * lease, the reservation, the record, the beat — is exercised end to end by\n * something that spends tokens, rather than by a stub that could pass with\n * the meter unplugged. Every other kind refuses until its own issue lands.\n *\n * The balanced tier with adaptive thinking: a brief is open-ended in a way the copy\n * assistant's element mode is not, and the cost is one call per job. The\n * static system block is cached; the brief rides in the user turn, so no\n * per-org byte sits inside the cached prefix (AGL-2352, enforced by the\n * runtime before the request leaves).\n */\n\n/** The model the text step runs on: the routing table's answer for `job.text`. */\nexport function aiJobTextModel(): string {\n return aiModelForStep('job.text')\n}\n\n/** The text step's answer ceiling, from the routing table. */\nexport const AI_JOB_TEXT_MAX_TOKENS = AI_ROUTING_TABLE['job.text'].maxTokens\n\n/**\n * The text step's time (AGL-3035): ONE request — no re-ask, and no site\n * inventory to look anything up in — at the routing table's ceiling on the\n * tier `job.text` is served from, with the step's reads and writes. That fits\n * an inline door's budget, so a door runs a text job where it is asked for,\n * and the least time is the helper's worst case rather than a figure anyone\n * chose; a slower tier asks less so its worst case still fits.\n */\nexport const AI_JOB_TEXT_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.text'],\n maxTokens: AI_JOB_TEXT_MAX_TOKENS,\n attempts: 1,\n lookups: 0,\n})\n\n/** The least time one text step needs before it starts. */\nexport const AI_JOB_TEXT_STEP_MINIMUM_MS = AI_JOB_TEXT_STEP_BUDGET.minimumMs\n\n/** How much of a brief is sent. Past this a brief is a document, not a brief. */\nexport const AI_JOB_BRIEF_MAX_CHARS = 4_000\n\n/**\n * What a step hands back to the machine. The machine meters `usage` at\n * `model`'s rates, records the step and appends the outputs; a step never\n * touches the job document or the meter itself.\n */\nexport interface AiJobStepOutcome {\n outputs: AiJobOutput[]\n /**\n * The step made progress and has more of the same work to do (AGL-2910):\n * a site audit works through its pages a batch at a time. The machine\n * records this pass — its spend and its outputs — and hands the SAME step\n * back to run again, so every pass is one reservation and one provider\n * exchange, and the job document says how far it got.\n */\n continue?: boolean\n usage: AssistTokenUsage\n estCostUsd: number\n model: string\n stopReason: string | null\n /**\n * The thinking effort the request asked for, recorded on the step\n * (AGL-2937); absent or `null` when the request named none.\n */\n effort?: AiEffort | null\n /** The model declined the brief (`stop_reason: 'refusal'`). Tokens were spent. */\n refused?: boolean\n /**\n * The model answered and nothing usable came of it — no structured answer\n * even after the step's own re-ask, say (AGL-2938). Tokens were spent, so\n * the machine meters the step before it fails the job with this sentence,\n * which is customer-safe and the only thing a customer reads.\n */\n failure?: string\n /** The plan the plan step proposed, which the machine keeps on the job (AGL-2935). */\n plan?: AiJobPlan\n /**\n * The step stopped for a person (AGL-2935). The machine records what it\n * spent and parks the job `needs_review`: a `plan` review completes the\n * step, so confirming runs the next one; a `doctrine` review hands the\n * step back, so trying again runs the same one.\n */\n review?: AiJobReview\n /**\n * The answer was refused by the platform's own checks, not the model's\n * (AGL-3594): the machine meters the step as any other and then gives the\n * job's credits back to the meters it was charged to (`refundJobCredits`),\n * a bounded number of times a day.\n */\n uncredited?: boolean\n /**\n * The `failure` is the workspace's own limit, not a fault of ours: the\n * month's Free AI credits are spent (a 429 from the kind's admission, asked\n * when the plan is kept). The machine fails the job and gives the step's\n * credits back exactly as for our failure, but announces it as NOT ours, so\n * no staff alert is raised for a customer reaching their allowance.\n */\n customerLimit?: boolean\n /**\n * What a guided site start put live on its last pass (AGL-3596), kept on\n * the job by the machine in the write that records the pass: a step never\n * writes the job document itself.\n */\n sitePublish?: AiJobSitePublish\n /**\n * A `build` pass's unit and what it came to (AGL-3616), which the machine\n * writes to the job's item ledger in the transaction that records the\n * pass's spend. An item's failure is never the step's: it is a row, and\n * the build goes on.\n */\n item?: AiJobItemOutcome\n /** A `build`'s ledger to start from, written by the machine in the same transaction (AGL-3616). */\n items?: AiJobItemLedger[]\n}\n\n/** What one `build` pass came to for the unit it ran (AGL-3616). */\nexport interface AiJobItemOutcome {\n slot: string\n /** `running` while the unit asks for another pass of its own. */\n status: AiJobItemStatus\n failure?: AiJobItemFailure | null\n /** Customer-safe: what the person should know about the item. */\n note?: string | null\n degradedBy?: string[]\n /** The ids of the outputs this pass produced for the item. */\n outputs?: string[]\n}\n\nexport interface AiJobStepContext {\n job: AiJob\n stepIndex: number\n now: Date\n /** Aborts the provider call when the runner's budget ends. */\n signal?: AbortSignal\n /**\n * The Admin SDK handle the machine runs on, for a step that reads what it\n * builds from — a site's theme, say — or writes a draft. A step never\n * writes the job document, the meter or the lease through it.\n */\n firestore: FirebaseFirestore.Firestore\n /** The org document the machine read for the step's reservation. */\n org?: Partial<AglynOrgBilling> | null\n /**\n * The model a step of this kind runs on for THIS job (AGL-2942): the\n * creator's pick where the plan and the allotment allowlists allow it,\n * the routing table otherwise. Absent, a runner asks the table itself.\n */\n modelFor?: (kind: AiStepKind) => string | undefined\n}\n\nexport type AiJobStepRunner = (\n context: AiJobStepContext,\n) => Promise<AiJobStepOutcome>\n\n/**\n * The static block, byte-identical on every request so it caches. The\n * customer's brief and the org's inputs never enter it.\n */\nexport const AI_JOB_TEXT_SYSTEM: AiSystemBlock[] = [\n {\n text:\n 'You write short, publishable copy for a website builder. You are ' +\n 'given a brief from the person who owns the site. Answer with the ' +\n 'copy only: no preamble, no headings unless the brief asks for them, ' +\n 'no closing remarks, no markdown fences. Keep to the length the brief ' +\n 'implies; when it implies none, write under 150 words. Write in the ' +\n 'language of the brief. Never invent facts, prices, names or claims ' +\n 'the brief did not give you; where a detail is missing, leave a ' +\n 'clearly marked placeholder in square brackets.',\n cacheBreakpoint: true,\n },\n]\n\n/** The brief as the user turn, with the kind-specific inputs stated plainly. */\nexport function aiJobTextPrompt(job: Pick<AiJob, 'brief' | 'inputs'>): string {\n const brief = job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)\n const tone = typeof job.inputs?.['tone'] === 'string' ? job.inputs['tone'] : ''\n const audience =\n typeof job.inputs?.['audience'] === 'string' ? job.inputs['audience'] : ''\n const lines = [`Brief: ${brief}`]\n if (tone) lines.push(`Tone: ${tone}`)\n if (audience) lines.push(`Audience: ${audience}`)\n return lines.join('\\n')\n}\n\nexport const runAiJobTextStep: AiJobStepRunner = async ({ job, signal, modelFor }) => {\n const model = modelFor?.('job.text') ?? aiJobTextModel()\n // Overlay copy (AGL-3603): the same one request, answered as fields.\n if (aiOverlayCopyRequested(job.inputs)) {\n return runAiOverlayCopy({\n job,\n model,\n maxTokens: AI_JOB_TEXT_STEP_BUDGET.maxTokens(model),\n ...(signal ? { signal } : {}),\n })\n }\n // A development run's effort A/B arm (AGL-3781), else the row's.\n const effort = aiDevEffortFor('job.text') ?? AI_ROUTING_TABLE['job.text'].effort\n const result = await runAiRequest({\n model,\n system: AI_JOB_TEXT_SYSTEM,\n messages: [{ role: 'user', content: aiJobTextPrompt(job) }],\n // The routing ceiling, lowered on a tier too slow to answer it inside the\n // least time the step registered.\n maxTokens: AI_JOB_TEXT_STEP_BUDGET.maxTokens(model),\n ...(AI_ROUTING_TABLE['job.text'].thinking ? { thinking: AI_ROUTING_TABLE['job.text'].thinking } : {}),\n ...(effort ? { effort } : {}),\n stream: false,\n ...(signal ? { signal } : {}),\n })\n if (result.kind === 'refusal') {\n return {\n outputs: [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model,\n stopReason: result.stopReason,\n refused: true,\n }\n }\n const text = result.text.trim()\n return {\n outputs: text\n ? [\n {\n resource: 'text',\n // A text output has no document of its own; the id names the\n // step within the job so a later step can address it.\n id: 'draft',\n hostId: job.hostId ?? null,\n label: 'Draft copy',\n text,\n },\n ]\n : [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model,\n stopReason: result.stopReason,\n }\n}\n"],"names":["AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","aiDevEffortFor","runAiRequest","aiJobStepBudget","aiOverlayCopyRequested","runAiOverlayCopy","aiJobTextModel","AI_JOB_TEXT_MAX_TOKENS","maxTokens","AI_JOB_TEXT_STEP_BUDGET","tier","attempts","lookups","AI_JOB_TEXT_STEP_MINIMUM_MS","minimumMs","AI_JOB_BRIEF_MAX_CHARS","AI_JOB_TEXT_SYSTEM","text","cacheBreakpoint","aiJobTextPrompt","job","brief","slice","tone","inputs","audience","lines","push","join","runAiJobTextStep","signal","modelFor","model","effort","result","system","messages","role","content","thinking","stream","kind","outputs","usage","estCostUsd","stopReason","refused","trim","resource","id","hostId","label"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAaD,SAASA,aAAa,QAAyB,0BAAsB;AACrE,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SAASC,cAAc,QAAQ,2BAAuB;AACtD,SAASC,YAAY,QAA2C,2BAAuB;AAEvF,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SAASC,sBAAsB,QAAQ,8BAA0B;AACjE,SAASC,gBAAgB,QAAQ,2BAAuB;AAExD;;;;;;;;;;;;;CAaC,GAED,gFAAgF,GAChF,OAAO,SAASC;IACd,OAAON,eAAe;AACxB;AAEA,4D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PhotoSourceInput {
|
|
|
412
412
|
language?: string;
|
|
413
413
|
/**
|
|
414
414
|
* The plan's photo words, in English (AGL-3760): what a site in another
|
|
415
|
-
* language is searched by, in place of its business type and its alt texts
|
|
415
|
+
* language is searched by, in place of its business type and its alt texts,
|
|
416
|
+
* unless its business type names a business listed in English
|
|
417
|
+
* (`aiStockBusinessNoun`, AGL-3779), which leads.
|
|
416
418
|
*/
|
|
417
419
|
photoWords?: string;
|
|
418
420
|
/**
|
|
419
421
|
* The English name of the kind of site the person picked (AGL-3771): what a
|
|
420
|
-
* site in another language
|
|
421
|
-
*
|
|
422
|
+
* site in another language is searched by when its business type names no
|
|
423
|
+
* business listed in English (`aiStockBusinessNoun`, AGL-3779) and its plan
|
|
424
|
+
* gave no photo words, rather than its business type in its own language.
|
|
422
425
|
*/
|
|
423
426
|
kindWords?: string;
|
|
424
427
|
/** The page's section names, by plan index. */
|
|
@@ -461,10 +464,11 @@ export declare function aiStockPhotoWordsOf(job: {
|
|
|
461
464
|
export declare function aiStockPhotoWordsSubject(photoWords: string): string;
|
|
462
465
|
/**
|
|
463
466
|
* What a source's photos are searched and judged by (AGL-3760, AGL-3769): a
|
|
464
|
-
* site in another language by
|
|
465
|
-
*
|
|
466
|
-
*
|
|
467
|
-
*
|
|
467
|
+
* site in another language by an English subject ({@link aiStockSourceSubject}:
|
|
468
|
+
* its business named in English, else its plan's photo words' subject, else
|
|
469
|
+
* its kind of site), every other site by its business type. One reading for
|
|
470
|
+
* every slot of every source — hero, background, gallery, card, product,
|
|
471
|
+
* post — so no slot searches by words another slot is held against.
|
|
468
472
|
*/
|
|
469
473
|
export declare function aiStockSourceTerms(input: Pick<AiLayoutStockPhotoSourceInput, 'business' | 'language' | 'photoWords' | 'kindWords'>): AiStockSiteTerms;
|
|
470
474
|
/**
|
|
@@ -20,6 +20,7 @@ import { aiLayoutSeedNumber } from "../layout-language/ai-layout-pictures.js";
|
|
|
20
20
|
import { aiStorefrontSays } from "../layout-language/ai-layout-storefront.js";
|
|
21
21
|
import { aiLayoutSpeaksOtherThanEnglish } from "../layout-language/ai-layout-labels.js";
|
|
22
22
|
import { aiSiteKindOfInputs } from "../model/ai-site-kinds.js";
|
|
23
|
+
import { aiStockBusinessNoun } from "./ai-stock-business-nouns.js";
|
|
23
24
|
/**
|
|
24
25
|
* STOCK PHOTOS FOR A LANGUAGE PAGE'S PICTURE SLOTS (AGL-3660).
|
|
25
26
|
*
|
|
@@ -1806,23 +1807,37 @@ const EXTENSIONS = {
|
|
|
1806
1807
|
}
|
|
1807
1808
|
/**
|
|
1808
1809
|
* What a source's photos are searched and judged by (AGL-3760, AGL-3769): a
|
|
1809
|
-
* site in another language by
|
|
1810
|
-
*
|
|
1811
|
-
*
|
|
1812
|
-
*
|
|
1810
|
+
* site in another language by an English subject ({@link aiStockSourceSubject}:
|
|
1811
|
+
* its business named in English, else its plan's photo words' subject, else
|
|
1812
|
+
* its kind of site), every other site by its business type. One reading for
|
|
1813
|
+
* every slot of every source — hero, background, gallery, card, product,
|
|
1814
|
+
* post — so no slot searches by words another slot is held against.
|
|
1813
1815
|
*/ export function aiStockSourceTerms(input) {
|
|
1814
1816
|
return aiStockSiteTerms(aiStockSourceSubject(input) || input.business);
|
|
1815
1817
|
}
|
|
1816
1818
|
/**
|
|
1817
|
-
* What a site in another language is searched by ({@link aiStockSourceTerms})
|
|
1818
|
-
*
|
|
1819
|
-
*
|
|
1820
|
-
*
|
|
1821
|
-
*
|
|
1819
|
+
* What a site in another language is searched by ({@link aiStockSourceTerms}),
|
|
1820
|
+
* in this order (AGL-3779):
|
|
1821
|
+
*
|
|
1822
|
+
* 1. The English name of the business its type names, where the curated table
|
|
1823
|
+
* knows it ({@link aiStockBusinessNoun}): "florist" for "Una floristería en
|
|
1824
|
+
* Sevilla". It leads whatever the plan's photo words say, because the words
|
|
1825
|
+
* are the model's and the table is not: a live plan for that florist gave
|
|
1826
|
+
* "wedding bouquets event flowers", whose subject, "wedding", would have
|
|
1827
|
+
* searched every slot, its hero included, by weddings.
|
|
1828
|
+
* 2. Its photo words' subject (AGL-3760, AGL-3769), for a business the table
|
|
1829
|
+
* does not list.
|
|
1830
|
+
* 3. The English name of its kind of site (AGL-3771), where the plan gave
|
|
1831
|
+
* none. Panaderia El Trigal's pages searched "con pan dulce" and placed the
|
|
1832
|
+
* Río Dulce; searched by its kind, a bakery's hero took a coffee mug
|
|
1833
|
+
* ("restaurant cafe"), which is why it comes last.
|
|
1834
|
+
*
|
|
1835
|
+
* The photo words' other words were never searched by (AGL-3769), so a site
|
|
1836
|
+
* the table names is searched by its name alone. Empty for every other site.
|
|
1822
1837
|
*/ function aiStockSourceSubject(input) {
|
|
1823
1838
|
var _input_photoWords, _input_kindWords;
|
|
1824
1839
|
if (!aiLayoutSpeaksOtherThanEnglish(input.language)) return '';
|
|
1825
|
-
return aiStockPhotoWordsSubject((_input_photoWords = input.photoWords) != null ? _input_photoWords : '') || ((_input_kindWords = input.kindWords) != null ? _input_kindWords : '').trim();
|
|
1840
|
+
return aiStockBusinessNoun(input.business) || aiStockPhotoWordsSubject((_input_photoWords = input.photoWords) != null ? _input_photoWords : '') || ((_input_kindWords = input.kindWords) != null ? _input_kindWords : '').trim();
|
|
1826
1841
|
}
|
|
1827
1842
|
/**
|
|
1828
1843
|
* The source for one page, or `null` when this deployment has no stock
|