@aglyn/plugins-ai 1.0.0-beta.232 → 1.0.0-beta.234
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +17 -17
- package/src/lib/components/ai-job-links.d.ts +6 -0
- package/src/lib/components/ai-job-links.js +9 -0
- package/src/lib/components/ai-job-links.js.map +1 -1
- package/src/lib/components/ai-site-build-page.component.js +41 -3
- package/src/lib/components/ai-site-build-page.component.js.map +1 -1
- package/src/lib/components/ai-site-start-card.component.js +91 -8
- package/src/lib/components/ai-site-start-card.component.js.map +1 -1
- package/src/lib/declarations.server.js +7 -4
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/jobs/ai-build-capabilities.js +8 -2
- package/src/lib/jobs/ai-build-capabilities.js.map +1 -1
- package/src/lib/jobs/ai-job-admission.d.ts +2 -1
- package/src/lib/jobs/ai-job-admission.js.map +1 -1
- package/src/lib/jobs/ai-job-email-step.d.ts +39 -0
- package/src/lib/jobs/ai-job-email-step.js +116 -5
- package/src/lib/jobs/ai-job-email-step.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-language.d.ts +3 -0
- package/src/lib/jobs/ai-job-layout-language.js +3 -1
- package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-site-pages.d.ts +2 -0
- package/src/lib/jobs/ai-job-layout-site-pages.js +23 -11
- package/src/lib/jobs/ai-job-layout-site-pages.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-step.js +3 -2
- package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
- package/src/lib/jobs/ai-job-page-language.d.ts +16 -0
- package/src/lib/jobs/ai-job-page-language.js +35 -6
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-step.d.ts +3 -0
- package/src/lib/jobs/ai-job-page-step.js +18 -4
- package/src/lib/jobs/ai-job-page-step.js.map +1 -1
- package/src/lib/jobs/ai-job-plan-step.d.ts +40 -1
- package/src/lib/jobs/ai-job-plan-step.js +121 -16
- package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-content.d.ts +6 -6
- package/src/lib/jobs/ai-job-site-content.js +6 -12
- package/src/lib/jobs/ai-job-site-content.js.map +1 -1
- package/src/lib/jobs/ai-job-site-step.d.ts +11 -0
- package/src/lib/jobs/ai-job-site-step.js +96 -44
- package/src/lib/jobs/ai-job-site-step.js.map +1 -1
- package/src/lib/jobs/ai-jobs-notify.d.ts +14 -4
- package/src/lib/jobs/ai-jobs-notify.js +70 -4
- package/src/lib/jobs/ai-jobs-notify.js.map +1 -1
- package/src/lib/jobs/ai-jobs.d.ts +22 -4
- package/src/lib/jobs/ai-jobs.js +47 -12
- package/src/lib/jobs/ai-jobs.js.map +1 -1
- package/src/lib/jobs/ai-layout-stock-photos.d.ts +98 -0
- package/src/lib/jobs/ai-layout-stock-photos.js +248 -0
- package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -0
- package/src/lib/jobs/ai-site-publish.d.ts +11 -0
- package/src/lib/jobs/ai-site-publish.js +31 -1
- package/src/lib/jobs/ai-site-publish.js.map +1 -1
- package/src/lib/jobs/fixtures/ai-juniper-portfolio-page-recording.d.ts +151 -0
- package/src/lib/jobs/fixtures/ai-juniper-portfolio-page-recording.js +183 -0
- package/src/lib/jobs/fixtures/ai-juniper-portfolio-page-recording.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-slow-roads-site-plan-recording.d.ts +27 -0
- package/src/lib/jobs/fixtures/ai-slow-roads-site-plan-recording.js +192 -0
- package/src/lib/jobs/fixtures/ai-slow-roads-site-plan-recording.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-yoga-site-plan-recording.d.ts +27 -0
- package/src/lib/jobs/fixtures/ai-yoga-site-plan-recording.js +222 -0
- package/src/lib/jobs/fixtures/ai-yoga-site-plan-recording.js.map +1 -0
- package/src/lib/layout-language/ai-layout-compiler.d.ts +29 -0
- package/src/lib/layout-language/ai-layout-compiler.js +698 -12
- package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
- package/src/lib/layout-language/ai-layout-design.d.ts +107 -0
- package/src/lib/layout-language/ai-layout-design.js +197 -0
- package/src/lib/layout-language/ai-layout-design.js.map +1 -0
- package/src/lib/layout-language/ai-layout-frame.d.ts +6 -0
- package/src/lib/layout-language/ai-layout-frame.js +22 -6
- package/src/lib/layout-language/ai-layout-frame.js.map +1 -1
- package/src/lib/layout-language/ai-layout-language.d.ts +2 -0
- package/src/lib/layout-language/ai-layout-language.js +15 -1
- package/src/lib/layout-language/ai-layout-language.js.map +1 -1
- package/src/lib/layout-language/ai-layout-links.d.ts +11 -0
- package/src/lib/layout-language/ai-layout-links.js +4 -0
- package/src/lib/layout-language/ai-layout-links.js.map +1 -1
- package/src/lib/layout-language/ai-layout-pictures.d.ts +11 -5
- package/src/lib/layout-language/ai-layout-pictures.js +80 -17
- package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
- package/src/lib/model/ai-job-notice.d.ts +9 -1
- package/src/lib/model/ai-job-notice.js +23 -0
- package/src/lib/model/ai-job-notice.js.map +1 -1
- package/src/lib/model/ai-plan-capabilities.d.ts +23 -0
- package/src/lib/model/ai-plan-capabilities.js +5 -0
- package/src/lib/model/ai-plan-capabilities.js.map +1 -1
- package/src/lib/model/ai-site-build-progress.d.ts +12 -2
- package/src/lib/model/ai-site-build-progress.js +78 -4
- package/src/lib/model/ai-site-build-progress.js.map +1 -1
- package/src/lib/model/ai-site-job.d.ts +209 -22
- package/src/lib/model/ai-site-job.js +247 -20
- package/src/lib/model/ai-site-job.js.map +1 -1
- package/src/lib/model/ai-site-kinds.js +6 -1
- package/src/lib/model/ai-site-kinds.js.map +1 -1
- package/src/lib/model/ai-site-look.d.ts +21 -0
- package/src/lib/model/ai-site-look.js +63 -14
- package/src/lib/model/ai-site-look.js.map +1 -1
- package/src/lib/operator-alerts.d.ts +18 -0
- package/src/lib/operator-alerts.js +42 -0
- package/src/lib/operator-alerts.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.d.ts +39 -1
- package/src/lib/runtime/ai-doctrine-validators.js +236 -6
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-doctrine.js +5 -3
- package/src/lib/runtime/ai-doctrine.js.map +1 -1
- package/src/lib/runtime/ai-palette.generated.d.ts +2 -0
- package/src/lib/runtime/ai-palette.generated.js +18 -2
- package/src/lib/runtime/ai-palette.generated.js.map +1 -1
- package/src/lib/server/ai-jobs-resume.js.map +1 -1
- package/src/lib/server/ai-jobs-route.js +15 -3
- package/src/lib/server/ai-jobs-route.js.map +1 -1
- package/src/lib/server/assist-edit.js +5 -2
- package/src/lib/server/assist-edit.js.map +1 -1
- package/src/lib/usage/free-ai-credits-left.d.ts +54 -0
- package/src/lib/usage/free-ai-credits-left.js +62 -0
- package/src/lib/usage/free-ai-credits-left.js.map +1 -0
|
@@ -19,6 +19,7 @@ import { type AiBuildPlan } from '../model/ai-build-plan';
|
|
|
19
19
|
import type { AiJob, AiJobKind, AiJobPlan, AiJobStatus } from '../model/ai-jobs.types';
|
|
20
20
|
import { type AiPlanCapabilities, type AiPlanJobScope } from '../model/ai-plan-capabilities';
|
|
21
21
|
import type { AiSiteInventory } from '../model/ai-site-inventory';
|
|
22
|
+
import { type AiDoctrineViolation } from '../runtime/ai-doctrine-validators';
|
|
22
23
|
import type { AiTool } from '../providers/contract';
|
|
23
24
|
import type { AiSystemBlock } from '../runtime/ai-runtime';
|
|
24
25
|
import { readSiteInventory } from '../runtime/site-inventory';
|
|
@@ -106,6 +107,39 @@ export declare function aiPlanBuildLines(job: Pick<AiJob, 'kind'>, capabilities:
|
|
|
106
107
|
* job's turn, whose length the Free page's wall is proven at.
|
|
107
108
|
*/
|
|
108
109
|
export declare function aiPlanSiteLines(job: Pick<AiJob, 'kind'> & Partial<Pick<AiJob, 'inputs'>>, inventory: AiSiteInventory | null, capabilities: AiPlanCapabilities | null): string[];
|
|
110
|
+
/**
|
|
111
|
+
* What a site start's home page is held to (AGL-3660): its fewest sections,
|
|
112
|
+
* and on the Free taste the sections the wall fits across the pages, which
|
|
113
|
+
* the home's count is shared out of. The plan's turn and its re-ask read this
|
|
114
|
+
* one figure, so the sentence the model is told is the check it is held to.
|
|
115
|
+
*/
|
|
116
|
+
export declare function aiSitePlanHomeRule(inventory: AiSiteInventory | null, capabilities: AiPlanCapabilities | null): {
|
|
117
|
+
min: number;
|
|
118
|
+
across: number | null;
|
|
119
|
+
};
|
|
120
|
+
/**
|
|
121
|
+
* A site plan's thin home, asked about on the FIRST answer only (AGL-3660).
|
|
122
|
+
* The re-ask names the count; an answer that still plans a thinner home is
|
|
123
|
+
* kept, since a home with four sections is a site and a stopped start is
|
|
124
|
+
* none — the same trade a language page makes with its last answer's gaps.
|
|
125
|
+
*/
|
|
126
|
+
export declare function aiSiteThinHomeCheck(rule: {
|
|
127
|
+
min: number;
|
|
128
|
+
across: number | null;
|
|
129
|
+
}): (plan: AiBuildPlan) => AiDoctrineViolation[];
|
|
130
|
+
/**
|
|
131
|
+
* A site plan's section that shows the work without its pieces (AGL-3660),
|
|
132
|
+
* asked about on the FIRST answer only, like a thin home: the re-ask names
|
|
133
|
+
* the section, and an answer that keeps it thin is kept.
|
|
134
|
+
*/
|
|
135
|
+
export declare function aiSiteEmptyGalleryCheck(): (plan: AiBuildPlan) => AiDoctrineViolation[];
|
|
136
|
+
/**
|
|
137
|
+
* A site plan's page standing in for the blog its start writes (AGL-3660),
|
|
138
|
+
* asked about on the FIRST answer only, like a thin home: the re-ask names
|
|
139
|
+
* the page, and an answer that keeps it is kept — the posts then take the
|
|
140
|
+
* next address the page leaves free, and the header links them all the same.
|
|
141
|
+
*/
|
|
142
|
+
export declare function aiSiteBlogStandInCheck(): (plan: AiBuildPlan) => AiDoctrineViolation[];
|
|
109
143
|
/**
|
|
110
144
|
* What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143
|
|
111
145
|
* §11): the subject's binding tokens, listed so the planner promises only
|
|
@@ -268,7 +302,12 @@ export declare function createAiJobPlanStep(deps?: AiJobPlanStepDeps): AiJobStep
|
|
|
268
302
|
* A site job's capabilities (AGL-3594, AGL-3660): it changes no theme in its
|
|
269
303
|
* plan — every scaffold designs its look first, in a unit of its own — and on
|
|
270
304
|
* the Free taste its plan holds at most the pages the member asked for within
|
|
271
|
-
* the Free band, which the Free wall then holds it to.
|
|
305
|
+
* the Free band, which the Free wall then holds it to.
|
|
306
|
+
*
|
|
307
|
+
* A build's pages are written in the layout language (`aiBuildUnitJob`), whose
|
|
308
|
+
* compiler draws a section's repeated items itself, so its plan is not asked
|
|
309
|
+
* for a component for them (`repeatsCompiled`, AGL-3616). It still may plan
|
|
310
|
+
* one, and a section two pages share is still one. Every other job's
|
|
272
311
|
* capabilities pass through.
|
|
273
312
|
*/
|
|
274
313
|
export declare function aiSitePlanCapabilities(job: Pick<AiJob, 'kind' | 'inputs'>, capabilities: AiPlanCapabilities | null): AiPlanCapabilities | null;
|
|
@@ -20,8 +20,10 @@ import { AI_BUILD_PLAN_TOOL, aiBuildPlanToolFor, isAiPlanNewRef } from "../model
|
|
|
20
20
|
import { AI_TEMPLATE_SUBJECT_DEFINITIONS, aiTemplateShownTokens } from "../model/ai-template-subjects.js";
|
|
21
21
|
import { AI_JOB_CREATE_KINDS, AI_JOB_CREATE_NOUNS } from "../model/ai-job-creations.js";
|
|
22
22
|
import { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from "../model/ai-page-job.js";
|
|
23
|
-
import { AI_PLAN_NO_FORM_SENTENCE, aiPlanCanPlaceForm, aiPlanCapabilitiesForJob, aiPlanCapabilityLines } from "../model/ai-plan-capabilities.js";
|
|
24
|
-
import { AI_FREE_SITE_WORST_CASE_CREDITS, AI_SITE_CREATE_KINDS, AI_SITE_FREE_PAGES, AI_SITE_PLAN_MAX_TOKENS, aiFreeSiteSectionsWithin, aiSiteNameSentence, aiSitePlanShapeRefusal } from "../model/ai-site-job.js";
|
|
23
|
+
import { AI_PLAN_COMPILED_REPEATS_SENTENCE, AI_PLAN_NO_FORM_SENTENCE, aiPlanCanPlaceForm, aiPlanCapabilitiesForJob, aiPlanCapabilityLines } from "../model/ai-plan-capabilities.js";
|
|
24
|
+
import { AI_FREE_SITE_WORST_CASE_CREDITS, AI_SITE_CREATE_KINDS, AI_SITE_FREE_PAGES, AI_SITE_PLAN_MAX_TOKENS, AI_SITE_HOME_BANDS, aiFreeSiteSectionsWithin, aiSiteFullPlanSentence, aiSiteHomeMinSections, aiSiteNameSentence, aiSitePlanIsHome, aiSitePlanShapeRefusal, aiSiteBlogStandInViolations, aiSiteThinHomeViolations, AI_SITE_GALLERY_SENTENCE, aiSiteEmptyGalleryViolations } from "../model/ai-site-job.js";
|
|
25
|
+
import { aiSiteContentPart } from "./ai-job-site-content.js";
|
|
26
|
+
import { AI_GENERATION_MAX_ATTEMPTS } from "../runtime/ai-generation-bounds.js";
|
|
25
27
|
import { aiPlanFailureCopy, aiPlanRetryRefusal } from "../model/ai-job-failure-copy.js";
|
|
26
28
|
import { FREE_AI_TASTE_CREDITS_PER_MONTH } from "../plan-entitlements.js";
|
|
27
29
|
import { aiDoctrineSystemBlocks, runValidatedGeneration } from "../runtime/ai-doctrine.js";
|
|
@@ -138,6 +140,11 @@ import { AI_JOBS_COLLECTION, registerAiJobPlanStep } from "./ai-jobs.js";
|
|
|
138
140
|
return [
|
|
139
141
|
`This is a build from one request: plan each page it asks for in screens (at most ${pages}), each new layout, form, component or email design in create, and anything else in items. Plan only what the request asks for; reuse what the site has.`,
|
|
140
142
|
'A page section that shows a form or an item places it: put its new:<name> in that section\'s uses. An item built after another lists it in dependsOn.',
|
|
143
|
+
// The layout language draws a section's repeated items (AGL-3660), so the
|
|
144
|
+
// doctrine's "repeated items place a component" is not asked of a build.
|
|
145
|
+
...(capabilities == null ? void 0 : capabilities.repeatsCompiled) ? [
|
|
146
|
+
AI_PLAN_COMPILED_REPEATS_SENTENCE
|
|
147
|
+
] : [],
|
|
141
148
|
...ops ? aiBuildOpLines(ops, AI_BUILD_STRUCTURAL_OPS) : []
|
|
142
149
|
];
|
|
143
150
|
}
|
|
@@ -152,13 +159,13 @@ import { AI_JOBS_COLLECTION, registerAiJobPlanStep } from "./ai-jobs.js";
|
|
|
152
159
|
* home there and was refused for the clash on every new site. Kept off a page
|
|
153
160
|
* job's turn, whose length the Free page's wall is proven at.
|
|
154
161
|
*/ export function aiPlanSiteLines(job, inventory, capabilities) {
|
|
155
|
-
var _ref;
|
|
156
|
-
var
|
|
162
|
+
var _ref, _job_inputs;
|
|
163
|
+
var _job_inputs1;
|
|
157
164
|
if (job.kind !== 'site') return [];
|
|
158
165
|
const lines = [];
|
|
159
166
|
// The business's own name, as the name to use (AGL-3596): the plan's search
|
|
160
167
|
// titles carry it, and an input line alone left the model free to coin one.
|
|
161
|
-
const name = (
|
|
168
|
+
const name = (_job_inputs1 = job.inputs) == null ? void 0 : _job_inputs1['businessName'];
|
|
162
169
|
if (typeof name === 'string' && name.trim()) lines.push(aiSiteNameSentence(name.trim()));
|
|
163
170
|
const pages = ((_ref = inventory == null ? void 0 : inventory.screens) != null ? _ref : []).filter((screen)=>!screen.template);
|
|
164
171
|
const starter = pages.find((screen)=>screen.replaceable);
|
|
@@ -172,20 +179,104 @@ import { AI_JOBS_COLLECTION, registerAiJobPlanStep } from "./ai-jobs.js";
|
|
|
172
179
|
}
|
|
173
180
|
}
|
|
174
181
|
const cap = capabilities == null ? void 0 : capabilities.freeSitePages;
|
|
182
|
+
const home = aiSitePlanHomeRule(inventory, capabilities);
|
|
175
183
|
if (cap !== undefined) {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
184
|
+
lines.push(`This is a Free workspace: plan at most ${cap} ${cap === 1 ? 'page' : 'pages'} — the home page at / and the one page the brief most needs, such as services, booking or contact — and ${home.across} sections across them.${aiPlanCanPlaceForm(inventory, capabilities) ? ' Put the contact form on one of them.' : ''}`);
|
|
185
|
+
}
|
|
186
|
+
// A new site is a full website (AGL-3660): its home is planned as one, not
|
|
187
|
+
// left to a ceiling the outline is free to stay far under.
|
|
188
|
+
const plansHome = !pages.some((page)=>!page.replaceable && aiSitePlanIsHome(page));
|
|
189
|
+
if (home.min > 0 && plansHome) {
|
|
190
|
+
lines.push(`The home page at / reads as a full website: at least ${home.min} sections — ${AI_SITE_HOME_BANDS}.`);
|
|
182
191
|
}
|
|
192
|
+
// The sections are a budget to use (AGL-3660): a prod start of 2026-10-08
|
|
193
|
+
// read "at most 8" as leave to plan a home of two.
|
|
194
|
+
lines.push(aiSiteFullPlanSentence({
|
|
195
|
+
pages: cap != null ? cap : 1,
|
|
196
|
+
across: home.across,
|
|
197
|
+
min: plansHome ? home.min : 0
|
|
198
|
+
}));
|
|
199
|
+
// A paid blog's first posts are written at /blog and linked from the
|
|
200
|
+
// header (AGL-3660, AGL-3676), so the plan plans no page standing in for it.
|
|
201
|
+
if (aiSiteContentPart((_job_inputs = job.inputs) != null ? _job_inputs : null, (capabilities == null ? void 0 : capabilities.freeTaste) === true) === 'posts') {
|
|
202
|
+
lines.push("This site's blog is written for it with its first posts at /blog, and the header links it. Plan no page that stands in for it (no Blog, Articles, Journal, Posts or Stories page); feature the posts in a section of the home page instead.");
|
|
203
|
+
}
|
|
204
|
+
// A section that shows the work counts its pieces (AGL-3660): a planned
|
|
205
|
+
// gallery of no items let a page about the work show none.
|
|
206
|
+
lines.push(AI_SITE_GALLERY_SENTENCE);
|
|
183
207
|
// The kind of site the person picked (AGL-3660): the pages it usually has.
|
|
184
208
|
const kind = aiSiteKindOfInputs(job.inputs);
|
|
185
209
|
if (kind) lines.push(`This is a ${kind.label.toLowerCase()} site. ${kind.pages}`);
|
|
186
210
|
lines.push("Keep the plan an outline: each page's title, address, a short search title and description, and its sections named in a few words. The build writes the copy.");
|
|
187
211
|
return lines;
|
|
188
212
|
}
|
|
213
|
+
/**
|
|
214
|
+
* What a site start's home page is held to (AGL-3660): its fewest sections,
|
|
215
|
+
* and on the Free taste the sections the wall fits across the pages, which
|
|
216
|
+
* the home's count is shared out of. The plan's turn and its re-ask read this
|
|
217
|
+
* one figure, so the sentence the model is told is the check it is held to.
|
|
218
|
+
*/ export function aiSitePlanHomeRule(inventory, capabilities) {
|
|
219
|
+
var _ref;
|
|
220
|
+
const cap = capabilities == null ? void 0 : capabilities.freeSitePages;
|
|
221
|
+
if (cap === undefined) return {
|
|
222
|
+
min: aiSiteHomeMinSections({
|
|
223
|
+
pages: 1,
|
|
224
|
+
across: null
|
|
225
|
+
}),
|
|
226
|
+
across: null
|
|
227
|
+
};
|
|
228
|
+
// Dear: a guided start that places a form makes one (AGL-3596).
|
|
229
|
+
const across = aiFreeSiteSectionsWithin({
|
|
230
|
+
layouts: ((_ref = inventory == null ? void 0 : inventory.layouts.length) != null ? _ref : 0) ? 0 : 1,
|
|
231
|
+
pages: cap,
|
|
232
|
+
forms: 1
|
|
233
|
+
}, FREE_AI_TASTE_CREDITS_PER_MONTH);
|
|
234
|
+
return {
|
|
235
|
+
min: aiSiteHomeMinSections({
|
|
236
|
+
pages: cap,
|
|
237
|
+
across
|
|
238
|
+
}),
|
|
239
|
+
across
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* A site plan's thin home, asked about on the FIRST answer only (AGL-3660).
|
|
244
|
+
* The re-ask names the count; an answer that still plans a thinner home is
|
|
245
|
+
* kept, since a home with four sections is a site and a stopped start is
|
|
246
|
+
* none — the same trade a language page makes with its last answer's gaps.
|
|
247
|
+
*/ export function aiSiteThinHomeCheck(rule) {
|
|
248
|
+
let answers = 0;
|
|
249
|
+
return (plan)=>{
|
|
250
|
+
answers += 1;
|
|
251
|
+
if (answers >= AI_GENERATION_MAX_ATTEMPTS) return [];
|
|
252
|
+
return aiSiteThinHomeViolations(plan, rule);
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* A site plan's section that shows the work without its pieces (AGL-3660),
|
|
257
|
+
* asked about on the FIRST answer only, like a thin home: the re-ask names
|
|
258
|
+
* the section, and an answer that keeps it thin is kept.
|
|
259
|
+
*/ export function aiSiteEmptyGalleryCheck() {
|
|
260
|
+
let answers = 0;
|
|
261
|
+
return (plan)=>{
|
|
262
|
+
answers += 1;
|
|
263
|
+
if (answers >= AI_GENERATION_MAX_ATTEMPTS) return [];
|
|
264
|
+
return aiSiteEmptyGalleryViolations(plan);
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* A site plan's page standing in for the blog its start writes (AGL-3660),
|
|
269
|
+
* asked about on the FIRST answer only, like a thin home: the re-ask names
|
|
270
|
+
* the page, and an answer that keeps it is kept — the posts then take the
|
|
271
|
+
* next address the page leaves free, and the header links them all the same.
|
|
272
|
+
*/ export function aiSiteBlogStandInCheck() {
|
|
273
|
+
let answers = 0;
|
|
274
|
+
return (plan)=>{
|
|
275
|
+
answers += 1;
|
|
276
|
+
if (answers >= AI_GENERATION_MAX_ATTEMPTS) return [];
|
|
277
|
+
return aiSiteBlogStandInViolations(plan);
|
|
278
|
+
};
|
|
279
|
+
}
|
|
189
280
|
/**
|
|
190
281
|
* What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143
|
|
191
282
|
* §11): the subject's binding tokens, listed so the planner promises only
|
|
@@ -252,7 +343,10 @@ import { AI_JOBS_COLLECTION, registerAiJobPlanStep } from "./ai-jobs.js";
|
|
|
252
343
|
* violations the plan's one re-ask names: the players the plan lists against
|
|
253
344
|
* the brief it answers (AGL-3433), which only this step reads beside the plan,
|
|
254
345
|
* and a kind's shape refusal.
|
|
255
|
-
*/ function planViolations(scope, brief, freeTaste = false, ops = null) {
|
|
346
|
+
*/ function planViolations(scope, brief, freeTaste = false, ops = null, home = null, blog = false, site = false) {
|
|
347
|
+
const thinHome = home && home.min > 0 ? aiSiteThinHomeCheck(home) : null;
|
|
348
|
+
const blogStandIn = blog ? aiSiteBlogStandInCheck() : null;
|
|
349
|
+
const emptyGallery = site ? aiSiteEmptyGalleryCheck() : null;
|
|
256
350
|
return (plan)=>{
|
|
257
351
|
var _ref;
|
|
258
352
|
// A build's plan is held to the operations this site has (AGL-3616):
|
|
@@ -272,7 +366,10 @@ import { AI_JOBS_COLLECTION, registerAiJobPlanStep } from "./ai-jobs.js";
|
|
|
272
366
|
code: 'plan-job-shape',
|
|
273
367
|
message
|
|
274
368
|
}
|
|
275
|
-
] : []
|
|
369
|
+
] : [],
|
|
370
|
+
...thinHome ? thinHome(plan) : [],
|
|
371
|
+
...blogStandIn ? blogStandIn(plan) : [],
|
|
372
|
+
...emptyGallery ? emptyGallery(plan) : []
|
|
276
373
|
];
|
|
277
374
|
};
|
|
278
375
|
}
|
|
@@ -463,7 +560,7 @@ export function createAiJobPlanStep(deps = {}) {
|
|
|
463
560
|
const readOps = (_deps_readOps = deps.readOps) != null ? _deps_readOps : readAiBuildOps;
|
|
464
561
|
const readContext = deps.readSiteContext === undefined ? readAiJobSiteContext : deps.readSiteContext;
|
|
465
562
|
return async ({ job, now, signal, firestore, modelFor, org: orgDocument })=>{
|
|
466
|
-
var _AI_JOB_PLAN_SCOPES_job_kind, _ref;
|
|
563
|
+
var _AI_JOB_PLAN_SCOPES_job_kind, _job_inputs, _ref;
|
|
467
564
|
const org = orgDocument != null ? orgDocument : null;
|
|
468
565
|
const [inventory, workspace, siteContext] = await Promise.all([
|
|
469
566
|
job.hostId ? readInventory(job.orgId, job.hostId, {
|
|
@@ -610,7 +707,7 @@ export function createAiJobPlanStep(deps = {}) {
|
|
|
610
707
|
signal
|
|
611
708
|
} : {}, {
|
|
612
709
|
capabilities,
|
|
613
|
-
extend: planViolations(scope, job.brief, freeTaste, ops)
|
|
710
|
+
extend: planViolations(scope, job.brief, freeTaste, ops, site ? aiSitePlanHomeRule(inventory, capabilities) : null, site && aiSiteContentPart((_job_inputs = job.inputs) != null ? _job_inputs : null, freeTaste) === 'posts', site)
|
|
614
711
|
}));
|
|
615
712
|
const spent = _extends({
|
|
616
713
|
outputs: [],
|
|
@@ -677,10 +774,18 @@ export function createAiJobPlanStep(deps = {}) {
|
|
|
677
774
|
* A site job's capabilities (AGL-3594, AGL-3660): it changes no theme in its
|
|
678
775
|
* plan — every scaffold designs its look first, in a unit of its own — and on
|
|
679
776
|
* the Free taste its plan holds at most the pages the member asked for within
|
|
680
|
-
* the Free band, which the Free wall then holds it to.
|
|
777
|
+
* the Free band, which the Free wall then holds it to.
|
|
778
|
+
*
|
|
779
|
+
* A build's pages are written in the layout language (`aiBuildUnitJob`), whose
|
|
780
|
+
* compiler draws a section's repeated items itself, so its plan is not asked
|
|
781
|
+
* for a component for them (`repeatsCompiled`, AGL-3616). It still may plan
|
|
782
|
+
* one, and a section two pages share is still one. Every other job's
|
|
681
783
|
* capabilities pass through.
|
|
682
784
|
*/ export function aiSitePlanCapabilities(job, capabilities) {
|
|
683
785
|
var _job_inputs;
|
|
786
|
+
if (job.kind === 'build' && capabilities) return _extends({}, capabilities, {
|
|
787
|
+
repeatsCompiled: true
|
|
788
|
+
});
|
|
684
789
|
if (job.kind !== 'site' || !capabilities) return capabilities;
|
|
685
790
|
const create = _extends({}, capabilities.create, {
|
|
686
791
|
'theme-change': {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-plan-step.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { createHash } from 'node:crypto'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport {\n AI_BUILD_PLAN_TOOL,\n aiBuildPlanToolFor,\n isAiPlanNewRef,\n type AiBuildPlan,\n} from '../model/ai-build-plan'\nimport type { AiJob, AiJobKind, AiJobPlan, AiJobStatus } from '../model/ai-jobs.types'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n aiTemplateShownTokens,\n type AiTemplateSubject,\n} from '../model/ai-template-subjects'\nimport { AI_JOB_CREATE_KINDS, AI_JOB_CREATE_NOUNS } from '../model/ai-job-creations'\nimport { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from '../model/ai-page-job'\nimport {\n AI_PLAN_NO_FORM_SENTENCE,\n aiPlanCanPlaceForm,\n aiPlanCapabilitiesForJob,\n aiPlanCapabilityLines,\n type AiPlanCapabilities,\n type AiPlanJobScope,\n} from '../model/ai-plan-capabilities'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport {\n AI_FREE_SITE_WORST_CASE_CREDITS,\n AI_SITE_CREATE_KINDS,\n AI_SITE_FREE_PAGES,\n AI_SITE_PLAN_MAX_TOKENS,\n aiFreeSiteSectionsWithin,\n aiSiteNameSentence,\n aiSitePlanShapeRefusal,\n} from '../model/ai-site-job'\nimport { aiPlanFailureCopy, aiPlanRetryRefusal } from '../model/ai-job-failure-copy'\nimport { FREE_AI_TASTE_CREDITS_PER_MONTH } from '../plan-entitlements'\nimport { aiDoctrineSystemBlocks, runValidatedGeneration } from '../runtime/ai-doctrine'\nimport { AI_STEP_TIERS, aiCatalogEntry, aiDefaultModelFor } from '../providers/catalog'\nimport {\n AI_FREE_PAGE_WORST_CASE_CREDITS,\n aiPlanEmbedBriefViolations,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { assistCreditsFromUsd } from '../usage/assist-credits'\nimport { ASSIST_RETURNED_USD_FIELD, assistSpendAfterReturnsUsd } from '../usage/assist-credit-returns'\nimport { freeAccountUsageRef, freeAssistAccount, type AssistMeteredOrg } from '../usage/assist-free-taste'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport type { AiTool } from '../providers/contract'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { readAiSiteContext } from '../runtime/site-context'\nimport { aiInstructionsWithSiteContext, type AiSiteContextInput } from '../model/ai-site-context'\nimport {\n AI_BUILD_CREATE_KINDS,\n AI_BUILD_STRUCTURAL_OPS,\n aiBuildPageLimit,\n aiBuildPlanShapeRefusal,\n type AiBuildOps,\n} from '../model/ai-build-job'\nimport { aiBuildOpLines, aiBuildOps } from './ai-build-capabilities'\nimport { aiJobAdmissionRefusal } from './ai-job-admission'\nimport { readAiPlanCapabilities } from './ai-job-drafts'\nimport {\n AI_JOB_BRIEF_MAX_CHARS,\n type AiJobStepOutcome,\n type AiJobStepRunner,\n} from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiDoctrineReview, aiUnspentOutcome } from './ai-job-generation'\nimport { aiPlanWithDraftIds } from './ai-job-draft-ids'\nimport { AI_JOBS_COLLECTION, registerAiJobPlanStep } from './ai-jobs'\n\n/**\n * The plan step (AGL-2935): the first step of every job that builds site\n * structure. Before a node is generated, the model answers with a typed plan\n * — what the site already has that the job reuses, what it creates and why,\n * and the screens it builds from them — held to the doctrine's plan rules\n * against the site's inventory and re-asked once when it breaks one.\n *\n * A plan that passes is kept on the job, and the job stops for review: the\n * member reads what it will build before a credit is spent building it, and\n * confirms through the resume door. A plan that still breaks a rule on its\n * re-ask stops the job the same way, with the rules named. Either way the\n * step writes nothing itself; the machine records the plan, the spend and\n * the stop, as it records every step.\n *\n * ── Told what it may create, refused what it cannot build (AGL-3030) ─────\n *\n * Before it asks, the step reads what the job may create on its site: the\n * workspace's plan, the site's counts against its limits, and — for a kind\n * that builds only some plans — what the job builds itself. The user turn\n * states it, the plan rules refuse a creation outside it with the one re-ask,\n * and where the workspace keeps no reusable components they accept the page\n * built inline. A plan the confirm door would still refuse — the kind's own\n * admission, handed the plan, as the resume door hands it — is refused HERE,\n * before a member is shown a Confirm: the job fails with the door's sentence,\n * its plan is not kept, and it holds nothing.\n */\n\n/** The plan step's own instructions, cached after the doctrine. */\nexport const AI_JOB_PLAN_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text:\n 'You plan what a website builder job will build, before anything is built. You are given the kind of job and the brief from the person who owns the site. ' +\n 'Answer with submit_build_plan: what the site inventory already has that the job reuses, what it must create and why nothing listed will do, and each page it builds (the screens list) with its layout, template, slug, search title, search description and sections from top to bottom. ' +\n 'Refer to inventory records by id and to what the plan creates as new:<name>. Plan only what the brief asks for: a component, layout, template, form or email job plans no pages unless the brief asks for them, and a page job plans exactly one page.',\n },\n]\n\n/**\n * The plan step's time (AGL-3026, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at the routing table's ceiling for `job.plan`, on\n * the tier that step kind is served from, with the step's reads and writes,\n * at the rates `ai-job-budget.ts` assumes — fitted to what a beat can give a\n * step, so the served tier asks a little under the routing ceiling.\n */\nexport const AI_JOB_PLAN_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.plan'],\n maxTokens: AI_ROUTING_TABLE['job.plan'].maxTokens,\n})\n\n/**\n * The least time a plan needs before it starts. Registered with the step, so\n * an inline door never starts a plan. A plan thinks before it answers and\n * routinely runs past an inline door's budget, and a provider call that\n * budget cuts off is still generated and billed upstream while the meter\n * records nothing. The beat starts a plan only with this much of its own\n * budget left, and a spec holds it inside that budget.\n */\nexport const AI_JOB_PLAN_STEP_MINIMUM_MS = AI_JOB_PLAN_STEP_BUDGET.minimumMs\n\n/**\n * The plan's answer ceiling on the model a job runs: the most whose worst\n * case fits the least time the step registered, and never more than the\n * routing table's. A model the catalog does not know is planned at the\n * slowest.\n */\nexport function aiJobPlanMaxTokens(model: string): number {\n return AI_JOB_PLAN_STEP_BUDGET.maxTokens(model)\n}\n\n/** What the member reads while a plan waits for them. */\nexport const AI_JOB_PLAN_REVIEW_COPY =\n 'The plan is ready. Review what the job will reuse and create, then confirm it to build.'\n\n/**\n * The job as the plan step's user turn: its kind, its brief, its scalar\n * inputs and, where the job read them, what it may create on its site\n * (AGL-3030). Per workspace and per site, which is why they ride here and\n * never in a system block the platform's cache entry is keyed on.\n */\nexport function aiJobPlanPrompt(\n job: Pick<AiJob, 'kind' | 'brief' | 'inputs'>,\n capabilities: AiPlanCapabilities | null = null,\n inventory: AiSiteInventory | null = null,\n ops: AiBuildOps | null = null,\n): string {\n const lines = [`Job kind: ${job.kind}`, `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`]\n for (const [key, value] of Object.entries(job.inputs ?? {})) {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n lines.push(`${key}: ${String(value)}`)\n }\n }\n if (capabilities) lines.push(...aiPlanCapabilityLines(capabilities))\n // A form is a saved form or none (AGL-3596): said where the site read has\n // none to place and the job may create none.\n if (capabilities && inventory && !aiPlanCanPlaceForm(inventory, capabilities)) {\n lines.push(AI_PLAN_NO_FORM_SENTENCE)\n }\n lines.push(...aiPlanTemplateTokenLines(job))\n lines.push(...aiPlanSiteLines(job, inventory, capabilities))\n lines.push(...aiPlanBuildLines(job, capabilities, ops))\n return lines.join('\\n')\n}\n\n/**\n * What a BUILD job's plan is told (AGL-3616): that one request becomes pages,\n * creations and items, how many pages it may hold, and the item operations\n * this site has with their arguments. On the job's own turn, never a cached\n * system block, because the operations are per site.\n */\nexport function aiPlanBuildLines(\n job: Pick<AiJob, 'kind'>,\n capabilities: AiPlanCapabilities | null,\n ops: AiBuildOps | null,\n): string[] {\n if (job.kind !== 'build') return []\n const pages = aiBuildPageLimit(capabilities?.freeTaste === true)\n return [\n `This is a build from one request: plan each page it asks for in screens (at most ${pages}), each new layout, form, component or email design in create, and anything else in items. Plan only what the request asks for; reuse what the site has.`,\n 'A page section that shows a form or an item places it: put its new:<name> in that section\\'s uses. An item built after another lists it in dependsOn.',\n ...(ops ? aiBuildOpLines(ops, AI_BUILD_STRUCTURAL_OPS) : []),\n ]\n}\n\n/**\n * What a SITE job's plan is told beside the inventory (AGL-3594): the pages\n * the site already has and that their addresses are taken, which one — the\n * untouched starter home — a planned home page at `/` replaces, the Free page\n * cap and its guidance, and that a plan is an outline.\n *\n * A site job only. A new site is born with a published home page at `/`\n * (AGL-3497), and a plan that did not know it could replace it planned its own\n * home there and was refused for the clash on every new site. Kept off a page\n * job's turn, whose length the Free page's wall is proven at.\n */\nexport function aiPlanSiteLines(\n job: Pick<AiJob, 'kind'> & Partial<Pick<AiJob, 'inputs'>>,\n inventory: AiSiteInventory | null,\n capabilities: AiPlanCapabilities | null,\n): string[] {\n if (job.kind !== 'site') return []\n const lines: string[] = []\n // The business's own name, as the name to use (AGL-3596): the plan's search\n // titles carry it, and an input line alone left the model free to coin one.\n const name = job.inputs?.['businessName']\n if (typeof name === 'string' && name.trim()) lines.push(aiSiteNameSentence(name.trim()))\n const pages = (inventory?.screens ?? []).filter((screen) => !screen.template)\n const starter = pages.find((screen) => screen.replaceable)\n if (pages.length) {\n lines.push('Pages the site already has; their addresses are taken unless a line says otherwise:')\n for (const page of pages) {\n lines.push(\n page.replaceable\n ? `- ${page.name} at ${page.slug}: the starter home page the site was created with. Plan this site's home page at / and it replaces this one.`\n : `- ${page.name} at ${page.slug}`,\n )\n }\n if (!starter && pages.some((page) => page.slug.trim() === '/' || page.slug.trim() === '')) {\n lines.push(\"The home page at / is the owner's own and stays: give every page you plan another address.\")\n }\n }\n const cap = capabilities?.freeSitePages\n if (cap !== undefined) {\n const sections = aiFreeSiteSectionsWithin(\n { layouts: (inventory?.layouts.length ?? 0) ? 0 : 1, pages: cap },\n FREE_AI_TASTE_CREDITS_PER_MONTH,\n )\n lines.push(\n `This is a Free workspace: plan at most ${cap} ${cap === 1 ? 'page' : 'pages'} — the home page at / and the one page the brief most needs, such as services, booking or contact — with at most ${sections} sections across them.${aiPlanCanPlaceForm(inventory, capabilities) ? ' Put the contact form on one of them.' : ''}`,\n )\n }\n // The kind of site the person picked (AGL-3660): the pages it usually has.\n const kind = aiSiteKindOfInputs(job.inputs)\n if (kind) lines.push(`This is a ${kind.label.toLowerCase()} site. ${kind.pages}`)\n lines.push(\n \"Keep the plan an outline: each page's title, address, a short search title and description, and its sections named in a few words. The build writes the copy.\",\n )\n return lines\n}\n\n/**\n * What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143\n * §11): the subject's binding tokens, listed so the planner promises only\n * what the page can fill and the build can be held to it\n * (`aiPlanTemplateTokenViolations`).\n *\n * ⛔ It rides the job's own turn and NOT the `fields` description in the plan\n * tool, which every kind's request caches. Written there it read better and\n * cost 40 tokens of the shared prefix — 2,980 to 3,020 — which is one credit\n * of the Free page's 300-credit wall, taking the room it keeps for a re-asked\n * section from 45 credits to 44 and breaking `ai-job-free-page.spec.ts`. A\n * page job must not pay for a sentence about templates.\n *\n * The list is the tokens a reader sees, never the whole catalog (AGL-3143\n * §16). Offered a slug and the publish timestamp, a live plan promised them,\n * and its build kept the promise the only way a slug can be kept: it printed\n * \"entry slug: {{entry.slug}}\" on every article.\n */\nexport function aiPlanTemplateTokenLines(job: Pick<AiJob, 'kind' | 'inputs'>): string[] {\n if (job.kind !== 'template') return []\n const subject = (job.inputs ?? {})['subject']\n const definition =\n typeof subject === 'string'\n ? AI_TEMPLATE_SUBJECT_DEFINITIONS[subject as AiTemplateSubject]\n : undefined\n if (!definition) return []\n return [\n `The template's fields are the binding tokens its page shows a reader, each one of: ${aiTemplateShownTokens(\n definition,\n ).join(', ')}. A link or picture token is shown by the link or picture holding it. Promise only what the page fills.`,\n ]\n}\n\n/** A kind that builds only some plans: the creations it makes, and the shapes it refuses. */\nexport interface AiJobPlanScope extends AiPlanJobScope {\n /** Why a job of the kind cannot build a plan of this shape; `null` when it can. Pure. */\n shapeRefusal: (plan: AiBuildPlan, options?: { freeTaste?: boolean }) => string | null\n}\n\n/**\n * The kinds whose confirm door builds only some plans (AGL-3030). A page job\n * builds one screen and a scaffold four to eight; each builds only the\n * creations its list names. A template, layout, component, form or email job\n * builds its own record and what that record places (AGL-3143 §15,\n * `AI_JOB_CREATE_KINDS`), and holds no plan to a shape.\n */\nexport const AI_JOB_PLAN_SCOPES: Readonly<Partial<Record<AiJobKind, AiJobPlanScope>>> = {\n page: { noun: 'a page job', creates: AI_PAGE_CREATE_KINDS, shapeRefusal: aiPagePlanShapeRefusal },\n // A build from one request (AGL-3616): its operations are judged against\n // the site's registry by the step, which reads it (`aiBuildPlanViolations`).\n build: {\n noun: 'a build',\n creates: AI_BUILD_CREATE_KINDS,\n shapeRefusal: (plan, options) => aiBuildPlanShapeRefusal(plan, { freeTaste: options?.freeTaste }),\n },\n site: { noun: 'a site scaffold', creates: AI_SITE_CREATE_KINDS, shapeRefusal: aiSitePlanShapeRefusal },\n ...Object.fromEntries(\n Object.entries(AI_JOB_CREATE_KINDS).map(([kind, creates]) => [\n kind,\n { noun: AI_JOB_CREATE_NOUNS[kind as AiJobKind] as string, creates, shapeRefusal: () => null },\n ]),\n ),\n}\n\n/**\n * What the plan step holds beyond the doctrine's plan rules, as the\n * violations the plan's one re-ask names: the players the plan lists against\n * the brief it answers (AGL-3433), which only this step reads beside the plan,\n * and a kind's shape refusal.\n */\nfunction planViolations(\n scope: AiJobPlanScope | null,\n brief: string,\n freeTaste = false,\n ops: AiBuildOps | null = null,\n): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n return (plan) => {\n // A build's plan is held to the operations this site has (AGL-3616):\n // an unknown op, arguments its schema refuses, a cycle or a reference\n // nothing makes are re-asked once like every other plan rule.\n const message = ops\n ? aiBuildPlanShapeRefusal(plan, { freeTaste, ops })\n : (scope?.shapeRefusal(plan, { freeTaste }) ?? null)\n return [\n ...aiPlanEmbedBriefViolations(plan, brief),\n ...(message ? [{ rule: null, code: 'plan-job-shape', message }] : []),\n ]\n }\n}\n\n/**\n * The inventory names of every id the plan references, so the proposal reads\n * \"the Services layout\" rather than an id — kept on the plan because the\n * inventory is not read again when the member opens it.\n */\nexport function aiPlanLabels(\n plan: AiBuildPlan,\n inventory: AiSiteInventory | null,\n): Record<string, string> {\n const names = new Map<string, string>()\n for (const rows of [\n inventory?.components,\n inventory?.layouts,\n inventory?.templates,\n inventory?.forms,\n inventory?.datasets,\n inventory?.collections,\n inventory?.screens,\n ]) {\n for (const row of rows ?? []) names.set(row.id, row.name)\n }\n const refs = [\n ...plan.reuse.map((entry) => entry.id),\n ...plan.create.map((entry) => entry.duplicateOf),\n ...plan.screens.flatMap((screen) => [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ]),\n ]\n const labels: Record<string, string> = {}\n for (const ref of refs) {\n if (!ref || isAiPlanNewRef(ref)) continue\n const name = names.get(ref)\n if (name) labels[ref] = name\n }\n return labels\n}\n\n/* ------------------------------------------------------------------------ *\n * Reusing an identical brief's plan\n * ------------------------------------------------------------------------ */\n\n/**\n * How long a plan may be reused for (AGL-2937).\n *\n * The window is what makes reuse safe rather than merely cheap. The key\n * already covers everything the request said — the brief, the inputs, the\n * model and the prompt as rendered, site inventory included — so a plan is\n * reused only when nothing the model was shown has changed. What the key\n * cannot see is the world outside the request: a page published, a component\n * renamed after the inventory was read, a member who meant something\n * different the second time. Fifteen minutes is short enough that the answer\n * is still the one the site would give, and long enough to cover what reuse\n * is actually for — the same brief run twice in a sitting, a job resubmitted\n * after a refused reservation, two members starting the same work.\n */\nexport const AI_PLAN_REUSE_WINDOW_MS = 15 * 60 * 1_000\n\n/** Jobs one lookup reads. More than one can share a key; the newest plan wins. */\nexport const AI_PLAN_REUSE_CANDIDATES = 5\n\n/** A job whose plan might be reused, as the finder reports it. */\nexport interface AiJobPlanCandidate {\n jobId: string\n status: AiJobStatus\n plan: AiJobPlan\n}\n\n/**\n * The digest a plan is reused by: the whole request, never the answer.\n *\n * It hashes what the model was asked and what it was shown — the job's kind\n * and site, the user turn (which carries the trimmed brief and every scalar\n * input), the model that would answer, every rendered system block including\n * the site inventory, and the tool's schema. Two requests that hash the same\n * would have been sent the same bytes to the same model, so the second can\n * keep the first's answer.\n *\n * The version tag is the escape hatch: anything that changes what a key\n * MEANS, rather than what it covers, bumps it and strands every old key\n * harmlessly, since a key nothing matches simply asks the model.\n */\nexport function aiJobPlanKey(input: {\n job: Pick<AiJob, 'kind' | 'hostId'>\n prompt: string\n model: string\n system: readonly AiSystemBlock[]\n /** The plan tool the request offers (AGL-3433); the plain one when absent. */\n tool?: AiTool\n}): string {\n const digest = createHash('sha256')\n for (const part of [\n 'plan.v1',\n input.job.kind,\n input.job.hostId ?? '',\n input.model,\n input.prompt,\n ...input.system.map((block) => block.text),\n JSON.stringify(input.tool ?? AI_BUILD_PLAN_TOOL),\n ]) {\n // Length-prefixed, so two different splits of the same characters cannot\n // collide by running into one another.\n digest.update(`${part.length}:${part}\\u0000`)\n }\n return digest.digest('hex')\n}\n\n/** A job that could not have produced a reusable plan, whatever its key says. */\nconst UNREUSABLE: readonly AiJobStatus[] = ['canceled', 'failed']\n\nfunction planMillis(plan: AiJobPlan): number | null {\n const at = plan.proposedAt as unknown\n if (at instanceof Date) return at.getTime()\n if (at && typeof (at as { toMillis?: unknown }).toMillis === 'function') {\n return (at as { toMillis(): number }).toMillis()\n }\n return null\n}\n\n/**\n * The newest plan worth reusing out of what the finder returned: another\n * job's, still proposed or already confirmed, on a job that was neither\n * canceled nor failed, proposed inside the window.\n *\n * A canceled or failed job is excluded even though its plan may be perfectly\n * good: those are the jobs a member walked away from, and handing their plan\n * to the next one would make a rejected answer look like a fresh one.\n */\nexport function aiReusablePlan(\n candidates: readonly AiJobPlanCandidate[],\n context: { jobId: string; now: Date },\n): AiJobPlanCandidate | null {\n const floor = context.now.getTime() - AI_PLAN_REUSE_WINDOW_MS\n let best: AiJobPlanCandidate | null = null\n let bestAt = -1\n for (const candidate of candidates) {\n if (candidate.jobId === context.jobId) continue\n if (UNREUSABLE.includes(candidate.status)) continue\n if (candidate.plan.status !== 'proposed' && candidate.plan.status !== 'confirmed') continue\n const at = planMillis(candidate.plan)\n if (at === null || at < floor || at > context.now.getTime()) continue\n if (at > bestAt) {\n best = candidate\n bestAt = at\n }\n }\n return best\n}\n\nexport type AiJobPlanFinder = (\n orgId: string,\n key: string,\n firestore?: FirebaseFirestore.Firestore,\n) => Promise<AiJobPlanCandidate[]>\n\n/**\n * The finder the step uses in production: an equality on `plan.key` inside\n * the org's own jobs.\n *\n * One equality on one field, with no ordering beside it, so Firestore's\n * automatic single-field index answers it and no composite index is deployed.\n * The window and the statuses are applied in memory instead, which is what\n * keeps it that way.\n */\nexport const findAiJobsByPlanKey: AiJobPlanFinder = async (orgId, key, firestore) => {\n if (!firestore) return []\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(AI_JOBS_COLLECTION)\n .where('plan.key', '==', key)\n .limit(AI_PLAN_REUSE_CANDIDATES)\n .get()\n return snapshot.docs.flatMap((doc) => {\n const data = doc.data() as { status?: AiJobStatus; plan?: AiJobPlan | null }\n return data.plan\n ? [{ jobId: doc.id, status: data.status ?? 'queued', plan: data.plan }]\n : []\n })\n}\n\n/** What a job may create on its site, read for the plan step; `null` for no site. */\nexport type AiPlanCapabilitiesReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiPlanCapabilities | null>\n\n/** The reader the step uses in production: the draft bands' own arithmetic, for the job's site. */\nexport const readAiJobPlanCapabilities: AiPlanCapabilitiesReader = async ({ job, org, firestore }) =>\n job.hostId ? readAiPlanCapabilities(firestore, { hostId: job.hostId, org }) : null\n\nexport interface AiJobPlanStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The reuse lookup; specs hand in a fake, and `null` turns reuse off. */\n findPlansByKey?: AiJobPlanFinder | null\n /** What the job may create on its site (AGL-3030); specs and the eval recorder hand in their own. */\n readCapabilities?: AiPlanCapabilitiesReader\n /** The kind's admission, asked of a plan before it is kept; the registry's otherwise. */\n admissionRefusal?: typeof aiJobAdmissionRefusal\n /** A build's operations on its site (AGL-3616); the registry and its gates otherwise. */\n readOps?: AiBuildOpsReader\n /**\n * The site's business profile, status and remembered preferences\n * (AGL-3661); specs and the eval recorder hand in their own, and `null`\n * turns it off.\n */\n readSiteContext?: AiSiteContextReader | null\n}\n\n/** What a job's site context is read with (AGL-3661). */\nexport type AiSiteContextReader = (input: {\n job: AiJob\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiSiteContextInput | null>\n\n/** The reader the step uses in production: fail-soft, org-scoped, `null` for a job with no site. */\nexport const readAiJobSiteContext: AiSiteContextReader = ({ job, firestore }) =>\n readAiSiteContext(firestore, { orgId: job.orgId, hostId: job.hostId })\n\n/** What a build may plan on its site (AGL-3616). */\nexport type AiBuildOpsReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n freeTaste: boolean\n}) => Promise<AiBuildOps>\n\n/** The reader the step uses in production: the registry, gated for the job's site. */\nexport const readAiBuildOps: AiBuildOpsReader = async ({ job, org, firestore, freeTaste }) => {\n const host = job.hostId\n ? (((await firestore.collection('hosts').doc(job.hostId).get()).data() ?? null) as Record<string, unknown> | null)\n : null\n return aiBuildOps({ orgId: job.orgId, hostId: job.hostId ?? null, org, host, freeTaste })\n}\n\n/**\n * A build plan's items with what each can cost (AGL-3616), from its\n * capability, recorded as the plan is kept so the console's estimate and the\n * confirm door read one figure without the registry.\n */\nexport function aiPlanWithItemCredits<T extends AiBuildPlan>(ops: AiBuildOps | null, plan: T): T {\n if (!ops || !plan.items?.length) return plan\n return {\n ...plan,\n items: plan.items.map((item) => {\n const capability = ops.get(item.op)\n return capability ? { ...item, credits: Math.max(0, Math.floor(capability.estimateCredits(item.args))) } : item\n }),\n }\n}\n\nexport function createAiJobPlanStep(deps: AiJobPlanStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const findPlansByKey =\n deps.findPlansByKey === undefined ? findAiJobsByPlanKey : deps.findPlansByKey\n const readCapabilities = deps.readCapabilities ?? readAiJobPlanCapabilities\n const admissionRefusal = deps.admissionRefusal ?? aiJobAdmissionRefusal\n const readOps = deps.readOps ?? readAiBuildOps\n const readContext = deps.readSiteContext === undefined ? readAiJobSiteContext : deps.readSiteContext\n return async ({ job, now, signal, firestore, modelFor, org: orgDocument }) => {\n const org = (orgDocument ?? null) as Partial<AglynOrgBilling> | null\n const [inventory, workspace, siteContext] = await Promise.all([\n job.hostId ? readInventory(job.orgId, job.hostId, { firestore }) : Promise.resolve(null),\n readCapabilities({ job, org, firestore }),\n job.hostId && readContext ? readContext({ job, firestore }) : Promise.resolve(null),\n ])\n // The site's profile, status and memory (AGL-3661), as a per-site cached\n // block after the plan rules. The inventory block already lists what the\n // site holds, so the context carries no index of its own here.\n const instructions = aiInstructionsWithSiteContext(AI_JOB_PLAN_INSTRUCTIONS, siteContext)\n const scope = AI_JOB_PLAN_SCOPES[job.kind] ?? null\n const capabilities = aiSitePlanCapabilities(\n job,\n workspace ? aiPlanCapabilitiesForJob(workspace, scope) : null,\n )\n const freeTaste = capabilities?.freeTaste === true\n // A build's operations, as this site has them (AGL-3616).\n const ops = job.kind === 'build' ? await readOps({ job, org, firestore, freeTaste }) : null\n const site = job.kind === 'site'\n // The model switch's answer for this job (AGL-2942): the creator's pick\n // where the plan, the org restriction and the allotment allowlists allow\n // it, and Auto held to those same lists otherwise. Without a resolver the\n // doctrine asks the routing table itself. A Free site plans on its\n // provider's fast tier (AGL-3594), unless the creator picked a model.\n const model = aiSitePlanModel(job, modelFor?.('job.plan'), freeTaste)\n const route = AI_ROUTING_TABLE['job.plan']\n const prompt = aiJobPlanPrompt(job, capabilities, inventory, ops)\n\n /**\n * The confirm door's answer for this plan, asked before the plan is kept\n * (AGL-3030): the kind's own admission, handed the plan as the resume\n * door hands it. A refusal fails the job with the door's sentence; a door\n * that could not answer keeps the plan, since the resume door asks again\n * before anything is built.\n */\n const refusalOnKeep = async (plan: AiJobPlan, outcome: AiJobStepOutcome): Promise<AiJobStepOutcome | null> => {\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>> = null\n try {\n refusal = await admissionRefusal(job.kind, {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n inputs: job.inputs ?? {},\n org,\n plan,\n uid: job.createdBy,\n })\n } catch (error) {\n console.error('ai plan admission failed', { orgId: job.orgId, jobId: job.$id, error })\n }\n return refusal ? { ...outcome, failure: refusal.error } : null\n }\n\n // Reuse before asking (AGL-2937). The key covers the whole request, so a\n // hit is a request that would have been sent the same bytes to the same\n // model; the window covers what the key cannot see. A reused plan spends\n // nothing, so the machine's spent-nothing branch releases the reservation\n // and meters no credit, and the job still stops for the member to confirm\n // — this job's plan is proposed to this member, whatever the last one did\n // with theirs.\n const resolved = model ?? aiModelForStep('job.plan')\n // A brief that asks for a video is offered the plan's list of players\n // (AGL-3433), and a job that may bind a dataset a record template on\n // each screen (AGL-3475).\n const tool = aiBuildPlanToolFor(job.brief, {\n records: Boolean(inventory?.datasets.length) || capabilities?.create.dataset.allowed === true,\n items: job.kind === 'build',\n })\n const key = aiJobPlanKey({\n job,\n prompt,\n model: resolved,\n system: aiDoctrineSystemBlocks(inventory, { instructions }),\n tool,\n })\n const reused = findPlansByKey\n ? aiReusablePlan(await findPlansByKey(job.orgId, key, firestore), {\n jobId: job.$id,\n now,\n })\n : null\n if (reused) {\n // The reused plan's draft ids name the other job's drafts; this job's are its own.\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...reused.plan,\n status: 'proposed',\n labels: aiPlanLabels(reused.plan, inventory),\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n reusedFrom: reused.jobId,\n }))\n const unspent = aiUnspentOutcome(resolved)\n return (\n (await refusalOnKeep(plan, unspent)) ?? {\n ...unspent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n\n const result = await runValidatedGeneration('plan', {\n step: 'job.plan',\n ...(model ? { model } : {}),\n instructions,\n inventory,\n messages: [{ role: 'user', content: prompt }],\n tool,\n // The routing ceiling, lowered on a tier too slow to look records up,\n // answer and ask again inside the least time the step registered; a\n // scaffold's outline is held to its own, far lower ceiling (AGL-3594).\n maxTokens: aiSitePlanMaxTokens(job, resolved, freeTaste),\n // A scaffold plans an outline without thinking (AGL-3594): the thinking\n // was nearly all of the 13,491 tokens a Free site's plan spent.\n ...(site ? { thinking: 'off' as const } : route.thinking ? { thinking: route.thinking } : {}),\n ...(route.effort ? { effort: route.effort } : {}),\n ...(signal ? { signal } : {}),\n capabilities,\n extend: planViolations(scope, job.brief, freeTaste, ops),\n })\n const spent: AiJobStepOutcome = {\n outputs: [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model: result.model,\n stopReason: result.stopReason,\n ...(result.effort ? { effort: result.effort } : {}),\n }\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') {\n // Refused by our own checks, after the one re-ask (AGL-3594): the member\n // reads a sentence and an action, staff the rules; the machine gives the\n // credits back (`uncredited`), and on the Free taste Try again says when\n // it cannot work. Whether the give-back was made is the job's to say\n // (`refundedCredits`), so this sentence does not promise it.\n const review = aiDoctrineReview(result)\n const retryRefusal = freeTaste\n ? await aiFreePlanRetryRefusal({ job, org, firestore, now, site })\n : null\n return {\n ...spent,\n uncredited: true,\n review: {\n ...review,\n message: aiPlanFailureCopy({\n kind: job.kind,\n codes: result.violations.map((violation) => violation.code),\n refunded: false,\n }),\n detail: review.detail ?? review.message,\n ...(retryRefusal ? { retryRefusal } : {}),\n },\n }\n }\n // Each draft the plan decides is named as the plan is kept, before anything is built (AGL-3079).\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...result.value,\n status: 'proposed',\n labels: aiPlanLabels(result.value, inventory),\n // A Date the Admin SDK stores as a timestamp, like every instant the machine writes.\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n }))\n return (\n (await refusalOnKeep(plan, spent)) ?? {\n ...spent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n}\n\n/**\n * A site job's capabilities (AGL-3594, AGL-3660): it changes no theme in its\n * plan — every scaffold designs its look first, in a unit of its own — and on\n * the Free taste its plan holds at most the pages the member asked for within\n * the Free band, which the Free wall then holds it to. Every other job's\n * capabilities pass through.\n */\nexport function aiSitePlanCapabilities(\n job: Pick<AiJob, 'kind' | 'inputs'>,\n capabilities: AiPlanCapabilities | null,\n): AiPlanCapabilities | null {\n if (job.kind !== 'site' || !capabilities) return capabilities\n const create = {\n ...capabilities.create,\n 'theme-change': {\n allowed: false,\n left: null,\n reason: 'a site start designs its own look before its pages',\n },\n // A site start builds its look, one layout and one form, never a\n // component (`AI_SITE_CREATE_KINDS`), so a paid workspace's plan draws\n // repeated items in their sections, as a Free one's does. Held to rule 1\n // instead, every paid plan was refused: for the component it left out,\n // or, re-asked, for the one it could not build (AGL-3660).\n component: {\n allowed: false,\n left: null,\n reason: 'a site start draws its repeated items in their sections',\n },\n }\n const site = { ...capabilities, reusableComponents: false, create }\n if (!capabilities.freeTaste) return site\n const asked = Number((job.inputs ?? {})['pages'])\n const pages =\n Number.isInteger(asked) && asked >= AI_SITE_FREE_PAGES.min\n ? Math.min(asked, AI_SITE_FREE_PAGES.max)\n : AI_SITE_FREE_PAGES.max\n return { ...site, freeSitePages: pages }\n}\n\n/**\n * The model a plan runs on (AGL-3594): the resolved one, except a Free site\n * plans on its provider's fast tier — an outline the plan rules hold and\n * re-ask, at a fifth of the balanced tier's output rate. A model the creator\n * picked by name stays theirs.\n */\nexport function aiSitePlanModel(\n job: Pick<AiJob, 'kind' | 'model'>,\n resolved: string | undefined,\n freeTaste: boolean,\n): string | undefined {\n if (job.kind !== 'site' || !freeTaste) return resolved\n const picked = typeof job.model === 'string' ? job.model.trim() : ''\n if (picked && picked !== 'auto') return resolved\n const entry = aiCatalogEntry(resolved ?? aiModelForStep('job.plan'))\n return (entry ? aiDefaultModelFor(entry.provider, 'fast') : undefined) ?? resolved\n}\n\n/** The plan's answer ceiling: the step's own, and a scaffold's outline ceiling under it (AGL-3594). */\nexport function aiSitePlanMaxTokens(\n job: Pick<AiJob, 'kind'>,\n model: string,\n freeTaste: boolean,\n): number {\n const ceiling = aiJobPlanMaxTokens(model)\n if (job.kind !== 'site') return ceiling\n return Math.min(ceiling, freeTaste ? AI_SITE_PLAN_MAX_TOKENS.free : AI_SITE_PLAN_MAX_TOKENS.paid)\n}\n\n/**\n * Why trying a Free plan again cannot work this month, or `null` (AGL-3594):\n * the owner's Free allowance left, read off the account month the meter\n * writes net of give-backs, against what a plan of this kind costs at its\n * worst. Read before this step is metered, and the machine gives a refused\n * plan's credits back, so the figure read is the figure left. A read that fails\n * leaves the button on: the reservation still refuses at the wall.\n */\nasync function aiFreePlanRetryRefusal(input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n now: Date\n site: boolean\n}): Promise<string | null> {\n const account = freeAssistAccount(input.org as AssistMeteredOrg | null)\n if (!account?.accountUid) return null\n try {\n // The meter's month key, `YYYY-MM` in UTC (`assistUsageMonth`).\n const month = input.now.toISOString().slice(0, 7)\n const snapshot = await freeAccountUsageRef(input.firestore, account.accountUid, month).get()\n const spent = assistCreditsFromUsd(\n assistSpendAfterReturnsUsd(snapshot.get('estCostUsd'), snapshot.get(ASSIST_RETURNED_USD_FIELD)),\n )\n return aiPlanRetryRefusal({\n creditsLeft: FREE_AI_TASTE_CREDITS_PER_MONTH - spent,\n planCredits: input.site ? AI_FREE_SITE_WORST_CASE_CREDITS.plan : AI_FREE_PAGE_WORST_CASE_CREDITS.plan,\n })\n } catch (error) {\n console.error('ai plan retry allowance read failed', { orgId: input.job.orgId, jobId: input.job.$id, error })\n return null\n }\n}\n\nexport const runAiJobPlanStep = createAiJobPlanStep()\n\n/**\n * Registers the plan step every planned kind runs first, with the least time\n * a plan needs; the plugin's console surface calls it.\n */\nexport function registerAiJobPlan(): void {\n registerAiJobPlanStep(runAiJobPlanStep, { minimumMs: AI_JOB_PLAN_STEP_MINIMUM_MS })\n}\n"],"names":["aiSiteKindOfInputs","createHash","AI_BUILD_PLAN_TOOL","aiBuildPlanToolFor","isAiPlanNewRef","AI_TEMPLATE_SUBJECT_DEFINITIONS","aiTemplateShownTokens","AI_JOB_CREATE_KINDS","AI_JOB_CREATE_NOUNS","AI_PAGE_CREATE_KINDS","aiPagePlanShapeRefusal","AI_PLAN_NO_FORM_SENTENCE","aiPlanCanPlaceForm","aiPlanCapabilitiesForJob","aiPlanCapabilityLines","AI_FREE_SITE_WORST_CASE_CREDITS","AI_SITE_CREATE_KINDS","AI_SITE_FREE_PAGES","AI_SITE_PLAN_MAX_TOKENS","aiFreeSiteSectionsWithin","aiSiteNameSentence","aiSitePlanShapeRefusal","aiPlanFailureCopy","aiPlanRetryRefusal","FREE_AI_TASTE_CREDITS_PER_MONTH","aiDoctrineSystemBlocks","runValidatedGeneration","AI_STEP_TIERS","aiCatalogEntry","aiDefaultModelFor","AI_FREE_PAGE_WORST_CASE_CREDITS","aiPlanEmbedBriefViolations","assistCreditsFromUsd","ASSIST_RETURNED_USD_FIELD","assistSpendAfterReturnsUsd","freeAccountUsageRef","freeAssistAccount","AI_ROUTING_TABLE","aiModelForStep","readSiteInventory","readAiSiteContext","aiInstructionsWithSiteContext","AI_BUILD_CREATE_KINDS","AI_BUILD_STRUCTURAL_OPS","aiBuildPageLimit","aiBuildPlanShapeRefusal","aiBuildOpLines","aiBuildOps","aiJobAdmissionRefusal","readAiPlanCapabilities","AI_JOB_BRIEF_MAX_CHARS","aiJobStepBudget","aiDoctrineReview","aiUnspentOutcome","aiPlanWithDraftIds","AI_JOBS_COLLECTION","registerAiJobPlanStep","AI_JOB_PLAN_INSTRUCTIONS","text","AI_JOB_PLAN_STEP_BUDGET","tier","maxTokens","AI_JOB_PLAN_STEP_MINIMUM_MS","minimumMs","aiJobPlanMaxTokens","model","AI_JOB_PLAN_REVIEW_COPY","aiJobPlanPrompt","job","capabilities","inventory","ops","lines","kind","brief","slice","key","value","Object","entries","inputs","push","String","aiPlanTemplateTokenLines","aiPlanSiteLines","aiPlanBuildLines","join","pages","freeTaste","name","trim","screens","filter","screen","template","starter","find","replaceable","length","page","slug","some","cap","freeSitePages","undefined","sections","layouts","label","toLowerCase","subject","definition","AI_JOB_PLAN_SCOPES","noun","creates","shapeRefusal","build","plan","options","site","fromEntries","map","planViolations","scope","message","rule","code","aiPlanLabels","names","Map","rows","components","templates","forms","datasets","collections","row","set","id","refs","reuse","entry","create","duplicateOf","flatMap","layout","section","uses","labels","ref","get","AI_PLAN_REUSE_WINDOW_MS","AI_PLAN_REUSE_CANDIDATES","aiJobPlanKey","input","digest","part","hostId","prompt","system","block","JSON","stringify","tool","update","UNREUSABLE","planMillis","at","proposedAt","Date","getTime","toMillis","aiReusablePlan","candidates","context","floor","now","best","bestAt","candidate","jobId","includes","status","findAiJobsByPlanKey","orgId","firestore","snapshot","collection","doc","where","limit","docs","data","readAiJobPlanCapabilities","org","readAiJobSiteContext","readAiBuildOps","host","aiPlanWithItemCredits","items","item","capability","op","credits","Math","max","estimateCredits","args","createAiJobPlanStep","deps","readInventory","findPlansByKey","readCapabilities","admissionRefusal","readOps","readContext","readSiteContext","signal","modelFor","orgDocument","workspace","siteContext","Promise","all","resolve","instructions","aiSitePlanCapabilities","aiSitePlanModel","route","refusalOnKeep","outcome","refusal","uid","createdBy","error","console","$id","failure","resolved","records","Boolean","dataset","allowed","reused","confirmedAt","confirmedBy","reusedFrom","unspent","review","reason","findings","result","step","messages","role","content","aiSitePlanMaxTokens","thinking","effort","extend","spent","outputs","usage","estCostUsd","stopReason","refused","retryRefusal","aiFreePlanRetryRefusal","uncredited","codes","violations","violation","refunded","detail","left","component","reusableComponents","asked","Number","isInteger","min","picked","provider","ceiling","free","paid","account","accountUid","month","toISOString","creditsLeft","planCredits","runAiJobPlanStep","registerAiJobPlan"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,UAAU,QAAQ,cAAa;AAExC,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,QAET,4BAAwB;AAE/B,SACEC,+BAA+B,EAC/BC,qBAAqB,QAEhB,mCAA+B;AACtC,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,+BAA2B;AACpF,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,0BAAsB;AACnF,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,wBAAwB,EACxBC,qBAAqB,QAGhB,mCAA+B;AAEtC,SACEC,+BAA+B,EAC/BC,oBAAoB,EACpBC,kBAAkB,EAClBC,uBAAuB,EACvBC,wBAAwB,EACxBC,kBAAkB,EAClBC,sBAAsB,QACjB,0BAAsB;AAC7B,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,kCAA8B;AACpF,SAASC,+BAA+B,QAAQ,0BAAsB;AACtE,SAASC,sBAAsB,EAAEC,sBAAsB,QAAQ,4BAAwB;AACvF,SAASC,aAAa,EAAEC,cAAc,EAAEC,iBAAiB,QAAQ,0BAAsB;AACvF,SACEC,+BAA+B,EAC/BC,0BAA0B,QAErB,uCAAmC;AAC1C,SAASC,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,yBAAyB,EAAEC,0BAA0B,QAAQ,oCAAgC;AACtG,SAASC,mBAAmB,EAAEC,iBAAiB,QAA+B,gCAA4B;AAC1G,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AAGvE,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SAASC,iBAAiB,QAAQ,6BAAyB;AAC3D,SAASC,6BAA6B,QAAiC,8BAA0B;AACjG,SACEC,qBAAqB,EACrBC,uBAAuB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AAEA,OAAO,MAAM0D,mBAAmBpF,sBAAqB;AAErD;;;CAGC,GACD,OAAO,SAASqF;IACd5O,sBAAsB2O,kBAAkB;QAAEpO,WAAWD;IAA4B;AACnF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-plan-step.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { createHash } from 'node:crypto'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport {\n AI_BUILD_PLAN_TOOL,\n aiBuildPlanToolFor,\n isAiPlanNewRef,\n type AiBuildPlan,\n} from '../model/ai-build-plan'\nimport type { AiJob, AiJobKind, AiJobPlan, AiJobStatus } from '../model/ai-jobs.types'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n aiTemplateShownTokens,\n type AiTemplateSubject,\n} from '../model/ai-template-subjects'\nimport { AI_JOB_CREATE_KINDS, AI_JOB_CREATE_NOUNS } from '../model/ai-job-creations'\nimport { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from '../model/ai-page-job'\nimport {\n AI_PLAN_COMPILED_REPEATS_SENTENCE,\n AI_PLAN_NO_FORM_SENTENCE,\n aiPlanCanPlaceForm,\n aiPlanCapabilitiesForJob,\n aiPlanCapabilityLines,\n type AiPlanCapabilities,\n type AiPlanJobScope,\n} from '../model/ai-plan-capabilities'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport {\n AI_FREE_SITE_WORST_CASE_CREDITS,\n AI_SITE_CREATE_KINDS,\n AI_SITE_FREE_PAGES,\n AI_SITE_PLAN_MAX_TOKENS,\n AI_SITE_HOME_BANDS,\n aiFreeSiteSectionsWithin,\n aiSiteFullPlanSentence,\n aiSiteHomeMinSections,\n aiSiteNameSentence,\n aiSitePlanIsHome,\n aiSitePlanShapeRefusal,\n aiSiteBlogStandInViolations,\n aiSiteThinHomeViolations,\n AI_SITE_GALLERY_SENTENCE,\n aiSiteEmptyGalleryViolations,\n} from '../model/ai-site-job'\nimport { aiSiteContentPart } from './ai-job-site-content'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport { aiPlanFailureCopy, aiPlanRetryRefusal } from '../model/ai-job-failure-copy'\nimport { FREE_AI_TASTE_CREDITS_PER_MONTH } from '../plan-entitlements'\nimport { aiDoctrineSystemBlocks, runValidatedGeneration } from '../runtime/ai-doctrine'\nimport { AI_STEP_TIERS, aiCatalogEntry, aiDefaultModelFor } from '../providers/catalog'\nimport {\n AI_FREE_PAGE_WORST_CASE_CREDITS,\n aiPlanEmbedBriefViolations,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { assistCreditsFromUsd } from '../usage/assist-credits'\nimport { ASSIST_RETURNED_USD_FIELD, assistSpendAfterReturnsUsd } from '../usage/assist-credit-returns'\nimport { freeAccountUsageRef, freeAssistAccount, type AssistMeteredOrg } from '../usage/assist-free-taste'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport type { AiTool } from '../providers/contract'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { readAiSiteContext } from '../runtime/site-context'\nimport { aiInstructionsWithSiteContext, type AiSiteContextInput } from '../model/ai-site-context'\nimport {\n AI_BUILD_CREATE_KINDS,\n AI_BUILD_STRUCTURAL_OPS,\n aiBuildPageLimit,\n aiBuildPlanShapeRefusal,\n type AiBuildOps,\n} from '../model/ai-build-job'\nimport { aiBuildOpLines, aiBuildOps } from './ai-build-capabilities'\nimport { aiJobAdmissionRefusal } from './ai-job-admission'\nimport { readAiPlanCapabilities } from './ai-job-drafts'\nimport {\n AI_JOB_BRIEF_MAX_CHARS,\n type AiJobStepOutcome,\n type AiJobStepRunner,\n} from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiDoctrineReview, aiUnspentOutcome } from './ai-job-generation'\nimport { aiPlanWithDraftIds } from './ai-job-draft-ids'\nimport { AI_JOBS_COLLECTION, registerAiJobPlanStep } from './ai-jobs'\n\n/**\n * The plan step (AGL-2935): the first step of every job that builds site\n * structure. Before a node is generated, the model answers with a typed plan\n * — what the site already has that the job reuses, what it creates and why,\n * and the screens it builds from them — held to the doctrine's plan rules\n * against the site's inventory and re-asked once when it breaks one.\n *\n * A plan that passes is kept on the job, and the job stops for review: the\n * member reads what it will build before a credit is spent building it, and\n * confirms through the resume door. A plan that still breaks a rule on its\n * re-ask stops the job the same way, with the rules named. Either way the\n * step writes nothing itself; the machine records the plan, the spend and\n * the stop, as it records every step.\n *\n * ── Told what it may create, refused what it cannot build (AGL-3030) ─────\n *\n * Before it asks, the step reads what the job may create on its site: the\n * workspace's plan, the site's counts against its limits, and — for a kind\n * that builds only some plans — what the job builds itself. The user turn\n * states it, the plan rules refuse a creation outside it with the one re-ask,\n * and where the workspace keeps no reusable components they accept the page\n * built inline. A plan the confirm door would still refuse — the kind's own\n * admission, handed the plan, as the resume door hands it — is refused HERE,\n * before a member is shown a Confirm: the job fails with the door's sentence,\n * its plan is not kept, and it holds nothing.\n */\n\n/** The plan step's own instructions, cached after the doctrine. */\nexport const AI_JOB_PLAN_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text:\n 'You plan what a website builder job will build, before anything is built. You are given the kind of job and the brief from the person who owns the site. ' +\n 'Answer with submit_build_plan: what the site inventory already has that the job reuses, what it must create and why nothing listed will do, and each page it builds (the screens list) with its layout, template, slug, search title, search description and sections from top to bottom. ' +\n 'Refer to inventory records by id and to what the plan creates as new:<name>. Plan only what the brief asks for: a component, layout, template, form or email job plans no pages unless the brief asks for them, and a page job plans exactly one page.',\n },\n]\n\n/**\n * The plan step's time (AGL-3026, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at the routing table's ceiling for `job.plan`, on\n * the tier that step kind is served from, with the step's reads and writes,\n * at the rates `ai-job-budget.ts` assumes — fitted to what a beat can give a\n * step, so the served tier asks a little under the routing ceiling.\n */\nexport const AI_JOB_PLAN_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.plan'],\n maxTokens: AI_ROUTING_TABLE['job.plan'].maxTokens,\n})\n\n/**\n * The least time a plan needs before it starts. Registered with the step, so\n * an inline door never starts a plan. A plan thinks before it answers and\n * routinely runs past an inline door's budget, and a provider call that\n * budget cuts off is still generated and billed upstream while the meter\n * records nothing. The beat starts a plan only with this much of its own\n * budget left, and a spec holds it inside that budget.\n */\nexport const AI_JOB_PLAN_STEP_MINIMUM_MS = AI_JOB_PLAN_STEP_BUDGET.minimumMs\n\n/**\n * The plan's answer ceiling on the model a job runs: the most whose worst\n * case fits the least time the step registered, and never more than the\n * routing table's. A model the catalog does not know is planned at the\n * slowest.\n */\nexport function aiJobPlanMaxTokens(model: string): number {\n return AI_JOB_PLAN_STEP_BUDGET.maxTokens(model)\n}\n\n/** What the member reads while a plan waits for them. */\nexport const AI_JOB_PLAN_REVIEW_COPY =\n 'The plan is ready. Review what the job will reuse and create, then confirm it to build.'\n\n/**\n * The job as the plan step's user turn: its kind, its brief, its scalar\n * inputs and, where the job read them, what it may create on its site\n * (AGL-3030). Per workspace and per site, which is why they ride here and\n * never in a system block the platform's cache entry is keyed on.\n */\nexport function aiJobPlanPrompt(\n job: Pick<AiJob, 'kind' | 'brief' | 'inputs'>,\n capabilities: AiPlanCapabilities | null = null,\n inventory: AiSiteInventory | null = null,\n ops: AiBuildOps | null = null,\n): string {\n const lines = [`Job kind: ${job.kind}`, `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`]\n for (const [key, value] of Object.entries(job.inputs ?? {})) {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n lines.push(`${key}: ${String(value)}`)\n }\n }\n if (capabilities) lines.push(...aiPlanCapabilityLines(capabilities))\n // A form is a saved form or none (AGL-3596): said where the site read has\n // none to place and the job may create none.\n if (capabilities && inventory && !aiPlanCanPlaceForm(inventory, capabilities)) {\n lines.push(AI_PLAN_NO_FORM_SENTENCE)\n }\n lines.push(...aiPlanTemplateTokenLines(job))\n lines.push(...aiPlanSiteLines(job, inventory, capabilities))\n lines.push(...aiPlanBuildLines(job, capabilities, ops))\n return lines.join('\\n')\n}\n\n/**\n * What a BUILD job's plan is told (AGL-3616): that one request becomes pages,\n * creations and items, how many pages it may hold, and the item operations\n * this site has with their arguments. On the job's own turn, never a cached\n * system block, because the operations are per site.\n */\nexport function aiPlanBuildLines(\n job: Pick<AiJob, 'kind'>,\n capabilities: AiPlanCapabilities | null,\n ops: AiBuildOps | null,\n): string[] {\n if (job.kind !== 'build') return []\n const pages = aiBuildPageLimit(capabilities?.freeTaste === true)\n return [\n `This is a build from one request: plan each page it asks for in screens (at most ${pages}), each new layout, form, component or email design in create, and anything else in items. Plan only what the request asks for; reuse what the site has.`,\n 'A page section that shows a form or an item places it: put its new:<name> in that section\\'s uses. An item built after another lists it in dependsOn.',\n // The layout language draws a section's repeated items (AGL-3660), so the\n // doctrine's \"repeated items place a component\" is not asked of a build.\n ...(capabilities?.repeatsCompiled ? [AI_PLAN_COMPILED_REPEATS_SENTENCE] : []),\n ...(ops ? aiBuildOpLines(ops, AI_BUILD_STRUCTURAL_OPS) : []),\n ]\n}\n\n/**\n * What a SITE job's plan is told beside the inventory (AGL-3594): the pages\n * the site already has and that their addresses are taken, which one — the\n * untouched starter home — a planned home page at `/` replaces, the Free page\n * cap and its guidance, and that a plan is an outline.\n *\n * A site job only. A new site is born with a published home page at `/`\n * (AGL-3497), and a plan that did not know it could replace it planned its own\n * home there and was refused for the clash on every new site. Kept off a page\n * job's turn, whose length the Free page's wall is proven at.\n */\nexport function aiPlanSiteLines(\n job: Pick<AiJob, 'kind'> & Partial<Pick<AiJob, 'inputs'>>,\n inventory: AiSiteInventory | null,\n capabilities: AiPlanCapabilities | null,\n): string[] {\n if (job.kind !== 'site') return []\n const lines: string[] = []\n // The business's own name, as the name to use (AGL-3596): the plan's search\n // titles carry it, and an input line alone left the model free to coin one.\n const name = job.inputs?.['businessName']\n if (typeof name === 'string' && name.trim()) lines.push(aiSiteNameSentence(name.trim()))\n const pages = (inventory?.screens ?? []).filter((screen) => !screen.template)\n const starter = pages.find((screen) => screen.replaceable)\n if (pages.length) {\n lines.push('Pages the site already has; their addresses are taken unless a line says otherwise:')\n for (const page of pages) {\n lines.push(\n page.replaceable\n ? `- ${page.name} at ${page.slug}: the starter home page the site was created with. Plan this site's home page at / and it replaces this one.`\n : `- ${page.name} at ${page.slug}`,\n )\n }\n if (!starter && pages.some((page) => page.slug.trim() === '/' || page.slug.trim() === '')) {\n lines.push(\"The home page at / is the owner's own and stays: give every page you plan another address.\")\n }\n }\n const cap = capabilities?.freeSitePages\n const home = aiSitePlanHomeRule(inventory, capabilities)\n if (cap !== undefined) {\n lines.push(\n `This is a Free workspace: plan at most ${cap} ${cap === 1 ? 'page' : 'pages'} — the home page at / and the one page the brief most needs, such as services, booking or contact — and ${home.across} sections across them.${aiPlanCanPlaceForm(inventory, capabilities) ? ' Put the contact form on one of them.' : ''}`,\n )\n }\n // A new site is a full website (AGL-3660): its home is planned as one, not\n // left to a ceiling the outline is free to stay far under.\n const plansHome = !pages.some((page) => !page.replaceable && aiSitePlanIsHome(page))\n if (home.min > 0 && plansHome) {\n lines.push(`The home page at / reads as a full website: at least ${home.min} sections — ${AI_SITE_HOME_BANDS}.`)\n }\n // The sections are a budget to use (AGL-3660): a prod start of 2026-10-08\n // read \"at most 8\" as leave to plan a home of two.\n lines.push(aiSiteFullPlanSentence({ pages: cap ?? 1, across: home.across, min: plansHome ? home.min : 0 }))\n // A paid blog's first posts are written at /blog and linked from the\n // header (AGL-3660, AGL-3676), so the plan plans no page standing in for it.\n if (aiSiteContentPart(job.inputs ?? null, capabilities?.freeTaste === true) === 'posts') {\n lines.push(\n \"This site's blog is written for it with its first posts at /blog, and the header links it. Plan no page that stands in for it (no Blog, Articles, Journal, Posts or Stories page); feature the posts in a section of the home page instead.\",\n )\n }\n // A section that shows the work counts its pieces (AGL-3660): a planned\n // gallery of no items let a page about the work show none.\n lines.push(AI_SITE_GALLERY_SENTENCE)\n // The kind of site the person picked (AGL-3660): the pages it usually has.\n const kind = aiSiteKindOfInputs(job.inputs)\n if (kind) lines.push(`This is a ${kind.label.toLowerCase()} site. ${kind.pages}`)\n lines.push(\n \"Keep the plan an outline: each page's title, address, a short search title and description, and its sections named in a few words. The build writes the copy.\",\n )\n return lines\n}\n\n/**\n * What a site start's home page is held to (AGL-3660): its fewest sections,\n * and on the Free taste the sections the wall fits across the pages, which\n * the home's count is shared out of. The plan's turn and its re-ask read this\n * one figure, so the sentence the model is told is the check it is held to.\n */\nexport function aiSitePlanHomeRule(\n inventory: AiSiteInventory | null,\n capabilities: AiPlanCapabilities | null,\n): { min: number; across: number | null } {\n const cap = capabilities?.freeSitePages\n if (cap === undefined) return { min: aiSiteHomeMinSections({ pages: 1, across: null }), across: null }\n // Dear: a guided start that places a form makes one (AGL-3596).\n const across = aiFreeSiteSectionsWithin(\n { layouts: (inventory?.layouts.length ?? 0) ? 0 : 1, pages: cap, forms: 1 },\n FREE_AI_TASTE_CREDITS_PER_MONTH,\n )\n return { min: aiSiteHomeMinSections({ pages: cap, across }), across }\n}\n\n/**\n * A site plan's thin home, asked about on the FIRST answer only (AGL-3660).\n * The re-ask names the count; an answer that still plans a thinner home is\n * kept, since a home with four sections is a site and a stopped start is\n * none — the same trade a language page makes with its last answer's gaps.\n */\nexport function aiSiteThinHomeCheck(\n rule: { min: number; across: number | null },\n): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteThinHomeViolations(plan, rule)\n }\n}\n\n/**\n * A site plan's section that shows the work without its pieces (AGL-3660),\n * asked about on the FIRST answer only, like a thin home: the re-ask names\n * the section, and an answer that keeps it thin is kept.\n */\nexport function aiSiteEmptyGalleryCheck(): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteEmptyGalleryViolations(plan)\n }\n}\n\n/**\n * A site plan's page standing in for the blog its start writes (AGL-3660),\n * asked about on the FIRST answer only, like a thin home: the re-ask names\n * the page, and an answer that keeps it is kept — the posts then take the\n * next address the page leaves free, and the header links them all the same.\n */\nexport function aiSiteBlogStandInCheck(): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteBlogStandInViolations(plan)\n }\n}\n\n/**\n * What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143\n * §11): the subject's binding tokens, listed so the planner promises only\n * what the page can fill and the build can be held to it\n * (`aiPlanTemplateTokenViolations`).\n *\n * ⛔ It rides the job's own turn and NOT the `fields` description in the plan\n * tool, which every kind's request caches. Written there it read better and\n * cost 40 tokens of the shared prefix — 2,980 to 3,020 — which is one credit\n * of the Free page's 300-credit wall, taking the room it keeps for a re-asked\n * section from 45 credits to 44 and breaking `ai-job-free-page.spec.ts`. A\n * page job must not pay for a sentence about templates.\n *\n * The list is the tokens a reader sees, never the whole catalog (AGL-3143\n * §16). Offered a slug and the publish timestamp, a live plan promised them,\n * and its build kept the promise the only way a slug can be kept: it printed\n * \"entry slug: {{entry.slug}}\" on every article.\n */\nexport function aiPlanTemplateTokenLines(job: Pick<AiJob, 'kind' | 'inputs'>): string[] {\n if (job.kind !== 'template') return []\n const subject = (job.inputs ?? {})['subject']\n const definition =\n typeof subject === 'string'\n ? AI_TEMPLATE_SUBJECT_DEFINITIONS[subject as AiTemplateSubject]\n : undefined\n if (!definition) return []\n return [\n `The template's fields are the binding tokens its page shows a reader, each one of: ${aiTemplateShownTokens(\n definition,\n ).join(', ')}. A link or picture token is shown by the link or picture holding it. Promise only what the page fills.`,\n ]\n}\n\n/** A kind that builds only some plans: the creations it makes, and the shapes it refuses. */\nexport interface AiJobPlanScope extends AiPlanJobScope {\n /** Why a job of the kind cannot build a plan of this shape; `null` when it can. Pure. */\n shapeRefusal: (plan: AiBuildPlan, options?: { freeTaste?: boolean }) => string | null\n}\n\n/**\n * The kinds whose confirm door builds only some plans (AGL-3030). A page job\n * builds one screen and a scaffold four to eight; each builds only the\n * creations its list names. A template, layout, component, form or email job\n * builds its own record and what that record places (AGL-3143 §15,\n * `AI_JOB_CREATE_KINDS`), and holds no plan to a shape.\n */\nexport const AI_JOB_PLAN_SCOPES: Readonly<Partial<Record<AiJobKind, AiJobPlanScope>>> = {\n page: { noun: 'a page job', creates: AI_PAGE_CREATE_KINDS, shapeRefusal: aiPagePlanShapeRefusal },\n // A build from one request (AGL-3616): its operations are judged against\n // the site's registry by the step, which reads it (`aiBuildPlanViolations`).\n build: {\n noun: 'a build',\n creates: AI_BUILD_CREATE_KINDS,\n shapeRefusal: (plan, options) => aiBuildPlanShapeRefusal(plan, { freeTaste: options?.freeTaste }),\n },\n site: { noun: 'a site scaffold', creates: AI_SITE_CREATE_KINDS, shapeRefusal: aiSitePlanShapeRefusal },\n ...Object.fromEntries(\n Object.entries(AI_JOB_CREATE_KINDS).map(([kind, creates]) => [\n kind,\n { noun: AI_JOB_CREATE_NOUNS[kind as AiJobKind] as string, creates, shapeRefusal: () => null },\n ]),\n ),\n}\n\n/**\n * What the plan step holds beyond the doctrine's plan rules, as the\n * violations the plan's one re-ask names: the players the plan lists against\n * the brief it answers (AGL-3433), which only this step reads beside the plan,\n * and a kind's shape refusal.\n */\nfunction planViolations(\n scope: AiJobPlanScope | null,\n brief: string,\n freeTaste = false,\n ops: AiBuildOps | null = null,\n home: { min: number; across: number | null } | null = null,\n blog = false,\n site = false,\n): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n const thinHome = home && home.min > 0 ? aiSiteThinHomeCheck(home) : null\n const blogStandIn = blog ? aiSiteBlogStandInCheck() : null\n const emptyGallery = site ? aiSiteEmptyGalleryCheck() : null\n return (plan) => {\n // A build's plan is held to the operations this site has (AGL-3616):\n // an unknown op, arguments its schema refuses, a cycle or a reference\n // nothing makes are re-asked once like every other plan rule.\n const message = ops\n ? aiBuildPlanShapeRefusal(plan, { freeTaste, ops })\n : (scope?.shapeRefusal(plan, { freeTaste }) ?? null)\n return [\n ...aiPlanEmbedBriefViolations(plan, brief),\n ...(message ? [{ rule: null, code: 'plan-job-shape', message }] : []),\n ...(thinHome ? thinHome(plan) : []),\n ...(blogStandIn ? blogStandIn(plan) : []),\n ...(emptyGallery ? emptyGallery(plan) : []),\n ]\n }\n}\n\n/**\n * The inventory names of every id the plan references, so the proposal reads\n * \"the Services layout\" rather than an id — kept on the plan because the\n * inventory is not read again when the member opens it.\n */\nexport function aiPlanLabels(\n plan: AiBuildPlan,\n inventory: AiSiteInventory | null,\n): Record<string, string> {\n const names = new Map<string, string>()\n for (const rows of [\n inventory?.components,\n inventory?.layouts,\n inventory?.templates,\n inventory?.forms,\n inventory?.datasets,\n inventory?.collections,\n inventory?.screens,\n ]) {\n for (const row of rows ?? []) names.set(row.id, row.name)\n }\n const refs = [\n ...plan.reuse.map((entry) => entry.id),\n ...plan.create.map((entry) => entry.duplicateOf),\n ...plan.screens.flatMap((screen) => [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ]),\n ]\n const labels: Record<string, string> = {}\n for (const ref of refs) {\n if (!ref || isAiPlanNewRef(ref)) continue\n const name = names.get(ref)\n if (name) labels[ref] = name\n }\n return labels\n}\n\n/* ------------------------------------------------------------------------ *\n * Reusing an identical brief's plan\n * ------------------------------------------------------------------------ */\n\n/**\n * How long a plan may be reused for (AGL-2937).\n *\n * The window is what makes reuse safe rather than merely cheap. The key\n * already covers everything the request said — the brief, the inputs, the\n * model and the prompt as rendered, site inventory included — so a plan is\n * reused only when nothing the model was shown has changed. What the key\n * cannot see is the world outside the request: a page published, a component\n * renamed after the inventory was read, a member who meant something\n * different the second time. Fifteen minutes is short enough that the answer\n * is still the one the site would give, and long enough to cover what reuse\n * is actually for — the same brief run twice in a sitting, a job resubmitted\n * after a refused reservation, two members starting the same work.\n */\nexport const AI_PLAN_REUSE_WINDOW_MS = 15 * 60 * 1_000\n\n/** Jobs one lookup reads. More than one can share a key; the newest plan wins. */\nexport const AI_PLAN_REUSE_CANDIDATES = 5\n\n/** A job whose plan might be reused, as the finder reports it. */\nexport interface AiJobPlanCandidate {\n jobId: string\n status: AiJobStatus\n plan: AiJobPlan\n}\n\n/**\n * The digest a plan is reused by: the whole request, never the answer.\n *\n * It hashes what the model was asked and what it was shown — the job's kind\n * and site, the user turn (which carries the trimmed brief and every scalar\n * input), the model that would answer, every rendered system block including\n * the site inventory, and the tool's schema. Two requests that hash the same\n * would have been sent the same bytes to the same model, so the second can\n * keep the first's answer.\n *\n * The version tag is the escape hatch: anything that changes what a key\n * MEANS, rather than what it covers, bumps it and strands every old key\n * harmlessly, since a key nothing matches simply asks the model.\n */\nexport function aiJobPlanKey(input: {\n job: Pick<AiJob, 'kind' | 'hostId'>\n prompt: string\n model: string\n system: readonly AiSystemBlock[]\n /** The plan tool the request offers (AGL-3433); the plain one when absent. */\n tool?: AiTool\n}): string {\n const digest = createHash('sha256')\n for (const part of [\n 'plan.v1',\n input.job.kind,\n input.job.hostId ?? '',\n input.model,\n input.prompt,\n ...input.system.map((block) => block.text),\n JSON.stringify(input.tool ?? AI_BUILD_PLAN_TOOL),\n ]) {\n // Length-prefixed, so two different splits of the same characters cannot\n // collide by running into one another.\n digest.update(`${part.length}:${part}\\u0000`)\n }\n return digest.digest('hex')\n}\n\n/** A job that could not have produced a reusable plan, whatever its key says. */\nconst UNREUSABLE: readonly AiJobStatus[] = ['canceled', 'failed']\n\nfunction planMillis(plan: AiJobPlan): number | null {\n const at = plan.proposedAt as unknown\n if (at instanceof Date) return at.getTime()\n if (at && typeof (at as { toMillis?: unknown }).toMillis === 'function') {\n return (at as { toMillis(): number }).toMillis()\n }\n return null\n}\n\n/**\n * The newest plan worth reusing out of what the finder returned: another\n * job's, still proposed or already confirmed, on a job that was neither\n * canceled nor failed, proposed inside the window.\n *\n * A canceled or failed job is excluded even though its plan may be perfectly\n * good: those are the jobs a member walked away from, and handing their plan\n * to the next one would make a rejected answer look like a fresh one.\n */\nexport function aiReusablePlan(\n candidates: readonly AiJobPlanCandidate[],\n context: { jobId: string; now: Date },\n): AiJobPlanCandidate | null {\n const floor = context.now.getTime() - AI_PLAN_REUSE_WINDOW_MS\n let best: AiJobPlanCandidate | null = null\n let bestAt = -1\n for (const candidate of candidates) {\n if (candidate.jobId === context.jobId) continue\n if (UNREUSABLE.includes(candidate.status)) continue\n if (candidate.plan.status !== 'proposed' && candidate.plan.status !== 'confirmed') continue\n const at = planMillis(candidate.plan)\n if (at === null || at < floor || at > context.now.getTime()) continue\n if (at > bestAt) {\n best = candidate\n bestAt = at\n }\n }\n return best\n}\n\nexport type AiJobPlanFinder = (\n orgId: string,\n key: string,\n firestore?: FirebaseFirestore.Firestore,\n) => Promise<AiJobPlanCandidate[]>\n\n/**\n * The finder the step uses in production: an equality on `plan.key` inside\n * the org's own jobs.\n *\n * One equality on one field, with no ordering beside it, so Firestore's\n * automatic single-field index answers it and no composite index is deployed.\n * The window and the statuses are applied in memory instead, which is what\n * keeps it that way.\n */\nexport const findAiJobsByPlanKey: AiJobPlanFinder = async (orgId, key, firestore) => {\n if (!firestore) return []\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(AI_JOBS_COLLECTION)\n .where('plan.key', '==', key)\n .limit(AI_PLAN_REUSE_CANDIDATES)\n .get()\n return snapshot.docs.flatMap((doc) => {\n const data = doc.data() as { status?: AiJobStatus; plan?: AiJobPlan | null }\n return data.plan\n ? [{ jobId: doc.id, status: data.status ?? 'queued', plan: data.plan }]\n : []\n })\n}\n\n/** What a job may create on its site, read for the plan step; `null` for no site. */\nexport type AiPlanCapabilitiesReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiPlanCapabilities | null>\n\n/** The reader the step uses in production: the draft bands' own arithmetic, for the job's site. */\nexport const readAiJobPlanCapabilities: AiPlanCapabilitiesReader = async ({ job, org, firestore }) =>\n job.hostId ? readAiPlanCapabilities(firestore, { hostId: job.hostId, org }) : null\n\nexport interface AiJobPlanStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The reuse lookup; specs hand in a fake, and `null` turns reuse off. */\n findPlansByKey?: AiJobPlanFinder | null\n /** What the job may create on its site (AGL-3030); specs and the eval recorder hand in their own. */\n readCapabilities?: AiPlanCapabilitiesReader\n /** The kind's admission, asked of a plan before it is kept; the registry's otherwise. */\n admissionRefusal?: typeof aiJobAdmissionRefusal\n /** A build's operations on its site (AGL-3616); the registry and its gates otherwise. */\n readOps?: AiBuildOpsReader\n /**\n * The site's business profile, status and remembered preferences\n * (AGL-3661); specs and the eval recorder hand in their own, and `null`\n * turns it off.\n */\n readSiteContext?: AiSiteContextReader | null\n}\n\n/** What a job's site context is read with (AGL-3661). */\nexport type AiSiteContextReader = (input: {\n job: AiJob\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiSiteContextInput | null>\n\n/** The reader the step uses in production: fail-soft, org-scoped, `null` for a job with no site. */\nexport const readAiJobSiteContext: AiSiteContextReader = ({ job, firestore }) =>\n readAiSiteContext(firestore, { orgId: job.orgId, hostId: job.hostId })\n\n/** What a build may plan on its site (AGL-3616). */\nexport type AiBuildOpsReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n freeTaste: boolean\n}) => Promise<AiBuildOps>\n\n/** The reader the step uses in production: the registry, gated for the job's site. */\nexport const readAiBuildOps: AiBuildOpsReader = async ({ job, org, firestore, freeTaste }) => {\n const host = job.hostId\n ? (((await firestore.collection('hosts').doc(job.hostId).get()).data() ?? null) as Record<string, unknown> | null)\n : null\n return aiBuildOps({ orgId: job.orgId, hostId: job.hostId ?? null, org, host, freeTaste })\n}\n\n/**\n * A build plan's items with what each can cost (AGL-3616), from its\n * capability, recorded as the plan is kept so the console's estimate and the\n * confirm door read one figure without the registry.\n */\nexport function aiPlanWithItemCredits<T extends AiBuildPlan>(ops: AiBuildOps | null, plan: T): T {\n if (!ops || !plan.items?.length) return plan\n return {\n ...plan,\n items: plan.items.map((item) => {\n const capability = ops.get(item.op)\n return capability ? { ...item, credits: Math.max(0, Math.floor(capability.estimateCredits(item.args))) } : item\n }),\n }\n}\n\nexport function createAiJobPlanStep(deps: AiJobPlanStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const findPlansByKey =\n deps.findPlansByKey === undefined ? findAiJobsByPlanKey : deps.findPlansByKey\n const readCapabilities = deps.readCapabilities ?? readAiJobPlanCapabilities\n const admissionRefusal = deps.admissionRefusal ?? aiJobAdmissionRefusal\n const readOps = deps.readOps ?? readAiBuildOps\n const readContext = deps.readSiteContext === undefined ? readAiJobSiteContext : deps.readSiteContext\n return async ({ job, now, signal, firestore, modelFor, org: orgDocument }) => {\n const org = (orgDocument ?? null) as Partial<AglynOrgBilling> | null\n const [inventory, workspace, siteContext] = await Promise.all([\n job.hostId ? readInventory(job.orgId, job.hostId, { firestore }) : Promise.resolve(null),\n readCapabilities({ job, org, firestore }),\n job.hostId && readContext ? readContext({ job, firestore }) : Promise.resolve(null),\n ])\n // The site's profile, status and memory (AGL-3661), as a per-site cached\n // block after the plan rules. The inventory block already lists what the\n // site holds, so the context carries no index of its own here.\n const instructions = aiInstructionsWithSiteContext(AI_JOB_PLAN_INSTRUCTIONS, siteContext)\n const scope = AI_JOB_PLAN_SCOPES[job.kind] ?? null\n const capabilities = aiSitePlanCapabilities(\n job,\n workspace ? aiPlanCapabilitiesForJob(workspace, scope) : null,\n )\n const freeTaste = capabilities?.freeTaste === true\n // A build's operations, as this site has them (AGL-3616).\n const ops = job.kind === 'build' ? await readOps({ job, org, firestore, freeTaste }) : null\n const site = job.kind === 'site'\n // The model switch's answer for this job (AGL-2942): the creator's pick\n // where the plan, the org restriction and the allotment allowlists allow\n // it, and Auto held to those same lists otherwise. Without a resolver the\n // doctrine asks the routing table itself. A Free site plans on its\n // provider's fast tier (AGL-3594), unless the creator picked a model.\n const model = aiSitePlanModel(job, modelFor?.('job.plan'), freeTaste)\n const route = AI_ROUTING_TABLE['job.plan']\n const prompt = aiJobPlanPrompt(job, capabilities, inventory, ops)\n\n /**\n * The confirm door's answer for this plan, asked before the plan is kept\n * (AGL-3030): the kind's own admission, handed the plan as the resume\n * door hands it. A refusal fails the job with the door's sentence; a door\n * that could not answer keeps the plan, since the resume door asks again\n * before anything is built.\n */\n const refusalOnKeep = async (plan: AiJobPlan, outcome: AiJobStepOutcome): Promise<AiJobStepOutcome | null> => {\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>> = null\n try {\n refusal = await admissionRefusal(job.kind, {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n inputs: job.inputs ?? {},\n org,\n plan,\n uid: job.createdBy,\n })\n } catch (error) {\n console.error('ai plan admission failed', { orgId: job.orgId, jobId: job.$id, error })\n }\n return refusal ? { ...outcome, failure: refusal.error } : null\n }\n\n // Reuse before asking (AGL-2937). The key covers the whole request, so a\n // hit is a request that would have been sent the same bytes to the same\n // model; the window covers what the key cannot see. A reused plan spends\n // nothing, so the machine's spent-nothing branch releases the reservation\n // and meters no credit, and the job still stops for the member to confirm\n // — this job's plan is proposed to this member, whatever the last one did\n // with theirs.\n const resolved = model ?? aiModelForStep('job.plan')\n // A brief that asks for a video is offered the plan's list of players\n // (AGL-3433), and a job that may bind a dataset a record template on\n // each screen (AGL-3475).\n const tool = aiBuildPlanToolFor(job.brief, {\n records: Boolean(inventory?.datasets.length) || capabilities?.create.dataset.allowed === true,\n items: job.kind === 'build',\n })\n const key = aiJobPlanKey({\n job,\n prompt,\n model: resolved,\n system: aiDoctrineSystemBlocks(inventory, { instructions }),\n tool,\n })\n const reused = findPlansByKey\n ? aiReusablePlan(await findPlansByKey(job.orgId, key, firestore), {\n jobId: job.$id,\n now,\n })\n : null\n if (reused) {\n // The reused plan's draft ids name the other job's drafts; this job's are its own.\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...reused.plan,\n status: 'proposed',\n labels: aiPlanLabels(reused.plan, inventory),\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n reusedFrom: reused.jobId,\n }))\n const unspent = aiUnspentOutcome(resolved)\n return (\n (await refusalOnKeep(plan, unspent)) ?? {\n ...unspent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n\n const result = await runValidatedGeneration('plan', {\n step: 'job.plan',\n ...(model ? { model } : {}),\n instructions,\n inventory,\n messages: [{ role: 'user', content: prompt }],\n tool,\n // The routing ceiling, lowered on a tier too slow to look records up,\n // answer and ask again inside the least time the step registered; a\n // scaffold's outline is held to its own, far lower ceiling (AGL-3594).\n maxTokens: aiSitePlanMaxTokens(job, resolved, freeTaste),\n // A scaffold plans an outline without thinking (AGL-3594): the thinking\n // was nearly all of the 13,491 tokens a Free site's plan spent.\n ...(site ? { thinking: 'off' as const } : route.thinking ? { thinking: route.thinking } : {}),\n ...(route.effort ? { effort: route.effort } : {}),\n ...(signal ? { signal } : {}),\n capabilities,\n extend: planViolations(\n scope,\n job.brief,\n freeTaste,\n ops,\n site ? aiSitePlanHomeRule(inventory, capabilities) : null,\n site && aiSiteContentPart(job.inputs ?? null, freeTaste) === 'posts',\n site,\n ),\n })\n const spent: AiJobStepOutcome = {\n outputs: [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model: result.model,\n stopReason: result.stopReason,\n ...(result.effort ? { effort: result.effort } : {}),\n }\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') {\n // Refused by our own checks, after the one re-ask (AGL-3594): the member\n // reads a sentence and an action, staff the rules; the machine gives the\n // credits back (`uncredited`), and on the Free taste Try again says when\n // it cannot work. Whether the give-back was made is the job's to say\n // (`refundedCredits`), so this sentence does not promise it.\n const review = aiDoctrineReview(result)\n const retryRefusal = freeTaste\n ? await aiFreePlanRetryRefusal({ job, org, firestore, now, site })\n : null\n return {\n ...spent,\n uncredited: true,\n review: {\n ...review,\n message: aiPlanFailureCopy({\n kind: job.kind,\n codes: result.violations.map((violation) => violation.code),\n refunded: false,\n }),\n detail: review.detail ?? review.message,\n ...(retryRefusal ? { retryRefusal } : {}),\n },\n }\n }\n // Each draft the plan decides is named as the plan is kept, before anything is built (AGL-3079).\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...result.value,\n status: 'proposed',\n labels: aiPlanLabels(result.value, inventory),\n // A Date the Admin SDK stores as a timestamp, like every instant the machine writes.\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n }))\n return (\n (await refusalOnKeep(plan, spent)) ?? {\n ...spent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n}\n\n/**\n * A site job's capabilities (AGL-3594, AGL-3660): it changes no theme in its\n * plan — every scaffold designs its look first, in a unit of its own — and on\n * the Free taste its plan holds at most the pages the member asked for within\n * the Free band, which the Free wall then holds it to.\n *\n * A build's pages are written in the layout language (`aiBuildUnitJob`), whose\n * compiler draws a section's repeated items itself, so its plan is not asked\n * for a component for them (`repeatsCompiled`, AGL-3616). It still may plan\n * one, and a section two pages share is still one. Every other job's\n * capabilities pass through.\n */\nexport function aiSitePlanCapabilities(\n job: Pick<AiJob, 'kind' | 'inputs'>,\n capabilities: AiPlanCapabilities | null,\n): AiPlanCapabilities | null {\n if (job.kind === 'build' && capabilities) return { ...capabilities, repeatsCompiled: true }\n if (job.kind !== 'site' || !capabilities) return capabilities\n const create = {\n ...capabilities.create,\n 'theme-change': {\n allowed: false,\n left: null,\n reason: 'a site start designs its own look before its pages',\n },\n // A site start builds its look, one layout and one form, never a\n // component (`AI_SITE_CREATE_KINDS`), so a paid workspace's plan draws\n // repeated items in their sections, as a Free one's does. Held to rule 1\n // instead, every paid plan was refused: for the component it left out,\n // or, re-asked, for the one it could not build (AGL-3660).\n component: {\n allowed: false,\n left: null,\n reason: 'a site start draws its repeated items in their sections',\n },\n }\n const site = { ...capabilities, reusableComponents: false, create }\n if (!capabilities.freeTaste) return site\n const asked = Number((job.inputs ?? {})['pages'])\n const pages =\n Number.isInteger(asked) && asked >= AI_SITE_FREE_PAGES.min\n ? Math.min(asked, AI_SITE_FREE_PAGES.max)\n : AI_SITE_FREE_PAGES.max\n return { ...site, freeSitePages: pages }\n}\n\n/**\n * The model a plan runs on (AGL-3594): the resolved one, except a Free site\n * plans on its provider's fast tier — an outline the plan rules hold and\n * re-ask, at a fifth of the balanced tier's output rate. A model the creator\n * picked by name stays theirs.\n */\nexport function aiSitePlanModel(\n job: Pick<AiJob, 'kind' | 'model'>,\n resolved: string | undefined,\n freeTaste: boolean,\n): string | undefined {\n if (job.kind !== 'site' || !freeTaste) return resolved\n const picked = typeof job.model === 'string' ? job.model.trim() : ''\n if (picked && picked !== 'auto') return resolved\n const entry = aiCatalogEntry(resolved ?? aiModelForStep('job.plan'))\n return (entry ? aiDefaultModelFor(entry.provider, 'fast') : undefined) ?? resolved\n}\n\n/** The plan's answer ceiling: the step's own, and a scaffold's outline ceiling under it (AGL-3594). */\nexport function aiSitePlanMaxTokens(\n job: Pick<AiJob, 'kind'>,\n model: string,\n freeTaste: boolean,\n): number {\n const ceiling = aiJobPlanMaxTokens(model)\n if (job.kind !== 'site') return ceiling\n return Math.min(ceiling, freeTaste ? AI_SITE_PLAN_MAX_TOKENS.free : AI_SITE_PLAN_MAX_TOKENS.paid)\n}\n\n/**\n * Why trying a Free plan again cannot work this month, or `null` (AGL-3594):\n * the owner's Free allowance left, read off the account month the meter\n * writes net of give-backs, against what a plan of this kind costs at its\n * worst. Read before this step is metered, and the machine gives a refused\n * plan's credits back, so the figure read is the figure left. A read that fails\n * leaves the button on: the reservation still refuses at the wall.\n */\nasync function aiFreePlanRetryRefusal(input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n now: Date\n site: boolean\n}): Promise<string | null> {\n const account = freeAssistAccount(input.org as AssistMeteredOrg | null)\n if (!account?.accountUid) return null\n try {\n // The meter's month key, `YYYY-MM` in UTC (`assistUsageMonth`).\n const month = input.now.toISOString().slice(0, 7)\n const snapshot = await freeAccountUsageRef(input.firestore, account.accountUid, month).get()\n const spent = assistCreditsFromUsd(\n assistSpendAfterReturnsUsd(snapshot.get('estCostUsd'), snapshot.get(ASSIST_RETURNED_USD_FIELD)),\n )\n return aiPlanRetryRefusal({\n creditsLeft: FREE_AI_TASTE_CREDITS_PER_MONTH - spent,\n planCredits: input.site ? AI_FREE_SITE_WORST_CASE_CREDITS.plan : AI_FREE_PAGE_WORST_CASE_CREDITS.plan,\n })\n } catch (error) {\n console.error('ai plan retry allowance read failed', { orgId: input.job.orgId, jobId: input.job.$id, error })\n return null\n }\n}\n\nexport const runAiJobPlanStep = createAiJobPlanStep()\n\n/**\n * Registers the plan step every planned kind runs first, with the least time\n * a plan needs; the plugin's console surface calls it.\n */\nexport function registerAiJobPlan(): void {\n registerAiJobPlanStep(runAiJobPlanStep, { minimumMs: AI_JOB_PLAN_STEP_MINIMUM_MS })\n}\n"],"names":["aiSiteKindOfInputs","createHash","AI_BUILD_PLAN_TOOL","aiBuildPlanToolFor","isAiPlanNewRef","AI_TEMPLATE_SUBJECT_DEFINITIONS","aiTemplateShownTokens","AI_JOB_CREATE_KINDS","AI_JOB_CREATE_NOUNS","AI_PAGE_CREATE_KINDS","aiPagePlanShapeRefusal","AI_PLAN_COMPILED_REPEATS_SENTENCE","AI_PLAN_NO_FORM_SENTENCE","aiPlanCanPlaceForm","aiPlanCapabilitiesForJob","aiPlanCapabilityLines","AI_FREE_SITE_WORST_CASE_CREDITS","AI_SITE_CREATE_KINDS","AI_SITE_FREE_PAGES","AI_SITE_PLAN_MAX_TOKENS","AI_SITE_HOME_BANDS","aiFreeSiteSectionsWithin","aiSiteFullPlanSentence","aiSiteHomeMinSections","aiSiteNameSentence","aiSitePlanIsHome","aiSitePlanShapeRefusal","aiSiteBlogStandInViolations","aiSiteThinHomeViolations","AI_SITE_GALLERY_SENTENCE","aiSiteEmptyGalleryViolations","aiSiteContentPart","AI_GENERATION_MAX_ATTEMPTS","aiPlanFailureCopy","aiPlanRetryRefusal","FREE_AI_TASTE_CREDITS_PER_MONTH","aiDoctrineSystemBlocks","runValidatedGeneration","AI_STEP_TIERS","aiCatalogEntry","aiDefaultModelFor","AI_FREE_PAGE_WORST_CASE_CREDITS","aiPlanEmbedBriefViolations","assistCreditsFromUsd","ASSIST_RETURNED_USD_FIELD","assistSpendAfterReturnsUsd","freeAccountUsageRef","freeAssistAccount","AI_ROUTING_TABLE","aiModelForStep","readSiteInventory","readAiSiteContext","aiInstructionsWithSiteContext","AI_BUILD_CREATE_KINDS","AI_BUILD_STRUCTURAL_OPS","aiBuildPageLimit","aiBuildPlanShapeRefusal","aiBuildOpLines","aiBuildOps","aiJobAdmissionRefusal","readAiPlanCapabilities","AI_JOB_BRIEF_MAX_CHARS","aiJobStepBudget","aiDoctrineReview","aiUnspentOutcome","aiPlanWithDraftIds","AI_JOBS_COLLECTION","registerAiJobPlanStep","AI_JOB_PLAN_INSTRUCTIONS","text","AI_JOB_PLAN_STEP_BUDGET","tier","maxTokens","AI_JOB_PLAN_STEP_MINIMUM_MS","minimumMs","aiJobPlanMaxTokens","model","AI_JOB_PLAN_REVIEW_COPY","aiJobPlanPrompt","job","capabilities","inventory","ops","lines","kind","brief","slice","key","value","Object","entries","inputs","push","String","aiPlanTemplateTokenLines","aiPlanSiteLines","aiPlanBuildLines","join","pages","freeTaste","repeatsCompiled","name","trim","screens","filter","screen","template","starter","find","replaceable","length","page","slug","some","cap","freeSitePages","home","aiSitePlanHomeRule","undefined","across","plansHome","min","label","toLowerCase","layouts","forms","aiSiteThinHomeCheck","rule","answers","plan","aiSiteEmptyGalleryCheck","aiSiteBlogStandInCheck","subject","definition","AI_JOB_PLAN_SCOPES","noun","creates","shapeRefusal","build","options","site","fromEntries","map","planViolations","scope","blog","thinHome","blogStandIn","emptyGallery","message","code","aiPlanLabels","names","Map","rows","components","templates","datasets","collections","row","set","id","refs","reuse","entry","create","duplicateOf","flatMap","layout","sections","section","uses","labels","ref","get","AI_PLAN_REUSE_WINDOW_MS","AI_PLAN_REUSE_CANDIDATES","aiJobPlanKey","input","digest","part","hostId","prompt","system","block","JSON","stringify","tool","update","UNREUSABLE","planMillis","at","proposedAt","Date","getTime","toMillis","aiReusablePlan","candidates","context","floor","now","best","bestAt","candidate","jobId","includes","status","findAiJobsByPlanKey","orgId","firestore","snapshot","collection","doc","where","limit","docs","data","readAiJobPlanCapabilities","org","readAiJobSiteContext","readAiBuildOps","host","aiPlanWithItemCredits","items","item","capability","op","credits","Math","max","estimateCredits","args","createAiJobPlanStep","deps","readInventory","findPlansByKey","readCapabilities","admissionRefusal","readOps","readContext","readSiteContext","signal","modelFor","orgDocument","workspace","siteContext","Promise","all","resolve","instructions","aiSitePlanCapabilities","aiSitePlanModel","route","refusalOnKeep","outcome","refusal","uid","createdBy","error","console","$id","failure","resolved","records","Boolean","dataset","allowed","reused","confirmedAt","confirmedBy","reusedFrom","unspent","review","reason","findings","result","step","messages","role","content","aiSitePlanMaxTokens","thinking","effort","extend","spent","outputs","usage","estCostUsd","stopReason","refused","retryRefusal","aiFreePlanRetryRefusal","uncredited","codes","violations","violation","refunded","detail","left","component","reusableComponents","asked","Number","isInteger","picked","provider","ceiling","free","paid","account","accountUid","month","toISOString","creditsLeft","planCredits","runAiJobPlanStep","registerAiJobPlan"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,UAAU,QAAQ,cAAa;AAExC,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,QAET,4BAAwB;AAE/B,SACEC,+BAA+B,EAC/BC,qBAAqB,QAEhB,mCAA+B;AACtC,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,+BAA2B;AACpF,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,0BAAsB;AACnF,SACEC,iCAAiC,EACjCC,wBAAwB,EACxBC,kBAAkB,EAClBC,wBAAwB,EACxBC,qBAAqB,QAGhB,mCAA+B;AAEtC,SACEC,+BAA+B,EAC/BC,oBAAoB,EACpBC,kBAAkB,EAClBC,uBAAuB,EACvBC,kBAAkB,EAClBC,wBAAwB,EACxBC,sBAAsB,EACtBC,qBAAqB,EACrBC,kBAAkB,EAClBC,gBAAgB,EAChBC,sBAAsB,EACtBC,2BAA2B,EAC3BC,wBAAwB,EACxBC,wBAAwB,EACxBC,4BAA4B,QACvB,0BAAsB;AAC7B,SAASC,iBAAiB,QAAQ,2BAAuB;AACzD,SAASC,0BAA0B,QAAQ,qCAAiC;AAC5E,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,kCAA8B;AACpF,SAASC,+BAA+B,QAAQ,0BAAsB;AACtE,SAASC,sBAAsB,EAAEC,sBAAsB,QAAQ,4BAAwB;AACvF,SAASC,aAAa,EAAEC,cAAc,EAAEC,iBAAiB,QAAQ,0BAAsB;AACvF,SACEC,+BAA+B,EAC/BC,0BAA0B,QAErB,uCAAmC;AAC1C,SAASC,oBAAoB,QAAQ,6BA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