@aglyn/plugins-ai 1.9.0 → 1.10.0
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-job-requests.d.ts +5 -0
- package/src/lib/components/ai-job-requests.js +4 -0
- package/src/lib/components/ai-job-requests.js.map +1 -1
- package/src/lib/components/ai-site-build-page.component.js +10 -3
- package/src/lib/components/ai-site-build-page.component.js.map +1 -1
- package/src/lib/components/ai-site-import-finish.component.d.ts +40 -0
- package/src/lib/components/ai-site-import-finish.component.js +174 -0
- package/src/lib/components/ai-site-import-finish.component.js.map +1 -0
- package/src/lib/components/ai-site-import-job.component.d.ts +11 -3
- package/src/lib/components/ai-site-import-job.component.js +220 -135
- package/src/lib/components/ai-site-import-job.component.js.map +1 -1
- package/src/lib/components/ai-site-import-start.component.d.ts +11 -2
- package/src/lib/components/ai-site-import-start.component.js +27 -5
- package/src/lib/components/ai-site-import-start.component.js.map +1 -1
- package/src/lib/components/ai-site-start-card.component.js +1 -1
- package/src/lib/components/ai-site-start-card.component.js.map +1 -1
- package/src/lib/jobs/ai-build-capabilities.js +2 -2
- package/src/lib/jobs/ai-build-capabilities.js.map +1 -1
- package/src/lib/jobs/ai-job-import-step.d.ts +2 -0
- package/src/lib/jobs/ai-job-import-step.js +31 -8
- package/src/lib/jobs/ai-job-import-step.js.map +1 -1
- package/src/lib/jobs/ai-job-page-language.d.ts +40 -2
- package/src/lib/jobs/ai-job-page-language.js +188 -9
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-step.js +2 -0
- package/src/lib/jobs/ai-job-page-step.js.map +1 -1
- package/src/lib/jobs/ai-job-privacy-step.d.ts +5 -0
- package/src/lib/jobs/ai-job-privacy-step.js +9 -4
- package/src/lib/jobs/ai-job-privacy-step.js.map +1 -1
- package/src/lib/jobs/ai-job-text-step.d.ts +7 -1
- package/src/lib/jobs/ai-job-text-step.js.map +1 -1
- package/src/lib/jobs/ai-site-import-compile.d.ts +13 -2
- package/src/lib/jobs/ai-site-import-compile.js +115 -21
- package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
- package/src/lib/jobs/ai-site-import-document.d.ts +5 -1
- package/src/lib/jobs/ai-site-import-document.js +5 -1
- package/src/lib/jobs/ai-site-import-document.js.map +1 -1
- package/src/lib/jobs/ai-site-import-look.d.ts +16 -4
- package/src/lib/jobs/ai-site-import-look.js +54 -13
- package/src/lib/jobs/ai-site-import-look.js.map +1 -1
- package/src/lib/jobs/ai-site-import-wording.d.ts +187 -0
- package/src/lib/jobs/ai-site-import-wording.js +747 -0
- package/src/lib/jobs/ai-site-import-wording.js.map +1 -0
- package/src/lib/layout-language/ai-layout-compiler.d.ts +12 -1
- package/src/lib/layout-language/ai-layout-compiler.js +29 -30
- package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
- package/src/lib/layout-language/ai-layout-language.d.ts +12 -0
- package/src/lib/layout-language/ai-layout-language.js.map +1 -1
- package/src/lib/model/ai-site-import-fidelity.d.ts +211 -2
- package/src/lib/model/ai-site-import-fidelity.js +1011 -14
- package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
- package/src/lib/model/ai-site-import-report.d.ts +52 -1
- package/src/lib/model/ai-site-import-report.js +102 -5
- package/src/lib/model/ai-site-import-report.js.map +1 -1
- package/src/lib/model/ai-site-import-view.d.ts +62 -2
- package/src/lib/model/ai-site-import-view.js +83 -4
- package/src/lib/model/ai-site-import-view.js.map +1 -1
- package/src/lib/model/ai-site-import.d.ts +122 -6
- package/src/lib/model/ai-site-import.js +202 -9
- package/src/lib/model/ai-site-import.js.map +1 -1
- package/src/lib/model/ai-site-look.d.ts +51 -0
- package/src/lib/model/ai-site-look.js +205 -29
- package/src/lib/model/ai-site-look.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.d.ts +19 -0
- package/src/lib/runtime/ai-doctrine-validators.js +25 -0
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-doctrine.js +4 -1
- package/src/lib/runtime/ai-doctrine.js.map +1 -1
- package/src/lib/server/ai-allotments.js +4 -2
- package/src/lib/server/ai-allotments.js.map +1 -1
- package/src/lib/server/ai-jobs-resume.js +32 -5
- package/src/lib/server/ai-jobs-resume.js.map +1 -1
- package/src/lib/site-import/fixtures/site-import-fidelity-replay.d.ts +36 -10
- package/src/lib/site-import/fixtures/site-import-fidelity-replay.js +48 -4
- package/src/lib/site-import/fixtures/site-import-fidelity-replay.js.map +1 -1
- package/src/lib/site-import/fixtures/site-look-slate.d.ts +27 -0
- package/src/lib/site-import/fixtures/site-look-slate.js +29 -0
- package/src/lib/site-import/fixtures/site-look-slate.js.map +1 -0
- package/src/lib/site-import/site-import-layout.d.ts +19 -5
- package/src/lib/site-import/site-import-layout.js +137 -16
- package/src/lib/site-import/site-import-layout.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-privacy-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 { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { holdsSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { orgPermissionLabel } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { aiAddonName, checkEntitlement } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { SCREEN_ROOT_PATH } from '@aglyn/aglyn/app-utils/screen-route'\nimport { HostScreenVisibility } from '@aglyn/aglyn/foundation/definitions/platform.types'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport type { PluginAiCapabilityArgsSchema } from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport { getLockdownVerdict } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldValue, type Firestore } from 'firebase-admin/firestore'\nimport type { AiJobOutput } from '../model/ai-jobs.types'\nimport { registerAiJobAdmission, type AiJobAdmission, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { aiJobEditModel } from './ai-job-edit-step'\nimport { aiLimitReview, aiUnspentOutcome } from './ai-job-generation'\nimport type { AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The `privacy` step (AGL-4033): who can see the site, as the console's own\n * three controls set it — maintenance mode (Admin → Error pages), the\n * Discourage search engines switch (Setup → SEO) and a page's Visibility\n * (its Page Access card) — as a first-class build operation, so \"make my site\n * private until launch\" or \"hide the pricing page\" is one item on Assist's\n * plan card. The docs page it mirrors is Site Protection → Make your site\n * private.\n *\n * NO MODEL. The planner already wrote the choices as the item's arguments;\n * this checks each against the rule the console's own control holds it to and\n * writes it, so it costs no credits.\n *\n * ── Only the controls' own fields ────────────────────────────────────────\n *\n * `maintenance` (true, or deleted on the way off, as the Error pages card\n * writes it), `seo.discourageSearchEngines` (likewise, as the Search engines\n * card does), and a page's `visibility` as Public, Unlisted or Members only.\n * Leaving password mode drops the page's stored hash, as the Page Access card\n * does, so protection never lingers on a page that no longer asks for it.\n *\n * NEVER: a page password. Setting one would put the password in the chat and\n * the plan, so it is not an argument; the note sends the person to the Page\n * Access card instead. Nor layouts, emails or record templates, which have no\n * Page Access card, nor the error pages themselves.\n *\n * ── Who may ──────────────────────────────────────────────────────────────\n *\n * Search indexing and page visibility: the Firestore rules' own for those\n * keys, a member with a write role on the site (admin, editor or author)\n * while no lockdown freezes it. Maintenance mode takes every page of the site\n * offline for every visitor, so, as the console keeps its card in the Admin\n * area, only a site ADMIN may change it here. A non-admin's request still\n * makes the rest of its changes and says why that one was not made.\n *\n * Members only is made only where the plan has content gating (Business and\n * above): the tenant serves gated pages nowhere else, so on a lower plan the\n * write would close the page to everyone, and the note says why it was not.\n *\n * ── Live on confirm, idempotent ──────────────────────────────────────────\n *\n * As the `settings` and `tracking` steps: none of these has a draft, so the\n * plan card's confirm is the agreement and the write is live. One transaction\n * re-reads the host and each page, re-checks the role, writes only what\n * differs, and queues a site-wide publish outbox entry, because visibility\n * changes navigation and the sitemap and both switches change every page.\n */\n\nexport const AI_PRIVACY_KIND = 'privacy' as const\n\n/** ASSUMED: the least time the step needs — the site, the org, the pages named and one transaction. */\nexport const AI_JOB_PRIVACY_STEP_MINIMUM_MS = 5_000\n\nexport const AI_PRIVACY_NO_SITE_COPY = 'Open the site whose privacy should change.'\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const AI_PRIVACY_ROLE_COPY = `Changing who can see the site needs the \"${orgPermissionLabel('site.edit')}\" permission on this site — ask an organization admin.`\n/** Names \"Manage site settings\" (`site.manage`, AGL-4047), never a role. */\nexport const AI_PRIVACY_ADMIN_COPY = `Turning maintenance mode on or off needs the \"${orgPermissionLabel('site.manage')}\" permission, so it was left as it is.`\nexport const AI_PRIVACY_LOCKED_COPY = 'This site is not accepting changes right now.'\nexport const AI_PRIVACY_NOTHING_COPY = 'The request named no privacy change this could make.'\nexport const AI_PRIVACY_PASSWORD_COPY =\n `To put a page behind a password, set it in that page’s Page Access card; ${aiAddonName()} never handles passwords.`\n\n/** The most pages one item may change. */\nexport const AI_PRIVACY_MAX_PAGES = 20\n\n/** The visibilities a build may set, by the Page Access card's labels. */\nexport const AI_PRIVACY_VISIBILITIES = ['public', 'unlisted', 'members'] as const\nexport type AiPrivacyVisibility = (typeof AI_PRIVACY_VISIBILITIES)[number]\n\nconst VISIBILITY_VALUES: Readonly<Record<AiPrivacyVisibility, HostScreenVisibility>> = {\n public: HostScreenVisibility.PUBLIC,\n unlisted: HostScreenVisibility.UNLISTED,\n members: HostScreenVisibility.AUTHENTICATED,\n}\n\nconst VISIBILITY_LABELS: Readonly<Record<AiPrivacyVisibility, string>> = {\n public: 'Public',\n unlisted: 'Unlisted',\n members: 'Members only',\n}\n\n/** Where a person finds each change, as the output links and notes name it. */\nexport const AI_PRIVACY_OUTPUTS = {\n maintenance: { id: 'maintenance', label: 'Maintenance mode', where: 'Admin → Error pages' },\n search: { id: 'search', label: 'Search engines', where: 'Setup → SEO' },\n pages: { id: 'pages', label: 'Page access', where: 'each page’s Page Access card' },\n} as const\n\n/** Where the operation's changes are made, as the build's notes name it. */\nexport const AI_PRIVACY_WHERE = 'the site’s privacy settings'\n\n/** The item's arguments, as the planner fills them in. Every one optional. */\nexport const AI_PRIVACY_ARGS_SCHEMA: PluginAiCapabilityArgsSchema = {\n type: 'object',\n properties: {\n maintenance: {\n type: 'boolean',\n description:\n 'true takes the whole site offline: every address shows its 503 page to every visitor, including anyone with a link, until it is turned off. false brings the site back. Leave it out unless the person asked to take the whole site offline, keep it from everyone until launch, or bring it back.',\n },\n discourageSearchEngines: {\n type: 'boolean',\n description:\n 'true asks search engines not to index any page of the site (it stays open to anyone with a link); false lets them index it again. Leave it out unless the person asked about search engines or Google.',\n },\n publicPages: {\n type: 'array',\n description: 'Pages to make Public: anyone can open them, and they are offered to search engines. Each by its id from the site inventory.',\n items: { type: 'string', maxLength: 64 },\n maxItems: AI_PRIVACY_MAX_PAGES,\n },\n unlistedPages: {\n type: 'array',\n description: 'Pages to make Unlisted: anyone with the link can open them, kept out of search results, the sitemap and navigation. Each by its id from the site inventory.',\n items: { type: 'string', maxLength: 64 },\n maxItems: AI_PRIVACY_MAX_PAGES,\n },\n membersPages: {\n type: 'array',\n description: 'Pages to make Members only: only visitors signed in to the site can open them (Business plan and above). Each by its id from the site inventory.',\n items: { type: 'string', maxLength: 64 },\n maxItems: AI_PRIVACY_MAX_PAGES,\n },\n },\n additionalProperties: false,\n}\n\n/** Each visibility's argument, as the planner lists the pages for it. */\nconst VISIBILITY_ARGS: Readonly<Record<AiPrivacyVisibility, string>> = {\n public: 'publicPages',\n unlisted: 'unlistedPages',\n members: 'membersPages',\n}\n\n/** What an item asks: each switch to set, and each page's new visibility. */\nexport interface AiPrivacyRequest {\n maintenance: boolean | null\n discourageSearchEngines: boolean | null\n pages: { page: string; visibility: AiPrivacyVisibility }[]\n}\n\nexport interface AiPrivacyRead {\n request: AiPrivacyRequest\n /** A sentence per value that could not be used, so the rest still are. */\n problems: string[]\n}\n\nconst flag = (value: unknown): boolean | null => (typeof value === 'boolean' ? value : null)\n\n/** A page id as the site inventory gives it: one document id, never a path. */\nconst PAGE_ID = /^[A-Za-z0-9_-]{1,64}$/\n\n/** The item's arguments read: what may be written, and a sentence for each that may not. */\nexport function aiPrivacyRequestOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiPrivacyRead {\n const problems: string[] = []\n const pages: AiPrivacyRequest['pages'] = []\n const asked = new Map<string, Set<AiPrivacyVisibility>>()\n for (const visibility of AI_PRIVACY_VISIBILITIES) {\n const listed = inputs?.[VISIBILITY_ARGS[visibility]]\n for (const entry of Array.isArray(listed) ? listed : []) {\n const page = typeof entry === 'string' ? entry.trim() : ''\n if (PAGE_ID.test(page)) asked.set(page, (asked.get(page) ?? new Set()).add(visibility))\n }\n }\n for (const [page, visibilities] of asked) {\n // A page asked to be two things is left alone rather than guessed at.\n if (visibilities.size > 1) problems.push('A page was asked to be two things at once, so it was left as it is.')\n else pages.push({ page, visibility: [...visibilities][0] })\n }\n if (pages.length > AI_PRIVACY_MAX_PAGES) {\n pages.splice(AI_PRIVACY_MAX_PAGES)\n problems.push(`Only the first ${AI_PRIVACY_MAX_PAGES} pages were changed; ask again for the rest.`)\n }\n return {\n request: {\n maintenance: flag(inputs?.['maintenance']),\n discourageSearchEngines: flag(inputs?.['discourageSearchEngines']),\n pages,\n },\n problems,\n }\n}\n\n/** Whether a read request asks for anything at all. */\nexport function aiPrivacyRequestEmpty(request: AiPrivacyRequest): boolean {\n return request.maintenance === null && request.discourageSearchEngines === null && request.pages.length === 0\n}\n\n// ── The write ─────────────────────────────────────────────────────────────\n\nexport type AiPrivacyWrite =\n | {\n ok: true\n /** A sentence per change asked, made now or already so, by output id. */\n done: { output: keyof typeof AI_PRIVACY_OUTPUTS; said: string }[]\n /** A sentence per part that was not made, and why. */\n notDone: string[]\n changedAny: boolean\n outboxId: string | null\n }\n | { ok: false; error: string }\n\n/**\n * The changes written, in one transaction that reads the host and each named\n * page as they are stored NOW: the member still holds a write role (and is an\n * admin, for maintenance), each page exists and is a page, and only what\n * differs from what is stored is written, with a site-wide publish outbox\n * entry beside it so the live site's cached pages are dropped.\n */\nexport async function writeAiSitePrivacy(\n firestore: Firestore,\n input: { hostId: string; uid: string; request: AiPrivacyRequest; contentGating: boolean; now: Date },\n): Promise<AiPrivacyWrite> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const screens = hostRef.collection('screens')\n return firestore.runTransaction(async (tx): Promise<AiPrivacyWrite> => {\n const host = await tx.get(hostRef)\n if (!host.exists) return { ok: false, error: 'Unknown site' }\n if (!holdsSiteKey(host, input.uid, 'site.edit')) return { ok: false, error: AI_PRIVACY_ROLE_COPY }\n const managesSite = holdsSiteKey(host, input.uid, 'site.manage')\n const pageDocs = await Promise.all(input.request.pages.map((one) => tx.get(screens.doc(one.page))))\n\n const done: { output: keyof typeof AI_PRIVACY_OUTPUTS; said: string }[] = []\n const notDone: string[] = []\n const hostUpdates: Record<string, unknown> = {}\n const pageUpdates: { ref: FirebaseFirestore.DocumentReference; update: Record<string, unknown> }[] = []\n\n const { maintenance, discourageSearchEngines } = input.request\n if (maintenance !== null) {\n if (!managesSite) {\n notDone.push(AI_PRIVACY_ADMIN_COPY)\n } else {\n if ((host.get('maintenance') === true) !== maintenance) {\n hostUpdates['maintenance'] = maintenance || FieldValue.delete()\n }\n const assigned = !!(host.get('errorScreens') as Record<string, unknown> | undefined)?.['unavailable']\n done.push({\n output: 'maintenance',\n said: maintenance\n ? `Maintenance mode is on: every address shows ${assigned ? 'your 503 page' : `${PLATFORM_BRAND_NAME}’s plain “undergoing maintenance” notice, because no 503 page is assigned yet`} to every visitor.`\n : 'Maintenance mode is off: the site is open to visitors again.',\n })\n }\n }\n if (discourageSearchEngines !== null) {\n const stored = (host.get('seo') as Record<string, unknown> | undefined)?.['discourageSearchEngines'] === true\n if (stored !== discourageSearchEngines) {\n hostUpdates['seo.discourageSearchEngines'] = discourageSearchEngines || FieldValue.delete()\n }\n done.push({\n output: 'search',\n said: discourageSearchEngines\n ? 'Search engines are asked not to index this site. Anyone with a link can still open it.'\n : 'Search engines may index this site again. They take days to come back.',\n })\n }\n input.request.pages.forEach((asked, index) => {\n const page = pageDocs[index]\n if (!page.exists || page.get('deletedAt') != null || page.get('kind')) {\n notDone.push('A page named is not one of this site’s pages, so it was left out.')\n return\n }\n const name = String(page.get('displayName') ?? '').trim() || 'A page'\n if (asked.visibility === 'members' && !input.contentGating) {\n // The tenant serves gated pages only on plans with content gating, so\n // writing it here would close the page to everyone.\n notDone.push(`“${name}” was not made Members only: members-only pages need the Business plan or above.`)\n return\n }\n const value = VISIBILITY_VALUES[asked.visibility]\n const update: Record<string, unknown> = {}\n if ((page.get('visibility') ?? HostScreenVisibility.PUBLIC) !== value) update['visibility'] = value\n const hadPassword = !!(page.get('protection') as Record<string, unknown> | undefined)?.['passwordHash']\n if (hadPassword) update['protection'] = FieldValue.delete()\n if (Object.keys(update).length) pageUpdates.push({ ref: page.ref, update: { ...update, updatedAt: input.now } })\n const extra = hadPassword ? ' Its page password was removed.' : ''\n done.push({ output: 'pages', said: `“${name}” is now ${VISIBILITY_LABELS[asked.visibility]}.${extra}` })\n })\n\n const changedAny = Object.keys(hostUpdates).length > 0 || pageUpdates.length > 0\n if (!changedAny) return { ok: true, done, notDone, changedAny, outboxId: null }\n if (Object.keys(hostUpdates).length) tx.update(hostRef, { ...hostUpdates, updatedAt: input.now })\n for (const { ref, update } of pageUpdates) tx.update(ref, update)\n // Both switches change every page, and a page's visibility changes the\n // navigation and the sitemap every other page carries.\n const outboxRef = firestore.collection('publishOutbox').doc(createResourceUid())\n tx.set(outboxRef, {\n hostId: input.hostId,\n paths: [SCREEN_ROOT_PATH],\n entireHost: true,\n createdAt: FieldValue.serverTimestamp(),\n attempts: 0,\n })\n return { ok: true, done, notDone, changedAny, outboxId: outboxRef.id }\n })\n}\n\n// ── The step ──────────────────────────────────────────────────────────────\n\n/** Why this member may not change who can see this site now, or `null`. */\nexport async function aiPrivacyAccessRefusal(\n input: { host: FirebaseFirestore.DocumentSnapshot; uid: string; org: object | null; request: AiPrivacyRequest },\n deps: { lockdown?: typeof getLockdownVerdict } = {},\n): Promise<string | null> {\n if (!input.host.exists) return 'Unknown site'\n if (!holdsSiteKey(input.host, input.uid, 'site.edit')) return AI_PRIVACY_ROLE_COPY\n // A request that is ONLY maintenance has nothing a non-admin may make.\n const onlyMaintenance =\n input.request.maintenance !== null && input.request.discourageSearchEngines === null && !input.request.pages.length\n if (onlyMaintenance && !holdsSiteKey(input.host, input.uid, 'site.manage')) return AI_PRIVACY_ADMIN_COPY\n const locked = await (deps.lockdown ?? getLockdownVerdict)({\n staff: false,\n uid: input.uid,\n org: input.org as never,\n host: input.host.data() as never,\n intent: 'write',\n })\n return locked ? AI_PRIVACY_LOCKED_COPY : null\n}\n\n/** One output's note: what changed, that it is live, and what was not done. */\nexport function aiPrivacyOutputNote(said: readonly string[], where: string, notDone: readonly string[], changedAny: boolean): string {\n const did = said.length\n ? `${said.join(' ')} Live now, in ${where}.${changedAny ? '' : ' It already was, so nothing was written.'}`\n : 'Nothing needed changing.'\n const not = notDone.length ? ` Not done: ${notDone.join(' ')}` : ''\n return `${did}${not}`.slice(0, 1_000)\n}\n\nexport interface AiJobPrivacyStepDeps {\n write?: typeof writeAiSitePrivacy\n lockdown?: typeof getLockdownVerdict\n dropCache?: typeof dropPluginSiteCache\n}\n\nexport function createAiJobPrivacyStep(deps: AiJobPrivacyStepDeps = {}): AiJobStepRunner {\n const write = deps.write ?? writeAiSitePrivacy\n const dropCache = deps.dropCache ?? dropPluginSiteCache\n return async ({ job, now, firestore, org, modelFor }): Promise<AiJobStepOutcome> => {\n // No model is asked: the outcome records the edit step's at no cost.\n const model = modelFor?.('job.edit') ?? aiJobEditModel()\n const unspent = (failure: string): AiJobStepOutcome => ({ ...aiUnspentOutcome(model), failure })\n const hostId = job.hostId\n if (!hostId) return unspent(AI_PRIVACY_NO_SITE_COPY)\n const read = aiPrivacyRequestOf(job.inputs)\n if (aiPrivacyRequestEmpty(read.request)) return unspent([AI_PRIVACY_NOTHING_COPY, ...read.problems].join(' '))\n const orgData = (org ?? ((await firestore.collection('orgs').doc(job.orgId).get()).data() ?? null)) as Record<string, unknown> | null\n const host = await firestore.collection('hosts').doc(hostId).get()\n const refused = await aiPrivacyAccessRefusal({ host, uid: job.createdBy, org: orgData, request: read.request }, { lockdown: deps.lockdown })\n if (refused) return aiUnspentOutcome(model, { review: aiLimitReview(refused) })\n const written = await write(firestore, {\n hostId,\n uid: job.createdBy,\n request: read.request,\n contentGating: checkEntitlement(orgData as never, 'contentGating'),\n now,\n })\n if (written.ok === false) return unspent(written.error)\n if (written.outboxId) {\n // The live site's cached pages go now; the outbox entry stays for the\n // drain unless the drop certainly happened.\n const dropped = await dropCache({ hostIds: [hostId], reason: 'AI build changed site privacy' }).catch(() => ({ complete: false }))\n if (dropped.complete) await firestore.collection('publishOutbox').doc(written.outboxId).delete().catch(() => undefined)\n }\n const notDone = [...read.problems, ...written.notDone]\n const hostSubdomain = (typeof host.get('subdomain') === 'string' && host.get('subdomain')) || null\n const outputs: AiJobOutput[] = (Object.keys(AI_PRIVACY_OUTPUTS) as (keyof typeof AI_PRIVACY_OUTPUTS)[])\n .filter((key) => written.done.some((one) => one.output === key))\n .map((key, index) => ({\n resource: 'privacy',\n id: AI_PRIVACY_OUTPUTS[key].id,\n hostId,\n hostSubdomain,\n label: AI_PRIVACY_OUTPUTS[key].label,\n note: aiPrivacyOutputNote(\n written.done.filter((one) => one.output === key).map((one) => one.said),\n AI_PRIVACY_OUTPUTS[key].where,\n // What was not done is said once, on the first output.\n index === 0 ? notDone : [],\n written.changedAny,\n ),\n }))\n if (!outputs.length) return unspent([AI_PRIVACY_NOTHING_COPY, ...notDone].join(' '))\n return aiUnspentOutcome(model, { outputs })\n }\n}\n\nexport const runAiJobPrivacyStep = createAiJobPrivacyStep()\n\n// ── Admission ─────────────────────────────────────────────────────────────\n\nexport interface AiPrivacyJobAdmissionDeps {\n ownerOf?: typeof resolveOrgIdForHost\n lockdown?: typeof getLockdownVerdict\n}\n\n/**\n * A privacy change is admitted on a site of the job's own org, for a member\n * who may write it now, where the request names at least one change this can\n * make. Refused in those words before anything is written.\n */\nexport function createAiPrivacyJobAdmission(deps: AiPrivacyJobAdmissionDeps = {}): AiJobAdmission {\n const ownerOf = deps.ownerOf ?? resolveOrgIdForHost\n return async (context): Promise<AiJobAdmissionRefusal | null> => {\n if (!context.hostId) return { status: 400, error: AI_PRIVACY_NO_SITE_COPY }\n const owner = await ownerOf(context.hostId)\n if (!owner || owner !== context.orgId) return { status: 404, error: 'Unknown site' }\n const read = aiPrivacyRequestOf(context.inputs as Record<string, unknown>)\n if (aiPrivacyRequestEmpty(read.request)) return { status: 400, error: [AI_PRIVACY_NOTHING_COPY, ...read.problems].join(' ') }\n const host = await context.firestore.collection('hosts').doc(context.hostId).get()\n const refused = await aiPrivacyAccessRefusal(\n { host, uid: context.uid ?? '', org: context.org, request: read.request },\n { lockdown: deps.lockdown },\n )\n return refused ? { status: 403, error: refused } : null\n }\n}\n\nexport const aiPrivacyJobAdmission = createAiPrivacyJobAdmission()\n\n/** Registers the privacy step and its door (AGL-4033). */\nexport function registerAiPrivacyJob(): void {\n registerAiJobStep(AI_PRIVACY_KIND, runAiJobPrivacyStep, { minimumMs: AI_JOB_PRIVACY_STEP_MINIMUM_MS })\n registerAiJobAdmission(AI_PRIVACY_KIND, aiPrivacyJobAdmission)\n}\n"],"names":["createResourceUid","holdsSiteKey","orgPermissionLabel","aiAddonName","checkEntitlement","PLATFORM_BRAND_NAME","SCREEN_ROOT_PATH","HostScreenVisibility","dropPluginSiteCache","getLockdownVerdict","resolveOrgIdForHost","FieldValue","registerAiJobAdmission","aiJobEditModel","aiLimitReview","aiUnspentOutcome","registerAiJobStep","AI_PRIVACY_KIND","AI_JOB_PRIVACY_STEP_MINIMUM_MS","AI_PRIVACY_NO_SITE_COPY","AI_PRIVACY_ROLE_COPY","AI_PRIVACY_ADMIN_COPY","AI_PRIVACY_LOCKED_COPY","AI_PRIVACY_NOTHING_COPY","AI_PRIVACY_PASSWORD_COPY","AI_PRIVACY_MAX_PAGES","AI_PRIVACY_VISIBILITIES","VISIBILITY_VALUES","public","PUBLIC","unlisted","UNLISTED","members","AUTHENTICATED","VISIBILITY_LABELS","AI_PRIVACY_OUTPUTS","maintenance","id","label","where","search","pages","AI_PRIVACY_WHERE","AI_PRIVACY_ARGS_SCHEMA","type","properties","description","discourageSearchEngines","publicPages","items","maxLength","maxItems","unlistedPages","membersPages","additionalProperties","VISIBILITY_ARGS","flag","value","PAGE_ID","aiPrivacyRequestOf","inputs","problems","asked","Map","visibility","listed","entry","Array","isArray","page","trim","test","set","get","Set","add","visibilities","size","push","length","splice","request","aiPrivacyRequestEmpty","writeAiSitePrivacy","firestore","input","hostRef","collection","doc","hostId","screens","runTransaction","tx","host","exists","ok","error","uid","managesSite","pageDocs","Promise","all","map","one","done","notDone","hostUpdates","pageUpdates","delete","assigned","output","said","stored","forEach","index","name","String","contentGating","update","hadPassword","Object","keys","ref","updatedAt","now","extra","changedAny","outboxId","outboxRef","paths","entireHost","createdAt","serverTimestamp","attempts","aiPrivacyAccessRefusal","deps","onlyMaintenance","locked","lockdown","staff","org","data","intent","aiPrivacyOutputNote","did","join","not","slice","createAiJobPrivacyStep","write","dropCache","job","modelFor","model","unspent","failure","read","orgData","orgId","refused","createdBy","review","written","dropped","hostIds","reason","catch","complete","undefined","hostSubdomain","outputs","filter","key","some","resource","note","runAiJobPrivacyStep","createAiPrivacyJobAdmission","ownerOf","context","status","owner","aiPrivacyJobAdmission","registerAiPrivacyJob","minimumMs"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,YAAY,QAAQ,0CAAyC;AACtE,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,WAAW,EAAEC,gBAAgB,QAAQ,2CAA0C;AACxF,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,gBAAgB,QAAQ,sCAAqC;AACtE,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAASC,mBAAmB,QAAQ,gDAA+C;AAEnF,SAASC,kBAAkB,QAAQ,2CAA0C;AAC7E,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,UAAU,QAAwB,2BAA0B;AAErE,SAASC,sBAAsB,QAAyD,wBAAoB;AAC5G,SAASC,cAAc,QAAQ,wBAAoB;AACnD,SAASC,aAAa,EAAEC,gBAAgB,QAAQ,yBAAqB;AAErE,SAASC,iBAAiB,QAAQ,eAAW;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CC,GAED,OAAO,MAAMC,kBAAkB,UAAkB;AAEjD,qGAAqG,GACrG,OAAO,MAAMC,iCAAiC,KAAK;AAEnD,OAAO,MAAMC,0BAA0B,6CAA4C;AACnF,qEAAqE,GACrE,OAAO,MAAMC,uBAAuB,CAAC,yCAAyC,EAAElB,mBAAmB,aAAa,sDAAsD,CAAC,CAAA;AACvK,0EAA0E,GAC1E,OAAO,MAAMmB,wBAAwB,CAAC,8CAA8C,EAAEnB,mBAAmB,eAAe,sCAAsC,CAAC,CAAA;AAC/J,OAAO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AIvC,KAAKuC,QAAQvC,GAAG;YAAE3D,SAAS2E,KAAK3E,OAAO;QAAC,GACxE;YAAEyD,UAAUH,KAAKG,QAAQ;QAAC;QAE5B,OAAOqB,UAAU;YAAEqB,QAAQ;YAAKpF,OAAO+D;QAAQ,IAAI;IACrD;AACF;AAEA,OAAO,MAAMuB,wBAAwBL,8BAA6B;AAElE,wDAAwD,GACxD,OAAO,SAASM;IACdvK,kBAAkBC,iBAAiB+J,qBAAqB;QAAEQ,WAAWtK;IAA+B;IACpGN,uBAAuBK,iBAAiBqK;AAC1C"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-privacy-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 { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { holdsSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { orgPermissionLabel } from '@aglyn/aglyn/app-utils/org-permissions'\nimport {\n aiAddonName,\n checkEntitlement,\n ENTERPRISE_PLAN_LABEL,\n planLabelGrantingFeature,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { SCREEN_ROOT_PATH } from '@aglyn/aglyn/app-utils/screen-route'\nimport { HostScreenVisibility } from '@aglyn/aglyn/foundation/definitions/platform.types'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport type { PluginAiCapabilityArgsSchema } from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport { getLockdownVerdict } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldValue, type Firestore } from 'firebase-admin/firestore'\nimport type { AiJobOutput } from '../model/ai-jobs.types'\nimport { registerAiJobAdmission, type AiJobAdmission, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { aiJobEditModel } from './ai-job-edit-step'\nimport { aiLimitReview, aiUnspentOutcome } from './ai-job-generation'\nimport type { AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The `privacy` step (AGL-4033): who can see the site, as the console's own\n * three controls set it — maintenance mode (Admin → Error pages), the\n * Discourage search engines switch (Setup → SEO) and a page's Visibility\n * (its Page Access card) — as a first-class build operation, so \"make my site\n * private until launch\" or \"hide the pricing page\" is one item on Assist's\n * plan card. The docs page it mirrors is Site Protection → Make your site\n * private.\n *\n * NO MODEL. The planner already wrote the choices as the item's arguments;\n * this checks each against the rule the console's own control holds it to and\n * writes it, so it costs no credits.\n *\n * ── Only the controls' own fields ────────────────────────────────────────\n *\n * `maintenance` (true, or deleted on the way off, as the Error pages card\n * writes it), `seo.discourageSearchEngines` (likewise, as the Search engines\n * card does), and a page's `visibility` as Public, Unlisted or Members only.\n * Leaving password mode drops the page's stored hash, as the Page Access card\n * does, so protection never lingers on a page that no longer asks for it.\n *\n * NEVER: a page password. Setting one would put the password in the chat and\n * the plan, so it is not an argument; the note sends the person to the Page\n * Access card instead. Nor layouts, emails or record templates, which have no\n * Page Access card, nor the error pages themselves.\n *\n * ── Who may ──────────────────────────────────────────────────────────────\n *\n * Search indexing and page visibility: the Firestore rules' own for those\n * keys, a member with a write role on the site (admin, editor or author)\n * while no lockdown freezes it. Maintenance mode takes every page of the site\n * offline for every visitor, so, as the console keeps its card in the Admin\n * area, only a site ADMIN may change it here. A non-admin's request still\n * makes the rest of its changes and says why that one was not made.\n *\n * Members only is made only where the plan has content gating (Business and\n * above): the tenant serves gated pages nowhere else, so on a lower plan the\n * write would close the page to everyone, and the note says why it was not.\n *\n * ── Live on confirm, idempotent ──────────────────────────────────────────\n *\n * As the `settings` and `tracking` steps: none of these has a draft, so the\n * plan card's confirm is the agreement and the write is live. One transaction\n * re-reads the host and each page, re-checks the role, writes only what\n * differs, and queues a site-wide publish outbox entry, because visibility\n * changes navigation and the sitemap and both switches change every page.\n */\n\nexport const AI_PRIVACY_KIND = 'privacy' as const\n\n/** ASSUMED: the least time the step needs — the site, the org, the pages named and one transaction. */\nexport const AI_JOB_PRIVACY_STEP_MINIMUM_MS = 5_000\n\nexport const AI_PRIVACY_NO_SITE_COPY = 'Open the site whose privacy should change.'\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const AI_PRIVACY_ROLE_COPY = `Changing who can see the site needs the \"${orgPermissionLabel('site.edit')}\" permission on this site — ask an organization admin.`\n/** Names \"Manage site settings\" (`site.manage`, AGL-4047), never a role. */\nexport const AI_PRIVACY_ADMIN_COPY = `Turning maintenance mode on or off needs the \"${orgPermissionLabel('site.manage')}\" permission, so it was left as it is.`\nexport const AI_PRIVACY_LOCKED_COPY = 'This site is not accepting changes right now.'\nexport const AI_PRIVACY_NOTHING_COPY = 'The request named no privacy change this could make.'\nexport const AI_PRIVACY_PASSWORD_COPY =\n `To put a page behind a password, set it in that page’s Page Access card; ${aiAddonName()} never handles passwords.`\n\n/** The most pages one item may change. */\n/**\n * The cheapest plan with members-only pages (`contentGating`), read from\n * `PLAN_ENTITLEMENTS` so the copy can never name a retired plan (AGL-4158).\n */\nexport const AI_MEMBERS_ONLY_PLAN_LABEL =\n planLabelGrantingFeature('contentGating') ?? ENTERPRISE_PLAN_LABEL\n\nexport const AI_PRIVACY_MAX_PAGES = 20\n\n/** The visibilities a build may set, by the Page Access card's labels. */\nexport const AI_PRIVACY_VISIBILITIES = ['public', 'unlisted', 'members'] as const\nexport type AiPrivacyVisibility = (typeof AI_PRIVACY_VISIBILITIES)[number]\n\nconst VISIBILITY_VALUES: Readonly<Record<AiPrivacyVisibility, HostScreenVisibility>> = {\n public: HostScreenVisibility.PUBLIC,\n unlisted: HostScreenVisibility.UNLISTED,\n members: HostScreenVisibility.AUTHENTICATED,\n}\n\nconst VISIBILITY_LABELS: Readonly<Record<AiPrivacyVisibility, string>> = {\n public: 'Public',\n unlisted: 'Unlisted',\n members: 'Members only',\n}\n\n/** Where a person finds each change, as the output links and notes name it. */\nexport const AI_PRIVACY_OUTPUTS = {\n maintenance: { id: 'maintenance', label: 'Maintenance mode', where: 'Admin → Error pages' },\n search: { id: 'search', label: 'Search engines', where: 'Setup → SEO' },\n pages: { id: 'pages', label: 'Page access', where: 'each page’s Page Access card' },\n} as const\n\n/** Where the operation's changes are made, as the build's notes name it. */\nexport const AI_PRIVACY_WHERE = 'the site’s privacy settings'\n\n/** The item's arguments, as the planner fills them in. Every one optional. */\nexport const AI_PRIVACY_ARGS_SCHEMA: PluginAiCapabilityArgsSchema = {\n type: 'object',\n properties: {\n maintenance: {\n type: 'boolean',\n description:\n 'true takes the whole site offline: every address shows its 503 page to every visitor, including anyone with a link, until it is turned off. false brings the site back. Leave it out unless the person asked to take the whole site offline, keep it from everyone until launch, or bring it back.',\n },\n discourageSearchEngines: {\n type: 'boolean',\n description:\n 'true asks search engines not to index any page of the site (it stays open to anyone with a link); false lets them index it again. Leave it out unless the person asked about search engines or Google.',\n },\n publicPages: {\n type: 'array',\n description: 'Pages to make Public: anyone can open them, and they are offered to search engines. Each by its id from the site inventory.',\n items: { type: 'string', maxLength: 64 },\n maxItems: AI_PRIVACY_MAX_PAGES,\n },\n unlistedPages: {\n type: 'array',\n description: 'Pages to make Unlisted: anyone with the link can open them, kept out of search results, the sitemap and navigation. Each by its id from the site inventory.',\n items: { type: 'string', maxLength: 64 },\n maxItems: AI_PRIVACY_MAX_PAGES,\n },\n membersPages: {\n type: 'array',\n description: `Pages to make Members only: only visitors signed in to the site can open them (the ${AI_MEMBERS_ONLY_PLAN_LABEL} plan and above). Each by its id from the site inventory.`,\n items: { type: 'string', maxLength: 64 },\n maxItems: AI_PRIVACY_MAX_PAGES,\n },\n },\n additionalProperties: false,\n}\n\n/** Each visibility's argument, as the planner lists the pages for it. */\nconst VISIBILITY_ARGS: Readonly<Record<AiPrivacyVisibility, string>> = {\n public: 'publicPages',\n unlisted: 'unlistedPages',\n members: 'membersPages',\n}\n\n/** What an item asks: each switch to set, and each page's new visibility. */\nexport interface AiPrivacyRequest {\n maintenance: boolean | null\n discourageSearchEngines: boolean | null\n pages: { page: string; visibility: AiPrivacyVisibility }[]\n}\n\nexport interface AiPrivacyRead {\n request: AiPrivacyRequest\n /** A sentence per value that could not be used, so the rest still are. */\n problems: string[]\n}\n\nconst flag = (value: unknown): boolean | null => (typeof value === 'boolean' ? value : null)\n\n/** A page id as the site inventory gives it: one document id, never a path. */\nconst PAGE_ID = /^[A-Za-z0-9_-]{1,64}$/\n\n/** The item's arguments read: what may be written, and a sentence for each that may not. */\nexport function aiPrivacyRequestOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiPrivacyRead {\n const problems: string[] = []\n const pages: AiPrivacyRequest['pages'] = []\n const asked = new Map<string, Set<AiPrivacyVisibility>>()\n for (const visibility of AI_PRIVACY_VISIBILITIES) {\n const listed = inputs?.[VISIBILITY_ARGS[visibility]]\n for (const entry of Array.isArray(listed) ? listed : []) {\n const page = typeof entry === 'string' ? entry.trim() : ''\n if (PAGE_ID.test(page)) asked.set(page, (asked.get(page) ?? new Set()).add(visibility))\n }\n }\n for (const [page, visibilities] of asked) {\n // A page asked to be two things is left alone rather than guessed at.\n if (visibilities.size > 1) problems.push('A page was asked to be two things at once, so it was left as it is.')\n else pages.push({ page, visibility: [...visibilities][0] })\n }\n if (pages.length > AI_PRIVACY_MAX_PAGES) {\n pages.splice(AI_PRIVACY_MAX_PAGES)\n problems.push(`Only the first ${AI_PRIVACY_MAX_PAGES} pages were changed; ask again for the rest.`)\n }\n return {\n request: {\n maintenance: flag(inputs?.['maintenance']),\n discourageSearchEngines: flag(inputs?.['discourageSearchEngines']),\n pages,\n },\n problems,\n }\n}\n\n/** Whether a read request asks for anything at all. */\nexport function aiPrivacyRequestEmpty(request: AiPrivacyRequest): boolean {\n return request.maintenance === null && request.discourageSearchEngines === null && request.pages.length === 0\n}\n\n// ── The write ─────────────────────────────────────────────────────────────\n\nexport type AiPrivacyWrite =\n | {\n ok: true\n /** A sentence per change asked, made now or already so, by output id. */\n done: { output: keyof typeof AI_PRIVACY_OUTPUTS; said: string }[]\n /** A sentence per part that was not made, and why. */\n notDone: string[]\n changedAny: boolean\n outboxId: string | null\n }\n | { ok: false; error: string }\n\n/**\n * The changes written, in one transaction that reads the host and each named\n * page as they are stored NOW: the member still holds a write role (and is an\n * admin, for maintenance), each page exists and is a page, and only what\n * differs from what is stored is written, with a site-wide publish outbox\n * entry beside it so the live site's cached pages are dropped.\n */\nexport async function writeAiSitePrivacy(\n firestore: Firestore,\n input: { hostId: string; uid: string; request: AiPrivacyRequest; contentGating: boolean; now: Date },\n): Promise<AiPrivacyWrite> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const screens = hostRef.collection('screens')\n return firestore.runTransaction(async (tx): Promise<AiPrivacyWrite> => {\n const host = await tx.get(hostRef)\n if (!host.exists) return { ok: false, error: 'Unknown site' }\n if (!holdsSiteKey(host, input.uid, 'site.edit')) return { ok: false, error: AI_PRIVACY_ROLE_COPY }\n const managesSite = holdsSiteKey(host, input.uid, 'site.manage')\n const pageDocs = await Promise.all(input.request.pages.map((one) => tx.get(screens.doc(one.page))))\n\n const done: { output: keyof typeof AI_PRIVACY_OUTPUTS; said: string }[] = []\n const notDone: string[] = []\n const hostUpdates: Record<string, unknown> = {}\n const pageUpdates: { ref: FirebaseFirestore.DocumentReference; update: Record<string, unknown> }[] = []\n\n const { maintenance, discourageSearchEngines } = input.request\n if (maintenance !== null) {\n if (!managesSite) {\n notDone.push(AI_PRIVACY_ADMIN_COPY)\n } else {\n if ((host.get('maintenance') === true) !== maintenance) {\n hostUpdates['maintenance'] = maintenance || FieldValue.delete()\n }\n const assigned = !!(host.get('errorScreens') as Record<string, unknown> | undefined)?.['unavailable']\n done.push({\n output: 'maintenance',\n said: maintenance\n ? `Maintenance mode is on: every address shows ${assigned ? 'your 503 page' : `${PLATFORM_BRAND_NAME}’s plain “undergoing maintenance” notice, because no 503 page is assigned yet`} to every visitor.`\n : 'Maintenance mode is off: the site is open to visitors again.',\n })\n }\n }\n if (discourageSearchEngines !== null) {\n const stored = (host.get('seo') as Record<string, unknown> | undefined)?.['discourageSearchEngines'] === true\n if (stored !== discourageSearchEngines) {\n hostUpdates['seo.discourageSearchEngines'] = discourageSearchEngines || FieldValue.delete()\n }\n done.push({\n output: 'search',\n said: discourageSearchEngines\n ? 'Search engines are asked not to index this site. Anyone with a link can still open it.'\n : 'Search engines may index this site again. They take days to come back.',\n })\n }\n input.request.pages.forEach((asked, index) => {\n const page = pageDocs[index]\n if (!page.exists || page.get('deletedAt') != null || page.get('kind')) {\n notDone.push('A page named is not one of this site’s pages, so it was left out.')\n return\n }\n const name = String(page.get('displayName') ?? '').trim() || 'A page'\n if (asked.visibility === 'members' && !input.contentGating) {\n // The tenant serves gated pages only on plans with content gating, so\n // writing it here would close the page to everyone.\n notDone.push(`“${name}” was not made Members only: members-only pages need the ${AI_MEMBERS_ONLY_PLAN_LABEL} plan or above.`)\n return\n }\n const value = VISIBILITY_VALUES[asked.visibility]\n const update: Record<string, unknown> = {}\n if ((page.get('visibility') ?? HostScreenVisibility.PUBLIC) !== value) update['visibility'] = value\n const hadPassword = !!(page.get('protection') as Record<string, unknown> | undefined)?.['passwordHash']\n if (hadPassword) update['protection'] = FieldValue.delete()\n if (Object.keys(update).length) pageUpdates.push({ ref: page.ref, update: { ...update, updatedAt: input.now } })\n const extra = hadPassword ? ' Its page password was removed.' : ''\n done.push({ output: 'pages', said: `“${name}” is now ${VISIBILITY_LABELS[asked.visibility]}.${extra}` })\n })\n\n const changedAny = Object.keys(hostUpdates).length > 0 || pageUpdates.length > 0\n if (!changedAny) return { ok: true, done, notDone, changedAny, outboxId: null }\n if (Object.keys(hostUpdates).length) tx.update(hostRef, { ...hostUpdates, updatedAt: input.now })\n for (const { ref, update } of pageUpdates) tx.update(ref, update)\n // Both switches change every page, and a page's visibility changes the\n // navigation and the sitemap every other page carries.\n const outboxRef = firestore.collection('publishOutbox').doc(createResourceUid())\n tx.set(outboxRef, {\n hostId: input.hostId,\n paths: [SCREEN_ROOT_PATH],\n entireHost: true,\n createdAt: FieldValue.serverTimestamp(),\n attempts: 0,\n })\n return { ok: true, done, notDone, changedAny, outboxId: outboxRef.id }\n })\n}\n\n// ── The step ──────────────────────────────────────────────────────────────\n\n/** Why this member may not change who can see this site now, or `null`. */\nexport async function aiPrivacyAccessRefusal(\n input: { host: FirebaseFirestore.DocumentSnapshot; uid: string; org: object | null; request: AiPrivacyRequest },\n deps: { lockdown?: typeof getLockdownVerdict } = {},\n): Promise<string | null> {\n if (!input.host.exists) return 'Unknown site'\n if (!holdsSiteKey(input.host, input.uid, 'site.edit')) return AI_PRIVACY_ROLE_COPY\n // A request that is ONLY maintenance has nothing a non-admin may make.\n const onlyMaintenance =\n input.request.maintenance !== null && input.request.discourageSearchEngines === null && !input.request.pages.length\n if (onlyMaintenance && !holdsSiteKey(input.host, input.uid, 'site.manage')) return AI_PRIVACY_ADMIN_COPY\n const locked = await (deps.lockdown ?? getLockdownVerdict)({\n staff: false,\n uid: input.uid,\n org: input.org as never,\n host: input.host.data() as never,\n intent: 'write',\n })\n return locked ? AI_PRIVACY_LOCKED_COPY : null\n}\n\n/** One output's note: what changed, that it is live, and what was not done. */\nexport function aiPrivacyOutputNote(said: readonly string[], where: string, notDone: readonly string[], changedAny: boolean): string {\n const did = said.length\n ? `${said.join(' ')} Live now, in ${where}.${changedAny ? '' : ' It already was, so nothing was written.'}`\n : 'Nothing needed changing.'\n const not = notDone.length ? ` Not done: ${notDone.join(' ')}` : ''\n return `${did}${not}`.slice(0, 1_000)\n}\n\nexport interface AiJobPrivacyStepDeps {\n write?: typeof writeAiSitePrivacy\n lockdown?: typeof getLockdownVerdict\n dropCache?: typeof dropPluginSiteCache\n}\n\nexport function createAiJobPrivacyStep(deps: AiJobPrivacyStepDeps = {}): AiJobStepRunner {\n const write = deps.write ?? writeAiSitePrivacy\n const dropCache = deps.dropCache ?? dropPluginSiteCache\n return async ({ job, now, firestore, org, modelFor }): Promise<AiJobStepOutcome> => {\n // No model is asked: the outcome records the edit step's at no cost.\n const model = modelFor?.('job.edit') ?? aiJobEditModel()\n const unspent = (failure: string): AiJobStepOutcome => ({ ...aiUnspentOutcome(model), failure })\n const hostId = job.hostId\n if (!hostId) return unspent(AI_PRIVACY_NO_SITE_COPY)\n const read = aiPrivacyRequestOf(job.inputs)\n if (aiPrivacyRequestEmpty(read.request)) return unspent([AI_PRIVACY_NOTHING_COPY, ...read.problems].join(' '))\n const orgData = (org ?? ((await firestore.collection('orgs').doc(job.orgId).get()).data() ?? null)) as Record<string, unknown> | null\n const host = await firestore.collection('hosts').doc(hostId).get()\n const refused = await aiPrivacyAccessRefusal({ host, uid: job.createdBy, org: orgData, request: read.request }, { lockdown: deps.lockdown })\n if (refused) return aiUnspentOutcome(model, { review: aiLimitReview(refused) })\n const written = await write(firestore, {\n hostId,\n uid: job.createdBy,\n request: read.request,\n contentGating: checkEntitlement(orgData as never, 'contentGating'),\n now,\n })\n if (written.ok === false) return unspent(written.error)\n if (written.outboxId) {\n // The live site's cached pages go now; the outbox entry stays for the\n // drain unless the drop certainly happened.\n const dropped = await dropCache({ hostIds: [hostId], reason: 'AI build changed site privacy' }).catch(() => ({ complete: false }))\n if (dropped.complete) await firestore.collection('publishOutbox').doc(written.outboxId).delete().catch(() => undefined)\n }\n const notDone = [...read.problems, ...written.notDone]\n const hostSubdomain = (typeof host.get('subdomain') === 'string' && host.get('subdomain')) || null\n const outputs: AiJobOutput[] = (Object.keys(AI_PRIVACY_OUTPUTS) as (keyof typeof AI_PRIVACY_OUTPUTS)[])\n .filter((key) => written.done.some((one) => one.output === key))\n .map((key, index) => ({\n resource: 'privacy',\n id: AI_PRIVACY_OUTPUTS[key].id,\n hostId,\n hostSubdomain,\n label: AI_PRIVACY_OUTPUTS[key].label,\n note: aiPrivacyOutputNote(\n written.done.filter((one) => one.output === key).map((one) => one.said),\n AI_PRIVACY_OUTPUTS[key].where,\n // What was not done is said once, on the first output.\n index === 0 ? notDone : [],\n written.changedAny,\n ),\n }))\n if (!outputs.length) return unspent([AI_PRIVACY_NOTHING_COPY, ...notDone].join(' '))\n return aiUnspentOutcome(model, { outputs })\n }\n}\n\nexport const runAiJobPrivacyStep = createAiJobPrivacyStep()\n\n// ── Admission ─────────────────────────────────────────────────────────────\n\nexport interface AiPrivacyJobAdmissionDeps {\n ownerOf?: typeof resolveOrgIdForHost\n lockdown?: typeof getLockdownVerdict\n}\n\n/**\n * A privacy change is admitted on a site of the job's own org, for a member\n * who may write it now, where the request names at least one change this can\n * make. Refused in those words before anything is written.\n */\nexport function createAiPrivacyJobAdmission(deps: AiPrivacyJobAdmissionDeps = {}): AiJobAdmission {\n const ownerOf = deps.ownerOf ?? resolveOrgIdForHost\n return async (context): Promise<AiJobAdmissionRefusal | null> => {\n if (!context.hostId) return { status: 400, error: AI_PRIVACY_NO_SITE_COPY }\n const owner = await ownerOf(context.hostId)\n if (!owner || owner !== context.orgId) return { status: 404, error: 'Unknown site' }\n const read = aiPrivacyRequestOf(context.inputs as Record<string, unknown>)\n if (aiPrivacyRequestEmpty(read.request)) return { status: 400, error: [AI_PRIVACY_NOTHING_COPY, ...read.problems].join(' ') }\n const host = await context.firestore.collection('hosts').doc(context.hostId).get()\n const refused = await aiPrivacyAccessRefusal(\n { host, uid: context.uid ?? '', org: context.org, request: read.request },\n { lockdown: deps.lockdown },\n )\n return refused ? { status: 403, error: refused } : null\n }\n}\n\nexport const aiPrivacyJobAdmission = createAiPrivacyJobAdmission()\n\n/** Registers the privacy step and its door (AGL-4033). */\nexport function registerAiPrivacyJob(): void {\n registerAiJobStep(AI_PRIVACY_KIND, runAiJobPrivacyStep, { minimumMs: AI_JOB_PRIVACY_STEP_MINIMUM_MS })\n registerAiJobAdmission(AI_PRIVACY_KIND, aiPrivacyJobAdmission)\n}\n"],"names":["planLabelGrantingFeature","createResourceUid","holdsSiteKey","orgPermissionLabel","aiAddonName","checkEntitlement","ENTERPRISE_PLAN_LABEL","PLATFORM_BRAND_NAME","SCREEN_ROOT_PATH","HostScreenVisibility","dropPluginSiteCache","getLockdownVerdict","resolveOrgIdForHost","FieldValue","registerAiJobAdmission","aiJobEditModel","aiLimitReview","aiUnspentOutcome","registerAiJobStep","AI_PRIVACY_KIND","AI_JOB_PRIVACY_STEP_MINIMUM_MS","AI_PRIVACY_NO_SITE_COPY","AI_PRIVACY_ROLE_COPY","AI_PRIVACY_ADMIN_COPY","AI_PRIVACY_LOCKED_COPY","AI_PRIVACY_NOTHING_COPY","AI_PRIVACY_PASSWORD_COPY","AI_MEMBERS_ONLY_PLAN_LABEL","AI_PRIVACY_MAX_PAGES","AI_PRIVACY_VISIBILITIES","VISIBILITY_VALUES","public","PUBLIC","unlisted","UNLISTED","members","AUTHENTICATED","VISIBILITY_LABELS","AI_PRIVACY_OUTPUTS","maintenance","id","label","where","search","pages","AI_PRIVACY_WHERE","AI_PRIVACY_ARGS_SCHEMA","type","properties","description","discourageSearchEngines","publicPages","items","maxLength","maxItems","unlistedPages","membersPages","additionalProperties","VISIBILITY_ARGS","flag","value","PAGE_ID","aiPrivacyRequestOf","inputs","problems","asked","Map","visibility","listed","entry","Array","isArray","page","trim","test","set","get","Set","add","visibilities","size","push","length","splice","request","aiPrivacyRequestEmpty","writeAiSitePrivacy","firestore","input","hostRef","collection","doc","hostId","screens","runTransaction","tx","host","exists","ok","error","uid","managesSite","pageDocs","Promise","all","map","one","done","notDone","hostUpdates","pageUpdates","delete","assigned","output","said","stored","forEach","index","name","String","contentGating","update","hadPassword","Object","keys","ref","updatedAt","now","extra","changedAny","outboxId","outboxRef","paths","entireHost","createdAt","serverTimestamp","attempts","aiPrivacyAccessRefusal","deps","onlyMaintenance","locked","lockdown","staff","org","data","intent","aiPrivacyOutputNote","did","join","not","slice","createAiJobPrivacyStep","write","dropCache","job","modelFor","model","unspent","failure","read","orgData","orgId","refused","createdBy","review","written","dropped","hostIds","reason","catch","complete","undefined","hostSubdomain","outputs","filter","key","some","resource","note","runAiJobPrivacyStep","createAiPrivacyJobAdmission","ownerOf","context","status","owner","aiPrivacyJobAdmission","registerAiPrivacyJob","minimumMs"],"mappings":";IA8GEA;AA9GF;;;;;;;;;;;;;;;CAeC,GAED,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,YAAY,QAAQ,0CAAyC;AACtE,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SACEC,WAAW,EACXC,gBAAgB,EAChBC,qBAAqB,EACrBN,wBAAwB,QACnB,2CAA0C;AACjD,SAASO,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,gBAAgB,QAAQ,sCAAqC;AACtE,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAASC,mBAAmB,QAAQ,gDAA+C;AAEnF,SAASC,kBAAkB,QAAQ,2CAA0C;AAC7E,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,UAAU,QAAwB,2BAA0B;AAErE,SAASC,sBAAsB,QAAyD,wBAAoB;AAC5G,SAASC,cAAc,QAAQ,wBAAoB;AACnD,SAASC,aAAa,EAAEC,gBAAgB,QAAQ,yBAAqB;AAErE,SAASC,iBAAiB,QAAQ,eAAW;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CC,GAED,OAAO,MAAMC,kBAAkB,UAAkB;AAEjD,qGAAqG,GACrG,OAAO,MAAMC,iCAAiC,KAAK;AAEnD,OAAO,MAAMC,0BAA0B,6CAA4C;AACnF,qEAAqE,GACrE,OAAO,MAAMC,uBAA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AAK3E,OAAO,GAAG,OAAO;YAAEmG,QAAQ;YAAKpF,OAAO;gBAAC1E;mBAA4BsI,KAAK/F,QAAQ;aAAC,CAACoF,IAAI,CAAC;QAAK;QAC5H,MAAMpD,OAAO,MAAMsF,QAAQ/F,SAAS,CAACG,UAAU,CAAC,SAASC,GAAG,CAAC2F,QAAQ1F,MAAM,EAAEhB,GAAG;QAChF,MAAMsF,UAAU,MAAMzB,uBACpB;YAAEzC;YAAMI,GAAG,GAAEkF,eAAAA,QAAQlF,GAAG,YAAXkF,eAAe;YAAIvC,KAAKuC,QAAQvC,GAAG;YAAE3D,SAAS2E,KAAK3E,OAAO;QAAC,GACxE;YAAEyD,UAAUH,KAAKG,QAAQ;QAAC;QAE5B,OAAOqB,UAAU;YAAEqB,QAAQ;YAAKpF,OAAO+D;QAAQ,IAAI;IACrD;AACF;AAEA,OAAO,MAAMuB,wBAAwBL,8BAA6B;AAElE,wDAAwD,GACxD,OAAO,SAASM;IACdxK,kBAAkBC,iBAAiBgK,qBAAqB;QAAEQ,WAAWvK;IAA+B;IACpGN,uBAAuBK,iBAAiBsK;AAC1C"}
|
|
@@ -19,7 +19,7 @@ import type { AiJob, AiJobOutput, AiJobPlan, AiJobReview, AiJobInputRequest, AiJ
|
|
|
19
19
|
import { type AiStepKind } from '../providers/catalog';
|
|
20
20
|
import { type AiEffort, type AiSystemBlock } from '../runtime/ai-runtime';
|
|
21
21
|
import type { AssistTokenUsage } from '../usage/assist-usage';
|
|
22
|
-
import type { AiSiteImportState } from '../model/ai-site-import';
|
|
22
|
+
import type { AiSiteImportState, AiSiteImportWords } from '../model/ai-site-import';
|
|
23
23
|
import type { AiSitePhotos } from '../model/ai-site-photos';
|
|
24
24
|
/**
|
|
25
25
|
* The `text` step (AGL-2904): a brief in, a short piece of copy out.
|
|
@@ -137,6 +137,12 @@ export interface AiJobStepOutcome {
|
|
|
137
137
|
* job document itself.
|
|
138
138
|
*/
|
|
139
139
|
siteImport?: AiSiteImportState;
|
|
140
|
+
/**
|
|
141
|
+
* How the words of a page brought in under Also improve my wording came
|
|
142
|
+
* out on this pass (AGL-4152): `kept` where its rewrite was refused, which
|
|
143
|
+
* the import step writes onto the page's row so it reads as kept.
|
|
144
|
+
*/
|
|
145
|
+
wording?: AiSiteImportWords;
|
|
140
146
|
/**
|
|
141
147
|
* A `site` job's pictures left on a starter photo after this pass
|
|
142
148
|
* (AGL-3988), whole: what its late photo pass fills before the site is
|
|
@@ -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 AiJobInputRequest,\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 type { AiSiteImportState } from '../model/ai-site-import'\nimport type { AiSitePhotos } from '../model/ai-site-photos'\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 * With a `plan` review: the plan needs an answer only the person can give\n * first (AGL-3978) — a tracking change with no pixel ID. The machine keeps\n * the plan and its review and parks the job `needs_input` with these\n * fields instead of `needs_review`; the answer returns it to the review.\n */\n input?: AiJobInputRequest\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 * An `import` job's waves after this pass (AGL-3976), kept on the job by\n * the machine in the write that records the pass: a step never writes the\n * job document itself.\n */\n siteImport?: AiSiteImportState\n /**\n * A `site` job's pictures left on a starter photo after this pass\n * (AGL-3988), whole: what its late photo pass fills before the site is\n * published. A page's or a dataset's pass reports its own; the site step\n * merges them and the machine keeps the result on the job.\n */\n sitePhotos?: AiSitePhotos\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 // AGL-4092: never a bracketed placeholder, which a page shows as written.\n 'the brief did not give you; where a detail is missing, leave it out ' +\n 'and write the sentence without it.',\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;AAcD,SAASA,aAAa,QAAyB,0BAAsB;AACrE,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SAASC,cAAc,QAAQ,2BAAuB;AACtD,SAASC,YAAY,QAA2C,2BAAuB;AAIvF,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,4DAA4D,GAC5D,OAAO,MAAMO,yBAAyBR,gBAAgB,CAAC,WAAW,CAACS,SAAS,CAAA;AAE5E;;;;;;;CAOC,GACD,OAAO,MAAMC,0BAA0BN,gBAAgB;IACrDO,MAAMZ,aAAa,CAAC,WAAW;IAC/BU,WAAWD;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MG,UAAShC,kBAAAA,eAAe,uBAAfA,kBAA8BF,gBAAgB,CAAC,WAAW,CAACkC,MAAM;IAChF,MAAMC,SAAS,MAAMhC,aAAa;QAChC8B;QACAG,QAAQnB;QACRoB,UAAU;YAAC;gBAAEC,MAAM;gBAAQC,SAASnB,gBAAgBC;YAAK;SAAE;QAC3D,0EAA0E;QAC1E,kCAAkC;QAClCZ,WAAWC,wBAAwBD,SAAS,CAACwB;OACzCjC,gBAAgB,CAAC,WAAW,CAACwC,QAAQ,GAAG;QAAEA,UAAUxC,gBAAgB,CAAC,WAAW,CAACwC,QAAQ;IAAC,IAAI,CAAC,GAC/FN,SAAS;QAAEA;IAAO,IAAI,CAAC;QAC3BO,QAAQ;OACJV,SAAS;QAAEA;IAAO,IAAI,CAAC;IAE7B,IAAII,OAAOO,IAAI,KAAK,WAAW;QAC7B,OAAO;YACLC,SAAS,EAAE;YACXC,OAAOT,OAAOS,KAAK;YACnBC,YAAYV,OAAOU,UAAU;YAC7BZ;YACAa,YAAYX,OAAOW,UAAU;YAC7BC,SAAS;QACX;IACF;IACA,MAAM7B,OAAOiB,OAAOjB,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,OAAOT,OAAOS,KAAK;QACnBC,YAAYV,OAAOU,UAAU;QAC7BZ;QACAa,YAAYX,OAAOW,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 AiJobInputRequest,\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 type { AiSiteImportState, AiSiteImportWords } from '../model/ai-site-import'\nimport type { AiSitePhotos } from '../model/ai-site-photos'\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 * With a `plan` review: the plan needs an answer only the person can give\n * first (AGL-3978) — a tracking change with no pixel ID. The machine keeps\n * the plan and its review and parks the job `needs_input` with these\n * fields instead of `needs_review`; the answer returns it to the review.\n */\n input?: AiJobInputRequest\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 * An `import` job's waves after this pass (AGL-3976), kept on the job by\n * the machine in the write that records the pass: a step never writes the\n * job document itself.\n */\n siteImport?: AiSiteImportState\n /**\n * How the words of a page brought in under Also improve my wording came\n * out on this pass (AGL-4152): `kept` where its rewrite was refused, which\n * the import step writes onto the page's row so it reads as kept.\n */\n wording?: AiSiteImportWords\n /**\n * A `site` job's pictures left on a starter photo after this pass\n * (AGL-3988), whole: what its late photo pass fills before the site is\n * published. A page's or a dataset's pass reports its own; the site step\n * merges them and the machine keeps the result on the job.\n */\n sitePhotos?: AiSitePhotos\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 // AGL-4092: never a bracketed placeholder, which a page shows as written.\n 'the brief did not give you; where a detail is missing, leave it out ' +\n 'and write the sentence without it.',\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;AAcD,SAASA,aAAa,QAAyB,0BAAsB;AACrE,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SAASC,cAAc,QAAQ,2BAAuB;AACtD,SAASC,YAAY,QAA2C,2BAAuB;AAIvF,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,4DAA4D,GAC5D,OAAO,MAAMO,yBAAyBR,gBAAgB,CAAC,WAAW,CAACS,SAAS,CAAA;AAE5E;;;;;;;CAOC,GACD,OAAO,MAAMC,0BAA0BN,gBAAgB;IACrDO,MAAMZ,aAAa,CAAC,WAAW;IAC/BU,WAAWD;IACXI,UAAU;IACVC,SAAS;AACX,GAAE;AAEF,yDAAyD,GACzD,OAAO,MAAMC,8BAA8BJ,wBAAwBK,SAAS,CAAA;AAE5E,+EAA+E,GAC/E,OAAO,MAAMC,yBAAyB,KAAK;AA6I3C;;;CAGC,GACD,OAAO,MAAMC,qBAAsC;IACjD;QACEC,MACE,sEACA,sEACA,yEACA,0EACA,wEACA,wEACA,0EAA0E;QAC1E,yEACA;QACFC,iBAAiB;IACnB;CACD,CAAA;AAED,8EAA8E,GAC9E,OAAO,SAASC,gBAAgBC,GAAoC;QAE9CA,aAEXA;IAHT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Q;IAAC,IAAI,CAAC,GAC/FN,SAAS;QAAEA;IAAO,IAAI,CAAC;QAC3BO,QAAQ;OACJV,SAAS;QAAEA;IAAO,IAAI,CAAC;IAE7B,IAAII,OAAOO,IAAI,KAAK,WAAW;QAC7B,OAAO;YACLC,SAAS,EAAE;YACXC,OAAOT,OAAOS,KAAK;YACnBC,YAAYV,OAAOU,UAAU;YAC7BZ;YACAa,YAAYX,OAAOW,UAAU;YAC7BC,SAAS;QACX;IACF;IACA,MAAM7B,OAAOiB,OAAOjB,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,OAAOT,OAAOS,KAAK;QACnBC,YAAYV,OAAOU,UAAU;QAC7BZ;QACAa,YAAYX,OAAOW,UAAU;IAC/B;AACF,EAAC"}
|
|
@@ -16,9 +16,9 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import { type AiLayoutCompiledPage, type AiLayoutPagePlan } from '../layout-language/ai-layout-compiler';
|
|
18
18
|
import type { AiLayoutDesign } from '../layout-language/ai-layout-design';
|
|
19
|
-
import { type AiLayoutColorRole, type AiLayoutDesignAnswer, type AiLayoutSection, type AiLayoutSettlement } from '../layout-language/ai-layout-language';
|
|
19
|
+
import { type AiLayoutColorRole, type AiLayoutDesignAnswer, type AiLayoutSection, type AiLayoutSettlement, type AiLayoutWidth } from '../layout-language/ai-layout-language';
|
|
20
20
|
import type { AiLayoutTargets } from '../layout-language/ai-layout-links';
|
|
21
|
-
import { type SiteImportIconShape, type SiteImportLayout, type SiteImportLookFacts } from '../model/ai-site-import';
|
|
21
|
+
import { type SiteImportIconShape, type SiteImportLayout, type SiteImportLayoutSection, type SiteImportLookFacts, type AiSiteImportFinish } from '../model/ai-site-import';
|
|
22
22
|
import { type AiSiteImportDocument } from './ai-site-import-document';
|
|
23
23
|
/**
|
|
24
24
|
* The model a page brought in asks its design answer on (AGL-4107): the page
|
|
@@ -96,6 +96,14 @@ export declare function aiSiteImportIconPath(shape: SiteImportIconShape | undefi
|
|
|
96
96
|
* band take the band's own.
|
|
97
97
|
*/
|
|
98
98
|
export declare function aiSiteImportColorRole(hex: string | null | undefined, look: Pick<SiteImportLookFacts, 'buttonFill' | 'link'> | null | undefined, use: 'ink' | 'fill' | 'rule'): AiLayoutColorRole | null;
|
|
99
|
+
/** How a page is finished (AGL-4152): the finish asked of it, else its document's, else kept as it is. */
|
|
100
|
+
export declare function aiSiteImportFinishOf(doc: Pick<AiSiteImportDocument, 'finish'> | null | undefined, asked?: AiSiteImportFinish | null): AiSiteImportFinish;
|
|
101
|
+
/**
|
|
102
|
+
* The Container width a source holds its opening's heading to (AGL-4152):
|
|
103
|
+
* the theme's breakpoint nearest its measure, at most a page's own, which an
|
|
104
|
+
* opening's words may span; none where the source sets none.
|
|
105
|
+
*/
|
|
106
|
+
export declare function aiSiteImportHeroMeasure(section: Pick<SiteImportLayoutSection, 'hero'>): Exclude<AiLayoutWidth, 'xl'> | null;
|
|
99
107
|
export interface AiSiteImportDesigned {
|
|
100
108
|
sections: AiLayoutSection[];
|
|
101
109
|
/** Lines taken into a block, by index of the page's blocks. */
|
|
@@ -113,6 +121,7 @@ export interface AiSiteImportDesigned {
|
|
|
113
121
|
*/
|
|
114
122
|
export declare function aiSiteImportDesignedSections(doc: AiSiteImportDocument, answer?: AiLayoutDesignAnswer | null, options?: {
|
|
115
123
|
formId?: string | null;
|
|
124
|
+
finish?: AiSiteImportFinish | null;
|
|
116
125
|
}): AiSiteImportDesigned;
|
|
117
126
|
export interface AiSiteImportCompileInput {
|
|
118
127
|
doc: AiSiteImportDocument;
|
|
@@ -126,6 +135,8 @@ export interface AiSiteImportCompileInput {
|
|
|
126
135
|
language?: string;
|
|
127
136
|
/** The page's design answer, for a main page; absent, the page is drawn as its source lays it out. */
|
|
128
137
|
answer?: AiLayoutDesignAnswer | null;
|
|
138
|
+
/** How the page is finished (AGL-4152); absent is `keep`. */
|
|
139
|
+
finish?: AiSiteImportFinish | null;
|
|
129
140
|
}
|
|
130
141
|
export interface AiSiteImportCompiled extends Pick<AiLayoutCompiledPage, 'tree' | 'sectionRoots' | 'videoIds'> {
|
|
131
142
|
sections: AiLayoutSection[];
|