@aglyn/plugins-ai 1.0.0-beta.271 → 1.0.0-beta.272
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/activity/ai-activity-actions.d.ts +4 -3
- package/src/lib/activity/ai-activity-actions.js +3 -0
- package/src/lib/activity/ai-activity-actions.js.map +1 -1
- package/src/lib/components/ai-site-build-page.component.js +18 -0
- package/src/lib/components/ai-site-build-page.component.js.map +1 -1
- package/src/lib/components/ai-site-import-job.component.d.ts +41 -0
- package/src/lib/components/ai-site-import-job.component.js +707 -0
- package/src/lib/components/ai-site-import-job.component.js.map +1 -0
- package/src/lib/components/ai-site-import-start.component.d.ts +64 -0
- package/src/lib/components/ai-site-import-start.component.js +335 -0
- package/src/lib/components/ai-site-import-start.component.js.map +1 -0
- package/src/lib/components/ai-site-ownership-proof.component.d.ts +42 -0
- package/src/lib/components/ai-site-ownership-proof.component.js +353 -0
- package/src/lib/components/ai-site-ownership-proof.component.js.map +1 -0
- package/src/lib/components/ai-site-start-card.component.js +165 -91
- package/src/lib/components/ai-site-start-card.component.js.map +1 -1
- package/src/lib/jobs/ai-job-drafts.d.ts +14 -0
- package/src/lib/jobs/ai-job-drafts.js +24 -0
- package/src/lib/jobs/ai-job-drafts.js.map +1 -1
- package/src/lib/jobs/ai-job-import-step.d.ts +136 -0
- package/src/lib/jobs/ai-job-import-step.js +809 -0
- package/src/lib/jobs/ai-job-import-step.js.map +1 -0
- package/src/lib/jobs/ai-job-page-language.d.ts +39 -1
- package/src/lib/jobs/ai-job-page-language.js +62 -4
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-step.d.ts +2 -2
- package/src/lib/jobs/ai-job-page-step.js +5 -2
- package/src/lib/jobs/ai-job-page-step.js.map +1 -1
- package/src/lib/jobs/ai-job-text-step.d.ts +7 -0
- package/src/lib/jobs/ai-job-text-step.js.map +1 -1
- package/src/lib/jobs/ai-jobs.d.ts +5 -0
- package/src/lib/jobs/ai-jobs.js +15 -3
- package/src/lib/jobs/ai-jobs.js.map +1 -1
- package/src/lib/jobs/ai-layout-owner-photos.d.ts +16 -1
- package/src/lib/jobs/ai-layout-owner-photos.js +47 -0
- package/src/lib/jobs/ai-layout-owner-photos.js.map +1 -1
- package/src/lib/jobs/ai-theme-brand-inputs.d.ts +61 -3
- package/src/lib/jobs/ai-theme-brand-inputs.js +117 -27
- package/src/lib/jobs/ai-theme-brand-inputs.js.map +1 -1
- package/src/lib/model/ai-credit-estimate.d.ts +20 -0
- package/src/lib/model/ai-credit-estimate.js +13 -0
- package/src/lib/model/ai-credit-estimate.js.map +1 -1
- package/src/lib/model/ai-job-activity.d.ts +2 -2
- package/src/lib/model/ai-job-activity.js +6 -4
- package/src/lib/model/ai-job-activity.js.map +1 -1
- package/src/lib/model/ai-job-notice.js +18 -4
- package/src/lib/model/ai-job-notice.js.map +1 -1
- package/src/lib/model/ai-jobs.types.d.ts +29 -2
- package/src/lib/model/ai-jobs.types.js +2 -1
- package/src/lib/model/ai-jobs.types.js.map +1 -1
- package/src/lib/model/ai-site-import-view.d.ts +130 -0
- package/src/lib/model/ai-site-import-view.js +182 -0
- package/src/lib/model/ai-site-import-view.js.map +1 -0
- package/src/lib/model/ai-site-import.d.ts +302 -0
- package/src/lib/model/ai-site-import.js +526 -0
- package/src/lib/model/ai-site-import.js.map +1 -0
- package/src/lib/model/ai-site-start.d.ts +22 -9
- package/src/lib/model/ai-site-start.js +64 -23
- package/src/lib/model/ai-site-start.js.map +1 -1
- package/src/lib/server/ai-jobs-route.js +11 -0
- package/src/lib/server/ai-jobs-route.js.map +1 -1
- package/src/lib/server/ai-site-import-route.d.ts +89 -0
- package/src/lib/server/ai-site-import-route.js +356 -0
- package/src/lib/server/ai-site-import-route.js.map +1 -0
- package/src/lib/server.js +14 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/site-import/fixtures/site-import-crawl-recordings.d.ts +45 -0
- package/src/lib/site-import/fixtures/site-import-crawl-recordings.js +313 -0
- package/src/lib/site-import/fixtures/site-import-crawl-recordings.js.map +1 -0
- package/src/lib/site-import/fixtures/site-import-wave-recordings.d.ts +50 -0
- package/src/lib/site-import/fixtures/site-import-wave-recordings.js +217 -0
- package/src/lib/site-import/fixtures/site-import-wave-recordings.js.map +1 -0
- package/src/lib/site-import/site-import-crawl.d.ts +163 -0
- package/src/lib/site-import/site-import-crawl.js +467 -0
- package/src/lib/site-import/site-import-crawl.js.map +1 -0
- package/src/lib/site-import/site-import-flag.d.ts +23 -0
- package/src/lib/site-import/site-import-flag.js +23 -0
- package/src/lib/site-import/site-import-flag.js.map +1 -0
- package/src/lib/site-import/site-import-html.d.ts +94 -0
- package/src/lib/site-import/site-import-html.js +462 -0
- package/src/lib/site-import/site-import-html.js.map +1 -0
- package/src/lib/site-import/site-import-images.d.ts +54 -0
- package/src/lib/site-import/site-import-images.js +204 -0
- package/src/lib/site-import/site-import-images.js.map +1 -0
- package/src/lib/site-import/site-import-page.d.ts +48 -0
- package/src/lib/site-import/site-import-page.js +150 -0
- package/src/lib/site-import/site-import-page.js.map +1 -0
- package/src/lib/site-import/site-import-review.d.ts +40 -0
- package/src/lib/site-import/site-import-review.js +149 -0
- package/src/lib/site-import/site-import-review.js.map +1 -0
- package/src/lib/site-import/site-import-robots.d.ts +52 -0
- package/src/lib/site-import/site-import-robots.js +126 -0
- package/src/lib/site-import/site-import-robots.js.map +1 -0
|
@@ -186,18 +186,29 @@ export declare function aiSiteStartAnswersFromInputs(inputs: Readonly<Record<str
|
|
|
186
186
|
}): AiSiteStartAnswers | null;
|
|
187
187
|
/**
|
|
188
188
|
* The questions' answers for a site staff are building for a client: what
|
|
189
|
-
* the business does is the kind of site, and
|
|
190
|
-
*
|
|
191
|
-
*
|
|
192
|
-
*
|
|
189
|
+
* the business does is the kind of site, and the details the intake holds
|
|
190
|
+
* fill the Details step's own fields (AGL-3979, AGL-3995): the phone, the
|
|
191
|
+
* email, the towns as the areas it serves and the hours, each held to that
|
|
192
|
+
* detail's own rule, so one the Details step would refuse is left empty
|
|
193
|
+
* there. Every other answer keeps its default, which the review shows to
|
|
194
|
+
* change. The intake, a refused detail included, also reaches the job
|
|
195
|
+
* through {@link aiSiteStartClientInputs} and {@link aiSiteStartClientBrief}.
|
|
193
196
|
*/
|
|
194
197
|
export declare function aiSiteStartAnswersFromClientBuild(intake: ClientBuildIntake): AiSiteStartAnswers;
|
|
195
198
|
/**
|
|
196
199
|
* The per-site inputs the intake fills, which the guided start's own
|
|
197
200
|
* questions leave empty: the business's name for the header and footer, and
|
|
198
201
|
* the towns it serves as its place.
|
|
202
|
+
*
|
|
203
|
+
* The towns are the place only while no address is given. The Entity reads
|
|
204
|
+
* `city` as the address's own locality wherever there is a street or a
|
|
205
|
+
* postal code (`aiSiteEntity`), so once the answers carry either, `city` is
|
|
206
|
+
* the city the Details step was given with that address, never the towns
|
|
207
|
+
* (AGL-3995). The intake asks no address, so today that is the Details step's
|
|
208
|
+
* own, typed on the review; the towns still reach the site as the areas it
|
|
209
|
+
* serves.
|
|
199
210
|
*/
|
|
200
|
-
export declare function aiSiteStartClientInputs(intake: ClientBuildIntake): Pick<AiSiteJobInputs, 'businessName' | 'city'>;
|
|
211
|
+
export declare function aiSiteStartClientInputs(intake: ClientBuildIntake, answers?: Pick<AiSiteStartAnswers, 'street' | 'postalCode' | 'city'> | null): Pick<AiSiteJobInputs, 'businessName' | 'city'>;
|
|
201
212
|
/**
|
|
202
213
|
* The intake as sentences added to the brief: how to reach the business and
|
|
203
214
|
* when it is open, which the site should say where a visitor looks for them,
|
|
@@ -206,9 +217,11 @@ export declare function aiSiteStartClientInputs(intake: ClientBuildIntake): Pick
|
|
|
206
217
|
*/
|
|
207
218
|
export declare function aiSiteStartClientBrief(intake: ClientBuildIntake): string;
|
|
208
219
|
/**
|
|
209
|
-
* What the review says the client build adds
|
|
210
|
-
* used without it being asked again:
|
|
211
|
-
*
|
|
212
|
-
*
|
|
220
|
+
* What the review says the client build adds beyond its own rows, so staff
|
|
221
|
+
* see the intake is used without it being asked again: the business's name
|
|
222
|
+
* and the owner's own words, which no row shows. The phone, email, towns and
|
|
223
|
+
* hours are the review's Details rows already (AGL-3995), so the note does
|
|
224
|
+
* not say them twice: "Also from the client's details: Harbor Plumbing and
|
|
225
|
+
* the owner's own words."
|
|
213
226
|
*/
|
|
214
227
|
export declare function aiSiteStartClientNote(intake: ClientBuildIntake): string;
|
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
|
-
import {
|
|
17
|
+
import { weeklyHoursFromText, weeklyHoursToText } from "@aglyn/shared-ui-jsx/utils/weekly-hours";
|
|
18
|
+
import { AI_SITE_DETAIL_KEYS, AI_SITE_NO_DETAILS, aiSiteDetailProblem, aiSiteDetailsOf } from "./ai-site-details.js";
|
|
18
19
|
import { aiSiteKind, aiSiteKindFor } from "./ai-site-kinds.js";
|
|
19
20
|
import { AI_SITE_INSPIRATION_INPUT, aiSiteInspirationInput, aiSiteInspirationLimit, aiSiteInspirationRefusal, aiSiteInspirationUrl } from "./ai-site-inspiration.js";
|
|
20
21
|
import { AI_SITE_INPUT_MAX_CHARS, AI_SITE_SUBMISSIONS, aiSitePagesBand } from "./ai-site-job.js";
|
|
@@ -304,25 +305,72 @@ import { AI_SITE_INPUT_MAX_CHARS, AI_SITE_SUBMISSIONS, aiSitePagesBand } from ".
|
|
|
304
305
|
const space = cut.lastIndexOf(' ');
|
|
305
306
|
return (space > max / 2 ? cut.slice(0, space) : cut).trim();
|
|
306
307
|
}
|
|
308
|
+
/** A time with am or pm: "9am", "5:30 pm", "12 a.m.". */ const TWELVE_HOUR_TIME = /\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?(?![a-z])/gi;
|
|
309
|
+
/**
|
|
310
|
+
* The hours an owner gave, in the shape the Details step's hours picker
|
|
311
|
+
* writes (`Tu-Sa 09:00-17:00`, one set of days a line), so the plan reads
|
|
312
|
+
* them as it reads hours picked there. A time with am or pm is the time it
|
|
313
|
+
* names, "to" joins a range as a dash does, and days with their hours may be
|
|
314
|
+
* set apart by a comma, a semicolon or a line. Whatever still does not read
|
|
315
|
+
* as hours — "8–5", "Sat by appointment" — is left out rather than guessed at.
|
|
316
|
+
*/ function clientBuildHours(hours) {
|
|
317
|
+
const lines = hours.replace(TWELVE_HOUR_TIME, (time, hour, minutes, half)=>{
|
|
318
|
+
const h = Number(hour);
|
|
319
|
+
if (h < 1 || h > 12) return time;
|
|
320
|
+
const clock = h % 12 + (half.toLowerCase() === 'p' ? 12 : 0);
|
|
321
|
+
return `${String(clock).padStart(2, '0')}:${minutes != null ? minutes : '00'}`;
|
|
322
|
+
}).replace(/\s+to\s+/gi, '-').replace(/(\d{1,2}:\d{2})\s*,\s*/g, '$1\n').replace(/;/g, '\n');
|
|
323
|
+
const week = weeklyHoursFromText(lines).hours;
|
|
324
|
+
return week.some((day)=>day.length) ? weeklyHoursToText(week) : '';
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* The towns an intake serves, one a line, as the Details step's "Areas you
|
|
328
|
+
* serve" holds them: "Austin, Round Rock and Pflugerville" is three.
|
|
329
|
+
*/ function clientBuildServiceArea(towns) {
|
|
330
|
+
return towns.split(/\r?\n|[,;]|\s+(?:and|&)\s+/i).map((town)=>town.trim()).filter(Boolean).join('\n');
|
|
331
|
+
}
|
|
307
332
|
/**
|
|
308
333
|
* The questions' answers for a site staff are building for a client: what
|
|
309
|
-
* the business does is the kind of site, and
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
*
|
|
334
|
+
* the business does is the kind of site, and the details the intake holds
|
|
335
|
+
* fill the Details step's own fields (AGL-3979, AGL-3995): the phone, the
|
|
336
|
+
* email, the towns as the areas it serves and the hours, each held to that
|
|
337
|
+
* detail's own rule, so one the Details step would refuse is left empty
|
|
338
|
+
* there. Every other answer keeps its default, which the review shows to
|
|
339
|
+
* change. The intake, a refused detail included, also reaches the job
|
|
340
|
+
* through {@link aiSiteStartClientInputs} and {@link aiSiteStartClientBrief}.
|
|
313
341
|
*/ export function aiSiteStartAnswersFromClientBuild(intake) {
|
|
342
|
+
const details = aiSiteDetailsOf({
|
|
343
|
+
phone: intake.phone,
|
|
344
|
+
email: intake.email,
|
|
345
|
+
serviceArea: clientBuildServiceArea(intake.towns),
|
|
346
|
+
hours: clientBuildHours(intake.hours)
|
|
347
|
+
});
|
|
314
348
|
return _extends({}, AI_SITE_START_ANSWERS, {
|
|
315
|
-
siteType: bounded(intake.whatTheyDo, AI_SITE_INPUT_MAX_CHARS)
|
|
349
|
+
siteType: bounded(intake.whatTheyDo, AI_SITE_INPUT_MAX_CHARS),
|
|
350
|
+
phone: details.phone,
|
|
351
|
+
email: details.email,
|
|
352
|
+
serviceArea: details.serviceArea,
|
|
353
|
+
hours: details.hours
|
|
316
354
|
});
|
|
317
355
|
}
|
|
318
356
|
/**
|
|
319
357
|
* The per-site inputs the intake fills, which the guided start's own
|
|
320
358
|
* questions leave empty: the business's name for the header and footer, and
|
|
321
359
|
* the towns it serves as its place.
|
|
322
|
-
|
|
360
|
+
*
|
|
361
|
+
* The towns are the place only while no address is given. The Entity reads
|
|
362
|
+
* `city` as the address's own locality wherever there is a street or a
|
|
363
|
+
* postal code (`aiSiteEntity`), so once the answers carry either, `city` is
|
|
364
|
+
* the city the Details step was given with that address, never the towns
|
|
365
|
+
* (AGL-3995). The intake asks no address, so today that is the Details step's
|
|
366
|
+
* own, typed on the review; the towns still reach the site as the areas it
|
|
367
|
+
* serves.
|
|
368
|
+
*/ export function aiSiteStartClientInputs(intake, answers) {
|
|
369
|
+
var _ref;
|
|
370
|
+
const addressed = Boolean((answers == null ? void 0 : answers.street.trim()) || (answers == null ? void 0 : answers.postalCode.trim()));
|
|
323
371
|
return {
|
|
324
372
|
businessName: bounded(intake.businessName, AI_SITE_INPUT_MAX_CHARS),
|
|
325
|
-
city: bounded(intake.towns, AI_SITE_INPUT_MAX_CHARS)
|
|
373
|
+
city: bounded(addressed ? (_ref = answers == null ? void 0 : answers.city) != null ? _ref : '' : intake.towns, AI_SITE_INPUT_MAX_CHARS)
|
|
326
374
|
};
|
|
327
375
|
}
|
|
328
376
|
/**
|
|
@@ -352,26 +400,19 @@ import { AI_SITE_INPUT_MAX_CHARS, AI_SITE_SUBMISSIONS, aiSitePagesBand } from ".
|
|
|
352
400
|
return sentences.join(' ');
|
|
353
401
|
}
|
|
354
402
|
/**
|
|
355
|
-
* What the review says the client build adds
|
|
356
|
-
* used without it being asked again:
|
|
357
|
-
*
|
|
358
|
-
*
|
|
403
|
+
* What the review says the client build adds beyond its own rows, so staff
|
|
404
|
+
* see the intake is used without it being asked again: the business's name
|
|
405
|
+
* and the owner's own words, which no row shows. The phone, email, towns and
|
|
406
|
+
* hours are the review's Details rows already (AGL-3995), so the note does
|
|
407
|
+
* not say them twice: "Also from the client's details: Harbor Plumbing and
|
|
408
|
+
* the owner's own words."
|
|
359
409
|
*/ export function aiSiteStartClientNote(intake) {
|
|
360
|
-
const name = intake.businessName.trim();
|
|
361
|
-
const towns = intake.towns.trim();
|
|
362
|
-
const reach = [
|
|
363
|
-
intake.phone.trim() ? 'phone' : '',
|
|
364
|
-
intake.email.trim() ? 'email' : '',
|
|
365
|
-
intake.hours.trim() ? 'hours' : ''
|
|
366
|
-
].filter(Boolean);
|
|
367
410
|
const parts = [
|
|
368
|
-
|
|
369
|
-
reach.length ? `its ${reach.length > 1 ? `${reach.slice(0, -1).join(', ')} and ${reach[reach.length - 1]}` : reach[0]}` : '',
|
|
411
|
+
intake.businessName.trim(),
|
|
370
412
|
intake.ownerWords.trim() ? "the owner's own words" : ''
|
|
371
413
|
].filter(Boolean);
|
|
372
414
|
if (!parts.length) return 'Built from the client’s details.';
|
|
373
|
-
|
|
374
|
-
return `Also from the client’s details: ${list}.`;
|
|
415
|
+
return `Also from the client’s details: ${parts.join(' and ')}.`;
|
|
375
416
|
}
|
|
376
417
|
|
|
377
418
|
//# sourceMappingURL=ai-site-start.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-site-start.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ClientBuildIntake } from '@aglyn/aglyn/app-utils/client-build'\nimport {\n AI_SITE_DETAIL_KEYS,\n AI_SITE_NO_DETAILS,\n aiSiteDetailProblem,\n type AiSiteDetailKey,\n type AiSiteDetails,\n} from './ai-site-details'\nimport { aiSiteKind, aiSiteKindFor, type AiSiteKind } from './ai-site-kinds'\nimport {\n AI_SITE_INSPIRATION_INPUT,\n aiSiteInspirationInput,\n aiSiteInspirationLimit,\n aiSiteInspirationRefusal,\n aiSiteInspirationUrl,\n} from './ai-site-inspiration'\nimport {\n AI_SITE_INPUT_MAX_CHARS,\n AI_SITE_SUBMISSIONS,\n aiSitePagesBand,\n type AiSiteJobInputs,\n type AiSiteSubmissions,\n} from './ai-site-job'\n\n/**\n * The guided start (AGL-2918): the questions a person answers on a site they\n * have just made, and the site job those answers become.\n *\n * A scaffold already exists — the `site` job plans four to eight pages, a\n * layout, a contact form, a palette and a welcome email, and builds every one\n * of them as a draft. What it had no way in through was a brief: somebody had\n * to know what to write, on a site where nothing has happened yet. So this\n * module is the QUESTIONS, and nothing else: what is asked, what an answer may\n * be, and how a set of answers becomes the brief and the scalar inputs the\n * `site` door already takes.\n *\n * ── Answering is never the way out ───────────────────────────────────────\n *\n * There is no answer here that means \"not this\". The way past the questions\n * is the `hostFirstRun` zone's own `startBlank`, which is drawn beside them\n * from the first one and creates nothing at all — see the zone in\n * `CONSOLE_WIDGET_SLOTS`. Putting the exit inside the question set would make\n * leaving a thing you answer your way to, and it is not.\n *\n * ── Every answer but the first is optional ───────────────────────────────\n *\n * Only what a site is FOR has no default worth guessing. The audience narrows\n * the copy, the example steers the shape, the page count and the welcome\n * email are defaults a person may change — so a person who types six words\n * and confirms gets a planned site, and the rest of the questions are there\n * for the person who wants to answer them.\n *\n * Pure: shapes, vocabularies and two string builders. No React, no network,\n * and no import of the starter catalog — {@link AI_SITE_START_EXAMPLES} names\n * the starters rather than reading them, so the console does not carry a\n * catalog of node maps to draw five cards. `ai-site-start.spec.ts` holds the\n * two lists to each other.\n */\n\n/** A worked example a person picks to steer what the site should look like. */\nexport interface AiSiteStartExample {\n /** A `STARTER_TEMPLATES` id, which is a persisted identifier. */\n id: string\n /** The starter as its card names it. */\n label: string\n /** The starter's category, which is how the examples group. */\n category: string\n /** What the example is, in one line a person reads before picking it. */\n blurb: string\n}\n\n/**\n * The examples the start offers, in the order they are shown. The platform's\n * own starter sites: a person who has no words for what they want has seen\n * these five shapes before, and picking one says more than a sentence would.\n */\nexport const AI_SITE_START_EXAMPLES: readonly AiSiteStartExample[] = [\n {\n id: 'business',\n label: 'Business',\n category: 'Business',\n blurb: 'A home page led by what you do, an about page and a contact page',\n },\n {\n id: 'landing',\n label: 'Landing Page',\n category: 'Marketing',\n blurb: 'One page that leads to one action, with the reasons to take it',\n },\n {\n id: 'portfolio',\n label: 'Portfolio',\n category: 'Personal',\n blurb: 'An introduction, a grid of work and a way to get in touch',\n },\n {\n id: 'physical-shop',\n label: 'Shop (physical products)',\n category: 'Commerce',\n blurb: 'Featured products, a shop to browse, and a cart',\n },\n {\n id: 'digital-shop',\n label: 'Shop (digital products)',\n category: 'Commerce',\n blurb: 'Downloads up front, a shop to browse, and a cart',\n },\n]\n\n/**\n * Kinds of site offered beside the first question's box, so answering it can\n * be a tap. They fill the box rather than replacing it: what somebody is\n * building is theirs to say, and a list of eight is a list somebody is not on.\n */\nexport const AI_SITE_START_TYPES: readonly string[] = [\n 'a local service business',\n 'a restaurant or cafe',\n 'a professional practice',\n 'a trades business',\n 'a shop',\n 'a nonprofit',\n 'a personal portfolio',\n 'an event',\n]\n\n/**\n * What a person answered; the shape the card holds and the brief is built from.\n *\n * Beside the answers each step asks, the business details its \"More details\"\n * offers (AGL-3979, `AiSiteDetails`): every one optional and `''` until given,\n * the phone number and email on the Details step itself.\n */\nexport interface AiSiteStartAnswers extends AiSiteDetails {\n /** What kind of site this is. The one answer with no default. */\n siteType: string\n /** Who the site is for; empty when they did not say. */\n audience: string\n /** The example they liked, by {@link AiSiteStartExample.id}; `null` for none. */\n example: string | null\n /**\n * The kind of site they picked (AGL-3660), by its `AI_SITE_KINDS` id;\n * `null` until they pick one, when the kind their first answer suggests is\n * the one used ({@link aiSiteStartKind}).\n */\n kind: string | null\n /** How many pages to plan. */\n pages: number\n /** Where the contact form's submissions go. */\n submissions: AiSiteSubmissions\n /** Whether the scaffold also drafts a welcome email. */\n welcomeEmail: boolean\n /** The city or town the business is in (AGL-3979); empty when they did not say. */\n city: string\n /** The brand color, as a six-digit hex (AGL-3979); empty for the style's own. */\n brand: string\n /**\n * The sites they like (AGL-3975), as typed, one a field; absent or empty\n * for none. Asked only while `release_ai_site_inspiration` is on.\n */\n inspiration?: string[]\n}\n\n/**\n * What the questions start on. Five pages because it is the middle of the\n * band the scaffold builds, a welcome email because the scaffold drafts one\n * unless it is told not to, and the Inbox because it is what every submission\n * does anyway — filing a lead as well is the addition, and an addition is the\n * thing a person should have to choose.\n */\nexport const AI_SITE_START_ANSWERS: AiSiteStartAnswers = {\n siteType: '',\n audience: '',\n example: null,\n kind: null,\n pages: 5,\n submissions: 'inbox',\n welcomeEmail: true,\n city: '',\n brand: '',\n ...AI_SITE_NO_DETAILS,\n}\n\n/** The answers a person may give beyond the ones each step asks, by key (AGL-3979). */\nexport type AiSiteStartExtraKey = AiSiteDetailKey | 'city' | 'brand'\n\n/** Every extra, in the order the review lists them. */\nexport const AI_SITE_START_EXTRA_KEYS: readonly AiSiteStartExtraKey[] = [\n 'phone',\n 'email',\n 'tagline',\n 'founded',\n 'serviceArea',\n 'priceRange',\n 'languages',\n 'brand',\n 'street',\n 'city',\n 'region',\n 'postalCode',\n 'country',\n 'hours',\n 'social',\n]\n\n/** What is wrong with one extra, worded for beside its field; `null` when it may be used. */\nexport function aiSiteStartExtraProblem(\n key: AiSiteStartExtraKey,\n value: string,\n): { code: 'too_long' | 'invalid'; message: string } | null {\n if (key === 'city' || key === 'brand') {\n return value.trim().length > AI_SITE_INPUT_MAX_CHARS\n ? { code: 'too_long', message: `Keep this under ${AI_SITE_INPUT_MAX_CHARS} characters.` }\n : null\n }\n return aiSiteDetailProblem(key, value)\n}\n\n/** The extras a person gave, in the review's order: what \"More details\" was used for. */\nexport function aiSiteStartExtrasGiven(answers: AiSiteStartAnswers): AiSiteStartExtraKey[] {\n return AI_SITE_START_EXTRA_KEYS.filter((key) => (answers[key] ?? '').trim() !== '')\n}\n\n/** The kind of site the answers pick, else the one what the site is and who it is for suggest. */\nexport function aiSiteStartKind(\n answers: Pick<AiSiteStartAnswers, 'kind' | 'siteType'> & Partial<Pick<AiSiteStartAnswers, 'audience'>>,\n): AiSiteKind {\n return aiSiteKind(answers.kind) ?? aiSiteKindFor(answers.siteType, answers.audience ?? '')\n}\n\n/** The example an answer names, or `null` when it names none this list knows. */\nexport function aiSiteStartExample(\n answers: AiSiteStartAnswers,\n): AiSiteStartExample | null {\n if (!answers.example) return null\n return AI_SITE_START_EXAMPLES.find((entry) => entry.id === answers.example) ?? null\n}\n\n/**\n * Why these answers cannot start a site, in a sentence a person reads; `null`\n * when they can. The door's own parser is what actually admits the job — this\n * is what the card says before it asks for one.\n */\nexport function aiSiteStartRefusal(\n answers: AiSiteStartAnswers,\n options: { freeTaste?: boolean } = {},\n): string | null {\n // The workspace's own band (AGL-3594): one or two pages on the Free taste.\n const band = aiSitePagesBand(options.freeTaste)\n const siteType = answers.siteType.trim()\n if (!siteType) return 'Say what kind of site this is.'\n if (siteType.length > AI_SITE_INPUT_MAX_CHARS) {\n return `Keep what kind of site this is under ${AI_SITE_INPUT_MAX_CHARS} characters.`\n }\n if (answers.audience.trim().length > AI_SITE_INPUT_MAX_CHARS) {\n return `Keep who the site is for under ${AI_SITE_INPUT_MAX_CHARS} characters.`\n }\n if (!Number.isInteger(answers.pages) || answers.pages < band.min || answers.pages > band.max) {\n return `A site is planned with ${band.min} to ${band.max} pages.`\n }\n if (answers.example !== null && !aiSiteStartExample(answers)) {\n return 'Pick one of the examples, or none of them.'\n }\n if (!(AI_SITE_SUBMISSIONS as readonly string[]).includes(answers.submissions)) {\n return 'Say where the contact form’s submissions go.'\n }\n for (const key of AI_SITE_START_EXTRA_KEYS) {\n const problem = aiSiteStartExtraProblem(key, answers[key] ?? '')\n if (problem) return problem.message\n }\n return aiSiteStartInspirationRefusal(answers, options)\n}\n\n/** The sites they typed, without the empty fields. */\nexport function aiSiteStartInspirationTyped(answers: Pick<AiSiteStartAnswers, 'inspiration'>): string[] {\n return (answers.inspiration ?? []).map((entry) => entry.trim()).filter(Boolean)\n}\n\n/** Why the sites they like cannot go forward, as the door would refuse them; `null` when they can. */\nexport function aiSiteStartInspirationRefusal(\n answers: Pick<AiSiteStartAnswers, 'inspiration'>,\n options: { freeTaste?: boolean } = {},\n): string | null {\n const typed = aiSiteStartInspirationTyped(answers)\n if (typed.some((entry) => !aiSiteInspirationUrl(entry))) {\n return 'Give each site you like as its https address, like https://example.com.'\n }\n return aiSiteInspirationRefusal(typed, options.freeTaste)\n}\n\n/**\n * The answers as the brief the `site` job is created with: the plan step reads\n * it as the person's own words, so it says what they said and asks for nothing\n * they did not.\n */\nexport function aiSiteStartBrief(answers: AiSiteStartAnswers): string {\n const siteType = answers.siteType.trim()\n const audience = answers.audience.trim()\n const example = aiSiteStartExample(answers)\n const sentences = [\n `A ${answers.pages}-page website for ${siteType}.`,\n ]\n if (audience) sentences.push(`It is for ${audience}.`)\n if (example) {\n sentences.push(\n `Follow the shape of the ${example.label} starter: ${example.blurb.toLowerCase()}.`,\n )\n }\n // The kind they picked, or the one their answer suggests (AGL-3660).\n sentences.push(`Make it a ${aiSiteStartKind(answers).label.toLowerCase()} site.`)\n // The form on the page a visitor opens to get in touch, never every page's\n // last band (AGL-3899): \"on the page that asks to be contacted\" read as\n // the home's closing band on 16 of the 22 newest production starts.\n sentences.push(\n answers.pages === 1\n ? 'Plan the page around what a visitor comes to do, with a contact form on it.'\n : 'Plan a page for each thing a visitor comes to do, with the contact form on the page a visitor opens to get in touch.',\n )\n if (audience) {\n // Said of the FORM as well as of the copy: who fills a form in is what\n // decides which fields it asks for, and a brief that named the audience\n // once, in a sentence about the pages, left the form to guess.\n sentences.push(`Ask the contact form for what ${audience} would be asked for.`)\n }\n return sentences.join(' ')\n}\n\n/**\n * The answers as the `site` job's scalar inputs. Read by the door's\n * {@link parseAiSiteJobInputs}, and put in front of the model one per line by\n * the plan step, which is how the audience and the example reach the plan\n * without a prompt of their own.\n *\n * The per-site variables an agency batch fills — the business name, the city,\n * the brand — are left empty here: the questions never ask them. The name is\n * the site's own, and the create door fills it from the site\n * (`aiJobAdmittedInputs`, AGL-3596) when the job is started — a job that\n * reached the model with no name had the model invent one for its header and\n * footer.\n */\nexport function aiSiteStartInputs(\n answers: AiSiteStartAnswers,\n): Omit<AiSiteJobInputs, 'batchId' | 'inspiration' | AiSiteDetailKey> & Partial<AiSiteDetails> & { inspiration?: string } {\n const example = aiSiteStartExample(answers)\n const kind = aiSiteStartKind(answers)\n // The details are sent only where given (AGL-3979): the plan step lists\n // every scalar input on a line of its own, and a start without them is\n // asked exactly what it was asked before.\n const details: Partial<AiSiteDetails> = {}\n for (const key of AI_SITE_DETAIL_KEYS) {\n const value = (answers[key] ?? '').trim()\n if (value) details[key] = value\n }\n // The sites they like travel only when there are some (AGL-3975), so a\n // start without them asks for exactly what it always did.\n const inspiration = aiSiteInspirationInput(aiSiteStartInspirationTyped(answers))\n return {\n businessType: answers.siteType.trim(),\n audience: answers.audience.trim(),\n starter: example?.id ?? kind.starter,\n siteKind: kind.id,\n pages: answers.pages,\n businessName: '',\n city: (answers.city ?? '').trim(),\n brand: (answers.brand ?? '').trim(),\n submissions: answers.submissions,\n welcomeEmail: answers.welcomeEmail,\n ...details,\n ...(inspiration ? { [AI_SITE_INSPIRATION_INPUT]: inspiration } : {}),\n }\n}\n\n/** The site inputs a guided start's answers become, by name: what a summary carries back (AGL-3596). */\nexport const AI_SITE_START_INPUT_KEYS = [\n 'businessType',\n 'audience',\n 'starter',\n 'siteKind',\n 'pages',\n 'businessName',\n 'city',\n 'brand',\n 'submissions',\n 'welcomeEmail',\n ...AI_SITE_DETAIL_KEYS,\n AI_SITE_INSPIRATION_INPUT,\n] as const\n\n/** A site job's scalar inputs, and nothing else its inputs carry; `null` when it has none. */\nexport function aiSiteStartInputsOf(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n): Record<string, unknown> | null {\n if (!inputs) return null\n const kept: Record<string, unknown> = {}\n for (const key of AI_SITE_START_INPUT_KEYS) {\n const value = inputs[key]\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') kept[key] = value\n }\n return Object.keys(kept).length ? kept : null\n}\n\n/**\n * A failed start's answers, back as the questions hold them (AGL-3596), so\n * Try again reopens the guided start filled in for the person to adjust:\n * the inverse of {@link aiSiteStartInputs}. Read defensively — an answer the\n * questions no longer offer goes back to its default — and held to the\n * workspace's page band. `null` when the inputs say no kind of site at all.\n */\nexport function aiSiteStartAnswersFromInputs(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n options: { freeTaste?: boolean } = {},\n): AiSiteStartAnswers | null {\n const text = (key: string) => (typeof inputs?.[key] === 'string' ? (inputs[key] as string).trim() : '')\n const siteType = text('businessType')\n if (!siteType) return null\n const band = aiSitePagesBand(options.freeTaste)\n const pages = typeof inputs?.['pages'] === 'number' ? Math.round(inputs['pages'] as number) : AI_SITE_START_ANSWERS.pages\n const starter = text('starter')\n const submissions = text('submissions')\n return {\n siteType,\n audience: text('audience'),\n example: AI_SITE_START_EXAMPLES.some((entry) => entry.id === starter) ? starter : null,\n kind: aiSiteKind(text('siteKind'))?.id ?? null,\n pages: Math.min(band.max, Math.max(band.min, pages)),\n submissions: (AI_SITE_SUBMISSIONS as readonly string[]).includes(submissions)\n ? (submissions as AiSiteSubmissions)\n : AI_SITE_START_ANSWERS.submissions,\n welcomeEmail: options.freeTaste ? false : inputs?.['welcomeEmail'] !== false,\n city: text('city'),\n brand: text('brand'),\n ...(Object.fromEntries(AI_SITE_DETAIL_KEYS.map((key) => [key, text(key)])) as unknown as AiSiteDetails),\n // The sites they liked come back as typed, within the workspace's limit (AGL-3975).\n ...(text(AI_SITE_INSPIRATION_INPUT)\n ? { inspiration: text(AI_SITE_INSPIRATION_INPUT).split(/\\s+/).filter(Boolean).slice(0, aiSiteInspirationLimit(options.freeTaste)) }\n : {}),\n }\n}\n\n// ── A build staff run for a client (AGL-3958) ───────────────────────────────\n\n/** Shortens an answer to what a scalar input admits, on a word where it can. */\nfunction bounded(value: string, max: number): string {\n const trimmed = value.trim().replace(/\\s+/g, ' ')\n if (trimmed.length <= max) return trimmed\n const cut = trimmed.slice(0, max)\n const space = cut.lastIndexOf(' ')\n return (space > max / 2 ? cut.slice(0, space) : cut).trim()\n}\n\n/**\n * The questions' answers for a site staff are building for a client: what\n * the business does is the kind of site, and every other answer keeps its\n * default, which the review shows to change. The rest of the intake is not an\n * answer to these questions; it reaches the job through\n * {@link aiSiteStartClientInputs} and {@link aiSiteStartClientBrief}.\n */\nexport function aiSiteStartAnswersFromClientBuild(intake: ClientBuildIntake): AiSiteStartAnswers {\n return {\n ...AI_SITE_START_ANSWERS,\n siteType: bounded(intake.whatTheyDo, AI_SITE_INPUT_MAX_CHARS),\n }\n}\n\n/**\n * The per-site inputs the intake fills, which the guided start's own\n * questions leave empty: the business's name for the header and footer, and\n * the towns it serves as its place.\n */\nexport function aiSiteStartClientInputs(\n intake: ClientBuildIntake,\n): Pick<AiSiteJobInputs, 'businessName' | 'city'> {\n return {\n businessName: bounded(intake.businessName, AI_SITE_INPUT_MAX_CHARS),\n city: bounded(intake.towns, AI_SITE_INPUT_MAX_CHARS),\n }\n}\n\n/**\n * The intake as sentences added to the brief: how to reach the business and\n * when it is open, which the site should say where a visitor looks for them,\n * and the owner's own words, quoted, which the copy should sound like. Empty\n * answers say nothing.\n */\nexport function aiSiteStartClientBrief(intake: ClientBuildIntake): string {\n const name = intake.businessName.trim()\n const towns = intake.towns.trim()\n const phone = intake.phone.trim()\n const email = intake.email.trim()\n const hours = intake.hours.trim()\n const words = intake.ownerWords.trim().replace(/\\s+/g, ' ')\n const sentences: string[] = []\n if (name) sentences.push(`The business is called ${name}.`)\n if (towns) sentences.push(`It serves ${towns}.`)\n const contact = [phone ? `call ${phone}` : '', email ? `email ${email}` : ''].filter(Boolean)\n if (contact.length) {\n sentences.push(`Visitors reach it to ${contact.join(' or ')}; say so wherever the site tells them how to get in touch.`)\n }\n if (hours) sentences.push(`Its hours are ${hours}.`)\n if (words) sentences.push(`In the owner's own words: \"${words}\" Write the copy so it sounds like them.`)\n return sentences.join(' ')\n}\n\n/**\n * What the review says the client build adds, so staff see the intake is\n * used without it being asked again: \"Also from the client's details:\n * Harbor Plumbing, serving Austin, its phone, email and hours, and the\n * owner's own words.\"\n */\nexport function aiSiteStartClientNote(intake: ClientBuildIntake): string {\n const name = intake.businessName.trim()\n const towns = intake.towns.trim()\n const reach = [\n intake.phone.trim() ? 'phone' : '',\n intake.email.trim() ? 'email' : '',\n intake.hours.trim() ? 'hours' : '',\n ].filter(Boolean)\n const parts = [\n name && towns ? `${name}, serving ${towns}` : name || (towns ? `serving ${towns}` : ''),\n reach.length ? `its ${reach.length > 1 ? `${reach.slice(0, -1).join(', ')} and ${reach[reach.length - 1]}` : reach[0]}` : '',\n intake.ownerWords.trim() ? \"the owner's own words\" : '',\n ].filter(Boolean)\n if (!parts.length) return 'Built from the client’s details.'\n const list = parts.length > 1 ? `${parts.slice(0, -1).join(', ')}, and ${parts[parts.length - 1]}` : parts[0]\n return `Also from the client’s details: ${list}.`\n}\n"],"names":["AI_SITE_DETAIL_KEYS","AI_SITE_NO_DETAILS","aiSiteDetailProblem","aiSiteKind","aiSiteKindFor","AI_SITE_INSPIRATION_INPUT","aiSiteInspirationInput","aiSiteInspirationLimit","aiSiteInspirationRefusal","aiSiteInspirationUrl","AI_SITE_INPUT_MAX_CHARS","AI_SITE_SUBMISSIONS","aiSitePagesBand","AI_SITE_START_EXAMPLES","id","label","category","blurb","AI_SITE_START_TYPES","AI_SITE_START_ANSWERS","siteType","audience","example","kind","pages","submissions","welcomeEmail","city","brand","AI_SITE_START_EXTRA_KEYS","aiSiteStartExtraProblem","key","value","trim","length","code","message","aiSiteStartExtrasGiven","answers","filter","aiSiteStartKind","aiSiteStartExample","find","entry","aiSiteStartRefusal","options","band","freeTaste","Number","isInteger","min","max","includes","problem","aiSiteStartInspirationRefusal","aiSiteStartInspirationTyped","inspiration","map","Boolean","typed","some","aiSiteStartBrief","sentences","push","toLowerCase","join","aiSiteStartInputs","details","businessType","starter","siteKind","businessName","AI_SITE_START_INPUT_KEYS","aiSiteStartInputsOf","inputs","kept","Object","keys","aiSiteStartAnswersFromInputs","text","Math","round","fromEntries","split","slice","bounded","trimmed","replace","cut","space","lastIndexOf","aiSiteStartAnswersFromClientBuild","intake","whatTheyDo","aiSiteStartClientInputs","towns","aiSiteStartClientBrief","name","phone","email","hours","words","ownerWords","contact","aiSiteStartClientNote","reach","parts","list"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,mBAAmB,EACnBC,kBAAkB,EAClBC,mBAAmB,QAGd,uBAAmB;AAC1B,SAASC,UAAU,EAAEC,aAAa,QAAyB,qBAAiB;AAC5E,SACEC,yBAAyB,EACzBC,sBAAsB,EACtBC,sBAAs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n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ClientBuildIntake } from '@aglyn/aglyn/app-utils/client-build'\nimport { weeklyHoursFromText, weeklyHoursToText } from '@aglyn/shared-ui-jsx/utils/weekly-hours'\nimport {\n AI_SITE_DETAIL_KEYS,\n AI_SITE_NO_DETAILS,\n aiSiteDetailProblem,\n aiSiteDetailsOf,\n type AiSiteDetailKey,\n type AiSiteDetails,\n} from './ai-site-details'\nimport { aiSiteKind, aiSiteKindFor, type AiSiteKind } from './ai-site-kinds'\nimport {\n AI_SITE_INSPIRATION_INPUT,\n aiSiteInspirationInput,\n aiSiteInspirationLimit,\n aiSiteInspirationRefusal,\n aiSiteInspirationUrl,\n} from './ai-site-inspiration'\nimport {\n AI_SITE_INPUT_MAX_CHARS,\n AI_SITE_SUBMISSIONS,\n aiSitePagesBand,\n type AiSiteJobInputs,\n type AiSiteSubmissions,\n} from './ai-site-job'\n\n/**\n * The guided start (AGL-2918): the questions a person answers on a site they\n * have just made, and the site job those answers become.\n *\n * A scaffold already exists — the `site` job plans four to eight pages, a\n * layout, a contact form, a palette and a welcome email, and builds every one\n * of them as a draft. What it had no way in through was a brief: somebody had\n * to know what to write, on a site where nothing has happened yet. So this\n * module is the QUESTIONS, and nothing else: what is asked, what an answer may\n * be, and how a set of answers becomes the brief and the scalar inputs the\n * `site` door already takes.\n *\n * ── Answering is never the way out ───────────────────────────────────────\n *\n * There is no answer here that means \"not this\". The way past the questions\n * is the `hostFirstRun` zone's own `startBlank`, which is drawn beside them\n * from the first one and creates nothing at all — see the zone in\n * `CONSOLE_WIDGET_SLOTS`. Putting the exit inside the question set would make\n * leaving a thing you answer your way to, and it is not.\n *\n * ── Every answer but the first is optional ───────────────────────────────\n *\n * Only what a site is FOR has no default worth guessing. The audience narrows\n * the copy, the example steers the shape, the page count and the welcome\n * email are defaults a person may change — so a person who types six words\n * and confirms gets a planned site, and the rest of the questions are there\n * for the person who wants to answer them.\n *\n * Pure: shapes, vocabularies and two string builders. No React, no network,\n * and no import of the starter catalog — {@link AI_SITE_START_EXAMPLES} names\n * the starters rather than reading them, so the console does not carry a\n * catalog of node maps to draw five cards. `ai-site-start.spec.ts` holds the\n * two lists to each other.\n */\n\n/** A worked example a person picks to steer what the site should look like. */\nexport interface AiSiteStartExample {\n /** A `STARTER_TEMPLATES` id, which is a persisted identifier. */\n id: string\n /** The starter as its card names it. */\n label: string\n /** The starter's category, which is how the examples group. */\n category: string\n /** What the example is, in one line a person reads before picking it. */\n blurb: string\n}\n\n/**\n * The examples the start offers, in the order they are shown. The platform's\n * own starter sites: a person who has no words for what they want has seen\n * these five shapes before, and picking one says more than a sentence would.\n */\nexport const AI_SITE_START_EXAMPLES: readonly AiSiteStartExample[] = [\n {\n id: 'business',\n label: 'Business',\n category: 'Business',\n blurb: 'A home page led by what you do, an about page and a contact page',\n },\n {\n id: 'landing',\n label: 'Landing Page',\n category: 'Marketing',\n blurb: 'One page that leads to one action, with the reasons to take it',\n },\n {\n id: 'portfolio',\n label: 'Portfolio',\n category: 'Personal',\n blurb: 'An introduction, a grid of work and a way to get in touch',\n },\n {\n id: 'physical-shop',\n label: 'Shop (physical products)',\n category: 'Commerce',\n blurb: 'Featured products, a shop to browse, and a cart',\n },\n {\n id: 'digital-shop',\n label: 'Shop (digital products)',\n category: 'Commerce',\n blurb: 'Downloads up front, a shop to browse, and a cart',\n },\n]\n\n/**\n * Kinds of site offered beside the first question's box, so answering it can\n * be a tap. They fill the box rather than replacing it: what somebody is\n * building is theirs to say, and a list of eight is a list somebody is not on.\n */\nexport const AI_SITE_START_TYPES: readonly string[] = [\n 'a local service business',\n 'a restaurant or cafe',\n 'a professional practice',\n 'a trades business',\n 'a shop',\n 'a nonprofit',\n 'a personal portfolio',\n 'an event',\n]\n\n/**\n * What a person answered; the shape the card holds and the brief is built from.\n *\n * Beside the answers each step asks, the business details its \"More details\"\n * offers (AGL-3979, `AiSiteDetails`): every one optional and `''` until given,\n * the phone number and email on the Details step itself.\n */\nexport interface AiSiteStartAnswers extends AiSiteDetails {\n /** What kind of site this is. The one answer with no default. */\n siteType: string\n /** Who the site is for; empty when they did not say. */\n audience: string\n /** The example they liked, by {@link AiSiteStartExample.id}; `null` for none. */\n example: string | null\n /**\n * The kind of site they picked (AGL-3660), by its `AI_SITE_KINDS` id;\n * `null` until they pick one, when the kind their first answer suggests is\n * the one used ({@link aiSiteStartKind}).\n */\n kind: string | null\n /** How many pages to plan. */\n pages: number\n /** Where the contact form's submissions go. */\n submissions: AiSiteSubmissions\n /** Whether the scaffold also drafts a welcome email. */\n welcomeEmail: boolean\n /** The city or town the business is in (AGL-3979); empty when they did not say. */\n city: string\n /** The brand color, as a six-digit hex (AGL-3979); empty for the style's own. */\n brand: string\n /**\n * The sites they like (AGL-3975), as typed, one a field; absent or empty\n * for none. Asked only while `release_ai_site_inspiration` is on.\n */\n inspiration?: string[]\n}\n\n/**\n * What the questions start on. Five pages because it is the middle of the\n * band the scaffold builds, a welcome email because the scaffold drafts one\n * unless it is told not to, and the Inbox because it is what every submission\n * does anyway — filing a lead as well is the addition, and an addition is the\n * thing a person should have to choose.\n */\nexport const AI_SITE_START_ANSWERS: AiSiteStartAnswers = {\n siteType: '',\n audience: '',\n example: null,\n kind: null,\n pages: 5,\n submissions: 'inbox',\n welcomeEmail: true,\n city: '',\n brand: '',\n ...AI_SITE_NO_DETAILS,\n}\n\n/** The answers a person may give beyond the ones each step asks, by key (AGL-3979). */\nexport type AiSiteStartExtraKey = AiSiteDetailKey | 'city' | 'brand'\n\n/** Every extra, in the order the review lists them. */\nexport const AI_SITE_START_EXTRA_KEYS: readonly AiSiteStartExtraKey[] = [\n 'phone',\n 'email',\n 'tagline',\n 'founded',\n 'serviceArea',\n 'priceRange',\n 'languages',\n 'brand',\n 'street',\n 'city',\n 'region',\n 'postalCode',\n 'country',\n 'hours',\n 'social',\n]\n\n/** What is wrong with one extra, worded for beside its field; `null` when it may be used. */\nexport function aiSiteStartExtraProblem(\n key: AiSiteStartExtraKey,\n value: string,\n): { code: 'too_long' | 'invalid'; message: string } | null {\n if (key === 'city' || key === 'brand') {\n return value.trim().length > AI_SITE_INPUT_MAX_CHARS\n ? { code: 'too_long', message: `Keep this under ${AI_SITE_INPUT_MAX_CHARS} characters.` }\n : null\n }\n return aiSiteDetailProblem(key, value)\n}\n\n/** The extras a person gave, in the review's order: what \"More details\" was used for. */\nexport function aiSiteStartExtrasGiven(answers: AiSiteStartAnswers): AiSiteStartExtraKey[] {\n return AI_SITE_START_EXTRA_KEYS.filter((key) => (answers[key] ?? '').trim() !== '')\n}\n\n/** The kind of site the answers pick, else the one what the site is and who it is for suggest. */\nexport function aiSiteStartKind(\n answers: Pick<AiSiteStartAnswers, 'kind' | 'siteType'> & Partial<Pick<AiSiteStartAnswers, 'audience'>>,\n): AiSiteKind {\n return aiSiteKind(answers.kind) ?? aiSiteKindFor(answers.siteType, answers.audience ?? '')\n}\n\n/** The example an answer names, or `null` when it names none this list knows. */\nexport function aiSiteStartExample(\n answers: AiSiteStartAnswers,\n): AiSiteStartExample | null {\n if (!answers.example) return null\n return AI_SITE_START_EXAMPLES.find((entry) => entry.id === answers.example) ?? null\n}\n\n/**\n * Why these answers cannot start a site, in a sentence a person reads; `null`\n * when they can. The door's own parser is what actually admits the job — this\n * is what the card says before it asks for one.\n */\nexport function aiSiteStartRefusal(\n answers: AiSiteStartAnswers,\n options: { freeTaste?: boolean } = {},\n): string | null {\n // The workspace's own band (AGL-3594): one or two pages on the Free taste.\n const band = aiSitePagesBand(options.freeTaste)\n const siteType = answers.siteType.trim()\n if (!siteType) return 'Say what kind of site this is.'\n if (siteType.length > AI_SITE_INPUT_MAX_CHARS) {\n return `Keep what kind of site this is under ${AI_SITE_INPUT_MAX_CHARS} characters.`\n }\n if (answers.audience.trim().length > AI_SITE_INPUT_MAX_CHARS) {\n return `Keep who the site is for under ${AI_SITE_INPUT_MAX_CHARS} characters.`\n }\n if (!Number.isInteger(answers.pages) || answers.pages < band.min || answers.pages > band.max) {\n return `A site is planned with ${band.min} to ${band.max} pages.`\n }\n if (answers.example !== null && !aiSiteStartExample(answers)) {\n return 'Pick one of the examples, or none of them.'\n }\n if (!(AI_SITE_SUBMISSIONS as readonly string[]).includes(answers.submissions)) {\n return 'Say where the contact form’s submissions go.'\n }\n for (const key of AI_SITE_START_EXTRA_KEYS) {\n const problem = aiSiteStartExtraProblem(key, answers[key] ?? '')\n if (problem) return problem.message\n }\n return aiSiteStartInspirationRefusal(answers, options)\n}\n\n/** The sites they typed, without the empty fields. */\nexport function aiSiteStartInspirationTyped(answers: Pick<AiSiteStartAnswers, 'inspiration'>): string[] {\n return (answers.inspiration ?? []).map((entry) => entry.trim()).filter(Boolean)\n}\n\n/** Why the sites they like cannot go forward, as the door would refuse them; `null` when they can. */\nexport function aiSiteStartInspirationRefusal(\n answers: Pick<AiSiteStartAnswers, 'inspiration'>,\n options: { freeTaste?: boolean } = {},\n): string | null {\n const typed = aiSiteStartInspirationTyped(answers)\n if (typed.some((entry) => !aiSiteInspirationUrl(entry))) {\n return 'Give each site you like as its https address, like https://example.com.'\n }\n return aiSiteInspirationRefusal(typed, options.freeTaste)\n}\n\n/**\n * The answers as the brief the `site` job is created with: the plan step reads\n * it as the person's own words, so it says what they said and asks for nothing\n * they did not.\n */\nexport function aiSiteStartBrief(answers: AiSiteStartAnswers): string {\n const siteType = answers.siteType.trim()\n const audience = answers.audience.trim()\n const example = aiSiteStartExample(answers)\n const sentences = [\n `A ${answers.pages}-page website for ${siteType}.`,\n ]\n if (audience) sentences.push(`It is for ${audience}.`)\n if (example) {\n sentences.push(\n `Follow the shape of the ${example.label} starter: ${example.blurb.toLowerCase()}.`,\n )\n }\n // The kind they picked, or the one their answer suggests (AGL-3660).\n sentences.push(`Make it a ${aiSiteStartKind(answers).label.toLowerCase()} site.`)\n // The form on the page a visitor opens to get in touch, never every page's\n // last band (AGL-3899): \"on the page that asks to be contacted\" read as\n // the home's closing band on 16 of the 22 newest production starts.\n sentences.push(\n answers.pages === 1\n ? 'Plan the page around what a visitor comes to do, with a contact form on it.'\n : 'Plan a page for each thing a visitor comes to do, with the contact form on the page a visitor opens to get in touch.',\n )\n if (audience) {\n // Said of the FORM as well as of the copy: who fills a form in is what\n // decides which fields it asks for, and a brief that named the audience\n // once, in a sentence about the pages, left the form to guess.\n sentences.push(`Ask the contact form for what ${audience} would be asked for.`)\n }\n return sentences.join(' ')\n}\n\n/**\n * The answers as the `site` job's scalar inputs. Read by the door's\n * {@link parseAiSiteJobInputs}, and put in front of the model one per line by\n * the plan step, which is how the audience and the example reach the plan\n * without a prompt of their own.\n *\n * The per-site variables an agency batch fills — the business name, the city,\n * the brand — are left empty here: the questions never ask them. The name is\n * the site's own, and the create door fills it from the site\n * (`aiJobAdmittedInputs`, AGL-3596) when the job is started — a job that\n * reached the model with no name had the model invent one for its header and\n * footer.\n */\nexport function aiSiteStartInputs(\n answers: AiSiteStartAnswers,\n): Omit<AiSiteJobInputs, 'batchId' | 'inspiration' | AiSiteDetailKey> & Partial<AiSiteDetails> & { inspiration?: string } {\n const example = aiSiteStartExample(answers)\n const kind = aiSiteStartKind(answers)\n // The details are sent only where given (AGL-3979): the plan step lists\n // every scalar input on a line of its own, and a start without them is\n // asked exactly what it was asked before.\n const details: Partial<AiSiteDetails> = {}\n for (const key of AI_SITE_DETAIL_KEYS) {\n const value = (answers[key] ?? '').trim()\n if (value) details[key] = value\n }\n // The sites they like travel only when there are some (AGL-3975), so a\n // start without them asks for exactly what it always did.\n const inspiration = aiSiteInspirationInput(aiSiteStartInspirationTyped(answers))\n return {\n businessType: answers.siteType.trim(),\n audience: answers.audience.trim(),\n starter: example?.id ?? kind.starter,\n siteKind: kind.id,\n pages: answers.pages,\n businessName: '',\n city: (answers.city ?? '').trim(),\n brand: (answers.brand ?? '').trim(),\n submissions: answers.submissions,\n welcomeEmail: answers.welcomeEmail,\n ...details,\n ...(inspiration ? { [AI_SITE_INSPIRATION_INPUT]: inspiration } : {}),\n }\n}\n\n/** The site inputs a guided start's answers become, by name: what a summary carries back (AGL-3596). */\nexport const AI_SITE_START_INPUT_KEYS = [\n 'businessType',\n 'audience',\n 'starter',\n 'siteKind',\n 'pages',\n 'businessName',\n 'city',\n 'brand',\n 'submissions',\n 'welcomeEmail',\n ...AI_SITE_DETAIL_KEYS,\n AI_SITE_INSPIRATION_INPUT,\n] as const\n\n/** A site job's scalar inputs, and nothing else its inputs carry; `null` when it has none. */\nexport function aiSiteStartInputsOf(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n): Record<string, unknown> | null {\n if (!inputs) return null\n const kept: Record<string, unknown> = {}\n for (const key of AI_SITE_START_INPUT_KEYS) {\n const value = inputs[key]\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') kept[key] = value\n }\n return Object.keys(kept).length ? kept : null\n}\n\n/**\n * A failed start's answers, back as the questions hold them (AGL-3596), so\n * Try again reopens the guided start filled in for the person to adjust:\n * the inverse of {@link aiSiteStartInputs}. Read defensively — an answer the\n * questions no longer offer goes back to its default — and held to the\n * workspace's page band. `null` when the inputs say no kind of site at all.\n */\nexport function aiSiteStartAnswersFromInputs(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n options: { freeTaste?: boolean } = {},\n): AiSiteStartAnswers | null {\n const text = (key: string) => (typeof inputs?.[key] === 'string' ? (inputs[key] as string).trim() : '')\n const siteType = text('businessType')\n if (!siteType) return null\n const band = aiSitePagesBand(options.freeTaste)\n const pages = typeof inputs?.['pages'] === 'number' ? Math.round(inputs['pages'] as number) : AI_SITE_START_ANSWERS.pages\n const starter = text('starter')\n const submissions = text('submissions')\n return {\n siteType,\n audience: text('audience'),\n example: AI_SITE_START_EXAMPLES.some((entry) => entry.id === starter) ? starter : null,\n kind: aiSiteKind(text('siteKind'))?.id ?? null,\n pages: Math.min(band.max, Math.max(band.min, pages)),\n submissions: (AI_SITE_SUBMISSIONS as readonly string[]).includes(submissions)\n ? (submissions as AiSiteSubmissions)\n : AI_SITE_START_ANSWERS.submissions,\n welcomeEmail: options.freeTaste ? false : inputs?.['welcomeEmail'] !== false,\n city: text('city'),\n brand: text('brand'),\n ...(Object.fromEntries(AI_SITE_DETAIL_KEYS.map((key) => [key, text(key)])) as unknown as AiSiteDetails),\n // The sites they liked come back as typed, within the workspace's limit (AGL-3975).\n ...(text(AI_SITE_INSPIRATION_INPUT)\n ? { inspiration: text(AI_SITE_INSPIRATION_INPUT).split(/\\s+/).filter(Boolean).slice(0, aiSiteInspirationLimit(options.freeTaste)) }\n : {}),\n }\n}\n\n// ── A build staff run for a client (AGL-3958) ───────────────────────────────\n\n/** Shortens an answer to what a scalar input admits, on a word where it can. */\nfunction bounded(value: string, max: number): string {\n const trimmed = value.trim().replace(/\\s+/g, ' ')\n if (trimmed.length <= max) return trimmed\n const cut = trimmed.slice(0, max)\n const space = cut.lastIndexOf(' ')\n return (space > max / 2 ? cut.slice(0, space) : cut).trim()\n}\n\n/** A time with am or pm: \"9am\", \"5:30 pm\", \"12 a.m.\". */\nconst TWELVE_HOUR_TIME = /\\b(\\d{1,2})(?::(\\d{2}))?\\s*([ap])\\.?m\\.?(?![a-z])/gi\n\n/**\n * The hours an owner gave, in the shape the Details step's hours picker\n * writes (`Tu-Sa 09:00-17:00`, one set of days a line), so the plan reads\n * them as it reads hours picked there. A time with am or pm is the time it\n * names, \"to\" joins a range as a dash does, and days with their hours may be\n * set apart by a comma, a semicolon or a line. Whatever still does not read\n * as hours — \"8–5\", \"Sat by appointment\" — is left out rather than guessed at.\n */\nfunction clientBuildHours(hours: string): string {\n const lines = hours\n .replace(TWELVE_HOUR_TIME, (time, hour: string, minutes: string | undefined, half: string) => {\n const h = Number(hour)\n if (h < 1 || h > 12) return time\n const clock = (h % 12) + (half.toLowerCase() === 'p' ? 12 : 0)\n return `${String(clock).padStart(2, '0')}:${minutes ?? '00'}`\n })\n .replace(/\\s+to\\s+/gi, '-')\n .replace(/(\\d{1,2}:\\d{2})\\s*,\\s*/g, '$1\\n')\n .replace(/;/g, '\\n')\n const week = weeklyHoursFromText(lines).hours\n return week.some((day) => day.length) ? weeklyHoursToText(week) : ''\n}\n\n/**\n * The towns an intake serves, one a line, as the Details step's \"Areas you\n * serve\" holds them: \"Austin, Round Rock and Pflugerville\" is three.\n */\nfunction clientBuildServiceArea(towns: string): string {\n return towns\n .split(/\\r?\\n|[,;]|\\s+(?:and|&)\\s+/i)\n .map((town) => town.trim())\n .filter(Boolean)\n .join('\\n')\n}\n\n/**\n * The questions' answers for a site staff are building for a client: what\n * the business does is the kind of site, and the details the intake holds\n * fill the Details step's own fields (AGL-3979, AGL-3995): the phone, the\n * email, the towns as the areas it serves and the hours, each held to that\n * detail's own rule, so one the Details step would refuse is left empty\n * there. Every other answer keeps its default, which the review shows to\n * change. The intake, a refused detail included, also reaches the job\n * through {@link aiSiteStartClientInputs} and {@link aiSiteStartClientBrief}.\n */\nexport function aiSiteStartAnswersFromClientBuild(intake: ClientBuildIntake): AiSiteStartAnswers {\n const details = aiSiteDetailsOf({\n phone: intake.phone,\n email: intake.email,\n serviceArea: clientBuildServiceArea(intake.towns),\n hours: clientBuildHours(intake.hours),\n })\n return {\n ...AI_SITE_START_ANSWERS,\n siteType: bounded(intake.whatTheyDo, AI_SITE_INPUT_MAX_CHARS),\n phone: details.phone,\n email: details.email,\n serviceArea: details.serviceArea,\n hours: details.hours,\n }\n}\n\n/**\n * The per-site inputs the intake fills, which the guided start's own\n * questions leave empty: the business's name for the header and footer, and\n * the towns it serves as its place.\n *\n * The towns are the place only while no address is given. The Entity reads\n * `city` as the address's own locality wherever there is a street or a\n * postal code (`aiSiteEntity`), so once the answers carry either, `city` is\n * the city the Details step was given with that address, never the towns\n * (AGL-3995). The intake asks no address, so today that is the Details step's\n * own, typed on the review; the towns still reach the site as the areas it\n * serves.\n */\nexport function aiSiteStartClientInputs(\n intake: ClientBuildIntake,\n answers?: Pick<AiSiteStartAnswers, 'street' | 'postalCode' | 'city'> | null,\n): Pick<AiSiteJobInputs, 'businessName' | 'city'> {\n const addressed = Boolean(answers?.street.trim() || answers?.postalCode.trim())\n return {\n businessName: bounded(intake.businessName, AI_SITE_INPUT_MAX_CHARS),\n city: bounded(addressed ? (answers?.city ?? '') : intake.towns, AI_SITE_INPUT_MAX_CHARS),\n }\n}\n\n/**\n * The intake as sentences added to the brief: how to reach the business and\n * when it is open, which the site should say where a visitor looks for them,\n * and the owner's own words, quoted, which the copy should sound like. Empty\n * answers say nothing.\n */\nexport function aiSiteStartClientBrief(intake: ClientBuildIntake): string {\n const name = intake.businessName.trim()\n const towns = intake.towns.trim()\n const phone = intake.phone.trim()\n const email = intake.email.trim()\n const hours = intake.hours.trim()\n const words = intake.ownerWords.trim().replace(/\\s+/g, ' ')\n const sentences: string[] = []\n if (name) sentences.push(`The business is called ${name}.`)\n if (towns) sentences.push(`It serves ${towns}.`)\n const contact = [phone ? `call ${phone}` : '', email ? `email ${email}` : ''].filter(Boolean)\n if (contact.length) {\n sentences.push(`Visitors reach it to ${contact.join(' or ')}; say so wherever the site tells them how to get in touch.`)\n }\n if (hours) sentences.push(`Its hours are ${hours}.`)\n if (words) sentences.push(`In the owner's own words: \"${words}\" Write the copy so it sounds like them.`)\n return sentences.join(' ')\n}\n\n/**\n * What the review says the client build adds beyond its own rows, so staff\n * see the intake is used without it being asked again: the business's name\n * and the owner's own words, which no row shows. The phone, email, towns and\n * hours are the review's Details rows already (AGL-3995), so the note does\n * not say them twice: \"Also from the client's details: Harbor Plumbing and\n * the owner's own words.\"\n */\nexport function aiSiteStartClientNote(intake: ClientBuildIntake): string {\n const parts = [intake.businessName.trim(), intake.ownerWords.trim() ? \"the owner's own words\" : ''].filter(Boolean)\n if (!parts.length) return 'Built from the client’s details.'\n return `Also from the client’s details: ${parts.join(' and ')}.`\n}\n"],"names":["weeklyHoursFromText","weeklyHoursToText","AI_SITE_DETAIL_KEYS","AI_SITE_NO_DETAILS","aiSiteDetailProblem","aiSiteDetailsOf","aiSiteKind","aiSiteKindFor","AI_SITE_INSPIRATION_INPUT","aiSiteInspirationInput","aiSiteInspirationLimit","aiSiteInspirationRefusal","aiSiteInspirationUrl","AI_SITE_INPUT_MAX_CHARS","AI_SITE_SUBMISSIONS","aiSitePagesBand","AI_SITE_START_EXAMPLES","id","label","category","blurb","AI_SITE_START_TYPES","AI_SITE_START_ANSWERS","siteType","audience","example","kind","pages","submissions","welcomeEmail","city","brand","AI_SITE_START_EXTRA_KEYS","aiSiteStartExtraProblem","key","value","trim","length","code","message","aiSiteStartExtrasGiven","answers","filter","aiSiteStartKind","aiSiteStartExample","find","entry","aiSiteStartRefusal","options","band","freeTaste","Number","isInteger","min","max","includes","problem","aiSiteStartInspirationRefusal","aiSiteStartInspirationTyped","inspiration","map","Boolean","typed","some","aiSiteStartBrief","sentences","push","toLowerCase","join","aiSiteStartInputs","details","businessType","starter","siteKind","businessName","AI_SITE_START_INPUT_KEYS","aiSiteStartInputsOf","inputs","kept","Object","keys","aiSiteStartAnswersFromInputs","text","Math","round","fromEntries","split","slice","bounded","trimmed","replace","cut","space","lastIndexOf","TWELVE_HOUR_TIME","clientBuildHours","hours","lines","time","hour","minutes","half","h","clock","String","padStart","week","day","clientBuildServiceArea","towns","town","aiSiteStartAnswersFromClientBuild","intake","phone","email","serviceArea","whatTheyDo","aiSiteStartClientInputs","addressed","street","postalCode","aiSiteStartClientBrief","name","words","ownerWords","contact","aiSiteStartClientNote","parts"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,mBAAmB,EAAEC,iBAAiB,QAAQ,0CAAyC;AAChG,SACEC,mBAAmB,EACnBC,kBAAkB,EAClBC,mBAAmB,EACnBC,eAAe,QAGV,uBAAmB;AAC1B,SAASC,UAAU,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C,IAAI,CAAC,CAAC,cAAc,EAAE8B,MAAM,CAAC,CAAC;IACnD,IAAI2B,OAAO1D,UAAUC,IAAI,CAAC,CAAC,2BAA2B,EAAEyD,MAAM,wCAAwC,CAAC;IACvG,OAAO1D,UAAUG,IAAI,CAAC;AACxB;AAEA;;;;;;;CAOC,GACD,OAAO,SAAS0D,sBAAsBd,MAAyB;IAC7D,MAAMe,QAAQ;QAACf,OAAOtC,YAAY,CAACtC,IAAI;QAAI4E,OAAOY,UAAU,CAACxF,IAAI,KAAK,0BAA0B;KAAG,CAACM,MAAM,CAACmB;IAC3G,IAAI,CAACkE,MAAM1F,MAAM,EAAE,OAAO;IAC1B,OAAO,CAAC,gCAAgC,EAAE0F,MAAM3D,IAAI,CAAC,SAAS,CAAC,CAAC;AAClE"}
|
|
@@ -33,6 +33,7 @@ import { readFreeAiCreditsLeft } from "../usage/free-ai-credits-left.js";
|
|
|
33
33
|
import { aiCreditsConfirmation } from "../model/ai-credit-estimate.js";
|
|
34
34
|
import { aiUsageMeter } from "../usage/ai-usage-meter.js";
|
|
35
35
|
import { aiJobsGate } from "./ai-jobs-gate.js";
|
|
36
|
+
import { siteImportOfferFor } from "./ai-site-import-route.js";
|
|
36
37
|
import { withoutErasedSites } from "./ai-jobs-live-sites.js";
|
|
37
38
|
import { AI_JOB_ACTIVE_STATUSES } from "../model/ai-job-activity.js";
|
|
38
39
|
import { reportServerError } from "@aglyn/tenant-data-admin/server/client-error-report";
|
|
@@ -398,6 +399,14 @@ export async function GET(request) {
|
|
|
398
399
|
org: gate.org,
|
|
399
400
|
now
|
|
400
401
|
}) : null;
|
|
402
|
+
// Whether Create site offers "Bring my site" (AGL-3976), asked only by the
|
|
403
|
+
// guided start's own read, so the card costs no other caller anything.
|
|
404
|
+
const siteImport = url.searchParams.get('siteImport') === '1' ? await siteImportOfferFor({
|
|
405
|
+
orgId: gate.orgId,
|
|
406
|
+
staff: gate.staff,
|
|
407
|
+
org: gate.org,
|
|
408
|
+
member: gate.member
|
|
409
|
+
}) : null;
|
|
401
410
|
// Whether the guided start asks for the sites the person likes (AGL-3975):
|
|
402
411
|
// the workspace's own verdict, the one its site job reads them by.
|
|
403
412
|
const siteInspiration = await isServerReleaseFlagOnForOrg(AI_SITE_INSPIRATION_FLAG, gate.orgId).catch(()=>false);
|
|
@@ -408,6 +417,8 @@ export async function GET(request) {
|
|
|
408
417
|
freeTaste
|
|
409
418
|
}, freeCredits ? {
|
|
410
419
|
freeCredits
|
|
420
|
+
} : {}, siteImport ? {
|
|
421
|
+
siteImport
|
|
411
422
|
} : {}, siteInspiration ? {
|
|
412
423
|
siteInspiration: true
|
|
413
424
|
} : {}), {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-jobs-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lockdown-423: via libs/plugins/ai/src/lib/runtime/ai-gate.ts\n// The POST climbs `aiGateLadder`, whose lockdown rung is the verdict; the\n// GET climbs `ai-jobs-gate.ts`, which carries the same rung.\n\nimport { randomUUID } from 'crypto'\nimport { resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n AI_JOB_KINDS,\n type AiJobKind,\n type AiJobStatus,\n} from '../model/ai-jobs.types'\n// By their own entry points rather than the barrel (AGL-2903): the specs\n// stub the barrel closed-world, and the ladder, the machine and the runtime\n// are the things under test here, not things to be stubbed away.\nimport { aiGateLadder } from '../runtime/ai-gate'\nimport { aiJobAdmissionRefusal, aiJobSiteRefusal } from '../jobs/ai-job-admission'\nimport { AI_JOB_BRIEF_MAX_CHARS } from '../jobs/ai-job-text-step'\nimport { aiJobAdmittedInputs } from '../jobs/ai-job-auto-confirm'\nimport {\n AI_JOB_INLINE_BUDGET_MS,\n aiJobNextStepMinimumMs,\n aiJobSummary,\n createAiJob,\n listAiJobs,\n runAiJobStep,\n} from '../jobs/ai-jobs'\nimport { releaseAssistMessage } from '../usage/assist-usage'\nimport { readFreeAiCreditsLeft } from '../usage/free-ai-credits-left'\nimport { aiCreditsConfirmation, type AiCreditsPrompt } from '../model/ai-credit-estimate'\nimport { aiUsageMeter } from '../usage/ai-usage-meter'\nimport { aiJobsGate } from './ai-jobs-gate'\nimport { withoutErasedSites } from './ai-jobs-live-sites'\nimport { AI_JOB_ACTIVE_STATUSES } from '../model/ai-job-activity'\nimport { reportServerError } from '@aglyn/tenant-data-admin/server/client-error-report'\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { AI_SITE_INSPIRATION_FLAG } from '../model/ai-site-inspiration'\n\n/**\n * A caught fault on this door, reported as well as logged (AGL-1921).\n *\n * `onRequestError` sees only an UNCAUGHT throw, and the Vercel log drain\n * forwards the status line but not a `console.error`, so the three 500s\n * this route answered on 2026-10-06 at 17:41–17:47Z reached the alert as\n * START/END/REPORT with no reason anywhere. Never throws.\n */\nasync function reportJobFault(what: string, error: unknown): Promise<void> {\n try {\n await reportServerError(\n {\n message: `${what}: ${error instanceof Error ? error.message : String(error)}`,\n stack: error instanceof Error ? error.stack : undefined,\n route: '/api/ai/jobs',\n routeType: 'route',\n method: 'POST',\n },\n { service: 'console-web' },\n )\n } catch {\n // The console line beside each call is the record of last resort.\n }\n}\n\n/**\n * AI generation jobs: create and list (AGL-2904).\n *\n * `POST` is a door that spends, so it climbs the whole ladder (AGL-2903) —\n * `aiGenerative`, `release_ai_generative`, the `ai-generate` switch, a\n * per-uid window, and a reservation — and then creates the job and runs\n * its first step INLINE under `AI_JOB_INLINE_BUDGET_MS`. A step that\n * finishes in time answers with the job `done` (or `queued` behind its\n * next step); one that does not is aborted, its reservation handed back,\n * and the job answers `queued` for the beat to resume. Either way the\n * caller gets the job document, and the events route is how it watches\n * from there.\n *\n * `POST` with `check: true` climbs the same ladder and asks the same\n * admission, then hands the reservation back and creates nothing: a 200\n * with `ok` true, or the refusal the create would have answered. \"Create site\"\n * asks it before it makes the site a guided start builds on (AGL-3859), so\n * a start that would be refused, or that asks for the Free go-ahead, leaves\n * no empty site behind. A checked job may name no site yet.\n *\n * `GET` lists the org's jobs, newest first, through the read gate: the\n * same rungs up to the lockdown verdict, no reservation. A job naming a\n * site that no longer exists is left out, so a page can come back shorter\n * than its `limit`.\n *\n * The request must NAME the org it is metered against (AGL-1934). There\n * is no fallback to \"the caller's first org\".\n */\n\nconst AI_JOBS_RATE_LIMIT = { key: 'ai-jobs', limit: 10, windowMs: 60_000 }\n\n/** Kind-specific inputs, bounded: a runner reads scalars, not a document. */\nconst MAX_INPUTS_JSON_CHARS = 8_000\n\n/** The admitted statuses for the list filter, as the union spells them. */\nconst AI_JOB_STATUSES: readonly AiJobStatus[] = [\n 'queued',\n 'running',\n 'needs_input',\n 'needs_review',\n 'done',\n 'failed',\n 'canceled',\n]\n\nexport interface CreateAiJobBody {\n orgId: string\n hostId: string | null\n kind: AiJobKind\n brief: string\n inputs: Record<string, string | number | boolean>\n /** A catalog model the creator picked (AGL-2942), or `null` for Auto. */\n model: string | null\n}\n\nconst ID_CHARS = /^[A-Za-z0-9_-]{1,100}$/\n\n/** The longest model id a body may carry; the catalog's ids are far shorter. */\nconst MAX_MODEL_CHARS = 100\n\n/** Validate + clamp the request body; a string names what is wrong. */\nexport function parseCreateAiJobBody(payload: unknown): CreateAiJobBody | string {\n const body = (payload ?? {}) as Record<string, unknown>\n const orgId = String(body.orgId ?? '').trim()\n if (!orgId) return 'Open a workspace before using this feature'\n const kind = String(body.kind ?? '')\n if (!(AI_JOB_KINDS as readonly string[]).includes(kind)) {\n return `kind must be one of ${AI_JOB_KINDS.join(', ')}`\n }\n const brief = String(body.brief ?? '').trim()\n if (!brief) return 'Write a brief for the job'\n if (brief.length > AI_JOB_BRIEF_MAX_CHARS) {\n return `Keep the brief under ${AI_JOB_BRIEF_MAX_CHARS.toLocaleString('en-US')} characters`\n }\n const rawHost = body.hostId\n const hostId =\n rawHost === undefined || rawHost === null || rawHost === ''\n ? null\n : typeof rawHost === 'string' && ID_CHARS.test(rawHost)\n ? rawHost\n : undefined\n if (hostId === undefined) return 'hostId is not a site id'\n // A theme is fields on one site's document, so a theme job that names no\n // site has nothing to propose a change to (AGL-2938).\n if (kind === 'theme' && !hostId) return 'Open a site before changing its theme'\n const rawInputs = body.inputs\n const inputs: Record<string, string | number | boolean> = {}\n if (rawInputs !== undefined && rawInputs !== null) {\n if (typeof rawInputs !== 'object' || Array.isArray(rawInputs)) {\n return 'inputs must be an object'\n }\n for (const [key, value] of Object.entries(rawInputs as Record<string, unknown>)) {\n if (\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n return `inputs.${key} must be a string, number or boolean`\n }\n inputs[key] = value\n }\n if (JSON.stringify(inputs).length > MAX_INPUTS_JSON_CHARS) {\n return 'inputs are too large'\n }\n }\n const rawModel = typeof body.model === 'string' ? body.model.trim() : ''\n if (rawModel.length > MAX_MODEL_CHARS) return 'model is not a model id'\n // Validated against the plan and the allotment allowlists when each step\n // runs, not here: the allowlists are read inside the step's reservation.\n const model = rawModel && rawModel !== 'auto' ? rawModel : null\n return { orgId, hostId, kind: kind as AiJobKind, brief, inputs, model }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n let payload: unknown\n try {\n payload = await request.json()\n } catch {\n payload = null\n }\n const parsed = parseCreateAiJobBody(payload)\n // The org is parsed BEFORE the ladder so a request that named none is\n // refused with the ladder's 400 rather than a shape error; every other\n // shape fault waits until the caller has proven who they are.\n const orgId = typeof parsed === 'string' ? String((payload as Record<string, unknown> | null)?.orgId ?? '') : parsed.orgId\n // The site rides along for the same reason: a collaborator's `ai.generate`\n // is decided per site (AGL-2927), so the ladder needs it before it can say\n // whether this member may generate here at all.\n const hostId = typeof parsed === 'string' ? null : parsed.hostId\n const gate = await aiGateLadder(\n { request, orgId, hostId },\n {\n feature: 'aiGenerative',\n releaseFlag: 'release_ai_generative',\n lockdownFeature: 'ai-generate',\n permission: 'ai.generate',\n rateLimit: AI_JOBS_RATE_LIMIT,\n },\n )\n if (gate instanceof Response) return gate\n if (typeof parsed === 'string') {\n // Admitted, reserved, and then found to have sent nothing runnable: the\n // reservation goes back, because no token was spent.\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json({ error: parsed }, { status: 400 })\n }\n // What only this kind can say about the request (AGL-2909): a site it\n // needs, inputs it reads, an allowance its draft counts against. Asked\n // before the job exists, so a refusal spends nothing.\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>>\n // A Free start past what is left, which the person chose to build as far as\n // it goes (AGL-3722): the prompt they confirmed, kept on the job.\n let confirmedCredits: AiCreditsPrompt | null = null\n // Asked before the site exists (AGL-3859): answers, creates nothing.\n const check = (payload as Record<string, unknown> | null)?.['check'] === true\n try {\n // A site that switched AI off first (AGL-3028), then the kind's own check.\n refusal =\n (await aiJobSiteRefusal({\n firestore: gate.firestore,\n org: gate.org,\n hostId: parsed.hostId,\n })) ??\n (await aiJobAdmissionRefusal(parsed.kind, {\n firestore: gate.firestore,\n orgId: gate.orgId,\n hostId: parsed.hostId,\n siteToCome: check && !parsed.hostId,\n inputs: parsed.inputs,\n org: gate.org,\n uid: gate.uid,\n creditsConfirmed: (payload as Record<string, unknown> | null)?.['creditsConfirmed'] === true,\n onCreditsConfirmed: (prompt) => {\n confirmedCredits = prompt\n },\n }))\n } catch (error) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job admission failed', { orgId: gate.orgId, kind: parsed.kind, error })\n await reportJobFault('ai job admission failed', error)\n return Response.json({ error: 'The AI job could not be created' }, { status: 500 })\n }\n if (refusal) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n // A Free start past what is left asks before it starts (AGL-3722): the\n // prompt rides the 409, so the dialog offers its choices.\n return Response.json(\n { error: refusal.error, ...(refusal.code ? { code: refusal.code } : {}), ...(refusal.credits ? { credits: refusal.credits } : {}) },\n { status: refusal.status },\n )\n }\n if (check) {\n // Admitted, and nothing to run: the reservation goes back.\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json({ ok: true }, { status: 200 })\n }\n\n const now = new Date()\n let created: Awaited<ReturnType<typeof createAiJob>>\n try {\n // The guided start's own plan confirmation (AGL-3594), kept only for a\n // site job on a site that has published nothing of the owner's yet.\n const inputs = await aiJobAdmittedInputs(gate.firestore, {\n kind: parsed.kind,\n hostId: parsed.hostId,\n inputs: parsed.inputs,\n })\n created = await createAiJob(\n gate.firestore,\n {\n orgId: gate.orgId,\n hostId: parsed.hostId,\n kind: parsed.kind,\n brief: parsed.brief,\n inputs,\n model: parsed.model,\n createdBy: gate.uid,\n createdByEmail: gate.decoded.email ?? null,\n creditsConfirmed: aiCreditsConfirmation(confirmedCredits, gate.uid, now),\n },\n now,\n )\n } catch (error) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job create failed', { orgId: gate.orgId, error })\n await reportJobFault('ai job create failed', error)\n return Response.json({ error: 'The AI job could not be created' }, { status: 500 })\n }\n const jobId = created.$id\n\n // A first step that needs more time than this request has (AGL-2907) is left\n // queued for the beat, which starts it with a budget of its own: a provider\n // call this request's timeout cut off would be billed upstream and metered\n // nowhere. Nothing ran, so the reservation goes back.\n if (aiJobNextStepMinimumMs(created) > AI_JOB_INLINE_BUDGET_MS) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json(\n {\n job: aiJobSummary(created, now),\n meter: aiUsageMeter(gate.reservation, { lastCredits: null }),\n },\n { status: 200 },\n )\n }\n\n // The first step, inline, on the reservation the ladder already holds.\n // The runner hands that reservation back itself if the provider is never\n // reached, and re-queues the step when the budget ends first.\n const run = await runAiJobStep(gate.firestore, gate.orgId, jobId, {\n owner: `route:${randomUUID()}`,\n now,\n reservation: gate.reservation,\n org: gate.org,\n signal: AbortSignal.timeout(AI_JOB_INLINE_BUDGET_MS),\n // The caller is on the request, so what the inline step produces is\n // attributed with their address; the beat's steps carry the uid alone.\n actor: { uid: gate.uid, email: gate.decoded.email ?? null },\n // The workspace's AI pause lets staff through, as the ladder above did.\n staff: gate.staff,\n })\n if (run.outcome === 'not-claimable') {\n // A job created a moment ago has a claimable first step; anything else\n // is a fault in the machine, and the reservation must not be stranded.\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job first step not claimable', { orgId: gate.orgId, jobId })\n await reportJobFault('ai job first step not claimable', new Error(`job ${jobId}`))\n return Response.json({ error: 'The AI job could not be started' }, { status: 500 })\n }\n return Response.json(\n {\n job: aiJobSummary(run.job),\n // The usage strip's envelope (AGL-2942): the reservation the ladder\n // took, with what the inline step spent.\n meter: aiUsageMeter(gate.reservation, {\n lastCredits: run.job.creditsSpent > 0 ? run.job.creditsSpent : null,\n }),\n },\n { status: 200 },\n )\n}\n\nexport async function GET(request: Request): Promise<Response> {\n const url = new URL(request.url)\n const gate = await aiJobsGate(request, url.searchParams.get('orgId') ?? '')\n if (gate instanceof Response) return gate\n const rawStatus = url.searchParams.get('status') ?? ''\n const status = (AI_JOB_STATUSES as readonly string[]).includes(rawStatus)\n ? (rawStatus as AiJobStatus)\n : undefined\n // `active` (AGL-3593): every job not yet settled, which is what the\n // console's top-bar indicator and the Assist launcher count.\n const active = rawStatus === 'active'\n const limit = Number(url.searchParams.get('limit') ?? '')\n // `hostId` (AGL-3596): one site's jobs, for the site's AI jobs page — a\n // query on the field under the (hostId, createdAt) index, never a filter\n // of a loaded window. An id that is not one is refused rather than ignored,\n // which would answer with every site's jobs.\n const rawHost = url.searchParams.get('hostId')\n if (rawHost !== null && !ID_CHARS.test(rawHost)) {\n return Response.json({ error: 'hostId is not a site id' }, { status: 400 })\n }\n const now = new Date()\n // A job naming a site that has been deleted is not listed (AGL-3596), so\n // no surface counts or shows work on a site nobody can open.\n const jobs = await withoutErasedSites(\n gate.firestore,\n await listAiJobs(gate.firestore, gate.orgId, {\n ...(status ? { status } : {}),\n ...(active ? { statuses: AI_JOB_ACTIVE_STATUSES } : {}),\n ...(rawHost ? { hostId: rawHost } : {}),\n ...(Number.isFinite(limit) && limit > 0 ? { limit } : {}),\n }),\n )\n const freeTaste = resolveEffectivePlan(gate.org as never) === 'free'\n // What the Free workspace has left this month (AGL-3660): the less of its\n // own band and its owner's allowance across their Free workspaces, which is\n // what the steps' reservations refuse at — never the 300 a month starts with.\n const freeCredits = freeTaste\n ? await readFreeAiCreditsLeft(gate.firestore, { orgId: gate.orgId, org: gate.org as object | null, now })\n : null\n // Whether the guided start asks for the sites the person likes (AGL-3975):\n // the workspace's own verdict, the one its site job reads them by.\n const siteInspiration = await isServerReleaseFlagOnForOrg(AI_SITE_INSPIRATION_FLAG, gate.orgId).catch(() => false)\n return Response.json(\n {\n jobs: jobs.map((job) => aiJobSummary(job, now)),\n // Whether the workspace spends the Free taste (AGL-3594), so the guided\n // start offers the Free page band from the request it already makes.\n freeTaste,\n ...(freeCredits ? { freeCredits } : {}),\n ...(siteInspiration ? { siteInspiration: true } : {}),\n },\n { status: 200, headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\nexport const dynamic = 'force-dynamic'\nexport const maxDuration = 60\n"],"names":["randomUUID","resolveEffectivePlan","AI_JOB_KINDS","aiGateLadder","aiJobAdmissionRefusal","aiJobSiteRefusal","AI_JOB_BRIEF_MAX_CHARS","aiJobAdmittedInputs","AI_JOB_INLINE_BUDGET_MS","aiJobNextStepMinimumMs","aiJobSummary","createAiJob","listAiJobs","runAiJobStep","releaseAssistMessage","readFreeAiCreditsLeft","aiCreditsConfirmation","aiUsageMeter","aiJobsGate","withoutErasedSites","AI_JOB_ACTIVE_STATUSES","reportServerError","isServerReleaseFlagOnForOrg","AI_SITE_INSPIRATION_FLAG","reportJobFault","what","error","message","Error","String","stack","undefined","route","routeType","method","service","AI_JOBS_RATE_LIMIT","key","limit","windowMs","MAX_INPUTS_JSON_CHARS","AI_JOB_STATUSES","ID_CHARS","MAX_MODEL_CHARS","parseCreateAiJobBody","payload","body","orgId","trim","kind","includes","join","brief","length","toLocaleString","rawHost","hostId","test","rawInputs","inputs","Array","isArray","value","Object","entries","JSON","stringify","rawModel","model","POST","request","gate","json","parsed","feature","releaseFlag","lockdownFeature","permission","rateLimit","Response","firestore","reservation","catch","status","refusal","confirmedCredits","check","org","siteToCome","uid","creditsConfirmed","onCreditsConfirmed","prompt","console","code","credits","ok","now","Date","created","createdBy","createdByEmail","decoded","email","jobId","$id","job","meter","lastCredits","run","owner","signal","AbortSignal","timeout","actor","staff","outcome","creditsSpent","GET","url","URL","searchParams","get","rawStatus","active","Number","jobs","statuses","isFinite","freeTaste","freeCredits","siteInspiration","map","headers","dynamic","maxDuration"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,+DAA+D;AAC/D,0EAA0E;AAC1E,6DAA6D;AAE7D,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,oBAAoB,QAAQ,2CAA0C;AAC/E,SACEC,YAAY,QAGP,4BAAwB;AAC/B,yEAAyE;AACzE,4EAA4E;AAC5E,iEAAiE;AACjE,SAASC,YAAY,QAAQ,wBAAoB;AACjD,SAASC,qBAAqB,EAAEC,gBAAgB,QAAQ,8BAA0B;AAClF,SAASC,sBAAsB,QAAQ,8BAA0B;AACjE,SAASC,mBAAmB,QAAQ,iCAA6B;AACjE,SACEC,uBAAuB,EACvBC,sBAAsB,EACtBC,YAAY,EACZC,WAAW,EACXC,UAAU,E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":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lockdown-423: via libs/plugins/ai/src/lib/runtime/ai-gate.ts\n// The POST climbs `aiGateLadder`, whose lockdown rung is the verdict; the\n// GET climbs `ai-jobs-gate.ts`, which carries the same rung.\n\nimport { randomUUID } from 'crypto'\nimport { resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n AI_JOB_KINDS,\n type AiJobKind,\n type AiJobStatus,\n} from '../model/ai-jobs.types'\n// By their own entry points rather than the barrel (AGL-2903): the specs\n// stub the barrel closed-world, and the ladder, the machine and the runtime\n// are the things under test here, not things to be stubbed away.\nimport { aiGateLadder } from '../runtime/ai-gate'\nimport { aiJobAdmissionRefusal, aiJobSiteRefusal } from '../jobs/ai-job-admission'\nimport { AI_JOB_BRIEF_MAX_CHARS } from '../jobs/ai-job-text-step'\nimport { aiJobAdmittedInputs } from '../jobs/ai-job-auto-confirm'\nimport {\n AI_JOB_INLINE_BUDGET_MS,\n aiJobNextStepMinimumMs,\n aiJobSummary,\n createAiJob,\n listAiJobs,\n runAiJobStep,\n} from '../jobs/ai-jobs'\nimport { releaseAssistMessage } from '../usage/assist-usage'\nimport { readFreeAiCreditsLeft } from '../usage/free-ai-credits-left'\nimport { aiCreditsConfirmation, type AiCreditsPrompt } from '../model/ai-credit-estimate'\nimport { aiUsageMeter } from '../usage/ai-usage-meter'\nimport { aiJobsGate } from './ai-jobs-gate'\nimport { siteImportOfferFor } from './ai-site-import-route'\nimport { withoutErasedSites } from './ai-jobs-live-sites'\nimport { AI_JOB_ACTIVE_STATUSES } from '../model/ai-job-activity'\nimport { reportServerError } from '@aglyn/tenant-data-admin/server/client-error-report'\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { AI_SITE_INSPIRATION_FLAG } from '../model/ai-site-inspiration'\n\n/**\n * A caught fault on this door, reported as well as logged (AGL-1921).\n *\n * `onRequestError` sees only an UNCAUGHT throw, and the Vercel log drain\n * forwards the status line but not a `console.error`, so the three 500s\n * this route answered on 2026-10-06 at 17:41–17:47Z reached the alert as\n * START/END/REPORT with no reason anywhere. Never throws.\n */\nasync function reportJobFault(what: string, error: unknown): Promise<void> {\n try {\n await reportServerError(\n {\n message: `${what}: ${error instanceof Error ? error.message : String(error)}`,\n stack: error instanceof Error ? error.stack : undefined,\n route: '/api/ai/jobs',\n routeType: 'route',\n method: 'POST',\n },\n { service: 'console-web' },\n )\n } catch {\n // The console line beside each call is the record of last resort.\n }\n}\n\n/**\n * AI generation jobs: create and list (AGL-2904).\n *\n * `POST` is a door that spends, so it climbs the whole ladder (AGL-2903) —\n * `aiGenerative`, `release_ai_generative`, the `ai-generate` switch, a\n * per-uid window, and a reservation — and then creates the job and runs\n * its first step INLINE under `AI_JOB_INLINE_BUDGET_MS`. A step that\n * finishes in time answers with the job `done` (or `queued` behind its\n * next step); one that does not is aborted, its reservation handed back,\n * and the job answers `queued` for the beat to resume. Either way the\n * caller gets the job document, and the events route is how it watches\n * from there.\n *\n * `POST` with `check: true` climbs the same ladder and asks the same\n * admission, then hands the reservation back and creates nothing: a 200\n * with `ok` true, or the refusal the create would have answered. \"Create site\"\n * asks it before it makes the site a guided start builds on (AGL-3859), so\n * a start that would be refused, or that asks for the Free go-ahead, leaves\n * no empty site behind. A checked job may name no site yet.\n *\n * `GET` lists the org's jobs, newest first, through the read gate: the\n * same rungs up to the lockdown verdict, no reservation. A job naming a\n * site that no longer exists is left out, so a page can come back shorter\n * than its `limit`.\n *\n * The request must NAME the org it is metered against (AGL-1934). There\n * is no fallback to \"the caller's first org\".\n */\n\nconst AI_JOBS_RATE_LIMIT = { key: 'ai-jobs', limit: 10, windowMs: 60_000 }\n\n/** Kind-specific inputs, bounded: a runner reads scalars, not a document. */\nconst MAX_INPUTS_JSON_CHARS = 8_000\n\n/** The admitted statuses for the list filter, as the union spells them. */\nconst AI_JOB_STATUSES: readonly AiJobStatus[] = [\n 'queued',\n 'running',\n 'needs_input',\n 'needs_review',\n 'done',\n 'failed',\n 'canceled',\n]\n\nexport interface CreateAiJobBody {\n orgId: string\n hostId: string | null\n kind: AiJobKind\n brief: string\n inputs: Record<string, string | number | boolean>\n /** A catalog model the creator picked (AGL-2942), or `null` for Auto. */\n model: string | null\n}\n\nconst ID_CHARS = /^[A-Za-z0-9_-]{1,100}$/\n\n/** The longest model id a body may carry; the catalog's ids are far shorter. */\nconst MAX_MODEL_CHARS = 100\n\n/** Validate + clamp the request body; a string names what is wrong. */\nexport function parseCreateAiJobBody(payload: unknown): CreateAiJobBody | string {\n const body = (payload ?? {}) as Record<string, unknown>\n const orgId = String(body.orgId ?? '').trim()\n if (!orgId) return 'Open a workspace before using this feature'\n const kind = String(body.kind ?? '')\n if (!(AI_JOB_KINDS as readonly string[]).includes(kind)) {\n return `kind must be one of ${AI_JOB_KINDS.join(', ')}`\n }\n const brief = String(body.brief ?? '').trim()\n if (!brief) return 'Write a brief for the job'\n if (brief.length > AI_JOB_BRIEF_MAX_CHARS) {\n return `Keep the brief under ${AI_JOB_BRIEF_MAX_CHARS.toLocaleString('en-US')} characters`\n }\n const rawHost = body.hostId\n const hostId =\n rawHost === undefined || rawHost === null || rawHost === ''\n ? null\n : typeof rawHost === 'string' && ID_CHARS.test(rawHost)\n ? rawHost\n : undefined\n if (hostId === undefined) return 'hostId is not a site id'\n // A theme is fields on one site's document, so a theme job that names no\n // site has nothing to propose a change to (AGL-2938).\n if (kind === 'theme' && !hostId) return 'Open a site before changing its theme'\n const rawInputs = body.inputs\n const inputs: Record<string, string | number | boolean> = {}\n if (rawInputs !== undefined && rawInputs !== null) {\n if (typeof rawInputs !== 'object' || Array.isArray(rawInputs)) {\n return 'inputs must be an object'\n }\n for (const [key, value] of Object.entries(rawInputs as Record<string, unknown>)) {\n if (\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n return `inputs.${key} must be a string, number or boolean`\n }\n inputs[key] = value\n }\n if (JSON.stringify(inputs).length > MAX_INPUTS_JSON_CHARS) {\n return 'inputs are too large'\n }\n }\n const rawModel = typeof body.model === 'string' ? body.model.trim() : ''\n if (rawModel.length > MAX_MODEL_CHARS) return 'model is not a model id'\n // Validated against the plan and the allotment allowlists when each step\n // runs, not here: the allowlists are read inside the step's reservation.\n const model = rawModel && rawModel !== 'auto' ? rawModel : null\n return { orgId, hostId, kind: kind as AiJobKind, brief, inputs, model }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n let payload: unknown\n try {\n payload = await request.json()\n } catch {\n payload = null\n }\n const parsed = parseCreateAiJobBody(payload)\n // The org is parsed BEFORE the ladder so a request that named none is\n // refused with the ladder's 400 rather than a shape error; every other\n // shape fault waits until the caller has proven who they are.\n const orgId = typeof parsed === 'string' ? String((payload as Record<string, unknown> | null)?.orgId ?? '') : parsed.orgId\n // The site rides along for the same reason: a collaborator's `ai.generate`\n // is decided per site (AGL-2927), so the ladder needs it before it can say\n // whether this member may generate here at all.\n const hostId = typeof parsed === 'string' ? null : parsed.hostId\n const gate = await aiGateLadder(\n { request, orgId, hostId },\n {\n feature: 'aiGenerative',\n releaseFlag: 'release_ai_generative',\n lockdownFeature: 'ai-generate',\n permission: 'ai.generate',\n rateLimit: AI_JOBS_RATE_LIMIT,\n },\n )\n if (gate instanceof Response) return gate\n if (typeof parsed === 'string') {\n // Admitted, reserved, and then found to have sent nothing runnable: the\n // reservation goes back, because no token was spent.\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json({ error: parsed }, { status: 400 })\n }\n // What only this kind can say about the request (AGL-2909): a site it\n // needs, inputs it reads, an allowance its draft counts against. Asked\n // before the job exists, so a refusal spends nothing.\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>>\n // A Free start past what is left, which the person chose to build as far as\n // it goes (AGL-3722): the prompt they confirmed, kept on the job.\n let confirmedCredits: AiCreditsPrompt | null = null\n // Asked before the site exists (AGL-3859): answers, creates nothing.\n const check = (payload as Record<string, unknown> | null)?.['check'] === true\n try {\n // A site that switched AI off first (AGL-3028), then the kind's own check.\n refusal =\n (await aiJobSiteRefusal({\n firestore: gate.firestore,\n org: gate.org,\n hostId: parsed.hostId,\n })) ??\n (await aiJobAdmissionRefusal(parsed.kind, {\n firestore: gate.firestore,\n orgId: gate.orgId,\n hostId: parsed.hostId,\n siteToCome: check && !parsed.hostId,\n inputs: parsed.inputs,\n org: gate.org,\n uid: gate.uid,\n creditsConfirmed: (payload as Record<string, unknown> | null)?.['creditsConfirmed'] === true,\n onCreditsConfirmed: (prompt) => {\n confirmedCredits = prompt\n },\n }))\n } catch (error) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job admission failed', { orgId: gate.orgId, kind: parsed.kind, error })\n await reportJobFault('ai job admission failed', error)\n return Response.json({ error: 'The AI job could not be created' }, { status: 500 })\n }\n if (refusal) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n // A Free start past what is left asks before it starts (AGL-3722): the\n // prompt rides the 409, so the dialog offers its choices.\n return Response.json(\n { error: refusal.error, ...(refusal.code ? { code: refusal.code } : {}), ...(refusal.credits ? { credits: refusal.credits } : {}) },\n { status: refusal.status },\n )\n }\n if (check) {\n // Admitted, and nothing to run: the reservation goes back.\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json({ ok: true }, { status: 200 })\n }\n\n const now = new Date()\n let created: Awaited<ReturnType<typeof createAiJob>>\n try {\n // The guided start's own plan confirmation (AGL-3594), kept only for a\n // site job on a site that has published nothing of the owner's yet.\n const inputs = await aiJobAdmittedInputs(gate.firestore, {\n kind: parsed.kind,\n hostId: parsed.hostId,\n inputs: parsed.inputs,\n })\n created = await createAiJob(\n gate.firestore,\n {\n orgId: gate.orgId,\n hostId: parsed.hostId,\n kind: parsed.kind,\n brief: parsed.brief,\n inputs,\n model: parsed.model,\n createdBy: gate.uid,\n createdByEmail: gate.decoded.email ?? null,\n creditsConfirmed: aiCreditsConfirmation(confirmedCredits, gate.uid, now),\n },\n now,\n )\n } catch (error) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job create failed', { orgId: gate.orgId, error })\n await reportJobFault('ai job create failed', error)\n return Response.json({ error: 'The AI job could not be created' }, { status: 500 })\n }\n const jobId = created.$id\n\n // A first step that needs more time than this request has (AGL-2907) is left\n // queued for the beat, which starts it with a budget of its own: a provider\n // call this request's timeout cut off would be billed upstream and metered\n // nowhere. Nothing ran, so the reservation goes back.\n if (aiJobNextStepMinimumMs(created) > AI_JOB_INLINE_BUDGET_MS) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json(\n {\n job: aiJobSummary(created, now),\n meter: aiUsageMeter(gate.reservation, { lastCredits: null }),\n },\n { status: 200 },\n )\n }\n\n // The first step, inline, on the reservation the ladder already holds.\n // The runner hands that reservation back itself if the provider is never\n // reached, and re-queues the step when the budget ends first.\n const run = await runAiJobStep(gate.firestore, gate.orgId, jobId, {\n owner: `route:${randomUUID()}`,\n now,\n reservation: gate.reservation,\n org: gate.org,\n signal: AbortSignal.timeout(AI_JOB_INLINE_BUDGET_MS),\n // The caller is on the request, so what the inline step produces is\n // attributed with their address; the beat's steps carry the uid alone.\n actor: { uid: gate.uid, email: gate.decoded.email ?? null },\n // The workspace's AI pause lets staff through, as the ladder above did.\n staff: gate.staff,\n })\n if (run.outcome === 'not-claimable') {\n // A job created a moment ago has a claimable first step; anything else\n // is a fault in the machine, and the reservation must not be stranded.\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job first step not claimable', { orgId: gate.orgId, jobId })\n await reportJobFault('ai job first step not claimable', new Error(`job ${jobId}`))\n return Response.json({ error: 'The AI job could not be started' }, { status: 500 })\n }\n return Response.json(\n {\n job: aiJobSummary(run.job),\n // The usage strip's envelope (AGL-2942): the reservation the ladder\n // took, with what the inline step spent.\n meter: aiUsageMeter(gate.reservation, {\n lastCredits: run.job.creditsSpent > 0 ? run.job.creditsSpent : null,\n }),\n },\n { status: 200 },\n )\n}\n\nexport async function GET(request: Request): Promise<Response> {\n const url = new URL(request.url)\n const gate = await aiJobsGate(request, url.searchParams.get('orgId') ?? '')\n if (gate instanceof Response) return gate\n const rawStatus = url.searchParams.get('status') ?? ''\n const status = (AI_JOB_STATUSES as readonly string[]).includes(rawStatus)\n ? (rawStatus as AiJobStatus)\n : undefined\n // `active` (AGL-3593): every job not yet settled, which is what the\n // console's top-bar indicator and the Assist launcher count.\n const active = rawStatus === 'active'\n const limit = Number(url.searchParams.get('limit') ?? '')\n // `hostId` (AGL-3596): one site's jobs, for the site's AI jobs page — a\n // query on the field under the (hostId, createdAt) index, never a filter\n // of a loaded window. An id that is not one is refused rather than ignored,\n // which would answer with every site's jobs.\n const rawHost = url.searchParams.get('hostId')\n if (rawHost !== null && !ID_CHARS.test(rawHost)) {\n return Response.json({ error: 'hostId is not a site id' }, { status: 400 })\n }\n const now = new Date()\n // A job naming a site that has been deleted is not listed (AGL-3596), so\n // no surface counts or shows work on a site nobody can open.\n const jobs = await withoutErasedSites(\n gate.firestore,\n await listAiJobs(gate.firestore, gate.orgId, {\n ...(status ? { status } : {}),\n ...(active ? { statuses: AI_JOB_ACTIVE_STATUSES } : {}),\n ...(rawHost ? { hostId: rawHost } : {}),\n ...(Number.isFinite(limit) && limit > 0 ? { limit } : {}),\n }),\n )\n const freeTaste = resolveEffectivePlan(gate.org as never) === 'free'\n // What the Free workspace has left this month (AGL-3660): the less of its\n // own band and its owner's allowance across their Free workspaces, which is\n // what the steps' reservations refuse at — never the 300 a month starts with.\n const freeCredits = freeTaste\n ? await readFreeAiCreditsLeft(gate.firestore, { orgId: gate.orgId, org: gate.org as object | null, now })\n : null\n // Whether Create site offers \"Bring my site\" (AGL-3976), asked only by the\n // guided start's own read, so the card costs no other caller anything.\n const siteImport =\n url.searchParams.get('siteImport') === '1'\n ? await siteImportOfferFor({ orgId: gate.orgId, staff: gate.staff, org: gate.org, member: gate.member })\n : null\n // Whether the guided start asks for the sites the person likes (AGL-3975):\n // the workspace's own verdict, the one its site job reads them by.\n const siteInspiration = await isServerReleaseFlagOnForOrg(AI_SITE_INSPIRATION_FLAG, gate.orgId).catch(() => false)\n return Response.json(\n {\n jobs: jobs.map((job) => aiJobSummary(job, now)),\n // Whether the workspace spends the Free taste (AGL-3594), so the guided\n // start offers the Free page band from the request it already makes.\n freeTaste,\n ...(freeCredits ? { freeCredits } : {}),\n ...(siteImport ? { siteImport } : {}),\n ...(siteInspiration ? { siteInspiration: true } : {}),\n },\n { status: 200, headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\nexport const dynamic = 'force-dynamic'\nexport const maxDuration = 60\n"],"names":["randomUUID","resolveEffectivePlan","AI_JOB_KINDS","aiGateLadder","aiJobAdmissionRefusal","aiJobSiteRefusal","AI_JOB_BRIEF_MAX_CHARS","aiJobAdmittedInputs","AI_JOB_INLINE_BUDGET_MS","aiJobNextStepMinimumMs","aiJobSummary","createAiJob","listAiJobs","runAiJobStep","releaseAssistMessage","readFreeAiCreditsLeft","aiCreditsConfirmation","aiUsageMeter","aiJobsGate","siteImportOfferFor","withoutErasedSites","AI_JOB_ACTIVE_STATUSES","reportServerError","isServerReleaseFlagOnForOrg","AI_SITE_INSPIRATION_FLAG","reportJobFault","what","error","message","Error","String","stack","undefined","route","routeType","method","service","AI_JOBS_RATE_LIMIT","key","limit","windowMs","MAX_INPUTS_JSON_CHARS","AI_JOB_STATUSES","ID_CHARS","MAX_MODEL_CHARS","parseCreateAiJobBody","payload","body","orgId","trim","kind","includes","join","brief","length","toLocaleString","rawHost","hostId","test","rawInputs","inputs","Array","isArray","value","Object","entries","JSON","stringify","rawModel","model","POST","request","gate","json","parsed","feature","releaseFlag","lockdownFeature","permission","rateLimit","Response","firestore","reservation","catch","status","refusal","confirmedCredits","check","org","siteToCome","uid","creditsConfirmed","onCreditsConfirmed","prompt","console","code","credits","ok","now","Date","created","createdBy","createdByEmail","decoded","email","jobId","$id","job","meter","lastCredits","run","owner","signal","AbortSignal","timeout","actor","staff","outcome","creditsSpent","GET","url","URL","searchParams","get","rawStatus","active","Number","jobs","statuses","isFinite","freeTaste","freeCredits","siteImport","member","siteInspiration","map","headers","dynamic","maxDuration"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,+DAA+D;AAC/D,0EAA0E;AAC1E,6DAA6D;AAE7D,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,oBAAoB,QAAQ,2CAA0C;AAC/E,SACEC,YAAY,QAGP,4BAAwB;AAC/B,yEAAyE;AACzE,4EAA4E;AAC5E,iEAAiE;AACjE,SAASC,YAAY,QAAQ,wBAAoB;AACjD,SAASC,qBAAqB,EAAEC,gBAAgB,QAAQ,8BAA0B;AAClF,SAASC,sBAAsB,QAAQ,8BAA0B;AACjE,SAASC,mBAAmB,QAAQ,iCAA6B;AACjE,SACEC,uBAAuB,EACvBC,sBAAsB,EACtBC,YAAY,EACZC,WAAW,EACXC,UAAU,EACVC,YAAY,QACP,qBAAiB;AACxB,SAASC,oBAAoB,QAAQ,2BAAuB;AAC5D,SAASC,qBAAqB,QAAQ,mCAA+B;AACrE,SAASC,qBAAqB,QAA8B,iCAA6B;AACzF,SAASC,YAAY,QAAQ,6BAAyB;AACtD,SAASC,UAAU,QAAQ,oBAAgB;AAC3C,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,kBAAkB,QAAQ,0BA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