@aglyn/plugins-ai 1.0.0-beta.293 → 1.0.0-beta.296

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-job-links.d.ts +15 -2
  3. package/src/lib/components/ai-job-links.js +24 -3
  4. package/src/lib/components/ai-job-links.js.map +1 -1
  5. package/src/lib/components/ai-job-requests.d.ts +9 -0
  6. package/src/lib/components/ai-job-requests.js +34 -0
  7. package/src/lib/components/ai-job-requests.js.map +1 -1
  8. package/src/lib/components/ai-site-build-page.component.js +28 -2
  9. package/src/lib/components/ai-site-build-page.component.js.map +1 -1
  10. package/src/lib/components/assist-jobs-drawer.component.d.ts +7 -1
  11. package/src/lib/components/assist-jobs-drawer.component.js +20 -6
  12. package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
  13. package/src/lib/components/assist-page-change-card.component.d.ts +44 -0
  14. package/src/lib/components/assist-page-change-card.component.js +166 -0
  15. package/src/lib/components/assist-page-change-card.component.js.map +1 -0
  16. package/src/lib/components/assist-panel.component.d.ts +105 -1
  17. package/src/lib/components/assist-panel.component.js +224 -29
  18. package/src/lib/components/assist-panel.component.js.map +1 -1
  19. package/src/lib/jobs/ai-job-edit-step.d.ts +62 -16
  20. package/src/lib/jobs/ai-job-edit-step.js +172 -61
  21. package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
  22. package/src/lib/jobs/ai-job-navigation-step.js +4 -2
  23. package/src/lib/jobs/ai-job-navigation-step.js.map +1 -1
  24. package/src/lib/model/ai-edit-job.d.ts +33 -16
  25. package/src/lib/model/ai-edit-job.js +50 -34
  26. package/src/lib/model/ai-edit-job.js.map +1 -1
  27. package/src/lib/model/ai-job-activity.d.ts +6 -11
  28. package/src/lib/model/ai-job-activity.js +8 -15
  29. package/src/lib/model/ai-job-activity.js.map +1 -1
  30. package/src/lib/model/ai-jobs.types.d.ts +6 -0
  31. package/src/lib/model/ai-jobs.types.js.map +1 -1
  32. package/src/lib/model/ai-site-inventory.d.ts +6 -0
  33. package/src/lib/model/ai-site-inventory.js.map +1 -1
  34. package/src/lib/model/assist-edit.d.ts +18 -1
  35. package/src/lib/model/assist-edit.js +7 -0
  36. package/src/lib/model/assist-edit.js.map +1 -1
  37. package/src/lib/model/assist-page-change.d.ts +86 -0
  38. package/src/lib/model/assist-page-change.js +86 -0
  39. package/src/lib/model/assist-page-change.js.map +1 -0
  40. package/src/lib/runtime/ai-eval.js +3 -1
  41. package/src/lib/runtime/ai-eval.js.map +1 -1
  42. package/src/lib/runtime/ai-node-tree.d.ts +5 -0
  43. package/src/lib/runtime/ai-node-tree.js +18 -3
  44. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  45. package/src/lib/runtime/site-inventory.d.ts +8 -1
  46. package/src/lib/runtime/site-inventory.js +18 -0
  47. package/src/lib/runtime/site-inventory.js.map +1 -1
  48. package/src/lib/server/assist-build.js +2 -0
  49. package/src/lib/server/assist-build.js.map +1 -1
  50. package/src/lib/server/assist-chat.js +51 -2
  51. package/src/lib/server/assist-chat.js.map +1 -1
  52. package/src/lib/server/assist-edit.d.ts +54 -2
  53. package/src/lib/server/assist-edit.js +219 -30
  54. package/src/lib/server/assist-edit.js.map +1 -1
  55. package/src/lib/server/assist-page-change.d.ts +62 -0
  56. package/src/lib/server/assist-page-change.js +140 -0
  57. package/src/lib/server/assist-page-change.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-jobs.types.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ITimestamp } from '@aglyn/shared-util-timestamp'\nimport type { AiEffort } from '../providers/contract'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport type { AiBuildPlan } from './ai-build-plan'\nimport type { AiFreeCreditsLeft } from './ai-site-job'\nimport type { AiJobCreditsConfirmation } from './ai-credit-estimate'\nimport type { AiSiteImportState } from './ai-site-import'\nimport type { AiSitePhotos } from './ai-site-photos'\nimport type { AiSiteInspiration } from '../jobs/ai-site-inspiration-signals'\n\n/**\n * AI generation jobs (AGL-2904).\n *\n * A job is one customer brief carried through one or more model steps by a\n * Firestore state machine, so that work longer than a request can survive\n * the request: the console route runs what it can inline, and the platform\n * job beat resumes whatever is left. The document is the whole state — no\n * process holds anything the next beat cannot read back.\n *\n * ── Outputs are drafts, never a publish ──────────────────────────────────\n *\n * Every output a job produces is a NEW draft or a new unpublished version of\n * an existing resource. A job never flips a version pointer, never registers\n * a route and never sends anything; a person opens the draft the job names\n * and publishes it through the door that already exists for that resource.\n * That is what lets a job run with no visitor, no session and no confirm\n * gate — the thing it writes cannot be seen by anyone but the workspace\n * until a member chooses otherwise.\n *\n * ── The lease ────────────────────────────────────────────────────────────\n *\n * A step runs under a lease: an owner id and an `until` instant. Two beats\n * fire a minute apart against a 120 s function timeout, and a console route\n * may still be running the first step when the first beat looks, so the\n * lease is what stops the same step being run — and metered — twice. A\n * claim is a transaction that refuses while another owner's lease is live;\n * an expired lease is simply claimable, which is also how a step abandoned\n * by a frozen process is recovered.\n */\n\n/**\n * What a job produces. `text` and `theme` have runners; every other kind is\n * registered and refuses with \"not available yet\" until its own issue lands,\n * so a kind's presence in the union says the job model accepts it, not that\n * a runner exists.\n */\nexport type AiJobKind =\n | 'page'\n | 'component'\n | 'layout'\n | 'template'\n | 'edit'\n | 'seo'\n | 'site'\n | 'email'\n | 'campaign'\n | 'form'\n | 'experiment'\n | 'insight'\n | 'products'\n | 'crm'\n | 'onboarding'\n | 'workflow'\n | 'logic'\n | 'text'\n | 'theme'\n | 'build'\n /** A change to a site's header or footer menu, made by code (AGL-3728). */\n | 'navigation'\n /** A copy of something a site already has, made by core's duplicate (AGL-3740). */\n | 'duplicate'\n /** A change to a site's settings, made by code and saved live (AGL-3748). */\n | 'settings'\n /** Folders, tags, alt text and names in a site's media library, made by code and saved live (AGL-3752). */\n | 'media'\n /** A change to a site's analytics and advertising tags, made by code and saved live (AGL-3751). */\n | 'tracking'\n /** A change to who can see a site — maintenance mode, search indexing, page visibility — made by code and saved live (AGL-4033). */\n | 'privacy'\n /** A person's own website brought in, page by page, in reviewed waves (AGL-3976). */\n | 'import'\n\n/** The union as a value, so a route can validate a body against it. */\nexport const AI_JOB_KINDS: readonly AiJobKind[] = [\n 'page',\n 'component',\n 'layout',\n 'template',\n 'edit',\n 'seo',\n 'site',\n 'email',\n 'campaign',\n 'form',\n 'experiment',\n 'insight',\n 'products',\n 'crm',\n 'onboarding',\n 'workflow',\n 'logic',\n 'text',\n 'theme',\n 'build',\n 'navigation',\n 'duplicate',\n 'settings',\n 'media',\n 'tracking',\n 'privacy',\n 'import',\n]\n\n/**\n * `queued` — waiting for a runner; `running` — a step holds the lease;\n * `needs_input` — the job stopped for something only the workspace can\n * change (credits, a cap, a switch), and the beat tries it again once that\n * may have changed — or, carrying `input`, for an answer only the person can\n * give (AGL-3978), which the beat leaves alone; `needs_review` — the job stopped for a person's decision\n * (AGL-2935): its plan is ready to confirm, or an answer broke a building\n * rule on its re-ask. No timer can make that decision, so neither the beat\n * nor anything but that person resumes it. The last three are terminal.\n */\nexport type AiJobStatus =\n | 'queued'\n | 'running'\n | 'needs_input'\n | 'needs_review'\n | 'done'\n | 'failed'\n | 'canceled'\n\nexport const AI_JOB_TERMINAL_STATUSES: readonly AiJobStatus[] = [\n 'done',\n 'failed',\n 'canceled',\n]\n\nexport type AiJobStepStatus = 'pending' | 'running' | 'done' | 'failed'\n\n/** The step a planned kind runs first (AGL-2935): its plan, before anything is built. */\nexport const AI_JOB_PLAN_STEP = 'plan'\n\nexport interface AiJobStep {\n /** Stable within the job (`plan`, `draft`, `generate`), unique per job. */\n name: string\n status: AiJobStepStatus\n startedAt?: ITimestamp | null\n endedAt?: ITimestamp | null\n /** Credits this step has actually cost, at the plan's credit rate. */\n creditsSpent: number\n /** Customer-safe only; provider detail goes to the server log. */\n error?: string | null\n /**\n * How many times a runner has been handed this step. A retryable provider\n * failure hands the step back as `pending`; the count is what stops a\n * provider outage re-running a step forever.\n */\n attempts?: number\n /**\n * Passes of a step that works through a list (AGL-2910): each one a\n * recorded, metered exchange that asked to continue. Attempts count again\n * from zero after a pass; this count is what bounds the step.\n */\n passes?: number\n /**\n * What the step's model calls cost in tokens and time (AGL-2937), summed\n * over every run that reached the provider. Absent on a step none has.\n */\n tokens?: AiJobStepTokens\n /**\n * The ids the step writes its drafts under, by draft (AGL-3079): minted\n * when the job is created, so every run of the step names the same drafts.\n * Absent on a step that writes none; a step that records none names its\n * drafts by the job's own id.\n */\n draftIds?: Partial<Record<AiJobDraftSlot, string>>\n}\n\n/**\n * A draft a job's kind always writes (AGL-3079): a screen, layout, template,\n * form or component; an email design; a campaign; an automation.\n */\nexport type AiJobDraftSlot =\n | 'screen'\n | 'layout'\n | 'template'\n | 'form'\n | 'component'\n | 'email'\n | 'campaign'\n | 'workflow'\n\n/**\n * A step's measure (AGL-2937): the four token counts the meter prices, the\n * time spent in the runner, and the model and thinking effort of the last\n * run. The machine writes it beside `creditsSpent`, so what a kind of step\n * costs in tokens is read off the job rather than inferred from the month.\n */\nexport interface AiJobStepTokens {\n /** Prompt tokens sent uncached. */\n input: number\n /** Prompt tokens read from the prompt cache. */\n cachedRead: number\n /** Prompt tokens written to the prompt cache. */\n cacheWrite: number\n /** Tokens generated, thinking included. */\n output: number\n /** The model the last run was served by. */\n model: string | null\n /** The thinking effort the last run asked for; `null` when it named none. */\n effort: AiEffort | null\n /** Milliseconds spent in the runner, summed over runs. */\n latencyMs: number\n /** Runs that reached the provider. */\n runs: number\n /**\n * Why the step's latest runs stopped (AGL-3042), oldest first and the last\n * run last: each run's stop reason and the tokens it generated, so a pass\n * cut off at its ceiling reads off the job rather than out of the sums. At\n * most `AI_JOB_STEP_LAST_RUNS` are kept; absent on a step measured before.\n */\n lastRuns?: AiJobStepRunStop[]\n}\n\n/** One run of a step, by why it stopped (AGL-3042). */\nexport interface AiJobStepRunStop {\n /**\n * The stop reason of the run's last model call — `tool_use` or `end_turn`\n * for an answer, `max_tokens` for one cut off at its ceiling, `refusal` —\n * and `null` when the provider named none.\n */\n stopReason: string | null\n /** Tokens the run generated, over every model call it made. */\n output: number\n}\n\nexport type AiJobOutputResource =\n | 'screen'\n | 'reusableComponent'\n | 'layout'\n | 'template'\n | 'form'\n | 'emailScreen'\n | 'campaign'\n | 'product'\n | 'experiment'\n | 'workflow'\n | 'text'\n | 'theme'\n | 'seo'\n | 'insight'\n | 'crm'\n /** A draft another plugin wrote for a build (AGL-3616), named by `draftResource`. */\n | 'draft'\n | 'logic'\n | 'orgAutomation'\n /** A post a guided start wrote into the site's blog (AGL-3676): a content collection entry. */\n | 'entry'\n /** A site's settings a build changed (AGL-3748): saved live, on the host document. */\n | 'settings'\n /** Files in a site's media library a build organized (AGL-3752): saved live, on their documents. */\n | 'media'\n /** A site's tracking tags a build changed (AGL-3751): saved live, on the host document. */\n | 'tracking'\n /** Who can see a site, as a build changed it (AGL-4033): saved live, on the host and page documents. */\n | 'privacy'\n\n/**\n * One thing a job wrote. Addressed by resource and id so the console can\n * build the \"open draft\" link without knowing what the runner did; `text`\n * has no document of its own, so its body rides on the output itself.\n *\n * A `theme` output is a proposal rather than a document (AGL-2938). A site's\n * theme is fields on its host document, and writing those fields is the save\n * the Theme section's editor performs, which a job never does. So the change\n * set rides on the output as `proposal`, and a person puts it in the editor\n * and saves it there, or does not.\n *\n * An `seo` output is a proposal rather than a document (AGL-2910): search\n * listing values for a page or a product, or a site audit's findings and\n * fixes. A screen's listing is served from the screen document itself, so a\n * job never writes it; the values ride on the output as `proposal`, a person\n * puts them in the editor and saves them there, and an audit's content fixes\n * become new versions only when a person applies them.\n *\n * A `crm` output is a proposal too (AGL-2917): a record's summary and next\n * step, an email draft, or an import's column matches. The CRM's own task\n * form, stage route, composer and import drawer are the writes, and a person\n * makes each of them, or does not.\n *\n * A `logic` output is a proposal too (AGL-3603): a site function or variable\n * the Functions & Variables editor opens unsaved. Saving it is the editor's\n * write, which a person makes, or does not.\n *\n * An `orgAutomation` output is a proposal too (AGL-3603): one of the\n * workspace's automations, which the Org automations editor opens unsaved and\n * switched off. `hostId` is `null`: it belongs to no one site.\n */\nexport interface AiJobOutput {\n resource: AiJobOutputResource\n id: string\n /** The unpublished version the job created, where the resource has versions. */\n versionId?: string | null\n /** `null` for an output that belongs to the org rather than one site. */\n hostId: string | null\n /**\n * The site's subdomain, which is what a console URL names a site by: the\n * `[host]` segment resolves by subdomain, so a link built from `hostId`\n * names no site the console can open.\n */\n hostSubdomain?: string | null\n label: string\n /** The body of a `text` output. Absent on every other resource. */\n text?: string\n /**\n * The change set of an output a person applies rather than opens — a\n * `theme` or `seo` proposal — in the shape its job kind's runner defines.\n */\n proposal?: Record<string, unknown>\n /**\n * What the person decides next about this output, in customer-safe words:\n * a routing the draft could not store, or part of the brief it could not\n * build. Absent when there is nothing to decide.\n */\n note?: string | null\n /**\n * What a first visit is estimated to transfer, as the doctrine measured\n * the generated document (AGL-2935) — the weight the proposal shows before\n * anything is applied. Absent where the output is not a page's document.\n */\n load?: AiLoadEstimate | null\n /**\n * For a `draft` output (AGL-3616): the resource whose owner wrote it, as\n * its writer is registered on the resource-draft seam.\n */\n draftResource?: string\n}\n\nexport interface AiJobLease {\n /** The process that holds the step: a route request id or a beat id. */\n owner: string\n until: ITimestamp\n}\n\n/** Why a job stopped for a person (AGL-2935). */\nexport type AiJobReviewReason =\n /** The plan step proposed a plan; generation waits for it to be confirmed. */\n | 'plan'\n /** An answer broke a building rule, and so did the answer to the re-ask. */\n | 'doctrine'\n /**\n * The site is at an allowance its plan sets for what the step writes, such\n * as its shared layouts or its templates (AGL-2909). Freeing one, or a plan\n * that holds more, is the member's decision; trying again runs the step\n * again.\n */\n | 'limit'\n /**\n * A site import's wave is in (AGL-3976): its pages are drafts for the\n * person to review, and the next wave starts only when they say so. Or the\n * import has read the site and waits for the first wave to be started.\n */\n | 'wave'\n /**\n * A site import's next wave needs a current proof that the workspace owns\n * the site (AGL-3976): the proof is older than its 30 days, or was never\n * made. Verifying again and starting the wave runs it.\n */\n | 'ownership'\n /**\n * A site import's read found its home page turned away by the site's bot\n * protection or firewall (AGL-4083): nothing is planned or spent. Letting\n * AglynBot in and choosing Check again reads the site again.\n */\n | 'blocked'\n /**\n * A site import's read could not read its home page for any other reason\n * (AGL-4083): an error, no answer, or a page that needs a browser to show\n * its words. Nothing is planned or spent; Check again reads it again.\n */\n | 'unreadable'\n\n/**\n * A building rule an answer broke, as the job keeps it: the number, the code,\n * the sentence, and where in the answer it was broken (AGL-3078).\n */\nexport interface AiJobRuleFinding {\n rule: number | null\n code: string\n /** Customer-safe. */\n message: string\n /** The nodes the finding names, by the ids the refused answer gave them. Absent when it names none. */\n nodeIds?: string[]\n /** The plan entries or answer fields it names, as `screens[0].sections[2]`. Absent when it names none. */\n paths?: string[]\n}\n\n/**\n * One node of the parts of a refused answer its findings name (AGL-3078), as\n * the review keeps it: the node's place, its element and the names of what it\n * sets, and never its copy. A Grid keeps the values of its layout props as\n * they were written, so a review can tell a shape the rules refuse from one\n * the model was asked to mend and did not.\n */\nexport interface AiJobReviewOutlineNode {\n /** The node's id, as the refused answer wrote it. */\n id: string\n /** How far below a node a finding names it sits: 0 for that node. */\n depth: number\n componentId: string\n /** The props it sets, by name only. */\n props: string[]\n /** The `sx` keys it sets, by name only; absent when it sets none. */\n sx?: string[]\n /** A Grid's layout props, `container`, `size`, `direction`, `spacing` and the rest, as written. */\n grid?: Record<string, string | number | boolean | null>\n /** Its children's element ids, in order. */\n children: string[]\n}\n\nexport interface AiJobReview {\n reason: AiJobReviewReason\n /** Customer-safe: what the person is asked to decide. */\n message: string\n /** The rules the last answer broke; empty for a plan. */\n findings: AiJobRuleFinding[]\n /**\n * The parts of the refused answer its findings name, each node with the\n * nodes below it (AGL-3078); absent when they name none. Kept with the job\n * for diagnosis, and shown to staff.\n */\n outline?: AiJobReviewOutlineNode[]\n /**\n * The checks' own sentence, where `message` was written for the member\n * instead (AGL-3594): rule numbers and all, for staff. Its presence is what\n * tells the drawer the findings are staff reading too.\n */\n detail?: string\n /**\n * Why trying again cannot work yet (AGL-3594) — the Free allowance left is\n * less than the step can cost — or absent when it can. The button is drawn\n * disabled with this beside it.\n */\n retryRefusal?: string\n /**\n * What a Free workspace had left when a build's plan was kept (AGL-3722),\n * so its plan card says, before Confirm, whether the build fits and offers\n * the go-ahead or a smaller first build when it does not. The confirm door\n * reads what is left again; this is what the card shows.\n */\n freeCredits?: AiFreeCreditsLeft\n}\n\n/**\n * One answer a job waits for (AGL-3978): an id only the person has, which the\n * operation that needs it describes — a tracking change's Meta pixel ID.\n */\nexport interface AiJobInputField {\n /** The plan item the answer fills, by its name in the plan. */\n item: string\n /** The item's argument the answer is written to. */\n arg: string\n /** The field's label, naming the provider: \"Meta pixel ID\". */\n label: string\n /** What an answer looks like, in the words of the card that sets it: \"8–20 digits\". */\n shape: string\n /** The pattern an answer is held to, as a RegExp's source. */\n pattern: string\n}\n\n/** What a job parked `needs_input` for a person asks (AGL-3978). */\nexport interface AiJobInputRequest {\n /** Customer-safe: the question, in the operation's own words. */\n message: string\n fields: AiJobInputField[]\n}\n\nexport type AiJobPlanStatus = 'proposed' | 'confirmed'\n\n/** The plan a job builds from, as the job keeps it once its plan step proposed it. */\nexport interface AiJobPlan extends AiBuildPlan {\n status: AiJobPlanStatus\n /** Names for the inventory ids the plan references, read when it was made. */\n labels: Record<string, string>\n proposedAt: ITimestamp\n confirmedAt: ITimestamp | null\n /** The member who confirmed it. */\n confirmedBy: string | null\n /**\n * A digest of the whole request that produced this plan (AGL-2937): the\n * job's kind, site, brief and scalar inputs, the model that answered, and\n * the prompt as it was rendered — the site inventory included. A later job\n * whose request hashes the same reuses this plan rather than paying for the\n * same answer again. A hash of the request, never of the answer, and no\n * part of the brief is recoverable from it.\n */\n key?: string\n /** The job this plan was reused from, when it was not asked for again. */\n reusedFrom?: string\n /**\n * What a site start read of the sites the person likes (AGL-3975): signals\n * only, each from a closed set or a hex color, which the plan was told the\n * structure of and the look pins the style of. Absent without them.\n */\n inspiration?: AiSiteInspiration\n}\n\n/**\n * Where one item of a `build` job stands (AGL-3616). A build settles item by\n * item: a failed item gives back its own spend and the rest of the plan still\n * runs, so the job keeps one row per item, written only by the machine's\n * `recordStep` — in the same transaction as the spend it accounts for — and\n * by the resume door's retry.\n */\nexport type AiJobItemStatus = 'pending' | 'running' | 'succeeded' | 'degraded' | 'failed' | 'skipped'\n\n/** Why an item failed: a give-back reason when it was ours, else the model's refusal or a review. */\nexport type AiJobItemFailureReason =\n | 'plan-refused'\n | 'doctrine-refused'\n | 'provider'\n | 'timeout'\n | 'step-failure'\n | 'unavailable'\n | 'refused'\n | 'review'\n\nexport interface AiJobItemFailure {\n /** Whether the failure was on our side: only then is the item's spend given back. */\n ours: boolean\n reason: AiJobItemFailureReason\n /** Customer-safe. */\n message: string\n /**\n * The checks' own sentence behind a `doctrine-refused` failure (AGL-3596),\n * rule numbers and all: kept on the job for staff and debugging, never on\n * the wire a customer reads.\n */\n detail?: string\n}\n\nexport interface AiJobItemLedger {\n /** The unit's slot within the plan: `c0` a creation, `p0` a page, `i0` an item. */\n slot: string\n /** The capability operation that builds it: `page`, `form`, or an owner's op. */\n op: string\n /** What a person reads: the page's title, the creation's or item's name. */\n label: string\n status: AiJobItemStatus\n /** Bumped by Try again; the refund key names it, so each attempt gives back once. */\n attempt: number\n /** What this item's passes cost, every attempt. */\n creditsSpent: number\n /** What this attempt's passes cost so far: what a failure of this attempt gives back. */\n attemptCredits?: number\n /** What was given back for this item's failures. */\n creditsRefunded: number\n /** The key the latest give-back for this item was made under. */\n refundKey?: string\n failure?: AiJobItemFailure | null\n /** The ids of the outputs this item produced. */\n outputs: string[]\n /** The slots whose failure changed how this item was built. */\n degradedBy?: string[]\n /** Customer-safe: what the person should know about this item. */\n note?: string | null\n /**\n * When this attempt settled, as an ISO string (AGL-3596): the moment the\n * next item started, which is what its progress row counts from. Absent\n * while the item is open, and on a ledger written before it was kept.\n */\n settledAt?: string | null\n}\n\n/** Whether a build's own planning was charged or given back (AGL-3616). */\nexport interface AiJobOrchestration {\n /** What the plan step spent. */\n creditsSpent: number\n /** `charged` once anything was delivered; `refunded` when nothing was. */\n settled: 'pending' | 'charged' | 'refunded'\n}\n\nexport interface AiJob {\n $id: string\n orgId: string\n hostId?: string | null\n kind: AiJobKind\n status: AiJobStatus\n /** The customer's brief, verbatim. Expires with the document. */\n brief: string\n /** Kind-specific inputs the runner reads (a screen id to edit, a tone). */\n inputs: Record<string, unknown>\n /**\n * The model the creator picked for the job's steps (AGL-2942), or `null`\n * for Auto. Each step honors it only where the plan and the allotment\n * allowlists allow it, and runs on the routing table otherwise.\n */\n model?: string | null\n steps: AiJobStep[]\n outputs: AiJobOutput[]\n /**\n * The nominal credit figure held against the job while steps are\n * outstanding. The meter's real bound is the per-step message reservation\n * and the org's monthly ceiling; this is the number the console shows so\n * a running job is not read as free.\n */\n creditsReserved: number\n creditsSpent: number\n /**\n * Credits the job gave back because it failed on our side (AGL-3594),\n * summed over its give-backs; absent when it gave none. `creditsSpent`\n * stays what ran, so what the job cost is the one less the other.\n */\n refundedCredits?: number\n /** Why the latest give-back was made (`AiJobRefundReason`). */\n refundReason?: string\n /** How many give-backs the job has had: the next one's key. */\n refunds?: number\n createdBy: string\n createdAt: ITimestamp\n updatedAt: ITimestamp\n /** TTL — the brief is verbatim customer text and expires like an exchange. */\n expiresAt: ITimestamp\n /** Customer-safe only. */\n error?: string | null\n lease?: AiJobLease | null\n /** The plan the job builds from, once its plan step proposed one. */\n plan?: AiJobPlan | null\n /** What the person is asked to decide while the job is `needs_review`. */\n review?: AiJobReview | null\n /**\n * What the job waits for while it is `needs_input` for a person rather than\n * the meter (AGL-3978): the fields only they can fill, an id the planner\n * must never make up. Its plan and the plan's review are kept beside it,\n * and the answer returns the job to that review.\n */\n input?: AiJobInputRequest | null\n /**\n * What a person applied from the job's outputs (AGL-2910). Written by the\n * door that applied them, never by a step runner, and absent until then.\n */\n applied?: AiJobApplied | null\n /**\n * What a guided site start put live when it finished (AGL-3596): written\n * once by the site step's last pass, never by a person. Absent on every\n * other job, which leaves its pages as drafts.\n */\n sitePublish?: AiJobSitePublish | null\n /** A `build` job's items, one row each (AGL-3616); absent on every other kind. */\n items?: AiJobItemLedger[] | null\n /** A `build` job's planning spend and how it settled (AGL-3616). */\n orchestration?: AiJobOrchestration | null\n /**\n * A Free job started past what was left (AGL-3722): the person chose to\n * build what fits, knowing it pauses where the credits run out. Who, when,\n * what was left and the range they were shown; absent on every job that fit.\n */\n creditsConfirmed?: AiJobCreditsConfirmation | null\n /**\n * A person asked to stop the job (AGL-3616): written only by the cancel\n * door, in the transaction that decides it. A job no step holds ends\n * `canceled` in that same write; a job whose step holds a live lease keeps\n * running until the step finishes or aborts, and the machine ends it\n * `canceled` at its next write. Absent on a job nobody canceled.\n */\n cancelRequested?: AiJobCancelRequest | null\n /**\n * The empty site this guided start was for was removed (AGL-3936): the\n * job was cancelled or failed before it built anything, nobody chose what\n * to do next within the grace period, and the AI jobs beat deleted the\n * site. Written once, by the beat, after the site is gone. Absent on every\n * other job.\n */\n siteRemoved?: AiJobSiteRemoved | null\n /**\n * When the one reminder about a plan waiting for its confirmation went out\n * (AGL-4076), a day after the plan was ready. Written once, by the AI jobs\n * beat, in the transaction that decides to send it, and never cleared: a\n * job is reminded at most once, however many plans it waits on. Absent on\n * every job that was not reminded.\n */\n remindedAt?: ITimestamp | null\n /**\n * An `import` job's site, read and cut into waves (AGL-3976): what was\n * found, what is brought in in which wave, what was left out and why, and\n * each wave's state. Written only by the machine's `recordStep`, from what\n * the import step returns; absent on every other kind.\n */\n siteImport?: AiSiteImportState | null\n /**\n * A `site` job's pictures left on a starter photo (AGL-3988): each page\n * picture and dataset record its library could not fill in its own pass,\n * with the picks the image hosts refused. Written only by the machine's\n * `recordStep`, from what the site step returns; emptied by its late photo\n * pass before the site is published. Never on the wire. Absent on every\n * other kind.\n */\n sitePhotos?: AiSitePhotos | null\n}\n\n/** When the AI jobs beat removed a guided start's empty site, and which (AGL-3936). */\nexport interface AiJobSiteRemoved {\n at: ITimestamp\n /** The site's name as it was, for a sentence that names it. */\n name: string | null\n}\n\n/** Who asked to cancel a job, and when (AGL-3616). */\nexport interface AiJobCancelRequest {\n at: ITimestamp\n /** The member or staff account that asked; `null` when nobody was named. */\n by: string | null\n}\n\n/**\n * A guided site start's publish (AGL-3596): the pages that went live, with\n * the address each answers, and the pages that stayed drafts, each with the\n * plain sentence for why. A page that stayed a draft never fails the job.\n */\nexport interface AiJobSitePublish {\n /** The site's live address, `https://<subdomain>.aglyn.app/`; `null` when the site has no subdomain. */\n liveUrl: string | null\n published: Array<{ id: string; label: string; path: string }>\n drafts: Array<{ id: string; label: string; reason: string }>\n}\n\n/**\n * The record of an apply (AGL-2910): what became a new unpublished version,\n * and what waits in its editor for a person to save.\n */\nexport interface AiJobApplied {\n at: ITimestamp\n /** The member who applied. */\n by: string\n /** The new version opened for each resource, by resource id. */\n versions: Record<string, string>\n /** Resource ids whose proposed values wait in their editor, unsaved. */\n staged: string[]\n}\n\n/** The plan on the wire: every instant an ISO string. */\nexport interface AiJobPlanSummary extends AiBuildPlan {\n status: AiJobPlanStatus\n labels: Record<string, string>\n proposedAt: string | null\n confirmedAt: string | null\n confirmedBy: string | null\n key?: string\n reusedFrom?: string\n}\n\n/**\n * The wire form the console reads: every instant an ISO string, the lease\n * reduced to whether a runner holds the job. The brief and the outputs\n * travel as they are — the reader is a member of the org that wrote them.\n */\nexport interface AiJobSummary {\n id: string\n orgId: string\n hostId: string | null\n kind: AiJobKind\n status: AiJobStatus\n brief: string\n /**\n * The batch a door created this job as one of (AGL-2911), read off the\n * job's inputs; `null` for a job created on its own. The console groups a\n * run of jobs by it, which is the one thing it cannot do from a list whose\n * rows carry no inputs — and the only input the wire form carries, because\n * a batch id names nothing the member wrote.\n */\n batch: string | null\n steps: Array<{\n name: string\n status: AiJobStepStatus\n startedAt: string | null\n endedAt: string | null\n creditsSpent: number\n error: string | null\n }>\n outputs: AiJobOutput[]\n creditsReserved: number\n creditsSpent: number\n /** Credits given back for a failure on our side (AGL-3594); 0 when none. */\n refundedCredits?: number\n createdBy: string\n createdAt: string\n updatedAt: string\n error: string | null\n running: boolean\n plan: AiJobPlanSummary | null\n review: AiJobReview | null\n /** The fields a `needs_input` job waits for a person to fill (AGL-3978); absent otherwise. */\n input?: AiJobInputRequest | null\n /** What a person applied from the outputs (AGL-2910); instants as ISO strings. */\n applied?: {\n at: string | null\n by: string\n versions: Record<string, string>\n staged: string[]\n } | null\n /** What a guided site start put live (AGL-3596); absent on every other job. */\n sitePublish?: AiJobSitePublish | null\n /**\n * A site job's answers (AGL-3596): the guided start's questions as the person\n * answered them, so a failed start's Try again reopens them filled in. The\n * scalar site inputs only, never anything else a job's inputs carry; absent\n * on every other kind.\n */\n siteInputs?: Record<string, unknown> | null\n /**\n * Whether the machine confirms this job's plan itself (AGL-3594): a guided\n * site start. Its plan parks for the instant the confirmation takes, and a\n * surface reads that park as the build going on (AGL-3596). Absent on every\n * other job.\n */\n autoConfirm?: boolean\n /** A `build` job's items (AGL-3616); absent on every other job. */\n items?: AiJobItemLedger[]\n /**\n * Whether a build's request asked to publish (AGL-3616), so its plan card\n * offers the box that confirms it. Absent on every other job.\n */\n publishAsked?: boolean\n /** A `build` job's planning spend and how it settled (AGL-3616). */\n orchestration?: AiJobOrchestration\n /**\n * A cancel was asked and the job has not ended yet (AGL-3616): the step in\n * flight is finishing or aborting, and nothing after it runs. Absent once\n * the job is terminal, and on every job nobody canceled.\n */\n cancelRequested?: boolean\n /**\n * The empty site this guided start was for was removed (AGL-3936): its\n * page is gone, and Start again opens Create site with the same answers.\n * Absent on every other job.\n */\n siteRemoved?: boolean\n /**\n * An `import` job's waves (AGL-3976), without the page text a wave read\n * holds for the model; absent on every other job.\n */\n siteImport?: AiSiteImportState | null\n}\n"],"names":["AI_JOB_KINDS","AI_JOB_TERMINAL_STATUSES","AI_JOB_PLAN_STEP"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAoFD,qEAAqE,GACrE,OAAO,MAAMA,eAAqC;IAChD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAqBD,OAAO,MAAMC,2BAAmD;IAC9D;IACA;IACA;CACD,CAAA;AAID,uFAAuF,GACvF,OAAO,MAAMC,mBAAmB,OAAM"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-jobs.types.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ITimestamp } from '@aglyn/shared-util-timestamp'\nimport type { AiEffort } from '../providers/contract'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport type { AiBuildPlan } from './ai-build-plan'\nimport type { AiFreeCreditsLeft } from './ai-site-job'\nimport type { AiJobCreditsConfirmation } from './ai-credit-estimate'\nimport type { AiSiteImportState } from './ai-site-import'\nimport type { AiSitePhotos } from './ai-site-photos'\nimport type { AiSiteInspiration } from '../jobs/ai-site-inspiration-signals'\n\n/**\n * AI generation jobs (AGL-2904).\n *\n * A job is one customer brief carried through one or more model steps by a\n * Firestore state machine, so that work longer than a request can survive\n * the request: the console route runs what it can inline, and the platform\n * job beat resumes whatever is left. The document is the whole state — no\n * process holds anything the next beat cannot read back.\n *\n * ── Outputs are drafts, never a publish ──────────────────────────────────\n *\n * Every output a job produces is a NEW draft or a new unpublished version of\n * an existing resource. A job never flips a version pointer, never registers\n * a route and never sends anything; a person opens the draft the job names\n * and publishes it through the door that already exists for that resource.\n * That is what lets a job run with no visitor, no session and no confirm\n * gate — the thing it writes cannot be seen by anyone but the workspace\n * until a member chooses otherwise.\n *\n * ── The lease ────────────────────────────────────────────────────────────\n *\n * A step runs under a lease: an owner id and an `until` instant. Two beats\n * fire a minute apart against a 120 s function timeout, and a console route\n * may still be running the first step when the first beat looks, so the\n * lease is what stops the same step being run — and metered — twice. A\n * claim is a transaction that refuses while another owner's lease is live;\n * an expired lease is simply claimable, which is also how a step abandoned\n * by a frozen process is recovered.\n */\n\n/**\n * What a job produces. `text` and `theme` have runners; every other kind is\n * registered and refuses with \"not available yet\" until its own issue lands,\n * so a kind's presence in the union says the job model accepts it, not that\n * a runner exists.\n */\nexport type AiJobKind =\n | 'page'\n | 'component'\n | 'layout'\n | 'template'\n | 'edit'\n | 'seo'\n | 'site'\n | 'email'\n | 'campaign'\n | 'form'\n | 'experiment'\n | 'insight'\n | 'products'\n | 'crm'\n | 'onboarding'\n | 'workflow'\n | 'logic'\n | 'text'\n | 'theme'\n | 'build'\n /** A change to a site's header or footer menu, made by code (AGL-3728). */\n | 'navigation'\n /** A copy of something a site already has, made by core's duplicate (AGL-3740). */\n | 'duplicate'\n /** A change to a site's settings, made by code and saved live (AGL-3748). */\n | 'settings'\n /** Folders, tags, alt text and names in a site's media library, made by code and saved live (AGL-3752). */\n | 'media'\n /** A change to a site's analytics and advertising tags, made by code and saved live (AGL-3751). */\n | 'tracking'\n /** A change to who can see a site — maintenance mode, search indexing, page visibility — made by code and saved live (AGL-4033). */\n | 'privacy'\n /** A person's own website brought in, page by page, in reviewed waves (AGL-3976). */\n | 'import'\n\n/** The union as a value, so a route can validate a body against it. */\nexport const AI_JOB_KINDS: readonly AiJobKind[] = [\n 'page',\n 'component',\n 'layout',\n 'template',\n 'edit',\n 'seo',\n 'site',\n 'email',\n 'campaign',\n 'form',\n 'experiment',\n 'insight',\n 'products',\n 'crm',\n 'onboarding',\n 'workflow',\n 'logic',\n 'text',\n 'theme',\n 'build',\n 'navigation',\n 'duplicate',\n 'settings',\n 'media',\n 'tracking',\n 'privacy',\n 'import',\n]\n\n/**\n * `queued` — waiting for a runner; `running` — a step holds the lease;\n * `needs_input` — the job stopped for something only the workspace can\n * change (credits, a cap, a switch), and the beat tries it again once that\n * may have changed — or, carrying `input`, for an answer only the person can\n * give (AGL-3978), which the beat leaves alone; `needs_review` — the job stopped for a person's decision\n * (AGL-2935): its plan is ready to confirm, or an answer broke a building\n * rule on its re-ask. No timer can make that decision, so neither the beat\n * nor anything but that person resumes it. The last three are terminal.\n */\nexport type AiJobStatus =\n | 'queued'\n | 'running'\n | 'needs_input'\n | 'needs_review'\n | 'done'\n | 'failed'\n | 'canceled'\n\nexport const AI_JOB_TERMINAL_STATUSES: readonly AiJobStatus[] = [\n 'done',\n 'failed',\n 'canceled',\n]\n\nexport type AiJobStepStatus = 'pending' | 'running' | 'done' | 'failed'\n\n/** The step a planned kind runs first (AGL-2935): its plan, before anything is built. */\nexport const AI_JOB_PLAN_STEP = 'plan'\n\nexport interface AiJobStep {\n /** Stable within the job (`plan`, `draft`, `generate`), unique per job. */\n name: string\n status: AiJobStepStatus\n startedAt?: ITimestamp | null\n endedAt?: ITimestamp | null\n /** Credits this step has actually cost, at the plan's credit rate. */\n creditsSpent: number\n /** Customer-safe only; provider detail goes to the server log. */\n error?: string | null\n /**\n * How many times a runner has been handed this step. A retryable provider\n * failure hands the step back as `pending`; the count is what stops a\n * provider outage re-running a step forever.\n */\n attempts?: number\n /**\n * Passes of a step that works through a list (AGL-2910): each one a\n * recorded, metered exchange that asked to continue. Attempts count again\n * from zero after a pass; this count is what bounds the step.\n */\n passes?: number\n /**\n * What the step's model calls cost in tokens and time (AGL-2937), summed\n * over every run that reached the provider. Absent on a step none has.\n */\n tokens?: AiJobStepTokens\n /**\n * The ids the step writes its drafts under, by draft (AGL-3079): minted\n * when the job is created, so every run of the step names the same drafts.\n * Absent on a step that writes none; a step that records none names its\n * drafts by the job's own id.\n */\n draftIds?: Partial<Record<AiJobDraftSlot, string>>\n}\n\n/**\n * A draft a job's kind always writes (AGL-3079): a screen, layout, template,\n * form or component; an email design; a campaign; an automation.\n */\nexport type AiJobDraftSlot =\n | 'screen'\n | 'layout'\n | 'template'\n | 'form'\n | 'component'\n | 'email'\n | 'campaign'\n | 'workflow'\n\n/**\n * A step's measure (AGL-2937): the four token counts the meter prices, the\n * time spent in the runner, and the model and thinking effort of the last\n * run. The machine writes it beside `creditsSpent`, so what a kind of step\n * costs in tokens is read off the job rather than inferred from the month.\n */\nexport interface AiJobStepTokens {\n /** Prompt tokens sent uncached. */\n input: number\n /** Prompt tokens read from the prompt cache. */\n cachedRead: number\n /** Prompt tokens written to the prompt cache. */\n cacheWrite: number\n /** Tokens generated, thinking included. */\n output: number\n /** The model the last run was served by. */\n model: string | null\n /** The thinking effort the last run asked for; `null` when it named none. */\n effort: AiEffort | null\n /** Milliseconds spent in the runner, summed over runs. */\n latencyMs: number\n /** Runs that reached the provider. */\n runs: number\n /**\n * Why the step's latest runs stopped (AGL-3042), oldest first and the last\n * run last: each run's stop reason and the tokens it generated, so a pass\n * cut off at its ceiling reads off the job rather than out of the sums. At\n * most `AI_JOB_STEP_LAST_RUNS` are kept; absent on a step measured before.\n */\n lastRuns?: AiJobStepRunStop[]\n}\n\n/** One run of a step, by why it stopped (AGL-3042). */\nexport interface AiJobStepRunStop {\n /**\n * The stop reason of the run's last model call — `tool_use` or `end_turn`\n * for an answer, `max_tokens` for one cut off at its ceiling, `refusal` —\n * and `null` when the provider named none.\n */\n stopReason: string | null\n /** Tokens the run generated, over every model call it made. */\n output: number\n}\n\nexport type AiJobOutputResource =\n | 'screen'\n | 'reusableComponent'\n | 'layout'\n | 'template'\n | 'form'\n | 'emailScreen'\n | 'campaign'\n | 'product'\n | 'experiment'\n | 'workflow'\n | 'text'\n | 'theme'\n | 'seo'\n | 'insight'\n | 'crm'\n /** A draft another plugin wrote for a build (AGL-3616), named by `draftResource`. */\n | 'draft'\n | 'logic'\n | 'orgAutomation'\n /** A post a guided start wrote into the site's blog (AGL-3676): a content collection entry. */\n | 'entry'\n /** A site's settings a build changed (AGL-3748): saved live, on the host document. */\n | 'settings'\n /** Files in a site's media library a build organized (AGL-3752): saved live, on their documents. */\n | 'media'\n /** A site's tracking tags a build changed (AGL-3751): saved live, on the host document. */\n | 'tracking'\n /** Who can see a site, as a build changed it (AGL-4033): saved live, on the host and page documents. */\n | 'privacy'\n\n/**\n * One thing a job wrote. Addressed by resource and id so the console can\n * build the \"open draft\" link without knowing what the runner did; `text`\n * has no document of its own, so its body rides on the output itself.\n *\n * A `theme` output is a proposal rather than a document (AGL-2938). A site's\n * theme is fields on its host document, and writing those fields is the save\n * the Theme section's editor performs, which a job never does. So the change\n * set rides on the output as `proposal`, and a person puts it in the editor\n * and saves it there, or does not.\n *\n * An `seo` output is a proposal rather than a document (AGL-2910): search\n * listing values for a page or a product, or a site audit's findings and\n * fixes. A screen's listing is served from the screen document itself, so a\n * job never writes it; the values ride on the output as `proposal`, a person\n * puts them in the editor and saves them there, and an audit's content fixes\n * become new versions only when a person applies them.\n *\n * A `crm` output is a proposal too (AGL-2917): a record's summary and next\n * step, an email draft, or an import's column matches. The CRM's own task\n * form, stage route, composer and import drawer are the writes, and a person\n * makes each of them, or does not.\n *\n * A `logic` output is a proposal too (AGL-3603): a site function or variable\n * the Functions & Variables editor opens unsaved. Saving it is the editor's\n * write, which a person makes, or does not.\n *\n * An `orgAutomation` output is a proposal too (AGL-3603): one of the\n * workspace's automations, which the Org automations editor opens unsaved and\n * switched off. `hostId` is `null`: it belongs to no one site.\n */\nexport interface AiJobOutput {\n resource: AiJobOutputResource\n id: string\n /** The unpublished version the job created, where the resource has versions. */\n versionId?: string | null\n /** `null` for an output that belongs to the org rather than one site. */\n hostId: string | null\n /**\n * The site's subdomain, which is what a console URL names a site by: the\n * `[host]` segment resolves by subdomain, so a link built from `hostId`\n * names no site the console can open.\n */\n hostSubdomain?: string | null\n label: string\n /** The body of a `text` output. Absent on every other resource. */\n text?: string\n /**\n * The change set of an output a person applies rather than opens — a\n * `theme` or `seo` proposal — in the shape its job kind's runner defines.\n */\n proposal?: Record<string, unknown>\n /**\n * What the person decides next about this output, in customer-safe words:\n * a routing the draft could not store, or part of the brief it could not\n * build. Absent when there is nothing to decide.\n */\n note?: string | null\n /**\n * What a first visit is estimated to transfer, as the doctrine measured\n * the generated document (AGL-2935) — the weight the proposal shows before\n * anything is applied. Absent where the output is not a page's document.\n */\n load?: AiLoadEstimate | null\n /**\n * For a `draft` output (AGL-3616): the resource whose owner wrote it, as\n * its writer is registered on the resource-draft seam.\n */\n draftResource?: string\n /**\n * The change is in the WORKING DRAFT of `versionId` (AGL-4116), which the\n * Besigner offers with Open draft, not in the version itself — so the\n * version's preview does not show it, and only the Besigner is linked.\n */\n inDraft?: true\n}\n\nexport interface AiJobLease {\n /** The process that holds the step: a route request id or a beat id. */\n owner: string\n until: ITimestamp\n}\n\n/** Why a job stopped for a person (AGL-2935). */\nexport type AiJobReviewReason =\n /** The plan step proposed a plan; generation waits for it to be confirmed. */\n | 'plan'\n /** An answer broke a building rule, and so did the answer to the re-ask. */\n | 'doctrine'\n /**\n * The site is at an allowance its plan sets for what the step writes, such\n * as its shared layouts or its templates (AGL-2909). Freeing one, or a plan\n * that holds more, is the member's decision; trying again runs the step\n * again.\n */\n | 'limit'\n /**\n * A site import's wave is in (AGL-3976): its pages are drafts for the\n * person to review, and the next wave starts only when they say so. Or the\n * import has read the site and waits for the first wave to be started.\n */\n | 'wave'\n /**\n * A site import's next wave needs a current proof that the workspace owns\n * the site (AGL-3976): the proof is older than its 30 days, or was never\n * made. Verifying again and starting the wave runs it.\n */\n | 'ownership'\n /**\n * A site import's read found its home page turned away by the site's bot\n * protection or firewall (AGL-4083): nothing is planned or spent. Letting\n * AglynBot in and choosing Check again reads the site again.\n */\n | 'blocked'\n /**\n * A site import's read could not read its home page for any other reason\n * (AGL-4083): an error, no answer, or a page that needs a browser to show\n * its words. Nothing is planned or spent; Check again reads it again.\n */\n | 'unreadable'\n\n/**\n * A building rule an answer broke, as the job keeps it: the number, the code,\n * the sentence, and where in the answer it was broken (AGL-3078).\n */\nexport interface AiJobRuleFinding {\n rule: number | null\n code: string\n /** Customer-safe. */\n message: string\n /** The nodes the finding names, by the ids the refused answer gave them. Absent when it names none. */\n nodeIds?: string[]\n /** The plan entries or answer fields it names, as `screens[0].sections[2]`. Absent when it names none. */\n paths?: string[]\n}\n\n/**\n * One node of the parts of a refused answer its findings name (AGL-3078), as\n * the review keeps it: the node's place, its element and the names of what it\n * sets, and never its copy. A Grid keeps the values of its layout props as\n * they were written, so a review can tell a shape the rules refuse from one\n * the model was asked to mend and did not.\n */\nexport interface AiJobReviewOutlineNode {\n /** The node's id, as the refused answer wrote it. */\n id: string\n /** How far below a node a finding names it sits: 0 for that node. */\n depth: number\n componentId: string\n /** The props it sets, by name only. */\n props: string[]\n /** The `sx` keys it sets, by name only; absent when it sets none. */\n sx?: string[]\n /** A Grid's layout props, `container`, `size`, `direction`, `spacing` and the rest, as written. */\n grid?: Record<string, string | number | boolean | null>\n /** Its children's element ids, in order. */\n children: string[]\n}\n\nexport interface AiJobReview {\n reason: AiJobReviewReason\n /** Customer-safe: what the person is asked to decide. */\n message: string\n /** The rules the last answer broke; empty for a plan. */\n findings: AiJobRuleFinding[]\n /**\n * The parts of the refused answer its findings name, each node with the\n * nodes below it (AGL-3078); absent when they name none. Kept with the job\n * for diagnosis, and shown to staff.\n */\n outline?: AiJobReviewOutlineNode[]\n /**\n * The checks' own sentence, where `message` was written for the member\n * instead (AGL-3594): rule numbers and all, for staff. Its presence is what\n * tells the drawer the findings are staff reading too.\n */\n detail?: string\n /**\n * Why trying again cannot work yet (AGL-3594) — the Free allowance left is\n * less than the step can cost — or absent when it can. The button is drawn\n * disabled with this beside it.\n */\n retryRefusal?: string\n /**\n * What a Free workspace had left when a build's plan was kept (AGL-3722),\n * so its plan card says, before Confirm, whether the build fits and offers\n * the go-ahead or a smaller first build when it does not. The confirm door\n * reads what is left again; this is what the card shows.\n */\n freeCredits?: AiFreeCreditsLeft\n}\n\n/**\n * One answer a job waits for (AGL-3978): an id only the person has, which the\n * operation that needs it describes — a tracking change's Meta pixel ID.\n */\nexport interface AiJobInputField {\n /** The plan item the answer fills, by its name in the plan. */\n item: string\n /** The item's argument the answer is written to. */\n arg: string\n /** The field's label, naming the provider: \"Meta pixel ID\". */\n label: string\n /** What an answer looks like, in the words of the card that sets it: \"8–20 digits\". */\n shape: string\n /** The pattern an answer is held to, as a RegExp's source. */\n pattern: string\n}\n\n/** What a job parked `needs_input` for a person asks (AGL-3978). */\nexport interface AiJobInputRequest {\n /** Customer-safe: the question, in the operation's own words. */\n message: string\n fields: AiJobInputField[]\n}\n\nexport type AiJobPlanStatus = 'proposed' | 'confirmed'\n\n/** The plan a job builds from, as the job keeps it once its plan step proposed it. */\nexport interface AiJobPlan extends AiBuildPlan {\n status: AiJobPlanStatus\n /** Names for the inventory ids the plan references, read when it was made. */\n labels: Record<string, string>\n proposedAt: ITimestamp\n confirmedAt: ITimestamp | null\n /** The member who confirmed it. */\n confirmedBy: string | null\n /**\n * A digest of the whole request that produced this plan (AGL-2937): the\n * job's kind, site, brief and scalar inputs, the model that answered, and\n * the prompt as it was rendered — the site inventory included. A later job\n * whose request hashes the same reuses this plan rather than paying for the\n * same answer again. A hash of the request, never of the answer, and no\n * part of the brief is recoverable from it.\n */\n key?: string\n /** The job this plan was reused from, when it was not asked for again. */\n reusedFrom?: string\n /**\n * What a site start read of the sites the person likes (AGL-3975): signals\n * only, each from a closed set or a hex color, which the plan was told the\n * structure of and the look pins the style of. Absent without them.\n */\n inspiration?: AiSiteInspiration\n}\n\n/**\n * Where one item of a `build` job stands (AGL-3616). A build settles item by\n * item: a failed item gives back its own spend and the rest of the plan still\n * runs, so the job keeps one row per item, written only by the machine's\n * `recordStep` — in the same transaction as the spend it accounts for — and\n * by the resume door's retry.\n */\nexport type AiJobItemStatus = 'pending' | 'running' | 'succeeded' | 'degraded' | 'failed' | 'skipped'\n\n/** Why an item failed: a give-back reason when it was ours, else the model's refusal or a review. */\nexport type AiJobItemFailureReason =\n | 'plan-refused'\n | 'doctrine-refused'\n | 'provider'\n | 'timeout'\n | 'step-failure'\n | 'unavailable'\n | 'refused'\n | 'review'\n\nexport interface AiJobItemFailure {\n /** Whether the failure was on our side: only then is the item's spend given back. */\n ours: boolean\n reason: AiJobItemFailureReason\n /** Customer-safe. */\n message: string\n /**\n * The checks' own sentence behind a `doctrine-refused` failure (AGL-3596),\n * rule numbers and all: kept on the job for staff and debugging, never on\n * the wire a customer reads.\n */\n detail?: string\n}\n\nexport interface AiJobItemLedger {\n /** The unit's slot within the plan: `c0` a creation, `p0` a page, `i0` an item. */\n slot: string\n /** The capability operation that builds it: `page`, `form`, or an owner's op. */\n op: string\n /** What a person reads: the page's title, the creation's or item's name. */\n label: string\n status: AiJobItemStatus\n /** Bumped by Try again; the refund key names it, so each attempt gives back once. */\n attempt: number\n /** What this item's passes cost, every attempt. */\n creditsSpent: number\n /** What this attempt's passes cost so far: what a failure of this attempt gives back. */\n attemptCredits?: number\n /** What was given back for this item's failures. */\n creditsRefunded: number\n /** The key the latest give-back for this item was made under. */\n refundKey?: string\n failure?: AiJobItemFailure | null\n /** The ids of the outputs this item produced. */\n outputs: string[]\n /** The slots whose failure changed how this item was built. */\n degradedBy?: string[]\n /** Customer-safe: what the person should know about this item. */\n note?: string | null\n /**\n * When this attempt settled, as an ISO string (AGL-3596): the moment the\n * next item started, which is what its progress row counts from. Absent\n * while the item is open, and on a ledger written before it was kept.\n */\n settledAt?: string | null\n}\n\n/** Whether a build's own planning was charged or given back (AGL-3616). */\nexport interface AiJobOrchestration {\n /** What the plan step spent. */\n creditsSpent: number\n /** `charged` once anything was delivered; `refunded` when nothing was. */\n settled: 'pending' | 'charged' | 'refunded'\n}\n\nexport interface AiJob {\n $id: string\n orgId: string\n hostId?: string | null\n kind: AiJobKind\n status: AiJobStatus\n /** The customer's brief, verbatim. Expires with the document. */\n brief: string\n /** Kind-specific inputs the runner reads (a screen id to edit, a tone). */\n inputs: Record<string, unknown>\n /**\n * The model the creator picked for the job's steps (AGL-2942), or `null`\n * for Auto. Each step honors it only where the plan and the allotment\n * allowlists allow it, and runs on the routing table otherwise.\n */\n model?: string | null\n steps: AiJobStep[]\n outputs: AiJobOutput[]\n /**\n * The nominal credit figure held against the job while steps are\n * outstanding. The meter's real bound is the per-step message reservation\n * and the org's monthly ceiling; this is the number the console shows so\n * a running job is not read as free.\n */\n creditsReserved: number\n creditsSpent: number\n /**\n * Credits the job gave back because it failed on our side (AGL-3594),\n * summed over its give-backs; absent when it gave none. `creditsSpent`\n * stays what ran, so what the job cost is the one less the other.\n */\n refundedCredits?: number\n /** Why the latest give-back was made (`AiJobRefundReason`). */\n refundReason?: string\n /** How many give-backs the job has had: the next one's key. */\n refunds?: number\n createdBy: string\n createdAt: ITimestamp\n updatedAt: ITimestamp\n /** TTL — the brief is verbatim customer text and expires like an exchange. */\n expiresAt: ITimestamp\n /** Customer-safe only. */\n error?: string | null\n lease?: AiJobLease | null\n /** The plan the job builds from, once its plan step proposed one. */\n plan?: AiJobPlan | null\n /** What the person is asked to decide while the job is `needs_review`. */\n review?: AiJobReview | null\n /**\n * What the job waits for while it is `needs_input` for a person rather than\n * the meter (AGL-3978): the fields only they can fill, an id the planner\n * must never make up. Its plan and the plan's review are kept beside it,\n * and the answer returns the job to that review.\n */\n input?: AiJobInputRequest | null\n /**\n * What a person applied from the job's outputs (AGL-2910). Written by the\n * door that applied them, never by a step runner, and absent until then.\n */\n applied?: AiJobApplied | null\n /**\n * What a guided site start put live when it finished (AGL-3596): written\n * once by the site step's last pass, never by a person. Absent on every\n * other job, which leaves its pages as drafts.\n */\n sitePublish?: AiJobSitePublish | null\n /** A `build` job's items, one row each (AGL-3616); absent on every other kind. */\n items?: AiJobItemLedger[] | null\n /** A `build` job's planning spend and how it settled (AGL-3616). */\n orchestration?: AiJobOrchestration | null\n /**\n * A Free job started past what was left (AGL-3722): the person chose to\n * build what fits, knowing it pauses where the credits run out. Who, when,\n * what was left and the range they were shown; absent on every job that fit.\n */\n creditsConfirmed?: AiJobCreditsConfirmation | null\n /**\n * A person asked to stop the job (AGL-3616): written only by the cancel\n * door, in the transaction that decides it. A job no step holds ends\n * `canceled` in that same write; a job whose step holds a live lease keeps\n * running until the step finishes or aborts, and the machine ends it\n * `canceled` at its next write. Absent on a job nobody canceled.\n */\n cancelRequested?: AiJobCancelRequest | null\n /**\n * The empty site this guided start was for was removed (AGL-3936): the\n * job was cancelled or failed before it built anything, nobody chose what\n * to do next within the grace period, and the AI jobs beat deleted the\n * site. Written once, by the beat, after the site is gone. Absent on every\n * other job.\n */\n siteRemoved?: AiJobSiteRemoved | null\n /**\n * When the one reminder about a plan waiting for its confirmation went out\n * (AGL-4076), a day after the plan was ready. Written once, by the AI jobs\n * beat, in the transaction that decides to send it, and never cleared: a\n * job is reminded at most once, however many plans it waits on. Absent on\n * every job that was not reminded.\n */\n remindedAt?: ITimestamp | null\n /**\n * An `import` job's site, read and cut into waves (AGL-3976): what was\n * found, what is brought in in which wave, what was left out and why, and\n * each wave's state. Written only by the machine's `recordStep`, from what\n * the import step returns; absent on every other kind.\n */\n siteImport?: AiSiteImportState | null\n /**\n * A `site` job's pictures left on a starter photo (AGL-3988): each page\n * picture and dataset record its library could not fill in its own pass,\n * with the picks the image hosts refused. Written only by the machine's\n * `recordStep`, from what the site step returns; emptied by its late photo\n * pass before the site is published. Never on the wire. Absent on every\n * other kind.\n */\n sitePhotos?: AiSitePhotos | null\n}\n\n/** When the AI jobs beat removed a guided start's empty site, and which (AGL-3936). */\nexport interface AiJobSiteRemoved {\n at: ITimestamp\n /** The site's name as it was, for a sentence that names it. */\n name: string | null\n}\n\n/** Who asked to cancel a job, and when (AGL-3616). */\nexport interface AiJobCancelRequest {\n at: ITimestamp\n /** The member or staff account that asked; `null` when nobody was named. */\n by: string | null\n}\n\n/**\n * A guided site start's publish (AGL-3596): the pages that went live, with\n * the address each answers, and the pages that stayed drafts, each with the\n * plain sentence for why. A page that stayed a draft never fails the job.\n */\nexport interface AiJobSitePublish {\n /** The site's live address, `https://<subdomain>.aglyn.app/`; `null` when the site has no subdomain. */\n liveUrl: string | null\n published: Array<{ id: string; label: string; path: string }>\n drafts: Array<{ id: string; label: string; reason: string }>\n}\n\n/**\n * The record of an apply (AGL-2910): what became a new unpublished version,\n * and what waits in its editor for a person to save.\n */\nexport interface AiJobApplied {\n at: ITimestamp\n /** The member who applied. */\n by: string\n /** The new version opened for each resource, by resource id. */\n versions: Record<string, string>\n /** Resource ids whose proposed values wait in their editor, unsaved. */\n staged: string[]\n}\n\n/** The plan on the wire: every instant an ISO string. */\nexport interface AiJobPlanSummary extends AiBuildPlan {\n status: AiJobPlanStatus\n labels: Record<string, string>\n proposedAt: string | null\n confirmedAt: string | null\n confirmedBy: string | null\n key?: string\n reusedFrom?: string\n}\n\n/**\n * The wire form the console reads: every instant an ISO string, the lease\n * reduced to whether a runner holds the job. The brief and the outputs\n * travel as they are — the reader is a member of the org that wrote them.\n */\nexport interface AiJobSummary {\n id: string\n orgId: string\n hostId: string | null\n kind: AiJobKind\n status: AiJobStatus\n brief: string\n /**\n * The batch a door created this job as one of (AGL-2911), read off the\n * job's inputs; `null` for a job created on its own. The console groups a\n * run of jobs by it, which is the one thing it cannot do from a list whose\n * rows carry no inputs — and the only input the wire form carries, because\n * a batch id names nothing the member wrote.\n */\n batch: string | null\n steps: Array<{\n name: string\n status: AiJobStepStatus\n startedAt: string | null\n endedAt: string | null\n creditsSpent: number\n error: string | null\n }>\n outputs: AiJobOutput[]\n creditsReserved: number\n creditsSpent: number\n /** Credits given back for a failure on our side (AGL-3594); 0 when none. */\n refundedCredits?: number\n createdBy: string\n createdAt: string\n updatedAt: string\n error: string | null\n running: boolean\n plan: AiJobPlanSummary | null\n review: AiJobReview | null\n /** The fields a `needs_input` job waits for a person to fill (AGL-3978); absent otherwise. */\n input?: AiJobInputRequest | null\n /** What a person applied from the outputs (AGL-2910); instants as ISO strings. */\n applied?: {\n at: string | null\n by: string\n versions: Record<string, string>\n staged: string[]\n } | null\n /** What a guided site start put live (AGL-3596); absent on every other job. */\n sitePublish?: AiJobSitePublish | null\n /**\n * A site job's answers (AGL-3596): the guided start's questions as the person\n * answered them, so a failed start's Try again reopens them filled in. The\n * scalar site inputs only, never anything else a job's inputs carry; absent\n * on every other kind.\n */\n siteInputs?: Record<string, unknown> | null\n /**\n * Whether the machine confirms this job's plan itself (AGL-3594): a guided\n * site start. Its plan parks for the instant the confirmation takes, and a\n * surface reads that park as the build going on (AGL-3596). Absent on every\n * other job.\n */\n autoConfirm?: boolean\n /** A `build` job's items (AGL-3616); absent on every other job. */\n items?: AiJobItemLedger[]\n /**\n * Whether a build's request asked to publish (AGL-3616), so its plan card\n * offers the box that confirms it. Absent on every other job.\n */\n publishAsked?: boolean\n /** A `build` job's planning spend and how it settled (AGL-3616). */\n orchestration?: AiJobOrchestration\n /**\n * A cancel was asked and the job has not ended yet (AGL-3616): the step in\n * flight is finishing or aborting, and nothing after it runs. Absent once\n * the job is terminal, and on every job nobody canceled.\n */\n cancelRequested?: boolean\n /**\n * The empty site this guided start was for was removed (AGL-3936): its\n * page is gone, and Start again opens Create site with the same answers.\n * Absent on every other job.\n */\n siteRemoved?: boolean\n /**\n * An `import` job's waves (AGL-3976), without the page text a wave read\n * holds for the model; absent on every other job.\n */\n siteImport?: AiSiteImportState | null\n}\n"],"names":["AI_JOB_KINDS","AI_JOB_TERMINAL_STATUSES","AI_JOB_PLAN_STEP"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAoFD,qEAAqE,GACrE,OAAO,MAAMA,eAAqC;IAChD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAqBD,OAAO,MAAMC,2BAAmD;IAC9D;IACA;IACA;CACD,CAAA;AAID,uFAAuF,GACvF,OAAO,MAAMC,mBAAmB,OAAM"}
