@aglyn/plugins-ai 1.9.1 → 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/server/ai-allotments.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 { pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport {\n assistCreditsFromUsd,\n resolveAssistCreditBudget,\n} from '../usage/assist-credits'\nimport { hostRoleFor, isOrgWideMember } from '@aglyn/aglyn/app-utils/organizations'\nimport { resolveSiteRolePresetPermissions } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { logAiAllotmentChanged } from '../activity/ai-activity'\nimport {\n AI_ALLOTMENT_MAX_CREDITS,\n AI_ALLOTMENT_MAX_MODELS,\n aiAllotmentCredits,\n parseAiAllotmentSubject,\n type AiAllotment,\n type AiAllotmentMode,\n type AiAllotmentSubject,\n} from '../model/ai-allotments'\nimport { aiUsageByUserMonthFrom, aiUsageMonthKeys } from '../model/ai-usage-by-user'\nimport { AI_MODEL_CATALOG } from '../providers/catalog'\nimport { AI_MODEL_RESTRICTION_PLANS } from '../providers/model-choice'\nimport { resolveAiProvider } from '../providers/routing'\nimport {\n AI_HOST_CREDITS_FIELD,\n applyAiAllotmentWrites,\n listAiAllotments,\n seedAiHostMonthCredits,\n type AiAllotmentWrite,\n} from '../usage/ai-allotments'\nimport { userAiUsageMonthRef } from '../usage/ai-usage-by-user'\nimport {\n ASSIST_RETURNED_USD_FIELD,\n assistSpendAfterReturnsUsd,\n} from '../usage/assist-credit-returns'\nimport type {\n AiAllotmentRowWire,\n AiAllotmentsHostWire,\n AiAllotmentsMemberWire,\n AiAllotmentsWire,\n} from '../usage/ai-usage-wire'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\n\n// lockdown-423: exempt — a spend control, the posture of ai/billing/overage\n// beside it: a billing-locked workspace must still be able to LOWER what its\n// people may spend, and a 423 would trap it spending.\n\n/**\n * AI ALLOTMENTS (AGL-2942) — read and set them.\n *\n * ## Who may read\n *\n * - The whole org's allotments (`orgId`): `billing.view`, the Usage page's\n * gate — every allotment is a figure about the pool it is part of.\n * - One site's (`hostId`): the same, or the site's admin when they are a\n * collaborator scoped to it — the collaborators card is theirs.\n * - One person's (`uid`): the same, or the person themselves.\n *\n * ## Who may write\n *\n * - A member's, a site's and the org-wide model restriction:\n * `billing.manage`. Each moves how much of the paid pool someone may\n * spend.\n * - A collaborator's on one site: `billing.manage`, or the admin of that\n * site when they are a collaborator scoped to it — never on their own\n * allotment, which they could otherwise raise.\n *\n * Staff pass, as at the other org routes. The org-wide restriction is set\n * only on a plan that offers it (`AI_MODEL_RESTRICTION_PLANS`); clearing it\n * is always allowed.\n *\n * ## One write, many subjects\n *\n * `POST { orgId, set, remove, everySite }`: `set` replaces allotments,\n * `remove` deletes them, and `everySite` sets the same allotment on every\n * site the org has — \"same for every client site\" — expanded here, from the\n * org's sites, rather than trusted from a client's list.\n */\n\nconst json = (body: unknown, status: number) => Response.json(body, { status })\n\n/** Batch writes a request may make; Firestore commits at most 500. */\nconst MAX_WRITES = 450\n\n/** Sites one `everySite` expands to. */\nconst MAX_SITES = 400\n\n/** Member months one `getAll` carries. */\nconst GET_ALL_CHUNK = 100\n\ninterface Caller {\n uid: string\n email: string | null\n staff: boolean\n member: AglynOrgMember | null\n}\n\nasync function authenticate(\n headers: Partial<Record<string, string>>,\n): Promise<Response | { decoded: { uid: string; email?: string; staff: boolean } }> {\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return json({ error: 'Unauthenticated' }, 401)\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n return { decoded: { uid: decoded.uid, email: decoded.email, staff: decoded['staff'] === true } }\n}\n\n/**\n * A collaborator scoped to the site who holds \"Manage site settings\" there\n * (`site.manage`, AGL-4047): their site role's preset (Admin), then the\n * site's toggle for them.\n */\nfunction isSiteAdminCollaborator(member: AglynOrgMember | null, hostId: string): boolean {\n if (!member || !hostId || isOrgWideMember(member)) return false\n return resolveSiteRolePresetPermissions(member, hostId)['site.manage'] === true\n}\n\ninterface RosterMonth {\n member: AglynOrgMember\n credits: number\n byHost: Record<string, number>\n}\n\n/** The roster and each member's month, by path — no index, one getAll a hundred. */\nasync function readRosterMonths(\n firestore: FirebaseFirestore.Firestore,\n orgRef: FirebaseFirestore.DocumentReference,\n month: string,\n): Promise<RosterMonth[]> {\n const roster = await orgRef.collection('members').get()\n const members = roster.docs.map(\n (doc) => ({ $id: doc.id, ...doc.data() }) as AglynOrgMember,\n )\n const out: RosterMonth[] = []\n for (let start = 0; start < members.length; start += GET_ALL_CHUNK) {\n const chunk = members.slice(start, start + GET_ALL_CHUNK)\n const snapshots = chunk.length\n ? await firestore.getAll(\n ...chunk.map((member) => userAiUsageMonthRef(orgRef, member.$id, month)),\n )\n : []\n snapshots.forEach((snapshot, index) => {\n const member = chunk[index]\n const usage = aiUsageByUserMonthFrom(\n snapshot.exists ? (snapshot.data() as Record<string, unknown>) : null,\n member.$id,\n month,\n )\n out.push({ member, credits: usage.credits, byHost: usage.byHost })\n })\n }\n return out\n}\n\nconst memberName = (member: AglynOrgMember): string =>\n String(member.displayName ?? '').trim() || String(member.email ?? '').trim() || member.$id\n\n/** A site's credits this month: the org map, else its people's months summed. */\nfunction siteCredits(\n orgMonth: FirebaseFirestore.DocumentSnapshot,\n roster: readonly RosterMonth[],\n hostId: string,\n): number {\n const map = (orgMonth.exists ? orgMonth.get(AI_HOST_CREDITS_FIELD) : null) as\n | Record<string, unknown>\n | null\n if (map && map[hostId] !== undefined) {\n const value = Number(map[hostId])\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0\n }\n return roster.reduce((sum, entry) => sum + (entry.byHost[hostId] ?? 0), 0)\n}\n\nasync function handleGet(request: Request): Promise<Response> {\n const { query, headers } = await pluginRequestFromWeb(request)\n const params = (query ?? {}) as Record<string, unknown>\n const hostId = String(params['hostId'] ?? '').trim()\n const subjectUid = String(params['uid'] ?? '').trim()\n const auth = await authenticate(headers as Partial<Record<string, string>>)\n if (auth instanceof Response) return auth\n const { decoded } = auth\n const orgId =\n String(params['orgId'] ?? '').trim() || (hostId ? ((await resolveOrgIdForHost(hostId)) ?? '') : '')\n if (!orgId) return json({ error: 'Missing orgId' }, 400)\n\n const membership = await resolveOrgMembership(decoded.uid, orgId)\n const member = membership?.member ?? null\n if (!member && !decoded.staff) return json({ error: 'Not found' }, 404)\n const canManage =\n decoded.staff || (await memberHasOrgPermission(orgId, member, 'billing.manage'))\n const canView =\n canManage || (await memberHasOrgPermission(orgId, member, 'billing.view'))\n const siteAdmin = isSiteAdminCollaborator(member, hostId)\n const allowed = subjectUid\n ? canView || subjectUid === decoded.uid || siteAdmin\n : hostId\n ? canView || siteAdmin\n : canView\n if (!allowed) return json({ error: 'billing.view required' }, 403)\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const month = aiUsageMonthKeys()[0]\n const [orgSnapshot, orgMonth, allotments, roster, hostDocs] = await Promise.all([\n orgRef.get(),\n orgRef.collection('assistUsage').doc(month).get(),\n listAiAllotments(firestore, orgId, subjectUid ? { uid: subjectUid } : hostId ? { hostId } : {}),\n readRosterMonths(firestore, orgRef, month),\n hostId\n ? firestore.collection('hosts').doc(hostId).get().then((doc) => (doc.exists ? [doc] : []))\n : firestore.collection('hosts').where('orgId', '==', orgId).limit(MAX_SITES).get().then((snapshot) => snapshot.docs),\n ])\n const org = (orgSnapshot.data() ?? {}) as Record<string, unknown>\n const byUid = new Map(roster.map((entry) => [entry.member.$id, entry]))\n\n const used = (allotment: AiAllotment): number => {\n const person = allotment.uid ? byUid.get(allotment.uid) : undefined\n switch (allotment.scope) {\n case 'member':\n return person?.credits ?? 0\n case 'collab':\n return allotment.hostId ? (person?.byHost[allotment.hostId] ?? 0) : 0\n case 'host':\n return allotment.hostId ? siteCredits(orgMonth, roster, allotment.hostId) : 0\n default:\n return 0\n }\n }\n const rows: AiAllotmentRowWire[] = allotments\n // A collaborator reading their own sees their own rows and nothing else.\n .filter((allotment) => canView || siteAdmin || allotment.uid === decoded.uid)\n .map((allotment) => ({\n subject: allotment.subject,\n scope: allotment.scope,\n uid: allotment.uid,\n hostId: allotment.hostId,\n credits: allotment.credits,\n mode: allotment.mode,\n models: allotment.models,\n used: used(allotment),\n }))\n\n const visibleMembers = roster.filter((entry) =>\n subjectUid\n ? entry.member.$id === subjectUid\n : hostId\n ? hostRoleFor(entry.member, hostId) !== null\n : canView,\n )\n const members: AiAllotmentsMemberWire[] = visibleMembers.map((entry) => ({\n uid: entry.member.$id,\n name: memberName(entry.member),\n email: typeof entry.member.email === 'string' ? entry.member.email : null,\n role: typeof entry.member.role === 'string' ? entry.member.role : null,\n orgWide: isOrgWideMember(entry.member),\n credits: entry.credits,\n byHost: entry.byHost,\n }))\n const hosts: AiAllotmentsHostWire[] = hostDocs.map((doc) => ({\n hostId: doc.id,\n name: String(doc.get('displayName') ?? '').trim() || String(doc.get('subdomain') ?? '').trim() || doc.id,\n credits: siteCredits(orgMonth, roster, doc.id),\n }))\n const provider = resolveAiProvider()\n const wire: AiAllotmentsWire = {\n orgId,\n month,\n pool: {\n used: assistCreditsFromUsd(\n assistSpendAfterReturnsUsd(\n orgMonth.get('estCostUsd'),\n orgMonth.get(ASSIST_RETURNED_USD_FIELD),\n ),\n ),\n limit: resolveAssistCreditBudget(org as never),\n },\n allotments: rows,\n members,\n hosts,\n models: AI_MODEL_CATALOG.filter((entry) => !provider || entry.provider === provider.id).map(\n (entry) => ({ id: entry.id, label: entry.label, tier: entry.tier }),\n ),\n restrictionAvailable: AI_MODEL_RESTRICTION_PLANS.includes(resolveEffectivePlan(org as never)),\n canEdit: {\n billing: canManage,\n collaborators: canManage || siteAdmin,\n },\n callerUid: decoded.uid,\n }\n return Response.json(wire, { status: 200, headers: { 'Cache-Control': 'no-store, private' } })\n}\n\ninterface ParsedWrite {\n subject: AiAllotmentSubject\n credits: number | null\n mode: AiAllotmentMode\n models: string[] | null\n}\n\nconst CATALOG_IDS = new Set(AI_MODEL_CATALOG.map((entry) => entry.id))\n\n/** One entry of `set`, validated; a string names what is wrong. */\nexport function parseAllotmentWrite(raw: unknown): ParsedWrite | string {\n const entry = (raw ?? {}) as Record<string, unknown>\n const subject = parseAiAllotmentSubject(entry['subject'])\n if (!subject) return 'subject must be member:{uid}, collab:{hostId}:{uid}, host:{hostId} or org'\n let credits: number | null = null\n if (entry['credits'] !== null && entry['credits'] !== undefined) {\n credits = typeof entry['credits'] === 'number' ? aiAllotmentCredits(entry['credits']) : null\n if (credits === null || (entry['credits'] as number) > AI_ALLOTMENT_MAX_CREDITS) {\n return `credits must be a whole number from 1 to ${AI_ALLOTMENT_MAX_CREDITS.toLocaleString('en-US')}`\n }\n }\n const mode = entry['mode'] === undefined ? 'hard' : entry['mode']\n if (mode !== 'hard' && mode !== 'soft') return 'mode must be hard or soft'\n let models: string[] | null = null\n if (entry['models'] !== null && entry['models'] !== undefined) {\n if (!Array.isArray(entry['models'])) return 'models must be a list of model ids'\n const ids = [...new Set(entry['models'].map((id) => String(id ?? '').trim()))].filter(Boolean)\n if (ids.length > AI_ALLOTMENT_MAX_MODELS) return `name at most ${AI_ALLOTMENT_MAX_MODELS} models`\n const unknown = ids.find((id) => !CATALOG_IDS.has(id))\n if (unknown) return `${unknown} is not a model this platform offers`\n models = ids.length ? ids : null\n }\n if (subject.scope === 'org' && credits !== null) {\n return 'the org-wide restriction carries models, not credits'\n }\n if (subject.scope !== 'org' && credits === null && models === null) {\n return 'set credits or models, or remove the allotment'\n }\n return { subject, credits, mode, models }\n}\n\nasync function handlePost(request: Request): Promise<Response> {\n const { body, headers } = await pluginRequestFromWeb(request)\n const auth = await authenticate(headers as Partial<Record<string, string>>)\n if (auth instanceof Response) return auth\n const { decoded } = auth\n const payload = (body ?? {}) as Record<string, unknown>\n const orgId = String(payload['orgId'] ?? '').trim()\n if (!orgId) return json({ error: 'Missing orgId' }, 400)\n\n const rawSet = Array.isArray(payload['set']) ? payload['set'] : []\n const rawRemove = Array.isArray(payload['remove']) ? payload['remove'] : []\n const rawEverySite = payload['everySite'] ?? null\n if (!rawSet.length && !rawRemove.length && !rawEverySite) {\n return json({ error: 'Nothing to change' }, 400)\n }\n if (rawSet.length + rawRemove.length > MAX_WRITES) {\n return json({ error: `Change at most ${MAX_WRITES} allotments at once` }, 400)\n }\n\n const writes: ParsedWrite[] = []\n for (const raw of rawSet) {\n const parsed = parseAllotmentWrite(raw)\n if (typeof parsed === 'string') return json({ error: parsed, code: 'invalid_allotment' }, 400)\n writes.push(parsed)\n }\n const removals: AiAllotmentSubject[] = []\n for (const raw of rawRemove) {\n const subject = parseAiAllotmentSubject(raw)\n if (!subject) return json({ error: `${String(raw)} is not an allotment subject` }, 400)\n removals.push(subject)\n }\n let everySite: Omit<ParsedWrite, 'subject'> | null = null\n if (rawEverySite) {\n const parsed = parseAllotmentWrite({ ...(rawEverySite as object), subject: 'host:every-site' })\n if (typeof parsed === 'string') return json({ error: parsed, code: 'invalid_allotment' }, 400)\n everySite = { credits: parsed.credits, mode: parsed.mode, models: parsed.models }\n }\n\n const membership = await resolveOrgMembership(decoded.uid, orgId)\n const caller: Caller = {\n uid: decoded.uid,\n email: decoded.email ?? null,\n staff: decoded.staff,\n member: membership?.member ?? null,\n }\n if (!caller.member && !caller.staff) return json({ error: 'Not found' }, 404)\n const canManage =\n caller.staff || (await memberHasOrgPermission(orgId, caller.member, 'billing.manage'))\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const orgSnapshot = await orgRef.get()\n if (!orgSnapshot.exists) return json({ error: 'Unknown organization' }, 404)\n const org = (orgSnapshot.data() ?? {}) as Record<string, unknown>\n\n // Every subject the request touches, set or removed, is decided the same\n // way: the permission first, then that the person or site belongs here.\n const touched = [...writes.map((write) => write.subject), ...removals]\n if (everySite && !canManage) return json({ error: 'billing.manage required' }, 403)\n const memberDocs = new Map<string, AglynOrgMember | null>()\n const memberOf = async (uid: string): Promise<AglynOrgMember | null> => {\n if (!memberDocs.has(uid)) {\n const snapshot = await orgRef.collection('members').doc(uid).get()\n memberDocs.set(uid, snapshot.exists ? ({ $id: uid, ...snapshot.data() } as AglynOrgMember) : null)\n }\n return memberDocs.get(uid) ?? null\n }\n const hostNames = new Map<string, string>()\n for (const subject of touched) {\n if (subject.scope === 'collab') {\n const siteAdmin = isSiteAdminCollaborator(caller.member, subject.hostId ?? '')\n if (!canManage && !siteAdmin) return json({ error: 'billing.manage required' }, 403)\n if (!canManage && subject.uid === caller.uid) {\n return json({ error: 'You cannot change your own AI allotment', code: 'own_allotment' }, 403)\n }\n const target = await memberOf(subject.uid ?? '')\n if (!target || hostRoleFor(target, subject.hostId ?? '') === null) {\n return json({ error: 'That person is not a collaborator on that site' }, 404)\n }\n // A site's admin sets allotments for the site's COLLABORATORS: a team\n // member's AI is the organization's to bound, not one site's.\n if (!canManage && isOrgWideMember(target)) {\n return json({ error: 'billing.manage required' }, 403)\n }\n } else if (!canManage) {\n return json({ error: 'billing.manage required' }, 403)\n } else if (subject.scope === 'member') {\n if (!(await memberOf(subject.uid ?? ''))) {\n return json({ error: 'That person is not a member of this organization' }, 404)\n }\n } else if (subject.scope === 'host') {\n const host = await firestore.collection('hosts').doc(subject.hostId ?? '').get()\n if (!host.exists || host.get('orgId') !== orgId) {\n return json({ error: 'That site is not part of this organization' }, 404)\n }\n hostNames.set(host.id, String(host.get('displayName') ?? '').trim() || host.id)\n }\n }\n const restricting = writes.some((write) => write.subject.scope === 'org' && write.models)\n if (restricting && !AI_MODEL_RESTRICTION_PLANS.includes(resolveEffectivePlan(org as never))) {\n return json(\n {\n error: 'Restricting models for the whole organization is available on Agency and Enterprise.',\n code: 'not_available',\n },\n 409,\n )\n }\n\n const set: AiAllotmentWrite[] = [...writes]\n if (everySite) {\n const sites = await firestore.collection('hosts').where('orgId', '==', orgId).limit(MAX_SITES).get()\n for (const site of sites.docs) {\n hostNames.set(site.id, String(site.get('displayName') ?? '').trim() || site.id)\n const subject = parseAiAllotmentSubject(`host:${site.id}`)\n if (subject) set.push({ subject, ...everySite })\n }\n if (set.length + removals.length > MAX_WRITES) {\n return json({ error: `Change at most ${MAX_WRITES} allotments at once` }, 400)\n }\n }\n\n await applyAiAllotmentWrites(\n firestore,\n orgId,\n { set, remove: removals.map((subject) => subject.id) },\n caller.uid,\n )\n\n // A site allotment set in a month the site's map has no key for yet is\n // given the month so far from its people's own months, once.\n const month = aiUsageMonthKeys()[0]\n const siteIds = set\n .filter((write) => write.subject.scope === 'host' && write.credits !== null)\n .map((write) => write.subject.hostId as string)\n if (siteIds.length) {\n const roster = await readRosterMonths(firestore, orgRef, month)\n await seedAiHostMonthCredits(firestore, orgId, siteIds, month, (siteId) =>\n roster.reduce((sum, entry) => sum + (entry.byHost[siteId] ?? 0), 0),\n ).catch((error) => console.error('[ai/allotments] site month seed failed', orgId, error))\n }\n\n void addAdminAudit(firestore, {\n actorUid: caller.uid,\n actorEmail: caller.email,\n action: 'ai.allotments.set',\n target: `orgs/${orgId}/aiAllotments`,\n before: null,\n after: {\n set: set.map((write) => ({ subject: write.subject.id, credits: write.credits, mode: write.mode, models: write.models })),\n removed: removals.map((subject) => subject.id),\n },\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n const actor = { uid: caller.uid, email: caller.email }\n const feedRow = (subject: AiAllotmentSubject) => ({\n type: subject.scope === 'host' ? ('host' as const) : subject.scope === 'org' ? ('org' as const) : ('member' as const),\n id: subject.scope === 'host' ? subject.hostId : subject.uid,\n name:\n subject.scope === 'host'\n ? hostNames.get(subject.hostId ?? '') ?? subject.hostId\n : subject.scope === 'org'\n ? 'Organization model restriction'\n : [\n memberDocs.get(subject.uid ?? '') ? memberName(memberDocs.get(subject.uid ?? '') as AglynOrgMember) : subject.uid,\n subject.scope === 'collab' ? `on ${subject.hostId}` : null,\n ]\n .filter(Boolean)\n .join(' '),\n })\n await Promise.all([\n ...set.map((write) =>\n logAiAllotmentChanged(orgId, actor, {\n subject: feedRow(write.subject),\n after: { credits: write.credits, mode: write.mode, models: write.models },\n }).catch(() => undefined),\n ),\n ...removals.map((subject) =>\n logAiAllotmentChanged(orgId, actor, { subject: feedRow(subject), after: null }).catch(\n () => undefined,\n ),\n ),\n ])\n\n return json({ ok: true, set: set.length, removed: removals.length }, 200)\n}\n\nasync function handler(request: Request): Promise<Response> {\n try {\n if (request.method === 'GET') return await handleGet(request)\n if (request.method === 'POST') return await handlePost(request)\n return json({ error: 'Method not allowed' }, 405)\n } catch (error) {\n // A refused credential is a 401, not a fault of ours (AGL-1993).\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error('[ai/allotments] failed', error)\n return json({ error: 'AI allotments unavailable' }, 500)\n }\n}\n\nexport { handler as GET, handler as POST }\n"],"names":["pluginRequestFromWeb","assistCreditsFromUsd","resolveAssistCreditBudget","hostRoleFor","isOrgWideMember","resolveSiteRolePresetPermissions","resolveEffectivePlan","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","memberHasOrgPermission","resolveOrgMembership","invalidIdTokenResponse","resolveOrgIdForHost","FieldValue","logAiAllotmentChanged","AI_ALLOTMENT_MAX_CREDITS","AI_ALLOTMENT_MAX_MODELS","aiAllotmentCredits","parseAiAllotmentSubject","aiUsageByUserMonthFrom","aiUsageMonthKeys","AI_MODEL_CATALOG","AI_MODEL_RESTRICTION_PLANS","resolveAiProvider","AI_HOST_CREDITS_FIELD","applyAiAllotmentWrites","listAiAllotments","seedAiHostMonthCredits","userAiUsageMonthRef","ASSIST_RETURNED_USD_FIELD","assistSpendAfterReturnsUsd","addAdminAudit","json","body","status","Response","MAX_WRITES","MAX_SITES","GET_ALL_CHUNK","authenticate","headers","authorization","idToken","startsWith","slice","length","undefined","error","decoded","app","auth","verifyIdToken","email_verified","uid","email","staff","isSiteAdminCollaborator","member","hostId","readRosterMonths","firestore","orgRef","month","roster","collection","get","members","docs","map","doc","$id","id","data","out","start","chunk","snapshots","getAll","forEach","snapshot","index","usage","exists","push","credits","byHost","memberName","String","displayName","trim","siteCredits","orgMonth","value","Number","isFinite","Math","floor","reduce","sum","entry","handleGet","request","params","orgSnapshot","query","subjectUid","orgId","membership","canManage","canView","siteAdmin","allowed","allotments","hostDocs","Promise","all","then","where","limit","org","byUid","Map","used","allotment","person","scope","rows","filter","subject","mode","models","visibleMembers","name","role","orgWide","hosts","provider","wire","pool","label","tier","restrictionAvailable","includes","canEdit","billing","collaborators","callerUid","CATALOG_IDS","Set","parseAllotmentWrite","raw","toLocaleString","Array","isArray","ids","Boolean","unknown","find","has","handlePost","payload","rawSet","rawRemove","rawEverySite","writes","parsed","code","removals","everySite","caller","touched","write","memberDocs","memberOf","set","hostNames","target","host","restricting","some","sites","site","remove","siteIds","siteId","catch","console","actorUid","actorEmail","action","before","after","removed","at","serverTimestamp","actor","feedRow","type","join","ok","handler","method","unauthenticated","GET","POST"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,sBAAqB;AAC1D,SACEC,oBAAoB,EACpBC,yBAAyB,QACpB,6BAAyB;AAChC,SAASC,WAAW,EAAEC,eAAe,QAAQ,uCAAsC;AACnF,SAASC,gCAAgC,QAAQ,0CAAyC;AAC1F,SAASC,oBAAoB,QAAQ,2CAA0C;AAE/E,SACEC,uBAAuB,EACvBC,aAAa,EACbC,sBAAsB,EACtBC,sBAAsB,EACtBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,qBAAqB,QAAQ,6BAAyB;AAC/D,SACEC,wBAAwB,EACxBC,uBAAuB,EACvBC,kBAAkB,EAClBC,uBAAuB,QAIlB,4BAAwB;AAC/B,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,+BAA2B;AACpF,SAASC,gBAAgB,QAAQ,0BAAsB;AACvD,SAASC,0BAA0B,QAAQ,+BAA2B;AACtE,SA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F,IAAIA,QAAQoG,MAAM,KAAK,OAAO,OAAO,MAAMrG,UAAUC;QACrD,IAAIA,QAAQoG,MAAM,KAAK,QAAQ,OAAO,MAAM1C,WAAW1D;QACvD,OAAOrE,KAAK;YAAEe,OAAO;QAAqB,GAAG;IAC/C,EAAE,OAAOA,OAAO;QACd,iEAAiE;QACjE,MAAM2J,kBAAkB/L,uBAAuBoC;QAC/C,IAAI2J,iBAAiB,OAAOA;QAC5BhB,QAAQ3I,KAAK,CAAC,0BAA0BA;QACxC,OAAOf,KAAK;YAAEe,OAAO;QAA4B,GAAG;IACtD;AACF;AAEA,SAASyJ,WAAWG,GAAG,EAAEH,WAAWI,IAAI,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-allotments.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 { pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport {\n assistCreditsFromUsd,\n resolveAssistCreditBudget,\n} from '../usage/assist-credits'\nimport { hostRoleFor, isOrgWideMember } from '@aglyn/aglyn/app-utils/organizations'\nimport { resolveSiteRolePresetPermissions } from '@aglyn/aglyn/app-utils/host-permissions'\nimport {\n ENTERPRISE_PLAN_LABEL,\n resolveEffectivePlan,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { logAiAllotmentChanged } from '../activity/ai-activity'\nimport {\n AI_ALLOTMENT_MAX_CREDITS,\n AI_ALLOTMENT_MAX_MODELS,\n aiAllotmentCredits,\n parseAiAllotmentSubject,\n type AiAllotment,\n type AiAllotmentMode,\n type AiAllotmentSubject,\n} from '../model/ai-allotments'\nimport { aiUsageByUserMonthFrom, aiUsageMonthKeys } from '../model/ai-usage-by-user'\nimport { AI_MODEL_CATALOG } from '../providers/catalog'\nimport { AI_MODEL_RESTRICTION_PLANS } from '../providers/model-choice'\nimport { resolveAiProvider } from '../providers/routing'\nimport {\n AI_HOST_CREDITS_FIELD,\n applyAiAllotmentWrites,\n listAiAllotments,\n seedAiHostMonthCredits,\n type AiAllotmentWrite,\n} from '../usage/ai-allotments'\nimport { userAiUsageMonthRef } from '../usage/ai-usage-by-user'\nimport {\n ASSIST_RETURNED_USD_FIELD,\n assistSpendAfterReturnsUsd,\n} from '../usage/assist-credit-returns'\nimport type {\n AiAllotmentRowWire,\n AiAllotmentsHostWire,\n AiAllotmentsMemberWire,\n AiAllotmentsWire,\n} from '../usage/ai-usage-wire'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\n\n// lockdown-423: exempt — a spend control, the posture of ai/billing/overage\n// beside it: a billing-locked workspace must still be able to LOWER what its\n// people may spend, and a 423 would trap it spending.\n\n/**\n * AI ALLOTMENTS (AGL-2942) — read and set them.\n *\n * ## Who may read\n *\n * - The whole org's allotments (`orgId`): `billing.view`, the Usage page's\n * gate — every allotment is a figure about the pool it is part of.\n * - One site's (`hostId`): the same, or the site's admin when they are a\n * collaborator scoped to it — the collaborators card is theirs.\n * - One person's (`uid`): the same, or the person themselves.\n *\n * ## Who may write\n *\n * - A member's, a site's and the org-wide model restriction:\n * `billing.manage`. Each moves how much of the paid pool someone may\n * spend.\n * - A collaborator's on one site: `billing.manage`, or the admin of that\n * site when they are a collaborator scoped to it — never on their own\n * allotment, which they could otherwise raise.\n *\n * Staff pass, as at the other org routes. The org-wide restriction is set\n * only on a plan that offers it (`AI_MODEL_RESTRICTION_PLANS`); clearing it\n * is always allowed.\n *\n * ## One write, many subjects\n *\n * `POST { orgId, set, remove, everySite }`: `set` replaces allotments,\n * `remove` deletes them, and `everySite` sets the same allotment on every\n * site the org has — \"same for every client site\" — expanded here, from the\n * org's sites, rather than trusted from a client's list.\n */\n\nconst json = (body: unknown, status: number) => Response.json(body, { status })\n\n/** Batch writes a request may make; Firestore commits at most 500. */\nconst MAX_WRITES = 450\n\n/** Sites one `everySite` expands to. */\nconst MAX_SITES = 400\n\n/** Member months one `getAll` carries. */\nconst GET_ALL_CHUNK = 100\n\ninterface Caller {\n uid: string\n email: string | null\n staff: boolean\n member: AglynOrgMember | null\n}\n\nasync function authenticate(\n headers: Partial<Record<string, string>>,\n): Promise<Response | { decoded: { uid: string; email?: string; staff: boolean } }> {\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return json({ error: 'Unauthenticated' }, 401)\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n return { decoded: { uid: decoded.uid, email: decoded.email, staff: decoded['staff'] === true } }\n}\n\n/**\n * A collaborator scoped to the site who holds \"Manage site settings\" there\n * (`site.manage`, AGL-4047): their site role's preset (Admin), then the\n * site's toggle for them.\n */\nfunction isSiteAdminCollaborator(member: AglynOrgMember | null, hostId: string): boolean {\n if (!member || !hostId || isOrgWideMember(member)) return false\n return resolveSiteRolePresetPermissions(member, hostId)['site.manage'] === true\n}\n\ninterface RosterMonth {\n member: AglynOrgMember\n credits: number\n byHost: Record<string, number>\n}\n\n/** The roster and each member's month, by path — no index, one getAll a hundred. */\nasync function readRosterMonths(\n firestore: FirebaseFirestore.Firestore,\n orgRef: FirebaseFirestore.DocumentReference,\n month: string,\n): Promise<RosterMonth[]> {\n const roster = await orgRef.collection('members').get()\n const members = roster.docs.map(\n (doc) => ({ $id: doc.id, ...doc.data() }) as AglynOrgMember,\n )\n const out: RosterMonth[] = []\n for (let start = 0; start < members.length; start += GET_ALL_CHUNK) {\n const chunk = members.slice(start, start + GET_ALL_CHUNK)\n const snapshots = chunk.length\n ? await firestore.getAll(\n ...chunk.map((member) => userAiUsageMonthRef(orgRef, member.$id, month)),\n )\n : []\n snapshots.forEach((snapshot, index) => {\n const member = chunk[index]\n const usage = aiUsageByUserMonthFrom(\n snapshot.exists ? (snapshot.data() as Record<string, unknown>) : null,\n member.$id,\n month,\n )\n out.push({ member, credits: usage.credits, byHost: usage.byHost })\n })\n }\n return out\n}\n\nconst memberName = (member: AglynOrgMember): string =>\n String(member.displayName ?? '').trim() || String(member.email ?? '').trim() || member.$id\n\n/** A site's credits this month: the org map, else its people's months summed. */\nfunction siteCredits(\n orgMonth: FirebaseFirestore.DocumentSnapshot,\n roster: readonly RosterMonth[],\n hostId: string,\n): number {\n const map = (orgMonth.exists ? orgMonth.get(AI_HOST_CREDITS_FIELD) : null) as\n | Record<string, unknown>\n | null\n if (map && map[hostId] !== undefined) {\n const value = Number(map[hostId])\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0\n }\n return roster.reduce((sum, entry) => sum + (entry.byHost[hostId] ?? 0), 0)\n}\n\nasync function handleGet(request: Request): Promise<Response> {\n const { query, headers } = await pluginRequestFromWeb(request)\n const params = (query ?? {}) as Record<string, unknown>\n const hostId = String(params['hostId'] ?? '').trim()\n const subjectUid = String(params['uid'] ?? '').trim()\n const auth = await authenticate(headers as Partial<Record<string, string>>)\n if (auth instanceof Response) return auth\n const { decoded } = auth\n const orgId =\n String(params['orgId'] ?? '').trim() || (hostId ? ((await resolveOrgIdForHost(hostId)) ?? '') : '')\n if (!orgId) return json({ error: 'Missing orgId' }, 400)\n\n const membership = await resolveOrgMembership(decoded.uid, orgId)\n const member = membership?.member ?? null\n if (!member && !decoded.staff) return json({ error: 'Not found' }, 404)\n const canManage =\n decoded.staff || (await memberHasOrgPermission(orgId, member, 'billing.manage'))\n const canView =\n canManage || (await memberHasOrgPermission(orgId, member, 'billing.view'))\n const siteAdmin = isSiteAdminCollaborator(member, hostId)\n const allowed = subjectUid\n ? canView || subjectUid === decoded.uid || siteAdmin\n : hostId\n ? canView || siteAdmin\n : canView\n if (!allowed) return json({ error: 'billing.view required' }, 403)\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const month = aiUsageMonthKeys()[0]\n const [orgSnapshot, orgMonth, allotments, roster, hostDocs] = await Promise.all([\n orgRef.get(),\n orgRef.collection('assistUsage').doc(month).get(),\n listAiAllotments(firestore, orgId, subjectUid ? { uid: subjectUid } : hostId ? { hostId } : {}),\n readRosterMonths(firestore, orgRef, month),\n hostId\n ? firestore.collection('hosts').doc(hostId).get().then((doc) => (doc.exists ? [doc] : []))\n : firestore.collection('hosts').where('orgId', '==', orgId).limit(MAX_SITES).get().then((snapshot) => snapshot.docs),\n ])\n const org = (orgSnapshot.data() ?? {}) as Record<string, unknown>\n const byUid = new Map(roster.map((entry) => [entry.member.$id, entry]))\n\n const used = (allotment: AiAllotment): number => {\n const person = allotment.uid ? byUid.get(allotment.uid) : undefined\n switch (allotment.scope) {\n case 'member':\n return person?.credits ?? 0\n case 'collab':\n return allotment.hostId ? (person?.byHost[allotment.hostId] ?? 0) : 0\n case 'host':\n return allotment.hostId ? siteCredits(orgMonth, roster, allotment.hostId) : 0\n default:\n return 0\n }\n }\n const rows: AiAllotmentRowWire[] = allotments\n // A collaborator reading their own sees their own rows and nothing else.\n .filter((allotment) => canView || siteAdmin || allotment.uid === decoded.uid)\n .map((allotment) => ({\n subject: allotment.subject,\n scope: allotment.scope,\n uid: allotment.uid,\n hostId: allotment.hostId,\n credits: allotment.credits,\n mode: allotment.mode,\n models: allotment.models,\n used: used(allotment),\n }))\n\n const visibleMembers = roster.filter((entry) =>\n subjectUid\n ? entry.member.$id === subjectUid\n : hostId\n ? hostRoleFor(entry.member, hostId) !== null\n : canView,\n )\n const members: AiAllotmentsMemberWire[] = visibleMembers.map((entry) => ({\n uid: entry.member.$id,\n name: memberName(entry.member),\n email: typeof entry.member.email === 'string' ? entry.member.email : null,\n role: typeof entry.member.role === 'string' ? entry.member.role : null,\n orgWide: isOrgWideMember(entry.member),\n credits: entry.credits,\n byHost: entry.byHost,\n }))\n const hosts: AiAllotmentsHostWire[] = hostDocs.map((doc) => ({\n hostId: doc.id,\n name: String(doc.get('displayName') ?? '').trim() || String(doc.get('subdomain') ?? '').trim() || doc.id,\n credits: siteCredits(orgMonth, roster, doc.id),\n }))\n const provider = resolveAiProvider()\n const wire: AiAllotmentsWire = {\n orgId,\n month,\n pool: {\n used: assistCreditsFromUsd(\n assistSpendAfterReturnsUsd(\n orgMonth.get('estCostUsd'),\n orgMonth.get(ASSIST_RETURNED_USD_FIELD),\n ),\n ),\n limit: resolveAssistCreditBudget(org as never),\n },\n allotments: rows,\n members,\n hosts,\n models: AI_MODEL_CATALOG.filter((entry) => !provider || entry.provider === provider.id).map(\n (entry) => ({ id: entry.id, label: entry.label, tier: entry.tier }),\n ),\n restrictionAvailable: AI_MODEL_RESTRICTION_PLANS.includes(resolveEffectivePlan(org as never)),\n canEdit: {\n billing: canManage,\n collaborators: canManage || siteAdmin,\n },\n callerUid: decoded.uid,\n }\n return Response.json(wire, { status: 200, headers: { 'Cache-Control': 'no-store, private' } })\n}\n\ninterface ParsedWrite {\n subject: AiAllotmentSubject\n credits: number | null\n mode: AiAllotmentMode\n models: string[] | null\n}\n\nconst CATALOG_IDS = new Set(AI_MODEL_CATALOG.map((entry) => entry.id))\n\n/** One entry of `set`, validated; a string names what is wrong. */\nexport function parseAllotmentWrite(raw: unknown): ParsedWrite | string {\n const entry = (raw ?? {}) as Record<string, unknown>\n const subject = parseAiAllotmentSubject(entry['subject'])\n if (!subject) return 'subject must be member:{uid}, collab:{hostId}:{uid}, host:{hostId} or org'\n let credits: number | null = null\n if (entry['credits'] !== null && entry['credits'] !== undefined) {\n credits = typeof entry['credits'] === 'number' ? aiAllotmentCredits(entry['credits']) : null\n if (credits === null || (entry['credits'] as number) > AI_ALLOTMENT_MAX_CREDITS) {\n return `credits must be a whole number from 1 to ${AI_ALLOTMENT_MAX_CREDITS.toLocaleString('en-US')}`\n }\n }\n const mode = entry['mode'] === undefined ? 'hard' : entry['mode']\n if (mode !== 'hard' && mode !== 'soft') return 'mode must be hard or soft'\n let models: string[] | null = null\n if (entry['models'] !== null && entry['models'] !== undefined) {\n if (!Array.isArray(entry['models'])) return 'models must be a list of model ids'\n const ids = [...new Set(entry['models'].map((id) => String(id ?? '').trim()))].filter(Boolean)\n if (ids.length > AI_ALLOTMENT_MAX_MODELS) return `name at most ${AI_ALLOTMENT_MAX_MODELS} models`\n const unknown = ids.find((id) => !CATALOG_IDS.has(id))\n if (unknown) return `${unknown} is not a model this platform offers`\n models = ids.length ? ids : null\n }\n if (subject.scope === 'org' && credits !== null) {\n return 'the org-wide restriction carries models, not credits'\n }\n if (subject.scope !== 'org' && credits === null && models === null) {\n return 'set credits or models, or remove the allotment'\n }\n return { subject, credits, mode, models }\n}\n\nasync function handlePost(request: Request): Promise<Response> {\n const { body, headers } = await pluginRequestFromWeb(request)\n const auth = await authenticate(headers as Partial<Record<string, string>>)\n if (auth instanceof Response) return auth\n const { decoded } = auth\n const payload = (body ?? {}) as Record<string, unknown>\n const orgId = String(payload['orgId'] ?? '').trim()\n if (!orgId) return json({ error: 'Missing orgId' }, 400)\n\n const rawSet = Array.isArray(payload['set']) ? payload['set'] : []\n const rawRemove = Array.isArray(payload['remove']) ? payload['remove'] : []\n const rawEverySite = payload['everySite'] ?? null\n if (!rawSet.length && !rawRemove.length && !rawEverySite) {\n return json({ error: 'Nothing to change' }, 400)\n }\n if (rawSet.length + rawRemove.length > MAX_WRITES) {\n return json({ error: `Change at most ${MAX_WRITES} allotments at once` }, 400)\n }\n\n const writes: ParsedWrite[] = []\n for (const raw of rawSet) {\n const parsed = parseAllotmentWrite(raw)\n if (typeof parsed === 'string') return json({ error: parsed, code: 'invalid_allotment' }, 400)\n writes.push(parsed)\n }\n const removals: AiAllotmentSubject[] = []\n for (const raw of rawRemove) {\n const subject = parseAiAllotmentSubject(raw)\n if (!subject) return json({ error: `${String(raw)} is not an allotment subject` }, 400)\n removals.push(subject)\n }\n let everySite: Omit<ParsedWrite, 'subject'> | null = null\n if (rawEverySite) {\n const parsed = parseAllotmentWrite({ ...(rawEverySite as object), subject: 'host:every-site' })\n if (typeof parsed === 'string') return json({ error: parsed, code: 'invalid_allotment' }, 400)\n everySite = { credits: parsed.credits, mode: parsed.mode, models: parsed.models }\n }\n\n const membership = await resolveOrgMembership(decoded.uid, orgId)\n const caller: Caller = {\n uid: decoded.uid,\n email: decoded.email ?? null,\n staff: decoded.staff,\n member: membership?.member ?? null,\n }\n if (!caller.member && !caller.staff) return json({ error: 'Not found' }, 404)\n const canManage =\n caller.staff || (await memberHasOrgPermission(orgId, caller.member, 'billing.manage'))\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const orgSnapshot = await orgRef.get()\n if (!orgSnapshot.exists) return json({ error: 'Unknown organization' }, 404)\n const org = (orgSnapshot.data() ?? {}) as Record<string, unknown>\n\n // Every subject the request touches, set or removed, is decided the same\n // way: the permission first, then that the person or site belongs here.\n const touched = [...writes.map((write) => write.subject), ...removals]\n if (everySite && !canManage) return json({ error: 'billing.manage required' }, 403)\n const memberDocs = new Map<string, AglynOrgMember | null>()\n const memberOf = async (uid: string): Promise<AglynOrgMember | null> => {\n if (!memberDocs.has(uid)) {\n const snapshot = await orgRef.collection('members').doc(uid).get()\n memberDocs.set(uid, snapshot.exists ? ({ $id: uid, ...snapshot.data() } as AglynOrgMember) : null)\n }\n return memberDocs.get(uid) ?? null\n }\n const hostNames = new Map<string, string>()\n for (const subject of touched) {\n if (subject.scope === 'collab') {\n const siteAdmin = isSiteAdminCollaborator(caller.member, subject.hostId ?? '')\n if (!canManage && !siteAdmin) return json({ error: 'billing.manage required' }, 403)\n if (!canManage && subject.uid === caller.uid) {\n return json({ error: 'You cannot change your own AI allotment', code: 'own_allotment' }, 403)\n }\n const target = await memberOf(subject.uid ?? '')\n if (!target || hostRoleFor(target, subject.hostId ?? '') === null) {\n return json({ error: 'That person is not a collaborator on that site' }, 404)\n }\n // A site's admin sets allotments for the site's COLLABORATORS: a team\n // member's AI is the organization's to bound, not one site's.\n if (!canManage && isOrgWideMember(target)) {\n return json({ error: 'billing.manage required' }, 403)\n }\n } else if (!canManage) {\n return json({ error: 'billing.manage required' }, 403)\n } else if (subject.scope === 'member') {\n if (!(await memberOf(subject.uid ?? ''))) {\n return json({ error: 'That person is not a member of this organization' }, 404)\n }\n } else if (subject.scope === 'host') {\n const host = await firestore.collection('hosts').doc(subject.hostId ?? '').get()\n if (!host.exists || host.get('orgId') !== orgId) {\n return json({ error: 'That site is not part of this organization' }, 404)\n }\n hostNames.set(host.id, String(host.get('displayName') ?? '').trim() || host.id)\n }\n }\n const restricting = writes.some((write) => write.subject.scope === 'org' && write.models)\n if (restricting && !AI_MODEL_RESTRICTION_PLANS.includes(resolveEffectivePlan(org as never))) {\n return json(\n {\n // The plan that sells it is Custom since pricing v4 (AGL-4158); a\n // workspace still stored on the retired Agency plan keeps it.\n error: `Restricting models for the whole organization is available on the ${ENTERPRISE_PLAN_LABEL} plan.`,\n code: 'not_available',\n },\n 409,\n )\n }\n\n const set: AiAllotmentWrite[] = [...writes]\n if (everySite) {\n const sites = await firestore.collection('hosts').where('orgId', '==', orgId).limit(MAX_SITES).get()\n for (const site of sites.docs) {\n hostNames.set(site.id, String(site.get('displayName') ?? '').trim() || site.id)\n const subject = parseAiAllotmentSubject(`host:${site.id}`)\n if (subject) set.push({ subject, ...everySite })\n }\n if (set.length + removals.length > MAX_WRITES) {\n return json({ error: `Change at most ${MAX_WRITES} allotments at once` }, 400)\n }\n }\n\n await applyAiAllotmentWrites(\n firestore,\n orgId,\n { set, remove: removals.map((subject) => subject.id) },\n caller.uid,\n )\n\n // A site allotment set in a month the site's map has no key for yet is\n // given the month so far from its people's own months, once.\n const month = aiUsageMonthKeys()[0]\n const siteIds = set\n .filter((write) => write.subject.scope === 'host' && write.credits !== null)\n .map((write) => write.subject.hostId as string)\n if (siteIds.length) {\n const roster = await readRosterMonths(firestore, orgRef, month)\n await seedAiHostMonthCredits(firestore, orgId, siteIds, month, (siteId) =>\n roster.reduce((sum, entry) => sum + (entry.byHost[siteId] ?? 0), 0),\n ).catch((error) => console.error('[ai/allotments] site month seed failed', orgId, error))\n }\n\n void addAdminAudit(firestore, {\n actorUid: caller.uid,\n actorEmail: caller.email,\n action: 'ai.allotments.set',\n target: `orgs/${orgId}/aiAllotments`,\n before: null,\n after: {\n set: set.map((write) => ({ subject: write.subject.id, credits: write.credits, mode: write.mode, models: write.models })),\n removed: removals.map((subject) => subject.id),\n },\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n const actor = { uid: caller.uid, email: caller.email }\n const feedRow = (subject: AiAllotmentSubject) => ({\n type: subject.scope === 'host' ? ('host' as const) : subject.scope === 'org' ? ('org' as const) : ('member' as const),\n id: subject.scope === 'host' ? subject.hostId : subject.uid,\n name:\n subject.scope === 'host'\n ? hostNames.get(subject.hostId ?? '') ?? subject.hostId\n : subject.scope === 'org'\n ? 'Organization model restriction'\n : [\n memberDocs.get(subject.uid ?? '') ? memberName(memberDocs.get(subject.uid ?? '') as AglynOrgMember) : subject.uid,\n subject.scope === 'collab' ? `on ${subject.hostId}` : null,\n ]\n .filter(Boolean)\n .join(' '),\n })\n await Promise.all([\n ...set.map((write) =>\n logAiAllotmentChanged(orgId, actor, {\n subject: feedRow(write.subject),\n after: { credits: write.credits, mode: write.mode, models: write.models },\n }).catch(() => undefined),\n ),\n ...removals.map((subject) =>\n logAiAllotmentChanged(orgId, actor, { subject: feedRow(subject), after: null }).catch(\n () => undefined,\n ),\n ),\n ])\n\n return json({ ok: true, set: set.length, removed: removals.length }, 200)\n}\n\nasync function handler(request: Request): Promise<Response> {\n try {\n if (request.method === 'GET') return await handleGet(request)\n if (request.method === 'POST') return await handlePost(request)\n return json({ error: 'Method not allowed' }, 405)\n } catch (error) {\n // A refused credential is a 401, not a fault of ours (AGL-1993).\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error('[ai/allotments] failed', error)\n return json({ error: 'AI allotments unavailable' }, 500)\n }\n}\n\nexport { handler as GET, handler as POST }\n"],"names":["pluginRequestFromWeb","assistCreditsFromUsd","resolveAssistCreditBudget","hostRoleFor","isOrgWideMember","resolveSiteRolePresetPermissions","ENTERPRISE_PLAN_LABEL","resolveEffectivePlan","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","memberHasOrgPermission","resolveOrgMembership","invalidIdTokenResponse","resolveOrgIdForHost","FieldValue","logAiAllotmentChanged","AI_ALLOTMENT_MAX_CREDITS","AI_ALLOTMENT_MAX_MODELS","aiAllotmentCredits","parseAiAllotmentSubject","aiUsageByUserMonthFrom","aiUsageMonthKeys","AI_MODEL_CATALOG","AI_MODEL_RESTRICTION_PLANS","resolveAiProvider","AI_HOST_CREDITS_FIELD","applyAiAllotmentWrites","listAiAllotments","seedAiHostMonthCredits","userAiUsageMonthRef","ASSIST_RETURNED_USD_FIELD","assistSpendAfterReturnsUsd","addAdminAudit","json","body","status","Response","MAX_WRITES","MAX_SITES","GET_ALL_CHUNK","authenticate","headers","authorization","idToken","startsWith","slice","length","undefined","error","decoded","app","auth","verifyIdToken","email_verified","uid","email","staff","isSiteAdminCollaborator","member","hostId","readRosterMonths","firestore","orgRef","month","roster","collection","get","members","docs","map","doc","$id","id","data","out","start","chunk","snapshots","getAll","forEach","snapshot","index","usage","exists","push","credits","byHost","memberName","String","displayName","trim","siteCredits","orgMonth","value","Number","isFinite","Math","floor","reduce","sum","entry","handleGet","request","params","orgSnapshot","query","subjectUid","orgId","membership","canManage","canView","siteAdmin","allowed","allotments","hostDocs","Promise","all","then","where","limit","org","byUid","Map","used","allotment","person","scope","rows","filter","subject","mode","models","visibleMembers","name","role","orgWide","hosts","provider","wire","pool","label","tier","restrictionAvailable","includes","canEdit","billing","collaborators","callerUid","CATALOG_IDS","Set","parseAllotmentWrite","raw","toLocaleString","Array","isArray","ids","Boolean","unknown","find","has","handlePost","payload","rawSet","rawRemove","rawEverySite","writes","parsed","code","removals","everySite","caller","touched","write","memberDocs","memberOf","set","hostNames","target","host","restricting","some","sites","site","remove","siteIds","siteId","catch","console","actorUid","actorEmail","action","before","after","removed","at","serverTimestamp","actor","feedRow","type","join","ok","handler","method","unauthenticated","GET","POST"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,sBAAqB;AAC1D,SACEC,oBAAoB,EACpBC,yBAAyB,QACpB,6BAAyB;AAChC,SAASC,WAAW,EAAEC,eAAe,QAAQ,uCAAsC;AACnF,SAASC,gCAAgC,QAAQ,0CAAyC;AAC1F,SACEC,qBAAqB,EACrBC,oBAAoB,QACf,2CAA0C;AAEjD,SACEC,uBAAuB,EACvBC,aAAa,EACbC,sBAAsB,EACtBC,sBAAsB,EACtBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,qBAAqB,QAAQ,6BAAyB;AAC/D,SACEC,wBAAwB,EACxBC,uBAAuB,EACvBC,kBAAkB,EAClBC,uBAAuB,QAIlB,4BAAwB;AAC/B,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,+BAA2B;AACpF,SAASC,gBAAgB,QAAQ,0BAAsB;AACvD,SAASC,0BAA0B,QAAQ,+BAA2B;AAC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ASzB,SAAS1H,MAAM;IAAC,GAAG;AACvE;AAEA,eAAe2J,QAAQnG,OAAgB;IACrC,IAAI;QACF,IAAIA,QAAQoG,MAAM,KAAK,OAAO,OAAO,MAAMrG,UAAUC;QACrD,IAAIA,QAAQoG,MAAM,KAAK,QAAQ,OAAO,MAAM1C,WAAW1D;QACvD,OAAOrE,KAAK;YAAEe,OAAO;QAAqB,GAAG;IAC/C,EAAE,OAAOA,OAAO;QACd,iEAAiE;QACjE,MAAM2J,kBAAkB/L,uBAAuBoC;QAC/C,IAAI2J,iBAAiB,OAAOA;QAC5BhB,QAAQ3I,KAAK,CAAC,0BAA0BA;QACxC,OAAOf,KAAK;YAAEe,OAAO;QAA4B,GAAG;IACtD;AACF;AAEA,SAASyJ,WAAWG,GAAG,EAAEH,WAAWI,IAAI,GAAE"}
|
|
@@ -23,6 +23,7 @@ import { aiBuildFreeCreditsRefusal, aiBuildFreeTaste } from "../jobs/ai-job-buil
|
|
|
23
23
|
import { aiBuildCreditRange, aiBuildFirstPagePlan, aiBuildRetryLedger, aiBuildUnits, aiLedgerUnits } from "../model/ai-build-job.js";
|
|
24
24
|
import { aiCreditsConfirmation } from "../model/ai-credit-estimate.js";
|
|
25
25
|
import { aiJobInputProblems } from "../model/ai-job-input.js";
|
|
26
|
+
import { aiSiteImportFinishUpdate } from "../model/ai-site-import.js";
|
|
26
27
|
import { FREE_AI_TASTE_CREDITS_PER_MONTH } from "../plan-entitlements.js";
|
|
27
28
|
import { aiGateLadder } from "../runtime/ai-gate.js";
|
|
28
29
|
import { releaseAssistMessage } from "../usage/assist-usage.js";
|
|
@@ -30,7 +31,10 @@ import { releaseAssistMessage } from "../usage/assist-usage.js";
|
|
|
30
31
|
* Resume a job that stopped for a person (AGL-2935): confirm its plan, or
|
|
31
32
|
* try again the step whose answer broke a building rule on its re-ask — or
|
|
32
33
|
* answer what a job waiting in `needs_input` asks (`input`, AGL-3978), which
|
|
33
|
-
* returns it to its plan card, or a 400 with `fieldErrors` by field.
|
|
34
|
+
* returns it to its plan card, or a 400 with `fieldErrors` by field. An
|
|
35
|
+
* import's next wave may carry the owner's Keep my site or Improve it
|
|
36
|
+
* (`finish`, `wording`, AGL-4152), written after the kind's own admission and
|
|
37
|
+
* only onto an import waiting for a wave that has not started.
|
|
34
38
|
*
|
|
35
39
|
* A door that SPENDS — the next step calls the provider — so it climbs the
|
|
36
40
|
* whole ladder the create door climbs: `aiGenerative`,
|
|
@@ -91,6 +95,18 @@ export async function POST(request, context) {
|
|
|
91
95
|
status: 400
|
|
92
96
|
});
|
|
93
97
|
}
|
|
98
|
+
// Keep my site or Improve it (AGL-4152): one of the two, and the wording switch on or off.
|
|
99
|
+
const rawFinish = payload == null ? void 0 : payload['finish'];
|
|
100
|
+
const rawWording = payload == null ? void 0 : payload['wording'];
|
|
101
|
+
if (rawFinish !== undefined && rawFinish !== 'keep' && rawFinish !== 'improve' || rawWording !== undefined && typeof rawWording !== 'boolean') {
|
|
102
|
+
await release();
|
|
103
|
+
return Response.json({
|
|
104
|
+
error: 'Choose Keep my site or Improve it.',
|
|
105
|
+
job: aiJobSummary(existing, new Date())
|
|
106
|
+
}, {
|
|
107
|
+
status: 400
|
|
108
|
+
});
|
|
109
|
+
}
|
|
94
110
|
// "Build what fits" (AGL-3722): a Free job past what is left, started on
|
|
95
111
|
// the person's go-ahead, which the job keeps.
|
|
96
112
|
const creditsConfirmed = (payload == null ? void 0 : payload['creditsConfirmed']) === true;
|
|
@@ -232,8 +248,16 @@ export async function POST(request, context) {
|
|
|
232
248
|
// "Start every remaining wave" (AGL-4084): an import waiting for its next
|
|
233
249
|
// wave starts every one left, with no review between them.
|
|
234
250
|
const startAll = (payload == null ? void 0 : payload['startAll']) === true && existing.kind === 'import' ? (await import("../jobs/ai-job-import-step.js")).aiSiteImportStartAllUpdate(existing) : null;
|
|
235
|
-
|
|
236
|
-
|
|
251
|
+
// Keep my site or Improve it (AGL-4152), changed before a wave: the waves
|
|
252
|
+
// not yet started are built the new way, and a wave already in never is.
|
|
253
|
+
const finish = rawFinish === 'keep' || rawFinish === 'improve' ? rawFinish : null;
|
|
254
|
+
const choosing = finish !== null || typeof rawWording === 'boolean';
|
|
255
|
+
const finishUpdate = choosing ? aiSiteImportFinishUpdate(existing, {
|
|
256
|
+
finish,
|
|
257
|
+
wording: typeof rawWording === 'boolean' ? rawWording : null
|
|
258
|
+
}) : null;
|
|
259
|
+
if (startAll || finishUpdate) {
|
|
260
|
+
await gate.firestore.collection('orgs').doc(gate.orgId).collection(AI_JOBS_COLLECTION).doc(jobId).update(_extends({}, startAll != null ? startAll : {}, finishUpdate != null ? finishUpdate : {}));
|
|
237
261
|
}
|
|
238
262
|
const now = new Date();
|
|
239
263
|
const confirmation = aiCreditsConfirmation(confirmedCredits, gate.uid, now);
|
|
@@ -264,11 +288,14 @@ export async function POST(request, context) {
|
|
|
264
288
|
actorEmail: (_gate_decoded_email = gate.decoded.email) != null ? _gate_decoded_email : null,
|
|
265
289
|
orgId: gate.orgId,
|
|
266
290
|
jobId,
|
|
267
|
-
after: {
|
|
291
|
+
after: _extends({
|
|
268
292
|
status: job.status,
|
|
269
293
|
reason: retryFailedItems ? 'retry-failed-items' : answering ? 'input' : (_ref1 = (_existing_review = existing.review) == null ? void 0 : _existing_review.reason) != null ? _ref1 : null,
|
|
270
294
|
kind: existing.kind
|
|
271
|
-
}
|
|
295
|
+
}, finishUpdate ? {
|
|
296
|
+
finish: finishUpdate['siteImport.finish'],
|
|
297
|
+
wording: finishUpdate['siteImport.wording']
|
|
298
|
+
} : {})
|
|
272
299
|
});
|
|
273
300
|
if (job.status !== 'queued') {
|
|
274
301
|
await release();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-jobs-resume.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\n// lockdown-423: via libs/plugins/ai/src/lib/runtime/ai-gate.ts\n// The POST climbs `aiGateLadder`, whose lockdown rung is the verdict.\n\nimport { randomUUID } from 'crypto'\nimport { aiJobAdmissionRefusal, aiJobSiteRefusal, type AiJobAdmissionRefusal } from '../jobs/ai-job-admission'\nimport {\n AI_JOB_INLINE_BUDGET_MS,\n AI_JOBS_COLLECTION,\n aiJobNextStepMinimumMs,\n aiJobSummary,\n getAiJob,\n aiBuildRetryable,\n resumeAiJob,\n retryAiBuildJob,\n runAiJobStep,\n writeAiJobAudit,\n} from '../jobs/ai-jobs'\nimport type { AiJob } from '../model/ai-jobs.types'\nimport { aiBuildFreeCreditsRefusal, aiBuildFreeTaste } from '../jobs/ai-job-build-step'\nimport {\n aiBuildCreditRange,\n aiBuildFirstPagePlan,\n aiBuildRetryLedger,\n aiBuildUnits,\n aiLedgerUnits,\n} from '../model/ai-build-job'\nimport { aiCreditsConfirmation, type AiCreditsPrompt } from '../model/ai-credit-estimate'\nimport { aiJobInputProblems } from '../model/ai-job-input'\nimport { FREE_AI_TASTE_CREDITS_PER_MONTH } from '../plan-entitlements'\nimport { aiGateLadder } from '../runtime/ai-gate'\nimport { releaseAssistMessage } from '../usage/assist-usage'\n\n/**\n * Resume a job that stopped for a person (AGL-2935): confirm its plan, or\n * try again the step whose answer broke a building rule on its re-ask — or\n * answer what a job waiting in `needs_input` asks (`input`, AGL-3978), which\n * returns it to its plan card, or a 400 with `fieldErrors` by field.\n *\n * A door that SPENDS — the next step calls the provider — so it climbs the\n * whole ladder the create door climbs: `aiGenerative`,\n * `release_ai_generative`, the `ai-generate` switch, `ai.generate` on the\n * job's site, a per-uid window and a reservation. It then runs the next\n * step inline on that reservation, the way the create door runs the first,\n * and hands the reservation back whenever no step runs here.\n *\n * The body names the org and the job's site. A site that is not the job's\n * is refused, so a collaborator's permission on one site never confirms a\n * job on another. Audited per resume that changed something.\n */\n\nconst AI_JOBS_RESUME_RATE_LIMIT = { key: 'ai-jobs-resume', limit: 10, windowMs: 60_000 }\n\nexport async function POST(\n request: Request,\n context: { params: Promise<{ jobId: string }> },\n): Promise<Response> {\n let payload: Record<string, unknown> | null\n try {\n payload = (await request.json()) as Record<string, unknown>\n } catch {\n payload = null\n }\n const rawHost = payload?.['hostId']\n const hostId = typeof rawHost === 'string' && rawHost ? rawHost : null\n const gate = await aiGateLadder(\n { request, orgId: String(payload?.['orgId'] ?? ''), hostId },\n {\n feature: 'aiGenerative',\n releaseFlag: 'release_ai_generative',\n lockdownFeature: 'ai-generate',\n permission: 'ai.generate',\n rateLimit: AI_JOBS_RESUME_RATE_LIMIT,\n },\n )\n if (gate instanceof Response) return gate\n // No token is spent until a step runs, so every exit before one hands the\n // message back.\n const release = () =>\n releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(() => undefined)\n\n const { jobId } = await context.params\n const existing = await getAiJob(gate.firestore, gate.orgId, jobId)\n if (!existing) {\n await release()\n return Response.json({ error: 'Unknown job' }, { status: 404 })\n }\n if ((existing.hostId ?? null) !== hostId) {\n await release()\n return Response.json({ error: 'That job belongs to another site' }, { status: 400 })\n }\n // \"Build what fits\" (AGL-3722): a Free job past what is left, started on\n // the person's go-ahead, which the job keeps.\n const creditsConfirmed = payload?.['creditsConfirmed'] === true\n let confirmedCredits: AiCreditsPrompt | null = null\n const onCreditsConfirmed = (prompt: AiCreditsPrompt) => {\n confirmedCredits = prompt\n }\n // \"Build the home page first\" (AGL-3722): the plan waiting for its\n // confirmation narrowed to its home page and what that page needs.\n const reduceToFirstPage =\n payload?.['reduce'] === 'first-page' && existing.kind === 'build' && existing.status === 'needs_review'\n const reduced = reduceToFirstPage && existing.plan ? aiBuildFirstPagePlan(existing.plan) : null\n if (reduceToFirstPage && !reduced) {\n await release()\n return Response.json(\n { error: 'This plan has no smaller first build', job: aiJobSummary(existing, new Date()) },\n { status: 409 },\n )\n }\n // A refusal as the door answers it: a Free job past what is left carries\n // its prompt, and a plan card the figures it should now show.\n const refused = async (refusal: AiJobAdmissionRefusal) => {\n await release()\n const now = new Date()\n const summary = aiJobSummary(existing, now)\n const fresh = refusal.credits\n ? { left: refusal.credits.left, total: FREE_AI_TASTE_CREDITS_PER_MONTH, resetsOn: refusal.credits.resetsOn }\n : null\n const job = fresh && summary.review ? { ...summary, review: { ...summary.review, freeCredits: fresh } } : summary\n return Response.json(\n {\n error: refusal.error,\n ...(refusal.code ? { code: refusal.code } : {}),\n ...(refusal.credits ? { credits: refusal.credits } : {}),\n job,\n },\n { status: refusal.status },\n )\n }\n // Try again on a build (AGL-3616): its failed items and what they left\n // unbuilt, never what succeeded, and never its plan again.\n const retryFailedItems = payload?.['retry'] === 'failed-items'\n if (retryFailedItems) {\n const refusal = await aiBuildRetryRefusal(gate, existing, { confirmed: creditsConfirmed, onCreditsConfirmed }).catch(\n (error: unknown) => {\n console.error('ai build retry admission failed', { orgId: gate.orgId, jobId, error })\n return { status: 500 as const, error: 'The AI job could not be resumed' }\n },\n )\n if (refusal) {\n if (refusal.status === 500) {\n await release()\n return Response.json({ error: refusal.error, job: aiJobSummary(existing, new Date()) }, { status: 500 })\n }\n return refused(refusal)\n }\n }\n // A job waiting for a person's answer (AGL-3978): every field must read\n // before anything changes, and a refusal names each field it is about.\n const answering = existing.status === 'needs_input' && Boolean(existing.input?.fields?.length)\n const rawInput = payload?.['input']\n const answers = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput) ? (rawInput as Record<string, unknown>) : null\n if (answering && existing.input) {\n const fieldErrors = aiJobInputProblems(existing.input, answers)\n const first = Object.values(fieldErrors)[0]\n if (first) {\n await release()\n return Response.json({ error: first, fieldErrors, job: aiJobSummary(existing, new Date()) }, { status: 400 })\n }\n }\n // A confirmed plan runs the step that writes, and an allowance free when the\n // job was created may be used by now (AGL-2909): the kind is asked again\n // before anything runs, and a refusal leaves the job waiting for review.\n if (existing.status === 'needs_review') {\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>>\n try {\n // A site that switched AI off first (AGL-3028), then the kind's own check.\n refusal =\n (await aiJobSiteRefusal({\n firestore: gate.firestore,\n org: gate.org,\n hostId: existing.hostId ?? null,\n })) ??\n (await aiJobAdmissionRefusal(existing.kind, {\n firestore: gate.firestore,\n orgId: gate.orgId,\n hostId: existing.hostId ?? null,\n inputs: existing.inputs ?? {},\n org: gate.org,\n // The plan being confirmed, for a kind that builds only some plans —\n // the smaller first build where the person chose it (AGL-3722).\n plan: reduced ?? existing.plan ?? null,\n uid: gate.uid,\n creditsConfirmed,\n onCreditsConfirmed,\n }))\n } catch (error) {\n await release()\n console.error('ai job admission failed', { orgId: gate.orgId, jobId, error })\n return Response.json({ error: 'The AI job could not be resumed' }, { status: 500 })\n }\n if (refusal) return refused(refusal)\n }\n // \"Start every remaining wave\" (AGL-4084): an import waiting for its next\n // wave starts every one left, with no review between them.\n const startAll =\n payload?.['startAll'] === true && existing.kind === 'import'\n ? (await import('../jobs/ai-job-import-step')).aiSiteImportStartAllUpdate(existing)\n : null\n if (startAll) {\n await gate.firestore.collection('orgs').doc(gate.orgId).collection(AI_JOBS_COLLECTION).doc(jobId).update(startAll)\n }\n const now = new Date()\n const confirmation = aiCreditsConfirmation(confirmedCredits, gate.uid, now)\n const { job, changed } = retryFailedItems\n ? await retryAiBuildJob(gate.firestore, gate.orgId, jobId, now, { creditsConfirmed: confirmation })\n : await resumeAiJob(gate.firestore, gate.orgId, jobId, { uid: gate.uid }, now, {\n publishConfirmed: payload?.['publish'] === true,\n creditsConfirmed: confirmation,\n ...(reduced ? { reducePlan: aiBuildFirstPagePlan } : {}),\n ...(answering ? { input: answers } : {}),\n })\n if (!changed) {\n await release()\n return Response.json(\n { error: 'This job is not waiting for review', job: aiJobSummary(job, now) },\n { status: 409 },\n )\n }\n await writeAiJobAudit(gate.firestore, {\n action: 'ai.job.resume',\n actorUid: gate.uid,\n actorEmail: gate.decoded.email ?? null,\n orgId: gate.orgId,\n jobId,\n after: {\n status: job.status,\n reason: retryFailedItems ? 'retry-failed-items' : answering ? 'input' : (existing.review?.reason ?? null),\n kind: existing.kind,\n },\n })\n if (job.status !== 'queued') {\n await release()\n return Response.json({ job: aiJobSummary(job, now) }, { status: 200 })\n }\n // A step that needs more time than this request has (AGL-2907) is left\n // queued for the beat, which starts it with a budget of its own: a provider\n // call this request's timeout cut off would be billed upstream and metered\n // nowhere.\n if (aiJobNextStepMinimumMs(job) > AI_JOB_INLINE_BUDGET_MS) {\n await release()\n return Response.json({ job: aiJobSummary(job, now) }, { status: 200 })\n }\n\n const run = await runAiJobStep(gate.firestore, gate.orgId, jobId, {\n owner: `route:${randomUUID()}`,\n now,\n reservation: gate.reservation,\n org: gate.org,\n signal: AbortSignal.timeout(AI_JOB_INLINE_BUDGET_MS),\n actor: { uid: gate.uid, email: gate.decoded.email ?? null },\n // The workspace's AI pause lets staff through, as the ladder above did.\n staff: gate.staff,\n })\n if (run.outcome === 'not-claimable') {\n // The beat claimed the step between the resume and this run; it runs\n // there, on a reservation of its own.\n await release()\n const latest = await getAiJob(gate.firestore, gate.orgId, jobId)\n return Response.json({ job: aiJobSummary(latest ?? job, now) }, { status: 200 })\n }\n return Response.json({ job: aiJobSummary(run.job) }, { status: 200 })\n}\n\n/**\n * Why a build's Try again cannot run (AGL-3616), or `null`: it is not a\n * finished build, the site switched AI off, or — on the Free taste — the\n * month's Free credits do not cover what the retried items are estimated at.\n */\nasync function aiBuildRetryRefusal(\n gate: { firestore: FirebaseFirestore.Firestore; orgId: string; org: object | null },\n job: AiJob,\n credits: { confirmed: boolean; onCreditsConfirmed: (prompt: AiCreditsPrompt) => void },\n): Promise<AiJobAdmissionRefusal | null> {\n const plan = job.plan?.status === 'confirmed' ? job.plan : null\n if (!aiBuildRetryable(job) || !plan || !job.items?.length) {\n return { status: 409, error: 'Only a finished build can try its failed items again' }\n }\n const site = await aiJobSiteRefusal({ firestore: gate.firestore, org: gate.org, hostId: job.hostId ?? null })\n if (site) return site\n const { retried } = aiBuildRetryLedger(job.items, job.kind === 'site' ? aiLedgerUnits(job.items) : aiBuildUnits(plan))\n if (!retried.length) return { status: 409, error: 'Nothing in this build is left to try again' }\n // A site's retried parts are its own pages and creations, held by the\n // reservation each pass takes; a build's are admitted on their measured p90\n // against the Free taste, or on the person's go-ahead (AGL-3722).\n if (job.kind === 'site' || !aiBuildFreeTaste(gate.org)) return null\n return aiBuildFreeCreditsRefusal({\n firestore: gate.firestore,\n orgId: gate.orgId,\n org: gate.org,\n range: aiBuildCreditRange(plan, { slots: new Set(retried) }),\n confirmed: credits.confirmed,\n onConfirmed: credits.onCreditsConfirmed,\n now: new Date(),\n })\n}\n\nexport const dynamic = 'force-dynamic'\nexport const maxDuration = 60\n"],"names":["randomUUID","aiJobAdmissionRefusal","aiJobSiteRefusal","AI_JOB_INLINE_BUDGET_MS","AI_JOBS_COLLECTION","aiJobNextStepMinimumMs","aiJobSummary","getAiJob","aiBuildRetryable","resumeAiJob","retryAiBuildJob","runAiJobStep","writeAiJobAudit","aiBuildFreeCreditsRefusal","aiBuildFreeTaste","aiBuildCreditRange","aiBuildFirstPagePlan","aiBuildRetryLedger","aiBuildUnits","aiLedgerUnits","aiCreditsConfirmation","aiJobInputProblems","FREE_AI_TASTE_CREDITS_PER_MONTH","aiGateLadder","releaseAssistMessage","AI_JOBS_RESUME_RATE_LIMIT","key","limit","windowMs","POST","request","context","existing","gate","payload","json","rawHost","hostId","orgId","String","feature","releaseFlag","lockdownFeature","permission","rateLimit","Response","release","firestore","reservation","catch","undefined","jobId","params","error","status","creditsConfirmed","confirmedCredits","onCreditsConfirmed","prompt","reduceToFirstPage","kind","reduced","plan","job","Date","refused","refusal","now","summary","fresh","credits","left","total","resetsOn","review","freeCredits","code","retryFailedItems","aiBuildRetryRefusal","confirmed","console","answering","Boolean","input","fields","length","rawInput","answers","Array","isArray","fieldErrors","first","Object","values","org","inputs","uid","startAll","aiSiteImportStartAllUpdate","collection","doc","update","confirmation","changed","publishConfirmed","reducePlan","action","actorUid","actorEmail","decoded","email","after","reason","run","owner","signal","AbortSignal","timeout","actor","staff","outcome","latest","items","site","retried","range","slots","Set","onConfirmed","dynamic","maxDuration"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,+DAA+D;AAC/D,sEAAsE;AAEtE,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,qBAAqB,EAAEC,gBAAgB,QAAoC,8BAA0B;AAC9G,SACEC,uBAAuB,EACvBC,kBAAkB,EAClBC,sBAAsB,EACtBC,YAAY,EACZC,QAAQ,EACRC,gBAAgB,EAChBC,WAAW,EACXC,eAAe,EACfC,YAAY,EACZC,eAAe,QACV,qBAAiB;AAExB,SAASC,yBAAyB,EAAEC,gBAAgB,QAAQ,+BAA2B;AACvF,SACEC,kBAAkB,EAClBC,oBAAoB,EACpBC,kBAAkB,EAClBC,YAAY,EACZC,aAAa,QACR,2BAAuB;AAC9B,SAASC,qBAAqB,QAA8B,iCAA6B;AACzF,SAASC,kBAAkB,QAAQ,2BAAuB;AAC1D,SAASC,+BAA+B,QAAQ,0BAAsB;AACtE,SAASC,YAAY,QAAQ,wBAAoB;AACjD,SAASC,oBAAoB,QAAQ,2BAAuB;AAE5D;;;;;;;;;;;;;;;;CAgBC,GAED,MAAMC,4BAA4B;IAAEC,KAAK;IAAkBC,OAAO;IAAIC,UAAU;AAAO;AAEvF,OAAO,eAAeC,KACpBC,OAAgB,EAChBC,OAA+C;cAgC1CC,kBAwISC,4BA4BmBA;QArG8BD,wBAAAA,iBA8EcA;IA3K7E,IAAIE;IACJ,IAAI;QACFA,UAAW,MAAMJ,QAAQK,IAAI;IAC/B,EAAE,eAAM;QACND,UAAU;IACZ;IACA,MAAME,UAAUF,2BAAAA,OAAS,CAAC,SAAS;IACnC,MAAMG,SAAS,OAA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E+C,KAAK7D,KAAK6D,GAAG;QAAEzD,MAAM,GAAE0B,cAAAA,IAAI1B,MAAM,YAAV0B,cAAc;IAAK;IAC3G,IAAI4D,MAAM,OAAOA;IACjB,MAAM,EAAEC,OAAO,EAAE,GAAG3G,mBAAmB8C,IAAI2D,KAAK,EAAE3D,IAAIH,IAAI,KAAK,SAASzC,cAAc4C,IAAI2D,KAAK,IAAIxG,aAAa4C;IAChH,IAAI,CAAC8D,QAAQvC,MAAM,EAAE,OAAO;QAAE/B,QAAQ;QAAKD,OAAO;IAA6C;IAC/F,sEAAsE;IACtE,4EAA4E;IAC5E,kEAAkE;IAClE,IAAIU,IAAIH,IAAI,KAAK,UAAU,CAAC9C,iBAAiBmB,KAAK6D,GAAG,GAAG,OAAO;IAC/D,OAAOjF,0BAA0B;QAC/BkC,WAAWd,KAAKc,SAAS;QACzBT,OAAOL,KAAKK,KAAK;QACjBwD,KAAK7D,KAAK6D,GAAG;QACb+B,OAAO9G,mBAAmB+C,MAAM;YAAEgE,OAAO,IAAIC,IAAIH;QAAS;QAC1D7C,WAAWT,QAAQS,SAAS;QAC5BiD,aAAa1D,QAAQb,kBAAkB;QACvCU,KAAK,IAAIH;IACX;AACF;AAEA,OAAO,MAAMiE,UAAU,gBAAe;AACtC,OAAO,MAAMC,cAAc,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-jobs-resume.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\n// lockdown-423: via libs/plugins/ai/src/lib/runtime/ai-gate.ts\n// The POST climbs `aiGateLadder`, whose lockdown rung is the verdict.\n\nimport { randomUUID } from 'crypto'\nimport { aiJobAdmissionRefusal, aiJobSiteRefusal, type AiJobAdmissionRefusal } from '../jobs/ai-job-admission'\nimport {\n AI_JOB_INLINE_BUDGET_MS,\n AI_JOBS_COLLECTION,\n aiJobNextStepMinimumMs,\n aiJobSummary,\n getAiJob,\n aiBuildRetryable,\n resumeAiJob,\n retryAiBuildJob,\n runAiJobStep,\n writeAiJobAudit,\n} from '../jobs/ai-jobs'\nimport type { AiJob } from '../model/ai-jobs.types'\nimport { aiBuildFreeCreditsRefusal, aiBuildFreeTaste } from '../jobs/ai-job-build-step'\nimport {\n aiBuildCreditRange,\n aiBuildFirstPagePlan,\n aiBuildRetryLedger,\n aiBuildUnits,\n aiLedgerUnits,\n} from '../model/ai-build-job'\nimport { aiCreditsConfirmation, type AiCreditsPrompt } from '../model/ai-credit-estimate'\nimport { aiJobInputProblems } from '../model/ai-job-input'\nimport { aiSiteImportFinishUpdate } from '../model/ai-site-import'\nimport { FREE_AI_TASTE_CREDITS_PER_MONTH } from '../plan-entitlements'\nimport { aiGateLadder } from '../runtime/ai-gate'\nimport { releaseAssistMessage } from '../usage/assist-usage'\n\n/**\n * Resume a job that stopped for a person (AGL-2935): confirm its plan, or\n * try again the step whose answer broke a building rule on its re-ask — or\n * answer what a job waiting in `needs_input` asks (`input`, AGL-3978), which\n * returns it to its plan card, or a 400 with `fieldErrors` by field. An\n * import's next wave may carry the owner's Keep my site or Improve it\n * (`finish`, `wording`, AGL-4152), written after the kind's own admission and\n * only onto an import waiting for a wave that has not started.\n *\n * A door that SPENDS — the next step calls the provider — so it climbs the\n * whole ladder the create door climbs: `aiGenerative`,\n * `release_ai_generative`, the `ai-generate` switch, `ai.generate` on the\n * job's site, a per-uid window and a reservation. It then runs the next\n * step inline on that reservation, the way the create door runs the first,\n * and hands the reservation back whenever no step runs here.\n *\n * The body names the org and the job's site. A site that is not the job's\n * is refused, so a collaborator's permission on one site never confirms a\n * job on another. Audited per resume that changed something.\n */\n\nconst AI_JOBS_RESUME_RATE_LIMIT = { key: 'ai-jobs-resume', limit: 10, windowMs: 60_000 }\n\nexport async function POST(\n request: Request,\n context: { params: Promise<{ jobId: string }> },\n): Promise<Response> {\n let payload: Record<string, unknown> | null\n try {\n payload = (await request.json()) as Record<string, unknown>\n } catch {\n payload = null\n }\n const rawHost = payload?.['hostId']\n const hostId = typeof rawHost === 'string' && rawHost ? rawHost : null\n const gate = await aiGateLadder(\n { request, orgId: String(payload?.['orgId'] ?? ''), hostId },\n {\n feature: 'aiGenerative',\n releaseFlag: 'release_ai_generative',\n lockdownFeature: 'ai-generate',\n permission: 'ai.generate',\n rateLimit: AI_JOBS_RESUME_RATE_LIMIT,\n },\n )\n if (gate instanceof Response) return gate\n // No token is spent until a step runs, so every exit before one hands the\n // message back.\n const release = () =>\n releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(() => undefined)\n\n const { jobId } = await context.params\n const existing = await getAiJob(gate.firestore, gate.orgId, jobId)\n if (!existing) {\n await release()\n return Response.json({ error: 'Unknown job' }, { status: 404 })\n }\n if ((existing.hostId ?? null) !== hostId) {\n await release()\n return Response.json({ error: 'That job belongs to another site' }, { status: 400 })\n }\n // Keep my site or Improve it (AGL-4152): one of the two, and the wording switch on or off.\n const rawFinish = payload?.['finish']\n const rawWording = payload?.['wording']\n if ((rawFinish !== undefined && rawFinish !== 'keep' && rawFinish !== 'improve') || (rawWording !== undefined && typeof rawWording !== 'boolean')) {\n await release()\n return Response.json({ error: 'Choose Keep my site or Improve it.', job: aiJobSummary(existing, new Date()) }, { status: 400 })\n }\n // \"Build what fits\" (AGL-3722): a Free job past what is left, started on\n // the person's go-ahead, which the job keeps.\n const creditsConfirmed = payload?.['creditsConfirmed'] === true\n let confirmedCredits: AiCreditsPrompt | null = null\n const onCreditsConfirmed = (prompt: AiCreditsPrompt) => {\n confirmedCredits = prompt\n }\n // \"Build the home page first\" (AGL-3722): the plan waiting for its\n // confirmation narrowed to its home page and what that page needs.\n const reduceToFirstPage =\n payload?.['reduce'] === 'first-page' && existing.kind === 'build' && existing.status === 'needs_review'\n const reduced = reduceToFirstPage && existing.plan ? aiBuildFirstPagePlan(existing.plan) : null\n if (reduceToFirstPage && !reduced) {\n await release()\n return Response.json(\n { error: 'This plan has no smaller first build', job: aiJobSummary(existing, new Date()) },\n { status: 409 },\n )\n }\n // A refusal as the door answers it: a Free job past what is left carries\n // its prompt, and a plan card the figures it should now show.\n const refused = async (refusal: AiJobAdmissionRefusal) => {\n await release()\n const now = new Date()\n const summary = aiJobSummary(existing, now)\n const fresh = refusal.credits\n ? { left: refusal.credits.left, total: FREE_AI_TASTE_CREDITS_PER_MONTH, resetsOn: refusal.credits.resetsOn }\n : null\n const job = fresh && summary.review ? { ...summary, review: { ...summary.review, freeCredits: fresh } } : summary\n return Response.json(\n {\n error: refusal.error,\n ...(refusal.code ? { code: refusal.code } : {}),\n ...(refusal.credits ? { credits: refusal.credits } : {}),\n job,\n },\n { status: refusal.status },\n )\n }\n // Try again on a build (AGL-3616): its failed items and what they left\n // unbuilt, never what succeeded, and never its plan again.\n const retryFailedItems = payload?.['retry'] === 'failed-items'\n if (retryFailedItems) {\n const refusal = await aiBuildRetryRefusal(gate, existing, { confirmed: creditsConfirmed, onCreditsConfirmed }).catch(\n (error: unknown) => {\n console.error('ai build retry admission failed', { orgId: gate.orgId, jobId, error })\n return { status: 500 as const, error: 'The AI job could not be resumed' }\n },\n )\n if (refusal) {\n if (refusal.status === 500) {\n await release()\n return Response.json({ error: refusal.error, job: aiJobSummary(existing, new Date()) }, { status: 500 })\n }\n return refused(refusal)\n }\n }\n // A job waiting for a person's answer (AGL-3978): every field must read\n // before anything changes, and a refusal names each field it is about.\n const answering = existing.status === 'needs_input' && Boolean(existing.input?.fields?.length)\n const rawInput = payload?.['input']\n const answers = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput) ? (rawInput as Record<string, unknown>) : null\n if (answering && existing.input) {\n const fieldErrors = aiJobInputProblems(existing.input, answers)\n const first = Object.values(fieldErrors)[0]\n if (first) {\n await release()\n return Response.json({ error: first, fieldErrors, job: aiJobSummary(existing, new Date()) }, { status: 400 })\n }\n }\n // A confirmed plan runs the step that writes, and an allowance free when the\n // job was created may be used by now (AGL-2909): the kind is asked again\n // before anything runs, and a refusal leaves the job waiting for review.\n if (existing.status === 'needs_review') {\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>>\n try {\n // A site that switched AI off first (AGL-3028), then the kind's own check.\n refusal =\n (await aiJobSiteRefusal({\n firestore: gate.firestore,\n org: gate.org,\n hostId: existing.hostId ?? null,\n })) ??\n (await aiJobAdmissionRefusal(existing.kind, {\n firestore: gate.firestore,\n orgId: gate.orgId,\n hostId: existing.hostId ?? null,\n inputs: existing.inputs ?? {},\n org: gate.org,\n // The plan being confirmed, for a kind that builds only some plans —\n // the smaller first build where the person chose it (AGL-3722).\n plan: reduced ?? existing.plan ?? null,\n uid: gate.uid,\n creditsConfirmed,\n onCreditsConfirmed,\n }))\n } catch (error) {\n await release()\n console.error('ai job admission failed', { orgId: gate.orgId, jobId, error })\n return Response.json({ error: 'The AI job could not be resumed' }, { status: 500 })\n }\n if (refusal) return refused(refusal)\n }\n // \"Start every remaining wave\" (AGL-4084): an import waiting for its next\n // wave starts every one left, with no review between them.\n const startAll =\n payload?.['startAll'] === true && existing.kind === 'import'\n ? (await import('../jobs/ai-job-import-step')).aiSiteImportStartAllUpdate(existing)\n : null\n // Keep my site or Improve it (AGL-4152), changed before a wave: the waves\n // not yet started are built the new way, and a wave already in never is.\n const finish = rawFinish === 'keep' || rawFinish === 'improve' ? rawFinish : null\n const choosing = finish !== null || typeof rawWording === 'boolean'\n const finishUpdate = choosing ? aiSiteImportFinishUpdate(existing, { finish, wording: typeof rawWording === 'boolean' ? rawWording : null }) : null\n if (startAll || finishUpdate) {\n await gate.firestore\n .collection('orgs')\n .doc(gate.orgId)\n .collection(AI_JOBS_COLLECTION)\n .doc(jobId)\n .update({ ...(startAll ?? {}), ...(finishUpdate ?? {}) })\n }\n const now = new Date()\n const confirmation = aiCreditsConfirmation(confirmedCredits, gate.uid, now)\n const { job, changed } = retryFailedItems\n ? await retryAiBuildJob(gate.firestore, gate.orgId, jobId, now, { creditsConfirmed: confirmation })\n : await resumeAiJob(gate.firestore, gate.orgId, jobId, { uid: gate.uid }, now, {\n publishConfirmed: payload?.['publish'] === true,\n creditsConfirmed: confirmation,\n ...(reduced ? { reducePlan: aiBuildFirstPagePlan } : {}),\n ...(answering ? { input: answers } : {}),\n })\n if (!changed) {\n await release()\n return Response.json(\n { error: 'This job is not waiting for review', job: aiJobSummary(job, now) },\n { status: 409 },\n )\n }\n await writeAiJobAudit(gate.firestore, {\n action: 'ai.job.resume',\n actorUid: gate.uid,\n actorEmail: gate.decoded.email ?? null,\n orgId: gate.orgId,\n jobId,\n after: {\n status: job.status,\n reason: retryFailedItems ? 'retry-failed-items' : answering ? 'input' : (existing.review?.reason ?? null),\n kind: existing.kind,\n ...(finishUpdate ? { finish: finishUpdate['siteImport.finish'], wording: finishUpdate['siteImport.wording'] } : {}),\n },\n })\n if (job.status !== 'queued') {\n await release()\n return Response.json({ job: aiJobSummary(job, now) }, { status: 200 })\n }\n // A step that needs more time than this request has (AGL-2907) is left\n // queued for the beat, which starts it with a budget of its own: a provider\n // call this request's timeout cut off would be billed upstream and metered\n // nowhere.\n if (aiJobNextStepMinimumMs(job) > AI_JOB_INLINE_BUDGET_MS) {\n await release()\n return Response.json({ job: aiJobSummary(job, now) }, { status: 200 })\n }\n\n const run = await runAiJobStep(gate.firestore, gate.orgId, jobId, {\n owner: `route:${randomUUID()}`,\n now,\n reservation: gate.reservation,\n org: gate.org,\n signal: AbortSignal.timeout(AI_JOB_INLINE_BUDGET_MS),\n actor: { uid: gate.uid, email: gate.decoded.email ?? null },\n // The workspace's AI pause lets staff through, as the ladder above did.\n staff: gate.staff,\n })\n if (run.outcome === 'not-claimable') {\n // The beat claimed the step between the resume and this run; it runs\n // there, on a reservation of its own.\n await release()\n const latest = await getAiJob(gate.firestore, gate.orgId, jobId)\n return Response.json({ job: aiJobSummary(latest ?? job, now) }, { status: 200 })\n }\n return Response.json({ job: aiJobSummary(run.job) }, { status: 200 })\n}\n\n/**\n * Why a build's Try again cannot run (AGL-3616), or `null`: it is not a\n * finished build, the site switched AI off, or — on the Free taste — the\n * month's Free credits do not cover what the retried items are estimated at.\n */\nasync function aiBuildRetryRefusal(\n gate: { firestore: FirebaseFirestore.Firestore; orgId: string; org: object | null },\n job: AiJob,\n credits: { confirmed: boolean; onCreditsConfirmed: (prompt: AiCreditsPrompt) => void },\n): Promise<AiJobAdmissionRefusal | null> {\n const plan = job.plan?.status === 'confirmed' ? job.plan : null\n if (!aiBuildRetryable(job) || !plan || !job.items?.length) {\n return { status: 409, error: 'Only a finished build can try its failed items again' }\n }\n const site = await aiJobSiteRefusal({ firestore: gate.firestore, org: gate.org, hostId: job.hostId ?? null })\n if (site) return site\n const { retried } = aiBuildRetryLedger(job.items, job.kind === 'site' ? aiLedgerUnits(job.items) : aiBuildUnits(plan))\n if (!retried.length) return { status: 409, error: 'Nothing in this build is left to try again' }\n // A site's retried parts are its own pages and creations, held by the\n // reservation each pass takes; a build's are admitted on their measured p90\n // against the Free taste, or on the person's go-ahead (AGL-3722).\n if (job.kind === 'site' || !aiBuildFreeTaste(gate.org)) return null\n return aiBuildFreeCreditsRefusal({\n firestore: gate.firestore,\n orgId: gate.orgId,\n org: gate.org,\n range: aiBuildCreditRange(plan, { slots: new Set(retried) }),\n confirmed: credits.confirmed,\n onConfirmed: credits.onCreditsConfirmed,\n now: new Date(),\n })\n}\n\nexport const dynamic = 'force-dynamic'\nexport const maxDuration = 60\n"],"names":["randomUUID","aiJobAdmissionRefusal","aiJobSiteRefusal","AI_JOB_INLINE_BUDGET_MS","AI_JOBS_COLLECTION","aiJobNextStepMinimumMs","aiJobSummary","getAiJob","aiBuildRetryable","resumeAiJob","retryAiBuildJob","runAiJobStep","writeAiJobAudit","aiBuildFreeCreditsRefusal","aiBuildFreeTaste","aiBuildCreditRange","aiBuildFirstPagePlan","aiBuildRetryLedger","aiBuildUnits","aiLedgerUnits","aiCreditsConfirmation","aiJobInputProblems","aiSiteImportFinishUpdate","FREE_AI_TASTE_CREDITS_PER_MONTH","aiGateLadder","releaseAssistMessage","AI_JOBS_RESUME_RATE_LIMIT","key","limit","windowMs","POST","request","context","existing","gate","payload","json","rawHost","hostId","orgId","String","feature","releaseFlag","lockdownFeature","permission","rateLimit","Response","release","firestore","reservation","catch","undefined","jobId","params","error","status","rawFinish","rawWording","job","Date","creditsConfirmed","confirmedCredits","onCreditsConfirmed","prompt","reduceToFirstPage","kind","reduced","plan","refused","refusal","now","summary","fresh","credits","left","total","resetsOn","review","freeCredits","code","retryFailedItems","aiBuildRetryRefusal","confirmed","console","answering","Boolean","input","fields","length","rawInput","answers","Array","isArray","fieldErrors","first","Object","values","org","inputs","uid","startAll","aiSiteImportStartAllUpdate","finish","choosing","finishUpdate","wording","collection","doc","update","confirmation","changed","publishConfirmed","reducePlan","action","actorUid","actorEmail","decoded","email","after","reason","run","owner","signal","AbortSignal","timeout","actor","staff","outcome","latest","items","site","retried","range","slots","Set","onConfirmed","dynamic","maxDuration"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,+DAA+D;AAC/D,sEAAsE;AAEtE,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,qBAAqB,EAAEC,gBAAgB,QAAoC,8BAA0B;AAC9G,SACEC,uBAAuB,EACvBC,kBAAkB,EAClBC,sBAAsB,EACtBC,YAAY,EACZC,QAAQ,EACRC,gBAAgB,EAChBC,WAAW,EACXC,eAAe,EACfC,YAAY,EACZC,eAAe,QACV,qBAAiB;AAExB,SAASC,yBAAyB,EAAEC,gBAAgB,QAAQ,+BAA2B;AACvF,SACEC,kBAAkB,EAClBC,oBAAoB,EACpBC,kBAAkB,EAClBC,YAAY,EACZC,aAAa,QACR,2BAAu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jC,QAAQ;YAAKD,OAAO;QAAuD;IACtF;IACA,MAAM4E,OAAO,MAAMhI,iBAAiB;QAAE8C,WAAWd,KAAKc,SAAS;QAAEiD,KAAK/D,KAAK+D,GAAG;QAAE3D,MAAM,GAAEoB,cAAAA,IAAIpB,MAAM,YAAVoB,cAAc;IAAK;IAC3G,IAAIwE,MAAM,OAAOA;IACjB,MAAM,EAAEC,OAAO,EAAE,GAAGlH,mBAAmByC,IAAIuE,KAAK,EAAEvE,IAAIO,IAAI,KAAK,SAAS9C,cAAcuC,IAAIuE,KAAK,IAAI/G,aAAaiD;IAChH,IAAI,CAACgE,QAAQ3C,MAAM,EAAE,OAAO;QAAEjC,QAAQ;QAAKD,OAAO;IAA6C;IAC/F,sEAAsE;IACtE,4EAA4E;IAC5E,kEAAkE;IAClE,IAAII,IAAIO,IAAI,KAAK,UAAU,CAACnD,iBAAiBoB,KAAK+D,GAAG,GAAG,OAAO;IAC/D,OAAOpF,0BAA0B;QAC/BmC,WAAWd,KAAKc,SAAS;QACzBT,OAAOL,KAAKK,KAAK;QACjB0D,KAAK/D,KAAK+D,GAAG;QACbmC,OAAOrH,mBAAmBoD,MAAM;YAAEkE,OAAO,IAAIC,IAAIH;QAAS;QAC1DjD,WAAWT,QAAQS,SAAS;QAC5BqD,aAAa9D,QAAQX,kBAAkB;QACvCQ,KAAK,IAAIX;IACX;AACF;AAEA,OAAO,MAAM6E,UAAU,gBAAe;AACtC,OAAO,MAAMC,cAAc,GAAE"}
|
|
@@ -15,8 +15,8 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import { type AiSiteImportDocument } from '../../jobs/ai-site-import-document';
|
|
18
|
-
import { type SiteImportFooter, type SiteImportNavTree } from '../../model/ai-site-import';
|
|
19
|
-
import type
|
|
18
|
+
import { type AiSiteImportFinish, type AiSiteImportWords, type SiteImportFooter, type SiteImportNavTree } from '../../model/ai-site-import';
|
|
19
|
+
import { type SiteImportFidelitySource, type SiteImportFidelityTheme, type SiteImportFidelityTree } from '../../model/ai-site-import-fidelity';
|
|
20
20
|
import { type SiteLayoutPageName } from './site-layout-recordings';
|
|
21
21
|
/** A recorded page as a wave's read keeps it and the import step hands it on: its blocks, its layout, its photos in the library. */
|
|
22
22
|
export declare function siteImportReplayDocument(name: SiteLayoutPageName): AiSiteImportDocument;
|
|
@@ -27,21 +27,47 @@ export interface SiteImportReplayPage {
|
|
|
27
27
|
tree: SiteImportFidelityTree;
|
|
28
28
|
violations: unknown[];
|
|
29
29
|
}
|
|
30
|
+
/** A recorded rewrite of one line of a page (AGL-4152, lane G), in the shape `submit_wording` answers: the line's index in the page's blocks, and its new words. */
|
|
31
|
+
export interface SiteImportReplayRewrite {
|
|
32
|
+
line: number;
|
|
33
|
+
text: string;
|
|
34
|
+
}
|
|
35
|
+
/** How a recorded page is built: its design answer, the site's forms, and how it is finished. */
|
|
36
|
+
export interface SiteImportReplayOptions {
|
|
37
|
+
answer?: Record<string, unknown> | null;
|
|
38
|
+
forms?: Array<{
|
|
39
|
+
id: string;
|
|
40
|
+
name: string;
|
|
41
|
+
}>;
|
|
42
|
+
layout?: boolean;
|
|
43
|
+
/** Keep my site or Improve it (AGL-4152), on the page's document as its wave stamps it; absent, the document names none. */
|
|
44
|
+
finish?: AiSiteImportFinish;
|
|
45
|
+
/** Whether its words are kept or improved (AGL-4152), on its document. */
|
|
46
|
+
words?: AiSiteImportWords;
|
|
47
|
+
/** Recorded rewrites of its lines (lane G): the page is built in them, and scored against the words as its source wrote them. */
|
|
48
|
+
wording?: readonly SiteImportReplayRewrite[];
|
|
49
|
+
}
|
|
30
50
|
/**
|
|
31
51
|
* A recorded page built and checked as the page step stores it (AGL-4109):
|
|
32
52
|
* with a recorded design `answer`, as a main page is arranged, or with none,
|
|
33
53
|
* as a page is drawn from its layout alone; `forms` are the site's saved
|
|
34
54
|
* forms. `layout: false` builds it as a read with no layout was built, one
|
|
35
55
|
* section at each second-level heading, as the 10/29 import did.
|
|
56
|
+
*
|
|
57
|
+
* `finish` and `words` (AGL-4152) ride the page's document as a wave stamps
|
|
58
|
+
* them, so the compile builds it as that finish asks wherever it reads them;
|
|
59
|
+
* `wording` builds it in recorded rewrites of its lines, while its source
|
|
60
|
+
* keeps the words as written.
|
|
36
61
|
*/
|
|
37
|
-
export declare function siteImportReplayPage(name: SiteLayoutPageName, options?:
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
62
|
+
export declare function siteImportReplayPage(name: SiteLayoutPageName, options?: SiteImportReplayOptions): SiteImportReplayPage;
|
|
63
|
+
/**
|
|
64
|
+
* The theme a recorded page is drawn in (AGL-4152): no site stores one, so
|
|
65
|
+
* it is computed as the look pass draws it, from the page's own look facts
|
|
66
|
+
* with the import's seed and no inspiration site, over the platform's
|
|
67
|
+
* default theme, and is marked as computed from the site style. `finish` is handed to the
|
|
68
|
+
* look's style as the pass hands it, for the pass that reads it.
|
|
69
|
+
*/
|
|
70
|
+
export declare function siteImportReplayTheme(name: SiteLayoutPageName, finish?: AiSiteImportFinish): SiteImportFidelityTheme | null;
|
|
45
71
|
/**
|
|
46
72
|
* The design answer recorded for aglyn.com's Home, in the tool's shape: a
|
|
47
73
|
* split hero, ruled cards, a dark band asked where the source drew its own
|
|
@@ -24,13 +24,17 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
|
|
|
24
24
|
* on its own site is a page the import plans, as on a whole-site import. No
|
|
25
25
|
* live AI: a design answer here is a recorded one, in the shape the tool
|
|
26
26
|
* answers.
|
|
27
|
-
*/ import {
|
|
27
|
+
*/ import { DEFAULT_SITE_THEME } from "@aglyn/aglyn/app-utils/default-site";
|
|
28
|
+
import { aiImportedPageCheck } from "../../jobs/ai-job-page-language.js";
|
|
28
29
|
import { aiSiteImportFrameJob, aiSiteImportHomeOf } from "../../jobs/ai-job-import-step.js";
|
|
29
30
|
import { aiLayoutSiteBrandOf, aiLayoutSiteFrameOf, aiLayoutSourceFrameBuild } from "../../jobs/ai-job-layout-language.js";
|
|
30
31
|
import { aiLayoutChecks } from "../../jobs/ai-job-layout-step.js";
|
|
31
32
|
import { aiSiteImportSectionNames } from "../../jobs/ai-site-import-compile.js";
|
|
32
33
|
import { AI_LAYOUT_IMPORTED_SECTIONS_INPUT, aiSiteImportDocumentOf } from "../../jobs/ai-site-import-document.js";
|
|
34
|
+
import { aiSiteImportStyle } from "../../jobs/ai-site-import-look.js";
|
|
33
35
|
import { aiSiteImportLedger } from "../../model/ai-site-import.js";
|
|
36
|
+
import { siteImportFidelityThemeOf } from "../../model/ai-site-import-fidelity.js";
|
|
37
|
+
import { aiSiteTheme } from "../../model/ai-site-look.js";
|
|
34
38
|
import { emptyAiSiteInventory } from "../../model/ai-site-inventory.js";
|
|
35
39
|
import { extractSiteImportPage } from "../site-import-html.js";
|
|
36
40
|
import { siteImportLayout, siteImportLookOf } from "../site-import-layout.js";
|
|
@@ -108,17 +112,37 @@ import { SITE_LAYOUT_PAGES, siteLayoutRecording, siteLayoutSameSite } from "./si
|
|
|
108
112
|
* as a page is drawn from its layout alone; `forms` are the site's saved
|
|
109
113
|
* forms. `layout: false` builds it as a read with no layout was built, one
|
|
110
114
|
* section at each second-level heading, as the 10/29 import did.
|
|
115
|
+
*
|
|
116
|
+
* `finish` and `words` (AGL-4152) ride the page's document as a wave stamps
|
|
117
|
+
* them, so the compile builds it as that finish asks wherever it reads them;
|
|
118
|
+
* `wording` builds it in recorded rewrites of its lines, while its source
|
|
119
|
+
* keeps the words as written.
|
|
111
120
|
*/ export function siteImportReplayPage(name, options = {}) {
|
|
112
|
-
var _options_forms, _options_answer, _ref;
|
|
121
|
+
var _options_wording, _options_forms, _options_answer, _ref;
|
|
113
122
|
var _result_value;
|
|
114
123
|
const read = siteImportReplayDocument(name);
|
|
115
124
|
const { layout } = read, rest = _object_without_properties_loose(read, [
|
|
116
125
|
"layout"
|
|
117
126
|
]);
|
|
127
|
+
const rewrites = new Map(((_options_wording = options.wording) != null ? _options_wording : []).map((rewrite)=>[
|
|
128
|
+
rewrite.line,
|
|
129
|
+
rewrite.text
|
|
130
|
+
]));
|
|
131
|
+
const finished = _extends({}, options.finish ? {
|
|
132
|
+
finish: options.finish
|
|
133
|
+
} : {}, options.words ? {
|
|
134
|
+
wording: options.words
|
|
135
|
+
} : {});
|
|
136
|
+
const given = _extends({}, options.layout === false ? rest : read, finished, {
|
|
137
|
+
blocks: read.blocks.map((block, index)=>rewrites.has(index) && block.kind !== 'image' ? _extends({}, block, {
|
|
138
|
+
text: rewrites.get(index)
|
|
139
|
+
}) : block)
|
|
140
|
+
});
|
|
118
141
|
// As the page step reads it: through the job's input, so a fact the reader drops is dropped here too (AGL-4138).
|
|
119
|
-
const
|
|
120
|
-
[AI_LAYOUT_IMPORTED_SECTIONS_INPUT]: JSON.parse(JSON.stringify(
|
|
142
|
+
const parsed = aiSiteImportDocumentOf({
|
|
143
|
+
[AI_LAYOUT_IMPORTED_SECTIONS_INPUT]: JSON.parse(JSON.stringify(given))
|
|
121
144
|
});
|
|
145
|
+
const doc = _extends({}, parsed, finished);
|
|
122
146
|
const names = aiSiteImportSectionNames(doc);
|
|
123
147
|
const sectionIds = names.map((_, index)=>`sec-${index}`);
|
|
124
148
|
const screen = {
|
|
@@ -173,6 +197,26 @@ import { SITE_LAYOUT_PAGES, siteLayoutRecording, siteLayoutSameSite } from "./si
|
|
|
173
197
|
violations: result.violations
|
|
174
198
|
};
|
|
175
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* The theme a recorded page is drawn in (AGL-4152): no site stores one, so
|
|
202
|
+
* it is computed as the look pass draws it, from the page's own look facts
|
|
203
|
+
* with the import's seed and no inspiration site, over the platform's
|
|
204
|
+
* default theme, and is marked as computed from the site style. `finish` is handed to the
|
|
205
|
+
* look's style as the pass hands it, for the pass that reads it.
|
|
206
|
+
*/ export function siteImportReplayTheme(name, finish) {
|
|
207
|
+
var _ref;
|
|
208
|
+
var _read_layout;
|
|
209
|
+
const read = siteImportReplayDocument(name);
|
|
210
|
+
const input = _extends({
|
|
211
|
+
seed: 7,
|
|
212
|
+
description: read.title,
|
|
213
|
+
facts: (_ref = (_read_layout = read.layout) == null ? void 0 : _read_layout.look) != null ? _ref : null
|
|
214
|
+
}, finish ? {
|
|
215
|
+
finish
|
|
216
|
+
} : {});
|
|
217
|
+
const style = aiSiteImportStyle(null, input);
|
|
218
|
+
return style ? siteImportFidelityThemeOf(aiSiteTheme(style, DEFAULT_SITE_THEME), 'style') : null;
|
|
219
|
+
}
|
|
176
220
|
/**
|
|
177
221
|
* The design answer recorded for aglyn.com's Home, in the tool's shape: a
|
|
178
222
|
* split hero, ruled cards, a dark band asked where the source drew its own
|