@@ -120,6 +120,12 @@ export interface AiInventoryDataset {
120
120
  * listing's cards by it.
121
121
  */
122
122
  recordBase?: string;
123
+ /**
124
+ * The page that template is (AGL-3616): the screen whose `{{item.*}}` the
125
+ * site fills with each record. Never shown in the prompt: an edit to that
126
+ * page reads it to know its tokens are filled.
127
+ */
128
+ recordScreenId?: string;
123
129
  /**
124
130
  * Whether it is shared with this site and no other (AGL-3912): its scope
125
131
  * names this site alone, so it was made for this site. Absent where it is
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-site-inventory.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/**\n * The site's inventory as a model sees it (AGL-2935): what the site already\n * has, so a plan reuses before it creates (doctrine rule 7).\n *\n * COMPACT by construction (AGL-2937): ids, names, prop shapes and slugs —\n * never a node tree, never a record's content. A component is its name and\n * the props an instance fills in; a form is its field names; a dataset its\n * field names. That is everything a planner needs to decide \"reuse this\"\n * and a generator needs to place a reference, and it is a few hundred\n * tokens where the trees would be tens of thousands.\n *\n * CAPPED three times, and the three are different numbers on purpose\n * (AGL-2937). The reader holds each kind to `AI_SITE_INVENTORY_MAX_PER_KIND`;\n * the prompt block LISTS only `AI_SITE_INVENTORY_LISTED_PER_KIND` of them and\n * is held to `AI_SITE_INVENTORY_MAX_CHARS` besides; and the rest are answered\n * on request, through the lookup tool the generation loop offers beside every\n * door's own (`tools/ai-inventory-lookup-tool.ts`).\n *\n * The listing cap is what a prompt can afford: the block is volatile, so it\n * is billed at full input rate on every request and every re-ask, and a site\n * with two hundred components would spend most of a plan's prompt on rows it\n * will not use. The read cap is what a LOOKUP can answer from, which is a\n * different question — a search for \"pricing card\" is worth nothing if the\n * card was never read. A kind cut by either is named in `truncated`, so the\n * model is told more exist rather than concluding they do not.\n *\n * The shapes live here, apart from the reader (`runtime/site-inventory.ts`),\n * so the prompt block, the validators and their specs can hold an inventory\n * without loading the Admin SDK the reader needs.\n */\n\n/**\n * Rows per kind the reader holds. Above the listing cap on purpose: the rows\n * past it are what the lookup tool searches, and a row never read cannot be\n * found. One projection of a few fields each, so the read is small even at\n * this cap.\n */\nexport const AI_SITE_INVENTORY_MAX_PER_KIND = 200\n\n/** Rows per kind the prompt block lists; the rest are found by lookup. */\nexport const AI_SITE_INVENTORY_LISTED_PER_KIND = 40\n\n/** The rendered block's ceiling: 2,000 tokens at four characters a token. */\nexport const AI_SITE_INVENTORY_MAX_CHARS = 8_000\n\nexport type AiInventoryKind =\n | 'components'\n | 'layouts'\n | 'templates'\n | 'forms'\n | 'datasets'\n | 'collections'\n | 'screens'\n\nexport const AI_INVENTORY_KINDS: readonly AiInventoryKind[] = [\n 'components',\n 'layouts',\n 'templates',\n 'forms',\n 'datasets',\n 'collections',\n 'screens',\n]\n\n/**\n * A reusable component's declared props as an instance may fill them: prop\n * name → its declared type (`text`, `image`, `href`, `number`, `boolean`, …).\n */\nexport type AiComponentPropTypes = Record<string, string>\n\nexport interface AiInventoryComponent {\n id: string\n name: string\n /** The props an instance fills in: name → declared type. */\n props: AiComponentPropTypes\n /**\n * The facts in square brackets each prop's default shows until a page sets\n * its own, by prop name (AGL-3056): what a page placing the component still\n * asks the member to fill. Read for the member's note, never listed in a\n * prompt; absent when no default holds one.\n */\n bracketedDefaults?: Record<string, string[]>\n}\n\nexport interface AiInventoryLayout {\n id: string\n name: string\n /** The layout this one nests inside, when it nests. */\n parentId: string | null\n}\n\nexport interface AiInventoryTemplate {\n id: string\n name: string\n kind: string\n}\n\nexport interface AiInventoryForm {\n id: string\n name: string\n fields: string[]\n}\n\nexport interface AiInventoryDataset {\n id: string\n name: string\n fields: string[]\n /**\n * The same fields' ids, in the same order: what a record template binds as\n * `{{item.<id>}}` (AGL-3475). Absent where the reader did not see them.\n */\n fieldIds?: string[]\n /**\n * The id of the field holding each record's photo, where it has one\n * (AGL-3616): what a record template's Image binds as its `src`.\n */\n imageField?: string\n /**\n * The id of the record's page-address field, where it has one (AGL-3727):\n * what a listing's card links each record's own page by. Where the site\n * already serves record pages for the dataset, the field those pages are\n * served by (AGL-3747).\n */\n addressField?: string\n /**\n * Where this site already serves each record a page of its own (AGL-3747):\n * the base of the dataset's saved record template (AGL-3475), without\n * slashes at either end — `team` for `/team/ada`. Absent where the site\n * keeps no record template for it. Never shown in the prompt: code links a\n * listing's cards by it.\n */\n recordBase?: string\n /**\n * Whether it is shared with this site and no other (AGL-3912): its scope\n * names this site alone, so it was made for this site. Absent where it is\n * the workspace's, shared with every site, or with others besides.\n */\n siteOnly?: true\n /**\n * How many records it holds (AGL-3912), counted for a site start's plan\n * only (`aiSiteInventoryWithRecordCounts`); absent where nobody counted, or\n * the count failed. Never shown in the prompt.\n */\n records?: number\n /**\n * Set on a site start's plan only (AGL-3912), where its records are not\n * this site's to show (`aiSiteDatasetIsThisSites`): the plan makes it\n * again rather than reuse it, so a creation of its name is no duplicate.\n */\n foreign?: true\n}\n\nexport interface AiInventoryCollection {\n id: string\n name: string\n slug: string\n}\n\nexport interface AiInventoryScreen {\n id: string\n name: string\n slug: string\n layoutId: string | null\n /** A collection's entry template rather than a page of its own. */\n template: boolean\n /**\n * The platform's starter home page, untouched since the site was created\n * (AGL-3594): the screen `host.defaultHomeScreenId` names, still answering\n * `/`, with no version but the one it was provisioned with. A plan may put\n * its own home page at its address, and publishing that page retires this\n * one (AGL-3408). Absent on every other screen, and on a starter home the\n * owner has edited, which a plan keeps and plans around.\n */\n replaceable?: true\n}\n\n/**\n * The site's one theme, as a planner and the email rule read it: a short\n * description, the light scheme's colors by palette path, and the families\n * the theme loads.\n */\nexport interface AiInventoryTheme {\n summary: string[]\n colors: Record<string, string>\n fonts: string[]\n}\n\nexport interface AiSiteInventory {\n hostId: string\n components: AiInventoryComponent[]\n layouts: AiInventoryLayout[]\n templates: AiInventoryTemplate[]\n forms: AiInventoryForm[]\n datasets: AiInventoryDataset[]\n collections: AiInventoryCollection[]\n screens: AiInventoryScreen[]\n theme: AiInventoryTheme | null\n /** Kinds with more records than are listed. */\n truncated: AiInventoryKind[]\n}\n\n/** One inventory record, whatever kind it is. */\nexport type AiInventoryRow =\n | AiInventoryComponent\n | AiInventoryLayout\n | AiInventoryTemplate\n | AiInventoryForm\n | AiInventoryDataset\n | AiInventoryCollection\n | AiInventoryScreen\n\n/**\n * The rows of one kind. The inventory's fields are named after their kinds,\n * so this is a lookup rather than a switch, and it is the one place that\n * relies on the correspondence: the prompt block, the lookup tool and their\n * specs all read a kind through it.\n */\nexport function aiInventoryRows(\n inventory: AiSiteInventory,\n kind: AiInventoryKind,\n): readonly AiInventoryRow[] {\n return inventory[kind]\n}\n\n/** The heading one kind's lines are listed under, naming its columns in order. */\nexport const AI_INVENTORY_KIND_HEADINGS: Readonly<Record<AiInventoryKind, string>> = {\n components: 'Reusable components (id \\u00b7 name \\u00b7 props an instance fills)',\n layouts: 'Layouts (id \\u00b7 name)',\n templates: 'Templates (id \\u00b7 name \\u00b7 kind)',\n forms: 'Forms (id \\u00b7 name \\u00b7 fields)',\n datasets: 'Datasets (id \\u00b7 name \\u00b7 fields)',\n collections: 'Content collections (id \\u00b7 name \\u00b7 slug)',\n screens: 'Pages (id \\u00b7 name \\u00b7 slug)',\n}\n\n/**\n * One record as a line, in the order its heading names the columns. The one\n * renderer: the prompt block and the lookup tool's answer read alike, so a\n * row found by lookup is the same shape as a row that was listed.\n */\nexport function aiInventoryLine(kind: AiInventoryKind, row: AiInventoryRow): string {\n const head = `${row.id} \\u00b7 ${row.name}`\n switch (kind) {\n case 'components': {\n const props = Object.entries((row as AiInventoryComponent).props)\n .map(([name, type]) => `${name}:${type}`)\n .join(', ')\n return `${head} \\u00b7 ${props || 'no props'}`\n }\n case 'layouts':\n return head\n case 'templates':\n return `${head} \\u00b7 ${(row as AiInventoryTemplate).kind}`\n case 'forms':\n return `${head} \\u00b7 ${(row as AiInventoryForm).fields.join(', ')}`\n case 'datasets':\n return `${head} \\u00b7 ${(row as AiInventoryDataset).fields.join(', ')}`\n case 'collections':\n return `${head} \\u00b7 ${(row as AiInventoryCollection).slug}`\n case 'screens': {\n const screen = row as AiInventoryScreen\n return `${head} \\u00b7 ${screen.slug}${screen.template ? ' \\u00b7 entry template' : ''}${\n screen.replaceable ? ' \\u00b7 starter home, a planned home page at / replaces it' : ''\n }`\n }\n }\n}\n\n/** Every word of a record a lookup searches: its line, which holds them all. */\nexport function aiInventoryHaystack(kind: AiInventoryKind, row: AiInventoryRow): string {\n return aiInventoryLine(kind, row).toLowerCase()\n}\n\n/** The addresses a site's home screen is stored under. */\nconst HOME_SLUGS = new Set(['', 'home', 'index'])\n\n/**\n * The site's home screens, by id (AGL-3056): a screen at the root or at\n * `home`, as a seeded site stores its first screen, or one named Home. A link\n * with nowhere to go is sent there, which is why the doctrine names them.\n */\nexport function aiHomeScreenIds(inventory: AiSiteInventory | null): string[] {\n const homes = (inventory?.screens ?? []).filter(\n (screen) =>\n !screen.template &&\n (HOME_SLUGS.has(screen.slug.trim().replace(/^\\/+|\\/+$/g, '').toLowerCase()) ||\n /^home(?:\\s?page)?$/i.test(screen.name.trim())),\n )\n // A starter home a planned home page replaces (AGL-3594) is retired when\n // that page is published, so a link is sent to the page that replaces it\n // wherever the site already has one.\n const kept = homes.filter((screen) => !screen.replaceable)\n return (kept.length ? kept : homes).map((screen) => screen.id)\n}\n\n/** The titles of the site's home screens ({@link aiHomeScreenIds}): a link under one says home, in the site's own language (AGL-3760). */\nexport function aiHomeScreenNames(inventory: AiSiteInventory | null): string[] {\n const ids = new Set(aiHomeScreenIds(inventory))\n return (inventory?.screens ?? []).filter((screen) => ids.has(screen.id) && screen.name.trim()).map((screen) => screen.name.trim())\n}\n\n/** A site the org does not own; the inventory is never read for it. */\nexport class AiInventoryScopeError extends Error {\n constructor(hostId: string) {\n super(`host ${hostId} is not a site of the workspace that asked`)\n this.name = 'AiInventoryScopeError'\n }\n}\n\nexport function emptyAiSiteInventory(hostId: string): AiSiteInventory {\n return {\n hostId,\n components: [],\n layouts: [],\n templates: [],\n forms: [],\n datasets: [],\n collections: [],\n screens: [],\n theme: null,\n truncated: [],\n }\n}\n"],"names":["AI_SITE_INVENTORY_MAX_PER_KIND","AI_SITE_INVENTORY_LISTED_PER_KIND","AI_SITE_INVENTORY_MAX_CHARS","AI_INVENTORY_KINDS","aiInventoryRows","inventory","kind","AI_INVENTORY_KIND_HEADINGS","components","layouts","templates","forms","datasets","collections","screens","aiInventoryLine","row","head","id","name","props","Object","entries","map","type","join","fields","slug","screen","template","replaceable","aiInventoryHaystack","toLowerCase","HOME_SLUGS","Set","aiHomeScreenIds","homes","filter","has","trim","replace","test","kept","length","aiHomeScreenNames","ids","AiInventoryScopeError","Error","hostId","emptyAiSiteInventory","theme","truncated"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GAED;;;;;CAKC,GACD,OAAO,MAAMA,iCAAiC,IAAG;AAEjD,wEAAwE,GACxE,OAAO,MAAMC,oCAAoC,GAAE;AAEnD,2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AAK,EAAEA,OAAO,0CAA0C,CAAC;QAChE,IAAI,CAAC7B,IAAI,GAAG;IACd;AACF;AAEA,OAAO,SAAS8B,qBAAqBD,MAAc;IACjD,OAAO;QACLA;QACAxC,YAAY,EAAE;QACdC,SAAS,EAAE;QACXC,WAAW,EAAE;QACbC,OAAO,EAAE;QACTC,UAAU,EAAE;QACZC,aAAa,EAAE;QACfC,SAAS,EAAE;QACXoC,OAAO;QACPC,WAAW,EAAE;IACf;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-site-inventory.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/**\n * The site's inventory as a model sees it (AGL-2935): what the site already\n * has, so a plan reuses before it creates (doctrine rule 7).\n *\n * COMPACT by construction (AGL-2937): ids, names, prop shapes and slugs —\n * never a node tree, never a record's content. A component is its name and\n * the props an instance fills in; a form is its field names; a dataset its\n * field names. That is everything a planner needs to decide \"reuse this\"\n * and a generator needs to place a reference, and it is a few hundred\n * tokens where the trees would be tens of thousands.\n *\n * CAPPED three times, and the three are different numbers on purpose\n * (AGL-2937). The reader holds each kind to `AI_SITE_INVENTORY_MAX_PER_KIND`;\n * the prompt block LISTS only `AI_SITE_INVENTORY_LISTED_PER_KIND` of them and\n * is held to `AI_SITE_INVENTORY_MAX_CHARS` besides; and the rest are answered\n * on request, through the lookup tool the generation loop offers beside every\n * door's own (`tools/ai-inventory-lookup-tool.ts`).\n *\n * The listing cap is what a prompt can afford: the block is volatile, so it\n * is billed at full input rate on every request and every re-ask, and a site\n * with two hundred components would spend most of a plan's prompt on rows it\n * will not use. The read cap is what a LOOKUP can answer from, which is a\n * different question — a search for \"pricing card\" is worth nothing if the\n * card was never read. A kind cut by either is named in `truncated`, so the\n * model is told more exist rather than concluding they do not.\n *\n * The shapes live here, apart from the reader (`runtime/site-inventory.ts`),\n * so the prompt block, the validators and their specs can hold an inventory\n * without loading the Admin SDK the reader needs.\n */\n\n/**\n * Rows per kind the reader holds. Above the listing cap on purpose: the rows\n * past it are what the lookup tool searches, and a row never read cannot be\n * found. One projection of a few fields each, so the read is small even at\n * this cap.\n */\nexport const AI_SITE_INVENTORY_MAX_PER_KIND = 200\n\n/** Rows per kind the prompt block lists; the rest are found by lookup. */\nexport const AI_SITE_INVENTORY_LISTED_PER_KIND = 40\n\n/** The rendered block's ceiling: 2,000 tokens at four characters a token. */\nexport const AI_SITE_INVENTORY_MAX_CHARS = 8_000\n\nexport type AiInventoryKind =\n | 'components'\n | 'layouts'\n | 'templates'\n | 'forms'\n | 'datasets'\n | 'collections'\n | 'screens'\n\nexport const AI_INVENTORY_KINDS: readonly AiInventoryKind[] = [\n 'components',\n 'layouts',\n 'templates',\n 'forms',\n 'datasets',\n 'collections',\n 'screens',\n]\n\n/**\n * A reusable component's declared props as an instance may fill them: prop\n * name → its declared type (`text`, `image`, `href`, `number`, `boolean`, …).\n */\nexport type AiComponentPropTypes = Record<string, string>\n\nexport interface AiInventoryComponent {\n id: string\n name: string\n /** The props an instance fills in: name → declared type. */\n props: AiComponentPropTypes\n /**\n * The facts in square brackets each prop's default shows until a page sets\n * its own, by prop name (AGL-3056): what a page placing the component still\n * asks the member to fill. Read for the member's note, never listed in a\n * prompt; absent when no default holds one.\n */\n bracketedDefaults?: Record<string, string[]>\n}\n\nexport interface AiInventoryLayout {\n id: string\n name: string\n /** The layout this one nests inside, when it nests. */\n parentId: string | null\n}\n\nexport interface AiInventoryTemplate {\n id: string\n name: string\n kind: string\n}\n\nexport interface AiInventoryForm {\n id: string\n name: string\n fields: string[]\n}\n\nexport interface AiInventoryDataset {\n id: string\n name: string\n fields: string[]\n /**\n * The same fields' ids, in the same order: what a record template binds as\n * `{{item.<id>}}` (AGL-3475). Absent where the reader did not see them.\n */\n fieldIds?: string[]\n /**\n * The id of the field holding each record's photo, where it has one\n * (AGL-3616): what a record template's Image binds as its `src`.\n */\n imageField?: string\n /**\n * The id of the record's page-address field, where it has one (AGL-3727):\n * what a listing's card links each record's own page by. Where the site\n * already serves record pages for the dataset, the field those pages are\n * served by (AGL-3747).\n */\n addressField?: string\n /**\n * Where this site already serves each record a page of its own (AGL-3747):\n * the base of the dataset's saved record template (AGL-3475), without\n * slashes at either end — `team` for `/team/ada`. Absent where the site\n * keeps no record template for it. Never shown in the prompt: code links a\n * listing's cards by it.\n */\n recordBase?: string\n /**\n * The page that template is (AGL-3616): the screen whose `{{item.*}}` the\n * site fills with each record. Never shown in the prompt: an edit to that\n * page reads it to know its tokens are filled.\n */\n recordScreenId?: string\n /**\n * Whether it is shared with this site and no other (AGL-3912): its scope\n * names this site alone, so it was made for this site. Absent where it is\n * the workspace's, shared with every site, or with others besides.\n */\n siteOnly?: true\n /**\n * How many records it holds (AGL-3912), counted for a site start's plan\n * only (`aiSiteInventoryWithRecordCounts`); absent where nobody counted, or\n * the count failed. Never shown in the prompt.\n */\n records?: number\n /**\n * Set on a site start's plan only (AGL-3912), where its records are not\n * this site's to show (`aiSiteDatasetIsThisSites`): the plan makes it\n * again rather than reuse it, so a creation of its name is no duplicate.\n */\n foreign?: true\n}\n\nexport interface AiInventoryCollection {\n id: string\n name: string\n slug: string\n}\n\nexport interface AiInventoryScreen {\n id: string\n name: string\n slug: string\n layoutId: string | null\n /** A collection's entry template rather than a page of its own. */\n template: boolean\n /**\n * The platform's starter home page, untouched since the site was created\n * (AGL-3594): the screen `host.defaultHomeScreenId` names, still answering\n * `/`, with no version but the one it was provisioned with. A plan may put\n * its own home page at its address, and publishing that page retires this\n * one (AGL-3408). Absent on every other screen, and on a starter home the\n * owner has edited, which a plan keeps and plans around.\n */\n replaceable?: true\n}\n\n/**\n * The site's one theme, as a planner and the email rule read it: a short\n * description, the light scheme's colors by palette path, and the families\n * the theme loads.\n */\nexport interface AiInventoryTheme {\n summary: string[]\n colors: Record<string, string>\n fonts: string[]\n}\n\nexport interface AiSiteInventory {\n hostId: string\n components: AiInventoryComponent[]\n layouts: AiInventoryLayout[]\n templates: AiInventoryTemplate[]\n forms: AiInventoryForm[]\n datasets: AiInventoryDataset[]\n collections: AiInventoryCollection[]\n screens: AiInventoryScreen[]\n theme: AiInventoryTheme | null\n /** Kinds with more records than are listed. */\n truncated: AiInventoryKind[]\n}\n\n/** One inventory record, whatever kind it is. */\nexport type AiInventoryRow =\n | AiInventoryComponent\n | AiInventoryLayout\n | AiInventoryTemplate\n | AiInventoryForm\n | AiInventoryDataset\n | AiInventoryCollection\n | AiInventoryScreen\n\n/**\n * The rows of one kind. The inventory's fields are named after their kinds,\n * so this is a lookup rather than a switch, and it is the one place that\n * relies on the correspondence: the prompt block, the lookup tool and their\n * specs all read a kind through it.\n */\nexport function aiInventoryRows(\n inventory: AiSiteInventory,\n kind: AiInventoryKind,\n): readonly AiInventoryRow[] {\n return inventory[kind]\n}\n\n/** The heading one kind's lines are listed under, naming its columns in order. */\nexport const AI_INVENTORY_KIND_HEADINGS: Readonly<Record<AiInventoryKind, string>> = {\n components: 'Reusable components (id \\u00b7 name \\u00b7 props an instance fills)',\n layouts: 'Layouts (id \\u00b7 name)',\n templates: 'Templates (id \\u00b7 name \\u00b7 kind)',\n forms: 'Forms (id \\u00b7 name \\u00b7 fields)',\n datasets: 'Datasets (id \\u00b7 name \\u00b7 fields)',\n collections: 'Content collections (id \\u00b7 name \\u00b7 slug)',\n screens: 'Pages (id \\u00b7 name \\u00b7 slug)',\n}\n\n/**\n * One record as a line, in the order its heading names the columns. The one\n * renderer: the prompt block and the lookup tool's answer read alike, so a\n * row found by lookup is the same shape as a row that was listed.\n */\nexport function aiInventoryLine(kind: AiInventoryKind, row: AiInventoryRow): string {\n const head = `${row.id} \\u00b7 ${row.name}`\n switch (kind) {\n case 'components': {\n const props = Object.entries((row as AiInventoryComponent).props)\n .map(([name, type]) => `${name}:${type}`)\n .join(', ')\n return `${head} \\u00b7 ${props || 'no props'}`\n }\n case 'layouts':\n return head\n case 'templates':\n return `${head} \\u00b7 ${(row as AiInventoryTemplate).kind}`\n case 'forms':\n return `${head} \\u00b7 ${(row as AiInventoryForm).fields.join(', ')}`\n case 'datasets':\n return `${head} \\u00b7 ${(row as AiInventoryDataset).fields.join(', ')}`\n case 'collections':\n return `${head} \\u00b7 ${(row as AiInventoryCollection).slug}`\n case 'screens': {\n const screen = row as AiInventoryScreen\n return `${head} \\u00b7 ${screen.slug}${screen.template ? ' \\u00b7 entry template' : ''}${\n screen.replaceable ? ' \\u00b7 starter home, a planned home page at / replaces it' : ''\n }`\n }\n }\n}\n\n/** Every word of a record a lookup searches: its line, which holds them all. */\nexport function aiInventoryHaystack(kind: AiInventoryKind, row: AiInventoryRow): string {\n return aiInventoryLine(kind, row).toLowerCase()\n}\n\n/** The addresses a site's home screen is stored under. */\nconst HOME_SLUGS = new Set(['', 'home', 'index'])\n\n/**\n * The site's home screens, by id (AGL-3056): a screen at the root or at\n * `home`, as a seeded site stores its first screen, or one named Home. A link\n * with nowhere to go is sent there, which is why the doctrine names them.\n */\nexport function aiHomeScreenIds(inventory: AiSiteInventory | null): string[] {\n const homes = (inventory?.screens ?? []).filter(\n (screen) =>\n !screen.template &&\n (HOME_SLUGS.has(screen.slug.trim().replace(/^\\/+|\\/+$/g, '').toLowerCase()) ||\n /^home(?:\\s?page)?$/i.test(screen.name.trim())),\n )\n // A starter home a planned home page replaces (AGL-3594) is retired when\n // that page is published, so a link is sent to the page that replaces it\n // wherever the site already has one.\n const kept = homes.filter((screen) => !screen.replaceable)\n return (kept.length ? kept : homes).map((screen) => screen.id)\n}\n\n/** The titles of the site's home screens ({@link aiHomeScreenIds}): a link under one says home, in the site's own language (AGL-3760). */\nexport function aiHomeScreenNames(inventory: AiSiteInventory | null): string[] {\n const ids = new Set(aiHomeScreenIds(inventory))\n return (inventory?.screens ?? []).filter((screen) => ids.has(screen.id) && screen.name.trim()).map((screen) => screen.name.trim())\n}\n\n/** A site the org does not own; the inventory is never read for it. */\nexport class AiInventoryScopeError extends Error {\n constructor(hostId: string) {\n super(`host ${hostId} is not a site of the workspace that asked`)\n this.name = 'AiInventoryScopeError'\n }\n}\n\nexport function emptyAiSiteInventory(hostId: string): AiSiteInventory {\n return {\n hostId,\n components: [],\n layouts: [],\n templates: [],\n forms: [],\n datasets: [],\n collections: [],\n screens: [],\n theme: null,\n truncated: [],\n }\n}\n"],"names":["AI_SITE_INVENTORY_MAX_PER_KIND","AI_SITE_INVENTORY_LISTED_PER_KIND","AI_SITE_INVENTORY_MAX_CHARS","AI_INVENTORY_KINDS","aiInventoryRows","inventory","kind","AI_INVENTORY_KIND_HEADINGS","components","layouts","templates","forms","datasets","collections","screens","aiInventoryLine","row","head","id","name","props","Object","entries","map","type","join","fields","slug","screen","template","replaceable","aiInventoryHaystack","toLowerCase","HOME_SLUGS","Set","aiHomeScreenIds","homes","filter","has","trim","replace","test","kept","length","aiHomeScreenNames","ids","AiInventoryScopeError","Error","hostId","emptyAiSiteInventory","theme","truncated"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GAED;;;;;CAKC,GACD,OAAO,MAAMA,iCAAiC,IAAG;AAEjD,wEAAwE,GACxE,OAAO,MAAMC,oCAAoC,GAAE;AAEnD,2EAA2E,GAC3E,OAAO,MAAMC,8BAA8B,KAAK;AAWhD,OAAO,MAAMC,qBAAiD;IAC5D;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AA2JD;;;;;CAKC,GACD,OAAO,SAASC,gBACdC,SAA0B,EAC1BC,IAAqB;IAErB,OAAOD,SAAS,CAACC,KAAK;AACxB;AAEA,gFAAgF,GAChF,OAAO,MAAMC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AE;QACXoC,OAAO;QACPC,WAAW,EAAE;IACf;AACF"}
@@ -64,6 +64,14 @@ export declare const ASSIST_EDIT_CONTEXT_MAX_PROPS = 16;
64
64
  export declare const ASSIST_EDIT_SELECTED_TEXT_CHARS = 400;
65
65
  /** Characters of a string prop every other element carries. */
66
66
  export declare const ASSIST_EDIT_OUTLINE_TEXT_CHARS = 80;
67
+ /**
68
+ * Elements a whole-document outline describes at most: one the server reads
69
+ * from the stored document for an edit job, where nothing is selected and
70
+ * nobody can be asked to select what the outline leaves out. Far past a page
71
+ * an AI build or a starter makes (the starter home has 182), so in practice
72
+ * the model sees every element it could be asked about.
73
+ */
74
+ export declare const ASSIST_EDIT_WHOLE_MAX_NODES = 400;
67
75
  /**
68
76
  * One element of the canvas outline a request carries. Ids, component ids
69
77
  * and short primitive values only — never a stored document, never markup.
@@ -80,7 +88,10 @@ export interface AssistEditCanvasNode {
80
88
  name?: string;
81
89
  /** Primitive props, strings shortened. */
82
90
  props?: Record<string, string | number | boolean>;
83
- /** The element's own styles — carried for the selected element only. */
91
+ /**
92
+ * The element's own styles — carried for the selected element only, and
93
+ * for every element of a whole-document outline.
94
+ */
84
95
  sx?: Record<string, unknown>;
85
96
  /**
86
97
  * Described by its place alone, without props: an element around the
@@ -131,6 +142,12 @@ export interface AssistEditCanvasContext {
131
142
  */
132
143
  total?: number;
133
144
  nodes: AssistEditCanvasNode[];
145
+ /**
146
+ * The document as stored, read on the server for a job: every element in
147
+ * page order up to {@link ASSIST_EDIT_WHOLE_MAX_NODES}, each with its
148
+ * settings and styles, and nobody to ask. Never read from a request body.
149
+ */
150
+ whole?: true;
134
151
  }
135
152
  /** An element of a validated subtree, in the flat shape the canvas stores. */
136
153
  export interface AssistEditNode {
@@ -72,6 +72,13 @@ const BESIGNER_DOCUMENT_ROUTE = /^\/[^/]+\/hosts\/[^/]+\/(screens|components|lay
72
72
  /** Props described per element at most. */ export const ASSIST_EDIT_CONTEXT_MAX_PROPS = 16;
73
73
  /** Characters of a string prop the selected element carries into a request. */ export const ASSIST_EDIT_SELECTED_TEXT_CHARS = 400;
74
74
  /** Characters of a string prop every other element carries. */ export const ASSIST_EDIT_OUTLINE_TEXT_CHARS = 80;
75
+ /**
76
+ * Elements a whole-document outline describes at most: one the server reads
77
+ * from the stored document for an edit job, where nothing is selected and
78
+ * nobody can be asked to select what the outline leaves out. Far past a page
79
+ * an AI build or a starter makes (the starter home has 182), so in practice
80
+ * the model sees every element it could be asked about.
81
+ */ export const ASSIST_EDIT_WHOLE_MAX_NODES = 400;
75
82
  /* ------------------------------------------------------------------ *
76
83
  * The interactions Assist may add (AGL-3603)
77
84
  * ------------------------------------------------------------------ */ /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/assist-edit.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ScreenSeoTextField } from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport type { ReusableComponentProp } from '@aglyn/aglyn/foundation/definitions/platform.types'\nimport type { NodeInteraction } from '@aglyn/aglyn/app-utils/node-interactions'\n\n/**\n * Assist level 3, the edit contract (AGL-2906): what the chat door proposes\n * for a besigner canvas, and what the panel applies once the author says so.\n *\n * Shared by the server, which validates a model's proposal into these\n * shapes, and the client, which applies them. Pure data and pure functions,\n * so the panel imports it without pulling the palette or the runtime.\n *\n * ## The boundary\n *\n * A proposal is OPERATIONS, never a document. The server writes nothing: it\n * answers with ops that name elements already on the canvas, or a validated\n * subtree to insert, and the client applies them through the canvas's own\n * guarded mutators, on confirm, as one undoable step. Every change lands as\n * an unsaved edit on the version the editor has open — a draft — and on a\n * version the live site serves, the editor's own new-version flow runs first.\n */\n\n/** The nine operations a proposal may carry. */\nexport const ASSIST_EDIT_OP_KINDS = [\n 'insertSubtree',\n 'updateProps',\n 'updateSx',\n 'move',\n 'remove',\n 'setSeo',\n 'rename',\n 'saveAsComponent',\n 'addInteraction',\n] as const\n\nexport type AssistEditOpKind = (typeof ASSIST_EDIT_OP_KINDS)[number]\n\n/** The id of the besigner view's edit action — the one edit a view offers. */\nexport const ASSIST_EDIT_ACTION_ID = 'edit.canvas'\n\n/** The name of the structured-output tool a model proposes an edit through. */\nexport const ASSIST_EDIT_TOOL_NAME = 'propose_canvas_edit'\n\n/** The besigner documents the edit rung opens on: those that keep versions. */\nexport type AssistEditDocumentKind = 'screen' | 'component' | 'layout'\n\nexport const ASSIST_EDIT_DOCUMENT_KINDS: readonly AssistEditDocumentKind[] = [\n 'screen',\n 'component',\n 'layout',\n]\n\nconst COLLECTION_KINDS: Readonly<Record<string, AssistEditDocumentKind>> = {\n screens: 'screen',\n components: 'component',\n layouts: 'layout',\n}\n\nconst BESIGNER_DOCUMENT_ROUTE =\n /^\\/[^/]+\\/hosts\\/[^/]+\\/(screens|components|layouts)\\/([A-Za-z0-9_-]{1,64})\\/versions\\/([A-Za-z0-9_-]{1,64})\\/besigner\\/?$/\n\n/** The document a besigner route has open. */\nexport interface AssistEditDocument {\n kind: AssistEditDocumentKind\n documentId: string\n versionId: string\n}\n\n/**\n * The open document off a console path, or null off a route the edit rung\n * serves. Only the versioned editors qualify — a template or an email editor\n * has no version to make first, so the rung does not open there.\n */\nexport function assistEditDocumentOf(route: string): AssistEditDocument | null {\n const match = BESIGNER_DOCUMENT_ROUTE.exec(String(route ?? ''))\n if (!match) return null\n return {\n kind: COLLECTION_KINDS[match[1]],\n documentId: match[2],\n versionId: match[3],\n }\n}\n\n/* ------------------------------------------------------------------ *\n * What the client tells the server about the canvas\n * ------------------------------------------------------------------ */\n\n/** Elements a request describes at most — the selection, its surroundings, its subtree. */\nexport const ASSIST_EDIT_CONTEXT_MAX_NODES = 60\n/** Props described per element at most. */\nexport const ASSIST_EDIT_CONTEXT_MAX_PROPS = 16\n/** Characters of a string prop the selected element carries into a request. */\nexport const ASSIST_EDIT_SELECTED_TEXT_CHARS = 400\n/** Characters of a string prop every other element carries. */\nexport const ASSIST_EDIT_OUTLINE_TEXT_CHARS = 80\n\n/**\n * One element of the canvas outline a request carries. Ids, component ids\n * and short primitive values only — never a stored document, never markup.\n */\nexport interface AssistEditCanvasNode {\n id: string\n componentId: string\n /** Null for the document root. */\n parentId: string | null\n /** Position among the parent's children. */\n index: number\n childCount: number\n /** The layer name, when the author gave it one. */\n name?: string\n /** Primitive props, strings shortened. */\n props?: Record<string, string | number | boolean>\n /** The element's own styles — carried for the selected element only. */\n sx?: Record<string, unknown>\n /**\n * Described by its place alone, without props: an element around the\n * selection, there so the model knows it exists and can ask for it.\n */\n brief?: boolean\n /**\n * An element described earlier whose contents this one's are built like,\n * the way the cards of a row are. Its own contents are left out.\n */\n like?: string\n /**\n * The interactions the element carries (AGL-3603), each by its name, the\n * event it listens for and its steps' kinds — carried for the selected\n * element only, so Assist can say what it does. Never a selector, a script\n * or HTML.\n */\n interactions?: AssistEditInteractionSummary[]\n}\n\n/** One interaction on an element, as an outline describes it. */\nexport interface AssistEditInteractionSummary {\n name: string\n event: string\n steps: string[]\n enabled: boolean\n}\n\n/* ------------------------------------------------------------------ *\n * The interactions Assist may add (AGL-3603)\n * ------------------------------------------------------------------ */\n\n/**\n * The events an interaction Assist adds may listen for: those that watch the\n * element it is added to, the way the Besigner's Interactions section offers\n * them on a selected element.\n */\nexport const ASSIST_EDIT_INTERACTION_EVENTS = [\n 'elementClick',\n 'elementHoverEnter',\n 'elementHoverLeave',\n 'elementVisible',\n 'scrollToElement',\n] as const\n\nexport type AssistEditInteractionEvent = (typeof ASSIST_EDIT_INTERACTION_EVENTS)[number]\n\n/**\n * The steps it may take: the platform's basic presentational client steps,\n * which run on every plan and touch no data. No script, no HTML, no\n * attribute, no overlay, no analytics event — and no server step.\n */\nexport const ASSIST_EDIT_INTERACTION_STEPS = [\n 'showElement',\n 'hideElement',\n 'toggleElement',\n 'addClass',\n 'removeClass',\n 'toggleClass',\n 'scrollTo',\n 'playVideo',\n 'openDrawer',\n 'closeDrawer',\n 'toggleDrawer',\n 'openMenu',\n 'closeMenu',\n 'toggleMenu',\n 'redirect',\n 'siteAlert',\n] as const\n\nexport type AssistEditInteractionStep = (typeof ASSIST_EDIT_INTERACTION_STEPS)[number]\n\nexport interface AssistEditCanvasContext {\n /** The element the author has selected, or null. */\n selectedId: string | null\n /**\n * Elements in the whole document, the root included, so the prompt can say\n * how much of it `nodes` leaves out. Absent from an outline sent by a panel\n * that predates it.\n */\n total?: number\n nodes: AssistEditCanvasNode[]\n}\n\n/* ------------------------------------------------------------------ *\n * What the server proposes\n * ------------------------------------------------------------------ */\n\n/** An element of a validated subtree, in the flat shape the canvas stores. */\nexport interface AssistEditNode {\n $id: string\n componentId: string\n pluginId?: string\n parentId: string | null\n nodes: string[]\n props: Record<string, unknown>\n sx?: Record<string, unknown>\n hidden?: boolean\n}\n\n/**\n * Every op that acts on an element names the component the server validated\n * it as, so the client can refuse an element that has changed since.\n */\ninterface AssistEditNodeOpBase {\n nodeId: string\n componentId: string\n}\n\nexport interface AssistEditInsertOp {\n op: 'insertSubtree'\n parentId: string\n /** The component the parent was validated as. */\n parentComponentId: string\n /** Position among the parent's children; null appends. */\n index: number | null\n rootId: string\n nodes: Record<string, AssistEditNode>\n}\n\nexport interface AssistEditUpdatePropsOp extends AssistEditNodeOpBase {\n op: 'updateProps'\n /** Merged over the props the element has; nothing else it carries changes. */\n props: Record<string, unknown>\n}\n\nexport interface AssistEditUpdateSxOp extends AssistEditNodeOpBase {\n op: 'updateSx'\n /** Merged over the element's own styles, one key at a time. */\n sx: Record<string, unknown>\n}\n\nexport interface AssistEditMoveOp extends AssistEditNodeOpBase {\n op: 'move'\n parentId: string\n /** The component the new parent was validated as. */\n parentComponentId: string\n index: number | null\n}\n\nexport interface AssistEditRemoveOp extends AssistEditNodeOpBase {\n op: 'remove'\n}\n\nexport interface AssistEditRenameOp extends AssistEditNodeOpBase {\n op: 'rename'\n name: string\n}\n\nexport interface AssistEditSetSeoOp {\n op: 'setSeo'\n fields: Partial<Record<ScreenSeoTextField, string>>\n}\n\n/**\n * A property the promoted subtree declares (AGL-2908), in the shape the\n * Properties dialog stores one — without a default.\n *\n * The server never sees a full value: the outline it read the selection from\n * shortens every string. So the default is read off the live canvas at apply\n * time, from the very field the token is about to replace, which is what\n * makes the instance render what was there a moment before.\n */\nexport type AssistEditComponentProp = Omit<ReusableComponentProp, 'defaultValue'>\n\n/** Where one property's token goes: an element of the selection, and a field of it. */\nexport interface AssistEditPropBinding {\n nodeId: string\n /** The component the element was validated as, so a changed one is refused. */\n componentId: string\n /** A prop of that element, or `hideIf` for a part a Yes / no hides. */\n field: string\n /** The property whose `{{prop.<name>}}` token the field takes. */\n prop: string\n}\n\n/**\n * Save the selection as a reusable component (AGL-2908), with the properties\n * the model proposed and the tokens bound into the tree.\n *\n * The only op that creates a document. It creates exactly the one the manual\n * Save as reusable component creates, through the same host resources route,\n * where the plan's entitlement and the route's allow-list are enforced — and\n * it changes the open canvas the same way that action does, by swapping the\n * promoted subtree for an instance. Nothing is published and nothing is\n * saved: the swap is an unsaved edit on the version the editor has open.\n */\nexport interface AssistEditSaveAsComponentOp extends AssistEditNodeOpBase {\n op: 'saveAsComponent'\n /** The name the component is created under. */\n name: string\n props: AssistEditComponentProp[]\n bindings: AssistEditPropBinding[]\n}\n\n/**\n * Add one interaction to an element (AGL-3603), in the shape the element\n * stores it — its trigger with no selector, which the element's id derives.\n * It never replaces or removes one the element already carries.\n */\nexport interface AssistEditAddInteractionOp extends AssistEditNodeOpBase {\n op: 'addInteraction'\n interaction: NodeInteraction\n /** Every other element a step acts on, each with the component it was validated as. */\n targets: Array<{ nodeId: string; componentId: string }>\n}\n\nexport type AssistEditOp =\n | AssistEditAddInteractionOp\n | AssistEditInsertOp\n | AssistEditUpdatePropsOp\n | AssistEditUpdateSxOp\n | AssistEditMoveOp\n | AssistEditRemoveOp\n | AssistEditRenameOp\n | AssistEditSetSeoOp\n | AssistEditSaveAsComponentOp\n\n/** Where a proposal applies, as the server read it off the request. */\nexport interface AssistEditTarget extends AssistEditDocument {\n hostId: string\n}\n\n/** The counts the card shows before the author decides. */\nexport interface AssistEditDiff {\n /** Elements added, every element of every inserted subtree counted. */\n added: number\n /** Elements removed — each with whatever it contains. */\n removed: number\n propsChanged: number\n stylesChanged: number\n moved: number\n renamed: number\n /** Search fields filled in. */\n seoFields: number\n /** Properties the selection declares once it is saved as a component. */\n componentProps: number\n /** Selections saved as a reusable component — at most one per proposal. */\n componentsSaved: number\n /** Interactions added to elements. */\n interactionsAdded: number\n}\n\n/** The most reasons a proposal carries for the changes validation left out. */\nexport const ASSIST_EDIT_MAX_DROPPED_REASONS = 10\n\nexport interface AssistEditProposal {\n id: typeof ASSIST_EDIT_ACTION_ID\n /** One line, in the model's words, of what the edit does. */\n summary: string\n ops: AssistEditOp[]\n diff: AssistEditDiff\n /** Why each change the model wrote and validation refused was left out. */\n dropped: string[]\n target: AssistEditTarget\n}\n\n/** The counts for a list of ops. */\nexport function summarizeAssistEditOps(ops: readonly AssistEditOp[]): AssistEditDiff {\n const diff: AssistEditDiff = {\n added: 0,\n removed: 0,\n propsChanged: 0,\n stylesChanged: 0,\n moved: 0,\n renamed: 0,\n seoFields: 0,\n componentProps: 0,\n componentsSaved: 0,\n interactionsAdded: 0,\n }\n for (const op of ops) {\n switch (op.op) {\n case 'insertSubtree':\n diff.added += Object.keys(op.nodes).length\n break\n case 'remove':\n diff.removed += 1\n break\n case 'updateProps':\n diff.propsChanged += 1\n break\n case 'updateSx':\n diff.stylesChanged += 1\n break\n case 'move':\n diff.moved += 1\n break\n case 'rename':\n diff.renamed += 1\n break\n case 'setSeo':\n diff.seoFields += Object.keys(op.fields).length\n break\n case 'saveAsComponent':\n diff.componentsSaved += 1\n diff.componentProps += op.props.length\n break\n case 'addInteraction':\n diff.interactionsAdded += 1\n break\n }\n }\n return diff\n}\n\nconst plural = (count: number, one: string, many: string): string =>\n `${count} ${count === 1 ? one : many}`\n\n/** The diff as the lines a person reads, zero counts omitted. */\nexport function describeAssistEditDiff(diff: AssistEditDiff): string[] {\n const lines: string[] = []\n if (diff.added) lines.push(`${plural(diff.added, 'element', 'elements')} added`)\n if (diff.removed) lines.push(`${plural(diff.removed, 'element', 'elements')} removed`)\n if (diff.propsChanged) {\n lines.push(`${plural(diff.propsChanged, 'element’s settings', 'elements’ settings')} changed`)\n }\n if (diff.stylesChanged) {\n lines.push(`${plural(diff.stylesChanged, 'element', 'elements')} restyled`)\n }\n if (diff.moved) lines.push(`${plural(diff.moved, 'element', 'elements')} moved`)\n if (diff.renamed) lines.push(`${plural(diff.renamed, 'layer', 'layers')} renamed`)\n if (diff.seoFields) {\n lines.push(`${plural(diff.seoFields, 'search field', 'search fields')} filled in`)\n }\n if (diff.interactionsAdded) {\n lines.push(`${plural(diff.interactionsAdded, 'interaction', 'interactions')} added`)\n }\n if (diff.componentsSaved) {\n lines.push(\n `saved as a reusable component with ${plural(diff.componentProps, 'property', 'properties')}`,\n )\n }\n return lines\n}\n\n/** The word each op kind is counted under in the activity row. */\nconst OP_COUNT_WORDS: Readonly<Record<AssistEditOpKind, string>> = {\n updateProps: 'set',\n updateSx: 'restyle',\n insertSubtree: 'insert',\n move: 'move',\n remove: 'remove',\n rename: 'rename',\n setSeo: 'seo',\n saveAsComponent: 'component',\n addInteraction: 'interaction',\n}\n\n/** The applied ops counted by kind, as the activity row names them (`{ set: 3, insert: 1 }`). */\nexport function assistEditOpCounts(ops: readonly AssistEditOp[]): Record<string, number> {\n const counts: Record<string, number> = {}\n for (const op of ops) {\n const word = OP_COUNT_WORDS[op.op]\n if (word) counts[word] = (counts[word] ?? 0) + 1\n }\n return counts\n}\n\n/** The words `assistEditOpCounts` counts under, for a door that reads them back. */\nexport const ASSIST_EDIT_OP_COUNT_WORDS: readonly string[] = Object.values(OP_COUNT_WORDS)\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Whether a `done` event's `edit` field is a proposal this client can apply.\n * The server built it, so this is a shape check rather than a validation: it\n * keeps a malformed or foreign payload from reaching the canvas mutators.\n */\nexport function isAssistEditProposal(value: unknown): value is AssistEditProposal {\n if (!isRecord(value) || value['id'] !== ASSIST_EDIT_ACTION_ID) return false\n const target = value['target']\n if (!isRecord(target)) return false\n if (!ASSIST_EDIT_DOCUMENT_KINDS.includes(target['kind'] as AssistEditDocumentKind)) return false\n if (typeof target['documentId'] !== 'string' || !target['documentId']) return false\n const ops = value['ops']\n if (!Array.isArray(ops) || !ops.length) return false\n return ops.every(\n (op) => isRecord(op) && ASSIST_EDIT_OP_KINDS.includes(op['op'] as AssistEditOpKind),\n )\n}\n\n/* ------------------------------------------------------------------ *\n * What the client reports once the author applied a proposal\n * ------------------------------------------------------------------ */\n\n/** The body of `POST /api/assist/edit-applied`. */\nexport interface AssistEditAppliedReport {\n orgId: string\n hostId: string\n /** The exchange whose answer carried the proposal. */\n exchangeId: string\n documentKind: AssistEditDocumentKind\n documentId: string\n /** The version the edits landed on — a new one when the open one was live. */\n versionId: string\n opCounts: Record<string, number>\n}\n"],"names":["ASSIST_EDIT_OP_KINDS","ASSIST_EDIT_ACTION_ID","ASSIST_EDIT_TOOL_NAME","ASSIST_EDIT_DOCUMENT_KINDS","COLLECTION_KINDS","screens","components","layouts","BESIGNER_DOCUMENT_ROUTE","assistEditDocumentOf","route","match","exec","String","kind","documentId","versionId","ASSIST_EDIT_CONTEXT_MAX_NODES","ASSIST_EDIT_CONTEXT_MAX_PROPS","ASSIST_EDIT_SELECTED_TEXT_CHARS","ASSIST_EDIT_OUTLINE_TEXT_CHARS","ASSIST_EDIT_INTERACTION_EVENTS","ASSIST_EDIT_INTERACTION_STEPS","ASSIST_EDIT_MAX_DROPPED_REASONS","summarizeAssistEditOps","ops","diff","added","removed","propsChanged","stylesChanged","moved","renamed","seoFields","componentProps","componentsSaved","interactionsAdded","op","Object","keys","nodes","length","fields","props","plural","count","one","many","describeAssistEditDiff","lines","push","OP_COUNT_WORDS","updateProps","updateSx","insertSubtree","move","remove","rename","setSeo","saveAsComponent","addInteraction","assistEditOpCounts","counts","word","ASSIST_EDIT_OP_COUNT_WORDS","values","isRecord","value","Array","isArray","isAssistEditProposal","target","includes","every"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAMD;;;;;;;;;;;;;;;;CAgBC,GAED,8CAA8C,GAC9C,OAAO,MAAMA,uBAAuB;IAClC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AAIV,4EAA4E,GAC5E,OAAO,MAAMC,wBAAwB,cAAa;AAElD,6EAA6E,GAC7E,OAAO,MAAMC,wBAAwB,sBAAqB;AAK1D,OAAO,MAAMC,6BAAgE;IAC3E;IACA;IACA;CACD,CAAA;AAED,MAAMC,mBAAqE;IACzEC,SAAS;IACTC,YAAY;IACZC,SAAS;AACX;AAEA,MAAMC,0BACJ;AASF;;;;CAIC,GACD,OAAO,SAASC,qBAAqBC,KAAa;IAChD,MAAMC,QAAQH,wBAAwBI,IAAI,CAACC,OAAOH,gBAAAA,QAAS;IAC3D,IAAI,CAACC,OAAO,OAAO;IACnB,OAAO;QACLG,MAAMV,gBAAgB,CAACO,KAAK,CAAC,EAAE,CAAC;QAChCI,YAAYJ,KAAK,CAAC,EAAE;QACpBK,WAAWL,KAAK,CAAC,EAAE;IACrB;AACF;AAEA;;sEAEsE,GAEtE,yFAAyF,GACzF,OAAO,MAAMM,gCAAgC,GAAE;AAC/C,yCAAyC,GACzC,OAAO,MAAMC,gCAAgC,GAAE;AAC/C,6EAA6E,GAC7E,OAAO,MAAMC,kCAAkC,IAAG;AAClD,6DAA6D,GAC7D,OAAO,MAA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../../../libs/plugins/ai/src/lib/model/assist-edit.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ScreenSeoTextField } from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport type { ReusableComponentProp } from '@aglyn/aglyn/foundation/definitions/platform.types'\nimport type { NodeInteraction } from '@aglyn/aglyn/app-utils/node-interactions'\n\n/**\n * Assist level 3, the edit contract (AGL-2906): what the chat door proposes\n * for a besigner canvas, and what the panel applies once the author says so.\n *\n * Shared by the server, which validates a model's proposal into these\n * shapes, and the client, which applies them. Pure data and pure functions,\n * so the panel imports it without pulling the palette or the runtime.\n *\n * ## The boundary\n *\n * A proposal is OPERATIONS, never a document. The server writes nothing: it\n * answers with ops that name elements already on the canvas, or a validated\n * subtree to insert, and the client applies them through the canvas's own\n * guarded mutators, on confirm, as one undoable step. Every change lands as\n * an unsaved edit on the version the editor has open — a draft — and on a\n * version the live site serves, the editor's own new-version flow runs first.\n */\n\n/** The nine operations a proposal may carry. */\nexport const ASSIST_EDIT_OP_KINDS = [\n 'insertSubtree',\n 'updateProps',\n 'updateSx',\n 'move',\n 'remove',\n 'setSeo',\n 'rename',\n 'saveAsComponent',\n 'addInteraction',\n] as const\n\nexport type AssistEditOpKind = (typeof ASSIST_EDIT_OP_KINDS)[number]\n\n/** The id of the besigner view's edit action — the one edit a view offers. */\nexport const ASSIST_EDIT_ACTION_ID = 'edit.canvas'\n\n/** The name of the structured-output tool a model proposes an edit through. */\nexport const ASSIST_EDIT_TOOL_NAME = 'propose_canvas_edit'\n\n/** The besigner documents the edit rung opens on: those that keep versions. */\nexport type AssistEditDocumentKind = 'screen' | 'component' | 'layout'\n\nexport const ASSIST_EDIT_DOCUMENT_KINDS: readonly AssistEditDocumentKind[] = [\n 'screen',\n 'component',\n 'layout',\n]\n\nconst COLLECTION_KINDS: Readonly<Record<string, AssistEditDocumentKind>> = {\n screens: 'screen',\n components: 'component',\n layouts: 'layout',\n}\n\nconst BESIGNER_DOCUMENT_ROUTE =\n /^\\/[^/]+\\/hosts\\/[^/]+\\/(screens|components|layouts)\\/([A-Za-z0-9_-]{1,64})\\/versions\\/([A-Za-z0-9_-]{1,64})\\/besigner\\/?$/\n\n/** The document a besigner route has open. */\nexport interface AssistEditDocument {\n kind: AssistEditDocumentKind\n documentId: string\n versionId: string\n}\n\n/**\n * The open document off a console path, or null off a route the edit rung\n * serves. Only the versioned editors qualify — a template or an email editor\n * has no version to make first, so the rung does not open there.\n */\nexport function assistEditDocumentOf(route: string): AssistEditDocument | null {\n const match = BESIGNER_DOCUMENT_ROUTE.exec(String(route ?? ''))\n if (!match) return null\n return {\n kind: COLLECTION_KINDS[match[1]],\n documentId: match[2],\n versionId: match[3],\n }\n}\n\n/* ------------------------------------------------------------------ *\n * What the client tells the server about the canvas\n * ------------------------------------------------------------------ */\n\n/** Elements a request describes at most — the selection, its surroundings, its subtree. */\nexport const ASSIST_EDIT_CONTEXT_MAX_NODES = 60\n/** Props described per element at most. */\nexport const ASSIST_EDIT_CONTEXT_MAX_PROPS = 16\n/** Characters of a string prop the selected element carries into a request. */\nexport const ASSIST_EDIT_SELECTED_TEXT_CHARS = 400\n/** Characters of a string prop every other element carries. */\nexport const ASSIST_EDIT_OUTLINE_TEXT_CHARS = 80\n/**\n * Elements a whole-document outline describes at most: one the server reads\n * from the stored document for an edit job, where nothing is selected and\n * nobody can be asked to select what the outline leaves out. Far past a page\n * an AI build or a starter makes (the starter home has 182), so in practice\n * the model sees every element it could be asked about.\n */\nexport const ASSIST_EDIT_WHOLE_MAX_NODES = 400\n\n/**\n * One element of the canvas outline a request carries. Ids, component ids\n * and short primitive values only — never a stored document, never markup.\n */\nexport interface AssistEditCanvasNode {\n id: string\n componentId: string\n /** Null for the document root. */\n parentId: string | null\n /** Position among the parent's children. */\n index: number\n childCount: number\n /** The layer name, when the author gave it one. */\n name?: string\n /** Primitive props, strings shortened. */\n props?: Record<string, string | number | boolean>\n /**\n * The element's own styles — carried for the selected element only, and\n * for every element of a whole-document outline.\n */\n sx?: Record<string, unknown>\n /**\n * Described by its place alone, without props: an element around the\n * selection, there so the model knows it exists and can ask for it.\n */\n brief?: boolean\n /**\n * An element described earlier whose contents this one's are built like,\n * the way the cards of a row are. Its own contents are left out.\n */\n like?: string\n /**\n * The interactions the element carries (AGL-3603), each by its name, the\n * event it listens for and its steps' kinds — carried for the selected\n * element only, so Assist can say what it does. Never a selector, a script\n * or HTML.\n */\n interactions?: AssistEditInteractionSummary[]\n}\n\n/** One interaction on an element, as an outline describes it. */\nexport interface AssistEditInteractionSummary {\n name: string\n event: string\n steps: string[]\n enabled: boolean\n}\n\n/* ------------------------------------------------------------------ *\n * The interactions Assist may add (AGL-3603)\n * ------------------------------------------------------------------ */\n\n/**\n * The events an interaction Assist adds may listen for: those that watch the\n * element it is added to, the way the Besigner's Interactions section offers\n * them on a selected element.\n */\nexport const ASSIST_EDIT_INTERACTION_EVENTS = [\n 'elementClick',\n 'elementHoverEnter',\n 'elementHoverLeave',\n 'elementVisible',\n 'scrollToElement',\n] as const\n\nexport type AssistEditInteractionEvent = (typeof ASSIST_EDIT_INTERACTION_EVENTS)[number]\n\n/**\n * The steps it may take: the platform's basic presentational client steps,\n * which run on every plan and touch no data. No script, no HTML, no\n * attribute, no overlay, no analytics event — and no server step.\n */\nexport const ASSIST_EDIT_INTERACTION_STEPS = [\n 'showElement',\n 'hideElement',\n 'toggleElement',\n 'addClass',\n 'removeClass',\n 'toggleClass',\n 'scrollTo',\n 'playVideo',\n 'openDrawer',\n 'closeDrawer',\n 'toggleDrawer',\n 'openMenu',\n 'closeMenu',\n 'toggleMenu',\n 'redirect',\n 'siteAlert',\n] as const\n\nexport type AssistEditInteractionStep = (typeof ASSIST_EDIT_INTERACTION_STEPS)[number]\n\nexport interface AssistEditCanvasContext {\n /** The element the author has selected, or null. */\n selectedId: string | null\n /**\n * Elements in the whole document, the root included, so the prompt can say\n * how much of it `nodes` leaves out. Absent from an outline sent by a panel\n * that predates it.\n */\n total?: number\n nodes: AssistEditCanvasNode[]\n /**\n * The document as stored, read on the server for a job: every element in\n * page order up to {@link ASSIST_EDIT_WHOLE_MAX_NODES}, each with its\n * settings and styles, and nobody to ask. Never read from a request body.\n */\n whole?: true\n}\n\n/* ------------------------------------------------------------------ *\n * What the server proposes\n * ------------------------------------------------------------------ */\n\n/** An element of a validated subtree, in the flat shape the canvas stores. */\nexport interface AssistEditNode {\n $id: string\n componentId: string\n pluginId?: string\n parentId: string | null\n nodes: string[]\n props: Record<string, unknown>\n sx?: Record<string, unknown>\n hidden?: boolean\n}\n\n/**\n * Every op that acts on an element names the component the server validated\n * it as, so the client can refuse an element that has changed since.\n */\ninterface AssistEditNodeOpBase {\n nodeId: string\n componentId: string\n}\n\nexport interface AssistEditInsertOp {\n op: 'insertSubtree'\n parentId: string\n /** The component the parent was validated as. */\n parentComponentId: string\n /** Position among the parent's children; null appends. */\n index: number | null\n rootId: string\n nodes: Record<string, AssistEditNode>\n}\n\nexport interface AssistEditUpdatePropsOp extends AssistEditNodeOpBase {\n op: 'updateProps'\n /** Merged over the props the element has; nothing else it carries changes. */\n props: Record<string, unknown>\n}\n\nexport interface AssistEditUpdateSxOp extends AssistEditNodeOpBase {\n op: 'updateSx'\n /** Merged over the element's own styles, one key at a time. */\n sx: Record<string, unknown>\n}\n\nexport interface AssistEditMoveOp extends AssistEditNodeOpBase {\n op: 'move'\n parentId: string\n /** The component the new parent was validated as. */\n parentComponentId: string\n index: number | null\n}\n\nexport interface AssistEditRemoveOp extends AssistEditNodeOpBase {\n op: 'remove'\n}\n\nexport interface AssistEditRenameOp extends AssistEditNodeOpBase {\n op: 'rename'\n name: string\n}\n\nexport interface AssistEditSetSeoOp {\n op: 'setSeo'\n fields: Partial<Record<ScreenSeoTextField, string>>\n}\n\n/**\n * A property the promoted subtree declares (AGL-2908), in the shape the\n * Properties dialog stores one — without a default.\n *\n * The server never sees a full value: the outline it read the selection from\n * shortens every string. So the default is read off the live canvas at apply\n * time, from the very field the token is about to replace, which is what\n * makes the instance render what was there a moment before.\n */\nexport type AssistEditComponentProp = Omit<ReusableComponentProp, 'defaultValue'>\n\n/** Where one property's token goes: an element of the selection, and a field of it. */\nexport interface AssistEditPropBinding {\n nodeId: string\n /** The component the element was validated as, so a changed one is refused. */\n componentId: string\n /** A prop of that element, or `hideIf` for a part a Yes / no hides. */\n field: string\n /** The property whose `{{prop.<name>}}` token the field takes. */\n prop: string\n}\n\n/**\n * Save the selection as a reusable component (AGL-2908), with the properties\n * the model proposed and the tokens bound into the tree.\n *\n * The only op that creates a document. It creates exactly the one the manual\n * Save as reusable component creates, through the same host resources route,\n * where the plan's entitlement and the route's allow-list are enforced — and\n * it changes the open canvas the same way that action does, by swapping the\n * promoted subtree for an instance. Nothing is published and nothing is\n * saved: the swap is an unsaved edit on the version the editor has open.\n */\nexport interface AssistEditSaveAsComponentOp extends AssistEditNodeOpBase {\n op: 'saveAsComponent'\n /** The name the component is created under. */\n name: string\n props: AssistEditComponentProp[]\n bindings: AssistEditPropBinding[]\n}\n\n/**\n * Add one interaction to an element (AGL-3603), in the shape the element\n * stores it — its trigger with no selector, which the element's id derives.\n * It never replaces or removes one the element already carries.\n */\nexport interface AssistEditAddInteractionOp extends AssistEditNodeOpBase {\n op: 'addInteraction'\n interaction: NodeInteraction\n /** Every other element a step acts on, each with the component it was validated as. */\n targets: Array<{ nodeId: string; componentId: string }>\n}\n\nexport type AssistEditOp =\n | AssistEditAddInteractionOp\n | AssistEditInsertOp\n | AssistEditUpdatePropsOp\n | AssistEditUpdateSxOp\n | AssistEditMoveOp\n | AssistEditRemoveOp\n | AssistEditRenameOp\n | AssistEditSetSeoOp\n | AssistEditSaveAsComponentOp\n\n/** Where a proposal applies, as the server read it off the request. */\nexport interface AssistEditTarget extends AssistEditDocument {\n hostId: string\n}\n\n/** The counts the card shows before the author decides. */\nexport interface AssistEditDiff {\n /** Elements added, every element of every inserted subtree counted. */\n added: number\n /** Elements removed — each with whatever it contains. */\n removed: number\n propsChanged: number\n stylesChanged: number\n moved: number\n renamed: number\n /** Search fields filled in. */\n seoFields: number\n /** Properties the selection declares once it is saved as a component. */\n componentProps: number\n /** Selections saved as a reusable component — at most one per proposal. */\n componentsSaved: number\n /** Interactions added to elements. */\n interactionsAdded: number\n}\n\n/** The most reasons a proposal carries for the changes validation left out. */\nexport const ASSIST_EDIT_MAX_DROPPED_REASONS = 10\n\nexport interface AssistEditProposal {\n id: typeof ASSIST_EDIT_ACTION_ID\n /** One line, in the model's words, of what the edit does. */\n summary: string\n ops: AssistEditOp[]\n diff: AssistEditDiff\n /** Why each change the model wrote and validation refused was left out. */\n dropped: string[]\n target: AssistEditTarget\n}\n\n/** The counts for a list of ops. */\nexport function summarizeAssistEditOps(ops: readonly AssistEditOp[]): AssistEditDiff {\n const diff: AssistEditDiff = {\n added: 0,\n removed: 0,\n propsChanged: 0,\n stylesChanged: 0,\n moved: 0,\n renamed: 0,\n seoFields: 0,\n componentProps: 0,\n componentsSaved: 0,\n interactionsAdded: 0,\n }\n for (const op of ops) {\n switch (op.op) {\n case 'insertSubtree':\n diff.added += Object.keys(op.nodes).length\n break\n case 'remove':\n diff.removed += 1\n break\n case 'updateProps':\n diff.propsChanged += 1\n break\n case 'updateSx':\n diff.stylesChanged += 1\n break\n case 'move':\n diff.moved += 1\n break\n case 'rename':\n diff.renamed += 1\n break\n case 'setSeo':\n diff.seoFields += Object.keys(op.fields).length\n break\n case 'saveAsComponent':\n diff.componentsSaved += 1\n diff.componentProps += op.props.length\n break\n case 'addInteraction':\n diff.interactionsAdded += 1\n break\n }\n }\n return diff\n}\n\nconst plural = (count: number, one: string, many: string): string =>\n `${count} ${count === 1 ? one : many}`\n\n/** The diff as the lines a person reads, zero counts omitted. */\nexport function describeAssistEditDiff(diff: AssistEditDiff): string[] {\n const lines: string[] = []\n if (diff.added) lines.push(`${plural(diff.added, 'element', 'elements')} added`)\n if (diff.removed) lines.push(`${plural(diff.removed, 'element', 'elements')} removed`)\n if (diff.propsChanged) {\n lines.push(`${plural(diff.propsChanged, 'element’s settings', 'elements’ settings')} changed`)\n }\n if (diff.stylesChanged) {\n lines.push(`${plural(diff.stylesChanged, 'element', 'elements')} restyled`)\n }\n if (diff.moved) lines.push(`${plural(diff.moved, 'element', 'elements')} moved`)\n if (diff.renamed) lines.push(`${plural(diff.renamed, 'layer', 'layers')} renamed`)\n if (diff.seoFields) {\n lines.push(`${plural(diff.seoFields, 'search field', 'search fields')} filled in`)\n }\n if (diff.interactionsAdded) {\n lines.push(`${plural(diff.interactionsAdded, 'interaction', 'interactions')} added`)\n }\n if (diff.componentsSaved) {\n lines.push(\n `saved as a reusable component with ${plural(diff.componentProps, 'property', 'properties')}`,\n )\n }\n return lines\n}\n\n/** The word each op kind is counted under in the activity row. */\nconst OP_COUNT_WORDS: Readonly<Record<AssistEditOpKind, string>> = {\n updateProps: 'set',\n updateSx: 'restyle',\n insertSubtree: 'insert',\n move: 'move',\n remove: 'remove',\n rename: 'rename',\n setSeo: 'seo',\n saveAsComponent: 'component',\n addInteraction: 'interaction',\n}\n\n/** The applied ops counted by kind, as the activity row names them (`{ set: 3, insert: 1 }`). */\nexport function assistEditOpCounts(ops: readonly AssistEditOp[]): Record<string, number> {\n const counts: Record<string, number> = {}\n for (const op of ops) {\n const word = OP_COUNT_WORDS[op.op]\n if (word) counts[word] = (counts[word] ?? 0) + 1\n }\n return counts\n}\n\n/** The words `assistEditOpCounts` counts under, for a door that reads them back. */\nexport const ASSIST_EDIT_OP_COUNT_WORDS: readonly string[] = Object.values(OP_COUNT_WORDS)\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Whether a `done` event's `edit` field is a proposal this client can apply.\n * The server built it, so this is a shape check rather than a validation: it\n * keeps a malformed or foreign payload from reaching the canvas mutators.\n */\nexport function isAssistEditProposal(value: unknown): value is AssistEditProposal {\n if (!isRecord(value) || value['id'] !== ASSIST_EDIT_ACTION_ID) return false\n const target = value['target']\n if (!isRecord(target)) return false\n if (!ASSIST_EDIT_DOCUMENT_KINDS.includes(target['kind'] as AssistEditDocumentKind)) return false\n if (typeof target['documentId'] !== 'string' || !target['documentId']) return false\n const ops = value['ops']\n if (!Array.isArray(ops) || !ops.length) return false\n return ops.every(\n (op) => isRecord(op) && ASSIST_EDIT_OP_KINDS.includes(op['op'] as AssistEditOpKind),\n )\n}\n\n/* ------------------------------------------------------------------ *\n * What the client reports once the author applied a proposal\n * ------------------------------------------------------------------ */\n\n/** The body of `POST /api/assist/edit-applied`. */\nexport interface AssistEditAppliedReport {\n orgId: string\n hostId: string\n /** The exchange whose answer carried the proposal. */\n exchangeId: string\n documentKind: AssistEditDocumentKind\n documentId: string\n /** The version the edits landed on — a new one when the open one was live. */\n versionId: string\n opCounts: Record<string, number>\n}\n"],"names":["ASSIST_EDIT_OP_KINDS","ASSIST_EDIT_ACTION_ID","ASSIST_EDIT_TOOL_NAME","ASSIST_EDIT_DOCUMENT_KINDS","COLLECTION_KINDS","screens","components","layouts","BESIGNER_DOCUMENT_ROUTE","assistEditDocumentOf","route","match","exec","String","kind","documentId","versionId","ASSIST_EDIT_CONTEXT_MAX_NODES","ASSIST_EDIT_CONTEXT_MAX_PROPS","ASSIST_EDIT_SELECTED_TEXT_CHARS","ASSIST_EDIT_OUTLINE_TEXT_CHARS","ASSIST_EDIT_WHOLE_MAX_NODES","ASSIST_EDIT_INTERACTION_EVENTS","ASSIST_EDIT_INTERACTION_STEPS","ASSIST_EDIT_MAX_DROPPED_REASONS","summarizeAssistEditOps","ops","diff","added","removed","propsChanged","stylesChanged","moved","renamed","seoFields","componentProps","componentsSaved","interactionsAdded","op","Object","keys","nodes","length","fields","props","plural","count","one","many","describeAssistEditDiff","lines","push","OP_COUNT_WORDS","updateProps","updateSx","insertSubtree","move","remove","rename","setSeo","saveAsComponent","addInteraction","assistEditOpCounts","counts","word","ASSIST_EDIT_OP_COUNT_WORDS","values","isRecord","value","Array","isArray","isAssistEditProposal","target","includes","every"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAMD;;;;;;;;;;;;;;;;CAgBC,GAED,8CAA8C,GAC9C,OAAO,MAAMA,uBAAuB;IAClC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AAIV,4EAA4E,GAC5E,OAAO,MAAMC,wBAAwB,cAAa;AAElD,6EAA6E,GAC7E,OAAO,MAAMC,wBAAwB,sBAAqB;AAK1D,OAAO,MAAMC,6BAAgE;IAC3E;IACA;IACA;CACD,CAAA;AAED,MAAMC,mBAAqE;IACzEC,SAAS;IACTC,YAAY;IACZC,SAAS;AACX;AAEA,MAAMC,0BACJ;AASF;;;;CAIC,GACD,OAAO,SAASC,qBAAqBC,KAAa;IAChD,MAAMC,QAAQH,wBAAwBI,IAAI,CAACC,OAAOH,gBAAAA,QAAS;IAC3D,IAAI,CAACC,OAAO,OAAO;IACnB,OAAO;QACLG,MAAMV,gBAAgB,CAACO,KAAK,CAAC,EAAE,CAAC;QAChCI,YAAYJ,KAAK,CAAC,EAAE;QACpBK,WAAWL,KAAK,CAAC,EAAE;IACrB;AACF;AAEA;;sEAEsE,GAEtE,yFAAyF,GACzF,OAAO,MAAMM,gCAAgC,GAAE;AAC/C,yCAAyC,GACzC,OAAO,MAAMC,gCAAgC,GAAE;AAC/C,6EAA6E,GAC7E,OAAO,MAAMC,kCAAkC,IAAG;AAClD,6DAA6D,GAC7D,OAAO,MAAMC,iCAAiC,GAAE;AAChD;;;;;;CAMC,GACD,OAAO,MAAMC,8BAA8B,IAAG;AAkD9C;;sEAEsE,GAEtE;;;;C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
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * A change to a page the site already has, asked in the Assist chat
19
+ * (AGL-4116). No plan and no new page: the panel starts one `edit` job on
20
+ * that page, which saves the change into the page's draft — on every plan,
21
+ * the draft the Besigner offers with Open draft — and the card links the
22
+ * page in the Besigner, where the person checks it and publishes it. Only
23
+ * when they ask for a new version, and the plan keeps version history, is
24
+ * the change saved as a new unpublished version instead.
25
+ *
26
+ * Asked through a build, a change to the home page came back as a second
27
+ * page at `/` the plan generated from scratch, and every follow-up made
28
+ * another plan. This is the short way, for the request that only changes
29
+ * what is there.
30
+ *
31
+ * Shared by the chat door that resolves it and the panel that starts it.
32
+ * Pure: no request, no React.
33
+ */
34
+ import type { AiJobOutput, AiJobSummary } from './ai-jobs.types';
35
+ /** The strict tool the chat model asks for a change to a page through. */
36
+ export declare const ASSIST_PAGE_CHANGE_TOOL_NAME = "change_page";
37
+ /** The proposal's fixed id, as `assistant_proposal_shown` records it. */
38
+ export declare const ASSIST_PAGE_CHANGE_ACTION_ID = "page-change";
39
+ /** The longest one-line summary the card shows. */
40
+ export declare const ASSIST_PAGE_CHANGE_SUMMARY_MAX_CHARS = 200;
41
+ export interface AssistPageChangeProposal {
42
+ id: typeof ASSIST_PAGE_CHANGE_ACTION_ID;
43
+ /** The site the request was asked on; the job is created for it. */
44
+ hostId: string;
45
+ /** The page to change: one the site has, by its id. */
46
+ pageId: string;
47
+ /** The page's name, as the site's list of pages gives it. */
48
+ pageName: string;
49
+ /** What to change on it, in the person's words. */
50
+ brief: string;
51
+ /** One line saying what will change. */
52
+ summary: string;
53
+ /** They asked for a new version of the page; otherwise the change goes into its draft. */
54
+ newVersion?: boolean;
55
+ }
56
+ /** Shape-checks a page change before it can start a job. */
57
+ export declare function isAssistPageChangeProposal(value: unknown): value is AssistPageChangeProposal;
58
+ /**
59
+ * The body of `POST /api/ai/jobs` a page change starts: an `edit` of the
60
+ * page. `versionId` is the version an earlier change in the same
61
+ * conversation wrote to, so a follow-up changes that version's draft rather
62
+ * than starting again from the published page.
63
+ */
64
+ export declare function assistPageChangeJobRequest(orgId: string, proposal: AssistPageChangeProposal, versionId: string | null): {
65
+ orgId: string;
66
+ hostId: string;
67
+ kind: 'edit';
68
+ brief: string;
69
+ inputs: {
70
+ target: string;
71
+ targetKind: 'screen';
72
+ versionId?: string;
73
+ newVersion?: true;
74
+ };
75
+ };
76
+ /** The version a finished change wrote to the page, or `null` before there is one. */
77
+ export declare function assistPageChangeOutput(job: Pick<AiJobSummary, 'status' | 'outputs'> | null): AiJobOutput | null;
78
+ /**
79
+ * The version a new change to `pageId` continues (AGL-4116): the one the
80
+ * conversation's latest finished change to that page wrote to — its draft
81
+ * holds that change — or `null` to start from the page as it is.
82
+ */
83
+ export declare function assistPageChangeDraftVersion(changes: ReadonlyArray<{
84
+ pageChange?: AssistPageChangeProposal | null;
85
+ pageChangeJob?: AiJobSummary | null;
86
+ }>, pageId: string): string | null;